Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Fix CLI tool execution file uploads and in-band warnings (#3078)
Rahul Tarak48ad7caeb3bb
diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.tsindex 3f96ed44e..27b7bead8 100644--- a/ts/packages/cli/src/commands/root-help.ts+++ b/ts/packages/cli/src/commands/root-help.ts@@ -35,7 +35,7 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [description:'Execute a tool. Validates inputs and connections automatically; use it aggressively.',usage:- 'execute <slug> [-d, --data text] [--dry-run] [--get-schema] | execute -p <slug> -d <text> <slug> -d <text> ...',+ 'execute <slug> [-d, --data text] [--file path] [--dry-run] [--get-schema] | execute -p <slug> -d <text> <slug> -d <text> ...',options: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },{@@ -47,8 +47,12 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [name: '-p, --parallel',description: 'Execute repeated <slug> -d <text> pairs concurrently',},+ {+ name: '--file',+ description: 'Inject a local file path into the single file_uploadable input',+ },{ name: '--dry-run', description: 'Validate and preview the tool call without executing it' },- { name: '--get-schema', description: 'Fetch and print the raw tool schema' },+ { name: '--get-schema', description: 'Fetch and print the CLI-facing input schema' },],},{@@ -192,7 +196,8 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {],},execute: {- usage: 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--parallel]',+ usage:+ 'composio execute <slug> [-d, --data text] [--file path] [--dry-run] [--get-schema] [--parallel]',description:'Execute a tool by slug. Validates inputs against cached schemas and checks connections automatically — just try it and it will tell you what to fix.',args: [@@ -212,9 +217,13 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {name: '-p, --parallel',description: 'Execute repeated TOOL_SLUG -d <text> groups concurrently',},+ {+ name: '--file <path>',+ description: 'Inject a local file path into the single file_uploadable input',+ },{name: '--get-schema',- description: 'Fetch and print the raw tool schema without executing',+ description: 'Fetch and print the CLI-facing input schema without executing',},{name: '--dry-run',@@ -281,7 +290,10 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {{ name: '-f, --file <text>', description: 'Run a TS/JS file instead of inline code' },{ name: '--dry-run', description: 'Preview execute() calls without running them' },{ name: '--debug', description: 'Log helper steps while the script runs' },- { name: '--logs-off', description: 'Hide the always-on experimental_subAgent streaming logs' },+ {+ name: '--logs-off',+ description: 'Hide the always-on experimental_subAgent streaming logs',+ },],flags: [{ name: '--skip-connection-check', description: 'Skip the connected-account check' },@@ -496,7 +508,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {'tools info': {usage: 'composio tools info [<slug>]',description:- 'View a brief summary of a tool and cache the raw schema used by `composio execute --get-schema`.',+ 'View a brief summary of a tool and show the CLI-facing schema used by `composio execute --get-schema`.',args: [{ name: '<slug>', description: 'Tool slug (e.g. "GMAIL_SEND_EMAIL")' }],},@@ -573,17 +585,21 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {},'dev playground-execute': {usage:- 'composio dev playground-execute <slug> [-d, --data text] [--user-id text] [--project-name text] [--dry-run] [--get-schema]',+ 'composio dev playground-execute <slug> [-d, --data text] [--file path] [--user-id text] [--project-name text] [--dry-run] [--get-schema]',description:'Test tool executions against playground users using your developer project auth configs.',args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],options: [{ name: '-d, --data <text>', description: 'JSON arguments, @file, or - for stdin' },+ {+ name: '--file <path>',+ description: 'Inject a local file path into the single file_uploadable input',+ },{ name: '--user-id <text>', description: 'Developer-project user ID override' },{ name: '--project-name <text>', description: 'Developer project name override' },{name: '--get-schema',- description: 'Fetch and print the raw tool schema without executing',+ description: 'Fetch and print the CLI-facing input schema without executing',},{ name: '--dry-run', description: 'Validate and preview without executing' },],diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.tsindex 65d068ccc..2bab004d0 100644--- a/ts/packages/cli/src/commands/run.cmd.ts+++ b/ts/packages/cli/src/commands/run.cmd.ts@@ -182,7 +182,6 @@ const resolveRunHelperModuleUrls = (): RunHelperModuleUrls => ({})).href,});-export const buildRunHelpersSource = (cliPrefix: ReadonlyArray<string>,context: RunHelperContext = {},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.tsindex 7fef0a25c..3f6b93efd 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@@ -48,6 +48,7 @@ import {resolveCliSessionArtifacts,} from 'src/services/cli-session-artifacts';import { storeCliSessionArtifact } from 'src/services/cli-session-artifacts';+import { findFileUploadablePaths, normalizeFileUploadSchema } from 'src/services/tool-file-uploads';import {ComposioNoActiveConnectionError,mapComposioError,@@ -64,6 +65,10 @@ const data = Options.text('data').pipe(Options.withDescription('JSON arguments, @file, or - for stdin'),Options.optional);+const file = Options.text('file').pipe(+ Options.withDescription('Inject a local file path into the single file_uploadable input'),+ Options.optional+);const userId = Options.text('user-id').pipe(Options.optional,@@ -76,7 +81,7 @@ const projectName = Options.text('project-name').pipe();const getSchema = Options.boolean('get-schema').pipe(- Options.withDescription('Fetch and print the raw tool schema without executing'),+ Options.withDescription('Fetch and print the CLI-facing input schema without executing'),Options.withDefault(false));const dryRun = Options.boolean('dry-run').pipe(@@ -119,6 +124,88 @@ const parseArguments = (raw: string) =>return parsed as Record<string, unknown>;});+const hasNestedKey = (+ record: Record<string, unknown>,+ pathParts: ReadonlyArray<string>+): boolean => {+ let current: unknown = record;+ for (const key of pathParts) {+ if (typeof current !== 'object' || current === null || Array.isArray(current)) {+ return false;+ }+ if (!(key in (current as Record<string, unknown>))) {+ return false;+ }+ current = (current as Record<string, unknown>)[key];+ }+ return true;+};++const setNestedKey = (+ record: Record<string, unknown>,+ pathParts: ReadonlyArray<string>,+ value: unknown+): Record<string, unknown> => {+ if (pathParts.length === 0) return record;++ const clone: Record<string, unknown> = { ...record };+ let current = clone;++ for (const [index, key] of pathParts.entries()) {+ if (index === pathParts.length - 1) {+ current[key] = value;+ break;+ }++ const next = current[key];+ const nextObject =+ typeof next === 'object' && next !== null && !Array.isArray(next)+ ? { ...(next as Record<string, unknown>) }+ : {};+ current[key] = nextObject;+ current = nextObject;+ }++ return clone;+};++const injectSingleFileArgument = (params: {+ readonly slug: string;+ readonly args: Record<string, unknown>;+ readonly filePath: string;+ readonly schema: Record<string, unknown>;+}) =>+ Effect.gen(function* () {+ const uploadablePaths = findFileUploadablePaths(params.schema);++ if (uploadablePaths.length === 0) {+ return yield* Effect.fail(+ new Error(+ `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`+ )+ );+ }++ if (uploadablePaths.length > 1) {+ return yield* Effect.fail(+ new Error(+ `Tool "${params.slug}" has multiple file_uploadable inputs (${uploadablePaths.map(parts => parts.join('.')).join(', ')}). Pass the target field explicitly with -d instead of --file.`+ )+ );+ }++ const targetPath = uploadablePaths[0] ?? [];+ if (hasNestedKey(params.args, targetPath)) {+ return yield* Effect.fail(+ new Error(+ `Cannot use --file because "${targetPath.join('.')}" is already set in -d. Remove that field or omit --file.`+ )+ );+ }++ return setNestedKey(params.args, targetPath, params.filePath);+ });+const connectionTips = (toolSlug: string, surface: 'root' | 'dev') => {const toolkit = toolkitFromToolSlug(toolSlug);const executeStep =@@ -564,9 +651,12 @@ const handleExecutionError = (return { error: mapped.message, slug: slugValue };});-class ToolExecutionError {+class ToolExecutionError extends Error {readonly _tag = 'ToolExecutionError';- constructor(readonly message: string) {}+ constructor(readonly message: string) {+ super(message);+ this.name = 'ToolExecutionError';+ }}type CachedValidationDecision =@@ -721,6 +811,7 @@ type DryRunSummary = {type RunToolsExecuteParams = {slug: string;data: Option.Option<string>;+ file: Option.Option<string>;userId: Option.Option<string>;projectName: Option.Option<string>;surface: 'root' | 'dev';@@ -732,7 +823,7 @@ type RunToolsExecuteParams = {skipChecks: boolean;};-type SharedRunToolsExecuteParams = Omit<RunToolsExecuteParams, 'slug' | 'data'>;+type SharedRunToolsExecuteParams = Omit<RunToolsExecuteParams, 'slug' | 'data' | 'file'>;type ParallelExecuteSpec = {readonly slug: string;@@ -792,6 +883,7 @@ const emitCachedSchema = (}) =>Effect.gen(function* () {+ const displaySchema = normalizeFileUploadSchema(definition.schema);yield* ui.log.message(`Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`);@@ -801,7 +893,7 @@ const emitCachedSchema = (slug,version: definition.version,schemaPath: definition.schemaPath,- inputSchema: definition.schema,+ inputSchema: displaySchema,},null,2@@ -823,7 +915,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>const projectContext = yield* ProjectContext;const input = (yield* resolveInput(params.data)) ?? '{}';- const args = yield* parseArguments(input);+ const parsedArgs = yield* parseArguments(input);const localProjectContext = yield* projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none())));@@ -850,6 +942,21 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>orgId: resolvedProject.orgId,projectId: resolvedProject.projectId,});+ const args = Option.isSome(params.file)+ ? yield* getOrFetchToolInputDefinition(params.slug, {+ orgId: resolvedProject.orgId,+ projectId: resolvedProject.projectId,+ }).pipe(+ Effect.flatMap(definition =>+ injectSingleFileArgument({+ slug: params.slug,+ args: parsedArgs,+ filePath: Option.getOrThrow(params.file),+ schema: definition.schema,+ })+ )+ )+ : parsedArgs;const executeOutputDir =process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() ||Option.getOrUndefined(@@ -1545,7 +1652,7 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>successful: true,version: definition.version,schemaPath: definition.schemaPath,- inputSchema: definition.schema,+ inputSchema: normalizeFileUploadSchema(definition.schema),} satisfies Extract<ParallelExecuteResult,{ readonly inputSchema: Record<string, unknown> }@@ -1610,6 +1717,7 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>resolveExecuteContext({slug: spec.slug,data: spec.data,+ file: Option.none(),userId: params.userId,projectName: params.projectName,surface: params.surface,@@ -1791,11 +1899,12 @@ export const runParallelToolsExecuteFromArgv = (argv: ReadonlyArray<string>) =>export const rootToolsCmd$Execute = Command.make('execute',- { slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks },- ({ slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks }) =>+ { slug, data, file, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks },+ ({ slug, data, file, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks }) =>runToolsExecute({slug,data,+ file,userId: Option.none(),projectName: Option.none(),surface: 'root',@@ -1814,11 +1923,13 @@ export const rootToolsCmd$Execute = Command.make('','Examples:',' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK --file ./image.png -d \'{ channels: "C123" }\'',' composio execute --parallel GMAIL_SEND_EMAIL -d \'{ recipient_email: "[email protected]" }\' GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\''," composio execute GMAIL_SEND_EMAIL --dry-run -d '{ ... }' Preview without executing",' composio execute GMAIL_SEND_EMAIL --get-schema Fetch and print the input schema','','Flags:',+ ' --file <path> Inject a local file path into the single file_uploadable input',' -p, --parallel Execute repeated TOOL_SLUG -d <json> groups concurrently',' --skip-connection-check Skip the connected-account check',' --skip-tool-params-check Skip input validation against cached schema',@@ -1837,6 +1948,7 @@ export const devToolsCmd$Execute = Command.make({slug,data,+ file,userId,projectName,getSchema,@@ -1848,6 +1960,7 @@ export const devToolsCmd$Execute = Command.make(({slug,data,+ file,userId,projectName,getSchema,@@ -1859,6 +1972,7 @@ export const devToolsCmd$Execute = Command.make(runToolsExecute({slug,data,+ file,userId,projectName,surface: 'dev',@@ -1878,10 +1992,12 @@ export const devToolsCmd$Execute = Command.make('','Examples:',' composio dev playground-execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio dev playground-execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK --file ./image.png -d \'{ channels: "C123" }\'',' composio dev playground-execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',' composio dev playground-execute GMAIL_SEND_EMAIL --get-schema','','Flags:',+ ' --file <path> Inject a local file path into the single file_uploadable input',' -p, --parallel Execute repeated TOOL_SLUG -d <json> groups concurrently',].join('\n'))diff --git a/ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.info.cmd.tsindex 50f29c3c4..0a4f4a8ba 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts@@ -5,6 +5,7 @@ import { TerminalUI } from 'src/services/terminal-ui';import { requireAuth } from 'src/effects/require-auth';import { handleHttpServerError } from 'src/effects/handle-http-error';import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';+import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';import { bold } from 'src/ui/colors';import { commandHintExample, commandHintStep } from 'src/services/command-hints';@@ -31,7 +32,9 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>// Missing slug guardif (Option.isNone(slug)) {yield* ui.log.warn('Missing required argument: <slug>');- yield* ui.log.step('Try specifying a tool slug, e.g.:\n> composio tools info "GMAIL_SEND_EMAIL"');+ yield* ui.log.step(+ 'Try specifying a tool slug, e.g.:\n> composio tools info "GMAIL_SEND_EMAIL"'+ );return;}@@ -69,6 +72,7 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>const tool = toolOpt.value;const definition = yield* getOrFetchToolInputDefinition(slugValue);+ const displaySchema = normalizeFileUploadSchema(definition.schema);const summary = [`${bold('Slug:')} ${tool.slug}`,@@ -97,6 +101,7 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>toolkit: tool.toolkit.slug,version: definition.version,schemaPath: definition.schemaPath,+ inputSchema: displaySchema,},null,2@@ -105,6 +110,6 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>})).pipe(Command.withDescription(- 'View a brief summary of a tool and cache the same raw schema used by `composio execute --get-schema`.'+ 'View a brief summary of a tool and show the CLI-facing input schema used by `composio execute`.'));diff --git a/ts/packages/cli/src/services/run-helpers-runtime.ts b/ts/packages/cli/src/services/run-helpers-runtime.tsindex 74fb33716..b79516791 100644--- a/ts/packages/cli/src/services/run-helpers-runtime.ts+++ b/ts/packages/cli/src/services/run-helpers-runtime.ts@@ -1,8 +1,10 @@import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';import process from 'node:process';import { z } from 'zod';import type { MasterKind } from 'src/services/master-detector';-import { isAcpInvokeError, type InvokeAgentTarget } from 'src/services/run-subagent-shared';+import { isAcpInvokeError } from 'src/services/run-subagent-shared';import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';@@ -209,6 +211,7 @@ export const installRunHelpers = async ({if (!perfDebugEnabled) return;const elapsedMs = Date.now() - perfDebugStart;const payload = { phase, label, elapsedMs, ...details };+ // eslint-disable-next-line no-consoleconsole.error(`[perf] ${JSON.stringify(payload)}`);};@@ -348,6 +351,67 @@ export const installRunHelpers = async ({return value;};+ const isPlainObjectForExecute = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++ const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {+ if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';+ const normalized = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';+ const explicit: Record<string, string> = {+ 'text/plain': 'txt',+ 'application/json': 'json',+ 'application/pdf': 'pdf',+ 'image/jpeg': 'jpg',+ 'image/png': 'png',+ 'image/webp': 'webp',+ 'image/gif': 'gif',+ };+ if (explicit[normalized]) return explicit[normalized];+ const subtype = normalized.split('/')[1] || 'bin';+ return subtype.includes('+') ? (subtype.split('+').pop() ?? 'bin') : subtype;+ };++ const writeTempExecuteFile = async (value: unknown): Promise<unknown> => {+ const outputDir = sharedRunOutputDir || path.join(os.tmpdir(), 'composio-run-files');+ fs.mkdirSync(outputDir, { recursive: true });+ if (typeof File !== 'undefined' && value instanceof File) {+ const safeName =+ typeof value.name === 'string' && value.name.trim().length > 0+ ? value.name+ : `file-${executeId()}.${runFileExtensionFromMimeType(value.type)}`;+ const filePath = path.join(outputDir, `${executeId()}-${safeName}`);+ fs.writeFileSync(filePath, new Uint8Array(await value.arrayBuffer()));+ return filePath;+ }+ if (typeof Blob !== 'undefined' && value instanceof Blob) {+ const filePath = path.join(+ outputDir,+ `${executeId()}.${runFileExtensionFromMimeType(value.type)}`+ );+ fs.writeFileSync(filePath, new Uint8Array(await value.arrayBuffer()));+ return filePath;+ }+ return value;+ };++ const materializeExecutePayload = async (value: unknown): Promise<unknown> => {+ if (typeof File !== 'undefined' && value instanceof File) return writeTempExecuteFile(value);+ if (typeof Blob !== 'undefined' && value instanceof Blob) return writeTempExecuteFile(value);+ if (Array.isArray(value)) {+ return Promise.all(value.map(item => materializeExecutePayload(item)));+ }+ if (isPlainObjectForExecute(value)) {+ const entries = await Promise.all(+ Object.entries(value).map(async ([key, entryValue]) => [+ key,+ await materializeExecutePayload(entryValue),+ ])+ );+ return Object.fromEntries(entries);+ }+ return value;+ };+const maybeLoadStoredCliResult = (result: RunCliResult): RunCliResult => {if (!result || typeof result !== 'object' || result.storedInFile !== true) {return attachPromptMethod(result);@@ -682,7 +746,9 @@ export const installRunHelpers = async ({if (helperContext.skipToolParamsCheck === true) args.push('--skip-tool-params-check');if (helperContext.skipChecks === true) args.push('--skip-checks');if (data !== undefined) {- const serialized = typeof data === 'string' ? data : JSON.stringify(data);+ const preparedData = await materializeExecutePayload(data);+ const serialized =+ typeof preparedData === 'string' ? preparedData : JSON.stringify(preparedData);if (sharedRunOutputDir) {const tmpFile = `${sharedRunOutputDir}/execute-data-${slug}-${executeId()}.json`;fs.writeFileSync(tmpFile, serialized, 'utf8');diff --git a/ts/packages/cli/src/services/tool-file-uploads.ts b/ts/packages/cli/src/services/tool-file-uploads.tsnew file mode 100644index 000000000..1f1d73adf--- /dev/null+++ b/ts/packages/cli/src/services/tool-file-uploads.ts@@ -0,0 +1,290 @@+import fs from 'node:fs/promises';+import path from 'node:path';+import type { Composio as RawComposioClient } from '@composio/client';+import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';++type JsonSchema = Record<string, unknown>;++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const isFileLike = (value: unknown): value is File =>+ typeof File !== 'undefined' && value instanceof File;++const isSchemaRecord = (value: unknown): value is JsonSchema => isRecord(value);++const getSchemaVariants = (schema: JsonSchema | undefined): ReadonlyArray<JsonSchema> => [+ ...((Array.isArray(schema?.anyOf) ? schema.anyOf : []) as JsonSchema[]),+ ...((Array.isArray(schema?.oneOf) ? schema.oneOf : []) as JsonSchema[]),+ ...((Array.isArray(schema?.allOf) ? schema.allOf : []) as JsonSchema[]),+];++const transformSchema = (schema: JsonSchema): JsonSchema => {+ if (schema.file_uploadable === true) {+ return {+ title: schema.title,+ description: schema.description,+ format: 'path',+ type: 'string',+ file_uploadable: true,+ };+ }++ const transformed: JsonSchema = { ...schema };++ if (isSchemaRecord(schema.properties)) {+ transformed.properties = Object.fromEntries(+ Object.entries(schema.properties).map(([key, value]) => [+ key,+ isSchemaRecord(value) ? transformSchema(value) : value,+ ])+ );+ }++ for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {+ if (Array.isArray(schema[key])) {+ transformed[key] = schema[key].map(value =>+ isSchemaRecord(value) ? transformSchema(value) : value+ );+ }+ }++ if (Array.isArray(schema.items)) {+ transformed.items = schema.items.map(value =>+ isSchemaRecord(value) ? transformSchema(value) : value+ );+ } else if (isSchemaRecord(schema.items)) {+ transformed.items = transformSchema(schema.items);+ }++ return transformed;+};++export const normalizeFileUploadSchema = (schema: JsonSchema): JsonSchema =>+ isSchemaRecord(schema) ? transformSchema(schema) : schema;++export const schemaHasFileUploadable = (schema: JsonSchema | undefined): boolean => {+ if (!schema) return false;+ if (schema.file_uploadable === true) return true;++ if (isSchemaRecord(schema.properties)) {+ for (const property of Object.values(schema.properties)) {+ if (isSchemaRecord(property) && schemaHasFileUploadable(property)) {+ return true;+ }+ }+ }++ for (const variant of getSchemaVariants(schema)) {+ if (schemaHasFileUploadable(variant)) {+ return true;+ }+ }++ if (Array.isArray(schema.items)) {+ return schema.items.some(item => isSchemaRecord(item) && schemaHasFileUploadable(item));+ }++ if (isSchemaRecord(schema.items)) {+ return schemaHasFileUploadable(schema.items);+ }++ return false;+};++export const findFileUploadablePaths = (+ schema: JsonSchema | undefined,+ basePath: ReadonlyArray<string> = []+): ReadonlyArray<ReadonlyArray<string>> => {+ if (!schema) return [];++ if (schema.file_uploadable === true) {+ return [basePath];+ }++ const directPropertyPaths = isSchemaRecord(schema.properties)+ ? Object.entries(schema.properties).flatMap(([key, property]) =>+ isSchemaRecord(property) ? findFileUploadablePaths(property, [...basePath, key]) : []+ )+ : [];++ const variantPaths = getSchemaVariants(schema).flatMap(variant =>+ findFileUploadablePaths(variant, basePath)+ );++ const itemPaths = Array.isArray(schema.items)+ ? schema.items.flatMap(item =>+ isSchemaRecord(item) ? findFileUploadablePaths(item, basePath) : []+ )+ : isSchemaRecord(schema.items)+ ? findFileUploadablePaths(schema.items, basePath)+ : [];++ const seen = new Set<string>();+ return [...directPropertyPaths, ...variantPaths, ...itemPaths].filter(pathParts => {+ const key = pathParts.join('.');+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+};++const readFileFromUrl = async (url: string) => {+ const response = await fetch(url);+ if (!response.ok) {+ throw new Error(`Failed to fetch file: ${response.statusText}`);+ }++ const bytes = new Uint8Array(await response.arrayBuffer());+ const parsedUrl = new URL(url);+ const fileName = path.basename(parsedUrl.pathname) || `file-${Date.now()}`;++ return {+ bytes,+ fileName,+ mimeType: response.headers.get('content-type') || 'application/octet-stream',+ };+};++const readFileFromDisk = async (filePath: string) => ({+ bytes: new Uint8Array(await fs.readFile(filePath)),+ fileName: path.basename(filePath),+ mimeType: 'application/octet-stream',+});++const readUploadSource = async (file: string | File) => {+ if (isFileLike(file)) {+ return {+ bytes: new Uint8Array(await file.arrayBuffer()),+ fileName: file.name || `file-${Date.now()}`,+ mimeType: file.type || 'application/octet-stream',+ };+ }++ if (typeof file === 'string' && /^https?:\/\//i.test(file)) {+ return readFileFromUrl(file);+ }++ if (typeof file === 'string') {+ return readFileFromDisk(file);+ }++ throw new Error('Unsupported upload source');+};++const uploadFile = async (params: {+ readonly file: string | File;+ readonly toolSlug: string;+ readonly toolkitSlug: string;+ readonly client: RawComposioClient;+}) => {+ const fileData = await readUploadSource(params.file);+ const { createHash } = await import('node:crypto');+ const md5 = createHash('md5').update(fileData.bytes).digest('hex');+ const presigned = await params.client.files.createPresignedURL({+ filename: fileData.fileName,+ mimetype: fileData.mimeType,+ md5,+ tool_slug: params.toolSlug,+ toolkit_slug: params.toolkitSlug,+ });++ const uploadResponse = await fetch(presigned.new_presigned_url, {+ method: 'PUT',+ body: fileData.bytes,+ headers: {+ 'Content-Type': fileData.mimeType,+ 'Content-Length': fileData.bytes.byteLength.toString(),+ },+ });++ if (!uploadResponse.ok) {+ throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);+ }++ return {+ name: fileData.fileName,+ mimetype: fileData.mimeType,+ s3key: presigned.key,+ };+};++const hydrateFileUploads = async (+ value: unknown,+ schema: JsonSchema | undefined,+ ctx: {+ readonly toolSlug: string;+ readonly toolkitSlug: string;+ readonly client: RawComposioClient;+ }+): Promise<unknown> => {+ if (schema?.file_uploadable === true) {+ if (typeof value !== 'string' && !isFileLike(value)) {+ return value;+ }++ return uploadFile({+ file: value,+ toolSlug: ctx.toolSlug,+ toolkitSlug: ctx.toolkitSlug,+ client: ctx.client,+ });+ }++ const uploadableVariants = getSchemaVariants(schema).filter(schemaHasFileUploadable);+ if (uploadableVariants.length > 0) {+ let nextValue = value;+ for (const variant of uploadableVariants) {+ nextValue = await hydrateFileUploads(nextValue, variant, ctx);+ }+ return nextValue;+ }++ if (isSchemaRecord(schema?.properties) && isRecord(value)) {+ const entries = await Promise.all(+ Object.entries(value).map(async ([key, entryValue]) => [+ key,+ await hydrateFileUploads(+ entryValue,+ isSchemaRecord((schema.properties as Record<string, unknown>)[key])+ ? ((schema.properties as Record<string, unknown>)[key] as JsonSchema)+ : undefined,+ ctx+ ),+ ])+ );+ return Object.fromEntries(entries);+ }++ if (schema?.type === 'array' && Array.isArray(value) && schema.items) {+ const itemSchema = Array.isArray(schema.items)+ ? schema.items.find(isSchemaRecord)+ : isSchemaRecord(schema.items)+ ? schema.items+ : undefined;++ return Promise.all(value.map(item => hydrateFileUploads(item, itemSchema, ctx)));+ }++ return value;+};++export const uploadToolInputFiles = async (params: {+ readonly toolSlug: string;+ readonly arguments_: Record<string, unknown>;+ readonly inputSchema: JsonSchema;+ readonly client: RawComposioClient;+ readonly toolkitSlug?: string;+}): Promise<Record<string, unknown>> => {+ if (!schemaHasFileUploadable(params.inputSchema)) {+ return params.arguments_;+ }++ const hydrated = await hydrateFileUploads(params.arguments_, params.inputSchema, {+ toolSlug: params.toolSlug,+ toolkitSlug: params.toolkitSlug ?? toolkitFromToolSlug(params.toolSlug) ?? 'unknown',+ client: params.client,+ });++ return isRecord(hydrated) ? hydrated : params.arguments_;+};diff --git a/ts/packages/cli/src/services/tool-input-validation.ts b/ts/packages/cli/src/services/tool-input-validation.tsindex 46e4345d3..cfeae48c6 100644--- a/ts/packages/cli/src/services/tool-input-validation.ts+++ b/ts/packages/cli/src/services/tool-input-validation.ts@@ -6,6 +6,7 @@ import { z } from 'zod/v3';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { ComposioToolkitsRepository, getLatestToolVersion } from 'src/services/composio-clients';import { isToolDebugEnabled } from 'src/services/runtime-debug-flags';+import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';import { ComposioUserContext } from 'src/services/user-context';const TOOL_DEFINITIONS_DIR = 'tool_definitions';@@ -373,9 +374,10 @@ export const validateToolInputArgumentsWithDefinition = (Effect.gen(function* () {const { schemaPath, schema } = definition;const allowedKeys = getObjectSchemaProperties(schema);+ const normalizedSchema = normalizeFileUploadSchema(schema);const zodSchema = yield* Effect.try({- try: () => jsonSchemaToZodSchema<z.ZodTypeAny>(schema),+ try: () => jsonSchemaToZodSchema<z.ZodTypeAny>(normalizedSchema),catch: error =>new ToolInputValidationError(slug,diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.tsindex 7fb85f836..0f736e0e1 100644--- a/ts/packages/cli/src/services/tools-executor.ts+++ b/ts/packages/cli/src/services/tools-executor.ts@@ -5,12 +5,18 @@ import type {SessionExecuteMetaResponse,SessionExecuteMetaParams,} from '@composio/client/resources/tool-router';+import type { FileSystem } from '@effect/platform';import { ComposioClientSingleton } from 'src/services/composio-clients';import { createToolRouterSession } from 'src/effects/create-tool-router-session';import {ComposioNoActiveConnectionError,mapComposioError,} from 'src/services/composio-error-overrides';+import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';+import { uploadToolInputFiles } from 'src/services/tool-file-uploads';+import type { NodeOs } from 'src/services/node-os';+import type { ComposioUserContext } from 'src/services/user-context';+import type { ComposioToolkitsRepository } from 'src/services/composio-clients';/*** Parameters accepted by the Tool Router-based executor.@@ -35,7 +41,11 @@ export interface ToolsExecutor {readonly execute: (slug: string,params: ToolExecuteParams- ) => Effect.Effect<ToolExecuteResponse, unknown>;+ ) => Effect.Effect<+ ToolExecuteResponse,+ unknown,+ FileSystem.FileSystem | NodeOs | ComposioUserContext | ComposioToolkitsRepository+ >;}export const ToolsExecutor = Context.GenericTag<ToolsExecutor>('services/ToolsExecutor');@@ -103,7 +113,6 @@ export const detectInBandWarning = (if (typeof data.message === 'string') return data.message;return 'Tool response indicates unsuccessful execution';}-return null;};@@ -124,18 +133,37 @@ export const ToolsExecutorLive = Layer.effect(const sessionId = yield* createToolRouterSession(resolvedClient, params.userId, {manageConnections: true,});+ const normalizedArguments = isMetaToolSlug(slug)+ ? params.arguments+ : yield* getOrFetchToolInputDefinition(slug).pipe(+ Effect.catchAll(() => Effect.succeed(null)),+ Effect.flatMap(definition => {+ if (!definition) {+ return Effect.succeed(params.arguments);+ }++ return Effect.tryPromise(() =>+ uploadToolInputFiles({+ toolSlug: slug,+ arguments_: params.arguments,+ inputSchema: definition.schema,+ client: resolvedClient,+ })+ );+ })+ );const raw: SessionExecuteResponse | SessionExecuteMetaResponse = yield* Effect.tryPromise(() => {if (isMetaToolSlug(slug)) {return resolvedClient.toolRouter.session.executeMeta(sessionId, {slug,- arguments: params.arguments,+ arguments: normalizedArguments,});}return resolvedClient.toolRouter.session.execute(sessionId, {tool_slug: slug,- arguments: params.arguments,+ arguments: normalizedArguments,});});diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.tsindex a1a47ea36..3a75dfe78 100644--- a/ts/packages/cli/test/__utils__/services/test-layer.ts+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts@@ -979,6 +979,18 @@ export const TestLayer = (input?: TestLiveInput) =>};},},+ files: {+ createPresignedURL: async (params: {+ filename: string;+ mimetype: string;+ md5: string;+ tool_slug: string;+ toolkit_slug: string;+ }) => ({+ key: `uploads/${params.filename}`,+ new_presigned_url: 'https://s3.test.composio.dev/upload',+ }),+ },toolRouter: {session: {create:diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.tsindex 9c59be059..100653fcf 100644--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts@@ -1,4 +1,6 @@import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';import { describe, expect, layer } from '@effect/vitest';import { vi, beforeEach, afterEach } from 'vitest';import { ConfigProvider, Effect, Option } from 'effect';@@ -86,6 +88,70 @@ describe('CLI: composio execute', () => {);});+ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ toolkitsData: {+ tools: [+ {+ name: 'Upload Slack File',+ slug: 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK',+ description: 'Uploads a file to Slack',+ tags: ['slack'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ channels: { type: 'string' },+ file: {+ type: 'object',+ file_uploadable: true,+ title: 'File',+ description: 'Local file accepted by CLI',+ properties: {+ name: { type: 'string' },+ mimetype: { type: 'string' },+ s3key: { type: 'string' },+ },+ required: ['name', 'mimetype', 's3key'],+ },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {},+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )('[Given] file_uploadable schema [Then] execute --get-schema shows a path string input', it => {+ it.scoped('renders the CLI-facing schema instead of the raw FileUploadable object', () =>+ Effect.gen(function* () {+ yield* cli(['execute', 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK', '--get-schema']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines) as unknown as {+ inputSchema: Record<string, unknown>;+ };++ expect(output.inputSchema).toEqual({+ type: 'object',+ properties: {+ channels: { type: 'string' },+ file: {+ title: 'File',+ description: 'Local file accepted by CLI',+ format: 'path',+ type: 'string',+ file_uploadable: true,+ },+ },+ });+ })+ );+ });+layer(TestLive({baseConfigProvider: testConfigProvider,@@ -586,6 +652,478 @@ describe('CLI: composio execute', () => {);});+ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email with attachment',+ tags: ['email'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ attachment: {+ file_uploadable: true,+ title: 'Attachment',+ description: 'Local path or URL to upload',+ },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {+ message_id: { type: 'string' },+ },+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )(+ '[Given] file_uploadable input as a local path [Then] execute uploads and sends s3key data',+ it => {+ it.scoped('uploads local file paths before Tool Router execution', () =>+ Effect.gen(function* () {+ const tempFile = path.join(os.tmpdir(), `composio-upload-${Date.now()}.txt`);+ fs.writeFileSync(tempFile, 'hello from cli upload', 'utf8');++ const originalFetch = globalThis.fetch;+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {+ const url =+ typeof input === 'string'+ ? input+ : input instanceof URL+ ? input.toString()+ : input.url;+ if (url === 'https://s3.test.composio.dev/upload') {+ return Promise.resolve(new Response(null, { status: 200 }));+ }+ return originalFetch(input, init);+ });++ yield* cli([+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '-d',+ JSON.stringify({+ recipient_email: '[email protected]',+ attachment: tempFile,+ }),+ ]);++ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines);++ expect(output.successful).toBe(true);+ expect(output.data.arguments).toEqual({+ recipient_email: '[email protected]',+ attachment: {+ name: path.basename(tempFile),+ mimetype: 'application/octet-stream',+ s3key: `uploads/${path.basename(tempFile)}`,+ },+ });+ expect(fetchSpy).toHaveBeenCalledWith(+ 'https://s3.test.composio.dev/upload',+ expect.objectContaining({+ method: 'PUT',+ headers: expect.objectContaining({+ 'Content-Type': 'application/octet-stream',+ }),+ })+ );++ fs.rmSync(tempFile, { force: true });+ })+ );+ }+ );++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolkitsData: {+ tools: [+ {+ name: 'Upload Slack File',+ slug: 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK',+ description: 'Uploads a file to Slack',+ tags: ['slack'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ channels: { type: 'string' },+ file: {+ type: 'object',+ file_uploadable: true,+ title: 'File',+ description: 'Local file accepted by CLI',+ properties: {+ name: { type: 'string' },+ mimetype: { type: 'string' },+ s3key: { type: 'string' },+ },+ required: ['name', 'mimetype', 's3key'],+ },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {},+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )(+ '[Given] --file for a tool with one file_uploadable input [Then] execute injects it automatically',+ it => {+ it.scoped('injects into the single file_uploadable field before upload hydration', () =>+ Effect.gen(function* () {+ const tempFile = path.join(os.tmpdir(), `composio-inject-${Date.now()}.png`);+ fs.writeFileSync(tempFile, 'png-binary-ish', 'utf8');++ const originalFetch = globalThis.fetch;+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {+ const url =+ typeof input === 'string'+ ? input+ : input instanceof URL+ ? input.toString()+ : input.url;+ if (url === 'https://s3.test.composio.dev/upload') {+ return Promise.resolve(new Response(null, { status: 200 }));+ }+ return originalFetch(input, init);+ });++ yield* cli([+ 'execute',+ 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK',+ '--skip-connection-check',+ '--file',+ tempFile,+ '-d',+ JSON.stringify({ channels: 'C123' }),+ ]);++ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines);++ expect(output.successful).toBe(true);+ expect(output.data.arguments).toEqual({+ channels: 'C123',+ file: {+ name: path.basename(tempFile),+ mimetype: 'application/octet-stream',+ s3key: `uploads/${path.basename(tempFile)}`,+ },+ });+ expect(fetchSpy).toHaveBeenCalled();++ fs.rmSync(tempFile, { force: true });+ })+ );+ }+ );++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolkitsData: {+ tools: [+ {+ name: 'Nested Upload',+ slug: 'NESTED_UPLOAD_TOOL',+ description: 'Uploads a nested file',+ tags: ['test'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ payload: {+ properties: {+ file: {+ file_uploadable: true,+ title: 'File',+ description: 'Nested file path',+ properties: {+ name: { type: 'string' },+ mimetype: { type: 'string' },+ s3key: { type: 'string' },+ },+ },+ },+ },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {},+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )(+ '[Given] a nested file_uploadable path under properties without explicit object type [Then] hydration still uploads it',+ it => {+ it.scoped('treats property-bearing schema nodes as object-like during upload hydration', () =>+ Effect.gen(function* () {+ const tempFile = path.join(os.tmpdir(), `composio-nested-${Date.now()}.png`);+ fs.writeFileSync(tempFile, 'nested-png-binary-ish', 'utf8');++ const originalFetch = globalThis.fetch;+ vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {+ const url =+ typeof input === 'string'+ ? input+ : input instanceof URL+ ? input.toString()+ : input.url;+ if (url === 'https://s3.test.composio.dev/upload') {+ return Promise.resolve(new Response(null, { status: 200 }));+ }+ return originalFetch(input, init);+ });++ yield* cli([+ 'execute',+ 'NESTED_UPLOAD_TOOL',+ '--skip-connection-check',+ '--file',+ tempFile,+ '-d',+ JSON.stringify({ payload: {} }),+ ]);++ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines);++ expect(output.successful).toBe(true);+ expect(output.data.arguments).toEqual({+ payload: {+ file: {+ name: path.basename(tempFile),+ mimetype: 'application/octet-stream',+ s3key: `uploads/${path.basename(tempFile)}`,+ },+ },+ });++ fs.rmSync(tempFile, { force: true });+ })+ );+ }+ );++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email with attachment',+ tags: ['email'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ attachment: {+ file_uploadable: true,+ title: 'Attachment',+ description: 'Local path or URL to upload',+ properties: {+ name: { type: 'string' },+ mimetype: { type: 'string' },+ s3key: { type: 'string' },+ },+ },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {},+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )(+ '[Given] an S3 upload failure [Then] execute surfaces the upload error instead of sending a raw path',+ it => {+ it.scoped('propagates upload failures from file hydration', () =>+ Effect.gen(function* () {+ const tempFile = path.join(os.tmpdir(), `composio-upload-fail-${Date.now()}.txt`);+ fs.writeFileSync(tempFile, 'hello from failed cli upload', 'utf8');++ const originalFetch = globalThis.fetch;+ vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {+ const url =+ typeof input === 'string'+ ? input+ : input instanceof URL+ ? input.toString()+ : input.url;+ if (url === 'https://s3.test.composio.dev/upload') {+ return Promise.resolve(+ new Response('Upload failed', { status: 500, statusText: 'Upload Failed' })+ );+ }+ return originalFetch(input, init);+ });++ const failure = yield* cli([+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--skip-connection-check',+ '-d',+ JSON.stringify({+ recipient_email: '[email protected]',+ attachment: tempFile,+ }),+ ]).pipe(+ Effect.flip,+ Effect.map(error => (error instanceof Error ? error.message : String(error)))+ );++ expect(failure).toContain('Failed to upload file to S3');++ fs.rmSync(tempFile, { force: true });+ })+ );+ }+ );++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email',+ tags: ['email'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {},+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )('[Given] --file for a tool with no file_uploadable input [Then] execute fails clearly', it => {+ it.scoped('rejects the convenience flag when the schema has no file input', () =>+ Effect.gen(function* () {+ const failure = yield* cli([+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--file',+ '/tmp/example.txt',+ ]).pipe(+ Effect.flip,+ Effect.map(error => (error instanceof Error ? error.message : String(error)))+ );++ expect(failure).toContain('has no file_uploadable input');+ })+ );+ });++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolkitsData: {+ tools: [+ {+ name: 'Multi Upload',+ slug: 'MULTI_UPLOAD_TOOL',+ description: 'Tool with two uploadable fields',+ tags: ['test'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ avatar: {+ type: 'object',+ file_uploadable: true,+ properties: {+ name: { type: 'string' },+ mimetype: { type: 'string' },+ s3key: { type: 'string' },+ },+ },+ resume: {+ type: 'object',+ file_uploadable: true,+ properties: {+ name: { type: 'string' },+ mimetype: { type: 'string' },+ s3key: { type: 'string' },+ },+ },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {},+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )(+ '[Given] --file for a tool with multiple file_uploadable inputs [Then] execute asks for explicit JSON',+ it => {+ it.scoped('fails instead of guessing which file field to use', () =>+ Effect.gen(function* () {+ const failure = yield* cli([+ 'execute',+ 'MULTI_UPLOAD_TOOL',+ '--file',+ '/tmp/example.txt',+ ]).pipe(+ Effect.flip,+ Effect.map(error => (error instanceof Error ? error.message : String(error)))+ );++ expect(failure).toContain('has multiple file_uploadable inputs');+ expect(failure).toContain('avatar');+ expect(failure).toContain('resume');+ })+ );+ }+ );+layer(TestLive({baseConfigProvider: testConfigProvider,@@ -887,7 +1425,7 @@ describe('CLI: composio execute', () => {expect(output).toContain('USAGE');expect(output).toContain(- 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--parallel]'+ 'composio execute <slug> [-d, --data text] [--file path] [--dry-run] [--get-schema] [--parallel]');expect(output).toContain('composio execute GMAIL_SEND_EMAIL --get-schema');expect(output).toContain('--parallel');diff --git a/ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.tsindex a63a6f404..5d5cb5e1c 100644--- a/ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts@@ -5,6 +5,19 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';import type { TestLiveInput } from 'test/__utils__/services/test-layer';import type { Tools } from 'src/models/tools';+const parseLastJson = (lines: ReadonlyArray<string>) => {+ for (let i = lines.length - 1; i >= 0; i -= 1) {+ const line = lines[i];+ if (!line) continue;+ try {+ return JSON.parse(line) as Record<string, unknown>;+ } catch {+ // continue+ }+ }+ throw new Error('Expected JSON output but none found');+};+const testTools: Tools = [{name: 'Send Email',@@ -39,6 +52,32 @@ const testTools: Tools = [input_parameters: { type: 'object', properties: {} },output_parameters: { type: 'object', properties: {} },},+ {+ name: 'Slack Upload',+ slug: 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK',+ description: 'Uploads a file to Slack',+ tags: ['files', 'slack'],+ available_versions: ['20260101_00'],+ input_parameters: {+ type: 'object',+ properties: {+ channels: { type: 'string', description: 'Slack channel ID' },+ file: {+ type: 'object',+ file_uploadable: true,+ title: 'File',+ description: 'Local file accepted by CLI',+ properties: {+ name: { type: 'string' },+ mimetype: { type: 'string' },+ s3key: { type: 'string' },+ },+ required: ['name', 'mimetype', 's3key'],+ },+ },+ },+ output_parameters: { type: 'object', properties: {} },+ },];const toolkitsData = {@@ -73,6 +112,35 @@ describe('CLI: composio tools info', () => {});+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(+ '[Given] file_uploadable tool info [Then] it shows the CLI-facing file schema',+ it => {+ it.scoped('renders file inputs as path strings in JSON output', () =>+ Effect.gen(function* () {+ yield* cli(['tools', 'info', 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines) as {+ inputSchema: Record<string, unknown>;+ };++ expect(output.inputSchema).toEqual({+ type: 'object',+ properties: {+ channels: { type: 'string', description: 'Slack channel ID' },+ file: {+ title: 'File',+ description: 'Local file accepted by CLI',+ format: 'path',+ type: 'string',+ file_uploadable: true,+ },+ },+ });+ })+ );+ }+ );+layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))('[Given] no slug [Then] warns missing argument',it => {