Skip to content

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

refactor(cli): seal the CommandDescriptor seam and drop zod for Schema (#3882)

Alberto Schiabel6d5465acd37f
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 3a10baf7c..06e0ac6d5 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -104,6 +104,18 @@ const cliDescriptorSeamRestrictedImportPatterns = [
},
];
+const cliDescriptorSeamRestrictedSyntax = [
+ {
+ selector: 'ImportExpression[source.value=/^@effect\\/cli(?:\\/(?:CommandDescriptor|Usage))?$/]',
+ message: cliDescriptorSeamMessage,
+ },
+ {
+ selector:
+ "CallExpression[callee.name='require'][arguments.0.value=/^@effect\\/cli(?:\\/(?:CommandDescriptor|Usage))?$/]",
+ message: cliDescriptorSeamMessage,
+ },
+];
+
const effectSchemaRestrictedImportPaths = [
{
name: 'zod',
@@ -118,6 +130,17 @@ const effectSchemaRestrictedImportPatterns = [
},
];
+const effectSchemaRestrictedSyntax = [
+ {
+ selector: 'ImportExpression[source.value=/^zod(?:\\/|$)/]',
+ message: 'Use Schema from effect for tool input validation.',
+ },
+ {
+ selector: "CallExpression[callee.name='require'][arguments.0.value=/^zod(?:\\/|$)/]",
+ message: 'Use Schema from effect for tool input validation.',
+ },
+];
+
/** @type {import('eslint').Linter.Config[]} */
export default [
{
@@ -189,16 +212,8 @@ export default [
'no-restricted-imports': [
'error',
{
- paths: [
- ...cliRestrictedImportPaths,
- // uncommented by the seam-rules PR of this stack
- // ...cliDescriptorSeamRestrictedImportPaths,
- ],
- patterns: [
- ...cliRestrictedImportPatterns,
- // uncommented by the seam-rules PR of this stack
- // ...cliDescriptorSeamRestrictedImportPatterns,
- ],
+ paths: [...cliRestrictedImportPaths, ...cliDescriptorSeamRestrictedImportPaths],
+ patterns: [...cliRestrictedImportPatterns, ...cliDescriptorSeamRestrictedImportPatterns],
},
],
'no-restricted-syntax': [
@@ -206,6 +221,7 @@ export default [
// uncommented by the boundary-ratchet PR of this stack
// ...cliRestrictedSyntax,
...cliProcessStreamRestrictions,
+ ...cliDescriptorSeamRestrictedSyntax,
],
},
},
@@ -237,34 +253,39 @@ export default [
// ],
// },
// },
- // uncommented by the seam-rules PR of this stack.
- // {
- // // The one file allowed to touch @effect/cli's CommandDescriptor/Usage
- // // modules (the Effect CLI v4 redesign seam).
- // files: ['ts/packages/cli/src/commands/command-introspection.ts'],
- // rules: {
- // 'no-restricted-imports': [
- // 'error',
- // {
- // paths: cliRestrictedImportPaths,
- // patterns: cliRestrictedImportPatterns,
- // },
- // ],
- // },
- // },
- // uncommented by the seam-rules PR of this stack.
- // {
- // files: ['ts/packages/cli/src/services/tool-input-validation.ts'],
- // rules: {
- // 'no-restricted-imports': [
- // 'error',
- // {
- // paths: [...cliRestrictedImportPaths, ...effectSchemaRestrictedImportPaths],
- // patterns: [...cliRestrictedImportPatterns, ...effectSchemaRestrictedImportPatterns],
- // },
- // ],
- // },
- // },
+ {
+ // The one file allowed to touch @effect/cli's CommandDescriptor/Usage
+ // modules (the Effect CLI v4 redesign seam).
+ files: ['ts/packages/cli/src/commands/command-introspection.ts'],
+ rules: {
+ 'no-restricted-imports': [
+ 'error',
+ {
+ paths: cliRestrictedImportPaths,
+ patterns: cliRestrictedImportPatterns,
+ },
+ ],
+ 'no-restricted-syntax': ['error', ...cliProcessStreamRestrictions],
+ },
+ },
+ {
+ files: ['ts/packages/cli/src/services/tool-input-validation.ts'],
+ rules: {
+ 'no-restricted-imports': [
+ 'error',
+ {
+ paths: [...cliRestrictedImportPaths, ...effectSchemaRestrictedImportPaths],
+ patterns: [...cliRestrictedImportPatterns, ...effectSchemaRestrictedImportPatterns],
+ },
+ ],
+ 'no-restricted-syntax': [
+ 'error',
+ ...cliProcessStreamRestrictions,
+ ...cliDescriptorSeamRestrictedSyntax,
+ ...effectSchemaRestrictedSyntax,
+ ],
+ },
+ },
{
files: ['ts/packages/cli/src/services/terminal-ui.ts'],
rules: {
diff --git a/package.json b/package.json
index 5eaad5b1c..8b6315129 100644
--- a/package.json
+++ b/package.json
@@ -9,6 +9,7 @@
"ts/packages/core",
"ts/packages/experimental",
"ts/packages/slim",
+ "ts/packages/json-schema-to-effect-schema",
"ts/packages/json-schema-to-zod",
"ts/packages/cli",
"ts/packages/cli-keyring",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e3d24218e..e6c19bd0c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1141,6 +1141,9 @@ importers:
'@composio/core':
specifier: workspace:*
version: link:../core
+ '@composio/json-schema-to-effect-schema':
+ specifier: workspace:*
+ version: link:../json-schema-to-effect-schema
'@composio/json-schema-to-zod':
specifier: workspace:*
version: link:../json-schema-to-zod
@@ -1404,6 +1407,31 @@ importers:
specifier: 'catalog:'
+ ts/packages/json-schema-to-effect-schema:
+ dependencies:
+ '@cfworker/json-schema':
+ specifier: ^4.1.1
+ version: 4.1.1
+ effect:
+ specifier: 'catalog:'
+ version: 3.21.4
+ devDependencies:
+ '@composio/json-schema-to-zod':
+ specifier: workspace:*
+ version: link:../json-schema-to-zod
+ tsdown:
+ specifier: 'catalog:'
+ typescript:
+ specifier: 'catalog:'
+ version: 6.0.3
+ vitest:
+ specifier: 'catalog:'
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
+
ts/packages/json-schema-to-zod:
devDependencies:
'@types/json-schema':
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 6f4d674e2..3247eeaed 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -11,6 +11,7 @@ packages:
- ts/packages/cli-local-tools
- ts/packages/core
- ts/packages/experimental
+ - ts/packages/json-schema-to-effect-schema
- ts/packages/json-schema-to-zod
- ts/packages/slim
- ts/packages/providers/*
diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.json
index 016c7c10e..74e785336 100644
--- a/ts/packages/cli/package.json
+++ b/ts/packages/cli/package.json
@@ -86,6 +86,7 @@
"@composio/cli-local-tools": "workspace:*",
"@composio/client": "catalog:",
"@composio/core": "workspace:*",
+ "@composio/json-schema-to-effect-schema": "workspace:*",
"@composio/json-schema-to-zod": "workspace:*",
"@composio/ts-builders": "workspace:*",
"@effect/cli": "catalog:",
diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.ts
index 550f44ed8..f80a1c9a5 100644
--- a/ts/packages/cli/src/cli-main.ts
+++ b/ts/packages/cli/src/cli-main.ts
@@ -1,11 +1,12 @@
import process from 'node:process';
-import { Cause, Effect, Exit, HashMap, Layer, Logger, Option } from 'effect';
+import { Cause, Effect, Exit, Layer, Logger } from 'effect';
import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
-import { CliConfig, CommandDescriptor, HelpDoc, Usage, ValidationError } from '@effect/cli';
+import { CliConfig, HelpDoc, ValidationError } from '@effect/cli';
import { FetchHttpClient } from '@effect/platform';
import { BunContext, BunRuntime, BunFileSystem, BunPath } from '@effect/platform-bun';
import type { Teardown } from '@effect/platform/Runtime';
import { buildRootCommand, runWithConfig } from 'src/commands';
+import { collectValueOptionNames } from 'src/commands/command-introspection';
import { matchCommandFromArgv, getCommandHelpText } from 'src/commands/root-help';
import * as constants from 'src/constants';
import { ComposioCliConfig } from 'src/cli-config';
@@ -140,53 +141,6 @@ const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) sati
unknown
>;
-const collectValueOptionNamesFromUsage = (usage: Usage.Usage, acc: Set<string>) => {
- switch (usage._tag) {
- case 'Named': {
- if (Option.isSome(usage.acceptedValues)) {
- for (const name of usage.names) {
- if (name.startsWith('-')) {
- acc.add(name);
- }
- }
- }
- return;
- }
- case 'Optional':
- case 'Repeated': {
- collectValueOptionNamesFromUsage(usage.usage, acc);
- return;
- }
- case 'Alternation':
- case 'Concat': {
- collectValueOptionNamesFromUsage(usage.left, acc);
- collectValueOptionNamesFromUsage(usage.right, acc);
- return;
- }
- case 'Mixed':
- case 'Empty': {
- return;
- }
- }
-};
-
-const collectValueOptionNames = (rootCommand: ReturnType<typeof buildRootCommand>) => {
- const names = new Set<string>();
- const visited = new Set<CommandDescriptor.Command<unknown>>();
- const visit = (command: CommandDescriptor.Command<unknown>) => {
- if (visited.has(command)) {
- return;
- }
- visited.add(command);
- collectValueOptionNamesFromUsage(CommandDescriptor.getUsage(command), names);
- for (const [, subcommand] of HashMap.toEntries(CommandDescriptor.getSubcommands(command))) {
- visit(subcommand);
- }
- };
- visit(rootCommand.descriptor);
- return names;
-};
-
const runWithTelemetry = Effect.gen(function* () {
const ui = yield* TerminalUI;
const terminal = yield* ui.capabilities;
@@ -314,6 +268,5 @@ showUpdateNotice.pipe(
),
Effect.provide(layers),
Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
- effect =>
- (BunRuntime.runMain({ teardown }) as (e: Effect.Effect<void, unknown, unknown>) => void)(effect)
+ BunRuntime.runMain({ teardown })
);
diff --git a/ts/packages/cli/src/commands/$default.cmd.ts b/ts/packages/cli/src/commands/$default.cmd.ts
index 71748e9f7..042a36669 100644
--- a/ts/packages/cli/src/commands/$default.cmd.ts
+++ b/ts/packages/cli/src/commands/$default.cmd.ts
@@ -1,9 +1,26 @@
-import { Context, Schema, LogLevel, String, pipe, Layer, Effect } from 'effect';
+import { Context, Schema, LogLevel, Equal, Layer, Effect } from 'effect';
import { Command, Options } from '@effect/cli';
import { setMinimumLogLevel } from 'src/effects/with-log-level';
import type { ConfigError } from 'effect/ConfigError';
-const logLevelChoices = LogLevel.allLevels.map(level => String.toLowerCase(level._tag));
+const logLevelEntries = [
+ ['all', LogLevel.All],
+ ['fatal', LogLevel.Fatal],
+ ['error', LogLevel.Error],
+ ['warning', LogLevel.Warning],
+ ['info', LogLevel.Info],
+ ['debug', LogLevel.Debug],
+ ['trace', LogLevel.Trace],
+ ['none', LogLevel.None],
+] as const satisfies ReadonlyArray<readonly [string, LogLevel.LogLevel]>;
+
+const logLevelChoices = logLevelEntries.map(([choice]) => choice);
+
+const decodeLogLevel = (literal: (typeof logLevelChoices)[number]): LogLevel.LogLevel =>
+ logLevelEntries.find(([choice]) => choice === literal)?.[1] ?? LogLevel.None;
+
+const encodeLogLevel = (logLevel: LogLevel.LogLevel): (typeof logLevelChoices)[number] =>
+ logLevelEntries.find(([, value]) => Equal.equals(value, logLevel))?.[0] ?? 'none';
const LogLevelLiteralSchema = Schema.Literal(...logLevelChoices)
.annotations({
@@ -12,13 +29,13 @@ const LogLevelLiteralSchema = Schema.Literal(...logLevelChoices)
.pipe(
Schema.transform(
Schema.declare((input: unknown): input is LogLevel.LogLevel =>
- LogLevel.allLevels.includes(input as LogLevel.LogLevel)
+ logLevelEntries.some(([, logLevel]) => Equal.equals(input, logLevel))
).annotations({
identifier: 'LogLevel',
}),
{
- decode: literal => pipe(literal, String.capitalize, LogLevel.fromLiteral),
- encode: logLevel => String.toLowerCase(logLevel._tag),
+ decode: decodeLogLevel,
+ encode: encodeLogLevel,
strict: true,
}
)
diff --git a/ts/packages/cli/src/commands/command-introspection.ts b/ts/packages/cli/src/commands/command-introspection.ts
new file mode 100644
index 000000000..21a4e3388
--- /dev/null
+++ b/ts/packages/cli/src/commands/command-introspection.ts
@@ -0,0 +1,94 @@
+import { Array as Arr, Effect, HashMap, HashSet, Match, Option } from 'effect';
+import { CliConfig, CommandDescriptor, Usage } from '@effect/cli';
+import { ComposioCliConfig } from 'src/cli-config';
+
+/**
+ * The only module in `src/` allowed to import `CommandDescriptor` or `Usage`
+ * from `@effect/cli`. Those modules are the redesign seam for Effect CLI v4's
+ * public command tree, so every descriptor walk must stay behind the small
+ * CLI-domain-shaped operations exported here — the v4 migration should only
+ * ever reimplement this file. An ESLint `no-restricted-imports` override in
+ * the repo-root `eslint.config.mjs` keeps the seam sealed.
+ */
+
+export type AnyCommandDescriptor = CommandDescriptor.Command<unknown>;
+
+export type AnyCommand = { readonly descriptor: AnyCommandDescriptor };
+
+const collectValueOptionNamesFromUsage = (usage: Usage.Usage, acc: Set<string>): void =>
+ Match.valueTags(usage, {
+ Named: usage => {
+ if (Option.isSome(usage.acceptedValues)) {
+ for (const name of usage.names) {
+ if (name.startsWith('-')) {
+ acc.add(name);
+ }
+ }
+ }
+ },
+ Optional: usage => {
+ collectValueOptionNamesFromUsage(usage.usage, acc);
+ },
+ Repeated: usage => {
+ collectValueOptionNamesFromUsage(usage.usage, acc);
+ },
+ Alternation: usage => {
+ collectValueOptionNamesFromUsage(usage.left, acc);
+ collectValueOptionNamesFromUsage(usage.right, acc);
+ },
+ Concat: usage => {
+ collectValueOptionNamesFromUsage(usage.left, acc);
+ collectValueOptionNamesFromUsage(usage.right, acc);
+ },
+ Mixed: () => undefined,
+ Empty: () => undefined,
+ });
+
+/**
+ * Collects the names of every flag that accepts a value (e.g. `--org`)
+ * across the whole command tree, so the top-level error handler can print
+ * a "Tip: --flag requires a value" hint on unknown-argument failures.
+ */
+export const collectValueOptionNames = (command: AnyCommand): ReadonlySet<string> => {
+ const names = new Set<string>();
+ const visited = new Set<AnyCommandDescriptor>();
+ const visit = (descriptor: AnyCommandDescriptor) => {
+ if (visited.has(descriptor)) {
+ return;
+ }
+ visited.add(descriptor);
+ collectValueOptionNamesFromUsage(CommandDescriptor.getUsage(descriptor), names);
+ for (const [, subcommand] of HashMap.toEntries(CommandDescriptor.getSubcommands(descriptor))) {
+ visit(subcommand);
+ }
+ };
+ visit(command.descriptor);
+ return names;
+};
+
+/** Whether `name` is one of the names the command itself answers to. */
+export const hasCommandName = (command: AnyCommand, name: string): boolean =>
+ HashSet.has(CommandDescriptor.getNames(command.descriptor), name);
+
+/**
+ * Lists the names of a command's direct subcommands, excluding the
+ * command's own names (the descriptor's subcommand map includes those).
+ */
+export const listSubcommandNames = (descriptor: AnyCommandDescriptor): ReadonlyArray<string> => {
+ const ownNames = CommandDescriptor.getNames(descriptor);
+ return Array.from(HashMap.keys(CommandDescriptor.getSubcommands(descriptor))).filter(
+ name => !HashSet.has(ownNames, name)
+ );
+};
+
+/**
+ * Parses `argv` (a full `process.argv`) against the command tree without
+ * running it, using the CLI's own config — a pre-flight check that surfaces
+ * `ValidationError`s (e.g. command mismatches) before the command executes.
+ */
+export const preflightParse = (command: AnyCommand, argv: ReadonlyArray<string>) =>
+ CommandDescriptor.parse(
+ command.descriptor,
+ Arr.prepend(Arr.drop(argv, 2), 'composio'),
+ CliConfig.make(ComposioCliConfig)
+ ).pipe(Effect.asVoid);
diff --git a/ts/packages/cli/src/commands/dev.cmd.ts b/ts/packages/cli/src/commands/dev.cmd.ts
index ce7b02ba6..10c8246c2 100644
--- a/ts/packages/cli/src/commands/dev.cmd.ts
+++ b/ts/packages/cli/src/commands/dev.cmd.ts
@@ -20,7 +20,7 @@ const devMode = Options.choice('mode', ['on', 'off'] as const).pipe(
Options.optional
);
-const devSubcommands = [
+export const devSubcommands = [
initCmd,
devToolsCmd$Execute,
triggersCmd$Listen,
diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.ts
index 3abebdc99..f4232f968 100644
--- a/ts/packages/cli/src/commands/index.ts
+++ b/ts/packages/cli/src/commands/index.ts
@@ -1,6 +1,12 @@
import process from 'node:process';
-import { Effect, Option } from 'effect';
+import { Array as Arr, Data, Effect, HashSet, Option } from 'effect';
import { Command, HelpDoc, ValidationError } from '@effect/cli';
+import {
+ hasCommandName,
+ listSubcommandNames,
+ preflightParse,
+ type AnyCommandDescriptor,
+} from './command-introspection';
import { $defaultCmd } from './$default.cmd';
import { getVersion } from 'src/effects/version';
import { versionCmd } from './version.cmd';
@@ -17,10 +23,11 @@ import { artifactsCmd } from './artifacts.cmd';
import { installCmd } from './install.cmd';
import { localToolsCmd } from './local-tools/local-tools.cmd';
import { generateCmd } from './generate/generate.cmd';
-import { buildDevCommand } from './dev.cmd';
+import { buildDevCommand, devSubcommands } from './dev.cmd';
import {
runParallelToolsExecuteFromArgv,
showToolsExecuteInputHelp,
+ TOOLS_EXECUTE_VALUE_OPTIONS,
} from './tools/commands/tools.execute.cmd';
import {
printRootHelp,
@@ -49,16 +56,9 @@ import {
} from 'src/services/command-project';
import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
import { installSkill, type SkillInstallTarget } from 'src/effects/install-skill';
-import {
- experimental,
- type CommandVisibility,
- type TaggedValue,
- tagged,
- visibleValues,
-} from './feature-tags';
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-const ROOT_COMMANDS: ReadonlyArray<TaggedValue<Command.Command<any, any, any, any>>> = [
+import { experimental, type CommandVisibility, tagged, visibleValues } from './feature-tags';
+
+const ROOT_COMMANDS = [
tagged(versionCmd),
tagged(upgradeCmd),
tagged(whoamiCmd),
@@ -84,193 +84,139 @@ const ROOT_COMMANDS: ReadonlyArray<TaggedValue<Command.Command<any, any, any, an
tagged(configCmd),
];
-export const buildRootCommand = (visibility: CommandVisibility) => {
- const subcommands = [...visibleValues(ROOT_COMMANDS, visibility), buildDevCommand(visibility)];
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return $defaultCmd.pipe(Command.withSubcommands(subcommands as any));
-};
-
-const formatSubcommandChoices = (choices: ReadonlyArray<string>) =>
- choices.map(choice => `'${choice}'`).join(', ');
-
-/**
- * Internal shape of an `@effect/cli` command descriptor. The public
- * `CommandDescriptor.getSubcommands` helper flattens nested subcommand trees
- * and only returns the *parent* Standard node for each branch, which means we
- * can't use it to walk deeper than one level. Walking the `_tag`-based
- * internal tree directly is the only way to recover the full descendable
- * structure without losing subcommand context on descent.
- */
-type InternalDescriptor =
- | { _tag: 'Standard'; name: string }
- | { _tag: 'GetUserInput'; name: string }
- | { _tag: 'Map'; command: InternalDescriptor }
- | {
- _tag: 'Subcommands';
- parent: InternalDescriptor;
- children: ReadonlyArray<InternalDescriptor>;
- };
-
-type UnwrappedDescriptor = Exclude<InternalDescriptor, { _tag: 'Map' }>;
-
-const unwrapMaps = (cmd: InternalDescriptor): UnwrappedDescriptor => {
- let current: InternalDescriptor = cmd;
- while (current._tag === 'Map') {
- current = current.command;
- }
- return current;
-};
-
-const getCommandName = (cmd: InternalDescriptor): string => {
- const unwrapped = unwrapMaps(cmd);
- if (unwrapped._tag === 'Subcommands') {
- return getCommandName(unwrapped.parent);
- }
- return unwrapped.name;
-};
-
-const getChildEntries = (
- cmd: InternalDescriptor
-): ReadonlyArray<readonly [string, InternalDescriptor]> => {
- const unwrapped = unwrapMaps(cmd);
- if (unwrapped._tag !== 'Subcommands') {
- return [];
- }
- return unwrapped.children.map(child => [getCommandName(child), child] as const);
+const getVisibleRootCommands = (visibility: CommandVisibility) => {
+ type RootCommand = (typeof ROOT_COMMANDS)[number]['value'];
+ return Arr.append(
+ visibleValues<RootCommand>(ROOT_COMMANDS, visibility),
+ buildDevCommand(visibility)
+ );
};
-const findNestedSubcommandMismatch = (
- argv: ReadonlyArray<string>,
- rootCommand: ReturnType<typeof buildRootCommand>
-): ReturnType<typeof ValidationError.commandMismatch> | undefined => {
- const args = argv.slice(2);
- let current: InternalDescriptor = rootCommand.descriptor as unknown as InternalDescriptor;
- const path = ['composio'];
-
- for (const token of args) {
- if (!token || token === '--' || token === '--help' || token === '-h' || token.startsWith('-')) {
- return undefined;
- }
-
- const children = getChildEntries(current);
- if (children.length === 0) {
- return undefined;
- }
-
- const match = children.find(([name]) => name === token);
- if (match) {
- current = match[1];
- path.push(token);
- continue;
- }
+export const buildRootCommand = (visibility: CommandVisibility) =>
+ $defaultCmd.pipe(Command.withSubcommands(getVisibleRootCommands(visibility)));
- if (path.length === 1) {
- return undefined;
- }
+const ROOT_INSTALL_SKILL_FLAGS = HashSet.make('--install-skill', '--instal-skill');
+const SKILL_INSTALL_TARGETS: ReadonlyArray<SkillInstallTarget> = ['claude', 'codex', 'openclaw'];
- const available = children.map(([name]) => name).sort();
- return ValidationError.commandMismatch(
- HelpDoc.p(
- `Invalid subcommand for ${path.join(' ')} - use one of ${formatSubcommandChoices(available)}`
- )
- );
- }
+class RootCommandError extends Data.TaggedError('commands/RootCommandError')<{
+ readonly message: string;
+}> {}
- return undefined;
+type RootInstallSkillRequest = {
+ readonly skillName?: string;
+ readonly target: SkillInstallTarget;
};
-const ROOT_INSTALL_SKILL_FLAGS = ['--install-skill', '--instal-skill'] as const;
-const SKILL_INSTALL_TARGETS = [
- 'claude',
- 'codex',
- 'openclaw',
-] as const satisfies ReadonlyArray<SkillInstallTarget>;
-
-type RootInstallSkillRequest =
- | {
- _tag: 'parsed';
- skillName?: string;
- target: SkillInstallTarget;
- }
- | { _tag: 'error'; message: string };
-
const isSkillInstallTarget = (value: string): value is SkillInstallTarget =>
- (SKILL_INSTALL_TARGETS as ReadonlyArray<string>).includes(value);
-
-export const parseRootInstallSkillRequest = (
- argv: ReadonlyArray<string>
-): RootInstallSkillRequest | undefined => {
- const args = argv.slice(2);
- for (let i = 0; i < args.length; i += 1) {
- const token = args[i];
- if (!token) continue;
-
- if ((ROOT_INSTALL_SKILL_FLAGS as ReadonlyArray<string>).includes(token)) {
- const rawValues: string[] = [];
- for (let j = i + 1; j < args.length; j += 1) {
- const next = args[j];
- if (!next) continue;
- if (next.startsWith('-')) break;
- rawValues.push(next);
+ SKILL_INSTALL_TARGETS.some(target => target === value);
+
+const rootCommandError = (message: string) => Effect.fail(new RootCommandError({ message }));
+
+const findRootInstallSkillValues = (
+ args: ReadonlyArray<string>
+): Option.Option<ReadonlyArray<string>> =>
+ Arr.matchLeft(args, {
+ onEmpty: Option.none,
+ onNonEmpty: (token, tail) => {
+ if (HashSet.has(ROOT_INSTALL_SKILL_FLAGS, token)) {
+ return Option.some(Arr.takeWhile(tail, value => !value.startsWith('-')));
}
-
- if (rawValues.length === 0) {
- return {
- _tag: 'error',
- message:
- 'Missing target for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>',
- };
+ if (token === '--log-level') {
+ return findRootInstallSkillValues(Arr.drop(tail, 1));
}
-
- if (rawValues.length === 1) {
- const [target] = rawValues;
- if (!isSkillInstallTarget(target)) {
- return {
- _tag: 'error',
- message:
- 'Invalid target for --install-skill. Expected one of: claude, codex, openclaw.',
- };
- }
- return { _tag: 'parsed', target };
+ if (token.startsWith('--log-level=') || token.startsWith('-')) {
+ return findRootInstallSkillValues(tail);
}
+ return Option.none();
+ },
+ });
- if (rawValues.length === 2) {
- const [skillName, target] = rawValues;
- if (!isSkillInstallTarget(target)) {
- return {
- _tag: 'error',
- message:
- 'Invalid target for --install-skill. Expected one of: claude, codex, openclaw.',
- };
- }
- return { _tag: 'parsed', skillName, target };
+const parseRootInstallSkillValues = (
+ rawValues: ReadonlyArray<string>
+): Effect.Effect<RootInstallSkillRequest, RootCommandError> =>
+ Arr.match(rawValues, {
+ onEmpty: () =>
+ rootCommandError(
+ 'Missing target for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>'
+ ),
+ onNonEmpty: ([first, second, ...rest]) => {
+ if (rest.length > 0) {
+ return rootCommandError(
+ 'Too many arguments for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>'
+ );
}
+ const target = second ?? first;
+ if (!isSkillInstallTarget(target)) {
+ return rootCommandError(
+ 'Invalid target for --install-skill. Expected one of: claude, codex, openclaw.'
+ );
+ }
+ return Effect.succeed(second === undefined ? { target } : { skillName: first, target });
+ },
+ });
- return {
- _tag: 'error',
- message:
- 'Too many arguments for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>',
- };
- }
+export const parseRootInstallSkillRequest = (
+ argv: ReadonlyArray<string>
+): Effect.Effect<Option.Option<RootInstallSkillRequest>, RootCommandError> =>
+ Option.match(findRootInstallSkillValues(Arr.drop(argv, 2)), {
+ onNone: () => Effect.succeed(Option.none()),
+ onSome: values => Effect.map(parseRootInstallSkillValues(values), Option.some),
+ });
- if (token === '--log-level') {
- i += 1;
- continue;
- }
+const scopeCommandMismatch = (
+ commandPath: string,
+ descriptor: AnyCommandDescriptor,
+ error: unknown
+) => {
+ if (!ValidationError.isValidationError(error) || !ValidationError.isCommandMismatch(error)) {
+ return error;
+ }
+ const childNames = listSubcommandNames(descriptor).map(name => `'${name}'`);
+ if (childNames.length === 0) return error;
+
+ const oneOf = childNames.length === 1 ? '' : ' one of';
+ return ValidationError.commandMismatch(
+ HelpDoc.p(
+ `Invalid subcommand for composio ${commandPath} - use${oneOf} ${childNames.join(', ')}`
+ )
+ );
+};
- if (token.startsWith('--log-level=')) {
- continue;
- }
+const refineRootCommandMismatch = (
+ argv: ReadonlyArray<string>,
+ visibility: CommandVisibility,
+ originalError: ValidationError.ValidationError
+) => {
+ const rootCommandName = argv[2];
+ if (!rootCommandName || !ValidationError.isCommandMismatch(originalError)) {
+ return Effect.fail(originalError);
+ }
- if (!token.startsWith('-')) {
- return undefined;
- }
+ const rootCommand = Arr.findFirst(getVisibleRootCommands(visibility), command =>
+ hasCommandName(command, rootCommandName)
+ );
+ if (Option.isNone(rootCommand)) {
+ return Effect.fail(originalError);
}
- return undefined;
+
+ const nestedCommandName = argv[3];
+ const nestedDevCommand =
+ rootCommandName === 'dev' && visibility.isDevModeEnabled && nestedCommandName
+ ? Arr.findFirst(devSubcommands, command => hasCommandName(command, nestedCommandName))
+ : Option.none();
+ const descriptor = Option.match(nestedDevCommand, {
+ onNone: () => rootCommand.value.descriptor,
+ onSome: command => command.descriptor,
+ });
+ const commandPath = Option.isSome(nestedDevCommand)
+ ? `${rootCommandName} ${nestedCommandName}`
+ : rootCommandName;
+
+ return Effect.fail(scopeCommandMismatch(commandPath, descriptor, originalError));
};
-const parseExecuteInputHelpSlug = (argv: ReadonlyArray<string>): string | undefined => {
- const args = argv.slice(2);
+export const parseExecuteInputHelpSlug = (argv: ReadonlyArray<string>): string | undefined => {
+ const args = Arr.drop(argv, 2);
const isRootExecute = args[0] === 'execute';
const isDevExecute = args[0] === 'dev' && args[1] === 'playground-execute';
if (!isRootExecute && !isDevExecute) return undefined;
@@ -278,55 +224,29 @@ const parseExecuteInputHelpSlug = (argv: ReadonlyArray<string>): string | undefi
const hasHelp = args.includes('--help') || args.includes('-h');
if (!hasHelp) return undefined;
- const tail = isRootExecute ? args.slice(1) : args.slice(2);
- for (let i = 0; i < tail.length; i += 1) {
- const token = tail[i];
- if (!token) continue;
-
- // Stop option parsing after "--" and treat next positional as slug.
- if (token === '--') {
- const candidate = tail[i + 1];
- return candidate && !candidate.startsWith('-') ? candidate : undefined;
- }
-
- // Ignore help flags.
- if (token === '--help' || token === '-h') {
- continue;
- }
-
- // Skip known execute option values.
- if (
- token === '--data' ||
- token === '-d' ||
- token === '--parallel' ||
- token === '-p' ||
- token === '--user-id' ||
- token === '--project-name'
- ) {
- i += 1;
- continue;
- }
- if (
- token.startsWith('--data=') ||
- token.startsWith('-d=') ||
- token === '--parallel' ||
- token === '-p' ||
- token.startsWith('--user-id=') ||
- token.startsWith('--project-name=')
- ) {
- continue;
- }
-
- // Skip unknown flags.
- if (token.startsWith('-')) {
- continue;
- }
-
- // First positional token is the slug.
- return token;
- }
+ const findSlug = (tail: ReadonlyArray<string>): string | undefined =>
+ Arr.matchLeft(tail, {
+ onEmpty: () => undefined,
+ onNonEmpty: (token, rest) => {
+ if (token === '--') {
+ return Option.getOrUndefined(
+ Option.filter(Arr.head(rest), candidate => !candidate.startsWith('-'))
+ );
+ }
+ if (token === '--help' || token === '-h') {
+ return findSlug(rest);
+ }
+ if (HashSet.has(TOOLS_EXECUTE_VALUE_OPTIONS, token)) {
+ return findSlug(Arr.drop(rest, 1));
+ }
+ if (token.startsWith('-')) {
+ return findSlug(rest);
+ }
+ return token;
+ },
+ });
- return undefined;
+ return findSlug(Arr.drop(args, isRootExecute ? 1 : 2));
};
const normalizeVersionShortFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
@@ -338,78 +258,54 @@ const normalizeVersionShortFlag = (argv: ReadonlyArray<string>): ReadonlyArray<s
};
const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
- const head = argv.slice(0, 2);
- const args = argv.slice(2);
+ const head = Arr.take(argv, 2);
+ const args = Arr.drop(argv, 2);
const isListen = args[0] === 'listen';
if (!isListen) {
return argv;
}
- const normalized: string[] = [...head];
- for (let i = 0; i < args.length; i += 1) {
- const token = args[i];
- if (token !== '--stream') {
- normalized.push(token ?? '');
- continue;
- }
-
- const next = args[i + 1];
- if (next === undefined || next.startsWith('-')) {
- normalized.push('--stream=');
- continue;
- }
+ return Arr.appendAll(
+ head,
+ Arr.map(args, (token, index) => {
+ const next = args[index + 1];
+ return token === '--stream' && (next === undefined || next.startsWith('-'))
+ ? '--stream='
+ : token;
+ })
+ );
+};
- normalized.push(token);
+const parseBooleanFlag = (argument: string, name: string): Option.Option<boolean> => {
+ if (argument === name || argument === `${name}=true`) {
+ return Option.some(true);
}
-
- return normalized;
+ return argument === `${name}=false` ? Option.some(false) : Option.none();
};
const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
- const normalized: string[] = [...argv.slice(0, 2)];
- const args = argv.slice(2);
+ const retainedArgs: Array<string> = [];
let perfDebug: boolean | undefined;
let toolDebug: boolean | undefined;
let acpOnly: boolean | undefined;
- for (const arg of args) {
- if (arg === '--perf-debug') {
- perfDebug = true;
- continue;
- }
- if (arg === '--tool-debug') {
- toolDebug = true;
- continue;
- }
- if (arg === '--perf-debug=false') {
- perfDebug = false;
+ for (const argument of Arr.drop(argv, 2)) {
+ const parsedPerfDebug = Option.getOrUndefined(parseBooleanFlag(argument, '--perf-debug'));
+ if (parsedPerfDebug !== undefined) {
+ perfDebug = parsedPerfDebug;
continue;
}
- if (arg === '--tool-debug=false') {
- toolDebug = false;
+ const parsedToolDebug = Option.getOrUndefined(parseBooleanFlag(argument, '--tool-debug'));
+ if (parsedToolDebug !== undefined) {
+ toolDebug = parsedToolDebug;
continue;
}
- if (arg === '--perf-debug=true') {
- perfDebug = true;
+ const parsedAcpOnly = Option.getOrUndefined(parseBooleanFlag(argument, '--acp-only'));
+ if (parsedAcpOnly !== undefined) {
+ acpOnly = parsedAcpOnly;
continue;
}
- if (arg === '--tool-debug=true') {
- toolDebug = true;
- continue;
- }
- if (arg === '--acp-only') {
- acpOnly = true;
- continue;
- }
- if (arg === '--acp-only=false') {
- acpOnly = false;
- continue;
- }
- if (arg === '--acp-only=true') {
- acpOnly = true;
- continue;
- }
- normalized.push(arg);
+ retainedArgs.push(argument);
}
resetRuntimeDebugFlags();
@@ -417,13 +313,15 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<s
...(perfDebug === undefined ? {} : { perfDebug }),
...(toolDebug === undefined ? {} : { toolDebug }),
});
+ // The hidden --acp-only flag is stripped from argv before @effect/cli parses it, so its value
+ // travels to run.cmd.ts through the environment; effect/Config cannot write or delete env vars.
if (acpOnly === undefined) {
delete process.env.COMPOSIO_RUN_ACP_ONLY;
} else {
process.env.COMPOSIO_RUN_ACP_ONLY = acpOnly ? '1' : '0';
}
- return normalized;
+ return Arr.appendAll(Arr.take(argv, 2), retainedArgs);
};
const isRootHelp = (argv: ReadonlyArray<string>): boolean => {
@@ -453,19 +351,18 @@ const isDebugWhoIsMyMaster = (argv: ReadonlyArray<string>): boolean => {
};
const normalizeDangerouslyAllowFlag = (argv: ReadonlyArray<string>) => {
- const normalized: string[] = [...argv.slice(0, 2)];
+ const retainedArgs: Array<string> = [];
let dangerouslyAllow = false;
-
- for (const arg of argv.slice(2)) {
- if (arg === '--dangerously-allow') {
+ for (const argument of Arr.drop(argv, 2)) {
+ if (argument === '--dangerously-allow') {
dangerouslyAllow = true;
- continue;
+ } else {
+ retainedArgs.push(argument);
}
- normalized.push(arg);
}
return {
- argv: normalized,
+ argv: Arr.appendAll(Arr.take(argv, 2), retainedArgs),
dangerouslyAllow,
};
};
@@ -492,6 +389,60 @@ const isDangerousDevCommand = (args: ReadonlyArray<string>): boolean => {
return false;
};
+const printCommandHintGraph = Effect.suspend(() =>
+ Effect.flatMap(TerminalUI, ui =>
+ ui.output(JSON.stringify(renderCommandHintGraph(), null, 2), { force: true })
+ )
+);
+
+const printDebugApiInfo = Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const confirmed = yield* ui.confirm(
+ 'This will print your current CLI API key and scoped identifiers to stdout. Continue?',
+ { defaultValue: false }
+ );
+ if (!confirmed) {
+ return yield* rootCommandError('Aborted printing API credentials.');
+ }
+ const ctx = yield* ComposioUserContext;
+ const apiKey = Option.getOrUndefined(ctx.data.apiKey);
+ if (!apiKey) {
+ return yield* rootCommandError('No user API key found in the current CLI session.');
+ }
+ const orgId = Option.getOrUndefined(ctx.data.orgId);
+ const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
+ Effect.mapError(formatResolveCommandProjectError),
+ Effect.option
+ );
+ return yield* ui.output(
+ JSON.stringify(
+ {
+ apiKey,
+ orgId: orgId ?? null,
+ consumerUserId:
+ Option.isSome(consumerProject) && consumerProject.value.projectType === 'CONSUMER'
+ ? (consumerProject.value.consumerUserId ?? null)
+ : null,
+ },
+ null,
+ 2
+ ),
+ { force: true }
+ );
+});
+
+const printDetectedMaster = Effect.suspend(() =>
+ Effect.flatMap(TerminalUI, ui =>
+ ui.output(JSON.stringify({ master: detectMaster() }, null, 2), { force: true })
+ )
+);
+
+const printDevModeDisabled = Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ yield* ui.log.error('Developer mode is off.');
+ yield* ui.log.step('Run `composio dev --mode on` in an interactive terminal to enable it.');
+});
+
export const runWithConfig = Effect.gen(function* () {
const cliUserConfig = yield* ComposioCliUserConfig;
const visibility: CommandVisibility = {
@@ -506,23 +457,8 @@ export const runWithConfig = Effect.gen(function* () {
version,
});
- return (argv: ReadonlyArray<string>) => {
- const { argv: argvWithoutDangerouslyAllow, dangerouslyAllow } =
- normalizeDangerouslyAllowFlag(argv);
- const normalizedArgv = normalizeHiddenDebugFlags(
- normalizeListenStreamFlag(normalizeVersionShortFlag(argvWithoutDangerouslyAllow))
- );
+ const routeRootCommand = (normalizedArgv: ReadonlyArray<string>, dangerouslyAllow: boolean) => {
const args = normalizedArgv.slice(2);
- const installSkillRequest = parseRootInstallSkillRequest(normalizedArgv);
- if (installSkillRequest) {
- if (installSkillRequest._tag === 'error') {
- return Effect.fail(new Error(installSkillRequest.message));
- }
- return installSkill({
- skillName: installSkillRequest.skillName,
- target: installSkillRequest.target,
- });
- }
if (isRootHelp(normalizedArgv)) {
return printRootHelp(visibility, parseHelpLevel(normalizedArgv[3]) ?? 'default');
}
@@ -531,75 +467,25 @@ export const runWithConfig = Effect.gen(function* () {
const helpLevel = parseHelpLevel(normalizedArgv[normalizedArgv.length - 1]) ?? 'default';
return printSubcommandHelp(subHelp, visibility, helpLevel);
}
- const nestedMismatch = findNestedSubcommandMismatch(normalizedArgv, rootCommand);
- if (nestedMismatch) {
- return Effect.fail(nestedMismatch);
- }
const parallelExecute = runParallelToolsExecuteFromArgv(normalizedArgv);
if (parallelExecute) {
return parallelExecute;
}
if (isGenerateGraph(normalizedArgv)) {
- return Effect.sync(() => {
- // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
- process.stdout.write(`${JSON.stringify(renderCommandHintGraph(), null, 2)}\n`);
- });
+ return printCommandHintGraph;
}
if (isDebugApiInfo(normalizedArgv)) {
- return Effect.gen(function* () {
- const ui = yield* TerminalUI;
- const confirmed = yield* ui.confirm(
- 'This will print your current CLI API key and scoped identifiers to stdout. Continue?',
- { defaultValue: false }
- );
- if (!confirmed) {
- return yield* Effect.fail(new Error('Aborted printing API credentials.'));
- }
- const ctx = yield* ComposioUserContext;
- const apiKey = Option.getOrUndefined(ctx.data.apiKey);
- if (!apiKey) {
- return yield* Effect.fail(new Error('No user API key found in the current CLI session.'));
- }
- const orgId = Option.getOrUndefined(ctx.data.orgId);
- const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
- Effect.mapError(formatResolveCommandProjectError),
- Effect.option
- );
- return yield* Effect.sync(() => {
- // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
- process.stdout.write(
- `${JSON.stringify(
- {
- apiKey,
- orgId: orgId ?? null,
- consumerUserId:
- Option.isSome(consumerProject) && consumerProject.value.projectType === 'CONSUMER'
- ? (consumerProject.value.consumerUserId ?? null)
- : null,
- },
- null,
- 2
- )}\n`
- );
- });
- });
+ return printDebugApiInfo;
}
if (isDebugWhoIsMyMaster(normalizedArgv)) {
- return Effect.sync(() => {
- // eslint-disable-next-line no-restricted-syntax -- migrated with the seam-rules slice (PR 6 of this stack)
- process.stdout.write(`${JSON.stringify({ master: detectMaster() }, null, 2)}\n`);
- });
+ return printDetectedMaster;
}
const executeHelpSlug = parseExecuteInputHelpSlug(normalizedArgv);
if (executeHelpSlug) {
return showToolsExecuteInputHelp(executeHelpSlug);
}
if (!visibility.isDevModeEnabled && args[0] === 'dev' && !isDevModeOnlyInvocation(args)) {
- return Effect.gen(function* () {
- const ui = yield* TerminalUI;
- yield* ui.log.error('Developer mode is off.');
- yield* ui.log.step('Run `composio dev --mode on` in an interactive terminal to enable it.');
- });
+ return printDevModeDisabled;
}
if (isDangerousDevCommand(args)) {
return Effect.gen(function* () {
@@ -619,6 +505,31 @@ export const runWithConfig = Effect.gen(function* () {
return yield* run(normalizedArgv);
});
}
- return run(normalizedArgv);
+ return preflightParse(rootCommand, normalizedArgv).pipe(
+ Effect.matchEffect({
+ onFailure: error =>
+ ValidationError.isCommandMismatch(error)
+ ? refineRootCommandMismatch(normalizedArgv, visibility, error)
+ : run(normalizedArgv),
+ onSuccess: () => run(normalizedArgv),
+ })
+ );
+ };
+
+ return (argv: ReadonlyArray<string>) => {
+ const { argv: argvWithoutDangerouslyAllow, dangerouslyAllow } =
+ normalizeDangerouslyAllowFlag(argv);
+ const normalizedArgv = normalizeHiddenDebugFlags(
+ normalizeListenStreamFlag(normalizeVersionShortFlag(argvWithoutDangerouslyAllow))
+ );
+
+ return parseRootInstallSkillRequest(normalizedArgv).pipe(
+ Effect.flatMap(
+ Option.match({
+ onNone: () => routeRootCommand(normalizedArgv, dangerouslyAllow),
+ onSome: installSkill,
+ })
+ )
+ );
};
});
diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
index 2cad132dc..4ab570991 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
@@ -2,7 +2,7 @@ import { Args, Command, Options } from '@effect/cli';
import type { Composio } from '@composio/client';
import { isLocalToolSlug } from '@composio/cli-local-tools';
import util from 'node:util';
-import { Effect, Option, Either, Exit, Fiber, Cause } from 'effect';
+import { Effect, Option, Either, Exit, Fiber, Cause, HashSet } from 'effect';
import { encodingForModel } from 'js-tiktoken';
import { redact } from 'src/ui/redact';
import { parseJsonRecord } from 'src/utils/parse-json';
@@ -84,6 +84,15 @@ const accountOption = Options.text('account').pipe(
Options.optional
);
+export const TOOLS_EXECUTE_VALUE_OPTIONS = HashSet.make(
+ '--data',
+ '-d',
+ '--file',
+ '--account',
+ '--user-id',
+ '--project-name'
+);
+
const userId = Options.text('user-id').pipe(
Options.optional,
Options.withDescription('Developer-project user ID override')
@@ -458,7 +467,11 @@ const emitExecuteFailureTelemetry = (params: {
? getToolExecuteValidationFailedEvent({
toolSlug: params.toolSlug,
args: params.args,
- error: new ToolInputValidationError(params.toolSlug, 'server', [message]),
+ error: new ToolInputValidationError({
+ toolSlug: params.toolSlug,
+ schemaPath: 'server',
+ issues: [message],
+ }),
surface: params.surface,
projectMode: params.projectMode,
stage:
diff --git a/ts/packages/cli/src/services/tool-input-validation.ts b/ts/packages/cli/src/services/tool-input-validation.ts
index a7007ed32..a05e8bc6e 100644
--- a/ts/packages/cli/src/services/tool-input-validation.ts
+++ b/ts/packages/cli/src/services/tool-input-validation.ts
@@ -1,13 +1,15 @@
-// eslint-disable-next-line no-restricted-imports -- migrated with the seam-rules slice (PR 6 of this stack)
-import path from 'node:path';
-import { FileSystem } from '@effect/platform';
-import { Effect, Option } from 'effect';
-import { jsonSchemaToZodSchema } from '@composio/core';
+import { AutoCorrect, CliConfig } from '@effect/cli';
+import { FileSystem, Path } from '@effect/platform';
+import { Data, Effect, Option, ParseResult, Schema } from 'effect';
import { getLocalToolInputDefinition } from '@composio/cli-local-tools';
-import { z } from 'zod/v3';
+import {
+ jsonSchemaToEffectSchema,
+ type JsonSchemaValidationIssue,
+} from '@composio/json-schema-to-effect-schema';
+import { JsonRecordSchema } from 'src/effects/json';
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 { logToolDebug } from 'src/services/runtime-debug-logger';
import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
import { ComposioUserContext } from 'src/services/user-context';
@@ -18,22 +20,32 @@ type CachedToolInputDefinition = {
readonly inputSchema: Record<string, unknown>;
};
+const CachedToolInputDefinitionEnvelope = Schema.Struct({
+ version: Schema.optional(Schema.Unknown),
+ inputSchema: JsonRecordSchema,
+});
+const ObjectSchemaWithProperties = Schema.Struct({ properties: JsonRecordSchema });
+
+const decodeJsonObject = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));
+const decodeCachedToolInputDefinitionEnvelope = Schema.decodeUnknownOption(
+ CachedToolInputDefinitionEnvelope
+);
+const decodeObjectSchemaWithProperties = Schema.decodeUnknownOption(ObjectSchemaWithProperties);
+
const sanitizeToolSlug = (slug: string) => slug.replace(/[^A-Za-z0-9_.-]/g, '_');
-const toolDefinitionPath = (cacheDir: string, slug: string) =>
+const toolDefinitionPath = (path: Path.Path, cacheDir: string, slug: string) =>
path.join(cacheDir, TOOL_DEFINITIONS_DIR, `${sanitizeToolSlug(slug)}.json`);
-const ensureToolDefinitionsDir = (fs: FileSystem.FileSystem, cacheDir: string) =>
+const ensureToolDefinitionsDir = (fs: FileSystem.FileSystem, path: Path.Path, cacheDir: string) =>
fs.makeDirectory(path.join(cacheDir, TOOL_DEFINITIONS_DIR), { recursive: true });
const parseSchemaFile = (raw: string, schemaPath: string) =>
- Effect.try({
- try: () => JSON.parse(raw) as Record<string, unknown>,
- catch: () => new Error(`Cached tool schema at ${schemaPath} is not valid JSON.`),
- });
-
-const isRecord = (value: unknown): value is Record<string, unknown> =>
- typeof value === 'object' && value !== null && !Array.isArray(value);
+ decodeJsonObject(raw).pipe(
+ Effect.mapError(
+ cause => new Error(`Cached tool schema at ${schemaPath} is not valid JSON.`, { cause })
+ )
+ );
const PLACEHOLDER_TOOL_VERSION = '00000000_00';
@@ -70,17 +82,12 @@ const resolveLatestAvailableVersion = (params: {
return params.toolkitLatestVersion;
};
-const toolDebugLog = (label: string, details: Record<string, unknown>) => {
- if (!isToolDebugEnabled()) return;
- console.error(`[tool-debug] ${JSON.stringify({ label, ...details })}`);
-};
-
const parseCachedToolDefinition = (parsed: Record<string, unknown>): CachedToolInputDefinition => {
- const inputSchema = parsed.inputSchema;
- if (isRecord(inputSchema)) {
+ const envelope = decodeCachedToolInputDefinitionEnvelope(parsed);
+ if (Option.isSome(envelope)) {
return {
- version: typeof parsed.version === 'string' ? parsed.version : null,
- inputSchema,
+ version: typeof envelope.value.version === 'string' ? envelope.value.version : null,
+ inputSchema: envelope.value.inputSchema,
};
}
@@ -104,14 +111,21 @@ const serializeCachedToolDefinition = (definition: CachedToolInputDefinition): s
export const getCachedToolInputDefinition = (slug: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const cacheDir = yield* setupCacheDir;
- const schemaPath = toolDefinitionPath(cacheDir, slug);
-
- if (!(yield* fs.exists(schemaPath))) {
+ const schemaPath = toolDefinitionPath(path, cacheDir, slug);
+
+ const raw = yield* fs
+ .readFileString(schemaPath, 'utf8')
+ .pipe(
+ Effect.catchTag('SystemError', error =>
+ error.reason === 'NotFound' ? Effect.succeed(null) : Effect.fail(error)
+ )
+ );
+ if (raw === null) {
return null;
}
- const raw = yield* fs.readFileString(schemaPath, 'utf8');
const parsed = yield* parseSchemaFile(raw, schemaPath);
const cached = parseCachedToolDefinition(parsed);
return {
@@ -123,18 +137,24 @@ export const getCachedToolInputDefinition = (slug: string) =>
export const getToolDefinitionCachePath = (slug: string) =>
Effect.gen(function* () {
+ const path = yield* Path.Path;
const cacheDir = yield* setupCacheDir;
- return toolDefinitionPath(cacheDir, slug);
+ return toolDefinitionPath(path, cacheDir, slug);
});
export const invalidateToolInputDefinition = (slug: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const cacheDir = yield* setupCacheDir;
- const schemaPath = toolDefinitionPath(cacheDir, slug);
- if (yield* fs.exists(schemaPath)) {
- yield* fs.remove(schemaPath);
- }
+ const schemaPath = toolDefinitionPath(path, cacheDir, slug);
+ yield* fs
+ .remove(schemaPath)
+ .pipe(
+ Effect.catchTag('SystemError', error =>
+ error.reason === 'NotFound' ? Effect.void : Effect.fail(error)
+ )
+ );
});
const fetchResolvedLatestToolVersion = (
@@ -155,7 +175,7 @@ const fetchResolvedLatestToolVersion = (
orgId: params?.orgId,
projectId: params?.projectId,
});
- toolDebugLog('latest_tool_version', {
+ yield* logToolDebug('latest_tool_version', {
slug,
orgId: params?.orgId,
projectId: params?.projectId,
@@ -170,11 +190,12 @@ const fetchAndCacheToolInputDefinition = (
) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const repo = yield* ComposioToolkitsRepository;
const cacheDir = yield* setupCacheDir;
const localDefinition = getLocalToolInputDefinition(slug);
- const schemaPath = toolDefinitionPath(cacheDir, localDefinition?.finalSlug ?? slug);
- yield* ensureToolDefinitionsDir(fs, cacheDir);
+ const schemaPath = toolDefinitionPath(path, cacheDir, localDefinition?.finalSlug ?? slug);
+ yield* ensureToolDefinitionsDir(fs, path, cacheDir);
if (localDefinition) {
yield* fs.writeFileString(
@@ -191,21 +212,27 @@ const fetchAndCacheToolInputDefinition = (
};
}
- const tool = yield* repo.getToolDetailed(slug);
- toolDebugLog('tool_detail', {
+ const [tool, latestVersion] = yield* Effect.all(
+ [
+ repo.getToolDetailed(slug),
+ fetchResolvedLatestToolVersion(slug, params).pipe(
+ Effect.catchAll(() => Effect.succeed(null))
+ ),
+ ],
+ { concurrency: 2 }
+ );
+ yield* logToolDebug('tool_detail', {
slug,
tool,
});
- const schema = (tool.input_parameters ?? {}) as Record<string, unknown>;
+ const schema = tool.input_parameters;
const version =
- (yield* fetchResolvedLatestToolVersion(slug, params).pipe(
- Effect.catchAll(() => Effect.succeed(null))
- )) ??
+ latestVersion ??
resolveLatestAvailableVersion({
toolLatestVersion: selectLatestVersion(tool.available_versions),
toolkitLatestVersion: null,
});
- toolDebugLog('resolved_tool_version', {
+ yield* logToolDebug('resolved_tool_version', {
slug,
resolvedVersion: version,
cachePath: schemaPath,
@@ -231,7 +258,7 @@ export const getOrFetchToolInputDefinition = (
return yield* fetchAndCacheToolInputDefinition(slug, params);
}
- const freshness = yield* refreshToolInputDefinitionIfVersionChanged(
+ const freshness = yield* refreshAndFetchToolInputDefinitionIfVersionChanged(
slug,
cached.version,
params
@@ -240,6 +267,7 @@ export const getOrFetchToolInputDefinition = (
Effect.succeed({
isStale: false,
latestVersion: cached.version,
+ definition: null,
skipped: false as const,
})
)
@@ -249,18 +277,20 @@ export const getOrFetchToolInputDefinition = (
return cached;
}
- const refreshed = yield* getCachedToolInputDefinition(slug);
- return refreshed ?? (yield* fetchAndCacheToolInputDefinition(slug, params));
+ return freshness.definition ?? cached;
});
-export const refreshToolInputDefinitionIfVersionChanged = (
+// Returns the freshly fetched definition on the stale path so callers that
+// need it (getOrFetchToolInputDefinition) don't re-read the cache file that
+// fetchAndCacheToolInputDefinition just wrote.
+const refreshAndFetchToolInputDefinitionIfVersionChanged = (
slug: string,
cachedVersion: string | null,
params?: { readonly orgId?: string; readonly projectId?: string }
) =>
Effect.gen(function* () {
const latestVersion = yield* fetchResolvedLatestToolVersion(slug, params);
- toolDebugLog('resolved_tool_version', {
+ yield* logToolDebug('resolved_tool_version', {
slug,
mode: 'refresh',
cachedVersion,
@@ -269,65 +299,47 @@ export const refreshToolInputDefinitionIfVersionChanged = (
projectId: params?.projectId,
});
const isStale = latestVersion !== cachedVersion;
+ const definition = isStale ? yield* fetchAndCacheToolInputDefinition(slug, params) : null;
- if (isStale) {
- yield* fetchAndCacheToolInputDefinition(slug, params);
- }
-
- return { isStale, latestVersion, skipped: false as const };
+ return { isStale, latestVersion, definition, skipped: false as const };
});
-export class ToolInputValidationError extends Error {
- readonly _tag = 'ToolInputValidationError';
+export const refreshToolInputDefinitionIfVersionChanged = (
+ slug: string,
+ cachedVersion: string | null,
+ params?: { readonly orgId?: string; readonly projectId?: string }
+) =>
+ refreshAndFetchToolInputDefinitionIfVersionChanged(slug, cachedVersion, params).pipe(
+ Effect.map(({ isStale, latestVersion, skipped }) => ({ isStale, latestVersion, skipped }))
+ );
- constructor(
- readonly toolSlug: string,
- readonly schemaPath: string,
- readonly issues: ReadonlyArray<string>,
- options?: ErrorOptions
- ) {
- super(
- [
- `Input validation failed for ${toolSlug}.`,
- `Schema: ${schemaPath}`,
- ...issues.map(issue => `- ${issue}`),
- ].join('\n'),
- options
- );
+export class ToolInputValidationError extends Data.TaggedError('ToolInputValidationError')<{
+ readonly toolSlug: string;
+ readonly schemaPath: string;
+ readonly issues: ReadonlyArray<string>;
+ readonly cause?: unknown;
+}> {
+ override get message(): string {
+ return [
+ `Input validation failed for ${this.toolSlug}.`,
+ `Schema: ${this.schemaPath}`,
+ ...this.issues.map(issue => `- ${issue}`),
+ ].join('\n');
}
}
const getObjectSchemaProperties = (schema: Record<string, unknown>): ReadonlyArray<string> => {
- const properties = schema.properties;
- if (!properties || typeof properties !== 'object' || Array.isArray(properties)) {
- return [];
- }
-
- return Object.keys(properties as Record<string, unknown>);
+ const objectSchema = decodeObjectSchemaWithProperties(schema);
+ return Option.isSome(objectSchema) ? Object.keys(objectSchema.value.properties) : [];
};
const normalizeKey = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
-const levenshteinDistance = (left: string, right: string): number => {
- if (left === right) return 0;
- if (left.length === 0) return right.length;
- if (right.length === 0) return left.length;
-
- const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
- const current = new Array<number>(right.length + 1);
-
- for (let i = 0; i < left.length; i += 1) {
- current[0] = i + 1;
- for (let j = 0; j < right.length; j += 1) {
- const cost = left[i] === right[j] ? 0 : 1;
- current[j + 1] = Math.min(current[j]! + 1, previous[j + 1]! + 1, previous[j]! + cost);
- }
- for (let j = 0; j <= right.length; j += 1) {
- previous[j] = current[j]!;
- }
- }
+const schemaKeySuggestionConfig = CliConfig.defaultConfig;
- return previous[right.length]!;
+type SchemaKeyCandidate = {
+ readonly key: string;
+ readonly score: number;
};
const findClosestSchemaKey = (
@@ -335,32 +347,39 @@ const findClosestSchemaKey = (
allowedKeys: ReadonlyArray<string>
): string | undefined => {
const normalizedUnknownKey = normalizeKey(unknownKey);
- const candidates = allowedKeys
- .map(key => ({
+ if (!normalizedUnknownKey) {
+ return undefined;
+ }
+
+ const closest = allowedKeys.reduce<SchemaKeyCandidate | undefined>((best, key) => {
+ const normalizedKey = normalizeKey(key);
+ const distance = AutoCorrect.levensteinDistance(
+ normalizedUnknownKey,
+ normalizedKey,
+ schemaKeySuggestionConfig
+ );
+ const containsBonus =
+ normalizedKey.includes(normalizedUnknownKey) || normalizedUnknownKey.includes(normalizedKey)
+ ? -2
+ : 0;
+ const candidate = {
key,
- normalized: normalizeKey(key),
- }))
- .map(candidate => {
- const distance = levenshteinDistance(normalizedUnknownKey, candidate.normalized);
- const containsBonus =
- candidate.normalized.includes(normalizedUnknownKey) ||
- normalizedUnknownKey.includes(candidate.normalized)
- ? -2
- : 0;
- return {
- key: candidate.key,
- score: distance + containsBonus,
- };
- })
- .sort((left, right) => left.score - right.score);
+ score: distance + containsBonus,
+ };
+
+ if (!best || candidate.score < best.score) {
+ return candidate;
+ }
- const best = candidates[0];
- if (!best) {
+ return best;
+ }, undefined);
+
+ const threshold = Math.max(3, Math.ceil(normalizedUnknownKey.length * 0.6));
+ if (!closest || closest.score > threshold) {
return undefined;
}
- const threshold = Math.max(3, Math.ceil(normalizedUnknownKey.length * 0.6));
- return best.score <= threshold ? best.key : undefined;
+ return closest.key;
};
const formatUnknownKeyIssue = (
@@ -381,6 +400,27 @@ const formatUnknownKeyIssue = (
});
};
+const formatSchemaIssues = (
+ schemaIssues: ReadonlyArray<JsonSchemaValidationIssue>,
+ allowedKeys: ReadonlyArray<string>
+): ReadonlyArray<string> =>
+ schemaIssues.flatMap(issue => {
+ if (issue.code === 'unrecognized_keys' && issue.keys) {
+ return formatUnknownKeyIssue(issue.keys, allowedKeys);
+ }
+
+ const location = issue.path.length > 0 ? issue.path.join('.') : '<root>';
+ return [`${location}: ${issue.message}`];
+ });
+
+const compileToolInputSchema = (
+ jsonSchema: Record<string, unknown>,
+ allowedKeys: ReadonlyArray<string>
+) =>
+ jsonSchemaToEffectSchema(jsonSchema, {
+ formatIssues: issues => formatSchemaIssues(issues, allowedKeys),
+ });
+
export const validateToolInputArgumentsWithDefinition = (
slug: string,
args: Record<string, unknown>,
@@ -394,31 +434,27 @@ export const validateToolInputArgumentsWithDefinition = (
const allowedKeys = getObjectSchemaProperties(schema);
const normalizedSchema = normalizeFileUploadSchema(schema);
- const zodSchema = yield* Effect.try({
- try: () => jsonSchemaToZodSchema<z.ZodTypeAny>(normalizedSchema),
+ const inputSchema = yield* Effect.try({
+ try: () => compileToolInputSchema(normalizedSchema, allowedKeys),
catch: error =>
- new ToolInputValidationError(
- slug,
+ new ToolInputValidationError({
+ toolSlug: slug,
schemaPath,
- ['Could not compile the cached JSON schema into a Zod validator.'],
- { cause: error }
- ),
+ issues: ['Could not compile the cached JSON schema into a validator.'],
+ cause: error,
+ }),
});
- const parsed = zodSchema.safeParse(args);
- if (parsed.success) {
- return { schemaPath, schema };
- }
-
- const issues = parsed.error.issues.flatMap(issue => {
- if (issue.code === 'unrecognized_keys') {
- return formatUnknownKeyIssue(issue.keys, allowedKeys);
- }
- const location = issue.path.length > 0 ? issue.path.join('.') : '<root>';
- return [`${location}: ${issue.message}`];
- });
+ yield* Schema.decodeUnknown(inputSchema, { errors: 'all' })(args).pipe(
+ Effect.mapError(error => {
+ const issues = ParseResult.ArrayFormatter.formatErrorSync(error).map(
+ issue => issue.message
+ );
+ return new ToolInputValidationError({ toolSlug: slug, schemaPath, issues, cause: error });
+ })
+ );
- return yield* Effect.fail(new ToolInputValidationError(slug, schemaPath, issues));
+ return { schemaPath, schema };
});
export const validateToolInputArgumentsIfCached = (slug: string, args: Record<string, unknown>) =>
diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.ts
index ede32deb9..8a6800561 100644
--- a/ts/packages/cli/src/services/tools-executor.ts
+++ b/ts/packages/cli/src/services/tools-executor.ts
@@ -20,6 +20,7 @@ import type { NodeOs } from 'src/services/node-os';
import type { NodeProcess } from 'src/services/node-process';
import type { ComposioUserContext } from 'src/services/user-context';
import type { ComposioToolkitsRepository } from 'src/services/composio-clients';
+import type { TerminalUI } from 'src/services/terminal-ui';
import { ComposioCliUserConfig } from 'src/services/cli-user-config';
import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
@@ -63,6 +64,7 @@ export interface ToolsExecutor {
| ComposioUserContext
| ComposioToolkitsRepository
| ComposioCliUserConfig
+ | TerminalUI
>;
}
diff --git a/ts/packages/cli/test/src/analytics.events.test.ts b/ts/packages/cli/test/src/analytics.events.test.ts
index 862730f00..8c2d0c27f 100644
--- a/ts/packages/cli/test/src/analytics.events.test.ts
+++ b/ts/packages/cli/test/src/analytics.events.test.ts
@@ -27,9 +27,11 @@ describe('CLI analytics execute failure events', () => {
});
it('marks cached-schema validation failures as fast_fail', () => {
- const error = new ToolInputValidationError('GMAIL_SEND_EMAIL', '/tmp/schema.json', [
- 'Unknown key "recipient"',
- ]);
+ const error = new ToolInputValidationError({
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ schemaPath: '/tmp/schema.json',
+ issues: ['Unknown key "recipient"'],
+ });
const event = getToolExecuteValidationFailedEvent({
toolSlug: 'GMAIL_SEND_EMAIL',
diff --git a/ts/packages/cli/test/src/commands/$default.cmd.test.ts b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
index 877464d80..95114176e 100644
--- a/ts/packages/cli/test/src/commands/$default.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
@@ -138,14 +138,9 @@ describe('CLI: composio', () => {
Effect.gen(function* () {
vi.stubEnv('CODEX_THREAD_ID', 'thread_123');
vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'sdk-ts');
- // The debug command still writes to process.stdout until the
- // seam-rules PR of this stack routes it through TerminalUI.
- const write = vi
- .spyOn(process.stdout, 'write')
- .mockImplementation((() => true) as typeof process.stdout.write);
yield* cli(['debug', 'who-is-my-master']);
- const output = write.mock.calls.map(call => String(call[0])).join('\n');
+ const output = (yield* MockConsole.getLines()).join('\n');
expect(output).toContain('"master": "codex"');
})
diff --git a/ts/packages/cli/test/src/commands/index.test.ts b/ts/packages/cli/test/src/commands/index.test.ts
new file mode 100644
index 000000000..c554eb9be
--- /dev/null
+++ b/ts/packages/cli/test/src/commands/index.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+import { parseExecuteInputHelpSlug } from 'src/commands';
+
+describe('execute input-help routing', () => {
+ it('does not mistake value-taking option values for the slug', () => {
+ expect(
+ parseExecuteInputHelpSlug([
+ 'bun',
+ 'composio',
+ 'execute',
+ '--account',
+ 'default',
+ '--file',
+ './input.txt',
+ 'GMAIL_SEND_EMAIL',
+ '--help',
+ ])
+ ).toBe('GMAIL_SEND_EMAIL');
+ });
+
+ it('does not treat the parallel flag as a value-taking option', () => {
+ expect(
+ parseExecuteInputHelpSlug([
+ 'bun',
+ 'composio',
+ 'execute',
+ '--parallel',
+ 'GMAIL_SEND_EMAIL',
+ '-d',
+ '{}',
+ 'GITHUB_CREATE_AN_ISSUE',
+ '--help',
+ ])
+ ).toBe('GMAIL_SEND_EMAIL');
+ });
+});
diff --git a/ts/packages/cli/test/src/commands/install-skill-root-flag.test.ts b/ts/packages/cli/test/src/commands/install-skill-root-flag.test.ts
index 35a68b807..7213c156c 100644
--- a/ts/packages/cli/test/src/commands/install-skill-root-flag.test.ts
+++ b/ts/packages/cli/test/src/commands/install-skill-root-flag.test.ts
@@ -1,78 +1,98 @@
import { describe, expect, it } from '@effect/vitest';
+import { Effect, Option } from 'effect';
import { parseRootInstallSkillRequest } from 'src/commands';
describe('CLI: --install-skill', () => {
- it('parses the default skill name when only a target is provided', () => {
- expect(
- parseRootInstallSkillRequest(['node', 'composio', '--install-skill', 'claude'])
- ).toEqual({
- _tag: 'parsed',
- target: 'claude',
- });
- });
+ it.effect('parses the default skill name when only a target is provided', () =>
+ Effect.gen(function* () {
+ const request = yield* parseRootInstallSkillRequest([
+ 'node',
+ 'composio',
+ '--install-skill',
+ 'claude',
+ ]);
+ expect(Option.getOrUndefined(request)).toEqual({ target: 'claude' });
+ })
+ );
- it('parses an explicit skill name and target', () => {
- expect(
- parseRootInstallSkillRequest([
+ it.effect('parses an explicit skill name and target', () =>
+ Effect.gen(function* () {
+ const request = yield* parseRootInstallSkillRequest([
'node',
'composio',
'--install-skill',
'composio-cli',
'codex',
- ])
- ).toEqual({
- _tag: 'parsed',
- skillName: 'composio-cli',
- target: 'codex',
- });
- });
+ ]);
+ expect(Option.getOrUndefined(request)).toEqual({
+ skillName: 'composio-cli',
+ target: 'codex',
+ });
+ })
+ );
- it('accepts the legacy --instal-skill alias', () => {
- expect(
- parseRootInstallSkillRequest(['node', 'composio', '--instal-skill', 'openclaw'])
- ).toEqual({
- _tag: 'parsed',
- target: 'openclaw',
- });
- });
+ it.effect('accepts the legacy --instal-skill alias', () =>
+ Effect.gen(function* () {
+ const request = yield* parseRootInstallSkillRequest([
+ 'node',
+ 'composio',
+ '--instal-skill',
+ 'openclaw',
+ ]);
+ expect(Option.getOrUndefined(request)).toEqual({
+ target: 'openclaw',
+ });
+ })
+ );
- it('accepts the root flag after leading global options', () => {
- expect(
- parseRootInstallSkillRequest([
+ it.effect('accepts the root flag after leading global options', () =>
+ Effect.gen(function* () {
+ const request = yield* parseRootInstallSkillRequest([
'node',
'composio',
'--log-level',
'debug',
'--install-skill',
'claude',
- ])
- ).toEqual({
- _tag: 'parsed',
- target: 'claude',
- });
- });
+ ]);
+ expect(Option.getOrUndefined(request)).toEqual({
+ target: 'claude',
+ });
+ })
+ );
- it('does not intercept subcommand flags after a positional command', () => {
- expect(
- parseRootInstallSkillRequest(['node', 'composio', 'upgrade', '--install-skill', 'claude'])
- ).toBeUndefined();
- });
+ it.effect('does not intercept subcommand flags after a positional command', () =>
+ Effect.gen(function* () {
+ const request = yield* parseRootInstallSkillRequest([
+ 'node',
+ 'composio',
+ 'upgrade',
+ '--install-skill',
+ 'claude',
+ ]);
+ expect(Option.isNone(request)).toBe(true);
+ })
+ );
- it('returns a helpful error when the target is missing', () => {
- expect(parseRootInstallSkillRequest(['node', 'composio', '--install-skill'])).toEqual({
- _tag: 'error',
- message:
- 'Missing target for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>',
- });
- });
+ it.effect('returns a helpful error when the target is missing', () =>
+ Effect.gen(function* () {
+ const error = yield* Effect.flip(
+ parseRootInstallSkillRequest(['node', 'composio', '--install-skill'])
+ );
+ expect(error.message).toBe(
+ 'Missing target for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>'
+ );
+ })
+ );
- it('returns a helpful error for invalid targets', () => {
- expect(parseRootInstallSkillRequest(['node', 'composio', '--install-skill', 'cursor'])).toEqual(
- {
- _tag: 'error',
- message:
- 'Invalid target for --install-skill. Expected one of: claude, codex, openclaw.',
- }
- );
- });
+ it.effect('returns a helpful error for invalid targets', () =>
+ Effect.gen(function* () {
+ const error = yield* Effect.flip(
+ parseRootInstallSkillRequest(['node', 'composio', '--install-skill', 'cursor'])
+ );
+ expect(error.message).toBe(
+ 'Invalid target for --install-skill. Expected one of: claude, codex, openclaw.'
+ );
+ })
+ );
});
diff --git a/ts/packages/cli/test/src/services/tool-input-validation.test.ts b/ts/packages/cli/test/src/services/tool-input-validation.test.ts
new file mode 100644
index 000000000..fbb2b540f
--- /dev/null
+++ b/ts/packages/cli/test/src/services/tool-input-validation.test.ts
@@ -0,0 +1,164 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { describe, expect, it } from '@effect/vitest';
+import { BunFileSystem, BunPath } from '@effect/platform-bun';
+import { ConfigProvider, Effect, Layer } from 'effect';
+import * as tempy from 'tempy';
+import {
+ getCachedToolInputDefinition,
+ ToolInputValidationError,
+ validateToolInputArgumentsWithDefinition,
+} from 'src/services/tool-input-validation';
+import { defaultNodeOs, NodeOs } from 'src/services/node-os';
+
+const definition = {
+ schemaPath: '/tmp/GMAIL_SEND_EMAIL.json',
+ schema: {
+ type: 'object',
+ additionalProperties: false,
+ required: ['recipient_email'],
+ properties: {
+ recipient_email: { type: 'string' },
+ subject: { type: 'string' },
+ body: { type: 'string' },
+ },
+ },
+} as const;
+
+describe('tool input validation', () => {
+ it.effect('validates tool input through Effect Schema', () =>
+ Effect.gen(function* () {
+ const result = yield* validateToolInputArgumentsWithDefinition(
+ 'GMAIL_SEND_EMAIL',
+ { recipient_email: '[email protected]', subject: 'Hello' },
+ definition
+ );
+
+ expect(result).toEqual(definition);
+ })
+ );
+
+ it.effect('suggests a schema key using the CLI autocorrect distance', () =>
+ Effect.gen(function* () {
+ const error = yield* validateToolInputArgumentsWithDefinition(
+ 'GMAIL_SEND_EMAIL',
+ { recipent_email: '[email protected]' },
+ definition
+ ).pipe(Effect.flip);
+
+ expect(error).toBeInstanceOf(ToolInputValidationError);
+ expect(error.issues).toContain(
+ '<root>: Unknown key "recipent_email". Use "recipient_email" instead. Allowed top-level keys: recipient_email, subject, body'
+ );
+ })
+ );
+
+ it.effect('keeps prefix-based suggestions without guessing unrelated keys', () =>
+ Effect.gen(function* () {
+ const prefixError = yield* validateToolInputArgumentsWithDefinition(
+ 'GMAIL_SEND_EMAIL',
+ { recipient: '[email protected]' },
+ definition
+ ).pipe(Effect.flip);
+ const unrelatedError = yield* validateToolInputArgumentsWithDefinition(
+ 'GMAIL_SEND_EMAIL',
+ { account: '[email protected]' },
+ definition
+ ).pipe(Effect.flip);
+
+ expect(prefixError.issues).toContain(
+ '<root>: Unknown key "recipient". Use "recipient_email" instead. Allowed top-level keys: recipient_email, subject, body'
+ );
+ expect(unrelatedError.issues).toContain(
+ '<root>: Unknown key "account". Allowed top-level keys: recipient_email, subject, body'
+ );
+ })
+ );
+
+ it.effect(
+ 'keeps length-aware typo suggestions without letting containment bypass the limit',
+ () =>
+ Effect.gen(function* () {
+ const longTypoError = yield* validateToolInputArgumentsWithDefinition(
+ 'GMAIL_SEND_EMAIL',
+ { recpnt_email: '[email protected]' },
+ definition
+ ).pipe(Effect.flip);
+ const containmentError = yield* validateToolInputArgumentsWithDefinition(
+ 'TEST_TOOL',
+ { to: true },
+ {
+ schemaPath: '/tmp/TEST_TOOL.json',
+ schema: {
+ type: 'object',
+ additionalProperties: false,
+ properties: { auto_reply: { type: 'boolean' } },
+ },
+ }
+ ).pipe(Effect.flip);
+
+ expect(longTypoError.issues).toContain(
+ '<root>: Unknown key "recpnt_email". Use "recipient_email" instead. Allowed top-level keys: recipient_email, subject, body'
+ );
+ expect(containmentError.issues).toContain(
+ '<root>: Unknown key "to". Allowed top-level keys: auto_reply'
+ );
+ })
+ );
+
+ it.effect('reads legacy bare-schema cache entries through the Effect decoder', () => {
+ const cacheDir = tempy.temporaryDirectory();
+ const schemaPath = path.join(cacheDir, 'tool_definitions', 'GMAIL_SEND_EMAIL.json');
+ fs.mkdirSync(path.dirname(schemaPath), { recursive: true });
+ fs.writeFileSync(schemaPath, JSON.stringify(definition.schema));
+
+ return Effect.gen(function* () {
+ const cached = yield* getCachedToolInputDefinition('GMAIL_SEND_EMAIL');
+
+ expect(cached).toEqual({
+ schemaPath,
+ schema: definition.schema,
+ version: null,
+ });
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ BunFileSystem.layer,
+ BunPath.layer,
+ Layer.succeed(NodeOs, defaultNodeOs({ homedir: cacheDir }))
+ )
+ ),
+ Effect.withConfigProvider(
+ ConfigProvider.fromMap(new Map([['CACHE_DIR', cacheDir]] satisfies Array<[string, string]>))
+ )
+ );
+ });
+
+ it.effect('preserves field paths in validation errors', () =>
+ Effect.gen(function* () {
+ const error = yield* validateToolInputArgumentsWithDefinition(
+ 'GMAIL_SEND_EMAIL',
+ { recipient_email: 42 },
+ definition
+ ).pipe(Effect.flip);
+
+ expect(error.issues.some(issue => issue.startsWith('recipient_email:'))).toBe(true);
+ })
+ );
+
+ it.effect('preserves all field and unknown-key failures in one validation pass', () =>
+ Effect.gen(function* () {
+ const error = yield* validateToolInputArgumentsWithDefinition(
+ 'GMAIL_SEND_EMAIL',
+ { recipient_email: 42, subject: false, recipent_email: '[email protected]' },
+ definition
+ ).pipe(Effect.flip);
+
+ expect(error.issues.some(issue => issue.startsWith('recipient_email:'))).toBe(true);
+ expect(error.issues.some(issue => issue.startsWith('subject:'))).toBe(true);
+ expect(error.issues).toContain(
+ '<root>: Unknown key "recipent_email". Use "recipient_email" instead. Allowed top-level keys: recipient_email, subject, body'
+ );
+ })
+ );
+});
diff --git a/ts/packages/cli/vitest.config.ts b/ts/packages/cli/vitest.config.ts
index c2f2d03d3..4dfa6a46c 100644
--- a/ts/packages/cli/vitest.config.ts
+++ b/ts/packages/cli/vitest.config.ts
@@ -4,6 +4,7 @@ import path from 'node:path';
const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));
const coreDir = path.resolve(__dirname, '../core');
const tsBuildersDir = path.resolve(__dirname, '../ts-builders');
+const jsonSchemaToEffectSchemaDir = path.resolve(__dirname, '../json-schema-to-effect-schema');
const jsonSchemaToZodDir = path.resolve(__dirname, '../json-schema-to-zod');
const cliLocalToolsDir = path.resolve(__dirname, '../cli-local-tools');
@@ -16,6 +17,10 @@ export default defineConfig({
'@composio/core/experimental': path.join(coreDir, 'src/experimental/index.ts'),
'@composio/core': path.join(coreDir, 'src/index.ts'),
'@composio/ts-builders': path.join(tsBuildersDir, 'src/index.ts'),
+ '@composio/json-schema-to-effect-schema': path.join(
+ jsonSchemaToEffectSchemaDir,
+ 'src/index.ts'
+ ),
'@composio/json-schema-to-zod': path.join(jsonSchemaToZodDir, 'src/index.ts'),
'@composio/cli-local-tools': path.join(cliLocalToolsDir, 'src/index.ts'),
'effect-errors/*': path.resolve(__dirname, './src/effect-errors'),
diff --git a/ts/packages/json-schema-to-effect-schema/README.md b/ts/packages/json-schema-to-effect-schema/README.md
new file mode 100644
index 000000000..0fc14725e
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/README.md
@@ -0,0 +1,7 @@
+# `@composio/json-schema-to-effect-schema`
+
+Internal, eval-free JSON Schema validation exposed through Effect Schema.
+
+The package uses `@cfworker/json-schema`, an interpreter designed for runtimes where dynamic code
+generation is unavailable. It also normalizes the OpenAPI and Composio schema extensions accepted by
+the previous Zod-backed tool-input validator.
diff --git a/ts/packages/json-schema-to-effect-schema/package.json b/ts/packages/json-schema-to-effect-schema/package.json
new file mode 100644
index 000000000..da259f516
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/package.json
@@ -0,0 +1,46 @@
+{
+ "name": "@composio/json-schema-to-effect-schema",
+ "version": "0.1.0",
+ "description": "Eval-free JSON Schema validation exposed as Effect Schema.",
+ "main": "src/index.ts",
+ "private": true,
+ "type": "module",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/ComposioHQ/composio.git",
+ "directory": "ts/packages/json-schema-to-effect-schema"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.mts",
+ "default": "./dist/index.mjs"
+ }
+ },
+ "files": [
+ "README.md",
+ "dist"
+ ],
+ "scripts": {
+ "clean": "git clean -xdf node_modules",
+ "build": "tsdown",
+ "test": "vitest run",
+ "typecheck:src": "pnpm exec tsgo --noEmit -p ./tsconfig.src.json",
+ "typecheck:test": "pnpm exec tsgo --noEmit -p ./tsconfig.test.json",
+ "typecheck": "pnpm run typecheck:src && pnpm run typecheck:test",
+ "typecheck:src:tsc": "tsc --noEmit -p ./tsconfig.src.json",
+ "typecheck:test:tsc": "tsc --noEmit -p ./tsconfig.test.json",
+ "typecheck:tsc": "pnpm run typecheck:src:tsc && pnpm run typecheck:test:tsc"
+ },
+ "license": "ISC",
+ "dependencies": {
+ "@cfworker/json-schema": "^4.1.1",
+ "effect": "catalog:"
+ },
+ "devDependencies": {
+ "@composio/json-schema-to-zod": "workspace:*",
+ "tsdown": "catalog:",
+ "typescript": "catalog:",
+ "vitest": "catalog:",
+ "zod": "catalog:"
+ }
+}
diff --git a/ts/packages/json-schema-to-effect-schema/src/index.ts b/ts/packages/json-schema-to-effect-schema/src/index.ts
new file mode 100644
index 000000000..f599325aa
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/src/index.ts
@@ -0,0 +1,362 @@
+import { Validator } from '@cfworker/json-schema';
+import type { OutputUnit, Schema as InterpreterSchema, SchemaDraft } from '@cfworker/json-schema';
+import { Either, ParseResult, Schema } from 'effect';
+
+export type JsonSchemaValidationIssue = {
+ readonly code: string;
+ readonly keys?: ReadonlyArray<string>;
+ readonly message: string;
+ readonly path: ReadonlyArray<PropertyKey>;
+};
+
+export type JsonSchemaToEffectSchemaOptions = {
+ readonly draft?: SchemaDraft;
+ readonly formatIssues?: (
+ issues: ReadonlyArray<JsonSchemaValidationIssue>
+ ) => ReadonlyArray<string>;
+};
+
+type JsonObject = Record<string, unknown>;
+
+const BASE64_PATTERN = '^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$';
+
+const schemaMapKeywords = new Set([
+ '$defs',
+ 'definitions',
+ 'dependentSchemas',
+ 'patternProperties',
+ 'properties',
+]);
+
+const schemaArrayKeywords = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
+
+const schemaValueKeywords = new Set([
+ 'additionalItems',
+ 'additionalProperties',
+ 'contains',
+ 'else',
+ 'if',
+ 'items',
+ 'not',
+ 'propertyNames',
+ 'then',
+ 'unevaluatedItems',
+ 'unevaluatedProperties',
+]);
+
+const isJsonObject = (value: unknown): value is JsonObject =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const isObjectSchema = (schema: JsonObject): boolean =>
+ schema.type === 'object' ||
+ 'properties' in schema ||
+ 'patternProperties' in schema ||
+ 'additionalProperties' in schema;
+
+const appendAllOf = (schema: JsonObject, constraint: JsonObject): void => {
+ const current = schema.allOf;
+ schema.allOf = Array.isArray(current) ? [...current, constraint] : [constraint];
+};
+
+const normalizeBounds = (schema: JsonObject): void => {
+ const type = schema.type;
+ const minimum = schema.min;
+ const maximum = schema.max;
+
+ if (typeof minimum === 'number') {
+ if ((type === 'number' || type === 'integer') && schema.minimum === undefined) {
+ schema.minimum = minimum;
+ } else if (type === 'string' && schema.minLength === undefined) {
+ schema.minLength = minimum;
+ } else if (type === 'array' && schema.minItems === undefined) {
+ schema.minItems = minimum;
+ }
+ }
+
+ if (typeof maximum === 'number') {
+ if ((type === 'number' || type === 'integer') && schema.maximum === undefined) {
+ schema.maximum = maximum;
+ } else if (type === 'string' && schema.maxLength === undefined) {
+ schema.maxLength = maximum;
+ } else if (type === 'array' && schema.maxItems === undefined) {
+ schema.maxItems = maximum;
+ }
+ }
+};
+
+const normalizeFormats = (schema: JsonObject): void => {
+ if (schema.type === 'number' && schema.format === 'int64') {
+ schema.type = 'integer';
+ }
+
+ if (schema.type !== 'string') {
+ return;
+ }
+
+ if (schema.format === 'binary' || schema.contentEncoding !== undefined) {
+ if (schema.pattern === undefined) {
+ schema.pattern = BASE64_PATTERN;
+ } else {
+ appendAllOf(schema, { pattern: BASE64_PATTERN });
+ }
+ }
+
+ if (schema.format === 'ip') {
+ delete schema.format;
+ appendAllOf(schema, {
+ anyOf: [{ format: 'ipv4' }, { format: 'ipv6' }],
+ });
+ }
+};
+
+const normalizeNullable = (schema: JsonObject): JsonObject => {
+ if (schema.nullable !== true) {
+ return schema;
+ }
+
+ delete schema.nullable;
+ if (typeof schema.type === 'string') {
+ schema.type = [schema.type, 'null'];
+ return schema;
+ }
+ if (Array.isArray(schema.type)) {
+ schema.type = schema.type.includes('null') ? schema.type : [...schema.type, 'null'];
+ return schema;
+ }
+
+ return { anyOf: [schema, { type: 'null' }] };
+};
+
+const normalizeSchemaNode = (
+ value: unknown,
+ seen: WeakMap<object, InterpreterSchema | boolean>
+): InterpreterSchema | boolean => {
+ if (typeof value === 'boolean') {
+ return value;
+ }
+ if (!isJsonObject(value)) {
+ return true;
+ }
+
+ const existing = seen.get(value);
+ if (existing) {
+ return existing;
+ }
+
+ const normalized: JsonObject = {};
+ seen.set(value, normalized as InterpreterSchema);
+
+ for (const [key, child] of Object.entries(value)) {
+ if (schemaMapKeywords.has(key) && isJsonObject(child)) {
+ normalized[key] = Object.fromEntries(
+ Object.entries(child).map(([name, nested]) => [name, normalizeSchemaNode(nested, seen)])
+ );
+ } else if (schemaArrayKeywords.has(key) && Array.isArray(child)) {
+ normalized[key] = child.map(nested => normalizeSchemaNode(nested, seen));
+ } else if (schemaValueKeywords.has(key)) {
+ normalized[key] = Array.isArray(child)
+ ? child.map(nested => normalizeSchemaNode(nested, seen))
+ : normalizeSchemaNode(child, seen);
+ } else {
+ normalized[key] = child;
+ }
+ }
+
+ if (isObjectSchema(normalized) && normalized.additionalProperties === undefined) {
+ normalized.additionalProperties = false;
+ }
+
+ normalizeBounds(normalized);
+ normalizeFormats(normalized);
+ const withNullable = normalizeNullable(normalized);
+ seen.set(value, withNullable as InterpreterSchema);
+ return withNullable as InterpreterSchema;
+};
+
+const normalizeJsonSchema = (schema: JsonObject): InterpreterSchema =>
+ normalizeSchemaNode(schema, new WeakMap()) as InterpreterSchema;
+
+const decodePointer = (pointer: string): ReadonlyArray<string> => {
+ if (pointer === '#' || pointer === '') {
+ return [];
+ }
+
+ const fragment = pointer.startsWith('#') ? pointer.slice(1) : pointer;
+ return fragment
+ .split('/')
+ .slice(1)
+ .map(part => part.replace(/~1/g, '/').replace(/~0/g, '~'));
+};
+
+const encodePointerPart = (part: string): string => part.replace(/~/g, '~0').replace(/\//g, '~1');
+
+const instancePath = (pointer: string): ReadonlyArray<PropertyKey> =>
+ decodePointer(pointer).map(part => (/^(?:0|[1-9]\d*)$/.test(part) ? Number(part) : part));
+
+const valueAtPointer = (root: unknown, pointer: string): unknown =>
+ decodePointer(pointer).reduce<unknown>((current, part) => {
+ if (isJsonObject(current)) {
+ return current[part];
+ }
+ if (Array.isArray(current) && /^(?:0|[1-9]\d*)$/.test(part)) {
+ return current[Number(part)];
+ }
+ return undefined;
+ }, root);
+
+const parentSchemaAtKeyword = (
+ schema: InterpreterSchema,
+ keywordLocation: string
+): JsonObject | null => {
+ const parts = decodePointer(keywordLocation);
+ const parentPointer = `#/${parts.slice(0, -1).map(encodePointerPart).join('/')}`;
+ const parent = valueAtPointer(schema, parts.length === 1 ? '#' : parentPointer);
+ return isJsonObject(parent) ? parent : null;
+};
+
+const propertyNameFromError = (error: OutputUnit): string | undefined =>
+ error.error.match(/^Property "([^"]+)"/)?.[1];
+
+const requiredNameFromError = (error: OutputUnit): string | undefined =>
+ error.error.match(/required property "([^"]+)"/)?.[1];
+
+const propertyIsDeclared = (parent: JsonObject | null, key: string): boolean => {
+ if (!parent) {
+ return false;
+ }
+ if (isJsonObject(parent.properties) && key in parent.properties) {
+ return true;
+ }
+ if (!isJsonObject(parent.patternProperties)) {
+ return false;
+ }
+
+ return Object.keys(parent.patternProperties).some(pattern =>
+ Either.getOrElse(
+ Either.try(() => new RegExp(pattern, 'u').test(key)),
+ () => false
+ )
+ );
+};
+
+const hasSpecificChildError = (errors: ReadonlyArray<OutputUnit>, error: OutputUnit): boolean =>
+ errors.some(
+ candidate =>
+ candidate !== error &&
+ candidate.instanceLocation.startsWith(`${error.instanceLocation}/`) &&
+ candidate.keyword !== 'additionalProperties'
+ );
+
+const mapValidationErrors = (
+ errors: ReadonlyArray<OutputUnit>,
+ schema: InterpreterSchema
+): ReadonlyArray<JsonSchemaValidationIssue> => {
+ const ignored = new Set<OutputUnit>();
+ const unknownByLocation = new Map<string, Array<string>>();
+
+ for (const [index, error] of errors.entries()) {
+ if (error.keyword !== 'additionalProperties') {
+ continue;
+ }
+ const key = propertyNameFromError(error);
+ if (!key) {
+ continue;
+ }
+ const parent = parentSchemaAtKeyword(schema, error.keywordLocation);
+ const additionalProperties = valueAtPointer(schema, error.keywordLocation);
+ if (additionalProperties === false) {
+ const child = errors[index + 1];
+ const childLocation = `${error.instanceLocation}/${encodePointerPart(key)}`;
+ if (child?.keyword === 'false' && child.instanceLocation === childLocation) {
+ ignored.add(child);
+ }
+ }
+ if (propertyIsDeclared(parent, key)) {
+ ignored.add(error);
+ continue;
+ }
+
+ if (additionalProperties === false) {
+ const keys = unknownByLocation.get(error.instanceLocation) ?? [];
+ keys.push(key);
+ unknownByLocation.set(error.instanceLocation, keys);
+ ignored.add(error);
+ } else if (hasSpecificChildError(errors, error)) {
+ ignored.add(error);
+ }
+ }
+
+ const issues: Array<JsonSchemaValidationIssue> = [];
+ for (const [location, keys] of unknownByLocation) {
+ issues.push({
+ code: 'unrecognized_keys',
+ keys,
+ message: `Unknown key${keys.length === 1 ? '' : 's'}: ${keys.join(', ')}`,
+ path: instancePath(location),
+ });
+ }
+
+ for (const error of errors) {
+ if (ignored.has(error)) {
+ continue;
+ }
+ if (
+ (error.keyword === 'properties' ||
+ error.keyword === 'patternProperties' ||
+ error.keyword === '$ref') &&
+ hasSpecificChildError(errors, error)
+ ) {
+ continue;
+ }
+
+ const path = [...instancePath(error.instanceLocation)];
+ const requiredName = error.keyword === 'required' ? requiredNameFromError(error) : undefined;
+ if (requiredName) {
+ path.push(requiredName);
+ }
+ issues.push({ code: error.keyword, message: error.error, path });
+ }
+
+ return issues;
+};
+
+const defaultFormatIssues = (
+ issues: ReadonlyArray<JsonSchemaValidationIssue>
+): ReadonlyArray<string> =>
+ issues.map(issue => {
+ const location = issue.path.length > 0 ? issue.path.join('.') : '<root>';
+ return `${location}: ${issue.message}`;
+ });
+
+export const jsonSchemaToEffectSchema = (
+ jsonSchema: JsonObject,
+ options: JsonSchemaToEffectSchemaOptions = {}
+) => {
+ const normalizedSchema = normalizeJsonSchema(jsonSchema);
+ const validator = new Validator(normalizedSchema, options.draft ?? '7', false);
+ const formatIssues = options.formatIssues ?? defaultFormatIssues;
+
+ return Schema.declare([Schema.Unknown], {
+ decode: () => (input, _parseOptions, ast) => {
+ const validation = Either.try(() => validator.validate(input));
+ if (Either.isLeft(validation)) {
+ return ParseResult.fail(
+ new ParseResult.Type(ast, input, `JSON Schema validation failed: ${validation.left}`)
+ );
+ }
+ if (validation.right.valid) {
+ return ParseResult.succeed(input);
+ }
+
+ const issues = mapValidationErrors(validation.right.errors, normalizedSchema);
+ const messages = formatIssues(issues);
+ const [first, ...rest] = messages.map(message => new ParseResult.Type(ast, input, message));
+ return ParseResult.fail(
+ first
+ ? new ParseResult.Composite(ast, input, [first, ...rest])
+ : new ParseResult.Type(ast, input, 'Input does not match the JSON schema.')
+ );
+ },
+ encode: () => input => ParseResult.succeed(input),
+ });
+};
diff --git a/ts/packages/json-schema-to-effect-schema/test/json-schema-to-effect-schema.test.ts b/ts/packages/json-schema-to-effect-schema/test/json-schema-to-effect-schema.test.ts
new file mode 100644
index 000000000..48b1e1a62
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/test/json-schema-to-effect-schema.test.ts
@@ -0,0 +1,118 @@
+import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
+import { Either, Schema } from 'effect';
+import { describe, expect, it } from 'vitest';
+import { jsonSchemaToEffectSchema, type JsonSchemaValidationIssue } from '../src/index';
+
+type JsonSchema = Record<string, unknown>;
+
+const effectAccepts = (schema: JsonSchema, input: unknown): boolean =>
+ Either.isRight(
+ Schema.decodeUnknownEither(jsonSchemaToEffectSchema(schema), { errors: 'all' })(input)
+ );
+
+const zodAccepts = (schema: JsonSchema, input: unknown): boolean =>
+ jsonSchemaToZod(schema).safeParse(input).success;
+
+const expectParity = (schema: JsonSchema, input: unknown, expected: boolean): void => {
+ expect(effectAccepts(schema, input)).toBe(expected);
+ expect(zodAccepts(schema, input)).toBe(expected);
+};
+
+describe('jsonSchemaToEffectSchema', () => {
+ it('matches the previous validator for object, required, and additional-property checks', () => {
+ const strictSchema = {
+ type: 'object',
+ required: ['name'],
+ properties: {
+ name: { type: 'string' },
+ metadata: {
+ type: 'object',
+ properties: { count: { type: 'integer' } },
+ },
+ },
+ } satisfies JsonSchema;
+
+ expectParity(strictSchema, { name: 'Ada', metadata: { count: 1 } }, true);
+ expectParity(strictSchema, { name: 'Ada', extra: true }, false);
+ expectParity(strictSchema, { name: 'Ada', metadata: { count: 1.5 } }, false);
+ expectParity(strictSchema, { metadata: { count: 1 } }, false);
+
+ expectParity({ type: 'object', additionalProperties: true }, { arbitrary: 'value' }, true);
+ });
+
+ it('normalizes the OpenAPI and Composio extensions accepted by the previous validator', () => {
+ expectParity({ type: 'string', nullable: true }, null, true);
+ expectParity({ type: 'string', nullable: true }, 42, false);
+ expectParity({ type: 'string', min: 2, max: 4 }, 'abc', true);
+ expectParity({ type: 'string', min: 2, max: 4 }, 'a', false);
+ expectParity({ type: 'array', min: 1, max: 2, items: { type: 'number' } }, [1], true);
+ expectParity({ type: 'array', min: 1, max: 2, items: { type: 'number' } }, [], false);
+ expectParity({ type: 'number', format: 'int64' }, 42, true);
+ expectParity({ type: 'number', format: 'int64' }, 4.2, false);
+ expectParity({ type: 'string', format: 'binary' }, 'aGVsbG8=', true);
+ expectParity({ type: 'string', format: 'binary' }, 'not base64', false);
+ expectParity({ type: 'string', format: 'ip' }, '127.0.0.1', true);
+ expectParity({ type: 'string', format: 'ip' }, 'not-an-ip', false);
+ });
+
+ it('supports JSON Schema composition without generated code', () => {
+ const schema = {
+ type: 'object',
+ additionalProperties: false,
+ required: ['value'],
+ properties: {
+ value: {
+ anyOf: [
+ { type: 'string', minLength: 1 },
+ { type: 'integer', minimum: 1 },
+ ],
+ },
+ },
+ } satisfies JsonSchema;
+
+ expect(effectAccepts(schema, { value: 'ready' })).toBe(true);
+ expect(effectAccepts(schema, { value: 2 })).toBe(true);
+ expect(effectAccepts(schema, { value: 0 })).toBe(false);
+ expect(effectAccepts(schema, { value: false })).toBe(false);
+ });
+
+ it('reports all failures with field paths and groups unknown keys', () => {
+ const schema = {
+ type: 'object',
+ additionalProperties: false,
+ required: ['email', 'profile'],
+ properties: {
+ email: { type: 'string' },
+ profile: {
+ type: 'object',
+ additionalProperties: false,
+ required: ['age'],
+ properties: { age: { type: 'integer' } },
+ },
+ },
+ } satisfies JsonSchema;
+ let captured: ReadonlyArray<JsonSchemaValidationIssue> = [];
+ const effectSchema = jsonSchemaToEffectSchema(schema, {
+ formatIssues: issues => {
+ captured = issues;
+ return issues.map(issue => issue.message);
+ },
+ });
+
+ const result = Schema.decodeUnknownEither(effectSchema, { errors: 'all' })({
+ email: 42,
+ profile: { age: 'old', extra: true },
+ typo: true,
+ });
+
+ expect(Either.isLeft(result)).toBe(true);
+ expect(captured).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ code: 'type', path: ['email'] }),
+ expect.objectContaining({ code: 'type', path: ['profile', 'age'] }),
+ expect.objectContaining({ code: 'unrecognized_keys', keys: ['extra'], path: ['profile'] }),
+ expect.objectContaining({ code: 'unrecognized_keys', keys: ['typo'], path: [] }),
+ ])
+ );
+ });
+});
diff --git a/ts/packages/json-schema-to-effect-schema/tsconfig.json b/ts/packages/json-schema-to-effect-schema/tsconfig.json
new file mode 100644
index 000000000..92abc2696
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./tsconfig.options.json",
+ "compilerOptions": {
+ "rootDir": "."
+ },
+ "include": ["src/**/*", "test/**/*", "package.json"]
+}
diff --git a/ts/packages/json-schema-to-effect-schema/tsconfig.options.json b/ts/packages/json-schema-to-effect-schema/tsconfig.options.json
new file mode 100644
index 000000000..b133b708c
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/tsconfig.options.json
@@ -0,0 +1,22 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "compilerOptions": {
+ "target": "es2022",
+ "module": "es2022",
+ "lib": ["es2022", "DOM"],
+ "declaration": true,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "strict": true,
+ "esModuleInterop": true,
+ "moduleResolution": "bundler",
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "pretty": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUnusedLocals": false,
+ "noUnusedParameters": false
+ },
+ "exclude": ["node_modules", "**/dist"]
+}
diff --git a/ts/packages/json-schema-to-effect-schema/tsconfig.src.json b/ts/packages/json-schema-to-effect-schema/tsconfig.src.json
new file mode 100644
index 000000000..dee0c0af3
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/tsconfig.src.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./tsconfig.options.json",
+ "compilerOptions": {
+ "outDir": "./dist",
+ "rootDir": "."
+ },
+ "include": ["src/**/*", "package.json"],
+ "exclude": ["node_modules", "../../../node_modules", "**/dist"]
+}
diff --git a/ts/packages/json-schema-to-effect-schema/tsconfig.test.json b/ts/packages/json-schema-to-effect-schema/tsconfig.test.json
new file mode 100644
index 000000000..972d895b7
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/tsconfig.test.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./tsconfig.options.json",
+ "compilerOptions": {
+ "rootDir": "."
+ },
+ "include": ["src/**/*", "test/**/*", "package.json"],
+ "exclude": ["node_modules", "../../../node_modules", "**/dist"]
+}
diff --git a/ts/packages/json-schema-to-effect-schema/tsdown.config.ts b/ts/packages/json-schema-to-effect-schema/tsdown.config.ts
new file mode 100644
index 000000000..645615ccd
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/tsdown.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'tsdown';
+import { baseConfig, baseNeverBundle } from '../../../tsdown.config.base.ts';
+
+export default defineConfig({
+ ...baseConfig,
+ tsconfig: 'tsconfig.src.json',
+ deps: {
+ neverBundle: [...baseNeverBundle, '@cfworker/json-schema', 'effect'],
+ onlyBundle: false,
+ },
+});
diff --git a/ts/packages/json-schema-to-effect-schema/vitest.config.ts b/ts/packages/json-schema-to-effect-schema/vitest.config.ts
new file mode 100644
index 000000000..cefc5da85
--- /dev/null
+++ b/ts/packages/json-schema-to-effect-schema/vitest.config.ts
@@ -0,0 +1,18 @@
+import { defineConfig } from 'vitest/config';
+import path from 'node:path';
+
+const packageDir = path.resolve(path.dirname(new URL(import.meta.url).pathname));
+
+export default defineConfig({
+ resolve: {
+ alias: {
+ '@composio/json-schema-to-zod': path.resolve(
+ packageDir,
+ '../json-schema-to-zod/src/index.ts'
+ ),
+ },
+ },
+ test: {
+ exclude: ['**/node_modules/**', '**/dist/**'],
+ },
+});