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 785 lines 30.8 KB
Raw
1 import { afterEach, describe, expect, it } from '@effect/vitest';
2 import { vi } from 'vitest';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
5 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
6 import * as BunPath from '@effect/platform-bun/BunPath';
7 import { ConfigProvider, Effect, Exit, Layer, Logger } from 'effect';
8 import { FetchHttpClient } from 'effect/http';
9 import * as tempy from 'tempy';
10 import { VERSION as clientLibraryVersion, type ComposioClientShape } from '@composio/client/effect';
11 import { ComposioClientSingleton, clientScopeKey } from 'src/services/composio-clients';
12 import { listActiveConnectedAccounts } from 'src/services/connected-account-selection';
13 import { stubComposioClient } from 'test/__utils__/services/stub-composio-client';
14 import { idempotent, validated } from 'src/services/composio-request';
15 import { APP_VERSION } from 'src/constants';
16 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
17 import { withoutClientNotices } from 'src/effects/without-client-notices';
18
19 // Exercise real user-context/config resolution without opening the OS credential store.
20 vi.mock('@composio/cli-keyring/effect', async importOriginal => {
21 const actual = await importOriginal<typeof import('@composio/cli-keyring/effect')>();
22 const { Effect, Layer } = await import('effect');
23 const { KeyringError } = await import('@composio/cli-keyring');
24 return {
25 ...actual,
26 KeyringLiveWithBackend: () =>
27 Layer.succeed(actual.KeyringService, {
28 getPassword: () => Effect.fail(new KeyringError({ kind: 'NoEntry' })),
29 getSecret: () => Effect.fail(new KeyringError({ kind: 'NoEntry' })),
30 setPassword: () => Effect.die(new Error('Unexpected credential write')),
31 setSecret: () => Effect.die(new Error('Unexpected credential write')),
32 deleteCredential: () => Effect.die(new Error('Unexpected credential deletion')),
33 isAvailable: Effect.succeed(true),
34 }),
35 };
36 });
37
38 const withConfigLayer = (map: Map<string, string>, homedir: string) =>
39 Layer.mergeAll(
40 BunFileSystem.layer,
41 BunPath.layer,
42 Layer.succeed(NodeOs, defaultNodeOs({ homedir })),
43 Layer.succeed(
44 ConfigProvider.ConfigProvider,
45 ConfigProvider.fromEnv({ env: Object.fromEntries(map) })
46 )
47 );
48
49 const okResponse = () =>
50 new Response(JSON.stringify({ data: [] }), {
51 status: 200,
52 headers: { 'Content-Type': 'application/json' },
53 });
54
55 // Mirrors the module-private `cwdHash` in src/services/consumer-short-term-cache.ts
56 // (djb2Hash + base36): the seeded cache key below must be byte-identical to what
57 // the service computes for process.cwd() when it looks up the CLI session.
58 const cwdHash = (cwd: string): string => {
59 const hash = Array.from({ length: cwd.length }, (_, index) => cwd.charCodeAt(index)).reduce(
60 (acc, code) => (acc * 33) ^ code,
61 5381
62 );
63 return Math.abs(hash >>> 0).toString(36);
64 };
65
66 const writeCliSessionCache = (
67 homedir: string,
68 session: { readonly id: string; readonly expiresAt: string }
69 ) =>
70 Effect.gen(function* () {
71 const fs = yield* FileSystem.FileSystem;
72 const path = yield* Path.Path;
73 const cacheDir = path.join(homedir, '.composio');
74 yield* fs.makeDirectory(cacheDir, { recursive: true });
75 yield* fs.writeFileString(
76 path.join(cacheDir, 'consumer-short-term-cache.json'),
77 JSON.stringify({
78 test: {
79 probablyMyCliSessionsByCwdHash: {
80 [cwdHash(process.cwd())]: session,
81 },
82 },
83 })
84 );
85 });
86
87 const listTools = (client: ComposioClientShape) =>
88 client.tools.list({ limit: 1, toolkit_versions: 'latest' });
89
90 describe('ComposioClientSingleton headers', () => {
91 afterEach(() => {
92 vi.restoreAllMocks();
93 vi.unstubAllEnvs();
94 });
95
96 it.effect('uses x-user-api-key and never x-api-key', () => {
97 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
98 const homedir = tempy.temporaryDirectory();
99 const configMap = new Map([
100 ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
101 ['COMPOSIO_API_KEY', 'ak_should_be_ignored'],
102 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
103 ]);
104
105 return Effect.gen(function* () {
106 const clientSingleton = yield* ComposioClientSingleton;
107 const client = yield* clientSingleton.get();
108 yield* listTools(client);
109
110 expect(fetchSpy).toHaveBeenCalledOnce();
111 const [, init] = fetchSpy.mock.calls[0]!;
112 const headers = new Headers((init as RequestInit).headers);
113
114 expect(headers.get('x-user-api-key')).toBe('uak_from_user_env');
115 expect(headers.has('x-api-key')).toBe(false);
116 expect(headers.get('x-framework')).toBe('cli');
117 expect(headers.get('x-source')).toBe('CLI');
118 expect(headers.get('x-runtime')).toBe('NODEJS');
119 expect(headers.get('x-sdk-version')).toBe(APP_VERSION);
120 expect(headers.get('x-client-provenance')).toBe('@composio/cli');
121 expect(headers.get('x-client-version')).toBe(APP_VERSION);
122 expect(headers.get('x-client-language')).toBe('typescript');
123 expect(headers.get('x-runtime-version')).toBe(process.versions.node);
124 expect(headers.get('x-cli-session-id')).toBeNull();
125 }).pipe(
126 Effect.provide(
127 Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
128 )
129 );
130 });
131
132 // The session-id reader compares expiresAt against Clock.currentTimeMillis;
133 // the TestClock sits at epoch 0, so fixed instants around it are
134 // deterministically in the future or the past.
135 it.effect('includes the current cwd CLI session ID', () => {
136 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
137 const homedir = tempy.temporaryDirectory();
138 const configMap = new Map([
139 ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
140 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
141 ]);
142
143 return Effect.gen(function* () {
144 const path = yield* Path.Path;
145 // The session-id reader resolves its cache dir from COMPOSIO_CACHE_DIR
146 // (stubbed by the shared vitest setup) before falling back to homedir,
147 // so point it at the directory this test writes the fixture into.
148 vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
149 yield* writeCliSessionCache(homedir, {
150 id: 'cli_s_current',
151 expiresAt: '1970-01-01T00:01:00.000Z',
152 });
153 const clientSingleton = yield* ComposioClientSingleton;
154 const client = yield* clientSingleton.get();
155 yield* listTools(client);
156
157 const [, init] = fetchSpy.mock.calls[0]!;
158 const headers = new Headers((init as RequestInit).headers);
159 expect(headers.get('x-cli-session-id')).toBe('cli_s_current');
160 }).pipe(
161 Effect.provide(
162 Layer.provideMerge(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
163 )
164 );
165 });
166
167 it.effect('reads the cwd CLI session ID once for every client it builds', () => {
168 const fetchSpy = vi
169 .spyOn(globalThis, 'fetch')
170 .mockImplementation(() => Promise.resolve(okResponse()));
171 const homedir = tempy.temporaryDirectory();
172 const configMap = new Map([
173 ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
174 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
175 ]);
176
177 return Effect.gen(function* () {
178 const path = yield* Path.Path;
179 vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
180 yield* writeCliSessionCache(homedir, {
181 id: 'cli_s_first',
182 expiresAt: '1970-01-01T00:01:00.000Z',
183 });
184 const clientSingleton = yield* ComposioClientSingleton;
185 yield* listTools(yield* clientSingleton.get());
186
187 yield* writeCliSessionCache(homedir, {
188 id: 'cli_s_second',
189 expiresAt: '1970-01-01T00:01:00.000Z',
190 });
191 yield* listTools(
192 yield* clientSingleton.getFor({ userApiKey: 'uak_other', orgId: 'o', projectId: 'p' })
193 );
194
195 const sessionIds = fetchSpy.mock.calls.map(call =>
196 new Headers((call[1] as RequestInit).headers).get('x-cli-session-id')
197 );
198 expect(sessionIds).toEqual(['cli_s_first', 'cli_s_first']);
199 }).pipe(
200 Effect.provide(
201 Layer.provideMerge(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
202 )
203 );
204 });
205
206 it.effect('omits an expired cwd CLI session ID', () => {
207 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
208 const homedir = tempy.temporaryDirectory();
209 const configMap = new Map([
210 ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
211 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
212 ]);
213
214 return Effect.gen(function* () {
215 const path = yield* Path.Path;
216 vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
217 yield* writeCliSessionCache(homedir, {
218 id: 'cli_s_expired',
219 expiresAt: '1969-12-31T23:59:00.000Z',
220 });
221 const clientSingleton = yield* ComposioClientSingleton;
222 const client = yield* clientSingleton.get();
223 yield* listTools(client);
224
225 const [, init] = fetchSpy.mock.calls[0]!;
226 const headers = new Headers((init as RequestInit).headers);
227 expect(headers.get('x-cli-session-id')).toBeNull();
228 }).pipe(
229 Effect.provide(
230 Layer.provideMerge(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
231 )
232 );
233 });
234
235 it.effect('does not read COMPOSIO_API_KEY for user auth', () => {
236 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
237 const homedir = tempy.temporaryDirectory();
238 const configMap = new Map([
239 ['COMPOSIO_API_KEY', 'ak_only'],
240 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
241 ]);
242
243 return Effect.gen(function* () {
244 const clientSingleton = yield* ComposioClientSingleton;
245 const client = yield* clientSingleton.get();
246 yield* listTools(client);
247
248 expect(fetchSpy).toHaveBeenCalledOnce();
249 const [, init] = fetchSpy.mock.calls[0]!;
250 const headers = new Headers((init as RequestInit).headers);
251
252 expect(headers.get('x-user-api-key')).toBeNull();
253 expect(headers.has('x-api-key')).toBe(false);
254 expect(headers.get('x-source')).toBe('CLI');
255 }).pipe(
256 Effect.provide(
257 Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
258 )
259 );
260 });
261
262 it.effect('ignores ambient COMPOSIO_* variables and logs nothing', () => {
263 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
264 const consoleSpies = (['log', 'info', 'warn', 'error', 'debug'] as const).map(method =>
265 vi.spyOn(console, method)
266 );
267 vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_ambient');
268 vi.stubEnv('COMPOSIO_API_KEY', 'ak_ambient');
269 vi.stubEnv('COMPOSIO_CUSTOM_HEADERS', '{"x-extra":"1"}');
270 vi.stubEnv('COMPOSIO_LOG_LEVEL', 'debug');
271 const homedir = tempy.temporaryDirectory();
272 const configMap = new Map([['COMPOSIO_BASE_URL', 'https://backend.composio.dev']]);
273
274 return Effect.gen(function* () {
275 const clientSingleton = yield* ComposioClientSingleton;
276 const client = yield* clientSingleton.get();
277 yield* listTools(client);
278
279 const [, init] = fetchSpy.mock.calls[0]!;
280 const headers = new Headers((init as RequestInit).headers);
281 expect(headers.has('x-extra')).toBe(false);
282 expect(headers.has('x-user-api-key')).toBe(false);
283 expect(headers.has('x-api-key')).toBe(false);
284 expect(consoleSpies.flatMap(spy => spy.mock.calls)).toEqual([]);
285 }).pipe(
286 Effect.provide(
287 Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
288 )
289 );
290 });
291
292 it.effect('sends exactly one user credential when a user key is set', () => {
293 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
294 const homedir = tempy.temporaryDirectory();
295 const configMap = new Map([
296 ['COMPOSIO_USER_API_KEY', 'uak_single'],
297 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
298 ]);
299
300 return Effect.gen(function* () {
301 const clientSingleton = yield* ComposioClientSingleton;
302 const client = yield* clientSingleton.get();
303 // The client authenticates with `Auth.user`, so the user key is its one
304 // credential on every operation.
305 yield* client.auth.session.retrieveInfo();
306
307 const [input, init] = fetchSpy.mock.calls[0]!;
308 expect(String(input)).toContain('/api/v3.1/auth/session/info');
309 const headers = new Headers((init as RequestInit).headers);
310 expect(headers.get('x-user-api-key')).toBe('uak_single');
311 expect(headers.has('x-api-key')).toBe(false);
312 }).pipe(
313 Effect.provide(
314 Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
315 )
316 );
317 });
318
319 it.effect('supports an explicitly configured plain-HTTP backend without an extra opt-in', () => {
320 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
321 const homedir = tempy.temporaryDirectory();
322 const configMap = new Map([
323 ['COMPOSIO_USER_API_KEY', 'uak_insecure'],
324 ['COMPOSIO_BASE_URL', 'http://host.docker.internal:9900'],
325 ]);
326
327 return Effect.gen(function* () {
328 const clientSingleton = yield* ComposioClientSingleton;
329 const client = yield* clientSingleton.get();
330 yield* listTools(client);
331
332 expect(fetchSpy).toHaveBeenCalledOnce();
333 const [input, init] = fetchSpy.mock.calls[0]!;
334 expect(String(input)).toContain('http://host.docker.internal:9900/');
335 expect(new Headers((init as RequestInit).headers).get('x-user-api-key')).toBe('uak_insecure');
336 }).pipe(
337 Effect.provide(
338 Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
339 )
340 );
341 });
342
343 it.effect('counts requests and response bytes, with or without Content-Length', () => {
344 const homedir = tempy.temporaryDirectory();
345 const configMap = new Map([
346 ['COMPOSIO_USER_API_KEY', 'uak_metrics'],
347 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
348 ]);
349 const sized = (length: number) =>
350 new Response(JSON.stringify({ data: [] }).padEnd(length, ' '), {
351 status: 200,
352 headers: { 'Content-Type': 'application/json', 'Content-Length': String(length) },
353 });
354 const unsized = () =>
355 new Response(
356 new ReadableStream<Uint8Array>({
357 start(controller) {
358 controller.enqueue(new TextEncoder().encode('{"items":[]}'));
359 controller.close();
360 },
361 }),
362 { status: 200, headers: { 'Content-Type': 'application/json' } }
363 );
364
365 return Effect.gen(function* () {
366 const clientSingleton = yield* ComposioClientSingleton;
367 const client = yield* clientSingleton.get();
368 // Installed after the client exists: the counting fetch still resolves
369 // `globalThis.fetch` per call.
370 vi.spyOn(globalThis, 'fetch')
371 .mockResolvedValueOnce(sized(10))
372 .mockResolvedValueOnce(sized(20))
373 .mockResolvedValueOnce(unsized());
374 yield* listTools(client);
375 yield* listTools(client);
376 expect(yield* clientSingleton.getMetrics()).toEqual({ requests: 2, byteSize: 30 });
377
378 yield* listTools(client);
379 expect(yield* clientSingleton.getMetrics()).toEqual({
380 requests: 3,
381 byteSize: 30 + '{"items":[]}'.length,
382 });
383 }).pipe(
384 Effect.provide(
385 Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
386 )
387 );
388 });
389 });
390
391 describe('ComposioClientSingleton client', () => {
392 afterEach(() => {
393 vi.restoreAllMocks();
394 vi.unstubAllEnvs();
395 });
396
397 const baseConfig = (entries: ReadonlyArray<readonly [string, string]> = []) =>
398 new Map([['COMPOSIO_BASE_URL', 'https://backend.composio.dev'], ...entries]);
399
400 const singletonLayer = (configMap: Map<string, string>) =>
401 Layer.provide(
402 ComposioClientSingleton.Default,
403 withConfigLayer(configMap, tempy.temporaryDirectory())
404 );
405
406 const sentHeaders = (call: Parameters<typeof globalThis.fetch>) =>
407 new Headers((call[1] as RequestInit).headers);
408
409 it.effect('sends the scope credentials and the provenance headers, never x-api-key', () => {
410 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
411
412 return Effect.gen(function* () {
413 const clientSingleton = yield* ComposioClientSingleton;
414 const client = yield* clientSingleton.getFor({
415 userApiKey: 'uak_scope',
416 orgId: 'org_a',
417 projectId: 'proj_a',
418 });
419 yield* listTools(client);
420
421 expect(fetchSpy).toHaveBeenCalledOnce();
422 const headers = sentHeaders(fetchSpy.mock.calls[0]!);
423
424 expect(headers.get('x-user-api-key')).toBe('uak_scope');
425 expect(headers.get('x-org-id')).toBe('org_a');
426 expect(headers.get('x-project-id')).toBe('proj_a');
427 expect(headers.has('x-api-key')).toBe(false);
428 expect(headers.get('x-framework')).toBe('cli');
429 expect(headers.get('x-source')).toBe('CLI');
430 expect(headers.get('x-runtime')).toBe('NODEJS');
431 expect(headers.get('x-client-runtime')).toBe('nodejs');
432 expect(headers.get('x-runtime-version')).toBe(process.versions.node);
433 expect(headers.get('x-sdk-version')).toBe(APP_VERSION);
434 expect(headers.get('x-client-provenance')).toBe('@composio/cli');
435 expect(headers.get('x-client-version')).toBe(APP_VERSION);
436 expect(headers.get('x-client-language')).toBe('typescript');
437 expect(headers.get('x-client-library')).toBe('@composio/client');
438 expect(headers.get('x-client-library-version')).toBe(clientLibraryVersion);
439 }).pipe(Effect.provide(singletonLayer(baseConfig())));
440 });
441
442 it.effect('rejects a scope with an org and no project, and would send neither header', () => {
443 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
444
445 return Effect.gen(function* () {
446 const clientSingleton = yield* ComposioClientSingleton;
447 // @ts-expect-error a scope names the org and the project together
448 const client = yield* clientSingleton.getFor({ userApiKey: 'uak_scope', orgId: 'org_a' });
449 yield* listTools(client);
450
451 const headers = sentHeaders(fetchSpy.mock.calls[0]!);
452 expect(headers.get('x-user-api-key')).toBe('uak_scope');
453 expect(headers.has('x-org-id')).toBe(false);
454 expect(headers.has('x-project-id')).toBe(false);
455 }).pipe(Effect.provide(singletonLayer(baseConfig())));
456 });
457
458 it.effect('sends a project key in place of the user key, with the scope', () => {
459 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
460
461 return Effect.gen(function* () {
462 const clientSingleton = yield* ComposioClientSingleton;
463 const client = yield* clientSingleton.getFor({
464 projectApiKey: 'ak_project',
465 orgId: 'org_a',
466 projectId: 'proj_a',
467 });
468 yield* listTools(client);
469
470 const headers = sentHeaders(fetchSpy.mock.calls[0]!);
471 expect(headers.get('x-api-key')).toBe('ak_project');
472 expect(headers.has('x-user-api-key')).toBe(false);
473 expect(headers.get('x-org-id')).toBe('org_a');
474 expect(headers.get('x-project-id')).toBe('proj_a');
475 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_user']]))));
476 });
477
478 it.effect('refuses a request that names another org than its scope, before sending', () => {
479 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
480
481 return Effect.gen(function* () {
482 const clientSingleton = yield* ComposioClientSingleton;
483 const client = yield* clientSingleton.getFor({
484 userApiKey: 'uak_scope',
485 orgId: 'org_a',
486 projectId: 'proj_a',
487 });
488 const error = yield* Effect.flip(
489 client.get('/api/v3/tools/X/get_latest_version', { headers: { 'x-org-id': 'org_b' } })
490 );
491
492 expect(error._tag).toBe('@composio/client/ConfigurationError');
493 expect(fetchSpy).not.toHaveBeenCalled();
494 }).pipe(Effect.provide(singletonLayer(baseConfig())));
495 });
496
497 it.effect('keys clients for a memo by credential, org, and project, never by instance', () =>
498 Effect.gen(function* () {
499 const clientSingleton = yield* ComposioClientSingleton;
500 const scope = { userApiKey: 'uak_a', orgId: 'org_a', projectId: 'proj_a' };
501
502 const first = yield* clientSingleton.getFor(scope);
503 const second = yield* clientSingleton.getFor(scope);
504 const otherKey = yield* clientSingleton.getFor({ ...scope, userApiKey: 'uak_b' });
505 const otherProject = yield* clientSingleton.getFor({ ...scope, projectId: 'proj_b' });
506 const projectKey = yield* clientSingleton.getFor({
507 projectApiKey: 'ak_a',
508 orgId: 'org_a',
509 projectId: 'proj_a',
510 });
511 const { client: elsewhere } = stubComposioClient(okResponse);
512
513 expect(second).not.toBe(first);
514 expect(clientScopeKey(second)).toBe(clientScopeKey(first));
515 expect(clientScopeKey(otherKey)).not.toBe(clientScopeKey(first));
516 expect(clientScopeKey(otherProject)).not.toBe(clientScopeKey(first));
517 expect(clientScopeKey(projectKey)).not.toBe(clientScopeKey(first));
518 expect(clientScopeKey(first)).not.toContain('uak_a');
519 // A client built outside the singleton is keyed on its own.
520 expect(clientScopeKey(elsewhere)).toBe(clientScopeKey(elsewhere));
521 expect(clientScopeKey(elsewhere)).not.toBe(clientScopeKey(first));
522 }).pipe(Effect.provide(singletonLayer(baseConfig())))
523 );
524
525 it.effect('lists active connected accounts once per credential, org, project, and user', () => {
526 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(() =>
527 Promise.resolve(
528 new Response(
529 JSON.stringify({
530 items: [],
531 total_items: 0,
532 total_pages: 1,
533 current_page: 1,
534 next_cursor: null,
535 }),
536 { status: 200, headers: { 'Content-Type': 'application/json' } }
537 )
538 )
539 );
540
541 return Effect.gen(function* () {
542 const clientSingleton = yield* ComposioClientSingleton;
543 const scope = { orgId: 'org_a', projectId: 'proj_a' };
544
545 // Two lookups of one scope hand back two instances; they share one fetch.
546 yield* listActiveConnectedAccounts({
547 client: yield* clientSingleton.getFor(scope),
548 userId: 'user_1',
549 });
550 yield* listActiveConnectedAccounts({
551 client: yield* clientSingleton.getFor(scope),
552 userId: 'user_1',
553 });
554 expect(fetchSpy).toHaveBeenCalledTimes(1);
555
556 yield* listActiveConnectedAccounts({
557 client: yield* clientSingleton.getFor({ ...scope, projectId: 'proj_b' }),
558 userId: 'user_1',
559 });
560 yield* listActiveConnectedAccounts({
561 client: yield* clientSingleton.getFor(scope),
562 userId: 'user_2',
563 });
564 expect(fetchSpy).toHaveBeenCalledTimes(3);
565
566 // Another user key on the same scope never reads the first key's list.
567 yield* listActiveConnectedAccounts({
568 client: yield* clientSingleton.getFor({ ...scope, userApiKey: 'uak_other' }),
569 userId: 'user_1',
570 });
571 expect(fetchSpy).toHaveBeenCalledTimes(4);
572 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_memo']]))));
573 });
574
575 it.effect('counts requests on its own transport beside an application FetchHttpClient', () => {
576 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
577
578 return Effect.gen(function* () {
579 const clientSingleton = yield* ComposioClientSingleton;
580 const client = yield* clientSingleton.getFor({ userApiKey: 'uak_scope' });
581 yield* listTools(client);
582
583 expect(fetchSpy).toHaveBeenCalledOnce();
584 expect((yield* clientSingleton.getMetrics()).requests).toBe(1);
585 }).pipe(
586 // The application's transport is built first, so a memoized
587 // `FetchHttpClient.layer` would be the one that counts nothing.
588 Effect.provide(
589 Layer.provide(
590 ComposioClientSingleton.Default,
591 Layer.merge(
592 withConfigLayer(baseConfig(), tempy.temporaryDirectory()),
593 FetchHttpClient.layer
594 )
595 )
596 )
597 );
598 });
599
600 it.effect('ignores ambient COMPOSIO_API_KEY and COMPOSIO_BASE_URL', () => {
601 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
602 vi.stubEnv('COMPOSIO_API_KEY', 'ak_ambient');
603 vi.stubEnv('COMPOSIO_BASE_URL', 'https://ambient.invalid');
604
605 return Effect.gen(function* () {
606 const clientSingleton = yield* ComposioClientSingleton;
607 const client = yield* clientSingleton.getFor({ userApiKey: 'uak_scope' });
608 yield* listTools(client);
609
610 const call = fetchSpy.mock.calls[0]!;
611 expect(String(call[0])).toContain('https://backend.composio.dev/');
612 const headers = sentHeaders(call);
613 expect(headers.get('x-user-api-key')).toBe('uak_scope');
614 expect(headers.has('x-api-key')).toBe(false);
615 }).pipe(Effect.provide(singletonLayer(baseConfig())));
616 });
617
618 it.effect('resolves globalThis.fetch on every request', () => {
619 const firstSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
620
621 return Effect.gen(function* () {
622 const clientSingleton = yield* ComposioClientSingleton;
623 const client = yield* clientSingleton.get();
624 yield* listTools(client);
625 expect(firstSpy).toHaveBeenCalledOnce();
626
627 firstSpy.mockRestore();
628 const secondSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
629 yield* listTools(client);
630
631 expect(secondSpy).toHaveBeenCalledOnce();
632 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_late']]))));
633 });
634
635 // Live clock: the retry backoff is a real sleep, cut to nothing by the
636 // `retry-after-ms` response header.
637 it.live('counts every attempt of a retried call', () => {
638 vi.spyOn(globalThis, 'fetch')
639 .mockResolvedValueOnce(
640 new Response('{}', {
641 status: 500,
642 headers: { 'Content-Type': 'application/json', 'retry-after-ms': '0' },
643 })
644 )
645 .mockResolvedValueOnce(
646 new Response(JSON.stringify(['GITHUB_CREATE_ISSUE']), {
647 status: 200,
648 headers: { 'Content-Type': 'application/json' },
649 })
650 );
651
652 return Effect.gen(function* () {
653 const clientSingleton = yield* ComposioClientSingleton;
654 const client = yield* clientSingleton.get();
655
656 expect(yield* client.tools.retrieveEnum(idempotent)).toEqual(['GITHUB_CREATE_ISSUE']);
657 expect((yield* clientSingleton.getMetrics()).requests).toBe(2);
658 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_retry']]))));
659 });
660
661 it.effect('sends a call that is not marked idempotent once', () => {
662 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(() =>
663 Promise.resolve(
664 new Response('{}', {
665 status: 500,
666 headers: { 'Content-Type': 'application/json', 'retry-after-ms': '0' },
667 })
668 )
669 );
670
671 return Effect.gen(function* () {
672 const clientSingleton = yield* ComposioClientSingleton;
673 const client = yield* clientSingleton.get();
674 const error = yield* Effect.flip(
675 client.triggerInstances.manage.update('ti_1', { status: 'enable' })
676 );
677
678 expect(error._tag).toBe('@composio/client/InternalServerError');
679 expect(fetchSpy).toHaveBeenCalledTimes(1);
680 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_once']]))));
681 });
682
683 it.effect('counts requests when the application already provides a fetch transport', () => {
684 vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
685
686 return Effect.gen(function* () {
687 const clientSingleton = yield* ComposioClientSingleton;
688 const client = yield* clientSingleton.get();
689 yield* listTools(client);
690
691 expect((yield* clientSingleton.getMetrics()).requests).toBe(1);
692 }).pipe(
693 Effect.provide(
694 Layer.provide(
695 ComposioClientSingleton.Default,
696 Layer.mergeAll(
697 withConfigLayer(
698 baseConfig([['COMPOSIO_USER_API_KEY', 'uak_metrics']]),
699 tempy.temporaryDirectory()
700 ),
701 FetchHttpClient.layer
702 )
703 )
704 )
705 );
706 });
707
708 it.effect('drops the deprecation notice the client logs at the CLI logger', () => {
709 vi.spyOn(globalThis, 'fetch').mockResolvedValue(
710 new Response(JSON.stringify({ data: [] }), {
711 status: 200,
712 headers: {
713 'Content-Type': 'application/json',
714 Deprecation: 'true',
715 Sunset: 'Wed, 31 Dec 2027 23:59:59 GMT',
716 Link: '<https://docs.composio.dev/migration>; rel="deprecation"',
717 },
718 })
719 );
720 const logged: Array<unknown> = [];
721 const shown: Array<unknown> = [];
722 const recordInto = (records: Array<unknown>) =>
723 Logger.make<unknown, void>(({ message }) => {
724 records.push(message);
725 });
726 const capturingLogger = Logger.layer([
727 recordInto(logged),
728 withoutClientNotices(recordInto(shown)),
729 ]);
730
731 return Effect.gen(function* () {
732 const clientSingleton = yield* ComposioClientSingleton;
733 const client = yield* clientSingleton.get();
734 yield* listTools(client);
735
736 expect(logged).toHaveLength(1);
737 expect(shown).toEqual([]);
738 }).pipe(
739 Effect.provide(
740 Layer.merge(
741 singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_quiet']])),
742 capturingLogger
743 )
744 )
745 );
746 });
747
748 it.effect('validates a response only for a call that asks for it', () => {
749 // `okResponse` is not a toolkits page.
750 vi.spyOn(globalThis, 'fetch').mockImplementation(() => Promise.resolve(okResponse()));
751
752 return Effect.gen(function* () {
753 const clientSingleton = yield* ComposioClientSingleton;
754 const client = yield* clientSingleton.get();
755
756 const lenient = yield* Effect.exit(client.toolkits.list({ limit: 1 }));
757 const strict = yield* Effect.flip(client.toolkits.list({ limit: 1 }, validated));
758
759 expect(Exit.isSuccess(lenient)).toBe(true);
760 expect(strict._tag).toBe('@composio/client/DecodeError');
761 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_strict']]))));
762 });
763
764 it.effect("reports an invalid base URL as the client's own configuration error", () =>
765 Effect.gen(function* () {
766 const clientSingleton = yield* ComposioClientSingleton;
767 const error = yield* Effect.flip(clientSingleton.getFor({ userApiKey: 'uak_a' }));
768
769 expect(error._tag).toBe('@composio/client/ConfigurationError');
770 }).pipe(Effect.provide(singletonLayer(new Map([['COMPOSIO_BASE_URL', 'not a url']]))))
771 );
772
773 it.effect('does not keep a client that could not be built', () =>
774 Effect.gen(function* () {
775 const clientSingleton = yield* ComposioClientSingleton;
776 const scope = { userApiKey: 'uak_a' };
777
778 const first = yield* Effect.flip(clientSingleton.getFor(scope));
779 const second = yield* Effect.flip(clientSingleton.getFor(scope));
780
781 expect(first._tag).toBe('@composio/client/ConfigurationError');
782 expect(second).not.toBe(first);
783 }).pipe(Effect.provide(singletonLayer(new Map([['COMPOSIO_BASE_URL', 'not a url']]))))
784 );
785 });