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(agent-gateway): drain Telegram and Discord inboxes with leased claims, retries and dead letters

nirholas7da824e6b998
diff --git a/api/_lib/gateway/store.js b/api/_lib/gateway/store.js
index 46d9331d5..d799c5369 100644
--- a/api/_lib/gateway/store.js
+++ b/api/_lib/gateway/store.js
@@ -224,42 +224,95 @@ export async function enqueueInbox({ platform, dedupeKey, chatKey, payload }) {
* Claim up to `limit` deliveries, at most one per chat, and only the oldest open
* delivery of a chat whose previous delivery is not still being processed, so a
* chat's replies always come back in the order its messages were sent.
+ *
+ * A queued delivery whose `locked_until` lies in the future is backing off after
+ * a failed attempt (failInbox with retryAfterSeconds) and is not ready yet; it
+ * still heads its chat, so nothing behind it overtakes it.
+ *
+ * `platforms` limits the claim to the platforms this worker has an adapter for,
+ * so a row for a platform it cannot deliver to waits for a worker that can.
+ * `chatKeys` limits it to specific chats (draining one chat while debugging).
*/
-export async function claimInbox({ limit = 8, leaseSeconds = 120 } = {}) {
+export async function claimInbox({ limit = 8, leaseSeconds = 120, platforms = null, chatKeys = null } = {}) {
+ const platformList = Array.isArray(platforms) ? platforms.map(String) : null;
+ const chatList = Array.isArray(chatKeys) ? chatKeys.map(String) : null;
return sql`
WITH heads AS (
SELECT DISTINCT ON (chat_key) id, status, locked_until
FROM gateway_inbox
WHERE status IN ('queued', 'processing')
+ AND (${platformList}::text[] IS NULL OR platform = ANY(${platformList}::text[]))
+ AND (${chatList}::text[] IS NULL OR chat_key = ANY(${chatList}::text[]))
ORDER BY chat_key, id
), ready AS (
SELECT id FROM heads
- WHERE status = 'queued' OR locked_until < now()
+ WHERE (status = 'queued' AND (locked_until IS NULL OR locked_until <= now()))
+ OR (status = 'processing' AND locked_until < now())
ORDER BY id
LIMIT ${limit}
)
UPDATE gateway_inbox g
SET status = 'processing', attempts = g.attempts + 1, locked_until = now() + make_interval(secs => ${leaseSeconds})
FROM ready
- WHERE g.id = ready.id AND (g.status = 'queued' OR g.locked_until < now())
- RETURNING g.id, g.platform, g.chat_key, g.payload, g.attempts`;
+ WHERE g.id = ready.id
+ AND ((g.status = 'queued' AND (g.locked_until IS NULL OR g.locked_until <= now()))
+ OR (g.status = 'processing' AND g.locked_until < now()))
+ RETURNING g.id, g.platform, g.chat_key, g.payload, g.attempts, g.created_at`;
+}
+
+/**
+ * Extend the lease on a delivery still being processed, so a long agent turn is
+ * never reclaimed (and answered twice) while it is still running. Returns false
+ * when the row is no longer this worker's to hold.
+ */
+export async function renewInboxLease(id, leaseSeconds = 120) {
+ const rows = await sql`
+ UPDATE gateway_inbox SET locked_until = now() + make_interval(secs => ${leaseSeconds})
+ WHERE id = ${id} AND status = 'processing'
+ RETURNING id`;
+ return rows.length > 0;
}
export async function completeInbox(id) {
await sql`UPDATE gateway_inbox SET status = 'done', finished_at = now(), locked_until = NULL WHERE id = ${id}`;
}
-/** Requeue for another attempt, or park as failed after `maxAttempts`. */
-export async function failInbox(id, message, { attempts, maxAttempts = 3 } = {}) {
- const giveUp = attempts >= maxAttempts;
+/**
+ * Requeue for another attempt, or park as failed (the dead letter) after
+ * `maxAttempts` or when `deadLetter` says a retry cannot help. A requeued row
+ * waits `retryAfterSeconds` before it can be claimed again.
+ */
+export async function failInbox(id, message, { attempts, maxAttempts = 3, retryAfterSeconds = 0, deadLetter = false } = {}) {
+ const giveUp = deadLetter || attempts >= maxAttempts;
+ const wait = giveUp ? 0 : Math.max(0, Math.ceil(Number(retryAfterSeconds) || 0));
await sql`
UPDATE gateway_inbox
SET status = ${giveUp ? 'failed' : 'queued'}, last_error = ${String(message || '').slice(0, 500)},
- locked_until = NULL, finished_at = ${giveUp ? new Date().toISOString() : null}
+ locked_until = ${wait > 0 ? new Date(Date.now() + wait * 1000).toISOString() : null},
+ finished_at = ${giveUp ? new Date().toISOString() : null}
WHERE id = ${id}`;
return giveUp;
}
+/** The most recent dead letters, newest first, for the operator. */
+export async function listFailedInbox({ limit = 20 } = {}) {
+ return sql`
+ SELECT id, platform, chat_key, attempts, last_error, created_at, finished_at
+ FROM gateway_inbox WHERE status = 'failed'
+ ORDER BY finished_at DESC NULLS LAST, id DESC
+ LIMIT ${limit}`;
+}
+
+/** Put one dead letter back on the queue with a fresh attempt budget. */
+export async function requeueInbox(id) {
+ const [row] = await sql`
+ UPDATE gateway_inbox
+ SET status = 'queued', attempts = 0, locked_until = NULL, finished_at = NULL
+ WHERE id = ${id} AND status = 'failed'
+ RETURNING id, platform, chat_key`;
+ return row || null;
+}
+
export async function pruneInbox({ keepDays = 7 } = {}) {
await sql`
DELETE FROM gateway_inbox
diff --git a/workers/agent-gateway/package-lock.json b/workers/agent-gateway/package-lock.json
index f42f7861e..4e55d1fef 100644
--- a/workers/agent-gateway/package-lock.json
+++ b/workers/agent-gateway/package-lock.json
@@ -8,8 +8,6 @@
"name": "@three-ws/agent-gateway",
"version": "0.1.0",
"dependencies": {
- "@slack/socket-mode": "^3.0.1",
- "@slack/web-api": "^8.1.1",
"discord.js": "^14.27.0",
"grammy": "^1.46.0"
},
@@ -195,68 +193,6 @@
"npm": ">=7.0.0"
}
},
- "node_modules/@slack/logger": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/@slack/logger/-/logger-5.0.0.tgz",
- "integrity": "sha512-VGXhmmgsAo9shdQYh4tFDndd+7nsgp0Y5h0UPDaUp8K359pBasI6YdkMqFW3mCOxLQkq09qj7o7cq6f3DuXcJQ==",
- "license": "MIT",
- "dependencies": {
- "@types/node": ">=20"
- },
- "engines": {
- "node": ">= 20",
- "npm": ">=9.6.4"
- }
- },
- "node_modules/@slack/socket-mode": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/@slack/socket-mode/-/socket-mode-3.0.1.tgz",
- "integrity": "sha512-7L4adgnJtQvQgo5cfIwqHG1QuR8mdZQ/WdMScNDp6uK644ZqnHDAa4rR+vZYfZFdJ5+obCqZQ66Dad8kcwJ4Jg==",
- "license": "MIT",
- "dependencies": {
- "@slack/logger": "^5.0.0",
- "@slack/web-api": "^8.0.0",
- "@types/node": ">=20",
- "eventemitter3": "^5"
- },
- "engines": {
- "node": ">=20",
- "npm": ">=9.6.4"
- },
- "peerDependencies": {
- "undici": "^7.0.0"
- }
- },
- "node_modules/@slack/types": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/@slack/types/-/types-3.1.0.tgz",
- "integrity": "sha512-bTzqrO3lxJ5iWedo1eJKNAs1koyEhaTwKLJUkD3KETnPeQvD978AAE4jvWstUws8Gbbc4JR6iYE6F7XjE8UGmw==",
- "license": "MIT",
- "engines": {
- "node": ">= 20",
- "npm": ">=9.6.4"
- }
- },
- "node_modules/@slack/web-api": {
- "version": "8.1.1",
- "resolved": "https://registry.npmjs.org/@slack/web-api/-/web-api-8.1.1.tgz",
- "integrity": "sha512-am/z/LLbEC7gNQp6FpaGT0l4XnWqcXetpwdgZHzS7Nbb96q9R9QwWA3lo0ZXGuAHDkct0MvFnouzuc2Y4XNmow==",
- "license": "MIT",
- "dependencies": {
- "@slack/logger": "^5.0.0",
- "@slack/types": "^3.1.0",
- "@types/node": ">=20",
- "@types/retry": "0.12.5",
- "eventemitter3": "^5.0.1",
- "p-queue": "^6.6.2",
- "p-retry": "^4.6.2",
- "retry": "^0.13.1"
- },
- "engines": {
- "node": ">= 20",
- "npm": ">=9.6.4"
- }
- },
"node_modules/@types/node": {
"version": "26.6.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.2.tgz",
@@ -266,12 +202,6 @@
"undici-types": "~8.9.0"
}
},
- "node_modules/@types/retry": {
- "version": "0.12.5",
- "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.5.tgz",
- "integrity": "sha512-3xSjTp3v03X/lSQLkczaN9UIEwJMoMCA1+Nb5HfbJEQWogdeQIyVtTvxPXDQjZ5zws8rFQfVfRdz03ARihPJgw==",
- "license": "MIT"
- },
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
@@ -371,12 +301,6 @@
"node": ">=6"
}
},
- "node_modules/eventemitter3": {
- "version": "5.0.4",
- "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
- "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
- "license": "MIT"
- },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -442,77 +366,6 @@
}
}
},
- "node_modules/p-finally": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
- "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==",
- "license": "MIT",
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/p-queue": {
- "version": "6.6.2",
- "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz",
- "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==",
- "license": "MIT",
- "dependencies": {
- "eventemitter3": "^4.0.4",
- "p-timeout": "^3.2.0"
- },
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/p-queue/node_modules/eventemitter3": {
- "version": "4.0.7",
- "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
- "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
- "license": "MIT"
- },
- "node_modules/p-retry": {
- "version": "4.6.2",
- "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
- "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
- "license": "MIT",
- "dependencies": {
- "@types/retry": "0.12.0",
- "retry": "^0.13.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/p-retry/node_modules/@types/retry": {
- "version": "0.12.0",
- "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
- "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
- "license": "MIT"
- },
- "node_modules/p-timeout": {
- "version": "3.2.0",
- "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz",
- "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==",
- "license": "MIT",
- "dependencies": {
- "p-finally": "^1.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/retry": {
- "version": "0.13.1",
- "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
- "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
- "license": "MIT",
- "engines": {
- "node": ">= 4"
- }
- },
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
@@ -531,16 +384,6 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
- "node_modules/undici": {
- "version": "7.30.0",
- "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz",
- "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==",
- "license": "MIT",
- "peer": true,
- "engines": {
- "node": ">=20.18.1"
- }
- },
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
diff --git a/workers/agent-gateway/package.json b/workers/agent-gateway/package.json
index 78a407c42..076bb3bde 100644
--- a/workers/agent-gateway/package.json
+++ b/workers/agent-gateway/package.json
@@ -2,21 +2,22 @@
"name": "@three-ws/agent-gateway",
"version": "0.1.0",
"private": true,
- "description": "One process that lets owners talk to their three.ws agents from Telegram, Discord, Slack, WhatsApp, Signal and SMS: drains the gateway inbox, runs each turn through the shared gateway core and delivers replies, previews and notifications.",
+ "description": "Drains the three.ws chat gateway inbox: runs every queued Telegram and Discord message, button press and notification through the shared gateway core and delivers the replies, previews and alerts. The adapter registry is where the next platform plugs in.",
"type": "module",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"dev": "node --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/index.js",
+ "test": "vitest run --config vitest.config.js",
+ "setup": "node --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/setup.js",
"register:discord": "node --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/setup.js discord-commands",
- "webhook:telegram": "node --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/setup.js telegram-webhook"
+ "webhook:telegram": "node --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/setup.js telegram-webhook",
+ "inbox": "node --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/setup.js inbox"
},
"engines": {
"node": ">=22"
},
"dependencies": {
- "@slack/socket-mode": "^3.0.1",
- "@slack/web-api": "^8.1.1",
"discord.js": "^14.27.0",
"grammy": "^1.46.0"
}
diff --git a/workers/agent-gateway/scripts/deploy-env.mjs b/workers/agent-gateway/scripts/deploy-env.mjs
new file mode 100644
index 000000000..2e7d6b82e
--- /dev/null
+++ b/workers/agent-gateway/scripts/deploy-env.mjs
@@ -0,0 +1,119 @@
+#!/usr/bin/env node
+// Derive the gateway's Cloud Run environment from the live three-ws-api service.
+//
+// The gateway runs the same agent turn as the web copilot (LLM chain, market
+// data, the agent's custodial wallet, the rate limiter), so it needs the same
+// configuration the API runs with, and it must never drift from it: the
+// agent-orders worker once pointed at stale copies of JWT_SECRET and
+// WALLET_ENCRYPTION_KEY and could not decrypt a single agent key. So instead of
+// a hand-kept list, every deploy copies the API's env: literals into an
+// --env-vars-file, Secret Manager references into --set-secrets, by reference,
+// so no secret value ever passes through this script or the build log.
+//
+// Two classes are left out on purpose:
+// - Cloud Run's reserved names (PORT, K_*).
+// - Platform signers: treasury, fee-payer, relayer and payout keys. A chat turn
+// signs only with the agent's own custodial key (decrypted with
+// WALLET_ENCRYPTION_KEY, which is kept). A process that reads messages from
+// the internet has no business holding the platform's money keys.
+//
+// Usage (Cloud Build runs exactly this; see ../cloudbuild.yaml):
+// gcloud run services describe three-ws-api --region us-central1 --format=json > api.json
+// node workers/agent-gateway/scripts/deploy-env.mjs api.json env.yaml secrets.txt [--set KEY=VALUE ...]
+// Add --print to see the names (never values) that would be mirrored and dropped.
+
+import { readFileSync, writeFileSync } from 'node:fs';
+
+const RESERVED = /^(PORT|K_SERVICE|K_REVISION|K_CONFIGURATION|CLOUD_RUN_JOB|CLOUD_RUN_EXECUTION|CLOUD_RUN_TASK_INDEX|CLOUD_RUN_TASK_ATTEMPT|CLOUD_RUN_TASK_COUNT)$/;
+const SIGNER_NAME = /(_SECRET_KEY_B64|_SECRET_BASE58|_PRIVATE_KEY|_KEYPAIR|_RELAYER_KEY|_PAYOUT_KEY|_TREASURY_SECRET|_DISTRIBUTOR_SECRET|_PAYER_SOLANA_SECRET|_WALLET_SECRET)$/;
+const SIGNER_SECRET = /^wallet-/;
+const KEEP = new Set(['WALLET_ENCRYPTION_KEY']);
+
+/** Why a variable is not mirrored, or null when it is. */
+export function exclusionReason(entry) {
+ if (RESERVED.test(entry.name)) return 'reserved by Cloud Run';
+ if (KEEP.has(entry.name)) return null;
+ const secret = entry.valueFrom?.secretKeyRef?.name || '';
+ if (SIGNER_SECRET.test(secret) || SIGNER_NAME.test(entry.name)) return 'platform signer';
+ return null;
+}
+
+/**
+ * @param {object} service `gcloud run services describe --format=json` output
+ * @param {Record<string,string>} [overrides] literals set on top (gateway knobs)
+ * @returns {{ env: Record<string,string>, secrets: Record<string,string>, excluded: Array<{name:string, reason:string}> }}
+ */
+export function buildDeployEnv(service, overrides = {}) {
+ const container = service?.spec?.template?.spec?.containers?.[0];
+ if (!container || !Array.isArray(container.env)) throw new Error('not a Cloud Run service description: spec.template.spec.containers[0].env is missing');
+ const env = {};
+ const secrets = {};
+ const excluded = [];
+ for (const entry of container.env) {
+ const reason = exclusionReason(entry);
+ if (reason) {
+ excluded.push({ name: entry.name, reason });
+ continue;
+ }
+ const ref = entry.valueFrom?.secretKeyRef;
+ if (ref) secrets[entry.name] = `${ref.name}:${ref.key || 'latest'}`;
+ else if (entry.value != null && entry.value !== '') env[entry.name] = String(entry.value);
+ }
+ for (const [k, v] of Object.entries(overrides)) {
+ delete secrets[k];
+ env[k] = String(v);
+ }
+ return { env, secrets, excluded };
+}
+
+/** YAML for --env-vars-file. Every value is a JSON string, which YAML reads verbatim. */
+export function envYaml(env) {
+ return `${Object.entries(env).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join('\n')}\n`;
+}
+
+/** The --set-secrets value: NAME=secret:version,... */
+export function secretsFlag(secrets) {
+ return Object.entries(secrets).map(([k, ref]) => `${k}=${ref}`).join(',');
+}
+
+function parseArgs(argv) {
+ const positional = [];
+ const overrides = {};
+ let print = false;
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i] === '--print') print = true;
+ else if (argv[i] === '--set') {
+ const pair = argv[++i] || '';
+ const eq = pair.indexOf('=');
+ if (eq <= 0) throw new Error(`--set needs KEY=VALUE, got "${pair}"`);
+ overrides[pair.slice(0, eq)] = pair.slice(eq + 1);
+ } else positional.push(argv[i]);
+ }
+ return { positional, overrides, print };
+}
+
+function main() {
+ const { positional: [input, envOut, secretsOut], overrides, print } = parseArgs(process.argv.slice(2));
+ if (!input) throw new Error('usage: deploy-env.mjs <service.json> [env.yaml secrets.txt] [--set KEY=VALUE ...] [--print]');
+ const { env, secrets, excluded } = buildDeployEnv(JSON.parse(readFileSync(input, 'utf8')), overrides);
+ if (envOut) writeFileSync(envOut, envYaml(env));
+ if (secretsOut) writeFileSync(secretsOut, secretsFlag(secrets));
+ const summary = `mirrored ${Object.keys(env).length} literals and ${Object.keys(secrets).length} secret references; left out ${excluded.length}`;
+ if (print) {
+ console.log(summary);
+ console.log(`literals: ${Object.keys(env).join(' ')}`);
+ console.log(`secrets: ${Object.keys(secrets).join(' ')}`);
+ for (const x of excluded) console.log(`left out ${x.name}: ${x.reason}`);
+ } else {
+ console.log(summary);
+ }
+}
+
+if (import.meta.url === `file://${process.argv[1]}`) {
+ try {
+ main();
+ } catch (e) {
+ console.error(`deploy-env: ${e.message}`);
+ process.exit(1);
+ }
+}
diff --git a/workers/agent-gateway/src/adapters/discord.js b/workers/agent-gateway/src/adapters/discord.js
new file mode 100644
index 000000000..8f5487de1
--- /dev/null
+++ b/workers/agent-gateway/src/adapters/discord.js
@@ -0,0 +1,331 @@
+// Discord adapter (discord.js). Two inbound paths land in the same inbox:
+//
+// interactions slash commands and the Approve / Cancel buttons. Discord
+// posts them to api/gateway/discord.js, which verifies the
+// Ed25519 signature, defers inside the three-second window and
+// queues the interaction. The worker answers through that
+// interaction's webhook: a command's first message replaces the
+// deferred "thinking...", later ones are followups, and a button
+// press edits the message the button sits on.
+// messages DMs to the bot and messages that mention it. These never
+// reach an HTTP endpoint; the worker holds a gateway connection
+// and queues each one as {kind:'discord_message'}. Discord
+// includes message content for DMs and mentions without the
+// privileged Message Content intent.
+//
+// Everything else (notifications, the preview sweeper, plain chat replies) is a
+// bot-token REST call to the channel.
+
+import {
+ Client, DiscordAPIError, Events, GatewayIntentBits, HTTPError, Partials, REST, RateLimitError, Routes,
+} from 'discord.js';
+import { chunkText, MAX_TEXT } from '../../../../api/_lib/gateway/format.js';
+import { parseActionId } from '../../../../api/_lib/gateway/approvals.js';
+import { DISCORD_INTERACTION } from '../../../../api/_lib/gateway/webhooks.js';
+import { PlatformError, isPermanentStatus } from '../errors.js';
+
+const PLATFORM = 'discord';
+const TEXT_LIMIT = MAX_TEXT.discord;
+const HARD_LIMIT = 2000;
+const EPHEMERAL = 64;
+// Interaction tokens live fifteen minutes; stop using one a minute early.
+const TOKEN_TTL_MS = 14 * 60 * 1000;
+const DISCORD_EPOCH = 1420070400000n;
+const STYLE = { primary: 1, secondary: 2, success: 3, danger: 4 };
+const NO_MENTIONS = { parse: [] };
+const IMAGE_EXT = /\.(png|jpe?g|webp|gif)(\?|$)/i;
+
+export function discordConfigured(env = process.env) {
+ const missing = ['DISCORD_BOT_TOKEN', 'DISCORD_APP_ID'].filter((k) => !env[k]);
+ return missing.length ? { ok: false, missing } : { ok: true };
+}
+
+/** When a snowflake (an interaction id) was minted, in epoch ms. */
+export function snowflakeTime(id) {
+ try {
+ return Number((BigInt(id) >> 22n) + DISCORD_EPOCH);
+ } catch {
+ return 0;
+ }
+}
+
+function tokenFresh(interactionId, now = Date.now()) {
+ const t = snowflakeTime(interactionId);
+ return t > 0 && now - t < TOKEN_TTL_MS;
+}
+
+/** Map a discord.js REST failure to a PlatformError the drain knows how to retry. */
+export function toPlatformError(err) {
+ if (err instanceof PlatformError) return err;
+ if (err instanceof DiscordAPIError) {
+ return new PlatformError(PLATFORM, err.message, { status: err.status, code: err.code, permanent: isPermanentStatus(err.status), cause: err });
+ }
+ if (err instanceof RateLimitError) return new PlatformError(PLATFORM, 'rate limited', { status: 429, retryAfterMs: err.retryAfter, cause: err });
+ if (err instanceof HTTPError) return new PlatformError(PLATFORM, err.message, { status: err.status, permanent: isPermanentStatus(err.status), cause: err });
+ return err;
+}
+
+async function call(fn) {
+ try {
+ return await fn();
+ } catch (e) {
+ throw toPlatformError(e);
+ }
+}
+
+/** A typed "/cmd args" in a DM or mention, for users who did not pick the slash command. */
+export function parseTypedCommand(text) {
+ const m = /^\/([a-z0-9_-]{1,32})(?:\s+([\s\S]*))?$/i.exec(String(text || '').trim());
+ if (!m) return null;
+ if (m[1].toLowerCase() === 'three') {
+ const rest = (m[2] || '').trim();
+ const sub = /^([a-z0-9_-]{1,32})(?:\s+([\s\S]*))?$/i.exec(rest);
+ return sub ? { command: sub[1].toLowerCase(), args: (sub[2] || '').trim() } : { command: 'help', args: '' };
+ }
+ return { command: m[1].toLowerCase(), args: (m[2] || '').trim() };
+}
+
+function componentRows(choices) {
+ if (!choices.length) return [];
+ return [{
+ type: 1,
+ components: choices.slice(0, 5).map((c) => ({ type: 2, style: STYLE[c.style] || STYLE.secondary, label: String(c.label).slice(0, 80), custom_id: String(c.id).slice(0, 100) })),
+ }];
+}
+
+function userOf(interaction) {
+ return interaction.member?.user || interaction.user || null;
+}
+
+function commandOf(data) {
+ let name = String(data?.name || '').toLowerCase();
+ let options = Array.isArray(data?.options) ? data.options : [];
+ if (name === 'three') {
+ const sub = options[0];
+ name = String(sub?.name || 'help').toLowerCase();
+ options = Array.isArray(sub?.options) ? sub.options : [];
+ }
+ const args = options.map((o) => (o?.value == null ? '' : String(o.value))).join(' ').trim();
+ return { command: name, args };
+}
+
+/**
+ * @param {object} [opts]
+ * @param {Record<string,string|undefined>} [opts.env]
+ * @param {{ get:Function, post:Function, patch:Function, put:Function, delete:Function }} [opts.rest]
+ * a discord.js REST client (tests pass one that answers at the platform boundary)
+ * @param {typeof fetch} [opts.fetch] downloads attachments
+ * @param {object} [opts.config] worker config (discordGateway)
+ * @param {object} [opts.log]
+ * @param {() => number} [opts.now]
+ */
+export function createDiscordAdapter({ env = process.env, rest = null, fetch: fetchImpl = globalThis.fetch, config = {}, log = null, now = Date.now } = {}) {
+ const token = env.DISCORD_BOT_TOKEN;
+ const appId = env.DISCORD_APP_ID;
+ const api = rest || new REST({ version: '10' }).setToken(token);
+ let client = null;
+
+ async function fetchAttachment(att) {
+ const r = await fetchImpl(att.url, { signal: AbortSignal.timeout(20_000) });
+ if (!r.ok) throw new PlatformError(PLATFORM, `attachment download ${r.status}`, { status: r.status, permanent: isPermanentStatus(r.status) });
+ return { buffer: Buffer.from(await r.arrayBuffer()), mimeType: att.content_type || r.headers.get('content-type') || 'application/octet-stream' };
+ }
+
+ function interactionEvent(i) {
+ const user = userOf(i);
+ if (!user?.id || !i.channel_id) return null;
+ const base = {
+ platform: PLATFORM,
+ chatId: String(i.channel_id),
+ chatType: i.guild_id ? 'guild' : 'dm',
+ chatTitle: i.channel?.name || null,
+ userId: String(user.id),
+ username: user.username || null,
+ interaction: { id: String(i.id), token: i.token, applicationId: String(i.application_id || appId), type: i.type, messageId: i.message?.id ? String(i.message.id) : null },
+ };
+ if (i.type === DISCORD_INTERACTION.APPLICATION_COMMAND) return { ...base, ...commandOf(i.data) };
+ if (i.type === DISCORD_INTERACTION.MESSAGE_COMPONENT) {
+ const action = parseActionId(i.data?.custom_id);
+ if (!action || !i.message?.id) return null;
+ return { ...base, action, messageRef: { kind: 'channel', channelId: String(i.channel_id), messageId: String(i.message.id) } };
+ }
+ return null;
+ }
+
+ function messageEvent(payload) {
+ const m = payload.message;
+ if (!m?.author?.id || m.author.bot || !m.channel_id) return null;
+ const base = {
+ platform: PLATFORM,
+ chatId: String(m.channel_id),
+ chatType: m.guild_id ? 'guild' : 'dm',
+ chatTitle: payload.channel_name || null,
+ userId: String(m.author.id),
+ username: m.author.username || null,
+ };
+ const botId = payload.botUserId ? String(payload.botUserId) : null;
+ const text = String(m.content || '').replace(botId ? new RegExp(`<@!?${botId}>`, 'g') : /$^/, '').trim();
+ const attachments = Array.isArray(m.attachments) ? m.attachments : [];
+ const audio = attachments.find((a) => String(a.content_type || '').startsWith('audio/'));
+ if (audio) return { ...base, voice: { fetch: () => fetchAttachment(audio) } };
+ const image = attachments.find((a) => String(a.content_type || '').startsWith('image/'));
+ if (image) return { ...base, photo: { fetch: () => fetchAttachment(image), caption: text } };
+ if (!text) return null;
+ const cmd = parseTypedCommand(text);
+ return cmd ? { ...base, ...cmd } : { ...base, text };
+ }
+
+ /** @returns {object|null} a GatewayEvent, or null for deliveries the gateway does not answer */
+ function normalize(payload) {
+ if (!payload || typeof payload !== 'object') return null;
+ if (payload.kind === 'discord_message') return messageEvent(payload);
+ if (payload.type === DISCORD_INTERACTION.APPLICATION_COMMAND || payload.type === DISCORD_INTERACTION.MESSAGE_COMPONENT) return interactionEvent(payload);
+ return null;
+ }
+
+ function channelRef(msg) {
+ return { kind: 'channel', channelId: String(msg.channel_id), messageId: String(msg.id) };
+ }
+
+ /**
+ * One gateway per event. It holds the interaction being answered, if any, and
+ * whether the deferred original response has been filled yet.
+ */
+ function gateway(event) {
+ const interaction = event?.interaction || null;
+ let originalFilled = false;
+ const live = () => interaction && tokenFresh(interaction.id, now());
+
+ async function post(chatId, body, files) {
+ const payload = { ...body, allowed_mentions: NO_MENTIONS };
+ if (live() && String(chatId) === String(event.chatId)) {
+ const { applicationId: app, token: tok } = interaction;
+ const opts = { body: payload, files, auth: false };
+ const fillOriginal = interaction.type === DISCORD_INTERACTION.APPLICATION_COMMAND && !originalFilled;
+ const msg = await call(() => (fillOriginal
+ ? api.patch(Routes.webhookMessage(app, tok, '@original'), opts)
+ : api.post(Routes.webhook(app, tok), opts)));
+ if (fillOriginal) originalFilled = true;
+ return { kind: 'interaction', applicationId: app, token: tok, interactionId: interaction.id, channelId: String(msg.channel_id || chatId), messageId: String(msg.id) };
+ }
+ const msg = await call(() => api.post(Routes.channelMessages(chatId), { body: payload, files }));
+ return channelRef(msg);
+ }
+
+ async function edit(ref, body) {
+ const payload = { ...body, allowed_mentions: NO_MENTIONS };
+ // The press being answered sits on this message: its own token edits it.
+ if (live() && interaction.type === DISCORD_INTERACTION.MESSAGE_COMPONENT && String(ref.messageId) === interaction.messageId) {
+ return call(() => api.patch(Routes.webhookMessage(interaction.applicationId, interaction.token, '@original'), { body: payload, auth: false }));
+ }
+ if (ref.kind === 'interaction' && tokenFresh(ref.interactionId, now())) {
+ try {
+ return await call(() => api.patch(Routes.webhookMessage(ref.applicationId, ref.token, ref.messageId), { body: payload, auth: false }));
+ } catch (e) {
+ if (!(e instanceof PlatformError) || !e.permanent) throw e;
+ }
+ }
+ return call(() => api.patch(Routes.channelMessage(ref.channelId, ref.messageId), { body: payload }));
+ }
+
+ return {
+ platform: PLATFORM,
+ buttons: true,
+ canEdit: true,
+ async sendText(chatId, text) {
+ let ref = null;
+ for (const part of chunkText(text, TEXT_LIMIT)) ref = await post(chatId, { content: part });
+ return ref;
+ },
+ sendChoice(chatId, text, choices) {
+ return post(chatId, { content: String(text).slice(0, HARD_LIMIT), components: componentRows(choices || []) });
+ },
+ async editMessage(ref, text, opts = {}) {
+ const body = { content: String(text).slice(0, HARD_LIMIT) };
+ if (Array.isArray(opts.choices)) body.components = componentRows(opts.choices);
+ await edit(ref, body);
+ },
+ sendMedia(chatId, media) {
+ const caption = media.caption ? String(media.caption).slice(0, HARD_LIMIT) : undefined;
+ const image = media.kind ? media.kind === 'image' : (IMAGE_EXT.test(media.url) || /\/api\/render\//.test(media.url));
+ return image
+ ? post(chatId, { content: caption, embeds: [{ image: { url: media.url } }] })
+ : post(chatId, { content: [caption, media.url].filter(Boolean).join('\n') });
+ },
+ sendVoice(chatId, clip) {
+ return post(chatId, { content: '' }, [{ name: clip.filename || 'reply.ogg', data: clip.buffer, contentType: clip.mimeType || 'audio/ogg' }]);
+ },
+ async typing(chatId) {
+ // A deferred command already shows "thinking..."; typing into a
+ // channel the bot is not a member of would only be refused.
+ if (live()) return;
+ await call(() => api.post(Routes.channelTyping(chatId)));
+ },
+ async ackAction(_event, text) {
+ if (!text || !live() || interaction.type !== DISCORD_INTERACTION.MESSAGE_COMPONENT) return;
+ await call(() => api.post(Routes.webhook(interaction.applicationId, interaction.token), {
+ body: { content: String(text).slice(0, HARD_LIMIT), flags: EPHEMERAL, allowed_mentions: NO_MENTIONS },
+ auth: false,
+ }));
+ },
+ /** Whether the deferred "thinking..." still needs resolving. */
+ pendingOriginal() {
+ return Boolean(live() && interaction.type === DISCORD_INTERACTION.APPLICATION_COMMAND && !originalFilled);
+ },
+ async clearOriginal() {
+ await call(() => api.delete(Routes.webhookMessage(interaction.applicationId, interaction.token, '@original'), { auth: false }));
+ originalFilled = true;
+ },
+ };
+ }
+
+ return {
+ platform: PLATFORM,
+ normalize,
+ gateway,
+ /** A command that produced no message would leave "thinking..." forever; remove it. */
+ async finish(_event, gw) {
+ if (typeof gw.pendingOriginal === 'function' && gw.pendingOriginal()) await gw.clearOriginal().catch(() => {});
+ },
+ async start({ enqueue }) {
+ if (config.discordGateway === false) return;
+ client = new Client({
+ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages],
+ partials: [Partials.Channel],
+ });
+ client.on(Events.MessageCreate, (m) => {
+ if (m.author?.bot) return;
+ const direct = !m.guildId;
+ if (!direct && !m.mentions?.users?.has(client.user.id)) return;
+ enqueue({
+ platform: PLATFORM,
+ dedupeKey: `message:${m.id}`,
+ chatKey: `${PLATFORM}:${m.channelId}`,
+ payload: {
+ kind: 'discord_message',
+ botUserId: client.user.id,
+ channel_name: m.channel?.name || null,
+ message: {
+ id: m.id,
+ channel_id: m.channelId,
+ guild_id: m.guildId || null,
+ content: m.content || '',
+ author: { id: m.author.id, username: m.author.username, bot: Boolean(m.author.bot) },
+ attachments: [...m.attachments.values()].map((a) => ({ url: a.url, content_type: a.contentType || null, size: a.size, filename: a.name })),
+ },
+ },
+ }).catch((e) => log?.error('discord message not queued', { error: e.message }));
+ });
+ client.on(Events.Error, (e) => log?.warn('discord gateway error', { error: e.message }));
+ client.once(Events.ClientReady, (c) => log?.info('discord gateway connected', { bot: c.user.tag }));
+ await client.login(token);
+ },
+ async stop() {
+ if (client) await client.destroy().catch(() => {});
+ client = null;
+ },
+ describe() {
+ return { app: appId, gateway: client?.isReady?.() ? 'connected' : (config.discordGateway === false ? 'off' : 'connecting') };
+ },
+ };
+}
diff --git a/workers/agent-gateway/src/adapters/index.js b/workers/agent-gateway/src/adapters/index.js
new file mode 100644
index 000000000..3a96ddae7
--- /dev/null
+++ b/workers/agent-gateway/src/adapters/index.js
@@ -0,0 +1,57 @@
+// The adapter registry: every chat platform the worker can drain.
+//
+// An adapter is a plain object:
+//
+// platform the gateway_inbox.platform value it owns
+// normalize(payload) the queued payload -> a GatewayEvent (api/_lib/gateway/core.js),
+// or null for a delivery nobody needs to answer
+// gateway(event) the send surface for one event (event is null for
+// notifications and the preview sweeper): sendText,
+// sendChoice, editMessage, sendMedia, typing, ackAction,
+// and sendVoice where the platform plays audio; plus the
+// capability flags `buttons` and `canEdit`
+// handle(event, gw) optional: its own turn instead of the shared core, for a
+// platform whose conversations are not paired chats
+// finish(event, gw) optional: tidy up after the handler (Discord resolves an
+// unanswered "thinking...")
+// start({enqueue}) optional: open inbound listeners that queue into the inbox
+// stop() optional: close them
+// describe() optional: a small status object for /healthz
+//
+// Adding a platform is one entry in FACTORIES plus its file; the drain loop
+// (src/drain.js) never changes. Each factory also exports a `configured(env)`
+// check naming the env vars it needs, so a worker without a platform's
+// credentials boots without that adapter and says which variable is missing.
+
+import { createTelegramAdapter, telegramConfigured } from './telegram.js';
+import { createDiscordAdapter, discordConfigured } from './discord.js';
+
+export const FACTORIES = {
+ telegram: { create: createTelegramAdapter, configured: telegramConfigured },
+ discord: { create: createDiscordAdapter, configured: discordConfigured },
+};
+
+/**
+ * Build every adapter that is both wanted (config.platforms, default all) and
+ * configured (its credentials are present).
+ * @returns {{ adapters: Map<string, object>, skipped: Array<{ platform:string, missing:string[] }> }}
+ */
+export function loadAdapters({ env = process.env, config = {}, log = null, factories = FACTORIES, overrides = {} } = {}) {
+ const adapters = new Map();
+ const skipped = [];
+ const wanted = config.platforms || Object.keys(factories);
+ for (const platform of wanted) {
+ const f = factories[platform];
+ if (!f) {
+ skipped.push({ platform, missing: [], reason: 'unknown platform' });
+ continue;
+ }
+ const check = f.configured(env);
+ if (!check.ok) {
+ skipped.push({ platform, missing: check.missing });
+ continue;
+ }
+ adapters.set(platform, f.create({ env, config, log, ...(overrides[platform] || {}) }));
+ }
+ return { adapters, skipped };
+}
diff --git a/workers/agent-gateway/src/adapters/telegram.js b/workers/agent-gateway/src/adapters/telegram.js
new file mode 100644
index 000000000..e68bb799d
--- /dev/null
+++ b/workers/agent-gateway/src/adapters/telegram.js
@@ -0,0 +1,264 @@
+// Telegram adapter (grammY). Turns a queued Bot API update into a gateway event
+// and implements the gateway send surface over the Bot API.
+//
+// Production delivery is the webhook: api/gateway/telegram.js verifies the
+// secret header and queues the raw update in gateway_inbox. For local
+// development without a public URL, GATEWAY_TELEGRAM_POLLING=1 pulls updates
+// with getUpdates and queues them the same way, so both paths drain through the
+// same loop. Polling refuses to start while a webhook is set, because
+// getUpdates only works after deleting it and that would cut production off.
+
+import { Api, Bot, GrammyError, HttpError, InputFile } from 'grammy';
+import { chunkText, MAX_TEXT } from '../../../../api/_lib/gateway/format.js';
+import { parseActionId } from '../../../../api/_lib/gateway/approvals.js';
+import { telegramInboxKeys } from '../../../../api/_lib/gateway/webhooks.js';
+import { PlatformError, isPermanentStatus } from '../errors.js';
+
+const PLATFORM = 'telegram';
+const TEXT_LIMIT = MAX_TEXT.telegram;
+const HARD_LIMIT = 4096;
+const CAPTION_LIMIT = 1024;
+const FILE_API = 'https://api.telegram.org/file';
+const ALLOWED_UPDATES = ['message', 'callback_query'];
+const IMAGE_EXT = /\.(png|jpe?g|webp|gif)(\?|$)/i;
+const VIDEO_EXT = /\.(mp4|mov|webm)(\?|$)/i;
+
+export function telegramConfigured(env = process.env) {
+ return env.TELEGRAM_BOT_TOKEN ? { ok: true } : { ok: false, missing: ['TELEGRAM_BOT_TOKEN'] };
+}
+
+/** Map a grammY failure to a PlatformError the drain knows how to retry. */
+export function toPlatformError(err) {
+ if (err instanceof PlatformError) return err;
+ if (err instanceof GrammyError) {
+ const retryAfter = Number(err.parameters?.retry_after);
+ return new PlatformError(PLATFORM, err.description || err.message, {
+ status: err.error_code,
+ code: err.error_code,
+ permanent: isPermanentStatus(err.error_code),
+ retryAfterMs: Number.isFinite(retryAfter) ? retryAfter * 1000 : null,
+ cause: err,
+ });
+ }
+ if (err instanceof HttpError) return new PlatformError(PLATFORM, `network: ${err.message}`, { cause: err });
+ return err;
+}
+
+async function call(fn) {
+ try {
+ return await fn();
+ } catch (e) {
+ throw toPlatformError(e);
+ }
+}
+
+/**
+ * A command as Telegram delivers it: "/cmd", "/cmd args" or "/cmd@bot args".
+ * Returns null for ordinary text and for a command addressed to another bot.
+ */
+export function parseTelegramCommand(text, botUsername = null) {
+ const m = /^\/([A-Za-z0-9_]{1,32})(?:@([A-Za-z0-9_]{3,64}))?(?:\s+([\s\S]*))?$/.exec(String(text || '').trim());
+ if (!m) return null;
+ if (m[2] && botUsername && m[2].toLowerCase() !== String(botUsername).toLowerCase()) return { foreign: true };
+ return { command: m[1].toLowerCase(), args: (m[3] || '').trim() };
+}
+
+function keyboard(choices) {
+ return { inline_keyboard: choices.length ? [choices.map((c) => ({ text: String(c.label).slice(0, 64), callback_data: String(c.id).slice(0, 64) }))] : [] };
+}
+
+function refOf(msg) {
+ return { chatId: String(msg.chat.id), messageId: msg.message_id };
+}
+
+function mediaKind(media) {
+ if (media.kind) return media.kind;
+ if (IMAGE_EXT.test(media.url) || /\/api\/render\//.test(media.url)) return 'image';
+ if (VIDEO_EXT.test(media.url)) return 'video';
+ return 'document';
+}
+
+/**
+ * @param {object} [opts]
+ * @param {Record<string,string|undefined>} [opts.env]
+ * @param {Api} [opts.api] a grammY Api (tests pass one whose transformer answers at the platform boundary)
+ * @param {typeof fetch} [opts.fetch] downloads voice notes and photos from the file endpoint
+ * @param {object} [opts.config] worker config (telegramPolling)
+ * @param {object} [opts.log]
+ */
+export function createTelegramAdapter({ env = process.env, api = null, fetch: fetchImpl = globalThis.fetch, config = {}, log = null } = {}) {
+ const token = env.TELEGRAM_BOT_TOKEN;
+ const client = api || new Api(token);
+ let botUsername = env.TELEGRAM_BOT_USERNAME ? env.TELEGRAM_BOT_USERNAME.replace(/^@/, '') : null;
+ let poller = null;
+
+ async function download(fileId, fallbackMime) {
+ const file = await call(() => client.getFile(fileId));
+ if (!file?.file_path) throw new PlatformError(PLATFORM, 'file has no download path', { permanent: true });
+ const r = await fetchImpl(`${FILE_API}/bot${token}/${file.file_path}`, { signal: AbortSignal.timeout(20_000) });
+ if (!r.ok) throw new PlatformError(PLATFORM, `file download ${r.status}`, { status: r.status, permanent: isPermanentStatus(r.status) });
+ return { buffer: Buffer.from(await r.arrayBuffer()), mimeType: r.headers.get('content-type')?.startsWith('application/octet') ? fallbackMime : (r.headers.get('content-type') || fallbackMime) };
+ }
+
+ function normalizeCallback(q) {
+ const msg = q.message;
+ if (!msg?.chat || !q.from) return null;
+ const action = parseActionId(q.data);
+ if (!action) return null;
+ return {
+ platform: PLATFORM,
+ chatId: String(msg.chat.id),
+ chatType: msg.chat.type || null,
+ chatTitle: msg.chat.title || msg.chat.username || null,
+ userId: String(q.from.id),
+ username: q.from.username || null,
+ action,
+ messageRef: refOf(msg),
+ callbackQueryId: q.id,
+ };
+ }
+
+ function normalizeMessage(m) {
+ if (!m?.chat || !m.from || m.from.is_bot) return null;
+ const base = {
+ platform: PLATFORM,
+ chatId: String(m.chat.id),
+ chatType: m.chat.type || null,
+ chatTitle: m.chat.title || m.chat.username || null,
+ userId: String(m.from.id),
+ username: m.from.username || null,
+ };
+ if (typeof m.text === 'string') {
+ const cmd = parseTelegramCommand(m.text, botUsername);
+ if (cmd?.foreign) return null;
+ if (cmd) return { ...base, command: cmd.command, args: cmd.args };
+ const mention = botUsername ? new RegExp(`@${botUsername}\\b`, 'ig') : null;
+ const text = (mention ? m.text.replace(mention, '') : m.text).trim();
+ return text ? { ...base, text } : null;
+ }
+ const audio = m.voice || m.audio;
+ if (audio?.file_id) {
+ const mime = audio.mime_type || 'audio/ogg';
+ return { ...base, voice: { fetch: () => download(audio.file_id, mime) } };
+ }
+ const photo = Array.isArray(m.photo) && m.photo.length ? m.photo[m.photo.length - 1] : null;
+ const imageDoc = m.document?.mime_type?.startsWith('image/') ? m.document : null;
+ if (photo || imageDoc) {
+ const fileId = (photo || imageDoc).file_id;
+ const mime = imageDoc?.mime_type || 'image/jpeg';
+ return { ...base, photo: { fetch: () => download(fileId, mime), caption: m.caption || '' } };
+ }
+ return null;
+ }
+
+ /** @returns {object|null} a GatewayEvent, or null for updates the gateway does not answer */
+ function normalize(update) {
+ if (!update || typeof update !== 'object') return null;
+ if (update.callback_query) return normalizeCallback(update.callback_query);
+ if (update.message) return normalizeMessage(update.message);
+ return null;
+ }
+
+ async function sendText(chatId, text) {
+ let ref = null;
+ for (const part of chunkText(text, TEXT_LIMIT)) {
+ const msg = await call(() => client.sendMessage(chatId, part, { link_preview_options: { is_disabled: true } }));
+ ref = refOf(msg);
+ }
+ return ref;
+ }
+
+ /** One gateway per event; Telegram needs no per-event state beyond the callback id. */
+ function gateway() {
+ return {
+ platform: PLATFORM,
+ buttons: true,
+ canEdit: true,
+ sendText,
+ async sendChoice(chatId, text, choices) {
+ const msg = await call(() => client.sendMessage(chatId, String(text).slice(0, HARD_LIMIT), {
+ reply_markup: keyboard(choices || []),
+ link_preview_options: { is_disabled: true },
+ }));
+ return refOf(msg);
+ },
+ async editMessage(ref, text, opts = {}) {
+ const other = { link_preview_options: { is_disabled: true } };
+ if (Array.isArray(opts.choices)) other.reply_markup = keyboard(opts.choices);
+ try {
+ await call(() => client.editMessageText(ref.chatId, ref.messageId, String(text).slice(0, HARD_LIMIT), other));
+ } catch (e) {
+ // Editing to identical text is a no-op Telegram reports as an error.
+ if (e instanceof PlatformError && /message is not modified/i.test(e.message)) return;
+ throw e;
+ }
+ },
+ async sendMedia(chatId, media) {
+ const caption = media.caption ? String(media.caption).slice(0, CAPTION_LIMIT) : undefined;
+ const kind = mediaKind(media);
+ const msg = await call(() => (kind === 'image'
+ ? client.sendPhoto(chatId, media.url, { caption })
+ : kind === 'video'
+ ? client.sendVideo(chatId, media.url, { caption })
+ : client.sendDocument(chatId, media.url, { caption })));
+ return refOf(msg);
+ },
+ async sendVoice(chatId, clip) {
+ const msg = await call(() => client.sendVoice(chatId, new InputFile(clip.buffer, clip.filename || 'reply.ogg')));
+ return refOf(msg);
+ },
+ async typing(chatId) {
+ await call(() => client.sendChatAction(chatId, 'typing'));
+ },
+ async ackAction(event, text) {
+ if (!event?.callbackQueryId) return;
+ try {
+ await call(() => client.answerCallbackQuery(event.callbackQueryId, text ? { text: String(text).slice(0, 200) } : {}));
+ } catch (e) {
+ // A press answered late ("query is too old") changes nothing for the
+ // owner; the preview message itself carries the outcome.
+ if (e instanceof PlatformError && e.status === 400) return;
+ throw e;
+ }
+ },
+ };
+ }
+
+ return {
+ platform: PLATFORM,
+ normalize,
+ gateway,
+ async start({ enqueue }) {
+ if (!botUsername) {
+ const me = await call(() => client.getMe()).catch((e) => {
+ log?.warn('telegram getMe failed; commands addressed to other bots cannot be told apart', { error: e.message });
+ return null;
+ });
+ botUsername = me?.username || null;
+ }
+ if (!config.telegramPolling) return;
+ const info = await call(() => client.getWebhookInfo());
+ if (info?.url) {
+ log?.error('telegram polling refused: a webhook is set, and polling would delete it', { webhookHost: new URL(info.url).host });
+ return;
+ }
+ poller = new Bot(token);
+ poller.use(async (ctx) => {
+ const keys = telegramInboxKeys(ctx.update);
+ if (!keys) return;
+ await enqueue({ platform: PLATFORM, ...keys, payload: ctx.update });
+ });
+ poller.catch((e) => log?.warn('telegram polling update failed', { error: e.message }));
+ poller.start({ allowed_updates: ALLOWED_UPDATES, drop_pending_updates: false })
+ .catch((e) => log?.error('telegram polling stopped', { error: e.message }));
+ log?.info('telegram polling started', { bot: botUsername });
+ },
+ async stop() {
+ if (poller) await poller.stop().catch(() => {});
+ poller = null;
+ },
+ describe() {
+ return { bot: botUsername, mode: poller ? 'polling' : 'webhook' };
+ },
+ };
+}
diff --git a/workers/agent-gateway/src/config.js b/workers/agent-gateway/src/config.js
new file mode 100644
index 000000000..3a35da5a7
--- /dev/null
+++ b/workers/agent-gateway/src/config.js
@@ -0,0 +1,55 @@
+// Worker configuration, read once at boot from the environment. Every knob has
+// a production default, so the Cloud Run service needs only credentials.
+
+function int(env, name, fallback, { min = 0, max = Number.MAX_SAFE_INTEGER } = {}) {
+ const raw = env[name];
+ if (raw == null || raw === '') return fallback;
+ const n = Number(raw);
+ if (!Number.isFinite(n)) throw new Error(`${name} must be a number, got "${raw}"`);
+ return Math.min(max, Math.max(min, Math.floor(n)));
+}
+
+function list(env, name) {
+ const raw = String(env[name] || '').trim();
+ return raw ? raw.split(',').map((s) => s.trim()).filter(Boolean) : null;
+}
+
+/**
+ * @typedef {object} GatewayConfig
+ * @property {number} port health endpoint port (Cloud Run injects PORT)
+ * @property {number} concurrency inbox rows processed at once (one per chat)
+ * @property {number} pollMs idle wait between claims when the inbox is empty
+ * @property {number} leaseSeconds how long a claimed row is held before another worker may take it
+ * @property {number} maxAttempts attempts before a row is dead-lettered
+ * @property {number} backoffBaseMs first retry delay; doubles per attempt
+ * @property {number} backoffMaxMs ceiling on a single retry delay
+ * @property {number} turnTimeoutMs a row still running after this is failed and its lease released
+ * @property {number} sweepMs preview expiry sweep and inbox prune interval
+ * @property {number} pruneKeepDays finished rows older than this are deleted
+ * @property {number} shutdownGraceMs how long SIGTERM waits for in-flight rows
+ * @property {string[]|null} platforms restrict the adapters that load (default: every configured one)
+ * @property {string[]|null} chatKeys drain only these chats (debugging one chat)
+ * @property {boolean} telegramPolling pull Telegram updates with getUpdates instead of the webhook (local development)
+ * @property {boolean} discordGateway hold a Discord gateway connection for DMs and mentions
+ */
+
+/** @returns {GatewayConfig} */
+export function loadConfig(env = process.env) {
+ return {
+ port: int(env, 'PORT', 8080, { min: 1, max: 65535 }),
+ concurrency: int(env, 'GATEWAY_CONCURRENCY', 8, { min: 1, max: 64 }),
+ pollMs: int(env, 'GATEWAY_POLL_MS', 1500, { min: 100 }),
+ leaseSeconds: int(env, 'GATEWAY_LEASE_SECONDS', 90, { min: 15 }),
+ maxAttempts: int(env, 'GATEWAY_MAX_ATTEMPTS', 5, { min: 1, max: 20 }),
+ backoffBaseMs: int(env, 'GATEWAY_BACKOFF_BASE_MS', 5000, { min: 0 }),
+ backoffMaxMs: int(env, 'GATEWAY_BACKOFF_MAX_MS', 300_000, { min: 0 }),
+ turnTimeoutMs: int(env, 'GATEWAY_TURN_TIMEOUT_MS', 300_000, { min: 1000 }),
+ sweepMs: int(env, 'GATEWAY_SWEEP_MS', 60_000, { min: 1000 }),
+ pruneKeepDays: int(env, 'GATEWAY_PRUNE_KEEP_DAYS', 7, { min: 1 }),
+ shutdownGraceMs: int(env, 'GATEWAY_SHUTDOWN_GRACE_MS', 8000, { min: 0 }),
+ platforms: list(env, 'GATEWAY_PLATFORMS'),
+ chatKeys: list(env, 'GATEWAY_CHAT_KEYS'),
+ telegramPolling: env.GATEWAY_TELEGRAM_POLLING === '1',
+ discordGateway: env.GATEWAY_DISCORD_GATEWAY !== '0',
+ };
+}
diff --git a/workers/agent-gateway/src/drain.js b/workers/agent-gateway/src/drain.js
new file mode 100644
index 000000000..659d06ec4
--- /dev/null
+++ b/workers/agent-gateway/src/drain.js
@@ -0,0 +1,331 @@
+// The inbox drain: claims gateway_inbox rows with a lease, runs each through its
+// platform adapter, and acknowledges, retries with backoff, or dead-letters it.
+//
+// Ordering and exclusivity come from the claim itself (api/_lib/gateway/store.js
+// claimInbox): at most one open row per chat is ever handed out, so a chat's
+// replies leave in the order its messages arrived, and concurrency here is
+// concurrency across chats. While a row runs, its lease is renewed so a long
+// agent turn is never reclaimed and answered twice.
+//
+// The loop knows nothing about any platform. It asks the adapter registry for
+// the adapter named by the row's `platform`, and the adapter supplies
+// normalize(payload) -> event, gateway(event) -> the send surface, and
+// optionally its own handle(event, gw); the default handler is the shared
+// gateway core (handleEvent). A new platform is a new adapter in
+// src/adapters/index.js, never a change here.
+
+import { handleEvent } from '../../../api/_lib/gateway/core.js';
+import { previewText } from '../../../api/_lib/gateway/conversation.js';
+import * as inboxStore from '../../../api/_lib/gateway/store.js';
+import { classifyFailure, errorSummary } from './errors.js';
+import { log as defaultLog } from './log.js';
+
+// Methods whose success means the chat saw something. typing and ackAction are
+// transient signals and do not count.
+const DELIVERY_METHODS = ['sendText', 'sendChoice', 'sendMedia', 'sendVoice', 'editMessage'];
+const EXPIRED_PREVIEW_LINE = 'Expired. Ask your agent again for a fresh quote.';
+const APOLOGY = 'Something went wrong on our side while answering that. Please send it again in a minute.';
+const PRUNE_EVERY_MS = 60 * 60 * 1000;
+
+class TurnTimeout extends Error {
+ constructor(ms) {
+ super(`row still running after ${ms}ms`);
+ this.code = 'turn_timeout';
+ }
+}
+
+/**
+ * Wrap an adapter's gateway so every successful delivery is counted. The
+ * wrapper keeps the original's shape: a method the adapter does not implement
+ * (sendVoice on a platform without audio) stays absent, because the core
+ * checks for it with typeof.
+ */
+export function trackDeliveries(gw) {
+ const counter = { delivered: 0 };
+ const wrapped = { ...gw };
+ for (const name of DELIVERY_METHODS) {
+ if (typeof gw[name] !== 'function') continue;
+ wrapped[name] = async (...args) => {
+ const out = await gw[name](...args);
+ counter.delivered += 1;
+ return out;
+ };
+ }
+ for (const name of Object.keys(gw)) {
+ if (typeof gw[name] === 'function' && !DELIVERY_METHODS.includes(name)) wrapped[name] = gw[name].bind(gw);
+ }
+ return { gw: wrapped, counter };
+}
+
+function withTimeout(promise, ms) {
+ let timer;
+ const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new TurnTimeout(ms)), ms); });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
+
+/**
+ * @param {object} opts
+ * @param {Map<string, object>} opts.adapters platform -> adapter (src/adapters/index.js)
+ * @param {import('./config.js').GatewayConfig} opts.config
+ * @param {object} [opts.store] the inbox store (defaults to api/_lib/gateway/store.js)
+ * @param {(event:object, gw:object) => Promise<unknown>} [opts.defaultHandler] defaults to the gateway core
+ * @param {object} [opts.log]
+ */
+export function createDrainer({ adapters, config, store = inboxStore, defaultHandler = handleEvent, log = defaultLog }) {
+ const platforms = [...adapters.keys()];
+ const inflight = new Map();
+ const stats = {
+ startedAt: new Date().toISOString(),
+ lastLoopAt: 0,
+ lastClaimOkAt: 0,
+ lastClaimError: null,
+ claimed: 0,
+ completed: 0,
+ ignored: 0,
+ retried: 0,
+ deadLettered: 0,
+ notificationsSent: 0,
+ notificationsSkipped: 0,
+ previewsExpired: 0,
+ };
+ let stopping = false;
+ let wakeUp = null;
+ let loopDone = null;
+ let sweepTimer = null;
+ let lastPruneAt = 0;
+
+ function wake() {
+ const fn = wakeUp;
+ wakeUp = null;
+ if (fn) fn();
+ }
+
+ function sleep(ms) {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => { wakeUp = null; resolve(); }, ms);
+ wakeUp = () => { clearTimeout(timer); resolve(); };
+ });
+ }
+
+ async function deliverNotification(row, adapter) {
+ const p = row.payload || {};
+ if (p.expiresAt && Date.parse(p.expiresAt) <= Date.now()) {
+ stats.notificationsSkipped += 1;
+ log.info('notification expired before delivery', { id: row.id, platform: row.platform });
+ return;
+ }
+ if (p.linkId) {
+ const link = await store.getLinkById(p.linkId);
+ if (!link || link.revoked_at || link.notify === false) {
+ stats.notificationsSkipped += 1;
+ log.info('notification skipped: chat unlinked or muted', { id: row.id, platform: row.platform });
+ return;
+ }
+ }
+ if (!p.chatId || !p.text) {
+ stats.notificationsSkipped += 1;
+ log.warn('notification row has no chat or text', { id: row.id });
+ return;
+ }
+ const { gw, counter } = trackDeliveries(adapter.gateway(null));
+ row.counter = counter;
+ await gw.sendText(String(p.chatId), String(p.text));
+ stats.notificationsSent += 1;
+ }
+
+ async function runEvent(row, adapter) {
+ const event = adapter.normalize(row.payload);
+ if (!event) {
+ stats.ignored += 1;
+ log.info('row ignored: nothing to handle', { id: row.id, platform: row.platform });
+ return;
+ }
+ const { gw, counter } = trackDeliveries(adapter.gateway(event));
+ row.counter = counter;
+ row.event = event;
+ row.gw = gw;
+ const handler = typeof adapter.handle === 'function' ? adapter.handle.bind(adapter) : defaultHandler;
+ log.info('handling event', {
+ id: row.id, platform: row.platform, attempt: row.attempts,
+ kind: event.action ? 'action' : event.command ? 'command' : event.voice ? 'voice' : event.photo ? 'photo' : 'text',
+ command: event.command || null,
+ });
+ await handler(event, gw);
+ if (typeof adapter.finish === 'function') await adapter.finish(event, gw, counter);
+ }
+
+ async function apologize(row) {
+ if (!row.event || !row.gw) return;
+ try {
+ await row.gw.sendText(String(row.event.chatId), APOLOGY);
+ } catch (e) {
+ log.warn('apology not delivered', { id: row.id, ...errorSummary(e) });
+ }
+ }
+
+ async function processRow(row) {
+ const adapter = adapters.get(row.platform);
+ const started = Date.now();
+ const renewEvery = Math.max(5000, Math.floor((config.leaseSeconds * 1000) / 3));
+ const renew = setInterval(() => {
+ store.renewInboxLease(row.id, config.leaseSeconds)
+ .then((held) => { if (!held) log.warn('lease lost while processing', { id: row.id }); })
+ .catch((e) => log.warn('lease renewal failed', { id: row.id, ...errorSummary(e) }));
+ }, renewEvery);
+ try {
+ if (!adapter) throw Object.assign(new Error(`no adapter for platform ${row.platform}`), { deadLetter: true });
+ const work = row.payload?.kind === 'notify' ? deliverNotification(row, adapter) : runEvent(row, adapter);
+ await withTimeout(work, config.turnTimeoutMs);
+ await store.completeInbox(row.id);
+ stats.completed += 1;
+ log.info('row done', { id: row.id, platform: row.platform, ms: Date.now() - started, delivered: row.counter?.delivered ?? 0 });
+ } catch (err) {
+ const delivered = row.counter?.delivered ?? 0;
+ const verdict = err?.deadLetter || err instanceof TurnTimeout
+ ? { deadLetter: true, retryAfterMs: 0, reason: err instanceof TurnTimeout ? 'timeout' : 'no_adapter' }
+ : classifyFailure(err, { attempts: row.attempts, maxAttempts: config.maxAttempts, delivered, baseMs: config.backoffBaseMs, maxMs: config.backoffMaxMs });
+ const summary = errorSummary(err);
+ try {
+ await store.failInbox(row.id, `${verdict.reason}: ${summary.error}`, {
+ attempts: row.attempts,
+ maxAttempts: config.maxAttempts,
+ retryAfterSeconds: verdict.retryAfterMs / 1000,
+ deadLetter: verdict.deadLetter,
+ });
+ } catch (e) {
+ log.error('could not record row failure; its lease will expire and it will be retried', { id: row.id, ...errorSummary(e) });
+ }
+ if (verdict.deadLetter) {
+ stats.deadLettered += 1;
+ log.error('row dead-lettered', { id: row.id, platform: row.platform, attempt: row.attempts, reason: verdict.reason, delivered, ...summary });
+ // The owner sent something and is waiting. Say so rather than leave
+ // them in silence, unless the platform itself refuses this chat,
+ // they already got part of an answer, or a timed-out turn may still
+ // answer on its own.
+ if (!['permanent', 'partially_delivered', 'timeout'].includes(verdict.reason)) await apologize(row);
+ } else {
+ stats.retried += 1;
+ log.warn('row will be retried', { id: row.id, platform: row.platform, attempt: row.attempts, retryInMs: verdict.retryAfterMs, ...summary });
+ }
+ } finally {
+ clearInterval(renew);
+ }
+ }
+
+ async function claim(limit) {
+ try {
+ const rows = await store.claimInbox({ limit, leaseSeconds: config.leaseSeconds, platforms, chatKeys: config.chatKeys });
+ stats.lastClaimOkAt = Date.now();
+ stats.lastClaimError = null;
+ return rows;
+ } catch (e) {
+ stats.lastClaimError = errorSummary(e).error;
+ log.error('inbox claim failed', errorSummary(e));
+ return null;
+ }
+ }
+
+ /** Claim and start as many rows as there are free slots. Returns how many started. */
+ async function tick() {
+ stats.lastLoopAt = Date.now();
+ const free = config.concurrency - inflight.size;
+ if (free <= 0 || stopping) return 0;
+ const rows = await claim(free);
+ if (!rows) return -1;
+ for (const row of rows) {
+ stats.claimed += 1;
+ const p = processRow(row).finally(() => {
+ inflight.delete(row.id);
+ wake();
+ });
+ inflight.set(row.id, p);
+ }
+ return rows.length;
+ }
+
+ async function loop() {
+ let failures = 0;
+ while (!stopping) {
+ const started = await tick();
+ if (started < 0) {
+ failures += 1;
+ await sleep(Math.min(30_000, config.pollMs * 2 ** Math.min(failures, 5)));
+ continue;
+ }
+ failures = 0;
+ // A full claim may have more waiting behind it; otherwise wait for
+ // the poll interval or for a running row to finish (which may free
+ // its chat's next message).
+ if (started > 0 && inflight.size < config.concurrency) continue;
+ await sleep(config.pollMs);
+ }
+ }
+
+ /** Expire overdue trade previews and strip their buttons; prune old rows hourly. */
+ async function sweep() {
+ try {
+ const due = await store.expireDuePreviews({ limit: 50 });
+ for (const p of due) {
+ stats.previewsExpired += 1;
+ const adapter = adapters.get(p.platform);
+ if (!adapter || !p.message_ref) continue;
+ const gw = adapter.gateway(null);
+ if (gw.canEdit === false || typeof gw.editMessage !== 'function') continue;
+ await gw.editMessage(p.message_ref, `${previewText(p.proposal || {})}\n\n${EXPIRED_PREVIEW_LINE}`, { choices: [] })
+ .catch((e) => log.warn('expired preview not edited', { previewId: p.id, ...errorSummary(e) }));
+ }
+ if (due.length) log.info('previews expired', { count: due.length });
+ } catch (e) {
+ log.warn('preview sweep failed', errorSummary(e));
+ }
+ if (Date.now() - lastPruneAt >= PRUNE_EVERY_MS) {
+ lastPruneAt = Date.now();
+ await store.pruneInbox({ keepDays: config.pruneKeepDays })
+ .catch((e) => log.warn('inbox prune failed', errorSummary(e)));
+ }
+ }
+
+ return {
+ stats,
+ inflight,
+ tick,
+ sweep,
+ processRow,
+ start() {
+ stopping = false;
+ loopDone = loop();
+ sweepTimer = setInterval(() => { sweep(); }, config.sweepMs);
+ sweepTimer.unref?.();
+ return loopDone;
+ },
+ /** Stop claiming, then wait up to `graceMs` for rows already running. */
+ async stop(graceMs = config.shutdownGraceMs) {
+ stopping = true;
+ clearInterval(sweepTimer);
+ wake();
+ await loopDone;
+ if (!inflight.size) return { abandoned: 0 };
+ let timer;
+ const grace = new Promise((resolve) => { timer = setTimeout(resolve, graceMs); });
+ await Promise.race([Promise.allSettled([...inflight.values()]), grace]);
+ clearTimeout(timer);
+ // Anything still running keeps its lease until it expires; the next
+ // worker reclaims it then.
+ return { abandoned: inflight.size };
+ },
+ health() {
+ const now = Date.now();
+ const stallMs = Math.max(60_000, config.pollMs * 20);
+ const looping = stopping || (stats.lastLoopAt > 0 && now - stats.lastLoopAt < stallMs) || inflight.size >= config.concurrency;
+ return {
+ ok: looping,
+ stopping,
+ platforms,
+ inflight: inflight.size,
+ concurrency: config.concurrency,
+ lastClaimOkAgoMs: stats.lastClaimOkAt ? now - stats.lastClaimOkAt : null,
+ ...stats,
+ };
+ },
+ };
+}
diff --git a/workers/agent-gateway/src/errors.js b/workers/agent-gateway/src/errors.js
new file mode 100644
index 000000000..1035bfaf5
--- /dev/null
+++ b/workers/agent-gateway/src/errors.js
@@ -0,0 +1,64 @@
+// How a failed delivery is retried. Adapters wrap every platform refusal in a
+// PlatformError that says whether trying again can help:
+//
+// permanent the platform will refuse the same call again (chat not found,
+// bot blocked or kicked, malformed request). Dead-letter now.
+// retryAfterMs the platform asked us to wait (HTTP 429). Retry no sooner.
+// neither a transient failure (5xx, network, timeout). Retry with backoff.
+//
+// Anything that is not a PlatformError (a database blip, an LLM lane outage that
+// escaped the core) is treated as transient.
+
+export class PlatformError extends Error {
+ /**
+ * @param {string} platform
+ * @param {string} message
+ * @param {{ status?:number|null, code?:string|number|null, permanent?:boolean, retryAfterMs?:number|null, cause?:unknown }} [info]
+ */
+ constructor(platform, message, { status = null, code = null, permanent = false, retryAfterMs = null, cause } = {}) {
+ super(`${platform}: ${message}`, cause ? { cause } : undefined);
+ this.name = 'PlatformError';
+ this.platform = platform;
+ this.status = status;
+ this.code = code;
+ this.permanent = Boolean(permanent);
+ this.retryAfterMs = retryAfterMs;
+ }
+}
+
+/** A 4xx other than 408 and 429 means the same request will be refused again. */
+export function isPermanentStatus(status) {
+ return Number.isInteger(status) && status >= 400 && status < 500 && status !== 408 && status !== 429;
+}
+
+/**
+ * The delay before attempt `attempts + 1`: exponential from `baseMs`, capped at
+ * `maxMs`, never shorter than what the platform asked for.
+ */
+export function backoffMs(attempts, { baseMs, maxMs, retryAfterMs = null }) {
+ const exp = Math.min(maxMs, baseMs * 2 ** Math.max(0, attempts - 1));
+ return Math.max(exp, Number(retryAfterMs) || 0);
+}
+
+/**
+ * Decide what to do with a row whose handler threw.
+ * @param {unknown} err
+ * @param {{ attempts:number, maxAttempts:number, delivered:number, baseMs:number, maxMs:number }} ctx
+ * @returns {{ deadLetter:boolean, retryAfterMs:number, reason:string }}
+ */
+export function classifyFailure(err, { attempts, maxAttempts, delivered, baseMs, maxMs }) {
+ // Something already reached the chat. Running the event again would repeat
+ // that message (and, for a conversation, a whole agent turn), so the row is
+ // parked instead of retried.
+ if (delivered > 0) return { deadLetter: true, retryAfterMs: 0, reason: 'partially_delivered' };
+ if (err instanceof PlatformError && err.permanent) return { deadLetter: true, retryAfterMs: 0, reason: 'permanent' };
+ if (attempts >= maxAttempts) return { deadLetter: true, retryAfterMs: 0, reason: 'attempts_exhausted' };
+ const retryAfterMs = backoffMs(attempts, { baseMs, maxMs, retryAfterMs: err instanceof PlatformError ? err.retryAfterMs : null });
+ return { deadLetter: false, retryAfterMs, reason: 'transient' };
+}
+
+/** A short, log-safe description of an error: never a message body. */
+export function errorSummary(err) {
+ if (err instanceof PlatformError) return { error: err.message, status: err.status, code: err.code, permanent: err.permanent };
+ return { error: String(err?.message || err).slice(0, 300), code: err?.code ?? null };
+}
diff --git a/workers/agent-gateway/src/index.js b/workers/agent-gateway/src/index.js
new file mode 100644
index 000000000..1aea02c11
--- /dev/null
+++ b/workers/agent-gateway/src/index.js
@@ -0,0 +1,105 @@
+// agent-gateway: the process behind every three.ws chat gateway.
+//
+// The webhook receivers (api/gateway/telegram.js, api/gateway/discord.js) verify
+// each delivery and queue it in gateway_inbox; notifications for paired chats
+// are queued there too (api/_lib/gateway/notify.js). This worker drains that
+// inbox: it claims rows one chat at a time under a lease, runs each through the
+// shared gateway core with the platform's adapter, and acknowledges, retries
+// with backoff, or dead-letters it. It also holds the Discord gateway connection
+// (DMs and mentions), expires stale trade previews and prunes finished rows.
+//
+// Cloud Run runs it as an always-on service (no CPU throttling, one instance is
+// enough; more are safe because the claim is exclusive). GET /healthz reports
+// the loop, the adapters and the counters. SIGTERM stops claiming, lets running
+// rows finish within the grace period, and closes the platform connections.
+//
+// Local: npm run dev (loads ../../.env and ../../.env.local). README.md has the
+// env vars and the deploy command.
+
+import http from 'node:http';
+import { enqueueInbox, inboxBacklog } from '../../../api/_lib/gateway/store.js';
+import { loadConfig } from './config.js';
+import { loadAdapters } from './adapters/index.js';
+import { createDrainer } from './drain.js';
+import { errorSummary } from './errors.js';
+import { log } from './log.js';
+
+function startHealthServer({ port, drainer, adapters, skipped }) {
+ const server = http.createServer(async (req, res) => {
+ const path = new URL(req.url, 'http://localhost').pathname;
+ if (req.method !== 'GET' || (path !== '/' && path !== '/healthz')) {
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: 'not_found' }));
+ return;
+ }
+ const h = drainer.health();
+ const backlog = await inboxBacklog().catch(() => null);
+ const body = {
+ ...h,
+ ok: h.ok && adapters.size > 0,
+ adapters: Object.fromEntries([...adapters].map(([p, a]) => [p, a.describe ? a.describe() : {}])),
+ skipped,
+ backlog,
+ };
+ res.writeHead(body.ok ? 200 : 503, { 'content-type': 'application/json', 'cache-control': 'no-store' });
+ res.end(JSON.stringify(body));
+ });
+ server.listen(port, () => log.info('health endpoint listening', { port }));
+ return server;
+}
+
+async function main() {
+ const config = loadConfig();
+ const { adapters, skipped } = loadAdapters({ config, log });
+ for (const s of skipped) log.warn('adapter not loaded', s);
+ if (!adapters.size) log.error('no chat platform is configured; set TELEGRAM_BOT_TOKEN and/or DISCORD_BOT_TOKEN + DISCORD_APP_ID');
+
+ const drainer = createDrainer({ adapters, config, log });
+ const server = startHealthServer({ port: config.port, drainer, adapters, skipped });
+
+ const enqueue = async (delivery) => {
+ const fresh = await enqueueInbox(delivery);
+ log.debug('inbound delivery queued', { platform: delivery.platform, fresh });
+ return fresh;
+ };
+ for (const [platform, adapter] of adapters) {
+ if (typeof adapter.start !== 'function') continue;
+ try {
+ await adapter.start({ enqueue });
+ } catch (e) {
+ log.error('adapter listener failed to start; queued deliveries still drain', { platform, ...errorSummary(e) });
+ }
+ }
+
+ log.info('agent gateway started', {
+ platforms: [...adapters.keys()],
+ concurrency: config.concurrency,
+ leaseSeconds: config.leaseSeconds,
+ maxAttempts: config.maxAttempts,
+ chatKeys: config.chatKeys,
+ });
+ drainer.start();
+
+ let shuttingDown = false;
+ const shutdown = async (signal) => {
+ if (shuttingDown) return;
+ shuttingDown = true;
+ log.info('shutdown requested', { signal, inflight: drainer.inflight.size });
+ const { abandoned } = await drainer.stop();
+ for (const [platform, adapter] of adapters) {
+ if (typeof adapter.stop === 'function') await adapter.stop().catch((e) => log.warn('adapter stop failed', { platform, ...errorSummary(e) }));
+ }
+ server.close();
+ log.info('agent gateway stopped', { abandoned });
+ process.exit(0);
+ };
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
+ process.on('SIGINT', () => shutdown('SIGINT'));
+}
+
+process.on('unhandledRejection', (e) => log.error('unhandled rejection', errorSummary(e)));
+
+main().catch((e) => {
+ log.error('agent gateway failed to start', errorSummary(e));
+ process.exit(1);
+});
diff --git a/workers/agent-gateway/src/log.js b/workers/agent-gateway/src/log.js
new file mode 100644
index 000000000..78227821d
--- /dev/null
+++ b/workers/agent-gateway/src/log.js
@@ -0,0 +1,17 @@
+// Structured single-line JSON logs. Cloud Logging reads `severity` and `message`
+// from each line, so a warning or error is filterable without parsing. Message
+// text from chats never reaches a log: callers pass ids, platforms and error
+// codes only.
+
+function emit(severity, message, meta) {
+ const line = JSON.stringify({ severity, message, time: new Date().toISOString(), worker: 'agent-gateway', ...(meta || {}) });
+ if (severity === 'ERROR' || severity === 'WARNING') console.error(line);
+ else console.log(line);
+}
+
+export const log = {
+ debug: (message, meta) => { if (process.env.GATEWAY_DEBUG === '1') emit('DEBUG', message, meta); },
+ info: (message, meta) => emit('INFO', message, meta),
+ warn: (message, meta) => emit('WARNING', message, meta),
+ error: (message, meta) => emit('ERROR', message, meta),
+};
diff --git a/workers/agent-gateway/src/setup.js b/workers/agent-gateway/src/setup.js
new file mode 100644
index 000000000..02ee0824d
--- /dev/null
+++ b/workers/agent-gateway/src/setup.js
@@ -0,0 +1,175 @@
+// One-time and operator commands for the chat gateway bots.
+//
+// node src/setup.js discord-commands [--guild <id>] [--dry-run]
+// Register the slash commands (every command in api/_lib/gateway/commands.js
+// plus /start, each also under /three) globally, or on one guild for an
+// instant test. Needs DISCORD_BOT_TOKEN and DISCORD_APP_ID.
+//
+// node src/setup.js telegram-webhook [--url <url>] [--dry-run] [--info] [--delete]
+// Point the bot at https://three.ws/api/gateway/telegram (or --url) with
+// the secret the receiver verifies, and publish the command menu.
+// --info only reads the current webhook; --delete removes it.
+//
+// node src/setup.js inbox [--failed <n>]
+// Queue depth, the oldest open delivery, and the most recent dead letters.
+//
+// node src/setup.js requeue <id>
+// Put one dead letter back on the queue with a fresh attempt budget.
+//
+// package.json wires the first two as `npm run register:discord` and
+// `npm run webhook:telegram`.
+
+import { Api } from 'grammy';
+import { REST, Routes } from 'discord.js';
+import { COMMANDS } from '../../../api/_lib/gateway/commands.js';
+import { telegramWebhookSecret } from '../../../api/_lib/gateway/webhooks.js';
+import { appOrigin } from '../../../api/_lib/gateway/format.js';
+
+const NAME_RE = /^[a-z0-9_-]{1,32}$/;
+
+function flag(argv, name) {
+ return argv.includes(`--${name}`);
+}
+
+function option(argv, name) {
+ const i = argv.indexOf(`--${name}`);
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : null;
+}
+
+function need(env, ...names) {
+ const missing = names.filter((n) => !env[n]);
+ if (missing.length) throw new Error(`missing ${missing.join(', ')}. Read them with: node scripts/read-service-env.mjs '^(${missing.join('|')})$'`);
+}
+
+/** The command list every platform shows: the shared commands plus /start. */
+export function gatewayCommands() {
+ return [{ name: 'start', description: 'Get a pairing code for this chat' }, ...COMMANDS];
+}
+
+function discordOption(cmd) {
+ if (!cmd.arg) return [];
+ if (cmd.arg === 'on|off') {
+ return [{ type: 3, name: 'state', description: 'on or off', required: false, choices: [{ name: 'on', value: 'on' }, { name: 'off', value: 'off' }] }];
+ }
+ const name = NAME_RE.test(cmd.arg) ? cmd.arg : 'value';
+ return [{ type: 3, name, description: cmd.arg === 'agent' ? 'Agent number or name' : cmd.arg === 'code' ? 'Pairing code from the site' : cmd.arg, required: false }];
+}
+
+/**
+ * The Discord application command set: each command top level, and the same
+ * set as subcommands of /three (how the help text names them on Discord).
+ * Guild installs, usable in servers and in the bot's DMs.
+ */
+export function discordCommandSet() {
+ const base = gatewayCommands().filter((c) => NAME_RE.test(c.name));
+ const shared = { integration_types: [0], contexts: [0, 1] };
+ const top = base.map((c) => ({ type: 1, name: c.name, description: c.description.slice(0, 100), options: discordOption(c), ...shared }));
+ const three = {
+ type: 1,
+ name: 'three',
+ description: 'Talk to your three.ws agent',
+ options: base.map((c) => ({ type: 1, name: c.name, description: c.description.slice(0, 100), options: discordOption(c) })),
+ ...shared,
+ };
+ return [...top, three];
+}
+
+/** The Telegram command menu (setMyCommands). */
+export function telegramCommandSet() {
+ return gatewayCommands()
+ .filter((c) => /^[a-z0-9_]{1,32}$/.test(c.name))
+ .map((c) => ({ command: c.name, description: c.description.slice(0, 256) }));
+}
+
+async function discordCommands(argv, env, out) {
+ const body = discordCommandSet();
+ const guild = option(argv, 'guild');
+ if (flag(argv, 'dry-run')) {
+ out(JSON.stringify({ route: guild ? `guild ${guild}` : 'global', commands: body }, null, 2));
+ return;
+ }
+ need(env, 'DISCORD_BOT_TOKEN', 'DISCORD_APP_ID');
+ const rest = new REST({ version: '10' }).setToken(env.DISCORD_BOT_TOKEN);
+ const route = guild ? Routes.applicationGuildCommands(env.DISCORD_APP_ID, guild) : Routes.applicationCommands(env.DISCORD_APP_ID);
+ const saved = await rest.put(route, { body });
+ out(`Registered ${saved.length} Discord commands ${guild ? `on guild ${guild} (live now)` : 'globally (can take up to an hour to appear)'}: ${saved.map((c) => `/${c.name}`).join(' ')}`);
+ out(`Interactions endpoint to set in the developer portal: ${appOrigin()}/api/gateway/discord`);
+}
+
+async function telegramWebhook(argv, env, out) {
+ need(env, 'TELEGRAM_BOT_TOKEN');
+ const api = new Api(env.TELEGRAM_BOT_TOKEN);
+ const describe = (info) => ({
+ url: info.url || '(none)',
+ pending_update_count: info.pending_update_count,
+ last_error: info.last_error_message || null,
+ last_error_at: info.last_error_date ? new Date(info.last_error_date * 1000).toISOString() : null,
+ allowed_updates: info.allowed_updates || null,
+ });
+ if (flag(argv, 'info')) {
+ out(JSON.stringify(describe(await api.getWebhookInfo()), null, 2));
+ return;
+ }
+ if (flag(argv, 'delete')) {
+ await api.deleteWebhook({ drop_pending_updates: false });
+ out('Webhook removed. Updates now wait for getUpdates (GATEWAY_TELEGRAM_POLLING=1).');
+ return;
+ }
+ const url = option(argv, 'url') || `${appOrigin()}/api/gateway/telegram`;
+ const commands = telegramCommandSet();
+ if (flag(argv, 'dry-run')) {
+ out(JSON.stringify({ setWebhook: { url, allowed_updates: ['message', 'callback_query'], secret_token: '(derived from TELEGRAM_BOT_TOKEN or TELEGRAM_WEBHOOK_SECRET)' }, setMyCommands: commands }, null, 2));
+ return;
+ }
+ await api.setWebhook(url, {
+ secret_token: telegramWebhookSecret(env),
+ allowed_updates: ['message', 'callback_query'],
+ max_connections: 40,
+ drop_pending_updates: false,
+ });
+ await api.setMyCommands(commands);
+ const me = await api.getMe();
+ out(`@${me.username} now delivers to ${url} with ${commands.length} commands in its menu.`);
+ out(JSON.stringify(describe(await api.getWebhookInfo()), null, 2));
+}
+
+async function inbox(argv, out) {
+ const { inboxBacklog, listFailedInbox } = await import('../../../api/_lib/gateway/store.js');
+ const backlog = await inboxBacklog();
+ out(`Open deliveries: ${backlog.open}, oldest ${backlog.oldestSeconds}s old.`);
+ const failed = await listFailedInbox({ limit: Number(option(argv, 'failed')) || 20 });
+ if (!failed.length) {
+ out('No dead letters.');
+ return;
+ }
+ out('Dead letters (newest first):');
+ for (const f of failed) out(` #${f.id} ${f.chat_key} attempts=${f.attempts} at ${new Date(f.finished_at || f.created_at).toISOString()}: ${f.last_error || ''}`);
+ out('Requeue one with: npm run setup -- requeue <id>');
+}
+
+async function requeue(argv, out) {
+ const id = argv.find((a) => /^\d+$/.test(a));
+ if (!id) throw new Error('usage: requeue <id>');
+ const { requeueInbox } = await import('../../../api/_lib/gateway/store.js');
+ const row = await requeueInbox(id);
+ out(row ? `Requeued #${row.id} (${row.chat_key}).` : `#${id} is not a dead letter.`);
+}
+
+export async function run(argv, { env = process.env, out = (s) => console.log(s) } = {}) {
+ const [cmd, ...rest] = argv;
+ switch (cmd) {
+ case 'discord-commands': return discordCommands(rest, env, out);
+ case 'telegram-webhook': return telegramWebhook(rest, env, out);
+ case 'inbox': return inbox(rest, out);
+ case 'requeue': return requeue(rest, out);
+ default:
+ throw new Error(`unknown command "${cmd || ''}". Use discord-commands, telegram-webhook, inbox or requeue.`);
+ }
+}
+
+if (import.meta.url === `file://${process.argv[1]}`) {
+ run(process.argv.slice(2)).then(() => process.exit(0), (e) => {
+ console.error(`setup failed: ${e.message}`);
+ process.exit(1);
+ });
+}
diff --git a/workers/agent-gateway/tests/_db.js b/workers/agent-gateway/tests/_db.js
new file mode 100644
index 000000000..525fb0e99
--- /dev/null
+++ b/workers/agent-gateway/tests/_db.js
@@ -0,0 +1,44 @@
+// A real Postgres for the worker tests: PGlite (the in-process Postgres the repo
+// already tests SQL semantics with, tests/_helpers/pglite-sql.js) carrying the
+// gateway tables exactly as production got them, built by running the two
+// shipped migration files verbatim. The tables those migrations reference but do
+// not own (users, agent_identities, notification_events, agent_messages) are
+// created first with only the columns the gateway touches.
+
+import { readFileSync } from 'node:fs';
+import { createPgliteSql } from '../../../tests/_helpers/pglite-sql.js';
+
+const MIGRATIONS = new URL('../../../api/_lib/migrations/', import.meta.url);
+const GATEWAY_MIGRATIONS = ['20260922180000_chat_gateways.sql', '20260922190000_more_chat_gateways.sql'];
+
+const PREREQUISITES = `
+ CREATE TABLE users (id uuid PRIMARY KEY DEFAULT gen_random_uuid());
+ CREATE TABLE agent_identities (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id uuid REFERENCES users(id),
+ name text,
+ meta jsonb NOT NULL DEFAULT '{}'::jsonb,
+ deleted_at timestamptz
+ );
+ CREATE TABLE notification_events (id bigserial PRIMARY KEY, channel text NOT NULL);
+ CREATE TABLE agent_messages (id bigserial PRIMARY KEY);
+`;
+
+export async function createGatewayDb() {
+ const db = createPgliteSql();
+ await db.exec(PREREQUISITES);
+ for (const file of GATEWAY_MIGRATIONS) await db.exec(readFileSync(new URL(file, MIGRATIONS), 'utf8'));
+ return db;
+}
+
+/** A user, one agent, and a live link pairing `chatId` on `platform` to them. */
+export async function seedPairedChat(db, { platform = 'telegram', chatId, platformUserId }) {
+ const [user] = await db.query('INSERT INTO users DEFAULT VALUES RETURNING id');
+ const [agent] = await db.query("INSERT INTO agent_identities (user_id, name) VALUES ($1, 'Test Agent') RETURNING id", [user.id]);
+ const [link] = await db.query(
+ `INSERT INTO gateway_links (platform, platform_user_id, chat_id, chat_type, user_id, default_agent_id, last_seen_at)
+ VALUES ($1, $2, $3, 'private', $4, $5, now()) RETURNING *`,
+ [platform, String(platformUserId), String(chatId), user.id, agent.id],
+ );
+ return { user, agent, link };
+}
diff --git a/workers/agent-gateway/tests/_telegram.js b/workers/agent-gateway/tests/_telegram.js
new file mode 100644
index 000000000..c605b98f3
--- /dev/null
+++ b/workers/agent-gateway/tests/_telegram.js
@@ -0,0 +1,43 @@
+// The Telegram Bot API at its boundary. A real grammY Api whose transformer
+// answers each call locally instead of sending it to api.telegram.org, so the
+// adapter's own request building, error mapping and chunking run for real while
+// nothing leaves the machine. Every call is recorded for assertions.
+
+import { Api } from 'grammy';
+
+export const FIXTURE_TOKEN = '7000000001:AAFixtureTokenNeverSentAnywhere000000';
+
+/**
+ * @param {(method:string, payload:object) => object|undefined} [answer]
+ * returns a Bot API response ({ ok, result } or { ok:false, error_code, description }),
+ * or undefined for the default success shape.
+ */
+export function fakeBotApi(answer = () => undefined) {
+ const calls = [];
+ let nextMessageId = 9000;
+ const api = new Api(FIXTURE_TOKEN);
+ api.config.use(async (_prev, method, payload) => {
+ calls.push({ method, payload });
+ const custom = answer(method, payload);
+ if (custom) return custom;
+ switch (method) {
+ case 'sendMessage':
+ case 'sendPhoto':
+ case 'sendVideo':
+ case 'sendDocument':
+ case 'sendVoice':
+ return { ok: true, result: { message_id: nextMessageId++, date: 1791446400, chat: { id: Number(payload.chat_id), type: 'private' }, text: payload.text } };
+ case 'editMessageText':
+ return { ok: true, result: { message_id: payload.message_id, date: 1791446400, chat: { id: Number(payload.chat_id), type: 'private' }, text: payload.text } };
+ case 'getMe':
+ return { ok: true, result: { id: 7000000001, is_bot: true, first_name: 'three.ws', username: 'threewsbot' } };
+ case 'getFile':
+ return { ok: true, result: { file_id: payload.file_id, file_unique_id: 'u', file_size: 9214, file_path: `voice/${payload.file_id}.oga` } };
+ default:
+ return { ok: true, result: true };
+ }
+ });
+ return { api, calls, of: (method) => calls.filter((c) => c.method === method) };
+}
+
+export const telegramEnv = { TELEGRAM_BOT_TOKEN: FIXTURE_TOKEN, TELEGRAM_BOT_USERNAME: 'threewsbot' };
diff --git a/workers/agent-gateway/tests/discord-adapter.test.js b/workers/agent-gateway/tests/discord-adapter.test.js
new file mode 100644
index 000000000..e797c1771
--- /dev/null
+++ b/workers/agent-gateway/tests/discord-adapter.test.js
@@ -0,0 +1,199 @@
+// The Discord adapter: interaction and gateway-message normalisation, and the
+// send surface with the Discord REST API answered at its boundary.
+
+import { readFileSync } from 'node:fs';
+import { describe, it, expect } from 'vitest';
+import { DiscordAPIError, Routes } from 'discord.js';
+import { createDiscordAdapter, parseTypedCommand, snowflakeTime, toPlatformError } from '../src/adapters/discord.js';
+import { PlatformError } from '../src/errors.js';
+
+const fixture = (name) => JSON.parse(readFileSync(new URL(`./fixtures/${name}.json`, import.meta.url), 'utf8'));
+const env = { DISCORD_BOT_TOKEN: 'fixture-bot-token-never-sent', DISCORD_APP_ID: '1290000000000000001' };
+
+/** The REST client at its boundary: records each call and answers like Discord. */
+function fakeRest(answer = () => undefined) {
+ const calls = [];
+ let nextId = 1400000000000000000n;
+ const handle = (verb) => async (route, opts = {}) => {
+ calls.push({ verb, route, opts });
+ const custom = answer(verb, route, opts);
+ if (custom instanceof Error) throw custom;
+ if (custom) return custom;
+ if (verb === 'delete') return undefined;
+ const channel = /\/channels\/(\d+)\//.exec(route)?.[1] || '1280000000000000002';
+ nextId += 1n;
+ return { id: String(nextId), channel_id: channel, content: opts.body?.content };
+ };
+ return { rest: { get: handle('get'), post: handle('post'), patch: handle('patch'), put: handle('put'), delete: handle('delete') }, calls };
+}
+
+function adapterAt(interactionFixture, answer) {
+ const { rest, calls } = fakeRest(answer);
+ const minted = snowflakeTime(fixture(interactionFixture).id);
+ const adapter = createDiscordAdapter({ env, rest, config: { discordGateway: false }, now: () => minted + 2000 });
+ return { adapter, calls };
+}
+
+describe('discord normalize', () => {
+ const { adapter } = adapterAt('discord-interaction-command');
+
+ it('reads a /three subcommand with its option as command and args', () => {
+ expect(adapter.normalize(fixture('discord-interaction-command'))).toMatchObject({
+ platform: 'discord', chatId: '1280000000000000002', chatType: 'guild', chatTitle: 'agent-desk',
+ userId: '1270000000000000001', username: 'fixture_owner', command: 'use', args: '2',
+ interaction: { id: '1300000000000000001', type: 2, applicationId: '1290000000000000001' },
+ });
+ });
+
+ it('reads a top-level command', () => {
+ const i = fixture('discord-interaction-command');
+ i.data = { id: '1', name: 'balance', type: 1 };
+ expect(adapter.normalize(i)).toMatchObject({ command: 'balance', args: '' });
+ });
+
+ it('maps a button press in a DM to an action on the pressed message', () => {
+ expect(adapter.normalize(fixture('discord-interaction-button'))).toMatchObject({
+ chatType: 'dm',
+ userId: '1270000000000000001',
+ action: { verb: 'approve', previewId: '4d5e6f70-1111-4222-8333-944455566677' },
+ messageRef: { kind: 'channel', channelId: '1280000000000000003', messageId: '1299000000000000009' },
+ });
+ });
+
+ it('turns a mention into text without the mention, and a typed command into a command', () => {
+ expect(adapter.normalize(fixture('discord-message-mention'))).toMatchObject({ chatType: 'guild', chatTitle: 'agent-desk', text: 'how is my portfolio doing?' });
+ const typed = fixture('discord-message-mention');
+ typed.message.content = '<@1290000000000000001> /three balance';
+ expect(adapter.normalize(typed)).toMatchObject({ command: 'balance', args: '' });
+ });
+
+ it('routes an audio attachment to voice and an image to photo', () => {
+ const voice = fixture('discord-message-mention');
+ voice.message.attachments = [{ url: 'https://cdn.discordapp.com/attachments/1/2/voice-message.ogg', content_type: 'audio/ogg', size: 9000, filename: 'voice-message.ogg' }];
+ expect(typeof adapter.normalize(voice).voice.fetch).toBe('function');
+ const photo = fixture('discord-message-mention');
+ photo.message.attachments = [{ url: 'https://cdn.discordapp.com/attachments/1/2/chart.png', content_type: 'image/png', size: 9000, filename: 'chart.png' }];
+ expect(adapter.normalize(photo).photo.caption).toBe('how is my portfolio doing?');
+ });
+
+ it('ignores bots, unknown buttons and empty mentions', () => {
+ const fromBot = fixture('discord-message-mention');
+ fromBot.message.author.bot = true;
+ expect(adapter.normalize(fromBot)).toBeNull();
+ const button = fixture('discord-interaction-button');
+ button.data.custom_id = 'someone-elses-button';
+ expect(adapter.normalize(button)).toBeNull();
+ const bare = fixture('discord-message-mention');
+ bare.message.content = '<@1290000000000000001>';
+ expect(adapter.normalize(bare)).toBeNull();
+ });
+
+ it('parseTypedCommand handles /three and plain commands', () => {
+ expect(parseTypedCommand('/three link ABCD-EFGH')).toEqual({ command: 'link', args: 'ABCD-EFGH' });
+ expect(parseTypedCommand('/three')).toEqual({ command: 'help', args: '' });
+ expect(parseTypedCommand('/Portfolio')).toEqual({ command: 'portfolio', args: '' });
+ expect(parseTypedCommand('not a command')).toBeNull();
+ });
+});
+
+describe('discord gateway: interactions', () => {
+ it('fills the deferred reply first, then sends followups, with mentions disabled', async () => {
+ const { adapter, calls } = adapterAt('discord-interaction-command');
+ const event = adapter.normalize(fixture('discord-interaction-command'));
+ const gw = adapter.gateway(event);
+ const first = await gw.sendText(event.chatId, 'This chat now talks to Agent 2.');
+ await gw.sendText(event.chatId, 'second message');
+ const token = fixture('discord-interaction-command').token;
+ expect(calls[0]).toMatchObject({ verb: 'patch', route: Routes.webhookMessage(env.DISCORD_APP_ID, token, '@original'), opts: { auth: false } });
+ expect(calls[0].opts.body).toEqual({ content: 'This chat now talks to Agent 2.', allowed_mentions: { parse: [] } });
+ expect(calls[1]).toMatchObject({ verb: 'post', route: Routes.webhook(env.DISCORD_APP_ID, token), opts: { auth: false } });
+ expect(first).toMatchObject({ kind: 'interaction', interactionId: '1300000000000000001', applicationId: env.DISCORD_APP_ID });
+ });
+
+ it('removes the "thinking..." placeholder when a command produced nothing', async () => {
+ const { adapter, calls } = adapterAt('discord-interaction-command');
+ const event = adapter.normalize(fixture('discord-interaction-command'));
+ const gw = adapter.gateway(event);
+ await adapter.finish(event, gw);
+ expect(calls[0]).toMatchObject({ verb: 'delete', route: Routes.webhookMessage(env.DISCORD_APP_ID, fixture('discord-interaction-command').token, '@original') });
+ });
+
+ it('edits the pressed message through the press itself, and acks privately', async () => {
+ const { adapter, calls } = adapterAt('discord-interaction-button');
+ const event = adapter.normalize(fixture('discord-interaction-button'));
+ const gw = adapter.gateway(event);
+ await gw.ackAction(event, 'Approved. Executing...');
+ await gw.editMessage(event.messageRef, 'Sell preview\n\nApproved. Executing...', { choices: [] });
+ const token = fixture('discord-interaction-button').token;
+ expect(calls[0]).toMatchObject({ verb: 'post', route: Routes.webhook(env.DISCORD_APP_ID, token) });
+ expect(calls[0].opts.body.flags).toBe(64);
+ expect(calls[1]).toMatchObject({ verb: 'patch', route: Routes.webhookMessage(env.DISCORD_APP_ID, token, '@original') });
+ expect(calls[1].opts.body.components).toEqual([]);
+ });
+
+ it('renders choices as one action row of buttons', async () => {
+ const { adapter, calls } = adapterAt('discord-interaction-command');
+ const event = adapter.normalize(fixture('discord-interaction-command'));
+ await adapter.gateway(event).sendChoice(event.chatId, 'Buy preview', [{ id: 'gw:ap:x', label: 'Approve', style: 'primary' }, { id: 'gw:cx:x', label: 'Cancel', style: 'danger' }]);
+ expect(calls[0].opts.body.components).toEqual([{ type: 1, components: [
+ { type: 2, style: 1, label: 'Approve', custom_id: 'gw:ap:x' },
+ { type: 2, style: 4, label: 'Cancel', custom_id: 'gw:cx:x' },
+ ] }]);
+ });
+
+ it('falls back to the bot channel API once an interaction token has expired', async () => {
+ const { rest, calls } = fakeRest();
+ const i = fixture('discord-interaction-command');
+ const adapter = createDiscordAdapter({ env, rest, config: { discordGateway: false }, now: () => snowflakeTime(i.id) + 20 * 60 * 1000 });
+ const event = adapter.normalize(i);
+ const ref = await adapter.gateway(event).sendText(event.chatId, 'late answer');
+ expect(calls[0]).toMatchObject({ verb: 'post', route: Routes.channelMessages('1280000000000000002') });
+ expect(calls[0].opts.auth).toBeUndefined();
+ expect(ref).toMatchObject({ kind: 'channel', channelId: '1280000000000000002' });
+ });
+});
+
+describe('discord gateway: channels', () => {
+ it('sends notifications, typing and images through the channel API', async () => {
+ const { rest, calls } = fakeRest();
+ const gw = createDiscordAdapter({ env, rest, config: { discordGateway: false } }).gateway(null);
+ await gw.sendText('555', 'Your run finished');
+ await gw.typing('555');
+ await gw.sendMedia('555', { url: 'https://three.ws/api/render/glb?glbUrl=x', caption: 'Rendered' });
+ expect(calls.map((c) => [c.verb, c.route])).toEqual([
+ ['post', Routes.channelMessages('555')],
+ ['post', Routes.channelTyping('555')],
+ ['post', Routes.channelMessages('555')],
+ ]);
+ expect(calls[2].opts.body.embeds).toEqual([{ image: { url: 'https://three.ws/api/render/glb?glbUrl=x' } }]);
+ });
+
+ it('edits a stored interaction ref by webhook, and through the channel when that is refused', async () => {
+ const refused = new DiscordAPIError({ code: 50027, message: 'Invalid Webhook Token' }, 50027, 401, 'PATCH', '/webhooks/x', {});
+ const { rest, calls } = fakeRest((verb, route) => (verb === 'patch' && route.startsWith('/webhooks/') ? refused : undefined));
+ const now = Date.now();
+ const gw = createDiscordAdapter({ env, rest, config: { discordGateway: false }, now: () => now }).gateway(null);
+ const freshId = String((BigInt(now - 60_000) - 1420070400000n) << 22n);
+ await gw.editMessage({ kind: 'interaction', applicationId: env.DISCORD_APP_ID, token: 't', interactionId: freshId, channelId: '777', messageId: '888' }, 'Expired.', { choices: [] });
+ expect(calls.map((c) => [c.verb, c.route])).toEqual([
+ ['patch', Routes.webhookMessage(env.DISCORD_APP_ID, 't', '888')],
+ ['patch', Routes.channelMessage('777', '888')],
+ ]);
+ });
+
+ it('uploads a spoken reply as an audio file', async () => {
+ const { rest, calls } = fakeRest();
+ await createDiscordAdapter({ env, rest, config: { discordGateway: false } }).gateway(null).sendVoice('555', { buffer: Buffer.from('OggS'), mimeType: 'audio/ogg', filename: 'reply.ogg' });
+ expect(calls[0].opts.files).toEqual([{ name: 'reply.ogg', data: Buffer.from('OggS'), contentType: 'audio/ogg' }]);
+ });
+});
+
+describe('discord error mapping', () => {
+ it('marks 4xx permanent and leaves 5xx retryable', () => {
+ const forbidden = toPlatformError(new DiscordAPIError({ code: 50001, message: 'Missing Access' }, 50001, 403, 'POST', '/channels/1/messages', {}));
+ expect(forbidden).toBeInstanceOf(PlatformError);
+ expect(forbidden).toMatchObject({ platform: 'discord', status: 403, code: 50001, permanent: true });
+ const outage = toPlatformError(new DiscordAPIError({ code: 0, message: 'Internal Server Error' }, 0, 503, 'POST', '/channels/1/messages', {}));
+ expect(outage.permanent).toBe(false);
+ });
+});
diff --git a/workers/agent-gateway/tests/drain.test.js b/workers/agent-gateway/tests/drain.test.js
new file mode 100644
index 000000000..94fa21dcb
--- /dev/null
+++ b/workers/agent-gateway/tests/drain.test.js
@@ -0,0 +1,342 @@
+// The drain loop against a real Postgres inbox (PGlite built from the shipped
+// gateway migrations) and the real gateway core. Only the Telegram Bot API is
+// answered locally (tests/_telegram.js), so claim, lease, ordering, retry,
+// backoff, dead letters, notifications and the preview sweeper all run for real.
+
+import { readFileSync } from 'node:fs';
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+import { createGatewayDb, seedPairedChat } from './_db.js';
+import { fakeBotApi, telegramEnv } from './_telegram.js';
+
+const holder = vi.hoisted(() => ({ db: null }));
+
+vi.mock('../../../api/_lib/db.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, sql: (strings, ...values) => holder.db.sql(strings, ...values) };
+});
+
+const store = await import('../../../api/_lib/gateway/store.js');
+const { createDrainer } = await import('../src/drain.js');
+const { createTelegramAdapter } = await import('../src/adapters/telegram.js');
+
+const fixture = (name) => JSON.parse(readFileSync(new URL(`./fixtures/${name}.json`, import.meta.url), 'utf8'));
+const quietLog = { debug() {}, info() {}, warn() {}, error() {} };
+
+const baseConfig = {
+ concurrency: 4,
+ pollMs: 50,
+ leaseSeconds: 60,
+ maxAttempts: 3,
+ backoffBaseMs: 5000,
+ backoffMaxMs: 60_000,
+ turnTimeoutMs: 10_000,
+ sweepMs: 60_000,
+ pruneKeepDays: 7,
+ shutdownGraceMs: 1000,
+ chatKeys: null,
+};
+
+async function queueTelegram(update) {
+ return store.enqueueInbox({ platform: 'telegram', dedupeKey: String(update.update_id), chatKey: `telegram:${update.message?.chat.id ?? update.callback_query.message.chat.id}`, payload: update });
+}
+
+function setup({ answer, config = {}, defaultHandler } = {}) {
+ const bot = fakeBotApi(answer);
+ const adapter = createTelegramAdapter({ env: telegramEnv, api: bot.api });
+ const drainer = createDrainer({ adapters: new Map([['telegram', adapter]]), config: { ...baseConfig, ...config }, log: quietLog, ...(defaultHandler ? { defaultHandler } : {}) });
+ const drain = async () => {
+ const n = await drainer.tick();
+ await Promise.allSettled([...drainer.inflight.values()]);
+ return n;
+ };
+ return { bot, adapter, drainer, drain };
+}
+
+async function inboxRows() {
+ return holder.db.query('SELECT id, platform, status, attempts, last_error, locked_until, chat_key FROM gateway_inbox ORDER BY id');
+}
+
+beforeAll(async () => {
+ holder.db = await createGatewayDb();
+});
+
+beforeEach(async () => {
+ await holder.db.exec('TRUNCATE gateway_inbox, gateway_reply_codes, gateway_previews, gateway_pair_codes, gateway_links, agent_identities, users RESTART IDENTITY CASCADE');
+});
+
+describe('drain: unpaired chats', () => {
+ it('answers a queued Telegram /help through the core and the adapter, then acknowledges the row', async () => {
+ const { bot, drain } = setup();
+ expect(await queueTelegram(fixture('telegram-update-help'))).toBe(true);
+ expect(await drain()).toBe(1);
+
+ const sent = bot.of('sendMessage');
+ expect(sent).toHaveLength(1);
+ expect(sent[0].payload.chat_id).toBe('5550001001');
+ expect(sent[0].payload.text).toContain('Talk to your three.ws agent here');
+ expect(sent[0].payload.text).toContain('send /start to get a pairing code');
+ const [row] = await inboxRows();
+ expect(row).toMatchObject({ status: 'done', attempts: 1 });
+ });
+
+ it('/start addressed to this bot in a group issues a pairing code and stores only its hash', async () => {
+ const { bot, drain } = setup();
+ await queueTelegram(fixture('telegram-update-start-group'));
+ await drain();
+ const [msg] = bot.of('sendMessage');
+ const code = /Your pairing code: ([A-Z0-9]{4}-[A-Z0-9]{4})/.exec(msg.payload.text)?.[1];
+ expect(code).toBeTruthy();
+ const codes = await holder.db.query('SELECT origin, platform, chat_id, chat_title, code_hash FROM gateway_pair_codes');
+ expect(codes).toHaveLength(1);
+ expect(codes[0]).toMatchObject({ origin: 'chat', platform: 'telegram', chat_id: '-1005550002002', chat_title: 'Fixture Traders' });
+ expect(codes[0].code_hash).not.toContain(code.replace('-', ''));
+ });
+
+ it('a duplicate delivery of the same update is queued once and answered once', async () => {
+ const { bot, drain } = setup();
+ const update = fixture('telegram-update-help');
+ expect(await queueTelegram(update)).toBe(true);
+ expect(await queueTelegram(update)).toBe(false);
+ await drain();
+ await drain();
+ expect(bot.of('sendMessage')).toHaveLength(1);
+ });
+});
+
+describe('drain: ordering and leases', () => {
+ it('claims one row per chat at a time, so replies leave in arrival order', async () => {
+ const { bot, drain } = setup();
+ const first = fixture('telegram-update-help');
+ const second = { ...fixture('telegram-update-help'), update_id: first.update_id + 1, message: { ...first.message, message_id: 4200, text: '/start' } };
+ await queueTelegram(first);
+ await queueTelegram(second);
+ expect(await drain()).toBe(1);
+ expect(bot.of('sendMessage')[0].payload.text).toContain('Talk to your three.ws agent here');
+ expect(await drain()).toBe(1);
+ expect(bot.of('sendMessage')[1].payload.text).toContain('Your pairing code');
+ expect((await inboxRows()).map((r) => r.status)).toEqual(['done', 'done']);
+ });
+
+ it('never hands out a row whose lease is still held, and renews a held lease', async () => {
+ await queueTelegram(fixture('telegram-update-help'));
+ const [claimed] = await store.claimInbox({ limit: 5, leaseSeconds: 60 });
+ expect(claimed.attempts).toBe(1);
+ expect(await store.claimInbox({ limit: 5, leaseSeconds: 60 })).toHaveLength(0);
+ expect(await store.renewInboxLease(claimed.id, 120)).toBe(true);
+ await store.completeInbox(claimed.id);
+ expect(await store.renewInboxLease(claimed.id, 120)).toBe(false);
+ });
+
+ it('reclaims a row whose lease expired (a crashed worker) and counts the attempt', async () => {
+ await queueTelegram(fixture('telegram-update-help'));
+ const [claimed] = await store.claimInbox({ limit: 1, leaseSeconds: 60 });
+ await holder.db.query("UPDATE gateway_inbox SET locked_until = now() - interval '1 second' WHERE id = $1", [claimed.id]);
+ const [again] = await store.claimInbox({ limit: 1, leaseSeconds: 60 });
+ expect(again.id).toBe(claimed.id);
+ expect(again.attempts).toBe(2);
+ });
+
+ it('leaves rows for a platform this worker has no adapter for', async () => {
+ const { drain } = setup();
+ await store.enqueueInbox({ platform: 'discord', dedupeKey: 'i-1', chatKey: 'discord:1', payload: fixture('discord-interaction-command') });
+ expect(await drain()).toBe(0);
+ const [row] = await inboxRows();
+ expect(row).toMatchObject({ platform: 'discord', status: 'queued', attempts: 0 });
+ });
+
+ it('drains only the chats named in chatKeys when asked to', async () => {
+ const { bot, drain } = setup({ config: { chatKeys: ['telegram:-1005550002002'] } });
+ await queueTelegram(fixture('telegram-update-help'));
+ await queueTelegram(fixture('telegram-update-start-group'));
+ expect(await drain()).toBe(1);
+ expect(bot.of('sendMessage')[0].payload.chat_id).toBe('-1005550002002');
+ expect((await inboxRows()).map((r) => r.status)).toEqual(['queued', 'done']);
+ });
+});
+
+describe('drain: failures', () => {
+ const serverError = (method) => (method === 'sendMessage' ? { ok: false, error_code: 502, description: 'Bad Gateway' } : undefined);
+
+ it('requeues a transient platform failure with backoff, then dead-letters after maxAttempts', async () => {
+ const { bot, drain } = setup({ answer: serverError, config: { maxAttempts: 2 } });
+ await queueTelegram(fixture('telegram-update-help'));
+ await drain();
+ let [row] = await inboxRows();
+ expect(row).toMatchObject({ status: 'queued', attempts: 1 });
+ expect(row.last_error).toMatch(/^transient: telegram: Bad Gateway/);
+ expect(new Date(row.locked_until).getTime()).toBeGreaterThan(Date.now() + 3000);
+
+ // Still backing off: not claimable, and it keeps heading its chat.
+ expect(await drain()).toBe(0);
+
+ await holder.db.query("UPDATE gateway_inbox SET locked_until = now() - interval '1 second'");
+ await drain();
+ [row] = await inboxRows();
+ expect(row).toMatchObject({ status: 'failed', attempts: 2 });
+ expect(row.last_error).toMatch(/^attempts_exhausted/);
+ // The help text twice, then the apology attempt after giving up.
+ expect(bot.of('sendMessage')).toHaveLength(3);
+ expect(bot.of('sendMessage')[2].payload.text).toContain('Something went wrong on our side');
+ });
+
+ it('honours a 429 retry_after longer than the backoff', async () => {
+ const { drain } = setup({ answer: (m) => (m === 'sendMessage' ? { ok: false, error_code: 429, description: 'Too Many Requests: retry after 120', parameters: { retry_after: 120 } } : undefined) });
+ await queueTelegram(fixture('telegram-update-help'));
+ await drain();
+ const [row] = await inboxRows();
+ expect(row.status).toBe('queued');
+ expect(new Date(row.locked_until).getTime()).toBeGreaterThan(Date.now() + 110_000);
+ });
+
+ it('dead-letters a permanent refusal at once and does not retry or apologise', async () => {
+ const { bot, drain } = setup({ answer: (m) => (m === 'sendMessage' ? { ok: false, error_code: 403, description: 'Forbidden: bot was blocked by the user' } : undefined) });
+ await queueTelegram(fixture('telegram-update-help'));
+ await drain();
+ const [row] = await inboxRows();
+ expect(row).toMatchObject({ status: 'failed', attempts: 1 });
+ expect(row.last_error).toMatch(/^permanent: telegram: Forbidden: bot was blocked/);
+ expect(bot.of('sendMessage')).toHaveLength(1);
+ });
+
+ it('never re-runs an event that already delivered something before it failed', async () => {
+ const handler = async (event, gw) => {
+ await gw.sendText(event.chatId, 'first part of an answer');
+ throw new Error('lane dropped mid-turn');
+ };
+ const { bot, drain } = setup({ defaultHandler: handler });
+ await queueTelegram(fixture('telegram-update-text'));
+ await drain();
+ const [row] = await inboxRows();
+ expect(row).toMatchObject({ status: 'failed', attempts: 1 });
+ expect(row.last_error).toMatch(/^partially_delivered: lane dropped mid-turn/);
+ expect(bot.of('sendMessage')).toHaveLength(1);
+ });
+
+ it('fails a turn that outlives the timeout without apologising (it may still answer)', async () => {
+ const handler = () => new Promise(() => {});
+ const { bot, drain } = setup({ defaultHandler: handler, config: { turnTimeoutMs: 50 } });
+ await queueTelegram(fixture('telegram-update-text'));
+ await drain();
+ const [row] = await inboxRows();
+ expect(row.status).toBe('failed');
+ expect(row.last_error).toMatch(/^timeout/);
+ expect(bot.of('sendMessage')).toHaveLength(0);
+ });
+
+ it('acknowledges a delivery with nothing to answer (a sticker) without calling the platform', async () => {
+ const { bot, drain } = setup();
+ const update = fixture('telegram-update-help');
+ delete update.message.text;
+ delete update.message.entities;
+ update.message.sticker = { file_id: 'CAACAgIAAxkBAAIfixture', width: 512, height: 512, is_animated: false, is_video: false, type: 'regular' };
+ await queueTelegram(update);
+ await drain();
+ expect((await inboxRows())[0].status).toBe('done');
+ expect(bot.calls).toHaveLength(0);
+ });
+});
+
+describe('drain: paired chats', () => {
+ it('a paired owner pressing Cancel on a live preview cancels it and strips the buttons', async () => {
+ const { link, user, agent } = await seedPairedChat(holder.db, { chatId: '5550001001', platformUserId: '5550001001' });
+ const [preview] = await holder.db.query(
+ `INSERT INTO gateway_previews (link_id, user_id, agent_id, kind, proposal, message_ref, expires_at)
+ VALUES ($1, $2, $3, 'buy', $4::jsonb, $5::jsonb, now() + interval '10 minutes') RETURNING id`,
+ [link.id, user.id, agent.id, JSON.stringify({ kind: 'buy', network: 'mainnet', sol_amount: 0.1, mint: 'THREEsynthetic1111111111111111111111111111', slippage_bps: 100, quote: { expected_out: 1000, min_received: 990, price_impact_pct: 0.4 } }), JSON.stringify({ chatId: '5550001001', messageId: 4190 })],
+ );
+ const update = fixture('telegram-update-callback');
+ update.callback_query.data = `gw:cx:${preview.id}`;
+ const { bot, drain } = setup();
+ await queueTelegram(update);
+ await drain();
+
+ expect(bot.of('answerCallbackQuery')[0].payload).toMatchObject({ callback_query_id: '4382910029381273001', text: 'Cancelled' });
+ const [edit] = bot.of('editMessageText');
+ expect(edit.payload).toMatchObject({ chat_id: '5550001001', message_id: 4190 });
+ expect(edit.payload.text).toContain('Cancelled. Nothing was sent.');
+ expect(edit.payload.reply_markup).toEqual({ inline_keyboard: [] });
+ const [after] = await holder.db.query('SELECT status FROM gateway_previews WHERE id = $1', [preview.id]);
+ expect(after.status).toBe('cancelled');
+ });
+
+ it('someone else in a paired chat is told it belongs to another account', async () => {
+ await seedPairedChat(holder.db, { chatId: '5550001001', platformUserId: '1' });
+ const { bot, drain } = setup();
+ await queueTelegram(fixture('telegram-update-text'));
+ await drain();
+ expect(bot.of('sendMessage')[0].payload.text).toContain("paired to another person's three.ws account");
+ });
+
+ it('/new in a paired chat resets the thread context', async () => {
+ const { link } = await seedPairedChat(holder.db, { chatId: '5550001001', platformUserId: '5550001001' });
+ const update = fixture('telegram-update-help');
+ update.message.text = '/new';
+ update.message.entities = [{ offset: 0, length: 4, type: 'bot_command' }];
+ const { bot, drain } = setup();
+ await queueTelegram(update);
+ await drain();
+ expect(bot.of('sendMessage')[0].payload.text).toContain('Started a fresh thread');
+ const [after] = await holder.db.query('SELECT context_reset_at FROM gateway_links WHERE id = $1', [link.id]);
+ expect(after.context_reset_at).not.toBeNull();
+ });
+});
+
+describe('drain: notifications', () => {
+ async function queueNotify(payload, key = 'n1') {
+ return store.enqueueInbox({ platform: 'telegram', dedupeKey: `notify:${key}`, chatKey: `telegram:${payload.chatId}`, payload: { kind: 'notify', ...payload } });
+ }
+
+ it('delivers a queued notification to its paired chat', async () => {
+ const { link } = await seedPairedChat(holder.db, { chatId: '5550001001', platformUserId: '5550001001' });
+ const { bot, drain } = setup();
+ await queueNotify({ chatId: '5550001001', linkId: link.id, type: 'run_completed', text: 'Your run finished\nhttps://three.ws/agents', expiresAt: new Date(Date.now() + 60_000).toISOString() });
+ await drain();
+ expect(bot.of('sendMessage')[0].payload).toMatchObject({ chat_id: '5550001001', text: 'Your run finished\nhttps://three.ws/agents' });
+ expect((await inboxRows())[0].status).toBe('done');
+ });
+
+ it('drops a stale notification and one whose chat was unlinked, without sending', async () => {
+ const { link, user } = await seedPairedChat(holder.db, { chatId: '5550001001', platformUserId: '5550001001' });
+ await store.revokeLink(link.id, user.id);
+ const { bot, drain } = setup();
+ await queueNotify({ chatId: '5550001001', linkId: link.id, type: 'bid', text: 'New bid', expiresAt: new Date(Date.now() + 60_000).toISOString() }, 'n-revoked');
+ await queueNotify({ chatId: '5550009999', linkId: null, type: 'bid', text: 'Old bid', expiresAt: new Date(Date.now() - 1000).toISOString() }, 'n-stale');
+ await drain();
+ expect(bot.of('sendMessage')).toHaveLength(0);
+ expect((await inboxRows()).map((r) => r.status)).toEqual(['done', 'done']);
+ });
+});
+
+describe('drain: sweeper', () => {
+ it('expires an overdue preview and removes its buttons in the chat', async () => {
+ const { link, user, agent } = await seedPairedChat(holder.db, { chatId: '5550001001', platformUserId: '5550001001' });
+ await holder.db.query(
+ `INSERT INTO gateway_previews (link_id, user_id, agent_id, kind, proposal, message_ref, expires_at)
+ VALUES ($1, $2, $3, 'limits', $4::jsonb, $5::jsonb, now() - interval '1 minute')`,
+ [link.id, user.id, agent.id, JSON.stringify({ kind: 'limits', changes: { per_trade_sol: 0.5 } }), JSON.stringify({ chatId: '5550001001', messageId: 4300 })],
+ );
+ const { bot, drainer } = setup();
+ await drainer.sweep();
+ const [edit] = bot.of('editMessageText');
+ expect(edit.payload.message_id).toBe(4300);
+ expect(edit.payload.text).toContain('Per-trade cap: 0.5 SOL');
+ expect(edit.payload.text).toContain('Expired. Ask your agent again for a fresh quote.');
+ expect(edit.payload.reply_markup).toEqual({ inline_keyboard: [] });
+ const [p] = await holder.db.query('SELECT status FROM gateway_previews');
+ expect(p.status).toBe('expired');
+ expect(drainer.stats.previewsExpired).toBe(1);
+ });
+});
+
+describe('drain: loop lifecycle', () => {
+ it('start() drains continuously and stop() returns once running rows finish', async () => {
+ const { bot, drainer } = setup();
+ await queueTelegram(fixture('telegram-update-help'));
+ drainer.start();
+ await vi.waitFor(async () => expect((await inboxRows())[0].status).toBe('done'), { timeout: 5000, interval: 25 });
+ const { abandoned } = await drainer.stop();
+ expect(abandoned).toBe(0);
+ expect(bot.of('sendMessage')).toHaveLength(1);
+ expect(drainer.health()).toMatchObject({ ok: true, stopping: true, platforms: ['telegram'], completed: 1 });
+ });
+});
diff --git a/workers/agent-gateway/tests/fixtures/discord-interaction-button.json b/workers/agent-gateway/tests/fixtures/discord-interaction-button.json
new file mode 100644
index 000000000..3b6f91425
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/discord-interaction-button.json
@@ -0,0 +1,11 @@
+{
+ "id": "1300000000000000002",
+ "application_id": "1290000000000000001",
+ "type": 3,
+ "token": "aW50ZXJhY3Rpb246MTMwMDAwMDAwMDAwMDAwMDAwMjpmaXh0dXJl",
+ "version": 1,
+ "channel_id": "1280000000000000003",
+ "user": { "id": "1270000000000000001", "username": "fixture_owner" },
+ "message": { "id": "1299000000000000009", "channel_id": "1280000000000000003", "content": "Sell preview on mainnet", "components": [] },
+ "data": { "component_type": 2, "custom_id": "gw:ap:4d5e6f70-1111-4222-8333-944455566677" }
+}
diff --git a/workers/agent-gateway/tests/fixtures/discord-interaction-command.json b/workers/agent-gateway/tests/fixtures/discord-interaction-command.json
new file mode 100644
index 000000000..01c02258d
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/discord-interaction-command.json
@@ -0,0 +1,12 @@
+{
+ "id": "1300000000000000001",
+ "application_id": "1290000000000000001",
+ "type": 2,
+ "token": "aW50ZXJhY3Rpb246MTMwMDAwMDAwMDAwMDAwMDAwMTpmaXh0dXJl",
+ "version": 1,
+ "guild_id": "1280000000000000001",
+ "channel_id": "1280000000000000002",
+ "channel": { "id": "1280000000000000002", "name": "agent-desk", "type": 0 },
+ "member": { "user": { "id": "1270000000000000001", "username": "fixture_owner", "global_name": "Fixture" }, "roles": [], "permissions": "2248473465835073" },
+ "data": { "id": "1295000000000000001", "name": "three", "type": 1, "options": [{ "type": 1, "name": "use", "options": [{ "type": 3, "name": "agent", "value": "2" }] }] }
+}
diff --git a/workers/agent-gateway/tests/fixtures/discord-message-mention.json b/workers/agent-gateway/tests/fixtures/discord-message-mention.json
new file mode 100644
index 000000000..0f4b5ec33
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/discord-message-mention.json
@@ -0,0 +1,13 @@
+{
+ "kind": "discord_message",
+ "botUserId": "1290000000000000001",
+ "channel_name": "agent-desk",
+ "message": {
+ "id": "1300000000000000003",
+ "channel_id": "1280000000000000002",
+ "guild_id": "1280000000000000001",
+ "content": "<@1290000000000000001> how is my portfolio doing?",
+ "author": { "id": "1270000000000000001", "username": "fixture_owner", "bot": false },
+ "attachments": []
+ }
+}
diff --git a/workers/agent-gateway/tests/fixtures/telegram-update-callback.json b/workers/agent-gateway/tests/fixtures/telegram-update-callback.json
new file mode 100644
index 000000000..378c214af
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/telegram-update-callback.json
@@ -0,0 +1,16 @@
+{
+ "update_id": 731204123,
+ "callback_query": {
+ "id": "4382910029381273001",
+ "from": { "id": 5550001001, "is_bot": false, "first_name": "Fixture", "username": "fixture_owner" },
+ "message": {
+ "message_id": 4190,
+ "from": { "id": 7000000001, "is_bot": true, "first_name": "three.ws", "username": "threewsbot" },
+ "chat": { "id": 5550001001, "first_name": "Fixture", "username": "fixture_owner", "type": "private" },
+ "date": 1791446700,
+ "text": "Buy preview on mainnet"
+ },
+ "chat_instance": "-6129381029381029381",
+ "data": "gw:cx:PREVIEW_ID"
+ }
+}
diff --git a/workers/agent-gateway/tests/fixtures/telegram-update-help.json b/workers/agent-gateway/tests/fixtures/telegram-update-help.json
new file mode 100644
index 000000000..7ba8445ba
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/telegram-update-help.json
@@ -0,0 +1,11 @@
+{
+ "update_id": 731204118,
+ "message": {
+ "message_id": 4182,
+ "from": { "id": 5550001001, "is_bot": false, "first_name": "Fixture", "username": "fixture_owner", "language_code": "en" },
+ "chat": { "id": 5550001001, "first_name": "Fixture", "username": "fixture_owner", "type": "private" },
+ "date": 1791446400,
+ "text": "/help",
+ "entities": [{ "offset": 0, "length": 5, "type": "bot_command" }]
+ }
+}
diff --git a/workers/agent-gateway/tests/fixtures/telegram-update-photo.json b/workers/agent-gateway/tests/fixtures/telegram-update-photo.json
new file mode 100644
index 000000000..51dd9233f
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/telegram-update-photo.json
@@ -0,0 +1,14 @@
+{
+ "update_id": 731204122,
+ "message": {
+ "message_id": 4185,
+ "from": { "id": 5550001001, "is_bot": false, "first_name": "Fixture", "username": "fixture_owner" },
+ "chat": { "id": 5550001001, "first_name": "Fixture", "username": "fixture_owner", "type": "private" },
+ "date": 1791446640,
+ "photo": [
+ { "file_id": "AgACAgEAAxkBAAIQ-fixture-small", "file_unique_id": "AQADs", "file_size": 1320, "width": 90, "height": 90 },
+ { "file_id": "AgACAgEAAxkBAAIQ-fixture-large", "file_unique_id": "AQADl", "file_size": 61022, "width": 1280, "height": 1280 }
+ ],
+ "caption": "is this chart bullish?"
+ }
+}
diff --git a/workers/agent-gateway/tests/fixtures/telegram-update-start-group.json b/workers/agent-gateway/tests/fixtures/telegram-update-start-group.json
new file mode 100644
index 000000000..da5540612
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/telegram-update-start-group.json
@@ -0,0 +1,11 @@
+{
+ "update_id": 731204119,
+ "message": {
+ "message_id": 77,
+ "from": { "id": 5550001002, "is_bot": false, "first_name": "Fixture", "username": "fixture_group_admin" },
+ "chat": { "id": -1005550002002, "title": "Fixture Traders", "type": "supergroup" },
+ "date": 1791446460,
+ "text": "/start@threewsbot",
+ "entities": [{ "offset": 0, "length": 17, "type": "bot_command" }]
+ }
+}
diff --git a/workers/agent-gateway/tests/fixtures/telegram-update-text.json b/workers/agent-gateway/tests/fixtures/telegram-update-text.json
new file mode 100644
index 000000000..b0be8f5c3
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/telegram-update-text.json
@@ -0,0 +1,10 @@
+{
+ "update_id": 731204120,
+ "message": {
+ "message_id": 4183,
+ "from": { "id": 5550001001, "is_bot": false, "first_name": "Fixture", "username": "fixture_owner" },
+ "chat": { "id": 5550001001, "first_name": "Fixture", "username": "fixture_owner", "type": "private" },
+ "date": 1791446520,
+ "text": "what is my balance?"
+ }
+}
diff --git a/workers/agent-gateway/tests/fixtures/telegram-update-voice.json b/workers/agent-gateway/tests/fixtures/telegram-update-voice.json
new file mode 100644
index 000000000..c7789160b
--- /dev/null
+++ b/workers/agent-gateway/tests/fixtures/telegram-update-voice.json
@@ -0,0 +1,10 @@
+{
+ "update_id": 731204121,
+ "message": {
+ "message_id": 4184,
+ "from": { "id": 5550001001, "is_bot": false, "first_name": "Fixture", "username": "fixture_owner" },
+ "chat": { "id": 5550001001, "first_name": "Fixture", "username": "fixture_owner", "type": "private" },
+ "date": 1791446580,
+ "voice": { "duration": 3, "mime_type": "audio/ogg", "file_id": "AwACAgEAAxkBAAIQ-fixture-voice", "file_unique_id": "AgADfixture", "file_size": 9214 }
+ }
+}
diff --git a/workers/agent-gateway/tests/registry-setup.test.js b/workers/agent-gateway/tests/registry-setup.test.js
new file mode 100644
index 000000000..098fe1f8a
--- /dev/null
+++ b/workers/agent-gateway/tests/registry-setup.test.js
@@ -0,0 +1,77 @@
+// The adapter registry, the retry policy and the setup command sets.
+
+import { describe, it, expect } from 'vitest';
+import { loadAdapters } from '../src/adapters/index.js';
+import { backoffMs, classifyFailure, PlatformError } from '../src/errors.js';
+import { loadConfig } from '../src/config.js';
+import { discordCommandSet, telegramCommandSet } from '../src/setup.js';
+import { COMMAND_HANDLERS } from '../../../api/_lib/gateway/commands.js';
+
+describe('adapter registry', () => {
+ it('loads only configured adapters and names the missing variables', () => {
+ const { adapters, skipped } = loadAdapters({ env: { TELEGRAM_BOT_TOKEN: '1:fixture' } });
+ expect([...adapters.keys()]).toEqual(['telegram']);
+ expect(skipped).toEqual([{ platform: 'discord', missing: ['DISCORD_BOT_TOKEN', 'DISCORD_APP_ID'] }]);
+ });
+
+ it('honours GATEWAY_PLATFORMS and accepts a new platform without touching the loop', () => {
+ const created = [];
+ const factories = {
+ telegram: { configured: () => ({ ok: true }), create: () => ({ platform: 'telegram' }) },
+ x: { configured: () => ({ ok: true }), create: (o) => { created.push(o); return { platform: 'x', normalize: () => null, gateway: () => ({}) }; } },
+ };
+ const { adapters } = loadAdapters({ env: {}, config: { platforms: ['x'] }, factories });
+ expect([...adapters.keys()]).toEqual(['x']);
+ expect(created).toHaveLength(1);
+ const unknown = loadAdapters({ env: {}, config: { platforms: ['fax'] }, factories });
+ expect(unknown.skipped).toEqual([{ platform: 'fax', missing: [], reason: 'unknown platform' }]);
+ });
+});
+
+describe('retry policy', () => {
+ const ctx = { attempts: 1, maxAttempts: 5, delivered: 0, baseMs: 5000, maxMs: 300_000 };
+
+ it('backs off exponentially, capped, never under the platform wait', () => {
+ expect(backoffMs(1, { baseMs: 5000, maxMs: 300_000 })).toBe(5000);
+ expect(backoffMs(3, { baseMs: 5000, maxMs: 300_000 })).toBe(20_000);
+ expect(backoffMs(12, { baseMs: 5000, maxMs: 300_000 })).toBe(300_000);
+ expect(backoffMs(1, { baseMs: 5000, maxMs: 300_000, retryAfterMs: 42_000 })).toBe(42_000);
+ });
+
+ it('classifies transient, permanent, exhausted and partially delivered failures', () => {
+ expect(classifyFailure(new Error('socket hang up'), ctx)).toEqual({ deadLetter: false, retryAfterMs: 5000, reason: 'transient' });
+ expect(classifyFailure(new PlatformError('telegram', 'chat not found', { status: 400, permanent: true }), ctx).reason).toBe('permanent');
+ expect(classifyFailure(new Error('x'), { ...ctx, attempts: 5 }).reason).toBe('attempts_exhausted');
+ expect(classifyFailure(new Error('x'), { ...ctx, delivered: 1 }).reason).toBe('partially_delivered');
+ });
+});
+
+describe('config', () => {
+ it('has production defaults and rejects a malformed number', () => {
+ expect(loadConfig({})).toMatchObject({ port: 8080, concurrency: 8, leaseSeconds: 90, maxAttempts: 5, platforms: null, telegramPolling: false, discordGateway: true });
+ expect(loadConfig({ GATEWAY_PLATFORMS: 'telegram, discord', GATEWAY_CHAT_KEYS: 'telegram:1' })).toMatchObject({ platforms: ['telegram', 'discord'], chatKeys: ['telegram:1'] });
+ expect(() => loadConfig({ GATEWAY_CONCURRENCY: 'lots' })).toThrow(/GATEWAY_CONCURRENCY/);
+ });
+});
+
+describe('setup command sets', () => {
+ it('registers every command the core handles on Discord, top level and under /three', () => {
+ const set = discordCommandSet();
+ const names = set.map((c) => c.name);
+ for (const name of [...Object.keys(COMMAND_HANDLERS), 'start', 'link', 'help']) expect(names).toContain(name);
+ const three = set.find((c) => c.name === 'three');
+ expect(three.options.map((o) => o.name)).toEqual(names.filter((n) => n !== 'three'));
+ for (const c of set) {
+ expect(c.name).toMatch(/^[a-z0-9_-]{1,32}$/);
+ expect(c.description.length).toBeLessThanOrEqual(100);
+ for (const o of c.options || []) expect(o.name).toMatch(/^[a-z0-9_-]{1,32}$/);
+ }
+ expect(set.find((c) => c.name === 'voice').options[0].choices.map((ch) => ch.value)).toEqual(['on', 'off']);
+ });
+
+ it('publishes a valid Telegram command menu', () => {
+ const set = telegramCommandSet();
+ expect(set[0]).toEqual({ command: 'start', description: 'Get a pairing code for this chat' });
+ for (const c of set) expect(c.command).toMatch(/^[a-z0-9_]{1,32}$/);
+ });
+});
diff --git a/workers/agent-gateway/tests/telegram-adapter.test.js b/workers/agent-gateway/tests/telegram-adapter.test.js
new file mode 100644
index 000000000..69e1b343f
--- /dev/null
+++ b/workers/agent-gateway/tests/telegram-adapter.test.js
@@ -0,0 +1,188 @@
+// The Telegram adapter: update normalisation and the send surface, with the
+// Bot API answered at its boundary (tests/_telegram.js).
+
+import { readFileSync } from 'node:fs';
+import { describe, it, expect } from 'vitest';
+import { createTelegramAdapter, parseTelegramCommand, toPlatformError } from '../src/adapters/telegram.js';
+import { PlatformError } from '../src/errors.js';
+import { fakeBotApi, telegramEnv, FIXTURE_TOKEN } from './_telegram.js';
+
+const fixture = (name) => JSON.parse(readFileSync(new URL(`./fixtures/${name}.json`, import.meta.url), 'utf8'));
+
+function adapterWith(answer, opts = {}) {
+ const bot = fakeBotApi(answer);
+ return { bot, adapter: createTelegramAdapter({ env: telegramEnv, api: bot.api, ...opts }) };
+}
+
+describe('parseTelegramCommand', () => {
+ it('reads commands, arguments and the bot suffix', () => {
+ expect(parseTelegramCommand('/help')).toEqual({ command: 'help', args: '' });
+ expect(parseTelegramCommand('/USE 2', 'threewsbot')).toEqual({ command: 'use', args: '2' });
+ expect(parseTelegramCommand('/link@threewsbot ABCD-EFGH', 'threewsbot')).toEqual({ command: 'link', args: 'ABCD-EFGH' });
+ expect(parseTelegramCommand('/start@SomeOtherBot', 'threewsbot')).toEqual({ foreign: true });
+ expect(parseTelegramCommand('hello /help')).toBeNull();
+ });
+});
+
+describe('telegram normalize', () => {
+ const { adapter } = adapterWith();
+
+ it('turns a command message into a command event', () => {
+ expect(adapter.normalize(fixture('telegram-update-help'))).toMatchObject({
+ platform: 'telegram', chatId: '5550001001', chatType: 'private', userId: '5550001001', username: 'fixture_owner', command: 'help', args: '',
+ });
+ });
+
+ it('keeps a group title and strips the bot suffix', () => {
+ expect(adapter.normalize(fixture('telegram-update-start-group'))).toMatchObject({ chatId: '-1005550002002', chatTitle: 'Fixture Traders', command: 'start' });
+ });
+
+ it('ignores a command meant for another bot in the same group', () => {
+ const u = fixture('telegram-update-start-group');
+ u.message.text = '/start@SomeOtherBot';
+ expect(adapter.normalize(u)).toBeNull();
+ });
+
+ it('turns plain text into a text event and drops a mention of the bot', () => {
+ const u = fixture('telegram-update-text');
+ expect(adapter.normalize(u)).toMatchObject({ text: 'what is my balance?' });
+ u.message.text = '@threewsbot what is my balance?';
+ expect(adapter.normalize(u).text).toBe('what is my balance?');
+ });
+
+ it('maps an Approve or Cancel press to an action with the pressed message', () => {
+ const u = fixture('telegram-update-callback');
+ u.callback_query.data = 'gw:ap:0c7f9a52-3f0e-4c61-9d0f-1f1e2d3c4b5a';
+ expect(adapter.normalize(u)).toMatchObject({
+ action: { verb: 'approve', previewId: '0c7f9a52-3f0e-4c61-9d0f-1f1e2d3c4b5a' },
+ messageRef: { chatId: '5550001001', messageId: 4190 },
+ callbackQueryId: '4382910029381273001',
+ userId: '5550001001',
+ });
+ });
+
+ it('ignores buttons it did not create and messages from bots', () => {
+ const press = fixture('telegram-update-callback');
+ press.callback_query.data = 'something-else';
+ expect(adapter.normalize(press)).toBeNull();
+ const botMsg = fixture('telegram-update-text');
+ botMsg.message.from.is_bot = true;
+ expect(adapter.normalize(botMsg)).toBeNull();
+ expect(adapter.normalize({ update_id: 1, edited_message: {} })).toBeNull();
+ });
+
+ it('fetches a voice note through getFile and the file endpoint', async () => {
+ const requested = [];
+ const fetchImpl = async (url) => {
+ requested.push(url);
+ return new Response(Buffer.from('OggS-fixture-bytes'), { headers: { 'content-type': 'application/octet-stream' } });
+ };
+ const { bot, adapter: a } = adapterWith(undefined, { fetch: fetchImpl });
+ const event = a.normalize(fixture('telegram-update-voice'));
+ const { buffer, mimeType } = await event.voice.fetch();
+ expect(bot.of('getFile')[0].payload.file_id).toBe('AwACAgEAAxkBAAIQ-fixture-voice');
+ expect(requested[0]).toBe(`https://api.telegram.org/file/bot${FIXTURE_TOKEN}/voice/AwACAgEAAxkBAAIQ-fixture-voice.oga`);
+ expect(buffer.toString()).toBe('OggS-fixture-bytes');
+ expect(mimeType).toBe('audio/ogg');
+ });
+
+ it('takes the largest photo size and keeps the caption', async () => {
+ const fetchImpl = async () => new Response(Buffer.from([0xff, 0xd8]), { headers: { 'content-type': 'image/jpeg' } });
+ const { bot, adapter: a } = adapterWith(undefined, { fetch: fetchImpl });
+ const event = a.normalize(fixture('telegram-update-photo'));
+ expect(event.photo.caption).toBe('is this chart bullish?');
+ const { mimeType } = await event.photo.fetch();
+ expect(bot.of('getFile')[0].payload.file_id).toBe('AgACAgEAAxkBAAIQ-fixture-large');
+ expect(mimeType).toBe('image/jpeg');
+ });
+});
+
+describe('telegram gateway', () => {
+ it('splits a long reply into several messages and returns the last one', async () => {
+ const { bot, adapter } = adapterWith();
+ const paragraph = 'word '.repeat(700).trim();
+ const ref = await adapter.gateway().sendText('42', `${paragraph}\n\n${paragraph}`);
+ const sent = bot.of('sendMessage');
+ expect(sent.length).toBe(2);
+ for (const s of sent) expect(s.payload.text.length).toBeLessThanOrEqual(4000);
+ expect(sent[0].payload.link_preview_options).toEqual({ is_disabled: true });
+ expect(ref).toEqual({ chatId: '42', messageId: 9001 });
+ });
+
+ it('renders choices as one row of inline buttons and removes them on edit', async () => {
+ const { bot, adapter } = adapterWith();
+ const gw = adapter.gateway();
+ const ref = await gw.sendChoice('42', 'Buy preview', [{ id: 'gw:ap:x', label: 'Approve', style: 'primary' }, { id: 'gw:cx:x', label: 'Cancel', style: 'danger' }]);
+ expect(bot.of('sendMessage')[0].payload.reply_markup).toEqual({ inline_keyboard: [[{ text: 'Approve', callback_data: 'gw:ap:x' }, { text: 'Cancel', callback_data: 'gw:cx:x' }]] });
+ await gw.editMessage(ref, 'Cancelled', { choices: [] });
+ expect(bot.of('editMessageText')[0].payload).toMatchObject({ chat_id: '42', message_id: 9000, text: 'Cancelled', reply_markup: { inline_keyboard: [] } });
+ await gw.editMessage(ref, 'working: get_quote');
+ expect(bot.of('editMessageText')[1].payload.reply_markup).toBeUndefined();
+ });
+
+ it('treats an edit to identical text as done', async () => {
+ const { adapter } = adapterWith((m) => (m === 'editMessageText' ? { ok: false, error_code: 400, description: 'Bad Request: message is not modified' } : undefined));
+ await expect(adapter.gateway().editMessage({ chatId: '42', messageId: 1 }, 'same')).resolves.toBeUndefined();
+ });
+
+ it('sends rendered images as photos and other files as documents', async () => {
+ const { bot, adapter } = adapterWith();
+ const gw = adapter.gateway();
+ await gw.sendMedia('42', { url: 'https://three.ws/api/render/glb?glbUrl=https%3A%2F%2Fthree.ws%2Fa.glb', caption: 'Your avatar' });
+ await gw.sendMedia('42', { url: 'https://three.ws/models/a.glb' });
+ expect(bot.of('sendPhoto')[0].payload).toMatchObject({ chat_id: '42', caption: 'Your avatar' });
+ expect(bot.of('sendDocument')[0].payload.document).toBe('https://three.ws/models/a.glb');
+ });
+
+ it('answers a button press, and tolerates a press answered too late', async () => {
+ const { bot, adapter } = adapterWith((m) => (m === 'answerCallbackQuery' && bot.of('answerCallbackQuery').length > 1 ? { ok: false, error_code: 400, description: 'Bad Request: query is too old' } : undefined));
+ const gw = adapter.gateway();
+ await gw.ackAction({ callbackQueryId: 'q1' }, 'Cancelled');
+ await expect(gw.ackAction({ callbackQueryId: 'q2' }, 'Cancelled')).resolves.toBeUndefined();
+ expect(bot.of('answerCallbackQuery')[0].payload).toEqual({ callback_query_id: 'q1', text: 'Cancelled' });
+ });
+
+ it('sends a spoken reply as a voice note and shows typing', async () => {
+ const { bot, adapter } = adapterWith();
+ const gw = adapter.gateway();
+ await gw.sendVoice('42', { buffer: Buffer.from('OggS'), mimeType: 'audio/ogg', filename: 'reply.ogg' });
+ await gw.typing('42');
+ expect(bot.of('sendVoice')).toHaveLength(1);
+ expect(bot.of('sendChatAction')[0].payload).toEqual({ chat_id: '42', action: 'typing' });
+ });
+});
+
+describe('telegram error mapping', () => {
+ it('marks refusals permanent and rate limits retryable with their wait', async () => {
+ const { adapter } = adapterWith((m, p) => {
+ if (p.chat_id === 'blocked') return { ok: false, error_code: 403, description: 'Forbidden: bot was blocked by the user' };
+ if (p.chat_id === 'busy') return { ok: false, error_code: 429, description: 'Too Many Requests: retry after 7', parameters: { retry_after: 7 } };
+ return undefined;
+ });
+ const gw = adapter.gateway();
+ const blocked = await gw.sendText('blocked', 'hi').catch((e) => e);
+ expect(blocked).toBeInstanceOf(PlatformError);
+ expect(blocked).toMatchObject({ platform: 'telegram', status: 403, permanent: true });
+ const busy = await gw.sendText('busy', 'hi').catch((e) => e);
+ expect(busy).toMatchObject({ status: 429, permanent: false, retryAfterMs: 7000 });
+ });
+
+ it('passes through errors that are not from the Bot API', () => {
+ const e = new Error('db down');
+ expect(toPlatformError(e)).toBe(e);
+ });
+});
+
+describe('telegram polling guard', () => {
+ it('refuses to poll while a webhook is set, so production is never cut off', async () => {
+ const errors = [];
+ const { bot, adapter } = adapterWith((m) => (m === 'getWebhookInfo' ? { ok: true, result: { url: 'https://three.ws/api/gateway/telegram', pending_update_count: 0, has_custom_certificate: false } } : undefined), {
+ config: { telegramPolling: true },
+ log: { info() {}, warn() {}, error: (msg) => errors.push(msg) },
+ });
+ await adapter.start({ enqueue: async () => true });
+ expect(errors[0]).toMatch(/polling refused/);
+ expect(bot.of('deleteWebhook')).toHaveLength(0);
+ expect(adapter.describe().mode).toBe('webhook');
+ });
+});
diff --git a/workers/agent-gateway/vitest.config.js b/workers/agent-gateway/vitest.config.js
new file mode 100644
index 000000000..7abc0d2a6
--- /dev/null
+++ b/workers/agent-gateway/vitest.config.js
@@ -0,0 +1,18 @@
+// Worker test config. The worker shares the repo's vitest install (resolved from
+// the root node_modules) and imports the gateway core from api/_lib/gateway, so
+// tests run with the repo root as the server root and this directory's tests
+// as the only include.
+
+import { defineConfig } from 'vitest/config';
+import { fileURLToPath } from 'node:url';
+
+export default defineConfig({
+ root: fileURLToPath(new URL('../..', import.meta.url)),
+ test: {
+ environment: 'node',
+ include: ['workers/agent-gateway/tests/**/*.test.js'],
+ testTimeout: 60_000,
+ hookTimeout: 120_000,
+ pool: 'forks',
+ },
+});