@devries-cameron20 / composio-1 / commits / fc1460995
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): make headless composio login agent-friendly (PRDE-1138)

Teach non-interactive login to reuse an existing READY agent identity without creating one implicitly. Preserve explicit --no-browser and --no-wait contracts, and branch on TerminalUI.canPrompt so piping stdout alone remains interactive. Add unattended guidance, installer analytics attribution, and focused unit and Docker E2E coverage. Exclude host node_modules from Docker build contexts.

Kshitij Jhunjhunwala committed Jul 24, 2026 at 14:01 UTC fc1460995b2b1118f2a595ca11b6d9fe45428208
11 files changed +489 -49
.dockerignore new
+5
@@ -0,0 +1,5 @@
1 +# The e2e Dockerfiles (ts/e2e-tests/_utils/Dockerfile.*) pnpm-install inside
2 +# the image; host node_modules are pnpm symlinks into a store that is not
3 +# copied, so they must never enter the build context.
4 +**/node_modules
5 +.git
install.sh
+1 -1
@@ -415,7 +415,7 @@ fi
415 if [[ $install_agent = true ]]; then
416 echo
417 info "Setting up Composio agent login..."
418 - if ! "$exe" login --agent --no-skill-install; then
418 + if ! COMPOSIO_CLI_INVOCATION_ORIGIN=installer "$exe" login --agent --no-skill-install; then
419 error 'Failed to sign up/log in as a Composio agent. If this CLI is already signed in as a regular user, run `composio logout` and then `composio signup` or `composio agent login <composio_agent_key>`.'
420 fi
421 fi
pnpm-lock.yaml
+6
@@ -205,6 +205,12 @@ importers:
205 specifier: 'catalog:'
206 version: 7.0.2
207
208 + ts/e2e-tests/cli/agent-signin:
209 + devDependencies:
210 + '@e2e-tests/utils':
211 + specifier: workspace:*
212 + version: link:../../_utils
213 +
214 ts/e2e-tests/cli/setup-plugins:
215 devDependencies:
216 '@e2e-tests/utils':
ts/e2e-tests/cli/agent-signin/README.md new
+15
@@ -0,0 +1,15 @@
1 +# CLI agent sign-in e2e (PRDE-1138)
2 +
3 +Asserts the headless agent onboarding contract:
4 +
5 +- `composio login --agent` takes an unattended agent from nothing to an
6 + authenticated CLI (mocked `agents.composio.dev` via
7 + `COMPOSIO_AGENTS_BASE_URL`), verified with a follow-up `composio whoami`.
8 +- A plain piped `composio login` prints the OAuth URL + poll instructions,
9 + offers the `composio login --agent` path for unattended agents, and never
10 + auto-creates an account (guardrail: humans in pipes are not signed up).
11 +- A stored READY agent identity (`agent.json`) lets plain headless
12 + `composio login` complete unattended by reuse, without signup.
13 +
14 +All network surfaces are mocked by
15 +`ts/packages/cli/scripts/mock-agents-server.ts`; no real accounts are created.
ts/e2e-tests/cli/agent-signin/e2e.test.ts new
+126
@@ -0,0 +1,126 @@
1 +/**
2 + * CLI agent sign-in e2e test (PRDE-1138)
3 + *
4 + * A headless agent must reach an authenticated CLI without human action, and
5 + * a human piping `composio login` must never be auto-signed-up as an agent.
6 + */
7 +
8 +import { e2e, type E2ETestResult } from '@e2e-tests/utils';
9 +import { TIMEOUTS } from '@e2e-tests/utils/const';
10 +import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
11 +import {
12 + startMockAgentsServer,
13 + type MockAgentsServer,
14 +} from '../../../packages/cli/scripts/mock-agents-server';
15 +
16 +const CACHE_DIR = '/tmp/composio-agent-signin';
17 +
18 +/** Parses the last stdout line as JSON — the `composio whoami` payload. */
19 +const lastJsonLine = (stdout: string): Record<string, unknown> =>
20 + JSON.parse(stdout.trim().split('\n').at(-1) ?? '{}') as Record<string, unknown>;
21 +
22 +const envPrefix = (server: MockAgentsServer): string =>
23 + [
24 + `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,
25 + `COMPOSIO_AGENTS_BASE_URL=${server.dockerBaseUrl}`,
26 + `COMPOSIO_CACHE_DIR=${CACHE_DIR}`,
27 + ].join(' ');
28 +
29 +e2e(import.meta.url, {
30 + versions: {
31 + cli: ['current'],
32 + },
33 + defineTests: ({ runCmd }) => {
34 + let signupServer: MockAgentsServer;
35 + let guardrailServer: MockAgentsServer;
36 + let reuseServer: MockAgentsServer;
37 + let unattendedSignup: E2ETestResult;
38 + let headlessHumanLogin: E2ETestResult;
39 + let storedIdentityLogin: E2ETestResult;
40 +
41 + beforeAll(async () => {
42 + signupServer = await startMockAgentsServer();
43 + guardrailServer = await startMockAgentsServer();
44 + reuseServer = await startMockAgentsServer();
45 +
46 + unattendedSignup = await runCmd(
47 + `${envPrefix(signupServer)} composio login --agent --no-skill-install && ${envPrefix(signupServer)} composio whoami`
48 + );
49 +
50 + headlessHumanLogin = await runCmd(`${envPrefix(guardrailServer)} composio login`);
51 +
52 + const storedIdentity = JSON.stringify(reuseServer.agentIdentity);
53 + storedIdentityLogin = await runCmd(
54 + [
55 + `mkdir -p ${CACHE_DIR}`,
56 + `printf '%s' '${storedIdentity}' > ${CACHE_DIR}/agent.json`,
57 + `${envPrefix(reuseServer)} composio login && ${envPrefix(reuseServer)} composio whoami`,
58 + ].join('\n')
59 + );
60 + }, TIMEOUTS.FIXTURE);
61 +
62 + afterAll(async () => {
63 + await signupServer.close();
64 + await guardrailServer.close();
65 + await reuseServer.close();
66 + });
67 +
68 + describe('composio login --agent (unattended onboarding)', () => {
69 + it('exits successfully', () => {
70 + expect(unattendedSignup.exitCode).toBe(0);
71 + });
72 +
73 + it('signs up via agents.composio.dev', () => {
74 + expect(signupServer.requests).toContain('POST /api/signup');
75 + });
76 +
77 + it('prints the agent login summary on stdout', () => {
78 + expect(unattendedSignup.stdout).toContain('"account_type":"agent"');
79 + expect(unattendedSignup.stdout).toContain('"logged_in":true');
80 + expect(unattendedSignup.stdout).toContain('"status":"READY"');
81 + });
82 +
83 + it('leaves the CLI authenticated as the agent (whoami)', () => {
84 + const whoami = lastJsonLine(unattendedSignup.stdout);
85 + expect(whoami.account_type).toBe('agent');
86 + });
87 + });
88 +
89 + describe('composio login (headless, no agent identity)', () => {
90 + it('exits successfully with instructions instead of hanging', () => {
91 + expect(headlessHumanLogin.exitCode).toBe(0);
92 + expect(headlessHumanLogin.stdout).toContain('Open this URL in your browser to log in:');
93 + expect(headlessHumanLogin.stdout).toContain('composio login --poll');
94 + });
95 +
96 + it('offers the unattended agent path', () => {
97 + expect(headlessHumanLogin.stdout).toContain('For unattended agents');
98 + expect(headlessHumanLogin.stdout).toContain('composio login --agent');
99 + });
100 +
101 + it('never auto-signs-up an account', () => {
102 + expect(guardrailServer.requests.filter(request => request.includes('/api/signup'))).toEqual(
103 + []
104 + );
105 + });
106 + });
107 +
108 + describe('composio login (headless, stored READY agent identity)', () => {
109 + it('completes login unattended by reusing the stored identity', () => {
110 + expect(storedIdentityLogin.exitCode).toBe(0);
111 + expect(storedIdentityLogin.stdout).toContain('"logged_in":true');
112 + expect(storedIdentityLogin.stdout).not.toContain('Open this URL in your browser');
113 + });
114 +
115 + it('refreshes the identity instead of signing up', () => {
116 + expect(reuseServer.requests).toContain('GET /api/whoami');
117 + expect(reuseServer.requests.filter(request => request.includes('/api/signup'))).toEqual([]);
118 + });
119 +
120 + it('leaves the CLI authenticated as the agent (whoami)', () => {
121 + const whoami = lastJsonLine(storedIdentityLogin.stdout);
122 + expect(whoami.account_type).toBe('agent');
123 + });
124 + });
125 + },
126 +});
ts/e2e-tests/cli/agent-signin/package.json new
+14
@@ -0,0 +1,14 @@
1 +{
2 + "name": "@e2e-tests/cli-agent-signin",
3 + "version": "0.0.0",
4 + "private": true,
5 + "type": "module",
6 + "scripts": {
7 + "typecheck": "tsc --noEmit",
8 + "test:e2e": "bun test e2e.test.ts",
9 + "test:e2e:cli": "bun test e2e.test.ts"
10 + },
11 + "devDependencies": {
12 + "@e2e-tests/utils": "workspace:*"
13 + }
14 +}
ts/packages/cli/CHANGELOG.md
+1
@@ -10,6 +10,7 @@
10
11 ### Minor Changes
12
13 +- Make headless `composio login` agent-friendly (PRDE-1138): the non-interactive instructions now offer the unattended `composio login --agent` path, and a machine with a stored READY agent identity (`~/.composio/agent.json`) completes plain headless `composio login` unattended by reusing it. Reuse only — a human piping `composio login` still gets the URL + poll instructions and never has an account auto-created.
14 - a0bef5d: Bump `@composio/client` to `0.1.0-alpha.74`.
15 - 025a657: Drop CommonJS entrypoints and publish the TypeScript SDK packages as ESM-only packages. This is a breaking change within the existing 0.x release line: consumers must use Node.js 22.22.3 or newer. CommonJS callers can only rely on Node's native `require(esm)` interop, and the SDK no longer ships custom CommonJS compatibility machinery or `.cjs` artifacts.
16
ts/packages/cli/scripts/mock-agents-server.ts new
+118
@@ -0,0 +1,118 @@
1 +#!/usr/bin/env bun
2 +
3 +import { createServer, type ServerResponse } from 'node:http';
4 +
5 +/**
6 + * Mock agents.composio.dev + the minimal Apollo endpoints the login flows
7 + * touch. Point the CLI at it via COMPOSIO_AGENTS_BASE_URL / COMPOSIO_BASE_URL.
8 + */
9 +
10 +const AGENT_IDENTITY = {
11 + status: 'READY',
12 + slug: 'e2e-agent',
13 + email: 'e2e-agent@agent.composio.ai',
14 + composio_agent_key: 'cak_e2e_agent',
15 + composio: {
16 + member_id: 'mem_e2e_agent',
17 + org_id: 'org_e2e_agent',
18 + project_id: 'proj_e2e_agent',
19 + user_api_key: 'uak_e2e_agent',
20 + },
21 +} as const;
22 +
23 +export interface MockAgentsServer {
24 + readonly hostBaseUrl: string;
25 + readonly dockerBaseUrl: string;
26 + readonly requests: string[];
27 + readonly agentIdentity: typeof AGENT_IDENTITY;
28 + readonly close: () => Promise<void>;
29 +}
30 +
31 +const sendJson = (res: ServerResponse, statusCode: number, body: unknown): void => {
32 + res.writeHead(statusCode, { 'Content-Type': 'application/json' });
33 + res.end(JSON.stringify(body));
34 +};
35 +
36 +export async function startMockAgentsServer(options?: {
37 + host?: string;
38 + port?: number;
39 +}): Promise<MockAgentsServer> {
40 + const host = options?.host ?? '0.0.0.0';
41 + const port = options?.port ?? 0;
42 + const requests: string[] = [];
43 +
44 + const server = createServer((req, res) => {
45 + const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`);
46 + const method = req.method ?? 'GET';
47 + requests.push(`${method} ${url.pathname}`);
48 +
49 + // agents.composio.dev surface
50 + if (method === 'POST' && url.pathname === '/api/signup') {
51 + sendJson(res, 200, AGENT_IDENTITY);
52 + return;
53 + }
54 +
55 + if (method === 'GET' && url.pathname === '/api/whoami') {
56 + const authorized =
57 + req.headers.authorization === `Bearer ${AGENT_IDENTITY.composio_agent_key}`;
58 + sendJson(
59 + res,
60 + authorized ? 200 : 401,
61 + authorized ? AGENT_IDENTITY : { message: 'unauthorized' }
62 + );
63 + return;
64 + }
65 +
66 + // Apollo surface used by the default login path
67 + if (method === 'POST' && url.pathname === '/api/v3.1/cli/create-session') {
68 + sendJson(res, 200, {
69 + id: 'e2e00000-0000-4000-8000-000000000001',
70 + code: 'E2E123',
71 + expiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
72 + status: 'pending',
73 + });
74 + return;
75 + }
76 +
77 + if (method === 'POST' && url.pathname === '/api/v3/cli/analytics') {
78 + sendJson(res, 204, {});
79 + return;
80 + }
81 +
82 + // Unmocked routes are non-fatal to the flows under test; 404 exercises
83 + // their degrade paths.
84 + sendJson(res, 404, { error: `Unhandled mock route: ${method} ${url.pathname}` });
85 + });
86 +
87 + await new Promise<void>((resolve, reject) => {
88 + server.once('error', reject);
89 + server.listen({ host, port }, () => {
90 + server.off('error', reject);
91 + resolve();
92 + });
93 + });
94 +
95 + const address = server.address();
96 + if (address === null || typeof address === 'string') {
97 + throw new Error('Failed to bind mock agents server to a TCP port');
98 + }
99 +
100 + const close = () =>
101 + new Promise<void>((resolve, reject) => {
102 + server.close(error => {
103 + if (error) {
104 + reject(error);
105 + return;
106 + }
107 + resolve();
108 + });
109 + });
110 +
111 + return {
112 + hostBaseUrl: `http://127.0.0.1:${address.port}`,
113 + dockerBaseUrl: `http://host.docker.internal:${address.port}`,
114 + requests,
115 + agentIdentity: AGENT_IDENTITY,
116 + close,
117 + };
118 +}
ts/packages/cli/src/commands/login.cmd.ts
+38 -7
@@ -22,8 +22,11 @@ import { APP_VERSION } from 'src/constants';
22 import {
23 ensureAgentSignupAllowed,
24 getOrSignupReadyAgent,
25 + getStoredReadyAgent,
26 + isAgentIdentityForApiKey,
27 loginWithAgentIdentity,
28 safeAgentSummary,
29 + type AgentIdentity,
30 } from 'src/services/agents';
31
32 export const noBrowser = Options.boolean('no-browser').pipe(
@@ -181,7 +184,9 @@ Then run this command to complete login:
184
185 ${params.pollCommand}
186
184 -hint: For agents: Show the URL above to the user to click, then run the command above. The command uses the cached login key, polls for up to 10 minutes, and exits once credentials are saved. Do not ask the user whether to poll — they already requested login.`;
187 +hint: For agents: Show the URL above to the user to click, then run the command above. The command uses the cached login key, polls for up to 10 minutes, and exits once credentials are saved. Do not ask the user whether to poll — they already requested login.
188 +
189 +hint: For unattended agents: If no human is available to open the URL, run \`composio login --agent\` instead — it signs the CLI in with a Composio agent account (creating one if needed) without a browser. Never use it when a human is present to log in with their own account.`;
190
191 const formatPollLoginComplete = (params: {
192 readonly email?: string;
@@ -278,6 +283,15 @@ const emitLoginComplete = (params: {
283 }
284 });
285
286 +const completeAgentLogin = (identity: AgentIdentity) =>
287 + Effect.gen(function* () {
288 + const ui = yield* TerminalUI;
289 + yield* loginWithAgentIdentity(identity);
290 + const summary = safeAgentSummary(identity);
291 + yield* ui.log.success(`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`);
292 + yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
293 + });
294 +
295 const resolveDirectLoginOrganization = (params: {
296 apiKey: string;
297 baseURL: string;
@@ -777,6 +791,9 @@ export const browserLogin = (params: {
791 * Use --agent to sign up or log in using a Composio agent identity.
792 * Use -y to skip org picker and use current org.
793 *
794 + * Non-interactive default flow: prints URL + poll instructions, or logs in
795 + * unattended when a READY agent identity is already stored.
796 + *
797 * @example
798 * ```bash
799 * composio login
@@ -883,12 +900,7 @@ export const loginCmd = Command.make(
900 Effect.gen(function* () {
901 yield* ensureAgentSignupAllowed;
902 const identity = yield* getOrSignupReadyAgent();
886 - yield* loginWithAgentIdentity(identity);
887 - const summary = safeAgentSummary(identity);
888 - yield* ui.log.success(
889 - `Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`
890 - );
891 - yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
903 + yield* completeAgentLogin(identity);
904 if (!noSkillInstall && canPrompt) {
905 yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
906 }
@@ -930,6 +942,25 @@ export const loginCmd = Command.make(
942 yield* ui.log.step('Re-authenticating for multi-project support...');
943 }
944
945 + // Reuse-only by design: headless login may complete with an existing
946 + // agent identity but must never auto-create one for a human in a pipe.
947 + // `--no-browser` and `--no-wait` opt out: both promise a specific output
948 + // contract (printed URL, session JSON) that silent agent reuse would replace.
949 + const requestedExplicitLoginFlow = noBrowser || noWait;
950 + if (!canPrompt && !requestedExplicitLoginFlow) {
951 + const storedAgent = yield* getStoredReadyAgent;
952 + if (Option.isSome(storedAgent)) {
953 + const identity = storedAgent.value;
954 + const activeApiKey = ctx.data.apiKey;
955 + if (
956 + Option.isNone(activeApiKey) ||
957 + isAgentIdentityForApiKey(identity, activeApiKey.value)
958 + ) {
959 + return yield* handleAgentAuthError(completeAgentLogin(identity));
960 + }
961 + }
962 + }
963 +
964 yield* browserLogin({
965 scope: 'user',
966 noBrowser,
ts/packages/cli/src/services/agents.ts
+24
@@ -365,6 +365,30 @@ export const resolveStoredAgentKey = Effect.gen(function* () {
365 return agentKey;
366 });
367
368 +/**
369 + * Reuse-only counterpart of {@link getOrSignupReadyAgent}: refreshes and
370 + * returns a stored READY identity but never signs up a new agent.
371 + */
372 +export const getStoredReadyAgent = Effect.gen(function* () {
373 + const stored = yield* readStoredAgentIdentity;
374 + if (Option.isNone(stored)) return Option.none<AgentIdentity>();
375 +
376 + const agentKey = getAgentKey(stored.value);
377 + if (!agentKey) return Option.none<AgentIdentity>();
378 +
379 + const remote = yield* fetchAgentWhoami(agentKey).pipe(Effect.option);
380 + const identity = Option.isSome(remote)
381 + ? yield* writeStoredAgentIdentity(remote.value)
382 + : stored.value;
383 +
384 + const ready =
385 + normalizeAgentStatus(identity.status) === 'READY' &&
386 + Boolean(identity.composio?.user_api_key) &&
387 + Boolean(identity.composio?.org_id);
388 +
389 + return ready ? Option.some(identity) : Option.none<AgentIdentity>();
390 +});
391 +
392 export const getOrSignupReadyAgent = (params: { force?: boolean } = {}) =>
393 Effect.gen(function* () {
394 if (!params.force) {
ts/packages/cli/test/src/commands/login.cmd.test.ts
+141 -41
@@ -9,33 +9,61 @@ import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
9 import * as constants from 'src/constants';
10 import { setupCacheDir } from 'src/effects/setup-cache-dir';
11 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
12 +import { writeStoredAgentIdentity } from 'src/services/agents';
13 import { ComposioUserContext } from 'src/services/user-context';
14
15 +vi.mock('open', () => ({
16 + default: vi.fn(async () => undefined),
17 +}));
18 +
19 const mockFetchResponse = (body: unknown, status = 200) =>
20 new Response(JSON.stringify(body), {
21 status,
22 headers: { 'Content-Type': 'application/json' },
23 });
24
20 -const setTtyState = (state: { stdin: boolean; stdout: boolean; stderr: boolean }) => {
21 - const descriptors = {
22 - stdin: Object.getOwnPropertyDescriptor(process.stdin, 'isTTY'),
23 - stdout: Object.getOwnPropertyDescriptor(process.stdout, 'isTTY'),
24 - stderr: Object.getOwnPropertyDescriptor(process.stderr, 'isTTY'),
25 - };
26 - Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: state.stdin });
27 - Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: state.stdout });
28 - Object.defineProperty(process.stderr, 'isTTY', { configurable: true, value: state.stderr });
29 - return () => {
30 - if (descriptors.stdin) Object.defineProperty(process.stdin, 'isTTY', descriptors.stdin);
31 - else delete (process.stdin as { isTTY?: boolean }).isTTY;
32 - if (descriptors.stdout) Object.defineProperty(process.stdout, 'isTTY', descriptors.stdout);
33 - else delete (process.stdout as { isTTY?: boolean }).isTTY;
34 - if (descriptors.stderr) Object.defineProperty(process.stderr, 'isTTY', descriptors.stderr);
35 - else delete (process.stderr as { isTTY?: boolean }).isTTY;
36 - };
25 +const requestUrl = (requestInput: RequestInfo | URL): string =>
26 + typeof requestInput === 'string'
27 + ? requestInput
28 + : requestInput instanceof URL
29 + ? requestInput.toString()
30 + : requestInput.url;
31 +
32 +const storedAgentIdentity = {
33 + status: 'READY',
34 + slug: 'test-agent',
35 + email: 'test-agent@agent.composio.ai',
36 + composio_agent_key: 'cak_test_agent',
37 + composio: {
38 + member_id: 'mem_agent',
39 + org_id: 'org_agent',
40 + project_id: 'proj_agent',
41 + user_api_key: 'uak_agent',
42 + },
43 };
44
45 +const terminalUIWithTtyState = (state: {
46 + readonly stdin: boolean;
47 + readonly stdout: boolean;
48 + readonly stderr: boolean;
49 +}) =>
50 + TerminalUI.of({
51 + ...terminalUITestImpl,
52 + capabilities: Effect.succeed(
53 + getTerminalCapabilities({
54 + stdin: { isTTY: state.stdin },
55 + stdout: { isTTY: state.stdout },
56 + stderr: { isTTY: state.stderr },
57 + })
58 + ),
59 + });
60 +
61 +const headlessStdinUI = terminalUIWithTtyState({
62 + stdin: false,
63 + stdout: false,
64 + stderr: false,
65 +});
66 +
67 // ── Tests ────────────────────────────────────────────────────────────────────
68
69 describe('CLI: composio login', () => {
@@ -85,15 +113,10 @@ describe('CLI: composio login', () => {
113 );
114 });
115
88 - layer(TestLive())(it => {
116 + layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
117 it.scoped('[When] stdin is non-interactive [Then] login prints agent instructions', () =>
118 Effect.gen(function* () {
91 - const restoreTty = setTtyState({ stdin: false, stdout: true, stderr: true });
92 - try {
93 - yield* cli(['login']);
94 - } finally {
95 - restoreTty();
96 - }
119 + yield* cli(['login']);
120
121 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
122 expect(output).toContain('Open this URL in your browser to log in:');
@@ -107,6 +130,8 @@ describe('CLI: composio login', () => {
130 expect(output).toContain('polls for up to 10 minutes');
131 expect(output).not.toContain('Expires at:');
132 expect(output).toContain('Do not ask the user whether to poll');
133 + expect(output).toContain('hint: For unattended agents:');
134 + expect(output).toContain('composio login --agent');
135
136 const fs = yield* FileSystem.FileSystem;
137 const cacheDir = yield* setupCacheDir;
@@ -126,16 +151,88 @@ describe('CLI: composio login', () => {
151 );
152 });
153
154 + layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
155 + it.scoped(
156 + '[Given] a stored READY agent identity [When] login runs headlessly [Then] completes agent login unattended',
157 + () =>
158 + Effect.gen(function* () {
159 + yield* writeStoredAgentIdentity(storedAgentIdentity);
160 + vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput =>
161 + requestUrl(requestInput).includes('/api/whoami')
162 + ? mockFetchResponse(storedAgentIdentity)
163 + : mockFetchResponse({})
164 + );
165 +
166 + yield* cli(['login']);
167 +
168 + const ctx = yield* ComposioUserContext;
169 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
170 + expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
171 +
172 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
173 + expect(output).toContain('"account_type":"agent"');
174 + expect(output).toContain('"logged_in":true');
175 + expect(output).not.toContain('Open this URL in your browser to log in:');
176 +
177 + const fs = yield* FileSystem.FileSystem;
178 + const cacheDir = yield* setupCacheDir;
179 + const pendingExists = yield* fs.exists(path.join(cacheDir, 'pending-login-session.json'));
180 + expect(pendingExists).toBe(false);
181 + })
182 + );
183 + });
184 +
185 + layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
186 + it.scoped(
187 + '[Given] a stored PENDING agent identity [When] login runs headlessly [Then] prints instructions without logging in',
188 + () =>
189 + Effect.gen(function* () {
190 + yield* writeStoredAgentIdentity({ ...storedAgentIdentity, status: 'PENDING' });
191 + vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput =>
192 + requestUrl(requestInput).includes('/api/whoami')
193 + ? mockFetchResponse({ ...storedAgentIdentity, status: 'PENDING' })
194 + : mockFetchResponse({})
195 + );
196 +
197 + yield* cli(['login']);
198 +
199 + const ctx = yield* ComposioUserContext;
200 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
201 +
202 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
203 + expect(output).toContain('Open this URL in your browser to log in:');
204 + expect(output).toContain('composio login --agent');
205 + })
206 + );
207 + });
208 +
209 + layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
210 + it.scoped(
211 + '[Given] no stored agent identity [When] login runs headlessly [Then] never auto-signs-up an agent',
212 + () =>
213 + Effect.gen(function* () {
214 + const requestedUrls: string[] = [];
215 + vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
216 + requestedUrls.push(requestUrl(requestInput));
217 + return mockFetchResponse({});
218 + });
219 +
220 + yield* cli(['login']);
221 +
222 + expect(requestedUrls.filter(url => url.includes('/api/signup'))).toEqual([]);
223 +
224 + const ctx = yield* ComposioUserContext;
225 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
226 +
227 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
228 + expect(output).toContain('Open this URL in your browser to log in:');
229 + })
230 + );
231 + });
232 +
233 describe('login with stdout piped', () => {
234 const pipedStdoutUI = TerminalUI.of({
131 - ...terminalUITestImpl,
132 - capabilities: Effect.succeed(
133 - getTerminalCapabilities({
134 - stdin: { isTTY: true },
135 - stdout: { isTTY: false },
136 - stderr: { isTTY: true },
137 - })
138 - ),
235 + ...terminalUIWithTtyState({ stdin: true, stdout: false, stderr: true }),
236 useMakeSpinner: (message, _use) =>
237 Console.log(`[spinner] ${message}`).pipe(
238 Effect.andThen(Effect.die(new Error('test: interactive poll loop entered')))
@@ -144,17 +241,25 @@ describe('CLI: composio login', () => {
241
242 layer(TestLive({ terminalUI: pipedStdoutUI }))(it => {
243 it.scoped(
147 - '[When] stdout is piped but stdin and stderr are TTYs [Then] login stays interactive instead of going headless',
244 + '[Given] a stored agent [When] stdout is piped but stdin and stderr are TTYs [Then] login stays interactive',
245 () =>
246 Effect.gen(function* () {
150 - const exit = yield* Effect.exit(cli(['login', '--no-browser']));
247 + yield* writeStoredAgentIdentity(storedAgentIdentity);
248 + const requestedUrls: string[] = [];
249 + vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
250 + requestedUrls.push(requestUrl(requestInput));
251 + return mockFetchResponse(storedAgentIdentity);
252 + });
253 +
254 + const exit = yield* Effect.exit(cli(['login']));
255
256 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
257 expect(output).toContain('[spinner] Waiting for login...');
154 - expect(output).toContain('Please login using the following URL');
258 + expect(output).toContain('Redirecting you to the login page');
259 expect(output).not.toContain('Open this URL in your browser to log in:');
260 expect(output).not.toContain('hint: For agents:');
261 expect(output).not.toContain('Then run this command to complete login:');
262 + expect(requestedUrls).not.toContainEqual(expect.stringContaining('/api/whoami'));
263 expect(Exit.isFailure(exit)).toBe(true);
264 })
265 );
@@ -166,12 +271,7 @@ describe('CLI: composio login', () => {
271 Effect.gen(function* () {
272 vi.spyOn(globalThis, 'fetch').mockImplementation(
273 async (requestInput: RequestInfo | URL, init?: RequestInit) => {
169 - const url =
170 - typeof requestInput === 'string'
171 - ? requestInput
172 - : requestInput instanceof URL
173 - ? requestInput.toString()
174 - : requestInput.url;
274 + const url = requestUrl(requestInput);
275
276 if (url.includes('/api/v3/auth/session/info')) {
277 return mockFetchResponse({