Skip to content

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

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

Alberto Schiabel5318f60de9b0
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 693c6d42d..3a10baf7c 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -201,9 +201,12 @@ export default [
],
},
],
- // uncommented by the terminal-streams PR of this stack (the try/catch and
- // process.env entries by the boundary-ratchet PR).
- // 'no-restricted-syntax': ['error', ...cliRestrictedSyntax, ...cliProcessStreamRestrictions],
+ 'no-restricted-syntax': [
+ 'error',
+ // uncommented by the boundary-ratchet PR of this stack
+ // ...cliRestrictedSyntax,
+ ...cliProcessStreamRestrictions,
+ ],
},
},
// uncommented by the test-rules PR of this stack.
@@ -262,14 +265,13 @@ export default [
// ],
// },
// },
- // uncommented by the terminal-streams PR of this stack.
- // {
- // files: ['ts/packages/cli/src/services/terminal-ui.ts'],
- // rules: {
- // // TerminalUI is the sole CLI boundary for Node's stdout and stderr streams.
- // 'no-restricted-syntax': ['error', ...cliRestrictedSyntax],
- // },
- // },
+ {
+ files: ['ts/packages/cli/src/services/terminal-ui.ts'],
+ rules: {
+ // TerminalUI is the sole CLI boundary for Node's stdout and stderr streams.
+ 'no-restricted-syntax': ['error', ...cliRestrictedSyntax],
+ },
+ },
{
// Examples are console-driven references. Keep type-safety rules
// (no-explicit-any, unused-vars) but drop console noise. The Buffer/crypto
diff --git a/ts/packages/cli/src/analytics/dispatch.ts b/ts/packages/cli/src/analytics/dispatch.ts
index f6013067a..8ef3a9377 100644
--- a/ts/packages/cli/src/analytics/dispatch.ts
+++ b/ts/packages/cli/src/analytics/dispatch.ts
@@ -1,15 +1,22 @@
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
-import fs from 'node:fs';
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
-import os from 'node:os';
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
-import path from 'node:path';
import process from 'node:process';
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
-import { spawn } from 'node:child_process';
-import { Effect } from 'effect';
-import type { AnalyticsEnvelope, TrackEvent } from './types';
+import { FileSystem, HttpClient, HttpClientRequest, Path } from '@effect/platform';
+import {
+ Cause,
+ Clock,
+ Config,
+ ConfigProvider,
+ DateTime,
+ Effect,
+ Encoding,
+ Option,
+ Schema,
+} from 'effect';
import * as constants from 'src/constants';
+import { spawnDetached } from 'src/services/detached-process';
+import { djb2Hash } from 'src/utils/djb2';
+import { NodeOs } from 'src/services/node-os';
+import { TerminalUI } from 'src/services/terminal-ui';
+import type { AnalyticsEnvelope, TrackEvent } from './types';
const INTERNAL_ANALYTICS_WORKER_FLAG = '__analytics-worker';
const INTERNAL_CODACT_FAILURE_WORKER_FLAG = '__codact-failure-worker';
@@ -18,7 +25,6 @@ const ANALYTICS_STATE_FILE_NAME = 'analytics.json';
const CONSUMER_SHORT_TERM_CACHE_FILE_NAME = 'consumer-short-term-cache.json';
const CLI_ANALYTICS_PATH = '/api/v3/cli/analytics';
const CLI_CODACT_FAILURES_PATH = '/api/v3/cli/codact_failures';
-const TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';
export type CliCodactFailureType = 'wrong_tool_slug' | 'wrong_tool_input_param';
@@ -38,37 +44,6 @@ export type CliCodactFailure = {
readonly requestId?: string;
};
-const truthy = (value: string | undefined): boolean =>
- value === '1' || value === 'true' || value === 'yes' || value === 'on';
-
-const isTelemetryDebugEnabled = (): boolean => truthy(process.env[TELEMETRY_DEBUG_ENV_VAR]);
-
-const telemetryDebugLog = (label: string, payload: Record<string, unknown>) => {
- if (!isTelemetryDebugEnabled()) {
- return;
- }
-
- process.stderr.write(
- `[telemetry-debug] ${JSON.stringify(
- {
- label,
- ...payload,
- },
- null,
- 2
- )}\n`
- );
-};
-
-const analyticsDir = () => path.join(os.homedir(), COMPOSIO_DIR);
-const analyticsStatePath = () => path.join(analyticsDir(), ANALYTICS_STATE_FILE_NAME);
-const userConfigPath = () => path.join(analyticsDir(), constants.USER_CONFIG_FILE_NAME);
-const cacheDir = () =>
- process.env.COMPOSIO_CACHE_DIR?.trim() ||
- process.env.CACHE_DIR?.trim() ||
- path.join(os.homedir(), constants.USER_COMPOSIO_DIR);
-const consumerShortTermCachePath = () => path.join(cacheDir(), CONSUMER_SHORT_TERM_CACHE_FILE_NAME);
-
type ConsumerShortTermCacheState = Record<
string,
{
@@ -82,122 +57,170 @@ type ConsumerShortTermCacheState = Record<
}
>;
-const ensureAnalyticsDir = () => {
- try {
- fs.mkdirSync(analyticsDir(), { recursive: true });
- } catch {
- // Non-fatal — analytics directory creation may fail in sandboxed environments.
- }
-};
+// Workers start before the CLI's prefixed ConfigProvider is assembled, so this
+// module names and reads the actual environment variables from a raw provider.
+const environmentProvider = ConfigProvider.fromEnv();
+const optionalString = (name: string) => Config.option(Config.string(name));
+const booleanWithDefault = (name: string) => Config.boolean(name).pipe(Config.withDefault(false));
+const configuredString = (value: Option.Option<string>): string | undefined =>
+ value.pipe(
+ Option.map(value => value.trim()),
+ Option.filter(value => value.length > 0),
+ Option.getOrUndefined
+ );
-const encodeBase64Url = (value: string): string => {
- const bytes = new TextEncoder().encode(value);
- let binary = '';
- for (const byte of bytes) {
- binary += String.fromCharCode(byte);
- }
- return btoa(binary).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
-};
+const telemetryDebugEnabled = environmentProvider.load(
+ booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DEBUG')
+);
+
+const analyticsDisabled = environmentProvider.load(
+ Config.all({
+ cliTelemetryDisabled: booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DISABLED'),
+ telemetryDisabled: booleanWithDefault('TELEMETRY_DISABLED'),
+ composioTelemetryDisabled: booleanWithDefault('COMPOSIO_DISABLE_TELEMETRY'),
+ nodeEnvironment: Config.string('NODE_ENV').pipe(Config.withDefault('')),
+ ci: booleanWithDefault('CI'),
+ }).pipe(
+ Config.map(
+ ({
+ cliTelemetryDisabled,
+ telemetryDisabled,
+ composioTelemetryDisabled,
+ nodeEnvironment,
+ ci,
+ }) =>
+ cliTelemetryDisabled ||
+ telemetryDisabled ||
+ composioTelemetryDisabled ||
+ nodeEnvironment === 'test' ||
+ ci
+ )
+ )
+);
+
+const jsonFromString = Schema.parseJson();
+const prettyJsonFromString = Schema.parseJson({ space: 2 });
+const decodeJson = Schema.decodeUnknown(jsonFromString);
+const encodeJson = Schema.encode(jsonFromString);
+const encodePrettyJson = Schema.encode(prettyJsonFromString);
+
+const telemetryDebugLog = (label: string, payload: Record<string, unknown>) =>
+ Effect.gen(function* () {
+ if (!(yield* telemetryDebugEnabled)) {
+ return;
+ }
-const decodeBase64Url = (value: string): string => {
- const normalized = value.replace(/-/gu, '+').replace(/_/gu, '/');
- const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
- const binary = atob(padded);
- const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
- return new TextDecoder().decode(bytes);
+ const body = yield* encodePrettyJson({ label, ...payload });
+ const ui = yield* TerminalUI;
+ yield* ui.error(`[telemetry-debug] ${body}`);
+ }).pipe(Effect.ignore);
+
+const telemetryErrorDetails = (cause: Cause.Cause<unknown>): Record<string, string> => {
+ const squashed = Cause.squash(cause);
+ const error = Cause.isUnknownException(squashed) ? squashed.error : squashed;
+ return error instanceof Error
+ ? { name: error.name, message: error.message }
+ : { message: String(error) };
};
-const djb2Hash = (value: string): number => {
- let hash = 5381;
- for (let index = 0; index < value.length; index += 1) {
- hash = (hash * 33) ^ value.charCodeAt(index);
- }
- return Math.abs(hash >>> 0);
-};
+const getAnalyticsPaths = Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const os = yield* NodeOs;
+ const cacheDirectories = yield* environmentProvider.load(
+ Config.all({
+ composio: optionalString('COMPOSIO_CACHE_DIR'),
+ legacy: optionalString('CACHE_DIR'),
+ })
+ );
+ const analyticsDir = path.join(os.homedir, COMPOSIO_DIR);
+ const cacheDir =
+ configuredString(cacheDirectories.composio) ??
+ configuredString(cacheDirectories.legacy) ??
+ path.join(os.homedir, constants.USER_COMPOSIO_DIR);
+
+ return {
+ analyticsDir,
+ analyticsStatePath: path.join(analyticsDir, ANALYTICS_STATE_FILE_NAME),
+ userConfigPath: path.join(analyticsDir, constants.USER_CONFIG_FILE_NAME),
+ consumerShortTermCachePath: path.join(cacheDir, CONSUMER_SHORT_TERM_CACHE_FILE_NAME),
+ };
+});
+
+const readOptionalJson = <A>(filePath: string) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const raw = yield* fs.readFileString(filePath, 'utf8');
+ return (yield* decodeJson(raw)) as A;
+ }).pipe(Effect.catchAll(() => Effect.succeed(undefined)));
const hashString = (value: string): string => djb2Hash(value).toString(16).padStart(8, '0');
-const getOrCreateInstallId = (): string => {
- try {
- ensureAnalyticsDir();
- const filePath = analyticsStatePath();
- if (fs.existsSync(filePath)) {
- const raw = fs.readFileSync(filePath, 'utf8');
- const parsed = JSON.parse(raw) as { install_id?: unknown };
- if (typeof parsed.install_id === 'string' && parsed.install_id.length > 0) {
- return parsed.install_id;
- }
- }
- const installId = crypto.randomUUID();
- fs.writeFileSync(
- filePath,
- JSON.stringify(
- {
- install_id: installId,
- created_at: new Date().toISOString(),
- },
- null,
- 2
- ),
- 'utf8'
- );
- return installId;
- } catch {
- return crypto.randomUUID();
- }
-};
+const makeInstallId = Effect.sync(() => crypto.randomUUID());
-const getHashedApiKeyDistinctId = (): string | null => {
- const envApiKey = process.env.COMPOSIO_USER_API_KEY?.trim();
- if (envApiKey) {
- return `user_${hashString(envApiKey)}`;
- }
+const getOrCreateInstallId = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const paths = yield* getAnalyticsPaths;
- try {
- const raw = fs.readFileSync(userConfigPath(), 'utf8');
- const parsed = JSON.parse(raw) as { api_key?: unknown };
- if (typeof parsed.api_key === 'string' && parsed.api_key.trim().length > 0) {
- return `user_${hashString(parsed.api_key.trim())}`;
- }
- } catch {
- // Ignore user config read failures.
+ yield* fs
+ .makeDirectory(paths.analyticsDir, { recursive: true })
+ .pipe(Effect.catchAll(() => Effect.void));
+
+ const state = yield* readOptionalJson<{ install_id?: unknown }>(paths.analyticsStatePath);
+ if (typeof state?.install_id === 'string' && state.install_id.length > 0) {
+ return state.install_id;
}
- return null;
-};
+ const installId = yield* makeInstallId;
+ const createdAt = DateTime.formatIso(yield* DateTime.now);
+ const contents = yield* encodeJson({
+ install_id: installId,
+ created_at: createdAt,
+ });
+ yield* fs.writeFileString(paths.analyticsStatePath, contents);
+ return installId;
+}).pipe(Effect.catchAll(() => makeInstallId));
-const getDistinctId = (): string => getHashedApiKeyDistinctId() ?? `anon_${getOrCreateInstallId()}`;
+const readUserConfig = Effect.gen(function* () {
+ const paths = yield* getAnalyticsPaths;
+ return yield* readOptionalJson<{ api_key?: unknown; base_url?: unknown }>(paths.userConfigPath);
+});
-const getUserApiKey = (): string | null => {
- const envApiKey = process.env.COMPOSIO_USER_API_KEY?.trim();
+const getUserApiKey = Effect.gen(function* () {
+ const envApiKey = configuredString(
+ yield* environmentProvider.load(optionalString('COMPOSIO_USER_API_KEY'))
+ );
if (envApiKey) {
return envApiKey;
}
- try {
- const raw = fs.readFileSync(userConfigPath(), 'utf8');
- const parsed = JSON.parse(raw) as { api_key?: unknown };
- if (typeof parsed.api_key === 'string' && parsed.api_key.trim().length > 0) {
- return parsed.api_key.trim();
- }
- } catch {
- // Ignore user config read failures.
- }
+ const userConfig = yield* readUserConfig;
+ return typeof userConfig?.api_key === 'string' && userConfig.api_key.trim().length > 0
+ ? userConfig.api_key.trim()
+ : null;
+});
- return null;
-};
+const getDistinctId = (installId: string) =>
+ Effect.map(getUserApiKey, userApiKey =>
+ userApiKey ? `user_${hashString(userApiKey)}` : `anon_${installId}`
+ );
const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);
-export const getCurrentCwdSessionId = (): string | undefined => {
- try {
- const raw = fs.readFileSync(consumerShortTermCachePath(), 'utf8');
- const parsed = JSON.parse(raw) as ConsumerShortTermCacheState;
- const currentCwdHash = cwdHash(process.cwd());
- const now = Date.now();
+export const getCurrentCwdSessionId = (cwd = process.cwd()) =>
+ Effect.gen(function* () {
+ const paths = yield* getAnalyticsPaths;
+ const state = yield* readOptionalJson<ConsumerShortTermCacheState>(
+ paths.consumerShortTermCachePath
+ );
+ if (!state) {
+ return undefined;
+ }
+
+ const currentCwdHash = cwdHash(cwd);
+ const now = yield* Clock.currentTimeMillis;
let best: { id: string; expiresAtMs: number } | undefined;
- for (const entry of Object.values(parsed)) {
+ for (const entry of Object.values(state)) {
const session = entry.probablyMyCliSessionsByCwdHash?.[currentCwdHash];
if (!session?.id) continue;
const expiresAtMs = Date.parse(session.expiresAt);
@@ -208,288 +231,268 @@ export const getCurrentCwdSessionId = (): string | undefined => {
}
return best?.id;
- } catch {
- return undefined;
- }
-};
-
-const withCliSessionId = (event: TrackEvent): TrackEvent => {
- if (!event) return event;
- const cliSessionId = getCurrentCwdSessionId();
- return {
- ...event,
- properties: {
- ...(event.properties ?? {}),
- cli_version: event.properties?.cli_version ?? constants.APP_VERSION,
- ...(cliSessionId ? { cli_session_id: cliSessionId } : {}),
- },
- };
-};
+ }).pipe(Effect.catchAllCause(() => Effect.succeed(undefined)));
+
+const withCliSessionId = (event: NonNullable<TrackEvent>, cliSessionId?: string): TrackEvent => ({
+ ...event,
+ properties: {
+ ...(event.properties ?? {}),
+ cli_version: event.properties?.cli_version ?? constants.APP_VERSION,
+ ...(cliSessionId ? { cli_session_id: cliSessionId } : {}),
+ },
+});
-export const readApiBaseUrl = (): string | null => {
- const envBaseUrl = process.env.COMPOSIO_BASE_URL?.trim();
+export const readApiBaseUrl = Effect.gen(function* () {
+ const envBaseUrl = configuredString(
+ yield* environmentProvider.load(optionalString('COMPOSIO_BASE_URL'))
+ );
if (envBaseUrl) {
return envBaseUrl.replace(/\/+$/u, '');
}
- try {
- const raw = fs.readFileSync(userConfigPath(), 'utf8');
- const parsed = JSON.parse(raw) as { base_url?: unknown };
- if (typeof parsed.base_url === 'string' && parsed.base_url.trim().length > 0) {
- return parsed.base_url.trim().replace(/\/+$/u, '');
- }
- } catch {
- // Ignore user config read failures.
- }
-
- return null;
-};
+ const userConfig = yield* readUserConfig;
+ return typeof userConfig?.base_url === 'string' && userConfig.base_url.trim().length > 0
+ ? userConfig.base_url.trim().replace(/\/+$/u, '')
+ : null;
+}).pipe(Effect.catchAllCause(() => Effect.succeed(null)));
+
+const getAnalyticsEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
+ baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null
+);
+
+const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
+ baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null
+);
+
+const getWorkerSpawnArgs = (workerFlag: string, encodedPayload: string) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const maybeScriptPath = process.argv[1];
+ const scriptPathExists =
+ typeof maybeScriptPath === 'string' && maybeScriptPath.length > 0
+ ? yield* fs.exists(maybeScriptPath).pipe(Effect.catchAll(() => Effect.succeed(false)))
+ : false;
+ const scriptPathLooksReal =
+ scriptPathExists && /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath ?? '');
+
+ return scriptPathLooksReal
+ ? {
+ command: process.execPath,
+ args: [maybeScriptPath as string, workerFlag, encodedPayload],
+ }
+ : {
+ command: process.execPath,
+ args: [workerFlag, encodedPayload],
+ };
+ });
-const getAnalyticsEndpoint = (): string | null => {
- const baseUrl = readApiBaseUrl();
- return baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null;
-};
+// Effect's Command processes are scoped and die with their scope; telemetry
+// workers intentionally outlive the CLI process, so they go through the
+// sanctioned detached-spawn boundary in src/services/detached-process.
+// Delivery is best effort: a failed spawn is swallowed, never surfaced.
+const spawnWorker = (command: string, args: ReadonlyArray<string>) =>
+ Effect.gen(function* () {
+ const debugEnabled = yield* telemetryDebugEnabled;
+ yield* spawnDetached(command, args, { inheritStderr: debugEnabled }).pipe(
+ Effect.catchTag('services/DetachedProcessSpawnError', () => Effect.void)
+ );
+ });
-const getCliCodactFailuresEndpoint = (): string | null => {
- const baseUrl = readApiBaseUrl();
- return baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null;
-};
+const captureToComposioAnalytics = (envelope: AnalyticsEnvelope) =>
+ Effect.gen(function* () {
+ const endpoint = yield* getAnalyticsEndpoint;
+ const disabled = yield* analyticsDisabled;
+ if (!endpoint || disabled) {
+ yield* telemetryDebugLog('delivery_skipped', {
+ reason: disabled ? 'disabled' : 'missing_endpoint',
+ endpoint,
+ eventName: envelope.event,
+ });
+ return;
+ }
-export const shouldDisableAnalytics = (): boolean =>
- truthy(process.env.COMPOSIO_CLI_TELEMETRY_DISABLED) ||
- truthy(process.env.TELEMETRY_DISABLED) ||
- truthy(process.env.COMPOSIO_DISABLE_TELEMETRY) ||
- process.env.NODE_ENV === 'test' ||
- process.env.CI === 'true';
-
-const getWorkerSpawnArgs = (encodedPayload: string): { command: string; args: string[] } => {
- const maybeScriptPath = process.argv[1];
- const scriptPathLooksReal =
- typeof maybeScriptPath === 'string' &&
- maybeScriptPath.length > 0 &&
- fs.existsSync(maybeScriptPath) &&
- /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath);
-
- return scriptPathLooksReal
- ? {
- command: process.execPath,
- args: [maybeScriptPath, INTERNAL_ANALYTICS_WORKER_FLAG, encodedPayload],
- }
- : {
- command: process.execPath,
- args: [INTERNAL_ANALYTICS_WORKER_FLAG, encodedPayload],
- };
-};
+ const httpClient = yield* HttpClient.HttpClient;
+ const userApiKey = yield* getUserApiKey;
+ const request = yield* HttpClientRequest.post(endpoint).pipe(
+ HttpClientRequest.setHeaders({
+ 'x-composio-analytics-source': 'cli',
+ ...(userApiKey ? { 'x-user-api-key': userApiKey } : {}),
+ }),
+ HttpClientRequest.bodyJson(envelope)
+ );
+ const response = yield* httpClient.execute(request);
+ const responseOk = response.status >= 200 && response.status < 300;
+ const debugEnabled = yield* telemetryDebugEnabled;
+ const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
-const captureToComposioAnalytics = async (envelope: AnalyticsEnvelope): Promise<void> => {
- const endpoint = getAnalyticsEndpoint();
- if (!endpoint || shouldDisableAnalytics()) {
- telemetryDebugLog('delivery_skipped', {
- reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
+ yield* telemetryDebugLog(responseOk ? 'delivery_succeeded' : 'delivery_failed', {
endpoint,
eventName: envelope.event,
+ status: response.status,
+ ok: responseOk,
+ responseBody: responseBody?.slice(0, 1000),
});
- return;
- }
-
- const userApiKey = getUserApiKey();
- const response = await fetch(endpoint, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'x-composio-analytics-source': 'cli',
- ...(userApiKey ? { 'x-user-api-key': userApiKey } : {}),
- },
- body: JSON.stringify(envelope),
});
- const responseBody =
- !response.ok && isTelemetryDebugEnabled() ? await response.text() : undefined;
-
- telemetryDebugLog(response.ok ? 'delivery_succeeded' : 'delivery_failed', {
- endpoint,
- eventName: envelope.event,
- status: response.status,
- ok: response.ok,
- responseBody: responseBody?.slice(0, 1000),
- });
-};
-export const createCliCodactFailureBody = (
- failure: CliCodactFailure
-): {
+type CliCodactFailureBody = {
failure_type: CliCodactFailureType;
tool_info?: CliCodactFailureToolInfo;
ctx: Record<string, unknown>;
session: Record<string, unknown>;
request_id?: string;
-} => ({
+};
+
+type CliInvocationContext = {
+ readonly origin?: string;
+ readonly parentRunId?: string;
+};
+
+const getCliInvocationContext = environmentProvider
+ .load(
+ Config.all({
+ origin: optionalString('COMPOSIO_CLI_INVOCATION_ORIGIN'),
+ parentRunId: optionalString('COMPOSIO_CLI_PARENT_RUN_ID'),
+ })
+ )
+ .pipe(
+ Effect.map(({ origin, parentRunId }) => ({
+ origin: configuredString(origin),
+ parentRunId: configuredString(parentRunId),
+ }))
+ );
+
+export const createCliCodactFailureBody = (
+ failure: CliCodactFailure,
+ cliSessionId?: string,
+ invocation: CliInvocationContext = {}
+): CliCodactFailureBody => ({
failure_type: failure.failureType,
...(failure.toolInfo ? { tool_info: failure.toolInfo } : {}),
ctx: failure.ctx,
session: {
source: 'cli',
- id: getCurrentCwdSessionId(),
+ id: cliSessionId,
cli_version: constants.APP_VERSION,
- invocation_origin: process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli',
- parent_run_id: process.env.COMPOSIO_CLI_PARENT_RUN_ID,
+ invocation_origin: invocation.origin ?? 'cli',
+ parent_run_id: invocation.parentRunId,
...(failure.session ?? {}),
},
...(failure.requestId ? { request_id: failure.requestId } : {}),
});
-const captureToComposioCodactFailures = async (failure: CliCodactFailure): Promise<void> => {
- const endpoint = getCliCodactFailuresEndpoint();
- if (!endpoint || shouldDisableAnalytics()) {
- telemetryDebugLog('codact_delivery_skipped', {
- reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
- endpoint,
- failureType: failure.failureType,
- });
- return;
- }
+const captureToComposioCodactFailures = (failure: CliCodactFailure) =>
+ Effect.gen(function* () {
+ const endpoint = yield* getCliCodactFailuresEndpoint;
+ const disabled = yield* analyticsDisabled;
+ if (!endpoint || disabled) {
+ yield* telemetryDebugLog('codact_delivery_skipped', {
+ reason: disabled ? 'disabled' : 'missing_endpoint',
+ endpoint,
+ failureType: failure.failureType,
+ });
+ return;
+ }
+
+ const userApiKey = yield* getUserApiKey;
+ if (!userApiKey) {
+ yield* telemetryDebugLog('codact_delivery_skipped', {
+ reason: 'missing_user_api_key',
+ endpoint,
+ failureType: failure.failureType,
+ });
+ return;
+ }
- const userApiKey = getUserApiKey();
- if (!userApiKey) {
- telemetryDebugLog('codact_delivery_skipped', {
- reason: 'missing_user_api_key',
+ const httpClient = yield* HttpClient.HttpClient;
+ const cliSessionId = yield* getCurrentCwdSessionId();
+ const invocation = yield* getCliInvocationContext;
+ const body = createCliCodactFailureBody(failure, cliSessionId, invocation);
+ const request = yield* HttpClientRequest.post(endpoint).pipe(
+ HttpClientRequest.setHeader('x-user-api-key', userApiKey),
+ HttpClientRequest.bodyJson(body)
+ );
+ const response = yield* httpClient.execute(request);
+ const responseOk = response.status >= 200 && response.status < 300;
+ const debugEnabled = yield* telemetryDebugEnabled;
+ const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
+
+ yield* telemetryDebugLog(responseOk ? 'codact_delivery_succeeded' : 'codact_delivery_failed', {
endpoint,
failureType: failure.failureType,
+ status: response.status,
+ ok: responseOk,
+ responseBody: responseBody?.slice(0, 1000),
});
- return;
- }
-
- const response = await fetch(endpoint, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'x-user-api-key': userApiKey,
- },
- body: JSON.stringify(createCliCodactFailureBody(failure)),
- });
- const responseBody =
- !response.ok && isTelemetryDebugEnabled() ? await response.text() : undefined;
-
- telemetryDebugLog(response.ok ? 'codact_delivery_succeeded' : 'codact_delivery_failed', {
- endpoint,
- failureType: failure.failureType,
- status: response.status,
- ok: response.ok,
- responseBody: responseBody?.slice(0, 1000),
});
-};
-export const trackCliEvent = (event: TrackEvent): void => {
- const endpoint = getAnalyticsEndpoint();
- if (!event) {
- return;
- }
+export const trackCliEventEffect = (event: TrackEvent) =>
+ Effect.gen(function* () {
+ if (!event) {
+ return;
+ }
- if (shouldDisableAnalytics() || !endpoint) {
- telemetryDebugLog('skip', {
- reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
- eventName: event.name,
- endpoint,
- });
- return;
- }
+ const endpoint = yield* getAnalyticsEndpoint;
+ const disabled = yield* analyticsDisabled;
+ if (disabled || !endpoint) {
+ yield* telemetryDebugLog('skip', {
+ reason: disabled ? 'disabled' : 'missing_endpoint',
+ eventName: event.name,
+ endpoint,
+ });
+ return;
+ }
- try {
- const enrichedEvent = withCliSessionId(event);
+ const cliSessionId = yield* getCurrentCwdSessionId();
+ const enrichedEvent = withCliSessionId(event, cliSessionId);
if (!enrichedEvent) {
return;
}
- const installId = getOrCreateInstallId();
- const distinctId = getDistinctId();
+
+ const installId = yield* getOrCreateInstallId;
+ const distinctId = yield* getDistinctId(installId);
+ const sentAt = DateTime.formatIso(yield* DateTime.now);
const envelope: AnalyticsEnvelope = {
event: enrichedEvent.name,
...(enrichedEvent.properties ? { properties: enrichedEvent.properties } : {}),
- sentAt: new Date().toISOString(),
+ sentAt,
source: 'cli',
distinctId,
installId,
};
- telemetryDebugLog('enqueue', {
- endpoint,
- envelope,
- });
- const encodedPayload = encodeBase64Url(JSON.stringify(envelope));
- const { command, args } = getWorkerSpawnArgs(encodedPayload);
- const child = spawn(command, args, {
- detached: true,
- stdio: isTelemetryDebugEnabled() ? ['ignore', 'ignore', 'inherit'] : 'ignore',
- env: {
- ...process.env,
- COMPOSIO_CLI_ANALYTICS_WORKER: '1',
- },
- });
- child.unref();
- } catch {
- // Analytics must never break CLI execution.
- }
-};
+ yield* telemetryDebugLog('enqueue', { endpoint, envelope });
+ const serializedEnvelope = yield* encodeJson(envelope);
+ const encodedPayload = Encoding.encodeBase64Url(serializedEnvelope);
+ const { command, args } = yield* getWorkerSpawnArgs(
+ INTERNAL_ANALYTICS_WORKER_FLAG,
+ encodedPayload
+ );
+ yield* spawnWorker(command, args);
+ }).pipe(Effect.catchAllCause(() => Effect.void));
-export const trackCliEventEffect = (event: TrackEvent) => Effect.sync(() => trackCliEvent(event));
-
-export const trackCliCodactFailure = (failure: CliCodactFailure): void => {
- const endpoint = getCliCodactFailuresEndpoint();
- const userApiKey = getUserApiKey();
- if (shouldDisableAnalytics() || !endpoint || !userApiKey) {
- telemetryDebugLog('codact_skip', {
- reason: shouldDisableAnalytics()
- ? 'disabled'
- : !endpoint
- ? 'missing_endpoint'
- : 'missing_user_api_key',
- failureType: failure.failureType,
- endpoint,
- });
- return;
- }
+export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
+ Effect.gen(function* () {
+ const endpoint = yield* getCliCodactFailuresEndpoint;
+ const userApiKey = yield* getUserApiKey;
+ const disabled = yield* analyticsDisabled;
+ if (disabled || !endpoint || !userApiKey) {
+ yield* telemetryDebugLog('codact_skip', {
+ reason: disabled ? 'disabled' : !endpoint ? 'missing_endpoint' : 'missing_user_api_key',
+ failureType: failure.failureType,
+ endpoint,
+ });
+ return;
+ }
- try {
- const encodedPayload = encodeBase64Url(JSON.stringify(createCliCodactFailureBody(failure)));
- const { command, args } = getWorkerSpawnArgsForFlag(
+ const cliSessionId = yield* getCurrentCwdSessionId();
+ const invocation = yield* getCliInvocationContext;
+ const body = yield* encodeJson(createCliCodactFailureBody(failure, cliSessionId, invocation));
+ const encodedPayload = Encoding.encodeBase64Url(body);
+ const { command, args } = yield* getWorkerSpawnArgs(
INTERNAL_CODACT_FAILURE_WORKER_FLAG,
encodedPayload
);
- const child = spawn(command, args, {
- detached: true,
- stdio: isTelemetryDebugEnabled() ? ['ignore', 'ignore', 'inherit'] : 'ignore',
- env: {
- ...process.env,
- COMPOSIO_CLI_ANALYTICS_WORKER: '1',
- },
- });
- child.unref();
- } catch {
- // Best-effort — codact failure tracking must never break CLI execution.
- }
-};
-
-export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
- Effect.sync(() => trackCliCodactFailure(failure));
-
-const getWorkerSpawnArgsForFlag = (
- workerFlag: string,
- encodedPayload: string
-): { command: string; args: string[] } => {
- const maybeScriptPath = process.argv[1];
- const scriptPathLooksReal =
- typeof maybeScriptPath === 'string' &&
- maybeScriptPath.length > 0 &&
- fs.existsSync(maybeScriptPath) &&
- /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath);
-
- return scriptPathLooksReal
- ? {
- command: process.execPath,
- args: [maybeScriptPath, workerFlag, encodedPayload],
- }
- : {
- command: process.execPath,
- args: [workerFlag, encodedPayload],
- };
-};
+ yield* spawnWorker(command, args);
+ }).pipe(Effect.catchAllCause(() => Effect.void));
const getWorkerFlagIndex = (argv: ReadonlyArray<string>, flag: string): number =>
argv.findIndex(token => token === flag);
@@ -498,45 +501,53 @@ export const isBackgroundWorkerInvocation = (argv: ReadonlyArray<string>): boole
getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG) >= 0 ||
getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG) >= 0;
-export const runBackgroundWorkerFromArgv = async (argv: ReadonlyArray<string>): Promise<void> => {
- const analyticsFlagIndex = getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG);
- if (analyticsFlagIndex >= 0) {
- const encodedPayload = argv[analyticsFlagIndex + 1];
- if (!encodedPayload) {
- return;
- }
+const decodeWorkerPayload = <A>(encodedPayload: string) =>
+ Effect.gen(function* () {
+ const serialized = yield* Encoding.decodeBase64UrlString(encodedPayload);
+ return (yield* decodeJson(serialized)) as A;
+ });
- try {
- const decoded = decodeBase64Url(encodedPayload);
- const envelope = JSON.parse(decoded) as AnalyticsEnvelope;
- if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
- return;
- }
- await captureToComposioAnalytics(envelope);
- } catch (error) {
- telemetryDebugLog('delivery_error', {
- error:
- error instanceof Error
- ? { name: error.name, message: error.message }
- : { message: String(error) },
- });
- }
- return;
+const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
+ const flagIndex = getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG);
+ if (flagIndex < 0) {
+ return Effect.succeed(false);
+ }
+
+ const encodedPayload = argv[flagIndex + 1];
+ if (!encodedPayload) {
+ return Effect.succeed(true);
}
- const codactFlagIndex = getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG);
- if (codactFlagIndex < 0) {
- return;
+ return Effect.gen(function* () {
+ const envelope = yield* decodeWorkerPayload<AnalyticsEnvelope>(encodedPayload);
+ if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
+ return true;
+ }
+ yield* captureToComposioAnalytics(envelope);
+ return true;
+ }).pipe(
+ Effect.catchAllCause(cause =>
+ telemetryDebugLog('delivery_error', { error: telemetryErrorDetails(cause) }).pipe(
+ Effect.as(true)
+ )
+ )
+ );
+};
+
+const runCodactFailureWorker = (argv: ReadonlyArray<string>) => {
+ const flagIndex = getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG);
+ if (flagIndex < 0) {
+ return Effect.void;
}
- const encodedPayload = argv[codactFlagIndex + 1];
+ const encodedPayload = argv[flagIndex + 1];
if (!encodedPayload) {
- return;
+ return Effect.void;
}
- try {
- const decoded = decodeBase64Url(encodedPayload);
- const body = JSON.parse(decoded) as ReturnType<typeof createCliCodactFailureBody>;
+ return Effect.gen(function* () {
+ const body =
+ yield* decodeWorkerPayload<ReturnType<typeof createCliCodactFailureBody>>(encodedPayload);
if (
body?.failure_type !== 'wrong_tool_slug' &&
body?.failure_type !== 'wrong_tool_input_param'
@@ -544,19 +555,24 @@ export const runBackgroundWorkerFromArgv = async (argv: ReadonlyArray<string>):
return;
}
- await captureToComposioCodactFailures({
+ yield* captureToComposioCodactFailures({
failureType: body.failure_type,
toolInfo: body.tool_info,
ctx: body.ctx,
session: body.session,
requestId: body.request_id,
});
- } catch (error) {
- telemetryDebugLog('codact_delivery_error', {
- error:
- error instanceof Error
- ? { name: error.name, message: error.message }
- : { message: String(error) },
- });
- }
+ }).pipe(
+ Effect.catchAllCause(cause =>
+ telemetryDebugLog('codact_delivery_error', { error: telemetryErrorDetails(cause) })
+ )
+ );
};
+
+export const runBackgroundWorkerFromArgv = (argv: ReadonlyArray<string>) =>
+ Effect.gen(function* () {
+ const handledAnalytics = yield* runAnalyticsWorker(argv);
+ if (!handledAnalytics) {
+ yield* runCodactFailureWorker(argv);
+ }
+ }).pipe(Effect.catchAllCause(() => Effect.void));
diff --git a/ts/packages/cli/src/analytics/events.ts b/ts/packages/cli/src/analytics/events.ts
index 213c2b1f1..a35e7bf62 100644
--- a/ts/packages/cli/src/analytics/events.ts
+++ b/ts/packages/cli/src/analytics/events.ts
@@ -338,12 +338,15 @@ const isGenericOnlyCommand = (commandPath: string): boolean =>
export const createCliCommandTelemetryContext = (
argv: ReadonlyArray<string>,
- cliVersion: string
+ cliVersion: string,
+ terminal: { readonly stdoutIsTTY: boolean; readonly stderrIsTTY: boolean }
): CliCommandTelemetryContext => ({
argv,
cliVersion,
commandPath: extractCommandPath(argv),
flagNames: extractFlagNames(argv),
+ stdoutIsTTY: terminal.stdoutIsTTY,
+ stderrIsTTY: terminal.stderrIsTTY,
startedAt: Date.now(),
runId:
extractCommandPath(argv) === 'run'
@@ -360,8 +363,8 @@ const getCliCommandInvokedEvent = (context: CliCommandTelemetryContext): TrackEv
command_path: context.commandPath,
flag_names: context.flagNames,
arg_count: Math.max(0, context.argv.length - 2),
- stdout_is_tty: Boolean(process.stdout.isTTY),
- stderr_is_tty: Boolean(process.stderr.isTTY),
+ stdout_is_tty: context.stdoutIsTTY,
+ stderr_is_tty: context.stderrIsTTY,
},
});
diff --git a/ts/packages/cli/src/analytics/types.ts b/ts/packages/cli/src/analytics/types.ts
index d43f51b0b..2535700d6 100644
--- a/ts/packages/cli/src/analytics/types.ts
+++ b/ts/packages/cli/src/analytics/types.ts
@@ -17,6 +17,8 @@ export type CliCommandTelemetryContext = {
readonly cliVersion: string;
readonly commandPath: string;
readonly flagNames: ReadonlyArray<string>;
+ readonly stdoutIsTTY: boolean;
+ readonly stderrIsTTY: boolean;
readonly startedAt: number;
readonly runId?: string;
};
diff --git a/ts/packages/cli/src/bin.ts b/ts/packages/cli/src/bin.ts
index 13dc24ddc..b133c185a 100644
--- a/ts/packages/cli/src/bin.ts
+++ b/ts/packages/cli/src/bin.ts
@@ -1,5 +1,10 @@
import process from 'node:process';
+import { Effect, Layer } from 'effect';
+import { FetchHttpClient } from '@effect/platform';
+import { BunFileSystem, BunPath, BunRuntime } from '@effect/platform-bun';
import { isBackgroundWorkerInvocation, runBackgroundWorkerFromArgv } from 'src/analytics/dispatch';
+import { NodeOs } from 'src/services/node-os';
+import { TerminalUILive } from 'src/services/terminal-ui';
const TELEMETRY_DEBUG_FLAG = '--telemetry-debug';
const CLI_TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';
@@ -12,14 +17,29 @@ const stripTelemetryDebugFlag = (argv: ReadonlyArray<string>): string[] => {
}
normalizedArgv.splice(flagIndex, 1);
+ // Bootstrap runs before the Effect runtime and ConfigProvider exist; the stripped flag is
+ // persisted as an env var so later effect/Config reads and child processes observe it.
process.env[CLI_TELEMETRY_DEBUG_ENV_VAR] = 'true';
return normalizedArgv;
};
if (isBackgroundWorkerInvocation(process.argv)) {
- void runBackgroundWorkerFromArgv(process.argv).finally(() => {
- process.exit(0);
- });
+ runBackgroundWorkerFromArgv(process.argv).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ BunFileSystem.layer,
+ BunPath.layer,
+ FetchHttpClient.layer,
+ NodeOs.Default,
+ TerminalUILive
+ )
+ ),
+ effect =>
+ BunRuntime.runMain(effect, {
+ disableErrorReporting: true,
+ teardown: (_exit, onExit) => onExit(0),
+ })
+ );
} else {
process.argv = stripTelemetryDebugFlag(process.argv);
void import('./cli-main');
diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.ts
index f6530783e..550f44ed8 100644
--- a/ts/packages/cli/src/cli-main.ts
+++ b/ts/packages/cli/src/cli-main.ts
@@ -1,5 +1,5 @@
import process from 'node:process';
-import { Cause, Console, Effect, Exit, HashMap, Layer, Logger, Option } from 'effect';
+import { Cause, Effect, Exit, HashMap, Layer, Logger, Option } from 'effect';
import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
import { CliConfig, CommandDescriptor, HelpDoc, Usage, ValidationError } from '@effect/cli';
import { FetchHttpClient } from '@effect/platform';
@@ -36,14 +36,14 @@ import {
getPrimaryLifecycleInvokedEvent,
getPrimaryLifecycleSucceededEvent,
} from 'src/analytics/events';
-import { trackCliEvent, trackCliEventEffect } from 'src/analytics/dispatch';
+import { trackCliEventEffect } from 'src/analytics/dispatch';
import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
import { SetupCommandError } from 'src/services/setup';
-import { canRenderTerminalDecoration } from 'src/utils/stdio';
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-type RequiredLayer = Layer.Layer<any, any, never>;
+// Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any
+// produced context and error type while still pinning the requirements (RIn) to `never`.
+type RequiredLayer = Layer.Layer<never, unknown, never>;
export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies RequiredLayer;
@@ -74,7 +74,7 @@ export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
export const UpgradeBinaryLive = Layer.provide(
UpgradeBinary.Default,
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, FetchHttpClient.layer)
+ Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
) satisfies RequiredLayer;
export const TriggersRealtimeLive = Layer.provide(
@@ -94,7 +94,7 @@ export const ToolsExecutorLive = Layer.provide(
export const ProjectContextLive = Layer.provide(
ProjectContext.Default,
- Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, NodeProcess.Default)
+ Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
) satisfies RequiredLayer;
export const SetupSkillInstallerLive = Layer.provide(
@@ -140,14 +140,6 @@ const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) sati
unknown
>;
-const commandTelemetryContext = createCliCommandTelemetryContext(
- process.argv,
- constants.APP_VERSION
-);
-if (commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId) {
- process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;
-}
-
const collectValueOptionNamesFromUsage = (usage: Usage.Usage, acc: Set<string>) => {
switch (usage._tag) {
case 'Named': {
@@ -195,23 +187,44 @@ const collectValueOptionNames = (rootCommand: ReturnType<typeof buildRootCommand
return names;
};
-showUpdateNotice();
-checkForUpdateInBackground();
-trackCliEvent(getPrimaryLifecycleInvokedEvent(commandTelemetryContext));
+const runWithTelemetry = Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const terminal = yield* ui.capabilities;
+ const commandTelemetryContext = createCliCommandTelemetryContext(
+ process.argv,
+ constants.APP_VERSION,
+ terminal
+ );
+ if (commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId) {
+ // effect/Config is read-only; the run id must be written into the environment so the run
+ // command and the child processes it spawns observe the same telemetry run id.
+ process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;
+ }
-runWithArgs.pipe(
- Effect.scoped,
- Effect.mapError(error =>
- ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
- ),
- Effect.tap(() => trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))),
- Effect.tapErrorCause(cause =>
- trackCliEventEffect(
- getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
+ return yield* trackCliEventEffect(getPrimaryLifecycleInvokedEvent(commandTelemetryContext)).pipe(
+ Effect.andThen(runWithArgs),
+ Effect.scoped,
+ Effect.mapError(error =>
+ ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
+ ),
+ Effect.tap(() =>
+ trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))
+ ),
+ Effect.tapErrorCause(cause =>
+ trackCliEventEffect(
+ getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
+ )
)
- ),
+ );
+});
+
+checkForUpdateInBackground();
+
+showUpdateNotice.pipe(
+ Effect.andThen(runWithTelemetry),
Effect.catchIf(ValidationError.isValidationError, error => {
return Effect.gen(function* () {
+ const ui = yield* TerminalUI;
const cliUserConfig = yield* ComposioCliUserConfig;
const visibility = {
isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
@@ -220,15 +233,15 @@ runWithArgs.pipe(
};
const valueOptionNames = collectValueOptionNames(buildRootCommand(visibility));
const text = HelpDoc.toAnsiText(error.error).trim();
- const errorEffect = text.length > 0 ? Console.error(text) : Effect.void;
+ const errorEffect = text.length > 0 ? ui.error(text) : Effect.void;
const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);
const tipEffect =
flagMatch && valueOptionNames.has(flagMatch[1])
- ? Console.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)
+ ? ui.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)
: Effect.void;
const cmdName = matchCommandFromArgv(process.argv, visibility);
const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
- const helpEffect = helpText ? Console.error(helpText) : Effect.void;
+ const helpEffect = helpText ? ui.error(helpText) : Effect.void;
return yield* Effect.all([errorEffect, tipEffect, helpEffect], { discard: true }).pipe(
Effect.tap(() =>
Effect.sync(() => {
@@ -247,11 +260,11 @@ runWithArgs.pipe(
error.operation === 'uninstall'
? 'Composio plugin uninstall was unsuccessful.'
: 'Composio setup was unsuccessful.';
- if (canRenderTerminalDecoration()) {
+ if ((yield* ui.capabilities).canDecorate) {
yield* ui.log.error(error.message);
yield* ui.outro(summary);
} else {
- yield* Console.error(`${summary} ${error.message}`);
+ yield* ui.error(`${summary} ${error.message}`);
}
process.exitCode = 1;
})
@@ -281,7 +294,8 @@ runWithArgs.pipe(
}
).trim();
if (message.length > 0) {
- yield* Console.error(message);
+ const ui = yield* TerminalUI;
+ yield* ui.error(message);
const cliUserConfig = yield* ComposioCliUserConfig;
const visibility = {
isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
@@ -291,7 +305,7 @@ runWithArgs.pipe(
const cmdName = matchCommandFromArgv(process.argv, visibility);
const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
if (helpText) {
- yield* Console.error(helpText);
+ yield* ui.error(helpText);
}
process.exitCode = 1;
}
diff --git a/ts/packages/cli/src/commands/artifacts.cmd.ts b/ts/packages/cli/src/commands/artifacts.cmd.ts
index 0b47114e5..b69971095 100644
--- a/ts/packages/cli/src/commands/artifacts.cmd.ts
+++ b/ts/packages/cli/src/commands/artifacts.cmd.ts
@@ -1,20 +1,21 @@
-import process from 'node:process';
import { Command } from '@effect/cli';
import { Effect, Option } from 'effect';
import {
resolveArtifactsRoot,
resolveCliSessionArtifacts,
} from 'src/services/cli-session-artifacts';
+import { TerminalUI } from 'src/services/terminal-ui';
const cwdCmd = Command.make('cwd').pipe(
Command.withDescription('Print the cwd-scoped session artifact directory.'),
Command.withHandler(() =>
Effect.gen(function* () {
+ const ui = yield* TerminalUI;
const artifacts = yield* resolveCliSessionArtifacts();
const directoryPath = Option.isSome(artifacts)
? artifacts.value.directoryPath
: yield* resolveArtifactsRoot;
- process.stdout.write(`${directoryPath}\n`);
+ yield* ui.output(directoryPath, { force: true });
})
)
);
diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.ts
index d7b6bd839..3abebdc99 100644
--- a/ts/packages/cli/src/commands/index.ts
+++ b/ts/packages/cli/src/commands/index.ts
@@ -541,6 +541,7 @@ export const runWithConfig = Effect.gen(function* () {
}
if (isGenerateGraph(normalizedArgv)) {
return Effect.sync(() => {
+ // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
process.stdout.write(`${JSON.stringify(renderCommandHintGraph(), null, 2)}\n`);
});
}
@@ -565,6 +566,7 @@ export const runWithConfig = Effect.gen(function* () {
Effect.option
);
return yield* Effect.sync(() => {
+ // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
process.stdout.write(
`${JSON.stringify(
{
@@ -584,6 +586,7 @@ export const runWithConfig = Effect.gen(function* () {
}
if (isDebugWhoIsMyMaster(normalizedArgv)) {
return Effect.sync(() => {
+ // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
process.stdout.write(`${JSON.stringify({ master: detectMaster() }, null, 2)}\n`);
});
}
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index 701082374..fb4872ca4 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -21,7 +21,6 @@ import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/co
import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
import { APP_VERSION } from 'src/constants';
-import { isInteractiveTerminal } from 'src/utils/stdio';
import {
ensureAgentSignupAllowed,
getOrSignupReadyAgent,
@@ -612,7 +611,7 @@ export const browserLogin = (params: {
expiresAt,
});
- const canPrompt = isInteractiveTerminal();
+ const canPrompt = (yield* ui.capabilities).isInteractive;
const effectiveNoWait = params.noWait || !canPrompt;
const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
@@ -782,7 +781,7 @@ export const loginCmd = Command.make(
Effect.gen(function* () {
const ui = yield* TerminalUI;
const ctx = yield* ComposioUserContext;
- const canPrompt = isInteractiveTerminal();
+ const canPrompt = (yield* ui.capabilities).isInteractive;
if (canPrompt) {
yield* ui.intro('composio login');
diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.ts
index 94482e56a..54a7f1ae4 100644
--- a/ts/packages/cli/src/commands/root-help.ts
+++ b/ts/packages/cli/src/commands/root-help.ts
@@ -1,5 +1,6 @@
-import { Console, Effect, Option } from 'effect';
+import { Effect, Option } from 'effect';
import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
+import { TerminalUI } from 'src/services/terminal-ui';
import { bold, dim, gray } from 'src/ui/colors';
import {
type CommandVisibility,
@@ -1406,11 +1407,19 @@ export function printSubcommandHelp(
cmd: string,
visibility: CommandVisibility,
helpLevel: HelpLevel = 'default'
-): Effect.Effect<void> {
- if (cmd === 'dev') return Console.log(renderDevHelp(visibility, helpLevel));
+): Effect.Effect<void, never, TerminalUI> {
+ if (cmd === 'dev') {
+ return Effect.flatMap(TerminalUI, ui =>
+ ui.output(renderDevHelp(visibility, helpLevel), { force: true })
+ );
+ }
const help = getVisibleSubcommandHelp(cmd, visibility, helpLevel);
- if (Option.isNone(help)) return Console.log(`Unknown command: ${cmd}`);
- return Console.log(renderSubcommandHelp(help.value, helpLevel));
+ if (Option.isNone(help)) {
+ return Effect.flatMap(TerminalUI, ui => ui.output(`Unknown command: ${cmd}`, { force: true }));
+ }
+ return Effect.flatMap(TerminalUI, ui =>
+ ui.output(renderSubcommandHelp(help.value, helpLevel), { force: true })
+ );
}
/**
@@ -1452,7 +1461,7 @@ export function getCommandHelpText(cmd: string, visibility: CommandVisibility):
export function printRootHelp(
visibility: CommandVisibility,
helpLevel: HelpLevel = 'default'
-): Effect.Effect<void> {
+): Effect.Effect<void, never, TerminalUI> {
const name = 'composio';
const developerCommands: ReadonlyArray<CompactCommand> = [
{
@@ -1584,5 +1593,5 @@ export function printRootHelp(
'',
];
- return Console.log(lines.join('\n'));
+ return Effect.flatMap(TerminalUI, ui => ui.output(lines.join('\n'), { force: true }));
}
diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.ts
index d2f493c36..8ef2f96b4 100644
--- a/ts/packages/cli/src/commands/run.cmd.ts
+++ b/ts/packages/cli/src/commands/run.cmd.ts
@@ -24,6 +24,7 @@ import {
resolveCliSessionArtifacts,
} from 'src/services/cli-session-artifacts';
import { USER_COMPOSIO_DIR } from 'src/constants';
+import { TerminalUI } from 'src/services/terminal-ui';
const file = Options.text('file').pipe(
Options.withAlias('f'),
@@ -471,6 +472,7 @@ export const runCmd = Command.make('run', {
helperContext,
runHelperModuleUrls
);
+ const ui = yield* TerminalUI;
let cleanupPaths: ReadonlyArray<string> = [];
try {
yield* appendCliSessionHistory({
@@ -484,7 +486,7 @@ export const runCmd = Command.make('run', {
debug,
},
}).pipe(Effect.catchAll(() => Effect.void));
- process.stderr.write(`RUN_LOG_FILE=${preload.runLogFilePath}\n`);
+ yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
const runCommand = buildRunCommand({
path,
file,
diff --git a/ts/packages/cli/src/commands/setup.cmd.ts b/ts/packages/cli/src/commands/setup.cmd.ts
index 4210e07ba..fa58e61bd 100644
--- a/ts/packages/cli/src/commands/setup.cmd.ts
+++ b/ts/packages/cli/src/commands/setup.cmd.ts
@@ -14,7 +14,6 @@ import {
} from 'src/services/setup';
import { TerminalUI } from 'src/services/terminal-ui';
import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
-import { isInteractiveTerminal } from 'src/utils/stdio';
const target = Options.choice('target', SETUP_TARGETS).pipe(
Options.withDefault('auto' as SetupTarget),
@@ -146,7 +145,7 @@ const setupBaseCmd = Command.make(
}
if (!yes && removable.length > 0) {
- if (!isInteractiveTerminal()) {
+ if (!(yield* ui.capabilities).isInteractive) {
return yield* Effect.fail(
new Error('Non-interactive uninstall requires `--yes` to approve local changes.')
);
@@ -186,7 +185,7 @@ const setupBaseCmd = Command.make(
const pendingPlugins = pending.filter(status => !isSetupPluginReady(status));
if (!yes) {
- if (!isInteractiveTerminal()) {
+ if (!(yield* ui.capabilities).isInteractive) {
return yield* Effect.fail(
new Error('Non-interactive setup requires `--yes` to approve local changes.')
);
diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
index 4b3976c2f..2cad132dc 100644
--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
@@ -342,6 +342,7 @@ const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirecto
const perfDebugEpoch = Date.now();
const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {
if (!isPerfDebugEnabled()) return;
+ // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
process.stderr.write(
`[perf] ${JSON.stringify({
phase: 'event',
@@ -353,6 +354,7 @@ const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {
};
const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {
if (!isToolDebugEnabled()) return;
+ // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
process.stderr.write(`[tool-debug] ${JSON.stringify({ label, ...details })}\n`);
};
diff --git a/ts/packages/cli/src/services/command-runner.ts b/ts/packages/cli/src/services/command-runner.ts
index d07343a87..eb3e8a229 100644
--- a/ts/packages/cli/src/services/command-runner.ts
+++ b/ts/packages/cli/src/services/command-runner.ts
@@ -16,9 +16,13 @@ export class CommandRunner extends Effect.Service<CommandRunner>()('services/Com
capture: (command: Command.Command) =>
Effect.scoped(
Effect.gen(function* () {
- const process = yield* Command.start(command);
+ const childProcess = yield* Command.start(command);
const [exitCode, stdout, stderr] = yield* Effect.all(
- [process.exitCode, collectText(process.stdout), collectText(process.stderr)],
+ [
+ childProcess.exitCode,
+ collectText(childProcess.stdout),
+ collectText(childProcess.stderr),
+ ],
{ concurrency: 'unbounded' }
);
return { exitCode: Number(exitCode), stdout, stderr } satisfies CommandResult;
diff --git a/ts/packages/cli/src/services/composio-clients.ts b/ts/packages/cli/src/services/composio-clients.ts
index 0723fdd8b..678c96257 100644
--- a/ts/packages/cli/src/services/composio-clients.ts
+++ b/ts/packages/cli/src/services/composio-clients.ts
@@ -13,6 +13,7 @@ import {
SynchronizedRef,
} from 'effect';
import { Composio as _RawComposioClient, APIPromise } from '@composio/client';
+import { FileSystem, Path } from '@effect/platform';
import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
import {
@@ -36,6 +37,7 @@ import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigg
import * as constants from 'src/constants';
import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
import { ComposioUserContext, ComposioUserContextLive } from './user-context';
+import { NodeOs } from './node-os';
import { ProjectContext } from './project-context';
import type { NoSuchElementException } from 'effect/Cause';
import { renderPrettyError } from './utils/pretty-error';
@@ -1338,8 +1340,8 @@ const buildDefaultHeaders = (params: {
userApiKey?: string;
orgId?: string;
projectId?: string;
+ cliSessionId?: string;
}): Record<string, string> | undefined => {
- const cliSessionId = getCurrentCwdSessionId();
const defaultHeaders = {
'x-framework': 'cli',
'x-source': 'CLI',
@@ -1354,8 +1356,8 @@ const buildDefaultHeaders = (params: {
'x-project-id': params.projectId,
} satisfies Record<string, string>)
: {}),
- ...(cliSessionId
- ? ({ 'x-cli-session-id': cliSessionId } satisfies Record<string, string>)
+ ...(params.cliSessionId
+ ? ({ 'x-cli-session-id': params.cliSessionId } satisfies Record<string, string>)
: {}),
};
@@ -1520,6 +1522,9 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
effect: Effect.gen(function* () {
const ctx = yield* ComposioUserContext;
const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const os = yield* NodeOs;
const cache = new Map<string, _RawComposioClient>();
const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
@@ -1537,6 +1542,12 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
return cached;
}
+ const cliSessionId = yield* getCurrentCwdSessionId().pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ Effect.provideService(NodeOs, os)
+ );
+
const client = new _RawComposioClient({
apiKey: null,
baseURL: ctx.data.baseURL,
@@ -1544,6 +1555,7 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
userApiKey: apiKey,
orgId: params?.orgId,
projectId: params?.projectId,
+ cliSessionId,
}),
});
diff --git a/ts/packages/cli/src/services/run-helpers-runtime.ts b/ts/packages/cli/src/services/run-helpers-runtime.ts
index db02429af..019f52a70 100644
--- a/ts/packages/cli/src/services/run-helpers-runtime.ts
+++ b/ts/packages/cli/src/services/run-helpers-runtime.ts
@@ -326,6 +326,7 @@ export const installRunHelpers = async ({
const line = formattedLine ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`;
appendRunLogLine(line);
if (shouldStreamHelperLog(step, formattedLine)) {
+ // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
process.stderr.write(`${line}\n`);
}
};
diff --git a/ts/packages/cli/src/services/run-subagent-output-mcp.ts b/ts/packages/cli/src/services/run-subagent-output-mcp.ts
index bb9febbab..f834c121e 100644
--- a/ts/packages/cli/src/services/run-subagent-output-mcp.ts
+++ b/ts/packages/cli/src/services/run-subagent-output-mcp.ts
@@ -57,6 +57,7 @@ const main = async (): Promise<void> => {
void main().catch(error => {
const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
+ // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
process.stderr.write(`${message}\n`);
process.exit(1);
});
diff --git a/ts/packages/cli/src/services/runtime-debug-logger.ts b/ts/packages/cli/src/services/runtime-debug-logger.ts
new file mode 100644
index 000000000..2fbeeffe3
--- /dev/null
+++ b/ts/packages/cli/src/services/runtime-debug-logger.ts
@@ -0,0 +1,28 @@
+import { Effect } from 'effect';
+import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
+import { TerminalUI } from 'src/services/terminal-ui';
+
+const writeJsonDebugLine = (channel: string, payload: Record<string, unknown>) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ yield* ui.error(`[${channel}] ${JSON.stringify(payload)}`);
+ });
+
+export const logToolDebug = (label: string, details: Record<string, unknown> = {}) =>
+ Effect.suspend(() =>
+ isToolDebugEnabled() ? writeJsonDebugLine('tool-debug', { label, ...details }) : Effect.void
+ );
+
+export const makePerfDebugLogger =
+ (startedAt: number = Date.now()) =>
+ (label: string, details: Record<string, unknown> = {}) =>
+ Effect.suspend(() =>
+ isPerfDebugEnabled()
+ ? writeJsonDebugLine('perf', {
+ phase: 'event',
+ label,
+ elapsedMs: Date.now() - startedAt,
+ ...details,
+ })
+ : Effect.void
+ );
diff --git a/ts/packages/cli/src/services/terminal-ui.ts b/ts/packages/cli/src/services/terminal-ui.ts
index 433f7436f..dfd7c7a65 100644
--- a/ts/packages/cli/src/services/terminal-ui.ts
+++ b/ts/packages/cli/src/services/terminal-ui.ts
@@ -1,7 +1,39 @@
import process from 'node:process';
import * as p from '@clack/prompts';
import { Context, Effect, Exit, Layer } from 'effect';
-import { canRenderTerminalDecoration, isInteractiveTerminal } from 'src/utils/stdio';
+
+export type TtyLikeStream = {
+ readonly isTTY?: boolean;
+};
+
+export type TerminalStdio = {
+ readonly stdin: TtyLikeStream;
+ readonly stdout: TtyLikeStream;
+ readonly stderr: TtyLikeStream;
+};
+
+export type TerminalCapabilities = {
+ readonly stdinIsTTY: boolean;
+ readonly stdoutIsTTY: boolean;
+ readonly stderrIsTTY: boolean;
+ readonly isInteractive: boolean;
+ readonly canDecorate: boolean;
+};
+
+/** Classify terminal streams without coupling callers or tests to Node globals. */
+export const getTerminalCapabilities = (stdio: TerminalStdio): TerminalCapabilities => {
+ const stdinIsTTY = Boolean(stdio.stdin.isTTY);
+ const stdoutIsTTY = Boolean(stdio.stdout.isTTY);
+ const stderrIsTTY = Boolean(stdio.stderr.isTTY);
+
+ return {
+ stdinIsTTY,
+ stdoutIsTTY,
+ stderrIsTTY,
+ isInteractive: stdinIsTTY && stdoutIsTTY && stderrIsTTY,
+ canDecorate: stderrIsTTY,
+ };
+};
// ---------------------------------------------------------------------------
// SpinnerHandle — returned by `useMakeSpinner` for manual control
@@ -21,6 +53,9 @@ export interface SpinnerHandle {
// ---------------------------------------------------------------------------
export interface TerminalUI {
+ /** Capabilities of the streams backing this terminal service. */
+ readonly capabilities: Effect.Effect<TerminalCapabilities>;
+
/**
* Write raw data to stdout for piping and scripting.
*
@@ -33,6 +68,14 @@ export interface TerminalUI {
*/
readonly output: (data: string, options?: { readonly force?: boolean }) => Effect.Effect<void>;
+ /**
+ * Write an unformatted line to stderr even when stderr is redirected.
+ *
+ * Use this for diagnostics and protocol metadata that must survive piping.
+ * Human-facing decoration belongs in `log`, `note`, `intro`, or `outro`.
+ */
+ readonly error: (data: string) => Effect.Effect<void>;
+
/** Display a session start marker (e.g., `┌ title`). Writes to stderr. */
readonly intro: (title: string) => Effect.Effect<void>;
/** Display a session end marker (e.g., `└ message`). Writes to stderr. */
@@ -116,14 +159,20 @@ export const TerminalUI = Context.GenericTag<TerminalUI>('services/TerminalUI');
* when stdin/stdout/stderr are all TTYs; agent and shell pipelines get
* non-interactive behavior.
*/
-const canPrompt = isInteractiveTerminal();
+const liveCapabilities = getTerminalCapabilities({
+ stdin: process.stdin,
+ stdout: process.stdout,
+ stderr: process.stderr,
+});
+
+const canPrompt = liveCapabilities.isInteractive;
/**
* Whether the CLI can render auxiliary UI. Logs, notes, and spinners only need
* stderr, so they can still be shown when stdin is redirected from /dev/null or
* stdout is reserved for machine-readable JSON/data.
*/
-const canDecorate = canRenderTerminalDecoration();
+const canDecorate = liveCapabilities.canDecorate;
/** Run a decoration side-effect only when stderr is a terminal. */
function decorate(fn: () => void): void {
@@ -161,6 +210,8 @@ const silentSpinnerHandle: SpinnerHandle = {
};
const makeLive: TerminalUI = {
+ capabilities: Effect.succeed(liveCapabilities),
+
output: (data, options) =>
Effect.sync(() => {
if (options?.force || !canPrompt) {
@@ -168,6 +219,8 @@ const makeLive: TerminalUI = {
}
}),
+ error: data => Effect.sync(() => process.stderr.write(`${data}\n`)),
+
intro: title => Effect.sync(() => decorate(() => p.intro(title, { output: process.stderr }))),
outro: message => Effect.sync(() => decorate(() => p.outro(message, { output: process.stderr }))),
@@ -199,8 +252,7 @@ const makeLive: TerminalUI = {
? Effect.promise(async () => {
const result = await p.select({
message,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- options: [...options] as any,
+ options: [...options],
output: process.stderr,
});
// p.select returns Value | symbol (symbol on cancel)
diff --git a/ts/packages/cli/src/services/update-check.ts b/ts/packages/cli/src/services/update-check.ts
index c448adb5c..221f4d69c 100644
--- a/ts/packages/cli/src/services/update-check.ts
+++ b/ts/packages/cli/src/services/update-check.ts
@@ -1,26 +1,20 @@
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
-import { readFileSync, mkdirSync } from 'node:fs';
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
-import { writeFile } from 'node:fs/promises';
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
-import { arch as getArch, homedir, platform as getPlatform } from 'node:os';
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
-import { dirname, join } from 'node:path';
+import { FileSystem, Path } from '@effect/platform';
+import { BunFileSystem } from '@effect/platform-bun';
+import { Config, Data, Effect, Layer, Option, Predicate, Schema } from 'effect';
import semver from 'semver';
import { bold, cyanBright, dim } from 'src/ui/colors';
import { APP_VERSION, GITHUB_REPO } from '../constants';
-import { isInteractiveTerminal } from 'src/utils/stdio';
-// The sync bridge keeps this pre-migration module working until the
-// typed-error slice (PR 8 of this stack) makes it Effect-native.
-import { resolveInstalledCliVersionSync } from './run-companion-modules';
+import { NodeOs } from './node-os';
+import { resolveInstalledCliVersion } from './run-companion-modules';
+import { TerminalUI } from './terminal-ui';
/**
* Background update check for @composio/cli.
*
- * Two entry points, both called synchronously from bin.ts BEFORE the Effect
- * runtime boots — they must never block or throw:
+ * Two entry points, both called from cli-main BEFORE the root command's
+ * Effect runtime boots — they must never block or throw:
*
- * showUpdateNotice() — sync file read (~1 ms)
+ * showUpdateNotice — reads a tiny cached JSON file (~1 ms)
* checkForUpdateInBackground() — fire-and-forget fetch, no await
*
* Strategy:
@@ -34,18 +28,23 @@ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
/** Matches `@composio/cli@<semver>` — excludes prereleases. */
const CLI_RELEASE_TAG_RE = /^@composio\/cli@(\d+\.\d+\.\d+)$/;
-export interface UpdateCheckRelease {
- tag_name?: unknown;
- prerelease?: unknown;
- draft?: unknown;
- assets?: unknown;
-}
-
export interface UpdateCheckState {
lastChecked: string; // ISO-8601
latestVersion: string; // e.g. "0.3.0"
}
+const UpdateCheckStateSchema = Schema.parseJson(
+ Schema.Struct({
+ lastChecked: Schema.String,
+ latestVersion: Schema.String,
+ })
+);
+
+/** Non-2xx response from the GitHub releases API; swallowed after the state write. */
+class UpdateCheckHttpError extends Data.TaggedError('UpdateCheckHttpError')<{
+ readonly status: number;
+}> {}
+
// ── Injectable configuration ────────────────────────────────────────────
/** Dependencies injected into the update checker — mirrors the Effect service pattern. */
@@ -57,14 +56,17 @@ export interface UpdateCheckConfig {
readonly binaryAssetName: string | undefined;
readonly accessToken: string | undefined;
readonly fetchFn: (url: string, init?: RequestInit) => Promise<Response>;
- readonly isInteractive: () => boolean;
}
-const _home = join(homedir(), '.composio');
+const defaultStateFile = Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const os = yield* NodeOs;
+ return path.join(os.homedir, '.composio', 'update-check.json');
+});
-function getCurrentBinaryAssetName(): string | undefined {
- const platform = getPlatform();
- const rawArch: string = getArch();
+function getCurrentBinaryAssetName(os: Pick<NodeOs, 'platform' | 'arch'>): string | undefined {
+ const { platform } = os;
+ const rawArch: string = os.arch;
if (platform !== 'darwin' && platform !== 'linux') return undefined;
const arch = rawArch === 'arm64' || rawArch === 'aarch64' ? 'aarch64' : rawArch;
@@ -73,16 +75,25 @@ function getCurrentBinaryAssetName(): string | undefined {
return `composio-${platform}-${arch}.zip`;
}
-const defaultConfig: UpdateCheckConfig = {
- stateFile: join(_home, 'update-check.json'),
- currentVersion: resolveInstalledCliVersionSync(process.execPath, APP_VERSION),
- checkIntervalMs: CHECK_INTERVAL_MS,
- releasesUrl: `${GITHUB_REPO.API_BASE_URL}/repos/${GITHUB_REPO.OWNER}/${GITHUB_REPO.REPO}/releases?per_page=100`,
- binaryAssetName: getCurrentBinaryAssetName(),
- accessToken: process.env.COMPOSIO_GITHUB_ACCESS_TOKEN,
- fetchFn: fetch,
- isInteractive: isInteractiveTerminal,
-};
+const defaultConfig = (stateFile: string) =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const currentVersion = yield* resolveInstalledCliVersion(process.execPath, APP_VERSION);
+ const accessToken = yield* Effect.orDie(
+ Config.option(Config.string('COMPOSIO_GITHUB_ACCESS_TOKEN')).pipe(
+ Config.map(Option.getOrUndefined)
+ )
+ );
+ return {
+ stateFile,
+ currentVersion,
+ checkIntervalMs: CHECK_INTERVAL_MS,
+ releasesUrl: `${GITHUB_REPO.API_BASE_URL}/repos/${GITHUB_REPO.OWNER}/${GITHUB_REPO.REPO}/releases?per_page=100`,
+ binaryAssetName: getCurrentBinaryAssetName(os),
+ accessToken,
+ fetchFn: fetch,
+ } satisfies UpdateCheckConfig;
+ });
// ── Pure helpers ────────────────────────────────────────────────────────
@@ -95,19 +106,15 @@ export function parseLatestVersionFromReleases(
let latest: string | undefined;
for (const release of releases) {
- if (typeof release !== 'object' || release === null) continue;
+ if (!Predicate.isRecord(release)) continue;
- const candidate = release as UpdateCheckRelease;
+ const candidate = release;
if (typeof candidate.tag_name !== 'string') continue;
if (candidate.prerelease === true || candidate.draft === true) continue;
if (!Array.isArray(candidate.assets)) continue;
const hasRequiredBinary = candidate.assets.some(
- asset =>
- typeof asset === 'object' &&
- asset !== null &&
- 'name' in asset &&
- asset.name === binaryAssetName
+ asset => Predicate.hasProperty(asset, 'name') && asset.name === binaryAssetName
);
if (!hasRequiredBinary) continue;
@@ -126,15 +133,22 @@ export function parseLatestVersionFromReleases(
// ── Factory ─────────────────────────────────────────────────────────────
export function createUpdateChecker(config: UpdateCheckConfig) {
+ const readState = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const rawState = yield* fs.readFileString(config.stateFile);
+ return yield* Schema.decodeUnknown(UpdateCheckStateSchema)(rawState);
+ });
+
/**
* If a cached newer version is known, print a one-line hint to stderr.
- * Purely synchronous — reads a tiny JSON file and does a semver compare.
+ * Reads a tiny JSON file and does a semver compare.
*/
- function showUpdateNotice(): void {
- try {
- if (!config.isInteractive()) return;
+ function showUpdateNotice(terminal: Pick<TerminalUI, 'capabilities' | 'error'>) {
+ return Effect.gen(function* () {
+ const capabilities = yield* terminal.capabilities;
+ if (!capabilities.isInteractive) return;
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ const state = yield* readState;
if (!state.latestVersion || !semver.valid(state.latestVersion)) return;
if (state.latestVersion === config.currentVersion) return;
@@ -145,95 +159,103 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
` ${dim('Update available:')} ${dim(config.currentVersion)} ${dim('→')} ${bold(cyanBright(state.latestVersion))}\n` +
` ${dim('Run')} ${cyanBright('composio upgrade')} ${dim('to update')}\n`;
- process.stderr.write(`\n${msg}\n`);
- } catch {
- // Silently ignore — ENOENT, corrupt JSON, etc. Never block the CLI.
- }
+ yield* terminal.error(`\n${msg}`);
+ }).pipe(Effect.ignore);
}
/**
* Fetch the latest @composio/cli release from GitHub, requiring the current
* platform binary asset before writing the result to the state file.
*
- * Returns the internal promise so tests can await completion.
- * The public wrapper discards it (fire-and-forget).
+ * Never fails: every fetch/parse/write error is swallowed so nothing can
+ * propagate back into the fire-and-forget caller.
*/
- function checkForUpdate(): Promise<void> | undefined {
- try {
- // Throttle: skip if checked recently.
- let previousLatestVersion: string | undefined;
- try {
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- if (Date.now() - new Date(state.lastChecked).getTime() < config.checkIntervalMs) {
- return undefined;
- }
- previousLatestVersion = state.latestVersion;
- } catch {
- // ENOENT or corrupt file — re-check.
- }
+ const checkForUpdate = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
+ // Throttle: skip if checked recently. A missing or corrupt state file
+ // just means "re-check".
+ const cachedState = yield* Effect.option(readState);
+ if (
+ Option.isSome(cachedState) &&
+ Date.now() - new Date(cachedState.value.lastChecked).getTime() < config.checkIntervalMs
+ ) {
+ return;
+ }
+ const previousLatestVersion = Option.getOrUndefined(
+ Option.map(cachedState, state => state.latestVersion)
+ );
- const headers: Record<string, string> = {
- Accept: 'application/vnd.github.v3+json',
- 'User-Agent': `composio-cli/${config.currentVersion}`,
- };
+ const headers: Record<string, string> = {
+ Accept: 'application/vnd.github.v3+json',
+ 'User-Agent': `composio-cli/${config.currentVersion}`,
+ };
- if (config.accessToken) {
- headers.Authorization = `Bearer ${config.accessToken}`;
- }
+ if (config.accessToken) {
+ headers.Authorization = `Bearer ${config.accessToken}`;
+ }
- // Always persist lastChecked to prevent retry loops when the fetch
- // fails or returns no matching releases with a matching binary.
- const writeState = (latestVersion?: string): Promise<void> => {
- try {
- const stateDir = dirname(config.stateFile);
- mkdirSync(stateDir, { recursive: true });
- } catch {
+ // Always persist lastChecked to prevent retry loops when the fetch
+ // fails or returns no matching releases with a matching binary.
+ const writeState = (latestVersion?: string) =>
+ fs.makeDirectory(path.dirname(config.stateFile), { recursive: true }).pipe(
+ Effect.matchEffect({
// If we can't create the directory, bail out silently.
- return Promise.resolve();
- }
-
- const state: UpdateCheckState = {
- lastChecked: new Date().toISOString(),
- latestVersion: latestVersion ?? previousLatestVersion ?? config.currentVersion,
- };
-
- return writeFile(config.stateFile, JSON.stringify(state, null, 2)).then(() => {});
- };
-
- return config
- .fetchFn(config.releasesUrl, { headers, signal: AbortSignal.timeout(10_000) })
- .then(res => {
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
+ onFailure: () => Effect.void,
+ onSuccess: () => {
+ const state: UpdateCheckState = {
+ lastChecked: new Date().toISOString(),
+ latestVersion: latestVersion ?? previousLatestVersion ?? config.currentVersion,
+ };
+ return fs.writeFileString(config.stateFile, JSON.stringify(state, null, 2));
+ },
})
- .then((releases: unknown) => {
- const latestVersion = parseLatestVersionFromReleases(releases, config.binaryAssetName);
- return writeState(latestVersion);
- })
- .catch(() => {
- // Silently ignore fetch/parse errors — never block the CLI.
- // Still update the timestamp to prevent unbounded retry loops.
- return writeState().catch(() => {});
- });
- } catch {
- // Silently ignore.
- return undefined;
- }
- }
+ );
+
+ const fetchLatestVersion = Effect.gen(function* () {
+ const response = yield* Effect.tryPromise(() =>
+ config.fetchFn(config.releasesUrl, { headers, signal: AbortSignal.timeout(10_000) })
+ );
+ if (!response.ok) {
+ return yield* new UpdateCheckHttpError({ status: response.status });
+ }
+ const releases: unknown = yield* Effect.tryPromise(() => response.json());
+ return parseLatestVersionFromReleases(releases, config.binaryAssetName);
+ });
+
+ yield* fetchLatestVersion.pipe(
+ Effect.flatMap(writeState),
+ // Silently ignore fetch/parse errors — never block the CLI.
+ // Still update the timestamp to prevent unbounded retry loops.
+ Effect.catchAll(() => Effect.ignore(writeState()))
+ );
+ });
return { showUpdateNotice, checkForUpdate };
}
// ── Public API (production defaults, fire-and-forget) ───────────────────
-const _checker = createUpdateChecker(defaultConfig);
+const DefaultConfigLayers = Layer.mergeAll(Path.layer, NodeOs.Default, BunFileSystem.layer);
/** Print upgrade hint to stderr if a newer version is cached. */
-export function showUpdateNotice(): void {
- _checker.showUpdateNotice();
-}
+export const showUpdateNotice = Effect.gen(function* () {
+ const terminal = yield* TerminalUI;
+ const stateFile = yield* defaultStateFile;
+ const config = yield* defaultConfig(stateFile);
+ yield* createUpdateChecker(config).showUpdateNotice(terminal);
+}).pipe(Effect.provide(DefaultConfigLayers));
/** Fire-and-forget background fetch to GitHub. */
export function checkForUpdateInBackground(): void {
- _checker.checkForUpdate();
+ // Runs from cli-main before the runtime boots; runPromiseExit never throws back
+ // into the caller and checkForUpdate swallows its own failures.
+ void Effect.runPromiseExit(
+ Effect.gen(function* () {
+ const stateFile = yield* defaultStateFile;
+ const config = yield* defaultConfig(stateFile);
+ yield* createUpdateChecker(config).checkForUpdate;
+ }).pipe(Effect.provide(DefaultConfigLayers))
+ );
}
diff --git a/ts/packages/cli/src/utils/stdio.ts b/ts/packages/cli/src/utils/stdio.ts
deleted file mode 100644
index 2060a05df..000000000
--- a/ts/packages/cli/src/utils/stdio.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import process from 'node:process';
-
-export type TtyLikeStream = {
- readonly isTTY?: boolean;
-};
-
-export type InteractiveStdio = {
- readonly stdin?: TtyLikeStream;
- readonly stdout?: TtyLikeStream;
- readonly stderr?: TtyLikeStream;
-};
-
-const getStdio = (stdio: InteractiveStdio = {}) => ({
- stdin: stdio.stdin ?? process.stdin,
- stdout: stdio.stdout ?? process.stdout,
- stderr: stdio.stderr ?? process.stderr,
-});
-
-/**
- * True only when the CLI is attached to a human terminal for input, data output,
- * and decoration output. Agent/shell pipelines typically fail at least one of
- * these checks, so human-only prompts/notices should stay silent there.
- */
-export const isInteractiveTerminal = (stdio: InteractiveStdio = {}): boolean => {
- const { stdin, stdout, stderr } = getStdio(stdio);
-
- return Boolean(stdin.isTTY && stdout.isTTY && stderr.isTTY);
-};
-
-/**
- * True when stderr can render terminal decoration such as logs, notes, and
- * spinners. Unlike prompts/notices, decoration only needs stderr; stdout can
- * remain clean for JSON/data and stdin can be redirected from /dev/null.
- */
-export const canRenderTerminalDecoration = (stdio: InteractiveStdio = {}): boolean => {
- const { stderr } = getStdio(stdio);
-
- return Boolean(stderr.isTTY);
-};
diff --git a/ts/packages/cli/test/__utils__/http-server.ts b/ts/packages/cli/test/__utils__/http-server.ts
index 3a070e706..408ed9f7b 100644
--- a/ts/packages/cli/test/__utils__/http-server.ts
+++ b/ts/packages/cli/test/__utils__/http-server.ts
@@ -1,4 +1,5 @@
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
+import { Effect } from 'effect';
/**
* Spin up a local HTTP server on an ephemeral port, run the callback,
@@ -39,3 +40,46 @@ export async function withHttpServer(
});
}
}
+
+/**
+ * Effect variant of {@link withHttpServer}: the server lifecycle is managed
+ * with acquireUseRelease so `use` can be an Effect run by @effect/vitest.
+ */
+export function withHttpServerEffect<A, E, R>(
+ handler: (req: IncomingMessage, res: ServerResponse) => void,
+ use: (baseUrl: string) => Effect.Effect<A, E, R>
+): Effect.Effect<A, E, R> {
+ return Effect.acquireUseRelease(
+ Effect.promise(async () => {
+ const server = createServer(handler);
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen({ port: 0, host: '127.0.0.1' }, () => {
+ server.off('error', reject);
+ resolve();
+ });
+ });
+
+ const address = server.address();
+ if (address === null || typeof address === 'string') {
+ throw new Error('Failed to bind test server to an ephemeral port');
+ }
+
+ return { server, baseUrl: `http://127.0.0.1:${address.port}` };
+ }),
+ ({ baseUrl }) => use(baseUrl),
+ ({ server }) =>
+ Effect.promise(
+ () =>
+ new Promise<void>((resolve, reject) => {
+ server.close(error => {
+ if (error) {
+ reject(error);
+ return;
+ }
+ resolve();
+ });
+ })
+ )
+ );
+}
diff --git a/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts b/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
index 84dcea05d..3945988d7 100644
--- a/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
+++ b/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
@@ -10,7 +10,15 @@ import { TerminalUI } from 'src/services/terminal-ui';
export const TerminalUITest = Layer.succeed(
TerminalUI,
TerminalUI.of({
+ capabilities: Effect.succeed({
+ stdinIsTTY: false,
+ stdoutIsTTY: false,
+ stderrIsTTY: false,
+ isInteractive: false,
+ canDecorate: false,
+ }),
output: data => Console.log(data),
+ error: data => Console.error(data),
intro: title => Console.log(`-- ${title} --`),
outro: message => Console.log(`-- ${message} --`),
diff --git a/ts/packages/cli/test/src/analytics.dispatch.test.ts b/ts/packages/cli/test/src/analytics.dispatch.test.ts
new file mode 100644
index 000000000..917d9365e
--- /dev/null
+++ b/ts/packages/cli/test/src/analytics.dispatch.test.ts
@@ -0,0 +1,406 @@
+import { describe, expect, it } from '@effect/vitest';
+import { afterEach, beforeEach, vi } from 'vitest';
+import { FetchHttpClient, FileSystem, Path } from '@effect/platform';
+import { BunFileSystem, BunPath } from '@effect/platform-bun';
+import { Effect, Layer } from 'effect';
+import * as tempy from 'tempy';
+import {
+ getCurrentCwdSessionId,
+ readApiBaseUrl,
+ runBackgroundWorkerFromArgv,
+ trackCliCodactFailureEffect,
+ trackCliEventEffect,
+} from 'src/analytics/dispatch';
+import { APP_VERSION, USER_CONFIG_FILE_NAME } from 'src/constants';
+import { defaultNodeOs, NodeOs } from 'src/services/node-os';
+import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
+
+const childProcessMocks = vi.hoisted(() => ({
+ on: vi.fn(),
+ spawn: vi.fn(),
+ unref: vi.fn(),
+}));
+
+vi.mock('node:child_process', () => ({
+ spawn: childProcessMocks.spawn,
+}));
+
+const originalArgv = [...process.argv];
+
+const cwdHash = (cwd: string): string => {
+ let hash = 5381;
+ for (let index = 0; index < cwd.length; index += 1) {
+ hash = (hash * 33) ^ cwd.charCodeAt(index);
+ }
+ return Math.abs(hash >>> 0).toString(36);
+};
+
+const makePlatformLayer = (home: string) =>
+ Layer.mergeAll(
+ BunFileSystem.layer,
+ BunPath.layer,
+ FetchHttpClient.layer,
+ TerminalUITest,
+ Layer.succeed(NodeOs, defaultNodeOs({ homedir: home }))
+ );
+
+const enableTelemetry = (apiKey = 'uak_test') => {
+ vi.stubEnv('COMPOSIO_BASE_URL', 'https://backend.example.test');
+ vi.stubEnv('COMPOSIO_USER_API_KEY', apiKey);
+ vi.stubEnv('NODE_ENV', 'development');
+ vi.stubEnv('CI', 'false');
+ vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DISABLED', 'false');
+ vi.stubEnv('TELEMETRY_DISABLED', 'false');
+ vi.stubEnv('COMPOSIO_DISABLE_TELEMETRY', 'false');
+};
+
+const decodeWorkerPayload = <A>(encodedPayload: string): A => {
+ const normalized = encodedPayload.replace(/-/gu, '+').replace(/_/gu, '/');
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
+ return JSON.parse(atob(padded)) as A;
+};
+
+const encodeWorkerPayload = (payload: unknown): string =>
+ btoa(JSON.stringify(payload)).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
+
+describe('CLI analytics dispatch', () => {
+ beforeEach(() => {
+ const child = {
+ on: childProcessMocks.on,
+ unref: childProcessMocks.unref,
+ };
+ childProcessMocks.on.mockReset().mockReturnValue(child);
+ childProcessMocks.spawn.mockReset().mockReturnValue(child);
+ childProcessMocks.unref.mockReset();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ process.argv = [...originalArgv];
+ });
+
+ it.effect(
+ 'reads configuration and the freshest current-directory session via platform services',
+ () => {
+ const home = tempy.temporaryDirectory();
+ const cacheDir = tempy.temporaryDirectory();
+ const cwd = '/workspace/project';
+ vi.stubEnv('COMPOSIO_CACHE_DIR', cacheDir);
+ vi.stubEnv('COMPOSIO_BASE_URL', '');
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const composioDir = path.join(home, '.composio');
+ yield* fs.makeDirectory(composioDir, { recursive: true });
+ yield* fs.writeFileString(
+ path.join(composioDir, USER_CONFIG_FILE_NAME),
+ JSON.stringify({ base_url: 'https://backend.example.test///' })
+ );
+ yield* fs.writeFileString(
+ path.join(cacheDir, 'consumer-short-term-cache.json'),
+ JSON.stringify({
+ older: {
+ probablyMyCliSessionsByCwdHash: {
+ [cwdHash(cwd)]: {
+ id: 'cli_s_older',
+ // The TestClock sits at epoch 0, so these fixed instants are
+ // deterministically 30s and 60s in the future.
+ expiresAt: '1970-01-01T00:00:30.000Z',
+ },
+ },
+ },
+ newer: {
+ probablyMyCliSessionsByCwdHash: {
+ [cwdHash(cwd)]: {
+ id: 'cli_s_newer',
+ expiresAt: '1970-01-01T00:01:00.000Z',
+ },
+ },
+ },
+ })
+ );
+
+ expect(yield* readApiBaseUrl).toBe('https://backend.example.test');
+ expect(yield* getCurrentCwdSessionId(cwd)).toBe('cli_s_newer');
+ }).pipe(Effect.provide(makePlatformLayer(home)));
+ }
+ );
+
+ it.effect('ignores malformed worker payloads', () => {
+ const home = tempy.temporaryDirectory();
+
+ return runBackgroundWorkerFromArgv([
+ process.execPath,
+ 'composio',
+ '__analytics-worker',
+ 'not-base64',
+ ]).pipe(Effect.provide(makePlatformLayer(home)));
+ });
+
+ it.effect('delivers analytics worker payloads to the configured endpoint', () => {
+ const home = tempy.temporaryDirectory();
+ const envelope = {
+ event: 'cli_command_invoked',
+ sentAt: '2026-07-16T00:00:00.000Z',
+ source: 'cli' as const,
+ distinctId: 'anon_test',
+ installId: 'install_test',
+ };
+ const encodedPayload = btoa(JSON.stringify(envelope))
+ .replace(/\+/gu, '-')
+ .replace(/\//gu, '_')
+ .replace(/=+$/u, '');
+ vi.stubEnv('COMPOSIO_BASE_URL', 'https://backend.example.test');
+ vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_test');
+ vi.stubEnv('NODE_ENV', 'development');
+ vi.stubEnv('CI', 'false');
+ vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DISABLED', 'false');
+ vi.stubEnv('TELEMETRY_DISABLED', 'false');
+ vi.stubEnv('COMPOSIO_DISABLE_TELEMETRY', 'false');
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response(null, { status: 204 }));
+
+ return Effect.gen(function* () {
+ yield* runBackgroundWorkerFromArgv([
+ process.execPath,
+ 'composio',
+ '__analytics-worker',
+ encodedPayload,
+ ]).pipe(Effect.provide(makePlatformLayer(home)));
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [endpoint, request] = fetchSpy.mock.calls[0]!;
+ expect(String(endpoint)).toBe('https://backend.example.test/api/v3/cli/analytics');
+ expect(request).toMatchObject({
+ method: 'POST',
+ headers: expect.objectContaining({
+ 'content-type': 'application/json',
+ 'x-composio-analytics-source': 'cli',
+ 'x-user-api-key': 'uak_test',
+ }),
+ });
+ expect(JSON.parse(new TextDecoder().decode(request?.body as Uint8Array))).toEqual(envelope);
+ });
+ });
+
+ it.effect('spawns a detached analytics worker with a decodable envelope', () => {
+ const home = tempy.temporaryDirectory();
+ const scriptPath = `${home}/composio.ts`;
+ enableTelemetry();
+ process.argv[1] = scriptPath;
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.writeFileString(scriptPath, '');
+ yield* trackCliEventEffect({
+ name: 'producer_event',
+ properties: { sample: 'value' },
+ });
+
+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
+ const [command, args, options] = childProcessMocks.spawn.mock.calls[0] as unknown as [
+ string,
+ string[],
+ { detached: boolean; stdio: unknown },
+ ];
+ expect(command).toBe(process.execPath);
+ expect(args.slice(0, 2)).toEqual([scriptPath, '__analytics-worker']);
+ expect(args).toHaveLength(3);
+ expect(decodeWorkerPayload(args[2]!)).toMatchObject({
+ event: 'producer_event',
+ properties: { cli_version: APP_VERSION, sample: 'value' },
+ source: 'cli',
+ });
+ expect(options).toMatchObject({
+ detached: true,
+ stdio: 'ignore',
+ });
+ expect(options).not.toHaveProperty('env');
+ expect(childProcessMocks.on).toHaveBeenCalledWith('error', expect.any(Function));
+ expect(childProcessMocks.unref).toHaveBeenCalledTimes(1);
+ }).pipe(Effect.provide(makePlatformLayer(home)));
+ });
+
+ it.effect('spawns a detached codact worker with a decodable failure body', () => {
+ const home = tempy.temporaryDirectory();
+ const scriptPath = `${home}/composio.ts`;
+ enableTelemetry();
+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'agent');
+ vi.stubEnv('COMPOSIO_CLI_PARENT_RUN_ID', 'run_parent');
+ process.argv[1] = scriptPath;
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.writeFileString(scriptPath, '');
+ yield* trackCliCodactFailureEffect({
+ failureType: 'wrong_tool_input_param',
+ toolInfo: {
+ toolkit: 'github',
+ tool: { slug: 'GITHUB_CREATE_ISSUE', version: 'latest' },
+ },
+ ctx: { invalidKey: 'repo' },
+ requestId: 'req_producer',
+ });
+
+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
+ const [command, args, options] = childProcessMocks.spawn.mock.calls[0] as unknown as [
+ string,
+ string[],
+ { detached: boolean; stdio: unknown },
+ ];
+ expect(command).toBe(process.execPath);
+ expect(args.slice(0, 2)).toEqual([scriptPath, '__codact-failure-worker']);
+ expect(args).toHaveLength(3);
+ expect(decodeWorkerPayload(args[2]!)).toMatchObject({
+ failure_type: 'wrong_tool_input_param',
+ tool_info: {
+ toolkit: 'github',
+ tool: { slug: 'GITHUB_CREATE_ISSUE', version: 'latest' },
+ },
+ ctx: { invalidKey: 'repo' },
+ request_id: 'req_producer',
+ session: {
+ cli_version: APP_VERSION,
+ invocation_origin: 'agent',
+ parent_run_id: 'run_parent',
+ source: 'cli',
+ },
+ });
+ expect(options).toMatchObject({
+ detached: true,
+ stdio: 'ignore',
+ });
+ expect(options).not.toHaveProperty('env');
+ expect(childProcessMocks.on).toHaveBeenCalledWith('error', expect.any(Function));
+ expect(childProcessMocks.unref).toHaveBeenCalledTimes(1);
+ }).pipe(Effect.provide(makePlatformLayer(home)));
+ });
+
+ it.effect('keeps both producer effects non-fatal when spawn throws', () => {
+ const home = tempy.temporaryDirectory();
+ enableTelemetry();
+ childProcessMocks.spawn.mockImplementation(() => {
+ throw new Error('spawn failed');
+ });
+
+ return Effect.gen(function* () {
+ yield* trackCliEventEffect({ name: 'producer_event' });
+ yield* trackCliCodactFailureEffect({
+ failureType: 'wrong_tool_slug',
+ ctx: { slug: 'MISSING_TOOL' },
+ });
+
+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(2);
+ expect(childProcessMocks.unref).not.toHaveBeenCalled();
+ }).pipe(Effect.provide(makePlatformLayer(home)));
+ });
+
+ it.effect('honors Effect boolean config when telemetry is disabled', () => {
+ const home = tempy.temporaryDirectory();
+ enableTelemetry();
+ vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DISABLED', 'yes');
+
+ return Effect.gen(function* () {
+ yield* trackCliEventEffect({ name: 'producer_event' });
+ yield* trackCliCodactFailureEffect({
+ failureType: 'wrong_tool_slug',
+ ctx: { slug: 'MISSING_TOOL' },
+ });
+
+ expect(childProcessMocks.spawn).not.toHaveBeenCalled();
+ }).pipe(Effect.provide(makePlatformLayer(home)));
+ });
+
+ it.effect('delivers codact worker failures with the user key and session body', () => {
+ const home = tempy.temporaryDirectory();
+ const failureBody = {
+ failure_type: 'wrong_tool_input_param',
+ tool_info: {
+ toolkit: 'github',
+ tool: { slug: 'GITHUB_CREATE_ISSUE', version: 'latest' },
+ },
+ ctx: { invalidKey: 'repository' },
+ session: {
+ source: 'cli',
+ id: 'cli_s_worker',
+ cli_version: '0.3.0-test',
+ invocation_origin: 'agent',
+ parent_run_id: 'run_parent',
+ },
+ request_id: 'req_worker',
+ };
+ enableTelemetry('uak_worker');
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response(null, { status: 204 }));
+
+ return Effect.gen(function* () {
+ yield* runBackgroundWorkerFromArgv([
+ process.execPath,
+ 'composio',
+ '__codact-failure-worker',
+ encodeWorkerPayload(failureBody),
+ ]).pipe(Effect.provide(makePlatformLayer(home)));
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [endpoint, request] = fetchSpy.mock.calls[0]!;
+ expect(String(endpoint)).toBe('https://backend.example.test/api/v3/cli/codact_failures');
+ expect(request).toMatchObject({
+ method: 'POST',
+ headers: expect.objectContaining({
+ 'content-type': 'application/json',
+ 'x-user-api-key': 'uak_worker',
+ }),
+ });
+ expect(JSON.parse(new TextDecoder().decode(request?.body as Uint8Array))).toEqual(
+ failureBody
+ );
+ });
+ });
+
+ it.effect('ignores malformed codact worker payloads', () => {
+ const home = tempy.temporaryDirectory();
+ enableTelemetry();
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response(null, { status: 204 }));
+
+ return Effect.gen(function* () {
+ yield* runBackgroundWorkerFromArgv([
+ process.execPath,
+ 'composio',
+ '__codact-failure-worker',
+ 'not-base64',
+ ]).pipe(Effect.provide(makePlatformLayer(home)));
+
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ it.effect('skips codact worker delivery without a user key', () => {
+ const home = tempy.temporaryDirectory();
+ enableTelemetry('');
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response(null, { status: 204 }));
+ const failureBody = {
+ failure_type: 'wrong_tool_slug',
+ ctx: { slug: 'MISSING_TOOL' },
+ session: { source: 'cli' },
+ };
+
+ return Effect.gen(function* () {
+ yield* runBackgroundWorkerFromArgv([
+ process.execPath,
+ 'composio',
+ '__codact-failure-worker',
+ encodeWorkerPayload(failureBody),
+ ]).pipe(Effect.provide(makePlatformLayer(home)));
+
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/ts/packages/cli/test/src/analytics.events.test.ts b/ts/packages/cli/test/src/analytics.events.test.ts
index 5194ef7ad..862730f00 100644
--- a/ts/packages/cli/test/src/analytics.events.test.ts
+++ b/ts/packages/cli/test/src/analytics.events.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
import { createCliCodactFailureBody } from 'src/analytics/dispatch';
import {
+ createCliCommandTelemetryContext,
+ getPrimaryLifecycleInvokedEvent,
getToolExecuteFailedEvent,
getToolExecuteToolNotFoundEvent,
getToolExecuteValidationFailedEvent,
@@ -10,6 +12,20 @@ import {
import { ToolInputValidationError } from 'src/services/tool-input-validation';
describe('CLI analytics execute failure events', () => {
+ it('records terminal capabilities supplied by the terminal service', () => {
+ const context = createCliCommandTelemetryContext(['bun', 'composio'], '0.3.0', {
+ stdoutIsTTY: true,
+ stderrIsTTY: false,
+ });
+
+ const event = getPrimaryLifecycleInvokedEvent(context);
+
+ expect(event?.properties).toMatchObject({
+ stdout_is_tty: true,
+ stderr_is_tty: false,
+ });
+ });
+
it('marks cached-schema validation failures as fast_fail', () => {
const error = new ToolInputValidationError('GMAIL_SEND_EMAIL', '/tmp/schema.json', [
'Unknown key "recipient"',
diff --git a/ts/packages/cli/test/src/commands/$default.cmd.test.ts b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
index a7fe10659..877464d80 100644
--- a/ts/packages/cli/test/src/commands/$default.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
@@ -6,15 +6,11 @@ import { ValidationError, HelpDoc } from '@effect/cli';
import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';
import { afterEach, vi } from 'vitest';
-type CommandMismatchResult = {
- _tag: string;
- error: {
- _tag: string;
- value: {
- _tag: string;
- value: string;
- };
- };
+const getCommandMismatch = (value: unknown): ValidationError.CommandMismatch => {
+ if (!ValidationError.isValidationError(value) || !ValidationError.isCommandMismatch(value)) {
+ throw new Error('Expected a command mismatch');
+ }
+ return value;
};
describe('CLI: composio', () => {
@@ -28,15 +24,12 @@ describe('CLI: composio', () => {
const args = ['--bar'];
const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
- const commandMismatch = result as CommandMismatchResult;
-
- expect(result).toEqual(expect.any(Object));
- expect(commandMismatch._tag).toBe(ValidationError.commandMismatch(HelpDoc.p(''))._tag);
- expect(commandMismatch.error._tag).toBe('Paragraph');
- expect(commandMismatch.error.value._tag).toBe('Text');
- expect(commandMismatch.error.value.value).toContain('Invalid subcommand for composio');
- expect(commandMismatch.error.value.value).toContain("'generate'");
- expect(commandMismatch.error.value.value).toContain("'orgs'");
+ const commandMismatch = getCommandMismatch(result);
+ const message = HelpDoc.toAnsiText(commandMismatch.error);
+
+ expect(message).toContain('Invalid subcommand for composio');
+ expect(message).toContain("'generate'");
+ expect(message).toContain("'orgs'");
})
);
});
@@ -47,18 +40,13 @@ describe('CLI: composio', () => {
const args = ['tools', 'search', 'metabase', 'put'];
const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
- const commandMismatch = result as CommandMismatchResult;
-
- expect(result).toEqual(expect.any(Object));
- expect(commandMismatch._tag).toBe(ValidationError.commandMismatch(HelpDoc.p(''))._tag);
- expect(commandMismatch.error._tag).toBe('Paragraph');
- expect(commandMismatch.error.value._tag).toBe('Text');
- expect(commandMismatch.error.value.value).toContain(
- 'Invalid subcommand for composio tools'
- );
- expect(commandMismatch.error.value.value).toContain("'info'");
- expect(commandMismatch.error.value.value).toContain("'list'");
- expect(commandMismatch.error.value.value).not.toContain("'version'");
+ const commandMismatch = getCommandMismatch(result);
+ const message = HelpDoc.toAnsiText(commandMismatch.error);
+
+ expect(message).toContain('Invalid subcommand for composio tools');
+ expect(message).toContain("'info'");
+ expect(message).toContain("'list'");
+ expect(message).not.toContain("'version'");
})
);
});
@@ -150,6 +138,8 @@ describe('CLI: composio', () => {
Effect.gen(function* () {
vi.stubEnv('CODEX_THREAD_ID', 'thread_123');
vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'sdk-ts');
+ // The debug command still writes to process.stdout until the
+ // seam-rules PR of this stack routes it through TerminalUI.
const write = vi
.spyOn(process.stdout, 'write')
.mockImplementation((() => true) as typeof process.stdout.write);
@@ -165,15 +155,8 @@ describe('CLI: composio', () => {
layer(TestLive())(it => {
it.scoped('[Given] artifacts cwd [Then] it prints the current session artifact directory', () =>
Effect.gen(function* () {
- const write = vi
- .spyOn(process.stdout, 'write')
- .mockImplementation((() => true) as typeof process.stdout.write);
-
yield* cli(['artifacts', 'cwd']);
- const output = write.mock.calls
- .map(call => String(call[0]))
- .join('\n')
- .trim();
+ const output = (yield* MockConsole.getLines()).join('\n').trim();
expect(output).toContain(path.join(os.tmpdir(), 'composio'));
})
diff --git a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
index 79ee6d7aa..45e850c72 100644
--- a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
@@ -50,6 +50,13 @@ const testConfigProvider = ConfigProvider.fromMap(
).pipe(extendConfigProvider);
const RecordingTerminalUI = TerminalUI.of({
+ capabilities: Effect.succeed({
+ stdinIsTTY: true,
+ stdoutIsTTY: true,
+ stderrIsTTY: true,
+ isInteractive: true,
+ canDecorate: true,
+ }),
output: (data, options) =>
Console.log(
JSON.stringify({
@@ -57,6 +64,7 @@ const RecordingTerminalUI = TerminalUI.of({
data,
})
),
+ error: data => Console.error(data),
intro: title => Console.log(title),
outro: message => Console.log(message),
log: {
diff --git a/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts b/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
index 269db9186..5dc15ed8d 100644
--- a/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
@@ -90,7 +90,15 @@ const testConfigProvider = ConfigProvider.fromMap(
const terminalUIWithConfirm = (confirmed: boolean) =>
TerminalUI.of({
+ capabilities: Effect.succeed({
+ stdinIsTTY: true,
+ stdoutIsTTY: true,
+ stderrIsTTY: true,
+ isInteractive: true,
+ canDecorate: true,
+ }),
output: data => Console.log(data),
+ error: data => Console.error(data),
intro: title => Console.log(`-- ${title} --`),
outro: message => Console.log(`-- ${message} --`),
log: {
diff --git a/ts/packages/cli/test/src/commands/logout.cmd.test.ts b/ts/packages/cli/test/src/commands/logout.cmd.test.ts
index 67bb55664..4f5039ed3 100644
--- a/ts/packages/cli/test/src/commands/logout.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/logout.cmd.test.ts
@@ -13,7 +13,15 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
const terminalUIWithConfirm = (confirmed: boolean) =>
TerminalUI.of({
+ capabilities: Effect.succeed({
+ stdinIsTTY: true,
+ stdoutIsTTY: true,
+ stderrIsTTY: true,
+ isInteractive: true,
+ canDecorate: true,
+ }),
output: data => Console.log(data),
+ error: data => Console.error(data),
intro: title => Console.log(`-- ${title} --`),
outro: message => Console.log(`-- ${message} --`),
log: {
diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.ts
index 430f63393..70648cae0 100644
--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts
@@ -44,11 +44,10 @@ describe('CLI: composio run', () => {
Effect.gen(function* () {
const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));
const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
- const stderrWrite = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
vi.stubGlobal('Bun', { spawn });
yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
- const output = stderrWrite.mock.calls.map(([chunk]) => String(chunk));
+ const output = yield* MockConsole.getLines();
expect(spawn).toHaveBeenCalledTimes(1);
const spawnConfig = (spawn as any).mock.calls[0][0] as {
@@ -71,7 +70,7 @@ describe('CLI: composio run', () => {
})
);
expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
- expect(output).toContainEqual(expect.stringMatching(/^RUN_LOG_FILE=.*run\.log\n$/));
+ expect(output).toContainEqual(expect.stringMatching(/^RUN_LOG_FILE=.*run\.log$/));
expect(exit).toHaveBeenCalledWith(7);
})
);
diff --git a/ts/packages/cli/test/src/services/composio-client-singleton.test.ts b/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
index a242777f2..889384a08 100644
--- a/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+++ b/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
@@ -110,8 +110,9 @@ describe('ComposioClientSingleton headers', () => {
);
});
- // Fixed instants far in the future/past keep the expiry comparison
- // deterministic regardless of the clock the session-id reader consults.
+ // The session-id reader compares expiresAt against Clock.currentTimeMillis;
+ // the TestClock sits at epoch 0, so fixed instants around it are
+ // deterministically in the future or the past.
it.effect('includes the current cwd CLI session ID', () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
const homedir = tempy.temporaryDirectory();
@@ -128,7 +129,7 @@ describe('ComposioClientSingleton headers', () => {
vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
yield* writeCliSessionCache(homedir, {
id: 'cli_s_current',
- expiresAt: '2099-01-01T00:00:00.000Z',
+ expiresAt: '1970-01-01T00:01:00.000Z',
});
const client = yield* ComposioClientSingleton.get();
yield* Effect.promise(() =>
@@ -161,7 +162,7 @@ describe('ComposioClientSingleton headers', () => {
vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
yield* writeCliSessionCache(homedir, {
id: 'cli_s_expired',
- expiresAt: '1970-01-01T00:01:00.000Z',
+ expiresAt: '1969-12-31T23:59:00.000Z',
});
const client = yield* ComposioClientSingleton.get();
yield* Effect.promise(() =>
diff --git a/ts/packages/cli/test/src/services/runtime-debug-logger.test.ts b/ts/packages/cli/test/src/services/runtime-debug-logger.test.ts
new file mode 100644
index 000000000..f30a5c484
--- /dev/null
+++ b/ts/packages/cli/test/src/services/runtime-debug-logger.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, layer, vi } from '@effect/vitest';
+import { Effect } from 'effect';
+import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';
+import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';
+import { MockConsole, TestLive } from 'test/__utils__';
+
+describe('runtime debug logger', () => {
+ afterEach(() => {
+ resetRuntimeDebugFlags();
+ vi.restoreAllMocks();
+ });
+
+ layer(TestLive())(it => {
+ it.scoped('writes tool diagnostics as the existing JSON line format', () =>
+ Effect.gen(function* () {
+ setRuntimeDebugFlags({ toolDebug: true });
+
+ yield* logToolDebug('resolved', { slug: 'GITHUB_GET_REPO' });
+
+ expect(yield* MockConsole.getLines()).toContain(
+ '[tool-debug] {"label":"resolved","slug":"GITHUB_GET_REPO"}'
+ );
+ })
+ );
+
+ it.scoped('writes performance diagnostics with elapsed time', () =>
+ Effect.gen(function* () {
+ setRuntimeDebugFlags({ perfDebug: true });
+ vi.spyOn(Date, 'now').mockReturnValue(125);
+ const logPerfDebug = makePerfDebugLogger(100);
+
+ yield* logPerfDebug('started', { slug: 'GITHUB_GET_REPO' });
+
+ expect(yield* MockConsole.getLines()).toContain(
+ '[perf] {"phase":"event","label":"started","elapsedMs":25,"slug":"GITHUB_GET_REPO"}'
+ );
+ })
+ );
+ });
+});
diff --git a/ts/packages/cli/test/src/services/terminal-ui.test.ts b/ts/packages/cli/test/src/services/terminal-ui.test.ts
index 1b623c327..4c0a2e22d 100644
--- a/ts/packages/cli/test/src/services/terminal-ui.test.ts
+++ b/ts/packages/cli/test/src/services/terminal-ui.test.ts
@@ -1,9 +1,29 @@
-import { describe, expect, layer } from '@effect/vitest';
-import { Effect } from 'effect';
-import { TerminalUI } from 'src/services/terminal-ui';
+import { describe, expect, it, layer } from '@effect/vitest';
+import { Data, Effect, Exit } from 'effect';
+import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
import { TestLive, MockConsole } from 'test/__utils__';
+class TestFailure extends Data.TaggedError('test/TestFailure')<{
+ readonly message: string;
+}> {}
+
describe('TerminalUI', () => {
+ it('classifies prompt and decoration capabilities independently', () => {
+ expect(
+ getTerminalCapabilities({
+ stdin: { isTTY: false },
+ stdout: { isTTY: true },
+ stderr: { isTTY: true },
+ })
+ ).toEqual({
+ stdinIsTTY: false,
+ stdoutIsTTY: true,
+ stderrIsTTY: true,
+ isInteractive: false,
+ canDecorate: true,
+ });
+ });
+
layer(TestLive())(it => {
// -----------------------------------------------------------------------
// Data output
@@ -19,6 +39,16 @@ describe('TerminalUI', () => {
})
);
+ it.scoped('error writes raw diagnostics capturable by MockConsole', () =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ yield* ui.error('diagnostic');
+
+ const lines = yield* MockConsole.getLines();
+ expect(lines).toContain('diagnostic');
+ })
+ );
+
// -----------------------------------------------------------------------
// Log text capture
// -----------------------------------------------------------------------
@@ -119,10 +149,10 @@ describe('TerminalUI', () => {
Effect.gen(function* () {
const ui = yield* TerminalUI;
const exit = yield* Effect.exit(
- ui.withSpinner('loading', Effect.fail(new Error('network error')))
+ ui.withSpinner('loading', Effect.fail(new TestFailure({ message: 'network error' })))
);
- expect(exit._tag).toBe('Failure');
+ expect(Exit.isFailure(exit)).toBe(true);
})
);
@@ -135,10 +165,12 @@ describe('TerminalUI', () => {
const ui = yield* TerminalUI;
const exit = yield* Effect.exit(
- ui.useMakeSpinner('fetching data', _spinner => Effect.fail(new Error('API returned 400')))
+ ui.useMakeSpinner('fetching data', _spinner =>
+ Effect.fail(new TestFailure({ message: 'API returned 400' }))
+ )
);
- expect(exit._tag).toBe('Failure');
+ expect(Exit.isFailure(exit)).toBe(true);
// The spinner error message should be captured
const lines = yield* MockConsole.getLines();
@@ -207,12 +239,12 @@ describe('TerminalUI', () => {
Effect.gen(function* () {
// Simulate tapError pattern: callback calls spinner.error(), then the effect fails
yield* spinner.error('Login timed out. Please try again.');
- return yield* Effect.fail(new Error('timed out'));
+ return yield* new TestFailure({ message: 'timed out' });
})
)
);
- expect(exit._tag).toBe('Failure');
+ expect(Exit.isFailure(exit)).toBe(true);
const lines = yield* MockConsole.getLines();
// Should see the user's error message
diff --git a/ts/packages/cli/test/src/services/update-check.test.ts b/ts/packages/cli/test/src/services/update-check.test.ts
index f0e810277..6a07a9edf 100644
--- a/ts/packages/cli/test/src/services/update-check.test.ts
+++ b/ts/packages/cli/test/src/services/update-check.test.ts
@@ -1,8 +1,11 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from '@effect/vitest';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { tmpdir } from 'node:os';
-import { withHttpServer } from 'test/__utils__/http-server';
+import { BunFileSystem, BunPath } from '@effect/platform-bun';
+import { Effect, Layer } from 'effect';
+import { withHttpServerEffect } from 'test/__utils__/http-server';
+import type { TerminalUI } from 'src/services/terminal-ui';
import {
createUpdateChecker,
parseLatestVersionFromReleases,
@@ -12,6 +15,9 @@ import {
// ── Helpers ─────────────────────────────────────────────────────────────
+/** Platform services required by the update checker's Effects. */
+const PlatformLayers = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
+
/** Create a temp directory that is cleaned up after each test. */
let tempDir: string;
beforeEach(() => {
@@ -31,11 +37,24 @@ function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig {
binaryAssetName: 'composio-darwin-aarch64.zip',
accessToken: undefined,
fetchFn: () => Promise.reject(new Error('fetch not configured')),
- isInteractive: () => true,
...overrides,
};
}
+const makeTerminal = (
+ output: string[],
+ isInteractive = true
+): Pick<TerminalUI, 'capabilities' | 'error'> => ({
+ capabilities: Effect.succeed({
+ stdinIsTTY: isInteractive,
+ stdoutIsTTY: isInteractive,
+ stderrIsTTY: isInteractive,
+ isInteractive,
+ canDecorate: isInteractive,
+ }),
+ error: line => Effect.sync(() => output.push(line)),
+});
+
/** Write a state file to the test config's stateFile path. */
function writeState(config: UpdateCheckConfig, state: UpdateCheckState): void {
mkdirSync(dirname(config.stateFile), { recursive: true });
@@ -132,312 +151,366 @@ describe('parseLatestVersionFromReleases', () => {
// ── showUpdateNotice ────────────────────────────────────────────────────
describe('showUpdateNotice', () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- let stderrSpy: any;
+ let output: string[];
beforeEach(() => {
- stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
+ output = [];
});
- afterEach(() => {
- stderrSpy.mockRestore();
- });
-
- it('does nothing when no state file exists', () => {
- const { showUpdateNotice } = createUpdateChecker(makeConfig());
+ it.effect('does nothing when no state file exists', () =>
+ Effect.gen(function* () {
+ const { showUpdateNotice } = createUpdateChecker(makeConfig());
- showUpdateNotice();
+ yield* showUpdateNotice(makeTerminal(output));
- expect(stderrSpy).not.toHaveBeenCalled();
- });
+ expect(output).toEqual([]);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
- it('does nothing when cached version equals current version', () => {
- const config = makeConfig({ currentVersion: '0.2.0' });
- writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
- const { showUpdateNotice } = createUpdateChecker(config);
+ it.effect('does nothing when cached version equals current version', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({ currentVersion: '0.2.0' });
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
+ const { showUpdateNotice } = createUpdateChecker(config);
- showUpdateNotice();
+ yield* showUpdateNotice(makeTerminal(output));
- expect(stderrSpy).not.toHaveBeenCalled();
- });
+ expect(output).toEqual([]);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
- it('does nothing when cached version is older than current', () => {
- const config = makeConfig({ currentVersion: '0.3.0' });
- writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
- const { showUpdateNotice } = createUpdateChecker(config);
+ it.effect('does nothing when cached version is older than current', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({ currentVersion: '0.3.0' });
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
+ const { showUpdateNotice } = createUpdateChecker(config);
- showUpdateNotice();
+ yield* showUpdateNotice(makeTerminal(output));
- expect(stderrSpy).not.toHaveBeenCalled();
- });
+ expect(output).toEqual([]);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
- it('prints upgrade hint when cached version is newer', () => {
- const config = makeConfig({ currentVersion: '0.2.0' });
- writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
- const { showUpdateNotice } = createUpdateChecker(config);
+ it.effect('prints upgrade hint when cached version is newer', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({ currentVersion: '0.2.0' });
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
+ const { showUpdateNotice } = createUpdateChecker(config);
- showUpdateNotice();
+ yield* showUpdateNotice(makeTerminal(output));
- expect(stderrSpy).toHaveBeenCalledOnce();
- const output = stderrSpy.mock.calls[0][0] as string;
- expect(output).toContain('Update available');
- expect(output).toContain('0.3.0');
- expect(output).toContain('composio upgrade');
- });
+ expect(output).toHaveLength(1);
+ expect(output[0]).toContain('Update available');
+ expect(output[0]).toContain('0.3.0');
+ expect(output[0]).toContain('composio upgrade');
+ }).pipe(Effect.provide(PlatformLayers))
+ );
- it('does not print upgrade hint in non-interactive environments', () => {
- const config = makeConfig({ currentVersion: '0.2.0', isInteractive: () => false });
- writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
- const { showUpdateNotice } = createUpdateChecker(config);
+ it.effect('does not print upgrade hint in non-interactive environments', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({ currentVersion: '0.2.0' });
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
+ const { showUpdateNotice } = createUpdateChecker(config);
- showUpdateNotice();
+ yield* showUpdateNotice(makeTerminal(output, false));
- expect(stderrSpy).not.toHaveBeenCalled();
- });
+ expect(output).toEqual([]);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
- it('silently ignores corrupt state file', () => {
- const config = makeConfig();
- mkdirSync(dirname(config.stateFile), { recursive: true });
- writeFileSync(config.stateFile, 'not-json!!!');
- const { showUpdateNotice } = createUpdateChecker(config);
+ it.effect('silently ignores corrupt state file', () =>
+ Effect.gen(function* () {
+ const config = makeConfig();
+ mkdirSync(dirname(config.stateFile), { recursive: true });
+ writeFileSync(config.stateFile, 'not-json!!!');
+ const { showUpdateNotice } = createUpdateChecker(config);
- showUpdateNotice();
+ yield* showUpdateNotice(makeTerminal(output));
- expect(stderrSpy).not.toHaveBeenCalled();
- });
+ expect(output).toEqual([]);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
- it('does nothing when cached version is not valid semver', () => {
- const config = makeConfig({ currentVersion: '0.2.0' });
- writeState(config, { lastChecked: new Date().toISOString(), latestVersion: 'not-semver' });
- const { showUpdateNotice } = createUpdateChecker(config);
+ it.effect('does nothing when cached version is not valid semver', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({ currentVersion: '0.2.0' });
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: 'not-semver' });
+ const { showUpdateNotice } = createUpdateChecker(config);
- showUpdateNotice();
+ yield* showUpdateNotice(makeTerminal(output));
- expect(stderrSpy).not.toHaveBeenCalled();
- });
+ expect(output).toEqual([]);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
});
// ── checkForUpdate ──────────────────────────────────────────────────────
describe('checkForUpdate', () => {
- it('skips fetch when cache is fresh', () => {
- const fetchFn = vi.fn();
- const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch });
- writeState(config, {
- lastChecked: new Date().toISOString(),
- latestVersion: '0.2.0',
- });
- const { checkForUpdate } = createUpdateChecker(config);
-
- const result = checkForUpdate();
-
- expect(result).toBeUndefined(); // returned early, no promise
- expect(fetchFn).not.toHaveBeenCalled();
- });
+ // Pin the wall clock so the throttle math in checkForUpdate is deterministic.
+ // Only Date is faked: the SUT awaits real fetch promises through
+ // Effect.tryPromise, which need real timers/microtasks to settle.
+ const pinnedNow = new Date('2026-01-01T00:00:00.000Z');
+ const staleLastChecked = '2025-12-30T23:00:00.000Z'; // 25 hours before pinnedNow
- it('fetches when cache is stale', async () => {
- const stale = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(); // 25 hours ago
- const config = makeConfig({
- fetchFn: vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])),
- }) as unknown as typeof fetch,
- });
- writeState(config, { lastChecked: stale, latestVersion: '0.2.0' });
- const { checkForUpdate } = createUpdateChecker(config);
-
- await checkForUpdate();
-
- expect(config.fetchFn).toHaveBeenCalledOnce();
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.latestVersion).toBe('0.3.0');
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(pinnedNow);
});
- it('fetches when no cache exists', async () => {
- const config = makeConfig({
- fetchFn: vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve(makeReleasesPayload(['0.4.0', '0.3.0'])),
- }) as unknown as typeof fetch,
- });
- const { checkForUpdate } = createUpdateChecker(config);
-
- await checkForUpdate();
-
- expect(existsSync(config.stateFile)).toBe(true);
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.latestVersion).toBe('0.4.0');
+ afterEach(() => {
+ vi.useRealTimers();
});
- it('fetches when cache file is corrupt', async () => {
- const config = makeConfig({
- fetchFn: vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve(makeReleasesPayload(['0.5.0'])),
- }) as unknown as typeof fetch,
- });
- mkdirSync(dirname(config.stateFile), { recursive: true });
- writeFileSync(config.stateFile, 'garbage');
- const { checkForUpdate } = createUpdateChecker(config);
+ it.effect('skips fetch when cache is fresh', () =>
+ Effect.gen(function* () {
+ const fetchFn = vi.fn();
+ const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch });
+ writeState(config, {
+ lastChecked: new Date().toISOString(),
+ latestVersion: '0.2.0',
+ });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
+ expect(fetchFn).not.toHaveBeenCalled();
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('fetches when cache is stale', () =>
+ Effect.gen(function* () {
+ const stale = staleLastChecked;
+ const config = makeConfig({
+ fetchFn: vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])),
+ }) as unknown as typeof fetch,
+ });
+ writeState(config, { lastChecked: stale, latestVersion: '0.2.0' });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
+ expect(config.fetchFn).toHaveBeenCalledOnce();
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ expect(state.latestVersion).toBe('0.3.0');
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('fetches when no cache exists', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ fetchFn: vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(makeReleasesPayload(['0.4.0', '0.3.0'])),
+ }) as unknown as typeof fetch,
+ });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
+ expect(existsSync(config.stateFile)).toBe(true);
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ expect(state.latestVersion).toBe('0.4.0');
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('fetches when cache file is corrupt', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ fetchFn: vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(makeReleasesPayload(['0.5.0'])),
+ }) as unknown as typeof fetch,
+ });
+ mkdirSync(dirname(config.stateFile), { recursive: true });
+ writeFileSync(config.stateFile, 'garbage');
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ expect(state.latestVersion).toBe('0.5.0');
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect(
+ 'still writes lastChecked when no CLI releases with the required binary are found',
+ () =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ fetchFn: vi.fn().mockResolvedValue({
+ ok: true,
+ json: () =>
+ Promise.resolve([
+ {
+ tag_name: '@composio/[email protected]',
+ assets: [{ name: 'composio-darwin-aarch64.zip' }],
+ },
+ ]),
+ }) as unknown as typeof fetch,
+ });
+ const { checkForUpdate } = createUpdateChecker(config);
- await checkForUpdate();
+ yield* checkForUpdate;
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.latestVersion).toBe('0.5.0');
- });
+ expect(existsSync(config.stateFile)).toBe(true);
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ expect(state.lastChecked).toBeDefined();
+ // Falls back to currentVersion since no previous state and no matching releases found
+ expect(state.latestVersion).toBe(config.currentVersion);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect(
+ 'preserves previous latestVersion when no CLI releases with the required binary are found',
+ () =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ fetchFn: vi.fn().mockResolvedValue({
+ ok: true,
+ json: () =>
+ Promise.resolve([
+ {
+ tag_name: '@composio/[email protected]',
+ assets: [{ name: 'composio-darwin-aarch64.zip' }],
+ },
+ ]),
+ }) as unknown as typeof fetch,
+ });
+ const stale = staleLastChecked;
+ writeState(config, { lastChecked: stale, latestVersion: '0.3.0' });
+ const { checkForUpdate } = createUpdateChecker(config);
- it('still writes lastChecked when no CLI releases with the required binary are found', async () => {
- const config = makeConfig({
- fetchFn: vi.fn().mockResolvedValue({
- ok: true,
- json: () =>
- Promise.resolve([
- { tag_name: '@composio/[email protected]', assets: [{ name: 'composio-darwin-aarch64.zip' }] },
- ]),
- }) as unknown as typeof fetch,
- });
- const { checkForUpdate } = createUpdateChecker(config);
-
- await checkForUpdate();
-
- expect(existsSync(config.stateFile)).toBe(true);
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.lastChecked).toBeDefined();
- // Falls back to currentVersion since no previous state and no matching releases found
- expect(state.latestVersion).toBe(config.currentVersion);
- });
+ yield* checkForUpdate;
- it('preserves previous latestVersion when no CLI releases with the required binary are found', async () => {
- const config = makeConfig({
- fetchFn: vi.fn().mockResolvedValue({
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ expect(state.latestVersion).toBe('0.3.0');
+ expect(new Date(state.lastChecked).getTime()).toBeGreaterThan(new Date(stale).getTime());
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('writes lastChecked on HTTP errors to prevent retry loops', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ fetchFn: vi.fn().mockResolvedValue({
+ ok: false,
+ status: 500,
+ }) as unknown as typeof fetch,
+ });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ // Should not fail
+ yield* checkForUpdate;
+
+ expect(existsSync(config.stateFile)).toBe(true);
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ expect(state.lastChecked).toBeDefined();
+ expect(state.latestVersion).toBe(config.currentVersion);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('writes lastChecked on network errors to prevent retry loops', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
+ });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
+ expect(existsSync(config.stateFile)).toBe(true);
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ expect(state.lastChecked).toBeDefined();
+ expect(state.latestVersion).toBe(config.currentVersion);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('sends Authorization header when accessToken is set', () =>
+ Effect.gen(function* () {
+ const fetchFn = vi.fn().mockResolvedValue({
ok: true,
- json: () =>
- Promise.resolve([
- { tag_name: '@composio/[email protected]', assets: [{ name: 'composio-darwin-aarch64.zip' }] },
- ]),
- }) as unknown as typeof fetch,
- });
- const stale = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString();
- writeState(config, { lastChecked: stale, latestVersion: '0.3.0' });
- const { checkForUpdate } = createUpdateChecker(config);
-
- await checkForUpdate();
-
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.latestVersion).toBe('0.3.0');
- expect(new Date(state.lastChecked).getTime()).toBeGreaterThan(new Date(stale).getTime());
- });
-
- it('writes lastChecked on HTTP errors to prevent retry loops', async () => {
- const config = makeConfig({
- fetchFn: vi.fn().mockResolvedValue({
- ok: false,
- status: 500,
- }) as unknown as typeof fetch,
- });
- const { checkForUpdate } = createUpdateChecker(config);
-
- // Should not throw
- await checkForUpdate();
-
- expect(existsSync(config.stateFile)).toBe(true);
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.lastChecked).toBeDefined();
- expect(state.latestVersion).toBe(config.currentVersion);
- });
-
- it('writes lastChecked on network errors to prevent retry loops', async () => {
- const config = makeConfig({
- fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
- });
- const { checkForUpdate } = createUpdateChecker(config);
-
- await checkForUpdate();
-
- expect(existsSync(config.stateFile)).toBe(true);
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.lastChecked).toBeDefined();
- expect(state.latestVersion).toBe(config.currentVersion);
- });
-
- it('sends Authorization header when accessToken is set', async () => {
- const fetchFn = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])),
- });
- const config = makeConfig({
- accessToken: 'ghp_secret123',
- fetchFn: fetchFn as unknown as typeof fetch,
- });
- const { checkForUpdate } = createUpdateChecker(config);
-
- await checkForUpdate();
-
- expect(fetchFn).toHaveBeenCalledOnce();
- const [, init] = fetchFn.mock.calls[0];
- expect(init.headers.Authorization).toBe('Bearer ghp_secret123');
- });
-
- it('does not send Authorization header when accessToken is undefined', async () => {
- const fetchFn = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])),
- });
- const config = makeConfig({
- accessToken: undefined,
- fetchFn: fetchFn as unknown as typeof fetch,
- });
- const { checkForUpdate } = createUpdateChecker(config);
-
- await checkForUpdate();
-
- const [, init] = fetchFn.mock.calls[0];
- expect(init.headers.Authorization).toBeUndefined();
- });
+ json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])),
+ });
+ const config = makeConfig({
+ accessToken: 'ghp_secret123',
+ fetchFn: fetchFn as unknown as typeof fetch,
+ });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
+ expect(fetchFn).toHaveBeenCalledOnce();
+ const [, init] = fetchFn.mock.calls[0];
+ expect(init.headers.Authorization).toBe('Bearer ghp_secret123');
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('does not send Authorization header when accessToken is undefined', () =>
+ Effect.gen(function* () {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])),
+ });
+ const config = makeConfig({
+ accessToken: undefined,
+ fetchFn: fetchFn as unknown as typeof fetch,
+ });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
+ const [, init] = fetchFn.mock.calls[0];
+ expect(init.headers.Authorization).toBeUndefined();
+ }).pipe(Effect.provide(PlatformLayers))
+ );
});
// ── Integration: real HTTP server ───────────────────────────────────────
describe('checkForUpdate with real HTTP', () => {
- it('fetches from a real server and writes state', async () => {
- await withHttpServer(
+ it.effect('fetches from a real server and writes state', () =>
+ withHttpServerEffect(
(_req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(makeReleasesPayload(['0.1.26', '0.2.0', '0.2.1'])));
},
- async baseUrl => {
- const config = makeConfig({ releasesUrl: baseUrl, fetchFn: fetch });
- const { checkForUpdate } = createUpdateChecker(config);
+ baseUrl =>
+ Effect.gen(function* () {
+ const config = makeConfig({ releasesUrl: baseUrl, fetchFn: fetch });
+ const { checkForUpdate } = createUpdateChecker(config);
- await checkForUpdate();
+ yield* checkForUpdate;
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.latestVersion).toBe('0.2.1');
- }
- );
- });
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
+ expect(state.latestVersion).toBe('0.2.1');
+ })
+ ).pipe(Effect.provide(PlatformLayers))
+ );
- it('passes Authorization header to the server', async () => {
+ it.effect('passes Authorization header to the server', () => {
let receivedAuth: string | undefined;
- await withHttpServer(
+ return withHttpServerEffect(
(req, res) => {
receivedAuth = req.headers.authorization;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(makeReleasesPayload(['0.2.1'])));
},
- async baseUrl => {
- const config = makeConfig({
- releasesUrl: baseUrl,
- accessToken: 'ghp_test_token',
- fetchFn: fetch,
- });
- const { checkForUpdate } = createUpdateChecker(config);
-
- await checkForUpdate();
-
- expect(receivedAuth).toBe('Bearer ghp_test_token');
- }
- );
+ baseUrl =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ releasesUrl: baseUrl,
+ accessToken: 'ghp_test_token',
+ fetchFn: fetch,
+ });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
+ expect(receivedAuth).toBe('Bearer ghp_test_token');
+ })
+ ).pipe(Effect.provide(PlatformLayers));
});
});
diff --git a/ts/packages/cli/test/src/services/upgrade-binary.test.ts b/ts/packages/cli/test/src/services/upgrade-binary.test.ts
index 43b2a5568..547ae5647 100644
--- a/ts/packages/cli/test/src/services/upgrade-binary.test.ts
+++ b/ts/packages/cli/test/src/services/upgrade-binary.test.ts
@@ -14,7 +14,15 @@ import { collectExpectedRunCompanionAssetRelativePaths } from 'src/services/run-
const TerminalUINoop = Layer.succeed(
TerminalUI,
TerminalUI.of({
+ capabilities: Effect.succeed({
+ stdinIsTTY: false,
+ stdoutIsTTY: false,
+ stderrIsTTY: false,
+ isInteractive: false,
+ canDecorate: false,
+ }),
output: () => Effect.void,
+ error: () => Effect.void,
intro: () => Effect.void,
outro: () => Effect.void,
log: {
diff --git a/ts/packages/cli/test/src/utils/stdio.test.ts b/ts/packages/cli/test/src/utils/stdio.test.ts
deleted file mode 100644
index 9ce69e156..000000000
--- a/ts/packages/cli/test/src/utils/stdio.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { canRenderTerminalDecoration, isInteractiveTerminal } from 'src/utils/stdio';
-
-describe('stdio helpers', () => {
- it('requires all streams to be TTYs for interactive prompts', () => {
- expect(
- isInteractiveTerminal({
- stdin: { isTTY: false },
- stdout: { isTTY: true },
- stderr: { isTTY: true },
- })
- ).toBe(false);
- });
-
- it('allows terminal decoration when only stderr is a TTY', () => {
- expect(
- canRenderTerminalDecoration({
- stdin: { isTTY: false },
- stdout: { isTTY: true },
- stderr: { isTTY: true },
- })
- ).toBe(true);
- });
-
- it('suppresses terminal decoration when stderr is not a TTY', () => {
- expect(
- canRenderTerminalDecoration({
- stdin: { isTTY: true },
- stdout: { isTTY: true },
- stderr: { isTTY: false },
- })
- ).toBe(false);
- });
-});