@devries-cameron20 / composio Mirror · read-only / commits / 13fa02022
Fork 0

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

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

Synced Nov 21, 03:37 UTC

fix(cli): escape control characters in displayed output (#5462)

- closes [SEC-2423](https://linear.app/composio/issue/SEC-2423) - Escape control characters before rendering listener records on stdout and stderr. - Apply the same display policy to developer listener events, proxy notes, execute output, and CLI errors. - Keep saved events, forwarded payloads, decoded JSON values, and redirected proxy bodies intact. - Add regression coverage for output framing, rendered diagnostics, and data fidelity. ## Verification - 249 tests passed across 12 affected CLI suites. - CLI source and test typechecks, lint, and the command-test and lint-boundary validators passed.

Alberto Schiabel committed Nov 19, 2026 at 11:44 UTC 13fa02022e2c8a733e1dba9d6c779344e32835c1
22 files changed +684 -48
ts/packages/cli/CHANGELOG.md
+6
@@ -6,6 +6,12 @@
6
7 - Update @composio/client to 2.1.35 to include the latest API changes.
8
9 +- `composio listen --stream` shows control characters, including embedded tabs and line breaks,
10 + as visible escapes in each output record. Read the saved event JSON for the original value.
11 + `composio dev listen`, `composio execute`, `composio proxy` and error messages also show
12 + control characters from events, responses and API errors as escapes on the terminal. Printed
13 + JSON decodes to the same values, and redirected `proxy` output stays unchanged.
14 +
15 - `composio upgrade` on Windows now retries a busy executable rename for up to two seconds, allowing a brief file lock after a previous upgrade to clear before replacing the binary.
16
17 - Update @composio/client to 2.1.33 to include the latest API changes.
ts/packages/cli/src/commands/listen/listen.format.ts
+10 -2
@@ -1,12 +1,20 @@
1 import { Effect } from 'effect';
2 import type { TerminalUI } from 'src/services/terminal-ui';
3 +import { escapeTerminalText } from 'src/ui/escape-terminal-text';
4
5 +/**
6 + * Emits one listener record on decorated stderr and on stdout. Event data in `line` can carry
7 + * controls and line breaks, so the line is escaped once for both sinks and stays one record;
8 + * the saved payload file keeps the original values.
9 + */
10 export const emitStreamLine = (line: string, ui: TerminalUI) =>
11 Effect.gen(function* () {
6 - yield* ui.log.message(line);
7 - yield* ui.output(line, { force: true });
12 + const record = escapeTerminalText(line);
13 + yield* ui.log.message(record);
14 + yield* ui.output(record, { force: true });
15 });
16
17 +/** The text of a `stream:` value: strings as they are, anything else as compact JSON. */
18 export const formatStreamValue = (value: unknown): string => {
19 if (value === undefined) return 'null';
20 if (typeof value === 'string') return value;
ts/packages/cli/src/commands/listen/listen.handler.ts
+3 -2
@@ -24,6 +24,7 @@ import { resolveConnectedAccountForToolkit } from 'src/services/connected-accoun
24 import { LISTENER_STOP, ShutdownSignal } from 'src/services/shutdown-signal';
25 import { TerminalUI } from 'src/services/terminal-ui';
26 import { TriggersRealtime } from 'src/services/triggers-realtime';
27 +import { escapeTerminalText } from 'src/ui/escape-terminal-text';
28 import { ListenCommandError } from './listen.errors';
29 import { emitStreamLine, formatStopMessage, formatStreamValue } from './listen.format';
30 import {
@@ -73,7 +74,7 @@ const disableTemporaryTrigger = (params: {
74 cause,
75 })
76 ),
76 - Effect.tapError(error => params.ui.log.warn(error.message)),
77 + Effect.tapError(error => params.ui.log.warn(escapeTerminalText(error.message))),
78 Effect.ignore
79 );
80
@@ -548,7 +549,7 @@ export const runListen = (input: ListenParams) =>
549 Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
550 reportFailure(
551 ui,
551 - `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`
552 + `Could not subscribe to realtime trigger events: ${escapeTerminalText(error.message)}. Check your network connection or run \`composio login\`.`
553 )
554 )
555 );
ts/packages/cli/src/commands/proxy/proxy.handler.ts
+8 -4
@@ -8,6 +8,7 @@ import {
8 refreshConsumerConnectedToolkitsCache,
9 } from 'src/services/consumer-short-term-cache';
10 import { TerminalUI } from 'src/services/terminal-ui';
11 +import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
12 import { ComposioClientSingleton } from 'src/services/composio-clients';
13 import { actingUser } from 'src/commands/surface';
14 import {
@@ -88,8 +89,10 @@ const handleProxyExecutionError = (params: {
89 toolkit: params.toolkit,
90 });
91
92 + // The message can quote the upstream API; the stdout result keeps it as it is.
93 + const displayMessage = escapeTerminalText(mapped.message);
94 if (mapped.normalized instanceof ComposioNoActiveConnectionError) {
92 - yield* params.ui.log.error(mapped.message);
95 + yield* params.ui.log.error(displayMessage);
96 yield* params.ui.note(
97 [
98 `Link the toolkit first: composio link ${params.toolkit}`,
@@ -98,7 +101,7 @@ const handleProxyExecutionError = (params: {
101 'Tips'
102 );
103 } else {
101 - yield* params.ui.log.error(mapped.message);
104 + yield* params.ui.log.error(displayMessage);
105 }
106 const output = formatProxyErrorOutput({
107 error: mapped.message,
@@ -295,9 +298,10 @@ export const runProxy = (params: ProxyParams) =>
298 );
299
300 const output = formatProxyOutput(result);
298 - yield* ui.log.info(`Status: ${String(result.status ?? 'unknown')}`);
301 + yield* ui.log.info(`Status: ${escapeTerminalText(String(result.status ?? 'unknown'))}`);
302 if (output) {
300 - yield* ui.note(output, 'Proxy Response');
303 + // The note shows the response on the terminal; redirected stdout gets the body as it is.
304 + yield* ui.note(escapeTerminalLines(output), 'Proxy Response');
305 yield* ui.output(output);
306 }
307 });
ts/packages/cli/src/commands/tools/execute/tools.execute.failure.ts
+14 -6
@@ -19,6 +19,7 @@ import {
19 import { cliInvocationContext } from 'src/services/runtime-cli-context';
20 import type { TerminalUI } from 'src/services/terminal-ui';
21 import { ToolInputValidationError } from 'src/services/tool-input-validation';
22 +import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
23 import { connectionTips, formatUnknownObject, redactRequestId } from './tools.execute.format';
24
25 export const emitExecuteFailureTelemetry = (params: {
@@ -251,9 +252,10 @@ export const handleExecutionError = (
252 });
253 yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);
254 yield* ui.note(
254 - [`Schema: ${normalized.schemaPath}`, ...normalized.issues.map(issue => `- ${issue}`)].join(
255 - '\n'
256 - ),
255 + [
256 + `Schema: ${normalized.schemaPath}`,
257 + ...normalized.issues.map(issue => `- ${escapeTerminalText(issue)}`),
258 + ].join('\n'),
259 'Tool schema validation'
260 );
261 return { error: normalized.message, slug: context.toolSlug };
@@ -274,8 +276,11 @@ export const handleExecutionError = (
276 mappedError: mapped,
277 });
278
279 + // The message and details can quote the API or the tool; the returned summary keeps them as
280 + // they are for the JSON result.
281 + const displayMessage = escapeTerminalText(mapped.message);
282 if (normalized instanceof ComposioNoActiveConnectionError) {
278 - yield* ui.log.error(mapped.message);
283 + yield* ui.log.error(displayMessage);
284 if (toolkit) {
285 yield* ui.note(
286 connectionTips({ toolkit, toolSlug: context.toolSlug, surface: context.surface }),
@@ -285,11 +290,14 @@ export const handleExecutionError = (
290 return { error: mapped.message, slug: slugValue ?? context.toolSlug };
291 }
292
288 - yield* ui.log.error(mapped.message);
293 + yield* ui.log.error(displayMessage);
294
295 const detailsObject = apiDetails;
296 if (detailsObject) {
292 - yield* ui.note(formatUnknownObject(redactRequestId(detailsObject)), 'Error details');
297 + yield* ui.note(
298 + escapeTerminalLines(formatUnknownObject(redactRequestId(detailsObject))),
299 + 'Error details'
300 + );
301 }
302
303 return { error: mapped.message, slug: slugValue };
ts/packages/cli/src/commands/tools/execute/tools.execute.format.ts
+8 -2
@@ -4,6 +4,7 @@ import { commandHintStep } from 'src/services/command-hints';
4 import type { TerminalUI } from 'src/services/terminal-ui';
5 import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
6 import type { InstantCharge } from 'src/services/tools-executor';
7 +import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
8 import { redact } from 'src/ui/redact';
9 import { isPlainRecord } from 'src/utils/parse-json';
10
@@ -108,11 +109,16 @@ export const executionSuccessSuffix = (result: {
109 instantChargeLabel(result.instantCharge),
110 result.logId ? `logId: ${redact({ value: result.logId, prefix: 'log_' })}` : undefined,
111 ].filter((value): value is string => Boolean(value));
111 - return metadata.length > 0 ? ` (${metadata.join(', ')})` : '';
112 + return metadata.length > 0 ? ` (${escapeTerminalText(metadata.join(', '))})` : '';
113 };
114
115 +/**
116 + * Prints serialized execute JSON on stdout, shown on a terminal too. JSON already escapes C0
117 + * controls in strings; DEL and C1 are escaped here as well, which decodes to the same values. A
118 + * response stored in a file keeps its original bytes.
119 + */
120 export const writeExecuteStdout = (ui: TerminalUI, data: string) =>
115 - ui.output(data, { force: true });
121 + ui.output(escapeTerminalLines(data), { force: true });
122
123 export type DryRunSummary = {
124 readonly successful: true;
ts/packages/cli/src/commands/tools/execute/tools.execute.handler.ts
+3 -2
@@ -16,6 +16,7 @@ import {
16 } from 'src/services/tool-input-validation';
17 import { detectInBandWarning } from 'src/services/tools-executor';
18 import type { ToolExecuteParams, ToolsExecutor } from 'src/services/tools-executor';
19 +import { escapeTerminalText } from 'src/ui/escape-terminal-text';
20 import { redact } from 'src/ui/redact';
21 import {
22 resolveExecuteContext,
@@ -305,7 +306,7 @@ const runExecuteWithSpinner = (params: {
306 if (!result.successful) {
307 yield* invalidateToolInputDefinition(params.slug).pipe(Effect.catch(() => Effect.void));
308 const logId = result.logId
308 - ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
309 + ? ` (logId: ${escapeTerminalText(redact({ value: result.logId, prefix: 'log_' }))})`
310 : '';
311 yield* spinner.error(`Execution failed${logId}`);
312
@@ -330,7 +331,7 @@ const runExecuteWithSpinner = (params: {
331 const inBandWarning = detectInBandWarning(result.data);
332 if (inBandWarning) {
333 yield* params.ui.log.warn(
333 - `The tool executed successfully but the response may contain an error: ${inBandWarning}`
334 + `The tool executed successfully but the response may contain an error: ${escapeTerminalText(inBandWarning)}`
335 );
336 }
337 const output = yield* prepareExecuteOutput(params.slug, result, params.executeOutputDir);
ts/packages/cli/src/commands/tools/execute/tools.execute.parallel.ts
+7 -3
@@ -12,6 +12,7 @@ import {
12 getOrFetchToolInputDefinition,
13 validateToolInputArgumentsWithDefinition,
14 } from 'src/services/tool-input-validation';
15 +import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
16 import { redact } from 'src/ui/redact';
17 import {
18 resolveExecuteContext,
@@ -361,7 +362,7 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
362 if (ui) {
363 for (const result of results) {
364 if (!result.successful) {
364 - yield* ui.log.error(`[${result.slug}] ${result.error}`);
365 + yield* ui.log.error(`[${result.slug}] ${escapeTerminalText(result.error)}`);
366 continue;
367 }
368
@@ -526,7 +527,7 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
527 'logId' in result && typeof result.logId === 'string' && result.logId.length > 0
528 ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
529 : '';
529 - yield* ui.log.error(`[${result.slug}] ${result.error}${logId}`);
530 + yield* ui.log.error(`[${result.slug}] ${escapeTerminalText(`${result.error}${logId}`)}`);
531 continue;
532 }
533
@@ -551,7 +552,10 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
552 `[${result.slug}] Execution successful${executionSuccessSuffix(result)}`
553 );
554 if ('data' in result) {
554 - yield* ui.note(serializeExecuteOutput(result), `Response: ${result.slug}`);
555 + yield* ui.note(
556 + escapeTerminalLines(serializeExecuteOutput(result)),
557 + `Response: ${result.slug}`
558 + );
559 }
560 }
561 }
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+7 -4
@@ -8,6 +8,7 @@ import { Deferred, Effect, FiberSet, Option } from 'effect';
8 import { APP_CONFIG } from 'src/config';
9 import { CommandSurface, resolveSurfaceProject } from 'src/commands/surface';
10 import { TerminalUI } from 'src/services/terminal-ui';
11 +import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
12 import { TriggersRealtime } from 'src/services/triggers-realtime';
13 import { LISTENER_STOP, ShutdownSignal } from 'src/services/shutdown-signal';
14 import { matchesTriggerListenFilters } from '../filter';
@@ -281,13 +282,15 @@ export const triggersCmd$Listen = Command.make(
282
283 yield* emitTableLine(tableLine, ui);
284 } else if (json) {
285 + // Shown JSON escapes the DEL and C1 controls JSON leaves as they are; the
286 + // decoded values do not change. --out and --forward get the original JSON.
287 yield* ui.note(formatTriggerListenSummary(parsed), `Event #${matchingEvents}`);
285 - yield* ui.log.message(JSON.stringify(eventData, null, 2));
286 - yield* ui.output(JSON.stringify(eventData));
288 + yield* ui.log.message(escapeTerminalLines(JSON.stringify(eventData, null, 2)));
289 + yield* ui.output(escapeTerminalText(JSON.stringify(eventData)));
290 } else {
291 yield* ui.note(formatTriggerListenSummary(parsed), `Event #${matchingEvents}`);
289 - yield* ui.log.message(JSON.stringify(parsed.payload, null, 2));
290 - yield* ui.output(JSON.stringify(eventData));
292 + yield* ui.log.message(escapeTerminalLines(JSON.stringify(parsed.payload, null, 2)));
293 + yield* ui.output(escapeTerminalText(JSON.stringify(eventData)));
294 }
295
296 const payloadForForwarding = JSON.stringify(eventData);
ts/packages/cli/src/commands/triggers/format.ts
+23 -11
@@ -2,18 +2,20 @@ import type { TriggerType } from 'src/models/trigger-types';
2 import type { TriggerListenEvent } from './types';
3 import type { TriggerInstanceItem } from 'src/models/triggers';
4 import { bold, gray } from 'src/ui/colors';
5 +import { escapeTerminalText } from 'src/ui/escape-terminal-text';
6 import { truncate } from 'src/ui/truncate';
7 import { extractSchemaProperties } from 'src/ui/extract-schema-properties';
8
9 +/** One line per field; event values are escaped so each stays on its own line. */
10 export const formatTriggerListenSummary = (event: TriggerListenEvent): string => {
11 const userId = event.userId || '-';
12 const connectedAccountId = event.metadata.connectedAccount.id || '-';
13 return [
12 - `Trigger: ${event.triggerSlug}`,
13 - `Toolkit: ${event.toolkitSlug}`,
14 - `Trigger Id: ${event.id}`,
15 - `Connected Account: ${connectedAccountId}`,
16 - `User Id: ${userId}`,
14 + `Trigger: ${escapeTerminalText(event.triggerSlug)}`,
15 + `Toolkit: ${escapeTerminalText(event.toolkitSlug)}`,
16 + `Trigger Id: ${escapeTerminalText(event.id)}`,
17 + `Connected Account: ${escapeTerminalText(connectedAccountId)}`,
18 + `User Id: ${escapeTerminalText(userId)}`,
19 ].join('\n');
20 };
21
@@ -36,6 +38,10 @@ export const formatTriggerListenTableHeader = (): string =>
38 bold('Connected Account Id'),
39 ].join(' ');
40
41 +/**
42 + * One table row. Each cell is escaped before it is truncated, padded and styled, so the row
43 + * stays one line and its widths count what is shown.
44 + */
45 export const formatTriggerListenTableRow = ({
46 timestamp,
47 event,
@@ -43,18 +49,24 @@ export const formatTriggerListenTableRow = ({
49 timestamp: string;
50 event: TriggerListenEvent;
51 }): string => {
46 - const connectedAccountId = event.metadata.connectedAccount.id || '-';
47 - const userId = event.userId || '-';
48 - const timestampCell = truncate(timestamp, TRIGGER_TABLE.timestamp).padEnd(
52 + const connectedAccountId = escapeTerminalText(event.metadata.connectedAccount.id || '-');
53 + const userId = escapeTerminalText(event.userId || '-');
54 + const timestampCell = truncate(escapeTerminalText(timestamp), TRIGGER_TABLE.timestamp).padEnd(
55 TRIGGER_TABLE.timestamp
56 );
51 - const triggerIdCell = truncate(event.id, TRIGGER_TABLE.triggerId).padEnd(TRIGGER_TABLE.triggerId);
57 + const triggerIdCell = truncate(escapeTerminalText(event.id), TRIGGER_TABLE.triggerId).padEnd(
58 + TRIGGER_TABLE.triggerId
59 + );
60
61 return [
62 gray(timestampCell),
63 triggerIdCell,
56 - truncate(event.triggerSlug, TRIGGER_TABLE.triggerSlug).padEnd(TRIGGER_TABLE.triggerSlug),
57 - truncate(event.toolkitSlug, TRIGGER_TABLE.toolkit).padEnd(TRIGGER_TABLE.toolkit),
64 + truncate(escapeTerminalText(event.triggerSlug), TRIGGER_TABLE.triggerSlug).padEnd(
65 + TRIGGER_TABLE.triggerSlug
66 + ),
67 + truncate(escapeTerminalText(event.toolkitSlug), TRIGGER_TABLE.toolkit).padEnd(
68 + TRIGGER_TABLE.toolkit
69 + ),
70 truncate(userId, TRIGGER_TABLE.userId).padEnd(TRIGGER_TABLE.userId),
71 truncate(connectedAccountId, TRIGGER_TABLE.connectedAccountId),
72 ].join(' ');
ts/packages/cli/src/commands/triggers/sink-failures.ts
+3 -1
@@ -1,6 +1,7 @@
1 import { Deferred, Effect, FiberSet } from 'effect';
2 import { reportFailure } from 'src/effects/report-failure';
3 import type { TerminalUI } from 'src/services/terminal-ui';
4 +import { escapeTerminalText } from 'src/ui/escape-terminal-text';
5
6 /**
7 * On a normal stop (`--max-events`, `--timeout`), lets the events the listener already accepted
@@ -37,7 +38,8 @@ export const makeSinkFailures = (params: {
38 record: (message: string) =>
39 Effect.gen(function* () {
40 count += 1;
40 - yield* params.ui.log.warn(message);
41 + // The message can quote a remote error or an event-derived path.
42 + yield* params.ui.log.warn(escapeTerminalText(message));
43 if (params.failFast) {
44 yield* params.stop;
45 return yield* Effect.interrupt;
ts/packages/cli/src/effect-errors/pretty-print/common/format-error-title.ts
+3 -2
@@ -1,4 +1,5 @@
1 import * as color from 'src/ui/colors';
2 +import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
3
4 export const formatErrorTitle = (
5 errorType: unknown,
@@ -9,9 +10,9 @@ export const formatErrorTitle = (
10 const failuresCount =
11 failuresLength > 1 ? color.bgRed(color.white(` #${failureIndex + 1} -`)) : '';
12 const type = color.bgRed(
12 - color.white(` ${(errorType as string | undefined) ?? 'Unknown error'} `)
13 + color.white(` ${escapeTerminalText(String(errorType ?? 'Unknown error'))} `)
14 );
14 - const formattedMessage = color.bold(color.white(` • ${message as string}`));
15 + const formattedMessage = color.bold(color.white(` • ${escapeTerminalLines(String(message))}`));
16
17 return [`💥 ${failuresCount}${type}${formattedMessage}`];
18 };
ts/packages/cli/src/invocation/invocation.ts
+9 -2
@@ -46,6 +46,7 @@ import type { ShutdownSignal } from 'src/services/shutdown-signal';
46 import { TerminalUI } from 'src/services/terminal-ui';
47 import type { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
48 import { BackgroundUpdateCheck, UpdateNotice } from 'src/services/update-check';
49 +import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
50 import { extractMessage } from 'src/utils/api-error-extraction';
51 import type { InvocationLive } from './live';
52
@@ -207,9 +208,11 @@ const report = (cause: Cause.Cause<unknown>) =>
208 const printRetryHint = Option.exists(error, isSafeToRetry)
209 ? ui.error(retryHint('safe'))
210 : Effect.void;
211 + // Both messages can quote a remote service, so their controls are escaped for display. An
212 + // expected failure's message can have its own line breaks; a backend message is one line.
213 const expected = Option.filter(error, isExpectedFailure);
214 if (Option.isSome(expected)) {
212 - yield* ui.error(expected.value.message);
215 + yield* ui.error(escapeTerminalLines(expected.value.message));
216 yield* printUnauthorizedHint(expected.value);
217 yield* printRetryHint;
218 return;
@@ -217,7 +220,11 @@ const report = (cause: Cause.Cause<unknown>) =>
220 // Any other 401 gets the backend's message in place of a defect report.
221 const rejected = Option.filter(error, isUnauthorized);
222 if (Option.isSome(rejected)) {
220 - yield* ui.error(extractMessage(rejected.value) ?? 'The Composio API rejected the request.');
223 + yield* ui.error(
224 + escapeTerminalText(
225 + extractMessage(rejected.value) ?? 'The Composio API rejected the request.'
226 + )
227 + );
228 yield* printUnauthorizedHint(rejected.value);
229 return;
230 }
ts/packages/cli/src/ui/escape-terminal-text.ts new
+39
@@ -0,0 +1,39 @@
1 +/**
2 + * Display encoding for text that did not come from the CLI itself (event fields, API messages,
3 + * tool and proxy responses) and is about to reach a terminal or a captured transcript.
4 + *
5 + * Every C0 control (U+0000–U+001F), DEL (U+007F) and C1 control (U+0080–U+009F) becomes a
6 + * visible JSON-style `\uXXXX` escape, so the text can neither change terminal state nor split
7 + * one record into several lines. Printable Unicode and backslashes are left as they are. Apply
8 + * it to decoded text before styling, so the CLI's own colors still render.
9 + *
10 + * The code points involved are all in the Basic Multilingual Plane and outside the surrogate
11 + * range, so walking UTF-16 code units never splits an astral character.
12 + */
13 +const isEscaped = (code: number, keepLineBreaks: boolean): boolean => {
14 + if (keepLineBreaks && (code === 0x0a || code === 0x09)) return false;
15 + return code <= 0x1f || (code >= 0x7f && code <= 0x9f);
16 +};
17 +
18 +const escapeControls = (text: string, keepLineBreaks: boolean): string => {
19 + let escaped = '';
20 + let start = 0;
21 + for (let index = 0; index < text.length; index += 1) {
22 + const code = text.charCodeAt(index);
23 + if (isEscaped(code, keepLineBreaks)) {
24 + escaped += `${text.slice(start, index)}\\u${code.toString(16).padStart(4, '0')}`;
25 + start = index + 1;
26 + }
27 + }
28 + return start === 0 ? text : escaped + text.slice(start);
29 +};
30 +
31 +/** For one-line display fields and records: every control, line breaks and tabs included. */
32 +export const escapeTerminalText = (text: string): string => escapeControls(text, false);
33 +
34 +/**
35 + * For intentionally multiline display (notes, pretty-printed JSON): CRLF becomes LF, LF and TAB
36 + * stay, and every other control, a lone CR included, is escaped.
37 + */
38 +export const escapeTerminalLines = (text: string): string =>
39 + escapeControls(text.replaceAll('\r\n', '\n'), true);
ts/packages/cli/test/__utils__/services/redirected-terminal-ui.ts
+11 -5
@@ -2,8 +2,11 @@ import { Writable } from 'node:stream';
2 import { Effect, Layer } from 'effect';
3 import { makeTerminalUI, TerminalUI } from 'src/services/terminal-ui';
4
5 -/** A redirected stream; with `readerClosed`, every write fails with EPIPE, as after `| head`. */
6 -const capture = (readerClosed = false) => {
5 +/**
6 + * A captured stream, redirected unless `isTTY`; with `readerClosed`, every write fails with
7 + * EPIPE, as after `| head`.
8 + */
9 +const capture = (readerClosed = false, isTTY = false) => {
10 const chunks: Array<string> = [];
11 const stream = Object.assign(
12 new Writable({
@@ -16,7 +19,7 @@ const capture = (readerClosed = false) => {
19 callback();
20 },
21 }),
19 - { isTTY: false }
22 + { isTTY }
23 );
24 return { stream, text: () => chunks.join('') };
25 };
@@ -25,16 +28,19 @@ const capture = (readerClosed = false) => {
28 * The real `TerminalUI` with stdin, stdout and stderr all redirected, as under a script, CI or
29 * an agent: `ui.log.*` decoration is dropped and only `ui.output` and `ui.error` are written.
30 * Unlike `terminalUITestImpl`, which prints decoration through `Console`, it shows what such a
28 - * caller actually sees.
31 + * caller actually sees. With `decoratedStderr`, stderr is a terminal instead, so `ui.log.*`
32 + * renders there as a person watching it would see it, while stdout stays redirected.
33 */
34 export const redirectedTerminalUI = (options?: {
35 /** Runs after a `log.warn` is logged — a signal that code behind the warn has run. */
36 readonly onWarn?: (message: string) => void;
37 /** The reader of stdout went away before the first write (`… | head -0`). */
38 readonly stdoutReaderClosed?: boolean;
39 + /** stderr is a terminal, so decoration renders on it. */
40 + readonly decoratedStderr?: boolean;
41 }) => {
42 const stdout = capture(options?.stdoutReaderClosed);
37 - const stderr = capture();
43 + const stderr = capture(false, options?.decoratedStderr);
44 const ui = makeTerminalUI({
45 stdin: { isTTY: false },
46 stdout: stdout.stream,
ts/packages/cli/test/src/commands/listen/listen.cmd.test.ts
+141
@@ -1,5 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
3 +import * as FileSystem from 'effect/FileSystem';
4 +import * as Path from 'effect/Path';
5 import { TestClock } from 'effect/testing';
6 import { ListenCommandError } from 'src/commands/listen/listen.errors';
7 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
@@ -41,6 +43,45 @@ const failingRealtime = Layer.succeed(
43 })
44 );
45
46 +// Formatting fixtures: standalone controls (BEL, DEL, NEL), CR/LF, a tab, a literal backslash,
47 +// combining and astral Unicode, in a value, a nested key and a top-level key.
48 +const formattingEvent = {
49 + id: 'evt_formatting_1',
50 + type: 'composio.connected_account.expired',
51 + timestamp: '2026-04-06T18:00:00.000Z',
52 + 'extra\u0085key': true,
53 + metadata: {
54 + project_id: 'consumer_project_id_test',
55 + org_id: 'org_test',
56 + 'label\u007f': 'value\u0085',
57 + },
58 + data: {
59 + id: 'con_expired_1',
60 + note: 'line one\r\nline two\ttabbed\u0007 C:\\temp e\u0301 \u{1f600}',
61 + },
62 +};
63 +
64 +/** Any C0, DEL or C1 code point but the line feed that ends a record. */
65 +const dataControl = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/u;
66 +/** SGR styling, the only escape sequence the CLI writes on its own. */
67 +const sgr = /\u001b\[[0-9;]*m/gu;
68 +
69 +/** The payload file the `event:` record names, and the `events.jsonl` index next to it. */
70 +const readSavedEvent = (stdoutLines: ReadonlyArray<string>) =>
71 + Effect.gen(function* () {
72 + const fs = yield* FileSystem.FileSystem;
73 + const path = yield* Path.Path;
74 + const eventLine = stdoutLines.find(line => line.startsWith('event: '));
75 + expect(eventLine).toBeDefined();
76 + const payloadPath = (eventLine ?? '').slice('event: '.length);
77 + const payload: unknown = JSON.parse(yield* fs.readFileString(payloadPath));
78 + const index = (yield* fs.readFileString(path.join(path.dirname(payloadPath), 'events.jsonl')))
79 + .trim()
80 + .split('\n')
81 + .map(line => JSON.parse(line) as { readonly file_path: string });
82 + return { payloadPath, payload, index };
83 + });
84 +
85 describe('CLI: composio listen', () => {
86 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
87 '[Given] the realtime subscription fails',
@@ -186,6 +227,106 @@ describe('CLI: composio listen', () => {
227 );
228 });
229
230 + layer(
231 + TestLive({
232 + baseConfigProvider: testConfigProvider,
233 + fixture: 'global-test-user-id',
234 + realtimeData: { events: [formattingEvent] },
235 + })
236 + )('[Given] an event whose fields carry controls and line breaks', it => {
237 + it.effect(
238 + '[When] a value is projected with --debug [Then] each record is one escaped line and the payload file keeps the event',
239 + () =>
240 + Effect.gen(function* () {
241 + yield* enableListen;
242 + const terminal = redirectedTerminalUI();
243 + yield* cli([
244 + 'listen',
245 + 'composio.connected_account.expired',
246 + '--max-events',
247 + '1',
248 + '--debug',
249 + '--stream',
250 + '.data.note',
251 + ]).pipe(Effect.provide(terminal.layer));
252 +
253 + const stdout = terminal.stdout();
254 + expect(stdout.endsWith('\n')).toBe(true);
255 + const lines = stdout.slice(0, -1).split('\n');
256 + expect(stdout).not.toMatch(dataControl);
257 + expect(lines.map(line => line.split(/[ :]/u)[0])).toEqual([
258 + 'listening',
259 + '[debug]',
260 + '[debug]',
261 + '[debug]',
262 + '[debug]',
263 + 'event',
264 + 'stream',
265 + ]);
266 + expect(lines).toContain(
267 + '[debug] raw event keys: id, type, timestamp, extra\\u0085key, metadata, data'
268 + );
269 + expect(lines.at(-1)).toBe(
270 + 'stream: line one\\u000d\\u000aline two\\u0009tabbed\\u0007 C:\\temp e\u0301 \u{1f600}'
271 + );
272 +
273 + // The preview escapes DEL and C1 in nested keys and values and still decodes to the
274 + // event.
275 + const previewPrefix = '[debug] raw event (truncated): ';
276 + const preview = lines.find(line => line.startsWith(previewPrefix)) ?? '';
277 + expect(preview).toContain('"label\\u007f":"value\\u0085"');
278 + expect(JSON.parse(preview.slice(previewPrefix.length))).toEqual(formattingEvent);
279 +
280 + const { payloadPath, payload, index } = yield* readSavedEvent(lines);
281 + expect(payload).toEqual(formattingEvent);
282 + // The index is appended across runs; this run's entry is the last one.
283 + expect(index.at(-1)?.file_path).toBe(payloadPath);
284 + // stderr is redirected: no decoration, so no copy of the records.
285 + expect(terminal.stderr()).toBe('');
286 + })
287 + );
288 +
289 + it.effect(
290 + '[When] stderr is a terminal and the whole event streams [Then] both sinks get the same escaped record',
291 + () =>
292 + Effect.gen(function* () {
293 + yield* enableListen;
294 + const terminal = redirectedTerminalUI({ decoratedStderr: true });
295 + yield* cli([
296 + 'listen',
297 + 'composio.connected_account.expired',
298 + '--max-events',
299 + '1',
300 + '--stream',
301 + ]).pipe(Effect.provide(terminal.layer));
302 +
303 + const lines = terminal.stdout().slice(0, -1).split('\n');
304 + const streamLines = lines.filter(line => line.startsWith('stream: '));
305 + expect(streamLines).toHaveLength(1);
306 + const record = streamLines[0] ?? '';
307 + expect(record).not.toMatch(dataControl);
308 + expect(JSON.parse(record.slice('stream: '.length))).toEqual(formattingEvent);
309 +
310 + // Raw capture: the decoration renders, carries the same record on one line, and
311 + // writes no escape sequence other than styling.
312 + const stderr = terminal.stderr();
313 + expect(stderr).toContain('│');
314 + expect(stderr.replace(sgr, '')).not.toMatch(dataControl);
315 + expect(stderr.replace(sgr, '')).not.toContain('\u001b');
316 + expect(
317 + stderr
318 + .replace(sgr, '')
319 + .split('\n')
320 + .filter(line => line.includes(record))
321 + ).toHaveLength(1);
322 + expect(stderr).toContain('Stopped after receiving 1 event.');
323 +
324 + const { payload } = yield* readSavedEvent(lines);
325 + expect(payload).toEqual(formattingEvent);
326 + })
327 + );
328 + });
329 +
330 layer(
331 TestLive({
332 baseConfigProvider: testConfigProvider,
ts/packages/cli/test/src/commands/proxy/proxy.cmd.test.ts
+85
@@ -15,6 +15,7 @@ import {
15 import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
16 import * as toolPermissions from 'src/services/tool-permissions';
17 import { cli, MockConsole, TestLive } from 'test/__utils__';
18 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
19
20 const testConfigProvider = ConfigProvider.fromEnv({
21 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
@@ -590,4 +591,88 @@ describe('CLI: composio proxy', () => {
591 );
592 }
593 );
594 +
595 + // Formatting fixtures: standalone controls (BEL, DEL), CR/LF, a lone CR and a tab.
596 + const remoteText = 'first line\r\nsecond\tcol\u0007 \u007f end\rover';
597 +
598 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
599 + '[Given] a text response with controls, stdout redirected and stderr a terminal',
600 + it => {
601 + it.effect('[Then] the note escapes them and stdout gets the body as it is', () =>
602 + Effect.gen(function* () {
603 + const terminal = redirectedTerminalUI({ decoratedStderr: true });
604 + const live = TestLive({
605 + baseConfigProvider: testConfigProvider,
606 + fixture: 'global-test-user-id',
607 + toolRouter: {
608 + proxyExecute: () =>
609 + Effect.succeed({
610 + result_type: 'completed' as const,
611 + status: 200,
612 + data: remoteText,
613 + headers: { 'content-type': 'text/plain' },
614 + }),
615 + },
616 + });
617 +
618 + yield* cli([
619 + 'proxy',
620 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
621 + '--toolkit',
622 + 'gmail',
623 + '--skip-connection-check',
624 + ]).pipe(Effect.provide(terminal.layer), Effect.provide(live));
625 +
626 + expect(terminal.stdout()).toBe(`${remoteText}\n`);
627 + const stderr = terminal.stderr();
628 + expect(stderr).toContain('Proxy Response');
629 + expect(stderr).toContain('first line');
630 + expect(stderr).toContain('second\tcol\\u0007 \\u007f end\\u000dover');
631 + expect(stderr).not.toMatch(/[\u0007\u007f]/u);
632 + })
633 + );
634 + }
635 + );
636 +
637 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
638 + '[Given] a blocked request whose message has controls',
639 + it => {
640 + it.effect('[Then] stderr shows it escaped and the stdout JSON keeps the message', () =>
641 + Effect.gen(function* () {
642 + const terminal = redirectedTerminalUI({ decoratedStderr: true });
643 + const live = TestLive({
644 + baseConfigProvider: testConfigProvider,
645 + fixture: 'global-test-user-id',
646 + toolRouter: {
647 + proxyExecute: () =>
648 + Effect.succeed({
649 + result_type: 'blocked' as const,
650 + reason: { type: 'request_blocked' as const, hook_id: 'policy' },
651 + message: remoteText,
652 + }),
653 + },
654 + });
655 +
656 + const failure = yield* cli([
657 + 'proxy',
658 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
659 + '--toolkit',
660 + 'gmail',
661 + '--skip-connection-check',
662 + ]).pipe(Effect.provide(terminal.layer), Effect.flip, Effect.provide(live));
663 +
664 + expect(failure).toMatchObject({ _tag: 'commands/ProxyRequestError' });
665 + const result = JSON.parse(terminal.stdout()) as { readonly error: string };
666 + expect(result.error).toBe(
667 + `GET proxy call via "gmail" was blocked by session hook "policy": ${remoteText}`
668 + );
669 + const stderr = terminal.stderr();
670 + expect(stderr).toContain(
671 + 'blocked by session hook "policy": first line\\u000d\\u000asecond\\u0009col\\u0007 \\u007f end\\u000dover'
672 + );
673 + expect(stderr).not.toMatch(/[\u0007\u007f]/u);
674 + })
675 + );
676 + }
677 + );
678 });
ts/packages/cli/test/src/commands/tools/execute/tools.execute.cmd.test.ts
+92
@@ -23,6 +23,7 @@ import { parseParallelExecuteArgs } from 'src/commands/tools/execute/tools.execu
23 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
24 import type { ToolkitDetailed } from 'src/models/toolkits';
25 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
26 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
27
28 vi.mock('node:dns/promises', () => ({
29 lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
@@ -3532,4 +3533,95 @@ describe('CLI: composio execute without a resolvable acting user', () => {
3533 })
3534 );
3535 });
3536 +
3537 + // Formatting fixtures: standalone controls (BEL, DEL, NEL), CR/LF and a tab, in keys and values.
3538 + const remoteText = 'first\r\nsecond\tcol\u0007 \u007f \u0085 end';
3539 + /** DEL and C1, which JSON leaves as they are, and any C0 but LF in the printed text. */
3540 + const shownControl = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/u;
3541 +
3542 + layer(
3543 + TestLive({
3544 + baseConfigProvider: testConfigProvider,
3545 + fixture: 'global-test-user-id',
3546 + stdin: { isTTY: true, data: '' },
3547 + toolsExecutor: {
3548 + respondWith: {
3549 + successful: true,
3550 + data: { status: 'failed', error: remoteText, ['note\u0085']: remoteText },
3551 + error: null,
3552 + logId: 'log_formatting',
3553 + },
3554 + },
3555 + })
3556 + )('[Given] a response whose data carries controls', it => {
3557 + it.effect('[Then] the printed JSON escapes them and decodes to the same data', () =>
3558 + Effect.gen(function* () {
3559 + const terminal = redirectedTerminalUI({ decoratedStderr: true });
3560 + yield* cli([
3561 + 'execute',
3562 + 'GMAIL_SEND_EMAIL',
3563 + '--skip-connection-check',
3564 + '-d',
3565 + '{"recipient":"a"}',
3566 + ]).pipe(Effect.provide(terminal.layer));
3567 +
3568 + const stdout = terminal.stdout();
3569 + expect(stdout).not.toMatch(shownControl);
3570 + expect(stdout).toContain('"note\\u0085"');
3571 + const output = JSON.parse(stdout) as { readonly data: unknown };
3572 + expect(output.data).toEqual({
3573 + status: 'failed',
3574 + error: remoteText,
3575 + ['note\u0085']: remoteText,
3576 + });
3577 + // The in-band warning quotes the response on one escaped line.
3578 + expect(terminal.stderr()).toContain(
3579 + 'the response may contain an error: first\\u000d\\u000asecond\\u0009col\\u0007 \\u007f \\u0085 end'
3580 + );
3581 + expect(terminal.stderr()).not.toMatch(/[\u0007\u007f\u0085]/u);
3582 + })
3583 + );
3584 + });
3585 +
3586 + layer(
3587 + TestLive({
3588 + baseConfigProvider: testConfigProvider,
3589 + fixture: 'global-test-user-id',
3590 + stdin: { isTTY: true, data: '' },
3591 + toolsExecutor: {
3592 + failWith: new BadRequestError({
3593 + message: `400 ${remoteText}`,
3594 + method: 'POST',
3595 + url: 'https://mock.invalid/api/v3.1/tools/execute/GMAIL_SEND_EMAIL',
3596 + status: 400,
3597 + requestId: undefined,
3598 + details: { message: remoteText, code: 400, slug: 'Tool_Failed', status: 400 },
3599 + body: undefined,
3600 + }),
3601 + },
3602 + })
3603 + )('[Given] an execution error whose message carries controls', it => {
3604 + it.effect('[Then] stderr shows it escaped and the JSON result keeps the message', () =>
3605 + Effect.gen(function* () {
3606 + const terminal = redirectedTerminalUI({ decoratedStderr: true });
3607 + const exit = yield* Effect.exit(
3608 + cli([
3609 + 'execute',
3610 + 'GMAIL_SEND_EMAIL',
3611 + '--skip-connection-check',
3612 + '-d',
3613 + '{"recipient":"a"}',
3614 + ]).pipe(Effect.provide(terminal.layer))
3615 + );
3616 +
3617 + expect(Exit.isFailure(exit)).toBe(true);
3618 + const stdout = terminal.stdout();
3619 + expect(stdout).not.toMatch(shownControl);
3620 + expect(JSON.parse(stdout)).toMatchObject({ successful: false, error: remoteText });
3621 + const stderr = terminal.stderr();
3622 + expect(stderr).toContain('first\\u000d\\u000asecond\\u0009col\\u0007 \\u007f \\u0085 end');
3623 + expect(stderr).not.toMatch(/[\u0007\u007f\u0085]/u);
3624 + })
3625 + );
3626 + });
3627 });
ts/packages/cli/test/src/commands/triggers/sink-failures.test.ts
+23
@@ -39,4 +39,27 @@ describe('makeSinkFailures', () => {
39 expect(Exit.isSuccess(exit)).toBe(true);
40 })
41 );
42 +
43 + it.effect(
44 + '[Given] a failure message quoting remote text [Then] its warn is one escaped line',
45 + () =>
46 + Effect.gen(function* () {
47 + const terminal = redirectedTerminalUI({ decoratedStderr: true });
48 + yield* Effect.gen(function* () {
49 + const failures = makeSinkFailures({
50 + ui: yield* TerminalUI,
51 + failFast: false,
52 + stop: Effect.void,
53 + summary: count => `${count} failed`,
54 + });
55 + // Formatting fixture: a BEL and CR/LF, as a remote error message could carry them.
56 + yield* failures.record('Forwarding failed: busy\u0007\r\nretry later');
57 + }).pipe(Effect.provide(terminal.layer));
58 +
59 + expect(terminal.stderr()).toContain(
60 + 'Forwarding failed: busy\\u0007\\u000d\\u000aretry later'
61 + );
62 + expect(terminal.stderr()).not.toMatch(/[\u0007\r]/u);
63 + })
64 + );
65 });
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts
+85
@@ -1,6 +1,9 @@
1 import type { ServerResponse } from 'node:http';
2 +import * as os from 'node:os';
3 +import * as nodePath from 'node:path';
4 import { describe, expect, layer } from '@effect/vitest';
5 import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
6 +import * as FileSystem from 'effect/FileSystem';
7 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
8 import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
9 import { makeShutdownController, ShutdownSignal } from 'src/services/shutdown-signal';
@@ -33,6 +36,24 @@ const failingRealtime = Layer.succeed(
36 })
37 );
38
39 +// Formatting fixtures: standalone controls (BEL, DEL, NEL), CR/LF and a tab in a trigger event.
40 +const formattingEvent = {
41 + id: 'msg_formatting_1',
42 + type: 'composio.trigger.message',
43 + timestamp: '2026-04-06T18:00:00.000Z',
44 + metadata: {
45 + trigger_slug: 'GM\u0007AIL_NEW',
46 + trigger_id: 'ti_1\u0085',
47 + connected_account_id: 'ca\r\n1',
48 + },
49 + data: { subject: 'hello\u007f', body: 'line\r\nnext\tcol' },
50 +};
51 +
52 +/** Any C0, DEL or C1 code point but the line feed that ends a line. */
53 +const dataControl = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/u;
54 +/** SGR styling, the only escape sequence the CLI writes on its own. */
55 +const sgr = /\u001b\[[0-9;]*m/gu;
56 +
57 describe('CLI: composio dev listen', () => {
58 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
59 '[Given] the realtime subscription fails',
@@ -373,4 +394,68 @@ describe('CLI: composio dev listen', () => {
394 })
395 );
396 });
397 +
398 + layer(
399 + TestLive({
400 + baseConfigProvider: testConfigProvider,
401 + fixture: 'global-test-user-id',
402 + realtimeData: { events: [formattingEvent] },
403 + })
404 + )('[Given] an event whose fields carry controls and line breaks', it => {
405 + it.effect('[When] --table [Then] each cell is escaped before the row is styled', () =>
406 + Effect.gen(function* () {
407 + yield* enableListen;
408 + const terminal = redirectedTerminalUI({ decoratedStderr: true });
409 + yield* cli(['dev', 'listen', '--table', '--max-events', '1']).pipe(
410 + Effect.provide(terminal.layer)
411 + );
412 +
413 + const lines = terminal.stdout().slice(0, -1).split('\n');
414 + expect(lines).toHaveLength(2);
415 + const row = lines[1] ?? '';
416 + expect(row.replace(sgr, '')).not.toMatch(dataControl);
417 + expect(row.replace(sgr, '')).not.toContain('\u001b');
418 + expect(row.replace(sgr, '').split(' ').filter(Boolean)).toEqual([
419 + '2026-04-06T18:00:00.000Z',
420 + 'ti_1\\u0085',
421 + 'GM\\u0007AIL_NEW',
422 + // The 8-column toolkit cell truncates what is shown, escape included.
423 + 'GM\\u0...',
424 + '-',
425 + 'ca\\u000d\\u000a1',
426 + ]);
427 + })
428 + );
429 +
430 + it.effect(
431 + '[When] --json --out [Then] the terminal shows escaped JSON and the file keeps the event',
432 + () =>
433 + Effect.gen(function* () {
434 + yield* enableListen;
435 + const fs = yield* FileSystem.FileSystem;
436 + const directory = yield* fs.makeTempDirectoryScoped({
437 + directory: os.tmpdir(),
438 + prefix: 'composio-dev-listen-formatting-',
439 + });
440 + const outFile = nodePath.join(directory, 'events.jsonl');
441 + const terminal = redirectedTerminalUI({ decoratedStderr: true });
442 + yield* cli(['dev', 'listen', '--json', '--out', outFile, '--max-events', '1']).pipe(
443 + Effect.provide(terminal.layer)
444 + );
445 +
446 + const stdout = terminal.stdout();
447 + expect(stdout.split('\n')).toHaveLength(2);
448 + expect(stdout).not.toMatch(dataControl);
449 + expect(JSON.parse(stdout)).toEqual(formattingEvent);
450 +
451 + const stderr = terminal.stderr().replace(sgr, '');
452 + expect(stderr).not.toMatch(dataControl);
453 + expect(stderr).toContain('Trigger: GM\\u0007AIL_NEW');
454 + expect(stderr).toContain('Connected Account: ca\\u000d\\u000a1');
455 + expect(stderr).toContain('"subject": "hello\\u007f"');
456 +
457 + expect(yield* fs.readFileString(outFile)).toBe(`${JSON.stringify(formattingEvent)}\n`);
458 + })
459 + );
460 + });
461 });
ts/packages/cli/test/src/invocation/report-invocation-failure.test.ts
+72 -2
@@ -1,8 +1,9 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import { Cause, Console, Effect, Exit, Layer } from 'effect';
2 +import { Cause, Console, Data, Effect, Exit, Layer } from 'effect';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
5 -import { APIConnectionTimeoutError } from '@composio/client/effect';
5 +import { APIConnectionTimeoutError, AuthenticationError } from '@composio/client/effect';
6 +import { ExpectedFailure } from 'src/effects/expected-failure';
7 import { ReportedFailure } from 'src/effects/report-failure';
8 import { requestError } from 'src/effects/request-error';
9 import { retryHint, TEMPORARY_FAILURE_EXIT_CODE } from 'src/effects/retry-advice';
@@ -26,6 +27,17 @@ const report = (cause: Cause.Cause<unknown>) =>
27 return { exit, stderr };
28 }).pipe(Effect.provide(TestLayer));
29
30 +// Standalone controls (BEL, DEL, NEL) and line breaks, as a remote message could carry them.
31 +const remoteText = 'remote\u0007text\u007f\u0085';
32 +
33 +class RemoteExpectedFailure extends Data.TaggedError('test/RemoteExpectedFailure')<{
34 + readonly message: string;
35 +}> {
36 + get [ExpectedFailure]() {
37 + return true;
38 + }
39 +}
40 +
41 const failureOf = (exit: Exit.Exit<unknown, unknown>) =>
42 Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
43
@@ -99,4 +111,62 @@ describe('reportInvocationFailure', () => {
111 expect(stderr.join('\n')).not.toContain(retryHint('safe'));
112 })
113 );
114 +
115 + it.effect(
116 + '[Given] an expected failure quoting remote text [Then] its controls print as escapes and it exits 1',
117 + () =>
118 + Effect.gen(function* () {
119 + const failure = new RemoteExpectedFailure({
120 + message: `Request failed: ${remoteText}\r\nRun the command again.\rdone`,
121 + });
122 +
123 + const { exit, stderr } = yield* report(Cause.fail(failure));
124 +
125 + expect(failureOf(exit)).toBe(failure);
126 + expect(exitCodeOf(exit)).toBe(1);
127 + // CRLF stays a line break; a lone CR does not.
128 + expect(stderr).toEqual([
129 + 'Request failed: remote\\u0007text\\u007f\\u0085\nRun the command again.\\u000ddone',
130 + ]);
131 + })
132 + );
133 +
134 + it.effect(
135 + '[Given] a 401 whose backend message has controls [Then] it prints as one escaped line',
136 + () =>
137 + Effect.gen(function* () {
138 + const failure = new AuthenticationError({
139 + message: '401 Unauthorized',
140 + method: 'GET',
141 + url: 'https://backend.composio.dev/api/v3.1/toolkits',
142 + status: 401,
143 + requestId: undefined,
144 + details: {
145 + message: `Key\nrejected ${remoteText}`,
146 + code: 401,
147 + slug: 'unauthorized',
148 + status: 401,
149 + },
150 + body: undefined,
151 + });
152 +
153 + const { exit, stderr } = yield* report(Cause.fail(failure));
154 +
155 + expect(exitCodeOf(exit)).toBe(1);
156 + expect(stderr[0]).toBe('Key\\u000arejected remote\\u0007text\\u007f\\u0085');
157 + })
158 + );
159 +
160 + it.effect(
161 + '[Given] a multiline defect message [Then] the error title preserves line breaks and escapes unsafe controls',
162 + () =>
163 + Effect.gen(function* () {
164 + const { exit, stderr } = yield* report(Cause.die(new Error(`boom\n${remoteText}\rdone`)));
165 +
166 + expect(exitCodeOf(exit)).toBe(1);
167 + expect(stderr).toHaveLength(1);
168 + expect(stderr[0]).toContain('boom\nremote\\u0007text\\u007f\\u0085\\u000ddone');
169 + expect(stderr[0]).not.toMatch(/[\u0007\u007f\u0085]/u);
170 + })
171 + );
172 });
ts/packages/cli/test/src/services/terminal-ui.test.ts
+32
@@ -12,6 +12,7 @@ import {
12 makeTerminalUI,
13 TerminalUI,
14 } from 'src/services/terminal-ui';
15 +import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
16 import { TestLive, MockConsole } from 'test/__utils__';
17
18 vi.mock('@clack/prompts', async importOriginal => {
@@ -278,6 +279,37 @@ describe('TerminalUI', () => {
279 );
280 });
281
282 + describe('escaping external text for display', () => {
283 + // Formatting fixtures: standalone controls at each range edge, CR/LF and a tab.
284 + const controls = '\u0000 \u0007 \u001f \u007f \u0080 \u0085 \u009f';
285 +
286 + it('escapes C0, DEL and C1 controls as JSON-style escapes on one line', () => {
287 + expect(escapeTerminalText(`a${controls}b`)).toBe(
288 + 'a\\u0000 \\u0007 \\u001f \\u007f \\u0080 \\u0085 \\u009fb'
289 + );
290 + expect(escapeTerminalText('one\r\ntwo\tthree')).toBe('one\\u000d\\u000atwo\\u0009three');
291 + });
292 +
293 + it('keeps printable text, backslashes, combining marks and astral characters', () => {
294 + const printable = 'plain C:\\temp \\u0007 e\u0301 \u{1f600} \u00a0 \u00e9';
295 + expect(escapeTerminalText(printable)).toBe(printable);
296 + expect(escapeTerminalLines(printable)).toBe(printable);
297 + });
298 +
299 + it('keeps LF and TAB in multiline text, folds CRLF and escapes a lone CR', () => {
300 + expect(escapeTerminalLines('one\r\ntwo\tcol\rthree\n\u0007')).toBe(
301 + 'one\ntwo\tcol\\u000dthree\n\\u0007'
302 + );
303 + });
304 +
305 + it('keeps serialized JSON decodable to the same value', () => {
306 + const value = { 'key\u0085': 'v\u007f\u0007', lines: 'a\r\nb', nested: [{ c: '\u0086' }] };
307 + const shown = escapeTerminalLines(JSON.stringify(value, null, 2));
308 + expect(shown).not.toMatch(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/u);
309 + expect(JSON.parse(shown)).toEqual(value);
310 + });
311 + });
312 +
313 describe('clampSpinnerMessage keeps live spinner messages on one terminal row', () => {
314 it('leaves a message that fits untouched', () => {
315 expect(clampSpinnerMessage(80, 'Checking for updates')).toBe('Checking for updates');