postgresai 0.18.0-dev.12 → 0.18.0-dev.14

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
@@ -235,8 +235,8 @@ payment checks. A private endpoint needs a network path, or monitoring hosted in
235
235
  (`--self-hosted`).
236
236
 
237
237
  `pgai mon deploy` and `pgai dblab deploy` share their options and results: the database URL as the
238
- argument (or `--db-url`), `--name` (default: from the database), `--location` (a Hetzner location;
239
- default: any with capacity), `--wait <minutes>` / `--no-wait`, `--yes` (never prompt), `--json`, the
238
+ argument (or `--db-url`), `--name` (default: from the database), `--cloud` and `--location` (where the box
239
+ runs; see the table), `--wait <minutes>` / `--no-wait`, `--yes` (never prompt), `--json`, the
240
240
  `status` words and exit codes below, and `instances list | watch | delete`, which take an id or a name
241
241
  (a name two instances have is refused, with their ids). `watch` is also `status`.
242
242
 
@@ -262,11 +262,12 @@ terminal, or with `--json`, it only points to `pgai mon deploy`.
262
262
  | `--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 (RDS); refused for Supabase, where PostgresAI creates `postgres_ai_mon` through the Supabase Management API |
263
263
  | `--db-url <url>` | the database URL, instead of the argument |
264
264
  | `--name <name>` | the instance's name (default: `host[:port]/database`); ignored, with a note, for a database already monitored |
265
- | `--location <location>` | Hetzner location `fsn1`, `nbg1` or `hel1` (default: any with capacity) |
265
+ | `--cloud <cloud>` | `mon deploy`: `aws` or `hetzner`; default: the database's cloud (its RDS, Aurora, EC2 or Supabase region), else AWS. `dblab deploy`: `hetzner`, `aws` or `gcp` (default `hetzner`) |
266
+ | `--location <location>` | a location of that cloud: an AWS region, or a Hetzner location (`fsn1`, `nbg1`, `hel1`, `ash`, `hil`). `mon deploy` default: the database's region, else us-east-1 on AWS; a location of another cloud is refused before anything is created |
266
267
  | `--vcpus <n>` | `mon deploy` only: the database server's vCPUs. Without it there is no AAS (database load) data; at a terminal you are asked. On a database already monitored, it sets missing vCPUs (a set value is changed with `mon instances set`) |
267
268
  | `--wait <minutes>` | how long to wait for the monitoring box; `0` does not wait (default 20) |
268
269
  | `--no-wait` | the same as `--wait 0` |
269
- | `-y, --yes` | never prompt; accept a billed box's price (`mon deploy` does not start the browser sign-in; `mon instances delete` does not ask) |
270
+ | `-y, --yes` | never prompt: deploy where shown and accept the price (`mon deploy` does not start the browser sign-in; `mon instances delete` does not ask). Without it, `mon deploy` asks before creating any box, free or billed, and at a terminal lets you choose another cloud and location; not at a terminal it stops (exit 3) with the place, the price and `choices` |
270
271
  | `--coupon <code>` | promotion code for the organization's monitoring subscription |
271
272
  | `--json` | JSON output, also on a terminal |
272
273
 
@@ -352,6 +353,11 @@ do `pgai dblab deploy` and `pgai dblab instances`:
352
353
  | `action_required` | do what `next` says, then re-run; also when the `--wait` of `pgai mon deploy` ran out with the box still starting (`next`: "Still in progress ... resume with pgai mon instances watch <id>") | 3 |
353
354
  | `failed` | `next` has the reason | 1 |
354
355
 
356
+ When PostgresAI is slow to answer the box request for a database URL, `pgai mon deploy` says it is still
357
+ creating the monitoring box and looks for the box for up to 5 minutes (30 seconds from the MCP tool)
358
+ before `--wait` starts, also with `--no-wait`; then it follows the box as usual. If no box appears, it
359
+ stops with `action_required` and says to check `pgai mon instances list` before running deploy again.
360
+
355
361
  `pgai init` exits with 130 when cancelled at a prompt (Ctrl-C, Ctrl-D).
356
362
 
357
363
  `--self-hosted` starts `mon local-install` with the monitoring URL, the API key and the ClickHouse
@@ -13430,9 +13430,9 @@ var require_dist2 = __commonJS(function(exports, module) {
13430
13430
  });
13431
13431
 
13432
13432
  // lib/util.ts
13433
- function requestTimeoutSignal2(timeoutMs) {
13433
+ function requestTimeoutSignal2(timeoutMs, ceilingMs = DEFAULT_HTTP_REQUEST_TIMEOUT_MS2) {
13434
13434
  const requested = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_HTTP_REQUEST_TIMEOUT_MS2;
13435
- const bounded = Math.max(1, Math.min(DEFAULT_HTTP_REQUEST_TIMEOUT_MS2, Math.floor(requested)));
13435
+ const bounded = Math.max(1, Math.min(ceilingMs, Math.floor(requested)));
13436
13436
  return { signal: AbortSignal.timeout(bounded), timeoutMs: bounded };
13437
13437
  }
13438
13438
  function maskSecret2(secret) {
@@ -13533,7 +13533,7 @@ var {
13533
13533
  // package.json
13534
13534
  var package_default = {
13535
13535
  name: "postgresai",
13536
- version: "0.18.0-dev.12",
13536
+ version: "0.18.0-dev.14",
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.12";
16896
+ var version = "0.18.0-dev.14";
16897
16897
  var package_default2 = {
16898
16898
  name: "postgresai",
16899
16899
  version,
@@ -17160,10 +17160,20 @@ function describeFetchError(operation, url, err) {
17160
17160
 
17161
17161
  class HttpStatusError extends Error {
17162
17162
  status;
17163
- constructor(message, status) {
17163
+ sqlstate;
17164
+ constructor(message, status, sqlstate) {
17164
17165
  super(message);
17165
17166
  this.name = "HttpStatusError";
17166
17167
  this.status = status;
17168
+ this.sqlstate = sqlstate;
17169
+ }
17170
+ }
17171
+ function sqlstateOf(body) {
17172
+ try {
17173
+ const code = JSON.parse(body)?.code;
17174
+ return typeof code === "string" && /^[0-9A-Z]{5}$/.test(code) ? code : undefined;
17175
+ } catch {
17176
+ return;
17167
17177
  }
17168
17178
  }
17169
17179
  function isRetryableHttpStatus(status) {
@@ -17201,9 +17211,9 @@ class HttpRequestTimeoutError extends Error {
17201
17211
  this.name = "HttpRequestTimeoutError";
17202
17212
  }
17203
17213
  }
17204
- function requestTimeoutSignal(timeoutMs) {
17214
+ function requestTimeoutSignal(timeoutMs, ceilingMs = DEFAULT_HTTP_REQUEST_TIMEOUT_MS) {
17205
17215
  const requested = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_HTTP_REQUEST_TIMEOUT_MS;
17206
- const bounded = Math.max(1, Math.min(DEFAULT_HTTP_REQUEST_TIMEOUT_MS, Math.floor(requested)));
17216
+ const bounded = Math.max(1, Math.min(ceilingMs, Math.floor(requested)));
17207
17217
  return { signal: AbortSignal.timeout(bounded), timeoutMs: bounded };
17208
17218
  }
17209
17219
  function isFetchTimeout(err) {
@@ -22662,8 +22672,11 @@ function nameFromDatabase(url) {
22662
22672
  const slug = (db || "dblab").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48).replace(/-+$/, "");
22663
22673
  return slug.length >= 2 ? slug : `db-${slug || "x"}`.slice(0, 48);
22664
22674
  }
22665
- function sharedDeployOptions(cmd, waitDefaultMinutes, nameHelp, locationHelp = "Hetzner location: fsn1, nbg1 or hel1 (default: any with capacity)") {
22666
- return cmd.argument("[database-url]", "the database: postgresql://user:password@host:5432/dbname").option("--db-url <url>", "the database URL (the same as the argument)").option("--name <name>", nameHelp).option("--location <location>", locationHelp).option("--wait <minutes>", "how long to wait for it to be ready (0 = do not wait)", String(waitDefaultMinutes)).option("--no-wait", "return once the deploy has started (the same as --wait 0)").option("-y, --yes", "never prompt: accept the price and every confirmation").option("--json", "JSON output: one result on stdout, progress on stderr (the default when stdout is not a terminal)").option("--debug", "print HTTP requests (secrets masked)");
22675
+ function sharedDeployOptions(cmd, waitDefaultMinutes, nameHelp, locationHelp = "Hetzner location: fsn1, nbg1 or hel1 (default: any with capacity)", cloudHelp) {
22676
+ cmd = cmd.argument("[database-url]", "the database: postgresql://user:password@host:5432/dbname").option("--db-url <url>", "the database URL (the same as the argument)").option("--name <name>", nameHelp).option("--location <location>", locationHelp);
22677
+ if (cloudHelp)
22678
+ cmd = cmd.option("--cloud <cloud>", cloudHelp);
22679
+ return cmd.option("--wait <minutes>", "how long to wait for it to be ready (0 = do not wait)", String(waitDefaultMinutes)).option("--no-wait", "return once the deploy has started (the same as --wait 0)").option("-y, --yes", "never prompt: accept the price and every confirmation").option("--json", "JSON output: one result on stdout, progress on stderr (the default when stdout is not a terminal)").option("--debug", "print HTTP requests (secrets masked)");
22667
22680
  }
22668
22681
 
22669
22682
  // lib/joe.ts
@@ -22689,7 +22702,7 @@ async function callRpcRaw(params) {
22689
22702
  console.error(`Debug: Request body: ${redactSecretsForLog(payload)}`);
22690
22703
  }
22691
22704
  let response;
22692
- const requestTimeout = requestTimeoutSignal(params.timeoutMs);
22705
+ const requestTimeout = requestTimeoutSignal(params.timeoutMs, params.timeoutCeilingMs);
22693
22706
  try {
22694
22707
  response = await fetch(url.toString(), {
22695
22708
  method: "POST",
@@ -22715,7 +22728,7 @@ async function callRpcRaw(params) {
22715
22728
  ({ response, text } = await send(params.fallbackBody));
22716
22729
  }
22717
22730
  if (!response.ok) {
22718
- throw new HttpStatusError(formatHttpError(operation, response.status, text, response.statusText), response.status);
22731
+ throw new HttpStatusError(formatHttpError(operation, response.status, text, response.statusText), response.status, sqlstateOf(text));
22719
22732
  }
22720
22733
  try {
22721
22734
  return { data: JSON.parse(text), status: response.status };
@@ -22940,6 +22953,7 @@ function storedPasswordNeeds(monitoringUrl) {
22940
22953
  return needs.length ? needs.join(" and ") : undefined;
22941
22954
  }
22942
22955
  var shellWord = (s) => /^[\w./:@%+=,-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
22956
+ var deleteRef = (d, list) => list.some((o) => o.id !== d.id && !disconnecting(o.status) && o.name === d.name) ? d.id : d.name;
22943
22957
  var disconnectEach = (names) => names.map((n) => `pgai mon instances delete ${shellWord(n)} --yes`).join(" and ");
22944
22958
  function loginName(url, sessionUser, role) {
22945
22959
  const user = decodeURIComponent(new URL(url).username);
@@ -22964,6 +22978,10 @@ function caNote(url) {
22964
22978
  return;
22965
22979
  return `the monitoring box has no copy of the CA in sslrootcert: with sslmode=${q.get("sslmode")} it connects only to a server certificate signed by a public CA (else use sslmode=require)`;
22966
22980
  }
22981
+ function chargeFailed(error, rerun, billingUrl, couponFlag = "--coupon") {
22982
+ const fix = /promotion code|coupon/i.test(error) ? `The promo code cannot be used by this organization: ${rerun} without ${couponFlag}, or with a code this organization can use` : `Update the payment method${billingUrl ? ` at ${billingUrl}` : ""}, then ${rerun}`;
22983
+ return `The first charge failed (${error}): the box is being removed and nothing is billed. ${fix}`;
22984
+ }
22967
22985
  function connectStatus(row, provider = row.provider, fresh = false) {
22968
22986
  const base = { provider, name: row.name, id: row.id, ...row.health_url ? { health_url: row.health_url } : {}, dashboard_url: row.dashboard_url, host_metrics: row.host_metrics };
22969
22987
  const status = stateOf(row.status);
@@ -22971,7 +22989,7 @@ function connectStatus(row, provider = row.provider, fresh = false) {
22971
22989
  return {
22972
22990
  ...base,
22973
22991
  status: "action_required",
22974
- next: `The first charge failed (${row.billing_error}): the box is being removed and nothing is billed. Update the payment method, then re-run pgai mon deploy.`
22992
+ next: `${chargeFailed(row.billing_error, "re-run pgai mon deploy")}.`
22975
22993
  };
22976
22994
  }
22977
22995
  if (status === "ready") {
@@ -22992,6 +23010,7 @@ var ESCAPES = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*
22992
23010
  var terminalText = (text) => text.replace(ESCAPES, "").split(`
