Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
refactor(cli): define services with Context.Tag and thread argv explicitly (#4359)
Alberto Schiabelf5ff810f2ec7
diff --git a/ts/packages/cli/AGENTS.md b/ts/packages/cli/AGENTS.mdindex c8e8040dc..25f09a0c6 100644--- a/ts/packages/cli/AGENTS.md+++ b/ts/packages/cli/AGENTS.md@@ -72,6 +72,8 @@ Options use `Options.text()`, `Options.boolean()`, `Options.choice()`, `Options.| `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions || `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |+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.+OS credential storage uses the sibling package `@composio/cli-keyring` (macOS Keychain / Linux Secret Service).### Effects — `src/effects/`diff --git a/ts/packages/cli/src/bin.ts b/ts/packages/cli/src/bin.tsindex ceaa3cae5..e17a38cab 100644--- a/ts/packages/cli/src/bin.ts+++ b/ts/packages/cli/src/bin.ts@@ -7,8 +7,8 @@ import { NodeOs } from 'src/services/node-os';import { TerminalUILive } from 'src/services/terminal-ui';import { stripTelemetryDebugFlag, telemetryDebugModeLayer } from 'src/services/runtime-flags';+// The one `process.argv` read: every later consumer receives this normalized argv explicitly.const bootstrap = stripTelemetryDebugFlag(process.argv);-process.argv = [...bootstrap.argv];const workerLayers = Layer.mergeAll(BunFileSystem.layer,@@ -33,6 +33,6 @@ if (isBackgroundWorkerInvocation(bootstrap.argv)) {);} else {void import('./cli-main').then(({ runCli }) =>- runCli({ telemetryDebug: bootstrap.telemetryDebug })+ runCli({ argv: bootstrap.argv, telemetryDebug: bootstrap.telemetryDebug }));}diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.tsindex d830251a4..90aab8cf5 100644--- a/ts/packages/cli/src/cli-main.ts+++ b/ts/packages/cli/src/cli-main.ts@@ -156,181 +156,187 @@ export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: nonExit(Number(process.exitCode ?? (shouldFail ? 1 : 0)));};-const runWithArgs = (bootstrap: RootCommandBootstrap) =>- Effect.flatMap(runWithConfig, run => run(process.argv, bootstrap)) satisfies Effect.Effect<+const runWithArgs = (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap) =>+ Effect.flatMap(runWithConfig, run => run(argv, bootstrap)) satisfies Effect.Effect<void,unknown,unknown>;-const runWithTelemetry = Effect.gen(function* () {- const ui = yield* TerminalUI;- const terminal = yield* ui.capabilities;+const runWithTelemetry = (argv: ReadonlyArray<string>) =>+ Effect.gen(function* () {+ const ui = yield* TerminalUI;+ const terminal = yield* ui.capabilities;- const version = yield* getVersion;- configureCliAnalyticsReleaseVersion(version);- const baseTelemetryContext = createCliCommandTelemetryContext(- process.argv,- version,- terminal,- yield* cliInvocationContext- );- const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);- const commandTelemetryContext =- executeToolSlug === undefined- ? baseTelemetryContext- : { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };- // `composio run` mints its run id here so the lifecycle events and the id the spawned script- // inherits are the same value; every other command leaves it unset.- const bootstrap: RootCommandBootstrap =- commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId- ? { runId: commandTelemetryContext.runId }- : {};- return yield* trackCliEventEffect(getPrimaryLifecycleInvokedEvent(commandTelemetryContext)).pipe(- Effect.andThen(runWithArgs(bootstrap)),- Effect.scoped,- Effect.mapError(error =>- ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })- ),- Effect.tap(() =>- trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))- ),- Effect.tapErrorCause(cause =>- trackCliEventEffect(- getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))+ const version = yield* getVersion;+ configureCliAnalyticsReleaseVersion(version);+ const baseTelemetryContext = createCliCommandTelemetryContext(+ argv,+ version,+ terminal,+ yield* cliInvocationContext+ );+ const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);+ const commandTelemetryContext =+ executeToolSlug === undefined+ ? baseTelemetryContext+ : { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };+ // `composio run` mints its run id here so the lifecycle events and the id the spawned script+ // inherits are the same value; every other command leaves it unset.+ const bootstrap: RootCommandBootstrap =+ commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId+ ? { runId: commandTelemetryContext.runId }+ : {};+ return yield* trackCliEventEffect(+ getPrimaryLifecycleInvokedEvent(commandTelemetryContext)+ ).pipe(+ Effect.andThen(runWithArgs(argv, bootstrap)),+ Effect.scoped,+ Effect.mapError(error =>+ ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })+ ),+ Effect.tap(() =>+ trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))+ ),+ Effect.tapErrorCause(cause =>+ trackCliEventEffect(+ getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))+ ))- )- );-});+ );+ });/*** Values `src/bin.ts` resolved before the Effect runtime existed and hands to it here.*/export type CliBootstrapOptions = {+ /** The full process argv (executable and script included) with `--telemetry-debug` stripped. */+ readonly argv: ReadonlyArray<string>;/** `--telemetry-debug` was on the command line, and was stripped from argv before parsing. */readonly telemetryDebug: boolean;};-const cliProgram = showUpdateNotice.pipe(- Effect.andThen(showPluginAcquisitionHint(process.argv)),- Effect.andThen(runWithTelemetry),- Effect.catchIf(ValidationError.isValidationError, error => {- return Effect.gen(function* () {- const ui = yield* TerminalUI;- const cliUserConfig = yield* ComposioCliUserConfig;- const visibility = {- isDevModeEnabled: cliUserConfig.isDevModeEnabled(),- isExperimentalFeatureEnabled: (feature: string) =>- cliUserConfig.isExperimentalFeatureEnabled(feature),- };- const valueOptionNames = collectValueOptionNames(buildRootCommand(visibility));- const text = HelpDoc.toAnsiText(error.error).trim();- const errorEffect = text.length > 0 ? ui.error(text) : Effect.void;- const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);- const tipEffect =- flagMatch && valueOptionNames.has(flagMatch[1])- ? ui.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)- : Effect.void;- const cmdName = matchCommandFromArgv(process.argv, visibility);- const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;- const helpEffect = helpText ? ui.error(helpText) : Effect.void;- return yield* Effect.all([errorEffect, tipEffect, helpEffect], { discard: true }).pipe(- Effect.tap(() =>- Effect.sync(() => {- process.exitCode = 1;- })- )- );- });- }),- Effect.catchIf(- (error): error is SetupCommandError => error instanceof SetupCommandError,- error =>- Effect.gen(function* () {+const cliProgram = (argv: ReadonlyArray<string>) =>+ showUpdateNotice.pipe(+ Effect.andThen(showPluginAcquisitionHint(argv)),+ Effect.andThen(runWithTelemetry(argv)),+ Effect.catchIf(ValidationError.isValidationError, error => {+ return Effect.gen(function* () {const ui = yield* TerminalUI;- const summary =- error.operation === 'uninstall'- ? 'Composio plugin uninstall was unsuccessful.'- : 'Composio setup was unsuccessful.';- if ((yield* ui.capabilities).canDecorate) {- yield* ui.log.error(error.message);- yield* ui.outro(summary);- } else {- yield* ui.error(`${summary} ${error.message}`);- }- process.exitCode = 1;- })- ),- // A bare `composio run` is a usage mistake, not a broken invariant: print the one-line fix and- // exit non-zero instead of routing it through the defect reporter below.- Effect.catchIf(- (error): error is MissingRunSourceError => error instanceof MissingRunSourceError,- error =>- Effect.gen(function* () {- const ui = yield* TerminalUI;- yield* ui.error(error.message);- process.exitCode = 1;- })- ),- Effect.catchIf(- (error): error is ShellSetupAbortError => error instanceof ShellSetupAbortError,- // `composio install` already printed the abort reason; the typed failure- // only exists so the process exits non-zero and install.sh runs its- // guarded inline PATH fallback instead of reporting a green install.- () =>- Effect.sync(() => {- process.exitCode = 1;- })- ),- Effect.withSpan('composio-cli', {- attributes: {- name: constants.APP_NAME,- filename: 'src/bin.ts',- },- }),- Effect.sandbox,- Effect.catchAll(- Effect.fn(function* (cause) {- const captured = yield* captureErrors(cause, {- stripCwd: true,+ const cliUserConfig = yield* ComposioCliUserConfig;+ const visibility = {+ isDevModeEnabled: cliUserConfig.isDevModeEnabled(),+ isExperimentalFeatureEnabled: (feature: string) =>+ cliUserConfig.isExperimentalFeatureEnabled(feature),+ };+ const valueOptionNames = collectValueOptionNames(buildRootCommand(visibility));+ const text = HelpDoc.toAnsiText(error.error).trim();+ const errorEffect = text.length > 0 ? ui.error(text) : Effect.void;+ const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);+ const tipEffect =+ flagMatch && valueOptionNames.has(flagMatch[1])+ ? ui.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)+ : Effect.void;+ const cmdName = matchCommandFromArgv(argv, visibility);+ const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;+ const helpEffect = helpText ? ui.error(helpText) : Effect.void;+ return yield* Effect.all([errorEffect, tipEffect, helpEffect], { discard: true }).pipe(+ Effect.tap(() =>+ Effect.sync(() => {+ process.exitCode = 1;+ })+ )+ );});- const filteredErrors = captured.errors.filter(- error => error.errorType !== 'ReportedToolExecutionError'- );- if (captured.interrupted || filteredErrors.length > 0) {- const message = prettyPrintFromCapturedErrors(- { ...captured, errors: filteredErrors },- {- hideStackTrace: true,- stripCwd: true,- enabled: true,- }- ).trim();- if (message.length > 0) {+ }),+ Effect.catchIf(+ (error): error is SetupCommandError => error instanceof SetupCommandError,+ error =>+ Effect.gen(function* () {const ui = yield* TerminalUI;- yield* ui.error(message);- const cliUserConfig = yield* ComposioCliUserConfig;- const visibility = {- isDevModeEnabled: cliUserConfig.isDevModeEnabled(),- isExperimentalFeatureEnabled: (feature: string) =>- cliUserConfig.isExperimentalFeatureEnabled(feature),- };- const cmdName = matchCommandFromArgv(process.argv, visibility);- const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;- if (helpText) {- yield* ui.error(helpText);+ const summary =+ error.operation === 'uninstall'+ ? 'Composio plugin uninstall was unsuccessful.'+ : 'Composio setup was unsuccessful.';+ if ((yield* ui.capabilities).canDecorate) {+ yield* ui.log.error(error.message);+ yield* ui.outro(summary);+ } else {+ yield* ui.error(`${summary} ${error.message}`);}process.exitCode = 1;+ })+ ),+ // A bare `composio run` is a usage mistake, not a broken invariant: print the one-line fix and+ // exit non-zero instead of routing it through the defect reporter below.+ Effect.catchIf(+ (error): error is MissingRunSourceError => error instanceof MissingRunSourceError,+ error =>+ Effect.gen(function* () {+ const ui = yield* TerminalUI;+ yield* ui.error(error.message);+ process.exitCode = 1;+ })+ ),+ Effect.catchIf(+ (error): error is ShellSetupAbortError => error instanceof ShellSetupAbortError,+ // `composio install` already printed the abort reason; the typed failure+ // only exists so the process exits non-zero and install.sh runs its+ // guarded inline PATH fallback instead of reporting a green install.+ () =>+ Effect.sync(() => {+ process.exitCode = 1;+ })+ ),+ Effect.withSpan('composio-cli', {+ attributes: {+ name: constants.APP_NAME,+ filename: 'src/bin.ts',+ },+ }),+ Effect.sandbox,+ Effect.catchAll(+ Effect.fn(function* (cause) {+ const captured = yield* captureErrors(cause, {+ stripCwd: true,+ });+ const filteredErrors = captured.errors.filter(+ error => error.errorType !== 'ReportedToolExecutionError'+ );+ if (captured.interrupted || filteredErrors.length > 0) {+ const message = prettyPrintFromCapturedErrors(+ { ...captured, errors: filteredErrors },+ {+ hideStackTrace: true,+ stripCwd: true,+ enabled: true,+ }+ ).trim();+ if (message.length > 0) {+ const ui = yield* TerminalUI;+ yield* ui.error(message);+ const cliUserConfig = yield* ComposioCliUserConfig;+ const visibility = {+ isDevModeEnabled: cliUserConfig.isDevModeEnabled(),+ isExperimentalFeatureEnabled: (feature: string) =>+ cliUserConfig.isExperimentalFeatureEnabled(feature),+ };+ const cmdName = matchCommandFromArgv(argv, visibility);+ const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;+ if (helpText) {+ yield* ui.error(helpText);+ }+ process.exitCode = 1;+ }}- }- })- ),- Effect.provide(layers),- Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive))-);+ })+ ),+ Effect.provide(layers),+ Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive))+ );export const runCli = (options: CliBootstrapOptions): void => {- cliProgram.pipe(+ cliProgram(options.argv).pipe(// Only provided when the flag was actually present: without it telemetry debugging falls back// to `COMPOSIO_CLI_TELEMETRY_DEBUG`.effect =>diff --git a/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts b/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.tsindex a872d97b9..c8bbd4534 100644--- a/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts+++ b/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts@@ -19,7 +19,10 @@ import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';import { Array, Data, Effect, Option, pipe } from 'effect';import { Match } from 'effect';import { FileSystem, Path } from '@effect/platform';-import { ComposioToolkitsRepository } from 'src/services/composio-clients';+import {+ ComposioToolkitsRepository,+ type ComposioToolkitsRepositoryShape,+} from 'src/services/composio-clients';import { logMetrics } from 'src/effects/log-metrics';import { NodeProcess } from 'src/services/node-process';import { createToolkitIndex } from 'src/generation/create-toolkit-index';@@ -115,7 +118,7 @@ type FetchResult = {* Makes targeted API calls for only the requested toolkits.*/function fetchFilteredData(- client: ComposioToolkitsRepository,+ client: ComposioToolkitsRepositoryShape,slugs: ReadonlyArray<string>,typeTools: boolean,versionOverrides: ToolkitVersionOverrides,@@ -195,7 +198,7 @@ function fetchFilteredData(* Fetches everything in parallel without version-specific handling.*/function fetchAllDataFastPath(- client: ComposioToolkitsRepository,+ client: ComposioToolkitsRepositoryShape,typeTools: boolean,spinner: SpinnerHandle): Effect.Effect<FetchResult, Error, never> {@@ -245,7 +248,7 @@ function fetchAllDataFastPath(* First fetches toolkit metadata, then fetches tools with version-specific handling.*/function fetchAllDataWithOverrides(- client: ComposioToolkitsRepository,+ client: ComposioToolkitsRepositoryShape,typeTools: boolean,versionOverrides: ToolkitVersionOverrides,spinner: SpinnerHandle@@ -305,7 +308,7 @@ function fetchAllDataWithOverrides(* Delegates to fast path or override-aware path based on version overrides.*/function fetchAllData(- client: ComposioToolkitsRepository,+ client: ComposioToolkitsRepositoryShape,typeTools: boolean,versionOverrides: ToolkitVersionOverrides,spinner: SpinnerHandlediff --git a/ts/packages/cli/src/effects/validate-toolkit-versions.ts b/ts/packages/cli/src/effects/validate-toolkit-versions.tsindex 65fcc5e36..2ddb61528 100644--- a/ts/packages/cli/src/effects/validate-toolkit-versions.ts+++ b/ts/packages/cli/src/effects/validate-toolkit-versions.ts@@ -3,7 +3,7 @@ import colors from 'picocolors';import { S_BAR, unicodeOr } from '@clack/prompts';import { TerminalUI } from 'src/services/terminal-ui';import type {- ComposioToolkitsRepository,+ ComposioToolkitsRepositoryShape,InvalidVersionDetail,} from 'src/services/composio-clients';import type { ToolkitVersionOverrides } from './toolkit-version-overrides';@@ -119,7 +119,7 @@ export interface ValidateVersionsOptions {/** Optional array of toolkit slugs to filter (from --toolkits flag) */readonly toolkitSlugsFilter: ReadonlyArray<string> | null;/** The ComposioToolkitsRepository client */- readonly client: ComposioToolkitsRepository;+ readonly client: ComposioToolkitsRepositoryShape;}/**diff --git a/ts/packages/cli/src/services/command-runner.ts b/ts/packages/cli/src/services/command-runner.tsindex c6ccfd193..1a66e09e7 100644--- a/ts/packages/cli/src/services/command-runner.ts+++ b/ts/packages/cli/src/services/command-runner.ts@@ -1,5 +1,5 @@import { Command } from '@effect/platform';-import { Effect, Stream, String } from 'effect';+import { Effect, Stream, String, Context, Layer } from 'effect';export interface CommandResult {readonly exitCode: number;@@ -11,24 +11,30 @@ export interface CommandResult {export const collectText = (stream: Stream.Stream<Uint8Array, unknown>) =>stream.pipe(Stream.decodeText(), Stream.runFold(String.empty, String.concat));-export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {- sync: () => ({- run: (command: Command.Command) => Command.exitCode(command),- capture: (command: Command.Command) =>- Effect.scoped(- Effect.gen(function* () {- const childProcess = yield* Command.start(command);- const [exitCode, stdout, stderr] = yield* Effect.all(- [- childProcess.exitCode,- collectText(childProcess.stdout),- collectText(childProcess.stderr),- ],- { concurrency: 'unbounded' }- );- return { exitCode: Number(exitCode), stdout, stderr } satisfies CommandResult;- })- ),- }),- dependencies: [],-}) {}+const makeCommandRunner = Effect.sync(() => ({+ run: (command: Command.Command) => Command.exitCode(command),+ capture: (command: Command.Command) =>+ Effect.scoped(+ Effect.gen(function* () {+ const childProcess = yield* Command.start(command);+ const [exitCode, stdout, stderr] = yield* Effect.all(+ [+ childProcess.exitCode,+ collectText(childProcess.stdout),+ collectText(childProcess.stderr),+ ],+ { concurrency: 'unbounded' }+ );+ return { exitCode: Number(exitCode), stdout, stderr } satisfies CommandResult;+ })+ ),+}));++export type CommandRunnerShape = Effect.Effect.Success<typeof makeCommandRunner>;++export class CommandRunner extends Context.Tag('services/CommandRunner')<+ CommandRunner,+ CommandRunnerShape+>() {+ static readonly Default = Layer.effect(CommandRunner, makeCommandRunner);+}diff --git a/ts/packages/cli/src/services/composio-clients-cached.ts b/ts/packages/cli/src/services/composio-clients-cached.tsindex d591fdca1..92a5555c8 100644--- a/ts/packages/cli/src/services/composio-clients-cached.ts+++ b/ts/packages/cli/src/services/composio-clients-cached.ts@@ -180,7 +180,7 @@ export const ComposioToolkitsRepositoryCached = Layer.effect();// Create the cached implementation that wraps the original implementation- return ComposioToolkitsRepository.make({+ return ComposioToolkitsRepository.of({// Memoized per layer instance; `getToolkitsBySlugs` stays unmemoized// because its result depends on the requested slugs.getToolkits: () => cachedGetToolkits,diff --git a/ts/packages/cli/src/services/composio-clients.ts b/ts/packages/cli/src/services/composio-clients.tsindex cd4cab42c..658d8aba9 100644--- a/ts/packages/cli/src/services/composio-clients.ts+++ b/ts/packages/cli/src/services/composio-clients.ts@@ -11,6 +11,8 @@ import {Stream,Sink,SynchronizedRef,+ Context,+ Layer,} from 'effect';import { Composio as _RawComposioClient, APIPromise } from '@composio/client';import { FileSystem, Path } from '@effect/platform';@@ -419,7 +421,7 @@ export interface TriggerInstanceUpsertParams {}function buildTriggerInstancesNamespace(- clientSingleton: ComposioClientSingleton,+ clientSingleton: ComposioClientSingletonShape,withMetrics: <A, E, R>(effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>) => Effect.Effect<A, E, R>@@ -473,7 +475,7 @@ function buildTriggerInstancesNamespace(};}-function buildTriggerInstanceRepositoryOperations(client: ComposioClientLive) {+function buildTriggerInstanceRepositoryOperations(client: ComposioClientLiveShape) {return {listActiveTriggers: (params: TriggerInstancesListActiveParams) =>client.triggerInstances.listActive(params),@@ -1377,7 +1379,7 @@ const buildDefaultHeaders = (params: {// Utility function for calling the Composio API and decoding its response.const callClient = <T, S extends Schema.Schema.AnyNoContext>(- clientSingleton: ComposioClientSingleton,+ clientSingleton: ComposioClientSingletonShape,apiCall: (client: _RawComposioClient) => APIPromise<T>,responseSchema: S): Effect.Effect<@@ -1437,7 +1439,7 @@ const MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 4;// Utility function for calling paginated Composio API endpoints.// Automatically fetches all pages, using MAX_PAGE_SIZE per request.const callClientWithPagination = <T, S extends PaginatedSchema>(- clientSingleton: ComposioClientSingleton,+ clientSingleton: ComposioClientSingletonShape,apiCall: (client: _RawComposioClient, cursor?: string, limit?: number) => APIPromise<T>,responseSchema: S): Effect.Effect<@@ -1524,93 +1526,97 @@ const callClientWithPagination = <T, S extends PaginatedSchema>(* Singleton service that lazily accesses `Config` only when needed, which is used to build and provide* a raw (uneffectful, Promise-based) Composio client instance.*/-export class ComposioClientSingleton extends Effect.Service<ComposioClientSingleton>()(- 'services/ComposioClientSingleton',- {- accessors: true,- effect: Effect.gen(function* () {- const ctx = yield* ComposioUserContext;- const projectContextOpt = yield* Effect.serviceOption(ProjectContext);- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const os = yield* NodeOs;- const cache = new Map<string, _RawComposioClient>();-- const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>- Effect.gen(function* () {- const apiKey = normalizeApiKey(- params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey)- );- const cacheKey = JSON.stringify({- apiKey: apiKey ?? null,- orgId: params?.orgId ?? null,- projectId: params?.projectId ?? null,- });- const cached = cache.get(cacheKey);- if (cached) {- return cached;- }+const makeComposioClientSingleton = Effect.gen(function* () {+ const ctx = yield* ComposioUserContext;+ const projectContextOpt = yield* Effect.serviceOption(ProjectContext);+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const os = yield* NodeOs;+ const cache = new Map<string, _RawComposioClient>();++ const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>+ Effect.gen(function* () {+ const apiKey = normalizeApiKey(params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey));+ const cacheKey = JSON.stringify({+ apiKey: apiKey ?? null,+ orgId: params?.orgId ?? null,+ projectId: params?.projectId ?? null,+ });+ const cached = cache.get(cacheKey);+ if (cached) {+ return cached;+ }- const cliSessionId = yield* getCurrentCwdSessionId().pipe(- Effect.provideService(FileSystem.FileSystem, fs),- Effect.provideService(Path.Path, path),- Effect.provideService(NodeOs, os)- );+ const cliSessionId = yield* getCurrentCwdSessionId().pipe(+ Effect.provideService(FileSystem.FileSystem, fs),+ Effect.provideService(Path.Path, path),+ Effect.provideService(NodeOs, os)+ );- const client = new _RawComposioClient({- apiKey: null,- baseURL: ctx.data.baseURL,- defaultHeaders: buildDefaultHeaders({- userApiKey: apiKey,- orgId: params?.orgId,- projectId: params?.projectId,- cliSessionId,- }),- });+ const client = new _RawComposioClient({+ apiKey: null,+ baseURL: ctx.data.baseURL,+ defaultHeaders: buildDefaultHeaders({+ userApiKey: apiKey,+ orgId: params?.orgId,+ projectId: params?.projectId,+ cliSessionId,+ }),+ });- cache.set(cacheKey, client);- return client;- });+ cache.set(cacheKey, client);+ return client;+ });- return {- get: Effect.fn(function* () {- const resolvedProjectContext = yield* Option.match(projectContextOpt, {- onNone: () => Effect.succeed(Option.none()),- onSome: projectContext =>- projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),- });- return yield* Option.match(resolvedProjectContext, {- onNone: () => getFor(),- onSome: keys =>- getFor({- orgId: keys.orgId,- projectId: keys.projectId,- }),- });- }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,- getFor: Effect.fn(function* (params: {- userApiKey?: string;- orgId?: string;- projectId?: string;- }) {- return yield* getFor(params);- }) satisfies (params: {- userApiKey?: string;- orgId?: string;- projectId?: string;- }) => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,- };- }),- dependencies: [ComposioUserContextLive],- }-) {}+ return {+ get: Effect.fn(function* () {+ const resolvedProjectContext = yield* Option.match(projectContextOpt, {+ onNone: () => Effect.succeed(Option.none()),+ onSome: projectContext =>+ projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),+ });+ return yield* Option.match(resolvedProjectContext, {+ onNone: () => getFor(),+ onSome: keys =>+ getFor({+ orgId: keys.orgId,+ projectId: keys.projectId,+ }),+ });+ }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,+ getFor: Effect.fn(function* (params: {+ userApiKey?: string;+ orgId?: string;+ projectId?: string;+ }) {+ return yield* getFor(params);+ }) satisfies (params: {+ userApiKey?: string;+ orgId?: string;+ projectId?: string;+ }) => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,+ };+});++export type ComposioClientSingletonShape = Effect.Effect.Success<+ typeof makeComposioClientSingleton+>;++export class ComposioClientSingleton extends Context.Tag('services/ComposioClientSingleton')<+ ComposioClientSingleton,+ ComposioClientSingletonShape+>() {+ static readonly Default = Layer.effect(ComposioClientSingleton, makeComposioClientSingleton).pipe(+ Layer.provide(ComposioUserContextLive)+ );+}/*** Build the `tools` namespace for ComposioClientLive.* Extracted to keep the main generator under the max-lines-per-function limit.*/function buildToolsNamespace(- clientSingleton: ComposioClientSingleton,+ clientSingleton: ComposioClientSingletonShape,withMetrics: <A, E, R>(effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>) => Effect.Effect<A, E, R>@@ -1723,7 +1729,7 @@ function buildToolsNamespace(* Extracted to keep the main generator under the max-lines-per-function limit.*/function buildAuthConfigsNamespace(- clientSingleton: ComposioClientSingleton,+ clientSingleton: ComposioClientSingletonShape,withMetrics: <A, E, R>(effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>) => Effect.Effect<A, E, R>@@ -1792,7 +1798,7 @@ function buildAuthConfigsNamespace(* Extracted to keep the main generator under the max-lines-per-function limit.*/function buildConnectedAccountsNamespace(- clientSingleton: ComposioClientSingleton,+ clientSingleton: ComposioClientSingletonShape,withMetrics: <A, E, R>(effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>) => Effect.Effect<A, E, R>@@ -1859,449 +1865,458 @@ function buildConnectedAccountsNamespace(}// Service that wraps the raw Composio client, which is shared by all client services.-export class ComposioClientLive extends Effect.Service<ComposioClientLive>()(- 'services/ComposioClientLive',- {- effect: Effect.gen(function* () {- const clientSingleton = yield* ComposioClientSingleton;-- // Initialize metrics tracking via SynchronizedRef- const metricsRef = yield* SynchronizedRef.make<Metrics>({ byteSize: 0, requests: 0 });-- // Helper to update metrics and return just the data- const withMetrics = <A, E, R>(- effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>- ): Effect.Effect<A, E, R> =>- Effect.gen(function* () {- const { data, metrics } = yield* effect;- yield* SynchronizedRef.update(metricsRef, current => ({- byteSize: current.byteSize + metrics.byteSize,- requests: current.requests + metrics.requests,- }));- return data;- });-- return {- /**- * Returns a snapshot of the current accumulated metrics (total bytes received and request count).- */- getMetrics: () => SynchronizedRef.get(metricsRef),- toolkits: {- /**- * Retrieves a comprehensive list of toolkits that are available to the authenticated project.- * Automatically handles pagination to fetch all items.- */- list: () =>- withMetrics(- callClientWithPagination(- clientSingleton,- (client, cursor, limit) => client.toolkits.list({ cursor, limit }),- ToolkitsResponse- )- ),- /**- * Retrieves a single toolkit by its slug.- * Transforms the response to match the Toolkit schema.- */- retrieve: (slug: string) =>- withMetrics(- callClient(- clientSingleton,- client => client.toolkits.retrieve(slug),- ToolkitRetrieveResponse- )- ).pipe(- // Transform to Toolkit format by adding missing fields- Effect.map(- retrieved =>- ({- name: retrieved.name,- slug: retrieved.slug,- auth_schemes: [], // retrieve endpoint doesn't return auth_schemes- composio_managed_auth_schemes: retrieved.composio_managed_auth_schemes,- is_local_toolkit: retrieved.is_local_toolkit,- no_auth: retrieved.no_auth,- meta: retrieved.meta,- }) satisfies Toolkit- )- ),- /**- * Searches toolkits with optional filters. Returns a single page of results (no auto-pagination).- * @param params - Search/filter parameters- */- search: (params: {- search?: string;- category?: string;- limit?: number;- cursor?: string;- }) =>- withMetrics(- callClient(- clientSingleton,- client =>- client.toolkits.list({- search: params.search,- category: params.category,- limit: params.limit,- cursor: params.cursor,- }),- ToolkitSearchResponse- )- ).pipe(- Effect.map(- response =>- ({- items: response.items,- total_items: response.total_items,- total_pages: response.total_pages,- next_cursor: response.next_cursor,- }) satisfies ToolkitSearchResult- )- ),- /**- * Retrieves detailed toolkit info including auth_config_details.- * @param slug - Toolkit slug- */- retrieveDetailed: (slug: string) =>- withMetrics(- callClient(- clientSingleton,- client => client.toolkits.retrieve(slug),- ToolkitDetailedResponse- )- ),- },- tools: buildToolsNamespace(clientSingleton, withMetrics),- triggersTypes: {- /**- * Retrieves a list of all available trigger type enum values that can be used across the API.- */- retrieveEnum: () =>- withMetrics(- callClient(- clientSingleton,- client => client.triggersTypes.retrieveEnum(),- TriggerTypesAsEnumsResponse- )- ),- /**- * Retrieves detailed info about a single trigger type by slug.- * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")- */- retrieve: (slug: string) =>- withMetrics(- callClient(- clientSingleton,- client => client.triggersTypes.retrieve(slug),- TriggerType- )- ),- /**- * Retrieve a list of trigger types, automatically handling pagination.- * @param toolkitSlugs - Optional array of toolkit slugs to filter by- */- list: (toolkitSlugs?: ReadonlyArray<string>) =>- withMetrics(- callClientWithPagination(- clientSingleton,- (client, cursor, limit) =>- client.triggersTypes.list({- cursor,- limit,- toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,- }),- TriggerTypesResponse- )- ),- },- triggerInstances: buildTriggerInstancesNamespace(clientSingleton, withMetrics),- cli: {- /**- * Generates a new CLI session with a random 6-character code.- * @param params.scope - 'user' for login, 'project' for init (future)- *- * TODO: don't use `@composio/client`, wrap `fetch` directly.- */- createSession: (params?: { scope?: 'user' | 'project' }) =>- withMetrics(- callClient(- clientSingleton,- client =>- client.cli.createSession(- { scope: params?.scope ?? 'user' },- { headers: { 'Content-Type': 'application/json' } }- ),- CliCreateSessionResponse- )- ),+const makeComposioClientLive = Effect.gen(function* () {+ const clientSingleton = yield* ComposioClientSingleton;- /**- * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.- */- getSession: (session: { id: string }) =>- withMetrics(- callClient(- clientSingleton,- client => client.cli.getSession(session),- CliGetSessionResponse- )- ),- getRealtimeCredentials: () =>- withMetrics(- callClient(- clientSingleton,- client => client.cli.realtime.credentials(),- CliRealtimeCredentialsResponse- )- ),- authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>- withMetrics(- callClient(- clientSingleton,- client => client.cli.realtime.auth(params),- CliRealtimeAuthResponse- )- ),- },- authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),- connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),- };- }),- dependencies: [ComposioClientSingleton.Default],- }-) {}+ // Initialize metrics tracking via SynchronizedRef+ const metricsRef = yield* SynchronizedRef.make<Metrics>({ byteSize: 0, requests: 0 });-export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsRepository>()(- 'services/ComposioToolkitsRepository',- {- effect: Effect.gen(function* () {- const client = yield* ComposioClientLive;+ // Helper to update metrics and return just the data+ const withMetrics = <A, E, R>(+ effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>+ ): Effect.Effect<A, E, R> =>+ Effect.gen(function* () {+ const { data, metrics } = yield* effect;+ yield* SynchronizedRef.update(metricsRef, current => ({+ byteSize: current.byteSize + metrics.byteSize,+ requests: current.requests + metrics.requests,+ }));+ return data;+ });- const getToolkits = () =>- client.toolkits.list().pipe(- Effect.map(response => response.items),- Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)- );+ return {+ /**+ * Returns a snapshot of the current accumulated metrics (total bytes received and request count).+ */+ getMetrics: () => SynchronizedRef.get(metricsRef),+ toolkits: {+ /**+ * Retrieves a comprehensive list of toolkits that are available to the authenticated project.+ * Automatically handles pagination to fetch all items.+ */+ list: () =>+ withMetrics(+ callClientWithPagination(+ clientSingleton,+ (client, cursor, limit) => client.toolkits.list({ cursor, limit }),+ ToolkitsResponse+ )+ ),+ /**+ * Retrieves a single toolkit by its slug.+ * Transforms the response to match the Toolkit schema.+ */+ retrieve: (slug: string) =>+ withMetrics(+ callClient(+ clientSingleton,+ client => client.toolkits.retrieve(slug),+ ToolkitRetrieveResponse+ )+ ).pipe(+ // Transform to Toolkit format by adding missing fields+ Effect.map(+ retrieved =>+ ({+ name: retrieved.name,+ slug: retrieved.slug,+ auth_schemes: [], // retrieve endpoint doesn't return auth_schemes+ composio_managed_auth_schemes: retrieved.composio_managed_auth_schemes,+ is_local_toolkit: retrieved.is_local_toolkit,+ no_auth: retrieved.no_auth,+ meta: retrieved.meta,+ }) satisfies Toolkit+ )+ ),+ /**+ * Searches toolkits with optional filters. Returns a single page of results (no auto-pagination).+ * @param params - Search/filter parameters+ */+ search: (params: { search?: string; category?: string; limit?: number; cursor?: string }) =>+ withMetrics(+ callClient(+ clientSingleton,+ client =>+ client.toolkits.list({+ search: params.search,+ category: params.category,+ limit: params.limit,+ cursor: params.cursor,+ }),+ ToolkitSearchResponse+ )+ ).pipe(+ Effect.map(+ response =>+ ({+ items: response.items,+ total_items: response.total_items,+ total_pages: response.total_pages,+ next_cursor: response.next_cursor,+ }) satisfies ToolkitSearchResult+ )+ ),+ /**+ * Retrieves detailed toolkit info including auth_config_details.+ * @param slug - Toolkit slug+ */+ retrieveDetailed: (slug: string) =>+ withMetrics(+ callClient(+ clientSingleton,+ client => client.toolkits.retrieve(slug),+ ToolkitDetailedResponse+ )+ ),+ },+ tools: buildToolsNamespace(clientSingleton, withMetrics),+ triggersTypes: {+ /**+ * Retrieves a list of all available trigger type enum values that can be used across the API.+ */+ retrieveEnum: () =>+ withMetrics(+ callClient(+ clientSingleton,+ client => client.triggersTypes.retrieveEnum(),+ TriggerTypesAsEnumsResponse+ )+ ),+ /**+ * Retrieves detailed info about a single trigger type by slug.+ * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")+ */+ retrieve: (slug: string) =>+ withMetrics(+ callClient(clientSingleton, client => client.triggersTypes.retrieve(slug), TriggerType)+ ),+ /**+ * Retrieve a list of trigger types, automatically handling pagination.+ * @param toolkitSlugs - Optional array of toolkit slugs to filter by+ */+ list: (toolkitSlugs?: ReadonlyArray<string>) =>+ withMetrics(+ callClientWithPagination(+ clientSingleton,+ (client, cursor, limit) =>+ client.triggersTypes.list({+ cursor,+ limit,+ toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,+ }),+ TriggerTypesResponse+ )+ ),+ },+ triggerInstances: buildTriggerInstancesNamespace(clientSingleton, withMetrics),+ cli: {+ /**+ * Generates a new CLI session with a random 6-character code.+ * @param params.scope - 'user' for login, 'project' for init (future)+ *+ * TODO: don't use `@composio/client`, wrap `fetch` directly.+ */+ createSession: (params?: { scope?: 'user' | 'project' }) =>+ withMetrics(+ callClient(+ clientSingleton,+ client =>+ client.cli.createSession(+ { scope: params?.scope ?? 'user' },+ { headers: { 'Content-Type': 'application/json' } }+ ),+ CliCreateSessionResponse+ )+ ),/**- * Fetches specific toolkits by their slugs.- * Makes parallel API calls to retrieve each toolkit.- * @param slugs - Array of toolkit slugs to fetch+ * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.*/- const getToolkitsBySlugs = (slugs: ReadonlyArray<string>) =>- Effect.all(- slugs.map(slug =>- client.toolkits.retrieve(slug).pipe(- // Only convert 404 errors to InvalidToolkitsError.- // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.- Effect.catchTag('services/HttpServerError', e =>- Effect.if(e.status === 404, {- onTrue: () =>- Effect.fail(- new InvalidToolkitsError({- invalidToolkits: [slug],- availableToolkits: [],- })- ),- onFalse: () => Effect.fail(e),- })- )- )- ),- { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }- ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));+ getSession: (session: { id: string }) =>+ withMetrics(+ callClient(+ clientSingleton,+ client => client.cli.getSession(session),+ CliGetSessionResponse+ )+ ),+ getRealtimeCredentials: () =>+ withMetrics(+ callClient(+ clientSingleton,+ client => client.cli.realtime.credentials(),+ CliRealtimeCredentialsResponse+ )+ ),+ authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>+ withMetrics(+ callClient(+ clientSingleton,+ client => client.cli.realtime.auth(params),+ CliRealtimeAuthResponse+ )+ ),+ },+ authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),+ connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),+ };+});- return {- getToolkits,- getToolkitsBySlugs,- getMetrics: () => client.getMetrics(),- getToolsAsEnums: () => client.tools.retrieveEnum(),- /**- * Fetches tools with optional toolkit filtering.- * When toolkitSlugs is provided, fetches all matching tools.- * @param toolkitSlugs - Optional array of toolkit slugs to filter by- */- getTools: (toolkitSlugs?: ReadonlyArray<string>) =>- client.tools.list(toolkitSlugs ?? []).pipe(- Effect.map(response => response.items),- Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)- ),- /**- * Fetches tools with per-toolkit version support.- * Groups toolkits by version and makes separate API calls for each group.- * @param specs - Array of { toolkitSlug, toolkitVersion } specifications- */- getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>- client.tools.listByVersionSpecs(specs).pipe(- Effect.map(response => response.items),- Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)- ),- getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),- /**- * Retrieves detailed info about a single trigger type by slug.- * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")- */- getTriggerTypeDetailed: (slug: string) => client.triggersTypes.retrieve(slug),- /**- * Fetches trigger types with optional toolkit filtering.- * When toolkitSlugs is provided, fetches all matching trigger types.- * @param toolkitSlugs - Optional array of toolkit slugs to filter by- */- getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>- client.triggersTypes.list(toolkitSlugs).pipe(- Effect.map(response => response.items),- Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)- ),- /**- * Validates that the given toolkit slugs are valid by comparing them against the list- * of available toolkits. Returns the list of valid toolkit slugs (normalized to lowercase).- * @param toolkitSlugs - Array of toolkit slugs to validate (case-insensitive)- */- validateToolkits: (- toolkitSlugs: ReadonlyArray<string>- ): Effect.Effect<- ReadonlyArray<string>,- InvalidToolkitsError | HttpError | NoSuchElementException- > =>- Effect.gen(function* () {- // Normalize input slugs to lowercase for comparison- const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));-- // Fetch all available toolkits- const allToolkits = yield* getToolkits();- const availableSlugs = allToolkits.map(toolkit => String.toLowerCase(toolkit.slug));-- // Find invalid slugs- const invalidSlugs = normalizedInputSlugs.filter(- slug => !availableSlugs.includes(slug)- );+export type ComposioClientLiveShape = Effect.Effect.Success<typeof makeComposioClientLive>;- if (invalidSlugs.length > 0) {- return yield* Effect.fail(- new InvalidToolkitsError({- invalidToolkits: invalidSlugs,- availableToolkits: availableSlugs,- })- );- }+export class ComposioClientLive extends Context.Tag('services/ComposioClientLive')<+ ComposioClientLive,+ ComposioClientLiveShape+>() {+ static readonly Default = Layer.effect(ComposioClientLive, makeComposioClientLive).pipe(+ Layer.provide(ComposioClientSingleton.Default)+ );+}- return normalizedInputSlugs;- }),- /**- * Filters the given list of toolkits to only include those with the specified slugs.- * @param toolkits - Array of toolkits to filter- * @param toolkitSlugs - Array of toolkit slugs to filter by (case-insensitive)- */- filterToolkitsBySlugs: (- toolkits: ReadonlyArray<Toolkit>,- toolkitSlugs: ReadonlyArray<string>- ): ReadonlyArray<Toolkit> => {- const normalizedSlugs = new Set(toolkitSlugs.map(slug => String.toLowerCase(slug)));- return toolkits.filter(toolkit => normalizedSlugs.has(String.toLowerCase(toolkit.slug)));- },- /**- * Validates that the requested toolkit versions exist in the API's available_versions.- * Makes parallel API calls to fetch toolkit metadata for validation.- *- * @param overrides - Map of toolkit slug to requested version- * @param relevantToolkits - Optional array of toolkit slugs to validate (if --toolkits filter is used)- * @returns Effect that succeeds with the validated overrides and warnings, or fails with InvalidToolkitVersionsError- */- validateToolkitVersions: (- overrides: ToolkitVersionOverrides,- relevantToolkits?: ReadonlyArray<string>- ): Effect.Effect<- {- validatedOverrides: ToolkitVersionOverrides;- warnings: ReadonlyArray<string>;- },- InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementException- > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),- /**- * Searches toolkits with optional filters. Returns a single page of results.- * @param params - Search/filter parameters- */- searchToolkits: (params: {- search?: string;- category?: string;- limit?: number;- cursor?: string;- }) => client.toolkits.search(params),- /**- * Retrieves detailed toolkit info including auth_config_details.- * @param slug - Toolkit slug- */- getToolkitDetailed: (slug: string) => client.toolkits.retrieveDetailed(slug),- /**- * Searches tools with optional filters. Returns a single page of results.- * @param params - Search/filter parameters- */- searchTools: (params: {- search?: string;- toolkit_slug?: string;- tags?: string;- limit?: number;- cursor?: string;- }) => client.tools.search(params),- /**- * Retrieves detailed info about a single tool by slug.- * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")- */- getToolDetailed: (slug: string) => client.tools.retrieve(slug),- /**- * Lists auth configs with optional filters. Returns a single page of results.- * @param params - Search/filter parameters- */- listAuthConfigs: (params: {- search?: string;- toolkit_slug?: string;- limit?: number;- show_disabled?: boolean;- }) => client.authConfigs.list(params),- /**- * Retrieves detailed info about a single auth config by its nanoid.- * @param nanoid - Auth config ID- */- getAuthConfig: (nanoid: string) => client.authConfigs.retrieve(nanoid),- /**- * Creates a new auth config for a toolkit.- * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)- */- createAuthConfig: (params: AuthConfigCreateParams) => client.authConfigs.create(params),- deleteAuthConfig: (nanoid: string) => client.authConfigs.delete(nanoid),- // Connected account operations (thin wrappers — see buildConnectedAccountsNamespace)- listConnectedAccounts: (params: {- toolkit_slugs?: string[];- user_ids?: string[];- statuses?: string[];- limit?: number;- }) => client.connectedAccounts.list(params),- getConnectedAccount: (nanoid: string) => client.connectedAccounts.retrieve(nanoid),- deleteConnectedAccount: (nanoid: string) => client.connectedAccounts.delete(nanoid),- createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>- client.connectedAccounts.createLink(params),- ...buildTriggerInstanceRepositoryOperations(client),- };- }),- dependencies: [ComposioClientLive.Default],- }-) {}+const makeComposioToolkitsRepository = Effect.gen(function* () {+ const client = yield* ComposioClientLive;-export class ComposioSessionRepository extends Effect.Service<ComposioSessionRepository>()(- 'services/ComposioSessionRepository',- {- effect: Effect.gen(function* () {- const client = yield* ComposioClientLive;+ const getToolkits = () =>+ client.toolkits.list().pipe(+ Effect.map(response => response.items),+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)+ );- return {- createSession: (params?: { scope?: 'user' | 'project' }) =>- client.cli.createSession(params),- getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),- getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),- authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>- client.cli.authRealtimeChannel(params),- };- }),- dependencies: [ComposioClientLive.Default],- }-) {}+ /**+ * Fetches specific toolkits by their slugs.+ * Makes parallel API calls to retrieve each toolkit.+ * @param slugs - Array of toolkit slugs to fetch+ */+ const getToolkitsBySlugs = (slugs: ReadonlyArray<string>) =>+ Effect.all(+ slugs.map(slug =>+ client.toolkits.retrieve(slug).pipe(+ // Only convert 404 errors to InvalidToolkitsError.+ // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.+ Effect.catchTag('services/HttpServerError', e =>+ Effect.if(e.status === 404, {+ onTrue: () =>+ Effect.fail(+ new InvalidToolkitsError({+ invalidToolkits: [slug],+ availableToolkits: [],+ })+ ),+ onFalse: () => Effect.fail(e),+ })+ )+ )+ ),+ { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }+ ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));++ return {+ getToolkits,+ getToolkitsBySlugs,+ getMetrics: () => client.getMetrics(),+ getToolsAsEnums: () => client.tools.retrieveEnum(),+ /**+ * Fetches tools with optional toolkit filtering.+ * When toolkitSlugs is provided, fetches all matching tools.+ * @param toolkitSlugs - Optional array of toolkit slugs to filter by+ */+ getTools: (toolkitSlugs?: ReadonlyArray<string>) =>+ client.tools.list(toolkitSlugs ?? []).pipe(+ Effect.map(response => response.items),+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)+ ),+ /**+ * Fetches tools with per-toolkit version support.+ * Groups toolkits by version and makes separate API calls for each group.+ * @param specs - Array of { toolkitSlug, toolkitVersion } specifications+ */+ getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>+ client.tools.listByVersionSpecs(specs).pipe(+ Effect.map(response => response.items),+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)+ ),+ getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),+ /**+ * Retrieves detailed info about a single trigger type by slug.+ * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")+ */+ getTriggerTypeDetailed: (slug: string) => client.triggersTypes.retrieve(slug),+ /**+ * Fetches trigger types with optional toolkit filtering.+ * When toolkitSlugs is provided, fetches all matching trigger types.+ * @param toolkitSlugs - Optional array of toolkit slugs to filter by+ */+ getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>+ client.triggersTypes.list(toolkitSlugs).pipe(+ Effect.map(response => response.items),+ Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)+ ),+ /**+ * Validates that the given toolkit slugs are valid by comparing them against the list+ * of available toolkits. Returns the list of valid toolkit slugs (normalized to lowercase).+ * @param toolkitSlugs - Array of toolkit slugs to validate (case-insensitive)+ */+ validateToolkits: (+ toolkitSlugs: ReadonlyArray<string>+ ): Effect.Effect<+ ReadonlyArray<string>,+ InvalidToolkitsError | HttpError | NoSuchElementException+ > =>+ Effect.gen(function* () {+ // Normalize input slugs to lowercase for comparison+ const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));++ // Fetch all available toolkits+ const allToolkits = yield* getToolkits();+ const availableSlugs = allToolkits.map(toolkit => String.toLowerCase(toolkit.slug));++ // Find invalid slugs+ const invalidSlugs = normalizedInputSlugs.filter(slug => !availableSlugs.includes(slug));++ if (invalidSlugs.length > 0) {+ return yield* Effect.fail(+ new InvalidToolkitsError({+ invalidToolkits: invalidSlugs,+ availableToolkits: availableSlugs,+ })+ );+ }++ return normalizedInputSlugs;+ }),+ /**+ * Filters the given list of toolkits to only include those with the specified slugs.+ * @param toolkits - Array of toolkits to filter+ * @param toolkitSlugs - Array of toolkit slugs to filter by (case-insensitive)+ */+ filterToolkitsBySlugs: (+ toolkits: ReadonlyArray<Toolkit>,+ toolkitSlugs: ReadonlyArray<string>+ ): ReadonlyArray<Toolkit> => {+ const normalizedSlugs = new Set(toolkitSlugs.map(slug => String.toLowerCase(slug)));+ return toolkits.filter(toolkit => normalizedSlugs.has(String.toLowerCase(toolkit.slug)));+ },+ /**+ * Validates that the requested toolkit versions exist in the API's available_versions.+ * Makes parallel API calls to fetch toolkit metadata for validation.+ *+ * @param overrides - Map of toolkit slug to requested version+ * @param relevantToolkits - Optional array of toolkit slugs to validate (if --toolkits filter is used)+ * @returns Effect that succeeds with the validated overrides and warnings, or fails with InvalidToolkitVersionsError+ */+ validateToolkitVersions: (+ overrides: ToolkitVersionOverrides,+ relevantToolkits?: ReadonlyArray<string>+ ): Effect.Effect<+ {+ validatedOverrides: ToolkitVersionOverrides;+ warnings: ReadonlyArray<string>;+ },+ InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementException+ > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),+ /**+ * Searches toolkits with optional filters. Returns a single page of results.+ * @param params - Search/filter parameters+ */+ searchToolkits: (params: {+ search?: string;+ category?: string;+ limit?: number;+ cursor?: string;+ }) => client.toolkits.search(params),+ /**+ * Retrieves detailed toolkit info including auth_config_details.+ * @param slug - Toolkit slug+ */+ getToolkitDetailed: (slug: string) => client.toolkits.retrieveDetailed(slug),+ /**+ * Searches tools with optional filters. Returns a single page of results.+ * @param params - Search/filter parameters+ */+ searchTools: (params: {+ search?: string;+ toolkit_slug?: string;+ tags?: string;+ limit?: number;+ cursor?: string;+ }) => client.tools.search(params),+ /**+ * Retrieves detailed info about a single tool by slug.+ * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")+ */+ getToolDetailed: (slug: string) => client.tools.retrieve(slug),+ /**+ * Lists auth configs with optional filters. Returns a single page of results.+ * @param params - Search/filter parameters+ */+ listAuthConfigs: (params: {+ search?: string;+ toolkit_slug?: string;+ limit?: number;+ show_disabled?: boolean;+ }) => client.authConfigs.list(params),+ /**+ * Retrieves detailed info about a single auth config by its nanoid.+ * @param nanoid - Auth config ID+ */+ getAuthConfig: (nanoid: string) => client.authConfigs.retrieve(nanoid),+ /**+ * Creates a new auth config for a toolkit.+ * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)+ */+ createAuthConfig: (params: AuthConfigCreateParams) => client.authConfigs.create(params),+ deleteAuthConfig: (nanoid: string) => client.authConfigs.delete(nanoid),+ // Connected account operations (thin wrappers — see buildConnectedAccountsNamespace)+ listConnectedAccounts: (params: {+ toolkit_slugs?: string[];+ user_ids?: string[];+ statuses?: string[];+ limit?: number;+ }) => client.connectedAccounts.list(params),+ getConnectedAccount: (nanoid: string) => client.connectedAccounts.retrieve(nanoid),+ deleteConnectedAccount: (nanoid: string) => client.connectedAccounts.delete(nanoid),+ createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>+ client.connectedAccounts.createLink(params),+ ...buildTriggerInstanceRepositoryOperations(client),+ };+});++export type ComposioToolkitsRepositoryShape = Effect.Effect.Success<+ typeof makeComposioToolkitsRepository+>;++export class ComposioToolkitsRepository extends Context.Tag('services/ComposioToolkitsRepository')<+ ComposioToolkitsRepository,+ ComposioToolkitsRepositoryShape+>() {+ static readonly Default = Layer.effect(+ ComposioToolkitsRepository,+ makeComposioToolkitsRepository+ ).pipe(Layer.provide(ComposioClientLive.Default));+}++const makeComposioSessionRepository = Effect.gen(function* () {+ const client = yield* ComposioClientLive;++ return {+ createSession: (params?: { scope?: 'user' | 'project' }) => client.cli.createSession(params),+ getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),+ getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),+ authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>+ client.cli.authRealtimeChannel(params),+ };+});++export type ComposioSessionRepositoryShape = Effect.Effect.Success<+ typeof makeComposioSessionRepository+>;++export class ComposioSessionRepository extends Context.Tag('services/ComposioSessionRepository')<+ ComposioSessionRepository,+ ComposioSessionRepositoryShape+>() {+ static readonly Default = Layer.effect(+ ComposioSessionRepository,+ makeComposioSessionRepository+ ).pipe(Layer.provide(ComposioClientLive.Default));+}diff --git a/ts/packages/cli/src/services/js-package-manager-detector.ts b/ts/packages/cli/src/services/js-package-manager-detector.tsindex 219bd4d26..cfa5d937a 100644--- a/ts/packages/cli/src/services/js-package-manager-detector.ts+++ b/ts/packages/cli/src/services/js-package-manager-detector.ts@@ -1,5 +1,5 @@import { BunFileSystem } from '@effect/platform-bun';-import { Data, Effect, Option, Schema, pipe } from 'effect';+import { Data, Effect, Option, Schema, pipe, Context, Layer } from 'effect';import { FileSystem, Path } from '@effect/platform';const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));@@ -27,130 +27,135 @@ const LOCK_FILES: Record<PackageManager, string> = {const PM_PREFERENCE: PackageManager[] = ['pnpm', 'bun', 'yarn', 'npm'];// Service that attempts to detect the package manager of the project in the current working directory.-export class JsPackageManagerDetector extends Effect.Service<JsPackageManagerDetector>()(- 'services/JsPackageManagerDetector',- {- accessors: true,- effect: Effect.gen(function* () {- yield* Effect.logDebug('[JsPackageManagerDetector] Identifying JS package manager...');-- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;-- const parsePackageManager = (pm: string): Option.Option<PackageManager> => {- if (pm.startsWith('pnpm@')) return Option.some('pnpm');- if (pm.startsWith('bun@')) return Option.some('bun');- if (pm.startsWith('yarn@')) return Option.some('yarn');- if (pm.startsWith('npm@')) return Option.some('npm');+const makeJsPackageManagerDetector = Effect.gen(function* () {+ yield* Effect.logDebug('[JsPackageManagerDetector] Identifying JS package manager...');++ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;++ const parsePackageManager = (pm: string): Option.Option<PackageManager> => {+ if (pm.startsWith('pnpm@')) return Option.some('pnpm');+ if (pm.startsWith('bun@')) return Option.some('bun');+ if (pm.startsWith('yarn@')) return Option.some('yarn');+ if (pm.startsWith('npm@')) return Option.some('npm');+ return Option.none();+ };++ const PackageJsonSchema = Schema.Struct({+ packageManager: Schema.optional(Schema.String),+ }).annotations({ identifier: 'package.json' });++ const detectFromPackageJson = (+ cwd: string+ ): Effect.Effect<Option.Option<PackageManager>, JsPackageManagerError> =>+ Effect.gen(function* () {+ const contentEffect = pipe(+ fs.readFileString(path.join(cwd, 'package.json')),+ Effect.catchTag('SystemError', e =>+ Effect.fail(+ new JsPackageManagerError({ cause: e, message: 'Failed to read package.json' })+ )+ )+ );++ const content = yield* Effect.option(contentEffect);++ if (Option.isNone(content)) {return Option.none();- };-- const PackageJsonSchema = Schema.Struct({- packageManager: Schema.optional(Schema.String),- }).annotations({ identifier: 'package.json' });-- const detectFromPackageJson = (- cwd: string- ): Effect.Effect<Option.Option<PackageManager>, JsPackageManagerError> =>- Effect.gen(function* () {- const contentEffect = pipe(- fs.readFileString(path.join(cwd, 'package.json')),- Effect.catchTag('SystemError', e =>- Effect.fail(- new JsPackageManagerError({ cause: e, message: 'Failed to read package.json' })- )- )- );-- const content = yield* Effect.option(contentEffect);-- if (Option.isNone(content)) {- return Option.none();- }-- const json = yield* Effect.try({- try: () => JSON.parse(content.value) as unknown,- catch: e =>- new JsPackageManagerError({- cause: toError(e),- message: 'Failed to parse package.json',- }),- });-- const decoded = yield* pipe(- Schema.decodeUnknown(PackageJsonSchema)(json),- Effect.mapError(- e =>- new JsPackageManagerError({- cause: toError(e),- message: 'Failed to decode package.json',- })- )- );-- return Option.fromNullable(decoded.packageManager).pipe(- Option.flatMap(parsePackageManager)- );- });-- const detectRecursive = (- cwd: string- ): Effect.Effect<Option.Option<PackageManager>, JsPackageManagerError> =>- Effect.gen(function* () {- const fromPackageJson = yield* detectFromPackageJson(cwd);- if (Option.isSome(fromPackageJson)) {- return fromPackageJson;- }-- const parentDir = path.dirname(cwd);- if (parentDir === cwd) {- return Option.none();- }-- return yield* detectRecursive(parentDir);- });-- const detectJsPackageManager = (- cwd: string- ): Effect.Effect<PackageManager, JsPackageManagerError> =>- Effect.gen(function* () {- const files = yield* pipe(- fs.readDirectory(cwd),- Effect.mapError(- e =>- new JsPackageManagerError({- cause: toError(e),- message: `Failed to read directory ${cwd}`,- })- )- );-- const fileNames = files.map(f => f.toLowerCase());-- for (const pm of PM_PREFERENCE) {- if (fileNames.includes(LOCK_FILES[pm])) {- return pm;- }- }-- const result = yield* detectRecursive(cwd);-- if (Option.isSome(result)) {- return result.value;- }-- return yield* Effect.fail(+ }++ const json = yield* Effect.try({+ try: () => JSON.parse(content.value) as unknown,+ catch: e =>+ new JsPackageManagerError({+ cause: toError(e),+ message: 'Failed to parse package.json',+ }),+ });++ const decoded = yield* pipe(+ Schema.decodeUnknown(PackageJsonSchema)(json),+ Effect.mapError(+ e =>new JsPackageManagerError({- cause: new Error('Recursive lookup exhausted'),- message: 'Failed to detect package manager',+ cause: toError(e),+ message: 'Failed to decode package.json',})- );- });-- return {- detectJsPackageManager,- };- }),- dependencies: [BunFileSystem.layer, Path.layer],- }-) {}+ )+ );++ return Option.fromNullable(decoded.packageManager).pipe(Option.flatMap(parsePackageManager));+ });++ const detectRecursive = (+ cwd: string+ ): Effect.Effect<Option.Option<PackageManager>, JsPackageManagerError> =>+ Effect.gen(function* () {+ const fromPackageJson = yield* detectFromPackageJson(cwd);+ if (Option.isSome(fromPackageJson)) {+ return fromPackageJson;+ }++ const parentDir = path.dirname(cwd);+ if (parentDir === cwd) {+ return Option.none();+ }++ return yield* detectRecursive(parentDir);+ });++ const detectJsPackageManager = (+ cwd: string+ ): Effect.Effect<PackageManager, JsPackageManagerError> =>+ Effect.gen(function* () {+ const files = yield* pipe(+ fs.readDirectory(cwd),+ Effect.mapError(+ e =>+ new JsPackageManagerError({+ cause: toError(e),+ message: `Failed to read directory ${cwd}`,+ })+ )+ );++ const fileNames = files.map(f => f.toLowerCase());++ for (const pm of PM_PREFERENCE) {+ if (fileNames.includes(LOCK_FILES[pm])) {+ return pm;+ }+ }++ const result = yield* detectRecursive(cwd);++ if (Option.isSome(result)) {+ return result.value;+ }++ return yield* Effect.fail(+ new JsPackageManagerError({+ cause: new Error('Recursive lookup exhausted'),+ message: 'Failed to detect package manager',+ })+ );+ });++ return {+ detectJsPackageManager,+ };+});++export type JsPackageManagerDetectorShape = Effect.Effect.Success<+ typeof makeJsPackageManagerDetector+>;++export class JsPackageManagerDetector extends Context.Tag('services/JsPackageManagerDetector')<+ JsPackageManagerDetector,+ JsPackageManagerDetectorShape+>() {+ static readonly Default = Layer.effect(+ JsPackageManagerDetector,+ makeJsPackageManagerDetector+ ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));+}diff --git a/ts/packages/cli/src/services/node-os.ts b/ts/packages/cli/src/services/node-os.tsindex b3d3595b2..9625df7ed 100644--- a/ts/packages/cli/src/services/node-os.ts+++ b/ts/packages/cli/src/services/node-os.ts@@ -1,17 +1,23 @@// eslint-disable-next-line no-restricted-imports -- This Effect service is the sole node:os boundary for CLI source.import os from 'node:os';-import { Effect } from 'effect';+import { Context, Layer } from 'effect';++export interface NodeOsShape {+ readonly homedir: string;+ readonly tmpdir: string;+ readonly platform: NodeJS.Platform;+ readonly arch: string;+}// Injectable operating-system details for testing purposes.-export class NodeOs extends Effect.Service<NodeOs>()('services/NodeOs', {- sync: () => ({+export class NodeOs extends Context.Tag('services/NodeOs')<NodeOs, NodeOsShape>() {+ static readonly Default: Layer.Layer<NodeOs> = Layer.sync(NodeOs, () => ({homedir: os.homedir(),tmpdir: os.tmpdir(),platform: os.platform(),arch: os.arch(),- }),- dependencies: [],-}) {}+ }));+}export const defaultNodeOs = ({homedir,@@ -19,4 +25,4 @@ export const defaultNodeOs = ({}: {homedir: string;tmpdir?: string;-}) => new NodeOs({ homedir, tmpdir, platform: os.platform(), arch: os.arch() });+}): NodeOsShape => NodeOs.of({ homedir, tmpdir, platform: os.platform(), arch: os.arch() });diff --git a/ts/packages/cli/src/services/node-process.ts b/ts/packages/cli/src/services/node-process.tsindex 63119ef5a..6a9838bbf 100644--- a/ts/packages/cli/src/services/node-process.ts+++ b/ts/packages/cli/src/services/node-process.ts@@ -1,13 +1,22 @@import process from 'node:process';-import { Effect } from 'effect';+import { Context, Layer } from 'effect';-// Service to that wraps `node:process`, for testing purposes.-export class NodeProcess extends Effect.Service<NodeProcess>()('services/NodeProcess', {- sync: () => ({+export interface NodeProcessShape {+ readonly cwd: string;+ readonly execPath: string;+ readonly platform: NodeJS.Platform;+ readonly arch: string;+}++// Service that wraps `node:process`, for testing purposes.+export class NodeProcess extends Context.Tag('services/NodeProcess')<+ NodeProcess,+ NodeProcessShape+>() {+ static readonly Default: Layer.Layer<NodeProcess> = Layer.sync(NodeProcess, () => ({cwd: process.cwd(),execPath: process.execPath,platform: process.platform,arch: process.arch,- }),- dependencies: [],-}) {}+ }));+}diff --git a/ts/packages/cli/src/services/project-context.ts b/ts/packages/cli/src/services/project-context.tsindex 7a2f024f8..a4f041a18 100644--- a/ts/packages/cli/src/services/project-context.ts+++ b/ts/packages/cli/src/services/project-context.ts@@ -1,4 +1,4 @@-import { Effect, Option } from 'effect';+import { Effect, Option, Context, Layer } from 'effect';import { FileSystem, Path } from '@effect/platform';import { NodeOs } from 'src/services/node-os';import { NodeProcess } from 'src/services/node-process';@@ -50,103 +50,111 @@ const parseEnvFile = (content: string): Map<string, string> => {* 2. Per-directory .composio/.env (only allowed keys)* 3. Per-directory .composio/project.json (walk up from CWD, stop at homedir)*/-export class ProjectContext extends Effect.Service<ProjectContext>()('services/ProjectContext', {- effect: Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const proc = yield* NodeProcess;- const os = yield* NodeOs;+const makeProjectContext = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const proc = yield* NodeProcess;+ const os = yield* NodeOs;- return {- /**- * Resolves the current org+project context.- * Returns Option.none() if no context is configured.- */- resolve: Effect.gen(function* () {- // 1. Check env vars (highest priority)- const envOrgId = yield* APP_CONFIG.ORG_ID;- const envProjectId = yield* APP_CONFIG.PROJECT_ID;- if (Option.isSome(envOrgId) && Option.isSome(envProjectId)) {- yield* Effect.logDebug('ProjectContext: resolved from env vars');- return Option.some<ProjectKeys>({- orgId: envOrgId.value,- projectId: envProjectId.value,- projectName: Option.none(),- orgName: Option.none(),- email: Option.none(),- testUserId: Option.none(),- });- }+ return {+ /**+ * Resolves the current org+project context.+ * Returns Option.none() if no context is configured.+ */+ resolve: Effect.gen(function* () {+ // 1. Check env vars (highest priority)+ const envOrgId = yield* APP_CONFIG.ORG_ID;+ const envProjectId = yield* APP_CONFIG.PROJECT_ID;+ if (Option.isSome(envOrgId) && Option.isSome(envProjectId)) {+ yield* Effect.logDebug('ProjectContext: resolved from env vars');+ return Option.some<ProjectKeys>({+ orgId: envOrgId.value,+ projectId: envProjectId.value,+ projectName: Option.none(),+ orgName: Option.none(),+ email: Option.none(),+ testUserId: Option.none(),+ });+ }- // 2. Walk up from CWD, stop at homedir (not filesystem root)- const stopAt = os.homedir;+ // 2. Walk up from CWD, stop at homedir (not filesystem root)+ const stopAt = os.homedir;- for (const dir of yield* getAncestors(proc.cwd)) {- const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);+ for (const dir of yield* getAncestors(proc.cwd)) {+ const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);- // 2a. Check .composio/.env- const envFilePath = path.join(composioDir, constants.PROJECT_ENV_FILE_NAME);- const envExists = yield* fs- .exists(envFilePath)- .pipe(Effect.catchAll(() => Effect.succeed(false)));- if (envExists) {- const envContent = yield* fs- .readFileString(envFilePath)- .pipe(Effect.catchAll(() => Effect.succeed('')));- const envMap = parseEnvFile(envContent);- const envFileOrgId = envMap.get('COMPOSIO_ORG_ID');- const envFileProjectId = envMap.get('COMPOSIO_PROJECT_ID');- if (envFileOrgId && envFileProjectId) {- yield* Effect.logDebug(`ProjectContext: resolved from ${envFilePath}`);- return Option.some<ProjectKeys>({- orgId: envFileOrgId,- projectId: envFileProjectId,- projectName: Option.none(),- orgName: Option.none(),- email: Option.none(),- testUserId: Option.none(),- });- }+ // 2a. Check .composio/.env+ const envFilePath = path.join(composioDir, constants.PROJECT_ENV_FILE_NAME);+ const envExists = yield* fs+ .exists(envFilePath)+ .pipe(Effect.catchAll(() => Effect.succeed(false)));+ if (envExists) {+ const envContent = yield* fs+ .readFileString(envFilePath)+ .pipe(Effect.catchAll(() => Effect.succeed('')));+ const envMap = parseEnvFile(envContent);+ const envFileOrgId = envMap.get('COMPOSIO_ORG_ID');+ const envFileProjectId = envMap.get('COMPOSIO_PROJECT_ID');+ if (envFileOrgId && envFileProjectId) {+ yield* Effect.logDebug(`ProjectContext: resolved from ${envFilePath}`);+ return Option.some<ProjectKeys>({+ orgId: envFileOrgId,+ projectId: envFileProjectId,+ projectName: Option.none(),+ orgName: Option.none(),+ email: Option.none(),+ testUserId: Option.none(),+ });}+ }- // 2b. Check .composio/project.json- const projectJsonPath = path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME);- const jsonExists = yield* fs- .exists(projectJsonPath)- .pipe(Effect.catchAll(() => Effect.succeed(false)));- if (jsonExists) {- const content = yield* fs- .readFileString(projectJsonPath)- .pipe(Effect.catchAll(() => Effect.succeed('')));- if (content) {- const keysOpt = yield* projectKeysFromJSON(content).pipe(- Effect.map(Option.some),- Effect.catchAll(error =>- Effect.gen(function* () {- yield* Effect.logDebug(- `ProjectContext: corrupt project.json at ${projectJsonPath}, skipping:`,- error- );- return Option.none();- })- )- );- if (Option.isSome(keysOpt)) {- yield* Effect.logDebug(`ProjectContext: resolved from ${projectJsonPath}`);- return keysOpt;- }+ // 2b. Check .composio/project.json+ const projectJsonPath = path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME);+ const jsonExists = yield* fs+ .exists(projectJsonPath)+ .pipe(Effect.catchAll(() => Effect.succeed(false)));+ if (jsonExists) {+ const content = yield* fs+ .readFileString(projectJsonPath)+ .pipe(Effect.catchAll(() => Effect.succeed('')));+ if (content) {+ const keysOpt = yield* projectKeysFromJSON(content).pipe(+ Effect.map(Option.some),+ Effect.catchAll(error =>+ Effect.gen(function* () {+ yield* Effect.logDebug(+ `ProjectContext: corrupt project.json at ${projectJsonPath}, skipping:`,+ error+ );+ return Option.none();+ })+ )+ );+ if (Option.isSome(keysOpt)) {+ yield* Effect.logDebug(`ProjectContext: resolved from ${projectJsonPath}`);+ return keysOpt;}}-- // Stop at homedir to avoid reading from system directories- if (dir === stopAt) break;}- // 3. Nothing found- yield* Effect.logDebug('ProjectContext: no context found');- return Option.none<ProjectKeys>();- }).pipe(Effect.provideService(Path.Path, path)),- };- }),- dependencies: [Path.layer],-}) {}+ // Stop at homedir to avoid reading from system directories+ if (dir === stopAt) break;+ }++ // 3. Nothing found+ yield* Effect.logDebug('ProjectContext: no context found');+ return Option.none<ProjectKeys>();+ }).pipe(Effect.provideService(Path.Path, path)),+ };+});++export type ProjectContextShape = Effect.Effect.Success<typeof makeProjectContext>;++export class ProjectContext extends Context.Tag('services/ProjectContext')<+ ProjectContext,+ ProjectContextShape+>() {+ static readonly Default = Layer.effect(ProjectContext, makeProjectContext).pipe(+ Layer.provide(Path.layer)+ );+}diff --git a/ts/packages/cli/src/services/project-environment-detector.ts b/ts/packages/cli/src/services/project-environment-detector.tsindex 56fcdf480..4855e0e01 100644--- a/ts/packages/cli/src/services/project-environment-detector.ts+++ b/ts/packages/cli/src/services/project-environment-detector.ts@@ -1,6 +1,6 @@import { BunFileSystem } from '@effect/platform-bun';import { FileSystem, Path } from '@effect/platform';-import { Data, Effect, Match } from 'effect';+import { Data, Effect, Match, Context, Layer } from 'effect';import { getAncestors } from 'src/utils/get-ancestors';import { UNPREFIXED_CONFIG } from 'src/effects/app-config';import { loadHostConfig } from 'src/services/config';@@ -551,48 +551,56 @@ const detectPythonPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>// Service// ----------------------------------------------------------------------------export class ProjectEnvironmentDetector extends Effect.Service<ProjectEnvironmentDetector>()(- 'services/ProjectEnvironmentDetector',- {- effect: Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;-- const detectProjectEnvironment = (- cwd: string- ): Effect.Effect<ProjectEnvironment, ProjectEnvironmentDetectorError> =>- Effect.gen(function* () {- const detection = yield* detectLanguage(fs, cwd);-- if (detection.language === 'python') {- const packageManager = yield* detectPythonPackageManager(fs, detection.rootDir);- return {- kind: 'python',- language: 'python',- packageManager,- rootDir: detection.rootDir,- evidence: detection.evidence.evidence,- } satisfies ProjectEnvironment;- }-- const packageManager = yield* detectJsPackageManager(fs, detection.rootDir);- return {- kind: 'js',- language: detection.language,- packageManager,- rootDir: detection.rootDir,- evidence: detection.evidence.evidence,- } satisfies ProjectEnvironment;- }).pipe(Effect.provideService(Path.Path, path));+const makeProjectEnvironmentDetector = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const detectProjectEnvironment = (+ cwd: string+ ): Effect.Effect<ProjectEnvironment, ProjectEnvironmentDetectorError> =>+ Effect.gen(function* () {+ const detection = yield* detectLanguage(fs, cwd);++ if (detection.language === 'python') {+ const packageManager = yield* detectPythonPackageManager(fs, detection.rootDir);+ return {+ kind: 'python',+ language: 'python',+ packageManager,+ rootDir: detection.rootDir,+ evidence: detection.evidence.evidence,+ } satisfies ProjectEnvironment;+ }++ const packageManager = yield* detectJsPackageManager(fs, detection.rootDir);return {- detectProjectEnvironment,- detectJsPackageManager: (cwd: string) =>- detectJsPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),- detectPythonPackageManager: (cwd: string) =>- detectPythonPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),- };- }),- dependencies: [BunFileSystem.layer, Path.layer],- }-) {}+ kind: 'js',+ language: detection.language,+ packageManager,+ rootDir: detection.rootDir,+ evidence: detection.evidence.evidence,+ } satisfies ProjectEnvironment;+ }).pipe(Effect.provideService(Path.Path, path));++ return {+ detectProjectEnvironment,+ detectJsPackageManager: (cwd: string) =>+ detectJsPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),+ detectPythonPackageManager: (cwd: string) =>+ detectPythonPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),+ };+});++export type ProjectEnvironmentDetectorShape = Effect.Effect.Success<+ typeof makeProjectEnvironmentDetector+>;++export class ProjectEnvironmentDetector extends Context.Tag('services/ProjectEnvironmentDetector')<+ ProjectEnvironmentDetector,+ ProjectEnvironmentDetectorShape+>() {+ static readonly Default = Layer.effect(+ ProjectEnvironmentDetector,+ makeProjectEnvironmentDetector+ ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));+}diff --git a/ts/packages/cli/src/services/setup-skill-installer.ts b/ts/packages/cli/src/services/setup-skill-installer.tsindex 9536df5d1..22b85e5a7 100644--- a/ts/packages/cli/src/services/setup-skill-installer.ts+++ b/ts/packages/cli/src/services/setup-skill-installer.ts@@ -1,5 +1,5 @@import { FileSystem, HttpClient, Path } from '@effect/platform';-import { Config, Effect } from 'effect';+import { Config, Effect, Context, Layer } from 'effect';import {inferSkillReleaseChannel,installSkill,@@ -117,39 +117,42 @@ export const removeManagedClaudeSkill = (home: string) =>return changed;}).pipe(Effect.uninterruptible);-export class SetupSkillInstaller extends Effect.Service<SetupSkillInstaller>()(- 'services/SetupSkillInstaller',- {- effect: Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const os = yield* NodeOs;- const isCurrent = (releaseTag: string) =>- checkClaudeSkillCurrent(fs, path, os.homedir, releaseTag);- const releaseTag = yield* Effect.cached(- resolveSetupSkillReleaseTag().pipe(- Effect.provideService(FileSystem.FileSystem, fs),- Effect.provideService(Path.Path, path)- )- );+const makeSetupSkillInstaller = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const os = yield* NodeOs;+ const isCurrent = (releaseTag: string) =>+ checkClaudeSkillCurrent(fs, path, os.homedir, releaseTag);+ const releaseTag = yield* Effect.cached(+ resolveSetupSkillReleaseTag().pipe(+ Effect.provideService(FileSystem.FileSystem, fs),+ Effect.provideService(Path.Path, path)+ )+ );++ return {+ isClaudeSkillReady: Effect.flatMap(releaseTag, isCurrent),+ hasManagedClaudeSkill: hasManagedClaudeSkill(os.homedir),+ ensureClaudeSkill: Effect.gen(function* () {+ const targetReleaseTag = yield* releaseTag;+ if (yield* isCurrent(targetReleaseTag)) return false;- return {- isClaudeSkillReady: Effect.flatMap(releaseTag, isCurrent),- hasManagedClaudeSkill: hasManagedClaudeSkill(os.homedir),- ensureClaudeSkill: Effect.gen(function* () {- const targetReleaseTag = yield* releaseTag;- if (yield* isCurrent(targetReleaseTag)) return false;-- yield* installSkill({- target: 'claude',- releaseTag: targetReleaseTag,- silent: true,- });- return true;- }),- removeClaudeSkill: removeManagedClaudeSkill(os.homedir),- };+ yield* installSkill({+ target: 'claude',+ releaseTag: targetReleaseTag,+ silent: true,+ });+ return true;}),- dependencies: [],- }-) {}+ removeClaudeSkill: removeManagedClaudeSkill(os.homedir),+ };+});++export type SetupSkillInstallerShape = Effect.Effect.Success<typeof makeSetupSkillInstaller>;++export class SetupSkillInstaller extends Context.Tag('services/SetupSkillInstaller')<+ SetupSkillInstaller,+ SetupSkillInstallerShape+>() {+ static readonly Default = Layer.effect(SetupSkillInstaller, makeSetupSkillInstaller);+}diff --git a/ts/packages/cli/src/services/toolkit-slug-catalog.ts b/ts/packages/cli/src/services/toolkit-slug-catalog.tsindex 41047b728..98c79fc3a 100644--- a/ts/packages/cli/src/services/toolkit-slug-catalog.ts+++ b/ts/packages/cli/src/services/toolkit-slug-catalog.ts@@ -1,4 +1,4 @@-import { DateTime, Duration, Effect, Option, Ref } from 'effect';+import { DateTime, Duration, Effect, Option, Ref, Context, Layer } from 'effect';import { BAKED_TOOLKIT_SLUGS } from 'src/generated/toolkit-slugs';import { ComposioToolkitsRepository } from 'src/services/composio-clients';import {@@ -100,28 +100,32 @@ const loadLocalToolkitSlugs = Effect.gen(function* () {* Memoizing also gates the staleness refresh to one fork per run, where an* unmemoized read forked — and rewrote the file — once per resolution.*/-export class ToolkitSlugCatalog extends Effect.Service<ToolkitSlugCatalog>()(- 'services/ToolkitSlugCatalog',- {- effect: Effect.gen(function* () {- const local = yield* Effect.cached(loadLocalToolkitSlugs);- const hasRecorded = yield* Ref.make(false);-- /**- * Records slugs learned from a catalog fetch, in the background, at most- * once per run. Every miss in a run merges the same memoized fetch into- * the same local list, so later calls would fork a daemon fiber only to- * rewrite an identical file — and each pending fiber holds the finished- * command open a little longer.- */- const remember = (slugs: ReadonlyArray<string>): Effect.Effect<void> =>- Effect.gen(function* () {- const alreadyRecorded = yield* Ref.getAndSet(hasRecorded, true);- if (alreadyRecorded) return;- yield* Effect.forkDaemon(writeKnownToolkitSlugs(slugs));- });-- return { local, remember };- }),- }-) {}+const makeToolkitSlugCatalog = Effect.gen(function* () {+ const local = yield* Effect.cached(loadLocalToolkitSlugs);+ const hasRecorded = yield* Ref.make(false);++ /**+ * Records slugs learned from a catalog fetch, in the background, at most+ * once per run. Every miss in a run merges the same memoized fetch into+ * the same local list, so later calls would fork a daemon fiber only to+ * rewrite an identical file — and each pending fiber holds the finished+ * command open a little longer.+ */+ const remember = (slugs: ReadonlyArray<string>): Effect.Effect<void> =>+ Effect.gen(function* () {+ const alreadyRecorded = yield* Ref.getAndSet(hasRecorded, true);+ if (alreadyRecorded) return;+ yield* Effect.forkDaemon(writeKnownToolkitSlugs(slugs));+ });++ return { local, remember };+});++export type ToolkitSlugCatalogShape = Effect.Effect.Success<typeof makeToolkitSlugCatalog>;++export class ToolkitSlugCatalog extends Context.Tag('services/ToolkitSlugCatalog')<+ ToolkitSlugCatalog,+ ToolkitSlugCatalogShape+>() {+ static readonly Default = Layer.effect(ToolkitSlugCatalog, makeToolkitSlugCatalog);+}diff --git a/ts/packages/cli/src/services/triggers-realtime.ts b/ts/packages/cli/src/services/triggers-realtime.tsindex 618ff3f03..85fbb6a62 100644--- a/ts/packages/cli/src/services/triggers-realtime.ts+++ b/ts/packages/cli/src/services/triggers-realtime.ts@@ -1,4 +1,15 @@-import { Array as Arr, Data, Effect, Either, Option, Predicate, Runtime, Schema } from 'effect';+import {+ Array as Arr,+ Data,+ Effect,+ Either,+ Option,+ Predicate,+ Runtime,+ Schema,+ Context,+ Layer,+} from 'effect';import { JsonRecordSchema } from 'src/effects/json';import {ComposioClientSingleton,@@ -76,241 +87,242 @@ export const resolvePusherConstructor = (* - `cli.realtime.credentials` to fetch Pusher credentials + project nano id* - `cli.realtime.auth` for private channel auth callbacks*/-export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(- 'services/TriggersRealtime',- {- effect: Effect.gen(function* () {- const sessionRepo = yield* ComposioSessionRepository;- const clientSingleton = yield* ComposioClientSingleton;- const runtime = yield* Effect.runtime<never>();-- const listenWith = (params: {- getRealtimeCredentials: () => Effect.Effect<- CliRealtimeCredentialsResponse,- TriggerRealtimeSubscriptionError- >;- authRealtimeChannel: (params: {- channel_name: string;- socket_id: string;- }) => Effect.Effect<CliRealtimeAuthResponse, TriggerRealtimeSubscriptionError>;- onEvent: (data: RawRealtimeEvent) => void;- }) =>- Effect.acquireUseRelease(- Effect.gen(function* () {- const creds = yield* params.getRealtimeCredentials();- const channelName = `private-cli-${creds.project_id}`;-- const pusherModule = yield* Effect.tryPromise({- try: () => import('pusher-js'),- catch: subscriptionError('Failed to load the realtime client'),- });+const makeTriggersRealtime = Effect.gen(function* () {+ const sessionRepo = yield* ComposioSessionRepository;+ const clientSingleton = yield* ComposioClientSingleton;+ const runtime = yield* Effect.runtime<never>();++ const listenWith = (params: {+ getRealtimeCredentials: () => Effect.Effect<+ CliRealtimeCredentialsResponse,+ TriggerRealtimeSubscriptionError+ >;+ authRealtimeChannel: (params: {+ channel_name: string;+ socket_id: string;+ }) => Effect.Effect<CliRealtimeAuthResponse, TriggerRealtimeSubscriptionError>;+ onEvent: (data: RawRealtimeEvent) => void;+ }) =>+ Effect.acquireUseRelease(+ Effect.gen(function* () {+ const creds = yield* params.getRealtimeCredentials();+ const channelName = `private-cli-${creds.project_id}`;++ const pusherModule = yield* Effect.tryPromise({+ try: () => import('pusher-js'),+ catch: subscriptionError('Failed to load the realtime client'),+ });- const Pusher = yield* resolvePusherConstructor(pusherModule).pipe(- Effect.mapError(- subscriptionError('Realtime client module does not expose a constructor')- )- );+ const Pusher = yield* resolvePusherConstructor(pusherModule).pipe(+ Effect.mapError(subscriptionError('Realtime client module does not expose a constructor'))+ );- const pusher = yield* Effect.try({- try: () =>- new Pusher(creds.pusher_key, {- cluster: creds.pusher_cluster,- channelAuthorization: {- customHandler: (authOptions, callback) => {- const channel_name = authOptions.channelName;- const socket_id = authOptions.socketId;-- const doAuth = async () => {- const response = await Runtime.runPromise(runtime)(- params.authRealtimeChannel({- channel_name,- socket_id,- })- );- // Pusher private channels verify signatures without channel_data.- // Some auth endpoints may still return channel_data, which can cause- // "Invalid signature" if included in the verification input.- const normalizedResponse = channel_name.startsWith('private-')- ? { auth: response.auth }- : response;- return normalizedResponse;- };-- void doAuth()- .then(data => callback(null, data))- .catch(cause =>- callback(cause instanceof Error ? cause : new Error(String(cause)), null)- );- },- },- }),- catch: subscriptionError('Failed to construct the realtime client'),- });+ const pusher = yield* Effect.try({+ try: () =>+ new Pusher(creds.pusher_key, {+ cluster: creds.pusher_cluster,+ channelAuthorization: {+ customHandler: (authOptions, callback) => {+ const channel_name = authOptions.channelName;+ const socket_id = authOptions.socketId;++ const doAuth = async () => {+ const response = await Runtime.runPromise(runtime)(+ params.authRealtimeChannel({+ channel_name,+ socket_id,+ })+ );+ // Pusher private channels verify signatures without channel_data.+ // Some auth endpoints may still return channel_data, which can cause+ // "Invalid signature" if included in the verification input.+ const normalizedResponse = channel_name.startsWith('private-')+ ? { auth: response.auth }+ : response;+ return normalizedResponse;+ };++ void doAuth()+ .then(data => callback(null, data))+ .catch(cause =>+ callback(cause instanceof Error ? cause : new Error(String(cause)), null)+ );+ },+ },+ }),+ catch: subscriptionError('Failed to construct the realtime client'),+ });- const channel = pusher.subscribe(channelName);-- // Pusher has a 10 KB per-message limit. When the Composio backend- // produces a trigger payload that exceeds this, it splits the JSON- // into numbered chunks sent as separate `chunked-trigger_to_client`- // events. We reassemble them here by accumulating chunks keyed by- // event id, then joining once the final chunk arrives and every- // intermediate index is present.- //- // Guard-rails:- // - Reject chunk indices outside [0, MAX_CHUNK_INDEX] to prevent a- // single malformed event from allocating a huge sparse array.- // - Evict incomplete entries older than CHUNK_TTL_MS so that lost- // chunks don't leak memory over long-running sessions.- // - Cap the total number of in-flight reassemblies to bound memory- // usage even under pathological input.- const MAX_CHUNK_INDEX = 1_000;- const CHUNK_TTL_MS = 60_000;- const MAX_PENDING_CHUNKS = 100;-- type PendingChunkedEvent = {- chunks: string[];- receivedFinal: boolean;- createdAt: number;- };-- const chunkedEvents = new Map<string, PendingChunkedEvent>();-- // Periodic sweep: drop entries that have been sitting incomplete for- // longer than CHUNK_TTL_MS. Runs every CHUNK_TTL_MS and is cleared- // on shutdown.- const cleanupInterval = setInterval(() => {- const now = Date.now();- for (const [id, entry] of chunkedEvents) {- if (now - entry.createdAt > CHUNK_TTL_MS) {- chunkedEvents.delete(id);- }- }- }, CHUNK_TTL_MS);-- channel.bind('trigger_to_client', (eventData: unknown) => {- params.onEvent(Option.getOrElse(decodeRawRealtimeEvent(eventData), () => ({})));- });+ const channel = pusher.subscribe(channelName);++ // Pusher has a 10 KB per-message limit. When the Composio backend+ // produces a trigger payload that exceeds this, it splits the JSON+ // into numbered chunks sent as separate `chunked-trigger_to_client`+ // events. We reassemble them here by accumulating chunks keyed by+ // event id, then joining once the final chunk arrives and every+ // intermediate index is present.+ //+ // Guard-rails:+ // - Reject chunk indices outside [0, MAX_CHUNK_INDEX] to prevent a+ // single malformed event from allocating a huge sparse array.+ // - Evict incomplete entries older than CHUNK_TTL_MS so that lost+ // chunks don't leak memory over long-running sessions.+ // - Cap the total number of in-flight reassemblies to bound memory+ // usage even under pathological input.+ const MAX_CHUNK_INDEX = 1_000;+ const CHUNK_TTL_MS = 60_000;+ const MAX_PENDING_CHUNKS = 100;++ type PendingChunkedEvent = {+ chunks: string[];+ receivedFinal: boolean;+ createdAt: number;+ };++ const chunkedEvents = new Map<string, PendingChunkedEvent>();++ // Periodic sweep: drop entries that have been sitting incomplete for+ // longer than CHUNK_TTL_MS. Runs every CHUNK_TTL_MS and is cleared+ // on shutdown.+ const cleanupInterval = setInterval(() => {+ const now = Date.now();+ for (const [id, entry] of chunkedEvents) {+ if (now - entry.createdAt > CHUNK_TTL_MS) {+ chunkedEvents.delete(id);+ }+ }+ }, CHUNK_TTL_MS);++ channel.bind('trigger_to_client', (eventData: unknown) => {+ params.onEvent(Option.getOrElse(decodeRawRealtimeEvent(eventData), () => ({})));+ });- channel.bind('chunked-trigger_to_client', (data: unknown) => {- const decoded = decodeChunkedRealtimeEvent(data);- if (Option.isNone(decoded)) {- return;- }- const typed = decoded.value;-- // Reject non-integer or out-of-range indices to prevent a single- // malformed event from creating a massive sparse array.- if (- !Number.isInteger(typed.index) ||- typed.index < 0 ||- typed.index > MAX_CHUNK_INDEX- ) {- return;- }-- if (!chunkedEvents.has(typed.id)) {- // If we already have too many in-flight reassemblies, drop the- // oldest one to make room.- if (chunkedEvents.size >= MAX_PENDING_CHUNKS) {- const oldestId = chunkedEvents.keys().next().value;- if (oldestId !== undefined) chunkedEvents.delete(oldestId);- }-- chunkedEvents.set(typed.id, {- chunks: [],- receivedFinal: false,- createdAt: Date.now(),- });- }-- const current = chunkedEvents.get(typed.id);- if (!current) {- return;- }- current.chunks[typed.index] = typed.chunk;- if (typed.final) {- current.receivedFinal = true;- }-- // Completeness check: for a dense array, .length equals the- // number of defined keys. For a sparse array (missing chunks),- // .length is highestIndex + 1 but Object.keys only counts the- // indices that were actually assigned, so the two diverge.- if (- current.receivedFinal &&- current.chunks.length === Object.keys(current.chunks).length- ) {- const reassembled = current.chunks.join('');- chunkedEvents.delete(typed.id);- // Silently discard events that fail to parse after chunk- // reassembly; the buffer entry is already cleared either way.- const parsed = Either.try((): unknown => JSON.parse(reassembled)).pipe(- Either.getRight,- Option.flatMap(decodeRawRealtimeEvent)- );- if (Option.isSome(parsed)) {- params.onEvent(parsed.value);- }- }+ channel.bind('chunked-trigger_to_client', (data: unknown) => {+ const decoded = decodeChunkedRealtimeEvent(data);+ if (Option.isNone(decoded)) {+ return;+ }+ const typed = decoded.value;++ // Reject non-integer or out-of-range indices to prevent a single+ // malformed event from creating a massive sparse array.+ if (!Number.isInteger(typed.index) || typed.index < 0 || typed.index > MAX_CHUNK_INDEX) {+ return;+ }++ if (!chunkedEvents.has(typed.id)) {+ // If we already have too many in-flight reassemblies, drop the+ // oldest one to make room.+ if (chunkedEvents.size >= MAX_PENDING_CHUNKS) {+ const oldestId = chunkedEvents.keys().next().value;+ if (oldestId !== undefined) chunkedEvents.delete(oldestId);+ }++ chunkedEvents.set(typed.id, {+ chunks: [],+ receivedFinal: false,+ createdAt: Date.now(),});+ }++ const current = chunkedEvents.get(typed.id);+ if (!current) {+ return;+ }+ current.chunks[typed.index] = typed.chunk;+ if (typed.final) {+ current.receivedFinal = true;+ }++ // Completeness check: for a dense array, .length equals the+ // number of defined keys. For a sparse array (missing chunks),+ // .length is highestIndex + 1 but Object.keys only counts the+ // indices that were actually assigned, so the two diverge.+ if (+ current.receivedFinal &&+ current.chunks.length === Object.keys(current.chunks).length+ ) {+ const reassembled = current.chunks.join('');+ chunkedEvents.delete(typed.id);+ // Silently discard events that fail to parse after chunk+ // reassembly; the buffer entry is already cleared either way.+ const parsed = Either.try((): unknown => JSON.parse(reassembled)).pipe(+ Either.getRight,+ Option.flatMap(decodeRawRealtimeEvent)+ );+ if (Option.isSome(parsed)) {+ params.onEvent(parsed.value);+ }+ }+ });- return {- shutdown: async () => {- clearInterval(cleanupInterval);- channel.unbind_all?.();- pusher.unsubscribe(channelName);- pusher.disconnect();- },- };+ return {+ shutdown: async () => {+ clearInterval(cleanupInterval);+ channel.unbind_all?.();+ pusher.unsubscribe(channelName);+ pusher.disconnect();+ },+ };+ }),+ () => Effect.never,+ resource =>+ Effect.tryPromise({+ try: () => resource.shutdown(),+ catch: subscriptionError('Failed to shut down the realtime subscription'),+ }).pipe(Effect.catchAll(() => Effect.void))+ );++ const listen = (onEvent: (data: RawRealtimeEvent) => void) =>+ listenWith({+ getRealtimeCredentials: () =>+ sessionRepo+ .getRealtimeCredentials()+ .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),+ authRealtimeChannel: params =>+ sessionRepo+ .authRealtimeChannel(params)+ .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),+ onEvent,+ });++ const listenInProject = (+ scope: { orgId: string; projectId: string },+ onEvent: (data: RawRealtimeEvent) => void+ ) =>+ Effect.gen(function* () {+ const client = yield* clientSingleton.getFor({+ orgId: scope.orgId,+ projectId: scope.projectId,+ });++ return yield* listenWith({+ getRealtimeCredentials: () =>+ Effect.tryPromise({+ try: () => client.cli.realtime.credentials(),+ catch: subscriptionError('Failed to fetch realtime credentials'),}),- () => Effect.never,- resource =>- Effect.tryPromise({- try: () => resource.shutdown(),- catch: subscriptionError('Failed to shut down the realtime subscription'),- }).pipe(Effect.catchAll(() => Effect.void))- );+ authRealtimeChannel: params =>+ Effect.tryPromise({+ try: () => client.cli.realtime.auth(params),+ catch: subscriptionError('Failed to authorize the realtime channel'),+ }),+ onEvent,+ });+ });- const listen = (onEvent: (data: RawRealtimeEvent) => void) =>- listenWith({- getRealtimeCredentials: () =>- sessionRepo- .getRealtimeCredentials()- .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),- authRealtimeChannel: params =>- sessionRepo- .authRealtimeChannel(params)- .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),- onEvent,- });+ return { listen, listenInProject };+});- const listenInProject = (- scope: { orgId: string; projectId: string },- onEvent: (data: RawRealtimeEvent) => void- ) =>- Effect.gen(function* () {- const client = yield* clientSingleton.getFor({- orgId: scope.orgId,- projectId: scope.projectId,- });-- return yield* listenWith({- getRealtimeCredentials: () =>- Effect.tryPromise({- try: () => client.cli.realtime.credentials(),- catch: subscriptionError('Failed to fetch realtime credentials'),- }),- authRealtimeChannel: params =>- Effect.tryPromise({- try: () => client.cli.realtime.auth(params),- catch: subscriptionError('Failed to authorize the realtime channel'),- }),- onEvent,- });- });+export type TriggersRealtimeShape = Effect.Effect.Success<typeof makeTriggersRealtime>;- return { listen, listenInProject };- }),- dependencies: [ComposioSessionRepository.Default, ComposioClientSingleton.Default],- }-) {}+export class TriggersRealtime extends Context.Tag('services/TriggersRealtime')<+ TriggersRealtime,+ TriggersRealtimeShape+>() {+ static readonly Default = Layer.effect(TriggersRealtime, makeTriggersRealtime).pipe(+ Layer.provide(+ Layer.mergeAll(ComposioSessionRepository.Default, ComposioClientSingleton.Default)+ )+ );+}diff --git a/ts/packages/cli/src/services/update-check.ts b/ts/packages/cli/src/services/update-check.tsindex 4108c22b9..1e7b8ea2f 100644--- a/ts/packages/cli/src/services/update-check.ts+++ b/ts/packages/cli/src/services/update-check.ts@@ -4,7 +4,7 @@ import { Config, Data, Effect, Layer, Option, Predicate, Schema } from 'effect';import semver from 'semver';import { bold, cyanBright, dim } from 'src/ui/colors';import { APP_VERSION, GITHUB_REPO } from '../constants';-import { NodeOs } from './node-os';+import { NodeOs, type NodeOsShape } from './node-os';import { resolveRunningCliVersion } from './run-companion-modules';import { TerminalUI } from './terminal-ui';@@ -84,7 +84,7 @@ const defaultStateFile = Effect.gen(function* () {return path.join(os.homedir, '.composio', 'update-check.json');});-function getCurrentBinaryAssetName(os: Pick<NodeOs, 'platform' | 'arch'>): string | undefined {+function getCurrentBinaryAssetName(os: Pick<NodeOsShape, 'platform' | 'arch'>): string | undefined {const { platform } = os;const rawArch: string = os.arch;if (platform !== 'darwin' && platform !== 'linux') return undefined;diff --git a/ts/packages/cli/src/services/upgrade-binary.ts b/ts/packages/cli/src/services/upgrade-binary.tsindex eef4d3df9..f3bbe6dd1 100644--- a/ts/packages/cli/src/services/upgrade-binary.ts+++ b/ts/packages/cli/src/services/upgrade-binary.ts@@ -8,6 +8,8 @@ import {Record as EffectRecord,Scope,Stream,+ Context,+ Layer,} from 'effect';import { HttpClient, HttpClientResponse, FileSystem, Path } from '@effect/platform';import { APP_VERSION } from '../constants';@@ -725,19 +727,26 @@ const upgrade = (});// Service to manage CLI binary upgrades-export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {- accessors: true,- effect: Effect.gen(function* () {- const ctx: UpgradeBinaryContext = {- httpClient: yield* HttpClient.HttpClient,- fs: yield* FileSystem.FileSystem,- path: yield* Path.Path,- githubConfig: yield* GITHUB_CONFIG_ALL,- };+const makeUpgradeBinary = Effect.gen(function* () {+ const ctx: UpgradeBinaryContext = {+ httpClient: yield* HttpClient.HttpClient,+ fs: yield* FileSystem.FileSystem,+ path: yield* Path.Path,+ githubConfig: yield* GITHUB_CONFIG_ALL,+ };++ return {+ upgrade: (options: { prerelease?: boolean; tag?: string } = {}) => upgrade(ctx, options),+ } as const;+});- return {- upgrade: (options: { prerelease?: boolean; tag?: string } = {}) => upgrade(ctx, options),- } as const;- }),- dependencies: [Path.layer],-}) {}+export type UpgradeBinaryShape = Effect.Effect.Success<typeof makeUpgradeBinary>;++export class UpgradeBinary extends Context.Tag('services/UpgradeBinary')<+ UpgradeBinary,+ UpgradeBinaryShape+>() {+ static readonly Default = Layer.effect(UpgradeBinary, makeUpgradeBinary).pipe(+ Layer.provide(Path.layer)+ );+}diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.tsindex 0d98583e7..b75417e4d 100644--- a/ts/packages/cli/test/__utils__/services/test-layer.ts+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts@@ -70,10 +70,13 @@ import type {import { Stdin } from 'src/services/stdin';import { ProjectContext } from 'src/services/project-context';import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';-import { CommandRunner } from 'src/services/command-runner';+import { CommandRunner, type CommandRunnerShape } from 'src/services/command-runner';import { TerminalUI } from 'src/services/terminal-ui';import { CommandExecutor } from '@effect/platform';-import { SetupSkillInstaller } from 'src/services/setup-skill-installer';+import {+ SetupSkillInstaller,+ type SetupSkillInstallerShape,+} from 'src/services/setup-skill-installer';export interface TestLiveInput {/**@@ -213,10 +216,10 @@ export interface TestLiveInput {* When set, the `CommandRunner` service uses the provided mock instance.* When NOT set, uses a default mock that always returns exit code 0.*/- commandRunner?: CommandRunner;+ commandRunner?: CommandRunnerShape;/** Override setup's Claude skill installer. Defaults to an idempotent no-op. */- setupSkillInstaller?: SetupSkillInstaller;+ setupSkillInstaller?: SetupSkillInstallerShape;/*** Override TerminalUI behavior for tests.@@ -345,7 +348,7 @@ export const TestLayer = (input?: TestLiveInput) =>const ComposioToolkitsRepositoryTest = Layer.succeed(ComposioToolkitsRepository,- new ComposioToolkitsRepository({+ ComposioToolkitsRepository.of({getToolkits: () => Effect.succeed(toolkitsData.toolkits),getToolkitsBySlugs: (slugs: ReadonlyArray<string>) => {const normalizedSlugs = new Set(slugs.map(s => String.toLowerCase(s)));@@ -792,7 +795,7 @@ export const TestLayer = (input?: TestLiveInput) =>const ComposioSessionRepositoryTest = yield* setupComposioSessionRepository();const TriggersRealtimeTest = Layer.succeed(TriggersRealtime,- new TriggersRealtime({+ TriggersRealtime.of({listen: onEvent =>Effect.gen(function* () {yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));@@ -809,7 +812,7 @@ export const TestLayer = (input?: TestLiveInput) =>// Mock operating-system detailsconst NodeOsTest = Layer.succeed(NodeOs,- new NodeOs({+ NodeOs.of({homedir: cwd,tmpdir: tempy.rootTemporaryDirectory,arch: 'arm64',@@ -820,7 +823,7 @@ export const TestLayer = (input?: TestLiveInput) =>// Mock `node:process`const NodeProcessTest = Layer.succeed(NodeProcess,- new NodeProcess({+ NodeProcess.of({cwd,execPath: input?.execPath ? path.resolve(cwd, input.execPath) : path.join(cwd, 'composio'),platform: 'darwin',@@ -1210,7 +1213,7 @@ export const TestLayer = (input?: TestLiveInput) =>const ComposioClientSingletonTest = Layer.succeed(ComposioClientSingleton,- new ComposioClientSingleton({+ ComposioClientSingleton.of({get: Effect.fn(function* () {return mockComposioClient;}),@@ -1262,7 +1265,7 @@ export const TestLayer = (input?: TestLiveInput) =>? Layer.succeed(CommandRunner, input.commandRunner): Layer.succeed(CommandRunner,- new CommandRunner({+ CommandRunner.of({run: () => Effect.succeed(CommandExecutor.ExitCode(0)),capture: () =>Effect.succeed({@@ -1281,7 +1284,7 @@ export const TestLayer = (input?: TestLiveInput) =>const SetupSkillInstallerTest = Layer.succeed(SetupSkillInstaller,input?.setupSkillInstaller ??- new SetupSkillInstaller({+ SetupSkillInstaller.of({isClaudeSkillReady: Effect.succeed(false),hasManagedClaudeSkill: Effect.succeed(false),ensureClaudeSkill: Effect.succeed(false),@@ -1528,7 +1531,7 @@ function setupComposioSessionRepository() {email: accountEmail,};- const composioSessionRepositoryTest = new ComposioSessionRepository({+ const composioSessionRepositoryTest = ComposioSessionRepository.of({createSession: () =>Effect.succeed({id: sessionId,diff --git a/ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts b/ts/packages/cli/test/__utils__/services/toolkits-repository-stub.tsindex 7f89ddf20..bfaf624a4 100644--- a/ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts+++ b/ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts@@ -1,9 +1,12 @@import { Effect, Layer } from 'effect';-import { ComposioToolkitsRepository } from 'src/services/composio-clients';+import {+ ComposioToolkitsRepository,+ type ComposioToolkitsRepositoryShape,+} from 'src/services/composio-clients';import type { Toolkits } from 'src/models/toolkits';export type GetToolkitsError = Effect.Effect.Error<- ReturnType<ComposioToolkitsRepository['getToolkits']>+ ReturnType<ComposioToolkitsRepositoryShape['getToolkits']>>;const notUsed = (method: string) => () => Effect.die(`${method} is not used in this test`);@@ -57,7 +60,7 @@ export const countingToolkitsRepository = (const layer = Layer.succeed(ComposioToolkitsRepository,- new ComposioToolkitsRepository({+ ComposioToolkitsRepository.of({...unusedRepositoryMethods,getToolkits: () =>Effect.suspend(() => {diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.tsindex 95990858e..3ad0fade5 100644--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts@@ -496,7 +496,7 @@ describe('CLI: composio login', () => {const now = yield* DateTime.now;const expiresAt = DateTime.add(now, { minutes: 10 });const sessionId = 'poll-session-id';- const sessionRepository = new ComposioSessionRepository({+ const sessionRepository = ComposioSessionRepository.of({createSession: () =>Effect.succeed({id: sessionId,diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.tsindex bbac80bde..fcbd76198 100644--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts@@ -102,7 +102,7 @@ const RunTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>Layer.merge(TestLive({...input,- commandRunner: new CommandRunner({+ commandRunner: CommandRunner.of({run: command => commandRuns(command),capture: () => Effect.succeed({ exitCode: 0, stdout: '', stderr: '' }),}),diff --git a/ts/packages/cli/test/src/commands/setup.cmd.test.ts b/ts/packages/cli/test/src/commands/setup.cmd.test.tsindex f3f55e37f..cea385e1f 100644--- a/ts/packages/cli/test/src/commands/setup.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/setup.cmd.test.ts@@ -77,7 +77,7 @@ const makeRunner = (readonly stderr?: string;}) =>- new CommandRunner({+ CommandRunner.of({run: () => Effect.succeed(CommandExecutor.ExitCode(0)),capture: command => {const result = respond(commandParts(command));@@ -106,7 +106,7 @@ const makeSkillInstaller = (initiallyReady = false, failInstall = false) => {return changed;});};- return new SetupSkillInstaller({+ return SetupSkillInstaller.of({isClaudeSkillReady: Effect.sync(() => ready),hasManagedClaudeSkill: Effect.sync(() => ready),ensureClaudeSkill: ensureClaudeSkill(),@@ -294,7 +294,7 @@ describe('CLI: composio setup', () => {});let staleSkillRepaired = false;let staleSkillReady = false;- const staleSkillInstaller = new SetupSkillInstaller({+ const staleSkillInstaller = SetupSkillInstaller.of({isClaudeSkillReady: Effect.sync(() => staleSkillReady),hasManagedClaudeSkill: Effect.succeed(true),ensureClaudeSkill: Effect.sync(() => {@@ -694,7 +694,7 @@ describe('CLI: composio setup', () => {layer(TestLive({commandRunner: orphanedClaudeSkill.runner,- setupSkillInstaller: new SetupSkillInstaller({+ setupSkillInstaller: SetupSkillInstaller.of({isClaudeSkillReady: Effect.sync(() => managedClaudeSkill),hasManagedClaudeSkill: Effect.sync(() => managedClaudeSkill),ensureClaudeSkill: Effect.succeed(false),@@ -726,7 +726,7 @@ describe('CLI: composio setup', () => {layer(TestLive({commandRunner: uninstallWithUnmanagedClaudeSkill.runner,- setupSkillInstaller: new SetupSkillInstaller({+ setupSkillInstaller: SetupSkillInstaller.of({isClaudeSkillReady: Effect.succeed(true),hasManagedClaudeSkill: Effect.succeed(false),ensureClaudeSkill: Effect.succeed(false),@@ -1133,7 +1133,7 @@ describe('CLI: composio setup', () => {);});- const hangingRunner = new CommandRunner({+ const hangingRunner = CommandRunner.of({run: () => Effect.succeed(CommandExecutor.ExitCode(0)),capture: () => Effect.never,});diff --git a/ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts b/ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.tsindex fb714b814..d62af142b 100644--- a/ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts@@ -83,7 +83,7 @@ const makeFakeHosts = (});};- const runner = new CommandRunner({+ const runner = CommandRunner.of({run: () => Effect.succeed(CommandExecutor.ExitCode(0)),capture: rawCommand => {const flattened = Command.flatten(rawCommand)[0];@@ -143,7 +143,7 @@ const makeFakeHosts = (const makeSkillInstaller = (initiallyReady = false) => {let ready = initiallyReady;- return new SetupSkillInstaller({+ return SetupSkillInstaller.of({isClaudeSkillReady: Effect.sync(() => ready),hasManagedClaudeSkill: Effect.sync(() => ready),ensureClaudeSkill: Effect.sync(() => {diff --git a/ts/packages/cli/test/src/effects/detect-platform.test.ts b/ts/packages/cli/test/src/effects/detect-platform.test.tsindex 5b1c2b861..b2b9127c1 100644--- a/ts/packages/cli/test/src/effects/detect-platform.test.ts+++ b/ts/packages/cli/test/src/effects/detect-platform.test.ts@@ -13,7 +13,7 @@ import { NodeOs } from 'src/services/node-os';const createMockNodeOs = <P extends NodeJS.Platform>(platform: P, arch: string) =>Layer.succeed(NodeOs,- NodeOs.make({+ NodeOs.of({homedir: '/mock/home',tmpdir: '/tmp',platform: platform as NodeJS.Platform,diff --git a/ts/packages/cli/test/src/services/composio-client-singleton.test.ts b/ts/packages/cli/test/src/services/composio-client-singleton.test.tsindex 37b933899..a51400ea5 100644--- a/ts/packages/cli/test/src/services/composio-client-singleton.test.ts+++ b/ts/packages/cli/test/src/services/composio-client-singleton.test.ts@@ -87,7 +87,7 @@ describe('ComposioClientSingleton headers', () => {]);return Effect.gen(function* () {- const client = yield* ComposioClientSingleton.get();+ const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());yield* Effect.promise(() =>client.tools.list({ limit: 1, toolkit_versions: 'latest' })@@ -134,7 +134,7 @@ describe('ComposioClientSingleton headers', () => {id: 'cli_s_current',expiresAt: '1970-01-01T00:01:00.000Z',});- const client = yield* ComposioClientSingleton.get();+ const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());yield* Effect.promise(() =>client.tools.list({ limit: 1, toolkit_versions: 'latest' })@@ -167,7 +167,7 @@ describe('ComposioClientSingleton headers', () => {id: 'cli_s_expired',expiresAt: '1969-12-31T23:59:00.000Z',});- const client = yield* ComposioClientSingleton.get();+ const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());yield* Effect.promise(() =>client.tools.list({ limit: 1, toolkit_versions: 'latest' })@@ -194,7 +194,7 @@ describe('ComposioClientSingleton headers', () => {]);return Effect.gen(function* () {- const client = yield* ComposioClientSingleton.get();+ const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());yield* Effect.promise(() =>client.tools.list({ limit: 1, toolkit_versions: 'latest' })diff --git a/ts/packages/cli/test/src/services/upgrade-binary.test.ts b/ts/packages/cli/test/src/services/upgrade-binary.test.tsindex 4cfcb8309..b6bec8937 100644--- a/ts/packages/cli/test/src/services/upgrade-binary.test.ts+++ b/ts/packages/cli/test/src/services/upgrade-binary.test.ts@@ -54,7 +54,7 @@ const TerminalUINoop = Layer.succeed(const NodeOsTest = Layer.succeed(NodeOs,- new NodeOs({+ NodeOs.of({homedir: '/tmp',tmpdir: '/tmp',platform: 'darwin',