postgresai 0.18.0-dev.16 → 0.18.0-dev.18

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.
@@ -13466,6 +13466,11 @@ function resolveBaseUrls2(opts, cfg, defaults = {}) {
13466
13466
  storageBaseUrl: normalizeBaseUrl2(storageCandidate)
13467
13467
  };
13468
13468
  }
13469
+ function canOpenBrowser(env = process.env, platform = process.platform) {
13470
+ if (platform === "darwin" || platform === "win32")
13471
+ return !env.SSH_CONNECTION && !env.SSH_TTY;
13472
+ return !!(env.DISPLAY || env.WAYLAND_DISPLAY);
13473
+ }
13469
13474
  var DEFAULT_HTTP_REQUEST_TIMEOUT_MS2 = 25000, SENSITIVE_KEY_SRC2 = "(?:password|passwd|db[-_]?pass|connstr|secret|token|api[-_]?key|private[-_]?key|access[-_]?key|cred(?:ential)?s?|dsn)", SENSITIVE_PAIR_SEPARATOR_SRC2 = `["']?\\s*[:=]`, CREDENTIAL_CHAR_SRC2 = "[A-Za-z0-9_+/=~.-]", TEXT_SENSITIVE_PAIR2, CREDENTIAL_RUN_ONLY2;
13470
13475
  var init_util = __esm(() => {
13471
13476
  TEXT_SENSITIVE_PAIR2 = new RegExp(`(${SENSITIVE_KEY_SRC2}${SENSITIVE_PAIR_SEPARATOR_SRC2}\\s*)` + `(?:("[^"]*"|'[^']*')` + `|([^\\s,;&]+)` + `((?:\\s+(?![^\\s,;&]*${SENSITIVE_KEY_SRC2}${SENSITIVE_PAIR_SEPARATOR_SRC2})[^\\s,;&]+)*)` + `)`, "gi");
@@ -13533,7 +13538,7 @@ var {
13533
13538
  // package.json
13534
13539
  var package_default = {
13535
13540
  name: "postgresai",
13536
- version: "0.18.0-dev.16",
13541
+ version: "0.18.0-dev.18",
13537
13542
  description: "postgres_ai CLI",
13538
13543
  license: "Apache-2.0",
13539
13544
  private: false,
@@ -16873,8 +16878,8 @@ var {
16873
16878
  } = yaml;
16874
16879
 
16875
16880
  // bin/postgres-ai.ts
16876
- import * as fs10 from "fs";
16877
- import * as path8 from "path";
16881
+ import * as fs12 from "fs";
16882
+ import * as path10 from "path";
16878
16883
  import * as os3 from "os";
16879
16884
  import { fileURLToPath as fileURLToPath3 } from "url";
16880
16885
  import * as crypto2 from "crypto";
@@ -16893,7 +16898,7 @@ var Result = import_lib.default.Result;
16893
16898
  var TypeOverrides = import_lib.default.TypeOverrides;
16894
16899
  var defaults = import_lib.default.defaults;
16895
16900
  // package.json
16896
- var version = "0.18.0-dev.16";
16901
+ var version = "0.18.0-dev.18";
16897
16902
  var package_default2 = {
16898
16903
  name: "postgresai",
16899
16904
  version,
@@ -17231,7 +17236,7 @@ function maskSecret(secret) {
17231
17236
  }
17232
17237
  function isSensitiveLogKey(key) {
17233
17238
  const normalized = key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
17234
- return /^(?:password|passwd|db_(?:pass|password|url)|conn_?str|secret|(?:[a-z]+_)?key_secret|token|api_key|private_key|access_key|access_token|refresh_token|auth|auth_key|auth_token|authorization|credentials?|dsn)$/.test(normalized);
17239
+ return /^(?:password|passwd|db_(?:pass|password|url)|prepare_db_sql|conn_?str|secret|(?:[a-z]+_)?key_secret|token|api_key|private_key|access_key|access_token|refresh_token|auth|auth_key|auth_token|authorization|credentials?|dsn)$/.test(normalized);
17235
17240
  }
17236
17241
  function redactSecrets(value) {
17237
17242
  if (Array.isArray(value)) {
@@ -18505,6 +18510,11 @@ function appendAttachmentsToContent(content, attachments) {
18505
18510
  ${links}`;
18506
18511
  }
18507
18512
 
18513
+ // lib/connect.ts
18514
+ import { execFile as execFile2 } from "node:child_process";
18515
+ import * as fs6 from "node:fs";
18516
+ import * as path5 from "node:path";
18517
+
18508
18518
  // node_modules/pg/esm/index.mjs
18509
18519
  var import_lib2 = __toESM(require_lib2(), 1);
18510
18520
  var Client2 = import_lib2.default.Client;
@@ -22829,6 +22839,178 @@ function isNumericProjectRef(ref) {
22829
22839
  return /^[0-9]+$/.test(ref.trim());
22830
22840
  }
22831
22841
 
22842
+ // lib/privatelink.ts
22843
+ import { execFile } from "node:child_process";
22844
+ var CFN_TEMPLATE_URL = "https://postgres-ai-cloudformation.s3.amazonaws.com/rds-privatelink-provider.yaml";
22845
+ var TERRAFORM_URL = "https://postgres-ai-cloudformation.s3.amazonaws.com/terraform/rds-privatelink-provider/main.tf";
22846
+ var PRINCIPAL_ARN = "arn:aws:iam::005923036815:user/pgai-rds-privatelink-monitoring";
22847
+ function rdsEndpoint(hostname) {
22848
+ const host = hostname.toLowerCase().replace(/\.$/, "");
22849
+ const m = /^([a-z][a-z0-9-]*)\.([a-z0-9-]+)\.([a-z]{2}(?:-[a-z]+)+-\d)\.rds\.amazonaws\.com(\.cn)?$/.exec(host);
22850
+ if (!m)
22851
+ return;
22852
+ const [, id, second, region, cn] = m;
22853
+ const kind = second.startsWith("cluster-ro-") ? "aurora_reader" : second.startsWith("cluster-custom-") ? "aurora_custom" : second.startsWith("cluster-") ? "aurora_writer" : second.startsWith("proxy-") ? "proxy" : "instance";
22854
+ const partition = cn ? "aws-cn" : region.startsWith("us-gov-") ? "aws-us-gov" : "aws";
22855
+ return { host, id, region, kind, partition };
22856
+ }
22857
+ var stackNameFor = (rdsId) => `postgresai-privatelink-${rdsId}`.slice(0, 128);
22858
+ var VPCE_SERVICE = /^com\.amazonaws\.vpce\.([a-z]{2}(?:-[a-z]+)+-\d)\.vpce-svc-[0-9a-f]{8,}$/;
22859
+ var ROLE_ARN = /^arn:aws:iam::\d{12}:role\/[\w+=,.@\/-]{1,512}$/;
22860
+ function isPrivateAddress(ip) {
22861
+ const v4 = /^(\d+)\.(\d+)\.\d+\.\d+$/.exec(ip);
22862
+ if (v4) {
22863
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
22864
+ return a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254;
22865
+ }
22866
+ return /^f[cd][0-9a-f]{2}:/i.test(ip) || /^fe80:/i.test(ip);
22867
+ }
22868
+ var DOH = ["https://cloudflare-dns.com/dns-query", "https://dns.google/resolve"];
22869
+ var DOH_TIMEOUT_MS = 3000;
22870
+ async function publicAddresses(host, fetchFn = fetch) {
22871
+ for (const base of DOH) {
22872
+ try {
22873
+ const r = await fetchFn(`${base}?name=${encodeURIComponent(host)}&type=A`, { headers: { accept: "application/dns-json" }, signal: AbortSignal.timeout(DOH_TIMEOUT_MS) });
22874
+ if (!r.ok)
22875
+ continue;
22876
+ const body = await r.json();
22877
+ if (body.Status !== 0)
22878
+ continue;
22879
+ return (body.Answer ?? []).filter((a) => a.type === 1).map((a) => a.data);
22880
+ } catch {}
22881
+ }
22882
+ return;
22883
+ }
22884
+
22885
+ class AwsError extends Error {
22886
+ kind;
22887
+ constructor(message, kind) {
22888
+ super(message);
22889
+ this.kind = kind;
22890
+ }
22891
+ }
22892
+ function awsRunner(profile) {
22893
+ return (args) => new Promise((resolve, reject) => {
22894
+ execFile("aws", [...args, "--output", "json", ...profile ? ["--profile", profile] : []], { timeout: 30000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, AWS_PAGER: "" } }, (err, stdout, stderr) => {
22895
+ if (!err) {
22896
+ try {
22897
+ return resolve(stdout.trim() ? JSON.parse(stdout) : null);
22898
+ } catch {
22899
+ return reject(new AwsError("the aws CLI returned no JSON", "other"));
22900
+ }
22901
+ }
22902
+ if (err.code === "ENOENT")
22903
+ return reject(new AwsError("the aws CLI is not installed", "missing"));
22904
+ const said = String(stderr || err.message).trim().split(`
22905
+ `).filter(Boolean).pop() ?? "";
22906
+ const kind = /DBInstanceNotFound|does not exist|NotFound/i.test(said) ? "not_found" : /expired|Unable to locate credentials|NoCredentialProviders|aws (sso )?login|profile .* could not be found|InvalidClientTokenId|SignatureDoesNotMatch/i.test(said) ? "credentials" : /AccessDenied|not authorized|UnauthorizedOperation/i.test(said) ? "denied" : "other";
22907
+ reject(new AwsError(said.replace(/^aws: \[ERROR\]: /, ""), kind));
22908
+ });
22909
+ });
22910
+ }
22911
+ async function describeDbInstance(run, id, region) {
22912
+ const d = await run(["rds", "describe-db-instances", "--db-instance-identifier", id, "--region", region, "--query", "DBInstances[0]"]);
22913
+ if (!d)
22914
+ throw new AwsError(`DB instance ${id} not found`, "not_found");
22915
+ return {
22916
+ publiclyAccessible: !!d.PubliclyAccessible,
22917
+ port: d.Endpoint?.Port ?? 5432,
22918
+ vpcId: d.DBSubnetGroup?.VpcId,
22919
+ subnets: (d.DBSubnetGroup?.Subnets ?? []).map((s) => ({ id: s.SubnetIdentifier, az: s.SubnetAvailabilityZone?.Name ?? "" })),
22920
+ securityGroupIds: (d.VpcSecurityGroups ?? []).filter((g) => g.Status !== "inactive").map((g) => g.VpcSecurityGroupId),
22921
+ instanceClass: d.DBInstanceClass,
22922
+ engine: d.Engine
22923
+ };
22924
+ }
22925
+ async function callerIdentity(run) {
22926
+ const r = await run(["sts", "get-caller-identity"]);
22927
+ return { account: r.Account, arn: r.Arn };
22928
+ }
22929
+ async function vcpusOfClass(run, instanceClass, region) {
22930
+ if (!instanceClass.startsWith("db."))
22931
+ return;
22932
+ try {
22933
+ const n = await run(["ec2", "describe-instance-types", "--instance-types", instanceClass.slice(3), "--region", region, "--query", "InstanceTypes[0].VCpuInfo.DefaultVCpus"]);
22934
+ return typeof n === "number" && n > 0 ? n : undefined;
22935
+ } catch {
22936
+ return;
22937
+ }
22938
+ }
22939
+ function oneSubnetPerAz(subnets) {
22940
+ const seen = new Map;
22941
+ for (const s of [...subnets].sort((a, b) => a.az.localeCompare(b.az) || a.id.localeCompare(b.id)))
22942
+ if (!seen.has(s.az))
22943
+ seen.set(s.az, s.id);
22944
+ return [...seen.values()];
22945
+ }
22946
+ var toStack = (s) => ({
22947
+ name: s.StackName,
22948
+ status: s.StackStatus,
22949
+ ...s.StackStatusReason ? { reason: s.StackStatusReason } : {},
22950
+ ...s.CreationTime ? { created: s.CreationTime } : {},
22951
+ outputs: Object.fromEntries((s.Outputs ?? []).map((o) => [o.OutputKey, o.OutputValue])),
22952
+ rdsId: s.Parameters?.find((p) => p.ParameterKey === "RdsInstanceIdentifier")?.ParameterValue
22953
+ });
22954
+ async function findStacks(run, rdsId, region) {
22955
+ const all = (await run(["cloudformation", "describe-stacks", "--region", region])).Stacks ?? [];
22956
+ const live = all.map(toStack).filter((s) => stackState(s.status) !== "deleting");
22957
+ const forThis = (s) => s.rdsId?.toLowerCase() === rdsId;
22958
+ const named = live.find((s) => s.name === stackNameFor(rdsId));
22959
+ const stacks = live.filter((s) => forThis(s) && (s === named || ("VpceServiceName" in s.outputs) || stackState(s.status) !== "ready"));
22960
+ return { stacks, ...named && !forThis(named) ? { misnamed: named } : {} };
22961
+ }
22962
+ async function stackFailure(run, name, region) {
22963
+ try {
22964
+ const r = await run(["cloudformation", "describe-stack-events", "--stack-name", name, "--region", region]);
22965
+ const failed = (r.StackEvents ?? []).filter((e) => /_FAILED$/.test(e.ResourceStatus) && e.ResourceStatusReason && !/cancelled/i.test(e.ResourceStatusReason));
22966
+ const first = failed[failed.length - 1];
22967
+ return first ? `${first.LogicalResourceId}: ${first.ResourceStatusReason}` : undefined;
22968
+ } catch {
22969
+ return;
22970
+ }
22971
+ }
22972
+ function stackState(status) {
22973
+ if (status === "DELETE_IN_PROGRESS" || status === "DELETE_COMPLETE")
22974
+ return "deleting";
22975
+ if (status === "ROLLBACK_IN_PROGRESS")
22976
+ return "in_progress";
22977
+ if (/^(CREATE_COMPLETE|UPDATE_COMPLETE|UPDATE_ROLLBACK_COMPLETE|IMPORT_COMPLETE|IMPORT_ROLLBACK_COMPLETE)$/.test(status))
22978
+ return "ready";
22979
+ if (/^(CREATE|UPDATE|UPDATE_ROLLBACK|IMPORT|IMPORT_ROLLBACK|REVIEW)_IN_PROGRESS$|^UPDATE(_ROLLBACK)?_COMPLETE_CLEANUP_IN_PROGRESS$/.test(status))
22980
+ return "in_progress";
22981
+ return "failed";
22982
+ }
22983
+ function quickCreateUrl(i) {
22984
+ const params = new URLSearchParams({ templateURL: CFN_TEMPLATE_URL, stackName: stackNameFor(i.rdsId) });
22985
+ params.set("param_RdsInstanceIdentifier", i.rdsId);
22986
+ params.set("param_RdsPort", String(i.port));
22987
+ if (i.vpcId)
22988
+ params.set("param_VpcId", i.vpcId);
22989
+ if (i.subnetIds?.length)
22990
+ params.set("param_SubnetIds", i.subnetIds.join(","));
22991
+ if (i.securityGroupId)
22992
+ params.set("param_RdsSecurityGroupId", i.securityGroupId);
22993
+ params.set("param_PostgresAiAccountArn", PRINCIPAL_ARN);
22994
+ if (i.externalId)
22995
+ params.set("param_PostgresAiExternalId", i.externalId);
22996
+ return `https://${i.region}.console.aws.amazon.com/cloudformation/home?region=${encodeURIComponent(i.region)}#/stacks/quickcreate?${params.toString()}`;
22997
+ }
22998
+ function terraformFiles(mainTf, i) {
22999
+ const q = JSON.stringify;
23000
+ const tfvars = [
23001
+ `aws_region = ${q(i.region)}`,
23002
+ ...i.externalId ? [`postgres_ai_external_id = ${q(i.externalId)}`] : [],
23003
+ `rds_instance_identifier = ${q(i.rdsId)}`,
23004
+ `rds_port = ${i.port}`,
23005
+ i.vpcId ? `vpc_id = ${q(i.vpcId)}` : `# vpc_id = "vpc-..." (the RDS's VPC)`,
23006
+ i.subnetIds?.length ? `subnet_ids = [${i.subnetIds.map((s) => q(s)).join(", ")}]` : `# subnet_ids = ["subnet-...", "subnet-..."] (one per availability zone)`,
23007
+ i.securityGroupId ? `rds_security_group_id = ${q(i.securityGroupId)}` : `# rds_security_group_id = "sg-..." (the RDS's security group)`
23008
+ ].join(`
23009
+ `);
23010
+ return { mainTf, tfvars: `${tfvars}
23011
+ ` };
23012
+ }
23013
+
22832
23014
  // lib/supabase.ts
22833
23015
  var SUPABASE_API_BASE = "https://api.supabase.com";
22834
23016
  function extractProjectRefFromUrl(dbUrl) {
@@ -23169,9 +23351,17 @@ async function connect(url, opts, deps) {
23169
23351
  const key = parseClickhouseKey(opts.clickhouseKey, provider === "clickhouse" && !opts.agent ? process.env : {});
23170
23352
  if (key && provider !== "clickhouse")
23171
23353
  throw new Error("--clickhouse-key applies to ClickHouse Managed Postgres only");
23354
+ const plFlag = privateLinkFlag(opts);
23172
23355
  if (!opts.selfHosted && provider === "rds") {
23173
- const ignored = monitoringUser ? ` (${opts.agent ? "monitoring_user" : "--monitoring-user"} is not used there)` : "";
23174
- return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}${ignored}` };
23356
+ const route = await rdsRoute(url, opts, deps, progress);
23357
+ if ("status" in route)
23358
+ return { ...route, provider, name };
23359
+ if (route.private)
23360
+ return deployPrivateLink(url, route, { ...opts, monitoringUser }, deps, progress);
23361
+ if (plFlag)
23362
+ return { status: "action_required", provider, name, next: `${plFlag} applies to AWS PrivateLink only, and ${name} is monitored directly${opts.privatelink === false ? ` (${opts.agent ? "privatelink: false" : "--no-privatelink"})` : " (it is publicly accessible)"}` };
23363
+ } else if (plFlag) {
23364
+ return { status: "action_required", provider, name, next: `${plFlag} applies to Amazon RDS monitored from PostgresAI Cloud only` };
23175
23365
  }
23176
23366
  if (opts.selfHosted && opts.resetPassword) {
23177
23367
  return { status: "action_required", provider, name, next: "--reset-password works with PostgresAI Cloud only (it checks what else monitors this server): deploy without --self-hosted, or set PGAI_MON_PASSWORD" };
@@ -23878,6 +24068,550 @@ async function supabaseBox(ref, name, opts, deps, progress, stop, label) {
23878
24068
  return { ...connectStatus(box, provider, true), ...b.billing };
23879
24069
  return follow(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "", place }, opts, deps, progress);
23880
24070
  }
24071
+ var PL = "AWS PrivateLink";
24072
+ var STACK_WAIT_MS = 30 * 60000;
24073
+ var STACK_POLL_MS = 15000;
24074
+ function privateLinkFlag(opts) {
24075
+ const named = [
24076
+ [opts.privatelink === true ? true : undefined, "--privatelink", "privatelink"],
24077
+ [opts.vpceService, "--vpce-service", "vpce_service"],
24078
+ [opts.hostStats ? true : undefined, "--host-stats", "host_stats"],
24079
+ [opts.hostStatsRole, "--host-stats-role", "host_stats_role"],
24080
+ [opts.terraform ? true : undefined, "--terraform", "terraform"],
24081
+ [opts.agent ? opts.nonce : undefined, "PGAI_MON_NONCE", "nonce"]
24082
+ ];
24083
+ const hit = named.find(([v]) => v !== undefined);
24084
+ return hit && (opts.agent ? hit[2] : hit[1]);
24085
+ }
24086
+ async function rdsRoute(url, opts, deps, progress) {
24087
+ const host = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
24088
+ const ep = rdsEndpoint(host);
24089
+ const flag = (cli, agent) => opts.agent ? agent : cli;
24090
+ const stop = (next) => ({ status: "action_required", next });
24091
+ if (opts.privatelink === false)
24092
+ return { private: false };
24093
+ const asked = opts.privatelink === true;
24094
+ let read = {};
24095
+ if (ep?.kind === "instance" && ep.partition === "aws" && opts.aws !== false && deps.aws)
24096
+ read = await readAws(ep, opts, deps, progress);
24097
+ let isPublic = read.inst?.publiclyAccessible;
24098
+ if (isPublic === undefined && ep && deps.publicAddresses) {
24099
+ progress("preparing", `Looking up ${host} in public DNS (cloudflare-dns.com, dns.google): is it publicly accessible?`);
24100
+ const addresses = await deps.publicAddresses(host);
24101
+ if (addresses?.length) {
24102
+ isPublic = !addresses.every(isPrivateAddress);
24103
+ progress("preparing", `${host} resolves to a ${isPublic ? "public address in public DNS, so it is monitored directly" : `private address in public DNS, so it is monitored over ${PL}`}`);
24104
+ }
24105
+ }
24106
+ if (isPublic === true) {
24107
+ if (asked)
24108
+ return stop(`${host} is publicly accessible, so it is monitored directly: deploy without ${flag("--privatelink", "privatelink")}`);
24109
+ return { private: false };
24110
+ }
24111
+ if (isPublic === undefined && !asked) {
24112
+ if (!deps.ask || opts.yes)
24113
+ return stop(`Could not tell whether ${host} is publicly accessible (AWS ${opts.aws === false ? "not read" : "not readable here"}, and public DNS did not answer): re-run with ${flag("--privatelink", "privatelink: true")} if it is not, or ${flag("--no-privatelink", "privatelink: false")} if it is`);
24114
+ const a = (await deps.ask(`Is ${host} publicly accessible? [y]es, monitor it directly / [n]o, over ${PL} / Enter to stop: `)).trim().toLowerCase();
24115
+ if (a === "y" || a === "yes")
24116
+ return { private: false };
24117
+ if (a !== "n" && a !== "no")
24118
+ return stop("Stopped: nothing was created");
24119
+ }
24120
+ if (!ep)
24121
+ return stop(`${PL} needs the RDS instance endpoint (<instance>.<id>.<region>.rds.amazonaws.com) in the URL, not ${host}; or monitor from this network with --self-hosted`);
24122
+ if (ep.partition !== "aws")
24123
+ return stop(`${ep.partition === "aws-cn" ? "AWS China" : "AWS GovCloud"} can't reach PostgresAI over ${PL} (it does not cross AWS partitions): monitor from this network with --self-hosted`);
24124
+ if (ep.kind !== "instance" || read.inst?.engine?.startsWith("aurora"))
24125
+ return stop(`${ep.kind === "proxy" ? "An RDS Proxy endpoint" : "Aurora"} is not supported over ${PL} yet: monitor from this network with --self-hosted, or ask support@postgres.ai`);
24126
+ return { private: true, ep, ...read };
24127
+ }
24128
+ async function readAws(ep, opts, deps, progress) {
24129
+ let profile = opts.awsProfile?.trim() || undefined;
24130
+ for (let tries = 0;tries < 3; tries++) {
24131
+ const run = deps.aws(profile);
24132
+ const of = profile ? ` (profile ${profile})` : "";
24133
+ let why;
24134
+ let missing = false;
24135
+ try {
24136
+ const me = await callerIdentity(run);
24137
+ const inst = await describeDbInstance(run, ep.id, ep.region);
24138
+ progress("preparing", `AWS account ${me.account} (${me.arn.split(":").pop()}), read-only: ${ep.id} is ${inst.publiclyAccessible ? "publicly accessible, so it is monitored directly" : `not publicly accessible, so it is monitored over ${PL}`}`);
24139
+ return { aws: run, inst };
24140
+ } catch (err) {
24141
+ if (!(err instanceof AwsError))
24142
+ throw err;
24143
+ missing = err.kind === "missing";
24144
+ why = missing ? "the aws CLI is not installed here" : err.kind === "not_found" ? `${ep.id} is not in ${ep.region} of this AWS account${of}` : err.kind === "credentials" ? `the AWS credentials${of} do not work: ${err.message}` : `AWS refused${of}: ${err.message}`;
24145
+ }
24146
+ if (missing || !deps.ask || opts.yes) {
24147
+ progress("preparing", `Note: ${why}; going on without AWS${missing ? "" : ` (${opts.agent ? "aws_profile" : "--aws-profile"} picks a profile)`}`);
24148
+ return {};
24149
+ }
24150
+ const profiles = deps.awsProfiles ? await deps.awsProfiles().catch(() => []) : [];
24151
+ const a = (await deps.ask(`AWS profile to read ${ep.id} with${profiles.length ? ` (${profiles.join(", ")})` : ""}, or Enter to go on without AWS: `, [`${why}.`])).trim();
24152
+ if (!a)
24153
+ return {};
24154
+ profile = a;
24155
+ }
24156
+ return {};
24157
+ }
24158
+ var VERIFY_FAILED = {
24159
+ unreachable: "The monitoring box could not reach the database over PrivateLink: check that the stack finished, its load balancer's target is healthy, and the RDS is not publicly accessible.",
24160
+ auth_failed: `The monitoring box reached the database, but ${DEFAULT_MONITORING_USER} could not log in with the password this deploy's SQL set: the SQL did not run there, or another setup ran its SQL after it.`,
24161
+ nonce_mismatch: "The database's newest PostgresAI setup is not this deploy's: its SQL did not run in this database, or a newer one ran after it (another deploy, or the Console), so monitoring does not start."
24162
+ };
24163
+ var utc = (iso) => {
24164
+ const d = new Date(iso);
24165
+ return Number.isNaN(d.getTime()) ? iso : `${d.toISOString().slice(0, 19).replace("T", " ")} UTC`;
24166
+ };
24167
+ function inDatabase(url, db) {
24168
+ const u = new URL(url);
24169
+ if (u.pathname.length <= 1)
24170
+ u.pathname = `/${encodeURIComponent(db)}`;
24171
+ return u.toString();
24172
+ }
24173
+ function roleUrl(url, db, password) {
24174
+ const u = new URL(loginUrlFor(url, DEFAULT_MONITORING_USER, db, password));
24175
+ u.pathname = new URL(inDatabase(url, db)).pathname;
24176
+ return u.toString();
24177
+ }
24178
+ async function deployPrivateLink(url, route, opts, deps, progress) {
24179
+ const provider = "rds";
24180
+ const { ep, inst } = route;
24181
+ const name = databaseName2(url);
24182
+ const db = name.split("/").slice(1).join("/") || "postgres";
24183
+ const port = Number(new URL(url).port || inst?.port || 5432);
24184
+ const cluster = `${ep.host}:${port}`;
24185
+ const flag = (cli, agent) => opts.agent ? agent : cli;
24186
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
24187
+ const notHere = [
24188
+ [opts.cloud, "--cloud", "cloud"],
24189
+ [opts.location, "--location", "location"],
24190
+ [opts.name, "--name", "name"],
24191
+ [opts.ipFirst || undefined, "--ip-first", "ip_first"],
24192
+ [opts.ipAllowed || undefined, "--ip-allowed", "ip_allowed"],
24193
+ [opts.resetPassword || undefined, "--reset-password", "reset_password"],
24194
+ [opts.monitoringUser, "--monitoring-user", "monitoring_user"]
24195
+ ].find(([v]) => v !== undefined && v !== "");
24196
+ if (notHere)
24197
+ return stop(`${flag(notHere[1], notHere[2])} does not apply over ${PL}: the box runs on AWS in ${ep.region} (the RDS's region), as ${DEFAULT_MONITORING_USER}, in a project named ${ep.id}`);
24198
+ if (opts.monitoringPassword === undefined !== (opts.nonce === undefined)) {
24199
+ return stop(opts.agent ? "Pass monitoring_password and nonce together (both from the prepare_db result)" : "Set PGAI_MON_PASSWORD and PGAI_MON_NONCE together (both from the printed SQL's result), or neither");
24200
+ }
24201
+ const rows = await deps.list();
24202
+ const live = rows.filter((d) => !disconnecting(d.status));
24203
+ const onServer = live.filter((d) => d.cluster && serverOf(d.cluster) === cluster);
24204
+ const verify = async (row) => VERIFY_FAILED[(await deps.rdsStatus?.(row.id).catch(() => {
24205
+ return;
24206
+ }))?.verified_status ?? ""];
24207
+ const own = onServer.find((d) => (d.provider === "rds" || d.provider === "aurora") && d.database != null && decodeURIComponent(d.database) === db);
24208
+ if (own) {
24209
+ const note = opts.vpceService || opts.hostStatsRole ? "; the flags for a new box were not used: it exists" : "";
24210
+ return overPrivateLink(await follow(own, { provider, name, fresh: false, billing: {}, note, verify }, opts, deps, progress));
24211
+ }
24212
+ const already = (d, how) => {
24213
+ const instead = d.database != null && decodeURIComponent(d.database) !== db ? `To monitor ${db} instead` : "To set it up from here instead";
24214
+ return stop(`${ep.id} is already monitored ${how} (instance ${d.name}). Setting up another instance would change ${DEFAULT_MONITORING_USER}'s password, which that instance logs in with. ${instead}, delete that instance first (pgai mon instances delete ${deleteRef(d, rows)})`);
24215
+ };
24216
+ if (onServer.length)
24217
+ return already(onServer[0], onServer[0].provider === "rds" ? `over ${PL}, database ${decodeURIComponent(onServer[0].database ?? "?")}` : "directly");
24218
+ const candidates = live.filter((r) => !r.cluster || r.provider === "rds" || r.provider === "aurora");
24219
+ let routes;
24220
+ try {
24221
+ routes = await Promise.all(candidates.map((d) => deps.rdsStatus?.(d.id).catch((err) => {
24222
+ if (httpStatus(err) === 404)
24223
+ return;
24224
+ throw err;
24225
+ })));
24226
+ } catch (err) {
24227
+ return stop(`Could not check what already monitors ${ep.id} (${errorText(err)}): re-run pgai mon deploy. Nothing was changed`);
24228
+ }
24229
+ const viaConsole = candidates.find((_, i) => routes[i]?.rds_endpoint.toLowerCase().replace(/\.$/, "") === ep.host);
24230
+ if (viaConsole)
24231
+ return already(viaConsole, `over ${PL}, set up in the console`);
24232
+ const hostStats = !!opts.hostStats || !!opts.hostStatsRole?.trim();
24233
+ const place = { cloud: "aws", location: ep.region, location_reason: "privatelink", location_reason_text: `same region as your database, over ${PL}` };
24234
+ progress("preparing", `Monitoring box: AWS, ${ep.region} (${place.location_reason_text})`, { cloud: "aws", location: ep.region, location_reason: "privatelink" });
24235
+ let quote;
24236
+ try {
24237
+ quote = await deps.quote(opts.coupon);
24238
+ } catch (err) {
24239
+ if (err instanceof HttpStatusError && err.status === 403)
24240
+ return stop(notAdminNext);
24241
+ throw err;
24242
+ }
24243
+ let vcpus = opts.vcpus;
24244
+ if (vcpus === undefined && route.aws && inst?.instanceClass) {
24245
+ vcpus = await vcpusOfClass(route.aws, inst.instanceClass, ep.region);
24246
+ if (vcpus)
24247
+ progress("billing", `vCPUs: ${vcpus} (${inst.instanceClass})`);
24248
+ }
24249
+ const where = `AWS, ${ep.region}`;
24250
+ const b = await billingFor(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)), async (price) => {
24251
+ if (opts.yes)
24252
+ return { go: true };
24253
+ if (deps.ask) {
24254
+ return await deps.confirm(`Deploy ${terminalText(name)} over ${PL} (monitoring box on ${where})? [y/N] `) ? { go: true } : { go: false, stop: { next: `Nothing was created: re-run with --yes to deploy over ${PL}` } };
24255
+ }
24256
+ return { go: false, stop: { next: opts.agent ? `Show the user the price (${price}); the monitoring box runs on ${where}, reached over ${PL}. Then call deploy_monitoring again with yes: true. Nothing was created.` : `The monitoring box would run on ${where} for ${price}, reached over ${PL}: re-run with --yes to deploy. Nothing was created.` } };
24257
+ });
24258
+ if (b.stop)
24259
+ return { ...stop(b.stop.next), ...place, ...b.stop };
24260
+ if (deps.aborted?.())
24261
+ throw new CancelledError;
24262
+ const more = { ...place, ...b.billing };
24263
+ if (vcpus === undefined) {
24264
+ vcpus = !opts.yes && !opts.agent && deps.askVcpus ? await deps.askVcpus(VCPUS_QUESTION) : undefined;
24265
+ if (deps.aborted?.())
24266
+ throw new CancelledError;
24267
+ if (vcpus === undefined)
24268
+ progress("billing", NO_VCPUS_NOTE);
24269
+ }
24270
+ const stack = await privateLinkStack({ ep, aws: route.aws, inst, port, hostStats, opts, deps, progress, stop: (next, m = {}) => stop(next, { ...more, ...m }) });
24271
+ if ("status" in stack)
24272
+ return stack;
24273
+ if (deps.aborted?.())
24274
+ throw new CancelledError;
24275
+ const role = await privateLinkRole(url, db, opts, deps, progress, (next, m = {}) => stop(next, { ...more, ...m }));
24276
+ if ("status" in role)
24277
+ return role;
24278
+ if (deps.aborted?.())
24279
+ throw new CancelledError;
24280
+ progress("provisioning", `Provisioning monitoring for ${name} over ${PL}`);
24281
+ const created = await deps.rdsProvision({
24282
+ vpce_service_name: stack.vpce,
24283
+ rds_endpoint: ep.host,
24284
+ db_password: role.password,
24285
+ rds_port: port,
24286
+ rds_database: db,
24287
+ region: ep.region,
24288
+ ...b.accepted ? { accept_price: true } : {},
24289
+ ...opts.coupon ? { promo_code: opts.coupon } : {},
24290
+ ...stack.roleArn ? { host_stats_role_arn: stack.roleArn } : {},
24291
+ ...vcpus ? { vcpus } : {}
24292
+ }).catch((err) => {
24293
+ if (err instanceof HttpStatusError && err.status === 402)
24294
+ return /declined/i.test(err.message) ? "declined" : "payment";
24295
+ if (err instanceof HttpStatusError && err.status === 412)
24296
+ return "price";
24297
+ if (err instanceof HttpStatusError && err.status < 500)
24298
+ return { refused: errorText(err) };
24299
+ if (mayHaveRun(err))
24300
+ return "unanswered";
24301
+ throw err;
24302
+ });
24303
+ if (typeof created === "object" && "refused" in created)
24304
+ return stop(`${created.refused.replace(/\.?$/, ".")} No monitoring box was created.`, more);
24305
+ if (created === "payment")
24306
+ return { status: "action_required", provider, name, ...place, ...b.billingPage };
24307
+ if (created === "declined")
24308
+ return { status: "action_required", provider, name, ...place, ...b.billingPage, next: b.billingPage.next.replace(/^Add a payment method at /, "The payment method on file was declined: update it at ") };
24309
+ if (created === "price")
24310
+ return stop("The price changed since it was shown: re-run pgai mon deploy to see it", more);
24311
+ let box;
24312
+ if (created === "unanswered") {
24313
+ progress("provisioning", STILL_CREATING);
24314
+ const known = new Set(rows.map((d) => d.id));
24315
+ const made = await lookForBox((list) => list.find((d) => !known.has(d.id) && !!d.cluster && serverOf(d.cluster) === cluster), opts, deps, deps.now());
24316
+ if (!made)
24317
+ return stop(deps.aborted?.() ? STOPPED_LOOKING : opts.agent ? NOT_CONFIRMED_AGENT : NOT_CONFIRMED, more);
24318
+ box = made;
24319
+ } else {
24320
+ box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: !!stack.roleArn };
24321
+ }
24322
+ if (deps.aborted?.())
24323
+ return { ...connectStatus(box, provider, true), ...more };
24324
+ return overPrivateLink(await follow(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "", place, verify }, opts, deps, progress));
24325
+ }
24326
+ var PRIVATELINK_LAUNCH_FAILED = `The monitoring box could not connect to the stack's endpoint service: check that the stack finished, and that the endpoint service (VPC console, Endpoint services, Allow principals) lists ${PRINCIPAL_ARN}.`;
24327
+ function overPrivateLink(r, why) {
24328
+ const { egress_ip: _ip, ...rest } = r;
24329
+ if (rest.status === "ready")
24330
+ return rest;
24331
+ const said = Object.values(VERIFY_FAILED).some((t) => rest.next.includes(t));
24332
+ const first = said ? undefined : why ?? (rest.status === "failed" ? PRIVATELINK_LAUNCH_FAILED : undefined);
24333
+ return first ? { ...rest, next: `${first} ${rest.status === "failed" ? "Then: " : ""}${rest.next}` } : rest;
24334
+ }
24335
+ async function privateLinkStack(c) {
24336
+ const { ep, opts, deps, progress } = c;
24337
+ const flag = (cli, agent) => opts.agent ? agent : cli;
24338
+ const terminal = !!deps.ask;
24339
+ const ask = opts.yes ? undefined : deps.ask;
24340
+ let aws = opts.terraform ? undefined : c.aws;
24341
+ let vpce = opts.vpceService?.trim() || undefined;
24342
+ let roleArn = opts.hostStatsRole?.trim() || undefined;
24343
+ const badVpce = (v) => {
24344
+ const m = VPCE_SERVICE.exec(v);
24345
+ if (!m)
24346
+ return `${v} is not a VpceServiceName (com.amazonaws.vpce.<region>.vpce-svc-<id>, the stack's output)`;
24347
+ if (m[1] !== ep.region)
24348
+ return `${v} is in ${m[1]}, and ${ep.id} in ${ep.region}: ${PL} connects within one region, so use the stack made in ${ep.region}`;
24349
+ return;
24350
+ };
24351
+ if (roleArn && !ROLE_ARN.test(roleArn))
24352
+ return c.stop(`${roleArn} is not an IAM role ARN (arn:aws:iam::<account>:role/<name>, the stack's HostStatsRoleArn output)`);
24353
+ if (vpce && badVpce(vpce))
24354
+ return c.stop(badVpce(vpce));
24355
+ let externalId;
24356
+ const externalIdOf = async () => externalId ??= await deps.rdsExternalId();
24357
+ let shown;
24358
+ const show = async () => {
24359
+ const inputs = {
24360
+ region: ep.region,
24361
+ rdsId: ep.id,
24362
+ port: c.port,
24363
+ vpcId: c.inst?.vpcId,
24364
+ subnetIds: c.inst ? oneSubnetPerAz(c.inst.subnets) : undefined,
24365
+ securityGroupId: c.inst?.securityGroupIds.length === 1 ? c.inst.securityGroupIds[0] : undefined,
24366
+ ...c.hostStats ? { externalId: await externalIdOf() } : {}
24367
+ };
24368
+ const cfn = quickCreateUrl(inputs);
24369
+ const [vpcKey, subnetsKey, sgKey] = opts.terraform ? ["vpc_id", "subnet_ids", "rds_security_group_id"] : ["VpcId", "SubnetIds", "RdsSecurityGroupId"];
24370
+ const w = sgKey.length + 2;
24371
+ const blanks = [
24372
+ !inputs.vpcId && ` ${vpcKey.padEnd(w)}the RDS's VPC`,
24373
+ !inputs.subnetIds?.length && ` ${subnetsKey.padEnd(w)}one subnet per availability zone of the RDS's subnet group`,
24374
+ !inputs.securityGroupId && ` ${sgKey.padEnd(w)}the RDS's security group`
24375
+ ].filter((l) => !!l);
24376
+ const choose = blanks.length ? `
24377
+ ${opts.terraform ? "In terraform.tfvars, fill in" : "In the form, choose (empty in the link)"}:
24378
+ ${blanks.join(`
24379
+ `)}
24380
+ (the RDS console lists them: ${ep.id}, Connectivity & security)` : "";
24381
+ let dir;
24382
+ if (opts.terraform)
24383
+ dir = await deps.writeTerraform(stackNameFor(ep.id), terraformFiles(await deps.terraformModule(), inputs));
24384
+ const where = deps.openUrl ? "" : `
24385
+ Open it in a browser signed in to that AWS account.`;
24386
+ const tf = opts.agent ? "" : `
24387
+ Prefer Terraform? ${deps.ask ? "Stop (Ctrl-C) and re-run" : "Re-run"} with --terraform: it writes the same stack as a module.`;
24388
+ progress("privatelink", dir ? `Terraform for the PrivateLink stack written to ${dir}: terraform init && terraform apply there${choose}` : `Create the PrivateLink stack in your AWS account from this link; nothing becomes public:${choose}
24389
+ ${cfn}${where}${tf}`, { cfn_url: cfn, stack_name: stackNameFor(ep.id) });
24390
+ return {
24391
+ step: "privatelink_stack",
24392
+ cfn_url: cfn,
24393
+ stack_name: stackNameFor(ep.id),
24394
+ region: ep.region,
24395
+ ...inputs.externalId ? { external_id: inputs.externalId } : {},
24396
+ ...dir ? { terraform_dir: dir } : {},
24397
+ ...blanks.length ? { choose_in_form: blanks.map((l) => l.trim().split(/\s+/)[0]) } : {}
24398
+ };
24399
+ };
24400
+ const resume = () => {
24401
+ const output = opts.terraform ? "vpce_service_name output" : "VpceServiceName output";
24402
+ const role = c.hostStats && !roleArn ? ` and ${flag("--host-stats-role", "host_stats_role")} <its ${opts.terraform ? "host_stats_role_arn" : "HostStatsRoleArn"} output>` : "";
24403
+ return aws ? opts.agent ? "call deploy_monitoring again" : "re-run pgai mon deploy" : `${opts.agent ? "call deploy_monitoring again with" : "re-run with"} ${flag("--vpce-service", "vpce_service")} <its ${output}>${role}`;
24404
+ };
24405
+ const deadline = deps.now() + STACK_WAIT_MS;
24406
+ let refusedPaste;
24407
+ let saidMisnamed = false;
24408
+ let readStack = false;
24409
+ const seenMaking = new Set;
24410
+ const saidFailed = new Set;
24411
+ const startedAt = Date.now() - 60000;
24412
+ const thisRuns = (s) => s.name === stackNameFor(ep.id) || seenMaking.has(s.name) || !!s.created && Date.parse(s.created) >= startedAt;
24413
+ for (let pastes = 0, empties = 0;!vpce; ) {
24414
+ let found = [];
24415
+ if (aws) {
24416
+ try {
24417
+ const r = await findStacks(aws, ep.id, ep.region);
24418
+ found = r.stacks;
24419
+ if (r.misnamed && !saidMisnamed) {
24420
+ saidMisnamed = true;
24421
+ progress("privatelink", `Note: stack ${r.misnamed.name} is for RDS ${r.misnamed.rdsId ?? "(none)"}, not ${ep.id}: not used. Give the new stack another name in the form`);
24422
+ }
24423
+ } catch (err) {
24424
+ if (!(err instanceof AwsError))
24425
+ throw err;
24426
+ progress("privatelink", `Note: could not read CloudFormation (${err.message}); going on without AWS`);
24427
+ aws = undefined;
24428
+ }
24429
+ }
24430
+ const ready = found.filter((s) => stackState(s.status) === "ready" && s.outputs.VpceServiceName);
24431
+ let stack;
24432
+ if (ready.length === 1)
24433
+ stack = ready[0];
24434
+ else if (ready.length > 1) {
24435
+ const rows = ready.map((s, i) => ` ${i + 1}. ${s.name} ${s.status}${s.created ? ` created ${utc(s.created)}` : ""} ${s.outputs.VpceServiceName}`);
24436
+ const listed = {
24437
+ step: "privatelink_stack",
24438
+ region: ep.region,
24439
+ stacks: ready.map((s) => ({ name: s.name, status: s.status, created: s.created ?? null, vpce_service_name: s.outputs.VpceServiceName }))
24440
+ };
24441
+ if (!ask) {
24442
+ return c.stop(`Several stacks publish ${ep.id}: ${opts.agent ? "ask the user which one, then call deploy_monitoring again with vpce_service" : "re-run with --vpce-service"} <the VpceServiceName of the one to use>. Nothing was created on PostgresAI yet.
24443
+ ${rows.join(`
24444
+ `)}`, listed);
24445
+ }
24446
+ for (let tries = 0;!stack && tries < 3; tries++) {
24447
+ const a = (await ask(`The stack to use (1-${ready.length}, Enter to stop): `, tries ? [`Type a number from 1 to ${ready.length}.`] : [`Several stacks publish ${ep.id}:`, ...rows])).trim();
24448
+ if (!a)
24449
+ return c.stop(`Stopped: re-run with --vpce-service <the VpceServiceName of the stack to use>. Nothing was created on PostgresAI yet.`, listed);
24450
+ const i = Number(a);
24451
+ if (Number.isInteger(i) && i >= 1 && i <= ready.length)
24452
+ stack = ready[i - 1];
24453
+ }
24454
+ if (!stack)
24455
+ return c.stop(`No stack picked: re-run with --vpce-service <the VpceServiceName of the stack to use>. Nothing was created on PostgresAI yet.`, listed);
24456
+ }
24457
+ if (stack) {
24458
+ vpce = stack.outputs.VpceServiceName;
24459
+ roleArn ??= stack.outputs.HostStatsRoleArn;
24460
+ readStack = true;
24461
+ progress("privatelink", `Using stack ${stack.name}${stack.created ? ` (created ${utc(stack.created)})` : ""}: ${vpce}`, { stack_name: stack.name });
24462
+ break;
24463
+ }
24464
+ for (const s of found)
24465
+ if (stackState(s.status) === "in_progress")
24466
+ seenMaking.add(s.name);
24467
+ const foreign = found.find((s) => s.name === stackNameFor(ep.id) && stackState(s.status) === "ready" && !s.outputs.VpceServiceName);
24468
+ if (foreign && !found.some((s) => stackState(s.status) === "in_progress")) {
24469
+ return c.stop(`Stack ${foreign.name} has no VpceServiceName output: it was not made from the PostgresAI template. Delete it, create the stack from the link deploy prints, then ${resume()}`, { step: "privatelink_stack", stack_name: foreign.name, region: ep.region });
24470
+ }
24471
+ const failedNow = found.filter((s) => stackState(s.status) === "failed").sort((a, b) => Date.parse(b.created ?? "") - Date.parse(a.created ?? "") || 0);
24472
+ const waits = terminal && !!aws;
24473
+ const failed = failedNow.find(thisRuns) ?? (waits ? undefined : failedNow[0]);
24474
+ for (const s of failedNow) {
24475
+ if (s === failed || saidFailed.has(s.name))
24476
+ continue;
24477
+ saidFailed.add(s.name);
24478
+ progress("privatelink", `Note: stack ${s.name} for ${ep.id} failed earlier (${s.status}): not used`);
24479
+ }
24480
+ if (failed && !found.some((s) => stackState(s.status) === "in_progress")) {
24481
+ const why = (aws && await stackFailure(aws, failed.name, ep.region) || failed.reason || failed.status).replace(/\s*\(RequestId: [^)]*\)/g, "");
24482
+ const fix = /^(CREATE_FAILED|ROLLBACK_|DELETE_FAILED)/.test(failed.status) ? `delete the stack, then re-run pgai mon deploy:
24483
+ aws cloudformation delete-stack --stack-name ${failed.name} --region ${ep.region}` : "repair the stack in the CloudFormation console (Stack actions, Continue update rollback), then re-run pgai mon deploy";
24484
+ return c.stop(`Stack ${failed.name} failed (${failed.status}): ${why}
24485
+ Fix that, ${fix}`, { step: "privatelink_stack", stack_name: failed.name, region: ep.region });
24486
+ }
24487
+ const being = found.find((s) => stackState(s.status) === "in_progress");
24488
+ const first = !shown;
24489
+ shown ??= await show();
24490
+ const making = being ? `Stack ${being.name} is ${/ROLLBACK/.test(being.status) ? "rolling back" : "being created"} (${being.status})` : undefined;
24491
+ if (!terminal || !aws && !ask) {
24492
+ const make = shown.terraform_dir ? `Run terraform init && terraform apply in ${shown.terraform_dir}` : opts.agent ? `Give the user cfn_url to open in the AWS account of ${ep.id}, to create the stack there${shown.choose_in_form ? ` (choosing ${shown.choose_in_form.join(", ")} in the form)` : ""}, or call again with terraform: true for the same as Terraform` : `Open the link below in the AWS account of ${ep.id} and create the stack there${shown.choose_in_form ? ` (choose ${shown.choose_in_form.join(", ")} in the form)` : ""}, or re-run with --terraform for the same as Terraform`;
24493
+ return c.stop(`${making ? `${making}: once it is CREATE_COMPLETE` : `${make}; once it is done`}, ${resume()}. Nothing was created on PostgresAI yet.`, shown);
24494
+ }
24495
+ const openIt = !shown.terraform_dir && deps.openUrl ? ", [o] to open the link in your browser" : "";
24496
+ if (aws) {
24497
+ if (first && openIt && ask) {
24498
+ const a = (await ask(`[o] opens the link in your browser; Enter waits for the stack: `)).trim().toLowerCase();
24499
+ if (a === "o")
24500
+ deps.openUrl(shown.cfn_url);
24501
+ }
24502
+ if (deps.aborted?.())
24503
+ throw new CancelledError;
24504
+ if (deps.now() >= deadline)
24505
+ return c.stop(`No stack for ${ep.id} was ready within ${STACK_WAIT_MS / 60000} minutes: re-run pgai mon deploy once it is. Nothing was created on PostgresAI yet.`, shown);
24506
+ progress("privatelink", making ?? `Waiting for you to create the stack from the link above (any name; deploy finds it by its RDS; up to ${STACK_WAIT_MS / 60000} min)`, { stack_name: being?.name ?? stackNameFor(ep.id) });
24507
+ await deps.sleep(STACK_POLL_MS);
24508
+ continue;
24509
+ }
24510
+ const output = opts.terraform ? "vpce_service_name output" : "VpceServiceName (CloudFormation, the stack, Outputs)";
24511
+ const a = (await ask(`Paste the stack's ${output}${openIt}, or [s] to stop: `, refusedPaste ? [refusedPaste] : [])).trim();
24512
+ if (a.toLowerCase() === "s")
24513
+ return c.stop(`Stopped: once the stack is done, ${resume()}. Nothing was created on PostgresAI yet.`, shown);
24514
+ if (!a) {
24515
+ if (++empties >= 3)
24516
+ return c.stop(`Stopped: once the stack is done, ${resume()}. Nothing was created on PostgresAI yet.`, shown);
24517
+ refusedPaste = `Paste the stack's ${opts.terraform ? "vpce_service_name output" : "VpceServiceName"} once it is created, or s to stop.`;
24518
+ continue;
24519
+ }
24520
+ empties = 0;
24521
+ if (openIt && a.toLowerCase() === "o") {
24522
+ deps.openUrl(shown.cfn_url);
24523
+ refusedPaste = undefined;
24524
+ continue;
24525
+ }
24526
+ refusedPaste = badVpce(a);
24527
+ if (!refusedPaste)
24528
+ vpce = a;
24529
+ else if (++pastes >= 3)
24530
+ return c.stop(refusedPaste, shown);
24531
+ }
24532
+ if (c.hostStats && !roleArn && !readStack) {
24533
+ const out = opts.terraform ? "host_stats_role_arn" : "HostStatsRoleArn";
24534
+ return c.stop(`Host metrics need the metrics role too: ${opts.agent ? "call deploy_monitoring again with" : "re-run with"} ${flag("--vpce-service", "vpce_service")} ${vpce} and ${flag("--host-stats-role", "host_stats_role")} <its ${out} output>. If it has none, it was made without this PostgresAiExternalId: ${opts.terraform ? "set postgres_ai_external_id in terraform.tfvars and apply again" : "update the stack with it"}; or deploy without ${flag("--host-stats", "host_stats")}.
24535
+ PostgresAiExternalId = ${await externalIdOf()}`, { external_id: externalId });
24536
+ }
24537
+ if (c.hostStats && !roleArn) {
24538
+ return c.stop(`Host metrics need the stack's metrics role (its HostStatsRoleArn output), and it has none: update the stack with this PostgresAiExternalId (it then creates a read-only role), then ${resume()}; or deploy without ${flag("--host-stats", "host_stats")}.
24539
+ PostgresAiExternalId = ${await externalIdOf()}`, { external_id: externalId });
24540
+ }
24541
+ return { vpce, ...roleArn ? { roleArn } : {} };
24542
+ }
24543
+ async function privateLinkRole(url, db, opts, deps, progress, stop) {
24544
+ let password = opts.monitoringPassword;
24545
+ let nonce = opts.nonce;
24546
+ const ask = opts.yes ? undefined : deps.ask;
24547
+ const warned = new Set;
24548
+ const warn = (m) => {
24549
+ if (!warned.has(m)) {
24550
+ warned.add(m);
24551
+ progress("preparing", m);
24552
+ }
24553
+ };
24554
+ const resumeWith = (n) => opts.agent ? `call deploy_monitoring again with monitoring_password and nonce from this result` : `re-run with PGAI_MON_NONCE=${n} and PGAI_MON_PASSWORD set to the v_password value near the top of the SQL`;
24555
+ let away = false;
24556
+ if (password === undefined || nonce === undefined) {
24557
+ let p;
24558
+ try {
24559
+ p = await deps.rdsPrepareSql(db);
24560
+ } catch (err) {
24561
+ if (err instanceof HttpStatusError && err.status === 403)
24562
+ return stop(notAdminNext);
24563
+ if (err instanceof HttpStatusError && err.status < 500)
24564
+ return stop(errorText(err));
24565
+ throw err;
24566
+ }
24567
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(p.nonce))
24568
+ throw new Error("cloud_monitoring_rds_prepare_sql returned a malformed nonce: nothing was changed");
24569
+ password = p.db_password;
24570
+ nonce = p.nonce;
24571
+ progress("preparing", `Preparing ${maskConnectionString(url)}`);
24572
+ const failed = await deps.runSql(inDatabase(url, db), p.prepare_db_sql, warn).then(() => {
24573
+ return;
24574
+ }, (err) => err);
24575
+ if (failed) {
24576
+ const e = failed;
24577
+ away = unreachable(failed);
24578
+ const refusedLogin = !away && (typeof e !== "object" || !e || !("severity" in e) || e.severity === "FATAL" || /^(28|3D|08)/.test(String(e.code ?? "")));
24579
+ if (refusedLogin)
24580
+ return stop(`Could not log in to ${maskConnectionString(inDatabase(url, db))}: ${errorText(failed)}. Check the URL's user and password`);
24581
+ const why = away ? `This machine can't reach the database (${errorText(failed)}), so the SQL does not run from here` : `The user in this URL (${decodeURIComponent(new URL(url).username)}) can't create ${DEFAULT_MONITORING_USER} (${errorText(failed)})`;
24582
+ const printed = { step: "prepare_db", sql: p.prepare_db_sql, nonce, monitoring_password: password };
24583
+ const run = `Run the SQL as the master user, connected to database ${db}${away ? ", from a machine that reaches it (in its VPC)" : ""}`;
24584
+ const only = `A deploy of this database without ${opts.agent ? "them" : "PGAI_MON_PASSWORD and PGAI_MON_NONCE"} issues a new SQL and replaces this one`;
24585
+ if (!ask)
24586
+ return stop(`${why}. ${run}, then ${resumeWith(nonce)}. ${only}.`, printed);
24587
+ const a = (await ask(`${run}, then press Enter ([s] to stop): `, [`${why}. The SQL:`, "", p.prepare_db_sql, ""])).trim().toLowerCase();
24588
+ if (a === "s" || a === "stop")
24589
+ return stop(`Stopped. ${run}, then ${resumeWith(nonce)}.`, { ...printed, sql: undefined });
24590
+ }
24591
+ }
24592
+ const boxChecks = (why) => {
24593
+ progress("preparing", `Not checked from here (${why}): the monitoring box checks that ${DEFAULT_MONITORING_USER} logs in to ${db} and that this SQL ran, and deploy says if it fails`);
24594
+ return { password, nonce };
24595
+ };
24596
+ if (away)
24597
+ return boxChecks("this machine can't reach the database");
24598
+ progress("preparing", `Checking that ${DEFAULT_MONITORING_USER} can log in to ${db} with the password the SQL set`);
24599
+ let found;
24600
+ try {
24601
+ found = await deps.readNonce(roleUrl(url, db, password), warn);
24602
+ } catch (err) {
24603
+ if (unreachable(err))
24604
+ return boxChecks(`this machine can't reach the database: ${errorText(err)}`);
24605
+ const fresh = opts.agent ? "call again without monitoring_password and nonce for a new SQL" : "re-run without PGAI_MON_PASSWORD and PGAI_MON_NONCE for a new SQL";
24606
+ return stop(opts.monitoringPassword === undefined ? `${DEFAULT_MONITORING_USER} could not log in to ${db} with the password the SQL set (${errorText(err)}): run the SQL again, connected to database ${db}` : opts.agent ? `${DEFAULT_MONITORING_USER} could not log in to ${db} with monitoring_password (${errorText(err)}): pass the monitoring_password of the prepare_db result whose SQL ran, or ${fresh}` : `${DEFAULT_MONITORING_USER} could not log in to ${db} with PGAI_MON_PASSWORD (${errorText(err)}): set it to the v_password value near the top of the SQL you ran, or ${fresh}`);
24607
+ }
24608
+ const again = opts.monitoringPassword !== undefined ? `${opts.agent ? "call again without monitoring_password and nonce" : "re-run without PGAI_MON_PASSWORD and PGAI_MON_NONCE"} for a new SQL, and run only that one` : "re-run pgai mon deploy";
24609
+ if (found === undefined)
24610
+ return stop(`The SQL has not run in database ${db} (perhaps in another database): run it connected to database ${db}, then ${resumeWith(nonce)}`);
24611
+ if (found !== nonce)
24612
+ return stop(`A newer PostgresAI setup SQL ran in database ${db} after this one (another deploy, or the Console): ${again}`);
24613
+ return { password, nonce };
24614
+ }
23881
24615
  var STILL_IN_PROGRESS = "Still in progress";
23882
24616
  var CONNECT_TIMEOUT_MS = 55000;
23883
24617
  var AGENT_CONNECT_TIMEOUT_MS = 25000;
@@ -23887,6 +24621,12 @@ var STOPPED_LOOKING = `${STILL_IN_PROGRESS}: deploy stopped watching before Post
23887
24621
  var NOT_CONFIRMED_AGENT = "PostgresAI did not confirm the monitoring box yet. Call deploy_monitoring again in a minute: it continues with the box if PostgresAI created it. If pgai mon instances list still has no box for this database, ask the user to run pgai mon deploy with --reset-password in a terminal";
23888
24622
  var LOOKUP_MS = 5 * 60000;
23889
24623
  var AGENT_RUN_MS = 50000;
24624
+ function unreachable(err) {
24625
+ if (typeof err !== "object" || !err || "severity" in err)
24626
+ return false;
24627
+ const codes = [err.code, ...(err.errors ?? []).map((e) => e?.code)];
24628
+ return codes.some((c) => ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH", "ETIMEDOUT", "ECONNRESET"].includes(String(c))) || /connection timeout|timeout expired/i.test(err instanceof Error ? err.message : "");
24629
+ }
23890
24630
  function mayHaveRun(err) {
23891
24631
  if (err instanceof HttpRequestTimeoutError)
23892
24632
  return true;
@@ -23911,7 +24651,14 @@ async function follow(row, f, opts, deps, progress) {
23911
24651
  const url = (_) => f.url ?? name;
23912
24652
  const billing = { ...f.billing, ...f.place };
23913
24653
  let shown;
24654
+ let unverified;
23914
24655
  for (const deadline = deps.now() + opts.waitMs;; ) {
24656
+ if (f.verify) {
24657
+ const why = await f.verify(row);
24658
+ if (why && why !== unverified)
24659
+ progress("box", `Note: ${why}`, { id: row.id });
24660
+ unverified = why;
24661
+ }
23915
24662
  if (row.billing_error && disconnecting(row.status)) {
23916
24663
  if (undoRole)
23917
24664
  await undoRole();
@@ -23941,15 +24688,16 @@ async function follow(row, f, opts, deps, progress) {
23941
24688
  final.next += "; for CPU, memory and disk, delete the instance (pgai mon instances delete) and deploy again with --clickhouse-key <key-id>:<key-secret>";
23942
24689
  }
23943
24690
  const { next, ...rest } = final;
24691
+ const why = unverified && final.status !== "ready" ? `${unverified} ` : "";
23944
24692
  if (final.status === "in_progress" && opts.waitMs > 0) {
23945
24693
  return {
23946
24694
  ...rest,
23947
24695
  status: "action_required",
23948
24696
  ...billing,
23949
- next: `${STILL_IN_PROGRESS} (box: ${boxWords(boxState(row))}) when the wait ended: resume with ${next}${note}`
24697
+ next: `${STILL_IN_PROGRESS} (box: ${boxWords(boxState(row))}) when the wait ended: ${why}${why ? "Resume" : "resume"} with ${next}${note}`
23950
24698
  };
23951
24699
  }
23952
- return { ...rest, ...billing, next: next + note };
24700
+ return { ...rest, ...billing, next: why + next + note };
23953
24701
  }
23954
24702
  await deps.sleep(POLL_MS);
23955
24703
  const listed = await deps.list().catch(() => {
@@ -24030,7 +24778,8 @@ async function prepareDatabase(url, provider, opts = {}) {
24030
24778
  or (pg_has_role(current_user, 'pg_monitor', 'USAGE WITH ADMIN OPTION')
24031
24779
  and pg_has_role(current_user, 'pg_read_all_stats', 'USAGE WITH ADMIN OPTION')))
24032
24780
  and has_database_privilege(current_user, current_database(), 'CREATE')
24033
- and exists (select 1 from pg_extension where extname = 'pg_stat_statements')) as admin,
24781
+ and (exists (select 1 from pg_extension where extname = 'pg_stat_statements')
24782
+ or exists (select 1 from pg_roles where rolname = 'rds_superuser' and pg_has_role(current_user, oid, 'MEMBER')))) as admin,
24034
24783
  exists (select 1 from pg_roles where rolname = ${quoteLiteral(role)}) as mon_exists,
24035
24784
  exists (select 1 from pg_roles where rolname = ${quoteLiteral(role)} and (rolsuper or rolcreatedb or rolcreaterole or rolreplication or rolbypassrls)) as mon_privileged,
24036
24785
  (select string_agg(g.rolname::text, ', ' order by g.rolname::text collate "C") from pg_roles m join pg_roles g
@@ -24281,10 +25030,50 @@ function platformDeps(p) {
24281
25030
  supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
24282
25031
  supabaseProjects: () => rpc("cloud_monitoring_supabase_projects", {}),
24283
25032
  deployOptions: (args) => rpc("monitoring_deploy_options", args),
24284
- handoffUrl: async (provider) => {
24285
- const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
24286
- const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
24287
- return `${p.uiBaseUrl}/${org?.alias ?? "<org>"}/monitoring/scale/create/${provider}`;
25033
+ rdsExternalId: async () => (await rpc("cloud_monitoring_rds_external_id")).external_id,
25034
+ rdsPrepareSql: (dbName) => rpc("cloud_monitoring_rds_prepare_sql", { db_name: dbName }),
25035
+ rdsProvision: (body) => rpc("cloud_monitoring_rds_provision", body, p.agent ? AGENT_CONNECT_TIMEOUT_MS : CONNECT_TIMEOUT_MS),
25036
+ rdsStatus: (id) => rpc("cloud_monitoring_rds_status", { instance_id: id }),
25037
+ aws: awsRunner,
25038
+ awsProfiles: () => new Promise((resolve) => execFile2("aws", ["configure", "list-profiles"], { timeout: 1e4 }, (err, stdout) => resolve(err ? [] : stdout.split(`
25039
+ `).map((l) => l.trim()).filter(Boolean)))),
25040
+ publicAddresses: (host) => publicAddresses(host),
25041
+ runSql: async (url, sql, warn) => {
25042
+ const { client } = await openConnection(url, { agent: p.agent, warn });
25043
+ try {
25044
+ await client.query(sql);
25045
+ } finally {
25046
+ await client.end().catch(() => {});
25047
+ }
25048
+ },
25049
+ readNonce: async (url, warn) => {
25050
+ const { client } = await openConnection(url, { agent: p.agent, warn });
25051
+ try {
25052
+ const r = await client.query("select nonce from postgres_ai.monitoring_ownership order by issued_at desc limit 1");
25053
+ return r.rows[0]?.nonce;
25054
+ } catch (err) {
25055
+ if (["3F000", "42P01"].includes(err.code ?? ""))
25056
+ return;
25057
+ throw err;
25058
+ } finally {
25059
+ await client.end().catch(() => {});
25060
+ }
25061
+ },
25062
+ terraformModule: async () => {
25063
+ const r = await fetch(TERRAFORM_URL, { signal: AbortSignal.timeout(30000) });
25064
+ if (!r.ok)
25065
+ throw new Error(`Could not download the Terraform module (${TERRAFORM_URL}: HTTP ${r.status})`);
25066
+ return r.text();
25067
+ },
25068
+ writeTerraform: async (dirName, files) => {
25069
+ const dir = path5.resolve(dirName);
25070
+ await fs6.promises.mkdir(dir, { recursive: true });
25071
+ await fs6.promises.writeFile(path5.join(dir, "main.tf"), files.mainTf);
25072
+ await fs6.promises.writeFile(path5.join(dir, "terraform.tfvars"), files.tfvars, { flag: "wx" }).catch((err) => {
25073
+ if (err.code !== "EEXIST")
25074
+ throw err;
25075
+ });
25076
+ return dir;
24288
25077
  },
24289
25078
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
24290
25079
  now: () => Date.now()
@@ -30963,6 +31752,7 @@ async function handleToolCall(req, rootOpts, extra) {
30963
31752
  }
30964
31753
  try {
30965
31754
  if (toolName === "deploy_monitoring") {
31755
+ const str = (v) => v === undefined || v === null ? undefined : String(v);
30966
31756
  const scope = resolveMcpOrgScope(args, apiKey, cfg);
30967
31757
  if (scope.error)
30968
31758
  return scope.error;
@@ -30982,6 +31772,15 @@ async function handleToolCall(req, rootOpts, extra) {
30982
31772
  location: args.location === undefined || args.location === null ? undefined : String(args.location),
30983
31773
  ipFirst: args.ip_first === true,
30984
31774
  ipAllowed: args.ip_allowed === true,
31775
+ privatelink: typeof args.privatelink === "boolean" ? args.privatelink : undefined,
31776
+ vpceService: str(args.vpce_service),
31777
+ hostStats: args.host_stats === true,
31778
+ hostStatsRole: str(args.host_stats_role),
31779
+ awsProfile: str(args.aws_profile),
31780
+ aws: args.no_aws === true ? false : undefined,
31781
+ terraform: args.terraform === true,
31782
+ monitoringPassword: str(args.monitoring_password),
31783
+ nonce: str(args.nonce),
30985
31784
  waitMs: 0,
30986
31785
  agent: true
30987
31786
  }, {
@@ -31556,7 +32355,7 @@ async function startMcpServer(rootOpts, extra) {
31556
32355
  },
31557
32356
  {
31558
32357
  name: "deploy_monitoring",
31559
- description: "Put a Postgres database under PostgresAI Cloud monitoring (same as `pgai mon deploy`): prepares the monitoring role (an admin URL creates it; otherwise returns the SQL), provisions the monitoring box, and returns JSON with status (ready | in_progress | deleting | deleted | inactive | action_required | failed: the same words as pgai dblab deploy), health_url (the project's Health Matrix in the console), dashboard_url (Grafana, signing in with PostgresAI) and next (the exact next action). A billed box is provisioned only with yes: true: without it the result is action_required with the price (and requires_payment_method), so show the price to the user first. It does not wait for the box: call it again to see the status. Safe to call again. When PostgresAI can't reach the database the way an IP allowlist refuses (or with ip_first), the box's IP is reserved first and the result is action_required with step allow_ip (ip, cidr, host, port, reserved_until): give the user the cidr and port to allow on the database, then call again with ip_allowed: true. ClickHouse Managed Postgres, RDS and Supabase are detected from the host. Supabase needs no password (PostgresAI prepares the database through the Supabase Management API): the first time, the result is action_required with a consent link in next; give it to the user to open and approve, then call again. Elsewhere the URL must carry its password, and only these query parameters: sslmode, channel_binding, application_name. PGAI_MON_PASSWORD, PGPASSWORD and CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET of the server process are not used (pass clickhouse_key), and a TLS failure is not retried in plaintext (say sslmode=disable for a server without TLS). For another database on a server PostgresAI already monitors for the org, an admin URL with sslmode=require (or verify-*), each query parameter once, is enough: PostgresAI fills in the password of postgres_ai_mon it keeps, over TLS only (on a server without TLS, pass the postgres_ai_mon URL; if nobody has its password, the user runs in a terminal: pgai mon instances delete the server's other databases, then pgai mon deploy <admin-url> --reset-password with PGAI_MON_PASSWORD set to a new one, then deploys them again with it).",
32358
+ description: "Put a Postgres database under PostgresAI Cloud monitoring (same as `pgai mon deploy`): prepares the monitoring role (an admin URL creates it; otherwise returns the SQL), provisions the monitoring box, and returns JSON with status (ready | in_progress | deleting | deleted | inactive | action_required | failed: the same words as pgai dblab deploy), health_url (the project's Health Matrix in the console), dashboard_url (Grafana, signing in with PostgresAI) and next (the exact next action). A billed box is provisioned only with yes: true: without it the result is action_required with the price (and requires_payment_method), so show the price to the user first. It does not wait for the box: call it again to see the status. Safe to call again. When PostgresAI can't reach the database the way an IP allowlist refuses (or with ip_first), the box's IP is reserved first and the result is action_required with step allow_ip (ip, cidr, host, port, reserved_until): give the user the cidr and port to allow on the database, then call again with ip_allowed: true. ClickHouse Managed Postgres, RDS and Supabase are detected from the host. An RDS instance that is not publicly accessible is monitored over AWS PrivateLink (no public IP, nothing opened): the user creates a CloudFormation stack in their AWS account from a link. Until the stack exists the result is action_required with step privatelink_stack and cfn_url: give the user the link to open in the RDS's AWS account (the stack keeps its name); once they say it is created, call again. When this machine's aws CLI can read the RDS (read-only; aws_profile picks the profile, no_aws: true skips it), the link is filled in and the stack is found by itself; otherwise pass vpce_service, the stack's VpceServiceName output. When the URL's user can't create the monitoring role, or this machine can't reach the database (a private RDS seen from outside its VPC), the result is action_required with step prepare_db, sql, nonce and monitoring_password: the user runs the SQL as the master user in that database, then call again with monitoring_password and nonce. host_stats: true adds host CPU, memory, disk and IOPS through a read-only role the stack creates (host_stats_role: its HostStatsRoleArn output, when not read from AWS). Aurora and RDS Proxy endpoints are not supported over PrivateLink. 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).",
31560
32359
  inputSchema: {
31561
32360
  type: "object",
31562
32361
  properties: {
@@ -31569,9 +32368,18 @@ async function startMcpServer(rootOpts, extra) {
31569
32368
  location: { type: "string", description: "A location of that cloud, from the result's choices (default: the database's region, else the cloud's default)" },
31570
32369
  coupon: { type: "string", description: "Stripe promotion code for the organization's monitoring subscription (applies when it is first created)" },
31571
32370
  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" },
31572
- monitoring_user: { type: "string", description: "Monitoring role to create or use (default postgres_ai_mon). A custom role always carries its own password: PostgresAI keeps only postgres_ai_mon's, so pass the role's own URL as database_url (an admin URL creates only postgres_ai_mon). Not for Supabase, where PostgresAI creates postgres_ai_mon" },
32371
+ 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, nor for a private RDS over AWS PrivateLink" },
31573
32372
  ip_first: { type: "boolean", description: "Reserve the monitoring box's IP and stop before the box (even when PostgresAI can reach the database), so the user can allow it on the database first. The result is action_required with step allow_ip: ip, cidr, host, port, reserved_until" },
31574
32373
  ip_allowed: { type: "boolean", description: "The database now allows the reserved IP (a previous result's step allow_ip): create the box with it. Give the user the cidr and port to allow first, and call with ip_allowed: true only once they confirm" },
32374
+ privatelink: { type: "boolean", description: "RDS: true monitors it over AWS PrivateLink (it is not publicly accessible), false directly (it is). Default: decided from AWS or public DNS; asked (action_required) when neither tells" },
32375
+ vpce_service: { type: "string", description: "RDS over PrivateLink: the stack's VpceServiceName output (com.amazonaws.vpce.<region>.vpce-svc-<id>), from the user, after step privatelink_stack" },
32376
+ host_stats: { type: "boolean", description: "RDS over PrivateLink: also host CPU, memory, disk and IOPS, through a read-only role the stack creates in the user's account" },
32377
+ host_stats_role: { type: "string", description: "RDS over PrivateLink with host_stats: the stack's HostStatsRoleArn output, when it is not read from AWS" },
32378
+ aws_profile: { type: "string", description: "RDS: the aws CLI profile that reads the RDS and its stack (read-only); default: the aws CLI's own (AWS_PROFILE, default, the instance role)" },
32379
+ no_aws: { type: "boolean", description: "RDS: do not use the aws CLI on this machine" },
32380
+ terraform: { type: "boolean", description: "RDS over PrivateLink: write the stack as a Terraform module (in the current directory) instead of the CloudFormation link" },
32381
+ monitoring_password: { type: "string", description: "RDS over PrivateLink: the monitoring_password of a prepare_db result whose SQL the user ran (with nonce)" },
32382
+ nonce: { type: "string", description: "RDS over PrivateLink: the nonce of that prepare_db result" },
31575
32383
  debug: { type: "boolean", description: "Enable verbose debug logs" }
31576
32384
  },
31577
32385
  required: ["database_url"],
@@ -32474,6 +33282,9 @@ function renderMarkdownForTerminal(md) {
32474
33282
  }
32475
33283
 
32476
33284
  // lib/connect.ts
33285
+ import { execFile as execFile3 } from "node:child_process";
33286
+ import * as fs7 from "node:fs";
33287
+ import * as path6 from "node:path";
32477
33288
  var clickhouseKeyHeld = (d) => d.host_metrics && (d.host_metrics_source === undefined || d.host_metrics_source === "clickhouse");
32478
33289
  function httpStatus2(err) {
32479
33290
  const status = err instanceof Error ? err.status : undefined;
@@ -32710,8 +33521,11 @@ function stepProgress(o) {
32710
33521
  view.start();
32711
33522
  }
32712
33523
  view.advance(e.event);
32713
- if (/^(Note|Warning):/.test(e.message))
33524
+ const kept = e.event === "privatelink" && (!!e.cfn_url || e.message.startsWith("Using stack "));
33525
+ if (/^(Note|Warning):/.test(e.message) || kept)
32714
33526
  view.log(e.message);
33527
+ if (e.event === "privatelink" && !kept && !/^(Note|Warning):/.test(e.message))
33528
+ view.setNote(e.message);
32715
33529
  if (e.event === "box" && e.state) {
32716
33530
  view.setNote(e.state === "waiting_for_access" && e.ip ? `box: waiting for database access from ${e.ip}` : `box: ${boxWords2(e.state)}`);
32717
33531
  if (e.state === "waiting_for_access" && e.ip && e.error && e.error !== refused) {
@@ -32729,7 +33543,7 @@ function stepProgress(o) {
32729
33543
  function stepViewEnd(r) {
32730
33544
  if (r.status === "ready")
32731
33545
  return "complete";
32732
- if (r.status === "in_progress" || r.step === "allow_ip" || r.next.startsWith(STILL_IN_PROGRESS2))
33546
+ if (r.status === "in_progress" || r.step || r.next.startsWith(STILL_IN_PROGRESS2))
32733
33547
  return "stop";
32734
33548
  return "fail";
32735
33549
  }
@@ -32750,6 +33564,7 @@ function personLines(r) {
32750
33564
  ...r.price ? [` Price: ${r.price}`] : [],
32751
33565
  ...r.cloud ? [` Runs on: ${cloudWord2(r.cloud)}, ${r.location}`] : [],
32752
33566
  ...r.egress_ip ? [` Connects from: ${r.egress_ip}`] : [],
33567
+ ...r.provider === "rds" && r.host_metrics ? [" Host metrics: on (CPU, memory, disk, IOPS)"] : [],
32753
33568
  ...!r.health_url && !r.dashboard_url && r.next && r.next !== "none" ? [`Next: ${r.next}`] : [],
32754
33569
  ...extra && (r.health_url || r.dashboard_url) ? [`Note: ${extra}`] : []
32755
33570
  ];
@@ -32770,6 +33585,8 @@ function personLines(r) {
32770
33585
  }
32771
33586
  if (r.projects?.length)
32772
33587
  return [r.next, ...supabaseProjectRows(r.projects)];
33588
+ if (r.step === "privatelink_stack" && r.cfn_url && !r.terraform_dir)
33589
+ return [r.next, ` ${r.cfn_url}`];
32773
33590
  return r.choices ? [r.next, ...Object.entries(r.choices).map(([cloud, codes]) => ` --cloud ${cloud} --location ${codes.join("|")}`)] : [r.next];
32774
33591
  }
32775
33592
  }
@@ -32887,9 +33704,17 @@ async function connect2(url, opts, deps) {
32887
33704
  const key = parseClickhouseKey2(opts.clickhouseKey, provider === "clickhouse" && !opts.agent ? process.env : {});
32888
33705
  if (key && provider !== "clickhouse")
32889
33706
  throw new Error("--clickhouse-key applies to ClickHouse Managed Postgres only");
33707
+ const plFlag = privateLinkFlag2(opts);
32890
33708
  if (!opts.selfHosted && provider === "rds") {
32891
- const ignored = monitoringUser ? ` (${opts.agent ? "monitoring_user" : "--monitoring-user"} is not used there)` : "";
32892
- return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}${ignored}` };
33709
+ const route = await rdsRoute2(url, opts, deps, progress);
33710
+ if ("status" in route)
33711
+ return { ...route, provider, name };
33712
+ if (route.private)
33713
+ return deployPrivateLink2(url, route, { ...opts, monitoringUser }, deps, progress);
33714
+ if (plFlag)
33715
+ return { status: "action_required", provider, name, next: `${plFlag} applies to AWS PrivateLink only, and ${name} is monitored directly${opts.privatelink === false ? ` (${opts.agent ? "privatelink: false" : "--no-privatelink"})` : " (it is publicly accessible)"}` };
33716
+ } else if (plFlag) {
33717
+ return { status: "action_required", provider, name, next: `${plFlag} applies to Amazon RDS monitored from PostgresAI Cloud only` };
32893
33718
  }
