1
import { FileSystem } from '@effect/platform';
2
-import { Data, Effect, Option } from 'effect';
2
+import { Data, Effect, Option, Predicate, Schema } from 'effect';
3
import path from 'node:path';
4
import { setupCacheDir } from 'src/effects/setup-cache-dir';
5
import { ComposioUserContext } from 'src/services/user-context';
10
11
export type AgentStatus = 'READY' | 'PENDING' | 'UNKNOWN';
12
13
-export interface AgentComposioCredentials {
14
- readonly member_id?: string;
15
- readonly org_id?: string;
16
- readonly project_id?: string;
17
- readonly api_key?: string;
18
- readonly user_api_key?: string;
19
-}
20
-
21
-export interface AgentIdentity {
22
- readonly status?: string;
23
- readonly request_id?: string;
24
- readonly slug?: string;
25
- readonly email?: string;
26
- readonly agent_key?: string;
27
- readonly composio_agent_key?: string;
28
- readonly claimed_by?: string | null;
29
- readonly claimed_at?: string | null;
30
- readonly composio?: AgentComposioCredentials;
31
- readonly [key: string]: unknown;
32
-}
33
-
34
-export interface AgentMailMessage {
35
- readonly id?: string;
36
- readonly thread_id?: string;
37
- readonly from?: string;
38
- readonly to?: string;
39
- readonly subject?: string;
40
- readonly preview?: string;
41
- readonly received_at?: string;
42
- readonly [key: string]: unknown;
43
-}
44
-
45
-export interface AgentMailResponse {
46
- readonly count?: number;
47
- readonly messages?: ReadonlyArray<AgentMailMessage>;
48
- readonly [key: string]: unknown;
49
-}
50
-
51
-export interface AgentClaimResponse {
52
- readonly status?: string;
53
- readonly email?: string;
54
- readonly org_id?: string;
55
- readonly invite_code?: string;
56
- readonly [key: string]: unknown;
57
-}
13
+const UnknownFields = Schema.Record({ key: Schema.String, value: Schema.Unknown });
14
+
15
+const AgentComposioCredentials = Schema.Struct({
16
+ member_id: Schema.optional(Schema.NullOr(Schema.String)),
17
+ org_id: Schema.optional(Schema.NullOr(Schema.String)),
18
+ project_id: Schema.optional(Schema.NullOr(Schema.String)),
19
+ api_key: Schema.optional(Schema.NullOr(Schema.String)),
20
+ user_api_key: Schema.optional(Schema.NullOr(Schema.String)),
21
+}).pipe(Schema.extend(UnknownFields));
22
+export type AgentComposioCredentials = Schema.Schema.Type<typeof AgentComposioCredentials>;
23
+
24
+const AgentIdentity = Schema.Struct({
25
+ status: Schema.optional(Schema.NullOr(Schema.String)),
26
+ request_id: Schema.optional(Schema.NullOr(Schema.String)),
27
+ slug: Schema.optional(Schema.NullOr(Schema.String)),
28
+ email: Schema.optional(Schema.NullOr(Schema.String)),
29
+ agent_key: Schema.optional(Schema.NullOr(Schema.String)),
30
+ composio_agent_key: Schema.optional(Schema.NullOr(Schema.String)),
31
+ claimed_by: Schema.optional(Schema.NullOr(Schema.String)),
32
+ claimed_at: Schema.optional(Schema.NullOr(Schema.String)),
33
+ composio: Schema.optional(AgentComposioCredentials),
34
+}).pipe(Schema.extend(UnknownFields));
35
+export type AgentIdentity = Schema.Schema.Type<typeof AgentIdentity>;
36
+
37
+const AgentMailMessage = Schema.Struct({
38
+ id: Schema.optional(Schema.NullOr(Schema.String)),
39
+ thread_id: Schema.optional(Schema.NullOr(Schema.String)),
40
+ from: Schema.optional(Schema.NullOr(Schema.String)),
41
+ to: Schema.optional(Schema.NullOr(Schema.String)),
42
+ subject: Schema.optional(Schema.NullOr(Schema.String)),
43
+ preview: Schema.optional(Schema.NullOr(Schema.String)),
44
+ received_at: Schema.optional(Schema.NullOr(Schema.String)),
45
+}).pipe(Schema.extend(UnknownFields));
46
+export type AgentMailMessage = Schema.Schema.Type<typeof AgentMailMessage>;
47
+
48
+const AgentMailResponse = Schema.Struct({
49
+ count: Schema.optional(Schema.Number),
50
+ messages: Schema.optional(Schema.Array(AgentMailMessage)),
51
+}).pipe(Schema.extend(UnknownFields));
52
+export type AgentMailResponse = Schema.Schema.Type<typeof AgentMailResponse>;
53
+
54
+const AgentClaimResponse = Schema.Struct({
55
+ status: Schema.optional(Schema.NullOr(Schema.String)),
56
+ email: Schema.optional(Schema.NullOr(Schema.String)),
57
+ org_id: Schema.optional(Schema.NullOr(Schema.String)),
58
+ invite_code: Schema.optional(Schema.NullOr(Schema.String)),
59
+}).pipe(Schema.extend(UnknownFields));
60
+export type AgentClaimResponse = Schema.Schema.Type<typeof AgentClaimResponse>;
61
62
export class AgentAuthError extends Data.TaggedError('services/AgentAuthError')<{
63
readonly message: string;
64
readonly nextSteps: ReadonlyArray<string>;
65
}> {}
66
67
+export class AgentRequestError extends Data.TaggedError('services/AgentRequestError')<{
68
+ readonly message: string;
69
+ readonly pathname: string;
70
+ readonly status?: number;
71
+ readonly cause?: unknown;
72
+}> {}
73
+
74
+export class AgentResponseDecodeError extends Data.TaggedError(
75
+ 'services/AgentResponseDecodeError'
76
+)<{
77
+ readonly message: string;
78
+ readonly pathname: string;
79
+ readonly cause: unknown;
80
+}> {}
81
+
82
const agentsBaseURL = (): string =>
83
(process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, '');
84
67
-const asRecord = (value: unknown): Record<string, unknown> =>
68
- value && typeof value === 'object' && !Array.isArray(value)
69
- ? (value as Record<string, unknown>)
70
- : {};
71
-
72
-const readJson = (value: string): unknown => JSON.parse(value) as unknown;
85
+const decodeAgentResponse =
86
+ <A, I>(pathname: string, schema: Schema.Schema<A, I>) =>
87
+ (payload: unknown) =>
88
+ Schema.decodeUnknown(schema)(payload).pipe(
89
+ Effect.mapError(
90
+ cause =>
91
+ new AgentResponseDecodeError({
92
+ message: `agents.composio.dev returned an invalid response for ${pathname}`,
93
+ pathname,
94
+ cause,
95
+ })
96
+ )
97
+ );
98
74
-export const normalizeAgentStatus = (status: string | undefined): AgentStatus => {
99
+export const normalizeAgentStatus = (status: string | null | undefined): AgentStatus => {
100
const normalized = status?.trim().toUpperCase();
101
if (normalized === 'READY') return 'READY';
102
if (normalized === 'PENDING') return 'PENDING';
112
export const isAgentIdentityForApiKey = (identity: AgentIdentity, apiKey: string): boolean =>
113
Boolean(getAgentKey(identity) && identity.composio?.user_api_key === apiKey);
114
115
+const normalizeDecodedAgentIdentity = (
116
+ identity: AgentIdentity,
117
+ fallbackAgentKey?: string
118
+): AgentIdentity => {
119
+ const agentKey = identity.composio_agent_key ?? identity.agent_key ?? fallbackAgentKey;
120
+
121
+ return agentKey ? { ...identity, agent_key: agentKey, composio_agent_key: agentKey } : identity;
122
+};
123
+
124
export const normalizeAgentIdentity = (
125
payload: unknown,
126
fallbackAgentKey?: string
93
-): AgentIdentity => {
94
- const record = asRecord(payload);
95
- const agentKey =
96
- (typeof record.composio_agent_key === 'string' ? record.composio_agent_key : undefined) ??
97
- (typeof record.agent_key === 'string' ? record.agent_key : undefined) ??
98
- fallbackAgentKey;
99
-
100
- const normalized: Record<string, unknown> = { ...record };
101
- if (agentKey) {
102
- normalized.agent_key = agentKey;
103
- normalized.composio_agent_key = agentKey;
104
- }
127
+): AgentIdentity =>
128
+ normalizeDecodedAgentIdentity(
129
+ Schema.decodeUnknownOption(AgentIdentity)(payload).pipe(
130
+ Option.getOrElse((): AgentIdentity => ({}))
131
+ ),
132
+ fallbackAgentKey
133
+ );
134
106
- return normalized as AgentIdentity;
135
+type SafeAgentSummary = {
136
+ readonly account_type: 'agent';
137
+ readonly status: AgentStatus;
138
+ readonly slug: string | null;
139
+ readonly email: string | null;
140
+ readonly org_id: string | null;
141
+ readonly project_id: string | null;
142
+ readonly member_id: string | null;
143
+ readonly claimed_by: string | null;
144
+ readonly claimed_at: string | null;
145
};
146
109
-export const safeAgentSummary = (identity: AgentIdentity) => ({
110
- account_type: 'agent' as const,
147
+export const safeAgentSummary = (identity: AgentIdentity): SafeAgentSummary => ({
148
+ account_type: 'agent',
149
status: normalizeAgentStatus(identity.status),
150
slug: identity.slug ?? null,
151
email: identity.email ?? null,
169
if (!exists) return Option.none<AgentIdentity>();
170
171
return yield* fs.readFileString(configPath, 'utf8').pipe(
134
- Effect.map(raw => Option.some(normalizeAgentIdentity(readJson(raw)))),
135
- Effect.catchAll(error =>
136
- Effect.gen(function* () {
137
- yield* Effect.logDebug('Failed to read agent identity:', error);
138
- return Option.none<AgentIdentity>();
139
- })
140
- )
172
+ Effect.flatMap(Schema.decodeUnknown(Schema.parseJson(AgentIdentity))),
173
+ Effect.map(normalizeDecodedAgentIdentity),
174
+ Effect.tapError(error => Effect.logDebug('Failed to read agent identity:', error)),
175
+ Effect.option
176
);
177
});
178
180
Effect.gen(function* () {
181
const fs = yield* FileSystem.FileSystem;
182
const configPath = yield* agentConfigPath;
148
- const normalized = normalizeAgentIdentity(identity);
183
+ const normalized = normalizeDecodedAgentIdentity(identity);
184
yield* fs.writeFileString(configPath, `${JSON.stringify(normalized, null, 2)}\n`);
185
return normalized;
186
});
188
export const removeStoredAgentIdentity = Effect.gen(function* () {
189
const fs = yield* FileSystem.FileSystem;
190
const configPath = yield* agentConfigPath;
156
- yield* fs.remove(configPath).pipe(Effect.catchAll(() => Effect.void));
191
+ yield* fs.remove(configPath).pipe(Effect.ignore);
192
});
193
194
const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>
160
- Effect.tryPromise({
161
- try: async () => {
162
- const response = await fetch(`${agentsBaseURL()}${pathname}`, {
163
- redirect: 'error',
164
- ...init,
165
- headers: {
166
- Accept: 'application/json',
167
- ...(init.body ? { 'Content-Type': 'application/json' } : {}),
168
- ...(init.headers ?? {}),
169
- },
195
+ Effect.gen(function* () {
196
+ const response = yield* Effect.tryPromise({
197
+ try: () =>
198
+ fetch(`${agentsBaseURL()}${pathname}`, {
199
+ redirect: 'error',
200
+ ...init,
201
+ headers: {
202
+ Accept: 'application/json',
203
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
204
+ ...(init.headers ?? {}),
205
+ },
206
+ }),
207
+ catch: cause =>
208
+ new AgentRequestError({
209
+ message: `agents.composio.dev request failed for ${pathname}`,
210
+ pathname,
211
+ cause,
212
+ }),
213
+ });
214
+
215
+ const text = yield* Effect.tryPromise({
216
+ try: () => response.text(),
217
+ catch: cause =>
218
+ new AgentRequestError({
219
+ message: `Failed to read agents.composio.dev response for ${pathname}`,
220
+ pathname,
221
+ status: response.status,
222
+ cause,
223
+ }),
224
+ });
225
+ const payload = text
226
+ ? yield* Schema.decodeUnknown(Schema.parseJson(Schema.Unknown))(text).pipe(
227
+ Effect.mapError(
228
+ cause =>
229
+ new AgentResponseDecodeError({
230
+ message: `agents.composio.dev returned invalid JSON for ${pathname}`,
231
+ pathname,
232
+ cause,
233
+ })
234
+ )
235
+ )
236
+ : {};
237
+
238
+ if (!response.ok) {
239
+ const message =
240
+ Predicate.isRecord(payload) && typeof payload.message === 'string'
241
+ ? payload.message
242
+ : `agents.composio.dev request failed with HTTP ${response.status}`;
243
+ return yield* new AgentRequestError({
244
+ message,
245
+ pathname,
246
+ status: response.status,
247
});
248
+ }
249
172
- const text = await response.text();
173
- const payload = text ? (JSON.parse(text) as unknown) : {};
174
- if (!response.ok) {
175
- const message =
176
- typeof asRecord(payload).message === 'string'
177
- ? (asRecord(payload).message as string)
178
- : `agents.composio.dev request failed with HTTP ${response.status}`;
179
- throw new Error(message);
180
- }
181
- return payload;
182
- },
183
- catch: error => (error instanceof Error ? error : new Error(String(error))),
250
+ return payload;
251
});
252
253
export const signupAgent = (params: { wait?: boolean } = {}) =>
257
method: 'POST',
258
body: JSON.stringify({}),
259
});
193
- return yield* writeStoredAgentIdentity(normalizeAgentIdentity(payload));
260
+ const identity = yield* decodeAgentResponse('/api/signup', AgentIdentity)(payload);
261
+ return yield* writeStoredAgentIdentity(identity);
262
});
263
264
export const fetchAgentWhoami = (agentKey: string) =>
267
method: 'GET',
268
headers: { Authorization: `Bearer ${agentKey}` },
269
});
202
- return normalizeAgentIdentity(payload, agentKey);
270
+ const identity = yield* decodeAgentResponse('/api/whoami', AgentIdentity)(payload);
271
+ return normalizeDecodedAgentIdentity(identity, agentKey);
272
});
273
274
export const fetchAgentInbox = (params: { agentKey: string; limit?: number }) =>
206
- fetchAgentJson(`/api/mail?limit=${encodeURIComponent(String(params.limit ?? 50))}`, {
207
- method: 'GET',
208
- headers: { Authorization: `Bearer ${params.agentKey}` },
209
- }).pipe(Effect.map(payload => payload as AgentMailResponse));
275
+ Effect.gen(function* () {
276
+ const pathname = `/api/mail?limit=${encodeURIComponent(String(params.limit ?? 50))}`;
277
+ const payload = yield* fetchAgentJson(pathname, {
278
+ method: 'GET',
279
+ headers: { Authorization: `Bearer ${params.agentKey}` },
280
+ });
281
+ return yield* decodeAgentResponse(pathname, AgentMailResponse)(payload);
282
+ });
283
284
export const claimAgent = (params: { agentKey: string; email: string }) =>
212
- fetchAgentJson('/api/claim', {
213
- method: 'POST',
214
- headers: { Authorization: `Bearer ${params.agentKey}` },
215
- body: JSON.stringify({ email: params.email }),
216
- }).pipe(Effect.map(payload => payload as AgentClaimResponse));
285
+ Effect.gen(function* () {
286
+ const pathname = '/api/claim';
287
+ const payload = yield* fetchAgentJson(pathname, {
288
+ method: 'POST',
289
+ headers: { Authorization: `Bearer ${params.agentKey}` },
290
+ body: JSON.stringify({ email: params.email }),
291
+ });
292
+ return yield* decodeAgentResponse(pathname, AgentClaimResponse)(payload);
293
+ });
294
295
const humanLoginError = () =>
296
new AgentAuthError({
309
const stored = yield* readStoredAgentIdentity;
310
if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, apiKey.value)) return;
311
235
- return yield* Effect.fail(humanLoginError());
312
+ return yield* humanLoginError();
313
});
314
315
export const getCurrentLoggedInAgent = Effect.gen(function* () {
332
333
if (Option.isSome(currentApiKey)) {
334
if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, currentApiKey.value)) {
258
- return getAgentKey(stored.value) as string;
335
+ const agentKey = getAgentKey(stored.value);
336
+ if (agentKey) return agentKey;
337
}
338
261
- return yield* Effect.fail(humanLoginError());
339
+ return yield* humanLoginError();
340
}
341
342
if (Option.isNone(stored)) {
265
- return yield* Effect.fail(
266
- new AgentAuthError({
267
- message: 'No Composio agent identity is saved on this machine.',
268
- nextSteps: [
269
- 'To create a new agent: run `composio signup` or `composio agent signup`.',
270
- 'To restore an existing agent: run `composio agent login <composio_agent_key>`.',
271
- ],
272
- })
273
- );
343
+ return yield* new AgentAuthError({
344
+ message: 'No Composio agent identity is saved on this machine.',
345
+ nextSteps: [
346
+ 'To create a new agent: run `composio signup` or `composio agent signup`.',
347
+ 'To restore an existing agent: run `composio agent login <composio_agent_key>`.',
348
+ ],
349
+ });
350
}
351
352
const agentKey = getAgentKey(stored.value);
353
if (!agentKey) {
278
- return yield* Effect.fail(
279
- new AgentAuthError({
280
- message: 'The saved Composio agent identity is missing its composio_agent_key.',
281
- nextSteps: [
282
- 'If you saved the key, run `composio agent login <composio_agent_key>`.',
283
- 'Otherwise create a new agent with `composio signup`.',
284
- ],
285
- })
286
- );
354
+ return yield* new AgentAuthError({
355
+ message: 'The saved Composio agent identity is missing its composio_agent_key.',
356
+ nextSteps: [
357
+ 'If you saved the key, run `composio agent login <composio_agent_key>`.',
358
+ 'Otherwise create a new agent with `composio signup`.',
359
+ ],
360
+ });
361
}
362
363
return agentKey;
389
const orgId = identity.composio?.org_id;
390
391
if (!userApiKey || !orgId) {
318
- return yield* Effect.fail(
319
- new Error(
320
- 'Agent identity is not ready yet. Run `composio agent whoami` and try again once status is READY.'
321
- )
322
- );
392
+ return yield* new AgentAuthError({
393
+ message: 'Agent identity is not ready yet.',
394
+ nextSteps: ['Run `composio agent whoami` and try again once status is READY.'],
395
+ });
396
}
397
398
yield* ctx.login(userApiKey, orgId);