22993
23011
  `).map(stripControlsToSpace).join(`
22994
23012
  `);
23013
+ var cloudWord = (cloud) => ({ aws: "AWS", hetzner: "Hetzner" })[cloud] ?? cloud;
22995
23014
  var boxState = (row) => row.status === "launch_requested" && row.registered_at ? "registered" : row.status ?? "starting";
22996
23015
  function boxWords(state) {
22997
23016
  if (!state || state === "starting" || state === "launch_requested")
@@ -23000,7 +23019,7 @@ function boxWords(state) {
23000
23019
  return "installing monitoring";
23001
23020
  return monitoringStatus(state).replace("_", " ");
23002
23021
  }
23003
- async function billingFor(q, name, opts, deps, show) {
23022
+ async function billingFor(q, name, opts, deps, show, ask) {
23004
23023
  const billing = { price: priceText(q), requires_payment_method: q.requires_payment_method };
23005
23024
  if (opts.coupon) {
23006
23025
  billing.coupon = q.promo?.valid ? { code: q.promo.code, valid: true, description: q.promo.discount_description } : { code: opts.coupon, valid: false, error: q.promo?.error ?? "not valid" };
@@ -23014,6 +23033,12 @@ async function billingFor(q, name, opts, deps, show) {
23014
23033
  if (q.requires_payment_method)
23015
23034
  return { billing, billingPage, billingUrl, accepted: false, stop: billingPage };
23016
23035
  show(billing.price);
23036
+ if (ask) {
23037
+ const d = await ask(billing.price);
23038
+ if (!d.go)
23039
+ return { billing, billingPage, billingUrl, accepted: false, stop: { ...billing, ...d.stop } };
23040
+ return { billing, billingPage, billingUrl, accepted: q.billed, placed: d.place };
23041
+ }
23017
23042
  if (q.billed && !opts.yes && !await deps.confirm(`Provision ${terminalText(name)}? (y/N): `)) {
23018
23043
  return stop(opts.agent ? `Call deploy_monitoring again with yes: true to accept ${billing.price}` : `Re-run with --yes to accept ${billing.price}`);
23019
23044
  }
@@ -23092,11 +23117,18 @@ async function connect(url, opts, deps) {
23092
23117
  if (opts.selfHosted && deps.localStackRunning()) {
23093
23118
  return { status: "action_required", provider, name, next: "A monitoring stack already runs on this machine: add the database with PGAI_DB_URL='<postgres_ai_mon URL>' pgai mon targets add" };
23094
23119
  }
23120
+ const byCluster = (d) => !!d.cluster && serverOf(d.cluster) === cluster && d.database != null && decodeURIComponent(d.database) === name.split("/").slice(1).join("/");
23121
+ const byName = (d) => (d.cluster == null || d.database == null) && d.name === name;
23095
23122
  const findDatabase = (list) => {
23096
23123
  const live = list.filter((d) => !disconnecting(d.status));
23097
- return live.find((d) => d.cluster && serverOf(d.cluster) === cluster && d.database != null && decodeURIComponent(d.database) === name.split("/").slice(1).join("/")) ?? live.find((d) => (d.cluster == null || d.database == null) && d.name === name);
23124
+ return live.find(byCluster) ?? live.find(byName);
23098
23125
  };
23099
23126
  const rows = opts.selfHosted ? [] : await deps.list();
23127
+ const known = new Set(rows.map((d) => d.id));
23128
+ const findMade = (list) => {
23129
+ const fresh = list.filter((d) => !known.has(d.id));
23130
+ return fresh.find(byCluster) ?? fresh.find(byName);
23131
+ };
23100
23132
  let row = findDatabase(rows);
23101
23133
  const fresh = !row;
23102
23134
  let note = "";
@@ -23104,6 +23136,7 @@ async function connect(url, opts, deps) {
23104
23136
  let billingPage;
23105
23137
  let accepted = false;
23106
23138
  let billingUrl;
23139
+ let place;
23107
23140
  let undoRole;
23108
23141
  const findOrg = async () => {
23109
23142
  try {
@@ -23137,7 +23170,7 @@ async function connect(url, opts, deps) {
23137
23170
  }
23138
23171
  }
23139
23172
  if (row && opts.resetPassword) {
23140
- return { status: "action_required", provider, name, id: row.id, next: `${name} is already monitored, and its monitoring uses the current password: pgai mon instances delete ${name} --yes first` };
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` };
23141
23174
  }
23142
23175
  if (row && key) {
23143
23176
  const found = await findOrg();
@@ -23165,26 +23198,30 @@ async function connect(url, opts, deps) {
23165
23198
  let lockId;
23166
23199
  const unread = (d) => !d.cluster;
23167
23200
  const onServer = (d) => !!d.cluster && serverOf(d.cluster) === cluster;
23168
- const othersOnServer = (list) => list.filter((d) => !disconnecting(d.status) && (unread(d) || onServer(d)));
23201
+ 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)));
23169
23203
  const storedPassword = !monitoringUser && rows.some((d) => d.monitoring_password_stored && !/delet/.test(d.status ?? "") && onServer(d)) || undefined;
