1
+import { FileSystem } from '@effect/platform';
2
+import { Data, Effect, Option } 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';
6
+import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
7
+
8
+export const AGENT_CONFIG_FILE_NAME = 'agent.json';
9
+export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';
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
+}
58
+
59
+export class AgentAuthError extends Data.TaggedError('services/AgentAuthError')<{
60
+ readonly message: string;
61
+ readonly nextSteps: ReadonlyArray<string>;
62
+}> {}
63
+
64
+const agentsBaseURL = (): string =>
65
+ (process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, '');
66
+
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;
73
+
74
+export const normalizeAgentStatus = (status: string | undefined): AgentStatus => {
75
+ const normalized = status?.trim().toUpperCase();
76
+ if (normalized === 'READY') return 'READY';
77
+ if (normalized === 'PENDING') return 'PENDING';
78
+ return 'UNKNOWN';
79
+};
80
+
81
+export const getAgentKey = (identity: AgentIdentity): string | undefined => {
82
+ if (typeof identity.composio_agent_key === 'string') return identity.composio_agent_key;
83
+ if (typeof identity.agent_key === 'string') return identity.agent_key;
84
+ return undefined;
85
+};
86
+
87
+export const isAgentIdentityForApiKey = (identity: AgentIdentity, apiKey: string): boolean =>
88
+ Boolean(getAgentKey(identity) && identity.composio?.user_api_key === apiKey);
89
+
90
+export const normalizeAgentIdentity = (
91
+ payload: unknown,
92
+ 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
+ }
105
+
106
+ return normalized as AgentIdentity;
107
+};
108
+
109
+export const safeAgentSummary = (identity: AgentIdentity) => ({
110
+ account_type: 'agent' as const,
111
+ status: normalizeAgentStatus(identity.status),
112
+ slug: identity.slug ?? null,
113
+ email: identity.email ?? null,
114
+ org_id: identity.composio?.org_id ?? null,
115
+ project_id: identity.composio?.project_id ?? null,
116
+ member_id: identity.composio?.member_id ?? null,
117
+ claimed_by: identity.claimed_by ?? null,
118
+ claimed_at: identity.claimed_at ?? null,
119
+});
120
+
121
+export const agentConfigPath = Effect.gen(function* () {
122
+ const cacheDir = yield* setupCacheDir;
123
+ return path.join(cacheDir, AGENT_CONFIG_FILE_NAME);
124
+});
125
+
126
+export const readStoredAgentIdentity = Effect.gen(function* () {
127
+ const fs = yield* FileSystem.FileSystem;
128
+ const configPath = yield* agentConfigPath;
129
+
130
+ const exists = yield* fs.exists(configPath);
131
+ if (!exists) return Option.none<AgentIdentity>();
132
+
133
+ 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
+ )
141
+ );
142
+});
143
+
144
+export const writeStoredAgentIdentity = (identity: AgentIdentity) =>
145
+ Effect.gen(function* () {
146
+ const fs = yield* FileSystem.FileSystem;
147
+ const configPath = yield* agentConfigPath;
148
+ const normalized = normalizeAgentIdentity(identity);
149
+ yield* fs.writeFileString(configPath, `${JSON.stringify(normalized, null, 2)}\n`);
150
+ return normalized;
151
+ });
152
+
153
+export const removeStoredAgentIdentity = Effect.gen(function* () {
154
+ const fs = yield* FileSystem.FileSystem;
155
+ const configPath = yield* agentConfigPath;
156
+ yield* fs.remove(configPath).pipe(Effect.catchAll(() => Effect.void));
157
+});
158
+
159
+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
+ },
170
+ });
171
+
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))),
184
+ });
185
+
186
+export const signupAgent = (params: { wait?: boolean } = {}) =>
187
+ Effect.gen(function* () {
188
+ const wait = params.wait ?? true;
189
+ const payload = yield* fetchAgentJson(`/api/signup${wait ? '' : '?wait=0'}`, {
190
+ method: 'POST',
191
+ body: JSON.stringify({}),
192
+ });
193
+ return yield* writeStoredAgentIdentity(normalizeAgentIdentity(payload));
194
+ });
195
+
196
+export const fetchAgentWhoami = (agentKey: string) =>
197
+ Effect.gen(function* () {
198
+ const payload = yield* fetchAgentJson('/api/whoami', {
199
+ method: 'GET',
200
+ headers: { Authorization: `Bearer ${agentKey}` },
201
+ });
202
+ return normalizeAgentIdentity(payload, agentKey);
203
+ });
204
+
205
+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));
210
+
211
+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));
217
+
218
+const humanLoginError = () =>
219
+ new AgentAuthError({
220
+ message: 'This CLI is currently signed in to Composio as a regular user, not an agent.',
221
+ nextSteps: [
222
+ 'To switch to an existing agent: run `composio logout`, then `composio agent login <composio_agent_key>`.',
223
+ 'To create a new agent: run `composio logout`, then `composio signup`.',
224
+ ],
225
+ });
226
+
227
+export const ensureAgentSignupAllowed = Effect.gen(function* () {
228
+ const ctx = yield* ComposioUserContext;
229
+ const apiKey = ctx.data.apiKey;
230
+ if (Option.isNone(apiKey)) return;
231
+
232
+ const stored = yield* readStoredAgentIdentity;
233
+ if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, apiKey.value)) return;
234
+
235
+ return yield* Effect.fail(humanLoginError());
236
+});
237
+
238
+export const getCurrentLoggedInAgent = Effect.gen(function* () {
239
+ const ctx = yield* ComposioUserContext;
240
+ const currentApiKey = ctx.data.apiKey;
241
+ if (Option.isNone(currentApiKey)) return Option.none<AgentIdentity>();
242
+
243
+ const stored = yield* readStoredAgentIdentity;
244
+ if (Option.isNone(stored)) return Option.none<AgentIdentity>();
245
+
246
+ return isAgentIdentityForApiKey(stored.value, currentApiKey.value)
247
+ ? stored
248
+ : Option.none<AgentIdentity>();
249
+});
250
+
251
+export const resolveStoredAgentKey = Effect.gen(function* () {
252
+ const ctx = yield* ComposioUserContext;
253
+ const stored = yield* readStoredAgentIdentity;
254
+ const currentApiKey = ctx.data.apiKey;
255
+
256
+ if (Option.isSome(currentApiKey)) {
257
+ if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, currentApiKey.value)) {
258
+ return getAgentKey(stored.value) as string;
259
+ }
260
+
261
+ return yield* Effect.fail(humanLoginError());
262
+ }
263
+
264
+ 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
+ );
274
+ }
275
+
276
+ const agentKey = getAgentKey(stored.value);
277
+ 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
+ );
287
+ }
288
+
289
+ return agentKey;
290
+});
291
+
292
+export const getOrSignupReadyAgent = (params: { force?: boolean } = {}) =>
293
+ Effect.gen(function* () {
294
+ if (!params.force) {
295
+ const stored = yield* readStoredAgentIdentity;
296
+ if (Option.isSome(stored)) {
297
+ const agentKey = getAgentKey(stored.value);
298
+ if (agentKey) {
299
+ const remote = yield* fetchAgentWhoami(agentKey).pipe(Effect.option);
300
+ if (Option.isSome(remote)) {
301
+ const saved = yield* writeStoredAgentIdentity(remote.value);
302
+ if (normalizeAgentStatus(saved.status) === 'READY') return saved;
303
+ }
304
+ }
305
+ }
306
+ }
307
+
308
+ return yield* signupAgent({ wait: true });
309
+ });
310
+
311
+export const loginWithAgentIdentity = (identity: AgentIdentity) =>
312
+ Effect.gen(function* () {
313
+ const ctx = yield* ComposioUserContext;
314
+ const userApiKey = identity.composio?.user_api_key;
315
+ const orgId = identity.composio?.org_id;
316
+
317
+ 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
+ );
323
+ }
324
+
325
+ yield* ctx.login(userApiKey, orgId);
326
+ yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId });
327
+ });