@devries-cameron20 / composio-1 / commits / f5ff810f2
Fork 0

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

refactor(cli): define services with Context.Tag and thread argv explicitly (#4359)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4358 - replaces the eleven `Effect.Service` files (fourteen services) with `Context.Tag` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer built from a `make<Name>` constructor - removes the three `accessors: true` declarations; nothing in `src/` used a generated accessor, and the one test that did now yields the service - builds test doubles with `Service.of({ ... })` instead of `new Service({ ... })`, and types helper parameters with the `Shape` types where the class had been used as a type - passes the normalized argv from `bin.ts` into `runCli` and through `cli-main.ts` instead of mutating `process.argv` and reading it back in five places - documents the service pattern in `ts/packages/cli/AGENTS.md` ## Context Effect v4 replaces `Effect.Service` with `Context.Service`, which generates neither a `.Default` layer nor accessors; with the explicit-layer shape already on v3, the port turns each service into a one-line rename. `Command.runWith` in `effect/unstable/cli` takes user arguments explicitly, so `cli-main.ts` now receives argv rather than re-reading process state. Second of three preparation PRs. ## Validation - `pnpm --filter @composio/cli typecheck`, `validate:boundaries`, and oxlint clean - `pnpm --filter @composio/cli test`: 127 files, 1319 tests pass, 1 skipped

Alberto Schiabel committed Sep 7, 2026 at 12:34 UTC f5ff810f2ec714d3881d152689f9d2c77e0bb9bc
27 files changed +1415 -1313
ts/packages/cli/AGENTS.md
+2
@@ -72,6 +72,8 @@ Options use `Options.text()`, `Options.boolean()`, `Options.choice()`, `Options.
72 | `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
73 | `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
74
75 +Services are `Context.Tag` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer (`Layer.effect` / `Layer.sync`, dependencies provided with `Layer.provide`). Build a test double with `Service.of({ ... })`; there are no generated accessors or constructors.
76 +
77 OS credential storage uses the sibling package `@composio/cli-keyring` (macOS Keychain / Linux Secret Service).
78
79 ### Effects — `src/effects/`
ts/packages/cli/src/bin.ts
+2 -2
@@ -7,8 +7,8 @@ import { NodeOs } from 'src/services/node-os';
7 import { TerminalUILive } from 'src/services/terminal-ui';
8 import { stripTelemetryDebugFlag, telemetryDebugModeLayer } from 'src/services/runtime-flags';
9
10 +// The one `process.argv` read: every later consumer receives this normalized argv explicitly.
11 const bootstrap = stripTelemetryDebugFlag(process.argv);
11 -process.argv = [...bootstrap.argv];
12
13 const workerLayers = Layer.mergeAll(
14 BunFileSystem.layer,
@@ -33,6 +33,6 @@ if (isBackgroundWorkerInvocation(bootstrap.argv)) {
33 );
34 } else {
35 void import('./cli-main').then(({ runCli }) =>
36 - runCli({ telemetryDebug: bootstrap.telemetryDebug })
36 + runCli({ argv: bootstrap.argv, telemetryDebug: bootstrap.telemetryDebug })
37 );
38 }
ts/packages/cli/src/cli-main.ts
+157 -151
@@ -156,181 +156,187 @@ export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: n
156 onExit(Number(process.exitCode ?? (shouldFail ? 1 : 0)));
157 };
158
159 -const runWithArgs = (bootstrap: RootCommandBootstrap) =>
160 - Effect.flatMap(runWithConfig, run => run(process.argv, bootstrap)) satisfies Effect.Effect<
159 +const runWithArgs = (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap) =>
160 + Effect.flatMap(runWithConfig, run => run(argv, bootstrap)) satisfies Effect.Effect<
161 void,
162 unknown,
163 unknown
164 >;
165
166 -const runWithTelemetry = Effect.gen(function* () {
167 - const ui = yield* TerminalUI;
168 - const terminal = yield* ui.capabilities;
166 +const runWithTelemetry = (argv: ReadonlyArray<string>) =>
167 + Effect.gen(function* () {
168 + const ui = yield* TerminalUI;
169 + const terminal = yield* ui.capabilities;
170
170 - const version = yield* getVersion;
171 - configureCliAnalyticsReleaseVersion(version);
172 - const baseTelemetryContext = createCliCommandTelemetryContext(
173 - process.argv,
174 - version,
175 - terminal,
176 - yield* cliInvocationContext
177 - );
178 - const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);
179 - const commandTelemetryContext =
180 - executeToolSlug === undefined
181 - ? baseTelemetryContext
182 - : { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };
183 - // `composio run` mints its run id here so the lifecycle events and the id the spawned script
184 - // inherits are the same value; every other command leaves it unset.
185 - const bootstrap: RootCommandBootstrap =
186 - commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId
187 - ? { runId: commandTelemetryContext.runId }
188 - : {};
189 - return yield* trackCliEventEffect(getPrimaryLifecycleInvokedEvent(commandTelemetryContext)).pipe(
190 - Effect.andThen(runWithArgs(bootstrap)),
191 - Effect.scoped,
192 - Effect.mapError(error =>
193 - ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
194 - ),
195 - Effect.tap(() =>
196 - trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))
197 - ),
198 - Effect.tapErrorCause(cause =>
199 - trackCliEventEffect(
200 - getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
171 + const version = yield* getVersion;
172 + configureCliAnalyticsReleaseVersion(version);
173 + const baseTelemetryContext = createCliCommandTelemetryContext(
174 + argv,
175 + version,
176 + terminal,
177 + yield* cliInvocationContext
178 + );
179 + const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);
180 + const commandTelemetryContext =
181 + executeToolSlug === undefined
182 + ? baseTelemetryContext
183 + : { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };
184 + // `composio run` mints its run id here so the lifecycle events and the id the spawned script
185 + // inherits are the same value; every other command leaves it unset.
186 + const bootstrap: RootCommandBootstrap =
187 + commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId
188 + ? { runId: commandTelemetryContext.runId }
189 + : {};
190 + return yield* trackCliEventEffect(
191 + getPrimaryLifecycleInvokedEvent(commandTelemetryContext)
192 + ).pipe(
193 + Effect.andThen(runWithArgs(argv, bootstrap)),
194 + Effect.scoped,
195 + Effect.mapError(error =>
196 + ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
197 + ),
198 + Effect.tap(() =>
199 + trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))
200 + ),
201 + Effect.tapErrorCause(cause =>
202 + trackCliEventEffect(
203 + getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
204 + )
205 )
202 - )
203 - );
204 -});
206 + );
207 + });
208
209 /**
210 * Values `src/bin.ts` resolved before the Effect runtime existed and hands to it here.
211 */
212 export type CliBootstrapOptions = {
213 + /** The full process argv (executable and script included) with `--telemetry-debug` stripped. */
214 + readonly argv: ReadonlyArray<string>;
215 /** `--telemetry-debug` was on the command line, and was stripped from argv before parsing. */
216 readonly telemetryDebug: boolean;
217 };
218
214 -const cliProgram = showUpdateNotice.pipe(
215 - Effect.andThen(showPluginAcquisitionHint(process.argv)),
216 - Effect.andThen(runWithTelemetry),
217 - Effect.catchIf(ValidationError.isValidationError, error => {
218 - return Effect.gen(function* () {
219 - const ui = yield* TerminalUI;
220 - const cliUserConfig = yield* ComposioCliUserConfig;
221 - const visibility = {
222 - isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
223 - isExperimentalFeatureEnabled: (feature: string) =>
224 - cliUserConfig.isExperimentalFeatureEnabled(feature),
225 - };
226 - const valueOptionNames = collectValueOptionNames(buildRootCommand(visibility));
227 - const text = HelpDoc.toAnsiText(error.error).trim();
228 - const errorEffect = text.length > 0 ? ui.error(text) : Effect.void;
229 - const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);
230 - const tipEffect =
231 - flagMatch && valueOptionNames.has(flagMatch[1])
232 - ? ui.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)
233 - : Effect.void;
234 - const cmdName = matchCommandFromArgv(process.argv, visibility);
235 - const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
236 - const helpEffect = helpText ? ui.error(helpText) : Effect.void;
237 - return yield* Effect.all([errorEffect, tipEffect, helpEffect], { discard: true }).pipe(
238 - Effect.tap(() =>
239 - Effect.sync(() => {
240 - process.exitCode = 1;
241 - })
242 - )
243 - );
244 - });
245 - }),
246 - Effect.catchIf(
247 - (error): error is SetupCommandError => error instanceof SetupCommandError,
248 - error =>
249 - Effect.gen(function* () {
219 +const cliProgram = (argv: ReadonlyArray<string>) =>
220 + showUpdateNotice.pipe(
221 + Effect.andThen(showPluginAcquisitionHint(argv)),
222 + Effect.andThen(runWithTelemetry(argv)),
223 + Effect.catchIf(ValidationError.isValidationError, error => {
224 + return Effect.gen(function* () {
225 const ui = yield* TerminalUI;
251 - const summary =
252 - error.operation === 'uninstall'
253 - ? 'Composio plugin uninstall was unsuccessful.'
254 - : 'Composio setup was unsuccessful.';
255 - if ((yield* ui.capabilities).canDecorate) {
256 - yield* ui.log.error(error.message);
257 - yield* ui.outro(summary);
258 - } else {
259 - yield* ui.error(`${summary} ${error.message}`);
260 - }
261 - process.exitCode = 1;
262 - })
263 - ),
264 - // A bare `composio run` is a usage mistake, not a broken invariant: print the one-line fix and
265 - // exit non-zero instead of routing it through the defect reporter below.
266 - Effect.catchIf(
267 - (error): error is MissingRunSourceError => error instanceof MissingRunSourceError,
268 - error =>
269 - Effect.gen(function* () {
270 - const ui = yield* TerminalUI;
271 - yield* ui.error(error.message);
272 - process.exitCode = 1;
273 - })
274 - ),
275 - Effect.catchIf(
276 - (error): error is ShellSetupAbortError => error instanceof ShellSetupAbortError,
277 - // `composio install` already printed the abort reason; the typed failure
278 - // only exists so the process exits non-zero and install.sh runs its
279 - // guarded inline PATH fallback instead of reporting a green install.
280 - () =>
281 - Effect.sync(() => {
282 - process.exitCode = 1;
283 - })
284 - ),
285 - Effect.withSpan('composio-cli', {
286 - attributes: {
287 - name: constants.APP_NAME,
288 - filename: 'src/bin.ts',
289 - },
290 - }),
291 - Effect.sandbox,
292 - Effect.catchAll(
293 - Effect.fn(function* (cause) {
294 - const captured = yield* captureErrors(cause, {
295 - stripCwd: true,
226 + const cliUserConfig = yield* ComposioCliUserConfig;
227 + const visibility = {
228 + isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
229 + isExperimentalFeatureEnabled: (feature: string) =>
230 + cliUserConfig.isExperimentalFeatureEnabled(feature),
231 + };
232 + const valueOptionNames = collectValueOptionNames(buildRootCommand(visibility));
233 + const text = HelpDoc.toAnsiText(error.error).trim();
234 + const errorEffect = text.length > 0 ? ui.error(text) : Effect.void;
235 + const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);
236 + const tipEffect =
237 + flagMatch && valueOptionNames.has(flagMatch[1])
238 + ? ui.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)
239 + : Effect.void;
240 + const cmdName = matchCommandFromArgv(argv, visibility);
241 + const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
242 + const helpEffect = helpText ? ui.error(helpText) : Effect.void;
243 + return yield* Effect.all([errorEffect, tipEffect, helpEffect], { discard: true }).pipe(
244 + Effect.tap(() =>
245 + Effect.sync(() => {
246 + process.exitCode = 1;
247 + })
248 + )
249 + );
250 });
297 - const filteredErrors = captured.errors.filter(
298 - error => error.errorType !== 'ReportedToolExecutionError'
299 - );
300 - if (captured.interrupted || filteredErrors.length > 0) {
301 - const message = prettyPrintFromCapturedErrors(
302 - { ...captured, errors: filteredErrors },
303 - {
304 - hideStackTrace: true,
305 - stripCwd: true,
306 - enabled: true,
307 - }
308 - ).trim();
309 - if (message.length > 0) {
251 + }),
252 + Effect.catchIf(
253 + (error): error is SetupCommandError => error instanceof SetupCommandError,
254 + error =>
255 + Effect.gen(function* () {
256 const ui = yield* TerminalUI;
311 - yield* ui.error(message);
312 - const cliUserConfig = yield* ComposioCliUserConfig;
313 - const visibility = {
314 - isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
315 - isExperimentalFeatureEnabled: (feature: string) =>
316 - cliUserConfig.isExperimentalFeatureEnabled(feature),
317 - };
318 - const cmdName = matchCommandFromArgv(process.argv, visibility);
319 - const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
320 - if (helpText) {
321 - yield* ui.error(helpText);
257 + const summary =
258 + error.operation === 'uninstall'
259 + ? 'Composio plugin uninstall was unsuccessful.'
260 + : 'Composio setup was unsuccessful.';
261 + if ((yield* ui.capabilities).canDecorate) {
262 + yield* ui.log.error(error.message);
263 + yield* ui.outro(summary);
264 + } else {
265 + yield* ui.error(`${summary} ${error.message}`);
266 }
267 process.exitCode = 1;
268 + })
269 + ),
270 + // A bare `composio run` is a usage mistake, not a broken invariant: print the one-line fix and
271 + // exit non-zero instead of routing it through the defect reporter below.
272 + Effect.catchIf(
273 + (error): error is MissingRunSourceError => error instanceof MissingRunSourceError,
274 + error =>
275 + Effect.gen(function* () {
276 + const ui = yield* TerminalUI;
277 + yield* ui.error(error.message);
278 + process.exitCode = 1;
279 + })
280 + ),
281 + Effect.catchIf(
282 + (error): error is ShellSetupAbortError => error instanceof ShellSetupAbortError,
283 + // `composio install` already printed the abort reason; the typed failure
284 + // only exists so the process exits non-zero and install.sh runs its
285 + // guarded inline PATH fallback instead of reporting a green install.
286 + () =>
287 + Effect.sync(() => {
288 + process.exitCode = 1;
289 + })
290 + ),
291 + Effect.withSpan('composio-cli', {
292 + attributes: {
293 + name: constants.APP_NAME,
294 + filename: 'src/bin.ts',
295 + },
296 + }),
297 + Effect.sandbox,
298 + Effect.catchAll(
299 + Effect.fn(function* (cause) {
300 + const captured = yield* captureErrors(cause, {
301 + stripCwd: true,
302 + });
303 + const filteredErrors = captured.errors.filter(
304 + error => error.errorType !== 'ReportedToolExecutionError'
305 + );
306 + if (captured.interrupted || filteredErrors.length > 0) {
307 + const message = prettyPrintFromCapturedErrors(
308 + { ...captured, errors: filteredErrors },
309 + {
310 + hideStackTrace: true,
311 + stripCwd: true,
312 + enabled: true,
313 + }
314 + ).trim();
315 + if (message.length > 0) {
316 + const ui = yield* TerminalUI;
317 + yield* ui.error(message);
318 + const cliUserConfig = yield* ComposioCliUserConfig;
319 + const visibility = {
320 + isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
321 + isExperimentalFeatureEnabled: (feature: string) =>
322 + cliUserConfig.isExperimentalFeatureEnabled(feature),
323 + };
324 + const cmdName = matchCommandFromArgv(argv, visibility);
325 + const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
326 + if (helpText) {
327 + yield* ui.error(helpText);
328 + }
329 + process.exitCode = 1;
330 + }
331 }
325 - }
326 - })
327 - ),
328 - Effect.provide(layers),
329 - Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive))
330 -);
332 + })
333 + ),
334 + Effect.provide(layers),
335 + Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive))
336 + );
337
338 export const runCli = (options: CliBootstrapOptions): void => {
333 - cliProgram.pipe(
339 + cliProgram(options.argv).pipe(
340 // Only provided when the flag was actually present: without it telemetry debugging falls back
341 // to `COMPOSIO_CLI_TELEMETRY_DEBUG`.
342 effect =>
ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts
+8 -5
@@ -19,7 +19,10 @@ import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';
19 import { Array, Data, Effect, Option, pipe } from 'effect';
20 import { Match } from 'effect';
21 import { FileSystem, Path } from '@effect/platform';
22 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
22 +import {
23 + ComposioToolkitsRepository,
24 + type ComposioToolkitsRepositoryShape,
25 +} from 'src/services/composio-clients';
26 import { logMetrics } from 'src/effects/log-metrics';
27 import { NodeProcess } from 'src/services/node-process';
28 import { createToolkitIndex } from 'src/generation/create-toolkit-index';
@@ -115,7 +118,7 @@ type FetchResult = {
118 * Makes targeted API calls for only the requested toolkits.
119 */
120 function fetchFilteredData(
118 - client: ComposioToolkitsRepository,
121 + client: ComposioToolkitsRepositoryShape,
122 slugs: ReadonlyArray<string>,
123 typeTools: boolean,
124 versionOverrides: ToolkitVersionOverrides,
@@ -195,7 +198,7 @@ function fetchFilteredData(
198 * Fetches everything in parallel without version-specific handling.
199 */
200 function fetchAllDataFastPath(
198 - client: ComposioToolkitsRepository,
201 + client: ComposioToolkitsRepositoryShape,
202 typeTools: boolean,
203 spinner: SpinnerHandle
204 ): Effect.Effect<FetchResult, Error, never> {
@@ -245,7 +248,7 @@ function fetchAllDataFastPath(
248 * First fetches toolkit metadata, then fetches tools with version-specific handling.
249 */
250 function fetchAllDataWithOverrides(
248 - client: ComposioToolkitsRepository,
251 + client: ComposioToolkitsRepositoryShape,
252 typeTools: boolean,
253 versionOverrides: ToolkitVersionOverrides,
254 spinner: SpinnerHandle
@@ -305,7 +308,7 @@ function fetchAllDataWithOverrides(
308 * Delegates to fast path or override-aware path based on version overrides.
309 */
310 function fetchAllData(
308 - client: ComposioToolkitsRepository,
311 + client: ComposioToolkitsRepositoryShape,
312 typeTools: boolean,
313 versionOverrides: ToolkitVersionOverrides,
314 spinner: SpinnerHandle
ts/packages/cli/src/effects/validate-toolkit-versions.ts
+2 -2
@@ -3,7 +3,7 @@ import colors from 'picocolors';
3 import { S_BAR, unicodeOr } from '@clack/prompts';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import type {
6 - ComposioToolkitsRepository,
6 + ComposioToolkitsRepositoryShape,
7 InvalidVersionDetail,
8 } from 'src/services/composio-clients';
9 import type { ToolkitVersionOverrides } from './toolkit-version-overrides';
@@ -119,7 +119,7 @@ export interface ValidateVersionsOptions {
119 /** Optional array of toolkit slugs to filter (from --toolkits flag) */
120 readonly toolkitSlugsFilter: ReadonlyArray<string> | null;
121 /** The ComposioToolkitsRepository client */
122 - readonly client: ComposioToolkitsRepository;
122 + readonly client: ComposioToolkitsRepositoryShape;
123 }
124
125 /**
ts/packages/cli/src/services/command-runner.ts
+28 -22
@@ -1,5 +1,5 @@
1 import { Command } from '@effect/platform';
2 -import { Effect, Stream, String } from 'effect';
2 +import { Effect, Stream, String, Context, Layer } from 'effect';
3
4 export interface CommandResult {
5 readonly exitCode: number;
@@ -11,24 +11,30 @@ export interface CommandResult {
11 export const collectText = (stream: Stream.Stream<Uint8Array, unknown>) =>
12 stream.pipe(Stream.decodeText(), Stream.runFold(String.empty, String.concat));
13
14 -export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {
15 - sync: () => ({
16 - run: (command: Command.Command) => Command.exitCode(command),
17 - capture: (command: Command.Command) =>
18 - Effect.scoped(
19 - Effect.gen(function* () {
20 - const childProcess = yield* Command.start(command);
21 - const [exitCode, stdout, stderr] = yield* Effect.all(
22 - [
23 - childProcess.exitCode,
24 - collectText(childProcess.stdout),
25 - collectText(childProcess.stderr),
26 - ],
27 - { concurrency: 'unbounded' }
28 - );
29 - return { exitCode: Number(exitCode), stdout, stderr } satisfies CommandResult;
30 - })
31 - ),
32 - }),
33 - dependencies: [],
34 -}) {}
14 +const makeCommandRunner = Effect.sync(() => ({
15 + run: (command: Command.Command) => Command.exitCode(command),
16 + capture: (command: Command.Command) =>
17 + Effect.scoped(
18 + Effect.gen(function* () {
19 + const childProcess = yield* Command.start(command);
20 + const [exitCode, stdout, stderr] = yield* Effect.all(
21 + [
22 + childProcess.exitCode,
23 + collectText(childProcess.stdout),
24 + collectText(childProcess.stderr),
25 + ],
26 + { concurrency: 'unbounded' }
27 + );
28 + return { exitCode: Number(exitCode), stdout, stderr } satisfies CommandResult;
29 + })
30 + ),
31 +}));
32 +
33 +export type CommandRunnerShape = Effect.Effect.Success<typeof makeCommandRunner>;
34 +
35 +export class CommandRunner extends Context.Tag('services/CommandRunner')<
36 + CommandRunner,
37 + CommandRunnerShape
38 +>() {
39 + static readonly Default = Layer.effect(CommandRunner, makeCommandRunner);
40 +}
ts/packages/cli/src/services/composio-clients-cached.ts
+1 -1
@@ -180,7 +180,7 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
180 );
181
182 // Create the cached implementation that wraps the original implementation
183 - return ComposioToolkitsRepository.make({
183 + return ComposioToolkitsRepository.of({
184 // Memoized per layer instance; `getToolkitsBySlugs` stays unmemoized
185 // because its result depends on the requested slugs.
186 getToolkits: () => cachedGetToolkits,
ts/packages/cli/src/services/composio-clients.ts
+533 -518
@@ -11,6 +11,8 @@ import {
11 Stream,
12 Sink,
13 SynchronizedRef,
14 + Context,
15 + Layer,
16 } from 'effect';
17 import { Composio as _RawComposioClient, APIPromise } from '@composio/client';
18 import { FileSystem, Path } from '@effect/platform';
@@ -419,7 +421,7 @@ export interface TriggerInstanceUpsertParams {
421 }
422
423 function buildTriggerInstancesNamespace(
422 - clientSingleton: ComposioClientSingleton,
424 + clientSingleton: ComposioClientSingletonShape,
425 withMetrics: <A, E, R>(
426 effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
427 ) => Effect.Effect<A, E, R>
@@ -473,7 +475,7 @@ function buildTriggerInstancesNamespace(
475 };
476 }
477
476 -function buildTriggerInstanceRepositoryOperations(client: ComposioClientLive) {
478 +function buildTriggerInstanceRepositoryOperations(client: ComposioClientLiveShape) {
479 return {
480 listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
481 client.triggerInstances.listActive(params),
@@ -1377,7 +1379,7 @@ const buildDefaultHeaders = (params: {
1379
1380 // Utility function for calling the Composio API and decoding its response.
1381 const callClient = <T, S extends Schema.Schema.AnyNoContext>(
1380 - clientSingleton: ComposioClientSingleton,
1382 + clientSingleton: ComposioClientSingletonShape,
1383 apiCall: (client: _RawComposioClient) => APIPromise<T>,
1384 responseSchema: S
1385 ): Effect.Effect<
@@ -1437,7 +1439,7 @@ const MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 4;
1439 // Utility function for calling paginated Composio API endpoints.
1440 // Automatically fetches all pages, using MAX_PAGE_SIZE per request.
1441 const callClientWithPagination = <T, S extends PaginatedSchema>(
1440 - clientSingleton: ComposioClientSingleton,
1442 + clientSingleton: ComposioClientSingletonShape,
1443 apiCall: (client: _RawComposioClient, cursor?: string, limit?: number) => APIPromise<T>,
1444 responseSchema: S
1445 ): Effect.Effect<
@@ -1524,93 +1526,97 @@ const callClientWithPagination = <T, S extends PaginatedSchema>(
1526 * Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
1527 * a raw (uneffectful, Promise-based) Composio client instance.
1528 */
1527 -export class ComposioClientSingleton extends Effect.Service<ComposioClientSingleton>()(
1528 - 'services/ComposioClientSingleton',
1529 - {
1530 - accessors: true,
1531 - effect: Effect.gen(function* () {
1532 - const ctx = yield* ComposioUserContext;
1533 - const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
1534 - const fs = yield* FileSystem.FileSystem;
1535 - const path = yield* Path.Path;
1536 - const os = yield* NodeOs;
1537 - const cache = new Map<string, _RawComposioClient>();
1538 -
1539 - const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
1540 - Effect.gen(function* () {
1541 - const apiKey = normalizeApiKey(
1542 - params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey)
1543 - );
1544 - const cacheKey = JSON.stringify({
1545 - apiKey: apiKey ?? null,
1546 - orgId: params?.orgId ?? null,
1547 - projectId: params?.projectId ?? null,
1548 - });
1549 - const cached = cache.get(cacheKey);
1550 - if (cached) {
1551 - return cached;
1552 - }
1529 +const makeComposioClientSingleton = Effect.gen(function* () {
1530 + const ctx = yield* ComposioUserContext;
1531 + const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
1532 + const fs = yield* FileSystem.FileSystem;
1533 + const path = yield* Path.Path;
1534 + const os = yield* NodeOs;
1535 + const cache = new Map<string, _RawComposioClient>();
1536 +
1537 + const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
1538 + Effect.gen(function* () {
1539 + const apiKey = normalizeApiKey(params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey));
1540 + const cacheKey = JSON.stringify({
1541 + apiKey: apiKey ?? null,
1542 + orgId: params?.orgId ?? null,
1543 + projectId: params?.projectId ?? null,
1544 + });
1545 + const cached = cache.get(cacheKey);
1546 + if (cached) {
1547 + return cached;
1548 + }
1549
1554 - const cliSessionId = yield* getCurrentCwdSessionId().pipe(
1555 - Effect.provideService(FileSystem.FileSystem, fs),
1556 - Effect.provideService(Path.Path, path),
1557 - Effect.provideService(NodeOs, os)
1558 - );
1550 + const cliSessionId = yield* getCurrentCwdSessionId().pipe(
1551 + Effect.provideService(FileSystem.FileSystem, fs),
1552 + Effect.provideService(Path.Path, path),
1553 + Effect.provideService(NodeOs, os)
1554 + );
1555
1560 - const client = new _RawComposioClient({
1561 - apiKey: null,
1562 - baseURL: ctx.data.baseURL,
1563 - defaultHeaders: buildDefaultHeaders({
1564 - userApiKey: apiKey,
1565 - orgId: params?.orgId,
1566 - projectId: params?.projectId,
1567 - cliSessionId,
1568 - }),
1569 - });
1556 + const client = new _RawComposioClient({
1557 + apiKey: null,
1558 + baseURL: ctx.data.baseURL,
1559 + defaultHeaders: buildDefaultHeaders({
1560 + userApiKey: apiKey,
1561 + orgId: params?.orgId,
1562 + projectId: params?.projectId,
1563 + cliSessionId,
1564 + }),
1565 + });
1566
1571 - cache.set(cacheKey, client);
1572 - return client;
1573 - });
1567 + cache.set(cacheKey, client);
1568 + return client;
1569 + });
1570
1575 - return {
1576 - get: Effect.fn(function* () {
1577 - const resolvedProjectContext = yield* Option.match(projectContextOpt, {
1578 - onNone: () => Effect.succeed(Option.none()),
1579 - onSome: projectContext =>
1580 - projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),
1581 - });
1582 - return yield* Option.match(resolvedProjectContext, {
1583 - onNone: () => getFor(),
1584 - onSome: keys =>
1585 - getFor({
1586 - orgId: keys.orgId,
1587 - projectId: keys.projectId,
1588 - }),
1589 - });
1590 - }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1591 - getFor: Effect.fn(function* (params: {
1592 - userApiKey?: string;
1593 - orgId?: string;
1594 - projectId?: string;
1595 - }) {
1596 - return yield* getFor(params);
1597 - }) satisfies (params: {
1598 - userApiKey?: string;
1599 - orgId?: string;
1600 - projectId?: string;
1601 - }) => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1602 - };
1603 - }),
1604 - dependencies: [ComposioUserContextLive],
1605 - }
1606 -) {}
1571 + return {
1572 + get: Effect.fn(function* () {
1573 + const resolvedProjectContext = yield* Option.match(projectContextOpt, {
1574 + onNone: () => Effect.succeed(Option.none()),
1575 + onSome: projectContext =>
1576 + projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),
1577 + });
1578 + return yield* Option.match(resolvedProjectContext, {
1579 + onNone: () => getFor(),
1580 + onSome: keys =>
1581 + getFor({
1582 + orgId: keys.orgId,
1583 + projectId: keys.projectId,
1584 + }),
1585 + });
1586 + }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1587 + getFor: Effect.fn(function* (params: {
1588 + userApiKey?: string;
1589 + orgId?: string;
1590 + projectId?: string;
1591 + }) {
1592 + return yield* getFor(params);
1593 + }) satisfies (params: {
1594 + userApiKey?: string;
1595 + orgId?: string;
1596 + projectId?: string;
1597 + }) => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1598 + };
1599 +});
1600 +
1601 +export type ComposioClientSingletonShape = Effect.Effect.Success<
1602 + typeof makeComposioClientSingleton
1603 +>;
1604 +
1605 +export class ComposioClientSingleton extends Context.Tag('services/ComposioClientSingleton')<
1606 + ComposioClientSingleton,
1607 + ComposioClientSingletonShape
1608 +>() {
1609 + static readonly Default = Layer.effect(ComposioClientSingleton, makeComposioClientSingleton).pipe(
1610 + Layer.provide(ComposioUserContextLive)
1611 + );
1612 +}
1613
1614 /**
1615 * Build the `tools` namespace for ComposioClientLive.
1616 * Extracted to keep the main generator under the max-lines-per-function limit.
1617 */
1618 function buildToolsNamespace(
1613 - clientSingleton: ComposioClientSingleton,
1619 + clientSingleton: ComposioClientSingletonShape,
1620 withMetrics: <A, E, R>(
1621 effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1622 ) => Effect.Effect<A, E, R>
@@ -1723,7 +1729,7 @@ function buildToolsNamespace(
1729 * Extracted to keep the main generator under the max-lines-per-function limit.
1730 */
1731 function buildAuthConfigsNamespace(
1726 - clientSingleton: ComposioClientSingleton,
1732 + clientSingleton: ComposioClientSingletonShape,
1733 withMetrics: <A, E, R>(
1734 effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1735 ) => Effect.Effect<A, E, R>
@@ -1792,7 +1798,7 @@ function buildAuthConfigsNamespace(
1798 * Extracted to keep the main generator under the max-lines-per-function limit.
1799 */
1800 function buildConnectedAccountsNamespace(
1795 - clientSingleton: ComposioClientSingleton,
1801 + clientSingleton: ComposioClientSingletonShape,
1802 withMetrics: <A, E, R>(
1803 effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1804 ) => Effect.Effect<A, E, R>
@@ -1859,449 +1865,458 @@ function buildConnectedAccountsNamespace(
1865 }
1866
1867 // Service that wraps the raw Composio client, which is shared by all client services.
1862 -export class ComposioClientLive extends Effect.Service<ComposioClientLive>()(
1863 - 'services/ComposioClientLive',
1864 - {
1865 - effect: Effect.gen(function* () {
1866 - const clientSingleton = yield* ComposioClientSingleton;
1867 -
1868 - // Initialize metrics tracking via SynchronizedRef
1869 - const metricsRef = yield* SynchronizedRef.make<Metrics>({ byteSize: 0, requests: 0 });
1870 -
1871 - // Helper to update metrics and return just the data
1872 - const withMetrics = <A, E, R>(
1873 - effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1874 - ): Effect.Effect<A, E, R> =>
1875 - Effect.gen(function* () {
1876 - const { data, metrics } = yield* effect;
1877 - yield* SynchronizedRef.update(metricsRef, current => ({
1878 - byteSize: current.byteSize + metrics.byteSize,
1879 - requests: current.requests + metrics.requests,
1880 - }));
1881 - return data;
1882 - });
1883 -
1884 - return {
1885 - /**
1886 - * Returns a snapshot of the current accumulated metrics (total bytes received and request count).
1887 - */
1888 - getMetrics: () => SynchronizedRef.get(metricsRef),
1889 - toolkits: {
1890 - /**
1891 - * Retrieves a comprehensive list of toolkits that are available to the authenticated project.
1892 - * Automatically handles pagination to fetch all items.
1893 - */
1894 - list: () =>
1895 - withMetrics(
1896 - callClientWithPagination(
1897 - clientSingleton,
1898 - (client, cursor, limit) => client.toolkits.list({ cursor, limit }),
1899 - ToolkitsResponse
1900 - )
1901 - ),
1902 - /**
1903 - * Retrieves a single toolkit by its slug.
1904 - * Transforms the response to match the Toolkit schema.
1905 - */
1906 - retrieve: (slug: string) =>
1907 - withMetrics(
1908 - callClient(
1909 - clientSingleton,
1910 - client => client.toolkits.retrieve(slug),
1911 - ToolkitRetrieveResponse
1912 - )
1913 - ).pipe(
1914 - // Transform to Toolkit format by adding missing fields
1915 - Effect.map(
1916 - retrieved =>
1917 - ({
1918 - name: retrieved.name,
1919 - slug: retrieved.slug,
1920 - auth_schemes: [], // retrieve endpoint doesn't return auth_schemes
1921 - composio_managed_auth_schemes: retrieved.composio_managed_auth_schemes,
1922 - is_local_toolkit: retrieved.is_local_toolkit,
1923 - no_auth: retrieved.no_auth,
1924 - meta: retrieved.meta,
1925 - }) satisfies Toolkit
1926 - )
1927 - ),
1928 - /**
1929 - * Searches toolkits with optional filters. Returns a single page of results (no auto-pagination).
1930 - * @param params - Search/filter parameters
1931 - */
1932 - search: (params: {
1933 - search?: string;
1934 - category?: string;
1935 - limit?: number;
1936 - cursor?: string;
1937 - }) =>
1938 - withMetrics(
1939 - callClient(
1940 - clientSingleton,
1941 - client =>
1942 - client.toolkits.list({
1943 - search: params.search,
1944 - category: params.category,
1945 - limit: params.limit,
1946 - cursor: params.cursor,
1947 - }),
1948 - ToolkitSearchResponse
1949 - )
1950 - ).pipe(
1951 - Effect.map(
1952 - response =>
1953 - ({
1954 - items: response.items,
1955 - total_items: response.total_items,
1956 - total_pages: response.total_pages,
1957 - next_cursor: response.next_cursor,
1958 - }) satisfies ToolkitSearchResult
1959 - )
1960 - ),
1961 - /**
1962 - * Retrieves detailed toolkit info including auth_config_details.
1963 - * @param slug - Toolkit slug
1964 - */
1965 - retrieveDetailed: (slug: string) =>
1966 - withMetrics(
1967 - callClient(
1968 - clientSingleton,
1969 - client => client.toolkits.retrieve(slug),
1970 - ToolkitDetailedResponse
1971 - )
1972 - ),
1973 - },
1974 - tools: buildToolsNamespace(clientSingleton, withMetrics),
1975 - triggersTypes: {
1976 - /**
1977 - * Retrieves a list of all available trigger type enum values that can be used across the API.
1978 - */
1979 - retrieveEnum: () =>
1980 - withMetrics(
1981 - callClient(
1982 - clientSingleton,
1983 - client => client.triggersTypes.retrieveEnum(),
1984 - TriggerTypesAsEnumsResponse
1985 - )
1986 - ),
1987 - /**
1988 - * Retrieves detailed info about a single trigger type by slug.
1989 - * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
1990 - */
1991 - retrieve: (slug: string) =>
1992 - withMetrics(
1993 - callClient(
1994 - clientSingleton,
1995 - client => client.triggersTypes.retrieve(slug),
1996 - TriggerType
1997 - )
1998 - ),
1999 - /**
2000 - * Retrieve a list of trigger types, automatically handling pagination.
2001 - * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2002 - */
2003 - list: (toolkitSlugs?: ReadonlyArray<string>) =>
2004 - withMetrics(
2005 - callClientWithPagination(
2006 - clientSingleton,
2007 - (client, cursor, limit) =>
2008 - client.triggersTypes.list({
2009 - cursor,
2010 - limit,
2011 - toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
2012 - }),
2013 - TriggerTypesResponse
2014 - )
2015 - ),
2016 - },
2017 - triggerInstances: buildTriggerInstancesNamespace(clientSingleton, withMetrics),
2018 - cli: {
2019 - /**
2020 - * Generates a new CLI session with a random 6-character code.
2021 - * @param params.scope - 'user' for login, 'project' for init (future)
2022 - *
2023 - * TODO: don't use `@composio/client`, wrap `fetch` directly.
2024 - */
2025 - createSession: (params?: { scope?: 'user' | 'project' }) =>
2026 - withMetrics(
2027 - callClient(
2028 - clientSingleton,
2029 - client =>
2030 - client.cli.createSession(
2031 - { scope: params?.scope ?? 'user' },
2032 - { headers: { 'Content-Type': 'application/json' } }
2033 - ),
2034 - CliCreateSessionResponse
2035 - )
2036 - ),
1868 +const makeComposioClientLive = Effect.gen(function* () {
1869 + const clientSingleton = yield* ComposioClientSingleton;
1870
2038 - /**
2039 - * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
2040 - */
2041 - getSession: (session: { id: string }) =>
2042 - withMetrics(
2043 - callClient(
2044 - clientSingleton,
2045 - client => client.cli.getSession(session),
2046 - CliGetSessionResponse
2047 - )
2048 - ),
2049 - getRealtimeCredentials: () =>
2050 - withMetrics(
2051 - callClient(
2052 - clientSingleton,
2053 - client => client.cli.realtime.credentials(),
2054 - CliRealtimeCredentialsResponse
2055 - )
2056 - ),
2057 - authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2058 - withMetrics(
2059 - callClient(
2060 - clientSingleton,
2061 - client => client.cli.realtime.auth(params),
2062 - CliRealtimeAuthResponse
2063 - )
2064 - ),
2065 - },
2066 - authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),
2067 - connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),
2068 - };
2069 - }),
2070 - dependencies: [ComposioClientSingleton.Default],
2071 - }
2072 -) {}
1871 + // Initialize metrics tracking via SynchronizedRef
1872 + const metricsRef = yield* SynchronizedRef.make<Metrics>({ byteSize: 0, requests: 0 });
1873
2074 -export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsRepository>()(
2075 - 'services/ComposioToolkitsRepository',
2076 - {
2077 - effect: Effect.gen(function* () {
2078 - const client = yield* ComposioClientLive;
1874 + // Helper to update metrics and return just the data
1875 + const withMetrics = <A, E, R>(
1876 + effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1877 + ): Effect.Effect<A, E, R> =>
1878 + Effect.gen(function* () {
1879 + const { data, metrics } = yield* effect;
1880 + yield* SynchronizedRef.update(metricsRef, current => ({
1881 + byteSize: current.byteSize + metrics.byteSize,
1882 + requests: current.requests + metrics.requests,
1883 + }));
1884 + return data;
1885 + });
1886
2080 - const getToolkits = () =>
2081 - client.toolkits.list().pipe(
2082 - Effect.map(response => response.items),
2083 - Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)
2084 - );
1887 + return {
1888 + /**
1889 + * Returns a snapshot of the current accumulated metrics (total bytes received and request count).
1890 + */
1891 + getMetrics: () => SynchronizedRef.get(metricsRef),
1892 + toolkits: {
1893 + /**
1894 + * Retrieves a comprehensive list of toolkits that are available to the authenticated project.
1895 + * Automatically handles pagination to fetch all items.
1896 + */
1897 + list: () =>
1898 + withMetrics(
1899 + callClientWithPagination(
1900 + clientSingleton,
1901 + (client, cursor, limit) => client.toolkits.list({ cursor, limit }),
1902 + ToolkitsResponse
1903 + )
1904 + ),
1905 + /**
1906 + * Retrieves a single toolkit by its slug.
1907 + * Transforms the response to match the Toolkit schema.
1908 + */
1909 + retrieve: (slug: string) =>
1910 + withMetrics(
1911 + callClient(
1912 + clientSingleton,
1913 + client => client.toolkits.retrieve(slug),
1914 + ToolkitRetrieveResponse
1915 + )
1916 + ).pipe(
1917 + // Transform to Toolkit format by adding missing fields
1918 + Effect.map(
1919 + retrieved =>
1920 + ({
1921 + name: retrieved.name,
1922 + slug: retrieved.slug,
1923 + auth_schemes: [], // retrieve endpoint doesn't return auth_schemes
1924 + composio_managed_auth_schemes: retrieved.composio_managed_auth_schemes,
1925 + is_local_toolkit: retrieved.is_local_toolkit,
1926 + no_auth: retrieved.no_auth,
1927 + meta: retrieved.meta,
1928 + }) satisfies Toolkit
1929 + )
1930 + ),
1931 + /**
1932 + * Searches toolkits with optional filters. Returns a single page of results (no auto-pagination).
1933 + * @param params - Search/filter parameters
1934 + */
1935 + search: (params: { search?: string; category?: string; limit?: number; cursor?: string }) =>
1936 + withMetrics(
1937 + callClient(
1938 + clientSingleton,
1939 + client =>
1940 + client.toolkits.list({
1941 + search: params.search,
1942 + category: params.category,
1943 + limit: params.limit,
1944 + cursor: params.cursor,
1945 + }),
1946 + ToolkitSearchResponse
1947 + )
1948 + ).pipe(
1949 + Effect.map(
1950 + response =>
1951 + ({
1952 + items: response.items,
1953 + total_items: response.total_items,
1954 + total_pages: response.total_pages,
1955 + next_cursor: response.next_cursor,
1956 + }) satisfies ToolkitSearchResult
1957 + )
1958 + ),
1959 + /**
1960 + * Retrieves detailed toolkit info including auth_config_details.
1961 + * @param slug - Toolkit slug
1962 + */
1963 + retrieveDetailed: (slug: string) =>
1964 + withMetrics(
1965 + callClient(
1966 + clientSingleton,
1967 + client => client.toolkits.retrieve(slug),
1968 + ToolkitDetailedResponse
1969 + )
1970 + ),
1971 + },
1972 + tools: buildToolsNamespace(clientSingleton, withMetrics),
1973 + triggersTypes: {
1974 + /**
1975 + * Retrieves a list of all available trigger type enum values that can be used across the API.
1976 + */
1977 + retrieveEnum: () =>
1978 + withMetrics(
1979 + callClient(
1980 + clientSingleton,
1981 + client => client.triggersTypes.retrieveEnum(),
1982 + TriggerTypesAsEnumsResponse
1983 + )
1984 + ),
1985 + /**
1986 + * Retrieves detailed info about a single trigger type by slug.
1987 + * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
1988 + */
1989 + retrieve: (slug: string) =>
1990 + withMetrics(
1991 + callClient(clientSingleton, client => client.triggersTypes.retrieve(slug), TriggerType)
1992 + ),
1993 + /**
1994 + * Retrieve a list of trigger types, automatically handling pagination.
1995 + * @param toolkitSlugs - Optional array of toolkit slugs to filter by
1996 + */
1997 + list: (toolkitSlugs?: ReadonlyArray<string>) =>
1998 + withMetrics(
1999 + callClientWithPagination(
2000 + clientSingleton,
2001 + (client, cursor, limit) =>
2002 + client.triggersTypes.list({
2003 + cursor,
2004 + limit,
2005 + toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
2006 + }),
2007 + TriggerTypesResponse
2008 + )
2009 + ),
2010 + },
2011 + triggerInstances: buildTriggerInstancesNamespace(clientSingleton, withMetrics),
2012 + cli: {
2013 + /**
2014 + * Generates a new CLI session with a random 6-character code.
2015 + * @param params.scope - 'user' for login, 'project' for init (future)
2016 + *
2017 + * TODO: don't use `@composio/client`, wrap `fetch` directly.
2018 + */
2019 + createSession: (params?: { scope?: 'user' | 'project' }) =>
2020 + withMetrics(
2021 + callClient(
2022 + clientSingleton,
2023 + client =>
2024 + client.cli.createSession(
2025 + { scope: params?.scope ?? 'user' },
2026 + { headers: { 'Content-Type': 'application/json' } }
2027 + ),
2028 + CliCreateSessionResponse
2029 + )
2030 + ),
2031
2032 /**
2087 - * Fetches specific toolkits by their slugs.
2088 - * Makes parallel API calls to retrieve each toolkit.
2089 - * @param slugs - Array of toolkit slugs to fetch
2033 + * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
2034 */
2091 - const getToolkitsBySlugs = (slugs: ReadonlyArray<string>) =>
2092 - Effect.all(
2093 - slugs.map(slug =>
2094 - client.toolkits.retrieve(slug).pipe(
2095 - // Only convert 404 errors to InvalidToolkitsError.
2096 - // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.
2097 - Effect.catchTag('services/HttpServerError', e =>
2098 - Effect.if(e.status === 404, {
2099 - onTrue: () =>
2100 - Effect.fail(
2101 - new InvalidToolkitsError({
2102 - invalidToolkits: [slug],
2103 - availableToolkits: [],
2104 - })
2105 - ),
2106 - onFalse: () => Effect.fail(e),
2107 - })
2108 - )
2109 - )
2110 - ),
2111 - { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
2112 - ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));
2035 + getSession: (session: { id: string }) =>
2036 + withMetrics(
2037 + callClient(
2038 + clientSingleton,
2039 + client => client.cli.getSession(session),
2040 + CliGetSessionResponse
2041 + )
2042 + ),
2043 + getRealtimeCredentials: () =>
2044 + withMetrics(
2045 + callClient(
2046 + clientSingleton,
2047 + client => client.cli.realtime.credentials(),
2048 + CliRealtimeCredentialsResponse
2049 + )
2050 + ),
2051 + authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2052 + withMetrics(
2053 + callClient(
2054 + clientSingleton,
2055 + client => client.cli.realtime.auth(params),
2056 + CliRealtimeAuthResponse
2057 + )
2058 + ),
2059 + },
2060 + authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),
2061 + connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),
2062 + };
2063 +});
2064
2114 - return {
2115 - getToolkits,
2116 - getToolkitsBySlugs,
2117 - getMetrics: () => client.getMetrics(),
2118 - getToolsAsEnums: () => client.tools.retrieveEnum(),
2119 - /**
2120 - * Fetches tools with optional toolkit filtering.
2121 - * When toolkitSlugs is provided, fetches all matching tools.
2122 - * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2123 - */
2124 - getTools: (toolkitSlugs?: ReadonlyArray<string>) =>
2125 - client.tools.list(toolkitSlugs ?? []).pipe(
2126 - Effect.map(response => response.items),
2127 - Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2128 - ),
2129 - /**
2130 - * Fetches tools with per-toolkit version support.
2131 - * Groups toolkits by version and makes separate API calls for each group.
2132 - * @param specs - Array of { toolkitSlug, toolkitVersion } specifications
2133 - */
2134 - getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
2135 - client.tools.listByVersionSpecs(specs).pipe(
2136 - Effect.map(response => response.items),
2137 - Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2138 - ),
2139 - getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),
2140 - /**
2141 - * Retrieves detailed info about a single trigger type by slug.
2142 - * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
2143 - */
2144 - getTriggerTypeDetailed: (slug: string) => client.triggersTypes.retrieve(slug),
2145 - /**
2146 - * Fetches trigger types with optional toolkit filtering.
2147 - * When toolkitSlugs is provided, fetches all matching trigger types.
2148 - * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2149 - */
2150 - getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
2151 - client.triggersTypes.list(toolkitSlugs).pipe(
2152 - Effect.map(response => response.items),
2153 - Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)
2154 - ),
2155 - /**
2156 - * Validates that the given toolkit slugs are valid by comparing them against the list
2157 - * of available toolkits. Returns the list of valid toolkit slugs (normalized to lowercase).
2158 - * @param toolkitSlugs - Array of toolkit slugs to validate (case-insensitive)
2159 - */
2160 - validateToolkits: (
2161 - toolkitSlugs: ReadonlyArray<string>
2162 - ): Effect.Effect<
2163 - ReadonlyArray<string>,
2164 - InvalidToolkitsError | HttpError | NoSuchElementException
2165 - > =>
2166 - Effect.gen(function* () {
2167 - // Normalize input slugs to lowercase for comparison
2168 - const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));
2169 -
2170 - // Fetch all available toolkits
2171 - const allToolkits = yield* getToolkits();
2172 - const availableSlugs = allToolkits.map(toolkit => String.toLowerCase(toolkit.slug));
2173 -
2174 - // Find invalid slugs
2175 - const invalidSlugs = normalizedInputSlugs.filter(
2176 - slug => !availableSlugs.includes(slug)
2177 - );
2065 +export type ComposioClientLiveShape = Effect.Effect.Success<typeof makeComposioClientLive>;
2066
2179 - if (invalidSlugs.length > 0) {
2180 - return yield* Effect.fail(
2181 - new InvalidToolkitsError({
2182 - invalidToolkits: invalidSlugs,
2183 - availableToolkits: availableSlugs,
2184 - })
2185 - );
2186 - }
2067 +export class ComposioClientLive extends Context.Tag('services/ComposioClientLive')<
2068 + ComposioClientLive,
2069 + ComposioClientLiveShape
2070 +>() {
2071 + static readonly Default = Layer.effect(ComposioClientLive, makeComposioClientLive).pipe(
2072 + Layer.provide(ComposioClientSingleton.Default)
2073 + );
2074 +}
2075
2188 - return normalizedInputSlugs;
2189 - }),
2190 - /**
2191 - * Filters the given list of toolkits to only include those with the specified slugs.
2192 - * @param toolkits - Array of toolkits to filter
2193 - * @param toolkitSlugs - Array of toolkit slugs to filter by (case-insensitive)
2194 - */
2195 - filterToolkitsBySlugs: (
2196 - toolkits: ReadonlyArray<Toolkit>,
2197 - toolkitSlugs: ReadonlyArray<string>
2198 - ): ReadonlyArray<Toolkit> => {
2199 - const normalizedSlugs = new Set(toolkitSlugs.map(slug => String.toLowerCase(slug)));
2200 - return toolkits.filter(toolkit => normalizedSlugs.has(String.toLowerCase(toolkit.slug)));
2201 - },
2202 - /**
2203 - * Validates that the requested toolkit versions exist in the API's available_versions.
2204 - * Makes parallel API calls to fetch toolkit metadata for validation.
2205 - *
2206 - * @param overrides - Map of toolkit slug to requested version
2207 - * @param relevantToolkits - Optional array of toolkit slugs to validate (if --toolkits filter is used)
2208 - * @returns Effect that succeeds with the validated overrides and warnings, or fails with InvalidToolkitVersionsError
2209 - */
2210 - validateToolkitVersions: (
2211 - overrides: ToolkitVersionOverrides,
2212 - relevantToolkits?: ReadonlyArray<string>
2213 - ): Effect.Effect<
2214 - {
2215 - validatedOverrides: ToolkitVersionOverrides;
2216 - warnings: ReadonlyArray<string>;
2217 - },
2218 - InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementException
2219 - > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),
2220 - /**
2221 - * Searches toolkits with optional filters. Returns a single page of results.
2222 - * @param params - Search/filter parameters
2223 - */
2224 - searchToolkits: (params: {
2225 - search?: string;
2226 - category?: string;
2227 - limit?: number;
2228 - cursor?: string;
2229 - }) => client.toolkits.search(params),
2230 - /**
2231 - * Retrieves detailed toolkit info including auth_config_details.
2232 - * @param slug - Toolkit slug
2233 - */
2234 - getToolkitDetailed: (slug: string) => client.toolkits.retrieveDetailed(slug),
2235 - /**
2236 - * Searches tools with optional filters. Returns a single page of results.
2237 - * @param params - Search/filter parameters
2238 - */
2239 - searchTools: (params: {
2240 - search?: string;
2241 - toolkit_slug?: string;
2242 - tags?: string;
2243 - limit?: number;
2244 - cursor?: string;
2245 - }) => client.tools.search(params),
2246 - /**
2247 - * Retrieves detailed info about a single tool by slug.
2248 - * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
2249 - */
2250 - getToolDetailed: (slug: string) => client.tools.retrieve(slug),
2251 - /**
2252 - * Lists auth configs with optional filters. Returns a single page of results.
2253 - * @param params - Search/filter parameters
2254 - */
2255 - listAuthConfigs: (params: {
2256 - search?: string;
2257 - toolkit_slug?: string;
2258 - limit?: number;
2259 - show_disabled?: boolean;
2260 - }) => client.authConfigs.list(params),
2261 - /**
2262 - * Retrieves detailed info about a single auth config by its nanoid.
2263 - * @param nanoid - Auth config ID
2264 - */
2265 - getAuthConfig: (nanoid: string) => client.authConfigs.retrieve(nanoid),
2266 - /**
2267 - * Creates a new auth config for a toolkit.
2268 - * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
2269 - */
2270 - createAuthConfig: (params: AuthConfigCreateParams) => client.authConfigs.create(params),
2271 - deleteAuthConfig: (nanoid: string) => client.authConfigs.delete(nanoid),
2272 - // Connected account operations (thin wrappers — see buildConnectedAccountsNamespace)
2273 - listConnectedAccounts: (params: {
2274 - toolkit_slugs?: string[];
2275 - user_ids?: string[];
2276 - statuses?: string[];
2277 - limit?: number;
2278 - }) => client.connectedAccounts.list(params),
2279 - getConnectedAccount: (nanoid: string) => client.connectedAccounts.retrieve(nanoid),
2280 - deleteConnectedAccount: (nanoid: string) => client.connectedAccounts.delete(nanoid),
2281 - createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
2282 - client.connectedAccounts.createLink(params),
2283 - ...buildTriggerInstanceRepositoryOperations(client),
2284 - };
2285 - }),
2286 - dependencies: [ComposioClientLive.Default],
2287 - }
2288 -) {}
2076 +const makeComposioToolkitsRepository = Effect.gen(function* () {
2077 + const client = yield* ComposioClientLive;
2078
2290 -export class ComposioSessionRepository extends Effect.Service<ComposioSessionRepository>()(
2291 - 'services/ComposioSessionRepository',
2292 - {
2293 - effect: Effect.gen(function* () {
2294 - const client = yield* ComposioClientLive;
2079 + const getToolkits = () =>
2080 + client.toolkits.list().pipe(
2081 + Effect.map(response => response.items),
2082 + Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)
2083 + );
2084
2296 - return {
2297 - createSession: (params?: { scope?: 'user' | 'project' }) =>
2298 - client.cli.createSession(params),
2299 - getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
2300 - getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
2301 - authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2302 - client.cli.authRealtimeChannel(params),
2303 - };
2304 - }),
2305 - dependencies: [ComposioClientLive.Default],
2306 - }
2307 -) {}
2085 + /**
2086 + * Fetches specific toolkits by their slugs.
2087 + * Makes parallel API calls to retrieve each toolkit.
2088 + * @param slugs - Array of toolkit slugs to fetch
2089 + */
2090 + const getToolkitsBySlugs = (slugs: ReadonlyArray<string>) =>
2091 + Effect.all(
2092 + slugs.map(slug =>
2093 + client.toolkits.retrieve(slug).pipe(
2094 + // Only convert 404 errors to InvalidToolkitsError.
2095 + // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.
2096 + Effect.catchTag('services/HttpServerError', e =>
2097 + Effect.if(e.status === 404, {
2098 + onTrue: () =>
2099 + Effect.fail(
2100 + new InvalidToolkitsError({
2101 + invalidToolkits: [slug],
2102 + availableToolkits: [],
2103 + })
2104 + ),
2105 + onFalse: () => Effect.fail(e),
2106 + })
2107 + )
2108 + )
2109 + ),
2110 + { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
2111 + ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));
2112 +
2113 + return {
2114 + getToolkits,
2115 + getToolkitsBySlugs,
2116 + getMetrics: () => client.getMetrics(),
2117 + getToolsAsEnums: () => client.tools.retrieveEnum(),
2118 + /**
2119 + * Fetches tools with optional toolkit filtering.
2120 + * When toolkitSlugs is provided, fetches all matching tools.
2121 + * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2122 + */
2123 + getTools: (toolkitSlugs?: ReadonlyArray<string>) =>
2124 + client.tools.list(toolkitSlugs ?? []).pipe(
2125 + Effect.map(response => response.items),
2126 + Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2127 + ),
2128 + /**
2129 + * Fetches tools with per-toolkit version support.
2130 + * Groups toolkits by version and makes separate API calls for each group.
2131 + * @param specs - Array of { toolkitSlug, toolkitVersion } specifications
2132 + */
2133 + getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
2134 + client.tools.listByVersionSpecs(specs).pipe(
2135 + Effect.map(response => response.items),
2136 + Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2137 + ),
2138 + getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),
2139 + /**
2140 + * Retrieves detailed info about a single trigger type by slug.
2141 + * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
2142 + */
2143 + getTriggerTypeDetailed: (slug: string) => client.triggersTypes.retrieve(slug),
2144 + /**
2145 + * Fetches trigger types with optional toolkit filtering.
2146 + * When toolkitSlugs is provided, fetches all matching trigger types.
2147 + * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2148 + */
2149 + getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
2150 + client.triggersTypes.list(toolkitSlugs).pipe(
2151 + Effect.map(response => response.items),
2152 + Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)
2153 + ),
2154 + /**
2155 + * Validates that the given toolkit slugs are valid by comparing them against the list
2156 + * of available toolkits. Returns the list of valid toolkit slugs (normalized to lowercase).
2157 + * @param toolkitSlugs - Array of toolkit slugs to validate (case-insensitive)
2158 + */
2159 + validateToolkits: (
2160 + toolkitSlugs: ReadonlyArray<string>
2161 + ): Effect.Effect<
2162 + ReadonlyArray<string>,
2163 + InvalidToolkitsError | HttpError | NoSuchElementException
2164 + > =>
2165 + Effect.gen(function* () {
2166 + // Normalize input slugs to lowercase for comparison
2167 + const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));
2168 +
2169 + // Fetch all available toolkits
2170 + const allToolkits = yield* getToolkits();
2171 + const availableSlugs = allToolkits.map(toolkit => String.toLowerCase(toolkit.slug));
2172 +
2173 + // Find invalid slugs
2174 + const invalidSlugs = normalizedInputSlugs.filter(slug => !availableSlugs.includes(slug));
2175 +
2176 + if (invalidSlugs.length > 0) {
2177 + return yield* Effect.fail(
2178 + new InvalidToolkitsError({
2179 + invalidToolkits: invalidSlugs,
2180 + availableToolkits: availableSlugs,
2181 + })
2182 + );
2183 + }
2184 +
2185 + return normalizedInputSlugs;
2186 + }),
2187 + /**
2188 + * Filters the given list of toolkits to only include those with the specified slugs.
2189 + * @param toolkits - Array of toolkits to filter
2190 + * @param toolkitSlugs - Array of toolkit slugs to filter by (case-insensitive)
2191 + */
2192 + filterToolkitsBySlugs: (
2193 + toolkits: ReadonlyArray<Toolkit>,
2194 + toolkitSlugs: ReadonlyArray<string>
2195 + ): ReadonlyArray<Toolkit> => {
2196 + const normalizedSlugs = new Set(toolkitSlugs.map(slug => String.toLowerCase(slug)));
2197 + return toolkits.filter(toolkit => normalizedSlugs.has(String.toLowerCase(toolkit.slug)));
2198 + },
2199 + /**
2200 + * Validates that the requested toolkit versions exist in the API's available_versions.
2201 + * Makes parallel API calls to fetch toolkit metadata for validation.
2202 + *
2203 + * @param overrides - Map of toolkit slug to requested version
2204 + * @param relevantToolkits - Optional array of toolkit slugs to validate (if --toolkits filter is used)
2205 + * @returns Effect that succeeds with the validated overrides and warnings, or fails with InvalidToolkitVersionsError
2206 + */
2207 + validateToolkitVersions: (
2208 + overrides: ToolkitVersionOverrides,
2209 + relevantToolkits?: ReadonlyArray<string>
2210 + ): Effect.Effect<
2211 + {
2212 + validatedOverrides: ToolkitVersionOverrides;
2213 + warnings: ReadonlyArray<string>;
2214 + },
2215 + InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementException
2216 + > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),
2217 + /**
2218 + * Searches toolkits with optional filters. Returns a single page of results.
2219 + * @param params - Search/filter parameters
2220 + */
2221 + searchToolkits: (params: {
2222 + search?: string;
2223 + category?: string;
2224 + limit?: number;
2225 + cursor?: string;
2226 + }) => client.toolkits.search(params),
2227 + /**
2228 + * Retrieves detailed toolkit info including auth_config_details.
2229 + * @param slug - Toolkit slug
2230 + */
2231 + getToolkitDetailed: (slug: string) => client.toolkits.retrieveDetailed(slug),
2232 + /**
2233 + * Searches tools with optional filters. Returns a single page of results.
2234 + * @param params - Search/filter parameters
2235 + */
2236 + searchTools: (params: {
2237 + search?: string;
2238 + toolkit_slug?: string;
2239 + tags?: string;
2240 + limit?: number;
2241 + cursor?: string;
2242 + }) => client.tools.search(params),
2243 + /**
2244 + * Retrieves detailed info about a single tool by slug.
2245 + * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
2246 + */
2247 + getToolDetailed: (slug: string) => client.tools.retrieve(slug),
2248 + /**
2249 + * Lists auth configs with optional filters. Returns a single page of results.
2250 + * @param params - Search/filter parameters
2251 + */
2252 + listAuthConfigs: (params: {
2253 + search?: string;
2254 + toolkit_slug?: string;
2255 + limit?: number;
2256 + show_disabled?: boolean;
2257 + }) => client.authConfigs.list(params),
2258 + /**
2259 + * Retrieves detailed info about a single auth config by its nanoid.
2260 + * @param nanoid - Auth config ID
2261 + */
2262 + getAuthConfig: (nanoid: string) => client.authConfigs.retrieve(nanoid),
2263 + /**
2264 + * Creates a new auth config for a toolkit.
2265 + * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
2266 + */
2267 + createAuthConfig: (params: AuthConfigCreateParams) => client.authConfigs.create(params),
2268 + deleteAuthConfig: (nanoid: string) => client.authConfigs.delete(nanoid),
2269 + // Connected account operations (thin wrappers — see buildConnectedAccountsNamespace)
2270 + listConnectedAccounts: (params: {
2271 + toolkit_slugs?: string[];
2272 + user_ids?: string[];
2273 + statuses?: string[];
2274 + limit?: number;
2275 + }) => client.connectedAccounts.list(params),
2276 + getConnectedAccount: (nanoid: string) => client.connectedAccounts.retrieve(nanoid),
2277 + deleteConnectedAccount: (nanoid: string) => client.connectedAccounts.delete(nanoid),
2278 + createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
2279 + client.connectedAccounts.createLink(params),
2280 + ...buildTriggerInstanceRepositoryOperations(client),
2281 + };
2282 +});
2283 +
2284 +export type ComposioToolkitsRepositoryShape = Effect.Effect.Success<
2285 + typeof makeComposioToolkitsRepository
2286 +>;
2287 +
2288 +export class ComposioToolkitsRepository extends Context.Tag('services/ComposioToolkitsRepository')<
2289 + ComposioToolkitsRepository,
2290 + ComposioToolkitsRepositoryShape
2291 +>() {
2292 + static readonly Default = Layer.effect(
2293 + ComposioToolkitsRepository,
2294 + makeComposioToolkitsRepository
2295 + ).pipe(Layer.provide(ComposioClientLive.Default));
2296 +}
2297 +
2298 +const makeComposioSessionRepository = Effect.gen(function* () {
2299 + const client = yield* ComposioClientLive;
2300 +
2301 + return {
2302 + createSession: (params?: { scope?: 'user' | 'project' }) => client.cli.createSession(params),
2303 + getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
2304 + getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
2305 + authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2306 + client.cli.authRealtimeChannel(params),
2307 + };
2308 +});
2309 +
2310 +export type ComposioSessionRepositoryShape = Effect.Effect.Success<
2311 + typeof makeComposioSessionRepository
2312 +>;
2313 +
2314 +export class ComposioSessionRepository extends Context.Tag('services/ComposioSessionRepository')<
2315 + ComposioSessionRepository,
2316 + ComposioSessionRepositoryShape
2317 +>() {
2318 + static readonly Default = Layer.effect(
2319 + ComposioSessionRepository,
2320 + makeComposioSessionRepository
2321 + ).pipe(Layer.provide(ComposioClientLive.Default));
2322 +}
ts/packages/cli/src/services/js-package-manager-detector.ts
+130 -125
@@ -1,5 +1,5 @@
1 import { BunFileSystem } from '@effect/platform-bun';
2 -import { Data, Effect, Option, Schema, pipe } from 'effect';
2 +import { Data, Effect, Option, Schema, pipe, Context, Layer } from 'effect';
3 import { FileSystem, Path } from '@effect/platform';
4
5 const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));
@@ -27,130 +27,135 @@ const LOCK_FILES: Record<PackageManager, string> = {
27 const PM_PREFERENCE: PackageManager[] = ['pnpm', 'bun', 'yarn', 'npm'];
28
29 // Service that attempts to detect the package manager of the project in the current working directory.
30 -export class JsPackageManagerDetector extends Effect.Service<JsPackageManagerDetector>()(
31 - 'services/JsPackageManagerDetector',
32 - {
33 - accessors: true,
34 - effect: Effect.gen(function* () {
35 - yield* Effect.logDebug('[JsPackageManagerDetector] Identifying JS package manager...');
36 -
37 - const fs = yield* FileSystem.FileSystem;
38 - const path = yield* Path.Path;
39 -
40 - const parsePackageManager = (pm: string): Option.Option<PackageManager> => {
41 - if (pm.startsWith('pnpm@')) return Option.some('pnpm');
42 - if (pm.startsWith('bun@')) return Option.some('bun');
43 - if (pm.startsWith('yarn@')) return Option.some('yarn');
44 - if (pm.startsWith('npm@')) return Option.some('npm');
30 +const makeJsPackageManagerDetector = Effect.gen(function* () {
31 + yield* Effect.logDebug('[JsPackageManagerDetector] Identifying JS package manager...');
32 +
33 + const fs = yield* FileSystem.FileSystem;
34 + const path = yield* Path.Path;
35 +
36 + const parsePackageManager = (pm: string): Option.Option<PackageManager> => {
37 + if (pm.startsWith('pnpm@')) return Option.some('pnpm');
38 + if (pm.startsWith('bun@')) return Option.some('bun');
39 + if (pm.startsWith('yarn@')) return Option.some('yarn');
40 + if (pm.startsWith('npm@')) return Option.some('npm');
41 + return Option.none();
42 + };
43 +
44 + const PackageJsonSchema = Schema.Struct({
45 + packageManager: Schema.optional(Schema.String),
46 + }).annotations({ identifier: 'package.json' });
47 +
48 + const detectFromPackageJson = (
49 + cwd: string
50 + ): Effect.Effect<Option.Option<PackageManager>, JsPackageManagerError> =>
51 + Effect.gen(function* () {
52 + const contentEffect = pipe(
53 + fs.readFileString(path.join(cwd, 'package.json')),
54 + Effect.catchTag('SystemError', e =>
55 + Effect.fail(
56 + new JsPackageManagerError({ cause: e, message: 'Failed to read package.json' })
57 + )
58 + )
59 + );
60 +
61 + const content = yield* Effect.option(contentEffect);
62 +
63 + if (Option.isNone(content)) {
64 return Option.none();
46 - };
47 -
48 - const PackageJsonSchema = Schema.Struct({
49 - packageManager: Schema.optional(Schema.String),
50 - }).annotations({ identifier: 'package.json' });
51 -
52 - const detectFromPackageJson = (
53 - cwd: string
54 - ): Effect.Effect<Option.Option<PackageManager>, JsPackageManagerError> =>
55 - Effect.gen(function* () {
56 - const contentEffect = pipe(
57 - fs.readFileString(path.join(cwd, 'package.json')),
58 - Effect.catchTag('SystemError', e =>
59 - Effect.fail(
60 - new JsPackageManagerError({ cause: e, message: 'Failed to read package.json' })
61 - )
62 - )
63 - );
64 -
65 - const content = yield* Effect.option(contentEffect);
66 -
67 - if (Option.isNone(content)) {
68 - return Option.none();
69 - }
70 -
71 - const json = yield* Effect.try({
72 - try: () => JSON.parse(content.value) as unknown,
73 - catch: e =>
74 - new JsPackageManagerError({
75 - cause: toError(e),
76 - message: 'Failed to parse package.json',
77 - }),
78 - });
79 -
80 - const decoded = yield* pipe(
81 - Schema.decodeUnknown(PackageJsonSchema)(json),
82 - Effect.mapError(
83 - e =>
84 - new JsPackageManagerError({
85 - cause: toError(e),
86 - message: 'Failed to decode package.json',
87 - })
88 - )
89 - );
90 -
91 - return Option.fromNullable(decoded.packageManager).pipe(
92 - Option.flatMap(parsePackageManager)
93 - );
94 - });
95 -
96 - const detectRecursive = (
97 - cwd: string
98 - ): Effect.Effect<Option.Option<PackageManager>, JsPackageManagerError> =>
99 - Effect.gen(function* () {
100 - const fromPackageJson = yield* detectFromPackageJson(cwd);
101 - if (Option.isSome(fromPackageJson)) {
102 - return fromPackageJson;
103 - }
104 -
105 - const parentDir = path.dirname(cwd);
106 - if (parentDir === cwd) {
107 - return Option.none();
108 - }
109 -
110 - return yield* detectRecursive(parentDir);
111 - });
112 -
113 - const detectJsPackageManager = (
114 - cwd: string
115 - ): Effect.Effect<PackageManager, JsPackageManagerError> =>
116 - Effect.gen(function* () {
117 - const files = yield* pipe(
118 - fs.readDirectory(cwd),
119 - Effect.mapError(
120 - e =>
121 - new JsPackageManagerError({
122 - cause: toError(e),
123 - message: `Failed to read directory ${cwd}`,
124 - })
125 - )
126 - );
127 -
128 - const fileNames = files.map(f => f.toLowerCase());
129 -
130 - for (const pm of PM_PREFERENCE) {
131 - if (fileNames.includes(LOCK_FILES[pm])) {
132 - return pm;
133 - }
134 - }
135 -
136 - const result = yield* detectRecursive(cwd);
137 -
138 - if (Option.isSome(result)) {
139 - return result.value;
140 - }
141 -
142 - return yield* Effect.fail(
65 + }
66 +
67 + const json = yield* Effect.try({
68 + try: () => JSON.parse(content.value) as unknown,
69 + catch: e =>
70 + new JsPackageManagerError({
71 + cause: toError(e),
72 + message: 'Failed to parse package.json',
73 + }),
74 + });
75 +
76 + const decoded = yield* pipe(
77 + Schema.decodeUnknown(PackageJsonSchema)(json),
78 + Effect.mapError(
79 + e =>
80 new JsPackageManagerError({
144 - cause: new Error('Recursive lookup exhausted'),
145 - message: 'Failed to detect package manager',
81 + cause: toError(e),
82 + message: 'Failed to decode package.json',
83 })
147 - );
148 - });
149 -
150 - return {
151 - detectJsPackageManager,
152 - };
153 - }),
154 - dependencies: [BunFileSystem.layer, Path.layer],
155 - }
156 -) {}
84 + )
85 + );
86 +
87 + return Option.fromNullable(decoded.packageManager).pipe(Option.flatMap(parsePackageManager));
88 + });
89 +
90 + const detectRecursive = (
91 + cwd: string
92 + ): Effect.Effect<Option.Option<PackageManager>, JsPackageManagerError> =>
93 + Effect.gen(function* () {
94 + const fromPackageJson = yield* detectFromPackageJson(cwd);
95 + if (Option.isSome(fromPackageJson)) {
96 + return fromPackageJson;
97 + }
98 +
99 + const parentDir = path.dirname(cwd);
100 + if (parentDir === cwd) {
101 + return Option.none();
102 + }
103 +
104 + return yield* detectRecursive(parentDir);
105 + });
106 +
107 + const detectJsPackageManager = (
108 + cwd: string
109 + ): Effect.Effect<PackageManager, JsPackageManagerError> =>
110 + Effect.gen(function* () {
111 + const files = yield* pipe(
112 + fs.readDirectory(cwd),
113 + Effect.mapError(
114 + e =>
115 + new JsPackageManagerError({
116 + cause: toError(e),
117 + message: `Failed to read directory ${cwd}`,
118 + })
119 + )
120 + );
121 +
122 + const fileNames = files.map(f => f.toLowerCase());
123 +
124 + for (const pm of PM_PREFERENCE) {
125 + if (fileNames.includes(LOCK_FILES[pm])) {
126 + return pm;
127 + }
128 + }
129 +
130 + const result = yield* detectRecursive(cwd);
131 +
132 + if (Option.isSome(result)) {
133 + return result.value;
134 + }
135 +
136 + return yield* Effect.fail(
137 + new JsPackageManagerError({
138 + cause: new Error('Recursive lookup exhausted'),
139 + message: 'Failed to detect package manager',
140 + })
141 + );
142 + });
143 +
144 + return {
145 + detectJsPackageManager,
146 + };
147 +});
148 +
149 +export type JsPackageManagerDetectorShape = Effect.Effect.Success<
150 + typeof makeJsPackageManagerDetector
151 +>;
152 +
153 +export class JsPackageManagerDetector extends Context.Tag('services/JsPackageManagerDetector')<
154 + JsPackageManagerDetector,
155 + JsPackageManagerDetectorShape
156 +>() {
157 + static readonly Default = Layer.effect(
158 + JsPackageManagerDetector,
159 + makeJsPackageManagerDetector
160 + ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));
161 +}
ts/packages/cli/src/services/node-os.ts
+13 -7
@@ -1,17 +1,23 @@
1 // eslint-disable-next-line no-restricted-imports -- This Effect service is the sole node:os boundary for CLI source.
2 import os from 'node:os';
3 -import { Effect } from 'effect';
3 +import { Context, Layer } from 'effect';
4 +
5 +export interface NodeOsShape {
6 + readonly homedir: string;
7 + readonly tmpdir: string;
8 + readonly platform: NodeJS.Platform;
9 + readonly arch: string;
10 +}
11
12 // Injectable operating-system details for testing purposes.
6 -export class NodeOs extends Effect.Service<NodeOs>()('services/NodeOs', {
7 - sync: () => ({
13 +export class NodeOs extends Context.Tag('services/NodeOs')<NodeOs, NodeOsShape>() {
14 + static readonly Default: Layer.Layer<NodeOs> = Layer.sync(NodeOs, () => ({
15 homedir: os.homedir(),
16 tmpdir: os.tmpdir(),
17 platform: os.platform(),
18 arch: os.arch(),
12 - }),
13 - dependencies: [],
14 -}) {}
19 + }));
20 +}
21
22 export const defaultNodeOs = ({
23 homedir,
@@ -19,4 +25,4 @@ export const defaultNodeOs = ({
25 }: {
26 homedir: string;
27 tmpdir?: string;
22 -}) => new NodeOs({ homedir, tmpdir, platform: os.platform(), arch: os.arch() });
28 +}): NodeOsShape => NodeOs.of({ homedir, tmpdir, platform: os.platform(), arch: os.arch() });
ts/packages/cli/src/services/node-process.ts
+16 -7
@@ -1,13 +1,22 @@
1 import process from 'node:process';
2 -import { Effect } from 'effect';
2 +import { Context, Layer } from 'effect';
3
4 -// Service to that wraps `node:process`, for testing purposes.
5 -export class NodeProcess extends Effect.Service<NodeProcess>()('services/NodeProcess', {
6 - sync: () => ({
4 +export interface NodeProcessShape {
5 + readonly cwd: string;
6 + readonly execPath: string;
7 + readonly platform: NodeJS.Platform;
8 + readonly arch: string;
9 +}
10 +
11 +// Service that wraps `node:process`, for testing purposes.
12 +export class NodeProcess extends Context.Tag('services/NodeProcess')<
13 + NodeProcess,
14 + NodeProcessShape
15 +>() {
16 + static readonly Default: Layer.Layer<NodeProcess> = Layer.sync(NodeProcess, () => ({
17 cwd: process.cwd(),
18 execPath: process.execPath,
19 platform: process.platform,
20 arch: process.arch,
11 - }),
12 - dependencies: [],
13 -}) {}
21 + }));
22 +}
ts/packages/cli/src/services/project-context.ts
+99 -91
@@ -1,4 +1,4 @@
1 -import { Effect, Option } from 'effect';
1 +import { Effect, Option, Context, Layer } from 'effect';
2 import { FileSystem, Path } from '@effect/platform';
3 import { NodeOs } from 'src/services/node-os';
4 import { NodeProcess } from 'src/services/node-process';
@@ -50,103 +50,111 @@ const parseEnvFile = (content: string): Map<string, string> => {
50 * 2. Per-directory .composio/.env (only allowed keys)
51 * 3. Per-directory .composio/project.json (walk up from CWD, stop at homedir)
52 */
53 -export class ProjectContext extends Effect.Service<ProjectContext>()('services/ProjectContext', {
54 - effect: Effect.gen(function* () {
55 - const fs = yield* FileSystem.FileSystem;
56 - const path = yield* Path.Path;
57 - const proc = yield* NodeProcess;
58 - const os = yield* NodeOs;
53 +const makeProjectContext = Effect.gen(function* () {
54 + const fs = yield* FileSystem.FileSystem;
55 + const path = yield* Path.Path;
56 + const proc = yield* NodeProcess;
57 + const os = yield* NodeOs;
58
60 - return {
61 - /**
62 - * Resolves the current org+project context.
63 - * Returns Option.none() if no context is configured.
64 - */
65 - resolve: Effect.gen(function* () {
66 - // 1. Check env vars (highest priority)
67 - const envOrgId = yield* APP_CONFIG.ORG_ID;
68 - const envProjectId = yield* APP_CONFIG.PROJECT_ID;
69 - if (Option.isSome(envOrgId) && Option.isSome(envProjectId)) {
70 - yield* Effect.logDebug('ProjectContext: resolved from env vars');
71 - return Option.some<ProjectKeys>({
72 - orgId: envOrgId.value,
73 - projectId: envProjectId.value,
74 - projectName: Option.none(),
75 - orgName: Option.none(),
76 - email: Option.none(),
77 - testUserId: Option.none(),
78 - });
79 - }
59 + return {
60 + /**
61 + * Resolves the current org+project context.
62 + * Returns Option.none() if no context is configured.
63 + */
64 + resolve: Effect.gen(function* () {
65 + // 1. Check env vars (highest priority)
66 + const envOrgId = yield* APP_CONFIG.ORG_ID;
67 + const envProjectId = yield* APP_CONFIG.PROJECT_ID;
68 + if (Option.isSome(envOrgId) && Option.isSome(envProjectId)) {
69 + yield* Effect.logDebug('ProjectContext: resolved from env vars');
70 + return Option.some<ProjectKeys>({
71 + orgId: envOrgId.value,
72 + projectId: envProjectId.value,
73 + projectName: Option.none(),
74 + orgName: Option.none(),
75 + email: Option.none(),
76 + testUserId: Option.none(),
77 + });
78 + }
79
81 - // 2. Walk up from CWD, stop at homedir (not filesystem root)
82 - const stopAt = os.homedir;
80 + // 2. Walk up from CWD, stop at homedir (not filesystem root)
81 + const stopAt = os.homedir;
82
84 - for (const dir of yield* getAncestors(proc.cwd)) {
85 - const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);
83 + for (const dir of yield* getAncestors(proc.cwd)) {
84 + const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);
85
87 - // 2a. Check .composio/.env
88 - const envFilePath = path.join(composioDir, constants.PROJECT_ENV_FILE_NAME);
89 - const envExists = yield* fs
90 - .exists(envFilePath)
91 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
92 - if (envExists) {
93 - const envContent = yield* fs
94 - .readFileString(envFilePath)
95 - .pipe(Effect.catchAll(() => Effect.succeed('')));
96 - const envMap = parseEnvFile(envContent);
97 - const envFileOrgId = envMap.get('COMPOSIO_ORG_ID');
98 - const envFileProjectId = envMap.get('COMPOSIO_PROJECT_ID');
99 - if (envFileOrgId && envFileProjectId) {
100 - yield* Effect.logDebug(`ProjectContext: resolved from ${envFilePath}`);
101 - return Option.some<ProjectKeys>({
102 - orgId: envFileOrgId,
103 - projectId: envFileProjectId,
104 - projectName: Option.none(),
105 - orgName: Option.none(),
106 - email: Option.none(),
107 - testUserId: Option.none(),
108 - });
109 - }
86 + // 2a. Check .composio/.env
87 + const envFilePath = path.join(composioDir, constants.PROJECT_ENV_FILE_NAME);
88 + const envExists = yield* fs
89 + .exists(envFilePath)
90 + .pipe(Effect.catchAll(() => Effect.succeed(false)));
91 + if (envExists) {
92 + const envContent = yield* fs
93 + .readFileString(envFilePath)
94 + .pipe(Effect.catchAll(() => Effect.succeed('')));
95 + const envMap = parseEnvFile(envContent);
96 + const envFileOrgId = envMap.get('COMPOSIO_ORG_ID');
97 + const envFileProjectId = envMap.get('COMPOSIO_PROJECT_ID');
98 + if (envFileOrgId && envFileProjectId) {
99 + yield* Effect.logDebug(`ProjectContext: resolved from ${envFilePath}`);
100 + return Option.some<ProjectKeys>({
101 + orgId: envFileOrgId,
102 + projectId: envFileProjectId,
103 + projectName: Option.none(),
104 + orgName: Option.none(),
105 + email: Option.none(),
106 + testUserId: Option.none(),
107 + });
108 }
109 + }
110
112 - // 2b. Check .composio/project.json
113 - const projectJsonPath = path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME);
114 - const jsonExists = yield* fs
115 - .exists(projectJsonPath)
116 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
117 - if (jsonExists) {
118 - const content = yield* fs
119 - .readFileString(projectJsonPath)
120 - .pipe(Effect.catchAll(() => Effect.succeed('')));
121 - if (content) {
122 - const keysOpt = yield* projectKeysFromJSON(content).pipe(
123 - Effect.map(Option.some),
124 - Effect.catchAll(error =>
125 - Effect.gen(function* () {
126 - yield* Effect.logDebug(
127 - `ProjectContext: corrupt project.json at ${projectJsonPath}, skipping:`,
128 - error
129 - );
130 - return Option.none();
131 - })
132 - )
133 - );
134 - if (Option.isSome(keysOpt)) {
135 - yield* Effect.logDebug(`ProjectContext: resolved from ${projectJsonPath}`);
136 - return keysOpt;
137 - }
111 + // 2b. Check .composio/project.json
112 + const projectJsonPath = path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME);
113 + const jsonExists = yield* fs
114 + .exists(projectJsonPath)
115 + .pipe(Effect.catchAll(() => Effect.succeed(false)));
116 + if (jsonExists) {
117 + const content = yield* fs
118 + .readFileString(projectJsonPath)
119 + .pipe(Effect.catchAll(() => Effect.succeed('')));
120 + if (content) {
121 + const keysOpt = yield* projectKeysFromJSON(content).pipe(
122 + Effect.map(Option.some),
123 + Effect.catchAll(error =>
124 + Effect.gen(function* () {
125 + yield* Effect.logDebug(
126 + `ProjectContext: corrupt project.json at ${projectJsonPath}, skipping:`,
127 + error
128 + );
129 + return Option.none();
130 + })
131 + )
132 + );
133 + if (Option.isSome(keysOpt)) {
134 + yield* Effect.logDebug(`ProjectContext: resolved from ${projectJsonPath}`);
135 + return keysOpt;
136 }
137 }
140 -
141 - // Stop at homedir to avoid reading from system directories
142 - if (dir === stopAt) break;
138 }
139
145 - // 3. Nothing found
146 - yield* Effect.logDebug('ProjectContext: no context found');
147 - return Option.none<ProjectKeys>();
148 - }).pipe(Effect.provideService(Path.Path, path)),
149 - };
150 - }),
151 - dependencies: [Path.layer],
152 -}) {}
140 + // Stop at homedir to avoid reading from system directories
141 + if (dir === stopAt) break;
142 + }
143 +
144 + // 3. Nothing found
145 + yield* Effect.logDebug('ProjectContext: no context found');
146 + return Option.none<ProjectKeys>();
147 + }).pipe(Effect.provideService(Path.Path, path)),
148 + };
149 +});
150 +
151 +export type ProjectContextShape = Effect.Effect.Success<typeof makeProjectContext>;
152 +
153 +export class ProjectContext extends Context.Tag('services/ProjectContext')<
154 + ProjectContext,
155 + ProjectContextShape
156 +>() {
157 + static readonly Default = Layer.effect(ProjectContext, makeProjectContext).pipe(
158 + Layer.provide(Path.layer)
159 + );
160 +}
ts/packages/cli/src/services/project-environment-detector.ts
+52 -44
@@ -1,6 +1,6 @@
1 import { BunFileSystem } from '@effect/platform-bun';
2 import { FileSystem, Path } from '@effect/platform';
3 -import { Data, Effect, Match } from 'effect';
3 +import { Data, Effect, Match, Context, Layer } from 'effect';
4 import { getAncestors } from 'src/utils/get-ancestors';
5 import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
6 import { loadHostConfig } from 'src/services/config';
@@ -551,48 +551,56 @@ const detectPythonPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
551 // Service
552 // ---------------------------------------------------------------------------
553
554 -export class ProjectEnvironmentDetector extends Effect.Service<ProjectEnvironmentDetector>()(
555 - 'services/ProjectEnvironmentDetector',
556 - {
557 - effect: Effect.gen(function* () {
558 - const fs = yield* FileSystem.FileSystem;
559 - const path = yield* Path.Path;
560 -
561 - const detectProjectEnvironment = (
562 - cwd: string
563 - ): Effect.Effect<ProjectEnvironment, ProjectEnvironmentDetectorError> =>
564 - Effect.gen(function* () {
565 - const detection = yield* detectLanguage(fs, cwd);
566 -
567 - if (detection.language === 'python') {
568 - const packageManager = yield* detectPythonPackageManager(fs, detection.rootDir);
569 - return {
570 - kind: 'python',
571 - language: 'python',
572 - packageManager,
573 - rootDir: detection.rootDir,
574 - evidence: detection.evidence.evidence,
575 - } satisfies ProjectEnvironment;
576 - }
577 -
578 - const packageManager = yield* detectJsPackageManager(fs, detection.rootDir);
579 - return {
580 - kind: 'js',
581 - language: detection.language,
582 - packageManager,
583 - rootDir: detection.rootDir,
584 - evidence: detection.evidence.evidence,
585 - } satisfies ProjectEnvironment;
586 - }).pipe(Effect.provideService(Path.Path, path));
554 +const makeProjectEnvironmentDetector = Effect.gen(function* () {
555 + const fs = yield* FileSystem.FileSystem;
556 + const path = yield* Path.Path;
557
558 + const detectProjectEnvironment = (
559 + cwd: string
560 + ): Effect.Effect<ProjectEnvironment, ProjectEnvironmentDetectorError> =>
561 + Effect.gen(function* () {
562 + const detection = yield* detectLanguage(fs, cwd);
563 +
564 + if (detection.language === 'python') {
565 + const packageManager = yield* detectPythonPackageManager(fs, detection.rootDir);
566 + return {
567 + kind: 'python',
568 + language: 'python',
569 + packageManager,
570 + rootDir: detection.rootDir,
571 + evidence: detection.evidence.evidence,
572 + } satisfies ProjectEnvironment;
573 + }
574 +
575 + const packageManager = yield* detectJsPackageManager(fs, detection.rootDir);
576 return {
589 - detectProjectEnvironment,
590 - detectJsPackageManager: (cwd: string) =>
591 - detectJsPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),
592 - detectPythonPackageManager: (cwd: string) =>
593 - detectPythonPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),
594 - };
595 - }),
596 - dependencies: [BunFileSystem.layer, Path.layer],
597 - }
598 -) {}
577 + kind: 'js',
578 + language: detection.language,
579 + packageManager,
580 + rootDir: detection.rootDir,
581 + evidence: detection.evidence.evidence,
582 + } satisfies ProjectEnvironment;
583 + }).pipe(Effect.provideService(Path.Path, path));
584 +
585 + return {
586 + detectProjectEnvironment,
587 + detectJsPackageManager: (cwd: string) =>
588 + detectJsPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),
589 + detectPythonPackageManager: (cwd: string) =>
590 + detectPythonPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),
591 + };
592 +});
593 +
594 +export type ProjectEnvironmentDetectorShape = Effect.Effect.Success<
595 + typeof makeProjectEnvironmentDetector
596 +>;
597 +
598 +export class ProjectEnvironmentDetector extends Context.Tag('services/ProjectEnvironmentDetector')<
599 + ProjectEnvironmentDetector,
600 + ProjectEnvironmentDetectorShape
601 +>() {
602 + static readonly Default = Layer.effect(
603 + ProjectEnvironmentDetector,
604 + makeProjectEnvironmentDetector
605 + ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));
606 +}
ts/packages/cli/src/services/setup-skill-installer.ts
+38 -35
@@ -1,5 +1,5 @@
1 import { FileSystem, HttpClient, Path } from '@effect/platform';
2 -import { Config, Effect } from 'effect';
2 +import { Config, Effect, Context, Layer } from 'effect';
3 import {
4 inferSkillReleaseChannel,
5 installSkill,
@@ -117,39 +117,42 @@ export const removeManagedClaudeSkill = (home: string) =>
117 return changed;
118 }).pipe(Effect.uninterruptible);
119
120 -export class SetupSkillInstaller extends Effect.Service<SetupSkillInstaller>()(
121 - 'services/SetupSkillInstaller',
122 - {
123 - effect: Effect.gen(function* () {
124 - const fs = yield* FileSystem.FileSystem;
125 - const path = yield* Path.Path;
126 - const os = yield* NodeOs;
127 - const isCurrent = (releaseTag: string) =>
128 - checkClaudeSkillCurrent(fs, path, os.homedir, releaseTag);
129 - const releaseTag = yield* Effect.cached(
130 - resolveSetupSkillReleaseTag().pipe(
131 - Effect.provideService(FileSystem.FileSystem, fs),
132 - Effect.provideService(Path.Path, path)
133 - )
134 - );
120 +const makeSetupSkillInstaller = Effect.gen(function* () {
121 + const fs = yield* FileSystem.FileSystem;
122 + const path = yield* Path.Path;
123 + const os = yield* NodeOs;
124 + const isCurrent = (releaseTag: string) =>
125 + checkClaudeSkillCurrent(fs, path, os.homedir, releaseTag);
126 + const releaseTag = yield* Effect.cached(
127 + resolveSetupSkillReleaseTag().pipe(
128 + Effect.provideService(FileSystem.FileSystem, fs),
129 + Effect.provideService(Path.Path, path)
130 + )
131 + );
132 +
133 + return {
134 + isClaudeSkillReady: Effect.flatMap(releaseTag, isCurrent),
135 + hasManagedClaudeSkill: hasManagedClaudeSkill(os.homedir),
136 + ensureClaudeSkill: Effect.gen(function* () {
137 + const targetReleaseTag = yield* releaseTag;
138 + if (yield* isCurrent(targetReleaseTag)) return false;
139
136 - return {
137 - isClaudeSkillReady: Effect.flatMap(releaseTag, isCurrent),
138 - hasManagedClaudeSkill: hasManagedClaudeSkill(os.homedir),
139 - ensureClaudeSkill: Effect.gen(function* () {
140 - const targetReleaseTag = yield* releaseTag;
141 - if (yield* isCurrent(targetReleaseTag)) return false;
142 -
143 - yield* installSkill({
144 - target: 'claude',
145 - releaseTag: targetReleaseTag,
146 - silent: true,
147 - });
148 - return true;
149 - }),
150 - removeClaudeSkill: removeManagedClaudeSkill(os.homedir),
151 - };
140 + yield* installSkill({
141 + target: 'claude',
142 + releaseTag: targetReleaseTag,
143 + silent: true,
144 + });
145 + return true;
146 }),
153 - dependencies: [],
154 - }
155 -) {}
147 + removeClaudeSkill: removeManagedClaudeSkill(os.homedir),
148 + };
149 +});
150 +
151 +export type SetupSkillInstallerShape = Effect.Effect.Success<typeof makeSetupSkillInstaller>;
152 +
153 +export class SetupSkillInstaller extends Context.Tag('services/SetupSkillInstaller')<
154 + SetupSkillInstaller,
155 + SetupSkillInstallerShape
156 +>() {
157 + static readonly Default = Layer.effect(SetupSkillInstaller, makeSetupSkillInstaller);
158 +}
ts/packages/cli/src/services/toolkit-slug-catalog.ts
+30 -26
@@ -1,4 +1,4 @@
1 -import { DateTime, Duration, Effect, Option, Ref } from 'effect';
1 +import { DateTime, Duration, Effect, Option, Ref, Context, Layer } from 'effect';
2 import { BAKED_TOOLKIT_SLUGS } from 'src/generated/toolkit-slugs';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import {
@@ -100,28 +100,32 @@ const loadLocalToolkitSlugs = Effect.gen(function* () {
100 * Memoizing also gates the staleness refresh to one fork per run, where an
101 * unmemoized read forked — and rewrote the file — once per resolution.
102 */
103 -export class ToolkitSlugCatalog extends Effect.Service<ToolkitSlugCatalog>()(
104 - 'services/ToolkitSlugCatalog',
105 - {
106 - effect: Effect.gen(function* () {
107 - const local = yield* Effect.cached(loadLocalToolkitSlugs);
108 - const hasRecorded = yield* Ref.make(false);
109 -
110 - /**
111 - * Records slugs learned from a catalog fetch, in the background, at most
112 - * once per run. Every miss in a run merges the same memoized fetch into
113 - * the same local list, so later calls would fork a daemon fiber only to
114 - * rewrite an identical file — and each pending fiber holds the finished
115 - * command open a little longer.
116 - */
117 - const remember = (slugs: ReadonlyArray<string>): Effect.Effect<void> =>
118 - Effect.gen(function* () {
119 - const alreadyRecorded = yield* Ref.getAndSet(hasRecorded, true);
120 - if (alreadyRecorded) return;
121 - yield* Effect.forkDaemon(writeKnownToolkitSlugs(slugs));
122 - });
123 -
124 - return { local, remember };
125 - }),
126 - }
127 -) {}
103 +const makeToolkitSlugCatalog = Effect.gen(function* () {
104 + const local = yield* Effect.cached(loadLocalToolkitSlugs);
105 + const hasRecorded = yield* Ref.make(false);
106 +
107 + /**
108 + * Records slugs learned from a catalog fetch, in the background, at most
109 + * once per run. Every miss in a run merges the same memoized fetch into
110 + * the same local list, so later calls would fork a daemon fiber only to
111 + * rewrite an identical file — and each pending fiber holds the finished
112 + * command open a little longer.
113 + */
114 + const remember = (slugs: ReadonlyArray<string>): Effect.Effect<void> =>
115 + Effect.gen(function* () {
116 + const alreadyRecorded = yield* Ref.getAndSet(hasRecorded, true);
117 + if (alreadyRecorded) return;
118 + yield* Effect.forkDaemon(writeKnownToolkitSlugs(slugs));
119 + });
120 +
121 + return { local, remember };
122 +});
123 +
124 +export type ToolkitSlugCatalogShape = Effect.Effect.Success<typeof makeToolkitSlugCatalog>;
125 +
126 +export class ToolkitSlugCatalog extends Context.Tag('services/ToolkitSlugCatalog')<
127 + ToolkitSlugCatalog,
128 + ToolkitSlugCatalogShape
129 +>() {
130 + static readonly Default = Layer.effect(ToolkitSlugCatalog, makeToolkitSlugCatalog);
131 +}
ts/packages/cli/src/services/triggers-realtime.ts
+241 -229
@@ -1,4 +1,15 @@
1 -import { Array as Arr, Data, Effect, Either, Option, Predicate, Runtime, Schema } from 'effect';
1 +import {
2 + Array as Arr,
3 + Data,
4 + Effect,
5 + Either,
6 + Option,
7 + Predicate,
8 + Runtime,
9 + Schema,
10 + Context,
11 + Layer,
12 +} from 'effect';
13 import { JsonRecordSchema } from 'src/effects/json';
14 import {
15 ComposioClientSingleton,
@@ -76,241 +87,242 @@ export const resolvePusherConstructor = (
87 * - `cli.realtime.credentials` to fetch Pusher credentials + project nano id
88 * - `cli.realtime.auth` for private channel auth callbacks
89 */
79 -export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
80 - 'services/TriggersRealtime',
81 - {
82 - effect: Effect.gen(function* () {
83 - const sessionRepo = yield* ComposioSessionRepository;
84 - const clientSingleton = yield* ComposioClientSingleton;
85 - const runtime = yield* Effect.runtime<never>();
86 -
87 - const listenWith = (params: {
88 - getRealtimeCredentials: () => Effect.Effect<
89 - CliRealtimeCredentialsResponse,
90 - TriggerRealtimeSubscriptionError
91 - >;
92 - authRealtimeChannel: (params: {
93 - channel_name: string;
94 - socket_id: string;
95 - }) => Effect.Effect<CliRealtimeAuthResponse, TriggerRealtimeSubscriptionError>;
96 - onEvent: (data: RawRealtimeEvent) => void;
97 - }) =>
98 - Effect.acquireUseRelease(
99 - Effect.gen(function* () {
100 - const creds = yield* params.getRealtimeCredentials();
101 - const channelName = `private-cli-${creds.project_id}`;
102 -
103 - const pusherModule = yield* Effect.tryPromise({
104 - try: () => import('pusher-js'),
105 - catch: subscriptionError('Failed to load the realtime client'),
106 - });
90 +const makeTriggersRealtime = Effect.gen(function* () {
91 + const sessionRepo = yield* ComposioSessionRepository;
92 + const clientSingleton = yield* ComposioClientSingleton;
93 + const runtime = yield* Effect.runtime<never>();
94 +
95 + const listenWith = (params: {
96 + getRealtimeCredentials: () => Effect.Effect<
97 + CliRealtimeCredentialsResponse,
98 + TriggerRealtimeSubscriptionError
99 + >;
100 + authRealtimeChannel: (params: {
101 + channel_name: string;
102 + socket_id: string;
103 + }) => Effect.Effect<CliRealtimeAuthResponse, TriggerRealtimeSubscriptionError>;
104 + onEvent: (data: RawRealtimeEvent) => void;
105 + }) =>
106 + Effect.acquireUseRelease(
107 + Effect.gen(function* () {
108 + const creds = yield* params.getRealtimeCredentials();
109 + const channelName = `private-cli-${creds.project_id}`;
110 +
111 + const pusherModule = yield* Effect.tryPromise({
112 + try: () => import('pusher-js'),
113 + catch: subscriptionError('Failed to load the realtime client'),
114 + });
115
108 - const Pusher = yield* resolvePusherConstructor(pusherModule).pipe(
109 - Effect.mapError(
110 - subscriptionError('Realtime client module does not expose a constructor')
111 - )
112 - );
116 + const Pusher = yield* resolvePusherConstructor(pusherModule).pipe(
117 + Effect.mapError(subscriptionError('Realtime client module does not expose a constructor'))
118 + );
119
114 - const pusher = yield* Effect.try({
115 - try: () =>
116 - new Pusher(creds.pusher_key, {
117 - cluster: creds.pusher_cluster,
118 - channelAuthorization: {
119 - customHandler: (authOptions, callback) => {
120 - const channel_name = authOptions.channelName;
121 - const socket_id = authOptions.socketId;
122 -
123 - const doAuth = async () => {
124 - const response = await Runtime.runPromise(runtime)(
125 - params.authRealtimeChannel({
126 - channel_name,
127 - socket_id,
128 - })
129 - );
130 - // Pusher private channels verify signatures without channel_data.
131 - // Some auth endpoints may still return channel_data, which can cause
132 - // "Invalid signature" if included in the verification input.
133 - const normalizedResponse = channel_name.startsWith('private-')
134 - ? { auth: response.auth }
135 - : response;
136 - return normalizedResponse;
137 - };
138 -
139 - void doAuth()
140 - .then(data => callback(null, data))
141 - .catch(cause =>
142 - callback(cause instanceof Error ? cause : new Error(String(cause)), null)
143 - );
144 - },
145 - },
146 - }),
147 - catch: subscriptionError('Failed to construct the realtime client'),
148 - });
120 + const pusher = yield* Effect.try({
121 + try: () =>
122 + new Pusher(creds.pusher_key, {
123 + cluster: creds.pusher_cluster,
124 + channelAuthorization: {
125 + customHandler: (authOptions, callback) => {
126 + const channel_name = authOptions.channelName;
127 + const socket_id = authOptions.socketId;
128 +
129 + const doAuth = async () => {
130 + const response = await Runtime.runPromise(runtime)(
131 + params.authRealtimeChannel({
132 + channel_name,
133 + socket_id,
134 + })
135 + );
136 + // Pusher private channels verify signatures without channel_data.
137 + // Some auth endpoints may still return channel_data, which can cause
138 + // "Invalid signature" if included in the verification input.
139 + const normalizedResponse = channel_name.startsWith('private-')
140 + ? { auth: response.auth }
141 + : response;
142 + return normalizedResponse;
143 + };
144 +
145 + void doAuth()
146 + .then(data => callback(null, data))
147 + .catch(cause =>
148 + callback(cause instanceof Error ? cause : new Error(String(cause)), null)
149 + );
150 + },
151 + },
152 + }),
153 + catch: subscriptionError('Failed to construct the realtime client'),
154 + });
155
150 - const channel = pusher.subscribe(channelName);
151 -
152 - // Pusher has a 10 KB per-message limit. When the Composio backend
153 - // produces a trigger payload that exceeds this, it splits the JSON
154 - // into numbered chunks sent as separate `chunked-trigger_to_client`
155 - // events. We reassemble them here by accumulating chunks keyed by
156 - // event id, then joining once the final chunk arrives and every
157 - // intermediate index is present.
158 - //
159 - // Guard-rails:
160 - // - Reject chunk indices outside [0, MAX_CHUNK_INDEX] to prevent a
161 - // single malformed event from allocating a huge sparse array.
162 - // - Evict incomplete entries older than CHUNK_TTL_MS so that lost
163 - // chunks don't leak memory over long-running sessions.
164 - // - Cap the total number of in-flight reassemblies to bound memory
165 - // usage even under pathological input.
166 - const MAX_CHUNK_INDEX = 1_000;
167 - const CHUNK_TTL_MS = 60_000;
168 - const MAX_PENDING_CHUNKS = 100;
169 -
170 - type PendingChunkedEvent = {
171 - chunks: string[];
172 - receivedFinal: boolean;
173 - createdAt: number;
174 - };
175 -
176 - const chunkedEvents = new Map<string, PendingChunkedEvent>();
177 -
178 - // Periodic sweep: drop entries that have been sitting incomplete for
179 - // longer than CHUNK_TTL_MS. Runs every CHUNK_TTL_MS and is cleared
180 - // on shutdown.
181 - const cleanupInterval = setInterval(() => {
182 - const now = Date.now();
183 - for (const [id, entry] of chunkedEvents) {
184 - if (now - entry.createdAt > CHUNK_TTL_MS) {
185 - chunkedEvents.delete(id);
186 - }
187 - }
188 - }, CHUNK_TTL_MS);
189 -
190 - channel.bind('trigger_to_client', (eventData: unknown) => {
191 - params.onEvent(Option.getOrElse(decodeRawRealtimeEvent(eventData), () => ({})));
192 - });
156 + const channel = pusher.subscribe(channelName);
157 +
158 + // Pusher has a 10 KB per-message limit. When the Composio backend
159 + // produces a trigger payload that exceeds this, it splits the JSON
160 + // into numbered chunks sent as separate `chunked-trigger_to_client`
161 + // events. We reassemble them here by accumulating chunks keyed by
162 + // event id, then joining once the final chunk arrives and every
163 + // intermediate index is present.
164 + //
165 + // Guard-rails:
166 + // - Reject chunk indices outside [0, MAX_CHUNK_INDEX] to prevent a
167 + // single malformed event from allocating a huge sparse array.
168 + // - Evict incomplete entries older than CHUNK_TTL_MS so that lost
169 + // chunks don't leak memory over long-running sessions.
170 + // - Cap the total number of in-flight reassemblies to bound memory
171 + // usage even under pathological input.
172 + const MAX_CHUNK_INDEX = 1_000;
173 + const CHUNK_TTL_MS = 60_000;
174 + const MAX_PENDING_CHUNKS = 100;
175 +
176 + type PendingChunkedEvent = {
177 + chunks: string[];
178 + receivedFinal: boolean;
179 + createdAt: number;
180 + };
181 +
182 + const chunkedEvents = new Map<string, PendingChunkedEvent>();
183 +
184 + // Periodic sweep: drop entries that have been sitting incomplete for
185 + // longer than CHUNK_TTL_MS. Runs every CHUNK_TTL_MS and is cleared
186 + // on shutdown.
187 + const cleanupInterval = setInterval(() => {
188 + const now = Date.now();
189 + for (const [id, entry] of chunkedEvents) {
190 + if (now - entry.createdAt > CHUNK_TTL_MS) {
191 + chunkedEvents.delete(id);
192 + }
193 + }
194 + }, CHUNK_TTL_MS);
195 +
196 + channel.bind('trigger_to_client', (eventData: unknown) => {
197 + params.onEvent(Option.getOrElse(decodeRawRealtimeEvent(eventData), () => ({})));
198 + });
199
194 - channel.bind('chunked-trigger_to_client', (data: unknown) => {
195 - const decoded = decodeChunkedRealtimeEvent(data);
196 - if (Option.isNone(decoded)) {
197 - return;
198 - }
199 - const typed = decoded.value;
200 -
201 - // Reject non-integer or out-of-range indices to prevent a single
202 - // malformed event from creating a massive sparse array.
203 - if (
204 - !Number.isInteger(typed.index) ||
205 - typed.index < 0 ||
206 - typed.index > MAX_CHUNK_INDEX
207 - ) {
208 - return;
209 - }
210 -
211 - if (!chunkedEvents.has(typed.id)) {
212 - // If we already have too many in-flight reassemblies, drop the
213 - // oldest one to make room.
214 - if (chunkedEvents.size >= MAX_PENDING_CHUNKS) {
215 - const oldestId = chunkedEvents.keys().next().value;
216 - if (oldestId !== undefined) chunkedEvents.delete(oldestId);
217 - }
218 -
219 - chunkedEvents.set(typed.id, {
220 - chunks: [],
221 - receivedFinal: false,
222 - createdAt: Date.now(),
223 - });
224 - }
225 -
226 - const current = chunkedEvents.get(typed.id);
227 - if (!current) {
228 - return;
229 - }
230 - current.chunks[typed.index] = typed.chunk;
231 - if (typed.final) {
232 - current.receivedFinal = true;
233 - }
234 -
235 - // Completeness check: for a dense array, .length equals the
236 - // number of defined keys. For a sparse array (missing chunks),
237 - // .length is highestIndex + 1 but Object.keys only counts the
238 - // indices that were actually assigned, so the two diverge.
239 - if (
240 - current.receivedFinal &&
241 - current.chunks.length === Object.keys(current.chunks).length
242 - ) {
243 - const reassembled = current.chunks.join('');
244 - chunkedEvents.delete(typed.id);
245 - // Silently discard events that fail to parse after chunk
246 - // reassembly; the buffer entry is already cleared either way.
247 - const parsed = Either.try((): unknown => JSON.parse(reassembled)).pipe(
248 - Either.getRight,
249 - Option.flatMap(decodeRawRealtimeEvent)
250 - );
251 - if (Option.isSome(parsed)) {
252 - params.onEvent(parsed.value);
253 - }
254 - }
200 + channel.bind('chunked-trigger_to_client', (data: unknown) => {
201 + const decoded = decodeChunkedRealtimeEvent(data);
202 + if (Option.isNone(decoded)) {
203 + return;
204 + }
205 + const typed = decoded.value;
206 +
207 + // Reject non-integer or out-of-range indices to prevent a single
208 + // malformed event from creating a massive sparse array.
209 + if (!Number.isInteger(typed.index) || typed.index < 0 || typed.index > MAX_CHUNK_INDEX) {
210 + return;
211 + }
212 +
213 + if (!chunkedEvents.has(typed.id)) {
214 + // If we already have too many in-flight reassemblies, drop the
215 + // oldest one to make room.
216 + if (chunkedEvents.size >= MAX_PENDING_CHUNKS) {
217 + const oldestId = chunkedEvents.keys().next().value;
218 + if (oldestId !== undefined) chunkedEvents.delete(oldestId);
219 + }
220 +
221 + chunkedEvents.set(typed.id, {
222 + chunks: [],
223 + receivedFinal: false,
224 + createdAt: Date.now(),
225 });
226 + }
227 +
228 + const current = chunkedEvents.get(typed.id);
229 + if (!current) {
230 + return;
231 + }
232 + current.chunks[typed.index] = typed.chunk;
233 + if (typed.final) {
234 + current.receivedFinal = true;
235 + }
236 +
237 + // Completeness check: for a dense array, .length equals the
238 + // number of defined keys. For a sparse array (missing chunks),
239 + // .length is highestIndex + 1 but Object.keys only counts the
240 + // indices that were actually assigned, so the two diverge.
241 + if (
242 + current.receivedFinal &&
243 + current.chunks.length === Object.keys(current.chunks).length
244 + ) {
245 + const reassembled = current.chunks.join('');
246 + chunkedEvents.delete(typed.id);
247 + // Silently discard events that fail to parse after chunk
248 + // reassembly; the buffer entry is already cleared either way.
249 + const parsed = Either.try((): unknown => JSON.parse(reassembled)).pipe(
250 + Either.getRight,
251 + Option.flatMap(decodeRawRealtimeEvent)
252 + );
253 + if (Option.isSome(parsed)) {
254 + params.onEvent(parsed.value);
255 + }
256 + }
257 + });
258
257 - return {
258 - shutdown: async () => {
259 - clearInterval(cleanupInterval);
260 - channel.unbind_all?.();
261 - pusher.unsubscribe(channelName);
262 - pusher.disconnect();
263 - },
264 - };
259 + return {
260 + shutdown: async () => {
261 + clearInterval(cleanupInterval);
262 + channel.unbind_all?.();
263 + pusher.unsubscribe(channelName);
264 + pusher.disconnect();
265 + },
266 + };
267 + }),
268 + () => Effect.never,
269 + resource =>
270 + Effect.tryPromise({
271 + try: () => resource.shutdown(),
272 + catch: subscriptionError('Failed to shut down the realtime subscription'),
273 + }).pipe(Effect.catchAll(() => Effect.void))
274 + );
275 +
276 + const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
277 + listenWith({
278 + getRealtimeCredentials: () =>
279 + sessionRepo
280 + .getRealtimeCredentials()
281 + .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),
282 + authRealtimeChannel: params =>
283 + sessionRepo
284 + .authRealtimeChannel(params)
285 + .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),
286 + onEvent,
287 + });
288 +
289 + const listenInProject = (
290 + scope: { orgId: string; projectId: string },
291 + onEvent: (data: RawRealtimeEvent) => void
292 + ) =>
293 + Effect.gen(function* () {
294 + const client = yield* clientSingleton.getFor({
295 + orgId: scope.orgId,
296 + projectId: scope.projectId,
297 + });
298 +
299 + return yield* listenWith({
300 + getRealtimeCredentials: () =>
301 + Effect.tryPromise({
302 + try: () => client.cli.realtime.credentials(),
303 + catch: subscriptionError('Failed to fetch realtime credentials'),
304 }),
266 - () => Effect.never,
267 - resource =>
268 - Effect.tryPromise({
269 - try: () => resource.shutdown(),
270 - catch: subscriptionError('Failed to shut down the realtime subscription'),
271 - }).pipe(Effect.catchAll(() => Effect.void))
272 - );
305 + authRealtimeChannel: params =>
306 + Effect.tryPromise({
307 + try: () => client.cli.realtime.auth(params),
308 + catch: subscriptionError('Failed to authorize the realtime channel'),
309 + }),
310 + onEvent,
311 + });
312 + });
313
274 - const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
275 - listenWith({
276 - getRealtimeCredentials: () =>
277 - sessionRepo
278 - .getRealtimeCredentials()
279 - .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),
280 - authRealtimeChannel: params =>
281 - sessionRepo
282 - .authRealtimeChannel(params)
283 - .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),
284 - onEvent,
285 - });
314 + return { listen, listenInProject };
315 +});
316
287 - const listenInProject = (
288 - scope: { orgId: string; projectId: string },
289 - onEvent: (data: RawRealtimeEvent) => void
290 - ) =>
291 - Effect.gen(function* () {
292 - const client = yield* clientSingleton.getFor({
293 - orgId: scope.orgId,
294 - projectId: scope.projectId,
295 - });
296 -
297 - return yield* listenWith({
298 - getRealtimeCredentials: () =>
299 - Effect.tryPromise({
300 - try: () => client.cli.realtime.credentials(),
301 - catch: subscriptionError('Failed to fetch realtime credentials'),
302 - }),
303 - authRealtimeChannel: params =>
304 - Effect.tryPromise({
305 - try: () => client.cli.realtime.auth(params),
306 - catch: subscriptionError('Failed to authorize the realtime channel'),
307 - }),
308 - onEvent,
309 - });
310 - });
317 +export type TriggersRealtimeShape = Effect.Effect.Success<typeof makeTriggersRealtime>;
318
312 - return { listen, listenInProject };
313 - }),
314 - dependencies: [ComposioSessionRepository.Default, ComposioClientSingleton.Default],
315 - }
316 -) {}
319 +export class TriggersRealtime extends Context.Tag('services/TriggersRealtime')<
320 + TriggersRealtime,
321 + TriggersRealtimeShape
322 +>() {
323 + static readonly Default = Layer.effect(TriggersRealtime, makeTriggersRealtime).pipe(
324 + Layer.provide(
325 + Layer.mergeAll(ComposioSessionRepository.Default, ComposioClientSingleton.Default)
326 + )
327 + );
328 +}
ts/packages/cli/src/services/update-check.ts
+2 -2
@@ -4,7 +4,7 @@ import { Config, Data, Effect, Layer, Option, Predicate, Schema } from 'effect';
4 import semver from 'semver';
5 import { bold, cyanBright, dim } from 'src/ui/colors';
6 import { APP_VERSION, GITHUB_REPO } from '../constants';
7 -import { NodeOs } from './node-os';
7 +import { NodeOs, type NodeOsShape } from './node-os';
8 import { resolveRunningCliVersion } from './run-companion-modules';
9 import { TerminalUI } from './terminal-ui';
10
@@ -84,7 +84,7 @@ const defaultStateFile = Effect.gen(function* () {
84 return path.join(os.homedir, '.composio', 'update-check.json');
85 });
86
87 -function getCurrentBinaryAssetName(os: Pick<NodeOs, 'platform' | 'arch'>): string | undefined {
87 +function getCurrentBinaryAssetName(os: Pick<NodeOsShape, 'platform' | 'arch'>): string | undefined {
88 const { platform } = os;
89 const rawArch: string = os.arch;
90 if (platform !== 'darwin' && platform !== 'linux') return undefined;
ts/packages/cli/src/services/upgrade-binary.ts
+24 -15
@@ -8,6 +8,8 @@ import {
8 Record as EffectRecord,
9 Scope,
10 Stream,
11 + Context,
12 + Layer,
13 } from 'effect';
14 import { HttpClient, HttpClientResponse, FileSystem, Path } from '@effect/platform';
15 import { APP_VERSION } from '../constants';
@@ -725,19 +727,26 @@ const upgrade = (
727 });
728
729 // Service to manage CLI binary upgrades
728 -export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {
729 - accessors: true,
730 - effect: Effect.gen(function* () {
731 - const ctx: UpgradeBinaryContext = {
732 - httpClient: yield* HttpClient.HttpClient,
733 - fs: yield* FileSystem.FileSystem,
734 - path: yield* Path.Path,
735 - githubConfig: yield* GITHUB_CONFIG_ALL,
736 - };
730 +const makeUpgradeBinary = Effect.gen(function* () {
731 + const ctx: UpgradeBinaryContext = {
732 + httpClient: yield* HttpClient.HttpClient,
733 + fs: yield* FileSystem.FileSystem,
734 + path: yield* Path.Path,
735 + githubConfig: yield* GITHUB_CONFIG_ALL,
736 + };
737 +
738 + return {
739 + upgrade: (options: { prerelease?: boolean; tag?: string } = {}) => upgrade(ctx, options),
740 + } as const;
741 +});
742
738 - return {
739 - upgrade: (options: { prerelease?: boolean; tag?: string } = {}) => upgrade(ctx, options),
740 - } as const;
741 - }),
742 - dependencies: [Path.layer],
743 -}) {}
743 +export type UpgradeBinaryShape = Effect.Effect.Success<typeof makeUpgradeBinary>;
744 +
745 +export class UpgradeBinary extends Context.Tag('services/UpgradeBinary')<
746 + UpgradeBinary,
747 + UpgradeBinaryShape
748 +>() {
749 + static readonly Default = Layer.effect(UpgradeBinary, makeUpgradeBinary).pipe(
750 + Layer.provide(Path.layer)
751 + );
752 +}
ts/packages/cli/test/__utils__/services/test-layer.ts
+15 -12
@@ -70,10 +70,13 @@ import type {
70 import { Stdin } from 'src/services/stdin';
71 import { ProjectContext } from 'src/services/project-context';
72 import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
73 -import { CommandRunner } from 'src/services/command-runner';
73 +import { CommandRunner, type CommandRunnerShape } from 'src/services/command-runner';
74 import { TerminalUI } from 'src/services/terminal-ui';
75 import { CommandExecutor } from '@effect/platform';
76 -import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
76 +import {
77 + SetupSkillInstaller,
78 + type SetupSkillInstallerShape,
79 +} from 'src/services/setup-skill-installer';
80
81 export interface TestLiveInput {
82 /**
@@ -213,10 +216,10 @@ export interface TestLiveInput {
216 * When set, the `CommandRunner` service uses the provided mock instance.
217 * When NOT set, uses a default mock that always returns exit code 0.
218 */
216 - commandRunner?: CommandRunner;
219 + commandRunner?: CommandRunnerShape;
220
221 /** Override setup's Claude skill installer. Defaults to an idempotent no-op. */
219 - setupSkillInstaller?: SetupSkillInstaller;
222 + setupSkillInstaller?: SetupSkillInstallerShape;
223
224 /**
225 * Override TerminalUI behavior for tests.
@@ -345,7 +348,7 @@ export const TestLayer = (input?: TestLiveInput) =>
348
349 const ComposioToolkitsRepositoryTest = Layer.succeed(
350 ComposioToolkitsRepository,
348 - new ComposioToolkitsRepository({
351 + ComposioToolkitsRepository.of({
352 getToolkits: () => Effect.succeed(toolkitsData.toolkits),
353 getToolkitsBySlugs: (slugs: ReadonlyArray<string>) => {
354 const normalizedSlugs = new Set(slugs.map(s => String.toLowerCase(s)));
@@ -792,7 +795,7 @@ export const TestLayer = (input?: TestLiveInput) =>
795 const ComposioSessionRepositoryTest = yield* setupComposioSessionRepository();
796 const TriggersRealtimeTest = Layer.succeed(
797 TriggersRealtime,
795 - new TriggersRealtime({
798 + TriggersRealtime.of({
799 listen: onEvent =>
800 Effect.gen(function* () {
801 yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));
@@ -809,7 +812,7 @@ export const TestLayer = (input?: TestLiveInput) =>
812 // Mock operating-system details
813 const NodeOsTest = Layer.succeed(
814 NodeOs,
812 - new NodeOs({
815 + NodeOs.of({
816 homedir: cwd,
817 tmpdir: tempy.rootTemporaryDirectory,
818 arch: 'arm64',
@@ -820,7 +823,7 @@ export const TestLayer = (input?: TestLiveInput) =>
823 // Mock `node:process`
824 const NodeProcessTest = Layer.succeed(
825 NodeProcess,
823 - new NodeProcess({
826 + NodeProcess.of({
827 cwd,
828 execPath: input?.execPath ? path.resolve(cwd, input.execPath) : path.join(cwd, 'composio'),
829 platform: 'darwin',
@@ -1210,7 +1213,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1213
1214 const ComposioClientSingletonTest = Layer.succeed(
1215 ComposioClientSingleton,
1213 - new ComposioClientSingleton({
1216 + ComposioClientSingleton.of({
1217 get: Effect.fn(function* () {
1218 return mockComposioClient;
1219 }),
@@ -1262,7 +1265,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1265 ? Layer.succeed(CommandRunner, input.commandRunner)
1266 : Layer.succeed(
1267 CommandRunner,
1265 - new CommandRunner({
1268 + CommandRunner.of({
1269 run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
1270 capture: () =>
1271 Effect.succeed({
@@ -1281,7 +1284,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1284 const SetupSkillInstallerTest = Layer.succeed(
1285 SetupSkillInstaller,
1286 input?.setupSkillInstaller ??
1284 - new SetupSkillInstaller({
1287 + SetupSkillInstaller.of({
1288 isClaudeSkillReady: Effect.succeed(false),
1289 hasManagedClaudeSkill: Effect.succeed(false),
1290 ensureClaudeSkill: Effect.succeed(false),
@@ -1528,7 +1531,7 @@ function setupComposioSessionRepository() {
1531 email: accountEmail,
1532 };
1533
1531 - const composioSessionRepositoryTest = new ComposioSessionRepository({
1534 + const composioSessionRepositoryTest = ComposioSessionRepository.of({
1535 createSession: () =>
1536 Effect.succeed({
1537 id: sessionId,
ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts
+6 -3
@@ -1,9 +1,12 @@
1 import { Effect, Layer } from 'effect';
2 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
2 +import {
3 + ComposioToolkitsRepository,
4 + type ComposioToolkitsRepositoryShape,
5 +} from 'src/services/composio-clients';
6 import type { Toolkits } from 'src/models/toolkits';
7
8 export type GetToolkitsError = Effect.Effect.Error<
6 - ReturnType<ComposioToolkitsRepository['getToolkits']>
9 + ReturnType<ComposioToolkitsRepositoryShape['getToolkits']>
10 >;
11
12 const notUsed = (method: string) => () => Effect.die(`${method} is not used in this test`);
@@ -57,7 +60,7 @@ export const countingToolkitsRepository = (
60
61 const layer = Layer.succeed(
62 ComposioToolkitsRepository,
60 - new ComposioToolkitsRepository({
63 + ComposioToolkitsRepository.of({
64 ...unusedRepositoryMethods,
65 getToolkits: () =>
66 Effect.suspend(() => {
ts/packages/cli/test/src/commands/login.cmd.test.ts
+1 -1
@@ -496,7 +496,7 @@ describe('CLI: composio login', () => {
496 const now = yield* DateTime.now;
497 const expiresAt = DateTime.add(now, { minutes: 10 });
498 const sessionId = 'poll-session-id';
499 - const sessionRepository = new ComposioSessionRepository({
499 + const sessionRepository = ComposioSessionRepository.of({
500 createSession: () =>
501 Effect.succeed({
502 id: sessionId,
ts/packages/cli/test/src/commands/run.cmd.test.ts
+1 -1
@@ -102,7 +102,7 @@ const RunTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>
102 Layer.merge(
103 TestLive({
104 ...input,
105 - commandRunner: new CommandRunner({
105 + commandRunner: CommandRunner.of({
106 run: command => commandRuns(command),
107 capture: () => Effect.succeed({ exitCode: 0, stdout: '', stderr: '' }),
108 }),
ts/packages/cli/test/src/commands/setup.cmd.test.ts
+6 -6
@@ -77,7 +77,7 @@ const makeRunner = (
77 readonly stderr?: string;
78 }
79 ) =>
80 - new CommandRunner({
80 + CommandRunner.of({
81 run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
82 capture: command => {
83 const result = respond(commandParts(command));
@@ -106,7 +106,7 @@ const makeSkillInstaller = (initiallyReady = false, failInstall = false) => {
106 return changed;
107 });
108 };
109 - return new SetupSkillInstaller({
109 + return SetupSkillInstaller.of({
110 isClaudeSkillReady: Effect.sync(() => ready),
111 hasManagedClaudeSkill: Effect.sync(() => ready),
112 ensureClaudeSkill: ensureClaudeSkill(),
@@ -294,7 +294,7 @@ describe('CLI: composio setup', () => {
294 });
295 let staleSkillRepaired = false;
296 let staleSkillReady = false;
297 - const staleSkillInstaller = new SetupSkillInstaller({
297 + const staleSkillInstaller = SetupSkillInstaller.of({
298 isClaudeSkillReady: Effect.sync(() => staleSkillReady),
299 hasManagedClaudeSkill: Effect.succeed(true),
300 ensureClaudeSkill: Effect.sync(() => {
@@ -694,7 +694,7 @@ describe('CLI: composio setup', () => {
694 layer(
695 TestLive({
696 commandRunner: orphanedClaudeSkill.runner,
697 - setupSkillInstaller: new SetupSkillInstaller({
697 + setupSkillInstaller: SetupSkillInstaller.of({
698 isClaudeSkillReady: Effect.sync(() => managedClaudeSkill),
699 hasManagedClaudeSkill: Effect.sync(() => managedClaudeSkill),
700 ensureClaudeSkill: Effect.succeed(false),
@@ -726,7 +726,7 @@ describe('CLI: composio setup', () => {
726 layer(
727 TestLive({
728 commandRunner: uninstallWithUnmanagedClaudeSkill.runner,
729 - setupSkillInstaller: new SetupSkillInstaller({
729 + setupSkillInstaller: SetupSkillInstaller.of({
730 isClaudeSkillReady: Effect.succeed(true),
731 hasManagedClaudeSkill: Effect.succeed(false),
732 ensureClaudeSkill: Effect.succeed(false),
@@ -1133,7 +1133,7 @@ describe('CLI: composio setup', () => {
1133 );
1134 });
1135
1136 - const hangingRunner = new CommandRunner({
1136 + const hangingRunner = CommandRunner.of({
1137 run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
1138 capture: () => Effect.never,
1139 });
ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts
+2 -2
@@ -83,7 +83,7 @@ const makeFakeHosts = (
83 });
84 };
85
86 - const runner = new CommandRunner({
86 + const runner = CommandRunner.of({
87 run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
88 capture: rawCommand => {
89 const flattened = Command.flatten(rawCommand)[0];
@@ -143,7 +143,7 @@ const makeFakeHosts = (
143
144 const makeSkillInstaller = (initiallyReady = false) => {
145 let ready = initiallyReady;
146 - return new SetupSkillInstaller({
146 + return SetupSkillInstaller.of({
147 isClaudeSkillReady: Effect.sync(() => ready),
148 hasManagedClaudeSkill: Effect.sync(() => ready),
149 ensureClaudeSkill: Effect.sync(() => {
ts/packages/cli/test/src/effects/detect-platform.test.ts
+1 -1
@@ -13,7 +13,7 @@ import { NodeOs } from 'src/services/node-os';
13 const createMockNodeOs = <P extends NodeJS.Platform>(platform: P, arch: string) =>
14 Layer.succeed(
15 NodeOs,
16 - NodeOs.make({
16 + NodeOs.of({
17 homedir: '/mock/home',
18 tmpdir: '/tmp',
19 platform: platform as NodeJS.Platform,
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+4 -4
@@ -87,7 +87,7 @@ describe('ComposioClientSingleton headers', () => {
87 ]);
88
89 return Effect.gen(function* () {
90 - const client = yield* ComposioClientSingleton.get();
90 + const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
91 yield* Effect.promise(() =>
92 client.tools
93 .list({ limit: 1, toolkit_versions: 'latest' })
@@ -134,7 +134,7 @@ describe('ComposioClientSingleton headers', () => {
134 id: 'cli_s_current',
135 expiresAt: '1970-01-01T00:01:00.000Z',
136 });
137 - const client = yield* ComposioClientSingleton.get();
137 + const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
138 yield* Effect.promise(() =>
139 client.tools
140 .list({ limit: 1, toolkit_versions: 'latest' })
@@ -167,7 +167,7 @@ describe('ComposioClientSingleton headers', () => {
167 id: 'cli_s_expired',
168 expiresAt: '1969-12-31T23:59:00.000Z',
169 });
170 - const client = yield* ComposioClientSingleton.get();
170 + const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
171 yield* Effect.promise(() =>
172 client.tools
173 .list({ limit: 1, toolkit_versions: 'latest' })
@@ -194,7 +194,7 @@ describe('ComposioClientSingleton headers', () => {
194 ]);
195
196 return Effect.gen(function* () {
197 - const client = yield* ComposioClientSingleton.get();
197 + const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
198 yield* Effect.promise(() =>
199 client.tools
200 .list({ limit: 1, toolkit_versions: 'latest' })
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+1 -1
@@ -54,7 +54,7 @@ const TerminalUINoop = Layer.succeed(
54
55 const NodeOsTest = Layer.succeed(
56 NodeOs,
57 - new NodeOs({
57 + NodeOs.of({
58 homedir: '/tmp',
59 tmpdir: '/tmp',
60 platform: 'darwin',