23170
- const cutOff = (others) => {
23171
- const on = others.filter((d) => !unread(d)).map((d) => d.name).join(", ");
23172
- const maybe = others.filter(unread).map((d) => d.name).join(", ");
23204
+ const cutOff = (others, list) => {
23205
+ const label = (d) => deleteRef(d, list) === d.id ? `${d.name} (id ${d.id})` : d.name;
23206
+ const on = others.filter((d) => !unread(d)).map(label).join(", ");
23207
+ const maybe = others.filter(unread).map(label).join(", ");
23173
23208
  const what = [on && `would cut off the monitoring of ${on} on this server`, maybe && `may cut off the monitoring of ${maybe} (the platform could not read its URL, so its server is not known)`].filter(Boolean).join(", and ");
23174
23209
  const instead = [
23175
23210
  ...storedPassword ? ["deploy without --reset-password (PostgresAI keeps its password for this server, and sends it only over TLS)"] : [],
23176
23211
  "set PGAI_MON_PASSWORD to its password instead",
23177
- `${disconnectEach(others.map((d) => d.name))} first`
23212
+ `${disconnectEach(others.map((d) => deleteRef(d, list)))} first`
23178
23213
  ];
23179
23214
  return { status: "action_required", provider, name, next: `A new password for ${role} ${what}: ${instead.join(", or ")}` };
23180
23215
  };
23181
- const others = othersOnServer(rows).filter((d) => !unread(d)).map((d) => d.name);
23216
+ const onThisServer = othersOnServer(rows).filter((d) => !unread(d));
23217
+ const others = onThisServer.map((d) => d.name);
23218
+ const otherRefs = onThisServer.map((d) => deleteRef(d, rows));
23182
23219
  if (opts.resetPassword && othersOnServer(rows).length)
23183
- return cutOff(othersOnServer(rows));
23220
+ return cutOff(othersOnServer(rows), rows);
23184
23221
  if (opts.coupon !== undefined && !opts.coupon.trim()) {
23185
23222
  return { status: "action_required", provider, name, next: `${opts.agent ? "coupon" : "--coupon"} is empty: pass a promotion code, or leave ${opts.agent ? "coupon" : "--coupon"} out` };
23186
23223
  }
23187
- const prepOpts = { resetPassword: opts.resetPassword, warn, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
23224
+ const prepOpts = { resetPassword: opts.resetPassword, warn, ...storedPassword ? { storedPassword, others, otherRefs } : {}, ...monitoringUser ? { monitoringUser } : {} };
23188
23225
  if (!opts.selfHosted) {
23189
23226
  const probe = await deps.prepare(url, provider, { ...prepOpts, check: true }).catch((err) => {
23190
23227
  if (err instanceof HttpStatusError || /Could not connect to/.test(errorText(err)))
@@ -23198,6 +23235,9 @@ async function connect(url, opts, deps) {
23198
23235
  }
23199
23236
  return { status: "action_required", provider, name, ...refusal };
23200
23237
  }
23238
+ const where = { db_host: new URL(url).hostname };
23239
+ const placed = await placeBox(deps, opts, where, progress);
23240
+ place = placed?.place;
23201
23241
  let quote;
23202
23242
  try {
23203
23243
  quote = await deps.quote(opts.coupon, clusterOf(url));
@@ -23206,9 +23246,11 @@ async function connect(url, opts, deps) {
23206
23246
  return { status: "action_required", provider, name, next: notAdminNext };
23207
23247
  throw err;
23208
23248
  }
23209
- const b = await billingFor(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)));
23249
+ const b = await billingFor(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)), placed && ((price) => decide(placed, name, price, opts, deps, where, progress)));
23210
23250
  if (b.stop)
23211
- return { status: "action_required", provider, name, ...b.stop };
23251
+ return { status: "action_required", provider, name, ...place, ...b.stop };
23252
+ if (b.placed)
23253
+ place = b.placed.place;
23212
23254
  if (deps.aborted?.())
23213
23255
  throw new CancelledError;
23214
23256
  ({ billing, billingPage, billingUrl, accepted } = b);
@@ -23245,10 +23287,10 @@ async function connect(url, opts, deps) {
23245
23287
  const now = await deps.list();
23246
23288
  const same = findDatabase(now);
23247
23289
  if (same)
23248
- return { status: "action_required", provider, name, id: same.id, ...billing, next: `${name} is already monitored, and its monitoring uses the current password: pgai mon instances delete ${name} --yes first` };
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` };
23249
23291
  const others = othersOnServer(now);
23250
23292
  if (others.length)
23251
- return { ...cutOff(others), ...billing };
23293
+ return { ...cutOff(others, now), ...billing };
23252
23294
  }
23253
23295
  if (deps.aborted?.())
23254
23296
  throw new CancelledError;
@@ -23278,10 +23320,10 @@ async function connect(url, opts, deps) {
23278
23320
  ...opts.coupon ? { promo_code: opts.coupon } : {},
23279
23321
  ...accepted ? { accept_price: true } : {},
23280
23322
  ...opts.name ? { project_name: opts.name } : {},
23281
- ...opts.location ? { server_location: opts.location } : {},
23323
+ ...place ? { cloud: place.cloud, server_location: place.location } : opts.location ? { server_location: opts.location } : {},
23282
23324
  ...vcpus ? { vcpus } : {}
23283
23325
  }).catch(async (err) => {
23284
- if (err instanceof HttpStatusError && err.status >= 400 && err.status < 500)
23326
+ if (err instanceof HttpStatusError && (err.status < 500 || err.sqlstate))
23285
23327
  await undo(prepared);
23286
23328
  else
23287
23329
  unanswered = true;
@@ -23291,8 +23333,25 @@ async function connect(url, opts, deps) {
23291
23333
  return "price";
23292
23334
  if (err instanceof HttpStatusError && err.status === 409 && "storedPassword" in prepared && prepared.storedPassword && /none is stored/.test(err.message))
23293
23335
  return "stored";
23336
+ if (mayHaveRun(err))
23337
+ return "unanswered";
23294
23338
  throw err;
23295
23339
  });
23340
+ if (created === "unanswered") {
23341
+ progress("provisioning", STILL_CREATING);
23342
+ const made = await lookForBox(findMade, opts, deps, started);
23343
+ if (!made && deps.aborted?.())
23344
+ return { status: "action_required", provider, name, ...billing, next: STOPPED_LOOKING };
23345
+ if (!made)
23346
+ return { status: "action_required", provider, name, ...billing, next: opts.agent ? NOT_CONFIRMED_AGENT : NOT_CONFIRMED };
23347
+ if (stateOf(made.status) === "failed" || disconnecting(made.status)) {
23348
+ await undo(prepared);
23349
+ unanswered = false;
23350
+ return { status: "failed", provider, name, id: made.id, next: disconnecting(made.status) ? "PostgresAI could not launch the monitoring box. Re-run pgai mon deploy later." : `PostgresAI could not launch the monitoring box. Run pgai mon instances delete ${made.id} --yes, then pgai mon deploy again.` };
23351
+ }
23352
+ unanswered = false;
23353
+ created = { id: made.id, name: made.name ?? name, status: made.status ?? "launch_requested" };
23354
+ }
23296
23355
  if (created === "payment")
23297
23356
  return { status: "action_required", provider, name, ...billingPage };
23298
23357
  if (created === "declined") {
@@ -23318,7 +23377,65 @@ async function connect(url, opts, deps) {
23318
23377
  const made = prepared;
23319
23378
  undoRole = () => undo(made);
23320
23379
  }
23321
- return follow(row, { provider, name, fresh, billing, billingUrl, undoRole, note }, opts, deps, progress);
23380
+ return follow(row, { provider, name, fresh, billing, billingUrl, undoRole, note, place }, opts, deps, progress);
23381
+ }
23382
+ async function placeBox(deps, opts, where, progress) {
23383
+ if (!deps.deployOptions)
23384
+ return;
23385
+ const cloud = opts.cloud?.trim().toLowerCase() || undefined;
23386
+ const location = opts.location?.trim() || undefined;
23387
+ const flag = (f) => opts.agent ? f : `--${f}`;
23388
+ let options;
23389
+ try {
23390
+ options = await deps.deployOptions({ ...where, ...cloud ? { cloud } : {}, ...location ? { location } : {}, check_stock: true });
23391
+ } catch (err) {
23392
+ if (httpStatus(err) !== 404)
23393
+ throw err;
23394
+ if (cloud)
23395
+ throw new Error(`This PostgresAI platform does not take ${flag("cloud")} yet: re-run without it. Nothing was created.`);
23396
+ if (location && where.supabase_project_ids) {
23397
+ throw new Error(`This PostgresAI platform does not take ${flag("location")} for Supabase yet: re-run without it. Nothing was created.`);
23398
+ }
23399
+ return;
23400
+ }
23401
+ if (!options.choice) {
23402
+ const said = options.error?.detail ?? options.error?.message ?? "The platform did not say where the monitoring box can run.";
23403
+ const elsewhere = location ? options.clouds.find((c) => c.available && c.code !== cloud && options.locations[c.code]?.some((l) => l.code === location)) : undefined;
23404
+ const available = options.clouds.filter((c) => c.available).map((c) => c.code);
23405
+ const how = elsewhere ? ` ${cloud ? "Use" : "Add"} ${flag("cloud")} ${elsewhere.code}.` : /^(Monitoring on .* is not (available here|offered yet)|Unknown cloud)/.test(said) && available.length ? ` Re-run with ${flag("cloud")} ${available.length === 1 ? available[0] : `set to one of: ${available.join(", ")}`}.` : "";
23406
+ throw new Error(`${said}${how} Nothing was created.`);
23407
+ }
23408
+ const c = options.choice;
23409
+ progress("preparing", `Monitoring box: ${c.cloud_label}, ${c.location} (${c.reason_text})`, { cloud: c.cloud, location: c.location, location_reason: c.reason });
23410
+ return { place: { cloud: c.cloud, location: c.location, location_reason: c.reason, location_reason_text: c.reason_text }, options };
23411
+ }
23412
+ async function decide(placed, name, price, opts, deps, where, progress) {
23413
+ if (opts.yes)
23414
+ return { go: true };
23415
+ const { place, options } = placed;
23416
+ const label = options.choice?.cloud_label ?? cloudWord(place.cloud);
23417
+ const explicit = !!(opts.cloud?.trim() || opts.location?.trim());
23418
+ const nothing = "Nothing was created";
23419
+ if (deps.choosePlace) {
23420
+ if (explicit) {
23421
+ return await deps.confirm(`Deploy ${terminalText(name)} on ${label}, ${place.location}? [y/N] `) ? { go: true } : { go: false, stop: { next: `${nothing}: re-run with --yes to deploy on ${label}, ${place.location}` } };
23422
+ }
23423
+ const answer = await deps.choosePlace(options, name);
23424
+ if (answer === true)
23425
+ return { go: true };
23426
+ if (answer === false)
23427
+ return { go: false, stop: { next: `${nothing}: re-run to deploy, with --cloud and --location to choose where` } };
23428
+ const summary = (_event, message, more) => progress("billing", message, more);
23429
+ const again = await placeBox(deps, { ...opts, cloud: answer.cloud, location: answer.location }, where, summary);
23430
+ if (!again)
23431
+ throw new Error(`The platform did not place the box on ${answer.cloud}, ${answer.location}. ${nothing}.`);
23432
+ summary("billing", `Next time, to skip this question: --cloud ${again.place.cloud} --location ${again.place.location} --yes`);
23433
+ return { go: true, place: again };
23434
+ }
23435
+ const choices = Object.fromEntries(options.clouds.filter((c) => c.available && options.locations[c.code]?.length).map((c) => [c.code, options.locations[c.code].map((l) => l.code)]));
23436
+ const here = `${label}, ${place.location} (${place.location_reason_text})`;
23437
+ const next = opts.agent ? `Show the user where the monitoring box would run (${here}) and the price (${price}), then call deploy_monitoring again with yes: true, or with cloud and location from choices and yes: true. ${nothing}.` : `The monitoring box would run on ${here} for ${price}: re-run with --yes to deploy there, or with --cloud and --location (choices below) and --yes. ${nothing}.`;
23438
+ return { go: false, stop: { location_reason_text: place.location_reason_text, choices, next } };
23322
23439
  }
23323
23440
  var isSupabaseUrl = (link) => {
23324
23441
  try {
@@ -23377,8 +23494,6 @@ function supabaseProjectUrl(ref, db = "postgres") {
23377
23494
  function supabaseOptionsRefused(opts) {
23378
23495
  if (opts.resetPassword)
23379
23496
  return "--reset-password does not apply to Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API";
23380
- if (opts.location)
23381
- return "--location does not apply to Supabase yet (PostgresAI picks the box's location): re-run without it";
23382
23497
  if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
23383
23498
  return `${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`;
23384
23499
  }
@@ -23525,6 +23640,9 @@ async function deploySupabaseProject(urlRef, opts, deps, progress) {
23525
23640
  }
23526
23641
  async function supabaseBox(ref, name, opts, deps, progress, stop, label) {
23527
23642
  const provider = "supabase";
23643
+ const where = { supabase_project_ids: [ref] };
23644
+ const placed = await placeBox(deps, opts, where, progress);
23645
+ let place = placed?.place;
23528
23646
  let quote;
23529
23647
  try {
23530
23648
  quote = await deps.quote(opts.coupon);
@@ -23533,9 +23651,11 @@ async function supabaseBox(ref, name, opts, deps, progress, stop, label) {
23533
23651
  return stop(notAdminNext);
23534
23652
  throw err;
23535
23653
  }
23536
- const b = await billingFor(quote, label ?? name, opts, deps, (price) => progress("billing", estimateLine(price), label ? { project: label } : {}));
23654
+ const b = await billingFor(quote, label ?? name, opts, deps, (price) => progress("billing", estimateLine(price), label ? { project: label } : {}), placed && ((price) => decide(placed, label ?? name, price, opts, deps, where, progress)));
23537
23655
  if (b.stop)
23538
- return { status: "action_required", provider, name, ...b.stop };
23656
+ return { status: "action_required", provider, name, ...place, ...b.stop };
23657
+ if (b.placed)
23658
+ place = b.placed.place;
23539
23659
  if (deps.aborted?.())
23540
23660
  throw new CancelledError;
23541
23661
  progress("provisioning", `Provisioning monitoring for ${label ?? name}`, label ? { project: label } : {});
@@ -23544,7 +23664,8 @@ async function supabaseBox(ref, name, opts, deps, progress, stop, label) {
23544
23664
  ...opts.name ? { name: opts.name } : {},
23545
23665
  ...b.accepted ? { accept_price: true } : {},
23546
23666
  ...opts.coupon ? { promo_code: opts.coupon } : {},
23547
- ...opts.vcpus ? { vcpus: opts.vcpus } : {}
23667
+ ...opts.vcpus ? { vcpus: opts.vcpus } : {},
23668
+ ...place ? { cloud: place.cloud, location: place.location } : {}
23548
23669
  }).catch((err) => {
23549
23670
  if (err instanceof HttpStatusError && err.status === 402)
23550
23671
  return /declined/i.test(err.message) ? "declined" : "payment";
@@ -23567,11 +23688,39 @@ async function supabaseBox(ref, name, opts, deps, progress, stop, label) {
23567
23688
  const box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: false };
23568
23689
  if (deps.aborted?.())
23569
23690
  return { ...connectStatus(box, provider, true), ...b.billing };
23570
- return follow(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "" }, opts, deps, progress);
23691
+ return follow(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "", place }, opts, deps, progress);
23571
23692
  }
23572
23693
  var STILL_IN_PROGRESS = "Still in progress";
23694
+ var CONNECT_TIMEOUT_MS = 55000;
23695
+ var AGENT_CONNECT_TIMEOUT_MS = 25000;
23696
+ var STILL_CREATING = "Still creating the monitoring box";
23697
+ var NOT_CONFIRMED = "PostgresAI did not confirm the monitoring box within 5 minutes. Run pgai mon instances list: if this database is there, follow it with pgai mon instances watch <id>; if not, run pgai mon deploy again";
23698
+ var STOPPED_LOOKING = `${STILL_IN_PROGRESS}: deploy stopped watching before PostgresAI confirmed the monitoring box; it may still appear. Run pgai mon instances list before running deploy again`;
23699
+ var NOT_CONFIRMED_AGENT = "PostgresAI did not confirm the monitoring box yet. Call deploy_monitoring again in a minute: it continues with the box if PostgresAI created it. If pgai mon instances list still has no box for this database, ask the user to run pgai mon deploy with --reset-password in a terminal";
23700
+ var LOOKUP_MS = 5 * 60000;
23701
+ var AGENT_RUN_MS = 50000;
23702
+ function mayHaveRun(err) {
23703
+ if (err instanceof HttpRequestTimeoutError)
23704
+ return true;
23705
+ if (err instanceof HttpStatusError)
23706
+ return err.status >= 500 && !err.sqlstate;
23707
+ const message = err instanceof Error ? err.message : "";
23708
+ return / could not reach /.test(message) && !/\((ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|CERT_\w+|ERR_TLS_\w+|UNABLE_TO_\w+|DEPTH_ZERO_\w+|SELF_SIGNED_\w+)\)/.test(message);
23709
+ }
23710
+ async function lookForBox(findMade, opts, deps, started) {
23711
+ for (const deadline = opts.agent ? started + AGENT_RUN_MS : deps.now() + LOOKUP_MS;; ) {
23712
+ const made = findMade(await deps.list().catch(() => []));
23713
+ if (made)
23714
+ return made;
23715
+ const now = deps.now();
23716
+ if (deps.aborted?.() || now >= deadline)
23717
+ return;
23718
+ await deps.sleep(Math.min(POLL_MS, deadline - now));
23719
+ }
23720
+ }
23573
23721
  async function follow(row, f, opts, deps, progress) {
23574
- const { provider, name, fresh, billing, billingUrl, undoRole, note } = f;
23722
+ const { provider, name, fresh, billingUrl, undoRole, note } = f;
23723
+ const billing = { ...f.billing, ...f.place };
23575
23724
  let shown;
23576
23725
  for (const deadline = deps.now() + opts.waitMs;; ) {
23577
23726
  if (row.billing_error && disconnecting(row.status)) {
@@ -23583,7 +23732,7 @@ async function follow(row, f, opts, deps, progress) {
23583
23732
  name,
23584
23733
  id: row.id,
23585
23734
  ...billing,
23586
- next: `The first charge failed (${row.billing_error}): the box is being removed and nothing is billed. Update the payment method${billingUrl ? ` at ${billingUrl}` : ""}, then re-run`
23735
+ next: chargeFailed(row.billing_error, "re-run", billingUrl, opts.agent ? "coupon" : "--coupon")
23587
23736
  };
23588
23737
  }
23589
23738
  const result = connectStatus(row, provider, fresh);
@@ -23751,7 +23900,7 @@ async function prepareDatabase(url, provider, opts = {}) {
23751
23900
  const noTls = refusedTls || !usedSsl && me.ssl === "off";
23752
23901
  const tlsOnly = `PostgresAI sends the password it keeps for ${role} only over TLS`;
23753
23902
  const others = opts.others?.length ? opts.others : undefined;
23754
- const disconnectOthers = others ? disconnectEach(others) : "pgai mon instances delete the server's other databases (pgai mon instances list)";
23903
+ const disconnectOthers = others ? disconnectEach(opts.otherRefs ?? others) : "pgai mon instances delete the server's other databases (pgai mon instances list)";
23755
23904
  const reconnectOthers = `(and deploy ${others ? others.join(", ") : "them"} again with it)`;
23756
23905
  const noTlsWayOut = opts.agent ? `Pass its URL as database_url, or run pgai mon deploy in a terminal with PGAI_MON_PASSWORD set to its password. If nobody has it, in a terminal: ${disconnectOthers}, then pgai mon deploy <admin-url> --reset-password with PGAI_MON_PASSWORD set to a new one ${reconnectOthers}` : `Set PGAI_MON_PASSWORD to its password, or turn on TLS on the server (ssl = on) and put sslmode=require in the URL. If nobody has the password: ${disconnectOthers}, then re-run with --reset-password and PGAI_MON_PASSWORD set to a new one ${reconnectOthers}`;
23757
23906
  const reuse = me.mon_exists && !opts.resetPassword && !!opts.storedPassword && !(opts.agent ? "" : process.env.PGAI_MON_PASSWORD?.trim());
@@ -23863,7 +24012,16 @@ function grafanaOAuthUrl(dashboardUrl) {
23863
24012
  return `${u.origin}/login/generic_oauth?redirectTo=${encodeURIComponent(`${u.pathname}${u.search}`)}`;
23864
24013
  }
23865
24014
  function platformDeps(p) {
23866
- const rpc = (fn, body = {}) => callRpc({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl, fn, body, operation: fn.replace(/_/g, " "), debug: p.debug, orgScope: p.orgScope });
24015
+ const rpc = (fn, body = {}, timeoutMs) => callRpc({
24016
+ apiKey: p.apiKey,
24017
+ apiBaseUrl: p.apiBaseUrl,
24018
+ fn,
24019
+ body,
24020
+ operation: fn.replace(/_/g, " "),
24021
+ debug: p.debug,
24022
+ orgScope: p.orgScope,
24023
+ ...timeoutMs ? { timeoutMs, timeoutCeilingMs: timeoutMs } : {}
24024
+ });
23867
24025
  let orgAlias;
23868
24026
  let projects;
23869
24027
  const healthUrl = async (row) => {
@@ -23887,7 +24045,7 @@ function platformDeps(p) {
23887
24045
  verifyTls: verifyCollectorTls,
23888
24046
  list: () => rpc("cloud_monitoring_list"),
23889
24047
  links: withLinks,
23890
- create: (body) => rpc("cloud_monitoring_connect", body),
24048
+ create: (body) => rpc("cloud_monitoring_connect", body, p.agent ? AGENT_CONNECT_TIMEOUT_MS : CONNECT_TIMEOUT_MS),
23891
24049
  disconnect: (id) => rpc("cloud_monitoring_disconnect", { instance_id: id }),
23892
24050
  setVcpus: (id, vcpus) => rpc("cloud_monitoring_set_vcpus", { instance_id: id, vcpus }),
23893
24051
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
@@ -23901,6 +24059,7 @@ function platformDeps(p) {
23901
24059
  supabaseStatus: (sessionId) => rpc("cloud_monitoring_supabase_status", { session_id: sessionId }),
23902
24060
  supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
23903
24061
  supabaseProjects: () => rpc("cloud_monitoring_supabase_projects", {}),
24062
+ deployOptions: (args) => rpc("monitoring_deploy_options", args),
23904
24063
  handoffUrl: async (provider) => {
23905
24064
  const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
23906
24065
  const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
@@ -30598,6 +30757,8 @@ async function handleToolCall(req, rootOpts, extra) {
30598
30757
  yes: args.yes === true,
30599
30758
  vcpus: args.vcpus === undefined || args.vcpus === null ? undefined : vcpusArg(String(args.vcpus)),
30600
30759
  monitoringUser: args.monitoring_user === undefined || args.monitoring_user === null ? undefined : String(args.monitoring_user),
30760
+ cloud: args.cloud === undefined || args.cloud === null ? undefined : String(args.cloud),
30761
+ location: args.location === undefined || args.location === null ? undefined : String(args.location),
30601
30762
  waitMs: 0,
30602
30763
  agent: true
30603
30764
  }, {
@@ -31180,7 +31341,9 @@ async function startMcpServer(rootOpts, extra) {
31180
31341
  database_url: { type: "string", description: "postgresql:// URL with the password in it (admin, or the postgres_ai_mon role)" },
31181
31342
  provider: { type: "string", description: "generic (direct PostgreSQL URL; alias: self-managed) | clickhouse | rds | supabase (default: detected from the host)" },
31182
31343
  clickhouse_key: { type: "string", description: "ClickHouse Cloud API key as <key-id>:<key-secret> (Basic Service API Reader), for CPU, memory and disk" },
31183
- 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" },
31344
+ yes: { type: "boolean", description: "Deploy: accept where the box runs and its price. Without it no box is provisioned, free or billed (on a platform without cloud choice, only a billed one waits for it): the result has status action_required with cloud, location, location_reason_text, price and choices (each cloud's locations); show them to the user, then call again with yes: true (and cloud/location if they chose another place)" },
31345
+ cloud: { type: "string", description: "Where the monitoring box runs: aws or hetzner (default: the database's cloud, else the platform's default). One of the result's choices" },
31346
+ location: { type: "string", description: "A location of that cloud, from the result's choices (default: the database's region, else the cloud's default)" },
31184
31347
  coupon: { type: "string", description: "Stripe promotion code for the organization's monitoring subscription (applies when it is first created)" },
31185
31348
  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" },
31186
31349
  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" },
@@ -32232,6 +32395,7 @@ function storedPasswordNeeds2(monitoringUrl) {
32232
32395
  return needs.length ? needs.join(" and ") : undefined;
32233
32396
  }
32234
32397
  var shellWord2 = (s) => /^[\w./:@%+=,-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
32398
+ var deleteRef2 = (d, list) => list.some((o) => o.id !== d.id && !disconnecting2(o.status) && o.name === d.name) ? d.id : d.name;
32235
32399
  var disconnectEach2 = (names) => names.map((n) => `pgai mon instances delete ${shellWord2(n)} --yes`).join(" and ");
32236
32400
  function loginName2(url, sessionUser, role) {
32237
32401
  const user = decodeURIComponent(new URL(url).username);
@@ -32256,6 +32420,10 @@ function caNote2(url) {
32256
32420
  return;
32257
32421
  return `the monitoring box has no copy of the CA in sslrootcert: with sslmode=${q.get("sslmode")} it connects only to a server certificate signed by a public CA (else use sslmode=require)`;
32258
32422
  }
32423
+ function chargeFailed2(error, rerun, billingUrl, couponFlag = "--coupon") {
32424
+ const fix = /promotion code|coupon/i.test(error) ? `The promo code cannot be used by this organization: ${rerun} without ${couponFlag}, or with a code this organization can use` : `Update the payment method${billingUrl ? ` at ${billingUrl}` : ""}, then ${rerun}`;
32425
+ return `The first charge failed (${error}): the box is being removed and nothing is billed. ${fix}`;
32426
+ }
32259
32427
  function connectStatus2(row, provider = row.provider, fresh = false) {
32260
32428
  const base = { provider, name: row.name, id: row.id, ...row.health_url ? { health_url: row.health_url } : {}, dashboard_url: row.dashboard_url, host_metrics: row.host_metrics };
32261
32429
  const status = stateOf2(row.status);
@@ -32263,7 +32431,7 @@ function connectStatus2(row, provider = row.provider, fresh = false) {
32263
32431
  return {
32264
32432
  ...base,
32265
32433
  status: "action_required",
32266
- next: `The first charge failed (${row.billing_error}): the box is being removed and nothing is billed. Update the payment method, then re-run pgai mon deploy.`
32434
+ next: `${chargeFailed2(row.billing_error, "re-run pgai mon deploy")}.`
32267
32435
  };
32268
32436
  }
32269
32437
  if (status === "ready") {
@@ -32310,12 +32478,15 @@ function stepProgress(o) {
32310
32478
  view.log(e.message);
32311
32479
  if (e.event === "box" && e.state)
32312
32480
  view.setNote(`box: ${boxWords2(e.state)}`);
32481
+ if (e.message === STILL_CREATING2)
32482
+ view.setNote(`still creating: PostgresAI is slow to answer (checking for up to ${LOOKUP_MS2 / 60000} min)`);
32313
32483
  };
32314
32484
  return { progress, view: () => view };
32315
32485
  }
32316
32486
  function resultLines(r) {
32317
32487
  return personLines(r).map(terminalText2);
32318
32488
  }
32489
+ var cloudWord2 = (cloud) => ({ aws: "AWS", hetzner: "Hetzner" })[cloud] ?? cloud;
32319
32490
  function personLines(r) {
32320
32491
  const who = r.name || "this database";
32321
32492
  const extra = (r.next ?? "").split("; ").slice(1).join("; ");
@@ -32327,6 +32498,7 @@ function personLines(r) {
32327
32498
  ...r.health_url ? [` Health Matrix: ${r.health_url}`] : [],
32328
32499
  ...r.dashboard_url ? [` Grafana: ${r.dashboard_url}`] : [],
32329
32500
  ...r.price ? [` Price: ${r.price}`] : [],
32501
+ ...r.cloud ? [` Runs on: ${cloudWord2(r.cloud)}, ${r.location}`] : [],
32330
32502
  ...!r.health_url && !r.dashboard_url && r.next && r.next !== "none" ? [`Next: ${r.next}`] : [],
32331
32503
  ...extra && (r.health_url || r.dashboard_url) ? [`Note: ${extra}`] : []
32332
32504
  ];
@@ -32336,7 +32508,9 @@ function personLines(r) {
32336
32508
  case "deleted":
32337
32509
  return [`Deleting the monitoring of ${who}.${billing ? ` Billing: ${billing}.` : ""}${r.next && r.next !== "none" ? ` ${r.next}` : ""}`];
32338
32510
  default:
32339
- return r.projects?.length ? [r.next, ...supabaseProjectRows(r.projects)] : [r.next];
32511
+ if (r.projects?.length)
32512
+ return [r.next, ...supabaseProjectRows(r.projects)];
32513
+ return r.choices ? [r.next, ...Object.entries(r.choices).map(([cloud, codes]) => ` --cloud ${cloud} --location ${codes.join("|")}`)] : [r.next];
32340
32514
  }
32341
32515
  }
32342
32516
  function progressText(e) {
@@ -32356,7 +32530,7 @@ function boxWords2(state) {
32356
32530
  return "installing monitoring";
32357
32531
  return monitoringStatus(state).replace("_", " ");
32358
32532
  }
32359
- async function billingFor2(q, name, opts, deps, show) {
32533
+ async function billingFor2(q, name, opts, deps, show, ask) {
32360
32534
  const billing = { price: priceText2(q), requires_payment_method: q.requires_payment_method };
32361
32535
  if (opts.coupon) {
32362
32536
  billing.coupon = q.promo?.valid ? { code: q.promo.code, valid: true, description: q.promo.discount_description } : { code: opts.coupon, valid: false, error: q.promo?.error ?? "not valid" };
@@ -32370,6 +32544,12 @@ async function billingFor2(q, name, opts, deps, show) {
32370
32544
  if (q.requires_payment_method)
32371
32545
  return { billing, billingPage, billingUrl, accepted: false, stop: billingPage };
32372
32546
  show(billing.price);
32547
+ if (ask) {
32548
+ const d = await ask(billing.price);
32549
+ if (!d.go)
32550
+ return { billing, billingPage, billingUrl, accepted: false, stop: { ...billing, ...d.stop } };
32551
+ return { billing, billingPage, billingUrl, accepted: q.billed, placed: d.place };
32552
+ }
32373
32553
  if (q.billed && !opts.yes && !await deps.confirm(`Provision ${terminalText2(name)}? (y/N): `)) {
32374
32554
  return stop(opts.agent ? `Call deploy_monitoring again with yes: true to accept ${billing.price}` : `Re-run with --yes to accept ${billing.price}`);
32375
32555
  }
@@ -32448,11 +32628,18 @@ async function connect2(url, opts, deps) {
32448
32628
  if (opts.selfHosted && deps.localStackRunning()) {
32449
32629
  return { status: "action_required", provider, name, next: "A monitoring stack already runs on this machine: add the database with PGAI_DB_URL='<postgres_ai_mon URL>' pgai mon targets add" };
32450
32630
  }
32631
+ const byCluster = (d) => !!d.cluster && serverOf2(d.cluster) === cluster && d.database != null && decodeURIComponent(d.database) === name.split("/").slice(1).join("/");
32632
+ const byName = (d) => (d.cluster == null || d.database == null) && d.name === name;
32451
32633
  const findDatabase = (list) => {
32452
32634
  const live = list.filter((d) => !disconnecting2(d.status));
32453
- return live.find((d) => d.cluster && serverOf2(d.cluster) === cluster && d.database != null && decodeURIComponent(d.database) === name.split("/").slice(1).join("/")) ?? live.find((d) => (d.cluster == null || d.database == null) && d.name === name);
32635
+ return live.find(byCluster) ?? live.find(byName);
32454
32636
  };
32455
32637
  const rows = opts.selfHosted ? [] : await deps.list();
32638
+ const known = new Set(rows.map((d) => d.id));
32639
+ const findMade = (list) => {
32640
+ const fresh = list.filter((d) => !known.has(d.id));
32641
+ return fresh.find(byCluster) ?? fresh.find(byName);
32642
+ };
32456
32643
  let row = findDatabase(rows);
32457
32644
  const fresh = !row;
32458
32645
  let note = "";
@@ -32460,6 +32647,7 @@ async function connect2(url, opts, deps) {
32460
32647
  let billingPage;
32461
32648
  let accepted = false;
32462
32649
  let billingUrl;
32650
+ let place;
32463
32651
  let undoRole;
32464
32652
  const findOrg = async () => {
32465
32653
  try {
@@ -32493,7 +32681,7 @@ async function connect2(url, opts, deps) {
32493
32681
  }
32494
32682
  }
32495
32683
  if (row && opts.resetPassword) {
32496
- return { status: "action_required", provider, name, id: row.id, next: `${name} is already monitored, and its monitoring uses the current password: pgai mon instances delete ${name} --yes first` };
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` };
32497
32685
  }
32498
32686
  if (row && key) {
32499
32687
  const found = await findOrg();
@@ -32521,26 +32709,30 @@ async function connect2(url, opts, deps) {
32521
32709
  let lockId;
32522
32710
  const unread = (d) => !d.cluster;
32523
32711
  const onServer = (d) => !!d.cluster && serverOf2(d.cluster) === cluster;
32524
- const othersOnServer = (list) => list.filter((d) => !disconnecting2(d.status) && (unread(d) || onServer(d)));
32712
+ 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)));
32525
32714
  const storedPassword = !monitoringUser && rows.some((d) => d.monitoring_password_stored && !/delet/.test(d.status ?? "") && onServer(d)) || undefined;
