@devries-cameron20 / composio-1 / commits / c2edefdfb
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.

fix(cli): act on an explicit developer project in dev commands (#5362)

This PR: - part of [PRDE-2212](https://linear.app/composio/issue/PRDE-2212/cli-e2e-tests-fake-backend-operation-suites-and-agent-journeys-with) - builds on top of https://github.com/ComposioHQ/composio/pull/5361; split from https://github.com/ComposioHQ/composio/pull/5334 - scopes developer auth-config, connected-account, trigger-instance, and log requests to the resolved project and accepts --project-name - preserves scripts without a directory project by resolving the default developer project once and naming that fallback on stderr, including off a terminal - preserves project lookup failures and removes the unreachable directory-project branch from the default client - replaces the unscoped auth-config pin and expected failure with one passing directory-project operation test and updates the agent-journeys README without changing its harness - passes the full CLI suite, CLI and workspace typechecks, Effect diagnostics, Oxlint, Prettier, and keyless Docker operations, whoami, and agent-signin suites The CLI test workflow runs for PRs targeting `next`, not this stack base; full CI completes after retargeting. The existing Docker scenarios cover these corrections; no recording changes are needed. ## Context Unscoped user-key requests act on the newest developer project in the selected org, or the user’s newest org when no org is selected. `GET /api/v3.1/auth/session/info` reports that project; `x-project-id` must use its `nano_id`. Scoping and default-project fallback land together so existing scripts keep working.

Alberto Schiabel committed Nov 16, 2026 at 13:19 UTC c2edefdfb2fc8761def3d2f957d4594a4fb4b671
52 files changed +1741 -318
.agents/skills/cli-command/references/implementation.md
+1 -1
@@ -6,7 +6,7 @@ The [contributor guide](../../../../ts/packages/cli/CONTRIBUTING.md) traces one
6
7 - Groups register children through `withRegisteredSubcommands`, which supplies parsed identity and inherited policy. Direct `Command.withSubcommands` bypasses it.
8 - `withCommandMeta` declares login, hooks, telemetry family, and unsupported shared flags. Handlers do not repeat login gates or lifecycle reporting.
9 -- `CommandSurface` supplies root/dev context and dev shared flags. `actingUser()` or `actingUserOption()` resolves the acting user and project. A user filter does not use a test-user fallback.
9 +- `CommandSurface` supplies root/dev context and dev shared flags. `actingUser()` resolves the acting user and project; `actingUserOption()` or `devActingUserOption(project)` finds an optional one for a developer project the command resolved. A user filter does not use a test-user fallback.
10 - The same command definition can have multiple registrations. Root shortcuts do not need copied handlers or descriptions.
11 - Changes to command paths or help summaries regenerate `COMMANDS.md` with `pnpm --filter @composio/cli run commands:map`.
12
ts/e2e-tests/cli/agent-journeys/README.md
+1 -1
@@ -76,7 +76,7 @@ A journey has two lists, and they answer different questions.
76 - No account became connected on a project the task does not involve. A person who approved `composio link slack` during a developer task gave access nobody asked for, and it stays.
77 - `run-inline-script`: the send happened during a shell command that is one `composio run`, which exited 0 and printed the timestamp, not during a `composio execute` followed by a script that prints what it was told. Requests are attributed per shell command and the command is recognised by its text, so this holds for the ways a shell line names `composio`; an alias or a wrapper script would get past it.
78 - `first-run-login`: a new `composio whoami` after the model stopped exits 0 as the person, in their org. The requests of the process that logged in do not show that anything was stored.
79 -- `developer-auth-configs-and-execute`: the auth configs were listed on the developer project. The CLI sends `dev auth-configs list` without a project scope today, and the fake answers an unscoped request with the developer project, so this check cannot tell which directory the agent ran it in. `operations/identity.test.ts` holds that defect as an expected failure; once it is fixed, the check should also require the scope headers.
79 +- `developer-auth-configs-and-execute`: the auth configs were listed on the developer project. The CLI now sends the resolved directory project in its scope headers, verified by `operations/identity.test.ts`. This journey check still accepts an unscoped request that the fake answers with the developer project; requiring scope headers here remains a follow-up to the eval harness.
80
81 **Detours** are what a confused agent does on the way: a `composio dev` command during a consumer task, a root `composio execute` or `composio link` during a developer task, a request to the other project that changed nothing. A detour never fails a run. A run that tried the wrong tree, read the error, and finished on the right one reached the goal, and its detours say how it got there. Reading the two lists separately gives a success rate and a wrong-tree rate; `composio dev --help` during a consumer task counts toward the second and not against the first.
82
ts/e2e-tests/cli/operations/README.md
+1 -1
@@ -30,7 +30,7 @@ The catalogue starts from one question: what can go wrong for a CLI that an agen
30 | Account linked on one tree, used on the other | world | Not connected on the other tree, both directions | ok |
31 | Root `execute` without a connection | world | exit 1; the error names `composio link <toolkit>` | ok |
32 | Dev `playground-execute` without a connection | world | exit 1; the error names `composio dev connected-accounts link <toolkit>`, not the root-tree `composio link` | ok |
33 -| `dev auth-configs list` in a directory set up for another project | `.composio/project.json` | The request is scoped to that project | expected failure: the request carries no org or project scope |
33 +| `dev auth-configs list` in a directory set up for another project | `.composio/project.json` | The request is scoped to that project | ok |
34 | Command from the other tree (`dev execute`, `dev link`, root `playground-execute`, root `auth-configs`, root `--user-id`) | argv | exit 1; stdout empty; stderr names the unknown subcommand or flag and lists the real commands; no request | ok |
35 | `composio dev link` | argv | stderr names `composio dev connected-accounts link` | known gap: the `dev` help lists `connected-accounts`, but no equivalent command is named |
36 | `composio dev link --help` | argv | exit 1 | known gap: prints the `dev` help and exits 0 |
ts/e2e-tests/cli/operations/identity.test.ts
+3 -13
@@ -234,27 +234,17 @@ describe('identity: the two command trees', () => {
234 };
235
236 it(
237 - "today: `dev auth-configs list` in another project's directory sends no scope and gets the key's default project",
237 + '`dev auth-configs list` is scoped to the project the directory is set up for',
238 async () => {
239 const { result, listing } = await listInOtherDirectory();
240 expect(result.exitCode).toBe(0);
241 expect(listing).toMatchObject({
242 - project: DEVELOPER_PROJECT.label,
243 - projectFrom: 'key-default',
242 + project: OTHER_DEVELOPER_PROJECT.label,
243 + projectFrom: 'scope-headers',
244 });
245 },
246 TEST_TIMEOUT_MS
247 );
248 -
249 - // CLI defect: commands on the shared backend client send the user key with no org or project scope, so the backend picks the project.
250 - it.failing(
251 - '`dev auth-configs list` is scoped to the project the directory is set up for',
252 - async () => {
253 - const { listing } = await listInOtherDirectory();
254 - expect(listing?.projectFrom).toBe('scope-headers');
255 - },
256 - TEST_TIMEOUT_MS
257 - );
248 });
249
250 describe('a command from the wrong tree', () => {
ts/packages/cli/AGENTS.md
+3 -3
@@ -64,12 +64,12 @@ Rules:
64
65 - `<group>.<name>.cmd.ts` declares the surface and nothing else: flag and argument constants, `Command.withDescription`, `Command.withExamples`, and the three-argument `Command.make(name, flags, handler)` with the handler imported from the sibling `.handler.ts`. It yields no service and contains no branching. `Command.withHandler` is reserved for `src/commands/index.ts`, where the root handler is attached at assembly time.
66 - `<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`).
67 -- 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. `--user-id` and `--project-name` are shared flags of the `dev` group (`dev.cmd.ts`), accepted before or after the subcommand name and documented once on every `dev` page; a handler reads them, and the tree it runs in, from `CommandSurface` (`surface.ts`) and never declares either flag itself, since `withSharedFlags` rejects a duplicate on a direct subcommand. A `dev` command that cannot honor one of them yet (it cannot target another project, or it does not act for a user) declares it in its `CommandMeta`: `withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })` for both, `{ sharedFlags: { projectName: false } }` for one, piped where its group registers it, or on a group entry for every subcommand under it. The selected command rejects such a flag right after it began, with a `CommandInputError` naming the command that ran (`dev logs tools`, not the `dev logs` group that declared it), which telemetry records too; never type a command path for the message. The `dev` group's own `--mode` toggle calls `rejectSharedFlags` (`surface.ts`) with its own wording. `execute` and `playground-execute` keep two registrations because their names differ; they share one handler.
67 +- 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. `--user-id` and `--project-name` are shared flags of the `dev` group (`dev.cmd.ts`), accepted before or after the subcommand name and documented once on every `dev` page; a handler reads them, and the tree it runs in, from `CommandSurface` (`surface.ts`) and never declares either flag itself, since `withSharedFlags` rejects a duplicate on a direct subcommand. A `dev` command that cannot honor one of them yet (it cannot target another project, or it does not act for a user) declares it in its `CommandMeta`: `withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })` for both, `{ sharedFlags: { userId: false } }` for one, piped where its group registers it, or on a group entry for every subcommand under it. The selected command rejects such a flag right after it began, with a `CommandInputError` naming the command that ran (`dev projects list`, not the `dev projects` group that declared it), which telemetry records too; never type a command path for the message. The `dev` group's own `--mode` toggle calls `rejectSharedFlags` (`surface.ts`) with its own wording. `execute` and `playground-execute` keep two registrations because their names differ; they share one handler.
68 - A hint, example, or message that names a command (`composio …`) names a real registration on the tree it names: `orgs` is a root command, so `composio dev orgs switch` is wrong. `test/src/commands/command-references.test.ts` finds every `composio <words>` in a string or template literal under `src/` and fails when the words stop at a group or before any command; prose that only reads like a command goes in its `NOT_COMMANDS` list.
69 -- A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`, an expected failure whose message fits the tree) or `actingUserOption` (for a command that also runs without one) in `surface.ts`; both name a fallback test user on stderr. A handler never reads `--user-id` or a test user id to resolve one itself, never prints that notice, and lets `MissingActingUserError` through instead of wrapping it in its own error (its tag is the `error_name` telemetry reports). An empty consumer user id counts as none. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
69 +- A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`, an expected failure whose message fits the tree) or `actingUserOption` / `devActingUserOption` (for commands that also run without one; the latter takes the developer project already resolved) in `surface.ts`; both name a fallback test user on stderr. A handler never reads `--user-id` or a test user id to resolve one itself, never prints that notice, and lets `MissingActingUserError` through instead of wrapping it in its own error (its tag is the `error_name` telemetry reports). An empty consumer user id counts as none. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
70 - Logic shared across groups belongs in `src/effects/` or `src/services/`, never in another command's directory.
71 - A group registers its subcommands with `withRegisteredSubcommands` (`src/commands/registration.ts`), never `Command.withSubcommands`, so each subcommand gets its command identity.
72 -- A command that needs a logged-in user pipes `withCommandMeta({ requiresLogin: true })` on itself or on its group entry, and the selected command checks it right after it began (`assertLoggedIn` in `src/effects/require-auth.ts`). 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`.
72 +- A command that needs a logged-in user pipes `withCommandMeta({ requiresLogin: true })` on itself or on its group entry, and the selected command checks it right after it began (`assertLoggedIn` in `src/effects/require-auth.ts`). 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`. A `dev` command that reads or writes a project's resources (auth configs, connected accounts, trigger instances, logs) resolves its developer project with `resolveDeveloperResourceProject` (`surface.ts`: `--project-name`'s, else the directory's, else the backend's default developer project, read once from session info and named on stderr even off a terminal, since these commands once let the backend pick it) and sends those requests on `ComposioClientSingleton.getFor` with it (`developerProjectClient`), or passes it to the repository method that takes it: `get()` carries no org or project, so the backend would pick the project per request. A command that always required a developer project (`dev playground-execute`, `dev triggers listen`, `dev connected-accounts list` and `link`) uses `resolveSurfaceProject('developer')` or `actingUser`, which fail with `ProjectResolutionError` instead.
73 - 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.
74
75 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.
ts/packages/cli/CHANGELOG.md
+2
@@ -4,6 +4,8 @@
4
5 ### Patch Changes
6
7 +- `composio dev` resource commands now act on the directory's developer project or `--project-name`, rather than leaving the backend to choose. Without a directory project they keep working by resolving the default developer project once from session info and naming it on stderr, including in scripts. Project lookup failures preserve their cause and recovery advice.
8 +
9 - A command whose stdout reader stops reading early, as in
10 `composio search "send a slack message" | head -1`, now drops the rest of
11 its output and exits as it would have. It printed an `EPIPE: broken pipe`
ts/packages/cli/GLOSSARY.md
+1 -1
@@ -30,7 +30,7 @@ _Avoid_: alias (reserved for a flag's or command's short name)
30 The project that holds a Composio user's own connections and executions, resolved from their login.
31
32 **Developer project**:
33 -A project a developer builds against, chosen by the working directory or `--project-name`.
33 +A project a developer builds against, chosen by the working directory or `--project-name`. A dev command that reads or writes a project's resources falls back, with a notice on stderr, to the backend's default developer project (the newest one in the logged-in org) when neither names a usable one.
34
35 **Consumer user**:
36 The user id of the logged-in person within their consumer project; no flag overrides it.
ts/packages/cli/src/commands/auth-configs/create/auth-configs.create.handler.ts
+7 -4
@@ -1,6 +1,7 @@
1 import type { AuthConfigCreateParams as AuthConfigCreateRequest } from '@composio/client/resources/auth-configs';
2 import { Effect, Option, Result } from 'effect';
3 import { commandInputError } from 'src/commands/errors';
4 +import { resolveDeveloperResourceProject } from 'src/commands/surface';
5 import { handleClientApiError } from 'src/effects/handle-http-error';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -80,9 +81,10 @@ export const buildAuthConfigCreateRequest = (input: {
81 const invalidInput = commandInputError('dev auth-configs create');
82
83 /**
83 - * Create an auth config: the summary on stderr, the API response as JSON on stdout. Invalid
84 - * `--custom-credentials` JSON fails with a `CommandInputError` before any request; an API
85 - * failure is reported with a hint and exits 1.
84 + * Create an auth config in the developer project: the summary on stderr, the API response as JSON
85 + * on stdout. Invalid `--custom-credentials` JSON fails with a `CommandInputError` before any
86 + * request, and a developer project that cannot be found with `ProjectResolutionError`; an API failure is
87 + * reported with a hint and exits 1.
88 */
89 export const runAuthConfigsCreate = ({
90 name,
@@ -110,9 +112,10 @@ export const runAuthConfigsCreate = ({
112 scopes: parseScopes(scopes),
113 customCredentials: parsedCustomCredentials.success,
114 });
115 + const project = yield* resolveDeveloperResourceProject;
116
117 const result = yield* ui
115 - .withSpinner('Creating auth config...', repo.createAuthConfig(request))
118 + .withSpinner('Creating auth config...', repo.createAuthConfig(project, request))
119 .pipe(
120 Effect.catchTag(
121 CLIENT_API_ERROR_TAGS,
ts/packages/cli/src/commands/auth-configs/info/auth-configs.info.handler.ts
+5 -3
@@ -1,5 +1,6 @@
1 import { Effect, Option } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 +import { resolveDeveloperResourceProject } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -13,8 +14,8 @@ export type AuthConfigsInfoParams = {
14 const invalidInput = commandInputError('dev auth-configs info');
15
16 /**
16 - * Show one auth config: the details on stderr, the JSON on stdout. A missing `<id>` fails with a
17 - * `CommandInputError` before any request; an API failure is reported with a hint and exits 1.
17 + * Show one auth config of the developer project: the details on stderr, the JSON on stdout. A
18 + * missing `<id>` fails with a `CommandInputError` before any request, and a developer project that cannot be found with `ProjectResolutionError`; an API failure is reported with a hint and exits 1.
19 */
20 export const runAuthConfigsInfo = ({ id }: AuthConfigsInfoParams) =>
21 Effect.gen(function* () {
@@ -29,10 +30,11 @@ export const runAuthConfigsInfo = ({ id }: AuthConfigsInfoParams) =>
30 }
31
32 const idValue = id.value;
33 + const project = yield* resolveDeveloperResourceProject;
34
35 // Auth config IDs are opaque nanoids — "Did you mean?" suggestions would not be useful
36 const item = yield* ui
35 - .withSpinner(`Fetching auth config "${idValue}"...`, repo.getAuthConfig(idValue))
37 + .withSpinner(`Fetching auth config "${idValue}"...`, repo.getAuthConfig(project, idValue))
38 .pipe(
39 Effect.catchTag(
40 CLIENT_API_ERROR_TAGS,
ts/packages/cli/src/commands/auth-configs/list/auth-configs.list.handler.ts
+6 -2
@@ -1,4 +1,5 @@
1 import { Array as Arr, Effect, Option, String } from 'effect';
2 +import { resolveDeveloperResourceProject } from 'src/commands/surface';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { clampLimit } from 'src/ui/clamp-limit';
@@ -12,16 +13,19 @@ export type AuthConfigsListParams = {
13 };
14
15 /**
15 - * List auth configs, filtered by toolkit and name: the table on stderr, the JSON on stdout.
16 + * List the developer project's auth configs, filtered by toolkit and name: the table on stderr,
17 + * the JSON on stdout. Fails with `ProjectResolutionError` when no developer project can be found
18 + * (`resolveDeveloperResourceProject`).
19 */
20 export const runAuthConfigsList = ({ toolkits, query, limit }: AuthConfigsListParams) =>
21 Effect.gen(function* () {
22 const ui = yield* TerminalUI;
23 const repo = yield* ComposioToolkitsRepository;
24 + const project = yield* resolveDeveloperResourceProject;
25
26 const result = yield* ui.withSpinner(
27 'Fetching auth configs...',
24 - repo.listAuthConfigs({
28 + repo.listAuthConfigs(project, {
29 search: Option.getOrUndefined(query),
30 toolkit_slug: Option.getOrUndefined(toolkits),
31 limit: clampLimit(limit),
ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts
+2 -3
@@ -1,6 +1,5 @@
1 import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 -import { NO_SHARED_FLAGS } from 'src/commands/surface';
3 import { connectedAccountsCmd$List } from './list/connected-accounts.list.cmd';
4 import { connectedAccountsCmd$Info } from './info/connected-accounts.info.cmd';
5 import { connectedAccountsCmd$Whoami } from './whoami/connected-accounts.whoami.cmd';
@@ -20,8 +19,8 @@ export const connectedAccountsCmd = Command.make('connected-accounts').pipe(
19 withRegisteredSubcommands([
20 connectedAccountsCmd$Link,
21 connectedAccountsCmd$List,
23 - connectedAccountsCmd$Info.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
24 - connectedAccountsCmd$Whoami.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
22 + connectedAccountsCmd$Info.pipe(withCommandMeta({ sharedFlags: { userId: false } })),
23 + connectedAccountsCmd$Whoami.pipe(withCommandMeta({ sharedFlags: { userId: false } })),
24 ]),
25 withCommandMeta({ requiresLogin: true })
26 );
ts/packages/cli/src/commands/connected-accounts/info/connected-accounts.info.handler.ts
+6 -3
@@ -1,5 +1,6 @@
1 import { Effect, Option } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 +import { resolveDeveloperResourceProject } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -27,9 +28,10 @@ const showConnectedAccount = (id: string) =>
28 Effect.gen(function* () {
29 const ui = yield* TerminalUI;
30 const repo = yield* ComposioToolkitsRepository;
31 + const project = yield* resolveDeveloperResourceProject;
32
33 const account = yield* ui
32 - .withSpinner(fetchingConnectedAccountMessage(id), repo.getConnectedAccount(id))
34 + .withSpinner(fetchingConnectedAccountMessage(id), repo.getConnectedAccount(project, id))
35 .pipe(
36 Effect.catchTag(
37 CLIENT_API_ERROR_TAGS,
@@ -45,8 +47,9 @@ const showConnectedAccount = (id: string) =>
47 });
48
49 /**
48 - * Shows one connected account. A missing `<id>` fails with a `CommandInputError` before any
49 - * request; an API failure is reported with a hint and exits 1.
50 + * Shows one connected account of the developer project. A missing `<id>` fails with a
51 + * `CommandInputError` before any request, and a developer project that cannot be found with
52 + * `ProjectResolutionError`; an API failure is reported with a hint and exits 1.
53 */
54 export const runConnectedAccountsInfo = ({ id }: ConnectedAccountsInfoParams) =>
55 Effect.gen(function* () {
ts/packages/cli/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.ts
+7 -4
@@ -1,5 +1,6 @@
1 import { Effect, Option } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 +import { resolveDeveloperResourceProject } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -28,9 +29,10 @@ const showConnectedAccountProfile = (id: string) =>
29 Effect.gen(function* () {
30 const ui = yield* TerminalUI;
31 const repo = yield* ComposioToolkitsRepository;
32 + const project = yield* resolveDeveloperResourceProject;
33
34 const account = yield* ui
33 - .withSpinner(fetchingConnectedAccountMessage(id), repo.getConnectedAccount(id))
35 + .withSpinner(fetchingConnectedAccountMessage(id), repo.getConnectedAccount(project, id))
36 .pipe(
37 Effect.catchTag(
38 CLIENT_API_ERROR_TAGS,
@@ -49,9 +51,10 @@ const showConnectedAccountProfile = (id: string) =>
51 });
52
53 /**
52 - * Shows who a connected account is connected as (toolkit, user, status), warning when the
53 - * connection is not ACTIVE. A missing `<id>` fails with a `CommandInputError` before any request;
54 - * an API failure is reported with a hint and exits 1.
54 + * Shows who a connected account of the developer project is connected as (toolkit, user,
55 + * status), warning when the connection is not ACTIVE. A missing `<id>` fails with a
56 + * `CommandInputError` before any request, and a developer project that cannot be found with
57 + * `ProjectResolutionError`; an API failure is reported with a hint and exits 1.
58 */
59 export const runConnectedAccountsWhoami = ({ id }: ConnectedAccountsWhoamiParams) =>
60 Effect.gen(function* () {
ts/packages/cli/src/commands/dev.cmd.ts
+2 -2
@@ -44,9 +44,9 @@ export const devSubcommands = [
44 initCmd.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
45 devToolsCmd$Execute,
46 triggersCmd$Listen.pipe(withCommandMeta({ requiresLogin: true })),
47 - logsCmd.pipe(withCommandMeta({ sharedFlags: { projectName: false } })),
47 + logsCmd,
48 toolkitsCmd,
49 - authConfigsCmd.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
49 + authConfigsCmd.pipe(withCommandMeta({ sharedFlags: { userId: false } })),
50 connectedAccountsCmd,
51 triggersCmd,
52 projectsCmd.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
ts/packages/cli/src/commands/logs/tools/logs.tools.handler.ts
+3 -4
@@ -1,11 +1,10 @@
1 import type { LogCreateToolExecutionParams } from '@composio/client/resources/logs';
2 import { Array as Arr, Clock, Effect, Option, String as Str } from 'effect';
3 import { commandInputError } from 'src/commands/errors';
4 -import { CommandSurface } from 'src/commands/surface';
4 +import { CommandSurface, developerProjectClient } from 'src/commands/surface';
5 import { parseCsv } from 'src/commands/triggers/parse-csv';
6 import { failedWith } from 'src/effects/request-error';
7 import { commandHintStep } from 'src/services/command-hints';
8 -import { ComposioClientSingleton } from 'src/services/composio-clients';
8 import { idempotent } from 'src/services/composio-request';
9 import { TerminalUI } from 'src/services/terminal-ui';
10 import { nonEmptyOrUndefined, optionalParams } from 'src/utils/optional-params';
@@ -78,7 +77,7 @@ const buildToolLogFilters = (
77 const showToolLog = (toolLogId: string) =>
78 Effect.gen(function* () {
79 const ui = yield* TerminalUI;
81 - const client = yield* (yield* ComposioClientSingleton).get();
80 + const client = yield* developerProjectClient;
81 const toolLog = yield* ui.withSpinner(
82 `Fetching tool log "${toolLogId}"...`,
83 client.logs
@@ -152,7 +151,7 @@ const listToolLogs = ({
151 : undefined;
152 const filters = buildToolLogFilters(filterInput);
153
155 - const client = yield* (yield* ComposioClientSingleton).get();
154 + const client = yield* developerProjectClient;
155 // The client names this read-only search POST createToolExecution.
156 const response = yield* ui.withSpinner(
157 'Fetching tool logs...',
ts/packages/cli/src/commands/logs/triggers/logs.triggers.handler.ts
+3 -4
@@ -1,10 +1,9 @@
1 import type { TriggerListParams } from '@composio/client/resources/_internal/logs';
2 import { Array as Arr, Effect, Option, String as Str } from 'effect';
3 -import { CommandSurface } from 'src/commands/surface';
3 +import { CommandSurface, developerProjectClient } from 'src/commands/surface';
4 import { parseCsv } from 'src/commands/triggers/parse-csv';
5 import { failedWith } from 'src/effects/request-error';
6 import { commandHintStep } from 'src/services/command-hints';
7 -import { ComposioClientSingleton } from 'src/services/composio-clients';
7 import { idempotent } from 'src/services/composio-request';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 import { clampLimit } from 'src/ui/clamp-limit';
@@ -48,7 +47,7 @@ export const triggerLogSearchParams = (
47 const showTriggerLog = (triggerLogId: string) =>
48 Effect.gen(function* () {
49 const ui = yield* TerminalUI;
51 - const client = yield* (yield* ComposioClientSingleton).get();
50 + const client = yield* developerProjectClient;
51 const triggerLog = yield* ui.withSpinner(
52 `Fetching trigger log "${triggerLogId}"...`,
53 client._internal.logs.triggers
@@ -81,7 +80,7 @@ const listTriggerLogs = ({
80 Effect.gen(function* () {
81 const userIdFilter = Option.orElse((yield* CommandSurface).userId, () => userId);
82 const ui = yield* TerminalUI;
84 - const client = yield* (yield* ComposioClientSingleton).get();
83 + const client = yield* developerProjectClient;
84 const searchParams = triggerLogSearchParams([
85 ['trigger_name', trigger],
86 ['trigger_id', triggerId],
ts/packages/cli/src/commands/surface.ts
+59
@@ -4,9 +4,11 @@ import { ExpectedFailure } from 'src/effects/expected-failure';
4 import type { CommandIdentity, SharedFlagName } from 'src/invocation/command-identity';
5 import {
6 resolveCommandProject,
7 + resolveDeveloperProjectOrDefault,
8 type ProjectMode,
9 type ResolvedCommandProject,
10 } from 'src/services/command-project';
11 +import { ComposioClientSingleton } from 'src/services/composio-clients';
12 import { ProjectContext } from 'src/services/project-context';
13 import { TerminalUI } from 'src/services/terminal-ui';
14 import { ComposioUserContext } from 'src/services/user-context';
@@ -56,6 +58,49 @@ export const resolveSurfaceProject = (mode: ProjectMode) =>
58 });
59 });
60
61 +/**
62 + * A warning that reaches stderr even off a terminal, where `ui.log.*` decoration is dropped: a
63 + * script or agent reading stderr must see a fallback that affects the result.
64 + */
65 +export const warnOnStderr = (message: string) =>
66 + Effect.gen(function* () {
67 + const ui = yield* TerminalUI;
68 + if ((yield* ui.capabilities).canDecorate) {
69 + yield* ui.log.warn(message);
70 + } else {
71 + yield* ui.error(`Warning: ${message}`);
72 + }
73 + });
74 +
75 +/**
76 + * The developer project of a dev command that reads or writes the project's resources (auth
77 + * configs, connected accounts, trigger instances, logs): `--project-name`'s, else the
78 + * directory's, else the backend's default developer project, named on stderr every time
79 + * (`resolveDeveloperProjectOrDefault`). These commands once sent no project and let the backend
80 + * pick that default, so a directory without a usable project of its own keeps working; a command
81 + * that always required one uses `resolveSurfaceProject('developer')`. Resolved once, so every
82 + * request of the command names the same project.
83 + */
84 +export const resolveDeveloperResourceProject = Effect.gen(function* () {
85 + const { projectName } = yield* CommandSurface;
86 + const { project, notice } = yield* resolveDeveloperProjectOrDefault({
87 + projectName: Option.getOrUndefined(projectName),
88 + });
89 + yield* Effect.transposeOption(Option.map(notice, warnOnStderr));
90 + return project;
91 +});
92 +
93 +/**
94 + * The client for the developer project a dev command acts on (`resolveDeveloperResourceProject`),
95 + * for a command whose requests all read or write that project's resources: they name it rather
96 + * than leaving the backend to pick the key's default project.
97 + */
98 +export const developerProjectClient = Effect.gen(function* () {
99 + const project = yield* resolveDeveloperResourceProject;
100 + const clientSingleton = yield* ComposioClientSingleton;
101 + return yield* clientSingleton.getFor({ orgId: project.orgId, projectId: project.projectId });
102 +});
103 +
104 // --- acting user ------------------------------------------------------------------------------
105
106 /** Which step of the acting-user rule picked the user. */
@@ -246,6 +291,20 @@ export const actingUserOption = () =>
291 }));
292 });
293
294 +/**
295 + * The dev tree's acting user for a command that also runs without one, against the developer
296 + * project the command resolved (`resolveSurfaceProject('developer')`), by the same rule as
297 + * `actingUser`: `--user-id`, then the directory test user (only for the directory's own project),
298 + * then the global test user. Names a test user standing in on stderr, as `actingUser` does; none
299 + * when no step finds a user.
300 + */
301 +export const devActingUserOption = (project: ResolvedCommandProject) =>
302 + Effect.gen(function* () {
303 + const user = yield* devUser(Option.some(project.projectId));
304 + yield* announceFallback(user);
305 + return Option.map(user, (found): ActingUser => ({ ...found, project }));
306 + });
307 +
308 /** A shared flag of the `dev` group. */
309 export type SharedFlag = '--user-id' | '--project-name';
310
ts/packages/cli/src/commands/triggers/create/triggers.create.handler.ts
+12 -9
@@ -1,6 +1,6 @@
1 import { Effect, Match, Option, Result } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 -import { actingUserOption } from 'src/commands/surface';
3 +import { devActingUserOption, resolveDeveloperResourceProject } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -41,10 +41,12 @@ const invalidTriggerConfig = (error: JsonParsingError) =>
41 );
42
43 /**
44 - * Create a trigger instance as the `dev` group's `--user-id`, else the directory project's test
45 - * user, else the global test user; without any, the request omits `user_id`. A missing `<trigger-name>` or an invalid `--trigger-config` fails
46 - * with a `CommandInputError` before any request; an API failure is reported with a hint and
47 - * exits 1.
44 + * Create a trigger instance in the developer project (`resolveDeveloperResourceProject`) as
45 + * the `dev` group's `--user-id`, else the directory project's test user (for its own project),
46 + * else the global test user; without any, the request omits `user_id`. A missing
47 + * `<trigger-name>` or an invalid `--trigger-config` fails with a `CommandInputError` before any
48 + * request, and a developer project that cannot be found with `ProjectResolutionError`; an API failure is
49 + * reported with a hint and exits 1.
50 *
51 * @example
52 * ```bash
@@ -72,15 +74,16 @@ export const runTriggersCreate = ({
74 return yield* invalidTriggerConfig(parsedTriggerConfig.failure);
75 }
76
75 - // The group rejects --project-name, so this is the directory's project. A defaulted user id
76 - // must own the connected account on a 2FA project; `actingUserOption` names it on stderr.
77 - const acting = yield* actingUserOption();
77 + const project = yield* resolveDeveloperResourceProject;
78 + // A defaulted user id must own the connected account on a 2FA project; `devActingUserOption`
79 + // names it on stderr.
80 + const acting = yield* devActingUserOption(project);
81 const resolvedUserId = Option.map(acting, found => found.userId);
82
83 const created = yield* ui
84 .withSpinner(
85 `Creating trigger "${triggerName.value}"...`,
83 - repo.createTrigger(triggerName.value, {
86 + repo.createTrigger(project, triggerName.value, {
87 connected_account_id: Option.getOrUndefined(connectedAccountId),
88 trigger_config: parsedTriggerConfig.success,
89 user_id: Option.getOrUndefined(resolvedUserId),
ts/packages/cli/src/commands/triggers/disable/triggers.disable.handler.ts
+16 -13
@@ -1,5 +1,6 @@
1 import { Effect, Option } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 +import { resolveDeveloperResourceProject } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -14,10 +15,9 @@ export type TriggersDisableParams = {
15 const invalidInput = commandInputError('dev triggers disable');
16
17 /**
17 - * Disable an existing trigger instance. A developer-destructive command: it runs only when
18 - * `developer.destructive_actions` is enabled and `--dangerously-allow` is passed. A missing `<id>`
19 - * fails with a `CommandInputError` before any request; an API failure is reported with a hint and
20 - * exits 1.
18 + * Disable an existing trigger instance of the developer project. A developer-destructive command:
19 + * it runs only when `developer.destructive_actions` is enabled and `--dangerously-allow` is passed.
20 + * A missing `<id>` fails with a `CommandInputError` before any request, and a developer project that cannot be found with `ProjectResolutionError`; an API failure is reported with a hint and exits 1.
21 *
22 * @example
23 * ```bash
@@ -49,15 +49,18 @@ export const runTriggersDisable = ({ id, dangerouslyAllow }: TriggersDisablePara
49 }
50
51 const idValue = id.value;
52 - yield* ui.withSpinner(`Disabling trigger "${idValue}"...`, repo.disableTrigger(idValue)).pipe(
53 - Effect.catchTag(
54 - CLIENT_API_ERROR_TAGS,
55 - handleClientApiError(ui, {
56 - fallbackMessage: `Failed to disable trigger "${idValue}".`,
57 - hint: 'Browse available triggers:\n> composio dev triggers status',
58 - })
59 - )
60 - );
52 + const project = yield* resolveDeveloperResourceProject;
53 + yield* ui
54 + .withSpinner(`Disabling trigger "${idValue}"...`, repo.disableTrigger(project, idValue))
55 + .pipe(
56 + Effect.catchTag(
57 + CLIENT_API_ERROR_TAGS,
58 + handleClientApiError(ui, {
59 + fallbackMessage: `Failed to disable trigger "${idValue}".`,
60 + hint: 'Browse available triggers:\n> composio dev triggers status',
61 + })
62 + )
63 + );
64
65 yield* ui.log.success(`Trigger "${idValue}" disabled.`);
66 });
ts/packages/cli/src/commands/triggers/enable/triggers.enable.handler.ts
+16 -11
@@ -1,5 +1,6 @@
1 import { Effect, Option } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 +import { resolveDeveloperResourceProject } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -12,8 +13,9 @@ export type TriggersEnableParams = {
13 const invalidInput = commandInputError('dev triggers enable');
14
15 /**
15 - * Enable an existing trigger instance. A missing `<id>` fails with a `CommandInputError` before
16 - * any request; an API failure is reported with a hint and exits 1.
16 + * Enable an existing trigger instance of the developer project. A missing `<id>` fails with a
17 + * `CommandInputError` before any request, and a developer project that cannot be found with
18 + * `ProjectResolutionError`; an API failure is reported with a hint and exits 1.
19 *
20 * @example
21 * ```bash
@@ -33,15 +35,18 @@ export const runTriggersEnable = ({ id }: TriggersEnableParams) =>
35 }
36
37 const idValue = id.value;
36 - yield* ui.withSpinner(`Enabling trigger "${idValue}"...`, repo.enableTrigger(idValue)).pipe(
37 - Effect.catchTag(
38 - CLIENT_API_ERROR_TAGS,
39 - handleClientApiError(ui, {
40 - fallbackMessage: `Failed to enable trigger "${idValue}".`,
41 - hint: 'Browse available triggers:\n> composio dev triggers status --show-disabled',
42 - })
43 - )
44 - );
38 + const project = yield* resolveDeveloperResourceProject;
39 + yield* ui
40 + .withSpinner(`Enabling trigger "${idValue}"...`, repo.enableTrigger(project, idValue))
41 + .pipe(
42 + Effect.catchTag(
43 + CLIENT_API_ERROR_TAGS,
44 + handleClientApiError(ui, {
45 + fallbackMessage: `Failed to enable trigger "${idValue}".`,
46 + hint: 'Browse available triggers:\n> composio dev triggers status --show-disabled',
47 + })
48 + )
49 + );
50
51 yield* ui.log.success(`Trigger "${idValue}" enabled.`);
52 });
ts/packages/cli/src/commands/triggers/status/triggers.status.handler.ts
+6 -2
@@ -1,4 +1,5 @@
1 import { Array as Arr, Effect, Option } from 'effect';
2 +import { resolveDeveloperResourceProject } from 'src/commands/surface';
3 import { handleClientApiError } from 'src/effects/handle-http-error';
4 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 import {
@@ -52,7 +53,9 @@ const filterByToolkits = (
53 });
54
55 /**
55 - * Display active trigger instances with optional filters.
56 + * Display the developer project's active trigger instances with optional filters. Fails with
57 + * `ProjectResolutionError` when no developer project can be found
58 + * (`resolveDeveloperResourceProject`).
59 *
60 * @example
61 * ```bash
@@ -72,6 +75,7 @@ export const runTriggersStatus = ({
75 Effect.gen(function* () {
76 const ui = yield* TerminalUI;
77 const repo = yield* ComposioToolkitsRepository;
78 + const project = yield* resolveDeveloperResourceProject;
79
80 // An empty list (`--toolkits ","`) filters nothing.
81 const toolkitFilter = Option.flatMap(toolkits, csv =>
@@ -84,7 +88,7 @@ export const runTriggersStatus = ({
88 const page = yield* ui
89 .withSpinner(
90 'Fetching trigger status...',
87 - repo.listActiveTriggers({
91 + repo.listActiveTriggers(project, {
92 user_ids: csvOption(userIds),
93 connected_account_ids: csvOption(connectedAccountIds),
94 trigger_ids: csvOption(triggerIds),
ts/packages/cli/src/commands/triggers/triggers.cmd.ts
+4 -4
@@ -24,10 +24,10 @@ export const triggersCmd = Command.make('triggers').pipe(
24 triggersCmd$Listen,
25 triggersCmd$List.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
26 triggersCmd$Info.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
27 - triggersCmd$Status.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
28 - triggersCmd$Create.pipe(withCommandMeta({ sharedFlags: { projectName: false } })),
29 - triggersCmd$Enable.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
30 - triggersCmd$Disable.pipe(withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })),
27 + triggersCmd$Status.pipe(withCommandMeta({ sharedFlags: { userId: false } })),
28 + triggersCmd$Create,
29 + triggersCmd$Enable.pipe(withCommandMeta({ sharedFlags: { userId: false } })),
30 + triggersCmd$Disable.pipe(withCommandMeta({ sharedFlags: { userId: false } })),
31 ]),
32 withCommandMeta({ requiresLogin: true })
33 );
ts/packages/cli/src/services/command-project.ts
+159 -50
@@ -1,5 +1,5 @@
1 import { isAPIError } from '@composio/client/effect';
2 -import { Data, Effect, Option } from 'effect';
2 +import { Data, Effect, Option, Predicate, Result } from 'effect';
3 import { ExpectedFailure } from 'src/effects/expected-failure';
4 import { extractMessage } from 'src/utils/api-error-extraction';
5 import { ProjectContext } from './project-context';
@@ -9,6 +9,7 @@ import {
9 findDeveloperProjectByName,
10 DeveloperProjectNotFoundError,
11 AmbiguousDeveloperProjectNameError,
12 + getSessionInfoByUserApiKey,
13 } from './composio-account';
14
15 export type ProjectMode = 'consumer' | 'developer';
@@ -16,7 +17,11 @@ export type ProjectMode = 'consumer' | 'developer';
17 export type CliProjectType = 'CONSUMER' | 'DEVELOPER';
18
19 export type CliProjectResolutionSource =
19 - 'consumer-default' | 'developer-project-name' | 'developer-local-config' | 'developer-explicit';
20 + | 'consumer-default'
21 + | 'developer-project-name'
22 + | 'developer-local-config'
23 + | 'developer-explicit'
24 + | 'developer-default';
25
26 export interface ResolvedCommandProject {
27 readonly orgId: string;
@@ -75,52 +80,125 @@ const normalizeLookupError = <E>(error: E): ProjectResolutionError | E => {
80 : new ProjectResolutionError({ reason: 'request_failed', message: apiMessage, cause: error });
81 };
82
83 +/** Why the working directory's developer project cannot serve a command. */
84 +type DirectoryProjectRefusal = { readonly reason: 'missing_developer_project' };
85 +
86 +const refusalError = (_refusal: DirectoryProjectRefusal): ProjectResolutionError =>
87 + new ProjectResolutionError({
88 + reason: 'missing_developer_project',
89 + message: 'No developer project configured for this directory. Run `composio dev init`.',
90 + });
91 +
92 +/** The developer project configured for the working directory. */
93 +const localDeveloperProject = (params: {
94 + projectContext: ProjectContext['Service'];
95 + apiKey: string;
96 + storedOrgId: Option.Option<string>;
97 +}) =>
98 + Effect.gen(function* () {
99 + const localProject = yield* params.projectContext.resolve;
100 + if (Option.isNone(localProject)) {
101 + return Result.fail<DirectoryProjectRefusal>({ reason: 'missing_developer_project' });
102 + }
103 + const { orgId, projectId, projectName } = localProject.value;
104 + return Result.succeed({
105 + orgId,
106 + projectId,
107 + projectName: Option.getOrUndefined(projectName),
108 + projectType: 'DEVELOPER',
109 + source: 'developer-local-config',
110 + } satisfies ResolvedCommandProject);
111 + });
112 +
113 +/** The directory's developer project; fails with `ProjectResolutionError` when it cannot be used. */
114 +const resolveLocalDeveloperProject = (params: Parameters<typeof localDeveloperProject>[0]) =>
115 + localDeveloperProject(params).pipe(
116 + Effect.flatMap(result => Effect.fromResult(Result.mapError(result, refusalError)))
117 + );
118 +
119 +/** What is wrong with the directory's developer project, as the start of a sentence. */
120 +const refusalSummary = (_refusal: DirectoryProjectRefusal): string =>
121 + 'No developer project is set up for this directory';
122 +
123 +/** The command that lets the directory's developer project serve the next run. */
124 +const refusalRemedy = (_refusal: DirectoryProjectRefusal): string =>
125 + 'Run `composio dev init` to choose one, or pass --project-name.';
126 +
127 +/** The stderr notice naming the default developer project a command uses instead. */
128 +const defaultProjectNotice = (
129 + refusal: DirectoryProjectRefusal,
130 + project: ResolvedCommandProject,
131 + storedOrgId: Option.Option<string>
132 +): string => {
133 + const which = Option.isSome(storedOrgId)
134 + ? 'the newest developer project in the org you are logged in to'
135 + : 'the newest developer project in the org you joined most recently';
136 + return `${refusalSummary(refusal)}; using "${project.projectName}" (${project.projectId}), ${which}, instead. ${refusalRemedy(refusal)}`;
137 +};
138 +
139 +/**
140 + * The developer project the backend acts on for a user-key request that names none: the newest
141 + * developer project of the stored org (sent as `x-org-id`, so `composio orgs switch` holds), or
142 + * without one, of the org the user joined most recently. Read once from session info, so every
143 + * request of the command names this one project even if another becomes the newest meanwhile.
144 + * Session info without a project, or a 404, means there is no such project. Other request
145 + * failures keep their cause and message instead of recommending project setup.
146 + */
147 +const defaultDeveloperProject = (params: {
148 + apiKey: string;
149 + storedOrgId: Option.Option<string>;
150 + refusal: DirectoryProjectRefusal;
151 +}) =>
152 + getSessionInfoByUserApiKey({
153 + userApiKey: params.apiKey,
154 + orgId: Option.getOrUndefined(params.storedOrgId),
155 + }).pipe(
156 + Effect.map(
157 + info =>
158 + ({
159 + orgId: info.project.org.id,
160 + projectId: info.project.nano_id,
161 + projectName: info.project.name,
162 + projectType: 'DEVELOPER',
163 + source: 'developer-default',
164 + }) satisfies ResolvedCommandProject
165 + ),
166 + Effect.mapError(error =>
167 + (isAPIError(error) && error.status === 404) ||
168 + Predicate.isTagged(error, 'services/HttpDecodingError')
169 + ? new ProjectResolutionError({
170 + reason: 'missing_developer_project',
171 + message: `${refusalSummary(params.refusal)}, and no developer project was found in your org to use instead. Run \`composio dev init\` to set one up.`,
172 + cause: error,
173 + })
174 + : error
175 + )
176 + );
177 +
178 export const resolveCommandProject = (params: { mode: ProjectMode; projectName?: string }) =>
179 Effect.gen(function* () {
180 const ctx = yield* ComposioUserContext;
181 const projectContext = yield* ProjectContext;
182 const apiKey = Option.getOrUndefined(ctx.data.apiKey);
83 - const currentOrgId = yield* Option.match(ctx.data.orgId, {
84 - onNone: () => Effect.fail(missingOrg()),
85 - onSome: value => Effect.succeed(value),
86 - });
87 -
183 if (!apiKey) {
184 return yield* Effect.fail(missingOrg());
185 }
186
92 - if (params.mode === 'consumer') {
93 - if (params.projectName) {
94 - const developerProject = yield* findDeveloperProjectByName({
95 - apiKey,
96 - orgId: currentOrgId,
97 - name: params.projectName,
98 - });
99 -
100 - return {
101 - orgId: currentOrgId,
102 - projectId: developerProject.id,
103 - projectName: developerProject.name,
104 - projectType: 'DEVELOPER',
105 - source: 'developer-project-name',
106 - } satisfies ResolvedCommandProject;
107 - }
108 -
109 - const consumerProject = yield* resolveConsumerProject({
187 + // The directory's own project needs no stored org: a key from `COMPOSIO_USER_API_KEY`
188 + // carries none, and the project file names its org.
189 + if (params.mode === 'developer' && !params.projectName) {
190 + return yield* resolveLocalDeveloperProject({
191 + projectContext,
192 apiKey,
111 - orgId: currentOrgId,
193 + storedOrgId: ctx.data.orgId,
194 });
113 -
114 - return {
115 - orgId: consumerProject.org_id,
116 - projectId: consumerProject.project_nano_id,
117 - projectName: consumerProject.project_name,
118 - projectType: 'CONSUMER',
119 - consumerUserId: consumerProject.consumer_user_id,
120 - source: 'consumer-default',
121 - } satisfies ResolvedCommandProject;
195 }
196
197 + const currentOrgId = yield* Option.match(ctx.data.orgId, {
198 + onNone: () => Effect.fail(missingOrg()),
199 + onSome: value => Effect.succeed(value),
200 + });
201 +
202 if (params.projectName) {
203 const developerProject = yield* findDeveloperProjectByName({
204 apiKey,
@@ -133,25 +211,56 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
211 projectId: developerProject.id,
212 projectName: developerProject.name,
213 projectType: 'DEVELOPER',
136 - source: 'developer-explicit',
214 + source: params.mode === 'consumer' ? 'developer-project-name' : 'developer-explicit',
215 } satisfies ResolvedCommandProject;
216 }
217
140 - const localProject = yield* projectContext.resolve;
141 - if (Option.isNone(localProject)) {
142 - return yield* Effect.fail(
143 - new ProjectResolutionError({
144 - reason: 'missing_developer_project',
145 - message: 'No developer project configured for this directory. Run `composio dev init`.',
146 - })
147 - );
148 - }
218 + const consumerProject = yield* resolveConsumerProject({
219 + apiKey,
220 + orgId: currentOrgId,
221 + });
222
223 return {
151 - orgId: localProject.value.orgId,
152 - projectId: localProject.value.projectId,
153 - projectName: Option.getOrUndefined(localProject.value.projectName),
154 - projectType: 'DEVELOPER',
155 - source: 'developer-local-config',
224 + orgId: consumerProject.org_id,
225 + projectId: consumerProject.project_nano_id,
226 + projectName: consumerProject.project_name,
227 + projectType: 'CONSUMER',
228 + consumerUserId: consumerProject.consumer_user_id,
229 + source: 'consumer-default',
230 } satisfies ResolvedCommandProject;
231 }).pipe(Effect.mapError(normalizeLookupError));
232 +
233 +/**
234 + * The developer project for a dev command that acted on the backend's default project before
235 + * it named one, so a directory without a usable project of its own keeps working: `--project-name`'s
236 + * (whose failures stay failures), else the directory's, else the backend's default developer
237 + * project (`defaultDeveloperProject`). `notice` says, for stderr, why the default stands in and
238 + * which project it is; it is none when the command uses the project it was given. The default
239 + * never stands in for a `--project-name` that cannot be resolved.
240 + */
241 +export const resolveDeveloperProjectOrDefault = (params: { projectName?: string }) =>
242 + Effect.gen(function* () {
243 + if (params.projectName) {
244 + const project = yield* resolveCommandProject({
245 + mode: 'developer',
246 + projectName: params.projectName,
247 + });
248 + return { project, notice: Option.none<string>() };
249 + }
250 + const ctx = yield* ComposioUserContext;
251 + const projectContext = yield* ProjectContext;
252 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
253 + if (!apiKey) {
254 + return yield* Effect.fail(missingOrg());
255 + }
256 + const storedOrgId = ctx.data.orgId;
257 + const local = yield* localDeveloperProject({ projectContext, apiKey, storedOrgId });
258 + return yield* Result.match(local, {
259 + onSuccess: project => Effect.succeed({ project, notice: Option.none<string>() }),
260 + onFailure: refusal =>
261 + Effect.map(defaultDeveloperProject({ apiKey, storedOrgId, refusal }), project => ({
262 + project,
263 + notice: Option.some(defaultProjectNotice(refusal, project, storedOrgId)),
264 + })),
265 + });
266 + }).pipe(Effect.mapError(normalizeLookupError));
ts/packages/cli/src/services/composio-clients.ts
+8 -19
@@ -25,7 +25,6 @@ import { cliClientIdentity } from './client-provenance';
25 import { sha256Hex } from 'src/utils/checksums';
26 import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
27 import { ComposioUserContext, ComposioUserContextLive } from './user-context';
28 -import { ProjectContext } from './project-context';
28 import { makeClientMetricsCollector, type ClientMetricsCollector } from './composio-client-metrics';
29 import { ComposioClientConfigurationError, type ClientError } from './composio-errors';
30 import { isClientConfigurationError } from 'src/utils/api-error-extraction';
@@ -104,8 +103,9 @@ export type ClientScope = ClientCredential &
103 */
104 export interface ComposioClientSingletonShape {
105 /**
107 - * The client for the user's key and, when the working directory resolves to
108 - * a project, that project's org and project.
106 + * The client for the user's key, with no org or project: the backend acts on
107 + * the key's default project. A command that acts on a project it resolved
108 + * (a developer project, the consumer project) asks `getFor` for that one.
109 */
110 readonly get: () => Effect.Effect<ComposioClientShape, ClientBuildError | NoSuchElementError>;
111 /**
@@ -171,7 +171,6 @@ export const clientScopeKey = (client: ComposioClientShape): string => {
171 const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
172 Effect.gen(function* () {
173 const ctx = yield* ComposioUserContext;
174 - const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
174 const httpClient = yield* HttpClient.HttpClient;
175
176 // Read from disk once per process, with the services captured here.
@@ -246,19 +245,7 @@ const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
245
246 return {
247 get: Effect.fn(function* () {
249 - const resolvedProjectContext = yield* Option.match(projectContextOpt, {
250 - onNone: () => Effect.succeed(Option.none()),
251 - onSome: projectContext =>
252 - projectContext.resolve.pipe(Effect.catch(() => Effect.succeed(Option.none()))),
253 - });
254 - return yield* Option.match(resolvedProjectContext, {
255 - onNone: () => getFor(),
256 - onSome: keys =>
257 - getFor({
258 - orgId: keys.orgId,
259 - projectId: keys.projectId,
260 - }),
261 - });
248 + return yield* getFor();
249 }),
250 getFor: Effect.fn(function* (params: ClientScope) {
251 return yield* getFor(params);
@@ -334,7 +321,7 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
321 * project-scoped, so they are absent from the build-time catalog and from
322 * {@link getToolkits}, whose callers expect Composio-managed toolkits only.
323 * @param scope - The org/project the command resolved; without it, the
337 - * project context decides, which is no project at all in consumer mode
324 + * backend picks the key's default project
325 */
326 const getProjectToolkits = (scope?: ToolkitProjectScope) => listToolkits('project', scope);
327
@@ -478,7 +465,9 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
465 */
466 getToolkitDetailed,
467 ...lookupOperations(client),
481 - ...resourceOperations(client),
468 + ...resourceOperations(scope =>
469 + clientSingleton.getFor({ orgId: scope.orgId, projectId: scope.projectId })
470 + ),
471 };
472 });
473
ts/packages/cli/src/services/composio-resource-operations.ts
+39 -23
@@ -14,25 +14,34 @@ import { ConnectedAccountItem } from 'src/models/connected-accounts';
14 import { Toolkits, type ToolkitSearchResult } from 'src/models/toolkits';
15 import { TriggerInstanceItems } from 'src/models/triggers';
16 import { TriggerType } from 'src/models/trigger-types';
17 +import type { ToolkitProjectScope } from './composio-clients';
18 import type { ClientError } from './composio-errors';
19 import { decode, idempotent } from './composio-request';
20
21 /**
22 * Auth config, connected account, and trigger instance operations: single-page
22 - * CRUD with no catalog caching.
23 + * CRUD with no catalog caching. These resources belong to a project, so every
24 + * call takes the org and project the command resolved and goes through the
25 + * client `clientFor` builds for them; none falls back to the project the
26 + * backend would pick for the key.
27 */
24 -export const resourceOperations = (client: Effect.Effect<ComposioClientShape, ClientError>) => ({
28 +export const resourceOperations = (
29 + clientFor: (scope: ToolkitProjectScope) => Effect.Effect<ComposioClientShape, ClientError>
30 +) => ({
31 /**
32 * Lists auth configs with optional filters. Returns a single page of results.
33 * @param params - Search/filter parameters
34 */
29 - listAuthConfigs: (params: {
30 - search?: string;
31 - toolkit_slug?: string;
32 - limit?: number;
33 - show_disabled?: boolean;
34 - }) =>
35 - client.pipe(
35 + listAuthConfigs: (
36 + scope: ToolkitProjectScope,
37 + params: {
38 + search?: string;
39 + toolkit_slug?: string;
40 + limit?: number;
41 + show_disabled?: boolean;
42 + }
43 + ) =>
44 + clientFor(scope).pipe(
45 Effect.flatMap(c =>
46 c.authConfigs.list(
47 {
@@ -50,8 +59,8 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
59 * Retrieves detailed info about a single auth config by its nanoid.
60 * @param nanoid - Auth config ID
61 */
53 - getAuthConfig: (nanoid: string) =>
54 - client.pipe(
62 + getAuthConfig: (scope: ToolkitProjectScope, nanoid: string) =>
63 + clientFor(scope).pipe(
64 Effect.flatMap(c => c.authConfigs.retrieve(nanoid, idempotent)),
65 Effect.flatMap(decode(AuthConfigItem))
66 ),
@@ -59,8 +68,8 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
68 * Creates a new auth config for a toolkit.
69 * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
70 */
62 - createAuthConfig: (params: AuthConfigCreateParams) =>
63 - client.pipe(
71 + createAuthConfig: (scope: ToolkitProjectScope, params: AuthConfigCreateParams) =>
72 + clientFor(scope).pipe(
73 Effect.flatMap(c => c.authConfigs.create(params)),
74 Effect.flatMap(decode(AuthConfigCreateResponse))
75 ),
@@ -68,8 +77,8 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
77 * Retrieves detailed info about a single connected account by its nanoid.
78 * @param nanoid - Connected account ID (e.g. "con_1a2b3c4d5e6f")
79 */
71 - getConnectedAccount: (nanoid: string) =>
72 - client.pipe(
80 + getConnectedAccount: (scope: ToolkitProjectScope, nanoid: string) =>
81 + clientFor(scope).pipe(
82 Effect.flatMap(c => c.connectedAccounts.retrieve(nanoid, idempotent)),
83 Effect.flatMap(decode(ConnectedAccountItem))
84 ),
@@ -77,8 +86,8 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
86 * Lists active trigger instances with optional filters.
87 * Returns a single page of results.
88 */
80 - listActiveTriggers: (params: TriggerInstanceListActiveParams) =>
81 - client.pipe(
89 + listActiveTriggers: (scope: ToolkitProjectScope, params: TriggerInstanceListActiveParams) =>
90 + clientFor(scope).pipe(
91 Effect.flatMap(c =>
92 c.triggerInstances.listActive(
93 {
@@ -108,12 +117,19 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
117 )
118 )
119 ),
111 - createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
112 - Effect.flatMap(client, c => c.triggerInstances.upsert(triggerSlug, params)),
113 - enableTrigger: (triggerId: string) =>
114 - Effect.flatMap(client, c => c.triggerInstances.manage.update(triggerId, { status: 'enable' })),
115 - disableTrigger: (triggerId: string) =>
116 - Effect.flatMap(client, c => c.triggerInstances.manage.update(triggerId, { status: 'disable' })),
120 + createTrigger: (
121 + scope: ToolkitProjectScope,
122 + triggerSlug: string,
123 + params?: TriggerInstanceUpsertParams
124 + ) => Effect.flatMap(clientFor(scope), c => c.triggerInstances.upsert(triggerSlug, params)),
125 + enableTrigger: (scope: ToolkitProjectScope, triggerId: string) =>
126 + Effect.flatMap(clientFor(scope), c =>
127 + c.triggerInstances.manage.update(triggerId, { status: 'enable' })
128 + ),
129 + disableTrigger: (scope: ToolkitProjectScope, triggerId: string) =>
130 + Effect.flatMap(clientFor(scope), c =>
131 + c.triggerInstances.manage.update(triggerId, { status: 'disable' })
132 + ),
133 });
134
135 /**
ts/packages/cli/src/services/tools-executor.ts
+2 -3
@@ -355,9 +355,8 @@ export const ToolsExecutorLive = Layer.effect(
355 return ToolsExecutor.of({
356 execute: (slug, params) =>
357 Effect.gen(function* () {
358 - // Resolved lazily: `get()` walks the project context off disk, and every
359 - // caller on the execute path already hands in a client built for the
360 - // resolved org/project.
358 + // Every caller on the execute path hands in a client built for the resolved
359 + // org/project; `get()` is unscoped and acts on the key's default project.
360 const resolvedClient = params.client ?? (yield* clientSingleton.get());
361 const sessionContext = yield* resolveToolRouterSessionContext(
362 resolvedClient,
ts/packages/cli/test/__utils__/layers/auth-configs.ts
+5 -2
@@ -12,6 +12,7 @@ import {
12 type AuthConfigsTestData,
13 } from './connected-accounts';
14 import { terminalUITestImpl } from '../services/terminal-ui-test';
15 +import { DirectoryProjectTest } from './developer-project';
16
17 /** What an `auth-configs` handler test serves. */
18 export interface AuthConfigsHandlerFixture {
@@ -23,13 +24,15 @@ export interface AuthConfigsHandlerFixture {
24
25 /**
26 * What an `auth-configs` handler needs without argv or `TestLive`: a headless terminal whose
26 - * stdout payloads land in `outputs` (decoration goes to `MockConsole`), and a repository
27 - * serving only the auth-config methods. Any other repository method dies.
27 + * stdout payloads land in `outputs` (decoration goes to `MockConsole`), the directory's
28 + * developer project (`DirectoryProjectTest`), and a repository serving only the auth-config
29 + * methods. Any other repository method dies.
30 */
31 export const AuthConfigsHandlerTest = (fixture: AuthConfigsHandlerFixture = {}) => {
32 const outputs: Array<string> = [];
33 const layer = Layer.mergeAll(
34 Layer.effect(Console.Console, MockConsole.make),
35 + DirectoryProjectTest,
36 Layer.succeed(
37 TerminalUI,
38 TerminalUI.of({
ts/packages/cli/test/__utils__/layers/connected-accounts.ts
+12 -9
@@ -106,12 +106,15 @@ export type ConnectedAccountRepositoryMethods = Pick<
106 export const authConfigRepositoryMethods = (
107 authConfigsData: ResolvedAuthConfigsTestData
108 ): AuthConfigRepositoryMethods => ({
109 - listAuthConfigs: (params: {
110 - search?: string;
111 - toolkit_slug?: string;
112 - limit?: number;
113 - show_disabled?: boolean;
114 - }) => {
109 + listAuthConfigs: (
110 + _scope,
111 + params: {
112 + search?: string;
113 + toolkit_slug?: string;
114 + limit?: number;
115 + show_disabled?: boolean;
116 + }
117 + ) => {
118 let results = [...authConfigsData.items];
119
120 if (params.toolkit_slug) {
@@ -136,14 +139,14 @@ export const authConfigRepositoryMethods = (
139 next_cursor: null,
140 });
141 },
139 - getAuthConfig: (nanoid: string) =>
142 + getAuthConfig: (_scope, nanoid: string) =>
143 findById(authConfigsData.items, nanoid, () =>
144 notFoundError(`Auth config "${nanoid}" not found`, {
145 message: `Auth config "${nanoid}" not found.`,
146 suggested_fix: 'Check the auth config ID and try again.',
147 })
148 ),
146 - createAuthConfig: (params: AuthConfigCreateParams) => {
149 + createAuthConfig: (_scope, params: AuthConfigCreateParams) => {
150 authConfigsData.onCreate?.(params);
151 return Effect.succeed(
152 authConfigsData.createResponse ?? {
@@ -163,7 +166,7 @@ export const connectedAccountRepositoryMethods = (
166 connectedAccountsData: ResolvedConnectedAccountsTestData
167 ): ConnectedAccountRepositoryMethods => ({
168 ...authConfigRepositoryMethods(authConfigsData),
166 - getConnectedAccount: (nanoid: string) =>
169 + getConnectedAccount: (_scope, nanoid: string) =>
170 findById(connectedAccountsData.items, nanoid, () =>
171 notFoundError(`Connected account "${nanoid}" not found`, {
172 message: `Connected account "${nanoid}" not found.`,
ts/packages/cli/test/__utils__/layers/developer-project.ts new
+143
@@ -0,0 +1,143 @@
1 +import { Effect, Layer, Option } from 'effect';
2 +import { CommandSurface } from 'src/commands/surface';
3 +import { ComposioClientSingleton } from 'src/services/composio-clients';
4 +import { ProjectContext } from 'src/services/project-context';
5 +import type { TerminalUI } from 'src/services/terminal-ui';
6 +import { ComposioUserContext } from 'src/services/user-context';
7 +import { cliExit } from 'test/__utils__/cli';
8 +import type { MockAccountRequest, MockRequestScope } from 'test/__utils__/layers/accounts';
9 +import { makeOrgProject, makeSessionInfo } from 'test/__utils__/models/account';
10 +import type { TestLiveInput } from 'test/__utils__/services/test-layer';
11 +import { recordRepositoryScopes } from 'test/__utils__/services/toolkits-repository-stub';
12 +
13 +/**
14 + * The developer project the `global-test-user-id` fixture's directory is set up for
15 + * (`.composio/project.json`), as the org and project a request is scoped to.
16 + */
17 +export const DIRECTORY_PROJECT_SCOPE = { orgId: 'org_test', projectId: 'proj_test' } as const;
18 +
19 +/** Another developer project in the same org, which `--project-name` names. */
20 +export const OTHER_DEVELOPER_PROJECT = makeOrgProject({
21 + id: 'proj_other',
22 + name: 'other-project',
23 + orgId: 'org_test',
24 +});
25 +
26 +export const OTHER_PROJECT_SCOPE = {
27 + orgId: 'org_test',
28 + projectId: OTHER_DEVELOPER_PROJECT.id,
29 +} as const;
30 +
31 +/**
32 + * `TestLive` input for a logged-in user (org `org_test`, global test user `global-default`)
33 + * working in a directory set up for {@link DIRECTORY_PROJECT_SCOPE}, whose org also holds
34 + * {@link OTHER_DEVELOPER_PROJECT}.
35 + */
36 +export const inDeveloperProjectDirectory = {
37 + fixture: 'global-test-user-id',
38 + accountData: { projects: [OTHER_DEVELOPER_PROJECT] },
39 +} as const satisfies TestLiveInput;
40 +
41 +/**
42 + * The developer project the backend acts on for a request that names none, as session info
43 + * reports it for `org_test`: the newest developer project of that org.
44 + */
45 +export const DEFAULT_PROJECT_SCOPE = { orgId: 'org_test', projectId: 'proj_newest' } as const;
46 +
47 +/**
48 + * `TestLive` account data whose session info reports {@link DEFAULT_PROJECT_SCOPE}'s project in the
49 + * org the request names (`org_test` when it names none), recording every account request in
50 + * `requests`.
51 + */
52 +export const defaultDeveloperProjectAccountData = (requests: Array<MockAccountRequest> = []) => ({
53 + // The org the request names (`x-org-id`), else `org_test`.
54 + sessionInfo: (scope: MockRequestScope) =>
55 + makeSessionInfo({
56 + orgId: scope.orgId ?? DEFAULT_PROJECT_SCOPE.orgId,
57 + projectNanoId: DEFAULT_PROJECT_SCOPE.projectId,
58 + projectName: 'newest-project',
59 + }),
60 + onRequest: (request: MockAccountRequest) => {
61 + requests.push(request);
62 + },
63 +});
64 +
65 +/**
66 + * What a dev command that acts on a project's resources says on stderr, off a terminal, when it
67 + * uses {@link DEFAULT_PROJECT_SCOPE} because the directory is set up for no project.
68 + */
69 +export const NO_DIRECTORY_PROJECT_NOTICE =
70 + 'Warning: No developer project is set up for this directory; using "newest-project" (proj_newest), the newest developer project in the org you are logged in to, instead. Run `composio dev init` to choose one, or pass --project-name.';
71 +
72 +/**
73 + * Runs the CLI with `args` while the repository records the scope of every project resource
74 + * call, and returns how the run ended with those calls. `layer` replaces more of the test layer,
75 + * such as the terminal.
76 + */
77 +export const runRecordingRepositoryScopes = (
78 + args: ReadonlyArray<string>,
79 + layer: Layer.Layer<TerminalUI> | undefined = undefined
80 +) =>
81 + Effect.gen(function* () {
82 + const recorder = recordRepositoryScopes();
83 + const result = yield* cliExit(args).pipe(
84 + Effect.provide(recorder.layer),
85 + Effect.provide(layer ?? Layer.empty)
86 + );
87 + return { ...result, calls: recorder.calls };
88 + });
89 +
90 +/** Logs in to `org_test` without setting the working directory up for any project. */
91 +export const loginWithoutDeveloperProject = Effect.gen(function* () {
92 + const userContext = yield* ComposioUserContext;
93 + yield* userContext.login('test_api_key', 'org_test');
94 +});
95 +
96 +/**
97 + * What `resolveSurfaceProject('developer')` reads in a handler test, without argv or `TestLive`:
98 + * the dev tree with no shared flags, a user logged in to `org_test`, and a working directory set
99 + * up for {@link DIRECTORY_PROJECT_SCOPE}. Resolving that project sends no request, so the
100 + * client singleton dies when asked for a client.
101 + */
102 +export const DirectoryProjectTest = Layer.mergeAll(
103 + CommandSurface.dev({ userId: Option.none(), projectName: Option.none() }),
104 + Layer.succeed(
105 + ComposioUserContext,
106 + ComposioUserContext.of({
107 + data: {
108 + apiKey: Option.some('uak_test'),
109 + baseURL: 'https://mock.invalid',
110 + webURL: 'https://platform.mock.invalid',
111 + orgId: Option.some(DIRECTORY_PROJECT_SCOPE.orgId),
112 + projectId: Option.none(),
113 + testUserId: Option.none(),
114 + },
115 + backendMismatch: Option.none(),
116 + isLoggedIn: () => true,
117 + logout: Effect.void,
118 + login: () => Effect.void,
119 + update: () => Effect.void,
120 + })
121 + ),
122 + Layer.succeed(
123 + ProjectContext,
124 + ProjectContext.of({
125 + resolve: Effect.succeedSome({
126 + orgId: DIRECTORY_PROJECT_SCOPE.orgId,
127 + projectId: DIRECTORY_PROJECT_SCOPE.projectId,
128 + projectName: Option.some('Developer Project'),
129 + orgName: Option.none(),
130 + email: Option.none(),
131 + testUserId: Option.none(),
132 + }),
133 + })
134 + ),
135 + Layer.succeed(
136 + ComposioClientSingleton,
137 + ComposioClientSingleton.of({
138 + get: () => Effect.die('the client singleton is not used in this test'),
139 + getFor: () => Effect.die('the client singleton is not used in this test'),
140 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
141 + })
142 + )
143 +);
ts/packages/cli/test/__utils__/services/stub-composio-client.ts
+72 -20
@@ -14,18 +14,25 @@ export interface StubRequest {
14 }
15
16 /**
17 - * The Effect client the CLI builds in production, over a transport that
18 - * records each request and answers it with `respond`. Retries, status errors,
19 - * and the validation a call asks for are the client's own.
20 - *
21 - * A retried call sleeps on Effect's clock, so a test whose answer is retryable
22 - * runs on the live clock (`it.live`, or `layer(..., { excludeTestServices: true })`)
23 - * and answers with a `retry-after-ms: 0` header.
17 + * The org and project a stubbed request carried in its scope headers (`x-org-id`,
18 + * `x-project-id`), as the client sends them for a client built with `scope`; both are absent
19 + * for a client built without one.
20 */
25 -export const stubComposioClient = (
26 - respond: (request: StubRequest) => Response
27 -): { readonly client: ComposioClientShape; readonly requests: ReadonlyArray<StubRequest> } => {
21 +export interface StubRequestScope {
22 + readonly orgId?: string;
23 + readonly projectId?: string;
24 +}
25 +
26 +/** The scope a client is built with: an org and a project together, as `getFor` takes them. */
27 +type StubClientScope = { readonly orgId: string; readonly projectId: string };
28 +
29 +/**
30 + * A transport that records each request, and the scope headers it carried, and answers it
31 + * with `respond`. `scopes[i]` is the scope of `requests[i]`.
32 + */
33 +const recordingTransport = (respond: (request: StubRequest) => Response) => {
34 const requests: Array<StubRequest> = [];
35 + const scopes: Array<StubRequestScope> = [];
36 const httpClient = HttpClient.make(request =>
37 Effect.promise(async () => {
38 const web = Result.getOrThrow(HttpClientRequest.toWebResult(request));
@@ -36,27 +43,58 @@ export const stubComposioClient = (
43 path: `${url.pathname}${url.search}`,
44 body: text === '' ? undefined : (JSON.parse(text) as unknown),
45 };
46 + const orgId = web.headers.get('x-org-id');
47 + const projectId = web.headers.get('x-project-id');
48 requests.push(recorded);
49 + scopes.push({
50 + ...(orgId === null ? {} : { orgId }),
51 + ...(projectId === null ? {} : { projectId }),
52 + });
53 return HttpClientResponse.fromWeb(request, respond(recorded));
54 })
55 );
43 - const client = make(
56 + return { httpClient, requests, scopes };
57 +};
58 +
59 +const makeStubClient = (httpClient: HttpClient.HttpClient, scope?: StubClientScope) =>
60 + make(
61 {
62 auth: Auth.project('test'),
63 + scope:
64 + scope === undefined
65 + ? undefined
66 + : { organizationId: scope.orgId, projectId: scope.projectId },
67 baseURL: 'https://stub.invalid',
68 maxRetries: 0,
69 schemas: schemaLoaders,
70 },
71 httpClient
72 );
52 - return { client, requests };
73 +
74 +/**
75 + * The Effect client the CLI builds in production, over a transport that
76 + * records each request and answers it with `respond`. Retries, status errors,
77 + * and the validation a call asks for are the client's own.
78 + *
79 + * A retried call sleeps on Effect's clock, so a test whose answer is retryable
80 + * runs on the live clock (`it.live`, or `layer(..., { excludeTestServices: true })`)
81 + * and answers with a `retry-after-ms: 0` header.
82 + */
83 +export const stubComposioClient = (
84 + respond: (request: StubRequest) => Response
85 +): { readonly client: ComposioClientShape; readonly requests: ReadonlyArray<StubRequest> } => {
86 + const { httpClient, requests } = recordingTransport(respond);
87 + return { client: makeStubClient(httpClient), requests };
88 };
89
90 /**
91 * A layer over a test layer's `ComposioClientSingleton` that swaps the named
92 * resources of every client it hands out for those of a client built by
58 - * {@link stubComposioClient}. Calls to those resources go through the real
59 - * client to `respond`; every other resource keeps the test layer's answers.
93 + * {@link stubComposioClient}, with the org and project the client was asked
94 + * for. Calls to those resources go through the real client to `respond`;
95 + * every other resource keeps the test layer's answers. `scopes[i]` holds the
96 + * scope headers `requests[i]` carried, so a test can tell which project a
97 + * request named.
98 *
99 * The test layer's answers do not model request options (`signal`,
100 * `maxRetries`, or any header beyond `decode`), and its connected-account
@@ -68,21 +106,35 @@ export const stubClientResources = (
106 resources: ReadonlyArray<keyof ComposioClientShape>,
107 respond: (request: StubRequest) => Response
108 ) => {
71 - const stub = stubComposioClient(respond);
72 - const overlay = Object.fromEntries(resources.map(resource => [resource, stub.client[resource]]));
73 - const stubbed = (client: ComposioClientShape): ComposioClientShape => ({ ...client, ...overlay });
109 + const transport = recordingTransport(respond);
110 + const overlayFor = (scope?: StubClientScope) => {
111 + const client = makeStubClient(transport.httpClient, scope);
112 + return Object.fromEntries(resources.map(resource => [resource, client[resource]]));
113 + };
114 + const unscoped = overlayFor();
115 + const stubbed =
116 + (overlay: ReturnType<typeof overlayFor>) =>
117 + (client: ComposioClientShape): ComposioClientShape => ({ ...client, ...overlay });
118 const layer = Layer.effect(
119 ComposioClientSingleton,
120 Effect.gen(function* () {
121 const base = yield* ComposioClientSingleton;
122 return ComposioClientSingleton.of({
123 ...base,
80 - get: () => Effect.map(base.get(), stubbed),
81 - getFor: params => Effect.map(base.getFor(params), stubbed),
124 + get: () => Effect.map(base.get(), stubbed(unscoped)),
125 + getFor: params =>
126 + Effect.map(
127 + base.getFor(params),
128 + stubbed(
129 + params.orgId === undefined || params.projectId === undefined
130 + ? unscoped
131 + : overlayFor({ orgId: params.orgId, projectId: params.projectId })
132 + )
133 + ),
134 });
135 })
136 );
85 - return { requests: stub.requests, layer };
137 + return { requests: transport.requests, scopes: transport.scopes, layer };
138 };
139
140 /** A request the stub answers specially: its method and a prefix of its path. */
ts/packages/cli/test/__utils__/services/test-layer.ts
+2 -2
@@ -335,7 +335,7 @@ export const TestLayer = (input?: TestLiveInput) =>
335 ComposioToolkitsRepository.of({
336 ...toolkitCatalogMethods(toolkitsData),
337 ...connectedAccountRepositoryMethods(authConfigsData, connectedAccountsData),
338 - listActiveTriggers: (params: TriggerInstanceListActiveParams) => {
338 + listActiveTriggers: (_scope, params: TriggerInstanceListActiveParams) => {
339 let results = [...triggersData.items];
340
341 const userIds = params.user_ids;
@@ -383,7 +383,7 @@ export const TestLayer = (input?: TestLiveInput) =>
383 next_cursor: null,
384 });
385 },
386 - createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
386 + createTrigger: (_scope, triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
387 Effect.succeed({
388 trigger_id: `trg_${triggerSlug.toLowerCase()}_${params?.connected_account_id ?? 'new'}`,
389 type: 'webhook' as const,
ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts
+51
@@ -95,3 +95,54 @@ export const countingToolkitsRepository = (
95
96 return { layer, calls: () => calls, projectCalls: () => projectCalls };
97 };
98 +
99 +/** The repository methods that act on a developer project's resources; each takes its scope first. */
100 +const PROJECT_RESOURCE_METHODS = [
101 + 'listAuthConfigs',
102 + 'getAuthConfig',
103 + 'createAuthConfig',
104 + 'getConnectedAccount',
105 + 'listActiveTriggers',
106 + 'createTrigger',
107 + 'enableTrigger',
108 + 'disableTrigger',
109 +] as const;
110 +
111 +type ProjectResourceMethod = (typeof PROJECT_RESOURCE_METHODS)[number];
112 +
113 +/** One project resource call: the method and the scope it was asked to act on. */
114 +export interface RecordedRepositoryScope {
115 + readonly method: ProjectResourceMethod;
116 + readonly scope: unknown;
117 +}
118 +
119 +/**
120 + * A layer over a test layer's `ComposioToolkitsRepository` that records the scope every project
121 + * resource call names (its first argument), then answers as the test layer does.
122 + */
123 +export const recordRepositoryScopes = () => {
124 + const calls: Array<RecordedRepositoryScope> = [];
125 + const layer = Layer.effect(
126 + ComposioToolkitsRepository,
127 + Effect.gen(function* () {
128 + const base = yield* ComposioToolkitsRepository;
129 + const recording = Object.fromEntries(
130 + PROJECT_RESOURCE_METHODS.map(method => {
131 + const call = base[method] as (
132 + ...args: ReadonlyArray<unknown>
133 + ) => Effect.Effect<unknown, unknown>;
134 + return [
135 + method,
136 + (...args: ReadonlyArray<unknown>) =>
137 + Effect.suspend(() => {
138 + calls.push({ method, scope: args[0] });
139 + return call(...args);
140 + }),
141 + ];
142 + })
143 + ) as Partial<ComposioToolkitsRepositoryShape>;
144 + return ComposioToolkitsRepository.of({ ...base, ...recording });
145 + })
146 + );
147 + return { calls, layer };
148 +};
ts/packages/cli/test/src/commands/auth-configs/create/auth-configs.create.cmd.test.ts
+75 -7
@@ -4,11 +4,24 @@ import type { AuthConfigCreateParams } from '@composio/client/resources/auth-con
4 import { ConfigProvider, Effect } from 'effect';
5 import { cli, TestLive, MockConsole } from 'test/__utils__';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7 +import {
8 + DIRECTORY_PROJECT_SCOPE,
9 + DEFAULT_PROJECT_SCOPE,
10 + defaultDeveloperProjectAccountData,
11 + inDeveloperProjectDirectory,
12 + loginWithoutDeveloperProject,
13 + OTHER_DEVELOPER_PROJECT,
14 + OTHER_PROJECT_SCOPE,
15 + runRecordingRepositoryScopes,
16 +} from 'test/__utils__/layers/developer-project';
17
18 const testConfigProvider = ConfigProvider.fromEnv({
19 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
20 });
21
22 +// Logged in, in a directory set up for a developer project.
23 +const inProject = { ...inDeveloperProjectDirectory, baseConfigProvider: testConfigProvider };
24 +
25 const dangerousDevConfig = {
26 cliUserConfig: {
27 developerDangerousCommandsEnabled: true,
@@ -16,7 +29,7 @@ const dangerousDevConfig = {
29 } satisfies TestLiveInput;
30
31 describe('CLI: composio dev auth-configs create', () => {
19 - layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
32 + layer(TestLive({ ...inProject, ...dangerousDevConfig }))(
33 '[Given] --toolkit "gmail" [Then] creates with Composio managed auth',
34 it => {
35 it.effect('creates successfully', () =>
@@ -33,7 +46,7 @@ describe('CLI: composio dev auth-configs create', () => {
46 }
47 );
48
36 - layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
49 + layer(TestLive({ ...inProject, ...dangerousDevConfig }))(
50 '[Given] named config --toolkit "gmail" [Then] creates with name',
51 it => {
52 it.effect('creates with name successfully', () =>
@@ -49,7 +62,7 @@ describe('CLI: composio dev auth-configs create', () => {
62 }
63 );
64
52 - layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
65 + layer(TestLive({ ...inProject, ...dangerousDevConfig }))(
66 '[Given] --auth-scheme "OAUTH2" [Then] creates with custom auth',
67 it => {
68 it.effect('creates with custom auth scheme', () =>
@@ -74,7 +87,7 @@ describe('CLI: composio dev auth-configs create', () => {
87
88 layer(
89 TestLive({
77 - baseConfigProvider: testConfigProvider,
90 + ...inProject,
91 ...dangerousDevConfig,
92 authConfigsData: {
93 createResponse: {
@@ -97,7 +110,7 @@ describe('CLI: composio dev auth-configs create', () => {
110 );
111 });
112
100 - layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
113 + layer(TestLive({ ...inProject, ...dangerousDevConfig }))(
114 '[Given] invalid JSON in --custom-credentials [Then] fails with a usage error',
115 it => {
116 it.effect('raises a CommandInputError naming --custom-credentials', () =>
@@ -141,7 +154,7 @@ describe('CLI: composio dev auth-configs create', () => {
154 }
155 );
156
144 - layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
157 + layer(TestLive({ ...inProject, ...dangerousDevConfig }))(
158 '[Given] next step hint [Then] includes auth config ID',
159 it => {
160 it.effect('shows next step hint', () =>
@@ -160,7 +173,7 @@ describe('CLI: composio dev auth-configs create', () => {
173
174 layer(
175 TestLive({
163 - baseConfigProvider: testConfigProvider,
176 + ...inProject,
177 ...dangerousDevConfig,
178 authConfigsData: {
179 createResponse: {
@@ -211,3 +224,58 @@ describe('CLI: composio dev auth-configs create', () => {
224 }
225 );
226 });
227 +
228 +// The request goes to the developer project the command resolved, never to the one the backend
229 +// would pick for the key.
230 +describe('CLI: composio dev auth-configs create acts on the developer project', () => {
231 + layer(TestLive({ ...inProject, ...dangerousDevConfig }))(it => {
232 + it.effect.each([
233 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
234 + {
235 + given: '--project-name',
236 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
237 + scope: OTHER_PROJECT_SCOPE,
238 + },
239 + ])('[Given] $given [Then] creates the auth config in that project', ({ args, scope }) =>
240 + Effect.gen(function* () {
241 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
242 + ...['dev', 'auth-configs', 'create', '--toolkit', 'gmail'],
243 + ...args,
244 + ]);
245 +
246 + expect(exitCode).toBe(0);
247 + expect(calls).toEqual([
248 + { method: 'createAuthConfig', scope: expect.objectContaining(scope) },
249 + ]);
250 + })
251 + );
252 + });
253 +
254 + layer(
255 + TestLive({
256 + baseConfigProvider: testConfigProvider,
257 + ...dangerousDevConfig,
258 + accountData: defaultDeveloperProjectAccountData(),
259 + })
260 + )(it => {
261 + it.effect(
262 + '[Given] a directory set up for no project [Then] acts on the default developer project',
263 + () =>
264 + Effect.gen(function* () {
265 + yield* loginWithoutDeveloperProject;
266 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
267 + 'dev',
268 + 'auth-configs',
269 + 'create',
270 + '--toolkit',
271 + 'gmail',
272 + ]);
273 +
274 + expect(exitCode).toBe(0);
275 + expect(calls).toEqual([
276 + { method: 'createAuthConfig', scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE) },
277 + ]);
278 + })
279 + );
280 + });
281 +});
ts/packages/cli/test/src/commands/auth-configs/info/auth-configs.info.cmd.test.ts
+68 -3
@@ -5,6 +5,16 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7 import type { AuthConfigItem } from 'src/models/auth-configs';
8 +import {
9 + DIRECTORY_PROJECT_SCOPE,
10 + DEFAULT_PROJECT_SCOPE,
11 + defaultDeveloperProjectAccountData,
12 + inDeveloperProjectDirectory,
13 + loginWithoutDeveloperProject,
14 + OTHER_DEVELOPER_PROJECT,
15 + OTHER_PROJECT_SCOPE,
16 + runRecordingRepositoryScopes,
17 +} from 'test/__utils__/layers/developer-project';
18
19 const testAuthConfigs: AuthConfigItem[] = [
20 {
@@ -30,8 +40,11 @@ const testConfigProvider = ConfigProvider.fromEnv({
40 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
41 });
42
43 +// Logged in, in a directory set up for a developer project.
44 +const inProject = { ...inDeveloperProjectDirectory, baseConfigProvider: testConfigProvider };
45 +
46 describe('CLI: composio dev auth-configs info', () => {
34 - layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
47 + layer(TestLive({ ...inProject, authConfigsData }))(
48 '[Given] valid ID [Then] displays auth config details',
49 it => {
50 it.effect('shows auth config details', () =>
@@ -51,7 +64,7 @@ describe('CLI: composio dev auth-configs info', () => {
64 }
65 );
66
54 - layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
67 + layer(TestLive({ ...inProject, authConfigsData }))(
68 '[Given] no ID [Then] fails with a usage error',
69 it => {
70 it.effect('raises a CommandInputError naming <id>', () =>
@@ -71,7 +84,7 @@ describe('CLI: composio dev auth-configs info', () => {
84 }
85 );
86
74 - layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
87 + layer(TestLive({ ...inProject, authConfigsData }))(
88 '[Given] invalid ID [Then] shows error with hint',
89 it => {
90 it.effect('shows not found error', () =>
@@ -99,3 +112,55 @@ describe('CLI: composio dev auth-configs info', () => {
112 );
113 });
114 });
115 +
116 +// The request goes to the developer project the command resolved, never to the one the backend
117 +// would pick for the key.
118 +describe('CLI: composio dev auth-configs info acts on the developer project', () => {
119 + layer(TestLive({ ...inProject, authConfigsData }))(it => {
120 + it.effect.each([
121 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
122 + {
123 + given: '--project-name',
124 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
125 + scope: OTHER_PROJECT_SCOPE,
126 + },
127 + ])('[Given] $given [Then] reads the auth config from that project', ({ args, scope }) =>
128 + Effect.gen(function* () {
129 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
130 + ...['dev', 'auth-configs', 'info', 'ac_gmail_default'],
131 + ...args,
132 + ]);
133 +
134 + expect(exitCode).toBe(0);
135 + expect(calls).toEqual([{ method: 'getAuthConfig', scope: expect.objectContaining(scope) }]);
136 + })
137 + );
138 + });
139 +
140 + layer(
141 + TestLive({
142 + baseConfigProvider: testConfigProvider,
143 + authConfigsData,
144 + accountData: defaultDeveloperProjectAccountData(),
145 + })
146 + )(it => {
147 + it.effect(
148 + '[Given] a directory set up for no project [Then] acts on the default developer project',
149 + () =>
150 + Effect.gen(function* () {
151 + yield* loginWithoutDeveloperProject;
152 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
153 + 'dev',
154 + 'auth-configs',
155 + 'info',
156 + 'ac_gmail_default',
157 + ]);
158 +
159 + expect(exitCode).toBe(0);
160 + expect(calls).toEqual([
161 + { method: 'getAuthConfig', scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE) },
162 + ]);
163 + })
164 + );
165 + });
166 +});
ts/packages/cli/test/src/commands/auth-configs/list/auth-configs.list.cmd.test.ts
+99 -18
@@ -3,6 +3,19 @@ import { ConfigProvider, Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
5 import type { AuthConfigItem } from 'src/models/auth-configs';
6 +import type { MockAccountRequest } from 'test/__utils__/layers/accounts';
7 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
8 +import {
9 + DEFAULT_PROJECT_SCOPE,
10 + defaultDeveloperProjectAccountData,
11 + DIRECTORY_PROJECT_SCOPE,
12 + inDeveloperProjectDirectory,
13 + loginWithoutDeveloperProject,
14 + NO_DIRECTORY_PROJECT_NOTICE,
15 + OTHER_DEVELOPER_PROJECT,
16 + OTHER_PROJECT_SCOPE,
17 + runRecordingRepositoryScopes,
18 +} from 'test/__utils__/layers/developer-project';
19
20 const testAuthConfigs: AuthConfigItem[] = [
21 {
@@ -54,8 +67,11 @@ const testConfigProvider = ConfigProvider.fromEnv({
67 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
68 });
69
70 +// Logged in, in a directory set up for a developer project.
71 +const inProject = { ...inDeveloperProjectDirectory, baseConfigProvider: testConfigProvider };
72 +
73 describe('CLI: composio dev auth-configs list', () => {
58 - layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
74 + layer(TestLive({ ...inProject, authConfigsData }))(
75 '[Given] no flags [Then] lists all auth configs',
76 it => {
77 it.effect('lists all auth configs with table', () =>
@@ -73,7 +89,7 @@ describe('CLI: composio dev auth-configs list', () => {
89 }
90 );
91
76 - layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
92 + layer(TestLive({ ...inProject, authConfigsData }))(
93 '[Given] --toolkits "gmail" [Then] lists only gmail auth configs',
94 it => {
95 it.effect('filters by toolkit', () =>
@@ -91,7 +107,7 @@ describe('CLI: composio dev auth-configs list', () => {
107 }
108 );
109
94 - layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
110 + layer(TestLive({ ...inProject, authConfigsData }))(
111 '[Given] --query "Custom" [Then] shows filtered results',
112 it => {
113 it.effect('filters by name search', () =>
@@ -107,7 +123,7 @@ describe('CLI: composio dev auth-configs list', () => {
123 }
124 );
125
110 - layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
126 + layer(TestLive({ ...inProject, authConfigsData }))(
127 '[Given] --limit 1 [Then] respects limit',
128 it => {
129 it.effect('respects limit', () =>
@@ -131,22 +147,19 @@ describe('CLI: composio dev auth-configs list', () => {
147 );
148 });
149
134 - layer(TestLive({ baseConfigProvider: testConfigProvider }))(
135 - '[Given] empty results [Then] shows no auth configs found',
136 - it => {
137 - it.effect('shows no auth configs found', () =>
138 - Effect.gen(function* () {
139 - yield* cli(['dev', 'auth-configs', 'list']);
140 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
141 - const output = lines.join('\n');
150 + layer(TestLive(inProject))('[Given] empty results [Then] shows no auth configs found', it => {
151 + it.effect('shows no auth configs found', () =>
152 + Effect.gen(function* () {
153 + yield* cli(['dev', 'auth-configs', 'list']);
154 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
155 + const output = lines.join('\n');
156
143 - expect(output).toContain('No auth configs found');
144 - })
145 - );
146 - }
147 - );
157 + expect(output).toContain('No auth configs found');
158 + })
159 + );
160 + });
161
149 - layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
162 + layer(TestLive({ ...inProject, authConfigsData }))(
163 '[Given] --toolkits "nonexistent" [Then] shows hint about toolkit slug',
164 it => {
165 it.effect('shows toolkit hint', () =>
@@ -162,3 +175,71 @@ describe('CLI: composio dev auth-configs list', () => {
175 }
176 );
177 });
178 +
179 +// The request goes to the developer project the command resolved, never to the one the backend
180 +// would pick for the key.
181 +describe('CLI: composio dev auth-configs list acts on the developer project', () => {
182 + layer(TestLive({ ...inProject, authConfigsData }))(it => {
183 + it.effect.each([
184 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
185 + {
186 + given: '--project-name',
187 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
188 + scope: OTHER_PROJECT_SCOPE,
189 + },
190 + ])('[Given] $given [Then] lists that project’s auth configs', ({ args, scope }) =>
191 + Effect.gen(function* () {
192 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
193 + ...['dev', 'auth-configs', 'list'],
194 + ...args,
195 + ]);
196 +
197 + expect(exitCode).toBe(0);
198 + expect(calls).toEqual([
199 + { method: 'listAuthConfigs', scope: expect.objectContaining(scope) },
200 + ]);
201 + })
202 + );
203 + });
204 +
205 + // Before the command named a project, the backend answered from its default developer project;
206 + // a directory without a usable project of its own still gets that one, named on stderr.
207 + const sessionRequests: Array<MockAccountRequest> = [];
208 + layer(
209 + TestLive({
210 + baseConfigProvider: testConfigProvider,
211 + authConfigsData,
212 + accountData: defaultDeveloperProjectAccountData(sessionRequests),
213 + })
214 + )(it => {
215 + it.effect(
216 + '[Given] a directory set up for no project [Then] lists the default developer project’s auth configs, saying so on stderr',
217 + () =>
218 + Effect.gen(function* () {
219 + yield* loginWithoutDeveloperProject;
220 + sessionRequests.length = 0;
221 + // Redirected streams, as under a script: only plain stderr lines and stdout data show.
222 + const terminal = redirectedTerminalUI();
223 + const { exitCode, calls } = yield* runRecordingRepositoryScopes(
224 + ['dev', 'auth-configs', 'list'],
225 + terminal.layer
226 + );
227 +
228 + expect(exitCode).toBe(0);
229 + expect(terminal.stderr()).toBe(`${NO_DIRECTORY_PROJECT_NOTICE}\n`);
230 + expect(JSON.parse(terminal.stdout()).map((item: { id: string }) => item.id)).toEqual(
231 + testAuthConfigs.map(item => item.id)
232 + );
233 + // One session-info read in the logged-in org picks the project every request names.
234 + expect(
235 + sessionRequests.filter(({ operation }) => operation === 'auth.session.retrieveInfo')
236 + ).toEqual([
237 + expect.objectContaining({ scope: expect.objectContaining({ orgId: 'org_test' }) }),
238 + ]);
239 + expect(calls).toEqual([
240 + { method: 'listAuthConfigs', scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE) },
241 + ]);
242 + })
243 + );
244 + });
245 +});
ts/packages/cli/test/src/commands/auth-configs/list/auth-configs.list.handler.test.ts
+1 -1
@@ -66,7 +66,7 @@ describe('runAuthConfigsList', () => {
66 const limits: Array<number | undefined> = [];
67 const { layer } = AuthConfigsHandlerTest({
68 repository: {
69 - listAuthConfigs: params =>
69 + listAuthConfigs: (_scope, params) =>
70 Effect.sync(() => {
71 limits.push(params.limit);
72 return {
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.cmd.test.ts
+73 -3
@@ -5,6 +5,16 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8 +import {
9 + DIRECTORY_PROJECT_SCOPE,
10 + DEFAULT_PROJECT_SCOPE,
11 + defaultDeveloperProjectAccountData,
12 + inDeveloperProjectDirectory,
13 + loginWithoutDeveloperProject,
14 + OTHER_DEVELOPER_PROJECT,
15 + OTHER_PROJECT_SCOPE,
16 + runRecordingRepositoryScopes,
17 +} from 'test/__utils__/layers/developer-project';
18
19 const testConnectedAccounts: ConnectedAccountItem[] = [
20 {
@@ -34,8 +44,11 @@ const testConfigProvider = ConfigProvider.fromEnv({
44 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
45 });
46
47 +// Logged in, in a directory set up for a developer project.
48 +const inProject = { ...inDeveloperProjectDirectory, baseConfigProvider: testConfigProvider };
49 +
50 describe('CLI: composio dev connected-accounts info', () => {
38 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
51 + layer(TestLive({ ...inProject, connectedAccountsData }))(
52 '[Given] valid ID [Then] shows connected account info',
53 it => {
54 it.effect('displays info for existing account', () =>
@@ -53,7 +66,7 @@ describe('CLI: composio dev connected-accounts info', () => {
66 }
67 );
68
56 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
69 + layer(TestLive({ ...inProject, connectedAccountsData }))(
70 '[Given] nonexistent ID [Then] shows error with hint',
71 it => {
72 it.effect('shows error for nonexistent account', () =>
@@ -72,7 +85,7 @@ describe('CLI: composio dev connected-accounts info', () => {
85 }
86 );
87
75 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
88 + layer(TestLive({ ...inProject, connectedAccountsData }))(
89 '[Given] no ID argument [Then] fails with a usage error',
90 it => {
91 it.effect('raises a CommandInputError naming <id>', () =>
@@ -105,3 +118,60 @@ describe('CLI: composio dev connected-accounts info', () => {
118 );
119 });
120 });
121 +
122 +// The request goes to the developer project the command resolved, never to the one the backend
123 +// would pick for the key.
124 +describe('CLI: composio dev connected-accounts info acts on the developer project', () => {
125 + layer(TestLive({ ...inProject, connectedAccountsData }))(it => {
126 + it.effect.each([
127 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
128 + {
129 + given: '--project-name',
130 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
131 + scope: OTHER_PROJECT_SCOPE,
132 + },
133 + ])('[Given] $given [Then] reads the account from that project', ({ args, scope }) =>
134 + Effect.gen(function* () {
135 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
136 + ...['dev', 'connected-accounts', 'info', 'con_gmail_active'],
137 + ...args,
138 + ]);
139 +
140 + expect(exitCode).toBe(0);
141 + expect(calls).toEqual([
142 + { method: 'getConnectedAccount', scope: expect.objectContaining(scope) },
143 + ]);
144 + })
145 + );
146 + });
147 +
148 + layer(
149 + TestLive({
150 + baseConfigProvider: testConfigProvider,
151 + connectedAccountsData,
152 + accountData: defaultDeveloperProjectAccountData(),
153 + })
154 + )(it => {
155 + it.effect(
156 + '[Given] a directory set up for no project [Then] acts on the default developer project',
157 + () =>
158 + Effect.gen(function* () {
159 + yield* loginWithoutDeveloperProject;
160 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
161 + 'dev',
162 + 'connected-accounts',
163 + 'info',
164 + 'con_gmail_active',
165 + ]);
166 +
167 + expect(exitCode).toBe(0);
168 + expect(calls).toEqual([
169 + {
170 + method: 'getConnectedAccount',
171 + scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE),
172 + },
173 + ]);
174 + })
175 + );
176 + });
177 +});
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.handler.test.ts
+2
@@ -8,6 +8,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
8 import { redact } from 'src/ui/redact';
9 import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
10 import { exitCodeOf } from 'test/__utils__/exit-code';
11 +import { DirectoryProjectTest } from 'test/__utils__/layers/developer-project';
12 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
13
14 const EXPIRED_ACCOUNT: ConnectedAccountItem = {
@@ -38,6 +39,7 @@ const infoTest = (items: ReadonlyArray<ConnectedAccountItem> = [EXPIRED_ACCOUNT]
39 const outputs: Array<string> = [];
40 const layer = Layer.mergeAll(
41 Layer.effect(Console.Console, MockConsole.make),
42 + DirectoryProjectTest,
43 Layer.succeed(
44 TerminalUI,
45 TerminalUI.of({
ts/packages/cli/test/src/commands/connected-accounts/list/connected-accounts.list.cmd.test.ts
+19 -12
@@ -66,7 +66,7 @@ const connectedAccountsData = {
66 const testDevConfigProvider = ConfigProvider.fromEnv({
67 env: {
68 COMPOSIO_USER_API_KEY: 'test_api_key',
69 - COMPOSIO_ORG_ID: 'dev_org_test',
69 + COMPOSIO_ORG_ID: 'org_test',
70 COMPOSIO_PROJECT_ID: 'dev_project_test',
71 },
72 });
@@ -168,17 +168,24 @@ describe('CLI: composio dev connected-accounts list', () => {
168 }
169 );
170
171 - layer(TestLive({ baseConfigProvider: testDevConfigProvider }))(
172 - '[Given] no org in user context [Then] warns user to login',
173 - it => {
174 - it.effect('warns user to login', () =>
175 - Effect.gen(function* () {
176 - const error = yield* Effect.flip(cli(['dev', 'connected-accounts', 'list']));
177 - expect(String(error)).toContain('No current org configured');
178 - })
179 - );
180 - }
181 - );
171 + // A key from `COMPOSIO_USER_API_KEY` stores no org; the directory's project names its own.
172 + layer(
173 + TestLive({
174 + baseConfigProvider: testDevConfigProvider,
175 + connectedAccountsData,
176 + // The directory's org is checked against the key's orgs.
177 + accountData: { organizations: [{ id: 'org_test', name: 'Test Org' }] },
178 + })
179 + )('[Given] no stored org [Then] lists the accounts of the directory project', it => {
180 + it.effect('lists the accounts of the directory project', () =>
181 + Effect.gen(function* () {
182 + yield* cli(['dev', 'connected-accounts', 'list']);
183 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
184 + expect(output).not.toContain('No current org configured');
185 + expect(output).toContain('Listing 3 of 3 connected accounts');
186 + })
187 + );
188 + });
189
190 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
191 it.effect('warns user to login', () =>
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.cmd.test.ts
+74 -4
@@ -5,6 +5,16 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8 +import {
9 + DIRECTORY_PROJECT_SCOPE,
10 + DEFAULT_PROJECT_SCOPE,
11 + defaultDeveloperProjectAccountData,
12 + inDeveloperProjectDirectory,
13 + loginWithoutDeveloperProject,
14 + OTHER_DEVELOPER_PROJECT,
15 + OTHER_PROJECT_SCOPE,
16 + runRecordingRepositoryScopes,
17 +} from 'test/__utils__/layers/developer-project';
18
19 const testConnectedAccounts: ConnectedAccountItem[] = [
20 {
@@ -51,8 +61,11 @@ const testConfigProvider = ConfigProvider.fromEnv({
61 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
62 });
63
64 +// Logged in, in a directory set up for a developer project.
65 +const inProject = { ...inDeveloperProjectDirectory, baseConfigProvider: testConfigProvider };
66 +
67 describe('CLI: composio dev connected-accounts whoami', () => {
55 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
68 + layer(TestLive({ ...inProject, connectedAccountsData }))(
69 '[Given] active connection [Then] shows account details',
70 it => {
71 it.effect('displays whoami for active connection', () =>
@@ -70,7 +83,7 @@ describe('CLI: composio dev connected-accounts whoami', () => {
83 }
84 );
85
73 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
86 + layer(TestLive({ ...inProject, connectedAccountsData }))(
87 '[Given] expired connection [Then] shows details with status warning',
88 it => {
89 it.effect('shows warning for non-ACTIVE connection', () =>
@@ -87,7 +100,7 @@ describe('CLI: composio dev connected-accounts whoami', () => {
100 }
101 );
102
90 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
103 + layer(TestLive({ ...inProject, connectedAccountsData }))(
104 '[Given] nonexistent ID [Then] shows error with hint',
105 it => {
106 it.effect('shows error for nonexistent account', () =>
@@ -106,7 +119,7 @@ describe('CLI: composio dev connected-accounts whoami', () => {
119 }
120 );
121
109 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
122 + layer(TestLive({ ...inProject, connectedAccountsData }))(
123 '[Given] no ID argument [Then] fails with a usage error',
124 it => {
125 it.effect('raises a CommandInputError naming <id>', () =>
@@ -139,3 +152,60 @@ describe('CLI: composio dev connected-accounts whoami', () => {
152 );
153 });
154 });
155 +
156 +// The request goes to the developer project the command resolved, never to the one the backend
157 +// would pick for the key.
158 +describe('CLI: composio dev connected-accounts whoami acts on the developer project', () => {
159 + layer(TestLive({ ...inProject, connectedAccountsData }))(it => {
160 + it.effect.each([
161 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
162 + {
163 + given: '--project-name',
164 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
165 + scope: OTHER_PROJECT_SCOPE,
166 + },
167 + ])('[Given] $given [Then] reads the account from that project', ({ args, scope }) =>
168 + Effect.gen(function* () {
169 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
170 + ...['dev', 'connected-accounts', 'whoami', 'con_gmail_active'],
171 + ...args,
172 + ]);
173 +
174 + expect(exitCode).toBe(0);
175 + expect(calls).toEqual([
176 + { method: 'getConnectedAccount', scope: expect.objectContaining(scope) },
177 + ]);
178 + })
179 + );
180 + });
181 +
182 + layer(
183 + TestLive({
184 + baseConfigProvider: testConfigProvider,
185 + connectedAccountsData,
186 + accountData: defaultDeveloperProjectAccountData(),
187 + })
188 + )(it => {
189 + it.effect(
190 + '[Given] a directory set up for no project [Then] acts on the default developer project',
191 + () =>
192 + Effect.gen(function* () {
193 + yield* loginWithoutDeveloperProject;
194 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
195 + 'dev',
196 + 'connected-accounts',
197 + 'whoami',
198 + 'con_gmail_active',
199 + ]);
200 +
201 + expect(exitCode).toBe(0);
202 + expect(calls).toEqual([
203 + {
204 + method: 'getConnectedAccount',
205 + scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE),
206 + },
207 + ]);
208 + })
209 + );
210 + });
211 +});
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.test.ts
+2
@@ -8,6 +8,7 @@ import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
10 import { exitCodeOf } from 'test/__utils__/exit-code';
11 +import { DirectoryProjectTest } from 'test/__utils__/layers/developer-project';
12 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
13
14 const account = (overrides: Partial<ConnectedAccountItem> = {}): ConnectedAccountItem => ({
@@ -42,6 +43,7 @@ const whoamiTest = () => {
43 const outputs: Array<string> = [];
44 const layer = Layer.mergeAll(
45 Layer.effect(Console.Console, MockConsole.make),
46 + DirectoryProjectTest,
47 Layer.succeed(
48 TerminalUI,
49 TerminalUI.of({
ts/packages/cli/test/src/commands/logs/tools/logs.tools.cmd.test.ts
+47 -1
@@ -1,7 +1,16 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { TestClock } from 'effect/testing';
4 -import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import { cli, cliExit, MockConsole, TestLive } from 'test/__utils__';
5 +import {
6 + DIRECTORY_PROJECT_SCOPE,
7 + DEFAULT_PROJECT_SCOPE,
8 + defaultDeveloperProjectAccountData,
9 + inDeveloperProjectDirectory,
10 + loginWithoutDeveloperProject,
11 + OTHER_DEVELOPER_PROJECT,
12 + OTHER_PROJECT_SCOPE,
13 +} from 'test/__utils__/layers/developer-project';
14 import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
15 import { log } from './logs.tools.fixtures';
16
@@ -178,3 +187,40 @@ describe('CLI: composio dev logs tools', () => {
187 );
188 });
189 });
190 +
191 +// The request goes to the developer project the command resolved, never to the one the backend
192 +// would pick for the key.
193 +describe('CLI: composio dev logs tools acts on the developer project', () => {
194 + const config = ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } });
195 +
196 + layer(TestLive({ ...inDeveloperProjectDirectory, baseConfigProvider: config }))(it => {
197 + it.effect.each([
198 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
199 + {
200 + given: '--project-name',
201 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
202 + scope: OTHER_PROJECT_SCOPE,
203 + },
204 + ])('[Given] $given [Then] reads the logs of that project', ({ args, scope }) =>
205 + Effect.gen(function* () {
206 + const stub = stubClientResources(['logs'], () => Response.json({ logs: [], next_cursor: null }));
207 + yield* cli([...['dev', 'logs', 'tools'], ...args]).pipe(Effect.provide(stub.layer));
208 +
209 + expect(stub.scopes).toEqual([scope]);
210 + })
211 + );
212 + });
213 +
214 + layer(TestLive({ baseConfigProvider: config, accountData: defaultDeveloperProjectAccountData() }))(it => {
215 + it.effect('[Given] a directory set up for no project [Then] reads the logs of the default developer project', () =>
216 + Effect.gen(function* () {
217 + yield* loginWithoutDeveloperProject;
218 + const stub = stubClientResources(['logs'], () => Response.json({ logs: [], next_cursor: null }));
219 + const { exitCode } = yield* cliExit(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
220 +
221 + expect(exitCode).toBe(0);
222 + expect(stub.scopes).toEqual([DEFAULT_PROJECT_SCOPE]);
223 + })
224 + );
225 + });
226 +});
ts/packages/cli/test/src/commands/logs/triggers/logs.triggers.cmd.test.ts
+48 -1
@@ -1,6 +1,15 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 -import { cli, MockConsole, TestLive } from 'test/__utils__';
3 +import { cli, cliExit, MockConsole, TestLive } from 'test/__utils__';
4 +import {
5 + DIRECTORY_PROJECT_SCOPE,
6 + DEFAULT_PROJECT_SCOPE,
7 + defaultDeveloperProjectAccountData,
8 + inDeveloperProjectDirectory,
9 + loginWithoutDeveloperProject,
10 + OTHER_DEVELOPER_PROJECT,
11 + OTHER_PROJECT_SCOPE,
12 +} from 'test/__utils__/layers/developer-project';
13 import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
14
15 const testLayer = TestLive({
@@ -186,3 +195,41 @@ describe('CLI: composio dev logs triggers', () => {
195 );
196 });
197 });
198 +
199 +// The request goes to the developer project the command resolved, never to the one the backend
200 +// would pick for the key.
201 +describe('CLI: composio dev logs triggers acts on the developer project', () => {
202 + const config = ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } });
203 +
204 + layer(TestLive({ ...inDeveloperProjectDirectory, baseConfigProvider: config }))(it => {
205 + it.effect.each([
206 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
207 + {
208 + given: '--project-name',
209 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
210 + scope: OTHER_PROJECT_SCOPE,
211 + },
212 + { given: 'a log id', args: ['log_1'], scope: DIRECTORY_PROJECT_SCOPE },
213 + ])('[Given] $given [Then] reads the logs of that project', ({ args, scope }) =>
214 + Effect.gen(function* () {
215 + const stub = stubClientResources(['_internal'], request => Response.json(request.method === 'GET' ? log : { data: [] }));
216 + yield* cli([...['dev', 'logs', 'triggers'], ...args]).pipe(Effect.provide(stub.layer));
217 +
218 + expect(stub.scopes).toEqual([scope]);
219 + })
220 + );
221 + });
222 +
223 + layer(TestLive({ baseConfigProvider: config, accountData: defaultDeveloperProjectAccountData() }))(it => {
224 + it.effect('[Given] a directory set up for no project [Then] reads the logs of the default developer project', () =>
225 + Effect.gen(function* () {
226 + yield* loginWithoutDeveloperProject;
227 + const stub = stubClientResources(['_internal'], request => Response.json(request.method === 'GET' ? log : { data: [] }));
228 + const { exitCode } = yield* cliExit(['dev', 'logs', 'triggers']).pipe(Effect.provide(stub.layer));
229 +
230 + expect(exitCode).toBe(0);
231 + expect(stub.scopes).toEqual([DEFAULT_PROJECT_SCOPE]);
232 + })
233 + );
234 + });
235 +});
ts/packages/cli/test/src/commands/surface.test.ts
+14 -23
@@ -98,7 +98,7 @@ describe('CommandSurface: the dev group shares --user-id and --project-name', ()
98 baseConfigProvider: ConfigProvider.fromEnv({
99 env: {
100 COMPOSIO_USER_API_KEY: 'test_api_key',
101 - COMPOSIO_ORG_ID: 'dev_org_test',
101 + COMPOSIO_ORG_ID: 'org_test',
102 COMPOSIO_PROJECT_ID: 'dev_project_test',
103 },
104 }),
@@ -251,7 +251,7 @@ describe('CommandSurface: playground-execute --parallel keeps the shared flags',
251 baseConfigProvider: ConfigProvider.fromEnv({
252 env: {
253 COMPOSIO_USER_API_KEY: 'test_api_key',
254 - COMPOSIO_ORG_ID: 'dev_org_test',
254 + COMPOSIO_ORG_ID: 'org_test',
255 COMPOSIO_PROJECT_ID: 'dev_project_test',
256 },
257 }),
@@ -311,7 +311,7 @@ describe('CommandSurface: playground-execute --parallel finds its command name',
311 baseConfigProvider: ConfigProvider.fromEnv({
312 env: {
313 COMPOSIO_USER_API_KEY: 'test_api_key',
314 - COMPOSIO_ORG_ID: 'dev_org_test',
314 + COMPOSIO_ORG_ID: 'org_test',
315 COMPOSIO_PROJECT_ID: 'dev_project_test',
316 },
317 }),
@@ -350,37 +350,28 @@ describe('CommandSurface: playground-execute --parallel finds its command name',
350 });
351 });
352
353 -// `dev logs tools|triggers` honor --user-id as their filter and reject only --project-name.
354 -// `dev logs`, `dev auth-configs` and `dev projects` declare the flags unsupported for every
355 -// command under them; the message still names the command that ran.
353 +// Commands that act on no project or for no user reject the shared flag they cannot honor.
354 +// `dev init` and `dev projects` declare both unsupported for every command under them, and
355 +// `dev auth-configs` declares --user-id so; the message still names the command that ran.
356 const rejectingCommands = [
357 { command: ['init'], args: [], flags: ['--project-name', '--user-id'] },
358 - { command: ['logs', 'tools'], args: [], flags: ['--project-name'] },
359 - { command: ['logs', 'triggers'], args: [], flags: ['--project-name'] },
360 - { command: ['auth-configs', 'list'], args: [], flags: ['--project-name', '--user-id'] },
358 + { command: ['auth-configs', 'list'], args: [], flags: ['--user-id'] },
359 + { command: ['auth-configs', 'info'], args: ['ac_1'], flags: ['--user-id'] },
360 + { command: ['auth-configs', 'create'], args: ['--toolkit', 'gmail'], flags: ['--user-id'] },
361 { command: ['projects', 'list'], args: [], flags: ['--project-name', '--user-id'] },
362 { command: ['toolkits', 'search'], args: ['email'], flags: ['--project-name', '--user-id'] },
363 { command: ['toolkits', 'version'], args: ['gmail'], flags: ['--project-name', '--user-id'] },
364 - {
365 - command: ['connected-accounts', 'info'],
366 - args: ['ca_1'],
367 - flags: ['--project-name', '--user-id'],
368 - },
369 - {
370 - command: ['connected-accounts', 'whoami'],
371 - args: ['ca_1'],
372 - flags: ['--project-name', '--user-id'],
373 - },
364 + { command: ['connected-accounts', 'info'], args: ['ca_1'], flags: ['--user-id'] },
365 + { command: ['connected-accounts', 'whoami'], args: ['ca_1'], flags: ['--user-id'] },
366 { command: ['triggers', 'list'], args: ['gmail'], flags: ['--project-name', '--user-id'] },
367 {
368 command: ['triggers', 'info'],
369 args: ['GMAIL_NEW_GMAIL_MESSAGE'],
370 flags: ['--project-name', '--user-id'],
371 },
380 - { command: ['triggers', 'status'], args: [], flags: ['--project-name', '--user-id'] },
381 - { command: ['triggers', 'create'], args: ['GMAIL_NEW_GMAIL_MESSAGE'], flags: ['--project-name'] },
382 - { command: ['triggers', 'enable'], args: ['ti_1'], flags: ['--project-name', '--user-id'] },
383 - { command: ['triggers', 'disable'], args: ['ti_1'], flags: ['--project-name', '--user-id'] },
372 + { command: ['triggers', 'status'], args: [], flags: ['--user-id'] },
373 + { command: ['triggers', 'enable'], args: ['ti_1'], flags: ['--user-id'] },
374 + { command: ['triggers', 'disable'], args: ['ti_1'], flags: ['--user-id'] },
375 ].flatMap(({ command, args, flags }) =>
376 flags.flatMap(flag =>
377 (['before', 'after'] as const).map(position => {
ts/packages/cli/test/src/commands/triggers/create/triggers.create.cmd.test.ts
+77 -4
@@ -10,16 +10,28 @@ import { cli, MockConsole, TestLive } from 'test/__utils__';
10 import { notFoundError } from 'test/__utils__/layers/not-found';
11 import { exitCodeOf } from 'test/__utils__/exit-code';
12 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
13 +import {
14 + DIRECTORY_PROJECT_SCOPE,
15 + DEFAULT_PROJECT_SCOPE,
16 + defaultDeveloperProjectAccountData,
17 + inDeveloperProjectDirectory,
18 + loginWithoutDeveloperProject,
19 + OTHER_DEVELOPER_PROJECT,
20 + OTHER_PROJECT_SCOPE,
21 + runRecordingRepositoryScopes,
22 +} from 'test/__utils__/layers/developer-project';
23
24 const testConfigProvider = ConfigProvider.fromEnv({
25 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
26 });
27
18 -const dangerousDevConfig = {
28 +const devConfigWithoutProject = {
29 baseConfigProvider: testConfigProvider,
30 cliUserConfig: { developerDangerousCommandsEnabled: true },
31 } as const;
32
33 +const dangerousDevConfig = { ...inDeveloperProjectDirectory, ...devConfigWithoutProject } as const;
34 +
35 const createArgs = [
36 'triggers',
37 'create',
@@ -95,7 +107,7 @@ describe('CLI: composio dev triggers create', () => {
107 const repository = Layer.succeed(
108 ComposioToolkitsRepository,
109 makeToolkitsRepositoryStub({
98 - createTrigger: (slug, params) =>
110 + createTrigger: (_scope, slug, params) =>
111 Effect.sync(() => {
112 calls.push({ slug, params });
113 return {
@@ -179,7 +191,7 @@ describe('CLI: composio dev triggers create', () => {
191 const repository = Layer.succeed(
192 ComposioToolkitsRepository,
193 makeToolkitsRepositoryStub({
182 - createTrigger: (slug, params) =>
194 + createTrigger: (_scope, slug, params) =>
195 Effect.sync(() => {
196 calls.push({ slug, params });
197 return {
@@ -205,7 +217,11 @@ describe('CLI: composio dev triggers create', () => {
217 expect(calls).toEqual([
218 {
219 slug: 'GMAIL_NEW_GMAIL_MESSAGE',
208 - params: { connected_account_id: 'con_123', trigger_config: { labelIds: 'INBOX' } },
220 + params: {
221 + connected_account_id: 'con_123',
222 + trigger_config: { labelIds: 'INBOX' },
223 + user_id: 'global-default',
224 + },
225 },
226 ]);
227 })
@@ -293,3 +309,60 @@ describe('CLI: composio dev triggers create', () => {
309 }
310 );
311 });
312 +
313 +// The request goes to the developer project the command resolved, never to the one the backend
314 +// would pick for the key.
315 +describe('CLI: composio dev triggers create acts on the developer project', () => {
316 + layer(TestLive(dangerousDevConfig))(it => {
317 + it.effect.each([
318 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
319 + {
320 + given: '--project-name',
321 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
322 + scope: OTHER_PROJECT_SCOPE,
323 + },
324 + ])('[Given] $given [Then] creates the trigger in that project', ({ args, scope }) =>
325 + Effect.gen(function* () {
326 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
327 + ...[
328 + 'dev',
329 + 'triggers',
330 + 'create',
331 + 'GMAIL_NEW_GMAIL_MESSAGE',
332 + '--connected-account-id',
333 + 'con_123',
334 + ],
335 + ...args,
336 + ]);
337 +
338 + expect(exitCode).toBe(0);
339 + expect(calls).toEqual([{ method: 'createTrigger', scope: expect.objectContaining(scope) }]);
340 + })
341 + );
342 + });
343 +
344 + layer(
345 + TestLive({ ...devConfigWithoutProject, accountData: defaultDeveloperProjectAccountData() })
346 + )(it => {
347 + it.effect(
348 + '[Given] a directory set up for no project [Then] acts on the default developer project',
349 + () =>
350 + Effect.gen(function* () {
351 + yield* loginWithoutDeveloperProject;
352 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
353 + 'dev',
354 + 'triggers',
355 + 'create',
356 + 'GMAIL_NEW_GMAIL_MESSAGE',
357 + '--connected-account-id',
358 + 'con_123',
359 + ]);
360 +
361 + expect(exitCode).toBe(0);
362 + expect(calls).toEqual([
363 + { method: 'createTrigger', scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE) },
364 + ]);
365 + })
366 + );
367 + });
368 +});
ts/packages/cli/test/src/commands/triggers/disable/triggers.disable.cmd.test.ts
+65 -2
@@ -6,16 +6,28 @@ import { cli, MockConsole, TestLive } from 'test/__utils__';
6 import { notFoundError } from 'test/__utils__/layers/not-found';
7 import { exitCodeOf } from 'test/__utils__/exit-code';
8 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
9 +import {
10 + DIRECTORY_PROJECT_SCOPE,
11 + DEFAULT_PROJECT_SCOPE,
12 + defaultDeveloperProjectAccountData,
13 + inDeveloperProjectDirectory,
14 + loginWithoutDeveloperProject,
15 + OTHER_DEVELOPER_PROJECT,
16 + OTHER_PROJECT_SCOPE,
17 + runRecordingRepositoryScopes,
18 +} from 'test/__utils__/layers/developer-project';
19
20 const testConfigProvider = ConfigProvider.fromEnv({
21 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
22 });
23
14 -const dangerousDevConfig = {
24 +const devConfigWithoutProject = {
25 baseConfigProvider: testConfigProvider,
26 cliUserConfig: { developerDangerousCommandsEnabled: true },
27 } as const;
28
29 +const dangerousDevConfig = { ...inDeveloperProjectDirectory, ...devConfigWithoutProject } as const;
30 +
31 describe('CLI: composio dev triggers disable', () => {
32 layer(TestLive(dangerousDevConfig))('[Given] disable with ID [Then] disables trigger', it => {
33 it.effect('disables trigger successfully', () =>
@@ -70,7 +82,7 @@ describe('CLI: composio dev triggers disable', () => {
82 }
83 );
84
73 - layer(TestLive({ baseConfigProvider: testConfigProvider }))(
85 + layer(TestLive({ ...inDeveloperProjectDirectory, baseConfigProvider: testConfigProvider }))(
86 '[Given] destructive dev commands disabled by config [Then] fails before the flag check',
87 it => {
88 it.effect('raises a CommandInputError naming the config setting', () =>
@@ -119,3 +131,54 @@ describe('CLI: composio dev triggers disable', () => {
131 }
132 );
133 });
134 +
135 +// The request goes to the developer project the command resolved, never to the one the backend
136 +// would pick for the key.
137 +describe('CLI: composio dev triggers disable acts on the developer project', () => {
138 + layer(TestLive(dangerousDevConfig))(it => {
139 + it.effect.each([
140 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
141 + {
142 + given: '--project-name',
143 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
144 + scope: OTHER_PROJECT_SCOPE,
145 + },
146 + ])('[Given] $given [Then] disables the trigger in that project', ({ args, scope }) =>
147 + Effect.gen(function* () {
148 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
149 + ...['dev', 'triggers', 'disable', 'trg_123', '--dangerously-allow'],
150 + ...args,
151 + ]);
152 +
153 + expect(exitCode).toBe(0);
154 + expect(calls).toEqual([
155 + { method: 'disableTrigger', scope: expect.objectContaining(scope) },
156 + ]);
157 + })
158 + );
159 + });
160 +
161 + layer(
162 + TestLive({ ...devConfigWithoutProject, accountData: defaultDeveloperProjectAccountData() })
163 + )(it => {
164 + it.effect(
165 + '[Given] a directory set up for no project [Then] acts on the default developer project',
166 + () =>
167 + Effect.gen(function* () {
168 + yield* loginWithoutDeveloperProject;
169 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
170 + 'dev',
171 + 'triggers',
172 + 'disable',
173 + 'trg_123',
174 + '--dangerously-allow',
175 + ]);
176 +
177 + expect(exitCode).toBe(0);
178 + expect(calls).toEqual([
179 + { method: 'disableTrigger', scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE) },
180 + ]);
181 + })
182 + );
183 + });
184 +});
ts/packages/cli/test/src/commands/triggers/enable/triggers.enable.cmd.test.ts
+61 -1
@@ -6,16 +6,28 @@ import { cli, MockConsole, TestLive } from 'test/__utils__';
6 import { notFoundError } from 'test/__utils__/layers/not-found';
7 import { exitCodeOf } from 'test/__utils__/exit-code';
8 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
9 +import {
10 + DIRECTORY_PROJECT_SCOPE,
11 + DEFAULT_PROJECT_SCOPE,
12 + defaultDeveloperProjectAccountData,
13 + inDeveloperProjectDirectory,
14 + loginWithoutDeveloperProject,
15 + OTHER_DEVELOPER_PROJECT,
16 + OTHER_PROJECT_SCOPE,
17 + runRecordingRepositoryScopes,
18 +} from 'test/__utils__/layers/developer-project';
19
20 const testConfigProvider = ConfigProvider.fromEnv({
21 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
22 });
23
14 -const dangerousDevConfig = {
24 +const devConfigWithoutProject = {
25 baseConfigProvider: testConfigProvider,
26 cliUserConfig: { developerDangerousCommandsEnabled: true },
27 } as const;
28
29 +const dangerousDevConfig = { ...inDeveloperProjectDirectory, ...devConfigWithoutProject } as const;
30 +
31 describe('CLI: composio dev triggers enable', () => {
32 layer(TestLive(dangerousDevConfig))('[Given] enable with ID [Then] enables trigger', it => {
33 it.effect('enables trigger successfully', () =>
@@ -84,3 +96,51 @@ describe('CLI: composio dev triggers enable', () => {
96 }
97 );
98 });
99 +
100 +// The request goes to the developer project the command resolved, never to the one the backend
101 +// would pick for the key.
102 +describe('CLI: composio dev triggers enable acts on the developer project', () => {
103 + layer(TestLive(dangerousDevConfig))(it => {
104 + it.effect.each([
105 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
106 + {
107 + given: '--project-name',
108 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
109 + scope: OTHER_PROJECT_SCOPE,
110 + },
111 + ])('[Given] $given [Then] enables the trigger in that project', ({ args, scope }) =>
112 + Effect.gen(function* () {
113 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
114 + ...['dev', 'triggers', 'enable', 'trg_123'],
115 + ...args,
116 + ]);
117 +
118 + expect(exitCode).toBe(0);
119 + expect(calls).toEqual([{ method: 'enableTrigger', scope: expect.objectContaining(scope) }]);
120 + })
121 + );
122 + });
123 +
124 + layer(
125 + TestLive({ ...devConfigWithoutProject, accountData: defaultDeveloperProjectAccountData() })
126 + )(it => {
127 + it.effect(
128 + '[Given] a directory set up for no project [Then] acts on the default developer project',
129 + () =>
130 + Effect.gen(function* () {
131 + yield* loginWithoutDeveloperProject;
132 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
133 + 'dev',
134 + 'triggers',
135 + 'enable',
136 + 'trg_123',
137 + ]);
138 +
139 + expect(exitCode).toBe(0);
140 + expect(calls).toEqual([
141 + { method: 'enableTrigger', scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE) },
142 + ]);
143 + })
144 + );
145 + });
146 +});
ts/packages/cli/test/src/commands/triggers/status/triggers.status.cmd.test.ts
+71 -5
@@ -3,6 +3,16 @@ import { ConfigProvider, Effect } from 'effect';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
4 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
5 import type { TriggerInstanceItem } from 'src/models/triggers';
6 +import {
7 + DIRECTORY_PROJECT_SCOPE,
8 + DEFAULT_PROJECT_SCOPE,
9 + defaultDeveloperProjectAccountData,
10 + inDeveloperProjectDirectory,
11 + loginWithoutDeveloperProject,
12 + OTHER_DEVELOPER_PROJECT,
13 + OTHER_PROJECT_SCOPE,
14 + runRecordingRepositoryScopes,
15 +} from 'test/__utils__/layers/developer-project';
16
17 const testTriggers: TriggerInstanceItem[] = [
18 {
@@ -54,8 +64,11 @@ const testConfigProvider = ConfigProvider.fromEnv({
64 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
65 });
66
67 +// Logged in, in a directory set up for a developer project.
68 +const inProject = { ...inDeveloperProjectDirectory, baseConfigProvider: testConfigProvider };
69 +
70 describe('CLI: composio dev triggers status', () => {
58 - layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
71 + layer(TestLive({ ...inProject, triggersData }))(
72 '[Given] no flags [Then] lists active triggers only',
73 it => {
74 it.effect('lists active trigger instances', () =>
@@ -73,7 +86,7 @@ describe('CLI: composio dev triggers status', () => {
86 }
87 );
88
76 - layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
89 + layer(TestLive({ ...inProject, triggersData }))(
90 '[Given] --show-disabled [Then] includes disabled triggers',
91 it => {
92 it.effect('includes disabled trigger instances', () =>
@@ -90,7 +103,7 @@ describe('CLI: composio dev triggers status', () => {
103 }
104 );
105
93 - layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
106 + layer(TestLive({ ...inProject, triggersData }))(
107 '[Given] --user-ids [Then] filters by user IDs',
108 it => {
109 it.effect('filters by user_ids', () =>
@@ -107,7 +120,7 @@ describe('CLI: composio dev triggers status', () => {
120 }
121 );
122
110 - layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
123 + layer(TestLive({ ...inProject, triggersData }))(
124 '[Given] --trigger-names lowercase [Then] applies case-insensitive filter',
125 it => {
126 it.effect('normalizes trigger names to uppercase', () =>
@@ -124,7 +137,7 @@ describe('CLI: composio dev triggers status', () => {
137 }
138 );
139
127 - layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
140 + layer(TestLive({ ...inProject, triggersData }))(
141 '[Given] --toolkits [Then] filters by toolkit slug',
142 it => {
143 it.effect('filters by toolkit prefix in trigger name', () =>
@@ -150,3 +163,56 @@ describe('CLI: composio dev triggers status', () => {
163 );
164 });
165 });
166 +
167 +// The request goes to the developer project the command resolved, never to the one the backend
168 +// would pick for the key.
169 +describe('CLI: composio dev triggers status acts on the developer project', () => {
170 + layer(TestLive({ ...inProject, triggersData }))(it => {
171 + it.effect.each([
172 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
173 + {
174 + given: '--project-name',
175 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
176 + scope: OTHER_PROJECT_SCOPE,
177 + },
178 + ])('[Given] $given [Then] lists that project’s triggers', ({ args, scope }) =>
179 + Effect.gen(function* () {
180 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
181 + ...['dev', 'triggers', 'status'],
182 + ...args,
183 + ]);
184 +
185 + expect(exitCode).toBe(0);
186 + expect(calls).toEqual([
187 + { method: 'listActiveTriggers', scope: expect.objectContaining(scope) },
188 + ]);
189 + })
190 + );
191 + });
192 +
193 + layer(
194 + TestLive({
195 + baseConfigProvider: testConfigProvider,
196 + triggersData,
197 + accountData: defaultDeveloperProjectAccountData(),
198 + })
199 + )(it => {
200 + it.effect(
201 + '[Given] a directory set up for no project [Then] acts on the default developer project',
202 + () =>
203 + Effect.gen(function* () {
204 + yield* loginWithoutDeveloperProject;
205 + const { exitCode, calls } = yield* runRecordingRepositoryScopes([
206 + 'dev',
207 + 'triggers',
208 + 'status',
209 + ]);
210 +
211 + expect(exitCode).toBe(0);
212 + expect(calls).toEqual([
213 + { method: 'listActiveTriggers', scope: expect.objectContaining(DEFAULT_PROJECT_SCOPE) },
214 + ]);
215 + })
216 + );
217 + });
218 +});
ts/packages/cli/test/src/commands/triggers/status/triggers.status.handler.test.ts
+3 -1
@@ -11,6 +11,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
11 import { MockConsole } from 'test/__utils__';
12 import { notFoundError } from 'test/__utils__/layers/not-found';
13 import { exitCodeOf } from 'test/__utils__/exit-code';
14 +import { DirectoryProjectTest } from 'test/__utils__/layers/developer-project';
15 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
16 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
17
@@ -59,6 +60,7 @@ const triggersStatusTest = (fixture: TriggersStatusFixture = {}) => {
60
61 const layer = Layer.mergeAll(
62 Layer.effect(Console.Console, MockConsole.make),
63 + DirectoryProjectTest,
64 Layer.succeed(
65 TerminalUI,
66 TerminalUI.of({
@@ -72,7 +74,7 @@ const triggersStatusTest = (fixture: TriggersStatusFixture = {}) => {
74 Layer.succeed(
75 ComposioToolkitsRepository,
76 makeToolkitsRepositoryStub({
75 - listActiveTriggers: params =>
77 + listActiveTriggers: (_scope, params) =>
78 Effect.suspend(() => {
79 requests.push(params);
80 return fixture.fails
ts/packages/cli/test/src/services/command-project.test.ts
+193 -4
@@ -6,21 +6,28 @@ 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';
9 +import {
10 + ProjectResolutionError,
11 + resolveCommandProject,
12 + resolveDeveloperProjectOrDefault,
13 +} from 'src/services/command-project';
14 import { ComposioClientSingleton } from 'src/services/composio-clients';
15 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
16 import { ProjectContext } from 'src/services/project-context';
17 import { ComposioUserContext } from 'src/services/user-context';
14 -import { makeOrgProject } from 'test/__utils__/models/account';
18 +import { makeOrgProject, makeSessionInfo } from 'test/__utils__/models/account';
19
20 const BASE_URL = 'https://backend.composio.dev';
21
18 -const userContext = (orgId: Option.Option<string>) =>
22 +const userContext = (
23 + orgId: Option.Option<string>,
24 + apiKey: Option.Option<string> = Option.some('uak_test')
25 +) =>
26 Layer.succeed(
27 ComposioUserContext,
28 ComposioUserContext.of({
29 data: {
23 - apiKey: Option.some('uak_test'),
30 + apiKey,
31 baseURL: BASE_URL,
32 webURL: 'https://app.composio.dev',
33 orgId,
@@ -71,6 +78,23 @@ const projectsPage = (names: ReadonlyArray<string>) =>
78 total_items: names.length,
79 });
80
81 +const localProject = (orgId: string) =>
82 + Layer.succeed(
83 + ProjectContext,
84 + ProjectContext.of({
85 + resolve: Effect.succeed(
86 + Option.some({
87 + orgId,
88 + projectId: 'pr_local',
89 + projectName: Option.some('local-app'),
90 + orgName: Option.none(),
91 + email: Option.none(),
92 + testUserId: Option.none(),
93 + })
94 + ),
95 + })
96 + );
97 +
98 describe('resolveCommandProject', () => {
99 afterEach(() => {
100 vi.restoreAllMocks();
@@ -184,3 +208,168 @@ describe('resolveCommandProject', () => {
208 }).pipe(Effect.provide(testLayer))
209 );
210 });
211 +
212 +// The backend's default developer project, as session info reports it.
213 +const defaultProjectInfo = (orgId: string) =>
214 + jsonResponse(makeSessionInfo({ orgId, projectNanoId: 'pr_newest', projectName: 'Newest App' }));
215 +
216 +const requestOf = (call: ReadonlyArray<unknown> | undefined) => {
217 + const [input, init] = call ?? [];
218 + return {
219 + path: new URL(String(input)).pathname,
220 + headers: new Headers((init as RequestInit | undefined)?.headers),
221 + };
222 +};
223 +
224 +const SESSION_INFO_PATH = '/api/v3.1/auth/session/info';
225 +
226 +describe('resolveDeveloperProjectOrDefault', () => {
227 + afterEach(() => {
228 + vi.restoreAllMocks();
229 + });
230 +
231 + it.effect('uses the directory project, with no notice and no request, when it is usable', () =>
232 + Effect.gen(function* () {
233 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
234 +
235 + const { project, notice } = yield* resolveDeveloperProjectOrDefault({});
236 +
237 + expect(project).toMatchObject({ projectId: 'pr_local', source: 'developer-local-config' });
238 + expect(notice).toEqual(Option.none());
239 + expect(fetchSpy).not.toHaveBeenCalled();
240 + }).pipe(
241 + Effect.provide(
242 + Layer.mergeAll(singleton, userContext(Option.some('org_1')), localProject('org_1'))
243 + )
244 + )
245 + );
246 +
247 + it.effect(
248 + 'falls back to the default developer project of the logged-in org when the directory has none',
249 + () =>
250 + Effect.gen(function* () {
251 + const fetchSpy = vi
252 + .spyOn(globalThis, 'fetch')
253 + .mockResolvedValue(defaultProjectInfo('org_1'));
254 +
255 + const { project, notice } = yield* resolveDeveloperProjectOrDefault({});
256 +
257 + expect(project).toEqual({
258 + orgId: 'org_1',
259 + projectId: 'pr_newest',
260 + projectName: 'Newest App',
261 + projectType: 'DEVELOPER',
262 + source: 'developer-default',
263 + });
264 + expect(notice).toEqual(
265 + Option.some(
266 + 'No developer project is set up for this directory; using "Newest App" (pr_newest), the newest developer project in the org you are logged in to, instead. Run `composio dev init` to choose one, or pass --project-name.'
267 + )
268 + );
269 + // One session-info read, scoped to the stored org so `composio orgs switch` holds.
270 + expect(fetchSpy).toHaveBeenCalledTimes(1);
271 + const request = requestOf(fetchSpy.mock.calls[0]);
272 + expect(request.path).toBe(SESSION_INFO_PATH);
273 + expect(request.headers.get('x-org-id')).toBe('org_1');
274 + expect(request.headers.has('x-project-id')).toBe(false);
275 + }).pipe(Effect.provide(testLayer))
276 + );
277 +
278 + it.effect('asks for the key’s default developer project when no org is stored', () =>
279 + Effect.gen(function* () {
280 + const fetchSpy = vi
281 + .spyOn(globalThis, 'fetch')
282 + .mockResolvedValue(defaultProjectInfo('org_joined_last'));
283 +
284 + const { project, notice } = yield* resolveDeveloperProjectOrDefault({});
285 +
286 + expect(project).toMatchObject({
287 + orgId: 'org_joined_last',
288 + projectId: 'pr_newest',
289 + source: 'developer-default',
290 + });
291 + expect(Option.getOrThrow(notice)).toContain(
292 + 'the newest developer project in the org you joined most recently'
293 + );
294 + expect(fetchSpy).toHaveBeenCalledTimes(1);
295 + expect(requestOf(fetchSpy.mock.calls[0]).headers.has('x-org-id')).toBe(false);
296 + }).pipe(Effect.provide(Layer.mergeAll(singleton, userContext(Option.none()), noLocalProject)))
297 + );
298 +
299 + it.effect.each([
300 + {
301 + given: 'session info without a project',
302 + response: () => jsonResponse({ ...makeSessionInfo(), project: null }),
303 + },
304 + {
305 + given: 'an API error',
306 + response: () =>
307 + jsonResponse(
308 + { error: { slug: 'NotFound', status: 404, code: 404, message: 'No project found.' } },
309 + 404
310 + ),
311 + },
312 + ])(
313 + '[Given] $given [Then] fails saying no developer project was found, naming `composio dev init`',
314 + ({ response }) =>
315 + Effect.gen(function* () {
316 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(response());
317 +
318 + const error = yield* resolveDeveloperProjectOrDefault({}).pipe(Effect.flip);
319 +
320 + expect(error).toBeInstanceOf(ProjectResolutionError);
321 + expect(error).toMatchObject({
322 + reason: 'missing_developer_project',
323 + message:
324 + 'No developer project is set up for this directory, and no developer project was found in your org to use instead. Run `composio dev init` to set one up.',
325 + });
326 + }).pipe(Effect.provide(testLayer))
327 + );
328 +
329 + it.effect.each([
330 + { status: 401, message: 'Invalid API key' },
331 + { status: 403, message: 'Access denied' },
332 + { status: 500, message: 'Session service unavailable' },
333 + ])(
334 + 'preserves a $status session lookup failure instead of recommending setup',
335 + ({ status, message }) =>
336 + Effect.gen(function* () {
337 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
338 + jsonResponse({ error: { status, code: status, message } }, status)
339 + );
340 +
341 + const error = yield* resolveDeveloperProjectOrDefault({}).pipe(Effect.flip);
342 +
343 + expect(error).toMatchObject({ reason: 'request_failed', message, cause: { status } });
344 + }).pipe(Effect.provide(testLayer))
345 + );
346 +
347 + it.effect('resolves --project-name as before, never falling back', () =>
348 + Effect.gen(function* () {
349 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(projectsPage(['Other']));
350 +
351 + const error = yield* resolveDeveloperProjectOrDefault({ projectName: 'Missing' }).pipe(
352 + Effect.flip
353 + );
354 +
355 + expect(error).toMatchObject({ reason: 'project_not_found' });
356 + expect(fetchSpy).toHaveBeenCalledTimes(1);
357 + expect(requestOf(fetchSpy.mock.calls[0]).path).not.toBe(SESSION_INFO_PATH);
358 + }).pipe(Effect.provide(testLayer))
359 + );
360 +
361 + it.effect('fails with missing_org before any request when there is no API key', () =>
362 + Effect.gen(function* () {
363 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
364 +
365 + const error = yield* resolveDeveloperProjectOrDefault({}).pipe(Effect.flip);
366 +
367 + expect(error).toMatchObject({ reason: 'missing_org' });
368 + expect(fetchSpy).not.toHaveBeenCalled();
369 + }).pipe(
370 + Effect.provide(
371 + Layer.mergeAll(singleton, userContext(Option.none(), Option.none()), noLocalProject)
372 + )
373 + )
374 + );
375 +});
ts/packages/cli/test/src/services/composio-clients.test.ts
+81 -8
@@ -13,7 +13,11 @@ import {
13 listOrganizations,
14 listOrgProjects,
15 } from 'src/services/composio-account';
16 -import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
16 +import {
17 + ComposioClientSingleton,
18 + ComposioToolkitsRepository,
19 + type ComposioToolkitsRepositoryShape,
20 +} from 'src/services/composio-clients';
21 import { InvalidToolkitsError } from 'src/services/toolkit-version-validation';
22 import { handleClientApiError } from 'src/effects/handle-http-error';
23 import { isClientApiError } from 'src/utils/api-error-extraction';
@@ -45,6 +49,9 @@ vi.mock('@composio/cli-keyring/effect', async importOriginal => {
49
50 const BASE_URL = 'https://backend.composio.dev';
51
52 +// The developer project a project resource call names.
53 +const PROJECT_SCOPE = { orgId: 'org_test', projectId: 'proj_test' };
54 +
55 const platformLayer = () =>
56 Layer.mergeAll(
57 BunFileSystem.layer,
@@ -545,7 +552,9 @@ describe('composio-clients', () => {
552 );
553 const repository = yield* ComposioToolkitsRepository;
554
548 - const error = yield* repository.getAuthConfig('ac_missing').pipe(Effect.flip);
555 + const error = yield* repository
556 + .getAuthConfig(PROJECT_SCOPE, 'ac_missing')
557 + .pipe(Effect.flip);
558
559 expect(error).toMatchObject({
560 _tag: '@composio/client/NotFoundError',
@@ -562,7 +571,7 @@ describe('composio-clients', () => {
571 );
572 const repository = yield* ComposioToolkitsRepository;
573
565 - const error = yield* repository.getAuthConfig('ac_1').pipe(Effect.flip);
574 + const error = yield* repository.getAuthConfig(PROJECT_SCOPE, 'ac_1').pipe(Effect.flip);
575
576 expect(error).toMatchObject({ status: 502, details: undefined });
577 }).pipe(Effect.provide(withRepository))
@@ -574,7 +583,7 @@ describe('composio-clients', () => {
583 errorResponse(400, errorEnvelope({ message: 'Bad input', code: 1001 }))
584 );
585 const repository = yield* ComposioToolkitsRepository;
577 - const error = yield* repository.getAuthConfig('ac_1').pipe(Effect.flip);
586 + const error = yield* repository.getAuthConfig(PROJECT_SCOPE, 'ac_1').pipe(Effect.flip);
587 expect(error).toMatchObject({ details: { message: 'Bad input', code: 1001 } });
588 assert(isClientApiError(error));
589
@@ -647,8 +656,8 @@ describe('composio-clients', () => {
656 .mockResolvedValueOnce(jsonResponse(connectedAccount));
657 const repository = yield* ComposioToolkitsRepository;
658
650 - const decodedAuthConfig = yield* repository.getAuthConfig('ac_1');
651 - const account = yield* repository.getConnectedAccount('con_1');
659 + const decodedAuthConfig = yield* repository.getAuthConfig(PROJECT_SCOPE, 'ac_1');
660 + const account = yield* repository.getConnectedAccount(PROJECT_SCOPE, 'con_1');
661
662 expect(JSON.stringify(decodedAuthConfig)).not.toContain('secret');
663 expect(JSON.stringify(account)).not.toContain('secret');
@@ -663,7 +672,7 @@ describe('composio-clients', () => {
672 );
673 const repository = yield* ComposioToolkitsRepository;
674
666 - const triggers = yield* repository.listActiveTriggers({});
675 + const triggers = yield* repository.listActiveTriggers(PROJECT_SCOPE, {});
676
677 expect(triggers).toMatchObject({
678 total_items: 2,
@@ -690,7 +699,9 @@ describe('composio-clients', () => {
699 );
700 const repository = yield* ComposioToolkitsRepository;
701
693 - const created = yield* repository.createAuthConfig({ toolkit: { slug: 'gmail' } });
702 + const created = yield* repository.createAuthConfig(PROJECT_SCOPE, {
703 + toolkit: { slug: 'gmail' },
704 + });
705
706 expect(created).toEqual({
707 auth_config: { id: 'ac_new', auth_scheme: 'OAUTH2', is_composio_managed: false },
@@ -824,4 +835,66 @@ describe('ComposioToolkitsRepository toolkit lists', () => {
835 expect(headers.has('x-project-id')).toBe(false);
836 }).pipe(Effect.provide(repositoryLayer()))
837 );
838 +
839 + // Auth configs, connected accounts and trigger instances belong to a project, so every call
840 + // names the one the command resolved instead of leaving it to the key's default.
841 + const scope = { orgId: 'org_scoped', projectId: 'pr_scoped' };
842 + it.effect.each<{
843 + readonly method: string;
844 + readonly call: (repository: ComposioToolkitsRepositoryShape) => Effect.Effect<unknown, unknown>;
845 + }>([
846 + {
847 + method: 'listAuthConfigs',
848 + call: (repository: ComposioToolkitsRepositoryShape) => repository.listAuthConfigs(scope, {}),
849 + },
850 + {
851 + method: 'getAuthConfig',
852 + call: (repository: ComposioToolkitsRepositoryShape) =>
853 + repository.getAuthConfig(scope, 'ac_1'),
854 + },
855 + {
856 + method: 'createAuthConfig',
857 + call: (repository: ComposioToolkitsRepositoryShape) =>
858 + repository.createAuthConfig(scope, { toolkit: { slug: 'gmail' } }),
859 + },
860 + {
861 + method: 'getConnectedAccount',
862 + call: (repository: ComposioToolkitsRepositoryShape) =>
863 + repository.getConnectedAccount(scope, 'con_1'),
864 + },
865 + {
866 + method: 'listActiveTriggers',
867 + call: (repository: ComposioToolkitsRepositoryShape) =>
868 + repository.listActiveTriggers(scope, {}),
869 + },
870 + {
871 + method: 'createTrigger',
872 + call: (repository: ComposioToolkitsRepositoryShape) =>
873 + repository.createTrigger(scope, 'GMAIL_NEW_GMAIL_MESSAGE', {}),
874 + },
875 + {
876 + method: 'enableTrigger',
877 + call: (repository: ComposioToolkitsRepositoryShape) =>
878 + repository.enableTrigger(scope, 'ti_1'),
879 + },
880 + {
881 + method: 'disableTrigger',
882 + call: (repository: ComposioToolkitsRepositoryShape) =>
883 + repository.disableTrigger(scope, 'ti_1'),
884 + },
885 + ])('[Given] a scope [Then] $method sends its org and project', ({ call }) =>
886 + Effect.gen(function* () {
887 + const fetchSpy = spyOnToolkitsFetch();
888 + const repository = yield* ComposioToolkitsRepository;
889 +
890 + // What is asserted is the request; the empty answer may not decode.
891 + yield* Effect.exit(call(repository));
892 +
893 + expect(fetchSpy).toHaveBeenCalledOnce();
894 + const { headers } = requestOf(fetchSpy);
895 + expect(headers.get('x-user-api-key')).toBe('uak_test');
896 + expect(headers.get('x-org-id')).toBe('org_scoped');
897 + expect(headers.get('x-project-id')).toBe('pr_scoped');
898 + }).pipe(Effect.provide(repositoryLayer()))
899 + );
900 });
ts/packages/cli/test/src/services/test-layer.test.ts
+9 -4
@@ -25,6 +25,7 @@ import {
25 import { makeSessionInfo } from 'test/__utils__/models/account';
26 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
27 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
28 +import { DIRECTORY_PROJECT_SCOPE } from 'test/__utils__/layers/developer-project';
29
30 describe('TestLayer', () => {
31 it.effect('leaves globalThis.fetch untouched', () =>
@@ -97,7 +98,7 @@ describe('ToolkitsTest', () => {
98 it.effect('dies on a repository method another family serves', () =>
99 Effect.gen(function* () {
100 const repo = yield* ComposioToolkitsRepository;
100 - const exit = yield* repo.listAuthConfigs({}).pipe(Effect.exit);
101 + const exit = yield* repo.listAuthConfigs(DIRECTORY_PROJECT_SCOPE, {}).pipe(Effect.exit);
102
103 expect(Exit.hasDies(exit)).toBe(true);
104 }).pipe(Effect.provide(ToolkitsTest()))
@@ -146,9 +147,13 @@ describe('ConnectedAccountsTest', () => {
147 ])('serves the same auth-config and connected-account answers through $name', ({ layer }) =>
148 Effect.gen(function* () {
149 const repo = yield* ComposioToolkitsRepository;
149 - const authConfigs = yield* repo.listAuthConfigs({ toolkit_slug: 'slack' });
150 - const found = yield* repo.getConnectedAccount('con_gmail');
151 - const missing = yield* repo.getAuthConfig('ac_nope').pipe(Effect.flip);
150 + const authConfigs = yield* repo.listAuthConfigs(DIRECTORY_PROJECT_SCOPE, {
151 + toolkit_slug: 'slack',
152 + });
153 + const found = yield* repo.getConnectedAccount(DIRECTORY_PROJECT_SCOPE, 'con_gmail');
154 + const missing = yield* repo
155 + .getAuthConfig(DIRECTORY_PROJECT_SCOPE, 'ac_nope')
156 + .pipe(Effect.flip);
157
158 expect(authConfigs.items.map(item => item.id)).toEqual(['ac_slack']);
159 expect(found.toolkit.slug).toBe('gmail');