postgresai 0.18.0-dev.11 → 0.18.0-dev.13

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.11",
13536
+ version: "0.18.0-dev.13",
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.11";
16896
+ var version = "0.18.0-dev.13";
16897
16897
  var package_default2 = {
16898
16898
  name: "postgresai",
16899
16899
  version,
@@ -22662,8 +22662,11 @@ function nameFromDatabase(url) {
22662
22662
  const slug = (db || "dblab").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48).replace(/-+$/, "");
22663
22663
  return slug.length >= 2 ? slug : `db-${slug || "x"}`.slice(0, 48);
22664
22664
  }
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)");
22665
+ function sharedDeployOptions(cmd, waitDefaultMinutes, nameHelp, locationHelp = "Hetzner location: fsn1, nbg1 or hel1 (default: any with capacity)", cloudHelp) {
22666
+ 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);
22667
+ if (cloudHelp)
22668
+ cmd = cmd.option("--cloud <cloud>", cloudHelp);
22669
+ 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
22670
  }
22668
22671
 
22669
22672
  // lib/joe.ts
@@ -22964,6 +22967,10 @@ function caNote(url) {
22964
22967
  return;
22965
22968
  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
22969
  }
22970
+ function chargeFailed(error, rerun, billingUrl, couponFlag = "--coupon") {
22971
+ 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}`;
22972
+ return `The first charge failed (${error}): the box is being removed and nothing is billed. ${fix}`;
22973
+ }
22967
22974
  function connectStatus(row, provider = row.provider, fresh = false) {
22968
22975
  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
22976
  const status = stateOf(row.status);
@@ -22971,7 +22978,7 @@ function connectStatus(row, provider = row.provider, fresh = false) {
22971
22978
  return {
22972
22979
  ...base,
22973
22980
  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.`
22981
+ next: `${chargeFailed(row.billing_error, "re-run pgai mon deploy")}.`
22975
22982
  };
22976
22983
  }
