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.

fix(x-content): stop holding posts when X refuses the account, and say what to fix

nirholasfda23d501e4b
diff --git a/api/_lib/x-content/runner.js b/api/_lib/x-content/runner.js
index 85877f321..f454dcbfa 100644
--- a/api/_lib/x-content/runner.js
+++ b/api/_lib/x-content/runner.js
@@ -53,7 +53,9 @@ export function placeHold(state, item, root, reason, now = Date.now()) {
// the account or the platform (stop, retry the same post next tick).
export function isPostSpecific(err) {
const status = Number(err?.code ?? err?.status);
- if (!status || status === 429 || status >= 500 || status === 401) return false;
+ // 402 is the X account out of API credits: every post would be refused the
+ // same way, so holding this one would only shelve good stock.
+ if (!status || status === 429 || status >= 500 || status === 401 || status === 402) return false;
const text = JSON.stringify(err?.data || err?.message || '').toLowerCase();
if (status === 403) return /duplicate|not allowed to create/.test(text);
return status >= 400 && status < 500;
@@ -129,6 +131,35 @@ async function refreshOutcomes({ outcomes, stored, collect, client, ledger, now
}
}
+// ── The account, not the post ───────────────────────────────────────────────
+// What X says when it refuses the account rather than the post, in words the
+// owner can act on. Rate limits and outages are left out: the next tick
+// retries them and they clear on their own.
+export function accountRefusal(err) {
+ const status = Number(err?.code ?? err?.status);
+ const text = JSON.stringify(err?.data || err?.message || '').toLowerCase();
+ if (status === 402) {
+ return /credits/.test(text)
+ ? 'the X API account has run out of credits; top it up in the X developer console, and the next tick posts'
+ : 'X answered 402 Payment Required for the account; check its billing in the X developer console';
+ }
+ if (status === 401) return 'X rejected the credentials (401); the access token or the app keys on the service need replacing';
+ if (status === 403 && !/duplicate|not allowed to create/.test(text)) return 'X refused the account (403); check the app permissions and the account status in the X developer console';
+ return null;
+}
+
+// Raised once a day per cause, as critical: no post can go out until a person
+// acts, and every slot until then is a missed one.
+async function alertAccountRefusal(state, store, refusal, now) {
+ const today = new Date(now).toISOString().slice(0, 10);
+ state.accountAlerted ||= {};
+ if (state.accountAlerted[refusal] === today) return;
+ state.accountAlerted[refusal] = today;
+ await store.save(state);
+ const { sendOpsAlert } = await import('../alerts.js');
+ await sendOpsAlert('🚨 x-content: X is refusing the account, nothing can post', refusal, { severity: 'critical' });
+}
+
// ── Missed slots ────────────────────────────────────────────────────────────
// Three a day is a quota (owner, 2026-09-30). An open slot with nothing to post
// is raised the moment it is seen, and a slot that closed unfilled is recorded
@@ -270,7 +301,11 @@ async function fillSlot({ queue, state, store, root, now, requestedId, client, c
}
return { published: row, stock, lowStock, score: decision.score, tier: decision.tier, filledDown: Boolean(decision.filledDown), vetoYielded: Boolean(decision.vetoYielded), resumed: Boolean(decision.resuming), held, blocked, missed };
} catch (err) {
- if (!isPostSpecific(err) || !untouched(state, item)) throw err;
+ if (!isPostSpecific(err) || !untouched(state, item)) {
+ const refusal = accountRefusal(err);
+ if (refusal) await alertAccountRefusal(state, store, refusal, now).catch(() => {});
+ throw err;
+ }
const reason = `X rejected the post: ${err.message}`;
held.push({ id: item.id, reason, hold: placeHold(state, item, root, reason, now) });
delete state.inflight?.[item.id];
diff --git a/tests/x-content.test.js b/tests/x-content.test.js
index a86da373b..6764db4da 100644
--- a/tests/x-content.test.js
+++ b/tests/x-content.test.js
@@ -9,7 +9,7 @@ import { markdownToContentState, attachArticleMedia } from '../api/_lib/x-conten
import { DEFAULT_SLOTS, currentSlot, inQuietHours, jitterMinutes, pickDue, slotOpenings, tierOrder } from '../api/_lib/x-content/schedule.js';
import { linkProbeUrl } from '../api/_lib/x-content/verify.js';
import { engagementSignals, loadLifts, loadVolumeModel, rankItems, scoreItem, volumeScore } from '../api/_lib/x-content/priority.js';
-import { activeHolds, inventory, isPostSpecific, placeHold, runTick } from '../api/_lib/x-content/runner.js';
+import { accountRefusal, activeHolds, inventory, isPostSpecific, placeHold, runTick } from '../api/_lib/x-content/runner.js';
import { memoryStore } from '../api/_lib/x-content/state.js';
import { validateItem, validateQueue, loadQueue } from '../api/_lib/x-content/queue.js';
import { previewClient, publishItem } from '../api/_lib/x-content/publisher.js';
@@ -323,10 +323,42 @@ describe('holds and fall-through', () => {
expect(isPostSpecific({ code: 403, data: { detail: 'forbidden' } })).toBe(false);
expect(isPostSpecific({ code: 401 })).toBe(false);
expect(isPostSpecific({ code: 429 })).toBe(false);
+ expect(isPostSpecific({ code: 402, data: { detail: 'credits depleted', type: 'https://api.x.com/2/problems/credits-depleted' } })).toBe(false);
expect(isPostSpecific({ code: 503 })).toBe(false);
expect(isPostSpecific(new Error('socket hang up'))).toBe(false);
});
+ it('names an account-level refusal in words the owner can act on', () => {
+ expect(accountRefusal({ code: 402, data: { detail: 'credits depleted' } })).toMatch(/run out of credits; top it up/);
+ expect(accountRefusal({ code: 402, data: { detail: 'payment required' } })).toMatch(/402 Payment Required/);
+ expect(accountRefusal({ code: 401 })).toMatch(/rejected the credentials/);
+ expect(accountRefusal({ code: 403, data: { detail: 'forbidden' } })).toMatch(/refused the account/);
+ expect(accountRefusal({ code: 403, data: { detail: 'You are not allowed to create a Tweet with duplicate content.' } })).toBe(null);
+ expect(accountRefusal({ code: 429 })).toBe(null);
+ expect(accountRefusal({ code: 503 })).toBe(null);
+ });
+
+ it('stops on an account refusal without holding the post, and keeps it ready for the next tick', async () => {
+ const { mkdtempSync: mk, mkdirSync: md, writeFileSync: wf } = await import('node:fs');
+ const { contentHash: hashOf, reviewPath: pathOf } = await import('../api/_lib/x-content/review.js');
+ const dir = mk(join(tmpdir(), 'x-refusal-'));
+ md(join(dir, 'data/x-content/reviews'), { recursive: true });
+ const cadence = { slots: [{ tier: 2, at: '12:00' }], windowMinutes: 0, minimumMinutesApart: 1, dailyCap: 3, quietHoursUtc: null };
+ const item = { id: 'ready', status: 'approved', kind: 'post', tier: 2, lane: 'a', pattern: 'b', notBefore: '2026-09-17T00:00:00Z', textOnly: true, posts: [{ text: HEAD }] };
+ wf(join(dir, pathOf(item.id)), JSON.stringify({ id: item.id, contentHash: hashOf(item, dir), reviewedAt: '2026-09-17T00:00:00Z', passed: true, blockers: [] }));
+ wf(join(dir, 'data/x-content/queue.json'), JSON.stringify({ account: 'trythreews', cadence, items: [item] }));
+ const store = memoryStore();
+ const client = previewClient();
+ client.tweet = async () => {
+ throw Object.assign(new Error('Request failed with code 402'), { code: 402, data: { detail: 'credits depleted' } });
+ };
+ const now = Date.parse('2026-09-17T12:30:00Z');
+ await expect(runTick({ root: dir, store, dryRun: false, now, env: {}, client, checks: async () => [], outcomes: null })).rejects.toThrow('402');
+ const state = await store.load();
+ expect(state.holds?.ready).toBeUndefined();
+ expect(Object.keys(state.accountAlerted)).toEqual([accountRefusal({ code: 402, data: { detail: 'credits depleted' } })]);
+ });
+
it('backs off a held post and releases it when the post changes', () => {
const dir = sandbox();
const item = { id: 'a', kind: 'post', posts: [{ text: HEAD }] };