@devries-cameron20 / composio-1 / commits / 335a3912a
Fork 0

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

refactor(ai): deduplicate and improve CLI skills

- Break create-cli symlink to Cursor rule; create standalone SKILL.md with corrected globs (ts/packages/cli/src/**/*.ts) and alwaysApply: false - Add YAML frontmatter with description to create-cli-e2e and implement-cli-command for skill discovery - Replace duplicated output conventions with AGENTS.md references - Add bidirectional cross-references across all three skills - Deduplicate e2e patterns B-E as deltas from canonical Pattern A - Add decision flowchart for choosing e2e test patterns - Standardize on Command.withHandler() pipe pattern - Add ComposioToolkitsRepositoryCached note and service creation guide - Trim generic CLI wisdom, unused CLI Spec Template, over-long option docs - Add build failure troubleshooting to implementation checklist - Update AGENTS.md cross-reference to reflect standalone skill file Total: 1516 → 1172 lines (-23%)

jkomyno committed Feb 18, 2026 at 16:51 UTC 335a3912a88de009bcb250188fc778657beef43b
5 files changed +352 -373
.claude/skills/create-cli-e2e/SKILL.md
+67 -244
@@ -1,3 +1,7 @@
1 +---
2 +description: Write end-to-end tests for CLI commands using the Docker-based test framework in ts/e2e-tests/cli/.
3 +---
4 +
5 # CLI E2E Test Development
6
7 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
13 - Debugging a failing CLI e2e test
14 - Reviewing whether a CLI command's output contract is properly tested
15
16 +For CLI **design** (arguments, flags, help text, UX), see the `create-cli` skill.
17 +For CLI **implementation** (Effect patterns, services, command registration), see the `implement-cli-command` skill.
18 +
19 ## Architecture
20
21 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:
32
33 ### What "piped mode" means for tests
34
28 -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:
29 -
30 -| Test Group | What It Verifies |
31 -|---|---|
32 -| **Command execution** (`composio version`) | stdout contains the data, stderr is empty |
33 -| **Stdout redirection** (`composio version > out.txt`) | Shell-level redirect captures data into a file; Docker stdout and stderr are both empty |
35 +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"):
36 +- `ui.output()` writes to stdout
37 +- All Clack decoration is suppressed
38 +- stderr is empty for successful commands
39
40 ## File Structure
41
@@ -68,27 +73,31 @@ ts/e2e-tests/cli/<suite-name>/
73 }
74 ```
75
71 -## Test Patterns
72 -
73 -Every test file starts with the same structure:
76 +## Choosing a Test Pattern
77
75 -```typescript
76 -import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
77 -import { TIMEOUTS } from '@e2e-tests/utils/const';
78 -import { describe, it, expect, beforeAll } from 'bun:test';
78 +Use this decision tree to select the right pattern:
79
80 -e2e(import.meta.url, {
81 - versions: { cli: ['current'] },
82 - // env: { ... }, // Only if needed
83 - defineTests: ({ runCmd }) => {
84 - // Tests here
85 - },
86 -});
80 ```
81 +Does the command need env vars (e.g., COMPOSIO_API_KEY)?
82 +├─ No → Is the output deterministic (exact value known at test time)?
83 +│ ├─ Yes → Pattern A (simple command, exact assertions)
84 +│ └─ No → Pattern D (fuzzy assertions: toContain, toBeGreaterThan)
85 +└─ Yes → Is the output deterministic given the env?
86 + ├─ Yes → Pattern B (env vars + exact assertions)
87 + └─ No → Pattern D (env vars + fuzzy assertions)
88 +
89 +Are you testing an error case (missing args, invalid input)?
90 +└─ Yes → Pattern C (non-zero exit code, stderr non-empty)
91 +
92 +Does the command perform an action with no machine-readable output?
93 +└─ Yes → Pattern E (exitCode=0, stdout empty, no redirect test)
94 +```
95 +
96 +## Test Patterns
97
89 -### Pattern A: Simple Command, No Env Vars
98 +### Pattern A: Simple Command, No Env Vars (Canonical)
99
91 -For commands that produce deterministic output without needing authentication.
100 +For commands that produce deterministic output without needing authentication. This is the base pattern — all other patterns are variations of this.
101
102 **Reference**: `ts/e2e-tests/cli/version/e2e.test.ts`
103
@@ -156,14 +165,17 @@ e2e(import.meta.url, {
165 });
166 ```
167
168 +**Structure summary:**
169 +- Two test groups: **command execution** (stdout has data, stderr empty) + **stdout redirection** (file has data, Docker stdout/stderr both empty)
170 +- Use `sanitizeOutput()` on stdout and file contents before assertions
171 +- Use `TIMEOUTS.FIXTURE` for the `beforeAll` that runs Docker commands
172 +
173 ### Pattern B: Command Requiring Env Vars
174
161 -For commands that need authentication or configuration from the host environment.
175 +**Same as Pattern A**, with three additions:
176
177 **Reference**: `ts/e2e-tests/cli/whoami/e2e.test.ts`
178
165 -Three additions compared to Pattern A:
166 -
179 1. **Type augmentation** for compile-time safety on `Bun.env`:
180 ```typescript
181 declare module 'bun' {
@@ -187,99 +199,21 @@ Three additions compared to Pattern A:
199
200 The rest follows the same two-group structure (command execution + stdout redirection).
201
190 -**Full example:**
191 -
192 -```typescript
193 -/**
194 - * CLI whoami command e2e test
195 - *
196 - * Verifies that the compiled composio CLI prints the API key in a scratch container.
197 - */
198 -
199 -import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
200 -import { TIMEOUTS } from '@e2e-tests/utils/const';
201 -import { describe, it, expect, beforeAll } from 'bun:test';
202 -
203 -declare module 'bun' {
204 - interface Env {
205 - COMPOSIO_API_KEY: string;
206 - }
207 -}
208 -
209 -e2e(import.meta.url, {
210 - versions: {
211 - cli: ['current'],
212 - },
213 - env: {
214 - COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
215 - },
216 - defineTests: ({ runCmd }) => {
217 - const expectedApiKey = Bun.env.COMPOSIO_API_KEY.trim();
218 - let whoamiResult: E2ETestResult;
219 - let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
220 -
221 - beforeAll(async () => {
222 - whoamiResult = await runCmd('composio whoami');
223 - redirectedResult = await runCmd({
224 - command: 'composio whoami > out.txt',
225 - files: ['out.txt'],
226 - });
227 - }, TIMEOUTS.FIXTURE);
228 -
229 - describe('composio whoami', () => {
230 - it('exits successfully', () => {
231 - expect(whoamiResult.exitCode).toBe(0);
232 - });
233 -
234 - it('stdout contains the API key', () => {
235 - expect(sanitizeOutput(whoamiResult.stdout)).toBe(expectedApiKey);
236 - });
237 -
238 - it('stderr is empty', () => {
239 - expect(whoamiResult.stderr).toBe('');
240 - });
241 - });
242 -
243 - describe('stdout redirection to out.txt', () => {
244 - it('exits successfully', () => {
245 - expect(redirectedResult.exitCode).toBe(0);
246 - });
247 -
248 - it('stdout is empty', () => {
249 - expect(redirectedResult.stdout).toBe('');
250 - });
251 -
252 - it('stderr is empty', () => {
253 - expect(redirectedResult.stderr).toBe('');
254 - });
255 -
256 - it('out.txt contains the API key', () => {
257 - expect(sanitizeOutput(redirectedResult.files['out.txt'])).toBe(expectedApiKey);
258 - });
259 - });
260 - },
261 -});
262 -```
263 -
202 ### Pattern C: Error Case Testing
203
266 -For verifying that the CLI fails gracefully with correct exit codes and error messages.
204 +**Differences from Pattern A:**
205 +- No stdout redirection test needed — error cases don't produce data output
206 +- Assert non-zero exit code with `not.toBe(0)` (don't hardcode a specific error code)
207 +- Assert stderr is non-empty; optionally use `toContain()` for specific error message fragments
208 +- Import only `E2ETestResult`, not `E2ETestResultWithFiles`
209
210 ```typescript
269 -/**
270 - * CLI tools-info error case e2e test
271 - *
272 - * Verifies that the CLI fails gracefully when required arguments are missing.
273 - */
274 -
211 import { e2e, sanitizeOutput, type E2ETestResult } from '@e2e-tests/utils';
212 import { TIMEOUTS } from '@e2e-tests/utils/const';
213 import { describe, it, expect, beforeAll } from 'bun:test';
214
215 e2e(import.meta.url, {
280 - versions: {
281 - cli: ['current'],
282 - },
216 + versions: { cli: ['current'] },
217 defineTests: ({ runCmd }) => {
218 let missingArgResult: E2ETestResult;
219
@@ -300,122 +234,42 @@ e2e(import.meta.url, {
234 });
235 ```
236
303 -Notes:
304 -- No stdout redirection test needed — error cases don't produce data output.
305 -- Use `not.toBe(0)` for exit code rather than a specific number (the CLI may change error codes).
306 -- Assert stderr is non-empty; optionally use `toContain()` for specific error message fragments.
237 +Pattern C can be combined with A or B in the same test file to test both success and error paths.
238
239 ### Pattern D: Multi-line / API-dependent Output
240
310 -For commands that call the Composio API and return dynamic, multi-line data.
311 -
312 -```typescript
313 -/**
314 - * CLI toolkits-list command e2e test
315 - *
316 - * Verifies that the CLI lists available toolkits from the API.
317 - */
318 -
319 -import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
320 -import { TIMEOUTS } from '@e2e-tests/utils/const';
321 -import { describe, it, expect, beforeAll } from 'bun:test';
322 -
323 -declare module 'bun' {
324 - interface Env {
325 - COMPOSIO_API_KEY: string;
326 - }
327 -}
328 -
329 -e2e(import.meta.url, {
330 - versions: {
331 - cli: ['current'],
332 - },
333 - env: {
334 - COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
335 - },
336 - defineTests: ({ runCmd }) => {
337 - let listResult: E2ETestResult;
338 - let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
339 -
340 - beforeAll(async () => {
341 - listResult = await runCmd('composio toolkits list');
342 - redirectedResult = await runCmd({
343 - command: 'composio toolkits list > out.txt',
344 - files: ['out.txt'],
345 - });
346 - }, TIMEOUTS.FIXTURE);
347 -
348 - describe('composio toolkits list', () => {
349 - it('exits successfully', () => {
350 - expect(listResult.exitCode).toBe(0);
351 - });
352 -
353 - it('stdout is non-empty', () => {
354 - expect(sanitizeOutput(listResult.stdout).length).toBeGreaterThan(0);
355 - });
356 -
357 - it('stdout contains known toolkits', () => {
358 - const output = sanitizeOutput(listResult.stdout);
359 - // Use well-known toolkits that are always present
360 - expect(output).toContain('github');
361 - });
362 -
363 - it('stdout has multiple lines', () => {
364 - const lines = sanitizeOutput(listResult.stdout).split('\n').filter(Boolean);
365 - expect(lines.length).toBeGreaterThan(1);
366 - });
367 -
368 - it('stderr is empty', () => {
369 - expect(listResult.stderr).toBe('');
370 - });
371 - });
372 -
373 - describe('stdout redirection to out.txt', () => {
374 - it('exits successfully', () => {
375 - expect(redirectedResult.exitCode).toBe(0);
376 - });
241 +**Same structure as Pattern A or B** (depending on whether env vars are needed), with different assertion strategies:
242
378 - it('stdout is empty', () => {
379 - expect(redirectedResult.stdout).toBe('');
380 - });
381 -
382 - it('stderr is empty', () => {
383 - expect(redirectedResult.stderr).toBe('');
384 - });
385 -
386 - it('out.txt contains data', () => {
387 - expect(sanitizeOutput(redirectedResult.files['out.txt']).length).toBeGreaterThan(0);
388 - });
389 - });
390 - },
391 -});
392 -```
393 -
394 -Key rules for API-dependent output:
243 - **Never use exact-match assertions** (`toBe`) on API data — the data changes over time.
244 - Use `toContain()` for known, stable items (e.g., `github`, `gmail` are always present).
245 - Use `toBeGreaterThan()` for structural checks (line count, length).
246 - Use `toMatch()` with regex for format validation.
247
248 +```typescript
249 +// Instead of:
250 +expect(sanitizeOutput(listResult.stdout)).toBe(exactValue);
251 +
252 +// Use fuzzy assertions:
253 +expect(sanitizeOutput(listResult.stdout).length).toBeGreaterThan(0);
254 +expect(sanitizeOutput(listResult.stdout)).toContain('github');
255 +const lines = sanitizeOutput(listResult.stdout).split('\n').filter(Boolean);
256 +expect(lines.length).toBeGreaterThan(1);
257 +```
258 +
259 +The redirect test group is identical to Pattern A — assert the file contains data, Docker stdout/stderr are empty.
260 +
261 ### Pattern E: Action Command, No Stdout Data
262
263 For commands that perform an action but produce no machine-readable output (e.g., `logout`, `upgrade`).
264
404 -```typescript
405 -/**
406 - * CLI logout command e2e test
407 - *
408 - * Verifies that the CLI logout command completes without error.
409 - */
410 -
411 -import { e2e, type E2ETestResult } from '@e2e-tests/utils';
412 -import { TIMEOUTS } from '@e2e-tests/utils/const';
413 -import { describe, it, expect, beforeAll } from 'bun:test';
265 +**Differences from Pattern A:**
266 +- No redirection test — there's no data to redirect
267 +- stdout should be literally empty (no `sanitizeOutput()` needed)
268 +- Import only `E2ETestResult`, not `E2ETestResultWithFiles`
269
270 +```typescript
271 e2e(import.meta.url, {
416 - versions: {
417 - cli: ['current'],
418 - },
272 + versions: { cli: ['current'] },
273 defineTests: ({ runCmd }) => {
274 let logoutResult: E2ETestResult;
275
@@ -440,20 +294,6 @@ e2e(import.meta.url, {
294 });
295 ```
296
443 -Notes:
444 -- No redirection test needed — there's no data to redirect.
445 -- No `sanitizeOutput()` needed — stdout should be literally empty.
446 -- Import only `E2ETestResult`, not `E2ETestResultWithFiles`.
447 -
448 -## Output Contract Rules
449 -
450 -Enforce these in every CLI e2e test:
451 -
452 -1. **Data commands** produce machine-readable output on stdout (via `ui.output()`).
453 -2. **Action commands** produce no stdout data — stdout is always empty.
454 -3. **stderr is always empty** for successful commands (non-TTY suppresses all Clack decoration).
455 -4. **Redirected output** (`> out.txt`) captures the same data that direct stdout contains; Docker stdout and stderr both become empty.
456 -
297 ## Commands NOT Testable with This Framework
298
299 Do not attempt to write e2e tests for:
@@ -557,20 +397,6 @@ runCmd('composio logout && composio whoami')
397
398 ## API Reference
399
560 -### `e2e(importMetaUrl, config)`
561 -
562 -Entry point. Pass `import.meta.url` as the first argument — the framework infers `cwd` and `suiteName` from the file path.
563 -
564 -### `E2EConfig`
565 -
566 -```typescript
567 -{
568 - versions: { cli: ['current'] }, // Always use ['current'] for CLI tests
569 - env?: Record<string, string | undefined>, // Env vars to pass to Docker
570 - defineTests: (ctx: DefineTestsContext) => void,
571 -}
572 -```
573 -
400 ### `runCmd` (two overloads)
401
402 ```typescript
@@ -585,12 +411,10 @@ const result: E2ETestResultWithFiles<'out.txt'> = await runCmd({
411 // Access: result.files['out.txt']
412 ```
413
588 -### `sanitizeOutput(output)`
589 -
590 -Strips ANSI escape codes, normalizes `\r\n` to `\n`, trims whitespace. Use on stdout and file contents before assertions.
591 -
414 ### `TIMEOUTS`
415
416 +Defined in `ts/e2e-tests/_utils/src/const.ts`:
417 +
418 ```typescript
419 TIMEOUTS.DEFAULT // 5_000ms — individual test timeout
420 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
431 | `ts/e2e-tests/cli/version/e2e.test.ts` | Pattern A reference |
432 | `ts/e2e-tests/cli/whoami/e2e.test.ts` | Pattern B reference |
433 | `ts/e2e-tests/_utils/src/types.ts` | `E2EConfig`, `E2ETestResult`, `DefineTestsContext` types |
610 -| `ts/e2e-tests/_utils/src/e2e.ts` | `e2e()` entry point |
434 | `ts/e2e-tests/_utils/src/const.ts` | `TIMEOUTS`, `WELL_KNOWN_ENV_VARS` |
435 | `ts/e2e-tests/_utils/src/sanitize.ts` | `sanitizeOutput()` |
436 | `ts/e2e-tests/_utils/Dockerfile.cli` | Docker image definition |
437 | `ts/e2e-tests/cli/README.md` | Test suites table |
438 | `CLI.md` | Planned CLI commands |
616 -| `ts/packages/cli/CLAUDE.md` | CLI architecture and output conventions |
439 +| `ts/packages/cli/AGENTS.md` | CLI architecture and output conventions |
.claude/skills/create-cli/SKILL.md deleted
-1
@@ -1 +0,0 @@
1 -../../../ts/packages/cli/.cursor/rules/cli-design-guidelines.mdc
\ No newline at end of file
.claude/skills/create-cli/SKILL.md new
+240
@@ -0,0 +1,240 @@
1 +---
2 +description: CLI design guidelines — arguments, flags, subcommands, help, output, errors, interactivity, config precedence. Apply when designing new commands or reviewing CLI UX.
3 +globs:
4 + - "ts/packages/cli/src/**/*.ts"
5 +alwaysApply: false
6 +---
7 +
8 +# CLI Design Guidelines
9 +
10 +Design CLI surface area (syntax + behavior), human-first, script-friendly.
11 +Adapted from [clig.dev](https://clig.dev/) for our TypeScript + Effect.ts + Clack stack.
12 +
13 +## When to Use
14 +
15 +- Designing a CLI spec (before implementation) or refactoring CLI surface area.
16 +- Adding new commands, flags, or interactive prompts.
17 +- Reviewing CLI UX decisions.
18 +
19 +After designing a command, use the `implement-cli-command` skill to build it.
20 +After implementation, use the `create-cli-e2e` skill to write end-to-end tests.
21 +
22 +## Stack & Architecture
23 +
24 +See `ts/packages/cli/AGENTS.md` for the full architecture reference, including dependencies, services, effects, and vendor submodule locations.
25 +
26 +## Output Conventions
27 +
28 +The CLI separates human-readable decoration from machine-readable data. See `ts/packages/cli/AGENTS.md` § "Output Conventions" for the full specification.
29 +
30 +Key rule: when adding a command, ask "Does this produce a value scripts should capture?"
31 +- **Yes** → `ui.output(value)` for data, `ui.log.*` / `ui.note()` for context.
32 +- **No** → Only `ui.log.*` / `ui.note()` / `ui.intro()` / `ui.outro()`.
33 +
34 +**Show state changes.** When a command modifies state, say what changed and the new state:
35 +
36 +```typescript
37 +// After logout:
38 +yield* ui.log.info('Removed API key from ~/.composio/user-config.json');
39 +
40 +// After generate:
41 +yield* ui.log.success('Generated 42 tools across 5 toolkits → src/generated/');
42 +```
43 +
44 +## Arguments & Flags
45 +
46 +Define options via `@effect/cli`:
47 +
48 +```typescript
49 +const toolkits = Options.text('toolkits').pipe(
50 + Options.optional,
51 + Options.withDescription('Comma-separated toolkit slugs'),
52 +);
53 +const force = Options.boolean('force').pipe(
54 + Options.withAlias('f'),
55 + Options.withDefault(false),
56 +);
57 +```
58 +
59 +Principles:
60 +- Prefer flags over positional args for clarity and extensibility.
61 +- Provide long versions of all flags; one-letter aliases only for the most common.
62 +- Default values should be right for most users.
63 +- Never accept secrets via flags — they leak to `ps` output and shell history. Use `--password-file`, stdin, or a secret manager instead.
64 +- Support `-` for stdin/stdout when input/output is a file path.
65 +
66 +Standard flag names:
67 +
68 +| Flag | Short | Purpose |
69 +| ---- | ----- | ------- |
70 +| `--help` | `-h` | Show help (built-in via @effect/cli) |
71 +| `--version` | | Print version to stdout |
72 +| `--quiet` | `-q` | Less output |
73 +| `--verbose` | `-v` | More output (never use `-v` for version) |
74 +| `--debug` | `-d` | Debug output |
75 +| `--force` | `-f` | Skip confirmations |
76 +| `--dry-run` | `-n` | Preview only |
77 +| `--json` | | Structured output |
78 +| `--output` | `-o` | Output file path |
79 +| `--no-input` | | Disable prompts; fail if required input missing |
80 +| `--no-browser` | | Skip browser-open steps |
81 +| `--no-color` | | Disable color output |
82 +
83 +## Subcommands
84 +
85 +```typescript
86 +const login = Command.make('login', { noBrowser }, handler);
87 +const generate = Command.make('generate', { toolkits, typeTools }, handler);
88 +const root = Command.make('composio').pipe(
89 + Command.withSubcommands([login, generate, /* ... */]),
90 +);
91 +```
92 +
93 +- Follow verb-noun pattern consistently: `composio login`, `composio generate`.
94 +- Share global flags via parent command composition.
95 +- Support `composio help <subcmd>` and `composio <subcmd> --help`.
96 +- Avoid ambiguous pairs (`update` vs `upgrade`) unless sharply differentiated.
97 +
98 +## Interactivity
99 +
100 +Use `@clack/prompts` for all interactive UI. All Clack output goes to stderr via `{ output: process.stderr }`.
101 +
102 +| Prompt | When to use |
103 +| ------ | ----------- |
104 +| `text()` | Free-form text input |
105 +| `password()` | Secret input (echo disabled) |
106 +| `confirm()` | Yes/no decisions |
107 +| `select()` | Choose one from a list |
108 +| `multiselect()` | Choose multiple from a list |
109 +| `spinner()` | Long-running operations |
110 +| `log.info/warn/error/step()` | Styled status messages |
111 +| `note()` | Boxed contextual info |
112 +| `intro()` / `outro()` | Session start/end markers |
113 +
114 +Rules:
115 +- Prompt only if stdin is a TTY.
116 +- `--no-input`: never prompt; fail with actionable message if required input missing.
117 +- Make escape hatches obvious (Ctrl-C).
118 +- Destructive operations: interactive confirmation + non-interactive requires `--force`.
119 +
120 +## Error Handling
121 +
122 +- Use the `effect-errors/` module for capture and formatting.
123 +- Catch and rewrite expected errors for humans; no stack traces by default.
124 +- Put the most important info last; use red intentionally.
125 +- For unexpected crashes: provide debug info path + bug report instructions.
126 +
127 +**Write actionable error messages.** Tell the user *what went wrong* and *how to fix it*:
128 +
129 +```
130 +// Bad:
131 +Error: EACCES
132 +
133 +// Good:
134 +Can't write to ~/.composio/user-config.json.
135 +You might need to fix permissions: chmod +w ~/.composio/user-config.json
136 +
137 +// Bad:
138 +Error: 401
139 +
140 +// Good:
141 +API key is invalid or expired.
142 +Run `composio login` to authenticate again.
143 +```
144 +
145 +**Suggest corrections** when the user mistypes a subcommand or flag. If they ran `composio genrate`, suggest `composio generate`.
146 +
147 +Exit codes:
148 +
149 +| Code | Meaning |
150 +| ---- | ------- |
151 +| `0` | Success |
152 +| `1` | Generic failure |
153 +| `2` | Invalid usage (parse/validation error) |
154 +
155 +## Help & Documentation
156 +
157 +- `@effect/cli` generates help text from Command/Options declarations.
158 +- If run with missing required args, show concise help + 1–2 examples + "use --help for more".
159 +- Lead with examples; show common flags first.
160 +- Link to docs URL per subcommand when applicable.
161 +- Provide both terminal help (offline, version-synced) and web docs (searchable, linkable).
162 +
163 +Good help text structure:
164 +
165 +```
166 +USAGE
167 + $ composio generate [--toolkits <slugs>] [--type-tools]
168 +
169 +OPTIONS
170 + --toolkits <slugs> Comma-separated toolkit slugs (default: all)
171 + --type-tools Generate full type definitions
172 + -o, --output <dir> Output directory (default: @composio/core/generated)
173 +
174 +EXAMPLES
175 + $ composio generate
176 + $ composio generate --toolkits github,slack --type-tools
177 +
178 +COMMANDS
179 + composio ts generate Generate TypeScript stubs
180 + composio py generate Generate Python stubs
181 +```
182 +
183 +**Suggest next commands** when it helps the user's flow:
184 +
185 +```
186 +✔ Logged in as user@example.com
187 + Next: run `composio generate` to generate type stubs for your toolkits.
188 +```
189 +
190 +## Configuration Precedence
191 +
192 +High to low: **flags > process env > project config > user config > system config**.
193 +
194 +- Composio prefixes: `COMPOSIO_*` for app config, `DEBUG_OVERRIDE_*` for debug.
195 +- User config stored in `~/.composio/`.
196 +- Respect common env vars: `NO_COLOR`, `DEBUG`, `EDITOR`, `PAGER`, `TERM`, `TMPDIR`, `HOME`.
197 +
198 +## Naming
199 +
200 +- Subcommand names: simple, lowercase, single word when possible.
201 +- Avoid too-generic names that collide with system tools.
202 +- Keep names short but not cryptic — easy to type matters.
203 +- Never create implicit catch-all subcommands that prevent future expansion.
204 +- Don't allow arbitrary abbreviations (reserving `g` for `generate` blocks future `g`-commands).
205 +- Use explicit aliases only when there's a clear, stable mapping.
206 +
207 +## Robustness & Performance
208 +
209 +- Validate early; fail fast with good error messages.
210 +- Print something within ~100ms (especially before network I/O). Start a Clack spinner immediately before any network call.
211 +- Show progress for long tasks (interactive only) via Clack spinners.
212 +- Use timeouts for network calls; allow configuration.
213 +- Make reruns safe: idempotent where possible; recoverable on failure.
214 +- **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.
215 +
216 +## Example Invocations
217 +
218 +```bash
219 +# Interactive — user sees Clack decoration on stderr
220 +composio login
221 +composio generate --toolkits github,slack
222 +
223 +# Piped — only data on stdout, no decoration
224 +composio whoami | pbcopy
225 +API_KEY=$(composio whoami)
226 +composio version | cat
227 +
228 +# Non-interactive with force
229 +composio logout --force --no-input
230 +
231 +# Debug mode
232 +composio generate --debug --verbose
233 +```
234 +
235 +## References
236 +
237 +- Community CLI Guidelines: https://clig.dev/
238 +- CLI architecture: `ts/packages/cli/AGENTS.md`
239 +- @effect/cli source: `ts/vendor/effect/packages/cli/src/`
240 +- @clack/prompts source: `ts/vendor/clack/packages/prompts/src/`
.claude/skills/implement-cli-command/SKILL.md
+43 -126
@@ -1,3 +1,7 @@
1 +---
2 +description: Implement new CLI commands in ts/packages/cli/ using Effect.ts patterns, service wiring, and @effect/cli declarations.
3 +---
4 +
5 # Implement CLI Command
6
7 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.
20
21 The CLI uses `@effect/cli` for command declaration, `effect` for the runtime, and a service-oriented architecture with dependency injection via Effect layers.
22
23 +See `ts/packages/cli/AGENTS.md` for the full architecture reference (services, effects, models, dependencies, vendor submodule locations).
24 +
25 ```
26 src/
27 ├── bin.ts # Entry point — layer composition, error handling, runtime
@@ -160,7 +166,7 @@ const layers = Layer.mergeAll(
166 );
167 ```
168
163 -Most commands only use services already provided: `TerminalUI`, `ComposioUserContext`, `ComposioToolkitsRepository`, `ComposioSessionRepository`, `UpgradeBinary`, `FileSystem`, `NodeProcess`, `NodeOs`.
169 +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.
170
171 ## Creating a Subcommand Group
172
@@ -247,9 +253,11 @@ const $cmd = $defaultCmd.pipe(
253
254 ## Option Declaration Patterns
255
250 -Options are declared at module level using `@effect/cli`'s `Options` API.
256 +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`.
257
252 -### Common Option Types
258 +Both `Options.optional(Options.text(...))` (wrapping) and `Options.text(...).pipe(Options.optional)` (piped) are valid. Use whichever reads better.
259 +
260 +### Common patterns:
261
262 ```typescript
263 import { Options } from '@effect/cli';
@@ -260,18 +268,6 @@ const verbose = Options.boolean('verbose').pipe(
268 Options.withDescription('Enable verbose output.')
269 );
270
263 -// Required text
264 -const name = Options.text('name').pipe(
265 - Options.withDescription('Name of the resource.')
266 -);
267 -
268 -// Optional text — yields Option<string> in handler
269 -const search = Options.optional(
270 - Options.text('search')
271 -).pipe(
272 - Options.withDescription('Search query.')
273 -);
274 -
271 // Text with alias
272 const output = Options.optional(
273 Options.text('output')
@@ -280,136 +276,50 @@ const output = Options.optional(
276 Options.withDescription('Output path.')
277 );
278
283 -// Repeated text — yields Array<string>
284 -const toolkits = Options.text('toolkits').pipe(
285 - Options.repeated,
286 - Options.withDescription('One or more toolkit slugs.')
287 -);
288 -
279 // Choice from fixed set
280 const format = Options.choice('format', ['json', 'table', 'plain']).pipe(
281 Options.withDefault('table'),
282 Options.withDescription('Output format.')
283 );
294 -
295 -// Directory path (with existence check)
296 -const dir = Options.optional(
297 - Options.directory('output-dir', { exists: 'either' })
298 -).pipe(
299 - Options.withAlias('o'),
300 - Options.withDescription('Output directory.')
301 -);
302 -
303 -// Schema-validated option
304 -import { Schema } from 'effect';
305 -
306 -const limit = Options.integer('limit').pipe(
307 - Options.withSchema(Schema.Int.pipe(Schema.positive())),
308 - Options.withDefault(10),
309 - Options.withDescription('Max results.')
310 -);
284 ```
285
286 ### Using Options in Handler
287
288 ```typescript
316 -Command.make('my-cmd', { search, verbose, toolkits }, ({ search, verbose, toolkits }) =>
317 - Effect.gen(function* () {
318 - // search: Option<string> — use Option.getOrUndefined, Option.match, Option.isSome
319 - const searchValue = Option.getOrUndefined(search);
320 -
321 - // verbose: boolean — direct use
322 - if (verbose) { yield* Effect.logDebug('Verbose mode'); }
289 +Command.make('my-cmd', { search, verbose }).pipe(
290 + Command.withHandler(({ search, verbose }) =>
291 + Effect.gen(function* () {
292 + // search: Option<string> — use Option.getOrUndefined, Option.match, Option.isSome
293 + const searchValue = Option.getOrUndefined(search);
294
324 - // toolkits: Array<string> — may be empty
325 - if (Array.isNonEmptyArray(toolkits)) {
326 - // filter by toolkits
327 - }
328 - })
329 -)
295 + // verbose: boolean — direct use
296 + if (verbose) { yield* Effect.logDebug('Verbose mode'); }
297 + })
298 + )
299 +);
300 ```
301
302 ## Output Conventions
303
334 -Every command must follow the composable CLI output contract:
335 -
336 -### Data Commands
304 +Follow the output conventions in `ts/packages/cli/AGENTS.md` § "Output Conventions" (stdout for data via `ui.output()`, stderr for decoration).
305
338 -Commands that produce a value scripts should capture:
306 +**Data commands** — produce a value scripts should capture:
307
308 ```typescript
309 yield* ui.note(apiKey, 'API Key'); // Decoration → stderr (pretty box)
310 yield* ui.output(apiKey); // Data → stdout (scripts capture)
311 ```
312
345 -### Action Commands
346 -
347 -Commands that perform a side effect but produce no data:
313 +**Action commands** — perform a side effect, no data:
314
315 ```typescript
316 yield* ui.log.success('Logged out successfully.');
317 // NO ui.output() call — nothing for scripts to capture
318 ```
319
354 -### Rule: Never Mix
320 +## TerminalUI Spinners
321
356 -- Never write data to stderr (decoration methods only)
357 -- Never write decoration to stdout (ui.output only)
358 -- `ui.output()` is a no-op in interactive mode (TTY) and writes to stdout when piped
359 -
360 -## Available Services
361 -
362 -Resolve services in handlers with `yield* ServiceName`.
363 -
364 -| Service | Import | Purpose |
365 -|---|---|---|
366 -| `TerminalUI` | `src/services/terminal-ui` | Output: `output()`, `log.*`, `note()`, `intro()`, `outro()`, spinners |
367 -| `ComposioUserContext` | `src/services/user-context` | Auth state: `data.apiKey`, `isLoggedIn()`, `logout` |
368 -| `ComposioToolkitsRepository` | `src/services/composio-clients` | API: `getToolkits()`, `getTools()`, `getTriggerTypes()`, `validateToolkits()` |
369 -| `ComposioSessionRepository` | `src/services/composio-clients` | OAuth: `createSession()`, `getSession()` |
370 -| `UpgradeBinary` | `src/services/upgrade-binary` | Self-update: `upgrade()` |
371 -| `FileSystem.FileSystem` | `@effect/platform` | File I/O: `readFileString()`, `writeFileString()`, `exists()` |
372 -| `NodeProcess` | `src/services/node-process` | Process info: `cwd`, `env` |
373 -| `NodeOs` | `src/services/node-os` | OS info: `homedir()`, `platform()`, `arch()` |
374 -| `EnvLangDetector` | `src/services/env-lang-detector` | Detect project language (TS/Python) |
375 -| `JsPackageManagerDetector` | `src/services/js-package-manager-detector` | Detect npm/pnpm/yarn/bun |
376 -
377 -## Available Effects
378 -
379 -Reusable computations from `src/effects/`:
380 -
381 -| Effect | Import | Purpose |
382 -|---|---|---|
383 -| `getVersion` | `src/effects/version` | CLI version from package.json |
384 -| `logMetrics` | `src/effects/log-metrics` | Log API request count and bytes |
385 -| `setupCacheDir` | `src/effects/setup-cache-dir` | Ensure `~/.composio/` exists |
386 -| `getToolkitVersionOverrides` | `src/effects/toolkit-version-overrides` | Parse `COMPOSIO_TOOLKIT_VERSION_*` env vars |
387 -| `jsFindComposioCoreGenerated` | `src/effects/find-composio-core-generated` | Locate `@composio/core` in node_modules |
388 -| `compareSemver` | `src/effects/compare-semver` | Semantic version comparison |
389 -
390 -## TerminalUI API
391 -
392 -### Output
393 -
394 -```typescript
395 -yield* ui.output(data); // Machine-readable data → stdout when piped, no-op when interactive
396 -```
397 -
398 -### Decoration (all → stderr when interactive, suppressed when piped)
399 -
400 -```typescript
401 -yield* ui.intro('composio my-command'); // Opening banner
402 -yield* ui.outro('Done'); // Closing banner
403 -yield* ui.note(content, 'Title'); // Boxed note
404 -yield* ui.log.info('message'); // Blue info
405 -yield* ui.log.success('message'); // Green success
406 -yield* ui.log.warn('message'); // Yellow warning
407 -yield* ui.log.error('message'); // Red error
408 -yield* ui.log.step('message'); // Green checkmark step
409 -yield* ui.log.message('message'); // With vertical bar
410 -```
411 -
412 -### Spinners
322 +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`.
323
324 ```typescript
325 // Automatic: wraps an Effect, auto-stops on success/error
@@ -432,6 +342,16 @@ const result = yield* ui.useMakeSpinner('Loading...', spinner =>
342 );
343 ```
344
345 +## Creating a New Service
346 +
347 +If your command requires functionality not covered by existing services (see `ts/packages/cli/AGENTS.md` for the full list):
348 +
349 +1. Define the service interface and tag in `src/services/<name>.ts`
350 +2. Create a `Live` layer implementation
351 +3. Register the layer in `src/bin.ts`
352 +
353 +Reference `src/services/upgrade-binary.ts` for a simple service pattern, or `src/services/composio-clients.ts` for a complex one with caching.
354 +
355 ## Error Handling Patterns
356
357 ### Optional Values
@@ -440,7 +360,10 @@ const result = yield* ui.useMakeSpinner('Loading...', spinner =>
360 yield* ctx.data.apiKey.pipe(
361 Option.match({
362 onNone: () => ui.log.warn('Not logged in. Run `composio login`.'),
443 - onSome: apiKey => ui.output(apiKey),
363 + onSome: apiKey =>
364 + Effect.gen(function* () {
365 + yield* ui.output(apiKey);
366 + }),
367 })
368 );
369 ```
@@ -458,14 +381,6 @@ yield* client.getToolkitsBySlugs(slugs).pipe(
381 );
382 ```
383
461 -### Error Transformation
462 -
463 -```typescript
464 -yield* fs.writeFileString(path, content).pipe(
465 - Effect.mapError(err => new Error(`Failed to write ${path}: ${err}`))
466 -);
467 -```
468 -
384 ### Logging Non-Fatal Errors
385
386 ```typescript
@@ -558,6 +473,8 @@ When implementing a new command:
473 7. If using a new service, add its layer to `src/bin.ts`
474 8. Build to verify: `cd ts/packages/cli && pnpm build`
475
476 +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.
477 +
478 ## Reference Files
479
480 | File | Purpose |
@@ -573,4 +490,4 @@ When implementing a new command:
490 | `src/bin.ts` | Entry point, layer composition, error handling |
491 | `src/services/terminal-ui.ts` | TerminalUI service interface |
492 | `src/services/composio-clients.ts` | API client service (HTTP, pagination, metrics) |
576 -| `ts/packages/cli/CLAUDE.md` | CLI architecture and output conventions |
493 +| `ts/packages/cli/AGENTS.md` | CLI architecture, services, effects, output conventions |
ts/packages/cli/AGENTS.md
+2 -2
@@ -285,7 +285,7 @@ When working on CLI code, reference the Effect source for accurate patterns:
285
286 For principles on how to design CLI interactions (arguments, flags, help text, output, errors, interactivity, config precedence), see:
287
288 -- **Full guidelines**: `ts/packages/cli/.cursor/rules/cli-design-guidelines.mdc`
289 -- **Also available as**: `.claude/skills/create-cli/SKILL.md` (symlink)
288 +- **Cursor rules**: `ts/packages/cli/.cursor/rules/cli-design-guidelines.mdc`
289 +- **Claude skill**: `.claude/skills/create-cli/SKILL.md` (standalone, trimmed for Claude Code context)
290
291 Use these guidelines when adding new commands, designing flag interfaces, or making UX decisions for the CLI.