22977
22984
  if (status === "ready") {
@@ -22988,6 +22995,11 @@ function connectStatus(row, provider = row.provider, fresh = false) {
22988
22995
  return { ...base, status, next: `pgai mon instances delete ${row.id} --yes, then pgai mon deploy again` };
22989
22996
  return { ...base, status, next: `pgai mon instances watch ${row.id}` };
22990
22997
  }
22998
+ var ESCAPES = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?|\x1b[ -~]?/g;
22999
+ var terminalText = (text) => text.replace(ESCAPES, "").split(`
23000
+ `).map(stripControlsToSpace).join(`
23001
+ `);
23002
+ var cloudWord = (cloud) => ({ aws: "AWS", hetzner: "Hetzner" })[cloud] ?? cloud;
22991
23003
  var boxState = (row) => row.status === "launch_requested" && row.registered_at ? "registered" : row.status ?? "starting";
22992
23004
  function boxWords(state) {
22993
23005
  if (!state || state === "starting" || state === "launch_requested")
@@ -22996,7 +23008,7 @@ function boxWords(state) {
22996
23008
  return "installing monitoring";
22997
23009
  return monitoringStatus(state).replace("_", " ");
22998
23010
  }
22999
- async function billingFor(q, name, opts, deps, show) {
23011
+ async function billingFor(q, name, opts, deps, show, ask) {
23000
23012
  const billing = { price: priceText(q), requires_payment_method: q.requires_payment_method };
23001
23013
  if (opts.coupon) {
23002
23014
  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" };
@@ -23010,7 +23022,13 @@ async function billingFor(q, name, opts, deps, show) {
23010
23022
  if (q.requires_payment_method)
23011
23023
  return { billing, billingPage, billingUrl, accepted: false, stop: billingPage };
23012
23024
  show(billing.price);
23013
- if (q.billed && !opts.yes && !await deps.confirm(`Provision ${name}? (y/N): `)) {
23025
+ if (ask) {
23026
+ const d = await ask(billing.price);
23027
+ if (!d.go)
23028
+ return { billing, billingPage, billingUrl, accepted: false, stop: { ...billing, ...d.stop } };
23029
+ return { billing, billingPage, billingUrl, accepted: q.billed, placed: d.place };
23030
+ }
23031
+ if (q.billed && !opts.yes && !await deps.confirm(`Provision ${terminalText(name)}? (y/N): `)) {
23014
23032
  return stop(opts.agent ? `Call deploy_monitoring again with yes: true to accept ${billing.price}` : `Re-run with --yes to accept ${billing.price}`);
23015
23033
  }
23016
23034
  return { billing, billingPage, billingUrl, accepted: q.billed };
@@ -23030,9 +23048,20 @@ async function connect(url, opts, deps) {
23030
23048
  warned.add(message);
23031
23049
  progress(step, message);
23032
23050
  };
23033
- const provider = providerArg(opts.provider) ?? detectCloudProvider(url);
23051
+ const project = opts.supabaseProject?.trim();
23052
+ const provider = providerArg(opts.provider) ?? (!url && project ? "supabase" : detectCloudProvider(url));
23034
23053
  if (!PROVIDERS.includes(provider))
23035
23054
  throw new Error(`--provider must be one of: generic, ${PROVIDERS.join(", ")}`);
23055
+ if (project !== undefined && provider !== "supabase") {
23056
+ return { status: "action_required", provider, name: url ? databaseName2(url) : "", next: "--supabase-project applies to Supabase only: leave it out, or use --provider supabase" };
23057
+ }
23058
+ if (!url) {
23059
+ if (provider !== "supabase")
23060
+ return { status: "action_required", provider, name: "", next: "Pass the database URL: pgai mon deploy postgresql://user:password@host:5432/dbname (Supabase: --provider supabase)" };
23061
+ if (opts.selfHosted)
23062
+ return { status: "action_required", provider, name: "", next: "--self-hosted needs the database URL: pass the project's connection string" };
23063
+ return deploySupabaseProject(undefined, opts, deps, progress);
23064
+ }
23036
23065
  assertEncodedUserinfo(url);
23037
23066
  if (!opts.selfHosted && provider === "supabase")
23038
23067
  return deploySupabase(url, opts, deps, progress);
@@ -23089,6 +23118,7 @@ async function connect(url, opts, deps) {
23089
23118
  let billingPage;
23090
23119
  let accepted = false;
23091
23120
  let billingUrl;
23121
+ let place;
23092
23122
  let undoRole;
23093
23123
  const findOrg = async () => {
23094
23124
  try {
@@ -23183,6 +23213,9 @@ async function connect(url, opts, deps) {
23183
23213
  }
23184
23214
  return { status: "action_required", provider, name, ...refusal };
23185
23215
  }
23216
+ const where = { db_host: new URL(url).hostname };
23217
+ const placed = await placeBox(deps, opts, where, progress);
23218
+ place = placed?.place;
23186
23219
  let quote;
23187
23220
  try {
23188
23221
  quote = await deps.quote(opts.coupon, clusterOf(url));
@@ -23191,9 +23224,11 @@ async function connect(url, opts, deps) {
23191
23224
  return { status: "action_required", provider, name, next: notAdminNext };
23192
23225
  throw err;
23193
23226
  }
23194
- const b = await billingFor(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)));
23227
+ const b = await billingFor(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)), placed && ((price) => decide(placed, name, price, opts, deps, where, progress)));
23195
23228
  if (b.stop)
23196
- return { status: "action_required", provider, name, ...b.stop };
23229
+ return { status: "action_required", provider, name, ...place, ...b.stop };
23230
+ if (b.placed)
23231
+ place = b.placed.place;
23197
23232
  if (deps.aborted?.())
23198
23233
  throw new CancelledError;
23199
23234
  ({ billing, billingPage, billingUrl, accepted } = b);
@@ -23263,7 +23298,7 @@ async function connect(url, opts, deps) {
23263
23298
  ...opts.coupon ? { promo_code: opts.coupon } : {},
23264
23299
  ...accepted ? { accept_price: true } : {},
23265
23300
  ...opts.name ? { project_name: opts.name } : {},
23266
- ...opts.location ? { server_location: opts.location } : {},
23301
+ ...place ? { cloud: place.cloud, server_location: place.location } : opts.location ? { server_location: opts.location } : {},
23267
23302
  ...vcpus ? { vcpus } : {}
23268
23303
  }).catch(async (err) => {
23269
23304
  if (err instanceof HttpStatusError && err.status >= 400 && err.status < 500)
@@ -23303,7 +23338,65 @@ async function connect(url, opts, deps) {
23303
23338
  const made = prepared;
23304
23339
  undoRole = () => undo(made);
23305
23340
  }
23306
- return follow(row, { provider, name, fresh, billing, billingUrl, undoRole, note }, opts, deps, progress);
23341
+ return follow(row, { provider, name, fresh, billing, billingUrl, undoRole, note, place }, opts, deps, progress);
23342
+ }
23343
+ async function placeBox(deps, opts, where, progress) {
23344
+ if (!deps.deployOptions)
23345
+ return;
23346
+ const cloud = opts.cloud?.trim().toLowerCase() || undefined;
23347
+ const location = opts.location?.trim() || undefined;
23348
+ const flag = (f) => opts.agent ? f : `--${f}`;
23349
+ let options;
23350
+ try {
23351
+ options = await deps.deployOptions({ ...where, ...cloud ? { cloud } : {}, ...location ? { location } : {}, check_stock: true });
23352
+ } catch (err) {
23353
+ if (httpStatus(err) !== 404)
23354
+ throw err;
23355
+ if (cloud)
23356
+ throw new Error(`This PostgresAI platform does not take ${flag("cloud")} yet: re-run without it. Nothing was created.`);
23357
+ if (location && where.supabase_project_ids) {
23358
+ throw new Error(`This PostgresAI platform does not take ${flag("location")} for Supabase yet: re-run without it. Nothing was created.`);
23359
+ }
23360
+ return;
23361
+ }
23362
+ if (!options.choice) {
23363
+ const said = options.error?.detail ?? options.error?.message ?? "The platform did not say where the monitoring box can run.";
23364
+ const elsewhere = location ? options.clouds.find((c) => c.available && c.code !== cloud && options.locations[c.code]?.some((l) => l.code === location)) : undefined;
23365
+ const available = options.clouds.filter((c) => c.available).map((c) => c.code);
23366
+ 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(", ")}`}.` : "";
23367
+ throw new Error(`${said}${how} Nothing was created.`);
23368
+ }
23369
+ const c = options.choice;
23370
+ progress("preparing", `Monitoring box: ${c.cloud_label}, ${c.location} (${c.reason_text})`, { cloud: c.cloud, location: c.location, location_reason: c.reason });
23371
+ return { place: { cloud: c.cloud, location: c.location, location_reason: c.reason, location_reason_text: c.reason_text }, options };
23372
+ }
23373
+ async function decide(placed, name, price, opts, deps, where, progress) {
23374
+ if (opts.yes)
23375
+ return { go: true };
23376
+ const { place, options } = placed;
23377
+ const label = options.choice?.cloud_label ?? cloudWord(place.cloud);
23378
+ const explicit = !!(opts.cloud?.trim() || opts.location?.trim());
23379
+ const nothing = "Nothing was created";
23380
+ if (deps.choosePlace) {
23381
+ if (explicit) {
23382
+ 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}` } };
23383
+ }
23384
+ const answer = await deps.choosePlace(options, name);
23385
+ if (answer === true)
23386
+ return { go: true };
23387
+ if (answer === false)
23388
+ return { go: false, stop: { next: `${nothing}: re-run to deploy, with --cloud and --location to choose where` } };
23389
+ const summary = (_event, message, more) => progress("billing", message, more);
23390
+ const again = await placeBox(deps, { ...opts, cloud: answer.cloud, location: answer.location }, where, summary);
23391
+ if (!again)
23392
+ throw new Error(`The platform did not place the box on ${answer.cloud}, ${answer.location}. ${nothing}.`);
23393
+ summary("billing", `Next time, to skip this question: --cloud ${again.place.cloud} --location ${again.place.location} --yes`);
23394
+ return { go: true, place: again };
23395
+ }
23396
+ 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)]));
23397
+ const here = `${label}, ${place.location} (${place.location_reason_text})`;
23398
+ 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}.`;
23399
+ return { go: false, stop: { location_reason_text: place.location_reason_text, choices, next } };
23307
23400
  }
23308
23401
  var isSupabaseUrl = (link) => {
23309
23402
  try {
@@ -23319,29 +23412,25 @@ async function deploySupabase(url, opts, deps, progress) {
23319
23412
  const provider = "supabase";
23320
23413
  const ref = extractProjectRefFromUrl(url);
23321
23414
  if (!ref)
23322
- return { status: "action_required", provider, name: databaseName2(url), next: "Not a Supabase project URL: use the project's connection string (db.<project-ref>.supabase.co, or the pooler with user postgres.<project-ref>)" };
23415
+ return { status: "action_required", provider, name: databaseName2(url), next: "Not a Supabase project URL: use the project's connection string (db.<project-ref>.supabase.co, or the pooler with user postgres.<project-ref>), or pass --provider supabase without a URL to pick the project" };
23323
23416
  const db = decodeURIComponent(new URL(url).pathname.replace(/^\//, "")) || "postgres";
23324
- const project = `postgresql://db.${ref}.supabase.co:5432/${encodeURIComponent(db)}`;
23325
- const name = databaseName2(project);
23326
- const cluster = clusterOf(project);
23417
+ const name = databaseName2(supabaseProjectUrl(ref, db));
23327
23418
  const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
23328
23419
  if (db !== "postgres")
23329
23420
  return stop("PostgresAI monitors a Supabase project through its postgres database: use the URL of the postgres database");
23330
- if (opts.resetPassword)
23331
- return stop("--reset-password does not apply to Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API");
23332
- if (opts.location)
23333
- return stop("--location does not apply to Supabase yet (PostgresAI picks the box's location): re-run without it");
23334
- if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
23335
- return stop(`${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`);
23336
- }
23337
- const row = (await deps.list()).find((d) => !disconnecting(d.status) && d.cluster && serverOf(d.cluster) === cluster && (!d.database || d.database === "postgres"));
23421
+ const refused = supabaseOptionsRefused(opts);
23422
+ if (refused)
23423
+ return stop(refused);
23424
+ if (opts.supabaseProject?.trim())
23425
+ return deploySupabaseProject(ref, opts, deps, progress);
23426
+ const row = await boxOnProject(ref, deps);
23338
23427
  if (row) {
23339
23428
  const note = opts.name && row.name !== opts.name ? `; --name ignored: this database is already monitored as ${row.name}` : "";
23340
23429
  return follow(row, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
23341
23430
  }
23342
23431
  let started;
23343
23432
  try {
23344
- started = await deps.supabaseStart(project);
23433
+ started = await deps.supabaseStart(supabaseProjectUrl(ref));
23345
23434
  } catch (err) {
23346
23435
  if (err instanceof HttpStatusError && err.status === 403)
23347
23436
  return stop(notAdminNext);
@@ -23350,30 +23439,171 @@ async function deploySupabase(url, opts, deps, progress) {
23350
23439
  throw err;
23351
23440
  }
23352
23441
  if ("auth_url" in started) {
23353
- if (!isSupabaseUrl(started.auth_url))
23354
- return { status: "failed", provider, name, next: `The platform sent a Supabase consent link that is not ${SUPABASE_API_BASE}: not opened. Re-run pgai mon deploy later.` };
23355
- const approve = `Open ${started.auth_url} in a browser and approve PostgresAI's access to Supabase`;
23356
- if (opts.agent || opts.waitMs <= 0)
23357
- return stop(`${approve}, then ${opts.agent ? "call deploy_monitoring again" : "re-run"}`);
23358
- progress("preparing", `Connect Supabase to PostgresAI: approve access in the browser (open ${started.auth_url} if it did not open). Waiting...`, { auth_url: started.auth_url });
23359
- deps.openUrl?.(started.auth_url);
23360
- const expires = started.expires_at ? Date.parse(started.expires_at) : NaN;
23361
- for (const deadline = deps.now() + Math.min(opts.waitMs, OAUTH_WAIT_MS);; ) {
23362
- if (deps.aborted?.())
23363
- throw new CancelledError;
23364
- const s = await deps.supabaseStatus(started.session_id);
23365
- if (s.status === "connected")
23366
- break;
23367
- if (s.status === "error")
23368
- return stop(`Supabase did not connect (${s.error ?? "no reason given"}): re-run to try again`);
23369
- const now = deps.now();
23370
- if (now >= expires)
23371
- return stop("The Supabase consent link expired before it was approved: re-run pgai mon deploy for a new one");
23372
- if (now >= deadline)
23373
- return stop(`${approve}, then re-run`);
23374
- await deps.sleep(OAUTH_POLL_MS);
23375
- }
23442
+ const waited = await supabaseConsent(started, opts, deps, progress, stop);
23443
+ if (waited)
23444
+ return waited;
23376
23445
  }
23446
+ return supabaseBox(ref, name, opts, deps, progress, stop);
23447
+ }
23448
+ async function boxOnProject(ref, deps) {
23449
+ const cluster = clusterOf(supabaseProjectUrl(ref));
23450
+ return (await deps.list()).find((d) => !disconnecting(d.status) && d.cluster && serverOf(d.cluster) === cluster && (!d.database || d.database === "postgres"));
23451
+ }
23452
+ function supabaseProjectUrl(ref, db = "postgres") {
23453
+ return `postgresql://db.${ref}.supabase.co:5432/${encodeURIComponent(db)}`;
23454
+ }
23455
+ function supabaseOptionsRefused(opts) {
23456
+ if (opts.resetPassword)
23457
+ return "--reset-password does not apply to Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API";
23458
+ if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
23459
+ return `${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`;
23460
+ }
23461
+ return;
23462
+ }
23463
+ async function supabaseConsent(started, opts, deps, progress, stop) {
23464
+ if (!isSupabaseUrl(started.auth_url))
23465
+ return { ...stop(""), status: "failed", next: `The platform sent a Supabase consent link that is not ${SUPABASE_API_BASE}: not opened. Re-run pgai mon deploy later.` };
23466
+ const approve = `Open ${started.auth_url} in a browser and approve PostgresAI's access to Supabase`;
23467
+ if (opts.agent || opts.waitMs <= 0)
23468
+ return stop(`${approve}, then ${opts.agent ? "call deploy_monitoring again" : "re-run"}`);
23469
+ progress("preparing", `Connect Supabase to PostgresAI: approve access in the browser (open ${started.auth_url} if it did not open). Waiting...`, { auth_url: started.auth_url });
23470
+ deps.openUrl?.(started.auth_url);
23471
+ const expires = started.expires_at ? Date.parse(started.expires_at) : NaN;
23472
+ for (const deadline = deps.now() + Math.min(opts.waitMs, OAUTH_WAIT_MS);; ) {
23473
+ if (deps.aborted?.())
23474
+ throw new CancelledError;
23475
+ const s = await deps.supabaseStatus(started.session_id);
23476
+ if (s.status === "connected")
23477
+ return;
23478
+ if (s.status === "error")
23479
+ return stop(`Supabase did not connect: ${(s.error ?? "no reason given").replace(/\.$/, "")}. Re-run to try again`);
23480
+ const now = deps.now();
23481
+ if (now >= expires)
23482
+ return stop("The Supabase consent link expired before it was approved: re-run pgai mon deploy for a new one");
23483
+ if (now >= deadline)
23484
+ return stop(`${approve}, then re-run`);
23485
+ await deps.sleep(OAUTH_POLL_MS);
23486
+ }
23487
+ }
23488
+ function supabaseStatusWords(status) {
23489
+ if (status === "inactive" || status === "paused")
23490
+ return "paused";
23491
+ if (status === "coming_up")
23492
+ return "starting";
23493
+ if (status === "unknown")
23494
+ return "in an unknown state";
23495
+ return status.replace(/_/g, " ");
23496
+ }
23497
+ function matchSupabaseProject(projects, wanted) {
23498
+ const value = wanted.trim();
23499
+ const byRef = projects.find((p) => p.ref === value);
23500
+ if (byRef)
23501
+ return { project: byRef };
23502
+ const byName = projects.filter((p) => p.name.toLowerCase() === value.toLowerCase());
23503
+ if (byName.length === 1)
23504
+ return { project: byName[0] };
23505
+ if (byName.length > 1)
23506
+ return { ambiguous: byName };
23507
+ return { none: true };
23508
+ }
23509
+ async function deploySupabaseProject(urlRef, opts, deps, progress) {
23510
+ const provider = "supabase";
23511
+ let name = urlRef ? databaseName2(supabaseProjectUrl(urlRef)) : "";
23512
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
23513
+ const refused = supabaseOptionsRefused(opts);
23514
+ if (refused)
23515
+ return stop(refused);
23516
+ const urlHint = "pass the project's URL instead (pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres')";
23517
+ if (!deps.supabaseProjects)
23518
+ return stop(`Picking a Supabase project needs a newer pgai: ${urlHint}`);
23519
+ const listed = async () => {
23520
+ try {
23521
+ return await deps.supabaseProjects();
23522
+ } catch (err) {
23523
+ if (err instanceof HttpStatusError && err.status === 403)
23524
+ return stop(notAdminNext);
23525
+ if (err instanceof HttpStatusError && err.status === 404)
23526
+ return stop(`This PostgresAI API cannot list Supabase projects yet: ${urlHint}`);
23527
+ throw err;
23528
+ }
23529
+ };
23530
+ let list = await listed();
23531
+ if ("status" in list)
23532
+ return list;
23533
+ if (!list.connected) {
23534
+ const waited = await supabaseConsent(list, opts, deps, progress, stop);
23535
+ if (waited)
23536
+ return waited;
23537
+ list = await listed();
23538
+ if ("status" in list)
23539
+ return list;
23540
+ if (!list.connected)
23541
+ return stop("Supabase did not stay connected after the approval: re-run pgai mon deploy --provider supabase");
23542
+ }
23543
+ const org = list.supabase_org_name;
23544
+ const projects = list.projects;
23545
+ const shown = { supabase_org: org, projects };
23546
+ if (!list.synced && !projects.length)
23547
+ return stop("Supabase did not answer the project list: re-run in a minute");
23548
+ const stale = list.synced ? "" : " (Supabase did not answer just now: the list may be out of date)";
23549
+ const inOrg = `organization "${org}"`;
23550
+ const useFlag = "--supabase-project <name or project ID>";
23551
+ if (!projects.length)
23552
+ return stop(`There are no projects in the Supabase ${inOrg}: create one there, then re-run`, shown);
23553
+ const wanted = opts.supabaseProject?.trim();
23554
+ let picked;
23555
+ if (wanted) {
23556
+ const m = matchSupabaseProject(projects, wanted);
23557
+ if ("none" in m)
23558
+ return stop(`No Supabase project "${wanted}" in ${inOrg}: re-run with ${useFlag} of one of its projects`, shown);
23559
+ if ("ambiguous" in m)
23560
+ return stop(`Several projects in ${inOrg} are called "${wanted}": re-run with the project ID instead`, { supabase_org: org, projects: m.ambiguous });
23561
+ picked = m.project;
23562
+ } else {
23563
+ if (!projects.some((p) => p.selectable)) {
23564
+ return stop(projects.some((p) => p.monitored) ? `Every active project in ${inOrg} is already monitored: see pgai mon instances list (a paused project can be monitored once it is resumed in Supabase)` : `No active project in ${inOrg}: resume one in Supabase, then re-run`, shown);
23565
+ }
23566
+ const ask = !opts.agent && !opts.yes ? deps.chooseSupabaseProject : undefined;
23567
+ if (!ask)
23568
+ return stop(`Choose the Supabase project to monitor, then re-run with ${useFlag}${stale}`, shown);
23569
+ const ref = await ask(projects, org);
23570
+ if (deps.aborted?.())
23571
+ throw new CancelledError;
23572
+ if (!ref)
23573
+ return stop(`No project chosen: re-run and pick one, or pass ${useFlag}`, shown);
23574
+ picked = projects.find((p) => p.ref === ref);
23575
+ }
23576
+ if (!picked)
23577
+ return stop(`No project chosen: re-run and pick one, or pass ${useFlag}`, shown);
23578
+ if (urlRef && picked.ref !== urlRef) {
23579
+ const urlProject = projects.find((p) => p.ref === urlRef);
23580
+ return stop(`--supabase-project is ${picked.name}, but the database URL is for ${urlProject ? urlProject.name : `project ${urlRef}`}: pass only one of them`);
23581
+ }
23582
+ name = databaseName2(supabaseProjectUrl(picked.ref));
23583
+ if (picked.monitored) {
23584
+ const box = (await deps.list()).find((d) => d.id === picked.monitored.id);
23585
+ if (box && !disconnecting(box.status)) {
23586
+ const note = opts.name && box.name !== opts.name ? `; --name ignored: this database is already monitored as ${box.name}` : "";
23587
+ return follow(box, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
23588
+ }
23589
+ return stop(`${picked.name} is already monitored${picked.monitored.name ? ` as ${picked.monitored.name}` : ""}: see pgai mon instances list`);
23590
+ }
23591
+ if (picked.reason === "paused")
23592
+ return stop(`${picked.name} is paused: resume it in Supabase, then re-run`);
23593
+ if (!picked.selectable)
23594
+ return stop(`${picked.name} is not ready in Supabase (${supabaseStatusWords(picked.status)}): re-run when it is active`);
23595
+ const existing = await boxOnProject(picked.ref, deps);
23596
+ if (existing) {
23597
+ const note = opts.name && existing.name !== opts.name ? `; --name ignored: this database is already monitored as ${existing.name}` : "";
23598
+ return follow(existing, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
23599
+ }
23600
+ return supabaseBox(picked.ref, name, opts, deps, progress, stop, `${picked.name} (Supabase)`);
23601
+ }
23602
+ async function supabaseBox(ref, name, opts, deps, progress, stop, label) {
23603
+ const provider = "supabase";
23604
+ const where = { supabase_project_ids: [ref] };
23605
+ const placed = await placeBox(deps, opts, where, progress);
23606
+ let place = placed?.place;
23377
23607
  let quote;
23378
23608
  try {
23379
23609
  quote = await deps.quote(opts.coupon);
@@ -23382,18 +23612,21 @@ async function deploySupabase(url, opts, deps, progress) {
23382
23612
  return stop(notAdminNext);
23383
23613
  throw err;
23384
23614
  }
23385
- const b = await billingFor(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)));
23615
+ 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)));
23386
23616
  if (b.stop)
23387
- return { status: "action_required", provider, name, ...b.stop };
23617
+ return { status: "action_required", provider, name, ...place, ...b.stop };
23618
+ if (b.placed)
23619
+ place = b.placed.place;
23388
23620
  if (deps.aborted?.())
23389
23621
  throw new CancelledError;
23390
- progress("provisioning", `Provisioning monitoring for ${name}`);
23622
+ progress("provisioning", `Provisioning monitoring for ${label ?? name}`, label ? { project: label } : {});
23391
23623
  const created = await deps.supabaseConnect({
23392
23624
  project_ref: ref,
23393
23625
  ...opts.name ? { name: opts.name } : {},
23394
23626
  ...b.accepted ? { accept_price: true } : {},
23395
23627
  ...opts.coupon ? { promo_code: opts.coupon } : {},
23396
- ...opts.vcpus ? { vcpus: opts.vcpus } : {}
23628
+ ...opts.vcpus ? { vcpus: opts.vcpus } : {},
23629
+ ...place ? { cloud: place.cloud, location: place.location } : {}
23397
23630
  }).catch((err) => {
23398
23631
  if (err instanceof HttpStatusError && err.status === 402)
23399
23632
  return /declined/i.test(err.message) ? "declined" : "payment";
@@ -23416,11 +23649,12 @@ async function deploySupabase(url, opts, deps, progress) {
23416
23649
  const box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: false };
23417
23650
  if (deps.aborted?.())
23418
23651
  return { ...connectStatus(box, provider, true), ...b.billing };
23419
- return follow(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "" }, opts, deps, progress);
23652
+ return follow(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "", place }, opts, deps, progress);
23420
23653
  }
23421
23654
  var STILL_IN_PROGRESS = "Still in progress";
23422
23655
  async function follow(row, f, opts, deps, progress) {
23423
- const { provider, name, fresh, billing, billingUrl, undoRole, note } = f;
23656
+ const { provider, name, fresh, billingUrl, undoRole, note } = f;
23657
+ const billing = { ...f.billing, ...f.place };
23424
23658
  let shown;
23425
23659
  for (const deadline = deps.now() + opts.waitMs;; ) {
23426
23660
  if (row.billing_error && disconnecting(row.status)) {
@@ -23432,7 +23666,7 @@ async function follow(row, f, opts, deps, progress) {
23432
23666
  name,
23433
23667
  id: row.id,
23434
23668
  ...billing,
23435
- 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`
23669
+ next: chargeFailed(row.billing_error, "re-run", billingUrl, opts.agent ? "coupon" : "--coupon")
23436
23670
  };
23437
23671
  }
23438
23672
  const result = connectStatus(row, provider, fresh);
@@ -23749,6 +23983,8 @@ function platformDeps(p) {
23749
23983
  supabaseStart: (dbUrl) => rpc("cloud_monitoring_supabase_start", { db_url: dbUrl }),
23750
23984
  supabaseStatus: (sessionId) => rpc("cloud_monitoring_supabase_status", { session_id: sessionId }),
23751
23985
  supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
23986
+ supabaseProjects: () => rpc("cloud_monitoring_supabase_projects", {}),
23987
+ deployOptions: (args) => rpc("monitoring_deploy_options", args),
23752
23988
  handoffUrl: async (provider) => {
23753
23989
  const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
23754
23990
  const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
@@ -30446,6 +30682,8 @@ async function handleToolCall(req, rootOpts, extra) {
30446
30682
  yes: args.yes === true,
30447
30683
  vcpus: args.vcpus === undefined || args.vcpus === null ? undefined : vcpusArg(String(args.vcpus)),
30448
30684
  monitoringUser: args.monitoring_user === undefined || args.monitoring_user === null ? undefined : String(args.monitoring_user),
30685
+ cloud: args.cloud === undefined || args.cloud === null ? undefined : String(args.cloud),
30686
+ location: args.location === undefined || args.location === null ? undefined : String(args.location),
30449
30687
  waitMs: 0,
30450
30688
  agent: true
30451
30689
  }, {
@@ -31028,7 +31266,9 @@ async function startMcpServer(rootOpts, extra) {
31028
31266
  database_url: { type: "string", description: "postgresql:// URL with the password in it (admin, or the postgres_ai_mon role)" },
31029
31267
  provider: { type: "string", description: "generic (direct PostgreSQL URL; alias: self-managed) | clickhouse | rds | supabase (default: detected from the host)" },
31030
31268
  clickhouse_key: { type: "string", description: "ClickHouse Cloud API key as <key-id>:<key-secret> (Basic Service API Reader), for CPU, memory and disk" },
31031
- 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" },
31269
+ 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)" },
31270
+ 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" },
31271
+ location: { type: "string", description: "A location of that cloud, from the result's choices (default: the database's region, else the cloud's default)" },
31032
31272
  coupon: { type: "string", description: "Stripe promotion code for the organization's monitoring subscription (applies when it is first created)" },
31033
31273
  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" },
31034
31274
  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" },
@@ -32104,6 +32344,10 @@ function caNote2(url) {
32104
32344
  return;
32105
32345
  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)`;
32106
32346
  }
32347
+ function chargeFailed2(error, rerun, billingUrl, couponFlag = "--coupon") {
32348
+ 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}`;
32349
+ return `The first charge failed (${error}): the box is being removed and nothing is billed. ${fix}`;
32350
+ }
32107
32351
  function connectStatus2(row, provider = row.provider, fresh = false) {
32108
32352
  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 };
32109
32353
  const status = stateOf2(row.status);
@@ -32111,7 +32355,7 @@ function connectStatus2(row, provider = row.provider, fresh = false) {
32111
32355
  return {
32112
32356
  ...base,
32113
32357
  status: "action_required",
32114
- 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.`
32358
+ next: `${chargeFailed2(row.billing_error, "re-run pgai mon deploy")}.`
32115
32359
  };
32116
32360
  }
32117
32361
  if (status === "ready") {
@@ -32128,8 +32372,8 @@ function connectStatus2(row, provider = row.provider, fresh = false) {
32128
32372
  return { ...base, status, next: `pgai mon instances delete ${row.id} --yes, then pgai mon deploy again` };
32129
32373
  return { ...base, status, next: `pgai mon instances watch ${row.id}` };
32130
32374
  }
32131
- var ESCAPES = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?|\x1b[ -~]?/g;
32132
- var terminalText = (text) => text.replace(ESCAPES, "").split(`
32375
+ var ESCAPES2 = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?|\x1b[ -~]?/g;
32376
+ var terminalText2 = (text) => text.replace(ESCAPES2, "").split(`
32133
32377
  `).map(stripControlsToSpace).join(`
32134
32378
  `);
32135
32379
  function stepProgress(o) {
@@ -32140,7 +32384,7 @@ function stepProgress(o) {
32140
32384
  o.onId?.(e.id);
32141
32385
  if (o.json)
32142
32386
  return o.writeEvent(e);
32143
- e = { ...e, message: terminalText(e.message), ...e.state ? { state: terminalText(e.state) } : {} };
32387
+ e = { ...e, message: terminalText2(e.message), ...e.state ? { state: terminalText2(e.state) } : {} };
32144
32388
  if (!o.tty)
32145
32389
  return o.writeLine(progressText(e));
32146
32390
  if (e.event === "billing") {
@@ -32162,8 +32406,9 @@ function stepProgress(o) {
32162
32406
  return { progress, view: () => view };
32163
32407
  }
32164
32408
  function resultLines(r) {
32165
- return personLines(r).map(terminalText);
32409
+ return personLines(r).map(terminalText2);
32166
32410
  }
32411
+ var cloudWord2 = (cloud) => ({ aws: "AWS", hetzner: "Hetzner" })[cloud] ?? cloud;
32167
32412
  function personLines(r) {
32168
32413
  const who = r.name || "this database";
32169
32414
  const extra = (r.next ?? "").split("; ").slice(1).join("; ");
@@ -32175,6 +32420,7 @@ function personLines(r) {
32175
32420
  ...r.health_url ? [` Health Matrix: ${r.health_url}`] : [],
32176
32421
  ...r.dashboard_url ? [` Grafana: ${r.dashboard_url}`] : [],
32177
32422
  ...r.price ? [` Price: ${r.price}`] : [],
32423
+ ...r.cloud ? [` Runs on: ${cloudWord2(r.cloud)}, ${r.location}`] : [],
32178
32424
  ...!r.health_url && !r.dashboard_url && r.next && r.next !== "none" ? [`Next: ${r.next}`] : [],
32179
32425
  ...extra && (r.health_url || r.dashboard_url) ? [`Note: ${extra}`] : []
32180
32426
  ];
@@ -32184,7 +32430,9 @@ function personLines(r) {
32184
32430
  case "deleted":
32185
32431
  return [`Deleting the monitoring of ${who}.${billing ? ` Billing: ${billing}.` : ""}${r.next && r.next !== "none" ? ` ${r.next}` : ""}`];
32186
32432
  default:
32187
- return [r.next];
32433
+ if (r.projects?.length)
32434
+ return [r.next, ...supabaseProjectRows(r.projects)];
32435
+ return r.choices ? [r.next, ...Object.entries(r.choices).map(([cloud, codes]) => ` --cloud ${cloud} --location ${codes.join("|")}`)] : [r.next];
32188
32436
  }
32189
32437
  }
32190
32438
  function progressText(e) {
@@ -32204,7 +32452,7 @@ function boxWords2(state) {
32204
32452
  return "installing monitoring";
32205
32453
  return monitoringStatus(state).replace("_", " ");
32206
32454
  }
32207
- async function billingFor2(q, name, opts, deps, show) {
32455
+ async function billingFor2(q, name, opts, deps, show, ask) {
32208
32456
  const billing = { price: priceText2(q), requires_payment_method: q.requires_payment_method };
32209
32457
  if (opts.coupon) {
32210
32458
  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" };
@@ -32218,7 +32466,13 @@ async function billingFor2(q, name, opts, deps, show) {
32218
32466
  if (q.requires_payment_method)
32219
32467
  return { billing, billingPage, billingUrl, accepted: false, stop: billingPage };
32220
32468
  show(billing.price);
32221
- if (q.billed && !opts.yes && !await deps.confirm(`Provision ${name}? (y/N): `)) {
32469
+ if (ask) {
32470
+ const d = await ask(billing.price);
32471
+ if (!d.go)
32472
+ return { billing, billingPage, billingUrl, accepted: false, stop: { ...billing, ...d.stop } };
32473
+ return { billing, billingPage, billingUrl, accepted: q.billed, placed: d.place };
32474
+ }
32475
+ if (q.billed && !opts.yes && !await deps.confirm(`Provision ${terminalText2(name)}? (y/N): `)) {
32222
32476
  return stop(opts.agent ? `Call deploy_monitoring again with yes: true to accept ${billing.price}` : `Re-run with --yes to accept ${billing.price}`);
32223
32477
  }
32224
32478
  return { billing, billingPage, billingUrl, accepted: q.billed };
@@ -32238,9 +32492,20 @@ async function connect2(url, opts, deps) {
32238
32492
  warned.add(message);
32239
32493
  progress(step, message);
32240
32494
  };
32241
- const provider = providerArg2(opts.provider) ?? detectCloudProvider2(url);
32495
+ const project = opts.supabaseProject?.trim();
32496
+ const provider = providerArg2(opts.provider) ?? (!url && project ? "supabase" : detectCloudProvider2(url));
32242
32497
  if (!PROVIDERS2.includes(provider))
32243
32498
  throw new Error(`--provider must be one of: generic, ${PROVIDERS2.join(", ")}`);
32499
+ if (project !== undefined && provider !== "supabase") {
32500
+ return { status: "action_required", provider, name: url ? databaseName3(url) : "", next: "--supabase-project applies to Supabase only: leave it out, or use --provider supabase" };
32501
+ }
32502
+ if (!url) {
32503
+ if (provider !== "supabase")
32504
+ return { status: "action_required", provider, name: "", next: "Pass the database URL: pgai mon deploy postgresql://user:password@host:5432/dbname (Supabase: --provider supabase)" };
32505
+ if (opts.selfHosted)
32506
+ return { status: "action_required", provider, name: "", next: "--self-hosted needs the database URL: pass the project's connection string" };
32507
+ return deploySupabaseProject2(undefined, opts, deps, progress);
32508
+ }
32244
32509
  assertEncodedUserinfo(url);
32245
32510
  if (!opts.selfHosted && provider === "supabase")
32246
32511
  return deploySupabase2(url, opts, deps, progress);
@@ -32297,6 +32562,7 @@ async function connect2(url, opts, deps) {
32297
32562
  let billingPage;
32298
32563
  let accepted = false;
32299
32564
  let billingUrl;
32565
+ let place;
32300
32566
  let undoRole;
32301
32567
  const findOrg = async () => {
32302
32568
  try {
@@ -32391,6 +32657,9 @@ async function connect2(url, opts, deps) {
32391
32657
  }
32392
32658
  return { status: "action_required", provider, name, ...refusal };
32393
32659
  }
32660
+ const where = { db_host: new URL(url).hostname };
32661
+ const placed = await placeBox2(deps, opts, where, progress);
32662
+ place = placed?.place;
32394
32663
  let quote;
32395
32664
  try {
32396
32665
  quote = await deps.quote(opts.coupon, clusterOf2(url));
@@ -32399,9 +32668,11 @@ async function connect2(url, opts, deps) {
32399
32668
  return { status: "action_required", provider, name, next: notAdminNext };
32400
32669
  throw err;
32401
32670
  }
32402
- const b = await billingFor2(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)));
32671
+ const b = await billingFor2(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)), placed && ((price) => decide2(placed, name, price, opts, deps, where, progress)));
32403
32672
  if (b.stop)
32404
- return { status: "action_required", provider, name, ...b.stop };
32673
+ return { status: "action_required", provider, name, ...place, ...b.stop };
32674
+ if (b.placed)
32675
+ place = b.placed.place;
32405
32676
  if (deps.aborted?.())
32406
32677
  throw new CancelledError2;
32407
32678
  ({ billing, billingPage, billingUrl, accepted } = b);
@@ -32471,7 +32742,7 @@ async function connect2(url, opts, deps) {
32471
32742
  ...opts.coupon ? { promo_code: opts.coupon } : {},
32472
32743
  ...accepted ? { accept_price: true } : {},
32473
32744
  ...opts.name ? { project_name: opts.name } : {},
32474
- ...opts.location ? { server_location: opts.location } : {},
32745
+ ...place ? { cloud: place.cloud, server_location: place.location } : opts.location ? { server_location: opts.location } : {},
32475
32746
  ...vcpus ? { vcpus } : {}
32476
32747
  }).catch(async (err) => {
32477
32748
  if (err instanceof HttpStatusError && err.status >= 400 && err.status < 500)
@@ -32511,7 +32782,110 @@ async function connect2(url, opts, deps) {
32511
32782
  const made = prepared;
32512
32783
  undoRole = () => undo(made);
32513
32784
  }
32514
- return follow2(row, { provider, name, fresh, billing, billingUrl, undoRole, note }, opts, deps, progress);
32785
+ return follow2(row, { provider, name, fresh, billing, billingUrl, undoRole, note, place }, opts, deps, progress);
32786
+ }
32787
+ async function placeBox2(deps, opts, where, progress) {
32788
+ if (!deps.deployOptions)
32789
+ return;
32790
+ const cloud = opts.cloud?.trim().toLowerCase() || undefined;
32791
+ const location = opts.location?.trim() || undefined;
32792
+ const flag = (f) => opts.agent ? f : `--${f}`;
32793
+ let options;
32794
+ try {
32795
+ options = await deps.deployOptions({ ...where, ...cloud ? { cloud } : {}, ...location ? { location } : {}, check_stock: true });
32796
+ } catch (err) {
32797
+ if (httpStatus2(err) !== 404)
32798
+ throw err;
32799
+ if (cloud)
32800
+ throw new Error(`This PostgresAI platform does not take ${flag("cloud")} yet: re-run without it. Nothing was created.`);
32801
+ if (location && where.supabase_project_ids) {
32802
+ throw new Error(`This PostgresAI platform does not take ${flag("location")} for Supabase yet: re-run without it. Nothing was created.`);
32803
+ }
32804
+ return;
32805
+ }
32806
+ if (!options.choice) {
32807
+ const said = options.error?.detail ?? options.error?.message ?? "The platform did not say where the monitoring box can run.";
32808
+ const elsewhere = location ? options.clouds.find((c) => c.available && c.code !== cloud && options.locations[c.code]?.some((l) => l.code === location)) : undefined;
32809
+ const available = options.clouds.filter((c) => c.available).map((c) => c.code);
32810
+ 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(", ")}`}.` : "";
32811
+ throw new Error(`${said}${how} Nothing was created.`);
32812
+ }
32813
+ const c = options.choice;
32814
+ progress("preparing", `Monitoring box: ${c.cloud_label}, ${c.location} (${c.reason_text})`, { cloud: c.cloud, location: c.location, location_reason: c.reason });
32815
+ return { place: { cloud: c.cloud, location: c.location, location_reason: c.reason, location_reason_text: c.reason_text }, options };
32816
+ }
32817
+ async function pickPlace(options, name, ask, say) {
32818
+ const number = async (what, n) => {
32819
+ for (let tries = 0;tries < 3; tries++) {
32820
+ const answer = (await ask(`${what} (1-${n}, Enter to cancel): `)).trim();
32821
+ if (!answer)
32822
+ return;
32823
+ const i = Number(answer);
32824
+ if (Number.isInteger(i) && i >= 1 && i <= n)
32825
+ return i - 1;
32826
+ say(`Type a number from 1 to ${n}.`);
32827
+ }
32828
+ return;
32829
+ };
32830
+ for (let tries = 0;tries < 3; tries++) {
32831
+ const answer = (await ask(`Deploy ${terminalText2(name)} here? [y]es / [c]hoose another location / [N]o: `)).trim().toLowerCase();
32832
+ if (answer === "y" || answer === "yes")
32833
+ return true;
32834
+ if (!answer || answer === "n" || answer === "no")
32835
+ return false;
32836
+ if (answer !== "c" && answer !== "choose") {
32837
+ say("Type y, c or n.");
32838
+ continue;
32839
+ }
32840
+ const clouds = options.clouds.filter((c) => c.available && options.locations[c.code]?.length);
32841
+ say("Clouds:");
32842
+ clouds.forEach((c, i) => say(` ${i + 1}. ${c.label}`));
32843
+ const ci = await number("Cloud", clouds.length);
32844
+ if (ci === undefined)
32845
+ return false;
32846
+ const cloud = clouds[ci];
32847
+ const locations = options.locations[cloud.code];
32848
+ say(`Locations on ${cloud.label}:`);
32849
+ let part = "";
32850
+ locations.forEach((l, i) => {
32851
+ if (l.world_part !== part)
32852
+ say(` ${part = l.world_part}`);
32853
+ say(` ${i + 1}. ${l.code}${l.label ? ` ${terminalText2(l.label)}` : ""}`);
32854
+ });
32855
+ const li = await number("Location", locations.length);
32856
+ if (li === undefined)
32857
+ return false;
32858
+ return { cloud: cloud.code, location: locations[li].code };
32859
+ }
32860
+ return false;
32861
+ }
32862
+ async function decide2(placed, name, price, opts, deps, where, progress) {
32863
+ if (opts.yes)
32864
+ return { go: true };
32865
+ const { place, options } = placed;
32866
+ const label = options.choice?.cloud_label ?? cloudWord2(place.cloud);
32867
+ const explicit = !!(opts.cloud?.trim() || opts.location?.trim());
32868
+ const nothing = "Nothing was created";
32869
+ if (deps.choosePlace) {
32870
+ if (explicit) {
32871
+ 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}` } };
32872
+ }
32873
+ const answer = await deps.choosePlace(options, name);
32874
+ if (answer === true)
32875
+ return { go: true };
32876
+ if (answer === false)
32877
+ return { go: false, stop: { next: `${nothing}: re-run to deploy, with --cloud and --location to choose where` } };
32878
+ const summary = (_event, message, more) => progress("billing", message, more);
32879
+ const again = await placeBox2(deps, { ...opts, cloud: answer.cloud, location: answer.location }, where, summary);
32880
+ if (!again)
32881
+ throw new Error(`The platform did not place the box on ${answer.cloud}, ${answer.location}. ${nothing}.`);
32882
+ summary("billing", `Next time, to skip this question: --cloud ${again.place.cloud} --location ${again.place.location} --yes`);
32883
+ return { go: true, place: again };
32884
+ }
32885
+ 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)]));
32886
+ const here = `${label}, ${place.location} (${place.location_reason_text})`;
32887
+ 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}.`;
32888
+ return { go: false, stop: { location_reason_text: place.location_reason_text, choices, next } };
32515
32889
  }
32516
32890
  var isSupabaseUrl2 = (link) => {
32517
32891
  try {
@@ -32527,29 +32901,25 @@ async function deploySupabase2(url, opts, deps, progress) {
32527
32901
  const provider = "supabase";
32528
32902
  const ref = extractProjectRefFromUrl(url);
32529
32903
  if (!ref)
32530
- return { status: "action_required", provider, name: databaseName3(url), next: "Not a Supabase project URL: use the project's connection string (db.<project-ref>.supabase.co, or the pooler with user postgres.<project-ref>)" };
32904
+ return { status: "action_required", provider, name: databaseName3(url), next: "Not a Supabase project URL: use the project's connection string (db.<project-ref>.supabase.co, or the pooler with user postgres.<project-ref>), or pass --provider supabase without a URL to pick the project" };
32531
32905
  const db = decodeURIComponent(new URL(url).pathname.replace(/^\//, "")) || "postgres";
32532
- const project = `postgresql://db.${ref}.supabase.co:5432/${encodeURIComponent(db)}`;
32533
- const name = databaseName3(project);
32534
- const cluster = clusterOf2(project);
32906
+ const name = databaseName3(supabaseProjectUrl2(ref, db));
32535
32907
  const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
32536
32908
  if (db !== "postgres")
32537
32909
  return stop("PostgresAI monitors a Supabase project through its postgres database: use the URL of the postgres database");
32538
- if (opts.resetPassword)
32539
- return stop("--reset-password does not apply to Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API");
32540
- if (opts.location)
32541
- return stop("--location does not apply to Supabase yet (PostgresAI picks the box's location): re-run without it");
32542
- if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
32543
- return stop(`${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`);
32544
- }
32545
- const row = (await deps.list()).find((d) => !disconnecting2(d.status) && d.cluster && serverOf2(d.cluster) === cluster && (!d.database || d.database === "postgres"));
32910
+ const refused = supabaseOptionsRefused2(opts);
32911
+ if (refused)
32912
+ return stop(refused);
32913
+ if (opts.supabaseProject?.trim())
32914
+ return deploySupabaseProject2(ref, opts, deps, progress);
32915
+ const row = await boxOnProject2(ref, deps);
32546
32916
  if (row) {
32547
32917
  const note = opts.name && row.name !== opts.name ? `; --name ignored: this database is already monitored as ${row.name}` : "";
32548
32918
  return follow2(row, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
32549
32919
  }
32550
32920
  let started;
32551
32921
  try {
32552
- started = await deps.supabaseStart(project);
32922
+ started = await deps.supabaseStart(supabaseProjectUrl2(ref));
32553
32923
  } catch (err) {
32554
32924
  if (err instanceof HttpStatusError && err.status === 403)
32555
32925
  return stop(notAdminNext);
@@ -32558,30 +32928,191 @@ async function deploySupabase2(url, opts, deps, progress) {
32558
32928
  throw err;
32559
32929
  }
32560
32930
  if ("auth_url" in started) {
32561
- if (!isSupabaseUrl2(started.auth_url))
32562
- return { status: "failed", provider, name, next: `The platform sent a Supabase consent link that is not ${SUPABASE_API_BASE}: not opened. Re-run pgai mon deploy later.` };
32563
- const approve = `Open ${started.auth_url} in a browser and approve PostgresAI's access to Supabase`;
32564
- if (opts.agent || opts.waitMs <= 0)
32565
- return stop(`${approve}, then ${opts.agent ? "call deploy_monitoring again" : "re-run"}`);
32566
- progress("preparing", `Connect Supabase to PostgresAI: approve access in the browser (open ${started.auth_url} if it did not open). Waiting...`, { auth_url: started.auth_url });
32567
- deps.openUrl?.(started.auth_url);
32568
- const expires = started.expires_at ? Date.parse(started.expires_at) : NaN;
32569
- for (const deadline = deps.now() + Math.min(opts.waitMs, OAUTH_WAIT_MS2);; ) {
32570
- if (deps.aborted?.())
32571
- throw new CancelledError2;
32572
- const s = await deps.supabaseStatus(started.session_id);
32573
- if (s.status === "connected")
32574
- break;
32575
- if (s.status === "error")
32576
- return stop(`Supabase did not connect (${s.error ?? "no reason given"}): re-run to try again`);
32577
- const now = deps.now();
32578
- if (now >= expires)
32579
- return stop("The Supabase consent link expired before it was approved: re-run pgai mon deploy for a new one");
32580
- if (now >= deadline)
32581
- return stop(`${approve}, then re-run`);
32582
- await deps.sleep(OAUTH_POLL_MS2);
32583
- }
32931
+ const waited = await supabaseConsent2(started, opts, deps, progress, stop);
32932
+ if (waited)
32933
+ return waited;
32934
+ }
32935
+ return supabaseBox2(ref, name, opts, deps, progress, stop);
32936
+ }
32937
+ async function boxOnProject2(ref, deps) {
32938
+ const cluster = clusterOf2(supabaseProjectUrl2(ref));
32939
+ return (await deps.list()).find((d) => !disconnecting2(d.status) && d.cluster && serverOf2(d.cluster) === cluster && (!d.database || d.database === "postgres"));
32940
+ }
32941
+ function supabaseProjectUrl2(ref, db = "postgres") {
32942
+ return `postgresql://db.${ref}.supabase.co:5432/${encodeURIComponent(db)}`;
32943
+ }
32944
+ function supabaseOptionsRefused2(opts) {
32945
+ if (opts.resetPassword)
32946
+ return "--reset-password does not apply to Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API";
32947
+ if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
32948
+ return `${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`;
32584
32949
  }
32950
+ return;
32951
+ }
32952
+ async function supabaseConsent2(started, opts, deps, progress, stop) {
32953
+ if (!isSupabaseUrl2(started.auth_url))
32954
+ return { ...stop(""), status: "failed", next: `The platform sent a Supabase consent link that is not ${SUPABASE_API_BASE}: not opened. Re-run pgai mon deploy later.` };
32955
+ const approve = `Open ${started.auth_url} in a browser and approve PostgresAI's access to Supabase`;
32956
+ if (opts.agent || opts.waitMs <= 0)
32957
+ return stop(`${approve}, then ${opts.agent ? "call deploy_monitoring again" : "re-run"}`);
32958
+ progress("preparing", `Connect Supabase to PostgresAI: approve access in the browser (open ${started.auth_url} if it did not open). Waiting...`, { auth_url: started.auth_url });
32959
+ deps.openUrl?.(started.auth_url);
32960
+ const expires = started.expires_at ? Date.parse(started.expires_at) : NaN;
32961
+ for (const deadline = deps.now() + Math.min(opts.waitMs, OAUTH_WAIT_MS2);; ) {
32962
+ if (deps.aborted?.())
32963
+ throw new CancelledError2;
32964
+ const s = await deps.supabaseStatus(started.session_id);
32965
+ if (s.status === "connected")
32966
+ return;
32967
+ if (s.status === "error")
32968
+ return stop(`Supabase did not connect: ${(s.error ?? "no reason given").replace(/\.$/, "")}. Re-run to try again`);
32969
+ const now = deps.now();
32970
+ if (now >= expires)
32971
+ return stop("The Supabase consent link expired before it was approved: re-run pgai mon deploy for a new one");
32972
+ if (now >= deadline)
32973
+ return stop(`${approve}, then re-run`);
32974
+ await deps.sleep(OAUTH_POLL_MS2);
32975
+ }
32976
+ }
32977
+ function supabaseStatusWords2(status) {
32978
+ if (status === "inactive" || status === "paused")
32979
+ return "paused";
32980
+ if (status === "coming_up")
32981
+ return "starting";
32982
+ if (status === "unknown")
32983
+ return "in an unknown state";
32984
+ return status.replace(/_/g, " ");
32985
+ }
32986
+ function supabaseWhy(p) {
32987
+ if (p.reason === "monitored")
32988
+ return `already monitored${p.monitored?.name ? ` as ${p.monitored.name}` : ""}`;
32989
+ if (p.reason === "paused")
32990
+ return "paused";
32991
+ if (p.reason?.startsWith("not_ready:"))
32992
+ return `not ready (${supabaseStatusWords2(p.reason.slice("not_ready:".length))})`;
32993
+ return "";
32994
+ }
32995
+ function supabaseProjectRows(projects, numbered = false) {
32996
+ const nameW = Math.max(...projects.map((p) => p.name.length));
32997
+ const regionW = Math.max(...projects.map((p) => (p.region ?? "").length));
32998
+ const numW = String(projects.filter((p) => p.selectable).length).length;
32999
+ let n = 0;
33000
+ return projects.map((p) => {
33001
+ const why = supabaseWhy(p);
33002
+ const mark = numbered ? `${(p.selectable ? `${++n}.` : "-").padStart(numW + 1)} ` : "";
33003
+ return ` ${mark}${p.name.padEnd(nameW)} ${(p.region ?? "").padEnd(regionW)} ${p.ref}${why ? ` ${why}` : ""}`.trimEnd();
33004
+ });
33005
+ }
33006
+ function matchSupabaseProject2(projects, wanted) {
33007
+ const value = wanted.trim();
33008
+ const byRef = projects.find((p) => p.ref === value);
33009
+ if (byRef)
33010
+ return { project: byRef };
33011
+ const byName = projects.filter((p) => p.name.toLowerCase() === value.toLowerCase());
33012
+ if (byName.length === 1)
33013
+ return { project: byName[0] };
33014
+ if (byName.length > 1)
33015
+ return { ambiguous: byName };
33016
+ return { none: true };
33017
+ }
33018
+ async function deploySupabaseProject2(urlRef, opts, deps, progress) {
33019
+ const provider = "supabase";
33020
+ let name = urlRef ? databaseName3(supabaseProjectUrl2(urlRef)) : "";
33021
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
33022
+ const refused = supabaseOptionsRefused2(opts);
33023
+ if (refused)
33024
+ return stop(refused);
33025
+ const urlHint = "pass the project's URL instead (pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres')";
33026
+ if (!deps.supabaseProjects)
33027
+ return stop(`Picking a Supabase project needs a newer pgai: ${urlHint}`);
33028
+ const listed = async () => {
33029
+ try {
33030
+ return await deps.supabaseProjects();
33031
+ } catch (err) {
33032
+ if (err instanceof HttpStatusError && err.status === 403)
33033
+ return stop(notAdminNext);
33034
+ if (err instanceof HttpStatusError && err.status === 404)
33035
+ return stop(`This PostgresAI API cannot list Supabase projects yet: ${urlHint}`);
33036
+ throw err;
33037
+ }
33038
+ };
33039
+ let list = await listed();
33040
+ if ("status" in list)
33041
+ return list;
33042
+ if (!list.connected) {
33043
+ const waited = await supabaseConsent2(list, opts, deps, progress, stop);
33044
+ if (waited)
33045
+ return waited;
33046
+ list = await listed();
33047
+ if ("status" in list)
33048
+ return list;
33049
+ if (!list.connected)
33050
+ return stop("Supabase did not stay connected after the approval: re-run pgai mon deploy --provider supabase");
33051
+ }
33052
+ const org = list.supabase_org_name;
33053
+ const projects = list.projects;
33054
+ const shown = { supabase_org: org, projects };
33055
+ if (!list.synced && !projects.length)
33056
+ return stop("Supabase did not answer the project list: re-run in a minute");
33057
+ const stale = list.synced ? "" : " (Supabase did not answer just now: the list may be out of date)";
33058
+ const inOrg = `organization "${org}"`;
33059
+ const useFlag = "--supabase-project <name or project ID>";
33060
+ if (!projects.length)
33061
+ return stop(`There are no projects in the Supabase ${inOrg}: create one there, then re-run`, shown);
33062
+ const wanted = opts.supabaseProject?.trim();
33063
+ let picked;
33064
+ if (wanted) {
33065
+ const m = matchSupabaseProject2(projects, wanted);
33066
+ if ("none" in m)
33067
+ return stop(`No Supabase project "${wanted}" in ${inOrg}: re-run with ${useFlag} of one of its projects`, shown);
33068
+ if ("ambiguous" in m)
33069
+ return stop(`Several projects in ${inOrg} are called "${wanted}": re-run with the project ID instead`, { supabase_org: org, projects: m.ambiguous });
33070
+ picked = m.project;
33071
+ } else {
33072
+ if (!projects.some((p) => p.selectable)) {
33073
+ return stop(projects.some((p) => p.monitored) ? `Every active project in ${inOrg} is already monitored: see pgai mon instances list (a paused project can be monitored once it is resumed in Supabase)` : `No active project in ${inOrg}: resume one in Supabase, then re-run`, shown);
33074
+ }
33075
+ const ask = !opts.agent && !opts.yes ? deps.chooseSupabaseProject : undefined;
33076
+ if (!ask)
33077
+ return stop(`Choose the Supabase project to monitor, then re-run with ${useFlag}${stale}`, shown);
33078
+ const ref = await ask(projects, org);
33079
+ if (deps.aborted?.())
33080
+ throw new CancelledError2;
33081
+ if (!ref)
33082
+ return stop(`No project chosen: re-run and pick one, or pass ${useFlag}`, shown);
33083
+ picked = projects.find((p) => p.ref === ref);
33084
+ }
33085
+ if (!picked)
33086
+ return stop(`No project chosen: re-run and pick one, or pass ${useFlag}`, shown);
33087
+ if (urlRef && picked.ref !== urlRef) {
33088
+ const urlProject = projects.find((p) => p.ref === urlRef);
33089
+ return stop(`--supabase-project is ${picked.name}, but the database URL is for ${urlProject ? urlProject.name : `project ${urlRef}`}: pass only one of them`);
33090
+ }
33091
+ name = databaseName3(supabaseProjectUrl2(picked.ref));
33092
+ if (picked.monitored) {
33093
+ const box = (await deps.list()).find((d) => d.id === picked.monitored.id);
33094
+ if (box && !disconnecting2(box.status)) {
33095
+ const note = opts.name && box.name !== opts.name ? `; --name ignored: this database is already monitored as ${box.name}` : "";
33096
+ return follow2(box, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
33097
+ }
33098
+ return stop(`${picked.name} is already monitored${picked.monitored.name ? ` as ${picked.monitored.name}` : ""}: see pgai mon instances list`);
33099
+ }
33100
+ if (picked.reason === "paused")
33101
+ return stop(`${picked.name} is paused: resume it in Supabase, then re-run`);
33102
+ if (!picked.selectable)
33103
+ return stop(`${picked.name} is not ready in Supabase (${supabaseStatusWords2(picked.status)}): re-run when it is active`);
33104
+ const existing = await boxOnProject2(picked.ref, deps);
33105
+ if (existing) {
33106
+ const note = opts.name && existing.name !== opts.name ? `; --name ignored: this database is already monitored as ${existing.name}` : "";
33107
+ return follow2(existing, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
33108
+ }
33109
+ return supabaseBox2(picked.ref, name, opts, deps, progress, stop, `${picked.name} (Supabase)`);
33110
+ }
33111
+ async function supabaseBox2(ref, name, opts, deps, progress, stop, label) {
33112
+ const provider = "supabase";
33113
+ const where = { supabase_project_ids: [ref] };
33114
+ const placed = await placeBox2(deps, opts, where, progress);
33115
+ let place = placed?.place;
32585
33116
  let quote;
32586
33117
  try {
32587
33118
  quote = await deps.quote(opts.coupon);
@@ -32590,18 +33121,21 @@ async function deploySupabase2(url, opts, deps, progress) {
32590
33121
  return stop(notAdminNext);
32591
33122
  throw err;
32592
33123
  }
32593
- const b = await billingFor2(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)));
33124
+ 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)));
32594
33125
  if (b.stop)
