Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

refactor(ai): deduplicate and improve CLI skills

jkomyno335a3912a88d
diff --git a/.claude/skills/create-cli-e2e/SKILL.md b/.claude/skills/create-cli-e2e/SKILL.md
index 6dc999042..e77662d17 100644
--- a/.claude/skills/create-cli-e2e/SKILL.md
+++ b/.claude/skills/create-cli-e2e/SKILL.md
@@ -1,3 +1,7 @@
+---
+description: Write end-to-end tests for CLI commands using the Docker-based test framework in ts/e2e-tests/cli/.
+---
+
# CLI E2E Test Development
Write, expand, and maintain end-to-end tests for CLI commands in `ts/e2e-tests/cli/`.
@@ -9,6 +13,9 @@ Write, expand, and maintain end-to-end tests for CLI commands in `ts/e2e-tests/c
- Debugging a failing CLI e2e test
- Reviewing whether a CLI command's output contract is properly tested
+For CLI **design** (arguments, flags, help text, UX), see the `create-cli` skill.
+For CLI **implementation** (Effect patterns, services, command registration), see the `implement-cli-command` skill.
+
## Architecture
Each CLI e2e test runs the compiled `composio` binary inside a **scratch Debian Docker container**. The binary is self-contained (built via `bun build --compile`) — no Node, Bun, or pnpm exists in the runtime image.
@@ -25,12 +32,10 @@ Key properties:
### What "piped mode" means for tests
-Inside Docker `sh -c`, the composio binary's stdout is never a TTY. This means `ui.output()` writes to stdout and all Clack decoration is suppressed. Both test groups verify piped-mode behavior:
-
-| Test Group | What It Verifies |
-|---|---|
-| **Command execution** (`composio version`) | stdout contains the data, stderr is empty |
-| **Stdout redirection** (`composio version > out.txt`) | Shell-level redirect captures data into a file; Docker stdout and stderr are both empty |
+Inside Docker, the composio binary's stdout is never a TTY. This triggers the CLI's piped-mode behavior (see `ts/packages/cli/AGENTS.md` § "Output Conventions"):
+- `ui.output()` writes to stdout
+- All Clack decoration is suppressed
+- stderr is empty for successful commands
## File Structure
@@ -68,27 +73,31 @@ ts/e2e-tests/cli/<suite-name>/
}
```
-## Test Patterns
-
-Every test file starts with the same structure:
+## Choosing a Test Pattern
-```typescript
-import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
-import { TIMEOUTS } from '@e2e-tests/utils/const';
-import { describe, it, expect, beforeAll } from 'bun:test';
+Use this decision tree to select the right pattern:
-e2e(import.meta.url, {
- versions: { cli: ['current'] },
- // env: { ... }, // Only if needed
- defineTests: ({ runCmd }) => {
- // Tests here
- },
-});
```
+Does the command need env vars (e.g., COMPOSIO_API_KEY)?
+├─ No → Is the output deterministic (exact value known at test time)?
+│ ├─ Yes → Pattern A (simple command, exact assertions)
+│ └─ No → Pattern D (fuzzy assertions: toContain, toBeGreaterThan)
+└─ Yes → Is the output deterministic given the env?
+ ├─ Yes → Pattern B (env vars + exact assertions)
+ └─ No → Pattern D (env vars + fuzzy assertions)
+
+Are you testing an error case (missing args, invalid input)?
+└─ Yes → Pattern C (non-zero exit code, stderr non-empty)
+
+Does the command perform an action with no machine-readable output?
+└─ Yes → Pattern E (exitCode=0, stdout empty, no redirect test)
+```
+
+## Test Patterns
-### Pattern A: Simple Command, No Env Vars
+### Pattern A: Simple Command, No Env Vars (Canonical)
-For commands that produce deterministic output without needing authentication.
+For commands that produce deterministic output without needing authentication. This is the base pattern — all other patterns are variations of this.
**Reference**: `ts/e2e-tests/cli/version/e2e.test.ts`
@@ -156,14 +165,17 @@ e2e(import.meta.url, {
});
```
+**Structure summary:**
+- Two test groups: **command execution** (stdout has data, stderr empty) + **stdout redirection** (file has data, Docker stdout/stderr both empty)
+- Use `sanitizeOutput()` on stdout and file contents before assertions
+- Use `TIMEOUTS.FIXTURE` for the `beforeAll` that runs Docker commands
+
### Pattern B: Command Requiring Env Vars
-For commands that need authentication or configuration from the host environment.
+**Same as Pattern A**, with three additions:
**Reference**: `ts/e2e-tests/cli/whoami/e2e.test.ts`
-Three additions compared to Pattern A:
-
1. **Type augmentation** for compile-time safety on `Bun.env`:
```typescript
declare module 'bun' {
@@ -187,99 +199,21 @@ Three additions compared to Pattern A:
The rest follows the same two-group structure (command execution + stdout redirection).
-**Full example:**
-
-```typescript
-/**
- * CLI whoami command e2e test
- *
- * Verifies that the compiled composio CLI prints the API key in a scratch container.
- */
-
-import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
-import { TIMEOUTS } from '@e2e-tests/utils/const';
-import { describe, it, expect, beforeAll } from 'bun:test';
-
-declare module 'bun' {
- interface Env {
- COMPOSIO_API_KEY: string;
- }
-}
-
-e2e(import.meta.url, {
- versions: {
- cli: ['current'],
- },
- env: {
- COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
- },
- defineTests: ({ runCmd }) => {
- const expectedApiKey = Bun.env.COMPOSIO_API_KEY.trim();
- let whoamiResult: E2ETestResult;
- let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
-
- beforeAll(async () => {
- whoamiResult = await runCmd('composio whoami');
- redirectedResult = await runCmd({
- command: 'composio whoami > out.txt',
- files: ['out.txt'],
- });
- }, TIMEOUTS.FIXTURE);
-
- describe('composio whoami', () => {
- it('exits successfully', () => {
- expect(whoamiResult.exitCode).toBe(0);
- });
-
- it('stdout contains the API key', () => {
- expect(sanitizeOutput(whoamiResult.stdout)).toBe(expectedApiKey);
- });
-
- it('stderr is empty', () => {
- expect(whoamiResult.stderr).toBe('');
- });
- });
-
- describe('stdout redirection to out.txt', () => {
- it('exits successfully', () => {
- expect(redirectedResult.exitCode).toBe(0);
- });
-
- it('stdout is empty', () => {
- expect(redirectedResult.stdout).toBe('');
- });
-
- it('stderr is empty', () => {
- expect(redirectedResult.stderr).toBe('');
- });
-
- it('out.txt contains the API key', () => {
- expect(sanitizeOutput(redirectedResult.files['out.txt'])).toBe(expectedApiKey);
- });
- });
- },
-});
-```
-
### Pattern C: Error Case Testing
-For verifying that the CLI fails gracefully with correct exit codes and error messages.
+**Differences from Pattern A:**
+- No stdout redirection test needed — error cases don't produce data output
+- Assert non-zero exit code with `not.toBe(0)` (don't hardcode a specific error code)
+- Assert stderr is non-empty; optionally use `toContain()` for specific error message fragments
+- Import only `E2ETestResult`, not `E2ETestResultWithFiles`
```typescript
-/**
- * CLI tools-info error case e2e test
- *
- * Verifies that the CLI fails gracefully when required arguments are missing.
- */
-
import { e2e, sanitizeOutput, type E2ETestResult } from '@e2e-tests/utils';
import { TIMEOUTS } from '@e2e-tests/utils/const';
import { describe, it, expect, beforeAll } from 'bun:test';
e2e(import.meta.url, {
- versions: {
- cli: ['current'],
- },
+ versions: { cli: ['current'] },
defineTests: ({ runCmd }) => {
let missingArgResult: E2ETestResult;
@@ -300,122 +234,42 @@ e2e(import.meta.url, {
});
```
-Notes:
-- No stdout redirection test needed — error cases don't produce data output.
-- Use `not.toBe(0)` for exit code rather than a specific number (the CLI may change error codes).
-- Assert stderr is non-empty; optionally use `toContain()` for specific error message fragments.
+Pattern C can be combined with A or B in the same test file to test both success and error paths.
### Pattern D: Multi-line / API-dependent Output
-For commands that call the Composio API and return dynamic, multi-line data.
-
-```typescript
-/**
- * CLI toolkits-list command e2e test
- *
- * Verifies that the CLI lists available toolkits from the API.
- */
-
-import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
-import { TIMEOUTS } from '@e2e-tests/utils/const';
-import { describe, it, expect, beforeAll } from 'bun:test';
-
-declare module 'bun' {
- interface Env {
- COMPOSIO_API_KEY: string;
- }
-}
-
-e2e(import.meta.url, {
- versions: {
- cli: ['current'],
- },
- env: {
- COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
- },
- defineTests: ({ runCmd }) => {
- let listResult: E2ETestResult;
- let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
-
- beforeAll(async () => {
- listResult = await runCmd('composio toolkits list');
- redirectedResult = await runCmd({
- command: 'composio toolkits list > out.txt',
- files: ['out.txt'],
- });
- }, TIMEOUTS.FIXTURE);
-
- describe('composio toolkits list', () => {
- it('exits successfully', () => {
- expect(listResult.exitCode).toBe(0);
- });
-
- it('stdout is non-empty', () => {
- expect(sanitizeOutput(listResult.stdout).length).toBeGreaterThan(0);
- });
-
- it('stdout contains known toolkits', () => {
- const output = sanitizeOutput(listResult.stdout);
- // Use well-known toolkits that are always present
- expect(output).toContain('github');
- });
-
- it('stdout has multiple lines', () => {
- const lines = sanitizeOutput(listResult.stdout).split('\n').filter(Boolean);
- expect(lines.length).toBeGreaterThan(1);
- });
-
- it('stderr is empty', () => {
- expect(listResult.stderr).toBe('');
- });
- });
-
- describe('stdout redirection to out.txt', () => {
- it('exits successfully', () => {
- expect(redirectedResult.exitCode).toBe(0);
- });
+**Same structure as Pattern A or B** (depending on whether env vars are needed), with different assertion strategies:
- it('stdout is empty', () => {
- expect(redirectedResult.stdout).toBe('');
- });
-
- it('stderr is empty', () => {
- expect(redirectedResult.stderr).toBe('');
- });
-
- it('out.txt contains data', () => {
- expect(sanitizeOutput(redirectedResult.files['out.txt']).length).toBeGreaterThan(0);
- });
- });
- },
-});
-```
-
-Key rules for API-dependent output:
- **Never use exact-match assertions** (`toBe`) on API data — the data changes over time.
- Use `toContain()` for known, stable items (e.g., `github`, `gmail` are always present).
- Use `toBeGreaterThan()` for structural checks (line count, length).
- Use `toMatch()` with regex for format validation.
+```typescript
+// Instead of:
+expect(sanitizeOutput(listResult.stdout)).toBe(exactValue);
+
+// Use fuzzy assertions:
+expect(sanitizeOutput(listResult.stdout).length).toBeGreaterThan(0);
+expect(sanitizeOutput(listResult.stdout)).toContain('github');
+const lines = sanitizeOutput(listResult.stdout).split('\n').filter(Boolean);
+expect(lines.length).toBeGreaterThan(1);
+```
+
+The redirect test group is identical to Pattern A — assert the file contains data, Docker stdout/stderr are empty.
+
### Pattern E: Action Command, No Stdout Data
For commands that perform an action but produce no machine-readable output (e.g., `logout`, `upgrade`).
-```typescript
-/**
- * CLI logout command e2e test
- *
- * Verifies that the CLI logout command completes without error.
- */
-
-import { e2e, type E2ETestResult } from '@e2e-tests/utils';
-import { TIMEOUTS } from '@e2e-tests/utils/const';
-import { describe, it, expect, beforeAll } from 'bun:test';
+**Differences from Pattern A:**
+- No redirection test — there's no data to redirect
+- stdout should be literally empty (no `sanitizeOutput()` needed)
+- Import only `E2ETestResult`, not `E2ETestResultWithFiles`
+```typescript
e2e(import.meta.url, {
- versions: {
- cli: ['current'],
- },
+ versions: { cli: ['current'] },
defineTests: ({ runCmd }) => {
let logoutResult: E2ETestResult;
@@ -440,20 +294,6 @@ e2e(import.meta.url, {
});
```
-Notes:
-- No redirection test needed — there's no data to redirect.
-- No `sanitizeOutput()` needed — stdout should be literally empty.
-- Import only `E2ETestResult`, not `E2ETestResultWithFiles`.
-
-## Output Contract Rules
-
-Enforce these in every CLI e2e test:
-
-1. **Data commands** produce machine-readable output on stdout (via `ui.output()`).
-2. **Action commands** produce no stdout data — stdout is always empty.
-3. **stderr is always empty** for successful commands (non-TTY suppresses all Clack decoration).
-4. **Redirected output** (`> out.txt`) captures the same data that direct stdout contains; Docker stdout and stderr both become empty.
-
## Commands NOT Testable with This Framework
Do not attempt to write e2e tests for:
@@ -557,20 +397,6 @@ runCmd('composio logout && composio whoami')
## API Reference
-### `e2e(importMetaUrl, config)`
-
-Entry point. Pass `import.meta.url` as the first argument — the framework infers `cwd` and `suiteName` from the file path.
-
-### `E2EConfig`
-
-```typescript
-{
- versions: { cli: ['current'] }, // Always use ['current'] for CLI tests
- env?: Record<string, string | undefined>, // Env vars to pass to Docker
- defineTests: (ctx: DefineTestsContext) => void,
-}
-```
-
### `runCmd` (two overloads)
```typescript
@@ -585,12 +411,10 @@ const result: E2ETestResultWithFiles<'out.txt'> = await runCmd({
// Access: result.files['out.txt']
```
-### `sanitizeOutput(output)`
-
-Strips ANSI escape codes, normalizes `\r\n` to `\n`, trims whitespace. Use on stdout and file contents before assertions.
-
### `TIMEOUTS`
+Defined in `ts/e2e-tests/_utils/src/const.ts`:
+
```typescript
TIMEOUTS.DEFAULT // 5_000ms — individual test timeout
TIMEOUTS.FIXTURE // 120_000ms — beforeAll timeout (Docker startup + command execution)
@@ -607,10 +431,9 @@ Use `TIMEOUTS.FIXTURE` for the `beforeAll` that runs Docker commands. Use `TIMEO
| `ts/e2e-tests/cli/version/e2e.test.ts` | Pattern A reference |
| `ts/e2e-tests/cli/whoami/e2e.test.ts` | Pattern B reference |
| `ts/e2e-tests/_utils/src/types.ts` | `E2EConfig`, `E2ETestResult`, `DefineTestsContext` types |
-| `ts/e2e-tests/_utils/src/e2e.ts` | `e2e()` entry point |
| `ts/e2e-tests/_utils/src/const.ts` | `TIMEOUTS`, `WELL_KNOWN_ENV_VARS` |
| `ts/e2e-tests/_utils/src/sanitize.ts` | `sanitizeOutput()` |
| `ts/e2e-tests/_utils/Dockerfile.cli` | Docker image definition |
| `ts/e2e-tests/cli/README.md` | Test suites table |
| `CLI.md` | Planned CLI commands |
-| `ts/packages/cli/CLAUDE.md` | CLI architecture and output conventions |
+| `ts/packages/cli/AGENTS.md` | CLI architecture and output conventions |
diff --git a/.claude/skills/create-cli/SKILL.md b/.claude/skills/create-cli/SKILL.md
deleted file mode 120000
index bb37a9f12..000000000
--- a/.claude/skills/create-cli/SKILL.md
+++ /dev/null
@@ -1 +0,0 @@
-../../../ts/packages/cli/.cursor/rules/cli-design-guidelines.mdc
\ No newline at end of file
diff --git a/.claude/skills/create-cli/SKILL.md b/.claude/skills/create-cli/SKILL.md
new file mode 100644
index 000000000..43e911d3a
--- /dev/null
+++ b/.claude/skills/create-cli/SKILL.md
@@ -0,0 +1,240 @@
+---
+description: CLI design guidelines — arguments, flags, subcommands, help, output, errors, interactivity, config precedence. Apply when designing new commands or reviewing CLI UX.
+globs:
+ - "ts/packages/cli/src/**/*.ts"
+alwaysApply: false
+---
+
+# CLI Design Guidelines
+
+Design CLI surface area (syntax + behavior), human-first, script-friendly.
+Adapted from [clig.dev](https://clig.dev/) for our TypeScript + Effect.ts + Clack stack.
+
+## When to Use
+
+- Designing a CLI spec (before implementation) or refactoring CLI surface area.
+- Adding new commands, flags, or interactive prompts.
+- Reviewing CLI UX decisions.
+
+After designing a command, use the `implement-cli-command` skill to build it.
+After implementation, use the `create-cli-e2e` skill to write end-to-end tests.
+
+## Stack & Architecture
+
+See `ts/packages/cli/AGENTS.md` for the full architecture reference, including dependencies, services, effects, and vendor submodule locations.
+
+## Output Conventions
+
+The CLI separates human-readable decoration from machine-readable data. See `ts/packages/cli/AGENTS.md` § "Output Conventions" for the full specification.
+
+Key rule: when adding a command, ask "Does this produce a value scripts should capture?"
+- **Yes** → `ui.output(value)` for data, `ui.log.*` / `ui.note()` for context.
+- **No** → Only `ui.log.*` / `ui.note()` / `ui.intro()` / `ui.outro()`.
+
+**Show state changes.** When a command modifies state, say what changed and the new state:
+
+```typescript
+// After logout:
+yield* ui.log.info('Removed API key from ~/.composio/user-config.json');
+
+// After generate:
+yield* ui.log.success('Generated 42 tools across 5 toolkits → src/generated/');
+```
+
+## Arguments & Flags
+
+Define options via `@effect/cli`:
+
+```typescript
+const toolkits = Options.text('toolkits').pipe(
+ Options.optional,
+ Options.withDescription('Comma-separated toolkit slugs'),
+);
+const force = Options.boolean('force').pipe(
+ Options.withAlias('f'),
+ Options.withDefault(false),
+);
+```
+
+Principles:
+- Prefer flags over positional args for clarity and extensibility.
+- Provide long versions of all flags; one-letter aliases only for the most common.
+- Default values should be right for most users.
+- Never accept secrets via flags — they leak to `ps` output and shell history. Use `--password-file`, stdin, or a secret manager instead.
+- Support `-` for stdin/stdout when input/output is a file path.
+
+Standard flag names:
+
+| Flag | Short | Purpose |
+| ---- | ----- | ------- |
+| `--help` | `-h` | Show help (built-in via @effect/cli) |
+| `--version` | | Print version to stdout |
+| `--quiet` | `-q` | Less output |
+| `--verbose` | `-v` | More output (never use `-v` for version) |
+| `--debug` | `-d` | Debug output |
+| `--force` | `-f` | Skip confirmations |
+| `--dry-run` | `-n` | Preview only |
+| `--json` | | Structured output |
+| `--output` | `-o` | Output file path |
+| `--no-input` | | Disable prompts; fail if required input missing |
+| `--no-browser` | | Skip browser-open steps |
+| `--no-color` | | Disable color output |
+
+## Subcommands
+
+```typescript
+const login = Command.make('login', { noBrowser }, handler);
+const generate = Command.make('generate', { toolkits, typeTools }, handler);
+const root = Command.make('composio').pipe(
+ Command.withSubcommands([login, generate, /* ... */]),
+);
+```
+
+- Follow verb-noun pattern consistently: `composio login`, `composio generate`.
+- Share global flags via parent command composition.
+- Support `composio help <subcmd>` and `composio <subcmd> --help`.
+- Avoid ambiguous pairs (`update` vs `upgrade`) unless sharply differentiated.
+
+## Interactivity
+
+Use `@clack/prompts` for all interactive UI. All Clack output goes to stderr via `{ output: process.stderr }`.
+
+| Prompt | When to use |
+| ------ | ----------- |
+| `text()` | Free-form text input |
+| `password()` | Secret input (echo disabled) |
+| `confirm()` | Yes/no decisions |
+| `select()` | Choose one from a list |
+| `multiselect()` | Choose multiple from a list |
+| `spinner()` | Long-running operations |
+| `log.info/warn/error/step()` | Styled status messages |
+| `note()` | Boxed contextual info |
+| `intro()` / `outro()` | Session start/end markers |
+
+Rules:
+- Prompt only if stdin is a TTY.
+- `--no-input`: never prompt; fail with actionable message if required input missing.
+- Make escape hatches obvious (Ctrl-C).
+- Destructive operations: interactive confirmation + non-interactive requires `--force`.
+
+## Error Handling
+
+- Use the `effect-errors/` module for capture and formatting.
+- Catch and rewrite expected errors for humans; no stack traces by default.
+- Put the most important info last; use red intentionally.
+- For unexpected crashes: provide debug info path + bug report instructions.
+
+**Write actionable error messages.** Tell the user *what went wrong* and *how to fix it*:
+
+```
+// Bad:
+Error: EACCES
+
+// Good:
+Can't write to ~/.composio/user-config.json.
+You might need to fix permissions: chmod +w ~/.composio/user-config.json
+
+// Bad:
+Error: 401
+
+// Good:
+API key is invalid or expired.
+Run `composio login` to authenticate again.
+```
+
+**Suggest corrections** when the user mistypes a subcommand or flag. If they ran `composio genrate`, suggest `composio generate`.
+
+Exit codes:
+
+| Code | Meaning |
+| ---- | ------- |
+| `0` | Success |
+| `1` | Generic failure |
+| `2` | Invalid usage (parse/validation error) |
+
+## Help & Documentation
+
+- `@effect/cli` generates help text from Command/Options declarations.
+- If run with missing required args, show concise help + 1–2 examples + "use --help for more".
+- Lead with examples; show common flags first.
+- Link to docs URL per subcommand when applicable.
+- Provide both terminal help (offline, version-synced) and web docs (searchable, linkable).
+
+Good help text structure:
+
+```
+USAGE
+ $ composio generate [--toolkits <slugs>] [--type-tools]
+
+OPTIONS
+ --toolkits <slugs> Comma-separated toolkit slugs (default: all)
+ --type-tools Generate full type definitions
+ -o, --output <dir> Output directory (default: @composio/core/generated)
+
+EXAMPLES
+ $ composio generate
+ $ composio generate --toolkits github,slack --type-tools
+
+COMMANDS
+ composio ts generate Generate TypeScript stubs
+ composio py generate Generate Python stubs
+```
+
+**Suggest next commands** when it helps the user's flow:
+
+```
+✔ Logged in as [email protected]
+ Next: run `composio generate` to generate type stubs for your toolkits.
+```
+
+## Configuration Precedence
+
+High to low: **flags > process env > project config > user config > system config**.
+
+- Composio prefixes: `COMPOSIO_*` for app config, `DEBUG_OVERRIDE_*` for debug.
+- User config stored in `~/.composio/`.
+- Respect common env vars: `NO_COLOR`, `DEBUG`, `EDITOR`, `PAGER`, `TERM`, `TMPDIR`, `HOME`.
+
+## Naming
+
+- Subcommand names: simple, lowercase, single word when possible.
+- Avoid too-generic names that collide with system tools.
+- Keep names short but not cryptic — easy to type matters.
+- Never create implicit catch-all subcommands that prevent future expansion.
+- Don't allow arbitrary abbreviations (reserving `g` for `generate` blocks future `g`-commands).
+- Use explicit aliases only when there's a clear, stable mapping.
+
+## Robustness & Performance
+
+- Validate early; fail fast with good error messages.
+- Print something within ~100ms (especially before network I/O). Start a Clack spinner immediately before any network call.
+- Show progress for long tasks (interactive only) via Clack spinners.
+- Use timeouts for network calls; allow configuration.
+- Make reruns safe: idempotent where possible; recoverable on failure.
+- **Crash-only design**: assume cleanup might not run. Defer cleanup to the next invocation rather than relying on shutdown hooks. If a cache file is half-written, the next run should detect and rebuild it.
+
+## Example Invocations
+
+```bash
+# Interactive — user sees Clack decoration on stderr
+composio login
+composio generate --toolkits github,slack
+
+# Piped — only data on stdout, no decoration
+composio whoami | pbcopy
+API_KEY=$(composio whoami)
+composio version | cat
+
+# Non-interactive with force
+composio logout --force --no-input
+
+# Debug mode
+composio generate --debug --verbose
+```
+
+## References
+
+- Community CLI Guidelines: https://clig.dev/
+- CLI architecture: `ts/packages/cli/AGENTS.md`
+- @effect/cli source: `ts/vendor/effect/packages/cli/src/`
+- @clack/prompts source: `ts/vendor/clack/packages/prompts/src/`
diff --git a/.claude/skills/implement-cli-command/SKILL.md b/.claude/skills/implement-cli-command/SKILL.md
index 7d5a11bff..12d9a6b38 100644
--- a/.claude/skills/implement-cli-command/SKILL.md
+++ b/.claude/skills/implement-cli-command/SKILL.md
@@ -1,3 +1,7 @@
+---
+description: Implement new CLI commands in ts/packages/cli/ using Effect.ts patterns, service wiring, and @effect/cli declarations.
+---
+
# Implement CLI Command
Implement new commands and subcommands in `ts/packages/cli/`. Covers file creation, Effect patterns, service wiring, option declaration, output conventions, and registration.
@@ -16,6 +20,8 @@ For CLI **e2e tests**, see the `create-cli-e2e` skill instead.
The CLI uses `@effect/cli` for command declaration, `effect` for the runtime, and a service-oriented architecture with dependency injection via Effect layers.
+See `ts/packages/cli/AGENTS.md` for the full architecture reference (services, effects, models, dependencies, vendor submodule locations).
+
```
src/
├── bin.ts # Entry point — layer composition, error handling, runtime
@@ -160,7 +166,7 @@ const layers = Layer.mergeAll(
);
```
-Most commands only use services already provided: `TerminalUI`, `ComposioUserContext`, `ComposioToolkitsRepository`, `ComposioSessionRepository`, `UpgradeBinary`, `FileSystem`, `NodeProcess`, `NodeOs`.
+Most commands only use services already provided. The `ComposioToolkitsRepository` service is provided by `ComposioToolkitsRepositoryCachedLive` in `bin.ts` — you do not need to add a separate layer for the base repository.
## Creating a Subcommand Group
@@ -247,9 +253,11 @@ const $cmd = $defaultCmd.pipe(
## Option Declaration Patterns
-Options are declared at module level using `@effect/cli`'s `Options` API.
+Options are declared at module level using `@effect/cli`'s `Options` API. The template above demonstrates the most common types (required text, optional text). For other option types, see `ts/vendor/effect/packages/cli/src/Options.ts`.
-### Common Option Types
+Both `Options.optional(Options.text(...))` (wrapping) and `Options.text(...).pipe(Options.optional)` (piped) are valid. Use whichever reads better.
+
+### Common patterns:
```typescript
import { Options } from '@effect/cli';
@@ -260,18 +268,6 @@ const verbose = Options.boolean('verbose').pipe(
Options.withDescription('Enable verbose output.')
);
-// Required text
-const name = Options.text('name').pipe(
- Options.withDescription('Name of the resource.')
-);
-
-// Optional text — yields Option<string> in handler
-const search = Options.optional(
- Options.text('search')
-).pipe(
- Options.withDescription('Search query.')
-);
-
// Text with alias
const output = Options.optional(
Options.text('output')
@@ -280,136 +276,50 @@ const output = Options.optional(
Options.withDescription('Output path.')
);
-// Repeated text — yields Array<string>
-const toolkits = Options.text('toolkits').pipe(
- Options.repeated,
- Options.withDescription('One or more toolkit slugs.')
-);
-
// Choice from fixed set
const format = Options.choice('format', ['json', 'table', 'plain']).pipe(
Options.withDefault('table'),
Options.withDescription('Output format.')
);
-
-// Directory path (with existence check)
-const dir = Options.optional(
- Options.directory('output-dir', { exists: 'either' })
-).pipe(
- Options.withAlias('o'),
- Options.withDescription('Output directory.')
-);
-
-// Schema-validated option
-import { Schema } from 'effect';
-
-const limit = Options.integer('limit').pipe(
- Options.withSchema(Schema.Int.pipe(Schema.positive())),
- Options.withDefault(10),
- Options.withDescription('Max results.')
-);
```
### Using Options in Handler
```typescript
-Command.make('my-cmd', { search, verbose, toolkits }, ({ search, verbose, toolkits }) =>
- Effect.gen(function* () {
- // search: Option<string> — use Option.getOrUndefined, Option.match, Option.isSome
- const searchValue = Option.getOrUndefined(search);
-
- // verbose: boolean — direct use
- if (verbose) { yield* Effect.logDebug('Verbose mode'); }
+Command.make('my-cmd', { search, verbose }).pipe(
+ Command.withHandler(({ search, verbose }) =>
+ Effect.gen(function* () {
+ // search: Option<string> — use Option.getOrUndefined, Option.match, Option.isSome
+ const searchValue = Option.getOrUndefined(search);
- // toolkits: Array<string> — may be empty
- if (Array.isNonEmptyArray(toolkits)) {
- // filter by toolkits
- }
- })
-)
+ // verbose: boolean — direct use
+ if (verbose) { yield* Effect.logDebug('Verbose mode'); }
+ })
+ )
+);
```
## Output Conventions
-Every command must follow the composable CLI output contract:
-
-### Data Commands
+Follow the output conventions in `ts/packages/cli/AGENTS.md` § "Output Conventions" (stdout for data via `ui.output()`, stderr for decoration).
-Commands that produce a value scripts should capture:
+**Data commands** — produce a value scripts should capture:
```typescript
yield* ui.note(apiKey, 'API Key'); // Decoration → stderr (pretty box)
yield* ui.output(apiKey); // Data → stdout (scripts capture)
```
-### Action Commands
-
-Commands that perform a side effect but produce no data:
+**Action commands** — perform a side effect, no data:
```typescript
yield* ui.log.success('Logged out successfully.');
// NO ui.output() call — nothing for scripts to capture
```
-### Rule: Never Mix
+## TerminalUI Spinners
-- Never write data to stderr (decoration methods only)
-- Never write decoration to stdout (ui.output only)
-- `ui.output()` is a no-op in interactive mode (TTY) and writes to stdout when piped
-
-## Available Services
-
-Resolve services in handlers with `yield* ServiceName`.
-
-| Service | Import | Purpose |
-|---|---|---|
-| `TerminalUI` | `src/services/terminal-ui` | Output: `output()`, `log.*`, `note()`, `intro()`, `outro()`, spinners |
-| `ComposioUserContext` | `src/services/user-context` | Auth state: `data.apiKey`, `isLoggedIn()`, `logout` |
-| `ComposioToolkitsRepository` | `src/services/composio-clients` | API: `getToolkits()`, `getTools()`, `getTriggerTypes()`, `validateToolkits()` |
-| `ComposioSessionRepository` | `src/services/composio-clients` | OAuth: `createSession()`, `getSession()` |
-| `UpgradeBinary` | `src/services/upgrade-binary` | Self-update: `upgrade()` |
-| `FileSystem.FileSystem` | `@effect/platform` | File I/O: `readFileString()`, `writeFileString()`, `exists()` |
-| `NodeProcess` | `src/services/node-process` | Process info: `cwd`, `env` |
-| `NodeOs` | `src/services/node-os` | OS info: `homedir()`, `platform()`, `arch()` |
-| `EnvLangDetector` | `src/services/env-lang-detector` | Detect project language (TS/Python) |
-| `JsPackageManagerDetector` | `src/services/js-package-manager-detector` | Detect npm/pnpm/yarn/bun |
-
-## Available Effects
-
-Reusable computations from `src/effects/`:
-
-| Effect | Import | Purpose |
-|---|---|---|
-| `getVersion` | `src/effects/version` | CLI version from package.json |
-| `logMetrics` | `src/effects/log-metrics` | Log API request count and bytes |
-| `setupCacheDir` | `src/effects/setup-cache-dir` | Ensure `~/.composio/` exists |
-| `getToolkitVersionOverrides` | `src/effects/toolkit-version-overrides` | Parse `COMPOSIO_TOOLKIT_VERSION_*` env vars |
-| `jsFindComposioCoreGenerated` | `src/effects/find-composio-core-generated` | Locate `@composio/core` in node_modules |
-| `compareSemver` | `src/effects/compare-semver` | Semantic version comparison |
-
-## TerminalUI API
-
-### Output
-
-```typescript
-yield* ui.output(data); // Machine-readable data → stdout when piped, no-op when interactive
-```
-
-### Decoration (all → stderr when interactive, suppressed when piped)
-
-```typescript
-yield* ui.intro('composio my-command'); // Opening banner
-yield* ui.outro('Done'); // Closing banner
-yield* ui.note(content, 'Title'); // Boxed note
-yield* ui.log.info('message'); // Blue info
-yield* ui.log.success('message'); // Green success
-yield* ui.log.warn('message'); // Yellow warning
-yield* ui.log.error('message'); // Red error
-yield* ui.log.step('message'); // Green checkmark step
-yield* ui.log.message('message'); // With vertical bar
-```
-
-### Spinners
+The `TerminalUI` service provides two spinner APIs. For output/decoration methods (`output`, `log.*`, `note`, `intro`, `outro`), see `ts/packages/cli/src/services/terminal-ui.ts`.
```typescript
// Automatic: wraps an Effect, auto-stops on success/error
@@ -432,6 +342,16 @@ const result = yield* ui.useMakeSpinner('Loading...', spinner =>
);
```
+## Creating a New Service
+
+If your command requires functionality not covered by existing services (see `ts/packages/cli/AGENTS.md` for the full list):
+
+1. Define the service interface and tag in `src/services/<name>.ts`
+2. Create a `Live` layer implementation
+3. Register the layer in `src/bin.ts`
+
+Reference `src/services/upgrade-binary.ts` for a simple service pattern, or `src/services/composio-clients.ts` for a complex one with caching.
+
## Error Handling Patterns
### Optional Values
@@ -440,7 +360,10 @@ const result = yield* ui.useMakeSpinner('Loading...', spinner =>
yield* ctx.data.apiKey.pipe(
Option.match({
onNone: () => ui.log.warn('Not logged in. Run `composio login`.'),
- onSome: apiKey => ui.output(apiKey),
+ onSome: apiKey =>
+ Effect.gen(function* () {
+ yield* ui.output(apiKey);
+ }),
})
);
```
@@ -458,14 +381,6 @@ yield* client.getToolkitsBySlugs(slugs).pipe(
);
```
-### Error Transformation
-
-```typescript
-yield* fs.writeFileString(path, content).pipe(
- Effect.mapError(err => new Error(`Failed to write ${path}: ${err}`))
-);
-```
-
### Logging Non-Fatal Errors
```typescript
@@ -558,6 +473,8 @@ When implementing a new command:
7. If using a new service, add its layer to `src/bin.ts`
8. Build to verify: `cd ts/packages/cli && pnpm build`
+If the build fails, check for: (1) missing service imports, (2) `Option<string>` being used where `string` is expected (use `Option.getOrUndefined` or `Option.match`), (3) the command not being exported from its file.
+
## Reference Files
| File | Purpose |
@@ -573,4 +490,4 @@ When implementing a new command:
| `src/bin.ts` | Entry point, layer composition, error handling |
| `src/services/terminal-ui.ts` | TerminalUI service interface |
| `src/services/composio-clients.ts` | API client service (HTTP, pagination, metrics) |
-| `ts/packages/cli/CLAUDE.md` | CLI architecture and output conventions |
+| `ts/packages/cli/AGENTS.md` | CLI architecture, services, effects, output conventions |
diff --git a/ts/packages/cli/AGENTS.md b/ts/packages/cli/AGENTS.md
index 9f190113f..b7fb1084f 100644
--- a/ts/packages/cli/AGENTS.md
+++ b/ts/packages/cli/AGENTS.md
@@ -285,7 +285,7 @@ When working on CLI code, reference the Effect source for accurate patterns:
For principles on how to design CLI interactions (arguments, flags, help text, output, errors, interactivity, config precedence), see:
-- **Full guidelines**: `ts/packages/cli/.cursor/rules/cli-design-guidelines.mdc`
-- **Also available as**: `.claude/skills/create-cli/SKILL.md` (symlink)
+- **Cursor rules**: `ts/packages/cli/.cursor/rules/cli-design-guidelines.mdc`
+- **Claude skill**: `.claude/skills/create-cli/SKILL.md` (standalone, trimmed for Claude Code context)
Use these guidelines when adding new commands, designing flag interfaces, or making UX decisions for the CLI.