32526
- const cutOff = (others) => {
32527
- const on = others.filter((d) => !unread(d)).map((d) => d.name).join(", ");
32528
- const maybe = others.filter(unread).map((d) => d.name).join(", ");
32715
+ const cutOff = (others, list) => {
32716
+ const label = (d) => deleteRef2(d, list) === d.id ? `${d.name} (id ${d.id})` : d.name;
32717
+ const on = others.filter((d) => !unread(d)).map(label).join(", ");
32718
+ const maybe = others.filter(unread).map(label).join(", ");
32529
32719
  const what = [on && `would cut off the monitoring of ${on} on this server`, maybe && `may cut off the monitoring of ${maybe} (the platform could not read its URL, so its server is not known)`].filter(Boolean).join(", and ");
32530
32720
  const instead = [
32531
32721
  ...storedPassword ? ["deploy without --reset-password (PostgresAI keeps its password for this server, and sends it only over TLS)"] : [],
32532
32722
  "set PGAI_MON_PASSWORD to its password instead",
32533
- `${disconnectEach2(others.map((d) => d.name))} first`
32723
+ `${disconnectEach2(others.map((d) => deleteRef2(d, list)))} first`
32534
32724
  ];
32535
32725
  return { status: "action_required", provider, name, next: `A new password for ${role} ${what}: ${instead.join(", or ")}` };
32536
32726
  };
32537
- const others = othersOnServer(rows).filter((d) => !unread(d)).map((d) => d.name);
32727
+ const onThisServer = othersOnServer(rows).filter((d) => !unread(d));
32728
+ const others = onThisServer.map((d) => d.name);
32729
+ const otherRefs = onThisServer.map((d) => deleteRef2(d, rows));
32538
32730
  if (opts.resetPassword && othersOnServer(rows).length)
32539
- return cutOff(othersOnServer(rows));
32731
+ return cutOff(othersOnServer(rows), rows);
32540
32732
  if (opts.coupon !== undefined && !opts.coupon.trim()) {
32541
32733
  return { status: "action_required", provider, name, next: `${opts.agent ? "coupon" : "--coupon"} is empty: pass a promotion code, or leave ${opts.agent ? "coupon" : "--coupon"} out` };
32542
32734
  }
32543
- const prepOpts = { resetPassword: opts.resetPassword, warn, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
32735
+ const prepOpts = { resetPassword: opts.resetPassword, warn, ...storedPassword ? { storedPassword, others, otherRefs } : {}, ...monitoringUser ? { monitoringUser } : {} };
32544
32736
  if (!opts.selfHosted) {
32545
32737
  const probe = await deps.prepare(url, provider, { ...prepOpts, check: true }).catch((err) => {
32546
32738
  if (err instanceof HttpStatusError || /Could not connect to/.test(errorText2(err)))
@@ -32554,6 +32746,9 @@ async function connect2(url, opts, deps) {
32554
32746
  }
32555
32747
  return { status: "action_required", provider, name, ...refusal };
32556
32748
  }
32749
+ const where = { db_host: new URL(url).hostname };
32750
+ const placed = await placeBox2(deps, opts, where, progress);
32751
+ place = placed?.place;
32557
32752
  let quote;
32558
32753
  try {
32559
32754
  quote = await deps.quote(opts.coupon, clusterOf2(url));
@@ -32562,9 +32757,11 @@ async function connect2(url, opts, deps) {
32562
32757
  return { status: "action_required", provider, name, next: notAdminNext };
32563
32758
  throw err;
32564
32759
  }
32565
- const b = await billingFor2(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)));
32760
+ const b = await billingFor2(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)), placed && ((price) => decide2(placed, name, price, opts, deps, where, progress)));
32566
32761
  if (b.stop)
32567
- return { status: "action_required", provider, name, ...b.stop };
32762
+ return { status: "action_required", provider, name, ...place, ...b.stop };
32763
+ if (b.placed)
32764
+ place = b.placed.place;
32568
32765
  if (deps.aborted?.())
32569
32766
  throw new CancelledError2;
32570
32767
  ({ billing, billingPage, billingUrl, accepted } = b);
@@ -32601,10 +32798,10 @@ async function connect2(url, opts, deps) {
32601
32798
  const now = await deps.list();
32602
32799
  const same = findDatabase(now);
32603
32800
  if (same)
32604
- return { status: "action_required", provider, name, id: same.id, ...billing, next: `${name} is already monitored, and its monitoring uses the current password: pgai mon instances delete ${name} --yes first` };
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` };
32605
32802
  const others = othersOnServer(now);
32606
32803
  if (others.length)
32607
- return { ...cutOff(others), ...billing };
32804
+ return { ...cutOff(others, now), ...billing };
32608
32805
  }
32609
32806
  if (deps.aborted?.())
32610
32807
  throw new CancelledError2;
@@ -32634,10 +32831,10 @@ async function connect2(url, opts, deps) {
32634
32831
  ...opts.coupon ? { promo_code: opts.coupon } : {},
32635
32832
  ...accepted ? { accept_price: true } : {},
32636
32833
  ...opts.name ? { project_name: opts.name } : {},
32637
- ...opts.location ? { server_location: opts.location } : {},
32834
+ ...place ? { cloud: place.cloud, server_location: place.location } : opts.location ? { server_location: opts.location } : {},
32638
32835
  ...vcpus ? { vcpus } : {}
32639
32836
  }).catch(async (err) => {
32640
- if (err instanceof HttpStatusError && err.status >= 400 && err.status < 500)
32837
+ if (err instanceof HttpStatusError && (err.status < 500 || err.sqlstate))
32641
32838
  await undo(prepared);
32642
32839
  else
32643
32840
  unanswered = true;
@@ -32647,8 +32844,25 @@ async function connect2(url, opts, deps) {
32647
32844
  return "price";
32648
32845
  if (err instanceof HttpStatusError && err.status === 409 && "storedPassword" in prepared && prepared.storedPassword && /none is stored/.test(err.message))
32649
32846
  return "stored";
32847
+ if (mayHaveRun2(err))
32848
+ return "unanswered";
32650
32849
  throw err;
32651
32850
  });
32851
+ if (created === "unanswered") {
32852
+ progress("provisioning", STILL_CREATING2);
32853
+ const made = await lookForBox2(findMade, opts, deps, started);
32854
+ if (!made && deps.aborted?.())
32855
+ return { status: "action_required", provider, name, ...billing, next: STOPPED_LOOKING2 };
32856
+ if (!made)
32857
+ return { status: "action_required", provider, name, ...billing, next: opts.agent ? NOT_CONFIRMED_AGENT2 : NOT_CONFIRMED2 };
32858
+ if (stateOf2(made.status) === "failed" || disconnecting2(made.status)) {
32859
+ await undo(prepared);
32860
+ unanswered = false;
32861
+ return { status: "failed", provider, name, id: made.id, next: disconnecting2(made.status) ? "PostgresAI could not launch the monitoring box. Re-run pgai mon deploy later." : `PostgresAI could not launch the monitoring box. Run pgai mon instances delete ${made.id} --yes, then pgai mon deploy again.` };
32862
+ }
32863
+ unanswered = false;
32864
+ created = { id: made.id, name: made.name ?? name, status: made.status ?? "launch_requested" };
32865
+ }
32652
32866
  if (created === "payment")
32653
32867
  return { status: "action_required", provider, name, ...billingPage };
32654
32868
  if (created === "declined") {
@@ -32674,7 +32888,110 @@ async function connect2(url, opts, deps) {
32674
32888
  const made = prepared;
32675
32889
  undoRole = () => undo(made);
32676
32890
  }
32677
- return follow2(row, { provider, name, fresh, billing, billingUrl, undoRole, note }, opts, deps, progress);
32891
+ return follow2(row, { provider, name, fresh, billing, billingUrl, undoRole, note, place }, opts, deps, progress);
32892
+ }
32893
+ async function placeBox2(deps, opts, where, progress) {
32894
+ if (!deps.deployOptions)
32895
+ return;
32896
+ const cloud = opts.cloud?.trim().toLowerCase() || undefined;
32897
+ const location = opts.location?.trim() || undefined;
32898
+ const flag = (f) => opts.agent ? f : `--${f}`;
32899
+ let options;
32900
+ try {
32901
+ options = await deps.deployOptions({ ...where, ...cloud ? { cloud } : {}, ...location ? { location } : {}, check_stock: true });
32902
+ } catch (err) {
32903
+ if (httpStatus2(err) !== 404)
32904
+ throw err;
32905
+ if (cloud)
32906
+ throw new Error(`This PostgresAI platform does not take ${flag("cloud")} yet: re-run without it. Nothing was created.`);
32907
+ if (location && where.supabase_project_ids) {
32908
+ throw new Error(`This PostgresAI platform does not take ${flag("location")} for Supabase yet: re-run without it. Nothing was created.`);
32909
+ }
32910
+ return;
32911
+ }
32912
+ if (!options.choice) {
32913
+ const said = options.error?.detail ?? options.error?.message ?? "The platform did not say where the monitoring box can run.";
32914
+ const elsewhere = location ? options.clouds.find((c) => c.available && c.code !== cloud && options.locations[c.code]?.some((l) => l.code === location)) : undefined;
32915
+ const available = options.clouds.filter((c) => c.available).map((c) => c.code);
32916
+ const how = elsewhere ? ` ${cloud ? "Use" : "Add"} ${flag("cloud")} ${elsewhere.code}.` : /^(Monitoring on .* is not (available here|offered yet)|Unknown cloud)/.test(said) && available.length ? ` Re-run with ${flag("cloud")} ${available.length === 1 ? available[0] : `set to one of: ${available.join(", ")}`}.` : "";
32917
+ throw new Error(`${said}${how} Nothing was created.`);
32918
+ }
32919
+ const c = options.choice;
32920
+ progress("preparing", `Monitoring box: ${c.cloud_label}, ${c.location} (${c.reason_text})`, { cloud: c.cloud, location: c.location, location_reason: c.reason });
32921
+ return { place: { cloud: c.cloud, location: c.location, location_reason: c.reason, location_reason_text: c.reason_text }, options };
32922
+ }
32923
+ async function pickPlace(options, name, ask, say) {
32924
+ const number = async (what, n) => {
32925
+ for (let tries = 0;tries < 3; tries++) {
32926
+ const answer = (await ask(`${what} (1-${n}, Enter to cancel): `)).trim();
32927
+ if (!answer)
32928
+ return;
32929
+ const i = Number(answer);
32930
+ if (Number.isInteger(i) && i >= 1 && i <= n)
32931
+ return i - 1;
32932
+ say(`Type a number from 1 to ${n}.`);
32933
+ }
32934
+ return;
32935
+ };
32936
+ for (let tries = 0;tries < 3; tries++) {
32937
+ const answer = (await ask(`Deploy ${terminalText2(name)} here? [y]es / [c]hoose another location / [N]o: `)).trim().toLowerCase();
32938
+ if (answer === "y" || answer === "yes")
32939
+ return true;
32940
+ if (!answer || answer === "n" || answer === "no")
32941
+ return false;
32942
+ if (answer !== "c" && answer !== "choose") {
32943
+ say("Type y, c or n.");
32944
+ continue;
32945
+ }
32946
+ const clouds = options.clouds.filter((c) => c.available && options.locations[c.code]?.length);
32947
+ say("Clouds:");
32948
+ clouds.forEach((c, i) => say(` ${i + 1}. ${c.label}`));
32949
+ const ci = await number("Cloud", clouds.length);
32950
+ if (ci === undefined)
32951
+ return false;
32952
+ const cloud = clouds[ci];
32953
+ const locations = options.locations[cloud.code];
32954
+ say(`Locations on ${cloud.label}:`);
32955
+ let part = "";
32956
+ locations.forEach((l, i) => {
32957
+ if (l.world_part !== part)
32958
+ say(` ${part = l.world_part}`);
32959
+ say(` ${i + 1}. ${l.code}${l.label ? ` ${terminalText2(l.label)}` : ""}`);
32960
+ });
32961
+ const li = await number("Location", locations.length);
32962
+ if (li === undefined)
32963
+ return false;
32964
+ return { cloud: cloud.code, location: locations[li].code };
32965
+ }
32966
+ return false;
32967
+ }
32968
+ async function decide2(placed, name, price, opts, deps, where, progress) {
32969
+ if (opts.yes)
32970
+ return { go: true };
32971
+ const { place, options } = placed;
32972
+ const label = options.choice?.cloud_label ?? cloudWord2(place.cloud);
32973
+ const explicit = !!(opts.cloud?.trim() || opts.location?.trim());
32974
+ const nothing = "Nothing was created";
32975
+ if (deps.choosePlace) {
32976
+ if (explicit) {
32977
+ return await deps.confirm(`Deploy ${terminalText2(name)} on ${label}, ${place.location}? [y/N] `) ? { go: true } : { go: false, stop: { next: `${nothing}: re-run with --yes to deploy on ${label}, ${place.location}` } };
32978
+ }
32979
+ const answer = await deps.choosePlace(options, name);
32980
+ if (answer === true)
32981
+ return { go: true };
32982
+ if (answer === false)
32983
+ return { go: false, stop: { next: `${nothing}: re-run to deploy, with --cloud and --location to choose where` } };
32984
+ const summary = (_event, message, more) => progress("billing", message, more);
32985
+ const again = await placeBox2(deps, { ...opts, cloud: answer.cloud, location: answer.location }, where, summary);
32986
+ if (!again)
32987
+ throw new Error(`The platform did not place the box on ${answer.cloud}, ${answer.location}. ${nothing}.`);
32988
+ summary("billing", `Next time, to skip this question: --cloud ${again.place.cloud} --location ${again.place.location} --yes`);
32989
+ return { go: true, place: again };
32990
+ }
32991
+ const choices = Object.fromEntries(options.clouds.filter((c) => c.available && options.locations[c.code]?.length).map((c) => [c.code, options.locations[c.code].map((l) => l.code)]));
32992
+ const here = `${label}, ${place.location} (${place.location_reason_text})`;
32993
+ const next = opts.agent ? `Show the user where the monitoring box would run (${here}) and the price (${price}), then call deploy_monitoring again with yes: true, or with cloud and location from choices and yes: true. ${nothing}.` : `The monitoring box would run on ${here} for ${price}: re-run with --yes to deploy there, or with --cloud and --location (choices below) and --yes. ${nothing}.`;
32994
+ return { go: false, stop: { location_reason_text: place.location_reason_text, choices, next } };
32678
32995
  }
32679
32996
  var isSupabaseUrl2 = (link) => {
32680
32997
  try {
@@ -32733,8 +33050,6 @@ function supabaseProjectUrl2(ref, db = "postgres") {
32733
33050
  function supabaseOptionsRefused2(opts) {
32734
33051
  if (opts.resetPassword)
32735
33052
  return "--reset-password does not apply to Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API";
32736
- if (opts.location)
32737
- return "--location does not apply to Supabase yet (PostgresAI picks the box's location): re-run without it";
32738
33053
  if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
32739
33054
  return `${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`;
32740
33055
  }
@@ -32901,6 +33216,9 @@ async function deploySupabaseProject2(urlRef, opts, deps, progress) {
32901
33216
  }
32902
33217
  async function supabaseBox2(ref, name, opts, deps, progress, stop, label) {
32903
33218
  const provider = "supabase";
33219
+ const where = { supabase_project_ids: [ref] };
33220
+ const placed = await placeBox2(deps, opts, where, progress);
33221
+ let place = placed?.place;
32904
33222
  let quote;
32905
33223
  try {
32906
33224
  quote = await deps.quote(opts.coupon);
@@ -32909,9 +33227,11 @@ async function supabaseBox2(ref, name, opts, deps, progress, stop, label) {
32909
33227
  return stop(notAdminNext);
32910
33228
  throw err;
32911
33229
  }
32912
- const b = await billingFor2(quote, label ?? name, opts, deps, (price) => progress("billing", estimateLine(price), label ? { project: label } : {}));
33230
+ const b = await billingFor2(quote, label ?? name, opts, deps, (price) => progress("billing", estimateLine(price), label ? { project: label } : {}), placed && ((price) => decide2(placed, label ?? name, price, opts, deps, where, progress)));
32913
33231
  if (b.stop)
32914
- return { status: "action_required", provider, name, ...b.stop };
33232
+ return { status: "action_required", provider, name, ...place, ...b.stop };
33233
+ if (b.placed)
33234
+ place = b.placed.place;
32915
33235
  if (deps.aborted?.())
32916
33236
  throw new CancelledError2;
32917
33237
  progress("provisioning", `Provisioning monitoring for ${label ?? name}`, label ? { project: label } : {});
@@ -32920,7 +33240,8 @@ async function supabaseBox2(ref, name, opts, deps, progress, stop, label) {
32920
33240
  ...opts.name ? { name: opts.name } : {},
32921
33241
  ...b.accepted ? { accept_price: true } : {},
32922
33242
  ...opts.coupon ? { promo_code: opts.coupon } : {},
32923
- ...opts.vcpus ? { vcpus: opts.vcpus } : {}
33243
+ ...opts.vcpus ? { vcpus: opts.vcpus } : {},
33244
+ ...place ? { cloud: place.cloud, location: place.location } : {}
32924
33245
  }).catch((err) => {
32925
33246
  if (err instanceof HttpStatusError && err.status === 402)
32926
33247
  return /declined/i.test(err.message) ? "declined" : "payment";
@@ -32943,11 +33264,39 @@ async function supabaseBox2(ref, name, opts, deps, progress, stop, label) {
32943
33264
  const box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: false };
32944
33265
  if (deps.aborted?.())
32945
33266
  return { ...connectStatus2(box, provider, true), ...b.billing };
32946
- return follow2(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "" }, opts, deps, progress);
33267
+ return follow2(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "", place }, opts, deps, progress);
32947
33268
  }
32948
33269
  var STILL_IN_PROGRESS2 = "Still in progress";
33270
+ var CONNECT_TIMEOUT_MS2 = 55000;
33271
+ var AGENT_CONNECT_TIMEOUT_MS2 = 25000;
33272
+ var STILL_CREATING2 = "Still creating the monitoring box";
33273
+ var NOT_CONFIRMED2 = "PostgresAI did not confirm the monitoring box within 5 minutes. Run pgai mon instances list: if this database is there, follow it with pgai mon instances watch <id>; if not, run pgai mon deploy again";
33274
+ var STOPPED_LOOKING2 = `${STILL_IN_PROGRESS2}: deploy stopped watching before PostgresAI confirmed the monitoring box; it may still appear. Run pgai mon instances list before running deploy again`;
33275
+ var NOT_CONFIRMED_AGENT2 = "PostgresAI did not confirm the monitoring box yet. Call deploy_monitoring again in a minute: it continues with the box if PostgresAI created it. If pgai mon instances list still has no box for this database, ask the user to run pgai mon deploy with --reset-password in a terminal";
33276
+ var LOOKUP_MS2 = 5 * 60000;
33277
+ var AGENT_RUN_MS2 = 50000;
33278
+ function mayHaveRun2(err) {
33279
+ if (err instanceof HttpRequestTimeoutError)
33280
+ return true;
33281
+ if (err instanceof HttpStatusError)
33282
+ return err.status >= 500 && !err.sqlstate;
33283
+ const message = err instanceof Error ? err.message : "";
33284
+ return / could not reach /.test(message) && !/\((ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|CERT_\w+|ERR_TLS_\w+|UNABLE_TO_\w+|DEPTH_ZERO_\w+|SELF_SIGNED_\w+)\)/.test(message);
33285
+ }
33286
+ async function lookForBox2(findMade, opts, deps, started) {
33287
+ for (const deadline = opts.agent ? started + AGENT_RUN_MS2 : deps.now() + LOOKUP_MS2;; ) {
33288
+ const made = findMade(await deps.list().catch(() => []));
33289
+ if (made)
33290
+ return made;
33291
+ const now = deps.now();
33292
+ if (deps.aborted?.() || now >= deadline)
33293
+ return;
33294
+ await deps.sleep(Math.min(POLL_MS2, deadline - now));
33295
+ }
33296
+ }
32949
33297
  async function follow2(row, f, opts, deps, progress) {
32950
- const { provider, name, fresh, billing, billingUrl, undoRole, note } = f;
33298
+ const { provider, name, fresh, billingUrl, undoRole, note } = f;
33299
+ const billing = { ...f.billing, ...f.place };
32951
33300
  let shown;
32952
33301
  for (const deadline = deps.now() + opts.waitMs;; ) {
32953
33302
  if (row.billing_error && disconnecting2(row.status)) {
@@ -32959,7 +33308,7 @@ async function follow2(row, f, opts, deps, progress) {
32959
33308
  name,
32960
33309
  id: row.id,
32961
33310
  ...billing,
32962
- next: `The first charge failed (${row.billing_error}): the box is being removed and nothing is billed. Update the payment method${billingUrl ? ` at ${billingUrl}` : ""}, then re-run`
33311
+ next: chargeFailed2(row.billing_error, "re-run", billingUrl, opts.agent ? "coupon" : "--coupon")
32963
33312
  };
32964
33313
  }
32965
33314
  const result = connectStatus2(row, provider, fresh);
@@ -33127,7 +33476,7 @@ async function prepareDatabase2(url, provider, opts = {}) {
33127
33476
  const noTls = refusedTls || !usedSsl && me.ssl === "off";
33128
33477
  const tlsOnly = `PostgresAI sends the password it keeps for ${role} only over TLS`;
33129
33478
  const others = opts.others?.length ? opts.others : undefined;
33130
- const disconnectOthers = others ? disconnectEach2(others) : "pgai mon instances delete the server's other databases (pgai mon instances list)";
33479
+ const disconnectOthers = others ? disconnectEach2(opts.otherRefs ?? others) : "pgai mon instances delete the server's other databases (pgai mon instances list)";
33131
33480
  const reconnectOthers = `(and deploy ${others ? others.join(", ") : "them"} again with it)`;
33132
33481
  const noTlsWayOut = opts.agent ? `Pass its URL as database_url, or run pgai mon deploy in a terminal with PGAI_MON_PASSWORD set to its password. If nobody has it, in a terminal: ${disconnectOthers}, then pgai mon deploy <admin-url> --reset-password with PGAI_MON_PASSWORD set to a new one ${reconnectOthers}` : `Set PGAI_MON_PASSWORD to its password, or turn on TLS on the server (ssl = on) and put sslmode=require in the URL. If nobody has the password: ${disconnectOthers}, then re-run with --reset-password and PGAI_MON_PASSWORD set to a new one ${reconnectOthers}`;
33133
33482
  const reuse = me.mon_exists && !opts.resetPassword && !!opts.storedPassword && !(opts.agent ? "" : process.env.PGAI_MON_PASSWORD?.trim());
@@ -33255,7 +33604,16 @@ function grafanaOAuthUrl2(dashboardUrl) {
33255
33604
  return `${u.origin}/login/generic_oauth?redirectTo=${encodeURIComponent(`${u.pathname}${u.search}`)}`;
33256
33605
  }
33257
33606
  function platformDeps2(p) {
33258
- const rpc = (fn, body = {}) => callRpc({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl, fn, body, operation: fn.replace(/_/g, " "), debug: p.debug, orgScope: p.orgScope });
33607
+ const rpc = (fn, body = {}, timeoutMs) => callRpc({
33608
+ apiKey: p.apiKey,
33609
+ apiBaseUrl: p.apiBaseUrl,
33610
+ fn,
33611
+ body,
33612
+ operation: fn.replace(/_/g, " "),
33613
+ debug: p.debug,
33614
+ orgScope: p.orgScope,
33615
+ ...timeoutMs ? { timeoutMs, timeoutCeilingMs: timeoutMs } : {}
33616
+ });
33259
33617
  let orgAlias;
33260
33618
  let projects;
33261
33619
  const healthUrl = async (row) => {
@@ -33279,7 +33637,7 @@ function platformDeps2(p) {
33279
33637
  verifyTls: verifyCollectorTls,
33280
33638
  list: () => rpc("cloud_monitoring_list"),
33281
33639
  links: withLinks,
33282
- create: (body) => rpc("cloud_monitoring_connect", body),
33640
+ create: (body) => rpc("cloud_monitoring_connect", body, p.agent ? AGENT_CONNECT_TIMEOUT_MS2 : CONNECT_TIMEOUT_MS2),
33283
33641
  disconnect: (id) => rpc("cloud_monitoring_disconnect", { instance_id: id }),
33284
33642
  setVcpus: (id, vcpus) => rpc("cloud_monitoring_set_vcpus", { instance_id: id, vcpus }),
33285
33643
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
@@ -33293,6 +33651,7 @@ function platformDeps2(p) {
33293
33651
  supabaseStatus: (sessionId) => rpc("cloud_monitoring_supabase_status", { session_id: sessionId }),
33294
33652
  supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
33295
33653
  supabaseProjects: () => rpc("cloud_monitoring_supabase_projects", {}),
33654
+ deployOptions: (args) => rpc("monitoring_deploy_options", args),
33296
33655
  handoffUrl: async (provider) => {
33297
33656
  const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
33298
33657
  const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
@@ -33329,7 +33688,7 @@ async function callRpcRaw2(params) {
33329
33688
  console.error(`Debug: Request body: ${redactSecretsForLog(payload)}`);
33330
33689
  }
33331
33690
  let response;
33332
- const requestTimeout = requestTimeoutSignal(params.timeoutMs);
33691
+ const requestTimeout = requestTimeoutSignal(params.timeoutMs, params.timeoutCeilingMs);
33333
33692
  try {
33334
33693
  response = await fetch(url.toString(), {
33335
33694
  method: "POST",
@@ -33355,7 +33714,7 @@ async function callRpcRaw2(params) {
33355
33714
  ({ response, text } = await send(params.fallbackBody));
33356
33715
  }
33357
33716
  if (!response.ok) {
33358
- throw new HttpStatusError(formatHttpError(operation, response.status, text, response.statusText), response.status);
33717
+ throw new HttpStatusError(formatHttpError(operation, response.status, text, response.statusText), response.status, sqlstateOf(text));
33359
33718
  }
33360
33719
  try {
33361
33720
  return { data: JSON.parse(text), status: response.status };
@@ -35220,8 +35579,11 @@ function assertEncodedUserinfo2(url) {
35220
35579
  throw new Error("The database URL has an '@' after the host: percent-encode it as %40 (in the password, the database name or the query; also / as %2F, ? as %3F, # as %23 in the password).");
35221
35580
  }
35222
35581
  }
35223
- function sharedDeployOptions2(cmd, waitDefaultMinutes, nameHelp, locationHelp = "Hetzner location: fsn1, nbg1 or hel1 (default: any with capacity)") {
35224
- return cmd.argument("[database-url]", "the database: postgresql://user:password@host:5432/dbname").option("--db-url <url>", "the database URL (the same as the argument)").option("--name <name>", nameHelp).option("--location <location>", locationHelp).option("--wait <minutes>", "how long to wait for it to be ready (0 = do not wait)", String(waitDefaultMinutes)).option("--no-wait", "return once the deploy has started (the same as --wait 0)").option("-y, --yes", "never prompt: accept the price and every confirmation").option("--json", "JSON output: one result on stdout, progress on stderr (the default when stdout is not a terminal)").option("--debug", "print HTTP requests (secrets masked)");
35582
+ function sharedDeployOptions2(cmd, waitDefaultMinutes, nameHelp, locationHelp = "Hetzner location: fsn1, nbg1 or hel1 (default: any with capacity)", cloudHelp) {
35583
+ cmd = cmd.argument("[database-url]", "the database: postgresql://user:password@host:5432/dbname").option("--db-url <url>", "the database URL (the same as the argument)").option("--name <name>", nameHelp).option("--location <location>", locationHelp);
35584
+ if (cloudHelp)
35585
+ cmd = cmd.option("--cloud <cloud>", cloudHelp);
35586
+ return cmd.option("--wait <minutes>", "how long to wait for it to be ready (0 = do not wait)", String(waitDefaultMinutes)).option("--no-wait", "return once the deploy has started (the same as --wait 0)").option("-y, --yes", "never prompt: accept the price and every confirmation").option("--json", "JSON output: one result on stdout, progress on stderr (the default when stdout is not a terminal)").option("--debug", "print HTTP requests (secrets masked)");
35225
35587
  }
35226
35588
 
35227
35589
  // lib/promql.ts
@@ -44885,6 +45247,8 @@ function composeContentEqual(a, b) {
44885
45247
  async function refreshBundledComposeIfStale(projectDir, oldTag) {
44886
45248
  if (fs10.existsSync(path8.resolve(projectDir, ".git")))
44887
45249
  return false;
45250
+ if (process.env.PGAI_SKIP_COMPOSE_REFRESH === "1")
45251
+ return false;
44888
45252
  const composeFile = path8.resolve(projectDir, "docker-compose.yml");
44889
45253
  if (!fs10.existsSync(composeFile))
44890
45254
  return false;
@@ -47052,6 +47416,7 @@ Resume: pgai mon instances watch ${createdId}`);
47052
47416
  process.exit(130);
47053
47417
  };
47054
47418
  let requested = false;
47419
+ let looking = false;
47055
47420
  const onSigint = () => {
47056
47421
  if (createdId)
47057
47422
  return resume();
@@ -47063,7 +47428,7 @@ Quit. The monitoring box may exist: pgai mon instances list`);
47063
47428
  process.exit(130);
47064
47429
  }
47065
47430
  stopping = true;
47066
- const reply = requested ? "Stopping: the monitoring box is already requested; deploy stops watching when the request ends (Ctrl-C again to quit now)." : "Cancelling: nothing has been created yet (Ctrl-C again to quit now).";
47431
+ const reply = looking ? "Stopping: PostgresAI may still create the monitoring box; deploy stops at its next check (Ctrl-C again to quit now)." : requested ? "Stopping: the monitoring box is already requested; deploy stops watching when the request ends (Ctrl-C again to quit now)." : "Cancelling: nothing has been created yet (Ctrl-C again to quit now).";
47067
47432
  const view = steps.view();
47068
47433
  if (view)
47069
47434
  view.log(reply);
@@ -47140,10 +47505,23 @@ Projects in the Supabase organization "${org}":`));
47140
47505
  closeReadline();