32894
33719
  if (opts.selfHosted && opts.resetPassword) {
32895
33720
  return { status: "action_required", provider, name, next: "--reset-password works with PostgresAI Cloud only (it checks what else monitors this server): deploy without --self-hosted, or set PGAI_MON_PASSWORD" };
@@ -33664,6 +34489,569 @@ async function supabaseBox2(ref, name, opts, deps, progress, stop, label) {
33664
34489
  return { ...connectStatus2(box, provider, true), ...b.billing };
33665
34490
  return follow2(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "", place }, opts, deps, progress);
33666
34491
  }
34492
+ var PL2 = "AWS PrivateLink";
34493
+ var STACK_WAIT_MS2 = 30 * 60000;
34494
+ var STACK_POLL_MS2 = 15000;
34495
+ function privateLinkFlag2(opts) {
34496
+ const named = [
34497
+ [opts.privatelink === true ? true : undefined, "--privatelink", "privatelink"],
34498
+ [opts.vpceService, "--vpce-service", "vpce_service"],
34499
+ [opts.hostStats ? true : undefined, "--host-stats", "host_stats"],
34500
+ [opts.hostStatsRole, "--host-stats-role", "host_stats_role"],
34501
+ [opts.terraform ? true : undefined, "--terraform", "terraform"],
34502
+ [opts.agent ? opts.nonce : undefined, "PGAI_MON_NONCE", "nonce"]
34503
+ ];
34504
+ const hit = named.find(([v]) => v !== undefined);
34505
+ return hit && (opts.agent ? hit[2] : hit[1]);
34506
+ }
34507
+ async function rdsRoute2(url, opts, deps, progress) {
34508
+ const host = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
34509
+ const ep = rdsEndpoint(host);
34510
+ const flag = (cli, agent) => opts.agent ? agent : cli;
34511
+ const stop = (next) => ({ status: "action_required", next });
34512
+ if (opts.privatelink === false)
34513
+ return { private: false };
34514
+ const asked = opts.privatelink === true;
34515
+ let read = {};
34516
+ if (ep?.kind === "instance" && ep.partition === "aws" && opts.aws !== false && deps.aws)
34517
+ read = await readAws2(ep, opts, deps, progress);
34518
+ let isPublic = read.inst?.publiclyAccessible;
34519
+ if (isPublic === undefined && ep && deps.publicAddresses) {
34520
+ progress("preparing", `Looking up ${host} in public DNS (cloudflare-dns.com, dns.google): is it publicly accessible?`);
34521
+ const addresses = await deps.publicAddresses(host);
34522
+ if (addresses?.length) {
34523
+ isPublic = !addresses.every(isPrivateAddress);
34524
+ progress("preparing", `${host} resolves to a ${isPublic ? "public address in public DNS, so it is monitored directly" : `private address in public DNS, so it is monitored over ${PL2}`}`);
34525
+ }
34526
+ }
34527
+ if (isPublic === true) {
34528
+ if (asked)
34529
+ return stop(`${host} is publicly accessible, so it is monitored directly: deploy without ${flag("--privatelink", "privatelink")}`);
34530
+ return { private: false };
34531
+ }
34532
+ if (isPublic === undefined && !asked) {
34533
+ if (!deps.ask || opts.yes)
34534
+ return stop(`Could not tell whether ${host} is publicly accessible (AWS ${opts.aws === false ? "not read" : "not readable here"}, and public DNS did not answer): re-run with ${flag("--privatelink", "privatelink: true")} if it is not, or ${flag("--no-privatelink", "privatelink: false")} if it is`);
34535
+ const a = (await deps.ask(`Is ${host} publicly accessible? [y]es, monitor it directly / [n]o, over ${PL2} / Enter to stop: `)).trim().toLowerCase();
34536
+ if (a === "y" || a === "yes")
34537
+ return { private: false };
34538
+ if (a !== "n" && a !== "no")
34539
+ return stop("Stopped: nothing was created");
34540
+ }
34541
+ if (!ep)
34542
+ return stop(`${PL2} needs the RDS instance endpoint (<instance>.<id>.<region>.rds.amazonaws.com) in the URL, not ${host}; or monitor from this network with --self-hosted`);
34543
+ if (ep.partition !== "aws")
34544
+ return stop(`${ep.partition === "aws-cn" ? "AWS China" : "AWS GovCloud"} can't reach PostgresAI over ${PL2} (it does not cross AWS partitions): monitor from this network with --self-hosted`);
34545
+ if (ep.kind !== "instance" || read.inst?.engine?.startsWith("aurora"))
34546
+ return stop(`${ep.kind === "proxy" ? "An RDS Proxy endpoint" : "Aurora"} is not supported over ${PL2} yet: monitor from this network with --self-hosted, or ask support@postgres.ai`);
34547
+ return { private: true, ep, ...read };
34548
+ }
34549
+ async function readAws2(ep, opts, deps, progress) {
34550
+ let profile = opts.awsProfile?.trim() || undefined;
34551
+ for (let tries = 0;tries < 3; tries++) {
34552
+ const run = deps.aws(profile);
34553
+ const of = profile ? ` (profile ${profile})` : "";
34554
+ let why;
34555
+ let missing = false;
34556
+ try {
34557
+ const me = await callerIdentity(run);
34558
+ const inst = await describeDbInstance(run, ep.id, ep.region);
34559
+ progress("preparing", `AWS account ${me.account} (${me.arn.split(":").pop()}), read-only: ${ep.id} is ${inst.publiclyAccessible ? "publicly accessible, so it is monitored directly" : `not publicly accessible, so it is monitored over ${PL2}`}`);
34560
+ return { aws: run, inst };
34561
+ } catch (err) {
34562
+ if (!(err instanceof AwsError))
34563
+ throw err;
34564
+ missing = err.kind === "missing";
34565
+ why = missing ? "the aws CLI is not installed here" : err.kind === "not_found" ? `${ep.id} is not in ${ep.region} of this AWS account${of}` : err.kind === "credentials" ? `the AWS credentials${of} do not work: ${err.message}` : `AWS refused${of}: ${err.message}`;
34566
+ }
34567
+ if (missing || !deps.ask || opts.yes) {
34568
+ progress("preparing", `Note: ${why}; going on without AWS${missing ? "" : ` (${opts.agent ? "aws_profile" : "--aws-profile"} picks a profile)`}`);
34569
+ return {};
34570
+ }
34571
+ const profiles = deps.awsProfiles ? await deps.awsProfiles().catch(() => []) : [];
34572
+ const a = (await deps.ask(`AWS profile to read ${ep.id} with${profiles.length ? ` (${profiles.join(", ")})` : ""}, or Enter to go on without AWS: `, [`${why}.`])).trim();
34573
+ if (!a)
34574
+ return {};
34575
+ profile = a;
34576
+ }
34577
+ return {};
34578
+ }
34579
+ var VERIFY_FAILED2 = {
34580
+ unreachable: "The monitoring box could not reach the database over PrivateLink: check that the stack finished, its load balancer's target is healthy, and the RDS is not publicly accessible.",
34581
+ auth_failed: `The monitoring box reached the database, but ${DEFAULT_MONITORING_USER} could not log in with the password this deploy's SQL set: the SQL did not run there, or another setup ran its SQL after it.`,
34582
+ nonce_mismatch: "The database's newest PostgresAI setup is not this deploy's: its SQL did not run in this database, or a newer one ran after it (another deploy, or the Console), so monitoring does not start."
34583
+ };
34584
+ async function privateLinkOf(d, rdsStatus) {
34585
+ if (!rdsStatus || disconnecting2(d.status))
34586
+ return;
34587
+ if (d.cluster && d.provider !== "rds" && d.provider !== "aurora")
34588
+ return;
34589
+ return rdsStatus(d.id).catch(() => {
34590
+ return;
34591
+ });
34592
+ }
34593
+ function verifiedWords(verified) {
34594
+ return verified === "db_verified" ? "verified" : verified === "pending" ? "not verified yet" : VERIFY_FAILED2[verified] ?? verified;
34595
+ }
34596
+ var privateLinkFailure = (s) => s ? VERIFY_FAILED2[s.verified_status] : undefined;
34597
+ function stackTeardown(s, id) {
34598
+ const ep = rdsEndpoint(s.rds_endpoint);
34599
+ const made = ep ? ` If deploy's link made it:
34600
+ aws cloudformation delete-stack --stack-name ${stackNameFor(ep.id)} --region ${ep.region}` : "";
34601
+ return `Once it is deleted (pgai mon instances watch ${id}), and if nothing else is to monitor this RDS (a new deploy for it reuses the stack), delete the PrivateLink stack in your AWS account whose VpceServiceName is ${s.vpce_service_name} (terraform destroy, if it was made with Terraform).${made}`;
34602
+ }
34603
+ var utc2 = (iso) => {
34604
+ const d = new Date(iso);
34605
+ return Number.isNaN(d.getTime()) ? iso : `${d.toISOString().slice(0, 19).replace("T", " ")} UTC`;
34606
+ };
34607
+ function inDatabase2(url, db) {
34608
+ const u = new URL(url);
34609
+ if (u.pathname.length <= 1)
34610
+ u.pathname = `/${encodeURIComponent(db)}`;
34611
+ return u.toString();
34612
+ }
34613
+ function roleUrl2(url, db, password) {
34614
+ const u = new URL(loginUrlFor2(url, DEFAULT_MONITORING_USER, db, password));
34615
+ u.pathname = new URL(inDatabase2(url, db)).pathname;
34616
+ return u.toString();
34617
+ }
34618
+ async function deployPrivateLink2(url, route, opts, deps, progress) {
34619
+ const provider = "rds";
34620
+ const { ep, inst } = route;
34621
+ const name = databaseName3(url);
34622
+ const db = name.split("/").slice(1).join("/") || "postgres";
34623
+ const port = Number(new URL(url).port || inst?.port || 5432);
34624
+ const cluster = `${ep.host}:${port}`;
34625
+ const flag = (cli, agent) => opts.agent ? agent : cli;
34626
+ const stop = (next, more = {}) => ({ status: "action_required", provider, name, ...more, next });
34627
+ const notHere = [
34628
+ [opts.cloud, "--cloud", "cloud"],
34629
+ [opts.location, "--location", "location"],
34630
+ [opts.name, "--name", "name"],
34631
+ [opts.ipFirst || undefined, "--ip-first", "ip_first"],
34632
+ [opts.ipAllowed || undefined, "--ip-allowed", "ip_allowed"],
34633
+ [opts.resetPassword || undefined, "--reset-password", "reset_password"],
34634
+ [opts.monitoringUser, "--monitoring-user", "monitoring_user"]
34635
+ ].find(([v]) => v !== undefined && v !== "");
34636
+ if (notHere)
34637
+ return stop(`${flag(notHere[1], notHere[2])} does not apply over ${PL2}: the box runs on AWS in ${ep.region} (the RDS's region), as ${DEFAULT_MONITORING_USER}, in a project named ${ep.id}`);
34638
+ if (opts.monitoringPassword === undefined !== (opts.nonce === undefined)) {
34639
+ return stop(opts.agent ? "Pass monitoring_password and nonce together (both from the prepare_db result)" : "Set PGAI_MON_PASSWORD and PGAI_MON_NONCE together (both from the printed SQL's result), or neither");
34640
+ }
34641
+ const rows = await deps.list();
34642
+ const live = rows.filter((d) => !disconnecting2(d.status));
34643
+ const onServer = live.filter((d) => d.cluster && serverOf2(d.cluster) === cluster);
34644
+ const verify = async (row) => VERIFY_FAILED2[(await deps.rdsStatus?.(row.id).catch(() => {
34645
+ return;
34646
+ }))?.verified_status ?? ""];
34647
+ const own = onServer.find((d) => (d.provider === "rds" || d.provider === "aurora") && d.database != null && decodeURIComponent(d.database) === db);
34648
+ if (own) {
34649
+ const note = opts.vpceService || opts.hostStatsRole ? "; the flags for a new box were not used: it exists" : "";
34650
+ return overPrivateLink2(await follow2(own, { provider, name, fresh: false, billing: {}, note, verify }, opts, deps, progress));
34651
+ }
34652
+ const already = (d, how) => {
34653
+ const instead = d.database != null && decodeURIComponent(d.database) !== db ? `To monitor ${db} instead` : "To set it up from here instead";
34654
+ return stop(`${ep.id} is already monitored ${how} (instance ${d.name}). Setting up another instance would change ${DEFAULT_MONITORING_USER}'s password, which that instance logs in with. ${instead}, delete that instance first (pgai mon instances delete ${deleteRef2(d, rows)})`);
34655
+ };
34656
+ if (onServer.length)
34657
+ return already(onServer[0], onServer[0].provider === "rds" ? `over ${PL2}, database ${decodeURIComponent(onServer[0].database ?? "?")}` : "directly");
34658
+ const candidates = live.filter((r) => !r.cluster || r.provider === "rds" || r.provider === "aurora");
34659
+ let routes;
34660
+ try {
34661
+ routes = await Promise.all(candidates.map((d) => deps.rdsStatus?.(d.id).catch((err) => {
34662
+ if (httpStatus2(err) === 404)
34663
+ return;
34664
+ throw err;
34665
+ })));
34666
+ } catch (err) {
34667
+ return stop(`Could not check what already monitors ${ep.id} (${errorText2(err)}): re-run pgai mon deploy. Nothing was changed`);
34668
+ }
34669
+ const viaConsole = candidates.find((_, i) => routes[i]?.rds_endpoint.toLowerCase().replace(/\.$/, "") === ep.host);
34670
+ if (viaConsole)
34671
+ return already(viaConsole, `over ${PL2}, set up in the console`);
34672
+ const hostStats = !!opts.hostStats || !!opts.hostStatsRole?.trim();
34673
+ const place = { cloud: "aws", location: ep.region, location_reason: "privatelink", location_reason_text: `same region as your database, over ${PL2}` };
34674
+ progress("preparing", `Monitoring box: AWS, ${ep.region} (${place.location_reason_text})`, { cloud: "aws", location: ep.region, location_reason: "privatelink" });
34675
+ let quote;
34676
+ try {
34677
+ quote = await deps.quote(opts.coupon);
34678
+ } catch (err) {
34679
+ if (err instanceof HttpStatusError && err.status === 403)
34680
+ return stop(notAdminNext);
34681
+ throw err;
34682
+ }
34683
+ let vcpus = opts.vcpus;
34684
+ if (vcpus === undefined && route.aws && inst?.instanceClass) {
34685
+ vcpus = await vcpusOfClass(route.aws, inst.instanceClass, ep.region);
34686
+ if (vcpus)
34687
+ progress("billing", `vCPUs: ${vcpus} (${inst.instanceClass})`);
34688
+ }
34689
+ const where = `AWS, ${ep.region}`;
34690
+ const b = await billingFor2(quote, name, opts, deps, (price) => progress("billing", estimateLine(price)), async (price) => {
34691
+ if (opts.yes)
34692
+ return { go: true };
34693
+ if (deps.ask) {
34694
+ return await deps.confirm(`Deploy ${terminalText2(name)} over ${PL2} (monitoring box on ${where})? [y/N] `) ? { go: true } : { go: false, stop: { next: `Nothing was created: re-run with --yes to deploy over ${PL2}` } };
34695
+ }
34696
+ return { go: false, stop: { next: opts.agent ? `Show the user the price (${price}); the monitoring box runs on ${where}, reached over ${PL2}. Then call deploy_monitoring again with yes: true. Nothing was created.` : `The monitoring box would run on ${where} for ${price}, reached over ${PL2}: re-run with --yes to deploy. Nothing was created.` } };
34697
+ });
34698
+ if (b.stop)
34699
+ return { ...stop(b.stop.next), ...place, ...b.stop };
34700
+ if (deps.aborted?.())
34701
+ throw new CancelledError2;
34702
+ const more = { ...place, ...b.billing };
34703
+ if (vcpus === undefined) {
34704
+ vcpus = !opts.yes && !opts.agent && deps.askVcpus ? await deps.askVcpus(VCPUS_QUESTION2) : undefined;
34705
+ if (deps.aborted?.())
34706
+ throw new CancelledError2;
34707
+ if (vcpus === undefined)
34708
+ progress("billing", NO_VCPUS_NOTE2);
34709
+ }
34710
+ const stack = await privateLinkStack2({ ep, aws: route.aws, inst, port, hostStats, opts, deps, progress, stop: (next, m = {}) => stop(next, { ...more, ...m }) });
34711
+ if ("status" in stack)
34712
+ return stack;
34713
+ if (deps.aborted?.())
34714
+ throw new CancelledError2;
34715
+ const role = await privateLinkRole2(url, db, opts, deps, progress, (next, m = {}) => stop(next, { ...more, ...m }));
34716
+ if ("status" in role)
34717
+ return role;
34718
+ if (deps.aborted?.())
34719
+ throw new CancelledError2;
34720
+ progress("provisioning", `Provisioning monitoring for ${name} over ${PL2}`);
34721
+ const created = await deps.rdsProvision({
34722
+ vpce_service_name: stack.vpce,
34723
+ rds_endpoint: ep.host,
34724
+ db_password: role.password,
34725
+ rds_port: port,
34726
+ rds_database: db,
34727
+ region: ep.region,
34728
+ ...b.accepted ? { accept_price: true } : {},
34729
+ ...opts.coupon ? { promo_code: opts.coupon } : {},
34730
+ ...stack.roleArn ? { host_stats_role_arn: stack.roleArn } : {},
34731
+ ...vcpus ? { vcpus } : {}
34732
+ }).catch((err) => {
34733
+ if (err instanceof HttpStatusError && err.status === 402)
34734
+ return /declined/i.test(err.message) ? "declined" : "payment";
34735
+ if (err instanceof HttpStatusError && err.status === 412)
34736
+ return "price";
34737
+ if (err instanceof HttpStatusError && err.status < 500)
34738
+ return { refused: errorText2(err) };
34739
+ if (mayHaveRun2(err))
34740
+ return "unanswered";
34741
+ throw err;
34742
+ });
34743
+ if (typeof created === "object" && "refused" in created)
34744
+ return stop(`${created.refused.replace(/\.?$/, ".")} No monitoring box was created.`, more);
34745
+ if (created === "payment")
34746
+ return { status: "action_required", provider, name, ...place, ...b.billingPage };
34747
+ if (created === "declined")
34748
+ return { status: "action_required", provider, name, ...place, ...b.billingPage, next: b.billingPage.next.replace(/^Add a payment method at /, "The payment method on file was declined: update it at ") };
34749
+ if (created === "price")
34750
+ return stop("The price changed since it was shown: re-run pgai mon deploy to see it", more);
34751
+ let box;
34752
+ if (created === "unanswered") {
34753
+ progress("provisioning", STILL_CREATING2);
34754
+ const known = new Set(rows.map((d) => d.id));
34755
+ const made = await lookForBox2((list) => list.find((d) => !known.has(d.id) && !!d.cluster && serverOf2(d.cluster) === cluster), opts, deps, deps.now());
34756
+ if (!made)
34757
+ return stop(deps.aborted?.() ? STOPPED_LOOKING2 : opts.agent ? NOT_CONFIRMED_AGENT2 : NOT_CONFIRMED2, more);
34758
+ box = made;
34759
+ } else {
34760
+ box = { id: created.id, name: created.name, provider, status: created.status, dashboard_url: null, host_metrics: !!stack.roleArn };
34761
+ }
34762
+ if (deps.aborted?.())
34763
+ return { ...connectStatus2(box, provider, true), ...more };
34764
+ return overPrivateLink2(await follow2(box, { provider, name, fresh: true, billing: b.billing, billingUrl: b.billingUrl, note: "", place, verify }, opts, deps, progress));
34765
+ }
34766
+ var PRIVATELINK_LAUNCH_FAILED2 = `The monitoring box could not connect to the stack's endpoint service: check that the stack finished, and that the endpoint service (VPC console, Endpoint services, Allow principals) lists ${PRINCIPAL_ARN}.`;
34767
+ function overPrivateLink2(r, why) {
34768
+ const { egress_ip: _ip, ...rest } = r;
34769
+ if (rest.status === "ready")
34770
+ return rest;
34771
+ const said = Object.values(VERIFY_FAILED2).some((t) => rest.next.includes(t));
34772
+ const first = said ? undefined : why ?? (rest.status === "failed" ? PRIVATELINK_LAUNCH_FAILED2 : undefined);
34773
+ return first ? { ...rest, next: `${first} ${rest.status === "failed" ? "Then: " : ""}${rest.next}` } : rest;
34774
+ }
34775
+ async function privateLinkStack2(c) {
34776
+ const { ep, opts, deps, progress } = c;
34777
+ const flag = (cli, agent) => opts.agent ? agent : cli;
34778
+ const terminal = !!deps.ask;
34779
+ const ask = opts.yes ? undefined : deps.ask;
34780
+ let aws = opts.terraform ? undefined : c.aws;
34781
+ let vpce = opts.vpceService?.trim() || undefined;
34782
+ let roleArn = opts.hostStatsRole?.trim() || undefined;
34783
+ const badVpce = (v) => {
34784
+ const m = VPCE_SERVICE.exec(v);
34785
+ if (!m)
34786
+ return `${v} is not a VpceServiceName (com.amazonaws.vpce.<region>.vpce-svc-<id>, the stack's output)`;
34787
+ if (m[1] !== ep.region)
34788
+ return `${v} is in ${m[1]}, and ${ep.id} in ${ep.region}: ${PL2} connects within one region, so use the stack made in ${ep.region}`;
34789
+ return;
34790
+ };
34791
+ if (roleArn && !ROLE_ARN.test(roleArn))
34792
+ return c.stop(`${roleArn} is not an IAM role ARN (arn:aws:iam::<account>:role/<name>, the stack's HostStatsRoleArn output)`);
34793
+ if (vpce && badVpce(vpce))
34794
+ return c.stop(badVpce(vpce));
34795
+ let externalId;
34796
+ const externalIdOf = async () => externalId ??= await deps.rdsExternalId();
34797
+ let shown;
34798
+ const show = async () => {
34799
+ const inputs = {
34800
+ region: ep.region,
34801
+ rdsId: ep.id,
34802
+ port: c.port,
34803
+ vpcId: c.inst?.vpcId,
34804
+ subnetIds: c.inst ? oneSubnetPerAz(c.inst.subnets) : undefined,
34805
+ securityGroupId: c.inst?.securityGroupIds.length === 1 ? c.inst.securityGroupIds[0] : undefined,
34806
+ ...c.hostStats ? { externalId: await externalIdOf() } : {}
34807
+ };
34808
+ const cfn = quickCreateUrl(inputs);
34809
+ const [vpcKey, subnetsKey, sgKey] = opts.terraform ? ["vpc_id", "subnet_ids", "rds_security_group_id"] : ["VpcId", "SubnetIds", "RdsSecurityGroupId"];
34810
+ const w = sgKey.length + 2;
34811
+ const blanks = [
34812
+ !inputs.vpcId && ` ${vpcKey.padEnd(w)}the RDS's VPC`,
34813
+ !inputs.subnetIds?.length && ` ${subnetsKey.padEnd(w)}one subnet per availability zone of the RDS's subnet group`,
34814
+ !inputs.securityGroupId && ` ${sgKey.padEnd(w)}the RDS's security group`
34815
+ ].filter((l) => !!l);
34816
+ const choose = blanks.length ? `
34817
+ ${opts.terraform ? "In terraform.tfvars, fill in" : "In the form, choose (empty in the link)"}:
34818
+ ${blanks.join(`
34819
+ `)}
34820
+ (the RDS console lists them: ${ep.id}, Connectivity & security)` : "";
34821
+ let dir;
34822
+ if (opts.terraform)
34823
+ dir = await deps.writeTerraform(stackNameFor(ep.id), terraformFiles(await deps.terraformModule(), inputs));
34824
+ const where = deps.openUrl ? "" : `
34825
+ Open it in a browser signed in to that AWS account.`;
34826
+ const tf = opts.agent ? "" : `
34827
+ Prefer Terraform? ${deps.ask ? "Stop (Ctrl-C) and re-run" : "Re-run"} with --terraform: it writes the same stack as a module.`;
34828
+ progress("privatelink", dir ? `Terraform for the PrivateLink stack written to ${dir}: terraform init && terraform apply there${choose}` : `Create the PrivateLink stack in your AWS account from this link; nothing becomes public:${choose}
34829
+ ${cfn}${where}${tf}`, { cfn_url: cfn, stack_name: stackNameFor(ep.id) });
34830
+ return {
34831
+ step: "privatelink_stack",
34832
+ cfn_url: cfn,
34833
+ stack_name: stackNameFor(ep.id),
34834
+ region: ep.region,
34835
+ ...inputs.externalId ? { external_id: inputs.externalId } : {},
34836
+ ...dir ? { terraform_dir: dir } : {},
34837
+ ...blanks.length ? { choose_in_form: blanks.map((l) => l.trim().split(/\s+/)[0]) } : {}
34838
+ };
34839
+ };
34840
+ const resume = () => {
34841
+ const output = opts.terraform ? "vpce_service_name output" : "VpceServiceName output";
34842
+ const role = c.hostStats && !roleArn ? ` and ${flag("--host-stats-role", "host_stats_role")} <its ${opts.terraform ? "host_stats_role_arn" : "HostStatsRoleArn"} output>` : "";
34843
+ return aws ? opts.agent ? "call deploy_monitoring again" : "re-run pgai mon deploy" : `${opts.agent ? "call deploy_monitoring again with" : "re-run with"} ${flag("--vpce-service", "vpce_service")} <its ${output}>${role}`;
34844
+ };
34845
+ const deadline = deps.now() + STACK_WAIT_MS2;
34846
+ let refusedPaste;
34847
+ let saidMisnamed = false;
34848
+ let readStack = false;
34849
+ const seenMaking = new Set;
34850
+ const saidFailed = new Set;
34851
+ const startedAt = Date.now() - 60000;
34852
+ const thisRuns = (s) => s.name === stackNameFor(ep.id) || seenMaking.has(s.name) || !!s.created && Date.parse(s.created) >= startedAt;
34853
+ for (let pastes = 0, empties = 0;!vpce; ) {
34854
+ let found = [];
34855
+ if (aws) {
34856
+ try {
34857
+ const r = await findStacks(aws, ep.id, ep.region);
34858
+ found = r.stacks;
34859
+ if (r.misnamed && !saidMisnamed) {
34860
+ saidMisnamed = true;
34861
+ progress("privatelink", `Note: stack ${r.misnamed.name} is for RDS ${r.misnamed.rdsId ?? "(none)"}, not ${ep.id}: not used. Give the new stack another name in the form`);
34862
+ }
34863
+ } catch (err) {
34864
+ if (!(err instanceof AwsError))
34865
+ throw err;
34866
+ progress("privatelink", `Note: could not read CloudFormation (${err.message}); going on without AWS`);
34867
+ aws = undefined;
34868
+ }
34869
+ }
34870
+ const ready = found.filter((s) => stackState(s.status) === "ready" && s.outputs.VpceServiceName);
34871
+ let stack;
34872
+ if (ready.length === 1)
34873
+ stack = ready[0];
34874
+ else if (ready.length > 1) {
34875
+ const rows = ready.map((s, i) => ` ${i + 1}. ${s.name} ${s.status}${s.created ? ` created ${utc2(s.created)}` : ""} ${s.outputs.VpceServiceName}`);
34876
+ const listed = {
34877
+ step: "privatelink_stack",
34878
+ region: ep.region,
34879
+ stacks: ready.map((s) => ({ name: s.name, status: s.status, created: s.created ?? null, vpce_service_name: s.outputs.VpceServiceName }))
34880
+ };
34881
+ if (!ask) {
34882
+ return c.stop(`Several stacks publish ${ep.id}: ${opts.agent ? "ask the user which one, then call deploy_monitoring again with vpce_service" : "re-run with --vpce-service"} <the VpceServiceName of the one to use>. Nothing was created on PostgresAI yet.
34883
+ ${rows.join(`
34884
+ `)}`, listed);
34885
+ }
34886
+ for (let tries = 0;!stack && tries < 3; tries++) {
34887
+ const a = (await ask(`The stack to use (1-${ready.length}, Enter to stop): `, tries ? [`Type a number from 1 to ${ready.length}.`] : [`Several stacks publish ${ep.id}:`, ...rows])).trim();
34888
+ if (!a)
34889
+ return c.stop(`Stopped: re-run with --vpce-service <the VpceServiceName of the stack to use>. Nothing was created on PostgresAI yet.`, listed);
34890
+ const i = Number(a);
34891
+ if (Number.isInteger(i) && i >= 1 && i <= ready.length)
34892
+ stack = ready[i - 1];
34893
+ }
34894
+ if (!stack)
34895
+ return c.stop(`No stack picked: re-run with --vpce-service <the VpceServiceName of the stack to use>. Nothing was created on PostgresAI yet.`, listed);
34896
+ }
34897
+ if (stack) {
34898
+ vpce = stack.outputs.VpceServiceName;
34899
+ roleArn ??= stack.outputs.HostStatsRoleArn;
34900
+ readStack = true;
34901
+ progress("privatelink", `Using stack ${stack.name}${stack.created ? ` (created ${utc2(stack.created)})` : ""}: ${vpce}`, { stack_name: stack.name });
34902
+ break;
34903
+ }
34904
+ for (const s of found)
34905
+ if (stackState(s.status) === "in_progress")
34906
+ seenMaking.add(s.name);
34907
+ const foreign = found.find((s) => s.name === stackNameFor(ep.id) && stackState(s.status) === "ready" && !s.outputs.VpceServiceName);
34908
+ if (foreign && !found.some((s) => stackState(s.status) === "in_progress")) {
34909
+ return c.stop(`Stack ${foreign.name} has no VpceServiceName output: it was not made from the PostgresAI template. Delete it, create the stack from the link deploy prints, then ${resume()}`, { step: "privatelink_stack", stack_name: foreign.name, region: ep.region });
34910
+ }
34911
+ const failedNow = found.filter((s) => stackState(s.status) === "failed").sort((a, b) => Date.parse(b.created ?? "") - Date.parse(a.created ?? "") || 0);
34912
+ const waits = terminal && !!aws;
34913
+ const failed = failedNow.find(thisRuns) ?? (waits ? undefined : failedNow[0]);
34914
+ for (const s of failedNow) {
34915
+ if (s === failed || saidFailed.has(s.name))
34916
+ continue;
34917
+ saidFailed.add(s.name);
34918
+ progress("privatelink", `Note: stack ${s.name} for ${ep.id} failed earlier (${s.status}): not used`);
34919
+ }
34920
+ if (failed && !found.some((s) => stackState(s.status) === "in_progress")) {
34921
+ const why = (aws && await stackFailure(aws, failed.name, ep.region) || failed.reason || failed.status).replace(/\s*\(RequestId: [^)]*\)/g, "");
34922
+ const fix = /^(CREATE_FAILED|ROLLBACK_|DELETE_FAILED)/.test(failed.status) ? `delete the stack, then re-run pgai mon deploy:
34923
+ aws cloudformation delete-stack --stack-name ${failed.name} --region ${ep.region}` : "repair the stack in the CloudFormation console (Stack actions, Continue update rollback), then re-run pgai mon deploy";
34924
+ return c.stop(`Stack ${failed.name} failed (${failed.status}): ${why}
34925
+ Fix that, ${fix}`, { step: "privatelink_stack", stack_name: failed.name, region: ep.region });
34926
+ }
34927
+ const being = found.find((s) => stackState(s.status) === "in_progress");
34928
+ const first = !shown;
34929
+ shown ??= await show();
34930
+ const making = being ? `Stack ${being.name} is ${/ROLLBACK/.test(being.status) ? "rolling back" : "being created"} (${being.status})` : undefined;
34931
+ if (!terminal || !aws && !ask) {
34932
+ const make = shown.terraform_dir ? `Run terraform init && terraform apply in ${shown.terraform_dir}` : opts.agent ? `Give the user cfn_url to open in the AWS account of ${ep.id}, to create the stack there${shown.choose_in_form ? ` (choosing ${shown.choose_in_form.join(", ")} in the form)` : ""}, or call again with terraform: true for the same as Terraform` : `Open the link below in the AWS account of ${ep.id} and create the stack there${shown.choose_in_form ? ` (choose ${shown.choose_in_form.join(", ")} in the form)` : ""}, or re-run with --terraform for the same as Terraform`;
34933
+ return c.stop(`${making ? `${making}: once it is CREATE_COMPLETE` : `${make}; once it is done`}, ${resume()}. Nothing was created on PostgresAI yet.`, shown);
34934
+ }
34935
+ const openIt = !shown.terraform_dir && deps.openUrl ? ", [o] to open the link in your browser" : "";
34936
+ if (aws) {
34937
+ if (first && openIt && ask) {
34938
+ const a = (await ask(`[o] opens the link in your browser; Enter waits for the stack: `)).trim().toLowerCase();
34939
+ if (a === "o")
34940
+ deps.openUrl(shown.cfn_url);
34941
+ }
34942
+ if (deps.aborted?.())
34943
+ throw new CancelledError2;
34944
+ if (deps.now() >= deadline)
34945
+ return c.stop(`No stack for ${ep.id} was ready within ${STACK_WAIT_MS2 / 60000} minutes: re-run pgai mon deploy once it is. Nothing was created on PostgresAI yet.`, shown);
34946
+ progress("privatelink", making ?? `Waiting for you to create the stack from the link above (any name; deploy finds it by its RDS; up to ${STACK_WAIT_MS2 / 60000} min)`, { stack_name: being?.name ?? stackNameFor(ep.id) });
34947
+ await deps.sleep(STACK_POLL_MS2);
34948
+ continue;
34949
+ }
34950
+ const output = opts.terraform ? "vpce_service_name output" : "VpceServiceName (CloudFormation, the stack, Outputs)";
34951
+ const a = (await ask(`Paste the stack's ${output}${openIt}, or [s] to stop: `, refusedPaste ? [refusedPaste] : [])).trim();
34952
+ if (a.toLowerCase() === "s")
34953
+ return c.stop(`Stopped: once the stack is done, ${resume()}. Nothing was created on PostgresAI yet.`, shown);
34954
+ if (!a) {
34955
+ if (++empties >= 3)
34956
+ return c.stop(`Stopped: once the stack is done, ${resume()}. Nothing was created on PostgresAI yet.`, shown);
34957
+ refusedPaste = `Paste the stack's ${opts.terraform ? "vpce_service_name output" : "VpceServiceName"} once it is created, or s to stop.`;
34958
+ continue;
34959
+ }
34960
+ empties = 0;
34961
+ if (openIt && a.toLowerCase() === "o") {
34962
+ deps.openUrl(shown.cfn_url);
34963
+ refusedPaste = undefined;
34964
+ continue;
34965
+ }
34966
+ refusedPaste = badVpce(a);
34967
+ if (!refusedPaste)
34968
+ vpce = a;
34969
+ else if (++pastes >= 3)
34970
+ return c.stop(refusedPaste, shown);
34971
+ }
34972
+ if (c.hostStats && !roleArn && !readStack) {
34973
+ const out = opts.terraform ? "host_stats_role_arn" : "HostStatsRoleArn";
34974
+ return c.stop(`Host metrics need the metrics role too: ${opts.agent ? "call deploy_monitoring again with" : "re-run with"} ${flag("--vpce-service", "vpce_service")} ${vpce} and ${flag("--host-stats-role", "host_stats_role")} <its ${out} output>. If it has none, it was made without this PostgresAiExternalId: ${opts.terraform ? "set postgres_ai_external_id in terraform.tfvars and apply again" : "update the stack with it"}; or deploy without ${flag("--host-stats", "host_stats")}.
34975
+ PostgresAiExternalId = ${await externalIdOf()}`, { external_id: externalId });
34976
+ }
34977
+ if (c.hostStats && !roleArn) {
34978
+ return c.stop(`Host metrics need the stack's metrics role (its HostStatsRoleArn output), and it has none: update the stack with this PostgresAiExternalId (it then creates a read-only role), then ${resume()}; or deploy without ${flag("--host-stats", "host_stats")}.
34979
+ PostgresAiExternalId = ${await externalIdOf()}`, { external_id: externalId });
34980
+ }
34981
+ return { vpce, ...roleArn ? { roleArn } : {} };
34982
+ }
34983
+ async function privateLinkRole2(url, db, opts, deps, progress, stop) {
34984
+ let password = opts.monitoringPassword;
34985
+ let nonce = opts.nonce;
34986
+ const ask = opts.yes ? undefined : deps.ask;
34987
+ const warned = new Set;
34988
+ const warn = (m) => {
34989
+ if (!warned.has(m)) {
34990
+ warned.add(m);
34991
+ progress("preparing", m);
34992
+ }
34993
+ };
34994
+ const resumeWith = (n) => opts.agent ? `call deploy_monitoring again with monitoring_password and nonce from this result` : `re-run with PGAI_MON_NONCE=${n} and PGAI_MON_PASSWORD set to the v_password value near the top of the SQL`;
34995
+ let away = false;
34996
+ if (password === undefined || nonce === undefined) {
34997
+ let p;
34998
+ try {
34999
+ p = await deps.rdsPrepareSql(db);
35000
+ } catch (err) {
35001
+ if (err instanceof HttpStatusError && err.status === 403)
35002
+ return stop(notAdminNext);
35003
+ if (err instanceof HttpStatusError && err.status < 500)
35004
+ return stop(errorText2(err));
35005
+ throw err;
35006
+ }
35007
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(p.nonce))
35008
+ throw new Error("cloud_monitoring_rds_prepare_sql returned a malformed nonce: nothing was changed");
35009
+ password = p.db_password;
35010
+ nonce = p.nonce;
35011
+ progress("preparing", `Preparing ${maskConnectionString(url)}`);
35012
+ const failed = await deps.runSql(inDatabase2(url, db), p.prepare_db_sql, warn).then(() => {
35013
+ return;
35014
+ }, (err) => err);
35015
+ if (failed) {
35016
+ const e = failed;
35017
+ away = unreachable2(failed);
35018
+ const refusedLogin = !away && (typeof e !== "object" || !e || !("severity" in e) || e.severity === "FATAL" || /^(28|3D|08)/.test(String(e.code ?? "")));
35019
+ if (refusedLogin)
35020
+ return stop(`Could not log in to ${maskConnectionString(inDatabase2(url, db))}: ${errorText2(failed)}. Check the URL's user and password`);
35021
+ const why = away ? `This machine can't reach the database (${errorText2(failed)}), so the SQL does not run from here` : `The user in this URL (${decodeURIComponent(new URL(url).username)}) can't create ${DEFAULT_MONITORING_USER} (${errorText2(failed)})`;
35022
+ const printed = { step: "prepare_db", sql: p.prepare_db_sql, nonce, monitoring_password: password };
35023
+ const run = `Run the SQL as the master user, connected to database ${db}${away ? ", from a machine that reaches it (in its VPC)" : ""}`;
35024
+ const only = `A deploy of this database without ${opts.agent ? "them" : "PGAI_MON_PASSWORD and PGAI_MON_NONCE"} issues a new SQL and replaces this one`;
35025
+ if (!ask)
35026
+ return stop(`${why}. ${run}, then ${resumeWith(nonce)}. ${only}.`, printed);
35027
+ const a = (await ask(`${run}, then press Enter ([s] to stop): `, [`${why}. The SQL:`, "", p.prepare_db_sql, ""])).trim().toLowerCase();
35028
+ if (a === "s" || a === "stop")
35029
+ return stop(`Stopped. ${run}, then ${resumeWith(nonce)}.`, { ...printed, sql: undefined });
35030
+ }
35031
+ }
35032
+ const boxChecks = (why) => {
35033
+ progress("preparing", `Not checked from here (${why}): the monitoring box checks that ${DEFAULT_MONITORING_USER} logs in to ${db} and that this SQL ran, and deploy says if it fails`);
35034
+ return { password, nonce };
35035
+ };
35036
+ if (away)
35037
+ return boxChecks("this machine can't reach the database");
35038
+ progress("preparing", `Checking that ${DEFAULT_MONITORING_USER} can log in to ${db} with the password the SQL set`);
35039
+ let found;
35040
+ try {
35041
+ found = await deps.readNonce(roleUrl2(url, db, password), warn);
35042
+ } catch (err) {
35043
+ if (unreachable2(err))
35044
+ return boxChecks(`this machine can't reach the database: ${errorText2(err)}`);
35045
+ const fresh = opts.agent ? "call again without monitoring_password and nonce for a new SQL" : "re-run without PGAI_MON_PASSWORD and PGAI_MON_NONCE for a new SQL";
35046
+ return stop(opts.monitoringPassword === undefined ? `${DEFAULT_MONITORING_USER} could not log in to ${db} with the password the SQL set (${errorText2(err)}): run the SQL again, connected to database ${db}` : opts.agent ? `${DEFAULT_MONITORING_USER} could not log in to ${db} with monitoring_password (${errorText2(err)}): pass the monitoring_password of the prepare_db result whose SQL ran, or ${fresh}` : `${DEFAULT_MONITORING_USER} could not log in to ${db} with PGAI_MON_PASSWORD (${errorText2(err)}): set it to the v_password value near the top of the SQL you ran, or ${fresh}`);
35047
+ }
35048
+ const again = opts.monitoringPassword !== undefined ? `${opts.agent ? "call again without monitoring_password and nonce" : "re-run without PGAI_MON_PASSWORD and PGAI_MON_NONCE"} for a new SQL, and run only that one` : "re-run pgai mon deploy";
35049
+ if (found === undefined)
35050
+ return stop(`The SQL has not run in database ${db} (perhaps in another database): run it connected to database ${db}, then ${resumeWith(nonce)}`);
35051
+ if (found !== nonce)
35052
+ return stop(`A newer PostgresAI setup SQL ran in database ${db} after this one (another deploy, or the Console): ${again}`);
35053
+ return { password, nonce };
35054
+ }
33667
35055
  var STILL_IN_PROGRESS2 = "Still in progress";
