postgresai 0.18.0-dev.10 → 0.18.0-dev.11

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.11",
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.11";
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;
@@ -22955,11 +23017,25 @@ async function billingFor(q, name, opts, deps, show) {
22955
23017
  }
22956
23018
  async function connect(url, opts, deps) {
22957
23019
  const started = deps.now();
22958
- const progress = (event, message, more = {}) => deps.progress({ event, elapsed_s: Math.round((deps.now() - started) / 1000), message, ...more });
23020
+ let step = "preparing";
23021
+ const progress = (event, message, more = {}) => {
23022
+ if (event !== "billing")
23023
+ step = event;
23024
+ deps.progress({ event, elapsed_s: Math.round((deps.now() - started) / 1000), message, ...more });
23025
+ };
23026
+ const warned = new Set;
23027
+ const warn = (message) => {
23028
+ if (warned.has(message))
23029
+ return;
23030
+ warned.add(message);
23031
+ progress(step, message);
23032
+ };
22959
23033
  const provider = providerArg(opts.provider) ?? detectCloudProvider(url);
22960
23034
  if (!PROVIDERS.includes(provider))
22961
23035
  throw new Error(`--provider must be one of: generic, ${PROVIDERS.join(", ")}`);
22962
23036
  assertEncodedUserinfo(url);
23037
+ if (!opts.selfHosted && provider === "supabase")
23038
+ return deploySupabase(url, opts, deps, progress);
22963
23039
  checkUrlParams(url, opts.agent);
22964
23040
  const name = databaseName2(url);
22965
23041
  const asked = opts.monitoringUser?.trim();
@@ -22991,7 +23067,7 @@ async function connect(url, opts, deps) {
22991
23067
  const key = parseClickhouseKey(opts.clickhouseKey, provider === "clickhouse" && !opts.agent ? process.env : {});
22992
23068
  if (key && provider !== "clickhouse")
22993
23069
  throw new Error("--clickhouse-key applies to ClickHouse Managed Postgres only");
22994
- if (!opts.selfHosted && (provider === "rds" || provider === "supabase")) {
23070
+ if (!opts.selfHosted && provider === "rds") {
22995
23071
  const ignored = monitoringUser ? ` (${opts.agent ? "monitoring_user" : "--monitoring-user"} is not used there)` : "";
22996
23072
  return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}${ignored}` };
22997
23073
  }
@@ -23069,7 +23145,7 @@ async function connect(url, opts, deps) {
23069
23145
  }
23070
23146
  const undo = async (p) => {
23071
23147
  if ("generated" in p && p.generated)
23072
- await deps.unprepare(url, monitoringUser).catch(() => false);
23148
+ await deps.unprepare(url, monitoringUser, { warn }).catch(() => false);
23073
23149
  };
23074
23150
  let lockId;
23075
23151
  const unread = (d) => !d.cluster;
@@ -23093,7 +23169,7 @@ async function connect(url, opts, deps) {
23093
23169
  if (opts.coupon !== undefined && !opts.coupon.trim()) {
23094
23170
  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
23171
  }
23096
- const prepOpts = { resetPassword: opts.resetPassword, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
23172
+ const prepOpts = { resetPassword: opts.resetPassword, warn, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
23097
23173
  if (!opts.selfHosted) {
23098
23174
  const probe = await deps.prepare(url, provider, { ...prepOpts, check: true }).catch((err) => {
23099
23175
  if (err instanceof HttpStatusError || /Could not connect to/.test(errorText(err)))
@@ -23227,6 +23303,124 @@ async function connect(url, opts, deps) {
23227
23303
  const made = prepared;
23228
23304
  undoRole = () => undo(made);
23229
23305
  }
23306
+ return follow(row, { provider, name, fresh, billing, billingUrl, undoRole, note }, opts, deps, progress);
23307
+ }
23308
+ var isSupabaseUrl = (link) => {
23309
+ try {
23310
+ const u = new URL(link);
23311
+ return u.origin === SUPABASE_API_BASE && !u.username && !u.password;
23312
+ } catch {
23313
+ return false;
23314
+ }
23315
+ };
23316
+ var OAUTH_WAIT_MS = 10 * 60000;
23317
+ var OAUTH_POLL_MS = 2000;
23318
+ async function deploySupabase(url, opts, deps, progress) {
23319
+ const provider = "supabase";
23320
+ const ref = extractProjectRefFromUrl(url);
23321
+ if (!ref)
23322
+ return { status: "action_required", provider, name: databaseName2(url), next: "Not a Supabase project URL: use the project's connection string (db.<project-ref>.supabase.co, or the pooler with user postgres.<project-ref>)" };
23323
+ const db = decodeURIComponent(new URL(url).pathname.replace(/^\//, "")) || "postgres";
23324
+ const project = `postgresql://db.${ref}.supabase.co:5432/${encodeURIComponent(db)}`;
23325
+ const name = databaseName2(project);
23326
+ const cluster = clusterOf(project);
23327
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
23328
+ if (db !== "postgres")
23329
+ return stop("PostgresAI monitors a Supabase project through its postgres database: use the URL of the postgres database");
23330
+ if (opts.resetPassword)
23331
+ return stop("--reset-password does not apply to Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API");
23332
+ if (opts.location)
23333
+ return stop("--location does not apply to Supabase yet (PostgresAI picks the box's location): re-run without it");
23334
+ if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
23335
+ return stop(`${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`);
23336
+ }
23337
+ const row = (await deps.list()).find((d) => !disconnecting(d.status) && d.cluster && serverOf(d.cluster) === cluster && (!d.database || d.database === "postgres"));
23338
+ if (row) {
23339
+ const note = opts.name && row.name !== opts.name ? `; --name ignored: this database is already monitored as ${row.name}` : "";
23340
+ return follow(row, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
23341
+ }
23342
+ let started;
23343
+ try {
23344
+ started = await deps.supabaseStart(project);
23345
+ } catch (err) {
23346
+ if (err instanceof HttpStatusError && err.status === 403)
23347
+ return stop(notAdminNext);
23348
+ if (err instanceof HttpStatusError && err.status === 409)
23349
+ return stop(errorText(err));
23350
+ throw err;
23351
+ }
23352
+ if ("auth_url" in started) {
23353
+ if (!isSupabaseUrl(started.auth_url))
23354
+ return { status: "failed", provider, name, next: `The platform sent a Supabase consent link that is not ${SUPABASE_API_BASE}: not opened. Re-run pgai mon deploy later.` };
23355
+ const approve = `Open ${started.auth_url} in a browser and approve PostgresAI's access to Supabase`;
23356
+ if (opts.agent || opts.waitMs <= 0)
23357
+ return stop(`${approve}, then ${opts.agent ? "call deploy_monitoring again" : "re-run"}`);
23358
+ progress("preparing", `Connect Supabase to PostgresAI: approve access in the browser (open ${started.auth_url} if it did not open). Waiting...`, { auth_url: started.auth_url });
23359
+ deps.openUrl?.(started.auth_url);
23360
+ const expires = started.expires_at ? Date.parse(started.expires_at) : NaN;
23361
+ for (const deadline = deps.now() + Math.min(opts.waitMs, OAUTH_WAIT_MS);; ) {
23362
+ if (deps.aborted?.())
23363
+ throw new CancelledError;
23364
+ const s = await deps.supabaseStatus(started.session_id);
23365
+ if (s.status === "connected")
23366
+ break;
23367
+ if (s.status === "error")
23368
+ return stop(`Supabase did not connect (${s.error ?? "no reason given"}): re-run to try again`);
23369
+ const now = deps.now();
23370
+ if (now >= expires)
23371
+ return stop("The Supabase consent link expired before it was approved: re-run pgai mon deploy for a new one");
23372
+ if (now >= deadline)
23373
+ return stop(`${approve}, then re-run`);
23374
+ await deps.sleep(OAUTH_POLL_MS);
23375
+ }
23376
+ }
23377
+ let quote;
23378
+ try {
23379
+ quote = await deps.quote(opts.coupon);
23380
+ } catch (err) {
23381
+ if (err instanceof HttpStatusError && err.status === 403)
23382
+ return stop(notAdminNext);
23383
+ throw err;
23384
+ }
23385
+ const b = await billingFor(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)));
23386
+ if (b.stop)
23387
+ return { status: "action_required", provider, name, ...b.stop };
23388
+ if (deps.aborted?.())
23389
+ throw new CancelledError;
23390
+ progress("provisioning", `Provisioning monitoring for ${name}`);
23391
+ const created = await deps.supabaseConnect({
23392
+ project_ref: ref,
23393
+ ...opts.name ? { name: opts.name } : {},
23394
+ ...b.accepted ? { accept_price: true } : {},
23395
+ ...opts.coupon ? { promo_code: opts.coupon } : {},
23396
+ ...opts.vcpus ? { vcpus: opts.vcpus } : {}
23397
+ }).catch((err) => {
23398
+ if (err instanceof HttpStatusError && err.status === 402)
23399
+ return /declined/i.test(err.message) ? "declined" : "payment";
23400
+ if (err instanceof HttpStatusError && err.status === 412)
23401
+ return "price";
23402
+ if (err instanceof HttpStatusError && err.status === 409)
23403
+ return { refused: errorText(err) };
23404
+ throw err;
23405
+ });
23406
+ if (typeof created === "object" && "refused" in created)
23407
+ return stop(created.refused);
23408
+ if (created === "payment")
23409
+ return { status: "action_required", provider, name, ...b.billingPage };
23410
+ if (created === "declined")
23411
+ 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 ") };
23412
+ if (created === "price")
23413
+ return stop("The price changed since it was shown: re-run pgai mon deploy to see it", b.billing);
23414
+ if (created.status === "failed")
23415
+ return { status: "failed", provider, name, id: created.id, ...b.billing, next: `${created.error} Re-run pgai mon deploy later.` };
23416
+ const box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: false };
23417
+ if (deps.aborted?.())
23418
+ return { ...connectStatus(box, provider, true), ...b.billing };
23419
+ return follow(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "" }, opts, deps, progress);
23420
+ }
23421
+ var STILL_IN_PROGRESS = "Still in progress";
23422
+ async function follow(row, f, opts, deps, progress) {
23423
+ const { provider, name, fresh, billing, billingUrl, undoRole, note } = f;
23230
23424
  let shown;
23231
23425
  for (const deadline = deps.now() + opts.waitMs;; ) {
23232
23426
  if (row.billing_error && disconnecting(row.status)) {
@@ -23252,6 +23446,14 @@ async function connect(url, opts, deps) {
23252
23446
  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
23447
  }
23254
23448
  const { next, ...rest } = final;
23449
+ if (final.status === "in_progress" && opts.waitMs > 0) {
23450
+ return {
23451
+ ...rest,
23452
+ status: "action_required",
23453
+ ...billing,
23454
+ next: `${STILL_IN_PROGRESS} (box: ${boxWords(boxState(row))}) when the wait ended: resume with ${next}${note}`
23455
+ };
23456
+ }
23255
23457
  return { ...rest, ...billing, next: next + note };
23256
23458
  }
23257
23459
  await deps.sleep(POLL_MS);
@@ -23259,8 +23461,9 @@ async function connect(url, opts, deps) {
23259
23461
  return;
23260
23462
  });
23261
23463
  const now = listed?.find((d) => d.id === row.id);
23262
- if (listed && !now && undoRole) {
23263
- await undoRole();
23464
+ if (listed && !now && fresh) {
23465
+ if (undoRole)
23466
+ await undoRole();
23264
23467
  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
23468
  }
23266
23469
  row = now ?? row;
@@ -23274,7 +23477,7 @@ async function openConnection(url, opts) {
23274
23477
  conn.clientConfig = { ...config, ...explicit };
23275
23478
  }
23276
23479
  const fallback = !opts.agent && !!conn.sslFallbackEnabled;
23277
- const { client, usedSsl } = await connectWithSslFallback(opts.Client ?? Client2, { ...conn, sslFallbackEnabled: fallback });
23480
+ const { client, usedSsl } = await connectWithSslFallback(opts.Client ?? Client2, { ...conn, sslFallbackEnabled: fallback }, false, opts.warn);
23278
23481
  await client.query("set search_path = pg_catalog, pg_temp");
23279
23482
  return { client, usedSsl, refusedTls: fallback && !usedSsl };
23280
23483
  }
@@ -23539,10 +23742,13 @@ function platformDeps(p) {
23539
23742
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
23540
23743
  resetUnlock: (lockId) => rpc("cloud_monitoring_reset_unlock", { lock_id: lockId }),
23541
23744
  prepare: (url, provider, o = {}) => prepareDatabase(url, provider, { ...o, agent: p.agent }),
23542
- unprepare: (url, monitoringUser) => unprepareDatabase(url, { agent: p.agent, monitoringUser }),
23745
+ unprepare: (url, monitoringUser, o = {}) => unprepareDatabase(url, { ...o, agent: p.agent, monitoringUser }),
23543
23746
  clickhouseOrg: clickhouseOrgFor,
23544
23747
  quote: (coupon, cluster) => rpc("cloud_monitoring_quote", { ...coupon ? { promo_code: coupon } : {}, ...cluster ? { db_server: cluster } : {} }),
23545
23748
  billingUrl: (orgAlias) => `${p.uiBaseUrl}/${orgAlias}/billing`,
23749
+ supabaseStart: (dbUrl) => rpc("cloud_monitoring_supabase_start", { db_url: dbUrl }),
23750
+ supabaseStatus: (sessionId) => rpc("cloud_monitoring_supabase_status", { session_id: sessionId }),
23751
+ supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
23546
23752
  handoffUrl: async (provider) => {
23547
23753
  const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
23548
23754
  const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
@@ -30814,7 +31020,7 @@ async function startMcpServer(rootOpts, extra) {
30814
31020
  },
30815
31021
  {
30816
31022
  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).",
31023
+ 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
31024
  inputSchema: {
30819
31025
  type: "object",
30820
31026
  properties: {
@@ -30825,7 +31031,7 @@ async function startMcpServer(rootOpts, extra) {
30825
31031
  yes: { type: "boolean", description: "Accept the price of a billed box. Without it, a billed box is not provisioned: the result has status action_required and the price; ask the user, then call again with yes: true" },
30826
31032
  coupon: { type: "string", description: "Stripe promotion code for the organization's monitoring subscription (applies when it is first created)" },
30827
31033
  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)" },
31034
+ 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
31035
  debug: { type: "boolean", description: "Enable verbose debug logs" }
30830
31036
  },
30831
31037
  required: ["database_url"],
@@ -31922,6 +32128,10 @@ function connectStatus2(row, provider = row.provider, fresh = false) {
31922
32128
  return { ...base, status, next: `pgai mon instances delete ${row.id} --yes, then pgai mon deploy again` };
31923
32129
  return { ...base, status, next: `pgai mon instances watch ${row.id}` };
31924
32130
  }
32131
+ var ESCAPES = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?|\x1b[ -~]?/g;
32132
+ var terminalText = (text) => text.replace(ESCAPES, "").split(`
32133
+ `).map(stripControlsToSpace).join(`
32134
+ `);
31925
32135
  function stepProgress(o) {
31926
32136
  let view;
31927
32137
  let priced = false;
@@ -31930,6 +32140,7 @@ function stepProgress(o) {
31930
32140
  o.onId?.(e.id);
31931
32141
  if (o.json)
31932
32142
  return o.writeEvent(e);
32143
+ e = { ...e, message: terminalText(e.message), ...e.state ? { state: terminalText(e.state) } : {} };
31933
32144
  if (!o.tty)
31934
32145
  return o.writeLine(progressText(e));
31935
32146
  if (e.event === "billing") {
@@ -31951,6 +32162,9 @@ function stepProgress(o) {
31951
32162
  return { progress, view: () => view };
31952
32163
  }
31953
32164
  function resultLines(r) {
32165
+ return personLines(r).map(terminalText);
32166
+ }
32167
+ function personLines(r) {
31954
32168
  const who = r.name || "this database";
31955
32169
  const extra = (r.next ?? "").split("; ").slice(1).join("; ");
31956
32170
  const billing = r.billing;
@@ -32011,11 +32225,25 @@ async function billingFor2(q, name, opts, deps, show) {
32011
32225
  }
32012
32226
  async function connect2(url, opts, deps) {
32013
32227
  const started = deps.now();
32014
- const progress = (event, message, more = {}) => deps.progress({ event, elapsed_s: Math.round((deps.now() - started) / 1000), message, ...more });
32228
+ let step = "preparing";
32229
+ const progress = (event, message, more = {}) => {
32230
+ if (event !== "billing")
32231
+ step = event;
32232
+ deps.progress({ event, elapsed_s: Math.round((deps.now() - started) / 1000), message, ...more });
32233
+ };
32234
+ const warned = new Set;
32235
+ const warn = (message) => {
32236
+ if (warned.has(message))
32237
+ return;
32238
+ warned.add(message);
32239
+ progress(step, message);
32240
+ };
32015
32241
  const provider = providerArg2(opts.provider) ?? detectCloudProvider2(url);
32016
32242
  if (!PROVIDERS2.includes(provider))
32017
32243
  throw new Error(`--provider must be one of: generic, ${PROVIDERS2.join(", ")}`);
32018
32244
  assertEncodedUserinfo(url);
32245
+ if (!opts.selfHosted && provider === "supabase")
32246
+ return deploySupabase2(url, opts, deps, progress);
32019
32247
  checkUrlParams2(url, opts.agent);
32020
32248
  const name = databaseName3(url);
32021
32249
  const asked = opts.monitoringUser?.trim();
@@ -32047,7 +32275,7 @@ async function connect2(url, opts, deps) {
32047
32275
  const key = parseClickhouseKey2(opts.clickhouseKey, provider === "clickhouse" && !opts.agent ? process.env : {});
32048
32276
  if (key && provider !== "clickhouse")
32049
32277
  throw new Error("--clickhouse-key applies to ClickHouse Managed Postgres only");
32050
- if (!opts.selfHosted && (provider === "rds" || provider === "supabase")) {
32278
+ if (!opts.selfHosted && provider === "rds") {
32051
32279
  const ignored = monitoringUser ? ` (${opts.agent ? "monitoring_user" : "--monitoring-user"} is not used there)` : "";
32052
32280
  return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}${ignored}` };
32053
32281
  }
@@ -32125,7 +32353,7 @@ async function connect2(url, opts, deps) {
32125
32353
  }
32126
32354
  const undo = async (p) => {
32127
32355
  if ("generated" in p && p.generated)
32128
- await deps.unprepare(url, monitoringUser).catch(() => false);
32356
+ await deps.unprepare(url, monitoringUser, { warn }).catch(() => false);
32129
32357
  };
32130
32358
  let lockId;
32131
32359
  const unread = (d) => !d.cluster;
@@ -32149,7 +32377,7 @@ async function connect2(url, opts, deps) {
32149
32377
  if (opts.coupon !== undefined && !opts.coupon.trim()) {
32150
32378
  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
32379
  }
32152
- const prepOpts = { resetPassword: opts.resetPassword, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
32380
+ const prepOpts = { resetPassword: opts.resetPassword, warn, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
32153
32381
  if (!opts.selfHosted) {
32154
32382
  const probe = await deps.prepare(url, provider, { ...prepOpts, check: true }).catch((err) => {
32155
32383
  if (err instanceof HttpStatusError || /Could not connect to/.test(errorText2(err)))
@@ -32283,6 +32511,124 @@ async function connect2(url, opts, deps) {
32283
32511
  const made = prepared;
32284
32512
  undoRole = () => undo(made);
32285
32513
  }
32514
+ return follow2(row, { provider, name, fresh, billing, billingUrl, undoRole, note }, opts, deps, progress);
32515
+ }
32516
+ var isSupabaseUrl2 = (link) => {
32517
+ try {
32518
+ const u = new URL(link);
32519
+ return u.origin === SUPABASE_API_BASE && !u.username && !u.password;
32520
+ } catch {
32521
+ return false;
32522
+ }
32523
+ };
32524
+ var OAUTH_WAIT_MS2 = 10 * 60000;
32525
+ var OAUTH_POLL_MS2 = 2000;
32526
+ async function deploySupabase2(url, opts, deps, progress) {
32527
+ const provider = "supabase";
32528
+ const ref = extractProjectRefFromUrl(url);
32529
+ if (!ref)
32530
+ return { status: "action_required", provider, name: databaseName3(url), next: "Not a Supabase project URL: use the project's connection string (db.<project-ref>.supabase.co, or the pooler with user postgres.<project-ref>)" };
32531
+ const db = decodeURIComponent(new URL(url).pathname.replace(/^\//, "")) || "postgres";
32532
+ const project = `postgresql://db.${ref}.supabase.co:5432/${encodeURIComponent(db)}`;
32533
+ const name = databaseName3(project);
32534
+ const cluster = clusterOf2(project);
32535
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
32536
+ if (db !== "postgres")
32537
+ return stop("PostgresAI monitors a Supabase project through its postgres database: use the URL of the postgres database");
32538
+ if (opts.resetPassword)
32539
+ return stop("--reset-password does not apply to Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API");
32540
+ if (opts.location)
32541
+ return stop("--location does not apply to Supabase yet (PostgresAI picks the box's location): re-run without it");
32542
+ if (opts.monitoringUser !== undefined && opts.monitoringUser.trim() !== DEFAULT_MONITORING_USER) {
32543
+ return stop(`${opts.agent ? "monitoring_user" : "--monitoring-user"} does not apply to Supabase: PostgresAI creates ${DEFAULT_MONITORING_USER} through the Supabase Management API`);
32544
+ }
32545
+ const row = (await deps.list()).find((d) => !disconnecting2(d.status) && d.cluster && serverOf2(d.cluster) === cluster && (!d.database || d.database === "postgres"));
32546
+ if (row) {
32547
+ const note = opts.name && row.name !== opts.name ? `; --name ignored: this database is already monitored as ${row.name}` : "";
32548
+ return follow2(row, { provider, name, fresh: false, billing: {}, note }, opts, deps, progress);
32549
+ }
32550
+ let started;
32551
+ try {
32552
+ started = await deps.supabaseStart(project);
32553
+ } catch (err) {
32554
+ if (err instanceof HttpStatusError && err.status === 403)
32555
+ return stop(notAdminNext);
32556
+ if (err instanceof HttpStatusError && err.status === 409)
32557
+ return stop(errorText2(err));
32558
+ throw err;
32559
+ }
32560
+ if ("auth_url" in started) {
32561
+ if (!isSupabaseUrl2(started.auth_url))
32562
+ return { status: "failed", provider, name, next: `The platform sent a Supabase consent link that is not ${SUPABASE_API_BASE}: not opened. Re-run pgai mon deploy later.` };
32563
+ const approve = `Open ${started.auth_url} in a browser and approve PostgresAI's access to Supabase`;
32564
+ if (opts.agent || opts.waitMs <= 0)
32565
+ return stop(`${approve}, then ${opts.agent ? "call deploy_monitoring again" : "re-run"}`);
32566
+ progress("preparing", `Connect Supabase to PostgresAI: approve access in the browser (open ${started.auth_url} if it did not open). Waiting...`, { auth_url: started.auth_url });
32567
+ deps.openUrl?.(started.auth_url);
32568
+ const expires = started.expires_at ? Date.parse(started.expires_at) : NaN;
32569
+ for (const deadline = deps.now() + Math.min(opts.waitMs, OAUTH_WAIT_MS2);; ) {
32570
+ if (deps.aborted?.())
32571
+ throw new CancelledError2;
32572
+ const s = await deps.supabaseStatus(started.session_id);
32573
+ if (s.status === "connected")
32574
+ break;
32575
+ if (s.status === "error")
32576
+ return stop(`Supabase did not connect (${s.error ?? "no reason given"}): re-run to try again`);
32577
+ const now = deps.now();
32578
+ if (now >= expires)
32579
+ return stop("The Supabase consent link expired before it was approved: re-run pgai mon deploy for a new one");
32580
+ if (now >= deadline)
32581
+ return stop(`${approve}, then re-run`);
32582
+ await deps.sleep(OAUTH_POLL_MS2);
32583
+ }
32584
+ }
32585
+ let quote;
32586
+ try {
32587
+ quote = await deps.quote(opts.coupon);
32588
+ } catch (err) {
32589
+ if (err instanceof HttpStatusError && err.status === 403)
32590
+ return stop(notAdminNext);
32591
+ throw err;
32592
+ }
32593
+ const b = await billingFor2(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)));
32594
+ if (b.stop)
32595
+ return { status: "action_required", provider, name, ...b.stop };
32596
+ if (deps.aborted?.())
32597
+ throw new CancelledError2;
32598
+ progress("provisioning", `Provisioning monitoring for ${name}`);
32599
+ const created = await deps.supabaseConnect({
32600
+ project_ref: ref,
32601
+ ...opts.name ? { name: opts.name } : {},
32602
+ ...b.accepted ? { accept_price: true } : {},
32603
+ ...opts.coupon ? { promo_code: opts.coupon } : {},
32604
+ ...opts.vcpus ? { vcpus: opts.vcpus } : {}
32605
+ }).catch((err) => {
32606
+ if (err instanceof HttpStatusError && err.status === 402)
32607
+ return /declined/i.test(err.message) ? "declined" : "payment";
32608
+ if (err instanceof HttpStatusError && err.status === 412)
32609
+ return "price";
32610
+ if (err instanceof HttpStatusError && err.status === 409)
32611
+ return { refused: errorText2(err) };
32612
+ throw err;
32613
+ });
32614
+ if (typeof created === "object" && "refused" in created)
32615
+ return stop(created.refused);
32616
+ if (created === "payment")
32617
+ return { status: "action_required", provider, name, ...b.billingPage };
32618
+ if (created === "declined")
32619
+ 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 ") };
32620
+ if (created === "price")
32621
+ return stop("The price changed since it was shown: re-run pgai mon deploy to see it", b.billing);
32622
+ if (created.status === "failed")
32623
+ return { status: "failed", provider, name, id: created.id, ...b.billing, next: `${created.error} Re-run pgai mon deploy later.` };
32624
+ const box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: false };
32625
+ if (deps.aborted?.())
32626
+ return { ...connectStatus2(box, provider, true), ...b.billing };
32627
+ return follow2(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "" }, opts, deps, progress);
32628
+ }
32629
+ var STILL_IN_PROGRESS2 = "Still in progress";
32630
+ async function follow2(row, f, opts, deps, progress) {
32631
+ const { provider, name, fresh, billing, billingUrl, undoRole, note } = f;
32286
32632
  let shown;
32287
32633
  for (const deadline = deps.now() + opts.waitMs;; ) {
32288
32634
  if (row.billing_error && disconnecting2(row.status)) {
@@ -32308,6 +32654,14 @@ async function connect2(url, opts, deps) {
32308
32654
  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
32655
  }
32310
32656
  const { next, ...rest } = final;
32657
+ if (final.status === "in_progress" && opts.waitMs > 0) {
32658
+ return {
32659
+ ...rest,
32660
+ status: "action_required",
32661
+ ...billing,
32662
+ next: `${STILL_IN_PROGRESS2} (box: ${boxWords2(boxState2(row))}) when the wait ended: resume with ${next}${note}`
32663
+ };
32664
+ }
32311
32665
  return { ...rest, ...billing, next: next + note };
32312
32666
  }
32313
32667
  await deps.sleep(POLL_MS2);
@@ -32315,8 +32669,9 @@ async function connect2(url, opts, deps) {
32315
32669
  return;
32316
32670
  });
32317
32671
  const now = listed?.find((d) => d.id === row.id);
32318
- if (listed && !now && undoRole) {
32319
- await undoRole();
32672
+ if (listed && !now && fresh) {
32673
+ if (undoRole)
32674
+ await undoRole();
32320
32675
  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
32676
  }
32322
32677
  row = now ?? row;
@@ -32330,7 +32685,7 @@ async function openConnection2(url, opts) {
32330
32685
  conn.clientConfig = { ...config, ...explicit };
32331
32686
  }
32332
32687
  const fallback = !opts.agent && !!conn.sslFallbackEnabled;
32333
- const { client, usedSsl } = await connectWithSslFallback(opts.Client ?? Client2, { ...conn, sslFallbackEnabled: fallback });
32688
+ const { client, usedSsl } = await connectWithSslFallback(opts.Client ?? Client2, { ...conn, sslFallbackEnabled: fallback }, false, opts.warn);
32334
32689
  await client.query("set search_path = pg_catalog, pg_temp");
32335
32690
  return { client, usedSsl, refusedTls: fallback && !usedSsl };
32336
32691
  }
@@ -32611,10 +32966,13 @@ function platformDeps2(p) {
32611
32966
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
32612
32967
  resetUnlock: (lockId) => rpc("cloud_monitoring_reset_unlock", { lock_id: lockId }),
32613
32968
  prepare: (url, provider, o = {}) => prepareDatabase2(url, provider, { ...o, agent: p.agent }),
32614
- unprepare: (url, monitoringUser) => unprepareDatabase2(url, { agent: p.agent, monitoringUser }),
32969
+ unprepare: (url, monitoringUser, o = {}) => unprepareDatabase2(url, { ...o, agent: p.agent, monitoringUser }),
32615
32970
  clickhouseOrg: clickhouseOrgFor2,
32616
32971
  quote: (coupon, cluster) => rpc("cloud_monitoring_quote", { ...coupon ? { promo_code: coupon } : {}, ...cluster ? { db_server: cluster } : {} }),
32617
32972
  billingUrl: (orgAlias) => `${p.uiBaseUrl}/${orgAlias}/billing`,
32973
+ supabaseStart: (dbUrl) => rpc("cloud_monitoring_supabase_start", { db_url: dbUrl }),
32974
+ supabaseStatus: (sessionId) => rpc("cloud_monitoring_supabase_status", { session_id: sessionId }),
32975
+ supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
32618
32976
  handoffUrl: async (provider) => {
32619
32977
  const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
32620
32978
  const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
@@ -33768,7 +34126,7 @@ class StepView {
33768
34126
  const st = this.states.get(s.key);
33769
34127
  const t = this.now();
33770
34128
  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}`;
34129
+ const icon = st === "done" ? `${GREEN}✓${RESET}` : st === "failed" ? `${RED}✗${RESET}` : st === "running" ? this.stopped ? "…" : FRAMES[this.frame % FRAMES.length] : `${DIM}·${RESET}`;
33772
34130
  const label = st === "pending" ? `${DIM}${s.label}${RESET}` : s.label;
33773
34131
  lines.push(` ${icon} ${label}${dur ? ` ${DIM}${dur}${RESET}` : ""}`);
33774
34132
  }
@@ -34293,6 +34651,13 @@ var MONITORING_STEPS = [
34293
34651
  { key: "box", label: "Install monitoring (about 5 min)" },
34294
34652
  { key: "ready", label: "Ready" }
34295
34653
  ];
34654
+ var SUPABASE_STEPS = [
34655
+ { key: "preparing", label: "Connect Supabase" },
34656
+ { key: "provisioning", label: "Create the monitoring box" },
34657
+ { key: "box", label: "Prepare the database and install monitoring (about 5 min)" },
34658
+ { key: "ready", label: "Ready" }
34659
+ ];
34660
+ var monitoringSteps = (provider) => provider === "supabase" ? SUPABASE_STEPS : MONITORING_STEPS;
34296
34661
  var FRAMES2 = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
34297
34662
  var GREEN2 = "\x1B[32m";
34298
34663
  var RED2 = "\x1B[31m";
@@ -34427,7 +34792,7 @@ class StepView2 {
34427
34792
  const st = this.states.get(s.key);
34428
34793
  const t = this.now();
34429
34794
  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}`;
34795
+ const icon = st === "done" ? `${GREEN2}✓${RESET2}` : st === "failed" ? `${RED2}✗${RESET2}` : st === "running" ? this.stopped ? "…" : FRAMES2[this.frame % FRAMES2.length] : `${DIM2}·${RESET2}`;
34431
34796
  const label = st === "pending" ? `${DIM2}${s.label}${RESET2}` : s.label;
34432
34797
  lines.push(` ${icon} ${label}${dur ? ` ${DIM2}${dur}${RESET2}` : ""}`);
34433
34798
  }
@@ -35342,7 +35707,19 @@ function isSslNegotiationError2(err) {
35342
35707
  }
35343
35708
  return false;
35344
35709
  }
35345
- async function connectWithSslFallback2(ClientClass, adminConn, verbose) {
35710
+ function effectiveConfig2(config) {
35711
+ const host = config.host ?? process.env.PGHOST;
35712
+ if (!config.connectionString)
35713
+ return { ssl: config.ssl, host };
35714
+ try {
35715
+ const parsed = parse(config.connectionString);
35716
+ const ssl = parsed.ssl === "no-verify" ? { rejectUnauthorized: false } : parsed.ssl;
35717
+ return { ssl: "ssl" in parsed ? ssl : config.ssl, host: parsed.host || host };
35718
+ } catch {
35719
+ return { ssl: config.ssl, host };
35720
+ }
35721
+ }
35722
+ async function connectWithSslFallback2(ClientClass, adminConn, verbose, warn = (message) => console.error(message)) {
35346
35723
  const tryConnect = async (config) => {
35347
35724
  const client = new ClientClass({ ...config, connectionTimeoutMillis: 1e4 });
35348
35725
  await client.connect();
@@ -35350,13 +35727,20 @@ async function connectWithSslFallback2(ClientClass, adminConn, verbose) {
35350
35727
  await client.query("SET statement_timeout = '30s'");
35351
35728
  return client;
35352
35729
  };
35730
+ const { ssl, host } = effectiveConfig2(adminConn.clientConfig);
35731
+ const socket = !!host?.startsWith("/");
35732
+ if (!socket && !ssl) {
35733
+ warn("Warning: this database connection uses plaintext, without TLS.");
35734
+ } else if (!socket && typeof ssl === "object" && ssl.rejectUnauthorized === false) {
35735
+ 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.");
35736
+ }
35353
35737
  if (!adminConn.sslFallbackEnabled) {
35354
35738
  const client = await tryConnect(adminConn.clientConfig);
35355
- return { client, usedSsl: !!adminConn.clientConfig.ssl };
35739
+ return { client, usedSsl: !!ssl };
35356
35740
  }
35357
35741
  try {
35358
35742
  const client = await tryConnect(adminConn.clientConfig);
35359
- return { client, usedSsl: true };
35743
+ return { client, usedSsl: !!ssl };
35360
35744
  } catch (sslErr) {
35361
35745
  if (!isSslNegotiationError2(sslErr)) {
35362
35746
  throw sslErr;
@@ -35365,9 +35749,12 @@ async function connectWithSslFallback2(ClientClass, adminConn, verbose) {
35365
35749
  console.error("SSL connection failed, retrying without SSL...");
35366
35750
  }
35367
35751
  const noSslConfig = { ...adminConn.clientConfig, ssl: false };
35752
+ const retrySsl = effectiveConfig2(noSslConfig).ssl;
35368
35753
  try {
35369
35754
  const client = await tryConnect(noSslConfig);
35370
- return { client, usedSsl: false };
35755
+ if (!retrySsl && !socket)
35756
+ warn("Warning: connected to the database without TLS after SSL negotiation failed.");
35757
+ return { client, usedSsl: !!retrySsl };
35371
35758
  } catch (noSslErr) {
35372
35759
  if (isSslNegotiationError2(noSslErr)) {
35373
35760
  const msg = noSslErr?.message || "";
@@ -35427,7 +35814,15 @@ function quoteLiteral2(value) {
35427
35814
  if (value.includes("\x00")) {
35428
35815
  throw new Error("Literal cannot contain null bytes");
35429
35816
  }
35430
- return `'${value.replace(/'/g, "''")}'`;
35817
+ const escapedQuotes = value.replace(/'/g, "''");
35818
+ return value.includes("\\") ? `E'${escapedQuotes.replace(/\\/g, "\\\\")}'` : `'${escapedQuotes}'`;
35819
+ }
35820
+ function safeDoDelimiter2(...values) {
35821
+ for (let n = 0;; n++) {
35822
+ const tag = `$pgai_do_${n}$`;
35823
+ if (values.every((value) => !value.includes(tag)))
35824
+ return tag;
35825
+ }
35431
35826
  }
35432
35827
  function redactPasswordsInSql2(sql) {
35433
35828
  return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
@@ -35669,14 +36064,16 @@ async function buildInitPlan2(params) {
35669
36064
  const iterations = Math.max(SCRAM_DEFAULT_ITERATIONS, serverIterations);
35670
36065
  const qPwVerifier = quoteLiteral2(scramSha256Verifier(params.monitoringPassword, { iterations }));
35671
36066
  const qRoleNameLit = quoteLiteral2(monitoringUser);
36067
+ const doQuote = safeDoDelimiter2(qRole, qDb, qRoleNameLit, qPwVerifier);
35672
36068
  const steps = [];
35673
36069
  const vars = {
35674
36070
  ROLE_IDENT: qRole,
35675
36071
  DB_IDENT: qDb,
35676
- ROLE_LITERAL: qRoleNameLit
36072
+ ROLE_LITERAL: qRoleNameLit,
36073
+ DO_QUOTE: doQuote
35677
36074
  };
35678
36075
  if (!SKIP_ROLE_CREATION_PROVIDERS2.includes(provider)) {
35679
- const roleStmt = `do $$ begin
36076
+ const roleStmt = `do ${doQuote} begin
35680
36077
  if not exists (select 1 from pg_catalog.pg_roles where rolname = ${qRoleNameLit}) then
35681
36078
  begin
35682
36079
  create user ${qRole} with password ${qPwVerifier};
@@ -35685,7 +36082,7 @@ async function buildInitPlan2(params) {
35685
36082
  end;
35686
36083
  end if;${params.keepExistingPassword ? "" : `
35687
36084
  alter user ${qRole} with password ${qPwVerifier};`}
35688
- end $$;`;
36085
+ end ${doQuote};`;
35689
36086
  const roleSql = applyTemplate2(loadSqlTemplate2("01.role.sql"), { ...vars, ROLE_STMT: roleStmt });
35690
36087
  steps.push({ name: "01.role", sql: roleSql });
35691
36088
  }
@@ -35789,11 +36186,13 @@ async function buildUninitPlan(params) {
35789
36186
  const qRole = quoteIdent2(monitoringUser);
35790
36187
  const qDb = quoteIdent2(database);
35791
36188
  const qRoleLiteral = quoteLiteral2(monitoringUser);
36189
+ const doQuote = safeDoDelimiter2(qRole, qDb, qRoleLiteral);
35792
36190
  const steps = [];
35793
36191
  const vars = {
35794
36192
  ROLE_IDENT: qRole,
35795
36193
  DB_IDENT: qDb,
35796
- ROLE_LITERAL: qRoleLiteral
36194
+ ROLE_LITERAL: qRoleLiteral,
36195
+ DO_QUOTE: doQuote
35797
36196
  };
35798
36197
  steps.push({
35799
36198
  name: "01.drop_helpers",
@@ -35878,6 +36277,18 @@ function roleSearchPathProblem2(spLine, extSchema) {
35878
36277
  return null;
35879
36278
  return `role search_path is ${expected.join(", ")}`;
35880
36279
  }
36280
+ async function legacyHelperWarnings(client) {
36281
+ const r = await client.query(`select
36282
+ pg_catalog.to_regprocedure('postgres_ai.explain_generic(text,text,text)') is not null as explain_generic,
36283
+ coalesce((select p.prosecdef from pg_catalog.pg_proc p
36284
+ where p.oid = pg_catalog.to_regprocedure('postgres_ai.table_describe(text)')::oid), false) as table_describe`);
36285
+ const row = r.rows?.[0];
36286
+ const legacy = [
36287
+ row?.explain_generic ? "postgres_ai.explain_generic(text, text, text)" : null,
36288
+ row?.table_describe ? "postgres_ai.table_describe(text)" : null
36289
+ ].filter((f) => f !== null);
36290
+ 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`);
36291
+ }
35881
36292
  async function verifyInitSetup2(params) {
35882
36293
  await params.client.query("begin isolation level repeatable read;");
35883
36294
  try {
@@ -35958,8 +36369,11 @@ async function verifyInitSetup2(params) {
35958
36369
  missingRequired.push(problem);
35959
36370
  }
35960
36371
  }
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) {
36372
+ const tableDescribeFnRes = await params.client.query(`select case when pg_catalog.to_regprocedure('postgres_ai.table_describe(text)') is not null
36373
+ then has_function_privilege($1, 'postgres_ai.table_describe(text)', 'EXECUTE') end as ok`, [role]);
36374
+ if (tableDescribeFnRes.rows?.[0]?.ok === null) {
36375
+ missingRequired.push("function postgres_ai.table_describe(text) exists");
36376
+ } else if (!tableDescribeFnRes.rows?.[0]?.ok) {
35963
36377
  missingRequired.push("EXECUTE on postgres_ai.table_describe(text)");
35964
36378
  }
35965
36379
  if (params.includeOptionalPermissions) {
@@ -36142,7 +36556,7 @@ Alternatively, run 'postgresai prepare-db' to set up permissions automatically.`
36142
36556
  }
36143
36557
 
36144
36558
  // lib/supabase.ts
36145
- var SUPABASE_API_BASE = "https://api.supabase.com";
36559
+ var SUPABASE_API_BASE2 = "https://api.supabase.com";
36146
36560
  var SUPABASE_POOLER_TRANSACTION_PORT = 6543;
36147
36561
  var SUPABASE_POOLER_SESSION_PORT = 5432;
36148
36562
  var SUPABASE_POOLER_HOST_SUFFIX = "pooler.supabase.com";
@@ -36172,7 +36586,7 @@ class SupabaseClient {
36172
36586
  this.config = config;
36173
36587
  }
36174
36588
  async query(sql, readOnly = false) {
36175
- const url = `${SUPABASE_API_BASE}/v1/projects/${encodeURIComponent(this.config.projectRef)}/database/query`;
36589
+ const url = `${SUPABASE_API_BASE2}/v1/projects/${encodeURIComponent(this.config.projectRef)}/database/query`;
36176
36590
  const response = await fetch(url, {
36177
36591
  method: "POST",
36178
36592
  headers: {
@@ -36315,7 +36729,7 @@ async function fetchPoolerDatabaseUrl(config, username) {
36315
36729
  if (!isValidProjectRef(config.projectRef)) {
36316
36730
  throw new Error(`Invalid Supabase project reference format: "${config.projectRef}". Expected 10-30 alphanumeric characters.`);
36317
36731
  }
36318
- const url = `${SUPABASE_API_BASE}/v1/projects/${encodeURIComponent(config.projectRef)}/config/database/pooler`;
36732
+ const url = `${SUPABASE_API_BASE2}/v1/projects/${encodeURIComponent(config.projectRef)}/config/database/pooler`;
36319
36733
  const suffix = `.${config.projectRef}`;
36320
36734
  const effectiveUsername = username.endsWith(suffix) ? username : `${username}${suffix}`;
36321
36735
  const encodedUsername = encodeURIComponent(effectiveUsername);
@@ -36366,7 +36780,7 @@ function resolveSupabaseConfig(opts) {
36366
36780
  }
36367
36781
  return { accessToken, projectRef };
36368
36782
  }
36369
- function extractProjectRefFromUrl(dbUrl) {
36783
+ function extractProjectRefFromUrl2(dbUrl) {
36370
36784
  try {
36371
36785
  const url = new URL(dbUrl);
36372
36786
  const host = url.hostname;
@@ -44500,7 +44914,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44500
44914
  try {
44501
44915
  let projectRef = opts.supabaseProjectRef;
44502
44916
  if (!projectRef && conn) {
44503
- projectRef = extractProjectRefFromUrl(conn);
44917
+ projectRef = extractProjectRefFromUrl2(conn);
44504
44918
  }
44505
44919
  supabaseConfig = resolveSupabaseConfig({
44506
44920
  accessToken: opts.supabaseAccessToken,
@@ -44537,6 +44951,11 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44537
44951
  monitoringUser: opts.monitoringUser,
44538
44952
  includeOptionalPermissions
44539
44953
  });
44954
+ const legacyFailures = await legacyHelperWarnings(supabaseClient);
44955
+ if (legacyFailures.length > 0) {
44956
+ v.missingRequired.push(...legacyFailures);
44957
+ v.ok = false;
44958
+ }
44540
44959
  if (v.ok) {
44541
44960
  if (jsonOutput) {
44542
44961
  const result = {
@@ -44659,6 +45078,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44659
45078
  client: supabaseClient,
44660
45079
  plan: effectivePlan
44661
45080
  });
45081
+ const legacyWarnings = await legacyHelperWarnings(supabaseClient);
44662
45082
  if (jsonOutput) {
44663
45083
  const result = {
44664
45084
  success: true,
@@ -44668,7 +45088,10 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44668
45088
  monitoringUser: opts.monitoringUser,
44669
45089
  applied,
44670
45090
  skippedOptional,
44671
- warnings: skippedOptional.length > 0 ? ["Some optional steps were skipped (not supported or insufficient privileges)"] : []
45091
+ warnings: [
45092
+ ...skippedOptional.length > 0 ? ["Some optional steps were skipped (not supported or insufficient privileges)"] : [],
45093
+ ...legacyWarnings
45094
+ ]
44672
45095
  };
44673
45096
  if (passwordGenerated) {
44674
45097
  result.generatedPassword = monPassword;
@@ -44684,6 +45107,8 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44684
45107
  for (const s of skippedOptional)
44685
45108
  console.error(`- ${s}`);
44686
45109
  }
45110
+ for (const w of legacyWarnings)
45111
+ console.error(`\u26A0 ${w}`);
44687
45112
  if (process.stdout.isTTY) {
44688
45113
  console.log(`Applied ${applied.length} steps`);
44689
45114
  }
@@ -44825,6 +45250,11 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44825
45250
  includeOptionalPermissions,
44826
45251
  provider
44827
45252
  });
45253
+ const legacyFailures = await legacyHelperWarnings(client);
45254
+ if (legacyFailures.length > 0) {
45255
+ v.missingRequired.push(...legacyFailures);
45256
+ v.ok = false;
45257
+ }
44828
45258
  if (v.ok) {
44829
45259
  if (jsonOutput) {
44830
45260
  outputJson({
@@ -44943,6 +45373,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44943
45373
  return;
44944
45374
  }
44945
45375
  const { applied, skippedOptional } = await applyInitPlan2({ client, plan: effectivePlan });
45376
+ const legacyWarnings = await legacyHelperWarnings(client);
44946
45377
  if (jsonOutput) {
44947
45378
  const result = {
44948
45379
  success: true,
@@ -44952,7 +45383,10 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44952
45383
  monitoringUser: opts.monitoringUser,
44953
45384
  applied,
44954
45385
  skippedOptional,
44955
- warnings: skippedOptional.length > 0 ? ["Some optional steps were skipped (not supported or insufficient privileges)"] : []
45386
+ warnings: [
45387
+ ...skippedOptional.length > 0 ? ["Some optional steps were skipped (not supported or insufficient privileges)"] : [],
45388
+ ...legacyWarnings
45389
+ ]
44956
45390
  };
44957
45391
  if (passwordGenerated) {
44958
45392
  result.generatedPassword = monPassword;
@@ -44965,6 +45399,8 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44965
45399
  for (const s of skippedOptional)
44966
45400
  console.error(`- ${s}`);
44967
45401
  }
45402
+ for (const w of legacyWarnings)
45403
+ console.error(`\u26A0 ${w}`);
44968
45404
  if (process.stdout.isTTY) {
44969
45405
  console.log(`Applied ${applied.length} steps`);
44970
45406
  }
@@ -44984,6 +45420,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44984
45420
  }
44985
45421
  const stepMatch = typeof message === "string" ? message.match(/Failed at step "([^"]+)":/i) : null;
44986
45422
  const failedStep = stepMatch?.[1];
45423
+ const legacyWarnings = failedStep && client ? await legacyHelperWarnings(client).catch(() => []) : [];
44987
45424
  const errorObj = { message };
44988
45425
  if (failedStep)
44989
45426
  errorObj.step = failedStep;
@@ -44999,7 +45436,8 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
44999
45436
  outputJson({
45000
45437
  success: false,
45001
45438
  mode: "direct",
45002
- error: errorObj
45439
+ error: errorObj,
45440
+ ...legacyWarnings.length > 0 ? { warnings: legacyWarnings } : {}
45003
45441
  });
45004
45442
  process.exitCode = 1;
45005
45443
  } else {
@@ -45018,6 +45456,8 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
45018
45456
  console.error(` Hint: ${errAny.hint}`);
45019
45457
  }
45020
45458
  }
45459
+ for (const w of legacyWarnings)
45460
+ console.error(`\u26A0 ${w}`);
45021
45461
  if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
45022
45462
  if (errAny.code === "42501") {
45023
45463
  if (failedStep === "01.role") {
@@ -45404,7 +45844,11 @@ Usage: postgresai checkup ${checkId} postgresql://user@host:5432/dbname
45404
45844
  const spinner = createTtySpinner(spinnerEnabled, "Connecting to Postgres");
45405
45845
  try {
45406
45846
  spinner.update("Connecting to Postgres");
45407
- const connResult = await connectWithSslFallback2(Client, adminConn);
45847
+ const connResult = await connectWithSslFallback2(Client, adminConn, false, (message) => {
45848
+ if (spinnerEnabled)
45849
+ process.stdout.write("\r\x1B[2K");
45850
+ console.error(message);
45851
+ });
45408
45852
  client = connResult.client;
45409
45853
  spinner.update("Checking database permissions");
45410
45854
  try {
@@ -46167,6 +46611,12 @@ async function inspectInstanceJobsState() {
46167
46611
  return /no such (object|container)/i.test(text) ? "absent" : "unknown";
46168
46612
  }
46169
46613
  }
46614
+ function openInBrowser(url) {
46615
+ const openCommand = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
46616
+ const browserProcess = spawn3(openCommand, [url], { detached: true, stdio: "ignore" });
46617
+ browserProcess.on("error", () => {});
46618
+ browserProcess.unref();
46619
+ }
46170
46620
  var CONNECT_EXIT = DEPLOY_EXIT2;
46171
46621
  function cloudApi(debug) {
46172
46622
  const rootOpts = program2.opts();
@@ -46174,7 +46624,7 @@ function cloudApi(debug) {
46174
46624
  const urls = resolveBaseUrls2(rootOpts, readConfig());
46175
46625
  return { apiKey, apiBaseUrl: urls.apiBaseUrl, ...platformDeps2({ apiKey, ...urls, orgScope: getActiveOrgScope2(), debug }) };
46176
46626
  }
46177
- function emitConnect(result, json) {
46627
+ function emitConnect(result, json, done = false) {
46178
46628
  if (!jsonOutput3(json)) {
46179
46629
  if (result.sql)
46180
46630
  console.log(`${result.sql}
@@ -46185,9 +46635,16 @@ function emitConnect(result, json) {
46185
46635
  out(line);
46186
46636
  } else {
46187
46637
  printResult(result, json);
46638
+ if (done)
46639
+ writeEvent2({ event: "done", status: result.status, ...result.id ? { id: result.id } : {}, next: result.next });
46188
46640
  }
46189
46641
  process.exitCode = CONNECT_EXIT[result.status];
46190
46642
  }
46643
+ function optionError(result, json) {
46644
+ if (jsonOutput3(json))
46645
+ console.error(result.next);
46646
+ emitConnect(result, json);
46647
+ }
46191
46648
  function failCloud(err, json) {
46192
46649
  printResult({ status: "failed", next: errorText2(err) }, json);
46193
46650
  process.exitCode = 1;
@@ -46216,7 +46673,7 @@ async function runConnect(urlArg, opts) {
46216
46673
  try {
46217
46674
  url = databaseUrlArg2(urlArg, opts.dbUrl, "pgai mon deploy");
46218
46675
  } catch (err) {
46219
- return emitConnect({ status: "failed", provider: "self-managed", name: "", next: errorText2(err) }, opts.json);
46676
+ return optionError({ status: "failed", provider: "self-managed", name: "", next: errorText2(err) }, opts.json);
46220
46677
  }
46221
46678
  const json = jsonOutput3(opts.json);
46222
46679
  const name = (() => {
@@ -46227,7 +46684,7 @@ async function runConnect(urlArg, opts) {
46227
46684
  }
46228
46685
  })();
46229
46686
  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);
46687
+ return optionError({ status: "failed", provider: "self-managed", name, next: "Pass a URL: pgai mon deploy postgresql://user:password@host:5432/dbname" }, opts.json);
46231
46688
  }
46232
46689
  const explicit = providerArg2(opts.provider);
46233
46690
  const provider = PROVIDERS2.find((p) => p === explicit) ?? detectCloudProvider2(url);
@@ -46235,18 +46692,18 @@ async function runConnect(urlArg, opts) {
46235
46692
  try {
46236
46693
  minutes = waitMinutes2(opts.wait, 20);
46237
46694
  } catch (err) {
46238
- return emitConnect({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
46695
+ return optionError({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
46239
46696
  }
46240
46697
  let vcpus;
46241
46698
  try {
46242
46699
  vcpus = vcpusArg2(opts.vcpus);
46243
46700
  } catch (err) {
46244
- return emitConnect({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
46701
+ return optionError({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
46245
46702
  }
46246
46703
  let shownView;
46247
46704
  try {
46248
46705
  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);
46706
+ 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
46707
  }
46251
46708
  const api = cloudApi(opts.debug);
46252
46709
  const tty = !json && !!process.stderr.isTTY && !process.env.CI && process.env.TERM !== "dumb";
@@ -46255,7 +46712,7 @@ async function runConnect(urlArg, opts) {
46255
46712
  const steps = stepProgress({
46256
46713
  json,
46257
46714
  tty,
46258
- makeView: () => new StepView2(`Deploying monitoring for ${name}`, MONITORING_STEPS, true),
46715
+ makeView: () => new StepView2(`Deploying monitoring for ${name}`, monitoringSteps(provider), true),
46259
46716
  writeLine: (line) => console.error(line),
46260
46717
  writeEvent: writeEvent2,
46261
46718
  onId: (id) => {
@@ -46270,14 +46727,25 @@ Stopped watching. The deploy continues on PostgresAI.
46270
46727
  Resume: pgai mon instances watch ${createdId}`);
46271
46728
  process.exit(130);
46272
46729
  };
46730
+ let requested = false;
46273
46731
  const onSigint = () => {
46274
46732
  if (createdId)
46275
46733
  return resume();
46276
- if (stopping)
46734
+ if (stopping) {
46735
+ steps.view()?.stop();
46736
+ if (requested)
46737
+ console.error(`
46738
+ Quit. The monitoring box may exist: pgai mon instances list`);
46277
46739
  process.exit(130);
46740
+ }
46278
46741
  stopping = true;
46279
- console.error(`
46280
- Cancelling: nothing has been created yet (Ctrl-C again to quit now).`);
46742
+ 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).";
46743
+ const view = steps.view();
46744
+ if (view)
46745
+ view.log(reply);
46746
+ else
46747
+ console.error(`
46748
+ ${reply}`);
46281
46749
  };
46282
46750
  process.on("SIGINT", onSigint);
46283
46751
  let result;
@@ -46323,7 +46791,12 @@ Cancelling: nothing has been created yet (Ctrl-C again to quit now).`);
46323
46791
  closeReadline();
46324
46792
  }
46325
46793
  },
46326
- progress: steps.progress,
46794
+ ...interactive(opts.json) ? { openUrl: openInBrowser } : {},
46795
+ progress: (e) => {
46796
+ if (e.event === "provisioning")
46797
+ requested = true;
46798
+ steps.progress(e);
46799
+ },
46327
46800
  aborted: () => stopping
46328
46801
  });
46329
46802
  } catch (err) {
@@ -46337,24 +46810,26 @@ Cancelling: nothing has been created yet (Ctrl-C again to quit now).`);
46337
46810
  } finally {
46338
46811
  process.removeListener("SIGINT", onSigint);
46339
46812
  }
46813
+ if (stopping && !createdId && result.status === "in_progress")
46814
+ createdId = result.id;
46340
46815
  if (stopping && createdId)
46341
46816
  return resume();
46342
46817
  const view = steps.view();
46343
46818
  if (view) {
46344
46819
  if (result.status === "ready")
46345
46820
  view.complete();
46346
- else if (result.status !== "in_progress")
46821
+ else if (result.status !== "in_progress" && !result.next.startsWith(STILL_IN_PROGRESS2))
46347
46822
  view.fail();
46348
46823
  view.stop();
46349
46824
  }
46350
- emitConnect(result, opts.json);
46825
+ emitConnect(result, opts.json, true);
46351
46826
  } catch (err) {
46352
46827
  const view = shownView?.();
46353
46828
  if (view) {
46354
46829
  view.fail();
46355
46830
  view.stop();
46356
46831
  }
46357
- emitConnect({ status: "failed", provider, name, next: errorText2(err) }, opts.json);
46832
+ emitConnect({ status: "failed", provider, name, next: errorText2(err) }, opts.json, true);
46358
46833
  }
46359
46834
  }
46360
46835
  var mon = program2.command("mon").description("monitoring services management");
@@ -46376,12 +46851,21 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
46376
46851
  "box is provisioned only when accepted: at the prompt, or with --yes. With no payment method",
46377
46852
  "it stops (exit 3) and names the console page to add one. --coupon applies a promotion code.",
46378
46853
  "",
46379
- 'Exit codes: 0 ready or in progress, 1 failed, 3 action required (see "next").',
46854
+ "Supabase: PostgresAI creates postgres_ai_mon through the Supabase Management API (the",
46855
+ "database password is not needed and not sent). The first time, the organization connects",
46856
+ "Supabase: deploy opens the consent page in the browser (the link is printed too, to open",
46857
+ 'it elsewhere; "auth_url" in the JSON event) and waits for the approval, up to 10 minutes.',
46858
+ 'With --wait 0, and for agents, it stops there (exit 3) with the link in "next".',
46859
+ "",
46860
+ "Exit codes: 0 ready (or in progress with --no-wait), 1 failed, 3 action required (see",
46861
+ '"next"), also when the wait ends before the box is ready.',
46380
46862
  "",
46381
46863
  "JSON output (--json): stdout is the result; stderr is one JSON event a",
46382
46864
  'line: the steps, and {"event":"log","level":"error"|"warn"|"info"|"debug","message":...}',
46383
46865
  'for any other text (an error, a warning, --debug); "source":"mon local-install" for that',
46384
46866
  "child's lines (the logins it prints are masked: pgai mon show-grafana-credentials shows them).",
46867
+ 'The last event of a run is {"event":"done","status":...,"next":...}; not after Ctrl-C (exit 130)',
46868
+ "or an error in the options or --org before the run starts (an error event, exit 1).",
46385
46869
  "",
46386
46870
  "Environment: PGAI_API_KEY (instead of signing in), PGAI_MON_PASSWORD (the password of",
46387
46871
  "postgres_ai_mon when the role already exists; it is checked, never changed; not needed",
@@ -46393,6 +46877,7 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
46393
46877
  "Examples:",
46394
46878
  " pgai mon deploy 'postgresql://postgres:<password>@<host>.pg.clickhouse.cloud:5432/postgres?sslmode=require'",
46395
46879
  " CLICKHOUSE_KEY_ID=... CLICKHOUSE_KEY_SECRET=... pgai mon deploy '<url>'",
46880
+ " pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres'",
46396
46881
  " pgai mon deploy '<url>' --self-hosted"
46397
46882
  ].join(`
46398
46883
  `)).action((urlArg, opts, cmd) => {
@@ -47512,7 +47997,7 @@ async function setUpHostMetrics(projectDir, instance, connStr, env, apply) {
47512
47997
  console.log(message);
47513
47998
  return true;
47514
47999
  }
47515
- const projectRef = extractProjectRefFromUrl(connStr);
48000
+ const projectRef = extractProjectRefFromUrl2(connStr);
47516
48001
  if (projectRef) {
47517
48002
  const on = supabaseHostMetricsOn(projectDir, env);
47518
48003
  if (on && !SUPABASE_TARGET_NAME_RE.test(name))
@@ -47598,7 +48083,7 @@ async function addTarget(file, projectDir, connStr, name, env, { apply = true, v
47598
48083
  return false;
47599
48084
  }
47600
48085
  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)) {
48086
+ if (detectProvider(connStr) !== "clickhouse" && extractProjectRefFromUrl2(connStr) && supabaseHostMetricsOn(projectDir, env) && !SUPABASE_TARGET_NAME_RE.test(instanceName)) {
47602
48087
  console.error(SUPABASE_TARGET_NAME_ERROR);
47603
48088
  process.exitCode = 1;
47604
48089
  return false;
@@ -47923,10 +48408,7 @@ Opening browser for authentication...`);
47923
48408
  console.log(`If browser does not open automatically, visit:
47924
48409
  ${authUrl}
47925
48410
  `);
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();
48411
+ openInBrowser(authUrl);
47930
48412
  console.log("Waiting for authorization...");
47931
48413
  console.log(`(Press Ctrl+C to cancel)
47932
48414
  `);