47141
47506
  }
47142
47507
  } } : {},
47508
+ ...interactive(opts.json) ? { choosePlace: async (options, name) => {
47509
+ process.exitCode = 130;
47510
+ try {
47511
+ return await pickPlace(options, name, question, (line) => console.error(line));
47512
+ } finally {
47513
+ process.exitCode = undefined;
47514
+ closeReadline();
47515
+ }
47516
+ } } : {},
47143
47517
  ...interactive(opts.json) ? { openUrl: openInBrowser } : {},
47144
47518
  progress: (e) => {
47145
47519
  if (e.event === "provisioning")
47146
47520
  requested = true;
47521
+ if (e.message === STILL_CREATING2)
47522
+ looking = true;
47523
+ if (e.event === "box")
47524
+ looking = false;
47147
47525
  if (e.project)
47148
47526
  shownName = terminalText2(e.project);
47149
47527
  steps.progress(e);
@@ -47167,6 +47545,12 @@ Projects in the Supabase organization "${org}":`));
47167
47545
  return resume();
47168
47546
  const view = steps.view();
47169
47547
  if (view) {
47548
+ if (result.next === NOT_CONFIRMED2)
47549
+ view.setNote(`not confirmed after ${LOOKUP_MS2 / 60000} min`);
47550
+ else if (result.next === STOPPED_LOOKING2)
47551
+ view.setNote("stopped watching");
47552
+ else if (looking)
47553
+ view.setNote("");
47170
47554
  if (result.status === "ready")
47171
47555
  view.complete();
47172
47556
  else if (result.status !== "in_progress" && !result.next.startsWith(STILL_IN_PROGRESS2))
@@ -47184,7 +47568,7 @@ Projects in the Supabase organization "${org}":`));
47184
47568
  }