33668
35056
  var CONNECT_TIMEOUT_MS2 = 55000;
33669
35057
  var AGENT_CONNECT_TIMEOUT_MS2 = 25000;
@@ -33673,6 +35061,12 @@ var STOPPED_LOOKING2 = `${STILL_IN_PROGRESS2}: deploy stopped watching before Po
33673
35061
  var NOT_CONFIRMED_AGENT2 = "PostgresAI did not confirm the monitoring box yet. Call deploy_monitoring again in a minute: it continues with the box if PostgresAI created it. If pgai mon instances list still has no box for this database, ask the user to run pgai mon deploy with --reset-password in a terminal";
33674
35062
  var LOOKUP_MS2 = 5 * 60000;
33675
35063
  var AGENT_RUN_MS2 = 50000;
35064
+ function unreachable2(err) {
35065
+ if (typeof err !== "object" || !err || "severity" in err)
35066
+ return false;
35067
+ const codes = [err.code, ...(err.errors ?? []).map((e) => e?.code)];
35068
+ return codes.some((c) => ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH", "ETIMEDOUT", "ECONNRESET"].includes(String(c))) || /connection timeout|timeout expired/i.test(err instanceof Error ? err.message : "");
35069
+ }
33676
35070
  function mayHaveRun2(err) {
33677
35071
  if (err instanceof HttpRequestTimeoutError)
33678
35072
  return true;
@@ -33697,7 +35091,14 @@ async function follow2(row, f, opts, deps, progress) {
33697
35091
  const url = (_) => f.url ?? name;
33698
35092
  const billing = { ...f.billing, ...f.place };
33699
35093
  let shown;
35094
+ let unverified;
33700
35095
  for (const deadline = deps.now() + opts.waitMs;; ) {
35096
+ if (f.verify) {
35097
+ const why = await f.verify(row);
35098
+ if (why && why !== unverified)
35099
+ progress("box", `Note: ${why}`, { id: row.id });
35100
+ unverified = why;
35101
+ }
33701
35102
  if (row.billing_error && disconnecting2(row.status)) {
33702
35103
  if (undoRole)
33703
35104
  await undoRole();
@@ -33727,15 +35128,16 @@ async function follow2(row, f, opts, deps, progress) {
33727
35128
  final.next += "; for CPU, memory and disk, delete the instance (pgai mon instances delete) and deploy again with --clickhouse-key <key-id>:<key-secret>";
33728
35129
  }
33729
35130
  const { next, ...rest } = final;
35131
+ const why = unverified && final.status !== "ready" ? `${unverified} ` : "";
33730
35132
  if (final.status === "in_progress" && opts.waitMs > 0) {
33731
35133
  return {
33732
35134
  ...rest,
33733
35135
  status: "action_required",
33734
35136
  ...billing,
33735
- next: `${STILL_IN_PROGRESS2} (box: ${boxWords2(boxState2(row))}) when the wait ended: resume with ${next}${note}`
35137
+ next: `${STILL_IN_PROGRESS2} (box: ${boxWords2(boxState2(row))}) when the wait ended: ${why}${why ? "Resume" : "resume"} with ${next}${note}`
33736
35138
  };
33737
35139
  }
33738
- return { ...rest, ...billing, next: next + note };
35140
+ return { ...rest, ...billing, next: why + next + note };
33739
35141
  }
33740
35142
  await deps.sleep(POLL_MS2);
33741
35143
  const listed = await deps.list().catch(() => {
@@ -33816,7 +35218,8 @@ async function prepareDatabase2(url, provider, opts = {}) {
33816
35218
  or (pg_has_role(current_user, 'pg_monitor', 'USAGE WITH ADMIN OPTION')
33817
35219
  and pg_has_role(current_user, 'pg_read_all_stats', 'USAGE WITH ADMIN OPTION')))
33818
35220
  and has_database_privilege(current_user, current_database(), 'CREATE')
33819
- and exists (select 1 from pg_extension where extname = 'pg_stat_statements')) as admin,
35221
+ and (exists (select 1 from pg_extension where extname = 'pg_stat_statements')
35222
+ or exists (select 1 from pg_roles where rolname = 'rds_superuser' and pg_has_role(current_user, oid, 'MEMBER')))) as admin,
33820
35223
  exists (select 1 from pg_roles where rolname = ${quoteLiteral(role)}) as mon_exists,
33821
35224
  exists (select 1 from pg_roles where rolname = ${quoteLiteral(role)} and (rolsuper or rolcreatedb or rolcreaterole or rolreplication or rolbypassrls)) as mon_privileged,
33822
35225
  (select string_agg(g.rolname::text, ', ' order by g.rolname::text collate "C") from pg_roles m join pg_roles g
@@ -34083,10 +35486,50 @@ function platformDeps2(p) {
34083
35486
  supabaseConnect: (body) => rpc("cloud_monitoring_supabase_connect", body),
34084
35487
  supabaseProjects: () => rpc("cloud_monitoring_supabase_projects", {}),
34085
35488
  deployOptions: (args) => rpc("monitoring_deploy_options", args),
34086
- handoffUrl: async (provider) => {
34087
- const orgs = await listOrgs({ apiKey: p.apiKey, apiBaseUrl: p.apiBaseUrl });
34088
- const org = orgs.length === 1 ? orgs[0] : orgs.find((o) => o.alias === p.orgScope?.alias || o.org_id === p.orgScope?.id);
34089
- return `${p.uiBaseUrl}/${org?.alias ?? "<org>"}/monitoring/scale/create/${provider}`;
35489
+ rdsExternalId: async () => (await rpc("cloud_monitoring_rds_external_id")).external_id,
35490
+ rdsPrepareSql: (dbName) => rpc("cloud_monitoring_rds_prepare_sql", { db_name: dbName }),
35491
+ rdsProvision: (body) => rpc("cloud_monitoring_rds_provision", body, p.agent ? AGENT_CONNECT_TIMEOUT_MS2 : CONNECT_TIMEOUT_MS2),
35492
+ rdsStatus: (id) => rpc("cloud_monitoring_rds_status", { instance_id: id }),
35493
+ aws: awsRunner,
35494
+ awsProfiles: () => new Promise((resolve) => execFile3("aws", ["configure", "list-profiles"], { timeout: 1e4 }, (err, stdout) => resolve(err ? [] : stdout.split(`
35495
+ `).map((l) => l.trim()).filter(Boolean)))),
35496
+ publicAddresses: (host) => publicAddresses(host),
35497
+ runSql: async (url, sql, warn) => {
35498
+ const { client } = await openConnection2(url, { agent: p.agent, warn });
35499
+ try {
35500
+ await client.query(sql);
35501
+ } finally {
35502
+ await client.end().catch(() => {});
35503
+ }
35504
+ },
35505
+ readNonce: async (url, warn) => {
35506
+ const { client } = await openConnection2(url, { agent: p.agent, warn });
35507
+ try {
35508
+ const r = await client.query("select nonce from postgres_ai.monitoring_ownership order by issued_at desc limit 1");
35509
+ return r.rows[0]?.nonce;
35510
+ } catch (err) {
35511
+ if (["3F000", "42P01"].includes(err.code ?? ""))
35512
+ return;
35513
+ throw err;
35514
+ } finally {
35515
+ await client.end().catch(() => {});
35516
+ }
35517
+ },
35518
+ terraformModule: async () => {
35519
+ const r = await fetch(TERRAFORM_URL, { signal: AbortSignal.timeout(30000) });
35520
+ if (!r.ok)
35521
+ throw new Error(`Could not download the Terraform module (${TERRAFORM_URL}: HTTP ${r.status})`);
35522
+ return r.text();
35523
+ },
35524
+ writeTerraform: async (dirName, files) => {
35525
+ const dir = path6.resolve(dirName);
35526
+ await fs7.promises.mkdir(dir, { recursive: true });
35527
+ await fs7.promises.writeFile(path6.join(dir, "main.tf"), files.mainTf);
35528
+ await fs7.promises.writeFile(path6.join(dir, "terraform.tfvars"), files.tfvars, { flag: "wx" }).catch((err) => {
35529
+ if (err.code !== "EEXIST")
35530
+ throw err;
35531
+ });
35532
+ return dir;
34090
35533
  },
34091
35534
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
34092
35535
  now: () => Date.now()
@@ -35767,6 +37210,13 @@ var SUPABASE_STEPS = [
35767
37210
  { key: "box", label: "Prepare the database and install monitoring (about 5 min)" },
35768
37211
  { key: "ready", label: "Ready" }
35769
37212
  ];
37213
+ var PRIVATELINK_STEPS = [
37214
+ { key: "privatelink", label: "Wait for you to create the PrivateLink stack in AWS" },
37215
+ { key: "preparing", label: "Prepare the database" },
37216
+ { key: "provisioning", label: "Create the monitoring box" },
37217
+ { key: "box", label: "Connect over PrivateLink and install monitoring (about 5 min)" },
37218
+ { key: "ready", label: "Ready" }
37219
+ ];
35770
37220
  var monitoringSteps = (provider) => provider === "supabase" ? SUPABASE_STEPS : MONITORING_STEPS;
35771
37221
  var FRAMES2 = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
35772
37222
  var GREEN2 = "\x1B[32m";
@@ -36381,8 +37831,8 @@ async function registerAasCollection(apiKey, instanceId, opts) {
36381
37831
  }
36382
37832
 
36383
37833
  // lib/storage.ts
36384
- import * as fs6 from "fs";
36385
- import * as path5 from "path";
37834
+ import * as fs8 from "fs";
37835
+ import * as path7 from "path";
36386
37836
  var MAX_UPLOAD_SIZE2 = 500 * 1024 * 1024;
36387
37837
  var MAX_DOWNLOAD_SIZE2 = 500 * 1024 * 1024;
36388
37838
  var MIME_TYPES2 = {
@@ -36423,11 +37873,11 @@ async function uploadFile2(params) {
36423
37873
  if (!filePath) {
36424
37874
  throw new Error("filePath is required");
36425
37875
  }
36426
- const resolvedPath = path5.resolve(filePath);
36427
- if (!fs6.existsSync(resolvedPath)) {
37876
+ const resolvedPath = path7.resolve(filePath);
37877
+ if (!fs8.existsSync(resolvedPath)) {
36428
37878
  throw new Error(`File not found: ${resolvedPath}`);
36429
37879
  }
36430
- const stat = fs6.statSync(resolvedPath);
37880
+ const stat = fs8.statSync(resolvedPath);
36431
37881
  if (!stat.isFile()) {
36432
37882
  throw new Error(`Not a file: ${resolvedPath}`);
36433
37883
  }
@@ -36439,9 +37889,9 @@ async function uploadFile2(params) {
36439
37889
  console.error("Warning: storage URL uses HTTP — API key will be sent unencrypted");
36440
37890
  }
36441
37891
  const url = `${base}/upload`;
36442
- const fileBuffer = fs6.readFileSync(resolvedPath);
36443
- const fileName = path5.basename(resolvedPath);
36444
- const ext = path5.extname(fileName).toLowerCase();
37892
+ const fileBuffer = fs8.readFileSync(resolvedPath);
37893
+ const fileName = path7.basename(resolvedPath);
37894
+ const ext = path7.extname(fileName).toLowerCase();
36445
37895
  const mimeType = MIME_TYPES2[ext] || "application/octet-stream";
36446
37896
  const formData = new FormData;
36447
37897
  formData.append("file", new Blob([fileBuffer], { type: mimeType }), fileName);
@@ -36501,15 +37951,15 @@ async function downloadFile2(params) {
36501
37951
  const relativePath = fileUrl.startsWith("/") ? fileUrl : `/${fileUrl}`;
36502
37952
  fullUrl = `${base}${relativePath}`;
36503
37953
  }
36504
- const urlFilename = path5.basename(new URL(fullUrl).pathname);
37954
+ const urlFilename = path7.basename(new URL(fullUrl).pathname);
36505
37955
  if (!urlFilename) {
36506
37956
  throw new Error("Cannot derive filename from URL; please specify --output");
36507
37957
  }
36508
- const saveTo = outputPath ? path5.resolve(outputPath) : path5.resolve(urlFilename);
37958
+ const saveTo = outputPath ? path7.resolve(outputPath) : path7.resolve(urlFilename);
36509
37959
  if (!outputPath) {
36510
- const normalizedSave = path5.normalize(saveTo);
36511
- const cwd = path5.normalize(process.cwd());
36512
- if (normalizedSave !== cwd && !normalizedSave.startsWith(cwd + path5.sep)) {
37960
+ const normalizedSave = path7.normalize(saveTo);
37961
+ const cwd = path7.normalize(process.cwd());
37962
+ if (normalizedSave !== cwd && !normalizedSave.startsWith(cwd + path7.sep)) {
36513
37963
  throw new Error("Derived output path escapes current directory; please specify --output");
36514
37964
  }
36515
37965
  }
@@ -36542,11 +37992,11 @@ async function downloadFile2(params) {
36542
37992
  }
36543
37993
  const arrayBuffer = await response.arrayBuffer();
36544
37994
  const buffer = Buffer.from(arrayBuffer);
36545
- const parentDir = path5.dirname(saveTo);
36546
- if (!fs6.existsSync(parentDir)) {
36547
- fs6.mkdirSync(parentDir, { recursive: true });
37995
+ const parentDir = path7.dirname(saveTo);
37996
+ if (!fs8.existsSync(parentDir)) {
37997
+ fs8.mkdirSync(parentDir, { recursive: true });
36548
37998
  }
36549
- fs6.writeFileSync(saveTo, buffer);
37999
+ fs8.writeFileSync(saveTo, buffer);
36550
38000
  return {
36551
38001
  savedTo: saveTo,
36552
38002
  size: buffer.length,
@@ -36558,9 +38008,9 @@ function buildMarkdownLink2(fileUrl, storageBaseUrl, filename) {
36558
38008
  const base = normalizeBaseUrl(storageBaseUrl);
36559
38009
  const normalizedFileUrl = fileUrl.startsWith("/") ? fileUrl : `/${fileUrl}`;
36560
38010
  const fullUrl = fileUrl.startsWith("http://") || fileUrl.startsWith("https://") ? fileUrl : `${base}${normalizedFileUrl}`;
36561
- const name = filename || path5.basename(new URL(fullUrl).pathname);
38011
+ const name = filename || path7.basename(new URL(fullUrl).pathname);
36562
38012
  const safeName = name.replace(/[\[\]()]/g, "\\$&");
36563
- const ext = path5.extname(name).toLowerCase();
38013
+ const ext = path7.extname(name).toLowerCase();
36564
38014
  if (IMAGE_EXTENSIONS2.has(ext)) {
36565
38015
  return `![${safeName}](${fullUrl})`;
36566
38016
  }
@@ -36606,7 +38056,7 @@ ${links}`;
36606
38056
 
