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

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

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

Synced Nov 21, 18:30 UTC

refactor(cli): route terminal output through the TerminalUI boundary (#3881)

This PR: - activates the terminal-streams rule group: `process.stdout`/`process.stderr` are now ESLint-banned in CLI source, with `services/terminal-ui.ts` as the sole stream boundary (that file is itself held to the try/catch + `process.env` restrictions early) - extends `TerminalUI` with `capabilities` (TTY/interactivity/decoration detection) and a raw `error()` writer, replacing `utils/stdio.ts` (deleted) - makes analytics dispatch Effect-native and delivers detached telemetry through `DetachedProcess`, staying non-fatal on failure - consolidates runtime debug logging into a `RuntimeDebugLogger` service and rebuilds `cli-main` around `showUpdateNotice`/telemetry as Effects with errors reported via `ui.error` - the update checker reads terminal capabilities from the service and keeps its fire-and-forget contract --- **Stack** (re-slice of https://github.com/ComposioHQ/composio/pull/3859; each PR targets its parent and auto-retargets to `next` as parents merge): 1. https://github.com/ComposioHQ/composio/pull/3877 — guidelines + inert rule groups 2. https://github.com/ComposioHQ/composio/pull/3878 — `new Function()` eval security fix 3. https://github.com/ComposioHQ/composio/pull/3879 — behavioral fix pack 4. https://github.com/ComposioHQ/composio/pull/3880 — platform-imports rule + migration 5. https://github.com/ComposioHQ/composio/pull/3881 — terminal-streams rule + TerminalUI boundary ← **this PR** 6. https://github.com/ComposioHQ/composio/pull/3882 — descriptor seam + zod→Schema 7. https://github.com/ComposioHQ/composio/pull/3883 — test-tree lint + deterministic suites 8. https://github.com/ComposioHQ/composio/pull/3884 — typed error boundaries + v4 seams 9. https://github.com/ComposioHQ/composio/pull/3885 — try/catch+env ban + boundary ratchet On stacked bases CI runs lint/build and the CLI Docker e2e job; unit tests and typecheck are verified locally per PR and re-verified by full CI when each PR is retargeted to `next`.

Alberto Schiabel committed Jul 21, 2026 at 11:25 UTC 5318f60de9b01e67b75b312125d1c4f957154122
36 files changed +1731 -978
eslint.config.mjs
+13 -11
@@ -201,9 +201,12 @@ export default [
201 ],
202 },
203 ],
204 - // uncommented by the terminal-streams PR of this stack (the try/catch and
205 - // process.env entries by the boundary-ratchet PR).
206 - // 'no-restricted-syntax': ['error', ...cliRestrictedSyntax, ...cliProcessStreamRestrictions],
204 + 'no-restricted-syntax': [
205 + 'error',
206 + // uncommented by the boundary-ratchet PR of this stack
207 + // ...cliRestrictedSyntax,
208 + ...cliProcessStreamRestrictions,
209 + ],
210 },
211 },
212 // uncommented by the test-rules PR of this stack.
@@ -262,14 +265,13 @@ export default [
265 // ],
266 // },
267 // },
265 - // uncommented by the terminal-streams PR of this stack.
266 - // {
267 - // files: ['ts/packages/cli/src/services/terminal-ui.ts'],
268 - // rules: {
269 - // // TerminalUI is the sole CLI boundary for Node's stdout and stderr streams.
270 - // 'no-restricted-syntax': ['error', ...cliRestrictedSyntax],
271 - // },
272 - // },
268 + {
269 + files: ['ts/packages/cli/src/services/terminal-ui.ts'],
270 + rules: {
271 + // TerminalUI is the sole CLI boundary for Node's stdout and stderr streams.
272 + 'no-restricted-syntax': ['error', ...cliRestrictedSyntax],
273 + },
274 + },
275 {
276 // Examples are console-driven references. Keep type-safety rules
277 // (no-explicit-any, unused-vars) but drop console noise. The Buffer/crypto
ts/packages/cli/src/analytics/dispatch.ts
+420 -404
@@ -1,15 +1,22 @@
1 -// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
2 -import fs from 'node:fs';
3 -// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
4 -import os from 'node:os';
5 -// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
6 -import path from 'node:path';
1 import process from 'node:process';
8 -// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
9 -import { spawn } from 'node:child_process';
10 -import { Effect } from 'effect';
11 -import type { AnalyticsEnvelope, TrackEvent } from './types';
2 +import { FileSystem, HttpClient, HttpClientRequest, Path } from '@effect/platform';
3 +import {
4 + Cause,
5 + Clock,
6 + Config,
7 + ConfigProvider,
8 + DateTime,
9 + Effect,
10 + Encoding,
11 + Option,
12 + Schema,
13 +} from 'effect';
14 import * as constants from 'src/constants';
15 +import { spawnDetached } from 'src/services/detached-process';
16 +import { djb2Hash } from 'src/utils/djb2';
17 +import { NodeOs } from 'src/services/node-os';
18 +import { TerminalUI } from 'src/services/terminal-ui';
19 +import type { AnalyticsEnvelope, TrackEvent } from './types';
20
21 const INTERNAL_ANALYTICS_WORKER_FLAG = '__analytics-worker';
22 const INTERNAL_CODACT_FAILURE_WORKER_FLAG = '__codact-failure-worker';
@@ -18,7 +25,6 @@ const ANALYTICS_STATE_FILE_NAME = 'analytics.json';
25 const CONSUMER_SHORT_TERM_CACHE_FILE_NAME = 'consumer-short-term-cache.json';
26 const CLI_ANALYTICS_PATH = '/api/v3/cli/analytics';
27 const CLI_CODACT_FAILURES_PATH = '/api/v3/cli/codact_failures';
21 -const TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';
28
29 export type CliCodactFailureType = 'wrong_tool_slug' | 'wrong_tool_input_param';
30
@@ -38,37 +44,6 @@ export type CliCodactFailure = {
44 readonly requestId?: string;
45 };
46
41 -const truthy = (value: string | undefined): boolean =>
42 - value === '1' || value === 'true' || value === 'yes' || value === 'on';
43 -
44 -const isTelemetryDebugEnabled = (): boolean => truthy(process.env[TELEMETRY_DEBUG_ENV_VAR]);
45 -
46 -const telemetryDebugLog = (label: string, payload: Record<string, unknown>) => {
47 - if (!isTelemetryDebugEnabled()) {
48 - return;
49 - }
50 -
51 - process.stderr.write(
52 - `[telemetry-debug] ${JSON.stringify(
53 - {
54 - label,
55 - ...payload,
56 - },
57 - null,
58 - 2
59 - )}\n`
60 - );
61 -};
62 -
63 -const analyticsDir = () => path.join(os.homedir(), COMPOSIO_DIR);
64 -const analyticsStatePath = () => path.join(analyticsDir(), ANALYTICS_STATE_FILE_NAME);
65 -const userConfigPath = () => path.join(analyticsDir(), constants.USER_CONFIG_FILE_NAME);
66 -const cacheDir = () =>
67 - process.env.COMPOSIO_CACHE_DIR?.trim() ||
68 - process.env.CACHE_DIR?.trim() ||
69 - path.join(os.homedir(), constants.USER_COMPOSIO_DIR);
70 -const consumerShortTermCachePath = () => path.join(cacheDir(), CONSUMER_SHORT_TERM_CACHE_FILE_NAME);
71 -
47 type ConsumerShortTermCacheState = Record<
48 string,
49 {
@@ -82,122 +57,170 @@ type ConsumerShortTermCacheState = Record<
57 }
58 >;
59
85 -const ensureAnalyticsDir = () => {
86 - try {
87 - fs.mkdirSync(analyticsDir(), { recursive: true });
88 - } catch {
89 - // Non-fatal — analytics directory creation may fail in sandboxed environments.
90 - }
91 -};
60 +// Workers start before the CLI's prefixed ConfigProvider is assembled, so this
61 +// module names and reads the actual environment variables from a raw provider.
62 +const environmentProvider = ConfigProvider.fromEnv();
63 +const optionalString = (name: string) => Config.option(Config.string(name));
64 +const booleanWithDefault = (name: string) => Config.boolean(name).pipe(Config.withDefault(false));
65 +const configuredString = (value: Option.Option<string>): string | undefined =>
66 + value.pipe(
67 + Option.map(value => value.trim()),
68 + Option.filter(value => value.length > 0),
69 + Option.getOrUndefined
70 + );
71
93 -const encodeBase64Url = (value: string): string => {
94 - const bytes = new TextEncoder().encode(value);
95 - let binary = '';
96 - for (const byte of bytes) {
97 - binary += String.fromCharCode(byte);
98 - }
99 - return btoa(binary).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
100 -};
72 +const telemetryDebugEnabled = environmentProvider.load(
73 + booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DEBUG')
74 +);
75 +
76 +const analyticsDisabled = environmentProvider.load(
77 + Config.all({
78 + cliTelemetryDisabled: booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DISABLED'),
79 + telemetryDisabled: booleanWithDefault('TELEMETRY_DISABLED'),
80 + composioTelemetryDisabled: booleanWithDefault('COMPOSIO_DISABLE_TELEMETRY'),
81 + nodeEnvironment: Config.string('NODE_ENV').pipe(Config.withDefault('')),
82 + ci: booleanWithDefault('CI'),
83 + }).pipe(
84 + Config.map(
85 + ({
86 + cliTelemetryDisabled,
87 + telemetryDisabled,
88 + composioTelemetryDisabled,
89 + nodeEnvironment,
90 + ci,
91 + }) =>
92 + cliTelemetryDisabled ||
93 + telemetryDisabled ||
94 + composioTelemetryDisabled ||
95 + nodeEnvironment === 'test' ||
96 + ci
97 + )
98 + )
99 +);
100 +
101 +const jsonFromString = Schema.parseJson();
102 +const prettyJsonFromString = Schema.parseJson({ space: 2 });
103 +const decodeJson = Schema.decodeUnknown(jsonFromString);
104 +const encodeJson = Schema.encode(jsonFromString);
105 +const encodePrettyJson = Schema.encode(prettyJsonFromString);
106 +
107 +const telemetryDebugLog = (label: string, payload: Record<string, unknown>) =>
108 + Effect.gen(function* () {
109 + if (!(yield* telemetryDebugEnabled)) {
110 + return;
111 + }
112
102 -const decodeBase64Url = (value: string): string => {
103 - const normalized = value.replace(/-/gu, '+').replace(/_/gu, '/');
104 - const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
105 - const binary = atob(padded);
106 - const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
107 - return new TextDecoder().decode(bytes);
113 + const body = yield* encodePrettyJson({ label, ...payload });
114 + const ui = yield* TerminalUI;
115 + yield* ui.error(`[telemetry-debug] ${body}`);
116 + }).pipe(Effect.ignore);
117 +
118 +const telemetryErrorDetails = (cause: Cause.Cause<unknown>): Record<string, string> => {
119 + const squashed = Cause.squash(cause);
120 + const error = Cause.isUnknownException(squashed) ? squashed.error : squashed;
121 + return error instanceof Error
122 + ? { name: error.name, message: error.message }
123 + : { message: String(error) };
124 };
125
110 -const djb2Hash = (value: string): number => {
111 - let hash = 5381;
112 - for (let index = 0; index < value.length; index += 1) {
113 - hash = (hash * 33) ^ value.charCodeAt(index);
114 - }
115 - return Math.abs(hash >>> 0);
116 -};
126 +const getAnalyticsPaths = Effect.gen(function* () {
127 + const path = yield* Path.Path;
128 + const os = yield* NodeOs;
129 + const cacheDirectories = yield* environmentProvider.load(
130 + Config.all({
131 + composio: optionalString('COMPOSIO_CACHE_DIR'),
132 + legacy: optionalString('CACHE_DIR'),
133 + })
134 + );
135 + const analyticsDir = path.join(os.homedir, COMPOSIO_DIR);
136 + const cacheDir =
137 + configuredString(cacheDirectories.composio) ??
138 + configuredString(cacheDirectories.legacy) ??
139 + path.join(os.homedir, constants.USER_COMPOSIO_DIR);
140 +
141 + return {
142 + analyticsDir,
143 + analyticsStatePath: path.join(analyticsDir, ANALYTICS_STATE_FILE_NAME),
144 + userConfigPath: path.join(analyticsDir, constants.USER_CONFIG_FILE_NAME),
145 + consumerShortTermCachePath: path.join(cacheDir, CONSUMER_SHORT_TERM_CACHE_FILE_NAME),
146 + };
147 +});
148 +
149 +const readOptionalJson = <A>(filePath: string) =>
150 + Effect.gen(function* () {
151 + const fs = yield* FileSystem.FileSystem;
152 + const raw = yield* fs.readFileString(filePath, 'utf8');
153 + return (yield* decodeJson(raw)) as A;
154 + }).pipe(Effect.catchAll(() => Effect.succeed(undefined)));
155
156 const hashString = (value: string): string => djb2Hash(value).toString(16).padStart(8, '0');
157
120 -const getOrCreateInstallId = (): string => {
121 - try {
122 - ensureAnalyticsDir();
123 - const filePath = analyticsStatePath();
124 - if (fs.existsSync(filePath)) {
125 - const raw = fs.readFileSync(filePath, 'utf8');
126 - const parsed = JSON.parse(raw) as { install_id?: unknown };
127 - if (typeof parsed.install_id === 'string' && parsed.install_id.length > 0) {
128 - return parsed.install_id;
129 - }
130 - }
131 - const installId = crypto.randomUUID();
132 - fs.writeFileSync(
133 - filePath,
134 - JSON.stringify(
135 - {
136 - install_id: installId,
137 - created_at: new Date().toISOString(),
138 - },
139 - null,
140 - 2
141 - ),
142 - 'utf8'
143 - );
144 - return installId;
145 - } catch {
146 - return crypto.randomUUID();
147 - }
148 -};
158 +const makeInstallId = Effect.sync(() => crypto.randomUUID());
159
150 -const getHashedApiKeyDistinctId = (): string | null => {
151 - const envApiKey = process.env.COMPOSIO_USER_API_KEY?.trim();
152 - if (envApiKey) {
153 - return `user_${hashString(envApiKey)}`;
154 - }
160 +const getOrCreateInstallId = Effect.gen(function* () {
161 + const fs = yield* FileSystem.FileSystem;
162 + const paths = yield* getAnalyticsPaths;
163
156 - try {
157 - const raw = fs.readFileSync(userConfigPath(), 'utf8');
158 - const parsed = JSON.parse(raw) as { api_key?: unknown };
159 - if (typeof parsed.api_key === 'string' && parsed.api_key.trim().length > 0) {
160 - return `user_${hashString(parsed.api_key.trim())}`;
161 - }
162 - } catch {
163 - // Ignore user config read failures.
164 + yield* fs
165 + .makeDirectory(paths.analyticsDir, { recursive: true })
166 + .pipe(Effect.catchAll(() => Effect.void));
167 +
168 + const state = yield* readOptionalJson<{ install_id?: unknown }>(paths.analyticsStatePath);
169 + if (typeof state?.install_id === 'string' && state.install_id.length > 0) {
170 + return state.install_id;
171 }
172
166 - return null;
167 -};
173 + const installId = yield* makeInstallId;
174 + const createdAt = DateTime.formatIso(yield* DateTime.now);
175 + const contents = yield* encodeJson({
176 + install_id: installId,
177 + created_at: createdAt,
178 + });
179 + yield* fs.writeFileString(paths.analyticsStatePath, contents);
180 + return installId;
181 +}).pipe(Effect.catchAll(() => makeInstallId));
182
169 -const getDistinctId = (): string => getHashedApiKeyDistinctId() ?? `anon_${getOrCreateInstallId()}`;
183 +const readUserConfig = Effect.gen(function* () {
184 + const paths = yield* getAnalyticsPaths;
185 + return yield* readOptionalJson<{ api_key?: unknown; base_url?: unknown }>(paths.userConfigPath);
186 +});
187
171 -const getUserApiKey = (): string | null => {
172 - const envApiKey = process.env.COMPOSIO_USER_API_KEY?.trim();
188 +const getUserApiKey = Effect.gen(function* () {
189 + const envApiKey = configuredString(
190 + yield* environmentProvider.load(optionalString('COMPOSIO_USER_API_KEY'))
191 + );
192 if (envApiKey) {
193 return envApiKey;
194 }
195
177 - try {
178 - const raw = fs.readFileSync(userConfigPath(), 'utf8');
179 - const parsed = JSON.parse(raw) as { api_key?: unknown };
180 - if (typeof parsed.api_key === 'string' && parsed.api_key.trim().length > 0) {
181 - return parsed.api_key.trim();
182 - }
183 - } catch {
184 - // Ignore user config read failures.
185 - }
196 + const userConfig = yield* readUserConfig;
197 + return typeof userConfig?.api_key === 'string' && userConfig.api_key.trim().length > 0
198 + ? userConfig.api_key.trim()
199 + : null;
200 +});
201
187 - return null;
188 -};
202 +const getDistinctId = (installId: string) =>
203 + Effect.map(getUserApiKey, userApiKey =>
204 + userApiKey ? `user_${hashString(userApiKey)}` : `anon_${installId}`
205 + );
206
207 const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);
208
192 -export const getCurrentCwdSessionId = (): string | undefined => {
193 - try {
194 - const raw = fs.readFileSync(consumerShortTermCachePath(), 'utf8');
195 - const parsed = JSON.parse(raw) as ConsumerShortTermCacheState;
196 - const currentCwdHash = cwdHash(process.cwd());
197 - const now = Date.now();
209 +export const getCurrentCwdSessionId = (cwd = process.cwd()) =>
210 + Effect.gen(function* () {
211 + const paths = yield* getAnalyticsPaths;
212 + const state = yield* readOptionalJson<ConsumerShortTermCacheState>(
213 + paths.consumerShortTermCachePath
214 + );
215 + if (!state) {
216 + return undefined;
217 + }
218 +
219 + const currentCwdHash = cwdHash(cwd);
220 + const now = yield* Clock.currentTimeMillis;
221 let best: { id: string; expiresAtMs: number } | undefined;
222
200 - for (const entry of Object.values(parsed)) {
223 + for (const entry of Object.values(state)) {
224 const session = entry.probablyMyCliSessionsByCwdHash?.[currentCwdHash];
225 if (!session?.id) continue;
226 const expiresAtMs = Date.parse(session.expiresAt);
@@ -208,288 +231,268 @@ export const getCurrentCwdSessionId = (): string | undefined => {
231 }
232
233 return best?.id;
211 - } catch {
212 - return undefined;
213 - }
214 -};
215 -
216 -const withCliSessionId = (event: TrackEvent): TrackEvent => {
217 - if (!event) return event;
218 - const cliSessionId = getCurrentCwdSessionId();
219 - return {
220 - ...event,
221 - properties: {
222 - ...(event.properties ?? {}),
223 - cli_version: event.properties?.cli_version ?? constants.APP_VERSION,
224 - ...(cliSessionId ? { cli_session_id: cliSessionId } : {}),
225 - },
226 - };
227 -};
234 + }).pipe(Effect.catchAllCause(() => Effect.succeed(undefined)));
235 +
236 +const withCliSessionId = (event: NonNullable<TrackEvent>, cliSessionId?: string): TrackEvent => ({
237 + ...event,
238 + properties: {
239 + ...(event.properties ?? {}),
240 + cli_version: event.properties?.cli_version ?? constants.APP_VERSION,
241 + ...(cliSessionId ? { cli_session_id: cliSessionId } : {}),
242 + },
243 +});
244
229 -export const readApiBaseUrl = (): string | null => {
230 - const envBaseUrl = process.env.COMPOSIO_BASE_URL?.trim();
245 +export const readApiBaseUrl = Effect.gen(function* () {
246 + const envBaseUrl = configuredString(
247 + yield* environmentProvider.load(optionalString('COMPOSIO_BASE_URL'))
248 + );
249 if (envBaseUrl) {
250 return envBaseUrl.replace(/\/+$/u, '');
251 }
252
235 - try {
236 - const raw = fs.readFileSync(userConfigPath(), 'utf8');
237 - const parsed = JSON.parse(raw) as { base_url?: unknown };
238 - if (typeof parsed.base_url === 'string' && parsed.base_url.trim().length > 0) {
239 - return parsed.base_url.trim().replace(/\/+$/u, '');
240 - }
241 - } catch {
242 - // Ignore user config read failures.
243 - }
244 -
245 - return null;
246 -};
253 + const userConfig = yield* readUserConfig;
254 + return typeof userConfig?.base_url === 'string' && userConfig.base_url.trim().length > 0
255 + ? userConfig.base_url.trim().replace(/\/+$/u, '')
256 + : null;
257 +}).pipe(Effect.catchAllCause(() => Effect.succeed(null)));
258 +
259 +const getAnalyticsEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
260 + baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null
261 +);
262 +
263 +const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
264 + baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null
265 +);
266 +
267 +const getWorkerSpawnArgs = (workerFlag: string, encodedPayload: string) =>
268 + Effect.gen(function* () {
269 + const fs = yield* FileSystem.FileSystem;
270 + const maybeScriptPath = process.argv[1];
271 + const scriptPathExists =
272 + typeof maybeScriptPath === 'string' && maybeScriptPath.length > 0
273 + ? yield* fs.exists(maybeScriptPath).pipe(Effect.catchAll(() => Effect.succeed(false)))
274 + : false;
275 + const scriptPathLooksReal =
276 + scriptPathExists && /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath ?? '');
277 +
278 + return scriptPathLooksReal
279 + ? {
280 + command: process.execPath,
281 + args: [maybeScriptPath as string, workerFlag, encodedPayload],
282 + }
283 + : {
284 + command: process.execPath,
285 + args: [workerFlag, encodedPayload],
286 + };
287 + });
288
248 -const getAnalyticsEndpoint = (): string | null => {
249 - const baseUrl = readApiBaseUrl();
250 - return baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null;
251 -};
289 +// Effect's Command processes are scoped and die with their scope; telemetry
290 +// workers intentionally outlive the CLI process, so they go through the
291 +// sanctioned detached-spawn boundary in src/services/detached-process.
292 +// Delivery is best effort: a failed spawn is swallowed, never surfaced.
293 +const spawnWorker = (command: string, args: ReadonlyArray<string>) =>
294 + Effect.gen(function* () {
295 + const debugEnabled = yield* telemetryDebugEnabled;
296 + yield* spawnDetached(command, args, { inheritStderr: debugEnabled }).pipe(
297 + Effect.catchTag('services/DetachedProcessSpawnError', () => Effect.void)
298 + );
299 + });
300
253 -const getCliCodactFailuresEndpoint = (): string | null => {
254 - const baseUrl = readApiBaseUrl();
255 - return baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null;
256 -};
301 +const captureToComposioAnalytics = (envelope: AnalyticsEnvelope) =>
302 + Effect.gen(function* () {
303 + const endpoint = yield* getAnalyticsEndpoint;
304 + const disabled = yield* analyticsDisabled;
305 + if (!endpoint || disabled) {
306 + yield* telemetryDebugLog('delivery_skipped', {
307 + reason: disabled ? 'disabled' : 'missing_endpoint',
308 + endpoint,
309 + eventName: envelope.event,
310 + });
311 + return;
312 + }
313
258 -export const shouldDisableAnalytics = (): boolean =>
259 - truthy(process.env.COMPOSIO_CLI_TELEMETRY_DISABLED) ||
260 - truthy(process.env.TELEMETRY_DISABLED) ||
261 - truthy(process.env.COMPOSIO_DISABLE_TELEMETRY) ||
262 - process.env.NODE_ENV === 'test' ||
263 - process.env.CI === 'true';
264 -
265 -const getWorkerSpawnArgs = (encodedPayload: string): { command: string; args: string[] } => {
266 - const maybeScriptPath = process.argv[1];
267 - const scriptPathLooksReal =
268 - typeof maybeScriptPath === 'string' &&
269 - maybeScriptPath.length > 0 &&
270 - fs.existsSync(maybeScriptPath) &&
271 - /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath);
272 -
273 - return scriptPathLooksReal
274 - ? {
275 - command: process.execPath,
276 - args: [maybeScriptPath, INTERNAL_ANALYTICS_WORKER_FLAG, encodedPayload],
277 - }
278 - : {
279 - command: process.execPath,
280 - args: [INTERNAL_ANALYTICS_WORKER_FLAG, encodedPayload],
281 - };
282 -};
314 + const httpClient = yield* HttpClient.HttpClient;
315 + const userApiKey = yield* getUserApiKey;
316 + const request = yield* HttpClientRequest.post(endpoint).pipe(
317 + HttpClientRequest.setHeaders({
318 + 'x-composio-analytics-source': 'cli',
319 + ...(userApiKey ? { 'x-user-api-key': userApiKey } : {}),
320 + }),
321 + HttpClientRequest.bodyJson(envelope)
322 + );
323 + const response = yield* httpClient.execute(request);
324 + const responseOk = response.status >= 200 && response.status < 300;
325 + const debugEnabled = yield* telemetryDebugEnabled;
326 + const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
327
284 -const captureToComposioAnalytics = async (envelope: AnalyticsEnvelope): Promise<void> => {
285 - const endpoint = getAnalyticsEndpoint();
286 - if (!endpoint || shouldDisableAnalytics()) {
287 - telemetryDebugLog('delivery_skipped', {
288 - reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
328 + yield* telemetryDebugLog(responseOk ? 'delivery_succeeded' : 'delivery_failed', {
329 endpoint,
330 eventName: envelope.event,
331 + status: response.status,
332 + ok: responseOk,
333 + responseBody: responseBody?.slice(0, 1000),
334 });
292 - return;
293 - }
294 -
295 - const userApiKey = getUserApiKey();
296 - const response = await fetch(endpoint, {
297 - method: 'POST',
298 - headers: {
299 - 'Content-Type': 'application/json',
300 - 'x-composio-analytics-source': 'cli',
301 - ...(userApiKey ? { 'x-user-api-key': userApiKey } : {}),
302 - },
303 - body: JSON.stringify(envelope),
335 });
305 - const responseBody =
306 - !response.ok && isTelemetryDebugEnabled() ? await response.text() : undefined;
307 -
308 - telemetryDebugLog(response.ok ? 'delivery_succeeded' : 'delivery_failed', {
309 - endpoint,
310 - eventName: envelope.event,
311 - status: response.status,
312 - ok: response.ok,
313 - responseBody: responseBody?.slice(0, 1000),
314 - });
315 -};
336
317 -export const createCliCodactFailureBody = (
318 - failure: CliCodactFailure
319 -): {
337 +type CliCodactFailureBody = {
338 failure_type: CliCodactFailureType;
339 tool_info?: CliCodactFailureToolInfo;
340 ctx: Record<string, unknown>;
341 session: Record<string, unknown>;
342 request_id?: string;
325 -} => ({
343 +};
344 +
345 +type CliInvocationContext = {
346 + readonly origin?: string;
347 + readonly parentRunId?: string;
348 +};
349 +
350 +const getCliInvocationContext = environmentProvider
351 + .load(
352 + Config.all({
353 + origin: optionalString('COMPOSIO_CLI_INVOCATION_ORIGIN'),
354 + parentRunId: optionalString('COMPOSIO_CLI_PARENT_RUN_ID'),
355 + })
356 + )
357 + .pipe(
358 + Effect.map(({ origin, parentRunId }) => ({
359 + origin: configuredString(origin),
360 + parentRunId: configuredString(parentRunId),
361 + }))
362 + );
363 +
364 +export const createCliCodactFailureBody = (
365 + failure: CliCodactFailure,
366 + cliSessionId?: string,
367 + invocation: CliInvocationContext = {}
368 +): CliCodactFailureBody => ({
369 failure_type: failure.failureType,
370 ...(failure.toolInfo ? { tool_info: failure.toolInfo } : {}),
371 ctx: failure.ctx,
372 session: {
373 source: 'cli',
331 - id: getCurrentCwdSessionId(),
374 + id: cliSessionId,
375 cli_version: constants.APP_VERSION,
333 - invocation_origin: process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli',
334 - parent_run_id: process.env.COMPOSIO_CLI_PARENT_RUN_ID,
376 + invocation_origin: invocation.origin ?? 'cli',
377 + parent_run_id: invocation.parentRunId,
378 ...(failure.session ?? {}),
379 },
380 ...(failure.requestId ? { request_id: failure.requestId } : {}),
381 });
382
340 -const captureToComposioCodactFailures = async (failure: CliCodactFailure): Promise<void> => {
341 - const endpoint = getCliCodactFailuresEndpoint();
342 - if (!endpoint || shouldDisableAnalytics()) {
343 - telemetryDebugLog('codact_delivery_skipped', {
344 - reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
345 - endpoint,
346 - failureType: failure.failureType,
347 - });
348 - return;
349 - }
383 +const captureToComposioCodactFailures = (failure: CliCodactFailure) =>
384 + Effect.gen(function* () {
385 + const endpoint = yield* getCliCodactFailuresEndpoint;
386 + const disabled = yield* analyticsDisabled;
387 + if (!endpoint || disabled) {
388 + yield* telemetryDebugLog('codact_delivery_skipped', {
389 + reason: disabled ? 'disabled' : 'missing_endpoint',
390 + endpoint,
391 + failureType: failure.failureType,
392 + });
393 + return;
394 + }
395 +
396 + const userApiKey = yield* getUserApiKey;
397 + if (!userApiKey) {
398 + yield* telemetryDebugLog('codact_delivery_skipped', {
399 + reason: 'missing_user_api_key',
400 + endpoint,
401 + failureType: failure.failureType,
402 + });
403 + return;
404 + }
405
351 - const userApiKey = getUserApiKey();
352 - if (!userApiKey) {
353 - telemetryDebugLog('codact_delivery_skipped', {
354 - reason: 'missing_user_api_key',
406 + const httpClient = yield* HttpClient.HttpClient;
407 + const cliSessionId = yield* getCurrentCwdSessionId();
408 + const invocation = yield* getCliInvocationContext;
409 + const body = createCliCodactFailureBody(failure, cliSessionId, invocation);
410 + const request = yield* HttpClientRequest.post(endpoint).pipe(
411 + HttpClientRequest.setHeader('x-user-api-key', userApiKey),
412 + HttpClientRequest.bodyJson(body)
413 + );
414 + const response = yield* httpClient.execute(request);
415 + const responseOk = response.status >= 200 && response.status < 300;
416 + const debugEnabled = yield* telemetryDebugEnabled;
417 + const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
418 +
419 + yield* telemetryDebugLog(responseOk ? 'codact_delivery_succeeded' : 'codact_delivery_failed', {
420 endpoint,
421 failureType: failure.failureType,
422 + status: response.status,
423 + ok: responseOk,
424 + responseBody: responseBody?.slice(0, 1000),
425 });
358 - return;
359 - }
360 -
361 - const response = await fetch(endpoint, {
362 - method: 'POST',
363 - headers: {
364 - 'Content-Type': 'application/json',
365 - 'x-user-api-key': userApiKey,
366 - },
367 - body: JSON.stringify(createCliCodactFailureBody(failure)),
368 - });
369 - const responseBody =
370 - !response.ok && isTelemetryDebugEnabled() ? await response.text() : undefined;
371 -
372 - telemetryDebugLog(response.ok ? 'codact_delivery_succeeded' : 'codact_delivery_failed', {
373 - endpoint,
374 - failureType: failure.failureType,
375 - status: response.status,
376 - ok: response.ok,
377 - responseBody: responseBody?.slice(0, 1000),
426 });
379 -};
427
381 -export const trackCliEvent = (event: TrackEvent): void => {
382 - const endpoint = getAnalyticsEndpoint();
383 - if (!event) {
384 - return;
385 - }
428 +export const trackCliEventEffect = (event: TrackEvent) =>
429 + Effect.gen(function* () {
430 + if (!event) {
431 + return;
432 + }
433
387 - if (shouldDisableAnalytics() || !endpoint) {
388 - telemetryDebugLog('skip', {
389 - reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
390 - eventName: event.name,
391 - endpoint,
392 - });
393 - return;
394 - }
434 + const endpoint = yield* getAnalyticsEndpoint;
435 + const disabled = yield* analyticsDisabled;
436 + if (disabled || !endpoint) {
437 + yield* telemetryDebugLog('skip', {
438 + reason: disabled ? 'disabled' : 'missing_endpoint',
439 + eventName: event.name,
440 + endpoint,
441 + });
442 + return;
443 + }
444
396 - try {
397 - const enrichedEvent = withCliSessionId(event);
445 + const cliSessionId = yield* getCurrentCwdSessionId();
446 + const enrichedEvent = withCliSessionId(event, cliSessionId);
447 if (!enrichedEvent) {
448 return;
449 }
401 - const installId = getOrCreateInstallId();
402 - const distinctId = getDistinctId();
450 +
451 + const installId = yield* getOrCreateInstallId;
452 + const distinctId = yield* getDistinctId(installId);
453 + const sentAt = DateTime.formatIso(yield* DateTime.now);
454 const envelope: AnalyticsEnvelope = {
455 event: enrichedEvent.name,
456 ...(enrichedEvent.properties ? { properties: enrichedEvent.properties } : {}),
406 - sentAt: new Date().toISOString(),
457 + sentAt,
458 source: 'cli',
459 distinctId,
460 installId,
461 };
411 - telemetryDebugLog('enqueue', {
412 - endpoint,
413 - envelope,
414 - });
415 - const encodedPayload = encodeBase64Url(JSON.stringify(envelope));
416 - const { command, args } = getWorkerSpawnArgs(encodedPayload);
417 - const child = spawn(command, args, {
418 - detached: true,
419 - stdio: isTelemetryDebugEnabled() ? ['ignore', 'ignore', 'inherit'] : 'ignore',
420 - env: {
421 - ...process.env,
422 - COMPOSIO_CLI_ANALYTICS_WORKER: '1',
423 - },
424 - });
425 - child.unref();
426 - } catch {
427 - // Analytics must never break CLI execution.
428 - }
429 -};
462 + yield* telemetryDebugLog('enqueue', { endpoint, envelope });
463 + const serializedEnvelope = yield* encodeJson(envelope);
464 + const encodedPayload = Encoding.encodeBase64Url(serializedEnvelope);
465 + const { command, args } = yield* getWorkerSpawnArgs(
466 + INTERNAL_ANALYTICS_WORKER_FLAG,
467 + encodedPayload
468 + );
469 + yield* spawnWorker(command, args);
470 + }).pipe(Effect.catchAllCause(() => Effect.void));
471
431 -export const trackCliEventEffect = (event: TrackEvent) => Effect.sync(() => trackCliEvent(event));
432 -
433 -export const trackCliCodactFailure = (failure: CliCodactFailure): void => {
434 - const endpoint = getCliCodactFailuresEndpoint();
435 - const userApiKey = getUserApiKey();
436 - if (shouldDisableAnalytics() || !endpoint || !userApiKey) {
437 - telemetryDebugLog('codact_skip', {
438 - reason: shouldDisableAnalytics()
439 - ? 'disabled'
440 - : !endpoint
441 - ? 'missing_endpoint'
442 - : 'missing_user_api_key',
443 - failureType: failure.failureType,
444 - endpoint,
445 - });
446 - return;
447 - }
472 +export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
473 + Effect.gen(function* () {
474 + const endpoint = yield* getCliCodactFailuresEndpoint;
475 + const userApiKey = yield* getUserApiKey;
476 + const disabled = yield* analyticsDisabled;
477 + if (disabled || !endpoint || !userApiKey) {
478 + yield* telemetryDebugLog('codact_skip', {
479 + reason: disabled ? 'disabled' : !endpoint ? 'missing_endpoint' : 'missing_user_api_key',
480 + failureType: failure.failureType,
481 + endpoint,
482 + });
483 + return;
484 + }
485
449 - try {
450 - const encodedPayload = encodeBase64Url(JSON.stringify(createCliCodactFailureBody(failure)));
451 - const { command, args } = getWorkerSpawnArgsForFlag(
486 + const cliSessionId = yield* getCurrentCwdSessionId();
487 + const invocation = yield* getCliInvocationContext;
488 + const body = yield* encodeJson(createCliCodactFailureBody(failure, cliSessionId, invocation));
489 + const encodedPayload = Encoding.encodeBase64Url(body);
490 + const { command, args } = yield* getWorkerSpawnArgs(
491 INTERNAL_CODACT_FAILURE_WORKER_FLAG,
492 encodedPayload
493 );
455 - const child = spawn(command, args, {
456 - detached: true,
457 - stdio: isTelemetryDebugEnabled() ? ['ignore', 'ignore', 'inherit'] : 'ignore',
458 - env: {
459 - ...process.env,
460 - COMPOSIO_CLI_ANALYTICS_WORKER: '1',
461 - },
462 - });
463 - child.unref();
464 - } catch {
465 - // Best-effort — codact failure tracking must never break CLI execution.
466 - }
467 -};
468 -
469 -export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
470 - Effect.sync(() => trackCliCodactFailure(failure));
471 -
472 -const getWorkerSpawnArgsForFlag = (
473 - workerFlag: string,
474 - encodedPayload: string
475 -): { command: string; args: string[] } => {
476 - const maybeScriptPath = process.argv[1];
477 - const scriptPathLooksReal =
478 - typeof maybeScriptPath === 'string' &&
479 - maybeScriptPath.length > 0 &&
480 - fs.existsSync(maybeScriptPath) &&
481 - /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath);
482 -
483 - return scriptPathLooksReal
484 - ? {
485 - command: process.execPath,
486 - args: [maybeScriptPath, workerFlag, encodedPayload],
487 - }
488 - : {
489 - command: process.execPath,
490 - args: [workerFlag, encodedPayload],
491 - };
492 -};
494 + yield* spawnWorker(command, args);
495 + }).pipe(Effect.catchAllCause(() => Effect.void));
496
497 const getWorkerFlagIndex = (argv: ReadonlyArray<string>, flag: string): number =>
498 argv.findIndex(token => token === flag);
@@ -498,45 +501,53 @@ export const isBackgroundWorkerInvocation = (argv: ReadonlyArray<string>): boole
501 getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG) >= 0 ||
502 getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG) >= 0;
503
501 -export const runBackgroundWorkerFromArgv = async (argv: ReadonlyArray<string>): Promise<void> => {
502 - const analyticsFlagIndex = getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG);
503 - if (analyticsFlagIndex >= 0) {
504 - const encodedPayload = argv[analyticsFlagIndex + 1];
505 - if (!encodedPayload) {
506 - return;
507 - }
504 +const decodeWorkerPayload = <A>(encodedPayload: string) =>
505 + Effect.gen(function* () {
506 + const serialized = yield* Encoding.decodeBase64UrlString(encodedPayload);
507 + return (yield* decodeJson(serialized)) as A;
508 + });
509
509 - try {
510 - const decoded = decodeBase64Url(encodedPayload);
511 - const envelope = JSON.parse(decoded) as AnalyticsEnvelope;
512 - if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
513 - return;
514 - }
515 - await captureToComposioAnalytics(envelope);
516 - } catch (error) {
517 - telemetryDebugLog('delivery_error', {
518 - error:
519 - error instanceof Error
520 - ? { name: error.name, message: error.message }
521 - : { message: String(error) },
522 - });
523 - }
524 - return;
510 +const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
511 + const flagIndex = getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG);
512 + if (flagIndex < 0) {
513 + return Effect.succeed(false);
514 + }
515 +
516 + const encodedPayload = argv[flagIndex + 1];
517 + if (!encodedPayload) {
518 + return Effect.succeed(true);
519 }
520
527 - const codactFlagIndex = getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG);
528 - if (codactFlagIndex < 0) {
529 - return;
521 + return Effect.gen(function* () {
522 + const envelope = yield* decodeWorkerPayload<AnalyticsEnvelope>(encodedPayload);
523 + if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
524 + return true;
525 + }
526 + yield* captureToComposioAnalytics(envelope);
527 + return true;
528 + }).pipe(
529 + Effect.catchAllCause(cause =>
530 + telemetryDebugLog('delivery_error', { error: telemetryErrorDetails(cause) }).pipe(
531 + Effect.as(true)
532 + )
533 + )
534 + );
535 +};
536 +
537 +const runCodactFailureWorker = (argv: ReadonlyArray<string>) => {
538 + const flagIndex = getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG);
539 + if (flagIndex < 0) {
540 + return Effect.void;
541 }
542
532 - const encodedPayload = argv[codactFlagIndex + 1];
543 + const encodedPayload = argv[flagIndex + 1];
544 if (!encodedPayload) {
534 - return;
545 + return Effect.void;
546 }
547
537 - try {
538 - const decoded = decodeBase64Url(encodedPayload);
539 - const body = JSON.parse(decoded) as ReturnType<typeof createCliCodactFailureBody>;
548 + return Effect.gen(function* () {
549 + const body =
550 + yield* decodeWorkerPayload<ReturnType<typeof createCliCodactFailureBody>>(encodedPayload);
551 if (
552 body?.failure_type !== 'wrong_tool_slug' &&
553 body?.failure_type !== 'wrong_tool_input_param'
@@ -544,19 +555,24 @@ export const runBackgroundWorkerFromArgv = async (argv: ReadonlyArray<string>):
555 return;
556 }
557
547 - await captureToComposioCodactFailures({
558 + yield* captureToComposioCodactFailures({
559 failureType: body.failure_type,
560 toolInfo: body.tool_info,
561 ctx: body.ctx,
562 session: body.session,
563 requestId: body.request_id,
564 });
554 - } catch (error) {
555 - telemetryDebugLog('codact_delivery_error', {
556 - error:
557 - error instanceof Error
558 - ? { name: error.name, message: error.message }
559 - : { message: String(error) },
560 - });
561 - }
565 + }).pipe(
566 + Effect.catchAllCause(cause =>
567 + telemetryDebugLog('codact_delivery_error', { error: telemetryErrorDetails(cause) })
568 + )
569 + );
570 };
571 +
572 +export const runBackgroundWorkerFromArgv = (argv: ReadonlyArray<string>) =>
573 + Effect.gen(function* () {
574 + const handledAnalytics = yield* runAnalyticsWorker(argv);
575 + if (!handledAnalytics) {
576 + yield* runCodactFailureWorker(argv);
577 + }
578 + }).pipe(Effect.catchAllCause(() => Effect.void));
ts/packages/cli/src/analytics/events.ts
+6 -3
@@ -338,12 +338,15 @@ const isGenericOnlyCommand = (commandPath: string): boolean =>
338
339 export const createCliCommandTelemetryContext = (
340 argv: ReadonlyArray<string>,
341 - cliVersion: string
341 + cliVersion: string,
342 + terminal: { readonly stdoutIsTTY: boolean; readonly stderrIsTTY: boolean }
343 ): CliCommandTelemetryContext => ({
344 argv,
345 cliVersion,
346 commandPath: extractCommandPath(argv),
347 flagNames: extractFlagNames(argv),
348 + stdoutIsTTY: terminal.stdoutIsTTY,
349 + stderrIsTTY: terminal.stderrIsTTY,
350 startedAt: Date.now(),
351 runId:
352 extractCommandPath(argv) === 'run'
@@ -360,8 +363,8 @@ const getCliCommandInvokedEvent = (context: CliCommandTelemetryContext): TrackEv
363 command_path: context.commandPath,
364 flag_names: context.flagNames,
365 arg_count: Math.max(0, context.argv.length - 2),
363 - stdout_is_tty: Boolean(process.stdout.isTTY),
364 - stderr_is_tty: Boolean(process.stderr.isTTY),
366 + stdout_is_tty: context.stdoutIsTTY,
367 + stderr_is_tty: context.stderrIsTTY,
368 },
369 });
370
ts/packages/cli/src/analytics/types.ts
+2
@@ -17,6 +17,8 @@ export type CliCommandTelemetryContext = {
17 readonly cliVersion: string;
18 readonly commandPath: string;
19 readonly flagNames: ReadonlyArray<string>;
20 + readonly stdoutIsTTY: boolean;
21 + readonly stderrIsTTY: boolean;
22 readonly startedAt: number;
23 readonly runId?: string;
24 };
ts/packages/cli/src/bin.ts
+23 -3
@@ -1,5 +1,10 @@
1 import process from 'node:process';
2 +import { Effect, Layer } from 'effect';
3 +import { FetchHttpClient } from '@effect/platform';
4 +import { BunFileSystem, BunPath, BunRuntime } from '@effect/platform-bun';
5 import { isBackgroundWorkerInvocation, runBackgroundWorkerFromArgv } from 'src/analytics/dispatch';
6 +import { NodeOs } from 'src/services/node-os';
7 +import { TerminalUILive } from 'src/services/terminal-ui';
8
9 const TELEMETRY_DEBUG_FLAG = '--telemetry-debug';
10 const CLI_TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';
@@ -12,14 +17,29 @@ const stripTelemetryDebugFlag = (argv: ReadonlyArray<string>): string[] => {
17 }
18
19 normalizedArgv.splice(flagIndex, 1);
20 + // Bootstrap runs before the Effect runtime and ConfigProvider exist; the stripped flag is
21 + // persisted as an env var so later effect/Config reads and child processes observe it.
22 process.env[CLI_TELEMETRY_DEBUG_ENV_VAR] = 'true';
23 return normalizedArgv;
24 };
25
26 if (isBackgroundWorkerInvocation(process.argv)) {
20 - void runBackgroundWorkerFromArgv(process.argv).finally(() => {
21 - process.exit(0);
22 - });
27 + runBackgroundWorkerFromArgv(process.argv).pipe(
28 + Effect.provide(
29 + Layer.mergeAll(
30 + BunFileSystem.layer,
31 + BunPath.layer,
32 + FetchHttpClient.layer,
33 + NodeOs.Default,
34 + TerminalUILive
35 + )
36 + ),
37 + effect =>
38 + BunRuntime.runMain(effect, {
39 + disableErrorReporting: true,
40 + teardown: (_exit, onExit) => onExit(0),
41 + })
42 + );
43 } else {
44 process.argv = stripTelemetryDebugFlag(process.argv);
45 void import('./cli-main');
ts/packages/cli/src/cli-main.ts
+49 -35
@@ -1,5 +1,5 @@
1 import process from 'node:process';
2 -import { Cause, Console, Effect, Exit, HashMap, Layer, Logger, Option } from 'effect';
2 +import { Cause, Effect, Exit, HashMap, Layer, Logger, Option } from 'effect';
3 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
4 import { CliConfig, CommandDescriptor, HelpDoc, Usage, ValidationError } from '@effect/cli';
5 import { FetchHttpClient } from '@effect/platform';
@@ -36,14 +36,14 @@ import {
36 getPrimaryLifecycleInvokedEvent,
37 getPrimaryLifecycleSucceededEvent,
38 } from 'src/analytics/events';
39 -import { trackCliEvent, trackCliEventEffect } from 'src/analytics/dispatch';
39 +import { trackCliEventEffect } from 'src/analytics/dispatch';
40 import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
41 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
42 import { SetupCommandError } from 'src/services/setup';
43 -import { canRenderTerminalDecoration } from 'src/utils/stdio';
43
45 -// eslint-disable-next-line @typescript-eslint/no-explicit-any
46 -type RequiredLayer = Layer.Layer<any, any, never>;
44 +// Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any
45 +// produced context and error type while still pinning the requirements (RIn) to `never`.
46 +type RequiredLayer = Layer.Layer<never, unknown, never>;
47
48 export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies RequiredLayer;
49
@@ -74,7 +74,7 @@ export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
74
75 export const UpgradeBinaryLive = Layer.provide(
76 UpgradeBinary.Default,
77 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, FetchHttpClient.layer)
77 + Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
78 ) satisfies RequiredLayer;
79
80 export const TriggersRealtimeLive = Layer.provide(
@@ -94,7 +94,7 @@ export const ToolsExecutorLive = Layer.provide(
94
95 export const ProjectContextLive = Layer.provide(
96 ProjectContext.Default,
97 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, NodeProcess.Default)
97 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
98 ) satisfies RequiredLayer;
99
100 export const SetupSkillInstallerLive = Layer.provide(
@@ -140,14 +140,6 @@ const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) sati
140 unknown
141 >;
142
143 -const commandTelemetryContext = createCliCommandTelemetryContext(
144 - process.argv,
145 - constants.APP_VERSION
146 -);
147 -if (commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId) {
148 - process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;
149 -}
150 -
143 const collectValueOptionNamesFromUsage = (usage: Usage.Usage, acc: Set<string>) => {
144 switch (usage._tag) {
145 case 'Named': {
@@ -195,23 +187,44 @@ const collectValueOptionNames = (rootCommand: ReturnType<typeof buildRootCommand
187 return names;
188 };
189
198 -showUpdateNotice();
199 -checkForUpdateInBackground();
200 -trackCliEvent(getPrimaryLifecycleInvokedEvent(commandTelemetryContext));
190 +const runWithTelemetry = Effect.gen(function* () {
191 + const ui = yield* TerminalUI;
192 + const terminal = yield* ui.capabilities;
193 + const commandTelemetryContext = createCliCommandTelemetryContext(
194 + process.argv,
195 + constants.APP_VERSION,
196 + terminal
197 + );
198 + if (commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId) {
199 + // effect/Config is read-only; the run id must be written into the environment so the run
200 + // command and the child processes it spawns observe the same telemetry run id.
201 + process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;
202 + }
203
202 -runWithArgs.pipe(
203 - Effect.scoped,
204 - Effect.mapError(error =>
205 - ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
206 - ),
207 - Effect.tap(() => trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))),
208 - Effect.tapErrorCause(cause =>
209 - trackCliEventEffect(
210 - getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
204 + return yield* trackCliEventEffect(getPrimaryLifecycleInvokedEvent(commandTelemetryContext)).pipe(
205 + Effect.andThen(runWithArgs),
206 + Effect.scoped,
207 + Effect.mapError(error =>
208 + ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
209 + ),
210 + Effect.tap(() =>
211 + trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))
212 + ),
213 + Effect.tapErrorCause(cause =>
214 + trackCliEventEffect(
215 + getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
216 + )
217 )
212 - ),
218 + );
219 +});
220 +
221 +checkForUpdateInBackground();
222 +
223 +showUpdateNotice.pipe(
224 + Effect.andThen(runWithTelemetry),
225 Effect.catchIf(ValidationError.isValidationError, error => {
226 return Effect.gen(function* () {
227 + const ui = yield* TerminalUI;
228 const cliUserConfig = yield* ComposioCliUserConfig;
229 const visibility = {
230 isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
@@ -220,15 +233,15 @@ runWithArgs.pipe(
233 };
234 const valueOptionNames = collectValueOptionNames(buildRootCommand(visibility));
235 const text = HelpDoc.toAnsiText(error.error).trim();
223 - const errorEffect = text.length > 0 ? Console.error(text) : Effect.void;
236 + const errorEffect = text.length > 0 ? ui.error(text) : Effect.void;
237 const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);
238 const tipEffect =
239 flagMatch && valueOptionNames.has(flagMatch[1])
227 - ? Console.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)
240 + ? ui.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)
241 : Effect.void;
242 const cmdName = matchCommandFromArgv(process.argv, visibility);
243 const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
231 - const helpEffect = helpText ? Console.error(helpText) : Effect.void;
244 + const helpEffect = helpText ? ui.error(helpText) : Effect.void;
245 return yield* Effect.all([errorEffect, tipEffect, helpEffect], { discard: true }).pipe(
246 Effect.tap(() =>
247 Effect.sync(() => {
@@ -247,11 +260,11 @@ runWithArgs.pipe(
260 error.operation === 'uninstall'
261 ? 'Composio plugin uninstall was unsuccessful.'
262 : 'Composio setup was unsuccessful.';
250 - if (canRenderTerminalDecoration()) {
263 + if ((yield* ui.capabilities).canDecorate) {
264 yield* ui.log.error(error.message);
265 yield* ui.outro(summary);
266 } else {
254 - yield* Console.error(`${summary} ${error.message}`);
267 + yield* ui.error(`${summary} ${error.message}`);
268 }
269 process.exitCode = 1;
270 })
@@ -281,7 +294,8 @@ runWithArgs.pipe(
294 }
295 ).trim();
296 if (message.length > 0) {
284 - yield* Console.error(message);
297 + const ui = yield* TerminalUI;
298 + yield* ui.error(message);
299 const cliUserConfig = yield* ComposioCliUserConfig;
300 const visibility = {
301 isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
@@ -291,7 +305,7 @@ runWithArgs.pipe(
305 const cmdName = matchCommandFromArgv(process.argv, visibility);
306 const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
307 if (helpText) {
294 - yield* Console.error(helpText);
308 + yield* ui.error(helpText);
309 }
310 process.exitCode = 1;
311 }
ts/packages/cli/src/commands/artifacts.cmd.ts
+3 -2
@@ -1,20 +1,21 @@
1 -import process from 'node:process';
1 import { Command } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 import {
4 resolveArtifactsRoot,
5 resolveCliSessionArtifacts,
6 } from 'src/services/cli-session-artifacts';
7 +import { TerminalUI } from 'src/services/terminal-ui';
8
9 const cwdCmd = Command.make('cwd').pipe(
10 Command.withDescription('Print the cwd-scoped session artifact directory.'),
11 Command.withHandler(() =>
12 Effect.gen(function* () {
13 + const ui = yield* TerminalUI;
14 const artifacts = yield* resolveCliSessionArtifacts();
15 const directoryPath = Option.isSome(artifacts)
16 ? artifacts.value.directoryPath
17 : yield* resolveArtifactsRoot;
17 - process.stdout.write(`${directoryPath}\n`);
18 + yield* ui.output(directoryPath, { force: true });
19 })
20 )
21 );
ts/packages/cli/src/commands/index.ts
+3
@@ -541,6 +541,7 @@ export const runWithConfig = Effect.gen(function* () {
541 }
542 if (isGenerateGraph(normalizedArgv)) {
543 return Effect.sync(() => {
544 + // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
545 process.stdout.write(`${JSON.stringify(renderCommandHintGraph(), null, 2)}\n`);
546 });
547 }
@@ -565,6 +566,7 @@ export const runWithConfig = Effect.gen(function* () {
566 Effect.option
567 );
568 return yield* Effect.sync(() => {
569 + // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
570 process.stdout.write(
571 `${JSON.stringify(
572 {
@@ -584,6 +586,7 @@ export const runWithConfig = Effect.gen(function* () {
586 }
587 if (isDebugWhoIsMyMaster(normalizedArgv)) {
588 return Effect.sync(() => {
589 + // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
590 process.stdout.write(`${JSON.stringify({ master: detectMaster() }, null, 2)}\n`);
591 });
592 }
ts/packages/cli/src/commands/login.cmd.ts
+2 -3
@@ -21,7 +21,6 @@ import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/co
21 import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
22 import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
23 import { APP_VERSION } from 'src/constants';
24 -import { isInteractiveTerminal } from 'src/utils/stdio';
24 import {
25 ensureAgentSignupAllowed,
26 getOrSignupReadyAgent,
@@ -612,7 +611,7 @@ export const browserLogin = (params: {
611 expiresAt,
612 });
613
615 - const canPrompt = isInteractiveTerminal();
614 + const canPrompt = (yield* ui.capabilities).isInteractive;
615 const effectiveNoWait = params.noWait || !canPrompt;
616 const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
617
@@ -782,7 +781,7 @@ export const loginCmd = Command.make(
781 Effect.gen(function* () {
782 const ui = yield* TerminalUI;
783 const ctx = yield* ComposioUserContext;
785 - const canPrompt = isInteractiveTerminal();
784 + const canPrompt = (yield* ui.capabilities).isInteractive;
785
786 if (canPrompt) {
787 yield* ui.intro('composio login');
ts/packages/cli/src/commands/root-help.ts
+16 -7
@@ -1,5 +1,6 @@
1 -import { Console, Effect, Option } from 'effect';
1 +import { Effect, Option } from 'effect';
2 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
3 +import { TerminalUI } from 'src/services/terminal-ui';
4 import { bold, dim, gray } from 'src/ui/colors';
5 import {
6 type CommandVisibility,
@@ -1406,11 +1407,19 @@ export function printSubcommandHelp(
1407 cmd: string,
1408 visibility: CommandVisibility,
1409 helpLevel: HelpLevel = 'default'
1409 -): Effect.Effect<void> {
1410 - if (cmd === 'dev') return Console.log(renderDevHelp(visibility, helpLevel));
1410 +): Effect.Effect<void, never, TerminalUI> {
1411 + if (cmd === 'dev') {
1412 + return Effect.flatMap(TerminalUI, ui =>
1413 + ui.output(renderDevHelp(visibility, helpLevel), { force: true })
1414 + );
1415 + }
1416 const help = getVisibleSubcommandHelp(cmd, visibility, helpLevel);
1412 - if (Option.isNone(help)) return Console.log(`Unknown command: ${cmd}`);
1413 - return Console.log(renderSubcommandHelp(help.value, helpLevel));
1417 + if (Option.isNone(help)) {
1418 + return Effect.flatMap(TerminalUI, ui => ui.output(`Unknown command: ${cmd}`, { force: true }));
1419 + }
1420 + return Effect.flatMap(TerminalUI, ui =>
1421 + ui.output(renderSubcommandHelp(help.value, helpLevel), { force: true })
1422 + );
1423 }
1424
1425 /**
@@ -1452,7 +1461,7 @@ export function getCommandHelpText(cmd: string, visibility: CommandVisibility):
1461 export function printRootHelp(
1462 visibility: CommandVisibility,
1463 helpLevel: HelpLevel = 'default'
1455 -): Effect.Effect<void> {
1464 +): Effect.Effect<void, never, TerminalUI> {
1465 const name = 'composio';
1466 const developerCommands: ReadonlyArray<CompactCommand> = [
1467 {
@@ -1584,5 +1593,5 @@ export function printRootHelp(
1593 '',
1594 ];
1595
1587 - return Console.log(lines.join('\n'));
1596 + return Effect.flatMap(TerminalUI, ui => ui.output(lines.join('\n'), { force: true }));
1597 }
ts/packages/cli/src/commands/run.cmd.ts
+3 -1
@@ -24,6 +24,7 @@ import {
24 resolveCliSessionArtifacts,
25 } from 'src/services/cli-session-artifacts';
26 import { USER_COMPOSIO_DIR } from 'src/constants';
27 +import { TerminalUI } from 'src/services/terminal-ui';
28
29 const file = Options.text('file').pipe(
30 Options.withAlias('f'),
@@ -471,6 +472,7 @@ export const runCmd = Command.make('run', {
472 helperContext,
473 runHelperModuleUrls
474 );
475 + const ui = yield* TerminalUI;
476 let cleanupPaths: ReadonlyArray<string> = [];
477 try {
478 yield* appendCliSessionHistory({
@@ -484,7 +486,7 @@ export const runCmd = Command.make('run', {
486 debug,
487 },
488 }).pipe(Effect.catchAll(() => Effect.void));
487 - process.stderr.write(`RUN_LOG_FILE=${preload.runLogFilePath}\n`);
489 + yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
490 const runCommand = buildRunCommand({
491 path,
492 file,
ts/packages/cli/src/commands/setup.cmd.ts
+2 -3
@@ -14,7 +14,6 @@ import {
14 } from 'src/services/setup';
15 import { TerminalUI } from 'src/services/terminal-ui';
16 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
17 -import { isInteractiveTerminal } from 'src/utils/stdio';
17
18 const target = Options.choice('target', SETUP_TARGETS).pipe(
19 Options.withDefault('auto' as SetupTarget),
@@ -146,7 +145,7 @@ const setupBaseCmd = Command.make(
145 }
146
147 if (!yes && removable.length > 0) {
149 - if (!isInteractiveTerminal()) {
148 + if (!(yield* ui.capabilities).isInteractive) {
149 return yield* Effect.fail(
150 new Error('Non-interactive uninstall requires `--yes` to approve local changes.')
151 );
@@ -186,7 +185,7 @@ const setupBaseCmd = Command.make(
185
186 const pendingPlugins = pending.filter(status => !isSetupPluginReady(status));
187 if (!yes) {
189 - if (!isInteractiveTerminal()) {
188 + if (!(yield* ui.capabilities).isInteractive) {
189 return yield* Effect.fail(
190 new Error('Non-interactive setup requires `--yes` to approve local changes.')
191 );
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+2
@@ -342,6 +342,7 @@ const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirecto
342 const perfDebugEpoch = Date.now();
343 const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {
344 if (!isPerfDebugEnabled()) return;
345 + // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
346 process.stderr.write(
347 `[perf] ${JSON.stringify({
348 phase: 'event',
@@ -353,6 +354,7 @@ const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {
354 };
355 const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {
356 if (!isToolDebugEnabled()) return;
357 + // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
358 process.stderr.write(`[tool-debug] ${JSON.stringify({ label, ...details })}\n`);
359 };
360
ts/packages/cli/src/services/command-runner.ts
+6 -2
@@ -16,9 +16,13 @@ export class CommandRunner extends Effect.Service<CommandRunner>()('services/Com
16 capture: (command: Command.Command) =>
17 Effect.scoped(
18 Effect.gen(function* () {
19 - const process = yield* Command.start(command);
19 + const childProcess = yield* Command.start(command);
20 const [exitCode, stdout, stderr] = yield* Effect.all(
21 - [process.exitCode, collectText(process.stdout), collectText(process.stderr)],
21 + [
22 + childProcess.exitCode,
23 + collectText(childProcess.stdout),
24 + collectText(childProcess.stderr),
25 + ],
26 { concurrency: 'unbounded' }
27 );
28 return { exitCode: Number(exitCode), stdout, stderr } satisfies CommandResult;
ts/packages/cli/src/services/composio-clients.ts
+15 -3
@@ -13,6 +13,7 @@ import {
13 SynchronizedRef,
14 } from 'effect';
15 import { Composio as _RawComposioClient, APIPromise } from '@composio/client';
16 +import { FileSystem, Path } from '@effect/platform';
17 import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
18 import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
19 import {
@@ -36,6 +37,7 @@ import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigg
37 import * as constants from 'src/constants';
38 import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
39 import { ComposioUserContext, ComposioUserContextLive } from './user-context';
40 +import { NodeOs } from './node-os';
41 import { ProjectContext } from './project-context';
42 import type { NoSuchElementException } from 'effect/Cause';
43 import { renderPrettyError } from './utils/pretty-error';
@@ -1338,8 +1340,8 @@ const buildDefaultHeaders = (params: {
1340 userApiKey?: string;
1341 orgId?: string;
1342 projectId?: string;
1343 + cliSessionId?: string;
1344 }): Record<string, string> | undefined => {
1342 - const cliSessionId = getCurrentCwdSessionId();
1345 const defaultHeaders = {
1346 'x-framework': 'cli',
1347 'x-source': 'CLI',
@@ -1354,8 +1356,8 @@ const buildDefaultHeaders = (params: {
1356 'x-project-id': params.projectId,
1357 } satisfies Record<string, string>)
1358 : {}),
1357 - ...(cliSessionId
1358 - ? ({ 'x-cli-session-id': cliSessionId } satisfies Record<string, string>)
1359 + ...(params.cliSessionId
1360 + ? ({ 'x-cli-session-id': params.cliSessionId } satisfies Record<string, string>)
1361 : {}),
1362 };
1363
@@ -1520,6 +1522,9 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
1522 effect: Effect.gen(function* () {
1523 const ctx = yield* ComposioUserContext;
1524 const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
1525 + const fs = yield* FileSystem.FileSystem;
1526 + const path = yield* Path.Path;
1527 + const os = yield* NodeOs;
1528 const cache = new Map<string, _RawComposioClient>();
1529
1530 const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
@@ -1537,6 +1542,12 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
1542 return cached;
1543 }
1544
1545 + const cliSessionId = yield* getCurrentCwdSessionId().pipe(
1546 + Effect.provideService(FileSystem.FileSystem, fs),
1547 + Effect.provideService(Path.Path, path),
1548 + Effect.provideService(NodeOs, os)
1549 + );
1550 +
1551 const client = new _RawComposioClient({
1552 apiKey: null,
1553 baseURL: ctx.data.baseURL,
@@ -1544,6 +1555,7 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
1555 userApiKey: apiKey,
1556 orgId: params?.orgId,
1557 projectId: params?.projectId,
1558 + cliSessionId,
1559 }),
1560 });
1561
ts/packages/cli/src/services/run-helpers-runtime.ts
+1
@@ -326,6 +326,7 @@ export const installRunHelpers = async ({
326 const line = formattedLine ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`;
327 appendRunLogLine(line);
328 if (shouldStreamHelperLog(step, formattedLine)) {
329 + // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
330 process.stderr.write(`${line}\n`);
331 }
332 };
ts/packages/cli/src/services/run-subagent-output-mcp.ts
+1
@@ -57,6 +57,7 @@ const main = async (): Promise<void> => {
57
58 void main().catch(error => {
59 const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
60 + // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
61 process.stderr.write(`${message}\n`);
62 process.exit(1);
63 });
ts/packages/cli/src/services/runtime-debug-logger.ts new
+28
@@ -0,0 +1,28 @@
1 +import { Effect } from 'effect';
2 +import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
3 +import { TerminalUI } from 'src/services/terminal-ui';
4 +
5 +const writeJsonDebugLine = (channel: string, payload: Record<string, unknown>) =>
6 + Effect.gen(function* () {
7 + const ui = yield* TerminalUI;
8 + yield* ui.error(`[${channel}] ${JSON.stringify(payload)}`);
9 + });
10 +
11 +export const logToolDebug = (label: string, details: Record<string, unknown> = {}) =>
12 + Effect.suspend(() =>
13 + isToolDebugEnabled() ? writeJsonDebugLine('tool-debug', { label, ...details }) : Effect.void
14 + );
15 +
16 +export const makePerfDebugLogger =
17 + (startedAt: number = Date.now()) =>
18 + (label: string, details: Record<string, unknown> = {}) =>
19 + Effect.suspend(() =>
20 + isPerfDebugEnabled()
21 + ? writeJsonDebugLine('perf', {
22 + phase: 'event',
23 + label,
24 + elapsedMs: Date.now() - startedAt,
25 + ...details,
26 + })
27 + : Effect.void
28 + );
ts/packages/cli/src/services/terminal-ui.ts
+57 -5
@@ -1,7 +1,39 @@
1 import process from 'node:process';
2 import * as p from '@clack/prompts';
3 import { Context, Effect, Exit, Layer } from 'effect';
4 -import { canRenderTerminalDecoration, isInteractiveTerminal } from 'src/utils/stdio';
4 +
5 +export type TtyLikeStream = {
6 + readonly isTTY?: boolean;
7 +};
8 +
9 +export type TerminalStdio = {
10 + readonly stdin: TtyLikeStream;
11 + readonly stdout: TtyLikeStream;
12 + readonly stderr: TtyLikeStream;
13 +};
14 +
15 +export type TerminalCapabilities = {
16 + readonly stdinIsTTY: boolean;
17 + readonly stdoutIsTTY: boolean;
18 + readonly stderrIsTTY: boolean;
19 + readonly isInteractive: boolean;
20 + readonly canDecorate: boolean;
21 +};
22 +
23 +/** Classify terminal streams without coupling callers or tests to Node globals. */
24 +export const getTerminalCapabilities = (stdio: TerminalStdio): TerminalCapabilities => {
25 + const stdinIsTTY = Boolean(stdio.stdin.isTTY);
26 + const stdoutIsTTY = Boolean(stdio.stdout.isTTY);
27 + const stderrIsTTY = Boolean(stdio.stderr.isTTY);
28 +
29 + return {
30 + stdinIsTTY,
31 + stdoutIsTTY,
32 + stderrIsTTY,
33 + isInteractive: stdinIsTTY && stdoutIsTTY && stderrIsTTY,
34 + canDecorate: stderrIsTTY,
35 + };
36 +};
37
38 // ---------------------------------------------------------------------------
39 // SpinnerHandle — returned by `useMakeSpinner` for manual control
@@ -21,6 +53,9 @@ export interface SpinnerHandle {
53 // ---------------------------------------------------------------------------
54
55 export interface TerminalUI {
56 + /** Capabilities of the streams backing this terminal service. */
57 + readonly capabilities: Effect.Effect<TerminalCapabilities>;
58 +
59 /**
60 * Write raw data to stdout for piping and scripting.
61 *
@@ -33,6 +68,14 @@ export interface TerminalUI {
68 */
69 readonly output: (data: string, options?: { readonly force?: boolean }) => Effect.Effect<void>;
70
71 + /**
72 + * Write an unformatted line to stderr even when stderr is redirected.
73 + *
74 + * Use this for diagnostics and protocol metadata that must survive piping.
75 + * Human-facing decoration belongs in `log`, `note`, `intro`, or `outro`.
76 + */
77 + readonly error: (data: string) => Effect.Effect<void>;
78 +
79 /** Display a session start marker (e.g., `┌ title`). Writes to stderr. */
80 readonly intro: (title: string) => Effect.Effect<void>;
81 /** Display a session end marker (e.g., `└ message`). Writes to stderr. */
@@ -116,14 +159,20 @@ export const TerminalUI = Context.GenericTag<TerminalUI>('services/TerminalUI');
159 * when stdin/stdout/stderr are all TTYs; agent and shell pipelines get
160 * non-interactive behavior.
161 */
119 -const canPrompt = isInteractiveTerminal();
162 +const liveCapabilities = getTerminalCapabilities({
163 + stdin: process.stdin,
164 + stdout: process.stdout,
165 + stderr: process.stderr,
166 +});
167 +
168 +const canPrompt = liveCapabilities.isInteractive;
169
170 /**
171 * Whether the CLI can render auxiliary UI. Logs, notes, and spinners only need
172 * stderr, so they can still be shown when stdin is redirected from /dev/null or
173 * stdout is reserved for machine-readable JSON/data.
174 */
126 -const canDecorate = canRenderTerminalDecoration();
175 +const canDecorate = liveCapabilities.canDecorate;
176
177 /** Run a decoration side-effect only when stderr is a terminal. */
178 function decorate(fn: () => void): void {
@@ -161,6 +210,8 @@ const silentSpinnerHandle: SpinnerHandle = {
210 };
211
212 const makeLive: TerminalUI = {
213 + capabilities: Effect.succeed(liveCapabilities),
214 +
215 output: (data, options) =>
216 Effect.sync(() => {
217 if (options?.force || !canPrompt) {
@@ -168,6 +219,8 @@ const makeLive: TerminalUI = {
219 }
220 }),
221
222 + error: data => Effect.sync(() => process.stderr.write(`${data}\n`)),
223 +
224 intro: title => Effect.sync(() => decorate(() => p.intro(title, { output: process.stderr }))),
225 outro: message => Effect.sync(() => decorate(() => p.outro(message, { output: process.stderr }))),
226
@@ -199,8 +252,7 @@ const makeLive: TerminalUI = {
252 ? Effect.promise(async () => {
253 const result = await p.select({
254 message,
202 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
203 - options: [...options] as any,
255 + options: [...options],
256 output: process.stderr,
257 });
258 // p.select returns Value | symbol (symbol on cancel)
ts/packages/cli/src/services/update-check.ts
+139 -117
@@ -1,26 +1,20 @@
1 -// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
2 -import { readFileSync, mkdirSync } from 'node:fs';
3 -// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
4 -import { writeFile } from 'node:fs/promises';
5 -// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
6 -import { arch as getArch, homedir, platform as getPlatform } from 'node:os';
7 -// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
8 -import { dirname, join } from 'node:path';
1 +import { FileSystem, Path } from '@effect/platform';
2 +import { BunFileSystem } from '@effect/platform-bun';
3 +import { Config, Data, Effect, Layer, Option, Predicate, Schema } from 'effect';
4 import semver from 'semver';
5 import { bold, cyanBright, dim } from 'src/ui/colors';
6 import { APP_VERSION, GITHUB_REPO } from '../constants';
12 -import { isInteractiveTerminal } from 'src/utils/stdio';
13 -// The sync bridge keeps this pre-migration module working until the
14 -// typed-error slice (PR 8 of this stack) makes it Effect-native.
15 -import { resolveInstalledCliVersionSync } from './run-companion-modules';
7 +import { NodeOs } from './node-os';
8 +import { resolveInstalledCliVersion } from './run-companion-modules';
9 +import { TerminalUI } from './terminal-ui';
10
11 /**
12 * Background update check for @composio/cli.
13 *
20 - * Two entry points, both called synchronously from bin.ts BEFORE the Effect
21 - * runtime boots — they must never block or throw:
14 + * Two entry points, both called from cli-main BEFORE the root command's
15 + * Effect runtime boots — they must never block or throw:
16 *
23 - * showUpdateNotice() — sync file read (~1 ms)
17 + * showUpdateNotice — reads a tiny cached JSON file (~1 ms)
18 * checkForUpdateInBackground() — fire-and-forget fetch, no await
19 *
20 * Strategy:
@@ -34,18 +28,23 @@ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
28 /** Matches `@composio/cli@<semver>` — excludes prereleases. */
29 const CLI_RELEASE_TAG_RE = /^@composio\/cli@(\d+\.\d+\.\d+)$/;
30
37 -export interface UpdateCheckRelease {
38 - tag_name?: unknown;
39 - prerelease?: unknown;
40 - draft?: unknown;
41 - assets?: unknown;
42 -}
43 -
31 export interface UpdateCheckState {
32 lastChecked: string; // ISO-8601
33 latestVersion: string; // e.g. "0.3.0"
34 }
35
36 +const UpdateCheckStateSchema = Schema.parseJson(
37 + Schema.Struct({
38 + lastChecked: Schema.String,
39 + latestVersion: Schema.String,
40 + })
41 +);
42 +
43 +/** Non-2xx response from the GitHub releases API; swallowed after the state write. */
44 +class UpdateCheckHttpError extends Data.TaggedError('UpdateCheckHttpError')<{
45 + readonly status: number;
46 +}> {}
47 +
48 // ── Injectable configuration ────────────────────────────────────────────
49
50 /** Dependencies injected into the update checker — mirrors the Effect service pattern. */
@@ -57,14 +56,17 @@ export interface UpdateCheckConfig {
56 readonly binaryAssetName: string | undefined;
57 readonly accessToken: string | undefined;
58 readonly fetchFn: (url: string, init?: RequestInit) => Promise<Response>;
60 - readonly isInteractive: () => boolean;
59 }
60
63 -const _home = join(homedir(), '.composio');
61 +const defaultStateFile = Effect.gen(function* () {
62 + const path = yield* Path.Path;
63 + const os = yield* NodeOs;
64 + return path.join(os.homedir, '.composio', 'update-check.json');
65 +});
66
65 -function getCurrentBinaryAssetName(): string | undefined {
66 - const platform = getPlatform();
67 - const rawArch: string = getArch();
67 +function getCurrentBinaryAssetName(os: Pick<NodeOs, 'platform' | 'arch'>): string | undefined {
68 + const { platform } = os;
69 + const rawArch: string = os.arch;
70 if (platform !== 'darwin' && platform !== 'linux') return undefined;
71
72 const arch = rawArch === 'arm64' || rawArch === 'aarch64' ? 'aarch64' : rawArch;
@@ -73,16 +75,25 @@ function getCurrentBinaryAssetName(): string | undefined {
75 return `composio-${platform}-${arch}.zip`;
76 }
77
76 -const defaultConfig: UpdateCheckConfig = {
77 - stateFile: join(_home, 'update-check.json'),
78 - currentVersion: resolveInstalledCliVersionSync(process.execPath, APP_VERSION),
79 - checkIntervalMs: CHECK_INTERVAL_MS,
80 - releasesUrl: `${GITHUB_REPO.API_BASE_URL}/repos/${GITHUB_REPO.OWNER}/${GITHUB_REPO.REPO}/releases?per_page=100`,
81 - binaryAssetName: getCurrentBinaryAssetName(),
82 - accessToken: process.env.COMPOSIO_GITHUB_ACCESS_TOKEN,
83 - fetchFn: fetch,
84 - isInteractive: isInteractiveTerminal,
85 -};
78 +const defaultConfig = (stateFile: string) =>
79 + Effect.gen(function* () {
80 + const os = yield* NodeOs;
81 + const currentVersion = yield* resolveInstalledCliVersion(process.execPath, APP_VERSION);
82 + const accessToken = yield* Effect.orDie(
83 + Config.option(Config.string('COMPOSIO_GITHUB_ACCESS_TOKEN')).pipe(
84 + Config.map(Option.getOrUndefined)
85 + )
86 + );
87 + return {
88 + stateFile,
89 + currentVersion,
90 + checkIntervalMs: CHECK_INTERVAL_MS,
91 + releasesUrl: `${GITHUB_REPO.API_BASE_URL}/repos/${GITHUB_REPO.OWNER}/${GITHUB_REPO.REPO}/releases?per_page=100`,
92 + binaryAssetName: getCurrentBinaryAssetName(os),
93 + accessToken,
94 + fetchFn: fetch,
95 + } satisfies UpdateCheckConfig;
96 + });
97
98 // ── Pure helpers ────────────────────────────────────────────────────────
99
@@ -95,19 +106,15 @@ export function parseLatestVersionFromReleases(
106
107 let latest: string | undefined;
108 for (const release of releases) {
98 - if (typeof release !== 'object' || release === null) continue;
109 + if (!Predicate.isRecord(release)) continue;
110
100 - const candidate = release as UpdateCheckRelease;
111 + const candidate = release;
112 if (typeof candidate.tag_name !== 'string') continue;
113 if (candidate.prerelease === true || candidate.draft === true) continue;
114 if (!Array.isArray(candidate.assets)) continue;
115
116 const hasRequiredBinary = candidate.assets.some(
106 - asset =>
107 - typeof asset === 'object' &&
108 - asset !== null &&
109 - 'name' in asset &&
110 - asset.name === binaryAssetName
117 + asset => Predicate.hasProperty(asset, 'name') && asset.name === binaryAssetName
118 );
119 if (!hasRequiredBinary) continue;
120
@@ -126,15 +133,22 @@ export function parseLatestVersionFromReleases(
133 // ── Factory ─────────────────────────────────────────────────────────────
134
135 export function createUpdateChecker(config: UpdateCheckConfig) {
136 + const readState = Effect.gen(function* () {
137 + const fs = yield* FileSystem.FileSystem;
138 + const rawState = yield* fs.readFileString(config.stateFile);
139 + return yield* Schema.decodeUnknown(UpdateCheckStateSchema)(rawState);
140 + });
141 +
142 /**
143 * If a cached newer version is known, print a one-line hint to stderr.
131 - * Purely synchronous — reads a tiny JSON file and does a semver compare.
144 + * Reads a tiny JSON file and does a semver compare.
145 */
133 - function showUpdateNotice(): void {
134 - try {
135 - if (!config.isInteractive()) return;
146 + function showUpdateNotice(terminal: Pick<TerminalUI, 'capabilities' | 'error'>) {
147 + return Effect.gen(function* () {
148 + const capabilities = yield* terminal.capabilities;
149 + if (!capabilities.isInteractive) return;
150
137 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
151 + const state = yield* readState;
152 if (!state.latestVersion || !semver.valid(state.latestVersion)) return;
153 if (state.latestVersion === config.currentVersion) return;
154
@@ -145,95 +159,103 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
159 ` ${dim('Update available:')} ${dim(config.currentVersion)} ${dim('→')} ${bold(cyanBright(state.latestVersion))}\n` +
160 ` ${dim('Run')} ${cyanBright('composio upgrade')} ${dim('to update')}\n`;
161
148 - process.stderr.write(`\n${msg}\n`);
149 - } catch {
150 - // Silently ignore — ENOENT, corrupt JSON, etc. Never block the CLI.
151 - }
162 + yield* terminal.error(`\n${msg}`);
163 + }).pipe(Effect.ignore);
164 }
165
166 /**
167 * Fetch the latest @composio/cli release from GitHub, requiring the current
168 * platform binary asset before writing the result to the state file.
169 *
158 - * Returns the internal promise so tests can await completion.
159 - * The public wrapper discards it (fire-and-forget).
170 + * Never fails: every fetch/parse/write error is swallowed so nothing can
171 + * propagate back into the fire-and-forget caller.
172 */
161 - function checkForUpdate(): Promise<void> | undefined {
162 - try {
163 - // Throttle: skip if checked recently.
164 - let previousLatestVersion: string | undefined;
165 - try {
166 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
167 - if (Date.now() - new Date(state.lastChecked).getTime() < config.checkIntervalMs) {
168 - return undefined;
169 - }
170 - previousLatestVersion = state.latestVersion;
171 - } catch {
172 - // ENOENT or corrupt file — re-check.
173 - }
173 + const checkForUpdate = Effect.gen(function* () {
174 + const fs = yield* FileSystem.FileSystem;
175 + const path = yield* Path.Path;
176 +
177 + // Throttle: skip if checked recently. A missing or corrupt state file
178 + // just means "re-check".
179 + const cachedState = yield* Effect.option(readState);
180 + if (
181 + Option.isSome(cachedState) &&
182 + Date.now() - new Date(cachedState.value.lastChecked).getTime() < config.checkIntervalMs
183 + ) {
184 + return;
185 + }
186 + const previousLatestVersion = Option.getOrUndefined(
187 + Option.map(cachedState, state => state.latestVersion)
188 + );
189
175 - const headers: Record<string, string> = {
176 - Accept: 'application/vnd.github.v3+json',
177 - 'User-Agent': `composio-cli/${config.currentVersion}`,
178 - };
190 + const headers: Record<string, string> = {
191 + Accept: 'application/vnd.github.v3+json',
192 + 'User-Agent': `composio-cli/${config.currentVersion}`,
193 + };
194
180 - if (config.accessToken) {
181 - headers.Authorization = `Bearer ${config.accessToken}`;
182 - }
195 + if (config.accessToken) {
196 + headers.Authorization = `Bearer ${config.accessToken}`;
197 + }
198
184 - // Always persist lastChecked to prevent retry loops when the fetch
185 - // fails or returns no matching releases with a matching binary.
186 - const writeState = (latestVersion?: string): Promise<void> => {
187 - try {
188 - const stateDir = dirname(config.stateFile);
189 - mkdirSync(stateDir, { recursive: true });
190 - } catch {
199 + // Always persist lastChecked to prevent retry loops when the fetch
200 + // fails or returns no matching releases with a matching binary.
201 + const writeState = (latestVersion?: string) =>
202 + fs.makeDirectory(path.dirname(config.stateFile), { recursive: true }).pipe(
203 + Effect.matchEffect({
204 // If we can't create the directory, bail out silently.
192 - return Promise.resolve();
193 - }
194 -
195 - const state: UpdateCheckState = {
196 - lastChecked: new Date().toISOString(),
197 - latestVersion: latestVersion ?? previousLatestVersion ?? config.currentVersion,
198 - };
199 -
200 - return writeFile(config.stateFile, JSON.stringify(state, null, 2)).then(() => {});
201 - };
202 -
203 - return config
204 - .fetchFn(config.releasesUrl, { headers, signal: AbortSignal.timeout(10_000) })
205 - .then(res => {
206 - if (!res.ok) throw new Error(`HTTP ${res.status}`);
207 - return res.json();
205 + onFailure: () => Effect.void,
206 + onSuccess: () => {
207 + const state: UpdateCheckState = {
208 + lastChecked: new Date().toISOString(),
209 + latestVersion: latestVersion ?? previousLatestVersion ?? config.currentVersion,
210 + };
211 + return fs.writeFileString(config.stateFile, JSON.stringify(state, null, 2));
212 + },
213 })
209 - .then((releases: unknown) => {
210 - const latestVersion = parseLatestVersionFromReleases(releases, config.binaryAssetName);
211 - return writeState(latestVersion);
212 - })
213 - .catch(() => {
214 - // Silently ignore fetch/parse errors — never block the CLI.
215 - // Still update the timestamp to prevent unbounded retry loops.
216 - return writeState().catch(() => {});
217 - });
218 - } catch {
219 - // Silently ignore.
220 - return undefined;
221 - }
222 - }
214 + );
215 +
216 + const fetchLatestVersion = Effect.gen(function* () {
217 + const response = yield* Effect.tryPromise(() =>
218 + config.fetchFn(config.releasesUrl, { headers, signal: AbortSignal.timeout(10_000) })
219 + );
220 + if (!response.ok) {
221 + return yield* new UpdateCheckHttpError({ status: response.status });
222 + }
223 + const releases: unknown = yield* Effect.tryPromise(() => response.json());
224 + return parseLatestVersionFromReleases(releases, config.binaryAssetName);
225 + });
226 +
227 + yield* fetchLatestVersion.pipe(
228 + Effect.flatMap(writeState),
229 + // Silently ignore fetch/parse errors — never block the CLI.
230 + // Still update the timestamp to prevent unbounded retry loops.
231 + Effect.catchAll(() => Effect.ignore(writeState()))
232 + );
233 + });
234
235 return { showUpdateNotice, checkForUpdate };
236 }
237
238 // ── Public API (production defaults, fire-and-forget) ───────────────────
239
229 -const _checker = createUpdateChecker(defaultConfig);
240 +const DefaultConfigLayers = Layer.mergeAll(Path.layer, NodeOs.Default, BunFileSystem.layer);
241
242 /** Print upgrade hint to stderr if a newer version is cached. */
232 -export function showUpdateNotice(): void {
233 - _checker.showUpdateNotice();
234 -}
243 +export const showUpdateNotice = Effect.gen(function* () {
244 + const terminal = yield* TerminalUI;
245 + const stateFile = yield* defaultStateFile;
246 + const config = yield* defaultConfig(stateFile);
247 + yield* createUpdateChecker(config).showUpdateNotice(terminal);
248 +}).pipe(Effect.provide(DefaultConfigLayers));
249
250 /** Fire-and-forget background fetch to GitHub. */
251 export function checkForUpdateInBackground(): void {
238 - _checker.checkForUpdate();
252 + // Runs from cli-main before the runtime boots; runPromiseExit never throws back
253 + // into the caller and checkForUpdate swallows its own failures.
254 + void Effect.runPromiseExit(
255 + Effect.gen(function* () {
256 + const stateFile = yield* defaultStateFile;
257 + const config = yield* defaultConfig(stateFile);
258 + yield* createUpdateChecker(config).checkForUpdate;
259 + }).pipe(Effect.provide(DefaultConfigLayers))
260 + );
261 }
ts/packages/cli/src/utils/stdio.ts deleted
-39
@@ -1,39 +0,0 @@
1 -import process from 'node:process';
2 -
3 -export type TtyLikeStream = {
4 - readonly isTTY?: boolean;
5 -};
6 -
7 -export type InteractiveStdio = {
8 - readonly stdin?: TtyLikeStream;
9 - readonly stdout?: TtyLikeStream;
10 - readonly stderr?: TtyLikeStream;
11 -};
12 -
13 -const getStdio = (stdio: InteractiveStdio = {}) => ({
14 - stdin: stdio.stdin ?? process.stdin,
15 - stdout: stdio.stdout ?? process.stdout,
16 - stderr: stdio.stderr ?? process.stderr,
17 -});
18 -
19 -/**
20 - * True only when the CLI is attached to a human terminal for input, data output,
21 - * and decoration output. Agent/shell pipelines typically fail at least one of
22 - * these checks, so human-only prompts/notices should stay silent there.
23 - */
24 -export const isInteractiveTerminal = (stdio: InteractiveStdio = {}): boolean => {
25 - const { stdin, stdout, stderr } = getStdio(stdio);
26 -
27 - return Boolean(stdin.isTTY && stdout.isTTY && stderr.isTTY);
28 -};
29 -
30 -/**
31 - * True when stderr can render terminal decoration such as logs, notes, and
32 - * spinners. Unlike prompts/notices, decoration only needs stderr; stdout can
33 - * remain clean for JSON/data and stdin can be redirected from /dev/null.
34 - */
35 -export const canRenderTerminalDecoration = (stdio: InteractiveStdio = {}): boolean => {
36 - const { stderr } = getStdio(stdio);
37 -
38 - return Boolean(stderr.isTTY);
39 -};
ts/packages/cli/test/__utils__/http-server.ts
+44
@@ -1,4 +1,5 @@
1 import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
2 +import { Effect } from 'effect';
3
4 /**
5 * Spin up a local HTTP server on an ephemeral port, run the callback,
@@ -39,3 +40,46 @@ export async function withHttpServer(
40 });
41 }
42 }
43 +
44 +/**
45 + * Effect variant of {@link withHttpServer}: the server lifecycle is managed
46 + * with acquireUseRelease so `use` can be an Effect run by @effect/vitest.
47 + */
48 +export function withHttpServerEffect<A, E, R>(
49 + handler: (req: IncomingMessage, res: ServerResponse) => void,
50 + use: (baseUrl: string) => Effect.Effect<A, E, R>
51 +): Effect.Effect<A, E, R> {
52 + return Effect.acquireUseRelease(
53 + Effect.promise(async () => {
54 + const server = createServer(handler);
55 + await new Promise<void>((resolve, reject) => {
56 + server.once('error', reject);
57 + server.listen({ port: 0, host: '127.0.0.1' }, () => {
58 + server.off('error', reject);
59 + resolve();
60 + });
61 + });
62 +
63 + const address = server.address();
64 + if (address === null || typeof address === 'string') {
65 + throw new Error('Failed to bind test server to an ephemeral port');
66 + }
67 +
68 + return { server, baseUrl: `http://127.0.0.1:${address.port}` };
69 + }),
70 + ({ baseUrl }) => use(baseUrl),
71 + ({ server }) =>
72 + Effect.promise(
73 + () =>
74 + new Promise<void>((resolve, reject) => {
75 + server.close(error => {
76 + if (error) {
77 + reject(error);
78 + return;
79 + }
80 + resolve();
81 + });
82 + })
83 + )
84 + );
85 +}
ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
+8
@@ -10,7 +10,15 @@ import { TerminalUI } from 'src/services/terminal-ui';
10 export const TerminalUITest = Layer.succeed(
11 TerminalUI,
12 TerminalUI.of({
13 + capabilities: Effect.succeed({
14 + stdinIsTTY: false,
15 + stdoutIsTTY: false,
16 + stderrIsTTY: false,
17 + isInteractive: false,
18 + canDecorate: false,
19 + }),
20 output: data => Console.log(data),
21 + error: data => Console.error(data),
22
23 intro: title => Console.log(`-- ${title} --`),
24 outro: message => Console.log(`-- ${message} --`),
ts/packages/cli/test/src/analytics.dispatch.test.ts new
+406
@@ -0,0 +1,406 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { afterEach, beforeEach, vi } from 'vitest';
3 +import { FetchHttpClient, FileSystem, Path } from '@effect/platform';
4 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
5 +import { Effect, Layer } from 'effect';
6 +import * as tempy from 'tempy';
7 +import {
8 + getCurrentCwdSessionId,
9 + readApiBaseUrl,
10 + runBackgroundWorkerFromArgv,
11 + trackCliCodactFailureEffect,
12 + trackCliEventEffect,
13 +} from 'src/analytics/dispatch';
14 +import { APP_VERSION, USER_CONFIG_FILE_NAME } from 'src/constants';
15 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
16 +import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
17 +
18 +const childProcessMocks = vi.hoisted(() => ({
19 + on: vi.fn(),
20 + spawn: vi.fn(),
21 + unref: vi.fn(),
22 +}));
23 +
24 +vi.mock('node:child_process', () => ({
25 + spawn: childProcessMocks.spawn,
26 +}));
27 +
28 +const originalArgv = [...process.argv];
29 +
30 +const cwdHash = (cwd: string): string => {
31 + let hash = 5381;
32 + for (let index = 0; index < cwd.length; index += 1) {
33 + hash = (hash * 33) ^ cwd.charCodeAt(index);
34 + }
35 + return Math.abs(hash >>> 0).toString(36);
36 +};
37 +
38 +const makePlatformLayer = (home: string) =>
39 + Layer.mergeAll(
40 + BunFileSystem.layer,
41 + BunPath.layer,
42 + FetchHttpClient.layer,
43 + TerminalUITest,
44 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: home }))
45 + );
46 +
47 +const enableTelemetry = (apiKey = 'uak_test') => {
48 + vi.stubEnv('COMPOSIO_BASE_URL', 'https://backend.example.test');
49 + vi.stubEnv('COMPOSIO_USER_API_KEY', apiKey);
50 + vi.stubEnv('NODE_ENV', 'development');
51 + vi.stubEnv('CI', 'false');
52 + vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DISABLED', 'false');
53 + vi.stubEnv('TELEMETRY_DISABLED', 'false');
54 + vi.stubEnv('COMPOSIO_DISABLE_TELEMETRY', 'false');
55 +};
56 +
57 +const decodeWorkerPayload = <A>(encodedPayload: string): A => {
58 + const normalized = encodedPayload.replace(/-/gu, '+').replace(/_/gu, '/');
59 + const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
60 + return JSON.parse(atob(padded)) as A;
61 +};
62 +
63 +const encodeWorkerPayload = (payload: unknown): string =>
64 + btoa(JSON.stringify(payload)).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
65 +
66 +describe('CLI analytics dispatch', () => {
67 + beforeEach(() => {
68 + const child = {
69 + on: childProcessMocks.on,
70 + unref: childProcessMocks.unref,
71 + };
72 + childProcessMocks.on.mockReset().mockReturnValue(child);
73 + childProcessMocks.spawn.mockReset().mockReturnValue(child);
74 + childProcessMocks.unref.mockReset();
75 + });
76 +
77 + afterEach(() => {
78 + vi.restoreAllMocks();
79 + vi.unstubAllEnvs();
80 + process.argv = [...originalArgv];
81 + });
82 +
83 + it.effect(
84 + 'reads configuration and the freshest current-directory session via platform services',
85 + () => {
86 + const home = tempy.temporaryDirectory();
87 + const cacheDir = tempy.temporaryDirectory();
88 + const cwd = '/workspace/project';
89 + vi.stubEnv('COMPOSIO_CACHE_DIR', cacheDir);
90 + vi.stubEnv('COMPOSIO_BASE_URL', '');
91 +
92 + return Effect.gen(function* () {
93 + const fs = yield* FileSystem.FileSystem;
94 + const path = yield* Path.Path;
95 + const composioDir = path.join(home, '.composio');
96 + yield* fs.makeDirectory(composioDir, { recursive: true });
97 + yield* fs.writeFileString(
98 + path.join(composioDir, USER_CONFIG_FILE_NAME),
99 + JSON.stringify({ base_url: 'https://backend.example.test///' })
100 + );
101 + yield* fs.writeFileString(
102 + path.join(cacheDir, 'consumer-short-term-cache.json'),
103 + JSON.stringify({
104 + older: {
105 + probablyMyCliSessionsByCwdHash: {
106 + [cwdHash(cwd)]: {
107 + id: 'cli_s_older',
108 + // The TestClock sits at epoch 0, so these fixed instants are
109 + // deterministically 30s and 60s in the future.
110 + expiresAt: '1970-01-01T00:00:30.000Z',
111 + },
112 + },
113 + },
114 + newer: {
115 + probablyMyCliSessionsByCwdHash: {
116 + [cwdHash(cwd)]: {
117 + id: 'cli_s_newer',
118 + expiresAt: '1970-01-01T00:01:00.000Z',
119 + },
120 + },
121 + },
122 + })
123 + );
124 +
125 + expect(yield* readApiBaseUrl).toBe('https://backend.example.test');
126 + expect(yield* getCurrentCwdSessionId(cwd)).toBe('cli_s_newer');
127 + }).pipe(Effect.provide(makePlatformLayer(home)));
128 + }
129 + );
130 +
131 + it.effect('ignores malformed worker payloads', () => {
132 + const home = tempy.temporaryDirectory();
133 +
134 + return runBackgroundWorkerFromArgv([
135 + process.execPath,
136 + 'composio',
137 + '__analytics-worker',
138 + 'not-base64',
139 + ]).pipe(Effect.provide(makePlatformLayer(home)));
140 + });
141 +
142 + it.effect('delivers analytics worker payloads to the configured endpoint', () => {
143 + const home = tempy.temporaryDirectory();
144 + const envelope = {
145 + event: 'cli_command_invoked',
146 + sentAt: '2026-07-16T00:00:00.000Z',
147 + source: 'cli' as const,
148 + distinctId: 'anon_test',
149 + installId: 'install_test',
150 + };
151 + const encodedPayload = btoa(JSON.stringify(envelope))
152 + .replace(/\+/gu, '-')
153 + .replace(/\//gu, '_')
154 + .replace(/=+$/u, '');
155 + vi.stubEnv('COMPOSIO_BASE_URL', 'https://backend.example.test');
156 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_test');
157 + vi.stubEnv('NODE_ENV', 'development');
158 + vi.stubEnv('CI', 'false');
159 + vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DISABLED', 'false');
160 + vi.stubEnv('TELEMETRY_DISABLED', 'false');
161 + vi.stubEnv('COMPOSIO_DISABLE_TELEMETRY', 'false');
162 + const fetchSpy = vi
163 + .spyOn(globalThis, 'fetch')
164 + .mockResolvedValue(new Response(null, { status: 204 }));
165 +
166 + return Effect.gen(function* () {
167 + yield* runBackgroundWorkerFromArgv([
168 + process.execPath,
169 + 'composio',
170 + '__analytics-worker',
171 + encodedPayload,
172 + ]).pipe(Effect.provide(makePlatformLayer(home)));
173 +
174 + expect(fetchSpy).toHaveBeenCalledTimes(1);
175 + const [endpoint, request] = fetchSpy.mock.calls[0]!;
176 + expect(String(endpoint)).toBe('https://backend.example.test/api/v3/cli/analytics');
177 + expect(request).toMatchObject({
178 + method: 'POST',
179 + headers: expect.objectContaining({
180 + 'content-type': 'application/json',
181 + 'x-composio-analytics-source': 'cli',
182 + 'x-user-api-key': 'uak_test',
183 + }),
184 + });
185 + expect(JSON.parse(new TextDecoder().decode(request?.body as Uint8Array))).toEqual(envelope);
186 + });
187 + });
188 +
189 + it.effect('spawns a detached analytics worker with a decodable envelope', () => {
190 + const home = tempy.temporaryDirectory();
191 + const scriptPath = `${home}/composio.ts`;
192 + enableTelemetry();
193 + process.argv[1] = scriptPath;
194 +
195 + return Effect.gen(function* () {
196 + const fs = yield* FileSystem.FileSystem;
197 + yield* fs.writeFileString(scriptPath, '');
198 + yield* trackCliEventEffect({
199 + name: 'producer_event',
200 + properties: { sample: 'value' },
201 + });
202 +
203 + expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
204 + const [command, args, options] = childProcessMocks.spawn.mock.calls[0] as unknown as [
205 + string,
206 + string[],
207 + { detached: boolean; stdio: unknown },
208 + ];
209 + expect(command).toBe(process.execPath);
210 + expect(args.slice(0, 2)).toEqual([scriptPath, '__analytics-worker']);
211 + expect(args).toHaveLength(3);
212 + expect(decodeWorkerPayload(args[2]!)).toMatchObject({
213 + event: 'producer_event',
214 + properties: { cli_version: APP_VERSION, sample: 'value' },
215 + source: 'cli',
216 + });
217 + expect(options).toMatchObject({
218 + detached: true,
219 + stdio: 'ignore',
220 + });
221 + expect(options).not.toHaveProperty('env');
222 + expect(childProcessMocks.on).toHaveBeenCalledWith('error', expect.any(Function));
223 + expect(childProcessMocks.unref).toHaveBeenCalledTimes(1);
224 + }).pipe(Effect.provide(makePlatformLayer(home)));
225 + });
226 +
227 + it.effect('spawns a detached codact worker with a decodable failure body', () => {
228 + const home = tempy.temporaryDirectory();
229 + const scriptPath = `${home}/composio.ts`;
230 + enableTelemetry();
231 + vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'agent');
232 + vi.stubEnv('COMPOSIO_CLI_PARENT_RUN_ID', 'run_parent');
233 + process.argv[1] = scriptPath;
234 +
235 + return Effect.gen(function* () {
236 + const fs = yield* FileSystem.FileSystem;
237 + yield* fs.writeFileString(scriptPath, '');
238 + yield* trackCliCodactFailureEffect({
239 + failureType: 'wrong_tool_input_param',
240 + toolInfo: {
241 + toolkit: 'github',
242 + tool: { slug: 'GITHUB_CREATE_ISSUE', version: 'latest' },
243 + },
244 + ctx: { invalidKey: 'repo' },
245 + requestId: 'req_producer',
246 + });
247 +
248 + expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
249 + const [command, args, options] = childProcessMocks.spawn.mock.calls[0] as unknown as [
250 + string,
251 + string[],
252 + { detached: boolean; stdio: unknown },
253 + ];
254 + expect(command).toBe(process.execPath);
255 + expect(args.slice(0, 2)).toEqual([scriptPath, '__codact-failure-worker']);
256 + expect(args).toHaveLength(3);
257 + expect(decodeWorkerPayload(args[2]!)).toMatchObject({
258 + failure_type: 'wrong_tool_input_param',
259 + tool_info: {
260 + toolkit: 'github',
261 + tool: { slug: 'GITHUB_CREATE_ISSUE', version: 'latest' },
262 + },
263 + ctx: { invalidKey: 'repo' },
264 + request_id: 'req_producer',
265 + session: {
266 + cli_version: APP_VERSION,
267 + invocation_origin: 'agent',
268 + parent_run_id: 'run_parent',
269 + source: 'cli',
270 + },
271 + });
272 + expect(options).toMatchObject({
273 + detached: true,
274 + stdio: 'ignore',
275 + });
276 + expect(options).not.toHaveProperty('env');
277 + expect(childProcessMocks.on).toHaveBeenCalledWith('error', expect.any(Function));
278 + expect(childProcessMocks.unref).toHaveBeenCalledTimes(1);
279 + }).pipe(Effect.provide(makePlatformLayer(home)));
280 + });
281 +
282 + it.effect('keeps both producer effects non-fatal when spawn throws', () => {
283 + const home = tempy.temporaryDirectory();
284 + enableTelemetry();
285 + childProcessMocks.spawn.mockImplementation(() => {
286 + throw new Error('spawn failed');
287 + });
288 +
289 + return Effect.gen(function* () {
290 + yield* trackCliEventEffect({ name: 'producer_event' });
291 + yield* trackCliCodactFailureEffect({
292 + failureType: 'wrong_tool_slug',
293 + ctx: { slug: 'MISSING_TOOL' },
294 + });
295 +
296 + expect(childProcessMocks.spawn).toHaveBeenCalledTimes(2);
297 + expect(childProcessMocks.unref).not.toHaveBeenCalled();
298 + }).pipe(Effect.provide(makePlatformLayer(home)));
299 + });
300 +
301 + it.effect('honors Effect boolean config when telemetry is disabled', () => {
302 + const home = tempy.temporaryDirectory();
303 + enableTelemetry();
304 + vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DISABLED', 'yes');
305 +
306 + return Effect.gen(function* () {
307 + yield* trackCliEventEffect({ name: 'producer_event' });
308 + yield* trackCliCodactFailureEffect({
309 + failureType: 'wrong_tool_slug',
310 + ctx: { slug: 'MISSING_TOOL' },
311 + });
312 +
313 + expect(childProcessMocks.spawn).not.toHaveBeenCalled();
314 + }).pipe(Effect.provide(makePlatformLayer(home)));
315 + });
316 +
317 + it.effect('delivers codact worker failures with the user key and session body', () => {
318 + const home = tempy.temporaryDirectory();
319 + const failureBody = {
320 + failure_type: 'wrong_tool_input_param',
321 + tool_info: {
322 + toolkit: 'github',
323 + tool: { slug: 'GITHUB_CREATE_ISSUE', version: 'latest' },
324 + },
325 + ctx: { invalidKey: 'repository' },
326 + session: {
327 + source: 'cli',
328 + id: 'cli_s_worker',
329 + cli_version: '0.3.0-test',
330 + invocation_origin: 'agent',
331 + parent_run_id: 'run_parent',
332 + },
333 + request_id: 'req_worker',
334 + };
335 + enableTelemetry('uak_worker');
336 + const fetchSpy = vi
337 + .spyOn(globalThis, 'fetch')
338 + .mockResolvedValue(new Response(null, { status: 204 }));
339 +
340 + return Effect.gen(function* () {
341 + yield* runBackgroundWorkerFromArgv([
342 + process.execPath,
343 + 'composio',
344 + '__codact-failure-worker',
345 + encodeWorkerPayload(failureBody),
346 + ]).pipe(Effect.provide(makePlatformLayer(home)));
347 +
348 + expect(fetchSpy).toHaveBeenCalledTimes(1);
349 + const [endpoint, request] = fetchSpy.mock.calls[0]!;
350 + expect(String(endpoint)).toBe('https://backend.example.test/api/v3/cli/codact_failures');
351 + expect(request).toMatchObject({
352 + method: 'POST',
353 + headers: expect.objectContaining({
354 + 'content-type': 'application/json',
355 + 'x-user-api-key': 'uak_worker',
356 + }),
357 + });
358 + expect(JSON.parse(new TextDecoder().decode(request?.body as Uint8Array))).toEqual(
359 + failureBody
360 + );
361 + });
362 + });
363 +
364 + it.effect('ignores malformed codact worker payloads', () => {
365 + const home = tempy.temporaryDirectory();
366 + enableTelemetry();
367 + const fetchSpy = vi
368 + .spyOn(globalThis, 'fetch')
369 + .mockResolvedValue(new Response(null, { status: 204 }));
370 +
371 + return Effect.gen(function* () {
372 + yield* runBackgroundWorkerFromArgv([
373 + process.execPath,
374 + 'composio',
375 + '__codact-failure-worker',
376 + 'not-base64',
377 + ]).pipe(Effect.provide(makePlatformLayer(home)));
378 +
379 + expect(fetchSpy).not.toHaveBeenCalled();
380 + });
381 + });
382 +
383 + it.effect('skips codact worker delivery without a user key', () => {
384 + const home = tempy.temporaryDirectory();
385 + enableTelemetry('');
386 + const fetchSpy = vi
387 + .spyOn(globalThis, 'fetch')
388 + .mockResolvedValue(new Response(null, { status: 204 }));
389 + const failureBody = {
390 + failure_type: 'wrong_tool_slug',
391 + ctx: { slug: 'MISSING_TOOL' },
392 + session: { source: 'cli' },
393 + };
394 +
395 + return Effect.gen(function* () {
396 + yield* runBackgroundWorkerFromArgv([
397 + process.execPath,
398 + 'composio',
399 + '__codact-failure-worker',
400 + encodeWorkerPayload(failureBody),
401 + ]).pipe(Effect.provide(makePlatformLayer(home)));
402 +
403 + expect(fetchSpy).not.toHaveBeenCalled();
404 + });
405 + });
406 +});
ts/packages/cli/test/src/analytics.events.test.ts
+16
@@ -1,6 +1,8 @@
1 import { describe, expect, it } from 'vitest';
2 import { createCliCodactFailureBody } from 'src/analytics/dispatch';
3 import {
4 + createCliCommandTelemetryContext,
5 + getPrimaryLifecycleInvokedEvent,
6 getToolExecuteFailedEvent,
7 getToolExecuteToolNotFoundEvent,
8 getToolExecuteValidationFailedEvent,
@@ -10,6 +12,20 @@ import {
12 import { ToolInputValidationError } from 'src/services/tool-input-validation';
13
14 describe('CLI analytics execute failure events', () => {
15 + it('records terminal capabilities supplied by the terminal service', () => {
16 + const context = createCliCommandTelemetryContext(['bun', 'composio'], '0.3.0', {
17 + stdoutIsTTY: true,
18 + stderrIsTTY: false,
19 + });
20 +
21 + const event = getPrimaryLifecycleInvokedEvent(context);
22 +
23 + expect(event?.properties).toMatchObject({
24 + stdout_is_tty: true,
25 + stderr_is_tty: false,
26 + });
27 + });
28 +
29 it('marks cached-schema validation failures as fast_fail', () => {
30 const error = new ToolInputValidationError('GMAIL_SEND_EMAIL', '/tmp/schema.json', [
31 'Unknown key "recipient"',
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+21 -38
@@ -6,15 +6,11 @@ import { ValidationError, HelpDoc } from '@effect/cli';
6 import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';
7 import { afterEach, vi } from 'vitest';
8
9 -type CommandMismatchResult = {
10 - _tag: string;
11 - error: {
12 - _tag: string;
13 - value: {
14 - _tag: string;
15 - value: string;
16 - };
17 - };
9 +const getCommandMismatch = (value: unknown): ValidationError.CommandMismatch => {
10 + if (!ValidationError.isValidationError(value) || !ValidationError.isCommandMismatch(value)) {
11 + throw new Error('Expected a command mismatch');
12 + }
13 + return value;
14 };
15
16 describe('CLI: composio', () => {
@@ -28,15 +24,12 @@ describe('CLI: composio', () => {
24 const args = ['--bar'];
25
26 const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
31 - const commandMismatch = result as CommandMismatchResult;
32 -
33 - expect(result).toEqual(expect.any(Object));
34 - expect(commandMismatch._tag).toBe(ValidationError.commandMismatch(HelpDoc.p(''))._tag);
35 - expect(commandMismatch.error._tag).toBe('Paragraph');
36 - expect(commandMismatch.error.value._tag).toBe('Text');
37 - expect(commandMismatch.error.value.value).toContain('Invalid subcommand for composio');
38 - expect(commandMismatch.error.value.value).toContain("'generate'");
39 - expect(commandMismatch.error.value.value).toContain("'orgs'");
27 + const commandMismatch = getCommandMismatch(result);
28 + const message = HelpDoc.toAnsiText(commandMismatch.error);
29 +
30 + expect(message).toContain('Invalid subcommand for composio');
31 + expect(message).toContain("'generate'");
32 + expect(message).toContain("'orgs'");
33 })
34 );
35 });
@@ -47,18 +40,13 @@ describe('CLI: composio', () => {
40 const args = ['tools', 'search', 'metabase', 'put'];
41
42 const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
50 - const commandMismatch = result as CommandMismatchResult;
51 -
52 - expect(result).toEqual(expect.any(Object));
53 - expect(commandMismatch._tag).toBe(ValidationError.commandMismatch(HelpDoc.p(''))._tag);
54 - expect(commandMismatch.error._tag).toBe('Paragraph');
55 - expect(commandMismatch.error.value._tag).toBe('Text');
56 - expect(commandMismatch.error.value.value).toContain(
57 - 'Invalid subcommand for composio tools'
58 - );
59 - expect(commandMismatch.error.value.value).toContain("'info'");
60 - expect(commandMismatch.error.value.value).toContain("'list'");
61 - expect(commandMismatch.error.value.value).not.toContain("'version'");
43 + const commandMismatch = getCommandMismatch(result);
44 + const message = HelpDoc.toAnsiText(commandMismatch.error);
45 +
46 + expect(message).toContain('Invalid subcommand for composio tools');
47 + expect(message).toContain("'info'");
48 + expect(message).toContain("'list'");
49 + expect(message).not.toContain("'version'");
50 })
51 );
52 });
@@ -150,6 +138,8 @@ describe('CLI: composio', () => {
138 Effect.gen(function* () {
139 vi.stubEnv('CODEX_THREAD_ID', 'thread_123');
140 vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'sdk-ts');
141 + // The debug command still writes to process.stdout until the
142 + // seam-rules PR of this stack routes it through TerminalUI.
143 const write = vi
144 .spyOn(process.stdout, 'write')
145 .mockImplementation((() => true) as typeof process.stdout.write);
@@ -165,15 +155,8 @@ describe('CLI: composio', () => {
155 layer(TestLive())(it => {
156 it.scoped('[Given] artifacts cwd [Then] it prints the current session artifact directory', () =>
157 Effect.gen(function* () {
168 - const write = vi
169 - .spyOn(process.stdout, 'write')
170 - .mockImplementation((() => true) as typeof process.stdout.write);
171 -
158 yield* cli(['artifacts', 'cwd']);
173 - const output = write.mock.calls
174 - .map(call => String(call[0]))
175 - .join('\n')
176 - .trim();
159 + const output = (yield* MockConsole.getLines()).join('\n').trim();
160
161 expect(output).toContain(path.join(os.tmpdir(), 'composio'));
162 })
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+8
@@ -50,6 +50,13 @@ const testConfigProvider = ConfigProvider.fromMap(
50 ).pipe(extendConfigProvider);
51
52 const RecordingTerminalUI = TerminalUI.of({
53 + capabilities: Effect.succeed({
54 + stdinIsTTY: true,
55 + stdoutIsTTY: true,
56 + stderrIsTTY: true,
57 + isInteractive: true,
58 + canDecorate: true,
59 + }),
60 output: (data, options) =>
61 Console.log(
62 JSON.stringify({
@@ -57,6 +64,7 @@ const RecordingTerminalUI = TerminalUI.of({
64 data,
65 })
66 ),
67 + error: data => Console.error(data),
68 intro: title => Console.log(title),
69 outro: message => Console.log(message),
70 log: {
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+8
@@ -90,7 +90,15 @@ const testConfigProvider = ConfigProvider.fromMap(
90
91 const terminalUIWithConfirm = (confirmed: boolean) =>
92 TerminalUI.of({
93 + capabilities: Effect.succeed({
94 + stdinIsTTY: true,
95 + stdoutIsTTY: true,
96 + stderrIsTTY: true,
97 + isInteractive: true,
98 + canDecorate: true,
99 + }),
100 output: data => Console.log(data),
101 + error: data => Console.error(data),
102 intro: title => Console.log(`-- ${title} --`),
103 outro: message => Console.log(`-- ${message} --`),
104 log: {
ts/packages/cli/test/src/commands/logout.cmd.test.ts
+8
@@ -13,7 +13,15 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
13
14 const terminalUIWithConfirm = (confirmed: boolean) =>
15 TerminalUI.of({
16 + capabilities: Effect.succeed({
17 + stdinIsTTY: true,
18 + stdoutIsTTY: true,
19 + stderrIsTTY: true,
20 + isInteractive: true,
21 + canDecorate: true,
22 + }),
23 output: data => Console.log(data),
24 + error: data => Console.error(data),
25 intro: title => Console.log(`-- ${title} --`),
26 outro: message => Console.log(`-- ${message} --`),
27 log: {
ts/packages/cli/test/src/commands/run.cmd.test.ts
+2 -3
@@ -44,11 +44,10 @@ describe('CLI: composio run', () => {
44 Effect.gen(function* () {
45 const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));
46 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
47 - const stderrWrite = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
47 vi.stubGlobal('Bun', { spawn });
48
49 yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
51 - const output = stderrWrite.mock.calls.map(([chunk]) => String(chunk));
50 + const output = yield* MockConsole.getLines();
51
52 expect(spawn).toHaveBeenCalledTimes(1);
53 const spawnConfig = (spawn as any).mock.calls[0][0] as {
@@ -71,7 +70,7 @@ describe('CLI: composio run', () => {
70 })
71 );
72 expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
74 - expect(output).toContainEqual(expect.stringMatching(/^RUN_LOG_FILE=.*run\.log\n$/));
73 + expect(output).toContainEqual(expect.stringMatching(/^RUN_LOG_FILE=.*run\.log$/));
74 expect(exit).toHaveBeenCalledWith(7);
75 })
76 );
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+5 -4
@@ -110,8 +110,9 @@ describe('ComposioClientSingleton headers', () => {
110 );
111 });
112
113 - // Fixed instants far in the future/past keep the expiry comparison
114 - // deterministic regardless of the clock the session-id reader consults.
113 + // The session-id reader compares expiresAt against Clock.currentTimeMillis;
114 + // the TestClock sits at epoch 0, so fixed instants around it are
115 + // deterministically in the future or the past.
116 it.effect('includes the current cwd CLI session ID', () => {
117 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
118 const homedir = tempy.temporaryDirectory();
@@ -128,7 +129,7 @@ describe('ComposioClientSingleton headers', () => {
129 vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
130 yield* writeCliSessionCache(homedir, {
131 id: 'cli_s_current',
131 - expiresAt: '2099-01-01T00:00:00.000Z',
132 + expiresAt: '1970-01-01T00:01:00.000Z',
133 });
134 const client = yield* ComposioClientSingleton.get();
135 yield* Effect.promise(() =>
@@ -161,7 +162,7 @@ describe('ComposioClientSingleton headers', () => {
162 vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
163 yield* writeCliSessionCache(homedir, {
164 id: 'cli_s_expired',
164 - expiresAt: '1970-01-01T00:01:00.000Z',
165 + expiresAt: '1969-12-31T23:59:00.000Z',
166 });
167 const client = yield* ComposioClientSingleton.get();
168 yield* Effect.promise(() =>
ts/packages/cli/test/src/services/runtime-debug-logger.test.ts new
+40
@@ -0,0 +1,40 @@
1 +import { afterEach, describe, expect, layer, vi } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';
4 +import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';
5 +import { MockConsole, TestLive } from 'test/__utils__';
6 +
7 +describe('runtime debug logger', () => {
8 + afterEach(() => {
9 + resetRuntimeDebugFlags();
10 + vi.restoreAllMocks();
11 + });
12 +
13 + layer(TestLive())(it => {
14 + it.scoped('writes tool diagnostics as the existing JSON line format', () =>
15 + Effect.gen(function* () {
16 + setRuntimeDebugFlags({ toolDebug: true });
17 +
18 + yield* logToolDebug('resolved', { slug: 'GITHUB_GET_REPO' });
19 +
20 + expect(yield* MockConsole.getLines()).toContain(
21 + '[tool-debug] {"label":"resolved","slug":"GITHUB_GET_REPO"}'
22 + );
23 + })
24 + );
25 +
26 + it.scoped('writes performance diagnostics with elapsed time', () =>
27 + Effect.gen(function* () {
28 + setRuntimeDebugFlags({ perfDebug: true });
29 + vi.spyOn(Date, 'now').mockReturnValue(125);
30 + const logPerfDebug = makePerfDebugLogger(100);
31 +
32 + yield* logPerfDebug('started', { slug: 'GITHUB_GET_REPO' });
33 +
34 + expect(yield* MockConsole.getLines()).toContain(
35 + '[perf] {"phase":"event","label":"started","elapsedMs":25,"slug":"GITHUB_GET_REPO"}'
36 + );
37 + })
38 + );
39 + });
40 +});
ts/packages/cli/test/src/services/terminal-ui.test.ts
+41 -9
@@ -1,9 +1,29 @@
1 -import { describe, expect, layer } from '@effect/vitest';
2 -import { Effect } from 'effect';
3 -import { TerminalUI } from 'src/services/terminal-ui';
1 +import { describe, expect, it, layer } from '@effect/vitest';
2 +import { Data, Effect, Exit } from 'effect';
3 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
4 import { TestLive, MockConsole } from 'test/__utils__';
5
6 +class TestFailure extends Data.TaggedError('test/TestFailure')<{
7 + readonly message: string;
8 +}> {}
9 +
10 describe('TerminalUI', () => {
11 + it('classifies prompt and decoration capabilities independently', () => {
12 + expect(
13 + getTerminalCapabilities({
14 + stdin: { isTTY: false },
15 + stdout: { isTTY: true },
16 + stderr: { isTTY: true },
17 + })
18 + ).toEqual({
19 + stdinIsTTY: false,
20 + stdoutIsTTY: true,
21 + stderrIsTTY: true,
22 + isInteractive: false,
23 + canDecorate: true,
24 + });
25 + });
26 +
27 layer(TestLive())(it => {
28 // -----------------------------------------------------------------------
29 // Data output
@@ -19,6 +39,16 @@ describe('TerminalUI', () => {
39 })
40 );
41
42 + it.scoped('error writes raw diagnostics capturable by MockConsole', () =>
43 + Effect.gen(function* () {
44 + const ui = yield* TerminalUI;
45 + yield* ui.error('diagnostic');
46 +
47 + const lines = yield* MockConsole.getLines();
48 + expect(lines).toContain('diagnostic');
49 + })
50 + );
51 +
52 // -----------------------------------------------------------------------
53 // Log text capture
54 // -----------------------------------------------------------------------
@@ -119,10 +149,10 @@ describe('TerminalUI', () => {
149 Effect.gen(function* () {
150 const ui = yield* TerminalUI;
151 const exit = yield* Effect.exit(
122 - ui.withSpinner('loading', Effect.fail(new Error('network error')))
152 + ui.withSpinner('loading', Effect.fail(new TestFailure({ message: 'network error' })))
153 );
154
125 - expect(exit._tag).toBe('Failure');
155 + expect(Exit.isFailure(exit)).toBe(true);
156 })
157 );
158
@@ -135,10 +165,12 @@ describe('TerminalUI', () => {
165 const ui = yield* TerminalUI;
166
167 const exit = yield* Effect.exit(
138 - ui.useMakeSpinner('fetching data', _spinner => Effect.fail(new Error('API returned 400')))
168 + ui.useMakeSpinner('fetching data', _spinner =>
169 + Effect.fail(new TestFailure({ message: 'API returned 400' }))
170 + )
171 );
172
141 - expect(exit._tag).toBe('Failure');
173 + expect(Exit.isFailure(exit)).toBe(true);
174
175 // The spinner error message should be captured
176 const lines = yield* MockConsole.getLines();
@@ -207,12 +239,12 @@ describe('TerminalUI', () => {
239 Effect.gen(function* () {
240 // Simulate tapError pattern: callback calls spinner.error(), then the effect fails
241 yield* spinner.error('Login timed out. Please try again.');
210 - return yield* Effect.fail(new Error('timed out'));
242 + return yield* new TestFailure({ message: 'timed out' });
243 })
244 )
245 );
246
215 - expect(exit._tag).toBe('Failure');
247 + expect(Exit.isFailure(exit)).toBe(true);
248
249 const lines = yield* MockConsole.getLines();
250 // Should see the user's error message
ts/packages/cli/test/src/services/update-check.test.ts
+325 -252
@@ -1,8 +1,11 @@
1 -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
1 +import { describe, it, expect, vi, beforeEach, afterEach } from '@effect/vitest';
2 import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
3 import { dirname, join } from 'node:path';
4 import { tmpdir } from 'node:os';
5 -import { withHttpServer } from 'test/__utils__/http-server';
5 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
6 +import { Effect, Layer } from 'effect';
7 +import { withHttpServerEffect } from 'test/__utils__/http-server';
8 +import type { TerminalUI } from 'src/services/terminal-ui';
9 import {
10 createUpdateChecker,
11 parseLatestVersionFromReleases,
@@ -12,6 +15,9 @@ import {
15
16 // ── Helpers ─────────────────────────────────────────────────────────────
17
18 +/** Platform services required by the update checker's Effects. */
19 +const PlatformLayers = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
20 +
21 /** Create a temp directory that is cleaned up after each test. */
22 let tempDir: string;
23 beforeEach(() => {
@@ -31,11 +37,24 @@ function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig {
37 binaryAssetName: 'composio-darwin-aarch64.zip',
38 accessToken: undefined,
39 fetchFn: () => Promise.reject(new Error('fetch not configured')),
34 - isInteractive: () => true,
40 ...overrides,
41 };
42 }
43
44 +const makeTerminal = (
45 + output: string[],
46 + isInteractive = true
47 +): Pick<TerminalUI, 'capabilities' | 'error'> => ({
48 + capabilities: Effect.succeed({
49 + stdinIsTTY: isInteractive,
50 + stdoutIsTTY: isInteractive,
51 + stderrIsTTY: isInteractive,
52 + isInteractive,
53 + canDecorate: isInteractive,
54 + }),
55 + error: line => Effect.sync(() => output.push(line)),
56 +});
57 +
58 /** Write a state file to the test config's stateFile path. */
59 function writeState(config: UpdateCheckConfig, state: UpdateCheckState): void {
60 mkdirSync(dirname(config.stateFile), { recursive: true });
@@ -132,312 +151,366 @@ describe('parseLatestVersionFromReleases', () => {
151 // ── showUpdateNotice ────────────────────────────────────────────────────
152
153 describe('showUpdateNotice', () => {
135 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
136 - let stderrSpy: any;
154 + let output: string[];
155
156 beforeEach(() => {
139 - stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
157 + output = [];
158 });
159
142 - afterEach(() => {
143 - stderrSpy.mockRestore();
144 - });
145 -
146 - it('does nothing when no state file exists', () => {
147 - const { showUpdateNotice } = createUpdateChecker(makeConfig());
160 + it.effect('does nothing when no state file exists', () =>
161 + Effect.gen(function* () {
162 + const { showUpdateNotice } = createUpdateChecker(makeConfig());
163
149 - showUpdateNotice();
164 + yield* showUpdateNotice(makeTerminal(output));
165
151 - expect(stderrSpy).not.toHaveBeenCalled();
152 - });
166 + expect(output).toEqual([]);
167 + }).pipe(Effect.provide(PlatformLayers))
168 + );
169
154 - it('does nothing when cached version equals current version', () => {
155 - const config = makeConfig({ currentVersion: '0.2.0' });
156 - writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
157 - const { showUpdateNotice } = createUpdateChecker(config);
170 + it.effect('does nothing when cached version equals current version', () =>
171 + Effect.gen(function* () {
172 + const config = makeConfig({ currentVersion: '0.2.0' });
173 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
174 + const { showUpdateNotice } = createUpdateChecker(config);
175
159 - showUpdateNotice();
176 + yield* showUpdateNotice(makeTerminal(output));
177
161 - expect(stderrSpy).not.toHaveBeenCalled();
162 - });
178 + expect(output).toEqual([]);
179 + }).pipe(Effect.provide(PlatformLayers))
180 + );
181
164 - it('does nothing when cached version is older than current', () => {
165 - const config = makeConfig({ currentVersion: '0.3.0' });
166 - writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
167 - const { showUpdateNotice } = createUpdateChecker(config);
182 + it.effect('does nothing when cached version is older than current', () =>
183 + Effect.gen(function* () {
184 + const config = makeConfig({ currentVersion: '0.3.0' });
185 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
186 + const { showUpdateNotice } = createUpdateChecker(config);
187
169 - showUpdateNotice();
188 + yield* showUpdateNotice(makeTerminal(output));
189
171 - expect(stderrSpy).not.toHaveBeenCalled();
172 - });
190 + expect(output).toEqual([]);
191 + }).pipe(Effect.provide(PlatformLayers))
192 + );
193
174 - it('prints upgrade hint when cached version is newer', () => {
175 - const config = makeConfig({ currentVersion: '0.2.0' });
176 - writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
177 - const { showUpdateNotice } = createUpdateChecker(config);
194 + it.effect('prints upgrade hint when cached version is newer', () =>
195 + Effect.gen(function* () {
196 + const config = makeConfig({ currentVersion: '0.2.0' });
197 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
198 + const { showUpdateNotice } = createUpdateChecker(config);
199
179 - showUpdateNotice();
200 + yield* showUpdateNotice(makeTerminal(output));
201
181 - expect(stderrSpy).toHaveBeenCalledOnce();
182 - const output = stderrSpy.mock.calls[0][0] as string;
183 - expect(output).toContain('Update available');
184 - expect(output).toContain('0.3.0');
185 - expect(output).toContain('composio upgrade');
186 - });
202 + expect(output).toHaveLength(1);
203 + expect(output[0]).toContain('Update available');
204 + expect(output[0]).toContain('0.3.0');
205 + expect(output[0]).toContain('composio upgrade');
206 + }).pipe(Effect.provide(PlatformLayers))
207 + );
208
188 - it('does not print upgrade hint in non-interactive environments', () => {
189 - const config = makeConfig({ currentVersion: '0.2.0', isInteractive: () => false });
190 - writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
191 - const { showUpdateNotice } = createUpdateChecker(config);
209 + it.effect('does not print upgrade hint in non-interactive environments', () =>
210 + Effect.gen(function* () {
211 + const config = makeConfig({ currentVersion: '0.2.0' });
212 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
213 + const { showUpdateNotice } = createUpdateChecker(config);
214
193 - showUpdateNotice();
215 + yield* showUpdateNotice(makeTerminal(output, false));
216
195 - expect(stderrSpy).not.toHaveBeenCalled();
196 - });
217 + expect(output).toEqual([]);
218 + }).pipe(Effect.provide(PlatformLayers))
219 + );
220
198 - it('silently ignores corrupt state file', () => {
199 - const config = makeConfig();
200 - mkdirSync(dirname(config.stateFile), { recursive: true });
201 - writeFileSync(config.stateFile, 'not-json!!!');
202 - const { showUpdateNotice } = createUpdateChecker(config);
221 + it.effect('silently ignores corrupt state file', () =>
222 + Effect.gen(function* () {
223 + const config = makeConfig();
224 + mkdirSync(dirname(config.stateFile), { recursive: true });
225 + writeFileSync(config.stateFile, 'not-json!!!');
226 + const { showUpdateNotice } = createUpdateChecker(config);
227
204 - showUpdateNotice();
228 + yield* showUpdateNotice(makeTerminal(output));
229
206 - expect(stderrSpy).not.toHaveBeenCalled();
207 - });
230 + expect(output).toEqual([]);
231 + }).pipe(Effect.provide(PlatformLayers))
232 + );
233
209 - it('does nothing when cached version is not valid semver', () => {
210 - const config = makeConfig({ currentVersion: '0.2.0' });
211 - writeState(config, { lastChecked: new Date().toISOString(), latestVersion: 'not-semver' });
212 - const { showUpdateNotice } = createUpdateChecker(config);
234 + it.effect('does nothing when cached version is not valid semver', () =>
235 + Effect.gen(function* () {
236 + const config = makeConfig({ currentVersion: '0.2.0' });
237 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: 'not-semver' });
238 + const { showUpdateNotice } = createUpdateChecker(config);
239
214 - showUpdateNotice();
240 + yield* showUpdateNotice(makeTerminal(output));
241
216 - expect(stderrSpy).not.toHaveBeenCalled();
217 - });
242 + expect(output).toEqual([]);
243 + }).pipe(Effect.provide(PlatformLayers))
244 + );
245 });
246
247 // ── checkForUpdate ──────────────────────────────────────────────────────
248
249 describe('checkForUpdate', () => {
223 - it('skips fetch when cache is fresh', () => {
224 - const fetchFn = vi.fn();
225 - const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch });
226 - writeState(config, {
227 - lastChecked: new Date().toISOString(),
228 - latestVersion: '0.2.0',
229 - });
230 - const { checkForUpdate } = createUpdateChecker(config);
231 -
232 - const result = checkForUpdate();
233 -
234 - expect(result).toBeUndefined(); // returned early, no promise
235 - expect(fetchFn).not.toHaveBeenCalled();
236 - });
250 + // Pin the wall clock so the throttle math in checkForUpdate is deterministic.
251 + // Only Date is faked: the SUT awaits real fetch promises through
252 + // Effect.tryPromise, which need real timers/microtasks to settle.
253 + const pinnedNow = new Date('2026-01-01T00:00:00.000Z');
254 + const staleLastChecked = '2025-12-30T23:00:00.000Z'; // 25 hours before pinnedNow
255
238 - it('fetches when cache is stale', async () => {
239 - const stale = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(); // 25 hours ago
240 - const config = makeConfig({
241 - fetchFn: vi.fn().mockResolvedValue({
242 - ok: true,
243 - json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])),
244 - }) as unknown as typeof fetch,
245 - });
246 - writeState(config, { lastChecked: stale, latestVersion: '0.2.0' });
247 - const { checkForUpdate } = createUpdateChecker(config);
248 -
249 - await checkForUpdate();
250 -
251 - expect(config.fetchFn).toHaveBeenCalledOnce();
252 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
253 - expect(state.latestVersion).toBe('0.3.0');
256 + beforeEach(() => {
257 + vi.useFakeTimers({ toFake: ['Date'] });
258 + vi.setSystemTime(pinnedNow);
259 });
260
256 - it('fetches when no cache exists', async () => {
257 - const config = makeConfig({
258 - fetchFn: vi.fn().mockResolvedValue({
259 - ok: true,
260 - json: () => Promise.resolve(makeReleasesPayload(['0.4.0', '0.3.0'])),
261 - }) as unknown as typeof fetch,
262 - });
263 - const { checkForUpdate } = createUpdateChecker(config);
264 -
265 - await checkForUpdate();
266 -
267 - expect(existsSync(config.stateFile)).toBe(true);
268 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
269 - expect(state.latestVersion).toBe('0.4.0');
261 + afterEach(() => {
262 + vi.useRealTimers();
263 });
264
272 - it('fetches when cache file is corrupt', async () => {
273 - const config = makeConfig({
274 - fetchFn: vi.fn().mockResolvedValue({
275 - ok: true,
276 - json: () => Promise.resolve(makeReleasesPayload(['0.5.0'])),
277 - }) as unknown as typeof fetch,
278 - });
279 - mkdirSync(dirname(config.stateFile), { recursive: true });
280 - writeFileSync(config.stateFile, 'garbage');
281 - const { checkForUpdate } = createUpdateChecker(config);
265 + it.effect('skips fetch when cache is fresh', () =>
266 + Effect.gen(function* () {
267 + const fetchFn = vi.fn();
268 + const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch });
269 + writeState(config, {
270 + lastChecked: new Date().toISOString(),
271 + latestVersion: '0.2.0',
272 + });
273 + const { checkForUpdate } = createUpdateChecker(config);
274 +
275 + yield* checkForUpdate;
276 +
277 + expect(fetchFn).not.toHaveBeenCalled();
278 + }).pipe(Effect.provide(PlatformLayers))
279 + );
280 +
281 + it.effect('fetches when cache is stale', () =>
282 + Effect.gen(function* () {
283 + const stale = staleLastChecked;
284 + const config = makeConfig({
285 + fetchFn: vi.fn().mockResolvedValue({
286 + ok: true,
287 + json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])),
288 + }) as unknown as typeof fetch,
289 + });
290 + writeState(config, { lastChecked: stale, latestVersion: '0.2.0' });
291 + const { checkForUpdate } = createUpdateChecker(config);
292 +
293 + yield* checkForUpdate;
294 +
295 + expect(config.fetchFn).toHaveBeenCalledOnce();
296 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
297 + expect(state.latestVersion).toBe('0.3.0');
298 + }).pipe(Effect.provide(PlatformLayers))
299 + );
300 +
301 + it.effect('fetches when no cache exists', () =>
302 + Effect.gen(function* () {
303 + const config = makeConfig({
304 + fetchFn: vi.fn().mockResolvedValue({
305 + ok: true,
306 + json: () => Promise.resolve(makeReleasesPayload(['0.4.0', '0.3.0'])),
307 + }) as unknown as typeof fetch,
308 + });
309 + const { checkForUpdate } = createUpdateChecker(config);
310 +
311 + yield* checkForUpdate;
312 +
313 + expect(existsSync(config.stateFile)).toBe(true);
314 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
315 + expect(state.latestVersion).toBe('0.4.0');
316 + }).pipe(Effect.provide(PlatformLayers))
317 + );
318 +
319 + it.effect('fetches when cache file is corrupt', () =>
320 + Effect.gen(function* () {
321 + const config = makeConfig({
322 + fetchFn: vi.fn().mockResolvedValue({
323 + ok: true,
324 + json: () => Promise.resolve(makeReleasesPayload(['0.5.0'])),
325 + }) as unknown as typeof fetch,
326 + });
327 + mkdirSync(dirname(config.stateFile), { recursive: true });
328 + writeFileSync(config.stateFile, 'garbage');
329 + const { checkForUpdate } = createUpdateChecker(config);
330 +
331 + yield* checkForUpdate;
332 +
333 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
334 + expect(state.latestVersion).toBe('0.5.0');
335 + }).pipe(Effect.provide(PlatformLayers))
336 + );
337 +
338 + it.effect(
339 + 'still writes lastChecked when no CLI releases with the required binary are found',
340 + () =>
341 + Effect.gen(function* () {
342 + const config = makeConfig({
343 + fetchFn: vi.fn().mockResolvedValue({
344 + ok: true,
345 + json: () =>
346 + Promise.resolve([
347 + {
348 + tag_name: '@composio/core@1.0.0',
349 + assets: [{ name: 'composio-darwin-aarch64.zip' }],
350 + },
351 + ]),
352 + }) as unknown as typeof fetch,
353 + });
354 + const { checkForUpdate } = createUpdateChecker(config);
355
283 - await checkForUpdate();
356 + yield* checkForUpdate;
357
285 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
286 - expect(state.latestVersion).toBe('0.5.0');
287 - });
358 + expect(existsSync(config.stateFile)).toBe(true);
359 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
360 + expect(state.lastChecked).toBeDefined();
361 + // Falls back to currentVersion since no previous state and no matching releases found
362 + expect(state.latestVersion).toBe(config.currentVersion);
363 + }).pipe(Effect.provide(PlatformLayers))
364 + );
365 +
366 + it.effect(
367 + 'preserves previous latestVersion when no CLI releases with the required binary are found',
368 + () =>
369 + Effect.gen(function* () {
370 + const config = makeConfig({
371 + fetchFn: vi.fn().mockResolvedValue({
372 + ok: true,
373 + json: () =>
374 + Promise.resolve([
375 + {
376 + tag_name: '@composio/core@1.0.0',
377 + assets: [{ name: 'composio-darwin-aarch64.zip' }],
378 + },
379 + ]),
380 + }) as unknown as typeof fetch,
381 + });
382 + const stale = staleLastChecked;
383 + writeState(config, { lastChecked: stale, latestVersion: '0.3.0' });
384 + const { checkForUpdate } = createUpdateChecker(config);
385
289 - it('still writes lastChecked when no CLI releases with the required binary are found', async () => {
290 - const config = makeConfig({
291 - fetchFn: vi.fn().mockResolvedValue({
292 - ok: true,
293 - json: () =>
294 - Promise.resolve([
295 - { tag_name: '@composio/core@1.0.0', assets: [{ name: 'composio-darwin-aarch64.zip' }] },
296 - ]),
297 - }) as unknown as typeof fetch,
298 - });
299 - const { checkForUpdate } = createUpdateChecker(config);
300 -
301 - await checkForUpdate();
302 -
303 - expect(existsSync(config.stateFile)).toBe(true);
304 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
305 - expect(state.lastChecked).toBeDefined();
306 - // Falls back to currentVersion since no previous state and no matching releases found
307 - expect(state.latestVersion).toBe(config.currentVersion);
308 - });
386 + yield* checkForUpdate;
387
310 - it('preserves previous latestVersion when no CLI releases with the required binary are found', async () => {
311 - const config = makeConfig({
312 - fetchFn: vi.fn().mockResolvedValue({
388 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
389 + expect(state.latestVersion).toBe('0.3.0');
390 + expect(new Date(state.lastChecked).getTime()).toBeGreaterThan(new Date(stale).getTime());
391 + }).pipe(Effect.provide(PlatformLayers))
392 + );
393 +
394 + it.effect('writes lastChecked on HTTP errors to prevent retry loops', () =>
395 + Effect.gen(function* () {
396 + const config = makeConfig({
397 + fetchFn: vi.fn().mockResolvedValue({
398 + ok: false,
399 + status: 500,
400 + }) as unknown as typeof fetch,
401 + });
402 + const { checkForUpdate } = createUpdateChecker(config);
403 +
404 + // Should not fail
405 + yield* checkForUpdate;
406 +
407 + expect(existsSync(config.stateFile)).toBe(true);
408 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
409 + expect(state.lastChecked).toBeDefined();
410 + expect(state.latestVersion).toBe(config.currentVersion);
411 + }).pipe(Effect.provide(PlatformLayers))
412 + );
413 +
414 + it.effect('writes lastChecked on network errors to prevent retry loops', () =>
415 + Effect.gen(function* () {
416 + const config = makeConfig({
417 + fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
418 + });
419 + const { checkForUpdate } = createUpdateChecker(config);
420 +
421 + yield* checkForUpdate;
422 +
423 + expect(existsSync(config.stateFile)).toBe(true);
424 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
425 + expect(state.lastChecked).toBeDefined();
426 + expect(state.latestVersion).toBe(config.currentVersion);
427 + }).pipe(Effect.provide(PlatformLayers))
428 + );
429 +
430 + it.effect('sends Authorization header when accessToken is set', () =>
431 + Effect.gen(function* () {
432 + const fetchFn = vi.fn().mockResolvedValue({
433 ok: true,
314 - json: () =>
315 - Promise.resolve([
316 - { tag_name: '@composio/core@1.0.0', assets: [{ name: 'composio-darwin-aarch64.zip' }] },
317 - ]),
318 - }) as unknown as typeof fetch,
319 - });
320 - const stale = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString();
321 - writeState(config, { lastChecked: stale, latestVersion: '0.3.0' });
322 - const { checkForUpdate } = createUpdateChecker(config);
323 -
324 - await checkForUpdate();
325 -
326 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
327 - expect(state.latestVersion).toBe('0.3.0');
328 - expect(new Date(state.lastChecked).getTime()).toBeGreaterThan(new Date(stale).getTime());
329 - });
330 -
331 - it('writes lastChecked on HTTP errors to prevent retry loops', async () => {
332 - const config = makeConfig({
333 - fetchFn: vi.fn().mockResolvedValue({
334 - ok: false,
335 - status: 500,
336 - }) as unknown as typeof fetch,
337 - });
338 - const { checkForUpdate } = createUpdateChecker(config);
339 -
340 - // Should not throw
341 - await checkForUpdate();
342 -
343 - expect(existsSync(config.stateFile)).toBe(true);
344 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
345 - expect(state.lastChecked).toBeDefined();
346 - expect(state.latestVersion).toBe(config.currentVersion);
347 - });
348 -
349 - it('writes lastChecked on network errors to prevent retry loops', async () => {
350 - const config = makeConfig({
351 - fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
352 - });
353 - const { checkForUpdate } = createUpdateChecker(config);
354 -
355 - await checkForUpdate();
356 -
357 - expect(existsSync(config.stateFile)).toBe(true);
358 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
359 - expect(state.lastChecked).toBeDefined();
360 - expect(state.latestVersion).toBe(config.currentVersion);
361 - });
362 -
363 - it('sends Authorization header when accessToken is set', async () => {
364 - const fetchFn = vi.fn().mockResolvedValue({
365 - ok: true,
366 - json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])),
367 - });
368 - const config = makeConfig({
369 - accessToken: 'ghp_secret123',
370 - fetchFn: fetchFn as unknown as typeof fetch,
371 - });
372 - const { checkForUpdate } = createUpdateChecker(config);
373 -
374 - await checkForUpdate();
375 -
376 - expect(fetchFn).toHaveBeenCalledOnce();
377 - const [, init] = fetchFn.mock.calls[0];
378 - expect(init.headers.Authorization).toBe('Bearer ghp_secret123');
379 - });
380 -
381 - it('does not send Authorization header when accessToken is undefined', async () => {
382 - const fetchFn = vi.fn().mockResolvedValue({
383 - ok: true,
384 - json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])),
385 - });
386 - const config = makeConfig({
387 - accessToken: undefined,
388 - fetchFn: fetchFn as unknown as typeof fetch,
389 - });
390 - const { checkForUpdate } = createUpdateChecker(config);
391 -
392 - await checkForUpdate();
393 -
394 - const [, init] = fetchFn.mock.calls[0];
395 - expect(init.headers.Authorization).toBeUndefined();
396 - });
434 + json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])),
435 + });
436 + const config = makeConfig({
437 + accessToken: 'ghp_secret123',
438 + fetchFn: fetchFn as unknown as typeof fetch,
439 + });
440 + const { checkForUpdate } = createUpdateChecker(config);
441 +
442 + yield* checkForUpdate;
443 +
444 + expect(fetchFn).toHaveBeenCalledOnce();
445 + const [, init] = fetchFn.mock.calls[0];
446 + expect(init.headers.Authorization).toBe('Bearer ghp_secret123');
447 + }).pipe(Effect.provide(PlatformLayers))
448 + );
449 +
450 + it.effect('does not send Authorization header when accessToken is undefined', () =>
451 + Effect.gen(function* () {
452 + const fetchFn = vi.fn().mockResolvedValue({
453 + ok: true,
454 + json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])),
455 + });
456 + const config = makeConfig({
457 + accessToken: undefined,
458 + fetchFn: fetchFn as unknown as typeof fetch,
459 + });
460 + const { checkForUpdate } = createUpdateChecker(config);
461 +
462 + yield* checkForUpdate;
463 +
464 + const [, init] = fetchFn.mock.calls[0];
465 + expect(init.headers.Authorization).toBeUndefined();
466 + }).pipe(Effect.provide(PlatformLayers))
467 + );
468 });
469
470 // ── Integration: real HTTP server ───────────────────────────────────────
471
472 describe('checkForUpdate with real HTTP', () => {
402 - it('fetches from a real server and writes state', async () => {
403 - await withHttpServer(
473 + it.effect('fetches from a real server and writes state', () =>
474 + withHttpServerEffect(
475 (_req, res) => {
476 res.writeHead(200, { 'Content-Type': 'application/json' });
477 res.end(JSON.stringify(makeReleasesPayload(['0.1.26', '0.2.0', '0.2.1'])));
478 },
408 - async baseUrl => {
409 - const config = makeConfig({ releasesUrl: baseUrl, fetchFn: fetch });
410 - const { checkForUpdate } = createUpdateChecker(config);
479 + baseUrl =>
480 + Effect.gen(function* () {
481 + const config = makeConfig({ releasesUrl: baseUrl, fetchFn: fetch });
482 + const { checkForUpdate } = createUpdateChecker(config);
483
412 - await checkForUpdate();
484 + yield* checkForUpdate;
485
414 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
415 - expect(state.latestVersion).toBe('0.2.1');
416 - }
417 - );
418 - });
486 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
487 + expect(state.latestVersion).toBe('0.2.1');
488 + })
489 + ).pipe(Effect.provide(PlatformLayers))
490 + );
491
420 - it('passes Authorization header to the server', async () => {
492 + it.effect('passes Authorization header to the server', () => {
493 let receivedAuth: string | undefined;
494
423 - await withHttpServer(
495 + return withHttpServerEffect(
496 (req, res) => {
497 receivedAuth = req.headers.authorization;
498 res.writeHead(200, { 'Content-Type': 'application/json' });
499 res.end(JSON.stringify(makeReleasesPayload(['0.2.1'])));
500 },
429 - async baseUrl => {
430 - const config = makeConfig({
431 - releasesUrl: baseUrl,
432 - accessToken: 'ghp_test_token',
433 - fetchFn: fetch,
434 - });
435 - const { checkForUpdate } = createUpdateChecker(config);
436 -
437 - await checkForUpdate();
438 -
439 - expect(receivedAuth).toBe('Bearer ghp_test_token');
440 - }
441 - );
501 + baseUrl =>
502 + Effect.gen(function* () {
503 + const config = makeConfig({
504 + releasesUrl: baseUrl,
505 + accessToken: 'ghp_test_token',
506 + fetchFn: fetch,
507 + });
508 + const { checkForUpdate } = createUpdateChecker(config);
509 +
510 + yield* checkForUpdate;
511 +
512 + expect(receivedAuth).toBe('Bearer ghp_test_token');
513 + })
514 + ).pipe(Effect.provide(PlatformLayers));
515 });
516 });
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+8
@@ -14,7 +14,15 @@ import { collectExpectedRunCompanionAssetRelativePaths } from 'src/services/run-
14 const TerminalUINoop = Layer.succeed(
15 TerminalUI,
16 TerminalUI.of({
17 + capabilities: Effect.succeed({
18 + stdinIsTTY: false,
19 + stdoutIsTTY: false,
20 + stderrIsTTY: false,
21 + isInteractive: false,
22 + canDecorate: false,
23 + }),
24 output: () => Effect.void,
25 + error: () => Effect.void,
26 intro: () => Effect.void,
27 outro: () => Effect.void,
28 log: {
ts/packages/cli/test/src/utils/stdio.test.ts deleted
-34
@@ -1,34 +0,0 @@
1 -import { describe, expect, it } from 'vitest';
2 -import { canRenderTerminalDecoration, isInteractiveTerminal } from 'src/utils/stdio';
3 -
4 -describe('stdio helpers', () => {
5 - it('requires all streams to be TTYs for interactive prompts', () => {
6 - expect(
7 - isInteractiveTerminal({
8 - stdin: { isTTY: false },
9 - stdout: { isTTY: true },
10 - stderr: { isTTY: true },
11 - })
12 - ).toBe(false);
13 - });
14 -
15 - it('allows terminal decoration when only stderr is a TTY', () => {
16 - expect(
17 - canRenderTerminalDecoration({
18 - stdin: { isTTY: false },
19 - stdout: { isTTY: true },
20 - stderr: { isTTY: true },
21 - })
22 - ).toBe(true);
23 - });
24 -
25 - it('suppresses terminal decoration when stderr is not a TTY', () => {
26 - expect(
27 - canRenderTerminalDecoration({
28 - stdin: { isTTY: true },
29 - stdout: { isTTY: true },
30 - stderr: { isTTY: false },
31 - })
32 - ).toBe(false);
33 - });
34 -});