47185
47569
  }
47186
47570
  var mon = program2.command("mon").description("monitoring services management");
47187
- 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; 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", [
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", [
47188
47572
  "",
47189
47573
  "Steps (each skipped when already done; safe to re-run): sign in, prepare the database",
47190
47574
  "(an admin URL creates the postgres_ai_mon role; otherwise the SQL is printed), provision",
@@ -47192,6 +47576,17 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
47192
47576
  "your PostgresAI account (dashboard_url). The box runs its first checkup at first_checkup_eta",
47193
47577
  "at the earliest (3 minutes after it is ready), once every target has data (at most 30 minutes).",
47194
47578
  "",
47579
+ "Where the box runs: the platform decides, as the console does, and deploy prints it before the",
47580
+ 'price ("Monitoring box: AWS, us-east-2 (same region as your database)"). Without --cloud and',
47581
+ "--location: the database's cloud and region (a Supabase project's region, an RDS, Aurora, EC2,",
47582
+ "Neon or Supabase pooler host), else AWS us-east-1. --location is a region of that cloud; a cloud",
47583
+ "that is not available, or a location it does not have, is refused before anything is created.",
47584
+ 'Without --yes, deploy asks before it creates a box in PostgresAI Cloud, free or billed: "Deploy',
47585
+ '<db> here? [y]es / [c]hoose another location / [N]o" (with --cloud/--location: "Deploy <db> on',
47586
+ '<cloud>, <location>? [y/N]"). Not at a terminal (piped, --json, agents) it stops (exit 3) with the',
47587
+ 'place, the price and the choices ("choices" in the JSON result): re-run with --yes, and with',
47588
+ "--cloud/--location to pick another place.",
47589
+ "",
47195
47590
  "Network: the database must be reachable from this machine and from PostgresAI. Before provisioning,",
