Skip to content

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)

Rahul Tarak8505dc330f49
diff --git a/install.sh b/install.sh
index 0d24bd0e5..b2a8774c6 100755
--- a/install.sh
+++ b/install.sh
@@ -59,9 +59,32 @@ command -v curl >/dev/null || error 'curl is required to install Composio CLI'
command -v unzip >/dev/null || error 'unzip is required to install Composio CLI'
command -v git >/dev/null || error 'git is required to install Composio CLI'
-if [[ $# -gt 1 ]]; then
- error 'Too many arguments. Usage: install.sh [version-tag] (e.g. "@composio/[email protected]")'
-fi
+install_agent=false
+version_arg=""
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --agent)
+ install_agent=true
+ shift
+ ;;
+ -h|--help)
+ echo 'Usage: install.sh [--agent] [version-tag] (e.g. "@composio/[email protected]")'
+ echo ' --agent After installing, sign up/log in as a Composio agent.'
+ exit 0
+ ;;
+ --*)
+ error "Unknown option: $1"
+ ;;
+ *)
+ if [[ -n "$version_arg" ]]; then
+ error 'Too many arguments. Usage: install.sh [--agent] [version-tag] (e.g. "@composio/[email protected]")'
+ fi
+ version_arg=$1
+ shift
+ ;;
+ esac
+done
# --- Platform detection ---
@@ -92,7 +115,7 @@ fi
# --- Version resolution ---
-if [[ $# = 0 ]]; then
+if [[ -z "$version_arg" ]]; then
info "Finding latest CLI release..."
version=$(git ls-remote --tags "$github_repo" "@composio/cli@*" \
@@ -107,7 +130,7 @@ if [[ $# = 0 ]]; then
info "Found latest version: $version"
else
- version=$1
+ version=$version_arg
fi
# --- Download into temp directory ---
@@ -311,6 +334,12 @@ else
fi
rm -f "$install_err"
+if [[ $install_agent = true ]]; then
+ echo
+ info "Setting up Composio agent login..."
+ "$exe" login --agent --no-skill-install || error 'Failed to sign up/log in as a Composio agent'
+fi
+
echo
info "To get started, run:"
echo
@@ -320,4 +349,8 @@ if [[ ${refresh_command:-} ]]; then
fi
info_bold " composio --help"
-info_bold " composio login"
+if [[ $install_agent = true ]]; then
+ info_bold " composio agent whoami"
+else
+ info_bold " composio login"
+fi
diff --git a/ts/packages/cli/src/commands/agent/agent.cmd.ts b/ts/packages/cli/src/commands/agent/agent.cmd.ts
new file mode 100644
index 000000000..9dde5a948
--- /dev/null
+++ b/ts/packages/cli/src/commands/agent/agent.cmd.ts
@@ -0,0 +1,17 @@
+import { Command } from '@effect/cli';
+import { agentCmd$Claim } from './commands/agent.claim.cmd';
+import { agentCmd$Inbox } from './commands/agent.inbox.cmd';
+import { agentCmd$Login } from './commands/agent.login.cmd';
+import { agentCmd$Signup } from './commands/agent.signup.cmd';
+import { agentCmd$Whoami } from './commands/agent.whoami.cmd';
+
+export const agentCmd = Command.make('agent').pipe(
+ Command.withDescription('Manage Composio agent identity, inbox, and handoff.'),
+ Command.withSubcommands([
+ agentCmd$Signup,
+ agentCmd$Login,
+ agentCmd$Whoami,
+ agentCmd$Claim,
+ agentCmd$Inbox,
+ ])
+);
diff --git a/ts/packages/cli/src/commands/agent/commands/agent.claim.cmd.ts b/ts/packages/cli/src/commands/agent/commands/agent.claim.cmd.ts
new file mode 100644
index 000000000..052d549a6
--- /dev/null
+++ b/ts/packages/cli/src/commands/agent/commands/agent.claim.cmd.ts
@@ -0,0 +1,32 @@
+import { Args, Command } from '@effect/cli';
+import { Effect } from 'effect';
+import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
+import { claimAgent, resolveStoredAgentKey } from 'src/services/agents';
+import { TerminalUI } from 'src/services/terminal-ui';
+
+const email = Args.text({ name: 'email' }).pipe(
+ Args.withDescription('Human email address to invite as an admin for this agent org')
+);
+
+export const agentCmd$Claim = Command.make('claim', { email }).pipe(
+ Command.withDescription('Invite a human admin to claim this agent org.'),
+ Command.withHandler(({ email }) =>
+ handleAgentAuthError(
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const agentKey = yield* resolveStoredAgentKey;
+ const result = yield* claimAgent({ agentKey, email });
+
+ yield* ui.log.success(`Sent Composio org claim invite to ${result.email ?? email}.`);
+ yield* ui.output(
+ JSON.stringify({
+ status: result.status ?? 'invited',
+ email: result.email ?? email,
+ org_id: result.org_id ?? null,
+ invite_code: result.invite_code ?? null,
+ })
+ );
+ })
+ )
+ )
+);
diff --git a/ts/packages/cli/src/commands/agent/commands/agent.inbox.cmd.ts b/ts/packages/cli/src/commands/agent/commands/agent.inbox.cmd.ts
new file mode 100644
index 000000000..e61e6c0ec
--- /dev/null
+++ b/ts/packages/cli/src/commands/agent/commands/agent.inbox.cmd.ts
@@ -0,0 +1,25 @@
+import { Command, Options } from '@effect/cli';
+import { Effect } from 'effect';
+import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
+import { fetchAgentInbox, resolveStoredAgentKey } from 'src/services/agents';
+import { TerminalUI } from 'src/services/terminal-ui';
+
+const limit = Options.integer('limit').pipe(
+ Options.withDefault(50),
+ Options.withDescription('Maximum number of inbox messages to fetch')
+);
+
+export const agentCmd$Inbox = Command.make('inbox', { limit }).pipe(
+ Command.withDescription('Read the stored Composio agent inbox.'),
+ Command.withHandler(({ limit }) =>
+ handleAgentAuthError(
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const agentKey = yield* resolveStoredAgentKey;
+ const inbox = yield* fetchAgentInbox({ agentKey, limit });
+
+ yield* ui.output(JSON.stringify(inbox), { force: true });
+ })
+ )
+ )
+);
diff --git a/ts/packages/cli/src/commands/agent/commands/agent.login.cmd.ts b/ts/packages/cli/src/commands/agent/commands/agent.login.cmd.ts
new file mode 100644
index 000000000..7c7fb525c
--- /dev/null
+++ b/ts/packages/cli/src/commands/agent/commands/agent.login.cmd.ts
@@ -0,0 +1,36 @@
+import { Args, Command } from '@effect/cli';
+import { Effect } from 'effect';
+import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
+import {
+ ensureAgentSignupAllowed,
+ fetchAgentWhoami,
+ loginWithAgentIdentity,
+ safeAgentSummary,
+ writeStoredAgentIdentity,
+} from 'src/services/agents';
+import { TerminalUI } from 'src/services/terminal-ui';
+
+const composioAgentKey = Args.text({ name: 'composio_agent_key' }).pipe(
+ Args.withDescription('Composio agent key for an existing agent identity')
+);
+
+export const agentCmd$Login = Command.make('login', { composioAgentKey }).pipe(
+ Command.withDescription('Log in with an existing Composio agent key.'),
+ Command.withHandler(({ composioAgentKey }) =>
+ handleAgentAuthError(
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+
+ yield* ensureAgentSignupAllowed;
+
+ const identity = yield* fetchAgentWhoami(composioAgentKey);
+ const saved = yield* writeStoredAgentIdentity(identity);
+ yield* loginWithAgentIdentity(saved);
+
+ const summary = safeAgentSummary(saved);
+ yield* ui.log.success(`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`);
+ yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
+ })
+ )
+ )
+);
diff --git a/ts/packages/cli/src/commands/agent/commands/agent.signup.cmd.ts b/ts/packages/cli/src/commands/agent/commands/agent.signup.cmd.ts
new file mode 100644
index 000000000..166479b9d
--- /dev/null
+++ b/ts/packages/cli/src/commands/agent/commands/agent.signup.cmd.ts
@@ -0,0 +1,27 @@
+import { Command, Options } from '@effect/cli';
+import { runAgentSignup } from '../../signup.cmd';
+
+const noWait = Options.boolean('no-wait').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Start agent signup and exit without waiting for credentials')
+);
+
+const noLogin = Options.boolean('no-login').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Create or verify the agent identity without logging the CLI in')
+);
+
+const force = Options.boolean('force').pipe(
+ Options.withAlias('f'),
+ Options.withDefault(false),
+ Options.withDescription(
+ 'Create a new agent identity even if ~/.composio/agent.json already exists'
+ )
+);
+
+export const agentCmd$Signup = Command.make(
+ 'signup',
+ { noWait, noLogin, force },
+ ({ noWait, noLogin, force }) =>
+ runAgentSignup({ noWait, noLogin, force, commandLabel: 'composio agent signup' })
+).pipe(Command.withDescription('Sign up and optionally log in as a Composio agent.'));
diff --git a/ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts b/ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts
new file mode 100644
index 000000000..759358414
--- /dev/null
+++ b/ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts
@@ -0,0 +1,39 @@
+import { Command } from '@effect/cli';
+import { Effect } from 'effect';
+import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
+import {
+ fetchAgentWhoami,
+ resolveStoredAgentKey,
+ safeAgentSummary,
+ writeStoredAgentIdentity,
+} from 'src/services/agents';
+import { TerminalUI } from 'src/services/terminal-ui';
+
+export const agentCmd$Whoami = Command.make('whoami', {}).pipe(
+ Command.withDescription('Show the stored Composio agent identity.'),
+ Command.withHandler(() =>
+ handleAgentAuthError(
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const agentKey = yield* resolveStoredAgentKey;
+ const identity = yield* fetchAgentWhoami(agentKey);
+ const saved = yield* writeStoredAgentIdentity(identity);
+ const summary = safeAgentSummary(saved);
+
+ yield* ui.note(
+ [
+ `Type: agent`,
+ `Status: ${summary.status}`,
+ `Email: ${summary.email ?? 'unknown'}`,
+ `Slug: ${summary.slug ?? 'unknown'}`,
+ `Default Org ID: ${summary.org_id ?? 'pending'}`,
+ `Project ID: ${summary.project_id ?? 'pending'}`,
+ `Claimed By: ${summary.claimed_by ?? 'not claimed'}`,
+ ].join('\n'),
+ 'Composio Agent'
+ );
+ yield* ui.output(JSON.stringify(summary));
+ })
+ )
+ )
+);
diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.ts
index 3b9d60a69..603a11ed6 100644
--- a/ts/packages/cli/src/commands/index.ts
+++ b/ts/packages/cli/src/commands/index.ts
@@ -7,6 +7,7 @@ import { versionCmd } from './version.cmd';
import { upgradeCmd } from './upgrade.cmd';
import { whoamiCmd } from './whoami.cmd';
import { loginCmd } from './login.cmd';
+import { signupCmd } from './signup.cmd';
import { listenCmd } from './listen.cmd';
import { logoutCmd } from './logout.cmd';
import { runCmd } from './run.cmd';
@@ -33,6 +34,7 @@ import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/con
import { orgsCmd } from './orgs/orgs.cmd';
import { configCmd } from './config/config.cmd';
import { rootConnectionsCmd } from './connections/connections.cmd';
+import { agentCmd } from './agent/agent.cmd';
import { renderCommandHintGraph } from 'src/services/command-hints';
import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';
import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -59,6 +61,8 @@ const ROOT_COMMANDS: ReadonlyArray<TaggedValue<Command.Command<any, any, any, an
tagged(upgradeCmd),
tagged(whoamiCmd),
tagged(loginCmd),
+ tagged(signupCmd),
+ tagged(agentCmd),
experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, listenCmd),
tagged(logoutCmd),
tagged(runCmd),
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index 49e88736a..5a0ee15a9 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -14,7 +14,14 @@ import { commandHintStep } from 'src/services/command-hints';
import { runOrgSelection } from 'src/effects/select-org-project';
import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
+import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
import { APP_VERSION } from 'src/constants';
+import {
+ ensureAgentSignupAllowed,
+ getOrSignupReadyAgent,
+ loginWithAgentIdentity,
+ safeAgentSummary,
+} from 'src/services/agents';
export const noBrowser = Options.boolean('no-browser').pipe(
Options.withDefault(false),
@@ -54,6 +61,11 @@ const noSkillInstall = Options.boolean('no-skill-install').pipe(
Options.withDescription('Skip installing the composio-cli skill for Claude Code')
);
+const agentOpt = Options.boolean('agent').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Sign up or log in using a Composio agent identity')
+);
+
const formatLoginSuccessMessage = (params: { email?: string; orgName?: string }): string => {
const { email, orgName } = params;
if (email && orgName) {
@@ -523,6 +535,7 @@ export const browserLogin = (params: {
* Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
* with --no-wait, checks once and fails if not linked.
* Use --user-api-key to log in directly without a browser flow, and --org to override the default org.
+ * Use --agent to sign up or log in using a Composio agent identity.
* Use -y to skip org picker and use session default org.
*
* @example
@@ -534,6 +547,7 @@ export const browserLogin = (params: {
* composio login --key <key> --no-wait
* composio login --user-api-key <uak>
* composio login --user-api-key <uak> --org <org>
+ * composio login --agent
* composio login -y
* ```
*/
@@ -547,8 +561,9 @@ export const loginCmd = Command.make(
org: orgOpt,
yes: yesOpt,
noSkillInstall,
+ agent: agentOpt,
},
- ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall }) =>
+ ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
const ctx = yield* ComposioUserContext;
@@ -559,6 +574,12 @@ export const loginCmd = Command.make(
return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));
}
+ if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {
+ return yield* Effect.fail(
+ new Error('`--agent` cannot be combined with browser, session, or direct-login flags.')
+ );
+ }
+
if (Option.isSome(org) && Option.isNone(userApiKey)) {
return yield* Effect.fail(new Error('`--org` requires `--user-api-key`.'));
}
@@ -571,6 +592,24 @@ export const loginCmd = Command.make(
);
}
+ if (agent) {
+ return yield* handleAgentAuthError(
+ Effect.gen(function* () {
+ yield* ensureAgentSignupAllowed;
+ const identity = yield* getOrSignupReadyAgent();
+ yield* loginWithAgentIdentity(identity);
+ const summary = safeAgentSummary(identity);
+ yield* ui.log.success(
+ `Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`
+ );
+ yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
+ if (!noSkillInstall) {
+ yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
+ }
+ })
+ );
+ }
+
if (Option.isSome(key)) {
yield* loginWithKey({
key: key.value,
diff --git a/ts/packages/cli/src/commands/logout.cmd.ts b/ts/packages/cli/src/commands/logout.cmd.ts
index 28f462e53..d7d000b0d 100644
--- a/ts/packages/cli/src/commands/logout.cmd.ts
+++ b/ts/packages/cli/src/commands/logout.cmd.ts
@@ -1,5 +1,10 @@
-import { Command } from '@effect/cli';
-import { Effect } from 'effect';
+import { Command, Options } from '@effect/cli';
+import { Effect, Option } from 'effect';
+import {
+ AGENT_CONFIG_FILE_NAME,
+ getCurrentLoggedInAgent,
+ removeStoredAgentIdentity,
+} from 'src/services/agents';
import { ComposioUserContext } from 'src/services/user-context';
import { TerminalUI } from 'src/services/terminal-ui';
@@ -11,7 +16,13 @@ import { TerminalUI } from 'src/services/terminal-ui';
* composio logout <command>
* ```
*/
-export const logoutCmd = Command.make('logout', {}, () =>
+const force = Options.boolean('force').pipe(
+ Options.withAlias('f'),
+ Options.withDefault(false),
+ Options.withDescription('Skip confirmation prompts')
+);
+
+export const logoutCmd = Command.make('logout', { force }, ({ force }) =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
const ctx = yield* ComposioUserContext;
@@ -21,8 +32,35 @@ export const logoutCmd = Command.make('logout', {}, () =>
return;
}
+ const loggedInAgent = yield* getCurrentLoggedInAgent;
+ if (Option.isSome(loggedInAgent) && !force) {
+ yield* ui.note(
+ [
+ `You are logged in as a Composio agent (${loggedInAgent.value.email ?? loggedInAgent.value.slug ?? 'unknown'}).`,
+ `Logging out will remove ~/.composio/${AGENT_CONFIG_FILE_NAME}, including the stored composio_agent_key.`,
+ 'Save that key before continuing if you may need this exact agent again.',
+ 'Without the key, you cannot run `composio agent login <composio_agent_key>` for this agent unless it has been claimed by a human admin.',
+ ].join('\n'),
+ 'Agent Logout Warning'
+ );
+
+ const confirmed = yield* ui.confirm('Remove the stored Composio agent key and log out?', {
+ defaultValue: false,
+ });
+ if (!confirmed) {
+ yield* ui.log.warn('Agent logout cancelled. No credentials were removed.');
+ return;
+ }
+ }
+
yield* ctx.logout;
+ if (Option.isSome(loggedInAgent)) {
+ yield* removeStoredAgentIdentity;
+ yield* ui.log.success('Logged out and removed stored Composio agent key.');
+ return;
+ }
+
yield* ui.log.success('Logged out successfully.');
})
).pipe(Command.withDescription('Log out from the Composio SDK.'));
diff --git a/ts/packages/cli/src/commands/signup.cmd.ts b/ts/packages/cli/src/commands/signup.cmd.ts
new file mode 100644
index 000000000..29debd27e
--- /dev/null
+++ b/ts/packages/cli/src/commands/signup.cmd.ts
@@ -0,0 +1,84 @@
+import { Command, Options } from '@effect/cli';
+import { Effect } from 'effect';
+import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
+import {
+ ensureAgentSignupAllowed,
+ getOrSignupReadyAgent,
+ loginWithAgentIdentity,
+ safeAgentSummary,
+ signupAgent,
+} from 'src/services/agents';
+import { TerminalUI } from 'src/services/terminal-ui';
+
+const noWait = Options.boolean('no-wait').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Start agent signup and exit without waiting for credentials')
+);
+
+const noLogin = Options.boolean('no-login').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Create or verify the agent identity without logging the CLI in')
+);
+
+const force = Options.boolean('force').pipe(
+ Options.withAlias('f'),
+ Options.withDefault(false),
+ Options.withDescription(
+ 'Create a new agent identity even if ~/.composio/agent.json already exists'
+ )
+);
+
+export const runAgentSignup = (params: {
+ noWait: boolean;
+ noLogin: boolean;
+ force: boolean;
+ commandLabel?: string;
+}) =>
+ handleAgentAuthError(
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const commandLabel = params.commandLabel ?? 'composio signup';
+
+ yield* ensureAgentSignupAllowed;
+ yield* ui.intro(commandLabel);
+ yield* ui.log.info(
+ `${commandLabel} signs you up as a Composio agent. This flow is fully non-interactive and does not open a browser.`
+ );
+
+ const identity = yield* params.noWait
+ ? signupAgent({ wait: false })
+ : getOrSignupReadyAgent({ force: params.force });
+ const summary = safeAgentSummary(identity);
+
+ yield* ui.note(
+ [
+ `Type: agent`,
+ `Status: ${summary.status}`,
+ `Email: ${summary.email ?? 'unknown'}`,
+ `Slug: ${summary.slug ?? 'unknown'}`,
+ `Default Org ID: ${summary.org_id ?? 'pending'}`,
+ `Project ID: ${summary.project_id ?? 'pending'}`,
+ `Agent key: stored in ~/.composio/agent.json`,
+ ].join('\n'),
+ 'Composio Agent'
+ );
+
+ if (!params.noWait && !params.noLogin) {
+ yield* loginWithAgentIdentity(identity);
+ yield* ui.log.success('Logged in with the Composio agent identity.');
+ } else if (params.noWait) {
+ yield* ui.log.info('Signup is pending. Run `composio agent whoami` to poll status.');
+ }
+
+ yield* ui.output(
+ JSON.stringify({ ...summary, logged_in: !params.noWait && !params.noLogin })
+ );
+ yield* ui.outro('Agent setup complete.');
+ })
+ );
+
+export const signupCmd = Command.make(
+ 'signup',
+ { noWait, noLogin, force },
+ ({ noWait, noLogin, force }) => runAgentSignup({ noWait, noLogin, force })
+).pipe(Command.withDescription('Sign up and optionally log in as a Composio agent.'));
diff --git a/ts/packages/cli/src/commands/whoami.cmd.ts b/ts/packages/cli/src/commands/whoami.cmd.ts
index 2614fcdb6..06857837b 100644
--- a/ts/packages/cli/src/commands/whoami.cmd.ts
+++ b/ts/packages/cli/src/commands/whoami.cmd.ts
@@ -4,6 +4,7 @@ import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
import { ComposioUserContext } from 'src/services/user-context';
import { TerminalUI } from 'src/services/terminal-ui';
import { commandHintStep } from 'src/services/command-hints';
+import { readStoredAgentIdentity } from 'src/services/agents';
/**
* CLI command to display your account information.
@@ -38,9 +39,17 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
const orgName = Option.map(sessionInfo, info => info.project.org.name).pipe(
Option.getOrUndefined
);
+ const storedAgent = yield* readStoredAgentIdentity;
+ const isStoredAgentKey = Option.match(storedAgent, {
+ onNone: () => false,
+ onSome: agent => agent.composio?.user_api_key === apiKey,
+ });
+ const accountType =
+ isStoredAgentKey || email?.endsWith('@agent.composio.ai') ? 'agent' : 'human';
yield* ui.note(
[
+ `Type: ${accountType}`,
`Email: ${email ?? 'unknown'}`,
`Default Org: ${orgName ?? 'unknown'}`,
`Default Org ID: ${defaultOrgId ?? 'not set'}`,
@@ -56,6 +65,7 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
);
yield* ui.output(
JSON.stringify({
+ account_type: accountType,
email: email ?? null,
default_org_name: orgName ?? null,
default_org_id: defaultOrgId ?? null,
diff --git a/ts/packages/cli/src/effects/handle-agent-auth-error.ts b/ts/packages/cli/src/effects/handle-agent-auth-error.ts
new file mode 100644
index 000000000..757131a2a
--- /dev/null
+++ b/ts/packages/cli/src/effects/handle-agent-auth-error.ts
@@ -0,0 +1,24 @@
+import process from 'node:process';
+import { Effect } from 'effect';
+import { AgentAuthError } from 'src/services/agents';
+import { TerminalUI } from 'src/services/terminal-ui';
+
+export const handleAgentAuthError = <E, R>(effect: Effect.Effect<void, E | AgentAuthError, R>) =>
+ effect.pipe(
+ Effect.catchIf(
+ (error): error is AgentAuthError => error instanceof AgentAuthError,
+ error =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ yield* ui.log.warn(error.message);
+ if (error.nextSteps.length > 0) {
+ yield* ui.log.info(
+ ['Next steps:', ...error.nextSteps.map((step: string) => `- ${step}`)].join('\n')
+ );
+ }
+ yield* Effect.sync(() => {
+ process.exitCode = 1;
+ });
+ })
+ )
+ );
diff --git a/ts/packages/cli/src/services/agents.ts b/ts/packages/cli/src/services/agents.ts
new file mode 100644
index 000000000..6844ae982
--- /dev/null
+++ b/ts/packages/cli/src/services/agents.ts
@@ -0,0 +1,327 @@
+import { FileSystem } from '@effect/platform';
+import { Data, Effect, Option } from 'effect';
+import path from 'node:path';
+import { setupCacheDir } from 'src/effects/setup-cache-dir';
+import { ComposioUserContext } from 'src/services/user-context';
+import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
+
+export const AGENT_CONFIG_FILE_NAME = 'agent.json';
+export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';
+
+export type AgentStatus = 'READY' | 'PENDING' | 'UNKNOWN';
+
+export interface AgentComposioCredentials {
+ readonly member_id?: string;
+ readonly org_id?: string;
+ readonly project_id?: string;
+ readonly api_key?: string;
+ readonly user_api_key?: string;
+}
+
+export interface AgentIdentity {
+ readonly status?: string;
+ readonly request_id?: string;
+ readonly slug?: string;
+ readonly email?: string;
+ readonly agent_key?: string;
+ readonly composio_agent_key?: string;
+ readonly claimed_by?: string | null;
+ readonly claimed_at?: string | null;
+ readonly composio?: AgentComposioCredentials;
+ readonly [key: string]: unknown;
+}
+
+export interface AgentMailMessage {
+ readonly id?: string;
+ readonly thread_id?: string;
+ readonly from?: string;
+ readonly to?: string;
+ readonly subject?: string;
+ readonly preview?: string;
+ readonly received_at?: string;
+ readonly [key: string]: unknown;
+}
+
+export interface AgentMailResponse {
+ readonly count?: number;
+ readonly messages?: ReadonlyArray<AgentMailMessage>;
+ readonly [key: string]: unknown;
+}
+
+export interface AgentClaimResponse {
+ readonly status?: string;
+ readonly email?: string;
+ readonly org_id?: string;
+ readonly invite_code?: string;
+ readonly [key: string]: unknown;
+}
+
+export class AgentAuthError extends Data.TaggedError('services/AgentAuthError')<{
+ readonly message: string;
+ readonly nextSteps: ReadonlyArray<string>;
+}> {}
+
+const agentsBaseURL = (): string =>
+ (process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, '');
+
+const asRecord = (value: unknown): Record<string, unknown> =>
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+
+const readJson = (value: string): unknown => JSON.parse(value) as unknown;
+
+export const normalizeAgentStatus = (status: string | undefined): AgentStatus => {
+ const normalized = status?.trim().toUpperCase();
+ if (normalized === 'READY') return 'READY';
+ if (normalized === 'PENDING') return 'PENDING';
+ return 'UNKNOWN';
+};
+
+export const getAgentKey = (identity: AgentIdentity): string | undefined => {
+ if (typeof identity.composio_agent_key === 'string') return identity.composio_agent_key;
+ if (typeof identity.agent_key === 'string') return identity.agent_key;
+ return undefined;
+};
+
+export const isAgentIdentityForApiKey = (identity: AgentIdentity, apiKey: string): boolean =>
+ Boolean(getAgentKey(identity) && identity.composio?.user_api_key === apiKey);
+
+export const normalizeAgentIdentity = (
+ payload: unknown,
+ fallbackAgentKey?: string
+): AgentIdentity => {
+ const record = asRecord(payload);
+ const agentKey =
+ (typeof record.composio_agent_key === 'string' ? record.composio_agent_key : undefined) ??
+ (typeof record.agent_key === 'string' ? record.agent_key : undefined) ??
+ fallbackAgentKey;
+
+ const normalized: Record<string, unknown> = { ...record };
+ if (agentKey) {
+ normalized.agent_key = agentKey;
+ normalized.composio_agent_key = agentKey;
+ }
+
+ return normalized as AgentIdentity;
+};
+
+export const safeAgentSummary = (identity: AgentIdentity) => ({
+ account_type: 'agent' as const,
+ status: normalizeAgentStatus(identity.status),
+ slug: identity.slug ?? null,
+ email: identity.email ?? null,
+ org_id: identity.composio?.org_id ?? null,
+ project_id: identity.composio?.project_id ?? null,
+ member_id: identity.composio?.member_id ?? null,
+ claimed_by: identity.claimed_by ?? null,
+ claimed_at: identity.claimed_at ?? null,
+});
+
+export const agentConfigPath = Effect.gen(function* () {
+ const cacheDir = yield* setupCacheDir;
+ return path.join(cacheDir, AGENT_CONFIG_FILE_NAME);
+});
+
+export const readStoredAgentIdentity = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const configPath = yield* agentConfigPath;
+
+ const exists = yield* fs.exists(configPath);
+ if (!exists) return Option.none<AgentIdentity>();
+
+ return yield* fs.readFileString(configPath, 'utf8').pipe(
+ Effect.map(raw => Option.some(normalizeAgentIdentity(readJson(raw)))),
+ Effect.catchAll(error =>
+ Effect.gen(function* () {
+ yield* Effect.logDebug('Failed to read agent identity:', error);
+ return Option.none<AgentIdentity>();
+ })
+ )
+ );
+});
+
+export const writeStoredAgentIdentity = (identity: AgentIdentity) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const configPath = yield* agentConfigPath;
+ const normalized = normalizeAgentIdentity(identity);
+ yield* fs.writeFileString(configPath, `${JSON.stringify(normalized, null, 2)}\n`);
+ return normalized;
+ });
+
+export const removeStoredAgentIdentity = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const configPath = yield* agentConfigPath;
+ yield* fs.remove(configPath).pipe(Effect.catchAll(() => Effect.void));
+});
+
+const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>
+ Effect.tryPromise({
+ try: async () => {
+ const response = await fetch(`${agentsBaseURL()}${pathname}`, {
+ redirect: 'error',
+ ...init,
+ headers: {
+ Accept: 'application/json',
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
+ ...(init.headers ?? {}),
+ },
+ });
+
+ const text = await response.text();
+ const payload = text ? (JSON.parse(text) as unknown) : {};
+ if (!response.ok) {
+ const message =
+ typeof asRecord(payload).message === 'string'
+ ? (asRecord(payload).message as string)
+ : `agents.composio.dev request failed with HTTP ${response.status}`;
+ throw new Error(message);
+ }
+ return payload;
+ },
+ catch: error => (error instanceof Error ? error : new Error(String(error))),
+ });
+
+export const signupAgent = (params: { wait?: boolean } = {}) =>
+ Effect.gen(function* () {
+ const wait = params.wait ?? true;
+ const payload = yield* fetchAgentJson(`/api/signup${wait ? '' : '?wait=0'}`, {
+ method: 'POST',
+ body: JSON.stringify({}),
+ });
+ return yield* writeStoredAgentIdentity(normalizeAgentIdentity(payload));
+ });
+
+export const fetchAgentWhoami = (agentKey: string) =>
+ Effect.gen(function* () {
+ const payload = yield* fetchAgentJson('/api/whoami', {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${agentKey}` },
+ });
+ return normalizeAgentIdentity(payload, agentKey);
+ });
+
+export const fetchAgentInbox = (params: { agentKey: string; limit?: number }) =>
+ fetchAgentJson(`/api/mail?limit=${encodeURIComponent(String(params.limit ?? 50))}`, {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${params.agentKey}` },
+ }).pipe(Effect.map(payload => payload as AgentMailResponse));
+
+export const claimAgent = (params: { agentKey: string; email: string }) =>
+ fetchAgentJson('/api/claim', {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${params.agentKey}` },
+ body: JSON.stringify({ email: params.email }),
+ }).pipe(Effect.map(payload => payload as AgentClaimResponse));
+
+const humanLoginError = () =>
+ new AgentAuthError({
+ message: 'This CLI is currently signed in to Composio as a regular user, not an agent.',
+ nextSteps: [
+ 'To switch to an existing agent: run `composio logout`, then `composio agent login <composio_agent_key>`.',
+ 'To create a new agent: run `composio logout`, then `composio signup`.',
+ ],
+ });
+
+export const ensureAgentSignupAllowed = Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ const apiKey = ctx.data.apiKey;
+ if (Option.isNone(apiKey)) return;
+
+ const stored = yield* readStoredAgentIdentity;
+ if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, apiKey.value)) return;
+
+ return yield* Effect.fail(humanLoginError());
+});
+
+export const getCurrentLoggedInAgent = Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ const currentApiKey = ctx.data.apiKey;
+ if (Option.isNone(currentApiKey)) return Option.none<AgentIdentity>();
+
+ const stored = yield* readStoredAgentIdentity;
+ if (Option.isNone(stored)) return Option.none<AgentIdentity>();
+
+ return isAgentIdentityForApiKey(stored.value, currentApiKey.value)
+ ? stored
+ : Option.none<AgentIdentity>();
+});
+
+export const resolveStoredAgentKey = Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ const stored = yield* readStoredAgentIdentity;
+ const currentApiKey = ctx.data.apiKey;
+
+ if (Option.isSome(currentApiKey)) {
+ if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, currentApiKey.value)) {
+ return getAgentKey(stored.value) as string;
+ }
+
+ return yield* Effect.fail(humanLoginError());
+ }
+
+ if (Option.isNone(stored)) {
+ return yield* Effect.fail(
+ new AgentAuthError({
+ message: 'No Composio agent identity is saved on this machine.',
+ nextSteps: [
+ 'To create a new agent: run `composio signup` or `composio agent signup`.',
+ 'To restore an existing agent: run `composio agent login <composio_agent_key>`.',
+ ],
+ })
+ );
+ }
+
+ const agentKey = getAgentKey(stored.value);
+ if (!agentKey) {
+ return yield* Effect.fail(
+ new AgentAuthError({
+ message: 'The saved Composio agent identity is missing its composio_agent_key.',
+ nextSteps: [
+ 'If you saved the key, run `composio agent login <composio_agent_key>`.',
+ 'Otherwise create a new agent with `composio signup`.',
+ ],
+ })
+ );
+ }
+
+ return agentKey;
+});
+
+export const getOrSignupReadyAgent = (params: { force?: boolean } = {}) =>
+ Effect.gen(function* () {
+ if (!params.force) {
+ const stored = yield* readStoredAgentIdentity;
+ if (Option.isSome(stored)) {
+ const agentKey = getAgentKey(stored.value);
+ if (agentKey) {
+ const remote = yield* fetchAgentWhoami(agentKey).pipe(Effect.option);
+ if (Option.isSome(remote)) {
+ const saved = yield* writeStoredAgentIdentity(remote.value);
+ if (normalizeAgentStatus(saved.status) === 'READY') return saved;
+ }
+ }
+ }
+ }
+
+ return yield* signupAgent({ wait: true });
+ });
+
+export const loginWithAgentIdentity = (identity: AgentIdentity) =>
+ Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ const userApiKey = identity.composio?.user_api_key;
+ const orgId = identity.composio?.org_id;
+
+ if (!userApiKey || !orgId) {
+ return yield* Effect.fail(
+ new Error(
+ 'Agent identity is not ready yet. Run `composio agent whoami` and try again once status is READY.'
+ )
+ );
+ }
+
+ yield* ctx.login(userApiKey, orgId);
+ yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId });
+ });
diff --git a/ts/packages/cli/test/src/commands/agent.cmd.test.ts b/ts/packages/cli/test/src/commands/agent.cmd.test.ts
new file mode 100644
index 000000000..e16d00194
--- /dev/null
+++ b/ts/packages/cli/test/src/commands/agent.cmd.test.ts
@@ -0,0 +1,275 @@
+import { describe, expect, layer } from '@effect/vitest';
+import { FileSystem } from '@effect/platform';
+import { Effect, Option } from 'effect';
+import path from 'node:path';
+import { afterEach, vi } from 'vitest';
+import * as constants from 'src/constants';
+import { setupCacheDir } from 'src/effects/setup-cache-dir';
+import { writeStoredAgentIdentity } from 'src/services/agents';
+import { ComposioUserContext } from 'src/services/user-context';
+import { cli, MockConsole, TestLive } from 'test/__utils__';
+
+const agentSignupResponse = {
+ status: 'READY',
+ slug: 'test-agent',
+ email: '[email protected]',
+ composio_agent_key: 'cak_test_agent',
+ composio: {
+ member_id: 'mem_agent',
+ org_id: 'org_agent',
+ project_id: 'proj_agent',
+ user_api_key: 'uak_agent',
+ },
+};
+
+describe('CLI: composio agent', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ process.exitCode = undefined;
+ });
+
+ layer(TestLive())(it => {
+ it.scoped('exposes agent signup as a subcommand', () =>
+ Effect.gen(function* () {
+ yield* cli(['agent', '--help']);
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+
+ expect(output).toContain('signup');
+ expect(output).toContain('login');
+ expect(output).toContain('whoami');
+ expect(output).toContain('claim');
+ })
+ );
+ });
+
+ layer(TestLive())(it => {
+ it.scoped('agent signup works when the CLI is not signed in', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
+ const url =
+ typeof requestInput === 'string'
+ ? requestInput
+ : requestInput instanceof URL
+ ? requestInput.toString()
+ : requestInput.url;
+
+ if (url.includes('/api/signup')) {
+ return new Response(JSON.stringify(agentSignupResponse), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({}), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ yield* cli(['agent', 'signup']);
+
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+ expect(output).toContain('composio agent signup signs you up as a Composio agent');
+ expect(output).toContain('fully non-interactive');
+
+ const ctx = yield* ComposioUserContext;
+ expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
+ expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
+
+ const fs = yield* FileSystem.FileSystem;
+ const cacheDir = yield* setupCacheDir;
+ const userConfigRaw = yield* fs.readFileString(
+ path.join(cacheDir, constants.USER_CONFIG_FILE_NAME),
+ 'utf8'
+ );
+ const agentConfigRaw = yield* fs.readFileString(path.join(cacheDir, 'agent.json'), 'utf8');
+
+ expect(JSON.parse(userConfigRaw)).toMatchObject({
+ api_key: 'uak_agent',
+ org_id: 'org_agent',
+ });
+ expect(JSON.parse(agentConfigRaw)).toMatchObject({
+ composio_agent_key: 'cak_test_agent',
+ agent_key: 'cak_test_agent',
+ composio: { user_api_key: 'uak_agent' },
+ });
+ })
+ );
+ });
+
+ layer(TestLive())(it => {
+ it.scoped('top-level signup makes clear it signs up an agent', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
+ const url =
+ typeof requestInput === 'string'
+ ? requestInput
+ : requestInput instanceof URL
+ ? requestInput.toString()
+ : requestInput.url;
+
+ if (url.includes('/api/signup')) {
+ return new Response(JSON.stringify(agentSignupResponse), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({}), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ yield* cli(['signup']);
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+
+ expect(output).toContain('composio signup signs you up as a Composio agent');
+ })
+ );
+ });
+
+ layer(TestLive())(it => {
+ it.scoped('agent inbox prints only JSON', () =>
+ Effect.gen(function* () {
+ yield* writeStoredAgentIdentity(agentSignupResponse);
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
+ const url =
+ typeof requestInput === 'string'
+ ? requestInput
+ : requestInput instanceof URL
+ ? requestInput.toString()
+ : requestInput.url;
+
+ if (url.includes('/api/mail')) {
+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer cak_test_agent');
+ return new Response(
+ JSON.stringify({
+ count: 1,
+ messages: [
+ {
+ id: 'msg_123',
+ subject: 'Hello',
+ preview: 'Hi agent',
+ },
+ ],
+ }),
+ {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }
+ );
+ }
+
+ return new Response(JSON.stringify({}), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ yield* cli(['agent', 'inbox']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+
+ expect(lines).toEqual([
+ JSON.stringify({
+ count: 1,
+ messages: [
+ {
+ id: 'msg_123',
+ subject: 'Hello',
+ preview: 'Hi agent',
+ },
+ ],
+ }),
+ ]);
+ })
+ );
+ });
+
+ layer(TestLive())(it => {
+ it.scoped('agent login restores an existing agent from composio_agent_key', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
+ const url =
+ typeof requestInput === 'string'
+ ? requestInput
+ : requestInput instanceof URL
+ ? requestInput.toString()
+ : requestInput.url;
+
+ if (url.includes('/api/whoami')) {
+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer cak_existing');
+ return new Response(
+ JSON.stringify({
+ ...agentSignupResponse,
+ composio_agent_key: 'cak_existing',
+ agent_key: 'cak_existing',
+ }),
+ {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }
+ );
+ }
+
+ return new Response(JSON.stringify({}), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ yield* cli(['agent', 'login', 'cak_existing']);
+
+ const ctx = yield* ComposioUserContext;
+ expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
+ expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
+
+ const fs = yield* FileSystem.FileSystem;
+ const cacheDir = yield* setupCacheDir;
+ const agentConfigRaw = yield* fs.readFileString(path.join(cacheDir, 'agent.json'), 'utf8');
+ expect(JSON.parse(agentConfigRaw)).toMatchObject({
+ composio_agent_key: 'cak_existing',
+ agent_key: 'cak_existing',
+ composio: { user_api_key: 'uak_agent' },
+ });
+ })
+ );
+ });
+
+ layer(TestLive({ fixture: 'user-config-example' }))(it => {
+ it.scoped('agent commands show a soft auth warning when signed in as a human user', () =>
+ Effect.gen(function* () {
+ yield* cli(['agent', 'whoami']);
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+
+ expect(output).toContain('currently signed in to Composio as a regular user');
+ expect(output).toContain('composio agent login <composio_agent_key>');
+ expect(process.exitCode).toBe(1);
+ })
+ );
+
+ it.scoped('agent signup shows a soft auth warning when signed in as a human user', () =>
+ Effect.gen(function* () {
+ yield* cli(['agent', 'signup']);
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+
+ expect(output).toContain('currently signed in to Composio as a regular user');
+ expect(output).toContain('composio signup');
+ expect(process.exitCode).toBe(1);
+ })
+ );
+
+ it.scoped('agent login shows a soft auth warning when signed in as a human user', () =>
+ Effect.gen(function* () {
+ yield* cli(['agent', 'login', 'cak_existing']);
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+
+ expect(output).toContain('currently signed in to Composio as a regular user');
+ expect(output).toContain('composio logout');
+ expect(process.exitCode).toBe(1);
+ })
+ );
+ });
+});
diff --git a/ts/packages/cli/test/src/commands/logout.cmd.test.ts b/ts/packages/cli/test/src/commands/logout.cmd.test.ts
index 51777e31c..67bb55664 100644
--- a/ts/packages/cli/test/src/commands/logout.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/logout.cmd.test.ts
@@ -1,10 +1,67 @@
import { describe, expect, layer } from '@effect/vitest';
-import { ConfigProvider, Effect, Option } from 'effect';
+import { FileSystem } from '@effect/platform';
+import { ConfigProvider, Console, Effect, Option } from 'effect';
+import path from 'node:path';
+import * as constants from 'src/constants';
+import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { UserDataWithDefaults } from 'src/models/user-data';
+import { writeStoredAgentIdentity } from 'src/services/agents';
import { extendConfigProvider } from 'src/services/config';
+import { TerminalUI } from 'src/services/terminal-ui';
import { ComposioUserContext } from 'src/services/user-context';
import { cli, TestLive, MockConsole } from 'test/__utils__';
+const terminalUIWithConfirm = (confirmed: boolean) =>
+ TerminalUI.of({
+ output: data => Console.log(data),
+ intro: title => Console.log(`-- ${title} --`),
+ outro: message => Console.log(`-- ${message} --`),
+ log: {
+ info: message => Console.log(message),
+ success: message => Console.log(message),
+ warn: message => Console.warn(message),
+ error: message => Console.error(message),
+ step: message => Console.log(message),
+ message: message => Console.log(message),
+ },
+ note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
+ select: (_message, options) => Effect.succeed(options[0]!.value),
+ confirm: () => Effect.succeed(confirmed),
+ withSpinner: (message, effect, options) =>
+ Effect.gen(function* () {
+ const result = yield* effect;
+ const successMsg =
+ typeof options?.successMessage === 'function'
+ ? options.successMessage(result)
+ : (options?.successMessage ?? message);
+ yield* Console.log(successMsg);
+ return result;
+ }),
+ useMakeSpinner: (_message, use) =>
+ use({
+ message: (_msg: string) => Effect.void,
+ stop: (msg?: string) => (msg ? Console.log(msg) : Effect.void),
+ error: (msg?: string) => (msg ? Console.error(msg) : Effect.void),
+ }),
+ });
+
+const setupLoggedInAgent = Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ yield* writeStoredAgentIdentity({
+ status: 'READY',
+ slug: 'test-agent',
+ email: '[email protected]',
+ composio_agent_key: 'cak_test_agent',
+ composio: {
+ org_id: 'org_agent',
+ project_id: 'proj_agent',
+ user_api_key: 'uak_agent',
+ },
+ });
+ yield* ctx.login('uak_agent', 'org_agent');
+ return ctx;
+});
+
describe('CLI: composio logout', () => {
describe('[When] logged out', () => {
layer(TestLive())(it => {
@@ -71,4 +128,51 @@ describe('CLI: composio logout', () => {
);
});
});
+
+ describe('[When] logged in as an agent', () => {
+ layer(TestLive({ terminalUI: terminalUIWithConfirm(false) }))(it => {
+ it.scoped('[Then] cancelling keeps user and agent credentials', () =>
+ Effect.gen(function* () {
+ const ctx = yield* setupLoggedInAgent;
+
+ yield* cli(['logout']);
+
+ const fs = yield* FileSystem.FileSystem;
+ const cacheDir = yield* setupCacheDir;
+ const agentConfigExists = yield* fs.exists(path.join(cacheDir, 'agent.json'));
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+
+ expect(output).toContain('Agent Logout Warning');
+ expect(output).toContain('composio_agent_key');
+ expect(output).toContain('Agent logout cancelled');
+ expect(ctx.isLoggedIn()).toBeTruthy();
+ expect(agentConfigExists).toBe(true);
+ })
+ );
+ });
+
+ layer(TestLive())(it => {
+ it.scoped('[Then] --force removes user and agent credentials', () =>
+ Effect.gen(function* () {
+ const ctx = yield* setupLoggedInAgent;
+
+ yield* cli(['logout', '--force']);
+
+ const fs = yield* FileSystem.FileSystem;
+ const cacheDir = yield* setupCacheDir;
+ const agentConfigExists = yield* fs.exists(path.join(cacheDir, 'agent.json'));
+ const userConfigRaw = yield* fs.readFileString(
+ path.join(cacheDir, constants.USER_CONFIG_FILE_NAME),
+ 'utf8'
+ );
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+
+ expect(output).toContain('removed stored Composio agent key');
+ expect(ctx.isLoggedIn()).toBeFalsy();
+ expect(agentConfigExists).toBe(false);
+ expect(JSON.parse(userConfigRaw)).toHaveProperty('api_key', null);
+ })
+ );
+ });
+ });
});