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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(avatar-reconstruction): implement avatar regeneration job tracking and source constraint
nirholas2b569c8ff5d0
diff --git a/.env.example b/.env.exampleindex 95d04caf7..8a434298c 100644--- a/.env.example+++ b/.env.example@@ -680,6 +680,25 @@ CLUB_SWEEP_DUST_ATOMICS=5000# per-provider default when unset (defined in api/marketplace/[action].js).PREVIEW_MODEL=+# ── AWS Marketplace (SaaS listing) ───────────────────────────────────────────+# Credentials for a dedicated IAM user scoped to the four aws-marketplace:*+# actions used by api/_lib/aws-marketplace.js (ResolveCustomer, MeterUsage,+# BatchMeterUsage, GetEntitlements). Required when a Marketplace listing is+# live; safe to leave unset until then — env reads are lazy.+AWS_MP_ACCESS_KEY_ID=+AWS_MP_SECRET_ACCESS_KEY=+# Region of the seller account. AWS Marketplace metering only resolves in+# us-east-1 today regardless of where you host the app.+AWS_MP_REGION=us-east-1+# Product code assigned by AWS when the SaaS product is created in AMMP.+# Appears in the public product page URL and in every SNS notification payload.+AWS_MP_PRODUCT_CODE=+# Optional. ARN of the SNS topic that receives subscribe/unsubscribe+# notifications. When set, api/aws-marketplace/subscription.js rejects any+# SNS message whose TopicArn does not match (defense-in-depth on top of+# AWS's signature verification).+AWS_MP_SNS_TOPIC_ARN=+# ── Debug toggles (leave unset in prod) ──────────────────────────────────────# Set DEBUG=true to log knowledge-retrieval failures from widget chat.DEBUG=diff --git a/migrations/20260517170000_avatar_reconstruct.sql b/api/_lib/migrations/2026-05-17-avatar-reconstruct.sqlsimilarity index 100%rename from migrations/20260517170000_avatar_reconstruct.sqlrename to api/_lib/migrations/2026-05-17-avatar-reconstruct.sqldiff --git a/migrations/20260526000000_aws_marketplace_customers.sql b/api/_lib/migrations/2026-05-26-aws-marketplace-customers.sqlsimilarity index 100%rename from migrations/20260526000000_aws_marketplace_customers.sqlrename to api/_lib/migrations/2026-05-26-aws-marketplace-customers.sqldiff --git a/docs/internal/AWS_MARKETPLACE_LISTING.md b/docs/internal/AWS_MARKETPLACE_LISTING.mdnew file mode 100644index 000000000..82a094c84--- /dev/null+++ b/docs/internal/AWS_MARKETPLACE_LISTING.md@@ -0,0 +1,175 @@+# AWS Marketplace Listing — three.ws++Reference for the AMMP "Create new SaaS product" form. Path = free SaaS subscription (zero metering), shortest route to a public seller profile page.++## Strategy++- **Product type:** SaaS Subscription+- **Pricing:** Free tier — single $0.00 dimension. No tax/banking blockers, fastest AWS review.+- **EULA:** AWS Standard Contract for Marketplace (SCMP). Custom EULAs add weeks of legal review — only switch later when revenue justifies it.+- **Fulfillment:** Existing endpoints in `api/aws-marketplace/` ([register.js](../../api/aws-marketplace/register.js), [subscription.js](../../api/aws-marketplace/subscription.js), [link.js](../../api/aws-marketplace/link.js)). No new code required.+- **Goal:** Public seller profile live on `aws.amazon.com/marketplace/seller-profile?id=...`. Paid tiers added later as separate products on the same seller account.++## Listing copy++### Product title+`three.ws — Open-Source 3D AI Agent Platform`++### Short description (110 char hard limit)+`Create, embed, and register 3D AI agents on EVM and Solana. WebGL-native, LLM-driven, embed anywhere.`++### Long description (paste verbatim)++three.ws is an open-source platform for creating, embedding, and owning 3D AI agents. Drop a glTF or GLB model into the browser, attach an LLM brain, and the agent renders instantly in WebGL with full PBR materials, animations, and morph-target emotion blending. No plugins, no server-side processing.++The agent runtime is built around Anthropic's Claude. A structured tool-loop architecture gives agents native gestures (wave, look-at, play-clip), emotion expression, memory, and an extensible skill system. Skills are self-contained bundles loaded from IPFS, Arweave, or HTTP — anyone can author and distribute new agent capabilities.++Every agent can be registered on-chain for a permanent, verifiable identity:+- **EVM:** ERC-8004 token with IdentityRegistry, ReputationRegistry, and ValidationRegistry contracts+- **Solana:** Metaplex Core asset with SPL Memo–anchored reputation and validation attestations++Agents distribute as the `<agent-3d>` web component — drop one element into any page, no framework dependency. Five widget variants ship out of the box: turntable, animation gallery, talking agent, on-chain passport card, and hotspot tour. The platform also includes Widget Studio, an Embed Editor, and oEmbed support for rich social previews.++three.ws includes a full OAuth 2.1 authorization server, Model Context Protocol (MCP) endpoint over JSON-RPC, and x402 payment integration so agents can transact autonomously in USDC across Base, BSC, and Solana.++The entire stack — viewer, agent runtime, identity contracts, backend, and web component — is open source under Apache 2.0. Production deployment runs at three.ws on AWS `us-east-1`.++**Use cases:** AI-powered customer support avatars on any website; embedded 3D characters for entertainment, education, and games; on-chain agent identity for autonomous economic actors; programmatic 3D presence for AI systems via MCP.++### Highlights (3 bullet points, ~30 chars each)+- Browser-native 3D AI agents — no installs+- On-chain identity on EVM + Solana+- Embed anywhere with one `<agent-3d>` tag++### Categories+Primary: **AI Agents & Tools**+Secondary: **Generative AI**, **Machine Learning** → **Computer Vision**, **Software Development**++### Search keywords+`AI agent, 3D, avatar, LLM, Claude, web component, embed, glTF, GLB, three.js, WebGL, Solana, EVM, ERC-8004, Metaplex, MCP, OAuth, x402, agent runtime, open source`++### Resources / links+- **Product website:** `https://three.ws`+- **Documentation:** `https://three.ws/docs`+- **Source code:** `https://github.com/nirholas/three.ws`+- **Support contact:** `[email protected]`++### Media assets to upload+| Asset | Spec | Source |+|---|---|---|+| Product logo | PNG, 110×110, transparent | three.ws favicon/logo asset |+| Hero image | PNG/JPG, 1200×630 | `public/screenshots/viewer.png` |+| Screenshot 1 | 1200×800 | `public/screenshots/viewer.png` |+| Screenshot 2 | 1200×800 | `public/screenshots/studio.png` |+| Screenshot 3 | 1200×800 | `public/screenshots/discover.png` |+| Screenshot 4 | 1200×800 | `public/screenshots/create.png` |+| Demo video | YouTube, 60–90s | README hero video |++## Pricing model++**Single dimension, $0.00:**++| Dimension API name | Display name | Unit | Price |+|---|---|---|---|+| `community_edition` | Community Edition | Subscription | $0.00 / month |++This is a free SaaS subscription. AWS still requires a dimension, but `community_edition` priced at $0 keeps the listing free and skips banking/tax verification gates.++## Fulfillment configuration++**Fulfillment URL:** `https://three.ws/aws-marketplace/welcome`++This matches the existing handler at [src/aws-marketplace-welcome.js](../../src/aws-marketplace-welcome.js) and the page route at [pages/aws-marketplace/welcome](../../pages/aws-marketplace).++**Registration flow** (already implemented):+1. Buyer clicks Subscribe in AWS Marketplace → AWS POSTs `x-amzn-marketplace-token` (form-encoded) to the fulfillment URL+2. [api/aws-marketplace/register.js](../../api/aws-marketplace/register.js) receives token, calls `ResolveCustomer` via [api/_lib/aws-marketplace.js](../../api/_lib/aws-marketplace.js#L49), upserts row in `aws_marketplace_customers`+3. Buyer redirected to `/aws-marketplace/welcome` to link an existing three.ws account or create a new one+4. [api/aws-marketplace/link.js](../../api/aws-marketplace/link.js) sets `user_id` on the customer row++**Subscription lifecycle** (SNS):+1. AWS sends SNS notifications on subscribe-success, subscribe-fail, unsubscribe-pending, unsubscribe-success+2. [api/aws-marketplace/subscription.js](../../api/aws-marketplace/subscription.js) verifies signature via [verifySnsMessage](../../api/_lib/aws-marketplace.js#L141) (real cert fetch, hostname pinned to `*.amazonaws.com`, topic ARN check)+3. Updates `subscription_status` in `aws_marketplace_customers`++## Required AWS-side resources++The free listing still needs these provisioned in the seller AWS account before AMMP will accept the listing. The provisioning script in [scripts/aws-marketplace-provision.sh](../../scripts/aws-marketplace-provision.sh) creates all of them idempotently:++```bash+# Configure aws CLI with admin creds on the seller account first+bash scripts/aws-marketplace-provision.sh+```++The script:+1. Creates SNS topic `three-ws-marketplace-subscription` in `us-east-1`+2. Applies a topic policy allowing `aws-marketplace.amazonaws.com` to publish (scoped to the seller account via `aws:SourceAccount`)+3. Creates IAM user `three-ws-marketplace` with an inline policy granting the four required `aws-marketplace:*` actions+4. Issues an access key pair for that user++Output is printed at the end in Vercel env-var format, ready to paste.++### Product code++The script does **not** create the product code — AMMP assigns it when the SaaS product is created in the portal. After creating the product, copy the code into Vercel env as `AWS_MP_PRODUCT_CODE`. Used by `meterUsage` and `getEntitlements` in [api/_lib/aws-marketplace.js](../../api/_lib/aws-marketplace.js).++### Database migration++The customer + metering tables are defined in [api/_lib/migrations/2026-05-26-aws-marketplace-customers.sql](../../api/_lib/migrations/2026-05-26-aws-marketplace-customers.sql). Apply with:++```bash+npm run db:migrate+```++This must be run against the production Neon database **before** the limited listing is exercised end-to-end, otherwise `register.js` and `subscription.js` will 500 on first request.++## Future paid tiers (do not list yet)++Add as separate products on the same seller account once the free listing is public and the seller profile is live. Drafted here so the copy is ready when revenue motion kicks in.++### Pro — $99 / month per agent++**Title:** `three.ws Pro — Production 3D AI Agents`+**Short:** `Production hosting, voice cloning, on-chain identity, and priority support for embedded 3D AI agents.`+**Dimensions:**+| API name | Display | Unit | Price |+|---|---|---|---|+| `agent_seat` | Active agent | Per agent / month | $99.00 |+| `voice_clone_minutes` | Voice cloning | Per minute synthesized | $0.05 |+| `inference_tokens` | LLM tokens | Per 1M output tokens | $8.00 |++### Enterprise — Contract pricing++**Title:** `three.ws Enterprise — Self-Hosted 3D AI Agent Platform`+**Short:** `Self-hosted three.ws deployment with private LLM routing, SSO, audit logs, and dedicated support.`+**Pricing model:** SaaS Contracts (annual, custom-quoted via private offer). No metering — entitlement-checked via `getEntitlements`.++When adding these, the integration code in [api/_lib/aws-marketplace.js](../../api/_lib/aws-marketplace.js) already supports both metered (`meterUsage`) and contract (`getEntitlements`) flows. No code changes required, just new product codes added to env.++## Submission checklist++Before clicking "Submit for review" in AMMP:++- [ ] Migration applied: `npm run db:migrate` against production Neon+- [ ] Provisioning script run: `bash scripts/aws-marketplace-provision.sh` (creates SNS topic + IAM user + keys)+- [ ] All four Vercel env vars set: `AWS_MP_ACCESS_KEY_ID`, `AWS_MP_SECRET_ACCESS_KEY`, `AWS_MP_REGION=us-east-1`, `AWS_MP_SNS_TOPIC_ARN`+- [ ] Seller registration complete in AMMP (tax interview + bank account verified)+- [ ] Public seller profile saved (name "three.ws", logo, description, website)+- [ ] Listing copy pasted from the sections above+- [ ] Logo + 4 screenshots + demo video uploaded+- [ ] Categories + keywords selected+- [ ] Fulfillment URL set to `https://three.ws/aws-marketplace/welcome`+- [ ] Pricing: single `community_edition` dimension at $0.00+- [ ] EULA: AWS Standard Contract for Marketplace selected+- [ ] Support contact: `[email protected]`+- [ ] After product creation: copy assigned product code into `AWS_MP_PRODUCT_CODE` in Vercel++## Review flow++1. AMMP creates a **limited product** (private, only your test account can subscribe)+2. Run end-to-end test: subscribe from a separate AWS account → token POSTs to register endpoint → SNS subscribe-success arrives at subscription endpoint → buyer lands on `/aws-marketplace/welcome` → account links+3. Submit for **public publication** with link to successful limited test+4. AWS reviews copy, EULA, integration health — typical 5–10 business days+5. On approval, public seller profile page goes live automatically++Once live, the seller profile URL is `https://aws.amazon.com/marketplace/seller-profile?id=<seller-id>` — that's your public sellers page.diff --git a/public/studio/launch-panel.js b/public/studio/launch-panel.jsindex 766a6769d..43daa2e4c 100644--- a/public/studio/launch-panel.js+++ b/public/studio/launch-panel.js@@ -1053,12 +1053,14 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewViewconst tx = VersionedTransaction.deserialize(Uint8Array.from(atob(prep.tx_base64), (c) => c.charCodeAt(0)),);+ // Phantom Lighthouse requires the wallet to sign FIRST when there are+ // multiple signers; additional signers must sign afterward.+ const signed = await w.signTransaction(tx);if (prep.mint_secret_key_b64) {- tx.sign([Keypair.fromSecretKey(+ signed.sign([Keypair.fromSecretKey(Uint8Array.from(atob(prep.mint_secret_key_b64), (c) => c.charCodeAt(0)),)]);}- const signed = await w.signTransaction(tx);// Send + poll confirmation (75s timeout)s.phase = 'confirming'; s.phaseLabel = 'Confirming on-chain…'; render();diff --git a/publish/src/agent-skills-pumpfun.js b/publish/src/agent-skills-pumpfun.jsindex 5bd3745c4..e6fd78c06 100644--- a/publish/src/agent-skills-pumpfun.js+++ b/publish/src/agent-skills-pumpfun.js@@ -67,8 +67,10 @@ async function sendIxs({ web3, connection, wallet, payer, instructions, extraSigconst { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();const tx = new web3.Transaction({ feePayer: payer, blockhash, lastValidBlockHeight });tx.add(...instructions);- if (extraSigners.length) tx.partialSign(...extraSigners);+ // Phantom Lighthouse requires the wallet to sign FIRST when there are+ // multiple signers; additional signers must sign afterward.const signed = await wallet.signTransaction(tx);+ if (extraSigners.length) signed.partialSign(...extraSigners);const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false });await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight });return sig;diff --git a/publish/src/erc8004/solana-deploy.js b/publish/src/erc8004/solana-deploy.jsindex 49b971cfb..b6135f703 100644--- a/publish/src/erc8004/solana-deploy.js+++ b/publish/src/erc8004/solana-deploy.js@@ -154,21 +154,21 @@ export async function runSolanaDeploy({ agent, network, vanity }) {const prep = await prepResp.json();const tx = decodeBase64Tx(prep.tx_base64);- // If we used a vanity keypair, the server built the tx with a noop signer- // for the asset slot — we must fill it in here before the wallet signs.- // VersionedTransaction.sign() only modifies signatures whose pubkey matches- // a provided signer, so the wallet sig slot is preserved as zero for Phantom.- if (vanityKeypair && tx instanceof VersionedTransaction) {- tx.sign([vanityKeypair]);- } else if (vanityKeypair && tx instanceof Transaction) {- tx.partialSign(vanityKeypair);- }-// Always sign locally and submit via our Helius-backed proxy. Wallet// `signAndSendTransaction` routes through the wallet's own RPC, which// returns 403 "Access forbidden" intermittently on mainnet.+ // Phantom Lighthouse requires the wallet to sign FIRST when there are+ // multiple signers; if a vanity keypair is in play, the server built the tx+ // with a noop signer for the asset slot and we fill it in after Phantom.+ // VersionedTransaction.sign() / Transaction.partialSign() only update the+ // matching signer's slot, so Phantom's signature is preserved.const endpoint = RPC[network] || RPC.mainnet;const signed = await wallet.signTransaction(tx);+ if (vanityKeypair && signed instanceof VersionedTransaction) {+ signed.sign([vanityKeypair]);+ } else if (vanityKeypair && signed instanceof Transaction) {+ signed.partialSign(vanityKeypair);+ }const conn2 = new Connection(endpoint, 'confirmed');const raw = signed.serialize();const signature = await conn2.sendRawTransaction(raw, {diff --git a/publish/src/pump/pump-modals.js b/publish/src/pump/pump-modals.jsindex 6ab94d72b..a596aff68 100644--- a/publish/src/pump/pump-modals.js+++ b/publish/src/pump/pump-modals.js@@ -163,8 +163,10 @@ async function signAndSend(txBase64, { extraSigners = [], network = 'mainnet' }const tx = VersionedTransaction.deserialize(Uint8Array.from(atob(txBase64), (c) => c.charCodeAt(0)),);- for (const kp of extraSigners) tx.sign([kp]);+ // Phantom Lighthouse requires the wallet to sign FIRST when there are+ // multiple signers; additional signers must sign afterward.const signed = await wallet.signTransaction(tx);+ for (const kp of extraSigners) signed.sign([kp]);const conn = new Connection(RPC(network), 'confirmed');const sig = await conn.sendRawTransaction(signed.serialize(), {skipPreflight: false,@@ -210,8 +212,10 @@ export async function signAndSendVTx(toSign = new VersionedTransaction(merged);}- for (const kp of extraSigners) toSign.sign([kp]);+ // Phantom Lighthouse requires the wallet to sign FIRST when there are+ // multiple signers; additional signers must sign afterward.const signed = await w.signTransaction(toSign);+ for (const kp of extraSigners) signed.sign([kp]);const sig = await conn.sendRawTransaction(signed.serialize(), {skipPreflight: false,});diff --git a/scripts/_audit-schema.mjs b/scripts/_audit-schema.mjsnew file mode 100644index 000000000..fca5817b0--- /dev/null+++ b/scripts/_audit-schema.mjs@@ -0,0 +1,84 @@+#!/usr/bin/env node+// One-shot audit: verifies each schema object from root migrations/ exists in DB.+import { neon } from '@neondatabase/serverless';++const sql = neon(process.env.DATABASE_URL);++const tables = [+ 'skill_purchases',+ 'agent_payment_intents',+ 'marketplace_themes',+ 'avatar_regen_jobs',+ 'user_subdomains',+ 'asset_prices',+ 'asset_purchases',+ 'asset_purchase_receipts',+];++const columns = [+ ['users', 'referral_code'],+ ['users', 'referred_by_id'],+ ['users', 'referral_earnings_total'],+ ['users', 'provider_keys'],+ ['avatars', 'featured'],+ ['avatars', 'view_count'],+ ['avatars', 'usdz_key'],+ ['avatars', 'halfbody_key'],+];++async function tableExists(name) {+ const r = await sql`+ select 1 from information_schema.tables+ where table_schema = 'public' and table_name = ${name}+ `;+ return r.length > 0;+}++async function columnExists(table, column) {+ const r = await sql`+ select 1 from information_schema.columns+ where table_schema = 'public' and table_name = ${table} and column_name = ${column}+ `;+ return r.length > 0;+}++const out = { tables: {}, columns: {} };+for (const t of tables) out.tables[t] = await tableExists(t);+for (const [t, c] of columns) out.columns[`${t}.${c}`] = await columnExists(t, c);++const nullableRow = await sql`+ select is_nullable from information_schema.columns+ where table_schema='public' and table_name='avatar_regen_jobs' and column_name='source_avatar_id'+`;+out['avatar_regen_jobs.source_avatar_id.nullable'] =+ nullableRow[0]?.is_nullable === 'YES';++const ck = await sql`+ select pg_get_constraintdef(c.oid) as def+ from pg_constraint c+ join pg_class t on t.oid = c.conrelid+ where t.relname = 'avatars' and c.conname like 'avatars_source_check%'+`;+out['avatars.source_check.def'] = ck[0]?.def || null;+out['avatars.source_check.allows_reconstruct'] =+ ck[0]?.def?.includes('reconstruct') ?? false;++const indexes = [+ 'idx_users_referral_code',+ 'idx_users_referred_by_id',+ 'idx_avatars_featured',+ 'idx_avatars_usdz_key',+ 'idx_avatar_regen_jobs_user',+ 'idx_avatar_regen_jobs_status',+ 'user_subdomains_label_parent',+ 'user_subdomains_user',+ 'asset_prices_item_unique',+ 'asset_purchases_buyer',+];+out.indexes = {};+for (const name of indexes) {+ const r = await sql`select 1 from pg_indexes where schemaname='public' and indexname=${name}`;+ out.indexes[name] = r.length > 0;+}++console.log(JSON.stringify(out, null, 2));diff --git a/scripts/aws-marketplace-provision.sh b/scripts/aws-marketplace-provision.shnew file mode 100755index 000000000..307468081--- /dev/null+++ b/scripts/aws-marketplace-provision.sh@@ -0,0 +1,122 @@+#!/usr/bin/env bash+# Provision AWS resources required for the AWS Marketplace SaaS listing.+#+# Creates:+# 1. SNS topic `three-ws-marketplace-subscription` (us-east-1)+# 2. Topic policy allowing aws-marketplace.amazonaws.com to publish+# 3. IAM user `three-ws-marketplace` with the four marketplace actions+# 4. Access key pair for that user+#+# Prereqs:+# - aws CLI v2 configured with admin creds on the seller AWS account+# - jq installed+#+# Outputs are printed at the end; paste them into:+# - AMMP product page (SNS Topic ARN)+# - Vercel project env vars (AWS_MP_ACCESS_KEY_ID, AWS_MP_SECRET_ACCESS_KEY)+#+# Idempotent: re-running is safe — existing resources are reused, only new+# access keys are issued if the user has fewer than 2 active keys.++set -euo pipefail++REGION="us-east-1"+TOPIC_NAME="three-ws-marketplace-subscription"+USER_NAME="three-ws-marketplace"+POLICY_NAME="three-ws-marketplace-policy"++ACCOUNT_ID="$(aws sts get-caller-identity --query Account --output text)"+echo "[*] Provisioning on AWS account $ACCOUNT_ID in $REGION"++# ─── 1. SNS topic ────────────────────────────────────────────────────────────+echo "[*] Creating SNS topic $TOPIC_NAME (idempotent)"+TOPIC_ARN="$(aws sns create-topic \+ --name "$TOPIC_NAME" \+ --region "$REGION" \+ --query TopicArn \+ --output text)"+echo " Topic ARN: $TOPIC_ARN"++# ─── 2. Topic policy: allow AWS Marketplace to publish ───────────────────────+echo "[*] Applying topic policy (allow aws-marketplace.amazonaws.com to publish)"+POLICY_JSON=$(cat <<EOF+{+ "Version": "2012-10-17",+ "Statement": [{+ "Sid": "AllowMarketplacePublish",+ "Effect": "Allow",+ "Principal": { "Service": "aws-marketplace.amazonaws.com" },+ "Action": "sns:Publish",+ "Resource": "$TOPIC_ARN",+ "Condition": {+ "StringEquals": { "aws:SourceAccount": "$ACCOUNT_ID" }+ }+ }]+}+EOF+)+aws sns set-topic-attributes \+ --topic-arn "$TOPIC_ARN" \+ --attribute-name Policy \+ --attribute-value "$POLICY_JSON" \+ --region "$REGION" >/dev/null++# ─── 3. IAM user + policy ────────────────────────────────────────────────────+echo "[*] Creating IAM user $USER_NAME (idempotent)"+if ! aws iam get-user --user-name "$USER_NAME" >/dev/null 2>&1; then+ aws iam create-user --user-name "$USER_NAME" >/dev/null+fi++echo "[*] Attaching inline policy $POLICY_NAME"+aws iam put-user-policy \+ --user-name "$USER_NAME" \+ --policy-name "$POLICY_NAME" \+ --policy-document '{+ "Version": "2012-10-17",+ "Statement": [{+ "Effect": "Allow",+ "Action": [+ "aws-marketplace:ResolveCustomer",+ "aws-marketplace:BatchMeterUsage",+ "aws-marketplace:MeterUsage",+ "aws-marketplace:GetEntitlements"+ ],+ "Resource": "*"+ }]+ }'++# ─── 4. Access keys ──────────────────────────────────────────────────────────+EXISTING_KEYS="$(aws iam list-access-keys --user-name "$USER_NAME" --query 'length(AccessKeyMetadata)' --output text)"+if [ "$EXISTING_KEYS" -ge 2 ]; then+ echo "[!] User already has $EXISTING_KEYS access keys (AWS limit is 2)."+ echo " Delete an existing key first if you need a new one."+ KEY_OUTPUT=""+else+ echo "[*] Issuing new access key"+ KEY_OUTPUT="$(aws iam create-access-key --user-name "$USER_NAME")"+fi++echo ""+echo "════════════════════════════════════════════════════════════════════════"+echo "DONE. Paste these values into Vercel env vars + AMMP."+echo "════════════════════════════════════════════════════════════════════════"+echo ""+echo "AWS_MP_SNS_TOPIC_ARN=$TOPIC_ARN"+echo "AWS_MP_REGION=$REGION"+if [ -n "$KEY_OUTPUT" ]; then+ ACCESS_KEY_ID="$(echo "$KEY_OUTPUT" | jq -r .AccessKey.AccessKeyId)"+ SECRET_ACCESS_KEY="$(echo "$KEY_OUTPUT" | jq -r .AccessKey.SecretAccessKey)"+ echo "AWS_MP_ACCESS_KEY_ID=$ACCESS_KEY_ID"+ echo "AWS_MP_SECRET_ACCESS_KEY=$SECRET_ACCESS_KEY"+ echo ""+ echo "[!] The secret access key is shown ONCE. Save it now."+fi+echo ""+echo "AWS_MP_PRODUCT_CODE = <assigned by AMMP after product creation>"+echo ""+echo "Next steps:"+echo " 1. Set the env vars above in Vercel (production + preview)"+echo " 2. In AMMP → Products → SaaS → Create new SaaS product"+echo " 3. Paste the SNS Topic ARN into the product's notification topic field"+echo " 4. AMMP will assign the AWS_MP_PRODUCT_CODE — add it to Vercel"+echo " 5. Submit limited (private) listing for end-to-end test"