32595
- return { status: "action_required", provider, name, ...b.stop };
33126
+ return { status: "action_required", provider, name, ...place, ...b.stop };
33127
+ if (b.placed)
33128
+ place = b.placed.place;
32596
33129
  if (deps.aborted?.())
32597
33130
  throw new CancelledError2;
32598
- progress("provisioning", `Provisioning monitoring for ${name}`);
33131
+ progress("provisioning", `Provisioning monitoring for ${label ?? name}`, label ? { project: label } : {});
32599
33132
  const created = await deps.supabaseConnect({
32600
33133
  project_ref: ref,
32601
33134
  ...opts.name ? { name: opts.name } : {},
32602
33135
  ...b.accepted ? { accept_price: true } : {},
32603
33136
  ...opts.coupon ? { promo_code: opts.coupon } : {},
32604
- ...opts.vcpus ? { vcpus: opts.vcpus } : {}
33137
+ ...opts.vcpus ? { vcpus: opts.vcpus } : {},
33138
+ ...place ? { cloud: place.cloud, location: place.location } : {}
32605
33139
  }).catch((err) => {
32606
33140
  if (err instanceof HttpStatusError && err.status === 402)
32607
33141
  return /declined/i.test(err.message) ? "declined" : "payment";
@@ -32624,11 +33158,12 @@ async function deploySupabase2(url, opts, deps, progress) {
32624
33158
  const box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: false };
32625
33159
  if (deps.aborted?.())
32626
33160
  return { ...connectStatus2(box, provider, true), ...b.billing };
32627
- return follow2(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "" }, opts, deps, progress);
33161
+ return follow2(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "", place }, opts, deps, progress);
32628
33162
  }
