@devries-cameron20 / composio-1 / commits / df8a7817b
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): carry over open execute and proxy fixes (#5126)

This PR: - carries over three open CLI fixes onto `next`, one commit each, with the original authors credited via `Co-authored-by` trailers: - https://github.com/ComposioHQ/composio/pull/5106 by @vin-bio: local file uploads infer the MIME type from the filename (adds the `mime` dependency), and `execute --file` preserves arrays and fills the single matching upload field in an existing array item - https://github.com/ComposioHQ/composio/pull/5036: `composio execute` exits 1 when an argument names a local file but the tool can't upload it for that input, instead of sending the path text - https://github.com/ComposioHQ/composio/pull/4745 by @manobhisriram: `composio execute` and `composio proxy` fail with an error listing candidate accounts when several are connected, none is aliased `default`, and no `--account` is given - skips https://github.com/ComposioHQ/composio/pull/5035, already on `next` via https://github.com/ComposioHQ/composio/pull/5040 - reconciles #5106 and #5036 for tuple-shaped array schemas with an `itemSchemaAt` helper; the overlapping test is rewritten to expect only `files.0` to be refused - breaking: - scripts that relied on the implicit newest-account pick now fail; pass `--account <id|alias>` or alias one account `default`. The CHANGELOG lists this under Minor Changes with that migration hint - verified locally: typecheck 14/14, `lint:effect` 0 errors, CLI tests 209 files / 2422 passed / 1 skipped, validators OK, oxlint 0 errors --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 27, 2026 at 20:54 UTC df8a7817bbf5ba1244155fb9ea3ae5a835a65a28
12 files changed +1468 -187
pnpm-lock.yaml
+10
@@ -1267,6 +1267,9 @@ importers:
1267 json5:
1268 specifier: ^2.2.3
1269 version: 2.2.3
1270 + mime:
1271 + specifier: ^4.1.1
1272 + version: 4.1.1
1273 open:
1274 specifier: ^11.0.4
1275 version: 11.0.4
@@ -5599,6 +5602,11 @@ packages:
5602 resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==}
5603 engines: {node: '>=18'}
5604
5605 + mime@4.1.1:
5606 + resolution: {integrity: sha512-YAApRsTpM2+gnUFHhRNGfkX8NK0V5xj1nyQLufGlwEI+eX4xRsTcel2IXDuMEGSGjBvzykNW4VuoEACgwYe7BQ==}
5607 + engines: {node: '>=16'}
5608 + hasBin: true
5609 +
5610 mimic-function@5.0.1:
5611 resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}
5612 engines: {node: '>=18'}
@@ -10794,6 +10802,8 @@ snapshots:
10802 dependencies:
10803 mime-db: 1.54.0
10804
10805 + mime@4.1.1: {}
10806 +
10807 mimic-function@5.0.1: {}
10808
10809 miniflare@5.20260815.0-alpha(@types/node@26.6.5):
ts/packages/cli/CHANGELOG.md
+21 -1
@@ -10,7 +10,27 @@
10 exits 1. Without it, a failed event is still reported and skipped, and the
11 exit code stays 0.
12
13 -### Patch Changes
13 +- `composio execute` and `composio proxy` now fail with an error listing
14 + the candidate accounts, instead of silently using the newest one, when a
15 + toolkit has several connected accounts, none is aliased `default`, and no
16 + `--account` is passed. Scripts that relied on the implicit newest-account
17 + pick now fail. To migrate, pass `--account <id|alias>`, or alias one account
18 + `default`.
19 +
20 +### Patch Changes
21 +
22 +- `composio execute` now exits 1 when an argument names a file on your machine
23 + but the tool does not accept file uploads for that input, such as `file` in
24 + `TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD`. It used to send the path text to
25 + the tool and report success, and the tool stored that text instead of the
26 + file. The error names the input and the path. Nothing is sent. `--dry-run`
27 + reports the same error. Paths that do not exist on your machine are still
28 + sent as before.
29 +
30 +- Local file uploads now use the filename's MIME type instead of always declaring
31 + `application/octet-stream`. `execute --file` preserves arrays and injects into
32 + the single matching upload field in an existing array item; ambiguous targets
33 + require explicit JSON. This fixes Word and PowerPoint image editing through the CLI.
34
35 - `composio upgrade` no longer starts with a stale "Update available" line.
36 The line came from the cached daily update check, so right after a release
ts/packages/cli/package.json
+1
@@ -78,6 +78,7 @@
78 "fast-string-width": "^3.0.2",
79 "indent-string": "^5.0.0",
80 "json5": "^2.2.3",
81 + "mime": "^4.1.1",
82 "open": "^11.0.4",
83 "openapi-typescript": "^7.13.0",
84 "picocolors": "catalog:",
ts/packages/cli/src/commands/proxy.cmd.ts
+10 -8
@@ -344,14 +344,16 @@ export const proxyCmd = Command.make('proxy', {
344 orgId: resolvedProject.orgId,
345 projectId: resolvedProject.projectId,
346 });
347 - const selectedConnectedAccountId = Option.isSome(account)
348 - ? yield* resolveConnectedAccountForToolkit({
349 - client,
350 - toolkitSlug: normalizedToolkit,
351 - userId: consumerUserId,
352 - selector: account,
353 - })
354 - : undefined;
347 + // Always resolve through here, even with no --account: this is what
348 + // makes the "multiple accounts, none aliased default" case fail
349 + // loudly instead of resolveToolRouterSession silently picking one
350 + // via resolveDefaultConnectedAccountsByToolkit.
351 + const selectedConnectedAccountId = yield* resolveConnectedAccountForToolkit({
352 + client,
353 + toolkitSlug: normalizedToolkit,
354 + userId: consumerUserId,
355 + selector: account,
356 + });
357 const { sessionId, permissionSnapshot, connectedAccounts, connectedAccountWordIds } =
358 yield* resolveToolRouterSession(client, consumerUserId, {
359 toolkits: [normalizedToolkit],
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+88 -84
@@ -5,6 +5,8 @@ import { ExpectedFailure } from 'src/effects/expected-failure';
5 import { Argument, Command, Flag } from 'effect/cli';
6 import util from 'node:util';
7 import { Data, Effect, Context, Option, Result } from 'effect';
8 +import * as FileSystem from 'effect/FileSystem';
9 +import * as Path from 'effect/Path';
10 import { redact } from 'src/ui/redact';
11 import { parseJsonRecord, isPlainRecord } from 'src/utils/parse-json';
12 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
@@ -50,7 +52,14 @@ import {
52 resolveCliSessionArtifacts,
53 } from 'src/services/cli-session-artifacts';
54 import { storeCliSessionArtifact } from 'src/services/cli-session-artifacts';
53 -import { findFileUploadablePaths, normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
55 +import {
56 + findFileUploadablePaths,
57 + normalizeFileUploadSchema,
58 + schemaHasFileUploadable,
59 + rejectLocalFilesWithoutUpload,
60 + setArgumentAt,
61 +} from 'src/services/tool-file-uploads';
62 +import { isMetaToolSlug } from 'src/utils/meta-tool-slugs';
63 import {
64 ComposioNoActiveConnectionError,
65 mapComposioError,
@@ -168,46 +177,19 @@ const parseArguments = (raw: string) =>
177
178 const hasNestedKey = (
179 record: Record<string, unknown>,
171 - pathParts: ReadonlyArray<string>
180 + pathParts: ReadonlyArray<string | number>
181 ): boolean => {
182 let current: unknown = record;
183 for (const key of pathParts) {
175 - if (!isPlainRecord(current)) {
176 - return false;
177 - }
178 - if (!(key in current)) {
179 - return false;
180 - }
181 - current = current[key];
184 + if (Array.isArray(current) && typeof key === 'number' && key < current.length) {
185 + current = current[key];
186 + } else if (isPlainRecord(current) && typeof key === 'string' && Object.hasOwn(current, key)) {
187 + current = current[key];
188 + } else return false;
189 }
190 return true;
191 };
192
186 -const setNestedKey = (
187 - record: Record<string, unknown>,
188 - pathParts: ReadonlyArray<string>,
189 - value: unknown
190 -): Record<string, unknown> => {
191 - if (pathParts.length === 0) return record;
192 -
193 - const clone: Record<string, unknown> = { ...record };
194 - let current = clone;
195 -
196 - for (const [index, key] of pathParts.entries()) {
197 - if (index === pathParts.length - 1) {
198 - current[key] = value;
199 - break;
200 - }
201 -
202 - const next = current[key];
203 - const nextObject = isPlainRecord(next) ? { ...next } : {};
204 - current[key] = nextObject;
205 - current = nextObject;
206 - }
207 -
208 - return clone;
209 -};
210 -
193 const injectSingleFileArgument = (params: {
194 readonly slug: string;
195 readonly args: Record<string, unknown>;
@@ -215,13 +197,15 @@ const injectSingleFileArgument = (params: {
197 readonly schema: Record<string, unknown>;
198 }) =>
199 Effect.gen(function* () {
218 - const uploadablePaths = findFileUploadablePaths(params.schema);
200 + const uploadablePaths = findFileUploadablePaths(params.schema, [], params.args);
201
202 if (uploadablePaths.length === 0) {
203 return yield* new ToolExecutionError({
204 reason: 'file_input',
205 toolSlug: params.slug,
224 - message: `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`,
206 + message: schemaHasFileUploadable(params.schema)
207 + ? `Tool "${params.slug}" has no matching file_uploadable input in the supplied arguments. Supply the target array item with -d, or remove --file.`
208 + : `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`,
209 });
210 }
211
@@ -242,7 +226,7 @@ const injectSingleFileArgument = (params: {
226 });
227 }
228
245 - return setNestedKey(params.args, targetPath, params.filePath);
229 + return setArgumentAt(params.args, targetPath, params.filePath);
230 });
231
232 const connectionTips = (params: {
@@ -706,6 +690,43 @@ const handleExecutionError = (
690 return { error: mapped.message, slug: slugValue };
691 });
692
693 +// What a dry run checks, matching the real call: the arguments against the
694 +// schema unless checks are skipped, then any local file the tool cannot upload.
695 +// The real call refuses that file whatever the skip flags say, loading the
696 +// schema for it and going on without one, and never for a meta tool, which
697 +// uploads nothing. Returns the schema only when the arguments were checked.
698 +const checkDryRunArguments = (params: {
699 + readonly slug: string;
700 + readonly args: Record<string, unknown>;
701 + readonly projectScope: { readonly orgId?: string; readonly projectId?: string };
702 + readonly verificationDisabled: boolean;
703 +}) =>
704 + Effect.gen(function* () {
705 + const { slug, args, verificationDisabled } = params;
706 + if (verificationDisabled && isMetaToolSlug(slug)) return null;
707 +
708 + const definition = verificationDisabled
709 + ? yield* getOrFetchToolInputDefinition(slug, params.projectScope).pipe(
710 + Effect.catch(() => Effect.succeed(null))
711 + )
712 + : yield* getOrFetchToolInputDefinition(slug, params.projectScope);
713 + if (!definition) return null;
714 +
715 + if (!verificationDisabled) {
716 + yield* validateToolInputArgumentsWithDefinition(slug, args, definition);
717 + }
718 + if (!isMetaToolSlug(slug)) {
719 + yield* rejectLocalFilesWithoutUpload({
720 + fs: yield* FileSystem.FileSystem,
721 + path: yield* Path.Path,
722 + toolSlug: slug,
723 + arguments_: args,
724 + inputSchema: definition.schema,
725 + });
726 + }
727 + return verificationDisabled ? null : definition;
728 + });
729 +
730 // Gates the tool call: the request is only sent once the arguments pass. A
731 // schema that cannot be loaded does not block the call, the server validates too.
732 const validateToolInputBeforeExecute = (params: {
@@ -1121,43 +1142,27 @@ const runExecuteWithSpinner = (params: {
1142 yield* params.ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
1143 Effect.gen(function* () {
1144 if (params.dryRun) {
1124 - const definition = verificationDisabled
1125 - ? null
1126 - : yield* getOrFetchToolInputDefinition(params.slug, {
1127 - orgId: params.resolvedProject.orgId,
1128 - projectId: params.resolvedProject.projectId,
1129 - }).pipe(
1130 - Effect.tapError(error =>
1131 - emitExecuteFailureTelemetry({
1132 - toolSlug: params.slug,
1133 - args: params.args,
1134 - error,
1135 - surface: params.surface,
1136 - projectMode: params.projectMode,
1137 - stage: 'dry_run',
1138 - projectScope: toolkitProjectScope(params.resolvedProject),
1139 - })
1140 - )
1141 - );
1142 - if (definition) {
1143 - yield* validateToolInputArgumentsWithDefinition(
1144 - params.slug,
1145 - params.args,
1146 - definition
1147 - ).pipe(
1148 - Effect.tapError(error =>
1149 - emitExecuteFailureTelemetry({
1150 - toolSlug: params.slug,
1151 - args: params.args,
1152 - error,
1153 - surface: params.surface,
1154 - projectMode: params.projectMode,
1155 - stage: 'dry_run',
1156 - projectScope: toolkitProjectScope(params.resolvedProject),
1157 - })
1158 - )
1159 - );
1160 - }
1145 + const definition = yield* checkDryRunArguments({
1146 + slug: params.slug,
1147 + args: params.args,
1148 + projectScope: {
1149 + orgId: params.resolvedProject.orgId,
1150 + projectId: params.resolvedProject.projectId,
1151 + },
1152 + verificationDisabled,
1153 + }).pipe(
1154 + Effect.tapError(error =>
1155 + emitExecuteFailureTelemetry({
1156 + toolSlug: params.slug,
1157 + args: params.args,
1158 + error,
1159 + surface: params.surface,
1160 + projectMode: params.projectMode,
1161 + stage: 'dry_run',
1162 + projectScope: toolkitProjectScope(params.resolvedProject),
1163 + })
1164 + )
1165 + );
1166 const summary: DryRunSummary = {
1167 successful: true,
1168 dryRun: true,
@@ -1755,16 +1760,15 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1760 });
1761
1762 if (params.dryRun) {
1758 - const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;
1759 - const definition = verificationDisabled
1760 - ? null
1761 - : yield* getOrFetchToolInputDefinition(toolSlug, {
1762 - orgId: context.resolvedProject.orgId,
1763 - projectId: context.resolvedProject.projectId,
1764 - });
1765 - if (definition) {
1766 - yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);
1767 - }
1763 + const definition = yield* checkDryRunArguments({
1764 + slug: toolSlug,
1765 + args: context.args,
1766 + projectScope: {
1767 + orgId: context.resolvedProject.orgId,
1768 + projectId: context.resolvedProject.projectId,
1769 + },
1770 + verificationDisabled: params.skipChecks || params.skipToolParamsCheck,
1771 + });
1772 return {
1773 successful: true,
1774 dryRun: true,
ts/packages/cli/src/services/connected-account-selection.ts
+30 -4
@@ -287,12 +287,38 @@ export const resolveConnectedAccountForToolkit = (params: {
287 )
288 );
289
290 + // A selector that is empty or all-whitespace (e.g. `--account=`) is
291 + // treated as "no selector" by resolveConnectedAccountSelection below; the
292 + // ambiguity guard below it must agree, or an empty --account value would
293 + // silently reach the "exactly one choice" fallback instead of failing.
294 + const effectiveSelector = Option.filter(params.selector, value => value.trim().length > 0);
295 +
296 const selected = resolveConnectedAccountSelection(
297 selectableAccounts,
292 - Option.getOrUndefined(params.selector)
298 + Option.getOrUndefined(effectiveSelector)
299 );
294 - if (selected) return selected.id;
295 - if (Option.isNone(params.selector)) return undefined;
300 +
301 + if (selected) {
302 + // No --account given: if more than one usable account exists and none
303 + // is the explicit alias=default, picking one silently is dangerous
304 + // (e.g. an agent reading/writing the wrong mailbox). Fail the same way
305 + // an unmatched selector already does, instead of guessing.
306 + if (Option.isNone(effectiveSelector)) {
307 + const usable = selectableAccounts.filter(isUsableConnectedAccount);
308 + const hasExplicitDefault = usable.some(
309 + item => normalizeSelector(item.alias ?? '') === 'default'
310 + );
311 + if (!hasExplicitDefault && usable.length > 1) {
312 + const choices = formatConnectedAccountChoices(selectableAccounts);
313 + return yield* new ConnectedAccountResolutionError({
314 + message: `Multiple connected accounts exist for toolkit "${toolkitSlug}" and no --account was given. Available accounts: ${choices.join(', ')}. Pass --account <alias or id> to choose one.`,
315 + toolkitSlug,
316 + });
317 + }
318 + }
319 + return selected.id;
320 + }
321 + if (Option.isNone(effectiveSelector)) return undefined;
322
323 const choices = formatConnectedAccountChoices(selectableAccounts);
324 const hint =
@@ -300,7 +326,7 @@ export const resolveConnectedAccountForToolkit = (params: {
326 ? ` Available accounts: ${choices.join(', ')}.`
327 : ' No active connected accounts were found for that toolkit.';
328 return yield* new ConnectedAccountResolutionError({
303 - message: `No connected account matched "${params.selector.value}" for toolkit "${toolkitSlug}".${hint}`,
329 + message: `No connected account matched "${effectiveSelector.value}" for toolkit "${toolkitSlug}".${hint}`,
330 toolkitSlug,
331 });
332 });
ts/packages/cli/src/services/tool-file-uploads.ts
+279 -83
@@ -7,7 +7,9 @@ import type * as FileSystem from 'effect/FileSystem';
7 import type * as Path from 'effect/Path';
8 import type { ComposioClientShape, ComposioError } from '@composio/client/effect';
9 import { Data, Effect, Predicate } from 'effect';
10 +import mime from 'mime';
11 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
12 +import { isPlainRecord } from 'src/utils/parse-json';
13 import { idempotent } from 'src/services/composio-request';
14
15 type JsonSchema = Record<string, unknown>;
@@ -22,7 +24,8 @@ const loadSsrfSafeFetch = Effect.promise(() => import('@composio/core/utils/ssrf
24 export class ToolFileUploadError extends Data.TaggedError('services/ToolFileUploadError')<{
25 readonly cause?: unknown;
26 readonly message: string;
25 - readonly reason: 'source-fetch' | 'source-read' | 'unsupported-source' | 'upload';
27 + readonly reason:
28 + 'not-uploadable' | 'source-fetch' | 'source-read' | 'unsupported-source' | 'upload';
29 readonly status?: number;
30 }> {}
31
@@ -56,10 +59,10 @@ const isSchemaRecord = (value: unknown): value is JsonSchema => Predicate.isObje
59 const getSchemaVariant = (value: unknown): ReadonlyArray<JsonSchema> =>
60 Array.isArray(value) ? value.filter(isSchemaRecord) : [];
61
59 -// `items` is either one schema or a tuple of schemas; keep only the schema records.
60 -const getItemSchemas = (items: unknown): ReadonlyArray<JsonSchema> => {
61 - if (Array.isArray(items)) return items.filter(isSchemaRecord);
62 - return isSchemaRecord(items) ? [items] : [];
62 +// `items` is either one schema for every element or a tuple of per-index schemas.
63 +const itemSchemaAt = (items: unknown, index: number): JsonSchema | undefined => {
64 + const itemSchema = Array.isArray(items) ? items[index] : items;
65 + return isSchemaRecord(itemSchema) ? itemSchema : undefined;
66 };
67
68 const getSchemaVariants = (schema: JsonSchema | undefined): ReadonlyArray<JsonSchema> => [
@@ -141,10 +144,29 @@ export const schemaHasFileUploadable = (schema: JsonSchema | undefined): boolean
144 return false;
145 };
146
147 +// Where a value sits in the tool arguments: object keys and array indices.
148 +export type ArgumentPath = ReadonlyArray<string | number>;
149 +
150 +// Whether a branch can describe the value, judged by its `const` properties.
151 +// A supplied property with another value rules the branch out, as does a
152 +// required one the caller left out; an omitted optional one rules nothing out.
153 +const matchesDiscriminants = (schema: JsonSchema, value: unknown): boolean => {
154 + if (!isSchemaRecord(schema.properties) || !isSchemaRecord(value)) return true;
155 + const required = Array.isArray(schema.required) ? schema.required : [];
156 + return Object.entries(schema.properties).every(([key, property]) => {
157 + if (!isSchemaRecord(property) || !Object.hasOwn(property, 'const')) return true;
158 + if (!Object.hasOwn(value, key)) return !required.includes(key);
159 + return value[key] === property.const;
160 + });
161 +};
162 +
163 +// Bind array schemas to the caller's existing items. A schema-only path loses
164 +// the index and would cause --file to replace the array with an object.
165 export const findFileUploadablePaths = (
166 schema: JsonSchema | undefined,
146 - basePath: ReadonlyArray<string> = []
147 -): ReadonlyArray<ReadonlyArray<string>> => {
167 + basePath: ArgumentPath = [],
168 + value?: unknown
169 +): ReadonlyArray<ArgumentPath> => {
170 if (!schema) return [];
171
172 if (schema.file_uploadable === true) {
@@ -153,27 +175,245 @@ export const findFileUploadablePaths = (
175
176 const directPropertyPaths = isSchemaRecord(schema.properties)
177 ? Object.entries(schema.properties).flatMap(([key, property]) =>
156 - isSchemaRecord(property) ? findFileUploadablePaths(property, [...basePath, key]) : []
178 + isSchemaRecord(property)
179 + ? findFileUploadablePaths(
180 + property,
181 + [...basePath, key],
182 + isSchemaRecord(value) ? value[key] : undefined
183 + )
184 + : []
185 )
186 : [];
187
160 - const variantPaths = getSchemaVariants(schema).flatMap(variant =>
161 - findFileUploadablePaths(variant, basePath)
162 - );
188 + const variantPaths = getSchemaVariants(schema)
189 + .filter(variant => matchesDiscriminants(variant, value))
190 + .flatMap(variant => findFileUploadablePaths(variant, basePath, value));
191
164 - const itemPaths = getItemSchemas(schema.items).flatMap(item =>
165 - findFileUploadablePaths(item, basePath)
166 - );
192 + const itemPaths = Array.isArray(value)
193 + ? value.flatMap((item, index) =>
194 + findFileUploadablePaths(itemSchemaAt(schema.items, index), [...basePath, index], item)
195 + )
196 + : [];
197
198 const seen = new Set<string>();
199 return [...directPropertyPaths, ...variantPaths, ...itemPaths].filter(pathParts => {
170 - const key = pathParts.join('.');
200 + const key = JSON.stringify(pathParts);
201 + if (seen.has(key)) return false;
202 + seen.add(key);
203 + return true;
204 + });
205 +};
206 +
207 +// Wording of inputs that take a file on the caller's machine, as the tool
208 +// catalog writes it: "Path to the local file to attach", "Local filesystem path
209 +// to the file to upload", "Path to the file to upload".
210 +const LOCAL_FILE_DESCRIPTION =
211 + /\blocal(?:ly)?[\s-]+(?:file|path|filesystem|file\s*system|disk)\b|\bpath\b[^.]{0,40}\bfile\b[^.]{0,40}\bupload/i;
212 +
213 +const describesLocalFile = (schema: JsonSchema): boolean =>
214 + [schema.title, schema.description].some(
215 + text => Predicate.isString(text) && LOCAL_FILE_DESCRIPTION.test(text)
216 + );
217 +
218 +// A path-shaped value: a separator or an extension, and no URL scheme. Keeps a
219 +// bare word such as "claude_code" from matching a file of that name.
220 +const looksLikeFilePath = (path: Path.Path, value: string): boolean =>
221 + !/^[a-z][a-z0-9+.-]*:\/\//i.test(value) &&
222 + (value.includes('/') || value.includes('\\') || path.extname(value) !== '');
223 +
224 +type LocalPathArgument = {
225 + readonly argumentPath: ArgumentPath;
226 + readonly value: string;
227 +};
228 +
229 +type UploadSite = {
230 + readonly argumentPath: ArgumentPath;
231 + readonly source: string | File;
232 +};
233 +
234 +/**
235 + * The schema and every `anyOf`/`oneOf`/`allOf` branch under it, at any depth:
236 + * all the schemas that can describe one value. Schemas are parsed JSON, so the
237 + * walk ends, as `findFileUploadablePaths` does on the same schema.
238 + */
239 +const schemasForValue = (schema: JsonSchema): ReadonlyArray<JsonSchema> => [
240 + schema,
241 + ...getSchemaVariants(schema).flatMap(schemasForValue),
242 +];
243 +
244 +const collectUploadSites = (
245 + value: unknown,
246 + schema: JsonSchema | undefined,
247 + argumentPath: ArgumentPath
248 +): ReadonlyArray<UploadSite> => {
249 + if (schema?.file_uploadable === true) {
250 + return Predicate.isString(value) || isFileLike(value) ? [{ argumentPath, source: value }] : [];
251 + }
252 +
253 + const uploadableVariants = getSchemaVariants(schema).filter(schemaHasFileUploadable);
254 + if (uploadableVariants.length > 0) {
255 + return uploadableVariants.flatMap(variant => collectUploadSites(value, variant, argumentPath));
256 + }
257 +
258 + const properties = schema?.properties;
259 + if (isSchemaRecord(properties) && Predicate.isObject(value)) {
260 + return Object.entries(value).flatMap(([key, entry]) =>
261 + collectUploadSites(entry, isSchemaRecord(properties[key]) ? properties[key] : undefined, [
262 + ...argumentPath,
263 + key,
264 + ])
265 + );
266 + }
267 +
268 + if (schema?.type === 'array' && Array.isArray(value) && schema.items) {
269 + return value.flatMap((item, index) =>
270 + collectUploadSites(item, itemSchemaAt(schema.items, index), [...argumentPath, index])
271 + );
272 + }
273 +
274 + return [];
275 +};
276 +
277 +/**
278 + * Every argument `uploadToolInputFiles` uploads, once per location even when
279 + * several branches mark it uploadable. The upload and the local-file guard
280 + * both read this one walk, so the guard exempts exactly what is uploaded.
281 + */
282 +const findUploadSites = (value: unknown, schema: JsonSchema): ReadonlyArray<UploadSite> => {
283 + const seen = new Set<string>();
284 + return collectUploadSites(value, schema, []).filter(site => {
285 + const key = JSON.stringify(site.argumentPath);
286 if (seen.has(key)) return false;
287 seen.add(key);
288 return true;
289 });
290 };
291
292 +/**
293 + * A copy of `record` with `value` at `argumentPath`, creating the objects on
294 + * the way. An index into anything but an existing array changes nothing.
295 + */
296 +export const setArgumentAt = (
297 + record: Record<string, unknown>,
298 + argumentPath: ArgumentPath,
299 + value: unknown
300 +): Record<string, unknown> => {
301 + const set = (current: unknown, remaining: ArgumentPath): unknown => {
302 + const [key, ...rest] = remaining;
303 + if (key === undefined) return value;
304 + if (typeof key === 'number') {
305 + if (!Array.isArray(current)) return current;
306 + const copy = [...current];
307 + copy[key] = set(copy[key], rest);
308 + return copy;
309 + }
310 + const copy = isPlainRecord(current) ? { ...current } : {};
311 + copy[key] = set(copy[key], rest);
312 + return copy;
313 + };
314 + const updated = set(record, argumentPath);
315 + return isPlainRecord(updated) ? updated : record;
316 +};
317 +
318 +const collectLocalPathCandidates = (
319 + value: unknown,
320 + schemas: ReadonlyArray<JsonSchema>,
321 + argumentPath: ArgumentPath
322 +): ReadonlyArray<LocalPathArgument> => {
323 + const nodes = schemas.flatMap(schemasForValue);
324 +
325 + if (Predicate.isString(value)) {
326 + return nodes.some(describesLocalFile) ? [{ argumentPath, value }] : [];
327 + }
328 +
329 + if (Array.isArray(value)) {
330 + return value.flatMap((item, index) =>
331 + collectLocalPathCandidates(
332 + item,
333 + nodes.flatMap(node => {
334 + const itemSchema = itemSchemaAt(node.items, index);
335 + return itemSchema ? [itemSchema] : [];
336 + }),
337 + [...argumentPath, index]
338 + )
339 + );
340 + }
341 +
342 + if (Predicate.isObject(value)) {
343 + return Object.entries(value).flatMap(([key, entry]) =>
344 + collectLocalPathCandidates(
345 + entry,
346 + nodes.flatMap(node => {
347 + const property = isSchemaRecord(node.properties) ? node.properties[key] : undefined;
348 + return isSchemaRecord(property) ? [property] : [];
349 + }),
350 + [...argumentPath, key]
351 + )
352 + );
353 + }
354 +
355 + return [];
356 +};
357 +
358 +/**
359 + * The string arguments a schema describes as a local file without marking
360 + * them `file_uploadable`. Composio runs the tool remotely and only uploads
361 + * `file_uploadable` inputs, so such an argument reaches the tool as the text of
362 + * the path, never as the file. Every branch that applies to a value is read
363 + * for the description, and a value that is uploaded is never returned.
364 + */
365 +export const findLocalPathArguments = (
366 + value: unknown,
367 + schema: JsonSchema | undefined
368 +): ReadonlyArray<LocalPathArgument> => {
369 + if (!schema) return [];
370 + const uploaded = new Set(
371 + findUploadSites(value, schema).map(site => JSON.stringify(site.argumentPath))
372 + );
373 + return collectLocalPathCandidates(value, [schema], []).filter(
374 + candidate => !uploaded.has(JSON.stringify(candidate.argumentPath))
375 + );
376 +};
377 +
378 +/**
379 + * Fails when an argument the schema describes as a local file names a file
380 + * that exists on this machine but the input is not `file_uploadable`: the tool
381 + * would get the path text instead of the file and still report success
382 + * (issue #4965). A path that does not exist here is left alone, since it may
383 + * name a file on the remote side.
384 + */
385 +export const rejectLocalFilesWithoutUpload = (params: {
386 + readonly fs: FileSystem.FileSystem;
387 + readonly path: Path.Path;
388 + readonly toolSlug: string;
389 + readonly arguments_: Record<string, unknown>;
390 + readonly inputSchema: JsonSchema;
391 +}) =>
392 + Effect.gen(function* () {
393 + const candidates = findLocalPathArguments(params.arguments_, params.inputSchema).filter(
394 + candidate => looksLikeFilePath(params.path, candidate.value)
395 + );
396 + const localFiles = yield* Effect.filter(candidates, candidate =>
397 + params.fs.stat(candidate.value).pipe(
398 + Effect.map(info => info.type === 'File'),
399 + Effect.orElseSucceed(() => false)
400 + )
401 + );
402 + if (localFiles.length === 0) return;
403 +
404 + const named = localFiles
405 + .map(({ argumentPath, value }) => `"${argumentPath.join('.')}" (${value})`)
406 + .join(', ');
407 + return yield* new ToolFileUploadError({
408 + reason: 'not-uploadable',
409 + message:
410 + `${params.toolSlug} cannot upload local files: ${named} names a file on this machine, ` +
411 + 'but the tool does not mark that input as a file upload, so Composio would receive the ' +
412 + 'path text instead of the file content. Nothing was executed. Use a URL input if the ' +
413 + 'tool has one, or report the tool schema to Composio.',
414 + });
415 + });
416 +
417 const readFileFromUrl = (path: Path.Path, url: string) =>
418 Effect.gen(function* () {
419 const { ssrfSafeFetch } = yield* loadSsrfSafeFetch;
@@ -240,7 +480,7 @@ const readFileFromDisk = (fs: FileSystem.FileSystem, path: Path.Path, filePath:
480 // wider ArrayBufferLike-backed Uint8Array that FileSystem returns.
481 bytes: new Uint8Array(bytes),
482 fileName: path.basename(filePath),
243 - mimeType: 'application/octet-stream',
483 + mimeType: mime.getType(path.basename(filePath)) ?? 'application/octet-stream',
484 };
485 });
486
@@ -327,68 +567,28 @@ const uploadFile = (params: {
567 };
568 });
569
570 +// Uploads every upload site and puts the uploaded file's reference in place of
571 +// its source.
572 const hydrateFileUploads = (
331 - value: unknown,
332 - schema: JsonSchema | undefined,
333 - ctx: {
334 - readonly fs: FileSystem.FileSystem;
335 - readonly path: Path.Path;
336 - readonly toolSlug: string;
337 - readonly toolkitSlug: string;
338 - readonly client: ComposioClientShape;
339 - }
340 -): Effect.Effect<unknown, ToolInputUploadError> =>
341 - Effect.gen(function* () {
342 - if (schema?.file_uploadable === true) {
343 - if (typeof value !== 'string' && !isFileLike(value)) {
344 - return value;
345 - }
346 -
347 - return yield* uploadFile({
348 - fs: ctx.fs,
349 - path: ctx.path,
350 - file: value,
351 - toolSlug: ctx.toolSlug,
352 - toolkitSlug: ctx.toolkitSlug,
353 - client: ctx.client,
354 - });
355 - }
356 -
357 - const uploadableVariants = getSchemaVariants(schema).filter(schemaHasFileUploadable);
358 - if (uploadableVariants.length > 0) {
359 - let nextValue = value;
360 - for (const variant of uploadableVariants) {
361 - nextValue = yield* hydrateFileUploads(nextValue, variant, ctx);
362 - }
363 - return nextValue;
364 - }
365 -
366 - if (isSchemaRecord(schema?.properties) && Predicate.isObject(value)) {
367 - const properties = schema.properties;
368 - const entries = yield* Effect.all(
369 - Object.entries(value).map(([key, entryValue]) =>
370 - hydrateFileUploads(
371 - entryValue,
372 - isSchemaRecord(properties[key]) ? properties[key] : undefined,
373 - ctx
374 - ).pipe(Effect.map(hydrated => [key, hydrated] as const))
375 - ),
376 - { concurrency: 'unbounded' }
377 - );
378 - return Object.fromEntries(entries);
379 - }
380 -
381 - if (schema?.type === 'array' && Array.isArray(value) && schema.items) {
382 - const itemSchema = getItemSchemas(schema.items).at(0);
383 -
384 - return yield* Effect.all(
385 - value.map(item => hydrateFileUploads(item, itemSchema, ctx)),
386 - { concurrency: 'unbounded' }
387 - );
388 - }
389 -
390 - return value;
391 - });
573 + arguments_: Record<string, unknown>,
574 + schema: JsonSchema,
575 + ctx: Omit<Parameters<typeof uploadFile>[0], 'file'>
576 +): Effect.Effect<Record<string, unknown>, ToolInputUploadError> =>
577 + Effect.forEach(
578 + findUploadSites(arguments_, schema),
579 + site =>
580 + uploadFile({ ...ctx, file: site.source }).pipe(
581 + Effect.map(uploaded => [site.argumentPath, uploaded] as const)
582 + ),
583 + { concurrency: 'unbounded' }
584 + ).pipe(
585 + Effect.map(uploads =>
586 + uploads.reduce(
587 + (args, [argumentPath, uploaded]) => setArgumentAt(args, argumentPath, uploaded),
588 + arguments_
589 + )
590 + )
591 + );
592
593 export const uploadToolInputFiles = (params: {
594 readonly fs: FileSystem.FileSystem;
@@ -400,17 +600,13 @@ export const uploadToolInputFiles = (params: {
600 readonly toolkitSlug?: string;
601 }): Effect.Effect<Record<string, unknown>, ToolInputUploadError> =>
602 Effect.gen(function* () {
403 - if (!schemaHasFileUploadable(params.inputSchema)) {
404 - return params.arguments_;
405 - }
603 + yield* rejectLocalFilesWithoutUpload(params);
604
407 - const hydrated = yield* hydrateFileUploads(params.arguments_, params.inputSchema, {
605 + return yield* hydrateFileUploads(params.arguments_, params.inputSchema, {
606 fs: params.fs,
607 path: params.path,
608 toolSlug: params.toolSlug,
609 toolkitSlug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug) ?? 'unknown',
610 client: params.client,
611 });
414 -
415 - return Predicate.isObject(hydrated) ? hydrated : params.arguments_;
612 });
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+94
@@ -202,6 +202,100 @@ describe('CLI: composio proxy', () => {
202 }
203 );
204
205 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
206 + '[Given] no --account and several connected accounts, none aliased default [Then] proxy fails instead of silently picking one',
207 + it => {
208 + it.effect('fails before creating a session', () =>
209 + Effect.gen(function* () {
210 + let createCalled = false;
211 + const live = TestLive({
212 + baseConfigProvider: testConfigProvider,
213 + fixture: 'global-test-user-id',
214 + cliUserConfig: { experimentalFeatures: { multi_account: false } },
215 + connectedAccountsData: {
216 + items: [
217 + {
218 + id: 'con_gmail_work',
219 + alias: 'work',
220 + word_id: 'gmail-work',
221 + status: 'ACTIVE',
222 + status_reason: null,
223 + is_disabled: false,
224 + user_id: 'consumer-user-org_test',
225 + toolkit: { slug: 'gmail' },
226 + auth_config: {
227 + id: 'ac_gmail_oauth',
228 + auth_scheme: 'OAUTH2',
229 + is_composio_managed: true,
230 + is_disabled: false,
231 + },
232 + created_at: '2026-01-01T00:00:00.000Z',
233 + updated_at: '2026-01-01T00:00:00.000Z',
234 + test_request_endpoint: '',
235 + },
236 + {
237 + id: 'con_gmail_personal',
238 + alias: 'personal',
239 + word_id: 'gmail-personal',
240 + status: 'ACTIVE',
241 + status_reason: null,
242 + is_disabled: false,
243 + user_id: 'consumer-user-org_test',
244 + toolkit: { slug: 'gmail' },
245 + auth_config: {
246 + id: 'ac_gmail_oauth',
247 + auth_scheme: 'OAUTH2',
248 + is_composio_managed: true,
249 + is_disabled: false,
250 + },
251 + created_at: '2026-01-02T00:00:00.000Z',
252 + updated_at: '2026-01-02T00:00:00.000Z',
253 + test_request_endpoint: '',
254 + },
255 + ],
256 + },
257 + toolRouter: {
258 + create: (_params: SessionCreateParams) =>
259 + Effect.sync(() => {
260 + createCalled = true;
261 + return {
262 + session_id: 'trs_proxy_test',
263 + config: {
264 + user_id: 'consumer-user-org_test',
265 + execute: {},
266 + search: {},
267 + preload: { tools: [] },
268 + instant: false,
269 + },
270 + config_version: 1,
271 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
272 + tool_router_tools: [],
273 + };
274 + }),
275 + },
276 + });
277 +
278 + const failure = yield* Effect.gen(function* () {
279 + return yield* cli([
280 + 'proxy',
281 + 'https://gmail.googleapis.com/gmail/v1/users/me/drafts',
282 + '--toolkit',
283 + 'gmail',
284 + '--skip-connection-check',
285 + '-X',
286 + 'post',
287 + ]).pipe(Effect.flip);
288 + }).pipe(Effect.provide(live));
289 +
290 + expect(createCalled).toBe(false);
291 + expect(String(failure)).toContain(
292 + 'Multiple connected accounts exist for toolkit "gmail"'
293 + );
294 + })
295 + );
296 + }
297 + );
298 +
299 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
300 '[Given] cached missing toolkit [Then] proxy fails fast before session creation',
301 it => {
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+263 -5
@@ -3,7 +3,7 @@ import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { describe, expect, it, layer } from '@effect/vitest';
5 import { vi, beforeEach, afterEach } from 'vitest';
6 -import { Config, ConfigProvider, DateTime, Effect, Exit, Option } from 'effect';
6 +import { Config, ConfigProvider, DateTime, Effect, Exit, Option, Schema } from 'effect';
7 import { APIConnectionError, BadRequestError } from '@composio/client/effect';
8 import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
9 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -120,6 +120,120 @@ const parseLastJson = (lines: ReadonlyArray<string>) =>
120 };
121
122 describe('CLI: composio execute', () => {
123 + layer(
124 + TestLive({
125 + baseConfigProvider: testConfigProvider,
126 + fixture: 'global-test-user-id',
127 + stdin: { isTTY: true, data: '' },
128 + toolkitsData: {
129 + tools: [
130 + {
131 + name: 'Nested Image Edit',
132 + slug: 'NESTED_IMAGE_EDIT_TOOL',
133 + description: 'Edit fixture',
134 + tags: ['test'],
135 + available_versions: ['20260316_00'],
136 + input_parameters: {
137 + type: 'object',
138 + properties: {
139 + item_id: { type: 'string' },
140 + operations: {
141 + type: 'array',
142 + items: {
143 + oneOf: [
144 + {
145 + type: 'object',
146 + properties: { type: { const: 'set_text' }, text: { type: 'string' } },
147 + required: ['type', 'text'],
148 + },
149 + {
150 + type: 'object',
151 + properties: {
152 + type: { const: 'add_image' },
153 + image: { type: 'object', file_uploadable: true },
154 + },
155 + required: ['type', 'image'],
156 + },
157 + {
158 + type: 'object',
159 + properties: {
160 + type: { const: 'replace_image' },
161 + image: { type: 'object', file_uploadable: true },
162 + },
163 + required: ['type', 'image'],
164 + },
165 + ],
166 + },
167 + },
168 + },
169 + },
170 + output_parameters: { type: 'object', properties: {} },
171 + },
172 + ],
173 + } satisfies TestLiveInput['toolkitsData'],
174 + })
175 + )('nested --file array injection', it => {
176 + it.effect('preserves sibling operations and injects into the selected array element', () =>
177 + Effect.gen(function* () {
178 + const operations = [{ type: 'set_text', text: 'Preserve me' }, { type: 'add_image' }];
179 + yield* cli([
180 + 'execute',
181 + 'NESTED_IMAGE_EDIT_TOOL',
182 + '--skip-connection-check',
183 + '--dry-run',
184 + '--file',
185 + '/tmp/dogfood.png',
186 + '-d',
187 + JSON.stringify({ item_id: 'deck', operations }),
188 + ]);
189 + const output = Schema.decodeUnknownSync(Schema.Struct({ arguments: Schema.Unknown }))(
190 + parseLastJson(yield* MockConsole.getLines({ stripAnsi: true }))
191 + );
192 + expect(output.arguments).toEqual({
193 + item_id: 'deck',
194 + operations: [
195 + { type: 'set_text', text: 'Preserve me' },
196 + { type: 'add_image', image: '/tmp/dogfood.png' },
197 + ],
198 + });
199 + expect(operations).toEqual([
200 + { type: 'set_text', text: 'Preserve me' },
201 + { type: 'add_image' },
202 + ]);
203 + })
204 + );
205 +
206 + it.effect.each([
207 + {
208 + operations: [{ type: 'add_image' }, { type: 'replace_image' }],
209 + message: 'multiple file_uploadable inputs',
210 + },
211 + {
212 + operations: [{ type: 'add_image', image: '/tmp/existing.png' }],
213 + message: 'already set in -d',
214 + },
215 + { operations: [], message: 'no matching file_uploadable input' },
216 + {
217 + operations: [{ type: 'set_text', text: 'Keep' }],
218 + message: 'no matching file_uploadable input',
219 + },
220 + ])('rejects without overwriting: $message ($operations)', scenario =>
221 + Effect.gen(function* () {
222 + const failure = yield* cli([
223 + 'execute',
224 + 'NESTED_IMAGE_EDIT_TOOL',
225 + '--skip-connection-check',
226 + '--dry-run',
227 + '--file',
228 + '/tmp/dogfood.png',
229 + '-d',
230 + JSON.stringify({ operations: scenario.operations }),
231 + ]).pipe(Effect.flip);
232 + expect(String(failure)).toContain(scenario.message);
233 + })
234 + );
235 + });
236 +
237 it.effect('returns a CLI validation error for malformed parallel arguments', () =>
238 Effect.gen(function* () {
239 const failure = yield* parseParallelExecuteArgs(['--parallel', '--data', '{}'], {
@@ -1934,7 +2048,7 @@ describe('CLI: composio execute', () => {
2048 recipient_email: 'a@b.com',
2049 attachment: {
2050 name: path.basename(tempFile),
1937 - mimetype: 'application/octet-stream',
2051 + mimetype: 'text/plain',
2052 s3key: `uploads/${path.basename(tempFile)}`,
2053 },
2054 });
@@ -1943,7 +2057,7 @@ describe('CLI: composio execute', () => {
2057 expect.objectContaining({
2058 method: 'PUT',
2059 headers: expect.objectContaining({
1946 - 'Content-Type': 'application/octet-stream',
2060 + 'Content-Type': 'text/plain',
2061 }),
2062 })
2063 );
@@ -2024,7 +2138,7 @@ describe('CLI: composio execute', () => {
2138 channels: 'C123',
2139 file: {
2140 name: path.basename(tempFile),
2027 - mimetype: 'application/octet-stream',
2141 + mimetype: 'image/png',
2142 s3key: `uploads/${path.basename(tempFile)}`,
2143 },
2144 });
@@ -2110,7 +2224,7 @@ describe('CLI: composio execute', () => {
2224 payload: {
2225 file: {
2226 name: path.basename(tempFile),
2113 - mimetype: 'application/octet-stream',
2227 + mimetype: 'image/png',
2228 s3key: `uploads/${path.basename(tempFile)}`,
2229 },
2230 },
@@ -2208,6 +2322,150 @@ describe('CLI: composio execute', () => {
2322 }
2323 );
2324
2325 + layer(
2326 + TestLive({
2327 + baseConfigProvider: testConfigProvider,
2328 + fixture: 'global-test-user-id',
2329 + stdin: { isTTY: true, data: '' },
2330 + toolkitsData: {
2331 + tools: [
2332 + {
2333 + name: 'Add attachment to card',
2334 + slug: 'TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD',
2335 + description: 'Adds an attachment to a Trello card',
2336 + tags: ['trello'],
2337 + available_versions: ['20261007_01'],
2338 + input_parameters: {
2339 + type: 'object',
2340 + required: ['idCard'],
2341 + properties: {
2342 + idCard: { type: 'string' },
2343 + // As the API serves it: a local path that is not file_uploadable.
2344 + file: {
2345 + type: 'string',
2346 + title: 'File',
2347 + description: 'Path to the local file to attach if not linking a `url`.',
2348 + },
2349 + },
2350 + },
2351 + output_parameters: { type: 'object', properties: {} },
2352 + },
2353 + ],
2354 + } satisfies TestLiveInput['toolkitsData'],
2355 + })
2356 + )(
2357 + '[Given] a local file for an input that is not file_uploadable [Then] execute fails instead of sending the path (issue #4965)',
2358 + it => {
2359 + it.effect('refuses before the tool runs', () =>
2360 + Effect.gen(function* () {
2361 + const tempFile = path.join(os.tmpdir(), `composio-trello-${crypto.randomUUID()}.jpg`);
2362 + fs.writeFileSync(tempFile, 'jpeg bytes', 'utf8');
2363 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
2364 +
2365 + const failure = yield* cli([
2366 + 'execute',
2367 + 'TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD',
2368 + '--skip-connection-check',
2369 + '-d',
2370 + JSON.stringify({ idCard: 'card', file: tempFile }),
2371 + ]).pipe(
2372 + Effect.flip,
2373 + Effect.map(error => (error as Error).message),
2374 + Effect.ensuring(Effect.sync(() => fs.rmSync(tempFile, { force: true })))
2375 + );
2376 +
2377 + expect(failure).toContain('cannot upload local files');
2378 + expect(failure).toContain(`"file" (${tempFile})`);
2379 + expect(fetchSpy).not.toHaveBeenCalled();
2380 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
2381 + expect(lines.join('\n')).not.toContain('"successful": true');
2382 + })
2383 + );
2384 +
2385 + it.effect('reports the same problem under --dry-run', () =>
2386 + Effect.gen(function* () {
2387 + const tempFile = path.join(os.tmpdir(), `composio-trello-${crypto.randomUUID()}.jpg`);
2388 + fs.writeFileSync(tempFile, 'jpeg bytes', 'utf8');
2389 +
2390 + const failure = yield* cli([
2391 + 'execute',
2392 + 'TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD',
2393 + '--skip-connection-check',
2394 + '--dry-run',
2395 + '-d',
2396 + JSON.stringify({ idCard: 'card', file: tempFile }),
2397 + ]).pipe(
2398 + Effect.flip,
2399 + Effect.map(error => (error as Error).message),
2400 + Effect.ensuring(Effect.sync(() => fs.rmSync(tempFile, { force: true })))
2401 + );
2402 +
2403 + expect(failure).toContain('cannot upload local files');
2404 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
2405 + expect(lines.join('\n')).not.toContain('Dry run successful');
2406 + })
2407 + );
2408 +
2409 + // The real call refuses the file whatever the skip flags say, so the
2410 + // dry run must too.
2411 + it.effect('reports the same problem under --dry-run --skip-checks', () =>
2412 + Effect.gen(function* () {
2413 + const tempFile = path.join(os.tmpdir(), `composio-trello-${crypto.randomUUID()}.jpg`);
2414 + fs.writeFileSync(tempFile, 'jpeg bytes', 'utf8');
2415 +
2416 + const failure = yield* cli([
2417 + 'execute',
2418 + 'TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD',
2419 + '--skip-checks',
2420 + '--dry-run',
2421 + '-d',
2422 + JSON.stringify({ idCard: 'card', file: tempFile }),
2423 + ]).pipe(
2424 + Effect.flip,
2425 + Effect.map(error => (error as Error).message),
2426 + Effect.ensuring(Effect.sync(() => fs.rmSync(tempFile, { force: true })))
2427 + );
2428 +
2429 + expect(failure).toContain('cannot upload local files');
2430 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
2431 + expect(lines.join('\n')).not.toContain('Dry run successful');
2432 + })
2433 + );
2434 +
2435 + it.effect('reports the same problem under --parallel --dry-run', () =>
2436 + Effect.gen(function* () {
2437 + const tempFile = path.join(os.tmpdir(), `composio-trello-${crypto.randomUUID()}.jpg`);
2438 + fs.writeFileSync(tempFile, 'jpeg bytes', 'utf8');
2439 +
2440 + yield* cli([
2441 + 'execute',
2442 + '--parallel',
2443 + '--skip-connection-check',
2444 + '--dry-run',
2445 + 'TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD',
2446 + '-d',
2447 + JSON.stringify({ idCard: 'card', file: tempFile }),
2448 + ]).pipe(
2449 + Effect.flip,
2450 + Effect.ensuring(Effect.sync(() => fs.rmSync(tempFile, { force: true })))
2451 + );
2452 +
2453 + const output = parseLastJson(yield* MockConsole.getLines({ stripAnsi: true }));
2454 + expect(output).toMatchObject({
2455 + successful: false,
2456 + results: [
2457 + {
2458 + slug: 'TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD',
2459 + successful: false,
2460 + error: expect.stringContaining('cannot upload local files'),
2461 + },
2462 + ],
2463 + });
2464 + })
2465 + );
2466 + }
2467 + );
2468 +
2469 layer(
2470 TestLive({
2471 baseConfigProvider: testConfigProvider,
ts/packages/cli/test/src/commands/tools/tools.execute.transport.test.ts
+1 -1
@@ -503,7 +503,7 @@ describe('CLI: composio execute transport', () => {
503 recipient_email: 'a@b.com',
504 attachment: {
505 name: path.basename(tempFile),
506 - mimetype: 'application/octet-stream',
506 + mimetype: 'text/plain',
507 s3key: `uploads/${path.basename(tempFile)}`,
508 },
509 });
ts/packages/cli/test/src/services/connected-account-selection.test.ts
+122
@@ -254,4 +254,126 @@ describe('resolveConnectedAccountForToolkit', () => {
254 );
255 })
256 );
257 +
258 + // #4745: with several usable accounts and none aliased `default`, picking the
259 + // newest silently could act on the wrong mailbox; the caller must choose.
260 + it.effect(
261 + 'fails instead of silently picking one, when several accounts are connected and none is alias=default',
262 + () =>
263 + Effect.gen(function* () {
264 + const { client } = stubComposioClient(() =>
265 + page([
266 + makeAccount({ id: 'con_work', alias: 'work', toolkit: { slug: 'gmail' } }),
267 + makeAccount({
268 + id: 'con_personal',
269 + alias: 'personal',
270 + toolkit: { slug: 'gmail' },
271 + updated_at: '2026-01-02T00:00:00.000Z',
272 + }),
273 + ])
274 + );
275 +
276 + const error = yield* resolveConnectedAccountForToolkit({
277 + client,
278 + toolkitSlug: 'gmail',
279 + userId: 'default',
280 + selector: Option.none(),
281 + }).pipe(Effect.flip, Effect.provide(TerminalUITest));
282 +
283 + expect(error).toBeInstanceOf(ConnectedAccountResolutionError);
284 + expect(error.message).toContain('Multiple connected accounts exist');
285 + expect(error.message).toContain('work');
286 + expect(error.message).toContain('personal');
287 + expect(error.message).toContain('Pass --account <alias or id> to choose one.');
288 + })
289 + );
290 +
291 + it.effect(
292 + 'still picks the alias=default account automatically when one exists, even with several accounts connected',
293 + () =>
294 + Effect.gen(function* () {
295 + const { client } = stubComposioClient(() =>
296 + page([
297 + makeAccount({ id: 'con_work', alias: 'work', toolkit: { slug: 'gmail' } }),
298 + makeAccount({ id: 'con_main', alias: 'default', toolkit: { slug: 'gmail' } }),
299 + ])
300 + );
301 +
302 + const selected = yield* resolveConnectedAccountForToolkit({
303 + client,
304 + toolkitSlug: 'gmail',
305 + userId: 'default',
306 + selector: Option.none(),
307 + }).pipe(Effect.provide(TerminalUITest));
308 +
309 + expect(selected).toBe('con_main');
310 + })
311 + );
312 +
313 + it.effect('still picks the only account automatically when exactly one is connected', () =>
314 + Effect.gen(function* () {
315 + const { client } = stubComposioClient(() =>
316 + page([makeAccount({ id: 'con_only', toolkit: { slug: 'gmail' } })])
317 + );
318 +
319 + const selected = yield* resolveConnectedAccountForToolkit({
320 + client,
321 + toolkitSlug: 'gmail',
322 + userId: 'default',
323 + selector: Option.none(),
324 + }).pipe(Effect.provide(TerminalUITest));
325 +
326 + expect(selected).toBe('con_only');
327 + })
328 + );
329 +
330 + it.effect(
331 + 'an explicit --account selector still matches as before, even with several accounts',
332 + () =>
333 + Effect.gen(function* () {
334 + const { client } = stubComposioClient(() =>
335 + page([
336 + makeAccount({ id: 'con_work', alias: 'work', toolkit: { slug: 'gmail' } }),
337 + makeAccount({ id: 'con_personal', alias: 'personal', toolkit: { slug: 'gmail' } }),
338 + ])
339 + );
340 +
341 + const selected = yield* resolveConnectedAccountForToolkit({
342 + client,
343 + toolkitSlug: 'gmail',
344 + userId: 'default',
345 + selector: Option.some('personal'),
346 + }).pipe(Effect.provide(TerminalUITest));
347 +
348 + expect(selected).toBe('con_personal');
349 + })
350 + );
351 +
352 + it.effect(
353 + 'an empty or whitespace-only --account value is treated as no selector, not a bypass',
354 + () =>
355 + Effect.gen(function* () {
356 + const { client } = stubComposioClient(() =>
357 + page([
358 + makeAccount({ id: 'con_work', alias: 'work', toolkit: { slug: 'gmail' } }),
359 + makeAccount({
360 + id: 'con_personal',
361 + alias: 'personal',
362 + toolkit: { slug: 'gmail' },
363 + updated_at: '2026-01-02T00:00:00.000Z',
364 + }),
365 + ])
366 + );
367 +
368 + const error = yield* resolveConnectedAccountForToolkit({
369 + client,
370 + toolkitSlug: 'gmail',
371 + userId: 'default',
372 + selector: Option.some(' '),
373 + }).pipe(Effect.flip, Effect.provide(TerminalUITest));
374 +
375 + expect(error).toBeInstanceOf(ConnectedAccountResolutionError);
376 + expect(error.message).toContain('Multiple connected accounts exist');
377 + })
378 + );
379 });
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+549 -1
@@ -15,6 +15,8 @@ import {
15 MAX_URL_UPLOAD_SIZE_BYTES,
16 } from '@composio/core';
17 import {
18 + findFileUploadablePaths,
19 + findLocalPathArguments,
20 schemaHasFileUploadable,
21 ToolFileUploadError,
22 uploadToolInputFiles,
@@ -30,6 +32,139 @@ const inputSchema = {
32 },
33 };
34
35 +describe('file argument paths', () => {
36 + const schema = {
37 + type: 'object',
38 + properties: {
39 + operations: {
40 + type: 'array',
41 + items: {
42 + oneOf: [
43 + {
44 + properties: { type: { const: 'add_image' }, image: { file_uploadable: true } },
45 + required: ['type'],
46 + },
47 + {
48 + properties: { type: { const: 'replace_image' }, image: { file_uploadable: true } },
49 + required: ['type'],
50 + },
51 + {
52 + properties: { type: { const: 'set_text' }, text: { type: 'string' } },
53 + required: ['type'],
54 + },
55 + ],
56 + },
57 + },
58 + },
59 + };
60 +
61 + it('binds the selected union branch to the existing array index', () => {
62 + expect(
63 + findFileUploadablePaths(schema, [], {
64 + operations: [{ type: 'set_text', text: 'keep' }, { type: 'add_image' }],
65 + })
66 + ).toEqual([['operations', 1, 'image']]);
67 + });
68 +
69 + it('does not invent array entries or choose between multiple image operations', () => {
70 + expect(findFileUploadablePaths(schema, [], { operations: [] })).toEqual([]);
71 + expect(findFileUploadablePaths(schema, [], { operations: [{ type: 'set_text' }] })).toEqual([]);
72 + expect(
73 + findFileUploadablePaths(schema, [], {
74 + operations: [{ type: 'add_image' }, { type: 'replace_image' }],
75 + })
76 + ).toEqual([
77 + ['operations', 0, 'image'],
78 + ['operations', 1, 'image'],
79 + ]);
80 + });
81 +
82 + it('preserves tuple indices, including preceding boolean schemas', () => {
83 + expect(
84 + findFileUploadablePaths(
85 + { type: 'array', items: [true, { file_uploadable: true }] },
86 + [],
87 + ['keep', undefined]
88 + )
89 + ).toEqual([[1]]);
90 + });
91 +
92 + const optionalModeSchema = (required: ReadonlyArray<string>) => ({
93 + type: 'object',
94 + allOf: [
95 + {
96 + properties: { mode: { const: 'upload' }, file: { file_uploadable: true } },
97 + required,
98 + },
99 + ],
100 + });
101 +
102 + it('keeps a branch whose optional const property the caller omitted', () => {
103 + expect(findFileUploadablePaths(optionalModeSchema(['file']), [], {})).toEqual([['file']]);
104 + });
105 +
106 + it('drops a branch whose const property is required and omitted, or set to another value', () => {
107 + expect(findFileUploadablePaths(optionalModeSchema(['mode', 'file']), [], {})).toEqual([]);
108 + expect(findFileUploadablePaths(optionalModeSchema(['file']), [], { mode: 'link' })).toEqual([]);
109 + });
110 +});
111 +
112 +describe('local file MIME metadata', () => {
113 + afterEach(() => {
114 + vi.unstubAllGlobals();
115 + vi.restoreAllMocks();
116 + });
117 +
118 + it.effect.each([
119 + { filename: 'picture.png', expectedMime: 'image/png' },
120 + { filename: 'picture.JPG', expectedMime: 'image/jpeg' },
121 + { filename: 'document.pdf', expectedMime: 'application/pdf' },
122 + {
123 + filename: 'slides.pptx',
124 + expectedMime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
125 + },
126 + {
127 + filename: 'document.docx',
128 + expectedMime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
129 + },
130 + { filename: 'unknown.extension-dogfood', expectedMime: 'application/octet-stream' },
131 + { filename: 'no-extension', expectedMime: 'application/octet-stream' },
132 + ])(
133 + 'uses the same MIME for the request, upload, and hydrated $filename',
134 + ({ filename, expectedMime }) => {
135 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-mime-'));
136 + const file = path.join(root, filename);
137 + writeFileSync(file, 'fixture bytes');
138 + const { client, requests } = makeClient();
139 + const uploadFetch = vi.fn(async () => new Response(null, { status: 200 }));
140 + vi.stubGlobal('fetch', uploadFetch);
141 + return Effect.gen(function* () {
142 + const fsApi = yield* FileSystem.FileSystem;
143 + const pathApi = yield* Path.Path;
144 + const result = yield* uploadToolInputFiles({
145 + fs: fsApi,
146 + path: pathApi,
147 + toolSlug: 'GMAIL_SEND_EMAIL',
148 + arguments_: { attachment: file },
149 + inputSchema,
150 + client,
151 + });
152 + expect(requests[0]?.body).toMatchObject({ mimetype: expectedMime });
153 + expect(uploadFetch).toHaveBeenCalledWith(
154 + 'https://1.1.1.1/put',
155 + expect.objectContaining({
156 + headers: expect.objectContaining({ 'Content-Type': expectedMime }),
157 + })
158 + );
159 + expect(result.attachment).toMatchObject({ name: filename, mimetype: expectedMime });
160 + }).pipe(
161 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
162 + Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
163 + );
164 + }
165 + );
166 +});
167 +
168 // The client over a transport that answers the presigned-URL request with
169 // `presigned`, and records each request it receives.
170 const makeClient = (
@@ -154,7 +289,7 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
289 path: '/api/v3.1/files/upload/request',
290 body: {
291 filename: 'document.pdf',
157 - mimetype: 'application/octet-stream',
292 + mimetype: 'application/pdf',
293 md5: '5d41402abc4b2a76b9719d911017c592',
294 tool_slug: 'GMAIL_SEND_EMAIL',
295 toolkit_slug: 'gmail',
@@ -373,3 +508,416 @@ describe('uploadToolInputFiles — URL download size cap', () => {
508 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)));
509 });
510 });
511 +
512 +// TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD as the API serves it (issue #4965):
513 +// `file` is described as a local file but is not `file_uploadable`.
514 +const trelloAttachmentSchema = {
515 + type: 'object',
516 + required: ['idCard'],
517 + properties: {
518 + idCard: { type: 'string', description: 'ID or shortLink of the Trello card.' },
519 + url: {
520 + type: 'string',
521 + description:
522 + "URL of an external resource to attach if not uploading a `file`. Must start with 'http://' or 'https://'.",
523 + },
524 + file: {
525 + type: 'string',
526 + title: 'File',
527 + description: 'Path to the local file to attach if not linking a `url`.',
528 + },
529 + },
530 +};
531 +
532 +describe('uploadToolInputFiles — local file for an input that is not file_uploadable (issue #4965)', () => {
533 + const withTempFile = <A, E, R>(
534 + use: (paths: { readonly root: string; readonly file: string }) => Effect.Effect<A, E, R>
535 + ) => {
536 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
537 + const file = path.join(root, 'photo.jpg');
538 + writeFileSync(file, 'jpeg bytes');
539 + return use({ root, file }).pipe(
540 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
541 + Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
542 + );
543 + };
544 +
545 + const run = (arguments_: Record<string, unknown>, schema: Record<string, unknown>) =>
546 + Effect.gen(function* () {
547 + const { client, requests } = makeClient();
548 + const result = yield* uploadToolInputFiles({
549 + fs: yield* FileSystem.FileSystem,
550 + path: yield* Path.Path,
551 + toolSlug: 'TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD',
552 + arguments_,
553 + inputSchema: schema,
554 + client,
555 + }).pipe(Effect.result);
556 + return { result, requests };
557 + });
558 +
559 + it.effect('fails before anything is sent when the argument names a local file', () =>
560 + withTempFile(({ file }) =>
561 + Effect.gen(function* () {
562 + const { result, requests } = yield* run({ idCard: 'card', file }, trelloAttachmentSchema);
563 +
564 + const failure = yield* Effect.flip(Effect.fromResult(result));
565 + expect(failure).toBeInstanceOf(ToolFileUploadError);
566 + expect(failure).toMatchObject({ reason: 'not-uploadable' });
567 + expect(failure.message).toContain(`"file" (${file})`);
568 + expect(failure.message).toContain('Nothing was executed');
569 + expect(requests).toEqual([]);
570 + })
571 + )
572 + );
573 +
574 + it.effect('names every offending argument, including ones nested in arrays', () =>
575 + withTempFile(({ file }) =>
576 + Effect.gen(function* () {
577 + const { result } = yield* run(
578 + { files: [{ file_path: file }, { content: 'inline' }] },
579 + {
580 + type: 'object',
581 + properties: {
582 + files: {
583 + type: 'array',
584 + items: {
585 + type: 'object',
586 + properties: {
587 + file_path: {
588 + type: 'string',
589 + description: 'Local filesystem path to the file.',
590 + },
591 + content: { type: 'string' },
592 + },
593 + },
594 + },
595 + },
596 + }
597 + );
598 +
599 + const failure = yield* Effect.flip(Effect.fromResult(result));
600 + expect(failure.message).toContain(`"files.0.file_path" (${file})`);
601 + })
602 + )
603 + );
604 +
605 + it.effect('passes a path that does not exist here through, as it may be remote', () =>
606 + withTempFile(({ root }) =>
607 + Effect.gen(function* () {
608 + const remote = path.join(root, 'missing', 'report.pdf');
609 + const { result, requests } = yield* run(
610 + { idCard: 'card', file: remote },
611 + trelloAttachmentSchema
612 + );
613 +
614 + expect(yield* Effect.fromResult(result)).toEqual({ idCard: 'card', file: remote });
615 + expect(requests).toEqual([]);
616 + })
617 + )
618 + );
619 +
620 + it.effect.each([
621 + { name: 'a directory', value: (root: string) => root },
622 + { name: 'a URL', value: () => 'https://example.com/photo.jpg' },
623 + { name: 'a bare word', value: () => 'photo' },
624 + ])('passes $name through', ({ value }) =>
625 + withTempFile(({ root }) =>
626 + Effect.gen(function* () {
627 + const file = value(root);
628 + const { result } = yield* run({ idCard: 'card', file }, trelloAttachmentSchema);
629 + expect(yield* Effect.fromResult(result)).toEqual({ idCard: 'card', file });
630 + })
631 + )
632 + );
633 +
634 + it.effect('leaves an existing file alone when the input is a repository path', () =>
635 + withTempFile(({ file }) =>
636 + Effect.gen(function* () {
637 + const { result } = yield* run(
638 + { path: file },
639 + {
640 + type: 'object',
641 + properties: {
642 + path: {
643 + type: 'string',
644 + description: 'The full path to the file in the repository, including the filename.',
645 + },
646 + },
647 + }
648 + );
649 +
650 + expect(yield* Effect.fromResult(result)).toEqual({ path: file });
651 + })
652 + )
653 + );
654 +
655 + it('reads the description of an optional input from its non-null variant', () => {
656 + expect(
657 + findLocalPathArguments(
658 + { file: '/tmp/photo.jpg' },
659 + {
660 + type: 'object',
661 + properties: {
662 + file: {
663 + anyOf: [
664 + { type: 'string', description: 'Local file path of the video to upload.' },
665 + { type: 'null' },
666 + ],
667 + },
668 + },
669 + }
670 + )
671 + ).toEqual([{ argumentPath: ['file'], value: '/tmp/photo.jpg' }]);
672 + });
673 +
674 + it('skips an input that also accepts an upload', () => {
675 + expect(
676 + findLocalPathArguments(
677 + { file: '/tmp/photo.jpg' },
678 + {
679 + type: 'object',
680 + properties: {
681 + file: {
682 + description: 'Path to the local file to upload.',
683 + anyOf: [{ file_uploadable: true }, { type: 'string' }],
684 + },
685 + },
686 + }
687 + )
688 + ).toEqual([]);
689 + });
690 +
691 + const localPathDescription = { type: 'string', description: 'Path to the local file to attach.' };
692 +
693 + it.each([
694 + {
695 + name: 'allOf splits the description and the upload marker across branches',
696 + schema: {
697 + type: 'object',
698 + allOf: [
699 + { properties: { file: localPathDescription } },
700 + { properties: { file: { file_uploadable: true } } },
701 + ],
702 + },
703 + },
704 + {
705 + name: 'anyOf offers an uploadable branch beside the path branch',
706 + schema: {
707 + type: 'object',
708 + properties: { file: { anyOf: [localPathDescription, { file_uploadable: true }] } },
709 + },
710 + },
711 + {
712 + name: 'oneOf nests the uploadable branch one level down',
713 + schema: {
714 + type: 'object',
715 + properties: {
716 + file: { oneOf: [localPathDescription, { allOf: [{ file_uploadable: true }] }] },
717 + },
718 + },
719 + },
720 + ])('never flags an input the upload code uploads: $name', ({ schema }) => {
721 + expect(findLocalPathArguments({ file: '/tmp/photo.jpg' }, schema)).toEqual([]);
722 + });
723 +
724 + it.effect('uploads, not refuses, a local file for an allOf-split uploadable input', () =>
725 + withTempFile(({ file }) =>
726 + Effect.gen(function* () {
727 + vi.stubGlobal(
728 + 'fetch',
729 + vi.fn(async () => ({ ok: true, statusText: 'OK' }))
730 + );
731 + const { result, requests } = yield* run(
732 + { file },
733 + {
734 + type: 'object',
735 + allOf: [
736 + { properties: { file: localPathDescription } },
737 + { properties: { file: { file_uploadable: true } } },
738 + ],
739 + }
740 + );
741 +
742 + expect(yield* Effect.fromResult(result)).toMatchObject({
743 + file: { name: 'photo.jpg', s3key: 's3key-123' },
744 + });
745 + expect(requests).toHaveLength(1);
746 + }).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllGlobals())))
747 + )
748 + );
749 +
750 + it.effect('uploads an input once when several branches mark it uploadable', () =>
751 + withTempFile(({ file }) =>
752 + Effect.gen(function* () {
753 + vi.stubGlobal(
754 + 'fetch',
755 + vi.fn(async () => ({ ok: true, statusText: 'OK' }))
756 + );
757 + const { result, requests } = yield* run(
758 + { file, note: 'keep' },
759 + {
760 + type: 'object',
761 + anyOf: [
762 + { properties: { file: { file_uploadable: true } } },
763 + { properties: { file: { file_uploadable: true }, note: { type: 'string' } } },
764 + ],
765 + }
766 + );
767 +
768 + expect(yield* Effect.fromResult(result)).toEqual({
769 + file: { name: 'photo.jpg', mimetype: 'image/jpeg', s3key: 's3key-123' },
770 + note: 'keep',
771 + });
772 + expect(requests).toHaveLength(1);
773 + }).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllGlobals())))
774 + )
775 + );
776 +
777 + it('flags only the tuple elements the upload code does not upload', () => {
778 + // `hydrateFileUploads` reads each tuple element against its own `items` schema.
779 + expect(
780 + findLocalPathArguments(
781 + { files: ['/tmp/photo.jpg', '/tmp/other.jpg'] },
782 + {
783 + type: 'object',
784 + properties: {
785 + files: {
786 + type: 'array',
787 + items: [localPathDescription, { ...localPathDescription, file_uploadable: true }],
788 + },
789 + },
790 + }
791 + )
792 + ).toEqual([{ argumentPath: ['files', 0], value: '/tmp/photo.jpg' }]);
793 + });
794 +
795 + it('reads descriptions in nested composition branches', () => {
796 + expect(
797 + findLocalPathArguments(
798 + { file: '/tmp/photo.jpg' },
799 + {
800 + type: 'object',
801 + properties: {
802 + file: { anyOf: [{ type: 'null' }, { allOf: [localPathDescription] }] },
803 + },
804 + }
805 + )
806 + ).toEqual([{ argumentPath: ['file'], value: '/tmp/photo.jpg' }]);
807 + });
808 +});
809 +
810 +describe('multiple PowerPoint images', () => {
811 + afterEach(() => {
812 + vi.unstubAllGlobals();
813 + vi.restoreAllMocks();
814 + });
815 +
816 + it.effect('keeps each nested image reference paired with its uploaded bytes', () => {
817 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-multiple-images-'));
818 + const first = path.join(root, 'first.png');
819 + const second = path.join(root, 'second.png');
820 + writeFileSync(first, 'first image bytes');
821 + writeFileSync(second, 'second image bytes');
822 + const { client, requests } = stubComposioClient(request => {
823 + const { filename } = request.body as { filename: string };
824 + return Response.json({
825 + new_presigned_url: `https://1.1.1.1/${filename}`,
826 + key: `uploads/${filename}`,
827 + });
828 + });
829 + const uploaded = new Map<string, string>();
830 + vi.stubGlobal('fetch', async (url: string, init: RequestInit) => {
831 + uploaded.set(url, Buffer.from(init.body as Uint8Array).toString());
832 + return new Response(null, { status: 200 });
833 + });
834 + const schema = {
835 + type: 'object',
836 + properties: {
837 + slides: {
838 + type: 'array',
839 + items: {
840 + type: 'object',
841 + properties: {
842 + blocks: {
843 + type: 'array',
844 + items: {
845 + oneOf: [
846 + { properties: { type: { const: 'text' }, text: { type: 'string' } } },
847 + { properties: { type: { const: 'image' }, image: { file_uploadable: true } } },
848 + ],
849 + },
850 + },
851 + },
852 + },
853 + },
854 + },
855 + };
856 + const arguments_ = {
857 + filename: 'two-images.pptx',
858 + slides: [
859 + {
860 + blocks: [
861 + { type: 'text', text: 'Keep this' },
862 + { type: 'image', image: first },
863 + ],
864 + },
865 + { blocks: [{ type: 'image', image: second }] },
866 + ],
867 + };
868 + return Effect.gen(function* () {
869 + const fsApi = yield* FileSystem.FileSystem;
870 + const pathApi = yield* Path.Path;
871 + const result = yield* uploadToolInputFiles({
872 + fs: fsApi,
873 + path: pathApi,
874 + toolSlug: 'MICROSOFT_POWERPOINT_CREATE_PRESENTATION',
875 + arguments_,
876 + inputSchema: schema,
877 + client,
878 + });
879 + expect(requests).toHaveLength(2);
880 + expect(uploaded).toEqual(
881 + new Map([
882 + ['https://1.1.1.1/first.png', 'first image bytes'],
883 + ['https://1.1.1.1/second.png', 'second image bytes'],
884 + ])
885 + );
886 + expect(result).toEqual({
887 + filename: 'two-images.pptx',
888 + slides: [
889 + {
890 + blocks: [
891 + { type: 'text', text: 'Keep this' },
892 + {
893 + type: 'image',
894 + image: {
895 + name: 'first.png',
896 + mimetype: 'image/png',
897 + s3key: 'uploads/first.png',
898 + },
899 + },
900 + ],
901 + },
902 + {
903 + blocks: [
904 + {
905 + type: 'image',
906 + image: {
907 + name: 'second.png',
908 + mimetype: 'image/png',
909 + s3key: 'uploads/second.png',
910 + },
911 + },
912 + ],
913 + },
914 + ],
915 + });
916 + expect(arguments_.slides[0]?.blocks[1]?.image).toBe(first);
917 + expect(arguments_.slides[1]?.blocks[0]?.image).toBe(second);
918 + }).pipe(
919 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
920 + Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
921 + );
922 + });
923 +});