47196
47591
  "PostgresAI tests the connection from an unpublished address, so the port must accept connections",
47197
47592
  "from the internet; after it, the monitoring box connects from the IP shown on its Console page.",
@@ -47199,7 +47594,7 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
47199
47594
  "",
47200
47595
  "Billing is per Postgres cluster observed: another database in a cluster the organization already",
47201
47596
  'monitors is included. Once the URL is checked, deploy shows the price (or "free (N of M free slots)"). A billed',
47202
- "box is provisioned only when accepted: at the prompt, or with --yes. With no payment method",
47597
+ "box is provisioned only when accepted: at the prompt above, or with --yes. With no payment method",
47203
47598
  "it stops (exit 3) and names the console page to add one. --coupon applies a promotion code.",
47204
47599
  "",
47205
47600
  "Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API (the",
@@ -47236,6 +47631,7 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
47236
47631
  " pgai mon deploy --provider supabase",
47237
47632
  " pgai mon deploy --supabase-project <name|project-id> --yes --json",
47238
47633
  " pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres'",
47634
+ " pgai mon deploy '<url>' --cloud hetzner --location nbg1",
47239
47635
  " pgai mon deploy '<url>' --self-hosted"
47240
47636
  ].join(`
47241
47637
  `)).action((urlArg, opts, cmd) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postgresai",
3
- "version": "0.18.0-dev.12",
3
+ "version": "0.18.0-dev.14",
4
4
  "description": "postgres_ai CLI",
5
5
  "license": "Apache-2.0",
6
6
  "private": false,