1
/**
2
- * Composes the CLI layers and runs Effect's command parser. Command.runWith renders
3
- * help and parse errors once. runWithConfig accepts full argv and removes the executable prefix.
2
+ * Runs one invocation (`src/invocation/invocation.ts`) as the process: over the production
3
+ * services (`InvocationLive`), under the CLI's own runner. The invocation takes the full argv;
4
+ * `runWithConfig` removes the executable prefix before `Command.runWith` parses it.
5
*
6
* Exit codes come from Effect's runtime markers, never `process.exitCode`: a failure that is
6
- * already on screen (ShowHelp, a command's own report, or a message printed here) carries
7
- * `[Runtime.errorReported] = false`, so the runner logs nothing, and `Runtime.defaultTeardown`
8
- * exits with its `[Runtime.errorExitCode]` (1 when unset), or 0 on success. Signals are the
9
- * runner's (`src/run-main.ts`): a command a signal cancelled exits 128 + its number.
7
+ * already on screen (ShowHelp, a command's own report, or a message the invocation printed)
8
+ * reaches the runner with `[Runtime.errorReported] = false` (`forRunner`), so the runner logs
9
+ * nothing, and `Runtime.defaultTeardown` exits with its `[Runtime.errorExitCode]` (1 when unset),
10
+ * or 0 on success. Signals are the runner's (`src/run-main.ts`): a command a signal cancelled
11
+ * exits 128 + its number.
12
*/
11
-import { Cause, ConfigProvider, Effect, Layer, Logger, Runtime } from 'effect';
12
-import * as Path from 'effect/Path';
13
-import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
14
-import { CliConfig, CliError } from 'effect/cli';
15
-import { FetchHttpClient } from 'effect/http';
16
-import * as BunServices from '@effect/platform-bun/BunServices';
17
-import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
18
-import * as BunPath from '@effect/platform-bun/BunPath';
19
-import { runWithConfig, type RootCommandBootstrap } from 'src/commands';
20
-import { withoutClientNotices } from 'src/effects/without-client-notices';
21
-import * as constants from 'src/constants';
22
-import { ComposioCliConfig } from 'src/cli-config';
23
-import {
24
- ComposioClientSingleton,
25
- ComposioSessionRepository,
26
- ComposioToolkitsRepository,
27
-} from 'src/services/composio-clients';
28
-import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
29
-import { NodeOs } from 'src/services/node-os';
30
-import { NodeProcess } from 'src/services/node-process';
31
-import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
32
-import { ComposioCliUserConfigLive } from 'src/services/cli-user-config';
33
-import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
34
-import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
35
-import { extractMessage } from 'src/utils/api-error-extraction';
36
-import { UpgradeBinary } from 'src/services/upgrade-binary';
37
-import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
38
-import { TriggersRealtime } from 'src/services/triggers-realtime';
39
-import { ToolsExecutorLive as _ToolsExecutorLive } from 'src/services/tools-executor';
40
-import { DashboardToolExecution } from 'src/services/dashboard-tool-execution';
41
-import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
42
-import { ProjectContext } from 'src/services/project-context';
43
-import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
44
-import { CommandRunner } from 'src/services/command-runner';
45
-import { StdinLive } from 'src/services/stdin';
46
-import { PluginHint } from 'src/services/plugin-hint';
47
-import { UpdateNotice } from 'src/services/update-check';
48
-import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
49
-import type { HookInvocation } from 'src/services/invocation-hook';
50
-import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
51
-import {
52
- configureCliAnalyticsReleaseVersion,
53
- createCliCommandTelemetryContext,
54
- getExecuteCommandToolSlug,
55
-} from 'src/analytics/events';
56
-import { getVersion } from 'src/effects/version';
57
-import { LogLevelFromConfigLive } from 'src/effects/with-log-level';
58
-import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
59
-import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
60
-import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
61
-import { PendingLoginSession } from 'src/services/pending-login-session';
62
-import { isExpectedFailure, type ExpectedFailure } from 'src/effects/expected-failure';
63
-import { ReportedFailure } from 'src/effects/report-failure';
64
-import { cliInvocationContext } from 'src/services/runtime-cli-context';
13
+import { ConfigProvider, Effect } from 'effect';
14
+import { forRunner, runInvocation } from 'src/invocation/invocation';
15
+import { InvocationLive } from 'src/invocation/live';
16
import { readTelemetryDebugOverride, telemetryDebugModeLayer } from 'src/services/runtime-flags';
17
import { normalizeRunScriptArgs } from 'src/commands/argv-compat';
18
import { makeShutdownController, ShutdownSignal } from 'src/services/shutdown-signal';
19
import { makeCliRunMain } from 'src/run-main';
20
70
-// Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any
71
-// produced context and error type while still pinning the requirements (RIn) to `never`.
72
-type RequiredLayer = Layer.Layer<never, unknown, never>;
73
-
74
-export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies RequiredLayer;
75
-
76
-export const ComposioUserContextLive = Layer.provide(
77
- _ComposioUserContextLive,
78
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
79
-) satisfies RequiredLayer;
80
-
81
-export const ComposioCliUserConfigLayer = Layer.provide(
82
- ComposioCliUserConfigLive,
83
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
84
-);
85
-
86
-export const ComposioSessionRepositoryLive = Layer.provide(
87
- ComposioSessionRepository.Default,
88
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
89
-) satisfies RequiredLayer;
90
-
91
-export const ComposioToolkitsRepositoryLive = Layer.provide(
92
- ComposioToolkitsRepository.Default,
93
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, LogLevelFromConfigLive)
94
-) satisfies RequiredLayer;
95
-
96
-export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
97
- ComposioToolkitsRepositoryCached,
98
- ComposioToolkitsRepositoryLive
99
-) satisfies RequiredLayer;
100
-
101
-export const UpgradeBinaryLive = Layer.provide(
102
- UpgradeBinary.Default,
103
- Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
104
-) satisfies RequiredLayer;
105
-
106
-export const TriggersRealtimeLive = Layer.provide(
107
- TriggersRealtime.Default,
108
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
109
-) satisfies RequiredLayer;
110
-
111
-export const ComposioClientSingletonLive = Layer.provide(
112
- ComposioClientSingleton.Default,
113
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, LogLevelFromConfigLive)
114
-) satisfies RequiredLayer;
115
-
116
-// Fed the cached repository so that the staleness refresh behind it shares the
117
-// one catalog fetch a run is allowed, rather than starting a second.
118
-export const ToolkitSlugCatalogLive = Layer.provide(
119
- ToolkitSlugCatalog.Default,
120
- ComposioToolkitsRepositoryCachedLive
121
-) satisfies RequiredLayer;
122
-
123
-export const DashboardToolExecutionLive = Layer.provide(
124
- DashboardToolExecution.Default,
125
- Layer.mergeAll(ComposioUserContextLive, FetchHttpClient.layer)
126
-);
127
-
128
-export const ToolsExecutorLive = Layer.provide(
129
- _ToolsExecutorLive,
130
- Layer.mergeAll(ComposioClientSingletonLive, ToolkitSlugCatalogLive, DashboardToolExecutionLive)
131
-) satisfies RequiredLayer;
132
-
133
-export const ProjectContextLive = Layer.provide(
134
- ProjectContext.Default,
135
- Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
136
-) satisfies RequiredLayer;
137
-
138
-export const SetupSkillInstallerLive = Layer.provide(
139
- SetupSkillInstaller.Default,
140
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
141
-) satisfies RequiredLayer;
142
-
143
-export const PendingLoginSessionLive = Layer.provide(
144
- PendingLoginSession.Default,
145
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
146
-) satisfies RequiredLayer;
147
-
148
-export const BackendMismatchWarningLive = Layer.provide(
149
- BackendMismatchWarning.Default,
150
- Layer.mergeAll(ComposioUserContextLive, TerminalUILive)
151
-) satisfies RequiredLayer;
152
-
153
-// `Path.layer`, not `BunPath.layer`: the update notice and the plugin hint have always resolved
154
-// their state files with Effect's own path implementation.
155
-export const UpdateNoticeLive = Layer.provide(
156
- UpdateNotice.Default,
157
- Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
158
-) satisfies RequiredLayer;
159
-
160
-export const PluginHintLive = Layer.provide(
161
- PluginHint.Default,
162
- Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
163
-) satisfies RequiredLayer;
164
-
165
-export const CommandLifecycleTelemetryLive = Layer.provide(
166
- CommandLifecycleTelemetry.Default,
167
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, TerminalUILive)
168
-) satisfies RequiredLayer;
169
-
170
-const layers = Layer.mergeAll(
171
- CliConfigLive.pipe(Layer.provide(LogLevelFromConfigLive)),
172
- NodeOs.Default,
173
- NodeProcess.Default,
174
- UpgradeBinaryLive,
175
- ComposioCliUserConfigLayer,
176
- ComposioUserContextLive,
177
- ComposioSessionRepositoryLive,
178
- ComposioClientSingletonLive,
179
- ComposioToolkitsRepositoryCachedLive,
180
- ToolkitSlugCatalogLive,
181
- ToolsExecutorLive,
182
- JsPackageManagerDetector.Default,
183
- ProjectEnvironmentDetector.Default,
184
- CommandRunner.Default,
185
- SetupSkillInstallerLive,
186
- TriggersRealtimeLive,
187
- ProjectContextLive,
188
- PendingLoginSessionLive,
189
- BunServices.layer,
190
- BunFileSystem.layer,
191
- BunPath.layer,
192
- FetchHttpClient.layer,
193
- StdinLive,
194
- TerminalUILive,
195
- BackendMismatchWarningLive,
196
- UpdateNoticeLive,
197
- PluginHintLive,
198
- CommandLifecycleTelemetryLive,
199
- Layer.merge(
200
- Logger.layer([withoutClientNotices(Logger.consolePretty())]),
201
- Layer.succeed(Logger.LogToStderr, true)
202
- )
203
-) satisfies RequiredLayer;
204
-
205
-/**
206
- * Whether `reason` has nothing for the catch-all to print: a failure already on screen, or an
207
- * interruption, which must reach the runner untouched: 128 + n after a signal, else 130 from
208
- * `Runtime.defaultTeardown`.
209
- */
210
-const hasNothingToPrint = (reason: Cause.Reason<unknown>): boolean =>
211
- Cause.isInterruptReason(reason) ||
212
- (Cause.isFailReason(reason) && !Runtime.getErrorReported(reason.error));
213
-
214
-/**
215
- * Prints the parts of `cause` nobody reported yet and fails with `ReportedFailure`. A cause with
216
- * nothing to print (a failure already on screen — `ShowHelp`, which `Command.runWith` printed
217
- * with any parse/validation errors, a command's own report, or a message printed in
218
- * `cliProgram` — or an interruption) is re-failed untouched: its `[Runtime.errorReported]` is
219
- * false, so the runner logs nothing, and `Runtime.defaultTeardown` exits with its
220
- * `[Runtime.errorExitCode]`; interruptions alone exit 128 + n after a signal, else 130. Nothing
221
- * here may print it, or output doubles.
222
- */
223
-export const reportUnreportedCause = Effect.fn(function* (cause: Cause.Cause<unknown>) {
224
- const unreported = Cause.fromReasons(cause.reasons.filter(reason => !hasNothingToPrint(reason)));
225
- if (unreported.reasons.length > 0) {
226
- const captured = yield* captureErrors(unreported, { stripCwd: true });
227
- const message =
228
- captured.errors.length > 0
229
- ? prettyPrintFromCapturedErrors(captured, {
230
- hideStackTrace: true,
231
- stripCwd: true,
232
- enabled: true,
233
- }).trim()
234
- : '';
235
- if (message.length > 0) {
236
- const ui = yield* TerminalUI;
237
- yield* ui.error(message);
238
- return yield* new ReportedFailure({ message });
239
- }
240
- }
241
- // Nothing printable: keep the original cause so its exit code survives and the runner logs
242
- // whatever is still unreported, instead of exiting 0.
243
- return yield* Effect.failCause(cause);
244
-});
245
-
246
-// `runWithConfig`'s root command tree (built from every `.cmd.ts` subcommand in
247
-// `src/commands`) is deep and wide enough that TypeScript's inference collapses its
248
-// requirement (`R`) type to `any` rather than the precise union of service tags. That
249
-// `any` is otherwise infectious through the rest of this pipeline (defeating the
250
-// `Effect.provide(layers)` / `RequiredLayer` checks below), so it is pinned here to the
251
-// same service union `layers` actually provides — this changes nothing at runtime, it
252
-// only restores the precise static type that inference failed to produce on its own.
253
-const runWithArgs = (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap) =>
254
- Effect.flatMap(runWithConfig, run => run(argv, bootstrap)) as Effect.Effect<
255
- void,
256
- unknown,
257
- Layer.Success<typeof layers> | ShutdownSignal
258
- >;
259
-
260
-const runWithTelemetry = (argv: ReadonlyArray<string>) =>
261
- Effect.gen(function* () {
262
- const ui = yield* TerminalUI;
263
- const terminal = yield* ui.capabilities;
264
-
265
- const version = yield* getVersion;
266
- configureCliAnalyticsReleaseVersion(version);
267
- const baseTelemetryContext = createCliCommandTelemetryContext(
268
- argv,
269
- version,
270
- terminal,
271
- yield* cliInvocationContext
272
- );
273
- const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);
274
- const commandTelemetryContext =
275
- executeToolSlug === undefined
276
- ? baseTelemetryContext
277
- : { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };
278
- // `composio run` mints its run id here so the lifecycle events and the id the spawned script
279
- // inherits are the same value; every other command leaves it unset.
280
- const bootstrap: RootCommandBootstrap =
281
- commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId
282
- ? { runId: commandTelemetryContext.runId }
283
- : {};
284
- const telemetry = yield* CommandLifecycleTelemetry;
285
- return yield* telemetry.invoked(commandTelemetryContext).pipe(
286
- Effect.andThen(runWithArgs(argv, bootstrap)),
287
- Effect.scoped,
288
- Effect.mapError(error =>
289
- CliError.isCliError(error) ? error : mapOnlyComposioOverrideError({ error })
290
- ),
291
- Effect.tap(() => telemetry.succeeded(commandTelemetryContext)),
292
- Effect.tapCause(cause => telemetry.failed(commandTelemetryContext, cause))
293
- );
294
- });
295
-
21
/**
22
* Values `src/bin.ts` resolved before the Effect runtime existed and hands to it here.
23
*/
26
readonly argv: ReadonlyArray<string>;
27
};
28
304
-/** Runs the hooks every invocation gets before its command, in order, on stderr. */
305
-const runInvocationHooks = (invocation: HookInvocation) =>
306
- Effect.gen(function* () {
307
- const backendMismatchWarning = yield* BackendMismatchWarning;
308
- const updateNotice = yield* UpdateNotice;
309
- const pluginHint = yield* PluginHint;
310
- yield* backendMismatchWarning.run(invocation);
311
- yield* updateNotice.run(invocation);
312
- yield* pluginHint.run(invocation);
313
- });
314
-
315
-const cliProgram = (argv: ReadonlyArray<string>) =>
316
- runInvocationHooks({ argv }).pipe(
317
- Effect.andThen(runWithTelemetry(argv)),
318
- // A usage mistake, a missing setup or login, or a failure a remote service reported clearly
319
- // (see `ExpectedFailure`) is not a broken invariant: print the message and exit 1 instead of
320
- // routing it through the defect reporter below.
321
- Effect.catchIf(
322
- (error): error is ExpectedFailure => isExpectedFailure(error),
323
- error =>
324
- Effect.gen(function* () {
325
- const ui = yield* TerminalUI;
326
- yield* ui.error(error.message);
327
- return yield* new ReportedFailure({ message: error.message });
328
- })
329
- ),
330
- // A rejected user API key gets the backend's message and the way to log in again, from
331
- // whichever command it escaped.
332
- Effect.catchIf(isRejectedUserApiKey, error =>
333
- Effect.gen(function* () {
334
- const ui = yield* TerminalUI;
335
- const message = extractMessage(error) ?? 'The user API key was rejected.';
336
- yield* ui.error(message);
337
- yield* ui.error(yield* rejectedUserApiKeyHint);
338
- return yield* new ReportedFailure({ message });
339
- })
340
- ),
341
- Effect.withSpan('composio-cli', {
342
- attributes: {
343
- name: constants.APP_NAME,
344
- filename: 'src/bin.ts',
345
- },
346
- }),
347
- Effect.sandbox,
348
- Effect.catch(reportUnreportedCause),
349
- Effect.provide(layers),
29
+export const runCli = (options: CliBootstrapOptions): void => {
30
+ const debug = readTelemetryDebugOverride(normalizeRunScriptArgs(options.argv));
31
+ // One per invocation: the runner reports the process's signals to the command through it.
32
+ const shutdown = makeShutdownController();
33
+ runInvocation(options.argv).pipe(
34
+ forRunner,
35
+ Effect.provide(InvocationLive),
36
// Built per invocation, never at module scope: `ConfigProvider.fromEnv()` snapshots
37
// `process.env` when constructed, and the ambient `ConfigProvider` reference caches its
38
// default snapshot process-wide on first use. A fresh provider here means every config read
39
// of this invocation observes the environment as it is now (`vi.stubEnv` in tests, any
40
// in-process mutation before `runCli`).
355
- Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv()))
356
- );
357
-
358
-export const runCli = (options: CliBootstrapOptions): void => {
359
- const debug = readTelemetryDebugOverride(normalizeRunScriptArgs(options.argv));
360
- // One per invocation: the runner reports the process's signals to the command through it.
361
- const shutdown = makeShutdownController();
362
- cliProgram(options.argv).pipe(
41
+ Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv())),
42
Effect.provideService(ShutdownSignal, shutdown.service),
43
effect =>
44
debug === undefined ? effect : Effect.provide(effect, telemetryDebugModeLayer(debug)),