@devries-cameron20 / composio Mirror · read-only / commits / 4752290a0
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 08:30 UTC

refactor(cli): move the `agent` commands into the directory shape (#4969)

This PR: - moves `agent signup`, `login`, `whoami`, `claim` and `inbox` into `agent/<name>/agent.<name>.{cmd,handler}.ts`, with `format.ts` for `whoami` and `claim` - moves the signup flow shared by `composio signup` and `composio agent signup` into `src/effects/agent-signup.ts` - adds `AgentHandlerTest` (`test/__utils__/layers/agents.ts`) and handler tests for all five commands, plus mirrored `.cmd.test.ts` suites - removes the four `agent` entries from `COMMAND_TEST_EXEMPTIONS` (15 → 11) - part of U9 of the CLI command-layout series; no user-visible change, so no CHANGELOG entry ## Context Verified: `pnpm typecheck`, `pnpm --filter @composio/cli test` (1925 passed; the known-flaky `analytics.dispatch` install_id test passes on rerun), `validate:command-tests`, `lint:effect`, oxlint, prettier. Binaries from `origin/next` and this branch give identical help, stdout, stderr and exit codes over 26 invocations (piped and TTY, agents API mocked).

Alberto Schiabel committed Oct 20, 2026 at 15:28 UTC 4752290a0ec83329beab6aab876e412092785f93
35 files changed +1429 -323
ts/packages/cli/scripts/command-tests.ts
-4
@@ -18,10 +18,6 @@ const TEST_SUFFIX = '.cmd.test.ts';
18 // Command paths are relative to src/commands/; tests are relative to
19 // test/src/commands/. Both use forward slashes.
20 export const COMMAND_TEST_EXEMPTIONS: readonly CommandTestExemption[] = [
21 - { command: 'agent/commands/agent.claim.cmd.ts', reason: 'no test yet' },
22 - { command: 'agent/commands/agent.inbox.cmd.ts', reason: 'no test yet' },
23 - { command: 'agent/commands/agent.signup.cmd.ts', reason: 'no test yet' },
24 - { command: 'agent/commands/agent.whoami.cmd.ts', reason: 'no test yet' },
21 { command: 'artifacts.cmd.ts', reason: 'no test yet' },
22 { command: 'connections/commands/connections.remove.cmd.ts', reason: 'no test yet' },
23 { command: 'debug.cmd.ts', reason: 'no test yet' },
ts/packages/cli/src/commands/agent/agent.cmd.ts
+5 -5
@@ -1,9 +1,9 @@
1 import { Command } from 'effect/cli';
2 -import { agentCmd$Claim } from './commands/agent.claim.cmd';
3 -import { agentCmd$Inbox } from './commands/agent.inbox.cmd';
4 -import { agentCmd$Login } from './commands/agent.login.cmd';
5 -import { agentCmd$Signup } from './commands/agent.signup.cmd';
6 -import { agentCmd$Whoami } from './commands/agent.whoami.cmd';
2 +import { agentCmd$Claim } from './claim/agent.claim.cmd';
3 +import { agentCmd$Inbox } from './inbox/agent.inbox.cmd';
4 +import { agentCmd$Login } from './login/agent.login.cmd';
5 +import { agentCmd$Signup } from './signup/agent.signup.cmd';
6 +import { agentCmd$Whoami } from './whoami/agent.whoami.cmd';
7
8 export const agentCmd = Command.make('agent').pipe(
9 Command.withDescription('Manage Composio agent identity, inbox, and handoff.'),
ts/packages/cli/src/commands/agent/claim/agent.claim.cmd.ts new
+10
@@ -0,0 +1,10 @@
1 +import { Argument, Command } from 'effect/cli';
2 +import { runAgentClaim } from './agent.claim.handler';
3 +
4 +const email = Argument.String('email').pipe(
5 + Argument.withDescription('Human email address to invite as an admin for this agent org')
6 +);
7 +
8 +export const agentCmd$Claim = Command.make('claim', { email }, runAgentClaim).pipe(
9 + Command.withDescription('Invite a human admin to claim this agent org.')
10 +);
ts/packages/cli/src/commands/agent/claim/agent.claim.format.ts new
+17
@@ -0,0 +1,17 @@
1 +import type { AgentClaimResponse } from 'src/services/agents';
2 +
3 +/** The success line `composio agent claim` prints on stderr. */
4 +export const claimInviteSentMessage = (email: string) =>
5 + `Sent Composio org claim invite to ${email}.`;
6 +
7 +/**
8 + * The stdout payload of `composio agent claim`: the invite the agents API created, with the
9 + * requested `email` and an `invited` status when the response leaves them out.
10 + */
11 +export const formatAgentClaimJson = (result: AgentClaimResponse, requestedEmail: string) =>
12 + JSON.stringify({
13 + status: result.status ?? 'invited',
14 + email: result.email ?? requestedEmail,
15 + org_id: result.org_id ?? null,
16 + invite_code: result.invite_code ?? null,
17 + });
ts/packages/cli/src/commands/agent/claim/agent.claim.handler.ts new
+26
@@ -0,0 +1,26 @@
1 +import { Effect } from 'effect';
2 +import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
3 +import { claimAgent, resolveStoredAgentKey } from 'src/services/agents';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +import { claimInviteSentMessage, formatAgentClaimJson } from './agent.claim.format';
6 +
7 +/** The argument of `composio agent claim`. */
8 +export type AgentClaimParams = {
9 + readonly email: string;
10 +};
11 +
12 +/**
13 + * Invites `email` as an admin of the stored agent's org. A missing or human login is reported
14 + * by `handleAgentAuthError` and exits 1.
15 + */
16 +export const runAgentClaim = ({ email }: AgentClaimParams) =>
17 + handleAgentAuthError(
18 + Effect.gen(function* () {
19 + const ui = yield* TerminalUI;
20 + const agentKey = yield* resolveStoredAgentKey;
21 + const result = yield* claimAgent({ agentKey, email });
22 +
23 + yield* ui.log.success(claimInviteSentMessage(result.email ?? email));
24 + yield* ui.output(formatAgentClaimJson(result, email));
25 + })
26 + );
ts/packages/cli/src/commands/agent/commands/agent.claim.cmd.ts deleted
-32
@@ -1,32 +0,0 @@
1 -import { Effect } from 'effect';
2 -import { Argument, Command } from 'effect/cli';
3 -import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 -import { claimAgent, resolveStoredAgentKey } from 'src/services/agents';
5 -import { TerminalUI } from 'src/services/terminal-ui';
6 -
7 -const email = Argument.String('email').pipe(
8 - Argument.withDescription('Human email address to invite as an admin for this agent org')
9 -);
10 -
11 -export const agentCmd$Claim = Command.make('claim', { email }).pipe(
12 - Command.withDescription('Invite a human admin to claim this agent org.'),
13 - Command.withHandler(({ email }) =>
14 - handleAgentAuthError(
15 - Effect.gen(function* () {
16 - const ui = yield* TerminalUI;
17 - const agentKey = yield* resolveStoredAgentKey;
18 - const result = yield* claimAgent({ agentKey, email });
19 -
20 - yield* ui.log.success(`Sent Composio org claim invite to ${result.email ?? email}.`);
21 - yield* ui.output(
22 - JSON.stringify({
23 - status: result.status ?? 'invited',
24 - email: result.email ?? email,
25 - org_id: result.org_id ?? null,
26 - invite_code: result.invite_code ?? null,
27 - })
28 - );
29 - })
30 - )
31 - )
32 -);
ts/packages/cli/src/commands/agent/commands/agent.inbox.cmd.ts deleted
-25
@@ -1,25 +0,0 @@
1 -import { Effect } from 'effect';
2 -import { Command, Flag } from 'effect/cli';
3 -import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 -import { fetchAgentInbox, resolveStoredAgentKey } from 'src/services/agents';
5 -import { TerminalUI } from 'src/services/terminal-ui';
6 -
7 -const limit = Flag.Int('limit').pipe(
8 - Flag.withDefault(50),
9 - Flag.withDescription('Maximum number of inbox messages to fetch')
10 -);
11 -
12 -export const agentCmd$Inbox = Command.make('inbox', { limit }).pipe(
13 - Command.withDescription('Read the stored Composio agent inbox.'),
14 - Command.withHandler(({ limit }) =>
15 - handleAgentAuthError(
16 - Effect.gen(function* () {
17 - const ui = yield* TerminalUI;
18 - const agentKey = yield* resolveStoredAgentKey;
19 - const inbox = yield* fetchAgentInbox({ agentKey, limit });
20 -
21 - yield* ui.output(JSON.stringify(inbox), { force: true });
22 - })
23 - )
24 - )
25 -);
ts/packages/cli/src/commands/agent/commands/agent.login.cmd.ts deleted
-27
@@ -1,27 +0,0 @@
1 -import { Effect } from 'effect';
2 -import { Argument, Command } from 'effect/cli';
3 -import { completeAgentLogin } from 'src/effects/complete-agent-login';
4 -import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
5 -import {
6 - ensureAgentSignupAllowed,
7 - fetchAgentWhoami,
8 - writeStoredAgentIdentity,
9 -} from 'src/services/agents';
10 -
11 -const composioAgentKey = Argument.String('composio_agent_key').pipe(
12 - Argument.withDescription('Composio agent key for an existing agent identity')
13 -);
14 -
15 -export const agentCmd$Login = Command.make('login', { composioAgentKey }).pipe(
16 - Command.withDescription('Log in with an existing Composio agent key.'),
17 - Command.withHandler(({ composioAgentKey }) =>
18 - handleAgentAuthError(
19 - Effect.gen(function* () {
20 - yield* ensureAgentSignupAllowed;
21 - const identity = yield* fetchAgentWhoami(composioAgentKey);
22 - const saved = yield* writeStoredAgentIdentity(identity);
23 - yield* completeAgentLogin(saved);
24 - })
25 - )
26 - )
27 -);
ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts deleted
-39
@@ -1,39 +0,0 @@
1 -import { Effect } from 'effect';
2 -import { Command } from 'effect/cli';
3 -import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 -import {
5 - fetchAgentWhoami,
6 - resolveStoredAgentKey,
7 - safeAgentSummary,
8 - writeStoredAgentIdentity,
9 -} from 'src/services/agents';
10 -import { TerminalUI } from 'src/services/terminal-ui';
11 -
12 -export const agentCmd$Whoami = Command.make('whoami', {}).pipe(
13 - Command.withDescription('Show the stored Composio agent identity.'),
14 - Command.withHandler(() =>
15 - handleAgentAuthError(
16 - Effect.gen(function* () {
17 - const ui = yield* TerminalUI;
18 - const agentKey = yield* resolveStoredAgentKey;
19 - const identity = yield* fetchAgentWhoami(agentKey);
20 - const saved = yield* writeStoredAgentIdentity(identity);
21 - const summary = safeAgentSummary(saved);
22 -
23 - yield* ui.note(
24 - [
25 - `Type: agent`,
26 - `Status: ${summary.status}`,
27 - `Email: ${summary.email ?? 'unknown'}`,
28 - `Slug: ${summary.slug ?? 'unknown'}`,
29 - `Current Org ID: ${summary.org_id ?? 'pending'}`,
30 - `Project ID: ${summary.project_id ?? 'pending'}`,
31 - `Claimed By: ${summary.claimed_by ?? 'not claimed'}`,
32 - ].join('\n'),
33 - 'Composio Agent'
34 - );
35 - yield* ui.output(JSON.stringify(summary));
36 - })
37 - )
38 - )
39 -);
ts/packages/cli/src/commands/agent/inbox/agent.inbox.cmd.ts new
+11
@@ -0,0 +1,11 @@
1 +import { Command, Flag } from 'effect/cli';
2 +import { runAgentInbox } from './agent.inbox.handler';
3 +
4 +const limit = Flag.Int('limit').pipe(
5 + Flag.withDefault(50),
6 + Flag.withDescription('Maximum number of inbox messages to fetch')
7 +);
8 +
9 +export const agentCmd$Inbox = Command.make('inbox', { limit }, runAgentInbox).pipe(
10 + Command.withDescription('Read the stored Composio agent inbox.')
11 +);
ts/packages/cli/src/commands/agent/inbox/agent.inbox.handler.ts new
+25
@@ -0,0 +1,25 @@
1 +import { Effect } from 'effect';
2 +import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
3 +import { fetchAgentInbox, resolveStoredAgentKey } from 'src/services/agents';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +
6 +/** The flags of `composio agent inbox`. */
7 +export type AgentInboxParams = {
8 + readonly limit: number;
9 +};
10 +
11 +/**
12 + * Prints the stored agent's inbox as the agents API returns it, on stdout even when stdout is a
13 + * terminal: the JSON is the whole output. A missing or human login is reported by
14 + * `handleAgentAuthError` and exits 1.
15 + */
16 +export const runAgentInbox = ({ limit }: AgentInboxParams) =>
17 + handleAgentAuthError(
18 + Effect.gen(function* () {
19 + const ui = yield* TerminalUI;
20 + const agentKey = yield* resolveStoredAgentKey;
21 + const inbox = yield* fetchAgentInbox({ agentKey, limit });
22 +
23 + yield* ui.output(JSON.stringify(inbox), { force: true });
24 + })
25 + );
ts/packages/cli/src/commands/agent/login/agent.login.cmd.ts new
+10
@@ -0,0 +1,10 @@
1 +import { Argument, Command } from 'effect/cli';
2 +import { runAgentLogin } from './agent.login.handler';
3 +
4 +const composioAgentKey = Argument.String('composio_agent_key').pipe(
5 + Argument.withDescription('Composio agent key for an existing agent identity')
6 +);
7 +
8 +export const agentCmd$Login = Command.make('login', { composioAgentKey }, runAgentLogin).pipe(
9 + Command.withDescription('Log in with an existing Composio agent key.')
10 +);
ts/packages/cli/src/commands/agent/login/agent.login.handler.ts new
+28
@@ -0,0 +1,28 @@
1 +import { Effect } from 'effect';
2 +import { completeAgentLogin } from 'src/effects/complete-agent-login';
3 +import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 +import {
5 + ensureAgentSignupAllowed,
6 + fetchAgentWhoami,
7 + writeStoredAgentIdentity,
8 +} from 'src/services/agents';
9 +
10 +/** The argument of `composio agent login`. */
11 +export type AgentLoginParams = {
12 + readonly composioAgentKey: string;
13 +};
14 +
15 +/**
16 + * Looks the key up with the agents API, stores the identity, and logs the CLI in with it. A
17 + * human login, or an identity without credentials yet, is reported by `handleAgentAuthError`
18 + * and exits 1.
19 + */
20 +export const runAgentLogin = ({ composioAgentKey }: AgentLoginParams) =>
21 + handleAgentAuthError(
22 + Effect.gen(function* () {
23 + yield* ensureAgentSignupAllowed;
24 + const identity = yield* fetchAgentWhoami(composioAgentKey);
25 + const saved = yield* writeStoredAgentIdentity(identity);
26 + yield* completeAgentLogin(saved);
27 + })
28 + );
ts/packages/cli/src/commands/agent/signup/agent.signup.cmd.ts renamed
+2 -3
@@ -1,5 +1,5 @@
1 import { Command, Flag } from 'effect/cli';
2 -import { runAgentSignup } from '../../signup.cmd';
2 +import { runAgentSignup } from './agent.signup.handler';
3
4 const noWait = Flag.Boolean('no-wait').pipe(
5 Flag.withDefault(false),
@@ -20,6 +20,5 @@ const force = Flag.Boolean('force').pipe(
20 export const agentCmd$Signup = Command.make(
21 'signup',
22 { noWait, noLogin, force },
23 - ({ noWait, noLogin, force }) =>
24 - runAgentSignup({ noWait, noLogin, force, commandLabel: 'composio agent signup' })
23 + runAgentSignup
24 ).pipe(Command.withDescription('Sign up and optionally log in as a Composio agent.'));
ts/packages/cli/src/commands/agent/signup/agent.signup.handler.ts new
+12
@@ -0,0 +1,12 @@
1 +import { runAgentSignupFlow } from 'src/effects/agent-signup';
2 +
3 +/** The flags of `composio agent signup`. */
4 +export type AgentSignupParams = {
5 + readonly noWait: boolean;
6 + readonly noLogin: boolean;
7 + readonly force: boolean;
8 +};
9 +
10 +/** Runs the agent signup flow `composio signup` shares, under this command's name. */
11 +export const runAgentSignup = (params: AgentSignupParams) =>
12 + runAgentSignupFlow({ ...params, commandLabel: 'composio agent signup' });
ts/packages/cli/src/commands/agent/whoami/agent.whoami.cmd.ts new
+6
@@ -0,0 +1,6 @@
1 +import { Command } from 'effect/cli';
2 +import { runAgentWhoami } from './agent.whoami.handler';
3 +
4 +export const agentCmd$Whoami = Command.make('whoami', {}, runAgentWhoami).pipe(
5 + Command.withDescription('Show the stored Composio agent identity.')
6 +);
ts/packages/cli/src/commands/agent/whoami/agent.whoami.format.ts new
+12
@@ -0,0 +1,12 @@
1 +import {
2 + AGENT_SUMMARY_NOTE_TITLE,
3 + agentSummaryLines,
4 + type SafeAgentSummary,
5 +} from 'src/services/agents';
6 +
7 +/** The note body `composio agent whoami` prints on stderr. */
8 +export const formatAgentWhoamiNote = (summary: SafeAgentSummary) =>
9 + [...agentSummaryLines(summary), `Claimed By: ${summary.claimed_by ?? 'not claimed'}`].join('\n');
10 +
11 +/** The stdout payload of `composio agent whoami`: the identity summary, without any key. */
12 +export const formatAgentWhoamiJson = (summary: SafeAgentSummary) => JSON.stringify(summary);
ts/packages/cli/src/commands/agent/whoami/agent.whoami.handler.ts new
+29
@@ -0,0 +1,29 @@
1 +import { Effect } from 'effect';
2 +import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
3 +import {
4 + AGENT_SUMMARY_NOTE_TITLE,
5 + fetchAgentWhoami,
6 + resolveStoredAgentKey,
7 + safeAgentSummary,
8 + writeStoredAgentIdentity,
9 +} from 'src/services/agents';
10 +import { TerminalUI } from 'src/services/terminal-ui';
11 +import { formatAgentWhoamiJson, formatAgentWhoamiNote } from './agent.whoami.format';
12 +
13 +/**
14 + * Refreshes the stored agent identity from the agents API, saves it, and prints its summary.
15 + * A missing or human login is reported by `handleAgentAuthError` and exits 1.
16 + */
17 +export const runAgentWhoami = () =>
18 + handleAgentAuthError(
19 + Effect.gen(function* () {
20 + const ui = yield* TerminalUI;
21 + const agentKey = yield* resolveStoredAgentKey;
22 + const identity = yield* fetchAgentWhoami(agentKey);
23 + const saved = yield* writeStoredAgentIdentity(identity);
24 + const summary = safeAgentSummary(saved);
25 +
26 + yield* ui.note(formatAgentWhoamiNote(summary), AGENT_SUMMARY_NOTE_TITLE);
27 + yield* ui.output(formatAgentWhoamiJson(summary));
28 + })
29 + );
ts/packages/cli/src/commands/signup.cmd.ts
+2 -60
@@ -1,14 +1,5 @@
1 import { Command, Flag } from 'effect/cli';
2 -import { Effect } from 'effect';
3 -import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 -import {
5 - ensureAgentSignupAllowed,
6 - getOrSignupReadyAgent,
7 - loginWithAgentIdentity,
8 - safeAgentSummary,
9 - signupAgent,
10 -} from 'src/services/agents';
11 -import { TerminalUI } from 'src/services/terminal-ui';
2 +import { runAgentSignupFlow } from 'src/effects/agent-signup';
3
4 const noWait = Flag.Boolean('no-wait').pipe(
5 Flag.withDefault(false),
@@ -26,57 +17,8 @@ const force = Flag.Boolean('force').pipe(
17 Flag.withDescription('Create a new agent identity even if ~/.composio/agent.json already exists')
18 );
19
29 -export const runAgentSignup = (params: {
30 - noWait: boolean;
31 - noLogin: boolean;
32 - force: boolean;
33 - commandLabel?: string;
34 -}) =>
35 - handleAgentAuthError(
36 - Effect.gen(function* () {
37 - const ui = yield* TerminalUI;
38 - const commandLabel = params.commandLabel ?? 'composio signup';
39 -
40 - yield* ensureAgentSignupAllowed;
41 - yield* ui.intro(commandLabel);
42 - yield* ui.log.info(
43 - `${commandLabel} signs you up as a Composio agent. This flow is fully non-interactive and does not open a browser.`
44 - );
45 -
46 - const identity = yield* params.noWait
47 - ? signupAgent({ wait: false })
48 - : getOrSignupReadyAgent({ force: params.force });
49 - const summary = safeAgentSummary(identity);
50 -
51 - yield* ui.note(
52 - [
53 - `Type: agent`,
54 - `Status: ${summary.status}`,
55 - `Email: ${summary.email ?? 'unknown'}`,
56 - `Slug: ${summary.slug ?? 'unknown'}`,
57 - `Current Org ID: ${summary.org_id ?? 'pending'}`,
58 - `Project ID: ${summary.project_id ?? 'pending'}`,
59 - `Agent key: stored in ~/.composio/agent.json`,
60 - ].join('\n'),
61 - 'Composio Agent'
62 - );
63 -
64 - if (!params.noWait && !params.noLogin) {
65 - yield* loginWithAgentIdentity(identity);
66 - yield* ui.log.success('Logged in with the Composio agent identity.');
67 - } else if (params.noWait) {
68 - yield* ui.log.info('Signup is pending. Run `composio agent whoami` to poll status.');
69 - }
70 -
71 - yield* ui.output(
72 - JSON.stringify({ ...summary, logged_in: !params.noWait && !params.noLogin })
73 - );
74 - yield* ui.outro('Agent setup complete.');
75 - })
76 - );
77 -
20 export const signupCmd = Command.make(
21 'signup',
22 { noWait, noLogin, force },
81 - ({ noWait, noLogin, force }) => runAgentSignup({ noWait, noLogin, force })
23 + ({ noWait, noLogin, force }) => runAgentSignupFlow({ noWait, noLogin, force })
24 ).pipe(Command.withDescription('Sign up and optionally log in as a Composio agent.'));
ts/packages/cli/src/effects/agent-signup.ts new
+62
@@ -0,0 +1,62 @@
1 +import { Effect } from 'effect';
2 +import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
3 +import {
4 + AGENT_SUMMARY_NOTE_TITLE,
5 + agentSummaryLines,
6 + ensureAgentSignupAllowed,
7 + getOrSignupReadyAgent,
8 + loginWithAgentIdentity,
9 + safeAgentSummary,
10 + signupAgent,
11 +} from 'src/services/agents';
12 +import { TerminalUI } from 'src/services/terminal-ui';
13 +
14 +/** The flags `composio signup` and `composio agent signup` share. */
15 +export type AgentSignupFlowParams = {
16 + readonly noWait: boolean;
17 + readonly noLogin: boolean;
18 + readonly force: boolean;
19 + /** The command the intro and the info line name. */
20 + readonly commandLabel?: string;
21 +};
22 +
23 +/**
24 + * Signs up (or reuses) a Composio agent identity and, unless `noWait` or `noLogin`, logs the
25 + * CLI in with it. Shared by `composio signup` and `composio agent signup`, which differ only in
26 + * `commandLabel`.
27 + */
28 +export const runAgentSignupFlow = (params: AgentSignupFlowParams) =>
29 + handleAgentAuthError(
30 + Effect.gen(function* () {
31 + const ui = yield* TerminalUI;
32 + const commandLabel = params.commandLabel ?? 'composio signup';
33 +
34 + yield* ensureAgentSignupAllowed;
35 + yield* ui.intro(commandLabel);
36 + yield* ui.log.info(
37 + `${commandLabel} signs you up as a Composio agent. This flow is fully non-interactive and does not open a browser.`
38 + );
39 +
40 + const identity = yield* params.noWait
41 + ? signupAgent({ wait: false })
42 + : getOrSignupReadyAgent({ force: params.force });
43 + const summary = safeAgentSummary(identity);
44 +
45 + yield* ui.note(
46 + [...agentSummaryLines(summary), `Agent key: stored in ~/.composio/agent.json`].join('\n'),
47 + AGENT_SUMMARY_NOTE_TITLE
48 + );
49 +
50 + if (!params.noWait && !params.noLogin) {
51 + yield* loginWithAgentIdentity(identity);
52 + yield* ui.log.success('Logged in with the Composio agent identity.');
53 + } else if (params.noWait) {
54 + yield* ui.log.info('Signup is pending. Run `composio agent whoami` to poll status.');
55 + }
56 +
57 + yield* ui.output(
58 + JSON.stringify({ ...summary, logged_in: !params.noWait && !params.noLogin })
59 + );
60 + yield* ui.outro('Agent setup complete.');
61 + })
62 + );
ts/packages/cli/src/services/agents.ts
+17 -1
@@ -155,7 +155,7 @@ export const normalizeAgentIdentity = (
155 fallbackAgentKey
156 );
157
158 -type SafeAgentSummary = {
158 +export type SafeAgentSummary = {
159 readonly account_type: 'agent';
160 readonly status: AgentStatus;
161 readonly slug: string | null;
@@ -179,6 +179,22 @@ export const safeAgentSummary = (identity: AgentIdentity): SafeAgentSummary => (
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;
ts/packages/cli/test/__utils__/layers/agents.ts new
+130
@@ -0,0 +1,130 @@
1 +import type { ComposioClientShape } from '@composio/client/effect';
2 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 +import * as BunPath from '@effect/platform-bun/BunPath';
4 +import { ConfigProvider, Console, Effect, Layer, Option } from 'effect';
5 +import { HttpClient } from 'effect/http';
6 +import * as tempy from 'tempy';
7 +import { ComposioClientSingleton } from 'src/services/composio-clients';
8 +import { NodeOs } from 'src/services/node-os';
9 +import { NodeProcess } from 'src/services/node-process';
10 +import { ProjectContext } from 'src/services/project-context';
11 +import { TerminalUI } from 'src/services/terminal-ui';
12 +import { ComposioUserContext } from 'src/services/user-context';
13 +import { hostOnlyEnvConfigProvider } from '../live-env-config-provider';
14 +import { makeSessionInfo } from '../models/account';
15 +import * as MockConsole from '../services/mock-console';
16 +import { terminalUITestImpl } from '../services/terminal-ui-test';
17 +import type { MockRequestScope } from './accounts';
18 +import { ToolkitsTest } from './toolkits';
19 +import { makeShadowClient } from './shadow-client';
20 +
21 +/** What the CLI is logged in with when an agent handler test starts. */
22 +export interface AgentHandlerFixture {
23 + /** The stored user API key; omitted means logged out. */
24 + readonly apiKey?: string;
25 +}
26 +
27 +/** One `ui.output` call: the stdout payload and whether it bypassed the TTY check. */
28 +export interface AgentHandlerOutput {
29 + readonly data: string;
30 + readonly force: boolean;
31 +}
32 +
33 +const clientFor = (scope: MockRequestScope): ComposioClientShape =>
34 + // The shadows answer only the fields `loginWithAgentIdentity` reads; `test-layer.ts` shadows
35 + // its mock client the same way.
36 + makeShadowClient(
37 + {
38 + sessionInfo: makeSessionInfo({
39 + orgId: scope.orgId ?? 'org_agent',
40 + orgName: 'Agent Org',
41 + orgMemberId: 'mem_agent',
42 + userId: 'user_agent',
43 + email: 'agent@agent.composio.ai',
44 + }),
45 + },
46 + scope
47 + );
48 +
49 +/**
50 + * What an `agent` handler needs without argv or `TestLive`: a headless terminal whose stdout
51 + * payloads land in `outputs` (decoration goes to `MockConsole`), a user context that records
52 + * `login` calls, the real filesystem under a temporary home (where `~/.composio/agent.json`
53 + * lives), and the services the agent login step reaches (session info for the analytics
54 + * link, and the consumer-toolkits cache refresh it starts in the background). The agents API
55 + * itself is plain `fetch`; tests stub it with `vi.spyOn(globalThis, 'fetch')`.
56 + */
57 +export const AgentHandlerTest = (fixture: AgentHandlerFixture = {}) => {
58 + const outputs: Array<AgentHandlerOutput> = [];
59 + const logins: Array<{ readonly apiKey: string; readonly orgId?: string }> = [];
60 + const apiKey = Option.fromUndefinedOr(fixture.apiKey);
61 + const homedir = tempy.temporaryDirectory({ prefix: 'agent-handler' });
62 +
63 + const layer = Layer.mergeAll(
64 + Layer.effect(Console.Console, MockConsole.make),
65 + Layer.succeed(
66 + TerminalUI,
67 + TerminalUI.of({
68 + ...terminalUITestImpl,
69 + output: (data, options) =>
70 + Effect.sync(() => {
71 + outputs.push({ data, force: options?.force ?? false });
72 + }),
73 + })
74 + ),
75 + Layer.succeed(
76 + ComposioUserContext,
77 + ComposioUserContext.of({
78 + data: {
79 + apiKey,
80 + baseURL: 'https://mock.invalid',
81 + webURL: 'https://platform.mock.invalid/',
82 + orgId: Option.none(),
83 + projectId: Option.none(),
84 + testUserId: Option.none(),
85 + },
86 + isLoggedIn: () => Option.isSome(apiKey),
87 + logout: Effect.void,
88 + login: (loginApiKey, orgId) =>
89 + Effect.sync(() => {
90 + logins.push({ apiKey: loginApiKey, orgId });
91 + }),
92 + update: () => Effect.void,
93 + })
94 + ),
95 + Layer.succeed(
96 + ComposioClientSingleton,
97 + ComposioClientSingleton.of({
98 + get: () => Effect.succeed(clientFor({})),
99 + getFor: (scope: MockRequestScope) => Effect.succeed(clientFor(scope)),
100 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
101 + })
102 + ),
103 + ToolkitsTest(),
104 + Layer.succeed(ProjectContext, ProjectContext.of({ resolve: Effect.succeed(Option.none()) })),
105 + Layer.succeed(
106 + HttpClient.HttpClient,
107 + HttpClient.make(request =>
108 + Effect.die(new Error(`unexpected HTTP call from an agent handler test: ${request.url}`))
109 + )
110 + ),
111 + BunFileSystem.layer,
112 + BunPath.layer,
113 + Layer.succeed(
114 + NodeOs,
115 + NodeOs.of({ homedir, tmpdir: homedir, arch: 'arm64', platform: 'darwin' })
116 + ),
117 + Layer.succeed(
118 + NodeProcess,
119 + NodeProcess.of({
120 + cwd: homedir,
121 + execPath: `${homedir}/composio`,
122 + platform: 'darwin',
123 + arch: 'arm64',
124 + setExitCode: () => Effect.void,
125 + })
126 + ),
127 + ConfigProvider.layer(hostOnlyEnvConfigProvider)
128 + );
129 + return { layer, outputs, logins };
130 +};
ts/packages/cli/test/__utils__/layers/shadow-client.ts new
+27
@@ -0,0 +1,27 @@
1 +import { Auth, make, type ComposioClientShape } from '@composio/client/effect';
2 +import { Effect } from 'effect';
3 +import { HttpClient } from 'effect/http';
4 +import { mockAccountResources, type AccountTestData, type MockRequestScope } from './accounts';
5 +
6 +// A resource the account mocks do not shadow reaches this transport and dies with its URL.
7 +const baseClient = make(
8 + { auth: Auth.project('test'), baseURL: 'https://mock.invalid' },
9 + HttpClient.make(request =>
10 + Effect.die(new Error(`unexpected network call from a shadowed test client: ${request.url}`))
11 + )
12 +);
13 +
14 +/**
15 + * A Composio client whose account resources answer from `mockAccountResources` and whose
16 + * unshadowed resources die loudly, so a handler test can never reach the network. Callers
17 + * supply only the account data their handler reads; `test-layer.ts` shadows its mock client
18 + * the same way.
19 + */
20 +export const makeShadowClient = (
21 + accountData: AccountTestData,
22 + scope: MockRequestScope
23 +): ComposioClientShape =>
24 + ({
25 + ...baseClient,
26 + ...mockAccountResources(accountData, scope),
27 + }) as unknown as ComposioClientShape;
ts/packages/cli/test/__utils__/models/agent.ts new
+26
@@ -0,0 +1,26 @@
1 +import type { AgentIdentity } from 'src/services/agents';
2 +
3 +/**
4 + * A READY agent identity as `agents.composio.dev` returns it from `/api/signup` and
5 + * `/api/whoami`. Suites override only the fields their scenario is about.
6 + */
7 +export const makeAgentIdentity = (overrides: Partial<AgentIdentity> = {}): AgentIdentity => ({
8 + status: 'READY',
9 + slug: 'test-agent',
10 + email: 'test-agent@agent.composio.ai',
11 + composio_agent_key: 'cak_test_agent',
12 + composio: {
13 + member_id: 'mem_agent',
14 + org_id: 'org_agent',
15 + project_id: 'proj_agent',
16 + user_api_key: 'uak_agent',
17 + },
18 + ...overrides,
19 +});
20 +
21 +/** A JSON response from the agents API, as the stubbed `fetch` answers it. */
22 +export const agentsJsonResponse = (body: unknown, status = 200) =>
23 + new Response(JSON.stringify(body), {
24 + status,
25 + headers: { 'Content-Type': 'application/json' },
26 + });
ts/packages/cli/test/src/commands/agent/agent.cmd.test.ts
+4 -127
@@ -3,30 +3,10 @@ import * as FileSystem from 'effect/FileSystem';
3 import { Effect, Option } from 'effect';
4 import path from 'node:path';
5 import { afterEach, vi } from 'vitest';
6 -import * as constants from 'src/constants';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 -import { readStoredAgentIdentity, writeStoredAgentIdentity } from 'src/services/agents';
9 -import { ComposioUserContext } from 'src/services/user-context';
7 +import { readStoredAgentIdentity } from 'src/services/agents';
8 import { cli, MockConsole, TestLive } from 'test/__utils__';
11 -
12 -const agentSignupResponse = {
13 - status: 'READY',
14 - slug: 'test-agent',
15 - email: 'test-agent@agent.composio.ai',
16 - composio_agent_key: 'cak_test_agent',
17 - composio: {
18 - member_id: 'mem_agent',
19 - org_id: 'org_agent',
20 - project_id: 'proj_agent',
21 - user_api_key: 'uak_agent',
22 - },
23 -};
24 -
25 -const jsonResponse = (body: unknown) =>
26 - new Response(JSON.stringify(body), {
27 - status: 200,
28 - headers: { 'Content-Type': 'application/json' },
29 - });
9 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
10
11 describe('CLI: composio agent', () => {
12 afterEach(() => {
@@ -40,7 +20,7 @@ describe('CLI: composio agent', () => {
20 const fs = yield* FileSystem.FileSystem;
21 const cacheDir = yield* setupCacheDir;
22 const agentConfigPath = path.join(cacheDir, 'agent.json');
43 - const encodedIdentity = `${JSON.stringify(agentSignupResponse, null, 2)}\n`;
23 + const encodedIdentity = `${JSON.stringify(makeAgentIdentity(), null, 2)}\n`;
24 yield* fs.writeFileString(agentConfigPath, encodedIdentity);
25 yield* fs.chmod(agentConfigPath, 0o644);
26 expect((yield* fs.stat(agentConfigPath)).mode & 0o777).toBe(0o644);
@@ -66,54 +46,12 @@ describe('CLI: composio agent', () => {
46 );
47 });
48
69 - layer(TestLive())(it => {
70 - it.effect('agent signup works when the CLI is not signed in', () =>
71 - Effect.gen(function* () {
72 - const fetchSpy = vi
73 - .spyOn(globalThis, 'fetch')
74 - .mockImplementation(async () => jsonResponse(agentSignupResponse));
75 -
76 - yield* cli(['agent', 'signup']);
77 -
78 - expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
79 - expect.stringContaining('/api/signup'),
80 - expect.objectContaining({ method: 'POST' })
81 - );
82 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
83 - expect(output).toContain('composio agent signup signs you up as a Composio agent');
84 - expect(output).toContain('fully non-interactive');
85 -
86 - const ctx = yield* ComposioUserContext;
87 - expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
88 - expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
89 -
90 - const fs = yield* FileSystem.FileSystem;
91 - const cacheDir = yield* setupCacheDir;
92 - const userConfigRaw = yield* fs.readFileString(
93 - path.join(cacheDir, constants.USER_CONFIG_FILE_NAME),
94 - 'utf8'
95 - );
96 - const agentConfigRaw = yield* fs.readFileString(path.join(cacheDir, 'agent.json'), 'utf8');
97 -
98 - expect(JSON.parse(userConfigRaw)).toMatchObject({
99 - api_key: 'uak_agent',
100 - org_id: 'org_agent',
101 - });
102 - expect(JSON.parse(agentConfigRaw)).toMatchObject({
103 - composio_agent_key: 'cak_test_agent',
104 - agent_key: 'cak_test_agent',
105 - composio: { user_api_key: 'uak_agent' },
106 - });
107 - })
108 - );
109 - });
110 -
49 layer(TestLive())(it => {
50 it.effect('top-level signup makes clear it signs up an agent', () =>
51 Effect.gen(function* () {
52 const fetchSpy = vi
53 .spyOn(globalThis, 'fetch')
116 - .mockImplementation(async () => jsonResponse(agentSignupResponse));
54 + .mockImplementation(async () => agentsJsonResponse(makeAgentIdentity()));
55
56 yield* cli(['signup']);
57 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
@@ -127,65 +65,4 @@ describe('CLI: composio agent', () => {
65 })
66 );
67 });
130 -
131 - layer(TestLive())(it => {
132 - it.effect('agent inbox prints only JSON', () =>
133 - Effect.gen(function* () {
134 - yield* writeStoredAgentIdentity(agentSignupResponse);
135 - const fs = yield* FileSystem.FileSystem;
136 - const cacheDir = yield* setupCacheDir;
137 - expect((yield* fs.stat(path.join(cacheDir, 'agent.json'))).mode & 0o777).toBe(0o600);
138 - const inbox = {
139 - count: 1,
140 - messages: [
141 - {
142 - id: 'msg_123',
143 - from: 'person@example.com',
144 - subject: 'Hello',
145 - preview: 'Hi agent',
146 - },
147 - ],
148 - };
149 - const fetchSpy = vi
150 - .spyOn(globalThis, 'fetch')
151 - .mockImplementation(async () => jsonResponse(inbox));
152 -
153 - yield* cli(['agent', 'inbox']);
154 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
155 -
156 - expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
157 - expect.stringContaining('/api/mail'),
158 - expect.objectContaining({
159 - method: 'GET',
160 - headers: expect.objectContaining({ Authorization: 'Bearer cak_test_agent' }),
161 - })
162 - );
163 - expect(lines).toEqual([JSON.stringify(inbox)]);
164 - })
165 - );
166 - });
167 -
168 - layer(TestLive({ fixture: 'user-config-example' }))(it => {
169 - it.effect('agent commands show a soft auth warning when signed in as a human user', () =>
170 - Effect.gen(function* () {
171 - yield* cli(['agent', 'whoami']);
172 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
173 -
174 - expect(output).toContain('currently signed in to Composio as a regular user');
175 - expect(output).toContain('composio agent login <composio_agent_key>');
176 - expect(process.exitCode).toBe(1);
177 - })
178 - );
179 -
180 - it.effect('agent signup shows a soft auth warning when signed in as a human user', () =>
181 - Effect.gen(function* () {
182 - yield* cli(['agent', 'signup']);
183 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
184 -
185 - expect(output).toContain('currently signed in to Composio as a regular user');
186 - expect(output).toContain('composio signup');
187 - expect(process.exitCode).toBe(1);
188 - })
189 - );
190 - });
68 });
ts/packages/cli/test/src/commands/agent/claim/agent.claim.cmd.test.ts new
+58
@@ -0,0 +1,58 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 +import { writeStoredAgentIdentity } from 'src/services/agents';
5 +import { cli, MockConsole, TestLive } from 'test/__utils__';
6 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
7 +
8 +describe('CLI: composio agent claim', () => {
9 + afterEach(() => {
10 + vi.restoreAllMocks();
11 + process.exitCode = undefined;
12 + });
13 +
14 + layer(TestLive())(it => {
15 + it.effect('[Given] an email [Then] invites it and prints the invite as JSON', () =>
16 + Effect.gen(function* () {
17 + yield* writeStoredAgentIdentity(makeAgentIdentity());
18 + const fetchSpy = vi
19 + .spyOn(globalThis, 'fetch')
20 + .mockImplementation(async () => agentsJsonResponse({ status: 'invited' }));
21 +
22 + yield* cli(['agent', 'claim', 'boss@example.com']);
23 +
24 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
25 + expect.stringContaining('/api/claim'),
26 + expect.objectContaining({
27 + method: 'POST',
28 + body: JSON.stringify({ email: 'boss@example.com' }),
29 + })
30 + );
31 + const stdout = yield* MockConsole.getLines({ stream: 'stdout', stripAnsi: true });
32 + expect(stdout.at(-1)).toBe(
33 + JSON.stringify({
34 + status: 'invited',
35 + email: 'boss@example.com',
36 + org_id: null,
37 + invite_code: null,
38 + })
39 + );
40 + })
41 + );
42 + });
43 +
44 + layer(TestLive({ fixture: 'user-config-example' }))(it => {
45 + it.effect('[Given] the CLI is signed in as a human user [Then] shows a soft auth warning', () =>
46 + Effect.gen(function* () {
47 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
48 +
49 + yield* cli(['agent', 'claim', 'boss@example.com']);
50 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
51 +
52 + expect(output).toContain('currently signed in to Composio as a regular user');
53 + expect(process.exitCode).toBe(1);
54 + expect(fetchSpy).not.toHaveBeenCalled();
55 + })
56 + );
57 + });
58 +});
ts/packages/cli/test/src/commands/agent/claim/agent.claim.handler.test.ts new
+116
@@ -0,0 +1,116 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 +import { runAgentClaim } from 'src/commands/agent/claim/agent.claim.handler';
5 +import { writeStoredAgentIdentity } from 'src/services/agents';
6 +import { MockConsole } from 'test/__utils__';
7 +import { AgentHandlerTest } from 'test/__utils__/layers/agents';
8 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
9 +
10 +describe('runAgentClaim', () => {
11 + afterEach(() => {
12 + vi.restoreAllMocks();
13 + process.exitCode = undefined;
14 + });
15 +
16 + it.effect(
17 + '[Given] a stored agent key [Then] posts the invite and prints what the API returned',
18 + () => {
19 + const { layer, outputs } = AgentHandlerTest();
20 + return Effect.gen(function* () {
21 + yield* writeStoredAgentIdentity(makeAgentIdentity());
22 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
23 + agentsJsonResponse({
24 + status: 'pending',
25 + email: 'Boss@Example.com',
26 + org_id: 'org_agent',
27 + invite_code: 'inv_123',
28 + })
29 + );
30 +
31 + yield* runAgentClaim({ email: 'boss@example.com' });
32 +
33 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
34 + 'https://agents.composio.dev/api/claim',
35 + expect.objectContaining({
36 + method: 'POST',
37 + body: JSON.stringify({ email: 'boss@example.com' }),
38 + headers: expect.objectContaining({ Authorization: 'Bearer cak_test_agent' }),
39 + })
40 + );
41 + expect(yield* MockConsole.getLines({ stripAnsi: true })).toEqual([
42 + 'Sent Composio org claim invite to Boss@Example.com.',
43 + ]);
44 + expect(outputs).toEqual([
45 + {
46 + data: JSON.stringify({
47 + status: 'pending',
48 + email: 'Boss@Example.com',
49 + org_id: 'org_agent',
50 + invite_code: 'inv_123',
51 + }),
52 + force: false,
53 + },
54 + ]);
55 + }).pipe(Effect.provide(layer));
56 + }
57 + );
58 +
59 + it.effect('[Given] an empty API response [Then] falls back to the requested email', () => {
60 + const { layer, outputs } = AgentHandlerTest();
61 + return Effect.gen(function* () {
62 + yield* writeStoredAgentIdentity(makeAgentIdentity());
63 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () => agentsJsonResponse({}));
64 +
65 + yield* runAgentClaim({ email: 'boss@example.com' });
66 +
67 + expect(yield* MockConsole.getLines({ stripAnsi: true })).toEqual([
68 + 'Sent Composio org claim invite to boss@example.com.',
69 + ]);
70 + expect(outputs.map(output => output.data)).toEqual([
71 + JSON.stringify({
72 + status: 'invited',
73 + email: 'boss@example.com',
74 + org_id: null,
75 + invite_code: null,
76 + }),
77 + ]);
78 + }).pipe(Effect.provide(layer));
79 + });
80 +
81 + it.effect('[Given] no stored identity [Then] warns, exits 1, and sends no invite', () => {
82 + const { layer, outputs } = AgentHandlerTest();
83 + return Effect.gen(function* () {
84 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
85 +
86 + yield* runAgentClaim({ email: 'boss@example.com' });
87 +
88 + expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
89 + 'No Composio agent identity is saved on this machine.',
90 + ]);
91 + expect(process.exitCode).toBe(1);
92 + expect(fetchSpy).not.toHaveBeenCalled();
93 + expect(outputs).toEqual([]);
94 + }).pipe(Effect.provide(layer));
95 + });
96 +
97 + it.effect('[Given] the agents API refuses the invite [Then] fails with its message', () => {
98 + const { layer, outputs } = AgentHandlerTest();
99 + return Effect.gen(function* () {
100 + yield* writeStoredAgentIdentity(makeAgentIdentity());
101 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
102 + agentsJsonResponse({ message: 'Org already claimed' }, 409)
103 + );
104 +
105 + const error = yield* Effect.flip(runAgentClaim({ email: 'boss@example.com' }));
106 +
107 + expect(error).toMatchObject({
108 + _tag: 'services/AgentRequestError',
109 + message: 'Org already claimed',
110 + pathname: '/api/claim',
111 + status: 409,
112 + });
113 + expect(outputs).toEqual([]);
114 + }).pipe(Effect.provide(layer));
115 + });
116 +});
ts/packages/cli/test/src/commands/agent/inbox/agent.inbox.cmd.test.ts new
+69
@@ -0,0 +1,69 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import { Effect } from 'effect';
4 +import path from 'node:path';
5 +import { afterEach, vi } from 'vitest';
6 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 +import { writeStoredAgentIdentity } from 'src/services/agents';
8 +import { cli, MockConsole, TestLive } from 'test/__utils__';
9 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
10 +
11 +describe('CLI: composio agent inbox', () => {
12 + afterEach(() => {
13 + vi.restoreAllMocks();
14 + process.exitCode = undefined;
15 + });
16 +
17 + layer(TestLive())(it => {
18 + it.effect('agent inbox prints only JSON', () =>
19 + Effect.gen(function* () {
20 + yield* writeStoredAgentIdentity(makeAgentIdentity());
21 + const fs = yield* FileSystem.FileSystem;
22 + const cacheDir = yield* setupCacheDir;
23 + expect((yield* fs.stat(path.join(cacheDir, 'agent.json'))).mode & 0o777).toBe(0o600);
24 + const inbox = {
25 + count: 1,
26 + messages: [
27 + {
28 + id: 'msg_123',
29 + from: 'person@example.com',
30 + subject: 'Hello',
31 + preview: 'Hi agent',
32 + },
33 + ],
34 + };
35 + const fetchSpy = vi
36 + .spyOn(globalThis, 'fetch')
37 + .mockImplementation(async () => agentsJsonResponse(inbox));
38 +
39 + yield* cli(['agent', 'inbox']);
40 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
41 +
42 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
43 + expect.stringContaining('/api/mail?limit=50'),
44 + expect.objectContaining({
45 + method: 'GET',
46 + headers: expect.objectContaining({ Authorization: 'Bearer cak_test_agent' }),
47 + })
48 + );
49 + expect(lines).toEqual([JSON.stringify(inbox)]);
50 + })
51 + );
52 +
53 + it.effect('[Given] --limit [Then] asks the agents API for that many messages', () =>
54 + Effect.gen(function* () {
55 + yield* writeStoredAgentIdentity(makeAgentIdentity());
56 + const fetchSpy = vi
57 + .spyOn(globalThis, 'fetch')
58 + .mockImplementation(async () => agentsJsonResponse({ count: 0, messages: [] }));
59 +
60 + yield* cli(['agent', 'inbox', '--limit', '5']);
61 +
62 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
63 + expect.stringContaining('/api/mail?limit=5'),
64 + expect.anything()
65 + );
66 + })
67 + );
68 + });
69 +});
ts/packages/cli/test/src/commands/agent/inbox/agent.inbox.handler.test.ts new
+102
@@ -0,0 +1,102 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 +import { runAgentInbox } from 'src/commands/agent/inbox/agent.inbox.handler';
5 +import { writeStoredAgentIdentity } from 'src/services/agents';
6 +import { MockConsole } from 'test/__utils__';
7 +import { AgentHandlerTest } from 'test/__utils__/layers/agents';
8 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
9 +
10 +const inbox = {
11 + count: 1,
12 + messages: [
13 + {
14 + id: 'msg_123',
15 + from: 'person@example.com',
16 + subject: 'Hello',
17 + preview: 'Hi agent',
18 + labels: ['inbox'],
19 + },
20 + ],
21 + next_cursor: 'cursor_2',
22 +};
23 +
24 +describe('runAgentInbox', () => {
25 + afterEach(() => {
26 + vi.restoreAllMocks();
27 + process.exitCode = undefined;
28 + });
29 +
30 + it.effect(
31 + '[Given] a stored agent key [Then] fetches up to --limit messages and forces the JSON to stdout',
32 + () => {
33 + const { layer, outputs } = AgentHandlerTest();
34 + return Effect.gen(function* () {
35 + yield* writeStoredAgentIdentity(makeAgentIdentity());
36 + const fetchSpy = vi
37 + .spyOn(globalThis, 'fetch')
38 + .mockImplementation(async () => agentsJsonResponse(inbox));
39 +
40 + yield* runAgentInbox({ limit: 7 });
41 +
42 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
43 + 'https://agents.composio.dev/api/mail?limit=7',
44 + expect.objectContaining({
45 + method: 'GET',
46 + headers: expect.objectContaining({ Authorization: 'Bearer cak_test_agent' }),
47 + })
48 + );
49 + // Fields the CLI does not model pass through unchanged.
50 + expect(outputs).toEqual([{ data: JSON.stringify(inbox), force: true }]);
51 + expect(yield* MockConsole.getLines()).toEqual([]);
52 + }).pipe(Effect.provide(layer));
53 + }
54 + );
55 +
56 + it.effect('[Given] a human login [Then] warns, exits 1, and reads no mail', () => {
57 + const { layer, outputs } = AgentHandlerTest({ apiKey: 'uak_human' });
58 + return Effect.gen(function* () {
59 + yield* writeStoredAgentIdentity(makeAgentIdentity());
60 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
61 +
62 + yield* runAgentInbox({ limit: 50 });
63 +
64 + expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
65 + 'This CLI is currently signed in to Composio as a regular user, not an agent.',
66 + ]);
67 + expect(process.exitCode).toBe(1);
68 + expect(fetchSpy).not.toHaveBeenCalled();
69 + expect(outputs).toEqual([]);
70 + }).pipe(Effect.provide(layer));
71 + });
72 +
73 + it.effect('[Given] the logged-in key is the stored agent [Then] reads its inbox', () => {
74 + const { layer, outputs } = AgentHandlerTest({ apiKey: 'uak_agent' });
75 + return Effect.gen(function* () {
76 + yield* writeStoredAgentIdentity(makeAgentIdentity());
77 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () => agentsJsonResponse(inbox));
78 +
79 + yield* runAgentInbox({ limit: 50 });
80 +
81 + expect(outputs).toEqual([{ data: JSON.stringify(inbox), force: true }]);
82 + }).pipe(Effect.provide(layer));
83 + });
84 +
85 + it.effect('[Given] a response that is not an inbox [Then] fails to decode it', () => {
86 + const { layer, outputs } = AgentHandlerTest();
87 + return Effect.gen(function* () {
88 + yield* writeStoredAgentIdentity(makeAgentIdentity());
89 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
90 + agentsJsonResponse({ count: 'one' })
91 + );
92 +
93 + const error = yield* Effect.flip(runAgentInbox({ limit: 50 }));
94 +
95 + expect(error).toMatchObject({
96 + _tag: 'services/AgentResponseDecodeError',
97 + pathname: '/api/mail?limit=50',
98 + });
99 + expect(outputs).toEqual([]);
100 + }).pipe(Effect.provide(layer));
101 + });
102 +});
ts/packages/cli/test/src/commands/agent/login/agent.login.cmd.test.ts renamed
ts/packages/cli/test/src/commands/agent/login/agent.login.handler.test.ts new
+82
@@ -0,0 +1,82 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect, Option } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 +import { runAgentLogin } from 'src/commands/agent/login/agent.login.handler';
5 +import { readStoredAgentIdentity, writeStoredAgentIdentity } from 'src/services/agents';
6 +import { MockConsole } from 'test/__utils__';
7 +import { AgentHandlerTest } from 'test/__utils__/layers/agents';
8 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
9 +
10 +describe('runAgentLogin', () => {
11 + afterEach(() => {
12 + vi.restoreAllMocks();
13 + process.exitCode = undefined;
14 + });
15 +
16 + it.effect(
17 + '[Given] a key the agents API knows [Then] stores the identity under that key and logs in',
18 + () => {
19 + const { layer, outputs, logins } = AgentHandlerTest();
20 + return Effect.gen(function* () {
21 + // The API answers without the key; the stored identity keeps the one the user passed.
22 + const fetchSpy = vi
23 + .spyOn(globalThis, 'fetch')
24 + .mockImplementation(async () =>
25 + agentsJsonResponse(makeAgentIdentity({ composio_agent_key: undefined }))
26 + );
27 +
28 + yield* runAgentLogin({ composioAgentKey: 'cak_existing' });
29 +
30 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
31 + 'https://agents.composio.dev/api/whoami',
32 + expect.objectContaining({
33 + headers: expect.objectContaining({ Authorization: 'Bearer cak_existing' }),
34 + })
35 + );
36 + expect(Option.getOrThrow(yield* readStoredAgentIdentity)).toMatchObject({
37 + composio_agent_key: 'cak_existing',
38 + agent_key: 'cak_existing',
39 + });
40 + expect(logins).toEqual([{ apiKey: 'uak_agent', orgId: 'org_agent' }]);
41 + expect(yield* MockConsole.getLines({ stripAnsi: true })).toEqual([
42 + 'Logged in as Composio agent test-agent@agent.composio.ai',
43 + ]);
44 + expect(outputs.map(output => JSON.parse(output.data))).toEqual([
45 + expect.objectContaining({ account_type: 'agent', logged_in: true }),
46 + ]);
47 + }).pipe(Effect.provide(layer));
48 + }
49 + );
50 +
51 + it.effect('[Given] the CLI is logged in as this agent [Then] logs in again', () => {
52 + const { layer, logins } = AgentHandlerTest({ apiKey: 'uak_agent' });
53 + return Effect.gen(function* () {
54 + yield* writeStoredAgentIdentity(makeAgentIdentity());
55 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
56 + agentsJsonResponse(makeAgentIdentity())
57 + );
58 +
59 + yield* runAgentLogin({ composioAgentKey: 'cak_test_agent' });
60 +
61 + expect(logins).toEqual([{ apiKey: 'uak_agent', orgId: 'org_agent' }]);
62 + expect(process.exitCode).toBeUndefined();
63 + }).pipe(Effect.provide(layer));
64 + });
65 +
66 + it.effect('[Given] a human login [Then] warns, exits 1, and looks nothing up', () => {
67 + const { layer, outputs, logins } = AgentHandlerTest({ apiKey: 'uak_human' });
68 + return Effect.gen(function* () {
69 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
70 +
71 + yield* runAgentLogin({ composioAgentKey: 'cak_existing' });
72 +
73 + expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
74 + 'This CLI is currently signed in to Composio as a regular user, not an agent.',
75 + ]);
76 + expect(process.exitCode).toBe(1);
77 + expect(fetchSpy).not.toHaveBeenCalled();
78 + expect(logins).toEqual([]);
79 + expect(outputs).toEqual([]);
80 + }).pipe(Effect.provide(layer));
81 + });
82 +});
ts/packages/cli/test/src/commands/agent/signup/agent.signup.cmd.test.ts new
+98
@@ -0,0 +1,98 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import { Effect, Option } from 'effect';
4 +import path from 'node:path';
5 +import { afterEach, vi } from 'vitest';
6 +import * as constants from 'src/constants';
7 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 +import { ComposioUserContext } from 'src/services/user-context';
9 +import { cli, MockConsole, TestLive } from 'test/__utils__';
10 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
11 +
12 +describe('CLI: composio agent signup', () => {
13 + afterEach(() => {
14 + vi.restoreAllMocks();
15 + process.exitCode = undefined;
16 + });
17 +
18 + layer(TestLive())(it => {
19 + it.effect('agent signup works when the CLI is not signed in', () =>
20 + Effect.gen(function* () {
21 + const fetchSpy = vi
22 + .spyOn(globalThis, 'fetch')
23 + .mockImplementation(async () => agentsJsonResponse(makeAgentIdentity()));
24 +
25 + yield* cli(['agent', 'signup']);
26 +
27 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
28 + expect.stringContaining('/api/signup'),
29 + expect.objectContaining({ method: 'POST' })
30 + );
31 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
32 + expect(output).toContain('composio agent signup signs you up as a Composio agent');
33 + expect(output).toContain('fully non-interactive');
34 +
35 + const ctx = yield* ComposioUserContext;
36 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
37 + expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
38 +
39 + const fs = yield* FileSystem.FileSystem;
40 + const cacheDir = yield* setupCacheDir;
41 + const userConfigRaw = yield* fs.readFileString(
42 + path.join(cacheDir, constants.USER_CONFIG_FILE_NAME),
43 + 'utf8'
44 + );
45 + const agentConfigRaw = yield* fs.readFileString(path.join(cacheDir, 'agent.json'), 'utf8');
46 +
47 + expect(JSON.parse(userConfigRaw)).toMatchObject({
48 + api_key: 'uak_agent',
49 + org_id: 'org_agent',
50 + });
51 + expect(JSON.parse(agentConfigRaw)).toMatchObject({
52 + composio_agent_key: 'cak_test_agent',
53 + agent_key: 'cak_test_agent',
54 + composio: { user_api_key: 'uak_agent' },
55 + });
56 + })
57 + );
58 + });
59 +
60 + layer(TestLive())(it => {
61 + it.effect('[Given] --no-wait -f [Then] starts a fresh signup and stays logged out', () =>
62 + Effect.gen(function* () {
63 + const fetchSpy = vi
64 + .spyOn(globalThis, 'fetch')
65 + .mockImplementation(async () =>
66 + agentsJsonResponse(makeAgentIdentity({ status: 'PENDING', composio: undefined }))
67 + );
68 +
69 + yield* cli(['agent', 'signup', '--no-wait', '-f']);
70 +
71 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
72 + expect.stringContaining('/api/signup?wait=0'),
73 + expect.objectContaining({ method: 'POST' })
74 + );
75 + const stdout = yield* MockConsole.getLines({ stream: 'stdout', stripAnsi: true });
76 + expect(JSON.parse(stdout.at(-1) ?? '')).toMatchObject({
77 + status: 'PENDING',
78 + logged_in: false,
79 + });
80 + const ctx = yield* ComposioUserContext;
81 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
82 + })
83 + );
84 + });
85 +
86 + layer(TestLive({ fixture: 'user-config-example' }))(it => {
87 + it.effect('agent signup shows a soft auth warning when signed in as a human user', () =>
88 + Effect.gen(function* () {
89 + yield* cli(['agent', 'signup']);
90 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
91 +
92 + expect(output).toContain('currently signed in to Composio as a regular user');
93 + expect(output).toContain('composio signup');
94 + expect(process.exitCode).toBe(1);
95 + })
96 + );
97 + });
98 +});
ts/packages/cli/test/src/commands/agent/signup/agent.signup.handler.test.ts new
+234
@@ -0,0 +1,234 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect, Option } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 +import {
5 + runAgentSignup,
6 + type AgentSignupParams,
7 +} from 'src/commands/agent/signup/agent.signup.handler';
8 +import { readStoredAgentIdentity, writeStoredAgentIdentity } from 'src/services/agents';
9 +import { MockConsole } from 'test/__utils__';
10 +import { AgentHandlerTest } from 'test/__utils__/layers/agents';
11 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
12 +
13 +const params = (overrides: Partial<AgentSignupParams> = {}): AgentSignupParams => ({
14 + noWait: false,
15 + noLogin: false,
16 + force: false,
17 + ...overrides,
18 +});
19 +
20 +const pendingIdentity = makeAgentIdentity({
21 + status: 'PENDING',
22 + composio_agent_key: 'cak_pending',
23 + composio: undefined,
24 +});
25 +
26 +/** The note body for the default READY identity. */
27 +const readyNote = [
28 + '[Composio Agent] Type: agent',
29 + 'Status: READY',
30 + 'Email: test-agent@agent.composio.ai',
31 + 'Slug: test-agent',
32 + 'Current Org ID: org_agent',
33 + 'Project ID: proj_agent',
34 + 'Agent key: stored in ~/.composio/agent.json',
35 +].join('\n');
36 +
37 +const INTRO = '-- composio agent signup --';
38 +const INFO =
39 + 'composio agent signup signs you up as a Composio agent. This flow is fully non-interactive and does not open a browser.';
40 +const OUTRO = '-- Agent setup complete. --';
41 +
42 +const summaryJson = (identity: ReturnType<typeof makeAgentIdentity>, loggedIn: boolean) =>
43 + JSON.stringify({
44 + account_type: 'agent',
45 + status: identity.status,
46 + slug: identity.slug,
47 + email: identity.email,
48 + org_id: identity.composio?.org_id ?? null,
49 + project_id: identity.composio?.project_id ?? null,
50 + member_id: identity.composio?.member_id ?? null,
51 + claimed_by: null,
52 + claimed_at: null,
53 + logged_in: loggedIn,
54 + });
55 +
56 +describe('runAgentSignup', () => {
57 + afterEach(() => {
58 + vi.restoreAllMocks();
59 + process.exitCode = undefined;
60 + });
61 +
62 + it.effect(
63 + '[Given] no stored identity [Then] signs up, waits, stores the identity, and logs in',
64 + () => {
65 + const { layer, outputs, logins } = AgentHandlerTest();
66 + return Effect.gen(function* () {
67 + const fetchSpy = vi
68 + .spyOn(globalThis, 'fetch')
69 + .mockImplementation(async () => agentsJsonResponse(makeAgentIdentity()));
70 +
71 + yield* runAgentSignup(params());
72 +
73 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
74 + 'https://agents.composio.dev/api/signup',
75 + expect.objectContaining({ method: 'POST', body: '{}' })
76 + );
77 + expect(Option.getOrThrow(yield* readStoredAgentIdentity)).toMatchObject({
78 + composio_agent_key: 'cak_test_agent',
79 + agent_key: 'cak_test_agent',
80 + });
81 + expect(logins).toEqual([{ apiKey: 'uak_agent', orgId: 'org_agent' }]);
82 + expect(yield* MockConsole.getLines({ stripAnsi: true })).toEqual([
83 + INTRO,
84 + INFO,
85 + readyNote,
86 + 'Logged in with the Composio agent identity.',
87 + OUTRO,
88 + ]);
89 + expect(outputs).toEqual([{ data: summaryJson(makeAgentIdentity(), true), force: false }]);
90 + }).pipe(Effect.provide(layer));
91 + }
92 + );
93 +
94 + it.effect(
95 + '[Given] --no-wait [Then] starts the signup, reports it pending, and stays logged out',
96 + () => {
97 + const { layer, outputs, logins } = AgentHandlerTest();
98 + return Effect.gen(function* () {
99 + const fetchSpy = vi
100 + .spyOn(globalThis, 'fetch')
101 + .mockImplementation(async () => agentsJsonResponse(pendingIdentity));
102 +
103 + yield* runAgentSignup(params({ noWait: true }));
104 +
105 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
106 + 'https://agents.composio.dev/api/signup?wait=0',
107 + expect.objectContaining({ method: 'POST' })
108 + );
109 + expect(Option.getOrThrow(yield* readStoredAgentIdentity).composio_agent_key).toBe(
110 + 'cak_pending'
111 + );
112 + expect(logins).toEqual([]);
113 + expect(yield* MockConsole.getLines({ stripAnsi: true })).toEqual([
114 + INTRO,
115 + INFO,
116 + [
117 + '[Composio Agent] Type: agent',
118 + 'Status: PENDING',
119 + 'Email: test-agent@agent.composio.ai',
120 + 'Slug: test-agent',
121 + 'Current Org ID: pending',
122 + 'Project ID: pending',
123 + 'Agent key: stored in ~/.composio/agent.json',
124 + ].join('\n'),
125 + 'Signup is pending. Run `composio agent whoami` to poll status.',
126 + OUTRO,
127 + ]);
128 + expect(outputs).toEqual([{ data: summaryJson(pendingIdentity, false), force: false }]);
129 + }).pipe(Effect.provide(layer));
130 + }
131 + );
132 +
133 + it.effect('[Given] --no-login [Then] signs up without logging in or a pending note', () => {
134 + const { layer, outputs, logins } = AgentHandlerTest();
135 + return Effect.gen(function* () {
136 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
137 + agentsJsonResponse(makeAgentIdentity())
138 + );
139 +
140 + yield* runAgentSignup(params({ noLogin: true }));
141 +
142 + expect(logins).toEqual([]);
143 + expect(yield* MockConsole.getLines({ stripAnsi: true })).toEqual([
144 + INTRO,
145 + INFO,
146 + readyNote,
147 + OUTRO,
148 + ]);
149 + expect(outputs).toEqual([{ data: summaryJson(makeAgentIdentity(), false), force: false }]);
150 + }).pipe(Effect.provide(layer));
151 + });
152 +
153 + it.effect(
154 + '[Given] a stored READY identity [Then] refreshes and reuses it without signing up',
155 + () => {
156 + const { layer, logins } = AgentHandlerTest();
157 + return Effect.gen(function* () {
158 + yield* writeStoredAgentIdentity(makeAgentIdentity());
159 + const fetchSpy = vi
160 + .spyOn(globalThis, 'fetch')
161 + .mockImplementation(async () => agentsJsonResponse(makeAgentIdentity()));
162 +
163 + yield* runAgentSignup(params());
164 +
165 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
166 + 'https://agents.composio.dev/api/whoami',
167 + expect.objectContaining({
168 + method: 'GET',
169 + headers: expect.objectContaining({ Authorization: 'Bearer cak_test_agent' }),
170 + })
171 + );
172 + expect(logins).toEqual([{ apiKey: 'uak_agent', orgId: 'org_agent' }]);
173 + }).pipe(Effect.provide(layer));
174 + }
175 + );
176 +
177 + it.effect('[Given] a stored identity and --force [Then] signs up a new agent', () => {
178 + const { layer } = AgentHandlerTest();
179 + return Effect.gen(function* () {
180 + yield* writeStoredAgentIdentity(makeAgentIdentity({ composio_agent_key: 'cak_old' }));
181 + const fetchSpy = vi
182 + .spyOn(globalThis, 'fetch')
183 + .mockImplementation(async () => agentsJsonResponse(makeAgentIdentity()));
184 +
185 + yield* runAgentSignup(params({ force: true, noLogin: true }));
186 +
187 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
188 + 'https://agents.composio.dev/api/signup',
189 + expect.objectContaining({ method: 'POST' })
190 + );
191 + expect(Option.getOrThrow(yield* readStoredAgentIdentity).composio_agent_key).toBe(
192 + 'cak_test_agent'
193 + );
194 + }).pipe(Effect.provide(layer));
195 + });
196 +
197 + it.effect('[Given] a human login [Then] warns, exits 1, and signs nothing up', () => {
198 + const { layer, outputs, logins } = AgentHandlerTest({ apiKey: 'uak_human' });
199 + return Effect.gen(function* () {
200 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
201 +
202 + yield* runAgentSignup(params());
203 +
204 + expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
205 + 'This CLI is currently signed in to Composio as a regular user, not an agent.',
206 + ]);
207 + expect(process.exitCode).toBe(1);
208 + expect(fetchSpy).not.toHaveBeenCalled();
209 + expect(logins).toEqual([]);
210 + expect(outputs).toEqual([]);
211 + }).pipe(Effect.provide(layer));
212 + });
213 +
214 + it.effect('[Given] the agents API refuses the signup [Then] fails and stores nothing', () => {
215 + const { layer, outputs, logins } = AgentHandlerTest();
216 + return Effect.gen(function* () {
217 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
218 + agentsJsonResponse({ message: 'Signup unavailable' }, 503)
219 + );
220 +
221 + const error = yield* Effect.flip(runAgentSignup(params()));
222 +
223 + expect(error).toMatchObject({
224 + _tag: 'services/AgentRequestError',
225 + message: 'Signup unavailable',
226 + pathname: '/api/signup',
227 + status: 503,
228 + });
229 + expect(Option.isNone(yield* readStoredAgentIdentity)).toBe(true);
230 + expect(logins).toEqual([]);
231 + expect(outputs).toEqual([]);
232 + }).pipe(Effect.provide(layer));
233 + });
234 +});
ts/packages/cli/test/src/commands/agent/whoami/agent.whoami.cmd.test.ts new
+48
@@ -0,0 +1,48 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 +import { writeStoredAgentIdentity } from 'src/services/agents';
5 +import { cli, MockConsole, TestLive } from 'test/__utils__';
6 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
7 +
8 +describe('CLI: composio agent whoami', () => {
9 + afterEach(() => {
10 + vi.restoreAllMocks();
11 + process.exitCode = undefined;
12 + });
13 +
14 + layer(TestLive())(it => {
15 + it.effect('[Given] a stored agent identity [Then] prints its summary as JSON', () =>
16 + Effect.gen(function* () {
17 + yield* writeStoredAgentIdentity(makeAgentIdentity());
18 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
19 + agentsJsonResponse(makeAgentIdentity())
20 + );
21 +
22 + yield* cli(['agent', 'whoami']);
23 +
24 + const stdout = yield* MockConsole.getLines({ stream: 'stdout', stripAnsi: true });
25 + expect(JSON.parse(stdout.at(-1) ?? '')).toMatchObject({
26 + account_type: 'agent',
27 + status: 'READY',
28 + email: 'test-agent@agent.composio.ai',
29 + });
30 + expect(stdout.join('\n')).not.toContain('cak_test_agent');
31 + expect(stdout.join('\n')).not.toContain('uak_agent');
32 + })
33 + );
34 + });
35 +
36 + layer(TestLive({ fixture: 'user-config-example' }))(it => {
37 + it.effect('[Given] the CLI is signed in as a human user [Then] shows a soft auth warning', () =>
38 + Effect.gen(function* () {
39 + yield* cli(['agent', 'whoami']);
40 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
41 +
42 + expect(output).toContain('currently signed in to Composio as a regular user');
43 + expect(output).toContain('composio agent login <composio_agent_key>');
44 + expect(process.exitCode).toBe(1);
45 + })
46 + );
47 + });
48 +});
ts/packages/cli/test/src/commands/agent/whoami/agent.whoami.handler.test.ts new
+161
@@ -0,0 +1,161 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect, Option } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 +import { runAgentWhoami } from 'src/commands/agent/whoami/agent.whoami.handler';
5 +import { readStoredAgentIdentity, writeStoredAgentIdentity } from 'src/services/agents';
6 +import { MockConsole } from 'test/__utils__';
7 +import { AgentHandlerTest } from 'test/__utils__/layers/agents';
8 +import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
9 +
10 +const decoration = Effect.map(MockConsole.getLines({ stripAnsi: true }), lines => lines.join('\n'));
11 +
12 +describe('runAgentWhoami', () => {
13 + afterEach(() => {
14 + vi.restoreAllMocks();
15 + process.exitCode = undefined;
16 + });
17 +
18 + it.effect(
19 + '[Given] a stored agent key [Then] refreshes and saves the identity, and prints its summary',
20 + () => {
21 + const { layer, outputs } = AgentHandlerTest();
22 + return Effect.gen(function* () {
23 + yield* writeStoredAgentIdentity(makeAgentIdentity({ status: 'PENDING', composio: {} }));
24 + const fetchSpy = vi
25 + .spyOn(globalThis, 'fetch')
26 + .mockImplementation(async () =>
27 + agentsJsonResponse(makeAgentIdentity({ claimed_by: 'owner@example.com' }))
28 + );
29 +
30 + yield* runAgentWhoami();
31 +
32 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
33 + 'https://agents.composio.dev/api/whoami',
34 + expect.objectContaining({
35 + method: 'GET',
36 + headers: expect.objectContaining({ Authorization: 'Bearer cak_test_agent' }),
37 + })
38 + );
39 + const stored = Option.getOrThrow(yield* readStoredAgentIdentity);
40 + expect(stored).toMatchObject({ status: 'READY', claimed_by: 'owner@example.com' });
41 + expect(yield* decoration).toBe(
42 + [
43 + '[Composio Agent] Type: agent',
44 + 'Status: READY',
45 + 'Email: test-agent@agent.composio.ai',
46 + 'Slug: test-agent',
47 + 'Current Org ID: org_agent',
48 + 'Project ID: proj_agent',
49 + 'Claimed By: owner@example.com',
50 + ].join('\n')
51 + );
52 + expect(outputs).toEqual([
53 + {
54 + data: JSON.stringify({
55 + account_type: 'agent',
56 + status: 'READY',
57 + slug: 'test-agent',
58 + email: 'test-agent@agent.composio.ai',
59 + org_id: 'org_agent',
60 + project_id: 'proj_agent',
61 + member_id: 'mem_agent',
62 + claimed_by: 'owner@example.com',
63 + claimed_at: null,
64 + }),
65 + force: false,
66 + },
67 + ]);
68 + expect(process.exitCode).toBeUndefined();
69 + }).pipe(Effect.provide(layer));
70 + }
71 + );
72 +
73 + it.effect('[Given] a pending identity [Then] prints placeholders for the missing fields', () => {
74 + const { layer } = AgentHandlerTest();
75 + return Effect.gen(function* () {
76 + yield* writeStoredAgentIdentity(makeAgentIdentity());
77 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
78 + agentsJsonResponse({ status: 'pending' })
79 + );
80 +
81 + yield* runAgentWhoami();
82 +
83 + expect(yield* decoration).toBe(
84 + [
85 + '[Composio Agent] Type: agent',
86 + 'Status: PENDING',
87 + 'Email: unknown',
88 + 'Slug: unknown',
89 + 'Current Org ID: pending',
90 + 'Project ID: pending',
91 + 'Claimed By: not claimed',
92 + ].join('\n')
93 + );
94 + // The key the request used is kept on the refreshed identity.
95 + const stored = Option.getOrThrow(yield* readStoredAgentIdentity);
96 + expect(stored.composio_agent_key).toBe('cak_test_agent');
97 + }).pipe(Effect.provide(layer));
98 + });
99 +
100 + it.effect.each([
101 + {
102 + name: 'no stored identity',
103 + apiKey: undefined,
104 + stored: Option.none(),
105 + message: 'No Composio agent identity is saved on this machine.',
106 + },
107 + {
108 + name: 'a stored identity without its key',
109 + apiKey: undefined,
110 + stored: Option.some(makeAgentIdentity({ composio_agent_key: undefined })),
111 + message: 'The saved Composio agent identity is missing its composio_agent_key.',
112 + },
113 + {
114 + name: 'a human login',
115 + apiKey: 'uak_human',
116 + stored: Option.some(makeAgentIdentity()),
117 + message: 'This CLI is currently signed in to Composio as a regular user, not an agent.',
118 + },
119 + ])(
120 + '[Given] $name [Then] warns with next steps, exits 1, and calls nothing',
121 + ({ apiKey, stored, message }) => {
122 + const { layer, outputs } = AgentHandlerTest({ apiKey });
123 + return Effect.gen(function* () {
124 + yield* Effect.forEach(Option.toArray(stored), writeStoredAgentIdentity);
125 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
126 +
127 + yield* runAgentWhoami();
128 +
129 + const warnings = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
130 + expect(warnings).toEqual([message]);
131 + expect(yield* decoration).toContain('Next steps:');
132 + expect(process.exitCode).toBe(1);
133 + expect(fetchSpy).not.toHaveBeenCalled();
134 + expect(outputs).toEqual([]);
135 + }).pipe(Effect.provide(layer));
136 + }
137 + );
138 +
139 + it.effect(
140 + '[Given] a key the agents API rejects [Then] fails and keeps the stored identity',
141 + () => {
142 + const { layer, outputs } = AgentHandlerTest();
143 + return Effect.gen(function* () {
144 + const original = yield* writeStoredAgentIdentity(makeAgentIdentity());
145 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
146 + agentsJsonResponse({ message: 'Invalid agent key' }, 401)
147 + );
148 +
149 + const error = yield* Effect.flip(runAgentWhoami());
150 +
151 + expect(error).toMatchObject({
152 + _tag: 'services/AgentRequestError',
153 + message: 'Invalid agent key',
154 + status: 401,
155 + });
156 + expect(Option.getOrThrow(yield* readStoredAgentIdentity)).toEqual(original);
157 + expect(outputs).toEqual([]);
158 + }).pipe(Effect.provide(layer));
159 + }
160 + );
161 +});