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-bot): let agents with their own X account answer mentions in their own persona
nirholas4516247ea18c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 673097988..f89e01898 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-10-23++- **Agents answer mentions of their own X account, in their own persona**: An agent with its own connected X account and mention replies switched on is now polled by the mention bot. It replies in its own persona, attaches a render of its own avatar to conversational replies, and only acts on the intents its owner allowed, up to a daily cap. Dry run stays the default: nothing posts until the owner turns dry run off and the operator enables live mode. A connection missing the posting scope is reported as missing_scope instead of being polled. (`/agents`) `[feature]`+## 2026-10-15- **.well-known/skill.md** (`/.well-known/skill.md`): SKILL-MD 1.0: every paid HTTP route on three.ws with its price, parameters, and the Solana and Base payment rails it settles on, generated straight from the live OpenAPI catalog. For the Agent Skills connector file, see /skill.md instead.diff --git a/api/_lib/x-agent-mentions.js b/api/_lib/x-agent-mentions.jsnew file mode 100644index 000000000..f9b4e8090--- /dev/null+++ b/api/_lib/x-agent-mentions.js@@ -0,0 +1,108 @@+// Agent mode for the X mention bot: which agents answer mentions of their own+// connected X account, and what each answer is built from.+//+// The mention poller (x-mention-poll.js) treats an agent account like the+// company account, with three differences supplied here:+//+// - the account list: every agent whose policy has mention_replies_enabled+// and whose own X account is connected (agent_x_connections),+// - the scope check: the connection must carry the scopes mention replies+// need (X_MENTION_REQUIRED_SCOPES); otherwise the poller reports+// `missing_scope` and the settings page shows the same gap,+// - the context: the agent's persona for the reply brain, its avatar poster+// for conversational replies, and its policy (dry run, daily cap, intents).++import { sql } from './db.js';+import { appOrigin } from './gateway/format.js';+import { posterPngUrl } from '../_mcp-studio/asset-links.js';+import { X_MENTION_REQUIRED_SCOPES, missingScopes } from './x-scopes.js';++/** Intents the allow-list governs. help and launch never carry a 3D side effect. */+const GATED_INTENTS = new Set(['chat', 'make', 'image3d', 'avatar']);++/**+ * Whether the policy lets an agent act on a parsed intent.+ * @param {{ mention_replies_allowed_intents?: string[] }} policy+ * @param {string} intent+ */+export function intentAllowed(policy, intent) {+ if (!GATED_INTENTS.has(intent)) return true;+ return (policy?.mention_replies_allowed_intents || []).includes(intent);+}++/** The policy fields the poller reads, from a joined row. */+export function mentionPolicyOf(row) {+ return {+ dry_run: row.mention_replies_dry_run !== false,+ daily_cap: Number.isInteger(row.mention_replies_daily_cap) ? row.mention_replies_daily_cap : 10,+ mention_replies_allowed_intents: row.mention_replies_allowed_intents || [],+ };+}++/**+ * Agents to poll: policy enabled and an own X account connected. Each entry+ * carries `missingScopes` so the poller can report the gap instead of calling X.+ *+ * @param {{ db?: typeof sql }} [opts]+ * @returns {Promise<Array<{ agentId: string, userId: string, agent: object, policy: object, missingScopes: string[] }>>}+ */+export async function agentMentionAccounts({ db = sql } = {}) {+ const rows = await db`+ select a.id, a.user_id, a.name, a.persona_prompt, a.meta, a.avatar_id,+ p.mention_replies_dry_run, p.mention_replies_daily_cap, p.mention_replies_allowed_intents,+ c.scopes+ from agent_x_policies p+ join agent_identities a on a.id = p.agent_id and a.deleted_at is null+ join agent_x_connections c on c.agent_id = p.agent_id and c.disconnected_at is null+ where p.mention_replies_enabled = true+ order by p.agent_id+ limit 200+ `;+ return rows.map((r) => ({+ agentId: String(r.id),+ userId: String(r.user_id),+ agent: { id: String(r.id), user_id: String(r.user_id), name: r.name, persona_prompt: r.persona_prompt, meta: r.meta || {}, avatar_id: r.avatar_id || null },+ policy: mentionPolicyOf(r),+ missingScopes: missingScopes(r.scopes, X_MENTION_REQUIRED_SCOPES),+ }));+}++/**+ * The poster image of an agent's own avatar, or null when it has none or its+ * model cannot be located. The render endpoint draws the GLB; nothing here is+ * taken from the mention.+ *+ * @param {{ avatar_id?: string|null }} agent+ */+export async function agentPosterUrl(agent, { db = sql, base = appOrigin() } = {}) {+ if (!agent?.avatar_id) return null;+ const [row] = await db`select storage_key from avatars where id = ${agent.avatar_id} and deleted_at is null limit 1`;+ const glbUrl = row ? (await import('./r2.js')).publicUrlOrNull(row.storage_key) : null;+ return glbUrl ? posterPngUrl(base, glbUrl) : null;+}++/**+ * A token resolver for one agent's own X account; refreshes on expiry. Only+ * the agent's connection is ever used, never the owner's personal account.+ */+export function agentTokenResolver({ agentId, userId }) {+ return async () => {+ const { resolveXConnection, refreshIfNeeded } = await import('./x-post.js');+ const conn = await resolveXConnection({ userId, agentId });+ if (!conn || conn.source !== 'agent') throw new Error(`agent ${agentId} has no connected X account`);+ return refreshIfNeeded(conn);+ };+}++/**+ * Token resolver for a recorded x_mention_events row, or null for non-agent+ * rows. Matches createDeliver's `getAccessToken(row)`: sync to call, lazy to run.+ */+export function tokenResolverForRow(row, { db = sql } = {}) {+ if (row?.account_kind !== 'agent') return null;+ return async () => {+ const [a] = await db`select user_id from agent_identities where id = ${row.account_ref} limit 1`;+ if (!a) throw new Error(`agent ${row.account_ref} no longer exists`);+ return agentTokenResolver({ agentId: String(row.account_ref), userId: String(a.user_id) })();+ };+}diff --git a/api/_lib/x-mention-poll.js b/api/_lib/x-mention-poll.jsindex 0bde85f59..8e4f7fec6 100644--- a/api/_lib/x-mention-poll.js+++ b/api/_lib/x-mention-poll.js@@ -14,7 +14,9 @@//// Dry run is the default. The adapter posts only when X_MENTION_BOT_LIVE is// "1" AND a poster token resolver is supplied; this loop supplies none for the-// company account, so going live is the separate owner step (order 928).+// company account, so going live is the separate owner step (order 928). An+// agent account (x-agent-mentions.js) goes live only when its owner also turned+// its mention-reply dry run off.//// Mention text is untrusted data: it is parsed by the pure parser and quoted// to the reply brain as data. The only action it can ever cause is one reply@@ -35,6 +37,8 @@ import { handleAvatar, finishPendingAvatars } from './x-mention-avatar.js';import { finishPendingMakes } from './x-mention-make.js';import { handleImage3d, finishPendingImage3d } from './x-mention-image3d.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';export const LOCK_KEY = 'x_mentions_lock';const DEFAULT_LOCK_SECONDS = 110;@@ -92,14 +96,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 }) {+async function composeAnswer({ mention, parsed, account, compose, agent = null }) {if (parsed.intent === 'help') {return { text: parsed.args?.topic === 'refused' ? REFUSED_REPLY : FIXED_HELP_REPLY, reason: parsed.reason };}if (UNBUILT_HANDLERS.has(parsed.intent)) {return { text: FIXED_HELP_REPLY, reason: 'handler_not_built' };}- const reply = await compose({ company: { handle: account.handle }, mention });+ const reply = await compose(agent ? { agent, mention } : { company: { handle: account.handle }, mention });return { text: reply.text, reason: reply.source === 'model' ? parsed.reason : `fallback:${reply.reason}`, provider: reply.provider, model: reply.model };}@@ -108,9 +112,12 @@ async function composeAnswer({ mention, parsed, account, compose }) {* 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 }) {+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 }) {const parsed = parseMentionIntent(mention, account);- const dryRun = true;+ // 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.+ const dryRun = agentCtx ? agentCtx.policy.dry_run || !xBotLive(env) : true;+ const getAccessToken = agentCtx && !dryRun ? agentTokenResolver({ agentId: agentCtx.agentId, userId: agentCtx.userId }) : null;const { inserted } = await store.recordMention({ mention, parsed, dryRun });if (!inserted) return { tweetId: mention.id, decision: 'duplicate', reason: null };@@ -126,7 +133,7 @@ export async function handleMention({ mention, account, limits, env, store = mentry {const verdict = await guard({ mention, account: mention.account, env, store });- if (!verdict.allow && verdict.reason === 'known_bot') {+ if (!verdict.allow && verdict.reason === 'known_bot' && !agentCtx) {// A known xAI account tagged us: answer on behalf of the human at the// root of the conversation, or skip with the reason (x-mention-on-behalf.js).const allowedBot = await budget.budgetGate({ intent: parsed.intent, env });@@ -151,24 +158,39 @@ export async function handleMention({ mention, account, limits, env, store = menawait store.updateDecision(mention.id, { decision: 'rate_limited', reason: limited });return { tweetId: mention.id, intent: parsed.intent, decision: 'rate_limited', reason: limited };}+ if (agentCtx) {+ if (!intentAllowed(agentCtx.policy, parsed.intent)) {+ const reason = `intent_not_allowed:${parsed.intent}`;+ await store.updateDecision(mention.id, { decision: 'skip', reason });+ return { tweetId: mention.id, intent: parsed.intent, decision: 'skip', reason };+ }+ const sentToday = await store.countAccountReplies(mention.account, { windowSeconds: DAY });+ if (sentToday >= agentCtx.policy.daily_cap) {+ await store.updateDecision(mention.id, { decision: 'rate_limited', reason: 'agent_daily_cap' });+ return { tweetId: mention.id, intent: parsed.intent, decision: 'rate_limited', reason: 'agent_daily_cap' };+ }+ }const allowed = await budget.budgetGate({ intent: parsed.intent, env });if (!allowed.allow) {await store.updateDecision(mention.id, { decision: 'budget', reason: allowed.reason });return { tweetId: mention.id, intent: parsed.intent, decision: 'budget', reason: allowed.reason };}+ const lateDeps = getAccessToken ? { deliver: createDeliver({ env, adapterFactory, getAccessToken: () => getAccessToken }) } : undefined;if (parsed.intent === 'avatar') {- const result = await avatar({ tweetId: mention.id, authorId: mention.userId || mention.author?.id, author: mention.author, dryRun });+ const result = await avatar({ tweetId: mention.id, authorId: mention.userId || mention.author?.id, author: mention.author, dryRun }, lateDeps);if (result.decision === 'reply') await budget.recordPosts(1);return { tweetId: mention.id, intent: 'avatar', decision: result.decision, reason: result.reason, text: result.text, dry_run: dryRun };}if (parsed.intent === 'image3d') {- const result = await image3d({ tweetId: mention.id, authorId: mention.userId || mention.author?.id, args: parsed.args, dryRun });+ const result = await image3d({ tweetId: mention.id, authorId: mention.userId || mention.author?.id, args: parsed.args, dryRun }, lateDeps);if (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 });- const adapter = adapterFactory({ mention, parsed, env, policyDryRun: true });- await adapter.sendText(mention.id, answer.text);+ const answer = await composeAnswer({ mention, parsed, account, compose, agent: agentCtx?.agent || null });+ 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 });+ else await adapter.sendText(mention.id, answer.text);await budget.recordPosts(1);await store.updateDecision(mention.id, { reason: answer.reason });return { tweetId: mention.id, intent: parsed.intent, decision: 'reply', reason: answer.reason, text: answer.text, dry_run: !adapter.live };@@ -188,6 +210,7 @@ export async function pollAccount({ descriptor, env = process.env, maxMentions =const fetcher = deps.fetchMentions || fetchMentions;const limits = replyLimits(env);const label = `${descriptor.kind}:${descriptor.ref}`;+ if (descriptor.missingScopes?.length) return { account: label, status: 'missing_scope', missing: descriptor.missingScopes };let sinceId;try {@@ -233,7 +256,7 @@ export async function pollAccount({ descriptor, env = process.env, maxMentions =let stoppedAt = null;for (const mention of batch) {try {- decisions.push(await handleMention({ mention, account: page.account, limits, env, store, compose: deps.compose, adapterFactory: deps.adapterFactory, guard: deps.guard, paused: deps.paused, budget: deps.budget, request: resolve, onBehalf: deps.onBehalf, knownBots: deps.knownBots, avatar: deps.avatar, image3d: deps.image3d }));+ decisions.push(await handleMention({ mention, account: page.account, limits, env, store, compose: deps.compose, adapterFactory: deps.adapterFactory, guard: deps.guard, paused: deps.paused, budget: deps.budget, request: resolve, onBehalf: deps.onBehalf, knownBots: deps.knownBots, avatar: deps.avatar, image3d: deps.image3d, agentCtx: descriptor.agentCtx || null, posterFor: deps.posterFor }));lastRecorded = mention.id;} catch (err) {stoppedAt = mention.id;@@ -255,16 +278,24 @@ export async function pollAccount({ descriptor, env = process.env, maxMentions =/*** Accounts to poll: the company account when its credentials are present,- * then each agent account with mention replies enabled (supplied by- * `agentAccounts`, which order 060 provides from the agent policy).+ * then each agent account with mention replies enabled (`agentAccounts`,+ * x-agent-mentions.js, from agent_x_policies and agent_x_connections).*/-export async function listAccounts({ env = process.env, agentAccounts = async () => [] } = {}) {+export async function listAccounts({ env = process.env, agentAccounts = agentMentionAccounts } = {}) {const accounts = [];if (companyMentionsConfigured(env)) {accounts.push({ kind: 'company', ref: env.X_COMPANY_HANDLE || 'trythreews', fetch: { kind: 'company' } });}- for (const a of await agentAccounts()) {- accounts.push({ kind: 'agent', ref: String(a.agentId), fetch: { kind: 'agent', agentId: a.agentId, userId: a.userId } });+ // A failing agent lookup must never stop the company account from being polled.+ const agentRows = await agentAccounts().catch((err) => {+ console.error('[x-mentions] agent account lookup failed', err?.message || err);+ return [];+ });+ for (const a of agentRows) {+ accounts.push({+ kind: 'agent', ref: String(a.agentId), fetch: { kind: 'agent', agentId: a.agentId, userId: a.userId },+ agentCtx: { agentId: String(a.agentId), userId: String(a.userId), agent: a.agent, policy: a.policy }, missingScopes: a.missingScopes || [],+ });}return accounts;}@@ -280,7 +311,7 @@ export async function runFollowUps({ env = process.env, deps = {} } = {}) {if (await (deps.paused || isPaused)(env)) return { followUps: { skipped: 'kill_switch' } };const gate = await budget.readGate({ env }).catch(() => ({ allow: true }));if (!gate.allow) return { followUps: { skipped: 'budget', reason: gate.reason } };- const baseDeliver = deps.deliver || createDeliver({ env, adapterFactory: deps.adapterFactory, getAccessToken: deps.getAccessToken });+ const baseDeliver = deps.deliver || createDeliver({ env, adapterFactory: deps.adapterFactory, getAccessToken: deps.getAccessToken || tokenResolverForRow });const deliver = async (args) => {const id = await baseDeliver(args);if (id) await budget.recordPosts(1).catch(() => {});diff --git a/api/_lib/x-mention-store.js b/api/_lib/x-mention-store.jsindex 64ca1fee6..a6a309d29 100644--- a/api/_lib/x-mention-store.js+++ b/api/_lib/x-mention-store.js@@ -275,6 +275,25 @@ export async function countRepliesInConversation(conversationId, { windowSecondsreturn row?.n ?? 0;}+/**+ * Replies one account has recorded in the trailing window, dry-run rows+ * included, so a daily cap holds the same in dry run as it will live.+ *+ * @param {{ kind: string, ref: string }} account+ * @param {{ windowSeconds?: number }} [opts]+ */+export async function countAccountReplies(account, { windowSeconds = 86400 } = {}) {+ const acct = accountOf(account);+ const secs = Math.max(1, Math.round(Number(windowSeconds) || 86400));+ const [row] = await sql`+ select count(*)::int as n from x_mention_events+ where account_kind = ${acct.kind} and account_ref = ${acct.ref}+ and decision = 'reply'+ and created_at > now() - make_interval(secs => ${secs})+ `;+ return row?.n ?? 0;+}+/*** Merge a patch into a recorded mention's args. Used to stamp the human a bot* mention is answered on behalf of (`on_behalf_of`) so rate limits and thediff --git a/data/changelog.json b/data/changelog.jsonindex 52d61fe63..42385488e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$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-23",+ "title": "Agents answer mentions of their own X account, in their own persona",+ "summary": "An agent with its own connected X account and mention replies switched on is now polled by the mention bot. It replies in its own persona, attaches a render of its own avatar to conversational replies, and only acts on the intents its owner allowed, up to a daily cap. Dry run stays the default: nothing posts until the owner turns dry run off and the operator enables live mode. A connection missing the posting scope is reported as missing_scope instead of being polled.",+ "tags": ["feature"],+ "link": "/agents"+ },{"date": "2026-10-15","title": "Turn any public OpenAPI spec or GitHub repo into a draft agent skill",diff --git a/deploy/x-partners/cloudbuild.yaml b/deploy/x-partners/cloudbuild.yamlindex ed5d3f69f..cee953f54 100644--- a/deploy/x-partners/cloudbuild.yaml+++ b/deploy/x-partners/cloudbuild.yaml@@ -32,3 +32,7 @@ options:machineType: E2_HIGHCPU_8logging: CLOUD_LOGGING_ONLYtimeout: 2400s++# The project's default compute SA was deleted; every manual build must pin the+# dedicated build SA or Cloud Build refuses the submission.+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]diff --git a/docs/x-mention-bot.md b/docs/x-mention-bot.mdindex d7996693c..4ffd544a0 100644--- a/docs/x-mention-bot.md+++ b/docs/x-mention-bot.md@@ -394,6 +394,39 @@ npx vitest run tests/x-mention-guard.test.js tests/x-budget.test.js tests/x-mentThe kill switch tests assert zero calls to the reply brain and the X adapter.+## Agent mode: an agent answers its own mentions++An agent with its own connected X account (`agent_x_connections`) and+`mention_replies_enabled` on is polled by the same cron as the company account,+through [`api/_lib/x-agent-mentions.js`](../api/_lib/x-agent-mentions.js):++- **Who is polled.** `agentMentionAccounts()` joins `agent_x_policies`,+ `agent_x_connections` and `agent_identities`; `listAccounts()` in+ [`x-mention-poll.js`](../api/_lib/x-mention-poll.js) turns each into a+ descriptor carrying the agent, its policy and its missing scopes. Only the+ agent's own account is read, never the owner's personal one.+- **Scope check.** The connection must carry `tweet.read`, `users.read` and+ `tweet.write` (`X_MENTION_REQUIRED_SCOPES`). If one is missing the poll+ reports `status: missing_scope` with the list and makes no X call; the+ settings page shows the same gap (`can_answer_mentions`,+ `missing_mention_scopes`). Reconnecting X with the full scope set clears it.+- **Gates, in order,** after the guard and per-author limits: the intent must be+ in `mention_replies_allowed_intents` (chat, make, image3d, avatar; help and+ launch carry no 3D side effect and always pass), then the account's replies in+ the last 24 hours must be under `mention_replies_daily_cap` (dry-run rows+ count, so the cap behaves the same live), then the shared X budget.+- **Persona and body.** The reply brain gets the agent's name and+ `persona_prompt` instead of the company persona. A `chat` reply attaches a+ render of the agent's own avatar (`agent_identities.avatar_id`, via+ `/api/render/glb`) when it has one.+- **Dry run by default.** A reply is posted only when the owner turned+ `mention_replies_dry_run` off AND the operator set `X_MENTION_BOT_LIVE=1`.+ Late make/avatar/image-to-3D replies for an agent row post through that+ agent's token too. A known bot tagging an agent is skipped+ (`known_bot`); the on-behalf-of flow is company-only.++Tests: [`tests/x-agent-mentions.test.js`](../tests/x-agent-mentions.test.js).+## What is not wired yetDocumented plainly rather than papered over, since this file is the singlediff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 62c277f0c..057652353 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,24 @@{- "generated_at": "2026-10-17T07:48:05.520Z",+ "generated_at": "2026-10-23T21:39:56.050Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 4107,+ "total": 4108,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "Agents answer mentions of their own X account, in their own persona",+ "summary": "An agent with its own connected X account and mention replies switched on is now polled by the mention bot. It replies in its own persona, attaches a render of its own avatar to conversational replies, and only acts on the intents its owner allowed, up to a daily cap. Dry run stays the default: nothing posts until the owner turns dry run off and the operator enables live mode. A connection missing the posting scope is reported as missing_scope instead of being polled.",+ "link": "/agents",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-15","type": "launch",@@ -1550,16 +1560,6 @@"tags": ["launch"]- },- {- "date": "2026-10-10",- "type": "launch",- "title": "Event Markets leaderboard: season rankings and rewards",- "summary": "Season and all-time rankings for the best event forecasters. Right calls on long odds score the most; streaks, badges and $THREE season rewards.",- "link": "/event-markets/leaderboard",- "tags": [- "launch"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex bd4f26047..3cad75662 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-10-17T07:48:05.494Z",+ "generated_at": "2026-10-23T21:39:55.731Z","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-10-23",+ "type": "update",+ "title": "Agents answer mentions of their own X account, in their own persona",+ "summary": "An agent with its own connected X account and mention replies switched on is now polled by the mention bot. It replies in its own persona, attaches a render of its own avatar to conversational replies, and only acts on the intents its owner allowed, up to a daily cap. Dry run stays the default: nothing posts until the owner turns dry run off and the operator enables live mode. A connection missing the posting scope is reported as missing_scope instead of being polled.",+ "link": "/agents",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-15","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 7ceb6f781..92d241820 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>Agents answer mentions of their own X account, in their own persona</title>+ <link>https://three.ws/agents</link>+ <guid isPermaLink="false">2026-10-23:Agents answer mentions of their own X account, in their own persona</guid>+ <pubDate>Fri, 23 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>An agent with its own connected X account and mention replies switched on is now polled by the mention bot. It replies in its own persona, attaches a render of its own avatar to conversational replies, and only acts on the intents its owner allowed, up to a daily cap. Dry run stays the default: nothing posts until the owner turns dry run off and the operator enables live mode. A connection missing the posting scope is reported as missing_scope instead of being polled.</description>+ </item><item><title>.well-known/skill.md</title><link>https://three.ws/.well-known/skill.md</link>diff --git a/public/features.json b/public/features.jsonindex ce399b283..c359dfd9a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-17T07:48:05.474Z",+ "generated_at": "2026-10-23T21:39:55.466Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/x-agent-mentions.test.js b/tests/x-agent-mentions.test.jsnew file mode 100644index 000000000..8ad8d959d--- /dev/null+++ b/tests/x-agent-mentions.test.js@@ -0,0 +1,204 @@+// Agent mode of the X mention bot: the supplier joining agent_x_policies and+// agent_x_connections, the scope check, and the policy gates in handleMention,+// against the real x_mention_events and agent_x_policies migrations (PGlite).+// The reply brain is the only captured boundary.++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 poll = await import('../api/_lib/x-mention-poll.js');+const store = await import('../api/_lib/x-mention-store.js');+const agents = await import('../api/_lib/x-agent-mentions.js');+const { DEFAULT_POLICY } = await import('../api/_lib/x-agent-policy.js');++const MIG = new URL('../api/_lib/migrations/', import.meta.url);+const read = (f) => readFileSync(new URL(f, MIG), 'utf8');+const APP_SETTINGS = (() => {+ const src = read('20260922210000_free_tier_models.sql');+ const start = src.indexOf('CREATE TABLE IF NOT EXISTS app_settings');+ return src.slice(start, src.indexOf(');', start) + 2);+})();++const AGENT_ID = '11111111-1111-4111-8111-111111111111';+const USER_ID = '22222222-2222-4222-8222-222222222222';+const AVATAR_ID = '33333333-3333-4333-8333-333333333333';+const ACCT = { kind: 'agent', ref: AGENT_ID };+const ACCOUNT = { ...ACCT, userId: '1700000000000000077', handle: 'scoutbot' };+const AGENT = { id: AGENT_ID, user_id: USER_ID, name: 'Scout', persona_prompt: 'Curious and brief.', meta: {}, avatar_id: null };+const policy = (over = {}) => ({ dry_run: true, daily_cap: 10, mention_replies_allowed_intents: ['chat'], ...over });+const ctx = (over = {}) => ({ agentId: AGENT_ID, userId: USER_ID, agent: AGENT, policy: policy(over) });++let n = 0;+function mention(text = '@scoutbot hello there', extra = {}) {+ const id = String(1900000000000001000n + BigInt(++n));+ return {+ id, userId: '42', username: 'alice', text, createdAt: new Date().toISOString(), conversationId: id, account: ACCT,+ mentions: [{ username: 'scoutbot', id: ACCOUNT.userId }], urls: [], media: [], inReplyToUserId: null, repliedTo: null,+ quoted: null, isRetweet: false, fromSelf: false, ...extra,+ };+}++const budget = { readGate: async () => ({ allow: true }), budgetGate: async () => ({ allow: true }), recordPosts: vi.fn(async () => {}) };+const compose = vi.fn(async () => ({ text: 'Hi Alice, Scout here.', source: 'model', reason: null }));+const run = (m, agentCtx, extra = {}) => poll.handleMention({+ mention: m, account: ACCOUNT, limits: poll.replyLimits({}), env: {}, budget, paused: async () => false,+ guard: async () => ({ allow: true }), compose, agentCtx, posterFor: async () => null, ...extra,+});++beforeEach(async () => {+ dbState.pg = new PGlite();+ await dbState.pg.exec(APP_SETTINGS);+ await dbState.pg.exec(read('20261008170000_x_mention_events.sql'));+ await dbState.pg.exec(`+ create table agent_identities (id uuid primary key, user_id uuid not null, name text not null, persona_prompt text, meta jsonb not null default '{}', avatar_id uuid, deleted_at timestamptz);+ create table avatars (id uuid primary key, storage_key text not null, deleted_at timestamptz);+ create table agent_x_connections (agent_id uuid primary key, scopes text not null default '', disconnected_at timestamptz);+ create table agent_x_policies (agent_id uuid primary key, enabled boolean not null default true);+ `);+ await dbState.pg.exec(read('20261011220000_agent_mention_policy.sql'));+ compose.mockClear();+ budget.recordPosts.mockClear();+});++describe('policy defaults', () => {+ it('keeps mention replies off, in dry run, with no intents, until the owner opts in', () => {+ expect(DEFAULT_POLICY).toMatchObject({ mention_replies_enabled: false, mention_replies_dry_run: true, mention_replies_daily_cap: 10 });+ expect(DEFAULT_POLICY.mention_replies_allowed_intents).toEqual([]);+ expect(agents.intentAllowed(DEFAULT_POLICY, 'chat')).toBe(false);+ });++ it('lets help and launch through the allow-list, which only gates the four action intents', () => {+ const p = { mention_replies_allowed_intents: ['chat'] };+ expect(agents.intentAllowed(p, 'chat')).toBe(true);+ for (const i of ['make', 'image3d', 'avatar']) expect(agents.intentAllowed(p, i)).toBe(false);+ for (const i of ['help', 'launch']) expect(agents.intentAllowed(p, i)).toBe(true);+ });+});++describe('agentMentionAccounts', () => {+ const seed = async ({ enabled = true, scopes = 'tweet.read users.read tweet.write offline.access', disconnected = false } = {}) => {+ await dbState.pg.query(`insert into agent_identities (id, user_id, name, persona_prompt) values ($1, $2, 'Scout', 'Curious and brief.')`, [AGENT_ID, USER_ID]);+ await dbState.pg.query(`insert into agent_x_connections (agent_id, scopes, disconnected_at) values ($1, $2, $3)`, [AGENT_ID, scopes, disconnected ? new Date().toISOString() : null]);+ await dbState.pg.query(`insert into agent_x_policies (agent_id, mention_replies_enabled, mention_replies_allowed_intents, mention_replies_daily_cap) values ($1, $2, '{chat,avatar}', 3)`, [AGENT_ID, enabled]);+ };++ it('returns an enabled agent with its persona, policy and no missing scopes', async () => {+ await seed();+ const [a] = await agents.agentMentionAccounts();+ expect(a).toMatchObject({ agentId: AGENT_ID, userId: USER_ID, missingScopes: [] });+ expect(a.agent).toMatchObject({ name: 'Scout', persona_prompt: 'Curious and brief.' });+ expect(a.policy).toEqual({ dry_run: true, daily_cap: 3, mention_replies_allowed_intents: ['chat', 'avatar'] });+ });++ it('skips agents whose policy is off or whose account is disconnected', async () => {+ await seed({ enabled: false });+ expect(await agents.agentMentionAccounts()).toEqual([]);+ await dbState.pg.exec('delete from agent_identities; delete from agent_x_connections; delete from agent_x_policies;');+ await seed({ disconnected: true });+ expect(await agents.agentMentionAccounts()).toEqual([]);+ });++ it('names the scopes a read-only connection lacks', async () => {+ await seed({ scopes: 'tweet.read users.read offline.access' });+ const [a] = await agents.agentMentionAccounts();+ expect(a.missingScopes).toEqual(['tweet.write']);+ });++ it('listAccounts still returns the company account when the agent lookup fails', async () => {+ const env = { X_COMPANY_HANDLE: 'trythreews', X_COMPANY_API_KEY: 'k', X_COMPANY_API_SECRET: 's', X_COMPANY_ACCESS_TOKEN: 't', X_COMPANY_ACCESS_SECRET: 's', X_COMPANY_USER_ID: '1' };+ const list = await poll.listAccounts({ env, agentAccounts: async () => { throw new Error('db down'); } });+ expect(list.every((a) => a.kind === 'company')).toBe(true);+ });++ it('listAccounts turns each agent into a pollable descriptor carrying its context', async () => {+ await seed();+ const list = await poll.listAccounts({ env: {} });+ expect(list).toHaveLength(1);+ expect(list[0]).toMatchObject({ kind: 'agent', ref: AGENT_ID, fetch: { kind: 'agent', agentId: AGENT_ID, userId: USER_ID }, missingScopes: [] });+ expect(list[0].agentCtx.policy.daily_cap).toBe(3);+ });+});++describe('pollAccount scope handling', () => {+ it('reports missing_scope without calling X', async () => {+ const fetchMentions = vi.fn();+ const out = await poll.pollAccount({+ descriptor: { kind: 'agent', ref: AGENT_ID, fetch: {}, missingScopes: ['tweet.write'], agentCtx: ctx() },+ env: {}, deps: { fetchMentions },+ });+ expect(out).toEqual({ account: `agent:${AGENT_ID}`, status: 'missing_scope', missing: ['tweet.write'] });+ expect(fetchMentions).not.toHaveBeenCalled();+ });+});++describe('handleMention in agent mode', () => {+ it('records a dry-run chat reply composed in the agent persona', async () => {+ const m = mention();+ const out = await run(m, ctx());+ expect(out).toMatchObject({ intent: 'chat', decision: 'reply', dry_run: true, text: 'Hi Alice, Scout here.' });+ expect(compose.mock.calls[0][0].agent).toMatchObject({ name: 'Scout', persona_prompt: 'Curious and brief.' });+ expect(compose.mock.calls[0][0].company).toBeUndefined();+ expect(await store.getMentionEvent(m.id)).toMatchObject({ account_kind: 'agent', account_ref: AGENT_ID, decision: 'reply', dry_run: true, reply_tweet_id: null });+ });++ it('attaches the agent avatar poster to a chat reply', async () => {+ const m = mention();+ const poster = 'https://three.test/api/render/glb?glbUrl=x&width=1024&height=1024';+ const out = await run(m, ctx(), { posterFor: async () => poster });+ expect(out.decision).toBe('reply');+ expect((await store.getMentionEvent(m.id)).reply_media_url).toBe(poster);+ });++ it('skips an intent the policy does not allow', async () => {+ const m = mention('@scoutbot make me an avatar');+ const out = await run(m, ctx({ mention_replies_allowed_intents: ['chat'] }));+ expect(out).toMatchObject({ decision: 'skip', reason: 'intent_not_allowed:avatar' });+ expect(compose).not.toHaveBeenCalled();+ expect(await store.getMentionEvent(m.id)).toMatchObject({ decision: 'skip', reason: 'intent_not_allowed:avatar' });+ });++ it('stops at the daily cap, counting dry-run replies', async () => {+ const c = ctx({ daily_cap: 2 });+ expect((await run(mention(), c)).decision).toBe('reply');+ expect((await run(mention(), c)).decision).toBe('reply');+ const third = await run(mention(), c);+ expect(third).toMatchObject({ decision: 'rate_limited', reason: 'agent_daily_cap' });+ expect(await store.countAccountReplies(ACCT)).toBe(2);+ });++ it('treats a cap of 0 as never replying', async () => {+ expect(await run(mention(), ctx({ daily_cap: 0 }))).toMatchObject({ decision: 'rate_limited', reason: 'agent_daily_cap' });+ });++ it('stays dry when the owner turned dry run off but the operator switch is off', async () => {+ const adapterFactory = vi.fn((o) => ({ live: false, sendText: async () => ({}), sendMedia: async () => ({}), o }));+ const out = await run(mention(), ctx({ dry_run: false }), { adapterFactory });+ expect(out.decision).toBe('reply');+ expect(adapterFactory.mock.calls[0][0]).toMatchObject({ policyDryRun: true, getAccessToken: null });+ });++ it('hands the adapter the agent token resolver only when both switches are live', async () => {+ const adapterFactory = vi.fn(() => ({ live: true, sendText: async () => ({}), sendMedia: async () => ({}) }));+ await run(mention(), ctx({ dry_run: false }), { adapterFactory, env: { X_MENTION_BOT_LIVE: '1' } });+ const call = adapterFactory.mock.calls[0][0];+ expect(call.policyDryRun).toBe(false);+ expect(typeof call.getAccessToken).toBe('function');+ });++ it('does not answer on behalf of a human when a known bot tags an agent', async () => {+ const out = await run(mention(), ctx(), { guard: async () => ({ allow: false, decision: 'skip', reason: 'known_bot' }) });+ expect(out).toMatchObject({ decision: 'skip', reason: 'known_bot' });+ });+});