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

refactor(cli): resolve the acting user in one place (#5127)

This PR: - targets `next` now that its former base, #5126 (`fix/cli-carry-over-open-fixes`), has been merged - adds `actingUser` / `actingUserOption` to `src/commands/surface.ts`: root tree → consumer user of the consumer project; dev tree → `--user-id` → directory test user (only for the directory's own project) → global test user, against the developer project. The result carries `{ userId, source, project }`, and a missing user fails with `MissingActingUserError` (`[ExpectedFailure]`) - moves all 14 call sites (execute / playground-execute incl. `--parallel`, search, `link` list / legacy `--auth-config` / Tool Router, dev toolkits list and info, dev triggers create, connections list and remove, listen, proxy, run) onto it; filter-only `--user-id` (dev logs, dev triggers listen, dev connected-accounts list) stays raw - no output changes: every site keeps its message, fallback notice, and error class, because the class tag is the `error_name` that `cli.command.failed` reports and the handler tests match on it. Where `link` departs from the rule (consumer project on the dev tree without `--project-name`, no directory step in the Tool Router flow), it says so through `ActingUserOptions.legacy`. Each of these exceptions is commented in the code; https://github.com/ComposioHQ/composio/pull/5130 removes them - an empty `consumer_user_id` keeps its per-command handling: `execute`, `search`, `link`, and `run` accept it as the user through `ActingUserOptions.legacy.acceptEmptyConsumerUserId`, while `connections` (list / remove), `listen`, and `proxy` reject it as no user. https://github.com/ComposioHQ/composio/pull/5130 treats it as missing everywhere - adds a table-driven suite (`test/src/commands/surface.acting-user.test.ts`) covering tree × user candidates × `--project-name` (absent / same project / other project) for both functions, plus the legacy options and the empty consumer user id accepted / rejected per site. Existing command tests pass unchanged - adds `ts/packages/cli/GLOSSARY.md` and links it from `AGENTS.md`, together with the rule that handlers take the acting user from `actingUser` / `actingUserOption` Verified with `pnpm typecheck`, `pnpm --filter @composio/cli run lint:effect`, `pnpm --filter @composio/cli test` (210 files, 2487 tests, with `validate:boundaries` and `validate:command-tests`), and `./node_modules/.bin/oxlint ts/packages/cli` (no errors). --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 28, 2026 at 12:08 UTC 04d0342af9bb753ce04153c10bf0bc65cdef87d8
22 files changed +1135 -326
ts/packages/cli/AGENTS.md
+15 -7
@@ -2,6 +2,8 @@
2
3 Instructions for AI agents working on `@composio/cli`. The sibling `CLAUDE.md` is a symlink to this file.
4
5 +The CLI's vocabulary (command trees, acting user, expected failure, …) is defined in [`GLOSSARY.md`](GLOSSARY.md); use its terms.
6 +
7 ## Required Checks
8
9 When you touch CLI code (anything under `ts/packages/cli/src/`), run `pnpm typecheck` from the repo root before pushing. Fix all type errors. Build/lint failures block CI. Also run `pnpm --filter @composio/cli run lint:effect`, which runs the Effect language service over `src/` and `test/` and fails on its error-level diagnostics; the main one is `floatingEffect`, an Effect that is created and never yielded (a dropped `client.…(...)` call compiles and silently sends nothing). CI runs it in the typecheck workflow.
@@ -70,7 +72,7 @@ src/commands/
72 index.ts root command tree, argv contract with cli-main.ts
73 $default.cmd.ts root command: shared flags and description
74 errors.ts CommandInputError, the one usage error every command raises
73 - surface.ts CommandSurface: the tree a command runs in and the dev group's shared flags
75 + surface.ts CommandSurface: the tree a command runs in, the dev group's shared flags, the acting user
76 <group>/<group>.cmd.ts group entry: Command.make(name) + withSubcommands, nothing else
77 <group>/<name>/<group>.<name>.cmd.ts flags, arguments, description, examples, Command.make
78 <group>/<name>/<group>.<name>.handler.ts (params) => Effect; imports nothing from effect/cli
@@ -85,6 +87,7 @@ Rules:
87 - `<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.
88 - `<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`).
89 - 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) pipes `rejectsSharedFlags` (`surface.ts`), and the `dev` group's own `--mode` toggle calls `rejectSharedFlags`, so the flag fails with a `CommandInputError` instead of being ignored. `execute` and `playground-execute` keep two registrations because their names differ; they share one handler.
90 +- A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`) or `actingUserOption` (for a command that also runs without one) in `surface.ts`; it never reads `--user-id` or a test user id to resolve one itself. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
91 - Logic shared across groups belongs in `src/effects/` or `src/services/`, never in another command's directory.
92 - A command that needs a logged-in user pipes `requireLogin` (`src/effects/require-auth.ts`) on itself or on its group entry, after `Command.withSubcommands`. Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`.
93 - 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.
@@ -196,18 +199,23 @@ Effect.gen(function* () {
199
200 Key patterns: `Effect.all([...], { concurrency: 'unbounded' })` for parallel work, `Layer.provide()` for dependency composition, `Effect.mapError()` / `Effect.catchTag()` for typed errors, `Effect.scoped` for resource cleanup.
201
199 -For table-driven tests over independent finite choices, use Effect Array do notation
200 -to build a typed Cartesian product instead of enumerating every case or nesting loops:
202 +For table-driven tests over independent finite choices, build a typed Cartesian product
203 +with plain `flatMap`/`map` instead of enumerating every case or writing loops (do
204 +notation is lint-banned, tests included):
205
206 ```typescript
207 const cases = pipe(
204 - Arr.Do,
205 - Arr.bind('firstAxis', () => choices),
206 - Arr.bind('secondAxis', () => choices)
208 + firstChoices,
209 + Arr.flatMap(firstAxis =>
210 + pipe(
211 + secondChoices,
212 + Arr.map(secondAxis => ({ firstAxis, secondAxis }))
213 + )
214 + )
215 );
216 ```
217
210 -Each `Arr.bind` adds one independent axis to the generated cases.
218 +Each nested `Arr.flatMap` adds one independent axis; the innermost `Arr.map` builds the case.
219
220 ### Effect safety and migration boundaries
221
ts/packages/cli/GLOSSARY.md new
+60
@@ -0,0 +1,60 @@
1 +# Composio CLI
2 +
3 +The vocabulary of `@composio/cli`: who a command acts for, where it runs, and how one invocation ends.
4 +
5 +## Command trees
6 +
7 +**Root tree**:
8 +The commands a Composio user runs directly (`composio execute`, `composio link`); they act on the user's consumer project.
9 +_Avoid_: consumer mode, root mode
10 +
11 +**Dev tree**:
12 +The commands under `composio dev`, for developers building on Composio; they act on a developer project.
13 +_Avoid_: developer mode, playground
14 +
15 +**Command path**:
16 +The command names of an invocation, without `composio`, flags, or arguments, e.g. `dev triggers list`.
17 +_Avoid_: command name, command string
18 +
19 +**Command registration**:
20 +One place a command appears in the command tree; the same command can have several, each with its own command path (`link` and `dev connected-accounts link`).
21 +_Avoid_: command instance
22 +
23 +**Root shortcut**:
24 +A root-tree command that reaches a command defined in a group, e.g. `search` for `tools search`.
25 +_Avoid_: alias (reserved for a flag's or command's short name)
26 +
27 +## Projects and users
28 +
29 +**Consumer project**:
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`.
34 +
35 +**Consumer user**:
36 +The user id of the logged-in person within their consumer project; no flag overrides it.
37 +
38 +**Test user**:
39 +A user id a developer acts as on a developer project: the directory test user (from the directory's project setup) or the global test user (stored at login).
40 +_Avoid_: playground user, default user
41 +
42 +**Acting user**:
43 +The user a command acts as: the consumer user on the root tree; on the dev tree, `--user-id` when given, otherwise the test user.
44 +_Avoid_: current user, target user
45 +
46 +**User filter**:
47 +A `--user-id` that only narrows listed results and never falls back to a test user.
48 +
49 +## Outcomes
50 +
51 +**Invocation**:
52 +One execution of the `composio` binary, from argv to exit code.
53 +_Avoid_: run (that is the `composio run` command)
54 +
55 +**Expected failure**:
56 +A failure the user fixes by changing the invocation or their setup, or that a remote service reported clearly; the CLI prints its message and no defect report.
57 +_Avoid_: usage error (a usage error is one kind)
58 +
59 +**Defect**:
60 +A failure that signals a bug in the CLI; the CLI prints a defect report.
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.handler.ts
+60 -87
@@ -3,10 +3,14 @@ import type { ComposioClientShape } from '@composio/client/effect';
3 import open from 'open';
4 import { commandInputError } from 'src/commands/errors';
5 import {
6 + actingUser,
7 + actingUserOption,
8 CommandSurface,
7 - directoryTestUserId,
9 + fallbackNotice,
10 missingUserIdMessage,
11 + type ActingUserOptions,
12 type CommandTree,
13 + type MissingActingUserError,
14 } from 'src/commands/surface';
15 import { ComposioUserContext } from 'src/services/user-context';
16 import { TerminalUI } from 'src/services/terminal-ui';
@@ -103,6 +107,25 @@ const consumerScope = (project: ResolvedCommandProject) =>
107 }))
108 );
109
110 +/**
111 + * On the dev tree without `--project-name`, `link` and `link --list` act as the consumer user on
112 + * the consumer project and ignore `--user-id`, matching their behavior before `actingUser`.
113 + */
114 +const LINK_LEGACY = {
115 + legacy: {
116 + consumerWithoutProjectName: true,
117 + // As before `actingUser`, an empty consumer user id still counts as a user.
118 + acceptEmptyConsumerUserId: true,
119 + },
120 +} satisfies ActingUserOptions;
121 +
122 +/**
123 + * Re-fail with link's own `MissingLinkUserIdError`, so `cli.command.failed` keeps reporting it as
124 + * `error_name` and the handler tests keep matching its tag.
125 + */
126 +const missingLinkUserId = (flow: LinkFlow) => (error: MissingActingUserError) =>
127 + Effect.fail(new MissingLinkUserIdError({ message: error.message, flow }));
128 +
129 /** The directory's project keys, or none when the directory is not initialized or unreadable. */
130 const directoryProject = Effect.gen(function* () {
131 const projectContext = yield* ProjectContext;
@@ -399,35 +422,17 @@ export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams)
422 }
423 const toolkitSlug = params.toolkit.value;
424
402 - const { userId, projectName } = yield* CommandSurface;
425 const clientSingleton = yield* ComposioClientSingleton;
404 - const userContext = yield* ComposioUserContext;
405 - const resolvedProject = yield* resolveCommandProject({
406 - mode: 'consumer',
407 - projectName: Option.getOrUndefined(projectName),
408 - });
426 + const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser({
427 + ...LINK_LEGACY,
428 + // Keep the command's own missing-user message rather than the tree's default.
429 + missingUserMessage: projectName =>
430 + missingUserIdMessage(
431 + projectName,
432 + 'Missing user id. Provide --user-id, or run composio dev init or composio login first.'
433 + ),
434 + }).pipe(Effect.catchTag('commands/MissingActingUserError', missingLinkUserId('list')));
435 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
410 - const localTestUserId = directoryTestUserId(
411 - yield* directoryProject,
412 - Option.as(projectName, resolvedProject.projectId)
413 - );
414 - const resolvedUserId = yield* pipe(
415 - resolvedProject.projectType === 'CONSUMER'
416 - ? Option.fromNullishOr(resolvedProject.consumerUserId)
417 - : Option.orElse(userId, () =>
418 - Option.orElse(localTestUserId, () => userContext.data.testUserId)
419 - ),
420 - Effect.fromOption(
421 - () =>
422 - new MissingLinkUserIdError({
423 - message: missingUserIdMessage(
424 - projectName,
425 - 'Missing user id. Provide --user-id, or run composio dev init or composio login first.'
426 - ),
427 - flow: 'list',
428 - })
429 - )
430 - );
436
437 const accounts = yield* ui.withSpinner(
438 `Listing connected accounts for "${toolkitSlug}"...`,
@@ -486,7 +491,7 @@ export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams)
491 export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams) =>
492 Effect.gen(function* () {
493 const ui = yield* TerminalUI;
489 - const { tree, userId, projectName } = yield* CommandSurface;
494 + const { tree, projectName } = yield* CommandSurface;
495 // The dispatcher never gets here without --auth-config. This narrows it for direct callers.
496 if (Option.isNone(params.authConfig)) {
497 return yield* Effect.fail(
@@ -496,49 +501,29 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
501 const authConfigId = params.authConfig.value;
502
503 const clientSingleton = yield* ComposioClientSingleton;
499 - const userContext = yield* ComposioUserContext;
500 - const resolvedProjectContext = yield* directoryProject;
501 - // A named project is looked up first: its id decides whether the directory's test user applies.
502 - const namedResolvedProject = yield* Effect.transposeOption(
503 - Option.map(projectName, name =>
504 - resolveCommandProject({ mode: 'developer', projectName: name })
505 - )
506 - );
507 - const localTestUserId = directoryTestUserId(
508 - resolvedProjectContext,
509 - Option.map(namedResolvedProject, project => project.projectId)
510 - );
511 - const globalTestUserId = userContext.data.testUserId;
512 - const resolvedUserId = yield* pipe(
513 - Option.orElse(userId, () => Option.orElse(localTestUserId, () => globalTestUserId)),
514 - Effect.fromOption(
515 - () =>
516 - new MissingLinkUserIdError({
517 - message: missingUserIdMessage(
518 - projectName,
519 - 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
520 - ),
521 - flow: 'legacy',
522 - })
523 - )
524 - );
525 - if (Option.isNone(projectName) && Option.isNone(resolvedProjectContext)) {
504 + // The user is checked before the directory's project, so a missing user wins over a
505 + // missing project; `actingUserOption` resolves only the --project-name project.
506 + const acting = yield* actingUserOption();
507 + if (Option.isNone(acting)) {
508 + // `actingUserOption` does not fail, so this flow raises link's own error and message.
509 + return yield* new MissingLinkUserIdError({
510 + message: missingUserIdMessage(
511 + projectName,
512 + 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
513 + ),
514 + flow: 'legacy',
515 + });
516 + }
517 + const { userId: resolvedUserId, project: namedResolvedProject } = acting.value;
518 + if (Option.isNone(projectName) && Option.isNone(yield* directoryProject)) {
519 return yield* Effect.fail(
520 invalidOptionValueFor(tree)(AUTH_CONFIG_SCOPE_MESSAGE, '--auth-config')
521 );
522 }
530 - // Without --user-id, say which test user stands in.
531 - yield* Option.isSome(userId)
532 - ? Effect.void
533 - : Option.match(localTestUserId, {
534 - onSome: testUserId => ui.log.warn(`Using test user id "${testUserId}"`),
535 - onNone: () =>
536 - Effect.transposeOption(
537 - Option.map(globalTestUserId, testUserId =>
538 - ui.log.warn(`Using global test user id "${testUserId}"`)
539 - )
540 - ),
541 - });
523 + // The acting-user helpers leave the test-user notice to the command, so print it here.
524 + yield* Effect.transposeOption(
525 + Option.map(fallbackNotice(acting.value), notice => ui.log.warn(notice))
526 + );
527
528 const resolvedProject = yield* Option.match(namedResolvedProject, {
529 onSome: Effect.succeed,
@@ -614,7 +599,7 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
599 export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
600 Effect.gen(function* () {
601 const ui = yield* TerminalUI;
617 - const { tree, userId, projectName } = yield* CommandSurface;
602 + const { tree } = yield* CommandSurface;
603 // The dispatcher never gets here without a toolkit. This narrows it for direct callers.
604 if (Option.isNone(params.toolkit)) {
605 return yield* Effect.fail(
@@ -625,24 +610,12 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
610
611 const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias, tree);
612 const clientSingleton = yield* ComposioClientSingleton;
628 - const userContext = yield* ComposioUserContext;
629 - const resolvedProject = yield* resolveCommandProject({
630 - mode: 'consumer',
631 - projectName: Option.getOrUndefined(projectName),
632 - });
633 - const resolvedUserId = yield* pipe(
634 - resolvedProject.projectType === 'CONSUMER'
635 - ? Option.fromNullishOr(resolvedProject.consumerUserId)
636 - : Option.orElse(userId, () => userContext.data.testUserId),
637 - Effect.fromOption(
638 - () =>
639 - new MissingLinkUserIdError({
640 - message:
641 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
642 - flow: 'tool-router',
643 - })
644 - )
645 - );
613 + const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser({
614 + // Ignores the directory test user and keeps its own message, as before `actingUser`.
615 + legacy: { ...LINK_LEGACY.legacy, skipDirectoryTestUser: true },
616 + missingUserMessage: () =>
617 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
618 + }).pipe(Effect.catchTag('commands/MissingActingUserError', missingLinkUserId('tool-router')));
619 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
620 const existingAccounts = yield* existingAccountsForHints({
621 client,
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+8 -11
@@ -7,7 +7,7 @@ import {
7 import { failedWith, requestError } from 'src/effects/request-error';
8 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
10 -import { resolveCommandProject } from 'src/services/command-project';
10 +import { actingUser } from 'src/commands/surface';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 import {
13 getConnectedAccountPermissionGroup,
@@ -78,16 +78,13 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
78 const ui = yield* TerminalUI;
79 const clientSingleton = yield* ComposioClientSingleton;
80 const toolkitSlug = Option.getOrUndefined(toolkit);
81 - const resolvedProject = yield* resolveCommandProject({
82 - mode: 'consumer',
83 - });
84 -
85 - const consumerUserId = resolvedProject.consumerUserId;
86 - if (!consumerUserId) {
87 - return yield* new MissingConnectionsConsumerUserIdError({
88 - message: 'Missing consumer user id. Run `composio login` and try again.',
89 - });
90 - }
81 + const { userId: consumerUserId, project: resolvedProject } = yield* actingUser().pipe(
82 + // Re-fail with the command's own error, not the expected `MissingActingUserError`: it has
83 + // always failed with it as a defect, and `cli.command.failed` keeps its `error_name`.
84 + Effect.catchTag('commands/MissingActingUserError', error =>
85 + Effect.fail(new MissingConnectionsConsumerUserIdError({ message: error.message }))
86 + )
87 + );
88
89 const client = yield* clientSingleton.getFor({
90 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/connections/remove/connections.remove.handler.ts
+8 -11
@@ -7,7 +7,7 @@ import {
7 import { failedWith } from 'src/effects/request-error';
8 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
10 -import { resolveCommandProject } from 'src/services/command-project';
10 +import { actingUser } from 'src/commands/surface';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 import { bold } from 'src/ui/colors';
13 import { redact } from 'src/ui/redact';
@@ -105,16 +105,13 @@ export const runConnectionsRemove = ({ account, yes }: ConnectionsRemoveParams)
105 return yield* invalidInput(NEEDS_YES_MESSAGE, '--yes');
106 }
107 const clientSingleton = yield* ComposioClientSingleton;
108 - const resolvedProject = yield* resolveCommandProject({
109 - mode: 'consumer',
110 - });
111 -
112 - const consumerUserId = resolvedProject.consumerUserId;
113 - if (!consumerUserId) {
114 - return yield* new MissingConnectionRemovalConsumerUserIdError({
115 - message: 'Missing consumer user id. Run `composio login` and try again.',
116 - });
117 - }
108 + const { userId: consumerUserId, project: resolvedProject } = yield* actingUser().pipe(
109 + // Re-fail with the command's own error, not the expected `MissingActingUserError`: it has
110 + // always failed with it as a defect, and `cli.command.failed` keeps its `error_name`.
111 + Effect.catchTag('commands/MissingActingUserError', error =>
112 + Effect.fail(new MissingConnectionRemovalConsumerUserIdError({ message: error.message }))
113 + )
114 + );
115
116 const client = yield* clientSingleton.getFor({
117 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/listen.cmd.ts
+20 -12
@@ -9,7 +9,7 @@ import type { ComposioClientShape } from '@composio/client/effect';
9 import { Data, Deferred, Effect, FiberSet, Result, Option, Predicate } from 'effect';
10 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
11 import { ComposioClientSingleton, type ToolkitProjectScope } from 'src/services/composio-clients';
12 -import { resolveCommandProject } from 'src/services/command-project';
12 +import { actingUser } from 'src/commands/surface';
13 import {
14 resolveArtifactsRoot,
15 resolveCliSessionArtifacts,
@@ -407,19 +407,11 @@ const resolveListenSetup = (params: {
407 readonly resolvedProject: {
408 readonly orgId: string;
409 readonly projectId: string;
410 - readonly consumerUserId?: string;
410 };
411 + readonly consumerUserId: string;
412 }) =>
413 Effect.gen(function* () {
414 - const consumerUserId = params.resolvedProject.consumerUserId;
415 - if (!consumerUserId) {
416 - return yield* new ListenCommandError({
417 - reason: 'project_context',
418 - message: 'No consumer user is available in the current project context.',
419 - slug: params.slug,
420 - });
421 - }
422 -
414 + const consumerUserId = params.consumerUserId;
415 const listeningToProjectEvent = isProjectEventType(params.slug);
416 const rawParams = Option.isSome(params.inputParams)
417 ? (yield* resolveParamsInput(params.inputParams))?.trim() || '{}'
@@ -469,6 +461,21 @@ const resolveListenSetup = (params: {
461 };
462 });
463
464 +/** The consumer user `listen` subscribes as, with the consumer project. */
465 +const listenActingUser = (slug: string) =>
466 + actingUser({
467 + // Keep the command's own missing-user message rather than the tree's default.
468 + missingUserMessage: () => 'No consumer user is available in the current project context.',
469 + }).pipe(
470 + // Re-fail with the command's own error, not the expected `MissingActingUserError`: it has
471 + // always failed with it as a defect, and `cli.command.failed` keeps its `error_name`.
472 + Effect.catchTag('commands/MissingActingUserError', error =>
473 + Effect.fail(
474 + new ListenCommandError({ reason: 'project_context', message: error.message, slug })
475 + )
476 + )
477 + );
478 +
479 export const listenCmd = Command.make(
480 'listen',
481 { slug, params, maxEvents, timeout, stream, account, failFast, debug },
@@ -480,7 +487,7 @@ export const listenCmd = Command.make(
487 const clientSingleton = yield* ComposioClientSingleton;
488 const realtime = yield* TriggersRealtime;
489
483 - const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' });
490 + const { userId: actingUserId, project: resolvedProject } = yield* listenActingUser(slug);
491
492 const client = yield* clientSingleton.getFor({
493 orgId: resolvedProject.orgId,
@@ -503,6 +510,7 @@ export const listenCmd = Command.make(
510 account,
511 client,
512 resolvedProject,
513 + consumerUserId: actingUserId,
514 });
515
516 const artifactsOption = yield* resolveCliSessionArtifacts({
ts/packages/cli/src/commands/proxy.cmd.ts
+12 -9
@@ -16,7 +16,7 @@ import {
16 } from 'src/services/consumer-short-term-cache';
17 import { TerminalUI } from 'src/services/terminal-ui';
18 import { ComposioClientSingleton } from 'src/services/composio-clients';
19 -import { resolveCommandProject } from 'src/services/command-project';
19 +import { actingUser } from 'src/commands/surface';
20 import {
21 ComposioNoActiveConnectionError,
22 mapComposioError,
@@ -304,14 +304,17 @@ export const proxyCmd = Command.make('proxy', {
304 const { endpoint, toolkit, account, method, headers, data, skipConnectionCheck } = options;
305 const ui = yield* TerminalUI;
306 const clientSingleton = yield* ComposioClientSingleton;
307 - const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' });
308 -
309 - if (resolvedProject.projectType !== 'CONSUMER' || !resolvedProject.consumerUserId) {
310 - return yield* new ProxyCommandError({
311 - message: 'No consumer project user is available for proxy execution in this context.',
312 - });
313 - }
314 - const consumerUserId = resolvedProject.consumerUserId;
307 + const { userId: consumerUserId, project: resolvedProject } = yield* actingUser({
308 + // Keep the command's own missing-user message rather than the tree's default.
309 + missingUserMessage: () =>
310 + 'No consumer project user is available for proxy execution in this context.',
311 + }).pipe(
312 + // Re-fail with the `ProxyCommandError` the command has always failed with, so
313 + // `cli.command.failed` keeps reporting it as `error_name`.
314 + Effect.catchTag('commands/MissingActingUserError', error =>
315 + Effect.fail(new ProxyCommandError({ message: error.message }))
316 + )
317 + );
318 const normalizedToolkit = toolkit.toLowerCase();
319
320 yield* runProxyConnectedToolkitFailFast({
ts/packages/cli/src/commands/run.cmd.ts
+12 -7
@@ -7,7 +7,7 @@ import { ChildProcess, ChildProcessSpawner } from 'effect/process';
7 import { Data, Deferred, Duration, Effect, MutableRef, Option, Result } from 'effect';
8 import { APP_VERSION } from 'src/constants';
9 import { loadGenerationRuntime } from 'src/effects/generation-runtime';
10 -import { resolveCommandProject } from 'src/services/command-project';
10 +import { actingUser } from 'src/commands/surface';
11 import { type RunHelperContext } from 'src/services/run-helpers-runtime';
12 import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
13 import { ComposioUserContext } from 'src/services/user-context';
@@ -284,23 +284,28 @@ const resolveRunHelperContext = () =>
284 return baseContext;
285 }
286
287 - const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(Effect.option);
288 - if (Option.isNone(consumerProject) || consumerProject.value.projectType !== 'CONSUMER') {
287 + // Without a consumer user the script runs with the base context alone.
288 + const consumer = yield* actingUser({
289 + // As before `actingUser`, an empty consumer user id still counts as a user.
290 + legacy: { acceptEmptyConsumerUserId: true },
291 + }).pipe(Effect.option);
292 + if (Option.isNone(consumer)) {
293 return baseContext;
294 }
295 + const { userId: consumerUserId, project: consumerProject } = consumer.value;
296
297 const sessionArtifactsDir = Option.getOrUndefined(
298 yield* resolveCliSessionArtifacts({
299 orgId,
295 - consumerUserId: consumerProject.value.consumerUserId,
300 + consumerUserId,
301 }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
302 );
303
304 return {
305 ...baseContext,
301 - consumerUserId: consumerProject.value.consumerUserId,
302 - consumerProjectId: consumerProject.value.projectId,
303 - consumerProjectName: consumerProject.value.projectName,
306 + consumerUserId,
307 + consumerProjectId: consumerProject.projectId,
308 + consumerProjectName: consumerProject.projectName,
309 runOutputDir: sessionArtifactsDir,
310 } satisfies RunHelperContext;
311 });
ts/packages/cli/src/commands/surface.ts
+194 -25
@@ -1,8 +1,14 @@
1 -import { Context, Effect, Layer, Option, pipe } from 'effect';
1 +import { Context, Data, Effect, Layer, Option, pipe } from 'effect';
2 import { Command } from 'effect/cli';
3 import { commandInputError } from 'src/commands/errors';
4 -import { resolveCommandProject, type ProjectMode } from 'src/services/command-project';
5 -import { ComposioClientSingleton } from 'src/services/composio-clients';
4 +import { ExpectedFailure } from 'src/effects/expected-failure';
5 +import {
6 + resolveCommandProject,
7 + type ProjectMode,
8 + type ResolvedCommandProject,
9 +} from 'src/services/command-project';
10 +import { ProjectContext } from 'src/services/project-context';
11 +import { ComposioUserContext } from 'src/services/user-context';
12
13 /** The command tree a command was invoked from. */
14 export type CommandTree = 'root' | 'dev';
@@ -49,23 +55,70 @@ export const resolveSurfaceProject = (mode: ProjectMode) =>
55 });
56 });
57
58 +// --- acting user ------------------------------------------------------------------------------
59 +
60 +/** Which step of the acting-user rule picked the user. */
61 +export type ActingUserSource = 'consumer' | 'flag' | 'directory-test-user' | 'global-test-user';
62 +
63 /**
53 - * The developer project the `dev` group's `--project-name` names, with its client, or none when
54 - * the flag is absent and the command keeps the directory's project and its default client.
64 + * The user a command acts as (glossary "Acting user"), with the project it was resolved
65 + * against. `actingUserOption` leaves the project optional; see there.
66 */
56 -export const namedProject = Effect.gen(function* () {
57 - const surface = yield* CommandSurface;
58 - if (Option.isNone(surface.projectName)) {
59 - return Option.none();
67 +export interface ActingUser<Project = ResolvedCommandProject> {
68 + readonly userId: string;
69 + readonly source: ActingUserSource;
70 + readonly project: Project;
71 +}
72 +
73 +/** No step of the acting-user rule found a user for the command. */
74 +export class MissingActingUserError extends Data.TaggedError('commands/MissingActingUserError')<{
75 + readonly tree: CommandTree;
76 + readonly projectName: Option.Option<string>;
77 + readonly message: string;
78 +}> {
79 + get [ExpectedFailure]() {
80 + return true;
81 }
61 - const project = yield* resolveSurfaceProject('developer');
62 - const clientSingleton = yield* ComposioClientSingleton;
63 - const client = yield* clientSingleton.getFor({
64 - orgId: project.orgId,
65 - projectId: project.projectId,
82 +}
83 +
84 +/**
85 + * The missing-user message for a command, given its `--project-name`. With the flag the
86 + * directory's test user does not carry over to another project, so the message points at
87 + * `--user-id` and `composio login` instead of `composio dev init`.
88 + */
89 +export const missingUserIdMessage = (projectName: Option.Option<string>, otherwise: string) =>
90 + Option.match(projectName, {
91 + onNone: () => otherwise,
92 + onSome: () =>
93 + 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
94 });
67 - return Option.some({ projectId: project.projectId, client });
68 -});
95 +
96 +const defaultMissingUserMessage =
97 + (tree: CommandTree) =>
98 + (projectName: Option.Option<string>): string =>
99 + tree === 'root'
100 + ? 'Missing consumer user id. Run `composio login` and try again.'
101 + : missingUserIdMessage(
102 + projectName,
103 + 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'
104 + );
105 +
106 +export interface ActingUserOptions {
107 + /** The `MissingActingUserError` message, given `--project-name`; defaults to the tree's. Only `actingUser` reads it: `actingUserOption` never fails with a missing user. */
108 + readonly missingUserMessage?: (projectName: Option.Option<string>) => string;
109 + /** Departures from the rule that some commands keep, as they behaved before `actingUser`. */
110 + readonly legacy?: {
111 + /**
112 + * Accept an empty consumer user id as the consumer user, as `execute`, `search`, `link` and
113 + * `run` do; without it an empty id counts as none, as `connections`, `listen` and `proxy` do.
114 + */
115 + readonly acceptEmptyConsumerUserId?: boolean;
116 + /** On the dev tree without `--project-name`, act as the consumer user, ignoring `--user-id`. */
117 + readonly consumerWithoutProjectName?: boolean;
118 + /** Skip the directory test user on the dev tree. */
119 + readonly skipDirectoryTestUser?: boolean;
120 + };
121 +}
122
123 /**
124 * The test user the directory configures (`.composio/project.json`), for a command that runs
@@ -73,7 +126,7 @@ export const namedProject = Effect.gen(function* () {
126 * borrow it, so the command falls back to the global test user; `namedProjectId` is the id of
127 * the project `--project-name` resolved to, or none without the flag.
128 */
76 -export const directoryTestUserId = (
129 +const directoryTestUserId = (
130 directoryProject: Option.Option<{
131 readonly projectId: string;
132 readonly testUserId: Option.Option<string>;
@@ -88,16 +141,132 @@ export const directoryTestUserId = (
141 Option.flatMap(keys => keys.testUserId)
142 );
143
144 +/** The dev tree's rule over its candidates: `--user-id`, the directory test user, the global one. */
145 +export const devActingUser = (candidates: {
146 + readonly flag: Option.Option<string>;
147 + readonly directoryTestUserId: Option.Option<string>;
148 + readonly globalTestUserId: Option.Option<string>;
149 +}): Option.Option<Omit<ActingUser, 'project'>> =>
150 + Option.firstSomeOf([
151 + Option.map(candidates.flag, userId => ({ userId, source: 'flag' as const })),
152 + Option.map(candidates.directoryTestUserId, userId => ({
153 + userId,
154 + source: 'directory-test-user' as const,
155 + })),
156 + Option.map(candidates.globalTestUserId, userId => ({
157 + userId,
158 + source: 'global-test-user' as const,
159 + })),
160 + ]);
161 +
162 +const noticeBySource: Record<ActingUserSource, (userId: string) => Option.Option<string>> = {
163 + consumer: () => Option.none(),
164 + flag: () => Option.none(),
165 + 'directory-test-user': userId => Option.some(`Using test user id "${userId}"`),
166 + 'global-test-user': userId => Option.some(`Using global test user id "${userId}"`),
167 +};
168 +
169 +/** The stderr notice for a test user standing in; none for the consumer user or `--user-id`. */
170 +export const fallbackNotice = (user: Omit<ActingUser, 'project'>): Option.Option<string> =>
171 + noticeBySource[user.source](user.userId);
172 +
173 +/** The consumer user of a consumer project; an empty id counts as none unless `legacy` accepts it. */
174 +const consumerUser = (project: ResolvedCommandProject, options: ActingUserOptions) =>
175 + pipe(
176 + Option.fromNullishOr(project.consumerUserId),
177 + Option.filter(
178 + userId => userId.length > 0 || options.legacy?.acceptEmptyConsumerUserId === true
179 + ),
180 + Option.map(userId => ({ userId, source: 'consumer' as const }))
181 + );
182 +
183 +/** The dev tree's user for a project, `namedProjectId` being the `--project-name` project's id. */
184 +const devUser = (namedProjectId: Option.Option<string>, options: ActingUserOptions) =>
185 + Effect.gen(function* () {
186 + const surface = yield* CommandSurface;
187 + const userContext = yield* ComposioUserContext;
188 + const projectContext = yield* ProjectContext;
189 + const directoryProject = options.legacy?.skipDirectoryTestUser
190 + ? Option.none()
191 + : yield* projectContext.resolve.pipe(Effect.option, Effect.map(Option.flatten));
192 + return devActingUser({
193 + flag: surface.userId,
194 + directoryTestUserId: directoryTestUserId(directoryProject, namedProjectId),
195 + globalTestUserId: userContext.data.testUserId,
196 + });
197 + });
198 +
199 +/** The tree whose rule applies: the surface's, unless a legacy option says otherwise. */
200 +const ruleTree = (surface: CommandSurfaceShape, options: ActingUserOptions): CommandTree =>
201 + surface.tree === 'dev' &&
202 + !(options.legacy?.consumerWithoutProjectName && Option.isNone(surface.projectName))
203 + ? 'dev'
204 + : 'root';
205 +
206 /**
92 - * The missing-user message for a command, given its `--project-name`. With the flag the
93 - * directory's test user does not carry over to another project, so the message points at
94 - * `--user-id` and `composio login` instead of `composio dev init`.
207 + * The acting user, resolved against the project the command runs in. On the root tree, the
208 + * consumer user of the consumer project. On the dev tree, against the developer project
209 + * (`--project-name`, else the directory's): `--user-id`, then the directory test user (only
210 + * for the directory's own project), then the global test user. Fails with
211 + * `ProjectResolutionError` when the project cannot be resolved and `MissingActingUserError`
212 + * when no step finds a user.
213 */
96 -export const missingUserIdMessage = (projectName: Option.Option<string>, otherwise: string) =>
97 - Option.match(projectName, {
98 - onNone: () => otherwise,
99 - onSome: () =>
100 - 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
214 +export const actingUser = (options: ActingUserOptions = {}) =>
215 + Effect.gen(function* () {
216 + const surface = yield* CommandSurface;
217 + const tree = ruleTree(surface, options);
218 + const project = yield* resolveCommandProject(
219 + tree === 'root'
220 + ? { mode: 'consumer' }
221 + : { mode: 'developer', projectName: Option.getOrUndefined(surface.projectName) }
222 + );
223 + const user =
224 + tree === 'root'
225 + ? consumerUser(project, options)
226 + : yield* devUser(Option.as(surface.projectName, project.projectId), options);
227 + if (Option.isNone(user)) {
228 + const message = options.missingUserMessage ?? defaultMissingUserMessage(tree);
229 + return yield* new MissingActingUserError({
230 + tree: surface.tree,
231 + projectName: surface.projectName,
232 + message: message(surface.projectName),
233 + });
234 + }
235 + return { ...user.value, project } satisfies ActingUser;
236 + });
237 +
238 +/**
239 + * The acting user for a command that also runs without one, by the same rule as `actingUser`.
240 + * On the dev tree it resolves only the project `--project-name` names, so `project` is none when
241 + * the command runs against the directory's project through the default client; on the root
242 + * tree it is the consumer project. Fails only when that project cannot be resolved.
243 + */
244 +export const actingUserOption = (options: Omit<ActingUserOptions, 'missingUserMessage'> = {}) =>
245 + Effect.gen(function* () {
246 + const surface = yield* CommandSurface;
247 + if (ruleTree(surface, options) === 'root') {
248 + const project = yield* resolveCommandProject({ mode: 'consumer' });
249 + return Option.map(
250 + consumerUser(project, options),
251 + (user): ActingUser<Option.Option<ResolvedCommandProject>> => ({
252 + ...user,
253 + project: Option.some(project),
254 + })
255 + );
256 + }
257 + const namedProject = yield* Effect.transposeOption(
258 + Option.map(surface.projectName, projectName =>
259 + resolveCommandProject({ mode: 'developer', projectName })
260 + )
261 + );
262 + const user = yield* devUser(
263 + Option.map(namedProject, project => project.projectId),
264 + options
265 + );
266 + return Option.map(user, (found): ActingUser<Option.Option<ResolvedCommandProject>> => ({
267 + ...found,
268 + project: namedProject,
269 + }));
270 });
271
272 /** A shared flag of the `dev` group. */
ts/packages/cli/src/commands/toolkits/info/toolkits.info.handler.ts
+18 -27
@@ -7,9 +7,7 @@ import { resolveToolRouterSession } from 'src/effects/create-tool-router-session
7 import { extractMessage } from 'src/utils/api-error-extraction';
8 import { reportFailure } from 'src/effects/report-failure';
9 import { commandInputError } from 'src/commands/errors';
10 -import { ProjectContext } from 'src/services/project-context';
11 -import { ComposioUserContext } from 'src/services/user-context';
12 -import { CommandSurface, directoryTestUserId, namedProject } from 'src/commands/surface';
10 +import { actingUserOption, fallbackNotice } from 'src/commands/surface';
11 import { BROWSE_TOOLKITS_HINT, formatToolkitInfo, formatToolkitInfoJson } from '../format';
12 import { ToolkitsInfoRequestError } from './toolkits.info.errors';
13
@@ -28,10 +26,7 @@ const invalidInput = commandInputError('dev toolkits info');
26 */
27 export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
28 Effect.gen(function* () {
31 - const { userId } = yield* CommandSurface;
29 const ui = yield* TerminalUI;
33 - const projectContext = yield* ProjectContext;
34 - const userContext = yield* ComposioUserContext;
30 const clientSingleton = yield* ComposioClientSingleton;
31
32 if (Option.isNone(slug)) {
@@ -43,29 +38,25 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
38
39 const slugValue = slug.value;
40 // Resolved outside the session lookup, whose failures only drop the connection status.
46 - const project = yield* namedProject;
41 + const acting = yield* actingUserOption();
42 const repo = yield* ComposioToolkitsRepository;
48 - const resolvedProjectContext = yield* projectContext.resolve;
49 - const testUserId = directoryTestUserId(
50 - resolvedProjectContext,
51 - Option.map(project, named => named.projectId)
43 + // The client of the project --project-name names; none keeps the default client.
44 + const namedClient = yield* Effect.transposeOption(
45 + Option.map(
46 + Option.flatMap(acting, found => found.project),
47 + project => clientSingleton.getFor({ orgId: project.orgId, projectId: project.projectId })
48 + )
49 );
53 - const globalTestUserId = userContext.data.testUserId;
54 - const resolvedUserId = Option.match(userId, {
55 - onSome: value => Option.some(value),
56 - onNone: () => Option.orElse(testUserId, () => globalTestUserId),
50 + const resolvedUserId = Option.map(acting, found => found.userId);
51 +
52 + // The acting-user helpers leave the test-user notice to the command, so print it here.
53 + yield* Option.match(acting, {
54 + onSome: found =>
55 + Effect.transposeOption(Option.map(fallbackNotice(found), notice => ui.log.warn(notice))),
56 + onNone: () =>
57 + ui.log.info('No test user id found; showing toolkit details without connection status.'),
58 });
59
59 - if (Option.isNone(userId) && Option.isSome(testUserId)) {
60 - yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
61 - } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
62 - yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
63 - } else if (Option.isNone(userId)) {
64 - yield* ui.log.info(
65 - 'No test user id found; showing toolkit details without connection status.'
66 - );
67 - }
68 -
60 const resultOpt = yield* ui
61 .withSpinner(
62 `Fetching toolkit "${slugValue}"...`,
@@ -73,8 +64,8 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
64 const detailedToolkitOpt = yield* repo.getToolkitDetailed(slugValue).pipe(Effect.option);
65
66 if (Option.isSome(resolvedUserId)) {
76 - const client = Option.isSome(project)
77 - ? project.value.client
67 + const client = Option.isSome(namedClient)
68 + ? namedClient.value
69 : yield* clientSingleton.get();
70 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
71 const sessionToolkits = yield* client.toolRouter.session
ts/packages/cli/src/commands/toolkits/list/toolkits.list.handler.ts
+36 -33
@@ -1,13 +1,16 @@
1 import type { SessionToolkitsResponse } from '@composio/client/resources/tool-router';
2 import { Array as Arr, Effect, Option } from 'effect';
3 -import { CommandSurface, directoryTestUserId, namedProject } from 'src/commands/surface';
3 +import {
4 + actingUserOption,
5 + devActingUser,
6 + fallbackNotice,
7 + type ActingUser,
8 +} from 'src/commands/surface';
9 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
10 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
11 import { idempotent } from 'src/services/composio-request';
7 -import { ProjectContext } from 'src/services/project-context';
12 import { reportFailure } from 'src/effects/report-failure';
13 import { TerminalUI } from 'src/services/terminal-ui';
10 -import { ComposioUserContext } from 'src/services/user-context';
14 import { clampLimit } from 'src/ui/clamp-limit';
15 import { extractMessage } from 'src/utils/api-error-extraction';
16 import {
@@ -31,25 +34,28 @@ export type ToolkitsListUser = {
34 readonly fallbackNotice: Option.Option<string>;
35 };
36
37 +const toolkitsListUser = (user: Omit<ActingUser, 'project'>): ToolkitsListUser => ({
38 + id: user.userId,
39 + fallbackNotice: fallbackNotice(user),
40 +});
41 +
42 /**
35 - * The `dev` group's `--user-id`, then the directory's test user id, then the global one.
43 + * The `dev` group's `--user-id`, then the directory's test user id, then the global one: the
44 + * acting-user rule (`devActingUser`) over given candidates.
45 */
46 export const resolveToolkitsListUser = (candidates: {
47 readonly flag: Option.Option<string>;
48 readonly projectTestUserId: Option.Option<string>;
49 readonly globalTestUserId: Option.Option<string>;
50 }): Option.Option<ToolkitsListUser> =>
42 - Option.firstSomeOf([
43 - Option.map(candidates.flag, id => ({ id, fallbackNotice: Option.none<string>() })),
44 - Option.map(candidates.projectTestUserId, id => ({
45 - id,
46 - fallbackNotice: Option.some(`Using test user id "${id}"`),
47 - })),
48 - Option.map(candidates.globalTestUserId, id => ({
49 - id,
50 - fallbackNotice: Option.some(`Using global test user id "${id}"`),
51 - })),
52 - ]);
51 + Option.map(
52 + devActingUser({
53 + flag: candidates.flag,
54 + directoryTestUserId: candidates.projectTestUserId,
55 + globalTestUserId: candidates.globalTestUserId,
56 + }),
57 + toolkitsListUser
58 + );
59
60 /**
61 * Applies `--connected` to the merged rows. The filter needs the session's connection data; when a
@@ -76,29 +82,26 @@ export const applyConnectedFilter = (
82 */
83 export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams) =>
84 Effect.gen(function* () {
79 - const { userId } = yield* CommandSurface;
85 const ui = yield* TerminalUI;
86 const repo = yield* ComposioToolkitsRepository;
87 const clientSingleton = yield* ComposioClientSingleton;
83 - const projectContext = yield* ProjectContext;
84 - const userContext = yield* ComposioUserContext;
88
89 const clampedLimit = clampLimit(limit);
90 // Resolved outside the session lookup, whose failures only drop the connection status.
88 - const project = yield* namedProject;
89 - const resolvedProjectContext = yield* projectContext.resolve;
90 - const user = resolveToolkitsListUser({
91 - flag: userId,
92 - projectTestUserId: directoryTestUserId(
93 - resolvedProjectContext,
94 - Option.map(project, named => named.projectId)
95 - ),
96 - globalTestUserId: userContext.data.testUserId,
97 - });
91 + const acting = yield* actingUserOption();
92 + const user = Option.map(acting, toolkitsListUser);
93 + // The client of the project --project-name names; none keeps the default client.
94 + const namedClient = yield* Effect.transposeOption(
95 + Option.map(
96 + Option.flatMap(acting, found => found.project),
97 + project => clientSingleton.getFor({ orgId: project.orgId, projectId: project.projectId })
98 + )
99 + );
100
99 - const fallbackNotice = Option.flatMap(user, resolved => resolved.fallbackNotice);
100 - if (Option.isSome(fallbackNotice)) {
101 - yield* ui.log.warn(fallbackNotice.value);
101 + // The acting-user helpers leave the test-user notice to the command, so print it here.
102 + const notice = Option.flatMap(user, resolved => resolved.fallbackNotice);
103 + if (Option.isSome(notice)) {
104 + yield* ui.log.warn(notice.value);
105 yield* ui.log.message('To show status for a specific user, use `--user-id`.');
106 }
107
@@ -119,8 +122,8 @@ export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams)
122 onNone: () => Effect.succeedNone,
123 onSome: resolved =>
124 Effect.gen(function* () {
122 - const client = yield* Option.match(project, {
123 - onSome: named => Effect.succeed(named.client),
125 + const client = yield* Option.match(namedClient, {
126 + onSome: Effect.succeed,
127 onNone: () => clientSingleton.get(),
128 });
129 const { sessionId } = yield* resolveToolRouterSession(client, resolved.id);
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+37 -53
@@ -1,5 +1,5 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 -import { CommandSurface, directoryTestUserId, missingUserIdMessage } from 'src/commands/surface';
2 +import { actingUser, CommandSurface } from 'src/commands/surface';
3 import { commandInputError } from 'src/commands/errors';
4 import { ExpectedFailure } from 'src/effects/expected-failure';
5 import { Argument, Command, Flag } from 'effect/cli';
@@ -28,8 +28,6 @@ import type {
28 ToolExecuteResponse,
29 } from 'src/services/tools-executor';
30 import type { ToolkitProjectScope } from 'src/services/composio-clients';
31 -import { ComposioUserContext } from 'src/services/user-context';
32 -import { ProjectContext } from 'src/services/project-context';
31 import { trackCliCodactFailureEffect, trackCliEventEffect } from 'src/analytics/dispatch';
32 import { cliInvocationContext } from 'src/services/runtime-cli-context';
33 import {
@@ -763,7 +761,6 @@ type RunToolsExecuteParams = {
761 data: Option.Option<string>;
762 file: Option.Option<string>;
763 account: Option.Option<string>;
766 - userId: Option.Option<string>;
764 projectName: Option.Option<string>;
765 surface: 'root' | 'dev';
766 projectMode: 'consumer' | 'developer';
@@ -783,6 +780,7 @@ type ParallelExecuteSpec = {
780 };
781
782 type ParsedParallelExecuteArgs = SharedRunToolsExecuteParams & {
783 + readonly userId: Option.Option<string>;
784 readonly specs: ReadonlyArray<ParallelExecuteSpec>;
785 };
786
@@ -872,44 +870,30 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
870 const parsedArgs = yield* parseArguments(input);
871 const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
872
875 - // The root tree has no --project-name.
876 - const projectName = Option.filter(params.projectName, () => params.surface !== 'root');
877 - const resolvedProject = yield* resolveCommandProject({
878 - mode: params.projectMode,
879 - projectName: Option.getOrUndefined(projectName),
880 - });
881 - const clientSingleton = yield* ComposioClientSingleton;
882 - const userContext = yield* ComposioUserContext;
883 - const projectContext = yield* ProjectContext;
884 -
885 - const localProjectContext = yield* projectContext.resolve.pipe(
886 - Effect.catch(() => Effect.succeed(Option.none()))
887 - );
888 - const localTestUserId = directoryTestUserId(
889 - localProjectContext,
890 - Option.as(projectName, resolvedProject.projectId)
873 + const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser(
874 + params.surface === 'root'
875 + ? {
876 + // As before `actingUser`, an empty consumer user id still counts as a user.
877 + legacy: { acceptEmptyConsumerUserId: true },
878 + // Keep the earlier message, which mentions --user-id, over the root tree's default.
879 + missingUserMessage: () =>
880 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
881 + }
882 + : {}
883 + ).pipe(
884 + // Re-fail with the `ToolExecutionError` the command has always failed with, so
885 + // `cli.command.failed` keeps reporting it as `error_name`.
886 + Effect.catchTag('commands/MissingActingUserError', error =>
887 + Effect.fail(
888 + new ToolExecutionError({
889 + reason: 'missing_user_id',
890 + toolSlug: params.slug,
891 + message: error.message,
892 + })
893 + )
894 + )
895 );
892 - const resolvedUserId =
893 - resolvedProject.projectType === 'CONSUMER'
894 - ? Option.fromNullishOr(resolvedProject.consumerUserId)
895 - : Option.match(params.userId, {
896 - onSome: value => Option.some(value),
897 - onNone: () => Option.orElse(localTestUserId, () => userContext.data.testUserId),
898 - });
899 -
900 - if (Option.isNone(resolvedUserId)) {
901 - return yield* new ToolExecutionError({
902 - reason: 'missing_user_id',
903 - toolSlug: params.slug,
904 - message: missingUserIdMessage(
905 - projectName,
906 - params.projectMode === 'developer'
907 - ? 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'
908 - : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
909 - ),
910 - });
911 - }
912 -
896 + const clientSingleton = yield* ComposioClientSingleton;
897 const client = yield* clientSingleton.getFor({
898 orgId: resolvedProject.orgId,
899 projectId: resolvedProject.projectId,
@@ -921,7 +905,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
905 const selectedConnectedAccountId = yield* resolveConnectedAccountForToolkit({
906 client,
907 toolkitSlug,
924 - userId: resolvedUserId.value,
908 + userId: resolvedUserId,
909 selector: params.account,
910 });
911 const args = Option.isSome(params.file)
@@ -962,11 +946,11 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
946 executor,
947 resolvedProject,
948 args,
965 - resolvedUserId: resolvedUserId.value,
949 + resolvedUserId,
950 selectedConnectedAccountId,
951 executeOutputDir,
952 executeParams: {
969 - userId: resolvedUserId.value,
953 + userId: resolvedUserId,
954 target: executesViaDashboard
955 ? { kind: 'dashboard', orgId: resolvedProject.orgId }
956 : { kind: 'backend' },
@@ -1625,7 +1609,6 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
1609 () =>
1610 resolveSchemaContext({
1611 account: params.account,
1628 - userId: params.userId,
1612 projectName: params.projectName,
1613 surface: params.surface,
1614 projectMode: params.projectMode,
@@ -1727,7 +1710,6 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1710 data: spec.data,
1711 file: Option.none(),
1712 account: spec.account,
1730 - userId: params.userId,
1713 projectName: params.projectName,
1714 surface: params.surface,
1715 projectMode: params.projectMode,
@@ -1927,14 +1909,18 @@ const runParallelFromCommand = (config: {
1909 allowProjectName: config.surface === 'dev',
1910 });
1911 // The tail starts after the command name, so the `dev` group's shared flags given before
1930 - // it reach the command only through the surface.
1912 + // it reach the command only through the surface; the tail's own win.
1913 const surface = yield* CommandSurface;
1914 + const userId = Option.orElse(parsed.userId, () => surface.userId);
1915 + const projectName = Option.orElse(parsed.projectName, () => surface.projectName);
1916 return yield* runParallelToolsExecuteFromParsed({
1917 ...parsed,
1918 ...config,
1935 - userId: Option.orElse(parsed.userId, () => surface.userId),
1936 - projectName: Option.orElse(parsed.projectName, () => surface.projectName),
1937 - });
1919 + userId,
1920 + projectName,
1921 + }).pipe(
1922 + Effect.provideService(CommandSurface, CommandSurface.of({ ...surface, userId, projectName }))
1923 + );
1924 });
1925
1926 const executeExamples = [
@@ -2016,7 +2002,6 @@ export const rootToolsCmd$Execute = Command.make(
2002 data,
2003 file,
2004 account,
2019 - userId: Option.none(),
2005 projectName: Option.none(),
2006 surface: 'root',
2007 projectMode: 'consumer',
@@ -2067,7 +2052,7 @@ export const devToolsCmd$Execute = Command.make(
2052 skipChecks,
2053 }) =>
2054 Effect.gen(function* () {
2070 - const { userId, projectName } = yield* CommandSurface;
2055 + const { projectName } = yield* CommandSurface;
2056 if (parallel) {
2057 return yield* runParallelFromCommand({
2058 surface: 'dev',
@@ -2087,7 +2072,6 @@ export const devToolsCmd$Execute = Command.make(
2072 data,
2073 file,
2074 account,
2090 - userId,
2075 projectName,
2076 surface: 'dev',
2077 projectMode: 'developer',
ts/packages/cli/src/commands/tools/search/tools.search.handler.ts
+17 -24
@@ -1,16 +1,14 @@
1 import { Effect, Option } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 -import { CommandSurface } from 'src/commands/surface';
3 +import { actingUser, CommandSurface } from 'src/commands/surface';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { failedWith } from 'src/effects/request-error';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { clampLimit } from 'src/ui/clamp-limit';
8 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9 import { buildMinimalPayloadFromSchema } from 'src/ui/build-minimal-payload';
10 -import { ComposioUserContext } from 'src/services/user-context';
10 import { ComposioClientSingleton } from 'src/services/composio-clients';
11 import { idempotent } from 'src/services/composio-request';
13 -import { resolveCommandProject } from 'src/services/command-project';
12 import { isRemoteCustomToolSlug } from 'src/utils/remote-custom-toolkit';
13 import { toolInputRequiredError } from 'src/utils/tool-input-required';
14 import {
@@ -108,8 +106,7 @@ const buildSearchJsonPayload = (params: {
106 export const runToolsSearch = (params: ToolsSearchParams) =>
107 Effect.gen(function* () {
108 const ui = yield* TerminalUI;
111 - const { tree, userId, projectName } = yield* CommandSurface;
112 - const userContext = yield* ComposioUserContext;
109 + const { tree } = yield* CommandSurface;
110
111 const clampedLimit = clampLimit(params.limit);
112 const emitHuman = params.human;
@@ -128,23 +125,19 @@ export const runToolsSearch = (params: ToolsSearchParams) =>
125 : undefined;
126
127 const runSearchRequest = Effect.gen(function* () {
131 - const resolvedProject = yield* resolveCommandProject({
132 - mode: 'consumer',
133 - projectName: Option.getOrUndefined(projectName),
134 - });
135 - const resolvedUserId =
136 - resolvedProject.projectType === 'CONSUMER'
137 - ? Option.fromNullishOr(resolvedProject.consumerUserId)
138 - : Option.match(userId, {
139 - onSome: value => Option.some(value),
140 - onNone: () => userContext.data.testUserId,
141 - });
142 - if (Option.isNone(resolvedUserId)) {
143 - return yield* invalidSearchInput(
128 + const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser({
129 + // As before `actingUser`, an empty consumer user id still counts as a user.
130 + legacy: { acceptEmptyConsumerUserId: true },
131 + // Keep the earlier message, which mentions --user-id, over the root tree's default.
132 + missingUserMessage: () =>
133 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
145 - '--user-id'
146 - );
147 - }
134 + }).pipe(
135 + // Re-fail with the `CommandInputError` the command has always failed with, so
136 + // `cli.command.failed` keeps reporting it as `error_name`.
137 + Effect.catchTag('commands/MissingActingUserError', error =>
138 + Effect.fail(invalidSearchInput(error.message, '--user-id'))
139 + )
140 + );
141 const clientSingleton = yield* ComposioClientSingleton;
142 const client = yield* clientSingleton.getFor({
143 orgId: resolvedProject.orgId,
@@ -153,10 +146,10 @@ export const runToolsSearch = (params: ToolsSearchParams) =>
146 if (resolvedProject.projectType === 'CONSUMER') {
147 yield* primeConsumerConnectedToolkitsCacheInBackground({
148 orgId: resolvedProject.orgId,
156 - consumerUserId: resolvedUserId.value,
149 + consumerUserId: resolvedUserId,
150 });
151 }
159 - const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
152 + const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId, {
153 toolkits: toolkitList,
154 cacheScope:
155 resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
@@ -233,7 +226,7 @@ export const runToolsSearch = (params: ToolsSearchParams) =>
226 resolvedProject.projectType === 'CONSUMER'
227 ? {
228 orgId: resolvedProject.orgId,
236 - consumerUserId: resolvedUserId.value,
229 + consumerUserId: resolvedUserId,
230 toolRouterSessionId: sessionId,
231 }
232 : undefined,
ts/packages/cli/src/commands/triggers/create/triggers.create.handler.ts
+8 -18
@@ -1,12 +1,10 @@
1 import { Effect, Match, Option, Result } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 -import { CommandSurface } from 'src/commands/surface';
3 +import { actingUserOption, fallbackNotice } 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';
7 -import { ProjectContext } from 'src/services/project-context';
7 import { TerminalUI } from 'src/services/terminal-ui';
9 -import { ComposioUserContext } from 'src/services/user-context';
8 import { parseJsonRecord, type JsonParsingError } from 'src/utils/parse-json';
9
10 export type TriggersCreateParams = {
@@ -61,9 +59,6 @@ export const runTriggersCreate = ({
59 Effect.gen(function* () {
60 const ui = yield* TerminalUI;
61 const repo = yield* ComposioToolkitsRepository;
64 - const { userId } = yield* CommandSurface;
65 - const projectContext = yield* ProjectContext;
66 - const userContext = yield* ComposioUserContext;
62
63 if (Option.isNone(triggerName)) {
64 return yield* invalidInput(
@@ -77,20 +72,15 @@ export const runTriggersCreate = ({
72 return yield* invalidTriggerConfig(parsedTriggerConfig.failure);
73 }
74
80 - const project = yield* projectContext.resolve;
81 - const projectTestUserId = Option.flatMap(project, keys => keys.testUserId);
82 - const globalTestUserId = userContext.data.testUserId;
83 - const resolvedUserId = userId.pipe(
84 - Option.orElse(() => projectTestUserId),
85 - Option.orElse(() => globalTestUserId)
86 - );
75 + // The group rejects --project-name, so this is the directory's project.
76 + const acting = yield* actingUserOption();
77 + const resolvedUserId = Option.map(acting, found => found.userId);
78
79 // A defaulted user id must own the connected account on a 2FA project, so name it.
89 - if (Option.isNone(userId) && Option.isSome(projectTestUserId)) {
90 - yield* ui.log.warn(`Using test user id "${projectTestUserId.value}"`);
91 - } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
92 - yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
93 - }
80 + // The acting-user helpers leave the test-user notice to the command, so print it here.
81 + yield* Effect.transposeOption(
82 + Option.map(Option.flatMap(acting, fallbackNotice), notice => ui.log.warn(notice))
83 + );
84
85 const createdOpt = yield* ui
86 .withSpinner(
ts/packages/cli/test/__utils__/layers/accounts.ts
+11 -1
@@ -49,6 +49,13 @@ export interface AccountTestData {
49 SessionRetrieveInfoResponse | ((scope: MockRequestScope) => SessionRetrieveInfoResponse);
50 organizations?: ReadonlyArray<OrganizationSummary>;
51 projects?: ReadonlyArray<OrgProject>;
52 + /**
53 + * The `consumer_user_id` the consumer project resolve endpoint answers with. Omitted (the
54 + * default) serves `consumer-user-<orgId>`; `''` serves an empty id (the backend's
55 + * "logged in, but no consumer user" shape); `null` serves no field at all, which only a
56 + * mock can answer — the real response schema requires the string.
57 + */
58 + consumerUserId?: string | null;
59 connectedToolkits?: ReadonlyArray<string>;
60 latestToolVersion?: { readonly tool_slug: string; readonly version: string };
61 projectApiKey?: string;
@@ -158,7 +165,10 @@ export const mockAccountResources = (accountData: AccountTestData, base: MockReq
165 org_id: orgId,
166 project_type: 'CONSUMER' as const,
167 config: { consumer_experience_enabled: true, enhanced_controls: false },
161 - consumer_user_id: `consumer-user-${orgId}`,
168 + consumer_user_id:
169 + accountData.consumerUserId === null
170 + ? undefined
171 + : (accountData.consumerUserId ?? `consumer-user-${orgId}`),
172 });
173 },
174 },
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts
+47 -1
@@ -25,6 +25,7 @@ import {
25 missingArgumentMessage,
26 } from 'src/commands/connected-accounts/link/connected-accounts.link.format';
27 import { CommandSurface } from 'src/commands/surface';
28 +import { MissingLinkUserIdError } from 'src/commands/connected-accounts/link/connected-accounts.link.errors';
29 import { CliUserConfig } from 'src/models/cli-user-config';
30 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
31 import type { ProjectKeys } from 'src/models/project-keys';
@@ -108,6 +109,8 @@ const params = (
109 interface LinkFixture {
110 readonly surface?: Layer.Layer<CommandSurface>;
111 readonly accounts?: ReadonlyArray<ConnectedAccountItem>;
112 + /** The `consumer_user_id` the consumer project resolves with; see `AccountTestData`. */
113 + readonly consumerUserId?: string | null;
114 readonly directoryProject?: Option.Option<ProjectKeys>;
115 readonly globalTestUserId?: Option.Option<string>;
116 /** Replaces the `link.create` answer, e.g. to fail it. */
@@ -195,7 +198,10 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
198 // client's full response types; `test-layer.ts` shadows its mock client the same way.
199 ({
200 ...baseClient,
198 - ...mockAccountResources({ projects: [DEVELOPER_PROJECT] }, scope),
201 + ...mockAccountResources(
202 + { projects: [DEVELOPER_PROJECT], consumerUserId: fixture.consumerUserId },
203 + scope
204 + ),
205 ...connectedAccountsResources,
206 link: {
207 create: (linkParams: { auth_config_id: string; user_id: string }) =>
@@ -832,6 +838,46 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
838 })
839 );
840
841 + it.effect(
842 + '[Given] no consumer user and no test user [Then] fails with the tool-router missing-user error',
843 + () =>
844 + Effect.gen(function* () {
845 + const { layer, requests } = linkHandlerTest({ consumerUserId: null });
846 + const failure = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
847 + Effect.flip,
848 + Effect.provide(layer)
849 + );
850 +
851 + // The flow re-fails `actingUser`'s expected failure as its own expected error, so
852 + // `cli.command.failed` keeps reporting `commands/MissingLinkUserIdError`.
853 + expect(failure).toBeInstanceOf(MissingLinkUserIdError);
854 + expect(failure).toMatchObject({
855 + flow: 'tool-router',
856 + message:
857 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
858 + });
859 + expect(requests).toEqual([]);
860 + })
861 + );
862 +
863 + it.effect('[Given] an empty consumer user id [Then] the flow still acts as it and links', () =>
864 + Effect.gen(function* () {
865 + const { layer, requests } = linkHandlerTest({ consumerUserId: '' });
866 + yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
867 + Effect.andThen(lines),
868 + Effect.provide(layer)
869 + );
870 +
871 + // As before `actingUser`, the flow's legacy options accept the empty id as the user.
872 + expect(requests).toEqual([
873 + {
874 + operation: 'toolRouter.session.link',
875 + params: { sessionId: 'trs_handler_test', toolkit: 'gmail' },
876 + },
877 + ]);
878 + })
879 + );
880 +
881 it.effect('[Given] a redirect URL without an http scheme [Then] warns and still waits', () =>
882 Effect.gen(function* () {
883 const { layer } = linkHandlerTest({
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+24
@@ -328,4 +328,28 @@ describe('CLI: composio connections list account identity', () => {
328 })
329 );
330 });
331 +
332 + layer(
333 + TestLive({
334 + baseConfigProvider: testConfigProvider,
335 + accountData: { consumerUserId: '' },
336 + })
337 + )(it => {
338 + it.effect(
339 + '[Given] an empty consumer user id [Then] fails with the command defect and its message',
340 + () =>
341 + Effect.gen(function* () {
342 + const userContext = yield* ComposioUserContext;
343 + yield* userContext.login('test_api_key', 'org_test');
344 + const failure = yield* cli(['connections', 'list']).pipe(Effect.flip);
345 +
346 + // The command has always failed with this class as a defect, so `actingUser`'s
347 + // expected failure is re-tagged; the tag and the message are both load-bearing.
348 + expect(failure).toMatchObject({
349 + _tag: 'commands/MissingConnectionsConsumerUserIdError',
350 + message: 'Missing consumer user id. Run `composio login` and try again.',
351 + });
352 + })
353 + );
354 + });
355 });
ts/packages/cli/test/src/commands/connections/remove/connections.remove.cmd.test.ts
+25
@@ -3,6 +3,7 @@ import { describe, expect, layer } from '@effect/vitest';
3 import { ConfigProvider, Effect } from 'effect';
4 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 +import { MissingConnectionRemovalConsumerUserIdError } from 'src/commands/connections/remove/connections.remove.errors';
7 import { ComposioUserContext } from 'src/services/user-context';
8 import { cli, TestLive, MockConsole } from 'test/__utils__';
9 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
@@ -361,4 +362,28 @@ describe('CLI: composio connections remove', () => {
362 })
363 );
364 });
365 +
366 + layer(
367 + TestLive({
368 + baseConfigProvider: testConfigProvider,
369 + accountData: { consumerUserId: '' },
370 + })
371 + )(it => {
372 + it.effect(
373 + '[Given] an empty consumer user id [Then] fails with the command defect and its message',
374 + () =>
375 + Effect.gen(function* () {
376 + const userContext = yield* ComposioUserContext;
377 + yield* userContext.login('test_api_key', 'org_test');
378 + const failure = yield* cli(['connections', 'remove', 'gmail', '--yes']).pipe(Effect.flip);
379 +
380 + // The removal has always failed with this class as a defect, so `actingUser`'s
381 + // expected failure is re-tagged; the tag and the message are both load-bearing.
382 + expect(failure).toBeInstanceOf(MissingConnectionRemovalConsumerUserIdError);
383 + expect(failure).toMatchObject({
384 + message: 'Missing consumer user id. Run `composio login` and try again.',
385 + });
386 + })
387 + );
388 + });
389 });
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+28
@@ -6,6 +6,7 @@ import { ListenCommandError } from 'src/commands/listen.cmd';
6 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
7 import { ConnectedAccountResolutionError } from 'src/services/connected-account-selection';
8 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
9 +import { ComposioUserContext } from 'src/services/user-context';
10 import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
11 import { cli, MockConsole, TestLive } from 'test/__utils__';
12 import { failingFileWrites } from 'test/__utils__/services/failing-file-writes';
@@ -573,4 +574,31 @@ describe('CLI: composio listen', () => {
574 })
575 );
576 });
577 +
578 + layer(TestLive({ baseConfigProvider: testConfigProvider, accountData: { consumerUserId: '' } }))(
579 + '[Given] no consumer user in the project context',
580 + it => {
581 + it.effect('[Then] fails before subscribing with the preserved message', () =>
582 + Effect.gen(function* () {
583 + const userContext = yield* ComposioUserContext;
584 + yield* userContext.login('test_api_key', 'org_test');
585 + yield* enableListen;
586 + const failure = yield* cli([
587 + 'listen',
588 + 'composio.connected_account.expired',
589 + '--max-events',
590 + '1',
591 + ]).pipe(Effect.flip);
592 +
593 + // The command has always failed with this class as a defect, so `actingUser`'s
594 + // expected failure is re-tagged; the reason and the message are both load-bearing.
595 + expect(failure).toBeInstanceOf(ListenCommandError);
596 + expect(failure).toMatchObject({
597 + reason: 'project_context',
598 + message: 'No consumer user is available in the current project context.',
599 + });
600 + })
601 + );
602 + }
603 + );
604 });
ts/packages/cli/test/src/commands/surface.acting-user.test.ts new
+373
@@ -0,0 +1,373 @@
1 +import type { ComposioClientShape } from '@composio/client/effect';
2 +import { describe, expect, it } from '@effect/vitest';
3 +import { Effect, Layer, Option } from 'effect';
4 +import {
5 + actingUser,
6 + actingUserOption,
7 + CommandSurface,
8 + fallbackNotice,
9 + MissingActingUserError,
10 + type ActingUserOptions,
11 + type ActingUserSource,
12 + type CommandTree,
13 +} from 'src/commands/surface';
14 +import type { ProjectKeys } from 'src/models/project-keys';
15 +import { ComposioClientSingleton } from 'src/services/composio-clients';
16 +import { ProjectContext } from 'src/services/project-context';
17 +import { ComposioUserContext } from 'src/services/user-context';
18 +import { mockAccountResources } from 'test/__utils__/layers/accounts';
19 +import { makeOrgProject } from 'test/__utils__/models/account';
20 +
21 +const ORG_ID = 'org_test';
22 +const CONSUMER_USER_ID = `consumer-user-${ORG_ID}`;
23 +const CONSUMER_PROJECT_ID = 'consumer_project_test';
24 +const DIRECTORY_PROJECT_ID = 'proj_directory';
25 +const OTHER_PROJECT_ID = 'proj_other';
26 +
27 +const projects = [
28 + makeOrgProject({ id: DIRECTORY_PROJECT_ID, name: 'directory', orgId: ORG_ID }),
29 + makeOrgProject({ id: OTHER_PROJECT_ID, name: 'other', orgId: ORG_ID }),
30 +];
31 +
32 +/** The candidates present, named after the one the dev tree's rule picks first. */
33 +type Candidates = 'flag' | 'directory' | 'global' | 'none';
34 +/** `--project-name`: absent, the directory's own project, or another one. */
35 +type ProjectName = 'absent' | 'same' | 'other';
36 +
37 +interface Fixture {
38 + readonly tree: CommandTree;
39 + readonly candidates: Candidates;
40 + readonly projectName: ProjectName;
41 + /** The consumer user id the consumer project resolves with. */
42 + readonly consumerUserId?: string;
43 +}
44 +
45 +const CANDIDATE_ORDER: ReadonlyArray<Candidates> = ['flag', 'directory', 'global', 'none'];
46 +
47 +const PROJECT_NAMES: Record<ProjectName, Option.Option<string>> = {
48 + absent: Option.none(),
49 + same: Option.some('directory'),
50 + other: Option.some('other'),
51 +};
52 +
53 +const actingUserLayer = (fixture: Fixture) => {
54 + const has = (candidate: Exclude<Candidates, 'none'>) =>
55 + CANDIDATE_ORDER.indexOf(candidate) >= CANDIDATE_ORDER.indexOf(fixture.candidates);
56 + const directory: ProjectKeys = {
57 + orgId: ORG_ID,
58 + projectId: DIRECTORY_PROJECT_ID,
59 + projectName: Option.some('directory'),
60 + orgName: Option.none(),
61 + email: Option.none(),
62 + testUserId: has('directory') ? Option.some('directory-user') : Option.none(),
63 + };
64 + const resources = mockAccountResources({ projects }, {});
65 + // The account resources answer only the fields `resolveCommandProject` reads.
66 + const client = {
67 + ...resources,
68 + _internal: {
69 + org: {
70 + consumer: {
71 + ...resources._internal.org.consumer,
72 + project: {
73 + resolve: (
74 + ...args: Parameters<typeof resources._internal.org.consumer.project.resolve>
75 + ) =>
76 + resources._internal.org.consumer.project.resolve(...args).pipe(
77 + Effect.map(project => ({
78 + ...project,
79 + consumer_user_id: fixture.consumerUserId ?? project.consumer_user_id,
80 + }))
81 + ),
82 + },
83 + },
84 + },
85 + },
86 + } as unknown as ComposioClientShape;
87 +
88 + return Layer.mergeAll(
89 + Layer.succeed(
90 + CommandSurface,
91 + CommandSurface.of({
92 + tree: fixture.tree,
93 + userId: has('flag') ? Option.some('flag-user') : Option.none(),
94 + projectName: PROJECT_NAMES[fixture.projectName],
95 + })
96 + ),
97 + Layer.succeed(
98 + ComposioUserContext,
99 + ComposioUserContext.of({
100 + data: {
101 + apiKey: Option.some('uak_test'),
102 + baseURL: 'https://mock.invalid',
103 + webURL: 'https://platform.mock.invalid',
104 + orgId: Option.some(ORG_ID),
105 + projectId: Option.none(),
106 + testUserId: has('global') ? Option.some('global-user') : Option.none(),
107 + },
108 + backendMismatch: Option.none(),
109 + isLoggedIn: () => true,
110 + logout: Effect.void,
111 + login: () => Effect.void,
112 + update: () => Effect.void,
113 + })
114 + ),
115 + Layer.succeed(ProjectContext, ProjectContext.of({ resolve: Effect.succeedSome(directory) })),
116 + Layer.succeed(
117 + ComposioClientSingleton,
118 + ComposioClientSingleton.of({
119 + get: () => Effect.succeed(client),
120 + getFor: () => Effect.succeed(client),
121 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
122 + })
123 + )
124 + );
125 +};
126 +
127 +/** The acting user the glossary's rule names, or none when it names no one. */
128 +const expectedUser = ({
129 + tree,
130 + candidates,
131 + projectName,
132 +}: Fixture): Option.Option<{ readonly userId: string; readonly source: ActingUserSource }> => {
133 + if (tree === 'root') {
134 + return Option.some({ userId: CONSUMER_USER_ID, source: 'consumer' });
135 + }
136 + if (candidates === 'flag') {
137 + return Option.some({ userId: 'flag-user', source: 'flag' });
138 + }
139 + // The directory test user stands in only for the directory's own project.
140 + if (candidates === 'directory' && projectName !== 'other') {
141 + return Option.some({ userId: 'directory-user', source: 'directory-test-user' });
142 + }
143 + return candidates === 'none'
144 + ? Option.none()
145 + : Option.some({ userId: 'global-user', source: 'global-test-user' });
146 +};
147 +
148 +/** The id of the project the user is resolved against. */
149 +const expectedProjectId = ({ tree, projectName }: Fixture) =>
150 + tree === 'root'
151 + ? CONSUMER_PROJECT_ID
152 + : projectName === 'other'
153 + ? OTHER_PROJECT_ID
154 + : DIRECTORY_PROJECT_ID;
155 +
156 +const TREES: ReadonlyArray<CommandTree> = ['root', 'dev'];
157 +const PROJECT_NAME_CASES: ReadonlyArray<ProjectName> = ['absent', 'same', 'other'];
158 +
159 +// Every combination of the three axes.
160 +const cases = TREES.flatMap(tree =>
161 + CANDIDATE_ORDER.flatMap(candidates =>
162 + PROJECT_NAME_CASES.map(projectName => ({
163 + tree,
164 + candidates,
165 + projectName,
166 + name: `${tree}, ${candidates} first, --project-name ${projectName}`,
167 + }))
168 + )
169 +);
170 +
171 +const run = <
172 + A,
173 + E,
174 + R extends CommandSurface | ComposioUserContext | ProjectContext | ComposioClientSingleton,
175 +>(
176 + effect: Effect.Effect<A, E, R>,
177 + fixture: Fixture
178 +) => effect.pipe(Effect.provide(actingUserLayer(fixture)));
179 +
180 +describe('actingUser', () => {
181 + it.effect.each(cases)('[Given] $name [Then] acts as the rule’s user', fixture =>
182 + Effect.gen(function* () {
183 + const result = yield* run(Effect.result(actingUser()), fixture);
184 + const expected = expectedUser(fixture);
185 +
186 + if (Option.isNone(expected)) {
187 + expect(result).toMatchObject({ failure: { _tag: 'commands/MissingActingUserError' } });
188 + return;
189 + }
190 + expect(result).toMatchObject({
191 + success: { ...expected.value, project: { projectId: expectedProjectId(fixture) } },
192 + });
193 + })
194 + );
195 +
196 + it.effect.each([
197 + {
198 + tree: 'root',
199 + projectName: 'absent',
200 + message: 'Missing consumer user id. Run `composio login` and try again.',
201 + },
202 + {
203 + tree: 'dev',
204 + projectName: 'absent',
205 + message:
206 + 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
207 + },
208 + {
209 + tree: 'dev',
210 + projectName: 'other',
211 + message:
212 + 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
213 + },
214 + ] as const)(
215 + '[Given] no user on the $tree tree, --project-name $projectName [Then] fails with the tree’s message',
216 + ({ tree, projectName, message }) =>
217 + Effect.gen(function* () {
218 + const error = yield* run(Effect.flip(actingUser()), {
219 + tree,
220 + projectName,
221 + candidates: 'none',
222 + consumerUserId: '',
223 + });
224 +
225 + expect(error).toBeInstanceOf(MissingActingUserError);
226 + expect(error).toMatchObject({ tree, projectName: PROJECT_NAMES[projectName], message });
227 + })
228 + );
229 +
230 + it.effect('[Given] a command’s own message [Then] fails with it, given --project-name', () =>
231 + Effect.gen(function* () {
232 + const error = yield* run(
233 + Effect.flip(
234 + actingUser({
235 + missingUserMessage: name => `No user for ${Option.getOrElse(name, () => 'none')}.`,
236 + })
237 + ),
238 + { tree: 'dev', projectName: 'other', candidates: 'none' }
239 + );
240 +
241 + expect(error).toMatchObject({ message: 'No user for other.' });
242 + })
243 + );
244 +
245 + it.effect.each([
246 + {
247 + name: 'the consumer project without --project-name ignores --user-id',
248 + options: { legacy: { consumerWithoutProjectName: true } },
249 + fixture: { tree: 'dev', candidates: 'flag', projectName: 'absent' },
250 + expected: { userId: CONSUMER_USER_ID, source: 'consumer', projectId: CONSUMER_PROJECT_ID },
251 + },
252 + {
253 + name: 'the consumer project still yields to --project-name',
254 + options: { legacy: { consumerWithoutProjectName: true } },
255 + fixture: { tree: 'dev', candidates: 'directory', projectName: 'same' },
256 + expected: {
257 + userId: 'directory-user',
258 + source: 'directory-test-user',
259 + projectId: DIRECTORY_PROJECT_ID,
260 + },
261 + },
262 + {
263 + name: 'skipping the directory test user falls back to the global one',
264 + options: { legacy: { skipDirectoryTestUser: true } },
265 + fixture: { tree: 'dev', candidates: 'directory', projectName: 'same' },
266 + expected: {
267 + userId: 'global-user',
268 + source: 'global-test-user',
269 + projectId: DIRECTORY_PROJECT_ID,
270 + },
271 + },
272 + ] satisfies ReadonlyArray<{
273 + name: string;
274 + options: ActingUserOptions;
275 + fixture: Fixture;
276 + expected: { userId: string; source: ActingUserSource; projectId: string };
277 + }>)('[Given] legacy: $name', ({ options, fixture, expected }) =>
278 + Effect.gen(function* () {
279 + const user = yield* run(actingUser(options), fixture);
280 +
281 + expect(user).toMatchObject({
282 + userId: expected.userId,
283 + source: expected.source,
284 + project: { projectId: expected.projectId },
285 + });
286 + })
287 + );
288 +});
289 +
290 +// Commands passing `acceptEmptyConsumerUserId` count an empty consumer user id as a user.
291 +describe('an empty consumer user id', () => {
292 + const ACCEPT_EMPTY = { legacy: { acceptEmptyConsumerUserId: true } } satisfies ActingUserOptions;
293 + const sites = [
294 + { sites: 'execute, search, link, run', options: ACCEPT_EMPTY, tree: 'root', accepted: true },
295 + {
296 + sites: 'link on the dev tree without --project-name',
297 + options: { legacy: { ...ACCEPT_EMPTY.legacy, consumerWithoutProjectName: true } },
298 + tree: 'dev',
299 + accepted: true,
300 + },
301 + { sites: 'connections list/remove, listen, proxy', options: {}, tree: 'root', accepted: false },
302 + ] satisfies ReadonlyArray<{
303 + sites: string;
304 + options: ActingUserOptions;
305 + tree: CommandTree;
306 + accepted: boolean;
307 + }>;
308 + const fixture = (tree: CommandTree): Fixture => ({
309 + tree,
310 + candidates: 'flag',
311 + projectName: 'absent',
312 + consumerUserId: '',
313 + });
314 +
315 + it.effect.each(sites)(
316 + '[Given] $sites [Then] actingUser accepts it: $accepted',
317 + ({ options, tree, accepted }) =>
318 + Effect.gen(function* () {
319 + const result = yield* run(Effect.result(actingUser(options)), fixture(tree));
320 +
321 + expect(result).toMatchObject(
322 + accepted
323 + ? { success: { userId: '', source: 'consumer' } }
324 + : { failure: { _tag: 'commands/MissingActingUserError' } }
325 + );
326 + })
327 + );
328 +
329 + it.effect.each(sites)(
330 + '[Given] $sites [Then] actingUserOption finds it: $accepted',
331 + ({ options, tree, accepted }) =>
332 + Effect.gen(function* () {
333 + const user = yield* run(actingUserOption(options), fixture(tree));
334 +
335 + expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(
336 + accepted ? Option.some({ userId: '', source: 'consumer' }) : Option.none()
337 + );
338 + })
339 + );
340 +});
341 +
342 +describe('actingUserOption', () => {
343 + it.effect.each(cases)('[Given] $name [Then] finds the rule’s user, or none', fixture =>
344 + Effect.gen(function* () {
345 + const user = yield* run(actingUserOption(), fixture);
346 + const expected = expectedUser(fixture);
347 + // Only the project --project-name names is resolved on the dev tree.
348 + const project =
349 + fixture.tree === 'dev' && fixture.projectName === 'absent'
350 + ? Option.none()
351 + : Option.some(expectedProjectId(fixture));
352 +
353 + expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(expected);
354 + expect(
355 + Option.map(user, found => Option.map(found.project, resolved => resolved.projectId))
356 + ).toEqual(Option.map(expected, () => project));
357 + })
358 + );
359 +});
360 +
361 +describe('fallbackNotice', () => {
362 + it.each([
363 + { source: 'consumer', expected: Option.none() },
364 + { source: 'flag', expected: Option.none() },
365 + { source: 'directory-test-user', expected: Option.some('Using test user id "u"') },
366 + { source: 'global-test-user', expected: Option.some('Using global test user id "u"') },
367 + ] as const)(
368 + '[Given] a $source user [Then] announces only a test user',
369 + ({ source, expected }) => {
370 + expect(fallbackNotice({ userId: 'u', source })).toEqual(expected);
371 + }
372 + );
373 +});
ts/packages/cli/test/src/commands/tools/search/tools.search.cmd.test.ts
+39
@@ -833,4 +833,43 @@ describe('CLI: composio search', () => {
833 );
834 }
835 );
836 +
837 + layer(
838 + TestLive({
839 + ...testLiveOptions,
840 + // The empty id is accepted (legacy); a response without the field at all is the only
841 + // way no consumer user resolves.
842 + accountData: { consumerUserId: null },
843 + })
844 + )('[Given] no consumer user id [Then] the search fails as a usage error', it => {
845 + it.effect('[Then] the preserved message names --user-id', () =>
846 + Effect.gen(function* () {
847 + const failure = yield* cli(['search', 'send']).pipe(Effect.flip);
848 +
849 + expect(failure).toBeInstanceOf(CommandInputError);
850 + expect(failure).toMatchObject({
851 + option: '--user-id',
852 + message:
853 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
854 + });
855 + })
856 + );
857 + });
858 +
859 + layer(
860 + TestLive({
861 + ...testLiveOptions,
862 + // As before `actingUser`, the search accepts the empty id as the user.
863 + accountData: { consumerUserId: '' },
864 + })
865 + )('[Given] an empty consumer user id [Then] the search still runs', it => {
866 + it.effect('[Then] results come back for the accepted user', () =>
867 + Effect.gen(function* () {
868 + yield* cli(['search', 'send']);
869 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
870 +
871 + expect(output).toContain('GMAIL_SEND_EMAIL');
872 + })
873 + );
874 + });
875 });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+83
@@ -12,6 +12,7 @@ import { clearInProcessMemos } from 'src/utils/memoize-in-process';
12 import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
13 import * as composioAccount from 'src/services/composio-account';
14 import type { ToolkitProjectScope } from 'src/services/composio-clients';
15 +import { ComposioUserContext } from 'src/services/user-context';
16 import * as toolPermissions from 'src/services/tool-permissions';
17 import * as redactModule from 'src/ui/redact';
18 import { cli, TestLive, MockConsole } from 'test/__utils__';
@@ -3447,3 +3448,85 @@ describe('CLI: composio execute', () => {
3448 );
3449 });
3450 });
3451 +
3452 +describe('CLI: composio execute without a resolvable acting user', () => {
3453 + layer(
3454 + TestLive({
3455 + baseConfigProvider: testConfigProvider,
3456 + fixture: 'global-test-user-id',
3457 + stdin: { isTTY: true, data: '' },
3458 + accountData: { consumerUserId: null },
3459 + })
3460 + )('[Given] the consumer project has no user id at all [Then] the root tree fails', it => {
3461 + it.effect('[Then] the missing_user_id failure carries the root message', () =>
3462 + Effect.gen(function* () {
3463 + const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{}']).pipe(Effect.flip);
3464 +
3465 + expect(failure).toMatchObject({
3466 + _tag: 'ToolExecutionError',
3467 + reason: 'missing_user_id',
3468 + message:
3469 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
3470 + });
3471 + })
3472 + );
3473 + });
3474 +
3475 + layer(
3476 + TestLive({
3477 + baseConfigProvider: ConfigProvider.fromEnv({
3478 + env: {
3479 + COMPOSIO_USER_API_KEY: 'test_api_key',
3480 + COMPOSIO_ORG_ID: 'org_test',
3481 + COMPOSIO_PROJECT_ID: 'proj_test',
3482 + },
3483 + }),
3484 + stdin: { isTTY: true, data: '' },
3485 + })
3486 + )('[Given] a directory project and no user candidates [Then] the dev tree fails', it => {
3487 + it.effect('[Then] the missing_user_id failure carries the dev message', () =>
3488 + Effect.gen(function* () {
3489 + const userContext = yield* ComposioUserContext;
3490 + yield* userContext.login('test_api_key', 'org_test');
3491 + const failure = yield* cli([
3492 + 'dev',
3493 + 'playground-execute',
3494 + 'GMAIL_SEND_EMAIL',
3495 + '-d',
3496 + '{}',
3497 + ]).pipe(Effect.flip);
3498 +
3499 + expect(failure).toMatchObject({
3500 + _tag: 'ToolExecutionError',
3501 + reason: 'missing_user_id',
3502 + message:
3503 + 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
3504 + });
3505 + })
3506 + );
3507 + });
3508 +
3509 + layer(
3510 + TestLive({
3511 + baseConfigProvider: testConfigProvider,
3512 + fixture: 'global-test-user-id',
3513 + stdin: { isTTY: true, data: '' },
3514 + accountData: { consumerUserId: '' },
3515 + })
3516 + )('[Given] an empty consumer user id [Then] the root tree accepts it as the user', it => {
3517 + it.effect('[Then] the execution runs and reports success', () =>
3518 + Effect.gen(function* () {
3519 + yield* cli([
3520 + 'execute',
3521 + 'GMAIL_SEND_EMAIL',
3522 + '--skip-connection-check',
3523 + '-d',
3524 + '{"recipient":"a"}',
3525 + ]);
3526 + const output = parseLastJson(yield* MockConsole.getLines({ stripAnsi: true }));
3527 +
3528 + expect(output.successful).toBe(true);
3529 + })
3530 + );
3531 + });
3532 +});