Skip to content

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

feat(x): per-agent X posting policy, X and Google social sign-in linking, and rate limits for both

nirholas6e10f83a74f7
diff --git a/api/_lib/migrations/20260922190000_account_social_sso.sql b/api/_lib/migrations/20260922190000_account_social_sso.sql
new file mode 100644
index 000000000..96b4a3b83
--- /dev/null
+++ b/api/_lib/migrations/20260922190000_account_social_sso.sql
@@ -0,0 +1,89 @@
+-- Account surfaces: per-agent X accounts and posting policy, and linked sign-in
+-- identities (Google). docs/authentication.md and docs/x-posting-policy.md are
+-- the user-facing guides; api/_lib/x-agent-policy.js and api/_lib/identities.js
+-- are the only writers.
+--
+-- agent_x_connections an X account connected to ONE agent, so an agent can
+-- post as itself instead of as its owner. Tokens are
+-- AES-GCM encrypted exactly like social_connections.
+-- An agent without a row posts through its owner's
+-- account (social_connections), if the policy allows.
+-- agent_x_policies what an agent may post, how often, whether a human
+-- approves each post first, and the tone rules the
+-- content check enforces. One row per agent; an agent
+-- with no row uses the defaults in x-agent-policy.js
+-- (review before post, nothing allowed until set).
+-- x_pending_reviews gains kind / source / source_ref so the approval
+-- queue can say why a post exists (a launch, a trade,
+-- a run, a reply) and link back to what produced it,
+-- plus scheduled_for: an approved post with a future
+-- time is scheduled rather than published at once,
+-- and reply_to_tweet_id so an approved reply threads.
+-- x_posts, x_scheduled_posts gain kind so the cadence caps can count by it.
+-- user_identities a sign-in method linked to an account beyond its
+-- original one. `subject` is the provider's stable id
+-- (Google's `sub`); one account per identity, one
+-- identity per provider per account.
+
+create table if not exists agent_x_connections (
+ agent_id uuid primary key references agent_identities(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ provider_uid text not null,
+ username text not null,
+ access_token text not null,
+ refresh_token text,
+ expires_at timestamptz,
+ scopes text not null default '',
+ raw_data jsonb not null default '{}'::jsonb,
+ posts_this_month integer not null default 0,
+ month_resets_at timestamptz not null default (date_trunc('month', now()) + interval '1 month'),
+ last_posted_at timestamptz,
+ connected_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ disconnected_at timestamptz
+);
+create index if not exists agent_x_connections_user_idx on agent_x_connections (user_id) where disconnected_at is null;
+
+create table if not exists agent_x_policies (
+ agent_id uuid primary key references agent_identities(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ enabled boolean not null default true,
+ allowed_kinds text[] not null default '{}',
+ review_before_post boolean not null default true,
+ max_posts_per_day integer not null default 4 check (max_posts_per_day between 0 and 50),
+ min_interval_min integer not null default 60 check (min_interval_min between 0 and 1440),
+ tone_guidance text not null default '' check (char_length(tone_guidance) <= 1000),
+ banned_terms text[] not null default '{}',
+ max_hashtags integer not null default 1 check (max_hashtags between 0 and 10),
+ allow_links boolean not null default true,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+create index if not exists agent_x_policies_user_idx on agent_x_policies (user_id);
+
+alter table x_pending_reviews add column if not exists kind text;
+alter table x_pending_reviews add column if not exists source text;
+alter table x_pending_reviews add column if not exists source_ref text;
+alter table x_pending_reviews add column if not exists scheduled_for timestamptz;
+alter table x_pending_reviews add column if not exists reply_to_tweet_id text;
+create index if not exists x_pending_reviews_agent_pending_idx
+ on x_pending_reviews (agent_id, created_at desc) where status = 'pending';
+
+alter table x_posts add column if not exists kind text;
+alter table x_scheduled_posts add column if not exists kind text;
+create index if not exists x_posts_agent_created_idx on x_posts (agent_id, created_at desc) where agent_id is not null;
+
+create table if not exists user_identities (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ provider text not null check (provider in ('google')),
+ subject text not null,
+ email text,
+ email_verified boolean not null default false,
+ display_name text,
+ avatar_url text,
+ linked_at timestamptz not null default now(),
+ last_used_at timestamptz
+);
+create unique index if not exists user_identities_provider_subject_uidx on user_identities (provider, subject);
+create unique index if not exists user_identities_user_provider_uidx on user_identities (user_id, provider);
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 572222541..b4f60cc1a 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -701,6 +701,11 @@ export const limits = {
// draining `authIp`, which gates the actual publish. 20 per 10 min is many
// more rerolls than composing a tweet needs and still caps the fan-out.
xDraftIp: (ip) => getLimiter('x:draft:ip', { limit: 20, window: '10 m' }).limit(ip),
+ // Per-agent X posting (api/x/agents.js, the post_to_x tool and run tool):
+ // every request runs the policy and may reach X, so bound it per account.
+ xAgentPost: (userId) => getLimiter('x:agent-post', { limit: 30, window: '10 m' }).limit(userId),
+ // Linking or unlinking a sign-in identity (api/auth/google, api/auth/identities).
+ identityLink: (userId) => getLimiter('identity:link', { limit: 10, window: '10 m' }).limit(userId),
// Strategy backtest (api/sniper/backtest.js) is a read-only replay over captured
// history; cached by strategy hash, so this only gates cache-miss origin work.
sniperBacktestIp: (ip) => getLimiter('sniper:backtest:ip', { limit: 40, window: '5 m' }).limit(ip),
diff --git a/api/_lib/x-agent-policy.js b/api/_lib/x-agent-policy.js
new file mode 100644
index 000000000..301da2ff5
--- /dev/null
+++ b/api/_lib/x-agent-policy.js
@@ -0,0 +1,488 @@
+// Per-agent X posting: which account an agent posts through, what it may post,
+// how often, and whether a human approves each post first.
+//
+// Every automated or tool-driven post for an agent goes through
+// requestAgentPost(). That is the one place the policy is enforced, so a run,
+// an MCP tool call and the settings page's composer can never disagree about
+// what is allowed:
+//
+// 1. the policy is on and the post's kind is allowed,
+// 2. the content passes the tone rules (banned terms, hashtags, links),
+// 3. the daily cap has room,
+// 4. then the post is queued for review (review_before_post), scheduled
+// (a future time, or the next slot the minimum interval allows), or
+// published now through publishTweet (which still applies the account's
+// X tier quota, dedup window and scope check).
+//
+// Owner approval of a queued post (api/x/reviews.js) is a human decision and
+// is not held to the agent's cadence caps; it still goes through publishTweet.
+
+import { sql } from './db.js';
+import { env } from './env.js';
+import { isUuid } from './validate.js';
+import { MAX_TWEET_LEN, XPostError, publishTweet, resolveXConnection } from './x-post.js';
+import { X_POST_REQUIRED_SCOPES, missingScopes } from './x-scopes.js';
+
+/** What an agent may post about. Order is the order the settings page lists them. */
+export const POST_KINDS = Object.freeze([
+ { id: 'launches', label: 'Launches', summary: 'Coins the agent launches on three.ws.' },
+ { id: 'trades', label: 'Trades', summary: 'Buys and sells the agent makes from its wallet.' },
+ { id: 'runs', label: 'Runs', summary: 'Results of the agent\'s runs and automations.' },
+ { id: 'replies', label: 'Replies', summary: 'Replies to posts on X, threaded under the original.' },
+ { id: 'updates', label: 'Updates', summary: 'General posts in the agent\'s voice.' },
+]);
+export const POST_KIND_IDS = Object.freeze(POST_KINDS.map((k) => k.id));
+
+/** The policy an agent has before its owner configures one: nothing may post. */
+export const DEFAULT_POLICY = Object.freeze({
+ enabled: true,
+ allowed_kinds: Object.freeze([]),
+ review_before_post: true,
+ max_posts_per_day: 4,
+ min_interval_min: 60,
+ tone_guidance: '',
+ banned_terms: Object.freeze([]),
+ max_hashtags: 1,
+ allow_links: true,
+});
+
+const LIMITS = Object.freeze({
+ max_posts_per_day: [0, 50],
+ min_interval_min: [0, 1440],
+ max_hashtags: [0, 10],
+ tone_guidance: 1000,
+ banned_terms: 50,
+ banned_term_len: 60,
+});
+
+// Ceiling on the review queue per agent: a run that loops must not be able to
+// bury the owner under drafts.
+const MAX_PENDING_REVIEWS_PER_AGENT = 50;
+const MAX_SCHEDULE_AHEAD_MS = 365 * 24 * 60 * 60 * 1000;
+const TWEET_ID_RE = /^\d{1,25}$/;
+const HASHTAG_RE = /(^|\s)#[\p{L}\p{N}_]+/gu;
+const LINK_RE = /\bhttps?:\/\/\S+|\bwww\.\S+/i;
+
+function invalid(message, extra) {
+ return new XPostError('validation_error', message, 400, extra);
+}
+
+function intInRange(value, [min, max], name) {
+ const n = Number(value);
+ if (!Number.isInteger(n) || n < min || n > max) throw invalid(`${name} must be an integer from ${min} to ${max}`);
+ return n;
+}
+
+/**
+ * Validate a partial policy update. Returns only the fields present, normalized.
+ * Throws XPostError('validation_error') on the first bad field.
+ */
+export function normalizePolicyPatch(patch) {
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw invalid('policy must be an object');
+ const out = {};
+ if ('enabled' in patch) {
+ if (typeof patch.enabled !== 'boolean') throw invalid('enabled must be a boolean');
+ out.enabled = patch.enabled;
+ }
+ if ('review_before_post' in patch) {
+ if (typeof patch.review_before_post !== 'boolean') throw invalid('review_before_post must be a boolean');
+ out.review_before_post = patch.review_before_post;
+ }
+ if ('allow_links' in patch) {
+ if (typeof patch.allow_links !== 'boolean') throw invalid('allow_links must be a boolean');
+ out.allow_links = patch.allow_links;
+ }
+ if ('allowed_kinds' in patch) {
+ if (!Array.isArray(patch.allowed_kinds)) throw invalid('allowed_kinds must be an array');
+ const unknown = patch.allowed_kinds.filter((k) => !POST_KIND_IDS.includes(k));
+ if (unknown.length) throw invalid(`unknown kind: ${unknown.join(', ')}. Use: ${POST_KIND_IDS.join(', ')}`);
+ out.allowed_kinds = POST_KIND_IDS.filter((k) => patch.allowed_kinds.includes(k));
+ }
+ for (const key of ['max_posts_per_day', 'min_interval_min', 'max_hashtags']) {
+ if (key in patch) out[key] = intInRange(patch[key], LIMITS[key], key);
+ }
+ if ('tone_guidance' in patch) {
+ if (typeof patch.tone_guidance !== 'string') throw invalid('tone_guidance must be a string');
+ const t = patch.tone_guidance.trim();
+ if (t.length > LIMITS.tone_guidance) throw invalid(`tone_guidance is limited to ${LIMITS.tone_guidance} characters`);
+ out.tone_guidance = t;
+ }
+ if ('banned_terms' in patch) {
+ if (!Array.isArray(patch.banned_terms) || patch.banned_terms.some((t) => typeof t !== 'string')) {
+ throw invalid('banned_terms must be an array of strings');
+ }
+ const terms = [...new Set(patch.banned_terms.map((t) => t.trim().toLowerCase()).filter(Boolean))];
+ if (terms.length > LIMITS.banned_terms) throw invalid(`at most ${LIMITS.banned_terms} banned terms`);
+ if (terms.some((t) => t.length > LIMITS.banned_term_len)) {
+ throw invalid(`each banned term is limited to ${LIMITS.banned_term_len} characters`);
+ }
+ out.banned_terms = terms;
+ }
+ return out;
+}
+
+/**
+ * Check post text against the tone rules. Returns a list of violations, empty
+ * when the post may go out. `parts` is one string per tweet.
+ */
+export function checkPostContent(policy, parts) {
+ const violations = [];
+ if (!parts.length || parts.every((p) => !p.trim())) violations.push({ rule: 'empty', message: 'the post has no text' });
+ parts.forEach((p, i) => {
+ if (p.length > MAX_TWEET_LEN) {
+ violations.push({ rule: 'length', message: `part ${i + 1} is ${p.length} characters; the limit is ${MAX_TWEET_LEN}` });
+ }
+ });
+ const all = parts.join('\n');
+ const lower = all.toLowerCase();
+ for (const term of policy.banned_terms || []) {
+ if (term && lower.includes(term)) violations.push({ rule: 'banned_term', message: `contains the banned term "${term}"` });
+ }
+ const hashtags = (all.match(HASHTAG_RE) || []).length;
+ if (hashtags > policy.max_hashtags) {
+ violations.push({ rule: 'hashtags', message: `${hashtags} hashtags; the policy allows ${policy.max_hashtags}` });
+ }
+ if (!policy.allow_links && LINK_RE.test(all)) {
+ violations.push({ rule: 'links', message: 'contains a link; the policy does not allow links' });
+ }
+ return violations;
+}
+
+/** Split request text into tweet parts. */
+export function toParts({ text = null, threadParts = null }) {
+ if (Array.isArray(threadParts) && threadParts.length) {
+ return threadParts.map((s) => String(s ?? '').trim()).filter(Boolean);
+ }
+ const t = String(text ?? '').trim();
+ return t ? [t] : [];
+}
+
+function rowToPolicy(row) {
+ if (!row) return { ...DEFAULT_POLICY, allowed_kinds: [], banned_terms: [], configured: false, updated_at: null };
+ return {
+ enabled: row.enabled,
+ allowed_kinds: row.allowed_kinds || [],
+ review_before_post: row.review_before_post,
+ max_posts_per_day: row.max_posts_per_day,
+ min_interval_min: row.min_interval_min,
+ tone_guidance: row.tone_guidance || '',
+ banned_terms: row.banned_terms || [],
+ max_hashtags: row.max_hashtags,
+ allow_links: row.allow_links,
+ configured: true,
+ updated_at: row.updated_at,
+ };
+}
+
+/** The agent, if the user owns it. Throws not_found otherwise. */
+export async function loadOwnedAgent(userId, agentId) {
+ if (!isUuid(agentId)) throw invalid('agent_id must be a uuid');
+ const [agent] = await sql`
+ select id, name from agent_identities
+ where id = ${agentId} and user_id = ${userId} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) throw new XPostError('not_found', 'agent not found', 404);
+ return agent;
+}
+
+export async function getAgentPolicy(agentId) {
+ const [row] = await sql`select * from agent_x_policies where agent_id = ${agentId} limit 1`;
+ return rowToPolicy(row);
+}
+
+/** Apply a partial update over the current policy (or the defaults) and store it. */
+export async function saveAgentPolicy({ userId, agentId, patch }) {
+ await loadOwnedAgent(userId, agentId);
+ const changes = normalizePolicyPatch(patch);
+ const next = { ...(await getAgentPolicy(agentId)), ...changes };
+ const [row] = await sql`
+ insert into agent_x_policies
+ (agent_id, user_id, enabled, allowed_kinds, review_before_post, max_posts_per_day,
+ min_interval_min, tone_guidance, banned_terms, max_hashtags, allow_links)
+ values
+ (${agentId}, ${userId}, ${next.enabled}, ${next.allowed_kinds}, ${next.review_before_post},
+ ${next.max_posts_per_day}, ${next.min_interval_min}, ${next.tone_guidance}, ${next.banned_terms},
+ ${next.max_hashtags}, ${next.allow_links})
+ on conflict (agent_id) do update set
+ user_id = excluded.user_id,
+ enabled = excluded.enabled,
+ allowed_kinds = excluded.allowed_kinds,
+ review_before_post = excluded.review_before_post,
+ max_posts_per_day = excluded.max_posts_per_day,
+ min_interval_min = excluded.min_interval_min,
+ tone_guidance = excluded.tone_guidance,
+ banned_terms = excluded.banned_terms,
+ max_hashtags = excluded.max_hashtags,
+ allow_links = excluded.allow_links,
+ updated_at = now()
+ returning *
+ `;
+ return rowToPolicy(row);
+}
+
+/**
+ * Posts that count against the agent's daily cap: published in the last 24h
+ * (thread heads only) plus scheduled ones due in the next 24h.
+ */
+async function cadenceState(agentId, policy) {
+ const [c] = await sql`
+ select
+ (select count(*)::int from x_posts
+ where agent_id = ${agentId} and created_at > now() - interval '24 hours'
+ and not exists (select 1 from x_posts p2
+ where p2.agent_id = ${agentId} and p2.tweet_id = x_posts.reply_to_tweet_id)) as published_24h,
+ (select count(*)::int from x_scheduled_posts
+ where agent_id = ${agentId} and posted_at is null and error is null
+ and scheduled_at < now() + interval '24 hours') as scheduled_24h,
+ (select max(created_at) from x_posts where agent_id = ${agentId}) as last_posted_at,
+ (select max(scheduled_at) from x_scheduled_posts
+ where agent_id = ${agentId} and posted_at is null and error is null) as last_scheduled_at
+ `;
+ const used = c.published_24h + c.scheduled_24h;
+ const anchors = [c.last_posted_at, c.last_scheduled_at].filter(Boolean).map((d) => new Date(d).getTime());
+ const lastSlot = anchors.length ? Math.max(...anchors) : 0;
+ const nextAllowedMs = lastSlot ? lastSlot + policy.min_interval_min * 60_000 : 0;
+ return {
+ used_24h: used,
+ cap: policy.max_posts_per_day,
+ remaining_24h: Math.max(0, policy.max_posts_per_day - used),
+ last_posted_at: c.last_posted_at,
+ next_allowed_at: nextAllowedMs > Date.now() ? new Date(nextAllowedMs).toISOString() : null,
+ };
+}
+
+function connectionSummary(conn) {
+ if (!conn) return null;
+ return {
+ account: conn.source,
+ username: conn.username,
+ can_post: missingScopes(conn.scopes, X_POST_REQUIRED_SCOPES).length === 0,
+ connected_at: conn.connected_at,
+ last_posted_at: conn.last_posted_at,
+ };
+}
+
+export function connectUrl(agentId, { target = 'agent' } = {}) {
+ const q = new URLSearchParams({ scope: 'full', return_to: '/settings/connections' });
+ if (agentId) q.set('agent_id', agentId);
+ if (target === 'agent') q.set('target', 'agent');
+ return `/api/auth/x/connect?${q.toString()}`;
+}
+
+/** Everything the settings page and get tools need for one agent. */
+export async function getAgentXState({ userId, agentId }) {
+ const agent = await loadOwnedAgent(userId, agentId);
+ const [policy, conn, [{ pending }]] = await Promise.all([
+ getAgentPolicy(agentId),
+ resolveXConnection({ userId, agentId }),
+ sql`select count(*)::int as pending from x_pending_reviews where agent_id = ${agentId} and user_id = ${userId} and status = 'pending'`,
+ ]);
+ return {
+ agent: { id: agent.id, name: agent.name },
+ configured: Boolean(env.X_OAUTH_CLIENT_ID && env.X_OAUTH_CLIENT_SECRET),
+ connection: connectionSummary(conn),
+ connect_url: connectUrl(agentId),
+ policy,
+ cadence: await cadenceState(agentId, policy),
+ pending_reviews: pending,
+ kinds: POST_KINDS,
+ };
+}
+
+/** Every agent the user owns, with its posting state, for the connections page. */
+export async function listAgentXStates(userId) {
+ const agents = await sql`
+ select a.id, a.name,
+ p.agent_id is not null as policy_configured, p.enabled, p.allowed_kinds, p.review_before_post,
+ c.username as agent_username, c.disconnected_at is null and c.agent_id is not null as has_own_account,
+ (select count(*)::int from x_pending_reviews r
+ where r.agent_id = a.id::text and r.user_id = ${userId} and r.status = 'pending') as pending_reviews
+ from agent_identities a
+ left join agent_x_policies p on p.agent_id = a.id
+ left join agent_x_connections c on c.agent_id = a.id and c.disconnected_at is null
+ where a.user_id = ${userId} and a.deleted_at is null
+ order by a.created_at desc
+ limit 200
+ `;
+ return agents.map((a) => ({
+ id: a.id,
+ name: a.name,
+ account: a.has_own_account ? { account: 'agent', username: a.agent_username } : null,
+ policy_configured: a.policy_configured,
+ enabled: a.policy_configured ? a.enabled : DEFAULT_POLICY.enabled,
+ allowed_kinds: a.allowed_kinds || [],
+ review_before_post: a.policy_configured ? a.review_before_post : DEFAULT_POLICY.review_before_post,
+ pending_reviews: a.pending_reviews,
+ }));
+}
+
+/** Disconnect the agent's own X account; it falls back to the owner's account. */
+export async function disconnectAgentX({ userId, agentId }) {
+ await loadOwnedAgent(userId, agentId);
+ const rows = await sql`
+ update agent_x_connections set disconnected_at = now(), updated_at = now()
+ where agent_id = ${agentId} and user_id = ${userId} and disconnected_at is null
+ returning agent_id
+ `;
+ return { disconnected: rows.length > 0 };
+}
+
+function parseSchedule(scheduledAt) {
+ if (scheduledAt == null || scheduledAt === '') return null;
+ const when = new Date(scheduledAt);
+ if (Number.isNaN(when.getTime())) throw invalid('scheduled_at must be an ISO timestamp');
+ if (when.getTime() < Date.now() - 60_000) throw invalid('scheduled_at must be in the future');
+ if (when.getTime() > Date.now() + MAX_SCHEDULE_AHEAD_MS) throw invalid('scheduled_at must be within a year');
+ return when.getTime() <= Date.now() ? null : when;
+}
+
+/**
+ * Ask for an agent to post. Applies the agent's policy and answers with what
+ * happened: `pending_review`, `scheduled` or `published`. Refusals throw
+ * XPostError with a code the caller can act on (posting_paused,
+ * kind_not_allowed, tone_violation, daily_cap_reached, review_queue_full,
+ * not_connected, plus everything publishTweet can refuse).
+ *
+ * @param {object} o
+ * @param {string} o.userId
+ * @param {string} o.agentId
+ * @param {string} o.kind one of POST_KIND_IDS
+ * @param {string} [o.text]
+ * @param {string[]} [o.threadParts]
+ * @param {string} [o.replyTo] tweet id; required for kind 'replies'
+ * @param {string} [o.scheduledAt] ISO time; the post goes out then
+ * @param {string} o.source what produced the post: 'mcp', 'run', 'settings', 'api'
+ * @param {string} [o.sourceRef] id of the run / launch / trade behind it
+ */
+export async function requestAgentPost({ userId, agentId, kind, text = null, threadParts = null, replyTo = null, scheduledAt = null, source, sourceRef = null }) {
+ await loadOwnedAgent(userId, agentId);
+ if (!POST_KIND_IDS.includes(kind)) throw invalid(`kind must be one of: ${POST_KIND_IDS.join(', ')}`);
+ if (kind === 'replies') {
+ if (!replyTo || !TWEET_ID_RE.test(String(replyTo))) throw invalid('a reply needs reply_to_tweet_id');
+ } else if (replyTo) {
+ throw invalid('reply_to_tweet_id is only valid for kind "replies"');
+ }
+
+ const policy = await getAgentPolicy(agentId);
+ const settings = `/settings/connections?agent=${agentId}#x`;
+ if (!policy.enabled) {
+ throw new XPostError('posting_paused', 'posting is paused for this agent', 403, { settings_url: settings });
+ }
+ if (!policy.allowed_kinds.includes(kind)) {
+ throw new XPostError('kind_not_allowed', `this agent's policy does not allow "${kind}" posts`, 403, {
+ allowed_kinds: policy.allowed_kinds,
+ settings_url: settings,
+ hint: policy.configured ? undefined : 'no posting policy is set yet; configure one with configure_twitter_posting',
+ });
+ }
+
+ const parts = toParts({ text, threadParts });
+ const violations = checkPostContent(policy, parts);
+ if (violations.length) {
+ throw new XPostError('tone_violation', violations.map((v) => v.message).join('; '), 422, {
+ violations,
+ tone_guidance: policy.tone_guidance || undefined,
+ });
+ }
+
+ const when = parseSchedule(scheduledAt);
+ const conn = await resolveXConnection({ userId, agentId });
+ const threadJson = parts.length > 1 ? JSON.stringify(parts) : null;
+
+ if (policy.review_before_post) {
+ const [{ pending }] = await sql`
+ select count(*)::int as pending from x_pending_reviews
+ where agent_id = ${agentId} and user_id = ${userId} and status = 'pending'
+ `;
+ if (pending >= MAX_PENDING_REVIEWS_PER_AGENT) {
+ throw new XPostError('review_queue_full', `${pending} posts are already waiting for approval`, 409, { review_url: settings });
+ }
+ const [row] = await sql`
+ insert into x_pending_reviews
+ (user_id, agent_id, text, thread_parts, kind, source, source_ref, scheduled_for, reply_to_tweet_id)
+ values (${userId}, ${agentId}, ${parts[0]}, ${threadJson}::jsonb, ${kind}, ${source}, ${sourceRef},
+ ${when ? when.toISOString() : null}, ${replyTo})
+ returning id, created_at
+ `;
+ return {
+ status: 'pending_review',
+ review_id: row.id,
+ kind,
+ scheduled_for: when ? when.toISOString() : null,
+ needs_connection: !conn,
+ connect_url: conn ? undefined : connectUrl(agentId),
+ review_url: settings,
+ message: conn
+ ? 'Queued for the owner\'s approval. Nothing was posted.'
+ : 'Queued for the owner\'s approval. Connect an X account before approving it.',
+ };
+ }
+
+ if (!conn) {
+ throw new XPostError('not_connected', 'no X account is connected for this agent or its owner', 400, {
+ connect_url: connectUrl(agentId),
+ });
+ }
+
+ const cadence = await cadenceState(agentId, policy);
+ if (cadence.remaining_24h <= 0) {
+ throw new XPostError('daily_cap_reached', `the policy allows ${policy.max_posts_per_day} posts a day`, 429, { cadence });
+ }
+
+ const nextSlot = cadence.next_allowed_at ? new Date(cadence.next_allowed_at) : null;
+ const goesOutAt = when && nextSlot ? (when > nextSlot ? when : nextSlot) : when || nextSlot;
+ if (goesOutAt) {
+ const [row] = await sql`
+ insert into x_scheduled_posts (user_id, agent_id, text, thread_parts, reply_to_tweet_id, scheduled_at, kind)
+ values (${userId}, ${agentId}, ${parts[0]}, ${threadJson}::jsonb, ${replyTo}, ${goesOutAt.toISOString()}, ${kind})
+ returning id, scheduled_at
+ `;
+ return {
+ status: 'scheduled',
+ scheduled_post_id: row.id,
+ scheduled_at: row.scheduled_at,
+ kind,
+ reason: when && goesOutAt === when ? 'requested_time' : 'min_interval',
+ };
+ }
+
+ const result = await publishTweet({
+ userId,
+ agentId,
+ kind,
+ text: parts.length > 1 ? null : parts[0],
+ threadParts: parts.length > 1 ? parts : null,
+ replyTo,
+ });
+ return { status: 'published', kind, ...result };
+}
+
+/** Pending approvals and scheduled posts, optionally for one agent. */
+export async function listScheduledPosts({ userId, agentId = null, limit = 50 }) {
+ if (agentId) await loadOwnedAgent(userId, agentId);
+ const lim = Math.min(Math.max(Number(limit) || 50, 1), 100);
+ const [reviews, scheduled] = await Promise.all([
+ agentId
+ ? sql`select id, agent_id, text, thread_parts, kind, source, source_ref, scheduled_for, reply_to_tweet_id, created_at
+ from x_pending_reviews where user_id = ${userId} and agent_id = ${agentId} and status = 'pending'
+ order by created_at desc limit ${lim}`
+ : sql`select id, agent_id, text, thread_parts, kind, source, source_ref, scheduled_for, reply_to_tweet_id, created_at
+ from x_pending_reviews where user_id = ${userId} and status = 'pending'
+ order by created_at desc limit ${lim}`,
+ agentId
+ ? sql`select id, agent_id, text, thread_parts, kind, scheduled_at, posted_at, tweet_id, error
+ from x_scheduled_posts where user_id = ${userId} and agent_id = ${agentId}
+ and (posted_at is null or posted_at > now() - interval '7 days')
+ order by scheduled_at desc limit ${lim}`
+ : sql`select id, agent_id, text, thread_parts, kind, scheduled_at, posted_at, tweet_id, error
+ from x_scheduled_posts where user_id = ${userId}
+ and (posted_at is null or posted_at > now() - interval '7 days')
+ order by scheduled_at desc limit ${lim}`,
+ ]);
+ const state = (p) => (p.posted_at ? 'posted' : p.error ? 'failed' : 'scheduled');
+ return {
+ pending_review: reviews,
+ scheduled: scheduled.map((p) => ({ ...p, state: state(p) })),
+ };
+}
diff --git a/api/_lib/x-post.js b/api/_lib/x-post.js
index caecedf6d..694cc49f4 100644
--- a/api/_lib/x-post.js
+++ b/api/_lib/x-post.js
@@ -66,14 +66,21 @@ async function refreshIfNeeded(conn) {
if (!r.ok) throw new XPostError('reauth_required', `X token refresh failed: ${await r.text()}`, 401);
const tok = await r.json();
const newExpiresAt = new Date(Date.now() + (tok.expires_in ?? 7200) * 1000).toISOString();
- await sql`
- update social_connections
- set access_token = ${encryptToken(tok.access_token)},
- refresh_token = ${tok.refresh_token ? encryptToken(tok.refresh_token) : conn.refresh_token},
- expires_at = ${newExpiresAt},
- updated_at = now()
- where id = ${conn.id}
- `;
+ const access = encryptToken(tok.access_token);
+ const refresh = tok.refresh_token ? encryptToken(tok.refresh_token) : conn.refresh_token;
+ if (conn.source === 'agent') {
+ await sql`
+ update agent_x_connections
+ set access_token = ${access}, refresh_token = ${refresh}, expires_at = ${newExpiresAt}, updated_at = now()
+ where agent_id = ${conn.agent_id}
+ `;
+ } else {
+ await sql`
+ update social_connections
+ set access_token = ${access}, refresh_token = ${refresh}, expires_at = ${newExpiresAt}, updated_at = now()
+ where id = ${conn.id}
+ `;
+ }
return tok.access_token;
}
@@ -178,10 +185,69 @@ async function uploadMediaSteps({ accessToken, buffer, mimeType, signal }) {
return mediaId;
}
+/**
+ * The X account a post goes out through. An agent with its own connected
+ * account (agent_x_connections) posts as itself; every other post uses the
+ * owner's account (social_connections). `source` tells the write paths which
+ * table the counters and refreshed tokens belong to.
+ */
+export async function resolveXConnection({ userId, agentId = null }) {
+ if (agentId) {
+ const [own] = await sql`
+ select agent_id, user_id, provider_uid, username, access_token, refresh_token, expires_at,
+ scopes, posts_this_month, month_resets_at, last_posted_at, connected_at
+ from agent_x_connections
+ where agent_id = ${agentId} and user_id = ${userId} and disconnected_at is null
+ limit 1
+ `;
+ if (own) return { ...own, source: 'agent' };
+ }
+ const [owner] = await sql`
+ select * from social_connections
+ where user_id = ${userId} and provider = 'x' and disconnected_at is null
+ limit 1
+ `;
+ return owner ? { ...owner, source: 'owner' } : null;
+}
+
+async function resetMonthIfDue(conn) {
+ if (new Date(conn.month_resets_at) > new Date()) return;
+ if (conn.source === 'agent') {
+ await sql`
+ update agent_x_connections
+ set posts_this_month = 0, month_resets_at = date_trunc('month', now()) + interval '1 month'
+ where agent_id = ${conn.agent_id}
+ `;
+ } else {
+ await sql`
+ update social_connections
+ set posts_this_month = 0, month_resets_at = date_trunc('month', now()) + interval '1 month'
+ where id = ${conn.id}
+ `;
+ }
+ conn.posts_this_month = 0;
+}
+
+async function recordPostedCount(conn, count) {
+ if (conn.source === 'agent') {
+ await sql`
+ update agent_x_connections
+ set posts_this_month = posts_this_month + ${count}, last_posted_at = now(), updated_at = now()
+ where agent_id = ${conn.agent_id}
+ `;
+ } else {
+ await sql`
+ update social_connections
+ set posts_this_month = posts_this_month + ${count}, last_posted_at = now(), updated_at = now()
+ where id = ${conn.id}
+ `;
+ }
+}
+
// Publish a single tweet (text) or a thread (threadParts).
// Counts each tweet against the user's monthly quota.
// Optionally appends a link to https://three.ws/avatars/<agentId> on the final tweet.
-export async function publishTweet({ userId, agentId = null, text, threadParts = null, replyTo = null, appendLink = false, mediaBuffer = null, mediaMimeType = null }) {
+export async function publishTweet({ userId, agentId = null, kind = null, text, threadParts = null, replyTo = null, appendLink = false, mediaBuffer = null, mediaMimeType = null }) {
if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {
throw new XPostError('not_configured', 'X OAuth is not configured', 501);
}
@@ -197,12 +263,7 @@ export async function publishTweet({ userId, agentId = null, text, threadParts =
const tier = await getUserTier(userId);
- const rows = await sql`
- select * from social_connections
- where user_id = ${userId} and provider = 'x' and disconnected_at is null
- limit 1
- `;
- const conn = rows[0];
+ const conn = await resolveXConnection({ userId, agentId });
if (!conn) throw new XPostError('not_connected', 'X account not connected', 400);
// A connection made for memory seeding only carries read scopes. Say so, and
@@ -214,20 +275,18 @@ export async function publishTweet({ userId, agentId = null, text, threadParts =
'insufficient_scope',
'this X connection is read-only; reconnect X with posting access to publish',
400,
- { missing_scopes: missingWrite, connect_url: '/api/auth/x/connect?scope=full' },
+ {
+ missing_scopes: missingWrite,
+ connect_url:
+ conn.source === 'agent'
+ ? `/api/auth/x/connect?scope=full&target=agent&agent_id=${encodeURIComponent(agentId)}`
+ : '/api/auth/x/connect?scope=full',
+ },
);
}
// Reset monthly counter if month boundary crossed.
- if (new Date(conn.month_resets_at) <= new Date()) {
- await sql`
- update social_connections
- set posts_this_month = 0,
- month_resets_at = date_trunc('month', now()) + interval '1 month'
- where id = ${conn.id}
- `;
- conn.posts_this_month = 0;
- }
+ await resetMonthIfDue(conn);
if (conn.posts_this_month + parts.length > tier.quota) {
throw new XPostError('quota_exceeded', `${tier.tier} tier limit of ${tier.quota} posts/month reached`, 402, {
@@ -290,25 +349,20 @@ export async function publishTweet({ userId, agentId = null, text, threadParts =
const d = await postOne({ accessToken, text: part, replyTo: prevId, mediaIds: i === 0 ? mediaIds : null });
published.push(d);
await sql`
- insert into x_posts (user_id, agent_id, tweet_id, text, reply_to_tweet_id)
- values (${userId}, ${agentId}, ${d.id}, ${part}, ${prevId})
+ insert into x_posts (user_id, agent_id, tweet_id, text, reply_to_tweet_id, kind)
+ values (${userId}, ${agentId}, ${d.id}, ${part}, ${prevId}, ${kind})
`;
prevId = d.id;
}
- await sql`
- update social_connections
- set posts_this_month = posts_this_month + ${published.length},
- last_posted_at = now(),
- updated_at = now()
- where id = ${conn.id}
- `;
+ await recordPostedCount(conn, published.length);
const head0 = published[0];
return {
tweet_id: head0.id,
url: `https://x.com/${conn.username}/status/${head0.id}`,
username: conn.username,
+ account: conn.source,
thread: published.length > 1 ? published.map((p) => p.id) : undefined,
posts_used: conn.posts_this_month + published.length,
quota: tier.quota,
diff --git a/api/auth/x/[action].js b/api/auth/x/[action].js
index 25040d502..6c2e2e4df 100644
--- a/api/auth/x/[action].js
+++ b/api/auth/x/[action].js
@@ -28,6 +28,7 @@ import { revokeAllSeedConsentsForUser } from '../../_lib/x-seed-consent.js';
import { resolveScopeSet } from '../../_lib/x-scopes.js';
import { fetchUpstream } from '../../_lib/upstream-fetch.js';
+import { isUuid } from '../../_lib/validate.js';
// ── Signed-cookie PKCE state ─────────────────────────────────────────────────
const STATE_COOKIE = '__Host-xoa';
@@ -40,7 +41,7 @@ function b64urlDecode(s) {
return Buffer.from(s, 'base64url').toString('utf8');
}
-async function signState({ state, codeVerifier, userId, agentId, scopeSet, returnTo }) {
+async function signState({ state, codeVerifier, userId, agentId, scopeSet, returnTo, target }) {
const payload = {
s: state,
v: codeVerifier,
@@ -48,6 +49,7 @@ async function signState({ state, codeVerifier, userId, agentId, scopeSet, retur
a: agentId,
k: scopeSet,
r: returnTo || null,
+ t: target === 'agent' ? 'agent' : 'owner',
e: Math.floor(Date.now() / 1000) + STATE_TTL_SEC,
};
const body = b64urlEncode(JSON.stringify(payload));
@@ -77,6 +79,7 @@ async function verifyState(token, expectedState) {
agentId: payload.a,
scopeSet: resolveScopeSet(payload.k).name,
returnTo: resolveReturnTo(payload.r),
+ target: payload.t === 'agent' ? 'agent' : 'owner',
};
}
@@ -133,13 +136,20 @@ export function decryptToken(ciphertext) {
// Surfaces that start a connect for their own flow and want the browser back on
// them. An allowlist, never a raw path, so the parameter cannot become an open
// redirect.
-const RETURN_SURFACES = new Set(['/fee-bridge']);
+const RETURN_SURFACES = new Set(['/fee-bridge', '/settings/connections']);
function resolveReturnTo(value) {
return typeof value === 'string' && RETURN_SURFACES.has(value) ? value : null;
}
-function connectReturnUrl({ scopeSet, agentId, outcome, returnTo = null }) {
+function connectReturnUrl({ scopeSet, agentId, outcome, returnTo = null, target = 'owner' }) {
+ // An agent-owned account is managed on /settings/connections, so a connect
+ // made for one agent always lands back on that agent's card there.
+ if (target === 'agent' || returnTo === '/settings/connections') {
+ const q = new URLSearchParams({ x: outcome });
+ if (agentId) q.set('agent', agentId);
+ return `/settings/connections?${q.toString()}#x`;
+ }
if (returnTo) return `${returnTo}?x=${outcome}`;
if (scopeSet === 'read') {
const q = new URLSearchParams({ tab: 'connected-accounts', x: outcome });
@@ -161,6 +171,12 @@ async function handleConnect(req, res) {
const agentId = url.searchParams.get('agent_id') || null;
const scopeSet = resolveScopeSet(url.searchParams.get('scope'));
const returnTo = resolveReturnTo(url.searchParams.get('return_to'));
+ // target=agent connects an X account to this one agent (it then posts as
+ // itself); the default connects the owner's own account.
+ const target = url.searchParams.get('target') === 'agent' ? 'agent' : 'owner';
+ if (target === 'agent' && !isUuid(agentId)) {
+ return error(res, 400, 'validation_error', 'target=agent needs agent_id (a uuid)');
+ }
if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {
// Every Connect X button on the site is an anchor or a location assignment,
@@ -171,7 +187,7 @@ async function handleConnect(req, res) {
if (wantsHtmlNavigation(req)) {
return redirect(
res,
- connectReturnUrl({ scopeSet: scopeSet.name, agentId, outcome: 'unconfigured', returnTo }),
+ connectReturnUrl({ scopeSet: scopeSet.name, agentId, outcome: 'unconfigured', returnTo, target }),
);
}
return error(res, 501, 'not_configured', 'X OAuth is not configured');
@@ -183,6 +199,13 @@ async function handleConnect(req, res) {
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (target === 'agent') {
+ const [owned] = await sql`
+ select 1 from agent_identities where id = ${agentId} and user_id = ${user.id} and deleted_at is null limit 1
+ `;
+ if (!owned) return error(res, 404, 'not_found', 'agent not found');
+ }
+
const codeVerifier = randomToken(32); // 43-char base64url
const codeChallenge = await sha256Base64Url(codeVerifier);
const state = randomToken(16);
@@ -194,6 +217,7 @@ async function handleConnect(req, res) {
agentId,
scopeSet: scopeSet.name,
returnTo,
+ target,
});
res.setHeader('set-cookie', stateCookie(signed));
@@ -235,11 +259,11 @@ async function handleCallback(req, res) {
res.setHeader('set-cookie', stateCookie('', { clear: true }));
if (!stateData) return error(res, 400, 'invalid_state', 'OAuth state expired or invalid');
- const { codeVerifier, userId, agentId: stateAgentId, scopeSet, returnTo } = stateData;
+ const { codeVerifier, userId, agentId: stateAgentId, scopeSet, returnTo, target } = stateData;
// Return to the surface that started the connect, the same one a refusal at
// /connect lands on.
const backTo = (outcome) =>
- connectReturnUrl({ scopeSet, agentId: stateAgentId, outcome, returnTo });
+ connectReturnUrl({ scopeSet, agentId: stateAgentId, outcome, returnTo, target });
const successRedirect = backTo('connected');
const errorRedirect = backTo('error');
const deniedRedirect = backTo('denied');
@@ -303,6 +327,33 @@ async function handleCallback(req, res) {
const encAccess = encryptToken(access_token);
const encRefresh = refresh_token ? encryptToken(refresh_token) : null;
+ if (target === 'agent') {
+ // Ownership was checked at /connect; re-check here because the agent can
+ // change hands (marketplace transfer) inside the ten-minute state window.
+ const [owned] = await sql`
+ select 1 from agent_identities where id = ${stateAgentId} and user_id = ${userId} and deleted_at is null limit 1
+ `;
+ if (!owned) return redirect(res, errorRedirect);
+ await sql`
+ INSERT INTO agent_x_connections
+ (agent_id, user_id, provider_uid, username, access_token, refresh_token, expires_at, raw_data, scopes)
+ VALUES
+ (${stateAgentId}, ${userId}, ${profile.id}, ${profile.username}, ${encAccess}, ${encRefresh}, ${expiresAt}, ${JSON.stringify(profile)}, ${grantedScopes})
+ ON CONFLICT (agent_id) DO UPDATE SET
+ user_id = EXCLUDED.user_id,
+ provider_uid = EXCLUDED.provider_uid,
+ username = EXCLUDED.username,
+ access_token = EXCLUDED.access_token,
+ refresh_token = EXCLUDED.refresh_token,
+ expires_at = EXCLUDED.expires_at,
+ raw_data = EXCLUDED.raw_data,
+ scopes = EXCLUDED.scopes,
+ disconnected_at = NULL,
+ updated_at = now()
+ `;
+ return redirect(res, successRedirect);
+ }
+
// Reconnecting a DIFFERENT X account retires every memory-seeding grant made
// for the previous one and deletes the memories it produced. Consent was
// given for that account's posts, and it does not transfer to this one.
diff --git a/api/oauth/[action].js b/api/oauth/[action].js
index 167c7bca4..5c11c912b 100644
--- a/api/oauth/[action].js
+++ b/api/oauth/[action].js
@@ -15,6 +15,7 @@ import { env } from '../_lib/env.js';
import { z } from 'zod';
import { parse } from '../_lib/validate.js';
import { filterRegisterableScope } from '../_lib/oauth-scopes.js';
+import { requireCsrf } from '../_lib/csrf.js';
// ── authorize ─────────────────────────────────────────────────────────────────
@@ -441,6 +442,55 @@ async function handleIntrospect(req, res) {
}
}
+// ── grants (connected apps) ───────────────────────────────────────────────────
+// The apps a person has authorized: the desktop console, the CLI, every editor
+// that signed in over MCP. GET lists one row per client holding a live refresh
+// token; DELETE ?client_id= revokes all of that client's refresh tokens.
+// Session only, on purpose: a bearer token must not be able to list or revoke
+// the other apps on the account, including itself.
+// Access tokens are stateless JWTs, so a revoked app keeps working until its
+// current access token expires (one hour at most) and then cannot renew.
+
+async function handleGrants(req, res) {
+ if (cors(req, res, { methods: 'GET,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'DELETE'])) return;
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to manage connected apps');
+ if (req.method === 'GET') {
+ const rows = await sql`
+ select c.client_id, c.name, c.client_uri, c.logo_uri, c.software_id, c.software_version,
+ min(t.created_at) as authorized_at, max(coalesce(t.last_used_at, t.created_at)) as last_used_at,
+ string_agg(distinct t.scope, ' ') as scopes
+ from oauth_refresh_tokens t
+ join oauth_clients c on c.client_id = t.client_id
+ where t.user_id = ${user.id} and t.revoked_at is null and t.expires_at > now()
+ group by c.client_id, c.name, c.client_uri, c.logo_uri, c.software_id, c.software_version
+ order by last_used_at desc
+ `;
+ return json(res, 200, {
+ grants: rows.map((r) => ({
+ client_id: r.client_id,
+ name: r.name,
+ client_uri: r.client_uri,
+ logo_uri: r.logo_uri,
+ software: r.software_id ? `${r.software_id}${r.software_version ? ` ${r.software_version}` : ''}` : null,
+ scopes: [...new Set(String(r.scopes || '').split(/\s+/).filter(Boolean))],
+ authorized_at: r.authorized_at,
+ last_used_at: r.last_used_at,
+ })),
+ });
+ }
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const clientId = new URL(req.url, 'http://x').searchParams.get('client_id');
+ if (!clientId) return error(res, 400, 'invalid_request', 'client_id required');
+ const revoked = await sql`
+ update oauth_refresh_tokens set revoked_at = now()
+ where user_id = ${user.id} and client_id = ${clientId} and revoked_at is null
+ returning id
+ `;
+ return json(res, 200, { client_id: clientId, revoked: revoked.length });
+}
+
// ── dispatcher ────────────────────────────────────────────────────────────────
const DISPATCH = {
@@ -450,6 +500,7 @@ const DISPATCH = {
register: handleRegister,
revoke: handleRevoke,
introspect: handleIntrospect,
+ grants: handleGrants,
};
export default wrap(async (req, res) => {
diff --git a/api/x/agents.js b/api/x/agents.js
new file mode 100644
index 000000000..df8f08fd4
--- /dev/null
+++ b/api/x/agents.js
@@ -0,0 +1,87 @@
+// Per-agent X posting: connection, policy, compose. docs/x-posting-policy.md.
+//
+// GET /api/x/agents every owned agent with its posting state
+// GET /api/x/agents?agent_id=<uuid> one agent: connection, policy, cadence, queue size
+// PUT /api/x/agents?agent_id=<uuid> update the posting policy (partial)
+// body: { enabled?, allowed_kinds?, review_before_post?,
+// max_posts_per_day?, min_interval_min?,
+// tone_guidance?, banned_terms?, max_hashtags?,
+// allow_links? }
+// POST /api/x/agents?agent_id=<uuid> ask the agent to post, through its policy
+// body: { kind, text? | thread_parts?, reply_to_tweet_id?,
+// scheduled_at? }
+// DELETE /api/x/agents?agent_id=<uuid> disconnect the agent's own X account
+//
+// Cookie sessions (CSRF on writes) and bearer tokens (agents:read / agents:write)
+// both work, so the settings page, the CLI and MCP clients share one surface.
+
+import { getRequestUser, hasScope } from '../_lib/auth.js';
+import { cors, method, wrap, error, readJson, json, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+import { XPostError } from '../_lib/x-post.js';
+import {
+ disconnectAgentX,
+ getAgentXState,
+ listAgentXStates,
+ requestAgentPost,
+ saveAgentPolicy,
+} from '../_lib/x-agent-policy.js';
+
+function scopeOk(user, needed) {
+ return user.source !== 'bearer' || hasScope(user.scope, needed);
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PUT,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT', 'POST', 'DELETE'])) return;
+
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const agentId = new URL(req.url, 'http://x').searchParams.get('agent_id');
+ if (agentId !== null && !isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');
+
+ try {
+ if (req.method === 'GET') {
+ if (!scopeOk(user, 'agents:read')) return error(res, 403, 'insufficient_scope', 'requires agents:read');
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ if (!agentId) return json(res, 200, { agents: await listAgentXStates(user.id) });
+ return json(res, 200, await getAgentXState({ userId: user.id, agentId }));
+ }
+
+ if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');
+ if (!scopeOk(user, 'agents:write')) return error(res, 403, 'insufficient_scope', 'requires agents:write');
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const rl = await limits.xAgentPost(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (req.method === 'DELETE') {
+ return json(res, 200, await disconnectAgentX({ userId: user.id, agentId }));
+ }
+
+ const body = (await readJson(req)) || {};
+
+ if (req.method === 'PUT') {
+ const policy = await saveAgentPolicy({ userId: user.id, agentId, patch: body });
+ return json(res, 200, { policy });
+ }
+
+ const result = await requestAgentPost({
+ userId: user.id,
+ agentId,
+ kind: body.kind,
+ text: typeof body.text === 'string' ? body.text : null,
+ threadParts: Array.isArray(body.thread_parts) ? body.thread_parts : null,
+ replyTo: typeof body.reply_to_tweet_id === 'string' ? body.reply_to_tweet_id : null,
+ scheduledAt: typeof body.scheduled_at === 'string' ? body.scheduled_at : null,
+ source: user.source === 'bearer' ? 'api' : 'settings',
+ });
+ return json(res, result.status === 'published' ? 201 : 202, result);
+ } catch (err) {
+ if (err instanceof XPostError) return error(res, err.status, err.code, err.message, err.extra);
+ throw err;
+ }
+});
diff --git a/api/x/reviews.js b/api/x/reviews.js
index dde32d1db..f63adb552 100644
--- a/api/x/reviews.js
+++ b/api/x/reviews.js
@@ -1,4 +1,4 @@
-// GET /api/x/reviews: list pending review drafts
+// GET /api/x/reviews[?agent_id=]: list pending review drafts (optionally for one agent)
// PATCH /api/x/reviews?id=<uuid>: approve (publishes) or edit + approve
// body: { action: 'approve'|'reject', text?, thread_parts? }
// DELETE /api/x/reviews?id=<uuid>: reject without publishing
@@ -8,7 +8,7 @@ import { getSessionUser } from '../_lib/auth.js';
import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { isUuid } from '../_lib/validate.js';
-import { publishTweet, XPostError } from '../_lib/x-post.js';
+import { publishTweet, XPostError, MAX_TWEET_LEN } from '../_lib/x-post.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
@@ -18,13 +18,23 @@ export default wrap(async (req, res) => {
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
if (req.method === 'GET') {
- const rows = await sql`
- select id, trigger_id, agent_id, text, thread_parts, status, created_at
- from x_pending_reviews
- where user_id = ${user.id} and status = 'pending'
- order by created_at desc
- limit 50
- `;
+ const agentFilter = new URL(req.url, 'http://x').searchParams.get('agent_id');
+ if (agentFilter && !isUuid(agentFilter)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');
+ const rows = agentFilter
+ ? await sql`
+ select id, trigger_id, agent_id, text, thread_parts, kind, source, source_ref, scheduled_for, reply_to_tweet_id, status, created_at
+ from x_pending_reviews
+ where user_id = ${user.id} and agent_id = ${agentFilter} and status = 'pending'
+ order by created_at desc
+ limit 50
+ `
+ : await sql`
+ select id, trigger_id, agent_id, text, thread_parts, kind, source, source_ref, scheduled_for, reply_to_tweet_id, status, created_at
+ from x_pending_reviews
+ where user_id = ${user.id} and status = 'pending'
+ order by created_at desc
+ limit 50
+ `;
return json(res, 200, { reviews: rows });
}
@@ -75,30 +85,51 @@ export default wrap(async (req, res) => {
const [review] = await sql`
update x_pending_reviews set status = 'approved', resolved_at = now()
where id = ${id} and user_id = ${user.id} and status = 'pending'
- returning id, agent_id, text, thread_parts
+ returning id, agent_id, text, thread_parts, kind, scheduled_for, reply_to_tweet_id
`;
if (!review) return error(res, 404, 'not_found', 'review not found or already resolved');
+ const release = () =>
+ sql`update x_pending_reviews set status = 'pending', resolved_at = null where id = ${id}`.catch((e) =>
+ console.error('[x-reviews] could not release review', id, e.message),
+ );
const text = typeof body?.text === 'string' ? body.text : review.text;
const threadParts = Array.isArray(body?.thread_parts)
? body.thread_parts
: (Array.isArray(review.thread_parts) ? review.thread_parts : null);
+ const parts = threadParts ? threadParts.map((p) => String(p).trim()).filter(Boolean) : [String(text).trim()];
+ if (!parts.length || parts.some((p) => !p || p.length > MAX_TWEET_LEN)) {
+ await release();
+ return error(res, 400, 'validation_error', `each part must be 1 to ${MAX_TWEET_LEN} characters`);
+ }
+
+ // A draft queued with a future time is scheduled on approval, not posted now.
+ if (review.scheduled_for && new Date(review.scheduled_for).getTime() > Date.now()) {
+ const [row] = await sql`
+ insert into x_scheduled_posts (user_id, agent_id, text, thread_parts, reply_to_tweet_id, scheduled_at, kind)
+ values (${user.id}, ${review.agent_id}, ${parts[0]}, ${parts.length > 1 ? JSON.stringify(parts) : null}::jsonb,
+ ${review.reply_to_tweet_id}, ${review.scheduled_for}, ${review.kind})
+ returning id, scheduled_at
+ `;
+ return json(res, 200, { approved: id, status: 'scheduled', scheduled_post_id: row.id, scheduled_at: row.scheduled_at });
+ }
+
try {
const result = await publishTweet({
userId: user.id,
agentId: review.agent_id,
- text: threadParts ? null : text,
- threadParts,
+ kind: review.kind,
+ text: parts.length > 1 ? null : parts[0],
+ threadParts: parts.length > 1 ? parts : null,
+ replyTo: review.reply_to_tweet_id || null,
appendLink,
});
- return json(res, 200, { approved: id, ...result });
+ return json(res, 200, { approved: id, status: 'published', ...result });
} catch (err) {
// Nothing was published, so hand the review back to the queue instead of
// leaving it marked approved with no tweet behind it.
- await sql`
- update x_pending_reviews set status = 'pending', resolved_at = null where id = ${id}
- `.catch((e) => console.error('[x-reviews] could not release review', id, e.message));
+ await release();
if (err instanceof XPostError) return error(res, err.status, err.code, err.message, err.extra);
console.error('[x-reviews] publish failed', err);
return error(res, 500, 'internal_error', err.message || 'publish failed');