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(chat): stop refusing questions on the platform's behalf; the model's own judgment is the only one
nirholas33df2f76ff57
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 85a932322..9c1069f67 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -1484,7 +1484,7 @@ Tiered memory architecture (Letta/MemGPT model):Returns `allow | review | block`. SHA-256 hash-chained audit records. Gates all autonomous SOL transfer actions.-**NVIDIA NemoGuard** (`api/_lib/moderation.js`): lightweight anonymous-user moderation via `llama-3.1-nemoguard-8b-content-safety`.+**NVIDIA NemoGuard** (`api/_lib/publish-safety.js`): brand-safety classifier (`llama-3.1-nemoguard-8b-content-safety`) for content the platform PUBLISHES outward, scoped to the Sketchfab showcase cron. It does not screen chat: no three.ws surface filters what a user may ask (owner directive 2026-08-07). Fail-open.---@@ -2362,7 +2362,7 @@ The shared library is **~370 modules + 19 subpackages**. Beyond the core modules| Wallet & custody | `agent-wallet.js` · `avatar-wallet.js` · `solana-wallet.js` · `agent-usdc-transfer.js` · `solana-transfer.js` · `evm-transfer.js` · `balances.js` · `custody-proof.js` · `wallet-anomaly.js` · `wallet-capabilities.js` · `wallet-intents.js` · `secret-box.js` · `crypto.js` · `resolve-recipient.js` || x402 & payments | `x402.js` · `x402-spec.js` · `x402-paid-endpoint.js` · `x402-buyer-fetch.js` · `x402-buyer-axios.js` · `x402-user-payer.js` · `x402-bsc-direct.js` · `x402-solana-confirm.js` · `x402-spending-cap.js` · `x402-spending-ledger.js` · `x402-spending-price.js` · `x402-prices.js` · `x402-errors.js` · `x402-builder-code.js` · `evm-payment-verify.js` · `fee.js` · `splits.js` · `payout.js` · `credits.js` · `credit-deposit.js` · `metering.js` · `usage.js` · subdir `x402/` || Agent runtime & economy | `agent-economy.js` · `agent-delegate.js` · `agent-spend-policy.js` · `spend-policy-compiler.js` · `spend-policy-rules.js` · `agent-trade-guards.js` · `agent-strategy-runtime.js` · `agent-paid-services.js` · `agent-pumpfun.js` · `agent-mirror.js` · `agent-labor.js` · `genome.js` · `genome-agent.js` · `networth-model.js` · `patronage.js` · `monetization.js` · `treasury-autopilot.js` · subdir `a2a/` |-| Memory & AI | `memory-store.js` · `memory-entities.js` · `embeddings.js` · `embedding-math.js` · `agent-embeddings.js` · `chunker.js` · `rerank.js` · `reflection.js` · `brain-bundle.js` · `brain-anchor.js` · `brain-sign.js` · `llm.js` · `llm-health.js` · `llm-pricing.js` · `chat-models.js` · `provider-health.js` · `provider-keys.js` · `orchestrate.js` · `watsonx.js` · `watsonx-forecast.js` · `granite-guardian.js` · `moderation.js` · `vision.js` · `text-extract.js` · `strip-reasoning.js` · `reasoning-ledger.js` · `circulation.js` · `circulation-personas.js` · `persona-store.js` |+| Memory & AI | `memory-store.js` · `memory-entities.js` · `embeddings.js` · `embedding-math.js` · `agent-embeddings.js` · `chunker.js` · `rerank.js` · `reflection.js` · `brain-bundle.js` · `brain-anchor.js` · `brain-sign.js` · `llm.js` · `llm-health.js` · `llm-pricing.js` · `chat-models.js` · `provider-health.js` · `provider-keys.js` · `orchestrate.js` · `watsonx.js` · `watsonx-forecast.js` · `granite-guardian.js` · `publish-safety.js` · `vision.js` · `text-extract.js` · `strip-reasoning.js` · `reasoning-ledger.js` · `circulation.js` · `circulation-personas.js` · `persona-store.js` || Voice & 3D media | `tts-nvidia.js` · `tts-voices.js` · `asr-nvidia.js` · `a2f-nvidia.js` · `elevenlabs.js` · `render-clip.js` · `render-glb.js` · `glb-compress.js` · `glb-inspect.js` · `glb-quality.js` · `glb-themer.js` · `bake.js` · `model-inspect.js` · `rig-inspect.js` · `auto-rig.js` · `auto-rig-eligibility.js` · `avatars.js` · `avatar-render.js` · `avatar-agent.js` · `avatar-alt-text.js` · `accessories.js` · `cosmetics.js` · `cosmetics-economy.js` · `cosmetics-ownership.js` · `avaturn-headless.js` · `avaturn-seed.js` · `fetch-model.js` · subdirs `a2f-protos/`, `riva-protos/` || Forge (3D gen) | `forge-tiers.js` · `forge-options.js` · `forge-scale.js` · `forge-cache.js` · `forge-store.js` · `forge-events.js` · `forge-health.js` · `forge-lane-health.js` · `forge-image-validate.js` · `forge-job-token.js` · `forge-provider-key.js` · `forge-consumption-payment.js` · `forge-high-payment.js` · `regen-provider.js` · `reconstruct-finalize.js` || Pump / market / oracle | `pump.js` · `pump-launch.js` · `pump-quote.js` · `pump-swap-ix.js` · `pump-trade-args.js` · `pump-pricing.js` · `pump-platform-fee.js` · `pump-vanity.js` · `pump-claims.js` · `pump-go.js` · `pump-alert-eval.js` · `pump-alert-runner.js` · `pump-launch-feed.js` · `pumpfun-ws-feed.js` · `pumpfun-mcp.js` · `smart-money.js` · `birdeye.js` · `gmgn-feed.js` · `helius.js` · `token-market.js` · `token-metadata.js` · `aixbt.js` · `trade-firewall.js` · `anomaly-events.js` · subdirs `pump-intel/`, `oracle/`, `sniper/`, `market/`, `coin/`, `token/` |@@ -3257,7 +3257,7 @@ All **150+ directories** under `api/` plus many top-level single-file endpoints.**~357 top-level `.js` modules** + **21 sub-packages** (`a2a`, `a2f-protos`, `club`, `coin`, `copy`, `evm`, `format`, `launch`, `market`, `migrations`, `oracle`, `pay`, `pricing`, `pump-intel`, `riva-protos`, `services`, `sniper`, `solana`, `token`, `trust`, `x402`). The `x402/` sub-package now carries a `pipelines/` fleet for the autonomous economy. Nothing in `_lib` is itself a route. Grouped by domain:- **DB / cache / storage / infra:** `db.js`, `db-retry.js`, `schema.sql`, `migrations/`, `cache.js`, `redis.js`, `redis-usage.js`, `skill-price-cache.js`, `r2.js`, `ipfs-pin.js`, `storage-mode.js`, `forge-cache.js`, `qstash.js`, `resilience.js` (cockatiel), `sse-poll-breaker.js`, `env.js`, `http.js`, `http-params.js`, `ids.js`, `sentry.js`, `axiom.js`, `rate-limit.js`.-- **Auth / security / crypto:** `auth.js`, `account-auth.js`, `admin.js`, `zauth.js`, `crypto.js`, `secret-box.js` (AES-256-GCM), `provider-keys.js`, `csrf.js`, `ssrf.js`, `ssrf-guard.js`, `fetch-model.js`, `pii.js`, `moderation.js` (NemoGuard), `granite-guardian.js`, `identity-integrity.js`, `siwe.js`, `siws.js`, `siwx-server.js`, `siwx-storage.js`, `saml.js`, `privy.js`, `audit.js`.+- **Auth / security / crypto:** `auth.js`, `account-auth.js`, `admin.js`, `zauth.js`, `crypto.js`, `secret-box.js` (AES-256-GCM), `provider-keys.js`, `csrf.js`, `ssrf.js`, `ssrf-guard.js`, `fetch-model.js`, `pii.js`, `publish-safety.js` (NemoGuard, publish-time only), `granite-guardian.js`, `identity-integrity.js`, `siwe.js`, `siws.js`, `siwx-server.js`, `siwx-storage.js`, `saml.js`, `privy.js`, `audit.js`.- **Solana / on-chain:** `solana/` (connection, rpc-fallback, confirm, gasless-tx, idl, programs, sdk-bridge), `solana-wallet.js`, `solana-signers.js`, `solana-transfer.js`, `solana-collection.js`, `solana-token-meta.js`, `token-metadata.js`, `onchain.js`, `onchain-deploy.js`, `agent-registry.js`, `agent-invocation-onchain.js`; attestations: `attest-event.js`, `sas.js`, `solana-attestations.js`, `solana-validation-attest.js`, `validation-attest.js`, `tournament-attest.js`, `trader-score-attest.js`, `ledger-anchor.js`, `brain-anchor.js`, `custody-proof.js`; `helius.js`, `balances.js`, `three-brand.js`, `threews-sns.js`.- **EVM / x402:** `x402/` (a2a-client/server, access-control, api-keys, audit-log, auth-hints, bazaar-client/helpers, idempotency-cache, offer-receipt-issuer/server, payment-identifier-client/server, paywall-handler, receipt-storage · **economy layer:** self-facilitator, pay, solana-payer, autonomous-registry, revenue-analytics, revenue-reconciliation, user-activity-analytics, agent-leaderboard-store, wallet-balance-monitor, granite-health, three-signal-store, sniper-analytics-store, scene-capture-processor, `pipelines/*`), `x402.js`, `x402-spec.js`, `x402-paid-endpoint.js`, `x402-prices.js`, `x402-errors.js`, `x402-buyer-fetch.js`, `x402-buyer-axios.js`, `x402-user-payer.js`, `x402-offer-receipt.js`, `x402-spending-cap/-ledger/-price.js`, `x402-solana-confirm.js`, `x402-bsc-direct.js`, `x402-builder-code.js`, `pay/` (payment-session, spend-governor), `evm/rpc.js`, `evm-transfer.js`, `evm-payment-verify.js`, `erc8004-chains.js`, `a2a/` (cart-mandate, mandate, reputation-gate, spend-ledger), `aws-marketplace.js`, `aws-marketplace-bridge.js`.- **LLM / embeddings / vision / voice:** `llm.js`, `chat-models.js`, `llm-pricing.js`, `llm-health.js`, `provider-health.js`, `strip-reasoning.js`, `orchestrate.js`, `watsonx.js`, `watsonx-forecast.js`, `embeddings.js`, `agent-embeddings.js`, `embedding-math.js`, `chunker.js`, `text-extract.js`, `rerank.js`, `vision.js`, `avatar-alt-text.js`, `forge-image-validate.js`, `a2f-nvidia.js`, `asr-nvidia.js`, `tts-nvidia.js`, `tts-voices.js`, `elevenlabs.js`, `a2f-protos/`, `riva-protos/`.@@ -3335,7 +3335,7 @@ Tiers: **CRITICAL** = `req()` in `api/_lib/env.js` (cold-start throw) or prod-fa- **Solana / on-chain:** `SOLANA_RPC_URL` (+aliases `SOLANA_RPC`/`SOLANA_MAINNET_RPC`/`NEXT_PUBLIC_SOLANA_RPC_URL`), `SOLANA_RPC_URL_DEVNET`/`SOLANA_DEVNET_RPC`, `SOLANA_RPC_URLS`/`_FALLBACK_URLS`, `HELIUS_API_KEY`/`HELIUS_WEBHOOK_AUTH`, `SOLANA_USDC_MINT`/`DEVNET_USDC_MINT`, `NEXT_PUBLIC_SOLANA_ALT_ADDRESS`, `TREASURY_KEYPAIR`/`PLATFORM_TREASURY_KEYPAIR`, `MAINNET_RPC_URL`, `JITO_BLOCK_ENGINE_URL`/`JITO_BUNDLE_URL`/`JITO_TIP_SOL`, `ALCHEMY_API_KEY`/`ANKR_API_KEY`/`DRPC_API_KEY`, `SOLANA_AGENT_COLLECTION_MAINNET`/`_DEVNET`/`_AUTHORITY_KEY`, `THREEWS_SOL_PARENT_DOMAIN`/`_PARENT_SECRET_BASE58`, `STOREFRONT_ORIGIN`, `BUBBLEGUM_MERKLE_TREE`/`_TREE_AUTHORITY`, `NFT_STORAGE_TOKEN`/`WEB3_STORAGE_TOKEN`/`PINATA_JWT`/`FILEBASE_KEY`/`_SECRET`, `BTC_INSCRIPTION_RECEIVE_ADDRESS`/`ORDINALSBOT_API_KEY`/`_BASE_URL`, `AGENC_RPC_URL`/`AGENC_DEVNET_RPC_URL`/`AGENC_BRIDGE_URL`.- **EVM / x402:** `AGENT_RELAYER_ADDRESS`, `PERMISSIONS_RELAYER_ENABLED`, `BASE_RPC_URL`/`BASE_SEPOLIA_RPC_URL`/`SEPOLIA_RPC_URL`, `RPC_URL_<CHAINID>`, `EVM_RPC_URL`, `EVM_PRIVATE_KEY`/`EVM_TREASURY_PRIVATE_KEY`/`PRIVATE_KEY`, `EVM_MIN_CONFIRMATIONS`, `X402_ASSET_MINT_SOLANA`/`X402_ASSET_ADDRESS_BASE`/`_ARBITRUM`/`_BSC`, `X402_MAX_AMOUNT_REQUIRED`, `X402_IDEMPOTENCY_TTL_SECONDS`, `X402_FACILITATOR_URL_SOLANA`/`_BASE`/`_TOKEN_*`/`_TIMEOUT_MS`, `CDP_API_KEY_ID`/`_SECRET`, `X402_CDP_FACILITATOR_URL`, `X402_ACCEPT_THREE_SOLANA`/`X402_THREE_AMOUNT_SOLANA`, `X402_EVM_NETWORKS`, `X402_BUILDER_CODE_APP`/`_WALLET`, `X402_MAX_PER_CALL_ATOMIC`/`_PER_HOUR_ATOMIC`/`_PER_DAY_ATOMIC`, `INTERNAL_API_KEY`, `OFFER_RECEIPT_SIGNING_PRIVATE_KEY`/`_FORMAT`/`_JWK`/`_JWS_ALG`, `SERVER_DOMAIN`, `A2A_MANDATE_SECRET`, `A2A_PAYER_PRIVATE_KEY`/`A2A_PAYER_SOLANA_SECRET`, `A2A_REPUTATION_RPC_URL`, `VALIDATOR_PRIVATE_KEY`, `ETHERSCAN_API_KEY`/`BASESCAN_API_KEY`, `ERC8004_CRAWL_LOOKBACK`, `SPLITS_SIGNER_PRIVATE_KEY`, `MARKETPLACE_PAYER_KEYPAIR`/`MARKETPLACE_PLATFORM_FEE_BPS`/`_WALLET`, `ZAUTH_API_KEY`/`_DEBUG`/`_API_ENDPOINT`/`_SCAN_URL`/`_CIRCUIT_*`/`_REFUND_*`.- **MCP / bridge:** `MCP_RESOURCE`, `MCP_REGISTRY_TOKEN`, `MCP_AGENT_TALK_ENDPOINT`, `MCP_POSE_PREVIEW_BASE`, `MCP_SVM_PAYMENT_ADDRESS`, `MCP_VANITY_PRICE_USD`, `MCP_BRIDGE_EVM_PRIVATE_KEY`/`_SVM_PRIVATE_KEY`, `MCP_BRIDGE_ALLOWED_HOSTS`/`_ALLOWED_PAYTO`/`_ALLOW_HTTP`, `MCP_BRIDGE_BAZAAR_URL`/`_DISCOVER_LIMIT`, `MCP_BRIDGE_MAX_DEPOSIT_ATOMIC`/`_MAX_PRICE_PER_CALL_ATOMIC`/`_MAX_TOTAL_ATOMIC`, `X402_BRIDGE_PORT`/`_ALLOWED_ENDPOINT_ORIGINS`/`_MAX_USDC_MICROS`.-- **LLM providers:** `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`/`OPENAI_BASE_URL`, `GROQ_API_KEY`, `NVIDIA_API_KEY`, `OPENROUTER_API_KEY`/`OPENROUTER_FALLBACK_KEYS`, `SAMBANOVA_API_KEY`, `MISTRAL_API_KEY`, `ZAI_API_KEY`, `SILICONFLOW_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`/`CLOUDFLARE_AI_API_TOKEN`, `DASHSCOPE_API_KEY`, `MODELSCOPE_API_KEY`, `GEMINI_API_KEY`/`GOOGLE_API_KEY`/`GOOGLE_GENAI_API_KEY`/`GOOGLE_CLOUD_PROJECT`, `WATSONX_API_KEY`/`_PROJECT_ID`/`_SPACE_ID`/`_URL`/`_MODEL_ID`/`_API_VERSION`/`_GUARDIAN_MODEL_ID`/`_VISION_MODEL_ID`/`_ORCHESTRATE_*`, `GUARDIAN_SEND_CAP_USD`/`GUARDIAN_DISABLE`, `LIVEPEER_API_KEY`, `LONGCAT_WORKER_URL`/`_KEY`, `OMNI_URL`/`NIM_URL`, `CHAT_MODEL`/`CHAT_MAX_TOKENS`/`CHAT_URL`, `KNOWLEDGE_RERANK_ENABLED`, `ANON_MODERATION_DISABLED`/`_MODEL`/`_TIMEOUT_MS`, `VOYAGE_API_KEY`, `BRAVE_API_KEY`, `TAVILY_API_KEY`/`EXA_API_KEY`/`SERPER_API_KEY`/`SERPAPI_API_KEY`, `BIRDEYE_API_KEY`/`GMGN_COOKIE`, `NEYNAR_API_KEY`, `TWITTER_BEARER_TOKEN`/`X_API_BEARER`, `AIXBT_API_KEY`/`_API_BASE`.+- **LLM providers:** `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`/`OPENAI_BASE_URL`, `GROQ_API_KEY`, `NVIDIA_API_KEY`, `OPENROUTER_API_KEY`/`OPENROUTER_FALLBACK_KEYS`, `SAMBANOVA_API_KEY`, `MISTRAL_API_KEY`, `ZAI_API_KEY`, `SILICONFLOW_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`/`CLOUDFLARE_AI_API_TOKEN`, `DASHSCOPE_API_KEY`, `MODELSCOPE_API_KEY`, `GEMINI_API_KEY`/`GOOGLE_API_KEY`/`GOOGLE_GENAI_API_KEY`/`GOOGLE_CLOUD_PROJECT`, `WATSONX_API_KEY`/`_PROJECT_ID`/`_SPACE_ID`/`_URL`/`_MODEL_ID`/`_API_VERSION`/`_GUARDIAN_MODEL_ID`/`_VISION_MODEL_ID`/`_ORCHESTRATE_*`, `GUARDIAN_SEND_CAP_USD`/`GUARDIAN_DISABLE`, `LIVEPEER_API_KEY`, `LONGCAT_WORKER_URL`/`_KEY`, `OMNI_URL`/`NIM_URL`, `CHAT_MODEL`/`CHAT_MAX_TOKENS`/`CHAT_URL`, `KNOWLEDGE_RERANK_ENABLED`, `PUBLISH_SAFETY_DISABLED`/`_MODEL`/`_TIMEOUT_MS`, `VOYAGE_API_KEY`, `BRAVE_API_KEY`, `TAVILY_API_KEY`/`EXA_API_KEY`/`SERPER_API_KEY`/`SERPAPI_API_KEY`, `BIRDEYE_API_KEY`/`GMGN_COOKIE`, `NEYNAR_API_KEY`, `TWITTER_BEARER_TOKEN`/`X_API_BEARER`, `AIXBT_API_KEY`/`_API_BASE`.- **Voice / 3D gen:** `ELEVENLABS_API_KEY`, `NVIDIA_ASR_FUNCTION_ID`/`NVIDIA_A2F_FUNCTION_ID`/`NVIDIA_COSMOS_INVOKE_URL`, `LIVEKIT_API_KEY`/`_SECRET`/`_SERVER_URL`, `GCP_PROJECT`/`GCP_REGION`/`GCP_SERVICE_ACCOUNT_JSON`, `GCP_RECONSTRUCTION_URL`/`_KEY`, `GCP_TRIPOSG_URL`/`GCP_HUNYUAN3D_URL`/`GCP_REMESH_URL`/`GCP_TEXTURE_URL`/`GCP_STYLIZE_URL`/`GCP_SEGMENT_URL`/`GCP_REMBG_URL`/`GCP_TEXT2MOTION_URL`, `HF_TOKEN`/`HF_RECONSTRUCT_SPACE(S)`, `REPLICATE_API_TOKEN`/`_RECONSTRUCT_MODEL`/`_RERIG_MODEL`/`_POLL_MS`/`_TIMEOUT_MS`/`_WEBHOOK_URL`/`_WEBHOOK_SIGNING_KEY`, `NIM_TRELLIS_URL`/`_KEY`/`MODEL_TRELLIS_URL`, `TRIPO_MODEL_VERSION`, `VERTEX_IMAGEN_MODEL`, `CHROMIUM_PACK_URL`/`CHROME_PATH`/`PUPPETEER_EXECUTABLE_PATH`, `AVATURN_API_KEY`/`_API_URL`/`_SEED_ENABLED`, `MIXAMO_TOKEN`, `AVATAR_REGEN_PROVIDER`, `AUTO_RIG_DAILY_PER_USER`/`_GLOBAL_HOURLY`/`_PRIVATE`/`_REQUIRE_TIER`, `FORGE_ORIGIN`/`FORGE_PREFER_FREE`/`FORGE_FREE_POLL_MS`/`FORGE_PAID_GLOBAL_HOURLY`.- **Pump.fun / $THREE / treasury:** `PUMP_X402_LAUNCHER_SECRET_KEY_B64`, `PUMP_CRON_RELAYER_SECRET_KEY_B64`, `PUMP_DEFAULT_AGENT_MINT`/`_NETWORK`, `PUMP_PLATFORM_FEE_BPS`/`_WALLET`, `PUMP_GRADUATIONS_SOURCE`/`GRADUATIONS_LIST_KEY`/`_MAX_LEN`, `PUMPFUN_BOT_TOKEN`/`_URL`/`PUMPFUN_MCP_URL`, `PUMP_COINS_V2_BASE`/`PUMP_FRONTEND_BASE`, `PUMPKIT_WEBHOOK_SECRET`, `THREE_WS_MARK_ENFORCE`/`ALLOW_UNMARKED_MINT`, `THREE_TOKEN_MINT`/`THREE_MINT`/`THREE_TOKEN_DECIMALS`, `THREE_PRIZE_PAYOUT_KEY`, `THREE_BURN_ADDRESS`, `THREE_QUOTE_TTL_S`, `THREE_ALLOWANCE_DELEGATE_SECRET_KEY_B64`, `THREE_BUYBACK_ENABLED`/`_SECRET_KEY_B64`/`_MIN_USD`/`_MAX_USD`/`_COMMIT_BPS`/`_SLIPPAGE_BPS`, `BUYBACK_BPS`, `PLATFORM_FEE_BPS`, `REWARDS_DISTRIBUTOR_SECRET`, `REFLECTION_DAILY_CAP`/`_DEBOUNCE_MS`/`REFLECT_SWEEP_BATCH`, `REFERRAL_COMMISSION_BPS`, `RIDER_VAULT_ADDRESS`/`_HELIUS_WEBHOOK_SECRET`, `CREDITS_DEPOSIT_WALLET_SOLANA`, `PURCHASE_RECEIPT_KEY`, `VANITY_SERVICE_KEY`/`VANITY_BOUNTY_PAYOUT_KEY`/`VANITY_DROP_FUNDING_KEY`, `COIN_TREASURY_SECRET_KEY_B64`, `COSMETIC_SPLIT_TREASURY_SECRET_KEY_B64`, `CLUB_SOLANA_TREASURY_SECRET_KEY_B64`/`CLUB_EVM_TREASURY_PRIVATE_KEY`/`CLUB_BASE_RPC_URL`/`CLUB_SWEEP_DUST_ATOMICS`.- **Comms / observability:** `TELEGRAM_BOT_TOKEN`/`TELEGRAM_CHANGELOG_CHAT_ID`/`_ALERTS_CHAT_ID`/`_ORACLE_CHAT_ID`/`_SNIPER_CHAT_ID`, `RESEND_API_KEY`/`_AUDIENCE_ID`, `EMAIL_FROM`/`_REPLY_TO`, `SENTRY_DSN`/`_ENVIRONMENT`/`_RELEASE`, `AXIOM_TOKEN`/`_DATASET`/`_URL`, `VAPID_PUBLIC_KEY`/`_PRIVATE_KEY`/`_SUBJECT`, `DEV_TO_API_KEY`, `MEDIUM_INTEGRATION_TOKEN`/`_AUTHOR_ID`, `THREEWS_TWITTER_URL`.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 68e6f69ac..5d0b8972a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-08-07++- **The chat no longer refuses questions it was never asked to refuse**: Every message sent to a three.ws chat surface used to pass through a small safety classifier of ours before the actual model saw it, and when that classifier said "unsafe" you got a canned brush-off instead of an answer. It was wrong often enough to be a real problem: it judged one message at a time with no memory of the conversation, so an ordinary follow-up in a security, trading, or fiction discussion could read as alarming on its own and get blocked, and you were left staring at a refusal no model had actually made. That layer is gone from all of it: the main chat, the /chat app, the embeddable concierge, the widget chat on customer sites, and the agent-idea box on /create. Your question now goes to the model as written. If a model declines something, that is the model exercising its own judgment in its own words, and you can switch models or bring your own key. Nothing else changed: the same rate limits still apply, and the separate confirmation step before any wallet action is untouched. The one place a content check still runs is outbound: what our own official Sketchfab account publishes under the three.ws name. (`/chat`) `[improvement, fix]`+## 2026-08-06- **Airdrop Checker** (`/airdrops`): Check any Solana or Ethereum wallet against tracked airdrop criteria: a real on-chain activity scan, a 0-100 eligibility score per program, exactly what is missing with next steps, and the manual protocol actions a scan cannot see. Free, keyless, deep-linkable.diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 5317d56f6..d0eed0e39 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -25,7 +25,7 @@ bottom.| Rig Doctor (will this GLB animate?) | [pages/rig-doctor.html](pages/rig-doctor.html) `→ /rig-doctor`, analysis [src/rig-report.js](src/rig-report.js), page runtime [src/rig-doctor-page.js](src/rig-doctor-page.js), styles [public/rig-doctor.css](public/rig-doctor.css) | Live | The answer to the most expensive silent failure on the platform: a rig loads, renders, and never moves, because clips address bones by name and this skeleton calls them something else. Drop a `.glb` and the page reads its glTF JSON chunk in the browser, names the authoring convention (eleven fingerprints, from Mixamo and Ready Player Me to Unreal, VRM, Biped, Rigify, and HumanIK), and scores four limb groups independently against the 52-joint canonical set, because "62% covered" is not actionable and "your legs will not move" is. The verdict mirrors the runtime gate in [src/animation-manager.js](src/animation-manager.js) exactly (a skinned mesh plus 8 mapped joints), so it predicts rather than approximates. It then does two things a report cannot: mounts the real [src/avatar-pose.js](src/avatar-pose.js) stage on a blob URL of the file so the user watches their own rig perform the actual clip library, and runs [src/glb-canonicalize.js](src/glb-canonicalize.js) in-browser to hand back a repaired GLB with canonical joint names. Nothing is uploaded: the only network calls are for the clip library and the sample rigs. Also emits a schema-v1 manifest, an `<agent-3d>` snippet, and the matching [packages/avatar-cli/](packages/avatar-cli) commands. Docs: [docs/rig-doctor.md](docs/rig-doctor.md) `→ /docs/rig-doctor`. Tests: [tests/rig-report.test.js](tests/rig-report.test.js) || Talking page guide | [page-agent-sdk/](page-agent-sdk) | Published as `@three-ws/page-agent` | Drop-in rigged 3D agent that narrates any page + visitor avatar picker. `<page-agent>` web component. Rigged-only catalog. `preset="…"` resolves one of 5 personas (greeting/role/suggested-prompt chips/tool allowlist) — see [page-agent-sdk/README.md#persona-presets](page-agent-sdk/README.md#persona-presets). See [page-agent-sdk/PUBLISHING.md](page-agent-sdk/PUBLISHING.md) || Guided site tour | [tour-sdk/](tour-sdk) | Published as `@three-ws/tour` | 3D guide walks a live site, spotlights sections, narrates each. One-tag CDN build + free roam |-| Concierge (embeddable AI support chat) | [concierge-sdk/](concierge-sdk), backend [api/concierge.js](api/concierge.js) `→ /api/concierge`, landing [pages/concierge.html](pages/concierge.html) `→ /concierge`, first-party CDN copy `→ /concierge/concierge.global.js` (mirrored by [concierge-sdk/build.mjs](concierge-sdk/build.mjs)) | Published as `@three-ws/concierge` | An AI concierge for ANY website: floating launcher, chat panel with a rigged 3D avatar bust (blink/idle/viseme lipsync via the page-agent stage lineage), SSE-streamed answers grounded in the live page (ask-time DOM harvest + host `knowledge`, no crawler), speaks while streaming (sentence-level TTS handoff), push-to-talk mic, themes/accent/position, avatar picker or custom GLB. Backend is anonymous + CORS-`*` (third-party origins by design) with its own rate buckets (`limits.conciergeIp`/`conciergeGlobal`), fail-open moderation, and streaming failover over the shared free-first chain (api/_lib/llm.js). Shopping mode (Shopify): when embedded on a Shopify storefront it auto-detects the store (`window.Shopify` / `shop` config) and becomes a shopping assistant, reading the store's public `/products.json` + `/collections.json` + `/policies/*` at ask-time (no key, no crawler, same-origin), retrieving the relevant products per question via keyword+intent search ([concierge-sdk/src/shopify.js](concierge-sdk/src/shopify.js)), grounding the answer in them, and rendering real product cards (image/live price/link + on-store `/cart/add.js` add-to-cart). The endpoint accepts a bounded `shopping` payload and swaps the system prompt to a store assistant. `<three-concierge>` element, `data-concierge` one-tag auto-init, or `new Concierge({...})`. Also reachable from any AI agent via the MCP server [packages/concierge-mcp/](packages/concierge-mcp) (`@three-ws/concierge-mcp`, registry `io.github.nirholas/concierge-mcp`): `concierge_ask` (ask any site's concierge, grounded in the fetched page), `concierge_embed` (generate the embed), `concierge_avatars`. Examples: [concierge-sdk/examples/](concierge-sdk/examples) (one-tag, web component, imperative, custom avatar, React, self-hosted backend). Docs: [docs/concierge.md](docs/concierge.md), tutorial [docs/tutorials/build-a-site-concierge.md](docs/tutorials/build-a-site-concierge.md). Tests: [concierge-sdk/test/](concierge-sdk/test), [tests/api-concierge.test.js](tests/api-concierge.test.js), [packages/concierge-mcp/test/](packages/concierge-mcp/test) |+| Concierge (embeddable AI support chat) | [concierge-sdk/](concierge-sdk), backend [api/concierge.js](api/concierge.js) `→ /api/concierge`, landing [pages/concierge.html](pages/concierge.html) `→ /concierge`, first-party CDN copy `→ /concierge/concierge.global.js` (mirrored by [concierge-sdk/build.mjs](concierge-sdk/build.mjs)) | Published as `@three-ws/concierge` | An AI concierge for ANY website: floating launcher, chat panel with a rigged 3D avatar bust (blink/idle/viseme lipsync via the page-agent stage lineage), SSE-streamed answers grounded in the live page (ask-time DOM harvest + host `knowledge`, no crawler), speaks while streaming (sentence-level TTS handoff), push-to-talk mic, themes/accent/position, avatar picker or custom GLB. Backend is anonymous + CORS-`*` (third-party origins by design) with its own rate buckets (`limits.conciergeIp`/`conciergeGlobal`), no platform-side content filter on the visitor question, and streaming failover over the shared free-first chain (api/_lib/llm.js). Shopping mode (Shopify): when embedded on a Shopify storefront it auto-detects the store (`window.Shopify` / `shop` config) and becomes a shopping assistant, reading the store's public `/products.json` + `/collections.json` + `/policies/*` at ask-time (no key, no crawler, same-origin), retrieving the relevant products per question via keyword+intent search ([concierge-sdk/src/shopify.js](concierge-sdk/src/shopify.js)), grounding the answer in them, and rendering real product cards (image/live price/link + on-store `/cart/add.js` add-to-cart). The endpoint accepts a bounded `shopping` payload and swaps the system prompt to a store assistant. `<three-concierge>` element, `data-concierge` one-tag auto-init, or `new Concierge({...})`. Also reachable from any AI agent via the MCP server [packages/concierge-mcp/](packages/concierge-mcp) (`@three-ws/concierge-mcp`, registry `io.github.nirholas/concierge-mcp`): `concierge_ask` (ask any site's concierge, grounded in the fetched page), `concierge_embed` (generate the embed), `concierge_avatars`. Examples: [concierge-sdk/examples/](concierge-sdk/examples) (one-tag, web component, imperative, custom avatar, React, self-hosted backend). Docs: [docs/concierge.md](docs/concierge.md), tutorial [docs/tutorials/build-a-site-concierge.md](docs/tutorials/build-a-site-concierge.md). Tests: [concierge-sdk/test/](concierge-sdk/test), [tests/api-concierge.test.js](tests/api-concierge.test.js), [packages/concierge-mcp/test/](packages/concierge-mcp/test) || Assistant widget (3D avatar assistant for any website) | Loader [public/assistant/v1.js](public/assistant/v1.js) `-> /assistant/v1.js`, iframe app [pages/assistant-frame.html](pages/assistant-frame.html) + [src/assistant-frame.js](src/assistant-frame.js) `-> /assistant-frame`, builder [pages/assistant.html](pages/assistant.html) + [src/assistant-page.js](src/assistant-page.js) `-> /assistant`, shared validators [src/assistant-widget-core.js](src/assistant-widget-core.js). npm SDK [assistant-sdk/](assistant-sdk) (`@three-ws/assistant`) is the single source for the loader; its [build.mjs](assistant-sdk/build.mjs) emits the npm ESM + the mirrored one-tag build at `public/assistant/v1.js`. MCP server [packages/assistant-mcp/](packages/assistant-mcp) (`@three-ws/assistant-mcp`, registry `io.github.nirholas/assistant-widget`): `build_assistant_widget` (config -> paste-ready snippet + frame URL + JS-API call), `list_assistant_options` (avatars, backgrounds, modes, attributes). | Published as `@three-ws/assistant` | One script tag adds a floating launcher to any site; clicking it pops up a full-body animated avatar against the host page (transparent) or a color/gradient. Two modes: chatbot (free chain via POST /api/chat, or the visitor's own Groq/OpenRouter key sent browser-to-provider, stored in the frame's localStorage only) and speak mode (avatar repeats typed text out loud via Web Speech + head-anchored speech bubble + talking clip). All params re-validated in-frame (CSS/URL injection safe). Sibling of Concierge (chat panel) - this one is the full-body, avatar-first widget. Install three ways: one-tag CDN, `npm i @three-ws/assistant`, or the MCP server for AI agents. Examples: [assistant-sdk/examples/](assistant-sdk/examples). Docs: [docs/assistant-widget.md](docs/assistant-widget.md) `-> /docs/assistant-widget`, tutorial [docs/tutorials/add-a-3d-assistant.md](docs/tutorials/add-a-3d-assistant.md). Tests: [tests/assistant-widget.test.js](tests/assistant-widget.test.js), [assistant-sdk/test/](assistant-sdk/test), [packages/assistant-mcp/test/](packages/assistant-mcp/test) || Chat (conversational surface) | [chat/](chat) `→ /chat` | Live | Svelte 4 + Vite client, fork of eplus, built by `build:chat` inside `build:gcp` into `public/chat` → `dist/chat`. Free Built-in lane via `/api/chat/proxy` plus BYOK providers; inline 3D forge tools + ModelViewer3D; shares the platform wallet via [src/shared/](src/shared). Docs: [chat/README.md](chat/README.md) || three.ws's own guided tour + onboarding | [src/feature-tour/](src/feature-tour) `→ /feature-tour.js`, entry [src/feature-tour.js](src/feature-tour.js), curriculum [public/tour/curriculum.json](public/tour/curriculum.json) generated by [scripts/build-tour.mjs](scripts/build-tour.mjs), landing [pages/tour.html](pages/tour.html) `→ /tour` | Live | A hardened, site-native fork of the [tour-sdk/](tour-sdk) engine (same curriculum schema — stops/sections/tracks/highlight/narration/targets), lazy-injected only when a tour is starting/active (`feature-tour-boot` Vite plugin) so pages that never tour pay no Three.js cost. Three tracks share one curriculum: `full` (every feature, chapter by chapter), `quick` (highlighted heroes), and `onboarding` (added 2026-07-12) — a 6-stop, hand-authored new-account walkthrough chaining `/start` → make an avatar (`/create/selfie`) → build a world (`/diorama`) → live `/markets` data → an optional coin launch (`/create-agent`, clearly skippable) → the new creator's own `/profile`. Auto-offered once to a signed-in account with zero creations across avatars/agents/forged models/worlds (`GET /api/me` → `show_onboarding_tour`, backed by `users.onboarding_tour_seen_at`/`onboarding_tour_completed_at`, migration [api/_lib/migrations/20260712030000_onboarding_tour_state.sql](api/_lib/migrations/20260712030000_onboarding_tour_state.sql)); always reachable afterward via "🎬 Replay guided tour" in the [public/getting-started.js](public/getting-started.js) checklist panel. Tests: [tests/feature-tour-curriculum.test.js](tests/feature-tour-curriculum.test.js), [tests/api-me-onboarding-tour.test.js](tests/api-me-onboarding-tour.test.js) |diff --git a/api/_lib/llm-metering-rule.js b/api/_lib/llm-metering-rule.jsindex 560f9b773..128994d68 100644--- a/api/_lib/llm-metering-rule.js+++ b/api/_lib/llm-metering-rule.js@@ -10,8 +10,8 @@//// Classification, in order:// fail tokens served with no provider recorded (unattributable traffic)-// skip a zero-token event with no provider (an anon moderation refusal never-// reached an upstream, so there is no lane to meter)+// skip a zero-token event with no provider (nothing reached an upstream, so+// there is no lane to meter)// fail any call in the window recorded an UNKNOWN cost (null), the model// reached production with no price; the fix is one table entry// fail a spending lane served tokens and reported exactly $0diff --git a/api/_lib/moderation.js b/api/_lib/moderation.jsdeleted file mode 100644index 1a729660d..000000000--- a/api/_lib/moderation.js+++ /dev/null@@ -1,208 +0,0 @@-// Free anonymous-chat moderation pre-filter — NVIDIA NemoGuard, fail-open.-//-// Anonymous chat surfaces (the anon path in api/chat.js, public widget chat,-// and api/chat/proxy.js) carry untrusted, unattributable traffic on the host's-// free LLM keys. Rather than inherit a third-party provider's moderation gate-// (e.g. OpenRouter's 403 "requires moderation"), we run our OWN safety pass on-// the inbound user message with a free NVIDIA NIM safety classifier and refuse-// locally — keeping the downstream free model routes open and under our control.-//-// ── THE PRIME RULE IS FAIL-OPEN ──────────────────────────────────────────────-// Moderation is a FILTER, not a GATE: it must never take chat down. A timeout,-// an outage, a bad key, a non-200, an unparseable reply — ANY failure whatsoever-// proceeds UN-moderated. The only outcome that blocks a message is a successful,-// parsed "unsafe" verdict. Everything else returns { flagged: false } and chat-// continues exactly as if the filter weren't there.-//-// Scope: NemoGuard is a CONTENT-safety classifier (harm, self-harm, weapons,-// sexual content, …). It is NOT a jailbreak / prompt-injection detector — that,-// plus autonomous-send governance, stays with IBM Granite Guardian (the sendSol-// Trust Layer in granite-guardian.js). The two are complementary.-//-// Signed-in users are attributable and rate-limited, so only the anonymous-// surfaces call this. Probe + schema: tasks/nvidia-nim/probes/moderation.md--const NIM_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';--// nvidia/llama-3.1-nemoguard-8b-content-safety — JSON verdict + named-// categories, median ~340 ms on the free tier (see probe). Override via-// ANON_MODERATION_MODEL; the parser also understands the Llama-Guard-// `unsafe\nS#` text form, so meta/llama-guard-4-12b is a drop-in.-const DEFAULT_MODEL = 'nvidia/llama-3.1-nemoguard-8b-content-safety';--// Per-call abort budget. Probe median is ~340 ms with a ~680 ms tail; 2 s leaves-// generous headroom and still fails over fast when the lane stalls.-const DEFAULT_TIMEOUT_MS = 2000;-const MIN_TIMEOUT_MS = 250;-const MAX_TIMEOUT_MS = 8000;--// The classifier only needs the message itself; cap the slice we send so a giant-// pasted payload can't blow the latency budget. Matches the chat message limit.-const MAX_MODERATION_CHARS = 4000;--function clampTimeout(ms) {- if (!Number.isFinite(ms) || ms <= 0) return DEFAULT_TIMEOUT_MS;- return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, ms));-}--/**- * Resolve the moderation config from the environment.- * enabled — true iff a NIM key is present AND the kill-switch is not set.- * key — NVIDIA_API_KEY (the free NIM lane), or null.- * model — ANON_MODERATION_MODEL override, else the NemoGuard default.- * timeoutMs — ANON_MODERATION_TIMEOUT_MS override (clamped), else 2000.- *- * Kill switch: ANON_MODERATION_DISABLED=true turns the filter off without a code- * change (mirrors the GUARDIAN_DISABLE convention). The filter is otherwise ON- * whenever the free NIM key is configured.- */-export function moderationConfig(env = process.env) {- const key = env.NVIDIA_API_KEY || null;- const disabled = String(env.ANON_MODERATION_DISABLED || '').toLowerCase() === 'true';- return {- enabled: !!key && !disabled,- key,- model: env.ANON_MODERATION_MODEL?.trim() || DEFAULT_MODEL,- timeoutMs: clampTimeout(parseInt(env.ANON_MODERATION_TIMEOUT_MS || '', 10)),- };-}--/** Whether the anonymous pre-filter is active for this deploy. */-export function moderationEnabled(env = process.env) {- return moderationConfig(env).enabled;-}--/**- * Parse a safety classifier's reply into { unsafe, categories }.- * Accepts NemoGuard JSON ({"User Safety":"unsafe","Safety Categories":"…"}) and- * the Llama-Guard text form ("unsafe\nS9" / "safe"). Anything unrecognized is- * treated as SAFE (fail-open) — we never block on a reply we can't read.- */-export function parseVerdict(content) {- const raw = String(content ?? '').trim();- if (!raw) return { unsafe: false, categories: [], parsed: false };-- // NemoGuard: clean JSON object (sometimes with a trailing space).- try {- const j = JSON.parse(raw);- const us = String(j['User Safety'] ?? j.user_safety ?? '').toLowerCase();- const cats = splitCategories(j['Safety Categories'] ?? j.safety_categories);- if (us === 'unsafe') return { unsafe: true, categories: cats, parsed: true };- if (us === 'safe') return { unsafe: false, categories: [], parsed: true };- } catch {- // not JSON — fall through to the text form- }-- // Llama-Guard text form: first line "safe" | "unsafe", codes on line 2.- const head = raw.toLowerCase();- if (/^unsafe\b/.test(head)) {- const codes = raw.split('\n').slice(1).join(' ').trim();- return { unsafe: true, categories: codes ? [codes] : [], parsed: true };- }- if (/^safe\b/.test(head)) return { unsafe: false, categories: [], parsed: true };-- return { unsafe: false, categories: [], parsed: false };-}--function splitCategories(value) {- return String(value ?? '')- .split(',')- .map((s) => s.trim())- .filter(Boolean);-}--/**- * Pull the latest user message from an OpenAI-shaped messages array (used by the- * proxy, which forwards a raw chat-completions body). Handles string and- * multi-part content. Returns '' when there's nothing to moderate.- */-export function lastUserMessage(messages) {- if (!Array.isArray(messages)) return '';- for (let i = messages.length - 1; i >= 0; i--) {- const m = messages[i];- if (!m || m.role !== 'user') continue;- if (typeof m.content === 'string') return m.content;- if (Array.isArray(m.content)) {- return m.content- .map((p) => (typeof p === 'string' ? p : p?.text || ''))- .join(' ')- .trim();- }- }- return '';-}--/**- * Moderate one anonymous user message. ALWAYS fail-open — see the file header.- *- * @returns {Promise<{- * checked: boolean, // did a verdict actually come back?- * flagged: boolean, // true ONLY on a parsed "unsafe" verdict- * categories?: string[], // named risk categories when flagged- * model?: string,- * latencyMs?: number,- * error?: string, // reason we failed open, when applicable- * }>}- */-export async function moderateAnonInput(message, opts = {}) {- const cfg = opts.config || moderationConfig();- if (!cfg.enabled || !cfg.key) return { checked: false, flagged: false };-- const text = String(message ?? '').trim();- if (!text) return { checked: false, flagged: false };-- const started = Date.now();- const ctrl = new AbortController();- const timer = setTimeout(() => ctrl.abort(), cfg.timeoutMs);- try {- const res = await fetch(NIM_URL, {- method: 'POST',- headers: {- Authorization: `Bearer ${cfg.key}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({- model: cfg.model,- messages: [{ role: 'user', content: text.slice(0, MAX_MODERATION_CHARS) }],- max_tokens: 64,- temperature: 0,- }),- signal: ctrl.signal,- });- const latencyMs = Date.now() - started;- if (!res.ok) {- // Non-200 (auth/billing/rate-limit/5xx) → fail open.- return { checked: false, flagged: false, error: `moderation ${res.status}`, latencyMs };- }- const data = await res.json();- const verdict = parseVerdict(data?.choices?.[0]?.message?.content);- return {- checked: verdict.parsed,- flagged: verdict.unsafe,- categories: verdict.categories,- model: cfg.model,- latencyMs,- };- } catch (err) {- // Timeout (AbortError), network failure, JSON error — all fail open.- return {- checked: false,- flagged: false,- error: err?.name === 'AbortError' ? 'timeout' : err?.message || 'error',- latencyMs: Date.now() - started,- };- } finally {- clearTimeout(timer);- }-}--/**- * The in-band refusal for a blocked anonymous message. Short, on-brand, and- * deliberately non-preachy — no lecture, no "as an AI", no policy recital. It- * redirects the visitor to what the agent is actually for. Delivered as a normal- * chat reply (SSE done/message event, or an OpenAI completion for the proxy) —- * never an HTTP error.- */-export function refusalReply() {- return "I can't go there — that one's outside what I can help with. Ask me about three.ws, the 3D scene, or building and embedding an agent, and I'm all yours.";-}diff --git a/api/_lib/publish-safety.js b/api/_lib/publish-safety.jsnew file mode 100644index 000000000..ffe0b9dfc--- /dev/null+++ b/api/_lib/publish-safety.js@@ -0,0 +1,177 @@+// Brand-safety classifier for content THIS PLATFORM PUBLISHES outward.+//+// Scope is deliberately narrow: the only caller is the Sketchfab showcase cron+// (api/cron/sketchfab-showcase.js), which uploads visitor-generated 3D models to+// our own official Sketchfab account. That is an outbound publishing decision+// under our brand on a third party's platform, subject to their terms, so we+// screen what we push there alongside the local denylist in _lib/sketchfab.js.+//+// ── THIS IS NOT A CHAT FILTER ────────────────────────────────────────────────+// It used to also pre-screen anonymous chat, concierge, widget, and agent-idea+// input. That is gone (owner directive 2026-08-07): no three.ws surface screens+// what a user may ASK. An 8B classifier judging a single message with no+// conversation context flagged plenty of ordinary questions, and a refusal the+// user never earned is worse than an answer the model itself would have+// declined. Whatever safety judgment the serving model makes is now the only+// one those routes apply. Do not wire this module back into a chat path.+//+// ── FAIL-OPEN ────────────────────────────────────────────────────────────────+// A timeout, an outage, a bad key, a non-200, an unparseable reply: ANY failure+// returns { flagged: false } and publishing proceeds. The only outcome that+// blocks an upload is a successful, parsed "unsafe" verdict.+//+// Autonomous-spend governance is a separate concern and stays with IBM Granite+// Guardian (granite-guardian.js). Probe + schema: tasks/nvidia-nim/probes/moderation.md++const NIM_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';++// nvidia/llama-3.1-nemoguard-8b-content-safety returns a JSON verdict + named+// categories, median ~340 ms on the free tier (see probe). Override via+// PUBLISH_SAFETY_MODEL; the parser also understands the Llama-Guard+// `unsafe\nS#` text form, so meta/llama-guard-4-12b is a drop-in.+const DEFAULT_MODEL = 'nvidia/llama-3.1-nemoguard-8b-content-safety';++// Per-call abort budget. Probe median is ~340 ms with a ~680 ms tail; 2 s leaves+// generous headroom and still fails over fast when the lane stalls.+const DEFAULT_TIMEOUT_MS = 2000;+const MIN_TIMEOUT_MS = 250;+const MAX_TIMEOUT_MS = 8000;++// The classifier only needs the text itself; cap the slice we send so a giant+// payload can't blow the latency budget.+const MAX_CLASSIFY_CHARS = 4000;++function clampTimeout(ms) {+ if (!Number.isFinite(ms) || ms <= 0) return DEFAULT_TIMEOUT_MS;+ return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, ms));+}++/**+ * Resolve the publish-safety config from the environment.+ * enabled: true iff a NIM key is present AND the kill-switch is not set.+ * key: NVIDIA_API_KEY (the free NIM lane), or null.+ * model: PUBLISH_SAFETY_MODEL override, else the NemoGuard default.+ * timeoutMs: PUBLISH_SAFETY_TIMEOUT_MS override (clamped), else 2000.+ *+ * Kill switch: PUBLISH_SAFETY_DISABLED=true turns the classifier off without a+ * code change (mirrors the GUARDIAN_DISABLE convention). It is otherwise ON+ * whenever the free NIM key is configured.+ */+export function publishSafetyConfig(env = process.env) {+ const key = env.NVIDIA_API_KEY || null;+ const disabled = String(env.PUBLISH_SAFETY_DISABLED || '').toLowerCase() === 'true';+ return {+ enabled: !!key && !disabled,+ key,+ model: env.PUBLISH_SAFETY_MODEL?.trim() || DEFAULT_MODEL,+ timeoutMs: clampTimeout(parseInt(env.PUBLISH_SAFETY_TIMEOUT_MS || '', 10)),+ };+}++/** Whether the publish-time classifier is active for this deploy. */+export function publishSafetyEnabled(env = process.env) {+ return publishSafetyConfig(env).enabled;+}++/**+ * Parse a safety classifier's reply into { unsafe, categories }.+ * Accepts NemoGuard JSON ({"User Safety":"unsafe","Safety Categories":"…"}) and+ * the Llama-Guard text form ("unsafe\nS9" / "safe"). Anything unrecognized is+ * treated as SAFE (fail-open); we never block on a reply we can't read.+ */+export function parseVerdict(content) {+ const raw = String(content ?? '').trim();+ if (!raw) return { unsafe: false, categories: [], parsed: false };++ // NemoGuard: clean JSON object (sometimes with a trailing space).+ try {+ const j = JSON.parse(raw);+ const us = String(j['User Safety'] ?? j.user_safety ?? '').toLowerCase();+ const cats = splitCategories(j['Safety Categories'] ?? j.safety_categories);+ if (us === 'unsafe') return { unsafe: true, categories: cats, parsed: true };+ if (us === 'safe') return { unsafe: false, categories: [], parsed: true };+ } catch {+ // not JSON, so fall through to the text form+ }++ // Llama-Guard text form: first line "safe" | "unsafe", codes on line 2.+ const head = raw.toLowerCase();+ if (/^unsafe\b/.test(head)) {+ const codes = raw.split('\n').slice(1).join(' ').trim();+ return { unsafe: true, categories: codes ? [codes] : [], parsed: true };+ }+ if (/^safe\b/.test(head)) return { unsafe: false, categories: [], parsed: true };++ return { unsafe: false, categories: [], parsed: false };+}++function splitCategories(value) {+ return String(value ?? '')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+}++/**+ * Classify one piece of outbound text before we publish it. ALWAYS fail-open.+ *+ * @returns {Promise<{+ * checked: boolean, // did a verdict actually come back?+ * flagged: boolean, // true ONLY on a parsed "unsafe" verdict+ * categories?: string[], // named risk categories when flagged+ * model?: string,+ * latencyMs?: number,+ * error?: string, // reason we failed open, when applicable+ * }>}+ */+export async function classifyPublishSafety(text, opts = {}) {+ const cfg = opts.config || publishSafetyConfig();+ if (!cfg.enabled || !cfg.key) return { checked: false, flagged: false };++ const content = String(text ?? '').trim();+ if (!content) return { checked: false, flagged: false };++ const started = Date.now();+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), cfg.timeoutMs);+ try {+ const res = await fetch(NIM_URL, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${cfg.key}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ model: cfg.model,+ messages: [{ role: 'user', content: content.slice(0, MAX_CLASSIFY_CHARS) }],+ max_tokens: 64,+ temperature: 0,+ }),+ signal: ctrl.signal,+ });+ const latencyMs = Date.now() - started;+ if (!res.ok) {+ // Non-200 (auth/billing/rate-limit/5xx) → fail open.+ return { checked: false, flagged: false, error: `publish-safety ${res.status}`, latencyMs };+ }+ const data = await res.json();+ const verdict = parseVerdict(data?.choices?.[0]?.message?.content);+ return {+ checked: verdict.parsed,+ flagged: verdict.unsafe,+ categories: verdict.categories,+ model: cfg.model,+ latencyMs,+ };+ } catch (err) {+ // Timeout (AbortError), network failure, JSON error: all fail open.+ return {+ checked: false,+ flagged: false,+ error: err?.name === 'AbortError' ? 'timeout' : err?.message || 'error',+ latencyMs: Date.now() - started,+ };+ } finally {+ clearTimeout(timer);+ }+}diff --git a/api/_lib/sketchfab.js b/api/_lib/sketchfab.jsindex f7a42cdcd..407049ba0 100644--- a/api/_lib/sketchfab.js+++ b/api/_lib/sketchfab.js@@ -31,7 +31,8 @@ const SHOWCASE_UTM = 'utm_source=sketchfab&utm_medium=referral&utm_campaign=show// explicit content under the three.ws name. Word-boundary matched, so// "bullet train" style false positives are accepted as the cost of a// conservative gate. This local list is always on; the NemoGuard classifier-// (api/_lib/moderation.js) runs as a second, fail-open layer in the cron.+// (api/_lib/publish-safety.js) runs as a second, fail-open layer in the cron.+// Both are limits on what THIS account publishes, not on what users may forge.const DENY_TERMS = ['glock', 'gun', 'guns', 'firearm', 'firearms', 'rifle', 'pistol', 'shotgun','revolver', 'ammo', 'bullet', 'bullets', 'grenade', 'bomb', 'explosive',diff --git a/api/chat.js b/api/chat.jsindex 399865be1..513f4e08f 100644--- a/api/chat.js+++ b/api/chat.js@@ -37,7 +37,6 @@ import { loadUserProviderKeys } from './_lib/provider-keys.js';import { watsonxConfig, watsonxAuthHeaders } from './_lib/watsonx.js';import { orchestrateConfig } from './_lib/orchestrate.js';import { guardianConfig, governSend, sendCapUsd } from './_lib/granite-guardian.js';-import { moderateAnonInput, refusalReply } from './_lib/moderation.js';import {markProviderCooldown,providersInCooldown,@@ -466,33 +465,11 @@ export default wrap(async (req, res) => {}}- // Anonymous pre-moderation (FAIL-OPEN). Signed-in callers are attributable- // and rate-limited, so only anon traffic is screened. A confirmed-unsafe- // message gets a normal in-band refusal over the SSE stream — never an HTTP- // error — and any moderation failure proceeds un-moderated (the filter can- // never take chat down). See api/_lib/moderation.js.- if (anonymous) {- const verdict = await moderateAnonInput(body.message);- if (verdict.flagged) {- res.writeHead(200, {- 'Content-Type': 'text/event-stream; charset=utf-8',- 'Cache-Control': 'no-cache, no-transform',- 'X-Accel-Buffering': 'no',- });- res.write(- `data: ${JSON.stringify({ type: 'done', reply: refusalReply(), actions: [], moderated: true })}\n\n`,- );- res.end();- recordEvent({- userId: null,- kind: 'chat',- tool: 'moderation',- latencyMs: verdict.latencyMs ?? 0,- meta: { moderated: true, categories: verdict.categories ?? [], anonymous: true },- });- return;- }- }+ // No platform-side content filter runs here. Whatever safety judgment the+ // serving model makes is the only one this route applies; we do not add a+ // classifier in front of it. Abuse is handled by attribution and metering+ // (the rate-limit buckets above), not by pre-screening what a visitor may+ // ask. Owner directive 2026-08-07.let userProviderKeys = {};if (auth?.userId) {diff --git a/api/chat/proxy.js b/api/chat/proxy.jsindex 92a1cb6c7..b6c89cd41 100644--- a/api/chat/proxy.js+++ b/api/chat/proxy.js@@ -1,7 +1,6 @@import { env } from '../_lib/env.js';import { cors, error, json, method, wrap, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { moderateAnonInput, refusalReply, lastUserMessage } from '../_lib/moderation.js';import { isFreeModelId, isLiveFreeModel, pickDefaultFreeModel } from '../_lib/openrouter-free.js';const UPGRADE_URL = `${env.APP_ORIGIN}/pricing`;@@ -58,39 +57,11 @@ export default wrap(async (req, res) => {activeModel = (await pickDefaultFreeModel({ exclude: [model] })) ?? model;}- // Anonymous pre-moderation (FAIL-OPEN). This proxy is unauthenticated, so- // screen the visitor's latest message with the free NIM safety lane before- // spending an upstream call. A confirmed-unsafe message gets an in-band- // refusal in the normal OpenAI reply shape (so the chat app renders it like- // any other answer) — never an HTTP error; any moderation failure proceeds- // un-moderated. See api/_lib/moderation.js.- const verdict = await moderateAnonInput(lastUserMessage(body?.messages));- if (verdict.flagged) {- const reply = refusalReply();- res.setHeader('cache-control', 'no-store');- if (body?.stream) {- res.statusCode = 200;- res.setHeader('content-type', 'text/event-stream; charset=utf-8');- const base = { id: 'chatcmpl-moderation', object: 'chat.completion.chunk', model };- res.write(- `data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: { role: 'assistant', content: reply }, finish_reason: null }] })}\n\n`,- );- res.write(- `data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\n`,- );- res.write('data: [DONE]\n\n');- res.end();- return;- }- return json(res, 200, {- id: 'chatcmpl-moderation',- object: 'chat.completion',- model,- choices: [- { index: 0, message: { role: 'assistant', content: reply }, finish_reason: 'stop' },- ],- });- }+ // The message goes upstream as written. This proxy adds no content filter of+ // its own: the serving model's own judgment is the only safety layer, and a+ // refusal, if any, is the model's to make and to word. Abuse control here is+ // the per-IP quota above plus the free-model-only gate, not pre-screening.+ // Owner directive 2026-08-07.// Only :free models pass the gate above, so any configured key can serve the// request. Rotate to the next key on account-level failures (bad key, out ofdiff --git a/api/concierge.js b/api/concierge.jsindex 93fca17f3..4a318e7c8 100644--- a/api/concierge.js+++ b/api/concierge.js@@ -26,7 +26,6 @@ import { cors, method, readJson, wrap, error, rateLimited } from './_lib/http.jsimport { parse } from './_lib/validate.js';import { limits, clientIp } from './_lib/rate-limit.js';import { providerChain, LlmUnavailableError } from './_lib/llm.js';-import { moderateAnonInput, refusalReply } from './_lib/moderation.js';import { markProviderCooldown, providersInCooldown, AUTH_COOLDOWN_SECONDS } from './_lib/provider-health.js';import { recordEvent } from './_lib/usage.js';import { captureException } from './_lib/sentry.js';@@ -208,24 +207,9 @@ export default wrap(async (req, res) => {});const sendSSE = (obj) => res.write(`data: ${JSON.stringify(obj)}\n\n`);- // Anonymous pre-moderation (FAIL-OPEN, same policy as /api/chat): a flagged- // message gets a normal in-band refusal, and a moderation outage never takes- // the concierge down.- const verdict = await moderateAnonInput(body.message);- if (verdict.flagged) {- sseHead();- sendSSE({ type: 'chunk', text: refusalReply() });- sendSSE({ type: 'done', moderated: true });- res.end();- recordEvent({- userId: null,- kind: 'chat',- tool: 'concierge',- latencyMs: Date.now() - started,- meta: { moderated: true, anonymous: true },- });- return;- }+ // No platform-side content filter (same policy as /api/chat): the visitor's+ // question goes to the model as written, and any refusal is the model's own.+ // Owner directive 2026-08-07.const system = buildSystemPrompt(body);const messages = [diff --git a/api/cron/sketchfab-showcase.js b/api/cron/sketchfab-showcase.jsindex d98730439..573882d92 100644--- a/api/cron/sketchfab-showcase.js+++ b/api/cron/sketchfab-showcase.js@@ -19,7 +19,7 @@// Brand safety: the official account never publishes firearms or explicit// content. A local denylist filters the selection SQL itself (dry-run// included) and re-checks before upload; the NemoGuard classifier-// (moderation.js) runs as a second, fail-open layer. A blocked creation is+// (publish-safety.js) runs as a second, fail-open layer. A blocked creation is// parked in the ledger with status 'blocked' so it is never re-picked.//// Every upload is tagged `ai-generated`, carries the source prompt, and@@ -48,7 +48,7 @@ import {sketchfabConfigured,uploadModel,} from '../_lib/sketchfab.js';-import { moderateAnonInput } from '../_lib/moderation.js';+import { classifyPublishSafety } from '../_lib/publish-safety.js';import { requireCron } from '../_lib/cron-auth.js';const MAX_ATTEMPTS = 3;@@ -152,11 +152,13 @@ async function claimCreation(candidate) {return row?.id || null;}-// Local denylist + NemoGuard verdict. Returns a block reason or null.+// Local denylist + NemoGuard verdict. Returns a block reason or null. This is a+// publishing decision about our own official account, not a filter on anything a+// user asks three.ws for; no chat surface screens input (see publish-safety.js).async function contentBlockReason(prompt) {const term = promptDenyMatch(prompt);if (term) return `denylist:${term}`;- const verdict = await moderateAnonInput(prompt).catch(() => ({ flagged: false }));+ const verdict = await classifyPublishSafety(prompt).catch(() => ({ flagged: false }));if (verdict?.flagged) {return `moderation:${(verdict.categories || []).join(',') || 'unsafe'}`;}diff --git a/api/instant-agent.js b/api/instant-agent.jsindex 4b277353e..c33273a02 100644--- a/api/instant-agent.js+++ b/api/instant-agent.js@@ -27,7 +27,6 @@import { cors, method, wrap, error, readJson, json, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { llmComplete, LlmUnavailableError } from './_lib/llm.js';-import { moderateAnonInput } from './_lib/moderation.js';const MAX_IDEA = 400;const MIN_IDEA = 8;@@ -303,18 +302,8 @@ export default wrap(async (req, res) => {return error(res, 400, 'idea_too_short', 'Describe the agent in a few more words.');}- // Anonymous free-text reaching a provider gets the same screening as- // anonymous chat. A block is a 400 with a plain reason, never a silent- // rewrite of what the visitor asked for.- const verdict = await moderateAnonInput(idea);- if (verdict.flagged) {- return error(- res,- 400,- 'idea_rejected',- 'That description cannot be used to create an agent. Try describing what it should help people do.',- );- }+ // The idea goes to the model as written: no platform-side screening decides+ // which agents a visitor is allowed to describe. Owner directive 2026-08-07.let result;try {diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].jsindex f75f99f62..4638835b7 100644--- a/api/widgets/[id]/[action].js+++ b/api/widgets/[id]/[action].js@@ -18,7 +18,6 @@ import { isDemoWidgetId, getDemoWidget } from '../_demo-fixtures.js';import { decorate } from '../index.js';import { PROVIDER_MODEL_DEFAULTS, DEFAULT_PROVIDER_ORDER, MODEL_CATALOG, PER_CALL_TIMEOUT_MS, modelRejectsSampling, modelThinksByDefault } from '../../_lib/chat-models.js';import { redactPii } from '../../_lib/pii.js';-import { moderateAnonInput, refusalReply } from '../../_lib/moderation.js';import { embeddingsConfigured, scoreRowsBySpace } from '../../_lib/embeddings.js';import { rerankConfigured, rerankPassages } from '../../_lib/rerank.js';import { watsonxConfig, watsonxToken } from '../../_lib/watsonx.js';@@ -260,39 +259,10 @@ async function handleChat(req, res) {}const allowedSkills = filterSkills(cfg.skills);- // Anonymous pre-moderation (FAIL-OPEN). Public widget visitors are- // unattributable, so screen their message with the free NIM safety lane;- // the owner's Studio preview (isOwner) is exempt. A confirmed-unsafe message- // gets a normal in-band refusal — never an HTTP error — and any moderation- // failure proceeds un-moderated. See api/_lib/moderation.js.- if (!isOwner) {- const verdict = await moderateAnonInput(body.message);- if (verdict.flagged) {- res.statusCode = 200;- res.setHeader('content-type', 'text/event-stream; charset=utf-8');- res.setHeader('cache-control', 'no-store');- res.setHeader('connection', 'keep-alive');- res.setHeader('x-accel-buffering', 'no');- res.flushHeaders?.();- const reply = refusalReply();- writeSse(res, 'message', { reply, actions: [] });- writeSse(res, 'done', {});- res.end();- persistTurn({- widgetId,- req,- body,- userMessage: body.message,- reply,- actions: [],- provider: 'moderation',- model: verdict.model || null,- }).catch((err) => {- if (process.env.DEBUG === 'true') console.warn('[widget-chat] persist', err?.message);- });- return;- }- }+ // A widget visitor's message reaches the brain as written. The platform adds+ // no content classifier in front of it; the serving model decides what it+ // will answer, and the widget owner shapes the rest through the persona and+ // skills they configured. Owner directive 2026-08-07.// Pull grounding chunks before we open the stream so latency stays in one// place rather than blocking after the visitor sees "typing…".diff --git a/data/changelog.json b/data/changelog.jsonindex 59ec4ed74..27db2fd17 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-07",+ "title": "The chat no longer refuses questions it was never asked to refuse",+ "summary": "Every message sent to a three.ws chat surface used to pass through a small safety classifier of ours before the actual model saw it, and when that classifier said \"unsafe\" you got a canned brush-off instead of an answer. It was wrong often enough to be a real problem: it judged one message at a time with no memory of the conversation, so an ordinary follow-up in a security, trading, or fiction discussion could read as alarming on its own and get blocked, and you were left staring at a refusal no model had actually made. That layer is gone from all of it: the main chat, the /chat app, the embeddable concierge, the widget chat on customer sites, and the agent-idea box on /create. Your question now goes to the model as written. If a model declines something, that is the model exercising its own judgment in its own words, and you can switch models or bring your own key. Nothing else changed: the same rate limits still apply, and the separate confirmation step before any wallet action is untouched. The one place a content check still runs is outbound: what our own official Sketchfab account publishes under the three.ws name.",+ "tags": [+ "improvement",+ "fix"+ ],+ "link": "/chat"+ },{"date": "2026-08-06","title": "A mirror that grades your fingerspelling, without your camera leaving the room",diff --git a/docs/agent-abilities/ABILITIES.md b/docs/agent-abilities/ABILITIES.mdindex 45f9f5ff2..36950770b 100644--- a/docs/agent-abilities/ABILITIES.md+++ b/docs/agent-abilities/ABILITIES.md@@ -922,7 +922,7 @@ Conversations with the latency and interruptibility of a phone call, not a walkiDrop a chat panel with a 3D avatar onto your own site. Visitors talk to it by text or voice, it answers grounded in the knowledge base you uploaded, performs its skills visibly through the avatar, reacts empathetically to visitor sentiment, and speaks replies aloud. Owners get saved transcripts and stats; visitor input is moderated and personally identifying information is redacted before storage. A variant even carries its own Solana wallet and can send SOL.-The NichAgent conversational surface routed through a per-widget chat endpoint with embedding-based retrieval plus reranking over ingested knowledge, PII redaction, anonymous-input moderation, and the multi-provider LLM failover chain.+The NichAgent conversational surface routed through a per-widget chat endpoint with embedding-based retrieval plus reranking over ingested knowledge, PII redaction, and the multi-provider LLM failover chain.A production-grade, voice-enabled AI greeter for your site in one snippet — with the safety plumbing already done.diff --git a/docs/agent-abilities/FULL-ARTICLE.md b/docs/agent-abilities/FULL-ARTICLE.mdindex edcf25929..f4d59ef72 100644--- a/docs/agent-abilities/FULL-ARTICLE.md+++ b/docs/agent-abilities/FULL-ARTICLE.md@@ -920,7 +920,7 @@ Beyond turn-based talk, agents support genuinely live, full-duplex voice: you caDrop a chat panel with a 3D avatar onto your own site. Visitors talk to it by text or voice, it answers grounded in the knowledge base you uploaded, performs its skills visibly through the avatar, reacts empathetically to visitor sentiment, and speaks replies aloud. Owners get saved transcripts and stats; visitor input is moderated and personally identifying information is redacted before storage. A variant even carries its own Solana wallet and can send SOL.-**How it works:** The NichAgent conversational surface routed through a per-widget chat endpoint with embedding-based retrieval plus reranking over ingested knowledge, PII redaction, anonymous-input moderation, and the multi-provider LLM failover chain.+**How it works:** The NichAgent conversational surface routed through a per-widget chat endpoint with embedding-based retrieval plus reranking over ingested knowledge, PII redaction, and the multi-provider LLM failover chain.**Why it matters:** A production-grade, voice-enabled AI greeter for your site in one snippet — with the safety plumbing already done.diff --git a/docs/agent-abilities/chapters/05-the-voice.md b/docs/agent-abilities/chapters/05-the-voice.mdindex 761a0dc2b..4111c6c44 100644--- a/docs/agent-abilities/chapters/05-the-voice.md+++ b/docs/agent-abilities/chapters/05-the-voice.md@@ -152,7 +152,7 @@ Beyond turn-based talk, agents support genuinely live, full-duplex voice: you caDrop a chat panel with a 3D avatar onto your own site. Visitors talk to it by text or voice, it answers grounded in the knowledge base you uploaded, performs its skills visibly through the avatar, reacts empathetically to visitor sentiment, and speaks replies aloud. Owners get saved transcripts and stats; visitor input is moderated and personally identifying information is redacted before storage. A variant even carries its own Solana wallet and can send SOL.-**How it works:** The NichAgent conversational surface routed through a per-widget chat endpoint with embedding-based retrieval plus reranking over ingested knowledge, PII redaction, anonymous-input moderation, and the multi-provider LLM failover chain.+**How it works:** The NichAgent conversational surface routed through a per-widget chat endpoint with embedding-based retrieval plus reranking over ingested knowledge, PII redaction, and the multi-provider LLM failover chain.**Why it matters:** A production-grade, voice-enabled AI greeter for your site in one snippet — with the safety plumbing already done.diff --git a/docs/assistant-widget.md b/docs/assistant-widget.mdindex 4f878dfe2..946197b7c 100644--- a/docs/assistant-widget.md+++ b/docs/assistant-widget.md@@ -124,7 +124,7 @@ Ask your agent something like "build a 3D assistant widget named Aria with an oc- The launcher and panel are plain DOM injected by [`public/assistant/v1.js`](https://github.com/nirholas/three.ws/blob/main/public/assistant/v1.js), the minified build of the [`@three-ws/assistant`](https://github.com/nirholas/three.ws/tree/main/assistant-sdk) loader (no dependencies, idempotent). The avatar, chat, and speech run inside an iframe on `https://three.ws/assistant-frame`, so your page never sees model keys and the frame never sees your DOM.- The frame ([`src/assistant-frame.js`](https://github.com/nirholas/three.ws/blob/main/src/assistant-frame.js)) renders the avatar with Three.js, retargets the platform's canonical animation clips onto it (idle, wave greeting, a talking loop while speaking), and anchors the speech bubble to the avatar's head projection every frame.-- Free-lane chat posts to `POST /api/chat` (SSE stream, anonymous access, server-side rate limits and moderation). BYOK chat streams directly from the visitor's browser to Groq or OpenRouter with their key; the key lives in `localStorage` on the three.ws origin and is never sent to three.ws servers or the host page.+- Free-lane chat posts to `POST /api/chat` (SSE stream, anonymous access, server-side rate limits; three.ws applies no content filter of its own, so any refusal is the serving model's). BYOK chat streams directly from the visitor's browser to Groq or OpenRouter with their key; the key lives in `localStorage` on the three.ws origin and is never sent to three.ws servers or the host page.- Speak mode and spoken chat replies use the Web Speech API (`speechSynthesis`). Voice pick persists per browser. When the browser has no TTS or voice is muted, the bubble and talking animation still run for the estimated duration, so the widget never silently stalls.- Every config param is re-validated inside the frame by [`src/assistant-widget-core.js`](https://github.com/nirholas/three.ws/blob/main/src/assistant-widget-core.js) (strict background/color grammars, length clamps, avatar host allow-list), so a hostile embedding page cannot inject CSS or URLs into the frame.diff --git a/docs/free-llm-providers.md b/docs/free-llm-providers.mdindex 32df076bd..c2cfef970 100644--- a/docs/free-llm-providers.md+++ b/docs/free-llm-providers.md@@ -1,6 +1,6 @@# Free LLM providers: the failover chain-three.ws never depends on a single AI vendor. Every text completion on the platform (chat, agent brains, copilots, translations, moderation helpers) runs through one shared failover chain that tries free providers first, in order, and only touches a paid key as a last resort. This page is the map of that chain: which providers are in it, what each one costs (nothing), where the keys come from, and how to add the next one.+three.ws never depends on a single AI vendor. Every text completion on the platform (chat, agent brains, copilots, translations) runs through one shared failover chain that tries free providers first, in order, and only touches a paid key as a last resort. This page is the map of that chain: which providers are in it, what each one costs (nothing), where the keys come from, and how to add the next one.The chain lives in [`api/_lib/llm.js`](../api/_lib/llm.js) (`providerChain()` + `llmComplete()`). The interactive chat ladder in [`api/chat.js`](../api/chat.js) uses the same policy with a shorter list (see `DEFAULT_PROVIDER_ORDER` in [`api/_lib/chat-models.js`](../api/_lib/chat-models.js)).diff --git a/docs/nvidia-models.md b/docs/nvidia-models.mdindex fe0e429ff..deb5d9484 100644--- a/docs/nvidia-models.md+++ b/docs/nvidia-models.md@@ -37,7 +37,7 @@ Because it is one key for everything, a deployment either has the whole NVIDIA l| **Vision / VLM** | `nvidia/nemotron-nano-12b-v2-vl`, `meta/llama-3.2-11b-vision-instruct` | `api/_lib/vision.js` | ✅ || **Embeddings** | `nvidia/nv-embedqa-e5-v5`, `baai/bge-m3` | `api/_lib/embeddings.js`, `api/agents/_id/embed.js` | ✅ || **Reranking** | `nvidia/rerank-qa-mistral-4b` | `api/_lib/rerank.js` | ✅ |-| **Content safety** | `nvidia/llama-3.1-nemoguard-8b-content-safety`, `meta/llama-guard-4-12b` | `api/_lib/moderation.js` | ✅ |+| **Content safety** | `nvidia/llama-3.1-nemoguard-8b-content-safety`, `meta/llama-guard-4-12b` | `api/_lib/publish-safety.js` | ✅ || **Text-to-speech** | `magpie-tts-multilingual` (Riva) | `api/_lib/tts-nvidia.js` | ✅ |---@@ -152,11 +152,11 @@ Cosine-over-embeddings recall is cheap but coarse. This **cross-encoder reranker## 7. Content safety — NemoGuard**Primary:** `nvidia/llama-3.1-nemoguard-8b-content-safety` · **Drop-in alt:** `meta/llama-guard-4-12b`-**Endpoint:** `integrate.api.nvidia.com/v1/chat/completions` · **Source:** [api/_lib/moderation.js](../api/_lib/moderation.js).+**Endpoint:** `integrate.api.nvidia.com/v1/chat/completions` · **Source:** [api/_lib/publish-safety.js](../api/_lib/publish-safety.js).-A free content-safety pre-filter for anonymous chat. NemoGuard classifies the inbound user message and returns a **JSON verdict plus named risk categories** (harm, self-harm, weapons, sexual content, …); the parser also accepts Llama Guard's `unsafe\nS#` text form, which is why the two are interchangeable. Median ~340 ms on the free tier.+A free content-safety classifier for what the platform publishes outward. Its only caller is the Sketchfab showcase cron, which uploads visitor-generated models to our own official account on a third party's platform. NemoGuard classifies the source prompt and returns a **JSON verdict plus named risk categories** (harm, self-harm, weapons, sexual content, …); the parser also accepts Llama Guard's `unsafe\nS#` text form, which is why the two are interchangeable. Median ~340 ms on the free tier.-**Scope and posture:** it is a *content*-safety classifier, **not** a jailbreak / prompt-injection detector. It is **fail-open** — anything it can't parse returns "not flagged" so a moderation outage never takes chat down. Only a clean parsed "unsafe" verdict blocks a message.+**Scope and posture:** it screens OUTBOUND publishing only. No three.ws chat surface filters what a user may ask (owner directive 2026-08-07): whatever safety judgment the serving model makes is the only one those routes apply. It is also a *content*-safety classifier, **not** a jailbreak / prompt-injection detector, and it is **fail-open**: anything it can't parse returns "not flagged", so a classifier outage never stops a publish. Only a clean parsed "unsafe" verdict blocks an upload.---diff --git a/docs/nvidia-nemotron-spotlight.md b/docs/nvidia-nemotron-spotlight.mdindex dfbeee0b9..76f79c972 100644--- a/docs/nvidia-nemotron-spotlight.md+++ b/docs/nvidia-nemotron-spotlight.md@@ -89,13 +89,15 @@ Note the comment on line two, because it is the load-bearing design decision inOnce we understood the pattern, we found the same shape everywhere in the product.-**Content safety.** Anonymous visitors can talk to any agent on the platform. We refuse unsafe messages ourselves rather than inheriting a downstream provider's moderation policy, using NVIDIA's `nvidia/llama-3.1-nemoguard-8b-content-safety` from the NeMo Guardrails family. Measured median latency on the free NIM tier: **~340 ms**, with a ~680 ms tail. We give it a 2-second abort budget, which is roughly six times its median. That's generous, and still fast to fail over.+**Publishing safety.** The showcase cron uploads community-forged models to our own official Sketchfab account, and what our brand publishes to a third party's platform is our call to make. That gate runs on NVIDIA's `nvidia/llama-3.1-nemoguard-8b-content-safety` from the NeMo Guardrails family. Measured median latency on the free NIM tier: **~340 ms**, with a ~680 ms tail. We give it a 2-second abort budget, which is roughly six times its median. That's generous, and still fast to fail over.++It used to screen anonymous chat too, and we retired that in August 2026. An 8B classifier judging one message with no conversation context refused plenty of ordinary questions, and a refusal a visitor never earned is a worse product than an answer the serving model would have declined on its own. The lesson generalizes: a guardrail belongs where you own the consequence, which is what you publish, not what someone is allowed to ask.**Reasoning turns.** When a feature wants a compact, reasoning-tuned model to actually lead rather than sit at the tail of a fallback chain, it opts into `nvidia/nvidia-nemotron-nano-9b-v2`. Prompt refinement, classification, structured extraction. A 9B model does these perfectly, and reaching for a frontier model to do them is a tax you pay on every request forever.**Retrieval.** Agent memory embeds through `nvidia/nv-embedqa-e5-v5` at 1024 dimensions, with `nvidia/rerank-qa-mistral-4b` as an optional cross-encoder rerank stage.-Every one of those models, one `nvapi-` key, and a bill of zero. I want to be unambiguous about what that meant for us: **we could not have built this product on paid inference.** Not at the price of a guardrail in front of every generation. The economics only close because NVIDIA hosts these models free, and so the guardrail costs nothing to run.+Every one of those models, one `nvapi-` key, and a bill of zero. I want to be unambiguous about what that meant for us: **we could not have built this product on paid inference.** Not at the price of a second model checking the first on every generation. The economics only close because NVIDIA hosts these models free, and so the judgment layer costs nothing to run.---diff --git a/docs/tutorials/build-a-site-concierge.md b/docs/tutorials/build-a-site-concierge.mdindex 8ca658177..26c19cac5 100644--- a/docs/tutorials/build-a-site-concierge.md+++ b/docs/tutorials/build-a-site-concierge.md@@ -101,7 +101,7 @@ app.post('/my/concierge', async (req, res) => {});```-Then: `<three-concierge endpoint="/my/concierge">`. The production reference, with rate limits, moderation, provider failover, and cooldowns, is [`api/concierge.js`](https://github.com/nirholas/three.ws/blob/main/api/concierge.js).+Then: `<three-concierge endpoint="/my/concierge">`. The production reference, with rate limits, provider failover, and cooldowns, is [`api/concierge.js`](https://github.com/nirholas/three.ws/blob/main/api/concierge.js).## Where to go nextdiff --git a/public/changelog.json b/public/changelog.jsonindex 1b30abcc8..a995c76d8 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-08-06T22:49:14.106Z",+ "generated_at": "2026-08-07T03:41:03.803Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-08-07",+ "type": "update",+ "title": "The chat no longer refuses questions it was never asked to refuse",+ "summary": "Every message sent to a three.ws chat surface used to pass through a small safety classifier of ours before the actual model saw it, and when that classifier said \"unsafe\" you got a canned brush-off instead of an answer. It was wrong often enough to be a real problem: it judged one message at a time with no memory of the conversation, so an ordinary follow-up in a security, trading, or fiction discussion could read as alarming on its own and get blocked, and you were left staring at a refusal no model had actually made. That layer is gone from all of it: the main chat, the /chat app, the embeddable concierge, the widget chat on customer sites, and the agent-idea box on /create. Your question now goes to the model as written. If a model declines something, that is the model exercising its own judgment in its own words, and you can switch models or bring your own key. Nothing else changed: the same rate limits still apply, and the separate confirmation step before any wallet action is untouched. The one place a content check still runs is outbound: what our own official Sketchfab account publishes under the three.ws name.",+ "link": "/chat",+ "tags": [+ "improvement",+ "fix"+ ]+ },{"date": "2026-08-06","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 7da70c9d8..160cf1715 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>The chat no longer refuses questions it was never asked to refuse</title>+ <link>https://three.ws/chat</link>+ <guid isPermaLink="false">2026-08-07:The chat no longer refuses questions it was never asked to refuse</guid>+ <pubDate>Fri, 07 Aug 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Every message sent to a three.ws chat surface used to pass through a small safety classifier of ours before the actual model saw it, and when that classifier said "unsafe" you got a canned brush-off instead of an answer. It was wrong often enough to be a real problem: it judged one message at a time with no memory of the conversation, so an ordinary follow-up in a security, trading, or fiction discussion could read as alarming on its own and get blocked, and you were left staring at a refusal no model had actually made. That layer is gone from all of it: the main chat, the /chat app, the embeddable concierge, the widget chat on customer sites, and the agent-idea box on /create. Your question now goes to the model as written. If a model declines something, that is the model exercising its own judgment in its own words, and you can switch models or bring your own key. Nothing else changed: the same rate limits still apply, and the separate confirmation step before any wallet action is untouched. The one place a content check still runs is outbound: what our own official Sketchfab account publishes under the three.ws name.</description>+ </item><item><title>Airdrop Checker</title><link>https://three.ws/airdrops</link>diff --git a/public/features.json b/public/features.jsonindex b2da795c3..6d92cce50 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-06T22:49:14.092Z",+ "generated_at": "2026-08-07T03:41:03.788Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/api-concierge.test.js b/tests/api-concierge.test.jsindex 48f11d957..5de969fae 100644--- a/tests/api-concierge.test.js+++ b/tests/api-concierge.test.js@@ -1,8 +1,8 @@// POST /api/concierge, the embeddable widget's answer engine. Covers: CORS is// any-origin (the whole point of the route), method/body validation, its own-// rate buckets, fail-open moderation with an in-band refusal, provider-// fallover with cooldown marking on billing/auth failures, and the SSE-// chunk→done stream a healthy rung produces.+// rate buckets, provider fallover with cooldown marking on billing/auth+// failures, and the SSE chunk→done stream a healthy rung produces. Nothing+// screens the visitor question: the concierge has no platform-side filter.import { describe, it, expect, vi, beforeEach } from 'vitest';const conciergeIpMock = vi.fn(async () => ({ success: true }));@@ -15,12 +15,6 @@ vi.mock('../api/_lib/rate-limit.js', () => ({clientIp: () => '203.0.113.9',}));-const moderateMock = vi.fn(async () => ({ checked: true, flagged: false }));-vi.mock('../api/_lib/moderation.js', () => ({- moderateAnonInput: (...a) => moderateMock(...a),- refusalReply: () => 'I can’t help with that, but I’m happy to answer questions about this site.',-}));-const providerChainMock = vi.fn(() => []);vi.mock('../api/_lib/llm.js', () => ({providerChain: (...a) => providerChainMock(...a),@@ -131,7 +125,6 @@ beforeEach(() => {vi.clearAllMocks();conciergeIpMock.mockResolvedValue({ success: true });conciergeGlobalMock.mockResolvedValue({ success: true });- moderateMock.mockResolvedValue({ checked: true, flagged: false });});describe('/api/concierge', () => {@@ -161,17 +154,6 @@ describe('/api/concierge', () => {expect(res.statusCode).toBe(429);});- it('flagged input gets an in-band SSE refusal, never an HTTP error', async () => {- moderateMock.mockResolvedValue({ checked: true, flagged: true });- const res = mkRes();- await handler(mkReq({ body: VALID_BODY }), res);- expect(res.statusCode).toBe(200);- const events = sseEvents(res);- expect(events[0].type).toBe('chunk');- expect(events[0].text).toMatch(/can’t help/);- expect(events.at(-1)).toMatchObject({ type: 'done', moderated: true });- expect(providerChainMock).not.toHaveBeenCalled();- });it('streams chunk→done from a healthy provider, grounded system prompt included', async () => {let capturedBody = null;diff --git a/tests/api/moderation.test.js b/tests/api/publish-safety.test.jssimilarity index 55%rename from tests/api/moderation.test.jsrename to tests/api/publish-safety.test.jsindex 7d707ca6a..7435dba86 100644--- a/tests/api/moderation.test.js+++ b/tests/api/publish-safety.test.js@@ -1,22 +1,27 @@-// Tests for api/_lib/moderation.js — the free anonymous-chat pre-filter-// (NVIDIA NemoGuard). Pins the four mandated invariants:-// 1. BLOCK — a parsed "unsafe" verdict flags the message.-// 2. ALLOW — a parsed "safe" verdict lets it through.-// 3. FAIL-OPEN — any moderation outage (timeout / non-200 / network / garbage)-// proceeds un-moderated; the filter can never block on failure.-// 4. FLAG-OFF — the kill switch (ANON_MODERATION_DISABLED) bypasses entirely,+// Tests for api/_lib/publish-safety.js, the NemoGuard classifier that screens+// what the platform PUBLISHES outward (the Sketchfab showcase cron). Pins the+// four mandated invariants:+// 1. BLOCK: a parsed "unsafe" verdict flags the content.+// 2. ALLOW: a parsed "safe" verdict lets it through.+// 3. FAIL-OPEN: any classifier outage (timeout / non-200 / network / garbage)+// proceeds unblocked; it can never stop publishing on failure.+// 4. FLAG-OFF: the kill switch (PUBLISH_SAFETY_DISABLED) bypasses entirely,// without even touching the network.+//+// It also pins the boundary that motivated the module's rename: no chat surface+// imports it. Input a user sends to a model is never screened by us.++import { readFileSync, readdirSync, statSync } from 'node:fs';+import { join } from 'node:path';import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import {- moderationConfig,- moderationEnabled,- moderateAnonInput,+ publishSafetyConfig,+ publishSafetyEnabled,+ classifyPublishSafety,parseVerdict,- lastUserMessage,- refusalReply,-} from '../../api/_lib/moderation.js';+} from '../../api/_lib/publish-safety.js';const NIM_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';const fetchMock = vi.fn();@@ -32,9 +37,9 @@ function nimReply(content) {function clearEnv() {delete process.env.NVIDIA_API_KEY;- delete process.env.ANON_MODERATION_DISABLED;- delete process.env.ANON_MODERATION_MODEL;- delete process.env.ANON_MODERATION_TIMEOUT_MS;+ delete process.env.PUBLISH_SAFETY_DISABLED;+ delete process.env.PUBLISH_SAFETY_MODEL;+ delete process.env.PUBLISH_SAFETY_TIMEOUT_MS;}beforeEach(() => {@@ -48,32 +53,32 @@ afterEach(() => {clearEnv();});-describe('moderationConfig / moderationEnabled', () => {+describe('publishSafetyConfig / publishSafetyEnabled', () => {it('is disabled with no key (fail-open: nothing to call)', () => {- expect(moderationEnabled()).toBe(false);- expect(moderationConfig().enabled).toBe(false);+ expect(publishSafetyEnabled()).toBe(false);+ expect(publishSafetyConfig().enabled).toBe(false);});it('is enabled when the NIM key is present', () => {process.env.NVIDIA_API_KEY = 'nvapi-test';- const cfg = moderationConfig();+ const cfg = publishSafetyConfig();expect(cfg.enabled).toBe(true);expect(cfg.key).toBe('nvapi-test');expect(cfg.model).toMatch(/nemoguard/);expect(cfg.timeoutMs).toBe(2000);});- it('kill switch ANON_MODERATION_DISABLED disables it even with a key', () => {+ it('kill switch PUBLISH_SAFETY_DISABLED disables it even with a key', () => {process.env.NVIDIA_API_KEY = 'nvapi-test';- process.env.ANON_MODERATION_DISABLED = 'true';- expect(moderationEnabled()).toBe(false);+ process.env.PUBLISH_SAFETY_DISABLED = 'true';+ expect(publishSafetyEnabled()).toBe(false);});it('honors model + timeout overrides (timeout is clamped)', () => {process.env.NVIDIA_API_KEY = 'nvapi-test';- process.env.ANON_MODERATION_MODEL = 'meta/llama-guard-4-12b';- process.env.ANON_MODERATION_TIMEOUT_MS = '999999';- const cfg = moderationConfig();+ process.env.PUBLISH_SAFETY_MODEL = 'meta/llama-guard-4-12b';+ process.env.PUBLISH_SAFETY_TIMEOUT_MS = '999999';+ const cfg = publishSafetyConfig();expect(cfg.model).toBe('meta/llama-guard-4-12b');expect(cfg.timeoutMs).toBe(8000); // clamped to MAX});@@ -112,37 +117,16 @@ describe('parseVerdict', () => {});});-describe('lastUserMessage', () => {- it('returns the latest user turn', () => {- const msgs = [- { role: 'user', content: 'first' },- { role: 'assistant', content: 'reply' },- { role: 'user', content: 'second' },- ];- expect(lastUserMessage(msgs)).toBe('second');- });-- it('flattens multi-part content', () => {- const msgs = [{ role: 'user', content: [{ text: 'hello' }, { text: 'world' }] }];- expect(lastUserMessage(msgs)).toBe('hello world');- });-- it('returns empty string for junk input', () => {- expect(lastUserMessage(null)).toBe('');- expect(lastUserMessage([{ role: 'assistant', content: 'x' }])).toBe('');- });-});--describe('moderateAnonInput', () => {+describe('classifyPublishSafety', () => {it('BLOCK: flags a parsed unsafe verdict', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';fetchMock.mockResolvedValueOnce(- nimReply('{"User Safety": "unsafe", "Safety Categories": "Suicide and Self Harm"}'),+ nimReply('{"User Safety": "unsafe", "Safety Categories": "Guns and Illegal Weapons"}'),);- const r = await moderateAnonInput('something harmful');+ const r = await classifyPublishSafety('a prompt we would not publish');expect(r.flagged).toBe(true);expect(r.checked).toBe(true);- expect(r.categories).toEqual(['Suicide and Self Harm']);+ expect(r.categories).toEqual(['Guns and Illegal Weapons']);expect(fetchMock).toHaveBeenCalledTimes(1);expect(fetchMock.mock.calls[0][0]).toBe(NIM_URL);});@@ -150,7 +134,7 @@ describe('moderateAnonInput', () => {it('ALLOW: a safe verdict passes through', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';fetchMock.mockResolvedValueOnce(nimReply('{"User Safety": "safe"}'));- const r = await moderateAnonInput('what is the capital of France?');+ const r = await classifyPublishSafety('a low-poly wooden chair');expect(r.flagged).toBe(false);expect(r.checked).toBe(true);});@@ -158,7 +142,7 @@ describe('moderateAnonInput', () => {it('FAIL-OPEN: non-200 upstream does not flag', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';fetchMock.mockResolvedValueOnce({ ok: false, status: 403, text: async () => 'Forbidden' });- const r = await moderateAnonInput('anything');+ const r = await classifyPublishSafety('anything');expect(r.flagged).toBe(false);expect(r.checked).toBe(false);expect(r.error).toMatch(/403/);@@ -167,7 +151,7 @@ describe('moderateAnonInput', () => {it('FAIL-OPEN: a thrown/aborted fetch does not flag', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';fetchMock.mockRejectedValueOnce(Object.assign(new Error('aborted'), { name: 'AbortError' }));- const r = await moderateAnonInput('anything');+ const r = await classifyPublishSafety('anything');expect(r.flagged).toBe(false);expect(r.checked).toBe(false);expect(r.error).toBe('timeout');@@ -176,28 +160,28 @@ describe('moderateAnonInput', () => {it('FAIL-OPEN: garbage model output does not flag', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';fetchMock.mockResolvedValueOnce(nimReply('uh, I am not sure about that one'));- const r = await moderateAnonInput('anything');+ const r = await classifyPublishSafety('anything');expect(r.flagged).toBe(false);expect(r.checked).toBe(false);});it('FLAG-OFF: kill switch bypasses without touching the network', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';- process.env.ANON_MODERATION_DISABLED = 'true';- const r = await moderateAnonInput('something harmful');+ process.env.PUBLISH_SAFETY_DISABLED = 'true';+ const r = await classifyPublishSafety('anything');expect(r.flagged).toBe(false);expect(fetchMock).not.toHaveBeenCalled();});- it('FAIL-OPEN: no key configured → no call, no flag', async () => {- const r = await moderateAnonInput('something harmful');+ it('FAIL-OPEN: no key configured, no call and no flag', async () => {+ const r = await classifyPublishSafety('anything');expect(r.flagged).toBe(false);expect(fetchMock).not.toHaveBeenCalled();});- it('empty message is a no-op (nothing to moderate)', async () => {+ it('empty text is a no-op (nothing to classify)', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';- const r = await moderateAnonInput(' ');+ const r = await classifyPublishSafety(' ');expect(r.flagged).toBe(false);expect(fetchMock).not.toHaveBeenCalled();});@@ -205,21 +189,43 @@ describe('moderateAnonInput', () => {it('sends the NemoGuard request shape (single user turn, temp 0)', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';fetchMock.mockResolvedValueOnce(nimReply('{"User Safety": "safe"}'));- await moderateAnonInput('hello there');+ await classifyPublishSafety('a low-poly wooden chair');const body = JSON.parse(fetchMock.mock.calls[0][1].body);expect(body.model).toMatch(/nemoguard/);expect(body.temperature).toBe(0);- expect(body.messages).toEqual([{ role: 'user', content: 'hello there' }]);+ expect(body.messages).toEqual([{ role: 'user', content: 'a low-poly wooden chair' }]);expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer nvapi-test');});});-describe('refusalReply', () => {- it('is a non-empty, non-preachy in-band reply', () => {- const r = refusalReply();- expect(typeof r).toBe('string');- expect(r.length).toBeGreaterThan(0);- // no lecture / "as an AI" boilerplate- expect(r.toLowerCase()).not.toMatch(/as an ai|i am just|policy|guidelines/);+// Owner directive 2026-08-07: the platform screens what it publishes, never what+// a user asks. This walks the real api/ tree so a future edit that reintroduces+// an input filter on a chat surface fails here instead of in production.+describe('no chat surface imports a content classifier', () => {+ const API_DIR = new URL('../../api/', import.meta.url).pathname;+ const ALLOWED = ['cron/sketchfab-showcase.js'];++ function walk(dir, prefix = '') {+ const out = [];+ for (const entry of readdirSync(dir)) {+ if (entry === 'node_modules') continue;+ const full = join(dir, entry);+ const rel = prefix ? `${prefix}/${entry}` : entry;+ if (statSync(full).isDirectory()) out.push(...walk(full, rel));+ else if (entry.endsWith('.js')) out.push({ rel, full });+ }+ return out;+ }++ it('only the outbound publishing cron imports publish-safety.js', () => {+ const importers = walk(API_DIR)+ .filter(({ full }) => /from\s+['"][^'"]*publish-safety\.js['"]/.test(readFileSync(full, 'utf8')))+ .map(({ rel }) => rel);+ expect(importers.sort()).toEqual([...ALLOWED].sort());+ });++ it('the retired moderation module is gone, not merely unused', () => {+ const survivors = walk(API_DIR).filter(({ rel }) => rel.endsWith('_lib/moderation.js'));+ expect(survivors).toEqual([]);});});diff --git a/tests/llm-metering-rule.test.js b/tests/llm-metering-rule.test.jsindex a4f62941c..db5d37f6a 100644--- a/tests/llm-metering-rule.test.js+++ b/tests/llm-metering-rule.test.js@@ -82,7 +82,7 @@ describe('attribution', () => {expect(classifyMeteringLane({ provider: null, model: null, tokens: 1000, costMicroUsd: 0 }).status).toBe('fail');});- it('skips a zero-token event with no provider (a moderation refusal)', () => {+ it('skips a zero-token event with no provider (nothing reached an upstream)', () => {const v = classifyMeteringLane({ provider: null, model: null, tokens: 0, costMicroUsd: 0, unpricedCalls: 33 });expect(v.status).toBe('skip');});