@devries-cameron20 / composio Mirror · read-only
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 21, 06:00 UTC

next
md 138 lines 9.79 KB
Rendered Raw
1 # CLI Implementation
2
3 ## Start with the current command model
4
5 The [contributor guide](../../../../ts/packages/cli/CONTRIBUTING.md) traces one command through parsing, behavior, registration, and its argv-level test. The generated [command catalog](../../../../ts/packages/cli/src/commands/COMMANDS.md) lists every registration and its source. The package's AGENTS.md remains authoritative.
6
7 - Groups register children through `withRegisteredSubcommands`, which supplies parsed identity and inherited policy. Direct `Command.withSubcommands` bypasses it.
8 - `withCommandMeta` declares login, hooks, telemetry family, and unsupported shared flags. Handlers do not repeat login gates or lifecycle reporting.
9 - `CommandSurface` supplies root/dev context and dev shared flags. `actingUser()` resolves the acting user and project; `devActingUserOption(project)` finds an optional one for a developer project the command resolved. A user filter does not use a test-user fallback.
10 - The same command definition can have multiple registrations. Root shortcuts do not need copied handlers or descriptions.
11 - Changes to command paths or help summaries regenerate `COMMANDS.md` with `pnpm --filter @composio/cli run commands:map`.
12
13 ## Command Files
14
15 One directory per command under `src/commands/`, files sharing the command's dotted basename. The authoritative description, including the legacy shape and the test mirror, is "Command module layout" in `ts/packages/cli/AGENTS.md`; the short form:
16
17 ```
18 src/commands/<group>/<group>.cmd.ts group entry: subcommand list only
19 src/commands/<group>/<name>/<group>.<name>.cmd.ts flags, description, examples, Command.make
20 src/commands/<group>/<name>/<group>.<name>.handler.ts (params) => Effect
21 src/commands/<group>/<name>/<group>.<name>.format.ts stderr renderer + stdout renderer
22 src/commands/<group>/<name>/<group>.<name>.errors.ts command-owned tagged errors, optional
23 test/src/commands/<group>/<name>/<group>.<name>.cmd.test.ts argv-level, required
24 test/src/commands/<group>/<name>/<group>.<name>.handler.test.ts handler-level, optional
25 ```
26
27 - Top-level commands use the same shape without a group: `src/commands/<name>/<name>.cmd.ts`.
28 - Register new commands through `src/commands/index.ts` or the nearest group entry.
29 - A usage mistake the parser cannot see (flag combination, business rule, missing input) raises `CommandInputError` via `commandInputError('<command>')` from `src/commands/errors.ts`, with the `option` at fault; the invocation (`src/invocation/invocation.ts`) prints the message and exits 1. Do not add a per-command message-only error class.
30 - A command that needs a login declares `withCommandMeta({ requiresLogin: true })` (`src/invocation/command-identity.ts`) on itself or on its group entry; the selected command checks it right after it began, and the handler never checks `apiKey`. `resolveCommandProject` fails with `ProjectResolutionError` and `resolveConnectedAccountForToolkit` with `ConnectedAccountResolutionError`; let them flow, they print and exit 1 like `CommandInputError`.
31 - A command still in the legacy single-file shape (`<group>/commands/<group>.<name>.cmd.ts`, or top-level `<name>.cmd.ts`) is migrated in the PR that next changes it substantively, one command per PR.
32 - `pnpm run validate:command-tests` (in `pnpm test`) fails on a command without its mirrored `.cmd.test.ts`, on an orphan `.cmd.test.ts`, and on a stale exemption. Add the test with the command; do not add exemptions.
33
34 ## Effect Patterns
35
36 The CLI is on `effect@^4.1.0` (workspace range) plus `@effect/platform-bun`/`@effect/vitest` at the same version. `@effect/cli` and `@effect/platform` no longer exist as separate deps — their functionality is consolidated into `effect`'s barrel and `effect/*` submodules.
37
38 Common shape. The command file declares the surface and passes the handler to the three-argument `Command.make`:
39
40 ```typescript
41 // src/commands/tools/list/tools.list.cmd.ts
42 import { Argument, Command, Flag } from 'effect/cli';
43 import { runToolsList } from './tools.list.handler';
44
45 const toolkit = Argument.String('toolkit').pipe(
46 Argument.withDescription('Toolkit slug to list tools for (e.g. "gmail")')
47 );
48
49 const query = Flag.String('query').pipe(
50 Flag.withDescription('Text search by name, slug, or description'),
51 Flag.optional
52 );
53
54 const limit = Flag.Int('limit').pipe(
55 Flag.withDefault(30),
56 Flag.withDescription('Number of results per page (1-1000)')
57 );
58
59 export const toolsCmd$List = Command.make('list', { toolkit, query, limit }, runToolsList).pipe(
60 Command.withDescription('List tools in a toolkit.')
61 );
62 ```
63
64 The handler declares the params it needs as a plain type; the compiler checks that the command's flags satisfy it. No `Effect.gen` and no service access in the command file:
65
66 ```typescript
67 // src/commands/tools/list/tools.list.handler.ts
68 import { Effect, Option } from 'effect';
69 import { TerminalUI } from 'src/services/terminal-ui';
70
71 export type ToolsListParams = {
72 readonly toolkit: string;
73 readonly query: Option.Option<string>;
74 readonly limit: number;
75 };
76
77 export const runToolsList = ({ toolkit, query, limit }: ToolsListParams) =>
78 Effect.gen(function* () {
79 const ui = yield* TerminalUI;
80 // resolve services with yield*, render through ./tools.list.format
81 });
82 ```
83
84 `Args`/`Options` (v3 `@effect/cli`) are gone — use `Argument` for positionals and `Flag` for named options, both from `effect/cli`. Constructors are capitalized (`Argument.String`, `Flag.String`/`.Boolean`/`.Int`/`.Literals`); `Argument.variadic()` remains lowercase and must be called rather than piped as a bare reference. Combinators remain lowercase (`.withDefault`/`.withDescription`/`.withAlias`/`.optional`). Optional flags read via `Option.getOrUndefined(...)`/`Option.isSome(...)`, matching the `query`/`tags` pattern above.
85
86 Follow existing local patterns before introducing new service abstractions.
87
88 ## Native Effect client
89
90 `ComposioClientSingleton` in `src/services/composio-clients.ts` builds `@composio/client/effect` clients with `make`, explicit `Auth`, scope, the Effect HTTP transport, CLI identity, and schema loaders. Handlers get a client through `getFor({ orgId, projectId })` after resolving project context.
91
92 Client operations already return Effects, so handlers yield them directly. Paginated reads use the client's streams. Fallible Promise adapters remain appropriate only for dependencies that return Promises. Read operations can pass `idempotent` from `src/services/composio-request.ts`. Execution and proxy operations must retain their existing retry policy. Runtime response decoding and stdout allowlists remain command-owned contracts.
93
94 The command-example reference contains a runnable recipe and request assertions against the real Effect client over a stub HTTP transport.
95
96 ## Effect Platform Boundaries
97
98 `node:path`, `node:fs`, `node:os`, `node:child_process`, `process.env`, and `try`/`catch` are lint-banned (oxlint) in `src/`:
99
100 - Path arithmetic → `Path` service from `effect/Path` (`const path = yield* Path.Path`).
101 - Filesystem I/O → `FileSystem` service from `effect/FileSystem` (`const fs = yield* FileSystem.FileSystem`).
102 - homedir/tmpdir/platform/arch → the `NodeOs` service (`src/services/node-os.ts`, a `Context.Service` with a `static readonly Default` layer); subprocesses → `ChildProcess`/`ChildProcessSpawner` from `effect/process`, or `services/detached-process.ts` for children that outlive the CLI.
103 - Environment reads → `effect/Config`; sync fallible ops (`JSON.parse`, `new URL`) → `Result.try` with a `Data.TaggedError` (JSON records via `parseJsonRecord` in `src/utils/parse-json.ts`, which returns `Result.Result<Record<string, unknown>, JsonParsingError>`; a `Result` is not yieldable in v4 even though it typechecks, so lift it with `yield* Effect.fromResult(parseJsonRecord(raw))`).
104 - Helpers that cannot become Effects (sync callbacks, promise pipelines) take the resolved service instance as a plain parameter instead of importing Node builtins.
105
106 `Either` (v3) is gone; the direct replacement is `Result` (`Either.try` → `Result.try`, `Either.isLeft`/`.left` → `Result.isFailure`/`.failure`, `Either.mapLeft` → `Result.mapError`). `ParseResult`/`ParseError` are gone too — `Schema.decodeUnknownEffect`/`Schema.decodeEffect` now fail with `Schema.SchemaError`.
107
108 Never add an `eslint-disable`: `pnpm run validate:boundaries` (CI-blocking via `pnpm test`) rejects any disable not registered in `lint-boundaries.json`. Genuine new runtime boundaries require regenerating the manifest with `pnpm run validate:boundaries -- --update` plus a justification in the PR. Full policy: "Effect Boundary Policy" in `ts/packages/cli/AGENTS.md`.
109
110 ## Analytics Events
111
112 Event names and builders live in `src/analytics/events.ts`; `buildEvent` stamps every event with
113 `journey_stage` and `cli_channel`, and `trackCliEventEffect` (`src/analytics/dispatch.ts`) adds
114 `agent_host_env` (`claude`, `codex`, or `none`, from `src/services/agent-host-env.ts`) to every
115 enqueued envelope. Setup-related events and their extra properties:
116
117 - `CLI_SETUP_HOST_DETECTED`: `host_config_dir_present` and `host_binary_in_known_paths` only when
118 `available` is `false` (probed by `src/services/agent-host-env.ts`).
119 - `CLI_SETUP_FAILED`: `failure_reason_code` read from `SetupCommandError.reasonCode`
120 (`src/services/setup-command-error.ts`).
121 - `CLI_PLUGIN_HINT_SHOWN`: emitted by `src/services/plugin-hint.ts` once per printed hint with
122 `command_path` and `agent_host`.
123
124 ## Required Checks
125
126 For CLI source changes, run from the repo root:
127
128 ```bash
129 pnpm typecheck
130 pnpm --filter @composio/cli run lint:effect
131 pnpm --filter @composio/cli test
132 ```
133
134 For binary behavior, pair with the `cli-e2e` skill.
135
136 ## Recordings
137
138 Add VHS recordings when a user-facing command changes documented workflow, introduces a new visible command surface, or needs release-note demo coverage. Skip them for internal wiring changes or hidden developer helpers, and say why in the PR.