@devries-cameron20 / composio-1 / commits / 24231bc3f
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.

fix(cli): proxy reads stdin only with -d -, execute fails on a silent stdin pipe (#5466)

## Why Agents calling `composio proxy` to the Gmail and Drive APIs saw some calls hang for minutes with no output, while identical calls returned normally. The agent waited instead of timing out. The ask was to fix the CLI so these calls stop hanging silently. Server logs show every proxy call that reached the backend returned in under a second, and no request arrived while the agent was stuck. So the hang happened in the CLI, before any request was sent. ## Root cause Without `-d`, `composio execute` and `composio proxy` read stdin whenever it is not a terminal, waiting for end of input with no timeout. Agent harnesses often run commands with a stdin pipe they never write to or close, so the command blocked before sending anything. ## Fix An earlier revision of this PR treated a pipe that stayed silent for 1 second as no input. Review pointed out that this trades the hang for silent data loss: `execute` could run a tool with `{}` while its arguments were still on their way. This revision takes a different approach: - **`proxy`** reads a request body from stdin only with `-d -` (or `-d @-`). Without `-d` it never touches stdin, so a proxied GET returns at once. This removes the root cause rather than bounding it. - **`execute`** still reads piped JSON without `-d`, since that is documented. A pipe that sends nothing within 1 second (`PIPED_STDIN_SILENCE_TIMEOUT`) now fails with `No input arrived on stdin within 1 second. Pass the arguments with -d '{...}', or -d - to wait for stdin.` and exits 1, without running the tool. - **`-d -`** (and `-d @-`) still waits for stdin as long as it takes, for both commands. - **`listen`** resolves `-p` through the explicit path. It never used the implicit stdin read. The trade-off: `slow_cmd | composio execute X` with no `-d`, where the first byte takes over a second, now fails and says to pass `-d -`. That is the behavior review asked for, in place of running the tool without arguments. ## Tests - `test/src/services/stdin.test.ts` drives the real reader (`readStdinToEnd`) over a `PassThrough` with fake timers: - a silent pipe gives up at the timeout - a first byte after the timeout gives up and leaves the data unread - empty end of input returns an empty string - data before the timeout is read to a late end of input - with no timeout, it waits for a late end of input - The test `Stdin` can now run that real reader over a `PassThrough` (`makeStreamStdin`). Over it: - `proxy` with a held-open pipe sends the request without reading it. I checked that this test hangs when the old implicit read is put back. - `proxy -d -` reads a body that arrives after 1.5 s. - `proxy -d @-` reads stdin. - `execute` with a silent pipe fails and never calls the executor. - `execute` whose JSON arrives after the timeout fails and never runs the tool with `{}`. ## Verification I built the binary from this branch and from `origin/next` and ran both against a local mock backend: | Scenario | `origin/next` | This PR | | --- | --- | --- | | `sleep 25 \| composio proxy …/users/me/profile --toolkit gmail` | exit 0 after 25,039 ms (waited for the pipe to close) | exit 0 after 337 ms, GET sent with no body | | `{ sleep 2; echo '{"owner":"x"}'; } \| composio execute GITHUB_GET_REPOS` | ran after 2,066 ms (would wait forever on a pipe that never closes) | exit 1 after 1,279 ms with the error above; tool not run | | `sleep 25 \| composio execute GITHUB_GET_REPOS` | waits until the pipe closes | exit 1 after 1,307 ms; tool not run | | `echo '{"owner":"x"}' \| composio execute GITHUB_GET_REPOS` | runs with `{"owner":"x"}` | runs with `{"owner":"x"}` in 367 ms | | `{ sleep 2; echo '{"raw":"abc"}'; } \| composio proxy … -X POST -d -` | — | waits, then sends the body (2,054 ms) | Other checks: - `pnpm test` in `ts/packages/cli`: 230 files, 3,236 tests passed. I ran it with the `CLAUDE*` environment unset; otherwise `cli-main.test.ts` picks up the agent-host plugin tip on stderr. - `pnpm run typecheck` and `pnpm run lint:effect` are clean. CLI notes are in `ts/packages/cli/CHANGELOG.md`. There's no changeset, because `@composio/cli` is ignored by Changesets. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Rayane Boussanni [zen] <rayane@composio.dev> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: jkomyno <alberto@composio.dev>

composio-zen[bot] committed Nov 19, 2026 at 17:36 UTC 24231bc3f0c95d416b61fa21d288dbd2fb1d68a8
13 files changed +378 -87
.agents/skills/cli-command/references/data-and-lifecycle.md
+1 -1
@@ -13,7 +13,7 @@
13
14 A command serializes its machine result before calling `output`. A command without a separate human renderer uses `force: true` when its data must remain visible on a terminal. Output consumers must follow that command's contract. `proxy` can return text or JSON, while listeners emit a stream rather than one JSON document.
15
16 -[resolveOptionalTextInput](../../../../ts/packages/cli/src/effects/resolve-optional-text-input.ts) handles a literal string, `@file`, explicit `-` for stdin, or implicit piped stdin when no value is supplied. A file or explicit value takes precedence over implicit stdin. The helper returns text or the configured missing-value fallback. The command validates supplied data with its own parser and schema before using it.
16 +[resolveExplicitTextInput](../../../../ts/packages/cli/src/effects/resolve-optional-text-input.ts) resolves an input flag: a literal string, `@file`, or `-` / `@-` to read stdin to end of input. With no flag it returns `undefined` and never reads stdin, so a command such as `proxy` or `listen` cannot wait on a pipe it was handed. `composio execute` alone also reads JSON piped without `-d` (`resolveInput` in `tools.execute.arguments.ts`) and fails when the pipe sends nothing within `PIPED_STDIN_SILENCE_TIMEOUT`. The command validates supplied data with its own parser and schema before using it.
17
18 [Stdin.readAll](../../../../ts/packages/cli/src/services/stdin.ts) buffers size-limited input until end of input (EOF). It is not a reader for an unlimited event stream. A producer that never closes stdin keeps the command waiting. `TestLive({ stdin: { isTTY: false, data: '...' } })` supplies finite test input without consuming the test runner's stdin.
19
ts/packages/cli/CHANGELOG.md
+4
@@ -8,6 +8,10 @@
8
9 - Release archives now include a `release-manifest.json` that lists the support files they ship. `composio upgrade` installs exactly what the manifest lists, so later releases can drop a support file without breaking upgrades. Files a release no longer lists stay in place. A release can name the oldest CLI version that may upgrade to it; an older CLI refuses it before changing anything and prints the install command to run instead.
10
11 +- Agents calling `composio proxy` or `composio execute` without `-d` no longer hang for minutes with no output. Agent harnesses often run commands with a stdin pipe they never write to or close, and both commands waited for that pipe to end before sending anything.
12 + - `composio proxy` reads a request body from stdin only with `-d -` (or `-d @-`). Without `-d` it sends the request without touching stdin, so a proxied GET returns at once. Any method but `GET` without `-d` from a non-terminal stdin warns on stderr that it is sent without a body, since piped input is no longer used as one.
13 + - `composio execute` still reads piped JSON arguments without `-d`. A pipe that sends nothing within 1 second now fails with `No input arrived on stdin within 1 second` and exit code 1, without running the tool, rather than running it with `{}` while the arguments may still be on their way. Pass the arguments with `-d '{...}'`, or `-d -` to wait for stdin as long as it takes.
14 +
15 - Update @composio/client to 2.1.35 to include the latest API changes.
16
17 - `composio listen --stream` shows control characters, including embedded tabs and line breaks,
ts/packages/cli/src/commands/listen/listen.handler.ts
+2 -7
@@ -12,7 +12,7 @@ import {
12 makeSinkFailures,
13 } from 'src/commands/triggers/sink-failures';
14 import { reportFailure } from 'src/effects/report-failure';
15 -import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
15 +import { resolveExplicitTextInput } from 'src/effects/resolve-optional-text-input';
16 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
17 import {
18 resolveArtifactsRoot,
@@ -80,9 +80,6 @@ const disableTemporaryTrigger = (params: {
80
81 const isProjectEventType = (value: string): boolean => value.startsWith('composio.');
82
83 -const resolveParamsInput = (input: Option.Option<string>) =>
84 - resolveOptionalTextInput(input, { missingValue: '{}' });
85 -
83 const assertSupportedListenParams = (params: {
84 listeningToProjectEvent: boolean;
85 slug: string;
@@ -224,9 +221,7 @@ const resolveListenSetup = (params: {
221 Effect.gen(function* () {
222 const consumerUserId = params.consumerUserId;
223 const listeningToProjectEvent = isProjectEventType(params.slug);
227 - const rawParams = Option.isSome(params.inputParams)
228 - ? (yield* resolveParamsInput(params.inputParams))?.trim() || '{}'
229 - : '{}';
224 + const rawParams = (yield* resolveExplicitTextInput(params.inputParams))?.trim() || '{}';
225 const createParamsInput = yield* Effect.fromResult(parseCreateParams(rawParams));
226 yield* assertSupportedListenParams({
227 listeningToProjectEvent,
ts/packages/cli/src/commands/proxy/proxy.handler.ts
+14 -5
@@ -1,6 +1,6 @@
1 import { Effect, Result, Option } from 'effect';
2 import type { SessionProxyExecuteParams } from '@composio/client/resources/tool-router/session';
3 -import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
3 +import { resolveExplicitTextInput } from 'src/effects/resolve-optional-text-input';
4 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
5 import { gateToolExecution } from 'src/services/tool-permissions';
6 import {
@@ -10,7 +10,8 @@ import {
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';
13 +import { actingUser, warnOnStderr } from 'src/commands/surface';
14 +import { Stdin } from 'src/services/stdin';
15 import {
16 ComposioNoActiveConnectionError,
17 mapComposioError,
@@ -72,8 +73,6 @@ export const parseProxyHeader = (value: string): { name: string; value: string }
73 return { name, value: headerValue };
74 };
75
75 -const resolveBodyInput = (input: Option.Option<string>) => resolveOptionalTextInput(input);
76 -
76 export const parseProxyBody = (raw: string): unknown =>
77 Result.getOrElse(parseJsonRecord(raw), (): unknown => raw);
78
@@ -195,7 +194,17 @@ export const runProxy = (params: ProxyParams) =>
194 };
195 }
196 );
198 - const rawBody = yield* resolveBodyInput(data);
197 + // Only `-d -` reads stdin: reading a pipe the caller left open would hang the request before
198 + // it is sent, and agents run with such pipes.
199 + const rawBody = yield* resolveExplicitTextInput(data);
200 + if (rawBody === undefined && normalizedMethod !== 'GET' && !(yield* Stdin).isTTY()) {
201 + // A body piped in without `-d` used to be sent; say why it no longer is, without reading
202 + // stdin, which an agent harness may hold open. A GET stays quiet: it is the bodiless read
203 + // agents run with such a pipe, and a warning on every one would be noise.
204 + yield* warnOnStderr(
205 + 'Sending the request without a body: composio proxy reads stdin only with -d -. Pass -d - to send piped input as the body.'
206 + );
207 + }
208 const parsedBody = rawBody === undefined ? undefined : parseProxyBody(rawBody);
209
210 const result = yield* ui.withSpinner(
ts/packages/cli/src/commands/tools/execute/tools.execute.arguments.ts
+33 -5
@@ -1,5 +1,6 @@
1 -import { Effect, Option, Result } from 'effect';
2 -import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
1 +import { Duration, Effect, Option, Result } from 'effect';
2 +import { resolveExplicitTextInput } from 'src/effects/resolve-optional-text-input';
3 +import { Stdin } from 'src/services/stdin';
4 import {
5 findFileUploadablePaths,
6 schemaHasFileUploadable,
@@ -8,10 +9,37 @@ import {
9 import { isPlainRecord, parseJsonRecord } from 'src/utils/parse-json';
10 import { invalidArguments, ToolExecutionError } from './tools.execute.errors';
11
12 +/**
13 + * How long `composio execute` waits for piped JSON to start arriving when it got no `-d`. An
14 + * agent harness can hand the CLI a pipe it never writes to or closes; waiting for its end would
15 + * hang the command with no output.
16 + */
17 +export const PIPED_STDIN_SILENCE_TIMEOUT = Duration.seconds(1);
18 +
19 +/**
20 + * The tool arguments: `-d` as `resolveExplicitTextInput` reads it, else JSON piped on stdin, else
21 + * `{}` when stdin is a terminal (e.g. tools with no required args).
22 + */
23 export const resolveInput = (input: Option.Option<string>) =>
12 - resolveOptionalTextInput(input, {
13 - // Default to empty object when no data provided (e.g. tools with no required args)
14 - missingValue: '{}',
24 + Effect.gen(function* () {
25 + if (Option.isSome(input)) {
26 + return (yield* resolveExplicitTextInput(input)) ?? '{}';
27 + }
28 + const stdin = yield* Stdin;
29 + if (stdin.isTTY()) {
30 + return '{}';
31 + }
32 + const piped = yield* stdin.readAllUnlessSilent(PIPED_STDIN_SILENCE_TIMEOUT);
33 + if (Option.isNone(piped)) {
34 + // Running the tool with `{}` could act without the arguments still on their way.
35 + return yield* Effect.fail(
36 + invalidArguments(
37 + "No input arrived on stdin within 1 second. Pass the arguments with -d '{...}', or -d - to wait for stdin.",
38 + '--data'
39 + )
40 + );
41 + }
42 + return piped.value;
43 });
44
45 export const parseArguments = (raw: string) =>
ts/packages/cli/src/commands/tools/execute/tools.execute.context.ts
+1 -1
@@ -74,7 +74,7 @@ export const resolveExecuteContext = (
74 Effect.gen(function* () {
75 const ui = yield* TerminalUI;
76 const executor = yield* ToolsExecutor;
77 - const input = (yield* resolveInput(params.data)) ?? '{}';
77 + const input = yield* resolveInput(params.data);
78 const parsedArgs = yield* parseArguments(input);
79 const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
80
ts/packages/cli/src/effects/read-stdin.ts
+2 -10
@@ -1,16 +1,8 @@
1 -import { Effect, Option } from 'effect';
1 +import { Effect } from 'effect';
2 import { Stdin } from 'src/services/stdin';
3
4 +/** Reads stdin to its end, however long that takes; for an explicit `-d -`. */
5 export const readStdin = Effect.gen(function* () {
6 const stdin = yield* Stdin;
7 return yield* stdin.readAll();
8 });
8 -
9 -export const readStdinIfPiped = Effect.gen(function* () {
10 - const stdin = yield* Stdin;
11 - if (stdin.isTTY()) {
12 - return Option.none<string>();
13 - }
14 - const data = yield* stdin.readAll();
15 - return Option.some(data);
16 -});
ts/packages/cli/src/effects/resolve-optional-text-input.ts
+27 -37
@@ -1,45 +1,35 @@
1 import { Effect, FileSystem, Option } from 'effect';
2 import { CliError } from 'effect/cli';
3
4 -import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';
4 +import { readStdin } from 'src/effects/read-stdin';
5
6 -type ResolveOptionalTextInputOptions = {
7 - readonly missingValue?: string;
8 -};
9 -
10 -export const resolveOptionalTextInput = (
11 - input: Option.Option<string>,
12 - options: ResolveOptionalTextInputOptions = {}
13 -) =>
6 +/**
7 + * Resolves an input flag such as `-d`: `-` or `@-` reads stdin to its end, `@path` reads the
8 + * file, anything else is the value itself. No flag means no input; stdin is never read then.
9 + */
10 +export const resolveExplicitTextInput = (input: Option.Option<string>) =>
11 Effect.gen(function* () {
15 - const fs = yield* FileSystem.FileSystem;
16 -
17 - if (Option.isSome(input)) {
18 - const value = input.value.trim();
19 - if (value === '-') {
20 - return yield* readStdin;
21 - }
22 - if (value.startsWith('@')) {
23 - const filePath = value.slice(1).trim();
24 - if (!filePath) {
25 - return yield* Effect.fail(
26 - new CliError.InvalidValue({
27 - option: 'data',
28 - value,
29 - expected: 'a file path after "@"',
30 - kind: 'flag',
31 - })
32 - );
33 - }
34 - return yield* fs.readFileString(filePath, 'utf-8');
35 - }
36 - return value;
12 + if (Option.isNone(input)) {
13 + return undefined;
14 }
38 -
39 - const piped = yield* readStdinIfPiped;
40 - if (Option.isSome(piped)) {
41 - return piped.value;
15 + const value = input.value.trim();
16 + if (value === '-' || value === '@-') {
17 + return yield* readStdin;
18 }
43 -
44 - return options.missingValue;
19 + if (value.startsWith('@')) {
20 + const filePath = value.slice(1).trim();
21 + if (!filePath) {
22 + return yield* Effect.fail(
23 + new CliError.InvalidValue({
24 + option: 'data',
25 + value,
26 + expected: 'a file path after "@"',
27 + kind: 'flag',
28 + })
29 + );
30 + }
31 + const fs = yield* FileSystem.FileSystem;
32 + return yield* fs.readFileString(filePath, 'utf-8');
33 + }
34 + return value;
35 });
ts/packages/cli/src/services/stdin.ts
+55 -16
@@ -1,5 +1,5 @@
1 import process from 'node:process';
2 -import { Context, Effect, Layer } from 'effect';
2 +import { Context, Duration, Effect, Layer, Option } from 'effect';
3
4 const MAX_STDIN_SIZE = 10 * 1024 * 1024; // 10 MB
5
@@ -13,16 +13,32 @@ export class StdinSizeLimitError extends Error {
13 export interface Stdin {
14 readonly isTTY: () => boolean;
15 readonly readAll: () => Effect.Effect<string, Error>;
16 + /**
17 + * Reads stdin to its end, unless stdin stays silent (no data and no end of input) for
18 + * `silenceTimeout`: then it stops listening and returns none. Once the first chunk or the end
19 + * of input arrives, it waits for the rest without a timeout.
20 + */
21 + readonly readAllUnlessSilent: (
22 + silenceTimeout: Duration.Duration
23 + ) => Effect.Effect<Option.Option<string>, Error>;
24 }
25
26 export const Stdin = Context.Service<Stdin>('services/Stdin');
27
20 -const readAll = (): Promise<string> =>
28 +/**
29 + * Reads a stdin stream to its end. Resolves `undefined` when `silenceTimeoutMs` passes before
30 + * any data or the end of input arrives.
31 + */
32 +export const readStdinToEnd = (
33 + input: NodeJS.ReadableStream,
34 + silenceTimeoutMs?: number
35 +): Promise<string | undefined> =>
36 new Promise((resolve, reject) => {
37 const chunks: string[] = [];
38 let totalLength = 0;
39
40 const onData = (chunk: string) => {
41 + clearTimeout(silenceTimer);
42 totalLength += chunk.length;
43 if (totalLength > MAX_STDIN_SIZE) {
44 cleanup();
@@ -42,27 +58,50 @@ const readAll = (): Promise<string> =>
58 reject(error);
59 };
60
61 + const onSilence = () => {
62 + cleanup();
63 + // An agent harness or task runner can hand the CLI a pipe it never writes to or closes;
64 + // waiting for its end would hang the command with no output.
65 + input.pause();
66 + resolve(undefined);
67 + };
68 +
69 const cleanup = () => {
46 - process.stdin.off('data', onData);
47 - process.stdin.off('end', onEnd);
48 - process.stdin.off('error', onError);
70 + clearTimeout(silenceTimer);
71 + input.off('data', onData);
72 + input.off('end', onEnd);
73 + input.off('error', onError);
74 };
75
51 - process.stdin.setEncoding('utf8');
52 - process.stdin.on('data', onData);
53 - process.stdin.on('end', onEnd);
54 - process.stdin.on('error', onError);
55 - process.stdin.resume();
76 + const silenceTimer =
77 + silenceTimeoutMs === undefined ? undefined : setTimeout(onSilence, silenceTimeoutMs);
78 +
79 + input.setEncoding('utf8');
80 + input.on('data', onData);
81 + input.on('end', onEnd);
82 + input.on('error', onError);
83 + input.resume();
84 });
85
58 -export const StdinLive = Layer.succeed(
59 - Stdin,
86 +const toStdinError = (e: unknown) => (e instanceof Error ? e : new Error(String(e)));
87 +
88 +/** A `Stdin` that reads `input`: `process.stdin` in `StdinLive`, a `PassThrough` in tests. */
89 +export const makeStreamStdin = (input: NodeJS.ReadableStream, isTTY: () => boolean): Stdin =>
90 Stdin.of({
61 - isTTY: () => !!process.stdin.isTTY,
91 + isTTY,
92 readAll: () =>
93 Effect.tryPromise({
64 - try: readAll,
65 - catch: e => (e instanceof Error ? e : new Error(String(e))),
94 + try: () => readStdinToEnd(input).then(text => text ?? ''),
95 + catch: toStdinError,
96 }),
67 - })
97 + readAllUnlessSilent: silenceTimeout =>
98 + Effect.tryPromise({
99 + try: () => readStdinToEnd(input, Duration.toMillis(silenceTimeout)),
100 + catch: toStdinError,
101 + }).pipe(Effect.map(Option.fromUndefinedOr)),
102 + });
103 +
104 +export const StdinLive = Layer.succeed(
105 + Stdin,
106 + makeStreamStdin(process.stdin, () => !!process.stdin.isTTY)
107 );
ts/packages/cli/test/__utils__/services/test-layer.ts
+13 -5
@@ -72,7 +72,7 @@ import type {
72 SessionSearchParams,
73 SessionToolkitsParams,
74 } from '@composio/client/resources/tool-router';
75 -import { Stdin } from 'src/services/stdin';
75 +import { makeStreamStdin, Stdin } from 'src/services/stdin';
76 import { ProjectContext } from 'src/services/project-context';
77 import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
78 import type { CommandRunnerShape } from 'src/services/command-runner';
@@ -185,6 +185,11 @@ export interface TestLiveInput {
185 stdin?: {
186 isTTY: boolean;
187 data: string;
188 + /**
189 + * Reads this stream with the real stdin reader instead of returning `data`: a `PassThrough`
190 + * the test writes to (or leaves open, like an agent harness can) when timing matters.
191 + */
192 + stream?: NodeJS.ReadableStream;
193 };
194
195 /**
@@ -488,10 +493,13 @@ export const TestLayer = (input?: TestLiveInput) =>
493
494 const StdinTest = Layer.succeed(
495 Stdin,
491 - Stdin.of({
492 - isTTY: () => input?.stdin?.isTTY ?? true,
493 - readAll: () => Effect.succeed(input?.stdin?.data ?? ''),
494 - })
496 + input?.stdin?.stream === undefined
497 + ? Stdin.of({
498 + isTTY: () => input?.stdin?.isTTY ?? true,
499 + readAll: () => Effect.succeed(input?.stdin?.data ?? ''),
500 + readAllUnlessSilent: () => Effect.succeed(Option.some(input?.stdin?.data ?? '')),
501 + })
502 + : makeStreamStdin(input.stdin.stream, () => input.stdin?.isTTY ?? true)
503 );
504
505 // --- Tool Router mock (ComposioClientSingleton) ---
ts/packages/cli/test/src/commands/proxy/proxy.cmd.test.ts
+95
@@ -2,6 +2,7 @@ import { BadRequestError, type RequestOptions } from '@composio/client/effect';
2 import { describe, expect, it, layer } from '@effect/vitest';
3 import { ConfigProvider, Effect, Option } from 'effect';
4 import { afterEach, vi } from 'vitest';
5 +import { PassThrough } from 'node:stream';
6 import type {
7 SessionCreateParams,
8 SessionProxyExecuteParams,
@@ -49,6 +50,100 @@ describe('CLI: composio proxy', () => {
50 expect(parseProxyBody('plain text')).toBe('plain text');
51 });
52
53 + describe('[Given] stdin is a pipe', () => {
54 + /** Runs `composio proxy` over `stdin` and returns the body it sent to proxy_execute. */
55 + const proxyBodyOver = (stdin: PassThrough, args: ReadonlyArray<string>) =>
56 + Effect.gen(function* () {
57 + let sentParams: SessionProxyExecuteParams | undefined;
58 + const live = TestLive({
59 + baseConfigProvider: testConfigProvider,
60 + fixture: 'global-test-user-id',
61 + stdin: { isTTY: false, data: '', stream: stdin },
62 + toolRouter: {
63 + proxyExecute: (_sessionId: string, params: SessionProxyExecuteParams) =>
64 + Effect.sync(() => {
65 + sentParams = params;
66 + return {
67 + result_type: 'completed' as const,
68 + status: 200,
69 + data: { ok: true },
70 + headers: {},
71 + };
72 + }),
73 + },
74 + });
75 + const output = yield* Effect.gen(function* () {
76 + yield* cli([
77 + 'proxy',
78 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
79 + '--toolkit',
80 + 'gmail',
81 + ...args,
82 + ]);
83 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
84 + return lines.join('\n');
85 + }).pipe(Effect.provide(live));
86 + expect(sentParams).toBeDefined();
87 + return { body: sentParams?.body, output };
88 + });
89 +
90 + it.live(
91 + '[When] it is held open and no -d is passed [Then] the request is sent without reading it',
92 + () =>
93 + Effect.gen(function* () {
94 + const heldOpen = new PassThrough();
95 + heldOpen.write('{"never":"read"}');
96 +
97 + const { body, output } = yield* proxyBodyOver(heldOpen, []);
98 +
99 + expect(body).toBeUndefined();
100 + expect(heldOpen.readableLength).toBeGreaterThan(0);
101 + expect(output).not.toContain('Sending the request without a body');
102 + })
103 + );
104 +
105 + // A bodiless GET is the read agents run with a held-open pipe, so only the other methods warn.
106 + it.live.each(['POST', 'PUT', 'PATCH', 'DELETE'])(
107 + '[When] a %s is sent without -d [Then] it warns that piped input is not the body, without reading it',
108 + method =>
109 + Effect.gen(function* () {
110 + const piped = new PassThrough();
111 + piped.write('{"meant":"as body"}');
112 +
113 + const { body, output } = yield* proxyBodyOver(piped, ['-X', method]);
114 +
115 + expect(body).toBeUndefined();
116 + expect(piped.readableLength).toBeGreaterThan(0);
117 + expect(output).toContain(
118 + 'Sending the request without a body: composio proxy reads stdin only with -d -. Pass -d - to send piped input as the body.'
119 + );
120 + })
121 + );
122 +
123 + it.live('[When] -d - is passed [Then] the body is read from stdin', () =>
124 + Effect.gen(function* () {
125 + const piped = new PassThrough();
126 + setTimeout(() => piped.end('{"message":{"raw":"abc"}}'), 1500);
127 +
128 + const { body, output } = yield* proxyBodyOver(piped, ['-X', 'POST', '-d', '-']);
129 +
130 + expect(body).toEqual({ message: { raw: 'abc' } });
131 + expect(output).not.toContain('Sending the request without a body');
132 + })
133 + );
134 +
135 + it.live('[When] -d @- is passed [Then] the body is read from stdin', () =>
136 + Effect.gen(function* () {
137 + const piped = new PassThrough();
138 + piped.end('plain text');
139 +
140 + const { body } = yield* proxyBodyOver(piped, ['-X', 'POST', '-d', '@-']);
141 +
142 + expect(body).toBe('plain text');
143 + })
144 + );
145 + });
146 +
147 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
148 '[Given] curl-like proxy flags [Then] it creates a scoped session and forwards proxy_execute',
149 it => {
ts/packages/cli/test/src/commands/tools/execute/tools.execute.cmd.test.ts
+53
@@ -1,6 +1,7 @@
1 import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 +import { PassThrough } from 'node:stream';
5 import { describe, expect, it, layer } from '@effect/vitest';
6 import { vi, beforeEach, afterEach } from 'vitest';
7 import { Config, ConfigProvider, DateTime, Effect, Exit, Option, Schema } from 'effect';
@@ -2870,6 +2871,58 @@ describe('CLI: composio execute', () => {
2871 );
2872 });
2873
2874 + describe('[Given] no -d and a stdin pipe that sends nothing within 1 second', () => {
2875 + const silentPipe = new PassThrough();
2876 + const slowPipe = new PassThrough();
2877 + const executedToolSlugs: string[] = [];
2878 + const recordExecutions = { onExecute: (slug: string) => void executedToolSlugs.push(slug) };
2879 +
2880 + layer(
2881 + TestLive({
2882 + baseConfigProvider: testConfigProvider,
2883 + fixture: 'global-test-user-id',
2884 + stdin: { isTTY: false, data: '', stream: silentPipe },
2885 + toolsExecutor: recordExecutions,
2886 + })
2887 + )('[When] the pipe stays open and silent', it => {
2888 + it.effect('[Then] fails without running the tool', () =>
2889 + Effect.gen(function* () {
2890 + const failure = yield* cli(['execute', 'GITHUB_GET_REPOS']).pipe(Effect.flip);
2891 +
2892 + expectInvalidValueMessage(failure, 'No input arrived on stdin within 1 second.');
2893 + expect(executedToolSlugs).toEqual([]);
2894 + })
2895 + );
2896 + });
2897 +
2898 + layer(
2899 + TestLive({
2900 + baseConfigProvider: testConfigProvider,
2901 + fixture: 'global-test-user-id',
2902 + stdin: { isTTY: false, data: '', stream: slowPipe },
2903 + toolsExecutor: recordExecutions,
2904 + })
2905 + )('[When] the JSON arrives after the timeout', it => {
2906 + it.effect('[Then] fails instead of running the tool with empty arguments', () =>
2907 + Effect.gen(function* () {
2908 + // Time the write from when the reader starts listening, not from test start, so slow
2909 + // setup cannot move it inside the 1 second window.
2910 + let lateWrite: ReturnType<typeof setTimeout> | undefined;
2911 + slowPipe.once('resume', () => {
2912 + lateWrite = setTimeout(() => slowPipe.end('{"owner":"x"}'), 1500);
2913 + });
2914 + const failure = yield* cli(['execute', 'GITHUB_GET_REPOS']).pipe(
2915 + Effect.flip,
2916 + Effect.ensuring(Effect.sync(() => clearTimeout(lateWrite)))
2917 + );
2918 +
2919 + expectInvalidValueMessage(failure, 'No input arrived on stdin within 1 second.');
2920 + expect(executedToolSlugs).toEqual([]);
2921 + })
2922 + );
2923 + });
2924 + });
2925 +
2926 layer(
2927 TestLive({
2928 baseConfigProvider: testConfigProvider,
ts/packages/cli/test/src/services/stdin.test.ts new
+78
@@ -0,0 +1,78 @@
1 +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2 +import { PassThrough } from 'node:stream';
3 +import { readStdinToEnd } from 'src/services/stdin';
4 +
5 +const SILENCE_TIMEOUT_MS = 1000;
6 +
7 +/** Marks a read still waiting, so a test can tell a pending read from a resolved one. */
8 +const PENDING = Symbol('pending');
9 +
10 +const settledValue = async (read: Promise<string | undefined>) => {
11 + await vi.advanceTimersByTimeAsync(0);
12 + return Promise.race([read, Promise.resolve(PENDING)]);
13 +};
14 +
15 +describe('readStdinToEnd', () => {
16 + beforeEach(() => {
17 + vi.useFakeTimers();
18 + });
19 +
20 + afterEach(() => {
21 + vi.useRealTimers();
22 + });
23 +
24 + it('[Given] a pipe that never sends data or closes [Then] resolves undefined once the silence timeout passes', async () => {
25 + const input = new PassThrough();
26 + const read = readStdinToEnd(input, SILENCE_TIMEOUT_MS);
27 +
28 + await vi.advanceTimersByTimeAsync(SILENCE_TIMEOUT_MS - 1);
29 + expect(await settledValue(read)).toBe(PENDING);
30 +
31 + await vi.advanceTimersByTimeAsync(1);
32 + expect(await settledValue(read)).toBeUndefined();
33 + expect(input.listenerCount('data')).toBe(0);
34 + expect(input.isPaused()).toBe(true);
35 + });
36 +
37 + it('[Given] stdin that closes without data [Then] resolves an empty string', async () => {
38 + const input = new PassThrough();
39 + const read = readStdinToEnd(input, SILENCE_TIMEOUT_MS);
40 + input.end();
41 +
42 + expect(await settledValue(read)).toBe('');
43 + });
44 +
45 + it('[Given] data before the silence timeout and the end of input after it [Then] reads everything', async () => {
46 + const input = new PassThrough();
47 + const read = readStdinToEnd(input, SILENCE_TIMEOUT_MS);
48 + input.write('{"owner":');
49 +
50 + await vi.advanceTimersByTimeAsync(SILENCE_TIMEOUT_MS * 3);
51 + expect(await settledValue(read)).toBe(PENDING);
52 +
53 + input.end('"composio"}');
54 + expect(await settledValue(read)).toBe('{"owner":"composio"}');
55 + });
56 +
57 + it('[Given] the first byte arrives after the silence timeout [Then] resolves undefined and leaves the data unread', async () => {
58 + const input = new PassThrough();
59 + const read = readStdinToEnd(input, SILENCE_TIMEOUT_MS);
60 +
61 + await vi.advanceTimersByTimeAsync(SILENCE_TIMEOUT_MS);
62 + input.end('{"owner":"x"}');
63 +
64 + expect(await settledValue(read)).toBeUndefined();
65 + expect(input.read()?.toString()).toBe('{"owner":"x"}');
66 + });
67 +
68 + it('[Given] no silence timeout [Then] waits for the end of input however late it arrives', async () => {
69 + const input = new PassThrough();
70 + const read = readStdinToEnd(input);
71 +
72 + await vi.advanceTimersByTimeAsync(SILENCE_TIMEOUT_MS * 60);
73 + expect(await settledValue(read)).toBe(PENDING);
74 +
75 + input.end('late');
76 + expect(await settledValue(read)).toBe('late');
77 + });
78 +});