@devries-cameron20 / composio Mirror · read-only / commits / 0ff607136
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, 09:45 UTC

refactor(cli): gate commands on login with `requireLogin` and type project-resolution failures (#4894)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4890 (PR 3 of the command-layout series) - breaking: - a command that needs a login now fails with `NotLoggedInError` and exits 1 when `~/.composio` holds no API key; until now it printed a warning and exited 0, so scripts could not tell "not logged in" from success - adds `requireLogin` (`src/effects/require-auth.ts`), a `Command.provideEffectDiscard` combinator, and pipes it on the eight group entries whose subcommands all need a login (`tools`, `toolkits`, `triggers` on both trees, `auth-configs`, `connected-accounts`, `connections`, `orgs`) and on the root-registered commands (`search`, `execute`, `link`, `proxy`, `listen`, `dev listen`, `dev projects list`); the 32 `if (!(yield* requireAuth)) return;` guards inside handlers are gone - replaces `formatResolveCommandProjectError`, which flattened four typed failures and API errors into a plain `Error`, with `ProjectResolutionError` raised by `resolveCommandProject` itself, carrying a `reason` and the same messages; the 12 `Effect.mapError(formatResolveCommandProjectError)` pipes are gone - extends the quiet path in `cli-main.ts` to the `UsageFailure` union (`CommandInputError | NotLoggedInError | ProjectResolutionError`, via `isUsageFailure` in `src/commands/errors.ts`): one line on stderr, exit 1, no defect banner - rewrites the 17 "warns user to login" tests to assert the typed failure, and documents the rule in `ts/packages/cli/AGENTS.md` and the `cli-command` skill ## Context `Command.provide` and its siblings wrap the handler that exists when they are applied, so piping `requireLogin` after `Command.withSubcommands` on a group entry covers every subcommand with one line. `dev projects switch` is the only subcommand under a gated-looking group that does not need a login, so `projects` gates `list` directly. Providing the resolved project as a service is deferred to the next PR, where the `dev` tree's shared `--user-id`/`--project-name` flags and the surface service make its mode a group property rather than a per-call argument.

Alberto Schiabel committed Oct 15, 2026 at 18:17 UTC 0ff60713623fa0048798500be9aba482c1f6e180
70 files changed +538 -346
.agents/skills/cli-command/references/implementation.md
+1
@@ -17,6 +17,7 @@ test/src/commands/<group>/<name>/<group>.<name>.handler.test.ts handler-level
17 - Top-level commands use the same shape without a group: `src/commands/<name>/<name>.cmd.ts`.
18 - Register new commands through `src/commands/index.ts` or the nearest group entry.
19 - 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; `cli-main.ts` prints the message and exits 1. Do not add a per-command message-only error class.
20 +- A command that needs a login pipes `requireLogin` from `src/effects/require-auth.ts` on itself or on its group entry after `Command.withSubcommands`; the handler never checks `apiKey`. `resolveCommandProject` fails with `ProjectResolutionError`; let it flow, it prints and exits 1 like `CommandInputError`.
21 - 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.
22 - `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.
23
.agents/skills/effect-v4/SKILL.md
+2 -1
@@ -19,7 +19,8 @@ See [versions.json](versions.json) for the full matrix (also `typescript`, `vite
19 ## Read next
20
21 - [references/core-patterns.md](references/core-patterns.md) — services, layers, typed
22 - errors, Schema, choosing between `Effect.gen` and `Effect.fn`, and the v3→v4 rename table
22 + errors, Schema, choosing between `Effect.gen` and `Effect.fn`, driving time in tests with
23 + `TestClock` (fork, adjust until the fiber settles, join) instead of `it.live`, and the v3→v4 rename table
24 (labeled historical, for recognizing stale patterns).
25 - [references/cli-surface.md](references/cli-surface.md) — `effect/cli`:
26 `Command`, `Flag`, `Argument`, `GlobalFlag`, `CliConfig`, the custom
.agents/skills/effect-v4/references/core-patterns.md
+56
@@ -190,6 +190,62 @@ When in doubt: value → `Effect.gen`; function → a plain arrow returning `Eff
190 upgrading to `Effect.fn` when failure attribution in error reports is worth the annotation.
191 Do not migrate one form to the other wholesale.
192
193 +## Time in tests: drive `TestClock`, never wait on a real clock
194 +
195 +`it.effect` from `@effect/vitest` runs the test on a `TestClock` parked at epoch. Any sleep
196 +on Effect's clock inside the code under test (`Effect.sleep`, `Effect.retry` with a
197 +`Schedule`, `Effect.timeout`, the API client's retry backoff) only completes when the test
198 +moves that clock. Awaiting such an effect on the test's own fiber hangs until the vitest
199 +timeout, because nothing is left to advance time. Do not fix that with `it.live`: a live
200 +clock makes CI wait out the real backoff.
201 +
202 +The pattern is fork, then yield and adjust until the fiber settles, then join:
203 +
204 +```ts
205 +import { it } from '@effect/vitest';
206 +import { Effect, Fiber, Schedule } from 'effect';
207 +import { TestClock } from 'effect/testing';
208 +
209 +class Unreachable extends Error {
210 + readonly _tag = 'Unreachable';
211 +}
212 +
213 +// Stands in for a client call that retries with a backoff on Effect's clock:
214 +// `Schedule.max` stops when either schedule does, so two retries, half a second apart and doubling.
215 +const lookup: Effect.Effect<never, Unreachable> = Effect.fail(new Unreachable('fetch failed')).pipe(
216 + Effect.retry(Schedule.max([Schedule.exponential('500 millis'), Schedule.recurs(2)]))
217 +);
218 +
219 +it.effect('passes the failure through once the retries are spent', () =>
220 + Effect.gen(function* () {
221 + // 1. Run the effect on its own fiber so the test fiber stays free to move the clock.
222 + const fiber = yield* lookup.pipe(Effect.flip, Effect.forkChild);
223 + // 2. Let the forked fiber run, then advance past every retry; `adjust` resumes each sleep
224 + // in order, and a sleep scheduled by a resumed fiber inside the window is resumed too.
225 + // Loop on the fiber's own state: when the code under test crosses a Promise boundary
226 + // (a rejected `fetch`) before its first sleep, one yield is not guaranteed to reach it.
227 + for (let step = 0; step < 100 && fiber.pollUnsafe() === undefined; step++) {
228 + yield* Effect.yieldNow;
229 + yield* TestClock.adjust('1 minute');
230 + }
231 + // 3. Join: the fiber has settled, so this returns without waiting.
232 + const error = yield* Fiber.join(fiber);
233 + if (error._tag !== 'Unreachable') throw new Error('expected the failure to pass through');
234 + })
235 +);
236 +```
237 +
238 +Pick an `adjust` window larger than the whole schedule, not equal to one step; one call is
239 +enough because the clock resumes sleeps iteratively up to the target time. Real uses:
240 +`ts/packages/cli/test/src/services/command-project.test.ts` (the client's connection-failure
241 +retry) and `ts/packages/cli/test/src/commands/setup.cmd.test.ts` (a two-minute command
242 +timeout).
243 +
244 +`it.live` is for code that sleeps outside Effect's clock, such as a spawned process or a
245 +`setTimeout` inside a non-Effect library, and even then the test should shorten the wait
246 +(the client retry tests pass a `retry-after-ms: 0` header). Nothing in the CLI suite waits on
247 +wall-clock time.
248 +
249 ## v3 → v4 rename table (historical — recognize stale patterns, don't copy them)
250
251 Verified against `ts/vendor/effect/migration/v3-to-v4.md` and this migration's own
.agents/skills/typescript-testing/references/effect-v4-cli.md
+7 -4
@@ -13,8 +13,10 @@ repo-local `effect-v4` skill.
13
14 - `it.effect` is the default tester. It runs inside `Effect.scoped` automatically, so a v3-style
15 `it.scoped` is unnecessary — v4's `@effect/vitest` no longer exports `it.scoped`.
16 -- `it.live` runs against the real (non-`TestClock`) environment; reach for it only when a test must
17 - observe real wall-clock behavior.
16 +- `it.live` runs against the real (non-`TestClock`) environment. Reach for it only when the code
17 + under test sleeps outside Effect's clock; a retry, timeout, or `Effect.sleep` inside the code
18 + under test is driven on `it.effect` by forking the effect, looping `Effect.yieldNow` and `TestClock.adjust`
19 + until `fiber.pollUnsafe()` is set, and `Fiber.join` (see "Time in tests" in the `effect-v4` skill's core-patterns reference).
20 - Reusable service layers go through `layer(...)`, not manual `Effect.provide` scattered per test:
21
22 ```ts no-check
@@ -105,8 +107,9 @@ choice.
107 `Layer.provideMerge` over `Layer.provide` when the reference's value must stay visible to
108 everything downstream (see the `ConfigProvider` comment in `test-layer.ts` for the bug this
109 distinction fixed).
108 -- `TestClock` lives under `effect/testing`. The FastCheck bridge was removed in rc.113; native
109 - arbitrary generation lives under `effect/Arbitrary`.
110 +- `TestClock` lives under `effect/testing`; `TestClock.adjust('1 minute')` resumes every sleep
111 + scheduled inside the window, including ones a resumed retry schedules next. The FastCheck bridge
112 + was removed in rc.113; native arbitrary generation lives under `effect/Arbitrary`.
113
114 ## CLI behavior matrix
115
ts/packages/cli/AGENTS.md
+3 -2
@@ -85,6 +85,7 @@ Rules:
85 - `<group>.<name>.handler.ts` exports the handler as a function of a plain params type it declares itself; the command proves it provides those params when it passes the handler to `Command.make`. Do not derive the params type from the `Command` value (no phantom commands, no `GetCmdParams`).
86 - A command that exists in both the root tree and the `dev` tree is defined once. The group supplies what differs between the two surfaces through `Command.withSharedFlags` and `Command.provide`, not through a second `Command.make` with a copied description.
87 - Logic shared across groups belongs in `src/effects/` or `src/services/`, never in another command's directory.
88 +- A command that needs a logged-in user pipes `requireLogin` (`src/effects/require-auth.ts`) on itself or on its group entry, after `Command.withSubcommands`. Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`.
89 - A group entry is recognised by its place in the tree: `<dir>/<dir>.cmd.ts` or `<dir>/root-<dir>.cmd.ts` with other `.cmd.ts` files below `<dir>/`. The same name with nothing below it (`logout/logout.cmd.ts`) is a top-level command. Every command needs a test; a group entry does not, though one with a default action (`generate`) still gets one.
90
91 Legacy shape still present while commands migrate: `<group>/commands/<group>.<name>.cmd.ts` holding flags, handler, helpers, and errors in one file, and top-level `<name>.cmd.ts` doing the same. Migrate a command to the directory shape when you touch it for more than a one-line fix, one command per PR.
@@ -123,7 +124,7 @@ OS credential storage uses the sibling package `@composio/cli-keyring` (macOS Ke
124
125 ### Effects — `src/effects/`
126
126 -Reusable Effect computations: `setup-cache-dir`, `toolkit-version-overrides` (maps `COMPOSIO_TOOLKIT_VERSION_<NAME>=<ver>` pins to toolkit slugs), `validate-toolkit-versions`, `with-log-level`, `find-composio-core-generated`, `version`, `compare-semver`, `log-metrics`.
127 +Reusable Effect computations: `require-auth` (`requireLogin`, the login gate for commands and groups), `setup-cache-dir`, `toolkit-version-overrides` (maps `COMPOSIO_TOOLKIT_VERSION_<NAME>=<ver>` pins to toolkit slugs), `validate-toolkit-versions`, `with-log-level`, `find-composio-core-generated`, `version`, `compare-semver`, `log-metrics`.
128
129 ### Models — `src/models/`
130
@@ -211,7 +212,7 @@ Each `Arr.bind` adds one independent axis to the generated cases.
212 - Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Result`, `Exit`, `Cause`, `CliError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
213 - Do not wrap a plain `Error` in `Effect.fail` for expected failures. Give the failure a meaningful `Data.TaggedError` type with structured fields and a preserved cause, then recover with `catchTag` / `catchTags`. Reserve `Effect.die` and `Effect.dieMessage` for impossible invariants.
214 - Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. Each typed API response is validated at most once. The CLI's own schema validates a response the CLI transforms, filters for stdout, or writes to a cache file: the catalog models (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), the auth-config and connected-account allowlists that keep credential-bearing fields off stdout (including the list responses and the `auth-configs create` response in `src/models/auth-configs.ts` and `connected-accounts.ts`), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, and `TriggerInstanceItems`. Those calls pass `decode: false` and decode with the CLI schema, failing with `services/HttpDecodingError`. The client's generated schema validates a read only where the CLI consumes the whole response through the client's types and no field of it may drift: `cli.realtime.credentials` (every field feeds the realtime connection), `org.list` (organization ids and names for login), and `org.consumer.listConnectedToolkits` (a list of slugs). Those three are the loader table in `src/services/composio-schema-loaders.ts`; a mismatch fails with the client's `DecodeError`. Every other typed call passes `undecoded` (`decode: false`): calls that are not reads, because failing after the server acted would invite a retry that repeats the side effect; reads the CLI validates with its own schema; and reads that must tolerate drift because the CLI consumes a few fields of a response whose client schema fixes enums or requires fields the CLI never reads (`logs.tools.*`, `logs.triggers.*`, `tools.list`, `tools.retrieve`, `org.project.list`, `toolRouter.session.search`, `toolRouter.session.toolkits`, `connectedAccounts.list`, which tolerates unknown statuses, and `triggerInstances.listActive`, whose page counts the CLI defaults). A typed call with no loader and no `decode: false` fails before it is sent, so adding a client-decoded read means adding its loader to the table and saying in its doc comment why the CLI cannot tolerate drift there. Responses fetched with the raw `client.get`/`client.post` are untyped and always need a CLI schema (`LatestToolVersionResponse` in `src/models/tools.ts`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
214 -- Do not inspect private `effect/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — handler-level validation raises `CommandInputError` from `src/commands/errors.ts` (built with `commandInputError('<command>')`, carrying `command`, `message`, and the `option` at fault) and `cli-main.ts` prints its message as one line and exits 1, not a hand-built `CliError`.
215 +- Do not inspect private `effect/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — handler-level validation raises `CommandInputError` from `src/commands/errors.ts` (built with `commandInputError('<command>')`, carrying `command`, `message`, and the `option` at fault), not a hand-built `CliError`. It, `NotLoggedInError`, and `ProjectResolutionError` are the `UsageFailure` union (`isUsageFailure` in `errors.ts`): `cli-main.ts` prints the message as one line and exits 1, with no defect banner.
216 - Prefer `Effect.mapError`, `Effect.matchEffect`, and typed recovery over `Effect.catch` blocks (the v4 name for what was `Effect.catchAll`) that flatten distinct failures into one message-only error.
217
218 ### Effect Boundary Policy
ts/packages/cli/src/cli-main.ts
+5 -4
@@ -53,7 +53,7 @@ import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overri
53 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
54 import { SetupCommandError } from 'src/services/setup-command-error';
55 import { ShellSetupAbortError } from 'src/commands/install.cmd';
56 -import { CommandInputError } from 'src/commands/errors';
56 +import { isUsageFailure, type UsageFailure } from 'src/commands/errors';
57 import { cliInvocationContext } from 'src/services/runtime-cli-context';
58 import { readTelemetryDebugOverride, telemetryDebugModeLayer } from 'src/services/runtime-flags';
59 import { normalizeRunScriptArgs } from 'src/commands/argv-compat';
@@ -263,10 +263,11 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
263 process.exitCode = 1;
264 })
265 ),
266 - // A usage mistake is not a broken invariant: print the one-line fix and exit non-zero
267 - // instead of routing it through the defect reporter below.
266 + // A usage mistake, a missing login, or an unresolved project is not a broken invariant:
267 + // print the one-line fix and exit non-zero instead of routing it through the defect
268 + // reporter below.
269 Effect.catchIf(
269 - (error): error is CommandInputError => error instanceof CommandInputError,
270 + (error): error is UsageFailure => isUsageFailure(error),
271 error =>
272 Effect.gen(function* () {
273 const ui = yield* TerminalUI;
ts/packages/cli/src/commands/auth-configs/auth-configs.cmd.ts
+3 -1
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { authConfigsCmd$List } from './commands/auth-configs.list.cmd';
4 import { authConfigsCmd$Info } from './commands/auth-configs.info.cmd';
@@ -13,5 +14,6 @@ import { authConfigsCmd$Create } from './commands/auth-configs.create.cmd';
14 */
15 export const authConfigsCmd = Command.make('auth-configs').pipe(
16 Command.withDescription('View and manage Composio auth configs.'),
16 - Command.withSubcommands([authConfigsCmd$List, authConfigsCmd$Info, authConfigsCmd$Create])
17 + Command.withSubcommands([authConfigsCmd$List, authConfigsCmd$Info, authConfigsCmd$Create]),
18 + requireLogin
19 );
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.create.cmd.ts
-3
@@ -4,7 +4,6 @@ import type { AuthConfigCreateParams } from '@composio/client/resources/auth-con
4 import { parseJsonRecord } from 'src/utils/parse-json';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 -import { requireAuth } from 'src/effects/require-auth';
7 import { handleClientApiError } from 'src/effects/handle-http-error';
8 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
9 import { redact } from 'src/ui/redact';
@@ -54,8 +53,6 @@ export const authConfigsCmd$Create = Command.make(
53 { name, toolkit, authScheme, scopes, customCredentials },
54 ({ name, toolkit, authScheme, scopes, customCredentials }) =>
55 Effect.gen(function* () {
57 - if (!(yield* requireAuth)) return;
58 -
56 const ui = yield* TerminalUI;
57 const repo = yield* ComposioToolkitsRepository;
58
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.info.cmd.ts
-3
@@ -2,7 +2,6 @@ import { Effect, Option } from 'effect';
2 import { Argument, Command } from 'effect/cli';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { requireAuth } from 'src/effects/require-auth';
5 import { handleClientApiError } from 'src/effects/handle-http-error';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 import { formatAuthConfigInfo } from '../format';
@@ -22,8 +21,6 @@ const id = Argument.String('id').pipe(
21 */
22 export const authConfigsCmd$Info = Command.make('info', { id }, ({ id }) =>
23 Effect.gen(function* () {
25 - if (!(yield* requireAuth)) return;
26 -
24 const ui = yield* TerminalUI;
25 const repo = yield* ComposioToolkitsRepository;
26
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.list.cmd.ts
-3
@@ -2,7 +2,6 @@ import { Effect, Option } from 'effect';
2 import { Command, Flag } from 'effect/cli';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { requireAuth } from 'src/effects/require-auth';
5 import { clampLimit } from 'src/ui/clamp-limit';
6 import { redact } from 'src/ui/redact';
7 import { formatAuthConfigsTable, formatAuthConfigsJson } from '../format';
@@ -37,8 +36,6 @@ export const authConfigsCmd$List = Command.make(
36 { toolkits, query, limit },
37 ({ toolkits, query, limit }) =>
38 Effect.gen(function* () {
40 - if (!(yield* requireAuth)) return;
41 -
39 const ui = yield* TerminalUI;
40 const repo = yield* ComposioToolkitsRepository;
41
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.info.cmd.ts
-3
@@ -2,7 +2,6 @@ import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { requireAuth } from 'src/effects/require-auth';
5 import { handleClientApiError } from 'src/effects/handle-http-error';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 import { formatConnectedAccountInfo } from '../format';
@@ -22,8 +21,6 @@ const id = Argument.String('id').pipe(
21 */
22 export const connectedAccountsCmd$Info = Command.make('info', { id }, ({ id }) =>
23 Effect.gen(function* () {
25 - if (!(yield* requireAuth)) return;
26 -
24 const ui = yield* TerminalUI;
25 const repo = yield* ComposioToolkitsRepository;
26
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+9 -12
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { commandInputError } from 'src/commands/errors';
3 import { Argument, Command, Flag } from 'effect/cli';
4 import { Data, Effect, Option, Schedule } from 'effect';
@@ -5,17 +6,13 @@ import type { ComposioClientShape } from '@composio/client/effect';
6 import open from 'open';
7 import { ComposioUserContext } from 'src/services/user-context';
8 import { TerminalUI } from 'src/services/terminal-ui';
8 -import { requireAuth } from 'src/effects/require-auth';
9 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
10 import { extractApiErrorDetails, extractMessage } from 'src/utils/api-error-extraction';
11 import { ProjectContext } from 'src/services/project-context';
12 import { ComposioClientSingleton } from 'src/services/composio-clients';
13 import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
14 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
15 -import {
16 - formatResolveCommandProjectError,
17 - resolveCommandProject,
18 -} from 'src/services/command-project';
15 +import { resolveCommandProject } from 'src/services/command-project';
16 import {
17 invalidateConsumerConnectedToolkitsCache,
18 writeConsumerConnectedToolkitsCache,
@@ -512,7 +509,7 @@ const handleListConnectedAccounts = (params: {
509 const resolvedProject = yield* resolveCommandProject({
510 mode: 'consumer',
511 projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
515 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
512 + });
513 const client = yield* params.clientSingleton.getFor({
514 orgId: resolvedProject.orgId,
515 projectId: resolvedProject.projectId,
@@ -661,7 +658,7 @@ const handleLegacyAuthConfigLink = (params: {
658 const resolvedProject = yield* resolveCommandProject({
659 mode: 'developer',
660 projectName: Option.getOrUndefined(params.projectName),
664 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
661 + });
662 const client = yield* params.clientSingleton.getFor({
663 orgId: resolvedProject.orgId,
664 projectId: resolvedProject.projectId,
@@ -778,8 +775,6 @@ const runConnectedAccountsLink = (params: {
775 rootOnly: boolean;
776 }) =>
777 Effect.gen(function* () {
781 - if (!(yield* requireAuth)) return;
782 -
778 const normalizedAliasOption = yield* resolveNormalizedAliasOption(params.alias);
779
780 const ui = yield* TerminalUI;
@@ -854,7 +849,7 @@ const runConnectedAccountsLink = (params: {
849 const resolvedProject = yield* resolveCommandProject({
850 mode: 'consumer',
851 projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
857 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
852 + });
853 const resolvedUserId =
854 resolvedProject.projectType === 'CONSUMER'
855 ? Option.fromNullishOr(resolvedProject.consumerUserId)
@@ -1049,7 +1044,8 @@ export const connectedAccountsCmd$Link = Command.make(
1044 ...example,
1045 command: example.command.replace('composio link', 'composio dev connected-accounts link'),
1046 }))
1052 - )
1047 + ),
1048 + requireLogin
1049 );
1050
1051 export const rootConnectedAccountsCmd$Link = Command.make(
@@ -1074,5 +1070,6 @@ export const rootConnectedAccountsCmd$Link = Command.make(
1070 Command.withShortDescription(
1071 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.'
1072 ),
1077 - Command.withExamples(linkExamples)
1073 + Command.withExamples(linkExamples),
1074 + requireLogin
1075 );
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts
+2 -8
@@ -3,13 +3,9 @@ import { Data, Effect, Option } from 'effect';
3 import { ComposioClientSingleton } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
6 -import { requireAuth } from 'src/effects/require-auth';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { redact } from 'src/ui/redact';
9 -import {
10 - formatResolveCommandProjectError,
11 - resolveCommandProject,
12 -} from 'src/services/command-project';
8 +import { resolveCommandProject } from 'src/services/command-project';
9 import { formatConnectedAccountsTable, formatConnectedAccountsJson } from '../format';
10
11 class ConnectedAccountsListRequestError extends Data.TaggedError(
@@ -59,8 +55,6 @@ export const connectedAccountsCmd$List = Command.make(
55 { toolkits, userId, status, limit },
56 ({ toolkits, userId, status, limit }) =>
57 Effect.gen(function* () {
62 - if (!(yield* requireAuth)) return;
63 -
58 const ui = yield* TerminalUI;
59 const clientSingleton = yield* ComposioClientSingleton;
60
@@ -69,7 +63,7 @@ export const connectedAccountsCmd$List = Command.make(
63 : undefined;
64 const resolvedProject = yield* resolveCommandProject({
65 mode: 'developer',
72 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
66 + });
67 const client = yield* clientSingleton.getFor({
68 orgId: resolvedProject.orgId,
69 projectId: resolvedProject.projectId,
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.whoami.cmd.ts
-3
@@ -2,7 +2,6 @@ import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { requireAuth } from 'src/effects/require-auth';
5 import { handleClientApiError } from 'src/effects/handle-http-error';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 import { formatConnectedAccountWhoami } from '../format';
@@ -26,8 +25,6 @@ const id = Argument.String('id').pipe(
25 */
26 export const connectedAccountsCmd$Whoami = Command.make('whoami', { id }, ({ id }) =>
27 Effect.gen(function* () {
29 - if (!(yield* requireAuth)) return;
30 -
28 const ui = yield* TerminalUI;
29 const repo = yield* ComposioToolkitsRepository;
30
ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts
+3 -1
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { connectedAccountsCmd$List } from './commands/connected-accounts.list.cmd';
4 import { connectedAccountsCmd$Info } from './commands/connected-accounts.info.cmd';
@@ -19,5 +20,6 @@ export const connectedAccountsCmd = Command.make('connected-accounts').pipe(
20 connectedAccountsCmd$List,
21 connectedAccountsCmd$Info,
22 connectedAccountsCmd$Whoami,
22 - ])
23 + ]),
24 + requireLogin
25 );
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+2 -8
@@ -1,13 +1,9 @@
1 import { Data, Effect, Option } from 'effect';
2 import { Command, Flag } from 'effect/cli';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 -import { requireAuth } from 'src/effects/require-auth';
4 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
7 -import {
8 - formatResolveCommandProjectError,
9 - resolveCommandProject,
10 -} from 'src/services/command-project';
6 +import { resolveCommandProject } from 'src/services/command-project';
7 import { TerminalUI } from 'src/services/terminal-ui';
8 import {
9 getConnectedAccountPermissionGroup,
@@ -63,14 +59,12 @@ const formatConnectionsJson = (
59
60 export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit }) =>
61 Effect.gen(function* () {
66 - if (!(yield* requireAuth)) return;
67 -
62 const ui = yield* TerminalUI;
63 const clientSingleton = yield* ComposioClientSingleton;
64 const toolkitSlug = Option.getOrUndefined(toolkit);
65 const resolvedProject = yield* resolveCommandProject({
66 mode: 'consumer',
73 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
67 + });
68
69 const consumerUserId = resolvedProject.consumerUserId;
70 if (!consumerUserId) {
ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
+2 -8
@@ -1,13 +1,9 @@
1 import { Data, Effect } from 'effect';
2 import { Argument, Command } from 'effect/cli';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 -import { requireAuth } from 'src/effects/require-auth';
4 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
7 -import {
8 - formatResolveCommandProjectError,
9 - resolveCommandProject,
10 -} from 'src/services/command-project';
6 +import { resolveCommandProject } from 'src/services/command-project';
7 import { TerminalUI } from 'src/services/terminal-ui';
8 import { bold } from 'src/ui/colors';
9 import { redact } from 'src/ui/redact';
@@ -96,13 +92,11 @@ const resolveAccount = (params: {
92
93 export const connectionsCmd$Remove = Command.make('remove', { account }, ({ account }) =>
94 Effect.gen(function* () {
99 - if (!(yield* requireAuth)) return;
100 -
95 const ui = yield* TerminalUI;
96 const clientSingleton = yield* ComposioClientSingleton;
97 const resolvedProject = yield* resolveCommandProject({
98 mode: 'consumer',
105 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
99 + });
100
101 const consumerUserId = resolvedProject.consumerUserId;
102 if (!consumerUserId) {
ts/packages/cli/src/commands/connections/connections.cmd.ts
+3 -1
@@ -1,8 +1,10 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { connectionsCmd$List } from './commands/connections.list.cmd';
4 import { connectionsCmd$Remove } from './commands/connections.remove.cmd';
5
6 export const rootConnectionsCmd = Command.make('connections').pipe(
7 Command.withDescription('Inspect and remove connected toolkit accounts.'),
7 - Command.withSubcommands([connectionsCmd$List, connectionsCmd$Remove])
8 + Command.withSubcommands([connectionsCmd$List, connectionsCmd$Remove]),
9 + requireLogin
10 );
ts/packages/cli/src/commands/debug.cmd.ts
+9 -6
@@ -5,10 +5,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
5 import { renderCommandHintGraph } from 'src/services/command-hints';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { detectMasterFromHost } from 'src/services/master-detector';
8 -import {
9 - formatResolveCommandProjectError,
10 - resolveCommandProject,
11 -} from 'src/services/command-project';
8 +import { resolveCommandProject } from 'src/services/command-project';
9
10 const debugError = commandInputError('debug');
11
@@ -33,9 +30,15 @@ const printDebugApiInfo = Effect.gen(function* () {
30 return yield* debugError('No user API key found in the current CLI session.');
31 }
32 const orgId = Option.getOrUndefined(ctx.data.orgId);
33 + // A project the user has not set up yet is a legitimate "none" here; a failed lookup is not,
34 + // and keeps its typed error so cli-main prints it and exits non-zero.
35 const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
37 - Effect.mapError(formatResolveCommandProjectError),
38 - Effect.option
36 + Effect.map(Option.some),
37 + Effect.catchTag('services/ProjectResolutionError', error =>
38 + error.reason === 'missing_org' || error.reason === 'missing_developer_project'
39 + ? Effect.succeed(Option.none())
40 + : Effect.fail(error)
41 + )
42 );
43 return yield* ui.output(
44 JSON.stringify(
ts/packages/cli/src/commands/dev.cmd.ts
+2 -1
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command, Flag } from 'effect/cli';
3 import { Effect, Option } from 'effect';
4 import { CommandInputError } from './errors';
@@ -23,7 +24,7 @@ const devMode = Flag.Literals('mode', ['on', 'off'] as const).pipe(
24 export const devSubcommands = [
25 initCmd,
26 devToolsCmd$Execute,
26 - triggersCmd$Listen,
27 + triggersCmd$Listen.pipe(requireLogin),
28 logsCmd,
29 toolkitsCmd,
30 authConfigsCmd,
ts/packages/cli/src/commands/errors.ts
+20
@@ -1,4 +1,5 @@
1 import { Data } from 'effect';
2 +import { ProjectResolutionError } from 'src/services/command-project';
3
4 /**
5 * A usage mistake the parser cannot see: a flag combination, a value that fails a business
@@ -15,6 +16,25 @@ export class CommandInputError extends Data.TaggedError('commands/CommandInputEr
16 readonly option?: string | undefined;
17 }> {}
18
19 +/** The command needs a logged-in user and `~/.composio` holds no API key. */
20 +export class NotLoggedInError extends Data.TaggedError('commands/NotLoggedInError')<{
21 + readonly message: string;
22 +}> {}
23 +
24 +export const notLoggedIn = (): NotLoggedInError =>
25 + new NotLoggedInError({ message: 'You are not logged in yet. Please run `composio login`.' });
26 +
27 +/**
28 + * Failures the user fixes by changing the invocation or their setup, not defects. `cli-main.ts`
29 + * prints the message as one line on stderr and exits 1.
30 + */
31 +export type UsageFailure = CommandInputError | NotLoggedInError | ProjectResolutionError;
32 +
33 +export const isUsageFailure = (error: unknown): error is UsageFailure =>
34 + error instanceof CommandInputError ||
35 + error instanceof NotLoggedInError ||
36 + error instanceof ProjectResolutionError;
37 +
38 /** Builds the constructor a command uses for its own input errors. */
39 export const commandInputError =
40 (command: string) =>
ts/packages/cli/src/commands/listen.cmd.ts
+5 -19
@@ -1,16 +1,13 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { commandInputError } from 'src/commands/errors';
3 import { Argument, Command, Flag } from 'effect/cli';
4 import * as FileSystem from 'effect/FileSystem';
5 import * as Path from 'effect/Path';
6 import type { ComposioClientShape } from '@composio/client/effect';
7 import { Data, Deferred, Effect, Result, Option, Predicate } from 'effect';
7 -import { requireAuth } from 'src/effects/require-auth';
8 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
9 import { ComposioClientSingleton, type ToolkitProjectScope } from 'src/services/composio-clients';
10 -import {
11 - formatResolveCommandProjectError,
12 - resolveCommandProject,
13 -} from 'src/services/command-project';
10 +import { resolveCommandProject } from 'src/services/command-project';
11 import {
12 resolveArtifactsRoot,
13 resolveCliSessionArtifacts,
@@ -489,8 +486,6 @@ export const listenCmd = Command.make(
486 { slug, params, maxEvents, timeout, stream, account, debug },
487 ({ slug, params, maxEvents, timeout, stream, account, debug }) =>
488 Effect.gen(function* () {
492 - if (!(yield* requireAuth)) return;
493 -
489 const ui = yield* TerminalUI;
490 const fs = yield* FileSystem.FileSystem;
491 const path = yield* Path.Path;
@@ -498,17 +493,7 @@ export const listenCmd = Command.make(
493 const clientSingleton = yield* ComposioClientSingleton;
494 const realtime = yield* TriggersRealtime;
495
501 - const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
502 - Effect.mapError(cause => {
503 - const formatted = formatResolveCommandProjectError(cause);
504 - return new ListenCommandError({
505 - reason: 'project_context',
506 - message: formatted.message,
507 - slug,
508 - cause,
509 - });
510 - })
511 - );
496 + const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' });
497
498 const client = yield* clientSingleton.getFor({
499 orgId: resolvedProject.orgId,
@@ -760,5 +745,6 @@ export const listenCmd = Command.make(
745 {
746 command: "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
747 },
763 - ])
748 + ]),
749 + requireLogin
750 );
ts/packages/cli/src/commands/logs/commands/logs.tools.cmd.ts
-3
@@ -1,6 +1,5 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 import { Data, Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
3 import { TerminalUI } from 'src/services/terminal-ui';
4 import { ComposioClientSingleton } from 'src/services/composio-clients';
5 import { undecoded } from 'src/services/composio-request';
@@ -169,8 +168,6 @@ export const logsCmd$Tools = Command.make(
168 sessionId,
169 }) =>
170 Effect.gen(function* () {
172 - if (!(yield* requireAuth)) return;
173 -
171 const ui = yield* TerminalUI;
172 const clientSingleton = yield* ComposioClientSingleton;
173 const client = yield* clientSingleton.get();
ts/packages/cli/src/commands/logs/commands/logs.triggers.cmd.ts
-3
@@ -1,6 +1,5 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 import { Data, Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
3 import { TerminalUI } from 'src/services/terminal-ui';
4 import { ComposioClientSingleton } from 'src/services/composio-clients';
5 import { undecoded } from 'src/services/composio-request';
@@ -126,8 +125,6 @@ export const logsCmd$Triggers = Command.make(
125 includePayload,
126 }) =>
127 Effect.gen(function* () {
129 - if (!(yield* requireAuth)) return;
130 -
128 const ui = yield* TerminalUI;
129 const clientSingleton = yield* ComposioClientSingleton;
130 const client = yield* clientSingleton.get();
ts/packages/cli/src/commands/logs/logs.cmd.ts
+3 -1
@@ -1,4 +1,5 @@
1 import { Command } from 'effect/cli';
2 +import { requireLogin } from 'src/effects/require-auth';
3 import { logsCmd$Tools } from './commands/logs.tools.cmd';
4 import { logsCmd$Triggers } from './commands/logs.triggers.cmd';
5
@@ -12,5 +13,6 @@ import { logsCmd$Triggers } from './commands/logs.triggers.cmd';
13 */
14 export const logsCmd = Command.make('logs').pipe(
15 Command.withDescription('Inspect trigger and tool execution logs.'),
15 - Command.withSubcommands([logsCmd$Triggers, logsCmd$Tools])
16 + Command.withSubcommands([logsCmd$Triggers, logsCmd$Tools]),
17 + requireLogin
18 );
ts/packages/cli/src/commands/orgs/commands/orgs.list.cmd.ts
-3
@@ -1,6 +1,5 @@
1 import { Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
3 import { TerminalUI } from 'src/services/terminal-ui';
4 import { listOrganizations } from 'src/services/composio-account';
5 import { ComposioUserContext } from 'src/services/user-context';
@@ -13,8 +12,6 @@ const limit = Flag.Int('limit').pipe(
12
13 export const orgsCmd$List = Command.make('list', { limit }, ({ limit }) =>
14 Effect.gen(function* () {
16 - if (!(yield* requireAuth)) return;
17 -
15 const ui = yield* TerminalUI;
16 const ctx = yield* ComposioUserContext;
17 const apiKey = Option.getOrUndefined(ctx.data.apiKey);
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
-3
@@ -1,6 +1,5 @@
1 import { Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
3 import { runOrgSelection } from 'src/effects/select-org-project';
4 import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity';
5 import { TerminalUI } from 'src/services/terminal-ui';
@@ -18,8 +17,6 @@ const limit = Flag.Int('limit').pipe(
17
18 export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId, limit }) =>
19 Effect.gen(function* () {
21 - if (!(yield* requireAuth)) return;
22 -
20 const ui = yield* TerminalUI;
21 const ctx = yield* ComposioUserContext;
22 yield* ui.intro('composio orgs switch');
ts/packages/cli/src/commands/orgs/orgs.cmd.ts
+3 -1
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { orgsCmd$List } from './commands/orgs.list.cmd';
4 import { orgsCmd$Switch } from './commands/orgs.switch.cmd';
@@ -7,5 +8,6 @@ import { orgsCmd$Switch } from './commands/orgs.switch.cmd';
8 */
9 export const orgsCmd = Command.make('orgs').pipe(
10 Command.withDescription('Manage default global organization/project context.'),
10 - Command.withSubcommands([orgsCmd$List, orgsCmd$Switch])
11 + Command.withSubcommands([orgsCmd$List, orgsCmd$Switch]),
12 + requireLogin
13 );
ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts
+5 -4
@@ -1,6 +1,6 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command, Flag } from 'effect/cli';
3 import { Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { listOrganizationProjects } from 'src/services/composio-account';
6 import { ComposioUserContext } from 'src/services/user-context';
@@ -18,8 +18,6 @@ const limit = Flag.Int('limit').pipe(
18
19 export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId, limit }) =>
20 Effect.gen(function* () {
21 - if (!(yield* requireAuth)) return;
22 -
21 const ui = yield* TerminalUI;
22 const ctx = yield* ComposioUserContext;
23 yield* ui.intro('composio dev projects list');
@@ -79,4 +77,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
77 )
78 );
79 })
82 -).pipe(Command.withDescription('List developer projects for the current organization.'));
80 +).pipe(
81 + Command.withDescription('List developer projects for the current organization.'),
82 + requireLogin
83 +);
ts/packages/cli/src/commands/proxy.cmd.ts
+5 -11
@@ -1,10 +1,10 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Argument, Command, Flag } from 'effect/cli';
3 import { Data, Effect, Result, Option } from 'effect';
4 import type {
5 SessionProxyExecuteParams,
6 SessionProxyExecuteResponse,
7 } from '@composio/client/resources/tool-router/session';
7 -import { requireAuth } from 'src/effects/require-auth';
8 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
9 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
10 import {
@@ -13,10 +13,7 @@ import {
13 } from 'src/services/consumer-short-term-cache';
14 import { TerminalUI } from 'src/services/terminal-ui';
15 import { ComposioClientSingleton } from 'src/services/composio-clients';
16 -import {
17 - resolveCommandProject,
18 - formatResolveCommandProjectError,
19 -} from 'src/services/command-project';
16 +import { resolveCommandProject } from 'src/services/command-project';
17 import {
18 ComposioNoActiveConnectionError,
19 mapComposioError,
@@ -288,13 +285,9 @@ export const proxyCmd = Command.make('proxy', {
285 Command.withHandler(options =>
286 Effect.gen(function* () {
287 const { endpoint, toolkit, account, method, headers, data, skipConnectionCheck } = options;
291 - if (!(yield* requireAuth)) return;
292 -
288 const ui = yield* TerminalUI;
289 const clientSingleton = yield* ComposioClientSingleton;
295 - const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
296 - Effect.mapError(formatResolveCommandProjectError)
297 - );
290 + const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' });
291
292 if (resolvedProject.projectType !== 'CONSUMER' || !resolvedProject.consumerUserId) {
293 return yield* new ProxyCommandError({
@@ -411,5 +404,6 @@ export const proxyCmd = Command.make('proxy', {
404 yield* ui.output(output);
405 }
406 })
414 - )
407 + ),
408 + requireLogin
409 );
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
-3
@@ -3,7 +3,6 @@ import { Data, Effect, Option } from 'effect';
3 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { undecoded } from 'src/services/composio-request';
6 -import { requireAuth } from 'src/effects/require-auth';
6 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
7 import { extractMessage } from 'src/utils/api-error-extraction';
8 import { ProjectContext } from 'src/services/project-context';
@@ -47,8 +46,6 @@ export const toolkitsCmd$Info = Command.make(
46 { slug, userId, allDetails },
47 ({ slug, userId, allDetails }) =>
48 Effect.gen(function* () {
50 - if (!(yield* requireAuth)) return;
51 -
49 const ui = yield* TerminalUI;
50 const projectContext = yield* ProjectContext;
51 const userContext = yield* ComposioUserContext;
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
-3
@@ -2,7 +2,6 @@ import process from 'node:process';
2 import { Command, Flag } from 'effect/cli';
3 import { Data, Effect, Option } from 'effect';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { requireAuth } from 'src/effects/require-auth';
5 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
6 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { undecoded } from 'src/services/composio-request';
@@ -57,8 +56,6 @@ export const toolkitsCmd$List = Command.make(
56 { query, limit, connected, userId },
57 ({ query, limit, connected, userId }) =>
58 Effect.gen(function* () {
60 - if (!(yield* requireAuth)) return;
61 -
59 const ui = yield* TerminalUI;
60 const repo = yield* ComposioToolkitsRepository;
61 const clientSingleton = yield* ComposioClientSingleton;
ts/packages/cli/src/commands/toolkits/commands/toolkits.search.cmd.ts
-3
@@ -3,7 +3,6 @@ import { Argument, Command, Flag } from 'effect/cli';
3 import { Effect } from 'effect';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 -import { requireAuth } from 'src/effects/require-auth';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { extractMessage } from 'src/utils/api-error-extraction';
8 import { mergeToolkitData, formatToolkitsTable, formatToolkitsJson } from '../format';
@@ -31,8 +30,6 @@ const limit = Flag.Int('limit').pipe(
30 */
31 export const toolkitsCmd$Search = Command.make('search', { query, limit }, ({ query, limit }) =>
32 Effect.gen(function* () {
34 - if (!(yield* requireAuth)) return;
35 -
33 const ui = yield* TerminalUI;
34 const repo = yield* ComposioToolkitsRepository;
35
ts/packages/cli/src/commands/toolkits/commands/toolkits.version.cmd.ts
-3
@@ -1,6 +1,5 @@
1 import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
3 import { ComposioClientSingleton } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { extractMessage } from 'src/utils/api-error-extraction';
@@ -16,8 +15,6 @@ const slug = Argument.String('slug').pipe(Argument.withDescription('Toolkit slug
15 */
16 export const toolkitsCmd$Version = Command.make('version', { slug }, ({ slug }) =>
17 Effect.gen(function* () {
19 - if (!(yield* requireAuth)) return;
20 -
18 const ui = yield* TerminalUI;
19 const clientSingleton = yield* ComposioClientSingleton;
20 const client = yield* clientSingleton.get();
ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts
+3 -1
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { toolkitsCmd$List } from './commands/toolkits.list.cmd';
4 import { toolkitsCmd$Info } from './commands/toolkits.info.cmd';
@@ -19,5 +20,6 @@ export const toolkitsCmd = Command.make('toolkits').pipe(
20 toolkitsCmd$Info,
21 toolkitsCmd$Search,
22 toolkitsCmd$Version,
22 - ])
23 + ]),
24 + requireLogin
25 );
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+8 -13
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { commandInputError } from 'src/commands/errors';
3 import { Argument, Command, Flag } from 'effect/cli';
4 import util from 'node:util';
@@ -5,7 +6,6 @@ import { Data, Effect, Context, Option, Result } from 'effect';
6 import { redact } from 'src/ui/redact';
7 import { parseJsonRecord, isPlainRecord } from 'src/utils/parse-json';
8 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
8 -import { requireAuth } from 'src/effects/require-auth';
9 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
10 import {
11 getOrFetchToolInputDefinition,
@@ -35,10 +35,7 @@ import {
35 isMaybeToolNotFoundError,
36 } from 'src/analytics/events';
37 import { ComposioClientSingleton } from 'src/services/composio-clients';
38 -import {
39 - resolveCommandProject,
40 - formatResolveCommandProjectError,
41 -} from 'src/services/command-project';
38 +import { resolveCommandProject } from 'src/services/command-project';
39 import { commandHintStep } from 'src/services/command-hints';
40 import {
41 getFreshConsumerConnectedToolkitsFromCache,
@@ -873,7 +870,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
870 mode: params.projectMode,
871 projectName:
872 params.surface === 'root' ? undefined : Option.getOrUndefined(params.projectName),
876 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
873 + });
874 const clientSingleton = yield* ComposioClientSingleton;
875 const userContext = yield* ComposioUserContext;
876 const projectContext = yield* ProjectContext;
@@ -980,7 +977,7 @@ const resolveSchemaContext = (params: SharedRunToolsExecuteParams) =>
977 mode: params.projectMode,
978 projectName:
979 params.surface === 'root' ? undefined : Option.getOrUndefined(params.projectName),
983 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
980 + });
981 const ui = yield* TerminalUI;
982
983 return {
@@ -1324,8 +1321,6 @@ const runExecuteWithSpinner = (params: {
1321
1322 const runToolsExecute = (params: RunToolsExecuteParams) =>
1323 Effect.gen(function* () {
1327 - if (!(yield* requireAuth)) return;
1328 -
1324 if (params.getSchema) {
1325 const context = yield* resolveSchemaContext(params);
1326 const definition = yield* getOrFetchToolInputDefinition(params.slug, {
@@ -1713,8 +1708,6 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
1708
1709 const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1710 Effect.gen(function* () {
1716 - if (!(yield* requireAuth)) return;
1717 -
1711 if (params.getSchema) {
1712 return yield* runParallelSchemaFetchFromParsed(params);
1713 }
@@ -2008,7 +2001,8 @@ export const rootToolsCmd$Execute = Command.make(
2001 Command.withShortDescription(
2002 'Execute a tool by slug. Validates inputs against cached schemas and checks connections'
2003 ),
2011 - Command.withExamples(executeExamples)
2004 + Command.withExamples(executeExamples),
2005 + requireLogin
2006 );
2007
2008 export const devToolsCmd$Execute = Command.make(
@@ -2082,5 +2076,6 @@ export const devToolsCmd$Execute = Command.make(
2076 ...example,
2077 command: example.command.replace('composio execute', 'composio dev playground-execute'),
2078 }))
2085 - )
2079 + ),
2080 + requireLogin
2081 );
ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts
-3
@@ -2,7 +2,6 @@ import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { requireAuth } from 'src/effects/require-auth';
5 import { handleClientApiError } from 'src/effects/handle-http-error';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
@@ -25,8 +24,6 @@ const slug = Argument.String('slug').pipe(
24 */
25 export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
26 Effect.gen(function* () {
28 - if (!(yield* requireAuth)) return;
29 -
27 const ui = yield* TerminalUI;
28 const repo = yield* ComposioToolkitsRepository;
29
ts/packages/cli/src/commands/tools/commands/tools.list.cmd.ts
-3
@@ -2,7 +2,6 @@ import { Argument, Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { requireAuth } from 'src/effects/require-auth';
5 import { commandHintStep } from 'src/services/command-hints';
6 import { isRemoteCustomToolkitSlug } from 'src/utils/remote-custom-toolkit';
7 import { clampLimit } from 'src/ui/clamp-limit';
@@ -42,8 +41,6 @@ export const toolsCmd$List = Command.make(
41 { toolkit, query, tags, limit },
42 ({ toolkit, query, tags, limit }) =>
43 Effect.gen(function* () {
45 - if (!(yield* requireAuth)) return;
46 -
44 const ui = yield* TerminalUI;
45 const repo = yield* ComposioToolkitsRepository;
46
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+7 -10
@@ -1,9 +1,9 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { commandInputError } from 'src/commands/errors';
3 import { Argument, Command, Flag } from 'effect/cli';
4 import type { SessionSearchResponse } from '@composio/client/resources/tool-router';
5 import { Data, Effect, Option } from 'effect';
6 import { TerminalUI } from 'src/services/terminal-ui';
6 -import { requireAuth } from 'src/effects/require-auth';
7 import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 import { clampLimit } from 'src/ui/clamp-limit';
9 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
@@ -13,10 +13,7 @@ import type { Tool } from 'src/models/tools';
13 import { ComposioUserContext } from 'src/services/user-context';
14 import { ComposioClientSingleton } from 'src/services/composio-clients';
15 import { undecoded } from 'src/services/composio-request';
16 -import {
17 - resolveCommandProject,
18 - formatResolveCommandProjectError,
19 -} from 'src/services/command-project';
16 +import { resolveCommandProject } from 'src/services/command-project';
17 import { commandHintExample, commandHintStep } from 'src/services/command-hints';
18 import { isRemoteCustomToolSlug } from 'src/utils/remote-custom-toolkit';
19 import { toolInputRequiredError } from 'src/utils/tool-input-required';
@@ -305,8 +302,6 @@ const runToolsSearch = (params: {
302 rootOnly: boolean;
303 }) =>
304 Effect.gen(function* () {
308 - if (!(yield* requireAuth)) return;
309 -
305 const ui = yield* TerminalUI;
306 const userContext = yield* ComposioUserContext;
307
@@ -330,7 +325,7 @@ const runToolsSearch = (params: {
325 const resolvedProject = yield* resolveCommandProject({
326 mode: 'consumer',
327 projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
333 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
328 + });
329 const resolvedUserId =
330 resolvedProject.projectType === 'CONSUMER'
331 ? Option.fromNullishOr(resolvedProject.consumerUserId)
@@ -562,7 +557,8 @@ export const toolsCmd$Search = Command.make(
557 " composio execute <slug> -d '{ ... }' Run a tool from the results",
558 " composio tools info <slug> Inspect a tool's schema before executing",
559 ].join('\n')
565 - )
560 + ),
561 + requireLogin
562 );
563
564 export const rootToolsCmd$Search = Command.make(
@@ -614,5 +610,6 @@ export const rootToolsCmd$Search = Command.make(
610 command: 'composio search "list calendar events" --toolkits google_calendar --limit 5',
611 description: 'Narrow results to a specific toolkit',
612 },
617 - ])
613 + ]),
614 + requireLogin
615 );
ts/packages/cli/src/commands/tools/tools.cmd.ts
+3 -1
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { toolsCmd$List } from './commands/tools.list.cmd';
4 import { toolsCmd$Info } from './commands/tools.info.cmd';
@@ -12,5 +13,6 @@ export const rootToolsCmd = Command.make('tools').pipe(
13 command: 'composio tools info GMAIL_SEND_EMAIL',
14 },
15 ]),
15 - Command.withSubcommands([toolsCmd$List, toolsCmd$Info])
16 + Command.withSubcommands([toolsCmd$List, toolsCmd$Info]),
17 + requireLogin
18 );
ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts
-3
@@ -1,7 +1,6 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 import { Effect, Option, Result } from 'effect';
3 import { parseJsonRecord } from 'src/utils/parse-json';
4 -import { requireAuth } from 'src/effects/require-auth';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -30,8 +29,6 @@ export const triggersCmd$Create = Command.make(
29 { triggerName, connectedAccountId, triggerConfig },
30 ({ triggerName, connectedAccountId, triggerConfig }) =>
31 Effect.gen(function* () {
33 - if (!(yield* requireAuth)) return;
34 -
32 const ui = yield* TerminalUI;
33 const repo = yield* ComposioToolkitsRepository;
34
ts/packages/cli/src/commands/triggers/commands/triggers.disable.cmd.ts
-3
@@ -1,7 +1,6 @@
1 import { commandInputError } from 'src/commands/errors';
2 import { Argument, Command, Flag } from 'effect/cli';
3 import { Effect, Option } from 'effect';
4 -import { requireAuth } from 'src/effects/require-auth';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -40,8 +39,6 @@ export const triggersCmd$Disable = Command.make(
39 '--dangerously-allow'
40 );
41 }
43 - if (!(yield* requireAuth)) return;
44 -
42 const ui = yield* TerminalUI;
43 const repo = yield* ComposioToolkitsRepository;
44
ts/packages/cli/src/commands/triggers/commands/triggers.enable.cmd.ts
-3
@@ -1,6 +1,5 @@
1 import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
3 import { handleClientApiError } from 'src/effects/handle-http-error';
4 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -16,8 +15,6 @@ const id = Argument.String('id').pipe(
15 */
16 export const triggersCmd$Enable = Command.make('enable', { id }, ({ id }) =>
17 Effect.gen(function* () {
19 - if (!(yield* requireAuth)) return;
20 -
18 const ui = yield* TerminalUI;
19 const repo = yield* ComposioToolkitsRepository;
20
ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts
-3
@@ -1,6 +1,5 @@
1 import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
3 import { handleClientApiError } from 'src/effects/handle-http-error';
4 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -33,8 +32,6 @@ const makeTriggersInfoCommand = ({
32 }: TriggersInfoCommandConfig) =>
33 Command.make('info', { slug }, ({ slug }) =>
34 Effect.gen(function* () {
36 - if (!(yield* requireAuth)) return;
37 -
35 const ui = yield* TerminalUI;
36 const repo = yield* ComposioToolkitsRepository;
37
ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts
-3
@@ -1,7 +1,6 @@
1 import { commandInputError } from 'src/commands/errors';
2 import { Argument, Command, Flag } from 'effect/cli';
3 import { Effect } from 'effect';
4 -import { requireAuth } from 'src/effects/require-auth';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { clampLimit } from 'src/ui/clamp-limit';
@@ -35,8 +34,6 @@ const limit = Flag.Int('limit').pipe(
34 const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersListCommandConfig) =>
35 Command.make('list', { toolkit, limit }, ({ toolkit, limit }) =>
36 Effect.gen(function* () {
38 - if (!(yield* requireAuth)) return;
39 -
37 const ui = yield* TerminalUI;
38 const repo = yield* ComposioToolkitsRepository;
39 const clampedLimit = clampLimit(limit);
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+5 -11
@@ -1,9 +1,9 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command, Flag } from 'effect/cli';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
5 import { Deferred, Effect, Option } from 'effect';
6 import { APP_CONFIG } from 'src/config';
6 -import { requireAuth } from 'src/effects/require-auth';
7 import { TerminalUI } from 'src/services/terminal-ui';
8 import { TriggersRealtime } from 'src/services/triggers-realtime';
9 import { matchesTriggerListenFilters } from '../filter';
@@ -15,10 +15,7 @@ import {
15 import { parseCsv } from '../parse-csv';
16 import { parseTriggerListenEvent } from '../parse';
17 import type { TriggerListenFilters } from '../types';
18 -import {
19 - resolveCommandProject,
20 - formatResolveCommandProjectError,
21 -} from 'src/services/command-project';
18 +import { resolveCommandProject } from 'src/services/command-project';
19
20 const toolkits = Flag.String('toolkits').pipe(
21 Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
@@ -170,12 +167,8 @@ export const triggersCmd$Listen = Command.make(
167 out,
168 }) =>
169 Effect.gen(function* () {
173 - if (!(yield* requireAuth)) return;
174 -
170 const ui = yield* TerminalUI;
176 - yield* resolveCommandProject({ mode: 'developer' }).pipe(
177 - Effect.mapError(formatResolveCommandProjectError)
178 - );
171 + yield* resolveCommandProject({ mode: 'developer' });
172 const fs = yield* FileSystem.FileSystem;
173 const path = yield* Path.Path;
174 const realtime = yield* TriggersRealtime;
@@ -353,5 +346,6 @@ export const triggersCmd$Listen = Command.make(
346 ).pipe(
347 Command.withDescription(
348 'Listen to realtime trigger events for your developer project and optionally forward them into your local dev environment.'
356 - )
349 + ),
350 + requireLogin
351 );
ts/packages/cli/src/commands/triggers/commands/triggers.status.cmd.ts
-3
@@ -2,7 +2,6 @@ import { Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { handleClientApiError } from 'src/effects/handle-http-error';
4 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 -import { requireAuth } from 'src/effects/require-auth';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { clampLimit } from 'src/ui/clamp-limit';
@@ -69,8 +68,6 @@ export const triggersCmd$Status = Command.make(
68 },
69 ({ userIds, connectedAccountIds, toolkits, triggerIds, triggerNames, showDisabled, limit }) =>
70 Effect.gen(function* () {
72 - if (!(yield* requireAuth)) return;
73 -
71 const ui = yield* TerminalUI;
72 const repo = yield* ComposioToolkitsRepository;
73
ts/packages/cli/src/commands/triggers/root-triggers.cmd.ts
+3 -1
@@ -1,8 +1,10 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { rootTriggersCmd$Info } from './commands/triggers.info.cmd';
4 import { rootTriggersCmd$List } from './commands/triggers.list.cmd';
5
6 export const rootTriggersCmd = Command.make('triggers').pipe(
7 Command.withDescription('Browse and inspect trigger types before creating subscriptions.'),
7 - Command.withSubcommands([rootTriggersCmd$List, rootTriggersCmd$Info])
8 + Command.withSubcommands([rootTriggersCmd$List, rootTriggersCmd$Info]),
9 + requireLogin
10 );
ts/packages/cli/src/commands/triggers/triggers.cmd.ts
+3 -1
@@ -1,3 +1,4 @@
1 +import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { triggersCmd$Info } from './commands/triggers.info.cmd';
4 import { triggersCmd$List } from './commands/triggers.list.cmd';
@@ -25,5 +26,6 @@ export const triggersCmd = Command.make('triggers').pipe(
26 triggersCmd$Create,
27 triggersCmd$Enable,
28 triggersCmd$Disable,
28 - ])
29 + ]),
30 + requireLogin
31 );
ts/packages/cli/src/effects/require-auth.ts
+16 -19
@@ -1,24 +1,21 @@
1 -import { Effect, Option } from 'effect';
1 +import { Effect } from 'effect';
2 +import { Command } from 'effect/cli';
3 +import { notLoggedIn } from 'src/commands/errors';
4 import { ComposioUserContext } from 'src/services/user-context';
3 -import { TerminalUI } from 'src/services/terminal-ui';
5
5 -/**
6 - * Checks that the user is authenticated. Returns `true` if an API key is present,
7 - * or logs a warning and returns `false` if not.
8 - *
9 - * Usage in commands:
10 - * ```ts
11 - * if (!(yield* requireAuth)) return;
12 - * ```
13 - */
14 -export const requireAuth = Effect.gen(function* () {
6 +/** Fails with `NotLoggedInError` when `~/.composio` holds no API key. */
7 +export const assertLoggedIn = Effect.gen(function* () {
8 const ctx = yield* ComposioUserContext;
16 -
17 - if (Option.isNone(ctx.data.apiKey)) {
18 - const ui = yield* TerminalUI;
19 - yield* ui.log.warn('You are not logged in yet. Please run `composio login`.');
20 - return false as const;
9 + if (!ctx.isLoggedIn()) {
10 + return yield* notLoggedIn();
11 }
22 -
23 - return true as const;
12 });
13 +
14 +/**
15 + * Makes a command, or a group entry and every subcommand under it, require a logged-in user.
16 + * Pipe it after `Command.withSubcommands`, since it wraps the handler that exists when it is
17 + * applied. The handler then never checks `apiKey` or prints a login hint.
18 + */
19 +export const requireLogin = <const Name extends string, Input, ContextInput, E, R>(
20 + self: Command.Command<Name, Input, ContextInput, E, R>
21 +) => Command.provideEffectDiscard(self, assertLoggedIn);
ts/packages/cli/src/services/command-project.ts
+57 -49
@@ -1,4 +1,6 @@
1 -import { Data, Effect, Option, Predicate } from 'effect';
1 +import { isAPIError } from '@composio/client/effect';
2 +import { Data, Effect, Option } from 'effect';
3 +import { extractMessage } from 'src/utils/api-error-extraction';
4 import { ProjectContext } from './project-context';
5 import { ComposioUserContext } from './user-context';
6 import {
@@ -24,27 +26,62 @@ export interface ResolvedCommandProject {
26 readonly source: CliProjectResolutionSource;
27 }
28
27 -export class MissingDefaultOrgError extends Data.TaggedError('services/MissingDefaultOrgError') {}
28 -
29 -export class MissingDeveloperProjectError extends Data.TaggedError(
30 - 'services/MissingDeveloperProjectError'
31 -) {}
32 -
33 -const requireDefaultOrg = (orgId: Option.Option<string>) =>
34 - Option.match(orgId, {
35 - onNone: () => Effect.fail(new MissingDefaultOrgError()),
36 - onSome: value => Effect.succeed(value),
29 +/**
30 + * The command's project could not be determined from the CLI's state and flags. The message
31 + * names the command that fixes it; `cli-main.ts` prints it as one line and exits 1.
32 + */
33 +export class ProjectResolutionError extends Data.TaggedError('services/ProjectResolutionError')<{
34 + readonly reason:
35 + | 'missing_org'
36 + | 'missing_developer_project'
37 + | 'project_not_found'
38 + | 'ambiguous_project_name'
39 + | 'request_failed';
40 + readonly message: string;
41 + readonly cause?: unknown;
42 +}> {}
43 +
44 +const missingOrg = () =>
45 + new ProjectResolutionError({
46 + reason: 'missing_org',
47 + message: 'No current org configured. Run `composio login` or `composio dev orgs switch`.',
48 });
49
50 +/**
51 + * Lookup failures a user can act on become `ProjectResolutionError`; other client errors
52 + * (connection, configuration) keep their type.
53 + */
54 +const normalizeLookupError = <E>(error: E): ProjectResolutionError | E => {
55 + if (error instanceof DeveloperProjectNotFoundError) {
56 + return new ProjectResolutionError({
57 + reason: 'project_not_found',
58 + message: `Developer project "${error.projectName}" was not found in org "${error.orgId}". Run \`composio dev init\` or \`composio dev projects list\`.`,
59 + });
60 + }
61 + if (error instanceof AmbiguousDeveloperProjectNameError) {
62 + return new ProjectResolutionError({
63 + reason: 'ambiguous_project_name',
64 + message: `Developer project name "${error.projectName}" is ambiguous in org "${error.orgId}". Use an exact unique project name.`,
65 + });
66 + }
67 + const apiMessage = isAPIError(error) ? extractMessage(error) : undefined;
68 + return apiMessage === undefined
69 + ? error
70 + : new ProjectResolutionError({ reason: 'request_failed', message: apiMessage, cause: error });
71 +};
72 +
73 export const resolveCommandProject = (params: { mode: ProjectMode; projectName?: string }) =>
74 Effect.gen(function* () {
75 const ctx = yield* ComposioUserContext;
76 const projectContext = yield* ProjectContext;
77 const apiKey = Option.getOrUndefined(ctx.data.apiKey);
44 - const currentOrgId = yield* requireDefaultOrg(ctx.data.orgId);
78 + const currentOrgId = yield* Option.match(ctx.data.orgId, {
79 + onNone: () => Effect.fail(missingOrg()),
80 + onSome: value => Effect.succeed(value),
81 + });
82
83 if (!apiKey) {
47 - return yield* Effect.fail(new MissingDefaultOrgError());
84 + return yield* Effect.fail(missingOrg());
85 }
86
87 if (params.mode === 'consumer') {
@@ -97,7 +134,12 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
134
135 const localProject = yield* projectContext.resolve;
136 if (Option.isNone(localProject)) {
100 - return yield* Effect.fail(new MissingDeveloperProjectError());
137 + return yield* Effect.fail(
138 + new ProjectResolutionError({
139 + reason: 'missing_developer_project',
140 + message: 'No developer project configured for this directory. Run `composio dev init`.',
141 + })
142 + );
143 }
144
145 return {
@@ -107,38 +149,4 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
149 projectType: 'DEVELOPER',
150 source: 'developer-local-config',
151 } satisfies ResolvedCommandProject;
110 - });
111 -
112 -export const formatResolveCommandProjectError = (error: unknown): Error => {
113 - if (error instanceof MissingDefaultOrgError) {
114 - return new Error(
115 - 'No current org configured. Run `composio login` or `composio dev orgs switch`.'
116 - );
117 - }
118 - if (error instanceof MissingDeveloperProjectError) {
119 - return new Error(
120 - 'No developer project configured for this directory. Run `composio dev init`.'
121 - );
122 - }
123 - if (error instanceof DeveloperProjectNotFoundError) {
124 - return new Error(
125 - `Developer project "${error.projectName}" was not found in org "${error.orgId}". Run \`composio dev init\` or \`composio dev projects list\`.`
126 - );
127 - }
128 - if (error instanceof AmbiguousDeveloperProjectNameError) {
129 - return new Error(
130 - `Developer project name "${error.projectName}" is ambiguous in org "${error.orgId}". Use an exact unique project name.`
131 - );
132 - }
133 - if (
134 - Predicate.hasProperty(error, 'details') &&
135 - Predicate.hasProperty(error.details, 'message') &&
136 - Predicate.isString(error.details.message)
137 - ) {
138 - return new Error(error.details.message);
139 - }
140 - if (error instanceof Error) {
141 - return error;
142 - }
143 - return new Error(String(error));
144 -};
152 + }).pipe(Effect.mapError(normalizeLookupError));
ts/packages/cli/test/src/cli-main.test.ts
+54
@@ -61,6 +61,60 @@ describe('CLI process error handling', () => {
61 );
62 });
63
64 + it('reports a missing login as one line and exits non-zero without a defect dump', () => {
65 + const configDirectory = tempy.temporaryDirectory();
66 +
67 + const result = spawnSync('bun', ['run', 'src/bin.ts', 'tools', 'list', 'gmail'], {
68 + cwd: process.cwd(),
69 + encoding: 'utf8',
70 + env: {
71 + ...process.env,
72 + CI: '1',
73 + NO_COLOR: '1',
74 + COMPOSIO_CACHE_DIR: configDirectory,
75 + },
76 + });
77 +
78 + expect(result.status).toBe(1);
79 + expect(result.stdout).toBe('');
80 + expect(result.stderr).toContain('You are not logged in yet. Please run `composio login`.');
81 + expect(result.stderr).not.toContain('NotLoggedInError');
82 + expect(result.stderr).not.toContain('Sources');
83 + });
84 +
85 + it('reports an unresolved project as one line and exits non-zero without a defect dump', () => {
86 + const configDirectory = tempy.temporaryDirectory();
87 + fs.writeFileSync(
88 + path.join(configDirectory, 'user_data.json'),
89 + JSON.stringify({
90 + api_key: 'test-api-key',
91 + base_url: 'https://backend.composio.dev',
92 + web_url: 'https://platform.composio.dev',
93 + org_id: null,
94 + test_user_id: null,
95 + })
96 + );
97 +
98 + const result = spawnSync('bun', ['run', 'src/bin.ts', 'connections', 'list'], {
99 + cwd: process.cwd(),
100 + encoding: 'utf8',
101 + env: {
102 + ...process.env,
103 + CI: '1',
104 + NO_COLOR: '1',
105 + COMPOSIO_CACHE_DIR: configDirectory,
106 + },
107 + });
108 +
109 + expect(result.status).toBe(1);
110 + expect(result.stdout).toBe('');
111 + expect(result.stderr).toContain(
112 + 'No current org configured. Run `composio login` or `composio dev orgs switch`.'
113 + );
114 + expect(result.stderr).not.toContain('ProjectResolutionError');
115 + expect(result.stderr).not.toContain('Sources');
116 + });
117 +
118 it('reports a bare `composio run` as a usage error without a defect dump', () => {
119 const configDirectory = tempy.temporaryDirectory();
120
ts/packages/cli/test/src/commands/auth-configs/auth-configs.create.cmd.test.ts
+4 -5
@@ -126,11 +126,10 @@ describe('CLI: composio dev auth-configs create', () => {
126 it => {
127 it.effect('warns user to login', () =>
128 Effect.gen(function* () {
129 - yield* cli(['dev', 'auth-configs', 'create', '--toolkit', 'gmail']);
130 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
131 - const output = lines.join('\n');
132 -
133 - expect(output).toContain('not logged in');
129 + const error = yield* cli(['dev', 'auth-configs', 'create', '--toolkit', 'gmail']).pipe(
130 + Effect.flip
131 + );
132 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
133 })
134 );
135 }
ts/packages/cli/test/src/commands/auth-configs/auth-configs.info.cmd.test.ts
+4 -5
@@ -83,11 +83,10 @@ describe('CLI: composio dev auth-configs info', () => {
83 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
84 it.effect('warns user to login', () =>
85 Effect.gen(function* () {
86 - yield* cli(['dev', 'auth-configs', 'info', 'ac_gmail_default']);
87 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
88 - const output = lines.join('\n');
89 -
90 - expect(output).toContain('not logged in');
86 + const error = yield* cli(['dev', 'auth-configs', 'info', 'ac_gmail_default']).pipe(
87 + Effect.flip
88 + );
89 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
90 })
91 );
92 });
ts/packages/cli/test/src/commands/auth-configs/auth-configs.list.cmd.test.ts
+2 -5
@@ -125,11 +125,8 @@ describe('CLI: composio dev auth-configs list', () => {
125 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
126 it.effect('warns user to login', () =>
127 Effect.gen(function* () {
128 - yield* cli(['dev', 'auth-configs', 'list']);
129 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
130 - const output = lines.join('\n');
131 -
132 - expect(output).toContain('not logged in');
128 + const error = yield* cli(['dev', 'auth-configs', 'list']).pipe(Effect.flip);
129 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
130 })
131 );
132 });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.info.cmd.test.ts
+4 -5
@@ -86,11 +86,10 @@ describe('CLI: composio dev connected-accounts info', () => {
86 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
87 it.effect('warns user to login', () =>
88 Effect.gen(function* () {
89 - yield* cli(['dev', 'connected-accounts', 'info', 'con_gmail_active']);
90 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
91 - const output = lines.join('\n');
92 -
93 - expect(output).toContain('not logged in');
89 + const error = yield* cli(['dev', 'connected-accounts', 'info', 'con_gmail_active']).pipe(
90 + Effect.flip
91 + );
92 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
93 })
94 );
95 });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+2 -4
@@ -285,10 +285,8 @@ describe('CLI: composio dev connected-accounts link', () => {
285 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
286 it.effect('warns user to login', () =>
287 Effect.gen(function* () {
288 - yield* cli(['link', 'gmail']);
289 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
290 - const output = lines.join('\n');
291 - expect(output).toContain('not logged in');
288 + const error = yield* cli(['link', 'gmail']).pipe(Effect.flip);
289 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
290 })
291 );
292 });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts
+2 -5
@@ -183,11 +183,8 @@ describe('CLI: composio dev connected-accounts list', () => {
183 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
184 it.effect('warns user to login', () =>
185 Effect.gen(function* () {
186 - yield* cli(['dev', 'connected-accounts', 'list']);
187 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
188 - const output = lines.join('\n');
189 -
190 - expect(output).toContain('not logged in');
186 + const error = yield* cli(['dev', 'connected-accounts', 'list']).pipe(Effect.flip);
187 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
188 })
189 );
190 });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.whoami.cmd.test.ts
+4 -5
@@ -120,11 +120,10 @@ describe('CLI: composio dev connected-accounts whoami', () => {
120 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
121 it.effect('warns user to login', () =>
122 Effect.gen(function* () {
123 - yield* cli(['dev', 'connected-accounts', 'whoami', 'con_gmail_active']);
124 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
125 - const output = lines.join('\n');
126 -
127 - expect(output).toContain('not logged in');
123 + const error = yield* cli(['dev', 'connected-accounts', 'whoami', 'con_gmail_active']).pipe(
124 + Effect.flip
125 + );
126 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
127 })
128 );
129 });
ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts
+2 -5
@@ -262,11 +262,8 @@ describe('CLI: composio dev toolkits info', () => {
262 layer(TestLive())('[Given] no API key', it => {
263 it.effect('warns user to login', () =>
264 Effect.gen(function* () {
265 - yield* cli(['dev', 'toolkits', 'info', 'gmail']);
266 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
267 - const output = lines.join('\n');
268 -
269 - expect(output).toContain('not logged in');
265 + const error = yield* cli(['dev', 'toolkits', 'info', 'gmail']).pipe(Effect.flip);
266 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
267 })
268 );
269 });
ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
+2 -5
@@ -161,11 +161,8 @@ describe('CLI: composio dev toolkits list', () => {
161 layer(TestLive())('[Given] no API key', it => {
162 it.effect('warns user to login', () =>
163 Effect.gen(function* () {
164 - yield* cli(['dev', 'toolkits', 'list']);
165 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
166 - const output = lines.join('\n');
167 -
168 - expect(output).toContain('not logged in');
164 + const error = yield* cli(['dev', 'toolkits', 'list']).pipe(Effect.flip);
165 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
166 })
167 );
168 });
ts/packages/cli/test/src/commands/toolkits/toolkits.search.cmd.test.ts
+2 -5
@@ -118,11 +118,8 @@ describe('CLI: composio dev toolkits search', () => {
118 layer(TestLive())('[Given] no API key', it => {
119 it.effect('warns user to login', () =>
120 Effect.gen(function* () {
121 - yield* cli(['dev', 'toolkits', 'search', 'email']);
122 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
123 - const output = lines.join('\n');
124 -
125 - expect(output).toContain('not logged in');
121 + const error = yield* cli(['dev', 'toolkits', 'search', 'email']).pipe(Effect.flip);
122 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
123 })
124 );
125 });
ts/packages/cli/test/src/commands/toolkits/toolkits.version.cmd.test.ts
+2 -5
@@ -118,11 +118,8 @@ describe('CLI: composio dev toolkits version', () => {
118 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
119 it.effect('warns user to login', () =>
120 Effect.gen(function* () {
121 - yield* cli(['dev', 'toolkits', 'version', 'gmail']);
122 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
123 - const output = lines.join('\n');
124 -
125 - expect(output).toContain('not logged in');
121 + const error = yield* cli(['dev', 'toolkits', 'version', 'gmail']).pipe(Effect.flip);
122 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
123 })
124 );
125 });
ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts
+2 -5
@@ -195,11 +195,8 @@ describe('CLI: composio tools info', () => {
195 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
196 it.effect('warns user to login', () =>
197 Effect.gen(function* () {
198 - yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']);
199 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
200 - const output = lines.join('\n');
201 -
202 - expect(output).toContain('not logged in');
198 + const error = yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']).pipe(Effect.flip);
199 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
200 })
201 );
202 });
ts/packages/cli/test/src/commands/tools/tools.list.cmd.test.ts
+2 -5
@@ -125,11 +125,8 @@ describe('CLI: composio tools list', () => {
125 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
126 it.effect('warns user to login', () =>
127 Effect.gen(function* () {
128 - yield* cli(['tools', 'list', 'gmail']);
129 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
130 - const output = lines.join('\n');
131 -
132 - expect(output).toContain('not logged in');
128 + const error = yield* cli(['tools', 'list', 'gmail']).pipe(Effect.flip);
129 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
130 })
131 );
132 });
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+2 -5
@@ -807,11 +807,8 @@ describe('CLI: composio search', () => {
807 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
808 it.effect('warns user to login', () =>
809 Effect.gen(function* () {
810 - yield* cli(['search', 'send', '--human']);
811 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
812 - const output = lines.join('\n');
813 -
814 - expect(output).toContain('not logged in');
810 + const error = yield* cli(['search', 'send', '--human']).pipe(Effect.flip);
811 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
812 })
813 );
814 });
ts/packages/cli/test/src/commands/triggers/triggers.info.cmd.test.ts
+4 -5
@@ -140,11 +140,10 @@ describe('CLI: composio dev triggers info', () => {
140 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
141 it.effect('warns user to login', () =>
142 Effect.gen(function* () {
143 - yield* cli(['dev', 'triggers', 'info', 'GMAIL_NEW_GMAIL_MESSAGE']);
144 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
145 - const output = lines.join('\n');
146 -
147 - expect(output).toContain('not logged in');
143 + const error = yield* cli(['dev', 'triggers', 'info', 'GMAIL_NEW_GMAIL_MESSAGE']).pipe(
144 + Effect.flip
145 + );
146 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
147 })
148 );
149 });
ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts
+2 -5
@@ -176,11 +176,8 @@ describe('CLI: composio dev triggers list', () => {
176 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
177 it.effect('warns user to login', () =>
178 Effect.gen(function* () {
179 - yield* cli(['dev', 'triggers', 'list', 'gmail']);
180 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
181 - const output = lines.join('\n');
182 -
183 - expect(output).toContain('not logged in');
179 + const error = yield* cli(['dev', 'triggers', 'list', 'gmail']).pipe(Effect.flip);
180 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
181 })
182 );
183 });
ts/packages/cli/test/src/commands/triggers/triggers.status.cmd.test.ts
+2 -5
@@ -144,11 +144,8 @@ describe('CLI: composio dev triggers status', () => {
144 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
145 it.effect('warns user to login', () =>
146 Effect.gen(function* () {
147 - yield* cli(['dev', 'triggers', 'status']);
148 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
149 - const output = lines.join('\n');
150 -
151 - expect(output).toContain('not logged in');
147 + const error = yield* cli(['dev', 'triggers', 'status']).pipe(Effect.flip);
148 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
149 })
150 );
151 });
ts/packages/cli/test/src/services/command-project.test.ts new
+185
@@ -0,0 +1,185 @@
1 +import { afterEach, describe, expect, it } from '@effect/vitest';
2 +import { vi } from 'vitest';
3 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 +import * as BunPath from '@effect/platform-bun/BunPath';
5 +import { APIConnectionError } from '@composio/client/effect';
6 +import { ConfigProvider, Effect, Fiber, Layer, Option } from 'effect';
7 +import { TestClock } from 'effect/testing';
8 +import * as tempy from 'tempy';
9 +import { ProjectResolutionError, resolveCommandProject } from 'src/services/command-project';
10 +import { ComposioClientSingleton } from 'src/services/composio-clients';
11 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
12 +import { ProjectContext } from 'src/services/project-context';
13 +import { ComposioUserContext } from 'src/services/user-context';
14 +import { makeOrgProject } from 'test/__utils__/models/account';
15 +
16 +const BASE_URL = 'https://backend.composio.dev';
17 +
18 +const userContext = (orgId: Option.Option<string>) =>
19 + Layer.succeed(
20 + ComposioUserContext,
21 + ComposioUserContext.of({
22 + data: {
23 + apiKey: Option.some('uak_test'),
24 + baseURL: BASE_URL,
25 + webURL: 'https://app.composio.dev',
26 + orgId,
27 + projectId: Option.none(),
28 + testUserId: Option.none(),
29 + },
30 + isLoggedIn: () => true,
31 + logout: Effect.void,
32 + login: () => Effect.void,
33 + update: () => Effect.void,
34 + })
35 + );
36 +
37 +const noLocalProject = Layer.succeed(
38 + ProjectContext,
39 + ProjectContext.of({ resolve: Effect.succeed(Option.none()) })
40 +);
41 +
42 +const singleton = Layer.provide(
43 + ComposioClientSingleton.Default,
44 + Layer.mergeAll(
45 + BunFileSystem.layer,
46 + BunPath.layer,
47 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempy.temporaryDirectory() })),
48 + Layer.succeed(
49 + ConfigProvider.ConfigProvider,
50 + ConfigProvider.fromEnv({
51 + env: { COMPOSIO_USER_API_KEY: 'uak_test', COMPOSIO_BASE_URL: BASE_URL },
52 + })
53 + )
54 + )
55 +);
56 +
57 +const testLayer = Layer.mergeAll(singleton, userContext(Option.some('org_1')), noLocalProject);
58 +
59 +const jsonResponse = (body: unknown, status = 200) =>
60 + new Response(JSON.stringify(body), {
61 + status,
62 + headers: { 'Content-Type': 'application/json', 'x-should-retry': 'false' },
63 + });
64 +
65 +const projectsPage = (names: ReadonlyArray<string>) =>
66 + jsonResponse({
67 + data: names.map((name, index) => makeOrgProject({ id: `p${index + 1}`, name })),
68 + total_pages: 1,
69 + current_page: 1,
70 + total_items: names.length,
71 + });
72 +
73 +describe('resolveCommandProject', () => {
74 + afterEach(() => {
75 + vi.restoreAllMocks();
76 + });
77 +
78 + it.effect('fails with missing_org before any request when no org is configured', () =>
79 + Effect.gen(function* () {
80 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
81 +
82 + const error = yield* resolveCommandProject({ mode: 'consumer' }).pipe(Effect.flip);
83 +
84 + expect(error).toBeInstanceOf(ProjectResolutionError);
85 + expect(error).toMatchObject({
86 + reason: 'missing_org',
87 + message: 'No current org configured. Run `composio login` or `composio dev orgs switch`.',
88 + });
89 + expect(fetchSpy).not.toHaveBeenCalled();
90 + }).pipe(Effect.provide(Layer.mergeAll(singleton, userContext(Option.none()), noLocalProject)))
91 + );
92 +
93 + it.effect('fails with missing_developer_project when nothing binds the directory', () =>
94 + Effect.gen(function* () {
95 + const error = yield* resolveCommandProject({ mode: 'developer' }).pipe(Effect.flip);
96 +
97 + expect(error).toMatchObject({
98 + _tag: 'services/ProjectResolutionError',
99 + reason: 'missing_developer_project',
100 + message: 'No developer project configured for this directory. Run `composio dev init`.',
101 + });
102 + }).pipe(Effect.provide(testLayer))
103 + );
104 +
105 + it.effect('turns an unknown project name into project_not_found with the remedy', () =>
106 + Effect.gen(function* () {
107 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(projectsPage(['Other']));
108 +
109 + const error = yield* resolveCommandProject({
110 + mode: 'developer',
111 + projectName: 'Missing',
112 + }).pipe(Effect.flip);
113 +
114 + expect(error).toMatchObject({
115 + _tag: 'services/ProjectResolutionError',
116 + reason: 'project_not_found',
117 + message:
118 + 'Developer project "Missing" was not found in org "org_1". Run `composio dev init` or `composio dev projects list`.',
119 + });
120 + }).pipe(Effect.provide(testLayer))
121 + );
122 +
123 + it.effect('turns a name collision into ambiguous_project_name', () =>
124 + Effect.gen(function* () {
125 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(projectsPage(['Shared', 'shared']));
126 +
127 + const error = yield* resolveCommandProject({
128 + mode: 'consumer',
129 + projectName: 'SHARED',
130 + }).pipe(Effect.flip);
131 +
132 + expect(error).toMatchObject({
133 + _tag: 'services/ProjectResolutionError',
134 + reason: 'ambiguous_project_name',
135 + message:
136 + 'Developer project name "SHARED" is ambiguous in org "org_1". Use an exact unique project name.',
137 + });
138 + }).pipe(Effect.provide(testLayer))
139 + );
140 +
141 + it.effect('turns an API error into request_failed carrying the server message', () =>
142 + Effect.gen(function* () {
143 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
144 + jsonResponse(
145 + { error: { slug: 'Forbidden', status: 403, code: 403, message: 'Org access revoked.' } },
146 + 403
147 + )
148 + );
149 +
150 + const error = yield* resolveCommandProject({
151 + mode: 'developer',
152 + projectName: 'Any',
153 + }).pipe(Effect.flip);
154 +
155 + expect(error).toBeInstanceOf(ProjectResolutionError);
156 + expect(error).toMatchObject({ reason: 'request_failed', message: 'Org access revoked.' });
157 + expect((error as ProjectResolutionError).cause).toMatchObject({ status: 403 });
158 + }).pipe(Effect.provide(testLayer))
159 + );
160 +
161 + it.effect('passes a connection failure through with its own type', () =>
162 + Effect.gen(function* () {
163 + vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('fetch failed'));
164 +
165 + // The client retries a connection failure with a backoff on Effect's clock, so run the
166 + // lookup on its own fiber and move the test clock past every retry before joining. The
167 + // first backoff is armed only after client construction and a rejected fetch promise, so
168 + // advance in bounded steps until the fiber has settled rather than assuming one yield
169 + // reaches it.
170 + const fiber = yield* resolveCommandProject({ mode: 'developer', projectName: 'Any' }).pipe(
171 + Effect.flip,
172 + Effect.forkChild
173 + );
174 + for (let step = 0; step < 100 && fiber.pollUnsafe() === undefined; step++) {
175 + yield* Effect.yieldNow;
176 + yield* TestClock.adjust('1 minute');
177 + }
178 + expect(fiber.pollUnsafe()).toBeDefined();
179 + const error = yield* Fiber.join(fiber);
180 +
181 + expect(error).not.toBeInstanceOf(ProjectResolutionError);
182 + expect(error).toBeInstanceOf(APIConnectionError);
183 + }).pipe(Effect.provide(testLayer))
184 + );
185 +});