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)
Co-authored-by: jkomyno <12381818+jkomyno@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
Alberto Schiabel committed
Feb 26, 2026 at 03:26 UTC
105c20344901373013025eb340362ca2a4b1c42f
45 files changed
+4981
-197
plans/feat-init-project-environment-detection.md
new
+619
@@ -0,0 +1,619 @@
1
+# feat: Add project environment detection and dependency installation to `composio init`
2
+
3
+## Overview
4
+
5
+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.
6
+
7
+## Problem Statement / Motivation
8
+
9
+Currently, `composio init` writes config files but does **not**:
10
+- Detect what kind of project the user is working in
11
+- Install Composio SDK packages (`@composio/core` for TS, `composio` for Python)
12
+- Install framework-specific provider packages (`@composio/mastra`, `@composio/openai`, etc.)
13
+
14
+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.
15
+
16
+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.
17
+
18
+## Proposed Solution
19
+
20
+### Architecture
21
+
22
+```mermaid
23
+graph TD
24
+ A[composio init] --> B[Project Selection]
25
+ B --> C[Init Wizard: usage mode + framework + skills]
26
+ C --> D[ProjectEnvironmentDetector.detectProjectEnvironment]
27
+ D --> E{Detected?}
28
+ E -->|Yes| F[Show detection + confirm]
29
+ E -->|Ambiguous| G[Prompt user to choose language]
30
+ E -->|No indicators| H[Prompt user to choose language + PM]
31
+ F --> I[resolveCoreDependencyState]
32
+ G --> I
33
+ H --> I
34
+ I --> J{Already installed?}
35
+ J -->|Yes, not --force| K[Skip install, log info]
36
+ J -->|No or --force| L[Confirm install command]
37
+ L --> M[CommandRunner.run with spinner]
38
+ M --> N[Write config files]
39
+ N --> O[Optionally install skills]
40
+```
41
+
42
+### Key Components
43
+
44
+1. **`ProjectEnvironmentDetector`** (new service) — replaces `EnvLangDetector` + `JsPackageManagerDetector` with a single service that:
45
+ - Walks up the directory tree looking for project indicators
46
+ - Produces a `ProjectEnvironment` discriminated union (`js` | `python`)
47
+ - Includes `language`, `packageManager`, `rootDir`, and `evidence[]`
48
+ - Handles ambiguity (both JS and Python indicators) with a tagged error
49
+ - Supports Deno (`deno.json`, `deno.lock`) as a JS package manager
50
+
51
+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.
52
+
53
+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.
54
+
55
+4. **Updated `init.cmd.ts`** — integrates detection + installation into the wizard flow after project selection.
56
+
57
+## Technical Approach
58
+
59
+### Phase 1: New Services and Effects
60
+
61
+#### 1.1 Add `ProjectEnvironmentDetector` service
62
+
63
+**File:** `ts/packages/cli/src/services/project-environment-detector.ts`
64
+
65
+Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/project-environment-detector.ts`
66
+
67
+The reference implementation is 587 lines and provides:
68
+
69
+```typescript
70
+export type ProjectEnvironment =
71
+ | { kind: 'js'; language: JsLanguage; packageManager: JsPackageManager; rootDir: string; evidence: string[] }
72
+ | { kind: 'python'; language: 'python'; packageManager: PythonPackageManager; rootDir: string; evidence: string[] };
73
+
74
+export type JsLanguage = 'typescript' | 'javascript';
75
+export type JsPackageManager = 'pnpm' | 'bun' | 'yarn' | 'npm' | 'deno';
76
+export type PythonPackageManager = 'uv' | 'pip';
77
+```
78
+
79
+Key detection strategies:
80
+- **Strong JS indicators:** `package.json`, `tsconfig.json`, `pnpm-workspace.yaml`, lock files — each gets a high score
81
+- **Strong Python indicators:** `pyproject.toml`, `setup.py`, `requirements.txt`, `uv.lock`, `poetry.lock`
82
+- **Weak indicators:** file extension counts (`.ts`, `.py`), subdirectory scans
83
+- **Package manager from `package.json`:** reads `packageManager` field (e.g., `"pnpm@9.0.0"`)
84
+- **Python package manager:** checks for `uv.lock` or `[tool.uv]` in `pyproject.toml`
85
+- **Ancestor walking:** walks up from CWD to filesystem root, checking each directory
86
+
87
+**Ambiguity handling:** If both JS and Python strong indicators exist at CWD depth 0, fails with `ProjectEnvironmentDetectorError`. At deeper levels, skips and continues searching.
88
+
89
+**Service pattern:** Uses `Effect.Service` class with `effect:` body and `dependencies: [BunFileSystem.layer]`.
90
+
91
+#### 1.2 Add `CommandRunner` service
92
+
93
+**File:** `ts/packages/cli/src/services/command-runner.ts`
94
+
95
+Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/command-runner.ts`
96
+
97
+```typescript
98
+import { Command } from '@effect/platform';
99
+import { Effect } from 'effect';
100
+
101
+export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {
102
+ sync: () => ({
103
+ run: (command: Command.Command) => Command.exitCode(command),
104
+ }),
105
+ dependencies: [],
106
+}) {}
107
+```
108
+
109
+This is intentionally thin — the real value is in testability. In tests, we provide `Layer.succeed(CommandRunner, new CommandRunner({ run: () => Effect.succeed(ExitCode(0)) }))`.
110
+
111
+#### 1.3 Add `core-dependency.ts` effect
112
+
113
+**File:** `ts/packages/cli/src/effects/core-dependency.ts`
114
+
115
+Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/effects/core-dependency.ts`
116
+
117
+Key exports:
118
+- `CoreDependencyPlan` — discriminated union with `installCommand`, `dependency`, `packageManager`, `rootDir`
119
+- `detectCoreDependencyPlan(cwd)` — maps `ProjectEnvironment` → `CoreDependencyPlan`
120
+- `detectCoreDependencyVersion(plan)` — checks if `@composio/core` or `composio` is already installed
121
+- `resolveCoreDependencyState(cwd)` — combines plan + version check
122
+- `getJsInstallCommand(pm, dependency)` — maps package manager to install command
123
+- `getPythonInstallCommand(pm, dependency)` — same for Python
124
+
125
+Install command mapping:
126
+
127
+| PM | Command |
128
+|---|---|
129
+| pnpm | `pnpm add @composio/core` |
130
+| bun | `bun add @composio/core` |
131
+| yarn | `yarn add @composio/core` |
132
+| npm | `npm install -S @composio/core` |
133
+| deno | `deno add npm:@composio/core` |
134
+| uv | `uv pip install composio` |
135
+| pip | `pip install composio` |
136
+
137
+### Phase 2: Update `composio init` Command
138
+
139
+#### 2.1 Add new CLI flags
140
+
141
+```typescript
142
+const dryRunOpt = Options.boolean('dry-run').pipe(
143
+ Options.withDefault(false),
144
+ Options.withDescription('Print install command without executing it')
145
+);
146
+
147
+const forceOpt = Options.boolean('force').pipe(
148
+ Options.withDefault(false),
149
+ Options.withDescription('Reinstall even if dependency appears installed')
150
+);
151
+
152
+const yesOpt = Options.boolean('yes').pipe(
153
+ Options.withAlias('y'),
154
+ Options.withDefault(false),
155
+ Options.withDescription('Skip confirmation prompts')
156
+);
157
+```
158
+
159
+#### 2.2 Extend `InitConfigBuilder` and `InitConfig`
160
+
161
+Add new builder steps and fields:
162
+
163
+```typescript
164
+interface InitConfig {
165
+ readonly usageMode: UsageMode;
166
+ readonly framework: NativeFramework | undefined;
167
+ readonly installSkills: boolean;
168
+ readonly detectedEnv: ProjectEnvironment; // NEW
169
+ readonly installPlan: CoreDependencyPlan; // NEW
170
+}
171
+```
172
+
173
+Add `withDetectedEnv` and `withInstallPlan` methods to `InitConfigBuilder`, and update the `build()` type constraint.
174
+
175
+#### 2.3 Updated wizard flow
176
+
177
+After the existing wizard steps (usage mode → framework → skills), add:
178
+
179
+```typescript
180
+// Step 4: Detect project environment
181
+const envDetector = yield* ProjectEnvironmentDetector;
182
+const detectedEnv = yield* envDetector
183
+ .detectProjectEnvironment(proc.cwd)
184
+ .pipe(
185
+ Effect.catchTag('services/ProjectEnvironmentDetectorError', e =>
186
+ Effect.gen(function* () {
187
+ yield* ui.log.warn(e.message);
188
+ // Fallback: ask user to choose
189
+ const lang = yield* ui.select('What language is your project?', [
190
+ { value: 'typescript', label: 'TypeScript' },
191
+ { value: 'python', label: 'Python' },
192
+ ]);
193
+ // ... prompt for package manager too
194
+ })
195
+ )
196
+ );
197
+
198
+yield* ui.log.step(`Detected: ${detectedEnv.language} (${detectedEnv.packageManager})`);
199
+
200
+// Step 5: Check if already installed + determine install plan
201
+const { plan, installedVersion } = yield* resolveCoreDependencyState(proc.cwd);
202
+
203
+if (installedVersion && !forceOpt) {
204
+ yield* ui.log.info(`Found ${plan.dependency}: ${installedVersion.version}`);
205
+ yield* ui.log.success('Dependency already installed.');
206
+} else {
207
+ // Step 6: Confirm and install
208
+ if (dryRunOpt) {
209
+ yield* ui.note(plan.installCommand, 'Install Command');
210
+ } else {
211
+ const shouldInstall = yesOpt || (yield* ui.confirm(`Run: ${plan.installCommand}?`));
212
+ if (shouldInstall) {
213
+ yield* ui.withSpinner(`Installing ${plan.dependency}...`, installEffect, {
214
+ successMessage: `Installed ${plan.dependency}`,
215
+ });
216
+ }
217
+ }
218
+}
219
+```
220
+
221
+#### 2.4 Framework provider installation
222
+
223
+When a framework is selected (not "skip"), also install the provider package:
224
+
225
+```typescript
226
+const frameworkPackage = getFrameworkPackage(config.framework, detectedEnv);
227
+// e.g., '@composio/mastra' for TS, 'composio[mastra]' for Python
228
+```
229
+
230
+| Framework | TS Package | Python Package |
231
+|---|---|---|
232
+| ai-sdk | `@composio/vercel` | `composio[vercel]` |
233
+| mastra | `@composio/mastra` | `composio[mastra]` |
234
+| openai-agents | `@composio/openai` | `composio[openai]` |
235
+| claude-agent-sdk | `@composio/anthropic` | `composio[anthropic]` |
236
+
237
+### Phase 3: Wire Services in Layer Composition
238
+
239
+#### 3.1 Update `bin.ts`
240
+
241
+Add to the layer composition:
242
+
243
+```typescript
244
+import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
245
+import { CommandRunner } from 'src/services/command-runner';
246
+
247
+const layers = Layer.mergeAll(
248
+ // ... existing layers ...
249
+ ProjectEnvironmentDetector.Default, // NEW
250
+ CommandRunner.Default, // NEW
251
+);
252
+```
253
+
254
+#### 3.2 Deprecate `EnvLangDetector` and `JsPackageManagerDetector`
255
+
256
+The new `ProjectEnvironmentDetector` subsumes both. However, `EnvLangDetector` is still used by `generate.cmd.ts`. Options:
257
+
258
+- **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.
259
+- **Option B:** Replace both immediately and update `generate.cmd.ts` to use the new service.
260
+
261
+Go with **Option A** to keep this PR focused.
262
+
263
+### Phase 4: Testing (TDD)
264
+
265
+#### 4.1 Unit tests for `ProjectEnvironmentDetector`
266
+
267
+**File:** `ts/packages/cli/test/src/services/project-environment-detector.test.ts`
268
+
269
+Uses `tempy.temporaryDirectory()` to create isolated temp dirs with specific file layouts. Tests use `BunFileSystem.layer` (real filesystem).
270
+
271
+```
272
+describe('ProjectEnvironmentDetector', () => {
273
+ describe('detectProjectEnvironment', () => {
274
+ // TypeScript detection
275
+ it('[Given] package.json + tsconfig.json [Then] detects typescript + npm')
276
+ it('[Given] pnpm-lock.yaml + package.json with packageManager:pnpm@ [Then] detects typescript + pnpm')
277
+ it('[Given] bun.lockb [Then] detects javascript + bun')
278
+ it('[Given] deno.json [Then] detects typescript + deno')
279
+ it('[Given] package.json with typescript dep [Then] detects typescript')
280
+
281
+ // Python detection
282
+ it('[Given] pyproject.toml with [tool.uv] [Then] detects python + uv')
283
+ it('[Given] requirements.txt only [Then] detects python + pip')
284
+ it('[Given] uv.lock [Then] detects python + uv')
285
+ it('[Given] setup.py only [Then] detects python + pip')
286
+
287
+ // Ambiguity
288
+ it('[Given] both package.json + pyproject.toml at CWD [Then] fails with ambiguity error')
289
+ it('[Given] both indicators but only at parent level [Then] skips and continues')
290
+
291
+ // Ancestor walking
292
+ it('[Given] indicators at parent directory [Then] detects from parent')
293
+ it('[Given] no indicators anywhere [Then] fails with no-detection error')
294
+
295
+ // File extension fallback
296
+ it('[Given] only .ts files, no config files [Then] detects typescript via weak signals')
297
+ it('[Given] only .py files, no config files [Then] detects python via weak signals')
298
+
299
+ // Edge cases
300
+ it('[Given] empty directory [Then] fails with no-detection error')
301
+ it('[Given] monorepo root with pnpm-workspace.yaml [Then] detects pnpm')
302
+ })
303
+
304
+ describe('detectJsPackageManager', () => {
305
+ it('[Given] packageManager field in package.json [Then] uses that')
306
+ it('[Given] lock file present [Then] detects from lock file')
307
+ it('[Given] no lock file, no packageManager field [Then] defaults to npm')
308
+ })
309
+
310
+ describe('detectPythonPackageManager', () => {
311
+ it('[Given] uv.lock present [Then] detects uv')
312
+ it('[Given] [tool.uv] in pyproject.toml [Then] detects uv')
313
+ it('[Given] no uv indicators [Then] defaults to pip')
314
+ })
315
+})
316
+```
317
+
318
+#### 4.2 Unit tests for `core-dependency.ts`
319
+
320
+**File:** `ts/packages/cli/test/src/effects/core-dependency.test.ts`
321
+
322
+```
323
+describe('core-dependency', () => {
324
+ describe('getJsInstallCommand', () => {
325
+ it('[Given] pnpm [Then] returns "pnpm add <dep>"')
326
+ it('[Given] npm [Then] returns "npm install -S <dep>"')
327
+ it('[Given] yarn [Then] returns "yarn add <dep>"')
328
+ it('[Given] bun [Then] returns "bun add <dep>"')
329
+ it('[Given] deno [Then] returns "deno add npm:<dep>"')
330
+ })
331
+
332
+ describe('getPythonInstallCommand', () => {
333
+ it('[Given] uv [Then] returns "uv pip install <dep>"')
334
+ it('[Given] pip [Then] returns "pip install <dep>"')
335
+ })
336
+
337
+ describe('detectCoreDependencyPlan', () => {
338
+ it('[Given] TS project [Then] plans @composio/core install')
339
+ it('[Given] Python project [Then] plans composio install')
340
+ })
341
+
342
+ describe('detectCoreDependencyVersion', () => {
343
+ it('[Given] @composio/core in node_modules [Then] returns version')
344
+ it('[Given] @composio/core in pnpm virtual store [Then] returns version')
345
+ it('[Given] not installed [Then] returns null')
346
+ })
347
+})
348
+```
349
+
350
+#### 4.3 Command tests for `composio init`
351
+
352
+**File:** `ts/packages/cli/test/src/commands/init.cmd.test.ts`
353
+
354
+Uses `TestLive` with fixtures and mocked services.
355
+
356
+```
357
+describe('CLI: composio init', () => {
358
+ // Agent-native path (--org-id + --project-id)
359
+ describe('[Given] --org-id + --project-id flags', () => {
360
+ layer(TestLive({ fixture: 'typescript-project' }))(it => {
361
+ it.scoped('[Then] detects TS project and shows install plan', () => ...)
362
+ })
363
+
364
+ layer(TestLive({ fixture: 'python-project' }))(it => {
365
+ it.scoped('[Then] detects Python project and shows install plan', () => ...)
366
+ })
367
+ })
368
+
369
+ // Dry-run mode
370
+ describe('[Given] --dry-run flag', () => {
371
+ layer(TestLive({ fixture: 'typescript-project' }))(it => {
372
+ it.scoped('[Then] prints install command without executing', () => ...)
373
+ })
374
+ })
375
+
376
+ // Already installed
377
+ describe('[Given] @composio/core already in node_modules', () => {
378
+ layer(TestLive({ fixture: 'typescript-project-with-composio-core' }))(it => {
379
+ it.scoped('[Then] skips install', () => ...)
380
+ })
381
+ })
382
+
383
+ // --force reinstall
384
+ describe('[Given] --force flag with dependency installed', () => {
385
+ layer(TestLive({ fixture: 'typescript-project-with-composio-core', commandRunner: successRunner }))(it => {
386
+ it.scoped('[Then] reinstalls', () => ...)
387
+ })
388
+ })
389
+
390
+ // Install failure
391
+ describe('[Given] install command fails', () => {
392
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: failRunner }))(it => {
393
+ it.scoped('[Then] shows error message', () => ...)
394
+ })
395
+ })
396
+})
397
+```
398
+
399
+#### 4.4 New test fixtures needed
400
+
401
+```
402
+test/__fixtures__/
403
+ typescript-project/ # EXISTING: package.json + tsconfig.json
404
+ python-project/ # EXISTING: requirements.txt + setup.py
405
+ typescript-project-with-composio-core/ # EXISTING
406
+ python-project-with-composio-core/ # EXISTING
407
+ typescript-pnpm-monorepo/ # NEW: pnpm-workspace.yaml + package.json with packageManager:pnpm@
408
+ typescript-bun-project/ # NEW: bun.lockb + package.json
409
+ python-uv-project/ # NEW: pyproject.toml with [tool.uv] + uv.lock
410
+ ambiguous-project/ # NEW: package.json + pyproject.toml (for error case)
411
+```
412
+
413
+#### 4.5 Test layer updates
414
+
415
+Update `TestLive` interface to accept optional overrides:
416
+
417
+```typescript
418
+interface TestLiveInput {
419
+ // ... existing fields ...
420
+ commandRunner?: CommandRunner; // NEW: mock for CommandRunner
421
+ terminalUI?: TerminalUI; // NEW: override TerminalUI for custom prompt behavior
422
+}
423
+```
424
+
425
+Add `ProjectEnvironmentDetector.Default` and `CommandRunner.Default` (or mock) to the test layer composition.
426
+
427
+### Phase 5: E2E Tests
428
+
429
+#### 5.1 `composio init` deterministic E2E test
430
+
431
+**Directory:** `ts/e2e-tests/cli/init/`
432
+
433
+**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.
434
+
435
+**Deterministic test strategy:** Use `--org-id` + `--project-id` flags to bypass API calls. Pre-create a fixture project directory inside the Docker container.
436
+
437
+```typescript
438
+// ts/e2e-tests/cli/init/e2e.test.ts
439
+e2e(import.meta.url, {
440
+ versions: { cli: ['current'] },
441
+ defineTests: ({ runCmd }) => {
442
+ describe('composio init --dry-run', () => {
443
+ it('detects TypeScript project', async () => {
444
+ // Create a minimal TS project in the container
445
+ await runCmd('mkdir -p /tmp/test-ts && echo \'{"name":"test"}\' > /tmp/test-ts/package.json');
446
+ await runCmd('echo \'{}\' > /tmp/test-ts/tsconfig.json');
447
+
448
+ const result = await runCmd(
449
+ 'cd /tmp/test-ts && composio init --org-id test-org --project-id test-proj --dry-run'
450
+ );
451
+
452
+ expect(result.exitCode).toBe(0);
453
+ // In non-interactive (piped) mode, output() writes JSON to stdout
454
+ expect(result.stdout).toContain('typescript');
455
+ });
456
+ });
457
+
458
+ describe('composio init on Python project', () => {
459
+ it('detects Python project', async () => {
460
+ await runCmd('mkdir -p /tmp/test-py && echo "composio" > /tmp/test-py/requirements.txt');
461
+
462
+ const result = await runCmd(
463
+ 'cd /tmp/test-py && composio init --org-id test-org --project-id test-proj --dry-run'
464
+ );
465
+
466
+ expect(result.exitCode).toBe(0);
467
+ expect(result.stdout).toContain('python');
468
+ });
469
+ });
470
+ },
471
+});
472
+```
473
+
474
+**Note:** The init command's interactive prompts are automatically skipped in piped mode (TerminalUI returns defaults). The `--dry-run` flag prevents actual package installation.
475
+
476
+## Alternative Approaches Considered
477
+
478
+### A. Extend existing `EnvLangDetector` + `JsPackageManagerDetector`
479
+
480
+**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.
481
+
482
+### B. Separate `composio install` command
483
+
484
+**Reference:** The `composio2` branch already has a standalone `install.cmd.ts`.
485
+
486
+**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`.
487
+
488
+### C. Use `Effect.Service` class vs `Context.Tag` for new services
489
+
490
+**Decision:** Use `Effect.Service` class pattern (newer pattern) for consistency with `EnvLangDetector`, `JsPackageManagerDetector`, `NodeOs`, `NodeProcess`.
491
+
492
+## Acceptance Criteria
493
+
494
+### Functional Requirements
495
+
496
+- [ ] `composio init` detects TypeScript projects (from `tsconfig.json`, `package.json`, lock files)
497
+- [ ] `composio init` detects Python projects (from `pyproject.toml`, `setup.py`, `requirements.txt`)
498
+- [ ] `composio init` detects the correct package manager (pnpm, npm, yarn, bun, deno, uv, pip)
499
+- [ ] `composio init` walks up the directory tree to find project root (monorepo support)
500
+- [ ] `composio init` shows the detected environment and asks for confirmation before installing
501
+- [ ] `composio init` runs the correct install command (`pnpm add`, `npm install`, `uv pip install`, etc.)
502
+- [ ] `composio init --dry-run` prints the install command without executing
503
+- [ ] `composio init --force` reinstalls even if dependency is already present
504
+- [ ] `composio init --yes` skips confirmation prompts
505
+- [ ] `composio init` shows appropriate error messages when detection fails (ambiguous or empty project)
506
+- [ ] `composio init` gracefully handles install command failures
507
+- [ ] `composio init` skips installation when dependency is already installed (without `--force`)
508
+- [ ] `composio init` emits structured JSON to stdout when piped (agent-native)
509
+- [ ] `composio init` writes `detectedEnv` info to `.composio/config.json`
510
+
511
+### Non-Functional Requirements
512
+
513
+- [ ] `pnpm typecheck` passes from repo root
514
+- [ ] All existing tests continue to pass
515
+- [ ] Detection completes in < 500ms for typical projects (filesystem I/O only, no network)
516
+
517
+### Quality Gates
518
+
519
+- [ ] Unit tests for `ProjectEnvironmentDetector` covering all detection strategies
520
+- [ ] Unit tests for `core-dependency.ts` covering all package managers
521
+- [ ] Command tests for `composio init` covering happy path + error cases
522
+- [ ] At least one E2E test for `composio init --dry-run` in Docker container
523
+- [ ] New test fixtures for pnpm monorepo, bun project, uv project, ambiguous project
524
+
525
+## Success Metrics
526
+
527
+- Users can run `composio init` in any TypeScript or Python project and have dependencies installed automatically
528
+- Zero manual `npm install` / `pnpm add` / `uv pip install` steps needed after init
529
+- Package manager is correctly detected in monorepo setups (pnpm workspaces, etc.)
530
+
531
+## Dependencies & Prerequisites
532
+
533
+- `@effect/platform` `Command` module is already a dependency of the CLI package
534
+- The `composio2` reference implementations are available at `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/`
535
+- Test fixtures for `typescript-project` and `python-project` already exist
536
+
537
+## Risk Analysis & Mitigation
538
+
539
+| Risk | Impact | Mitigation |
540
+|---|---|---|
541
+| Ambiguous project detection (both TS + Python) | User confusion | Prompt user to choose, provide clear error message with evidence |
542
+| Install command fails (network, permissions) | Blocked init flow | Show error with the failing command, suggest manual install |
543
+| Package manager not installed on system | Install fails | Check binary existence before running, suggest install |
544
+| Monorepo: init from subdirectory | Wrong root dir detected | Ancestor walking already handles this; root dir = where lock file or package.json with workspaces lives |
545
+| Breaking existing `generate.cmd.ts` | Regression | Keep old services (Option A), migrate generate in follow-up PR |
546
+
547
+## Implementation Phases
548
+
549
+### Phase 1: Foundation (Services + Effects)
550
+- [x] Add `ProjectEnvironmentDetector` service (`src/services/project-environment-detector.ts`)
551
+- [x] Add `CommandRunner` service (`src/services/command-runner.ts`)
552
+- [x] Add `core-dependency.ts` effect (`src/effects/core-dependency.ts`)
553
+- [x] Wire new services in `bin.ts` layer composition
554
+- [x] Add new test fixtures (pnpm monorepo, bun project, uv project, ambiguous)
555
+
556
+### Phase 2: Unit Tests (TDD Red)
557
+- [x] Write `ProjectEnvironmentDetector` tests (17 test cases)
558
+- [x] Write `core-dependency.ts` tests (7 test cases)
559
+- [x] All tests pass (green)
560
+
561
+### Phase 3: Update `composio init` (Green)
562
+- [x] Add `--dry-run`, `--force`, `--yes` flags to init command
563
+- [x] Extend `InitConfigBuilder` with `withDetectedEnv` and `withInstallPlan`
564
+- [x] Integrate detection into the wizard flow
565
+- [x] Integrate installation with spinner and error handling
566
+- [x] Update structured JSON output to include detection info
567
+- [x] Update `.composio/config.json` to include detection info
568
+
569
+### Phase 4: Command Tests
570
+- [x] Write `init.cmd.test.ts` command tests (8 scenarios)
571
+- [x] Update `TestLive` to support `commandRunner` and `terminalUI` overrides
572
+- [x] Add `ProjectEnvironmentDetector.Default` to test layer
573
+
574
+### Phase 5: E2E Tests
575
+- [ ] Add `ts/e2e-tests/cli/init/` E2E test suite (deferred to follow-up PR)
576
+- [ ] Test `--dry-run` mode with TS and Python fixtures in Docker (deferred)
577
+- [ ] Update `ts/e2e-tests/cli/README.md` with new test info (deferred)
578
+
579
+### Phase 6: Cleanup
580
+- [x] Run `pnpm typecheck` and fix any issues
581
+- [x] Run full test suite and fix regressions
582
+- [ ] Update `CLAUDE.md` if needed (document new services)
583
+
584
+## Future Considerations
585
+
586
+- **`composio install` as standalone command** — extract install logic for re-use outside init
587
+- **Framework provider installation** — add framework-specific packages based on wizard selection
588
+- **Skills installation** — run `npx skills add ComposioHQ/skills` when `installSkills: true`
589
+- **Migrate `generate.cmd.ts`** — replace `EnvLangDetector` usage with `ProjectEnvironmentDetector`
590
+- **Deno support** — handle `deno add npm:@composio/core` pattern
591
+
592
+## References & Research
593
+
594
+### Internal References
595
+
596
+- Current `composio init`: `ts/packages/cli/src/commands/init.cmd.ts`
597
+- Existing `EnvLangDetector`: `ts/packages/cli/src/services/env-lang-detector.ts`
598
+- Existing `JsPackageManagerDetector`: `ts/packages/cli/src/services/js-package-manager-detector.ts`
599
+- Layer composition: `ts/packages/cli/src/bin.ts` (lines 93-112)
600
+- Test infrastructure: `ts/packages/cli/test/__utils__/services/test-layer.ts`
601
+- E2E test framework: `ts/e2e-tests/cli/README.md`
602
+- Login command tests (pattern reference): `ts/packages/cli/test/src/commands/login.cmd.test.ts`
603
+
604
+### Reference Implementations (composio2)
605
+
606
+- `ProjectEnvironmentDetector`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/project-environment-detector.ts`
607
+- `CommandRunner`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/command-runner.ts`
608
+- `core-dependency.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/effects/core-dependency.ts`
609
+- `install.cmd.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/commands/install.cmd.ts`
610
+- `install.cmd.test.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/test/src/commands/install.cmd.test.ts`
611
+- `TerminalUI` with prompts: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/terminal-ui.ts`
612
+
613
+### External References
614
+
615
+- Effect.ts Service pattern: `ts/vendor/effect/packages/effect/src/`
616
+- @effect/cli Command: `ts/vendor/effect/packages/cli/src/Command.ts`
617
+- @effect/platform FileSystem: `ts/vendor/effect/packages/platform/src/FileSystem.ts`
618
+- @effect/platform Command (subprocess): `ts/vendor/effect/packages/platform/src/Command.ts`
619
+- @clack/prompts: `ts/vendor/clack/packages/prompts/src/`
ts/packages/cli/src/bin.ts
+11
-2
@@ -17,13 +17,15 @@ import {
17
import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
18
import { NodeOs } from 'src/services/node-os';
19
import { NodeProcess } from 'src/services/node-process';
20
-import { EnvLangDetector } from 'src/services/env-lang-detector';
20
import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
21
import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
22
import { UpgradeBinary } from 'src/services/upgrade-binary';
23
import { TerminalUILive } from 'src/services/terminal-ui';
24
import { TriggersRealtime } from 'src/services/triggers-realtime';
25
import { ToolsExecutorLive as _ToolsExecutorLive } from 'src/services/tools-executor';
26
+import { ProjectContext } from 'src/services/project-context';
27
+import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
28
+import { CommandRunner } from 'src/services/command-runner';
29
import { StdinLive } from 'src/services/stdin';
30
31
/**
@@ -84,6 +86,11 @@ export const ToolsExecutorLive = Layer.provide(
86
ComposioClientSingletonLive
87
) satisfies RequiredLayer;
88
89
+export const ProjectContextLive = Layer.provide(
90
+ ProjectContext.Default,
91
+ Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
92
+) satisfies RequiredLayer;
93
+
94
const layers = Layer.mergeAll(
95
CliConfigLive.pipe(Layer.provide(ConfigLive)),
96
NodeOs.Default,
@@ -94,9 +101,11 @@ const layers = Layer.mergeAll(
101
ComposioClientSingletonLive, // Expose ComposioClientSingleton for commands that use Tool Router directly
102
ComposioToolkitsRepositoryCachedLive, // Use the cached layer instead of the regular one
103
ToolsExecutorLive,
97
- EnvLangDetector.Default,
104
JsPackageManagerDetector.Default,
105
+ ProjectEnvironmentDetector.Default,
106
+ CommandRunner.Default,
107
TriggersRealtimeLive,
108
+ ProjectContextLive,
109
BunContext.layer,
110
BunFileSystem.layer,
111
StdinLive,
ts/packages/cli/src/commands/generate.cmd.ts
+8
-7
@@ -1,6 +1,6 @@
1
import { Command, Options } from '@effect/cli';
2
import { Effect, Match } from 'effect';
3
-import { EnvLangDetector } from 'src/services/env-lang-detector';
3
+import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
4
import { NodeProcess } from 'src/services/node-process';
5
import { TerminalUI } from 'src/services/terminal-ui';
6
import { generateTypescriptTypeStubs } from './ts/commands/ts.generate.cmd';
@@ -43,13 +43,14 @@ export const generateCmd = Command.make('generate', { outputOpt, typeTools, tool
43
const cwd = process.cwd;
44
45
yield* Effect.logDebug('Identifying project type...');
46
- const envLangDetector = yield* EnvLangDetector;
47
- const envLang = yield* envLangDetector.detectEnvLanguage(cwd);
48
- yield* ui.log.step(`Project type detected: ${envLang}`);
46
+ const envDetector = yield* ProjectEnvironmentDetector;
47
+ const env = yield* envDetector.detectProjectEnvironment(cwd);
48
+ const displayLang = env.kind === 'js' ? 'TypeScript' : 'Python';
49
+ yield* ui.log.step(`Project type detected: ${displayLang}`);
50
51
// Redirect to either `ts generate` or `py generate` commands
51
- yield* Match.value(envLang).pipe(
52
- Match.when('TypeScript', () =>
52
+ yield* Match.value(env.kind).pipe(
53
+ Match.when('js', () =>
54
generateTypescriptTypeStubs({
55
outputOpt,
56
compact: false,
@@ -58,7 +59,7 @@ export const generateCmd = Command.make('generate', { outputOpt, typeTools, tool
59
toolkitsOpt,
60
})
61
),
61
- Match.when('Python', () => generatePythonTypeStubs({ outputOpt, toolkitsOpt })),
62
+ Match.when('python', () => generatePythonTypeStubs({ outputOpt, toolkitsOpt })),
63
Match.exhaustive
64
);
65
})
ts/packages/cli/src/commands/index.ts
+2
@@ -8,6 +8,7 @@ import { upgradeCmd } from './upgrade.cmd';
8
import { whoamiCmd } from './whoami.cmd';
9
import { loginCmd } from './login.cmd';
10
import { logoutCmd } from './logout.cmd';
11
+import { initCmd } from './init.cmd';
12
import { pyCmd } from './py/py.cmd';
13
import { tsCmd } from './ts/ts.cmd';
14
import { generateCmd } from './generate.cmd';
@@ -24,6 +25,7 @@ const $cmd = $defaultCmd.pipe(
25
whoamiCmd,
26
loginCmd,
27
logoutCmd,
28
+ initCmd,
29
generateCmd,
30
pyCmd,
31
tsCmd,
ts/packages/cli/src/commands/init.cmd.ts
new
+693
@@ -0,0 +1,693 @@
1
+import path from 'node:path';
2
+import { Command as CliCommand, Options } from '@effect/cli';
3
+import { Command as PlatformCommand } from '@effect/platform';
4
+import { Effect, Option } from 'effect';
5
+import { FileSystem } from '@effect/platform';
6
+import { ComposioUserContext } from 'src/services/user-context';
7
+import { NodeProcess } from 'src/services/node-process';
8
+import { projectKeysToJSON, type ProjectKeys } from 'src/models/project-keys';
9
+import { listOrgProjects, type OrgProject } from 'src/services/composio-clients';
10
+import * as constants from 'src/constants';
11
+import { TerminalUI } from 'src/services/terminal-ui';
12
+import { browserLogin, noBrowser as noBrowserOpt } from 'src/commands/login.cmd';
13
+import {
14
+ ProjectEnvironmentDetector,
15
+ type ProjectEnvironment,
16
+} from 'src/services/project-environment-detector';
17
+import { CommandRunner } from 'src/services/command-runner';
18
+import {
19
+ detectCoreDependencyPlan,
20
+ resolveCoreDependencyState,
21
+ type CoreDependencyPlan,
22
+} from 'src/effects/core-dependency';
23
+
24
+/**
25
+ * `composio init` — Initialize a Composio project in the current directory.
26
+ *
27
+ * ## Behavior
28
+ *
29
+ * 1. **Project selection** — fetches projects from the API or accepts `--org-id`/`--project-id`.
30
+ * 2. **Usage mode** — asks "Native tools" vs "Composio MCP".
31
+ * 3. **Framework** — if native, asks which agent framework.
32
+ * 4. **Coding-agent skills** — asks whether to install Composio skills.
33
+ * 5. **Environment detection** — detects language (TS/Python) and package manager.
34
+ * 6. **Dependency installation** — installs `@composio/core` or `composio` via detected PM.
35
+ * 7. **Writes config** — saves `<cwd>/.composio/project.json` and `<cwd>/.composio/config.json`.
36
+ *
37
+ * ## Flags
38
+ *
39
+ * - `--dry-run` — print install command without executing
40
+ * - `--force` — reinstall even if dependency is already present
41
+ * - `--yes` / `-y` — skip confirmation prompts
42
+ */
43
+
44
+const orgIdOpt = Options.text('org-id').pipe(
45
+ Options.optional,
46
+ Options.withDescription('Organization ID (skip interactive picker)')
47
+);
48
+
49
+const projectIdOpt = Options.text('project-id').pipe(
50
+ Options.optional,
51
+ Options.withDescription('Project ID (skip interactive picker)')
52
+);
53
+
54
+const dryRunOpt = Options.boolean('dry-run').pipe(
55
+ Options.withDefault(false),
56
+ Options.withDescription('Print install command without executing it')
57
+);
58
+
59
+const forceOpt = Options.boolean('force').pipe(
60
+ Options.withDefault(false),
61
+ Options.withDescription('Reinstall even if dependency appears installed')
62
+);
63
+
64
+const yesOpt = Options.boolean('yes').pipe(
65
+ Options.withAlias('y'),
66
+ Options.withDefault(false),
67
+ Options.withDescription('Skip confirmation prompts')
68
+);
69
+
70
+const noSkillsOpt = Options.boolean('no-skills').pipe(
71
+ Options.withDefault(false),
72
+ Options.withDescription('Skip Composio skills installation')
73
+);
74
+
75
+// ---------------------------------------------------------------------------
76
+// Init config types and options
77
+// ---------------------------------------------------------------------------
78
+
79
+type UsageMode = 'native' | 'mcp';
80
+type NativeFramework = 'skip' | 'ai-sdk' | 'mastra' | 'openai-agents' | 'claude-agent-sdk';
81
+
82
+const USAGE_MODE_OPTIONS: ReadonlyArray<{
83
+ value: UsageMode;
84
+ label: string;
85
+ hint: string;
86
+}> = [
87
+ {
88
+ value: 'native',
89
+ label: 'Native tools',
90
+ hint: 'Use with Agent frameworks: AI SDK, Mastra, etc.',
91
+ },
92
+ {
93
+ value: 'mcp',
94
+ label: 'Composio MCP',
95
+ hint: 'Use Composio tools via MCP',
96
+ },
97
+];
98
+
99
+const NATIVE_FRAMEWORK_OPTIONS: ReadonlyArray<{
100
+ value: NativeFramework;
101
+ label: string;
102
+}> = [
103
+ { value: 'skip', label: 'Skip' },
104
+ { value: 'ai-sdk', label: 'AI SDK' },
105
+ { value: 'mastra', label: 'Mastra' },
106
+ { value: 'openai-agents', label: 'OpenAI Agents' },
107
+ { value: 'claude-agent-sdk', label: 'Claude Agent SDK' },
108
+];
109
+
110
+// ---------------------------------------------------------------------------
111
+// InitConfig — type-safe builder for the init wizard answers
112
+// ---------------------------------------------------------------------------
113
+
114
+/**
115
+ * Immutable config object built step-by-step through the init wizard.
116
+ * Each `.with*` method returns a new instance with the added field,
117
+ * narrowing the type so downstream code can rely on what has been set.
118
+ *
119
+ * The builder enforces that `build()` can only be called once ALL wizard
120
+ * steps have been completed — calling it too early is a compile-time error.
121
+ *
122
+ * Future wizard steps (e.g., detected environment, dependency list) can be
123
+ * added by introducing new `with*` methods and extending the `build()`
124
+ * constraint.
125
+ */
126
+class InitConfigBuilder<T extends Record<string, unknown> = Record<string, never>> {
127
+ private constructor(private readonly data: T) {}
128
+
129
+ static create(): InitConfigBuilder {
130
+ return new InitConfigBuilder({});
131
+ }
132
+
133
+ withUsageMode(mode: UsageMode): InitConfigBuilder<T & { usageMode: UsageMode }> {
134
+ return new InitConfigBuilder({ ...this.data, usageMode: mode });
135
+ }
136
+
137
+ withFramework(
138
+ fw: NativeFramework | undefined
139
+ ): InitConfigBuilder<T & { framework: NativeFramework | undefined }> {
140
+ return new InitConfigBuilder({ ...this.data, framework: fw });
141
+ }
142
+
143
+ withInstallSkills(install: boolean): InitConfigBuilder<T & { installSkills: boolean }> {
144
+ return new InitConfigBuilder({ ...this.data, installSkills: install });
145
+ }
146
+
147
+ withDetectedEnv(
148
+ env: ProjectEnvironment | undefined
149
+ ): InitConfigBuilder<T & { detectedEnv: ProjectEnvironment | undefined }> {
150
+ return new InitConfigBuilder({ ...this.data, detectedEnv: env });
151
+ }
152
+
153
+ withInstallPlan(
154
+ plan: CoreDependencyPlan | undefined
155
+ ): InitConfigBuilder<T & { installPlan: CoreDependencyPlan | undefined }> {
156
+ return new InitConfigBuilder({ ...this.data, installPlan: plan });
157
+ }
158
+
159
+ /** Extract the final config. Only callable when all required fields are present. */
160
+ build(
161
+ this: InitConfigBuilder<{
162
+ usageMode: UsageMode;
163
+ framework: NativeFramework | undefined;
164
+ installSkills: boolean;
165
+ detectedEnv: ProjectEnvironment | undefined;
166
+ installPlan: CoreDependencyPlan | undefined;
167
+ }>
168
+ ): InitConfig {
169
+ return {
170
+ usageMode: this.data.usageMode,
171
+ framework: this.data.framework,
172
+ installSkills: this.data.installSkills,
173
+ detectedEnv: this.data.detectedEnv,
174
+ installPlan: this.data.installPlan,
175
+ };
176
+ }
177
+
178
+ /** Read accumulated data (for intermediate access). */
179
+ get value(): T {
180
+ return this.data;
181
+ }
182
+}
183
+
184
+interface InitConfig {
185
+ readonly usageMode: UsageMode;
186
+ readonly framework: NativeFramework | undefined;
187
+ readonly installSkills: boolean;
188
+ readonly detectedEnv: ProjectEnvironment | undefined;
189
+ readonly installPlan: CoreDependencyPlan | undefined;
190
+}
191
+
192
+// ---------------------------------------------------------------------------
193
+// Init wizard — collects all answers via the builder
194
+// ---------------------------------------------------------------------------
195
+
196
+/**
197
+ * Detect the project environment. Returns `undefined` if detection fails
198
+ * (logs a warning but does not abort the wizard).
199
+ */
200
+const detectEnvironment = (cwd: string) =>
201
+ Effect.gen(function* () {
202
+ const ui = yield* TerminalUI;
203
+ const envDetector = yield* ProjectEnvironmentDetector;
204
+
205
+ return yield* envDetector.detectProjectEnvironment(cwd).pipe(
206
+ Effect.tap(env => ui.log.step(`Detected: ${env.language} (${env.packageManager})`)),
207
+ Effect.catchTag('services/ProjectEnvironmentDetectorError', e =>
208
+ Effect.gen(function* () {
209
+ yield* ui.log.warn(e.message);
210
+ if (e.details) yield* ui.log.info(e.details);
211
+ yield* ui.log.info('Skipping dependency installation.');
212
+ return undefined;
213
+ })
214
+ )
215
+ );
216
+ });
217
+
218
+/**
219
+ * Resolve the install plan for the detected environment.
220
+ * Only determines WHAT to install (no version checking or shell commands).
221
+ * Version checking is deferred to `runInstallStep`.
222
+ */
223
+const resolveInstallPlan = (cwd: string) =>
224
+ detectCoreDependencyPlan(cwd).pipe(Effect.catchAll(() => Effect.succeed(null)));
225
+
226
+/**
227
+ * After detecting the project environment and resolving an install plan,
228
+ * ask the user to confirm the detected package manager or skip installation.
229
+ * Returns the plan if confirmed, `undefined` if skipped.
230
+ */
231
+const confirmInstallPlan = (plan: CoreDependencyPlan) =>
232
+ Effect.gen(function* () {
233
+ const ui = yield* TerminalUI;
234
+
235
+ type PmChoice = 'confirm' | 'skip';
236
+ const choice = yield* ui.select<PmChoice>(
237
+ `Install ${plan.dependency} using ${plan.packageManager}?`,
238
+ [
239
+ { value: 'confirm' as PmChoice, label: plan.packageManager, hint: plan.installCommand },
240
+ { value: 'skip' as PmChoice, label: 'Skip' },
241
+ ]
242
+ );
243
+
244
+ return choice === 'confirm' ? plan : undefined;
245
+ });
246
+
247
+/**
248
+ * Runs the interactive init wizard.
249
+ *
250
+ * Steps:
251
+ * 1. Usage mode — "Native tools" or "Composio MCP"
252
+ * 2. Framework — which agent framework (only if native)
253
+ * 3. Install skills — whether to install Composio coding-agent skills
254
+ * 4. Detect project environment (only if native)
255
+ * 5. Resolve + confirm install plan (only if native and environment detected)
256
+ *
257
+ * All inputs are collected through the builder before any side effects run.
258
+ * Returns a fully-built `InitConfig`.
259
+ */
260
+const runInitWizard = (cwd: string, params: { noSkills: boolean }) =>
261
+ Effect.gen(function* () {
262
+ const ui = yield* TerminalUI;
263
+
264
+ // Step 1: Usage mode
265
+ const usageMode = yield* ui.select<UsageMode>(
266
+ 'How would you like to use Composio?',
267
+ USAGE_MODE_OPTIONS
268
+ );
269
+
270
+ // Step 2: Framework (only for native tools)
271
+ const framework: NativeFramework | undefined =
272
+ usageMode === 'native'
273
+ ? yield* ui
274
+ .select<NativeFramework>('Which framework do you use?', NATIVE_FRAMEWORK_OPTIONS)
275
+ .pipe(Effect.map(fw => (fw === 'skip' ? undefined : fw)))
276
+ : undefined;
277
+
278
+ // Step 3: Install Composio skills (skip prompt when --no-skills)
279
+ const installSkills = params.noSkills
280
+ ? false
281
+ : yield* ui.confirm('Install Composio skills for your Coding Agent?', {
282
+ defaultValue: true,
283
+ });
284
+
285
+ // Steps 4+5: Detect environment + confirm install plan (only for native tools)
286
+ let detectedEnv: ProjectEnvironment | undefined;
287
+ let installPlan: CoreDependencyPlan | undefined;
288
+
289
+ if (usageMode === 'native') {
290
+ // Step 4: Detect project environment
291
+ detectedEnv = yield* detectEnvironment(cwd);
292
+
293
+ // Step 5: Resolve install plan and confirm package manager
294
+ if (detectedEnv) {
295
+ const plan = yield* resolveInstallPlan(cwd);
296
+ if (plan) {
297
+ installPlan = yield* confirmInstallPlan(plan);
298
+ }
299
+ }
300
+ }
301
+
302
+ return InitConfigBuilder.create()
303
+ .withUsageMode(usageMode)
304
+ .withFramework(framework)
305
+ .withInstallSkills(installSkills)
306
+ .withDetectedEnv(detectedEnv)
307
+ .withInstallPlan(installPlan)
308
+ .build();
309
+ });
310
+
311
+// ---------------------------------------------------------------------------
312
+// File I/O helpers
313
+// ---------------------------------------------------------------------------
314
+
315
+/**
316
+ * Serializes an `InitConfig` to the JSON payload written to `.composio/config.json`.
317
+ */
318
+const initConfigToJSON = (config: InitConfig): string => {
319
+ const payload: Record<string, unknown> = {
320
+ usage_mode: config.usageMode,
321
+ };
322
+ if (config.framework) {
323
+ payload.framework = config.framework;
324
+ }
325
+ payload.install_skills = config.installSkills;
326
+ if (config.detectedEnv) {
327
+ payload.detected_language = config.detectedEnv.language;
328
+ payload.package_manager = config.detectedEnv.packageManager;
329
+ }
330
+ return JSON.stringify(payload, null, 2);
331
+};
332
+
333
+/** Writes project keys + init config to `<cwd>/.composio/` and creates a `.gitignore`. */
334
+const writeProjectConfig = (composioDir: string, selected: ProjectKeys, config: InitConfig) =>
335
+ Effect.gen(function* () {
336
+ const fs = yield* FileSystem.FileSystem;
337
+
338
+ yield* fs
339
+ .makeDirectory(composioDir, { recursive: true })
340
+ .pipe(Effect.catchAll(() => Effect.void));
341
+
342
+ const projectJson = yield* projectKeysToJSON(selected);
343
+ yield* fs.writeFileString(
344
+ path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME),
345
+ projectJson
346
+ );
347
+
348
+ yield* fs.writeFileString(path.join(composioDir, 'config.json'), initConfigToJSON(config));
349
+
350
+ // Create .composio/.gitignore to prevent accidental commits
351
+ const gitignorePath = path.join(composioDir, '.gitignore');
352
+ const gitignoreExists = yield* fs.exists(gitignorePath);
353
+ if (!gitignoreExists) {
354
+ yield* fs.writeFileString(gitignorePath, '*\n');
355
+ }
356
+ });
357
+
358
+// ---------------------------------------------------------------------------
359
+// Install step — runs after wizard, before outro
360
+// ---------------------------------------------------------------------------
361
+
362
+/**
363
+ * Runs the dependency installation step based on the init config.
364
+ * Handles --dry-run, --force, --yes flags and already-installed detection.
365
+ */
366
+const runInstallStep = (params: {
367
+ config: InitConfig;
368
+ cwd: string;
369
+ dryRun: boolean;
370
+ force: boolean;
371
+ yes: boolean;
372
+}) =>
373
+ Effect.gen(function* () {
374
+ const { config, cwd, dryRun, force, yes } = params;
375
+ if (!config.installPlan) return;
376
+
377
+ const ui = yield* TerminalUI;
378
+ const runner = yield* CommandRunner;
379
+ const plan = config.installPlan;
380
+
381
+ // Check if already installed (only for JS — Python version check requires shell)
382
+ if (plan.kind === 'js') {
383
+ const depState = yield* resolveCoreDependencyState(cwd).pipe(
384
+ Effect.catchAll(() => Effect.succeed({ plan, installedVersion: null }))
385
+ );
386
+
387
+ if (depState.installedVersion && !force) {
388
+ const detail =
389
+ depState.installedVersion.source === 'package.json'
390
+ ? `declared in package.json (${depState.installedVersion.version})`
391
+ : `${depState.installedVersion.version} (${depState.installedVersion.source})`;
392
+ yield* ui.log.info(`Found ${plan.dependency}: ${detail}`);
393
+ yield* ui.log.success('Dependency already installed.');
394
+ return;
395
+ }
396
+
397
+ if (depState.installedVersion && force) {
398
+ yield* ui.log.warn('Reinstalling due to --force.');
399
+ }
400
+ }
401
+
402
+ if (dryRun) {
403
+ yield* ui.note(plan.installCommand, 'Install Command');
404
+ yield* ui.log.info('Dry run complete.');
405
+ return;
406
+ }
407
+
408
+ const shouldInstall =
409
+ yes || (yield* ui.confirm(`Run: ${plan.installCommand}?`, { defaultValue: true }));
410
+ if (!shouldInstall) {
411
+ yield* ui.log.warn('Installation cancelled.');
412
+ return;
413
+ }
414
+
415
+ const [cmd, ...args] = plan.installCommand.split(' ');
416
+ const command = PlatformCommand.make(cmd!, ...args).pipe(
417
+ PlatformCommand.workingDirectory(plan.rootDir)
418
+ );
419
+
420
+ const install = Effect.gen(function* () {
421
+ const exitCode = yield* runner.run(command);
422
+ if (exitCode !== 0) {
423
+ yield* Effect.fail(new Error(`Install command failed with exit code ${exitCode}`));
424
+ }
425
+ });
426
+
427
+ yield* ui
428
+ .withSpinner(`Installing ${plan.dependency}...`, install, {
429
+ successMessage: `Installed ${plan.dependency}.`,
430
+ errorMessage: `Failed to install ${plan.dependency}.`,
431
+ })
432
+ .pipe(
433
+ Effect.catchAll(e =>
434
+ Effect.gen(function* () {
435
+ yield* ui.log.error(`Install failed: ${e instanceof Error ? e.message : String(e)}`);
436
+ yield* ui.log.info(`You can install manually: ${plan.installCommand}`);
437
+ })
438
+ )
439
+ );
440
+ });
441
+
442
+// ---------------------------------------------------------------------------
443
+// Skills install step — runs `npx skills add composiohq/skills`
444
+// ---------------------------------------------------------------------------
445
+
446
+const SKILLS_INSTALL_COMMAND = 'npx skills add composiohq/skills';
447
+
448
+/**
449
+ * Runs the Composio skills installation step.
450
+ * Uses `npx skills add composiohq/skills` to install coding-agent skills.
451
+ */
452
+const runSkillsInstallStep = (params: {
453
+ config: InitConfig;
454
+ cwd: string;
455
+ dryRun: boolean;
456
+ yes: boolean;
457
+}) =>
458
+ Effect.gen(function* () {
459
+ const { config, cwd, dryRun, yes } = params;
460
+ if (!config.installSkills) return;
461
+
462
+ const ui = yield* TerminalUI;
463
+ const runner = yield* CommandRunner;
464
+
465
+ if (dryRun) {
466
+ yield* ui.note(SKILLS_INSTALL_COMMAND, 'Skills Install Command');
467
+ return;
468
+ }
469
+
470
+ const shouldInstall =
471
+ yes || (yield* ui.confirm(`Run: ${SKILLS_INSTALL_COMMAND}?`, { defaultValue: true }));
472
+ if (!shouldInstall) {
473
+ yield* ui.log.warn('Skills installation cancelled.');
474
+ return;
475
+ }
476
+
477
+ const [cmd, ...args] = SKILLS_INSTALL_COMMAND.split(' ');
478
+ const command = PlatformCommand.make(cmd!, ...args).pipe(
479
+ PlatformCommand.workingDirectory(cwd)
480
+ );
481
+
482
+ const install = Effect.gen(function* () {
483
+ const exitCode = yield* runner.run(command);
484
+ if (exitCode !== 0) {
485
+ yield* Effect.fail(new Error(`Skills install command failed with exit code ${exitCode}`));
486
+ }
487
+ });
488
+
489
+ yield* ui
490
+ .withSpinner('Installing Composio skills...', install, {
491
+ successMessage: 'Installed Composio skills.',
492
+ errorMessage: 'Failed to install Composio skills.',
493
+ })
494
+ .pipe(
495
+ Effect.catchAll(e =>
496
+ Effect.gen(function* () {
497
+ yield* ui.log.error(
498
+ `Skills install failed: ${e instanceof Error ? e.message : String(e)}`
499
+ );
500
+ yield* ui.log.info(`You can install manually: ${SKILLS_INSTALL_COMMAND}`);
501
+ })
502
+ )
503
+ );
504
+ });
505
+
506
+// ---------------------------------------------------------------------------
507
+// Structured output helper
508
+// ---------------------------------------------------------------------------
509
+
510
+const makeOutputJson = (selected: ProjectKeys, config: InitConfig, composioDir: string) =>
511
+ JSON.stringify({
512
+ org_id: selected.orgId,
513
+ project_id: selected.projectId,
514
+ usage_mode: config.usageMode,
515
+ framework: config.framework ?? null,
516
+ install_skills: config.installSkills,
517
+ detected_language: config.detectedEnv?.language ?? null,
518
+ package_manager: config.detectedEnv?.packageManager ?? null,
519
+ install_command: config.installPlan?.installCommand ?? null,
520
+ path: composioDir,
521
+ });
522
+
523
+// ---------------------------------------------------------------------------
524
+// Command
525
+// ---------------------------------------------------------------------------
526
+
527
+/**
528
+ * CLI command to initialize a Composio project in the current directory.
529
+ *
530
+ * Creates `<cwd>/.composio/project.json` with org_id and project_id,
531
+ * plus `<cwd>/.composio/config.json` with usage mode, framework, and skill preferences.
532
+ *
533
+ * Supports two modes:
534
+ * 1. Interactive: Fetches projects from the API and prompts for selection
535
+ * 2. Non-interactive: Accepts --org-id and --project-id flags for agents/CI
536
+ *
537
+ * @example
538
+ * ```bash
539
+ * composio init
540
+ * composio init --org-id <org> --project-id <project>
541
+ * ```
542
+ */
543
+export const initCmd = CliCommand.make(
544
+ 'init',
545
+ {
546
+ orgId: orgIdOpt,
547
+ projectId: projectIdOpt,
548
+ noBrowser: noBrowserOpt,
549
+ dryRun: dryRunOpt,
550
+ force: forceOpt,
551
+ yes: yesOpt,
552
+ noSkills: noSkillsOpt,
553
+ },
554
+ ({ orgId, projectId, noBrowser, dryRun, force, yes, noSkills }) =>
555
+ Effect.gen(function* () {
556
+ const ui = yield* TerminalUI;
557
+ const ctx = yield* ComposioUserContext;
558
+ const proc = yield* NodeProcess;
559
+
560
+ yield* ui.intro('composio init');
561
+
562
+ const composioDir = path.join(proc.cwd, constants.PROJECT_COMPOSIO_DIR);
563
+
564
+ // Agent-native path: --org-id and --project-id flags skip project picker
565
+ if (Option.isSome(orgId) && Option.isSome(projectId)) {
566
+ const selected: ProjectKeys = {
567
+ orgId: orgId.value,
568
+ projectId: projectId.value,
569
+ projectName: Option.none(),
570
+ orgName: Option.none(),
571
+ email: Option.none(),
572
+ };
573
+
574
+ const config = yield* runInitWizard(proc.cwd, { noSkills });
575
+ yield* writeProjectConfig(composioDir, selected, config);
576
+ yield* runInstallStep({ config, cwd: proc.cwd, dryRun, force, yes });
577
+ yield* runSkillsInstallStep({ config, cwd: proc.cwd, dryRun, yes });
578
+
579
+ yield* ui.log.success(`Project initialized in ${composioDir}/`);
580
+ yield* ui.output(makeOutputJson(selected, config, composioDir));
581
+ yield* ui.outro('');
582
+ return;
583
+ }
584
+
585
+ yield* initInteractiveFlow({ composioDir, noBrowser, dryRun, force, yes, noSkills });
586
+ })
587
+).pipe(CliCommand.withDescription('Initialize a Composio project in the current directory.'));
588
+
589
+/**
590
+ * Interactive init flow — handles login, project selection, wizard, install.
591
+ * Extracted to keep the main command handler under the line limit.
592
+ */
593
+const initInteractiveFlow = (params: {
594
+ composioDir: string;
595
+ noBrowser: boolean;
596
+ dryRun: boolean;
597
+ force: boolean;
598
+ yes: boolean;
599
+ noSkills: boolean;
600
+}) =>
601
+ Effect.gen(function* () {
602
+ const { composioDir, noBrowser, dryRun, force, yes, noSkills } = params;
603
+ const ui = yield* TerminalUI;
604
+ const ctx = yield* ComposioUserContext;
605
+ const proc = yield* NodeProcess;
606
+
607
+ // 1. Ensure user is logged in
608
+ if (!ctx.isLoggedIn()) {
609
+ yield* ui.log.step('No credentials found. Logging in...');
610
+ yield* browserLogin({ scope: 'project', noBrowser });
611
+ }
612
+
613
+ // 2. Fetch projects
614
+ const apiKey = Option.getOrUndefined(ctx.data.apiKey);
615
+ const orgIdValue = Option.getOrUndefined(ctx.data.orgId);
616
+ const projectIdValue = Option.getOrUndefined(ctx.data.projectId);
617
+ if (!apiKey || !orgIdValue || !projectIdValue) {
618
+ yield* ui.log.warn(
619
+ 'No API key, org ID, or project ID found. Please try `composio login` first.'
620
+ );
621
+ yield* ui.outro('');
622
+ return;
623
+ }
624
+
625
+ const orgProjects = yield* listOrgProjects({
626
+ baseURL: ctx.data.baseURL,
627
+ apiKey,
628
+ orgId: orgIdValue,
629
+ projectId: projectIdValue,
630
+ }).pipe(
631
+ Effect.catchTag('services/HttpServerError', e =>
632
+ Effect.gen(function* () {
633
+ yield* Effect.logDebug('Failed to list org projects:', e);
634
+ yield* ui.log.warn('Could not fetch projects from the server.');
635
+ yield* ui.log.info(
636
+ 'Use `composio init --org-id <org> --project-id <project>` to set up manually.'
637
+ );
638
+ yield* ui.outro('');
639
+ return yield* Effect.fail(e);
640
+ })
641
+ ),
642
+ Effect.catchTag('services/HttpDecodingError', e =>
643
+ Effect.gen(function* () {
644
+ yield* Effect.logDebug('Failed to decode org projects response:', e);
645
+ yield* ui.log.warn('Unexpected response from the server.');
646
+ yield* ui.log.info(
647
+ 'Use `composio init --org-id <org> --project-id <project>` to set up manually.'
648
+ );
649
+ yield* ui.outro('');
650
+ return yield* Effect.fail(e);
651
+ })
652
+ )
653
+ );
654
+
655
+ if (orgProjects.data.length === 0) {
656
+ yield* ui.log.warn('No projects found for your organization.');
657
+ yield* ui.log.info(
658
+ 'Create a project at https://platform.composio.dev, then run `composio init` again.'
659
+ );
660
+ yield* ui.outro('');
661
+ return;
662
+ }
663
+
664
+ // 3. Select a project
665
+ const orgProjectToKeys = (p: OrgProject): ProjectKeys => ({
666
+ orgId: p.org_id,
667
+ projectId: p.id,
668
+ projectName: Option.some(p.name),
669
+ orgName: Option.none(),
670
+ email: Option.some(p.email),
671
+ });
672
+
673
+ const selectedProject: OrgProject =
674
+ orgProjects.data.length === 1
675
+ ? orgProjects.data[0]
676
+ : yield* ui.select<OrgProject>(
677
+ 'Select a project:',
678
+ orgProjects.data.map(p => ({ value: p, label: p.name, hint: p.id }))
679
+ );
680
+
681
+ const selected = orgProjectToKeys(selectedProject);
682
+ yield* ui.log.step(`Using project "${selectedProject.name}"`);
683
+
684
+ // 4. Run wizard + write config + install
685
+ const config = yield* runInitWizard(proc.cwd, { noSkills });
686
+ yield* writeProjectConfig(composioDir, selected, config);
687
+ yield* runInstallStep({ config, cwd: proc.cwd, dryRun, force, yes });
688
+ yield* runSkillsInstallStep({ config, cwd: proc.cwd, dryRun, yes });
689
+
690
+ yield* ui.log.success(`Project initialized in ${composioDir}/`);
691
+ yield* ui.output(makeOutputJson(selected, config, composioDir));
692
+ yield* ui.outro('');
693
+ });
ts/packages/cli/src/commands/login.cmd.ts
+239
-42
@@ -1,7 +1,12 @@
1
import { Command, Options } from '@effect/cli';
2
-import { Effect, Schedule } from 'effect';
2
+import { Effect, Option, Schedule } from 'effect';
3
import open from 'open';
4
-import { ComposioSessionRepository } from 'src/services/composio-clients';
4
+import {
5
+ ComposioSessionRepository,
6
+ getSessionInfo,
7
+ getSessionInfoByUserApiKey,
8
+ type SessionInfoResponse,
9
+} from 'src/services/composio-clients';
10
import { ComposioUserContext } from 'src/services/user-context';
11
import { TerminalUI } from 'src/services/terminal-ui';
12
@@ -10,41 +15,148 @@ export const noBrowser = Options.boolean('no-browser').pipe(
15
Options.withDescription('Login without browser interaction')
16
);
17
18
+const apiKeyOpt = Options.text('api-key').pipe(
19
+ Options.optional,
20
+ Options.withDescription('API key for non-interactive login (agents/CI)')
21
+);
22
+
23
+const orgIdOpt = Options.text('org-id').pipe(
24
+ Options.optional,
25
+ Options.withDescription('Organization ID for non-interactive login')
26
+);
27
+
28
+const projectIdOpt = Options.text('project-id').pipe(
29
+ Options.optional,
30
+ Options.withDescription('Project ID for non-interactive login')
31
+);
32
+
33
/**
14
- * CLI command to login using Composio's CLI session APIs.
34
+ * Verifies credentials via session/info and stores them.
35
*
16
- * @example
17
- * ```bash
18
- * composio login <command>
19
- * ```
36
+ * Resolves TerminalUI and ComposioUserContext from the Effect context rather
37
+ * than accepting them as parameters -- this keeps the signature focused on
38
+ * data and avoids hand-rolled structural types.
39
*/
21
-export const loginCmd = Command.make('login', { noBrowser }, ({ noBrowser }) =>
40
+const storeCredentials = (params: {
41
+ baseURL: string;
42
+ uakApiKey: string;
43
+ initialOrgId: string;
44
+ initialProjectId: string;
45
+ fallbackEmail: string;
46
+ /**
47
+ * When true, 400/401/403 from session/info will fail the login.
48
+ * Used for non-interactive login where the user provides explicit IDs.
49
+ * When false, all session/info errors are non-fatal (browser login).
50
+ */
51
+ strictVerification: boolean;
52
+}) =>
53
Effect.gen(function* () {
54
const ui = yield* TerminalUI;
55
const ctx = yield* ComposioUserContext;
56
26
- yield* ui.intro('composio login');
57
+ const {
58
+ baseURL,
59
+ uakApiKey,
60
+ initialOrgId,
61
+ initialProjectId,
62
+ fallbackEmail,
63
+ strictVerification,
64
+ } = params;
65
28
- if (ctx.isLoggedIn()) {
29
- yield* ui.log.warn(`You're already logged in!`);
30
- yield* ui.log.info(
31
- `If you want to log in with a different account, please run \`composio logout\` first.`
32
- );
33
- yield* ui.outro('');
34
- return;
66
+ // Call session/info to enrich the login with org/project metadata.
67
+ // In strict mode (non-interactive login), 400/401/403 are hard failures.
68
+ // In non-strict mode (browser login), all errors are non-fatal since
69
+ // the linked session is already authenticated.
70
+ const sessionInfo: SessionInfoResponse | undefined = yield* getSessionInfo({
71
+ baseURL,
72
+ apiKey: uakApiKey,
73
+ orgId: initialOrgId,
74
+ projectId: initialProjectId,
75
+ }).pipe(
76
+ Effect.catchTag('services/HttpServerError', e =>
77
+ Effect.gen(function* () {
78
+ if (strictVerification && e.status && e.status >= 400 && e.status < 500) {
79
+ return yield* Effect.fail(e);
80
+ }
81
+ yield* Effect.logDebug(`Session info fetch failed (HTTP ${e.status ?? '?'}):`, e);
82
+ return undefined;
83
+ })
84
+ ),
85
+ Effect.catchTag('services/HttpDecodingError', e =>
86
+ Effect.gen(function* () {
87
+ yield* Effect.logDebug('Session info decoding error:', e);
88
+ return undefined;
89
+ })
90
+ )
91
+ );
92
+
93
+ // Use session/info as the canonical source of org/project IDs when available.
94
+ // The initial IDs come from the linked session response (which may use session-level
95
+ // identifiers rather than the actual org/project IDs).
96
+ const orgId = sessionInfo?.org_member.id ?? initialOrgId;
97
+ const projectId = sessionInfo?.project.id ?? initialProjectId;
98
+
99
+ if (sessionInfo) {
100
+ if (initialOrgId !== orgId) {
101
+ yield* Effect.logDebug(`orgId corrected: ${initialOrgId} -> ${orgId} (from session/info)`);
102
+ }
103
+ if (initialProjectId !== projectId) {
104
+ yield* Effect.logDebug(
105
+ `projectId corrected: ${initialProjectId} -> ${projectId} (from session/info)`
106
+ );
107
+ }
108
}
109
110
+ // Store UAK + org/project IDs in user_data.json
111
+ yield* ctx.login(uakApiKey, orgId, projectId);
112
+
113
+ const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
114
+ yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
115
+ yield* ui.log.info('Run `composio init` in your project directory to set up project context.');
116
+
117
+ // Emit structured JSON for piped/scripted consumption (agent-native)
118
+ yield* ui.output(
119
+ JSON.stringify({
120
+ email,
121
+ org_id: orgId,
122
+ project_id: projectId,
123
+ org_name: sessionInfo?.project.org.name ?? '',
124
+ project_name: sessionInfo?.project.name ?? '',
125
+ })
126
+ );
127
+
128
+ yield* ui.outro("You're all set!");
129
+ });
130
+
131
+/**
132
+ * Runs the browser-based login flow: creates a CLI session, opens the browser,
133
+ * polls until linked, enriches via session/info, and stores credentials.
134
+ *
135
+ * Shared by `composio login` (scope: 'user') and `composio init` (scope: 'project').
136
+ *
137
+ * Resolves TerminalUI, ComposioUserContext, and ComposioSessionRepository
138
+ * from the Effect context.
139
+ */
140
+export const browserLogin = (params: {
141
+ /** Session scope: 'user' for login, 'project' for init. */
142
+ scope: 'user' | 'project';
143
+ /** When true, don't open browser — just show the URL. */
144
+ noBrowser: boolean;
145
+}) =>
146
+ Effect.gen(function* () {
147
+ const ui = yield* TerminalUI;
148
+ const ctx = yield* ComposioUserContext;
149
const client = yield* ComposioSessionRepository;
150
39
- yield* Effect.logDebug('Authenticating...');
151
+ yield* Effect.logDebug(`Authenticating (scope: ${params.scope})...`);
152
41
- const session = yield* client.createSession();
153
+ const session = yield* client.createSession({ scope: params.scope });
154
43
- yield* Effect.logDebug(`Created session:`, session);
155
+ yield* Effect.logDebug(`Created session: ${session.id}`);
156
157
const url = `${ctx.data.webURL}?cliKey=${session.id}`;
158
47
- if (noBrowser) {
159
+ if (params.noBrowser) {
160
yield* ui.log.info('Please login using the following URL:');
161
} else {
162
yield* ui.log.step('Redirecting you to the login page');
@@ -53,45 +165,31 @@ export const loginCmd = Command.make('login', { noBrowser }, ({ noBrowser }) =>
165
yield* ui.note(url, 'Login URL');
166
yield* ui.output(url);
167
56
- if (!noBrowser) {
57
- // Open the given `url` in the default browser.
58
- // Do NOT use `apps.browser` — it triggers AppleScript-based default browser
59
- // detection (`bundle-name` → Finder + System Events), which fails on macOS
60
- // when the terminal lacks Apple Events permissions (error -1743).
61
- // Calling `open(url)` without an app lets the OS handle browser selection natively.
168
+ if (!params.noBrowser) {
169
yield* Effect.tryPromise(() => open(url, { wait: false })).pipe(
170
Effect.catchAll(error =>
171
Effect.gen(function* () {
172
yield* Effect.logDebug('Failed to open browser:', error);
173
yield* ui.log.warn('Could not open the browser automatically.');
174
yield* ui.log.info(
68
- `Tip: try using \`composio login --no-browser\` and open the URL manually.`
175
+ `Tip: try using the \`--no-browser\` flag and open the URL manually.`
176
);
177
})
178
)
179
);
180
}
181
75
- // Retry operation until the session status is "linked" with exponential backoff.
76
- // useMakeSpinner auto-cleans up the spinner on interruption (e.g., Ctrl+C).
182
const linkedSession = yield* ui.useMakeSpinner('Waiting for login...', spinner =>
183
Effect.retry(
184
Effect.gen(function* () {
80
- const currentSession = yield* client.getSession({
81
- ...session,
82
- });
83
-
84
- // Check if session is linked
185
+ const currentSession = yield* client.getSession({ ...session });
186
if (currentSession.status === 'linked') {
187
return currentSession;
188
}
88
-
89
- // If still pending, fail to trigger retry
189
return yield* Effect.fail(
190
new Error(`Session status is still '${currentSession.status}', waiting for 'linked'`)
191
);
192
}),
94
- // Exponential backoff: start with 0.3s, max 5s, up to 15 retries
193
Schedule.exponential('0.3 seconds').pipe(
194
Schedule.intersect(Schedule.recurs(15)),
195
Schedule.intersect(Schedule.spaced('5 seconds'))
@@ -102,11 +200,110 @@ export const loginCmd = Command.make('login', { noBrowser }, ({ noBrowser }) =>
200
)
201
);
202
105
- yield* Effect.logDebug(`Linked session: ${JSON.stringify(linkedSession)}`);
203
+ yield* Effect.logDebug(`Linked session ID: ${linkedSession.id}`);
204
107
- yield* ctx.login(linkedSession.api_key);
205
+ // e.g., "uak_b813ydmoEYdB_xBxGHeW"
206
+ const uakApiKey = linkedSession.api_key;
207
109
- yield* ui.log.success(`Logged in with user account ${linkedSession.account.email}`);
110
- yield* ui.outro("You're all set!");
111
- })
208
+ const uakSessionInfo = yield* getSessionInfoByUserApiKey({
209
+ baseURL: ctx.data.baseURL,
210
+ userApiKey: uakApiKey,
211
+ });
212
+
213
+ // e.g., "pr_xlSR6oN5jIlk"
214
+ const xProjectId = uakSessionInfo.project.nano_id;
215
+ // e.g., "k2OiqRLMdHyM"
216
+ const xOrgId = uakSessionInfo.project.org.id;
217
+
218
+ yield* Effect.logDebug('UAK session info:', { xProjectId, xOrgId });
219
+
220
+ yield* storeCredentials({
221
+ baseURL: ctx.data.baseURL,
222
+ uakApiKey,
223
+ initialOrgId: xOrgId,
224
+ initialProjectId: xProjectId,
225
+ fallbackEmail: linkedSession.account.email,
226
+ strictVerification: false,
227
+ });
228
+ });
229
+
230
+/**
231
+ * CLI command to login using Composio's CLI session APIs.
232
+ *
233
+ * Supports two modes:
234
+ * 1. Browser-based: Opens browser for OAuth flow (default)
235
+ * 2. Non-interactive: Accepts --api-key, --org-id, --project-id flags for agents/CI
236
+ *
237
+ * @example
238
+ * ```bash
239
+ * composio login
240
+ * composio login --no-browser
241
+ * composio login --api-key uak_xxx --org-id org-id --project-id proj-id
242
+ * ```
243
+ */
244
+export const loginCmd = Command.make(
245
+ 'login',
246
+ { noBrowser, apiKey: apiKeyOpt, orgId: orgIdOpt, projectId: projectIdOpt },
247
+ ({ noBrowser, apiKey, orgId, projectId }) =>
248
+ Effect.gen(function* () {
249
+ const ui = yield* TerminalUI;
250
+ const ctx = yield* ComposioUserContext;
251
+
252
+ yield* ui.intro('composio login');
253
+
254
+ // Non-interactive path: --api-key, --org-id, --project-id flags skip browser flow.
255
+ // All three must be provided together; partial flags are an error.
256
+ const nonInteractiveFlags = [apiKey, orgId, projectId];
257
+ const anyProvided = nonInteractiveFlags.some(Option.isSome);
258
+ const allProvided = nonInteractiveFlags.every(Option.isSome);
259
+
260
+ if (anyProvided && !allProvided) {
261
+ const missing = [
262
+ Option.isNone(apiKey) && '--api-key',
263
+ Option.isNone(orgId) && '--org-id',
264
+ Option.isNone(projectId) && '--project-id',
265
+ ].filter(Boolean);
266
+ yield* ui.log.error(`Missing required flag(s): ${missing.join(', ')}`);
267
+ yield* ui.log.info(
268
+ 'Non-interactive login requires all three: --api-key, --org-id, --project-id'
269
+ );
270
+ yield* ui.outro('');
271
+ return;
272
+ }
273
+
274
+ // Strict verification: 400/401/403 from session/info are hard failures since
275
+ // the user explicitly provided the IDs.
276
+ if (
277
+ allProvided &&
278
+ Option.isSome(apiKey) &&
279
+ Option.isSome(orgId) &&
280
+ Option.isSome(projectId)
281
+ ) {
282
+ yield* Effect.logDebug('Non-interactive login with provided credentials');
283
+ yield* storeCredentials({
284
+ baseURL: ctx.data.baseURL,
285
+ uakApiKey: apiKey.value,
286
+ initialOrgId: orgId.value,
287
+ initialProjectId: projectId.value,
288
+ fallbackEmail: '',
289
+ strictVerification: true,
290
+ });
291
+ return;
292
+ }
293
+
294
+ if (ctx.isLoggedIn()) {
295
+ // Allow re-login when orgId/projectId are not yet set (old CLI login without multi-project support)
296
+ if (Option.isSome(ctx.data.orgId) && Option.isSome(ctx.data.projectId)) {
297
+ yield* ui.log.warn(`You're already logged in!`);
298
+ yield* ui.log.info(
299
+ `If you want to log in with a different account, please run \`composio logout\` first.`
300
+ );
301
+ yield* ui.outro('');
302
+ return;
303
+ }
304
+ yield* ui.log.step('Re-authenticating for multi-project support...');
305
+ }
306
+
307
+ yield* browserLogin({ scope: 'user', noBrowser });
308
+ })
309
).pipe(Command.withDescription('Log in to the Composio SDK.'));
ts/packages/cli/src/commands/logout.cmd.ts
+1
@@ -22,6 +22,7 @@ export const logoutCmd = Command.make('logout', {}, () =>
22
}
23
24
yield* ctx.logout;
25
+
26
yield* ui.log.success('Logged out successfully.');
27
})
28
).pipe(Command.withDescription('Log out from the Composio SDK.'));
ts/packages/cli/src/constants.ts
+27
@@ -5,6 +5,18 @@ const { DEFAULT_BASE_URL, DEFAULT_WEB_URL } = constants;
5
6
export { DEFAULT_BASE_URL, DEFAULT_WEB_URL };
7
8
+/**
9
+ * Staging base URL for the Composio API server (backend).
10
+ * Used when `COMPOSIO_ENVIRONMENT=staging`.
11
+ */
12
+export const STAGING_BASE_URL = 'https://staging-backend.composio.dev';
13
+
14
+/**
15
+ * Staging base URL for the Composio web app (frontend).
16
+ * Used when `COMPOSIO_ENVIRONMENT=staging`.
17
+ */
18
+export const STAGING_WEB_URL = 'https://staging-platform.composio.dev';
19
+
20
/**
21
* Prefix for user environment variable keys used by the Composio CLI.
22
*/
@@ -45,6 +57,21 @@ export const APP_VERSION = pkg.version;
57
*/
58
export const APP_NAME = pkg.name;
59
60
+/**
61
+ * Name of the per-directory project config file.
62
+ */
63
+export const PROJECT_CONFIG_FILE_NAME = 'project.json';
64
+
65
+/**
66
+ * Name of the per-directory .env file for CLI-only config overrides.
67
+ */
68
+export const PROJECT_ENV_FILE_NAME = '.env';
69
+
70
+/**
71
+ * Name of the per-directory Composio config directory.
72
+ */
73
+export const PROJECT_COMPOSIO_DIR = '.composio';
74
+
75
/**
76
* GitHub repository information for release fetching
77
*/
ts/packages/cli/src/effects/app-config.ts
+39
-2
@@ -3,29 +3,66 @@ import * as constants from 'src/constants';
3
4
type APP_CONFIG = Config.Config.Wrap<{
5
API_KEY: Option.Option<string>;
6
+ ENVIRONMENT: Option.Option<string>;
7
BASE_URL: string;
8
WEB_URL: string;
9
CACHE_DIR: Option.Option<string>;
10
LOG_LEVEL: Option.Option<LogLevel.LogLevel>;
11
+ ORG_ID: Option.Option<string>;
12
+ PROJECT_ID: Option.Option<string>;
13
}>;
14
15
+/**
16
+ * Derives a URL default based on the `COMPOSIO_ENVIRONMENT` config key.
17
+ * Returns `stagingDefault` when ENVIRONMENT is `"staging"`, otherwise `prodDefault`.
18
+ */
19
+const environmentBasedDefault = (
20
+ prodDefault: string,
21
+ stagingDefault: string
22
+): Config.Config<string> =>
23
+ Config.string('ENVIRONMENT').pipe(
24
+ Config.map(env => (env === 'staging' ? stagingDefault : prodDefault)),
25
+ Config.withDefault(prodDefault)
26
+ );
27
+
28
/**
29
* Describe every configuration key used at runtime.
30
* Keys are read from environment variables (with the `${APP_ENV_CONFIG_KEY_PREFIX}<key>` format).
31
+ *
32
+ * URL precedence (highest → lowest):
33
+ * COMPOSIO_BASE_URL → COMPOSIO_ENVIRONMENT-derived → DEFAULT_BASE_URL
34
+ * COMPOSIO_WEB_URL → COMPOSIO_ENVIRONMENT-derived → DEFAULT_WEB_URL
35
*/
36
export const APP_CONFIG = {
37
// The API key for the Composio API
38
API_KEY: Config.option(Config.string('API_KEY')),
39
40
+ // The deployment environment ("production" | "staging"). Controls URL defaults.
41
+ ENVIRONMENT: Config.option(Config.string('ENVIRONMENT')),
42
+
43
// The base URL for the Composio API
21
- BASE_URL: Config.string('BASE_URL').pipe(Config.withDefault(constants.DEFAULT_BASE_URL)),
44
+ BASE_URL: Config.string('BASE_URL').pipe(
45
+ Config.orElse(() =>
46
+ environmentBasedDefault(constants.DEFAULT_BASE_URL, constants.STAGING_BASE_URL)
47
+ )
48
+ ),
49
50
// The base URL for the Composio web app
24
- WEB_URL: Config.string('WEB_URL').pipe(Config.withDefault(constants.DEFAULT_WEB_URL)),
51
+ WEB_URL: Config.string('WEB_URL').pipe(
52
+ Config.orElse(() =>
53
+ environmentBasedDefault(constants.DEFAULT_WEB_URL, constants.STAGING_WEB_URL)
54
+ )
55
+ ),
56
57
// The cache directory for the Composio CLI
58
CACHE_DIR: Config.option(Config.string('CACHE_DIR')),
59
60
// The log level for the Composio CLI
61
LOG_LEVEL: Config.option(Config.logLevel('LOG_LEVEL')),
62
+
63
+ // The organization ID for multi-project auth (overrides file-based config)
64
+ ORG_ID: Config.option(Config.string('ORG_ID')),
65
+
66
+ // The project ID for multi-project auth (overrides file-based config)
67
+ PROJECT_ID: Config.option(Config.string('PROJECT_ID')),
68
} satisfies APP_CONFIG;
ts/packages/cli/src/effects/core-dependency.ts
new
+227
@@ -0,0 +1,227 @@
1
+import path from 'node:path';
2
+import { Command, FileSystem } from '@effect/platform';
3
+import { Effect, Match } from 'effect';
4
+import {
5
+ ProjectEnvironmentDetector,
6
+ type JsLanguage,
7
+ type JsPackageManager,
8
+ type PythonPackageManager,
9
+} from 'src/services/project-environment-detector';
10
+import { getAncestors } from 'src/utils/get-ancestors';
11
+
12
+export type CoreDependencyPlan =
13
+ | {
14
+ kind: 'js';
15
+ language: JsLanguage;
16
+ packageManager: JsPackageManager;
17
+ rootDir: string;
18
+ dependency: '@composio/core';
19
+ installCommand: string;
20
+ }
21
+ | {
22
+ kind: 'python';
23
+ language: 'python';
24
+ packageManager: PythonPackageManager;
25
+ rootDir: string;
26
+ dependency: 'composio';
27
+ installCommand: string;
28
+ };
29
+
30
+export type CoreDependencyVersion = {
31
+ version: string;
32
+ source: 'package.json' | 'node_modules' | 'python';
33
+};
34
+
35
+export const getJsInstallCommand = (pm: JsPackageManager, dependency: string) =>
36
+ Match.value(pm).pipe(
37
+ Match.when('pnpm', () => `pnpm add ${dependency}`),
38
+ Match.when('bun', () => `bun add ${dependency}`),
39
+ Match.when('yarn', () => `yarn add ${dependency}`),
40
+ Match.when('npm', () => `npm install -S ${dependency}`),
41
+ Match.when('deno', () => `deno add npm:${dependency}`),
42
+ Match.exhaustive
43
+ );
44
+
45
+export const getPythonInstallCommand = (pm: PythonPackageManager, dependency: string) =>
46
+ pm === 'uv' ? `uv pip install ${dependency}` : `pip install ${dependency}`;
47
+
48
+export const detectCoreDependencyPlan = (cwd: string) =>
49
+ Effect.gen(function* () {
50
+ const envDetector = yield* ProjectEnvironmentDetector;
51
+ const env = yield* envDetector.detectProjectEnvironment(cwd);
52
+
53
+ if (env.kind === 'python') {
54
+ return {
55
+ kind: 'python',
56
+ language: 'python',
57
+ packageManager: env.packageManager,
58
+ rootDir: env.rootDir,
59
+ dependency: 'composio',
60
+ installCommand: getPythonInstallCommand(env.packageManager, 'composio'),
61
+ } satisfies CoreDependencyPlan;
62
+ }
63
+
64
+ return {
65
+ kind: 'js',
66
+ language: env.language,
67
+ packageManager: env.packageManager,
68
+ rootDir: env.rootDir,
69
+ dependency: '@composio/core',
70
+ installCommand: getJsInstallCommand(env.packageManager, '@composio/core'),
71
+ } satisfies CoreDependencyPlan;
72
+ });
73
+
74
+const readPackageJson = (fs: FileSystem.FileSystem, dir: string) =>
75
+ fs.readFileString(path.join(dir, 'package.json')).pipe(
76
+ Effect.andThen(content =>
77
+ Effect.try({
78
+ try: () => JSON.parse(content) as Record<string, unknown>,
79
+ catch: () => null,
80
+ })
81
+ ),
82
+ Effect.catchAll(() => Effect.succeed(null))
83
+ );
84
+
85
+const findDependencySpec = (pkg: Record<string, unknown>, name: string) => {
86
+ const deps = (pkg.dependencies ?? {}) as Record<string, string>;
87
+ const devDeps = (pkg.devDependencies ?? {}) as Record<string, string>;
88
+ const peerDeps = (pkg.peerDependencies ?? {}) as Record<string, string>;
89
+ const optionalDeps = (pkg.optionalDependencies ?? {}) as Record<string, string>;
90
+
91
+ return deps[name] ?? devDeps[name] ?? peerDeps[name] ?? optionalDeps[name] ?? null;
92
+};
93
+
94
+const detectJsDependencyVersion = (
95
+ fs: FileSystem.FileSystem,
96
+ plan: Extract<CoreDependencyPlan, { kind: 'js' }>
97
+) =>
98
+ Effect.gen(function* () {
99
+ const dirs = getAncestors(plan.rootDir);
100
+
101
+ for (const dir of dirs) {
102
+ const packageJsonPath = path.join(dir, 'node_modules', '@composio', 'core', 'package.json');
103
+ const content = yield* fs
104
+ .readFileString(packageJsonPath)
105
+ .pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
106
+
107
+ if (content) {
108
+ const parsed = yield* Effect.try({
109
+ try: () => JSON.parse(content) as { version?: string },
110
+ catch: () => null,
111
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
112
+
113
+ if (parsed?.version) {
114
+ return {
115
+ version: parsed.version,
116
+ source: 'node_modules',
117
+ } satisfies CoreDependencyVersion;
118
+ }
119
+ }
120
+
121
+ if (plan.packageManager === 'pnpm') {
122
+ const pnpmStore = path.join(dir, 'node_modules', '.pnpm');
123
+ const entries = yield* fs
124
+ .readDirectory(pnpmStore)
125
+ .pipe(Effect.catchAll(() => Effect.succeed<string[]>([])));
126
+ const match = entries.find(entry => entry.startsWith('@composio+core@'));
127
+ if (!match) {
128
+ continue;
129
+ }
130
+ const pnpmPkgPath = path.join(
131
+ pnpmStore,
132
+ match,
133
+ 'node_modules',
134
+ '@composio',
135
+ 'core',
136
+ 'package.json'
137
+ );
138
+ const pnpmContent = yield* fs
139
+ .readFileString(pnpmPkgPath)
140
+ .pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
141
+
142
+ if (pnpmContent) {
143
+ const pnpmParsed = yield* Effect.try({
144
+ try: () => JSON.parse(pnpmContent) as { version?: string },
145
+ catch: () => null,
146
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
147
+
148
+ if (pnpmParsed?.version) {
149
+ return {
150
+ version: pnpmParsed.version,
151
+ source: 'node_modules',
152
+ } satisfies CoreDependencyVersion;
153
+ }
154
+ }
155
+ }
156
+ }
157
+
158
+ for (const dir of dirs) {
159
+ const pkg = yield* readPackageJson(fs, dir);
160
+ if (!pkg) {
161
+ continue;
162
+ }
163
+ const spec = findDependencySpec(pkg, plan.dependency);
164
+ if (spec) {
165
+ return {
166
+ version: spec,
167
+ source: 'package.json',
168
+ } satisfies CoreDependencyVersion;
169
+ }
170
+ }
171
+
172
+ return null;
173
+ });
174
+
175
+const detectPythonDependencyVersion = (plan: Extract<CoreDependencyPlan, { kind: 'python' }>) =>
176
+ Effect.gen(function* () {
177
+ const [cmd, ...args] =
178
+ plan.packageManager === 'uv'
179
+ ? [
180
+ 'uv',
181
+ 'run',
182
+ 'python',
183
+ '-c',
184
+ "import importlib.metadata as m; print(m.version('composio'))",
185
+ ]
186
+ : ['python', '-c', "import importlib.metadata as m; print(m.version('composio'))"];
187
+
188
+ const stdout = yield* Command.make(cmd, ...args).pipe(
189
+ Command.string,
190
+ Effect.catchAll(() => Effect.succeed<string | null>(null))
191
+ );
192
+
193
+ if (!stdout) {
194
+ return null;
195
+ }
196
+
197
+ const version = stdout.trim();
198
+ if (!version) {
199
+ return null;
200
+ }
201
+
202
+ return {
203
+ version,
204
+ source: 'python',
205
+ } satisfies CoreDependencyVersion;
206
+ });
207
+
208
+export const detectCoreDependencyVersion = (plan: CoreDependencyPlan) =>
209
+ Effect.gen(function* () {
210
+ if (plan.kind === 'python') {
211
+ return yield* detectPythonDependencyVersion(plan);
212
+ }
213
+
214
+ const fs = yield* FileSystem.FileSystem;
215
+ return yield* detectJsDependencyVersion(fs, plan);
216
+ });
217
+
218
+export const resolveCoreDependencyState = (cwd: string) =>
219
+ Effect.gen(function* () {
220
+ const plan = yield* detectCoreDependencyPlan(cwd);
221
+ const installedVersion = yield* detectCoreDependencyVersion(plan);
222
+
223
+ return {
224
+ plan,
225
+ installedVersion,
226
+ } as const;
227
+ });
ts/packages/cli/src/models/project-keys.ts
new
+54
@@ -0,0 +1,54 @@
1
+import { Schema } from 'effect';
2
+import { OptionFromNullishOr } from 'effect/Schema';
3
+import { JSONTransformSchema } from './utils/json-transform-schema';
4
+
5
+/**
6
+ * Organization and project identifiers for a CLI project profile.
7
+ * Stored in `~/.composio/_keys/<projectId>.json` (global registry)
8
+ * and `<cwd>/.composio/project.json` (per-directory config).
9
+ */
10
+export const ProjectKeys = Schema.Struct({
11
+ /**
12
+ * Organization member ID (maps to `x-org-id` header).
13
+ */
14
+ orgId: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('org_id')),
15
+
16
+ /**
17
+ * Project ID (maps to `x-project-id` header).
18
+ */
19
+ projectId: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('project_id')),
20
+
21
+ /**
22
+ * Human-readable project name from session/info (optional for backward compat).
23
+ */
24
+ projectName: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
25
+ Schema.fromKey('project_name')
26
+ ),
27
+
28
+ /**
29
+ * Human-readable org name from session/info (optional for backward compat).
30
+ */
31
+ orgName: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
32
+ Schema.fromKey('org_name')
33
+ ),
34
+
35
+ /**
36
+ * User email from session/info (optional for backward compat).
37
+ */
38
+ email: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
39
+ Schema.fromKey('email')
40
+ ),
41
+}).annotations({
42
+ identifier: 'ProjectKeys',
43
+ description: 'Organization and project identifiers for a CLI project profile',
44
+});
45
+
46
+export type ProjectKeys = Schema.Schema.Type<typeof ProjectKeys>;
47
+
48
+export const ProjectKeysJSON = JSONTransformSchema(ProjectKeys);
49
+export const projectKeysFromJSON = Schema.decode(ProjectKeysJSON, {
50
+ propertyOrder: 'original',
51
+ onExcessProperty: 'ignore',
52
+ exact: false,
53
+});
54
+export const projectKeysToJSON = Schema.encode(ProjectKeysJSON);
ts/packages/cli/src/models/user-data.ts
+16
@@ -23,6 +23,20 @@ export const UserData = Schema.Struct({
23
webURL: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
24
Schema.fromKey('web_url')
25
),
26
+
27
+ /**
28
+ * Organization ID for the current user.
29
+ */
30
+ orgId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
31
+ Schema.fromKey('org_id')
32
+ ),
33
+
34
+ /**
35
+ * Project ID for the current user.
36
+ */
37
+ projectId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
38
+ Schema.fromKey('project_id')
39
+ ),
40
}).annotations({
41
identifier: 'UserData',
42
description: 'User data storage for the Composio CLI',
@@ -35,6 +49,8 @@ export const UserDataWithDefaults = Schema.Struct({
49
50
baseURL: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('base_url')),
51
webURL: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('web_url')),
52
+
53
+ // orgId and projectId remain as Option<string> — they may not be set.
54
}).annotations({
55
identifier: 'UserDataWithDefaults',
56
description: 'User data storage for the Composio CLI with defaults',
ts/packages/cli/src/services/command-runner.ts
new
+9
@@ -0,0 +1,9 @@
1
+import { Command } from '@effect/platform';
2
+import { Effect } from 'effect';
3
+
4
+export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {
5
+ sync: () => ({
6
+ run: (command: Command.Command) => Command.exitCode(command),
7
+ }),
8
+ dependencies: [],
9
+}) {}
ts/packages/cli/src/services/composio-clients.ts
+219
-3
@@ -336,6 +336,41 @@ export type TriggerInstanceManageDeleteResponse = Schema.Schema.Type<
336
typeof TriggerInstanceManageDeleteResponse
337
>;
338
339
+/**
340
+ * Response from GET /api/v3/auth/session/info.
341
+ * Contains project, org member, and API key details for the authenticated session.
342
+ * Fields like webhook_url, webhook_secret, auto_id, deleted are intentionally omitted.
343
+ */
344
+export const SessionInfoResponse = Schema.Struct({
345
+ project: Schema.Struct({
346
+ name: Schema.String,
347
+ id: Schema.String,
348
+ org_id: Schema.String,
349
+ nano_id: Schema.String,
350
+ email: Schema.String,
351
+ created_at: Schema.String,
352
+ updated_at: Schema.String,
353
+ org: Schema.Struct({
354
+ name: Schema.String,
355
+ id: Schema.String,
356
+ plan: Schema.String,
357
+ }),
358
+ }),
359
+ org_member: Schema.Struct({
360
+ id: Schema.String,
361
+ email: Schema.String,
362
+ name: Schema.String,
363
+ role: Schema.String,
364
+ }),
365
+ api_key: Schema.Struct({
366
+ name: Schema.String,
367
+ project_id: Schema.String,
368
+ id: Schema.String,
369
+ org_member_id: Schema.String,
370
+ }),
371
+}).annotations({ identifier: 'SessionInfoResponse' });
372
+export type SessionInfoResponse = Schema.Schema.Type<typeof SessionInfoResponse>;
373
+
374
export interface TriggerInstancesListActiveParams {
375
user_ids?: string[];
376
connected_account_ids?: string[];
@@ -641,6 +676,179 @@ const streamResponseWithByteCount = (
676
return { json, byteSize };
677
});
678
679
+/**
680
+ * A single project entry returned by GET /api/v3/org/project/list.
681
+ */
682
+export const OrgProject = Schema.Struct({
683
+ id: Schema.String,
684
+ name: Schema.String,
685
+ email: Schema.String,
686
+ deleted: Schema.Boolean,
687
+ org_id: Schema.String,
688
+ created_at: Schema.String,
689
+ updated_at: Schema.String,
690
+}).annotations({ identifier: 'OrgProject' });
691
+export type OrgProject = Schema.Schema.Type<typeof OrgProject>;
692
+
693
+/**
694
+ * Response from GET /api/v3/org/project/list.
695
+ */
696
+export const OrgProjectListResponse = Schema.Struct({
697
+ data: Schema.Array(OrgProject),
698
+ next_cursor: Schema.NullOr(Schema.String),
699
+ total_pages: Schema.Int,
700
+ current_page: Schema.Int,
701
+ total_items: Schema.Int,
702
+}).annotations({ identifier: 'OrgProjectListResponse' });
703
+export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListResponse>;
704
+
705
+/**
706
+ * Lists all projects for the logged-in user's organization.
707
+ * Uses plain fetch since this endpoint is not available in @composio/client.
708
+ *
709
+ * @param params.baseURL - API base URL
710
+ * @param params.apiKey - UAK (sent as `x-user-api-key`)
711
+ * @param params.orgId - Organization ID (sent as `x-composio-org-id`)
712
+ * @param params.projectId - Project ID (sent as `x-composio-project-id`)
713
+ * @param params.limit - Max projects to return (default 100)
714
+ */
715
+export const listOrgProjects = (params: {
716
+ baseURL: string;
717
+ apiKey: string;
718
+ orgId: string;
719
+ projectId: string;
720
+ limit?: number;
721
+}): Effect.Effect<OrgProjectListResponse, HttpServerError | HttpDecodingError> =>
722
+ Effect.gen(function* () {
723
+ const limit = params.limit ?? 100;
724
+ const response = yield* Effect.tryPromise({
725
+ try: () =>
726
+ fetch(
727
+ `${params.baseURL}/api/v3/org/project/list?list_all_org_projects=true&limit=${limit}`,
728
+ {
729
+ method: 'GET',
730
+ redirect: 'error',
731
+ headers: {
732
+ 'x-user-api-key': params.apiKey,
733
+ 'x-composio-org-id': params.orgId,
734
+ 'x-composio-project-id': params.projectId,
735
+ 'User-Agent': '@composio/cli',
736
+ Accept: 'application/json',
737
+ 'Content-Type': 'application/json',
738
+ },
739
+ }
740
+ ),
741
+ catch: error => new HttpServerError({ cause: error }),
742
+ });
743
+
744
+ if (!response.ok) {
745
+ return yield* handleHttpErrorResponse(response);
746
+ }
747
+
748
+ const { json } = yield* streamResponseWithByteCount(response);
749
+
750
+ return yield* pipe(
751
+ Schema.decodeUnknown(OrgProjectListResponse)(json),
752
+ Effect.catchTag('ParseError', e => {
753
+ const message = ParseResult.TreeFormatter.formatErrorSync(e);
754
+ return new HttpDecodingError({
755
+ cause: `ParseError\n ${message}`,
756
+ });
757
+ })
758
+ );
759
+ });
760
+
761
+/**
762
+ * Calls GET /api/v3/auth/session/info with the full layered auth headers.
763
+ * Uses plain fetch since this endpoint is not available in @composio/client.
764
+ * This is a standalone function, NOT on ComposioSessionRepository, to keep
765
+ * the repository as a pure facade over @composio/client.
766
+ */
767
+export const getSessionInfo = (params: {
768
+ baseURL: string;
769
+ apiKey: string;
770
+ orgId: string;
771
+ projectId: string;
772
+}): Effect.Effect<SessionInfoResponse, HttpServerError | HttpDecodingError> =>
773
+ Effect.gen(function* () {
774
+ const response = yield* Effect.tryPromise({
775
+ try: () =>
776
+ fetch(`${params.baseURL}/api/v3/auth/session/info`, {
777
+ method: 'GET',
778
+ redirect: 'error',
779
+ headers: {
780
+ 'x-api-key': params.apiKey,
781
+ 'x-org-id': params.orgId,
782
+ 'x-project-id': params.projectId,
783
+ 'User-Agent': '@composio/cli',
784
+ Accept: '*/*',
785
+ 'Content-Type': 'application/json',
786
+ },
787
+ }),
788
+ catch: error => new HttpServerError({ cause: error }),
789
+ });
790
+
791
+ if (!response.ok) {
792
+ return yield* handleHttpErrorResponse(response);
793
+ }
794
+
795
+ const { json } = yield* streamResponseWithByteCount(response);
796
+
797
+ return yield* pipe(
798
+ Schema.decodeUnknown(SessionInfoResponse)(json),
799
+ Effect.catchTag('ParseError', e => {
800
+ const message = ParseResult.TreeFormatter.formatErrorSync(e);
801
+ return new HttpDecodingError({
802
+ cause: `ParseError\n ${message}`,
803
+ });
804
+ })
805
+ );
806
+ });
807
+
808
+/**
809
+ * Calls GET /api/v3/auth/session/info using only the x-user-api-key header.
810
+ * Unlike getSessionInfo which requires org/project IDs, this variant resolves
811
+ * session metadata from the UAK alone — useful during login before org/project
812
+ * context is known.
813
+ * Uses plain fetch since this endpoint is not available in @composio/client.
814
+ */
815
+export const getSessionInfoByUserApiKey = (params: {
816
+ baseURL: string;
817
+ userApiKey: string;
818
+}): Effect.Effect<SessionInfoResponse, HttpServerError | HttpDecodingError> =>
819
+ Effect.gen(function* () {
820
+ const response = yield* Effect.tryPromise({
821
+ try: () =>
822
+ fetch(`${params.baseURL}/api/v3/auth/session/info`, {
823
+ method: 'GET',
824
+ redirect: 'error',
825
+ headers: {
826
+ 'x-user-api-key': params.userApiKey,
827
+ 'User-Agent': '@composio/cli',
828
+ Accept: '*/*',
829
+ 'Content-Type': 'application/json',
830
+ },
831
+ }),
832
+ catch: error => new HttpServerError({ cause: error }),
833
+ });
834
+
835
+ if (!response.ok) {
836
+ return yield* handleHttpErrorResponse(response);
837
+ }
838
+
839
+ const { json } = yield* streamResponseWithByteCount(response);
840
+
841
+ return yield* pipe(
842
+ Schema.decodeUnknown(SessionInfoResponse)(json),
843
+ Effect.catchTag('ParseError', e => {
844
+ const message = ParseResult.TreeFormatter.formatErrorSync(e);
845
+ return new HttpDecodingError({
846
+ cause: `ParseError\n ${message}`,
847
+ });
848
+ })
849
+ );
850
+ });
851
+
852
// Utility function for calling the Composio API and decoding its response.
853
// eslint-disable-next-line @typescript-eslint/no-explicit-any
854
const callClient = <T, S extends Schema.Schema<any, any>>(
@@ -1235,12 +1443,19 @@ export class ComposioClientLive extends Effect.Service<ComposioClientLive>()(
1443
cli: {
1444
/**
1445
* Generates a new CLI session with a random 6-character code.
1446
+ * @param params.scope - 'user' for login, 'project' for init (future)
1447
+ *
1448
+ * TODO: don't use `@composio/client`, wrap `fetch` directly.
1449
*/
1239
- createSession: () =>
1450
+ createSession: (params?: { scope?: 'user' | 'project' }) =>
1451
withMetrics(
1452
callClient(
1453
clientSingleton,
1243
- client => client.cli.createSession(),
1454
+ client =>
1455
+ client.cli.createSession(
1456
+ { scope: params?.scope ?? 'user' },
1457
+ { headers: { 'Content-Type': 'application/json' } }
1458
+ ),
1459
CliCreateSessionResponse
1460
)
1461
),
@@ -1541,7 +1756,8 @@ export class ComposioSessionRepository extends Effect.Service<ComposioSessionRep
1756
const client = yield* ComposioClientLive;
1757
1758
return {
1544
- createSession: () => client.cli.createSession(),
1759
+ createSession: (params?: { scope?: 'user' | 'project' }) =>
1760
+ client.cli.createSession(params),
1761
getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
1762
getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
1763
authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
ts/packages/cli/src/services/project-context.ts
new
+153
@@ -0,0 +1,153 @@
1
+import path from 'node:path';
2
+import { Effect, Option } from 'effect';
3
+import { FileSystem } from '@effect/platform';
4
+import { NodeOs } from 'src/services/node-os';
5
+import { NodeProcess } from 'src/services/node-process';
6
+import { APP_CONFIG } from 'src/effects/app-config';
7
+import * as constants from 'src/constants';
8
+import { type ProjectKeys, projectKeysFromJSON } from 'src/models/project-keys';
9
+import type { PlatformError } from '@effect/platform/Error';
10
+import type { ParseError } from 'effect/ParseResult';
11
+
12
+/**
13
+ * Keys allowed in `.composio/.env` files.
14
+ * Only project context keys are permitted -- NOT API_KEY or BASE_URL,
15
+ * to prevent credential injection via malicious repo clones.
16
+ */
17
+const ALLOWED_ENV_KEYS = new Set(['COMPOSIO_ORG_ID', 'COMPOSIO_PROJECT_ID']);
18
+
19
+/**
20
+ * Parse a `.env` file into a key-value map.
21
+ * Only keys in the ALLOWED_ENV_KEYS set are returned.
22
+ */
23
+const parseEnvFile = (content: string): Map<string, string> => {
24
+ const result = new Map<string, string>();
25
+ for (const line of content.split('\n')) {
26
+ const trimmed = line.trim();
27
+ if (trimmed === '' || trimmed.startsWith('#')) continue;
28
+ const eqIndex = trimmed.indexOf('=');
29
+ if (eqIndex === -1) continue;
30
+ const key = trimmed.slice(0, eqIndex).trim();
31
+ let value = trimmed.slice(eqIndex + 1).trim();
32
+ // Strip surrounding quotes (single or double) consistent with dotenv convention
33
+ if (
34
+ (value.startsWith('"') && value.endsWith('"')) ||
35
+ (value.startsWith("'") && value.endsWith("'"))
36
+ ) {
37
+ value = value.slice(1, -1);
38
+ }
39
+ if (ALLOWED_ENV_KEYS.has(key)) {
40
+ result.set(key, value);
41
+ }
42
+ }
43
+ return result;
44
+};
45
+
46
+/**
47
+ * Service that resolves the current project context using a precedence chain.
48
+ * Read-only -- it does NOT write files.
49
+ *
50
+ * Precedence (highest first):
51
+ * 1. System env vars (COMPOSIO_ORG_ID, COMPOSIO_PROJECT_ID)
52
+ * 2. Per-directory .composio/.env (only allowed keys)
53
+ * 3. Per-directory .composio/project.json (walk up from CWD, stop at homedir)
54
+ */
55
+export class ProjectContext extends Effect.Service<ProjectContext>()('services/ProjectContext', {
56
+ effect: Effect.gen(function* () {
57
+ const fs = yield* FileSystem.FileSystem;
58
+ const proc = yield* NodeProcess;
59
+ const os = yield* NodeOs;
60
+
61
+ return {
62
+ /**
63
+ * Resolves the current org+project context.
64
+ * Returns Option.none() if no context is configured.
65
+ */
66
+ resolve: Effect.gen(function* () {
67
+ // 1. Check env vars (highest priority)
68
+ const envOrgId = yield* APP_CONFIG.ORG_ID;
69
+ const envProjectId = yield* APP_CONFIG.PROJECT_ID;
70
+ if (Option.isSome(envOrgId) && Option.isSome(envProjectId)) {
71
+ yield* Effect.logDebug('ProjectContext: resolved from env vars');
72
+ return Option.some<ProjectKeys>({
73
+ orgId: envOrgId.value,
74
+ projectId: envProjectId.value,
75
+ projectName: Option.none(),
76
+ orgName: Option.none(),
77
+ email: Option.none(),
78
+ });
79
+ }
80
+
81
+ // 2. Walk up from CWD, stop at homedir (not filesystem root)
82
+ let dir = proc.cwd;
83
+ const stopAt = os.homedir;
84
+
85
+ while (true) {
86
+ const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);
87
+
88
+ // 2a. Check .composio/.env
89
+ const envFilePath = path.join(composioDir, constants.PROJECT_ENV_FILE_NAME);
90
+ const envExists = yield* fs
91
+ .exists(envFilePath)
92
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
93
+ if (envExists) {
94
+ const envContent = yield* fs
95
+ .readFileString(envFilePath)
96
+ .pipe(Effect.catchAll(() => Effect.succeed('')));
97
+ const envMap = parseEnvFile(envContent);
98
+ const envFileOrgId = envMap.get('COMPOSIO_ORG_ID');
99
+ const envFileProjectId = envMap.get('COMPOSIO_PROJECT_ID');
100
+ if (envFileOrgId && envFileProjectId) {
101
+ yield* Effect.logDebug(`ProjectContext: resolved from ${envFilePath}`);
102
+ return Option.some<ProjectKeys>({
103
+ orgId: envFileOrgId,
104
+ projectId: envFileProjectId,
105
+ projectName: Option.none(),
106
+ orgName: Option.none(),
107
+ email: Option.none(),
108
+ });
109
+ }
110
+ }
111
+
112
+ // 2b. Check .composio/project.json
113
+ const projectJsonPath = path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME);
114
+ const jsonExists = yield* fs
115
+ .exists(projectJsonPath)
116
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
117
+ if (jsonExists) {
118
+ const content = yield* fs
119
+ .readFileString(projectJsonPath)
120
+ .pipe(Effect.catchAll(() => Effect.succeed('')));
121
+ if (content) {
122
+ const keysOpt = yield* projectKeysFromJSON(content).pipe(
123
+ Effect.map(Option.some),
124
+ Effect.catchAll(error =>
125
+ Effect.gen(function* () {
126
+ yield* Effect.logDebug(
127
+ `ProjectContext: corrupt project.json at ${projectJsonPath}, skipping:`,
128
+ error
129
+ );
130
+ return Option.none();
131
+ })
132
+ )
133
+ );
134
+ if (Option.isSome(keysOpt)) {
135
+ yield* Effect.logDebug(`ProjectContext: resolved from ${projectJsonPath}`);
136
+ return keysOpt;
137
+ }
138
+ }
139
+ }
140
+
141
+ // Stop at homedir to avoid reading from system directories
142
+ if (dir === stopAt || dir === path.dirname(dir)) break;
143
+ dir = path.dirname(dir);
144
+ }
145
+
146
+ // 3. Nothing found
147
+ yield* Effect.logDebug('ProjectContext: no context found');
148
+ return Option.none<ProjectKeys>();
149
+ }),
150
+ };
151
+ }),
152
+ dependencies: [],
153
+}) {}
ts/packages/cli/src/services/project-environment-detector.ts
new
+564
@@ -0,0 +1,564 @@
1
+import { BunFileSystem } from '@effect/platform-bun';
2
+import { FileSystem } from '@effect/platform';
3
+import { Data, Effect, Match } from 'effect';
4
+import * as path from 'node:path';
5
+import process from 'node:process';
6
+import { getAncestors } from 'src/utils/get-ancestors';
7
+
8
+const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));
9
+
10
+export type JsLanguage = 'typescript' | 'javascript';
11
+export type JsPackageManager = 'pnpm' | 'bun' | 'yarn' | 'npm' | 'deno';
12
+export type PythonPackageManager = 'uv' | 'pip';
13
+
14
+export type ProjectEnvironment =
15
+ | {
16
+ kind: 'js';
17
+ language: JsLanguage;
18
+ packageManager: JsPackageManager;
19
+ rootDir: string;
20
+ evidence: string[];
21
+ }
22
+ | {
23
+ kind: 'python';
24
+ language: 'python';
25
+ packageManager: PythonPackageManager;
26
+ rootDir: string;
27
+ evidence: string[];
28
+ };
29
+
30
+export class ProjectEnvironmentDetectorError extends Data.TaggedError(
31
+ 'services/ProjectEnvironmentDetectorError'
32
+)<{
33
+ readonly cause: Error;
34
+ readonly message: string;
35
+ readonly checkedPaths: string[];
36
+ readonly details?: string;
37
+}> {}
38
+
39
+// ---------------------------------------------------------------------------
40
+// Constants
41
+// ---------------------------------------------------------------------------
42
+
43
+const JS_LOCK_FILES: Record<JsPackageManager, string[]> = {
44
+ pnpm: ['pnpm-lock.yaml', 'pnpm-workspace.yaml'],
45
+ bun: ['bun.lockb', 'bun.lock'],
46
+ yarn: ['yarn.lock'],
47
+ npm: ['package-lock.json', 'npm-shrinkwrap.json'],
48
+ deno: ['deno.lock', 'deno.lock.json'],
49
+};
50
+
51
+const PYTHON_INDICATORS = new Set([
52
+ 'pyproject.toml',
53
+ 'setup.py',
54
+ 'setup.cfg',
55
+ 'requirements.txt',
56
+ 'requirements-dev.txt',
57
+ 'requirements.in',
58
+ 'pipfile',
59
+ 'pipfile.lock',
60
+ 'poetry.lock',
61
+ 'uv.lock',
62
+ 'environment.yml',
63
+ 'conda.yaml',
64
+ 'tox.ini',
65
+ 'pytest.ini',
66
+]);
67
+
68
+const JS_CONFIG_FILES = new Set(['jsconfig.json', 'deno.json', 'deno.jsonc']);
69
+
70
+const COMMON_SOURCE_DIRS = ['src', 'lib', 'app', 'apps', 'packages', 'scripts'];
71
+
72
+// ---------------------------------------------------------------------------
73
+// Internal types
74
+// ---------------------------------------------------------------------------
75
+
76
+type DirEvidence = {
77
+ dir: string;
78
+ jsScore: number;
79
+ tsScore: number;
80
+ pyScore: number;
81
+ strongJs: boolean;
82
+ strongPy: boolean;
83
+ jsHints: {
84
+ tsConfig: boolean;
85
+ tsDependency: boolean;
86
+ tsFiles: boolean;
87
+ jsFiles: boolean;
88
+ denoConfig: boolean;
89
+ };
90
+ evidence: string[];
91
+};
92
+
93
+// ---------------------------------------------------------------------------
94
+// Pure helpers (no dependencies)
95
+// ---------------------------------------------------------------------------
96
+
97
+const isTsConfig = (name: string) => {
98
+ const lower = name.toLowerCase();
99
+ return lower === 'tsconfig.json' || (lower.startsWith('tsconfig.') && lower.endsWith('.json'));
100
+};
101
+
102
+const countExtensions = (files: string[]) => {
103
+ let ts = 0;
104
+ let js = 0;
105
+ let py = 0;
106
+
107
+ for (const file of files) {
108
+ const ext = path.extname(file).toLowerCase();
109
+ if (ext === '.ts' || ext === '.tsx' || ext === '.mts' || ext === '.cts') {
110
+ ts += 1;
111
+ } else if (ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {
112
+ js += 1;
113
+ } else if (ext === '.py' || ext === '.pyi' || ext === '.pyw' || ext === '.pyx') {
114
+ py += 1;
115
+ }
116
+ }
117
+
118
+ return { ts, js, py };
119
+};
120
+
121
+const chooseJsLanguage = (evidence: DirEvidence): JsLanguage => {
122
+ if (evidence.tsScore > evidence.jsScore) return 'typescript';
123
+ if (evidence.jsScore > evidence.tsScore) return 'javascript';
124
+ if (evidence.jsHints.tsConfig || evidence.jsHints.tsDependency) return 'typescript';
125
+ if (evidence.jsHints.tsFiles && !evidence.jsHints.jsFiles) return 'typescript';
126
+ if (evidence.jsHints.jsFiles && !evidence.jsHints.tsFiles) return 'javascript';
127
+ if (evidence.jsHints.denoConfig) return 'typescript';
128
+ return 'javascript';
129
+};
130
+
131
+const pickBestWeak = (candidate: DirEvidence, depth: number) => {
132
+ const bestScore = Math.max(candidate.tsScore, candidate.jsScore, candidate.pyScore);
133
+ if (bestScore <= 0) return null;
134
+ const language =
135
+ candidate.pyScore >= candidate.tsScore && candidate.pyScore >= candidate.jsScore
136
+ ? 'python'
137
+ : chooseJsLanguage(candidate);
138
+ return {
139
+ dir: candidate.dir,
140
+ depth,
141
+ language,
142
+ score: bestScore - depth * 0.5,
143
+ evidence: candidate,
144
+ } as const;
145
+};
146
+
147
+const parsePackageManagerField = (pm: string) =>
148
+ Match.value(pm).pipe(
149
+ Match.when(
150
+ pm => pm.startsWith('pnpm@'),
151
+ () => 'pnpm' as const
152
+ ),
153
+ Match.when(
154
+ pm => pm.startsWith('bun@'),
155
+ () => 'bun' as const
156
+ ),
157
+ Match.when(
158
+ pm => pm.startsWith('yarn@'),
159
+ () => 'yarn' as const
160
+ ),
161
+ Match.when(
162
+ pm => pm.startsWith('npm@'),
163
+ () => 'npm' as const
164
+ ),
165
+ Match.orElse(() => null)
166
+ );
167
+
168
+/**
169
+ * Detect package manager from the `npm_config_user_agent` env var.
170
+ * Set automatically when running via `npx`, `pnpm dlx`, `bunx`, etc.
171
+ * Inspired by https://github.com/prisma/create-prisma/blob/main/src/utils/package-manager.ts
172
+ */
173
+const parseUserAgent = (userAgent: string | undefined): JsPackageManager | null => {
174
+ if (!userAgent) return null;
175
+ if (userAgent.startsWith('pnpm')) return 'pnpm';
176
+ if (userAgent.startsWith('bun')) return 'bun';
177
+ if (userAgent.startsWith('yarn')) return 'yarn';
178
+ if (userAgent.startsWith('npm')) return 'npm';
179
+ return null;
180
+};
181
+
182
+// ---------------------------------------------------------------------------
183
+// FS helpers (take FileSystem as parameter)
184
+// ---------------------------------------------------------------------------
185
+
186
+const makeReadDirectoryOptional = (fs: FileSystem.FileSystem) => (dir: string) =>
187
+ fs.readDirectory(dir).pipe(Effect.catchAll(() => Effect.succeed<string[]>([])));
188
+
189
+const makeReadFileStringOptional = (fs: FileSystem.FileSystem) => (filePath: string) =>
190
+ fs.readFileString(filePath).pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
191
+
192
+const makeReadPackageJson = (fs: FileSystem.FileSystem) => {
193
+ const readFileStringOptional = makeReadFileStringOptional(fs);
194
+ return (dir: string) =>
195
+ Effect.gen(function* () {
196
+ const content = yield* readFileStringOptional(path.join(dir, 'package.json'));
197
+ if (!content) return null;
198
+ return yield* Effect.try({
199
+ try: () => JSON.parse(content) as Record<string, unknown>,
200
+ catch: toError,
201
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
202
+ });
203
+};
204
+
205
+// ---------------------------------------------------------------------------
206
+// Analysis (split into focused functions)
207
+// ---------------------------------------------------------------------------
208
+
209
+const analyzeDirectory = (
210
+ fs: FileSystem.FileSystem,
211
+ dir: string
212
+): Effect.Effect<DirEvidence, ProjectEnvironmentDetectorError> =>
213
+ Effect.gen(function* () {
214
+ const files = yield* fs.readDirectory(dir).pipe(
215
+ Effect.mapError(
216
+ e =>
217
+ new ProjectEnvironmentDetectorError({
218
+ cause: toError(e),
219
+ message: `Failed to read directory ${dir}`,
220
+ checkedPaths: [dir],
221
+ })
222
+ )
223
+ );
224
+ const readDirectoryOptional = makeReadDirectoryOptional(fs);
225
+ const readFileStringOptional = makeReadFileStringOptional(fs);
226
+ const readPackageJson = makeReadPackageJson(fs);
227
+
228
+ const lowerFiles = files.map(file => file.toLowerCase());
229
+ const fileSet = new Set(lowerFiles);
230
+ const fileByLower = new Map<string, string>();
231
+ for (const file of files) {
232
+ const lower = file.toLowerCase();
233
+ if (!fileByLower.has(lower)) fileByLower.set(lower, file);
234
+ }
235
+
236
+ let jsScore = 0;
237
+ let tsScore = 0;
238
+ let pyScore = 0;
239
+ let strongJs = false;
240
+ let strongPy = false;
241
+ const evidence: string[] = [];
242
+ const jsHints = {
243
+ tsConfig: false,
244
+ tsDependency: false,
245
+ tsFiles: false,
246
+ jsFiles: false,
247
+ denoConfig: false,
248
+ };
249
+
250
+ // Score file indicators
251
+ for (const file of lowerFiles) {
252
+ if (file === 'package.json') {
253
+ strongJs = true;
254
+ jsScore += 3;
255
+ evidence.push('package.json');
256
+ }
257
+ if (JS_CONFIG_FILES.has(file)) {
258
+ strongJs = true;
259
+ jsScore += 3;
260
+ if (file === 'deno.json' || file === 'deno.jsonc') {
261
+ jsHints.denoConfig = true;
262
+ tsScore += 2;
263
+ evidence.push(file);
264
+ }
265
+ }
266
+ if (isTsConfig(file)) {
267
+ strongJs = true;
268
+ tsScore += 5;
269
+ jsHints.tsConfig = true;
270
+ evidence.push('tsconfig');
271
+ }
272
+ if (file === 'jsconfig.json') {
273
+ strongJs = true;
274
+ jsScore += 4;
275
+ evidence.push('jsconfig.json');
276
+ }
277
+ if (file === 'pnpm-workspace.yaml') {
278
+ strongJs = true;
279
+ jsScore += 3;
280
+ evidence.push('pnpm-workspace.yaml');
281
+ }
282
+ if (PYTHON_INDICATORS.has(file)) {
283
+ strongPy = true;
284
+ pyScore += 3;
285
+ evidence.push(file);
286
+ if (file === 'uv.lock') pyScore += 2;
287
+ }
288
+ }
289
+
290
+ // Score JS lock files
291
+ for (const [, lockFiles] of Object.entries(JS_LOCK_FILES)) {
292
+ if (lockFiles.some(lf => fileSet.has(lf))) {
293
+ strongJs = true;
294
+ jsScore += 4;
295
+ evidence.push(lockFiles.find(lf => fileSet.has(lf)) ?? lockFiles[0]);
296
+ }
297
+ }
298
+
299
+ // Score from package.json content
300
+ const packageJson = yield* readPackageJson(dir);
301
+ if (packageJson) {
302
+ const deps = (packageJson.dependencies ?? {}) as Record<string, string>;
303
+ const devDeps = (packageJson.devDependencies ?? {}) as Record<string, string>;
304
+ if ({ ...deps, ...devDeps }.typescript) {
305
+ tsScore += 4;
306
+ jsHints.tsDependency = true;
307
+ evidence.push('typescript dependency');
308
+ }
309
+ const pm =
310
+ typeof packageJson.packageManager === 'string'
311
+ ? parsePackageManagerField(packageJson.packageManager)
312
+ : null;
313
+ if (pm) {
314
+ jsScore += 2;
315
+ strongJs = true;
316
+ evidence.push(`packageManager:${pm}`);
317
+ }
318
+ }
319
+
320
+ // Score from pyproject.toml content
321
+ const pyProject = yield* readFileStringOptional(path.join(dir, 'pyproject.toml'));
322
+ if (pyProject) {
323
+ const hasPythonSections = [
324
+ '[project]',
325
+ '[tool.poetry]',
326
+ '[tool.setuptools]',
327
+ '[tool.uv]',
328
+ '[build-system]',
329
+ ].some(s => pyProject.includes(s));
330
+ if (hasPythonSections) {
331
+ strongPy = true;
332
+ pyScore += 2;
333
+ }
334
+ }
335
+
336
+ // Score from file extensions
337
+ const extensionCounts = countExtensions(files);
338
+ if (extensionCounts.ts > 0) {
339
+ tsScore += Math.min(3, extensionCounts.ts);
340
+ jsHints.tsFiles = true;
341
+ }
342
+ if (extensionCounts.js > 0) {
343
+ jsScore += Math.min(3, extensionCounts.js);
344
+ jsHints.jsFiles = true;
345
+ }
346
+ if (extensionCounts.py > 0) {
347
+ pyScore += Math.min(3, extensionCounts.py);
348
+ }
349
+
350
+ // Score from subdirectory extensions
351
+ for (const subdir of COMMON_SOURCE_DIRS) {
352
+ if (!fileSet.has(subdir)) continue;
353
+ const actualSubdir = fileByLower.get(subdir) ?? subdir;
354
+ const subFiles = yield* readDirectoryOptional(path.join(dir, actualSubdir));
355
+ const subCounts = countExtensions(subFiles);
356
+ if (subCounts.ts > 0) {
357
+ tsScore += Math.min(2, subCounts.ts);
358
+ jsHints.tsFiles = true;
359
+ }
360
+ if (subCounts.js > 0) {
361
+ jsScore += Math.min(2, subCounts.js);
362
+ jsHints.jsFiles = true;
363
+ }
364
+ if (subCounts.py > 0) {
365
+ pyScore += Math.min(2, subCounts.py);
366
+ }
367
+ }
368
+
369
+ return {
370
+ dir,
371
+ jsScore,
372
+ tsScore,
373
+ pyScore,
374
+ strongJs,
375
+ strongPy,
376
+ jsHints,
377
+ evidence,
378
+ } satisfies DirEvidence;
379
+ });
380
+
381
+// ---------------------------------------------------------------------------
382
+// Detection functions
383
+// ---------------------------------------------------------------------------
384
+
385
+const detectLanguage = (fs: FileSystem.FileSystem, cwd: string) =>
386
+ Effect.gen(function* () {
387
+ const dirs = getAncestors(cwd);
388
+ let bestWeak: ReturnType<typeof pickBestWeak> | null = null;
389
+ let ambiguous: { dir: string; details: string } | null = null;
390
+
391
+ for (const [depth, dir] of dirs.entries()) {
392
+ const evidence = yield* analyzeDirectory(fs, dir);
393
+
394
+ if (evidence.strongJs && evidence.strongPy) {
395
+ if (depth === 0) {
396
+ return yield* Effect.fail(
397
+ new ProjectEnvironmentDetectorError({
398
+ cause: new Error('Ambiguous project language'),
399
+ message: `Detected both JavaScript/TypeScript and Python indicators in ${dir}`,
400
+ details: `Indicators: ${evidence.evidence.join(', ')}`,
401
+ checkedPaths: dirs,
402
+ })
403
+ );
404
+ }
405
+ if (!ambiguous) ambiguous = { dir, details: `Indicators: ${evidence.evidence.join(', ')}` };
406
+ continue;
407
+ }
408
+
409
+ if (evidence.strongJs)
410
+ return { language: chooseJsLanguage(evidence), rootDir: dir, evidence } as const;
411
+ if (evidence.strongPy)
412
+ return { language: 'python' as const, rootDir: dir, evidence } as const;
413
+
414
+ const weakCandidate = pickBestWeak(evidence, depth);
415
+ if (weakCandidate && (!bestWeak || weakCandidate.score > bestWeak.score))
416
+ bestWeak = weakCandidate;
417
+ }
418
+
419
+ if (bestWeak)
420
+ return {
421
+ language: bestWeak.language,
422
+ rootDir: bestWeak.dir,
423
+ evidence: bestWeak.evidence,
424
+ } as const;
425
+
426
+ if (ambiguous) {
427
+ return yield* Effect.fail(
428
+ new ProjectEnvironmentDetectorError({
429
+ cause: new Error('Ambiguous project language'),
430
+ message: `Detected both JavaScript/TypeScript and Python indicators in ${ambiguous.dir}`,
431
+ details: ambiguous.details,
432
+ checkedPaths: dirs,
433
+ })
434
+ );
435
+ }
436
+
437
+ return yield* Effect.fail(
438
+ new ProjectEnvironmentDetectorError({
439
+ cause: new Error('No project language detected'),
440
+ message: `No recognizable JavaScript/TypeScript or Python project indicators found in ${cwd}`,
441
+ checkedPaths: dirs,
442
+ })
443
+ );
444
+ });
445
+
446
+const detectJsPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
447
+ Effect.gen(function* () {
448
+ const readDirectoryOptional = makeReadDirectoryOptional(fs);
449
+ const readPackageJson = makeReadPackageJson(fs);
450
+ const dirs = getAncestors(cwd);
451
+
452
+ for (const dir of dirs) {
453
+ const files = yield* readDirectoryOptional(dir);
454
+ const fileSet = new Set(files.map(f => f.toLowerCase()));
455
+
456
+ if (fileSet.has('package.json')) {
457
+ const pkg = yield* readPackageJson(dir);
458
+ if (pkg && typeof pkg.packageManager === 'string') {
459
+ const pm = parsePackageManagerField(pkg.packageManager);
460
+ if (pm) return pm;
461
+ }
462
+ }
463
+
464
+ if (fileSet.has('deno.json') || fileSet.has('deno.jsonc') || fileSet.has('deno.lock'))
465
+ return 'deno' as const;
466
+
467
+ for (const pm of ['pnpm', 'bun', 'yarn', 'npm'] as const) {
468
+ if (JS_LOCK_FILES[pm].some(lf => fileSet.has(lf))) return pm;
469
+ }
470
+
471
+ if (fileSet.has('pnpm-workspace.yaml')) return 'pnpm' as const;
472
+ }
473
+
474
+ const userAgent = parseUserAgent(process.env.npm_config_user_agent);
475
+ if (userAgent) return userAgent;
476
+
477
+ return 'npm' as const;
478
+ });
479
+
480
+const detectPythonPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
481
+ Effect.gen(function* () {
482
+ const readDirectoryOptional = makeReadDirectoryOptional(fs);
483
+ const readFileStringOptional = makeReadFileStringOptional(fs);
484
+ const dirs = getAncestors(cwd);
485
+ let fallback: PythonPackageManager | null = null;
486
+
487
+ for (const dir of dirs) {
488
+ const files = yield* readDirectoryOptional(dir);
489
+ const fileSet = new Set(files.map(f => f.toLowerCase()));
490
+
491
+ if (fileSet.has('uv.lock')) return 'uv' as const;
492
+
493
+ if (fileSet.has('pyproject.toml')) {
494
+ const content = yield* readFileStringOptional(path.join(dir, 'pyproject.toml'));
495
+ if (content?.includes('[tool.uv]')) return 'uv' as const;
496
+ }
497
+
498
+ if (
499
+ [
500
+ 'requirements.txt',
501
+ 'requirements-dev.txt',
502
+ 'requirements.in',
503
+ 'setup.py',
504
+ 'setup.cfg',
505
+ 'pipfile',
506
+ 'pipfile.lock',
507
+ 'poetry.lock',
508
+ 'environment.yml',
509
+ 'conda.yaml',
510
+ ].some(f => fileSet.has(f))
511
+ ) {
512
+ fallback = 'pip';
513
+ }
514
+ }
515
+
516
+ return fallback ?? 'pip';
517
+ });
518
+
519
+// ---------------------------------------------------------------------------
520
+// Service
521
+// ---------------------------------------------------------------------------
522
+
523
+export class ProjectEnvironmentDetector extends Effect.Service<ProjectEnvironmentDetector>()(
524
+ 'services/ProjectEnvironmentDetector',
525
+ {
526
+ effect: Effect.gen(function* () {
527
+ const fs = yield* FileSystem.FileSystem;
528
+
529
+ const detectProjectEnvironment = (
530
+ cwd: string
531
+ ): Effect.Effect<ProjectEnvironment, ProjectEnvironmentDetectorError> =>
532
+ Effect.gen(function* () {
533
+ const detection = yield* detectLanguage(fs, cwd);
534
+
535
+ if (detection.language === 'python') {
536
+ const packageManager = yield* detectPythonPackageManager(fs, detection.rootDir);
537
+ return {
538
+ kind: 'python',
539
+ language: 'python',
540
+ packageManager,
541
+ rootDir: detection.rootDir,
542
+ evidence: detection.evidence.evidence,
543
+ } satisfies ProjectEnvironment;
544
+ }
545
+
546
+ const packageManager = yield* detectJsPackageManager(fs, detection.rootDir);
547
+ return {
548
+ kind: 'js',
549
+ language: detection.language,
550
+ packageManager,
551
+ rootDir: detection.rootDir,
552
+ evidence: detection.evidence.evidence,
553
+ } satisfies ProjectEnvironment;
554
+ });
555
+
556
+ return {
557
+ detectProjectEnvironment,
558
+ detectJsPackageManager: (cwd: string) => detectJsPackageManager(fs, cwd),
559
+ detectPythonPackageManager: (cwd: string) => detectPythonPackageManager(fs, cwd),
560
+ };
561
+ }),
562
+ dependencies: [BunFileSystem.layer],
563
+ }
564
+) {}
ts/packages/cli/src/services/terminal-ui.ts
+31
@@ -78,6 +78,19 @@ export interface TerminalUI {
78
options?: { readonly defaultValue?: boolean }
79
) => Effect.Effect<boolean>;
80
81
+ /**
82
+ * Present a single-select list to the user.
83
+ * In non-interactive mode (piped), returns the first option's value.
84
+ */
85
+ readonly select: <Value>(
86
+ message: string,
87
+ options: ReadonlyArray<{
88
+ readonly value: Value;
89
+ readonly label: string;
90
+ readonly hint?: string;
91
+ }>
92
+ ) => Effect.Effect<Value>;
93
+
94
/**
95
* Create a controllable spinner that is automatically stopped on error or interruption.
96
* The `use` function receives a SpinnerHandle and must return an Effect.
@@ -170,6 +183,24 @@ const makeLive: TerminalUI = {
183
decorate(() => p.note(message, title ?? '', { format: line => line, output: process.stderr }))
184
),
185
186
+ select: ((
187
+ message: string,
188
+ options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>
189
+ ) =>
190
+ isInteractive
191
+ ? Effect.promise(async () => {
192
+ const result = await p.select({
193
+ message,
194
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
195
+ options: [...options] as any,
196
+ output: process.stderr,
197
+ });
198
+ // p.select returns Value | symbol (symbol on cancel)
199
+ if (typeof result === 'symbol') return options[0].value;
200
+ return result;
201
+ })
202
+ : Effect.succeed(options[0].value)) as TerminalUI['select'],
203
+
204
confirm: (message, options) =>
205
isInteractive
206
? Effect.promise(async () => {
ts/packages/cli/src/services/user-context.ts
+38
-6
@@ -29,9 +29,13 @@ export class ComposioUserContext extends Context.Tag('ComposioUserData')<
29
logout: Effect.Effect<void, ParseError | PlatformError, never>;
30
31
/**
32
- * Logs in the user by setting the API key.
32
+ * Logs in the user by setting the API key, and optionally org/project IDs.
33
*/
34
- login: (apiKey: string) => Effect.Effect<void, ParseError | PlatformError, never>;
34
+ login: (
35
+ apiKey: string,
36
+ orgId?: string,
37
+ projectId?: string
38
+ ) => Effect.Effect<void, ParseError | PlatformError, never>;
39
40
/**
41
* Saves the user data to a persistent store, e.g., file or database.
@@ -58,15 +62,29 @@ export const ComposioUserContextLive = Layer.effect(
62
apiKey,
63
baseURL: Option.some(baseURL),
64
webURL: Option.some(webURL),
65
+ orgId: Option.none(),
66
+ projectId: Option.none(),
67
});
68
69
const logout = Effect.gen(function* () {
64
- yield* update({ apiKey: Option.none(), baseURL: Option.none(), webURL: Option.some(webURL) });
70
+ yield* update({
71
+ apiKey: Option.none(),
72
+ baseURL: Option.none(),
73
+ webURL: Option.some(webURL),
74
+ orgId: Option.none(),
75
+ projectId: Option.none(),
76
+ });
77
});
78
67
- const login = (apiKey: string) =>
79
+ const login = (apiKey: string, orgId?: string, projectId?: string) =>
80
Effect.gen(function* () {
69
- yield* update({ apiKey: Option.some(apiKey) });
81
+ yield* update({
82
+ apiKey: Option.some(apiKey),
83
+ baseURL: Option.some(baseURL),
84
+ webURL: Option.some(webURL),
85
+ orgId: Option.fromNullable(orgId),
86
+ projectId: Option.fromNullable(projectId),
87
+ });
88
});
89
90
/**
@@ -97,6 +115,8 @@ export const ComposioUserContextLive = Layer.effect(
115
apiKey: apiKey.pipe(Option.orElse(() => parsedUserData.apiKey)),
116
baseURL: Option.some(baseURL),
117
webURL: Option.some(webURL),
118
+ orgId: parsedUserData.orgId,
119
+ projectId: parsedUserData.projectId,
120
} satisfies UserData;
121
122
yield* Effect.logDebug('User data (overridden from env vars):', overriddenUserData);
@@ -107,7 +127,17 @@ export const ComposioUserContextLive = Layer.effect(
127
128
if (yield* fs.exists(jsonUserConfigPath)) {
129
yield* Effect.logDebug('User data file exists, loading it');
110
- yield* load;
130
+ yield* load.pipe(
131
+ Effect.catchAll(error =>
132
+ Effect.gen(function* () {
133
+ yield* Effect.logDebug(
134
+ 'Failed to load user data file (empty or corrupted), resetting to defaults:',
135
+ error
136
+ );
137
+ yield* update(userData);
138
+ })
139
+ )
140
+ );
141
} else {
142
yield* Effect.logDebug('User data file does not exist, creating a new one');
143
yield* update(userData);
@@ -119,6 +149,8 @@ export const ComposioUserContextLive = Layer.effect(
149
...userData,
150
baseURL: Option.getOrElse(userData.baseURL, () => baseURL),
151
webURL: Option.getOrElse(userData.webURL, () => webURL),
152
+ orgId: userData.orgId,
153
+ projectId: userData.projectId,
154
};
155
156
return ComposioUserContext.of({
ts/packages/cli/src/services/utils/pretty-error.ts
+1
-1
@@ -5,7 +5,7 @@ const S_CORNER_TOP_LEFT = unicodeOr('╭', '+');
5
const S_CORNER_BOTTOM_LEFT = unicodeOr('╰', '+');
6
7
export function renderPrettyError(errorLines: Array<[key: string, value: unknown]>): string {
8
- return renderPrettyErrorGen(errorLines).toArray().join('\n');
8
+ return Array.from(renderPrettyErrorGen(errorLines)).join('\n');
9
}
10
11
function* renderPrettyErrorGen(
ts/packages/cli/src/utils/get-ancestors.ts
new
+20
@@ -0,0 +1,20 @@
1
+import path from 'node:path';
2
+
3
+/**
4
+ * Walk up from a directory to the filesystem root, collecting all ancestor paths.
5
+ * Returns an array starting with the resolved `cwd` and ending at the root.
6
+ */
7
+export const getAncestors = (cwd: string): string[] => {
8
+ const resolved = path.resolve(cwd);
9
+ const dirs = [resolved];
10
+ let current = resolved;
11
+
12
+ while (true) {
13
+ const parent = path.dirname(current);
14
+ if (parent === current) break;
15
+ dirs.push(parent);
16
+ current = parent;
17
+ }
18
+
19
+ return dirs;
20
+};
ts/packages/cli/test/__fixtures__/ambiguous-project/package.json
new
+7
@@ -0,0 +1,7 @@
1
+{
2
+ "name": "test-ambiguous",
3
+ "type": "module",
4
+ "devDependencies": {
5
+ "typescript": "^5.9.2"
6
+ }
7
+}
ts/packages/cli/test/__fixtures__/ambiguous-project/pyproject.toml
new
+4
@@ -0,0 +1,4 @@
1
+[project]
2
+name = "test-ambiguous"
3
+version = "0.1.0"
4
+requires-python = ">=3.10"
ts/packages/cli/test/__fixtures__/ambiguous-project/requirements.txt
new
+1
@@ -0,0 +1 @@
1
+composio
ts/packages/cli/test/__fixtures__/python-uv-project/pyproject.toml
new
+7
@@ -0,0 +1,7 @@
1
+[project]
2
+name = "test-uv-project"
3
+version = "0.1.0"
4
+requires-python = ">=3.10"
5
+
6
+[tool.uv]
7
+dev-dependencies = []
ts/packages/cli/test/__fixtures__/python-uv-project/uv.lock
new
+1
@@ -0,0 +1 @@
1
+version = 1
ts/packages/cli/test/__fixtures__/typescript-bun-project/bun.lockb
ts/packages/cli/test/__fixtures__/typescript-bun-project/package.json
new
+7
@@ -0,0 +1,7 @@
1
+{
2
+ "name": "test-bun-project",
3
+ "type": "module",
4
+ "devDependencies": {
5
+ "typescript": "^5.9.2"
6
+ }
7
+}
ts/packages/cli/test/__fixtures__/typescript-bun-project/tsconfig.json
new
+6
@@ -0,0 +1,6 @@
1
+{
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext"
5
+ }
6
+}
ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/package.json
new
+8
@@ -0,0 +1,8 @@
1
+{
2
+ "name": "test-monorepo",
3
+ "private": true,
4
+ "packageManager": "pnpm@9.15.0",
5
+ "devDependencies": {
6
+ "typescript": "^5.9.2"
7
+ }
8
+}
ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/pnpm-lock.yaml
new
+1
@@ -0,0 +1 @@
1
+lockfileVersion: '9.0'
ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/pnpm-workspace.yaml
new
+2
@@ -0,0 +1,2 @@
1
+packages:
2
+ - 'packages/*'
ts/packages/cli/test/__fixtures__/typescript-pnpm-monorepo/tsconfig.json
new
+6
@@ -0,0 +1,6 @@
1
+{
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext"
5
+ }
6
+}
ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
+2
@@ -26,6 +26,8 @@ export const TerminalUITest = Layer.succeed(
26
27
note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
28
29
+ select: (_message, options) => Effect.succeed(options[0].value),
30
+
31
confirm: (_message, options) => Effect.succeed(options?.defaultValue ?? true),
32
33
withSpinner: (message, effect, options) =>
ts/packages/cli/test/__utils__/services/test-layer.ts
+57
-5
@@ -30,7 +30,6 @@ import {
30
type InvalidVersionDetail,
31
} from 'src/services/composio-clients';
32
import type { ToolkitVersionOverrides } from 'src/effects/toolkit-version-overrides';
33
-import { EnvLangDetector } from 'src/services/env-lang-detector';
33
import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
34
import type { Tools } from 'src/models/tools';
35
import type { TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
@@ -58,6 +57,12 @@ import type {
57
SessionToolkitsParams,
58
} from '@composio/client/resources/tool-router';
59
import { Stdin } from 'src/services/stdin';
60
+import { ProjectContext } from 'src/services/project-context';
61
+import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
62
+import { CommandRunner } from 'src/services/command-runner';
63
+import { TerminalUI } from 'src/services/terminal-ui';
64
+import { CommandExecutor } from '@effect/platform';
65
+import { Option } from 'effect';
66
67
export interface TestLiveInput {
68
/**
@@ -164,6 +169,19 @@ export interface TestLiveInput {
169
params?: SessionToolkitsParams | null
170
) => Promise<SessionToolkitsResponse>;
171
};
172
+
173
+ /**
174
+ * Override CommandRunner behavior for tests.
175
+ * When set, the `CommandRunner` service uses the provided mock instance.
176
+ * When NOT set, uses a default mock that always returns exit code 0.
177
+ */
178
+ commandRunner?: CommandRunner;
179
+
180
+ /**
181
+ * Override TerminalUI behavior for tests.
182
+ * When set, replaces the default TerminalUITest (which auto-selects first option).
183
+ */
184
+ terminalUI?: TerminalUI;
185
}
186
187
/**
@@ -857,6 +875,21 @@ export const TestLayer = (input?: TestLiveInput) =>
875
876
const CliConfigLive = CliConfig.layer(ComposioCliConfig);
877
878
+ // CommandRunner mock — default returns exit code 0
879
+ const CommandRunnerTest = input?.commandRunner
880
+ ? Layer.succeed(CommandRunner, input.commandRunner)
881
+ : Layer.succeed(
882
+ CommandRunner,
883
+ new CommandRunner({
884
+ run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
885
+ })
886
+ );
887
+
888
+ // TerminalUI — use provided override or default TerminalUITest
889
+ const TerminalUILayer = input?.terminalUI
890
+ ? Layer.succeed(TerminalUI, input.terminalUI)
891
+ : TerminalUITest;
892
+
893
const _console = yield* MockConsole.make;
894
895
const layers = Layer.mergeAll(
@@ -869,15 +902,22 @@ export const TestLayer = (input?: TestLiveInput) =>
902
TriggersRealtimeTest,
903
ComposioClientSingletonTest,
904
ComposioToolkitsRepositoryTest,
872
- EnvLangDetector.Default,
905
JsPackageManagerDetector.Default,
906
+ ProjectEnvironmentDetector.Default,
907
+ CommandRunnerTest,
908
ToolsExecutorTest,
909
BunFileSystem.layer,
910
BunContext.layer,
911
MockTerminal.layer,
912
BunPath.layer,
913
StdinTest,
880
- TerminalUITest
914
+ TerminalUILayer,
915
+ Layer.succeed(
916
+ ProjectContext,
917
+ new ProjectContext({
918
+ resolve: Effect.succeed(Option.none()),
919
+ })
920
+ )
921
) satisfies RequiredLayer;
922
923
return layers;
@@ -918,10 +958,22 @@ function setupFixtureFolder({ fixture, tempDir }: { fixture?: string; tempDir: s
958
// Retry the task with a delay between retries and a maximum of 3 retries
959
const policy = Schedule.addDelay(Schedule.recurs(3), () => '100 millis');
960
921
- // If all retries fail, run the fallback effect
961
+ // If all retries fail, run the fallback effect.
962
+ // Use tar to skip heavy directories (.venv) that the global setup may have created.
963
+ // tar --exclude is POSIX and available on any Linux/macOS without extra packages.
964
const task = Effect.gen(function* () {
965
yield* fs.makeDirectory(tmpFixturesPath, { recursive: true });
924
- yield* fs.copy(realFixturePath, tmpFixturesPath);
966
+ const tarCmd = Command.make(
967
+ 'tar',
968
+ '-cf',
969
+ '-',
970
+ '--exclude',
971
+ '.venv',
972
+ '-C',
973
+ realFixturePath,
974
+ '.'
975
+ ).pipe(Command.pipeTo(Command.make('tar', '-xf', '-', '-C', tmpFixturesPath)));
976
+ yield* tarCmd.pipe(Command.exitCode, Effect.provide(BunContext.layer));
977
});
978
979
const repeated = Effect.retryOrElse(policy, () =>
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+2
-129
@@ -15,7 +15,7 @@ describe('CLI: composio', () => {
15
expect(result).toEqual(
16
ValidationError.commandMismatch(
17
HelpDoc.p(
18
- "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'generate', 'py', 'ts', 'toolkits', 'tools', 'auth-configs', 'connected-accounts', 'triggers'"
18
+ "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'init', 'generate', 'py', 'ts', 'toolkits', 'tools', 'auth-configs', 'connected-accounts', 'triggers'"
19
)
20
)
21
);
@@ -31,118 +31,7 @@ describe('CLI: composio', () => {
31
const lines = yield* MockConsole.getLines();
32
const output = lines.join('\n');
33
34
- expect(yield* sanitize(output)).toMatchInlineSnapshot(`
35
- "[0;1m[0;37;1mcomposio[0;1m[0m
36
-
37
- composio <VERSION>
38
-
39
- [0;1mUSAGE[0m
40
-
41
- $ composio [--log-level all | trace | debug | info | warning | error | fatal | none]
42
-
43
- [0;1mDESCRIPTION[0m
44
-
45
- Composio CLI - A tool for managing Python and TypeScript composio.dev projects.
46
-
47
- [0;1mOPTIONS[0m
48
-
49
- [0;1m--log-level all | trace | debug | info | warning | error | fatal | none[0m
50
-
51
- One of the following: all, trace, debug, info, warning, error, fatal, none
52
-
53
- Define log level
54
-
55
- This setting is optional.
56
-
57
- [0;1mCOMMANDS[0m
58
-
59
- - version Display the current Composio CLI version.
60
-
61
- - upgrade Upgrade your Composio CLI to the latest available version.
62
-
63
- - whoami Display your account information.
64
-
65
- - login [--no-browser] Log in to the Composio SDK.
66
-
67
- - logout Log out from the Composio SDK.
68
-
69
- - generate [(-o, --output-dir directory)] [--type-tools] --toolkits text... Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
70
-
71
- - py Handle Python projects.
72
-
73
- - py generate [(-o, --output-dir directory)] --toolkits text... Generate Python type stubs for toolkits, tools, and triggers from the Composio API.
74
-
75
- Environment Variables:
76
- COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
77
- Use "latest" or unset to use the latest version.
78
-
79
- - ts Handle TypeScript projects.
80
-
81
- - ts generate [(-o, --output-dir directory)] [--compact] [--transpiled] [--type-tools] --toolkits text... Generate TypeScript types for toolkits, tools, and triggers from the Composio API.
82
-
83
- Environment Variables:
84
- COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
85
- Use "latest" or unset to use the latest version.
86
-
87
- - toolkits Discover and inspect Composio toolkits.
88
-
89
- - toolkits list [--query text] [--limit integer] [--connected] [--user-id text] List available toolkits with connection status.
90
-
91
- - toolkits info [--user-id text] [<slug>] View details of a specific toolkit.
92
-
93
- - toolkits search [--limit integer] <query> Search toolkits by use case.
94
-
95
- - tools Discover and inspect Composio tools.
96
-
97
- - tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
98
-
99
- - tools info [<slug>] View details of a specific tool.
100
-
101
- - tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
102
-
103
- - tools execute [(-d, --data text)] [--user-id text] <slug> Execute a tool by slug with JSON arguments.
104
-
105
- - auth-configs View and manage Composio auth configs.
106
-
107
- - auth-configs list [--toolkits text] [--query text] [--limit integer] List auth configs.
108
-
109
- - auth-configs info [<id>] View details of a specific auth config.
110
-
111
- - auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>] Create a new auth config.
112
-
113
- - auth-configs delete [(-y, --yes)] [<id>] Delete an auth config.
114
-
115
- - connected-accounts View and manage Composio connected accounts.
116
-
117
- - connected-accounts list [--toolkits text] [--user-id text] [--status INITIALIZING | INITIATED | ACTIVE | FAILED | EXPIRED | INACTIVE] [--limit integer] List connected accounts.
118
-
119
- - connected-accounts info [<id>] View details of a specific connected account.
120
-
121
- - connected-accounts whoami [<id>] Show the external account profile for a connected account.
122
-
123
- - connected-accounts delete [(-y, --yes)] [<id>] Delete a connected account.
124
-
125
- - connected-accounts link [--auth-config text] [--user-id text] [--no-browser] [<toolkit>] Link an external account via OAuth redirect.
126
-
127
- - triggers Inspect and subscribe to trigger events.
128
-
129
- - triggers list [--toolkits text] [--limit integer] List available trigger types.
130
-
131
- - triggers info [<slug>] View details of a specific trigger type.
132
-
133
- - 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.
134
-
135
- - 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.
136
-
137
- - triggers create [--connected-account-id text] [--trigger-config text] [<trigger-name>] Create a new trigger instance.
138
-
139
- - triggers enable [<id>] Enable a trigger instance.
140
-
141
- - triggers disable [<id>] Disable a trigger instance.
142
-
143
- - triggers delete [(-y, --yes)] [<id>] Delete a trigger instance.
144
- "
145
- `);
34
+ expect(yield* sanitize(output)).toMatchSnapshot();
35
})
36
);
37
});
@@ -158,20 +47,4 @@ describe('CLI: composio', () => {
47
})
48
);
49
});
161
-
162
- // layer(TestLive())(it => {
163
- // it.scoped('[Pressing] CTRL+C [Then] quit wizard mode', () =>
164
- // Effect.gen(function* () {
165
- // const args = ['--wizard'];
166
-
167
- // const fiber = yield* Effect.fork(cli(args));
168
- // yield* MockTerminal.inputKey('c', { ctrl: true });
169
- // yield* Fiber.join(fiber);
170
-
171
- // const lines = yield* MockConsole.getLines();
172
- // const output = lines.join('\n');
173
- // expect(output).toContain('Quitting wizard mode...');
174
- // })
175
- // );
176
- // });
50
});
ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
new
+116
@@ -0,0 +1,116 @@
1
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2
+
3
+exports[`CLI: composio > [Given] --help flag [Then] prints help message 1`] = `
4
+"[0;1m[0;37;1mcomposio[0;1m[0m
5
+
6
+composio <VERSION>
7
+
8
+[0;1mUSAGE[0m
9
+
10
+$ composio [--log-level all | trace | debug | info | warning | error | fatal | none]
11
+
12
+[0;1mDESCRIPTION[0m
13
+
14
+Composio CLI - A tool for managing Python and TypeScript composio.dev projects.
15
+
16
+[0;1mOPTIONS[0m
17
+
18
+[0;1m--log-level all | trace | debug | info | warning | error | fatal | none[0m
19
+
20
+ One of the following: all, trace, debug, info, warning, error, fatal, none
21
+
22
+ Define log level
23
+
24
+ This setting is optional.
25
+
26
+[0;1mCOMMANDS[0m
27
+
28
+ - version Display the current Composio CLI version.
29
+
30
+ - upgrade Upgrade your Composio CLI to the latest available version.
31
+
32
+ - whoami Display your account information.
33
+
34
+ - login [--no-browser] [--api-key text] [--org-id text] [--project-id text] Log in to the Composio SDK.
35
+
36
+ - logout Log out from the Composio SDK.
37
+
38
+ - init [--org-id text] [--project-id text] [--no-browser] [--dry-run] [--force] [(-y, --yes)] [--no-skills] Initialize a Composio project in the current directory.
39
+
40
+ - generate [(-o, --output-dir directory)] [--type-tools] --toolkits text... Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
41
+
42
+ - py Handle Python projects.
43
+
44
+ - py generate [(-o, --output-dir directory)] --toolkits text... Generate Python type stubs for toolkits, tools, and triggers from the Composio API.
45
+
46
+Environment Variables:
47
+ COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
48
+ Use "latest" or unset to use the latest version.
49
+
50
+ - ts Handle TypeScript projects.
51
+
52
+ - ts generate [(-o, --output-dir directory)] [--compact] [--transpiled] [--type-tools] --toolkits text... Generate TypeScript types for toolkits, tools, and triggers from the Composio API.
53
+
54
+Environment Variables:
55
+ COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
56
+ Use "latest" or unset to use the latest version.
57
+
58
+ - toolkits Discover and inspect Composio toolkits.
59
+
60
+ - toolkits list [--query text] [--limit integer] [--connected] [--user-id text] List available toolkits with connection status.
61
+
62
+ - toolkits info [--user-id text] [<slug>] View details of a specific toolkit.
63
+
64
+ - toolkits search [--limit integer] <query> Search toolkits by use case.
65
+
66
+ - tools Discover and inspect Composio tools.
67
+
68
+ - tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
69
+
70
+ - tools info [<slug>] View details of a specific tool.
71
+
72
+ - tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
73
+
74
+ - tools execute [(-d, --data text)] [--user-id text] <slug> Execute a tool by slug with JSON arguments.
75
+
76
+ - auth-configs View and manage Composio auth configs.
77
+
78
+ - auth-configs list [--toolkits text] [--query text] [--limit integer] List auth configs.
79
+
80
+ - auth-configs info [<id>] View details of a specific auth config.
81
+
82
+ - auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>] Create a new auth config.
83
+
84
+ - auth-configs delete [(-y, --yes)] [<id>] Delete an auth config.
85
+
86
+ - connected-accounts View and manage Composio connected accounts.
87
+
88
+ - connected-accounts list [--toolkits text] [--user-id text] [--status INITIALIZING | INITIATED | ACTIVE | FAILED | EXPIRED | INACTIVE] [--limit integer] List connected accounts.
89
+
90
+ - connected-accounts info [<id>] View details of a specific connected account.
91
+
92
+ - connected-accounts whoami [<id>] Show the external account profile for a connected account.
93
+
94
+ - connected-accounts delete [(-y, --yes)] [<id>] Delete a connected account.
95
+
96
+ - connected-accounts link [--auth-config text] [--user-id text] [--no-browser] [<toolkit>] Link an external account via OAuth redirect.
97
+
98
+ - triggers Inspect and subscribe to trigger events.
99
+
100
+ - triggers list [--toolkits text] [--limit integer] List available trigger types.
101
+
102
+ - triggers info [<slug>] View details of a specific trigger type.
103
+
104
+ - 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.
105
+
106
+ - 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.
107
+
108
+ - triggers create [--connected-account-id text] [--trigger-config text] [<trigger-name>] Create a new trigger instance.
109
+
110
+ - triggers enable [<id>] Enable a trigger instance.
111
+
112
+ - triggers disable [<id>] Disable a trigger instance.
113
+
114
+ - triggers delete [(-y, --yes)] [<id>] Delete a trigger instance.
115
+"
116
+`;
ts/packages/cli/test/src/commands/generate.cmd.test.ts
+57
@@ -64,6 +64,63 @@ describe('CLI: composio generate', () => {
64
);
65
});
66
67
+ layer(
68
+ TestLive({
69
+ fixture: 'typescript-pnpm-monorepo',
70
+ })
71
+ )(it => {
72
+ it.scoped('[Given] a pnpm monorepo project in cwd [Then] it detects TypeScript', () =>
73
+ Effect.gen(function* () {
74
+ const process = yield* NodeProcess;
75
+ const cwd = process.cwd;
76
+
77
+ const args = ['generate', '--output-dir', cwd];
78
+ yield* cli(args);
79
+ const lines = yield* MockConsole.getLines();
80
+ const output = lines.join('\n');
81
+ expect(output).toContain('Project type detected: TypeScript');
82
+ })
83
+ );
84
+ });
85
+
86
+ layer(
87
+ TestLive({
88
+ fixture: 'typescript-bun-project',
89
+ })
90
+ )(it => {
91
+ it.scoped('[Given] a bun project in cwd [Then] it detects TypeScript', () =>
92
+ Effect.gen(function* () {
93
+ const process = yield* NodeProcess;
94
+ const cwd = process.cwd;
95
+
96
+ const args = ['generate', '--output-dir', cwd];
97
+ yield* cli(args);
98
+ const lines = yield* MockConsole.getLines();
99
+ const output = lines.join('\n');
100
+ expect(output).toContain('Project type detected: TypeScript');
101
+ })
102
+ );
103
+ });
104
+
105
+ layer(
106
+ TestLive({
107
+ fixture: 'python-uv-project',
108
+ })
109
+ )(it => {
110
+ it.scoped('[Given] a uv Python project in cwd [Then] it detects Python', () =>
111
+ Effect.gen(function* () {
112
+ const process = yield* NodeProcess;
113
+ const cwd = process.cwd;
114
+
115
+ const args = ['generate', '--output-dir', cwd];
116
+ yield* cli(args);
117
+ const lines = yield* MockConsole.getLines();
118
+ const output = lines.join('\n');
119
+ expect(output).toContain('Project type detected: Python');
120
+ })
121
+ );
122
+ });
123
+
124
layer(
125
TestLive({
126
fixture: 'typescript-project',
ts/packages/cli/test/src/commands/init.cmd.test.ts
new
+512
@@ -0,0 +1,512 @@
1
+import path from 'node:path';
2
+import { describe, expect, layer } from '@effect/vitest';
3
+import { vi, afterEach, beforeAll, afterAll } from 'vitest';
4
+import { Console, Effect, Exit } from 'effect';
5
+import { CommandExecutor, FileSystem } from '@effect/platform';
6
+import { NodeProcess } from 'src/services/node-process';
7
+import { CommandRunner } from 'src/services/command-runner';
8
+import { TerminalUI } from 'src/services/terminal-ui';
9
+import { cli, TestLive, MockConsole } from 'test/__utils__';
10
+
11
+// ── Helpers ──────────────────────────────────────────────────────────────────
12
+
13
+const makeSessionInfoBody = () => ({
14
+ project: {
15
+ name: 'test-project',
16
+ id: 'proj_test_123',
17
+ org_id: 'org_test_456',
18
+ nano_id: 'pr_nano_789',
19
+ email: 'test@composio.dev',
20
+ created_at: '2026-01-01T00:00:00.000Z',
21
+ updated_at: '2026-01-01T00:00:00.000Z',
22
+ org: { name: 'Test Org', id: 'org_test_456', plan: 'free' },
23
+ },
24
+ org_member: {
25
+ id: 'org_test_456',
26
+ email: 'test@composio.dev',
27
+ name: 'Test User',
28
+ role: 'admin',
29
+ },
30
+ api_key: {
31
+ name: 'default',
32
+ project_id: 'proj_test_123',
33
+ id: 'ak_test',
34
+ org_member_id: 'org_test_456',
35
+ },
36
+});
37
+
38
+function mockFetchResponse(body: unknown, status = 200): Response {
39
+ return new Response(JSON.stringify(body), {
40
+ status,
41
+ headers: { 'Content-Type': 'application/json' },
42
+ });
43
+}
44
+
45
+const makeCommandRunnerSuccess = () =>
46
+ new CommandRunner({
47
+ run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
48
+ });
49
+
50
+const makeCommandRunnerFail = (exitCode = 1) =>
51
+ new CommandRunner({
52
+ run: () => Effect.succeed(CommandExecutor.ExitCode(exitCode)),
53
+ });
54
+
55
+/**
56
+ * Creates a TerminalUI where specific `select()` calls return custom values.
57
+ * `selectOverrides` maps call index (0-based) to the option index to pick.
58
+ * Calls without overrides default to picking the first option (index 0).
59
+ */
60
+const makeTerminalUIWithSelectOverrides = (selectOverrides: Record<number, number>): TerminalUI => {
61
+ let selectCallIndex = 0;
62
+
63
+ return TerminalUI.of({
64
+ output: data => Console.log(data),
65
+ intro: title => Console.log(`-- ${title} --`),
66
+ outro: message => Console.log(`-- ${message} --`),
67
+ log: {
68
+ info: message => Console.log(message),
69
+ success: message => Console.log(message),
70
+ warn: message => Console.warn(message),
71
+ error: message => Console.error(message),
72
+ step: message => Console.log(message),
73
+ message: message => Console.log(message),
74
+ },
75
+ note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
76
+ select: (_message, options) => {
77
+ const idx = selectCallIndex++;
78
+ const optionIdx = selectOverrides[idx] ?? 0;
79
+ return Effect.succeed(options[optionIdx].value);
80
+ },
81
+ confirm: (_message, options) => Effect.succeed(options?.defaultValue ?? true),
82
+ withSpinner: (message, effect, options) =>
83
+ Effect.gen(function* () {
84
+ const result = yield* effect;
85
+ const successMsg =
86
+ typeof options?.successMessage === 'function'
87
+ ? options.successMessage(result)
88
+ : (options?.successMessage ?? message);
89
+ yield* Console.log(successMsg);
90
+ return result;
91
+ }),
92
+ useMakeSpinner: (message, use) =>
93
+ Effect.gen(function* () {
94
+ let stopped = false;
95
+ const handle = {
96
+ message: (_msg: string) => Effect.void,
97
+ stop: (msg?: string) =>
98
+ Effect.gen(function* () {
99
+ stopped = true;
100
+ if (msg) yield* Console.log(msg);
101
+ }),
102
+ error: (msg?: string) =>
103
+ Effect.gen(function* () {
104
+ stopped = true;
105
+ if (msg) yield* Console.error(msg);
106
+ }),
107
+ };
108
+ const exit = yield* Effect.exit(use(handle));
109
+ if (Exit.isFailure(exit) && !stopped) {
110
+ yield* Console.error(message);
111
+ }
112
+ return yield* exit;
113
+ }),
114
+ });
115
+};
116
+
117
+// ── Tests ────────────────────────────────────────────────────────────────────
118
+
119
+describe('CLI: composio init', () => {
120
+ let savedUserAgent: string | undefined;
121
+
122
+ beforeAll(() => {
123
+ savedUserAgent = process.env.npm_config_user_agent;
124
+ delete process.env.npm_config_user_agent;
125
+ });
126
+
127
+ afterAll(() => {
128
+ if (savedUserAgent !== undefined) {
129
+ process.env.npm_config_user_agent = savedUserAgent;
130
+ } else {
131
+ delete process.env.npm_config_user_agent;
132
+ }
133
+ });
134
+
135
+ afterEach(() => {
136
+ vi.restoreAllMocks();
137
+ });
138
+
139
+ describe('[Given] --org-id + --project-id flags with TS project', () => {
140
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
141
+ it => {
142
+ it.scoped('[Then] detects TS project and installs dependency', () =>
143
+ Effect.gen(function* () {
144
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
145
+ mockFetchResponse(makeSessionInfoBody())
146
+ );
147
+
148
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
149
+ yield* cli(args);
150
+
151
+ const lines = yield* MockConsole.getLines();
152
+ const output = lines.join('\n');
153
+
154
+ expect(output).toContain('typescript');
155
+ expect(output).toContain('Installed @composio/core');
156
+ })
157
+ );
158
+ }
159
+ );
160
+ });
161
+
162
+ describe('[Given] --org-id + --project-id flags with Python project', () => {
163
+ layer(TestLive({ fixture: 'python-project', commandRunner: makeCommandRunnerSuccess() }))(
164
+ it => {
165
+ it.scoped('[Then] detects Python project and shows correct install command', () =>
166
+ Effect.gen(function* () {
167
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
168
+ mockFetchResponse(makeSessionInfoBody())
169
+ );
170
+
171
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
172
+ yield* cli(args);
173
+
174
+ const lines = yield* MockConsole.getLines();
175
+ const output = lines.join('\n');
176
+
177
+ expect(output).toContain('python');
178
+ expect(output).toContain('pip install composio');
179
+ expect(output).toContain('Dry run complete.');
180
+ })
181
+ );
182
+ }
183
+ );
184
+ });
185
+
186
+ describe('[Given] --dry-run flag with TS project', () => {
187
+ layer(TestLive({ fixture: 'typescript-project' }))(it => {
188
+ it.scoped('[Then] prints install command without executing', () =>
189
+ Effect.gen(function* () {
190
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
191
+
192
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
193
+ yield* cli(args);
194
+
195
+ const lines = yield* MockConsole.getLines();
196
+ const output = lines.join('\n');
197
+
198
+ expect(output).toContain('npm install -S @composio/core');
199
+ expect(output).toContain('Dry run complete.');
200
+ expect(output).not.toContain('Installed @composio/core');
201
+ })
202
+ );
203
+ });
204
+ });
205
+
206
+ describe('[Given] @composio/core already in node_modules', () => {
207
+ layer(
208
+ TestLive({
209
+ fixture: 'typescript-project-with-composio-core',
210
+ commandRunner: makeCommandRunnerSuccess(),
211
+ })
212
+ )(it => {
213
+ it.scoped('[Then] skips install', () =>
214
+ Effect.gen(function* () {
215
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
216
+
217
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1'];
218
+ yield* cli(args);
219
+
220
+ const lines = yield* MockConsole.getLines();
221
+ const output = lines.join('\n');
222
+
223
+ expect(output).toContain('Dependency already installed');
224
+ expect(output).not.toContain('Installed @composio/core');
225
+ })
226
+ );
227
+ });
228
+ });
229
+
230
+ describe('[Given] --force flag with dependency installed', () => {
231
+ layer(
232
+ TestLive({
233
+ fixture: 'typescript-project-with-composio-core',
234
+ commandRunner: makeCommandRunnerSuccess(),
235
+ })
236
+ )(it => {
237
+ it.scoped('[Then] reinstalls', () =>
238
+ Effect.gen(function* () {
239
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
240
+
241
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--force', '--yes'];
242
+ yield* cli(args);
243
+
244
+ const lines = yield* MockConsole.getLines();
245
+ const output = lines.join('\n');
246
+
247
+ expect(output).toContain('Reinstalling due to --force');
248
+ expect(output).toContain('Installed @composio/core');
249
+ })
250
+ );
251
+ });
252
+ });
253
+
254
+ describe('[Given] install command fails', () => {
255
+ layer(
256
+ TestLive({
257
+ fixture: 'typescript-project',
258
+ commandRunner: makeCommandRunnerFail(1),
259
+ })
260
+ )(it => {
261
+ it.scoped('[Then] shows error and suggests manual install', () =>
262
+ Effect.gen(function* () {
263
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
264
+
265
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
266
+ yield* cli(args);
267
+
268
+ const lines = yield* MockConsole.getLines();
269
+ const output = lines.join('\n');
270
+
271
+ expect(output).toContain('Install failed');
272
+ expect(output).toContain('install manually');
273
+ })
274
+ );
275
+ });
276
+ });
277
+
278
+ describe('[Given] pnpm monorepo fixture', () => {
279
+ layer(
280
+ TestLive({
281
+ fixture: 'typescript-pnpm-monorepo',
282
+ commandRunner: makeCommandRunnerSuccess(),
283
+ })
284
+ )(it => {
285
+ it.scoped('[Then] detects pnpm and uses pnpm add', () =>
286
+ Effect.gen(function* () {
287
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
288
+
289
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
290
+ yield* cli(args);
291
+
292
+ const lines = yield* MockConsole.getLines();
293
+ const output = lines.join('\n');
294
+
295
+ expect(output).toContain('pnpm');
296
+ expect(output).toContain('pnpm add @composio/core');
297
+ })
298
+ );
299
+ });
300
+ });
301
+
302
+ // ── Skills installation tests ──────────────────────────────────────────────
303
+
304
+ describe('[Given] skills install with --yes flag', () => {
305
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
306
+ it => {
307
+ it.scoped('[Then] installs Composio skills', () =>
308
+ Effect.gen(function* () {
309
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
310
+ mockFetchResponse(makeSessionInfoBody())
311
+ );
312
+
313
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
314
+ yield* cli(args);
315
+
316
+ const lines = yield* MockConsole.getLines();
317
+ const output = lines.join('\n');
318
+
319
+ expect(output).toContain('Installed Composio skills');
320
+ })
321
+ );
322
+ }
323
+ );
324
+ });
325
+
326
+ describe('[Given] --dry-run flag shows skills command', () => {
327
+ layer(TestLive({ fixture: 'typescript-project' }))(it => {
328
+ it.scoped('[Then] prints skills install command without executing', () =>
329
+ Effect.gen(function* () {
330
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
331
+
332
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
333
+ yield* cli(args);
334
+
335
+ const lines = yield* MockConsole.getLines();
336
+ const output = lines.join('\n');
337
+
338
+ expect(output).toContain('npx skills add composiohq/skills');
339
+ expect(output).not.toContain('Installed Composio skills');
340
+ })
341
+ );
342
+ });
343
+ });
344
+
345
+ describe('[Given] skills install command fails', () => {
346
+ layer(
347
+ TestLive({
348
+ fixture: 'typescript-project',
349
+ commandRunner: makeCommandRunnerFail(1),
350
+ })
351
+ )(it => {
352
+ it.scoped('[Then] shows error and suggests manual skills install', () =>
353
+ Effect.gen(function* () {
354
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
355
+
356
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
357
+ yield* cli(args);
358
+
359
+ const lines = yield* MockConsole.getLines();
360
+ const output = lines.join('\n');
361
+
362
+ expect(output).toContain('Skills install failed');
363
+ expect(output).toContain('npx skills add composiohq/skills');
364
+ })
365
+ );
366
+ });
367
+ });
368
+
369
+ // ── --no-skills flag tests ─────────────────────────────────────────────────
370
+
371
+ describe('[Given] --no-skills flag', () => {
372
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
373
+ it => {
374
+ it.scoped('[Then] skips skills prompt and does not install skills', () =>
375
+ Effect.gen(function* () {
376
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
377
+ mockFetchResponse(makeSessionInfoBody())
378
+ );
379
+
380
+ const proc = yield* NodeProcess;
381
+ const fs = yield* FileSystem.FileSystem;
382
+ const args = [
383
+ 'init',
384
+ '--org-id',
385
+ 'org1',
386
+ '--project-id',
387
+ 'proj1',
388
+ '--yes',
389
+ '--no-skills',
390
+ ];
391
+ yield* cli(args);
392
+
393
+ const lines = yield* MockConsole.getLines();
394
+ const output = lines.join('\n');
395
+
396
+ // Should NOT install skills
397
+ expect(output).not.toContain('Installed Composio skills');
398
+ // Should still install the core dependency
399
+ expect(output).toContain('Installed @composio/core');
400
+
401
+ // config.json should have install_skills: false
402
+ const configPath = path.join(proc.cwd, '.composio', 'config.json');
403
+ const configContent = yield* fs.readFileString(configPath);
404
+ const config = JSON.parse(configContent);
405
+ expect(config.install_skills).toBe(false);
406
+ })
407
+ );
408
+ }
409
+ );
410
+ });
411
+
412
+ // ── MCP mode and PM-skip tests ─────────────────────────────────────────────
413
+
414
+ describe('[Given] MCP usage mode selected', () => {
415
+ // Select overrides: 0th select (usage mode) → index 1 ("Composio MCP")
416
+ const mcpUI = makeTerminalUIWithSelectOverrides({ 0: 1 });
417
+
418
+ layer(
419
+ TestLive({
420
+ fixture: 'typescript-project',
421
+ commandRunner: makeCommandRunnerSuccess(),
422
+ terminalUI: mcpUI,
423
+ })
424
+ )(it => {
425
+ it.scoped('[Then] skips env detection and dependency install', () =>
426
+ Effect.gen(function* () {
427
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
428
+
429
+ const proc = yield* NodeProcess;
430
+ const fs = yield* FileSystem.FileSystem;
431
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
432
+ yield* cli(args);
433
+
434
+ const lines = yield* MockConsole.getLines();
435
+ const output = lines.join('\n');
436
+
437
+ // Should NOT detect environment or install dependency in MCP mode
438
+ expect(output).not.toContain('Detected:');
439
+ expect(output).not.toContain('Installed @composio/core');
440
+ expect(output).toContain('Project initialized');
441
+
442
+ // config.json should not have detected_language or package_manager
443
+ const configPath = path.join(proc.cwd, '.composio', 'config.json');
444
+ const configContent = yield* fs.readFileString(configPath);
445
+ const config = JSON.parse(configContent);
446
+ expect(config.usage_mode).toBe('mcp');
447
+ expect(config.detected_language).toBeUndefined();
448
+ expect(config.package_manager).toBeUndefined();
449
+ })
450
+ );
451
+ });
452
+ });
453
+
454
+ describe('[Given] native mode but user skips PM confirmation', () => {
455
+ // Select overrides:
456
+ // 0th select (usage mode) → index 0 ("Native tools")
457
+ // 1st select (framework) → index 0 ("Skip")
458
+ // 2nd select (PM confirm) → index 1 ("Skip")
459
+ const skipPmUI = makeTerminalUIWithSelectOverrides({ 2: 1 });
460
+
461
+ layer(
462
+ TestLive({
463
+ fixture: 'typescript-project',
464
+ commandRunner: makeCommandRunnerSuccess(),
465
+ terminalUI: skipPmUI,
466
+ })
467
+ )(it => {
468
+ it.scoped('[Then] detects env but skips dependency install', () =>
469
+ Effect.gen(function* () {
470
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
471
+
472
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
473
+ yield* cli(args);
474
+
475
+ const lines = yield* MockConsole.getLines();
476
+ const output = lines.join('\n');
477
+
478
+ // Should detect environment but NOT install dependency
479
+ expect(output).toContain('Detected:');
480
+ expect(output).not.toContain('Installed @composio/core');
481
+ expect(output).toContain('Project initialized');
482
+ })
483
+ );
484
+ });
485
+ });
486
+
487
+ describe('[Given] config files are written', () => {
488
+ layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
489
+ it => {
490
+ it.scoped('[Then] config.json includes detection info', () =>
491
+ Effect.gen(function* () {
492
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
493
+ mockFetchResponse(makeSessionInfoBody())
494
+ );
495
+
496
+ const proc = yield* NodeProcess;
497
+ const fs = yield* FileSystem.FileSystem;
498
+ const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
499
+ yield* cli(args);
500
+
501
+ const configPath = path.join(proc.cwd, '.composio', 'config.json');
502
+ const configContent = yield* fs.readFileString(configPath);
503
+ const config = JSON.parse(configContent);
504
+
505
+ expect(config.detected_language).toBeDefined();
506
+ expect(config.package_manager).toBeDefined();
507
+ })
508
+ );
509
+ }
510
+ );
511
+ });
512
+});
ts/packages/cli/test/src/commands/login.cmd.test.ts
new
+247
@@ -0,0 +1,247 @@
1
+import { describe, expect, layer } from '@effect/vitest';
2
+import { vi, afterEach } from 'vitest';
3
+import { Effect } from 'effect';
4
+import { ComposioUserContext } from 'src/services/user-context';
5
+import { cli, TestLive, MockConsole } from 'test/__utils__';
6
+
7
+// ── Helpers ──────────────────────────────────────────────────────────────────
8
+
9
+/**
10
+ * Build a canned SessionInfoResponse JSON body for mocking `getSessionInfo`
11
+ * and `getSessionInfoByUserApiKey`.
12
+ */
13
+const makeSessionInfoBody = (overrides?: {
14
+ orgId?: string;
15
+ orgName?: string;
16
+ projectId?: string;
17
+ projectNanoId?: string;
18
+ projectName?: string;
19
+ email?: string;
20
+ memberName?: string;
21
+}) => ({
22
+ project: {
23
+ name: overrides?.projectName ?? 'test-project',
24
+ id: overrides?.projectId ?? 'proj_test_123',
25
+ org_id: overrides?.orgId ?? 'org_test_456',
26
+ nano_id: overrides?.projectNanoId ?? 'pr_nano_789',
27
+ email: overrides?.email ?? 'test@composio.dev',
28
+ created_at: '2026-01-01T00:00:00.000Z',
29
+ updated_at: '2026-01-01T00:00:00.000Z',
30
+ org: {
31
+ name: overrides?.orgName ?? 'Test Org',
32
+ id: overrides?.orgId ?? 'org_test_456',
33
+ plan: 'free',
34
+ },
35
+ },
36
+ org_member: {
37
+ id: overrides?.orgId ?? 'org_test_456',
38
+ email: overrides?.email ?? 'test@composio.dev',
39
+ name: overrides?.memberName ?? 'Test User',
40
+ role: 'admin',
41
+ },
42
+ api_key: {
43
+ name: 'default',
44
+ project_id: overrides?.projectId ?? 'proj_test_123',
45
+ id: 'ak_test',
46
+ org_member_id: overrides?.orgId ?? 'org_test_456',
47
+ },
48
+});
49
+
50
+/**
51
+ * Creates a mock Response object.
52
+ */
53
+function mockFetchResponse(body: unknown, status = 200): Response {
54
+ const bodyStr = JSON.stringify(body);
55
+ return new Response(bodyStr, {
56
+ status,
57
+ headers: { 'Content-Type': 'application/json' },
58
+ });
59
+}
60
+
61
+// ── Tests ────────────────────────────────────────────────────────────────────
62
+
63
+describe('CLI: composio login', () => {
64
+ afterEach(() => {
65
+ vi.restoreAllMocks();
66
+ });
67
+
68
+ describe('[When] not logged in', () => {
69
+ describe('non-interactive login: session/info succeeds', () => {
70
+ layer(TestLive())(it => {
71
+ it.scoped('[Then] stores credentials with enriched org/project IDs', () =>
72
+ Effect.gen(function* () {
73
+ const ctx = yield* ComposioUserContext;
74
+ expect(ctx.isLoggedIn()).toBe(false);
75
+
76
+ // Mock fetch for getSessionInfo call
77
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
78
+ mockFetchResponse(
79
+ makeSessionInfoBody({
80
+ orgId: 'org_verified',
81
+ projectId: 'proj_verified',
82
+ email: 'verified@composio.dev',
83
+ projectName: 'Verified Project',
84
+ orgName: 'Verified Org',
85
+ })
86
+ )
87
+ );
88
+
89
+ yield* cli([
90
+ 'login',
91
+ '--api-key',
92
+ 'uak_test_key',
93
+ '--org-id',
94
+ 'org_initial',
95
+ '--project-id',
96
+ 'proj_initial',
97
+ ]);
98
+
99
+ // Verify fetch was called with session/info endpoint and correct headers
100
+ expect(fetchSpy).toHaveBeenCalledOnce();
101
+ const [url, init] = fetchSpy.mock.calls[0]!;
102
+ expect(url).toContain('/api/v3/auth/session/info');
103
+ expect((init as RequestInit).headers).toMatchObject({
104
+ 'x-api-key': 'uak_test_key',
105
+ 'x-org-id': 'org_initial',
106
+ 'x-project-id': 'proj_initial',
107
+ });
108
+
109
+ // The mutable isLoggedIn closure reflects the login
110
+ expect(ctx.isLoggedIn()).toBe(true);
111
+
112
+ // Verify console output contains the enriched email and success message
113
+ const lines = yield* MockConsole.getLines();
114
+ const output = lines.join('\n');
115
+ expect(output).toContain('verified@composio.dev');
116
+ expect(output).toContain("You're all set!");
117
+ })
118
+ );
119
+ });
120
+ });
121
+
122
+ describe('non-interactive login: session/info returns 500', () => {
123
+ layer(TestLive())(it => {
124
+ it.scoped('[Then] falls back to initial IDs on server error', () =>
125
+ Effect.gen(function* () {
126
+ const ctx = yield* ComposioUserContext;
127
+ expect(ctx.isLoggedIn()).toBe(false);
128
+
129
+ // Mock fetch to return a 500 error.
130
+ // In strict mode, only 400-499 are hard failures.
131
+ // 500 falls through the generic catch → undefined sessionInfo → use initial IDs.
132
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
133
+ mockFetchResponse(
134
+ {
135
+ status: 500,
136
+ error: {
137
+ error: {
138
+ message: 'Internal server error',
139
+ suggested_fix: 'Try again later',
140
+ code: 500,
141
+ },
142
+ },
143
+ },
144
+ 500
145
+ )
146
+ );
147
+
148
+ yield* cli([
149
+ 'login',
150
+ '--api-key',
151
+ 'uak_fallback_key',
152
+ '--org-id',
153
+ 'org_fallback',
154
+ '--project-id',
155
+ 'proj_fallback',
156
+ ]);
157
+
158
+ // Credentials stored with initial (uncorrected) IDs since session/info failed
159
+ expect(ctx.isLoggedIn()).toBe(true);
160
+
161
+ const lines = yield* MockConsole.getLines();
162
+ const output = lines.join('\n');
163
+ expect(output).toContain('Logged in');
164
+ })
165
+ );
166
+ });
167
+ });
168
+
169
+ describe('non-interactive login: session/info returns 401', () => {
170
+ layer(TestLive())(it => {
171
+ it.scoped('[Then] rejects invalid API key', () =>
172
+ Effect.gen(function* () {
173
+ const ctx = yield* ComposioUserContext;
174
+ expect(ctx.isLoggedIn()).toBe(false);
175
+
176
+ // Mock fetch to return 401
177
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
178
+ mockFetchResponse(
179
+ {
180
+ status: 401,
181
+ error: {
182
+ error: {
183
+ message: 'Invalid API key',
184
+ suggested_fix: 'Check your API key',
185
+ code: 401,
186
+ },
187
+ },
188
+ },
189
+ 401
190
+ )
191
+ );
192
+
193
+ // Non-interactive login: strict verification fails on 401
194
+ const result = yield* cli([
195
+ 'login',
196
+ '--api-key',
197
+ 'uak_bad_key',
198
+ '--org-id',
199
+ 'org_test',
200
+ '--project-id',
201
+ 'proj_test',
202
+ ]).pipe(Effect.either);
203
+
204
+ // The command should fail
205
+ expect(result._tag).toBe('Left');
206
+
207
+ // Should NOT be logged in after a failed verification
208
+ expect(ctx.isLoggedIn()).toBe(false);
209
+ })
210
+ );
211
+ });
212
+ });
213
+
214
+ describe('non-interactive login: session/info network failure', () => {
215
+ layer(TestLive())(it => {
216
+ it.scoped('[Then] falls back to initial IDs on network error', () =>
217
+ Effect.gen(function* () {
218
+ const ctx = yield* ComposioUserContext;
219
+ expect(ctx.isLoggedIn()).toBe(false);
220
+
221
+ // Mock fetch to throw a network error
222
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('fetch failed'));
223
+
224
+ yield* cli([
225
+ 'login',
226
+ '--api-key',
227
+ 'uak_network_key',
228
+ '--org-id',
229
+ 'org_net',
230
+ '--project-id',
231
+ 'proj_net',
232
+ ]);
233
+
234
+ // Network errors are non-fatal even in strict mode (only 400-499 are strict)
235
+ // Actually: the fetch itself fails → HttpServerError with no status →
236
+ // strict check (e.status >= 400 && < 500) doesn't match → falls through → undefined
237
+ expect(ctx.isLoggedIn()).toBe(true);
238
+
239
+ const lines = yield* MockConsole.getLines();
240
+ const output = lines.join('\n');
241
+ expect(output).toContain('Logged in');
242
+ })
243
+ );
244
+ });
245
+ });
246
+ });
247
+});
ts/packages/cli/test/src/commands/logout.cmd.test.ts
+4
@@ -17,6 +17,8 @@ describe('CLI: composio logout', () => {
17
apiKey: Option.none(),
18
baseURL: 'https://backend.composio.dev',
19
webURL: 'https://platform.composio.dev',
20
+ orgId: Option.none(),
21
+ projectId: Option.none(),
22
});
23
24
expect(ctx.data).toMatchObject(expectedUserData);
@@ -51,6 +53,8 @@ describe('CLI: composio logout', () => {
53
apiKey: Option.some('api_key_already_logged_in'),
54
baseURL: 'https://backend.composio.dev',
55
webURL: 'https://platform.composio.dev',
56
+ orgId: Option.none(),
57
+ projectId: Option.none(),
58
})
59
);
60
ts/packages/cli/test/src/effects/core-dependency.test.ts
new
+36
@@ -0,0 +1,36 @@
1
+import { describe, it, expect } from 'vitest';
2
+import { getJsInstallCommand, getPythonInstallCommand } from 'src/effects/core-dependency';
3
+
4
+describe('core-dependency', () => {
5
+ describe('getJsInstallCommand', () => {
6
+ it('[Given] pnpm [Then] returns "pnpm add <dep>"', () => {
7
+ expect(getJsInstallCommand('pnpm', '@composio/core')).toBe('pnpm add @composio/core');
8
+ });
9
+
10
+ it('[Given] npm [Then] returns "npm install -S <dep>"', () => {
11
+ expect(getJsInstallCommand('npm', '@composio/core')).toBe('npm install -S @composio/core');
12
+ });
13
+
14
+ it('[Given] yarn [Then] returns "yarn add <dep>"', () => {
15
+ expect(getJsInstallCommand('yarn', '@composio/core')).toBe('yarn add @composio/core');
16
+ });
17
+
18
+ it('[Given] bun [Then] returns "bun add <dep>"', () => {
19
+ expect(getJsInstallCommand('bun', '@composio/core')).toBe('bun add @composio/core');
20
+ });
21
+
22
+ it('[Given] deno [Then] returns "deno add npm:<dep>"', () => {
23
+ expect(getJsInstallCommand('deno', '@composio/core')).toBe('deno add npm:@composio/core');
24
+ });
25
+ });
26
+
27
+ describe('getPythonInstallCommand', () => {
28
+ it('[Given] uv [Then] returns "uv pip install <dep>"', () => {
29
+ expect(getPythonInstallCommand('uv', 'composio')).toBe('uv pip install composio');
30
+ });
31
+
32
+ it('[Given] pip [Then] returns "pip install <dep>"', () => {
33
+ expect(getPythonInstallCommand('pip', 'composio')).toBe('pip install composio');
34
+ });
35
+ });
36
+});
ts/packages/cli/test/src/models/project-keys.test.ts
new
+181
@@ -0,0 +1,181 @@
1
+import { describe, it, expect } from 'vitest';
2
+import { Effect, Option } from 'effect';
3
+import { ProjectKeys, projectKeysFromJSON, projectKeysToJSON } from 'src/models/project-keys';
4
+
5
+describe('ProjectKeys', () => {
6
+ describe('decode from JSON', () => {
7
+ it('decodes valid JSON with required fields only', () => {
8
+ const json = JSON.stringify({ org_id: 'abc', project_id: 'def' });
9
+
10
+ const result = Effect.runSync(projectKeysFromJSON(json));
11
+
12
+ expect(result.orgId).toBe('abc');
13
+ expect(result.projectId).toBe('def');
14
+ expect(Option.isNone(result.projectName)).toBe(true);
15
+ expect(Option.isNone(result.orgName)).toBe(true);
16
+ expect(Option.isNone(result.email)).toBe(true);
17
+ });
18
+
19
+ it('decodes valid JSON with all fields', () => {
20
+ const json = JSON.stringify({
21
+ org_id: 'abc',
22
+ project_id: 'def',
23
+ project_name: 'My Project',
24
+ org_name: 'My Org',
25
+ email: 'test@test.com',
26
+ });
27
+
28
+ const result = Effect.runSync(projectKeysFromJSON(json));
29
+
30
+ expect(result.orgId).toBe('abc');
31
+ expect(result.projectId).toBe('def');
32
+ expect(Option.getOrUndefined(result.projectName)).toBe('My Project');
33
+ expect(Option.getOrUndefined(result.orgName)).toBe('My Org');
34
+ expect(Option.getOrUndefined(result.email)).toBe('test@test.com');
35
+ });
36
+
37
+ it('decodes null optional fields as Option.none()', () => {
38
+ const json = JSON.stringify({
39
+ org_id: 'abc',
40
+ project_id: 'def',
41
+ project_name: null,
42
+ org_name: null,
43
+ email: null,
44
+ });
45
+
46
+ const result = Effect.runSync(projectKeysFromJSON(json));
47
+
48
+ expect(result.orgId).toBe('abc');
49
+ expect(result.projectId).toBe('def');
50
+ expect(Option.isNone(result.projectName)).toBe(true);
51
+ expect(Option.isNone(result.orgName)).toBe(true);
52
+ expect(Option.isNone(result.email)).toBe(true);
53
+ });
54
+
55
+ it('ignores extra keys in decoded JSON', () => {
56
+ const json = JSON.stringify({
57
+ org_id: 'abc',
58
+ project_id: 'def',
59
+ future_field: 'unknown',
60
+ });
61
+
62
+ // Should not throw -- onExcessProperty: 'ignore' silently drops extra keys
63
+ const result = Effect.runSync(projectKeysFromJSON(json));
64
+ expect(result.orgId).toBe('abc');
65
+ expect(result.projectId).toBe('def');
66
+ });
67
+
68
+ it('fails on missing org_id', () => {
69
+ const json = JSON.stringify({ project_id: 'def' });
70
+ expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
71
+ });
72
+
73
+ it('fails on missing project_id', () => {
74
+ const json = JSON.stringify({ org_id: 'abc' });
75
+ expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
76
+ });
77
+
78
+ it('fails on non-string org_id', () => {
79
+ const json = JSON.stringify({ org_id: 123, project_id: 'def' });
80
+ expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
81
+ });
82
+
83
+ it('fails on non-string project_id', () => {
84
+ const json = JSON.stringify({ org_id: 'abc', project_id: true });
85
+ expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
86
+ });
87
+
88
+ it('fails on invalid JSON', () => {
89
+ expect(() => Effect.runSync(projectKeysFromJSON('not json'))).toThrow();
90
+ });
91
+
92
+ it('accepts empty strings for required fields', () => {
93
+ const json = JSON.stringify({ org_id: '', project_id: '' });
94
+ const result = Effect.runSync(projectKeysFromJSON(json));
95
+ expect(result.orgId).toBe('');
96
+ expect(result.projectId).toBe('');
97
+ });
98
+ });
99
+
100
+ describe('encode to JSON', () => {
101
+ it('encodes ProjectKeys with Some values', () => {
102
+ const keys: ProjectKeys = {
103
+ orgId: 'abc',
104
+ projectId: 'def',
105
+ projectName: Option.some('My Project'),
106
+ orgName: Option.some('My Org'),
107
+ email: Option.some('test@test.com'),
108
+ };
109
+
110
+ const json = Effect.runSync(projectKeysToJSON(keys));
111
+ const parsed = JSON.parse(json);
112
+
113
+ expect(parsed.org_id).toBe('abc');
114
+ expect(parsed.project_id).toBe('def');
115
+ expect(parsed.project_name).toBe('My Project');
116
+ expect(parsed.org_name).toBe('My Org');
117
+ expect(parsed.email).toBe('test@test.com');
118
+ });
119
+
120
+ it('encodes None optional fields as null', () => {
121
+ const keys: ProjectKeys = {
122
+ orgId: 'abc',
123
+ projectId: 'def',
124
+ projectName: Option.none(),
125
+ orgName: Option.none(),
126
+ email: Option.none(),
127
+ };
128
+
129
+ const json = Effect.runSync(projectKeysToJSON(keys));
130
+ const parsed = JSON.parse(json);
131
+
132
+ expect(parsed.org_id).toBe('abc');
133
+ expect(parsed.project_id).toBe('def');
134
+ expect(parsed.project_name).toBeNull();
135
+ expect(parsed.org_name).toBeNull();
136
+ expect(parsed.email).toBeNull();
137
+ });
138
+ });
139
+
140
+ describe('round-trip', () => {
141
+ it('encode then decode preserves Some values', () => {
142
+ const original: ProjectKeys = {
143
+ orgId: 'org-123',
144
+ projectId: 'proj-456',
145
+ projectName: Option.some('Test Project'),
146
+ orgName: Option.some('Test Org'),
147
+ email: Option.some('user@example.com'),
148
+ };
149
+
150
+ const json = Effect.runSync(projectKeysToJSON(original));
151
+ const decoded = Effect.runSync(projectKeysFromJSON(json));
152
+
153
+ expect(decoded.orgId).toBe(original.orgId);
154
+ expect(decoded.projectId).toBe(original.projectId);
155
+ expect(Option.getOrUndefined(decoded.projectName)).toBe(
156
+ Option.getOrUndefined(original.projectName)
157
+ );
158
+ expect(Option.getOrUndefined(decoded.orgName)).toBe(Option.getOrUndefined(original.orgName));
159
+ expect(Option.getOrUndefined(decoded.email)).toBe(Option.getOrUndefined(original.email));
160
+ });
161
+
162
+ it('encode then decode preserves None values', () => {
163
+ const original: ProjectKeys = {
164
+ orgId: 'org-123',
165
+ projectId: 'proj-456',
166
+ projectName: Option.none(),
167
+ orgName: Option.none(),
168
+ email: Option.none(),
169
+ };
170
+
171
+ const json = Effect.runSync(projectKeysToJSON(original));
172
+ const decoded = Effect.runSync(projectKeysFromJSON(json));
173
+
174
+ expect(decoded.orgId).toBe(original.orgId);
175
+ expect(decoded.projectId).toBe(original.projectId);
176
+ expect(Option.isNone(decoded.projectName)).toBe(true);
177
+ expect(Option.isNone(decoded.orgName)).toBe(true);
178
+ expect(Option.isNone(decoded.email)).toBe(true);
179
+ });
180
+ });
181
+});
ts/packages/cli/test/src/services/config.test.ts
+181
@@ -5,6 +5,7 @@ import { Config, ConfigProvider, Effect, Option, Data, LogLevel } from 'effect';
5
import { APP_CONFIG } from 'src/effects/app-config';
6
import { extendConfigProvider } from 'src/services/config';
7
import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
8
+import * as constants from 'src/constants';
9
10
describe('Config', () => {
11
describe('[When] using `ConfigProvider.fromMap`', () => {
@@ -23,9 +24,12 @@ describe('Config', () => {
24
actual,
25
Data.struct({
26
API_KEY: Option.none(),
27
+ ENVIRONMENT: Option.none(),
28
BASE_URL: 'https://backend.composio.dev',
29
CACHE_DIR: Option.none(),
30
LOG_LEVEL: Option.none(),
31
+ ORG_ID: Option.none(),
32
+ PROJECT_ID: Option.none(),
33
WEB_URL: 'https://platform.composio.dev',
34
})
35
);
@@ -47,9 +51,12 @@ describe('Config', () => {
51
actual,
52
Data.struct({
53
API_KEY: Option.none(),
54
+ ENVIRONMENT: Option.none(),
55
BASE_URL: 'https://backend.composio.dev',
56
CACHE_DIR: Option.none(),
57
LOG_LEVEL: Option.none(),
58
+ ORG_ID: Option.none(),
59
+ PROJECT_ID: Option.none(),
60
WEB_URL: 'https://platform.composio.dev',
61
})
62
);
@@ -72,10 +79,129 @@ describe('Config', () => {
79
actual,
80
Data.struct({
81
API_KEY: Option.some('api_key'),
82
+ ENVIRONMENT: Option.none(),
83
BASE_URL: 'https://test.localhost',
84
WEB_URL: 'https://test.localhost',
85
CACHE_DIR: Option.some('~/.composio'),
86
LOG_LEVEL: Option.some(LogLevel.Info),
87
+ ORG_ID: Option.none(),
88
+ PROJECT_ID: Option.none(),
89
+ })
90
+ );
91
+ });
92
+
93
+ it('[When] COMPOSIO_ENVIRONMENT is "production"', () => {
94
+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'production']]) satisfies Map<string, string>;
95
+
96
+ const actual = Effect.runSync(
97
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
98
+ );
99
+
100
+ assertEquals(
101
+ actual,
102
+ Data.struct({
103
+ API_KEY: Option.none(),
104
+ ENVIRONMENT: Option.some('production'),
105
+ BASE_URL: constants.DEFAULT_BASE_URL,
106
+ WEB_URL: constants.DEFAULT_WEB_URL,
107
+ CACHE_DIR: Option.none(),
108
+ LOG_LEVEL: Option.none(),
109
+ ORG_ID: Option.none(),
110
+ PROJECT_ID: Option.none(),
111
+ })
112
+ );
113
+ });
114
+
115
+ it('[When] COMPOSIO_ENVIRONMENT is "staging"', () => {
116
+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'staging']]) satisfies Map<string, string>;
117
+
118
+ const actual = Effect.runSync(
119
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
120
+ );
121
+
122
+ assertEquals(
123
+ actual,
124
+ Data.struct({
125
+ API_KEY: Option.none(),
126
+ ENVIRONMENT: Option.some('staging'),
127
+ BASE_URL: constants.STAGING_BASE_URL,
128
+ WEB_URL: constants.STAGING_WEB_URL,
129
+ CACHE_DIR: Option.none(),
130
+ LOG_LEVEL: Option.none(),
131
+ ORG_ID: Option.none(),
132
+ PROJECT_ID: Option.none(),
133
+ })
134
+ );
135
+ });
136
+
137
+ it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_BASE_URL is set', () => {
138
+ const map = new Map([
139
+ ['COMPOSIO_ENVIRONMENT', 'staging'],
140
+ ['COMPOSIO_BASE_URL', 'https://custom-backend.localhost'],
141
+ ]) satisfies Map<string, string>;
142
+
143
+ const actual = Effect.runSync(
144
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
145
+ );
146
+
147
+ assertEquals(
148
+ actual,
149
+ Data.struct({
150
+ API_KEY: Option.none(),
151
+ ENVIRONMENT: Option.some('staging'),
152
+ BASE_URL: 'https://custom-backend.localhost',
153
+ WEB_URL: constants.STAGING_WEB_URL,
154
+ CACHE_DIR: Option.none(),
155
+ LOG_LEVEL: Option.none(),
156
+ ORG_ID: Option.none(),
157
+ PROJECT_ID: Option.none(),
158
+ })
159
+ );
160
+ });
161
+
162
+ it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_WEB_URL is set', () => {
163
+ const map = new Map([
164
+ ['COMPOSIO_ENVIRONMENT', 'staging'],
165
+ ['COMPOSIO_WEB_URL', 'https://custom-web.localhost'],
166
+ ]) satisfies Map<string, string>;
167
+
168
+ const actual = Effect.runSync(
169
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
170
+ );
171
+
172
+ assertEquals(
173
+ actual,
174
+ Data.struct({
175
+ API_KEY: Option.none(),
176
+ ENVIRONMENT: Option.some('staging'),
177
+ BASE_URL: constants.STAGING_BASE_URL,
178
+ WEB_URL: 'https://custom-web.localhost',
179
+ CACHE_DIR: Option.none(),
180
+ LOG_LEVEL: Option.none(),
181
+ ORG_ID: Option.none(),
182
+ PROJECT_ID: Option.none(),
183
+ })
184
+ );
185
+ });
186
+
187
+ it('[When] COMPOSIO_ENVIRONMENT is an unknown value', () => {
188
+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'unknown']]) satisfies Map<string, string>;
189
+
190
+ const actual = Effect.runSync(
191
+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
192
+ );
193
+
194
+ assertEquals(
195
+ actual,
196
+ Data.struct({
197
+ API_KEY: Option.none(),
198
+ ENVIRONMENT: Option.some('unknown'),
199
+ BASE_URL: constants.DEFAULT_BASE_URL,
200
+ WEB_URL: constants.DEFAULT_WEB_URL,
201
+ CACHE_DIR: Option.none(),
202
+ LOG_LEVEL: Option.none(),
203
+ ORG_ID: Option.none(),
204
+ PROJECT_ID: Option.none(),
205
})
206
);
207
});
@@ -179,10 +305,13 @@ describe('Config', () => {
305
actual,
306
Data.struct({
307
API_KEY: Option.none(),
308
+ ENVIRONMENT: Option.none(),
309
BASE_URL: 'https://backend.composio.dev',
310
WEB_URL: 'https://platform.composio.dev',
311
CACHE_DIR: Option.none(),
312
LOG_LEVEL: Option.none(),
313
+ ORG_ID: Option.none(),
314
+ PROJECT_ID: Option.none(),
315
})
316
);
317
});
@@ -201,10 +330,13 @@ describe('Config', () => {
330
actual,
331
Data.struct({
332
API_KEY: Option.none(),
333
+ ENVIRONMENT: Option.none(),
334
BASE_URL: 'https://backend.composio.dev',
335
WEB_URL: 'https://platform.composio.dev',
336
CACHE_DIR: Option.none(),
337
LOG_LEVEL: Option.none(),
338
+ ORG_ID: Option.none(),
339
+ PROJECT_ID: Option.none(),
340
})
341
);
342
});
@@ -224,10 +356,59 @@ describe('Config', () => {
356
actual,
357
Data.struct({
358
API_KEY: Option.some('api_key'),
359
+ ENVIRONMENT: Option.none(),
360
BASE_URL: 'https://test.localhost',
361
WEB_URL: 'https://test.localhost',
362
CACHE_DIR: Option.some('~/.composio'),
363
LOG_LEVEL: Option.some(LogLevel.Info),
364
+ ORG_ID: Option.none(),
365
+ PROJECT_ID: Option.none(),
366
+ })
367
+ );
368
+ });
369
+
370
+ it('[When] COMPOSIO_ENVIRONMENT is "staging"', () => {
371
+ vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
372
+
373
+ const actual = Effect.runSync(
374
+ withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
375
+ );
376
+
377
+ assertEquals(
378
+ actual,
379
+ Data.struct({
380
+ API_KEY: Option.none(),
381
+ ENVIRONMENT: Option.some('staging'),
382
+ BASE_URL: constants.STAGING_BASE_URL,
383
+ WEB_URL: constants.STAGING_WEB_URL,
384
+ CACHE_DIR: Option.none(),
385
+ LOG_LEVEL: Option.none(),
386
+ ORG_ID: Option.none(),
387
+ PROJECT_ID: Option.none(),
388
+ })
389
+ );
390
+ });
391
+
392
+ it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit URLs override', () => {
393
+ vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
394
+ vi.stubEnv('COMPOSIO_BASE_URL', 'https://custom.localhost');
395
+ vi.stubEnv('COMPOSIO_WEB_URL', 'https://custom-web.localhost');
396
+
397
+ const actual = Effect.runSync(
398
+ withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
399
+ );
400
+
401
+ assertEquals(
402
+ actual,
403
+ Data.struct({
404
+ API_KEY: Option.none(),
405
+ ENVIRONMENT: Option.some('staging'),
406
+ BASE_URL: 'https://custom.localhost',
407
+ WEB_URL: 'https://custom-web.localhost',
408
+ CACHE_DIR: Option.none(),
409
+ LOG_LEVEL: Option.none(),
410
+ ORG_ID: Option.none(),
411
+ PROJECT_ID: Option.none(),
412
})
413
);
414
});
ts/packages/cli/test/src/services/project-environment-detector.test.ts
new
+419
@@ -0,0 +1,419 @@
1
+import path from 'node:path';
2
+import * as tempy from 'tempy';
3
+import { describe, expect, layer, assert } from '@effect/vitest';
4
+import { beforeAll, afterAll } from 'vitest';
5
+import { Effect, Layer, Either } from 'effect';
6
+import { FileSystem } from '@effect/platform';
7
+import { BunFileSystem } from '@effect/platform-bun';
8
+import {
9
+ ProjectEnvironmentDetector,
10
+ ProjectEnvironmentDetectorError,
11
+} from 'src/services/project-environment-detector';
12
+
13
+const testLayer = Layer.provideMerge(ProjectEnvironmentDetector.Default, BunFileSystem.layer);
14
+
15
+const writeFile = (fs: FileSystem.FileSystem, filePath: string, content: string) =>
16
+ Effect.gen(function* () {
17
+ const dir = path.dirname(filePath);
18
+ yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
19
+ yield* fs.writeFileString(filePath, content);
20
+ });
21
+
22
+describe('ProjectEnvironmentDetector', () => {
23
+ let savedUserAgent: string | undefined;
24
+
25
+ beforeAll(() => {
26
+ savedUserAgent = process.env.npm_config_user_agent;
27
+ delete process.env.npm_config_user_agent;
28
+ });
29
+
30
+ afterAll(() => {
31
+ if (savedUserAgent !== undefined) {
32
+ process.env.npm_config_user_agent = savedUserAgent;
33
+ } else {
34
+ delete process.env.npm_config_user_agent;
35
+ }
36
+ });
37
+
38
+ describe('detectProjectEnvironment', () => {
39
+ // -- TypeScript detection --
40
+
41
+ layer(testLayer)('TypeScript detection', it => {
42
+ it.scoped('[Given] package.json + tsconfig.json [Then] detects typescript + npm', () =>
43
+ Effect.gen(function* () {
44
+ const fs = yield* FileSystem.FileSystem;
45
+ const detector = yield* ProjectEnvironmentDetector;
46
+ const cwd = tempy.temporaryDirectory();
47
+
48
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
49
+ yield* writeFile(fs, path.join(cwd, 'tsconfig.json'), '{}');
50
+
51
+ const result = yield* detector.detectProjectEnvironment(cwd);
52
+
53
+ expect(result.kind).toBe('js');
54
+ expect(result.language).toBe('typescript');
55
+ expect(result.packageManager).toBe('npm');
56
+ expect(result.rootDir).toBe(cwd);
57
+ })
58
+ );
59
+
60
+ it.scoped(
61
+ '[Given] pnpm-lock.yaml + package.json with packageManager:pnpm@ [Then] detects typescript + pnpm',
62
+ () =>
63
+ Effect.gen(function* () {
64
+ const fs = yield* FileSystem.FileSystem;
65
+ const detector = yield* ProjectEnvironmentDetector;
66
+ const cwd = tempy.temporaryDirectory();
67
+
68
+ yield* writeFile(
69
+ fs,
70
+ path.join(cwd, 'package.json'),
71
+ JSON.stringify({
72
+ name: 'test-mono',
73
+ packageManager: 'pnpm@9.15.0',
74
+ devDependencies: { typescript: '^5.0.0' },
75
+ })
76
+ );
77
+ yield* writeFile(fs, path.join(cwd, 'pnpm-lock.yaml'), 'lockfileVersion: 9');
78
+ yield* writeFile(fs, path.join(cwd, 'tsconfig.json'), '{}');
79
+
80
+ const result = yield* detector.detectProjectEnvironment(cwd);
81
+
82
+ expect(result.kind).toBe('js');
83
+ expect(result.language).toBe('typescript');
84
+ expect(result.packageManager).toBe('pnpm');
85
+ })
86
+ );
87
+
88
+ it.scoped('[Given] bun.lockb [Then] detects js + bun', () =>
89
+ Effect.gen(function* () {
90
+ const fs = yield* FileSystem.FileSystem;
91
+ const detector = yield* ProjectEnvironmentDetector;
92
+ const cwd = tempy.temporaryDirectory();
93
+
94
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
95
+ yield* writeFile(fs, path.join(cwd, 'bun.lockb'), '');
96
+
97
+ const result = yield* detector.detectProjectEnvironment(cwd);
98
+
99
+ expect(result.kind).toBe('js');
100
+ expect(result.packageManager).toBe('bun');
101
+ })
102
+ );
103
+
104
+ it.scoped('[Given] bun.lock (text format) [Then] detects bun', () =>
105
+ Effect.gen(function* () {
106
+ const fs = yield* FileSystem.FileSystem;
107
+ const detector = yield* ProjectEnvironmentDetector;
108
+ const cwd = tempy.temporaryDirectory();
109
+
110
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
111
+ yield* writeFile(fs, path.join(cwd, 'bun.lock'), '{}');
112
+
113
+ const result = yield* detector.detectProjectEnvironment(cwd);
114
+
115
+ expect(result.kind).toBe('js');
116
+ expect(result.packageManager).toBe('bun');
117
+ })
118
+ );
119
+
120
+ it.scoped('[Given] package.json with typescript dep [Then] detects typescript', () =>
121
+ Effect.gen(function* () {
122
+ const fs = yield* FileSystem.FileSystem;
123
+ const detector = yield* ProjectEnvironmentDetector;
124
+ const cwd = tempy.temporaryDirectory();
125
+
126
+ yield* writeFile(
127
+ fs,
128
+ path.join(cwd, 'package.json'),
129
+ JSON.stringify({ name: 'test', devDependencies: { typescript: '^5.0.0' } })
130
+ );
131
+
132
+ const result = yield* detector.detectProjectEnvironment(cwd);
133
+
134
+ expect(result.kind).toBe('js');
135
+ expect(result.language).toBe('typescript');
136
+ })
137
+ );
138
+
139
+ it.scoped('[Given] monorepo root with pnpm-workspace.yaml [Then] detects pnpm', () =>
140
+ Effect.gen(function* () {
141
+ const fs = yield* FileSystem.FileSystem;
142
+ const detector = yield* ProjectEnvironmentDetector;
143
+ const cwd = tempy.temporaryDirectory();
144
+
145
+ yield* writeFile(
146
+ fs,
147
+ path.join(cwd, 'package.json'),
148
+ JSON.stringify({ name: 'monorepo' })
149
+ );
150
+ yield* writeFile(
151
+ fs,
152
+ path.join(cwd, 'pnpm-workspace.yaml'),
153
+ "packages:\n - 'packages/*'"
154
+ );
155
+ yield* writeFile(fs, path.join(cwd, 'tsconfig.json'), '{}');
156
+
157
+ const result = yield* detector.detectProjectEnvironment(cwd);
158
+
159
+ expect(result.kind).toBe('js');
160
+ expect(result.packageManager).toBe('pnpm');
161
+ })
162
+ );
163
+ });
164
+
165
+ // -- Python detection --
166
+
167
+ layer(testLayer)('Python detection', it => {
168
+ it.scoped('[Given] pyproject.toml with [tool.uv] + uv.lock [Then] detects python + uv', () =>
169
+ Effect.gen(function* () {
170
+ const fs = yield* FileSystem.FileSystem;
171
+ const detector = yield* ProjectEnvironmentDetector;
172
+ const cwd = tempy.temporaryDirectory();
173
+
174
+ yield* writeFile(
175
+ fs,
176
+ path.join(cwd, 'pyproject.toml'),
177
+ '[project]\nname = "test"\n\n[tool.uv]\ndev-dependencies = []'
178
+ );
179
+ yield* writeFile(fs, path.join(cwd, 'uv.lock'), 'version = 1');
180
+
181
+ const result = yield* detector.detectProjectEnvironment(cwd);
182
+
183
+ expect(result.kind).toBe('python');
184
+ expect(result.language).toBe('python');
185
+ expect(result.packageManager).toBe('uv');
186
+ })
187
+ );
188
+
189
+ it.scoped('[Given] requirements.txt only [Then] detects python + pip', () =>
190
+ Effect.gen(function* () {
191
+ const fs = yield* FileSystem.FileSystem;
192
+ const detector = yield* ProjectEnvironmentDetector;
193
+ const cwd = tempy.temporaryDirectory();
194
+
195
+ yield* writeFile(fs, path.join(cwd, 'requirements.txt'), 'composio');
196
+
197
+ const result = yield* detector.detectProjectEnvironment(cwd);
198
+
199
+ expect(result.kind).toBe('python');
200
+ expect(result.language).toBe('python');
201
+ expect(result.packageManager).toBe('pip');
202
+ })
203
+ );
204
+
205
+ it.scoped('[Given] setup.py only [Then] detects python + pip', () =>
206
+ Effect.gen(function* () {
207
+ const fs = yield* FileSystem.FileSystem;
208
+ const detector = yield* ProjectEnvironmentDetector;
209
+ const cwd = tempy.temporaryDirectory();
210
+
211
+ yield* writeFile(
212
+ fs,
213
+ path.join(cwd, 'setup.py'),
214
+ 'from setuptools import setup\nsetup(name="test")'
215
+ );
216
+
217
+ const result = yield* detector.detectProjectEnvironment(cwd);
218
+
219
+ expect(result.kind).toBe('python');
220
+ expect(result.packageManager).toBe('pip');
221
+ })
222
+ );
223
+ });
224
+
225
+ // -- Ambiguity --
226
+
227
+ layer(testLayer)('Ambiguity handling', it => {
228
+ it.scoped(
229
+ '[Given] both package.json + pyproject.toml at CWD [Then] fails with ambiguity error',
230
+ () =>
231
+ Effect.gen(function* () {
232
+ const fs = yield* FileSystem.FileSystem;
233
+ const detector = yield* ProjectEnvironmentDetector;
234
+ const cwd = tempy.temporaryDirectory();
235
+
236
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
237
+ yield* writeFile(fs, path.join(cwd, 'pyproject.toml'), '[project]\nname = "test"');
238
+ yield* writeFile(fs, path.join(cwd, 'requirements.txt'), 'composio');
239
+
240
+ const result = yield* detector.detectProjectEnvironment(cwd).pipe(Effect.either);
241
+
242
+ assert(Either.isLeft(result));
243
+ expect(result.left).toBeInstanceOf(ProjectEnvironmentDetectorError);
244
+ expect(result.left.message).toContain('both');
245
+ })
246
+ );
247
+ });
248
+
249
+ // -- Edge cases --
250
+
251
+ layer(testLayer)('Edge cases', it => {
252
+ it.scoped('[Given] empty directory [Then] fails with no-detection error', () =>
253
+ Effect.gen(function* () {
254
+ const detector = yield* ProjectEnvironmentDetector;
255
+ const cwd = tempy.temporaryDirectory();
256
+
257
+ const result = yield* detector.detectProjectEnvironment(cwd).pipe(Effect.either);
258
+
259
+ assert(Either.isLeft(result));
260
+ expect(result.left.message).toContain('No recognizable');
261
+ })
262
+ );
263
+
264
+ it.scoped('[Given] indicators at parent directory [Then] detects from parent', () =>
265
+ Effect.gen(function* () {
266
+ const fs = yield* FileSystem.FileSystem;
267
+ const detector = yield* ProjectEnvironmentDetector;
268
+ const parentDir = tempy.temporaryDirectory();
269
+ const childDir = path.join(parentDir, 'subdir');
270
+ yield* fs.makeDirectory(childDir, { recursive: true });
271
+
272
+ yield* writeFile(
273
+ fs,
274
+ path.join(parentDir, 'package.json'),
275
+ JSON.stringify({ name: 'parent', packageManager: 'pnpm@9.0.0' })
276
+ );
277
+ yield* writeFile(fs, path.join(parentDir, 'pnpm-lock.yaml'), '');
278
+ yield* writeFile(fs, path.join(parentDir, 'tsconfig.json'), '{}');
279
+
280
+ const result = yield* detector.detectProjectEnvironment(childDir);
281
+
282
+ expect(result.kind).toBe('js');
283
+ expect(result.packageManager).toBe('pnpm');
284
+ expect(result.rootDir).toBe(parentDir);
285
+ })
286
+ );
287
+ });
288
+ });
289
+
290
+ // -- detectJsPackageManager --
291
+
292
+ describe('detectJsPackageManager', () => {
293
+ layer(testLayer)('JS package manager detection', it => {
294
+ it.scoped('[Given] packageManager field in package.json [Then] uses that', () =>
295
+ Effect.gen(function* () {
296
+ const fs = yield* FileSystem.FileSystem;
297
+ const detector = yield* ProjectEnvironmentDetector;
298
+ const cwd = tempy.temporaryDirectory();
299
+
300
+ yield* writeFile(
301
+ fs,
302
+ path.join(cwd, 'package.json'),
303
+ JSON.stringify({ name: 'test', packageManager: 'yarn@4.0.0' })
304
+ );
305
+
306
+ const result = yield* detector.detectJsPackageManager(cwd);
307
+ expect(result).toBe('yarn');
308
+ })
309
+ );
310
+
311
+ it.scoped('[Given] lock file present [Then] detects from lock file', () =>
312
+ Effect.gen(function* () {
313
+ const fs = yield* FileSystem.FileSystem;
314
+ const detector = yield* ProjectEnvironmentDetector;
315
+ const cwd = tempy.temporaryDirectory();
316
+
317
+ yield* writeFile(fs, path.join(cwd, 'package.json'), JSON.stringify({ name: 'test' }));
318
+ yield* writeFile(fs, path.join(cwd, 'yarn.lock'), '');
319
+
320
+ const result = yield* detector.detectJsPackageManager(cwd);
321
+ expect(result).toBe('yarn');
322
+ })
323
+ );
324
+
325
+ it.scoped('[Given] no lock file, no packageManager field [Then] defaults to npm', () =>
326
+ Effect.gen(function* () {
327
+ const detector = yield* ProjectEnvironmentDetector;
328
+ const cwd = tempy.temporaryDirectory();
329
+
330
+ const result = yield* detector.detectJsPackageManager(cwd);
331
+ expect(result).toBe('npm');
332
+ })
333
+ );
334
+
335
+ it.scoped(
336
+ '[Given] no lock file, no packageManager field, but npm_config_user_agent=pnpm [Then] detects pnpm',
337
+ () =>
338
+ Effect.gen(function* () {
339
+ const detector = yield* ProjectEnvironmentDetector;
340
+ const cwd = tempy.temporaryDirectory();
341
+
342
+ process.env.npm_config_user_agent = 'pnpm/9.15.0 npm/? node/v20.11.0';
343
+ try {
344
+ const result = yield* detector.detectJsPackageManager(cwd);
345
+ expect(result).toBe('pnpm');
346
+ } finally {
347
+ delete process.env.npm_config_user_agent;
348
+ }
349
+ })
350
+ );
351
+
352
+ it.scoped(
353
+ '[Given] no lock file, no packageManager field, but npm_config_user_agent=bun [Then] detects bun',
354
+ () =>
355
+ Effect.gen(function* () {
356
+ const detector = yield* ProjectEnvironmentDetector;
357
+ const cwd = tempy.temporaryDirectory();
358
+
359
+ process.env.npm_config_user_agent = 'bun/1.1.0';
360
+ try {
361
+ const result = yield* detector.detectJsPackageManager(cwd);
362
+ expect(result).toBe('bun');
363
+ } finally {
364
+ delete process.env.npm_config_user_agent;
365
+ }
366
+ })
367
+ );
368
+ });
369
+ });
370
+
371
+ // -- detectPythonPackageManager --
372
+
373
+ describe('detectPythonPackageManager', () => {
374
+ layer(testLayer)('Python package manager detection', it => {
375
+ it.scoped('[Given] uv.lock present [Then] detects uv', () =>
376
+ Effect.gen(function* () {
377
+ const fs = yield* FileSystem.FileSystem;
378
+ const detector = yield* ProjectEnvironmentDetector;
379
+ const cwd = tempy.temporaryDirectory();
380
+
381
+ yield* writeFile(fs, path.join(cwd, 'uv.lock'), 'version = 1');
382
+
383
+ const result = yield* detector.detectPythonPackageManager(cwd);
384
+ expect(result).toBe('uv');
385
+ })
386
+ );
387
+
388
+ it.scoped('[Given] [tool.uv] in pyproject.toml [Then] detects uv', () =>
389
+ Effect.gen(function* () {
390
+ const fs = yield* FileSystem.FileSystem;
391
+ const detector = yield* ProjectEnvironmentDetector;
392
+ const cwd = tempy.temporaryDirectory();
393
+
394
+ yield* writeFile(
395
+ fs,
396
+ path.join(cwd, 'pyproject.toml'),
397
+ '[project]\nname = "test"\n\n[tool.uv]\ndev-dependencies = []'
398
+ );
399
+
400
+ const result = yield* detector.detectPythonPackageManager(cwd);
401
+ expect(result).toBe('uv');
402
+ })
403
+ );
404
+
405
+ it.scoped('[Given] no uv indicators [Then] defaults to pip', () =>
406
+ Effect.gen(function* () {
407
+ const fs = yield* FileSystem.FileSystem;
408
+ const detector = yield* ProjectEnvironmentDetector;
409
+ const cwd = tempy.temporaryDirectory();
410
+
411
+ yield* writeFile(fs, path.join(cwd, 'requirements.txt'), 'composio');
412
+
413
+ const result = yield* detector.detectPythonPackageManager(cwd);
414
+ expect(result).toBe('pip');
415
+ })
416
+ );
417
+ });
418
+ });
419
+});
ts/packages/cli/test/src/services/user-context.test.ts
+146
@@ -33,6 +33,8 @@ describe('ComposioUserContext', () => {
33
apiKey: Option.none(),
34
baseURL: 'https://backend.composio.dev',
35
webURL: 'https://platform.composio.dev',
36
+ orgId: Option.none(),
37
+ projectId: Option.none(),
38
});
39
assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
40
assertEquals(ctx.isLoggedIn(), false);
@@ -61,6 +63,8 @@ describe('ComposioUserContext', () => {
63
apiKey: Option.some('api_key'),
64
baseURL: 'https://test.composio.localhost',
65
webURL: 'https://platform.composio.dev',
66
+ orgId: Option.none(),
67
+ projectId: Option.none(),
68
});
69
assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
70
assertEquals(ctx.isLoggedIn(), true);
@@ -87,6 +91,8 @@ describe('ComposioUserContext', () => {
91
apiKey: Option.some('api_key'),
92
baseURL: Option.some('https://test.composio.localhost'),
93
webURL: Option.some('https://platform.composio.dev'),
94
+ orgId: Option.none(),
95
+ projectId: Option.none(),
96
});
97
const userDataAsJson = yield* userDataToJSON(expectedUserData);
98
@@ -124,6 +130,8 @@ describe('ComposioUserContext', () => {
130
apiKey: Option.some('api_key'),
131
baseURL: Option.none(),
132
webURL: Option.some('https://platform.composio.dev'),
133
+ orgId: Option.none(),
134
+ projectId: Option.none(),
135
});
136
const userDataAsJson = yield* userDataToJSON(expectedUserData);
137
@@ -145,5 +153,143 @@ describe('ComposioUserContext', () => {
153
}).pipe(Effect.provide(ComposioUserContextTest));
154
});
155
});
156
+
157
+ describe('[When] the file is empty', () => {
158
+ it('[Then] it falls back to defaults and overwrites the file', () => {
159
+ const cwd = tempy.temporaryDirectory();
160
+ const map = new Map([]) satisfies Map<string, string>;
161
+
162
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
163
+ const ComposioUserContextTest = Layer.provideMerge(
164
+ ComposioUserContextLive,
165
+ Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
166
+ );
167
+
168
+ return Effect.gen(function* () {
169
+ const fs = yield* FileSystem.FileSystem;
170
+ yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
171
+ // Write an empty file
172
+ yield* fs.writeFileString(path.join(cwd, '.composio', 'user_data.json'), '');
173
+
174
+ // Should NOT throw — should fall back to defaults
175
+ const ctx = yield* ComposioUserContext;
176
+
177
+ const expectedUserData = UserDataWithDefaults.make({
178
+ apiKey: Option.none(),
179
+ baseURL: 'https://backend.composio.dev',
180
+ webURL: 'https://platform.composio.dev',
181
+ orgId: Option.none(),
182
+ projectId: Option.none(),
183
+ });
184
+ assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
185
+ assertEquals(ctx.isLoggedIn(), false);
186
+
187
+ // The corrupted file should have been overwritten with valid defaults
188
+ const contents = yield* fs.readFileString(
189
+ path.join(cwd, '.composio', 'user_data.json'),
190
+ 'utf8'
191
+ );
192
+ const parsed = JSON.parse(contents);
193
+ assertEquals(parsed.api_key, null);
194
+ }).pipe(Effect.provide(ComposioUserContextTest));
195
+ });
196
+ });
197
+
198
+ describe('[When] the file contains invalid JSON', () => {
199
+ it('[Then] it falls back to defaults and overwrites the file', () => {
200
+ const cwd = tempy.temporaryDirectory();
201
+ const map = new Map([]) satisfies Map<string, string>;
202
+
203
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
204
+ const ComposioUserContextTest = Layer.provideMerge(
205
+ ComposioUserContextLive,
206
+ Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
207
+ );
208
+
209
+ return Effect.gen(function* () {
210
+ const fs = yield* FileSystem.FileSystem;
211
+ yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
212
+ // Write corrupted JSON
213
+ yield* fs.writeFileString(
214
+ path.join(cwd, '.composio', 'user_data.json'),
215
+ '{not valid json!!!'
216
+ );
217
+
218
+ // Should NOT throw — should fall back to defaults
219
+ const ctx = yield* ComposioUserContext;
220
+
221
+ const expectedUserData = UserDataWithDefaults.make({
222
+ apiKey: Option.none(),
223
+ baseURL: 'https://backend.composio.dev',
224
+ webURL: 'https://platform.composio.dev',
225
+ orgId: Option.none(),
226
+ projectId: Option.none(),
227
+ });
228
+ assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
229
+ assertEquals(ctx.isLoggedIn(), false);
230
+ }).pipe(Effect.provide(ComposioUserContextTest));
231
+ });
232
+ });
233
+
234
+ describe('[When] the file contains valid JSON but wrong schema', () => {
235
+ it('[Then] it falls back to defaults and overwrites the file', () => {
236
+ const cwd = tempy.temporaryDirectory();
237
+ const map = new Map([]) satisfies Map<string, string>;
238
+
239
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
240
+ const ComposioUserContextTest = Layer.provideMerge(
241
+ ComposioUserContextLive,
242
+ Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
243
+ );
244
+
245
+ return Effect.gen(function* () {
246
+ const fs = yield* FileSystem.FileSystem;
247
+ yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
248
+ // Write valid JSON but with wrong schema (api_key should be string|null, not number)
249
+ yield* fs.writeFileString(
250
+ path.join(cwd, '.composio', 'user_data.json'),
251
+ JSON.stringify({ api_key: 12345, unknown_field: true })
252
+ );
253
+
254
+ // Should NOT throw — should fall back to defaults
255
+ const ctx = yield* ComposioUserContext;
256
+
257
+ const expectedUserData = UserDataWithDefaults.make({
258
+ apiKey: Option.none(),
259
+ baseURL: 'https://backend.composio.dev',
260
+ webURL: 'https://platform.composio.dev',
261
+ orgId: Option.none(),
262
+ projectId: Option.none(),
263
+ });
264
+ assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
265
+ assertEquals(ctx.isLoggedIn(), false);
266
+ }).pipe(Effect.provide(ComposioUserContextTest));
267
+ });
268
+ });
269
+
270
+ describe('[When] the file is corrupted but env API_KEY is set', () => {
271
+ it('[Then] it falls back to defaults but preserves env API_KEY', () => {
272
+ const cwd = tempy.temporaryDirectory();
273
+ const map = new Map([['COMPOSIO_API_KEY', 'env_api_key']]) satisfies Map<string, string>;
274
+
275
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
276
+ const ComposioUserContextTest = Layer.provideMerge(
277
+ ComposioUserContextLive,
278
+ Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
279
+ );
280
+
281
+ return Effect.gen(function* () {
282
+ const fs = yield* FileSystem.FileSystem;
283
+ yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
284
+ yield* fs.writeFileString(path.join(cwd, '.composio', 'user_data.json'), '');
285
+
286
+ const ctx = yield* ComposioUserContext;
287
+
288
+ // Despite corrupted file, env API_KEY should still work
289
+ assertEquals(ctx.isLoggedIn(), true);
290
+ assertEquals(Option.getOrUndefined(ctx.data.apiKey), 'env_api_key');
291
+ }).pipe(Effect.provide(ComposioUserContextTest));
292
+ });
293
+ });
294
});
295
});