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

feat(ts): drop CommonJS support (#3494)

This PR moves the TypeScript SDK support floor to the latest Node.js 22 release and uses that as the point where we stop carrying custom CommonJS compatibility machinery. The e2e runtime coverage now exercises the latest Node 22, Node 24, and Node 25 lines, so the SDK is tested against the minimum supported version and the newer runtimes users are likely to adopt next. Because the SDK packages are still on `0.x`, the accompanying changeset uses `minor` bumps while calling out that this is a breaking change inside the existing 0.x line. It also moves pnpm under mise on this Node 22 layer. That belongs here, not in #3493, because the pinned `pnpm@10.28.2` requires Node.js `>=22.13`. Removing Corepack is intentional: Node.js documents that Corepack is no longer distributed starting with Node.js v25, so relying on `corepack enable` would keep a toolchain dependency that is already on the way out of the Node distribution. ## What changed - Pins the local/toolchain Node.js floor to `22.22.3` in `mise.toml`, `mise.lock`, `toolchain-versions.json`, and root `devEngines`. - Pins pnpm in `mise.toml` as `"npm:pnpm" = "10.28.2"` and makes mise the single source of truth for the pnpm version. Removes the root `packageManager` / `devEngines.packageManager` Corepack pin entirely (rather than keeping a second copy of the version that could drift) and removes stale `packageManager` metadata from real TS packages/examples and generators. - Sets `dangerouslyDisablePackageManagerCheck: true` in `turbo.jsonc` so Turbo discovers pnpm from `pnpm-lock.yaml` instead of requiring a `packageManager` field. Without this, Turbo fails workspace resolution (`Could not resolve workspaces -> Missing 'packageManager' field`), which is the only reason the field would otherwise need to stay. - Replaces `corepack enable` in the shared setup action with mise-managed pnpm. The E2E Docker images install bun + pnpm directly from `mise.toml`/`mise.lock` (with `dangerouslyDisablePackageManagerCheck`-style separation: Node/Deno stay on the base image as the test matrix axis and are disabled via `MISE_DISABLE_TOOLS` so mise does not shadow them; the tool binaries are symlinked into `/usr/local/bin`). No `BUN_VERSION`/`PNPM_VERSION` build args are threaded from the host anymore, and bun+pnpm now carry `mise.lock` checksum verification. - Extends the install-time toolchain check to validate pnpm against mise alongside Bun. - Sets the Node E2E matrix and install fallback checks to `22.22.3`, `24.16.0`, and `25.9.0`. - Makes TS package builds ESM-only: `tsdown` now emits `.mjs` / `.d.mts` only and uses the ATTW `esm-only` profile. - Removes explicit `require` / `.cjs` / `.d.cts` package export paths and internal import mappings from the public TS SDK packages. - Marks public TS SDK packages as `type: module` where they were missing it. - Replaces the remaining runtime `require('pusher-js')` with dynamic ESM import. - Deletes the legacy CJS example. - Reintroduces `node/cjs-basic` as a modern Node `require(esm)` interop E2E: it verifies `require('@composio/core')` works through Node's native ESM loader on Node 22, 24, and 25 while resolving to `dist/index.mjs`, not a `.cjs` artifact. - Removes `.cjs` / `.cts` handling from example validation and CLI project-language detection. - Updates provider scaffolding so newly generated providers are ESM-only. - Adds a minor changeset warning that CommonJS callers can only rely on Node's native `require(esm)` interop and that custom CommonJS compatibility machinery is gone. ## Bundled behavior changes Two changes here are technically independent of the CommonJS removal but ride along because they touch the same files and ship in the same release cut. Calling them out explicitly so they are not missed in review: - **`PusherUtils` realtime channel auth (`@composio/core`).** Replacing the runtime `require('pusher-js')` with a dynamic ESM `import()` was done alongside conforming `channelAuthorization` to pusher-js's typed `customHandler(params, callback)` contract. The previous `(authOptions) => Promise` shape did not match pusher-js's actual calling convention — it read `endpoint`/`headers`/`params` off an argument that pusher-js never passes — so this also fixes that latent mismatch. New unit tests (`ts/packages/core/test/utils/pusher.test.ts`) cover the auth request shape (endpoint, `x-api-key` header, JSON `socket_id`/`channel_name` body) and the success / invalid-JSON / network-failure callback paths. - **CLI meta-tool slug list (`@composio/cli`).** Drops `COMPOSIO_UPSERT_RECIPE` and `COMPOSIO_GET_RECIPE` from `META_TOOL_SLUG_LIST` in `tools-executor.ts`; `@composio/client` alpha.74 removed those slugs from the `SessionExecuteMetaParams['slug']` union. The list is declared `satisfies ReadonlyArray<SessionExecuteMetaParams['slug']>`, so this is enforced at compile time (`pnpm typecheck`) — keeping the stale slugs would be a type error — and needs no separate runtime test. ## Verification - Verified latest Node 22/24/25 releases from the official Node dist index: `22.22.3`, `24.16.0`, `25.9.0` (https://nodejs.org/dist/index.json). - Verified Node docs state Corepack is no longer distributed starting with Node.js v25: https://nodejs.org/download/release/v22.22.3/docs/api/corepack.html - `mise exec -- pnpm --version` -> `10.28.2` - `mise exec -- pnpm install --frozen-lockfile` - `mise exec -- bun run ts/scripts/pre-install/check-toolchain.ts` - `mise exec -- pnpm --filter @e2e-tests/utils typecheck` - `mise exec -- pnpm --filter @e2e-tests/node-cjs-basic typecheck` - `mise exec -- pnpm --filter @e2e-tests/node-cjs-basic test:e2e:node` - `mise exec -- pnpm --filter @e2e-tests/node-esm-basic typecheck` - `mise exec -- pnpm --filter @composio/cli typecheck` - `mise exec -- pnpm --filter @composio/cli test -- --runInBand` - `mise exec -- pnpm --filter @composio/core typecheck` - `mise exec -- pnpm --filter @composio/core exec vitest run test/utils/pusher.test.ts` - `mise exec -- pnpm run build:packages` - `mise exec -- turbo run build --dry-run` resolves all workspace packages with no root `packageManager` field (pnpm discovered from `pnpm-lock.yaml`). - `mise exec -- pnpm --filter @composio/cli exec vitest run test/src/services/project-environment-detector.test.ts` - `mise exec -- pnpm exec prettier --check ...` - `docker build -f ts/e2e-tests/_utils/Dockerfile.node --build-arg NODE_VERSION=24.16.0 -t composio-e2e-node:misecheck .` (also `Dockerfile.deno` with `DENO_VERSION=2.6.7 NODE_MAJOR=22`) — both build green; runtime resolves Node/Deno from the base image and pnpm 10.28.2 / bun 1.3.10 from mise. - `docker manifest inspect node:24.16.0-slim` - `docker manifest inspect node:25.9.0-slim` - `bash -n ts/scripts/create-provider.sh && git diff --check` - `ruby -e "require 'yaml'; YAML.load_file('.github/workflows/ts.test-e2e.yml')"` - Tracked example validation in a clean temporary tree: `Validated 21 example packages.`

Alberto Schiabel committed Jun 19, 2026 at 22:22 UTC 025a657597c60d9b1c3ac1d53edcaa59ac3a2436
85 files changed +550 -1778
.changeset/drop-commonjs-entrypoints.md new
+20
@@ -0,0 +1,20 @@
1 +---
2 +'@composio/core': minor
3 +'@composio/json-schema-to-zod': minor
4 +'@composio/ts-builders': minor
5 +'@composio/cli': minor
6 +'@composio/cli-keyring': minor
7 +'@composio/cli-local-tools': minor
8 +'@composio/anthropic': minor
9 +'@composio/claude-agent-sdk': minor
10 +'@composio/cloudflare': minor
11 +'@composio/google': minor
12 +'@composio/langchain': minor
13 +'@composio/llamaindex': minor
14 +'@composio/mastra': minor
15 +'@composio/openai': minor
16 +'@composio/openai-agents': minor
17 +'@composio/vercel': minor
18 +---
19 +
20 +Drop CommonJS entrypoints and publish the TypeScript SDK packages as ESM-only packages. This is a breaking change within the existing 0.x release line: consumers must use Node.js 22.22.3 or newer. CommonJS callers can only rely on Node's native `require(esm)` interop, and the SDK no longer ships custom CommonJS compatibility machinery or `.cjs` artifacts.
.github/workflows/ts.release.yml
+3 -3
@@ -34,9 +34,9 @@ jobs:
34 - name: Setup Node.js, pnpm, Bun
35 uses: ./.github/actions/setup-node-pnpm-bun
36 with:
37 - # TODO: Once https://github.com/ComposioHQ/composio/pull/3494 lands,
38 - # centralize this trusted-publishing runtime in mise.toml and drop
39 - # the release-only override.
37 + # Pin Node.js 24 for the release job only: the npm it bundles supports
38 + # OIDC trusted publishing, which the toolchain's Node 22 (mise.toml)
39 + # does not. Intentionally a release-only override, not centralized.
40 node-version: '24.17.0'
41
42 - name: Install Dependencies
.github/workflows/ts.test-e2e.yml
+1 -3
@@ -39,7 +39,7 @@ jobs:
39 echo "deno=$(jq -c '.deno' toolchain-versions.json)" >> "$GITHUB_OUTPUT"
40
41 # Node.js E2E tests, running in Docker to isolate environment
42 - # Each test suite defines its own nodeVersions in e2e.test.ts
42 + # Each test suite defines its own versions.node in e2e.test.ts
43 # Tests that don't support the matrix version are automatically skipped
44 test-e2e-node-docker:
45 name: E2E Test Node.js ${{ matrix.node-version }}
@@ -82,7 +82,6 @@ jobs:
82 run: |
83 docker build -f ts/e2e-tests/_utils/Dockerfile.node \
84 --build-arg NODE_VERSION=${{ matrix.node-version }} \
85 - --build-arg BUN_VERSION=${{ steps.setup-toolchain.outputs.bun-version }} \
85 --label composio.e2e=true \
86 --label composio.runtime=node \
87 --label "composio.node_version=${{ matrix.node-version }}" \
@@ -179,7 +178,6 @@ jobs:
178 docker build -f ts/e2e-tests/_utils/Dockerfile.cli \
179 --build-arg CLI_VERSION="${CLI_VERSION}" \
180 --build-arg NODE_VERSION="${{ steps.setup-toolchain.outputs.node-version }}" \
182 - --build-arg BUN_VERSION="${{ steps.setup-toolchain.outputs.bun-version }}" \
181 --label composio.e2e=true \
182 --label composio.runtime=cli \
183 --label "composio.cli_version=${CLI_VERSION}" \
AGENTS.md
+4 -5
@@ -28,8 +28,7 @@ pnpm test # Run tests
28 ### Package Management
29
30 ```bash
31 -mise install # Install Node, Bun, Deno, Python, uv (one-time; needs mise — https://mise.jdx.dev/installing-mise.html)
32 -corepack enable # Activate pnpm from package.json#packageManager
31 +mise install # Install Node, Bun, Deno, pnpm, Python, uv (one-time; needs mise — https://mise.jdx.dev/installing-mise.html)
32 pnpm install # Install dependencies
33 pnpm check:peer-deps # Check peer dependencies
34 pnpm update:peer-deps # Update peer dependencies
@@ -115,7 +114,7 @@ composio/
114
115 ```bash
116 pnpm test:e2e # All (Node.js + Deno + Cloudflare)
118 -pnpm test:e2e:node # Node.js CJS/ESM compatibility (Docker)
117 +pnpm test:e2e:node # Node.js ESM and require(esm) interop (Docker)
118 pnpm test:e2e:deno # Deno npm: specifier compatibility (Docker)
119 pnpm test:e2e:cloudflare # Cloudflare Workers
120 ```
@@ -227,9 +226,9 @@ Toolchain versions are coalesced in `mise.toml`. To check the current values:
226 - **Deno**: `mise current deno`
227 - **Python**: `mise current python`
228 - **uv**: `mise current uv`
230 -- **pnpm**: `node -p "require('./package.json').packageManager"`
229 +- **pnpm**: `mise current npm:pnpm`
230
232 -To bump, edit `mise.toml` (or `package.json#packageManager` for pnpm), then run:
231 +To bump, edit `mise.toml`, then run:
232
233 ```bash
234 mise lock --platform linux-x64,linux-arm64,macos-arm64,macos-x64
CLAUDE.md
+5 -6
@@ -29,8 +29,7 @@ composio/
29 ## TypeScript Commands
30
31 ```bash
32 -mise install # Installs Node, Bun, Deno, Python, uv from mise.toml (one-time per machine)
33 -corepack enable # Activates pnpm pinned in package.json#packageManager
32 +mise install # Installs Node, Bun, Deno, pnpm, Python, uv from mise.toml (one-time per machine)
33 pnpm install # First-time setup
34 pnpm build # Build all packages (Turbo)
35 pnpm build:packages # TS packages only
@@ -38,8 +37,8 @@ pnpm lint / lint:fix
37 pnpm format
38 pnpm typecheck # MANDATORY before pushing CLI changes
39 pnpm test # Vitest, all packages
41 -pnpm test:e2e # All runtimes (Node CJS+ESM, Deno, Cloudflare Workers) via Docker
42 -pnpm test:e2e:node # Override with COMPOSIO_E2E_NODE_VERSION=22.12.0
40 +pnpm test:e2e # All runtimes (Node ESM + require(esm), Deno, Cloudflare Workers) via Docker
41 +pnpm test:e2e:node # Override with COMPOSIO_E2E_NODE_VERSION=22.22.3
42 pnpm test:e2e:deno # Override with COMPOSIO_E2E_DENO_VERSION=2.6.7
43 pnpm test:e2e:cloudflare
44 pnpm changeset # Create release changeset (required for stable CLI/SDK releases)
@@ -47,7 +46,7 @@ pnpm create:provider <name> [--agentic]
46 pnpm create:example <name>
47 ```
48
50 -Toolchain versions are pinned in `mise.toml` (Node, Bun, Deno, Python, uv) and `package.json#packageManager` (pnpm via corepack). Install mise once with `brew install mise` (macOS), `winget install jdx.mise` (Windows), or `curl https://mise.run | sh` (any), then activate it in your shell — see https://mise.jdx.dev/installing-mise.html. CI can set `BYPASS_TOOLCHAIN_CHECK=1` only when using prebuilt toolchain images.
49 +Toolchain versions are pinned in `mise.toml` (Node, Bun, Deno, pnpm, Python, uv). Install mise once with `brew install mise` (macOS), `winget install jdx.mise` (Windows), or `curl https://mise.run | sh` (any), then activate it in your shell — see https://mise.jdx.dev/installing-mise.html. CI can set `BYPASS_TOOLCHAIN_CHECK=1` only when using prebuilt toolchain images.
50
51 ## Python Commands
52
@@ -89,7 +88,7 @@ COMPOSIO_DISABLE_TELEMETRY # "true" to disable
88 - Core Composio class: `ts/packages/core/src/composio.ts`
89 - Types: `ts/packages/core/src/types/`, errors: `ts/packages/core/src/errors/`
90 - Build configs: `turbo.jsonc`, `tsconfig.base.json`, `tsdown.config.base.ts`
92 -- Toolchain pins: `mise.toml` (Node, Bun, Deno, Python, uv), `mise.lock`, `toolchain-versions.json` (test matrices), `package.json#packageManager` (pnpm)
91 +- Toolchain pins: `mise.toml` (Node, Bun, Deno, pnpm, Python, uv), `mise.lock`, `toolchain-versions.json` (test matrices)
92 - CI release docs to update when bumping toolchain: `ts/docs/internal/release.md`
93 - Python config: `python/Makefile`, `python/noxfile.py`, `python/config/{pytest.ini,ruff.toml}`
94
mise.lock
+9 -9
@@ -61,24 +61,24 @@ checksum = "sha256:fae025e69cada67fb57affdda26abbe72991b02b515c3221e92c58aa8a642
61 url = "https://dl.deno.land/release/v2.6.7/deno-x86_64-apple-darwin.zip"
62
63 [[tools.node]]
64 -version = "20.20.2"
64 +version = "22.22.3"
65 backend = "core:node"
66
67 [tools.node."platforms.linux-arm64"]
68 -checksum = "sha256:47ef73d543ecf6eb19435f6c03a0ac4809b3bf0dd6b26c7c571efc2a6572a74d"
69 -url = "https://nodejs.org/dist/v20.20.2/node-v20.20.2-linux-arm64.tar.gz"
68 +checksum = "sha256:cc8bc82b2dd0b595c3b95a4c3c9c8c350907cff011afbdee3d1379e812e1e3e3"
69 +url = "https://nodejs.org/dist/v22.22.3/node-v22.22.3-linux-arm64.tar.gz"
70
71 [tools.node."platforms.linux-x64"]
72 -checksum = "sha256:19e56f0825510207dd904f087fe52faa0a4eb6b2aab5f0ea7a33830d04888b8b"
73 -url = "https://nodejs.org/dist/v20.20.2/node-v20.20.2-linux-x64.tar.gz"
72 +checksum = "sha256:c7a10d6816da8eaaa7534dd73c71c6e2b2c391dbbf845e364902d156615dd1b8"
73 +url = "https://nodejs.org/dist/v22.22.3/node-v22.22.3-linux-x64.tar.gz"
74
75 [tools.node."platforms.macos-arm64"]
76 -checksum = "sha256:466e05f3477c20dfb723054dfebffe55bc74660ee77f612166fca121dacb65b6"
77 -url = "https://nodejs.org/dist/v20.20.2/node-v20.20.2-darwin-arm64.tar.gz"
76 +checksum = "sha256:0da7ff74ef8611328c8212f17943368713a2ad953fb7d89a8c8a0eae87c23207"
77 +url = "https://nodejs.org/dist/v22.22.3/node-v22.22.3-darwin-arm64.tar.gz"
78
79 [tools.node."platforms.macos-x64"]
80 -checksum = "sha256:8be6f5e4bb128c82774f8a0b8d7a1cc1365a7977d9657cece0ca647b3fe04e61"
81 -url = "https://nodejs.org/dist/v20.20.2/node-v20.20.2-darwin-x64.tar.gz"
80 +checksum = "sha256:45830ba752fa0d892c6dcd640946669801293cac820a33591ded40ac075198ec"
81 +url = "https://nodejs.org/dist/v22.22.3/node-v22.22.3-darwin-x64.tar.gz"
82
83 [[tools."npm:pnpm"]]
84 version = "10.28.2"
mise.toml
+3 -2
@@ -4,12 +4,13 @@
4 # CI: driven by `jdx/mise-action` in the composite actions under `.github/actions/`
5 #
6 # pnpm is pinned through mise's npm backend so mise owns the full local and CI
7 -# toolchain. CI cannot assume Corepack has created a pnpm shim before caching.
7 +# toolchain. We do not rely on Corepack because Node.js no longer distributes it
8 +# starting with v25.
9
10 min_version = "2026.1.0"
11
12 [tools]
12 -node = "20.20.2"
13 +node = "22.22.3"
14 bun = "1.3.10"
15 deno = "2.6.7"
16 python = "3.12"
package.json
+1 -7
@@ -52,16 +52,10 @@
52 "clean": "git clean -xdf .turbo node_modules ts/packages/**/.turbo ts/packages/**/node_modules ts/packages/**/dist",
53 "clean:workspace": "pnpm turbo clean"
54 },
55 - "packageManager": "pnpm@10.28.2",
55 "devEngines": {
56 "runtime": {
57 "name": "node",
59 - "version": "20.20.2",
60 - "onFail": "warn"
61 - },
62 - "packageManager": {
63 - "name": "pnpm",
64 - "version": "10.28.2",
58 + "version": "22.22.3",
59 "onFail": "warn"
60 }
61 },
plans/feat-init-project-environment-detection.md deleted
-619
@@ -1,619 +0,0 @@
1 -# feat: Add project environment detection and dependency installation to `composio init`
2 -
3 -## Overview
4 -
5 -Enhance `composio init` to automatically detect the project environment (TypeScript/Python, package manager, monorepo vs single-package) and install Composio's SDK dependencies using the correct package manager command. This replaces the existing `EnvLangDetector` + `JsPackageManagerDetector` services with a unified `ProjectEnvironmentDetector` service that produces richer detection results, and adds a `CommandRunner` service for running install commands in tests.
6 -
7 -## Problem Statement / Motivation
8 -
9 -Currently, `composio init` writes config files but does **not**:
10 -- Detect what kind of project the user is working in
11 -- Install Composio SDK packages (`@composio/core` for TS, `composio` for Python)
12 -- Install framework-specific provider packages (`@composio/mastra`, `@composio/openai`, etc.)
13 -
14 -Users must manually figure out which packages to install and run the correct package manager command. This is error-prone, especially in monorepos where the package manager may differ from what the user expects.
15 -
16 -The `composio2` branch already has working implementations of `ProjectEnvironmentDetector`, `CommandRunner`, `core-dependency.ts`, and an `install.cmd.ts` with tests. This plan imports and adapts those implementations into the current `feat/cli-login-2.0` branch.
17 -
18 -## Proposed Solution
19 -
20 -### Architecture
21 -
22 -```mermaid
23 -graph TD
24 - A[composio init] --> B[Project Selection]
25 - B --> C[Init Wizard: usage mode + framework + skills]
26 - C --> D[ProjectEnvironmentDetector.detectProjectEnvironment]
27 - D --> E{Detected?}
28 - E -->|Yes| F[Show detection + confirm]
29 - E -->|Ambiguous| G[Prompt user to choose language]
30 - E -->|No indicators| H[Prompt user to choose language + PM]
31 - F --> I[resolveCoreDependencyState]
32 - G --> I
33 - H --> I
34 - I --> J{Already installed?}
35 - J -->|Yes, not --force| K[Skip install, log info]
36 - J -->|No or --force| L[Confirm install command]
37 - L --> M[CommandRunner.run with spinner]
38 - M --> N[Write config files]
39 - N --> O[Optionally install skills]
40 -```
41 -
42 -### Key Components
43 -
44 -1. **`ProjectEnvironmentDetector`** (new service) — replaces `EnvLangDetector` + `JsPackageManagerDetector` with a single service that:
45 - - Walks up the directory tree looking for project indicators
46 - - Produces a `ProjectEnvironment` discriminated union (`js` | `python`)
47 - - Includes `language`, `packageManager`, `rootDir`, and `evidence[]`
48 - - Handles ambiguity (both JS and Python indicators) with a tagged error
49 - - Supports Deno (`deno.json`, `deno.lock`) as a JS package manager
50 -
51 -2. **`CommandRunner`** (new service) — thin wrapper around `@effect/platform` `Command.exitCode` for testability. In production, it runs the actual command; in tests, it returns a configurable exit code.
52 -
53 -3. **`core-dependency.ts`** (new effect) — maps a `ProjectEnvironment` to a `CoreDependencyPlan` containing the install command string, dependency name, and package manager. Also detects if the dependency is already installed.
54 -
55 -4. **Updated `init.cmd.ts`** — integrates detection + installation into the wizard flow after project selection.
56 -
57 -## Technical Approach
58 -
59 -### Phase 1: New Services and Effects
60 -
61 -#### 1.1 Add `ProjectEnvironmentDetector` service
62 -
63 -**File:** `ts/packages/cli/src/services/project-environment-detector.ts`
64 -
65 -Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/project-environment-detector.ts`
66 -
67 -The reference implementation is 587 lines and provides:
68 -
69 -```typescript
70 -export type ProjectEnvironment =
71 - | { kind: 'js'; language: JsLanguage; packageManager: JsPackageManager; rootDir: string; evidence: string[] }
72 - | { kind: 'python'; language: 'python'; packageManager: PythonPackageManager; rootDir: string; evidence: string[] };
73 -
74 -export type JsLanguage = 'typescript' | 'javascript';
75 -export type JsPackageManager = 'pnpm' | 'bun' | 'yarn' | 'npm' | 'deno';
76 -export type PythonPackageManager = 'uv' | 'pip';
77 -```
78 -
79 -Key detection strategies:
80 -- **Strong JS indicators:** `package.json`, `tsconfig.json`, `pnpm-workspace.yaml`, lock files — each gets a high score
81 -- **Strong Python indicators:** `pyproject.toml`, `setup.py`, `requirements.txt`, `uv.lock`, `poetry.lock`
82 -- **Weak indicators:** file extension counts (`.ts`, `.py`), subdirectory scans
83 -- **Package manager from `package.json`:** reads `packageManager` field (e.g., `"pnpm@9.0.0"`)
84 -- **Python package manager:** checks for `uv.lock` or `[tool.uv]` in `pyproject.toml`
85 -- **Ancestor walking:** walks up from CWD to filesystem root, checking each directory
86 -
87 -**Ambiguity handling:** If both JS and Python strong indicators exist at CWD depth 0, fails with `ProjectEnvironmentDetectorError`. At deeper levels, skips and continues searching.
88 -
89 -**Service pattern:** Uses `Effect.Service` class with `effect:` body and `dependencies: [BunFileSystem.layer]`.
90 -
91 -#### 1.2 Add `CommandRunner` service
92 -
93 -**File:** `ts/packages/cli/src/services/command-runner.ts`
94 -
95 -Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/command-runner.ts`
96 -
97 -```typescript
98 -import { Command } from '@effect/platform';
99 -import { Effect } from 'effect';
100 -
101 -export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {
102 - sync: () => ({
103 - run: (command: Command.Command) => Command.exitCode(command),
104 - }),
105 - dependencies: [],
106 -}) {}
107 -```
108 -
109 -This is intentionally thin — the real value is in testability. In tests, we provide `Layer.succeed(CommandRunner, new CommandRunner({ run: () => Effect.succeed(ExitCode(0)) }))`.
110 -
111 -#### 1.3 Add `core-dependency.ts` effect
112 -
113 -**File:** `ts/packages/cli/src/effects/core-dependency.ts`
114 -
115 -Import from: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/effects/core-dependency.ts`
116 -
117 -Key exports:
118 -- `CoreDependencyPlan` — discriminated union with `installCommand`, `dependency`, `packageManager`, `rootDir`
119 -- `detectCoreDependencyPlan(cwd)` — maps `ProjectEnvironment` → `CoreDependencyPlan`
120 -- `detectCoreDependencyVersion(plan)` — checks if `@composio/core` or `composio` is already installed
121 -- `resolveCoreDependencyState(cwd)` — combines plan + version check
122 -- `getJsInstallCommand(pm, dependency)` — maps package manager to install command
123 -- `getPythonInstallCommand(pm, dependency)` — same for Python
124 -
125 -Install command mapping:
126 -
127 -| PM | Command |
128 -|---|---|
129 -| pnpm | `pnpm add @composio/core` |
130 -| bun | `bun add @composio/core` |
131 -| yarn | `yarn add @composio/core` |
132 -| npm | `npm install -S @composio/core` |
133 -| deno | `deno add npm:@composio/core` |
134 -| uv | `uv pip install composio` |
135 -| pip | `pip install composio` |
136 -
137 -### Phase 2: Update `composio init` Command
138 -
139 -#### 2.1 Add new CLI flags
140 -
141 -```typescript
142 -const dryRunOpt = Options.boolean('dry-run').pipe(
143 - Options.withDefault(false),
144 - Options.withDescription('Print install command without executing it')
145 -);
146 -
147 -const forceOpt = Options.boolean('force').pipe(
148 - Options.withDefault(false),
149 - Options.withDescription('Reinstall even if dependency appears installed')
150 -);
151 -
152 -const yesOpt = Options.boolean('yes').pipe(
153 - Options.withAlias('y'),
154 - Options.withDefault(false),
155 - Options.withDescription('Skip confirmation prompts')
156 -);
157 -```
158 -
159 -#### 2.2 Extend `InitConfigBuilder` and `InitConfig`
160 -
161 -Add new builder steps and fields:
162 -
163 -```typescript
164 -interface InitConfig {
165 - readonly usageMode: UsageMode;
166 - readonly framework: NativeFramework | undefined;
167 - readonly installSkills: boolean;
168 - readonly detectedEnv: ProjectEnvironment; // NEW
169 - readonly installPlan: CoreDependencyPlan; // NEW
170 -}
171 -```
172 -
173 -Add `withDetectedEnv` and `withInstallPlan` methods to `InitConfigBuilder`, and update the `build()` type constraint.
174 -
175 -#### 2.3 Updated wizard flow
176 -
177 -After the existing wizard steps (usage mode → framework → skills), add:
178 -
179 -```typescript
180 -// Step 4: Detect project environment
181 -const envDetector = yield* ProjectEnvironmentDetector;
182 -const detectedEnv = yield* envDetector
183 - .detectProjectEnvironment(proc.cwd)
184 - .pipe(
185 - Effect.catchTag('services/ProjectEnvironmentDetectorError', e =>
186 - Effect.gen(function* () {
187 - yield* ui.log.warn(e.message);
188 - // Fallback: ask user to choose
189 - const lang = yield* ui.select('What language is your project?', [
190 - { value: 'typescript', label: 'TypeScript' },
191 - { value: 'python', label: 'Python' },
192 - ]);
193 - // ... prompt for package manager too
194 - })
195 - )
196 - );
197 -
198 -yield* ui.log.step(`Detected: ${detectedEnv.language} (${detectedEnv.packageManager})`);
199 -
200 -// Step 5: Check if already installed + determine install plan
201 -const { plan, installedVersion } = yield* resolveCoreDependencyState(proc.cwd);
202 -
203 -if (installedVersion && !forceOpt) {
204 - yield* ui.log.info(`Found ${plan.dependency}: ${installedVersion.version}`);
205 - yield* ui.log.success('Dependency already installed.');
206 -} else {
207 - // Step 6: Confirm and install
208 - if (dryRunOpt) {
209 - yield* ui.note(plan.installCommand, 'Install Command');
210 - } else {
211 - const shouldInstall = yesOpt || (yield* ui.confirm(`Run: ${plan.installCommand}?`));
212 - if (shouldInstall) {
213 - yield* ui.withSpinner(`Installing ${plan.dependency}...`, installEffect, {
214 - successMessage: `Installed ${plan.dependency}`,
215 - });
216 - }
217 - }
218 -}
219 -```
220 -
221 -#### 2.4 Framework provider installation
222 -
223 -When a framework is selected (not "skip"), also install the provider package:
224 -
225 -```typescript
226 -const frameworkPackage = getFrameworkPackage(config.framework, detectedEnv);
227 -// e.g., '@composio/mastra' for TS, 'composio[mastra]' for Python
228 -```
229 -
230 -| Framework | TS Package | Python Package |
231 -|---|---|---|
232 -| ai-sdk | `@composio/vercel` | `composio[vercel]` |
233 -| mastra | `@composio/mastra` | `composio[mastra]` |
234 -| openai-agents | `@composio/openai` | `composio[openai]` |
235 -| claude-agent-sdk | `@composio/anthropic` | `composio[anthropic]` |
236 -
237 -### Phase 3: Wire Services in Layer Composition
238 -
239 -#### 3.1 Update `bin.ts`
240 -
241 -Add to the layer composition:
242 -
243 -```typescript
244 -import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
245 -import { CommandRunner } from 'src/services/command-runner';
246 -
247 -const layers = Layer.mergeAll(
248 - // ... existing layers ...
249 - ProjectEnvironmentDetector.Default, // NEW
250 - CommandRunner.Default, // NEW
251 -);
252 -```
253 -
254 -#### 3.2 Deprecate `EnvLangDetector` and `JsPackageManagerDetector`
255 -
256 -The new `ProjectEnvironmentDetector` subsumes both. However, `EnvLangDetector` is still used by `generate.cmd.ts`. Options:
257 -
258 -- **Option A (recommended):** Keep both old services for now, use `ProjectEnvironmentDetector` only in `init.cmd.ts`. Migrate `generate.cmd.ts` in a follow-up PR.
259 -- **Option B:** Replace both immediately and update `generate.cmd.ts` to use the new service.
260 -
261 -Go with **Option A** to keep this PR focused.
262 -
263 -### Phase 4: Testing (TDD)
264 -
265 -#### 4.1 Unit tests for `ProjectEnvironmentDetector`
266 -
267 -**File:** `ts/packages/cli/test/src/services/project-environment-detector.test.ts`
268 -
269 -Uses `tempy.temporaryDirectory()` to create isolated temp dirs with specific file layouts. Tests use `BunFileSystem.layer` (real filesystem).
270 -
271 -```
272 -describe('ProjectEnvironmentDetector', () => {
273 - describe('detectProjectEnvironment', () => {
274 - // TypeScript detection
275 - it('[Given] package.json + tsconfig.json [Then] detects typescript + npm')
276 - it('[Given] pnpm-lock.yaml + package.json with packageManager:pnpm@ [Then] detects typescript + pnpm')
277 - it('[Given] bun.lockb [Then] detects javascript + bun')
278 - it('[Given] deno.json [Then] detects typescript + deno')
279 - it('[Given] package.json with typescript dep [Then] detects typescript')
280 -
281 - // Python detection
282 - it('[Given] pyproject.toml with [tool.uv] [Then] detects python + uv')
283 - it('[Given] requirements.txt only [Then] detects python + pip')
284 - it('[Given] uv.lock [Then] detects python + uv')
285 - it('[Given] setup.py only [Then] detects python + pip')
286 -
287 - // Ambiguity
288 - it('[Given] both package.json + pyproject.toml at CWD [Then] fails with ambiguity error')
289 - it('[Given] both indicators but only at parent level [Then] skips and continues')
290 -
291 - // Ancestor walking
292 - it('[Given] indicators at parent directory [Then] detects from parent')
293 - it('[Given] no indicators anywhere [Then] fails with no-detection error')
294 -
295 - // File extension fallback
296 - it('[Given] only .ts files, no config files [Then] detects typescript via weak signals')
297 - it('[Given] only .py files, no config files [Then] detects python via weak signals')
298 -
299 - // Edge cases
300 - it('[Given] empty directory [Then] fails with no-detection error')
301 - it('[Given] monorepo root with pnpm-workspace.yaml [Then] detects pnpm')
302 - })
303 -
304 - describe('detectJsPackageManager', () => {
305 - it('[Given] packageManager field in package.json [Then] uses that')
306 - it('[Given] lock file present [Then] detects from lock file')
307 - it('[Given] no lock file, no packageManager field [Then] defaults to npm')
308 - })
309 -
310 - describe('detectPythonPackageManager', () => {
311 - it('[Given] uv.lock present [Then] detects uv')
312 - it('[Given] [tool.uv] in pyproject.toml [Then] detects uv')
313 - it('[Given] no uv indicators [Then] defaults to pip')
314 - })
315 -})
316 -```
317 -
318 -#### 4.2 Unit tests for `core-dependency.ts`
319 -
320 -**File:** `ts/packages/cli/test/src/effects/core-dependency.test.ts`
321 -
322 -```
323 -describe('core-dependency', () => {
324 - describe('getJsInstallCommand', () => {
325 - it('[Given] pnpm [Then] returns "pnpm add <dep>"')
326 - it('[Given] npm [Then] returns "npm install -S <dep>"')
327 - it('[Given] yarn [Then] returns "yarn add <dep>"')
328 - it('[Given] bun [Then] returns "bun add <dep>"')
329 - it('[Given] deno [Then] returns "deno add npm:<dep>"')
330 - })
331 -
332 - describe('getPythonInstallCommand', () => {
333 - it('[Given] uv [Then] returns "uv pip install <dep>"')
334 - it('[Given] pip [Then] returns "pip install <dep>"')
335 - })
336 -
337 - describe('detectCoreDependencyPlan', () => {
338 - it('[Given] TS project [Then] plans @composio/core install')
339 - it('[Given] Python project [Then] plans composio install')
340 - })
341 -
342 - describe('detectCoreDependencyVersion', () => {
343 - it('[Given] @composio/core in node_modules [Then] returns version')
344 - it('[Given] @composio/core in pnpm virtual store [Then] returns version')
345 - it('[Given] not installed [Then] returns null')
346 - })
347 -})
348 -```
349 -
350 -#### 4.3 Command tests for `composio init`
351 -
352 -**File:** `ts/packages/cli/test/src/commands/init.cmd.test.ts`
353 -
354 -Uses `TestLive` with fixtures and mocked services.
355 -
356 -```
357 -describe('CLI: composio init', () => {
358 - // Agent-native path (--org-id + --project-id)
359 - describe('[Given] --org-id + --project-id flags', () => {
360 - layer(TestLive({ fixture: 'typescript-project' }))(it => {
361 - it.scoped('[Then] detects TS project and shows install plan', () => ...)
362 - })
363 -
364 - layer(TestLive({ fixture: 'python-project' }))(it => {
365 - it.scoped('[Then] detects Python project and shows install plan', () => ...)
366 - })
367 - })
368 -
369 - // Dry-run mode
370 - describe('[Given] --dry-run flag', () => {
371 - layer(TestLive({ fixture: 'typescript-project' }))(it => {
372 - it.scoped('[Then] prints install command without executing', () => ...)
373 - })
374 - })
375 -
376 - // Already installed
377 - describe('[Given] @composio/core already in node_modules', () => {
378 - layer(TestLive({ fixture: 'typescript-project-with-composio-core' }))(it => {
379 - it.scoped('[Then] skips install', () => ...)
380 - })
381 - })
382 -
383 - // --force reinstall
384 - describe('[Given] --force flag with dependency installed', () => {
385 - layer(TestLive({ fixture: 'typescript-project-with-composio-core', commandRunner: successRunner }))(it => {
386 - it.scoped('[Then] reinstalls', () => ...)
387 - })
388 - })
389 -
390 - // Install failure
391 - describe('[Given] install command fails', () => {
392 - layer(TestLive({ fixture: 'typescript-project', commandRunner: failRunner }))(it => {
393 - it.scoped('[Then] shows error message', () => ...)
394 - })
395 - })
396 -})
397 -```
398 -
399 -#### 4.4 New test fixtures needed
400 -
401 -```
402 -test/__fixtures__/
403 - typescript-project/ # EXISTING: package.json + tsconfig.json
404 - python-project/ # EXISTING: requirements.txt + setup.py
405 - typescript-project-with-composio-core/ # EXISTING
406 - python-project-with-composio-core/ # EXISTING
407 - typescript-pnpm-monorepo/ # NEW: pnpm-workspace.yaml + package.json with packageManager:pnpm@
408 - typescript-bun-project/ # NEW: bun.lockb + package.json
409 - python-uv-project/ # NEW: pyproject.toml with [tool.uv] + uv.lock
410 - ambiguous-project/ # NEW: package.json + pyproject.toml (for error case)
411 -```
412 -
413 -#### 4.5 Test layer updates
414 -
415 -Update `TestLive` interface to accept optional overrides:
416 -
417 -```typescript
418 -interface TestLiveInput {
419 - // ... existing fields ...
420 - commandRunner?: CommandRunner; // NEW: mock for CommandRunner
421 - terminalUI?: TerminalUI; // NEW: override TerminalUI for custom prompt behavior
422 -}
423 -```
424 -
425 -Add `ProjectEnvironmentDetector.Default` and `CommandRunner.Default` (or mock) to the test layer composition.
426 -
427 -### Phase 5: E2E Tests
428 -
429 -#### 5.1 `composio init` deterministic E2E test
430 -
431 -**Directory:** `ts/e2e-tests/cli/init/`
432 -
433 -**Constraint:** E2E tests run inside Docker containers. The init command requires API access for project listing, which makes it hard to test end-to-end without mocking.
434 -
435 -**Deterministic test strategy:** Use `--org-id` + `--project-id` flags to bypass API calls. Pre-create a fixture project directory inside the Docker container.
436 -
437 -```typescript
438 -// ts/e2e-tests/cli/init/e2e.test.ts
439 -e2e(import.meta.url, {
440 - versions: { cli: ['current'] },
441 - defineTests: ({ runCmd }) => {
442 - describe('composio init --dry-run', () => {
443 - it('detects TypeScript project', async () => {
444 - // Create a minimal TS project in the container
445 - await runCmd('mkdir -p /tmp/test-ts && echo \'{"name":"test"}\' > /tmp/test-ts/package.json');
446 - await runCmd('echo \'{}\' > /tmp/test-ts/tsconfig.json');
447 -
448 - const result = await runCmd(
449 - 'cd /tmp/test-ts && composio init --org-id test-org --project-id test-proj --dry-run'
450 - );
451 -
452 - expect(result.exitCode).toBe(0);
453 - // In non-interactive (piped) mode, output() writes JSON to stdout
454 - expect(result.stdout).toContain('typescript');
455 - });
456 - });
457 -
458 - describe('composio init on Python project', () => {
459 - it('detects Python project', async () => {
460 - await runCmd('mkdir -p /tmp/test-py && echo "composio" > /tmp/test-py/requirements.txt');
461 -
462 - const result = await runCmd(
463 - 'cd /tmp/test-py && composio init --org-id test-org --project-id test-proj --dry-run'
464 - );
465 -
466 - expect(result.exitCode).toBe(0);
467 - expect(result.stdout).toContain('python');
468 - });
469 - });
470 - },
471 -});
472 -```
473 -
474 -**Note:** The init command's interactive prompts are automatically skipped in piped mode (TerminalUI returns defaults). The `--dry-run` flag prevents actual package installation.
475 -
476 -## Alternative Approaches Considered
477 -
478 -### A. Extend existing `EnvLangDetector` + `JsPackageManagerDetector`
479 -
480 -**Rejected because:** The existing services have separate interfaces that would need to be called independently and manually composed. The `ProjectEnvironmentDetector` provides a single, unified detection result with richer evidence tracking and proper ambiguity handling.
481 -
482 -### B. Separate `composio install` command
483 -
484 -**Reference:** The `composio2` branch already has a standalone `install.cmd.ts`.
485 -
486 -**Decision:** Both approaches have merit. The `composio init` command should include dependency installation as part of the initialization flow. A separate `composio install` command could be added later for re-installation or CI use. This plan focuses on integrating detection + installation into `init`.
487 -
488 -### C. Use `Effect.Service` class vs `Context.Tag` for new services
489 -
490 -**Decision:** Use `Effect.Service` class pattern (newer pattern) for consistency with `EnvLangDetector`, `JsPackageManagerDetector`, `NodeOs`, `NodeProcess`.
491 -
492 -## Acceptance Criteria
493 -
494 -### Functional Requirements
495 -
496 -- [ ] `composio init` detects TypeScript projects (from `tsconfig.json`, `package.json`, lock files)
497 -- [ ] `composio init` detects Python projects (from `pyproject.toml`, `setup.py`, `requirements.txt`)
498 -- [ ] `composio init` detects the correct package manager (pnpm, npm, yarn, bun, deno, uv, pip)
499 -- [ ] `composio init` walks up the directory tree to find project root (monorepo support)
500 -- [ ] `composio init` shows the detected environment and asks for confirmation before installing
501 -- [ ] `composio init` runs the correct install command (`pnpm add`, `npm install`, `uv pip install`, etc.)
502 -- [ ] `composio init --dry-run` prints the install command without executing
503 -- [ ] `composio init --force` reinstalls even if dependency is already present
504 -- [ ] `composio init --yes` skips confirmation prompts
505 -- [ ] `composio init` shows appropriate error messages when detection fails (ambiguous or empty project)
506 -- [ ] `composio init` gracefully handles install command failures
507 -- [ ] `composio init` skips installation when dependency is already installed (without `--force`)
508 -- [ ] `composio init` emits structured JSON to stdout when piped (agent-native)
509 -- [ ] `composio init` writes `detectedEnv` info to `.composio/config.json`
510 -
511 -### Non-Functional Requirements
512 -
513 -- [ ] `pnpm typecheck` passes from repo root
514 -- [ ] All existing tests continue to pass
515 -- [ ] Detection completes in < 500ms for typical projects (filesystem I/O only, no network)
516 -
517 -### Quality Gates
518 -
519 -- [ ] Unit tests for `ProjectEnvironmentDetector` covering all detection strategies
520 -- [ ] Unit tests for `core-dependency.ts` covering all package managers
521 -- [ ] Command tests for `composio init` covering happy path + error cases
522 -- [ ] At least one E2E test for `composio init --dry-run` in Docker container
523 -- [ ] New test fixtures for pnpm monorepo, bun project, uv project, ambiguous project
524 -
525 -## Success Metrics
526 -
527 -- Users can run `composio init` in any TypeScript or Python project and have dependencies installed automatically
528 -- Zero manual `npm install` / `pnpm add` / `uv pip install` steps needed after init
529 -- Package manager is correctly detected in monorepo setups (pnpm workspaces, etc.)
530 -
531 -## Dependencies & Prerequisites
532 -
533 -- `@effect/platform` `Command` module is already a dependency of the CLI package
534 -- The `composio2` reference implementations are available at `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/`
535 -- Test fixtures for `typescript-project` and `python-project` already exist
536 -
537 -## Risk Analysis & Mitigation
538 -
539 -| Risk | Impact | Mitigation |
540 -|---|---|---|
541 -| Ambiguous project detection (both TS + Python) | User confusion | Prompt user to choose, provide clear error message with evidence |
542 -| Install command fails (network, permissions) | Blocked init flow | Show error with the failing command, suggest manual install |
543 -| Package manager not installed on system | Install fails | Check binary existence before running, suggest install |
544 -| Monorepo: init from subdirectory | Wrong root dir detected | Ancestor walking already handles this; root dir = where lock file or package.json with workspaces lives |
545 -| Breaking existing `generate.cmd.ts` | Regression | Keep old services (Option A), migrate generate in follow-up PR |
546 -
547 -## Implementation Phases
548 -
549 -### Phase 1: Foundation (Services + Effects)
550 -- [x] Add `ProjectEnvironmentDetector` service (`src/services/project-environment-detector.ts`)
551 -- [x] Add `CommandRunner` service (`src/services/command-runner.ts`)
552 -- [x] Add `core-dependency.ts` effect (`src/effects/core-dependency.ts`)
553 -- [x] Wire new services in `bin.ts` layer composition
554 -- [x] Add new test fixtures (pnpm monorepo, bun project, uv project, ambiguous)
555 -
556 -### Phase 2: Unit Tests (TDD Red)
557 -- [x] Write `ProjectEnvironmentDetector` tests (17 test cases)
558 -- [x] Write `core-dependency.ts` tests (7 test cases)
559 -- [x] All tests pass (green)
560 -
561 -### Phase 3: Update `composio init` (Green)
562 -- [x] Add `--dry-run`, `--force`, `--yes` flags to init command
563 -- [x] Extend `InitConfigBuilder` with `withDetectedEnv` and `withInstallPlan`
564 -- [x] Integrate detection into the wizard flow
565 -- [x] Integrate installation with spinner and error handling
566 -- [x] Update structured JSON output to include detection info
567 -- [x] Update `.composio/config.json` to include detection info
568 -
569 -### Phase 4: Command Tests
570 -- [x] Write `init.cmd.test.ts` command tests (8 scenarios)
571 -- [x] Update `TestLive` to support `commandRunner` and `terminalUI` overrides
572 -- [x] Add `ProjectEnvironmentDetector.Default` to test layer
573 -
574 -### Phase 5: E2E Tests
575 -- [ ] Add `ts/e2e-tests/cli/init/` E2E test suite (deferred to follow-up PR)
576 -- [ ] Test `--dry-run` mode with TS and Python fixtures in Docker (deferred)
577 -- [ ] Update `ts/e2e-tests/cli/README.md` with new test info (deferred)
578 -
579 -### Phase 6: Cleanup
580 -- [x] Run `pnpm typecheck` and fix any issues
581 -- [x] Run full test suite and fix regressions
582 -- [ ] Update `CLAUDE.md` if needed (document new services)
583 -
584 -## Future Considerations
585 -
586 -- **`composio install` as standalone command** — extract install logic for re-use outside init
587 -- **Framework provider installation** — add framework-specific packages based on wizard selection
588 -- **Skills installation** — run `npx skills add ComposioHQ/skills` when `installSkills: true`
589 -- **Migrate `generate.cmd.ts`** — replace `EnvLangDetector` usage with `ProjectEnvironmentDetector`
590 -- **Deno support** — handle `deno add npm:@composio/core` pattern
591 -
592 -## References & Research
593 -
594 -### Internal References
595 -
596 -- Current `composio init`: `ts/packages/cli/src/commands/init.cmd.ts`
597 -- Existing `EnvLangDetector`: `ts/packages/cli/src/services/env-lang-detector.ts`
598 -- Existing `JsPackageManagerDetector`: `ts/packages/cli/src/services/js-package-manager-detector.ts`
599 -- Layer composition: `ts/packages/cli/src/bin.ts` (lines 93-112)
600 -- Test infrastructure: `ts/packages/cli/test/__utils__/services/test-layer.ts`
601 -- E2E test framework: `ts/e2e-tests/cli/README.md`
602 -- Login command tests (pattern reference): `ts/packages/cli/test/src/commands/login.cmd.test.ts`
603 -
604 -### Reference Implementations (composio2)
605 -
606 -- `ProjectEnvironmentDetector`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/project-environment-detector.ts`
607 -- `CommandRunner`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/command-runner.ts`
608 -- `core-dependency.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/effects/core-dependency.ts`
609 -- `install.cmd.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/commands/install.cmd.ts`
610 -- `install.cmd.test.ts`: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/test/src/commands/install.cmd.test.ts`
611 -- `TerminalUI` with prompts: `/Users/jkomyno/work/composio/composio2/ts/packages/cli/src/services/terminal-ui.ts`
612 -
613 -### External References
614 -
615 -- Effect.ts Service pattern: `ts/vendor/effect/packages/effect/src/`
616 -- @effect/cli Command: `ts/vendor/effect/packages/cli/src/Command.ts`
617 -- @effect/platform FileSystem: `ts/vendor/effect/packages/platform/src/FileSystem.ts`
618 -- @effect/platform Command (subprocess): `ts/vendor/effect/packages/platform/src/Command.ts`
619 -- @clack/prompts: `ts/vendor/clack/packages/prompts/src/`
plans/fix-mastra-dangling-defs-ref.md deleted
-435
@@ -1,435 +0,0 @@
1 -# fix: Tolerate dangling `$ref` in Mastra provider when API omits `$defs`
2 -
3 -## Overview
4 -
5 -`MastraProvider.wrapTool` calls `dereferenceJsonSchema` to inline JSON Schema `$ref`
6 -pointers before handing the schema to `@mastra/schema-compat`. That contract was
7 -introduced in PLEN-2244 (commit `cc673b654`) and assumes every `#/$defs/...` ref
8 -has a resolvable target. The Composio API ships at least one toolkit family
9 -(Gmail, and any other toolkit whose `outputParameters` uses `$ref`) where the
10 -schema declares `"$ref": "#/$defs/FetchEmailsResponse"` **without ever declaring
11 -`$defs`**. The current resolver correctly throws a typed
12 -`JsonSchemaRefResolutionError`, but that error escapes `wrapTool` and crashes
13 -`composio.tools.get(...)` upfront — making affected toolkits unusable through
14 -the Mastra provider.
15 -
16 -This plan makes `dereferenceJsonSchema` opt-in lenient against unresolved
17 -internal refs (using the existing cycle sentinel, `{ type: 'object', additionalProperties: true }`),
18 -opts the Mastra provider into that lenient mode with a one-shot per-tool warning,
19 -and locks the behavior in with red-green regression tests that mirror the exact
20 -`GMAIL_FETCH_EMAILS` shape from the Linear ticket.
21 -
22 -> **API-side follow-up (out of scope here):** the proper long-term fix is for
23 -> `/api/v3/tools/:slug` to emit a top-level `$defs` block alongside any `$ref`
24 -> it produces. That fix benefits every consumer (Mastra, Vercel AI SDK, future
25 -> providers). It is tracked separately so the SDK does not have to block on
26 -> the backend roll-out.
27 -
28 -## Problem Statement / Motivation
29 -
30 -### Reproduction (from PLEN-2451, verified 2026-05-10)
31 -
32 -Direct dump of `GMAIL_FETCH_EMAILS.outputParameters` via
33 -`composio.tools.getRawComposioTools(...)`:
34 -
35 -```jsonc
36 -{
37 - "type": "object",
38 - "properties": {
39 - "data": {
40 - "description": "Data from the action execution",
41 - "title": "Data",
42 - "$ref": "#/$defs/FetchEmailsResponse" // ← points into $defs
43 - },
44 - "error": { "type": "string", "description": "...", "title": "Error" },
45 - "successful": { "type": "boolean", "description": "...", "title": "Successful" }
46 - },
47 - "required": ["data", "successful"],
48 - "title": "FetchEmailsResponseWrapper"
49 - // ← no `$defs` block anywhere
50 -}
51 -```
52 -
53 -Observed behavior:
54 -
55 -| Version pair | Failure mode |
56 -| --------------------------------- | ----------------------------------------------------------------------------------------------------- |
57 -| `@composio/{core,mastra}@0.6.11` | `tools.get` returns a degraded Standard Schema whose `output()` crashes at runtime; agent sees a ~600B validation-error stub. |
58 -| `@composio/{core,mastra}@0.9.0` (latest) | `tools.get` itself throws `JsonSchemaRefResolutionError: Cannot resolve $ref #/$defs/FetchEmailsResponse` upfront. |
59 -
60 -The 0.9.0 behavior is *correct* given the PLEN-2244 strict contract — but the
61 -contract is wrong for upstream-supplied schemas the SDK cannot edit. Every
62 -toolkit whose `outputParameters` carries a `$ref` (Gmail, Slack, Google
63 -Calendar, …) currently breaks Mastra integration.
64 -
65 -### Why the reporter's "Option A" fix does not work
66 -
67 -GitHub issue [#3307](https://github.com/ComposioHQ/composio/issues/3307)
68 -proposes inlining `$defs` before calling `applyCompatLayer`. That is exactly
69 -what PLEN-2244 already does (`ts/packages/providers/mastra/src/index.ts:100-110`).
70 -The root cause is **upstream of** `applyCompatLayer`: there is no `$defs` to
71 -inline. PLEN-2244's fix surfaces a dangling pointer instead of silently
72 -producing a permissive `anyOf`, which is the right developer experience for
73 -custom tools but the wrong one for opaque API-supplied schemas.
74 -
75 -## Proposed Solution
76 -
77 -Two-tier fix that keeps the same architecture as PLEN-2244:
78 -
79 -### 1. `@composio/core` — add an `onUnresolved` option to `dereferenceJsonSchema`
80 -
81 -`ts/packages/core/src/utils/jsonSchema.ts`
82 -
83 -```typescript
84 -export type UnresolvedRefStrategy = 'throw' | 'sentinel';
85 -
86 -export interface DereferenceJsonSchemaOptions {
87 - /**
88 - * What to do when a `#/$defs/...` or `#/definitions/...` $ref cannot be
89 - * resolved (target missing, $defs/definitions block absent, malformed
90 - * pointer beneath an internal #/ prefix).
91 - *
92 - * - `'throw'` (default): preserve current behavior — throw
93 - * `JsonSchemaRefResolutionError`. Right for first-party / custom-tool
94 - * schemas where a dangling ref is a developer bug.
95 - * - `'sentinel'`: replace the offending node with the cycle-break
96 - * sentinel (`{ type: 'object', additionalProperties: true }`). Right for
97 - * schemas sourced from an upstream service the caller cannot edit.
98 - * Each replacement invokes `onReplace` exactly once.
99 - */
100 - onUnresolved?: UnresolvedRefStrategy;
101 - /**
102 - * Callback invoked once per replaced node (only when `onUnresolved === 'sentinel'`).
103 - * Lets callers emit one-shot warnings without losing the offending pointer.
104 - */
105 - onReplace?: (ref: string, reason: 'missing-target' | 'malformed-pointer') => void;
106 -}
107 -
108 -export function dereferenceJsonSchema<T = unknown>(
109 - schema: T,
110 - options?: DereferenceJsonSchemaOptions
111 -): T { /* … */ }
112 -```
113 -
114 -Implementation notes:
115 -
116 -- The walker already produces `CYCLE_BREAK_SENTINEL` on detected cycles
117 - (`jsonSchema.ts:9, 98, 107, 127`). The lenient branch reuses **the same
118 - sentinel constant** so cycles and dangling refs share semantics: "we can't
119 - resolve this further; fall back to a permissive object".
120 -- `resolvePointer` currently throws via `failResolution`
121 - (`jsonSchema.ts:19-24, 26-36`). Refactor: have `failResolution` return a
122 - discriminator (`{ kind: 'unresolved', ref, reason }`) consumed by the walker,
123 - so the lenient and strict branches share a single code path. Strict mode
124 - throws at the boundary, lenient mode emits the sentinel + invokes
125 - `onReplace`. Net change to strict-mode behavior: zero.
126 -- The chain-depth cap (`MAX_REF_CHAIN_DEPTH`) and node-depth cap
127 - (`MAX_NODE_DEPTH`) keep throwing in **both** modes — those are safety caps,
128 - not data-shape issues. Document this in the JSDoc.
129 -- External (`http://`, `https://`, `file://`) refs continue to be left as-is
130 - with a single audit-log `logger.warn` per call (`jsonSchema.ts:113-118`).
131 - Unchanged.
132 -- `$defs` / `definitions` continue to be stripped from the returned root
133 - (`jsonSchema.ts:148-152`). Unchanged.
134 -
135 -### 2. `@composio/mastra` — opt into lenient mode with a per-tool warning
136 -
137 -`ts/packages/providers/mastra/src/index.ts`
138 -
139 -```typescript
140 -wrapTool(tool: Tool, executeTool: ExecuteToolFn): MastraTool {
141 - // ...existing strict-mode branch for inputParameters...
142 -
143 - // Output schemas come straight from the Composio API. The API can emit a
144 - // `$ref: "#/$defs/..."` without declaring `$defs` (PLEN-2451) — strict
145 - // mode would crash `tools.get` upfront. Fall back to the permissive
146 - // object sentinel and emit a single warning so the degraded shape is
147 - // observable in the agent's logs.
148 - const onReplace = (ref: string) => this.warnDanglingRefOnce(tool.slug, ref);
149 -
150 - const inputSchema = applyCompatLayer({
151 - schema: dereferenceJsonSchema(parameters ?? {}, {
152 - onUnresolved: 'sentinel',
153 - onReplace,
154 - }),
155 - compatLayers: [],
156 - mode: 'jsonSchema',
157 - });
158 -
159 - const outputSchema = applyCompatLayer({
160 - schema: dereferenceJsonSchema(tool.outputParameters ?? {}, {
161 - onUnresolved: 'sentinel',
162 - onReplace,
163 - }),
164 - compatLayers: [],
165 - mode: 'jsonSchema',
166 - });
167 -
168 - // ...createTool(...)...
169 -}
170 -```
171 -
172 -Add a small instance-scoped `Set<string>` (`warnedDanglingRefs`, keyed by
173 -`${slug}:${ref}`) so a Mastra agent that wraps the same tool many times only
174 -emits one warning per `(tool, ref)` pair. The warning message names the
175 -toolkit slug, tool slug, and the dangling pointer:
176 -
177 -```
178 -[composio/mastra] Tool GMAIL_FETCH_EMAILS (toolkit gmail) declares
179 -$ref #/$defs/FetchEmailsResponse but no matching $defs entry. Falling
180 -back to a permissive object schema for this branch — the wrapped
181 -Mastra tool will validate the response loosely. Tracked in
182 -https://linear.app/composio/issue/PLEN-2451.
183 -```
184 -
185 -Why warn (not silent fallback)?
186 -
187 -- **Why:** customers iterating on a Mastra agent need to know they got a
188 - degraded schema; otherwise the failure mode becomes "agent validates loosely
189 - and you never find out why a downstream typed consumer broke". The warning
190 - also gives us a signal we can pipe into telemetry to prioritize the
191 - API-side fix.
192 -- **How to apply:** rate-limit per `(slug, ref)` so noisy agents don't spam
193 - the log; never emit at module-load (the warning has to point at a concrete
194 - tool slug).
195 -
196 -### Why the fix stays inside `MastraProvider.wrapTool`
197 -
198 -It is tempting to dereference centrally — in
199 -`Tools.transformToolCases` (`Tools.ts:140`) or
200 -`Tools.applyDefaultSchemaModifiers` (`Tools.ts:192`). That would be wrong for
201 -three reasons:
202 -
203 -1. **No other provider needs this for output schemas.** Vercel
204 - (`ts/packages/providers/vercel/src/index.ts:108-133`) only feeds
205 - `inputParameters` to its Zod converter, and OpenAI/Anthropic/Google bind
206 - tool *input* schemas to function-calling APIs that ignore output shapes.
207 - `outputParameters` validation is a Mastra-specific surface.
208 -2. **Centralized dereferencing would mutate `tools.get()`'s public shape.**
209 - Users today read raw `inputParameters` / `outputParameters` from
210 - `tools.get` and `getRawComposioToolBySlug` and expect them to mirror the
211 - API response (modulo case transformation in `transformToolCases`).
212 - Inlining `$defs` for every caller — including ones whose consumers can
213 - resolve `$ref` natively — is a silent behavior change for non-Mastra
214 - users.
215 -3. **PLEN-2244 set the precedent.** Both fixes share the same boundary:
216 - the provider that owns the validation contract is the provider that
217 - pre-processes the schema. Keeping the new lenient path at the same
218 - boundary preserves architectural consistency.
219 -
220 -## Acceptance Criteria
221 -
222 -### Code
223 -
224 -- [x] `dereferenceJsonSchema` accepts an optional second arg
225 - `{ onUnresolved?: 'throw' | 'sentinel'; onReplace?: (ref, reason) => void }`.
226 -- [x] Default behavior (no opts) is byte-for-byte unchanged: still throws
227 - `JsonSchemaRefResolutionError` on a dangling internal `$ref`.
228 -- [x] Lenient mode (`onUnresolved: 'sentinel'`) replaces the offending node
229 - with the existing `CYCLE_BREAK_SENTINEL` and invokes `onReplace` exactly
230 - once per replacement, passing the original ref pointer + reason.
231 -- [x] Lenient mode still throws on `MAX_REF_CHAIN_DEPTH` /
232 - `MAX_NODE_DEPTH` breaches (safety caps are not lenient).
233 -- [x] `MastraProvider.wrapTool` calls `dereferenceJsonSchema(..., {
234 - onUnresolved: 'sentinel', onReplace })` for both `inputParameters` and
235 - `outputParameters`.
236 -- [x] `MastraProvider` warns once per `(toolSlug, refPointer)` pair via
237 - `@composio/core`'s `logger.warn`.
238 -- [x] No public TypeScript API is *removed*; the new opts arg is purely additive.
239 -
240 -### Tests (red before fix; green after)
241 -
242 -- [x] New unit tests in `ts/packages/core/test/utils/jsonSchema.test.ts`
243 - (9 new cases, all under `describe("with onUnresolved: 'sentinel' lenient mode")`):
244 - sentinel replaces dangling ref; sentinel replaces missing-key ref;
245 - `onReplace` invoked with ref + `'missing-target'`; `onReplace` invoked
246 - with `'malformed-pointer'` for non-`#/` pointers; chain-depth cap still
247 - throws; node-depth cap still throws; explicit `'throw'` matches default;
248 - `onReplace` not called in strict mode; mixed schema preserves resolvable
249 - branches while replacing only the dangling one.
250 -- [x] New regression test file
251 - `ts/packages/providers/mastra/test/mastra-dangling-defs.test.ts`
252 - (6 cases, un-mocked `@mastra/schema-compat`): no throw on dangling
253 - output ref (GMAIL shape); defined outputSchema with no surviving `$ref`;
254 - one warn per `(slug, ref)` pair across repeat wraps; separate warning
255 - per slug; symmetric tolerance on input refs; resolvable `$defs` still
256 - preserved.
257 -- [x] All existing tests still pass: core 908; mastra-ref 3; mastra.test 39;
258 - every other provider/cli package green.
259 -
260 -### Changeset
261 -
262 -- [x] `.changeset/fix-mastra-dangling-defs-ref.md` added — `@composio/core`
263 - and `@composio/mastra` both bumped patch; body describes the API
264 - behavior, the new `onUnresolved`/`onReplace` opt, and the Mastra opt-in.
265 - No Linear IDs (per repo convention — changesets ship to npm).
266 -
267 -### Manual verification
268 -
269 -- [ ] (Post-merge) Reproduce against the live API using the script from the
270 - tracking issue: `tools.get(userId, { tools: ['GMAIL_FETCH_EMAILS'] })`
271 - should return a `MastraTool` object whose `outputSchema` is defined.
272 -- [ ] Confirm the SDK logs exactly one warning per process per `(slug, ref)`
273 - pair with the expected message.
274 -
275 -## Red-Green Test Strategy
276 -
277 -The TDD loop:
278 -
279 -1. **Red — write tests + the new error/option signature.** No production
280 - implementation yet.
281 - - Add the new `DereferenceJsonSchemaOptions` interface and export it.
282 - - Type-only stub: `dereferenceJsonSchema` still accepts an unused second
283 - arg (`_options?: DereferenceJsonSchemaOptions`).
284 - - Add the four new `jsonSchema.test.ts` cases. They fail with
285 - `JsonSchemaRefResolutionError` (current strict behavior) or compile
286 - errors (if `onReplace` callback isn't exposed yet).
287 - - Add the four new `mastra-dangling-defs.test.ts` cases. They fail with
288 - `JsonSchemaRefResolutionError` propagated up from `wrapTool`.
289 -
290 -2. **Green — minimum implementation.**
291 - - Plumb the `onUnresolved` strategy through `walk` / `resolvePointer` /
292 - `stepInto`. Reuse `CYCLE_BREAK_SENTINEL`.
293 - - Wire `onReplace` invocations at the two failure call sites
294 - (`resolvePointer`'s missing target, `stepInto`'s non-object cursor).
295 - - Add `warnDanglingRefOnce` to `MastraProvider`, invoke from the two
296 - `wrapTool` call sites.
297 -
298 -3. **Refactor — tighten.**
299 - - Verify no allocation in the strict path (the new branch must be a
300 - zero-cost extension on the existing happy path).
301 - - Run the full `jsonSchema.test.ts` + `mastra-ref.test.ts` +
302 - `mastra-dangling-defs.test.ts` matrix to confirm no regressions.
303 -
304 -## Technical Considerations
305 -
306 -### Security
307 -
308 -- The sentinel (`{ type: 'object', additionalProperties: true }`) is the
309 - most permissive valid object schema. A schema falling back to it means
310 - Mastra's `validateToolOutput` will accept anything — *for that branch
311 - only*. The siblings (e.g. `required`, `title`) at the parent level are
312 - unaffected. This is strictly more permissive than `dereferenceJsonSchema`'s
313 - current "throw and refuse to run" behavior, so it does not introduce a new
314 - validation-bypass vector for trusted tool authors.
315 -- Prototype-pollution filter (`POLLUTING_KEYS` at `jsonSchema.ts:10`) and
316 - `WeakSet` cycle tracking are unaffected.
317 -
318 -### Performance
319 -
320 -- Walker still visits each node at most once. The new branch is an extra
321 - `if (strategy === 'sentinel') return CYCLE_BREAK_SENTINEL` after
322 - `resolvePointer` throws or returns the "unresolved" discriminator. No new
323 - allocations in the common (resolvable) path.
324 -
325 -### Compatibility
326 -
327 -- `DereferenceJsonSchemaOptions` is **additive**. Both the public
328 - `dereferenceJsonSchema` export (consumed by `@composio/mastra`) and the
329 - internal call sites can ignore the new parameter.
330 -- The `JsonSchemaRefResolutionError` class is unchanged. Callers that catch
331 - it (none today outside the test suite) keep working.
332 -- The default mode is `'throw'`, matching the PLEN-2244 contract. Custom-tool
333 - authors who deliberately point `$ref` at a non-existent `$defs` entry will
334 - still get a hard error — that is the right behavior for *their* schemas.
335 -
336 -## Dependencies & Risks
337 -
338 -- **No dependency bumps.** Unlike PLEN-2244 (which bumped
339 - `@mastra/schema-compat` to `^1.2.9`), this fix is internal to the SDK.
340 -- **Risk: developer surprise on raw schemas.** A reader of
341 - `getRawComposioTools(...)` sees `$ref` in the raw schema and finds it
342 - resolved to a sentinel in `wrapTool` output. Mitigation: the JSDoc on
343 - `dereferenceJsonSchema` documents the lenient contract, and the warning
344 - emitted by `MastraProvider` names the offending pointer.
345 -- **Risk: telemetry noise.** A user wrapping every Gmail tool in a wide
346 - toolkit fetch could see many warnings on first run. Mitigation: per-tool
347 - dedup in the Mastra provider; warning text points at the upstream Linear
348 - ticket so callers know it is a known, tracked issue.
349 -
350 -## File-Level Plan
351 -
352 -```
353 -ts/packages/core/src/utils/jsonSchema.ts # add opts; reuse CYCLE_BREAK_SENTINEL
354 -ts/packages/core/test/utils/jsonSchema.test.ts # 4 new cases (red → green)
355 -ts/packages/core/src/index.ts # re-export DereferenceJsonSchemaOptions if needed
356 -ts/packages/providers/mastra/src/index.ts # opt into 'sentinel' + per-tool warn dedup
357 -ts/packages/providers/mastra/test/mastra-dangling-defs.test.ts # new file, 4 cases (red → green)
358 -.changeset/fix-mastra-dangling-defs-ref.md # patch/patch
359 -```
360 -
361 -Pseudocode for the touchpoints:
362 -
363 -### `ts/packages/core/src/utils/jsonSchema.ts`
364 -
365 -```typescript
366 -export type UnresolvedRefStrategy = 'throw' | 'sentinel';
367 -
368 -export interface DereferenceJsonSchemaOptions {
369 - onUnresolved?: UnresolvedRefStrategy;
370 - onReplace?: (ref: string, reason: 'missing-target' | 'malformed-pointer') => void;
371 -}
372 -
373 -const failResolution = (
374 - pointer: string,
375 - segment: string,
376 - strategy: UnresolvedRefStrategy,
377 - onReplace?: DereferenceJsonSchemaOptions['onReplace']
378 -): typeof CYCLE_BREAK_SENTINEL => {
379 - if (strategy === 'sentinel') {
380 - onReplace?.(pointer, 'malformed-pointer');
381 - return { ...CYCLE_BREAK_SENTINEL };
382 - }
383 - throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
384 - meta: { ref: pointer, failedAt: segment },
385 - possibleFixes: REF_RESOLUTION_FIXES,
386 - });
387 -};
388 -// `resolvePointer` and `stepInto` receive `strategy` + `onReplace` and forward to `failResolution`.
389 -// `walk` checks for the sentinel return shape and stops descending.
390 -```
391 -
392 -### `ts/packages/providers/mastra/src/index.ts`
393 -
394 -```typescript
395 -private warnedDanglingRefs = new Set<string>();
396 -
397 -private warnDanglingRefOnce(toolSlug: string, toolkitSlug: string, ref: string) {
398 - const key = `${toolSlug}:${ref}`;
399 - if (this.warnedDanglingRefs.has(key)) return;
400 - this.warnedDanglingRefs.add(key);
401 - logger.warn(
402 - `[composio/mastra] Tool ${toolSlug} (toolkit ${toolkitSlug}) declares ` +
403 - `$ref ${ref} but no matching $defs/definitions entry. Falling back to a ` +
404 - `permissive object schema for this branch — the wrapped Mastra tool will ` +
405 - `validate loosely. See https://linear.app/composio/issue/PLEN-2451.`
406 - );
407 -}
408 -```
409 -
410 -## References & Research
411 -
412 -### Linear / GitHub
413 -
414 -- Linear ticket: PLEN-2451 — *MastraProvider $defs/$ref schema is dangling at the API source*.
415 -- Customer-facing GitHub issue: https://github.com/ComposioHQ/composio/issues/3307 (reported by `@0xpaperhead`, 2026-04-28).
416 -- Prior, related fix: PLEN-2244 (commits `5300bf8ba` red tests, `cc673b654` fix). Closed by `.changeset/fix-mastra-ref-dereference.md`.
417 -
418 -### Files
419 -
420 -- `ts/packages/providers/mastra/src/index.ts:80-126` — `MastraProvider.wrapTool` (the call site that needs to opt into lenient mode).
421 -- `ts/packages/core/src/utils/jsonSchema.ts:64-153` — `dereferenceJsonSchema` (the helper that needs the new opt).
422 -- `ts/packages/core/src/utils/jsonSchema.ts:9` — `CYCLE_BREAK_SENTINEL` (the sentinel to reuse).
423 -- `ts/packages/core/src/utils/jsonSchema.ts:19-36` — `failResolution` / `stepInto` (refactor target).
424 -- `ts/packages/core/src/errors/ValidationErrors.ts:89-99` — `JsonSchemaRefResolutionError` (unchanged).
425 -- `ts/packages/core/test/utils/jsonSchema.test.ts:150-158` — existing strict-mode test (the contract we keep as default).
426 -- `ts/packages/providers/mastra/test/mastra-ref.test.ts` — pattern to mirror for the new test file.
427 -- `ts/packages/providers/vercel/src/index.ts:108-133` — confirms `outputParameters` is Mastra-only.
428 -- `ts/packages/core/src/types/tool.types.ts:29-102` — `JSONSchemaPropertySchema` admits `$ref` / `$defs` / `definitions` (so the raw shape we test against is valid against `ToolSchema`).
429 -- `ts/packages/core/src/models/Tools.ts:140-150, 192-198` — confirms the central pipeline does *not* pre-process schemas and that the provider boundary is the right one.
430 -
431 -### External
432 -
433 -- JSON Pointer (RFC 6901) — escape semantics already handled correctly at `jsonSchema.ts:16-17`.
434 -- JSON Schema 2020-12 — sibling-keyword merge semantics already handled correctly at `jsonSchema.ts:133-141`.
435 -- `@mastra/schema-compat` — AJV-backed; refuses to compile schemas with unresolved internal `$ref`. Bundles `convertSchemaToZod` which silently degrades `$ref` → permissive `anyOf` when AJV is bypassed (the pre-PLEN-2244 failure mode).
pnpm-lock.yaml
-16
@@ -524,22 +524,6 @@ importers:
524 specifier: 'catalog:'
525 version: 5.9.3
526
527 - ts/examples/cjs:
528 - dependencies:
529 - '@composio/core':
530 - specifier: workspace:*
531 - version: link:../../packages/core
532 - dotenv:
533 - specifier: ^16.4.1
534 - version: 16.6.1
535 - devDependencies:
536 - '@types/bun':
537 - specifier: ^1.2.9
538 - version: 1.3.9
539 - typescript:
540 - specifier: 'catalog:'
541 - version: 5.9.3
542 -
527 ts/examples/cloudflare-wrangler:
528 dependencies:
529 '@composio/core':
test/release-workflow.test.ts
-1
@@ -381,7 +381,6 @@ esac
381 {
382 name: 'changeset-peer-fixture',
383 private: true,
384 - packageManager: packageJson.packageManager,
384 workspaces: ['packages/*'],
385 },
386 null,
ts/docs/internal/release.md
+1 -3
@@ -78,8 +78,7 @@ The manual release process is available for cases where direct control over the
78
79 ### Prerequisites
80
81 -- Node.js, Bun, Python, Deno, and uv from `mise.toml`
82 -- pnpm from `package.json#packageManager` via corepack
81 +- Node.js, Bun, Python, Deno, uv, and pnpm from `mise.toml`
82 - Access to npm registry
83 - Write access to the repository
84
@@ -94,7 +93,6 @@ The manual release process is available for cases where direct control over the
93
94 # Install dependencies
95 mise install
97 - corepack enable
96 pnpm install
97
98 # Run quality checks
ts/e2e-tests/README.md
+4 -2
@@ -26,7 +26,7 @@ ts/e2e-tests/
26 │ └── README.md # Utils documentation
27 ├── runtimes/
28 ├── node/ # Node.js runtime tests
29 - │ ├── cjs-basic/ # CommonJS compatibility tests
29 + │ ├── cjs-basic/ # Node.js 22 require(esm) interop tests
30 │ ├── custom-tools/ # Custom local tools execution (session.execute, proxyExecute, Zod validation)
31 │ ├── esm-basic/ # ESM compatibility tests
32 │ ├── json-schema-to-zod-v3/ # @composio/json-schema-to-zod + Zod v3 tests
@@ -196,7 +196,9 @@ import { TIMEOUTS } from '@e2e-tests/utils/const';
196 import { describe, it, expect, beforeAll } from 'bun:test';
197
198 e2e(import.meta.url, {
199 - nodeVersions: ['22.22.3', '24.16.0', '25.9.0'],
199 + versions: {
200 + node: ['22.22.3', '24.16.0', '25.9.0'],
201 + },
202 usesFixtures: true, // Sets cwd to fixtures/ directory
203 env: { MY_API_KEY: process.env.MY_API_KEY },
204 defineTests: ({ runFixture }) => {
ts/e2e-tests/_utils/Dockerfile.cli
+20 -11
@@ -1,24 +1,33 @@
1 # Reusable Dockerfile for CLI e2e tests (debian runtime)
2 -# Usage: docker build -f Dockerfile.cli --build-arg CLI_VERSION=0.1.24 --build-arg NODE_VERSION=22.22.3 --build-arg BUN_VERSION=1.3.10 -t test-name .
2 +# Usage: docker build -f Dockerfile.cli --build-arg CLI_VERSION=0.1.24 --build-arg NODE_VERSION=22.22.3 -t test-name .
3
4 ARG NODE_VERSION
5 -ARG BUN_VERSION
5 ARG CLI_VERSION=0.0.0
6
8 -FROM oven/bun:${BUN_VERSION} AS bun
9 -
7 FROM node:${NODE_VERSION}-slim AS builder
8
12 -ENV PNPM_HOME="/pnpm"
13 -ENV PATH="$PNPM_HOME:/usr/local/bin:$PATH"
9 +ENV MISE_DATA_DIR="/mise"
10 +ENV MISE_DISABLE_TOOLS="node,deno,python,uv"
11 +ENV PATH="/mise/shims:$PATH"
12
13 WORKDIR /app
14
17 -# Bring in bun binary from the official image (no curl)
18 -COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun
19 -
20 -# Install corepack (pnpm) without curl/git
21 -RUN corepack enable
15 +# Install system dependencies (mise needs curl + ca-certificates)
16 +RUN apt-get update && \
17 + apt-get install -y --no-install-recommends ca-certificates curl unzip && \
18 + rm -rf /var/lib/apt/lists/*
19 +
20 +# Install bun + pnpm via mise (versions pinned in mise.toml/mise.lock).
21 +# mise is installed to /usr/local/bin and the tool binaries are symlinked there too;
22 +# Node is disabled so the base image's Node is used.
23 +RUN curl -fsSL https://mise.run | MISE_INSTALL_PATH=/usr/local/bin/mise sh
24 +COPY mise.toml mise.lock ./
25 +RUN mise trust /app/mise.toml && \
26 + mise install && \
27 + ln -sf "$(mise which bun)" /usr/local/bin/bun && \
28 + ln -sf "$(mise which pnpm)" /usr/local/bin/pnpm && \
29 + pnpm --version && \
30 + bun --version
31
32 # Copy lockfile first for optimal layer caching
33 COPY pnpm-lock.yaml ./
ts/e2e-tests/_utils/Dockerfile.deno
+19 -12
@@ -1,18 +1,21 @@
1 # Reusable Dockerfile for Deno e2e tests
2 -# Usage: docker build -f Dockerfile.deno --build-arg DENO_VERSION=2.6.7 --build-arg NODE_MAJOR=20 --build-arg BUN_VERSION=1.3.10 -t test-name .
2 +# Usage: docker build -f Dockerfile.deno --build-arg DENO_VERSION=2.6.7 --build-arg NODE_MAJOR=22 -t test-name .
3 #
4 # Uses official denoland/deno images. For multi-version testing, run the build/run
5 # multiple times with different DENO_VERSION values from the shell script.
6 +#
7 +# Deno is the test matrix axis (base image); Node comes from nodesource (needed by
8 +# pnpm and the build). bun and pnpm are installed from mise.toml/mise.lock, with
9 +# node/deno disabled in mise so it does not shadow the base/nodesource binaries.
10
11 ARG DENO_VERSION
12
13 FROM denoland/deno:${DENO_VERSION}
14 ARG NODE_MAJOR
11 -ARG BUN_VERSION
15
13 -ENV PNPM_HOME="/pnpm"
14 -ENV BUN_INSTALL="/usr/local"
15 -ENV PATH="$BUN_INSTALL/bin:$PNPM_HOME:$PATH"
16 +ENV MISE_DATA_DIR="/mise"
17 +ENV MISE_DISABLE_TOOLS="node,deno,python,uv"
18 +ENV PATH="/mise/shims:$PATH"
19
20 # Switch to root for installation
21 USER root
@@ -24,17 +27,21 @@ RUN apt-get update && \
27 apt-get install -y --no-install-recommends ca-certificates curl unzip && \
28 rm -rf /var/lib/apt/lists/*
29
27 -# Install Node.js (needed for pnpm and building packages)
30 +# Install Node.js (needed for pnpm's npm backend and building packages)
31 RUN curl -fsSL "https://deb.nodesource.com/setup_${NODE_MAJOR}.x" | bash - && \
32 apt-get install -y nodejs && \
33 rm -rf /var/lib/apt/lists/*
34
32 -# Install corepack (for pnpm)
33 -RUN npm i -g corepack@latest && \
34 - corepack enable
35 -
36 -# Install Bun
37 -RUN curl -fsSL https://bun.sh/install | BUN_INSTALL=/usr/local bash -s "bun-v${BUN_VERSION}" && \
35 +# Install bun + pnpm via mise (versions pinned in mise.toml/mise.lock).
36 +# mise is installed to /usr/local/bin and the tool binaries are symlinked there too so
37 +# they stay on PATH for the non-root runtime user (login shells reset PATH).
38 +RUN curl -fsSL https://mise.run | MISE_INSTALL_PATH=/usr/local/bin/mise sh
39 +COPY mise.toml mise.lock ./
40 +RUN mise trust /app/mise.toml && \
41 + mise install && \
42 + ln -sf "$(mise which bun)" /usr/local/bin/bun && \
43 + ln -sf "$(mise which pnpm)" /usr/local/bin/pnpm && \
44 + pnpm --version && \
45 bun --version
46
47 # Copy lockfile first for optimal layer caching
ts/e2e-tests/_utils/Dockerfile.node
+18 -11
@@ -1,17 +1,20 @@
1 # Reusable Dockerfile for Node.js e2e tests
2 -# Usage: docker build -f Dockerfile.node --build-arg NODE_VERSION=22.22.3 --build-arg BUN_VERSION=1.3.10 -t test-name .
2 +# Usage: docker build -f Dockerfile.node --build-arg NODE_VERSION=22.22.3 -t test-name .
3 #
4 # Uses official node:slim images. For multi-version testing, run the build/run
5 # multiple times with different NODE_VERSION values from the shell script.
6 +#
7 +# bun and pnpm are installed from mise.toml/mise.lock (the single source of truth).
8 +# Node is the test matrix axis and stays on the base image, so it is disabled in
9 +# mise (MISE_DISABLE_TOOLS) to avoid shadowing the base image's Node.
10
11 ARG NODE_VERSION
12
13 FROM node:${NODE_VERSION}-slim
10 -ARG BUN_VERSION
14
12 -ENV PNPM_HOME="/pnpm"
13 -ENV BUN_INSTALL="/usr/local"
14 -ENV PATH="$BUN_INSTALL/bin:$PNPM_HOME:$PATH"
15 +ENV MISE_DATA_DIR="/mise"
16 +ENV MISE_DISABLE_TOOLS="node,deno,python,uv"
17 +ENV PATH="/mise/shims:$PATH"
18
19 WORKDIR /app
20
@@ -20,12 +23,16 @@ RUN apt-get update && \
23 apt-get install -y --no-install-recommends ca-certificates curl unzip && \
24 rm -rf /var/lib/apt/lists/*
25
23 -# Install corepack (for pnpm)
24 -RUN npm i -g corepack@latest --force && \
25 - corepack enable
26 -
27 -# Install Bun
28 -RUN curl -fsSL https://bun.sh/install | BUN_INSTALL=/usr/local bash -s "bun-v${BUN_VERSION}" && \
26 +# Install bun + pnpm via mise (versions pinned in mise.toml/mise.lock).
27 +# mise is installed to /usr/local/bin; the tool binaries are symlinked there too so
28 +# they stay on PATH for the non-root runtime user (login shells reset PATH).
29 +RUN curl -fsSL https://mise.run | MISE_INSTALL_PATH=/usr/local/bin/mise sh
30 +COPY mise.toml mise.lock ./
31 +RUN mise trust /app/mise.toml && \
32 + mise install && \
33 + ln -sf "$(mise which bun)" /usr/local/bin/bun && \
34 + ln -sf "$(mise which pnpm)" /usr/local/bin/pnpm && \
35 + pnpm --version && \
36 bun --version
37
38 # Copy lockfile first for optimal layer caching
ts/e2e-tests/_utils/scripts/docker-build.ts
+8 -12
@@ -21,7 +21,6 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
21 type DockerToolchain = {
22 nodeVersion: string;
23 nodeMajorVersion: string;
24 - bunVersion: string;
24 };
25
26 function getRepoRoot(): string {
@@ -29,7 +28,9 @@ function getRepoRoot(): string {
28 return resolve(__dirname, '../../../..');
29 }
30
32 -function getMiseVersion(repoRoot: string, tool: 'node' | 'bun' | 'deno'): string {
31 +// bun and pnpm are installed inside the images from mise.toml/mise.lock, so only the
32 +// matrixed runtimes (node, deno) need to be resolved on the host and threaded as build args.
33 +function getMiseVersion(repoRoot: string, tool: 'node' | 'deno'): string {
34 try {
35 return execFileSync('mise', ['current', tool], { cwd: repoRoot, encoding: 'utf-8' }).trim();
36 } catch (err) {
@@ -46,7 +47,6 @@ function getDockerToolchain(repoRoot: string): DockerToolchain {
47 return {
48 nodeVersion,
49 nodeMajorVersion: getMajorVersion(nodeVersion),
49 - bunVersion: getMiseVersion(repoRoot, 'bun'),
50 };
51 }
52
@@ -75,11 +75,7 @@ function defaultNodeLabels(nodeVersion: string): Record<string, string> {
75 };
76 }
77
78 -async function buildNodeImage(
79 - nodeVersion: string,
80 - toolchain: DockerToolchain,
81 - repoRoot: string
82 -): Promise<boolean> {
78 +async function buildNodeImage(nodeVersion: string, repoRoot: string): Promise<boolean> {
79 const dockerfilePath = resolve(repoRoot, 'ts/e2e-tests/_utils/Dockerfile.node');
80 const imageTag = imageTagForNodeVersion(nodeVersion);
81 const labels = defaultNodeLabels(nodeVersion);
@@ -90,7 +86,7 @@ async function buildNodeImage(
86 console.log(`\nBuilding image for Node.js ${nodeVersion}...`);
87
88 const result =
93 - await $`docker build -f ${dockerfilePath} --build-arg NODE_VERSION=${nodeVersion} --build-arg BUN_VERSION=${toolchain.bunVersion} ${{ raw: labelArgs }} -t ${imageTag} ${repoRoot}`
89 + await $`docker build -f ${dockerfilePath} --build-arg NODE_VERSION=${nodeVersion} ${{ raw: labelArgs }} -t ${imageTag} ${repoRoot}`
90 .cwd(repoRoot)
91 .nothrow();
92
@@ -135,7 +131,7 @@ async function buildDenoImage(
131 console.log(`\nBuilding image for Deno ${denoVersion}...`);
132
133 const result =
138 - await $`docker build -f ${dockerfilePath} --build-arg DENO_VERSION=${denoVersion} --build-arg NODE_MAJOR=${toolchain.nodeMajorVersion} --build-arg BUN_VERSION=${toolchain.bunVersion} ${{ raw: labelArgs }} -t ${imageTag} ${repoRoot}`
134 + await $`docker build -f ${dockerfilePath} --build-arg DENO_VERSION=${denoVersion} --build-arg NODE_MAJOR=${toolchain.nodeMajorVersion} ${{ raw: labelArgs }} -t ${imageTag} ${repoRoot}`
135 .cwd(repoRoot)
136 .nothrow();
137
@@ -180,7 +176,7 @@ async function buildCliImage(
176 console.log(`\nBuilding image for CLI ${cliVersion}...`);
177
178 const result =
183 - await $`docker build -f ${dockerfilePath} --build-arg CLI_VERSION=${cliVersion} --build-arg NODE_VERSION=${toolchain.nodeVersion} --build-arg BUN_VERSION=${toolchain.bunVersion} ${{ raw: labelArgs }} -t ${imageTag} ${repoRoot}`
179 + await $`docker build -f ${dockerfilePath} --build-arg CLI_VERSION=${cliVersion} --build-arg NODE_VERSION=${toolchain.nodeVersion} ${{ raw: labelArgs }} -t ${imageTag} ${repoRoot}`
180 .cwd(repoRoot)
181 .nothrow();
182
@@ -271,7 +267,7 @@ async function main() {
267 // Build Node.js images
268 for (const version of nodeVersions) {
269 total++;
274 - const success = await buildNodeImage(version, dockerToolchain, repoRoot);
270 + const success = await buildNodeImage(version, repoRoot);
271 if (!success) {
272 failed++;
273 }
ts/e2e-tests/_utils/src/image-lifecycle.ts
+3 -10
@@ -185,7 +185,9 @@ export async function checkDocker(options: CheckDockerOptions = {}): Promise<Exe
185 return exec('docker', ['info'], { cwd: repoRoot });
186 }
187
188 -async function getMiseVersion(tool: 'node' | 'bun' | 'deno', repoRoot: string): Promise<string> {
188 +// bun and pnpm are installed inside the images from mise.toml/mise.lock, so only the
189 +// matrixed runtimes (node, deno) need to be resolved on the host and threaded as build args.
190 +async function getMiseVersion(tool: 'node' | 'deno', repoRoot: string): Promise<string> {
191 const result = await exec('mise', ['current', tool], { cwd: repoRoot });
192 const version = result.stdout.trim();
193 if (result.exitCode !== 0 || !version) {
@@ -230,7 +232,6 @@ export async function ensureNodeImage(
232 const dockerfilePath =
233 options.dockerfilePath ?? resolve(repoRoot, 'ts/e2e-tests/_utils/Dockerfile.node');
234 const imageTag = imageTagForNodeVersion(nodeVersion);
233 - const bunVersion = await getMiseVersion('bun', repoRoot);
235
236 const inspect = await exec('docker', ['image', 'inspect', imageTag], { cwd: repoRoot });
237 if (inspect.exitCode === 0) {
@@ -243,8 +244,6 @@ export async function ensureNodeImage(
244 dockerfilePath,
245 '--build-arg',
246 `NODE_VERSION=${nodeVersion}`,
246 - '--build-arg',
247 - `BUN_VERSION=${bunVersion}`,
247 ...labelsToArgs(defaultNodeLabels(nodeVersion)),
248 '-t',
249 imageTag,
@@ -416,7 +415,6 @@ export async function ensureDenoImage(
415 options.dockerfilePath ?? resolve(repoRoot, 'ts/e2e-tests/_utils/Dockerfile.deno');
416 const imageTag = imageTagForDenoVersion(denoVersion);
417 const nodeVersion = await getMiseVersion('node', repoRoot);
419 - const bunVersion = await getMiseVersion('bun', repoRoot);
418
419 const inspect = await exec('docker', ['image', 'inspect', imageTag], { cwd: repoRoot });
420 if (inspect.exitCode === 0) {
@@ -431,8 +429,6 @@ export async function ensureDenoImage(
429 `DENO_VERSION=${denoVersion}`,
430 '--build-arg',
431 `NODE_MAJOR=${getMajorVersion(nodeVersion)}`,
434 - '--build-arg',
435 - `BUN_VERSION=${bunVersion}`,
432 ...labelsToArgs(defaultDenoLabels(denoVersion)),
433 '-t',
434 imageTag,
@@ -605,7 +601,6 @@ export async function ensureCliImage(
601 options.dockerfilePath ?? resolve(repoRoot, 'ts/e2e-tests/_utils/Dockerfile.cli');
602 const imageTag = imageTagForCliVersion(cliVersion);
603 const nodeVersion = await getMiseVersion('node', repoRoot);
608 - const bunVersion = await getMiseVersion('bun', repoRoot);
604
605 const inspect = await exec('docker', ['image', 'inspect', imageTag], { cwd: repoRoot });
606 if (inspect.exitCode === 0) {
@@ -620,8 +615,6 @@ export async function ensureCliImage(
615 `CLI_VERSION=${cliVersion}`,
616 '--build-arg',
617 `NODE_VERSION=${nodeVersion}`,
623 - '--build-arg',
624 - `BUN_VERSION=${bunVersion}`,
618 ...labelsToArgs(defaultCliLabels(cliVersion)),
619 '-t',
620 imageTag,
ts/e2e-tests/_utils/src/types.ts
+22 -7
@@ -1,4 +1,8 @@
1 -import { WELL_KNOWN_NODE_VERSIONS, WELL_KNOWN_DENO_VERSIONS, WELL_KNOWN_CLI_VERSIONS } from './const';
1 +import {
2 + WELL_KNOWN_NODE_VERSIONS,
3 + WELL_KNOWN_DENO_VERSIONS,
4 + WELL_KNOWN_CLI_VERSIONS,
5 +} from './const';
6
7 export type NonEmptyArray<T> = [T, ...T[]];
8
@@ -13,9 +17,9 @@ export type NonEmptyArray<T> = [T, ...T[]];
17 */
18 export type NonEmptyString<T extends string> = T extends '' ? never : T;
19
16 -export type NodeVersionFromUser = typeof WELL_KNOWN_NODE_VERSIONS[number];
17 -export type DenoVersionFromUser = typeof WELL_KNOWN_DENO_VERSIONS[number];
18 -export type CliVersionFromUser = typeof WELL_KNOWN_CLI_VERSIONS[number];
20 +export type NodeVersionFromUser = (typeof WELL_KNOWN_NODE_VERSIONS)[number];
21 +export type DenoVersionFromUser = (typeof WELL_KNOWN_DENO_VERSIONS)[number];
22 +export type CliVersionFromUser = (typeof WELL_KNOWN_CLI_VERSIONS)[number];
23
24 /**
25 * Result of CI skip check for a specific Node version.
@@ -30,7 +34,11 @@ export interface SkipInCI {
34 * Includes skip state for CI mode.
35 */
36 export type NodeVersionMeta =
33 - | { kind: 'static'; value: Exclude<typeof WELL_KNOWN_NODE_VERSIONS[number], 'current'>; skip: SkipInCI }
37 + | {
38 + kind: 'static';
39 + value: Exclude<(typeof WELL_KNOWN_NODE_VERSIONS)[number], 'current'>;
40 + skip: SkipInCI;
41 + }
42 | { kind: 'overridden'; value: string; skip: SkipInCI }
43 | { kind: 'current'; value: string; skip: SkipInCI };
44
@@ -39,7 +47,11 @@ export type NodeVersionMeta =
47 * Includes skip state for CI mode.
48 */
49 export type DenoVersionMeta =
42 - | { kind: 'static'; value: Exclude<typeof WELL_KNOWN_DENO_VERSIONS[number], 'current'>; skip: SkipInCI }
50 + | {
51 + kind: 'static';
52 + value: Exclude<(typeof WELL_KNOWN_DENO_VERSIONS)[number], 'current'>;
53 + skip: SkipInCI;
54 + }
55 | { kind: 'overridden'; value: string; skip: SkipInCI }
56 | { kind: 'current'; value: string; skip: SkipInCI };
57
@@ -128,7 +140,10 @@ export interface DefineTestsContext {
140 /** Run an arbitrary command in the Docker container */
141 runCmd: {
142 <const C extends string>(command: NonEmptyString<C>): Promise<E2ETestResult>;
131 - <const C extends string, const F extends string>(options: { command: NonEmptyString<C>; files: NonEmptyArray<F> }): Promise<E2ETestResultWithFiles<F>>;
143 + <const C extends string, const F extends string>(options: {
144 + command: NonEmptyString<C>;
145 + files: NonEmptyArray<F>;
146 + }): Promise<E2ETestResultWithFiles<F>>;
147 };
148 /**
149 * Run a fixture file with Node.js.
ts/e2e-tests/runtimes/node/cjs-basic/README.md
+19 -25
@@ -1,43 +1,37 @@
1 -# Node.js CommonJS Compatibility Test
1 +# Node.js CommonJS require(esm) Interop Test
2
3 -Verifies that `@composio/core` works correctly when imported via `require()` in CommonJS environments.
3 +Verifies that `@composio/core` can still be loaded from a CommonJS caller on Node.js 22 through Node's native `require(esm)` support, without Composio publishing CommonJS artifacts.
4
5 ## Why This Exists
6
7 -Many Node.js projects still use CommonJS. This suite ensures:
7 +The TypeScript SDK packages are ESM-only. This suite ensures:
8
9 -- `require('@composio/core')` resolves without errors
10 -- All public exports are accessible
11 -- Classes can be instantiated
12 -- No ESM-only syntax leaks into CJS builds
9 +- `require('@composio/core')` works on Node.js 22, 24, and 25.
10 +- `require.resolve('@composio/core')` resolves to `dist/index.mjs`, not a `.cjs` artifact.
11 +- The main public exports remain available through Node's native CommonJS-to-ESM interop.
12
13 ## What It Tests
14
16 -| Test | Description |
17 -| --------------------- | ----------------------------------------- |
18 -| Basic require | `require('@composio/core')` doesn't throw |
19 -| Composio class | Main class is exported and constructible |
20 -| OpenAIProvider | Provider class exports and instantiation |
21 -| AuthScheme | Auth enum is accessible |
22 -| ComposioError | Error classes are exported |
23 -| jsonSchemaToZodSchema | Utility function is exported |
24 -| constants | Constants namespace is accessible |
25 -| logger | Logger instance is exported |
15 +| Test | Description |
16 +| --------------------- | ----------------------------------------------------- |
17 +| require(esm) support | Node exposes native `process.features.require_module` |
18 +| Entry resolution | `@composio/core` resolves to `dist/index.mjs` |
19 +| CommonJS require | `require('@composio/core')` doesn't throw |
20 +| Composio class | Main class is exported and constructible |
21 +| OpenAIProvider | Provider class exports and instantiation |
22 +| AuthScheme | Auth enum is accessible |
23 +| ComposioError | Error classes are exported |
24 +| jsonSchemaToZodSchema | Utility function is exported |
25 +| constants | Constants namespace is accessible |
26 +| logger | Logger instance is exported |
27
28 ## Fixture
29
30 ```
31 fixtures/
31 -└── test.cjs # CommonJS test script using require()
32 +└── test.cjs # CommonJS script using require('@composio/core')
33 ```
34
34 -The fixture is a standalone `.cjs` file that:
35 -
36 -- Uses `require('@composio/core')` to import the package
37 -- Verifies each export exists and has the correct type
38 -- Attempts to instantiate `OpenAIProvider` to catch runtime errors
39 -- Outputs test results to stdout with pass/fail markers
40 -
35 ## Isolation Tool
36
37 **Docker** with Node.js versions: 22.22.3, 24.16.0, 25.9.0.
ts/e2e-tests/runtimes/node/cjs-basic/e2e.test.ts
+22 -13
@@ -1,7 +1,8 @@
1 /**
2 - * CommonJS compatibility e2e test
2 + * CommonJS require(esm) interop e2e test.
3 *
4 - * Verifies that @composio/core can be imported using require() in Node.js.
4 + * Verifies that Node.js 22 can require @composio/core through its native
5 + * require(esm) support without us publishing CommonJS artifacts.
6 */
7
8 import { e2e, type E2ETestResult } from '@e2e-tests/utils';
@@ -20,49 +21,57 @@ e2e(import.meta.url, {
21 result = await runFixture({ filename: 'test.cjs' });
22 }, TIMEOUTS.FIXTURE);
23
23 - describe('CommonJS compatibility', () => {
24 + describe('CommonJS require(esm) interop', () => {
25 it('exits successfully', () => {
26 expect(result.exitCode).toBe(0);
27 });
28
29 + it('uses Node.js native require(esm)', () => {
30 + expect(result.stdout).toContain('Test 1 passed: require(esm) is available');
31 + });
32 +
33 + it('resolves the ESM entrypoint', () => {
34 + expect(result.stdout).toContain('Test 2 passed: resolved ESM entrypoint');
35 + });
36 +
37 it('require() succeeds', () => {
29 - expect(result.stdout).toContain('Test 1 passed: require() succeeded');
38 + expect(result.stdout).toContain('Test 3 passed: require() succeeded');
39 });
40
41 it('exports Composio class', () => {
33 - expect(result.stdout).toContain('Test 2 passed: Composio class is exported');
42 + expect(result.stdout).toContain('Test 4 passed: Composio class is exported');
43 });
44
45 it('exports OpenAIProvider class', () => {
37 - expect(result.stdout).toContain('Test 3 passed: OpenAIProvider class is exported');
46 + expect(result.stdout).toContain('Test 5 passed: OpenAIProvider class is exported');
47 });
48
49 it('instantiates OpenAIProvider successfully', () => {
41 - expect(result.stdout).toContain('Test 4 passed: OpenAIProvider instantiated successfully');
50 + expect(result.stdout).toContain('Test 6 passed: OpenAIProvider instantiated successfully');
51 });
52
53 it('exports AuthScheme', () => {
45 - expect(result.stdout).toContain('Test 5 passed: AuthScheme is exported');
54 + expect(result.stdout).toContain('Test 7 passed: AuthScheme is exported');
55 });
56
57 it('exports Error classes', () => {
49 - expect(result.stdout).toContain('Test 6 passed: Error classes are exported');
58 + expect(result.stdout).toContain('Test 8 passed: Error classes are exported');
59 });
60
61 it('exports jsonSchemaToZodSchema', () => {
53 - expect(result.stdout).toContain('Test 7 passed: jsonSchemaToZodSchema is exported');
62 + expect(result.stdout).toContain('Test 9 passed: jsonSchemaToZodSchema is exported');
63 });
64
65 it('exports constants namespace', () => {
57 - expect(result.stdout).toContain('Test 8 passed: constants namespace is exported');
66 + expect(result.stdout).toContain('Test 10 passed: constants namespace is exported');
67 });
68
69 it('exports logger', () => {
61 - expect(result.stdout).toContain('Test 9 passed: logger is exported');
70 + expect(result.stdout).toContain('Test 11 passed: logger is exported');
71 });
72
73 it('completes all tests', () => {
65 - expect(result.stdout).toContain('All CommonJS compatibility tests passed!');
74 + expect(result.stdout).toContain('All CommonJS require(esm) interop tests passed!');
75 });
76 });
77 },
ts/e2e-tests/runtimes/node/cjs-basic/fixtures/test.cjs
+55 -35
@@ -1,77 +1,97 @@
1 /**
2 - * CommonJS compatibility test for @composio/core
3 - * This test verifies that the package can be imported using require() in Node.js
2 + * CommonJS require(esm) interop test for @composio/core.
3 + *
4 + * This fixture intentionally uses CommonJS syntax while resolving the ESM-only
5 + * package entrypoint through Node.js 22 native require(esm) support.
6 */
7
8 'use strict';
9
10 const assert = require('node:assert');
11 +const path = require('node:path');
12
10 -console.log('🧪 Testing CommonJS compatibility for @composio/core...\n');
13 +console.log('Testing CommonJS require(esm) interop for @composio/core...\n');
14
12 -// Test 1: Basic require() works
13 -console.log('Test 1: require("@composio/core") should not throw...');
15 +console.log('Test 1: Node.js require(esm) support should be available...');
16 +assert.strictEqual(
17 + process.features.require_module,
18 + true,
19 + 'Node.js require(esm) support should be enabled'
20 +);
21 +console.log('Test 1 passed: require(esm) is available\n');
22 +
23 +console.log('Test 2: require.resolve("@composio/core") should use the ESM entrypoint...');
24 +const resolvedPath = require.resolve('@composio/core');
25 +const normalizedPath = resolvedPath.split(path.sep).join('/');
26 +assert.ok(
27 + normalizedPath.endsWith('/dist/index.mjs'),
28 + `Expected @composio/core to resolve to dist/index.mjs, got ${resolvedPath}`
29 +);
30 +assert.ok(!normalizedPath.endsWith('.cjs'), `Expected no CJS artifact, got ${resolvedPath}`);
31 +console.log('Test 2 passed: resolved ESM entrypoint\n');
32 +
33 +console.log('Test 3: require("@composio/core") should not throw...');
34 let composioModule;
35 try {
36 composioModule = require('@composio/core');
17 - console.log('✅ Test 1 passed: require() succeeded\n');
37 + console.log('Test 3 passed: require() succeeded\n');
38 } catch (error) {
19 - console.error('❌ Test 1 failed: require() threw an error');
39 + console.error('Test 3 failed: require() threw an error');
40 console.error(error);
41 process.exit(1);
42 }
43
24 -// Test 2: Composio class is exported
25 -console.log('Test 2: Composio class should be exported...');
44 +console.log('Test 4: Composio class should be exported...');
45 assert.ok(composioModule.Composio, 'Composio class should be exported');
46 assert.strictEqual(typeof composioModule.Composio, 'function', 'Composio should be a constructor');
28 -console.log('✅ Test 2 passed: Composio class is exported\n');
47 +console.log('Test 4 passed: Composio class is exported\n');
48
30 -// Test 3: OpenAIProvider class is exported
31 -console.log('Test 3: OpenAIProvider class should be exported...');
49 +console.log('Test 5: OpenAIProvider class should be exported...');
50 assert.ok(composioModule.OpenAIProvider, 'OpenAIProvider class should be exported');
33 -assert.strictEqual(typeof composioModule.OpenAIProvider, 'function', 'OpenAIProvider should be a constructor');
34 -console.log('✅ Test 3 passed: OpenAIProvider class is exported\n');
51 +assert.strictEqual(
52 + typeof composioModule.OpenAIProvider,
53 + 'function',
54 + 'OpenAIProvider should be a constructor'
55 +);
56 +console.log('Test 5 passed: OpenAIProvider class is exported\n');
57
36 -// Test 4: Can instantiate OpenAIProvider (doesn't require API key)
37 -console.log('Test 4: OpenAIProvider should be instantiable...');
58 +console.log('Test 6: OpenAIProvider should be instantiable...');
59 try {
60 const provider = new composioModule.OpenAIProvider();
61 assert.ok(provider, 'Provider instance should exist');
41 - console.log('✅ Test 4 passed: OpenAIProvider instantiated successfully\n');
62 + console.log('Test 6 passed: OpenAIProvider instantiated successfully\n');
63 } catch (error) {
43 - console.error('❌ Test 4 failed: Could not instantiate OpenAIProvider');
64 + console.error('Test 6 failed: Could not instantiate OpenAIProvider');
65 console.error(error);
66 process.exit(1);
67 }
68
48 -// Test 5: AuthScheme is exported
49 -console.log('Test 5: AuthScheme should be exported...');
69 +console.log('Test 7: AuthScheme should be exported...');
70 assert.ok(composioModule.AuthScheme, 'AuthScheme should be exported');
51 -console.log('✅ Test 5 passed: AuthScheme is exported\n');
71 +console.log('Test 7 passed: AuthScheme is exported\n');
72
53 -// Test 6: Error classes are exported
54 -console.log('Test 6: Error classes should be exported...');
73 +console.log('Test 8: Error classes should be exported...');
74 assert.ok(composioModule.ComposioError, 'ComposioError should be exported');
56 -console.log('✅ Test 6 passed: Error classes are exported\n');
75 +console.log('Test 8 passed: Error classes are exported\n');
76
58 -// Test 7: jsonSchemaToZodSchema utility is exported
59 -console.log('Test 7: jsonSchemaToZodSchema should be exported...');
77 +console.log('Test 9: jsonSchemaToZodSchema should be exported...');
78 assert.ok(composioModule.jsonSchemaToZodSchema, 'jsonSchemaToZodSchema should be exported');
61 -assert.strictEqual(typeof composioModule.jsonSchemaToZodSchema, 'function', 'jsonSchemaToZodSchema should be a function');
62 -console.log('✅ Test 7 passed: jsonSchemaToZodSchema is exported\n');
79 +assert.strictEqual(
80 + typeof composioModule.jsonSchemaToZodSchema,
81 + 'function',
82 + 'jsonSchemaToZodSchema should be a function'
83 +);
84 +console.log('Test 9 passed: jsonSchemaToZodSchema is exported\n');
85
64 -// Test 8: constants namespace is exported
65 -console.log('Test 8: constants namespace should be exported...');
86 +console.log('Test 10: constants namespace should be exported...');
87 assert.ok(composioModule.constants, 'constants should be exported');
67 -console.log('✅ Test 8 passed: constants namespace is exported\n');
88 +console.log('Test 10 passed: constants namespace is exported\n');
89
69 -// Test 9: logger is exported
70 -console.log('Test 9: logger should be exported...');
90 +console.log('Test 11: logger should be exported...');
91 assert.ok(composioModule.logger, 'logger should be exported');
72 -console.log('✅ Test 9 passed: logger is exported\n');
92 +console.log('Test 11 passed: logger is exported\n');
93
94 console.log('========================================');
75 -console.log('🎉 All CommonJS compatibility tests passed!');
95 +console.log('All CommonJS require(esm) interop tests passed!');
96 console.log('========================================');
97 process.exit(0);
ts/e2e-tests/runtimes/node/esm-basic/README.md
+1 -1
@@ -9,7 +9,7 @@ ESM is the modern JavaScript module standard. This suite ensures:
9 - `import('@composio/core')` resolves without errors
10 - Named imports work (`import { Composio } from '@composio/core'`)
11 - All public exports are accessible
12 -- No CJS-only patterns break ESM consumers
12 +- The ESM-only package entrypoints resolve correctly
13
14 ## What It Tests
15
ts/e2e-tests/runtimes/node/file-roundtrip/README.md
+1 -1
@@ -31,7 +31,7 @@ If `COMPOSIO_API_KEY` is not set, the suite is skipped.
31
32 ## Isolation Tool
33
34 -**Docker** with Node.js versions: current (as specified in `mise.toml`).
34 +**Docker** with Node.js versions: 22.22.3, 24.16.0, 25.9.0.
35
36 This ensures the behavior is tested against specific Node.js versions independent of the developer's local setup.
37
ts/e2e-tests/runtimes/node/file-roundtrip/e2e.test.ts
+1 -1
@@ -8,7 +8,7 @@ declare module 'bun' {
8 }
9
10 e2e(import.meta.url, {
11 - versions: { node: ['current'] },
11 + versions: { node: ['22.22.3', '24.16.0', '25.9.0'] },
12 usesFixtures: true,
13 env: {
14 COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
ts/e2e-tests/runtimes/node/json-schema-to-zod-v3/README.md
+1 -1
@@ -36,7 +36,7 @@ Tests use `bun:test` assertions to verify schema conversion and round-trip behav
36
37 ## Isolation Tool
38
39 -**Docker** with Node.js versions: current (as specified in `mise.toml`).
39 +**Docker** with Node.js versions: 22.22.3, 24.16.0, 25.9.0.
40
41 ## Running
42
ts/e2e-tests/runtimes/node/json-schema-to-zod-v3/e2e.test.ts
+1 -1
@@ -11,7 +11,7 @@ import { describe, it, expect } from 'bun:test';
11 import zodToJsonSchema from 'zod-to-json-schema';
12
13 e2e(import.meta.url, {
14 - versions: { node: ['current'] },
14 + versions: { node: ['22.22.3', '24.16.0', '25.9.0'] },
15 defineTests: () => {
16 describe('json-schema-to-zod with Zod v3', () => {
17 describe('Basic functionality', () => {
ts/e2e-tests/runtimes/node/json-schema-to-zod-v4/README.md
+1 -1
@@ -37,7 +37,7 @@ Tests use `bun:test` assertions to verify schema conversion and parsing behavior
37
38 ## Isolation Tool
39
40 -**Docker** with Node.js versions: current (as specified in `mise.toml`).
40 +**Docker** with Node.js versions: 22.22.3, 24.16.0, 25.9.0.
41
42 ## Running
43
ts/e2e-tests/runtimes/node/json-schema-to-zod-v4/e2e.test.ts
+1 -1
@@ -10,7 +10,7 @@ import { e2e } from '@e2e-tests/utils';
10 import { describe, it, expect } from 'bun:test';
11
12 e2e(import.meta.url, {
13 - versions: { node: ['current'] },
13 + versions: { node: ['22.22.3', '24.16.0', '25.9.0'] },
14 defineTests: () => {
15 describe('json-schema-to-zod with Zod v4', () => {
16 describe('Basic functionality', () => {
ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/README.md
+1 -1
@@ -55,7 +55,7 @@ The fixture script:
55
56 ## Isolation Tool
57
58 -**Docker** with Node.js versions: current (as specified in `mise.toml`).
58 +**Docker** with Node.js versions: 22.22.3, 24.16.0, 25.9.0.
59
60 ## Running
61
ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/e2e.test.ts
+1 -1
@@ -9,7 +9,7 @@ import { e2e, type E2ETestResult } from '@e2e-tests/utils';
9 import { describe, it, expect, beforeAll } from 'bun:test';
10
11 e2e(import.meta.url, {
12 - versions: { node: ['current'] },
12 + versions: { node: ['22.22.3', '24.16.0', '25.9.0'] },
13 defineTests: ({ runFixture }) => {
14 let result: E2ETestResult;
15
ts/examples/anthropic/package.json
-1
@@ -13,7 +13,6 @@
13 "keywords": [],
14 "author": "",
15 "license": "ISC",
16 - "packageManager": "pnpm@10.28.0",
16 "dependencies": {
17 "@anthropic-ai/sdk": "^0.71.0",
18 "@anthropic-ai/claude-agent-sdk": "^0.1.9",
ts/examples/cjs/README.md deleted
-31
@@ -1,31 +0,0 @@
1 -# CJS Example
2 -
3 -This example demonstrates how to use Composio SDK with CommonJS.
4 -
5 -## Setup
6 -
7 -1. **Install dependencies:**
8 - ```bash
9 - pnpm install
10 - ```
11 -
12 -2. **Configure environment:**
13 - ```bash
14 - cp .env.example .env
15 - ```
16 -
17 - Then edit `.env` and add your API keys:
18 - - `COMPOSIO_API_KEY`: Get it from [Composio Dashboard](https://app.composio.dev)
19 -
20 -## Running the Example
21 -
22 -```bash
23 -# Run the example
24 -pnpm start
25 -```
26 -
27 -## Support
28 -
29 -- [Documentation](https://docs.composio.dev)
30 -- [Discord Community](https://discord.gg/composio)
31 -- [GitHub Issues](https://github.com/composio/composio/issues)
ts/examples/cjs/package.json deleted
-23
@@ -1,23 +0,0 @@
1 -{
2 - "name": "cjs-example",
3 - "type": "commonjs",
4 - "private": true,
5 - "version": "0.1.0",
6 - "description": "Example project for CommonJS",
7 - "main": "src/index.ts",
8 - "scripts": {
9 - "start": "node ./src/index.cjs"
10 - },
11 - "keywords": ["composio", "example", "cjs"],
12 - "author": "",
13 - "license": "ISC",
14 - "packageManager": "pnpm@10.28.0",
15 - "dependencies": {
16 - "@composio/core": "workspace:*",
17 - "dotenv": "^16.4.1"
18 - },
19 - "devDependencies": {
20 - "@types/bun": "^1.2.9",
21 - "typescript": "catalog:"
22 - }
23 -}
ts/examples/cjs/src/index.cjs deleted
-20
@@ -1,20 +0,0 @@
1 -const { Composio } = require('@composio/core');
2 -require('dotenv/config');
3 -
4 -const composio = new Composio({
5 - apiKey: process.env.COMPOSIO_API_KEY,
6 -});
7 -
8 -async function main() {
9 - console.log('Fetching tools enum...');
10 -
11 - const tools = await composio.tools.getToolsEnum();
12 -
13 - console.log('Tools enum fetched:', tools.items.length);
14 -}
15 -
16 -main()
17 - .catch(e => {
18 - console.error(e);
19 - process.exit(1);
20 - })
ts/examples/cjs/tsconfig.json deleted
-16
@@ -1,16 +0,0 @@
1 -{
2 - "compilerOptions": {
3 - "target": "es2022",
4 - "module": "esnext",
5 - "declaration": true,
6 - "declarationDir": "./dist",
7 - "outDir": "./dist",
8 - "rootDir": "./src",
9 - "strict": true,
10 - "esModuleInterop": true,
11 - "moduleResolution": "bundler",
12 - "skipLibCheck": true,
13 - "resolveJsonModule": true
14 - },
15 - "include": ["src"]
16 -}
ts/examples/cloudflare-wrangler/package.json
-1
@@ -2,7 +2,6 @@
2 "name": "cloudflare-wrangler-example",
3 "version": "0.0.0",
4 "private": true,
5 - "packageManager": "pnpm@10.28.0",
5 "scripts": {
6 "deploy": "wrangler deploy",
7 "dev": "wrangler dev",
ts/examples/connected-accounts/package.json
-1
@@ -12,7 +12,6 @@
12 "keywords": [],
13 "author": "",
14 "license": "ISC",
15 - "packageManager": "pnpm@10.28.0",
15 "dependencies": {
16 "@composio/core": "workspace:*",
17 "openai": "catalog:"
ts/examples/error-handling-demo/package.json
-1
@@ -12,7 +12,6 @@
12 "keywords": [],
13 "author": "",
14 "license": "ISC",
15 - "packageManager": "pnpm@10.28.0",
15 "dependencies": {
16 "@composio/core": "workspace:*",
17 "dotenv": "^16.5.0"
ts/examples/file-handling/package.json
+5 -2
@@ -9,10 +9,13 @@
9 "dev": "bun --watch src/index.ts",
10 "test": "echo \"Error: no test specified\" && exit 1"
11 },
12 - "keywords": ["composio", "example", "file-handling"],
12 + "keywords": [
13 + "composio",
14 + "example",
15 + "file-handling"
16 + ],
17 "author": "",
18 "license": "ISC",
15 - "packageManager": "pnpm@10.28.0",
19 "dependencies": {
20 "@composio/core": "workspace:*",
21 "dotenv": "^16.4.1"
ts/examples/google/package.json
-1
@@ -19,7 +19,6 @@
19 ],
20 "author": "",
21 "license": "ISC",
22 - "packageManager": "pnpm@10.28.0",
22 "dependencies": {
23 "@composio/core": "workspace:*",
24 "@composio/google": "workspace:*",
ts/examples/json-schema-to-zod/package.json
-1
@@ -17,7 +17,6 @@
17 ],
18 "author": "",
19 "license": "ISC",
20 - "packageManager": "pnpm@10.28.0",
20 "dependencies": {
21 "@composio/core": "workspace:*",
22 "@composio/vercel": "workspace:^",
ts/examples/langchain/package.json
-1
@@ -12,7 +12,6 @@
12 "keywords": [],
13 "author": "",
14 "license": "ISC",
15 - "packageManager": "pnpm@10.28.0",
15 "dependencies": {
16 "@composio/core": "workspace:*",
17 "@composio/langchain": "workspace:*",
ts/examples/llamaindex/package.json
-1
@@ -16,7 +16,6 @@
16 ],
17 "author": "",
18 "license": "ISC",
19 - "packageManager": "pnpm@10.28.0",
19 "dependencies": {
20 "@composio/core": "workspace:*",
21 "@composio/llamaindex": "workspace:*",
ts/examples/mastra/package.json
-1
@@ -22,7 +22,6 @@
22 ],
23 "author": "",
24 "license": "ISC",
25 - "packageManager": "pnpm@10.28.0",
25 "dependencies": {
26 "@ai-sdk/openai": "^3.0.13",
27 "@composio/core": "workspace:*",
ts/examples/mcp/package.json
-1
@@ -16,7 +16,6 @@
16 ],
17 "author": "",
18 "license": "ISC",
19 - "packageManager": "pnpm@10.28.0",
19 "dependencies": {
20 "@ai-sdk/openai": "^2.0.35",
21 "@composio/core": "workspace:*",
ts/examples/modifiers/package.json
-1
@@ -12,7 +12,6 @@
12 "keywords": [],
13 "author": "",
14 "license": "ISC",
15 - "packageManager": "pnpm@10.28.0",
15 "dependencies": {
16 "@ai-sdk/openai": "^1.3.16",
17 "@composio/core": "workspace:*",
ts/examples/openai/package.json
-1
@@ -17,7 +17,6 @@
17 "keywords": [],
18 "author": "",
19 "license": "ISC",
20 - "packageManager": "pnpm@10.28.0",
20 "dependencies": {
21 "@composio/core": "workspace:*",
22 "@composio/openai": "workspace:*",
ts/examples/session-management/package.json
+5 -2
@@ -10,10 +10,13 @@
10 "dev": "bun --watch src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
12 },
13 - "keywords": ["composio", "example", "session-management"],
13 + "keywords": [
14 + "composio",
15 + "example",
16 + "session-management"
17 + ],
18 "author": "",
19 "license": "ISC",
16 - "packageManager": "pnpm@10.28.0",
20 "dependencies": {
21 "@composio/core": "workspace:*",
22 "dotenv": "^16.4.1"
ts/examples/tool-router/package.json
-1
@@ -18,7 +18,6 @@
18 ],
19 "author": "",
20 "license": "ISC",
21 - "packageManager": "pnpm@10.28.0",
21 "dependencies": {
22 "@ai-sdk/mcp": "^0.0.11",
23 "@ai-sdk/openai": "^3.0.11",
ts/examples/toolkits/package.json
-1
@@ -12,7 +12,6 @@
12 "keywords": [],
13 "author": "",
14 "license": "ISC",
15 - "packageManager": "pnpm@10.28.0",
15 "dependencies": {
16 "@ai-sdk/openai": "^1.3.16",
17 "@composio/core": "workspace:*",
ts/examples/tools/package.json
-1
@@ -16,7 +16,6 @@
16 ],
17 "author": "",
18 "license": "ISC",
19 - "packageManager": "pnpm@10.28.0",
19 "dependencies": {
20 "@ai-sdk/openai": "^3.0.12",
21 "@composio/core": "workspace:*",
ts/examples/triggers/package.json
+5 -2
@@ -11,10 +11,13 @@
11 "webhook:server": "bun src/webhook-server.ts",
12 "test": "echo \"Error: no test specified\" && exit 1"
13 },
14 - "keywords": ["composio", "example", "triggers"],
14 + "keywords": [
15 + "composio",
16 + "example",
17 + "triggers"
18 + ],
19 "author": "",
20 "license": "ISC",
17 - "packageManager": "pnpm@10.28.0",
21 "dependencies": {
22 "@composio/core": "workspace:*",
23 "dotenv": "^16.4.1"
ts/examples/vercel/package.json
-1
@@ -14,7 +14,6 @@
14 "keywords": [],
15 "author": "",
16 "license": "ISC",
17 - "packageManager": "pnpm@10.28.0",
17 "dependencies": {
18 "@ai-sdk/mcp": "^1.0.1",
19 "@ai-sdk/openai": "^3.0.11",
ts/examples/versioning/package.json
+5 -2
@@ -9,10 +9,13 @@
9 "dev": "bun --watch src/index.ts",
10 "test": "echo \"Error: no test specified\" && exit 1"
11 },
12 - "keywords": ["composio", "example", "versioning"],
12 + "keywords": [
13 + "composio",
14 + "example",
15 + "versioning"
16 + ],
17 "author": "",
18 "license": "ISC",
15 - "packageManager": "pnpm@10.28.0",
19 "dependencies": {
20 "@composio/core": "workspace:*",
21 "dotenv": "^16.4.1"
ts/packages/cli-keyring/package.json
+4 -25
@@ -17,32 +17,12 @@
17 },
18 "exports": {
19 ".": {
20 - "import": {
21 - "types": "./dist/index.d.mts",
22 - "default": "./dist/index.mjs"
23 - },
24 - "require": {
25 - "types": "./dist/index.d.cts",
26 - "default": "./dist/index.cjs"
27 - },
28 - "default": {
29 - "types": "./dist/index.d.cts",
30 - "default": "./dist/index.cjs"
31 - }
20 + "types": "./dist/index.d.mts",
21 + "default": "./dist/index.mjs"
22 },
23 "./effect": {
34 - "import": {
35 - "types": "./dist/effect.d.mts",
36 - "default": "./dist/effect.mjs"
37 - },
38 - "require": {
39 - "types": "./dist/effect.d.cts",
40 - "default": "./dist/effect.cjs"
41 - },
42 - "default": {
43 - "types": "./dist/effect.d.cts",
44 - "default": "./dist/effect.cjs"
45 - }
24 + "types": "./dist/effect.d.mts",
25 + "default": "./dist/effect.mjs"
26 }
27 },
28 "files": [
@@ -70,7 +50,6 @@
50 ],
51 "author": "Composio",
52 "license": "ISC",
73 - "packageManager": "pnpm@10.28.0",
53 "devDependencies": {
54 "@types/node": "^24.0.1",
55 "bun-types": "^1.3.11",
ts/packages/cli-keyring/tsdown.config.ts
+2 -3
@@ -5,9 +5,8 @@ export default defineConfig({
5 ...baseConfig,
6 entry: ['src/index.ts', 'src/effect.ts'],
7 tsconfig: 'tsconfig.src.json',
8 - // bun:ffi is a Bun built-in; in the Node/CJS output it must remain
9 - // an unresolved import so Node never tries to load the FFI backend
10 - // chunk at startup. The runtime branch in stores/macos-security.ts
8 + // bun:ffi is a Bun built-in. Keep it external so Node never tries to
9 + // load the FFI backend chunk at startup; stores/macos-security.ts
10 // guards `isBun` before reaching the dynamic import.
11 external: [...baseConfig.external, /^bun:/],
12 });
ts/packages/cli-local-tools/package.json
+2 -12
@@ -9,18 +9,8 @@
9 "types": "dist/index.d.mts",
10 "exports": {
11 ".": {
12 - "import": {
13 - "types": "./dist/index.d.mts",
14 - "default": "./dist/index.mjs"
15 - },
16 - "require": {
17 - "types": "./dist/index.d.cts",
18 - "default": "./dist/index.cjs"
19 - },
20 - "default": {
21 - "types": "./dist/index.d.cts",
22 - "default": "./dist/index.cjs"
23 - }
12 + "types": "./dist/index.d.mts",
13 + "default": "./dist/index.mjs"
14 }
15 },
16 "repository": {
ts/packages/cli/package.json
-1
@@ -56,7 +56,6 @@
56 ],
57 "author": "Alberto Schiabel <alberto.schiabel@gmail.com> (https://github.com/jkomyno)",
58 "license": "ISC",
59 - "packageManager": "pnpm@10.28.0",
59 "devDependencies": {
60 "@effect/eslint-plugin": "catalog:",
61 "@effect/language-service": "catalog:",
ts/packages/cli/src/services/env-lang-detector.ts
+2 -10
@@ -75,11 +75,7 @@ export class EnvLangDetector extends Effect.Service<EnvLangDetector>()('services
75 if (!hasTypescriptIndicator && !hasPythonIndicator) {
76 // Get actual file names (not lowercase) for extension checking
77 const hasTypeScriptFiles = files.some(
78 - file =>
79 - file.endsWith('.ts') ||
80 - file.endsWith('.tsx') ||
81 - file.endsWith('.mts') ||
82 - file.endsWith('.cts')
78 + file => file.endsWith('.ts') || file.endsWith('.tsx') || file.endsWith('.mts')
79 );
80
81 const hasPythonFiles = files.some(
@@ -153,11 +149,7 @@ export class EnvLangDetector extends Effect.Service<EnvLangDetector>()('services
149 const allFileNames = [...files, ...allFiles];
150
151 const deepTsFiles = allFileNames.filter(
156 - file =>
157 - file.endsWith('.ts') ||
158 - file.endsWith('.tsx') ||
159 - file.endsWith('.mts') ||
160 - file.endsWith('.cts')
152 + file => file.endsWith('.ts') || file.endsWith('.tsx') || file.endsWith('.mts')
153 ).length;
154
155 const deepPyFiles = allFileNames.filter(
ts/packages/cli/src/services/project-environment-detector.ts
+2 -2
@@ -106,9 +106,9 @@ const countExtensions = (files: string[]) => {
106
107 for (const file of files) {
108 const ext = path.extname(file).toLowerCase();
109 - if (ext === '.ts' || ext === '.tsx' || ext === '.mts' || ext === '.cts') {
109 + if (ext === '.ts' || ext === '.tsx' || ext === '.mts') {
110 ts += 1;
111 - } else if (ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {
111 + } else if (ext === '.js' || ext === '.jsx' || ext === '.mjs') {
112 js += 1;
113 } else if (ext === '.py' || ext === '.pyi' || ext === '.pyw' || ext === '.pyx') {
114 py += 1;
ts/packages/core/package.json
+16 -73
@@ -13,80 +13,36 @@
13 "#platform": {
14 "workerd": "./dist/platform/workerd.mjs",
15 "edge-light": "./dist/platform/workerd.mjs",
16 - "node": {
17 - "import": "./dist/platform/node.mjs",
18 - "require": "./dist/platform/node.cjs"
19 - },
20 - "default": {
21 - "import": "./dist/platform/node.mjs",
22 - "require": "./dist/platform/node.cjs"
23 - }
16 + "node": "./dist/platform/node.mjs",
17 + "default": "./dist/platform/node.mjs"
18 },
19 "#files": {
20 "workerd": "./dist/models/Files.workerd.mjs",
21 "edge-light": "./dist/models/Files.workerd.mjs",
28 - "node": {
29 - "import": "./dist/models/Files.node.mjs",
30 - "require": "./dist/models/Files.node.cjs"
31 - },
32 - "default": {
33 - "import": "./dist/models/Files.node.mjs",
34 - "require": "./dist/models/Files.node.cjs"
35 - }
22 + "node": "./dist/models/Files.node.mjs",
23 + "default": "./dist/models/Files.node.mjs"
24 },
25 "#file_tool_modifier": {
26 "workerd": "./dist/utils/modifiers/FileToolModifier.workerd.mjs",
27 "edge-light": "./dist/utils/modifiers/FileToolModifier.workerd.mjs",
40 - "node": {
41 - "import": "./dist/utils/modifiers/FileToolModifier.node.mjs",
42 - "require": "./dist/utils/modifiers/FileToolModifier.node.cjs"
43 - },
44 - "default": {
45 - "import": "./dist/utils/modifiers/FileToolModifier.node.mjs",
46 - "require": "./dist/utils/modifiers/FileToolModifier.node.cjs"
47 - }
28 + "node": "./dist/utils/modifiers/FileToolModifier.node.mjs",
29 + "default": "./dist/utils/modifiers/FileToolModifier.node.mjs"
30 },
31 "#config_defaults": {
32 "workerd": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
33 "edge-light": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
52 - "node": {
53 - "import": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
54 - "require": "./dist/utils/config-defaults/ConfigDefaults.node.cjs"
55 - },
56 - "default": {
57 - "import": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
58 - "require": "./dist/utils/config-defaults/ConfigDefaults.node.cjs"
59 - }
34 + "node": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
35 + "default": "./dist/utils/config-defaults/ConfigDefaults.node.mjs"
36 }
37 },
38 "exports": {
39 ".": {
64 - "import": {
65 - "types": "./dist/index.d.mts",
66 - "default": "./dist/index.mjs"
67 - },
68 - "require": {
69 - "types": "./dist/index.d.cts",
70 - "default": "./dist/index.cjs"
71 - },
72 - "default": {
73 - "types": "./dist/index.d.cts",
74 - "default": "./dist/index.cjs"
75 - }
40 + "types": "./dist/index.d.mts",
41 + "default": "./dist/index.mjs"
42 },
43 "./experimental": {
78 - "import": {
79 - "types": "./dist/experimental/index.d.mts",
80 - "default": "./dist/experimental/index.mjs"
81 - },
82 - "require": {
83 - "types": "./dist/experimental/index.d.cts",
84 - "default": "./dist/experimental/index.cjs"
85 - },
86 - "default": {
87 - "types": "./dist/experimental/index.d.cts",
88 - "default": "./dist/experimental/index.cjs"
89 - }
44 + "types": "./dist/experimental/index.d.mts",
45 + "default": "./dist/experimental/index.mjs"
46 },
47 "./platform": {
48 "workerd": {
@@ -98,24 +54,12 @@
54 "default": "./dist/platform/workerd.mjs"
55 },
56 "node": {
101 - "import": {
102 - "types": "./dist/platform/node.d.mts",
103 - "default": "./dist/platform/node.mjs"
104 - },
105 - "require": {
106 - "types": "./dist/platform/node.d.cts",
107 - "default": "./dist/platform/node.cjs"
108 - }
57 + "types": "./dist/platform/node.d.mts",
58 + "default": "./dist/platform/node.mjs"
59 },
60 "default": {
111 - "import": {
112 - "types": "./dist/platform/node.d.mts",
113 - "default": "./dist/platform/node.mjs"
114 - },
115 - "require": {
116 - "types": "./dist/platform/node.d.cts",
117 - "default": "./dist/platform/node.cjs"
118 - }
61 + "types": "./dist/platform/node.d.mts",
62 + "default": "./dist/platform/node.mjs"
63 }
64 },
65 "./generated": {
@@ -140,7 +84,6 @@
84 "keywords": [],
85 "author": "",
86 "license": "ISC",
143 - "packageManager": "pnpm@10.28.0",
87 "devDependencies": {
88 "@type-challenges/utils": "^0.1.1",
89 "@types/semver": "^7.7.0",
ts/packages/core/src/utils/pusher.ts
+30 -35
@@ -21,12 +21,6 @@ type PusherClient = {
21 };
22 };
23
24 -type AuthOptions = {
25 - endpoint: string;
26 - headers: Record<string, string>;
27 - params?: Record<string, string>;
28 -};
29 -
24 type TChunkedTriggerData = {
25 id: string;
26 index: number;
@@ -62,40 +56,41 @@ export class PusherUtils {
56 static async getPusherClient(baseURL: string, apiKey: string): Promise<PusherClient> {
57 try {
58 if (!PusherUtils.pusherClient) {
65 - // Dynamic import not available, using require for now
66 - // TODO: Update to use dynamic import when available
67 - // eslint-disable-next-line @typescript-eslint/no-require-imports
68 - const PusherClient = require('pusher-js');
59 + const { default: PusherClient } = await import('pusher-js');
60 + const authEndpoint = `${baseURL}/api/v3/internal/sdk/realtime/auth`;
61 PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
62 cluster: PUSHER_CLUSTER,
63 channelAuthorization: {
72 - endpoint: `${baseURL}/api/v3/internal/sdk/realtime/auth`,
73 - headers: {
74 - 'x-api-key': apiKey,
75 - },
64 + // `transport` and `endpoint` are required by pusher-js's types but are
65 + // unused at runtime: `customHandler` fully owns the auth request below.
66 transport: 'ajax',
77 - customHandler: async (authOptions: AuthOptions) => {
78 - try {
79 - const response = await fetch(authOptions.endpoint, {
80 - method: 'POST',
81 - headers: {
82 - ...authOptions.headers,
83 - 'Content-Type': 'application/json',
84 - },
85 - body: JSON.stringify(authOptions.params),
67 + endpoint: authEndpoint,
68 + customHandler: (params, callback) => {
69 + fetch(authEndpoint, {
70 + method: 'POST',
71 + headers: {
72 + 'x-api-key': apiKey,
73 + 'Content-Type': 'application/json',
74 + },
75 + body: JSON.stringify({
76 + socket_id: params.socketId,
77 + channel_name: params.channelName,
78 + }),
79 + })
80 + .then(async response => {
81 + const data = await response.text();
82 + logger.debug('Pusher auth response:', data);
83 + try {
84 + callback(null, JSON.parse(data));
85 + } catch (e) {
86 + logger.error('Failed to parse auth response:', e);
87 + callback(new Error('Invalid auth response format'), null);
88 + }
89 + })
90 + .catch((error: unknown) => {
91 + logger.error('Pusher auth request failed:', error);
92 + callback(error instanceof Error ? error : new Error(String(error)), null);
93 });
87 - const data = await response.text();
88 - logger.debug('Pusher auth response:', data);
89 - try {
90 - return JSON.parse(data);
91 - } catch (e) {
92 - logger.error('Failed to parse auth response:', e);
93 - throw new Error('Invalid auth response format');
94 - }
95 - } catch (error) {
96 - logger.error('Pusher auth request failed:', error);
97 - throw error;
98 - }
94 },
95 },
96 });
ts/packages/core/test/utils/pusher.test.ts new
+110
@@ -0,0 +1,110 @@
1 +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 +import { PusherUtils } from '../../src/utils/pusher';
3 +
4 +// Capture the options passed to the Pusher constructor so the
5 +// channelAuthorization.customHandler can be exercised in isolation.
6 +const { constructorCalls } = vi.hoisted(() => ({
7 + constructorCalls: [] as Array<{ key: string; options: Record<string, any> }>,
8 +}));
9 +
10 +vi.mock('pusher-js', () => {
11 + class FakePusher {
12 + connection = { bind: vi.fn() };
13 + subscribe = vi.fn();
14 + unsubscribe = vi.fn();
15 + bind = vi.fn();
16 + constructor(key: string, options: Record<string, any>) {
17 + constructorCalls.push({ key, options });
18 + }
19 + }
20 + return { default: FakePusher };
21 +});
22 +
23 +type CustomHandler = (
24 + params: { socketId: string; channelName: string },
25 + callback: (error: Error | null, data: unknown) => void
26 +) => void;
27 +
28 +const baseURL = 'https://backend.composio.dev';
29 +const apiKey = 'test-api-key';
30 +const authEndpoint = `${baseURL}/api/v3/internal/sdk/realtime/auth`;
31 +
32 +async function getCustomHandler(): Promise<CustomHandler> {
33 + await PusherUtils.getPusherClient(baseURL, apiKey);
34 + const { options } = constructorCalls.at(-1)!;
35 + return options.channelAuthorization.customHandler as CustomHandler;
36 +}
37 +
38 +describe('PusherUtils channelAuthorization', () => {
39 + beforeEach(() => {
40 + constructorCalls.length = 0;
41 + // Reset the cached singleton so getPusherClient rebuilds the client.
42 + (PusherUtils as unknown as { pusherClient?: unknown }).pusherClient = undefined;
43 + });
44 +
45 + afterEach(() => {
46 + vi.unstubAllGlobals();
47 + });
48 +
49 + it('configures the realtime auth endpoint with ajax transport', async () => {
50 + await PusherUtils.getPusherClient(baseURL, apiKey);
51 + const { options } = constructorCalls.at(-1)!;
52 +
53 + expect(options.channelAuthorization.endpoint).toBe(authEndpoint);
54 + expect(options.channelAuthorization.transport).toBe('ajax');
55 + expect(typeof options.channelAuthorization.customHandler).toBe('function');
56 + });
57 +
58 + it('POSTs socket_id/channel_name as JSON and returns the parsed auth payload', async () => {
59 + const authData = { auth: 'app_key:signature' };
60 + const fetchMock = vi.fn().mockResolvedValue({ text: async () => JSON.stringify(authData) });
61 + vi.stubGlobal('fetch', fetchMock);
62 +
63 + const customHandler = await getCustomHandler();
64 + const callback = vi.fn();
65 + customHandler({ socketId: '123.456', channelName: 'private-abc' }, callback);
66 +
67 + await vi.waitFor(() => expect(callback).toHaveBeenCalled());
68 +
69 + expect(fetchMock).toHaveBeenCalledWith(
70 + authEndpoint,
71 + expect.objectContaining({
72 + method: 'POST',
73 + headers: { 'x-api-key': apiKey, 'Content-Type': 'application/json' },
74 + body: JSON.stringify({ socket_id: '123.456', channel_name: 'private-abc' }),
75 + })
76 + );
77 + expect(callback).toHaveBeenCalledWith(null, authData);
78 + });
79 +
80 + it('reports an error to the callback when the response is not valid JSON', async () => {
81 + const fetchMock = vi.fn().mockResolvedValue({ text: async () => 'not-json' });
82 + vi.stubGlobal('fetch', fetchMock);
83 +
84 + const customHandler = await getCustomHandler();
85 + const callback = vi.fn();
86 + customHandler({ socketId: '1', channelName: 'c' }, callback);
87 +
88 + await vi.waitFor(() => expect(callback).toHaveBeenCalled());
89 +
90 + const [error, data] = callback.mock.calls[0];
91 + expect(error).toBeInstanceOf(Error);
92 + expect(data).toBeNull();
93 + });
94 +
95 + it('reports an error to the callback when the auth request rejects', async () => {
96 + const fetchMock = vi.fn().mockRejectedValue(new Error('network down'));
97 + vi.stubGlobal('fetch', fetchMock);
98 +
99 + const customHandler = await getCustomHandler();
100 + const callback = vi.fn();
101 + customHandler({ socketId: '1', channelName: 'c' }, callback);
102 +
103 + await vi.waitFor(() => expect(callback).toHaveBeenCalled());
104 +
105 + const [error, data] = callback.mock.calls[0];
106 + expect(error).toBeInstanceOf(Error);
107 + expect((error as Error).message).toBe('network down');
108 + expect(data).toBeNull();
109 + });
110 +});
ts/packages/core/tsdown.config.ts
-17
@@ -25,23 +25,6 @@ export default defineConfig({
25 'src/utils/config-defaults/ConfigDefaults.node.ts',
26 'src/utils/config-defaults/ConfigDefaults.workerd.ts',
27 ],
28 - attw: {
29 - ...baseConfig.attw,
30 - ignoreRules: [
31 - ...(baseConfig.attw?.ignoreRules ?? []),
32 -
33 - /**
34 - * We currently need `"type": "module"` in `@composio/core` package.json because:
35 - * - `@composio/cli` tests rely on it
36 - * - `@composio/cli` users rely on it
37 - * This causes issus with `attw`.
38 - *
39 - * Ideally, we can drop cjs support altogether in `@composio/core`.
40 - * Alternatively, we'd need to modify `composio ts generate` so that it generates .mjs files (and not .js).
41 - */
42 - 'cjs-resolves-to-esm',
43 - ],
44 - },
28 /**
29 * We don't want to accidentally bundle `node:*` packages (e.g., `node:module`)
30 * as not all of them are available in Cloudflare Workers / Vercel Edge runtimes.
ts/packages/json-schema-to-zod/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.1.20",
4 "description": "",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -51,7 +42,6 @@
42 "keywords": [],
43 "author": "",
44 "license": "ISC",
54 - "packageManager": "pnpm@10.28.0",
45 "devDependencies": {
46 "@types/json-schema": "^7.0.15",
47 "@types/node": "^24.0.1",
ts/packages/providers/anthropic/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "Non-Agentic Provider for Anthropic in Composio SDK",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -49,7 +40,6 @@
40 ],
41 "author": "",
42 "license": "ISC",
52 - "packageManager": "pnpm@10.28.0",
43 "peerDependencies": {
44 "@anthropic-ai/sdk": "^0.52.0",
45 "@composio/core": ">=0.10.0 <1.0.0",
ts/packages/providers/claude-agent-sdk/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "Composio provider for Claude Agent SDK",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -52,7 +43,6 @@
43 ],
44 "author": "",
45 "license": "ISC",
55 - "packageManager": "pnpm@10.28.0",
46 "dependencies": {
47 "zod": "^3.25.76"
48 },
ts/packages/providers/cloudflare/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -45,7 +36,6 @@
36 "keywords": [],
37 "author": "",
38 "license": "ISC",
48 - "packageManager": "pnpm@10.28.0",
39 "peerDependencies": {
40 "@cloudflare/workers-types": "catalog:",
41 "@composio/core": ">=0.10.0 <1.0.0"
ts/packages/providers/google/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "Google GenAI Provider for Composio SDK",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -51,7 +42,6 @@
42 ],
43 "author": "",
44 "license": "ISC",
54 - "packageManager": "pnpm@10.28.0",
45 "peerDependencies": {
46 "@composio/core": ">=0.10.0 <1.0.0",
47 "@google/genai": "^1.1.0"
ts/packages/providers/langchain/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "",
5 "main": "dist/index.js",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -45,7 +36,6 @@
36 "keywords": [],
37 "author": "",
38 "license": "ISC",
48 - "packageManager": "pnpm@10.28.0",
39 "peerDependencies": {
40 "@composio/core": ">=0.10.0 <1.0.0",
41 "@langchain/core": "^1.1.4"
ts/packages/providers/llamaindex/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "Agentic Provider for llamaindex in Composio SDK",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -48,7 +39,6 @@
39 ],
40 "author": "",
41 "license": "ISC",
51 - "packageManager": "pnpm@10.28.0",
42 "peerDependencies": {
43 "@composio/core": ">=0.10.0 <1.0.0",
44 "llamaindex": "^0.12.0"
ts/packages/providers/mastra/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "Agentic Provider for mastra in Composio SDK",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -51,7 +42,6 @@
42 ],
43 "author": "",
44 "license": "ISC",
54 - "packageManager": "pnpm@10.28.0",
45 "peerDependencies": {
46 "@composio/core": ">=0.10.0 <1.0.0",
47 "@mastra/core": "^1.0.4",
ts/packages/providers/openai-agents/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -45,7 +36,6 @@
36 "keywords": [],
37 "author": "",
38 "license": "ISC",
48 - "packageManager": "pnpm@10.28.0",
39 "peerDependencies": {
40 "@composio/core": ">=0.10.0 <1.0.0",
41 "@openai/agents": "^0.1.3",
ts/packages/providers/openai/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -45,7 +36,6 @@
36 "keywords": [],
37 "author": "",
38 "license": "ISC",
48 - "packageManager": "pnpm@10.28.0",
39 "peerDependencies": {
40 "@composio/core": ">=0.10.0 <1.0.0",
41 "openai": "catalog:"
ts/packages/providers/vercel/package.json
+3 -13
@@ -3,6 +3,7 @@
3 "version": "0.9.3",
4 "description": "",
5 "main": "src/index.ts",
6 + "type": "module",
7 "repository": {
8 "type": "git",
9 "url": "https://github.com/ComposioHQ/composio.git",
@@ -19,18 +20,8 @@
20 },
21 "exports": {
22 ".": {
22 - "import": {
23 - "types": "./dist/index.d.mts",
24 - "default": "./dist/index.mjs"
25 - },
26 - "require": {
27 - "types": "./dist/index.d.cts",
28 - "default": "./dist/index.cjs"
29 - },
30 - "default": {
31 - "types": "./dist/index.d.cts",
32 - "default": "./dist/index.cjs"
33 - }
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 }
26 },
27 "files": [
@@ -45,7 +36,6 @@
36 "keywords": [],
37 "author": "",
38 "license": "ISC",
48 - "packageManager": "pnpm@10.28.0",
39 "peerDependencies": {
40 "@composio/core": ">=0.10.0 <1.0.0",
41 "ai": "^5.0.0 || ^6.0.0"
ts/packages/ts-builders/package.json
+3 -12
@@ -3,22 +3,13 @@
3 "version": "0.1.24",
4 "description": "Fork of @prisma/ts-builders",
5 "main": "dist/index.mjs",
6 + "type": "module",
7 "module": "dist/index.mjs",
8 "types": "dist/index.d.mts",
9 "exports": {
10 ".": {
10 - "import": {
11 - "types": "./dist/index.d.mts",
12 - "default": "./dist/index.mjs"
13 - },
14 - "require": {
15 - "types": "./dist/index.d.cts",
16 - "default": "./dist/index.cjs"
17 - },
18 - "default": {
19 - "types": "./dist/index.d.cts",
20 - "default": "./dist/index.cjs"
21 - }
11 + "types": "./dist/index.d.mts",
12 + "default": "./dist/index.mjs"
13 }
14 },
15 "repository": {
ts/scripts/create-example.sh
-1
@@ -36,7 +36,6 @@ cat > "$EXAMPLE_PATH/package.json" << EOL
36 "keywords": ["composio", "example", "${EXAMPLE_NAME}"],
37 "author": "",
38 "license": "ISC",
39 - "packageManager": "pnpm@10.28.0",
39 "dependencies": {
40 "@composio/core": "workspace:*",
41 "dotenv": "^16.4.1"
ts/scripts/create-provider.sh
+12 -17
@@ -30,14 +30,13 @@ cat > "$TOOLSET_PATH/package.json" << EOL
30 "type": "module",
31 "publishConfig": {
32 "access": "public",
33 - "main": "dist/index.js",
34 - "types": "dist/index.d.ts"
33 + "main": "dist/index.mjs",
34 + "types": "dist/index.d.mts"
35 },
36 "exports": {
37 ".": {
38 - "import": "./dist/index.js",
39 - "types": "./dist/index.d.ts",
40 - "require": "./dist/index.cjs"
38 + "types": "./dist/index.d.mts",
39 + "default": "./dist/index.mjs"
40 }
41 },
42 "files": [
@@ -45,13 +44,12 @@ cat > "$TOOLSET_PATH/package.json" << EOL
44 "dist"
45 ],
46 "scripts": {
48 - "build": "bun run --bun tsdown",
47 + "build": "pnpm exec tsdown",
48 "test": "vitest run"
49 },
50 "keywords": ["composio", "provider", "${TOOLSET_NAME}"],
51 "author": "",
52 "license": "ISC",
54 - "packageManager": "pnpm@10.28.0",
53 "peerDependencies": {
54 "@composio/core": "^0.1.0"
55 },
@@ -83,17 +81,14 @@ cat > "$TOOLSET_PATH/tsconfig.json" << EOL
81 }
82 EOL
83
86 -# Create tsup.config.ts
87 -cat > "$TOOLSET_PATH/tsup.config.ts" << EOL
88 -import { defineConfig } from 'tsup';
84 +# Create tsdown.config.ts
85 +cat > "$TOOLSET_PATH/tsdown.config.ts" << EOL
86 +import { defineConfig } from 'tsdown';
87 +import { baseConfig } from '../../../../tsdown.config.base.ts';
88
89 export default defineConfig({
91 - entry: ['src/index.ts'],
92 - format: ['esm', 'cjs'],
93 - dts: true,
94 - clean: true,
95 - minify: false,
96 - outDir: 'dist',
90 + ...baseConfig,
91 + tsconfig: 'tsconfig.json',
92 });
93 EOL
94
@@ -254,4 +249,4 @@ chmod +x "$TOOLSET_PATH"
249 cd "$TOOLSET_PATH" && pnpm install
250
251 echo "✨ Created new ${IS_AGENTIC:+agentic }provider at $TOOLSET_PATH"
257 -echo "✨ Dependencies installed successfully"
\ No newline at end of file
252 +echo "✨ Dependencies installed successfully"
ts/scripts/pre-install.sh
+1 -1
@@ -17,5 +17,5 @@ if ! command -v bun &> /dev/null; then
17 fi
18
19 echo "Bun is installed."
20 -echo "Checking if Bun version matches mise.toml..."
20 +echo "Checking if toolchain versions match mise.toml..."
21 bun run "$SCRIPT_DIR/pre-install/check-toolchain.ts"
ts/scripts/pre-install/check-toolchain.ts
+37 -10
@@ -12,12 +12,19 @@ declare module 'bun' {
12 }
13 }
14
15 -function getRequiredBunVersion(): string {
15 +type CheckedTool = 'bun' | 'pnpm';
16 +
17 +const miseTool: Record<CheckedTool, string> = {
18 + bun: 'bun',
19 + pnpm: 'npm:pnpm',
20 +};
21 +
22 +function getRequiredVersion(tool: CheckedTool): string {
23 try {
17 - return execFileSync('mise', ['current', 'bun'], { encoding: 'utf-8' }).trim();
24 + return execFileSync('mise', ['current', miseTool[tool]], { encoding: 'utf-8' }).trim();
25 } catch (err) {
26 console.error(
20 - `Failed to resolve Bun version from mise.toml.
27 + `Failed to resolve ${tool} version from mise.toml.
28 Install mise and run:
29
30 \`mise install\`
@@ -28,17 +35,28 @@ Original error: ${(err as Error).message}`
35 }
36 }
37
31 -function main() {
32 - if (Bun.env.BYPASS_TOOLCHAIN_CHECK) {
33 - return;
38 +function getPnpmVersion(): string {
39 + try {
40 + return execFileSync('pnpm', ['--version'], { encoding: 'utf-8' }).trim();
41 + } catch (err) {
42 + console.error(
43 + `Failed to resolve pnpm version.
44 +Install the repository toolchain by running:
45 +
46 +\`mise install\`
47 +
48 +Original error: ${(err as Error).message}`
49 + );
50 + process.exit(1);
51 }
52 +}
53
36 - const requiredBunVersion = getRequiredBunVersion();
37 - const actualBunVersion = Bun.version.trim();
54 +function assertVersion(tool: CheckedTool, actualVersion: string) {
55 + const requiredVersion = getRequiredVersion(tool);
56
39 - if (actualBunVersion !== requiredBunVersion) {
57 + if (actualVersion !== requiredVersion) {
58 console.error(
41 - `Bun version mismatch: expected ${requiredBunVersion}, got ${actualBunVersion}.
59 + `${tool} version mismatch: expected ${requiredVersion}, got ${actualVersion}.
60 Install the repository toolchain by running:
61
62 \`mise install\`
@@ -48,6 +66,15 @@ Install the repository toolchain by running:
66 }
67 }
68
69 +function main() {
70 + if (Bun.env.BYPASS_TOOLCHAIN_CHECK) {
71 + return;
72 + }
73 +
74 + assertVersion('bun', Bun.version.trim());
75 + assertVersion('pnpm', getPnpmVersion());
76 +}
77 +
78 if (import.meta.path === Bun.main) {
79 main();
80 }
ts/scripts/validate-examples.ts
+14 -28
@@ -4,17 +4,7 @@ import ts from 'typescript';
4
5 const repoRoot = process.cwd();
6 const examplesRoot = path.join(repoRoot, 'ts', 'examples');
7 -const allowedSourceExtensions = new Set([
8 - '.cjs',
9 - '.cts',
10 - '.js',
11 - '.jsx',
12 - '.mjs',
13 - '.mts',
14 - '.ts',
15 - '.tsx',
16 - '.json',
17 -]);
7 +const allowedSourceExtensions = new Set(['.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx', '.json']);
8
9 type ValidationIssue = {
10 example: string;
@@ -53,7 +43,6 @@ const validatePackageJson = (exampleName: string, exampleDir: string) => {
43 dependencies?: Record<string, string>;
44 devDependencies?: Record<string, string>;
45 name?: string;
56 - packageManager?: string;
46 private?: boolean;
47 scripts?: Record<string, string>;
48 };
@@ -66,10 +55,6 @@ const validatePackageJson = (exampleName: string, exampleDir: string) => {
55 addIssue(exampleName, packageJsonPath, 'Examples must be marked private');
56 }
57
69 - if (!pkg.packageManager?.startsWith('pnpm@')) {
70 - addIssue(exampleName, packageJsonPath, 'Examples must declare a pnpm packageManager');
71 - }
72 -
58 if (!pkg.scripts || (!pkg.scripts.start && !pkg.scripts.dev)) {
59 addIssue(exampleName, packageJsonPath, 'Examples must expose a start or dev script');
60 }
@@ -80,7 +65,11 @@ const validatePackageJson = (exampleName: string, exampleDir: string) => {
65 };
66
67 if (!Object.keys(allDeps).some(dep => dep.startsWith('@composio/'))) {
83 - addIssue(exampleName, packageJsonPath, 'Examples must depend on at least one @composio package');
68 + addIssue(
69 + exampleName,
70 + packageJsonPath,
71 + 'Examples must depend on at least one @composio package'
72 + );
73 }
74 } catch (error) {
75 addIssue(
@@ -140,14 +129,13 @@ const validateSourceFile = (exampleName: string, filePath: string) => {
129 }
130
131 const sourceText = fs.readFileSync(filePath, 'utf8');
143 - const isTsFile = ['.ts', '.tsx', '.mts', '.cts'].includes(extension);
144 - const scriptKind = extension === '.tsx'
145 - ? ts.ScriptKind.TSX
146 - : extension === '.jsx'
147 - ? ts.ScriptKind.JSX
148 - : extension === '.js'
149 - ? ts.ScriptKind.JS
150 - : extension === '.cjs'
132 + const isTsFile = ['.ts', '.tsx', '.mts'].includes(extension);
133 + const scriptKind =
134 + extension === '.tsx'
135 + ? ts.ScriptKind.TSX
136 + : extension === '.jsx'
137 + ? ts.ScriptKind.JSX
138 + : extension === '.js'
139 ? ts.ScriptKind.JS
140 : extension === '.mjs'
141 ? ts.ScriptKind.JS
@@ -177,9 +165,7 @@ const validateSourceFile = (exampleName: string, filePath: string) => {
165 )
166 : undefined;
167
180 - const formattedLocation = location
181 - ? `:${location.line + 1}:${location.character + 1}`
182 - : '';
168 + const formattedLocation = location ? `:${location.line + 1}:${location.character + 1}` : '';
169
170 addIssue(exampleName, `${relativePath}${formattedLocation}`, `Syntax error: ${message}`);
171 }
tsdown.config.base.ts
+11 -18
@@ -1,4 +1,4 @@
1 -import type { UserConfig, OutExtensionContext } from 'tsdown';
1 +import type { UserConfig } from 'tsdown';
2
3 // Turbo task execution triggers a tsdown ATTW tarball path bug for scoped packages.
4 // Keep ATTW for direct package builds, but disable it for workspace builds.
@@ -19,21 +19,16 @@ export const baseConfig = {
19 * Output directory for the build.
20 */
21 outDir: 'dist',
22 - outExtensions: (ctx) => ({
23 - js: isESM(ctx)
24 - ? '.mjs'
25 - : '.cjs',
26 - dts: isESM(ctx)
27 - ? '.d.mts'
28 - : '.d.cts',
22 + outExtensions: () => ({
23 + js: '.mjs',
24 + dts: '.d.mts',
25 }),
26
27 /**
28 * Configures the output formats for the build.
29 * - 'esm' generates ESM (ECMAScript Module) output
34 - * - 'cjs' generates lecayse CommonJS output
30 */
36 - format: ['esm', 'cjs' /* legacy */],
31 + format: ['esm'],
32
33 /**
34 * Generates TypeScript declaration files (.d.mts, .d.ts)
@@ -77,14 +72,16 @@ export const baseConfig = {
72 * Configuration for @arethetypeswrong/cli.
73 * Uses '.' entrypoint to check the package root via the exports field,
74 * since src/index.ts is only used during development and not exported.
80 - * Uses 'node16' profile since packages support both ESM and CJS.
75 + * Uses the ESM-only profile because packages no longer publish CJS entrypoints.
76 */
77 attw: {
78 entrypoints: ['.'],
79 enabled: !isTurboTask,
80 level: 'error',
86 - profile: 'node16',
87 - ignoreRules: [/* Node.js 10 only, attw doesn't automatically exclude it despite the selected profile */ 'internal-resolution-error'],
81 + profile: 'esm-only',
82 + ignoreRules: [
83 + /* Node.js 10 only, attw doesn't automatically exclude it despite the selected profile */ 'internal-resolution-error',
84 + ],
85 },
86
87 /**
@@ -95,8 +92,4 @@ export const baseConfig = {
92 level: 'error',
93 pack: 'pnpm',
94 },
98 -} satisfies UserConfig
99 -
100 -function isESM(ctx: OutExtensionContext) {
101 - return ctx.format === 'es'
102 -}
95 +} satisfies UserConfig;
turbo.jsonc
+5
@@ -1,5 +1,10 @@
1 {
2 "$schema": "https://turbo.build/schema.json",
3 + // pnpm is pinned solely by mise (`npm:pnpm` in mise.toml). We intentionally
4 + // omit the root `packageManager` field rather than duplicate that version, so
5 + // mise stays the single source of truth. Turbo then infers pnpm from
6 + // pnpm-lock.yaml for workspace resolution.
7 + "dangerouslyDisablePackageManagerCheck": true,
8 "tasks": {
9 "build": {
10 "dependsOn": ["^build"],