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 multi-key auth with `composio login` and `composio init` (#2738)

Alberto Schiabel105c20344901
diff --git a/plans/feat-init-project-environment-detection.md b/plans/feat-init-project-environment-detection.md
new file mode 100644
index 000000000..b31e3c7e5
--- /dev/null
+++ b/plans/feat-init-project-environment-detection.md
@@ -0,0 +1,619 @@
+# feat: Add project environment detection and dependency installation to `composio init`
+
+## Overview
+
+Enhance `composio init` to automatically detect the project environment (TypeScript/Python, package manager, monorepo vs single-package) and install Composio's SDK dependencies using the correct package manager command. This replaces the existing `EnvLangDetector` + `JsPackageManagerDetector` services with a unified `ProjectEnvironmentDetector` service that produces richer detection results, and adds a `CommandRunner` service for running install commands in tests.
+
+## Problem Statement / Motivation
+
+Currently, `composio init` writes config files but does **not**:
+- Detect what kind of project the user is working in
+- Install Composio SDK packages (`@composio/core` for TS, `composio` for Python)
+- Install framework-specific provider packages (`@composio/mastra`, `@composio/openai`, etc.)
+
+Users must manually figure out which packages to install and run the correct package manager command. This is error-prone, especially in monorepos where the package manager may differ from what the user expects.
+
+The `composio2` branch already has working implementations of `ProjectEnvironmentDetector`, `CommandRunner`, `core-dependency.ts`, and an `install.cmd.ts` with tests. This plan imports and adapts those implementations into the current `feat/cli-login-2.0` branch.
+
+## Proposed Solution
+
+### Architecture
+
+```mermaid
+graph TD
+ A[composio init] --> B[Project Selection]
+ B --> C[Init Wizard: usage mode + framework + skills]
+ C --> D[ProjectEnvironmentDetector.detectProjectEnvironment]
+ D --> E{Detected?}
+ E -->|Yes| F[Show detection + confirm]
+ E -->|Ambiguous| G[Prompt user to choose language]
+ E -->|No indicators| H[Prompt user to choose language + PM]
+ F --> I[resolveCoreDependencyState]
+ G --> I
+ H --> I
+ I --> J{Already installed?}
+ J -->|Yes, not --force| K[Skip install, log info]
+ J -->|No or --force| L[Confirm install command]
+ L --> M[CommandRunner.run with spinner]
+ M --> N[Write config files]
+ N --> O[Optionally install skills]
+```
+
+### Key Components
+
+1. **`ProjectEnvironmentDetector`** (new service) — replaces `EnvLangDetector` + `JsPackageManagerDetector` with a single service that:
+ - Walks up the directory tree looking for project indicators
+ - Produces a `ProjectEnvironment` discriminated union (`js` | `python`)
+ - Includes `language`, `packageManager`, `rootDir`, and `evidence[]`
+ - Handles ambiguity (both JS and Python indicators) with a tagged error
+ - Supports Deno (`deno.json`, `deno.lock`) as a JS package manager
+
+2. **`CommandRunner`** (new service) — thin wrapper around `@effect/platform` `Command.exitCode` for testability. In production, it runs the actual command; in tests, it returns a configurable exit code.
+
+3. **`core-dependency.ts`** (new effect) — maps a `ProjectEnvironment` to a `CoreDependencyPlan` containing the install command string, dependency name, and package manager. Also detects if the dependency is already installed.
+
+4. **Updated `init.cmd.ts`** — integrates detection + installation into the wizard flow after project selection.
+
+## Technical Approach
+
+### Phase 1: New Services and Effects
+
+#### 1.1 Add `ProjectEnvironmentDetector` service
+
+**File:** `ts/packages/cli/src/services/project-environment-detector.ts`
+
+Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/project-environment-detector.ts`
+
+The reference implementation is 587 lines and provides:
+
+```typescript
+export type ProjectEnvironment =
+ | { kind: 'js'; language: JsLanguage; packageManager: JsPackageManager; rootDir: string; evidence: string[] }
+ | { kind: 'python'; language: 'python'; packageManager: PythonPackageManager; rootDir: string; evidence: string[] };
+
+export type JsLanguage = 'typescript' | 'javascript';
+export type JsPackageManager = 'pnpm' | 'bun' | 'yarn' | 'npm' | 'deno';
+export type PythonPackageManager = 'uv' | 'pip';
+```
+
+Key detection strategies:
+- **Strong JS indicators:** `package.json`, `tsconfig.json`, `pnpm-workspace.yaml`, lock files — each gets a high score
+- **Strong Python indicators:** `pyproject.toml`, `setup.py`, `requirements.txt`, `uv.lock`, `poetry.lock`
+- **Weak indicators:** file extension counts (`.ts`, `.py`), subdirectory scans
+- **Package manager from `package.json`:** reads `packageManager` field (e.g., `"[email protected]"`)
+- **Python package manager:** checks for `uv.lock` or `[tool.uv]` in `pyproject.toml`
+- **Ancestor walking:** walks up from CWD to filesystem root, checking each directory
+
+**Ambiguity handling:** If both JS and Python strong indicators exist at CWD depth 0, fails with `ProjectEnvironmentDetectorError`. At deeper levels, skips and continues searching.
+
+**Service pattern:** Uses `Effect.Service` class with `effect:` body and `dependencies: [BunFileSystem.layer]`.
+
+#### 1.2 Add `CommandRunner` service
+
+**File:** `ts/packages/cli/src/services/command-runner.ts`
+
+Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/command-runner.ts`
+
+```typescript
+import { Command } from '@effect/platform';
+import { Effect } from 'effect';
+
+export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {
+ sync: () => ({
+ run: (command: Command.Command) => Command.exitCode(command),
+ }),
+ dependencies: [],
+}) {}
+```
+
+This is intentionally thin — the real value is in testability. In tests, we provide `Layer.succeed(CommandRunner, new CommandRunner({ run: () => Effect.succeed(ExitCode(0)) }))`.
+
+#### 1.3 Add `core-dependency.ts` effect
+
+**File:** `ts/packages/cli/src/effects/core-dependency.ts`
+
+Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/effects/core-dependency.ts`
+
+Key exports:
+- `CoreDependencyPlan` — discriminated union with `installCommand`, `dependency`, `packageManager`, `rootDir`
+- `detectCoreDependencyPlan(cwd)` — maps `ProjectEnvironment` → `CoreDependencyPlan`
+- `detectCoreDependencyVersion(plan)` — checks if `@composio/core` or `composio` is already installed
+- `resolveCoreDependencyState(cwd)` — combines plan + version check
+- `getJsInstallCommand(pm, dependency)` — maps package manager to install command
+- `getPythonInstallCommand(pm, dependency)` — same for Python
+
+Install command mapping:
+
+| PM | Command |
+|---|---|
+| pnpm | `pnpm add @composio/core` |
+| bun | `bun add @composio/core` |
+| yarn | `yarn add @composio/core` |
+| npm | `npm install -S @composio/core` |
+| deno | `deno add npm:@composio/core` |
+| uv | `uv pip install composio` |
+| pip | `pip install composio` |
+
+### Phase 2: Update `composio init` Command
+
+#### 2.1 Add new CLI flags
+
+```typescript
+const dryRunOpt = Options.boolean('dry-run').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Print install command without executing it')
+);
+
+const forceOpt = Options.boolean('force').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Reinstall even if dependency appears installed')
+);
+
+const yesOpt = Options.boolean('yes').pipe(
+ Options.withAlias('y'),
+ Options.withDefault(false),
+ Options.withDescription('Skip confirmation prompts')
+);
+```
+
+#### 2.2 Extend `InitConfigBuilder` and `InitConfig`
+
+Add new builder steps and fields:
+
+```typescript
+interface InitConfig {
+ readonly usageMode: UsageMode;
+ readonly framework: NativeFramework | undefined;
+ readonly installSkills: boolean;
+ readonly detectedEnv: ProjectEnvironment; // NEW
+ readonly installPlan: CoreDependencyPlan; // NEW
+}
+```
+
+Add `withDetectedEnv` and `withInstallPlan` methods to `InitConfigBuilder`, and update the `build()` type constraint.
+
+#### 2.3 Updated wizard flow
+
+After the existing wizard steps (usage mode → framework → skills), add:
+
+```typescript
+// Step 4: Detect project environment
+const envDetector = yield* ProjectEnvironmentDetector;
+const detectedEnv = yield* envDetector
+ .detectProjectEnvironment(proc.cwd)
+ .pipe(
+ Effect.catchTag('services/ProjectEnvironmentDetectorError', e =>
+ Effect.gen(function* () {
+ yield* ui.log.warn(e.message);
+ // Fallback: ask user to choose
+ const lang = yield* ui.select('What language is your project?', [
+ { value: 'typescript', label: 'TypeScript' },
+ { value: 'python', label: 'Python' },
+ ]);
+ // ... prompt for package manager too
+ })
+ )
+ );
+
+yield* ui.log.step(`Detected: ${detectedEnv.language} (${detectedEnv.packageManager})`);
+
+// Step 5: Check if already installed + determine install plan
+const { plan, installedVersion } = yield* resolveCoreDependencyState(proc.cwd);
+
+if (installedVersion && !forceOpt) {
+ yield* ui.log.info(`Found ${plan.dependency}: ${installedVersion.version}`);
+ yield* ui.log.success('Dependency already installed.');
+} else {
+ // Step 6: Confirm and install
+ if (dryRunOpt) {
+ yield* ui.note(plan.installCommand, 'Install Command');
+ } else {
+ const shouldInstall = yesOpt || (yield* ui.confirm(`Run: ${plan.installCommand}?`));
+ if (shouldInstall) {
+ yield* ui.withSpinner(`Installing ${plan.dependency}...`, installEffect, {
+ successMessage: `Installed ${plan.dependency}`,
+ });
+ }
+ }
+}
+```
+
+#### 2.4 Framework provider installation
+
+When a framework is selected (not "skip"), also install the provider package:
+
+```typescript
+const frameworkPackage = getFrameworkPackage(config.framework, detectedEnv);
+// e.g., '@composio/mastra' for TS, 'composio[mastra]' for Python
+```
+
+| Framework | TS Package | Python Package |
+|---|---|---|
+| ai-sdk | `@composio/vercel` | `composio[vercel]` |
+| mastra | `@composio/mastra` | `composio[mastra]` |
+| openai-agents | `@composio/openai` | `composio[openai]` |
+| claude-agent-sdk | `@composio/anthropic` | `composio[anthropic]` |
+
+### Phase 3: Wire Services in Layer Composition
+
+#### 3.1 Update `bin.ts`
+
+Add to the layer composition:
+
+```typescript
+import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
+import { CommandRunner } from 'src/services/command-runner';
+
+const layers = Layer.mergeAll(
+ // ... existing layers ...
+ ProjectEnvironmentDetector.Default, // NEW
+ CommandRunner.Default, // NEW
+);
+```
+
+#### 3.2 Deprecate `EnvLangDetector` and `JsPackageManagerDetector`
+
+The new `ProjectEnvironmentDetector` subsumes both. However, `EnvLangDetector` is still used by `generate.cmd.ts`. Options:
+
+- **Option A (recommended):** Keep both old services for now, use `ProjectEnvironmentDetector` only in `init.cmd.ts`. Migrate `generate.cmd.ts` in a follow-up PR.
+- **Option B:** Replace both immediately and update `generate.cmd.ts` to use the new service.
+
+Go with **Option A** to keep this PR focused.
+
+### Phase 4: Testing (TDD)
+
+#### 4.1 Unit tests for `ProjectEnvironmentDetector`
+
+**File:** `ts/packages/cli/test/src/services/project-environment-detector.test.ts`
+
+Uses `tempy.temporaryDirectory()` to create isolated temp dirs with specific file layouts. Tests use `BunFileSystem.layer` (real filesystem).
+
+```
+describe('ProjectEnvironmentDetector', () => {
+ describe('detectProjectEnvironment', () => {
+ // TypeScript detection
+ it('[Given] package.json + tsconfig.json [Then] detects typescript + npm')
+ it('[Given] pnpm-lock.yaml + package.json with packageManager:pnpm@ [Then] detects typescript + pnpm')
+ it('[Given] bun.lockb [Then] detects javascript + bun')
+ it('[Given] deno.json [Then] detects typescript + deno')
+ it('[Given] package.json with typescript dep [Then] detects typescript')
+
+ // Python detection
+ it('[Given] pyproject.toml with [tool.uv] [Then] detects python + uv')
+ it('[Given] requirements.txt only [Then] detects python + pip')
+ it('[Given] uv.lock [Then] detects python + uv')
+ it('[Given] setup.py only [Then] detects python + pip')
+
+ // Ambiguity
+ it('[Given] both package.json + pyproject.toml at CWD [Then] fails with ambiguity error')
+ it('[Given] both indicators but only at parent level [Then] skips and continues')
+
+ // Ancestor walking
+ it('[Given] indicators at parent directory [Then] detects from parent')
+ it('[Given] no indicators anywhere [Then] fails with no-detection error')
+
+ // File extension fallback
+ it('[Given] only .ts files, no config files [Then] detects typescript via weak signals')
+ it('[Given] only .py files, no config files [Then] detects python via weak signals')
+
+ // Edge cases
+ it('[Given] empty directory [Then] fails with no-detection error')
+ it('[Given] monorepo root with pnpm-workspace.yaml [Then] detects pnpm')
+ })
+
+ describe('detectJsPackageManager', () => {
+ it('[Given] packageManager field in package.json [Then] uses that')
+ it('[Given] lock file present [Then] detects from lock file')
+ it('[Given] no lock file, no packageManager field [Then] defaults to npm')
+ })
+
+ describe('detectPythonPackageManager', () => {
+ it('[Given] uv.lock present [Then] detects uv')
+ it('[Given] [tool.uv] in pyproject.toml [Then] detects uv')
+ it('[Given] no uv indicators [Then] defaults to pip')
+ })
+})
+```
+
+#### 4.2 Unit tests for `core-dependency.ts`
+
+**File:** `ts/packages/cli/test/src/effects/core-dependency.test.ts`
+
+```
+describe('core-dependency', () => {
+ describe('getJsInstallCommand', () => {
+ it('[Given] pnpm [Then] returns "pnpm add <dep>"')
+ it('[Given] npm [Then] returns "npm install -S <dep>"')
+ it('[Given] yarn [Then] returns "yarn add <dep>"')
+ it('[Given] bun [Then] returns "bun add <dep>"')
+ it('[Given] deno [Then] returns "deno add npm:<dep>"')
+ })
+
+ describe('getPythonInstallCommand', () => {
+ it('[Given] uv [Then] returns "uv pip install <dep>"')
+ it('[Given] pip [Then] returns "pip install <dep>"')
+ })
+
+ describe('detectCoreDependencyPlan', () => {
+ it('[Given] TS project [Then] plans @composio/core install')
+ it('[Given] Python project [Then] plans composio install')
+ })
+
+ describe('detectCoreDependencyVersion', () => {
+ it('[Given] @composio/core in node_modules [Then] returns version')
+ it('[Given] @composio/core in pnpm virtual store [Then] returns version')
+ it('[Given] not installed [Then] returns null')
+ })
+})
+```
+
+#### 4.3 Command tests for `composio init`
+
+**File:** `ts/packages/cli/test/src/commands/init.cmd.test.ts`
+
+Uses `TestLive` with fixtures and mocked services.
+
+```
+describe('CLI: composio init', () => {
+ // Agent-native path (--org-id + --project-id)
+ describe('[Given] --org-id + --project-id flags', () => {
+ layer(TestLive({ fixture: 'typescript-project' }))(it => {
+ it.scoped('[Then] detects TS project and shows install plan', () => ...)
+ })
+
+ layer(TestLive({ fixture: 'python-project' }))(it => {
+ it.scoped('[Then] detects Python project and shows install plan', () => ...)
+ })
+ })
+
+ // Dry-run mode
+ describe('[Given] --dry-run flag', () => {
+ layer(TestLive({ fixture: 'typescript-project' }))(it => {
+ it.scoped('[Then] prints install command without executing', () => ...)
+ })
+ })
+
+ // Already installed
+ describe('[Given] @composio/core already in node_modules', () => {
+ layer(TestLive({ fixture: 'typescript-project-with-composio-core' }))(it => {
+ it.scoped('[Then] skips install', () => ...)
+ })
+ })
+
+ // --force reinstall
+ describe('[Given] --force flag with dependency installed', () => {
+ layer(TestLive({ fixture: 'typescript-project-with-composio-core', commandRunner: successRunner }))(it => {
+ it.scoped('[Then] reinstalls', () => ...)
+ })
+ })
+
+ // Install failure
+ describe('[Given] install command fails', () => {
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: failRunner }))(it => {
+ it.scoped('[Then] shows error message', () => ...)
+ })
+ })
+})
+```
+
+#### 4.4 New test fixtures needed
+
+```
+test/__fixtures__/
+ typescript-project/ # EXISTING: package.json + tsconfig.json
+ python-project/ # EXISTING: requirements.txt + setup.py
+ typescript-project-with-composio-core/ # EXISTING
+ python-project-with-composio-core/ # EXISTING
+ typescript-pnpm-monorepo/ # NEW: pnpm-workspace.yaml + package.json with packageManager:pnpm@
+ typescript-bun-project/ # NEW: bun.lockb + package.json
+ python-uv-project/ # NEW: pyproject.toml with [tool.uv] + uv.lock
+ ambiguous-project/ # NEW: package.json + pyproject.toml (for error case)
+```
+
+#### 4.5 Test layer updates
+
+Update `TestLive` interface to accept optional overrides:
+
+```typescript
+interface TestLiveInput {
+ // ... existing fields ...
+ commandRunner?: CommandRunner; // NEW: mock for CommandRunner
+ terminalUI?: TerminalUI; // NEW: override TerminalUI for custom prompt behavior
+}
+```
+
+Add `ProjectEnvironmentDetector.Default` and `CommandRunner.Default` (or mock) to the test layer composition.
+
+### Phase 5: E2E Tests
+
+#### 5.1 `composio init` deterministic E2E test
+
+**Directory:** `ts/e2e-tests/cli/init/`
+
+**Constraint:** E2E tests run inside Docker containers. The init command requires API access for project listing, which makes it hard to test end-to-end without mocking.
+
+**Deterministic test strategy:** Use `--org-id` + `--project-id` flags to bypass API calls. Pre-create a fixture project directory inside the Docker container.
+
+```typescript
+// ts/e2e-tests/cli/init/e2e.test.ts
+e2e(import.meta.url, {
+ versions: { cli: ['current'] },
+ defineTests: ({ runCmd }) => {
+ describe('composio init --dry-run', () => {
+ it('detects TypeScript project', async () => {
+ // Create a minimal TS project in the container
+ await runCmd('mkdir -p /tmp/test-ts && echo \'{"name":"test"}\' > /tmp/test-ts/package.json');
+ await runCmd('echo \'{}\' > /tmp/test-ts/tsconfig.json');
+
+ const result = await runCmd(
+ 'cd /tmp/test-ts && composio init --org-id test-org --project-id test-proj --dry-run'
+ );
+
+ expect(result.exitCode).toBe(0);
+ // In non-interactive (piped) mode, output() writes JSON to stdout
+ expect(result.stdout).toContain('typescript');
+ });
+ });
+
+ describe('composio init on Python project', () => {
+ it('detects Python project', async () => {
+ await runCmd('mkdir -p /tmp/test-py && echo "composio" > /tmp/test-py/requirements.txt');
+
+ const result = await runCmd(
+ 'cd /tmp/test-py && composio init --org-id test-org --project-id test-proj --dry-run'
+ );
+
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain('python');
+ });
+ });
+ },
+});
+```
+
+**Note:** The init command's interactive prompts are automatically skipped in piped mode (TerminalUI returns defaults). The `--dry-run` flag prevents actual package installation.
+
+## Alternative Approaches Considered
+
+### A. Extend existing `EnvLangDetector` + `JsPackageManagerDetector`
+
+**Rejected because:** The existing services have separate interfaces that would need to be called independently and manually composed. The `ProjectEnvironmentDetector` provides a single, unified detection result with richer evidence tracking and proper ambiguity handling.
+
+### B. Separate `composio install` command
+
+**Reference:** The `composio2` branch already has a standalone `install.cmd.ts`.
+
+**Decision:** Both approaches have merit. The `composio init` command should include dependency installation as part of the initialization flow. A separate `composio install` command could be added later for re-installation or CI use. This plan focuses on integrating detection + installation into `init`.
+
+### C. Use `Effect.Service` class vs `Context.Tag` for new services
+
+**Decision:** Use `Effect.Service` class pattern (newer pattern) for consistency with `EnvLangDetector`, `JsPackageManagerDetector`, `NodeOs`, `NodeProcess`.
+
+## Acceptance Criteria
+
+### Functional Requirements
+
+- [ ] `composio init` detects TypeScript projects (from `tsconfig.json`, `package.json`, lock files)
+- [ ] `composio init` detects Python projects (from `pyproject.toml`, `setup.py`, `requirements.txt`)
+- [ ] `composio init` detects the correct package manager (pnpm, npm, yarn, bun, deno, uv, pip)
+- [ ] `composio init` walks up the directory tree to find project root (monorepo support)
+- [ ] `composio init` shows the detected environment and asks for confirmation before installing
+- [ ] `composio init` runs the correct install command (`pnpm add`, `npm install`, `uv pip install`, etc.)
+- [ ] `composio init --dry-run` prints the install command without executing
+- [ ] `composio init --force` reinstalls even if dependency is already present
+- [ ] `composio init --yes` skips confirmation prompts
+- [ ] `composio init` shows appropriate error messages when detection fails (ambiguous or empty project)
+- [ ] `composio init` gracefully handles install command failures
+- [ ] `composio init` skips installation when dependency is already installed (without `--force`)
+- [ ] `composio init` emits structured JSON to stdout when piped (agent-native)
+- [ ] `composio init` writes `detectedEnv` info to `.composio/config.json`
+
+### Non-Functional Requirements
+
+- [ ] `pnpm typecheck` passes from repo root
+- [ ] All existing tests continue to pass
+- [ ] Detection completes in < 500ms for typical projects (filesystem I/O only, no network)
+
+### Quality Gates
+
+- [ ] Unit tests for `ProjectEnvironmentDetector` covering all detection strategies
+- [ ] Unit tests for `core-dependency.ts` covering all package managers
+- [ ] Command tests for `composio init` covering happy path + error cases
+- [ ] At least one E2E test for `composio init --dry-run` in Docker container
+- [ ] New test fixtures for pnpm monorepo, bun project, uv project, ambiguous project
+
+## Success Metrics
+
+- Users can run `composio init` in any TypeScript or Python project and have dependencies installed automatically
+- Zero manual `npm install` / `pnpm add` / `uv pip install` steps needed after init
+- Package manager is correctly detected in monorepo setups (pnpm workspaces, etc.)
+
+## Dependencies & Prerequisites
+
+- `@effect/platform` `Command` module is already a dependency of the CLI package
+- The `composio2` reference implementations are available at `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/`
+- Test fixtures for `typescript-project` and `python-project` already exist
+
+## Risk Analysis & Mitigation
+
+| Risk | Impact | Mitigation |
+|---|---|---|
+| Ambiguous project detection (both TS + Python) | User confusion | Prompt user to choose, provide clear error message with evidence |
+| Install command fails (network, permissions) | Blocked init flow | Show error with the failing command, suggest manual install |
+| Package manager not installed on system | Install fails | Check binary existence before running, suggest install |
+| Monorepo: init from subdirectory | Wrong root dir detected | Ancestor walking already handles this; root dir = where lock file or package.json with workspaces lives |
+| Breaking existing `generate.cmd.ts` | Regression | Keep old services (Option A), migrate generate in follow-up PR |
+
+## Implementation Phases
+
+### Phase 1: Foundation (Services + Effects)
+- [x] Add `ProjectEnvironmentDetector` service (`src/services/project-environment-detector.ts`)
+- [x] Add `CommandRunner` service (`src/services/command-runner.ts`)
+- [x] Add `core-dependency.ts` effect (`src/effects/core-dependency.ts`)
+- [x] Wire new services in `bin.ts` layer composition
+- [x] Add new test fixtures (pnpm monorepo, bun project, uv project, ambiguous)
+
+### Phase 2: Unit Tests (TDD Red)
+- [x] Write `ProjectEnvironmentDetector` tests (17 test cases)
+- [x] Write `core-dependency.ts` tests (7 test cases)
+- [x] All tests pass (green)
+
+### Phase 3: Update `composio init` (Green)
+- [x] Add `--dry-run`, `--force`, `--yes` flags to init command
+- [x] Extend `InitConfigBuilder` with `withDetectedEnv` and `withInstallPlan`
+- [x] Integrate detection into the wizard flow
+- [x] Integrate installation with spinner and error handling
+- [x] Update structured JSON output to include detection info
+- [x] Update `.composio/config.json` to include detection info
+
+### Phase 4: Command Tests
+- [x] Write `init.cmd.test.ts` command tests (8 scenarios)
+- [x] Update `TestLive` to support `commandRunner` and `terminalUI` overrides
+- [x] Add `ProjectEnvironmentDetector.Default` to test layer
+
+### Phase 5: E2E Tests
+- [ ] Add `ts/e2e-tests/cli/init/` E2E test suite (deferred to follow-up PR)
+- [ ] Test `--dry-run` mode with TS and Python fixtures in Docker (deferred)
+- [ ] Update `ts/e2e-tests/cli/README.md` with new test info (deferred)
+
+### Phase 6: Cleanup
+- [x] Run `pnpm typecheck` and fix any issues
+- [x] Run full test suite and fix regressions
+- [ ] Update `CLAUDE.md` if needed (document new services)
+
+## Future Considerations
+
+- **`composio install` as standalone command** — extract install logic for re-use outside init
+- **Framework provider installation** — add framework-specific packages based on wizard selection
+- **Skills installation** — run `npx skills add ComposioHQ/skills` when `installSkills: true`
+- **Migrate `generate.cmd.ts`** — replace `EnvLangDetector` usage with `ProjectEnvironmentDetector`
+- **Deno support** — handle `deno add npm:@composio/core` pattern
+
+## References & Research
+
+### Internal References
+
+- Current `composio init`: `ts/packages/cli/src/commands/init.cmd.ts`
+- Existing `EnvLangDetector`: `ts/packages/cli/src/services/env-lang-detector.ts`
+- Existing `JsPackageManagerDetector`: `ts/packages/cli/src/services/js-package-manager-detector.ts`
+- Layer composition: `ts/packages/cli/src/bin.ts` (lines 93-112)
+- Test infrastructure: `ts/packages/cli/test/__utils__/services/test-layer.ts`
+- E2E test framework: `ts/e2e-tests/cli/README.md`
+- Login command tests (pattern reference): `ts/packages/cli/test/src/commands/login.cmd.test.ts`
+
+### Reference Implementations (composio2)
+
+- `ProjectEnvironmentDetector`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/project-environment-detector.ts`
+- `CommandRunner`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/command-runner.ts`
+- `core-dependency.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/effects/core-dependency.ts`
+- `install.cmd.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/commands/install.cmd.ts`
+- `install.cmd.test.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/test/src/commands/install.cmd.test.ts`
+- `TerminalUI` with prompts: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/terminal-ui.ts`
+
+### External References
+
+- Effect.ts Service pattern: `ts/vendor/effect/packages/effect/src/`
+- @effect/cli Command: `ts/vendor/effect/packages/cli/src/Command.ts`
+- @effect/platform FileSystem: `ts/vendor/effect/packages/platform/src/FileSystem.ts`
+- @effect/platform Command (subprocess): `ts/vendor/effect/packages/platform/src/Command.ts`
+- @clack/prompts: `ts/vendor/clack/packages/prompts/src/`
diff --git a/ts/packages/cli/src/bin.ts b/ts/packages/cli/src/bin.ts
index c23096fa6..e2af4be04 100644
--- a/ts/packages/cli/src/bin.ts
+++ b/ts/packages/cli/src/bin.ts
@@ -17,13 +17,15 @@ import {
import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
import { NodeOs } from 'src/services/node-os';
import { NodeProcess } from 'src/services/node-process';
-import { EnvLangDetector } from 'src/services/env-lang-detector';
import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
import { UpgradeBinary } from 'src/services/upgrade-binary';
import { TerminalUILive } from 'src/services/terminal-ui';
import { TriggersRealtime } from 'src/services/triggers-realtime';
import { ToolsExecutorLive as _ToolsExecutorLive } from 'src/services/tools-executor';
+import { ProjectContext } from 'src/services/project-context';
+import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
+import { CommandRunner } from 'src/services/command-runner';
import { StdinLive } from 'src/services/stdin';
/**
@@ -84,6 +86,11 @@ export const ToolsExecutorLive = Layer.provide(
ComposioClientSingletonLive
) satisfies RequiredLayer;
+export const ProjectContextLive = Layer.provide(
+ ProjectContext.Default,
+ Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
+) satisfies RequiredLayer;
+
const layers = Layer.mergeAll(
CliConfigLive.pipe(Layer.provide(ConfigLive)),
NodeOs.Default,
@@ -94,9 +101,11 @@ const layers = Layer.mergeAll(
ComposioClientSingletonLive, // Expose ComposioClientSingleton for commands that use Tool Router directly
ComposioToolkitsRepositoryCachedLive, // Use the cached layer instead of the regular one
ToolsExecutorLive,
- EnvLangDetector.Default,
JsPackageManagerDetector.Default,
+ ProjectEnvironmentDetector.Default,
+ CommandRunner.Default,
TriggersRealtimeLive,
+ ProjectContextLive,
BunContext.layer,
BunFileSystem.layer,
StdinLive,
diff --git a/ts/packages/cli/src/commands/generate.cmd.ts b/ts/packages/cli/src/commands/generate.cmd.ts
index 795b299f3..4a8329060 100644
--- a/ts/packages/cli/src/commands/generate.cmd.ts
+++ b/ts/packages/cli/src/commands/generate.cmd.ts
@@ -1,6 +1,6 @@
import { Command, Options } from '@effect/cli';
import { Effect, Match } from 'effect';
-import { EnvLangDetector } from 'src/services/env-lang-detector';
+import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
import { NodeProcess } from 'src/services/node-process';
import { TerminalUI } from 'src/services/terminal-ui';
import { generateTypescriptTypeStubs } from './ts/commands/ts.generate.cmd';
@@ -43,13 +43,14 @@ export const generateCmd = Command.make('generate', { outputOpt, typeTools, tool
const cwd = process.cwd;
yield* Effect.logDebug('Identifying project type...');
- const envLangDetector = yield* EnvLangDetector;
- const envLang = yield* envLangDetector.detectEnvLanguage(cwd);
- yield* ui.log.step(`Project type detected: ${envLang}`);
+ const envDetector = yield* ProjectEnvironmentDetector;
+ const env = yield* envDetector.detectProjectEnvironment(cwd);
+ const displayLang = env.kind === 'js' ? 'TypeScript' : 'Python';
+ yield* ui.log.step(`Project type detected: ${displayLang}`);
// Redirect to either `ts generate` or `py generate` commands
- yield* Match.value(envLang).pipe(
- Match.when('TypeScript', () =>
+ yield* Match.value(env.kind).pipe(
+ Match.when('js', () =>
generateTypescriptTypeStubs({
outputOpt,
compact: false,
@@ -58,7 +59,7 @@ export const generateCmd = Command.make('generate', { outputOpt, typeTools, tool
toolkitsOpt,
})
),
- Match.when('Python', () => generatePythonTypeStubs({ outputOpt, toolkitsOpt })),
+ Match.when('python', () => generatePythonTypeStubs({ outputOpt, toolkitsOpt })),
Match.exhaustive
);
})
diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.ts
index edf56e732..578fbf4ff 100644
--- a/ts/packages/cli/src/commands/index.ts
+++ b/ts/packages/cli/src/commands/index.ts
@@ -8,6 +8,7 @@ import { upgradeCmd } from './upgrade.cmd';
import { whoamiCmd } from './whoami.cmd';
import { loginCmd } from './login.cmd';
import { logoutCmd } from './logout.cmd';
+import { initCmd } from './init.cmd';
import { pyCmd } from './py/py.cmd';
import { tsCmd } from './ts/ts.cmd';
import { generateCmd } from './generate.cmd';
@@ -24,6 +25,7 @@ const $cmd = $defaultCmd.pipe(
whoamiCmd,
loginCmd,
logoutCmd,
+ initCmd,
generateCmd,
pyCmd,
tsCmd,
diff --git a/ts/packages/cli/src/commands/init.cmd.ts b/ts/packages/cli/src/commands/init.cmd.ts
new file mode 100644
index 000000000..cabe4922a
--- /dev/null
+++ b/ts/packages/cli/src/commands/init.cmd.ts
@@ -0,0 +1,693 @@
+import path from 'node:path';
+import { Command as CliCommand, Options } from '@effect/cli';
+import { Command as PlatformCommand } from '@effect/platform';
+import { Effect, Option } from 'effect';
+import { FileSystem } from '@effect/platform';
+import { ComposioUserContext } from 'src/services/user-context';
+import { NodeProcess } from 'src/services/node-process';
+import { projectKeysToJSON, type ProjectKeys } from 'src/models/project-keys';
+import { listOrgProjects, type OrgProject } from 'src/services/composio-clients';
+import * as constants from 'src/constants';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { browserLogin, noBrowser as noBrowserOpt } from 'src/commands/login.cmd';
+import {
+ ProjectEnvironmentDetector,
+ type ProjectEnvironment,
+} from 'src/services/project-environment-detector';
+import { CommandRunner } from 'src/services/command-runner';
+import {
+ detectCoreDependencyPlan,
+ resolveCoreDependencyState,
+ type CoreDependencyPlan,
+} from 'src/effects/core-dependency';
+
+/**
+ * `composio init` — Initialize a Composio project in the current directory.
+ *
+ * ## Behavior
+ *
+ * 1. **Project selection** — fetches projects from the API or accepts `--org-id`/`--project-id`.
+ * 2. **Usage mode** — asks "Native tools" vs "Composio MCP".
+ * 3. **Framework** — if native, asks which agent framework.
+ * 4. **Coding-agent skills** — asks whether to install Composio skills.
+ * 5. **Environment detection** — detects language (TS/Python) and package manager.
+ * 6. **Dependency installation** — installs `@composio/core` or `composio` via detected PM.
+ * 7. **Writes config** — saves `<cwd>/.composio/project.json` and `<cwd>/.composio/config.json`.
+ *
+ * ## Flags
+ *
+ * - `--dry-run` — print install command without executing
+ * - `--force` — reinstall even if dependency is already present
+ * - `--yes` / `-y` — skip confirmation prompts
+ */
+
+const orgIdOpt = Options.text('org-id').pipe(
+ Options.optional,
+ Options.withDescription('Organization ID (skip interactive picker)')
+);
+
+const projectIdOpt = Options.text('project-id').pipe(
+ Options.optional,
+ Options.withDescription('Project ID (skip interactive picker)')
+);
+
+const dryRunOpt = Options.boolean('dry-run').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Print install command without executing it')
+);
+
+const forceOpt = Options.boolean('force').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Reinstall even if dependency appears installed')
+);
+
+const yesOpt = Options.boolean('yes').pipe(
+ Options.withAlias('y'),
+ Options.withDefault(false),
+ Options.withDescription('Skip confirmation prompts')
+);
+
+const noSkillsOpt = Options.boolean('no-skills').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Skip Composio skills installation')
+);
+
+// ---------------------------------------------------------------------------
+// Init config types and options
+// ---------------------------------------------------------------------------
+
+type UsageMode = 'native' | 'mcp';
+type NativeFramework = 'skip' | 'ai-sdk' | 'mastra' | 'openai-agents' | 'claude-agent-sdk';
+
+const USAGE_MODE_OPTIONS: ReadonlyArray<{
+ value: UsageMode;
+ label: string;
+ hint: string;
+}> = [
+ {
+ value: 'native',
+ label: 'Native tools',
+ hint: 'Use with Agent frameworks: AI SDK, Mastra, etc.',
+ },
+ {
+ value: 'mcp',
+ label: 'Composio MCP',
+ hint: 'Use Composio tools via MCP',
+ },
+];
+
+const NATIVE_FRAMEWORK_OPTIONS: ReadonlyArray<{
+ value: NativeFramework;
+ label: string;
+}> = [
+ { value: 'skip', label: 'Skip' },
+ { value: 'ai-sdk', label: 'AI SDK' },
+ { value: 'mastra', label: 'Mastra' },
+ { value: 'openai-agents', label: 'OpenAI Agents' },
+ { value: 'claude-agent-sdk', label: 'Claude Agent SDK' },
+];
+
+// ---------------------------------------------------------------------------
+// InitConfig — type-safe builder for the init wizard answers
+// ---------------------------------------------------------------------------
+
+/**
+ * Immutable config object built step-by-step through the init wizard.
+ * Each `.with*` method returns a new instance with the added field,
+ * narrowing the type so downstream code can rely on what has been set.
+ *
+ * The builder enforces that `build()` can only be called once ALL wizard
+ * steps have been completed — calling it too early is a compile-time error.
+ *
+ * Future wizard steps (e.g., detected environment, dependency list) can be
+ * added by introducing new `with*` methods and extending the `build()`
+ * constraint.
+ */
+class InitConfigBuilder<T extends Record<string, unknown> = Record<string, never>> {
+ private constructor(private readonly data: T) {}
+
+ static create(): InitConfigBuilder {
+ return new InitConfigBuilder({});
+ }
+
+ withUsageMode(mode: UsageMode): InitConfigBuilder<T & { usageMode: UsageMode }> {
+ return new InitConfigBuilder({ ...this.data, usageMode: mode });
+ }
+
+ withFramework(
+ fw: NativeFramework | undefined
+ ): InitConfigBuilder<T & { framework: NativeFramework | undefined }> {
+ return new InitConfigBuilder({ ...this.data, framework: fw });
+ }
+
+ withInstallSkills(install: boolean): InitConfigBuilder<T & { installSkills: boolean }> {
+ return new InitConfigBuilder({ ...this.data, installSkills: install });
+ }
+
+ withDetectedEnv(
+ env: ProjectEnvironment | undefined
+ ): InitConfigBuilder<T & { detectedEnv: ProjectEnvironment | undefined }> {
+ return new InitConfigBuilder({ ...this.data, detectedEnv: env });
+ }
+
+ withInstallPlan(
+ plan: CoreDependencyPlan | undefined
+ ): InitConfigBuilder<T & { installPlan: CoreDependencyPlan | undefined }> {
+ return new InitConfigBuilder({ ...this.data, installPlan: plan });
+ }
+
+ /** Extract the final config. Only callable when all required fields are present. */
+ build(
+ this: InitConfigBuilder<{
+ usageMode: UsageMode;
+ framework: NativeFramework | undefined;
+ installSkills: boolean;
+ detectedEnv: ProjectEnvironment | undefined;
+ installPlan: CoreDependencyPlan | undefined;
+ }>
+ ): InitConfig {
+ return {
+ usageMode: this.data.usageMode,
+ framework: this.data.framework,
+ installSkills: this.data.installSkills,
+ detectedEnv: this.data.detectedEnv,
+ installPlan: this.data.installPlan,
+ };
+ }
+
+ /** Read accumulated data (for intermediate access). */
+ get value(): T {
+ return this.data;
+ }
+}
+
+interface InitConfig {
+ readonly usageMode: UsageMode;
+ readonly framework: NativeFramework | undefined;
+ readonly installSkills: boolean;
+ readonly detectedEnv: ProjectEnvironment | undefined;
+ readonly installPlan: CoreDependencyPlan | undefined;
+}
+
+// ---------------------------------------------------------------------------
+// Init wizard — collects all answers via the builder
+// ---------------------------------------------------------------------------
+
+/**
+ * Detect the project environment. Returns `undefined` if detection fails
+ * (logs a warning but does not abort the wizard).
+ */
+const detectEnvironment = (cwd: string) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const envDetector = yield* ProjectEnvironmentDetector;
+
+ return yield* envDetector.detectProjectEnvironment(cwd).pipe(
+ Effect.tap(env => ui.log.step(`Detected: ${env.language} (${env.packageManager})`)),
+ Effect.catchTag('services/ProjectEnvironmentDetectorError', e =>
+ Effect.gen(function* () {
+ yield* ui.log.warn(e.message);
+ if (e.details) yield* ui.log.info(e.details);
+ yield* ui.log.info('Skipping dependency installation.');
+ return undefined;
+ })
+ )
+ );
+ });
+
+/**
+ * Resolve the install plan for the detected environment.
+ * Only determines WHAT to install (no version checking or shell commands).
+ * Version checking is deferred to `runInstallStep`.
+ */
+const resolveInstallPlan = (cwd: string) =>
+ detectCoreDependencyPlan(cwd).pipe(Effect.catchAll(() => Effect.succeed(null)));
+
+/**
+ * After detecting the project environment and resolving an install plan,
+ * ask the user to confirm the detected package manager or skip installation.
+ * Returns the plan if confirmed, `undefined` if skipped.
+ */
+const confirmInstallPlan = (plan: CoreDependencyPlan) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+
+ type PmChoice = 'confirm' | 'skip';
+ const choice = yield* ui.select<PmChoice>(
+ `Install ${plan.dependency} using ${plan.packageManager}?`,
+ [
+ { value: 'confirm' as PmChoice, label: plan.packageManager, hint: plan.installCommand },
+ { value: 'skip' as PmChoice, label: 'Skip' },
+ ]
+ );
+
+ return choice === 'confirm' ? plan : undefined;
+ });
+
+/**
+ * Runs the interactive init wizard.
+ *
+ * Steps:
+ * 1. Usage mode — "Native tools" or "Composio MCP"
+ * 2. Framework — which agent framework (only if native)
+ * 3. Install skills — whether to install Composio coding-agent skills
+ * 4. Detect project environment (only if native)
+ * 5. Resolve + confirm install plan (only if native and environment detected)
+ *
+ * All inputs are collected through the builder before any side effects run.
+ * Returns a fully-built `InitConfig`.
+ */
+const runInitWizard = (cwd: string, params: { noSkills: boolean }) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+
+ // Step 1: Usage mode
+ const usageMode = yield* ui.select<UsageMode>(
+ 'How would you like to use Composio?',
+ USAGE_MODE_OPTIONS
+ );
+
+ // Step 2: Framework (only for native tools)
+ const framework: NativeFramework | undefined =
+ usageMode === 'native'
+ ? yield* ui
+ .select<NativeFramework>('Which framework do you use?', NATIVE_FRAMEWORK_OPTIONS)
+ .pipe(Effect.map(fw => (fw === 'skip' ? undefined : fw)))
+ : undefined;
+
+ // Step 3: Install Composio skills (skip prompt when --no-skills)
+ const installSkills = params.noSkills
+ ? false
+ : yield* ui.confirm('Install Composio skills for your Coding Agent?', {
+ defaultValue: true,
+ });
+
+ // Steps 4+5: Detect environment + confirm install plan (only for native tools)
+ let detectedEnv: ProjectEnvironment | undefined;
+ let installPlan: CoreDependencyPlan | undefined;
+
+ if (usageMode === 'native') {
+ // Step 4: Detect project environment
+ detectedEnv = yield* detectEnvironment(cwd);
+
+ // Step 5: Resolve install plan and confirm package manager
+ if (detectedEnv) {
+ const plan = yield* resolveInstallPlan(cwd);
+ if (plan) {
+ installPlan = yield* confirmInstallPlan(plan);
+ }
+ }
+ }
+
+ return InitConfigBuilder.create()
+ .withUsageMode(usageMode)
+ .withFramework(framework)
+ .withInstallSkills(installSkills)
+ .withDetectedEnv(detectedEnv)
+ .withInstallPlan(installPlan)
+ .build();
+ });
+
+// ---------------------------------------------------------------------------
+// File I/O helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Serializes an `InitConfig` to the JSON payload written to `.composio/config.json`.
+ */
+const initConfigToJSON = (config: InitConfig): string => {
+ const payload: Record<string, unknown> = {
+ usage_mode: config.usageMode,
+ };
+ if (config.framework) {
+ payload.framework = config.framework;
+ }
+ payload.install_skills = config.installSkills;
+ if (config.detectedEnv) {
+ payload.detected_language = config.detectedEnv.language;
+ payload.package_manager = config.detectedEnv.packageManager;
+ }
+ return JSON.stringify(payload, null, 2);
+};
+
+/** Writes project keys + init config to `<cwd>/.composio/` and creates a `.gitignore`. */
+const writeProjectConfig = (composioDir: string, selected: ProjectKeys, config: InitConfig) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+
+ yield* fs
+ .makeDirectory(composioDir, { recursive: true })
+ .pipe(Effect.catchAll(() => Effect.void));
+
+ const projectJson = yield* projectKeysToJSON(selected);
+ yield* fs.writeFileString(
+ path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME),
+ projectJson
+ );
+
+ yield* fs.writeFileString(path.join(composioDir, 'config.json'), initConfigToJSON(config));
+
+ // Create .composio/.gitignore to prevent accidental commits
+ const gitignorePath = path.join(composioDir, '.gitignore');
+ const gitignoreExists = yield* fs.exists(gitignorePath);
+ if (!gitignoreExists) {
+ yield* fs.writeFileString(gitignorePath, '*\n');
+ }
+ });
+
+// ---------------------------------------------------------------------------
+// Install step — runs after wizard, before outro
+// ---------------------------------------------------------------------------
+
+/**
+ * Runs the dependency installation step based on the init config.
+ * Handles --dry-run, --force, --yes flags and already-installed detection.
+ */
+const runInstallStep = (params: {
+ config: InitConfig;
+ cwd: string;
+ dryRun: boolean;
+ force: boolean;
+ yes: boolean;
+}) =>
+ Effect.gen(function* () {
+ const { config, cwd, dryRun, force, yes } = params;
+ if (!config.installPlan) return;
+
+ const ui = yield* TerminalUI;
+ const runner = yield* CommandRunner;
+ const plan = config.installPlan;
+
+ // Check if already installed (only for JS — Python version check requires shell)
+ if (plan.kind === 'js') {
+ const depState = yield* resolveCoreDependencyState(cwd).pipe(
+ Effect.catchAll(() => Effect.succeed({ plan, installedVersion: null }))
+ );
+
+ if (depState.installedVersion && !force) {
+ const detail =
+ depState.installedVersion.source === 'package.json'
+ ? `declared in package.json (${depState.installedVersion.version})`
+ : `${depState.installedVersion.version} (${depState.installedVersion.source})`;
+ yield* ui.log.info(`Found ${plan.dependency}: ${detail}`);
+ yield* ui.log.success('Dependency already installed.');
+ return;
+ }
+
+ if (depState.installedVersion && force) {
+ yield* ui.log.warn('Reinstalling due to --force.');
+ }
+ }
+
+ if (dryRun) {
+ yield* ui.note(plan.installCommand, 'Install Command');
+ yield* ui.log.info('Dry run complete.');
+ return;
+ }
+
+ const shouldInstall =
+ yes || (yield* ui.confirm(`Run: ${plan.installCommand}?`, { defaultValue: true }));
+ if (!shouldInstall) {
+ yield* ui.log.warn('Installation cancelled.');
+ return;
+ }
+
+ const [cmd, ...args] = plan.installCommand.split(' ');
+ const command = PlatformCommand.make(cmd!, ...args).pipe(
+ PlatformCommand.workingDirectory(plan.rootDir)
+ );
+
+ const install = Effect.gen(function* () {
+ const exitCode = yield* runner.run(command);
+ if (exitCode !== 0) {
+ yield* Effect.fail(new Error(`Install command failed with exit code ${exitCode}`));
+ }
+ });
+
+ yield* ui
+ .withSpinner(`Installing ${plan.dependency}...`, install, {
+ successMessage: `Installed ${plan.dependency}.`,
+ errorMessage: `Failed to install ${plan.dependency}.`,
+ })
+ .pipe(
+ Effect.catchAll(e =>
+ Effect.gen(function* () {
+ yield* ui.log.error(`Install failed: ${e instanceof Error ? e.message : String(e)}`);
+ yield* ui.log.info(`You can install manually: ${plan.installCommand}`);
+ })
+ )
+ );
+ });
+
+// ---------------------------------------------------------------------------
+// Skills install step — runs `npx skills add composiohq/skills`
+// ---------------------------------------------------------------------------
+
+const SKILLS_INSTALL_COMMAND = 'npx skills add composiohq/skills';
+
+/**
+ * Runs the Composio skills installation step.
+ * Uses `npx skills add composiohq/skills` to install coding-agent skills.
+ */
+const runSkillsInstallStep = (params: {
+ config: InitConfig;
+ cwd: string;
+ dryRun: boolean;
+ yes: boolean;
+}) =>
+ Effect.gen(function* () {
+ const { config, cwd, dryRun, yes } = params;
+ if (!config.installSkills) return;
+
+ const ui = yield* TerminalUI;
+ const runner = yield* CommandRunner;
+
+ if (dryRun) {
+ yield* ui.note(SKILLS_INSTALL_COMMAND, 'Skills Install Command');
+ return;
+ }
+
+ const shouldInstall =
+ yes || (yield* ui.confirm(`Run: ${SKILLS_INSTALL_COMMAND}?`, { defaultValue: true }));
+ if (!shouldInstall) {
+ yield* ui.log.warn('Skills installation cancelled.');
+ return;
+ }
+
+ const [cmd, ...args] = SKILLS_INSTALL_COMMAND.split(' ');
+ const command = PlatformCommand.make(cmd!, ...args).pipe(
+ PlatformCommand.workingDirectory(cwd)
+ );
+
+ const install = Effect.gen(function* () {
+ const exitCode = yield* runner.run(command);
+ if (exitCode !== 0) {
+ yield* Effect.fail(new Error(`Skills install command failed with exit code ${exitCode}`));
+ }
+ });
+
+ yield* ui
+ .withSpinner('Installing Composio skills...', install, {
+ successMessage: 'Installed Composio skills.',
+ errorMessage: 'Failed to install Composio skills.',
+ })
+ .pipe(
+ Effect.catchAll(e =>
+ Effect.gen(function* () {
+ yield* ui.log.error(
+ `Skills install failed: ${e instanceof Error ? e.message : String(e)}`
+ );
+ yield* ui.log.info(`You can install manually: ${SKILLS_INSTALL_COMMAND}`);
+ })
+ )
+ );
+ });
+
+// ---------------------------------------------------------------------------
+// Structured output helper
+// ---------------------------------------------------------------------------
+
+const makeOutputJson = (selected: ProjectKeys, config: InitConfig, composioDir: string) =>
+ JSON.stringify({
+ org_id: selected.orgId,
+ project_id: selected.projectId,
+ usage_mode: config.usageMode,
+ framework: config.framework ?? null,
+ install_skills: config.installSkills,
+ detected_language: config.detectedEnv?.language ?? null,
+ package_manager: config.detectedEnv?.packageManager ?? null,
+ install_command: config.installPlan?.installCommand ?? null,
+ path: composioDir,
+ });
+
+// ---------------------------------------------------------------------------
+// Command
+// ---------------------------------------------------------------------------
+
+/**
+ * CLI command to initialize a Composio project in the current directory.
+ *
+ * Creates `<cwd>/.composio/project.json` with org_id and project_id,
+ * plus `<cwd>/.composio/config.json` with usage mode, framework, and skill preferences.
+ *
+ * Supports two modes:
+ * 1. Interactive: Fetches projects from the API and prompts for selection
+ * 2. Non-interactive: Accepts --org-id and --project-id flags for agents/CI
+ *
+ * @example
+ * ```bash
+ * composio init
+ * composio init --org-id <org> --project-id <project>
+ * ```
+ */
+export const initCmd = CliCommand.make(
+ 'init',
+ {
+ orgId: orgIdOpt,
+ projectId: projectIdOpt,
+ noBrowser: noBrowserOpt,
+ dryRun: dryRunOpt,
+ force: forceOpt,
+ yes: yesOpt,
+ noSkills: noSkillsOpt,
+ },
+ ({ orgId, projectId, noBrowser, dryRun, force, yes, noSkills }) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const ctx = yield* ComposioUserContext;
+ const proc = yield* NodeProcess;
+
+ yield* ui.intro('composio init');
+
+ const composioDir = path.join(proc.cwd, constants.PROJECT_COMPOSIO_DIR);
+
+ // Agent-native path: --org-id and --project-id flags skip project picker
+ if (Option.isSome(orgId) && Option.isSome(projectId)) {
+ const selected: ProjectKeys = {
+ orgId: orgId.value,
+ projectId: projectId.value,
+ projectName: Option.none(),
+ orgName: Option.none(),
+ email: Option.none(),
+ };
+
+ const config = yield* runInitWizard(proc.cwd, { noSkills });
+ yield* writeProjectConfig(composioDir, selected, config);
+ yield* runInstallStep({ config, cwd: proc.cwd, dryRun, force, yes });
+ yield* runSkillsInstallStep({ config, cwd: proc.cwd, dryRun, yes });
+
+ yield* ui.log.success(`Project initialized in ${composioDir}/`);
+ yield* ui.output(makeOutputJson(selected, config, composioDir));
+ yield* ui.outro('');
+ return;
+ }
+
+ yield* initInteractiveFlow({ composioDir, noBrowser, dryRun, force, yes, noSkills });
+ })
+).pipe(CliCommand.withDescription('Initialize a Composio project in the current directory.'));
+
+/**
+ * Interactive init flow — handles login, project selection, wizard, install.
+ * Extracted to keep the main command handler under the line limit.
+ */
+const initInteractiveFlow = (params: {
+ composioDir: string;
+ noBrowser: boolean;
+ dryRun: boolean;
+ force: boolean;
+ yes: boolean;
+ noSkills: boolean;
+}) =>
+ Effect.gen(function* () {
+ const { composioDir, noBrowser, dryRun, force, yes, noSkills } = params;
+ const ui = yield* TerminalUI;
+ const ctx = yield* ComposioUserContext;
+ const proc = yield* NodeProcess;
+
+ // 1. Ensure user is logged in
+ if (!ctx.isLoggedIn()) {
+ yield* ui.log.step('No credentials found. Logging in...');
+ yield* browserLogin({ scope: 'project', noBrowser });
+ }
+
+ // 2. Fetch projects
+ const apiKey = Option.getOrUndefined(ctx.data.apiKey);
+ const orgIdValue = Option.getOrUndefined(ctx.data.orgId);
+ const projectIdValue = Option.getOrUndefined(ctx.data.projectId);
+ if (!apiKey || !orgIdValue || !projectIdValue) {
+ yield* ui.log.warn(
+ 'No API key, org ID, or project ID found. Please try `composio login` first.'
+ );
+ yield* ui.outro('');
+ return;
+ }
+
+ const orgProjects = yield* listOrgProjects({
+ baseURL: ctx.data.baseURL,
+ apiKey,
+ orgId: orgIdValue,
+ projectId: projectIdValue,
+ }).pipe(
+ Effect.catchTag('services/HttpServerError', e =>
+ Effect.gen(function* () {
+ yield* Effect.logDebug('Failed to list org projects:', e);
+ yield* ui.log.warn('Could not fetch projects from the server.');
+ yield* ui.log.info(
+ 'Use `composio init --org-id <org> --project-id <project>` to set up manually.'
+ );
+ yield* ui.outro('');
+ return yield* Effect.fail(e);
+ })
+ ),
+ Effect.catchTag('services/HttpDecodingError', e =>
+ Effect.gen(function* () {
+ yield* Effect.logDebug('Failed to decode org projects response:', e);
+ yield* ui.log.warn('Unexpected response from the server.');
+ yield* ui.log.info(
+ 'Use `composio init --org-id <org> --project-id <project>` to set up manually.'
+ );
+ yield* ui.outro('');
+ return yield* Effect.fail(e);
+ })
+ )
+ );
+
+ if (orgProjects.data.length === 0) {
+ yield* ui.log.warn('No projects found for your organization.');
+ yield* ui.log.info(
+ 'Create a project at https://platform.composio.dev, then run `composio init` again.'
+ );
+ yield* ui.outro('');
+ return;
+ }
+
+ // 3. Select a project
+ const orgProjectToKeys = (p: OrgProject): ProjectKeys => ({
+ orgId: p.org_id,
+ projectId: p.id,
+ projectName: Option.some(p.name),
+ orgName: Option.none(),
+ email: Option.some(p.email),
+ });
+
+ const selectedProject: OrgProject =
+ orgProjects.data.length === 1
+ ? orgProjects.data[0]
+ : yield* ui.select<OrgProject>(
+ 'Select a project:',
+ orgProjects.data.map(p => ({ value: p, label: p.name, hint: p.id }))
+ );
+
+ const selected = orgProjectToKeys(selectedProject);
+ yield* ui.log.step(`Using project "${selectedProject.name}"`);
+
+ // 4. Run wizard + write config + install
+ const config = yield* runInitWizard(proc.cwd, { noSkills });
+ yield* writeProjectConfig(composioDir, selected, config);
+ yield* runInstallStep({ config, cwd: proc.cwd, dryRun, force, yes });
+ yield* runSkillsInstallStep({ config, cwd: proc.cwd, dryRun, yes });
+
+ yield* ui.log.success(`Project initialized in ${composioDir}/`);
+ yield* ui.output(makeOutputJson(selected, config, composioDir));
+ yield* ui.outro('');
+ });
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index 2578cf603..aecd66e41 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -1,7 +1,12 @@
import { Command, Options } from '@effect/cli';
-import { Effect, Schedule } from 'effect';
+import { Effect, Option, Schedule } from 'effect';
import open from 'open';
-import { ComposioSessionRepository } from 'src/services/composio-clients';
+import {
+ ComposioSessionRepository,
+ getSessionInfo,
+ getSessionInfoByUserApiKey,
+ type SessionInfoResponse,
+} from 'src/services/composio-clients';
import { ComposioUserContext } from 'src/services/user-context';
import { TerminalUI } from 'src/services/terminal-ui';
@@ -10,41 +15,148 @@ export const noBrowser = Options.boolean('no-browser').pipe(
Options.withDescription('Login without browser interaction')
);
+const apiKeyOpt = Options.text('api-key').pipe(
+ Options.optional,
+ Options.withDescription('API key for non-interactive login (agents/CI)')
+);
+
+const orgIdOpt = Options.text('org-id').pipe(
+ Options.optional,
+ Options.withDescription('Organization ID for non-interactive login')
+);
+
+const projectIdOpt = Options.text('project-id').pipe(
+ Options.optional,
+ Options.withDescription('Project ID for non-interactive login')
+);
+
/**
- * CLI command to login using Composio's CLI session APIs.
+ * Verifies credentials via session/info and stores them.
*
- * @example
- * ```bash
- * composio login <command>
- * ```
+ * Resolves TerminalUI and ComposioUserContext from the Effect context rather
+ * than accepting them as parameters -- this keeps the signature focused on
+ * data and avoids hand-rolled structural types.
*/
-export const loginCmd = Command.make('login', { noBrowser }, ({ noBrowser }) =>
+const storeCredentials = (params: {
+ baseURL: string;
+ uakApiKey: string;
+ initialOrgId: string;
+ initialProjectId: string;
+ fallbackEmail: string;
+ /**
+ * When true, 400/401/403 from session/info will fail the login.
+ * Used for non-interactive login where the user provides explicit IDs.
+ * When false, all session/info errors are non-fatal (browser login).
+ */
+ strictVerification: boolean;
+}) =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
const ctx = yield* ComposioUserContext;
- yield* ui.intro('composio login');
+ const {
+ baseURL,
+ uakApiKey,
+ initialOrgId,
+ initialProjectId,
+ fallbackEmail,
+ strictVerification,
+ } = params;
- if (ctx.isLoggedIn()) {
- yield* ui.log.warn(`You're already logged in!`);
- yield* ui.log.info(
- `If you want to log in with a different account, please run \`composio logout\` first.`
- );
- yield* ui.outro('');
- return;
+ // Call session/info to enrich the login with org/project metadata.
+ // In strict mode (non-interactive login), 400/401/403 are hard failures.
+ // In non-strict mode (browser login), all errors are non-fatal since
+ // the linked session is already authenticated.
+ const sessionInfo: SessionInfoResponse | undefined = yield* getSessionInfo({
+ baseURL,
+ apiKey: uakApiKey,
+ orgId: initialOrgId,
+ projectId: initialProjectId,
+ }).pipe(
+ Effect.catchTag('services/HttpServerError', e =>
+ Effect.gen(function* () {
+ if (strictVerification && e.status && e.status >= 400 && e.status < 500) {
+ return yield* Effect.fail(e);
+ }
+ yield* Effect.logDebug(`Session info fetch failed (HTTP ${e.status ?? '?'}):`, e);
+ return undefined;
+ })
+ ),
+ Effect.catchTag('services/HttpDecodingError', e =>
+ Effect.gen(function* () {
+ yield* Effect.logDebug('Session info decoding error:', e);
+ return undefined;
+ })
+ )
+ );
+
+ // Use session/info as the canonical source of org/project IDs when available.
+ // The initial IDs come from the linked session response (which may use session-level
+ // identifiers rather than the actual org/project IDs).
+ const orgId = sessionInfo?.org_member.id ?? initialOrgId;
+ const projectId = sessionInfo?.project.id ?? initialProjectId;
+
+ if (sessionInfo) {
+ if (initialOrgId !== orgId) {
+ yield* Effect.logDebug(`orgId corrected: ${initialOrgId} -> ${orgId} (from session/info)`);
+ }
+ if (initialProjectId !== projectId) {
+ yield* Effect.logDebug(
+ `projectId corrected: ${initialProjectId} -> ${projectId} (from session/info)`
+ );
+ }
}
+ // Store UAK + org/project IDs in user_data.json
+ yield* ctx.login(uakApiKey, orgId, projectId);
+
+ const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
+ yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
+ yield* ui.log.info('Run `composio init` in your project directory to set up project context.');
+
+ // Emit structured JSON for piped/scripted consumption (agent-native)
+ yield* ui.output(
+ JSON.stringify({
+ email,
+ org_id: orgId,
+ project_id: projectId,
+ org_name: sessionInfo?.project.org.name ?? '',
+ project_name: sessionInfo?.project.name ?? '',
+ })
+ );
+
+ yield* ui.outro("You're all set!");
+ });
+
+/**
+ * Runs the browser-based login flow: creates a CLI session, opens the browser,
+ * polls until linked, enriches via session/info, and stores credentials.
+ *
+ * Shared by `composio login` (scope: 'user') and `composio init` (scope: 'project').
+ *
+ * Resolves TerminalUI, ComposioUserContext, and ComposioSessionRepository
+ * from the Effect context.
+ */
+export const browserLogin = (params: {
+ /** Session scope: 'user' for login, 'project' for init. */
+ scope: 'user' | 'project';
+ /** When true, don't open browser — just show the URL. */
+ noBrowser: boolean;
+}) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const ctx = yield* ComposioUserContext;
const client = yield* ComposioSessionRepository;
- yield* Effect.logDebug('Authenticating...');
+ yield* Effect.logDebug(`Authenticating (scope: ${params.scope})...`);
- const session = yield* client.createSession();
+ const session = yield* client.createSession({ scope: params.scope });
- yield* Effect.logDebug(`Created session:`, session);
+ yield* Effect.logDebug(`Created session: ${session.id}`);
const url = `${ctx.data.webURL}?cliKey=${session.id}`;
- if (noBrowser) {
+ if (params.noBrowser) {
yield* ui.log.info('Please login using the following URL:');
} else {
yield* ui.log.step('Redirecting you to the login page');
@@ -53,45 +165,31 @@ export const loginCmd = Command.make('login', { noBrowser }, ({ noBrowser }) =>
yield* ui.note(url, 'Login URL');
yield* ui.output(url);
- if (!noBrowser) {
- // Open the given `url` in the default browser.
- // Do NOT use `apps.browser` — it triggers AppleScript-based default browser
- // detection (`bundle-name` → Finder + System Events), which fails on macOS
- // when the terminal lacks Apple Events permissions (error -1743).
- // Calling `open(url)` without an app lets the OS handle browser selection natively.
+ if (!params.noBrowser) {
yield* Effect.tryPromise(() => open(url, { wait: false })).pipe(
Effect.catchAll(error =>
Effect.gen(function* () {
yield* Effect.logDebug('Failed to open browser:', error);
yield* ui.log.warn('Could not open the browser automatically.');
yield* ui.log.info(
- `Tip: try using \`composio login --no-browser\` and open the URL manually.`
+ `Tip: try using the \`--no-browser\` flag and open the URL manually.`
);
})
)
);
}
- // Retry operation until the session status is "linked" with exponential backoff.
- // useMakeSpinner auto-cleans up the spinner on interruption (e.g., Ctrl+C).
const linkedSession = yield* ui.useMakeSpinner('Waiting for login...', spinner =>
Effect.retry(
Effect.gen(function* () {
- const currentSession = yield* client.getSession({
- ...session,
- });
-
- // Check if session is linked
+ const currentSession = yield* client.getSession({ ...session });
if (currentSession.status === 'linked') {
return currentSession;
}
-
- // If still pending, fail to trigger retry
return yield* Effect.fail(
new Error(`Session status is still '${currentSession.status}', waiting for 'linked'`)
);
}),
- // Exponential backoff: start with 0.3s, max 5s, up to 15 retries
Schedule.exponential('0.3 seconds').pipe(
Schedule.intersect(Schedule.recurs(15)),
Schedule.intersect(Schedule.spaced('5 seconds'))
@@ -102,11 +200,110 @@ export const loginCmd = Command.make('login', { noBrowser }, ({ noBrowser }) =>
)
);
- yield* Effect.logDebug(`Linked session: ${JSON.stringify(linkedSession)}`);
+ yield* Effect.logDebug(`Linked session ID: ${linkedSession.id}`);
- yield* ctx.login(linkedSession.api_key);
+ // e.g., "uak_b813ydmoEYdB_xBxGHeW"
+ const uakApiKey = linkedSession.api_key;
- yield* ui.log.success(`Logged in with user account ${linkedSession.account.email}`);
- yield* ui.outro("You're all set!");
- })
+ const uakSessionInfo = yield* getSessionInfoByUserApiKey({
+ baseURL: ctx.data.baseURL,
+ userApiKey: uakApiKey,
+ });
+
+ // e.g., "pr_xlSR6oN5jIlk"
+ const xProjectId = uakSessionInfo.project.nano_id;
+ // e.g., "k2OiqRLMdHyM"
+ const xOrgId = uakSessionInfo.project.org.id;
+
+ yield* Effect.logDebug('UAK session info:', { xProjectId, xOrgId });
+
+ yield* storeCredentials({
+ baseURL: ctx.data.baseURL,
+ uakApiKey,
+ initialOrgId: xOrgId,
+ initialProjectId: xProjectId,
+ fallbackEmail: linkedSession.account.email,
+ strictVerification: false,
+ });
+ });
+
+/**
+ * CLI command to login using Composio's CLI session APIs.
+ *
+ * Supports two modes:
+ * 1. Browser-based: Opens browser for OAuth flow (default)
+ * 2. Non-interactive: Accepts --api-key, --org-id, --project-id flags for agents/CI
+ *
+ * @example
+ * ```bash
+ * composio login
+ * composio login --no-browser
+ * composio login --api-key uak_xxx --org-id org-id --project-id proj-id
+ * ```
+ */
+export const loginCmd = Command.make(
+ 'login',
+ { noBrowser, apiKey: apiKeyOpt, orgId: orgIdOpt, projectId: projectIdOpt },
+ ({ noBrowser, apiKey, orgId, projectId }) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const ctx = yield* ComposioUserContext;
+
+ yield* ui.intro('composio login');
+
+ // Non-interactive path: --api-key, --org-id, --project-id flags skip browser flow.
+ // All three must be provided together; partial flags are an error.
+ const nonInteractiveFlags = [apiKey, orgId, projectId];
+ const anyProvided = nonInteractiveFlags.some(Option.isSome);
+ const allProvided = nonInteractiveFlags.every(Option.isSome);
+
+ if (anyProvided && !allProvided) {
+ const missing = [
+ Option.isNone(apiKey) && '--api-key',
+ Option.isNone(orgId) && '--org-id',
+ Option.isNone(projectId) && '--project-id',
+ ].filter(Boolean);
+ yield* ui.log.error(`Missing required flag(s): ${missing.join(', ')}`);
+ yield* ui.log.info(
+ 'Non-interactive login requires all three: --api-key, --org-id, --project-id'
+ );
+ yield* ui.outro('');
+ return;
+ }
+
+ // Strict verification: 400/401/403 from session/info are hard failures since
+ // the user explicitly provided the IDs.
+ if (
+ allProvided &&
+ Option.isSome(apiKey) &&
+ Option.isSome(orgId) &&
+ Option.isSome(projectId)
+ ) {
+ yield* Effect.logDebug('Non-interactive login with provided credentials');
+ yield* storeCredentials({
+ baseURL: ctx.data.baseURL,
+ uakApiKey: apiKey.value,
+ initialOrgId: orgId.value,
+ initialProjectId: projectId.value,
+ fallbackEmail: '',
+ strictVerification: true,
+ });
+ return;
+ }
+
+ if (ctx.isLoggedIn()) {
+ // Allow re-login when orgId/projectId are not yet set (old CLI login without multi-project support)
+ if (Option.isSome(ctx.data.orgId) && Option.isSome(ctx.data.projectId)) {
+ yield* ui.log.warn(`You're already logged in!`);
+ yield* ui.log.info(
+ `If you want to log in with a different account, please run \`composio logout\` first.`
+ );
+ yield* ui.outro('');
+ return;
+ }
+ yield* ui.log.step('Re-authenticating for multi-project support...');
+ }
+
+ yield* browserLogin({ scope: 'user', noBrowser });
+ })
).pipe(Command.withDescription('Log in to the Composio SDK.'));
diff --git a/ts/packages/cli/src/commands/logout.cmd.ts b/ts/packages/cli/src/commands/logout.cmd.ts
index 2d6b47593..28f462e53 100644
--- a/ts/packages/cli/src/commands/logout.cmd.ts
+++ b/ts/packages/cli/src/commands/logout.cmd.ts
@@ -22,6 +22,7 @@ export const logoutCmd = Command.make('logout', {}, () =>
}
yield* ctx.logout;
+
yield* ui.log.success('Logged out successfully.');
})
).pipe(Command.withDescription('Log out from the Composio SDK.'));
diff --git a/ts/packages/cli/src/constants.ts b/ts/packages/cli/src/constants.ts
index 8917f89b8..eb18723c6 100644
--- a/ts/packages/cli/src/constants.ts
+++ b/ts/packages/cli/src/constants.ts
@@ -5,6 +5,18 @@ const { DEFAULT_BASE_URL, DEFAULT_WEB_URL } = constants;
export { DEFAULT_BASE_URL, DEFAULT_WEB_URL };
+/**
+ * Staging base URL for the Composio API server (backend).
+ * Used when `COMPOSIO_ENVIRONMENT=staging`.
+ */
+export const STAGING_BASE_URL = 'https://staging-backend.composio.dev';
+
+/**
+ * Staging base URL for the Composio web app (frontend).
+ * Used when `COMPOSIO_ENVIRONMENT=staging`.
+ */
+export const STAGING_WEB_URL = 'https://staging-platform.composio.dev';
+
/**
* Prefix for user environment variable keys used by the Composio CLI.
*/
@@ -45,6 +57,21 @@ export const APP_VERSION = pkg.version;
*/
export const APP_NAME = pkg.name;
+/**
+ * Name of the per-directory project config file.
+ */
+export const PROJECT_CONFIG_FILE_NAME = 'project.json';
+
+/**
+ * Name of the per-directory .env file for CLI-only config overrides.
+ */
+export const PROJECT_ENV_FILE_NAME = '.env';
+
+/**
+ * Name of the per-directory Composio config directory.
+ */
+export const PROJECT_COMPOSIO_DIR = '.composio';
+
/**
* GitHub repository information for release fetching
*/
diff --git a/ts/packages/cli/src/effects/app-config.ts b/ts/packages/cli/src/effects/app-config.ts
index 840ed5983..080a041ca 100644
--- a/ts/packages/cli/src/effects/app-config.ts
+++ b/ts/packages/cli/src/effects/app-config.ts
@@ -3,29 +3,66 @@ import * as constants from 'src/constants';
type APP_CONFIG = Config.Config.Wrap<{
API_KEY: Option.Option<string>;
+ ENVIRONMENT: Option.Option<string>;
BASE_URL: string;
WEB_URL: string;
CACHE_DIR: Option.Option<string>;
LOG_LEVEL: Option.Option<LogLevel.LogLevel>;
+ ORG_ID: Option.Option<string>;
+ PROJECT_ID: Option.Option<string>;
}>;
+/**
+ * Derives a URL default based on the `COMPOSIO_ENVIRONMENT` config key.
+ * Returns `stagingDefault` when ENVIRONMENT is `"staging"`, otherwise `prodDefault`.
+ */
+const environmentBasedDefault = (
+ prodDefault: string,
+ stagingDefault: string
+): Config.Config<string> =>
+ Config.string('ENVIRONMENT').pipe(
+ Config.map(env => (env === 'staging' ? stagingDefault : prodDefault)),
+ Config.withDefault(prodDefault)
+ );
+
/**
* Describe every configuration key used at runtime.
* Keys are read from environment variables (with the `${APP_ENV_CONFIG_KEY_PREFIX}<key>` format).
+ *
+ * URL precedence (highest → lowest):
+ * COMPOSIO_BASE_URL → COMPOSIO_ENVIRONMENT-derived → DEFAULT_BASE_URL
+ * COMPOSIO_WEB_URL → COMPOSIO_ENVIRONMENT-derived → DEFAULT_WEB_URL
*/
export const APP_CONFIG = {
// The API key for the Composio API
API_KEY: Config.option(Config.string('API_KEY')),
+ // The deployment environment ("production" | "staging"). Controls URL defaults.
+ ENVIRONMENT: Config.option(Config.string('ENVIRONMENT')),
+
// The base URL for the Composio API
- BASE_URL: Config.string('BASE_URL').pipe(Config.withDefault(constants.DEFAULT_BASE_URL)),
+ BASE_URL: Config.string('BASE_URL').pipe(
+ Config.orElse(() =>
+ environmentBasedDefault(constants.DEFAULT_BASE_URL, constants.STAGING_BASE_URL)
+ )
+ ),
// The base URL for the Composio web app
- WEB_URL: Config.string('WEB_URL').pipe(Config.withDefault(constants.DEFAULT_WEB_URL)),
+ WEB_URL: Config.string('WEB_URL').pipe(
+ Config.orElse(() =>
+ environmentBasedDefault(constants.DEFAULT_WEB_URL, constants.STAGING_WEB_URL)
+ )
+ ),
// The cache directory for the Composio CLI
CACHE_DIR: Config.option(Config.string('CACHE_DIR')),
// The log level for the Composio CLI
LOG_LEVEL: Config.option(Config.logLevel('LOG_LEVEL')),
+
+ // The organization ID for multi-project auth (overrides file-based config)
+ ORG_ID: Config.option(Config.string('ORG_ID')),
+
+ // The project ID for multi-project auth (overrides file-based config)
+ PROJECT_ID: Config.option(Config.string('PROJECT_ID')),
} satisfies APP_CONFIG;
diff --git a/ts/packages/cli/src/effects/core-dependency.ts b/ts/packages/cli/src/effects/core-dependency.ts
new file mode 100644
index 000000000..85115d3d1
--- /dev/null
+++ b/ts/packages/cli/src/effects/core-dependency.ts
@@ -0,0 +1,227 @@
+import path from 'node:path';
+import { Command, FileSystem } from '@effect/platform';
+import { Effect, Match } from 'effect';
+import {
+ ProjectEnvironmentDetector,
+ type JsLanguage,
+ type JsPackageManager,
+ type PythonPackageManager,
+} from 'src/services/project-environment-detector';
+import { getAncestors } from 'src/utils/get-ancestors';
+
+export type CoreDependencyPlan =
+ | {
+ kind: 'js';
+ language: JsLanguage;
+ packageManager: JsPackageManager;
+ rootDir: string;
+ dependency: '@composio/core';
+ installCommand: string;
+ }
+ | {
+ kind: 'python';
+ language: 'python';
+ packageManager: PythonPackageManager;
+ rootDir: string;
+ dependency: 'composio';
+ installCommand: string;
+ };
+
+export type CoreDependencyVersion = {
+ version: string;
+ source: 'package.json' | 'node_modules' | 'python';
+};
+
+export const getJsInstallCommand = (pm: JsPackageManager, dependency: string) =>
+ Match.value(pm).pipe(
+ Match.when('pnpm', () => `pnpm add ${dependency}`),
+ Match.when('bun', () => `bun add ${dependency}`),
+ Match.when('yarn', () => `yarn add ${dependency}`),
+ Match.when('npm', () => `npm install -S ${dependency}`),
+ Match.when('deno', () => `deno add npm:${dependency}`),
+ Match.exhaustive
+ );
+
+export const getPythonInstallCommand = (pm: PythonPackageManager, dependency: string) =>
+ pm === 'uv' ? `uv pip install ${dependency}` : `pip install ${dependency}`;
+
+export const detectCoreDependencyPlan = (cwd: string) =>
+ Effect.gen(function* () {
+ const envDetector = yield* ProjectEnvironmentDetector;
+ const env = yield* envDetector.detectProjectEnvironment(cwd);
+
+ if (env.kind === 'python') {
+ return {
+ kind: 'python',
+ language: 'python',
+ packageManager: env.packageManager,
+ rootDir: env.rootDir,
+ dependency: 'composio',
+ installCommand: getPythonInstallCommand(env.packageManager, 'composio'),
+ } satisfies CoreDependencyPlan;
+ }
+
+ return {
+ kind: 'js',
+ language: env.language,
+ packageManager: env.packageManager,
+ rootDir: env.rootDir,
+ dependency: '@composio/core',
+ installCommand: getJsInstallCommand(env.packageManager, '@composio/core'),
+ } satisfies CoreDependencyPlan;
+ });
+
+const readPackageJson = (fs: FileSystem.FileSystem, dir: string) =>
+ fs.readFileString(path.join(dir, 'package.json')).pipe(
+ Effect.andThen(content =>
+ Effect.try({
+ try: () => JSON.parse(content) as Record<string, unknown>,
+ catch: () => null,
+ })
+ ),
+ Effect.catchAll(() => Effect.succeed(null))
+ );
+
+const findDependencySpec = (pkg: Record<string, unknown>, name: string) => {
+ const deps = (pkg.dependencies ?? {}) as Record<string, string>;
+ const devDeps = (pkg.devDependencies ?? {}) as Record<string, string>;
+ const peerDeps = (pkg.peerDependencies ?? {}) as Record<string, string>;
+ const optionalDeps = (pkg.optionalDependencies ?? {}) as Record<string, string>;
+
+ return deps[name] ?? devDeps[name] ?? peerDeps[name] ?? optionalDeps[name] ?? null;
+};
+
+const detectJsDependencyVersion = (
+ fs: FileSystem.FileSystem,
+ plan: Extract<CoreDependencyPlan, { kind: 'js' }>
+) =>
+ Effect.gen(function* () {
+ const dirs = getAncestors(plan.rootDir);
+
+ for (const dir of dirs) {
+ const packageJsonPath = path.join(dir, 'node_modules', '@composio', 'core', 'package.json');
+ const content = yield* fs
+ .readFileString(packageJsonPath)
+ .pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
+
+ if (content) {
+ const parsed = yield* Effect.try({
+ try: () => JSON.parse(content) as { version?: string },
+ catch: () => null,
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
+
+ if (parsed?.version) {
+ return {
+ version: parsed.version,
+ source: 'node_modules',
+ } satisfies CoreDependencyVersion;
+ }
+ }
+
+ if (plan.packageManager === 'pnpm') {
+ const pnpmStore = path.join(dir, 'node_modules', '.pnpm');
+ const entries = yield* fs
+ .readDirectory(pnpmStore)
+ .pipe(Effect.catchAll(() => Effect.succeed<string[]>([])));
+ const match = entries.find(entry => entry.startsWith('@composio+core@'));
+ if (!match) {
+ continue;
+ }
+ const pnpmPkgPath = path.join(
+ pnpmStore,
+ match,
+ 'node_modules',
+ '@composio',
+ 'core',
+ 'package.json'
+ );
+ const pnpmContent = yield* fs
+ .readFileString(pnpmPkgPath)
+ .pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
+
+ if (pnpmContent) {
+ const pnpmParsed = yield* Effect.try({
+ try: () => JSON.parse(pnpmContent) as { version?: string },
+ catch: () => null,
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
+
+ if (pnpmParsed?.version) {
+ return {
+ version: pnpmParsed.version,
+ source: 'node_modules',
+ } satisfies CoreDependencyVersion;
+ }
+ }
+ }
+ }
+
+ for (const dir of dirs) {
+ const pkg = yield* readPackageJson(fs, dir);
+ if (!pkg) {
+ continue;
+ }
+ const spec = findDependencySpec(pkg, plan.dependency);
+ if (spec) {
+ return {
+ version: spec,
+ source: 'package.json',
+ } satisfies CoreDependencyVersion;
+ }
+ }
+
+ return null;
+ });
+
+const detectPythonDependencyVersion = (plan: Extract<CoreDependencyPlan, { kind: 'python' }>) =>
+ Effect.gen(function* () {
+ const [cmd, ...args] =
+ plan.packageManager === 'uv'
+ ? [
+ 'uv',
+ 'run',
+ 'python',
+ '-c',
+ "import importlib.metadata as m; print(m.version('composio'))",
+ ]
+ : ['python', '-c', "import importlib.metadata as m; print(m.version('composio'))"];
+
+ const stdout = yield* Command.make(cmd, ...args).pipe(
+ Command.string,
+ Effect.catchAll(() => Effect.succeed<string | null>(null))
+ );
+
+ if (!stdout) {
+ return null;
+ }
+
+ const version = stdout.trim();
+ if (!version) {
+ return null;
+ }
+
+ return {
+ version,
+ source: 'python',
+ } satisfies CoreDependencyVersion;
+ });
+
+export const detectCoreDependencyVersion = (plan: CoreDependencyPlan) =>
+ Effect.gen(function* () {
+ if (plan.kind === 'python') {
+ return yield* detectPythonDependencyVersion(plan);
+ }
+
+ const fs = yield* FileSystem.FileSystem;
+ return yield* detectJsDependencyVersion(fs, plan);
+ });
+
+export const resolveCoreDependencyState = (cwd: string) =>
+ Effect.gen(function* () {
+ const plan = yield* detectCoreDependencyPlan(cwd);
+ const installedVersion = yield* detectCoreDependencyVersion(plan);
+
+ return {
+ plan,
+ installedVersion,
+ } as const;
+ });
diff --git a/ts/packages/cli/src/models/project-keys.ts b/ts/packages/cli/src/models/project-keys.ts
new file mode 100644
index 000000000..3ee5baeb1
--- /dev/null
+++ b/ts/packages/cli/src/models/project-keys.ts
@@ -0,0 +1,54 @@
+import { Schema } from 'effect';
+import { OptionFromNullishOr } from 'effect/Schema';
+import { JSONTransformSchema } from './utils/json-transform-schema';
+
+/**
+ * Organization and project identifiers for a CLI project profile.
+ * Stored in `~/.composio/_keys/<projectId>.json` (global registry)
+ * and `<cwd>/.composio/project.json` (per-directory config).
+ */
+export const ProjectKeys = Schema.Struct({
+ /**
+ * Organization member ID (maps to `x-org-id` header).
+ */
+ orgId: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('org_id')),
+
+ /**
+ * Project ID (maps to `x-project-id` header).
+ */
+ projectId: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('project_id')),
+
+ /**
+ * Human-readable project name from session/info (optional for backward compat).
+ */
+ projectName: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
+ Schema.fromKey('project_name')
+ ),
+
+ /**
+ * Human-readable org name from session/info (optional for backward compat).
+ */
+ orgName: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
+ Schema.fromKey('org_name')
+ ),
+
+ /**
+ * User email from session/info (optional for backward compat).
+ */
+ email: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
+ Schema.fromKey('email')
+ ),
+}).annotations({
+ identifier: 'ProjectKeys',
+ description: 'Organization and project identifiers for a CLI project profile',
+});
+
+export type ProjectKeys = Schema.Schema.Type<typeof ProjectKeys>;
+
+export const ProjectKeysJSON = JSONTransformSchema(ProjectKeys);
+export const projectKeysFromJSON = Schema.decode(ProjectKeysJSON, {
+ propertyOrder: 'original',
+ onExcessProperty: 'ignore',
+ exact: false,
+});
+export const projectKeysToJSON = Schema.encode(ProjectKeysJSON);
diff --git a/ts/packages/cli/src/models/user-data.ts b/ts/packages/cli/src/models/user-data.ts
index 7d93cfc39..7ac051ac3 100644
--- a/ts/packages/cli/src/models/user-data.ts
+++ b/ts/packages/cli/src/models/user-data.ts
@@ -23,6 +23,20 @@ export const UserData = Schema.Struct({
webURL: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
Schema.fromKey('web_url')
),
+
+ /**
+ * Organization ID for the current user.
+ */
+ orgId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
+ Schema.fromKey('org_id')
+ ),
+
+ /**
+ * Project ID for the current user.
+ */
+ projectId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
+ Schema.fromKey('project_id')
+ ),
}).annotations({
identifier: 'UserData',
description: 'User data storage for the Composio CLI',
@@ -35,6 +49,8 @@ export const UserDataWithDefaults = Schema.Struct({
baseURL: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('base_url')),
webURL: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('web_url')),
+
+ // orgId and projectId remain as Option<string> — they may not be set.
}).annotations({
identifier: 'UserDataWithDefaults',
description: 'User data storage for the Composio CLI with defaults',
diff --git a/ts/packages/cli/src/services/command-runner.ts b/ts/packages/cli/src/services/command-runner.ts
new file mode 100644
index 000000000..9d3678fca
--- /dev/null
+++ b/ts/packages/cli/src/services/command-runner.ts
@@ -0,0 +1,9 @@
+import { Command } from '@effect/platform';
+import { Effect } from 'effect';
+
+export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {
+ sync: () => ({
+ run: (command: Command.Command) => Command.exitCode(command),
+ }),
+ dependencies: [],
+}) {}
diff --git a/ts/packages/cli/src/services/composio-clients.ts b/ts/packages/cli/src/services/composio-clients.ts
index fcc7ce91d..37434b65e 100644
--- a/ts/packages/cli/src/services/composio-clients.ts
+++ b/ts/packages/cli/src/services/composio-clients.ts
@@ -336,6 +336,41 @@ export type TriggerInstanceManageDeleteResponse = Schema.Schema.Type<
typeof TriggerInstanceManageDeleteResponse
>;
+/**
+ * Response from GET /api/v3/auth/session/info.
+ * Contains project, org member, and API key details for the authenticated session.
+ * Fields like webhook_url, webhook_secret, auto_id, deleted are intentionally omitted.
+ */
+export const SessionInfoResponse = Schema.Struct({
+ project: Schema.Struct({
+ name: Schema.String,
+ id: Schema.String,
+ org_id: Schema.String,
+ nano_id: Schema.String,
+ email: Schema.String,
+ created_at: Schema.String,
+ updated_at: Schema.String,
+ org: Schema.Struct({
+ name: Schema.String,
+ id: Schema.String,
+ plan: Schema.String,
+ }),
+ }),
+ org_member: Schema.Struct({
+ id: Schema.String,
+ email: Schema.String,
+ name: Schema.String,
+ role: Schema.String,
+ }),
+ api_key: Schema.Struct({
+ name: Schema.String,
+ project_id: Schema.String,
+ id: Schema.String,
+ org_member_id: Schema.String,
+ }),
+}).annotations({ identifier: 'SessionInfoResponse' });
+export type SessionInfoResponse = Schema.Schema.Type<typeof SessionInfoResponse>;
+
export interface TriggerInstancesListActiveParams {
user_ids?: string[];
connected_account_ids?: string[];
@@ -641,6 +676,179 @@ const streamResponseWithByteCount = (
return { json, byteSize };
});
+/**
+ * A single project entry returned by GET /api/v3/org/project/list.
+ */
+export const OrgProject = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ email: Schema.String,
+ deleted: Schema.Boolean,
+ org_id: Schema.String,
+ created_at: Schema.String,
+ updated_at: Schema.String,
+}).annotations({ identifier: 'OrgProject' });
+export type OrgProject = Schema.Schema.Type<typeof OrgProject>;
+
+/**
+ * Response from GET /api/v3/org/project/list.
+ */
+export const OrgProjectListResponse = Schema.Struct({
+ data: Schema.Array(OrgProject),
+ next_cursor: Schema.NullOr(Schema.String),
+ total_pages: Schema.Int,
+ current_page: Schema.Int,
+ total_items: Schema.Int,
+}).annotations({ identifier: 'OrgProjectListResponse' });
+export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListResponse>;
+
+/**
+ * Lists all projects for the logged-in user's organization.
+ * Uses plain fetch since this endpoint is not available in @composio/client.
+ *
+ * @param params.baseURL - API base URL
+ * @param params.apiKey - UAK (sent as `x-user-api-key`)
+ * @param params.orgId - Organization ID (sent as `x-composio-org-id`)
+ * @param params.projectId - Project ID (sent as `x-composio-project-id`)
+ * @param params.limit - Max projects to return (default 100)
+ */
+export const listOrgProjects = (params: {
+ baseURL: string;
+ apiKey: string;
+ orgId: string;
+ projectId: string;
+ limit?: number;
+}): Effect.Effect<OrgProjectListResponse, HttpServerError | HttpDecodingError> =>
+ Effect.gen(function* () {
+ const limit = params.limit ?? 100;
+ const response = yield* Effect.tryPromise({
+ try: () =>
+ fetch(
+ `${params.baseURL}/api/v3/org/project/list?list_all_org_projects=true&limit=${limit}`,
+ {
+ method: 'GET',
+ redirect: 'error',
+ headers: {
+ 'x-user-api-key': params.apiKey,
+ 'x-composio-org-id': params.orgId,
+ 'x-composio-project-id': params.projectId,
+ 'User-Agent': '@composio/cli',
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ }
+ ),
+ catch: error => new HttpServerError({ cause: error }),
+ });
+
+ if (!response.ok) {
+ return yield* handleHttpErrorResponse(response);
+ }
+
+ const { json } = yield* streamResponseWithByteCount(response);
+
+ return yield* pipe(
+ Schema.decodeUnknown(OrgProjectListResponse)(json),
+ Effect.catchTag('ParseError', e => {
+ const message = ParseResult.TreeFormatter.formatErrorSync(e);
+ return new HttpDecodingError({
+ cause: `ParseError\n ${message}`,
+ });
+ })
+ );
+ });
+
+/**
+ * Calls GET /api/v3/auth/session/info with the full layered auth headers.
+ * Uses plain fetch since this endpoint is not available in @composio/client.
+ * This is a standalone function, NOT on ComposioSessionRepository, to keep
+ * the repository as a pure facade over @composio/client.
+ */
+export const getSessionInfo = (params: {
+ baseURL: string;
+ apiKey: string;
+ orgId: string;
+ projectId: string;
+}): Effect.Effect<SessionInfoResponse, HttpServerError | HttpDecodingError> =>
+ Effect.gen(function* () {
+ const response = yield* Effect.tryPromise({
+ try: () =>
+ fetch(`${params.baseURL}/api/v3/auth/session/info`, {
+ method: 'GET',
+ redirect: 'error',
+ headers: {
+ 'x-api-key': params.apiKey,
+ 'x-org-id': params.orgId,
+ 'x-project-id': params.projectId,
+ 'User-Agent': '@composio/cli',
+ Accept: '*/*',
+ 'Content-Type': 'application/json',
+ },
+ }),
+ catch: error => new HttpServerError({ cause: error }),
+ });
+
+ if (!response.ok) {
+ return yield* handleHttpErrorResponse(response);
+ }
+
+ const { json } = yield* streamResponseWithByteCount(response);
+
+ return yield* pipe(
+ Schema.decodeUnknown(SessionInfoResponse)(json),
+ Effect.catchTag('ParseError', e => {
+ const message = ParseResult.TreeFormatter.formatErrorSync(e);
+ return new HttpDecodingError({
+ cause: `ParseError\n ${message}`,
+ });
+ })
+ );
+ });
+
+/**
+ * Calls GET /api/v3/auth/session/info using only the x-user-api-key header.
+ * Unlike getSessionInfo which requires org/project IDs, this variant resolves
+ * session metadata from the UAK alone — useful during login before org/project
+ * context is known.
+ * Uses plain fetch since this endpoint is not available in @composio/client.
+ */
+export const getSessionInfoByUserApiKey = (params: {
+ baseURL: string;
+ userApiKey: string;
+}): Effect.Effect<SessionInfoResponse, HttpServerError | HttpDecodingError> =>
+ Effect.gen(function* () {
+ const response = yield* Effect.tryPromise({
+ try: () =>
+ fetch(`${params.baseURL}/api/v3/auth/session/info`, {
+ method: 'GET',
+ redirect: 'error',
+ headers: {
+ 'x-user-api-key': params.userApiKey,
+ 'User-Agent': '@composio/cli',
+ Accept: '*/*',
+ 'Content-Type': 'application/json',
+ },
+ }),
+ catch: error => new HttpServerError({ cause: error }),
+ });
+
+ if (!response.ok) {
+ return yield* handleHttpErrorResponse(response);
+ }
+
+ const { json } = yield* streamResponseWithByteCount(response);
+
+ return yield* pipe(
+ Schema.decodeUnknown(SessionInfoResponse)(json),
+ Effect.catchTag('ParseError', e => {
+ const message = ParseResult.TreeFormatter.formatErrorSync(e);
+ return new HttpDecodingError({
+ cause: `ParseError\n ${message}`,
+ });
+ })
+ );
+ });
+
// Utility function for calling the Composio API and decoding its response.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const callClient = <T, S extends Schema.Schema<any, any>>(
@@ -1235,12 +1443,19 @@ export class ComposioClientLive extends Effect.Service<ComposioClientLive>()(
cli: {
/**
* Generates a new CLI session with a random 6-character code.
+ * @param params.scope - 'user' for login, 'project' for init (future)
+ *
+ * TODO: don't use `@composio/client`, wrap `fetch` directly.
*/
- createSession: () =>
+ createSession: (params?: { scope?: 'user' | 'project' }) =>
withMetrics(
callClient(
clientSingleton,
- client => client.cli.createSession(),
+ client =>
+ client.cli.createSession(
+ { scope: params?.scope ?? 'user' },
+ { headers: { 'Content-Type': 'application/json' } }
+ ),
CliCreateSessionResponse
)
),
@@ -1541,7 +1756,8 @@ export class ComposioSessionRepository extends Effect.Service<ComposioSessionRep
const client = yield* ComposioClientLive;
return {
- createSession: () => client.cli.createSession(),
+ createSession: (params?: { scope?: 'user' | 'project' }) =>
+ client.cli.createSession(params),
getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
diff --git a/ts/packages/cli/src/services/project-context.ts b/ts/packages/cli/src/services/project-context.ts
new file mode 100644
index 000000000..8ac6353d1
--- /dev/null
+++ b/ts/packages/cli/src/services/project-context.ts
@@ -0,0 +1,153 @@
+import path from 'node:path';
+import { Effect, Option } from 'effect';
+import { FileSystem } from '@effect/platform';
+import { NodeOs } from 'src/services/node-os';
+import { NodeProcess } from 'src/services/node-process';
+import { APP_CONFIG } from 'src/effects/app-config';
+import * as constants from 'src/constants';
+import { type ProjectKeys, projectKeysFromJSON } from 'src/models/project-keys';
+import type { PlatformError } from '@effect/platform/Error';
+import type { ParseError } from 'effect/ParseResult';
+
+/**
+ * Keys allowed in `.composio/.env` files.
+ * Only project context keys are permitted -- NOT API_KEY or BASE_URL,
+ * to prevent credential injection via malicious repo clones.
+ */
+const ALLOWED_ENV_KEYS = new Set(['COMPOSIO_ORG_ID', 'COMPOSIO_PROJECT_ID']);
+
+/**
+ * Parse a `.env` file into a key-value map.
+ * Only keys in the ALLOWED_ENV_KEYS set are returned.
+ */
+const parseEnvFile = (content: string): Map<string, string> => {
+ const result = new Map<string, string>();
+ for (const line of content.split('\n')) {
+ const trimmed = line.trim();
+ if (trimmed === '' || trimmed.startsWith('#')) continue;
+ const eqIndex = trimmed.indexOf('=');
+ if (eqIndex === -1) continue;
+ const key = trimmed.slice(0, eqIndex).trim();
+ let value = trimmed.slice(eqIndex + 1).trim();
+ // Strip surrounding quotes (single or double) consistent with dotenv convention
+ if (
+ (value.startsWith('"') && value.endsWith('"')) ||
+ (value.startsWith("'") && value.endsWith("'"))
+ ) {
+ value = value.slice(1, -1);
+ }
+ if (ALLOWED_ENV_KEYS.has(key)) {
+ result.set(key, value);
+ }
+ }
+ return result;
+};
+
+/**
+ * Service that resolves the current project context using a precedence chain.
+ * Read-only -- it does NOT write files.
+ *
+ * Precedence (highest first):
+ * 1. System env vars (COMPOSIO_ORG_ID, COMPOSIO_PROJECT_ID)
+ * 2. Per-directory .composio/.env (only allowed keys)
+ * 3. Per-directory .composio/project.json (walk up from CWD, stop at homedir)
+ */
+export class ProjectContext extends Effect.Service<ProjectContext>()('services/ProjectContext', {
+ effect: Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const proc = yield* NodeProcess;
+ const os = yield* NodeOs;
+
+ return {
+ /**
+ * Resolves the current org+project context.
+ * Returns Option.none() if no context is configured.
+ */
+ resolve: Effect.gen(function* () {
+ // 1. Check env vars (highest priority)
+ const envOrgId = yield* APP_CONFIG.ORG_ID;
+ const envProjectId = yield* APP_CONFIG.PROJECT_ID;
+ if (Option.isSome(envOrgId) && Option.isSome(envProjectId)) {
+ yield* Effect.logDebug('ProjectContext: resolved from env vars');
+ return Option.some<ProjectKeys>({
+ orgId: envOrgId.value,
+ projectId: envProjectId.value,
+ projectName: Option.none(),
+ orgName: Option.none(),
+ email: Option.none(),
+ });
+ }
+
+ // 2. Walk up from CWD, stop at homedir (not filesystem root)
+ let dir = proc.cwd;
+ const stopAt = os.homedir;
+
+ while (true) {
+ const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);
+
+ // 2a. Check .composio/.env
+ const envFilePath = path.join(composioDir, constants.PROJECT_ENV_FILE_NAME);
+ const envExists = yield* fs
+ .exists(envFilePath)
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
+ if (envExists) {
+ const envContent = yield* fs
+ .readFileString(envFilePath)
+ .pipe(Effect.catchAll(() => Effect.succeed('')));
+ const envMap = parseEnvFile(envContent);
+ const envFileOrgId = envMap.get('COMPOSIO_ORG_ID');
+ const envFileProjectId = envMap.get('COMPOSIO_PROJECT_ID');
+ if (envFileOrgId && envFileProjectId) {
+ yield* Effect.logDebug(`ProjectContext: resolved from ${envFilePath}`);
+ return Option.some<ProjectKeys>({
+ orgId: envFileOrgId,
+ projectId: envFileProjectId,
+ projectName: Option.none(),
+ orgName: Option.none(),
+ email: Option.none(),
+ });
+ }
+ }
+
+ // 2b. Check .composio/project.json
+ const projectJsonPath = path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME);
+ const jsonExists = yield* fs
+ .exists(projectJsonPath)
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
+ if (jsonExists) {
+ const content = yield* fs
+ .readFileString(projectJsonPath)
+ .pipe(Effect.catchAll(() => Effect.succeed('')));
+ if (content) {
+ const keysOpt = yield* projectKeysFromJSON(content).pipe(
+ Effect.map(Option.some),
+ Effect.catchAll(error =>
+ Effect.gen(function* () {
+ yield* Effect.logDebug(
+ `ProjectContext: corrupt project.json at ${projectJsonPath}, skipping:`,
+ error
+ );
+ return Option.none();
+ })
+ )
+ );
+ if (Option.isSome(keysOpt)) {
+ yield* Effect.logDebug(`ProjectContext: resolved from ${projectJsonPath}`);
+ return keysOpt;
+ }
+ }
+ }
+
+ // Stop at homedir to avoid reading from system directories
+ if (dir === stopAt || dir === path.dirname(dir)) break;
+ dir = path.dirname(dir);
+ }
+
+ // 3. Nothing found
+ yield* Effect.logDebug('ProjectContext: no context found');
+ return Option.none<ProjectKeys>();
+ }),
+ };
+ }),
+ dependencies: [],
+}) {}
diff --git a/ts/packages/cli/src/services/project-environment-detector.ts b/ts/packages/cli/src/services/project-environment-detector.ts
new file mode 100644
index 000000000..e0abc877f
--- /dev/null
+++ b/ts/packages/cli/src/services/project-environment-detector.ts
@@ -0,0 +1,564 @@
+import { BunFileSystem } from '@effect/platform-bun';
+import { FileSystem } from '@effect/platform';
+import { Data, Effect, Match } from 'effect';
+import * as path from 'node:path';
+import process from 'node:process';
+import { getAncestors } from 'src/utils/get-ancestors';
+
+const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));
+
+export type JsLanguage = 'typescript' | 'javascript';
+export type JsPackageManager = 'pnpm' | 'bun' | 'yarn' | 'npm' | 'deno';
+export type PythonPackageManager = 'uv' | 'pip';
+
+export type ProjectEnvironment =
+ | {
+ kind: 'js';
+ language: JsLanguage;
+ packageManager: JsPackageManager;
+ rootDir: string;
+ evidence: string[];
+ }
+ | {
+ kind: 'python';
+ language: 'python';
+ packageManager: PythonPackageManager;
+ rootDir: string;
+ evidence: string[];
+ };
+
+export class ProjectEnvironmentDetectorError extends Data.TaggedError(
+ 'services/ProjectEnvironmentDetectorError'
+)<{
+ readonly cause: Error;
+ readonly message: string;
+ readonly checkedPaths: string[];
+ readonly details?: string;
+}> {}
+
+// ---------------------------------------------------------------------------
+// Constants
+// ---------------------------------------------------------------------------
+
+const JS_LOCK_FILES: Record<JsPackageManager, string[]> = {
+ pnpm: ['pnpm-lock.yaml', 'pnpm-workspace.yaml'],
+ bun: ['bun.lockb', 'bun.lock'],
+ yarn: ['yarn.lock'],
+ npm: ['package-lock.json', 'npm-shrinkwrap.json'],
+ deno: ['deno.lock', 'deno.lock.json'],
+};
+
+const PYTHON_INDICATORS = new Set([
+ 'pyproject.toml',
+ 'setup.py',
+ 'setup.cfg',
+ 'requirements.txt',
+ 'requirements-dev.txt',
+ 'requirements.in',
+ 'pipfile',
+ 'pipfile.lock',
+ 'poetry.lock',
+ 'uv.lock',
+ 'environment.yml',
+ 'conda.yaml',
+ 'tox.ini',
+ 'pytest.ini',
+]);
+
+const JS_CONFIG_FILES = new Set(['jsconfig.json', 'deno.json', 'deno.jsonc']);
+
+const COMMON_SOURCE_DIRS = ['src', 'lib', 'app', 'apps', 'packages', 'scripts'];
+
+// ---------------------------------------------------------------------------
+// Internal types
+// ---------------------------------------------------------------------------
+
+type DirEvidence = {
+ dir: string;
+ jsScore: number;
+ tsScore: number;
+ pyScore: number;
+ strongJs: boolean;
+ strongPy: boolean;
+ jsHints: {
+ tsConfig: boolean;
+ tsDependency: boolean;
+ tsFiles: boolean;
+ jsFiles: boolean;
+ denoConfig: boolean;
+ };
+ evidence: string[];
+};
+
+// ---------------------------------------------------------------------------
+// Pure helpers (no dependencies)
+// ---------------------------------------------------------------------------
+
+const isTsConfig = (name: string) => {
+ const lower = name.toLowerCase();
+ return lower === 'tsconfig.json' || (lower.startsWith('tsconfig.') && lower.endsWith('.json'));
+};
+
+const countExtensions = (files: string[]) => {
+ let ts = 0;
+ let js = 0;
+ let py = 0;
+
+ for (const file of files) {
+ const ext = path.extname(file).toLowerCase();
+ if (ext === '.ts' || ext === '.tsx' || ext === '.mts' || ext === '.cts') {
+ ts += 1;
+ } else if (ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {
+ js += 1;
+ } else if (ext === '.py' || ext === '.pyi' || ext === '.pyw' || ext === '.pyx') {
+ py += 1;
+ }
+ }
+
+ return { ts, js, py };
+};
+
+const chooseJsLanguage = (evidence: DirEvidence): JsLanguage => {
+ if (evidence.tsScore > evidence.jsScore) return 'typescript';
+ if (evidence.jsScore > evidence.tsScore) return 'javascript';
+ if (evidence.jsHints.tsConfig || evidence.jsHints.tsDependency) return 'typescript';
+ if (evidence.jsHints.tsFiles && !evidence.jsHints.jsFiles) return 'typescript';
+ if (evidence.jsHints.jsFiles && !evidence.jsHints.tsFiles) return 'javascript';
+ if (evidence.jsHints.denoConfig) return 'typescript';
+ return 'javascript';
+};
+
+const pickBestWeak = (candidate: DirEvidence, depth: number) => {
+ const bestScore = Math.max(candidate.tsScore, candidate.jsScore, candidate.pyScore);
+ if (bestScore <= 0) return null;
+ const language =
+ candidate.pyScore >= candidate.tsScore && candidate.pyScore >= candidate.jsScore
+ ? 'python'
+ : chooseJsLanguage(candidate);
+ return {
+ dir: candidate.dir,
+ depth,
+ language,
+ score: bestScore - depth * 0.5,
+ evidence: candidate,
+ } as const;
+};
+
+const parsePackageManagerField = (pm: string) =>
+ Match.value(pm).pipe(
+ Match.when(
+ pm => pm.startsWith('pnpm@'),
+ () => 'pnpm' as const
+ ),
+ Match.when(
+ pm => pm.startsWith('bun@'),
+ () => 'bun' as const
+ ),
+ Match.when(
+ pm => pm.startsWith('yarn@'),
+ () => 'yarn' as const
+ ),
+ Match.when(
+ pm => pm.startsWith('npm@'),
+ () => 'npm' as const
+ ),
+ Match.orElse(() => null)
+ );
+
+/**
+ * Detect package manager from the `npm_config_user_agent` env var.
+ * Set automatically when running via `npx`, `pnpm dlx`, `bunx`, etc.
+ * Inspired by https://github.com/prisma/create-prisma/blob/main/src/utils/package-manager.ts
+ */
+const parseUserAgent = (userAgent: string | undefined): JsPackageManager | null => {
+ if (!userAgent) return null;
+ if (userAgent.startsWith('pnpm')) return 'pnpm';
+ if (userAgent.startsWith('bun')) return 'bun';
+ if (userAgent.startsWith('yarn')) return 'yarn';
+ if (userAgent.startsWith('npm')) return 'npm';
+ return null;
+};
+
+// ---------------------------------------------------------------------------
+// FS helpers (take FileSystem as parameter)
+// ---------------------------------------------------------------------------
+
+const makeReadDirectoryOptional = (fs: FileSystem.FileSystem) => (dir: string) =>
+ fs.readDirectory(dir).pipe(Effect.catchAll(() => Effect.succeed<string[]>([])));
+
+const makeReadFileStringOptional = (fs: FileSystem.FileSystem) => (filePath: string) =>
+ fs.readFileString(filePath).pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
+
+const makeReadPackageJson = (fs: FileSystem.FileSystem) => {
+ const readFileStringOptional = makeReadFileStringOptional(fs);
+ return (dir: string) =>
+ Effect.gen(function* () {
+ const content = yield* readFileStringOptional(path.join(dir, 'package.json'));
+ if (!content) return null;
+ return yield* Effect.try({
+ try: () => JSON.parse(content) as Record<string, unknown>,
+ catch: toError,
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
+ });
+};
+
+// ---------------------------------------------------------------------------
+// Analysis (split into focused functions)
+// ---------------------------------------------------------------------------
+
+const analyzeDirectory = (
+ fs: FileSystem.FileSystem,
+ dir: string
+): Effect.Effect<DirEvidence, ProjectEnvironmentDetectorError> =>
+ Effect.gen(function* () {
+ const files = yield* fs.readDirectory(dir).pipe(
+ Effect.mapError(
+ e =>
+ new ProjectEnvironmentDetectorError({
+ cause: toError(e),
+ message: `Failed to read directory ${dir}`,
+ checkedPaths: [dir],
+ })
+ )
+ );
+ const readDirectoryOptional = makeReadDirectoryOptional(fs);
+ const readFileStringOptional = makeReadFileStringOptional(fs);
+ const readPackageJson = makeReadPackageJson(fs);
+
+ const lowerFiles = files.map(file => file.toLowerCase());
+ const fileSet = new Set(lowerFiles);
+ const fileByLower = new Map<string, string>();
+ for (const file of files) {
+ const lower = file.toLowerCase();
+ if (!fileByLower.has(lower)) fileByLower.set(lower, file);
+ }
+
+ let jsScore = 0;
+ let tsScore = 0;
+ let pyScore = 0;
+ let strongJs = false;
+ let strongPy = false;
+ const evidence: string[] = [];
+ const jsHints = {
+ tsConfig: false,
+ tsDependency: false,
+ tsFiles: false,
+ jsFiles: false,
+ denoConfig: false,
+ };
+
+ // Score file indicators
+ for (const file of lowerFiles) {
+ if (file === 'package.json') {
+ strongJs = true;
+ jsScore += 3;
+ evidence.push('package.json');
+ }
+ if (JS_CONFIG_FILES.has(file)) {
+ strongJs = true;
+ jsScore += 3;
+ if (file === 'deno.json' || file === 'deno.jsonc') {
+ jsHints.denoConfig = true;
+ tsScore += 2;
+ evidence.push(file);
+ }
+ }
+ if (isTsConfig(file)) {
+ strongJs = true;
+ tsScore += 5;
+ jsHints.tsConfig = true;
+ evidence.push('tsconfig');
+ }
+ if (file === 'jsconfig.json') {
+ strongJs = true;
+ jsScore += 4;
+ evidence.push('jsconfig.json');
+ }
+ if (file === 'pnpm-workspace.yaml') {
+ strongJs = true;
+ jsScore += 3;
+ evidence.push('pnpm-workspace.yaml');
+ }
+ if (PYTHON_INDICATORS.has(file)) {
+ strongPy = true;
+ pyScore += 3;
+ evidence.push(file);
+ if (file === 'uv.lock') pyScore += 2;
+ }
+ }
+
+ // Score JS lock files
+ for (const [, lockFiles] of Object.entries(JS_LOCK_FILES)) {
+ if (lockFiles.some(lf => fileSet.has(lf))) {
+ strongJs = true;
+ jsScore += 4;
+ evidence.push(lockFiles.find(lf => fileSet.has(lf)) ?? lockFiles[0]);
+ }
+ }
+
+ // Score from package.json content
+ const packageJson = yield* readPackageJson(dir);
+ if (packageJson) {
+ const deps = (packageJson.dependencies ?? {}) as Record<string, string>;
+ const devDeps = (packageJson.devDependencies ?? {}) as Record<string, string>;
+ if ({ ...deps, ...devDeps }.typescript) {
+ tsScore += 4;
+ jsHints.tsDependency = true;
+ evidence.push('typescript dependency');
+ }
+ const pm =
+ typeof packageJson.packageManager === 'string'
+ ? parsePackageManagerField(packageJson.packageManager)
+ : null;
+ if (pm) {
+ jsScore += 2;
+ strongJs = true;
+ evidence.push(`packageManager:${pm}`);
+ }
+ }
+
+ // Score from pyproject.toml content
+ const pyProject = yield* readFileStringOptional(path.join(dir, 'pyproject.toml'));
+ if (pyProject) {
+ const hasPythonSections = [
+ '[project]',
+ '[tool.poetry]',
+ '[tool.setuptools]',
+ '[tool.uv]',
+ '[build-system]',
+ ].some(s => pyProject.includes(s));
+ if (hasPythonSections) {
+ strongPy = true;
+ pyScore += 2;
+ }
+ }
+
+ // Score from file extensions
+ const extensionCounts = countExtensions(files);
+ if (extensionCounts.ts > 0) {
+ tsScore += Math.min(3, extensionCounts.ts);
+ jsHints.tsFiles = true;
+ }
+ if (extensionCounts.js > 0) {
+ jsScore += Math.min(3, extensionCounts.js);
+ jsHints.jsFiles = true;
+ }
+ if (extensionCounts.py > 0) {
+ pyScore += Math.min(3, extensionCounts.py);
+ }
+
+ // Score from subdirectory extensions
+ for (const subdir of COMMON_SOURCE_DIRS) {
+ if (!fileSet.has(subdir)) continue;
+ const actualSubdir = fileByLower.get(subdir) ?? subdir;
+ const subFiles = yield* readDirectoryOptional(path.join(dir, actualSubdir));
+ const subCounts = countExtensions(subFiles);
+ if (subCounts.ts > 0) {
+ tsScore += Math.min(2, subCounts.ts);
+ jsHints.tsFiles = true;
+ }
+ if (subCounts.js > 0) {
+ jsScore += Math.min(2, subCounts.js);
+ jsHints.jsFiles = true;
+ }
+ if (subCounts.py > 0) {
+ pyScore += Math.min(2, subCounts.py);
+ }
+ }
+
+ return {
+ dir,
+ jsScore,
+ tsScore,
+ pyScore,
+ strongJs,
+ strongPy,
+ jsHints,
+ evidence,
+ } satisfies DirEvidence;
+ });
+
+// ---------------------------------------------------------------------------
+// Detection functions
+// ---------------------------------------------------------------------------
+
+const detectLanguage = (fs: FileSystem.FileSystem, cwd: string) =>
+ Effect.gen(function* () {
+ const dirs = getAncestors(cwd);
+ let bestWeak: ReturnType<typeof pickBestWeak> | null = null;
+ let ambiguous: { dir: string; details: string } | null = null;
+
+ for (const [depth, dir] of dirs.entries()) {
+ const evidence = yield* analyzeDirectory(fs, dir);
+
+ if (evidence.strongJs && evidence.strongPy) {
+ if (depth === 0) {
+ return yield* Effect.fail(
+ new ProjectEnvironmentDetectorError({
+ cause: new Error('Ambiguous project language'),
+ message: `Detected both JavaScript/TypeScript and Python indicators in ${dir}`,
+ details: `Indicators: ${evidence.evidence.join(', ')}`,
+ checkedPaths: dirs,
+ })
+ );
+ }
+ if (!ambiguous) ambiguous = { dir, details: `Indicators: ${evidence.evidence.join(', ')}` };
+ continue;
+ }
+
+ if (evidence.strongJs)
+ return { language: chooseJsLanguage(evidence), rootDir: dir, evidence } as const;
+ if (evidence.strongPy)
+ return { language: 'python' as const, rootDir: dir, evidence } as const;
+
+ const weakCandidate = pickBestWeak(evidence, depth);
+ if (weakCandidate && (!bestWeak || weakCandidate.score > bestWeak.score))
+ bestWeak = weakCandidate;
+ }
+
+ if (bestWeak)
+ return {
+ language: bestWeak.language,
+ rootDir: bestWeak.dir,
+ evidence: bestWeak.evidence,
+ } as const;
+
+ if (ambiguous) {
+ return yield* Effect.fail(
+ new ProjectEnvironmentDetectorError({
+ cause: new Error('Ambiguous project language'),
+ message: `Detected both JavaScript/TypeScript and Python indicators in ${ambiguous.dir}`,
+ details: ambiguous.details,
+ checkedPaths: dirs,
+ })
+ );
+ }
+
+ return yield* Effect.fail(
+ new ProjectEnvironmentDetectorError({
+ cause: new Error('No project language detected'),
+ message: `No recognizable JavaScript/TypeScript or Python project indicators found in ${cwd}`,
+ checkedPaths: dirs,
+ })
+ );
+ });
+
+const detectJsPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
+ Effect.gen(function* () {
+ const readDirectoryOptional = makeReadDirectoryOptional(fs);
+ const readPackageJson = makeReadPackageJson(fs);
+ const dirs = getAncestors(cwd);
+
+ for (const dir of dirs) {
+ const files = yield* readDirectoryOptional(dir);
+ const fileSet = new Set(files.map(f => f.toLowerCase()));
+
+ if (fileSet.has('package.json')) {
+ const pkg = yield* readPackageJson(dir);
+ if (pkg && typeof pkg.packageManager === 'string') {
+ const pm = parsePackageManagerField(pkg.packageManager);
+ if (pm) return pm;
+ }
+ }
+
+ if (fileSet.has('deno.json') || fileSet.has('deno.jsonc') || fileSet.has('deno.lock'))
+ return 'deno' as const;
+
+ for (const pm of ['pnpm', 'bun', 'yarn', 'npm'] as const) {
+ if (JS_LOCK_FILES[pm].some(lf => fileSet.has(lf))) return pm;
+ }
+
+ if (fileSet.has('pnpm-workspace.yaml')) return 'pnpm' as const;
+ }
+
+ const userAgent = parseUserAgent(process.env.npm_config_user_agent);
+ if (userAgent) return userAgent;
+
+ return 'npm' as const;
+ });
+
+const detectPythonPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
+ Effect.gen(function* () {
+ const readDirectoryOptional = makeReadDirectoryOptional(fs);
+ const readFileStringOptional = makeReadFileStringOptional(fs);
+ const dirs = getAncestors(cwd);
+ let fallback: PythonPackageManager | null = null;
+
+ for (const dir of dirs) {
+ const files = yield* readDirectoryOptional(dir);
+ const fileSet = new Set(files.map(f => f.toLowerCase()));
+
+ if (fileSet.has('uv.lock')) return 'uv' as const;
+
+ if (fileSet.has('pyproject.toml')) {
+ const content = yield* readFileStringOptional(path.join(dir, 'pyproject.toml'));
+ if (content?.includes('[tool.uv]')) return 'uv' as const;
+ }
+
+ if (
+ [
+ 'requirements.txt',
+ 'requirements-dev.txt',
+ 'requirements.in',
+ 'setup.py',
+ 'setup.cfg',
+ 'pipfile',
+ 'pipfile.lock',
+ 'poetry.lock',
+ 'environment.yml',
+ 'conda.yaml',
+ ].some(f => fileSet.has(f))
+ ) {
+ fallback = 'pip';
+ }
+ }
+
+ return fallback ?? 'pip';
+ });
+
+// ---------------------------------------------------------------------------
+// Service
+// ---------------------------------------------------------------------------
+
+export class ProjectEnvironmentDetector extends Effect.Service<ProjectEnvironmentDetector>()(
+ 'services/ProjectEnvironmentDetector',
+ {
+ effect: Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+
+ const detectProjectEnvironment = (
+ cwd: string
+ ): Effect.Effect<ProjectEnvironment, ProjectEnvironmentDetectorError> =>
+ Effect.gen(function* () {
+ const detection = yield* detectLanguage(fs, cwd);
+
+ if (detection.language === 'python') {
+ const packageManager = yield* detectPythonPackageManager(fs, detection.rootDir);
+ return {
+ kind: 'python',
+ language: 'python',
+ packageManager,
+ rootDir: detection.rootDir,
+ evidence: detection.evidence.evidence,
+ } satisfies ProjectEnvironment;
+ }
+
+ const packageManager = yield* detectJsPackageManager(fs, detection.rootDir);
+ return {
+ kind: 'js',
+ language: detection.language,
+ packageManager,
+ rootDir: detection.rootDir,
+ evidence: detection.evidence.evidence,
+ } satisfies ProjectEnvironment;
+ });
+
+ return {
+ detectProjectEnvironment,
+ detectJsPackageManager: (cwd: string) => detectJsPackageManager(fs, cwd),
+ detectPythonPackageManager: (cwd: string) => detectPythonPackageManager(fs, cwd),
+ };
+ }),
+ dependencies: [BunFileSystem.layer],
+ }
+) {}
diff --git a/ts/packages/cli/src/services/terminal-ui.ts b/ts/packages/cli/src/services/terminal-ui.ts
index 9ed5b6557..f644fb61c 100644
--- a/ts/packages/cli/src/services/terminal-ui.ts
+++ b/ts/packages/cli/src/services/terminal-ui.ts
@@ -78,6 +78,19 @@ export interface TerminalUI {
options?: { readonly defaultValue?: boolean }
) => Effect.Effect<boolean>;
+ /**
+ * Present a single-select list to the user.
+ * In non-interactive mode (piped), returns the first option's value.
+ */
+ readonly select: <Value>(
+ message: string,
+ options: ReadonlyArray<{
+ readonly value: Value;
+ readonly label: string;
+ readonly hint?: string;
+ }>
+ ) => Effect.Effect<Value>;
+
/**
* Create a controllable spinner that is automatically stopped on error or interruption.
* The `use` function receives a SpinnerHandle and must return an Effect.
@@ -170,6 +183,24 @@ const makeLive: TerminalUI = {
decorate(() => p.note(message, title ?? '', { format: line => line, output: process.stderr }))
),
+ select: ((
+ message: string,
+ options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>
+ ) =>
+ isInteractive
+ ? Effect.promise(async () => {
+ const result = await p.select({
+ message,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ options: [...options] as any,
+ output: process.stderr,
+ });
+ // p.select returns Value | symbol (symbol on cancel)
+ if (typeof result === 'symbol') return options[0].value;
+ return result;
+ })
+ : Effect.succeed(options[0].value)) as TerminalUI['select'],
+
confirm: (message, options) =>
isInteractive
? Effect.promise(async () => {
diff --git a/ts/packages/cli/src/services/user-context.ts b/ts/packages/cli/src/services/user-context.ts
index 56759e8ab..5b8f8a65e 100644
--- a/ts/packages/cli/src/services/user-context.ts
+++ b/ts/packages/cli/src/services/user-context.ts
@@ -29,9 +29,13 @@ export class ComposioUserContext extends Context.Tag('ComposioUserData')<
logout: Effect.Effect<void, ParseError | PlatformError, never>;
/**
- * Logs in the user by setting the API key.
+ * Logs in the user by setting the API key, and optionally org/project IDs.
*/
- login: (apiKey: string) => Effect.Effect<void, ParseError | PlatformError, never>;
+ login: (
+ apiKey: string,
+ orgId?: string,
+ projectId?: string
+ ) => Effect.Effect<void, ParseError | PlatformError, never>;
/**
* Saves the user data to a persistent store, e.g., file or database.
@@ -58,15 +62,29 @@ export const ComposioUserContextLive = Layer.effect(
apiKey,
baseURL: Option.some(baseURL),
webURL: Option.some(webURL),
+ orgId: Option.none(),
+ projectId: Option.none(),
});
const logout = Effect.gen(function* () {
- yield* update({ apiKey: Option.none(), baseURL: Option.none(), webURL: Option.some(webURL) });
+ yield* update({
+ apiKey: Option.none(),
+ baseURL: Option.none(),
+ webURL: Option.some(webURL),
+ orgId: Option.none(),
+ projectId: Option.none(),
+ });
});
- const login = (apiKey: string) =>
+ const login = (apiKey: string, orgId?: string, projectId?: string) =>
Effect.gen(function* () {
- yield* update({ apiKey: Option.some(apiKey) });
+ yield* update({
+ apiKey: Option.some(apiKey),
+ baseURL: Option.some(baseURL),
+ webURL: Option.some(webURL),
+ orgId: Option.fromNullable(orgId),
+ projectId: Option.fromNullable(projectId),
+ });
});
/**
@@ -97,6 +115,8 @@ export const ComposioUserContextLive = Layer.effect(
apiKey: apiKey.pipe(Option.orElse(() => parsedUserData.apiKey)),
baseURL: Option.some(baseURL),
webURL: Option.some(webURL),
+ orgId: parsedUserData.orgId,
+ projectId: parsedUserData.projectId,
} satisfies UserData;
yield* Effect.logDebug('User data (overridden from env vars):', overriddenUserData);
@@ -107,7 +127,17 @@ export const ComposioUserContextLive = Layer.effect(
if (yield* fs.exists(jsonUserConfigPath)) {
yield* Effect.logDebug('User data file exists, loading it');
- yield* load;
+ yield* load.pipe(
+ Effect.catchAll(error =>
+ Effect.gen(function* () {
+ yield* Effect.logDebug(
+ 'Failed to load user data file (empty or corrupted), resetting to defaults:',
+ error
+ );
+ yield* update(userData);
+ })
+ )
+ );
} else {
yield* Effect.logDebug('User data file does not exist, creating a new one');
yield* update(userData);
@@ -119,6 +149,8 @@ export const ComposioUserContextLive = Layer.effect(
...userData,
baseURL: Option.getOrElse(userData.baseURL, () => baseURL),
webURL: Option.getOrElse(userData.webURL, () => webURL),
+ orgId: userData.orgId,
+ projectId: userData.projectId,
};
return ComposioUserContext.of({
diff --git a/ts/packages/cli/src/services/utils/pretty-error.ts b/ts/packages/cli/src/services/utils/pretty-error.ts
index 1e0f7b65b..c2c390aba 100644
--- a/ts/packages/cli/src/services/utils/pretty-error.ts
+++ b/ts/packages/cli/src/services/utils/pretty-error.ts
@@ -5,7 +5,7 @@ const S_CORNER_TOP_LEFT = unicodeOr('╭', '+');
const S_CORNER_BOTTOM_LEFT = unicodeOr('╰', '+');
export function renderPrettyError(errorLines: Array<[key: string, value: unknown]>): string {
- return renderPrettyErrorGen(errorLines).toArray().join('\n');
+ return Array.from(renderPrettyErrorGen(errorLines)).join('\n');
}
function* renderPrettyErrorGen(
diff --git a/ts/packages/cli/src/utils/get-ancestors.ts b/ts/packages/cli/src/utils/get-ancestors.ts
new file mode 100644
index 000000000..f5873e590
--- /dev/null
+++ b/ts/packages/cli/src/utils/get-ancestors.ts
@@ -0,0 +1,20 @@
+import path from 'node:path';
+
+/**
+ * Walk up from a directory to the filesystem root, collecting all ancestor paths.
+ * Returns an array starting with the resolved `cwd` and ending at the root.
+ */
+export const getAncestors = (cwd: string): string[] => {
+ const resolved = path.resolve(cwd);
+ const dirs = [resolved];
+ let current = resolved;
+
+ while (true) {
+ const parent = path.dirname(current);
+ if (parent === current) break;
+ dirs.push(parent);
+ current = parent;
+ }
+
+ return dirs;
+};
diff --git a/ts/packages/cli/test/__fixtures__/ambiguous-project/package.json b/ts/packages/cli/test/__fixtures__/ambiguous-project/package.json
new file mode 100644
index 000000000..7beb84dd6
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/ambiguous-project/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "test-ambiguous",
+ "type": "module",
+ "devDependencies": {
+ "typescript": "^5.9.2"
+ }
+}
diff --git a/ts/packages/cli/test/__fixtures__/ambiguous-project/pyproject.toml b/ts/packages/cli/test/__fixtures__/ambiguous-project/pyproject.toml
new file mode 100644
index 000000000..d03906640
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/ambiguous-project/pyproject.toml
@@ -0,0 +1,4 @@
+[project]
+name = "test-ambiguous"
+version = "0.1.0"
+requires-python = ">=3.10"
diff --git a/ts/packages/cli/test/__fixtures__/ambiguous-project/requirements.txt b/ts/packages/cli/test/__fixtures__/ambiguous-project/requirements.txt
new file mode 100644
index 000000000..e091e25e6
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/ambiguous-project/requirements.txt
@@ -0,0 +1 @@
+composio
diff --git a/ts/packages/cli/test/__fixtures__/python-uv-project/pyproject.toml b/ts/packages/cli/test/__fixtures__/python-uv-project/pyproject.toml
new file mode 100644
index 000000000..ddbcfb7de
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/python-uv-project/pyproject.toml
@@ -0,0 +1,7 @@
+[project]
+name = "test-uv-project"
+version = "0.1.0"
+requires-python = ">=3.10"
+
+[tool.uv]
+dev-dependencies = []
diff --git a/ts/packages/cli/test/__fixtures__/python-uv-project/uv.lock b/ts/packages/cli/test/__fixtures__/python-uv-project/uv.lock
new file mode 100644
index 000000000..d9914dfa6
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/python-uv-project/uv.lock
@@ -0,0 +1 @@
+version = 1
diff --git a/ts/packages/cli/test/__fixtures__/typescript-bun-project/bun.lockb b/ts/packages/cli/test/__fixtures__/typescript-bun-project/bun.lockb
new file mode 100644
index 000000000..e69de29bb
diff --git a/ts/packages/cli/test/__fixtures__/typescript-bun-project/package.json b/ts/packages/cli/test/__fixtures__/typescript-bun-project/package.json
new file mode 100644
index 000000000..7bced5a75
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/typescript-bun-project/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "test-bun-project",
+ "type": "module",
+ "devDependencies": {
+ "typescript": "^5.9.2"
+ }
+}
diff --git a/ts/packages/cli/test/__fixtures__/typescript-bun-project/tsconfig.json b/ts/packages/cli/test/__fixtures__/typescript-bun-project/tsconfig.json
new file mode 100644
index 000000000..74ad6e040
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/typescript-bun-project/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext"
+ }
+}
diff --git a/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/package.json b/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/package.json
new file mode 100644
index 000000000..94161eace
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "test-monorepo",
+ "private": true,
+ "packageManager": "[email protected]",
+ "devDependencies": {
+ "typescript": "^5.9.2"
+ }
+}
diff --git a/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/pnpm-lock.yaml b/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/pnpm-lock.yaml
new file mode 100644
index 000000000..b0a073a9c
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/pnpm-lock.yaml
@@ -0,0 +1 @@
+lockfileVersion: '9.0'
diff --git a/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/pnpm-workspace.yaml b/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/pnpm-workspace.yaml
new file mode 100644
index 000000000..18ec407ef
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/pnpm-workspace.yaml
@@ -0,0 +1,2 @@
+packages:
+ - 'packages/*'
diff --git a/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/tsconfig.json b/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/tsconfig.json
new file mode 100644
index 000000000..74ad6e040
--- /dev/null
+++ b/ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext"
+ }
+}
diff --git a/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts b/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
index 89b02728f..84dcea05d 100644
--- a/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
+++ b/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
@@ -26,6 +26,8 @@ export const TerminalUITest = Layer.succeed(
note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
+ select: (_message, options) => Effect.succeed(options[0].value),
+
confirm: (_message, options) => Effect.succeed(options?.defaultValue ?? true),
withSpinner: (message, effect, options) =>
diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.ts
index f2f2278f9..9dba22ec2 100644
--- a/ts/packages/cli/test/__utils__/services/test-layer.ts
+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts
@@ -30,7 +30,6 @@ import {
type InvalidVersionDetail,
} from 'src/services/composio-clients';
import type { ToolkitVersionOverrides } from 'src/effects/toolkit-version-overrides';
-import { EnvLangDetector } from 'src/services/env-lang-detector';
import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
import type { Tools } from 'src/models/tools';
import type { TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
@@ -58,6 +57,12 @@ import type {
SessionToolkitsParams,
} from '@composio/client/resources/tool-router';
import { Stdin } from 'src/services/stdin';
+import { ProjectContext } from 'src/services/project-context';
+import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
+import { CommandRunner } from 'src/services/command-runner';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { CommandExecutor } from '@effect/platform';
+import { Option } from 'effect';
export interface TestLiveInput {
/**
@@ -164,6 +169,19 @@ export interface TestLiveInput {
params?: SessionToolkitsParams | null
) => Promise<SessionToolkitsResponse>;
};
+
+ /**
+ * Override CommandRunner behavior for tests.
+ * When set, the `CommandRunner` service uses the provided mock instance.
+ * When NOT set, uses a default mock that always returns exit code 0.
+ */
+ commandRunner?: CommandRunner;
+
+ /**
+ * Override TerminalUI behavior for tests.
+ * When set, replaces the default TerminalUITest (which auto-selects first option).
+ */
+ terminalUI?: TerminalUI;
}
/**
@@ -857,6 +875,21 @@ export const TestLayer = (input?: TestLiveInput) =>
const CliConfigLive = CliConfig.layer(ComposioCliConfig);
+ // CommandRunner mock — default returns exit code 0
+ const CommandRunnerTest = input?.commandRunner
+ ? Layer.succeed(CommandRunner, input.commandRunner)
+ : Layer.succeed(
+ CommandRunner,
+ new CommandRunner({
+ run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
+ })
+ );
+
+ // TerminalUI — use provided override or default TerminalUITest
+ const TerminalUILayer = input?.terminalUI
+ ? Layer.succeed(TerminalUI, input.terminalUI)
+ : TerminalUITest;
+
const _console = yield* MockConsole.make;
const layers = Layer.mergeAll(
@@ -869,15 +902,22 @@ export const TestLayer = (input?: TestLiveInput) =>
TriggersRealtimeTest,
ComposioClientSingletonTest,
ComposioToolkitsRepositoryTest,
- EnvLangDetector.Default,
JsPackageManagerDetector.Default,
+ ProjectEnvironmentDetector.Default,
+ CommandRunnerTest,
ToolsExecutorTest,
BunFileSystem.layer,
BunContext.layer,
MockTerminal.layer,
BunPath.layer,
StdinTest,
- TerminalUITest
+ TerminalUILayer,
+ Layer.succeed(
+ ProjectContext,
+ new ProjectContext({
+ resolve: Effect.succeed(Option.none()),
+ })
+ )
) satisfies RequiredLayer;
return layers;
@@ -918,10 +958,22 @@ function setupFixtureFolder({ fixture, tempDir }: { fixture?: string; tempDir: s
// Retry the task with a delay between retries and a maximum of 3 retries
const policy = Schedule.addDelay(Schedule.recurs(3), () => '100 millis');
- // If all retries fail, run the fallback effect
+ // If all retries fail, run the fallback effect.
+ // Use tar to skip heavy directories (.venv) that the global setup may have created.
+ // tar --exclude is POSIX and available on any Linux/macOS without extra packages.
const task = Effect.gen(function* () {
yield* fs.makeDirectory(tmpFixturesPath, { recursive: true });
- yield* fs.copy(realFixturePath, tmpFixturesPath);
+ const tarCmd = Command.make(
+ 'tar',
+ '-cf',
+ '-',
+ '--exclude',
+ '.venv',
+ '-C',
+ realFixturePath,
+ '.'
+ ).pipe(Command.pipeTo(Command.make('tar', '-xf', '-', '-C', tmpFixturesPath)));
+ yield* tarCmd.pipe(Command.exitCode, Effect.provide(BunContext.layer));
});
const repeated = Effect.retryOrElse(policy, () =>
diff --git a/ts/packages/cli/test/src/commands/$default.cmd.test.ts b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
index 0aee9e0a0..363f1d1b9 100644
--- a/ts/packages/cli/test/src/commands/$default.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
@@ -15,7 +15,7 @@ describe('CLI: composio', () => {
expect(result).toEqual(
ValidationError.commandMismatch(
HelpDoc.p(
- "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'generate', 'py', 'ts', 'toolkits', 'tools', 'auth-configs', 'connected-accounts', 'triggers'"
+ "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'init', 'generate', 'py', 'ts', 'toolkits', 'tools', 'auth-configs', 'connected-accounts', 'triggers'"
)
)
);
@@ -31,118 +31,7 @@ describe('CLI: composio', () => {
const lines = yield* MockConsole.getLines();
const output = lines.join('\n');
- expect(yield* sanitize(output)).toMatchInlineSnapshot(`
- "composio
-
- composio <VERSION>
-
- USAGE
-
- $ composio [--log-level all | trace | debug | info | warning | error | fatal | none]
-
- DESCRIPTION
-
- Composio CLI - A tool for managing Python and TypeScript composio.dev projects.
-
- OPTIONS
-
- --log-level all | trace | debug | info | warning | error | fatal | none
-
- One of the following: all, trace, debug, info, warning, error, fatal, none
-
- Define log level
-
- This setting is optional.
-
- COMMANDS
-
- - version Display the current Composio CLI version.
-
- - upgrade Upgrade your Composio CLI to the latest available version.
-
- - whoami Display your account information.
-
- - login [--no-browser] Log in to the Composio SDK.
-
- - logout Log out from the Composio SDK.
-
- - generate [(-o, --output-dir directory)] [--type-tools] --toolkits text... Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
-
- - py Handle Python projects.
-
- - py generate [(-o, --output-dir directory)] --toolkits text... Generate Python type stubs for toolkits, tools, and triggers from the Composio API.
-
- Environment Variables:
- COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
- Use "latest" or unset to use the latest version.
-
- - ts Handle TypeScript projects.
-
- - ts generate [(-o, --output-dir directory)] [--compact] [--transpiled] [--type-tools] --toolkits text... Generate TypeScript types for toolkits, tools, and triggers from the Composio API.
-
- Environment Variables:
- COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
- Use "latest" or unset to use the latest version.
-
- - toolkits Discover and inspect Composio toolkits.
-
- - toolkits list [--query text] [--limit integer] [--connected] [--user-id text] List available toolkits with connection status.
-
- - toolkits info [--user-id text] [<slug>] View details of a specific toolkit.
-
- - toolkits search [--limit integer] <query> Search toolkits by use case.
-
- - tools Discover and inspect Composio tools.
-
- - tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
-
- - tools info [<slug>] View details of a specific tool.
-
- - tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
-
- - tools execute [(-d, --data text)] [--user-id text] <slug> Execute a tool by slug with JSON arguments.
-
- - auth-configs View and manage Composio auth configs.
-
- - auth-configs list [--toolkits text] [--query text] [--limit integer] List auth configs.
-
- - auth-configs info [<id>] View details of a specific auth config.
-
- - auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>] Create a new auth config.
-
- - auth-configs delete [(-y, --yes)] [<id>] Delete an auth config.
-
- - connected-accounts View and manage Composio connected accounts.
-
- - connected-accounts list [--toolkits text] [--user-id text] [--status INITIALIZING | INITIATED | ACTIVE | FAILED | EXPIRED | INACTIVE] [--limit integer] List connected accounts.
-
- - connected-accounts info [<id>] View details of a specific connected account.
-
- - connected-accounts whoami [<id>] Show the external account profile for a connected account.
-
- - connected-accounts delete [(-y, --yes)] [<id>] Delete a connected account.
-
- - connected-accounts link [--auth-config text] [--user-id text] [--no-browser] [<toolkit>] Link an external account via OAuth redirect.
-
- - triggers Inspect and subscribe to trigger events.
-
- - triggers list [--toolkits text] [--limit integer] List available trigger types.
-
- - triggers info [<slug>] View details of a specific trigger type.
-
- - triggers listen [--toolkits text] [--trigger-id text] [--connected-account-id text] [--trigger-slug text] [--user-id text] [--json] [--table] [--max-events integer] [--forward text] [--out text] Listen to realtime trigger events for your project.
-
- - triggers status [--user-ids text] [--connected-account-ids text] [--toolkits text] [--trigger-ids text] [--trigger-names text] [--show-disabled] [--limit integer] Show active triggers with optional filters.
-
- - triggers create [--connected-account-id text] [--trigger-config text] [<trigger-name>] Create a new trigger instance.
-
- - triggers enable [<id>] Enable a trigger instance.
-
- - triggers disable [<id>] Disable a trigger instance.
-
- - triggers delete [(-y, --yes)] [<id>] Delete a trigger instance.
- "
- `);
+ expect(yield* sanitize(output)).toMatchSnapshot();
})
);
});
@@ -158,20 +47,4 @@ describe('CLI: composio', () => {
})
);
});
-
- // layer(TestLive())(it => {
- // it.scoped('[Pressing] CTRL+C [Then] quit wizard mode', () =>
- // Effect.gen(function* () {
- // const args = ['--wizard'];
-
- // const fiber = yield* Effect.fork(cli(args));
- // yield* MockTerminal.inputKey('c', { ctrl: true });
- // yield* Fiber.join(fiber);
-
- // const lines = yield* MockConsole.getLines();
- // const output = lines.join('\n');
- // expect(output).toContain('Quitting wizard mode...');
- // })
- // );
- // });
});
diff --git a/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap b/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
new file mode 100644
index 000000000..12726b544
--- /dev/null
+++ b/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
@@ -0,0 +1,116 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`CLI: composio > [Given] --help flag [Then] prints help message 1`] = `
+"composio
+
+composio <VERSION>
+
+USAGE
+
+$ composio [--log-level all | trace | debug | info | warning | error | fatal | none]
+
+DESCRIPTION
+
+Composio CLI - A tool for managing Python and TypeScript composio.dev projects.
+
+OPTIONS
+
+--log-level all | trace | debug | info | warning | error | fatal | none
+
+ One of the following: all, trace, debug, info, warning, error, fatal, none
+
+ Define log level
+
+ This setting is optional.
+
+COMMANDS
+
+ - version Display the current Composio CLI version.
+
+ - upgrade Upgrade your Composio CLI to the latest available version.
+
+ - whoami Display your account information.
+
+ - login [--no-browser] [--api-key text] [--org-id text] [--project-id text] Log in to the Composio SDK.
+
+ - logout Log out from the Composio SDK.
+
+ - init [--org-id text] [--project-id text] [--no-browser] [--dry-run] [--force] [(-y, --yes)] [--no-skills] Initialize a Composio project in the current directory.
+
+ - generate [(-o, --output-dir directory)] [--type-tools] --toolkits text... Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
+
+ - py Handle Python projects.
+
+ - py generate [(-o, --output-dir directory)] --toolkits text... Generate Python type stubs for toolkits, tools, and triggers from the Composio API.
+
+Environment Variables:
+ COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
+ Use "latest" or unset to use the latest version.
+
+ - ts Handle TypeScript projects.
+
+ - ts generate [(-o, --output-dir directory)] [--compact] [--transpiled] [--type-tools] --toolkits text... Generate TypeScript types for toolkits, tools, and triggers from the Composio API.
+
+Environment Variables:
+ COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
+ Use "latest" or unset to use the latest version.
+
+ - toolkits Discover and inspect Composio toolkits.
+
+ - toolkits list [--query text] [--limit integer] [--connected] [--user-id text] List available toolkits with connection status.
+
+ - toolkits info [--user-id text] [<slug>] View details of a specific toolkit.
+
+ - toolkits search [--limit integer] <query> Search toolkits by use case.
+
+ - tools Discover and inspect Composio tools.
+
+ - tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
+
+ - tools info [<slug>] View details of a specific tool.
+
+ - tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
+
+ - tools execute [(-d, --data text)] [--user-id text] <slug> Execute a tool by slug with JSON arguments.
+
+ - auth-configs View and manage Composio auth configs.
+
+ - auth-configs list [--toolkits text] [--query text] [--limit integer] List auth configs.
+
+ - auth-configs info [<id>] View details of a specific auth config.
+
+ - auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>] Create a new auth config.
+
+ - auth-configs delete [(-y, --yes)] [<id>] Delete an auth config.
+
+ - connected-accounts View and manage Composio connected accounts.
+
+ - connected-accounts list [--toolkits text] [--user-id text] [--status INITIALIZING | INITIATED | ACTIVE | FAILED | EXPIRED | INACTIVE] [--limit integer] List connected accounts.
+
+ - connected-accounts info [<id>] View details of a specific connected account.
+
+ - connected-accounts whoami [<id>] Show the external account profile for a connected account.
+
+ - connected-accounts delete [(-y, --yes)] [<id>] Delete a connected account.
+
+ - connected-accounts link [--auth-config text] [--user-id text] [--no-browser] [<toolkit>] Link an external account via OAuth redirect.
+
+ - triggers Inspect and subscribe to trigger events.
+
+ - triggers list [--toolkits text] [--limit integer] List available trigger types.
+
+ - triggers info [<slug>] View details of a specific trigger type.
+
+ - triggers listen [--toolkits text] [--trigger-id text] [--connected-account-id text] [--trigger-slug text] [--user-id text] [--json] [--table] [--max-events integer] [--forward text] [--out text] Listen to realtime trigger events for your project.
+
+ - triggers status [--user-ids text] [--connected-account-ids text] [--toolkits text] [--trigger-ids text] [--trigger-names text] [--show-disabled] [--limit integer] Show active triggers with optional filters.
+
+ - triggers create [--connected-account-id text] [--trigger-config text] [<trigger-name>] Create a new trigger instance.
+
+ - triggers enable [<id>] Enable a trigger instance.
+
+ - triggers disable [<id>] Disable a trigger instance.
+
+ - triggers delete [(-y, --yes)] [<id>] Delete a trigger instance.
+"
+`;
diff --git a/ts/packages/cli/test/src/commands/generate.cmd.test.ts b/ts/packages/cli/test/src/commands/generate.cmd.test.ts
index a7b3a0b72..0a0d2f03a 100644
--- a/ts/packages/cli/test/src/commands/generate.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/generate.cmd.test.ts
@@ -64,6 +64,63 @@ describe('CLI: composio generate', () => {
);
});
+ layer(
+ TestLive({
+ fixture: 'typescript-pnpm-monorepo',
+ })
+ )(it => {
+ it.scoped('[Given] a pnpm monorepo project in cwd [Then] it detects TypeScript', () =>
+ Effect.gen(function* () {
+ const process = yield* NodeProcess;
+ const cwd = process.cwd;
+
+ const args = ['generate', '--output-dir', cwd];
+ yield* cli(args);
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+ expect(output).toContain('Project type detected: TypeScript');
+ })
+ );
+ });
+
+ layer(
+ TestLive({
+ fixture: 'typescript-bun-project',
+ })
+ )(it => {
+ it.scoped('[Given] a bun project in cwd [Then] it detects TypeScript', () =>
+ Effect.gen(function* () {
+ const process = yield* NodeProcess;
+ const cwd = process.cwd;
+
+ const args = ['generate', '--output-dir', cwd];
+ yield* cli(args);
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+ expect(output).toContain('Project type detected: TypeScript');
+ })
+ );
+ });
+
+ layer(
+ TestLive({
+ fixture: 'python-uv-project',
+ })
+ )(it => {
+ it.scoped('[Given] a uv Python project in cwd [Then] it detects Python', () =>
+ Effect.gen(function* () {
+ const process = yield* NodeProcess;
+ const cwd = process.cwd;
+
+ const args = ['generate', '--output-dir', cwd];
+ yield* cli(args);
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+ expect(output).toContain('Project type detected: Python');
+ })
+ );
+ });
+
layer(
TestLive({
fixture: 'typescript-project',
diff --git a/ts/packages/cli/test/src/commands/init.cmd.test.ts b/ts/packages/cli/test/src/commands/init.cmd.test.ts
new file mode 100644
index 000000000..0b7860e59
--- /dev/null
+++ b/ts/packages/cli/test/src/commands/init.cmd.test.ts
@@ -0,0 +1,512 @@
+import path from 'node:path';
+import { describe, expect, layer } from '@effect/vitest';
+import { vi, afterEach, beforeAll, afterAll } from 'vitest';
+import { Console, Effect, Exit } from 'effect';
+import { CommandExecutor, FileSystem } from '@effect/platform';
+import { NodeProcess } from 'src/services/node-process';
+import { CommandRunner } from 'src/services/command-runner';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { cli, TestLive, MockConsole } from 'test/__utils__';
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+const makeSessionInfoBody = () => ({
+ project: {
+ name: 'test-project',
+ id: 'proj_test_123',
+ org_id: 'org_test_456',
+ nano_id: 'pr_nano_789',
+ email: '[email protected]',
+ created_at: '2026-01-01T00:00:00.000Z',
+ updated_at: '2026-01-01T00:00:00.000Z',
+ org: { name: 'Test Org', id: 'org_test_456', plan: 'free' },
+ },
+ org_member: {
+ id: 'org_test_456',
+ email: '[email protected]',
+ name: 'Test User',
+ role: 'admin',
+ },
+ api_key: {
+ name: 'default',
+ project_id: 'proj_test_123',
+ id: 'ak_test',
+ org_member_id: 'org_test_456',
+ },
+});
+
+function mockFetchResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+const makeCommandRunnerSuccess = () =>
+ new CommandRunner({
+ run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
+ });
+
+const makeCommandRunnerFail = (exitCode = 1) =>
+ new CommandRunner({
+ run: () => Effect.succeed(CommandExecutor.ExitCode(exitCode)),
+ });
+
+/**
+ * Creates a TerminalUI where specific `select()` calls return custom values.
+ * `selectOverrides` maps call index (0-based) to the option index to pick.
+ * Calls without overrides default to picking the first option (index 0).
+ */
+const makeTerminalUIWithSelectOverrides = (selectOverrides: Record<number, number>): TerminalUI => {
+ let selectCallIndex = 0;
+
+ return 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) => {
+ const idx = selectCallIndex++;
+ const optionIdx = selectOverrides[idx] ?? 0;
+ return Effect.succeed(options[optionIdx].value);
+ },
+ confirm: (_message, options) => Effect.succeed(options?.defaultValue ?? true),
+ 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) =>
+ Effect.gen(function* () {
+ let stopped = false;
+ const handle = {
+ message: (_msg: string) => Effect.void,
+ stop: (msg?: string) =>
+ Effect.gen(function* () {
+ stopped = true;
+ if (msg) yield* Console.log(msg);
+ }),
+ error: (msg?: string) =>
+ Effect.gen(function* () {
+ stopped = true;
+ if (msg) yield* Console.error(msg);
+ }),
+ };
+ const exit = yield* Effect.exit(use(handle));
+ if (Exit.isFailure(exit) && !stopped) {
+ yield* Console.error(message);
+ }
+ return yield* exit;
+ }),
+ });
+};
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+
+describe('CLI: composio init', () => {
+ let savedUserAgent: string | undefined;
+
+ beforeAll(() => {
+ savedUserAgent = process.env.npm_config_user_agent;
+ delete process.env.npm_config_user_agent;
+ });
+
+ afterAll(() => {
+ if (savedUserAgent !== undefined) {
+ process.env.npm_config_user_agent = savedUserAgent;
+ } else {
+ delete process.env.npm_config_user_agent;
+ }
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe('[Given] --org-id + --project-id flags with TS project', () => {
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
+ it => {
+ it.scoped('[Then] detects TS project and installs dependency', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ mockFetchResponse(makeSessionInfoBody())
+ );
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('typescript');
+ expect(output).toContain('Installed @composio/core');
+ })
+ );
+ }
+ );
+ });
+
+ describe('[Given] --org-id + --project-id flags with Python project', () => {
+ layer(TestLive({ fixture: 'python-project', commandRunner: makeCommandRunnerSuccess() }))(
+ it => {
+ it.scoped('[Then] detects Python project and shows correct install command', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ mockFetchResponse(makeSessionInfoBody())
+ );
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('python');
+ expect(output).toContain('pip install composio');
+ expect(output).toContain('Dry run complete.');
+ })
+ );
+ }
+ );
+ });
+
+ describe('[Given] --dry-run flag with TS project', () => {
+ layer(TestLive({ fixture: 'typescript-project' }))(it => {
+ it.scoped('[Then] prints install command without executing', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('npm install -S @composio/core');
+ expect(output).toContain('Dry run complete.');
+ expect(output).not.toContain('Installed @composio/core');
+ })
+ );
+ });
+ });
+
+ describe('[Given] @composio/core already in node_modules', () => {
+ layer(
+ TestLive({
+ fixture: 'typescript-project-with-composio-core',
+ commandRunner: makeCommandRunnerSuccess(),
+ })
+ )(it => {
+ it.scoped('[Then] skips install', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('Dependency already installed');
+ expect(output).not.toContain('Installed @composio/core');
+ })
+ );
+ });
+ });
+
+ describe('[Given] --force flag with dependency installed', () => {
+ layer(
+ TestLive({
+ fixture: 'typescript-project-with-composio-core',
+ commandRunner: makeCommandRunnerSuccess(),
+ })
+ )(it => {
+ it.scoped('[Then] reinstalls', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--force', '--yes'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('Reinstalling due to --force');
+ expect(output).toContain('Installed @composio/core');
+ })
+ );
+ });
+ });
+
+ describe('[Given] install command fails', () => {
+ layer(
+ TestLive({
+ fixture: 'typescript-project',
+ commandRunner: makeCommandRunnerFail(1),
+ })
+ )(it => {
+ it.scoped('[Then] shows error and suggests manual install', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('Install failed');
+ expect(output).toContain('install manually');
+ })
+ );
+ });
+ });
+
+ describe('[Given] pnpm monorepo fixture', () => {
+ layer(
+ TestLive({
+ fixture: 'typescript-pnpm-monorepo',
+ commandRunner: makeCommandRunnerSuccess(),
+ })
+ )(it => {
+ it.scoped('[Then] detects pnpm and uses pnpm add', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('pnpm');
+ expect(output).toContain('pnpm add @composio/core');
+ })
+ );
+ });
+ });
+
+ // ── Skills installation tests ──────────────────────────────────────────────
+
+ describe('[Given] skills install with --yes flag', () => {
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
+ it => {
+ it.scoped('[Then] installs Composio skills', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ mockFetchResponse(makeSessionInfoBody())
+ );
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('Installed Composio skills');
+ })
+ );
+ }
+ );
+ });
+
+ describe('[Given] --dry-run flag shows skills command', () => {
+ layer(TestLive({ fixture: 'typescript-project' }))(it => {
+ it.scoped('[Then] prints skills install command without executing', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('npx skills add composiohq/skills');
+ expect(output).not.toContain('Installed Composio skills');
+ })
+ );
+ });
+ });
+
+ describe('[Given] skills install command fails', () => {
+ layer(
+ TestLive({
+ fixture: 'typescript-project',
+ commandRunner: makeCommandRunnerFail(1),
+ })
+ )(it => {
+ it.scoped('[Then] shows error and suggests manual skills install', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ expect(output).toContain('Skills install failed');
+ expect(output).toContain('npx skills add composiohq/skills');
+ })
+ );
+ });
+ });
+
+ // ── --no-skills flag tests ─────────────────────────────────────────────────
+
+ describe('[Given] --no-skills flag', () => {
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
+ it => {
+ it.scoped('[Then] skips skills prompt and does not install skills', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ mockFetchResponse(makeSessionInfoBody())
+ );
+
+ const proc = yield* NodeProcess;
+ const fs = yield* FileSystem.FileSystem;
+ const args = [
+ 'init',
+ '--org-id',
+ 'org1',
+ '--project-id',
+ 'proj1',
+ '--yes',
+ '--no-skills',
+ ];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ // Should NOT install skills
+ expect(output).not.toContain('Installed Composio skills');
+ // Should still install the core dependency
+ expect(output).toContain('Installed @composio/core');
+
+ // config.json should have install_skills: false
+ const configPath = path.join(proc.cwd, '.composio', 'config.json');
+ const configContent = yield* fs.readFileString(configPath);
+ const config = JSON.parse(configContent);
+ expect(config.install_skills).toBe(false);
+ })
+ );
+ }
+ );
+ });
+
+ // ── MCP mode and PM-skip tests ─────────────────────────────────────────────
+
+ describe('[Given] MCP usage mode selected', () => {
+ // Select overrides: 0th select (usage mode) → index 1 ("Composio MCP")
+ const mcpUI = makeTerminalUIWithSelectOverrides({ 0: 1 });
+
+ layer(
+ TestLive({
+ fixture: 'typescript-project',
+ commandRunner: makeCommandRunnerSuccess(),
+ terminalUI: mcpUI,
+ })
+ )(it => {
+ it.scoped('[Then] skips env detection and dependency install', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const proc = yield* NodeProcess;
+ const fs = yield* FileSystem.FileSystem;
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ // Should NOT detect environment or install dependency in MCP mode
+ expect(output).not.toContain('Detected:');
+ expect(output).not.toContain('Installed @composio/core');
+ expect(output).toContain('Project initialized');
+
+ // config.json should not have detected_language or package_manager
+ const configPath = path.join(proc.cwd, '.composio', 'config.json');
+ const configContent = yield* fs.readFileString(configPath);
+ const config = JSON.parse(configContent);
+ expect(config.usage_mode).toBe('mcp');
+ expect(config.detected_language).toBeUndefined();
+ expect(config.package_manager).toBeUndefined();
+ })
+ );
+ });
+ });
+
+ describe('[Given] native mode but user skips PM confirmation', () => {
+ // Select overrides:
+ // 0th select (usage mode) → index 0 ("Native tools")
+ // 1st select (framework) → index 0 ("Skip")
+ // 2nd select (PM confirm) → index 1 ("Skip")
+ const skipPmUI = makeTerminalUIWithSelectOverrides({ 2: 1 });
+
+ layer(
+ TestLive({
+ fixture: 'typescript-project',
+ commandRunner: makeCommandRunnerSuccess(),
+ terminalUI: skipPmUI,
+ })
+ )(it => {
+ it.scoped('[Then] detects env but skips dependency install', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
+
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
+ yield* cli(args);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+
+ // Should detect environment but NOT install dependency
+ expect(output).toContain('Detected:');
+ expect(output).not.toContain('Installed @composio/core');
+ expect(output).toContain('Project initialized');
+ })
+ );
+ });
+ });
+
+ describe('[Given] config files are written', () => {
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
+ it => {
+ it.scoped('[Then] config.json includes detection info', () =>
+ Effect.gen(function* () {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ mockFetchResponse(makeSessionInfoBody())
+ );
+
+ const proc = yield* NodeProcess;
+ const fs = yield* FileSystem.FileSystem;
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
+ yield* cli(args);
+
+ const configPath = path.join(proc.cwd, '.composio', 'config.json');
+ const configContent = yield* fs.readFileString(configPath);
+ const config = JSON.parse(configContent);
+
+ expect(config.detected_language).toBeDefined();
+ expect(config.package_manager).toBeDefined();
+ })
+ );
+ }
+ );
+ });
+});
diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.ts
new file mode 100644
index 000000000..bca8b7610
--- /dev/null
+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts
@@ -0,0 +1,247 @@
+import { describe, expect, layer } from '@effect/vitest';
+import { vi, afterEach } from 'vitest';
+import { Effect } from 'effect';
+import { ComposioUserContext } from 'src/services/user-context';
+import { cli, TestLive, MockConsole } from 'test/__utils__';
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+/**
+ * Build a canned SessionInfoResponse JSON body for mocking `getSessionInfo`
+ * and `getSessionInfoByUserApiKey`.
+ */
+const makeSessionInfoBody = (overrides?: {
+ orgId?: string;
+ orgName?: string;
+ projectId?: string;
+ projectNanoId?: string;
+ projectName?: string;
+ email?: string;
+ memberName?: string;
+}) => ({
+ project: {
+ name: overrides?.projectName ?? 'test-project',
+ id: overrides?.projectId ?? 'proj_test_123',
+ org_id: overrides?.orgId ?? 'org_test_456',
+ nano_id: overrides?.projectNanoId ?? 'pr_nano_789',
+ email: overrides?.email ?? '[email protected]',
+ created_at: '2026-01-01T00:00:00.000Z',
+ updated_at: '2026-01-01T00:00:00.000Z',
+ org: {
+ name: overrides?.orgName ?? 'Test Org',
+ id: overrides?.orgId ?? 'org_test_456',
+ plan: 'free',
+ },
+ },
+ org_member: {
+ id: overrides?.orgId ?? 'org_test_456',
+ email: overrides?.email ?? '[email protected]',
+ name: overrides?.memberName ?? 'Test User',
+ role: 'admin',
+ },
+ api_key: {
+ name: 'default',
+ project_id: overrides?.projectId ?? 'proj_test_123',
+ id: 'ak_test',
+ org_member_id: overrides?.orgId ?? 'org_test_456',
+ },
+});
+
+/**
+ * Creates a mock Response object.
+ */
+function mockFetchResponse(body: unknown, status = 200): Response {
+ const bodyStr = JSON.stringify(body);
+ return new Response(bodyStr, {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+
+describe('CLI: composio login', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe('[When] not logged in', () => {
+ describe('non-interactive login: session/info succeeds', () => {
+ layer(TestLive())(it => {
+ it.scoped('[Then] stores credentials with enriched org/project IDs', () =>
+ Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ expect(ctx.isLoggedIn()).toBe(false);
+
+ // Mock fetch for getSessionInfo call
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ mockFetchResponse(
+ makeSessionInfoBody({
+ orgId: 'org_verified',
+ projectId: 'proj_verified',
+ email: '[email protected]',
+ projectName: 'Verified Project',
+ orgName: 'Verified Org',
+ })
+ )
+ );
+
+ yield* cli([
+ 'login',
+ '--api-key',
+ 'uak_test_key',
+ '--org-id',
+ 'org_initial',
+ '--project-id',
+ 'proj_initial',
+ ]);
+
+ // Verify fetch was called with session/info endpoint and correct headers
+ expect(fetchSpy).toHaveBeenCalledOnce();
+ const [url, init] = fetchSpy.mock.calls[0]!;
+ expect(url).toContain('/api/v3/auth/session/info');
+ expect((init as RequestInit).headers).toMatchObject({
+ 'x-api-key': 'uak_test_key',
+ 'x-org-id': 'org_initial',
+ 'x-project-id': 'proj_initial',
+ });
+
+ // The mutable isLoggedIn closure reflects the login
+ expect(ctx.isLoggedIn()).toBe(true);
+
+ // Verify console output contains the enriched email and success message
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+ expect(output).toContain('[email protected]');
+ expect(output).toContain("You're all set!");
+ })
+ );
+ });
+ });
+
+ describe('non-interactive login: session/info returns 500', () => {
+ layer(TestLive())(it => {
+ it.scoped('[Then] falls back to initial IDs on server error', () =>
+ Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ expect(ctx.isLoggedIn()).toBe(false);
+
+ // Mock fetch to return a 500 error.
+ // In strict mode, only 400-499 are hard failures.
+ // 500 falls through the generic catch → undefined sessionInfo → use initial IDs.
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ mockFetchResponse(
+ {
+ status: 500,
+ error: {
+ error: {
+ message: 'Internal server error',
+ suggested_fix: 'Try again later',
+ code: 500,
+ },
+ },
+ },
+ 500
+ )
+ );
+
+ yield* cli([
+ 'login',
+ '--api-key',
+ 'uak_fallback_key',
+ '--org-id',
+ 'org_fallback',
+ '--project-id',
+ 'proj_fallback',
+ ]);
+
+ // Credentials stored with initial (uncorrected) IDs since session/info failed
+ expect(ctx.isLoggedIn()).toBe(true);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+ expect(output).toContain('Logged in');
+ })
+ );
+ });
+ });
+
+ describe('non-interactive login: session/info returns 401', () => {
+ layer(TestLive())(it => {
+ it.scoped('[Then] rejects invalid API key', () =>
+ Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ expect(ctx.isLoggedIn()).toBe(false);
+
+ // Mock fetch to return 401
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ mockFetchResponse(
+ {
+ status: 401,
+ error: {
+ error: {
+ message: 'Invalid API key',
+ suggested_fix: 'Check your API key',
+ code: 401,
+ },
+ },
+ },
+ 401
+ )
+ );
+
+ // Non-interactive login: strict verification fails on 401
+ const result = yield* cli([
+ 'login',
+ '--api-key',
+ 'uak_bad_key',
+ '--org-id',
+ 'org_test',
+ '--project-id',
+ 'proj_test',
+ ]).pipe(Effect.either);
+
+ // The command should fail
+ expect(result._tag).toBe('Left');
+
+ // Should NOT be logged in after a failed verification
+ expect(ctx.isLoggedIn()).toBe(false);
+ })
+ );
+ });
+ });
+
+ describe('non-interactive login: session/info network failure', () => {
+ layer(TestLive())(it => {
+ it.scoped('[Then] falls back to initial IDs on network error', () =>
+ Effect.gen(function* () {
+ const ctx = yield* ComposioUserContext;
+ expect(ctx.isLoggedIn()).toBe(false);
+
+ // Mock fetch to throw a network error
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('fetch failed'));
+
+ yield* cli([
+ 'login',
+ '--api-key',
+ 'uak_network_key',
+ '--org-id',
+ 'org_net',
+ '--project-id',
+ 'proj_net',
+ ]);
+
+ // Network errors are non-fatal even in strict mode (only 400-499 are strict)
+ // Actually: the fetch itself fails → HttpServerError with no status →
+ // strict check (e.status >= 400 && < 500) doesn't match → falls through → undefined
+ expect(ctx.isLoggedIn()).toBe(true);
+
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+ expect(output).toContain('Logged in');
+ })
+ );
+ });
+ });
+ });
+});
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 1cdb9ce47..365edbd1a 100644
--- a/ts/packages/cli/test/src/commands/logout.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/logout.cmd.test.ts
@@ -17,6 +17,8 @@ describe('CLI: composio logout', () => {
apiKey: Option.none(),
baseURL: 'https://backend.composio.dev',
webURL: 'https://platform.composio.dev',
+ orgId: Option.none(),
+ projectId: Option.none(),
});
expect(ctx.data).toMatchObject(expectedUserData);
@@ -51,6 +53,8 @@ describe('CLI: composio logout', () => {
apiKey: Option.some('api_key_already_logged_in'),
baseURL: 'https://backend.composio.dev',
webURL: 'https://platform.composio.dev',
+ orgId: Option.none(),
+ projectId: Option.none(),
})
);
diff --git a/ts/packages/cli/test/src/effects/core-dependency.test.ts b/ts/packages/cli/test/src/effects/core-dependency.test.ts
new file mode 100644
index 000000000..f19e50c79
--- /dev/null
+++ b/ts/packages/cli/test/src/effects/core-dependency.test.ts
@@ -0,0 +1,36 @@
+import { describe, it, expect } from 'vitest';
+import { getJsInstallCommand, getPythonInstallCommand } from 'src/effects/core-dependency';
+
+describe('core-dependency', () => {
+ describe('getJsInstallCommand', () => {
+ it('[Given] pnpm [Then] returns "pnpm add <dep>"', () => {
+ expect(getJsInstallCommand('pnpm', '@composio/core')).toBe('pnpm add @composio/core');
+ });
+
+ it('[Given] npm [Then] returns "npm install -S <dep>"', () => {
+ expect(getJsInstallCommand('npm', '@composio/core')).toBe('npm install -S @composio/core');
+ });
+
+ it('[Given] yarn [Then] returns "yarn add <dep>"', () => {
+ expect(getJsInstallCommand('yarn', '@composio/core')).toBe('yarn add @composio/core');
+ });
+
+ it('[Given] bun [Then] returns "bun add <dep>"', () => {
+ expect(getJsInstallCommand('bun', '@composio/core')).toBe('bun add @composio/core');
+ });
+
+ it('[Given] deno [Then] returns "deno add npm:<dep>"', () => {
+ expect(getJsInstallCommand('deno', '@composio/core')).toBe('deno add npm:@composio/core');
+ });
+ });
+
+ describe('getPythonInstallCommand', () => {
+ it('[Given] uv [Then] returns "uv pip install <dep>"', () => {
+ expect(getPythonInstallCommand('uv', 'composio')).toBe('uv pip install composio');
+ });
+
+ it('[Given] pip [Then] returns "pip install <dep>"', () => {
+ expect(getPythonInstallCommand('pip', 'composio')).toBe('pip install composio');
+ });
+ });
+});
diff --git a/ts/packages/cli/test/src/models/project-keys.test.ts b/ts/packages/cli/test/src/models/project-keys.test.ts
new file mode 100644
index 000000000..d7798187f
--- /dev/null
+++ b/ts/packages/cli/test/src/models/project-keys.test.ts
@@ -0,0 +1,181 @@
+import { describe, it, expect } from 'vitest';
+import { Effect, Option } from 'effect';
+import { ProjectKeys, projectKeysFromJSON, projectKeysToJSON } from 'src/models/project-keys';
+
+describe('ProjectKeys', () => {
+ describe('decode from JSON', () => {
+ it('decodes valid JSON with required fields only', () => {
+ const json = JSON.stringify({ org_id: 'abc', project_id: 'def' });
+
+ const result = Effect.runSync(projectKeysFromJSON(json));
+
+ expect(result.orgId).toBe('abc');
+ expect(result.projectId).toBe('def');
+ expect(Option.isNone(result.projectName)).toBe(true);
+ expect(Option.isNone(result.orgName)).toBe(true);
+ expect(Option.isNone(result.email)).toBe(true);
+ });
+
+ it('decodes valid JSON with all fields', () => {
+ const json = JSON.stringify({
+ org_id: 'abc',
+ project_id: 'def',
+ project_name: 'My Project',
+ org_name: 'My Org',
+ email: '[email protected]',
+ });
+
+ const result = Effect.runSync(projectKeysFromJSON(json));
+
+ expect(result.orgId).toBe('abc');
+ expect(result.projectId).toBe('def');
+ expect(Option.getOrUndefined(result.projectName)).toBe('My Project');
+ expect(Option.getOrUndefined(result.orgName)).toBe('My Org');
+ expect(Option.getOrUndefined(result.email)).toBe('[email protected]');
+ });
+
+ it('decodes null optional fields as Option.none()', () => {
+ const json = JSON.stringify({
+ org_id: 'abc',
+ project_id: 'def',
+ project_name: null,
+ org_name: null,
+ email: null,
+ });
+
+ const result = Effect.runSync(projectKeysFromJSON(json));
+
+ expect(result.orgId).toBe('abc');
+ expect(result.projectId).toBe('def');
+ expect(Option.isNone(result.projectName)).toBe(true);
+ expect(Option.isNone(result.orgName)).toBe(true);
+ expect(Option.isNone(result.email)).toBe(true);
+ });
+
+ it('ignores extra keys in decoded JSON', () => {
+ const json = JSON.stringify({
+ org_id: 'abc',
+ project_id: 'def',
+ future_field: 'unknown',
+ });
+
+ // Should not throw -- onExcessProperty: 'ignore' silently drops extra keys
+ const result = Effect.runSync(projectKeysFromJSON(json));
+ expect(result.orgId).toBe('abc');
+ expect(result.projectId).toBe('def');
+ });
+
+ it('fails on missing org_id', () => {
+ const json = JSON.stringify({ project_id: 'def' });
+ expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
+ });
+
+ it('fails on missing project_id', () => {
+ const json = JSON.stringify({ org_id: 'abc' });
+ expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
+ });
+
+ it('fails on non-string org_id', () => {
+ const json = JSON.stringify({ org_id: 123, project_id: 'def' });
+ expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
+ });
+
+ it('fails on non-string project_id', () => {
+ const json = JSON.stringify({ org_id: 'abc', project_id: true });
+ expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
+ });
+
+ it('fails on invalid JSON', () => {
+ expect(() => Effect.runSync(projectKeysFromJSON('not json'))).toThrow();
+ });
+
+ it('accepts empty strings for required fields', () => {
+ const json = JSON.stringify({ org_id: '', project_id: '' });
+ const result = Effect.runSync(projectKeysFromJSON(json));
+ expect(result.orgId).toBe('');
+ expect(result.projectId).toBe('');
+ });
+ });
+
+ describe('encode to JSON', () => {
+ it('encodes ProjectKeys with Some values', () => {
+ const keys: ProjectKeys = {
+ orgId: 'abc',
+ projectId: 'def',
+ projectName: Option.some('My Project'),
+ orgName: Option.some('My Org'),
+ email: Option.some('[email protected]'),
+ };
+
+ const json = Effect.runSync(projectKeysToJSON(keys));
+ const parsed = JSON.parse(json);
+
+ expect(parsed.org_id).toBe('abc');
+ expect(parsed.project_id).toBe('def');
+ expect(parsed.project_name).toBe('My Project');
+ expect(parsed.org_name).toBe('My Org');
+ expect(parsed.email).toBe('[email protected]');
+ });
+
+ it('encodes None optional fields as null', () => {
+ const keys: ProjectKeys = {
+ orgId: 'abc',
+ projectId: 'def',
+ projectName: Option.none(),
+ orgName: Option.none(),
+ email: Option.none(),
+ };
+
+ const json = Effect.runSync(projectKeysToJSON(keys));
+ const parsed = JSON.parse(json);
+
+ expect(parsed.org_id).toBe('abc');
+ expect(parsed.project_id).toBe('def');
+ expect(parsed.project_name).toBeNull();
+ expect(parsed.org_name).toBeNull();
+ expect(parsed.email).toBeNull();
+ });
+ });
+
+ describe('round-trip', () => {
+ it('encode then decode preserves Some values', () => {
+ const original: ProjectKeys = {
+ orgId: 'org-123',
+ projectId: 'proj-456',
+ projectName: Option.some('Test Project'),
+ orgName: Option.some('Test Org'),
+ email: Option.some('[email protected]'),
+ };
+
+ const json = Effect.runSync(projectKeysToJSON(original));
+ const decoded = Effect.runSync(projectKeysFromJSON(json));
+
+ expect(decoded.orgId).toBe(original.orgId);
+ expect(decoded.projectId).toBe(original.projectId);
+ expect(Option.getOrUndefined(decoded.projectName)).toBe(
+ Option.getOrUndefined(original.projectName)
+ );
+ expect(Option.getOrUndefined(decoded.orgName)).toBe(Option.getOrUndefined(original.orgName));
+ expect(Option.getOrUndefined(decoded.email)).toBe(Option.getOrUndefined(original.email));
+ });
+
+ it('encode then decode preserves None values', () => {
+ const original: ProjectKeys = {
+ orgId: 'org-123',
+ projectId: 'proj-456',
+ projectName: Option.none(),
+ orgName: Option.none(),
+ email: Option.none(),
+ };
+
+ const json = Effect.runSync(projectKeysToJSON(original));
+ const decoded = Effect.runSync(projectKeysFromJSON(json));
+
+ expect(decoded.orgId).toBe(original.orgId);
+ expect(decoded.projectId).toBe(original.projectId);
+ expect(Option.isNone(decoded.projectName)).toBe(true);
+ expect(Option.isNone(decoded.orgName)).toBe(true);
+ expect(Option.isNone(decoded.email)).toBe(true);
+ });
+ });
+});
diff --git a/ts/packages/cli/test/src/services/config.test.ts b/ts/packages/cli/test/src/services/config.test.ts
index b6365841a..271d2cd93 100644
--- a/ts/packages/cli/test/src/services/config.test.ts
+++ b/ts/packages/cli/test/src/services/config.test.ts
@@ -5,6 +5,7 @@ import { Config, ConfigProvider, Effect, Option, Data, LogLevel } from 'effect';
import { APP_CONFIG } from 'src/effects/app-config';
import { extendConfigProvider } from 'src/services/config';
import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
+import * as constants from 'src/constants';
describe('Config', () => {
describe('[When] using `ConfigProvider.fromMap`', () => {
@@ -23,9 +24,12 @@ describe('Config', () => {
actual,
Data.struct({
API_KEY: Option.none(),
+ ENVIRONMENT: Option.none(),
BASE_URL: 'https://backend.composio.dev',
CACHE_DIR: Option.none(),
LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
WEB_URL: 'https://platform.composio.dev',
})
);
@@ -47,9 +51,12 @@ describe('Config', () => {
actual,
Data.struct({
API_KEY: Option.none(),
+ ENVIRONMENT: Option.none(),
BASE_URL: 'https://backend.composio.dev',
CACHE_DIR: Option.none(),
LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
WEB_URL: 'https://platform.composio.dev',
})
);
@@ -72,10 +79,129 @@ describe('Config', () => {
actual,
Data.struct({
API_KEY: Option.some('api_key'),
+ ENVIRONMENT: Option.none(),
BASE_URL: 'https://test.localhost',
WEB_URL: 'https://test.localhost',
CACHE_DIR: Option.some('~/.composio'),
LOG_LEVEL: Option.some(LogLevel.Info),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
+ })
+ );
+ });
+
+ it('[When] COMPOSIO_ENVIRONMENT is "production"', () => {
+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'production']]) satisfies Map<string, string>;
+
+ const actual = Effect.runSync(
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
+ );
+
+ assertEquals(
+ actual,
+ Data.struct({
+ API_KEY: Option.none(),
+ ENVIRONMENT: Option.some('production'),
+ BASE_URL: constants.DEFAULT_BASE_URL,
+ WEB_URL: constants.DEFAULT_WEB_URL,
+ CACHE_DIR: Option.none(),
+ LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
+ })
+ );
+ });
+
+ it('[When] COMPOSIO_ENVIRONMENT is "staging"', () => {
+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'staging']]) satisfies Map<string, string>;
+
+ const actual = Effect.runSync(
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
+ );
+
+ assertEquals(
+ actual,
+ Data.struct({
+ API_KEY: Option.none(),
+ ENVIRONMENT: Option.some('staging'),
+ BASE_URL: constants.STAGING_BASE_URL,
+ WEB_URL: constants.STAGING_WEB_URL,
+ CACHE_DIR: Option.none(),
+ LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
+ })
+ );
+ });
+
+ it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_BASE_URL is set', () => {
+ const map = new Map([
+ ['COMPOSIO_ENVIRONMENT', 'staging'],
+ ['COMPOSIO_BASE_URL', 'https://custom-backend.localhost'],
+ ]) satisfies Map<string, string>;
+
+ const actual = Effect.runSync(
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
+ );
+
+ assertEquals(
+ actual,
+ Data.struct({
+ API_KEY: Option.none(),
+ ENVIRONMENT: Option.some('staging'),
+ BASE_URL: 'https://custom-backend.localhost',
+ WEB_URL: constants.STAGING_WEB_URL,
+ CACHE_DIR: Option.none(),
+ LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
+ })
+ );
+ });
+
+ it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_WEB_URL is set', () => {
+ const map = new Map([
+ ['COMPOSIO_ENVIRONMENT', 'staging'],
+ ['COMPOSIO_WEB_URL', 'https://custom-web.localhost'],
+ ]) satisfies Map<string, string>;
+
+ const actual = Effect.runSync(
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
+ );
+
+ assertEquals(
+ actual,
+ Data.struct({
+ API_KEY: Option.none(),
+ ENVIRONMENT: Option.some('staging'),
+ BASE_URL: constants.STAGING_BASE_URL,
+ WEB_URL: 'https://custom-web.localhost',
+ CACHE_DIR: Option.none(),
+ LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
+ })
+ );
+ });
+
+ it('[When] COMPOSIO_ENVIRONMENT is an unknown value', () => {
+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'unknown']]) satisfies Map<string, string>;
+
+ const actual = Effect.runSync(
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
+ );
+
+ assertEquals(
+ actual,
+ Data.struct({
+ API_KEY: Option.none(),
+ ENVIRONMENT: Option.some('unknown'),
+ BASE_URL: constants.DEFAULT_BASE_URL,
+ WEB_URL: constants.DEFAULT_WEB_URL,
+ CACHE_DIR: Option.none(),
+ LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
})
);
});
@@ -179,10 +305,13 @@ describe('Config', () => {
actual,
Data.struct({
API_KEY: Option.none(),
+ ENVIRONMENT: Option.none(),
BASE_URL: 'https://backend.composio.dev',
WEB_URL: 'https://platform.composio.dev',
CACHE_DIR: Option.none(),
LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
})
);
});
@@ -201,10 +330,13 @@ describe('Config', () => {
actual,
Data.struct({
API_KEY: Option.none(),
+ ENVIRONMENT: Option.none(),
BASE_URL: 'https://backend.composio.dev',
WEB_URL: 'https://platform.composio.dev',
CACHE_DIR: Option.none(),
LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
})
);
});
@@ -224,10 +356,59 @@ describe('Config', () => {
actual,
Data.struct({
API_KEY: Option.some('api_key'),
+ ENVIRONMENT: Option.none(),
BASE_URL: 'https://test.localhost',
WEB_URL: 'https://test.localhost',
CACHE_DIR: Option.some('~/.composio'),
LOG_LEVEL: Option.some(LogLevel.Info),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
+ })
+ );
+ });
+
+ it('[When] COMPOSIO_ENVIRONMENT is "staging"', () => {
+ vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
+
+ const actual = Effect.runSync(
+ withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
+ );
+
+ assertEquals(
+ actual,
+ Data.struct({
+ API_KEY: Option.none(),
+ ENVIRONMENT: Option.some('staging'),
+ BASE_URL: constants.STAGING_BASE_URL,
+ WEB_URL: constants.STAGING_WEB_URL,
+ CACHE_DIR: Option.none(),
+ LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
+ })
+ );
+ });
+
+ it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit URLs override', () => {
+ vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
+ vi.stubEnv('COMPOSIO_BASE_URL', 'https://custom.localhost');
+ vi.stubEnv('COMPOSIO_WEB_URL', 'https://custom-web.localhost');
+
+ const actual = Effect.runSync(
+ withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
+ );
+
+ assertEquals(
+ actual,
+ Data.struct({
+ API_KEY: Option.none(),
+ ENVIRONMENT: Option.some('staging'),
+ BASE_URL: 'https://custom.localhost',
+ WEB_URL: 'https://custom-web.localhost',
+ CACHE_DIR: Option.none(),
+ LOG_LEVEL: Option.none(),
+ ORG_ID: Option.none(),
+ PROJECT_ID: Option.none(),
})
);
});
diff --git a/ts/packages/cli/test/src/services/project-environment-detector.test.ts b/ts/packages/cli/test/src/services/project-environment-detector.test.ts
new file mode 100644
index 000000000..480765942
--- /dev/null
+++ b/ts/packages/cli/test/src/services/project-environment-detector.test.ts
@@ -0,0 +1,419 @@
+import path from 'node:path';
+import * as tempy from 'tempy';
+import { describe, expect, layer, assert } from '@effect/vitest';
+import { beforeAll, afterAll } from 'vitest';
+import { Effect, Layer, Either } from 'effect';
+import { FileSystem } from '@effect/platform';
+import { BunFileSystem } from '@effect/platform-bun';
+import {
+ ProjectEnvironmentDetector,
+ ProjectEnvironmentDetectorError,
+} from 'src/services/project-environment-detector';
+
+const testLayer = Layer.provideMerge(ProjectEnvironmentDetector.Default, BunFileSystem.layer);
+
+const writeFile = (fs: FileSystem.FileSystem, filePath: string, content: string) =>
+ Effect.gen(function* () {
+ const dir = path.dirname(filePath);
+ yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
+ yield* fs.writeFileString(filePath, content);
+ });
+
+describe('ProjectEnvironmentDetector', () => {
+ let savedUserAgent: string | undefined;
+
+ beforeAll(() => {
+ savedUserAgent = process.env.npm_config_user_agent;
+ delete process.env.npm_config_user_agent;
+ });
+
+ afterAll(() => {
+ if (savedUserAgent !== undefined) {
+ process.env.npm_config_user_agent = savedUserAgent;
+ } else {
+ delete process.env.npm_config_user_agent;
+ }
+ });
+
+ describe('detectProjectEnvironment', () => {
+ // -- TypeScript detection --
+
+ layer(testLayer)('TypeScript detection', it => {
+ it.scoped('[Given] package.json + tsconfig.json [Then] detects typescript + npm', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
+ yield* writeFile(fs, path.join(cwd, 'tsconfig.json'), '{}');
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('js');
+ expect(result.language).toBe('typescript');
+ expect(result.packageManager).toBe('npm');
+ expect(result.rootDir).toBe(cwd);
+ })
+ );
+
+ it.scoped(
+ '[Given] pnpm-lock.yaml + package.json with packageManager:pnpm@ [Then] detects typescript + pnpm',
+ () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(
+ fs,
+ path.join(cwd, 'package.json'),
+ JSON.stringify({
+ name: 'test-mono',
+ packageManager: '[email protected]',
+ devDependencies: { typescript: '^5.0.0' },
+ })
+ );
+ yield* writeFile(fs, path.join(cwd, 'pnpm-lock.yaml'), 'lockfileVersion: 9');
+ yield* writeFile(fs, path.join(cwd, 'tsconfig.json'), '{}');
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('js');
+ expect(result.language).toBe('typescript');
+ expect(result.packageManager).toBe('pnpm');
+ })
+ );
+
+ it.scoped('[Given] bun.lockb [Then] detects js + bun', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
+ yield* writeFile(fs, path.join(cwd, 'bun.lockb'), '');
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('js');
+ expect(result.packageManager).toBe('bun');
+ })
+ );
+
+ it.scoped('[Given] bun.lock (text format) [Then] detects bun', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
+ yield* writeFile(fs, path.join(cwd, 'bun.lock'), '{}');
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('js');
+ expect(result.packageManager).toBe('bun');
+ })
+ );
+
+ it.scoped('[Given] package.json with typescript dep [Then] detects typescript', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(
+ fs,
+ path.join(cwd, 'package.json'),
+ JSON.stringify({ name: 'test', devDependencies: { typescript: '^5.0.0' } })
+ );
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('js');
+ expect(result.language).toBe('typescript');
+ })
+ );
+
+ it.scoped('[Given] monorepo root with pnpm-workspace.yaml [Then] detects pnpm', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(
+ fs,
+ path.join(cwd, 'package.json'),
+ JSON.stringify({ name: 'monorepo' })
+ );
+ yield* writeFile(
+ fs,
+ path.join(cwd, 'pnpm-workspace.yaml'),
+ "packages:\n - 'packages/*'"
+ );
+ yield* writeFile(fs, path.join(cwd, 'tsconfig.json'), '{}');
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('js');
+ expect(result.packageManager).toBe('pnpm');
+ })
+ );
+ });
+
+ // -- Python detection --
+
+ layer(testLayer)('Python detection', it => {
+ it.scoped('[Given] pyproject.toml with [tool.uv] + uv.lock [Then] detects python + uv', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(
+ fs,
+ path.join(cwd, 'pyproject.toml'),
+ '[project]\nname = "test"\n\n[tool.uv]\ndev-dependencies = []'
+ );
+ yield* writeFile(fs, path.join(cwd, 'uv.lock'), 'version = 1');
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('python');
+ expect(result.language).toBe('python');
+ expect(result.packageManager).toBe('uv');
+ })
+ );
+
+ it.scoped('[Given] requirements.txt only [Then] detects python + pip', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(fs, path.join(cwd, 'requirements.txt'), 'composio');
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('python');
+ expect(result.language).toBe('python');
+ expect(result.packageManager).toBe('pip');
+ })
+ );
+
+ it.scoped('[Given] setup.py only [Then] detects python + pip', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(
+ fs,
+ path.join(cwd, 'setup.py'),
+ 'from setuptools import setup\nsetup(name="test")'
+ );
+
+ const result = yield* detector.detectProjectEnvironment(cwd);
+
+ expect(result.kind).toBe('python');
+ expect(result.packageManager).toBe('pip');
+ })
+ );
+ });
+
+ // -- Ambiguity --
+
+ layer(testLayer)('Ambiguity handling', it => {
+ it.scoped(
+ '[Given] both package.json + pyproject.toml at CWD [Then] fails with ambiguity error',
+ () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
+ yield* writeFile(fs, path.join(cwd, 'pyproject.toml'), '[project]\nname = "test"');
+ yield* writeFile(fs, path.join(cwd, 'requirements.txt'), 'composio');
+
+ const result = yield* detector.detectProjectEnvironment(cwd).pipe(Effect.either);
+
+ assert(Either.isLeft(result));
+ expect(result.left).toBeInstanceOf(ProjectEnvironmentDetectorError);
+ expect(result.left.message).toContain('both');
+ })
+ );
+ });
+
+ // -- Edge cases --
+
+ layer(testLayer)('Edge cases', it => {
+ it.scoped('[Given] empty directory [Then] fails with no-detection error', () =>
+ Effect.gen(function* () {
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ const result = yield* detector.detectProjectEnvironment(cwd).pipe(Effect.either);
+
+ assert(Either.isLeft(result));
+ expect(result.left.message).toContain('No recognizable');
+ })
+ );
+
+ it.scoped('[Given] indicators at parent directory [Then] detects from parent', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const parentDir = tempy.temporaryDirectory();
+ const childDir = path.join(parentDir, 'subdir');
+ yield* fs.makeDirectory(childDir, { recursive: true });
+
+ yield* writeFile(
+ fs,
+ path.join(parentDir, 'package.json'),
+ JSON.stringify({ name: 'parent', packageManager: '[email protected]' })
+ );
+ yield* writeFile(fs, path.join(parentDir, 'pnpm-lock.yaml'), '');
+ yield* writeFile(fs, path.join(parentDir, 'tsconfig.json'), '{}');
+
+ const result = yield* detector.detectProjectEnvironment(childDir);
+
+ expect(result.kind).toBe('js');
+ expect(result.packageManager).toBe('pnpm');
+ expect(result.rootDir).toBe(parentDir);
+ })
+ );
+ });
+ });
+
+ // -- detectJsPackageManager --
+
+ describe('detectJsPackageManager', () => {
+ layer(testLayer)('JS package manager detection', it => {
+ it.scoped('[Given] packageManager field in package.json [Then] uses that', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(
+ fs,
+ path.join(cwd, 'package.json'),
+ JSON.stringify({ name: 'test', packageManager: '[email protected]' })
+ );
+
+ const result = yield* detector.detectJsPackageManager(cwd);
+ expect(result).toBe('yarn');
+ })
+ );
+
+ it.scoped('[Given] lock file present [Then] detects from lock file', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
+ yield* writeFile(fs, path.join(cwd, 'yarn.lock'), '');
+
+ const result = yield* detector.detectJsPackageManager(cwd);
+ expect(result).toBe('yarn');
+ })
+ );
+
+ it.scoped('[Given] no lock file, no packageManager field [Then] defaults to npm', () =>
+ Effect.gen(function* () {
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ const result = yield* detector.detectJsPackageManager(cwd);
+ expect(result).toBe('npm');
+ })
+ );
+
+ it.scoped(
+ '[Given] no lock file, no packageManager field, but npm_config_user_agent=pnpm [Then] detects pnpm',
+ () =>
+ Effect.gen(function* () {
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ process.env.npm_config_user_agent = 'pnpm/9.15.0 npm/? node/v20.11.0';
+ try {
+ const result = yield* detector.detectJsPackageManager(cwd);
+ expect(result).toBe('pnpm');
+ } finally {
+ delete process.env.npm_config_user_agent;
+ }
+ })
+ );
+
+ it.scoped(
+ '[Given] no lock file, no packageManager field, but npm_config_user_agent=bun [Then] detects bun',
+ () =>
+ Effect.gen(function* () {
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ process.env.npm_config_user_agent = 'bun/1.1.0';
+ try {
+ const result = yield* detector.detectJsPackageManager(cwd);
+ expect(result).toBe('bun');
+ } finally {
+ delete process.env.npm_config_user_agent;
+ }
+ })
+ );
+ });
+ });
+
+ // -- detectPythonPackageManager --
+
+ describe('detectPythonPackageManager', () => {
+ layer(testLayer)('Python package manager detection', it => {
+ it.scoped('[Given] uv.lock present [Then] detects uv', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(fs, path.join(cwd, 'uv.lock'), 'version = 1');
+
+ const result = yield* detector.detectPythonPackageManager(cwd);
+ expect(result).toBe('uv');
+ })
+ );
+
+ it.scoped('[Given] [tool.uv] in pyproject.toml [Then] detects uv', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(
+ fs,
+ path.join(cwd, 'pyproject.toml'),
+ '[project]\nname = "test"\n\n[tool.uv]\ndev-dependencies = []'
+ );
+
+ const result = yield* detector.detectPythonPackageManager(cwd);
+ expect(result).toBe('uv');
+ })
+ );
+
+ it.scoped('[Given] no uv indicators [Then] defaults to pip', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const detector = yield* ProjectEnvironmentDetector;
+ const cwd = tempy.temporaryDirectory();
+
+ yield* writeFile(fs, path.join(cwd, 'requirements.txt'), 'composio');
+
+ const result = yield* detector.detectPythonPackageManager(cwd);
+ expect(result).toBe('pip');
+ })
+ );
+ });
+ });
+});
diff --git a/ts/packages/cli/test/src/services/user-context.test.ts b/ts/packages/cli/test/src/services/user-context.test.ts
index ef53b826b..1cc55a67f 100644
--- a/ts/packages/cli/test/src/services/user-context.test.ts
+++ b/ts/packages/cli/test/src/services/user-context.test.ts
@@ -33,6 +33,8 @@ describe('ComposioUserContext', () => {
apiKey: Option.none(),
baseURL: 'https://backend.composio.dev',
webURL: 'https://platform.composio.dev',
+ orgId: Option.none(),
+ projectId: Option.none(),
});
assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
assertEquals(ctx.isLoggedIn(), false);
@@ -61,6 +63,8 @@ describe('ComposioUserContext', () => {
apiKey: Option.some('api_key'),
baseURL: 'https://test.composio.localhost',
webURL: 'https://platform.composio.dev',
+ orgId: Option.none(),
+ projectId: Option.none(),
});
assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
assertEquals(ctx.isLoggedIn(), true);
@@ -87,6 +91,8 @@ describe('ComposioUserContext', () => {
apiKey: Option.some('api_key'),
baseURL: Option.some('https://test.composio.localhost'),
webURL: Option.some('https://platform.composio.dev'),
+ orgId: Option.none(),
+ projectId: Option.none(),
});
const userDataAsJson = yield* userDataToJSON(expectedUserData);
@@ -124,6 +130,8 @@ describe('ComposioUserContext', () => {
apiKey: Option.some('api_key'),
baseURL: Option.none(),
webURL: Option.some('https://platform.composio.dev'),
+ orgId: Option.none(),
+ projectId: Option.none(),
});
const userDataAsJson = yield* userDataToJSON(expectedUserData);
@@ -145,5 +153,143 @@ describe('ComposioUserContext', () => {
}).pipe(Effect.provide(ComposioUserContextTest));
});
});
+
+ describe('[When] the file is empty', () => {
+ it('[Then] it falls back to defaults and overwrites the file', () => {
+ const cwd = tempy.temporaryDirectory();
+ const map = new Map([]) satisfies Map<string, string>;
+
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
+ const ComposioUserContextTest = Layer.provideMerge(
+ ComposioUserContextLive,
+ Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ );
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
+ // Write an empty file
+ yield* fs.writeFileString(path.join(cwd, '.composio', 'user_data.json'), '');
+
+ // Should NOT throw — should fall back to defaults
+ const ctx = yield* ComposioUserContext;
+
+ const expectedUserData = UserDataWithDefaults.make({
+ apiKey: Option.none(),
+ baseURL: 'https://backend.composio.dev',
+ webURL: 'https://platform.composio.dev',
+ orgId: Option.none(),
+ projectId: Option.none(),
+ });
+ assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
+ assertEquals(ctx.isLoggedIn(), false);
+
+ // The corrupted file should have been overwritten with valid defaults
+ const contents = yield* fs.readFileString(
+ path.join(cwd, '.composio', 'user_data.json'),
+ 'utf8'
+ );
+ const parsed = JSON.parse(contents);
+ assertEquals(parsed.api_key, null);
+ }).pipe(Effect.provide(ComposioUserContextTest));
+ });
+ });
+
+ describe('[When] the file contains invalid JSON', () => {
+ it('[Then] it falls back to defaults and overwrites the file', () => {
+ const cwd = tempy.temporaryDirectory();
+ const map = new Map([]) satisfies Map<string, string>;
+
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
+ const ComposioUserContextTest = Layer.provideMerge(
+ ComposioUserContextLive,
+ Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ );
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
+ // Write corrupted JSON
+ yield* fs.writeFileString(
+ path.join(cwd, '.composio', 'user_data.json'),
+ '{not valid json!!!'
+ );
+
+ // Should NOT throw — should fall back to defaults
+ const ctx = yield* ComposioUserContext;
+
+ const expectedUserData = UserDataWithDefaults.make({
+ apiKey: Option.none(),
+ baseURL: 'https://backend.composio.dev',
+ webURL: 'https://platform.composio.dev',
+ orgId: Option.none(),
+ projectId: Option.none(),
+ });
+ assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
+ assertEquals(ctx.isLoggedIn(), false);
+ }).pipe(Effect.provide(ComposioUserContextTest));
+ });
+ });
+
+ describe('[When] the file contains valid JSON but wrong schema', () => {
+ it('[Then] it falls back to defaults and overwrites the file', () => {
+ const cwd = tempy.temporaryDirectory();
+ const map = new Map([]) satisfies Map<string, string>;
+
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
+ const ComposioUserContextTest = Layer.provideMerge(
+ ComposioUserContextLive,
+ Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ );
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
+ // Write valid JSON but with wrong schema (api_key should be string|null, not number)
+ yield* fs.writeFileString(
+ path.join(cwd, '.composio', 'user_data.json'),
+ JSON.stringify({ api_key: 12345, unknown_field: true })
+ );
+
+ // Should NOT throw — should fall back to defaults
+ const ctx = yield* ComposioUserContext;
+
+ const expectedUserData = UserDataWithDefaults.make({
+ apiKey: Option.none(),
+ baseURL: 'https://backend.composio.dev',
+ webURL: 'https://platform.composio.dev',
+ orgId: Option.none(),
+ projectId: Option.none(),
+ });
+ assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
+ assertEquals(ctx.isLoggedIn(), false);
+ }).pipe(Effect.provide(ComposioUserContextTest));
+ });
+ });
+
+ describe('[When] the file is corrupted but env API_KEY is set', () => {
+ it('[Then] it falls back to defaults but preserves env API_KEY', () => {
+ const cwd = tempy.temporaryDirectory();
+ const map = new Map([['COMPOSIO_API_KEY', 'env_api_key']]) satisfies Map<string, string>;
+
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
+ const ComposioUserContextTest = Layer.provideMerge(
+ ComposioUserContextLive,
+ Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ );
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
+ yield* fs.writeFileString(path.join(cwd, '.composio', 'user_data.json'), '');
+
+ const ctx = yield* ComposioUserContext;
+
+ // Despite corrupted file, env API_KEY should still work
+ assertEquals(ctx.isLoggedIn(), true);
+ assertEquals(Option.getOrUndefined(ctx.data.apiKey), 'env_api_key');
+ }).pipe(Effect.provide(ComposioUserContextTest));
+ });
+ });
});
});