@devries-cameron20 / composio-1 / commits / 8505dc330
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.

feat(cli): add agent signup and claim support (#3317)

## Summary - add `composio signup`, `composio login --agent`, and `composio agent signup` flows backed by agents.composio.dev - make signup messaging explicit that `composio signup` creates/signs into a Composio agent and that the flow is non-interactive - add `composio agent login <composio_agent_key>` for restoring an existing agent when the key was saved - add `composio agent whoami`, `claim`, and JSON-only `inbox` commands using the stored `~/.composio/agent.json` agent identity - guard agent flows so a regular human CLI login cannot run `composio agent ...` or overwrite itself with agent signup without logging out first - show expected agent-auth issues as a softer warning with next steps instead of the global crash-style error panel - warn and confirm before agent logout removes `~/.composio/agent.json` / `composio_agent_key`; `logout --force` skips the prompt - update `install.sh --agent` to sign up/log in as an agent after install ## Tests - `pnpm --filter @composio/cli build` - `pnpm --filter @composio/cli test -- test/src/commands/agent.cmd.test.ts` - `pnpm --filter @composio/cli test -- test/src/commands/agent.cmd.test.ts test/src/commands/logout.cmd.test.ts test/src/commands/login.cmd.test.ts` - `pnpm lint` (passes with existing warnings only) ## CI - GitHub checks are rerunning on the latest push.

Rahul Tarak committed May 1, 2026 at 15:05 UTC 8505dc330f49321479f5b16eea02a45c4a016251
16 files changed +1125 -11
install.sh
+39 -6
@@ -59,9 +59,32 @@ command -v curl >/dev/null || error 'curl is required to install Composio CLI'
59 command -v unzip >/dev/null || error 'unzip is required to install Composio CLI'
60 command -v git >/dev/null || error 'git is required to install Composio CLI'
61
62 -if [[ $# -gt 1 ]]; then
63 - error 'Too many arguments. Usage: install.sh [version-tag] (e.g. "@composio/cli@0.1.32")'
64 -fi
62 +install_agent=false
63 +version_arg=""
64 +
65 +while [[ $# -gt 0 ]]; do
66 + case "$1" in
67 + --agent)
68 + install_agent=true
69 + shift
70 + ;;
71 + -h|--help)
72 + echo 'Usage: install.sh [--agent] [version-tag] (e.g. "@composio/cli@0.1.32")'
73 + echo ' --agent After installing, sign up/log in as a Composio agent.'
74 + exit 0
75 + ;;
76 + --*)
77 + error "Unknown option: $1"
78 + ;;
79 + *)
80 + if [[ -n "$version_arg" ]]; then
81 + error 'Too many arguments. Usage: install.sh [--agent] [version-tag] (e.g. "@composio/cli@0.1.32")'
82 + fi
83 + version_arg=$1
84 + shift
85 + ;;
86 + esac
87 +done
88
89 # --- Platform detection ---
90
@@ -92,7 +115,7 @@ fi
115
116 # --- Version resolution ---
117
95 -if [[ $# = 0 ]]; then
118 +if [[ -z "$version_arg" ]]; then
119 info "Finding latest CLI release..."
120
121 version=$(git ls-remote --tags "$github_repo" "@composio/cli@*" \
@@ -107,7 +130,7 @@ if [[ $# = 0 ]]; then
130
131 info "Found latest version: $version"
132 else
110 - version=$1
133 + version=$version_arg
134 fi
135
136 # --- Download into temp directory ---
@@ -311,6 +334,12 @@ else
334 fi
335 rm -f "$install_err"
336
337 +if [[ $install_agent = true ]]; then
338 + echo
339 + info "Setting up Composio agent login..."
340 + "$exe" login --agent --no-skill-install || error 'Failed to sign up/log in as a Composio agent'
341 +fi
342 +
343 echo
344 info "To get started, run:"
345 echo
@@ -320,4 +349,8 @@ if [[ ${refresh_command:-} ]]; then
349 fi
350
351 info_bold " composio --help"
323 -info_bold " composio login"
352 +if [[ $install_agent = true ]]; then
353 + info_bold " composio agent whoami"
354 +else
355 + info_bold " composio login"
356 +fi
ts/packages/cli/src/commands/agent/agent.cmd.ts new
+17
@@ -0,0 +1,17 @@
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';
7 +
8 +export const agentCmd = Command.make('agent').pipe(
9 + Command.withDescription('Manage Composio agent identity, inbox, and handoff.'),
10 + Command.withSubcommands([
11 + agentCmd$Signup,
12 + agentCmd$Login,
13 + agentCmd$Whoami,
14 + agentCmd$Claim,
15 + agentCmd$Inbox,
16 + ])
17 +);
ts/packages/cli/src/commands/agent/commands/agent.claim.cmd.ts new
+32
@@ -0,0 +1,32 @@
1 +import { Args, Command } from '@effect/cli';
2 +import { Effect } from 'effect';
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 = Args.text({ name: 'email' }).pipe(
8 + Args.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 new
+25
@@ -0,0 +1,25 @@
1 +import { Command, Options } from '@effect/cli';
2 +import { Effect } from 'effect';
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 = Options.integer('limit').pipe(
8 + Options.withDefault(50),
9 + Options.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 new
+36
@@ -0,0 +1,36 @@
1 +import { Args, Command } from '@effect/cli';
2 +import { Effect } from 'effect';
3 +import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 +import {
5 + ensureAgentSignupAllowed,
6 + fetchAgentWhoami,
7 + loginWithAgentIdentity,
8 + safeAgentSummary,
9 + writeStoredAgentIdentity,
10 +} from 'src/services/agents';
11 +import { TerminalUI } from 'src/services/terminal-ui';
12 +
13 +const composioAgentKey = Args.text({ name: 'composio_agent_key' }).pipe(
14 + Args.withDescription('Composio agent key for an existing agent identity')
15 +);
16 +
17 +export const agentCmd$Login = Command.make('login', { composioAgentKey }).pipe(
18 + Command.withDescription('Log in with an existing Composio agent key.'),
19 + Command.withHandler(({ composioAgentKey }) =>
20 + handleAgentAuthError(
21 + Effect.gen(function* () {
22 + const ui = yield* TerminalUI;
23 +
24 + yield* ensureAgentSignupAllowed;
25 +
26 + const identity = yield* fetchAgentWhoami(composioAgentKey);
27 + const saved = yield* writeStoredAgentIdentity(identity);
28 + yield* loginWithAgentIdentity(saved);
29 +
30 + const summary = safeAgentSummary(saved);
31 + yield* ui.log.success(`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`);
32 + yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
33 + })
34 + )
35 + )
36 +);
ts/packages/cli/src/commands/agent/commands/agent.signup.cmd.ts new
+27
@@ -0,0 +1,27 @@
1 +import { Command, Options } from '@effect/cli';
2 +import { runAgentSignup } from '../../signup.cmd';
3 +
4 +const noWait = Options.boolean('no-wait').pipe(
5 + Options.withDefault(false),
6 + Options.withDescription('Start agent signup and exit without waiting for credentials')
7 +);
8 +
9 +const noLogin = Options.boolean('no-login').pipe(
10 + Options.withDefault(false),
11 + Options.withDescription('Create or verify the agent identity without logging the CLI in')
12 +);
13 +
14 +const force = Options.boolean('force').pipe(
15 + Options.withAlias('f'),
16 + Options.withDefault(false),
17 + Options.withDescription(
18 + 'Create a new agent identity even if ~/.composio/agent.json already exists'
19 + )
20 +);
21 +
22 +export const agentCmd$Signup = Command.make(
23 + 'signup',
24 + { noWait, noLogin, force },
25 + ({ noWait, noLogin, force }) =>
26 + runAgentSignup({ noWait, noLogin, force, commandLabel: 'composio agent signup' })
27 +).pipe(Command.withDescription('Sign up and optionally log in as a Composio agent.'));
ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts new
+39
@@ -0,0 +1,39 @@
1 +import { Command } from '@effect/cli';
2 +import { Effect } from 'effect';
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 + `Default 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/index.ts
+4
@@ -7,6 +7,7 @@ import { versionCmd } from './version.cmd';
7 import { upgradeCmd } from './upgrade.cmd';
8 import { whoamiCmd } from './whoami.cmd';
9 import { loginCmd } from './login.cmd';
10 +import { signupCmd } from './signup.cmd';
11 import { listenCmd } from './listen.cmd';
12 import { logoutCmd } from './logout.cmd';
13 import { runCmd } from './run.cmd';
@@ -33,6 +34,7 @@ import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/con
34 import { orgsCmd } from './orgs/orgs.cmd';
35 import { configCmd } from './config/config.cmd';
36 import { rootConnectionsCmd } from './connections/connections.cmd';
37 +import { agentCmd } from './agent/agent.cmd';
38 import { renderCommandHintGraph } from 'src/services/command-hints';
39 import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';
40 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -59,6 +61,8 @@ const ROOT_COMMANDS: ReadonlyArray<TaggedValue<Command.Command<any, any, any, an
61 tagged(upgradeCmd),
62 tagged(whoamiCmd),
63 tagged(loginCmd),
64 + tagged(signupCmd),
65 + tagged(agentCmd),
66 experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, listenCmd),
67 tagged(logoutCmd),
68 tagged(runCmd),
ts/packages/cli/src/commands/login.cmd.ts
+40 -1
@@ -14,7 +14,14 @@ import { commandHintStep } from 'src/services/command-hints';
14 import { runOrgSelection } from 'src/effects/select-org-project';
15 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
16 import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
17 +import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
18 import { APP_VERSION } from 'src/constants';
19 +import {
20 + ensureAgentSignupAllowed,
21 + getOrSignupReadyAgent,
22 + loginWithAgentIdentity,
23 + safeAgentSummary,
24 +} from 'src/services/agents';
25
26 export const noBrowser = Options.boolean('no-browser').pipe(
27 Options.withDefault(false),
@@ -54,6 +61,11 @@ const noSkillInstall = Options.boolean('no-skill-install').pipe(
61 Options.withDescription('Skip installing the composio-cli skill for Claude Code')
62 );
63
64 +const agentOpt = Options.boolean('agent').pipe(
65 + Options.withDefault(false),
66 + Options.withDescription('Sign up or log in using a Composio agent identity')
67 +);
68 +
69 const formatLoginSuccessMessage = (params: { email?: string; orgName?: string }): string => {
70 const { email, orgName } = params;
71 if (email && orgName) {
@@ -523,6 +535,7 @@ export const browserLogin = (params: {
535 * Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
536 * with --no-wait, checks once and fails if not linked.
537 * Use --user-api-key to log in directly without a browser flow, and --org to override the default org.
538 + * Use --agent to sign up or log in using a Composio agent identity.
539 * Use -y to skip org picker and use session default org.
540 *
541 * @example
@@ -534,6 +547,7 @@ export const browserLogin = (params: {
547 * composio login --key <key> --no-wait
548 * composio login --user-api-key <uak>
549 * composio login --user-api-key <uak> --org <org>
550 + * composio login --agent
551 * composio login -y
552 * ```
553 */
@@ -547,8 +561,9 @@ export const loginCmd = Command.make(
561 org: orgOpt,
562 yes: yesOpt,
563 noSkillInstall,
564 + agent: agentOpt,
565 },
551 - ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall }) =>
566 + ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>
567 Effect.gen(function* () {
568 const ui = yield* TerminalUI;
569 const ctx = yield* ComposioUserContext;
@@ -559,6 +574,12 @@ export const loginCmd = Command.make(
574 return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));
575 }
576
577 + if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {
578 + return yield* Effect.fail(
579 + new Error('`--agent` cannot be combined with browser, session, or direct-login flags.')
580 + );
581 + }
582 +
583 if (Option.isSome(org) && Option.isNone(userApiKey)) {
584 return yield* Effect.fail(new Error('`--org` requires `--user-api-key`.'));
585 }
@@ -571,6 +592,24 @@ export const loginCmd = Command.make(
592 );
593 }
594
595 + if (agent) {
596 + return yield* handleAgentAuthError(
597 + Effect.gen(function* () {
598 + yield* ensureAgentSignupAllowed;
599 + const identity = yield* getOrSignupReadyAgent();
600 + yield* loginWithAgentIdentity(identity);
601 + const summary = safeAgentSummary(identity);
602 + yield* ui.log.success(
603 + `Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`
604 + );
605 + yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
606 + if (!noSkillInstall) {
607 + yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
608 + }
609 + })
610 + );
611 + }
612 +
613 if (Option.isSome(key)) {
614 yield* loginWithKey({
615 key: key.value,
ts/packages/cli/src/commands/logout.cmd.ts
+41 -3
@@ -1,5 +1,10 @@
1 -import { Command } from '@effect/cli';
2 -import { Effect } from 'effect';
1 +import { Command, Options } from '@effect/cli';
2 +import { Effect, Option } from 'effect';
3 +import {
4 + AGENT_CONFIG_FILE_NAME,
5 + getCurrentLoggedInAgent,
6 + removeStoredAgentIdentity,
7 +} from 'src/services/agents';
8 import { ComposioUserContext } from 'src/services/user-context';
9 import { TerminalUI } from 'src/services/terminal-ui';
10
@@ -11,7 +16,13 @@ import { TerminalUI } from 'src/services/terminal-ui';
16 * composio logout <command>
17 * ```
18 */
14 -export const logoutCmd = Command.make('logout', {}, () =>
19 +const force = Options.boolean('force').pipe(
20 + Options.withAlias('f'),
21 + Options.withDefault(false),
22 + Options.withDescription('Skip confirmation prompts')
23 +);
24 +
25 +export const logoutCmd = Command.make('logout', { force }, ({ force }) =>
26 Effect.gen(function* () {
27 const ui = yield* TerminalUI;
28 const ctx = yield* ComposioUserContext;
@@ -21,8 +32,35 @@ export const logoutCmd = Command.make('logout', {}, () =>
32 return;
33 }
34
35 + const loggedInAgent = yield* getCurrentLoggedInAgent;
36 + if (Option.isSome(loggedInAgent) && !force) {
37 + yield* ui.note(
38 + [
39 + `You are logged in as a Composio agent (${loggedInAgent.value.email ?? loggedInAgent.value.slug ?? 'unknown'}).`,
40 + `Logging out will remove ~/.composio/${AGENT_CONFIG_FILE_NAME}, including the stored composio_agent_key.`,
41 + 'Save that key before continuing if you may need this exact agent again.',
42 + 'Without the key, you cannot run `composio agent login <composio_agent_key>` for this agent unless it has been claimed by a human admin.',
43 + ].join('\n'),
44 + 'Agent Logout Warning'
45 + );
46 +
47 + const confirmed = yield* ui.confirm('Remove the stored Composio agent key and log out?', {
48 + defaultValue: false,
49 + });
50 + if (!confirmed) {
51 + yield* ui.log.warn('Agent logout cancelled. No credentials were removed.');
52 + return;
53 + }
54 + }
55 +
56 yield* ctx.logout;
57
58 + if (Option.isSome(loggedInAgent)) {
59 + yield* removeStoredAgentIdentity;
60 + yield* ui.log.success('Logged out and removed stored Composio agent key.');
61 + return;
62 + }
63 +
64 yield* ui.log.success('Logged out successfully.');
65 })
66 ).pipe(Command.withDescription('Log out from the Composio SDK.'));
ts/packages/cli/src/commands/signup.cmd.ts new
+84
@@ -0,0 +1,84 @@
1 +import { Command, Options } 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';
12 +
13 +const noWait = Options.boolean('no-wait').pipe(
14 + Options.withDefault(false),
15 + Options.withDescription('Start agent signup and exit without waiting for credentials')
16 +);
17 +
18 +const noLogin = Options.boolean('no-login').pipe(
19 + Options.withDefault(false),
20 + Options.withDescription('Create or verify the agent identity without logging the CLI in')
21 +);
22 +
23 +const force = Options.boolean('force').pipe(
24 + Options.withAlias('f'),
25 + Options.withDefault(false),
26 + Options.withDescription(
27 + 'Create a new agent identity even if ~/.composio/agent.json already exists'
28 + )
29 +);
30 +
31 +export const runAgentSignup = (params: {
32 + noWait: boolean;
33 + noLogin: boolean;
34 + force: boolean;
35 + commandLabel?: string;
36 +}) =>
37 + handleAgentAuthError(
38 + Effect.gen(function* () {
39 + const ui = yield* TerminalUI;
40 + const commandLabel = params.commandLabel ?? 'composio signup';
41 +
42 + yield* ensureAgentSignupAllowed;
43 + yield* ui.intro(commandLabel);
44 + yield* ui.log.info(
45 + `${commandLabel} signs you up as a Composio agent. This flow is fully non-interactive and does not open a browser.`
46 + );
47 +
48 + const identity = yield* params.noWait
49 + ? signupAgent({ wait: false })
50 + : getOrSignupReadyAgent({ force: params.force });
51 + const summary = safeAgentSummary(identity);
52 +
53 + yield* ui.note(
54 + [
55 + `Type: agent`,
56 + `Status: ${summary.status}`,
57 + `Email: ${summary.email ?? 'unknown'}`,
58 + `Slug: ${summary.slug ?? 'unknown'}`,
59 + `Default Org ID: ${summary.org_id ?? 'pending'}`,
60 + `Project ID: ${summary.project_id ?? 'pending'}`,
61 + `Agent key: stored in ~/.composio/agent.json`,
62 + ].join('\n'),
63 + 'Composio Agent'
64 + );
65 +
66 + if (!params.noWait && !params.noLogin) {
67 + yield* loginWithAgentIdentity(identity);
68 + yield* ui.log.success('Logged in with the Composio agent identity.');
69 + } else if (params.noWait) {
70 + yield* ui.log.info('Signup is pending. Run `composio agent whoami` to poll status.');
71 + }
72 +
73 + yield* ui.output(
74 + JSON.stringify({ ...summary, logged_in: !params.noWait && !params.noLogin })
75 + );
76 + yield* ui.outro('Agent setup complete.');
77 + })
78 + );
79 +
80 +export const signupCmd = Command.make(
81 + 'signup',
82 + { noWait, noLogin, force },
83 + ({ noWait, noLogin, force }) => runAgentSignup({ noWait, noLogin, force })
84 +).pipe(Command.withDescription('Sign up and optionally log in as a Composio agent.'));
ts/packages/cli/src/commands/whoami.cmd.ts
+10
@@ -4,6 +4,7 @@ import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
4 import { ComposioUserContext } from 'src/services/user-context';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { commandHintStep } from 'src/services/command-hints';
7 +import { readStoredAgentIdentity } from 'src/services/agents';
8
9 /**
10 * CLI command to display your account information.
@@ -38,9 +39,17 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
39 const orgName = Option.map(sessionInfo, info => info.project.org.name).pipe(
40 Option.getOrUndefined
41 );
42 + const storedAgent = yield* readStoredAgentIdentity;
43 + const isStoredAgentKey = Option.match(storedAgent, {
44 + onNone: () => false,
45 + onSome: agent => agent.composio?.user_api_key === apiKey,
46 + });
47 + const accountType =
48 + isStoredAgentKey || email?.endsWith('@agent.composio.ai') ? 'agent' : 'human';
49
50 yield* ui.note(
51 [
52 + `Type: ${accountType}`,
53 `Email: ${email ?? 'unknown'}`,
54 `Default Org: ${orgName ?? 'unknown'}`,
55 `Default Org ID: ${defaultOrgId ?? 'not set'}`,
@@ -56,6 +65,7 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
65 );
66 yield* ui.output(
67 JSON.stringify({
68 + account_type: accountType,
69 email: email ?? null,
70 default_org_name: orgName ?? null,
71 default_org_id: defaultOrgId ?? null,
ts/packages/cli/src/effects/handle-agent-auth-error.ts new
+24
@@ -0,0 +1,24 @@
1 +import process from 'node:process';
2 +import { Effect } from 'effect';
3 +import { AgentAuthError } from 'src/services/agents';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +
6 +export const handleAgentAuthError = <E, R>(effect: Effect.Effect<void, E | AgentAuthError, R>) =>
7 + effect.pipe(
8 + Effect.catchIf(
9 + (error): error is AgentAuthError => error instanceof AgentAuthError,
10 + error =>
11 + Effect.gen(function* () {
12 + const ui = yield* TerminalUI;
13 + yield* ui.log.warn(error.message);
14 + if (error.nextSteps.length > 0) {
15 + yield* ui.log.info(
16 + ['Next steps:', ...error.nextSteps.map((step: string) => `- ${step}`)].join('\n')
17 + );
18 + }
19 + yield* Effect.sync(() => {
20 + process.exitCode = 1;
21 + });
22 + })
23 + )
24 + );
ts/packages/cli/src/services/agents.ts new
+327
@@ -0,0 +1,327 @@
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 + });
ts/packages/cli/test/src/commands/agent.cmd.test.ts new
+275
@@ -0,0 +1,275 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { FileSystem } from '@effect/platform';
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 { writeStoredAgentIdentity } from 'src/services/agents';
9 +import { ComposioUserContext } from 'src/services/user-context';
10 +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 +describe('CLI: composio agent', () => {
26 + afterEach(() => {
27 + vi.restoreAllMocks();
28 + process.exitCode = undefined;
29 + });
30 +
31 + layer(TestLive())(it => {
32 + it.scoped('exposes agent signup as a subcommand', () =>
33 + Effect.gen(function* () {
34 + yield* cli(['agent', '--help']);
35 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
36 +
37 + expect(output).toContain('signup');
38 + expect(output).toContain('login');
39 + expect(output).toContain('whoami');
40 + expect(output).toContain('claim');
41 + })
42 + );
43 + });
44 +
45 + layer(TestLive())(it => {
46 + it.scoped('agent signup works when the CLI is not signed in', () =>
47 + Effect.gen(function* () {
48 + vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
49 + const url =
50 + typeof requestInput === 'string'
51 + ? requestInput
52 + : requestInput instanceof URL
53 + ? requestInput.toString()
54 + : requestInput.url;
55 +
56 + if (url.includes('/api/signup')) {
57 + return new Response(JSON.stringify(agentSignupResponse), {
58 + status: 200,
59 + headers: { 'Content-Type': 'application/json' },
60 + });
61 + }
62 +
63 + return new Response(JSON.stringify({}), {
64 + status: 200,
65 + headers: { 'Content-Type': 'application/json' },
66 + });
67 + });
68 +
69 + yield* cli(['agent', 'signup']);
70 +
71 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
72 + expect(output).toContain('composio agent signup signs you up as a Composio agent');
73 + expect(output).toContain('fully non-interactive');
74 +
75 + const ctx = yield* ComposioUserContext;
76 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
77 + expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
78 +
79 + const fs = yield* FileSystem.FileSystem;
80 + const cacheDir = yield* setupCacheDir;
81 + const userConfigRaw = yield* fs.readFileString(
82 + path.join(cacheDir, constants.USER_CONFIG_FILE_NAME),
83 + 'utf8'
84 + );
85 + const agentConfigRaw = yield* fs.readFileString(path.join(cacheDir, 'agent.json'), 'utf8');
86 +
87 + expect(JSON.parse(userConfigRaw)).toMatchObject({
88 + api_key: 'uak_agent',
89 + org_id: 'org_agent',
90 + });
91 + expect(JSON.parse(agentConfigRaw)).toMatchObject({
92 + composio_agent_key: 'cak_test_agent',
93 + agent_key: 'cak_test_agent',
94 + composio: { user_api_key: 'uak_agent' },
95 + });
96 + })
97 + );
98 + });
99 +
100 + layer(TestLive())(it => {
101 + it.scoped('top-level signup makes clear it signs up an agent', () =>
102 + Effect.gen(function* () {
103 + vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
104 + const url =
105 + typeof requestInput === 'string'
106 + ? requestInput
107 + : requestInput instanceof URL
108 + ? requestInput.toString()
109 + : requestInput.url;
110 +
111 + if (url.includes('/api/signup')) {
112 + return new Response(JSON.stringify(agentSignupResponse), {
113 + status: 200,
114 + headers: { 'Content-Type': 'application/json' },
115 + });
116 + }
117 +
118 + return new Response(JSON.stringify({}), {
119 + status: 200,
120 + headers: { 'Content-Type': 'application/json' },
121 + });
122 + });
123 +
124 + yield* cli(['signup']);
125 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
126 +
127 + expect(output).toContain('composio signup signs you up as a Composio agent');
128 + })
129 + );
130 + });
131 +
132 + layer(TestLive())(it => {
133 + it.scoped('agent inbox prints only JSON', () =>
134 + Effect.gen(function* () {
135 + yield* writeStoredAgentIdentity(agentSignupResponse);
136 + vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
137 + const url =
138 + typeof requestInput === 'string'
139 + ? requestInput
140 + : requestInput instanceof URL
141 + ? requestInput.toString()
142 + : requestInput.url;
143 +
144 + if (url.includes('/api/mail')) {
145 + expect(new Headers(init?.headers).get('authorization')).toBe('Bearer cak_test_agent');
146 + return new Response(
147 + JSON.stringify({
148 + count: 1,
149 + messages: [
150 + {
151 + id: 'msg_123',
152 + from: 'person@example.com',
153 + subject: 'Hello',
154 + preview: 'Hi agent',
155 + },
156 + ],
157 + }),
158 + {
159 + status: 200,
160 + headers: { 'Content-Type': 'application/json' },
161 + }
162 + );
163 + }
164 +
165 + return new Response(JSON.stringify({}), {
166 + status: 200,
167 + headers: { 'Content-Type': 'application/json' },
168 + });
169 + });
170 +
171 + yield* cli(['agent', 'inbox']);
172 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
173 +
174 + expect(lines).toEqual([
175 + JSON.stringify({
176 + count: 1,
177 + messages: [
178 + {
179 + id: 'msg_123',
180 + from: 'person@example.com',
181 + subject: 'Hello',
182 + preview: 'Hi agent',
183 + },
184 + ],
185 + }),
186 + ]);
187 + })
188 + );
189 + });
190 +
191 + layer(TestLive())(it => {
192 + it.scoped('agent login restores an existing agent from composio_agent_key', () =>
193 + Effect.gen(function* () {
194 + vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
195 + const url =
196 + typeof requestInput === 'string'
197 + ? requestInput
198 + : requestInput instanceof URL
199 + ? requestInput.toString()
200 + : requestInput.url;
201 +
202 + if (url.includes('/api/whoami')) {
203 + expect(new Headers(init?.headers).get('authorization')).toBe('Bearer cak_existing');
204 + return new Response(
205 + JSON.stringify({
206 + ...agentSignupResponse,
207 + composio_agent_key: 'cak_existing',
208 + agent_key: 'cak_existing',
209 + }),
210 + {
211 + status: 200,
212 + headers: { 'Content-Type': 'application/json' },
213 + }
214 + );
215 + }
216 +
217 + return new Response(JSON.stringify({}), {
218 + status: 200,
219 + headers: { 'Content-Type': 'application/json' },
220 + });
221 + });
222 +
223 + yield* cli(['agent', 'login', 'cak_existing']);
224 +
225 + const ctx = yield* ComposioUserContext;
226 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
227 + expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
228 +
229 + const fs = yield* FileSystem.FileSystem;
230 + const cacheDir = yield* setupCacheDir;
231 + const agentConfigRaw = yield* fs.readFileString(path.join(cacheDir, 'agent.json'), 'utf8');
232 + expect(JSON.parse(agentConfigRaw)).toMatchObject({
233 + composio_agent_key: 'cak_existing',
234 + agent_key: 'cak_existing',
235 + composio: { user_api_key: 'uak_agent' },
236 + });
237 + })
238 + );
239 + });
240 +
241 + layer(TestLive({ fixture: 'user-config-example' }))(it => {
242 + it.scoped('agent commands show a soft auth warning when signed in as a human user', () =>
243 + Effect.gen(function* () {
244 + yield* cli(['agent', 'whoami']);
245 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
246 +
247 + expect(output).toContain('currently signed in to Composio as a regular user');
248 + expect(output).toContain('composio agent login <composio_agent_key>');
249 + expect(process.exitCode).toBe(1);
250 + })
251 + );
252 +
253 + it.scoped('agent signup shows a soft auth warning when signed in as a human user', () =>
254 + Effect.gen(function* () {
255 + yield* cli(['agent', 'signup']);
256 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
257 +
258 + expect(output).toContain('currently signed in to Composio as a regular user');
259 + expect(output).toContain('composio signup');
260 + expect(process.exitCode).toBe(1);
261 + })
262 + );
263 +
264 + it.scoped('agent login shows a soft auth warning when signed in as a human user', () =>
265 + Effect.gen(function* () {
266 + yield* cli(['agent', 'login', 'cak_existing']);
267 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
268 +
269 + expect(output).toContain('currently signed in to Composio as a regular user');
270 + expect(output).toContain('composio logout');
271 + expect(process.exitCode).toBe(1);
272 + })
273 + );
274 + });
275 +});
ts/packages/cli/test/src/commands/logout.cmd.test.ts
+105 -1
@@ -1,10 +1,67 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect, Option } from 'effect';
2 +import { FileSystem } from '@effect/platform';
3 +import { ConfigProvider, Console, Effect, Option } from 'effect';
4 +import path from 'node:path';
5 +import * as constants from 'src/constants';
6 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { UserDataWithDefaults } from 'src/models/user-data';
8 +import { writeStoredAgentIdentity } from 'src/services/agents';
9 import { extendConfigProvider } from 'src/services/config';
10 +import { TerminalUI } from 'src/services/terminal-ui';
11 import { ComposioUserContext } from 'src/services/user-context';
12 import { cli, TestLive, MockConsole } from 'test/__utils__';
13
14 +const terminalUIWithConfirm = (confirmed: boolean) =>
15 + TerminalUI.of({
16 + output: data => Console.log(data),
17 + intro: title => Console.log(`-- ${title} --`),
18 + outro: message => Console.log(`-- ${message} --`),
19 + log: {
20 + info: message => Console.log(message),
21 + success: message => Console.log(message),
22 + warn: message => Console.warn(message),
23 + error: message => Console.error(message),
24 + step: message => Console.log(message),
25 + message: message => Console.log(message),
26 + },
27 + note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
28 + select: (_message, options) => Effect.succeed(options[0]!.value),
29 + confirm: () => Effect.succeed(confirmed),
30 + withSpinner: (message, effect, options) =>
31 + Effect.gen(function* () {
32 + const result = yield* effect;
33 + const successMsg =
34 + typeof options?.successMessage === 'function'
35 + ? options.successMessage(result)
36 + : (options?.successMessage ?? message);
37 + yield* Console.log(successMsg);
38 + return result;
39 + }),
40 + useMakeSpinner: (_message, use) =>
41 + use({
42 + message: (_msg: string) => Effect.void,
43 + stop: (msg?: string) => (msg ? Console.log(msg) : Effect.void),
44 + error: (msg?: string) => (msg ? Console.error(msg) : Effect.void),
45 + }),
46 + });
47 +
48 +const setupLoggedInAgent = Effect.gen(function* () {
49 + const ctx = yield* ComposioUserContext;
50 + yield* writeStoredAgentIdentity({
51 + status: 'READY',
52 + slug: 'test-agent',
53 + email: 'test-agent@agent.composio.ai',
54 + composio_agent_key: 'cak_test_agent',
55 + composio: {
56 + org_id: 'org_agent',
57 + project_id: 'proj_agent',
58 + user_api_key: 'uak_agent',
59 + },
60 + });
61 + yield* ctx.login('uak_agent', 'org_agent');
62 + return ctx;
63 +});
64 +
65 describe('CLI: composio logout', () => {
66 describe('[When] logged out', () => {
67 layer(TestLive())(it => {
@@ -71,4 +128,51 @@ describe('CLI: composio logout', () => {
128 );
129 });
130 });
131 +
132 + describe('[When] logged in as an agent', () => {
133 + layer(TestLive({ terminalUI: terminalUIWithConfirm(false) }))(it => {
134 + it.scoped('[Then] cancelling keeps user and agent credentials', () =>
135 + Effect.gen(function* () {
136 + const ctx = yield* setupLoggedInAgent;
137 +
138 + yield* cli(['logout']);
139 +
140 + const fs = yield* FileSystem.FileSystem;
141 + const cacheDir = yield* setupCacheDir;
142 + const agentConfigExists = yield* fs.exists(path.join(cacheDir, 'agent.json'));
143 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
144 +
145 + expect(output).toContain('Agent Logout Warning');
146 + expect(output).toContain('composio_agent_key');
147 + expect(output).toContain('Agent logout cancelled');
148 + expect(ctx.isLoggedIn()).toBeTruthy();
149 + expect(agentConfigExists).toBe(true);
150 + })
151 + );
152 + });
153 +
154 + layer(TestLive())(it => {
155 + it.scoped('[Then] --force removes user and agent credentials', () =>
156 + Effect.gen(function* () {
157 + const ctx = yield* setupLoggedInAgent;
158 +
159 + yield* cli(['logout', '--force']);
160 +
161 + const fs = yield* FileSystem.FileSystem;
162 + const cacheDir = yield* setupCacheDir;
163 + const agentConfigExists = yield* fs.exists(path.join(cacheDir, 'agent.json'));
164 + const userConfigRaw = yield* fs.readFileString(
165 + path.join(cacheDir, constants.USER_CONFIG_FILE_NAME),
166 + 'utf8'
167 + );
168 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
169 +
170 + expect(output).toContain('removed stored Composio agent key');
171 + expect(ctx.isLoggedIn()).toBeFalsy();
172 + expect(agentConfigExists).toBe(false);
173 + expect(JSON.parse(userConfigRaw)).toHaveProperty('api_key', null);
174 + })
175 + );
176 + });
177 + });
178 });