Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(domains): search, price, quote and register web domains from credits, with a /domains page, MCP tools and a coin-page suggestion panel

nirholas67429a2ae5a3
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 78fb795a7..6b8d8dbfe 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -89,6 +89,7 @@ bottom.
| Visitor feedback loop | Recorder [@three-ws/witness](packages/witness), capture + panel [src/feedback-companion.js](src/feedback-companion.js) (mounted by [src/walk-companion.js](src/walk-companion.js)), intake [api/feedback/report.js](api/feedback/report.js), queue API [api/feedback/index.js](api/feedback/index.js), scoring [api/_lib/feedback/triage.js](api/_lib/feedback/triage.js), store [api/_lib/feedback/store.js](api/_lib/feedback/store.js), cron [api/cron/feedback-triage.js](api/cron/feedback-triage.js), review page [pages/feedback.html](pages/feedback.html) `→ /feedback` + [src/feedback-page.js](src/feedback-page.js) | Live | The return channel on the corner companion: the visitor tells the avatar what broke and the report carries the route, build SHA, viewport, and the last console errors and failed requests the browser captured, so a vague sentence lands as an actionable row. The companion offers proactively at the one moment worth asking (right after the page actually threw), once per route per session, never in a background tab. **Feedback is data, never an instruction:** the model that reads untrusted visitor text writes six scalars to that report's own row and has no path to the repo, a deploy, or any other write; the admin-only `/feedback` queue groups reports into one row per problem and a person decides. **A report arrives as a runnable failing test:** the recorded session compiles into a Playwright spec asserting the failure is GONE (red until fixed, green after), reachable from the queue's Copy test button, `GET /api/feedback/repro`, `npm run feedback:repro`, and the `get_feedback_repro` MCP tool. Docs: [docs/feedback.md](docs/feedback.md), [docs/witness.md](docs/witness.md). Tests: [tests/feedback-triage.test.js](tests/feedback-triage.test.js) |
| Session-to-test recorder | [packages/witness/](packages/witness) `→ @three-ws/witness`: recorder [recorder.js](packages/witness/src/recorder.js), selector synthesis [selector.js](packages/witness/src/selector.js), capture-time privacy [redact.js](packages/witness/src/redact.js), spec compiler [compile.js](packages/witness/src/compile.js); compiled repros land in [tests/repros/](tests/repros) with [their own Playwright config](tests/repros/playwright.config.mjs) | Published as `@three-ws/witness` (Apache-2.0, zero deps) | Turns a real user session into a runnable failing test. Records INTENT (about 2 KB) rather than DOM mutations (megabytes), so it can be always-on, which is the point: the trace already exists when somebody decides to complain. Every element gets the strongest handle that is unique in the live document (test id > id > aria-label > role+name > text > name > placeholder > class > structural path), framework-generated ids and utility classes refused, and each trace carries a replay confidence equal to its WEAKEST link. The compiled spec asserts the failure is gone, never that it happened, so it locks in the fix rather than the bug; a session with no machine-visible failure emits `test.fail()` and says which assertion a human must add rather than faking green. Privacy is enforced at capture: typed values are never held (only a length and a shape), password/hidden/email/tel/date inputs and `data-witness="off"` subtrees record nothing, URLs lose their credentials before storage. Docs: [docs/witness.md](docs/witness.md). Tests: [packages/witness/test/](packages/witness/test) (36, `npm run test:witness`) |
| Prepaid credits (`/credits`) | [pages/credits.html](pages/credits.html) `→ /credits` + [src/credits.js](src/credits.js), balance/ledger [api/credits/index.js](api/credits/index.js) `→ GET /api/credits`, deposit verifier [api/credits/deposit.js](api/credits/deposit.js) `→ POST /api/credits/deposit` over [api/_lib/credit-deposit.js](api/_lib/credit-deposit.js), ledger engine [api/_lib/credits.js](api/_lib/credits.js), schema [api/_lib/migrations/20260621200000_credits.sql](api/_lib/migrations/20260621200000_credits.sql) | Live | The prepaid balance every metered action on the platform debits. Top up by sending SOL or $THREE to the platform deposit wallet (connect + SIWS-link + sign in the page, or paste a signature you already sent); crediting is server-authoritative and idempotent on the signature, so a signature that is not signed by a wallet linked to the account credits nobody. The page renders the caller's $THREE holder tier from the same `holder` block [api/pricing.js](api/pricing.js) returns ([api/_lib/three-tier.js](api/_lib/three-tier.js)), which is the discount [api/_lib/credits.js](api/_lib/credits.js) already applies to every debit, and lists what credits buy straight from the pricing catalog ([api/_lib/pricing/catalog.js](api/_lib/pricing/catalog.js)). Ledger is keyset-paginated. Docs: [docs/payment-sessions.md](docs/payment-sessions.md). Tests: [tests/credits.test.js](tests/credits.test.js) |
+| Web domains (`/domains`) | [pages/domains.html](pages/domains.html) `→ /domains` + [src/domains/](src/domains), API [api/domains/[action].js](api/domains/%5Baction%5D.js) `→ /api/domains/*`, MCP [api/_mcp/tools/domains.js](api/_mcp/tools/domains.js), service [api/_lib/domains-service.js](api/_lib/domains-service.js) + [api/_lib/cloud-domains.js](api/_lib/cloud-domains.js) + [api/_lib/domain-connect.js](api/_lib/domain-connect.js), renewals [api/cron/domain-renewals.js](api/cron/domain-renewals.js), schema [api/_lib/migrations/20261011000000_web_domains.sql](api/_lib/migrations/20261011000000_web_domains.sql) | Live pending deploy | Search, price, check and register web domains through Google Cloud Domains, paid from credits behind a quote, an explicit confirm and an idempotency key, then serve an agent's public page on the domain. Coin pages carry a live domain suggestion panel. Docs: [docs/domains.md](docs/domains.md). Tests: [tests/domains-service.test.js](tests/domains-service.test.js) |
| Agent payment sessions (`/payments`) | [pages/payments.html](pages/payments.html) `-> /payments`, API [api/pay/session.js](api/pay/session.js) (`POST`/`GET`/`PATCH`/`DELETE /api/pay/session`, `GET /api/pay/session/:id/executions`), spend rail [api/pay/execute.js](api/pay/execute.js) + [api/pay/simulate.js](api/pay/simulate.js), engine [api/_lib/pay/payment-session.js](api/_lib/pay/payment-session.js) + governor [api/_lib/pay/spend-governor.js](api/_lib/pay/spend-governor.js), expiry sweep [api/cron/payment-session-sweep.js](api/cron/payment-session-sweep.js) | Live | The dashboard for platform-managed spend envelopes: fund a budget out of `/credits`, get a one-time `pss_` bearer token, and hand it to an agent that pays x402 endpoints without ever holding a private key (the platform's Solana wallet signs, and the governor enforces budget, host allowlist and per-tx cap atomically on every call). Each card carries the budget bar, remaining balance, expiry countdown, host allowlist, per-tx cap, an inline execution ledger from `GET /api/pay/session/:id/executions` with a Solscan link per settled payment, an env-var-referencing MCP config for [packages/agentcore-payments-mcp](packages/agentcore-payments-mcp), and cancel-and-refund. Press `N` for the create dialog. Docs: [docs/payment-sessions.md](docs/payment-sessions.md), [docs/tutorials/agent-spending-envelope.md](docs/tutorials/agent-spending-envelope.md). Tests: [tests/payment-session-governor.test.js](tests/payment-session-governor.test.js), [tests/payment-session-sweep.test.js](tests/payment-session-sweep.test.js) |
| Skill bundles (seller builder + evidence pricing) | [pages/bundles.html](pages/bundles.html) `→ /bundles`, API [api/agents/[id]/bundles.js](api/agents/%5Bid%5D/bundles.js), arithmetic [api/_lib/bundle-pricing.js](api/_lib/bundle-pricing.js), checkout [api/marketplace/purchase-bundle.js](api/marketplace/purchase-bundle.js) | Live (seller side); no buyer-facing browser view yet | Sell several of one agent's skills as one purchase. The price is derived from the agent's own ledger rather than a rule of thumb: the public `?action=pricing` endpoint finds every buyer who already bought 2+ of the selected skills, suggests the median of what they really paid (`basis: median_basket`), and backtests any candidate price against those same baskets; with no such buyer yet it falls back to 20% off the sum of the parts and labels itself `discount_off_list` so a default is never read as a finding. Every amount is an atomic integer carried as a BigInt end to end, because a 9-decimal mint puts real sums past `Number.MAX_SAFE_INTEGER`. Checkout settles on-chain and writes one `skill_purchases` row per skill (`kind = 'bundle'`, amount 0) so one bundle sale is never counted as N skill sales. Docs: [docs/skill-bundles.md](docs/skill-bundles.md). Tests: [tests/bundle-pricing.test.js](tests/bundle-pricing.test.js), [tests/vercel-agents-subpath-routes.test.js](tests/vercel-agents-subpath-routes.test.js) |
| Marketplace analytics & trial funnel | [pages/marketplace-analytics.html](pages/marketplace-analytics.html) `→ /marketplace/analytics`, renderer [src/marketplace-analytics.js](src/marketplace-analytics.js), backend [api/marketplace/analytics.js](api/marketplace/analytics.js) | Live | Public transparency page for the skill marketplace: paid sales, volume, top skills/agents, and the trial conversion funnel. **Every money aggregate gates on `status = 'confirmed'` alone.** Counting `status IN ('confirmed','trial')` as a sale published 10,454 "sales" and 6.2M $THREE of "volume" on 2026-07-30 against a table holding zero confirmed purchases, because a `trial` row is a free grant whose `amount` is only the list price it would have cost. Free trials now render as their own stat and as a four-stage funnel (granted → used → exhausted → converted), which also names the two shapes that mean a wiring fault rather than weak demand: trials never spent, or trials exhausted with nothing converting. Docs: [docs/marketplace.md](docs/marketplace.md), tutorial [docs/tutorials/sell-a-skill-with-a-trial.md](docs/tutorials/sell-a-skill-with-a-trial.md). Tests: [tests/marketplace-analytics-paid-only.test.js](tests/marketplace-analytics-paid-only.test.js) |
diff --git a/api/_lib/cloud-domains.js b/api/_lib/cloud-domains.js
index f5c284c04..e8ef41b47 100644
--- a/api/_lib/cloud-domains.js
+++ b/api/_lib/cloud-domains.js
@@ -124,15 +124,15 @@ async function call(path, { method = 'GET', body, query } = {}) {
};
// A write is never retried: a register that timed out may still have
// succeeded, and the caller resolves that through the idempotency key.
- // A 4xx other than 429 is the API's answer about this request, so it comes
- // back as a response to map; 429 and 5xx are transient and are retried.
+ // Every 4xx, 429 included, is the API's answer about this request, so it
+ // comes back as a response to map (a quota 429 is not worth retrying inside
+ // the call and must not trip the breaker); only 5xx is transient.
const res = await fetchUpstream(url, init, {
name: 'cloud-domains',
timeoutMs: 20_000,
attempts: method === 'GET' ? 3 : 1,
- okWhen: (r) => r.ok || (r.status >= 400 && r.status < 500 && r.status !== 429),
+ okWhen: (r) => r.status < 500,
}).catch((err) => {
- if (err?.status === 429) throw mapUpstreamError(429, null);
throw new CloudDomainsError(`Cloud Domains is unavailable: ${err?.message || 'network error'}`, { status: 502, code: 'domains_upstream_error' });
});
const text = await res.text();
@@ -195,3 +195,11 @@ export async function configureCustomDns(domainName, nameServers, { validateOnly
},
});
}
+
+/** Switch a registration between AUTOMATIC_RENEWAL and MANUAL_RENEWAL at the registrar. */
+export async function setRenewalMethod(domainName, method) {
+ return call(`${LOCATION}/registrations/${domainName}:configureManagementSettings`, {
+ method: 'POST',
+ body: { managementSettings: { preferredRenewalMethod: method }, updateMask: 'preferredRenewalMethod' },
+ });
+}
diff --git a/api/_lib/domain-connect.js b/api/_lib/domain-connect.js
new file mode 100644
index 000000000..ff21e6252
--- /dev/null
+++ b/api/_lib/domain-connect.js
@@ -0,0 +1,280 @@
+// Connect a purchased domain to an agent's public page.
+//
+// Production is Cloud Run behind one global external load balancer
+// (docs/ops/gcp-production.md, "DNS and TLS"). A domain reaches an agent's page
+// in four steps, each a real API call run as the domains service account:
+//
+// 1. a public Cloud DNS managed zone for the domain, with A records for the
+// apex and www pointing at the load balancer's address;
+// 2. the registration's nameservers switched to that zone (Cloud Domains
+// configureDnsSettings);
+// 3. a Google-managed SSL certificate for the apex and www, attached to the
+// HTTPS proxy (the proxy holds at most 15 certificates);
+// 4. rows in web_domain_hosts. Once the certificate turns ACTIVE the rows go
+// `live` and the host router in server/index.mjs serves the agent page on
+// that host.
+//
+// A domain connects only if the caller owns an active registration for it.
+
+import { createHash } from 'node:crypto';
+
+import { sql } from './db.js';
+import { acquireLock, releaseLock } from './cache.js';
+import { fetchUpstream } from './upstream-fetch.js';
+import { logger } from './usage.js';
+import { GCP_PROJECT, configureCustomDns, getDomainsAccessToken } from './cloud-domains.js';
+import { DomainsError, normalizeDomain } from './domains-service.js';
+
+const log = logger('domain-connect');
+
+export const LB_ADDRESS_NAME = process.env.DOMAINS_LB_ADDRESS_NAME || 'three-ws-ip';
+export const HTTPS_PROXY = process.env.DOMAINS_HTTPS_PROXY || 'three-ws-https-proxy';
+
+/** Google caps one target HTTPS proxy at 15 SSL certificates; one is the platform's own. */
+export const PROXY_CERT_LIMIT = 15;
+
+async function gcp(url, { method = 'GET', body } = {}) {
+ const token = await getDomainsAccessToken();
+ const res = await fetchUpstream(
+ url,
+ {
+ method,
+ headers: { Authorization: `Bearer ${token}`, 'x-goog-user-project': GCP_PROJECT, ...(body ? { 'content-type': 'application/json' } : {}) },
+ ...(body ? { body: JSON.stringify(body) } : {}),
+ },
+ { name: 'gcp-domain-connect', timeoutMs: 30_000, attempts: method === 'GET' ? 3 : 1, okWhen: (r) => r.status < 500 },
+ ).catch((err) => {
+ throw new DomainsError(`Google Cloud is unavailable: ${err?.message || 'network error'}`, { status: 502, code: 'domains_upstream_error' });
+ });
+ const text = await res.text();
+ let json = null;
+ try {
+ json = text ? JSON.parse(text) : null;
+ } catch {
+ json = null;
+ }
+ if (!res.ok) {
+ const message = json?.error?.message || `Google Cloud answered ${res.status}`;
+ const e = new DomainsError(message, { status: res.status === 404 ? 404 : res.status === 409 ? 409 : res.status === 403 ? 503 : 502, code: res.status === 409 ? 'already_exists' : res.status === 404 ? 'not_found' : res.status === 403 ? 'domains_permission_denied' : 'domains_upstream_error' });
+ e.upstreamStatus = res.status;
+ throw e;
+ }
+ return json;
+}
+
+const COMPUTE = `https://compute.googleapis.com/compute/v1/projects/${GCP_PROJECT}/global`;
+const DNS = `https://dns.googleapis.com/dns/v1/projects/${GCP_PROJECT}`;
+
+async function waitGlobalOperation(op) {
+ if (!op?.name || op.status === 'DONE') return op;
+ const done = await gcp(`${COMPUTE}/operations/${op.name}/wait`, { method: 'POST' });
+ if (done?.error?.errors?.length) {
+ throw new DomainsError(done.error.errors.map((e) => e.message).join('; '), { status: 502, code: 'domains_upstream_error' });
+ }
+ return done;
+}
+
+const slug = (domain) => createHash('sha256').update(domain).digest('hex').slice(0, 12);
+const zoneName = (domain) => `tw-${slug(domain)}`;
+const certName = (domain) => `tw-${slug(domain)}`;
+
+async function loadBalancerIp() {
+ const a = await gcp(`${COMPUTE}/addresses/${LB_ADDRESS_NAME}`);
+ if (!a?.address) throw new DomainsError('The load balancer address could not be read.', { status: 502, code: 'domains_upstream_error' });
+ return a.address;
+}
+
+async function ensureZone(domain) {
+ const name = zoneName(domain);
+ try {
+ return await gcp(`${DNS}/managedZones`, {
+ method: 'POST',
+ body: { name, dnsName: `${domain}.`, description: `three.ws agent domain ${domain}`, visibility: 'public' },
+ });
+ } catch (err) {
+ if (err.code !== 'already_exists') throw err;
+ return gcp(`${DNS}/managedZones/${name}`);
+ }
+}
+
+async function ensureRecords(zone, domain, ip) {
+ const additions = [`${domain}.`, `www.${domain}.`].map((name) => ({ name, type: 'A', ttl: 300, rrdatas: [ip] }));
+ const existing = await gcp(`${DNS}/managedZones/${zone}/rrsets?type=A`);
+ const have = new Map((existing?.rrsets || []).map((r) => [r.name, r]));
+ const todo = additions.filter((r) => have.get(r.name)?.rrdatas?.[0] !== ip);
+ if (!todo.length) return;
+ const deletions = todo.filter((r) => have.has(r.name)).map((r) => have.get(r.name));
+ await gcp(`${DNS}/managedZones/${zone}/changes`, { method: 'POST', body: { additions: todo, ...(deletions.length ? { deletions } : {}) } });
+}
+
+async function proxyCertificates() {
+ const proxy = await gcp(`${COMPUTE}/targetHttpsProxies/${HTTPS_PROXY}`);
+ return { proxy, urls: proxy?.sslCertificates || [] };
+}
+
+async function ensureCertificate(domain) {
+ const name = certName(domain);
+ try {
+ await waitGlobalOperation(
+ await gcp(`${COMPUTE}/sslCertificates`, {
+ method: 'POST',
+ body: { name, type: 'MANAGED', managed: { domains: [domain, `www.${domain}`] }, description: `three.ws agent domain ${domain}` },
+ }),
+ );
+ } catch (err) {
+ if (err.code !== 'already_exists') throw err;
+ }
+ const lockKey = `domains:proxy-certs`;
+ if (!(await acquireLock(lockKey, 60))) {
+ throw new DomainsError('Another domain is being attached right now. Retry in a few seconds.', { status: 409, code: 'connect_busy' });
+ }
+ try {
+ const { urls } = await proxyCertificates();
+ const url = `https://www.googleapis.com/compute/v1/projects/${GCP_PROJECT}/global/sslCertificates/${name}`;
+ if (urls.includes(url)) return name;
+ if (urls.length >= PROXY_CERT_LIMIT) {
+ throw new DomainsError(
+ `The load balancer already holds ${urls.length} of its ${PROXY_CERT_LIMIT} certificates. Free one or move to a certificate map before connecting another domain.`,
+ { status: 503, code: 'cert_capacity' },
+ );
+ }
+ await waitGlobalOperation(
+ await gcp(`${COMPUTE}/targetHttpsProxies/${HTTPS_PROXY}/setSslCertificates`, { method: 'POST', body: { sslCertificates: [...urls, url] } }),
+ );
+ return name;
+ } finally {
+ await releaseLock(lockKey);
+ }
+}
+
+async function ownedRegistration(userId, domain) {
+ const [row] = await sql`
+ select id, domain_name from web_domain_registrations
+ where user_id = ${userId} and lower(domain_name) = ${domain} and status = 'active'
+ `;
+ if (!row) {
+ throw new DomainsError(`You have no active registration for ${domain}. Register it first (domain_register), then connect it once its status is active.`, {
+ status: 403,
+ code: 'domain_not_owned',
+ });
+ }
+ return row;
+}
+
+async function ownedAgent(userId, agentId) {
+ const [agent] = await sql`select id, name from agent_identities where id = ${agentId} and user_id = ${userId} and deleted_at is null`;
+ if (!agent) throw new DomainsError('That agent was not found on your account.', { status: 404, code: 'agent_not_found' });
+ return agent;
+}
+
+function publicHost(h) {
+ return { host: h.host, agentId: h.agent_id, status: h.status, certName: h.cert_name, nameServers: h.name_servers, error: h.error, liveAt: h.live_at };
+}
+
+/**
+ * Connect an owned domain to an agent's public page. Idempotent: running it
+ * again for the same domain re-checks each step and returns the current state.
+ */
+export async function connectDomain({ userId, agentId, domain: input }) {
+ const domain = normalizeDomain(input);
+ const reg = await ownedRegistration(userId, domain);
+ await ownedAgent(userId, agentId);
+
+ const [taken] = await sql`select user_id from web_domain_hosts where lower(host) = ${domain} and user_id <> ${userId}`;
+ if (taken) throw new DomainsError('That host is connected to another account.', { status: 409, code: 'host_taken' });
+
+ const ip = await loadBalancerIp();
+ const zone = await ensureZone(domain);
+ await ensureRecords(zone.name, domain, ip);
+ const nameServers = zone.nameServers || [];
+ if (nameServers.length) {
+ try {
+ await configureCustomDns(domain, nameServers);
+ } catch (err) {
+ // The registrar rejects a no-op change; the zone is already the delegation.
+ if (err.code !== 'domains_invalid_request' && err.code !== 'domains_conflict') throw new DomainsError(err.message, { status: err.status, code: err.code });
+ }
+ }
+ const cert = await ensureCertificate(domain);
+
+ const rows = [];
+ for (const host of [domain, `www.${domain}`]) {
+ const [row] = await sql`
+ insert into web_domain_hosts (user_id, agent_id, host, registration_id, status, dns_zone, name_servers, cert_name)
+ values (${userId}, ${agentId}, ${host}, ${reg.id}, 'pending_cert', ${zone.name}, ${nameServers}, ${cert})
+ on conflict (lower(host)) do update
+ set agent_id = excluded.agent_id, dns_zone = excluded.dns_zone, name_servers = excluded.name_servers,
+ cert_name = excluded.cert_name, error = null, updated_at = now(),
+ status = case when web_domain_hosts.status = 'live' then 'live' else 'pending_cert' end
+ returning *
+ `;
+ rows.push(row);
+ }
+ log.info('connected', { domain, agentId, cert });
+ return {
+ domain,
+ agentId,
+ status: rows[0].status,
+ nameServers,
+ dns: { zone: zone.name, records: [`${domain} A ${ip}`, `www.${domain} A ${ip}`] },
+ certificate: cert,
+ hosts: rows.map(publicHost),
+ note: 'DNS and the certificate propagate on their own. The certificate usually turns active within 15 to 60 minutes; poll domain_connect_status until the host is live.',
+ };
+}
+
+/** Poll the certificate and promote hosts to live when it is ACTIVE. */
+export async function connectStatus({ userId, domain: input }) {
+ const domain = normalizeDomain(input);
+ const rows = await sql`select * from web_domain_hosts where user_id = ${userId} and (lower(host) = ${domain} or lower(host) = ${`www.${domain}`}) order by host`;
+ if (!rows.length) throw new DomainsError(`${domain} is not connected to an agent. Run domain_connect first.`, { status: 404, code: 'not_connected' });
+ const cert = rows[0].cert_name;
+ let certState = null;
+ if (cert) {
+ const c = await gcp(`${COMPUTE}/sslCertificates/${cert}`).catch(() => null);
+ certState = { status: c?.managed?.status || 'UNKNOWN', domainStatus: c?.managed?.domainStatus || {} };
+ if (certState.status === 'ACTIVE') {
+ await sql`update web_domain_hosts set status = 'live', live_at = coalesce(live_at, now()), error = null, updated_at = now() where user_id = ${userId} and cert_name = ${cert}`;
+ } else if (certState.status === 'PROVISIONING_FAILED' || certState.status === 'PROVISIONING_FAILED_PERMANENTLY') {
+ await sql`update web_domain_hosts set status = 'failed', error = ${`Certificate provisioning failed: ${JSON.stringify(certState.domainStatus)}`}, updated_at = now() where user_id = ${userId} and cert_name = ${cert} and status <> 'live'`;
+ }
+ }
+ const fresh = await sql`select * from web_domain_hosts where user_id = ${userId} and cert_name = ${cert} order by host`;
+ return {
+ domain,
+ status: fresh.every((h) => h.status === 'live') ? 'live' : fresh[0].status,
+ certificate: certState,
+ hosts: fresh.map(publicHost),
+ url: fresh.every((h) => h.status === 'live') ? `https://${domain}` : null,
+ };
+}
+
+/** The caller's connected hosts. */
+export async function listHosts(userId) {
+ const rows = await sql`select * from web_domain_hosts where user_id = ${userId} order by created_at desc limit 100`;
+ return rows.map(publicHost);
+}
+
+// ── Host routing ────────────────────────────────────────────────────────────
+
+const HOST_TTL_MS = 30_000;
+let hostMemo = { at: 0, map: new Map() };
+
+/**
+ * The agent id a live custom host serves, or null. Held in memory for 30
+ * seconds so the router costs one query per instance per half minute.
+ */
+export async function agentForHost(host) {
+ const h = String(host || '').toLowerCase().split(':')[0];
+ if (!h) return null;
+ if (Date.now() - hostMemo.at > HOST_TTL_MS) {
+ try {
+ const rows = await sql`select lower(host) as host, agent_id from web_domain_hosts where status = 'live'`;
+ hostMemo = { at: Date.now(), map: new Map(rows.map((r) => [r.host, r.agent_id])) };
+ } catch (err) {
+ log.warn('host_table_unavailable', { message: err?.message });
+ hostMemo = { at: Date.now() - HOST_TTL_MS + 5_000, map: hostMemo.map };
+ }
+ }
+ return hostMemo.map.get(h) || null;
+}
diff --git a/api/_lib/domains-service.js b/api/_lib/domains-service.js
new file mode 100644
index 000000000..acd5db88f
--- /dev/null
+++ b/api/_lib/domains-service.js
@@ -0,0 +1,616 @@
+// Web domains: search, check, price and register, on top of Google Cloud Domains.
+//
+// The registrar is cloud-domains.js. This layer adds what the platform needs
+// around it:
+//
+// - the daily API quota as a first-class constraint. Cloud Domains meters
+// "sensitive" requests (search, availability, register) per project per day,
+// so reads are cached, pricing is served from a snapshot (data/domain-tlds.json)
+// that costs no calls, and a 429 on the daily quota trips a flag so callers
+// get a designed answer instead of a stack of failures;
+// - registration as a gated spend: quote (validate-only against the real API),
+// then a confirmed, idempotent register that debits prepaid credits at the
+// exact price Google quoted and refunds them if the registration fails;
+// - a status poll that settles the long-running operation.
+//
+// Registration is one year; the yearly price is also the renewal price.
+// See docs/domains.md.
+
+import { readFileSync } from 'node:fs';
+import { domainToASCII } from 'node:url';
+
+import { sql } from './db.js';
+import { cacheGet, cacheSet } from './cache.js';
+import { debitCredits, refundCredits, getCreditAccount } from './credits.js';
+import { logger } from './usage.js';
+import {
+ CloudDomainsError,
+ configureCustomDns,
+ getOperation,
+ getRegistration,
+ moneyToNumber,
+ numberToMoney,
+ registerDomain,
+ retrieveRegisterParameters,
+ searchDomains,
+ GCP_PROJECT,
+} from './cloud-domains.js';
+
+const log = logger('domains');
+
+export class DomainsError extends Error {
+ constructor(message, { status = 400, code = 'bad_request', detail } = {}) {
+ super(message);
+ this.name = 'DomainsError';
+ this.status = status;
+ this.code = code;
+ if (detail !== undefined) this.detail = detail;
+ }
+}
+
+const FQDN_RE = /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{1,62}$/;
+const LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
+
+// ── Snapshot ─────────────────────────────────────────────────────────────────
+
+let snapshotMemo;
+
+/** The TLD snapshot written by scripts/refresh-domain-tlds.mjs, or an empty one. */
+export function tldSnapshot() {
+ if (snapshotMemo) return snapshotMemo;
+ try {
+ snapshotMemo = JSON.parse(readFileSync(new URL('../../data/domain-tlds.json', import.meta.url), 'utf8'));
+ } catch {
+ snapshotMemo = { generatedAt: null, probed: 0, supported: 0, tlds: [] };
+ }
+ return snapshotMemo;
+}
+
+/**
+ * TLDs and their yearly price from the snapshot. Costs no Cloud Domains calls.
+ * Registration and renewal share one price (registrations are for one year).
+ */
+export function domainPricing({ tld, maxPriceUsd, limit = 200 } = {}) {
+ const snap = tldSnapshot();
+ let rows = snap.tlds;
+ if (tld) {
+ const want = String(tld).toLowerCase().replace(/^\./, '');
+ rows = rows.filter((r) => r.tld === want);
+ }
+ if (maxPriceUsd != null) rows = rows.filter((r) => r.yearlyUsd != null && r.yearlyUsd <= Number(maxPriceUsd));
+ rows = rows
+ .map((r) => ({
+ tld: r.tld,
+ registrationUsd: r.yearlyUsd,
+ renewalUsd: r.yearlyUsd,
+ currency: r.currency,
+ termYears: 1,
+ privacy: r.privacy,
+ notices: r.notices,
+ }))
+ .sort((a, b) => (a.registrationUsd ?? 1e9) - (b.registrationUsd ?? 1e9));
+ return {
+ tlds: rows.slice(0, limit),
+ count: rows.length,
+ snapshotAt: snap.generatedAt,
+ source: 'Google Cloud Domains retrieveRegisterParameters, snapshotted',
+ note: 'Registrations are for one year; the yearly price is also the renewal price. A name can price above its TLD base (premium names), so check or quote a specific name for the exact figure.',
+ };
+}
+
+// ── Quota ────────────────────────────────────────────────────────────────────
+
+const QUOTA_DAILY_LIMIT = Number(process.env.DOMAINS_DAILY_QUOTA || 300);
+
+// Cloud Domains resets its per-day quota at 07:00 UTC (midnight Pacific).
+function quotaDay(now = new Date()) {
+ const t = new Date(now.getTime() - 7 * 3600_000);
+ return t.toISOString().slice(0, 10);
+}
+
+function secondsUntilQuotaReset(now = new Date()) {
+ const next = new Date(now);
+ next.setUTCHours(7, 0, 0, 0);
+ if (next <= now) next.setUTCDate(next.getUTCDate() + 1);
+ return Math.max(60, Math.ceil((next - now) / 1000));
+}
+
+const exhaustedKey = () => `domains:quota-exhausted:${quotaDay()}`;
+const usedKey = () => `domains:quota-used:${quotaDay()}`;
+
+/** How much of the daily Cloud Domains quota this deployment has used, as counted here. */
+export async function quotaStatus() {
+ const [used, exhausted] = await Promise.all([cacheGet(usedKey()), cacheGet(exhaustedKey())]);
+ return {
+ dailyLimit: QUOTA_DAILY_LIMIT,
+ used: Number(used || 0),
+ exhausted: Boolean(exhausted),
+ resetsInSeconds: secondsUntilQuotaReset(),
+ };
+}
+
+async function spendQuota() {
+ const used = Number((await cacheGet(usedKey())) || 0) + 1;
+ await cacheSet(usedKey(), used, 86_400);
+}
+
+function quotaError() {
+ return new DomainsError(
+ 'The registrar\'s daily request quota is used up. Cached answers and TLD pricing still work; live availability returns when the quota resets.',
+ { status: 429, code: 'domains_quota_exhausted', detail: { resetsInSeconds: secondsUntilQuotaReset() } },
+ );
+}
+
+/** Run a live registrar call under the quota flag. */
+async function metered(fn) {
+ if (await cacheGet(exhaustedKey())) throw quotaError();
+ await spendQuota();
+ try {
+ return await fn();
+ } catch (err) {
+ if (err instanceof CloudDomainsError && err.code === 'domains_rate_limited') {
+ // A per-minute 429 clears in a minute; a per-day one does not.
+ if (/per day|daily|PerDay/i.test(String(err.detail || '')) || (await isDailyExhausted())) {
+ await cacheSet(exhaustedKey(), 1, secondsUntilQuotaReset());
+ throw quotaError();
+ }
+ }
+ throw err;
+ }
+}
+
+async function isDailyExhausted() {
+ const used = Number((await cacheGet(usedKey())) || 0);
+ return used >= QUOTA_DAILY_LIMIT * 0.9;
+}
+
+function wrap(err) {
+ if (err instanceof DomainsError) return err;
+ if (err instanceof CloudDomainsError) {
+ return new DomainsError(err.message, { status: err.status, code: err.code, detail: err.detail });
+ }
+ return err;
+}
+
+// ── Names ────────────────────────────────────────────────────────────────────
+
+/** Lowercase, punycode, validate. Throws a 400 for anything that is not a registrable name. */
+export function normalizeDomain(input) {
+ const raw = String(input || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '').replace(/\.$/, '');
+ const ascii = domainToASCII(raw);
+ if (!ascii || !FQDN_RE.test(ascii)) {
+ throw new DomainsError(`"${input}" is not a valid domain name. Use a name like launchpad.app.`, { code: 'invalid_domain' });
+ }
+ return ascii;
+}
+
+/** A search query becomes a label: "My Cool Coin!" -> "my-cool-coin". */
+export function labelFromQuery(input) {
+ const first = String(input || '').trim().toLowerCase().split('.')[0];
+ const label = (domainToASCII(first) || first)
+ .normalize('NFKD')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 63);
+ if (!LABEL_RE.test(label)) {
+ throw new DomainsError('Give a name to search for, like "orbit".', { code: 'invalid_query' });
+ }
+ return label;
+}
+
+const AVAILABILITY = {
+ AVAILABLE: { available: true, reason: null },
+ UNAVAILABLE: { available: false, reason: 'registered', message: 'That name is already registered.' },
+ UNSUPPORTED: { available: false, reason: 'unsupported_tld', message: 'The registrar does not sell that extension.' },
+ AVAILABILITY_UNSPECIFIED: { available: false, reason: 'unknown', message: 'The registrar could not confirm availability.' },
+};
+
+function shape(p, domain) {
+ const a = AVAILABILITY[p?.availability] || AVAILABILITY.AVAILABILITY_UNSPECIFIED;
+ const price = moneyToNumber(p?.yearlyPrice);
+ return {
+ domain: p?.domainName || domain,
+ available: a.available,
+ reason: a.reason,
+ message: a.message || null,
+ registrationUsd: a.available ? price : null,
+ renewalUsd: a.available ? price : null,
+ currency: p?.yearlyPrice?.currencyCode || 'USD',
+ termYears: 1,
+ privacy: p?.supportedPrivacy || [],
+ notices: p?.domainNotices || [],
+ };
+}
+
+const CHECK_TTL = 300;
+const SEARCH_TTL = 3600;
+
+/** Exact availability and price for one name. Cached five minutes. */
+export async function domainCheck(input) {
+ const domain = normalizeDomain(input);
+ const key = `domains:check:${domain}`;
+ const hit = await cacheGet(key);
+ if (hit) return { ...hit, cached: true };
+ try {
+ const p = await metered(() => retrieveRegisterParameters(domain));
+ const out = shape(p, domain);
+ await cacheSet(key, out, CHECK_TTL);
+ return { ...out, cached: false };
+ } catch (err) {
+ const e = wrap(err);
+ // A TLD the registrar does not sell answers 400: a clear unavailable
+ // reason, not an error.
+ if (e.code === 'domains_invalid_request') {
+ return {
+ domain,
+ available: false,
+ reason: 'unsupported_tld',
+ message: 'The registrar does not sell that extension.',
+ registrationUsd: null,
+ renewalUsd: null,
+ currency: 'USD',
+ termYears: 1,
+ privacy: [],
+ notices: [],
+ cached: false,
+ };
+ }
+ throw e;
+ }
+}
+
+/**
+ * Names across TLDs for a query. One registrar search call plus, when `tlds`
+ * is given, an exact check for the name on each of those TLDs (at most 6).
+ */
+export async function domainSearch(query, { tlds = [], limit = 20 } = {}) {
+ const label = labelFromQuery(query);
+ const key = `domains:search:${label}`;
+ let suggestions = await cacheGet(key);
+ let cached = Boolean(suggestions);
+ if (!suggestions) {
+ try {
+ const rows = await metered(() => searchDomains(label));
+ suggestions = rows.map((p) => shape(p, p.domainName));
+ await cacheSet(key, suggestions, SEARCH_TTL);
+ } catch (err) {
+ throw wrap(err);
+ }
+ }
+ const wanted = [...new Set((tlds || []).map((t) => String(t).toLowerCase().replace(/^\./, '')).filter(Boolean))].slice(0, 6);
+ const have = new Set(suggestions.map((s) => s.domain));
+ const extra = [];
+ for (const tld of wanted) {
+ const name = `${label}.${tld}`;
+ if (have.has(name)) continue;
+ extra.push(await domainCheck(name));
+ }
+ const results = [...extra, ...suggestions].slice(0, limit);
+ return {
+ query: label,
+ results,
+ availableCount: results.filter((r) => r.available).length,
+ cached,
+ note: 'Prices are per year and double as the renewal price. Availability is the registrar\'s answer at the time of the call; domain_check or domain_register_quote confirms it before any spend.',
+ };
+}
+
+/** Project-name suggestions for a launch: the search plus the cheapest available picks. */
+export async function suggestForProject(name, { limit = 12 } = {}) {
+ const out = await domainSearch(name, { tlds: ['com', 'xyz', 'app', 'io'], limit: 40 });
+ const picks = out.results.filter((r) => r.available).sort((a, b) => a.registrationUsd - b.registrationUsd).slice(0, limit);
+ return { ...out, results: picks, taken: out.results.filter((r) => !r.available).map((r) => r.domain).slice(0, 8) };
+}
+
+// ── Contact ──────────────────────────────────────────────────────────────────
+
+const CONTACT_FIELDS = ['name', 'email', 'phone', 'address_lines', 'city', 'region', 'postal_code', 'country'];
+
+/** Validate the registrant contact the owner supplied. */
+export function normalizeContact(c) {
+ if (!c || typeof c !== 'object') {
+ throw new DomainsError('A registrant contact is required: name, email, phone, address, city, postal_code and country.', { code: 'contact_required' });
+ }
+ const out = {
+ name: String(c.name || '').trim(),
+ email: String(c.email || '').trim(),
+ phone: String(c.phone || '').replace(/[^\d+]/g, ''),
+ address_lines: (Array.isArray(c.address_lines) ? c.address_lines : [c.address_line1, c.address_line2])
+ .map((s) => String(s || '').trim())
+ .filter(Boolean)
+ .slice(0, 3),
+ city: String(c.city || '').trim(),
+ region: String(c.region || '').trim(),
+ postal_code: String(c.postal_code || '').trim(),
+ country: String(c.country || '').trim().toUpperCase(),
+ };
+ const missing = [];
+ if (!out.name) missing.push('name');
+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(out.email)) missing.push('email');
+ if (!/^\+\d{6,15}$/.test(out.phone)) missing.push('phone (international format, like +14155550123)');
+ if (!out.address_lines.length) missing.push('address_lines');
+ if (!out.city) missing.push('city');
+ if (!out.postal_code) missing.push('postal_code');
+ if (!/^[A-Z]{2}$/.test(out.country)) missing.push('country (two-letter code)');
+ if (missing.length) {
+ throw new DomainsError(`The registrant contact is incomplete: ${missing.join(', ')}.`, { code: 'contact_invalid', detail: { missing } });
+ }
+ return out;
+}
+
+function googleContact(c) {
+ return {
+ email: c.email,
+ phoneNumber: c.phone,
+ postalAddress: {
+ regionCode: c.country,
+ postalCode: c.postal_code,
+ administrativeArea: c.region || undefined,
+ locality: c.city,
+ addressLines: c.address_lines,
+ recipients: [c.name],
+ },
+ };
+}
+
+function registrationBody(domain, contact, { autoRenew, privacy }) {
+ const gc = googleContact(contact);
+ return {
+ domainName: domain,
+ labels: { source: 'three-ws' },
+ contactSettings: { privacy, registrantContact: gc, adminContact: gc, technicalContact: gc },
+ managementSettings: { preferredRenewalMethod: autoRenew ? 'AUTOMATIC_RENEWAL' : 'MANUAL_RENEWAL' },
+ };
+}
+
+const PRIVACY_PREFERENCE = ['REDACTED_CONTACT_DATA', 'PRIVATE_CONTACT_DATA', 'PUBLIC_CONTACT_DATA'];
+
+function pickPrivacy(supported, wanted) {
+ if (wanted && supported.includes(wanted)) return wanted;
+ return PRIVACY_PREFERENCE.find((p) => supported.includes(p)) || supported[0] || 'PUBLIC_CONTACT_DATA';
+}
+
+// ── Quote and register ───────────────────────────────────────────────────────
+
+/**
+ * Price a registration against the real API without registering anything.
+ * Runs retrieveRegisterParameters for the exact price and notices, then
+ * register with validateOnly:true, which checks availability, price and the
+ * contact server-side. Also reads the caller's credit balance.
+ */
+export async function quoteRegistration({ userId, domain: input, contact, autoRenew = false, privacy }) {
+ const domain = normalizeDomain(input);
+ const c = normalizeContact(contact);
+ let params;
+ try {
+ params = await metered(() => retrieveRegisterParameters(domain));
+ } catch (err) {
+ const e = wrap(err);
+ if (e.code === 'domains_invalid_request') {
+ throw new DomainsError('The registrar does not sell that extension.', { code: 'unsupported_tld' });
+ }
+ throw e;
+ }
+ const s = shape(params, domain);
+ if (!s.available) {
+ throw new DomainsError(s.message || 'That name is not available.', { status: 409, code: `domain_${s.reason || 'unavailable'}` });
+ }
+ const chosenPrivacy = pickPrivacy(s.privacy, privacy);
+ try {
+ await metered(() =>
+ registerDomain({
+ registration: registrationBody(domain, c, { autoRenew, privacy: chosenPrivacy }),
+ yearlyPrice: params.yearlyPrice,
+ domainNotices: s.notices,
+ validateOnly: true,
+ }),
+ );
+ } catch (err) {
+ const e = wrap(err);
+ if (e.code === 'domains_invalid_request') {
+ throw new DomainsError(`The registrar rejected this registration: ${e.message}`, { code: 'registration_invalid', detail: e.detail });
+ }
+ throw e;
+ }
+ const account = await getCreditAccount(userId);
+ const priceUsd = s.registrationUsd;
+ return {
+ domain,
+ priceUsd,
+ currency: s.currency,
+ termYears: 1,
+ renewalUsd: priceUsd,
+ autoRenew: Boolean(autoRenew),
+ autoRenewNote: autoRenew
+ ? `Renews on its own each year for ${priceUsd} ${s.currency}, taken from your credits 14 days before expiry. If credits are short it switches to manual renewal and the name can lapse.`
+ : 'Expires after one year unless renewed.',
+ privacy: chosenPrivacy,
+ notices: s.notices,
+ contact: c,
+ payment: { method: 'credits', balanceUsd: account.balanceUsd, sufficient: account.balanceUsd >= priceUsd },
+ validated: true,
+ note: 'Validated against the registrar with validate-only; nothing was registered or charged.',
+ };
+}
+
+function publicRegistration(r) {
+ return {
+ id: r.id,
+ domain: r.domain_name,
+ status: r.status,
+ priceUsd: Number(r.price_usd),
+ currency: r.currency,
+ termYears: r.years,
+ autoRenew: r.auto_renew,
+ privacy: r.privacy,
+ agentId: r.agent_id,
+ error: r.error,
+ createdAt: r.created_at,
+ registeredAt: r.registered_at,
+ expiresAt: r.expires_at,
+ renewalNote: r.renewal_note,
+ };
+}
+
+/**
+ * Register a domain. The caller has already shown the owner the quote and got
+ * an explicit yes (`confirm`), and sends `expectedPriceUsd` (the quoted price)
+ * and a stable idempotency key.
+ *
+ * The live price is re-read first; if it moved from what the owner approved the
+ * call stops with `price_changed` and charges nothing. Credits are debited for
+ * the exact yearly price before the registrar call and refunded if the
+ * registrar refuses or the operation fails.
+ */
+export async function registerWithCredits({ userId, domain: input, contact, autoRenew = false, privacy, expectedPriceUsd, confirm, idempotencyKey, agentId = null, source = null }) {
+ if (confirm !== true) {
+ throw new DomainsError('Registration spends money. Show the owner the quote and send confirm: true only after they approve it.', { code: 'confirmation_required' });
+ }
+ if (!idempotencyKey || String(idempotencyKey).length < 8 || String(idempotencyKey).length > 128) {
+ throw new DomainsError('idempotency_key is required (8 to 128 characters) so a retry never registers twice.', { code: 'idempotency_key_required' });
+ }
+ const domain = normalizeDomain(input);
+ const c = normalizeContact(contact);
+
+ const [existing] = await sql`select * from web_domain_registrations where user_id = ${userId} and idempotency_key = ${idempotencyKey}`;
+ if (existing) {
+ if (existing.domain_name !== domain) {
+ throw new DomainsError('That idempotency_key was already used for a different domain.', { status: 409, code: 'idempotency_key_reused' });
+ }
+ return { replayed: true, registration: publicRegistration(existing) };
+ }
+
+ let params;
+ try {
+ params = await metered(() => retrieveRegisterParameters(domain));
+ } catch (err) {
+ throw wrap(err);
+ }
+ const s = shape(params, domain);
+ if (!s.available) throw new DomainsError(s.message || 'That name is not available.', { status: 409, code: `domain_${s.reason || 'unavailable'}` });
+ const priceUsd = s.registrationUsd;
+ if (Number(expectedPriceUsd) !== priceUsd) {
+ throw new DomainsError(`The price changed from ${expectedPriceUsd} to ${priceUsd} ${s.currency}. Nothing was charged. Request a new quote.`, {
+ status: 409,
+ code: 'price_changed',
+ detail: { priceUsd, expectedPriceUsd: Number(expectedPriceUsd) },
+ });
+ }
+ const chosenPrivacy = pickPrivacy(s.privacy, privacy);
+
+ let row;
+ try {
+ [row] = await sql`
+ insert into web_domain_registrations
+ (user_id, agent_id, domain_name, idempotency_key, price_usd, currency, auto_renew, privacy, status, contact, source)
+ values (${userId}, ${agentId}, ${domain}, ${idempotencyKey}, ${priceUsd}, ${s.currency}, ${Boolean(autoRenew)}, ${chosenPrivacy}, 'registering', ${JSON.stringify(c)}::jsonb, ${source})
+ returning *
+ `;
+ } catch (err) {
+ if (err?.code === '23505') {
+ throw new DomainsError('That domain is already being registered or is registered.', { status: 409, code: 'domain_taken' });
+ }
+ throw err;
+ }
+
+ let debit;
+ try {
+ debit = await debitCredits({
+ userId,
+ amountUsd: priceUsd,
+ action: 'domain_registration',
+ refType: 'web_domain_registration',
+ refId: row.id,
+ idempotencyKey: `domain:debit:${row.id}`,
+ meta: { domain },
+ });
+ } catch (err) {
+ await sql`update web_domain_registrations set status = 'failed', error = ${err.message}, updated_at = now() where id = ${row.id}`;
+ if (err.code === 'insufficient_credits') {
+ throw new DomainsError(`Not enough credits: this domain costs ${priceUsd} USD and the balance is ${err.available_usd}. Top up at /credits and retry with a new idempotency key.`, {
+ status: 402,
+ code: 'insufficient_credits',
+ detail: { requiredUsd: priceUsd, availableUsd: err.available_usd },
+ });
+ }
+ throw err;
+ }
+ await sql`update web_domain_registrations set debit_ledger_id = ${debit.ledgerId} where id = ${row.id}`;
+
+ try {
+ const op = await metered(() =>
+ registerDomain({
+ registration: registrationBody(domain, c, { autoRenew, privacy: chosenPrivacy }),
+ yearlyPrice: params.yearlyPrice || numberToMoney(priceUsd, s.currency),
+ domainNotices: s.notices,
+ }),
+ );
+ const [done] = await sql`
+ update web_domain_registrations set operation_name = ${op?.name || null}, updated_at = now()
+ where id = ${row.id} returning *
+ `;
+ log.info('register_submitted', { domain, id: row.id, op: op?.name });
+ return { replayed: false, registration: publicRegistration(done) };
+ } catch (err) {
+ const e = wrap(err);
+ await failRegistration(row.id, userId, priceUsd, e.message);
+ throw e;
+ }
+}
+
+async function failRegistration(id, userId, priceUsd, message) {
+ const refund = await refundCredits({
+ userId,
+ amountUsd: priceUsd,
+ action: 'domain_registration',
+ refType: 'web_domain_registration',
+ refId: id,
+ idempotencyKey: `domain:refund:${id}`,
+ meta: { reason: message },
+ });
+ await sql`
+ update web_domain_registrations
+ set status = 'failed', error = ${message}, refund_ledger_id = ${refund.ledgerId}, updated_at = now()
+ where id = ${id}
+ `;
+}
+
+/**
+ * Settle a registration by polling its long-running operation. Idempotent:
+ * an active or failed registration returns as stored.
+ */
+export async function registrationStatus({ userId, id, domain }) {
+ const [row] = id
+ ? await sql`select * from web_domain_registrations where id = ${id} and user_id = ${userId}`
+ : await sql`select * from web_domain_registrations where lower(domain_name) = ${normalizeDomain(domain)} and user_id = ${userId} order by created_at desc limit 1`;
+ if (!row) throw new DomainsError('No registration found for that id or domain on this account.', { status: 404, code: 'not_found' });
+ if (row.status !== 'registering' || !row.operation_name) return publicRegistration(row);
+
+ let op;
+ try {
+ op = await getOperation(row.operation_name);
+ } catch (err) {
+ throw wrap(err);
+ }
+ if (!op?.done) return { ...publicRegistration(row), operationDone: false };
+ if (op.error) {
+ await failRegistration(row.id, userId, Number(row.price_usd), op.error.message || 'The registrar could not complete the registration.');
+ } else {
+ const reg = await getRegistration(row.domain_name).catch(() => null);
+ await sql`
+ update web_domain_registrations
+ set status = 'active', registered_at = now(), expires_at = ${reg?.expireTime || null}, updated_at = now()
+ where id = ${row.id}
+ `;
+ }
+ const [fresh] = await sql`select * from web_domain_registrations where id = ${row.id}`;
+ return { ...publicRegistration(fresh), operationDone: true };
+}
+
+/** The caller's registrations, newest first. */
+export async function listRegistrations(userId, { limit = 50 } = {}) {
+ const rows = await sql`select * from web_domain_registrations where user_id = ${userId} order by created_at desc limit ${limit}`;
+ return rows.map(publicRegistration);
+}
+
+export { GCP_PROJECT, configureCustomDns };
diff --git a/api/_lib/migrations/20261011000000_web_domains.sql b/api/_lib/migrations/20261011000000_web_domains.sql
new file mode 100644
index 000000000..32db4b3a5
--- /dev/null
+++ b/api/_lib/migrations/20261011000000_web_domains.sql
@@ -0,0 +1,97 @@
+-- Web domains: registrations an agent's owner buys through Google Cloud Domains
+-- and the hosts that serve an agent's public page.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261011000000_web_domains.sql
+-- Idempotent.
+--
+-- web_domain_registrations
+-- One purchase. `idempotency_key` is unique per user, so a retried
+-- domain_register returns the row it already produced and never charges twice.
+-- price_usd the exact yearly price Cloud Domains quoted, which is what
+-- credits were debited. Registration is for one year, and the
+-- same price is the renewal price.
+-- status quoted -> registering -> active, or failed (credits refunded).
+-- operation_name the long-running operation to poll.
+-- debit_ledger_id / refund_ledger_id the credit_ledger rows for the charge and
+-- for the refund of a registration that did not complete.
+-- expires_at end of the paid year. With auto_renew on, the renewal cron
+-- debits the same yearly price from credits 14 days before it;
+-- if credits are short it switches the registration to manual
+-- renewal at the registrar and writes `renewal_note`.
+-- contact the registrant contact the owner supplied, kept only so the
+-- status read can show what the domain was registered to. It is
+-- never returned to another account.
+--
+-- web_domain_hosts
+-- A host (apex or subdomain) that serves an agent's public page. The Express
+-- host router reads only rows whose status is `live`.
+-- status pending_dns -> pending_cert -> live, or failed.
+-- cert_name the Google-managed ssl-certificate attached to the load
+-- balancer's HTTPS proxy for this host.
+--
+-- Service layer: api/_lib/domains-service.js, api/_lib/domain-connect.js.
+-- Routes: /api/domains/*. MCP tools: api/_mcp/tools/domains.js.
+-- Doc: docs/domains.md.
+
+create table if not exists web_domain_registrations (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid references agent_identities(id) on delete set null,
+ domain_name text not null,
+ idempotency_key text not null,
+ price_usd numeric(12, 2) not null,
+ currency text not null default 'USD',
+ years integer not null default 1,
+ auto_renew boolean not null default true,
+ privacy text not null default 'REDACTED_CONTACT_DATA',
+ status text not null default 'registering',
+ operation_name text,
+ error text,
+ contact jsonb not null default '{}'::jsonb,
+ debit_ledger_id uuid,
+ refund_ledger_id uuid,
+ source text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ registered_at timestamptz,
+ expires_at timestamptz,
+ renewal_note text,
+ constraint web_domain_registrations_status_chk
+ check (status in ('registering', 'active', 'failed'))
+);
+
+create unique index if not exists web_domain_registrations_user_key
+ on web_domain_registrations (user_id, idempotency_key);
+
+-- A name can be registered once. A failed attempt does not hold the name.
+create unique index if not exists web_domain_registrations_live_name
+ on web_domain_registrations (lower(domain_name)) where status <> 'failed';
+
+create index if not exists web_domain_registrations_user_created
+ on web_domain_registrations (user_id, created_at desc);
+
+create table if not exists web_domain_hosts (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ host text not null,
+ registration_id uuid references web_domain_registrations(id) on delete set null,
+ status text not null default 'pending_dns',
+ dns_zone text,
+ name_servers text[] not null default '{}',
+ cert_name text,
+ error text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ live_at timestamptz,
+ constraint web_domain_hosts_status_chk
+ check (status in ('pending_dns', 'pending_cert', 'live', 'failed'))
+);
+
+create unique index if not exists web_domain_hosts_host
+ on web_domain_hosts (lower(host));
+
+create index if not exists web_domain_hosts_user
+ on web_domain_hosts (user_id, created_at desc);
+
+create index if not exists web_domain_hosts_agent
+ on web_domain_hosts (agent_id);
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 479108fc0..43cc7bfbe 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -957,6 +957,11 @@ export const limits = {
window: '1 h',
critical: true,
}).limit('global'),
+ // Web domains. Every uncached search or check is a metered Cloud Domains
+ // request (300 a day per project), so a caller gets a small hourly budget and
+ // a registration attempt, which spends credits, a smaller one.
+ domainsLookup: (key) => getLimiter('domains:lookup', { limit: 40, window: '1 h' }).limit(key),
+ domainsRegister: (key) => getLimiter('domains:register', { limit: 10, window: '1 h', critical: true }).limit(key),
// Free generation lane (NVIDIA NIM TRELLIS draft). No Replicate/vendor spend,
// so it gets a much higher per-principal ceiling than the paid bucket and is
// NON-critical: a Redis outage must never deny a zero-cost generation (fail
diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.js
index 986f1fbf0..a272e5240 100644
--- a/api/_mcp/catalog.js
+++ b/api/_mcp/catalog.js
@@ -28,6 +28,9 @@ import { toolDefs as customSkillDefs } from './tools/custom-skills.js';
import { toolDefs as resourceDefs } from './tools/resources.js';
const baseDefs = [
+import { toolDefs as mailDefs } from './tools/mail.js';
+import { toolDefs as whitelistDefs } from './tools/whitelist.js';
+import { toolDefs as domainDefs } from './tools/domains.js';
...libraryDefs,
...avatarDefs,
...embedDefs,
@@ -55,6 +58,9 @@ const baseDefs = [
// Free, public entry point — listed first so discovery clients see it up top.
// priceFor annotates the per-call price of the paid tools in the overview.
+ ...mailDefs,
+ ...whitelistDefs,
+ ...domainDefs,
// Annotations: a static, local overview built at module load — read-only,
// deterministic, closed-world (destructiveHint is explicit because the MCP
// spec defaults it to true when omitted).
diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.js
index 9577d84e2..aa6bcc407 100644
--- a/api/_mcp/dispatch.js
+++ b/api/_mcp/dispatch.js
@@ -41,6 +41,13 @@ const PUBLIC_TOOLS = new Set([
'paired_markets',
'paired_coins',
'paired_coin',
+ // Web-domain lookups: the registrar's public availability and prices, no
+ // caller data. Per-caller hourly limits protect the registrar's daily quota.
+ 'domain_search',
+ 'domain_check',
+ 'domain_pricing',
+ // The launch-lane comparison is live platform config, no caller data.
+ 'launch_lanes',
]);
export function isPublicTool(name) {
diff --git a/api/_mcp/tools/domains.js b/api/_mcp/tools/domains.js
new file mode 100644
index 000000000..104094ebb
--- /dev/null
+++ b/api/_mcp/tools/domains.js
@@ -0,0 +1,289 @@
+// Web-domain MCP tools: search, check, price, register and connect.
+//
+// The backend is Google Cloud Domains (api/_lib/cloud-domains.js) behind
+// api/_lib/domains-service.js, the same library the REST API uses
+// (api/domains/[action].js), so quotas, caching, the credit debit and the audit
+// trail are identical on both surfaces.
+//
+// domain_register_quote is the preview: it runs the registrar's own validation
+// (register with validateOnly) and the policy layer stamps a quote_id on its
+// result. domain_register spends credits, so it needs that quote_id, the same
+// domain/term/privacy, expected_price_usd, an idempotency_key and
+// confirm_spend: true. See docs/domains.md.
+
+import { connectDomain, connectStatus } from '../../_lib/domain-connect.js';
+import {
+ DomainsError,
+ domainCheck,
+ domainPricing,
+ domainSearch,
+ quoteRegistration,
+ registerWithCredits,
+ registrationStatus,
+} from '../../_lib/domains-service.js';
+import { limits } from '../../_lib/rate-limit.js';
+
+const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
+const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
+const MONEY = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true };
+
+const CONTACT = {
+ type: 'object',
+ description: 'The registrant. Used for the registrant, admin and technical contacts. Hidden from the public WHOIS where the TLD allows it.',
+ properties: {
+ name: { type: 'string', maxLength: 120 },
+ email: { type: 'string', maxLength: 254 },
+ phone: { type: 'string', description: 'International format, like +14155550123.' },
+ address_lines: { type: 'array', items: { type: 'string', maxLength: 120 }, minItems: 1, maxItems: 3 },
+ city: { type: 'string', maxLength: 80 },
+ region: { type: 'string', maxLength: 80, description: 'State or province, where the country has one.' },
+ postal_code: { type: 'string', maxLength: 20 },
+ country: { type: 'string', minLength: 2, maxLength: 2, description: 'Two-letter country code, like US.' },
+ },
+ required: ['name', 'email', 'phone', 'address_lines', 'city', 'postal_code', 'country'],
+ additionalProperties: false,
+};
+
+const REGISTER_PROPS = {
+ domain: { type: 'string', maxLength: 253, description: 'Fully-qualified name, like orbit.app.' },
+ contact: CONTACT,
+ auto_renew: { type: 'boolean', default: false, description: 'Renew each year from credits, 14 days before expiry. Off: the name expires after the one-year term.' },
+ privacy: { type: 'string', enum: ['REDACTED_CONTACT_DATA', 'PRIVATE_CONTACT_DATA', 'PUBLIC_CONTACT_DATA'], description: 'WHOIS privacy. Defaults to the most private mode the TLD supports.' },
+ agent_id: { type: 'string', format: 'uuid', description: 'Agent this domain is for (from list_my_agents). Optional.' },
+};
+
+function ok(structured, text) {
+ return { content: [{ type: 'text', text: text || JSON.stringify(structured, null, 2) }], structuredContent: structured };
+}
+
+function failure(e) {
+ if (e instanceof DomainsError || (e?.status && e.status < 500 && e?.code)) {
+ const structured = { error: e.code || 'bad_request', message: e.message, ...(e.detail ? { detail: e.detail } : {}) };
+ return { content: [{ type: 'text', text: `Error (${structured.error}): ${e.message}` }], structuredContent: structured, isError: true };
+ }
+ throw e;
+}
+
+function needsAccount() {
+ return {
+ content: [{ type: 'text', text: 'Connect a three.ws account (OAuth or API key) to register a domain.' }],
+ structuredContent: { error: 'unauthorized' },
+ isError: true,
+ };
+}
+
+// Every uncached lookup is a metered registrar request, so callers (anonymous
+// ones included) get an hourly budget.
+async function lookupLimited(auth) {
+ const rl = await limits.domainsLookup(String(auth?.userId || auth?.rateKey || 'anon'));
+ if (rl.success) return null;
+ return failure(new DomainsError('Domain lookups are limited per hour. Try again shortly.', { status: 429, code: 'rate_limited', detail: { retryAfterSeconds: Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000)) } }));
+}
+
+export const toolDefs = [
+ {
+ name: 'domain_search',
+ title: 'Search web domains',
+ group: 'domains',
+ annotations: READ,
+ description:
+ 'Suggest web domains for a name across TLDs, live from Google Cloud Domains. Each result gives availability, the yearly registration price and the renewal price (registrations are one year, so they are the same figure). Pass tlds to also check the exact name on those extensions (up to 6). Searches are cached and the registrar allows a limited number of live requests a day.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', minLength: 1, maxLength: 80, description: 'A name or idea, like "orbit" or "Orbit Labs".' },
+ tlds: { type: 'array', items: { type: 'string', maxLength: 24 }, maxItems: 6, description: 'Extensions to check the exact name on, like ["com","xyz"].' },
+ limit: { type: 'integer', minimum: 1, maximum: 40, default: 20 },
+ },
+ required: ['query'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ const limited = await lookupLimited(auth);
+ if (limited) return limited;
+ try {
+ return ok(await domainSearch(args.query, { tlds: args.tlds, limit: args.limit ?? 20 }));
+ } catch (e) {
+ return failure(e);
+ }
+ },
+ },
+ {
+ name: 'domain_check',
+ title: 'Check one web domain',
+ group: 'domains',
+ annotations: READ,
+ description:
+ 'One answer for one fully-qualified name: available or not, with a clear reason when it is not (already registered, or an extension the registrar does not sell), the exact yearly registration and renewal price, the WHOIS privacy modes the TLD supports and any notices a registration must acknowledge.',
+ inputSchema: {
+ type: 'object',
+ properties: { domain: { type: 'string', maxLength: 253, description: 'Fully-qualified name, like orbit.app.' } },
+ required: ['domain'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ const limited = await lookupLimited(auth);
+ if (limited) return limited;
+ try {
+ return ok(await domainCheck(args.domain));
+ } catch (e) {
+ return failure(e);
+ }
+ },
+ },
+ {
+ name: 'domain_pricing',
+ title: 'List domain TLD pricing',
+ group: 'domains',
+ annotations: READ,
+ description:
+ 'The extensions Google Cloud Domains sells with their yearly registration and renewal price, cheapest first. Served from a snapshot of the registrar (so it costs no live requests); the response says when it was taken. Filter with tld or max_price_usd. A specific name can price above its extension (premium names), so use domain_check for the exact figure.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tld: { type: 'string', maxLength: 24, description: 'One extension, like "app".' },
+ max_price_usd: { type: 'number', minimum: 0 },
+ limit: { type: 'integer', minimum: 1, maximum: 300, default: 100 },
+ },
+ additionalProperties: false,
+ },
+ async handler(args) {
+ return ok(domainPricing({ tld: args.tld, maxPriceUsd: args.max_price_usd, limit: args.limit ?? 100 }));
+ },
+ },
+ {
+ name: 'domain_register_quote',
+ title: 'Quote a domain registration',
+ group: 'domains',
+ tier: 'write',
+ scope: 'wallet:read',
+ annotations: WRITE,
+ description:
+ 'Price a domain registration without buying it: the exact yearly price, the one-year term, the renewal terms for your auto_renew choice, the privacy mode, the notices that apply and your credit balance. It validates the registration with the registrar (validate-only), so a bad contact or an unavailable name fails here, before any spend. Show the result to the owner; domain_register needs the quote_id this returns.',
+ inputSchema: {
+ type: 'object',
+ properties: { ...REGISTER_PROPS },
+ required: ['domain', 'contact'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ if (!auth?.userId) return needsAccount();
+ const limited = await lookupLimited(auth);
+ if (limited) return limited;
+ try {
+ return ok(await quoteRegistration({ userId: auth.userId, domain: args.domain, contact: args.contact, autoRenew: args.auto_renew, privacy: args.privacy }));
+ } catch (e) {
+ return failure(e);
+ }
+ },
+ },
+ {
+ name: 'domain_register',
+ title: 'Register a domain (spends credits)',
+ group: 'domains',
+ tier: 'financial',
+ confirmFlag: 'confirm_spend',
+ previewTool: 'domain_register_quote',
+ scope: 'wallet:write',
+ annotations: MONEY,
+ description:
+ 'Register the domain domain_register_quote priced, paying the exact yearly price from your prepaid credits (refunded in full if the registrar fails). Requires the quote_id from the quote, the same domain/auto_renew/privacy, expected_price_usd from the quote, an idempotency_key (a retry returns the same registration, never a second charge) and confirm_spend: true, which you may only send after the owner explicitly approved the quote. Registration is asynchronous: poll domain_status until it is active.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ ...REGISTER_PROPS,
+ expected_price_usd: { type: 'number', minimum: 0, description: 'priceUsd from the quote. If the live price differs, nothing is charged.' },
+ idempotency_key: { type: 'string', minLength: 8, maxLength: 128, description: 'A unique key for this purchase. Reuse it on a retry.' },
+ quote_id: { type: 'string', description: 'From domain_register_quote.' },
+ confirm_spend: { type: 'boolean', description: 'Must be true, and only after the owner said yes to the quote.' },
+ },
+ required: ['domain', 'contact', 'expected_price_usd', 'idempotency_key', 'quote_id', 'confirm_spend'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ if (!auth?.userId) return needsAccount();
+ const rl = await limits.domainsRegister(String(auth.userId));
+ if (!rl.success) return failure(new DomainsError('Too many registration attempts this hour.', { status: 429, code: 'rate_limited' }));
+ try {
+ const out = await registerWithCredits({
+ userId: auth.userId,
+ domain: args.domain,
+ contact: args.contact,
+ autoRenew: args.auto_renew,
+ privacy: args.privacy,
+ expectedPriceUsd: args.expected_price_usd,
+ confirm: true,
+ idempotencyKey: args.idempotency_key,
+ agentId: args.agent_id || null,
+ source: 'mcp',
+ });
+ return ok(out);
+ } catch (e) {
+ return failure(e);
+ }
+ },
+ },
+ {
+ name: 'domain_status',
+ title: 'Poll a domain registration',
+ group: 'domains',
+ scope: 'wallet:read',
+ annotations: READ,
+ description: 'The state of a registration you started: registering, active (with its expiry) or failed (credits refunded). Polls the registrar and settles the registration. Pass the registration id from domain_register or the domain name.',
+ inputSchema: {
+ type: 'object',
+ properties: { id: { type: 'string', format: 'uuid' }, domain: { type: 'string', maxLength: 253 } },
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ if (!auth?.userId) return needsAccount();
+ if (!args.id && !args.domain) return failure(new DomainsError('Pass the registration id or the domain.', { code: 'bad_request' }));
+ try {
+ return ok(await registrationStatus({ userId: auth.userId, id: args.id, domain: args.domain }));
+ } catch (e) {
+ return failure(e);
+ }
+ },
+ },
+ {
+ name: 'domain_connect',
+ title: 'Connect a domain to an agent page',
+ group: 'domains',
+ tier: 'write',
+ scope: 'agents:write',
+ annotations: WRITE,
+ description:
+ "Serve an agent's public page on a domain you registered here: creates the DNS zone and records, points the registration at it, issues a managed HTTPS certificate on the load balancer and routes the host to the agent. Idempotent. The domain must be an active registration on your account. Follow with domain_connect_status until the host is live.",
+ inputSchema: {
+ type: 'object',
+ properties: { domain: { type: 'string', maxLength: 253 }, agent_id: { type: 'string', format: 'uuid', description: 'Agent UUID (from list_my_agents).' } },
+ required: ['domain', 'agent_id'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ if (!auth?.userId) return needsAccount();
+ try {
+ return ok(await connectDomain({ userId: auth.userId, agentId: args.agent_id, domain: args.domain }));
+ } catch (e) {
+ return failure(e);
+ }
+ },
+ },
+ {
+ name: 'domain_connect_status',
+ title: 'Check a connected domain',
+ group: 'domains',
+ scope: 'agents:read',
+ annotations: READ,
+ description: 'Whether a connected domain is live: the certificate state, the DNS nameservers in use and the URL once HTTPS is serving. Promotes the host to live when its certificate turns active.',
+ inputSchema: { type: 'object', properties: { domain: { type: 'string', maxLength: 253 } }, required: ['domain'], additionalProperties: false },
+ async handler(args, auth) {
+ if (!auth?.userId) return needsAccount();
+ try {
+ return ok(await connectStatus({ userId: auth.userId, domain: args.domain }));
+ } catch (e) {
+ return failure(e);
+ }
+ },
+ },
+];
diff --git a/api/cron/domain-renewals.js b/api/cron/domain-renewals.js
new file mode 100644
index 000000000..8254afd85
--- /dev/null
+++ b/api/cron/domain-renewals.js
@@ -0,0 +1,87 @@
+// GET/POST /api/cron/domain-renewals - pay for upcoming domain renewals from credits.
+//
+// Google bills the GCP project when an AUTOMATIC_RENEWAL registration renews, so
+// the owner's credits must cover that charge first. Daily, for every active
+// registration with auto_renew whose paid year ends within RENEW_WINDOW_DAYS:
+// 1. read the registrar's expireTime, so a registration that already renewed
+// advances its own expires_at and is not charged twice;
+// 2. debit the yearly price from the owner's credits, idempotent per term
+// (key domain:renew:<id>:<expiry date>), and note it on the row;
+// 3. if credits are short, switch the registration to MANUAL_RENEWAL at the
+// registrar, turn auto_renew off, and write renewal_note, so the platform
+// never absorbs a renewal nobody paid for. The owner re-enables it on /domains.
+//
+// Auth: the shared cron gate (api/_lib/cron-auth.js).
+
+import { sql } from '../_lib/db.js';
+import { debitCredits } from '../_lib/credits.js';
+import { getRegistration, setRenewalMethod } from '../_lib/cloud-domains.js';
+import { cors, json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { logger } from '../_lib/usage.js';
+
+export const maxDuration = 60;
+
+const RENEW_WINDOW_DAYS = 14;
+const BATCH_LIMIT = 50;
+const log = logger('domain-renewals');
+
+async function renewOne(row) {
+ const reg = await getRegistration(row.domain_name);
+ const registrarExpiry = reg?.expireTime ? new Date(reg.expireTime) : null;
+ if (registrarExpiry && registrarExpiry.getTime() > new Date(row.expires_at).getTime() + 30 * 86400_000) {
+ await sql`update web_domain_registrations set expires_at = ${registrarExpiry.toISOString()}, renewal_note = null, updated_at = now() where id = ${row.id}`;
+ return 'already_renewed';
+ }
+ const term = new Date(row.expires_at).toISOString().slice(0, 10);
+ try {
+ await debitCredits({
+ userId: row.user_id,
+ amountUsd: Number(row.price_usd),
+ action: 'domain_renewal',
+ refType: 'web_domain_registration',
+ refId: row.id,
+ idempotencyKey: `domain:renew:${row.id}:${term}`,
+ meta: { domain: row.domain_name, term },
+ });
+ } catch (err) {
+ if (err.code !== 'insufficient_credits') throw err;
+ await setRenewalMethod(row.domain_name, 'MANUAL_RENEWAL');
+ await sql`
+ update web_domain_registrations
+ set auto_renew = false, updated_at = now(),
+ renewal_note = ${`Credits were short for the ${term} renewal ($${Number(row.price_usd).toFixed(2)}), so auto-renew was switched off and the name will lapse unless renewed.`}
+ where id = ${row.id}`;
+ return 'switched_to_manual';
+ }
+ await sql`
+ update web_domain_registrations
+ set renewal_note = ${`Renewal for the term ending ${term} was paid from credits ($${Number(row.price_usd).toFixed(2)}).`}, updated_at = now()
+ where id = ${row.id}`;
+ return 'paid';
+}
+
+export default wrapCron(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const due = await sql`
+ select * from web_domain_registrations
+ where status = 'active' and auto_renew
+ and expires_at is not null
+ and expires_at < now() + make_interval(days => ${RENEW_WINDOW_DAYS})
+ order by expires_at
+ limit ${BATCH_LIMIT}`;
+
+ const counts = { paid: 0, switched_to_manual: 0, already_renewed: 0, failed: 0 };
+ for (const row of due) {
+ try {
+ counts[await renewOne(row)]++;
+ } catch (err) {
+ counts.failed++;
+ log.error('renewal_failed', { domain: row.domain_name, error: err.message });
+ }
+ }
+ return json(res, 200, { checked: due.length, ...counts });
+});
diff --git a/api/domains/[action].js b/api/domains/[action].js
new file mode 100644
index 000000000..656d16ce8
--- /dev/null
+++ b/api/domains/[action].js
@@ -0,0 +1,125 @@
+/**
+ * Web domains API: search, check, price, register and connect.
+ * Backed by Google Cloud Domains (api/_lib/cloud-domains.js). Doc: docs/domains.md.
+ *
+ * Public reads (rate limited per caller, because each uncached call is a
+ * metered registrar request):
+ * GET /api/domains/search?q=orbit&tlds=com,xyz suggestions with prices
+ * GET /api/domains/check?domain=orbit.app one answer + reason
+ * GET /api/domains/pricing?tld=app TLD price list (snapshot)
+ * GET /api/domains/suggest?name=Orbit cheapest available names for a project
+ * GET /api/domains/quota registrar quota status
+ *
+ * Signed in:
+ * POST /api/domains/quote validate-only quote for a registration
+ * POST /api/domains/register spend credits, register (confirm + idempotency_key)
+ * GET /api/domains/status?id=|domain= settle and read a registration
+ * GET /api/domains/list your registrations and connected hosts
+ * POST /api/domains/connect serve an agent page on a registered domain
+ * GET /api/domains/connect-status?domain=
+ */
+
+import { authenticateBearer, extractBearer, getSessionUser, assertBearerMaySpend } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { connectDomain, connectStatus, listHosts } from '../_lib/domain-connect.js';
+import {
+ DomainsError,
+ domainCheck,
+ domainPricing,
+ domainSearch,
+ listRegistrations,
+ quoteRegistration,
+ quotaStatus,
+ registerWithCredits,
+ registrationStatus,
+ suggestForProject,
+} from '../_lib/domains-service.js';
+import { cors, error, json, method, rateLimited, readJson, respondError, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+
+async function resolveUser(req, res) {
+ const session = await getSessionUser(req, res);
+ if (session) return { user: session, bearer: null };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) {
+ const [u] = await sql`select id, wallet_address from users where id = ${bearer.userId} and deleted_at is null limit 1`;
+ return { user: u || null, bearer };
+ }
+ return { user: null, bearer: null };
+}
+
+function fail(res, err) {
+ if (err instanceof DomainsError || (err?.status && err?.code)) {
+ return respondError(res, err.status || 500, err.code || 'domains_error', err, err.detail ? { detail: err.detail } : {});
+ }
+ throw err;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const action = url.searchParams.get('action') || url.pathname.split('/').filter(Boolean)[2];
+ const q = url.searchParams;
+
+ const publicReads = new Set(['search', 'check', 'pricing', 'suggest', 'quota']);
+ try {
+ if (publicReads.has(action)) {
+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'use GET');
+ if (action === 'pricing') {
+ return json(res, 200, domainPricing({ tld: q.get('tld') || undefined, maxPriceUsd: q.get('max_price_usd') ?? undefined, limit: Number(q.get('limit')) || 200 }), { 'cache-control': 'public, max-age=300' });
+ }
+ if (action === 'quota') return json(res, 200, await quotaStatus());
+ const rl = await limits.domainsLookup(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'Domain lookups are limited per hour.');
+ if (action === 'check') return json(res, 200, await domainCheck(q.get('domain')));
+ if (action === 'suggest') return json(res, 200, await suggestForProject(q.get('name')));
+ const tlds = (q.get('tlds') || '').split(',').map((s) => s.trim()).filter(Boolean);
+ return json(res, 200, await domainSearch(q.get('q'), { tlds, limit: Number(q.get('limit')) || 20 }));
+ }
+
+ const { user, bearer } = await resolveUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'Sign in to register or connect a domain.');
+
+ if (action === 'status') return json(res, 200, await registrationStatus({ userId: user.id, id: q.get('id') || undefined, domain: q.get('domain') || undefined }));
+ if (action === 'list') {
+ const [registrations, hosts] = await Promise.all([listRegistrations(user.id), listHosts(user.id)]);
+ return json(res, 200, { registrations, hosts });
+ }
+ if (action === 'connect-status') return json(res, 200, await connectStatus({ userId: user.id, domain: q.get('domain') }));
+
+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'use POST');
+ const body = (await readJson(req).catch(() => null)) || {};
+
+ if (action === 'quote') {
+ const rl = await limits.domainsLookup(String(user.id));
+ if (!rl.success) return rateLimited(res, rl, 'Domain lookups are limited per hour.');
+ return json(res, 200, await quoteRegistration({ userId: user.id, domain: body.domain, contact: body.contact, autoRenew: body.auto_renew, privacy: body.privacy }));
+ }
+ if (action === 'register') {
+ assertBearerMaySpend(bearer, req);
+ const rl = await limits.domainsRegister(String(user.id));
+ if (!rl.success) return rateLimited(res, rl, 'Too many registration attempts this hour.');
+ const out = await registerWithCredits({
+ userId: user.id,
+ domain: body.domain,
+ contact: body.contact,
+ autoRenew: body.auto_renew,
+ privacy: body.privacy,
+ expectedPriceUsd: body.expected_price_usd,
+ confirm: body.confirm,
+ idempotencyKey: body.idempotency_key,
+ agentId: body.agent_id || null,
+ source: body.source === 'coin' ? 'coin' : 'api',
+ });
+ return json(res, out.replayed ? 200 : 202, out);
+ }
+ if (action === 'connect') {
+ return json(res, 200, await connectDomain({ userId: user.id, agentId: body.agent_id, domain: body.domain }));
+ }
+ return error(res, 404, 'not_found', `Unknown domains action "${action}".`);
+ } catch (err) {
+ return fail(res, err);
+ }
+});
diff --git a/data/changelog.json b/data/changelog.json
index 3b30ef1e6..37fcc45d1 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -29476,6 +29476,30 @@
"feature"
],
"link": "/teams"
+ },
+ {
+ "date": "2026-10-10",
+ "title": "Agents can find and register web domains",
+ "summary": "Search any name across popular extensions with live availability and the exact yearly price, check a single name, and register it from your credits after a quote and an explicit yes. Coin pages now suggest available domains for the project name, and a registered domain can serve your agent's public page. Registration is for one year, renews at the same price, and has no markup.",
+ "tags": ["feature"],
+ "link": "/domains"
+ },
+ {
+ "date": "2026-10-10",
+ "title": "Token ceilings, a spend page, USDC deposits and a way out of the free tier",
+ "summary": "Every agent can now carry hourly, daily and per-run token ceilings next to its dollar caps. A ceiling is checked before the model is called; hitting one pauses the agent, tells you, and gives you Resume and Extend once. The new /spend page shows what each agent spends by day, by model and by tool, projects the month end, and alerts at 50, 80 and 100 percent of any cap. Credits can be topped up with USDC at a fixed rate alongside SOL and $THREE, the deposit page lists every accepted asset and its rate from live config, and paying in $THREE earns whatever bonus the owner has set. When the free tier runs out, the error now carries your choices: wait for the reset, top up, bring your own key, or resend the same request with paid_fallback: true to bill it to credits in one step.",
+ "tags": ["feature"],
+ "link": "/spend"
+ },
+ {
+ "date": "2026-10-10",
+ "title": "Agents get their own email inbox",
+ "summary": "Every agent can now have an email address on agents.three.ws, with an inbox right on its profile (the Mail button). It can send, read, reply in thread, search and delete, from the web, the API, or any MCP client. Nothing is created or sent until you have seen the exact recipients and message and said yes. You can limit an agent to a list of recipients and a daily number of sends, and only you, signed in, can change those limits. Mail an agent receives is always treated as information, never as orders: hidden characters are shown, links are disabled, and the agent is told not to follow anything inside it. Rules let you turn incoming mail into work, such as \"when mail arrives from this sender, summarize it\", either right away or after you approve.",
+ "tags": [
+ "feature",
+ "security"
+ ],
+ "link": "/agent-mail"
}
]
}
diff --git a/data/pages.json b/data/pages.json
index 99b3c9116..e9c11dc47 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -35,7 +35,7 @@
},
{
"title": "Economy and $THREE",
- "paths": ["/three-token", "/three", "/three-launchpad", "/launch", "/launches", "/pay", "/credits", "/pricing", "/economy", "/analytics"]
+ "paths": ["/three-token", "/three", "/three-launchpad", "/launch", "/launches", "/pay", "/credits", "/domains", "/pricing", "/economy", "/analytics"]
},
{
"title": "Learn",
@@ -2919,6 +2919,14 @@
"title": "Account",
"description": "Sign-in, dashboard, billing.",
"pages": [
+ {
+ "path": "/domains",
+ "title": "Domains",
+ "description": "Search live registrar availability, see the exact yearly price, register a web domain from credits and serve an agent's public page on it.",
+ "priority": 0.6,
+ "changefreq": "weekly",
+ "added": "2026-10-10"
+ },
{
"path": "/credits",
"title": "Credits",
@@ -3504,6 +3512,14 @@
"changefreq": "monthly",
"added": "2026-10-09"
},
+ {
+ "path": "/docs/domains",
+ "title": "Docs · Web Domains",
+ "description": "Search, price, check and register web domains from an agent or the dashboard through Google Cloud Domains, paid from credits behind a quote and an explicit confirm, with the daily registrar quota, one-year terms, auto-renew and connecting a domain to an agent's public page.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-10-10"
+ },
{
"path": "/docs/materialize",
"title": "Docs · Materialize: turn a generation into a real object",
diff --git a/docs/domains.md b/docs/domains.md
new file mode 100644
index 000000000..046bbeee3
--- /dev/null
+++ b/docs/domains.md
@@ -0,0 +1,86 @@
+# Web domains
+
+Agents can search, price, check and register real web domains, and serve their public page on one. The registrar is Google Cloud Domains. Registration spends money, so it is a gated action on every surface.
+
+- Page: [/domains](https://three.ws/domains), source [pages/domains.html](../pages/domains.html) and [src/domains/](../src/domains/)
+- REST: `/api/domains/*`, handler [api/domains/[action].js](../api/domains/%5Baction%5D.js)
+- MCP tools: [api/_mcp/tools/domains.js](../api/_mcp/tools/domains.js)
+- Service layer: [api/_lib/domains-service.js](../api/_lib/domains-service.js), registrar client [api/_lib/cloud-domains.js](../api/_lib/cloud-domains.js), connect flow [api/_lib/domain-connect.js](../api/_lib/domain-connect.js)
+- Renewals: [api/cron/domain-renewals.js](../api/cron/domain-renewals.js)
+
+## What it does and does not do
+
+| Fact | Detail |
+|---|---|
+| Term | One year. Cloud Domains registers for one year only. |
+| Renewal price | Same as the yearly registration price. |
+| Payment | Prepaid credits ([/credits](https://three.ws/credits)), debited at the exact price Google quotes. No markup. |
+| Premium names | A name can price above its TLD base. `domain_check` and `domain_register_quote` return the exact figure for that name. |
+| Supported TLDs | Cloud Domains has no list endpoint. [data/domain-tlds.json](../data/domain-tlds.json) is a snapshot probed by `node scripts/refresh-domain-tlds.mjs` (run with `DOMAINS_ACCESS_TOKEN=$(gcloud auth print-access-token)`). An unsupported TLD answers `UNSUPPORTED`. |
+| Registrar quota | 300 sensitive requests per day per project, 100 per minute, 20 registrations per project. |
+
+### The daily quota
+
+Search, availability and register count against the 300/day quota, which resets about 07:00 UTC. The platform treats it as a first-class limit: pricing is served from the snapshot and costs no calls, search is cached 1 hour and check 5 minutes, public lookups are limited to 40 per hour per caller, and a 429 from Google trips a flag so callers get a clear `domains_quota_exhausted` answer with `resetsInSeconds` instead of repeated failures. `GET /api/domains/quota` reports the state. A raise to 3000/day was requested (quota preference `domains-sensitive-per-day`).
+
+## MCP tools
+
+| Tool | Tier | Purpose |
+|---|---|---|
+| `domain_search` | read | Names across TLDs with availability and registration and renewal price. |
+| `domain_check` | read | One name: available or not, with the reason (`registered`, `unsupported_tld`, `unknown`). |
+| `domain_pricing` | read | TLD price list from the snapshot, filter by `tld` or `max_price_usd`. |
+| `domain_register_quote` | write | Validate-only register against the real API: exact price, term, renewal, privacy, notices, credit balance. Returns the `quote_id`. |
+| `domain_register` | financial | Spend credits and register. Needs `quote_id`, `confirm_spend: true`, `expected_price_usd`, `idempotency_key`. |
+| `domain_status` | read | Settle and read a registration. |
+| `domain_connect` | write | Serve an agent's public page on a registered domain. |
+| `domain_connect_status` | read | DNS, certificate and live state of a connected host. |
+
+The flow an agent follows:
+
+1. `domain_check` or `domain_search` to find a name.
+2. `domain_register_quote` with the registrant contact and `auto_renew`. Show the owner the price, the one-year term, the renewal note and the balance.
+3. Only after the owner says yes, `domain_register` with the same arguments, the `quote_id`, `confirm_spend: true`, the quoted price as `expected_price_usd`, and a fresh `idempotency_key`.
+4. Poll `domain_status` until `active`. A failed registration refunds the credits automatically.
+
+`domain_register` re-reads the live price and refuses with `price_changed` if it moved since the quote. A retry with the same `idempotency_key` returns the same registration and never charges twice.
+
+## REST
+
+```bash
+curl 'https://three.ws/api/domains/check?domain=orbit.app'
+curl 'https://three.ws/api/domains/search?q=orbit&tlds=com,xyz,app'
+curl 'https://three.ws/api/domains/pricing?max_price_usd=15'
+curl 'https://three.ws/api/domains/suggest?name=Orbit'
+```
+
+Signed-in: `POST /api/domains/quote`, `POST /api/domains/register`, `GET /api/domains/status`, `GET /api/domains/list`, `POST /api/domains/connect`, `GET /api/domains/connect-status`. Registration through an API key needs the key's spend scope.
+
+## Registrant contact
+
+Required: `name`, `email`, `phone` (international, `+14155550123`), `address_lines`, `city`, `postal_code`, `country` (two letters), optionally `region`. It is sent to the registrar, stored on the registration so the owner can see what it was registered to, and never returned to another account. Privacy defaults to hidden WHOIS where the TLD supports it.
+
+## Auto-renew
+
+If `auto_renew` is on, Google renews the name each year and bills the GCP project. To keep that from falling on the platform, [api/cron/domain-renewals.js](../api/cron/domain-renewals.js) runs daily: 14 days before expiry it debits the renewal price from the owner's credits (idempotent per term). If credits are short it switches the registration to manual renewal at the registrar, turns `auto_renew` off and writes `renewal_note`, so the name can lapse but nobody is charged unpaid. Keep credits topped up if you want a name to renew.
+
+## From a coin page
+
+Coin pages ([/coin/:id](https://three.ws/coin/bitcoin)) show a "Domains" panel: live-availability suggestions for the project name across `.com`, `.xyz`, `.app` and `.io`, each linking to `/domains?domain=...` to register.
+
+## Connect a domain to an agent
+
+`domain_connect` / `POST /api/domains/connect` runs the Cloud Run plus load balancer procedure in [docs/ops/gcp-production.md](ops/gcp-production.md#web-domains):
+
+1. Create a Cloud DNS zone for the domain and A records for the apex and `www` at the load balancer address.
+2. Point the registration's nameservers at the zone.
+3. Create a Google-managed certificate and attach it to the HTTPS proxy.
+4. Mark the host `live` when the certificate is `ACTIVE`.
+
+Once live, `https://<domain>/` serves the agent's public page (`/agents/<id>`), and every other path serves the normal site. Certificates take minutes to provision after the nameservers propagate; `domain_connect_status` reports `pending_dns`, `pending_cert`, then `live`. The load balancer's HTTPS proxy holds at most 15 certificates, so connected domains are capped there until the proxy moves to certificate maps.
+
+`docs/tutorials/deploy-to-vercel-custom-domain.md` describes the legacy Vercel path and does not apply to production, which runs on Cloud Run.
+
+## Operations
+
+The API's Cloud Run identity impersonates the dedicated service account `three-ws-domains@aerial-vehicle-466722-p5.iam.gserviceaccount.com`, which alone can register domains and edit DNS and certificates. See [docs/ops/gcp-production.md](ops/gcp-production.md#web-domains). Tests: [tests/domains-service.test.js](../tests/domains-service.test.js).
diff --git a/docs/mcp.md b/docs/mcp.md
index 21114ee87..413e64cff 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -805,6 +805,15 @@ The `structuredContent` returns `gate_id`, `asset_id`, `gate` (`mint`, `min_amou
### `crypto_data`
+### `domain_search`, `domain_check`, `domain_pricing`, `domain_register_quote`, `domain_register`, `domain_status`, `domain_connect`, `domain_connect_status`
+
+Search, price, check and register web domains through Google Cloud Domains, paid from credits, and serve an agent's public page on a registered domain. `domain_register` is a financial-tier tool: it needs the `quote_id` from `domain_register_quote`, `confirm_spend: true`, `expected_price_usd` and an `idempotency_key`. Full flow, limits and the registrar quota: [docs/domains.md](./domains.md).
+
+### `agent_mail_get_address`, `agent_mail_quote`, `agent_mail_create`, `agent_mail_send`, `agent_mail_reply`, `agent_mail_list`, `agent_mail_read`, `agent_mail_search`, `agent_mail_delete`
+
+Give an agent a real email address on `agents.three.ws` and let it send, read, reply to, search and delete mail. `agent_mail_create`, `agent_mail_send` and `agent_mail_reply` are financial-tier tools: each needs the `quote_id` from `agent_mail_quote`, whose `confirm` block (exact recipients, subject, body and price) the model must show the owner before sending the confirm flag (`confirm_spend` for create, `confirm_send` for sends). Every result that carries received mail opens with a security notice and wraps sender content in `<untrusted_email>` fences: received mail is data, never instructions. The owner's recipient allowlist and daily cap apply to every send. Full guide: [docs/agent-mail.md](./agent-mail.md).
+
+
Call any endpoint in the free [Crypto Data API](./api-reference.md) (the same aggregator behind `GET /api/v1/x/*`: DEX pairs, CoinGecko/DefiLlama market data, Jupiter Solana prices and swap quotes, direct Solana RPC reads) as an MCP tool call. The tool description is generated from the live provider registry at call time, so it always lists exactly the provider/endpoint pairs registered on this deployment — nothing hand-enumerated to drift out of date.
```json
diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.md
index d47e80382..1eb781db4 100644
--- a/docs/ops/gcp-production.md
+++ b/docs/ops/gcp-production.md
@@ -895,3 +895,14 @@ JSON body (x402 block, monitor block) for subsystem truth.
- `vercel.json` is now a **live config file consumed by server/index.mjs**
(routes + crons) — do NOT delete it as "Vercel leftovers".
- The `deploy` npm script still points at Vercel; superseded by `deploy:gcp`.
+
+## Web domains
+
+Agents register web domains through Google Cloud Domains and serve their public page on them. Product doc: [docs/domains.md](../domains.md). Code: `api/_lib/cloud-domains.js`, `api/_lib/domains-service.js`, `api/_lib/domain-connect.js`, `api/cron/domain-renewals.js`.
+
+- **Identity.** The API never calls Cloud Domains as its own runtime identity. It impersonates `three-ws-domains@aerial-vehicle-466722-p5.iam.gserviceaccount.com` through IAM Credentials `generateAccessToken`; the runtime account holds `roles/iam.serviceAccountTokenCreator` on that one account. No key exists for it. The account holds `roles/domains.admin`, `roles/dns.admin` and the custom role `threewsDomainConnect` (`compute.sslCertificates.create/delete/get/list`, `compute.targetHttpsProxies.get/setSslCertificates/use`, `compute.globalAddresses.get`, `compute.globalOperations.get`). `DOMAINS_ACCESS_TOKEN` overrides it for workstation scripts only.
+- **Quota.** `domains.googleapis.com` allows 300 sensitive requests per day and 100 per minute per project, and 20 registrations. The daily window resets about 07:00 UTC. A 3000/day increase was requested (preference `domains-sensitive-per-day`). `GET /api/domains/quota` shows the platform's approximate use.
+- **TLD snapshot.** `node scripts/refresh-domain-tlds.mjs` regenerates `data/domain-tlds.json` (about 150 candidate TLDs probed serially, around 3 minutes and 150 quota calls). Run it right after a quota reset, then commit the file.
+- **Connect procedure** (what `connectDomain` automates): Cloud DNS managed zone `tw-<sha12>` with `A` records for the apex and `www` at the named global address `three-ws-ip` (136.68.246.178); `configureDnsSettings` on the registration to the zone's nameservers; a Google-managed certificate `tw-<sha12>` created and attached to `three-ws-https-proxy` by replacing its certificate list under a Redis lock; the host becomes `live` when the certificate is `ACTIVE`. The proxy holds at most 15 certificates, one of which is `three-ws-cert`; past that `connect` answers `cert_capacity`. Express routes a `live` host's `/` to `/agents/<id>` ([server/index.mjs](../../server/index.mjs)).
+- **Renewals.** `/api/cron/domain-renewals` (daily, in `vercel.json`) debits credits 14 days before expiry and otherwise switches the name to manual renewal. After adding it, run `npm run deploy:gcp:sync-crons`.
+- **Rollback.** Detach a certificate with `gcloud compute target-https-proxies update three-ws-https-proxy --ssl-certificates=<remaining list> --global`; delete the `web_domain_hosts` row (or set status `failed`) to stop host routing.
diff --git a/packages/mcp-policy/src/groups.js b/packages/mcp-policy/src/groups.js
index c3a5de336..f399e5147 100644
--- a/packages/mcp-policy/src/groups.js
+++ b/packages/mcp-policy/src/groups.js
@@ -67,6 +67,7 @@ export const GROUPS = Object.freeze([
{ id: 'lending', label: 'Lending', summary: 'Supply, borrow, and repay on lending markets.' },
{ id: 'predictions', label: 'Predictions', summary: 'Prediction market positions.' },
{ id: 'launch', label: 'Launch', summary: 'Launch a coin: metadata upload, vanity mints, launch, and creator-fee collection.' },
+ { id: 'domains', label: 'Domains', summary: 'Search, price and register web domains, and connect a domain to an agent page. Registration spends credits.' },
{ id: 'marketplace', label: 'Marketplace', summary: 'Browse and hire agents and skills, the job board, and bounty markets.' },
{ id: 'cards', label: 'Cards', summary: 'Agent payment cards.' },
{ id: 'mail', label: 'Mail', summary: 'Outward messages: paid knocks, announcements to a person, and agent mail.' },
diff --git a/packages/mcp-policy/src/table.js b/packages/mcp-policy/src/table.js
index 262097ce0..e0eb8e603 100644
--- a/packages/mcp-policy/src/table.js
+++ b/packages/mcp-policy/src/table.js
@@ -157,6 +157,17 @@ export const POLICY = {
agent_card_connect: r('cards'),
agent_card_connect_link: w('cards'),
// Agent lifecycle, runs and automations (api/_mcp/tools/agent-lifecycle.js).
+ // Web domains (api/_mcp/tools/domains.js). Registration spends credits, so it
+ // is financial: domain_register_quote validates against the registrar and
+ // domain_register needs its quote_id and confirm_spend.
+ domain_search: r('domains'),
+ domain_check: r('domains'),
+ domain_pricing: r('domains'),
+ domain_register_quote: w('domains'),
+ domain_register: f('domains', 'confirm_spend', 'domain_register_quote', ['domain', 'auto_renew', 'privacy']),
+ domain_status: r('domains'),
+ domain_connect: w('domains'),
+ domain_connect_status: r('domains'),
// Deletes are financial-tier because they cannot be undone. Swap and
// transfer automations gate themselves: connector keys are refused, the
// bearer needs wallet:write, and the call needs confirm_spend after the
diff --git a/pages/coin.html b/pages/coin.html
index a479beaa8..b5895ccaa 100644
--- a/pages/coin.html
+++ b/pages/coin.html
@@ -36,6 +36,7 @@
<link rel="stylesheet" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/src/coin-pages.css" />
+ <link rel="stylesheet" href="/domains.css" />
<link rel="stylesheet" href="/footer.css" />
<style>
/* /coin/:id enrichment sections — same token/card system as coin-pages.css,
@@ -469,6 +470,9 @@
<!-- Official links + explorers + contracts. -->
<section id="cv-links" class="cv-section" aria-label="Links"></section>
+ <!-- Live-availability domain suggestions for the project name. -->
+ <section id="cv-domains" class="cv-section dm-sug" aria-label="Domain names"></section>
+
<p class="cv-updated" id="cv-updated" hidden></p>
</main>
diff --git a/pages/domains.html b/pages/domains.html
new file mode 100644
index 000000000..24d8e05d9
--- /dev/null
+++ b/pages/domains.html
@@ -0,0 +1,71 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>
+ (function () {
+ document.documentElement.classList.add('js');
+ try {
+ var m = localStorage.getItem('twx_theme');
+ var l = m === 'auto' ? window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches : m === 'light';
+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');
+ } catch (e) {
+ document.documentElement.setAttribute('data-theme', 'dark');
+ }
+ })();
+ </script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <title>Domains · three.ws</title>
+ <meta name="description" content="Search, price and register web domains with live registrar availability, paid from your credits, then serve an agent's public page on the domain." />
+ <meta property="og:title" content="Domains · three.ws" />
+ <meta property="og:description" content="Find an available domain, see the exact yearly price, register it from credits and point it at your agent." />
+ <meta property="og:url" content="https://three.ws/domains" />
+ <link rel="canonical" href="https://three.ws/domains" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+ <link rel="stylesheet" href="/domains.css" />
+ </head>
+ <body>
+ <a href="#main-content" class="h-skip-link">Skip to main content</a>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main id="main-content" class="dm-wrap">
+ <h1>Domains</h1>
+ <p class="dm-lede">Search live registrar availability, see the exact yearly price, and register from your credits. Registration is for one year and the same price renews it. Then serve an agent's public page on the domain.</p>
+
+ <div id="dm-banner" role="status" aria-live="polite"></div>
+
+ <section class="dm-card" aria-labelledby="dm-search-h">
+ <h2 id="dm-search-h">Find a domain</h2>
+ <form id="dm-search" class="dm-search" role="search">
+ <input id="dm-q" class="dm-input" type="text" name="q" placeholder="orbit, orbit.app or a project name" autocomplete="off" spellcheck="false" aria-label="Domain name or keyword" required />
+ <button class="dm-btn" type="submit">Search</button>
+ </form>
+ <p id="dm-search-status" class="dm-status" aria-live="polite"></p>
+ <ul id="dm-results" class="dm-results"></ul>
+ </section>
+
+ <section id="dm-register" class="dm-card" aria-labelledby="dm-reg-h" hidden>
+ <h2 id="dm-reg-h">Register</h2>
+ <div id="dm-reg-body"></div>
+ </section>
+
+ <section class="dm-card" aria-labelledby="dm-mine-h">
+ <h2 id="dm-mine-h">Your domains</h2>
+ <div id="dm-mine"></div>
+ </section>
+ </main>
+
+ <script type="module" src="/src/domains/page.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/domains.css b/public/domains.css
new file mode 100644
index 000000000..d74feaaef
--- /dev/null
+++ b/public/domains.css
@@ -0,0 +1,48 @@
+/* /domains page and the domain suggestion panel on coin pages. */
+.dm-wrap { max-width: 1040px; width: 100%; min-width: 0; margin: 0 auto; padding: clamp(1.25rem, 4vw, 3rem) 1.25rem 4rem; }
+.dm-wrap h1 { font-size: clamp(1.7rem, 4vw, 2.5rem); margin: 0 0 0.35rem; letter-spacing: -0.02em; }
+.dm-lede { color: var(--ink-dim, #9aa3b2); margin: 0 0 1.5rem; max-width: 60ch; }
+.dm-card { background: var(--surface-1, #14171d); border: 1px solid var(--stroke, #262a33); border-radius: 14px; padding: 1.1rem; margin-bottom: 1.25rem; min-width: 0; }
+.dm-card h2 { font-size: 1.05rem; margin: 0 0 0.75rem; }
+.dm-search { display: flex; gap: 0.5rem; }
+.dm-input, .dm-field input, .dm-field select { flex: 1; min-width: 0; background: var(--surface-2, #1c1f27); border: 1px solid var(--stroke, #262a33); border-radius: 10px; color: var(--ink, #e8ebf2); font: inherit; padding: 0.6rem 0.8rem; }
+.dm-input:focus-visible, .dm-field input:focus-visible, .dm-field select:focus-visible, .dm-btn:focus-visible, .dm-sug-chip:focus-visible { outline: 2px solid var(--accent, #6d8dff); outline-offset: 2px; }
+.dm-btn { background: var(--btn-primary-bg, var(--accent, #6d8dff)); color: var(--btn-primary-fg, #fff); border: 0; border-radius: 10px; padding: 0.6rem 1.1rem; font: inherit; font-weight: 600; cursor: pointer; transition: transform 0.12s, opacity 0.12s; }
+.dm-btn:hover { opacity: 0.9; }
+.dm-btn:active { transform: translateY(1px); }
+.dm-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+.dm-btn.ghost { background: transparent; color: var(--ink, #e8ebf2); border: 1px solid var(--stroke, #262a33); }
+.dm-status { margin: 0.6rem 0 0; color: var(--ink-dim, #9aa3b2); font-size: 0.9rem; min-height: 1.2em; }
+.dm-banner { border: 1px solid var(--stroke, #262a33); border-radius: 10px; padding: 0.7rem 0.9rem; margin-bottom: 1rem; font-size: 0.92rem; }
+.dm-banner.warn { border-color: #b8860b; }
+.dm-banner.err { border-color: #c0392b; }
+.dm-results { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.5rem; }
+.dm-row { display: grid; grid-template-columns: 1fr auto auto; gap: 0.75rem; align-items: center; padding: 0.7rem 0.9rem; border: 1px solid var(--stroke, #262a33); border-radius: 12px; background: var(--surface-2, #1c1f27); transition: border-color 0.15s, transform 0.15s; }
+.dm-row:hover { border-color: var(--accent, #6d8dff); }
+.dm-row .name { font-weight: 600; overflow-wrap: anywhere; }
+.dm-row .why { color: var(--ink-dim, #9aa3b2); font-size: 0.85rem; }
+.dm-row .price { font-variant-numeric: tabular-nums; text-align: right; }
+.dm-row .price small { display: block; color: var(--ink-dim, #9aa3b2); }
+.dm-row.taken { opacity: 0.6; }
+.dm-empty { color: var(--ink-dim, #9aa3b2); padding: 1rem 0; }
+.dm-skel { height: 56px; border-radius: 12px; background: linear-gradient(90deg, var(--surface-2, #1c1f27), var(--surface-1, #14171d), var(--surface-2, #1c1f27)); background-size: 200% 100%; animation: dm-shimmer 1.2s linear infinite; }
+@keyframes dm-shimmer { to { background-position: -200% 0; } }
+.dm-form { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0.7rem; }
+.dm-field { display: flex; flex-direction: column; gap: 0.25rem; font-size: 0.85rem; color: var(--ink-dim, #9aa3b2); min-width: 0; }
+.dm-field.wide { grid-column: 1 / -1; }
+.dm-check { display: flex; gap: 0.5rem; align-items: center; font-size: 0.92rem; }
+.dm-quote { margin: 1rem 0; display: grid; gap: 0.35rem; font-variant-numeric: tabular-nums; }
+.dm-quote div { display: flex; justify-content: space-between; gap: 1rem; }
+.dm-quote .total { font-weight: 700; border-top: 1px solid var(--stroke, #262a33); padding-top: 0.4rem; }
+.dm-actions { display: flex; gap: 0.6rem; flex-wrap: wrap; margin-top: 0.75rem; }
+.dm-table { width: 100%; border-collapse: collapse; font-size: 0.92rem; }
+.dm-table th, .dm-table td { text-align: left; padding: 0.5rem 0.4rem; border-bottom: 1px solid var(--stroke, #262a33); overflow-wrap: anywhere; }
+.dm-pill { display: inline-block; padding: 0.1rem 0.55rem; border-radius: 999px; border: 1px solid var(--stroke, #262a33); font-size: 0.78rem; }
+.dm-pill.ok { border-color: var(--success, #2ecc71); color: var(--success, #2ecc71); }
+.dm-sug-title { font-size: 1.15rem; margin: 0 0 0.6rem; }
+.dm-sug-list { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 0.5rem; }
+.dm-sug-chip { display: inline-flex; gap: 0.6rem; align-items: baseline; padding: 0.45rem 0.8rem; border: 1px solid var(--stroke, #262a33); border-radius: 999px; text-decoration: none; color: inherit; transition: border-color 0.15s, transform 0.15s; }
+.dm-sug-chip:hover { border-color: var(--accent, #6d8dff); transform: translateY(-1px); }
+.dm-sug-note { color: var(--ink-dim, #9aa3b2); font-size: 0.88rem; margin: 0.6rem 0 0; }
+@media (max-width: 560px) { .dm-row { grid-template-columns: 1fr auto; } .dm-row .act { grid-column: 1 / -1; } .dm-form { grid-template-columns: 1fr; } .dm-search { flex-direction: column; } }
+@media (prefers-reduced-motion: reduce) { .dm-skel { animation: none; } .dm-row, .dm-sug-chip, .dm-btn { transition: none; } }
diff --git a/scripts/refresh-domain-tlds.mjs b/scripts/refresh-domain-tlds.mjs
index b1901b545..0e076c09e 100644
--- a/scripts/refresh-domain-tlds.mjs
+++ b/scripts/refresh-domain-tlds.mjs
@@ -16,27 +16,14 @@
import { writeFileSync } from 'node:fs';
import { retrieveRegisterParameters, moneyToNumber } from '../api/_lib/cloud-domains.js';
-const CANDIDATES = `com net org info biz name mobi pro tel asia xyz online site store tech cloud app dev page art shop club live
-life studio media agency academy accountant actor adult africa ai airforce army attorney auction audio auto band bar bargains
-beer best bet bid bike bio black blog blue boutique build builders business buzz cab cafe camera camp capital car cards care
-career careers cash casino catering center ceo charity chat cheap church city claims cleaning click clinic clothing coach codes
-coffee community company computer condos construction consulting contact contractors cool coupons credit creditcard cricket
-cruises dance date dating deals degree delivery democrat dental dentist design diamonds digital direct directory discount
-doctor dog domains earth education email energy engineer engineering enterprises equipment estate events exchange expert
-exposed express fail faith family fan fans farm fashion film finance financial fish fishing fit fitness flights florist flowers
-football forsale foundation fun fund furniture futbol fyi gallery game games garden gift gifts gives glass global gmbh gold
-golf graphics gratis green gripe group guide guitars guru haus health healthcare help hockey holdings holiday home horse
-hospital host house how icu immo immobilien inc industries ink institute insure international investments io irish jewelry
-juegos kaufen kim kitchen kiwi land lawyer lease legal lgbt lighting limited limo link live loan loans lol love ltd luxury
-maison management market marketing mba media memorial men menu moda moe money mortgage movie navy network new news ninja
-nyc one onl organic page partners parts party pet photo photography photos pics pictures pink pizza place plumbing plus
-poker porn press productions promo properties property pub quest racing recipes red rehab reise reisen rent rentals repair
-report republican rest restaurant review reviews rich rip rocks rodeo run sale salon sarl school schule science security
-services sex sexy shiksha shoes show singles site ski soccer social software solar solutions soy space sport store stream
-studio study style sucks supplies supply support surf surgery systems tax taxi team tech technology tennis theater tips
-tires today tools top tours town toys trade trading training tube university uno vacations vegas ventures vet viajes video
-villas vin vip vision vodka vote voting voto voyage wang watch webcam website wedding wiki win wine work works world wtf
-xyz yoga zone co us uk de fr es it nl be ch at se no dk fi pl cz pt ie eu ca au nz jp in br mx ar cl`.split(/\s+/);
+const CANDIDATES = `com net org info biz name pro xyz online site store tech cloud app dev page art shop club live life studio media agency
+academy ai auto bar best blog blue build business buzz cafe capital cash center chat city click coach codes community company
+computer consulting cool dance deals design digital direct domains earth email energy events exchange expert express family
+fan farm finance fit fun fund fyi gallery game games global gold golf graphics green group guide guru health help holdings
+home host house inc industries ink io land link lol love ltd market marketing money network news ninja one partners party
+photo pics place plus press productions promo run sale school science services show social software solutions space support
+systems team technology today tools top town trade training tube vip wiki win work works world wtf zone co us uk de fr es it
+nl ch se ca au in`.split(/\s+/);
const dryRun = process.argv.includes('--dry-run');
const unique = [...new Set(CANDIDATES)];
diff --git a/server/index.mjs b/server/index.mjs
index 639b15896..3d647c4a2 100644
--- a/server/index.mjs
+++ b/server/index.mjs
@@ -376,6 +376,28 @@ app.use((req, res, next) => {
app.use((req, res, next) => {
const url = new URL(req.url, 'http://internal');
const pathname = url.pathname;
+// Custom domains. A host a user registered and connected here
+// (api/_lib/domain-connect.js, table web_domain_hosts) serves that agent's
+// public page at its root. Everything else on the host (assets, /api, the
+// agent page's own subpaths) resolves as on the apex, so the page works as it
+// does on three.ws. Only the root document is rewritten.
+app.use(async (req, res, next) => {
+ const host = String(req.headers.host || '').toLowerCase().split(':')[0];
+ if (!host || host === CANONICAL_HOST || host === WWW_HOST || host.endsWith('.run.app') || host === 'localhost') return next();
+ if (req.method !== 'GET' && req.method !== 'HEAD') return next();
+ try {
+ const { agentForHost } = await import('../api/_lib/domain-connect.js');
+ const agentId = await agentForHost(host);
+ if (agentId && (req.path === '/' || req.path === '')) {
+ const q = req.url.indexOf('?');
+ req.url = `/agents/${agentId}${q === -1 ? '' : req.url.slice(q)}`;
+ }
+ } catch (err) {
+ console.error('[server] custom-domain lookup failed:', err?.message || err);
+ }
+ next();
+});
+
for (const route of phase1Routes) {
const m = route.re.exec(pathname);
if (!m) continue;
diff --git a/src/coin-page.js b/src/coin-page.js
index 089c1605c..9b4e60183 100644
--- a/src/coin-page.js
+++ b/src/coin-page.js
@@ -26,6 +26,7 @@ import {
escapeHtml as esc,
} from './shared/coin-format.js';
import { markNoindex } from './seo-meta.js';
+import { mountDomainSuggestions } from './domains/suggest-panel.js';
const TIME_RANGES = [
{ label: '24H', days: 1 },
@@ -1163,6 +1164,7 @@ async function main() {
renderDevCom(coin);
renderAbout(coin);
renderLinks(coin);
+ mountDomainSuggestions($('cv-domains'), coin.name);
renderProvenance(coin, source);
// Chart, markets, and news stream in independently of the core profile.
// A remembered non-CoinGecko source mounts its terminal directly and defers
diff --git a/src/domains/api.js b/src/domains/api.js
new file mode 100644
index 000000000..0ab5bf32a
--- /dev/null
+++ b/src/domains/api.js
@@ -0,0 +1,42 @@
+// Client for /api/domains. Every call returns parsed JSON or throws an Error
+// whose `code` and `status` come from the API's error envelope.
+
+async function request(path, { method = 'GET', body } = {}) {
+ const res = await fetch(`/api/domains/${path}`, {
+ method,
+ credentials: 'include',
+ headers: body ? { 'content-type': 'application/json' } : undefined,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const err = new Error(data.error_description || data.message || `Request failed (${res.status})`);
+ err.status = res.status;
+ err.code = data.error || 'request_failed';
+ err.detail = data.detail;
+ throw err;
+ }
+ return data;
+}
+
+const qs = (o) => new URLSearchParams(Object.entries(o).filter(([, v]) => v != null && v !== '')).toString();
+
+export const domainsApi = {
+ search: (q, tlds) => request(`search?${qs({ q, tlds: tlds?.join(',') })}`),
+ check: (domain) => request(`check?${qs({ domain })}`),
+ suggest: (name) => request(`suggest?${qs({ name })}`),
+ pricing: (params = {}) => request(`pricing?${qs(params)}`),
+ quota: () => request('quota'),
+ list: () => request('list'),
+ quote: (body) => request('quote', { method: 'POST', body }),
+ register: (body) => request('register', { method: 'POST', body }),
+ status: (id) => request(`status?${qs({ id })}`),
+ connect: (body) => request('connect', { method: 'POST', body }),
+ connectStatus: (domain) => request(`connect-status?${qs({ domain })}`),
+};
+
+export const fmtUsd = (n) => (n == null ? '' : `$${Number(n).toFixed(2)}`);
+
+export function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+}
diff --git a/src/domains/page.js b/src/domains/page.js
new file mode 100644
index 000000000..d869f75b0
--- /dev/null
+++ b/src/domains/page.js
@@ -0,0 +1,243 @@
+// /domains: search, quote, confirmed register (credits) and connect to an agent.
+
+import { domainsApi, esc, fmtUsd } from './api.js';
+
+const $ = (id) => document.getElementById(id);
+const CONTACT_KEY = 'twx_domain_contact';
+
+let selected = null;
+let pendingKey = null;
+
+function banner(kind, html) {
+ $('dm-banner').innerHTML = html ? `<div class="dm-banner ${kind}">${html}</div>` : '';
+}
+
+function loadContact() {
+ try {
+ return JSON.parse(localStorage.getItem(CONTACT_KEY) || '{}');
+ } catch {
+ return {};
+ }
+}
+
+function saveContact(c) {
+ try {
+ localStorage.setItem(CONTACT_KEY, JSON.stringify(c));
+ } catch {}
+}
+
+async function showQuota() {
+ try {
+ const q = await domainsApi.quota();
+ if (q.exhausted) {
+ banner('warn', 'The registrar is at its daily request limit. Pricing still works from the snapshot; live availability resumes after the daily reset.');
+ }
+ } catch {}
+}
+
+function resultRow(r) {
+ const act = r.available
+ ? `<button class="dm-btn act" type="button" data-pick="${esc(r.domain)}">Register</button>`
+ : `<span class="why act">${esc(r.message || r.reason)}</span>`;
+ return `<li class="dm-row ${r.available ? '' : 'taken'}">
+ <div><div class="name">${esc(r.domain)}</div><div class="why">${r.available ? 'Available' : esc(r.reason)}</div></div>
+ <div class="price">${r.available ? `${fmtUsd(r.registrationUsd)}<small>per year, renews at ${fmtUsd(r.renewalUsd)}</small>` : ''}</div>
+ ${act}</li>`;
+}
+
+async function runSearch(q) {
+ const status = $('dm-search-status');
+ const list = $('dm-results');
+ status.textContent = 'Searching…';
+ list.innerHTML = '<li class="dm-skel"></li><li class="dm-skel"></li><li class="dm-skel"></li>';
+ try {
+ const out = await domainsApi.search(q);
+ list.innerHTML = out.results.length ? out.results.map(resultRow).join('') : '<li class="dm-empty">No names found. Try a shorter keyword.</li>';
+ status.textContent = `${out.availableCount} available of ${out.results.length}. ${out.cached ? 'Cached result.' : 'Live from the registrar.'}`;
+ } catch (e) {
+ list.innerHTML = '';
+ status.textContent = e.code === 'domains_quota_exhausted' ? e.message : e.status === 429 ? 'Too many searches this hour. Try again later.' : `${e.message} Check your connection and search again.`;
+ }
+}
+
+function field(id, label, value, { wide = false, type = 'text', placeholder = '' } = {}) {
+ return `<label class="dm-field ${wide ? 'wide' : ''}" for="${id}">${label}<input id="${id}" type="${type}" value="${esc(value || '')}" placeholder="${esc(placeholder)}" /></label>`;
+}
+
+function openRegister(domain) {
+ selected = domain;
+ pendingKey = null;
+ const c = loadContact();
+ $('dm-register').hidden = false;
+ $('dm-reg-body').innerHTML = `
+ <p><strong>${esc(domain)}</strong>. The registrant contact is sent to the registrar and is hidden from the public WHOIS by default.</p>
+ <form id="dm-form" class="dm-form" novalidate>
+ ${field('c-name', 'Full name', c.name)}
+ ${field('c-email', 'Email', c.email, { type: 'email' })}
+ ${field('c-phone', 'Phone (+14155550123)', c.phone, { type: 'tel' })}
+ ${field('c-country', 'Country (2 letters)', c.country, { placeholder: 'US' })}
+ ${field('c-addr', 'Street address', (c.address_lines || [])[0], { wide: true })}
+ ${field('c-city', 'City', c.city)}
+ ${field('c-region', 'State or region', c.region)}
+ ${field('c-postal', 'Postal code', c.postal_code)}
+ <label class="dm-check wide"><input id="c-renew" type="checkbox" /> Renew automatically each year from my credits</label>
+ <div class="dm-actions wide"><button class="dm-btn" type="submit">Get exact quote</button><button class="dm-btn ghost" type="button" id="dm-cancel">Cancel</button></div>
+ </form>
+ <div id="dm-quote"></div>`;
+ $('dm-register').scrollIntoView({ behavior: 'smooth', block: 'start' });
+ $('dm-cancel').addEventListener('click', () => ($('dm-register').hidden = true));
+ $('dm-form').addEventListener('submit', (e) => {
+ e.preventDefault();
+ getQuote();
+ });
+}
+
+function readContact() {
+ const v = (id) => $(id).value.trim();
+ return { name: v('c-name'), email: v('c-email'), phone: v('c-phone'), country: v('c-country'), address_lines: [v('c-addr')], city: v('c-city'), region: v('c-region'), postal_code: v('c-postal') };
+}
+
+async function getQuote() {
+ const box = $('dm-quote');
+ const contact = readContact();
+ saveContact(contact);
+ box.innerHTML = '<div class="dm-skel"></div>';
+ try {
+ const q = await domainsApi.quote({ domain: selected, contact, auto_renew: $('c-renew').checked });
+ const short = !q.payment.sufficient;
+ box.innerHTML = `<div class="dm-quote" aria-live="polite">
+ <div><span>${esc(q.domain)}, ${q.termYears} year</span><span>${fmtUsd(q.priceUsd)}</span></div>
+ <div><span>Renews at</span><span>${fmtUsd(q.renewalUsd)} / year</span></div>
+ <div><span>Your credits</span><span>${fmtUsd(q.payment.balanceUsd)}</span></div>
+ <div class="total"><span>Charged now</span><span>${fmtUsd(q.priceUsd)}</span></div>
+ </div>
+ <p class="dm-status">${esc(q.autoRenewNote)}</p>
+ ${short ? '<p class="dm-banner warn">Your credits do not cover this. <a href="/credits">Add credits</a> then quote again.</p>' : ''}
+ <div class="dm-actions"><button id="dm-confirm" class="dm-btn" type="button" ${short ? 'disabled' : ''}>Confirm and pay ${fmtUsd(q.priceUsd)} from credits</button></div>`;
+ $('dm-confirm').addEventListener('click', () => confirmRegister(q));
+ } catch (e) {
+ const missing = e.detail?.missing?.length ? ` Missing: ${esc(e.detail.missing.join(', '))}.` : '';
+ box.innerHTML = e.status === 401
+ ? '<p class="dm-banner warn"><a href="/login?next=/domains">Sign in</a> to register a domain.</p>'
+ : `<p class="dm-banner err">${esc(e.message)}${missing}</p>`;
+ }
+}
+
+async function confirmRegister(q) {
+ const btn = $('dm-confirm');
+ btn.disabled = true;
+ btn.textContent = 'Registering…';
+ pendingKey = pendingKey || crypto.randomUUID();
+ try {
+ const out = await domainsApi.register({
+ domain: q.domain,
+ contact: readContact(),
+ auto_renew: q.autoRenew,
+ expected_price_usd: q.priceUsd,
+ confirm: true,
+ idempotency_key: pendingKey,
+ source: 'api',
+ });
+ $('dm-quote').innerHTML = `<p class="dm-banner">Registration submitted for ${esc(out.registration.domain)}. This usually settles within a minute.</p>`;
+ await pollRegistration(out.registration.id);
+ loadMine();
+ } catch (e) {
+ btn.disabled = false;
+ btn.textContent = 'Retry';
+ const msg = e.code === 'price_changed' ? 'The price changed. Get a new quote.' : e.message;
+ $('dm-quote').insertAdjacentHTML('beforeend', `<p class="dm-banner err">${esc(msg)} Nothing is charged twice if you retry.</p>`);
+ }
+}
+
+async function pollRegistration(id) {
+ for (let i = 0; i < 30; i++) {
+ const s = await domainsApi.status(id).catch(() => null);
+ if (s && s.status !== 'registering') {
+ banner(s.status === 'active' ? '' : 'err', s.status === 'active' ? `${esc(s.domain)} is registered.` : `Registration failed: ${esc(s.error || 'unknown')}. Your credits were refunded.`);
+ return;
+ }
+ await new Promise((r) => setTimeout(r, 4000));
+ }
+ banner('warn', 'Still registering. It will appear under Your domains when it settles.');
+}
+
+async function loadMine() {
+ const box = $('dm-mine');
+ box.innerHTML = '<div class="dm-skel"></div>';
+ try {
+ const { registrations, hosts } = await domainsApi.list();
+ if (!registrations.length) {
+ box.innerHTML = '<p class="dm-empty">No domains yet. Search above and register one.</p>';
+ return;
+ }
+ const hostMap = new Map(hosts.map((h) => [h.host, h]));
+ const agents = await fetch('/api/agents', { credentials: 'include' }).then((r) => (r.ok ? r.json() : { agents: [] })).catch(() => ({ agents: [] }));
+ const opts = (agents.agents || []).map((a) => `<option value="${esc(a.id)}">${esc(a.name || a.id)}</option>`).join('');
+ box.innerHTML = `<table class="dm-table"><thead><tr><th>Domain</th><th>Status</th><th>Expires</th><th>Serve agent page</th></tr></thead><tbody>${registrations
+ .map((r) => {
+ const h = hostMap.get(r.domain);
+ const connect = r.status !== 'active'
+ ? ''
+ : h
+ ? `<span class="dm-pill ${h.status === 'live' ? 'ok' : ''}">${esc(h.status.replace('_', ' '))}</span> ${h.status === 'live' ? `<a href="https://${esc(h.host)}">Open</a>` : `<button class="dm-btn ghost" data-recheck="${esc(r.domain)}">Check</button>`}`
+ : opts
+ ? `<select aria-label="Agent for ${esc(r.domain)}" data-agent-for="${esc(r.domain)}">${opts}</select> <button class="dm-btn" data-connect="${esc(r.domain)}">Connect</button>`
+ : '<a href="/create">Create an agent first</a>';
+ return `<tr><td>${esc(r.domain)}</td><td><span class="dm-pill ${r.status === 'active' ? 'ok' : ''}">${esc(r.status)}</span></td><td>${r.expiresAt ? new Date(r.expiresAt).toLocaleDateString() : ''}</td><td>${connect}</td></tr>`;
+ })
+ .join('')}</tbody></table><p id="dm-connect-note" class="dm-status" aria-live="polite"></p>`;
+ } catch (e) {
+ box.innerHTML = e.status === 401 ? '<p class="dm-empty"><a href="/login?next=/domains">Sign in</a> to see your domains.</p>' : `<p class="dm-banner err">${esc(e.message)} <button class="dm-btn ghost" id="dm-retry">Retry</button></p>`;
+ $('dm-retry')?.addEventListener('click', loadMine);
+ }
+}
+
+async function connect(domain) {
+ const note = $('dm-connect-note');
+ const agentId = document.querySelector(`[data-agent-for="${CSS.escape(domain)}"]`)?.value;
+ note.textContent = 'Setting up DNS and the certificate…';
+ try {
+ const out = await domainsApi.connect({ domain, agent_id: agentId });
+ note.textContent = out.message || `Connecting ${domain}. The certificate can take several minutes to provision.`;
+ loadMine();
+ } catch (e) {
+ note.textContent = e.message;
+ }
+}
+
+async function recheck(domain) {
+ const note = $('dm-connect-note');
+ try {
+ const s = await domainsApi.connectStatus(domain);
+ note.textContent = `${domain}: ${s.status}${s.error ? `. ${s.error}` : ''}`;
+ loadMine();
+ } catch (e) {
+ note.textContent = e.message;
+ }
+}
+
+document.addEventListener('click', (e) => {
+ const t = e.target.closest('[data-pick],[data-connect],[data-recheck]');
+ if (!t) return;
+ if (t.dataset.pick) openRegister(t.dataset.pick);
+ else if (t.dataset.connect) connect(t.dataset.connect);
+ else recheck(t.dataset.recheck);
+});
+
+$('dm-search').addEventListener('submit', (e) => {
+ e.preventDefault();
+ const q = $('dm-q').value.trim();
+ if (q) {
+ history.replaceState(null, '', `?q=${encodeURIComponent(q)}`);
+ runSearch(q);
+ }
+});
+
+const params = new URLSearchParams(location.search);
+const pre = params.get('domain') || params.get('q');
+if (pre) {
+ $('dm-q').value = pre;
+ runSearch(pre);
+}
+showQuota();
+loadMine();
diff --git a/src/domains/suggest-panel.js b/src/domains/suggest-panel.js
new file mode 100644
index 000000000..f66f2b0ae
--- /dev/null
+++ b/src/domains/suggest-panel.js
@@ -0,0 +1,27 @@
+// Domain suggestions for a project name: the cheapest available names across
+// popular TLDs, each linking into /domains to register. Mounted on coin pages.
+
+import { domainsApi, esc, fmtUsd } from './api.js';
+
+export async function mountDomainSuggestions(el, name) {
+ const label = String(name || '').trim();
+ if (!el || !label) return;
+ el.innerHTML = `<h2 class="dm-sug-title">Domains for ${esc(label)}</h2><p class="dm-sug-note" aria-live="polite">Checking availability…</p>`;
+ try {
+ const out = await domainsApi.suggest(label);
+ const picks = out.results || [];
+ if (!picks.length) {
+ el.innerHTML = `<h2 class="dm-sug-title">Domains for ${esc(label)}</h2><p class="dm-sug-note">No available names found for this project. <a href="/domains?q=${encodeURIComponent(label)}">Search other names</a>.</p>`;
+ return;
+ }
+ el.innerHTML = `<h2 class="dm-sug-title">Domains for ${esc(label)}</h2>
+ <ul class="dm-sug-list">${picks
+ .map(
+ (r) => `<li><a class="dm-sug-chip" href="/domains?domain=${encodeURIComponent(r.domain)}"><span>${esc(r.domain)}</span><b>${fmtUsd(r.registrationUsd)}/yr</b></a></li>`,
+ )
+ .join('')}</ul>
+ <p class="dm-sug-note">Live registrar availability. <a href="/domains?q=${encodeURIComponent(label)}">See all results</a>.</p>`;
+ } catch (e) {
+ el.innerHTML = `<h2 class="dm-sug-title">Domains for ${esc(label)}</h2><p class="dm-sug-note">${esc(e.message)} <a href="/domains?q=${encodeURIComponent(label)}">Try the domain search</a>.</p>`;
+ }
+}
diff --git a/tests/domains-service.test.js b/tests/domains-service.test.js
new file mode 100644
index 000000000..4eed46178
--- /dev/null
+++ b/tests/domains-service.test.js
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest';
+
+import { moneyToNumber, numberToMoney } from '../api/_lib/cloud-domains.js';
+import { DomainsError, domainPricing, labelFromQuery, normalizeContact, normalizeDomain } from '../api/_lib/domains-service.js';
+import { toolDefs } from '../api/_mcp/tools/domains.js';
+
+const contact = {
+ name: 'Ada Lovelace',
+ email: '[email protected]',
+ phone: '+1 (415) 555-0123',
+ address_lines: ['1 Main St'],
+ city: 'San Francisco',
+ region: 'CA',
+ postal_code: '94105',
+ country: 'us',
+};
+
+describe('normalizeDomain', () => {
+ it('lowercases, strips scheme and path, and punycodes', () => {
+ expect(normalizeDomain('HTTPS://Orbit.App/path')).toBe('orbit.app');
+ expect(normalizeDomain('bücher.de')).toBe('xn--bcher-kva.de');
+ });
+ it('rejects names that are not registrable', () => {
+ for (const bad of ['', 'nodot', 'a..b', '-x.com', 'spa ce.com']) {
+ expect(() => normalizeDomain(bad)).toThrow(DomainsError);
+ }
+ });
+});
+
+describe('labelFromQuery', () => {
+ it('turns a project name into a label', () => {
+ expect(labelFromQuery('My Cool Coin!')).toBe('my-cool-coin');
+ expect(labelFromQuery('orbit.app')).toBe('orbit');
+ });
+ it('refuses an empty query', () => {
+ expect(() => labelFromQuery('!!!')).toThrow(DomainsError);
+ });
+});
+
+describe('normalizeContact', () => {
+ it('normalizes phone and country', () => {
+ const c = normalizeContact(contact);
+ expect(c.phone).toBe('+14155550123');
+ expect(c.country).toBe('US');
+ });
+ it('names every missing field', () => {
+ try {
+ normalizeContact({ ...contact, email: 'nope', city: '' });
+ throw new Error('should have thrown');
+ } catch (e) {
+ expect(e.code).toBe('contact_invalid');
+ expect(e.detail.missing).toEqual(expect.arrayContaining(['email', 'city']));
+ }
+ });
+ it('requires a contact at all', () => {
+ expect(() => normalizeContact(null)).toThrow(/contact is required/);
+ });
+});
+
+describe('money conversion', () => {
+ it('round-trips Google Money', () => {
+ expect(moneyToNumber({ units: '12', nanos: 500000000 })).toBe(12.5);
+ expect(numberToMoney(12.5)).toEqual({ currencyCode: 'USD', units: '12', nanos: 500000000 });
+ expect(numberToMoney(9)).toEqual({ currencyCode: 'USD', units: '9' });
+ });
+});
+
+describe('domainPricing', () => {
+ it('answers from the snapshot without a registrar call', () => {
+ const out = domainPricing({ limit: 5 });
+ expect(Array.isArray(out.tlds)).toBe(true);
+ expect(out.note).toMatch(/one year/);
+ });
+});
+
+describe('domain MCP tools', () => {
+ const byName = Object.fromEntries(toolDefs.map((t) => [t.name, t]));
+ it('exposes the full set', () => {
+ expect(Object.keys(byName).sort()).toEqual(
+ ['domain_check', 'domain_connect', 'domain_connect_status', 'domain_pricing', 'domain_register', 'domain_register_quote', 'domain_search', 'domain_status'].sort(),
+ );
+ });
+ it('gates registration behind confirm, price and idempotency', () => {
+ const t = byName.domain_register;
+ expect(t.annotations.destructiveHint).toBe(true);
+ expect(t.inputSchema.required).toEqual(expect.arrayContaining(['confirm_spend', 'expected_price_usd', 'idempotency_key', 'quote_id']));
+ });
+});
diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.json
index 2d64d1dbb..f4f772642 100644
--- a/tests/fixtures/mcp-golden-tools.json
+++ b/tests/fixtures/mcp-golden-tools.json
@@ -653,6 +653,72 @@
},
"schemaHash": "755f21dddd24"
},
+ "api/_mcp/tools/domains.js": [
+ {
+ "name": "domain_check",
+ "title": "Check one web domain",
+ "descHead": "One answer for one fully-qualified name: available or not, with a clear ",
+ "descHash": "6648209f239b",
+ "annotations": "ref:READ",
+ "schemaHash": "f3ac2146f00a"
+ },
+ {
+ "name": "domain_connect",
+ "title": "Connect a domain to an agent page",
+ "descHead": "Serve an agent's public page on a domain you registered here: creates th",
+ "descHash": "40bdfd435bb4",
+ "annotations": "ref:WRITE",
+ "schemaHash": "90cd775ae53a"
+ },
+ {
+ "name": "domain_connect_status",
+ "title": "Check a connected domain",
+ "descHead": "Whether a connected domain is live: the certificate state, the DNS names",
+ "descHash": "460ca38b913e",
+ "annotations": "ref:READ",
+ "schemaHash": "5a390848d5ae"
+ },
+ {
+ "name": "domain_pricing",
+ "title": "List domain TLD pricing",
+ "descHead": "The extensions Google Cloud Domains sells with their yearly registration",
+ "descHash": "7693f70918c9",
+ "annotations": "ref:READ",
+ "schemaHash": "3317b68691fa"
+ },
+ {
+ "name": "domain_register",
+ "title": "Register a domain (spends credits)",
+ "descHead": "Register the domain domain_register_quote priced, paying the exact yearl",
+ "descHash": "7e2697e2a4fd",
+ "annotations": "ref:MONEY",
+ "schemaHash": "55d848b7dc66"
+ },
+ {
+ "name": "domain_register_quote",
+ "title": "Quote a domain registration",
+ "descHead": "Price a domain registration without buying it: the exact yearly price, t",
+ "descHash": "1451c7595b98",
+ "annotations": "ref:WRITE",
+ "schemaHash": "a360feac8341"
+ },
+ {
+ "name": "domain_search",
+ "title": "Search web domains",
+ "descHead": "Suggest web domains for a name across TLDs, live from Google Cloud Domai",
+ "descHash": "6c8a2d58bccd",
+ "annotations": "ref:READ",
+ "schemaHash": "1684dd9c948b"
+ },
+ {
+ "name": "domain_status",
+ "title": "Poll a domain registration",
+ "descHead": "The state of a registration you started: registering, active (with its e",
+ "descHash": "f6cb05ee34ec",
+ "annotations": "ref:READ",
+ "schemaHash": "1f18b648f326"
+ }
+ ],
{
"name": "recall",
"title": "Recall",
diff --git a/tests/mcp-remote-annotations.test.js b/tests/mcp-remote-annotations.test.js
index 24ff50f3d..c7eb9045d 100644
--- a/tests/mcp-remote-annotations.test.js
+++ b/tests/mcp-remote-annotations.test.js
@@ -40,6 +40,7 @@ const CATALOGS = [
// agent_card_create buys a card or gift card with the agent's funds
// agent_card_reveal exposes a card's secret number or code, once
// agent_card_cancel, agent_card_withdraw close a card or pull its funds
+// domain_register buys a web domain from the user's credits, one year
// paired_launch launches a coin and its opening buy on Robinhood Chain
// paired_claim_fees signs and broadcasts the fee-collection transaction on
// Robinhood Chain (marked destructive on 2026-10-09)
@@ -66,7 +67,7 @@ const DESTRUCTIVE_TOOLS = new Set([
'delete_avatar', 'forget', 'delete_custom_skill', 'delete_agent', 'automation_delete',
'pay_and_call', 'persona_tip', 'persona_send',
'agent_card_create', 'agent_card_reveal', 'agent_card_cancel', 'agent_card_withdraw',
- 'paired_launch', 'paired_claim_fees', 'automation_trigger',
+ 'domain_register', 'paired_launch', 'paired_claim_fees', 'automation_trigger',
'create_marketplace_listing', 'delist_marketplace_listing', 'place_bid', 'buy_now',
'accept_marketplace_bid', 'withdraw_marketplace_bid',
'predictions_open', 'predictions_close', 'predictions_redeem',
diff --git a/vercel.json b/vercel.json
index e30b213f8..bac3c3fa2 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2538,6 +2538,10 @@
},
{
"src": "/showcase/?",
+ {
+ "src": "/domains/?",
+ "dest": "/domains.html"
+ },
"dest": "/app.html"
},
{
@@ -5550,6 +5554,10 @@
{
"src": "/discover/a/sol/([A-Za-z0-9]+)",
"dest": "/api/discover-detail?kind=solana&asset=$1"
+ {
+ "src": "/api/domains/([^/]+)",
+ "dest": "/api/domains/[action]?action=$1"
+ },
},
{
"src": "/discover/avatar/([^/]+)",
@@ -6777,6 +6785,10 @@
"path": "/api/cron/forge-finalize",
"schedule": "* * * * *"
},
+ {
+ "path": "/api/cron/domain-renewals",
+ "schedule": "17 6 * * *"
+ },
{
"path": "/api/llm/health",
"schedule": "0 * * * *"
diff --git a/vite.config.js b/vite.config.js
index 16a1848c5..307274ea9 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1022,6 +1022,7 @@ const appConfig = {
status: resolve(__dirname, 'pages/status.html'),
xr: resolve(__dirname, 'pages/xr.html'),
temporary: resolve(__dirname, 'pages/temporary.html'),
+ domains: resolve(__dirname, 'pages/domains.html'),
irl: resolve(__dirname, 'pages/irl.html'),
daily: resolve(__dirname, 'pages/daily.html'),
'ar-studio': resolve(__dirname, 'pages/ar-studio.html'),