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 487 lines 17.3 KB
Raw
1 import { cliRequestHeaders } from './client-provenance';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 import { Data, Effect, Option, Predicate, Result, Schema } from 'effect';
5 import { APP_CONFIG } from 'src/config';
6 import { JsonRecordSchema } from 'src/effects/json';
7 import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 import { atomicWritePrivateFileString, ensurePrivateFileMode } from 'src/utils/atomic-write';
9 import { ComposioUserContext } from 'src/services/user-context';
10 import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
11 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
12 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
13
14 export const AGENT_CONFIG_FILE_NAME = 'agent.json';
15 export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';
16
17 export type AgentStatus = 'READY' | 'PENDING' | 'UNKNOWN';
18
19 const UnknownFields = [JsonRecordSchema] as const;
20
21 const AgentComposioCredentials = Schema.StructWithRest(
22 Schema.Struct({
23 member_id: Schema.optional(Schema.NullOr(Schema.String)),
24 org_id: Schema.optional(Schema.NullOr(Schema.String)),
25 project_id: Schema.optional(Schema.NullOr(Schema.String)),
26 api_key: Schema.optional(Schema.NullOr(Schema.String)),
27 user_api_key: Schema.optional(Schema.NullOr(Schema.String)),
28 }),
29 UnknownFields
30 );
31 export type AgentComposioCredentials = Schema.Schema.Type<typeof AgentComposioCredentials>;
32
33 const AgentIdentity = Schema.StructWithRest(
34 Schema.Struct({
35 status: Schema.optional(Schema.NullOr(Schema.String)),
36 request_id: Schema.optional(Schema.NullOr(Schema.String)),
37 slug: Schema.optional(Schema.NullOr(Schema.String)),
38 email: Schema.optional(Schema.NullOr(Schema.String)),
39 agent_key: Schema.optional(Schema.NullOr(Schema.String)),
40 composio_agent_key: Schema.optional(Schema.NullOr(Schema.String)),
41 claimed_by: Schema.optional(Schema.NullOr(Schema.String)),
42 claimed_at: Schema.optional(Schema.NullOr(Schema.String)),
43 composio: Schema.optional(AgentComposioCredentials),
44 }),
45 UnknownFields
46 );
47 export type AgentIdentity = Schema.Schema.Type<typeof AgentIdentity>;
48
49 const AgentMailMessage = Schema.StructWithRest(
50 Schema.Struct({
51 id: Schema.optional(Schema.NullOr(Schema.String)),
52 thread_id: Schema.optional(Schema.NullOr(Schema.String)),
53 from: Schema.optional(Schema.NullOr(Schema.String)),
54 to: Schema.optional(Schema.NullOr(Schema.String)),
55 subject: Schema.optional(Schema.NullOr(Schema.String)),
56 preview: Schema.optional(Schema.NullOr(Schema.String)),
57 received_at: Schema.optional(Schema.NullOr(Schema.String)),
58 }),
59 UnknownFields
60 );
61 export type AgentMailMessage = Schema.Schema.Type<typeof AgentMailMessage>;
62
63 const AgentMailResponse = Schema.StructWithRest(
64 Schema.Struct({
65 count: Schema.optional(Schema.Number),
66 messages: Schema.optional(Schema.Array(AgentMailMessage)),
67 }),
68 UnknownFields
69 );
70 export type AgentMailResponse = Schema.Schema.Type<typeof AgentMailResponse>;
71
72 const AgentClaimResponse = Schema.StructWithRest(
73 Schema.Struct({
74 status: Schema.optional(Schema.NullOr(Schema.String)),
75 email: Schema.optional(Schema.NullOr(Schema.String)),
76 org_id: Schema.optional(Schema.NullOr(Schema.String)),
77 invite_code: Schema.optional(Schema.NullOr(Schema.String)),
78 }),
79 UnknownFields
80 );
81 export type AgentClaimResponse = Schema.Schema.Type<typeof AgentClaimResponse>;
82
83 export class AgentAuthError extends Data.TaggedError('services/AgentAuthError')<{
84 readonly message: string;
85 readonly nextSteps: ReadonlyArray<string>;
86 }> {}
87
88 export class AgentRequestError extends Data.TaggedError('services/AgentRequestError')<{
89 readonly message: string;
90 readonly pathname: string;
91 readonly status?: number;
92 readonly cause?: unknown;
93 }> {}
94
95 export class AgentResponseDecodeError extends Data.TaggedError(
96 'services/AgentResponseDecodeError'
97 )<{
98 readonly message: string;
99 readonly pathname: string;
100 readonly cause: unknown;
101 }> {}
102
103 const agentsBaseURL = APP_CONFIG.AGENTS_BASE_URL.pipe(
104 Effect.orDie,
105 Effect.map(value => (value ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, ''))
106 );
107
108 const decodeAgentResponse =
109 <A, I>(pathname: string, schema: Schema.Codec<A, I>) =>
110 (payload: unknown) =>
111 Schema.decodeUnknownEffect(schema)(payload).pipe(
112 Effect.mapError(
113 cause =>
114 new AgentResponseDecodeError({
115 message: `agents.composio.dev returned an invalid response for ${pathname}`,
116 pathname,
117 cause,
118 })
119 )
120 );
121
122 export const normalizeAgentStatus = (status: string | null | undefined): AgentStatus => {
123 const normalized = status?.trim().toUpperCase();
124 if (normalized === 'READY') return 'READY';
125 if (normalized === 'PENDING') return 'PENDING';
126 return 'UNKNOWN';
127 };
128
129 export const getAgentKey = (identity: AgentIdentity): string | undefined => {
130 if (typeof identity.composio_agent_key === 'string') return identity.composio_agent_key;
131 if (typeof identity.agent_key === 'string') return identity.agent_key;
132 return undefined;
133 };
134
135 export const isAgentIdentityForApiKey = (identity: AgentIdentity, apiKey: string): boolean =>
136 Boolean(getAgentKey(identity) && identity.composio?.user_api_key === apiKey);
137
138 const normalizeDecodedAgentIdentity = (
139 identity: AgentIdentity,
140 fallbackAgentKey?: string
141 ): AgentIdentity => {
142 const agentKey = identity.composio_agent_key ?? identity.agent_key ?? fallbackAgentKey;
143
144 return agentKey ? { ...identity, agent_key: agentKey, composio_agent_key: agentKey } : identity;
145 };
146
147 export const normalizeAgentIdentity = (
148 payload: unknown,
149 fallbackAgentKey?: string
150 ): AgentIdentity =>
151 normalizeDecodedAgentIdentity(
152 Schema.decodeUnknownOption(AgentIdentity)(payload).pipe(
153 Option.getOrElse((): AgentIdentity => ({}))
154 ),
155 fallbackAgentKey
156 );
157
158 export type SafeAgentSummary = {
159 readonly account_type: 'agent';
160 readonly status: AgentStatus;
161 readonly slug: string | null;
162 readonly email: string | null;
163 readonly org_id: string | null;
164 readonly project_id: string | null;
165 readonly member_id: string | null;
166 readonly claimed_by: string | null;
167 readonly claimed_at: string | null;
168 };
169
170 export const safeAgentSummary = (identity: AgentIdentity): SafeAgentSummary => ({
171 account_type: 'agent',
172 status: normalizeAgentStatus(identity.status),
173 slug: identity.slug ?? null,
174 email: identity.email ?? null,
175 org_id: identity.composio?.org_id ?? null,
176 project_id: identity.composio?.project_id ?? null,
177 member_id: identity.composio?.member_id ?? null,
178 claimed_by: identity.claimed_by ?? null,
179 claimed_at: identity.claimed_at ?? null,
180 });
181
182 /** The title both agent summary notes print. */
183 export const AGENT_SUMMARY_NOTE_TITLE = 'Composio Agent';
184
185 /**
186 * The note lines every agent summary shares, in print order. Callers append their
187 * command-specific last line (whoami: claimed by; signup: where the agent key lives).
188 */
189 export const agentSummaryLines = (summary: SafeAgentSummary): readonly string[] => [
190 `Type: agent`,
191 `Status: ${summary.status}`,
192 `Email: ${summary.email ?? 'unknown'}`,
193 `Slug: ${summary.slug ?? 'unknown'}`,
194 `Current Org ID: ${summary.org_id ?? 'pending'}`,
195 `Project ID: ${summary.project_id ?? 'pending'}`,
196 ];
197
198 export const agentConfigPath = Effect.gen(function* () {
199 const path = yield* Path.Path;
200 const cacheDir = yield* setupCacheDir;
201 return path.join(cacheDir, AGENT_CONFIG_FILE_NAME);
202 });
203
204 export const readStoredAgentIdentity = Effect.gen(function* () {
205 const fs = yield* FileSystem.FileSystem;
206 const configPath = yield* agentConfigPath;
207
208 const exists = yield* fs.exists(configPath);
209 if (!exists) return Option.none<AgentIdentity>();
210
211 return yield* ensurePrivateFileMode({ fs, target: configPath }).pipe(
212 Effect.andThen(fs.readFileString(configPath, 'utf8')),
213 Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(AgentIdentity))),
214 Effect.map(normalizeDecodedAgentIdentity),
215 Effect.tapError(error => Effect.logDebug('Failed to read agent identity:', error)),
216 Effect.option
217 );
218 });
219
220 export const writeStoredAgentIdentity = (identity: AgentIdentity) =>
221 Effect.gen(function* () {
222 const fs = yield* FileSystem.FileSystem;
223 const configPath = yield* agentConfigPath;
224 const normalized = normalizeDecodedAgentIdentity(identity);
225 yield* atomicWritePrivateFileString({
226 fs,
227 target: configPath,
228 contents: `${JSON.stringify(normalized, null, 2)}\n`,
229 });
230 return normalized;
231 });
232
233 export const removeStoredAgentIdentity = Effect.gen(function* () {
234 const fs = yield* FileSystem.FileSystem;
235 const configPath = yield* agentConfigPath;
236 yield* fs.remove(configPath).pipe(Effect.ignore);
237 });
238
239 const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>
240 Effect.gen(function* () {
241 const baseURL = yield* agentsBaseURL;
242 const response = yield* Effect.tryPromise({
243 try: () =>
244 fetch(`${baseURL}${pathname}`, {
245 redirect: 'error',
246 ...init,
247 headers: {
248 ...cliRequestHeaders(),
249 Accept: 'application/json',
250 ...(init.body ? { 'Content-Type': 'application/json' } : {}),
251 ...(init.headers ?? {}),
252 },
253 }),
254 catch: cause =>
255 new AgentRequestError({
256 message: `agents.composio.dev request failed for ${pathname}`,
257 pathname,
258 cause,
259 }),
260 });
261
262 const text = yield* Effect.tryPromise({
263 try: () => response.text(),
264 catch: cause =>
265 new AgentRequestError({
266 message: `Failed to read agents.composio.dev response for ${pathname}`,
267 pathname,
268 status: response.status,
269 cause,
270 }),
271 });
272 const payload = text
273 ? yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(text).pipe(
274 Effect.mapError(
275 cause =>
276 new AgentResponseDecodeError({
277 message: `agents.composio.dev returned invalid JSON for ${pathname}`,
278 pathname,
279 cause,
280 })
281 )
282 )
283 : {};
284
285 if (!response.ok) {
286 const message =
287 Predicate.isObject(payload) && typeof payload.message === 'string'
288 ? payload.message
289 : `agents.composio.dev request failed with HTTP ${response.status}`;
290 return yield* new AgentRequestError({
291 message,
292 pathname,
293 status: response.status,
294 });
295 }
296
297 return payload;
298 });
299
300 export const signupAgent = (params: { wait?: boolean } = {}) =>
301 Effect.gen(function* () {
302 const wait = params.wait ?? true;
303 const payload = yield* fetchAgentJson(`/api/signup${wait ? '' : '?wait=0'}`, {
304 method: 'POST',
305 body: JSON.stringify({}),
306 });
307 const identity = yield* decodeAgentResponse('/api/signup', AgentIdentity)(payload);
308 return yield* writeStoredAgentIdentity(identity);
309 });
310
311 export const fetchAgentWhoami = (agentKey: string) =>
312 Effect.gen(function* () {
313 const payload = yield* fetchAgentJson('/api/whoami', {
314 method: 'GET',
315 headers: { Authorization: `Bearer ${agentKey}` },
316 });
317 const identity = yield* decodeAgentResponse('/api/whoami', AgentIdentity)(payload);
318 return normalizeDecodedAgentIdentity(identity, agentKey);
319 });
320
321 export const fetchAgentInbox = (params: { agentKey: string; limit?: number }) =>
322 Effect.gen(function* () {
323 const pathname = `/api/mail?limit=${encodeURIComponent(String(params.limit ?? 50))}`;
324 const payload = yield* fetchAgentJson(pathname, {
325 method: 'GET',
326 headers: { Authorization: `Bearer ${params.agentKey}` },
327 });
328 return yield* decodeAgentResponse(pathname, AgentMailResponse)(payload);
329 });
330
331 export const claimAgent = (params: { agentKey: string; email: string }) =>
332 Effect.gen(function* () {
333 const pathname = '/api/claim';
334 const payload = yield* fetchAgentJson(pathname, {
335 method: 'POST',
336 headers: { Authorization: `Bearer ${params.agentKey}` },
337 body: JSON.stringify({ email: params.email }),
338 });
339 return yield* decodeAgentResponse(pathname, AgentClaimResponse)(payload);
340 });
341
342 const humanLoginError = () =>
343 new AgentAuthError({
344 message: 'This CLI is currently signed in to Composio as a regular user, not an agent.',
345 nextSteps: [
346 'To switch to an existing agent: run `composio logout`, then `composio agent login <composio_agent_key>`.',
347 'To create a new agent: run `composio logout`, then `composio signup`.',
348 ],
349 });
350
351 export const ensureAgentSignupAllowed = Effect.gen(function* () {
352 const ctx = yield* ComposioUserContext;
353 const apiKey = ctx.data.apiKey;
354 if (Option.isNone(apiKey)) return;
355
356 const stored = yield* readStoredAgentIdentity;
357 if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, apiKey.value)) return;
358
359 return yield* humanLoginError();
360 });
361
362 export const getCurrentLoggedInAgent = Effect.gen(function* () {
363 const ctx = yield* ComposioUserContext;
364 const currentApiKey = ctx.data.apiKey;
365 if (Option.isNone(currentApiKey)) return Option.none<AgentIdentity>();
366
367 const stored = yield* readStoredAgentIdentity;
368 if (Option.isNone(stored)) return Option.none<AgentIdentity>();
369
370 return isAgentIdentityForApiKey(stored.value, currentApiKey.value)
371 ? stored
372 : Option.none<AgentIdentity>();
373 });
374
375 export const resolveStoredAgentKey = Effect.gen(function* () {
376 const ctx = yield* ComposioUserContext;
377 const stored = yield* readStoredAgentIdentity;
378 const currentApiKey = ctx.data.apiKey;
379
380 if (Option.isSome(currentApiKey)) {
381 if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, currentApiKey.value)) {
382 const agentKey = getAgentKey(stored.value);
383 if (agentKey) return agentKey;
384 }
385
386 return yield* humanLoginError();
387 }
388
389 if (Option.isNone(stored)) {
390 return yield* new AgentAuthError({
391 message: 'No Composio agent identity is saved on this machine.',
392 nextSteps: [
393 'To create a new agent: run `composio signup` or `composio agent signup`.',
394 'To restore an existing agent: run `composio agent login <composio_agent_key>`.',
395 ],
396 });
397 }
398
399 const agentKey = getAgentKey(stored.value);
400 if (!agentKey) {
401 return yield* new AgentAuthError({
402 message: 'The saved Composio agent identity is missing its composio_agent_key.',
403 nextSteps: [
404 'If you saved the key, run `composio agent login <composio_agent_key>`.',
405 'Otherwise create a new agent with `composio signup`.',
406 ],
407 });
408 }
409
410 return agentKey;
411 });
412
413 const isAgentKeyRejection = (error: AgentRequestError | AgentResponseDecodeError): boolean =>
414 error instanceof AgentRequestError && (error.status === 401 || error.status === 403);
415
416 /**
417 * Reuse-only counterpart of {@link getOrSignupReadyAgent}: refreshes and
418 * returns a stored READY identity but never signs up a new agent.
419 */
420 export const getStoredReadyAgent = Effect.gen(function* () {
421 const stored = yield* readStoredAgentIdentity;
422 if (Option.isNone(stored)) return Option.none<AgentIdentity>();
423
424 const agentKey = getAgentKey(stored.value);
425 if (!agentKey) return Option.none<AgentIdentity>();
426
427 const remote = yield* fetchAgentWhoami(agentKey).pipe(Effect.result);
428 // An auth rejection means the API examined and refused this key — the stored
429 // identity is revoked, not unreachable. Only transport-shaped failures may
430 // fall back to the on-disk identity.
431 if (Result.isFailure(remote) && isAgentKeyRejection(remote.failure)) {
432 return Option.none<AgentIdentity>();
433 }
434
435 const identity = Result.isSuccess(remote)
436 ? yield* writeStoredAgentIdentity(remote.success)
437 : stored.value;
438
439 const ready =
440 normalizeAgentStatus(identity.status) === 'READY' &&
441 Boolean(identity.composio?.user_api_key) &&
442 Boolean(identity.composio?.org_id);
443
444 return ready ? Option.some(identity) : Option.none<AgentIdentity>();
445 });
446
447 export const getOrSignupReadyAgent = (params: { force?: boolean } = {}) =>
448 Effect.gen(function* () {
449 if (!params.force) {
450 const stored = yield* readStoredAgentIdentity;
451 if (Option.isSome(stored)) {
452 const agentKey = getAgentKey(stored.value);
453 if (agentKey) {
454 const remote = yield* fetchAgentWhoami(agentKey).pipe(Effect.option);
455 if (Option.isSome(remote)) {
456 const saved = yield* writeStoredAgentIdentity(remote.value);
457 if (normalizeAgentStatus(saved.status) === 'READY') return saved;
458 }
459 }
460 }
461 }
462
463 return yield* signupAgent({ wait: true });
464 });
465
466 export const loginWithAgentIdentity = (identity: AgentIdentity) =>
467 Effect.gen(function* () {
468 const ctx = yield* ComposioUserContext;
469 const userApiKey = identity.composio?.user_api_key;
470 const orgId = identity.composio?.org_id;
471
472 if (!userApiKey || !orgId) {
473 return yield* new AgentAuthError({
474 message: 'Agent identity is not ready yet.',
475 nextSteps: ['Run `composio agent whoami` and try again once status is READY.'],
476 });
477 }
478
479 // agents.composio.dev issued this key, not whichever backend an earlier login recorded.
480 yield* ctx.login(userApiKey, orgId, undefined, { issuer: 'environment' });
481 // Best-effort analytics stitch after the credential persists; must never break login.
482 yield* getSessionInfoByUserApiKey({ userApiKey, orgId }).pipe(
483 Effect.flatMap(info => linkApolloIdentityForAnalytics(info.org_member.id, userApiKey)),
484 Effect.catchCause(() => Effect.void)
485 );
486 yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId });
487 });