36607
38057
  // lib/clickhouse.ts
36608
38058
  import { existsSync as existsSync7, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "node:fs";
36609
- import { join as join5 } from "node:path";
38059
+ import { join as join7 } from "node:path";
36610
38060
  function validateName(name) {
36611
38061
  if (!/^[A-Za-z0-9_-]+$/.test(name))
36612
38062
  throw new Error("Invalid ClickHouse target name.");
@@ -36673,7 +38123,7 @@ async function addHostMetrics({ projectDir, name, conn, env, cluster = "default"
36673
38123
  const prefix = `clickhouse-${name}`;
36674
38124
  const text = renderScrapeConfig({ name, cluster, nodeName, orgId, serviceId: service.id, keyId, passwordFile: `/etc/pgai/host-metrics/${prefix}.secret`, apiUrl });
36675
38125
  const dir = hostMetricsDir(projectDir);
36676
- const secretFile = join5(dir, `${prefix}.secret`);
38126
+ const secretFile = join7(dir, `${prefix}.secret`);
36677
38127
  const tmpFile = `${secretFile}.tmp`;
36678
38128
  rmSync2(tmpFile, { force: true });
36679
38129
  try {
@@ -36688,7 +38138,7 @@ async function addHostMetrics({ projectDir, name, conn, env, cluster = "default"
36688
38138
  function removeHostMetrics(projectDir, name) {
36689
38139
  if (!/^[A-Za-z0-9_-]+$/.test(name))
36690
38140
  return false;
36691
- const files = ["yml", "secret", "secret.tmp"].map((ext) => join5(projectDir, "host-metrics", `clickhouse-${name}.${ext}`)).filter((file) => existsSync7(file));
38141
+ const files = ["yml", "secret", "secret.tmp"].map((ext) => join7(projectDir, "host-metrics", `clickhouse-${name}.${ext}`)).filter((file) => existsSync7(file));
36692
38142
  for (const file of files)
36693
38143
  rmSync2(file, { force: true });
36694
38144
  return files.length > 0;
@@ -36697,21 +38147,21 @@ function removeHostMetrics(projectDir, name) {
36697
38147
  // lib/host-metrics.ts
36698
38148
  import { createHash as createHash3 } from "node:crypto";
36699
38149
  import { chmodSync as chmodSync4, lstatSync as lstatSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync9, writeFileSync as writeFileSync8 } from "node:fs";
36700
- import { join as join6 } from "node:path";
38150
+ import { join as join8 } from "node:path";
36701
38151
  function scrapeFileText2(config) {
36702
38152
  const revision = `r${createHash3("sha256").update(dump2([config], { lineWidth: -1 })).digest("hex").slice(0, 16)}`;
36703
38153
  Object.assign(config.static_configs[0].labels, { __pgai_rev: revision });
36704
38154
  return dump2([config], { lineWidth: -1 });
36705
38155
  }
36706
38156
  function scrapeRevision(projectDir, file) {
36707
- const [config] = load2(readFileSync9(join6(projectDir, "host-metrics", file), "utf8"));
38157
+ const [config] = load2(readFileSync9(join8(projectDir, "host-metrics", file), "utf8"));
36708
38158
  const revision = config?.static_configs?.[0]?.labels?.__pgai_rev;
36709
38159
  if (typeof revision !== "string" || !/^r[0-9a-f]{16}$/.test(revision))
36710
38160
  throw new Error(`host-metrics/${file} has no __pgai_rev label.`);
36711
38161
  return revision;
36712
38162
  }
36713
38163
  function hostMetricsDir2(projectDir) {
36714
- const dir = join6(projectDir, "host-metrics");
38164
+ const dir = join8(projectDir, "host-metrics");
36715
38165
  if (lstatSync3(dir, { throwIfNoEntry: false })?.isSymbolicLink())
36716
38166
  throw new Error(`${dir}: host-metrics must be a directory, not a symlink.`);
36717
38167
  mkdirSync6(dir, { recursive: true, mode: 448 });
@@ -36719,8 +38169,8 @@ function hostMetricsDir2(projectDir) {
36719
38169
  return dir;
36720
38170
  }
36721
38171
  function writeScrapeFile2(dir, file, text) {
36722
- writeFileSync8(join6(dir, file), text, { mode: 420 });
36723
- chmodSync4(join6(dir, file), 420);
38172
+ writeFileSync8(join8(dir, file), text, { mode: 420 });
38173
+ chmodSync4(join8(dir, file), 420);
36724
38174
  }
36725
38175
  var HOST_METRICS_VERIFY_SCRIPT = `auth="Authorization: Basic $(printf '%s:%s' "$VM_AUTH_USERNAME" "$VM_AUTH_PASSWORD" | base64 | tr -d '\\n')"; end=$(($(date +%s) + 10)); while [ "$(date +%s)" -lt "$end" ]; do if t=$(wget -qO- -T 2 --header "$auth" http://127.0.0.1:9090/api/v1/targets); then case "$t" in '{"status":"success"'*) case "$t" in *"$1"*) [ "$2" = present ] && exit 0 ;; *) [ "$2" = absent ] && exit 0 ;; esac ;; esac; fi; sleep 0.5; done; exit 1`;
36726
38176
  var SUPABASE_JOB = "supabase-host-metrics";
@@ -36749,8 +38199,8 @@ function rdsInstance(host) {
36749
38199
  // lib/init.ts
36750
38200
  import { randomBytes as randomBytes3 } from "crypto";
36751
38201
  import { URL as URL3, fileURLToPath as fileURLToPath2 } from "url";
36752
- import * as fs7 from "fs";
36753
- import * as path6 from "path";
38202
+ import * as fs9 from "fs";
38203
+ import * as path8 from "path";
36754
38204
  var DEFAULT_MONITORING_USER2 = "postgres_ai_mon";
36755
38205
  var KNOWN_PROVIDERS = ["self-managed", "supabase", "clickhouse"];
36756
38206
  var SKIP_ROLE_CREATION_PROVIDERS2 = ["supabase"];
@@ -36895,21 +38345,21 @@ function describeInitScope(plan) {
36895
38345
  }
36896
38346
  function sqlDir2() {
36897
38347
  const currentFile = fileURLToPath2(import.meta.url);
36898
- const currentDir = path6.dirname(currentFile);
38348
+ const currentDir = path8.dirname(currentFile);
36899
38349
  const candidates = [
36900
- path6.resolve(currentDir, "..", "sql"),
36901
- path6.resolve(currentDir, "..", "..", "sql")
38350
+ path8.resolve(currentDir, "..", "sql"),
38351
+ path8.resolve(currentDir, "..", "..", "sql")
36902
38352
  ];
36903
38353
  for (const candidate of candidates) {
36904
- if (fs7.existsSync(candidate)) {
38354
+ if (fs9.existsSync(candidate)) {
36905
38355
  return candidate;
36906
38356
  }
36907
38357
  }
36908
38358
  throw new Error(`SQL directory not found. Searched: ${candidates.join(", ")}`);
36909
38359
  }
36910
38360
  function loadSqlTemplate2(filename) {
36911
- const p = path6.join(sqlDir2(), filename);
36912
- return fs7.readFileSync(p, "utf8");
38361
+ const p = path8.join(sqlDir2(), filename);
38362
+ return fs9.readFileSync(p, "utf8");
36913
38363
  }
36914
38364
  function applyTemplate2(sql, vars) {
36915
38365
  return sql.replace(/\{\{([A-Z0-9_]+)\}\}/g, (_, key) => {
@@ -38712,8 +40162,8 @@ import { Writable } from "stream";
38712
40162
  import * as childProcess from "child_process";
38713
40163
 
38714
40164
  // lib/checkup.ts
38715
- import * as fs8 from "fs";
38716
- import * as path7 from "path";
40165
+ import * as fs10 from "fs";
40166
+ import * as path9 from "path";
38717
40167
 
38718
40168
  // lib/metrics-embedded.ts
38719
40169
  var METRICS = {
@@ -42681,7 +44131,7 @@ function createBaseReport(checkId, checkTitle, nodeName) {
42681
44131
  }
42682
44132
  function readTextFileSafe(p) {
42683
44133
  try {
42684
- const value = fs8.readFileSync(p, "utf8").trim();
44134
+ const value = fs10.readFileSync(p, "utf8").trim();
42685
44135
  return value || null;
42686
44136
  } catch {
42687
44137
  return null;
@@ -42694,8 +44144,8 @@ function resolveBuildTs() {
42694
44144
  if (fromFile)
42695
44145
  return fromFile;
42696
44146
  try {
42697
- const pkgRoot = path7.resolve(__dirname, "..");
42698
- const fromPkgFile = readTextFileSafe(path7.join(pkgRoot, "BUILD_TS"));
44147
+ const pkgRoot = path9.resolve(__dirname, "..");
44148
+ const fromPkgFile = readTextFileSafe(path9.join(pkgRoot, "BUILD_TS"));
42699
44149
  if (fromPkgFile)
42700
44150
  return fromPkgFile;
42701
44151
  } catch (err) {
@@ -42703,8 +44153,8 @@ function resolveBuildTs() {
42703
44153
  console.warn(`[resolveBuildTs] Warning: path resolution failed: ${errorMsg}`);
42704
44154
  }
42705
44155
  try {
42706
- const pkgJsonPath = path7.resolve(__dirname, "..", "package.json");
42707
- const st = fs8.statSync(pkgJsonPath);
44156
+ const pkgJsonPath = path9.resolve(__dirname, "..", "package.json");
44157
+ const st = fs10.statSync(pkgJsonPath);
42708
44158
  return st.mtime.toISOString();
42709
44159
  } catch (err) {
42710
44160
  if (process.env.DEBUG) {
@@ -44913,7 +46363,7 @@ function runChild(command, args, env, json, source) {
44913
46363
  }
44914
46364
 
44915
46365
  // lib/instances.ts
44916
- import * as fs9 from "fs";
46366
+ import * as fs11 from "fs";
44917
46367
  class InstancesParseError2 extends Error {
44918
46368
  constructor(file, cause) {
44919
46369
  const yamlErr = cause;
@@ -44923,11 +46373,11 @@ class InstancesParseError2 extends Error {
44923
46373
  }
44924
46374
  }
44925
46375
  function loadInstances2(file) {
44926
- if (!fs9.existsSync(file))
46376
+ if (!fs11.existsSync(file))
44927
46377
  return [];
44928
- if (fs9.lstatSync(file).isDirectory())
46378
+ if (fs11.lstatSync(file).isDirectory())
44929
46379
  return [];
44930
- const text = fs9.readFileSync(file, "utf8");
46380
+ const text = fs11.readFileSync(file, "utf8");
44931
46381
  if (text.trim() === "")
44932
46382
  return [];
44933
46383
  let parsed;
@@ -44960,8 +46410,8 @@ function buildInstance(name, connStr) {
44960
46410
  };
44961
46411
  }
44962
46412
  function addInstanceToFile(file, instance) {
44963
- if (fs9.existsSync(file) && fs9.lstatSync(file).isDirectory()) {
44964
- fs9.rmSync(file, { recursive: true, force: true });
46413
+ if (fs11.existsSync(file) && fs11.lstatSync(file).isDirectory()) {
46414
+ fs11.rmSync(file, { recursive: true, force: true });
44965
46415
  }
44966
46416
  const existing = loadInstances2(file);
44967
46417
  if (existing.some((i) => i.name === instance.name)) {
@@ -44980,18 +46430,18 @@ function removeInstanceFromFile(file, name) {
44980
46430
  }
44981
46431
  function writeInstancesFile(file, instances) {
44982
46432
  const content = dump2(instances);
44983
- const fd = fs9.openSync(file, "w", 384);
46433
+ const fd = fs11.openSync(file, "w", 384);
44984
46434
  try {
44985
46435
  try {
44986
- fs9.fchmodSync(fd, 384);
46436
+ fs11.fchmodSync(fd, 384);
44987
46437
  } catch (err) {
44988
46438
  const message = err instanceof Error ? err.message : String(err);
44989
46439
  console.error(`Warning: could not restrict permissions on ${file}: ${message}`);
44990
46440
  console.error(" It may be readable by other users on this machine.");
44991
46441
  }
44992
- fs9.writeFileSync(fd, content, "utf8");
46442
+ fs11.writeFileSync(fd, content, "utf8");
44993
46443
  } finally {
44994
- fs9.closeSync(fd);
46444
+ fs11.closeSync(fd);
44995
46445
  }
44996
46446
  }
44997
46447
  function extractSslmode2(connStr) {
@@ -45102,7 +46552,7 @@ async function verifyCollectorTls2(url) {
45102
46552
  u.searchParams.delete(key);
45103
46553
  const client = new Client2({
45104
46554
  ...buildClientConfig2(splitChannelBinding2(u.toString()).uri, { connectionTimeoutMillis: 1e4 }),
45105
- ssl: { rejectUnauthorized: true, servername: u.hostname, ...ca ? { ca: fs9.readFileSync(ca, "utf8") } : {} }
46555
+ ssl: { rejectUnauthorized: true, servername: u.hostname, ...ca ? { ca: fs11.readFileSync(ca, "utf8") } : {} }
45106
46556
  });
45107
46557
  try {
45108
46558
  await client.connect();
@@ -45191,8 +46641,8 @@ var REQUIRED_ENV_KEYS = [
45191
46641
  { key: "VM_PPROF_AUTH_KEY", defaultValue: () => crypto2.randomBytes(32).toString("hex"), introducedIn: "0.17" }
45192
46642
  ];
45193
46643
  function ensureRequiredEnvVars(projectDir) {
45194
- const envFile = path8.resolve(projectDir, ".env");
45195
- const existing = fs10.existsSync(envFile) ? fs10.readFileSync(envFile, "utf8") : "";
46644
+ const envFile = path10.resolve(projectDir, ".env");
46645
+ const existing = fs12.existsSync(envFile) ? fs12.readFileSync(envFile, "utf8") : "";
45196
46646
  const added = [];
45197
46647
  const appendLines = [];
45198
46648
  let content = existing;
@@ -45227,23 +46677,23 @@ function ensureRequiredEnvVars(projectDir) {
45227
46677
  function writeEnvFile(envFile, content) {
45228
46678
  let targetFile = envFile;
45229
46679
  try {
45230
- if (fs10.existsSync(envFile))
45231
- targetFile = fs10.realpathSync(envFile);
46680
+ if (fs12.existsSync(envFile))
46681
+ targetFile = fs12.realpathSync(envFile);
45232
46682
  } catch {}
45233
46683
  const tmpFile = `${targetFile}.tmp`;
45234
- fs10.writeFileSync(tmpFile, content, { encoding: "utf8", mode: 384 });
46684
+ fs12.writeFileSync(tmpFile, content, { encoding: "utf8", mode: 384 });
45235
46685
  try {
45236
- fs10.chmodSync(tmpFile, 384);
45237
- if (fs10.existsSync(targetFile)) {
45238
- const st = fs10.statSync(targetFile);
45239
- fs10.chownSync(tmpFile, st.uid, st.gid);
46686
+ fs12.chmodSync(tmpFile, 384);
46687
+ if (fs12.existsSync(targetFile)) {
46688
+ const st = fs12.statSync(targetFile);
46689
+ fs12.chownSync(tmpFile, st.uid, st.gid);
45240
46690
  }
45241
46691
  } catch {}
45242
46692
  try {
45243
- fs10.renameSync(tmpFile, targetFile);
46693
+ fs12.renameSync(tmpFile, targetFile);
45244
46694
  } catch (error) {
45245
46695
  try {
45246
- fs10.unlinkSync(tmpFile);
46696
+ fs12.unlinkSync(tmpFile);
45247
46697
  } catch {}
45248
46698
  throw error;
45249
46699
  }
@@ -45300,7 +46750,7 @@ function statOwner(file) {
45300
46750
  return;
45301
46751
  let st;
45302
46752
  try {
45303
- st = fs10.statSync(file);
46753
+ st = fs12.statSync(file);
45304
46754
  } catch {
45305
46755
  return;
45306
46756
  }
@@ -45444,7 +46894,7 @@ function expandHomePath(p) {
45444
46894
  if (s === "~")
45445
46895
  return os3.homedir();
45446
46896
  if (s.startsWith("~/") || s.startsWith("~\\")) {
45447
- return path8.join(os3.homedir(), s.slice(2));
46897
+ return path10.join(os3.homedir(), s.slice(2));
45448
46898
  }
45449
46899
  return s;
45450
46900
  }
@@ -45493,10 +46943,10 @@ function prepareOutputDirectory(outputOpt) {
45493
46943
  if (!outputOpt)
45494
46944
  return;
45495
46945
  const outputDir = expandHomePath(outputOpt);
45496
- const outputPath = path8.isAbsolute(outputDir) ? outputDir : path8.resolve(process.cwd(), outputDir);
45497
- if (!fs10.existsSync(outputPath)) {
46946
+ const outputPath = path10.isAbsolute(outputDir) ? outputDir : path10.resolve(process.cwd(), outputDir);
46947
+ if (!fs12.existsSync(outputPath)) {
45498
46948
  try {
45499
- fs10.mkdirSync(outputPath, { recursive: true });
46949
+ fs12.mkdirSync(outputPath, { recursive: true });
45500
46950
  } catch (e) {
45501
46951
  const errAny = e;
45502
46952
  const code = typeof errAny?.code === "string" ? errAny.code : "";
@@ -45587,8 +47037,8 @@ async function uploadCheckupReports(uploadCfg, reports, spinner, logUpload) {
45587
47037
  }
45588
47038
  function writeReportFiles(reports, outputPath) {
45589
47039
  for (const [checkId, report] of Object.entries(reports)) {
45590
- const filePath = path8.join(outputPath, `${checkId}.json`);
45591
- fs10.writeFileSync(filePath, JSON.stringify(report, null, 2), "utf8");
47040
+ const filePath = path10.join(outputPath, `${checkId}.json`);
47041
+ fs12.writeFileSync(filePath, JSON.stringify(report, null, 2), "utf8");
45592
47042
  const title = report.checkTitle || checkId;
45593
47043
  console.log(`\u2713 ${checkId} ${title}: ${filePath}`);
45594
47044
  }
@@ -45633,7 +47083,7 @@ function getDefaultMonitoringProjectDir() {
45633
47083
  const override = process.env.PGAI_PROJECT_DIR;
45634
47084
  if (override && override.trim())
45635
47085
  return override.trim();
45636
- return path8.join(getConfigDir(), "monitoring");
47086
+ return path10.join(getConfigDir(), "monitoring");
45637
47087
  }
45638
47088
  async function downloadText(url) {
45639
47089
  const controller = new AbortController;
@@ -45658,52 +47108,52 @@ function composeRefCandidates() {
45658
47108
  }
45659
47109
  async function ensureDefaultMonitoringProject() {
45660
47110
  const projectDir = getDefaultMonitoringProjectDir();
45661
- const composeFile = path8.resolve(projectDir, "docker-compose.yml");
45662
- const instancesFile = path8.resolve(projectDir, "instances.yml");
45663
- if (!fs10.existsSync(projectDir)) {
45664
- fs10.mkdirSync(projectDir, { recursive: true, mode: 448 });
47111
+ const composeFile = path10.resolve(projectDir, "docker-compose.yml");
47112
+ const instancesFile = path10.resolve(projectDir, "instances.yml");
47113
+ if (!fs12.existsSync(projectDir)) {
47114
+ fs12.mkdirSync(projectDir, { recursive: true, mode: 448 });
45665
47115
  }
45666
- if (!fs10.existsSync(composeFile)) {
47116
+ if (!fs12.existsSync(composeFile)) {
45667
47117
  const refs = composeRefCandidates();
45668
47118
  let lastErr;
45669
47119
  for (const ref of refs) {
45670
47120
  const url = `https://gitlab.com/postgres-ai/postgres_ai/-/raw/${encodeURIComponent(ref)}/docker-compose.yml`;
45671
47121
  try {
45672
47122
  const text = await downloadText(url);
45673
- fs10.writeFileSync(composeFile, text, { encoding: "utf8", mode: 384 });
47123
+ fs12.writeFileSync(composeFile, text, { encoding: "utf8", mode: 384 });
45674
47124
  break;
45675
47125
  } catch (err) {
45676
47126
  lastErr = err;
45677
47127
  }
45678
47128
  }
45679
- if (!fs10.existsSync(composeFile)) {
47129
+ if (!fs12.existsSync(composeFile)) {
45680
47130
  const msg = lastErr instanceof Error ? lastErr.message : String(lastErr);
45681
47131
  throw new Error(`Failed to bootstrap docker-compose.yml: ${msg}`);
45682
47132
  }
45683
47133
  }
45684
47134
  ensureHostMetricsDir(projectDir);
45685
- if (fs10.existsSync(instancesFile) && fs10.lstatSync(instancesFile).isDirectory()) {
45686
- fs10.rmSync(instancesFile, { recursive: true, force: true });
47135
+ if (fs12.existsSync(instancesFile) && fs12.lstatSync(instancesFile).isDirectory()) {
47136
+ fs12.rmSync(instancesFile, { recursive: true, force: true });
45687
47137
  }
45688
- if (!fs10.existsSync(instancesFile)) {
47138
+ if (!fs12.existsSync(instancesFile)) {
45689
47139
  const header = `# PostgreSQL instances to monitor
45690
47140
  ` + `# Add your instances using: pgai mon targets add <connection-string> <name>
45691
47141
 
45692
47142
  `;
45693
- fs10.writeFileSync(instancesFile, header, { encoding: "utf8", mode: 384 });
47143
+ fs12.writeFileSync(instancesFile, header, { encoding: "utf8", mode: 384 });
45694
47144
  }
45695
- const pgwatchConfig = path8.resolve(projectDir, ".pgwatch-config");
45696
- if (!fs10.existsSync(pgwatchConfig)) {
45697
- fs10.writeFileSync(pgwatchConfig, "", { encoding: "utf8", mode: 384 });
47145
+ const pgwatchConfig = path10.resolve(projectDir, ".pgwatch-config");
47146
+ if (!fs12.existsSync(pgwatchConfig)) {
47147
+ fs12.writeFileSync(pgwatchConfig, "", { encoding: "utf8", mode: 384 });
45698
47148
  }
45699
- const envFile = path8.resolve(projectDir, ".env");
45700
- if (!fs10.existsSync(envFile)) {
47149
+ const envFile = path10.resolve(projectDir, ".env");
47150
+ if (!fs12.existsSync(envFile)) {
45701
47151
  const envText = `PGAI_TAG=${package_default.version}
45702
47152
  # PGAI_REGISTRY=registry.gitlab.com/postgres-ai/postgres_ai
45703
47153
  `;
45704
- fs10.writeFileSync(envFile, envText, { encoding: "utf8", mode: 384 });
47154
+ fs12.writeFileSync(envFile, envText, { encoding: "utf8", mode: 384 });
45705
47155
  }
45706
- return { fs: fs10, path: path8, projectDir, composeFile, instancesFile };
47156
+ return { fs: fs12, path: path10, projectDir, composeFile, instancesFile };
45707
47157
  }
45708
47158
  function sanitizeTagForBackup(tag) {
45709
47159
  if (tag == null)
@@ -45712,10 +47162,10 @@ function sanitizeTagForBackup(tag) {
45712
47162
  return /^[A-Za-z0-9._-]{1,64}$/.test(stripped) ? stripped : null;
45713
47163
  }
45714
47164
  function readDeployedTag(projectDir) {
45715
- const envFile = path8.resolve(projectDir, ".env");
45716
- if (!fs10.existsSync(envFile))
47165
+ const envFile = path10.resolve(projectDir, ".env");
47166
+ if (!fs12.existsSync(envFile))
45717
47167
  return null;
45718
- const m = fs10.readFileSync(envFile, "utf8").match(/^PGAI_TAG=(.+)$/m);
47168
+ const m = fs12.readFileSync(envFile, "utf8").match(/^PGAI_TAG=(.+)$/m);
45719
47169
  return m ? sanitizeTagForBackup(m[1]) : null;
45720
47170
  }
45721
47171
  function isValidComposeYaml(text) {
@@ -45752,12 +47202,12 @@ function composeContentEqual(a, b) {
45752
47202
  return a.replace(/\s+$/, "") === b.replace(/\s+$/, "");
45753
47203
  }
45754
47204
  async function refreshBundledComposeIfStale(projectDir, oldTag) {
45755
- if (fs10.existsSync(path8.resolve(projectDir, ".git")))
47205
+ if (fs12.existsSync(path10.resolve(projectDir, ".git")))
45756
47206
  return false;
45757
47207
  if (process.env.PGAI_SKIP_COMPOSE_REFRESH === "1")
45758
47208
  return false;
45759
- const composeFile = path8.resolve(projectDir, "docker-compose.yml");
45760
- if (!fs10.existsSync(composeFile))
47209
+ const composeFile = path10.resolve(projectDir, "docker-compose.yml");
47210
+ if (!fs12.existsSync(composeFile))
45761
47211
  return false;
45762
47212
  const refs = composeRefCandidates();
45763
47213
  const fetched = await fetchTargetCompose(refs);
@@ -45766,24 +47216,24 @@ async function refreshBundledComposeIfStale(projectDir, oldTag) {
45766
47216
  console.error(" Keeping the existing compose. If dashboards are blank after upgrade, re-run this command once network is available.");
45767
47217
  return false;
45768
47218
  }
45769
- const existing = fs10.readFileSync(composeFile, "utf8");
47219
+ const existing = fs12.readFileSync(composeFile, "utf8");
45770
47220
  if (composeContentEqual(existing, fetched))
45771
47221
  return false;
45772
47222
  const deployedTag = sanitizeTagForBackup(oldTag ?? readDeployedTag(projectDir));
45773
47223
  const tagPart = deployedTag ?? new Date().toISOString().replace(/[:.]/g, "-");
45774
47224
  const oldHash = crypto2.createHash("sha256").update(existing).digest("hex").slice(0, 8);
45775
- const backup = path8.resolve(projectDir, `docker-compose.yml.bak-${tagPart}-${oldHash}`);
47225
+ const backup = path10.resolve(projectDir, `docker-compose.yml.bak-${tagPart}-${oldHash}`);
45776
47226
  let backupName = null;
45777
47227
  try {
45778
- fs10.writeFileSync(backup, existing, { encoding: "utf8", mode: 384, flag: "wx" });
45779
- backupName = path8.basename(backup);
47228
+ fs12.writeFileSync(backup, existing, { encoding: "utf8", mode: 384, flag: "wx" });
47229
+ backupName = path10.basename(backup);
45780
47230
  } catch (err) {
45781
47231
  const e = err;
45782
47232
  if (e && e.code === "EEXIST") {
45783
- backupName = path8.basename(backup);
47233
+ backupName = path10.basename(backup);
45784
47234
  }
45785
47235
  }
45786
- fs10.writeFileSync(composeFile, fetched, { encoding: "utf8", mode: 384 });
47236
+ fs12.writeFileSync(composeFile, fetched, { encoding: "utf8", mode: 384 });
45787
47237
  const backupNote = backupName ? ` (backup: ${backupName})` : "";
45788
47238
  console.log(`\u2713 Refreshed docker-compose.yml to ${package_default.version}${backupNote}`);
45789
47239
  return true;
@@ -47208,12 +48658,12 @@ function resolvePaths() {
47208
48658
  const startDir = process.cwd();
47209
48659
  let currentDir = startDir;
47210
48660
  while (true) {
47211
- const composeFile = path8.resolve(currentDir, "docker-compose.yml");
47212
- if (fs10.existsSync(composeFile)) {
47213
- const instancesFile = path8.resolve(currentDir, "instances.yml");
47214
- return { fs: fs10, path: path8, projectDir: currentDir, composeFile, instancesFile };
48661
+ const composeFile = path10.resolve(currentDir, "docker-compose.yml");
48662
+ if (fs12.existsSync(composeFile)) {
48663
+ const instancesFile = path10.resolve(currentDir, "instances.yml");
48664
+ return { fs: fs12, path: path10, projectDir: currentDir, composeFile, instancesFile };
47215
48665
  }
47216
- const parentDir = path8.dirname(currentDir);
48666
+ const parentDir = path10.dirname(currentDir);
47217
48667
  if (parentDir === currentDir)
47218
48668
  break;
47219
48669
  currentDir = parentDir;
@@ -47232,7 +48682,7 @@ async function resolveOrInitPaths() {
47232
48682
  }
47233
48683
  function ensureHostMetricsDir(projectDir) {
47234
48684
  try {
47235
- fs10.mkdirSync(path8.join(projectDir, "host-metrics"), { recursive: true, mode: 448 });
48685
+ fs12.mkdirSync(path10.join(projectDir, "host-metrics"), { recursive: true, mode: 448 });
47236
48686
  } catch {}
47237
48687
  }
47238
48688
  function isDockerRunning() {
@@ -47373,13 +48823,13 @@ function resolveAdoptedProject(reg) {
47373
48823
  }
47374
48824
  function updatePgwatchConfig(configPath, updates) {
47375
48825
  let lines = [];
47376
- if (fs10.existsSync(configPath)) {
47377
- const stats = fs10.statSync(configPath);
48826
+ if (fs12.existsSync(configPath)) {
48827
+ const stats = fs12.statSync(configPath);
47378
48828
  if (!stats.isFile()) {
47379
48829
  throw new Error(`${configPath} exists but is not a regular file; refusing to write through it`);
47380
48830
  }
47381
48831
  {
47382
- const content = fs10.readFileSync(configPath, "utf8").replace(/^\uFEFF+/, "");
48832
+ const content = fs12.readFileSync(configPath, "utf8").replace(/^\uFEFF+/, "");
47383
48833
  lines = content.split(/\r?\n/).filter((l) => l.trim() !== "");
47384
48834
  }
47385
48835
  }
@@ -47392,18 +48842,18 @@ function updatePgwatchConfig(configPath, updates) {
47392
48842
  lines.push(`${key}=${value}`);
47393
48843
  }
47394
48844
  }
47395
- fs10.writeFileSync(configPath, lines.join(`
48845
+ fs12.writeFileSync(configPath, lines.join(`
47396
48846
  `) + `
47397
48847
  `, { encoding: "utf8", mode: 384 });
47398
48848
  try {
47399
- fs10.chmodSync(configPath, 384);
48849
+ fs12.chmodSync(configPath, 384);
47400
48850
  } catch (err) {
47401
48851
  const message = err instanceof Error ? err.message : String(err);
47402
48852
  console.error(`Warning: could not restrict permissions on ${configPath}: ${message}`);
47403
48853
  }
47404
48854
  }
47405
48855
  function applyApiKey(projectDir, apiKey, opts) {
47406
- const configPath = path8.resolve(projectDir, ".pgwatch-config");
48856
+ const configPath = path10.resolve(projectDir, ".pgwatch-config");
47407
48857
  try {
47408
48858
  updatePgwatchConfig(configPath, { api_key: apiKey, api_url: resolveBaseUrls2(opts).apiBaseUrl });
47409
48859
  } catch (err) {
@@ -47438,10 +48888,10 @@ function parseDurationSeconds(v) {
47438
48888
  function readInstanceIdFromProject() {
47439
48889
  try {
47440
48890
  const { projectDir } = resolvePaths();
47441
- const configPath = path8.resolve(projectDir, ".pgwatch-config");
47442
- if (!fs10.existsSync(configPath))
48891
+ const configPath = path10.resolve(projectDir, ".pgwatch-config");
48892
+ if (!fs12.existsSync(configPath))
47443
48893
  return null;
47444
- const line = fs10.readFileSync(configPath, "utf8").replace(/^\uFEFF+/, "").split(/\r?\n/).find((l) => l.startsWith("instance_id="));
48894
+ const line = fs12.readFileSync(configPath, "utf8").replace(/^\uFEFF+/, "").split(/\r?\n/).find((l) => l.startsWith("instance_id="));
47445
48895
  const value = line?.slice("instance_id=".length).trim();
47446
48896
  return value && INSTANCE_ID_RE.test(value) ? value : null;
47447
48897
  } catch {
@@ -47449,7 +48899,7 @@ function readInstanceIdFromProject() {
47449
48899
  }
47450
48900
  }
47451
48901
  function applyProjectName(projectDir, project) {
47452
- const configPath = path8.resolve(projectDir, ".pgwatch-config");
48902
+ const configPath = path10.resolve(projectDir, ".pgwatch-config");
47453
48903
  try {
47454
48904
  updatePgwatchConfig(configPath, { project_name: project });
47455
48905
  } catch (err) {
@@ -47465,7 +48915,7 @@ function persistInstanceId(projectDir, reg, requestedId, alsoWrite = {}) {
47465
48915
  const updates = { ...alsoWrite, ...instanceId ? { instance_id: instanceId } : {} };
47466
48916
  if (Object.keys(updates).length === 0)
47467
48917
  return false;
47468
- const configPath = path8.resolve(projectDir, ".pgwatch-config");
48918
+ const configPath = path10.resolve(projectDir, ".pgwatch-config");
47469
48919
  try {
47470
48920
  updatePgwatchConfig(configPath, updates);
47471
48921
  return instanceId != null;
@@ -47567,12 +49017,12 @@ async function runCompose(args, grafanaPassword, extraEnv) {
47567
49017
  if (grafanaPassword) {
47568
49018
  env.GF_SECURITY_ADMIN_PASSWORD = grafanaPassword;
47569
49019
  } else {
47570
- const cfgPath = path8.resolve(projectDir, ".pgwatch-config");
47571
- if (fs10.existsSync(cfgPath)) {
49020
+ const cfgPath = path10.resolve(projectDir, ".pgwatch-config");
49021
+ if (fs12.existsSync(cfgPath)) {
47572
49022
  try {
47573
- const stats = fs10.statSync(cfgPath);
49023
+ const stats = fs12.statSync(cfgPath);
47574
49024
  if (!stats.isDirectory()) {
47575
- const content = fs10.readFileSync(cfgPath, "utf8");
49025
+ const content = fs12.readFileSync(cfgPath, "utf8");
47576
49026
  const match = content.match(/^grafana_password=([^\r\n]+)/m);
47577
49027
  if (match) {
47578
49028
  env.GF_SECURITY_ADMIN_PASSWORD = match[1].trim();
@@ -47585,10 +49035,10 @@ async function runCompose(args, grafanaPassword, extraEnv) {
47585
49035
  }
47586
49036
  }
47587
49037
  }
47588
- const envFilePath = path8.resolve(projectDir, ".env");
47589
- if (fs10.existsSync(envFilePath)) {
49038
+ const envFilePath = path10.resolve(projectDir, ".env");
49039
+ if (fs12.existsSync(envFilePath)) {
47590
49040
  try {
47591
- const envContent = fs10.readFileSync(envFilePath, "utf8");
49041
+ const envContent = fs12.readFileSync(envFilePath, "utf8");
47592
49042
  if (!env.VM_AUTH_USERNAME) {
47593
49043
  const m = envContent.match(/^VM_AUTH_USERNAME=([^\r\n]+)/m);
47594
49044
  if (m)
@@ -47632,7 +49082,7 @@ async function applySinkPrometheusConfig(projectDir) {
47632
49082
  const { stdout } = await execFilePromise(composeCmd[0], [
47633
49083
  ...composeCmd.slice(1),
47634
49084
  "-f",
47635
- path8.resolve(projectDir, "docker-compose.yml"),
49085
+ path10.resolve(projectDir, "docker-compose.yml"),
47636
49086
  "ps",
47637
49087
  "-q",
47638
49088
  "sink-prometheus"
@@ -47679,10 +49129,10 @@ function readComposeProfiles(knownProjectDir) {
47679
49129
  projectDir = getDefaultMonitoringProjectDir();
47680
49130
  }
47681
49131
  }
47682
- const envFile = path8.resolve(projectDir, ".env");
49132
+ const envFile = path10.resolve(projectDir, ".env");
47683
49133
  let content;
47684
49134
  try {
47685
- content = fs10.readFileSync(envFile, "utf8");
49135
+ content = fs12.readFileSync(envFile, "utf8");
47686
49136
  } catch (err) {
47687
49137
  if (err?.code !== "ENOENT") {
47688
49138
  console.error(`\u26A0 Could not read ${envFile}: ${err instanceof Error ? err.message : String(err)}`);
@@ -47727,7 +49177,7 @@ async function composeServiceRunning(projectDir, service) {
47727
49177
  if (!composeCmd)
47728
49178
  return null;
47729
49179
  try {
47730
- const { stdout } = await execFilePromise(composeCmd[0], [...composeCmd.slice(1), "-f", path8.resolve(projectDir, "docker-compose.yml"), "ps", "-q", service], { cwd: projectDir });
49180
+ const { stdout } = await execFilePromise(composeCmd[0], [...composeCmd.slice(1), "-f", path10.resolve(projectDir, "docker-compose.yml"), "ps", "-q", service], { cwd: projectDir });
47731
49181
  return stdout.trim().length > 0;
47732
49182
  } catch {
47733
49183
  return null;
@@ -47884,10 +49334,11 @@ async function runConnect(urlArg, opts) {
47884
49334
  const tty = !json && !!process.stderr.isTTY && !process.env.CI && process.env.TERM !== "dumb";
47885
49335
  let createdId;
47886
49336
  let stopping = false;
49337
+ let privateLink = false;
47887
49338
  const steps = stepProgress({
47888
49339
  json,
47889
49340
  tty,
47890
- makeView: () => new StepView2(`Deploying monitoring for ${shownName || "the Supabase project"}`, monitoringSteps(provider), true),
49341
+ makeView: () => new StepView2(`Deploying monitoring for ${shownName || "the Supabase project"}`, privateLink ? PRIVATELINK_STEPS : monitoringSteps(provider), true),
47891
49342
  writeLine: (line) => console.error(line),
47892
49343
  writeEvent: writeEvent2,
47893
49344
  onId: (id) => {
@@ -47926,7 +49377,8 @@ ${reply}`);
47926
49377
  process.on("SIGINT", onSigint);
47927
49378
  let result;
47928
49379
  try {
47929
- result = await connect2(url, { ...opts, vcpus, waitMs: minutes * 60000 }, {
49380
+ const resumed = provider === "rds" && process.env.PGAI_MON_NONCE ? { nonce: process.env.PGAI_MON_NONCE, monitoringPassword: process.env.PGAI_MON_PASSWORD } : {};
49381
+ result = await connect2(url, { ...opts, ...resumed, vcpus, waitMs: minutes * 60000 }, {
47930
49382
  ...api,
47931
49383
  selfHosted: async (monitoringUrl, env) => {
47932
49384
  const scope = getActiveOrgScope2();
@@ -47967,6 +49419,19 @@ ${reply}`);
47967
49419
  closeReadline();
47968
49420
  }
47969
49421
  },
49422
+ ...interactive(opts.json) ? { ask: async (q, lines = []) => {
49423
+ steps.view()?.stop();
49424
+ for (const line of lines)
49425
+ console.error(terminalText2(line));
49426
+ process.exitCode = 130;
49427
+ try {
49428
+ return await question(q);
49429
+ } finally {
49430
+ process.exitCode = undefined;
49431
+ closeReadline();
49432
+ steps.reset();
49433
+ }
49434
+ } } : {},
47970
49435
  ...interactive(opts.json) ? { allowIp: async (lines) => {
47971
49436
  steps.view()?.stop();
47972
49437
  console.error("");
@@ -48022,7 +49487,7 @@ Projects in the Supabase organization "${org}":`));
48022
49487
  closeReadline();
48023
49488
  }
48024
49489
  } } : {},
48025
- ...interactive(opts.json) ? { openUrl: openInBrowser } : {},
49490
+ ...interactive(opts.json) && canOpenBrowser() ? { openUrl: openInBrowser } : {},
48026
49491
  progress: (e) => {
48027
49492
  if (e.event === "provisioning")
48028
49493
  requested = true;
@@ -48032,6 +49497,8 @@ Projects in the Supabase organization "${org}":`));
48032
49497
  looking = false;
48033
49498
  if (e.project)
48034
49499
  shownName = terminalText2(e.project);
49500
+ if (e.location_reason === "privatelink")
49501
+ privateLink = true;
48035
49502
  steps.progress(e);
48036
49503
  },
48037
49504
  aborted: () => stopping
@@ -48077,7 +49544,7 @@ Projects in the Supabase organization "${org}":`));
48077
49544
  }
48078
49545
  }
48079
49546
  var mon = program2.command("mon").description("monitoring services management");
48080
- sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (default: host[:port]/database)", "the box's region on its cloud (default: the database's region when that cloud has it; see below)", "where the monitoring box runs: aws or hetzner (default: the database's cloud, else aws)").description("deploy PostgresAI Cloud monitoring for a database: prepare it, provision the monitoring box, print its Health Matrix and dashboard").option("--provider <provider>", "generic (direct PostgreSQL URL; alias: self-managed) | clickhouse | rds | supabase (default: detected from the host)").option("--clickhouse-key <id:secret>", "ClickHouse Cloud API key (Basic Service API Reader) for CPU, memory and disk; or CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET").option("--self-hosted", "run the monitoring stack on this machine (mon local-install) instead of PostgresAI Cloud").option("--reset-password", "the monitoring role exists and its password is lost: set a new one (admin URL; refused while another database on the server is monitored)").option("--monitoring-user <name>", "monitoring role to create or use", DEFAULT_MONITORING_USER2).option("--coupon <code>", "promotion code for the organization's monitoring subscription (applies when it is first created)").option("--vcpus <n>", "vCPUs of the database server; without it there is no AAS (database load) data (asked at a terminal; Supabase: from the project's compute size)").option("--supabase-project <name|project-id>", "the Supabase project to monitor (its exact name, or its project ID), instead of a URL; implies --provider supabase").option("--ip-first", "reserve the monitoring box's IP and stop before the box: the IP is kept for a week, so you can allow it on the database and continue the deploy afterwards with --ip-allowed (PostgresAI Cloud only)").option("--ip-allowed", "the database now allows the reserved IP: create the box with it").addHelpText("after", [
49547
+ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (default: host[:port]/database)", "the box's region on its cloud (default: the database's region when that cloud has it; see below)", "where the monitoring box runs: aws or hetzner (default: the database's cloud, else aws)").description("deploy PostgresAI Cloud monitoring for a database: prepare it, provision the monitoring box, print its Health Matrix and dashboard").option("--provider <provider>", "generic (direct PostgreSQL URL; alias: self-managed) | clickhouse | rds | supabase (default: detected from the host)").option("--clickhouse-key <id:secret>", "ClickHouse Cloud API key (Basic Service API Reader) for CPU, memory and disk; or CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET").option("--self-hosted", "run the monitoring stack on this machine (mon local-install) instead of PostgresAI Cloud").option("--reset-password", "the monitoring role exists and its password is lost: set a new one (admin URL; refused while another database on the server is monitored)").option("--monitoring-user <name>", "monitoring role to create or use (not over AWS PrivateLink, which uses postgres_ai_mon)", DEFAULT_MONITORING_USER2).option("--coupon <code>", "promotion code for the organization's monitoring subscription (applies when it is first created)").option("--vcpus <n>", "vCPUs of the database server; without it there is no AAS (database load) data (asked at a terminal; Supabase: from the project's compute size)").option("--supabase-project <name|project-id>", "the Supabase project to monitor (its exact name, or its project ID), instead of a URL; implies --provider supabase").option("--ip-first", "reserve the monitoring box's IP and stop before the box: the IP is kept for a week, so you can allow it on the database and continue the deploy afterwards with --ip-allowed (PostgresAI Cloud only)").option("--ip-allowed", "the database now allows the reserved IP: create the box with it").option("--privatelink", "RDS: monitor over AWS PrivateLink (the instance is not publicly accessible; default: decided from AWS or public DNS)").option("--no-privatelink", "RDS: monitor directly (the instance is publicly accessible)").option("--vpce-service <name>", "RDS over PrivateLink: the stack's VpceServiceName output, when this machine can't read it from AWS").option("--host-stats", "RDS over PrivateLink: also host CPU, memory, disk and IOPS, through a read-only role the stack creates").option("--host-stats-role <arn>", "RDS over PrivateLink: the stack's HostStatsRoleArn output, when not read from AWS (implies --host-stats)").option("--aws-profile <name>", "RDS: the aws CLI profile that reads the instance and its stack, read-only (default: the aws CLI's own)").option("--no-aws", "RDS: do not use the aws CLI on this machine").option("--terraform", "RDS over PrivateLink: write the stack as a Terraform module (./postgresai-privatelink-<instance>/) instead of the CloudFormation link").addHelpText("after", [
48081
49548
  "",
48082
49549
  "Steps (each skipped when already done; safe to re-run): sign in, prepare the database",
48083
49550
  "(an admin URL creates the postgres_ai_mon role; otherwise the SQL is printed), provision",
@@ -48103,7 +49570,22 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
48103
49570
  "at a terminal). Allow it on the database, then re-run with --ip-allowed (at a terminal: Enter).",
48104
49571
  "The IP is held 7 days and stays the box's for its life. If the box still can't connect, it waits",
48105
49572
  "up to 90 minutes, then is removed and the IP kept: allow it and re-run with --ip-allowed.",
48106
- "RDS can also use AWS PrivateLink (no public IP), or monitor with --self-hosted.",
49573
+ "",
49574
+ "Amazon RDS that is not publicly accessible: over AWS PrivateLink (nothing becomes public, no",
49575
+ "port is opened). Run deploy anywhere (where it can't reach the database, it prints the setup SQL",
49576
+ "to run where the database is reachable, and the box checks it). It reads the instance",
49577
+ "with the aws CLI when it can (read-only: the profile it uses is printed; --aws-profile picks one,",
49578
+ "--no-aws skips it), else asks public DNS; --privatelink / --no-privatelink decide instead. Then:",
49579
+ "the price, a CloudFormation link that creates the stack in your AWS account (filled in with what",
49580
+ "AWS said; --terraform writes the same as Terraform), the monitoring role, and the box on AWS in the",
49581
+ "RDS's region. At a terminal deploy waits up to 30 minutes for the stack (any name: it is found by",
49582
+ "its RDS; with several, you pick one), or without AWS asks for its VpceServiceName;",
49583
+ 'elsewhere it stops (exit 3, "step":"privatelink_stack" with cfn_url): create the stack,',
49584
+ "then re-run (with --vpce-service <VpceServiceName> when AWS is not read here). When the URL's",
49585
+ `user can't create the role, or this machine can't reach the database, the SQL is printed ("step":"prepare_db" with sql, nonce,`,
49586
+ "monitoring_password): run it as the master user in that database, then re-run with",
49587
+ "PGAI_MON_PASSWORD and PGAI_MON_NONCE set to those two. Aurora and RDS Proxy: not over PrivateLink.",
49588
+ "Any database can also be monitored from this machine with --self-hosted.",
48107
49589
  "",
48108
49590
  "Billing is per Postgres cluster observed: another database in a cluster the organization already",
48109
49591
  'monitors is included. Once the URL is checked, deploy shows the price (or "free (N of M free slots)"). A billed',
@@ -48136,7 +49618,8 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
48136
49618
  "for another database on a server PostgresAI already monitors for the org, with",
48137
49619
  "sslmode=require or verify-* in the URL: PostgresAI fills in the password it keeps, over TLS only),",
48138
49620
  "PGPASSWORD (the password for a URL without one),",
48139
- "CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET (instead of --clickhouse-key).",
49621
+ "CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET (instead of --clickhouse-key),",
49622
+ "PGAI_MON_NONCE (RDS over PrivateLink: with PGAI_MON_PASSWORD, the printed SQL ran; see above).",
48140
49623
  "",
48141
49624
  "Examples:",
48142
49625
  " pgai mon deploy 'postgresql://postgres:<password>@<host>.pg.clickhouse.cloud:5432/postgres?sslmode=require'",
@@ -48145,7 +49628,9 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
48145
49628
  " pgai mon deploy --supabase-project <name|project-id> --yes --json",
48146
49629
  " pgai mon deploy 'postgresql://postgres@db.<project-ref>.supabase.co:5432/postgres'",
48147
49630
  " pgai mon deploy '<url>' --cloud hetzner --location nbg1",
48148
- " pgai mon deploy '<url>' --self-hosted"
49631
+ " pgai mon deploy '<url>' --self-hosted",
49632
+ " pgai mon deploy 'postgresql://postgres:<password>@<instance>.<id>.<region>.rds.amazonaws.com:5432/app'",
49633
+ " pgai mon deploy '<rds-url>' --yes --json --vpce-service com.amazonaws.vpce.<region>.vpce-svc-<id>"
48149
49634
  ].join(`
48150
49635
  `)).action((urlArg, opts, cmd) => {
48151
49636
  const supabase = providerArg2(opts.provider) === "supabase" || !opts.provider && !!opts.supabaseProject?.trim();
@@ -48177,7 +49662,10 @@ async function cloudInstance(opts, ref, live = false) {
48177
49662
  }
48178
49663
  async function linkedDatabases(opts) {
48179
49664
  const api = cloudApi(opts.debug);
48180
- return Promise.all((await api.list()).map(api.links));
49665
+ return Promise.all((await api.list()).map(async (d) => {
49666
+ const [linked, pl] = await Promise.all([api.links(d), privateLinkOf(d, api.rdsStatus)]);
49667
+ return pl ? { ...linked, privatelink: { region: pl.region, vpce_service_name: pl.vpce_service_name, verified: verifiedWords(pl.verified_status) } } : linked;
49668
+ }));
48181
49669
  }
48182
49670
  var monPollMs = () => {
48183
49671
  const v = Number.parseInt(process.env.PGAI_DEPLOY_POLL_MS ?? "", 10);
@@ -48208,7 +49696,9 @@ withOrgOptions(monInstances.command("watch <id-or-name>")).alias("status").descr
48208
49696
  } finally {
48209
49697
  undetach();
48210
49698
  }
48211
- emitConnect(connectStatus2(await cloudApi(opts.debug).links(row)), opts.json);
49699
+ const pl = await privateLinkOf(row, cloudApi(opts.debug).rdsStatus);
49700
+ const status = connectStatus2(await cloudApi(opts.debug).links(row));
49701
+ emitConnect(pl ? overPrivateLink2(status, privateLinkFailure(pl)) : status, opts.json);
48212
49702
  } catch (err) {
48213
49703
  failCloud(err, opts.json);
48214
49704
  }
@@ -48219,6 +49709,7 @@ withOrgOptions(monInstances.command("delete <id-or-name>")).description("stop mo
48219
49709
  if (!opts.yes && !(interactive(opts.json) && /^y/i.test(await question(`Stop monitoring ${row.name} and delete its monitoring box? (y/N): `)))) {
48220
49710
  return emitConnect({ status: "action_required", provider: row.provider, name: row.name, id: row.id, next: `pgai mon instances delete ${row.id} --yes` }, opts.json);
48221
49711
  }
49712
+ const pl = await privateLinkOf(row, cloudApi(opts.debug).rdsStatus);
48222
49713
  const billing = disconnectBilling(await cloudApi(opts.debug).disconnect(row.id));
48223
49714
  emitConnect({
48224
49715
  status: "deleting",
@@ -48226,7 +49717,7 @@ withOrgOptions(monInstances.command("delete <id-or-name>")).description("stop mo
48226
49717
  name: row.name,
48227
49718
  id: row.id,
48228
49719
  ...billing ? { billing } : {},
48229
- next: clickhouseKeyHeld(row) ? "Delete the ClickHouse Cloud API key you gave us" : "none"
49720
+ next: pl ? stackTeardown(pl, row.id) : clickhouseKeyHeld(row) ? "Delete the ClickHouse Cloud API key you gave us" : "none"
48230
49721
  }, opts.json);
48231
49722
  } catch (err) {
48232
49723
  failCloud(err, opts.json);
@@ -48311,8 +49802,8 @@ mon.command("local-install").description("install local monitoring stack (genera
48311
49802
  process.exitCode = 1;
48312
49803
  return;
48313
49804
  }
48314
- const envFile = path8.resolve(projectDir, ".env");
48315
- const existingEnv = fs10.existsSync(envFile) ? fs10.readFileSync(envFile, "utf8") : "";
49805
+ const envFile = path10.resolve(projectDir, ".env");
49806
+ const existingEnv = fs12.existsSync(envFile) ? fs12.readFileSync(envFile, "utf8") : "";
48316
49807
  const previousTagMatch = existingEnv.match(/^PGAI_TAG=(.+)$/m);
48317
49808
  const previousTag = previousTagMatch ? previousTagMatch[1].trim() : null;
48318
49809
  const imageTag = opts.tag || package_default.version;
@@ -48323,7 +49814,7 @@ mon.command("local-install").description("install local monitoring stack (genera
48323
49814
  return;
48324
49815
  }
48325
49816
  const instanceJobs = instanceJobsRequest.enabled;
48326
- const { content: envContent, preservedKeys } = buildLocalInstallEnv(existingEnv, imageTag, opts.instanceId || process.env.PGAI_INSTANCE_ID || null, path8.resolve(projectDir, ".pgwatch-config"), instanceJobs);
49817
+ const { content: envContent, preservedKeys } = buildLocalInstallEnv(existingEnv, imageTag, opts.instanceId || process.env.PGAI_INSTANCE_ID || null, path10.resolve(projectDir, ".pgwatch-config"), instanceJobs);
48327
49818
  writeEnvFile(envFile, envContent);
48328
49819
  if (preservedKeys.length > 0) {
48329
49820
  console.log(`Preserved existing .env settings: ${preservedKeys.join(", ")}
@@ -48418,7 +49909,7 @@ Use demo mode without API key: postgres-ai mon local-install --demo`);
48418
49909
  # Add your instances using: postgres-ai mon targets add
48419
49910
 
48420
49911
  `;
48421
- fs10.writeFileSync(instancesPath, emptyInstancesContent, "utf8");
49912
+ fs12.writeFileSync(instancesPath, emptyInstancesContent, "utf8");
48422
49913
  console.log(`Instances file: ${instancesPath}`);
48423
49914
  console.log(`Project directory: ${projectDir}
48424
49915
  `);
@@ -48509,17 +50000,17 @@ You can provide either:`);
48509
50000
  }
48510
50001
  } else {
48511
50002
  console.log("Step 2: Demo mode enabled - using included demo PostgreSQL database");
48512
- const currentDir = path8.dirname(fileURLToPath3(import.meta.url));
50003
+ const currentDir = path10.dirname(fileURLToPath3(import.meta.url));
48513
50004
  const demoCandidates = [
48514
- path8.resolve(currentDir, "..", "..", "instances.demo.yml"),
48515
- path8.resolve(currentDir, "..", "..", "..", "instances.demo.yml")
50005
+ path10.resolve(currentDir, "..", "..", "instances.demo.yml"),
50006
+ path10.resolve(currentDir, "..", "..", "..", "instances.demo.yml")
48516
50007
  ];
48517
- const demoSrc = demoCandidates.find((p) => fs10.existsSync(p));
50008
+ const demoSrc = demoCandidates.find((p) => fs12.existsSync(p));
48518
50009
  if (demoSrc) {
48519
- if (fs10.existsSync(instancesPath) && fs10.lstatSync(instancesPath).isDirectory()) {
48520
- fs10.rmSync(instancesPath, { recursive: true, force: true });
50010
+ if (fs12.existsSync(instancesPath) && fs12.lstatSync(instancesPath).isDirectory()) {
50011
+ fs12.rmSync(instancesPath, { recursive: true, force: true });
48521
50012
  }
48522
- fs10.copyFileSync(demoSrc, instancesPath);
50013
+ fs12.copyFileSync(demoSrc, instancesPath);
48523
50014
  console.log(`\u2713 Demo monitoring target configured
48524
50015
  `);
48525
50016
  } else {
@@ -48538,15 +50029,15 @@ Searched: ${demoCandidates.join(", ")}
48538
50029
  console.log(`\u2713 Configuration updated
48539
50030
  `);
48540
50031
  console.log(opts.demo ? "Step 4: Configuring Grafana security..." : "Step 4: Configuring Grafana security...");
48541
- const cfgPath = path8.resolve(projectDir, ".pgwatch-config");
50032
+ const cfgPath = path10.resolve(projectDir, ".pgwatch-config");
48542
50033
  let grafanaPassword = "";
48543
50034
  let vmAuthUsername = "";
48544
50035
  let vmAuthPassword = "";
48545
50036
  try {
48546
- if (fs10.existsSync(cfgPath)) {
48547
- const stats = fs10.statSync(cfgPath);
50037
+ if (fs12.existsSync(cfgPath)) {
50038
+ const stats = fs12.statSync(cfgPath);
48548
50039
  if (!stats.isDirectory()) {
48549
- const content = fs10.readFileSync(cfgPath, "utf8");
50040
+ const content = fs12.readFileSync(cfgPath, "utf8");
48550
50041
  const match = content.match(/^grafana_password=([^\r\n]+)/m);
48551
50042
  if (match) {
48552
50043
  grafanaPassword = match[1].trim();
@@ -48558,22 +50049,22 @@ Searched: ${demoCandidates.join(", ")}
48558
50049
  const { stdout: password } = await execFilePromise("openssl", ["rand", "-base64", "12"]);
48559
50050
  grafanaPassword = password.trim().replace(/\n/g, "");
48560
50051
  let configContent = "";
48561
- if (fs10.existsSync(cfgPath)) {
48562
- const stats = fs10.statSync(cfgPath);
50052
+ if (fs12.existsSync(cfgPath)) {
50053
+ const stats = fs12.statSync(cfgPath);
48563
50054
  if (!stats.isDirectory()) {
48564
- configContent = fs10.readFileSync(cfgPath, "utf8");
50055
+ configContent = fs12.readFileSync(cfgPath, "utf8");
48565
50056
  }
48566
50057
  }
48567
50058
  const lines = configContent.split(/\r?\n/).filter((l) => !/^grafana_password=/.test(l));
48568
50059
  lines.push(`grafana_password=${grafanaPassword}`);
48569
- fs10.writeFileSync(cfgPath, lines.filter(Boolean).join(`
50060
+ fs12.writeFileSync(cfgPath, lines.filter(Boolean).join(`
48570
50061
  `) + `
48571
50062
  `, {
48572
50063
  encoding: "utf8",
48573
50064
  mode: 384
48574
50065
  });
48575
50066
  try {
48576
- fs10.chmodSync(cfgPath, 384);
50067
+ fs12.chmodSync(cfgPath, 384);
48577
50068
  } catch {}
48578
50069
  }
48579
50070
  console.log(`\u2713 Grafana password configured
@@ -48585,9 +50076,9 @@ Searched: ${demoCandidates.join(", ")}
48585
50076
  grafanaPassword = "demo";
48586
50077
  }
48587
50078
  try {
48588
- const envFile = path8.resolve(projectDir, ".env");
48589
- if (fs10.existsSync(envFile)) {
48590
- const envContent = fs10.readFileSync(envFile, "utf8");
50079
+ const envFile = path10.resolve(projectDir, ".env");
50080
+ if (fs12.existsSync(envFile)) {
50081
+ const envContent = fs12.readFileSync(envFile, "utf8");
48591
50082
  const userMatch = envContent.match(/^VM_AUTH_USERNAME=([^\r\n]+)/m);
48592
50083
  const passMatch = envContent.match(/^VM_AUTH_PASSWORD=([^\r\n]+)/m);
48593
50084
  if (userMatch)
@@ -48603,8 +50094,8 @@ Searched: ${demoCandidates.join(", ")}
48603
50094
  vmAuthPassword = vmPass.trim().replace(/\n/g, "");
48604
50095
  }
48605
50096
  let envContent = "";
48606
- if (fs10.existsSync(envFile)) {
48607
- envContent = fs10.readFileSync(envFile, "utf8");
50097
+ if (fs12.existsSync(envFile)) {
50098
+ envContent = fs12.readFileSync(envFile, "utf8");
48608
50099
  }
48609
50100
  const envLines = envContent.split(/\r?\n/).filter((l) => !/^VM_AUTH_USERNAME=/.test(l) && !/^VM_AUTH_PASSWORD=/.test(l)).filter((l, i, arr) => !(i === arr.length - 1 && l === ""));
48610
50101
  envLines.push(`VM_AUTH_USERNAME=${vmAuthUsername}`);
@@ -48900,11 +50391,11 @@ mon.command("config").description("show monitoring services configuration").acti
48900
50391
  console.log(`Project Directory: ${projectDir}`);
48901
50392
  console.log(`Docker Compose File: ${composeFile}`);
48902
50393
  console.log(`Instances File: ${instancesFile}`);
48903
- if (fs10.existsSync(instancesFile) && !fs10.lstatSync(instancesFile).isDirectory()) {
50394
+ if (fs12.existsSync(instancesFile) && !fs12.lstatSync(instancesFile).isDirectory()) {
48904
50395
  console.log(`
48905
50396
  Instances configuration:
48906
50397
  `);
48907
- const text = fs10.readFileSync(instancesFile, "utf8");
50398
+ const text = fs12.readFileSync(instancesFile, "utf8");
48908
50399
  process.stdout.write(text);
48909
50400
  if (!/\n$/.test(text))
48910
50401
  console.log();
@@ -48958,8 +50449,8 @@ mon.command("update").description("update monitoring stack (migrate .env, pull i
48958
50449
  console.log("\u2713 .env is up to date");
48959
50450
  }
48960
50451
  console.log();
48961
- const gitDir = path8.resolve(projectDir, ".git");
48962
- if (fs10.existsSync(gitDir)) {
50452
+ const gitDir = path10.resolve(projectDir, ".git");
50453
+ if (fs12.existsSync(gitDir)) {
48963
50454
  console.log("Fetching latest changes...");
48964
50455
  await execFilePromise("git", ["fetch", "origin"]);
48965
50456
  const { stdout: branch } = await execFilePromise("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
@@ -49206,10 +50697,10 @@ function parseEnvValue(content, key) {
49206
50697
  return quoted ?? raw.replace(/ #.*$/, "").trimEnd();
49207
50698
  }
49208
50699
  function readEnvValue(projectDir, key) {
49209
- const envFile = path8.resolve(projectDir, ".env");
49210
- if (!fs10.existsSync(envFile))
50700
+ const envFile = path10.resolve(projectDir, ".env");
50701
+ if (!fs12.existsSync(envFile))
49211
50702
  return;
49212
- return parseEnvValue(fs10.readFileSync(envFile, "utf8"), key);
50703
+ return parseEnvValue(fs12.readFileSync(envFile, "utf8"), key);
49213
50704
  }
49214
50705
  function supabaseHostMetricsOn(projectDir, env) {
49215
50706
  return /^\s*true\s*$/i.test(env.PGAI_SUPABASE_HOST_METRICS ?? readEnvValue(projectDir, "PGAI_SUPABASE_HOST_METRICS") ?? "");
@@ -49217,8 +50708,8 @@ function supabaseHostMetricsOn(projectDir, env) {
49217
50708
  var SUPABASE_TARGET_NAME_RE = /^[A-Za-z0-9_-]+$/;
49218
50709
  var SUPABASE_TARGET_NAME_ERROR = "Host metrics: a Supabase target name may use only letters, digits, '_' and '-' while PGAI_SUPABASE_HOST_METRICS is true. Choose another name.";
49219
50710
  function setEnvValues(projectDir, values) {
49220
- const envFile = path8.resolve(projectDir, ".env");
49221
- let content = fs10.existsSync(envFile) ? fs10.readFileSync(envFile, "utf8") : "";
50711
+ const envFile = path10.resolve(projectDir, ".env");
50712
+ let content = fs12.existsSync(envFile) ? fs12.readFileSync(envFile, "utf8") : "";
49222
50713
  for (const [key, value] of Object.entries(values)) {
49223
50714
  const line = `^[ \\t]*(?:export[ \\t]+)?${key}=.*(?:\\n|$)`;
49224
50715
  if (value === null)
@@ -49273,9 +50764,9 @@ async function setUpHostMetrics(projectDir, instance, connStr, env, apply) {
49273
50764
  throw new Error(SUPABASE_TARGET_NAME_ERROR);
49274
50765
  const dir = hostMetricsDir2(projectDir);
49275
50766
  const file = `supabase-${name}.yml`;
49276
- const stale = fs10.readdirSync(dir).filter((f) => /^supabase-.*\.yml$/.test(f) && !(on && f === file));
50767
+ const stale = fs12.readdirSync(dir).filter((f) => /^supabase-.*\.yml$/.test(f) && !(on && f === file));
49277
50768
  for (const f of stale)
49278
- fs10.rmSync(path8.join(dir, f), { force: true });
50769
+ fs12.rmSync(path10.join(dir, f), { force: true });
49279
50770
  if (on)
49280
50771
  writeScrapeFile2(dir, file, renderSupabaseScrapeConfig({ projectRef: projectRef.toLowerCase(), cluster, nodeName }));
49281
50772
  else if (stale.length === 0)
@@ -49305,8 +50796,8 @@ async function setUpHostMetrics(projectDir, instance, connStr, env, apply) {
49305
50796
  }
49306
50797
  }
49307
50798
  async function syncVmalert(projectDir, apply, addOnly = false) {
49308
- const dir = path8.join(projectDir, "host-metrics");
49309
- const want = fs10.existsSync(dir) && fs10.readdirSync(dir).some((f) => /^(clickhouse|supabase)-.*\.yml$/.test(f));
50799
+ const dir = path10.join(projectDir, "host-metrics");
50800
+ const want = fs12.existsSync(dir) && fs12.readdirSync(dir).some((f) => /^(clickhouse|supabase)-.*\.yml$/.test(f));
49310
50801
  const current = readEnvValue(projectDir, "COMPOSE_PROFILES") ?? "";
49311
50802
  const exported = process.env.COMPOSE_PROFILES;
49312
50803
  if (want && exported !== undefined && !instanceJobsProfileEnabled(exported, "host-metrics")) {
@@ -49392,7 +50883,7 @@ async function addTarget(file, projectDir, connStr, name, env, { apply = true, v
49392
50883
  var targets = mon.command("targets").description("manage databases to monitor");
49393
50884
  targets.command("list").description("list monitoring target databases").action(async () => {
49394
50885
  const { instancesFile: instancesPath, projectDir } = await resolveOrInitPaths();
49395
- if (!fs10.existsSync(instancesPath) || fs10.lstatSync(instancesPath).isDirectory()) {
50886
+ if (!fs12.existsSync(instancesPath) || fs12.lstatSync(instancesPath).isDirectory()) {
49396
50887
  console.error(`instances.yml not found in ${projectDir}`);
49397
50888
  process.exitCode = 1;
49398
50889
  return;
@@ -49483,7 +50974,7 @@ Environment:
49483
50974
  });
49484
50975
  targets.command("remove <name>").description("remove monitoring target database").action(async (name) => {
49485
50976
  const { instancesFile: file, projectDir } = await resolveOrInitPaths();
49486
- if (!fs10.existsSync(file) || fs10.lstatSync(file).isDirectory()) {
50977
+ if (!fs12.existsSync(file) || fs12.lstatSync(file).isDirectory()) {
49487
50978
  console.error("instances.yml not found");
49488
50979
  process.exitCode = 1;
49489
50980
  return;
@@ -49499,9 +50990,9 @@ targets.command("remove <name>").description("remove monitoring target database"
49499
50990
  console.log(`Monitoring target '${name}' removed`);
49500
50991
  if (removeHostMetrics(projectDir, name) && !await reloadHostMetrics(projectDir, `clickhouse-${name}`))
49501
50992
  process.exitCode = 1;
49502
- const supabaseFile = path8.join(projectDir, "host-metrics", `supabase-${name}.yml`);
49503
- if (SUPABASE_TARGET_NAME_RE.test(name) && fs10.existsSync(supabaseFile)) {
49504
- fs10.rmSync(supabaseFile);
50993
+ const supabaseFile = path10.join(projectDir, "host-metrics", `supabase-${name}.yml`);
50994
+ if (SUPABASE_TARGET_NAME_RE.test(name) && fs12.existsSync(supabaseFile)) {
50995
+ fs12.rmSync(supabaseFile);
49505
50996
  if (!await reloadHostMetrics(projectDir, SUPABASE_JOB))
49506
50997
  process.exitCode = 1;
49507
50998
  }
@@ -49531,7 +51022,7 @@ targets.command("remove <name>").description("remove monitoring target database"
49531
51022
  });
49532
51023
  targets.command("test <name>").description("test monitoring target database connectivity").action(async (name) => {
49533
51024
  const { instancesFile: instancesPath } = await resolveOrInitPaths();
49534
- if (!fs10.existsSync(instancesPath) || fs10.lstatSync(instancesPath).isDirectory()) {
51025
+ if (!fs12.existsSync(instancesPath) || fs12.lstatSync(instancesPath).isDirectory()) {
49535
51026
  console.error("instances.yml not found");
49536
51027
  process.exitCode = 1;
49537
51028
  return;
@@ -49846,15 +51337,15 @@ To authenticate, run: pgai auth`);
49846
51337
  });
49847
51338
  auth.command("remove-key").description("remove API key").action(async () => {
49848
51339
  const newConfigPath = getConfigPath();
49849
- const hasNewConfig = fs10.existsSync(newConfigPath);
51340
+ const hasNewConfig = fs12.existsSync(newConfigPath);
49850
51341
  let legacyPath;
49851
51342
  try {
49852
51343
  const { projectDir } = await resolveOrInitPaths();
49853
- legacyPath = path8.resolve(projectDir, ".pgwatch-config");
51344
+ legacyPath = path10.resolve(projectDir, ".pgwatch-config");
49854
51345
  } catch {
49855
- legacyPath = path8.resolve(process.cwd(), ".pgwatch-config");
51346
+ legacyPath = path10.resolve(process.cwd(), ".pgwatch-config");
49856
51347
  }
49857
- const hasLegacyConfig = fs10.existsSync(legacyPath) && fs10.statSync(legacyPath).isFile();
51348
+ const hasLegacyConfig = fs12.existsSync(legacyPath) && fs12.statSync(legacyPath).isFile();
49858
51349
  if (!hasNewConfig && !hasLegacyConfig) {
49859
51350
  console.log("No API key configured");
49860
51351
  return;
@@ -49864,11 +51355,11 @@ auth.command("remove-key").description("remove API key").action(async () => {
49864
51355
  }
49865
51356
  if (hasLegacyConfig) {
49866
51357
  try {
49867
- const content = fs10.readFileSync(legacyPath, "utf8");
51358
+ const content = fs12.readFileSync(legacyPath, "utf8");
49868
51359
  const filtered = content.split(/\r?\n/).filter((l) => !/^api_key=/.test(l)).join(`
49869
51360
  `).replace(/\n+$/g, `
49870
51361
  `);
49871
- fs10.writeFileSync(legacyPath, filtered, "utf8");
51362
+ fs12.writeFileSync(legacyPath, filtered, "utf8");
49872
51363
  } catch (err) {
49873
51364
  console.warn(`Warning: Could not update legacy config: ${err instanceof Error ? err.message : String(err)}`);
49874
51365
  }
@@ -49879,7 +51370,7 @@ To authenticate again, run: pgai auth`);
49879
51370
  });
49880
51371
  mon.command("generate-grafana-password").description("generate Grafana password for monitoring services").action(async () => {
49881
51372
  const { projectDir } = await resolveOrInitPaths();
49882
- const cfgPath = path8.resolve(projectDir, ".pgwatch-config");
51373
+ const cfgPath = path10.resolve(projectDir, ".pgwatch-config");
49883
51374
  try {
49884
51375
  const { stdout: password } = await execFilePromise("openssl", ["rand", "-base64", "12"]);
49885
51376
  const newPassword = password.trim().replace(/\n/g, "");
@@ -49889,24 +51380,24 @@ mon.command("generate-grafana-password").description("generate Grafana password
49889
51380
  return;
49890
51381
  }
49891
51382
  let configContent = "";
49892
- if (fs10.existsSync(cfgPath)) {
49893
- const stats = fs10.statSync(cfgPath);
51383
+ if (fs12.existsSync(cfgPath)) {
51384
+ const stats = fs12.statSync(cfgPath);
49894
51385
  if (stats.isDirectory()) {
49895
51386
  console.error(".pgwatch-config is a directory, expected a file. Skipping read.");
49896
51387
  } else {
49897
- configContent = fs10.readFileSync(cfgPath, "utf8");
51388
+ configContent = fs12.readFileSync(cfgPath, "utf8");
49898
51389
  }
49899
51390
  }
49900
51391
  const lines = configContent.split(/\r?\n/).filter((l) => !/^grafana_password=/.test(l));
49901
51392
  lines.push(`grafana_password=${newPassword}`);
49902
- fs10.writeFileSync(cfgPath, lines.filter(Boolean).join(`
51393
+ fs12.writeFileSync(cfgPath, lines.filter(Boolean).join(`
49903
51394
  `) + `
49904
51395
  `, {
49905
51396
  encoding: "utf8",
49906
51397
  mode: 384
49907
51398
  });
49908
51399
  try {
49909
- fs10.chmodSync(cfgPath, 384);
51400
+ fs12.chmodSync(cfgPath, 384);
49910
51401
  } catch {}
49911
51402
  console.log("\u2713 New Grafana password generated and saved");
49912
51403
  console.log(`
@@ -49927,19 +51418,19 @@ Note: This command requires 'openssl' to be installed`);
49927
51418
  });
49928
51419
  mon.command("show-grafana-credentials").description("show Grafana credentials for monitoring services").action(async () => {
49929
51420
  const { projectDir } = await resolveOrInitPaths();
49930
- const cfgPath = path8.resolve(projectDir, ".pgwatch-config");
49931
- if (!fs10.existsSync(cfgPath)) {
51421
+ const cfgPath = path10.resolve(projectDir, ".pgwatch-config");
51422
+ if (!fs12.existsSync(cfgPath)) {
49932
51423
  console.error("Configuration file not found. Run 'postgres-ai mon local-install' first.");
49933
51424
  process.exitCode = 1;
49934
51425
  return;
49935
51426
  }
49936
- const stats = fs10.statSync(cfgPath);
51427
+ const stats = fs12.statSync(cfgPath);
49937
51428
  if (stats.isDirectory()) {
49938
51429
  console.error(".pgwatch-config is a directory, expected a file. Cannot read credentials.");
49939
51430
  process.exitCode = 1;
49940
51431
  return;
49941
51432
  }
49942
- const content = fs10.readFileSync(cfgPath, "utf8");
51433
+ const content = fs12.readFileSync(cfgPath, "utf8");
49943
51434
  const lines = content.split(/\r?\n/);
49944
51435
  let password = "";
49945
51436
  for (const line of lines) {
@@ -49959,9 +51450,9 @@ Grafana credentials:`);
49959
51450
  console.log(" URL: http://localhost:3000");
49960
51451
  console.log(" Username: monitor");
49961
51452
  console.log(` Password: ${password}`);
49962
- const envFile = path8.resolve(projectDir, ".env");
49963
- if (fs10.existsSync(envFile)) {
49964
- const envContent = fs10.readFileSync(envFile, "utf8");
51453
+ const envFile = path10.resolve(projectDir, ".env");
51454
+ if (fs12.existsSync(envFile)) {
51455
+ const envContent = fs12.readFileSync(envFile, "utf8");
49965
51456
  const vmUser = envContent.match(/^VM_AUTH_USERNAME=([^\r\n]+)/m);
49966
51457
  const vmPass = envContent.match(/^VM_AUTH_PASSWORD=([^\r\n]+)/m);
49967
51458
  if (vmUser && vmPass) {
@@ -50846,13 +52337,13 @@ withOrgOptions(reports.command("data [reportId]")).description("get checkup repo
50846
52337
  });
50847
52338
  spinner.stop();
50848
52339
  if (opts.output) {
50849
- const dir = path8.resolve(opts.output);
50850
- fs10.mkdirSync(dir, { recursive: true });
52340
+ const dir = path10.resolve(opts.output);
52341
+ fs12.mkdirSync(dir, { recursive: true });
50851
52342
  for (const f of result) {
50852
- const safeName = path8.basename(f.filename);
50853
- const filePath = path8.join(dir, safeName);
52343
+ const safeName = path10.basename(f.filename);
52344
+ const filePath = path10.join(dir, safeName);
50854
52345
  const content = f.type === "json" ? JSON.stringify(tryParseJson(f.data), null, 2) : f.data;
50855
- fs10.writeFileSync(filePath, content, "utf-8");
52346
+ fs12.writeFileSync(filePath, content, "utf-8");
50856
52347
  console.log(filePath);
50857
52348
  }
50858
52349
  } else if (opts.json) {
@@ -51350,29 +52841,29 @@ mcp.command("install [client]").description("install MCP server configuration fo
51350
52841
  let configDir;
51351
52842
  switch (client) {
51352
52843
  case "cursor":
51353
- configPath = path8.join(homeDir, ".cursor", "mcp.json");
51354
- configDir = path8.dirname(configPath);
52844
+ configPath = path10.join(homeDir, ".cursor", "mcp.json");
52845
+ configDir = path10.dirname(configPath);
51355
52846
  break;
51356
52847
  case "windsurf":
51357
- configPath = path8.join(homeDir, ".windsurf", "mcp.json");
51358
- configDir = path8.dirname(configPath);
52848
+ configPath = path10.join(homeDir, ".windsurf", "mcp.json");
52849
+ configDir = path10.dirname(configPath);
51359
52850
  break;
51360
52851
  case "codex":
51361
- configPath = path8.join(homeDir, ".codex", "mcp.json");
51362
- configDir = path8.dirname(configPath);
52852
+ configPath = path10.join(homeDir, ".codex", "mcp.json");
52853
+ configDir = path10.dirname(configPath);
51363
52854
  break;
51364
52855
  default:
51365
52856
  console.error(`Configuration not implemented for: ${client}`);
51366
52857
  process.exitCode = 1;
51367
52858
  return;
51368
52859
  }
51369
- if (!fs10.existsSync(configDir)) {
51370
- fs10.mkdirSync(configDir, { recursive: true });
52860
+ if (!fs12.existsSync(configDir)) {
52861
+ fs12.mkdirSync(configDir, { recursive: true });
51371
52862
  }
51372
52863
  let config = { mcpServers: {} };
51373
- if (fs10.existsSync(configPath)) {
52864
+ if (fs12.existsSync(configPath)) {
51374
52865
  try {
51375
- const content = fs10.readFileSync(configPath, "utf8");
52866
+ const content = fs12.readFileSync(configPath, "utf8");
51376
52867
  config = JSON.parse(content);
51377
52868
  if (!config.mcpServers) {
51378
52869
  config.mcpServers = {};
@@ -51385,7 +52876,7 @@ mcp.command("install [client]").description("install MCP server configuration fo
51385
52876
  command: pgaiPath,
51386
52877
  args: ["mcp", "start"]
51387
52878
  };
51388
- fs10.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf8");
52879
+ fs12.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf8");
51389
52880
  console.log(`\u2713 PostgresAI MCP server configured for ${client}`);
51390
52881
  console.log(` Config file: ${configPath}`);
51391
52882
  console.log("");