Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 398 lines 16.2 KB
Raw
1 /**
2 * Cumulative stages of the example's files, built up one piece at a time. Each
3 * stage's `code` is the full file at that point; <FileBuildup> diffs consecutive
4 * stages so the reader watches the file grow from a basic agent to the full bot.
5 */
6
7 export interface BuildStage {
8 title: string;
9 description: string;
10 /** Full file contents at this stage. */
11 code: string;
12 }
13
14 // ── shared bot.ts parts ─────────────────────────────────────────────────────
15
16 const head1 = `import { Composio } from '@composio/core';
17 import { PiProvider } from '@composio/experimental';
18 import { createAgentSession, SessionManager } from '@earendil-works/pi-coding-agent';
19
20 const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
21 const piProvider = new PiProvider();
22 `;
23
24 const head2 = `import { Composio } from '@composio/core';
25 import type { IncomingTriggerPayload } from '@composio/core';
26 import { PiProvider } from '@composio/experimental';
27 import { createAgentSession, SessionManager } from '@earendil-works/pi-coding-agent';
28
29 const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
30 const piProvider = new PiProvider();
31 const callbackUrl = \`\${process.env.APP_URL}/connections/callback\`;
32 `;
33
34 const head2Shared = `import { Composio } from '@composio/core';
35 import type { IncomingTriggerPayload } from '@composio/core';
36 import { PiProvider } from '@composio/experimental';
37 import { createAgentSession, SessionManager } from '@earendil-works/pi-coding-agent';
38
39 const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
40 const piProvider = new PiProvider();
41 const callbackUrl = \`\${process.env.APP_URL}/connections/callback\`;
42
43 // One Slack connection, shared by the whole workspace. The bot posts as this
44 // identity while acting in every other app as the individual user.
45 const SHARED_SLACK_CONNECTION_ID = process.env.SLACK_CONNECTION_ID;
46 `;
47
48 const runPi = `
49 // Run the Pi agent over a session's tools and return its final text.
50 async function runPi(tools: unknown, prompt: string) {
51 const { session: pi } = await createAgentSession({
52 sessionManager: SessionManager.inMemory(process.cwd()),
53 customTools: tools,
54 tools: ['composio_search_tools', 'composio_manage_connections', 'composio_execute_tool'],
55 });
56 let reply = '';
57 pi.subscribe((e) => {
58 if (e.type === 'message_update' && e.assistantMessageEvent.type === 'text_delta') {
59 reply += e.assistantMessageEvent.delta;
60 }
61 });
62 await pi.prompt(prompt);
63 pi.dispose();
64 return reply;
65 }
66 `;
67
68 const runAgent = `
69 // The smallest agent: one session, its tools, one prompt.
70 export async function runAgent(userId: string, prompt: string) {
71 const session = await composio.create(userId);
72 const tools = piProvider.createSessionTools({
73 sessionId: session.sessionId,
74 search: (params) => session.search(params),
75 execute: (slug, args, options) => session.execute(slug, args, options),
76 });
77 return runPi(tools, prompt);
78 }
79 `;
80
81 const memNoPin = `
82 // One session per Slack thread, reused so the agent keeps context, with a short
83 // transcript for memory across turns.
84 const threads = new Map<string, { sessionId: string; history: { role: string; content: string }[] }>();
85 const threadKey = (event: IncomingTriggerPayload) =>
86 \`\${event.payload?.channel}:\${event.payload?.thread_ts ?? event.payload?.ts}\`;
87
88 async function sessionForThread(event: IncomingTriggerPayload) {
89 const key = threadKey(event);
90 const existing = threads.get(key);
91 if (existing) return { session: await composio.use(existing.sessionId), memory: existing };
92
93 const session = await composio.create(event.userId, {
94 manageConnections: { enable: true, callbackUrl, waitForConnections: true },
95 });
96 const memory = { sessionId: session.sessionId, history: [] as { role: string; content: string }[] };
97 threads.set(key, memory);
98 return { session, memory };
99 }
100 `;
101
102 const memPin = `
103 // One session per Slack thread, reused so the agent keeps context, with a short
104 // transcript for memory across turns.
105 const threads = new Map<string, { sessionId: string; history: { role: string; content: string }[] }>();
106 const threadKey = (event: IncomingTriggerPayload) =>
107 \`\${event.payload?.channel}:\${event.payload?.thread_ts ?? event.payload?.ts}\`;
108
109 async function sessionForThread(event: IncomingTriggerPayload) {
110 const key = threadKey(event);
111 const existing = threads.get(key);
112 if (existing) return { session: await composio.use(existing.sessionId), memory: existing };
113
114 const session = await composio.create(event.userId, {
115 // Pin the shared Slack connection; the session still resolves every other
116 // toolkit against this user's own connections.
117 connectedAccounts: { slackbot: [SHARED_SLACK_CONNECTION_ID] },
118 manageConnections: { enable: true, callbackUrl, waitForConnections: true },
119 });
120 const memory = { sessionId: session.sessionId, history: [] as { role: string; content: string }[] };
121 threads.set(key, memory);
122 return { session, memory };
123 }
124 `;
125
126 const proxy = `
127 // Anything the toolkit doesn't wrap as a tool, reach via the proxy: it calls the
128 // Slack Web API with the pinned connection's auth, so you never touch a token.
129 async function setStatus(session, event: IncomingTriggerPayload, status: string) {
130 await session
131 .proxyExecute({
132 toolkit: 'slackbot',
133 endpoint: 'https://slack.com/api/assistant.threads.setStatus',
134 method: 'POST',
135 body: { channel_id: event.payload?.channel, thread_ts: event.payload?.thread_ts, status },
136 })
137 .catch(() => {});
138 }
139
140 async function openDm(session, userId: string): Promise<string> {
141 const res = await session.proxyExecute({
142 toolkit: 'slackbot',
143 endpoint: 'https://slack.com/api/conversations.open',
144 method: 'POST',
145 body: { users: userId },
146 });
147 return res.data?.channel?.id;
148 }
149 `;
150
151 const auth = `
152 // Redirect auth links. When a tool hits an app the user hasn't connected, the
153 // result carries a one-time Composio connect URL. Never let the model or the
154 // channel see it: redact it from the tool output and DM the user privately. The
155 // session's manageConnections + waitForConnections resumes the run on approval.
156 const CONNECT_LINK = /https:\\/\\/(?:connect\\.composio\\.dev|[^\\s"']*composio[^\\s"']*\\/link)\\/[^\\s"')]+/gi;
157
158 function redactLinks<T>(value: T): T {
159 if (typeof value === 'string') return value.replace(CONNECT_LINK, '[connection link sent via DM]') as T;
160 if (Array.isArray(value)) return value.map(redactLinks) as T;
161 if (value && typeof value === 'object') {
162 return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactLinks(v)])) as T;
163 }
164 return value;
165 }
166
167 async function handleAuthLinks<T>(session, event: IncomingTriggerPayload, value: T): Promise<T> {
168 const links = [...new Set([...JSON.stringify(value ?? '').matchAll(CONNECT_LINK)].map((m) => m[0]))];
169 if (links.length > 0) {
170 const dm = await openDm(session, event.userId);
171 for (const url of links) {
172 await session.execute('SLACKBOT_SEND_MESSAGE', {
173 channel: dm,
174 text: \`*Connection needed.* Approve access and I'll continue automatically:\\n<\${url}|Connect>\`,
175 });
176 }
177 }
178 return redactLinks(value); // hand the model a result with the raw URL stripped
179 }
180 `;
181
182 const toolsNoAuth = `
183 function toolsForSession(session) {
184 return piProvider.createSessionTools({
185 sessionId: session.sessionId,
186 callbackUrl,
187 search: (params) => session.search(params),
188 execute: (slug, args, options) => session.execute(slug, args, options),
189 connections: {
190 getToolkitStates: (toolkits) => session.toolkits({ toolkits }),
191 authorizeToolkit: async (toolkit) => {
192 const request = await session.authorize(toolkit, { callbackUrl });
193 return { status: 'needs_connection', redirectUrl: request.redirectUrl };
194 },
195 isConnected: (state) => state.connection?.isActive ?? false,
196 },
197 });
198 }
199 `;
200
201 const toolsAuth = `
202 function toolsForSession(session, event: IncomingTriggerPayload) {
203 return piProvider.createSessionTools({
204 sessionId: session.sessionId,
205 callbackUrl,
206 search: (params) => session.search(params),
207 // Every tool result passes through handleAuthLinks: connect URLs get DM'd to
208 // the user and redacted before the model ever sees them.
209 execute: async (slug, args, options) => handleAuthLinks(session, event, await session.execute(slug, args, options)),
210 connections: {
211 getToolkitStates: (toolkits) => session.toolkits({ toolkits }),
212 authorizeToolkit: async (toolkit) => {
213 const request = await session.authorize(toolkit, { callbackUrl });
214 await handleAuthLinks(session, event, request.redirectUrl);
215 return { status: 'needs_connection', redirectUrl: request.redirectUrl };
216 },
217 isConnected: (state) => state.connection?.isActive ?? false,
218 },
219 });
220 }
221 `;
222
223 const handleNoStatus = `
224 // Reply to one Slack message as the user who sent it.
225 async function handleSlackMessage(event: IncomingTriggerPayload) {
226 const { session, memory } = await sessionForThread(event);
227 const prompt = [...memory.history.map((m) => \`\${m.role}: \${m.content}\`), \`user: \${event.payload?.text}\`].join('\\n');
228
229 const reply = await runPi(toolsForSession(session), prompt);
230
231 await session.execute('SLACKBOT_SEND_MESSAGE', {
232 channel: event.payload?.channel,
233 thread_ts: event.payload?.thread_ts,
234 text: reply,
235 });
236 memory.history.push({ role: 'user', content: event.payload?.text ?? '' }, { role: 'assistant', content: reply });
237 }
238 `;
239
240 const handleStatus = `
241 // Reply to one Slack message as the user who sent it.
242 async function handleSlackMessage(event: IncomingTriggerPayload) {
243 const { session, memory } = await sessionForThread(event);
244 await setStatus(session, event, 'Working on it…');
245
246 const prompt = [...memory.history.map((m) => \`\${m.role}: \${m.content}\`), \`user: \${event.payload?.text}\`].join('\\n');
247 const reply = await runPi(toolsForSession(session, event), prompt);
248
249 await session.execute('SLACKBOT_SEND_MESSAGE', {
250 channel: event.payload?.channel,
251 thread_ts: event.payload?.thread_ts,
252 text: reply,
253 });
254 memory.history.push({ role: 'user', content: event.payload?.text ?? '' }, { role: 'assistant', content: reply });
255 }
256 `;
257
258 // handleStatus calls toolsForSession(session, event); for the proxy stage (before
259 // auth) toolsForSession still takes one arg, so use a variant without the event.
260 const handleStatusNoAuth = handleStatus.replace('toolsForSession(session, event)', 'toolsForSession(session)');
261
262 const serve = `
263 Bun.serve({
264 port: 3000,
265 async fetch(req) {
266 const url = new URL(req.url);
267 if (req.method === 'POST' && url.pathname === '/webhooks/composio') {
268 const { payload } = await composio.triggers.verifyWebhook({
269 payload: await req.text(),
270 secret: process.env.COMPOSIO_WEBHOOK_SECRET,
271 id: req.headers.get('webhook-id'),
272 timestamp: req.headers.get('webhook-timestamp'),
273 signature: req.headers.get('webhook-signature'),
274 });
275 void handleSlackMessage(payload);
276 return Response.json({ ok: true });
277 }
278 return new Response('Not found', { status: 404 });
279 },
280 });
281 `;
282
283 const BOT_STAGES: { title: string; description: string; parts: string[] }[] = [
284 {
285 title: 'A basic agent',
286 description:
287 'Start from scratch. The smallest possible agent: create a session for a user, hand the Pi provider the session so it can search and execute, run a prompt. This already works against every app that user has connected, with no Slack yet.',
288 parts: [head1, runPi, runAgent],
289 },
290 {
291 title: 'Wire it to Slack threads',
292 description:
293 'Turn the one-shot agent into a handler. Each Slack thread gets its own session (reused for memory), the agent runs over the session tools, and the reply is posted with the SLACKBOT_SEND_MESSAGE tool.',
294 parts: [head2, memNoPin, toolsNoAuth, runPi, handleNoStatus],
295 },
296 {
297 title: 'Share one workspace connection',
298 description:
299 'Pin a single SHARED Slack connection into every session. Now the bot posts as the workspace bot, but still acts in GitHub, Gmail, and everything else as the individual user.',
300 parts: [head2Shared, memPin, toolsNoAuth, runPi, handleNoStatus],
301 },
302 {
303 title: 'Reach the gaps with the proxy',
304 description:
305 'Add a typing indicator and a DM-channel opener. Neither has a SLACKBOT_* tool, so they drop down to the proxy, which calls the Slack Web API with the pinned connection.',
306 parts: [head2Shared, memPin, proxy, toolsNoAuth, runPi, handleStatusNoAuth],
307 },
308 {
309 title: 'Redirect auth links',
310 description:
311 'The payoff. When the agent touches an app the user has not connected, the tool result carries a one-time connect URL. Redact it from the model and the channel, DM it to the user privately, and let the run resume on approval.',
312 parts: [head2Shared, memPin, proxy, auth, toolsAuth, runPi, handleStatus],
313 },
314 {
315 title: 'Serve the webhook',
316 description:
317 'Verify each trigger signature and dispatch the work off the response path. This is the whole server.',
318 parts: [head2Shared, memPin, proxy, auth, toolsAuth, runPi, handleStatus, serve],
319 },
320 ];
321
322 export const BOT_BUILD_STAGES: BuildStage[] = BOT_STAGES.map((s) => ({
323 title: s.title,
324 description: s.description,
325 code: s.parts.join('').replace(/^\n/, ''),
326 }));
327
328 // ── install.ts ──────────────────────────────────────────────────────────────
329
330 const installAuth = `import { Composio } from '@composio/core';
331
332 const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
333
334 // The scopes the bot needs. The slackbot toolkit ships Composio-managed OAuth,
335 // so you never register your own Slack app.
336 const authConfig = await composio.authConfigs.create('slackbot', {
337 type: 'use_composio_managed_auth',
338 name: 'workspace-bot',
339 credentials: {
340 scopes: ['app_mentions:read', 'channels:history', 'chat:write', 'reactions:write', 'users:read'],
341 user_scopes: ['search:read'],
342 },
343 });
344 `;
345
346 const installAuthorize = `
347 // One connection for the whole workspace: authorize it as SHARED.
348 const setup = await composio.create('setup:workspace-bot', {
349 toolkits: ['slackbot'],
350 authConfigs: { slackbot: authConfig.id },
351 manageConnections: true,
352 });
353 const request = await setup.authorize('slackbot', {
354 callbackUrl: \`\${process.env.APP_URL}/setup/callback\`,
355 experimental: { accountType: 'SHARED' },
356 });
357 console.log('Approve the install:', request.redirectUrl);
358 `;
359
360 const installWire = `
361 // On the OAuth callback: open the ACL, subscribe your webhook, create triggers.
362 // Persist connectedAccountId as SLACK_CONNECTION_ID for the bot server.
363 export async function onSetupCallback(connectedAccountId: string) {
364 await composio.connectedAccounts.updateAcl(connectedAccountId, { allowAllUsers: true });
365 await composio.triggers.setWebhookSubscription({ webhookUrl: \`\${process.env.APP_URL}/webhooks/composio\` });
366 await composio.triggers.create('setup:workspace-bot', 'SLACKBOT_CHANNEL_MESSAGE_RECEIVED', { triggerConfig: { is_bot_message: false } });
367 await composio.triggers.create('setup:workspace-bot', 'SLACKBOT_DIRECT_MESSAGE_RECEIVED', { triggerConfig: {} });
368 }
369 `;
370
371 const INSTALL_STAGES: { title: string; description: string; parts: string[] }[] = [
372 {
373 title: 'Declare the scopes',
374 description: 'Create a Composio-managed auth config for the slackbot toolkit. No Slack app of your own to register.',
375 parts: [installAuth],
376 },
377 {
378 title: 'Authorize one shared connection',
379 description: 'Start a setup session and authorize slackbot as a SHARED connection, so a single approval serves every user.',
380 parts: [installAuth, installAuthorize],
381 },
382 {
383 title: 'Open it up and wire events',
384 description: 'On the callback, open the ACL to the workspace, subscribe your webhook, and create the message triggers.',
385 parts: [installAuth, installAuthorize, installWire],
386 },
387 ];
388
389 export const INSTALL_BUILD_STAGES: BuildStage[] = INSTALL_STAGES.map((s) => ({
390 title: s.title,
391 description: s.description,
392 code: s.parts.join(''),
393 }));
394
395 export const FILE_BUILDS: Record<string, { file: string; stages: BuildStage[] }> = {
396 install: { file: 'install.ts', stages: INSTALL_BUILD_STAGES },
397 bot: { file: 'bot.ts', stages: BOT_BUILD_STAGES },
398 };