@devries-cameron20 / composio Mirror · read-only / commits / d5694a91e
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 08:15 UTC

feat(ai): add "implement-cli-command" skill

jkomyno committed Feb 18, 2026 at 16:34 UTC d5694a91ec2140ff12e19a64968638d205fb0d92
1 file changed +576
.claude/skills/implement-cli-command/SKILL.md new
+576
@@ -0,0 +1,576 @@
1 +# Implement CLI Command
2 +
3 +Implement new commands and subcommands in `ts/packages/cli/`. Covers file creation, Effect patterns, service wiring, option declaration, output conventions, and registration.
4 +
5 +## When to Use
6 +
7 +- Implementing a new CLI command from a spec or design
8 +- Adding a subcommand to an existing command group
9 +- Wiring a new command into the command tree
10 +- Understanding how existing commands work to extend them
11 +
12 +For CLI **design** (arguments, flags, help text, UX), see the `create-cli` skill instead.
13 +For CLI **e2e tests**, see the `create-cli-e2e` skill instead.
14 +
15 +## Architecture
16 +
17 +The CLI uses `@effect/cli` for command declaration, `effect` for the runtime, and a service-oriented architecture with dependency injection via Effect layers.
18 +
19 +```
20 +src/
21 +├── bin.ts # Entry point — layer composition, error handling, runtime
22 +├── commands/
23 +│ ├── index.ts # Command tree — registers all commands
24 +│ ├── $default.cmd.ts # Root command with global options (--log-level)
25 +│ ├── version.cmd.ts # Simple data command
26 +│ ├── whoami.cmd.ts # Data command with service dependency
27 +│ ├── login.cmd.ts # Complex command (options, spinner, polling)
28 +│ ├── logout.cmd.ts # Action command (no stdout data)
29 +│ ├── upgrade.cmd.ts # Action command (delegates to service)
30 +│ ├── generate.cmd.ts # Command that auto-delegates to subcommands
31 +│ ├── ts/
32 +│ │ ├── ts.cmd.ts # Parent command group
33 +│ │ └── commands/
34 +│ │ └── ts.generate.cmd.ts # Subcommand with complex logic
35 +│ └── py/
36 +│ ├── py.cmd.ts
37 +│ └── commands/
38 +│ └── py.generate.cmd.ts
39 +├── services/ # Effect services (dependency injection)
40 +├── effects/ # Reusable Effect computations
41 +├── models/ # Effect Schema definitions
42 +├── generation/ # Code generation pipeline
43 +├── effect-errors/ # Error capture and formatting
44 +└── ui/ # Terminal output helpers
45 +```
46 +
47 +### File Naming Convention
48 +
49 +- Command files: `<name>.cmd.ts` (e.g., `version.cmd.ts`, `login.cmd.ts`)
50 +- Subcommand files: `<parent>.<name>.cmd.ts` inside `commands/` (e.g., `ts.generate.cmd.ts`)
51 +- Parent command groups: `<name>.cmd.ts` at the group level (e.g., `ts/ts.cmd.ts`)
52 +
53 +## Creating a New Command
54 +
55 +### Step 1: Create the Command File
56 +
57 +Create `src/commands/<name>.cmd.ts`.
58 +
59 +**Minimal template** (data command, no options):
60 +
61 +```typescript
62 +import { Command } from '@effect/cli';
63 +import { Effect } from 'effect';
64 +import { TerminalUI } from 'src/services/terminal-ui';
65 +
66 +export const myCmd = Command.make('my-command', {}).pipe(
67 + Command.withDescription('Brief description of what the command does.'),
68 + Command.withHandler(() =>
69 + Effect.gen(function* () {
70 + const ui = yield* TerminalUI;
71 +
72 + // Compute result...
73 + const result = 'some-value';
74 +
75 + yield* ui.log.info(result); // Decoration → stderr
76 + yield* ui.output(result); // Data → stdout (for scripts)
77 + })
78 + )
79 +);
80 +```
81 +
82 +**Template with options:**
83 +
84 +```typescript
85 +import { Command, Options } from '@effect/cli';
86 +import { Effect, Option } from 'effect';
87 +import { TerminalUI } from 'src/services/terminal-ui';
88 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
89 +
90 +// Define options at module level
91 +const toolkitSlug = Options.text('toolkit').pipe(
92 + Options.withDescription('Toolkit slug to look up.')
93 +);
94 +
95 +const searchOpt = Options.optional(
96 + Options.text('search')
97 +).pipe(
98 + Options.withDescription('Search query to filter results.')
99 +);
100 +
101 +export const myCmd = Command.make('my-command', { toolkitSlug, searchOpt }).pipe(
102 + Command.withDescription('Brief description.'),
103 + Command.withHandler(({ toolkitSlug, searchOpt }) =>
104 + Effect.gen(function* () {
105 + const ui = yield* TerminalUI;
106 + const client = yield* ComposioToolkitsRepository;
107 +
108 + yield* ui.intro('composio my-command');
109 +
110 + // Use options — searchOpt is Option<string>
111 + const search = Option.getOrUndefined(searchOpt);
112 +
113 + // Fetch data with spinner
114 + const result = yield* ui.withSpinner(
115 + 'Fetching data...',
116 + client.getToolkits(),
117 + { successMessage: 'Done', errorMessage: 'Failed to fetch' }
118 + );
119 +
120 + // Output
121 + yield* ui.note(formatResult(result), 'Result');
122 + yield* ui.output(formatResult(result));
123 + yield* ui.outro('Done');
124 + })
125 + )
126 +);
127 +```
128 +
129 +### Step 2: Register the Command
130 +
131 +Add the command to `src/commands/index.ts`:
132 +
133 +```typescript
134 +import { myCmd } from './my-command.cmd';
135 +
136 +const $cmd = $defaultCmd.pipe(
137 + Command.withSubcommands([
138 + versionCmd,
139 + upgradeCmd,
140 + whoamiCmd,
141 + loginCmd,
142 + logoutCmd,
143 + generateCmd,
144 + pyCmd,
145 + tsCmd,
146 + myCmd, // Add here
147 + ])
148 +);
149 +```
150 +
151 +### Step 3: Add Required Service Layers (if any)
152 +
153 +If your command uses a new service not already in `bin.ts`, add its layer:
154 +
155 +```typescript
156 +// In src/bin.ts
157 +const layers = Layer.mergeAll(
158 + // ... existing layers
159 + MyNewServiceLive, // Add if needed
160 +);
161 +```
162 +
163 +Most commands only use services already provided: `TerminalUI`, `ComposioUserContext`, `ComposioToolkitsRepository`, `ComposioSessionRepository`, `UpgradeBinary`, `FileSystem`, `NodeProcess`, `NodeOs`.
164 +
165 +## Creating a Subcommand Group
166 +
167 +For commands like `composio toolkits list`, `composio toolkits info`:
168 +
169 +### Step 1: Create the Directory Structure
170 +
171 +```
172 +src/commands/toolkits/
173 +├── toolkits.cmd.ts # Parent command group
174 +└── commands/
175 + ├── toolkits.list.cmd.ts # composio toolkits list
176 + └── toolkits.info.cmd.ts # composio toolkits info
177 +```
178 +
179 +### Step 2: Create the Parent Command
180 +
181 +`src/commands/toolkits/toolkits.cmd.ts`:
182 +
183 +```typescript
184 +import { Command } from '@effect/cli';
185 +import { toolkitsCmd$List } from './commands/toolkits.list.cmd';
186 +import { toolkitsCmd$Info } from './commands/toolkits.info.cmd';
187 +
188 +export const toolkitsCmd = Command.make('toolkits').pipe(
189 + Command.withDescription('Discover and inspect available toolkits.'),
190 + Command.withSubcommands([toolkitsCmd$List, toolkitsCmd$Info])
191 +);
192 +```
193 +
194 +### Step 3: Create Each Subcommand
195 +
196 +`src/commands/toolkits/commands/toolkits.list.cmd.ts`:
197 +
198 +```typescript
199 +import { Command, Options } from '@effect/cli';
200 +import { Effect, Option } from 'effect';
201 +import { TerminalUI } from 'src/services/terminal-ui';
202 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
203 +
204 +const searchOpt = Options.optional(
205 + Options.text('search')
206 +).pipe(
207 + Options.withDescription('Search toolkits by name or description.')
208 +);
209 +
210 +export const toolkitsCmd$List = Command.make('list', { searchOpt }).pipe(
211 + Command.withDescription('List available toolkits.'),
212 + Command.withHandler(({ searchOpt }) =>
213 + Effect.gen(function* () {
214 + const ui = yield* TerminalUI;
215 + const client = yield* ComposioToolkitsRepository;
216 +
217 + const toolkits = yield* ui.withSpinner(
218 + 'Fetching toolkits...',
219 + client.getToolkits(),
220 + { successMessage: 'Toolkits loaded' }
221 + );
222 +
223 + // Format and output
224 + const output = toolkits
225 + .map(t => `${t.slug} - ${t.meta.description}`)
226 + .join('\n');
227 +
228 + yield* ui.log.info(output);
229 + yield* ui.output(output);
230 + })
231 + )
232 +);
233 +```
234 +
235 +### Step 4: Register the Parent in index.ts
236 +
237 +```typescript
238 +import { toolkitsCmd } from './toolkits/toolkits.cmd';
239 +
240 +const $cmd = $defaultCmd.pipe(
241 + Command.withSubcommands([
242 + // ... existing commands
243 + toolkitsCmd,
244 + ])
245 +);
246 +```
247 +
248 +## Option Declaration Patterns
249 +
250 +Options are declared at module level using `@effect/cli`'s `Options` API.
251 +
252 +### Common Option Types
253 +
254 +```typescript
255 +import { Options } from '@effect/cli';
256 +
257 +// Boolean flag (with default)
258 +const verbose = Options.boolean('verbose').pipe(
259 + Options.withDefault(false),
260 + Options.withDescription('Enable verbose output.')
261 +);
262 +
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 +
275 +// Text with alias
276 +const output = Options.optional(
277 + Options.text('output')
278 +).pipe(
279 + Options.withAlias('o'),
280 + Options.withDescription('Output path.')
281 +);
282 +
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 +
289 +// Choice from fixed set
290 +const format = Options.choice('format', ['json', 'table', 'plain']).pipe(
291 + Options.withDefault('table'),
292 + Options.withDescription('Output format.')
293 +);
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 +);
311 +```
312 +
313 +### Using Options in Handler
314 +
315 +```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'); }
323 +
324 + // toolkits: Array<string> — may be empty
325 + if (Array.isNonEmptyArray(toolkits)) {
326 + // filter by toolkits
327 + }
328 + })
329 +)
330 +```
331 +
332 +## Output Conventions
333 +
334 +Every command must follow the composable CLI output contract:
335 +
336 +### Data Commands
337 +
338 +Commands that produce a value scripts should capture:
339 +
340 +```typescript
341 +yield* ui.note(apiKey, 'API Key'); // Decoration → stderr (pretty box)
342 +yield* ui.output(apiKey); // Data → stdout (scripts capture)
343 +```
344 +
345 +### Action Commands
346 +
347 +Commands that perform a side effect but produce no data:
348 +
349 +```typescript
350 +yield* ui.log.success('Logged out successfully.');
351 +// NO ui.output() call — nothing for scripts to capture
352 +```
353 +
354 +### Rule: Never Mix
355 +
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
413 +
414 +```typescript
415 +// Automatic: wraps an Effect, auto-stops on success/error
416 +const result = yield* ui.withSpinner(
417 + 'Loading...',
418 + someEffect,
419 + { successMessage: 'Done!', errorMessage: 'Failed!' }
420 +);
421 +
422 +// Manual: full control over message updates
423 +const result = yield* ui.useMakeSpinner('Loading...', spinner =>
424 + Effect.gen(function* () {
425 + yield* spinner.message('Step 1...');
426 + const data = yield* fetchStep1;
427 + yield* spinner.message('Step 2...');
428 + const result = yield* fetchStep2(data);
429 + yield* spinner.stop('All done!');
430 + return result;
431 + })
432 +);
433 +```
434 +
435 +## Error Handling Patterns
436 +
437 +### Optional Values
438 +
439 +```typescript
440 +yield* ctx.data.apiKey.pipe(
441 + Option.match({
442 + onNone: () => ui.log.warn('Not logged in. Run `composio login`.'),
443 + onSome: apiKey => ui.output(apiKey),
444 + })
445 +);
446 +```
447 +
448 +### Typed Errors with catchTag
449 +
450 +```typescript
451 +yield* client.getToolkitsBySlugs(slugs).pipe(
452 + Effect.catchTag('services/InvalidToolkitsError', error =>
453 + Effect.gen(function* () {
454 + yield* ui.log.error(`Invalid toolkits: ${error.invalidToolkits.join(', ')}`);
455 + return yield* Effect.fail(error);
456 + })
457 + )
458 +);
459 +```
460 +
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 +
469 +### Logging Non-Fatal Errors
470 +
471 +```typescript
472 +yield* riskyOperation.pipe(
473 + Effect.catchAll(error =>
474 + Effect.logWarning(`Non-critical failure: ${error.message}`)
475 + )
476 +);
477 +```
478 +
479 +## Parallel Data Fetching
480 +
481 +Use `Effect.all` with `concurrency` for parallel API calls:
482 +
483 +```typescript
484 +const [toolkits, tools, triggerTypes] = yield* Effect.all(
485 + [
486 + client.getToolkits(),
487 + client.getTools(slugs),
488 + client.getTriggerTypes(slugs),
489 + ],
490 + { concurrency: 'unbounded' }
491 +);
492 +```
493 +
494 +## Extracting Reusable Logic
495 +
496 +For commands that share logic (e.g., `composio generate` delegates to `composio ts generate`):
497 +
498 +```typescript
499 +// In ts.generate.cmd.ts — export the logic separately
500 +export function generateTypescriptTypeStubs(params: { ... }) {
501 + return Effect.gen(function* () {
502 + const ui = yield* TerminalUI;
503 + // ... implementation
504 + });
505 +}
506 +
507 +// The command uses it
508 +export const tsCmd$Generate = Command.make('generate', { ... }).pipe(
509 + Command.withHandler(params => generateTypescriptTypeStubs(params))
510 +);
511 +
512 +// Other commands can reuse it
513 +// In generate.cmd.ts
514 +import { generateTypescriptTypeStubs } from './ts/commands/ts.generate.cmd';
515 +
516 +yield* Match.value(envLang).pipe(
517 + Match.when('TypeScript', () => generateTypescriptTypeStubs({ ... })),
518 + Match.when('Python', () => generatePythonTypeStubs({ ... })),
519 + Match.exhaustive
520 +);
521 +```
522 +
523 +## Retry with Exponential Backoff
524 +
525 +For polling operations (e.g., waiting for OAuth):
526 +
527 +```typescript
528 +import { Schedule } from 'effect';
529 +
530 +const result = yield* ui.useMakeSpinner('Waiting...', spinner =>
531 + Effect.retry(
532 + Effect.gen(function* () {
533 + const status = yield* client.getSession(session);
534 + if (status.status === 'linked') return status;
535 + return yield* Effect.fail(new Error('Still pending'));
536 + }),
537 + Schedule.exponential('0.3 seconds').pipe(
538 + Schedule.intersect(Schedule.recurs(15)),
539 + Schedule.intersect(Schedule.spaced('5 seconds'))
540 + )
541 + ).pipe(
542 + Effect.tap(() => spinner.stop('Success!')),
543 + Effect.tapError(() => spinner.error('Timed out'))
544 + )
545 +);
546 +```
547 +
548 +## Checklist
549 +
550 +When implementing a new command:
551 +
552 +1. Create `src/commands/<name>.cmd.ts` (or `src/commands/<group>/commands/<group>.<name>.cmd.ts` for subcommands)
553 +2. Define options at module level using `Options.*`
554 +3. Create the command with `Command.make(name, options).pipe(Command.withDescription(...), Command.withHandler(...))`
555 +4. In the handler, resolve services with `yield* ServiceName`
556 +5. Follow the output convention: `ui.output()` for data, `ui.log.*` for decoration
557 +6. Register in `src/commands/index.ts` (or in the parent group's command file)
558 +7. If using a new service, add its layer to `src/bin.ts`
559 +8. Build to verify: `cd ts/packages/cli && pnpm build`
560 +
561 +## Reference Files
562 +
563 +| File | Purpose |
564 +|---|---|
565 +| `src/commands/version.cmd.ts` | Simplest command (no options, no services beyond TerminalUI) |
566 +| `src/commands/whoami.cmd.ts` | Data command with service dependency |
567 +| `src/commands/login.cmd.ts` | Complex command (options, spinner, polling, retry) |
568 +| `src/commands/logout.cmd.ts` | Action command (no stdout data) |
569 +| `src/commands/upgrade.cmd.ts` | Action command delegating to service |
570 +| `src/commands/generate.cmd.ts` | Auto-detection and delegation to subcommands |
571 +| `src/commands/ts/commands/ts.generate.cmd.ts` | Full subcommand with parallel fetching, spinner, file I/O |
572 +| `src/commands/index.ts` | Command tree registration |
573 +| `src/bin.ts` | Entry point, layer composition, error handling |
574 +| `src/services/terminal-ui.ts` | TerminalUI service interface |
575 +| `src/services/composio-clients.ts` | API client service (HTTP, pagination, metrics) |
576 +| `ts/packages/cli/CLAUDE.md` | CLI architecture and output conventions |