diff --git a/README.md b/README.md index 44f033851..ab3f3d032 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ For news and updates, [follow us on Threads](https://www.threads.com/@itsaplande - A run starts on an @mention in a comment on an issue or a document, on an assignment, or on a schedule. A schedule starts on a timer or when an issue moves to a state - Tokens and cost of every run, by agent, project, and model -- Tools for other services: Notion, Baserow, Telegram, Slack, Threads, Instagram, Jina, +- Tools for other services: Notion, Baserow, Telegram, Slack, Threads, X, Instagram, Jina, Firecrawl, Keenable, DataForSEO, Gitea, Forgejo, GitHub, and GitLab - Images, video, music, and speech from the models on [Kie](https://kie.ai?ref=0b6eb19939298accdf58e18b1a92a26e): Nano Banana, Seedream, Kling, diff --git a/packages/agent-tools/src/registry.ts b/packages/agent-tools/src/registry.ts index 818fa5cbf..ce7dde079 100644 --- a/packages/agent-tools/src/registry.ts +++ b/packages/agent-tools/src/registry.ts @@ -14,6 +14,7 @@ import { firecrawl } from './tools/firecrawl'; import { telegram } from './tools/telegram'; import { slack } from './tools/slack'; import { threads } from './tools/threads'; +import { x } from './tools/x'; import { instagram } from './tools/instagram'; import { notion } from './tools/notion'; import { baserow } from './tools/baserow'; @@ -33,6 +34,7 @@ export const INTEGRATIONS: Integration[] = [ telegram, slack, threads, + x, instagram, notion, baserow, diff --git a/packages/agent-tools/src/tools/x/__tests__/x.test.ts b/packages/agent-tools/src/tools/x/__tests__/x.test.ts new file mode 100644 index 000000000..eecce6530 --- /dev/null +++ b/packages/agent-tools/src/tools/x/__tests__/x.test.ts @@ -0,0 +1,163 @@ +import { afterAll, afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import { ResponseTooLargeError, UrlNotAllowedError } from '@repo/net'; + +const pinnedFetch = mock( + async (_url: string) => new Response('png-bytes', { headers: { 'content-type': 'image/png' } }), +); +mock.module('@repo/net', () => ({ pinnedFetch, ResponseTooLargeError, UrlNotAllowedError })); + +const { getTool } = await import('../../../registry'); +const { authorization } = await import('../client'); +const { xPost } = await import('../post'); +const { xSearch } = await import('../search'); +const { xGetPost } = await import('../get-post'); +const { verifyX } = await import('../verify'); +const { xLike } = await import('../interactions'); +const { xHomeTimeline } = await import('../timelines'); + +const fetchSpy = spyOn(globalThis, 'fetch'); +const credential = { + apiKey: 'ck', + apiKeySecret: 'cs', + accessToken: 'at', + accessTokenSecret: 'ats', +}; + +function calls() { + return fetchSpy.mock.calls.map(([url, init]) => ({ + url: String(url), + init: init as RequestInit & { headers: Record }, + })); +} + +describe('x', () => { + beforeEach(() => pinnedFetch.mockClear()); + afterEach(() => fetchSpy.mockReset()); + afterAll(() => fetchSpy.mockRestore()); + + it('is registered with four secret fields', () => { + const integration = getTool('x_post')?.integration; + expect(integration?.key).toBe('x'); + expect(integration?.credentialSchema.map((f) => [f.key, f.type])).toEqual([ + ['apiKey', 'secret'], + ['apiKeySecret', 'secret'], + ['accessToken', 'secret'], + ['accessTokenSecret', 'secret'], + ]); + }); + + // The worked example of X's "Creating a signature" guide. + it('signs a request as the OAuth 1.0a guide does', () => { + const header = authorization( + { + apiKey: 'xvz1evFS4wEEPTGEFPHBog', + apiKeySecret: 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw', + accessToken: '370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb', + accessTokenSecret: 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE', + }, + 'POST', + 'https://api.twitter.com/1.1/statuses/update.json', + [ + ['status', 'Hello Ladies + Gentlemen, a signed OAuth request!'], + ['include_entities', 'true'], + ], + { nonce: 'kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg', timestamp: 1318622958 }, + ); + expect(header).toContain('oauth_signature="hCtSmYh%2BiHYCEqBWrE7C7hYmtUk%3D"'); + }); + + it('uploads each image, then posts a reply with their media ids', async () => { + fetchSpy + .mockResolvedValueOnce(Response.json({ data: { id: 'm1' } })) + .mockResolvedValueOnce( + Response.json({ data: { id: '42', text: 'Shipped' } }, { status: 201 }), + ); + const result = await xPost.execute(credential, { + text: 'Shipped', + imageUrls: ['https://cdn.example.com/a.png'], + replyToId: '7', + }); + + expect(pinnedFetch.mock.calls[0]?.[0]).toBe('https://cdn.example.com/a.png'); + const [upload, post] = calls(); + expect(upload?.url).toBe('https://api.x.com/2/media/upload'); + const form = upload?.init.body as FormData; + expect(form.get('media_category')).toBe('tweet_image'); + expect(form.get('media')).toBeInstanceOf(Blob); + expect(post?.url).toBe('https://api.x.com/2/tweets'); + expect(post?.init.headers.Authorization).toStartWith('OAuth oauth_consumer_key="ck"'); + expect(JSON.parse(String(post?.init.body))).toEqual({ + text: 'Shipped', + media: { media_ids: ['m1'] }, + reply: { in_reply_to_tweet_id: '7' }, + }); + expect(result).toEqual({ id: '42', text: 'Shipped', url: 'https://x.com/i/status/42' }); + }); + + it('encodes query values by RFC 3986 and sends start_time without milliseconds', async () => { + fetchSpy.mockResolvedValueOnce(Response.json({ meta: { result_count: 0 } })); + const result = await xSearch.execute(credential, { + query: 'from:me (a) b', + startTime: '2026-11-25', + }); + + const url = new URL(calls()[0]!.url); + expect(url.search).toContain('query=from%3Ame%20%28a%29%20b'); + expect(url.searchParams.get('start_time')).toBe('2026-11-25T00:00:00Z'); + expect(result).toEqual({ data: [], includes: null, meta: { result_count: 0 } }); + }); + + it('fails with the detail X sends, also on a 200 with no data', async () => { + fetchSpy.mockResolvedValueOnce( + Response.json({ + errors: [{ title: 'Not Found Error', detail: 'Could not find post with id: [9].' }], + }), + ); + await expect(xGetPost.execute(credential, { postId: '9' })).rejects.toThrow( + 'X API error (200): Could not find post with id: [9].', + ); + }); + + it('likes as the account the credential acts as, and undoes the like', async () => { + fetchSpy + .mockResolvedValueOnce(Response.json({ data: { id: '5' } })) + .mockResolvedValueOnce(Response.json({ data: { liked: true } })) + .mockResolvedValueOnce(Response.json({ data: { id: '5' } })) + .mockResolvedValueOnce(Response.json({ data: { liked: false } })); + expect(await xLike.execute(credential, { postId: '42' })).toEqual({ + postId: '42', + liked: true, + }); + expect(await xLike.execute(credential, { postId: '42', undo: true })).toEqual({ + postId: '42', + liked: false, + }); + + const [, like, , unlike] = calls(); + expect(like?.url).toBe('https://api.x.com/2/users/5/likes'); + expect(JSON.parse(String(like?.init.body))).toEqual({ tweet_id: '42' }); + expect([unlike?.init.method, unlike?.url]).toEqual([ + 'DELETE', + 'https://api.x.com/2/users/5/likes/42', + ]); + }); + + it('reads the home timeline of the own account without the left-out kinds', async () => { + fetchSpy + .mockResolvedValueOnce(Response.json({ data: { id: '5' } })) + .mockResolvedValueOnce(Response.json({ data: [{ id: '1', text: 'hi' }], meta: {} })); + const result = await xHomeTimeline.execute(credential, { exclude: ['replies', 'retweets'] }); + + const url = new URL(calls()[1]!.url); + expect(url.pathname).toBe('/2/users/5/timelines/reverse_chronological'); + expect(url.searchParams.get('exclude')).toBe('replies,retweets'); + expect(result).toMatchObject({ data: [{ id: '1', text: 'hi' }] }); + }); + + it('rejects a credential X answers 401 to', async () => { + fetchSpy.mockResolvedValueOnce(Response.json({ title: 'Unauthorized' }, { status: 401 })); + expect(await verifyX(credential, AbortSignal.timeout(1000))).toBe('rejected'); + fetchSpy.mockResolvedValueOnce(Response.json({ data: { id: '1' } })); + expect(await verifyX(credential, AbortSignal.timeout(1000))).toBe('valid'); + }); +}); diff --git a/packages/agent-tools/src/tools/x/client.ts b/packages/agent-tools/src/tools/x/client.ts new file mode 100644 index 000000000..914a2a5e0 --- /dev/null +++ b/packages/agent-tools/src/tools/x/client.ts @@ -0,0 +1,135 @@ +import { createHmac, randomBytes } from 'node:crypto'; +import type { ToolConfig } from '../../types'; +import { timeFilter, toUnixSeconds } from '../time'; + +// X API v2. A credential is the app's key pair plus the access token pair of one account, +// for OAuth 1.0a: those tokens do not expire, while an OAuth 2.0 user token lasts two hours. +export const X_BASE = 'https://api.x.com/2'; + +// RFC 3986, which OAuth 1.0a signs with: encodeURIComponent leaves !'()* unencoded. +function pct(s: string): string { + return encodeURIComponent(s).replace( + /[!'()*]/g, + (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, + ); +} + +function compare(a: string, b: string): number { + if (a === b) return 0; + return a < b ? -1 : 1; +} + +// The signature covers the method, the address and the query parameters. A JSON or +// multipart body is not signed. +export function authorization( + credential: ToolConfig, + method: string, + url: string, + params: [string, string][] = [], + oauth = { nonce: randomBytes(16).toString('hex'), timestamp: Math.floor(Date.now() / 1000) }, +): string { + const fields: Record = { + oauth_consumer_key: String(credential.apiKey ?? ''), + oauth_nonce: oauth.nonce, + oauth_signature_method: 'HMAC-SHA1', + oauth_timestamp: String(oauth.timestamp), + oauth_token: String(credential.accessToken ?? ''), + oauth_version: '1.0', + }; + const pairs = [...params, ...Object.entries(fields)].map(([k, v]) => [pct(k), pct(v)]); + pairs.sort(([ak, av], [bk, bv]) => compare(ak, bk) || compare(av, bv)); + const base = [method, pct(url), pct(pairs.map(([k, v]) => `${k}=${v}`).join('&'))].join('&'); + const key = `${pct(String(credential.apiKeySecret ?? ''))}&${pct(String(credential.accessTokenSecret ?? ''))}`; + const signature = createHmac('sha1', key).update(base).digest('base64'); + return `OAuth ${Object.entries({ ...fields, oauth_signature: signature }) + .map(([k, v]) => `${k}="${pct(v)}"`) + .join(', ')}`; +} + +type XProblem = { title?: string; detail?: string; message?: string }; + +export interface XResponse { + data?: T; + includes?: unknown; + meta?: Record; + errors?: XProblem[]; +} + +// A lookup of a missing or deleted post answers 200 with errors and no data, so that is +// a failure too. +export async function xRequest( + credential: ToolConfig, + method: 'GET' | 'POST' | 'DELETE', + path: string, + opts: { + query?: Record; + json?: unknown; + form?: FormData; + } = {}, +): Promise> { + const url = `${X_BASE}/${path}`; + const params = Object.entries(opts.query ?? {}) + .filter(([, v]) => v !== undefined && v !== '') + .map(([k, v]): [string, string] => [k, String(v)]); + const query = params.map(([k, v]) => `${pct(k)}=${pct(v)}`).join('&'); + const headers: Record = { + Authorization: authorization(credential, method, url, params), + }; + let body: string | FormData | undefined = opts.form; + if (opts.json !== undefined) { + headers['Content-Type'] = 'application/json'; + body = JSON.stringify(opts.json); + } + const res = await fetch(query ? `${url}?${query}` : url, { method, headers, body }); + const raw = await res.text(); + let parsed: XResponse & XProblem = {}; + try { + parsed = raw ? JSON.parse(raw) : {}; + } catch { + /* non-JSON error page */ + } + let problem: XProblem | undefined; + if (!res.ok) problem = parsed.errors?.[0] ?? parsed; + else if (parsed.data === undefined) problem = parsed.errors?.[0]; + if (problem) { + const msg = problem.detail || problem.message || problem.title || raw.slice(0, 300); + throw new Error(`X API error (${res.status})${msg ? `: ${msg}` : ''}`); + } + return parsed; +} + +export async function myId(credential: ToolConfig): Promise { + const body = await xRequest<{ id: string }>(credential, 'GET', 'users/me'); + return String(body.data?.id); +} + +// The author is expanded so a result names who wrote each post. +export const POST_QUERY = { + 'post.fields': 'created_at,conversation_id,public_metrics', + expansions: 'author_id', + 'user.fields': 'username,name', +}; + +export const USER_FIELDS = + 'description,location,url,created_at,verified,public_metrics,profile_image_url'; + +export function page(body: XResponse) { + return { data: body.data ?? [], includes: body.includes ?? null, meta: body.meta ?? null }; +} + +export function usernamePath(username: unknown): string { + return `users/by/username/${encodeURIComponent(String(username).replace(/^@/, ''))}`; +} + +// A second describe() replaces the first, so each field gets its whole text here. +export function timeInput(meaning: string) { + return timeFilter + .optional() + .describe(`${meaning} A date like "2026-06-14", an ISO time, or a unix timestamp in seconds.`); +} + +// X takes RFC 3339 times without milliseconds. +export function isoTime(v: unknown): string | undefined { + const s = toUnixSeconds(v as number | string | undefined); + return s === undefined ? undefined : new Date(s * 1000).toISOString().replace('.000Z', 'Z'); +} diff --git a/packages/agent-tools/src/tools/x/delete.ts b/packages/agent-tools/src/tools/x/delete.ts new file mode 100644 index 000000000..2e05e6eae --- /dev/null +++ b/packages/agent-tools/src/tools/x/delete.ts @@ -0,0 +1,18 @@ +import { z } from 'zod'; +import type { CustomToolEntry } from '../../types'; +import { xRequest } from './client'; + +export const xDeletePost: CustomToolEntry = { + key: 'x_delete_post', + group: 'Publishing', + label: 'X Delete Post', + description: 'Delete one of your own posts or replies on X by its id.', + inputSchema: z.object({ + postId: z.string().min(1).describe('Id of the post to delete.'), + }), + execute: async (credential, input) => { + const postId = String(input.postId); + await xRequest(credential, 'DELETE', `tweets/${encodeURIComponent(postId)}`); + return { deleted: true, postId }; + }, +}; diff --git a/packages/agent-tools/src/tools/x/get-post.ts b/packages/agent-tools/src/tools/x/get-post.ts new file mode 100644 index 000000000..ae3370d9b --- /dev/null +++ b/packages/agent-tools/src/tools/x/get-post.ts @@ -0,0 +1,23 @@ +import { z } from 'zod'; +import type { CustomToolEntry } from '../../types'; +import { POST_QUERY, xRequest } from './client'; + +export const xGetPost: CustomToolEntry = { + key: 'x_get_post', + group: 'Posts and profiles', + label: 'X Get Post', + description: + 'Get a post on X by its id: text, author, time, conversation id and like, repost and reply counts.', + inputSchema: z.object({ + postId: z.string().min(1).describe('Id of the post, the number at the end of its URL.'), + }), + execute: async (credential, input) => { + const { data, includes } = await xRequest( + credential, + 'GET', + `tweets/${encodeURIComponent(String(input.postId))}`, + { query: POST_QUERY }, + ); + return { data, includes: includes ?? null }; + }, +}; diff --git a/packages/agent-tools/src/tools/x/icon.ts b/packages/agent-tools/src/tools/x/icon.ts new file mode 100644 index 000000000..b4e9906b3 --- /dev/null +++ b/packages/agent-tools/src/tools/x/icon.ts @@ -0,0 +1,6 @@ +import type { IntegrationIcon } from '../../types'; + +// From Simple Icons (CC0). The mark is black, so it takes the text color. +export const xIcon: IntegrationIcon = { + path: 'M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z', +}; diff --git a/packages/agent-tools/src/tools/x/index.ts b/packages/agent-tools/src/tools/x/index.ts new file mode 100644 index 000000000..03c884823 --- /dev/null +++ b/packages/agent-tools/src/tools/x/index.ts @@ -0,0 +1,67 @@ +import type { Integration } from '../../types'; +import { xPost } from './post'; +import { xDeletePost } from './delete'; +import { xGetProfile, xGetUser } from './profile'; +import { xGetPost } from './get-post'; +import { xListPosts, xListMentions, xHomeTimeline } from './timelines'; +import { xSearch } from './search'; +import { xLike, xRepost } from './interactions'; +import { xIcon } from './icon'; +import { verifyX } from './verify'; + +const KEYS_HELP = + 'In the [X Developer Console](https://console.x.com), open your app and its **Keys and tokens** page.'; + +export const x: Integration = { + key: 'x', + label: 'X', + description: 'Publishes posts and replies, reads mentions and searches posts on X (Twitter).', + icon: xIcon, + website: 'https://x.com', + credentialSchema: [ + { + key: 'apiKey', + label: 'Consumer key', + type: 'secret', + required: true, + help: `${KEYS_HELP} Copy the Consumer Key.`, + }, + { + key: 'apiKeySecret', + label: 'Consumer secret', + type: 'secret', + required: true, + help: `${KEYS_HELP} Copy the Consumer Secret.`, + }, + { + key: 'accessToken', + label: 'Access token', + type: 'secret', + required: true, + help: + `${KEYS_HELP} Generate the access token and secret. They belong to the X account that owns the app, and the agent posts as that account.\n\n` + + 'To publish, set the app permissions to **Read and write** in its user authentication settings first. A token generated before that change can only read.', + }, + { + key: 'accessTokenSecret', + label: 'Access token secret', + type: 'secret', + required: true, + help: `${KEYS_HELP} It is shown together with the access token.`, + }, + ], + verify: verifyX, + tools: [ + xPost, + xDeletePost, + xLike, + xRepost, + xGetProfile, + xGetUser, + xGetPost, + xListPosts, + xListMentions, + xHomeTimeline, + xSearch, + ], +}; diff --git a/packages/agent-tools/src/tools/x/interactions.ts b/packages/agent-tools/src/tools/x/interactions.ts new file mode 100644 index 000000000..4c2e18033 --- /dev/null +++ b/packages/agent-tools/src/tools/x/interactions.ts @@ -0,0 +1,45 @@ +import { z } from 'zod'; +import type { CustomToolEntry } from '../../types'; +import { myId, xRequest } from './client'; + +export const xLike: CustomToolEntry = { + key: 'x_like', + group: 'Interactions', + label: 'X Like/Unlike Post', + description: 'Like a post on X, or remove your like with undo.', + inputSchema: z.object({ + postId: z.string().min(1).describe('Id of the post.'), + undo: z.boolean().optional().describe('true to remove the like.'), + }), + execute: async (credential, input) => { + const id = await myId(credential); + const postId = String(input.postId); + if (input.undo === true) { + await xRequest(credential, 'DELETE', `users/${id}/likes/${encodeURIComponent(postId)}`); + } else { + await xRequest(credential, 'POST', `users/${id}/likes`, { json: { tweet_id: postId } }); + } + return { postId, liked: input.undo !== true }; + }, +}; + +export const xRepost: CustomToolEntry = { + key: 'x_repost', + group: 'Interactions', + label: 'X Repost/Undo Repost', + description: 'Repost a post on X to your followers, or remove your repost with undo.', + inputSchema: z.object({ + postId: z.string().min(1).describe('Id of the post.'), + undo: z.boolean().optional().describe('true to remove the repost.'), + }), + execute: async (credential, input) => { + const id = await myId(credential); + const postId = String(input.postId); + if (input.undo === true) { + await xRequest(credential, 'DELETE', `users/${id}/retweets/${encodeURIComponent(postId)}`); + } else { + await xRequest(credential, 'POST', `users/${id}/retweets`, { json: { tweet_id: postId } }); + } + return { postId, reposted: input.undo !== true }; + }, +}; diff --git a/packages/agent-tools/src/tools/x/media.ts b/packages/agent-tools/src/tools/x/media.ts new file mode 100644 index 000000000..9bd809cb1 --- /dev/null +++ b/packages/agent-tools/src/tools/x/media.ts @@ -0,0 +1,46 @@ +import { pinnedFetch, ResponseTooLargeError, UrlNotAllowedError } from '@repo/net'; +import type { ToolConfig } from '../../types'; +import { xRequest } from './client'; + +// X's limit for an image in a post. +const MAX_IMAGE_MB = 5; +const MAX_REDIRECTS = 5; + +// Each hop goes through the SSRF guard again, so a redirect cannot lead to an address +// the first check never saw. +async function download(url: string): Promise { + let current = url; + for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { + let res: Response; + try { + res = await pinnedFetch(current, { + publicOnly: true, + timeoutMs: 30_000, + maxBytes: MAX_IMAGE_MB * 1024 * 1024, + }); + } catch (err) { + if (err instanceof UrlNotAllowedError) + throw new Error(`Cannot fetch ${current}: ${err.message}.`); + if (err instanceof ResponseTooLargeError) + throw new Error(`The image ${url} is larger than ${MAX_IMAGE_MB} MB.`); + throw new Error(`Could not fetch ${current}.`); + } + const location = res.headers.get('location'); + if (res.status >= 300 && res.status < 400 && location) { + current = new URL(location, current).toString(); + continue; + } + if (!res.ok) throw new Error(`Could not fetch ${current} (status ${res.status}).`); + return new Blob([await res.arrayBuffer()], { type: res.headers.get('content-type') ?? '' }); + } + throw new Error(`${url} redirects more than ${MAX_REDIRECTS} times.`); +} + +// Returns the media id a post attaches. +export async function uploadImage(credential: ToolConfig, url: string): Promise { + const form = new FormData(); + form.append('media', await download(url)); + form.append('media_category', 'tweet_image'); + const body = await xRequest<{ id: string }>(credential, 'POST', 'media/upload', { form }); + return String(body.data?.id); +} diff --git a/packages/agent-tools/src/tools/x/post.ts b/packages/agent-tools/src/tools/x/post.ts new file mode 100644 index 000000000..774b547fe --- /dev/null +++ b/packages/agent-tools/src/tools/x/post.ts @@ -0,0 +1,62 @@ +import { z } from 'zod'; +import type { CustomToolEntry } from '../../types'; +import { xRequest } from './client'; +import { uploadImage } from './media'; + +export const xPost: CustomToolEntry = { + key: 'x_post', + group: 'Publishing', + label: 'X Publish Post', + description: + 'Publish a post on X, or a reply when replyToId is given. Provide text and/or up to 4 public image URLs (JPG, PNG, GIF or WEBP, up to 5 MB each), or a poll. Returns the post id and its URL.', + inputSchema: z.object({ + text: z + .string() + .optional() + .describe( + 'Post text. At most 280 characters unless the account has X Premium. Required when no image is given.', + ), + imageUrls: z + .array(z.string().url()) + .max(4) + .optional() + .describe('Public image URLs to attach, up to 4. Cannot be combined with a poll.'), + replyToId: z.string().optional().describe('Id of the post to reply to.'), + pollOptions: z + .array(z.string().min(1).max(25)) + .min(2) + .max(4) + .optional() + .describe('2-4 poll choices, up to 25 characters each.'), + pollDurationMinutes: z + .number() + .int() + .min(5) + .max(10080) + .optional() + .describe('How long the poll stays open, 5-10080 minutes. Default 1440 (one day).'), + replySettings: z + .enum(['following', 'mentionedUsers', 'subscribers', 'verified']) + .optional() + .describe('Who may reply. Everyone when left out.'), + }), + execute: async (credential, input) => { + const imageUrls = (input.imageUrls as string[] | undefined) ?? []; + const mediaIds: string[] = []; + for (const url of imageUrls) mediaIds.push(await uploadImage(credential, url)); + const pollOptions = input.pollOptions as string[] | undefined; + const body = await xRequest<{ id: string; text: string }>(credential, 'POST', 'tweets', { + json: { + text: input.text || undefined, + media: mediaIds.length ? { media_ids: mediaIds } : undefined, + reply: input.replyToId ? { in_reply_to_tweet_id: String(input.replyToId) } : undefined, + poll: pollOptions + ? { options: pollOptions, duration_minutes: input.pollDurationMinutes ?? 1440 } + : undefined, + reply_settings: input.replySettings, + }, + }); + const id = String(body.data?.id); + return { id, text: body.data?.text, url: `https://x.com/i/status/${id}` }; + }, +}; diff --git a/packages/agent-tools/src/tools/x/profile.ts b/packages/agent-tools/src/tools/x/profile.ts new file mode 100644 index 000000000..f3fade832 --- /dev/null +++ b/packages/agent-tools/src/tools/x/profile.ts @@ -0,0 +1,34 @@ +import { z } from 'zod'; +import type { CustomToolEntry } from '../../types'; +import { USER_FIELDS, usernamePath, xRequest } from './client'; + +export const xGetProfile: CustomToolEntry = { + key: 'x_get_profile', + group: 'Posts and profiles', + label: 'X Get My Profile', + description: + 'Get the X account the credential posts as: id, username, name, bio and follower counts.', + inputSchema: z.object({}), + execute: async (credential) => { + const body = await xRequest(credential, 'GET', 'users/me', { + query: { 'user.fields': USER_FIELDS }, + }); + return body.data; + }, +}; + +export const xGetUser: CustomToolEntry = { + key: 'x_get_user', + group: 'Posts and profiles', + label: 'X Get User', + description: 'Get an X account by its username: id, name, bio and follower counts.', + inputSchema: z.object({ + username: z.string().min(1).describe('The username, without "@".'), + }), + execute: async (credential, input) => { + const body = await xRequest(credential, 'GET', usernamePath(input.username), { + query: { 'user.fields': USER_FIELDS }, + }); + return body.data; + }, +}; diff --git a/packages/agent-tools/src/tools/x/search.ts b/packages/agent-tools/src/tools/x/search.ts new file mode 100644 index 000000000..3824e19ec --- /dev/null +++ b/packages/agent-tools/src/tools/x/search.ts @@ -0,0 +1,42 @@ +import { z } from 'zod'; +import type { CustomToolEntry } from '../../types'; +import { POST_QUERY, isoTime, page, timeInput, xRequest } from './client'; + +export const xSearch: CustomToolEntry = { + key: 'x_search', + group: 'Search', + label: 'X Search Posts', + description: + 'Search public posts on X from the last 7 days. The query takes X search operators: "from:username", "to:username", "conversation_id:" for the replies to a post, "-is:retweet", "lang:en". To read further, call again with meta.next_token as nextToken.', + inputSchema: z.object({ + query: z.string().min(1).max(4096).describe('The search query.'), + sortOrder: z + .enum(['recency', 'relevancy']) + .optional() + .describe('recency (default) or relevancy.'), + startTime: timeInput('Only posts at or after this time, within the last 7 days.'), + endTime: timeInput('Only posts before this time.'), + maxResults: z + .number() + .int() + .min(10) + .max(100) + .optional() + .describe('How many posts to return (10-100, default 10).'), + nextToken: z.string().optional().describe('meta.next_token of the previous call.'), + }), + execute: async (credential, input) => { + const body = await xRequest(credential, 'GET', 'tweets/search/recent', { + query: { + ...POST_QUERY, + query: String(input.query), + sort_order: input.sortOrder as string | undefined, + start_time: isoTime(input.startTime), + end_time: isoTime(input.endTime), + max_results: input.maxResults as number | undefined, + next_token: input.nextToken as string | undefined, + }, + }); + return page(body); + }, +}; diff --git a/packages/agent-tools/src/tools/x/timelines.ts b/packages/agent-tools/src/tools/x/timelines.ts new file mode 100644 index 000000000..9f56f84a5 --- /dev/null +++ b/packages/agent-tools/src/tools/x/timelines.ts @@ -0,0 +1,90 @@ +import { z } from 'zod'; +import type { CustomToolEntry, ToolConfig } from '../../types'; +import { POST_QUERY, isoTime, myId, page, timeInput, usernamePath, xRequest } from './client'; + +const timelineInput = { + startTime: timeInput('Only posts at or after this time.'), + endTime: timeInput('Only posts before this time.'), + maxResults: z + .number() + .int() + .min(5) + .max(100) + .optional() + .describe('How many posts to return (5-100, default 10).'), + paginationToken: z.string().optional().describe('meta.next_token of the previous call.'), +}; + +const excludeInput = z + .array(z.enum(['replies', 'retweets'])) + .optional() + .describe('Leave out replies and/or reposts.'); + +function timelineQuery(input: Record) { + return { + ...POST_QUERY, + start_time: isoTime(input.startTime), + end_time: isoTime(input.endTime), + exclude: (input.exclude as string[] | undefined)?.join(','), + max_results: input.maxResults as number | undefined, + pagination_token: input.paginationToken as string | undefined, + }; +} + +async function userId(credential: ToolConfig, username: unknown): Promise { + if (!username) return myId(credential); + const body = await xRequest<{ id: string }>(credential, 'GET', usernamePath(username)); + return String(body.data?.id); +} + +export const xListPosts: CustomToolEntry = { + key: 'x_list_posts', + group: 'Posts and profiles', + label: 'X List Posts', + description: + "List an account's posts on X, newest first: your own, or another account's by username. To read further, call again with meta.next_token as paginationToken.", + inputSchema: z.object({ + username: z.string().optional().describe('Whose posts, without "@". Your own when left out.'), + exclude: excludeInput, + ...timelineInput, + }), + execute: async (credential, input) => { + const id = await userId(credential, input.username); + const body = await xRequest(credential, 'GET', `users/${id}/tweets`, { + query: timelineQuery(input), + }); + return page(body); + }, +}; + +export const xListMentions: CustomToolEntry = { + key: 'x_list_mentions', + group: 'Posts and profiles', + label: 'X List Mentions', + description: + 'List the posts on X that mention your account, newest first. To read further, call again with meta.next_token as paginationToken.', + inputSchema: z.object(timelineInput), + execute: async (credential, input) => { + const id = await myId(credential); + const body = await xRequest(credential, 'GET', `users/${id}/mentions`, { + query: timelineQuery(input), + }); + return page(body); + }, +}; + +export const xHomeTimeline: CustomToolEntry = { + key: 'x_home_timeline', + group: 'Posts and profiles', + label: 'X Home Timeline', + description: + 'List the home timeline of your X account, newest first: your posts and the posts of the accounts you follow. To read further, call again with meta.next_token as paginationToken.', + inputSchema: z.object({ exclude: excludeInput, ...timelineInput }), + execute: async (credential, input) => { + const id = await myId(credential); + const body = await xRequest(credential, 'GET', `users/${id}/timelines/reverse_chronological`, { + query: timelineQuery(input), + }); + return page(body); + }, +}; diff --git a/packages/agent-tools/src/tools/x/verify.ts b/packages/agent-tools/src/tools/x/verify.ts new file mode 100644 index 000000000..a721e93a0 --- /dev/null +++ b/packages/agent-tools/src/tools/x/verify.ts @@ -0,0 +1,16 @@ +import type { CredentialCheck, ToolConfig } from '../../types'; +import { X_BASE, authorization } from './client'; + +// X bills every request, and reading the account the token belongs to is the cheapest one. +export async function verifyX( + credential: ToolConfig, + signal: AbortSignal, +): Promise { + const url = `${X_BASE}/users/me`; + const res = await fetch(url, { + headers: { Authorization: authorization(credential, 'GET', url) }, + signal, + }); + if (res.status === 401) return 'rejected'; + return res.ok ? 'valid' : 'unavailable'; +}