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(x-mentions): answer a launch mention with a prefilled /launch link the author signs themselves
nirholasc3e24a281a9b
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex c972573aa..8c53a273a 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -422,6 +422,7 @@ packages, a generated standalone GitHub mirror). See| X content pipeline (internal) | Queue [data/x-content/queue.json](data/x-content/queue.json), engine [api/_lib/x-content/](api/_lib/x-content), cron [api/cron/x-content.js](api/cron/x-content.js), CLI [scripts/x-content.mjs](scripts/x-content.mjs), media `public/x-media/` | Internal · docs [docs/x-content-pipeline.md](docs/x-content-pipeline.md), [docs/x-story-authoring.md](docs/x-story-authoring.md), [docs/x-reply-playbook.md](docs/x-reply-playbook.md) | The reviewed @trythreews publishing queue: posts and threads with native images, GIFs, and captioned video, blog or external pages imported as native posts or full X Articles (via the X Articles API), a copy lint against automated-feed tells, jittered cadence with lane rotation, and a database ledger that resumes a half-sent thread instead of reposting. A post's video is a proof reel ([reel.js](api/_lib/x-content/reel.js)): a filmed, passing end-to-end run of its own scenario against production, so a feature that does not work cannot be announced. The queue learns from its own measured results ([outcomes.js](api/_lib/x-content/outcomes.js)), releases filmed posts by policy with a veto window ([approval.js](api/_lib/x-content/approval.js)), and can ship an approved post without a deploy as a signed bundle ([overlay.js](api/_lib/x-content/overlay.js)). A daily partner spotlight ([partners.js](api/_lib/x-content/partners.js), CLI [scripts/x-partners.mjs](scripts/x-partners.mjs), registry [data/x-content/partners/](data/x-content/partners), docs [docs/x-partner-series.md](docs/x-partner-series.md)) owns the prime-time slot: one partner and one feature built on it each day, filmed live, drafted from registry facts only, plus a weekly partner deep-dive X Article built from every feature's run, and a scheduled Cloud Run Job runner ([deploy/x-partners/](deploy/x-partners), setup [scripts/create-x-partners-job.mjs](scripts/create-x-partners-job.mjs)). Previews only until `X_CONTENT_AUTO_PUBLISH=true`. Tests: [tests/x-content.test.js](tests/x-content.test.js), [x-content-reel](tests/x-content-reel.test.js), [x-content-approval](tests/x-content-approval.test.js), [x-content-outcomes](tests/x-content-outcomes.test.js), [x-content-overlay](tests/x-content-overlay.test.js), [x-content-partners](tests/x-content-partners.test.js) || X post archive + engagement analysis (internal) | Snapshots [data/x-archive/](data/x-archive), schema [api/_lib/migrations/20260814120000_x_account_archive.sql](api/_lib/migrations/20260814120000_x_account_archive.sql), normalization + analysis [scripts/x-archive-lib.mjs](scripts/x-archive-lib.mjs), commands [scripts/x-archive-import.mjs](scripts/x-archive-import.mjs) · [scripts/x-archive-refresh.mjs](scripts/x-archive-refresh.mjs) · [scripts/x-archive-analyze.mjs](scripts/x-archive-analyze.mjs), report [docs/x-archive/](docs/x-archive) | Internal · doc [docs/x-archive.md](docs/x-archive.md) | Every post our own X accounts published, kept as raw snapshot files and indexed into `x_account_posts` / `x_account_post_snapshots` so engagement is a measured time series rather than a memory. `npm run x:archive:analyze` regenerates a report ranking posts by engagement and by engagement *rate*, and scores every measurable signal (media, mentions, length, subject, hour) as lift against the corpus median. Two scraper defects are handled rather than inherited: a profile scrape returns reposts of other accounts with `isRetweet: false` (authorship is read from the permalink instead), and X renders like counts lazily so real posts arrive at "0 likes" (those are archived, named, and excluded from the medians until `npm run x:archive:refresh` replaces them with exact X API counters). Distinct from `x_posts`, which is what platform users publish through [api/x/post.js](api/x/post.js). `npm run x:archive:price` ([scripts/x-archive-price-impact.mjs](scripts/x-archive-price-impact.mjs), logic in [api/_lib/x-content/price-impact.js](api/_lib/x-content/price-impact.js)) joins every post to the $THREE/SOL price at post time and its +1h/+4h/+24h returns against an any-time baseline, writes [public/data/trythreews-post-impact.json](public/data/trythreews-post-impact.json) for the Posts view on the $THREE oracle chart ([public/oracle-coin.js](public/oracle-coin.js)), and stamps the content pipeline's outcome rows with a +24h price return ([api/_lib/x-content/outcomes.js](api/_lib/x-content/outcomes.js)). Tests: [tests/x-archive.test.js](tests/x-archive.test.js) || X mention-reply bot + operator console | Reader [api/_lib/x-mentions.js](api/_lib/x-mentions.js), real-time webhook [api/x/webhook.js](api/x/webhook.js) `→ /api/x/webhook` (Account Activity API, CRC + HMAC signature verified, gated by `X_WEBHOOK_ENABLED`), pure intent parser [api/_lib/x-mention-intents.js](api/_lib/x-mention-intents.js), ledger [api/_lib/x-mention-store.js](api/_lib/x-mention-store.js) (`x_mention_events`), per-agent decisions endpoint [api/x/mention-decisions.js](api/x/mention-decisions.js) `→ /api/x/mention-decisions`, operator controls [api/_lib/x-mention-admin.js](api/_lib/x-mention-admin.js) (kill switch, blocklist, live-send), console API [api/x/ops/[action].js](api/x/ops/%5Baction%5D.js) `→ /api/x/ops/*`, console page [pages/x-ops.html](pages/x-ops.html) + [src/x-ops.js](src/x-ops.js) + [src/x-ops.css](src/x-ops.css) `→ /x/ops` (admin-only, noindex), health [api/_lib/x-mention-health.js](api/_lib/x-mention-health.js) feeding `/api/healthz`, public status [api/x/mention-bot/status.js](api/x/mention-bot/status.js) `→ /api/x/mention-bot/status` (shown on [/grok](pages/grok.html)) | Console: Live (admin-only) · Webhook: receives and records (not yet live-replying) · doc [docs/x-mention-bot.md](docs/x-mention-bot.md) (internal) | Every `@`-mention of a company or agent X account, delivered by polling or by the Account Activity webhook, is parsed into one of seven intents (never treated as an instruction to spend, transfer, launch or post on its own) and recorded once per tweet id before any reply is composed; a reply can be captured dry-run (recorded, never sent) or live. `/x/ops` is the admin review surface over that ledger: filter by account, intent, decision and dry-run status, read the full mention and would-be-reply text, pause or resume the bot (`app_settings` kill switch, also honored via `X_MENTION_BOT_PAUSED`), blocklist or unblock an author, and, for one dry-run `reply` row, send that exact already-composed reply live (company account via OAuth 1.0a, agent account via its own OAuth2 connection) behind an explicit "this posts publicly" confirmation. The enforcement side (a poll cron honoring the kill switch and blocklist, composing and sending replies automatically) is a separate piece of work tracked in the x-grok campaign; this console and webhook only ever write the switches and ledger rows they are responsible for. Tests: [tests/x-ops-authorization.test.js](tests/x-ops-authorization.test.js), [tests/api/x-webhook.test.js](tests/api/x-webhook.test.js), [tests/x-mention-health.test.js](tests/x-mention-health.test.js) |+| X launch-by-mention | Handler [api/_lib/x-mention-launch.js](api/_lib/x-mention-launch.js) (called from `composeAnswer` in [api/_lib/x-mention-poll.js](api/_lib/x-mention-poll.js)), grammar `parseLaunch` in [api/_lib/x-mention-intents.js](api/_lib/x-mention-intents.js) | Dry run until `X_MENTION_BOT_LIVE=1` (owner order 928) · doc [docs/x-mention-bot.md](docs/x-mention-bot.md#launch-by-mention) | `@trythreews launch <NAME> $<TICKER> [description]` is answered with a prefilled `/launch` link for the author's linked three.ws agent (or a sign-in, create-agent or give-it-a-body link). The bot never launches or spends: the author reviews the cost and signs on three.ws. Tests: [tests/x-mention-launch.test.js](tests/x-mention-launch.test.js) || Interactive 3D history timeline | [pages/timeline.html](pages/timeline.html) `→ /timeline`, [src/timeline.js](src/timeline.js), data [data/timeline.json](data/timeline.json) | Live | three.ws's public history (launches, partnerships, listings, press, product ships) as an explorable 3D scene: 60+ milestones as glowing markers along a curved path, 360° free-orbit or a marker-to-marker Walk mode with a guide beacon (reuses the shared `AnimationManager` + default rig from [src/walk.js](src/walk.js)'s pattern), a synced bottom scrubber, category filters, and a detail panel linking to the original source where one exists (IBM Community, NVIDIA Developer Forums, Yahoo Finance, Phemex, CoinGecko, HackerNoon). Real accessible HTML-list fallback for no-WebGL or fetch-failure. || Upstream resilience toolkit | [scripts/resilience/](scripts/resilience) + [scripts/audit-upstreams.mjs](scripts/audit-upstreams.mjs) `→ npm run audit:upstreams`, baseline [data/upstream-baseline.json](data/upstream-baseline.json), generated map [docs/resilience.md](docs/resilience.md) | Live | Answers the question a fallback alone cannot: when a third-party service is down, what is each endpoint ALLOWED to say? An AST pass grades every outbound call site on five protections (deadline, retry, failover, last-good, breaker) and ratchets against a committed baseline, so a new unbounded call fails the build while the existing tail is paid down at its own pace. On top of it, endpoints declare a degradation contract (`may-serve-stale`, `must-refuse`, `must-not-serve-stale`) that [tests/upstream-degradation.test.js](tests/upstream-degradation.test.js) proves by replacing fetch with a dead upstream and judging the real response. Built after four fallbacks that each passed review turned out to serve remembered data on paths where staleness costs money or grants access. Complements [scripts/check-fetch-timeouts.mjs](scripts/check-fetch-timeouts.mjs), which enforces the deadline floor. Docs: [scripts/resilience/README.md](scripts/resilience/README.md) || Ecosystem hubs (curated directories) | [hubs/](hubs) | Ready to publish as separate repos | Eleven self-contained JSON-backed awesome-list hubs (agent payments, identity, wallets, protocols, skills, data APIs, browser agents, Solana agents, embodied agents, generative 3D, Robinhood Crypto), each with schema, validator, README generator and contribution templates. Index: [hubs/README.md](hubs/README.md) |diff --git a/api/_lib/x-mention-launch.js b/api/_lib/x-mention-launch.jsnew file mode 100644index 000000000..0d488b2b2--- /dev/null+++ b/api/_lib/x-mention-launch.js@@ -0,0 +1,79 @@+// The `launch` intent of the X mention bot: "@trythreews launch Moon Cat $MCAT".+//+// This module NEVER launches anything. A launch signs with the agent's+// custodial wallet, and three.ws allows that only from a same-site browser+// session (requireSessionUser in api/pump/[action].js). So the only product of+// a launch mention is one reply to the author: a prefilled /launch link they+// open, review the cost on, and sign themselves. Nothing is paid until then.+//+// The mention text is untrusted data. By the time it reaches here it has been+// reduced by the pure parser (x-mention-intents.js parseLaunch) to a name, a+// ticker and a description of bounded length; this module only places those+// three strings in URL query parameters (URLSearchParams encodes them) and in+// no other position that could be read as an instruction. The author is+// resolved from the X user id X itself attached to the post, never from text.+//+// Three outcomes, each a plain reply:+// linked author with an agent that has a 3D body -> the prefilled /launch link+// linked author with no agent or no body -> a link to create one+// author not linked to a three.ws account -> the sign-in and X linking link++import { sql } from './db.js';+import { findUserByXId } from './x-identity.js';+import { claimUrl } from './x-creation-claim.js';++export const LAUNCH_NO_SPEND_LINE = 'Nothing is paid until you review and sign on three.ws.';++/** The agent that would launch for this user: newest live agent that has a 3D body. */+export async function launchAgentForUser(userId) {+ const [row] = await sql`+ select id, name, avatar_id from agent_identities+ where user_id = ${userId} and deleted_at is null and avatar_id is not null+ order by created_at desc+ limit 1+ `;+ if (row) return { id: row.id, name: row.name, avatarId: row.avatar_id, hasBody: true };+ const [bare] = await sql`+ select id, name from agent_identities+ where user_id = ${userId} and deleted_at is null+ order by created_at desc+ limit 1+ `;+ return bare ? { id: bare.id, name: bare.name, avatarId: null, hasBody: false } : null;+}++/** The /launch URL with the coin fields prefilled. PURE. */+export function launchUrl(base, { avatarId, name, symbol, description }) {+ const url = new URL('/launch', base);+ url.searchParams.set('avatar', avatarId);+ url.searchParams.set('name', name);+ url.searchParams.set('symbol', symbol);+ if (description) url.searchParams.set('description', description);+ return url.toString();+}++/**+ * Decide the reply to a parsed launch mention.+ *+ * @param {{ args: { name: string, symbol: string, description?: string }, authorId: string|null, base: string }} input+ * @param {{ findUser?: typeof findUserByXId, findAgent?: typeof launchAgentForUser }} [deps]+ * @returns {Promise<{ text: string, reason: string, link: string }>}+ */+export async function composeLaunchReply({ args, authorId, base }, deps = {}) {+ const user = authorId ? await (deps.findUser || findUserByXId)(String(authorId)) : null;+ if (!user) {+ const link = claimUrl(base);+ return { text: `Sign in to three.ws and connect this X account first, then ask again: ${link} ${LAUNCH_NO_SPEND_LINE}`, reason: 'launch_unlinked', link };+ }+ const agent = await (deps.findAgent || launchAgentForUser)(user.user_id);+ if (!agent) {+ const link = `${base}/create`;+ return { text: `You need an agent before you can launch its coin. Create one here: ${link}`, reason: 'launch_no_agent', link };+ }+ if (!agent.hasBody) {+ const link = `${base}/agents/${agent.id}`;+ return { text: `${agent.name} needs a 3D body before it can launch a coin. Give it one here: ${link}`, reason: 'launch_no_body', link };+ }+ const link = launchUrl(base, { avatarId: agent.avatarId, name: args.name, symbol: args.symbol, description: args.description });+ return { text: `${args.name} ($${args.symbol}) is ready to launch with ${agent.name}. Review the cost and sign here: ${link} ${LAUNCH_NO_SPEND_LINE}`, reason: 'launch_link', link };+}diff --git a/api/_lib/x-mention-poll.js b/api/_lib/x-mention-poll.jsindex 8e4f7fec6..159868f1d 100644--- a/api/_lib/x-mention-poll.js+++ b/api/_lib/x-mention-poll.js@@ -36,6 +36,8 @@ import * as xBudget from './x-budget.js';import { handleAvatar, finishPendingAvatars } from './x-mention-avatar.js';import { finishPendingMakes } from './x-mention-make.js';import { handleImage3d, finishPendingImage3d } from './x-mention-image3d.js';+import { composeLaunchReply } from './x-mention-launch.js';+import { selfOrigin } from './self-origin.js';import { createDeliver } from './x-mention-deliver.js';import { xBotLive } from './gateway/adapters/x.js';import { agentMentionAccounts, agentPosterUrl, agentTokenResolver, intentAllowed, tokenResolverForRow } from './x-agent-mentions.js';@@ -49,7 +51,7 @@ const DAY = 86400;const REFUSED_REPLY = 'I cannot move funds or handle keys, and no one can ask me to. I make 3D models: try "make a red vintage scooter". https://three.ws/grok';/** Intents whose dedicated handler is a later order; they answer with help until it lands. */-const UNBUILT_HANDLERS = Object.freeze(new Set(['make', 'launch']));+const UNBUILT_HANDLERS = Object.freeze(new Set(['make']));function intEnv(env, name, fallback) {const n = Number.parseInt(env[name] ?? '', 10);@@ -96,10 +98,14 @@ export async function overReplyLimit(authorId, account, limits, store = mentionS}/** The text a parsed mention is answered with, or why it is not answered. */-async function composeAnswer({ mention, parsed, account, compose, agent = null }) {+async function composeAnswer({ mention, parsed, account, compose, agent = null, launch = composeLaunchReply }) {if (parsed.intent === 'help') {return { text: parsed.args?.topic === 'refused' ? REFUSED_REPLY : FIXED_HELP_REPLY, reason: parsed.reason };}+ if (parsed.intent === 'launch') {+ const reply = await launch({ args: parsed.args, authorId: mention.userId || mention.author?.id || null, base: selfOrigin() });+ return { text: reply.text, reason: reply.reason };+ }if (UNBUILT_HANDLERS.has(parsed.intent)) {return { text: FIXED_HELP_REPLY, reason: 'handler_not_built' };}@@ -112,7 +118,7 @@ async function composeAnswer({ mention, parsed, account, compose, agent = null }* Only ever throws for a store failure on the mention row itself, which the* caller treats as "not fully recorded" and stops the batch there.*/-export async function handleMention({ mention, account, limits, env, store = mentionStore, compose = composePublicReply, adapterFactory = createXAdapter, guard = guardMention, paused = isPaused, budget = xBudget, request = null, onBehalf = answerOnBehalf, knownBots = null, avatar = handleAvatar, image3d = handleImage3d, agentCtx = null, posterFor = agentPosterUrl }) {+export async function handleMention({ mention, account, limits, env, store = mentionStore, compose = composePublicReply, adapterFactory = createXAdapter, guard = guardMention, paused = isPaused, budget = xBudget, request = null, onBehalf = answerOnBehalf, knownBots = null, avatar = handleAvatar, image3d = handleImage3d, agentCtx = null, posterFor = agentPosterUrl, launch = composeLaunchReply }) {const parsed = parseMentionIntent(mention, account);// The company account is always dry run here. An agent answers for real only// when its owner turned dry run off AND the operator's global switch is on.@@ -186,7 +192,7 @@ export async function handleMention({ mention, account, limits, env, store = menif (result.decision === 'reply') await budget.recordPosts(1);return { tweetId: mention.id, intent: 'image3d', decision: result.decision, reason: result.reason, text: result.text, dry_run: dryRun };}- const answer = await composeAnswer({ mention, parsed, account, compose, agent: agentCtx?.agent || null });+ const answer = await composeAnswer({ mention, parsed, account, compose, agent: agentCtx?.agent || null, launch });const adapter = adapterFactory({ mention, parsed, env, policyDryRun: agentCtx ? dryRun : true, getAccessToken });const poster = agentCtx && parsed.intent === 'chat' ? await posterFor(agentCtx.agent).catch(() => null) : null;if (poster) await adapter.sendMedia(mention.id, { url: poster, caption: answer.text });diff --git a/data/changelog.json b/data/changelog.jsonindex 0b48779bc..e23fdc194 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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-24",+ "title": "Mention the bot with a coin idea and get a prefilled launch link",+ "summary": "Post \"@trythreews launch Moon Cat $MCAT a cat on the moon\" and the bot answers with a three.ws launch link that already has the name, ticker and description filled in for your agent. The bot never launches anything: you review the cost and sign on three.ws yourself, and the reply says so. Authors whose X account is not linked get a link to sign in and connect it, and linked authors without an agent or a 3D body get a link to create one. The bot is in dry run until the owner turns it live: replies are recorded for review and nothing is posted.",+ "tags": [+ "feature",+ "agents"+ ],+ "link": "/grok"+ },{"date": "2026-10-23","title": "Token due diligence: insiders, snipers, bundlers, fresh wallets and a funding graph",diff --git a/docs/x-mention-bot.md b/docs/x-mention-bot.mdindex 4ffd544a0..97ec1c68b 100644--- a/docs/x-mention-bot.md+++ b/docs/x-mention-bot.md@@ -8,10 +8,8 @@ reviewed, and what is and is not wired yet.For the sibling capability that lets an X account *sign in* to three.ws(rather than be read as a mention), see the "Account linking" section below.-For the launch-by-mention intent (`launch <NAME> $<TICKER>`), see-`prompts/finish/925-parity-15-mention-to-launch.md`: it plugs its reply into-the same parser and the same ledger this doc covers, and this file is the one-place it should extend rather than write a second mention doc.+For the launch-by-mention intent (`launch <NAME> $<TICKER>`), see the+"Launch by mention" section below.## Design rules@@ -313,8 +311,34 @@ wait is recorded as `pending`. Every `x-mentions` tick then runsas `paused` for lack of a deliver.The `image3d` intent is routed to `handleImage3d()` in `handleMention` (dry-run, same budget and per-author limits as any reply); only `make` and-`launch` still answer with help (`handler_not_built`).+run, same budget and per-author limits as any reply); only `make` still+answers with help (`handler_not_built`).++## Launch by mention++`@trythreews launch Moon Cat $MCAT a cat on the moon` is answered with a link,+never a launch. Launching signs with the agent's custodial wallet, which+three.ws allows only from a same-site browser session, so the bot has no+spend path at all: `api/_lib/x-mention-launch.js` imports a database handle,+the X identity lookup and a URL helper, and nothing that can sign, pay or call+a launch API (a test asserts the import list). The grammar is+`parseLaunch` in `api/_lib/x-mention-intents.js`; tweet text reaches the+reply only as URL-encoded query values of the `/launch` link.++| Author | Reply | `reason` |+|---|---|---|+| X account linked to a three.ws account, with an agent that has a 3D body | Prefilled `/launch?avatar=...&name=...&symbol=...&description=...` plus "Nothing is paid until you review and sign on three.ws." | `launch_link` |+| Linked, agent without a body | Link to the agent page to give it one | `launch_no_body` |+| Linked, no agent | Link to `/create` | `launch_no_agent` |+| Not linked (`findUserByXId`) | Link to `/x/claim` to sign in and connect X | `launch_unlinked` |++The author is the X user id X attached to the post, never anything in the text.+The agent is the newest live agent of the linked user that has a 3D body. The+polling cron (`/api/cron/x-mentions`, every two minutes), the cursor, dedupe+by tweet id, per-author limits and the decision ledger are the ones every+other intent uses. With `X_MENTION_BOT_LIVE` unset the company account only+records the reply it would send (`x_mention_events.reply_text`, visible in+`/x/ops`); nothing is posted. Going live is the owner step (order 928).Going live stays the separate owner step.diff --git a/tests/x-mention-launch.test.js b/tests/x-mention-launch.test.jsnew file mode 100644index 000000000..72fac49cc--- /dev/null+++ b/tests/x-mention-launch.test.js@@ -0,0 +1,105 @@+import { readFileSync } from 'node:fs';+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { PGlite } from '@electric-sql/pglite';++const dbState = { pg: null };+vi.mock('../api/_lib/db.js', () => {+ const sql = async (strings, ...values) => {+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');+ return (await dbState.pg.query(text, values)).rows;+ };+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});+vi.mock('../api/auth/x/[action].js', () => ({ encryptToken: (s) => s, decryptToken: (s) => s }));++const { composeLaunchReply, launchUrl, launchAgentForUser, LAUNCH_NO_SPEND_LINE } = await import('../api/_lib/x-mention-launch.js');+const poll = await import('../api/_lib/x-mention-poll.js');+const store = await import('../api/_lib/x-mention-store.js');+const { parseMentionIntent } = await import('../api/_lib/x-mention-intents.js');+const { weightedLength, X_POST_MAX_WEIGHT } = await import('../api/_lib/x-text-weight.js');++const BASE = 'https://three.ws';+const ARGS = { name: 'Moon Cat', symbol: 'MCAT', description: 'a cat on the moon' };+const AVATAR = '5b1f2c52-0000-4000-8000-000000000001';+const user = (id = 'u1') => async () => ({ user_id: id, username: 'alice' });++describe('composeLaunchReply', () => {+ it('gives a linked author with a bodied agent the prefilled /launch link', async () => {+ const r = await composeLaunchReply({ args: ARGS, authorId: '42', base: BASE }, { findUser: user(), findAgent: async () => ({ id: 'a1', name: 'Nova', avatarId: AVATAR, hasBody: true }) });+ expect(r.reason).toBe('launch_link');+ const u = new URL(r.link);+ expect(u.pathname).toBe('/launch');+ expect(Object.fromEntries(u.searchParams)).toEqual({ avatar: AVATAR, name: 'Moon Cat', symbol: 'MCAT', description: 'a cat on the moon' });+ expect(r.text).toContain(LAUNCH_NO_SPEND_LINE);+ expect(weightedLength(r.text)).toBeLessThanOrEqual(X_POST_MAX_WEIGHT);+ expect([...r.text].some((ch) => ch.charCodeAt(0) === 0x2013 || ch.charCodeAt(0) === 0x2014)).toBe(false);+ });++ it('sends an unlinked author to sign-in and X linking, with no launch link', async () => {+ const r = await composeLaunchReply({ args: ARGS, authorId: '42', base: BASE }, { findUser: async () => null });+ expect(r.reason).toBe('launch_unlinked');+ expect(r.text).not.toContain('/launch');+ });++ it('sends an author with no agent to create one, and one with no body to give it one', async () => {+ const none = await composeLaunchReply({ args: ARGS, authorId: '42', base: BASE }, { findUser: user(), findAgent: async () => null });+ expect(none).toMatchObject({ reason: 'launch_no_agent', link: `${BASE}/create` });+ const bare = await composeLaunchReply({ args: ARGS, authorId: '42', base: BASE }, { findUser: user(), findAgent: async () => ({ id: 'a1', name: 'Nova', avatarId: null, hasBody: false }) });+ expect(bare).toMatchObject({ reason: 'launch_no_body', link: `${BASE}/agents/a1` });+ });++ it('treats hostile text as data: it only ever lands URL-encoded in query values', () => {+ const url = launchUrl(BASE, { avatarId: AVATAR, name: 'x&avatar=evil', symbol: 'A', description: '"><script>https://evil.example</script>' });+ const u = new URL(url);+ expect(u.origin).toBe(BASE);+ expect(u.searchParams.get('avatar')).toBe(AVATAR);+ expect(u.searchParams.get('name')).toBe('x&avatar=evil');+ });++ it('has no path to a spend: the module imports no signer, wallet, payment or launch API', () => {+ const src = readFileSync(new URL('../api/_lib/x-mention-launch.js', import.meta.url), 'utf8');+ const imports = [...src.matchAll(/^import .* from '(.+)';$/gm)].map((m) => m[1]);+ expect(imports.sort()).toEqual(['./db.js', './x-creation-claim.js', './x-identity.js']);+ const code = src.replace(/^\/\/.*$/gm, '');+ expect(code).not.toMatch(/fetch\(|sendTransaction|signTransaction|x402|pump\//);+ });+});++describe('against the real tables', () => {+ beforeEach(async () => {+ dbState.pg = new PGlite();+ await dbState.pg.exec(`create table agent_identities (id uuid primary key default gen_random_uuid(), user_id text not null, name text, avatar_id uuid, created_at timestamptz not null default now(), deleted_at timestamptz);`);+ });++ it('prefers the newest live agent with a body and ignores deleted ones', async () => {+ await dbState.pg.query(`insert into agent_identities (user_id, name, avatar_id, created_at) values ('u1','Old',$1, now() - interval '2 day'), ('u1','New',$1, now())`, [AVATAR]);+ await dbState.pg.query(`insert into agent_identities (user_id, name, avatar_id, deleted_at) values ('u1','Gone',$1, now())`, [AVATAR]);+ expect(await launchAgentForUser('u1')).toMatchObject({ name: 'New', avatarId: AVATAR, hasBody: true });+ expect(await launchAgentForUser('nobody')).toBeNull();+ });+});++describe('the poll loop with a launch mention (dry run)', () => {+ const MIG = new URL('../api/_lib/migrations/', import.meta.url);+ const COMPANY = { kind: 'company', ref: 'trythreews', userId: '1700000000000000001', handle: 'trythreews' };++ it('records the would-be reply with the link and posts nothing', async () => {+ dbState.pg = new PGlite();+ const src = readFileSync(new URL('20260922210000_free_tier_models.sql', MIG), 'utf8');+ const start = src.indexOf('CREATE TABLE IF NOT EXISTS app_settings');+ await dbState.pg.exec(src.slice(start, src.indexOf(');', start) + 2));+ await dbState.pg.exec(readFileSync(new URL('20261008170000_x_mention_events.sql', MIG), 'utf8'));+ const id = '1900000000000000777';+ const mention = {+ id, userId: '42', username: 'alice', text: '@trythreews launch Moon Cat $MCAT a cat on the moon', createdAt: new Date().toISOString(), conversationId: id, account: COMPANY,+ mentions: [{ username: 'trythreews', id: COMPANY.userId }], urls: [], media: [], inReplyToUserId: null, repliedTo: null, quoted: null, isRetweet: false, fromSelf: false,+ };+ expect(parseMentionIntent(mention, COMPANY).intent).toBe('launch');+ const budget = { readGate: async () => ({ allow: true }), budgetGate: async () => ({ allow: true }), recordPosts: vi.fn(async () => {}) };+ const launch = (e) => composeLaunchReply(e, { findUser: user(), findAgent: async () => ({ id: 'a1', name: 'Nova', avatarId: AVATAR, hasBody: true }) });+ const out = await poll.handleMention({ mention, account: COMPANY, limits: poll.replyLimits({}), env: {}, budget, paused: async () => false, guard: async () => ({ allow: true }), launch });+ expect(out).toMatchObject({ intent: 'launch', decision: 'reply', reason: 'launch_link', dry_run: true });+ expect(out.text).toContain('/launch?avatar=');+ expect(await store.getMentionEvent(id)).toMatchObject({ intent: 'launch', decision: 'reply', dry_run: true, reply_tweet_id: null });+ });+});diff --git a/tests/x-mention-poll.test.js b/tests/x-mention-poll.test.jsindex edfe082a4..fe0f17876 100644--- a/tests/x-mention-poll.test.js+++ b/tests/x-mention-poll.test.js@@ -95,10 +95,10 @@ describe('a poll with a cursor', () => {expect(await store.getCursor(ACCT)).toBe(out.cursor);});- it('routes the make and launch intents (later orders) to help with handler_not_built', async () => {+ it('routes the make intent (a later order) to help with handler_not_built', async () => {await poll.pollAccount({ descriptor: DESCRIPTOR, env: {}, deps: deps() });const rows = await store.recentDecisions(ACCT, { limit: 50 });- const unbuilt = rows.filter((r) => ['make', 'launch'].includes(r.intent) && r.decision === 'reply');+ const unbuilt = rows.filter((r) => r.intent === 'make' && r.decision === 'reply');for (const r of unbuilt) expect(r.reason).toBe('handler_not_built');});