postgresai 0.18.0-dev.10 → 0.18.0-dev.12

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.10",
13536
+ version: "0.18.0-dev.12",
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.10";
16896
+ var version = "0.18.0-dev.12";
16897
16897
  var package_default2 = {
16898
16898
  name: "postgresai",
16899
16899
  version,
@@ -21927,7 +21927,19 @@ function isSslNegotiationError(err) {
21927
21927
  }
21928
21928
  return false;
21929
21929
  }
21930
- async function connectWithSslFallback(ClientClass, adminConn, verbose) {
21930
+ function effectiveConfig(config) {
21931
+ const host = config.host ?? process.env.PGHOST;
21932
+ if (!config.connectionString)
21933
+ return { ssl: config.ssl, host };
21934
+ try {
21935
+ const parsed = parse(config.connectionString);
21936
+ const ssl = parsed.ssl === "no-verify" ? { rejectUnauthorized: false } : parsed.ssl;
21937
+ return { ssl: "ssl" in parsed ? ssl : config.ssl, host: parsed.host || host };
21938
+ } catch {
21939
+ return { ssl: config.ssl, host };
21940
+ }
21941
+ }
21942
+ async function connectWithSslFallback(ClientClass, adminConn, verbose, warn = (message) => console.error(message)) {
21931
21943
  const tryConnect = async (config) => {
21932
21944
  const client = new ClientClass({ ...config, connectionTimeoutMillis: 1e4 });
21933
21945
  await client.connect();
@@ -21935,13 +21947,20 @@ async function connectWithSslFallback(ClientClass, adminConn, verbose) {
21935
21947
  await client.query("SET statement_timeout = '30s'");
21936
21948
  return client;
21937
21949
  };
21950
+ const { ssl, host } = effectiveConfig(adminConn.clientConfig);
21951
+ const socket = !!host?.startsWith("/");
21952
+ if (!socket && !ssl) {
21953
+ warn("Warning: this database connection uses plaintext, without TLS.");
21954
+ } else if (!socket && typeof ssl === "object" && ssl.rejectUnauthorized === false) {
21955
+ warn("Warning: the database server certificate is not verified" + (adminConn.sslFallbackEnabled ? " and this connection may fall back to plaintext" : "") + ". Use sslmode=verify-full with a trusted CA to authenticate the server.");
21956
+ }
21938
21957
  if (!adminConn.sslFallbackEnabled) {
21939
21958
  const client = await tryConnect(adminConn.clientConfig);
21940
- return { client, usedSsl: !!adminConn.clientConfig.ssl };
21959
+ return { client, usedSsl: !!ssl };
21941
21960
  }
21942
21961
  try {
21943
21962
  const client = await tryConnect(adminConn.clientConfig);
21944
- return { client, usedSsl: true };
21963
+ return { client, usedSsl: !!ssl };
21945
21964
  } catch (sslErr) {
21946
21965
  if (!isSslNegotiationError(sslErr)) {
21947
21966
  throw sslErr;
@@ -21950,9 +21969,12 @@ async function connectWithSslFallback(ClientClass, adminConn, verbose) {
21950
21969
  console.error("SSL connection failed, retrying without SSL...");
21951
21970
  }
21952
21971
  const noSslConfig = { ...adminConn.clientConfig, ssl: false };
21972
+ const retrySsl = effectiveConfig(noSslConfig).ssl;
21953
21973
  try {
21954
21974
  const client = await tryConnect(noSslConfig);
21955
- return { client, usedSsl: false };
21975
+ if (!retrySsl && !socket)
21976
+ warn("Warning: connected to the database without TLS after SSL negotiation failed.");
21977
+ return { client, usedSsl: !!retrySsl };
21956
21978
  } catch (noSslErr) {
21957
21979
  if (isSslNegotiationError(noSslErr)) {
21958
21980
  const msg = noSslErr?.message || "";
@@ -22000,7 +22022,15 @@ function quoteLiteral(value) {
22000
22022
  if (value.includes("\x00")) {
22001
22023
  throw new Error("Literal cannot contain null bytes");
22002
22024
  }
22003
- return `'${value.replace(/'/g, "''")}'`;
22025
+ const escapedQuotes = value.replace(/'/g, "''");
22026
+ return value.includes("\\") ? `E'${escapedQuotes.replace(/\\/g, "\\\\")}'` : `'${escapedQuotes}'`;
22027
+ }
22028
+ function safeDoDelimiter(...values) {
22029
+ for (let n = 0;; n++) {
22030
+ const tag = `$pgai_do_${n}$`;
22031
+ if (values.every((value) => !value.includes(tag)))
22032
+ return tag;
22033
+ }
22004
22034
  }
22005
22035
  function redactPasswordsInSql(sql) {
22006
22036
  return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
@@ -22242,14 +22272,16 @@ async function buildInitPlan(params) {
22242
22272
  const iterations = Math.max(SCRAM_DEFAULT_ITERATIONS, serverIterations);
22243
22273
  const qPwVerifier = quoteLiteral(scramSha256Verifier(params.monitoringPassword, { iterations }));
22244
22274
  const qRoleNameLit = quoteLiteral(monitoringUser);
22275
+ const doQuote = safeDoDelimiter(qRole, qDb, qRoleNameLit, qPwVerifier);
22245
22276
  const steps = [];
22246
22277
  const vars = {
22247
22278
  ROLE_IDENT: qRole,
22248
22279
  DB_IDENT: qDb,
22249
- ROLE_LITERAL: qRoleNameLit
22280
+ ROLE_LITERAL: qRoleNameLit,
22281
+ DO_QUOTE: doQuote
22250
22282
  };
22251
22283
  if (!SKIP_ROLE_CREATION_PROVIDERS.includes(provider)) {
22252
- const roleStmt = `do $$ begin
22284
+ const roleStmt = `do ${doQuote} begin
22253
22285
  if not exists (select 1 from pg_catalog.pg_roles where rolname = ${qRoleNameLit}) then
22254
22286
  begin
22255
22287
  create user ${qRole} with password ${qPwVerifier};
@@ -22258,7 +22290,7 @@ async function buildInitPlan(params) {
22258
22290
  end;
22259
22291
  end if;${params.keepExistingPassword ? "" : `
22260
22292
  alter user ${qRole} with password ${qPwVerifier};`}
22261
- end $$;`;
22293
+ end ${doQuote};`;
22262
22294
  const roleSql = applyTemplate(loadSqlTemplate("01.role.sql"), { ...vars, ROLE_STMT: roleStmt });
22263
22295
  steps.push({ name: "01.role", sql: roleSql });
22264
22296
  }
@@ -22467,8 +22499,11 @@ async function verifyInitSetup(params) {
22467
22499
  missingRequired.push(problem);
22468
22500
  }
22469
22501
  }
22470
- const tableDescribeFnRes = await params.client.query("select has_function_privilege($1, 'postgres_ai.table_describe(text)', 'EXECUTE') as ok", [role]);
22471
- if (!tableDescribeFnRes.rows?.[0]?.ok) {
22502
+ const tableDescribeFnRes = await params.client.query(`select case when pg_catalog.to_regprocedure('postgres_ai.table_describe(text)') is not null
22503
+ then has_function_privilege($1, 'postgres_ai.table_describe(text)', 'EXECUTE') end as ok`, [role]);
22504
+ if (tableDescribeFnRes.rows?.[0]?.ok === null) {
22505
+ missingRequired.push("function postgres_ai.table_describe(text) exists");
22506
+ } else if (!tableDescribeFnRes.rows?.[0]?.ok) {
22472
22507
  missingRequired.push("EXECUTE on postgres_ai.table_describe(text)");
22473
22508
  }
22474
22509
  if (params.includeOptionalPermissions) {
@@ -22731,6 +22766,33 @@ function isNumericProjectRef(ref) {
22731
22766
  return /^[0-9]+$/.test(ref.trim());
22732
22767
  }
22733
22768
 
22769
+ // lib/supabase.ts
22770
+ var SUPABASE_API_BASE = "https://api.supabase.com";
22771
+ function extractProjectRefFromUrl(dbUrl) {
22772
+ try {
22773
+ const url = new URL(dbUrl);
22774
+ const host = url.hostname;
22775
+ const match = host.match(/^(?:db\.)?([^.]+)\.supabase\.co$/i);
22776
+ if (match && match[1]) {
22777
+ return match[1];
22778
+ }
22779
+ if (host.endsWith(".pooler.supabase.com")) {
22780
+ const username = decodeURIComponent(url.username);
22781
+ const userMatch = username.match(/^[^.]+\.([a-z0-9]+)$/i);
22782
+ if (userMatch && userMatch[1]) {
22783
+ return userMatch[1];
22784
+ }
22785
+ }
22786
+ const poolerMatch = host.match(/^([a-z0-9]+)\.pooler\.supabase\.com$/i);
22787
+ if (poolerMatch && poolerMatch[1] && !poolerMatch[1].startsWith("aws-")) {
22788
+ return poolerMatch[1];
22789
+ }
22790
+ return;
22791
+ } catch {
22792
+ return;
22793
+ }
22794
+ }
22795
+
22734
22796
  // lib/connect.ts
22735
22797
  function httpStatus(err) {
22736
22798
  const status = err instanceof Error ? err.status : undefined;
@@ -22926,6 +22988,10 @@ function connectStatus(row, provider = row.provider, fresh = false) {
22926
22988
  return { ...base, status, next: `pgai mon instances delete ${row.id} --yes, then pgai mon deploy again` };
22927
22989
  return { ...base, status, next: `pgai mon instances watch ${row.id}` };
22928
22990
  }
22991
+ var ESCAPES = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?|\x1b[ -~]?/g;
22992
+ var terminalText = (text) => text.replace(ESCAPES, "").split(`
22993
+ `).map(stripControlsToSpace).join(`
22994
+ `);
22929
22995
  var boxState = (row) => row.status === "launch_requested" && row.registered_at ? "registered" : row.status ?? "starting";
22930
22996
  function boxWords(state) {
22931
22997
  if (!state || state === "starting" || state === "launch_requested")
@@ -22948,18 +23014,43 @@ async function billingFor(q, name, opts, deps, show) {
22948
23014
  if (q.requires_payment_method)
22949
23015
  return { billing, billingPage, billingUrl, accepted: false, stop: billingPage };
22950
23016
  show(billing.price);
22951
- if (q.billed && !opts.yes && !await deps.confirm(`Provision ${name}? (y/N): `)) {
23017
+ if (q.billed && !opts.yes && !await deps.confirm(`Provision ${terminalText(name)}? (y/N): `)) {
22952
23018
  return stop(opts.agent ? `Call deploy_monitoring again with yes: true to accept ${billing.price}` : `Re-run with --yes to accept ${billing.price}`);
22953
23019
  }
22954
23020
  return { billing, billingPage, billingUrl, accepted: q.billed };
22955
23021
  }
22956
23022
  async function connect(url, opts, deps) {
22957
23023
  const started = deps.now();
22958
- const progress = (event, message, more = {}) => deps.progress({ event, elapsed_s: Math.round((deps.now() - started) / 1000), message, ...more });
22959
- const provider = providerArg(opts.provider) ?? detectCloudProvider(url);
23024
+ let step = "preparing";
23025
+ const progress = (event, message, more = {}) => {
23026
+ if (event !== "billing")
23027
+ step = event;
23028
+ deps.progress({ event, elapsed_s: Math.round((deps.now() - started) / 1000), message, ...more });
23029
+ };
23030
+ const warned = new Set;
23031
+ const warn = (message) => {
23032
+ if (warned.has(message))
23033
+ return;
23034
+ warned.add(message);
23035
+ progress(step, message);
23036
+ };
23037
+ const project = opts.supabaseProject?.trim();
23038
+ const provider = providerArg(opts.provider) ?? (!url && project ? "supabase" : detectCloudProvider(url));
22960
23039
  if (!PROVIDERS.includes(provider))
22961
23040
  throw new Error(`--provider must be one of: generic, ${PROVIDERS.join(", ")}`);
23041
+ if (project !== undefined && provider !== "supabase") {
23042
+ return { status: "action_required", provider, name: url ? databaseName2(url) : "", next: "--supabase-project applies to Supabase only: leave it out, or use --provider supabase" };
23043
+ }
23044
+ if (!url) {
23045
+ if (provider !== "supabase")
23046
+ return { status: "action_required", provider, name: "", next: "Pass the database URL: pgai mon deploy postgresql://user:password@host:5432/dbname (Supabase: --provider supabase)" };
23047
+ if (opts.selfHosted)
23048
+ return { status: "action_required", provider, name: "", next: "--self-hosted needs the database URL: pass the project's connection string" };
23049
+ return deploySupabaseProject(undefined, opts, deps, progress);
23050
+ }
22962
23051
  assertEncodedUserinfo(url);
23052
+ if (!opts.selfHosted && provider === "supabase")
23053
+ return deploySupabase(url, opts, deps, progress);
22963
23054
  checkUrlParams(url, opts.agent);
22964
23055
  const name = databaseName2(url);
22965
23056
  const asked = opts.monitoringUser?.trim();
@@ -22991,7 +23082,7 @@ async function connect(url, opts, deps) {
22991
23082
  const key = parseClickhouseKey(opts.clickhouseKey, provider === "clickhouse" && !opts.agent ? process.env : {});
22992
23083
  if (key && provider !== "clickhouse")
22993
23084
  throw new Error("--clickhouse-key applies to ClickHouse Managed Postgres only");
22994
- if (!opts.selfHosted && (provider === "rds" || provider === "supabase")) {
23085
+ if (!opts.selfHosted && provider === "rds") {
22995
23086
  const ignored = monitoringUser ? ` (${opts.agent ? "monitoring_user" : "--monitoring-user"} is not used there)` : "";
22996
23087
  return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}${ignored}` };
22997
23088
  }
@@ -23069,7 +23160,7 @@ async function connect(url, opts, deps) {
23069
23160
  }
23070
23161
  const undo = async (p) => {
23071
23162
  if ("generated" in p && p.generated)
23072
- await deps.unprepare(url, monitoringUser).catch(() => false);
23163
+ await deps.unprepare(url, monitoringUser, { warn }).catch(() => false);
23073
23164
  };
23074
23165
  let lockId;
23075
23166
  const unread = (d) => !d.cluster;
@@ -23093,7 +23184,7 @@ async function connect(url, opts, deps) {
23093
23184
  if (opts.coupon !== undefined && !opts.coupon.trim()) {
23094
23185
  return { status: "action_required", provider, name, next: `${opts.agent ? "coupon" : "--coupon"} is empty: pass a promotion code, or leave ${opts.agent ? "coupon" : "--coupon"} out` };
23095
23186
  }
23096
- const prepOpts = { resetPassword: opts.resetPassword, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
23187
+ const prepOpts = { resetPassword: opts.resetPassword, warn, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
23097
23188
  if (!opts.selfHosted) {
23098
23189
  const probe = await deps.prepare(url, provider, { ...prepOpts, check: true }).catch((err) => {
23099
23190
  if (err instanceof HttpStatusError || /Could not connect to/.test(errorText(err)))
@@ -23227,6 +23318,260 @@ async function connect(url, opts, deps) {
23227
23318
  const made = prepared;
23228
23319
  undoRole = () => undo(made);
23229
23320
  }
23321
+ return follow(row, { provider, name, fresh, billing, billingUrl, undoRole, note }, opts, deps, progress);
23322
+ }
23323
+ var isSupabaseUrl = (link) => {
23324
+ try {
23325
+ const u = new URL(link);
23326
+ return u.origin === SUPABASE_API_BASE && !u.username && !u.password;
23327
+ } catch {
23328
+ return false;
23329
+ }
23330
+ };
23331
+ var OAUTH_WAIT_MS = 10 * 60000;
23332
+ var OAUTH_POLL_MS = 2000;
23333
+ async function deploySupabase(url, opts, deps, progress) {
23334
+ const provider = "supabase";
23335
+ const ref = extractProjectRefFromUrl(url);
23336
+ if (!ref)
23337
+ 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" };
23338
+ const db = decodeURIComponent(new URL(url).pathname.replace(/^\//, "")) || "postgres";
23339
+ const name = databaseName2(supabaseProjectUrl(ref, db));
23340
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
23341
+ if (db !== "postgres")
23342
+ return stop("PostgresAI monitors a Supabase project through its postgres database: use the URL of the postgres database");
23343
+ const refused = supabaseOptionsRefused(opts);
23344
+ if (refused)
23345
+ return stop(refused);
23346
+ if (opts.supabaseProject?.trim())
23347
+ return deploySupabaseProject(ref, opts, deps, progress);
23348
+ const row = await boxOnProject(ref, deps);
23349
+ if (row) {
23350
+ const note = opts.name && row.name !== opts.name ? `; --name ignored: this database is already monitored as ${row.name}` : "";
23351
+ return follow(row, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
23352
+ }
23353
+ let started;
23354
+ try {
23355
+ started = await deps.supabaseStart(supabaseProjectUrl(ref));
23356
+ } catch (err) {
23357
+ if (err instanceof HttpStatusError && err.status === 403)
23358
+ return stop(notAdminNext);
23359
+ if (err instanceof HttpStatusError && err.status === 409)
23360
+ return stop(errorText(err));
23361
+ throw err;
23362
+ }
23363
+ if ("auth_url" in started) {
23364
+ const waited = await supabaseConsent(started, opts, deps, progress, stop);
23365
+ if (waited)
23366
+ return waited;
23367
+ }
23368
+ return supabaseBox(ref, name, opts, deps, progress, stop);
23369
+ }
23370
+ async function boxOnProject(ref, deps) {
23371
+ const cluster = clusterOf(supabaseProjectUrl(ref));
23372
+ return (await deps.list()).find((d) => !disconnecting(d.status) && d.cluster && serverOf(d.cluster) === cluster && (!d.database || d.database === "postgres"));
23373
+ }
23374
+ function supabaseProjectUrl(ref, db = "postgres") {
23375
+ return `postgresql://db.${ref}.supabase.co:5432/${encodeURIComponent(db)}`;
23376
+ }
23377
+ function supabaseOptionsRefused(opts) {
23378
+ if (opts.resetPassword)
23379
+ 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
+ if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
23383
+ return `${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`;
23384
+ }
23385
+ return;
23386
+ }
23387
+ async function supabaseConsent(started, opts, deps, progress, stop) {
23388
+ if (!isSupabaseUrl(started.auth_url))
23389
+ 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.` };
23390
+ const approve = `Open ${started.auth_url} in a browser and approve PostgresAI's access to Supabase`;
23391
+ if (opts.agent || opts.waitMs <= 0)
23392
+ return stop(`${approve}, then ${opts.agent ? "call deploy_monitoring again" : "re-run"}`);
23393
+ 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 });
23394
+ deps.openUrl?.(started.auth_url);
23395
+ const expires = started.expires_at ? Date.parse(started.expires_at) : NaN;
23396
+ for (const deadline = deps.now() + Math.min(opts.waitMs, OAUTH_WAIT_MS);; ) {
23397
+ if (deps.aborted?.())
23398
+ throw new CancelledError;
23399
+ const s = await deps.supabaseStatus(started.session_id);
23400
+ if (s.status === "connected")
23401
+ return;
23402
+ if (s.status === "error")
23403
+ return stop(`Supabase did not connect: ${(s.error ?? "no reason given").replace(/\.$/, "")}. Re-run to try again`);
23404
+ const now = deps.now();
23405
+ if (now >= expires)
23406
+ return stop("The Supabase consent link expired before it was approved: re-run pgai mon deploy for a new one");
23407
+ if (now >= deadline)
23408
+ return stop(`${approve}, then re-run`);
23409
+ await deps.sleep(OAUTH_POLL_MS);
23410
+ }
23411
+ }
23412
+ function supabaseStatusWords(status) {
23413
+ if (status === "inactive" || status === "paused")
23414
+ return "paused";
23415
+ if (status === "coming_up")
23416
+ return "starting";
23417
+ if (status === "unknown")
23418
+ return "in an unknown state";
23419
+ return status.replace(/_/g, " ");
23420
+ }
23421
+ function matchSupabaseProject(projects, wanted) {
23422
+ const value = wanted.trim();
23423
+ const byRef = projects.find((p) => p.ref === value);
23424
+ if (byRef)
23425
+ return { project: byRef };
23426
+ const byName = projects.filter((p) => p.name.toLowerCase() === value.toLowerCase());
23427
+ if (byName.length === 1)
23428
+ return { project: byName[0] };
23429
+ if (byName.length > 1)
23430
+ return { ambiguous: byName };
23431
+ return { none: true };
23432
+ }
23433
+ async function deploySupabaseProject(urlRef, opts, deps, progress) {
23434
+ const provider = "supabase";
23435
+ let name = urlRef ? databaseName2(supabaseProjectUrl(urlRef)) : "";
23436
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
23437
+ const refused = supabaseOptionsRefused(opts);
23438
+ if (refused)
23439
+ return stop(refused);
23440
+ const urlHint = "pass the project's URL instead (pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres')";
23441
+ if (!deps.supabaseProjects)
23442
+ return stop(`Picking a Supabase project needs a newer pgai: ${urlHint}`);
23443
+ const listed = async () => {
23444
+ try {
23445
+ return await deps.supabaseProjects();
23446
+ } catch (err) {
23447
+ if (err instanceof HttpStatusError && err.status === 403)
23448
+ return stop(notAdminNext);
23449
+ if (err instanceof HttpStatusError && err.status === 404)
23450
+ return stop(`This PostgresAI API cannot list Supabase projects yet: ${urlHint}`);
23451
+ throw err;
23452
+ }
23453
+ };
23454
+ let list = await listed();
23455
+ if ("status" in list)
23456
+ return list;
23457
+ if (!list.connected) {
23458
+ const waited = await supabaseConsent(list, opts, deps, progress, stop);
23459
+ if (waited)
23460
+ return waited;
23461
+ list = await listed();
23462
+ if ("status" in list)
23463
+ return list;
23464
+ if (!list.connected)
23465
+ return stop("Supabase did not stay connected after the approval: re-run pgai mon deploy --provider supabase");
23466
+ }
23467
+ const org = list.supabase_org_name;
23468
+ const projects = list.projects;
23469
+ const shown = { supabase_org: org, projects };
23470
+ if (!list.synced && !projects.length)
23471
+ return stop("Supabase did not answer the project list: re-run in a minute");
23472
+ const stale = list.synced ? "" : " (Supabase did not answer just now: the list may be out of date)";
23473
+ const inOrg = `organization "${org}"`;
23474
+ const useFlag = "--supabase-project <name or project ID>";
23475
+ if (!projects.length)
23476
+ return stop(`There are no projects in the Supabase ${inOrg}: create one there, then re-run`, shown);
23477
+ const wanted = opts.supabaseProject?.trim();
23478
+ let picked;
23479
+ if (wanted) {
23480
+ const m = matchSupabaseProject(projects, wanted);
23481
+ if ("none" in m)
23482
+ return stop(`No Supabase project "${wanted}" in ${inOrg}: re-run with ${useFlag} of one of its projects`, shown);
23483
+ if ("ambiguous" in m)
23484
+ return stop(`Several projects in ${inOrg} are called "${wanted}": re-run with the project ID instead`, { supabase_org: org, projects: m.ambiguous });
23485
+ picked = m.project;
23486
+ } else {
23487
+ if (!projects.some((p) => p.selectable)) {
23488
+ 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);
23489
+ }
23490
+ const ask = !opts.agent && !opts.yes ? deps.chooseSupabaseProject : undefined;
23491
+ if (!ask)
23492
+ return stop(`Choose the Supabase project to monitor, then re-run with ${useFlag}${stale}`, shown);
23493
+ const ref = await ask(projects, org);
23494
+ if (deps.aborted?.())
23495
+ throw new CancelledError;
23496
+ if (!ref)
23497
+ return stop(`No project chosen: re-run and pick one, or pass ${useFlag}`, shown);
23498
+ picked = projects.find((p) => p.ref === ref);
23499
+ }
23500
+ if (!picked)
23501
+ return stop(`No project chosen: re-run and pick one, or pass ${useFlag}`, shown);
23502
+ if (urlRef && picked.ref !== urlRef) {
23503
+ const urlProject = projects.find((p) => p.ref === urlRef);
23504
+ return stop(`--supabase-project is ${picked.name}, but the database URL is for ${urlProject ? urlProject.name : `project ${urlRef}`}: pass only one of them`);
23505
+ }
23506
+ name = databaseName2(supabaseProjectUrl(picked.ref));
23507
+ if (picked.monitored) {
23508
+ const box = (await deps.list()).find((d) => d.id === picked.monitored.id);
23509
+ if (box && !disconnecting(box.status)) {
23510
+ const note = opts.name && box.name !== opts.name ? `; --name ignored: this database is already monitored as ${box.name}` : "";
23511
+ return follow(box, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
23512
+ }
23513
+ return stop(`${picked.name} is already monitored${picked.monitored.name ? ` as ${picked.monitored.name}` : ""}: see pgai mon instances list`);
23514
+ }
23515
+ if (picked.reason === "paused")
23516
+ return stop(`${picked.name} is paused: resume it in Supabase, then re-run`);
23517
+ if (!picked.selectable)
23518
+ return stop(`${picked.name} is not ready in Supabase (${supabaseStatusWords(picked.status)}): re-run when it is active`);
23519
+ const existing = await boxOnProject(picked.ref, deps);
23520
+ if (existing) {
23521
+ const note = opts.name && existing.name !== opts.name ? `; --name ignored: this database is already monitored as ${existing.name}` : "";
23522
+ return follow(existing, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
23523
+ }
23524
+ return supabaseBox(picked.ref, name, opts, deps, progress, stop, `${picked.name} (Supabase)`);
23525
+ }
23526
+ async function supabaseBox(ref, name, opts, deps, progress, stop, label) {
23527
+ const provider = "supabase";
23528
+ let quote;
23529
+ try {
23530
+ quote = await deps.quote(opts.coupon);
23531
+ } catch (err) {
23532
+ if (err instanceof HttpStatusError && err.status === 403)
23533
+ return stop(notAdminNext);
23534
+ throw err;
23535
+ }
23536
+ const b = await billingFor(quote, label ?? name, opts, deps, (price) => progress("billing", estimateLine(price), label ? { project: label } : {}));
23537
+ if (b.stop)
23538
+ return { status: "action_required", provider, name, ...b.stop };
23539
+ if (deps.aborted?.())
23540
+ throw new CancelledError;
23541
+ progress("provisioning", `Provisioning monitoring for ${label ?? name}`, label ? { project: label } : {});
23542
+ const created = await deps.supabaseConnect({
23543
+ project_ref: ref,
23544
+ ...opts.name ? { name: opts.name } : {},
23545
+ ...b.accepted ? { accept_price: true } : {},
23546
+ ...opts.coupon ? { promo_code: opts.coupon } : {},
23547
+ ...opts.vcpus ? { vcpus: opts.vcpus } : {}
23548
+ }).catch((err) => {
23549
+ if (err instanceof HttpStatusError && err.status === 402)
23550
+ return /declined/i.test(err.message) ? "declined" : "payment";
23551
+ if (err instanceof HttpStatusError && err.status === 412)
23552
+ return "price";
23553
+ if (err instanceof HttpStatusError && err.status === 409)
23554
+ return { refused: errorText(err) };
23555
+ throw err;
23556
+ });
23557
+ if (typeof created === "object" && "refused" in created)
23558
+ return stop(created.refused);
23559
+ if (created === "payment")
23560
+ return { status: "action_required", provider, name, ...b.billingPage };
23561
+ if (created === "declined")
23562
+ return { status: "action_required", provider, name, ...b.billingPage, next: b.billingPage.next.replace(/^Add a payment method at /, "The payment method on file was declined: update it at ") };
23563
+ if (created === "price")
23564
+ return stop("The price changed since it was shown: re-run pgai mon deploy to see it", b.billing);
23565
+ if (created.status === "failed")
23566
+ return { status: "failed", provider, name, id: created.id, ...b.billing, next: `${created.error} Re-run pgai mon deploy later.` };
23567
+ const box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: false };
23568
+ if (deps.aborted?.())
23569
+ 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);
23571
+ }
23572
+ var STILL_IN_PROGRESS = "Still in progress";
23573
+ async function follow(row, f, opts, deps, progress) {
23574
+ const { provider, name, fresh, billing, billingUrl, undoRole, note } = f;
23230
23575
  let shown;
23231
23576
  for (const deadline = deps.now() + opts.waitMs;; ) {
23232
23577
  if (row.billing_error && disconnecting(row.status)) {
@@ -23252,6 +23597,14 @@ async function connect(url, opts, deps) {
23252
23597
  final.next += "; for CPU, memory and disk, delete the instance (pgai mon instances delete) and deploy again with --clickhouse-key <key-id>:<key-secret>";
23253
23598
  }
23254
23599
  const { next, ...rest } = final;
23600
+ if (final.status === "in_progress" && opts.waitMs > 0) {
23601
+ return {
23602
+ ...rest,
23603
+ status: "action_required",
23604
+ ...billing,
23605
+ next: `${STILL_IN_PROGRESS} (box: ${boxWords(boxState(row))}) when the wait ended: resume with ${next}${note}`
23606
+ };
23607
+ }
23255
23608
  return { ...rest, ...billing, next: next + note };
23256
23609
  }
23257
23610
  await deps.sleep(POLL_MS);
@@ -23259,8 +23612,9 @@ async function connect(url, opts, deps) {
23259
23612
  return;
23260
23613
  });
23261
23614
  const now = listed?.find((d) => d.id === row.id);
23262
- if (listed && !now && undoRole) {
23263
- await undoRole();
23615
+ if (listed && !now && fresh) {
23616
+ if (undoRole)
23617
+ await undoRole();
23264
23618
  return { status: "failed", provider, name, id: row.id, ...billing, next: "The monitoring box was removed before it became active: see pgai mon instances list, then re-run pgai mon deploy" };
23265
23619
  }
23266
23620
  row = now ?? row;
@@ -23274,7 +23628,7 @@ async function openConnection(url, opts) {
23274
23628
  conn.clientConfig = { ...config, ...explicit };
23275
23629
  }
23276
23630
  const fallback = !opts.agent && !!conn.sslFallbackEnabled;
23277
- const { client, usedSsl } = await connectWithSslFallback(opts.Client ?? Client2, { ...conn, sslFallbackEnabled: fallback });
23631
+ const { client, usedSsl } = await connectWithSslFallback(opts.Client ?? Client2, { ...conn, sslFallbackEnabled: fallback }, false, opts.warn);
23278
23632
  await client.query("set search_path = pg_catalog, pg_temp");
23279
23633
  return { client, usedSsl, refusedTls: fallback && !usedSsl };
23280
23634
  }
@@ -23539,10 +23893,14 @@ function platformDeps(p) {
23539
23893
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
23540
23894
  resetUnlock: (lockId) => rpc("cloud_monitoring_reset_unlock", { lock_id: lockId }),
23541
23895
  prepare: (url, provider, o = {}) => prepareDatabase(url, provider, { ...o, agent: p.agent }),
23542
- unprepare: (url, monitoringUser) => unprepareDatabase(url, { agent: p.agent, monitoringUser }),
23896
+ unprepare: (url, monitoringUser, o = {}) => unprepareDatabase(url, { ...o, agent: p.agent, monitoringUser }),
23543
23897
  clickhouseOrg: clickhouseOrgFor,
23544
23898
  quote: (coupon, cluster) => rpc("cloud_monitoring_quote", { ...coupon ? { promo_code: coupon } : {}, ...cluster ? { db_server: cluster } : {} }),
23545
23899
  billingUrl: (orgAlias) => `${p.uiBaseUrl}/${orgAlias}/billing`,
23900
+ supabaseStart: (dbUrl) => rpc("cloud_monitoring_supabase_start", { db_url: dbUrl }),
23901
+ supabaseStatus: (sessionId) => rpc("cloud_monitoring_supabase_status", { session_id: sessionId }),
23902
+ supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
23903
+ supabaseProjects: () => rpc("cloud_monitoring_supabase_projects", {}),
23546
23904
  handoffUrl: async (provider) => {
23547
23905
  const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
23548
23906
  const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
@@ -30814,7 +31172,7 @@ async function startMcpServer(rootOpts, extra) {
30814
31172
  },
30815
31173
  {
30816
31174
  name: "deploy_monitoring",
30817
- description: "Put a Postgres database under PostgresAI Cloud monitoring (same as `pgai mon deploy`): prepares the monitoring role (an admin URL creates it; otherwise returns the SQL), provisions the monitoring box, and returns JSON with status (ready | in_progress | deleting | deleted | inactive | action_required | failed: the same words as pgai dblab deploy), health_url (the project's Health Matrix in the console), dashboard_url (Grafana, signing in with PostgresAI) and next (the exact next action). A billed box is provisioned only with yes: true: without it the result is action_required with the price (and requires_payment_method), so show the price to the user first. It does not wait for the box: call it again to see the status. Safe to call again. ClickHouse Managed Postgres, RDS and Supabase are detected from the host. The URL must carry its password, and only these query parameters: sslmode, channel_binding, application_name. PGAI_MON_PASSWORD, PGPASSWORD and CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET of the server process are not used (pass clickhouse_key), and a TLS failure is not retried in plaintext (say sslmode=disable for a server without TLS). For another database on a server PostgresAI already monitors for the org, an admin URL with sslmode=require (or verify-*), each query parameter once, is enough: PostgresAI fills in the password of postgres_ai_mon it keeps, over TLS only (on a server without TLS, pass the postgres_ai_mon URL; if nobody has its password, the user runs in a terminal: pgai mon instances delete the server's other databases, then pgai mon deploy <admin-url> --reset-password with PGAI_MON_PASSWORD set to a new one, then deploys them again with it).",
31175
+ description: "Put a Postgres database under PostgresAI Cloud monitoring (same as `pgai mon deploy`): prepares the monitoring role (an admin URL creates it; otherwise returns the SQL), provisions the monitoring box, and returns JSON with status (ready | in_progress | deleting | deleted | inactive | action_required | failed: the same words as pgai dblab deploy), health_url (the project's Health Matrix in the console), dashboard_url (Grafana, signing in with PostgresAI) and next (the exact next action). A billed box is provisioned only with yes: true: without it the result is action_required with the price (and requires_payment_method), so show the price to the user first. It does not wait for the box: call it again to see the status. Safe to call again. ClickHouse Managed Postgres, RDS and Supabase are detected from the host. Supabase needs no password (PostgresAI prepares the database through the Supabase Management API): the first time, the result is action_required with a consent link in next; give it to the user to open and approve, then call again. Elsewhere the URL must carry its password, and only these query parameters: sslmode, channel_binding, application_name. PGAI_MON_PASSWORD, PGPASSWORD and CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET of the server process are not used (pass clickhouse_key), and a TLS failure is not retried in plaintext (say sslmode=disable for a server without TLS). For another database on a server PostgresAI already monitors for the org, an admin URL with sslmode=require (or verify-*), each query parameter once, is enough: PostgresAI fills in the password of postgres_ai_mon it keeps, over TLS only (on a server without TLS, pass the postgres_ai_mon URL; if nobody has its password, the user runs in a terminal: pgai mon instances delete the server's other databases, then pgai mon deploy <admin-url> --reset-password with PGAI_MON_PASSWORD set to a new one, then deploys them again with it).",
30818
31176
  inputSchema: {
30819
31177
  type: "object",
30820
31178
  properties: {
@@ -30825,7 +31183,7 @@ async function startMcpServer(rootOpts, extra) {
30825
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" },
30826
31184
  coupon: { type: "string", description: "Stripe promotion code for the organization's monitoring subscription (applies when it is first created)" },
30827
31185
  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" },
30828
- 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)" },
31186
+ 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" },
30829
31187
  debug: { type: "boolean", description: "Enable verbose debug logs" }
30830
31188
  },
30831
31189
  required: ["database_url"],
@@ -31922,6 +32280,10 @@ function connectStatus2(row, provider = row.provider, fresh = false) {
31922
32280
  return { ...base, status, next: `pgai mon instances delete ${row.id} --yes, then pgai mon deploy again` };
31923
32281
  return { ...base, status, next: `pgai mon instances watch ${row.id}` };
31924
32282
  }
32283
+ var ESCAPES2 = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?|\x1b[ -~]?/g;
32284
+ var terminalText2 = (text) => text.replace(ESCAPES2, "").split(`
32285
+ `).map(stripControlsToSpace).join(`
32286
+ `);
31925
32287
  function stepProgress(o) {
31926
32288
  let view;
31927
32289
  let priced = false;
@@ -31930,6 +32292,7 @@ function stepProgress(o) {
31930
32292
  o.onId?.(e.id);
31931
32293
  if (o.json)
31932
32294
  return o.writeEvent(e);
32295
+ e = { ...e, message: terminalText2(e.message), ...e.state ? { state: terminalText2(e.state) } : {} };
31933
32296
  if (!o.tty)
31934
32297
  return o.writeLine(progressText(e));
31935
32298
  if (e.event === "billing") {
@@ -31951,6 +32314,9 @@ function stepProgress(o) {
31951
32314
  return { progress, view: () => view };
31952
32315
  }
31953
32316
  function resultLines(r) {
32317
+ return personLines(r).map(terminalText2);
32318
+ }
32319
+ function personLines(r) {
31954
32320
  const who = r.name || "this database";
31955
32321
  const extra = (r.next ?? "").split("; ").slice(1).join("; ");
31956
32322
  const billing = r.billing;
@@ -31970,7 +32336,7 @@ function resultLines(r) {
31970
32336
  case "deleted":
31971
32337
  return [`Deleting the monitoring of ${who}.${billing ? ` Billing: ${billing}.` : ""}${r.next && r.next !== "none" ? ` ${r.next}` : ""}`];
31972
32338
  default:
31973
- return [r.next];
32339
+ return r.projects?.length ? [r.next, ...supabaseProjectRows(r.projects)] : [r.next];
31974
32340
  }
31975
32341
  }
31976
32342
  function progressText(e) {
@@ -32004,18 +32370,43 @@ async function billingFor2(q, name, opts, deps, show) {
32004
32370
  if (q.requires_payment_method)
32005
32371
  return { billing, billingPage, billingUrl, accepted: false, stop: billingPage };
32006
32372
  show(billing.price);
32007
- if (q.billed && !opts.yes && !await deps.confirm(`Provision ${name}? (y/N): `)) {
32373
+ if (q.billed && !opts.yes && !await deps.confirm(`Provision ${terminalText2(name)}? (y/N): `)) {
32008
32374
  return stop(opts.agent ? `Call deploy_monitoring again with yes: true to accept ${billing.price}` : `Re-run with --yes to accept ${billing.price}`);
32009
32375
  }
32010
32376
  return { billing, billingPage, billingUrl, accepted: q.billed };
32011
32377
  }
32012
32378
  async function connect2(url, opts, deps) {
32013
32379
  const started = deps.now();
32014
- const progress = (event, message, more = {}) => deps.progress({ event, elapsed_s: Math.round((deps.now() - started) / 1000), message, ...more });
32015
- const provider = providerArg2(opts.provider) ?? detectCloudProvider2(url);
32380
+ let step = "preparing";
32381
+ const progress = (event, message, more = {}) => {
32382
+ if (event !== "billing")
32383
+ step = event;
32384
+ deps.progress({ event, elapsed_s: Math.round((deps.now() - started) / 1000), message, ...more });
32385
+ };
32386
+ const warned = new Set;
32387
+ const warn = (message) => {
32388
+ if (warned.has(message))
32389
+ return;
32390
+ warned.add(message);
32391
+ progress(step, message);
32392
+ };
32393
+ const project = opts.supabaseProject?.trim();
32394
+ const provider = providerArg2(opts.provider) ?? (!url && project ? "supabase" : detectCloudProvider2(url));
32016
32395
  if (!PROVIDERS2.includes(provider))
32017
32396
  throw new Error(`--provider must be one of: generic, ${PROVIDERS2.join(", ")}`);
32397
+ if (project !== undefined && provider !== "supabase") {
32398
+ return { status: "action_required", provider, name: url ? databaseName3(url) : "", next: "--supabase-project applies to Supabase only: leave it out, or use --provider supabase" };
32399
+ }
32400
+ if (!url) {
32401
+ if (provider !== "supabase")
32402
+ return { status: "action_required", provider, name: "", next: "Pass the database URL: pgai mon deploy postgresql://user:password@host:5432/dbname (Supabase: --provider supabase)" };
32403
+ if (opts.selfHosted)
32404
+ return { status: "action_required", provider, name: "", next: "--self-hosted needs the database URL: pass the project's connection string" };
32405
+ return deploySupabaseProject2(undefined, opts, deps, progress);
32406
+ }
32018
32407
  assertEncodedUserinfo(url);
32408
+ if (!opts.selfHosted && provider === "supabase")
32409
+ return deploySupabase2(url, opts, deps, progress);
32019
32410
  checkUrlParams2(url, opts.agent);
32020
32411
  const name = databaseName3(url);
32021
32412
  const asked = opts.monitoringUser?.trim();
@@ -32047,7 +32438,7 @@ async function connect2(url, opts, deps) {
32047
32438
  const key = parseClickhouseKey2(opts.clickhouseKey, provider === "clickhouse" && !opts.agent ? process.env : {});
32048
32439
  if (key && provider !== "clickhouse")
32049
32440
  throw new Error("--clickhouse-key applies to ClickHouse Managed Postgres only");
32050
- if (!opts.selfHosted && (provider === "rds" || provider === "supabase")) {
32441
+ if (!opts.selfHosted && provider === "rds") {
32051
32442
  const ignored = monitoringUser ? ` (${opts.agent ? "monitoring_user" : "--monitoring-user"} is not used there)` : "";
32052
32443
  return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}${ignored}` };
32053
32444
  }
@@ -32125,7 +32516,7 @@ async function connect2(url, opts, deps) {
32125
32516
  }
32126
32517
  const undo = async (p) => {
32127
32518
  if ("generated" in p && p.generated)
32128
- await deps.unprepare(url, monitoringUser).catch(() => false);
32519
+ await deps.unprepare(url, monitoringUser, { warn }).catch(() => false);
32129
32520
  };
32130
32521
  let lockId;
32131
32522
  const unread = (d) => !d.cluster;
@@ -32149,7 +32540,7 @@ async function connect2(url, opts, deps) {
32149
32540
  if (opts.coupon !== undefined && !opts.coupon.trim()) {
32150
32541
  return { status: "action_required", provider, name, next: `${opts.agent ? "coupon" : "--coupon"} is empty: pass a promotion code, or leave ${opts.agent ? "coupon" : "--coupon"} out` };
32151
32542
  }
32152
- const prepOpts = { resetPassword: opts.resetPassword, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
32543
+ const prepOpts = { resetPassword: opts.resetPassword, warn, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
32153
32544
  if (!opts.selfHosted) {
32154
32545
  const probe = await deps.prepare(url, provider, { ...prepOpts, check: true }).catch((err) => {
32155
32546
  if (err instanceof HttpStatusError || /Could not connect to/.test(errorText2(err)))
@@ -32283,6 +32674,280 @@ async function connect2(url, opts, deps) {
32283
32674
  const made = prepared;
32284
32675
  undoRole = () => undo(made);
32285
32676
  }
32677
+ return follow2(row, { provider, name, fresh, billing, billingUrl, undoRole, note }, opts, deps, progress);
32678
+ }
32679
+ var isSupabaseUrl2 = (link) => {
32680
+ try {
32681
+ const u = new URL(link);
32682
+ return u.origin === SUPABASE_API_BASE && !u.username && !u.password;
32683
+ } catch {
32684
+ return false;
32685
+ }
32686
+ };
32687
+ var OAUTH_WAIT_MS2 = 10 * 60000;
32688
+ var OAUTH_POLL_MS2 = 2000;
32689
+ async function deploySupabase2(url, opts, deps, progress) {
32690
+ const provider = "supabase";
32691
+ const ref = extractProjectRefFromUrl(url);
32692
+ if (!ref)
32693
+ 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" };
32694
+ const db = decodeURIComponent(new URL(url).pathname.replace(/^\//, "")) || "postgres";
32695
+ const name = databaseName3(supabaseProjectUrl2(ref, db));
32696
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
32697
+ if (db !== "postgres")
32698
+ return stop("PostgresAI monitors a Supabase project through its postgres database: use the URL of the postgres database");
32699
+ const refused = supabaseOptionsRefused2(opts);
32700
+ if (refused)
32701
+ return stop(refused);
32702
+ if (opts.supabaseProject?.trim())
32703
+ return deploySupabaseProject2(ref, opts, deps, progress);
32704
+ const row = await boxOnProject2(ref, deps);
32705
+ if (row) {
32706
+ const note = opts.name && row.name !== opts.name ? `; --name ignored: this database is already monitored as ${row.name}` : "";
32707
+ return follow2(row, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
32708
+ }
32709
+ let started;
32710
+ try {
32711
+ started = await deps.supabaseStart(supabaseProjectUrl2(ref));
32712
+ } catch (err) {
32713
+ if (err instanceof HttpStatusError && err.status === 403)
32714
+ return stop(notAdminNext);
32715
+ if (err instanceof HttpStatusError && err.status === 409)
32716
+ return stop(errorText2(err));
32717
+ throw err;
32718
+ }
32719
+ if ("auth_url" in started) {
32720
+ const waited = await supabaseConsent2(started, opts, deps, progress, stop);
32721
+ if (waited)
32722
+ return waited;
32723
+ }
32724
+ return supabaseBox2(ref, name, opts, deps, progress, stop);
32725
+ }
32726
+ async function boxOnProject2(ref, deps) {
32727
+ const cluster = clusterOf2(supabaseProjectUrl2(ref));
32728
+ return (await deps.list()).find((d) => !disconnecting2(d.status) && d.cluster && serverOf2(d.cluster) === cluster && (!d.database || d.database === "postgres"));
32729
+ }
32730
+ function supabaseProjectUrl2(ref, db = "postgres") {
32731
+ return `postgresql://db.${ref}.supabase.co:5432/${encodeURIComponent(db)}`;
32732
+ }
32733
+ function supabaseOptionsRefused2(opts) {
32734
+ if (opts.resetPassword)
32735
+ 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
+ if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
32739
+ return `${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`;
32740
+ }
32741
+ return;
32742
+ }
32743
+ async function supabaseConsent2(started, opts, deps, progress, stop) {
32744
+ if (!isSupabaseUrl2(started.auth_url))
32745
+ 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.` };
32746
+ const approve = `Open ${started.auth_url} in a browser and approve PostgresAI's access to Supabase`;
32747
+ if (opts.agent || opts.waitMs <= 0)
32748
+ return stop(`${approve}, then ${opts.agent ? "call deploy_monitoring again" : "re-run"}`);
32749
+ 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 });
32750
+ deps.openUrl?.(started.auth_url);
32751
+ const expires = started.expires_at ? Date.parse(started.expires_at) : NaN;
32752
+ for (const deadline = deps.now() + Math.min(opts.waitMs, OAUTH_WAIT_MS2);; ) {
32753
+ if (deps.aborted?.())
32754
+ throw new CancelledError2;
32755
+ const s = await deps.supabaseStatus(started.session_id);
32756
+ if (s.status === "connected")
32757
+ return;
32758
+ if (s.status === "error")
32759
+ return stop(`Supabase did not connect: ${(s.error ?? "no reason given").replace(/\.$/, "")}. Re-run to try again`);
32760
+ const now = deps.now();
32761
+ if (now >= expires)
32762
+ return stop("The Supabase consent link expired before it was approved: re-run pgai mon deploy for a new one");
32763
+ if (now >= deadline)
32764
+ return stop(`${approve}, then re-run`);
32765
+ await deps.sleep(OAUTH_POLL_MS2);
32766
+ }
32767
+ }
32768
+ function supabaseStatusWords2(status) {
32769
+ if (status === "inactive" || status === "paused")
32770
+ return "paused";
32771
+ if (status === "coming_up")
32772
+ return "starting";
32773
+ if (status === "unknown")
32774
+ return "in an unknown state";
32775
+ return status.replace(/_/g, " ");
32776
+ }
32777
+ function supabaseWhy(p) {
32778
+ if (p.reason === "monitored")
32779
+ return `already monitored${p.monitored?.name ? ` as ${p.monitored.name}` : ""}`;
32780
+ if (p.reason === "paused")
32781
+ return "paused";
32782
+ if (p.reason?.startsWith("not_ready:"))
32783
+ return `not ready (${supabaseStatusWords2(p.reason.slice("not_ready:".length))})`;
32784
+ return "";
32785
+ }
32786
+ function supabaseProjectRows(projects, numbered = false) {
32787
+ const nameW = Math.max(...projects.map((p) => p.name.length));
32788
+ const regionW = Math.max(...projects.map((p) => (p.region ?? "").length));
32789
+ const numW = String(projects.filter((p) => p.selectable).length).length;
32790
+ let n = 0;
32791
+ return projects.map((p) => {
32792
+ const why = supabaseWhy(p);
32793
+ const mark = numbered ? `${(p.selectable ? `${++n}.` : "-").padStart(numW + 1)} ` : "";
32794
+ return ` ${mark}${p.name.padEnd(nameW)} ${(p.region ?? "").padEnd(regionW)} ${p.ref}${why ? ` ${why}` : ""}`.trimEnd();
32795
+ });
32796
+ }
32797
+ function matchSupabaseProject2(projects, wanted) {
32798
+ const value = wanted.trim();
32799
+ const byRef = projects.find((p) => p.ref === value);
32800
+ if (byRef)
32801
+ return { project: byRef };
32802
+ const byName = projects.filter((p) => p.name.toLowerCase() === value.toLowerCase());
32803
+ if (byName.length === 1)
32804
+ return { project: byName[0] };
32805
+ if (byName.length > 1)
32806
+ return { ambiguous: byName };
32807
+ return { none: true };
32808
+ }
32809
+ async function deploySupabaseProject2(urlRef, opts, deps, progress) {
32810
+ const provider = "supabase";
32811
+ let name = urlRef ? databaseName3(supabaseProjectUrl2(urlRef)) : "";
32812
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
32813
+ const refused = supabaseOptionsRefused2(opts);
32814
+ if (refused)
32815
+ return stop(refused);
32816
+ const urlHint = "pass the project's URL instead (pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres')";
32817
+ if (!deps.supabaseProjects)
32818
+ return stop(`Picking a Supabase project needs a newer pgai: ${urlHint}`);
32819
+ const listed = async () => {
32820
+ try {
32821
+ return await deps.supabaseProjects();
32822
+ } catch (err) {
32823
+ if (err instanceof HttpStatusError && err.status === 403)
32824
+ return stop(notAdminNext);
32825
+ if (err instanceof HttpStatusError && err.status === 404)
32826
+ return stop(`This PostgresAI API cannot list Supabase projects yet: ${urlHint}`);
32827
+ throw err;
32828
+ }
32829
+ };
32830
+ let list = await listed();
32831
+ if ("status" in list)
32832
+ return list;
32833
+ if (!list.connected) {
32834
+ const waited = await supabaseConsent2(list, opts, deps, progress, stop);
32835
+ if (waited)
32836
+ return waited;
32837
+ list = await listed();
32838
+ if ("status" in list)
32839
+ return list;
32840
+ if (!list.connected)
32841
+ return stop("Supabase did not stay connected after the approval: re-run pgai mon deploy --provider supabase");
32842
+ }
32843
+ const org = list.supabase_org_name;
32844
+ const projects = list.projects;
32845
+ const shown = { supabase_org: org, projects };
32846
+ if (!list.synced && !projects.length)
32847
+ return stop("Supabase did not answer the project list: re-run in a minute");
32848
+ const stale = list.synced ? "" : " (Supabase did not answer just now: the list may be out of date)";
32849
+ const inOrg = `organization "${org}"`;
32850
+ const useFlag = "--supabase-project <name or project ID>";
32851
+ if (!projects.length)
32852
+ return stop(`There are no projects in the Supabase ${inOrg}: create one there, then re-run`, shown);
32853
+ const wanted = opts.supabaseProject?.trim();
32854
+ let picked;
32855
+ if (wanted) {
32856
+ const m = matchSupabaseProject2(projects, wanted);
32857
+ if ("none" in m)
32858
+ return stop(`No Supabase project "${wanted}" in ${inOrg}: re-run with ${useFlag} of one of its projects`, shown);
32859
+ if ("ambiguous" in m)
32860
+ return stop(`Several projects in ${inOrg} are called "${wanted}": re-run with the project ID instead`, { supabase_org: org, projects: m.ambiguous });
32861
+ picked = m.project;
32862
+ } else {
32863
+ if (!projects.some((p) => p.selectable)) {
32864
+ 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);
32865
+ }
32866
+ const ask = !opts.agent && !opts.yes ? deps.chooseSupabaseProject : undefined;
32867
+ if (!ask)
32868
+ return stop(`Choose the Supabase project to monitor, then re-run with ${useFlag}${stale}`, shown);
32869
+ const ref = await ask(projects, org);
32870
+ if (deps.aborted?.())
32871
+ throw new CancelledError2;
32872
+ if (!ref)
32873
+ return stop(`No project chosen: re-run and pick one, or pass ${useFlag}`, shown);
32874
+ picked = projects.find((p) => p.ref === ref);
32875
+ }
32876
+ if (!picked)
32877
+ return stop(`No project chosen: re-run and pick one, or pass ${useFlag}`, shown);
32878
+ if (urlRef && picked.ref !== urlRef) {
32879
+ const urlProject = projects.find((p) => p.ref === urlRef);
32880
+ return stop(`--supabase-project is ${picked.name}, but the database URL is for ${urlProject ? urlProject.name : `project ${urlRef}`}: pass only one of them`);
32881
+ }
32882
+ name = databaseName3(supabaseProjectUrl2(picked.ref));
32883
+ if (picked.monitored) {
32884
+ const box = (await deps.list()).find((d) => d.id === picked.monitored.id);
32885
+ if (box && !disconnecting2(box.status)) {
32886
+ const note = opts.name && box.name !== opts.name ? `; --name ignored: this database is already monitored as ${box.name}` : "";
32887
+ return follow2(box, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
32888
+ }
32889
+ return stop(`${picked.name} is already monitored${picked.monitored.name ? ` as ${picked.monitored.name}` : ""}: see pgai mon instances list`);
32890
+ }
32891
+ if (picked.reason === "paused")
32892
+ return stop(`${picked.name} is paused: resume it in Supabase, then re-run`);
32893
+ if (!picked.selectable)
32894
+ return stop(`${picked.name} is not ready in Supabase (${supabaseStatusWords2(picked.status)}): re-run when it is active`);
32895
+ const existing = await boxOnProject2(picked.ref, deps);
32896
+ if (existing) {
32897
+ const note = opts.name && existing.name !== opts.name ? `; --name ignored: this database is already monitored as ${existing.name}` : "";
32898
+ return follow2(existing, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
32899
+ }
32900
+ return supabaseBox2(picked.ref, name, opts, deps, progress, stop, `${picked.name} (Supabase)`);
32901
+ }
32902
+ async function supabaseBox2(ref, name, opts, deps, progress, stop, label) {
32903
+ const provider = "supabase";
32904
+ let quote;
32905
+ try {
32906
+ quote = await deps.quote(opts.coupon);
32907
+ } catch (err) {
32908
+ if (err instanceof HttpStatusError && err.status === 403)
32909
+ return stop(notAdminNext);
32910
+ throw err;
32911
+ }
32912
+ const b = await billingFor2(quote, label ?? name, opts, deps, (price) => progress("billing", estimateLine(price), label ? { project: label } : {}));
32913
+ if (b.stop)
32914
+ return { status: "action_required", provider, name, ...b.stop };
32915
+ if (deps.aborted?.())
32916
+ throw new CancelledError2;
32917
+ progress("provisioning", `Provisioning monitoring for ${label ?? name}`, label ? { project: label } : {});
32918
+ const created = await deps.supabaseConnect({
32919
+ project_ref: ref,
32920
+ ...opts.name ? { name: opts.name } : {},
32921
+ ...b.accepted ? { accept_price: true } : {},
32922
+ ...opts.coupon ? { promo_code: opts.coupon } : {},
32923
+ ...opts.vcpus ? { vcpus: opts.vcpus } : {}
32924
+ }).catch((err) => {
32925
+ if (err instanceof HttpStatusError && err.status === 402)
32926
+ return /declined/i.test(err.message) ? "declined" : "payment";
32927
+ if (err instanceof HttpStatusError && err.status === 412)
32928
+ return "price";
32929
+ if (err instanceof HttpStatusError && err.status === 409)
32930
+ return { refused: errorText2(err) };
32931
+ throw err;
32932
+ });
32933
+ if (typeof created === "object" && "refused" in created)
32934
+ return stop(created.refused);
32935
+ if (created === "payment")
32936
+ return { status: "action_required", provider, name, ...b.billingPage };
32937
+ if (created === "declined")
32938
+ return { status: "action_required", provider, name, ...b.billingPage, next: b.billingPage.next.replace(/^Add a payment method at /, "The payment method on file was declined: update it at ") };
32939
+ if (created === "price")
32940
+ return stop("The price changed since it was shown: re-run pgai mon deploy to see it", b.billing);
32941
+ if (created.status === "failed")
32942
+ return { status: "failed", provider, name, id: created.id, ...b.billing, next: `${created.error} Re-run pgai mon deploy later.` };
32943
+ const box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: false };
32944
+ if (deps.aborted?.())
32945
+ 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);
32947
+ }
32948
+ var STILL_IN_PROGRESS2 = "Still in progress";
32949
+ async function follow2(row, f, opts, deps, progress) {
32950
+ const { provider, name, fresh, billing, billingUrl, undoRole, note } = f;
32286
32951
  let shown;
32287
32952
  for (const deadline = deps.now() + opts.waitMs;; ) {
32288
32953
  if (row.billing_error && disconnecting2(row.status)) {
@@ -32308,6 +32973,14 @@ async function connect2(url, opts, deps) {
32308
32973
  final.next += "; for CPU, memory and disk, delete the instance (pgai mon instances delete) and deploy again with --clickhouse-key <key-id>:<key-secret>";
32309
32974
  }
32310
32975
  const { next, ...rest } = final;
32976
+ if (final.status === "in_progress" && opts.waitMs > 0) {
32977
+ return {
32978
+ ...rest,
32979
+ status: "action_required",
32980
+ ...billing,
32981
+ next: `${STILL_IN_PROGRESS2} (box: ${boxWords2(boxState2(row))}) when the wait ended: resume with ${next}${note}`
32982
+ };
32983
+ }
32311
32984
  return { ...rest, ...billing, next: next + note };
32312
32985
  }
32313
32986
  await deps.sleep(POLL_MS2);
@@ -32315,8 +32988,9 @@ async function connect2(url, opts, deps) {
32315
32988
  return;
32316
32989
  });
32317
32990
  const now = listed?.find((d) => d.id === row.id);
32318
- if (listed && !now && undoRole) {
32319
- await undoRole();
32991
+ if (listed && !now && fresh) {
32992
+ if (undoRole)
32993
+ await undoRole();
32320
32994
  return { status: "failed", provider, name, id: row.id, ...billing, next: "The monitoring box was removed before it became active: see pgai mon instances list, then re-run pgai mon deploy" };
32321
32995
  }
32322
32996
  row = now ?? row;
@@ -32330,7 +33004,7 @@ async function openConnection2(url, opts) {
32330
33004
  conn.clientConfig = { ...config, ...explicit };
32331
33005
  }
32332
33006
  const fallback = !opts.agent && !!conn.sslFallbackEnabled;
32333
- const { client, usedSsl } = await connectWithSslFallback(opts.Client ?? Client2, { ...conn, sslFallbackEnabled: fallback });
33007
+ const { client, usedSsl } = await connectWithSslFallback(opts.Client ?? Client2, { ...conn, sslFallbackEnabled: fallback }, false, opts.warn);
32334
33008
  await client.query("set search_path = pg_catalog, pg_temp");
32335
33009
  return { client, usedSsl, refusedTls: fallback && !usedSsl };
32336
33010
  }
@@ -32611,10 +33285,14 @@ function platformDeps2(p) {
32611
33285
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
32612
33286
  resetUnlock: (lockId) => rpc("cloud_monitoring_reset_unlock", { lock_id: lockId }),
32613
33287
  prepare: (url, provider, o = {}) => prepareDatabase2(url, provider, { ...o, agent: p.agent }),
32614
- unprepare: (url, monitoringUser) => unprepareDatabase2(url, { agent: p.agent, monitoringUser }),
33288
+ unprepare: (url, monitoringUser, o = {}) => unprepareDatabase2(url, { ...o, agent: p.agent, monitoringUser }),
32615
33289
  clickhouseOrg: clickhouseOrgFor2,
32616
33290
  quote: (coupon, cluster) => rpc("cloud_monitoring_quote", { ...coupon ? { promo_code: coupon } : {}, ...cluster ? { db_server: cluster } : {} }),
32617
33291
  billingUrl: (orgAlias) => `${p.uiBaseUrl}/${orgAlias}/billing`,
33292
+ supabaseStart: (dbUrl) => rpc("cloud_monitoring_supabase_start", { db_url: dbUrl }),
33293
+ supabaseStatus: (sessionId) => rpc("cloud_monitoring_supabase_status", { session_id: sessionId }),
33294
+ supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
33295
+ supabaseProjects: () => rpc("cloud_monitoring_supabase_projects", {}),
32618
33296
  handoffUrl: async (provider) => {
32619
33297
  const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
32620
33298
  const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
@@ -33768,7 +34446,7 @@ class StepView {
33768
34446
  const st = this.states.get(s.key);
33769
34447
  const t = this.now();
33770
34448
  const dur = st === "running" ? formatDuration(t - (this.started.get(s.key) ?? t)) : st === "done" || st === "failed" ? formatDuration((this.finished.get(s.key) ?? t) - (this.started.get(s.key) ?? t)) : "";
33771
- const icon = st === "done" ? `${GREEN}✓${RESET}` : st === "failed" ? `${RED}✗${RESET}` : st === "running" ? FRAMES[this.frame % FRAMES.length] : `${DIM}·${RESET}`;
34449
+ const icon = st === "done" ? `${GREEN}✓${RESET}` : st === "failed" ? `${RED}✗${RESET}` : st === "running" ? this.stopped ? "…" : FRAMES[this.frame % FRAMES.length] : `${DIM}·${RESET}`;
33772
34450
  const label = st === "pending" ? `${DIM}${s.label}${RESET}` : s.label;
33773
34451
  lines.push(` ${icon} ${label}${dur ? ` ${DIM}${dur}${RESET}` : ""}`);
33774
34452
  }
@@ -34293,6 +34971,13 @@ var MONITORING_STEPS = [
34293
34971
  { key: "box", label: "Install monitoring (about 5 min)" },
34294
34972
  { key: "ready", label: "Ready" }
34295
34973
  ];
34974
+ var SUPABASE_STEPS = [
34975
+ { key: "preparing", label: "Connect Supabase" },
34976
+ { key: "provisioning", label: "Create the monitoring box" },
34977
+ { key: "box", label: "Prepare the database and install monitoring (about 5 min)" },
34978
+ { key: "ready", label: "Ready" }
34979
+ ];
34980
+ var monitoringSteps = (provider) => provider === "supabase" ? SUPABASE_STEPS : MONITORING_STEPS;
34296
34981
  var FRAMES2 = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
34297
34982
  var GREEN2 = "\x1B[32m";
34298
34983
  var RED2 = "\x1B[31m";
@@ -34427,7 +35112,7 @@ class StepView2 {
34427
35112
  const st = this.states.get(s.key);
34428
35113
  const t = this.now();
34429
35114
  const dur = st === "running" ? formatDuration2(t - (this.started.get(s.key) ?? t)) : st === "done" || st === "failed" ? formatDuration2((this.finished.get(s.key) ?? t) - (this.started.get(s.key) ?? t)) : "";
34430
- const icon = st === "done" ? `${GREEN2}✓${RESET2}` : st === "failed" ? `${RED2}✗${RESET2}` : st === "running" ? FRAMES2[this.frame % FRAMES2.length] : `${DIM2}·${RESET2}`;
35115
+ const icon = st === "done" ? `${GREEN2}✓${RESET2}` : st === "failed" ? `${RED2}✗${RESET2}` : st === "running" ? this.stopped ? "…" : FRAMES2[this.frame % FRAMES2.length] : `${DIM2}·${RESET2}`;
34431
35116
  const label = st === "pending" ? `${DIM2}${s.label}${RESET2}` : s.label;
34432
35117
  lines.push(` ${icon} ${label}${dur ? ` ${DIM2}${dur}${RESET2}` : ""}`);
34433
35118
  }
@@ -35342,7 +36027,19 @@ function isSslNegotiationError2(err) {
35342
36027
  }
35343
36028
  return false;
35344
36029
  }
35345
- async function connectWithSslFallback2(ClientClass, adminConn, verbose) {
36030
+ function effectiveConfig2(config) {
36031
+ const host = config.host ?? process.env.PGHOST;
36032
+ if (!config.connectionString)
36033
+ return { ssl: config.ssl, host };
36034
+ try {
36035
+ const parsed = parse(config.connectionString);
36036
+ const ssl = parsed.ssl === "no-verify" ? { rejectUnauthorized: false } : parsed.ssl;
36037
+ return { ssl: "ssl" in parsed ? ssl : config.ssl, host: parsed.host || host };
36038
+ } catch {
36039
+ return { ssl: config.ssl, host };
36040
+ }
36041
+ }
36042
+ async function connectWithSslFallback2(ClientClass, adminConn, verbose, warn = (message) => console.error(message)) {
35346
36043
  const tryConnect = async (config) => {
35347
36044
  const client = new ClientClass({ ...config, connectionTimeoutMillis: 1e4 });
35348
36045
  await client.connect();
@@ -35350,13 +36047,20 @@ async function connectWithSslFallback2(ClientClass, adminConn, verbose) {
35350
36047
  await client.query("SET statement_timeout = '30s'");
35351
36048
  return client;
35352
36049
  };
36050
+ const { ssl, host } = effectiveConfig2(adminConn.clientConfig);
36051
+ const socket = !!host?.startsWith("/");
36052
+ if (!socket && !ssl) {
36053
+ warn("Warning: this database connection uses plaintext, without TLS.");
36054
+ } else if (!socket && typeof ssl === "object" && ssl.rejectUnauthorized === false) {
36055
+ warn("Warning: the database server certificate is not verified" + (adminConn.sslFallbackEnabled ? " and this connection may fall back to plaintext" : "") + ". Use sslmode=verify-full with a trusted CA to authenticate the server.");
36056
+ }
35353
36057
  if (!adminConn.sslFallbackEnabled) {
35354
36058
  const client = await tryConnect(adminConn.clientConfig);
35355
- return { client, usedSsl: !!adminConn.clientConfig.ssl };
36059
+ return { client, usedSsl: !!ssl };
35356
36060
  }
35357
36061
  try {
35358
36062
  const client = await tryConnect(adminConn.clientConfig);
35359
- return { client, usedSsl: true };
36063
+ return { client, usedSsl: !!ssl };
35360
36064
  } catch (sslErr) {
35361
36065
  if (!isSslNegotiationError2(sslErr)) {
35362
36066
  throw sslErr;
@@ -35365,9 +36069,12 @@ async function connectWithSslFallback2(ClientClass, adminConn, verbose) {
35365
36069
  console.error("SSL connection failed, retrying without SSL...");
35366
36070
  }
35367
36071
  const noSslConfig = { ...adminConn.clientConfig, ssl: false };
36072
+ const retrySsl = effectiveConfig2(noSslConfig).ssl;
35368
36073
  try {
35369
36074
  const client = await tryConnect(noSslConfig);
35370
- return { client, usedSsl: false };
36075
+ if (!retrySsl && !socket)
36076
+ warn("Warning: connected to the database without TLS after SSL negotiation failed.");
36077
+ return { client, usedSsl: !!retrySsl };
35371
36078
  } catch (noSslErr) {
35372
36079
  if (isSslNegotiationError2(noSslErr)) {
35373
36080
  const msg = noSslErr?.message || "";
@@ -35427,7 +36134,15 @@ function quoteLiteral2(value) {
35427
36134
  if (value.includes("\x00")) {
35428
36135
  throw new Error("Literal cannot contain null bytes");
35429
36136
  }
35430
- return `'${value.replace(/'/g, "''")}'`;
36137
+ const escapedQuotes = value.replace(/'/g, "''");
36138
+ return value.includes("\\") ? `E'${escapedQuotes.replace(/\\/g, "\\\\")}'` : `'${escapedQuotes}'`;
36139
+ }
36140
+ function safeDoDelimiter2(...values) {
36141
+ for (let n = 0;; n++) {
36142
+ const tag = `$pgai_do_${n}$`;
36143
+ if (values.every((value) => !value.includes(tag)))
36144
+ return tag;
36145
+ }
35431
36146
  }
35432
36147
  function redactPasswordsInSql2(sql) {
35433
36148
  return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
@@ -35669,14 +36384,16 @@ async function buildInitPlan2(params) {
35669
36384
  const iterations = Math.max(SCRAM_DEFAULT_ITERATIONS, serverIterations);
35670
36385
  const qPwVerifier = quoteLiteral2(scramSha256Verifier(params.monitoringPassword, { iterations }));
35671
36386
  const qRoleNameLit = quoteLiteral2(monitoringUser);
36387
+ const doQuote = safeDoDelimiter2(qRole, qDb, qRoleNameLit, qPwVerifier);
35672
36388
  const steps = [];
35673
36389
  const vars = {
35674
36390
  ROLE_IDENT: qRole,
35675
36391
  DB_IDENT: qDb,
35676
- ROLE_LITERAL: qRoleNameLit
36392
+ ROLE_LITERAL: qRoleNameLit,
36393
+ DO_QUOTE: doQuote
35677
36394
  };
35678
36395
  if (!SKIP_ROLE_CREATION_PROVIDERS2.includes(provider)) {
35679
- const roleStmt = `do $$ begin
36396
+ const roleStmt = `do ${doQuote} begin
35680
36397
  if not exists (select 1 from pg_catalog.pg_roles where rolname = ${qRoleNameLit}) then
35681
36398
  begin
35682
36399
  create user ${qRole} with password ${qPwVerifier};
@@ -35685,7 +36402,7 @@ async function buildInitPlan2(params) {
35685
36402
  end;
35686
36403
  end if;${params.keepExistingPassword ? "" : `
35687
36404
  alter user ${qRole} with password ${qPwVerifier};`}
35688
- end $$;`;
36405
+ end ${doQuote};`;
35689
36406
  const roleSql = applyTemplate2(loadSqlTemplate2("01.role.sql"), { ...vars, ROLE_STMT: roleStmt });
35690
36407
  steps.push({ name: "01.role", sql: roleSql });
35691
36408
  }
@@ -35789,11 +36506,13 @@ async function buildUninitPlan(params) {
35789
36506
  const qRole = quoteIdent2(monitoringUser);
35790
36507
  const qDb = quoteIdent2(database);
35791
36508
  const qRoleLiteral = quoteLiteral2(monitoringUser);
36509
+ const doQuote = safeDoDelimiter2(qRole, qDb, qRoleLiteral);
35792
36510
  const steps = [];
35793
36511
  const vars = {
35794
36512
  ROLE_IDENT: qRole,
35795
36513
  DB_IDENT: qDb,
35796
- ROLE_LITERAL: qRoleLiteral
36514
+ ROLE_LITERAL: qRoleLiteral,
36515
+ DO_QUOTE: doQuote
35797
36516
  };
35798
36517
  steps.push({
35799
36518
  name: "01.drop_helpers",
@@ -35878,6 +36597,18 @@ function roleSearchPathProblem2(spLine, extSchema) {
35878
36597
  return null;
35879
36598
  return `role search_path is ${expected.join(", ")}`;
35880
36599
  }
36600
+ async function legacyHelperWarnings(client) {
36601
+ const r = await client.query(`select
36602
+ pg_catalog.to_regprocedure('postgres_ai.explain_generic(text,text,text)') is not null as explain_generic,
36603
+ coalesce((select p.prosecdef from pg_catalog.pg_proc p
36604
+ where p.oid = pg_catalog.to_regprocedure('postgres_ai.table_describe(text)')::oid), false) as table_describe`);
36605
+ const row = r.rows?.[0];
36606
+ const legacy = [
36607
+ row?.explain_generic ? "postgres_ai.explain_generic(text, text, text)" : null,
36608
+ row?.table_describe ? "postgres_ai.table_describe(text)" : null
36609
+ ].filter((f) => f !== null);
36610
+ return legacy.map((f) => `legacy SECURITY DEFINER helper ${f} is still installed; its owner or a superuser must drop it, then re-run prepare-db`);
36611
+ }
35881
36612
  async function verifyInitSetup2(params) {
35882
36613
  await params.client.query("begin isolation level repeatable read;");
35883
36614
  try {
@@ -35958,8 +36689,11 @@ async function verifyInitSetup2(params) {
35958
36689
  missingRequired.push(problem);
35959
36690
  }
35960
36691
  }
35961
- const tableDescribeFnRes = await params.client.query("select has_function_privilege($1, 'postgres_ai.table_describe(text)', 'EXECUTE') as ok", [role]);
35962
- if (!tableDescribeFnRes.rows?.[0]?.ok) {
36692
+ const tableDescribeFnRes = await params.client.query(`select case when pg_catalog.to_regprocedure('postgres_ai.table_describe(text)') is not null
36693
+ then has_function_privilege($1, 'postgres_ai.table_describe(text)', 'EXECUTE') end as ok`, [role]);
36694
+ if (tableDescribeFnRes.rows?.[0]?.ok === null) {
36695
+ missingRequired.push("function postgres_ai.table_describe(text) exists");
36696
+ } else if (!tableDescribeFnRes.rows?.[0]?.ok) {
35963
36697
  missingRequired.push("EXECUTE on postgres_ai.table_describe(text)");
35964
36698
  }
35965
36699
  if (params.includeOptionalPermissions) {
@@ -36142,7 +36876,7 @@ Alternatively, run 'postgresai prepare-db' to set up permissions automatically.`
36142
36876
  }
36143
36877
 
36144
36878
  // lib/supabase.ts
36145
- var SUPABASE_API_BASE = "https://api.supabase.com";
36879
+ var SUPABASE_API_BASE2 = "https://api.supabase.com";
36146
36880
  var SUPABASE_POOLER_TRANSACTION_PORT = 6543;
36147
36881
  var SUPABASE_POOLER_SESSION_PORT = 5432;
36148
36882
  var SUPABASE_POOLER_HOST_SUFFIX = "pooler.supabase.com";
@@ -36172,7 +36906,7 @@ class SupabaseClient {
36172
36906
  this.config = config;
36173
36907
  }
36174
36908
  async query(sql, readOnly = false) {
36175
- const url = `${SUPABASE_API_BASE}/v1/projects/${encodeURIComponent(this.config.projectRef)}/database/query`;
36909
+ const url = `${SUPABASE_API_BASE2}/v1/projects/${encodeURIComponent(this.config.projectRef)}/database/query`;
36176
36910
  const response = await fetch(url, {
36177
36911
  method: "POST",
36178
36912
  headers: {
@@ -36315,7 +37049,7 @@ async function fetchPoolerDatabaseUrl(config, username) {
36315
37049
  if (!isValidProjectRef(config.projectRef)) {
36316
37050
  throw new Error(`Invalid Supabase project reference format: "${config.projectRef}". Expected 10-30 alphanumeric characters.`);
36317
37051
  }
36318
- const url = `${SUPABASE_API_BASE}/v1/projects/${encodeURIComponent(config.projectRef)}/config/database/pooler`;
37052
+ const url = `${SUPABASE_API_BASE2}/v1/projects/${encodeURIComponent(config.projectRef)}/config/database/pooler`;
36319
37053
  const suffix = `.${config.projectRef}`;
36320
37054
  const effectiveUsername = username.endsWith(suffix) ? username : `${username}${suffix}`;
36321
37055
  const encodedUsername = encodeURIComponent(effectiveUsername);
@@ -36366,7 +37100,7 @@ function resolveSupabaseConfig(opts) {
36366
37100
  }
36367
37101
  return { accessToken, projectRef };
36368
37102
  }
36369
- function extractProjectRefFromUrl(dbUrl) {
37103
+ function extractProjectRefFromUrl2(dbUrl) {
36370
37104
  try {
36371
37105
  const url = new URL(dbUrl);
36372
37106
  const host = url.hostname;
@@ -44500,7 +45234,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44500
45234
  try {
44501
45235
  let projectRef = opts.supabaseProjectRef;
44502
45236
  if (!projectRef && conn) {
44503
- projectRef = extractProjectRefFromUrl(conn);
45237
+ projectRef = extractProjectRefFromUrl2(conn);
44504
45238
  }
44505
45239
  supabaseConfig = resolveSupabaseConfig({
44506
45240
  accessToken: opts.supabaseAccessToken,
@@ -44537,6 +45271,11 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44537
45271
  monitoringUser: opts.monitoringUser,
44538
45272
  includeOptionalPermissions
44539
45273
  });
45274
+ const legacyFailures = await legacyHelperWarnings(supabaseClient);
45275
+ if (legacyFailures.length > 0) {
45276
+ v.missingRequired.push(...legacyFailures);
45277
+ v.ok = false;
45278
+ }
44540
45279
  if (v.ok) {
44541
45280
  if (jsonOutput) {
44542
45281
  const result = {
@@ -44659,6 +45398,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44659
45398
  client: supabaseClient,
44660
45399
  plan: effectivePlan
44661
45400
  });
45401
+ const legacyWarnings = await legacyHelperWarnings(supabaseClient);
44662
45402
  if (jsonOutput) {
44663
45403
  const result = {
44664
45404
  success: true,
@@ -44668,7 +45408,10 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44668
45408
  monitoringUser: opts.monitoringUser,
44669
45409
  applied,
44670
45410
  skippedOptional,
44671
- warnings: skippedOptional.length > 0 ? ["Some optional steps were skipped (not supported or insufficient privileges)"] : []
45411
+ warnings: [
45412
+ ...skippedOptional.length > 0 ? ["Some optional steps were skipped (not supported or insufficient privileges)"] : [],
45413
+ ...legacyWarnings
45414
+ ]
44672
45415
  };
44673
45416
  if (passwordGenerated) {
44674
45417
  result.generatedPassword = monPassword;
@@ -44684,6 +45427,8 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44684
45427
  for (const s of skippedOptional)
44685
45428
  console.error(`- ${s}`);
44686
45429
  }
45430
+ for (const w of legacyWarnings)
45431
+ console.error(`\u26A0 ${w}`);
44687
45432
  if (process.stdout.isTTY) {
44688
45433
  console.log(`Applied ${applied.length} steps`);
44689
45434
  }
@@ -44825,6 +45570,11 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44825
45570
  includeOptionalPermissions,
44826
45571
  provider
44827
45572
  });
45573
+ const legacyFailures = await legacyHelperWarnings(client);
45574
+ if (legacyFailures.length > 0) {
45575
+ v.missingRequired.push(...legacyFailures);
45576
+ v.ok = false;
45577
+ }
44828
45578
  if (v.ok) {
44829
45579
  if (jsonOutput) {
44830
45580
  outputJson({
@@ -44943,6 +45693,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44943
45693
  return;
44944
45694
  }
44945
45695
  const { applied, skippedOptional } = await applyInitPlan2({ client, plan: effectivePlan });
45696
+ const legacyWarnings = await legacyHelperWarnings(client);
44946
45697
  if (jsonOutput) {
44947
45698
  const result = {
44948
45699
  success: true,
@@ -44952,7 +45703,10 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44952
45703
  monitoringUser: opts.monitoringUser,
44953
45704
  applied,
44954
45705
  skippedOptional,
44955
- warnings: skippedOptional.length > 0 ? ["Some optional steps were skipped (not supported or insufficient privileges)"] : []
45706
+ warnings: [
45707
+ ...skippedOptional.length > 0 ? ["Some optional steps were skipped (not supported or insufficient privileges)"] : [],
45708
+ ...legacyWarnings
45709
+ ]
44956
45710
  };
44957
45711
  if (passwordGenerated) {
44958
45712
  result.generatedPassword = monPassword;
@@ -44965,6 +45719,8 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44965
45719
  for (const s of skippedOptional)
44966
45720
  console.error(`- ${s}`);
44967
45721
  }
45722
+ for (const w of legacyWarnings)
45723
+ console.error(`\u26A0 ${w}`);
44968
45724
  if (process.stdout.isTTY) {
44969
45725
  console.log(`Applied ${applied.length} steps`);
44970
45726
  }
@@ -44984,6 +45740,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44984
45740
  }
44985
45741
  const stepMatch = typeof message === "string" ? message.match(/Failed at step "([^"]+)":/i) : null;
44986
45742
  const failedStep = stepMatch?.[1];
45743
+ const legacyWarnings = failedStep && client ? await legacyHelperWarnings(client).catch(() => []) : [];
44987
45744
  const errorObj = { message };
44988
45745
  if (failedStep)
44989
45746
  errorObj.step = failedStep;
@@ -44999,7 +45756,8 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44999
45756
  outputJson({
45000
45757
  success: false,
45001
45758
  mode: "direct",
45002
- error: errorObj
45759
+ error: errorObj,
45760
+ ...legacyWarnings.length > 0 ? { warnings: legacyWarnings } : {}
45003
45761
  });
45004
45762
  process.exitCode = 1;
45005
45763
  } else {
@@ -45018,6 +45776,8 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
45018
45776
  console.error(` Hint: ${errAny.hint}`);
45019
45777
  }
45020
45778
  }
45779
+ for (const w of legacyWarnings)
45780
+ console.error(`\u26A0 ${w}`);
45021
45781
  if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
45022
45782
  if (errAny.code === "42501") {
45023
45783
  if (failedStep === "01.role") {
@@ -45404,7 +46164,11 @@ Usage: postgresai checkup ${checkId} postgresql://user@host:5432/dbname
45404
46164
  const spinner = createTtySpinner(spinnerEnabled, "Connecting to Postgres");
45405
46165
  try {
45406
46166
  spinner.update("Connecting to Postgres");
45407
- const connResult = await connectWithSslFallback2(Client, adminConn);
46167
+ const connResult = await connectWithSslFallback2(Client, adminConn, false, (message) => {
46168
+ if (spinnerEnabled)
46169
+ process.stdout.write("\r\x1B[2K");
46170
+ console.error(message);
46171
+ });
45408
46172
  client = connResult.client;
45409
46173
  spinner.update("Checking database permissions");
45410
46174
  try {
@@ -46167,6 +46931,12 @@ async function inspectInstanceJobsState() {
46167
46931
  return /no such (object|container)/i.test(text) ? "absent" : "unknown";
46168
46932
  }
46169
46933
  }
46934
+ function openInBrowser(url) {
46935
+ const openCommand = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
46936
+ const browserProcess = spawn3(openCommand, [url], { detached: true, stdio: "ignore" });
46937
+ browserProcess.on("error", () => {});
46938
+ browserProcess.unref();
46939
+ }
46170
46940
  var CONNECT_EXIT = DEPLOY_EXIT2;
46171
46941
  function cloudApi(debug) {
46172
46942
  const rootOpts = program2.opts();
@@ -46174,7 +46944,7 @@ function cloudApi(debug) {
46174
46944
  const urls = resolveBaseUrls2(rootOpts, readConfig());
46175
46945
  return { apiKey, apiBaseUrl: urls.apiBaseUrl, ...platformDeps2({ apiKey, ...urls, orgScope: getActiveOrgScope2(), debug }) };
46176
46946
  }
46177
- function emitConnect(result, json) {
46947
+ function emitConnect(result, json, done = false) {
46178
46948
  if (!jsonOutput3(json)) {
46179
46949
  if (result.sql)
46180
46950
  console.log(`${result.sql}
@@ -46185,9 +46955,16 @@ function emitConnect(result, json) {
46185
46955
  out(line);
46186
46956
  } else {
46187
46957
  printResult(result, json);
46958
+ if (done)
46959
+ writeEvent2({ event: "done", status: result.status, ...result.id ? { id: result.id } : {}, next: result.next });
46188
46960
  }
46189
46961
  process.exitCode = CONNECT_EXIT[result.status];
46190
46962
  }
46963
+ function optionError(result, json) {
46964
+ if (jsonOutput3(json))
46965
+ console.error(result.next);
46966
+ emitConnect(result, json);
46967
+ }
46191
46968
  function failCloud(err, json) {
46192
46969
  printResult({ status: "failed", next: errorText2(err) }, json);
46193
46970
  process.exitCode = 1;
@@ -46212,50 +46989,54 @@ Resume: ${resume}`);
46212
46989
  return () => process.removeListener("SIGINT", onSigint);
46213
46990
  }
46214
46991
  async function runConnect(urlArg, opts) {
46215
- let url;
46216
- try {
46217
- url = databaseUrlArg2(urlArg, opts.dbUrl, "pgai mon deploy");
46218
- } catch (err) {
46219
- return emitConnect({ status: "failed", provider: "self-managed", name: "", next: errorText2(err) }, opts.json);
46992
+ const explicit = providerArg2(opts.provider);
46993
+ const projectMode = !urlArg?.trim() && !opts.dbUrl?.trim() && (explicit === "supabase" || !explicit && !!opts.supabaseProject?.trim());
46994
+ let url = "";
46995
+ if (!projectMode) {
46996
+ try {
46997
+ url = databaseUrlArg2(urlArg, opts.dbUrl, "pgai mon deploy");
46998
+ } catch (err) {
46999
+ return optionError({ status: "failed", provider: "self-managed", name: "", next: errorText2(err) }, opts.json);
47000
+ }
46220
47001
  }
46221
47002
  const json = jsonOutput3(opts.json);
46222
- const name = (() => {
47003
+ const name = projectMode ? "" : (() => {
46223
47004
  try {
46224
47005
  return databaseName3(url);
46225
47006
  } catch {
46226
47007
  return "";
46227
47008
  }
46228
47009
  })();
46229
- if (!name || !/^postgres(ql)?:\/\//.test(url)) {
46230
- return emitConnect({ status: "failed", provider: "self-managed", name, next: "Pass a URL: pgai mon deploy postgresql://user:password@host:5432/dbname" }, opts.json);
47010
+ if (!projectMode && (!name || !/^postgres(ql)?:\/\//.test(url))) {
47011
+ return optionError({ status: "failed", provider: "self-managed", name, next: "Pass a URL: pgai mon deploy postgresql://user:password@host:5432/dbname" }, opts.json);
46231
47012
  }
46232
- const explicit = providerArg2(opts.provider);
46233
- const provider = PROVIDERS2.find((p) => p === explicit) ?? detectCloudProvider2(url);
47013
+ const provider = projectMode ? "supabase" : PROVIDERS2.find((p) => p === explicit) ?? detectCloudProvider2(url);
46234
47014
  let minutes;
46235
47015
  try {
46236
47016
  minutes = waitMinutes2(opts.wait, 20);
46237
47017
  } catch (err) {
46238
- return emitConnect({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
47018
+ return optionError({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
46239
47019
  }
46240
47020
  let vcpus;
46241
47021
  try {
46242
47022
  vcpus = vcpusArg2(opts.vcpus);
46243
47023
  } catch (err) {
46244
- return emitConnect({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
47024
+ return optionError({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
46245
47025
  }
46246
47026
  let shownView;
46247
47027
  try {
46248
47028
  if (!opts.selfHosted && !signedIn(opts)) {
46249
- return emitConnect({ status: "action_required", provider, name, next: "Sign in: pgai auth login (agents: set PGAI_API_KEY), then re-run" }, opts.json);
47029
+ return emitConnect({ status: "action_required", provider, name, next: "Sign in: pgai auth login (agents: set PGAI_API_KEY), then re-run" }, opts.json, true);
46250
47030
  }
46251
47031
  const api = cloudApi(opts.debug);
47032
+ let shownName = name;
46252
47033
  const tty = !json && !!process.stderr.isTTY && !process.env.CI && process.env.TERM !== "dumb";
46253
47034
  let createdId;
46254
47035
  let stopping = false;
46255
47036
  const steps = stepProgress({
46256
47037
  json,
46257
47038
  tty,
46258
- makeView: () => new StepView2(`Deploying monitoring for ${name}`, MONITORING_STEPS, true),
47039
+ makeView: () => new StepView2(`Deploying monitoring for ${shownName || "the Supabase project"}`, monitoringSteps(provider), true),
46259
47040
  writeLine: (line) => console.error(line),
46260
47041
  writeEvent: writeEvent2,
46261
47042
  onId: (id) => {
@@ -46270,14 +47051,25 @@ Stopped watching. The deploy continues on PostgresAI.
46270
47051
  Resume: pgai mon instances watch ${createdId}`);
46271
47052
  process.exit(130);
46272
47053
  };
47054
+ let requested = false;
46273
47055
  const onSigint = () => {
46274
47056
  if (createdId)
46275
47057
  return resume();
46276
- if (stopping)
47058
+ if (stopping) {
47059
+ steps.view()?.stop();
47060
+ if (requested)
47061
+ console.error(`
47062
+ Quit. The monitoring box may exist: pgai mon instances list`);
46277
47063
  process.exit(130);
47064
+ }
46278
47065
  stopping = true;
46279
- console.error(`
46280
- Cancelling: nothing has been created yet (Ctrl-C again to quit now).`);
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).";
47067
+ const view = steps.view();
47068
+ if (view)
47069
+ view.log(reply);
47070
+ else
47071
+ console.error(`
47072
+ ${reply}`);
46281
47073
  };
46282
47074
  process.on("SIGINT", onSigint);
46283
47075
  let result;
@@ -46323,7 +47115,39 @@ Cancelling: nothing has been created yet (Ctrl-C again to quit now).`);
46323
47115
  closeReadline();
46324
47116
  }
46325
47117
  },
46326
- progress: steps.progress,
47118
+ ...interactive(opts.json) ? { chooseSupabaseProject: async (projects, org) => {
47119
+ const selectable = projects.filter((x) => x.selectable);
47120
+ console.error(terminalText2(`
47121
+ Projects in the Supabase organization "${org}":`));
47122
+ for (const line of supabaseProjectRows(projects, true))
47123
+ console.error(terminalText2(line));
47124
+ if (!selectable.length)
47125
+ return;
47126
+ process.exitCode = 130;
47127
+ try {
47128
+ for (let tries = 0;tries < 3; tries++) {
47129
+ const answer = (await question(`Project to monitor (1-${selectable.length}, Enter to cancel): `)).trim();
47130
+ if (!answer)
47131
+ return;
47132
+ const i = Number(answer);
47133
+ if (Number.isInteger(i) && i >= 1 && i <= selectable.length)
47134
+ return selectable[i - 1].ref;
47135
+ console.error(`Type a number from 1 to ${selectable.length}.`);
47136
+ }
47137
+ return;
47138
+ } finally {
47139
+ process.exitCode = undefined;
47140
+ closeReadline();
47141
+ }
47142
+ } } : {},
47143
+ ...interactive(opts.json) ? { openUrl: openInBrowser } : {},
47144
+ progress: (e) => {
47145
+ if (e.event === "provisioning")
47146
+ requested = true;
47147
+ if (e.project)
47148
+ shownName = terminalText2(e.project);
47149
+ steps.progress(e);
47150
+ },
46327
47151
  aborted: () => stopping
46328
47152
  });
46329
47153
  } catch (err) {
@@ -46337,28 +47161,30 @@ Cancelling: nothing has been created yet (Ctrl-C again to quit now).`);
46337
47161
  } finally {
46338
47162
  process.removeListener("SIGINT", onSigint);
46339
47163
  }
47164
+ if (stopping && !createdId && result.status === "in_progress")
47165
+ createdId = result.id;
46340
47166
  if (stopping && createdId)
46341
47167
  return resume();
46342
47168
  const view = steps.view();
46343
47169
  if (view) {
46344
47170
  if (result.status === "ready")
46345
47171
  view.complete();
46346
- else if (result.status !== "in_progress")
47172
+ else if (result.status !== "in_progress" && !result.next.startsWith(STILL_IN_PROGRESS2))
46347
47173
  view.fail();
46348
47174
  view.stop();
46349
47175
  }
46350
- emitConnect(result, opts.json);
47176
+ emitConnect(result, opts.json, true);
46351
47177
  } catch (err) {
46352
47178
  const view = shownView?.();
46353
47179
  if (view) {
46354
47180
  view.fail();
46355
47181
  view.stop();
46356
47182
  }
46357
- emitConnect({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
47183
+ emitConnect({ status: "failed", provider, name, next: errorText2(err) }, opts.json, true);
46358
47184
  }
46359
47185
  }
46360
47186
  var mon = program2.command("mon").description("monitoring services management");
46361
- 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", [
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", [
46362
47188
  "",
46363
47189
  "Steps (each skipped when already done; safe to re-run): sign in, prepare the database",
46364
47190
  "(an admin URL creates the postgres_ai_mon role; otherwise the SQL is printed), provision",
@@ -46376,12 +47202,26 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
46376
47202
  "box is provisioned only when accepted: at the prompt, or with --yes. With no payment method",
46377
47203
  "it stops (exit 3) and names the console page to add one. --coupon applies a promotion code.",
46378
47204
  "",
46379
- 'Exit codes: 0 ready or in progress, 1 failed, 3 action required (see "next").',
47205
+ "Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API (the",
47206
+ "database password is not needed and not sent). The first time, the organization connects",
47207
+ "Supabase: deploy opens the consent page in the browser (the link is printed too, to open",
47208
+ 'it elsewhere; "auth_url" in the JSON event) and waits for the approval, up to 10 minutes.',
47209
+ 'With --wait 0, and for agents, it stops there (exit 3) with the link in "next".',
47210
+ "No URL needed: pgai mon deploy --provider supabase lists the projects of the connected",
47211
+ "Supabase organization to pick one at a terminal; --supabase-project <name|project-id> picks it",
47212
+ "for agents and scripts. Without either, and not at a terminal, it stops (exit 3) with the list",
47213
+ `("projects" in the JSON result). Paused and not-ready projects are listed but can't be`,
47214
+ "picked; an already-monitored one returns its monitoring.",
47215
+ "",
47216
+ "Exit codes: 0 ready (or in progress with --no-wait), 1 failed, 3 action required (see",
47217
+ '"next"), also when the wait ends before the box is ready.',
46380
47218
  "",
46381
47219
  "JSON output (--json): stdout is the result; stderr is one JSON event a",
46382
47220
  'line: the steps, and {"event":"log","level":"error"|"warn"|"info"|"debug","message":...}',
46383
47221
  'for any other text (an error, a warning, --debug); "source":"mon local-install" for that',
46384
47222
  "child's lines (the logins it prints are masked: pgai mon show-grafana-credentials shows them).",
47223
+ 'The last event of a run is {"event":"done","status":...,"next":...}; not after Ctrl-C (exit 130)',
47224
+ "or an error in the options or --org before the run starts (an error event, exit 1).",
46385
47225
  "",
46386
47226
  "Environment: PGAI_API_KEY (instead of signing in), PGAI_MON_PASSWORD (the password of",
46387
47227
  "postgres_ai_mon when the role already exists; it is checked, never changed; not needed",
@@ -46393,11 +47233,16 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
46393
47233
  "Examples:",
46394
47234
  " pgai mon deploy 'postgresql://postgres:<password>@<host>.pg.clickhouse.cloud:5432/postgres?sslmode=require'",
46395
47235
  " CLICKHOUSE_KEY_ID=... CLICKHOUSE_KEY_SECRET=... pgai mon deploy '<url>'",
47236
+ " pgai mon deploy --provider supabase",
47237
+ " pgai mon deploy --supabase-project <name|project-id> --yes --json",
47238
+ " pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres'",
46396
47239
  " pgai mon deploy '<url>' --self-hosted"
46397
47240
  ].join(`
46398
47241
  `)).action((urlArg, opts, cmd) => {
46399
- if (!urlArg?.trim() && !opts.dbUrl?.trim())
46400
- return cmd.error("error: missing required argument 'database-url'");
47242
+ const supabase = providerArg2(opts.provider) === "supabase" || !opts.provider && !!opts.supabaseProject?.trim();
47243
+ if (!urlArg?.trim() && !opts.dbUrl?.trim() && !supabase) {
47244
+ return cmd.error("error: missing required argument 'database-url' (or --provider supabase to pick a Supabase project)");
47245
+ }
46401
47246
  return runConnect(urlArg, opts);
46402
47247
  });
46403
47248
  var interactive = (json) => !!process.stdin.isTTY && !!process.stdout.isTTY && !json;
@@ -47512,7 +48357,7 @@ async function setUpHostMetrics(projectDir, instance, connStr, env, apply) {
47512
48357
  console.log(message);
47513
48358
  return true;
47514
48359
  }
47515
- const projectRef = extractProjectRefFromUrl(connStr);
48360
+ const projectRef = extractProjectRefFromUrl2(connStr);
47516
48361
  if (projectRef) {
47517
48362
  const on = supabaseHostMetricsOn(projectDir, env);
47518
48363
  if (on && !SUPABASE_TARGET_NAME_RE.test(name))
@@ -47598,7 +48443,7 @@ async function addTarget(file, projectDir, connStr, name, env, { apply = true, v
47598
48443
  return false;
47599
48444
  }
47600
48445
  const instanceName = name && name.trim() ? name.trim() : defaultName.name;
47601
- if (detectProvider(connStr) !== "clickhouse" && extractProjectRefFromUrl(connStr) && supabaseHostMetricsOn(projectDir, env) && !SUPABASE_TARGET_NAME_RE.test(instanceName)) {
48446
+ if (detectProvider(connStr) !== "clickhouse" && extractProjectRefFromUrl2(connStr) && supabaseHostMetricsOn(projectDir, env) && !SUPABASE_TARGET_NAME_RE.test(instanceName)) {
47602
48447
  console.error(SUPABASE_TARGET_NAME_ERROR);
47603
48448
  process.exitCode = 1;
47604
48449
  return false;
@@ -47923,10 +48768,7 @@ Opening browser for authentication...`);
47923
48768
  console.log(`If browser does not open automatically, visit:
47924
48769
  ${authUrl}
47925
48770
  `);
47926
- const openCommand = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
47927
- const browserProcess = spawn3(openCommand, [authUrl], { detached: true, stdio: "ignore" });
47928
- browserProcess.on("error", () => {});
47929
- browserProcess.unref();
48771
+ openInBrowser(authUrl);
47930
48772
  console.log("Waiting for authorization...");
47931
48773
  console.log(`(Press Ctrl+C to cancel)
47932
48774
  `);