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.
8
-
9
-## When to Use
10
-
11
-- Implementing a new CLI command from a spec or design
12
-- Adding a subcommand to an existing command group
13
-- Wiring a new command into the command tree
14
-- Understanding how existing commands work to extend them
15
-
16
-For CLI **design** (arguments, flags, help text, UX), see the `create-cli` skill instead.
17
-For CLI **e2e tests**, see the `create-cli-e2e` skill instead.
18
-
19
-## Architecture
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
28
-├── commands/
29
-│ ├── index.ts # Command tree — registers all commands
30
-│ ├── $default.cmd.ts # Root command with global options (--log-level)
31
-│ ├── version.cmd.ts # Simple data command
32
-│ ├── whoami.cmd.ts # Data command with service dependency
33
-│ ├── login.cmd.ts # Complex command (options, spinner, polling)
34
-│ ├── logout.cmd.ts # Action command (no stdout data)
35
-│ ├── upgrade.cmd.ts # Action command (delegates to service)
36
-│ ├── generate/
37
-│ │ ├── generate.cmd.ts # Parent command group for `composio generate`
38
-│ │ ├── generate-py.cmd.ts # `composio generate py`
39
-│ │ └── generate-ts.cmd.ts # `composio generate ts`
40
-│ ├── manage/
41
-│ │ └── manage.cmd.ts # Parent command group for `composio manage`
42
-│ ├── ts/
43
-│ │ ├── ts.cmd.ts # Existing TS generation internals, referenced from generate/
44
-│ │ └── commands/
45
-│ │ └── ts.generate.cmd.ts # Reusable TS generation logic
46
-│ └── py/
47
-│ ├── py.cmd.ts # Existing Python generation internals, referenced from generate/
48
-│ └── commands/
49
-│ └── py.generate.cmd.ts
50
-├── services/ # Effect services (dependency injection)
51
-├── effects/ # Reusable Effect computations
52
-├── models/ # Effect Schema definitions
53
-├── generation/ # Code generation pipeline
54
-├── effect-errors/ # Error capture and formatting
55
-└── ui/ # Terminal output helpers
56
-```
57
-
58
-### File Naming Convention
59
-
60
-- Command files: `<name>.cmd.ts` (e.g., `version.cmd.ts`, `login.cmd.ts`)
61
-- Subcommand implementation files: `<parent>.<name>.cmd.ts` inside `commands/` (e.g., `ts.generate.cmd.ts`)
62
-- Parent command groups: `<name>.cmd.ts` at the group level (e.g., `generate/generate.cmd.ts`, `manage/manage.cmd.ts`)
63
-- Wrapper subcommand entrypoints can also live beside their parent group (e.g., `generate/generate-py.cmd.ts`, `generate/generate-ts.cmd.ts`)
64
-
65
-## Creating a New Command
66
-### Step 1: Create the Command File
67
-
68
-Create `src/commands/<name>.cmd.ts`.
69
-
70
-**Minimal template** (data command, no options):
71
-
72
-```typescript
73
-import { Command } from '@effect/cli';
74
-import { Effect } from 'effect';
75
-import { TerminalUI } from 'src/services/terminal-ui';
76
-
77
-export const myCmd = Command.make('my-command', {}).pipe(
78
- Command.withDescription('Brief description of what the command does.'),
79
- Command.withHandler(() =>
80
- Effect.gen(function* () {
81
- const ui = yield* TerminalUI;
82
-
83
- // Compute result...
84
- const result = 'some-value';
85
-
86
- yield* ui.log.info(result); // Decoration → stderr
87
- yield* ui.output(result); // Data → stdout (for scripts)
88
- })
89
- )
90
-);
91
-```
92
-
93
-**Template with options:**
94
-
95
-```typescript
96
-import { Command, Options } from '@effect/cli';
97
-import { Effect, Option } from 'effect';
98
-import { TerminalUI } from 'src/services/terminal-ui';
99
-import { ComposioToolkitsRepository } from 'src/services/composio-clients';
100
-
101
-// Define options at module level
102
-const toolkitSlug = Options.text('toolkit').pipe(
103
- Options.withDescription('Toolkit slug to look up.')
104
-);
105
-
106
-const searchOpt = Options.optional(
107
- Options.text('search')
108
-).pipe(
109
- Options.withDescription('Search query to filter results.')
110
-);
111
-
112
-export const myCmd = Command.make('my-command', { toolkitSlug, searchOpt }).pipe(
113
- Command.withDescription('Brief description.'),
114
- Command.withHandler(({ toolkitSlug, searchOpt }) =>
115
- Effect.gen(function* () {
116
- const ui = yield* TerminalUI;
117
- const client = yield* ComposioToolkitsRepository;
118
-
119
- yield* ui.intro('composio my-command');
120
-
121
- // Use options — searchOpt is Option<string>
122
- const search = Option.getOrUndefined(searchOpt);
123
-
124
- // Fetch data with spinner
125
- const result = yield* ui.withSpinner(
126
- 'Fetching data...',
127
- client.getToolkits(),
128
- { successMessage: 'Done', errorMessage: 'Failed to fetch' }
129
- );
130
-
131
- // Output
132
- yield* ui.note(formatResult(result), 'Result');
133
- yield* ui.output(formatResult(result));
134
- yield* ui.outro('Done');
135
- })
136
- )
137
-);
138
-```
139
-
140
-### Step 2: Register the Command
141
-
142
-Add the command to `src/commands/index.ts`:
143
-
144
-```typescript
145
-import { myCmd } from './my-command.cmd';
146
-
147
-const $cmd = $defaultCmd.pipe(
148
- Command.withSubcommands([
149
- versionCmd,
150
- upgradeCmd,
151
- whoamiCmd,
152
- loginCmd,
153
- logoutCmd,
154
- generateCmd,
155
- manageCmd,
156
- myCmd, // Add here
157
- ])
158
-);
159
-```
160
-
161
-### Step 3: Add Required Service Layers (if any)
162
-
163
-If your command uses a new service not already in `bin.ts`, add its layer:
164
-
165
-```typescript
166
-// In src/bin.ts
167
-const layers = Layer.mergeAll(
168
- // ... existing layers
169
- MyNewServiceLive, // Add if needed
170
-);
171
-```
172
-
173
-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.
174
-
175
-## Creating a Subcommand Group
176
-
177
-For commands like `composio manage toolkits list`, `composio manage toolkits info`:
178
-
179
-### Step 1: Create the Directory Structure
180
-
181
-```
182
-src/commands/manage/toolkits/
183
-├── toolkits.cmd.ts # Parent command group under `manage`
184
-└── commands/
185
- ├── toolkits.list.cmd.ts # composio manage toolkits list
186
- └── toolkits.info.cmd.ts # composio manage toolkits info
187
-```
188
-
189
-### Step 2: Create the Parent Command
190
-
191
-`src/commands/manage/toolkits/toolkits.cmd.ts`:
192
-```typescript
193
-import { Command } from '@effect/cli';
194
-import { toolkitsCmd$List } from './commands/toolkits.list.cmd';
195
-import { toolkitsCmd$Info } from './commands/toolkits.info.cmd';
196
-
197
-export const toolkitsCmd = Command.make('toolkits').pipe(
198
- Command.withDescription('Discover and inspect available toolkits.'),
199
- Command.withSubcommands([toolkitsCmd$List, toolkitsCmd$Info])
200
-);
201
-```
202
-
203
-### Step 3: Create Each Subcommand
204
-
205
-`src/commands/manage/toolkits/commands/toolkits.list.cmd.ts`:
206
-```typescript
207
-import { Command, Options } from '@effect/cli';
208
-import { Effect, Option } from 'effect';
209
-import { TerminalUI } from 'src/services/terminal-ui';
210
-import { ComposioToolkitsRepository } from 'src/services/composio-clients';
211
-
212
-const searchOpt = Options.optional(
213
- Options.text('search')
214
-).pipe(
215
- Options.withDescription('Search toolkits by name or description.')
216
-);
217
-
218
-export const toolkitsCmd$List = Command.make('list', { searchOpt }).pipe(
219
- Command.withDescription('List available toolkits.'),
220
- Command.withHandler(({ searchOpt }) =>
221
- Effect.gen(function* () {
222
- const ui = yield* TerminalUI;
223
- const client = yield* ComposioToolkitsRepository;
224
-
225
- const toolkits = yield* ui.withSpinner(
226
- 'Fetching toolkits...',
227
- client.getToolkits(),
228
- { successMessage: 'Toolkits loaded' }
229
- );
230
-
231
- // Format and output
232
- const output = toolkits
233
- .map(t => `${t.slug} - ${t.meta.description}`)
234
- .join('\n');
235
-
236
- yield* ui.log.info(output);
237
- yield* ui.output(output);
238
- })
239
- )
240
-);
241
-```
242
-
243
-### Step 4: Register the Parent in `manage/manage.cmd.ts`
244
-
245
-```typescript
246
-import { Command } from '@effect/cli';
247
-import { toolkitsCmd } from './toolkits/toolkits.cmd';
248
-
249
-export const manageCmd = Command.make('manage').pipe(
250
- Command.withDescription('Manage existing Composio resources.'),
251
- Command.withSubcommands([
252
- // ... existing manage subcommands
253
- toolkitsCmd,
254
- ])
255
-);
256
-```
257
-
258
-## Option Declaration Patterns
259
-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`.
260
-
261
-Both `Options.optional(Options.text(...))` (wrapping) and `Options.text(...).pipe(Options.optional)` (piped) are valid. Use whichever reads better.
262
-
263
-### Common patterns:
264
-
265
-```typescript
266
-import { Options } from '@effect/cli';
267
-
268
-// Boolean flag (with default)
269
-const verbose = Options.boolean('verbose').pipe(
270
- Options.withDefault(false),
271
- Options.withDescription('Enable verbose output.')
272
-);
273
-
274
-// Text with alias
275
-const output = Options.optional(
276
- Options.text('output')
277
-).pipe(
278
- Options.withAlias('o'),
279
- Options.withDescription('Output path.')
280
-);
281
-
282
-// Choice from fixed set
283
-const format = Options.choice('format', ['json', 'table', 'plain']).pipe(
284
- Options.withDefault('table'),
285
- Options.withDescription('Output format.')
286
-);
287
-```
288
-
289
-### Using Options in Handler
290
-
291
-```typescript
292
-Command.make('my-cmd', { search, verbose }).pipe(
293
- Command.withHandler(({ search, verbose }) =>
294
- Effect.gen(function* () {
295
- // search: Option<string> — use Option.getOrUndefined, Option.match, Option.isSome
296
- const searchValue = Option.getOrUndefined(search);
297
-
298
- // verbose: boolean — direct use
299
- if (verbose) { yield* Effect.logDebug('Verbose mode'); }
300
- })
301
- )
302
-);
303
-```
304
-
305
-## Output Conventions
306
-
307
-Follow the output conventions in `ts/packages/cli/AGENTS.md` § "Output Conventions" (stdout for data via `ui.output()`, stderr for decoration).
308
-
309
-**Data commands** — produce a value scripts should capture:
310
-
311
-```typescript
312
-yield* ui.note(apiKey, 'API Key'); // Decoration → stderr (pretty box)
313
-yield* ui.output(apiKey); // Data → stdout (scripts capture)
314
-```
315
-
316
-**Action commands** — perform a side effect, no data:
317
-
318
-```typescript
319
-yield* ui.log.success('Logged out successfully.');
320
-// NO ui.output() call — nothing for scripts to capture
321
-```
322
-
323
-## TerminalUI Spinners
324
-
325
-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`.
326
-
327
-```typescript
328
-// Automatic: wraps an Effect, auto-stops on success/error
329
-const result = yield* ui.withSpinner(
330
- 'Loading...',
331
- someEffect,
332
- { successMessage: 'Done!', errorMessage: 'Failed!' }
333
-);
334
-
335
-// Manual: full control over message updates
336
-const result = yield* ui.useMakeSpinner('Loading...', spinner =>
337
- Effect.gen(function* () {
338
- yield* spinner.message('Step 1...');
339
- const data = yield* fetchStep1;
340
- yield* spinner.message('Step 2...');
341
- const result = yield* fetchStep2(data);
342
- yield* spinner.stop('All done!');
343
- return result;
344
- })
345
-);
346
-```
347
-
348
-## Creating a New Service
349
-
350
-If your command requires functionality not covered by existing services (see `ts/packages/cli/AGENTS.md` for the full list):
351
-
352
-1. Define the service interface and tag in `src/services/<name>.ts`
353
-2. Create a `Live` layer implementation
354
-3. Register the layer in `src/bin.ts`
355
-
356
-Reference `src/services/upgrade-binary.ts` for a simple service pattern, or `src/services/composio-clients.ts` for a complex one with caching.
357
-
358
-## Error Handling Patterns
359
-
360
-### Optional Values
361
-
362
-```typescript
363
-yield* ctx.data.apiKey.pipe(
364
- Option.match({
365
- onNone: () => ui.log.warn('Not logged in. Run `composio login`.'),
366
- onSome: apiKey =>
367
- Effect.gen(function* () {
368
- yield* ui.output(apiKey);
369
- }),
370
- })
371
-);
372
-```
373
-
374
-### Typed Errors with catchTag
375
-
376
-```typescript
377
-yield* client.getToolkitsBySlugs(slugs).pipe(
378
- Effect.catchTag('services/InvalidToolkitsError', error =>
379
- Effect.gen(function* () {
380
- yield* ui.log.error(`Invalid toolkits: ${error.invalidToolkits.join(', ')}`);
381
- return yield* Effect.fail(error);
382
- })
383
- )
384
-);
385
-```
386
-
387
-### Logging Non-Fatal Errors
388
-
389
-```typescript
390
-yield* riskyOperation.pipe(
391
- Effect.catchAll(error =>
392
- Effect.logWarning(`Non-critical failure: ${error.message}`)
393
- )
394
-);
395
-```
396
-
397
-## Parallel Data Fetching
398
-
399
-Use `Effect.all` with `concurrency` for parallel API calls:
400
-
401
-```typescript
402
-const [toolkits, tools, triggerTypes] = yield* Effect.all(
403
- [
404
- client.getToolkits(),
405
- client.getTools(slugs),
406
- client.getTriggerTypes(slugs),
407
- ],
408
- { concurrency: 'unbounded' }
409
-);
410
-```
411
-
412
-## Extracting Reusable Logic
413
-
414
-For commands that share logic (e.g., `composio generate` delegates to `composio generate ts`):
415
-```typescript
416
-// In ts.generate.cmd.ts — export the logic separately
417
-export function generateTypescriptTypeStubs(params: { ... }) {
418
- return Effect.gen(function* () {
419
- const ui = yield* TerminalUI;
420
- // ... implementation
421
- });
422
-}
423
-
424
-// The command uses it
425
-export const tsCmd$Generate = Command.make('generate', { ... }).pipe(
426
- Command.withHandler(params => generateTypescriptTypeStubs(params))
427
-);
428
-
429
-// Other commands can reuse it
430
-// In generate/generate-ts.cmd.ts
431
-import { generateTypescriptTypeStubs } from '../ts/commands/ts.generate.cmd';
432
-yield* Match.value(envLang).pipe(
433
- Match.when('TypeScript', () => generateTypescriptTypeStubs({ ... })),
434
- Match.when('Python', () => generatePythonTypeStubs({ ... })),
435
- Match.exhaustive
436
-);
437
-```
438
-
439
-## Retry with Exponential Backoff
440
-
441
-For polling operations (e.g., waiting for OAuth):
442
-
443
-```typescript
444
-import { Schedule } from 'effect';
445
-
446
-const result = yield* ui.useMakeSpinner('Waiting...', spinner =>
447
- Effect.retry(
448
- Effect.gen(function* () {
449
- const status = yield* client.getSession(session);
450
- if (status.status === 'linked') return status;
451
- return yield* Effect.fail(new Error('Still pending'));
452
- }),
453
- Schedule.exponential('0.3 seconds').pipe(
454
- Schedule.intersect(Schedule.recurs(15)),
455
- Schedule.intersect(Schedule.spaced('5 seconds'))
456
- )
457
- ).pipe(
458
- Effect.tap(() => spinner.stop('Success!')),
459
- Effect.tapError(() => spinner.error('Timed out'))
460
- )
461
-);
462
-```
463
-
464
-## Checklist
465
-
466
-When implementing a new command:
467
-
468
-1. Create `src/commands/<name>.cmd.ts` (or `src/commands/<group>/commands/<group>.<name>.cmd.ts` for subcommands)
469
-2. Define options at module level using `Options.*`
470
-3. Create the command with `Command.make(name, options).pipe(Command.withDescription(...), Command.withHandler(...))`
471
-4. In the handler, resolve services with `yield* ServiceName`
472
-5. Follow the output convention: `ui.output()` for data, `ui.log.*` for decoration
473
-6. Register in `src/commands/index.ts` (or in the parent group's command file)
474
-7. If using a new service, add its layer to `src/bin.ts`
475
-8. Build to verify: `cd ts/packages/cli && pnpm build`
476
-9. Add recordings for the new command (see **Recording** below)
477
-
478
-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.
479
-
480
-## Recording
481
-
482
-New commands should have VHS recordings for documentation. Recordings produce SVGs and asciicasts that demonstrate the command in action.
483
-
484
-### Step 1: Add Entries to recordings.yaml
485
-
486
-Add recording entries to `ts/packages/cli/recordings/recordings.yaml` under the appropriate group:
487
-
488
-```yaml
489
-recordings:
490
- my-command:
491
- - name: help
492
- description: Show my-command help
493
- command: "composio my-command --help"
494
- height: dynamic # Use for commands whose output exceeds 750px
495
-
496
- - name: basic
497
- description: Run my-command with default options
498
- command: "composio my-command"
499
-```
500
-
501
-Each entry has:
502
-- `name` — filename for the recording (produces `<name>.svg`, `<name>.ascii`, `<name>.tape`)
503
-- `command` — the exact shell command to record
504
-- `description` — (optional) comment shown instantly above the command
505
-- `sleepAfterEnter` — (optional) override the default wait time after Enter (default: `6s`)
506
-- `height` — (optional) `'dynamic'` for auto-sizing via two-pass recording, or a fixed pixel number. Omit to use the default height (750px)
507
-
508
-Use `height: dynamic` for commands that produce long output (help text, full listings). Fixed height is fine for short-output commands (version, no-results, limited queries).
509
-
510
-### Step 2: Run the Recorder
511
-
512
-```bash
513
-cd ts/packages/cli
514
-bun scripts/record.ts
515
-```
516
-
517
-Requires `COMPOSIO_API_KEY` in the environment and `vhs` + `composio` on `PATH`.
518
-
519
-### Output Structure
520
-
521
-```
522
-recordings/
523
-├── recordings.yaml # Config
524
-├── tapes/<group>/<name>.tape # Generated VHS tape files (committed)
525
-├── svgs/<group>/<name>.svg # SVG recordings
526
-└── ascii/<group>/<name>.ascii # Asciicast recordings
527
-```
528
-
529
-## Reference Files
530
-
531
-| File | Purpose |
532
-|---|---|
533
-| `src/commands/version.cmd.ts` | Simplest command (no options, no services beyond TerminalUI) |
534
-| `src/commands/whoami.cmd.ts` | Data command with service dependency |
535
-| `src/commands/login.cmd.ts` | Complex command (options, spinner, polling, retry) |
536
-| `src/commands/logout.cmd.ts` | Action command (no stdout data) |
537
-| `src/commands/upgrade.cmd.ts` | Action command delegating to service |
538
-| `src/commands/generate/generate.cmd.ts` | Parent `generate` command and delegation entrypoint |
539
-| `src/commands/manage/manage.cmd.ts` | Parent `manage` command and subcommand registration |
540
-| `src/commands/ts/commands/ts.generate.cmd.ts` | Reusable TS generation logic used by `generate ts` |
541
-| `src/commands/index.ts` | Command tree registration |
542
-| `src/bin.ts` | Entry point, layer composition, error handling |
543
-| `src/services/terminal-ui.ts` | TerminalUI service interface |
544
-| `src/services/composio-clients.ts` | API client service (HTTP, pagination, metrics) |
545
-| `ts/packages/cli/AGENTS.md` | CLI architecture, services, effects, output conventions |
\ No newline at end of file