Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(cli): make headless composio login agent-friendly (PRDE-1138)
Kshitij Jhunjhunwalafc1460995b2b
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 000000000..bd6341892--- /dev/null+++ b/.dockerignore@@ -0,0 +1,5 @@+# The e2e Dockerfiles (ts/e2e-tests/_utils/Dockerfile.*) pnpm-install inside+# the image; host node_modules are pnpm symlinks into a store that is not+# copied, so they must never enter the build context.+**/node_modules+.gitdiff --git a/install.sh b/install.shindex 8cade2fec..66e5a4044 100755--- a/install.sh+++ b/install.sh@@ -415,7 +415,7 @@ fiif [[ $install_agent = true ]]; thenechoinfo "Setting up Composio agent login..."- if ! "$exe" login --agent --no-skill-install; then+ if ! COMPOSIO_CLI_INVOCATION_ORIGIN=installer "$exe" login --agent --no-skill-install; thenerror '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>`.'fifidiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex fc9239132..43d3388c1 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -205,6 +205,12 @@ importers:specifier: 'catalog:'version: 7.0.2+ ts/e2e-tests/cli/agent-signin:+ devDependencies:+ '@e2e-tests/utils':+ specifier: workspace:*+ version: link:../../_utils+ts/e2e-tests/cli/setup-plugins:devDependencies:'@e2e-tests/utils':diff --git a/ts/e2e-tests/cli/agent-signin/README.md b/ts/e2e-tests/cli/agent-signin/README.mdnew file mode 100644index 000000000..3e08f5021--- /dev/null+++ b/ts/e2e-tests/cli/agent-signin/README.md@@ -0,0 +1,15 @@+# CLI agent sign-in e2e (PRDE-1138)++Asserts the headless agent onboarding contract:++- `composio login --agent` takes an unattended agent from nothing to an+ authenticated CLI (mocked `agents.composio.dev` via+ `COMPOSIO_AGENTS_BASE_URL`), verified with a follow-up `composio whoami`.+- A plain piped `composio login` prints the OAuth URL + poll instructions,+ offers the `composio login --agent` path for unattended agents, and never+ auto-creates an account (guardrail: humans in pipes are not signed up).+- A stored READY agent identity (`agent.json`) lets plain headless+ `composio login` complete unattended by reuse, without signup.++All network surfaces are mocked by+`ts/packages/cli/scripts/mock-agents-server.ts`; no real accounts are created.diff --git a/ts/e2e-tests/cli/agent-signin/e2e.test.ts b/ts/e2e-tests/cli/agent-signin/e2e.test.tsnew file mode 100644index 000000000..290d35f10--- /dev/null+++ b/ts/e2e-tests/cli/agent-signin/e2e.test.ts@@ -0,0 +1,126 @@+/**+ * CLI agent sign-in e2e test (PRDE-1138)+ *+ * A headless agent must reach an authenticated CLI without human action, and+ * a human piping `composio login` must never be auto-signed-up as an agent.+ */++import { e2e, type E2ETestResult } from '@e2e-tests/utils';+import { TIMEOUTS } from '@e2e-tests/utils/const';+import { afterAll, beforeAll, describe, expect, it } from 'bun:test';+import {+ startMockAgentsServer,+ type MockAgentsServer,+} from '../../../packages/cli/scripts/mock-agents-server';++const CACHE_DIR = '/tmp/composio-agent-signin';++/** Parses the last stdout line as JSON — the `composio whoami` payload. */+const lastJsonLine = (stdout: string): Record<string, unknown> =>+ JSON.parse(stdout.trim().split('\n').at(-1) ?? '{}') as Record<string, unknown>;++const envPrefix = (server: MockAgentsServer): string =>+ [+ `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,+ `COMPOSIO_AGENTS_BASE_URL=${server.dockerBaseUrl}`,+ `COMPOSIO_CACHE_DIR=${CACHE_DIR}`,+ ].join(' ');++e2e(import.meta.url, {+ versions: {+ cli: ['current'],+ },+ defineTests: ({ runCmd }) => {+ let signupServer: MockAgentsServer;+ let guardrailServer: MockAgentsServer;+ let reuseServer: MockAgentsServer;+ let unattendedSignup: E2ETestResult;+ let headlessHumanLogin: E2ETestResult;+ let storedIdentityLogin: E2ETestResult;++ beforeAll(async () => {+ signupServer = await startMockAgentsServer();+ guardrailServer = await startMockAgentsServer();+ reuseServer = await startMockAgentsServer();++ unattendedSignup = await runCmd(+ `${envPrefix(signupServer)} composio login --agent --no-skill-install && ${envPrefix(signupServer)} composio whoami`+ );++ headlessHumanLogin = await runCmd(`${envPrefix(guardrailServer)} composio login`);++ const storedIdentity = JSON.stringify(reuseServer.agentIdentity);+ storedIdentityLogin = await runCmd(+ [+ `mkdir -p ${CACHE_DIR}`,+ `printf '%s' '${storedIdentity}' > ${CACHE_DIR}/agent.json`,+ `${envPrefix(reuseServer)} composio login && ${envPrefix(reuseServer)} composio whoami`,+ ].join('\n')+ );+ }, TIMEOUTS.FIXTURE);++ afterAll(async () => {+ await signupServer.close();+ await guardrailServer.close();+ await reuseServer.close();+ });++ describe('composio login --agent (unattended onboarding)', () => {+ it('exits successfully', () => {+ expect(unattendedSignup.exitCode).toBe(0);+ });++ it('signs up via agents.composio.dev', () => {+ expect(signupServer.requests).toContain('POST /api/signup');+ });++ it('prints the agent login summary on stdout', () => {+ expect(unattendedSignup.stdout).toContain('"account_type":"agent"');+ expect(unattendedSignup.stdout).toContain('"logged_in":true');+ expect(unattendedSignup.stdout).toContain('"status":"READY"');+ });++ it('leaves the CLI authenticated as the agent (whoami)', () => {+ const whoami = lastJsonLine(unattendedSignup.stdout);+ expect(whoami.account_type).toBe('agent');+ });+ });++ describe('composio login (headless, no agent identity)', () => {+ it('exits successfully with instructions instead of hanging', () => {+ expect(headlessHumanLogin.exitCode).toBe(0);+ expect(headlessHumanLogin.stdout).toContain('Open this URL in your browser to log in:');+ expect(headlessHumanLogin.stdout).toContain('composio login --poll');+ });++ it('offers the unattended agent path', () => {+ expect(headlessHumanLogin.stdout).toContain('For unattended agents');+ expect(headlessHumanLogin.stdout).toContain('composio login --agent');+ });++ it('never auto-signs-up an account', () => {+ expect(guardrailServer.requests.filter(request => request.includes('/api/signup'))).toEqual(+ []+ );+ });+ });++ describe('composio login (headless, stored READY agent identity)', () => {+ it('completes login unattended by reusing the stored identity', () => {+ expect(storedIdentityLogin.exitCode).toBe(0);+ expect(storedIdentityLogin.stdout).toContain('"logged_in":true');+ expect(storedIdentityLogin.stdout).not.toContain('Open this URL in your browser');+ });++ it('refreshes the identity instead of signing up', () => {+ expect(reuseServer.requests).toContain('GET /api/whoami');+ expect(reuseServer.requests.filter(request => request.includes('/api/signup'))).toEqual([]);+ });++ it('leaves the CLI authenticated as the agent (whoami)', () => {+ const whoami = lastJsonLine(storedIdentityLogin.stdout);+ expect(whoami.account_type).toBe('agent');+ });+ });+ },+});diff --git a/ts/e2e-tests/cli/agent-signin/package.json b/ts/e2e-tests/cli/agent-signin/package.jsonnew file mode 100644index 000000000..05e220a83--- /dev/null+++ b/ts/e2e-tests/cli/agent-signin/package.json@@ -0,0 +1,14 @@+{+ "name": "@e2e-tests/cli-agent-signin",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "typecheck": "tsc --noEmit",+ "test:e2e": "bun test e2e.test.ts",+ "test:e2e:cli": "bun test e2e.test.ts"+ },+ "devDependencies": {+ "@e2e-tests/utils": "workspace:*"+ }+}diff --git a/ts/packages/cli/CHANGELOG.md b/ts/packages/cli/CHANGELOG.mdindex 12f229fe6..0d4a09e4b 100644--- a/ts/packages/cli/CHANGELOG.md+++ b/ts/packages/cli/CHANGELOG.md@@ -10,6 +10,7 @@### Minor Changes+- 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.- a0bef5d: Bump `@composio/client` to `0.1.0-alpha.74`.- 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.diff --git a/ts/packages/cli/scripts/mock-agents-server.ts b/ts/packages/cli/scripts/mock-agents-server.tsnew file mode 100644index 000000000..b7fc45a1a--- /dev/null+++ b/ts/packages/cli/scripts/mock-agents-server.ts@@ -0,0 +1,118 @@+#!/usr/bin/env bun++import { createServer, type ServerResponse } from 'node:http';++/**+ * Mock agents.composio.dev + the minimal Apollo endpoints the login flows+ * touch. Point the CLI at it via COMPOSIO_AGENTS_BASE_URL / COMPOSIO_BASE_URL.+ */++const AGENT_IDENTITY = {+ status: 'READY',+ slug: 'e2e-agent',+ email: '[email protected]',+ composio_agent_key: 'cak_e2e_agent',+ composio: {+ member_id: 'mem_e2e_agent',+ org_id: 'org_e2e_agent',+ project_id: 'proj_e2e_agent',+ user_api_key: 'uak_e2e_agent',+ },+} as const;++export interface MockAgentsServer {+ readonly hostBaseUrl: string;+ readonly dockerBaseUrl: string;+ readonly requests: string[];+ readonly agentIdentity: typeof AGENT_IDENTITY;+ readonly close: () => Promise<void>;+}++const sendJson = (res: ServerResponse, statusCode: number, body: unknown): void => {+ res.writeHead(statusCode, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(body));+};++export async function startMockAgentsServer(options?: {+ host?: string;+ port?: number;+}): Promise<MockAgentsServer> {+ const host = options?.host ?? '0.0.0.0';+ const port = options?.port ?? 0;+ const requests: string[] = [];++ const server = createServer((req, res) => {+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`);+ const method = req.method ?? 'GET';+ requests.push(`${method} ${url.pathname}`);++ // agents.composio.dev surface+ if (method === 'POST' && url.pathname === '/api/signup') {+ sendJson(res, 200, AGENT_IDENTITY);+ return;+ }++ if (method === 'GET' && url.pathname === '/api/whoami') {+ const authorized =+ req.headers.authorization === `Bearer ${AGENT_IDENTITY.composio_agent_key}`;+ sendJson(+ res,+ authorized ? 200 : 401,+ authorized ? AGENT_IDENTITY : { message: 'unauthorized' }+ );+ return;+ }++ // Apollo surface used by the default login path+ if (method === 'POST' && url.pathname === '/api/v3.1/cli/create-session') {+ sendJson(res, 200, {+ id: 'e2e00000-0000-4000-8000-000000000001',+ code: 'E2E123',+ expiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString(),+ status: 'pending',+ });+ return;+ }++ if (method === 'POST' && url.pathname === '/api/v3/cli/analytics') {+ sendJson(res, 204, {});+ return;+ }++ // Unmocked routes are non-fatal to the flows under test; 404 exercises+ // their degrade paths.+ sendJson(res, 404, { error: `Unhandled mock route: ${method} ${url.pathname}` });+ });++ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen({ host, port }, () => {+ server.off('error', reject);+ resolve();+ });+ });++ const address = server.address();+ if (address === null || typeof address === 'string') {+ throw new Error('Failed to bind mock agents server to a TCP port');+ }++ const close = () =>+ new Promise<void>((resolve, reject) => {+ server.close(error => {+ if (error) {+ reject(error);+ return;+ }+ resolve();+ });+ });++ return {+ hostBaseUrl: `http://127.0.0.1:${address.port}`,+ dockerBaseUrl: `http://host.docker.internal:${address.port}`,+ requests,+ agentIdentity: AGENT_IDENTITY,+ close,+ };+}diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.tsindex 1a4a71844..6e4149865 100644--- a/ts/packages/cli/src/commands/login.cmd.ts+++ b/ts/packages/cli/src/commands/login.cmd.ts@@ -22,8 +22,11 @@ import { APP_VERSION } from 'src/constants';import {ensureAgentSignupAllowed,getOrSignupReadyAgent,+ getStoredReadyAgent,+ isAgentIdentityForApiKey,loginWithAgentIdentity,safeAgentSummary,+ type AgentIdentity,} from 'src/services/agents';export const noBrowser = Options.boolean('no-browser').pipe(@@ -181,7 +184,9 @@ Then run this command to complete login:${params.pollCommand}-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.`;+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.++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.`;const formatPollLoginComplete = (params: {readonly email?: string;@@ -278,6 +283,15 @@ const emitLoginComplete = (params: {}});+const completeAgentLogin = (identity: AgentIdentity) =>+ Effect.gen(function* () {+ const ui = yield* TerminalUI;+ 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 }));+ });+const resolveDirectLoginOrganization = (params: {apiKey: string;baseURL: string;@@ -777,6 +791,9 @@ export const browserLogin = (params: {* Use --agent to sign up or log in using a Composio agent identity.* Use -y to skip org picker and use current org.*+ * Non-interactive default flow: prints URL + poll instructions, or logs in+ * unattended when a READY agent identity is already stored.+ ** @example* ```bash* composio login@@ -883,12 +900,7 @@ export const loginCmd = Command.make(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 }));+ yield* completeAgentLogin(identity);if (!noSkillInstall && canPrompt) {yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });}@@ -930,6 +942,25 @@ export const loginCmd = Command.make(yield* ui.log.step('Re-authenticating for multi-project support...');}+ // Reuse-only by design: headless login may complete with an existing+ // agent identity but must never auto-create one for a human in a pipe.+ // `--no-browser` and `--no-wait` opt out: both promise a specific output+ // contract (printed URL, session JSON) that silent agent reuse would replace.+ const requestedExplicitLoginFlow = noBrowser || noWait;+ if (!canPrompt && !requestedExplicitLoginFlow) {+ const storedAgent = yield* getStoredReadyAgent;+ if (Option.isSome(storedAgent)) {+ const identity = storedAgent.value;+ const activeApiKey = ctx.data.apiKey;+ if (+ Option.isNone(activeApiKey) ||+ isAgentIdentityForApiKey(identity, activeApiKey.value)+ ) {+ return yield* handleAgentAuthError(completeAgentLogin(identity));+ }+ }+ }+yield* browserLogin({scope: 'user',noBrowser,diff --git a/ts/packages/cli/src/services/agents.ts b/ts/packages/cli/src/services/agents.tsindex 0dfdb7620..2d76c0262 100644--- a/ts/packages/cli/src/services/agents.ts+++ b/ts/packages/cli/src/services/agents.ts@@ -365,6 +365,30 @@ export const resolveStoredAgentKey = Effect.gen(function* () {return agentKey;});+/**+ * Reuse-only counterpart of {@link getOrSignupReadyAgent}: refreshes and+ * returns a stored READY identity but never signs up a new agent.+ */+export const getStoredReadyAgent = Effect.gen(function* () {+ const stored = yield* readStoredAgentIdentity;+ if (Option.isNone(stored)) return Option.none<AgentIdentity>();++ const agentKey = getAgentKey(stored.value);+ if (!agentKey) return Option.none<AgentIdentity>();++ const remote = yield* fetchAgentWhoami(agentKey).pipe(Effect.option);+ const identity = Option.isSome(remote)+ ? yield* writeStoredAgentIdentity(remote.value)+ : stored.value;++ const ready =+ normalizeAgentStatus(identity.status) === 'READY' &&+ Boolean(identity.composio?.user_api_key) &&+ Boolean(identity.composio?.org_id);++ return ready ? Option.some(identity) : Option.none<AgentIdentity>();+});+export const getOrSignupReadyAgent = (params: { force?: boolean } = {}) =>Effect.gen(function* () {if (!params.force) {diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.tsindex b9d8a824c..9250ab687 100644--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts@@ -9,33 +9,61 @@ import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';import * as constants from 'src/constants';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';+import { writeStoredAgentIdentity } from 'src/services/agents';import { ComposioUserContext } from 'src/services/user-context';+vi.mock('open', () => ({+ default: vi.fn(async () => undefined),+}));+const mockFetchResponse = (body: unknown, status = 200) =>new Response(JSON.stringify(body), {status,headers: { 'Content-Type': 'application/json' },});-const setTtyState = (state: { stdin: boolean; stdout: boolean; stderr: boolean }) => {- const descriptors = {- stdin: Object.getOwnPropertyDescriptor(process.stdin, 'isTTY'),- stdout: Object.getOwnPropertyDescriptor(process.stdout, 'isTTY'),- stderr: Object.getOwnPropertyDescriptor(process.stderr, 'isTTY'),- };- Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: state.stdin });- Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: state.stdout });- Object.defineProperty(process.stderr, 'isTTY', { configurable: true, value: state.stderr });- return () => {- if (descriptors.stdin) Object.defineProperty(process.stdin, 'isTTY', descriptors.stdin);- else delete (process.stdin as { isTTY?: boolean }).isTTY;- if (descriptors.stdout) Object.defineProperty(process.stdout, 'isTTY', descriptors.stdout);- else delete (process.stdout as { isTTY?: boolean }).isTTY;- if (descriptors.stderr) Object.defineProperty(process.stderr, 'isTTY', descriptors.stderr);- else delete (process.stderr as { isTTY?: boolean }).isTTY;- };+const requestUrl = (requestInput: RequestInfo | URL): string =>+ typeof requestInput === 'string'+ ? requestInput+ : requestInput instanceof URL+ ? requestInput.toString()+ : requestInput.url;++const storedAgentIdentity = {+ 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',+ },};+const terminalUIWithTtyState = (state: {+ readonly stdin: boolean;+ readonly stdout: boolean;+ readonly stderr: boolean;+}) =>+ TerminalUI.of({+ ...terminalUITestImpl,+ capabilities: Effect.succeed(+ getTerminalCapabilities({+ stdin: { isTTY: state.stdin },+ stdout: { isTTY: state.stdout },+ stderr: { isTTY: state.stderr },+ })+ ),+ });++const headlessStdinUI = terminalUIWithTtyState({+ stdin: false,+ stdout: false,+ stderr: false,+});+// ── Tests ────────────────────────────────────────────────────────────────────describe('CLI: composio login', () => {@@ -85,15 +113,10 @@ describe('CLI: composio login', () => {);});- layer(TestLive())(it => {+ layer(TestLive({ terminalUI: headlessStdinUI }))(it => {it.scoped('[When] stdin is non-interactive [Then] login prints agent instructions', () =>Effect.gen(function* () {- const restoreTty = setTtyState({ stdin: false, stdout: true, stderr: true });- try {- yield* cli(['login']);- } finally {- restoreTty();- }+ yield* cli(['login']);const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');expect(output).toContain('Open this URL in your browser to log in:');@@ -107,6 +130,8 @@ describe('CLI: composio login', () => {expect(output).toContain('polls for up to 10 minutes');expect(output).not.toContain('Expires at:');expect(output).toContain('Do not ask the user whether to poll');+ expect(output).toContain('hint: For unattended agents:');+ expect(output).toContain('composio login --agent');const fs = yield* FileSystem.FileSystem;const cacheDir = yield* setupCacheDir;@@ -126,16 +151,88 @@ describe('CLI: composio login', () => {);});+ layer(TestLive({ terminalUI: headlessStdinUI }))(it => {+ it.scoped(+ '[Given] a stored READY agent identity [When] login runs headlessly [Then] completes agent login unattended',+ () =>+ Effect.gen(function* () {+ yield* writeStoredAgentIdentity(storedAgentIdentity);+ vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput =>+ requestUrl(requestInput).includes('/api/whoami')+ ? mockFetchResponse(storedAgentIdentity)+ : mockFetchResponse({})+ );++ yield* cli(['login']);++ const ctx = yield* ComposioUserContext;+ expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');+ expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');++ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');+ expect(output).toContain('"account_type":"agent"');+ expect(output).toContain('"logged_in":true');+ expect(output).not.toContain('Open this URL in your browser to log in:');++ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ const pendingExists = yield* fs.exists(path.join(cacheDir, 'pending-login-session.json'));+ expect(pendingExists).toBe(false);+ })+ );+ });++ layer(TestLive({ terminalUI: headlessStdinUI }))(it => {+ it.scoped(+ '[Given] a stored PENDING agent identity [When] login runs headlessly [Then] prints instructions without logging in',+ () =>+ Effect.gen(function* () {+ yield* writeStoredAgentIdentity({ ...storedAgentIdentity, status: 'PENDING' });+ vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput =>+ requestUrl(requestInput).includes('/api/whoami')+ ? mockFetchResponse({ ...storedAgentIdentity, status: 'PENDING' })+ : mockFetchResponse({})+ );++ yield* cli(['login']);++ const ctx = yield* ComposioUserContext;+ expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();++ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');+ expect(output).toContain('Open this URL in your browser to log in:');+ expect(output).toContain('composio login --agent');+ })+ );+ });++ layer(TestLive({ terminalUI: headlessStdinUI }))(it => {+ it.scoped(+ '[Given] no stored agent identity [When] login runs headlessly [Then] never auto-signs-up an agent',+ () =>+ Effect.gen(function* () {+ const requestedUrls: string[] = [];+ vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {+ requestedUrls.push(requestUrl(requestInput));+ return mockFetchResponse({});+ });++ yield* cli(['login']);++ expect(requestedUrls.filter(url => url.includes('/api/signup'))).toEqual([]);++ const ctx = yield* ComposioUserContext;+ expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();++ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');+ expect(output).toContain('Open this URL in your browser to log in:');+ })+ );+ });+describe('login with stdout piped', () => {const pipedStdoutUI = TerminalUI.of({- ...terminalUITestImpl,- capabilities: Effect.succeed(- getTerminalCapabilities({- stdin: { isTTY: true },- stdout: { isTTY: false },- stderr: { isTTY: true },- })- ),+ ...terminalUIWithTtyState({ stdin: true, stdout: false, stderr: true }),useMakeSpinner: (message, _use) =>Console.log(`[spinner] ${message}`).pipe(Effect.andThen(Effect.die(new Error('test: interactive poll loop entered')))@@ -144,17 +241,25 @@ describe('CLI: composio login', () => {layer(TestLive({ terminalUI: pipedStdoutUI }))(it => {it.scoped(- '[When] stdout is piped but stdin and stderr are TTYs [Then] login stays interactive instead of going headless',+ '[Given] a stored agent [When] stdout is piped but stdin and stderr are TTYs [Then] login stays interactive',() =>Effect.gen(function* () {- const exit = yield* Effect.exit(cli(['login', '--no-browser']));+ yield* writeStoredAgentIdentity(storedAgentIdentity);+ const requestedUrls: string[] = [];+ vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {+ requestedUrls.push(requestUrl(requestInput));+ return mockFetchResponse(storedAgentIdentity);+ });++ const exit = yield* Effect.exit(cli(['login']));const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');expect(output).toContain('[spinner] Waiting for login...');- expect(output).toContain('Please login using the following URL');+ expect(output).toContain('Redirecting you to the login page');expect(output).not.toContain('Open this URL in your browser to log in:');expect(output).not.toContain('hint: For agents:');expect(output).not.toContain('Then run this command to complete login:');+ expect(requestedUrls).not.toContainEqual(expect.stringContaining('/api/whoami'));expect(Exit.isFailure(exit)).toBe(true);}));@@ -166,12 +271,7 @@ describe('CLI: composio login', () => {Effect.gen(function* () {vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput: RequestInfo | URL, init?: RequestInit) => {- const url =- typeof requestInput === 'string'- ? requestInput- : requestInput instanceof URL- ? requestInput.toString()- : requestInput.url;+ const url = requestUrl(requestInput);if (url.includes('/api/v3/auth/session/info')) {return mockFetchResponse({