1
+import { describe, it, expect, vi, afterEach } from 'vitest';
2
+import ComposioClient, { Auth, createFetchTransport } from '@composio/client';
3
+import { Tools } from '../../src/models/Tools';
4
+import { ComposioRequestCancelledError } from '../../src/errors/SDKErrors';
5
+import { MockProvider } from '../utils/mocks/provider.mock';
6
+import { toolMocks } from '../utils/mocks/data.mock';
7
+import {
8
+ ComposioToolExecutionError,
9
+ ComposioToolExecutionRateLimitError,
10
+ ComposioToolFetchError,
11
+ ComposioToolFetchRateLimitError,
12
+ isComposioRateLimitError,
13
+} from '../../src/errors/ToolErrors';
14
+
15
+vi.mock('../../src/telemetry/Telemetry', () => ({
16
+ telemetry: { instrument: vi.fn() },
17
+}));
18
+
19
+const SLUG = 'GITHUB_GET_REPOS';
20
+const json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
21
+ new Response(JSON.stringify(body), {
22
+ status,
23
+ headers: { 'content-type': 'application/json', ...headers },
24
+ });
25
+const rateLimited = () =>
26
+ json({ error: { message: 'slow down' } }, 429, { 'retry-after': '7', 'retry-after-ms': '1' });
27
+
28
+/** A real client whose schema and execute responses come from the given handlers. */
29
+const createTools = (
30
+ options: {
31
+ retrieve?: () => Response;
32
+ execute?: () => Response;
33
+ toolkitVersions?: Record<string, string>;
34
+ } = {}
35
+) => {
36
+ const retrieve = vi.fn(options.retrieve ?? (() => json(toolMocks.rawTool)));
37
+ const execute = vi.fn(options.execute ?? (() => json(toolMocks.rawToolExecuteResponse)));
38
+ const fetch = vi.fn<typeof globalThis.fetch>(async (input, init) => {
39
+ const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
40
+ return method === 'GET' ? retrieve() : execute();
41
+ });
42
+ const client = new ComposioClient({
43
+ auth: Auth.project('test-api-key'),
44
+ baseURL: 'https://backend.invalid',
45
+ transport: createFetchTransport({ fetch }),
46
+ });
47
+ const tools = new Tools(client, {
48
+ provider: new MockProvider(),
49
+ toolkitVersions: options.toolkitVersions,
50
+ });
51
+ return { tools, retrieve, execute };
52
+};
53
+
54
+const run = (tools: ReturnType<typeof createTools>['tools'], version?: string) =>
55
+ tools.execute(SLUG, {
56
+ userId: 'user_1',
57
+ arguments: {},
58
+ version,
59
+ dangerouslySkipVersionCheck: true,
60
+ });
61
+
62
+describe('tools.execute schema cache', () => {
63
+ afterEach(() => {
64
+ vi.useRealTimers();
65
+ });
66
+
67
+ it('fetches the schema once across executions of one tool', async () => {
68
+ const { tools, retrieve, execute } = createTools();
69
+
70
+ await run(tools);
71
+ await run(tools);
72
+ await run(tools);
73
+
74
+ expect(retrieve).toHaveBeenCalledTimes(1);
75
+ expect(execute).toHaveBeenCalledTimes(3);
76
+ });
77
+
78
+ it('keeps a separate entry per version', async () => {
79
+ const { tools, retrieve } = createTools();
80
+
81
+ await run(tools, '20250909_00');
82
+ await run(tools, '20250910_00');
83
+ await run(tools, '20250909_00');
84
+
85
+ expect(retrieve).toHaveBeenCalledTimes(2);
86
+ });
87
+
88
+ it('refetches a latest schema after 5 minutes', async () => {
89
+ vi.useFakeTimers({ toFake: ['Date'] });
90
+ const { tools, retrieve } = createTools();
91
+
92
+ await run(tools);
93
+ vi.advanceTimersByTime(5 * 60 * 1000 - 1);
94
+ await run(tools);
95
+ expect(retrieve).toHaveBeenCalledTimes(1);
96
+
97
+ vi.advanceTimersByTime(1);
98
+ await run(tools);
99
+ expect(retrieve).toHaveBeenCalledTimes(2);
100
+ });
101
+
102
+ it('keeps a pinned schema for an hour', async () => {
103
+ vi.useFakeTimers({ toFake: ['Date'] });
104
+ const { tools, retrieve } = createTools();
105
+
106
+ await run(tools, '20250909_00');
107
+ vi.advanceTimersByTime(60 * 60 * 1000 - 1);
108
+ await run(tools, '20250909_00');
109
+ expect(retrieve).toHaveBeenCalledTimes(1);
110
+
111
+ vi.advanceTimersByTime(1);
112
+ await run(tools, '20250909_00');
113
+ expect(retrieve).toHaveBeenCalledTimes(2);
114
+ });
115
+
116
+ it('does not cache a failed fetch', async () => {
117
+ const retrieve = vi
118
+ .fn<() => Response>()
119
+ .mockReturnValueOnce(json({ error: { message: 'bad' } }, 400))
120
+ .mockReturnValue(json(toolMocks.rawTool));
121
+ const { tools } = createTools({ retrieve });
122
+
123
+ await expect(run(tools)).rejects.toThrow();
124
+ await expect(run(tools)).resolves.toBeDefined();
125
+ expect(retrieve).toHaveBeenCalledTimes(2);
126
+ });
127
+
128
+ it('still honors an aborted signal on a cache hit', async () => {
129
+ const { tools, execute } = createTools();
130
+ await run(tools);
131
+
132
+ const error = await tools
133
+ .execute(
134
+ SLUG,
135
+ { userId: 'user_1', arguments: {}, dangerouslySkipVersionCheck: true },
136
+ { signal: AbortSignal.abort() }
137
+ )
138
+ .catch(e => e);
139
+
140
+ expect(error).toBeInstanceOf(ComposioRequestCancelledError);
141
+ expect(execute).toHaveBeenCalledTimes(1);
142
+ });
143
+
144
+ it('leaves getRawComposioToolBySlug uncached', async () => {
145
+ const { tools, retrieve } = createTools();
146
+
147
+ await tools.getRawComposioToolBySlug(SLUG);
148
+ await tools.getRawComposioToolBySlug(SLUG);
149
+
150
+ expect(retrieve).toHaveBeenCalledTimes(2);
151
+ });
152
+});
153
+
154
+describe('rate limit errors', () => {
155
+ it('reports a rejected schema fetch as a rate limit, not a bad slug', async () => {
156
+ const { tools, execute } = createTools({ retrieve: rateLimited });
157
+
158
+ const error = await run(tools).catch(e => e);
159
+
160
+ expect(error).toBeInstanceOf(ComposioToolFetchRateLimitError);
161
+ expect(error).toBeInstanceOf(ComposioToolFetchError);
162
+ expect(isComposioRateLimitError(error)).toBe(true);
163
+ expect(error.retryAfterSeconds).toBe(7);
164
+ expect(error.statusCode).toBe(429);
165
+ expect(error.possibleFixes.join(' ')).not.toContain('slug');
166
+ expect(execute).not.toHaveBeenCalled();
167
+ });
168
+
169
+ it('reports a rejected execution as a rate limit, once', async () => {
170
+ const { tools, execute } = createTools({ execute: rateLimited });
171
+
172
+ const error = await run(tools).catch(e => e);
173
+
174
+ expect(error).toBeInstanceOf(ComposioToolExecutionRateLimitError);
175
+ expect(error).toBeInstanceOf(ComposioToolExecutionError);
176
+ expect(isComposioRateLimitError(error)).toBe(true);
177
+ expect(error.retryAfterSeconds).toBe(7);
178
+ expect(error.statusCode).toBe(429);
179
+ expect(execute).toHaveBeenCalledTimes(1);
180
+ });
181
+
182
+ it('leaves out retryAfterSeconds when the response gives no wait', async () => {
183
+ const { tools } = createTools({
184
+ retrieve: () => json({ error: { message: 'slow down' } }, 429, { 'retry-after-ms': '1' }),
185
+ });
186
+
187
+ const error = await run(tools).catch(e => e);
188
+
189
+ expect(isComposioRateLimitError(error)).toBe(true);
190
+ expect(Object.keys(error)).not.toContain('retryAfterSeconds');
191
+ });
192
+
193
+ it('does not report other failures as rate limits', async () => {
194
+ const { tools } = createTools({
195
+ retrieve: () => json({ error: { message: 'bad key' } }, 401),
196
+ });
197
+
198
+ const error = await run(tools).catch(e => e);
199
+
200
+ expect(error).toBeInstanceOf(ComposioToolFetchError);
201
+ expect(isComposioRateLimitError(error)).toBe(false);
202
+ });
203
+});