32629
33163
  var STILL_IN_PROGRESS2 = "Still in progress";
32630
33164
  async function follow2(row, f, opts, deps, progress) {
32631
- const { provider, name, fresh, billing, billingUrl, undoRole, note } = f;
33165
+ const { provider, name, fresh, billingUrl, undoRole, note } = f;
33166
+ const billing = { ...f.billing, ...f.place };
32632
33167
  let shown;
32633
33168
  for (const deadline = deps.now() + opts.waitMs;; ) {
32634
33169
  if (row.billing_error && disconnecting2(row.status)) {
@@ -32640,7 +33175,7 @@ async function follow2(row, f, opts, deps, progress) {
32640
33175
  name,
32641
33176
  id: row.id,
32642
33177
  ...billing,
32643
- 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`
33178
+ next: chargeFailed2(row.billing_error, "re-run", billingUrl, opts.agent ? "coupon" : "--coupon")
32644
33179
  };
32645
33180
  }
32646
33181
  const result = connectStatus2(row, provider, fresh);
@@ -32973,6 +33508,8 @@ function platformDeps2(p) {
32973
33508
  supabaseStart: (dbUrl) => rpc("cloud_monitoring_supabase_start", { db_url: dbUrl }),
32974
33509
  supabaseStatus: (sessionId) => rpc("cloud_monitoring_supabase_status", { session_id: sessionId }),
32975
33510
  supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
33511
+ supabaseProjects: () => rpc("cloud_monitoring_supabase_projects", {}),
33512
+ deployOptions: (args) => rpc("monitoring_deploy_options", args),
32976
33513
  handoffUrl: async (provider) => {
32977
33514
  const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
32978
33515
  const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
@@ -34900,8 +35437,11 @@ function assertEncodedUserinfo2(url) {
34900
35437
  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).");
34901
35438
  }
34902
35439
  }
34903
- function sharedDeployOptions2(cmd, waitDefaultMinutes, nameHelp, locationHelp = "Hetzner location: fsn1, nbg1 or hel1 (default: any with capacity)") {
34904
- 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)");
35440
+ function sharedDeployOptions2(cmd, waitDefaultMinutes, nameHelp, locationHelp = "Hetzner location: fsn1, nbg1 or hel1 (default: any with capacity)", cloudHelp) {
35441
+ 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);
35442
+ if (cloudHelp)
35443
+ cmd = cmd.option("--cloud <cloud>", cloudHelp);
35444
+ 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)");
34905
35445
  }
34906
35446
 
34907
35447
  // lib/promql.ts
@@ -46669,25 +47209,28 @@ Resume: ${resume}`);
46669
47209
  return () => process.removeListener("SIGINT", onSigint);
46670
47210
  }
46671
47211
  async function runConnect(urlArg, opts) {
46672
- let url;
46673
- try {
46674
- url = databaseUrlArg2(urlArg, opts.dbUrl, "pgai mon deploy");
46675
- } catch (err) {
46676
- return optionError({ status: "failed", provider: "self-managed", name: "", next: errorText2(err) }, opts.json);
47212
+ const explicit = providerArg2(opts.provider);
47213
+ const projectMode = !urlArg?.trim() && !opts.dbUrl?.trim() && (explicit === "supabase" || !explicit && !!opts.supabaseProject?.trim());
47214
+ let url = "";
47215
+ if (!projectMode) {
47216
+ try {
47217
+ url = databaseUrlArg2(urlArg, opts.dbUrl, "pgai mon deploy");
47218
+ } catch (err) {
47219
+ return optionError({ status: "failed", provider: "self-managed", name: "", next: errorText2(err) }, opts.json);
47220
+ }
46677
47221
  }
46678
47222
  const json = jsonOutput3(opts.json);
46679
- const name = (() => {
47223
+ const name = projectMode ? "" : (() => {
46680
47224
  try {
46681
47225
  return databaseName3(url);
46682
47226
  } catch {
46683
47227
  return "";
46684
47228
  }
46685
47229
  })();
46686
- if (!name || !/^postgres(ql)?:\/\//.test(url)) {
47230
+ if (!projectMode && (!name || !/^postgres(ql)?:\/\//.test(url))) {
46687
47231
  return optionError({ status: "failed", provider: "self-managed", name, next: "Pass a URL: pgai mon deploy postgresql://user:password@host:5432/dbname" }, opts.json);
46688
47232
  }
46689
- const explicit = providerArg2(opts.provider);
46690
- const provider = PROVIDERS2.find((p) => p === explicit) ?? detectCloudProvider2(url);
47233
+ const provider = projectMode ? "supabase" : PROVIDERS2.find((p) => p === explicit) ?? detectCloudProvider2(url);
46691
47234
  let minutes;
46692
47235
  try {
46693
47236
  minutes = waitMinutes2(opts.wait, 20);
@@ -46706,13 +47249,14 @@ async function runConnect(urlArg, opts) {
46706
47249
  return emitConnect({ status: "action_required", provider, name, next: "Sign in: pgai auth login (agents: set PGAI_API_KEY), then re-run" }, opts.json, true);
46707
47250
  }
46708
47251
  const api = cloudApi(opts.debug);
47252
+ let shownName = name;
46709
47253
  const tty = !json && !!process.stderr.isTTY && !process.env.CI && process.env.TERM !== "dumb";
46710
47254
  let createdId;
46711
47255
  let stopping = false;
46712
47256
  const steps = stepProgress({
46713
47257
  json,
46714
47258
  tty,
46715
- makeView: () => new StepView2(`Deploying monitoring for ${name}`, monitoringSteps(provider), true),
47259
+ makeView: () => new StepView2(`Deploying monitoring for ${shownName || "the Supabase project"}`, monitoringSteps(provider), true),
46716
47260
  writeLine: (line) => console.error(line),
46717
47261
  writeEvent: writeEvent2,
46718
47262
  onId: (id) => {
@@ -46791,10 +47335,46 @@ ${reply}`);
46791
47335
  closeReadline();
46792
47336
  }
46793
47337
  },
47338
+ ...interactive(opts.json) ? { chooseSupabaseProject: async (projects, org) => {
47339
+ const selectable = projects.filter((x) => x.selectable);
47340
+ console.error(terminalText2(`
47341
+ Projects in the Supabase organization "${org}":`));
47342
+ for (const line of supabaseProjectRows(projects, true))
47343
+ console.error(terminalText2(line));
47344
+ if (!selectable.length)
47345
+ return;
47346
+ process.exitCode = 130;
47347
+ try {
47348
+ for (let tries = 0;tries < 3; tries++) {
47349
+ const answer = (await question(`Project to monitor (1-${selectable.length}, Enter to cancel): `)).trim();
47350
+ if (!answer)
47351
+ return;
47352
+ const i = Number(answer);
47353
+ if (Number.isInteger(i) && i >= 1 && i <= selectable.length)
47354
+ return selectable[i - 1].ref;
47355
+ console.error(`Type a number from 1 to ${selectable.length}.`);
47356
+ }
47357
+ return;
47358
+ } finally {
47359
+ process.exitCode = undefined;
47360
+ closeReadline();
47361
+ }
47362
+ } } : {},
47363
+ ...interactive(opts.json) ? { choosePlace: async (options, name) => {
47364
+ process.exitCode = 130;
47365
+ try {
47366
+ return await pickPlace(options, name, question, (line) => console.error(line));
47367
+ } finally {
47368
+ process.exitCode = undefined;
47369
+ closeReadline();
47370
+ }
47371
+ } } : {},
46794
47372
  ...interactive(opts.json) ? { openUrl: openInBrowser } : {},
46795
47373
  progress: (e) => {
46796
47374
  if (e.event === "provisioning")
46797
47375
  requested = true;
47376
+ if (e.project)
47377
+ shownName = terminalText2(e.project);
46798
47378
  steps.progress(e);
46799
47379
  },
46800
47380
  aborted: () => stopping
@@ -46833,7 +47413,7 @@ ${reply}`);
46833
47413
  }
46834
47414
  }
46835
47415
  var mon = program2.command("mon").description("monitoring services management");
46836
- sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (default: host[:port]/database)").description("deploy PostgresAI Cloud monitoring for a database: prepare it, provision the monitoring box, print its Health Matrix and dashboard").option("--provider <provider>", "generic (direct PostgreSQL URL; alias: self-managed) | clickhouse | rds | supabase (default: detected from the host)").option("--clickhouse-key <id:secret>", "ClickHouse Cloud API key (Basic Service API Reader) for CPU, memory and disk; or CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET").option("--self-hosted", "run the monitoring stack on this machine (mon local-install) instead of PostgresAI Cloud").option("--reset-password", "the monitoring role exists and its password is lost: set a new one (admin URL; refused while another database on the server is monitored)").option("--monitoring-user <name>", "monitoring role to create or use", DEFAULT_MONITORING_USER2).option("--coupon <code>", "promotion code for the organization's monitoring subscription (applies when it is first created)").option("--vcpus <n>", "vCPUs of the database server; without it there is no AAS (database load) data (asked at a terminal)").addHelpText("after", [
47416
+ 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", [
46837
47417
  "",
46838
47418
  "Steps (each skipped when already done; safe to re-run): sign in, prepare the database",
46839
47419
  "(an admin URL creates the postgres_ai_mon role; otherwise the SQL is printed), provision",
@@ -46841,6 +47421,17 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
46841
47421
  "your PostgresAI account (dashboard_url). The box runs its first checkup at first_checkup_eta",
46842
47422
  "at the earliest (3 minutes after it is ready), once every target has data (at most 30 minutes).",
46843
47423
  "",
47424
+ "Where the box runs: the platform decides, as the console does, and deploy prints it before the",
47425
+ 'price ("Monitoring box: AWS, us-east-2 (same region as your database)"). Without --cloud and',
47426
+ "--location: the database's cloud and region (a Supabase project's region, an RDS, Aurora, EC2,",
47427
+ "Neon or Supabase pooler host), else AWS us-east-1. --location is a region of that cloud; a cloud",
47428
+ "that is not available, or a location it does not have, is refused before anything is created.",
47429
+ 'Without --yes, deploy asks before it creates a box in PostgresAI Cloud, free or billed: "Deploy',
47430
+ '<db> here? [y]es / [c]hoose another location / [N]o" (with --cloud/--location: "Deploy <db> on',
47431
+ '<cloud>, <location>? [y/N]"). Not at a terminal (piped, --json, agents) it stops (exit 3) with the',
47432
+ 'place, the price and the choices ("choices" in the JSON result): re-run with --yes, and with',
47433
+ "--cloud/--location to pick another place.",
47434
+ "",
46844
47435
  "Network: the database must be reachable from this machine and from PostgresAI. Before provisioning,",
46845
47436
  "PostgresAI tests the connection from an unpublished address, so the port must accept connections",
46846
47437
  "from the internet; after it, the monitoring box connects from the IP shown on its Console page.",
@@ -46848,7 +47439,7 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
46848
47439
  "",
46849
47440
  "Billing is per Postgres cluster observed: another database in a cluster the organization already",
46850
47441
  'monitors is included. Once the URL is checked, deploy shows the price (or "free (N of M free slots)"). A billed',
46851
- "box is provisioned only when accepted: at the prompt, or with --yes. With no payment method",
47442
+ "box is provisioned only when accepted: at the prompt above, or with --yes. With no payment method",
46852
47443
  "it stops (exit 3) and names the console page to add one. --coupon applies a promotion code.",
46853
47444
  "",
46854
47445
  "Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API (the",
@@ -46856,6 +47447,11 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
46856
47447
  "Supabase: deploy opens the consent page in the browser (the link is printed too, to open",
46857
47448
  'it elsewhere; "auth_url" in the JSON event) and waits for the approval, up to 10 minutes.',
46858
47449
  'With --wait 0, and for agents, it stops there (exit 3) with the link in "next".',
47450
+ "No URL needed: pgai mon deploy --provider supabase lists the projects of the connected",
47451
+ "Supabase organization to pick one at a terminal; --supabase-project <name|project-id> picks it",
47452
+ "for agents and scripts. Without either, and not at a terminal, it stops (exit 3) with the list",
47453
+ `("projects" in the JSON result). Paused and not-ready projects are listed but can't be`,
47454
+ "picked; an already-monitored one returns its monitoring.",
46859
47455
  "",
46860
47456
  "Exit codes: 0 ready (or in progress with --no-wait), 1 failed, 3 action required (see",
46861
47457
  '"next"), also when the wait ends before the box is ready.',
@@ -46877,12 +47473,17 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
46877
47473
  "Examples:",
46878
47474
  " pgai mon deploy 'postgresql://postgres:<password>@<host>.pg.clickhouse.cloud:5432/postgres?sslmode=require'",
46879
47475
  " CLICKHOUSE_KEY_ID=... CLICKHOUSE_KEY_SECRET=... pgai mon deploy '<url>'",
47476
+ " pgai mon deploy --provider supabase",
47477
+ " pgai mon deploy --supabase-project <name|project-id> --yes --json",
46880
47478
  " pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres'",
47479
+ " pgai mon deploy '<url>' --cloud hetzner --location nbg1",
46881
47480
  " pgai mon deploy '<url>' --self-hosted"
46882
47481
  ].join(`
46883
47482
  `)).action((urlArg, opts, cmd) => {
46884
- if (!urlArg?.trim() && !opts.dbUrl?.trim())
46885
- return cmd.error("error: missing required argument 'database-url'");
47483
+ const supabase = providerArg2(opts.provider) === "supabase" || !opts.provider && !!opts.supabaseProject?.trim();
47484
+ if (!urlArg?.trim() && !opts.dbUrl?.trim() && !supabase) {
47485
+ return cmd.error("error: missing required argument 'database-url' (or --provider supabase to pick a Supabase project)");
47486
+ }
46886
47487
  return runConnect(urlArg, opts);
46887
47488
  });
46888
47489
  var interactive = (json) => !!process.stdin.isTTY && !!process.stdout.isTTY && !json;