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 84 lines 2.48 KB
Raw
1 import { z } from 'zod';
2 import { fetchWithRetry, type FetchWithRetryOptions } from './fetch-with-retry';
3 import { createComposioClient } from '../lib/composio-api';
4
5 interface ToolkitWithVersion {
6 slug: string;
7 version: string | null;
8 }
9
10 // A malformed entry is dropped rather than failing the run; only a response
11 // without an items array is rejected.
12 const changelogEntrySchema = z
13 .object({
14 slug: z.string().optional().catch(undefined),
15 versions: z
16 .array(z.object({ version: z.string().optional().catch(undefined) }).catch({}))
17 .optional()
18 .catch(undefined),
19 })
20 .catch({});
21
22 const changelogSchema = z.object({ items: z.array(changelogEntrySchema) });
23
24 export type ToolkitVersionFetcher = (
25 url: string,
26 options?: FetchWithRetryOptions
27 ) => Promise<Response>;
28
29 /** Fetch the authoritative toolkit-version map from the production API. */
30 export async function fetchProductionToolkitVersions(
31 apiKey: string,
32 fetcher: ToolkitVersionFetcher = fetchWithRetry
33 ): Promise<Map<string, string>> {
34 const client = createComposioClient(apiKey, {
35 maxRetries: 0,
36 timeout: 10 * 60_000,
37 fetch: (input, init) => fetcher(String(input), init),
38 });
39
40 let response: unknown;
41 try {
42 response = await client.toolkits.retrieveChangelog();
43 } catch (error) {
44 throw new Error(
45 `Failed to fetch production toolkit changelog: ${error instanceof Error ? error.message : String(error)}`
46 );
47 }
48 const data = changelogSchema.safeParse(response);
49 if (!data.success) {
50 throw new Error('Production toolkit changelog response is missing an items array');
51 }
52
53 const versionMap = new Map<string, string>();
54
55 for (const entry of data.data.items) {
56 const slug = entry.slug?.toLowerCase();
57 const latestVersion = entry.versions?.[0]?.version;
58 if (slug && latestVersion) {
59 versionMap.set(slug, latestVersion);
60 }
61 }
62
63 if (versionMap.size === 0) {
64 throw new Error('Production toolkit changelog contains no toolkit versions');
65 }
66
67 return versionMap;
68 }
69
70 /** Apply generator semantics: absent production changelog entries become null. */
71 export function applyToolkitVersions<T extends ToolkitWithVersion>(
72 toolkits: T[],
73 versionMap: ReadonlyMap<string, string>
74 ): { matched: number; missing: number } {
75 let matched = 0;
76
77 for (const toolkit of toolkits) {
78 const version = versionMap.get(toolkit.slug.toLowerCase()) ?? null;
79 toolkit.version = version;
80 if (version) matched++;
81 }
82
83 return { matched, missing: toolkits.length - matched };
84 }