@devries-cameron20 / composio Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 533 lines 17.5 KB
Raw
1 /**
2 * The seeded state of the fake Composio deployment.
3 *
4 * Everything a response can echo back (ids, timestamps, emails) is fixed here,
5 * so two runs of the same journey print the same bytes.
6 */
7
8 /** The one instant every seeded `created_at`/`updated_at` reports. */
9 export const SEEDED_AT = '2026-01-01T00:00:00.000Z';
10
11 /** Far enough ahead that a seeded login session never expires during a run. */
12 export const SEEDED_EXPIRY = '2099-01-01T00:00:00.000Z';
13
14 export interface SeededOrg {
15 readonly id: string;
16 readonly name: string;
17 readonly plan: string;
18 }
19
20 export interface SeededMember {
21 readonly id: string;
22 readonly email: string;
23 readonly name: string;
24 readonly role: string;
25 }
26
27 export type ProjectKind = 'consumer' | 'developer';
28
29 export interface SeededProject {
30 /** What the journal calls this project, so assertions never repeat an id. */
31 readonly label: string;
32 readonly kind: ProjectKind;
33 readonly autoId: number;
34 readonly uuid: string;
35 readonly nanoId: string;
36 readonly name: string;
37 readonly orgId: string;
38 /** Project API key (`ak_`), minted for the developer project by `dev init`. */
39 readonly apiKey: string;
40 }
41
42 export interface SeededToolkit {
43 readonly slug: string;
44 readonly name: string;
45 readonly description: string;
46 readonly noAuth: boolean;
47 readonly version: string;
48 }
49
50 export interface SeededTool {
51 readonly slug: string;
52 readonly name: string;
53 readonly toolkit: string;
54 readonly description: string;
55 readonly inputParameters: Record<string, unknown>;
56 /** Whether running it changes nothing: a lookup, as opposed to a send or a create. */
57 readonly readOnly: boolean;
58 /** What a successful execution answers with, given the arguments it received. */
59 readonly respond: (args: Record<string, unknown>) => Record<string, unknown>;
60 }
61
62 export interface Connection {
63 readonly id: string;
64 readonly projectLabel: string;
65 readonly userId: string;
66 readonly toolkit: string;
67 readonly authConfigId: string;
68 status: 'INITIATED' | 'ACTIVE';
69 readonly wordId: string;
70 readonly alias: string | null;
71 /** Status reads left before the account turns `ACTIVE`; `null` when it never will. */
72 pollsUntilActive: number | null;
73 /** Whether the person approved it, as opposed to a seeded or self-completing connection. */
74 approvedByPerson: boolean;
75 /** Whether an answer has told a caller that the account is `ACTIVE`. */
76 reportedActive: boolean;
77 }
78
79 export interface ReleaseAsset {
80 readonly name: string;
81 readonly read: () => Uint8Array;
82 }
83
84 /** A GitHub release of the CLI, as `composio upgrade` and the update check see it. */
85 export interface Release {
86 readonly tag: string;
87 readonly prerelease: boolean;
88 readonly assets: ReadonlyArray<ReleaseAsset>;
89 }
90
91 export interface AuthConfig {
92 readonly id: string;
93 readonly uuid: string;
94 readonly projectLabel: string;
95 readonly toolkit: string;
96 readonly name: string;
97 }
98
99 export interface CliLoginSession {
100 readonly id: string;
101 readonly code: string;
102 status: 'pending' | 'linked';
103 /** Whether an answer has told a caller that the session is linked. */
104 reportedLinked: boolean;
105 }
106
107 export interface ToolRouterSession {
108 readonly id: string;
109 readonly projectLabel: string;
110 readonly userId: string;
111 }
112
113 export const ORG: SeededOrg = { id: 'ok_e2eacme00001', name: 'Acme E2E', plan: 'BUSINESS' };
114
115 /** A second organization the same person belongs to, for `--org` and `orgs` rows. */
116 export const OTHER_ORG: SeededOrg = { id: 'ok_e2eglobex001', name: 'Globex E2E', plan: 'HOBBY' };
117
118 export const MEMBER: SeededMember = {
119 id: '00000000-0000-4000-8000-00000000a001',
120 email: 'dev@acme-e2e.test',
121 name: 'Dev Eloper',
122 role: 'admin',
123 };
124
125 /** The user API key (`uk_`) a completed login stores. */
126 export const USER_API_KEY = 'uk_e2e_acme_user_key_0001';
127
128 /** A well-formed user key this deployment never issued. */
129 export const FOREIGN_USER_API_KEY = 'uk_e2e_issued_elsewhere_9999';
130
131 export const CONSUMER_PROJECT: SeededProject = {
132 label: 'consumer',
133 kind: 'consumer',
134 autoId: 1001,
135 uuid: '00000000-0000-4000-8000-00000000c001',
136 nanoId: 'pr_e2econsumer01',
137 name: 'acme-e2e-consumer',
138 orgId: ORG.id,
139 apiKey: 'ak_e2e_consumer_project_key',
140 };
141
142 export const DEVELOPER_PROJECT: SeededProject = {
143 label: 'developer',
144 kind: 'developer',
145 autoId: 2001,
146 uuid: '00000000-0000-4000-8000-00000000d001',
147 nanoId: 'pr_e2edeveloper1',
148 name: 'acme-e2e-dev',
149 orgId: ORG.id,
150 apiKey: 'ak_e2e_developer_project_key',
151 };
152
153 /** A second developer project, the target of `--project-name`. */
154 export const OTHER_DEVELOPER_PROJECT: SeededProject = {
155 label: 'developer-other',
156 kind: 'developer',
157 autoId: 2002,
158 uuid: '00000000-0000-4000-8000-00000000d002',
159 nanoId: 'pr_e2edeveloper2',
160 name: 'acme-e2e-staging',
161 orgId: ORG.id,
162 apiKey: 'ak_e2e_developer_other_key',
163 };
164
165 /** The consumer user: the logged-in person inside their consumer project. */
166 export const CONSUMER_USER_ID = 'consumer-user-e2e-acme-0001';
167
168 /** The global test user a login stores for the dev tree. */
169 export const GLOBAL_TEST_USER_ID = `pg-test-${MEMBER.id}`;
170
171 export const TOOLKITS: ReadonlyArray<SeededToolkit> = [
172 {
173 slug: 'slack',
174 name: 'Slack',
175 description: 'Send messages and manage channels in Slack.',
176 noAuth: false,
177 version: '20260101_00',
178 },
179 {
180 slug: 'github',
181 name: 'GitHub',
182 description: 'Work with repositories, issues, and pull requests.',
183 noAuth: false,
184 version: '20260101_00',
185 },
186 {
187 slug: 'gmail',
188 name: 'Gmail',
189 description: 'Read and send email with Gmail.',
190 noAuth: false,
191 version: '20260101_00',
192 },
193 {
194 slug: 'hackernews',
195 name: 'Hacker News',
196 description: 'Read stories and user profiles from Hacker News.',
197 noAuth: true,
198 version: '20260101_00',
199 },
200 ];
201
202 const objectSchema = (
203 properties: Record<string, { type: string; description: string }>,
204 required: ReadonlyArray<string>
205 ) => ({ type: 'object', properties, required: [...required] });
206
207 export const TOOLS: ReadonlyArray<SeededTool> = [
208 {
209 slug: 'SLACK_SEND_MESSAGE',
210 name: 'Send message',
211 toolkit: 'slack',
212 description: 'Posts a message to a Slack channel.',
213 inputParameters: objectSchema(
214 {
215 channel: { type: 'string', description: 'Channel name or id to post to.' },
216 text: { type: 'string', description: 'Message text.' },
217 },
218 ['channel', 'text']
219 ),
220 readOnly: false,
221 respond: args => ({
222 ok: true,
223 channel: args.channel ?? null,
224 ts: '1767225600.000100',
225 message: { text: args.text ?? null },
226 }),
227 },
228 {
229 slug: 'GITHUB_CREATE_AN_ISSUE',
230 name: 'Create an issue',
231 toolkit: 'github',
232 description: 'Creates an issue in a GitHub repository.',
233 inputParameters: objectSchema(
234 {
235 owner: { type: 'string', description: 'Repository owner.' },
236 repo: { type: 'string', description: 'Repository name.' },
237 title: { type: 'string', description: 'Issue title.' },
238 body: { type: 'string', description: 'Issue body.' },
239 },
240 ['owner', 'repo', 'title']
241 ),
242 readOnly: false,
243 respond: args => ({
244 number: 101,
245 title: args.title ?? null,
246 html_url: `https://github.com/${String(args.owner)}/${String(args.repo)}/issues/101`,
247 }),
248 },
249 {
250 slug: 'GITHUB_GET_THE_AUTHENTICATED_USER',
251 name: 'Get the authenticated user',
252 toolkit: 'github',
253 description: 'Returns the profile of the connected GitHub account.',
254 inputParameters: objectSchema({}, []),
255 readOnly: true,
256 respond: () => ({ login: 'acme-e2e-dev', id: 4242 }),
257 },
258 {
259 slug: 'GMAIL_SEND_EMAIL',
260 name: 'Send email',
261 toolkit: 'gmail',
262 description: 'Sends an email from the connected Gmail account.',
263 inputParameters: objectSchema(
264 {
265 recipient_email: { type: 'string', description: 'Recipient address.' },
266 subject: { type: 'string', description: 'Subject line.' },
267 body: { type: 'string', description: 'Message body.' },
268 },
269 ['recipient_email']
270 ),
271 readOnly: false,
272 respond: () => ({ id: 'msg_e2e_0001', labelIds: ['SENT'] }),
273 },
274 {
275 slug: 'HACKERNEWS_GET_USER',
276 name: 'Get user',
277 toolkit: 'hackernews',
278 description: 'Returns a Hacker News user profile.',
279 inputParameters: objectSchema(
280 { username: { type: 'string', description: 'Hacker News username.' } },
281 ['username']
282 ),
283 readOnly: true,
284 respond: args => ({ id: args.username ?? null, karma: 157316 }),
285 },
286 ];
287
288 /** Mutable state; one instance per fake backend. */
289 export class World {
290 readonly org = ORG;
291 readonly organizations: ReadonlyArray<SeededOrg> = [ORG, OTHER_ORG];
292 readonly member = MEMBER;
293 readonly userApiKey: string;
294 readonly projects: ReadonlyArray<SeededProject> = [
295 CONSUMER_PROJECT,
296 DEVELOPER_PROJECT,
297 OTHER_DEVELOPER_PROJECT,
298 ];
299 /** The project an unscoped user-key request acts on, as `auth/session/info` reports it. */
300 readonly defaultProject = DEVELOPER_PROJECT;
301 readonly toolkits = TOOLKITS;
302 readonly tools = TOOLS;
303
304 readonly connections: Connection[] = [];
305 readonly authConfigs: AuthConfig[] = [];
306 readonly loginSessions: CliLoginSession[] = [];
307 readonly toolRouterSessions: ToolRouterSession[] = [];
308 /** Project API keys minted by `POST …/api_keys/create`, newest last. */
309 readonly mintedProjectKeys: Array<{ key: string; projectLabel: string; name: string }> = [];
310 /** Published CLI releases. Empty by default: no update is ever on offer. */
311 readonly releases: Release[] = [];
312 /**
313 * How a link request ends, standing in for the person at the OAuth screen:
314 * the number of status reads before the account is `ACTIVE`, or `null` when
315 * nobody ever finishes authorizing.
316 */
317 linkCompletesAfterPolls: number | null = 1;
318 private toolExecutions = 0;
319
320 constructor(options: { userApiKey?: string } = {}) {
321 this.userApiKey = options.userApiKey ?? USER_API_KEY;
322 // Each developer project starts with one Composio-managed auth config per
323 // toolkit that needs auth, as a fresh project gets on first use.
324 for (const project of this.projects.filter(p => p.kind === 'developer')) {
325 for (const toolkit of this.toolkits.filter(t => !t.noAuth)) {
326 this.authConfigForToolkit(project.label, toolkit.slug);
327 }
328 }
329 }
330
331 projectByLabel(label: string): SeededProject {
332 const project = this.projects.find(p => p.label === label);
333 if (!project) throw new Error(`No seeded project labelled ${label}`);
334 return project;
335 }
336
337 /** A project by nano id, uuid, or name: the ids a request can carry. */
338 findProject(reference: string | undefined): SeededProject | undefined {
339 if (!reference) return undefined;
340 return this.projects.find(
341 p => p.nanoId === reference || p.uuid === reference || p.name === reference
342 );
343 }
344
345 projectForApiKey(key: string): SeededProject | undefined {
346 const minted = this.mintedProjectKeys.find(k => k.key === key);
347 if (minted) return this.projectByLabel(minted.projectLabel);
348 return this.projects.find(p => p.apiKey === key);
349 }
350
351 findToolkit(slug: string): SeededToolkit | undefined {
352 return this.toolkits.find(t => t.slug === slug.toLowerCase());
353 }
354
355 findTool(slug: string): SeededTool | undefined {
356 return this.tools.find(t => t.slug === slug.toUpperCase());
357 }
358
359 authConfigForToolkit(projectLabel: string, toolkit: string): AuthConfig {
360 const existing = this.authConfigs.find(
361 a => a.projectLabel === projectLabel && a.toolkit === toolkit
362 );
363 if (existing) return existing;
364 const ordinal = String(this.authConfigs.length + 1).padStart(4, '0');
365 const created: AuthConfig = {
366 id: `ac_e2e${ordinal}`,
367 uuid: `00000000-0000-4000-8000-0000000a${ordinal}`,
368 projectLabel,
369 toolkit,
370 name: `${toolkit}-${projectLabel}`,
371 };
372 this.authConfigs.push(created);
373 return created;
374 }
375
376 activeConnection(projectLabel: string, userId: string, toolkit: string): Connection | undefined {
377 return this.connections.find(
378 c =>
379 c.projectLabel === projectLabel &&
380 c.userId === userId &&
381 c.toolkit === toolkit &&
382 c.status === 'ACTIVE'
383 );
384 }
385
386 /** `activeConnection` for answering a request: the caller now knows the account is active. */
387 reportActiveConnection(
388 projectLabel: string,
389 userId: string,
390 toolkit: string
391 ): Connection | undefined {
392 const connection = this.activeConnection(projectLabel, userId, toolkit);
393 if (connection) connection.reportedActive = true;
394 return connection;
395 }
396
397 /** Starts a connection the way a link request does: `INITIATED`, with a redirect to follow. */
398 beginConnection(params: {
399 projectLabel: string;
400 userId: string;
401 toolkit: string;
402 alias?: string | null;
403 }): Connection {
404 const ordinal = String(this.connections.length + 1).padStart(4, '0');
405 const connection: Connection = {
406 id: `ca_e2e${ordinal}`,
407 projectLabel: params.projectLabel,
408 userId: params.userId,
409 toolkit: params.toolkit,
410 authConfigId: this.authConfigForToolkit(params.projectLabel, params.toolkit).id,
411 status: 'INITIATED',
412 wordId: `${params.toolkit}_e2e_${ordinal}`,
413 alias: params.alias ?? null,
414 pollsUntilActive: this.linkCompletesAfterPolls,
415 approvedByPerson: false,
416 reportedActive: false,
417 };
418 this.connections.push(connection);
419 return connection;
420 }
421
422 /** One status read of a pending connection, which may be the one that finds it authorized. */
423 pollConnection(connection: Connection): void {
424 if (connection.status === 'ACTIVE' || connection.pollsUntilActive === null) return;
425 connection.pollsUntilActive -= 1;
426 if (connection.pollsUntilActive <= 0) connection.status = 'ACTIVE';
427 }
428
429 /** Seeds an already-active connection, for journeys that start connected. */
430 connect(projectLabel: string, userId: string, toolkit: string): Connection {
431 const connection = this.beginConnection({ projectLabel, userId, toolkit });
432 connection.status = 'ACTIVE';
433 return connection;
434 }
435
436 /** Stands in for the person approving one authorization; `false` when there is none pending under that id. */
437 authorizeConnection(id: string): boolean {
438 const connection = this.connections.find(c => c.id === id && c.status === 'INITIATED');
439 if (!connection) return false;
440 connection.status = 'ACTIVE';
441 connection.approvedByPerson = true;
442 return true;
443 }
444
445 /**
446 * Ids of the login sessions and connections the person approved that no
447 * answer has reported yet: the CLI, and so the agent, cannot know of them.
448 */
449 unreportedApprovals(): ReadonlyArray<string> {
450 return [
451 ...this.loginSessions
452 .filter(session => session.status === 'linked' && !session.reportedLinked)
453 .map(session => session.id),
454 ...this.connections
455 .filter(connection => connection.approvedByPerson && !connection.reportedActive)
456 .map(connection => connection.id),
457 ];
458 }
459
460 createLoginSession(): CliLoginSession {
461 const ordinal = String(this.loginSessions.length + 1).padStart(4, '0');
462 const session: CliLoginSession = {
463 id: `00000000-0000-4000-8000-00000005${ordinal}`,
464 code: `E2E${ordinal.slice(1)}`,
465 status: 'pending',
466 reportedLinked: false,
467 };
468 this.loginSessions.push(session);
469 return session;
470 }
471
472 /** Stands in for the person approving the login in the browser. */
473 linkLoginSession(idOrCode?: string): CliLoginSession {
474 const session = idOrCode
475 ? this.loginSessions.find(s => s.id === idOrCode || s.code === idOrCode)
476 : this.loginSessions.at(-1);
477 if (!session) throw new Error('No CLI login session to link');
478 session.status = 'linked';
479 return session;
480 }
481
482 createToolRouterSession(projectLabel: string, userId: string): ToolRouterSession {
483 const ordinal = String(this.toolRouterSessions.length + 1).padStart(4, '0');
484 const session: ToolRouterSession = { id: `trs_e2e${ordinal}`, projectLabel, userId };
485 this.toolRouterSessions.push(session);
486 return session;
487 }
488
489 mintProjectKey(projectLabel: string, name: string): string {
490 const ordinal = String(this.mintedProjectKeys.length + 1).padStart(4, '0');
491 const key = `ak_e2e_minted_${projectLabel.replace(/[^a-z]/g, '')}_${ordinal}`;
492 this.mintedProjectKeys.push({ key, projectLabel, name });
493 return key;
494 }
495
496 nextLogId(): string {
497 this.toolExecutions += 1;
498 return `log_e2e${String(this.toolExecutions).padStart(4, '0')}`;
499 }
500
501 /**
502 * Everything the world holds, as plain data: the seed and what requests have
503 * changed since. A tool's `respond` is code and a release asset's bytes are
504 * read on demand, so a tool is kept without the one and an asset by its name.
505 *
506 * The deployment's user API key stays out: no request changes it, so it is
507 * not state a run is compared by, and a digest of a credential is a password
508 * hash to any reader (and to CodeQL).
509 */
510 snapshot(): unknown {
511 return {
512 org: this.org,
513 organizations: this.organizations,
514 member: this.member,
515 projects: this.projects,
516 defaultProject: this.defaultProject.label,
517 toolkits: this.toolkits,
518 tools: this.tools.map(({ respond: _respond, ...tool }) => tool),
519 connections: this.connections,
520 authConfigs: this.authConfigs,
521 loginSessions: this.loginSessions,
522 toolRouterSessions: this.toolRouterSessions,
523 mintedProjectKeys: this.mintedProjectKeys,
524 releases: this.releases.map(release => ({
525 tag: release.tag,
526 prerelease: release.prerelease,
527 assets: release.assets.map(asset => asset.name),
528 })),
529 linkCompletesAfterPolls: this.linkCompletesAfterPolls,
530 toolExecutions: this.toolExecutions,
531 };
532 }
533 }