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.

67.2 KB
Raw Blame
import { Effect, Option } from 'effect';
import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
import { TerminalUI } from 'src/services/terminal-ui';
import { bold, dim, gray } from 'src/ui/colors';
import {
  type CommandVisibility,
  experimental,
  type HelpLevel,
  full,
  isTaggedValueVisible,
  isTaggedValueVisibleForHelpLevel,
  simple,
  tagged,
  visibleValues,
  type TaggedValue,
} from './feature-tags';

type DetailedCommand = {
  name: string;
  description: string;
  usage: string;
  options?: ReadonlyArray<{ name: string; description: string }>;
};

type CompactCommand = {
  name: string;
  description: string;
};

// ── Core workflow commands ──────────────────────────────────────────────

const CORE_COMMANDS: ReadonlyArray<TaggedValue<DetailedCommand>> = [
  simple({
    name: 'search',
    description: 'Find tools by use case across all toolkits/apps.',
    usage: 'search <query...> [--toolkits text] [--limit integer] [--human]',
    options: [
      {
        name: '<query...>',
        description: 'One or more semantic use-case queries (e.g. "send emails" "github issues")',
      },
      { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },
      { name: '--limit', description: 'Maximum number of results (1-1000)' },
      { name: '--human', description: 'Show formatted output instead of default JSON' },
    ],
  }),
  simple({
    name: 'execute',
    description:
      'Execute a tool. Validates inputs and connections automatically; use it aggressively.',
    usage:
      'execute <slug> [-d, --data text] [--account selector] [--file path] [--dry-run] [--get-schema] | execute -p <slug> -d <text> <slug> -d <text> ...',
    options: [
      { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },
      {
        name: '-d, --data',
        description:
          'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
      },
      {
        name: '-p, --parallel',
        description: 'Execute repeated <slug> -d <text> pairs concurrently',
      },
      {
        name: '--account',
        description: 'Select a connected account by alias, word_id, or account ID',
      },
      {
        name: '--file',
        description: 'Inject a local file path into the single file_uploadable input',
      },
      { name: '--dry-run', description: 'Validate and preview the tool call without executing it' },
      { name: '--get-schema', description: 'Fetch and print the CLI-facing input schema' },
    ],
  }),
  simple({
    name: 'link',
    description: 'Connect your account for a toolkit/app.',
    usage: 'link [<toolkit>] [--alias text]',
    options: [
      { name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' },
      { name: '--alias', description: 'Alias for this connected account' },
    ],
  }),
  tagged({
    name: 'run',
    description:
      'Run inline TS/JS code with shimmed CLI commands; injected execute(), search(), proxy(), experimental_subAgent(), and z (zod).',
    usage: 'run <code> [-- ...args] | run [-f, --file text] [-- ...args] [--dry-run]',
    options: [
      { name: '<code>', description: 'Inline Bun ESNext code to evaluate' },
      { name: '-f, --file', description: 'Run a TS/JS file instead of inline code' },
      { name: '--dry-run', description: 'Preview execute() calls without running remote actions' },
    ],
  }),
  experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, {
    name: 'listen',
    description:
      'Create a temporary subscription for consumer-project events and persist each payload into the session artifact folder.',
    usage:
      'listen <slug> [-p, --params text] [--account selector] [--max-events integer] [--timeout text] [--stream [text]]',
    options: [
      { name: '<slug>', description: 'Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")' },
      {
        name: '-p, --params',
        description:
          "Trigger create params as JSON or JS-style object, e.g. -p '{ trigger_config: { ... } }'.",
      },
      {
        name: '--account',
        description: 'Select a connected account by alias, word_id, or account ID',
      },
      {
        name: '--max-events',
        description: 'Stop after receiving N events, then disable the temporary trigger',
      },
      {
        name: '--timeout',
        description:
          'Stop after a duration such as 30s, 5m, or 1hr, then disable the temporary trigger',
      },
      {
        name: '--stream',
        description:
          'Also print each payload inline as a single-line stream value. Optionally pass a jq-like path such as ".thread.id".',
      },
    ],
  }),
  tagged({
    name: 'proxy',
    description:
      'curl-like access to any toolkit API through Composio using your connected account.',
    usage: 'proxy <url> --toolkit text [--account selector] [-X method] [-H header]... [-d data]',
    options: [
      { name: '<url>', description: 'Full API endpoint URL' },
      { name: '--toolkit', description: 'Toolkit slug whose connected account should be used' },
      { name: '--account', description: 'Connected account alias, word_id, or account ID' },
      { name: '-X, --method', description: 'HTTP method (GET, POST, PUT, DELETE, PATCH)' },
      { name: '-H, --header', description: 'Header in "Name: value" format. Repeat for multiple.' },
      { name: '-d, --data', description: 'Request body as raw text, JSON, @file, or - for stdin' },
    ],
  }),
];

// ── Developer commands ─────────────────────────────────────────────────

const OTHER_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
  tagged({
    name: 'composio tools info <slug>',
    description: 'Print tool summary and cache its schema',
  }),
  tagged({
    name: 'composio tools list <toolkit>',
    description: 'List tools available in a toolkit',
  }),
  tagged({
    name: 'composio triggers info <slug>',
    description: 'Print trigger type details and schema summaries',
  }),
  tagged({
    name: 'composio triggers list <toolkit>',
    description: 'List available trigger types in a toolkit',
  }),
  tagged({
    name: 'composio artifacts cwd',
    description: 'Print the cwd-scoped session artifact directory',
  }),
];

const GENERATE_COMMAND: TaggedValue<CompactCommand> = tagged({
  name: 'generate',
  description: 'Generate type stubs for toolkits, tools, and triggers (TypeScript | Python).',
});

// ── Account commands ───────────────────────────────────────────────────

const ACCOUNT_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
  tagged({ name: 'setup', description: 'Install or uninstall agent plugins' }),
  tagged({ name: 'login', description: 'Log in to Composio' }),
  tagged({ name: 'logout', description: 'Log out from Composio' }),
  tagged({ name: 'whoami', description: 'Show current account info' }),
  tagged({ name: 'orgs', description: 'Manage current organization context (list, switch)' }),
  tagged({ name: 'version', description: 'Display CLI version' }),
  tagged({ name: 'upgrade', description: 'Upgrade CLI to the latest version' }),
  tagged({ name: 'config', description: 'View and manage CLI configuration' }),
];

const FULL_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
  full({
    name: 'files',
    description: 'Show where CLI config, cache, and session artifacts live',
  }),
  full({ name: 'tools list', description: 'List tools for a toolkit with query/tag filters' }),
  full({ name: 'tools info', description: 'Inspect a tool summary and cached schema details' }),
  full({ name: 'triggers list', description: 'List trigger types for a toolkit' }),
  full({ name: 'triggers info', description: 'Inspect a trigger type and schema summary' }),
  full({ name: 'connections list', description: 'Print toolkit connection statuses as JSON' }),
  full({ name: 'connections remove', description: 'Interactively remove a toolkit connection' }),
  full({ name: 'local-tools list', description: 'List registered local CLI toolkits and tools' }, [
    CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
  ]),
  full(
    {
      name: 'local-tools doctor',
      description: 'Check local toolkit readiness and setup hints',
    },
    [CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]
  ),
  full(
    {
      name: 'local-tools configure',
      description: 'Set local toolkit/tool metadata overrides',
    },
    [CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]
  ),
  full({ name: 'local-tools meta', description: 'Inspect or initialize local tools metadata' }, [
    CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
  ]),
  full({ name: 'generate ts', description: 'Generate TypeScript stubs for selected toolkits' }),
  full({ name: 'generate py', description: 'Generate Python stubs for selected toolkits' }),
  full({
    name: 'dev init',
    description: 'Initialize a developer project in the current directory',
  }),
  full({
    name: 'dev playground-execute',
    description: 'Execute tools against developer playground users and auth configs',
  }),
  full({
    name: 'dev listen',
    description: 'Stream developer-project realtime trigger events with optional forwarding',
  }),
];

// ── Render helpers ─────────────────────────────────────────────────────

function renderDetailedCommands(name: string, commands: ReadonlyArray<DetailedCommand>): string[] {
  const lines: string[] = [];
  for (const cmd of commands) {
    lines.push(`  ${bold(cmd.name)}`);
    lines.push(`    ${cmd.description}`);
    lines.push(`    ${dim('Usage:')} ${name} ${cmd.usage}`);
    if (cmd.options && cmd.options.length > 0) {
      for (const opt of cmd.options) {
        lines.push(`      ${dim(opt.name.padEnd(20))}${opt.description}`);
      }
    }
    lines.push('');
  }
  return lines;
}

function renderCompactCommands(commands: ReadonlyArray<CompactCommand>): string[] {
  const maxLen = Math.max(...commands.map(c => c.name.length));
  return commands.map(cmd => `  ${cmd.name.padEnd(maxLen + 2)}${cmd.description}`);
}

function renderDevHelp(visibility: CommandVisibility, helpLevel: HelpLevel = 'default'): string {
  const lines: string[] = [
    '',
    bold('USAGE'),
    visibility.isDevModeEnabled
      ? '  composio dev [--mode on|off] <command> [options]'
      : '  composio dev [--mode on|off]',
    '',
    bold('DESCRIPTION'),
    visibility.isDevModeEnabled
      ? '  Developer workflows for local project setup, playground execution, logs, and developer-scoped management.'
      : '  Developer mode is off. Only mode switching is available until you turn it back on.',
    '',
    bold('MODE'),
    '  --mode <on|off>         Turn developer mode on or off.',
    '',
  ];

  if (!visibility.isDevModeEnabled) {
    if (helpLevel !== 'simple') {
      lines.push(bold('EXAMPLES'));
      lines.push('  composio dev --mode on');
      lines.push('  composio dev --mode off');
      lines.push('');
      lines.push(bold('NOTE'));
      lines.push(
        '  Developer mode is for engineers building with the CLI. It unlocks more advanced commands like creating or updating auth configs and connected accounts.'
      );
      lines.push('');
    }
    return lines.join('\n');
  }

  lines.push(bold('PROJECT'));
  lines.push('  dev init                 Initialize this directory with a developer project');
  lines.push('');

  lines.push(bold('EXECUTION'));
  lines.push('  dev playground-execute   Execute a tool against a developer playground user');
  lines.push('  dev listen               Listen to developer-project trigger events');
  lines.push('  dev logs tools           Browse tool logs');
  lines.push('  dev logs triggers        Browse trigger logs');
  lines.push('');

  lines.push(bold('TOOLKITS'));
  lines.push('  dev toolkits list        Browse available toolkits');
  lines.push('  dev toolkits info        Inspect a toolkit');
  lines.push('  dev toolkits search      Search toolkits');
  lines.push('  dev toolkits version     Inspect toolkit versions');
  lines.push('');

  lines.push(bold('AUTH CONFIGS'));
  lines.push('  dev auth-configs list    List auth configs');
  lines.push('  dev auth-configs info    View one auth config');
  lines.push('  dev auth-configs create  Create an auth config');
  lines.push('');

  lines.push(bold('CONNECTED ACCOUNTS'));
  lines.push('  dev connected-accounts link   Link a connected account');
  lines.push('  dev connected-accounts list   List connected accounts');
  lines.push('  dev connected-accounts info   View one connected account');
  lines.push('  dev connected-accounts whoami Resolve an account identity');
  lines.push('');

  lines.push(bold('TRIGGERS'));
  lines.push('  dev triggers list        List trigger types');
  lines.push('  dev triggers info        View one trigger type');
  lines.push('  dev triggers status      Inspect trigger instances');
  lines.push('  dev triggers create      Create a trigger instance');
  lines.push('  dev triggers enable      Enable a trigger instance');
  lines.push('  dev triggers disable     Disable a trigger instance [guarded]');
  lines.push('');

  lines.push(bold('PROJECTS'));
  lines.push('  dev projects list        List projects');
  lines.push('  dev projects switch      Switch default project');
  lines.push('');

  lines.push(bold('GUARDED'));
  lines.push('  dev triggers disable     Disable a trigger instance');
  lines.push(
    '  This requires `developer.destructive_actions: true` in `~/.composio/config.json` and `--dangerously-allow` on the command line.'
  );
  lines.push('');
  if (helpLevel !== 'simple') {
    lines.push(bold('EXAMPLES'));
    lines.push('  composio dev --mode off');
    lines.push('  composio dev toolkits list');
    lines.push(
      '  composio dev playground-execute GMAIL_SEND_EMAIL --dangerously-allow -d \'{ recipient_email: "[email protected]" }\''
    );
    lines.push('');
  }
  return lines.join('\n');
}
export const HELP_LEVELS = [
  'simple',
  'default',
  'full',
] as const satisfies ReadonlyArray<HelpLevel>;

export const parseHelpLevel = (token: string | undefined): HelpLevel | undefined => {
  if (!token) {
    return undefined;
  }
  if (token === 'verbose') {
    return 'full';
  }
  return HELP_LEVELS.find(level => level === token);
};

const splitTrailingHelpLevel = (
  args: ReadonlyArray<string>
): { args: ReadonlyArray<string>; helpLevel: HelpLevel } => {
  const trailingLevel = parseHelpLevel(args[args.length - 1]);
  if (!trailingLevel) {
    return { args, helpLevel: 'default' };
  }

  return {
    args: args.slice(0, -1),
    helpLevel: trailingLevel,
  };
};

// ── Subcommand help definitions ────────────────────────────────────────

type SubcommandHelp = {
  usage: string;
  description: string;
  args?: ReadonlyArray<{ name: string; description: string }>;
  options?: ReadonlyArray<{ name: string; description: string }>;
  flags?: ReadonlyArray<{ name: string; description: string }>;
  injectedHelpers?: ReadonlyArray<{ name: string; description: string }>;
  examples?: ReadonlyArray<string>;
  seeAlso?: ReadonlyArray<string>;
};

const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHelp>> = {
  search: {
    usage: 'composio search <query...> [--toolkits text] [--limit integer] [--human]',
    description:
      'Find tools by use case. Defaults to JSON output; use --human for formatted output.',
    args: [
      {
        name: '<query...>',
        description:
          'One or more semantic use-case queries (e.g. "send an email", "create github issue")',
      },
    ],
    options: [
      { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
      { name: '--limit <integer>', description: 'Maximum number of results (1-1000)' },
      { name: '--human', description: 'Show formatted human-readable search output' },
    ],
    examples: [
      '# Find tools for a use case',
      'composio search "send an email"',
      'composio search "send an email" "create github issue"',
      'composio search "my emails" "my github issues" --toolkits gmail,github',
      'composio search "create issue" --toolkits github',
      'composio search "send an email" --human',
      '',
      '# Cross-app workflow discovery',
      'composio search "post a message to a slack channel"',
      'composio search "add a row to google sheet"',
      '',
      '# Narrow results to a specific toolkit',
      'composio search "list calendar events" --toolkits google_calendar --limit 5',
    ],
    seeAlso: [
      "composio execute <slug> -d '{ ... }'    Run a tool from the results",
      "composio tools info <slug>               Inspect a tool's full schema",
      'composio link <toolkit>                  Connect an account if execute tells you to',
    ],
  },
  execute: {
    usage:
      'composio execute <slug> [-d, --data text] [--account selector] [--file path] [--dry-run] [--get-schema] [--parallel]',
    description:
      'Execute a tool by slug. Validates inputs against cached schemas and checks connections automatically — just try it and it will tell you what to fix.',
    args: [
      {
        name: '<slug>',
        description:
          'Tool slug for single execute, or repeated <slug> -d <text> pairs when using -p/--parallel',
      },
    ],
    options: [
      {
        name: '-d, --data <text>',
        description:
          'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
      },
      {
        name: '-p, --parallel',
        description: 'Execute repeated TOOL_SLUG -d <text> groups concurrently',
      },
      {
        name: '--account <selector>',
        description: 'Select a connected account by alias, word_id, or connected account ID',
      },
      {
        name: '--file <path>',
        description: 'Inject a local file path into the single file_uploadable input',
      },
      {
        name: '--get-schema',
        description: 'Fetch and print the CLI-facing input schema without executing',
      },
      {
        name: '--dry-run',
        description: 'Validate and preview the tool call without executing',
      },
    ],
    flags: [
      { name: '--skip-connection-check', description: 'Skip the connected-account check' },
      {
        name: '--skip-tool-params-check',
        description: 'Skip input validation against cached schema',
      },
      { name: '--skip-checks', description: 'Skip both checks above' },
    ],
    examples: [
      '# Send an email',
      `composio execute GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]", subject: "Hello", body: "World" }'`,
      '',
      '# Create a GitHub issue with a named account',
      `composio execute GITHUB_CREATE_ISSUE --account work -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'`,
      '',
      '# Preview what a tool call would send without executing',
      `composio execute SLACK_SEND_A_MESSAGE_TO_A_SLACK_CHANNEL --dry-run -d '{ channel: "general", text: "Hello team" }'`,
      '',
      '# Check what inputs a tool needs',
      'composio execute GMAIL_SEND_EMAIL --get-schema',
      '',
      '# Read arguments from a file',
      'composio execute GITHUB_CREATE_ISSUE -d @issue.json',
      '',
      '# Execute multiple tools concurrently',
      `composio execute -p GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]" }' GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
    ],
    seeAlso: [
      'composio search "<query>"               Find tool slugs by use case',
      'composio tools info <slug>              Schema summary with jq hints',
      'composio link <toolkit>                 Connect an account for a toolkit',
      'composio artifacts cwd                  Print the current session artifact directory',
    ],
  },
  listen: experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, {
    usage:
      'composio listen <slug> [-p, --params text] [--account selector] [--max-events integer] [--timeout text] [--stream [text]]',
    description:
      'Create a temporary subscription for consumer-project events so background agents can easily consume new emails, Slack messages, and other trigger payloads from artifacts.',
    args: [{ name: '<slug>', description: 'Trigger slug to create and listen to' }],
    options: [
      {
        name: '-p, --params <text>',
        description:
          'Trigger create params as JSON/JS object, @file, or - for stdin. Pass optional trigger config fields only.',
      },
      {
        name: '--account <selector>',
        description: 'Select a connected account by alias, word_id, or connected account ID',
      },
      {
        name: '--max-events <integer>',
        description: 'Stop after N events for this temporary trigger and disable it',
      },
      {
        name: '--timeout <text>',
        description: 'Stop after a duration such as "30s", "5m", or "1hr" and disable the trigger',
      },
      {
        name: '--stream [text]',
        description:
          'Also print each event payload inline. Optionally pass a jq-like path such as ".thread.id" or ".data[0].id".',
      },
    ],
    examples: [
      'composio listen GMAIL_NEW_GMAIL_MESSAGE',
      'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5',
      'composio listen GMAIL_NEW_GMAIL_MESSAGE --account work --timeout 5m',
      "composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 1hr --stream '.data.threadId'",
      'composio listen SLACK_RECEIVE_MESSAGE -p \'{ trigger_config: { channel: "C123" } }\'',
      'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream',
      "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
    ],
    seeAlso: [
      'composio artifacts cwd                   Print the current session artifact directory',
      'composio triggers info <slug>            Inspect trigger type details before listening',
      'composio link <toolkit>                  Connect the required account before creating the trigger',
    ],
  }),
  link: {
    usage: 'composio link [<toolkit>] [--no-wait] [--no-browser] [--alias text] [--list]',
    description:
      'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf. Opens a browser for OAuth authorization and waits for confirmation.',
    args: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],
    options: [
      {
        name: '--alias <text>',
        description:
          'Alias for the connected account. Required when creating an additional account for the same toolkit',
      },
    ],
    flags: [
      {
        name: '--no-wait',
        description: 'Print link info and exit without waiting for authorization',
      },
      {
        name: '--no-browser',
        description: 'Do not open the browser automatically; print the URL to open manually',
      },
      {
        name: '--list',
        description:
          'List existing connected accounts for the toolkit instead of creating a new link',
      },
    ],
    examples: [
      'composio link github',
      'composio link gmail --alias work',
      'composio link github --list',
    ],
    seeAlso: [
      'composio search "<query>"               Find tools to use after linking',
      "composio execute <slug> --account <alias> -d '{ ... }'   Use a named account",
      'composio connections list --toolkit <toolkit>              List account selectors',
    ],
  },
  'connections list': {
    usage: 'composio connections list [--toolkit <text>]',
    description:
      'Print connected toolkit statuses as JSON. Adds aliases when a toolkit has multiple connections.',
    options: [{ name: '--toolkit <text>', description: 'Filter to a single toolkit slug' }],
    examples: ['composio connections list', 'composio connections list --toolkit gmail'],
    seeAlso: [
      'composio link <toolkit>                 Connect a new account for a toolkit',
      'composio dev connected-accounts list    Inspect the full connected-account table',
    ],
  },
  'connections remove': {
    usage: 'composio connections remove <account>',
    description:
      'Interactively remove a connected toolkit account. The command prompts for confirmation and defaults to No.',
    args: [
      {
        name: '<account>',
        description: 'Toolkit slug, alias, word_id, or connected account ID',
      },
    ],
    examples: [
      'composio connections remove gmail',
      'composio connections remove work',
      'composio connections remove castle',
    ],
    seeAlso: [
      'composio connections list                Find connection selectors',
      'composio link <toolkit>                  Reconnect a toolkit account',
    ],
  },
  'local-tools': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
    usage: 'composio local-tools <list|doctor|configure|meta>',
    description:
      'Inspect local CLI tools that the Tool Router can search and execute alongside hosted Composio tools.',
    examples: [
      'composio local-tools list',
      'composio local-tools doctor',
      'composio local-tools configure <toolkit> --command /path/to/tool',
    ],
    seeAlso: [
      'composio local-tools doctor            Check installed local tool readiness',
      'composio local-tools meta --init       Initialize local tools metadata',
    ],
  }),
  'local-tools list': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
    usage: 'composio local-tools list [--json] [--all-platforms] [--toolkits <text>]',
    description:
      'List registered local toolkits and the exact LOCAL_* tool slugs exposed to Tool Router.',
    options: [
      { name: '--json', description: 'Print structured declarations' },
      {
        name: '--all-platforms',
        description: 'Include unsupported toolkits for the current platform',
      },
      { name: '--toolkits <text>', description: 'Comma-separated local toolkit slug filter' },
    ],
    examples: [
      'composio local-tools list',
      'composio local-tools list --json',
      'composio local-tools list --toolkits <toolkit> --all-platforms',
    ],
    seeAlso: ['composio local-tools meta              Inspect local metadata state'],
  }),
  'local-tools doctor': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
    usage: 'composio local-tools doctor [--json] [--all-platforms] [--toolkits <text>] [--strict]',
    description:
      'Check command availability, platform support, and setup hints for registered local toolkits.',
    options: [
      { name: '--json', description: 'Print structured readiness report' },
      {
        name: '--all-platforms',
        description: 'Include unsupported toolkits for the current platform',
      },
      { name: '--toolkits <text>', description: 'Comma-separated local toolkit slug filter' },
      { name: '--strict', description: 'Exit non-zero if any visible local tool is not ready' },
    ],
    examples: [
      'composio local-tools doctor',
      'composio local-tools doctor --json',
      'composio local-tools doctor --toolkits <toolkit> --strict',
    ],
    seeAlso: ['composio local-tools meta              Inspect local metadata state'],
  }),
  'local-tools configure': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
    usage:
      'composio local-tools configure <selector> [--command <text>] [--enable|--disable] [--authenticated|--unauthenticated] [--json]',
    description:
      'Configure ~/composio/local_tools.json for a local toolkit slug or LOCAL_* tool slug without hand-editing JSON.',
    args: [
      {
        name: '<selector>',
        description: 'Local toolkit slug or LOCAL_* tool slug',
      },
    ],
    options: [
      { name: '--command <text>', description: 'Override the local binary/launcher command' },
      { name: '--json', description: 'Print the updated metadata entry as JSON' },
    ],
    flags: [
      { name: '--enable', description: 'Clear disabled state' },
      { name: '--disable', description: 'Disable this local toolkit/tool' },
      { name: '--authenticated', description: 'Mark this local toolkit/tool authenticated' },
      { name: '--unauthenticated', description: 'Mark this local toolkit/tool unauthenticated' },
    ],
    examples: [
      'composio local-tools configure <toolkit> --command /path/to/tool',
      'composio local-tools configure LOCAL_EXAMPLE_RUN --disable',
      'composio local-tools configure <toolkit> --authenticated --json',
    ],
    seeAlso: ['composio local-tools doctor            Validate the configured command'],
  }),
  'local-tools meta': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
    usage: 'composio local-tools meta [--json] [--init]',
    description: 'Inspect or initialize ~/composio/local_tools.json for local auth/install state.',
    options: [
      { name: '--json', description: 'Print metadata state as JSON' },
      { name: '--init', description: 'Create the metadata file if needed' },
    ],
    examples: [
      'composio local-tools meta',
      'composio local-tools meta --init',
      'composio local-tools meta --json',
    ],
  }),
  run: {
    usage: 'composio run <code> [-- ...args] | run -f <file> [-- ...args]',
    description:
      'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.',
    args: [{ name: '<code>', description: 'Inline Bun ESNext code to evaluate' }],
    options: [
      { name: '-f, --file <text>', description: 'Run a TS/JS file instead of inline code' },
      { name: '--dry-run', description: 'Preview execute() calls without running them' },
      { name: '--debug', description: 'Log helper steps while the script runs' },
      {
        name: '--logs-off',
        description: 'Hide the always-on experimental_subAgent streaming logs',
      },
    ],
    flags: [
      { name: '--skip-connection-check', description: 'Skip the connected-account check' },
      {
        name: '--skip-tool-params-check',
        description: 'Skip input validation against cached schema',
      },
      { name: '--skip-checks', description: 'Skip both checks above' },
    ],
    injectedHelpers: [
      {
        name: 'execute(slug, data?)',
        description: 'Run a tool — same as `composio execute`, returns parsed JSON',
      },
      { name: 'search(query, opts?)', description: 'Find tools — same as `composio search`' },
      { name: 'proxy(toolkit)', description: 'Returns a fetch() bound to your connected account' },
      {
        name: 'experimental_subAgent(prompt, opts?)',
        description: 'Experimental sub-agent helper (Claude/Codex) with optional structured output',
      },
      {
        name: 'result.prompt()',
        description: 'Serialize any helper result into an LLM-friendly string',
      },
      { name: 'z', description: 'Global from zod for defining structured output schemas' },
    ],
    examples: [
      `composio run '`,
      `  // execute(slug, data?) — run a tool, returns parsed JSON`,
      `  const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");`,
      `  console.log(me);`,
      `'`,
      '',
      `composio run '`,
      `  // search(query, opts?) — find tools by use case`,
      `  const tools = await search("send email");`,
      `  console.log(tools);`,
      `'`,
      '',
      '# Sequential: chain tool outputs across services',
      `composio run '`,
      `  const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Deploy v2" });`,
      `  await execute("SLACK_SEND_A_MESSAGE_TO_A_SLACK_CHANNEL", { channel: "eng", text: "Created: " + issue.data.html_url });`,
      `'`,
      '',
      '# Parallel: fetch from multiple services at once with Promise.all',
      `composio run '`,
      `  const [emails, issues, events] = await Promise.all([`,
      `    execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
      `    execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
      `    execute("GOOGLECALENDAR_FIND_EVENT", { calendar_id: "primary" }),`,
      `  ]);`,
      `  console.log({ emails: emails.data, issues: issues.data, events: events.data });`,
      `'`,
      '',
      '# Bulk: fan out with Promise.all + .map()',
      `composio run '`,
      `  const issues = [101, 102, 103, 104];`,
      `  await Promise.all(issues.map(n =>`,
      `    execute("GITHUB_ADD_LABELS_TO_ISSUE", { owner: "acme", repo: "app", issue_number: n, labels: ["priority"] })`,
      `  ));`,
      `'`,
      '',
      '# proxy(toolkit) — returns a fetch() bound to your connected account',
      `composio run '`,
      `  const f = await proxy("gmail");`,
      `  console.log(await f("https://gmail.googleapis.com/gmail/v1/users/me/profile"));`,
      `'`,
      '',
      '# experimental_subAgent + z + result.prompt() — structured output from a sub-agent',
      `composio run '`,
      `  const [emails, issues] = await Promise.all([`,
      `    execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
      `    execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
      `  ]);`,
      `  // result.prompt() serializes helper output for LLM consumption`,
      `  // z is a global from zod for defining structured output schemas`,
      `  const brief = await experimental_subAgent(`,
      `    \`Summarize these emails and issues.\\n\\n\${emails.prompt()}\\n\\n\${issues.prompt()}\`,`,
      `    { schema: z.object({ summary: z.string(), urgent: z.array(z.string()) }) }`,
      `  );`,
      `  console.log(brief.structuredOutput);`,
      `'`,
      '',
      '# Run from a file',
      'composio run --file ./workflow.ts -- --repo acme/app',
    ],
    seeAlso: [
      'composio search "<query>"               Discover tool slugs before scripting',
      'composio link <toolkit>                  Connect accounts before scripting',
      'composio execute <slug> --get-schema     Inspect tool inputs before scripting',
      'composio artifacts cwd                   Print the current session artifact directory',
    ],
  },
  proxy: {
    usage:
      'composio proxy <url> --toolkit <text> [--account <selector>] [-X method] [-H header]... [-d data]',
    description:
      'curl-like access to any toolkit API through Composio using your connected account. Composio handles authentication — just provide the full URL and toolkit.',
    args: [{ name: '<url>', description: 'Full API endpoint URL' }],
    options: [
      {
        name: '-t, --toolkit <text>',
        description: 'Toolkit slug whose connected account should be used',
      },
      {
        name: '--account <selector>',
        description: 'Select a connected account by alias, word_id, or connected account ID',
      },
      { name: '-X, --method <text>', description: 'HTTP method (GET, POST, PUT, DELETE, PATCH)' },
      {
        name: '-H, --header <text>',
        description: 'Header in "Name: value" format. Repeat for multiple.',
      },
      {
        name: '-d, --data <text>',
        description: 'Request body as raw text, JSON, @file, or - for stdin',
      },
    ],
    flags: [{ name: '--skip-connection-check', description: 'Skip the connected-account check' }],
    examples: [
      'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail --account work',
      `composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\`,
      `  -X POST -H 'content-type: application/json' -d '{"message":{"raw":"..."}}'`,
    ],
    seeAlso: [
      'composio link <toolkit>                              Connect an account first',
      `composio run 'const f = await proxy("gmail"); ...'   Use proxy in a script`,
    ],
  },

  // ── Account commands ──────────────────────────────────────────────────

  login: {
    usage:
      'composio login [--no-browser] [--poll] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]',
    description:
      'Log in to the Composio CLI session. By default, also installs the composio-cli skill for Claude Code.',
    options: [
      {
        name: '--key <text>',
        description: 'Poll and complete login using the session key from composio login',
      },
      {
        name: '--user-api-key <text>',
        description: 'Log in directly with a Composio user API key',
      },
      {
        name: '--org <text>',
        description: 'Current organization ID or name to store for CLI commands',
      },
    ],
    flags: [
      { name: '--no-browser', description: 'Login without browser interaction' },
      {
        name: '--poll',
        description: 'Poll the cached pending login key for up to 10 minutes',
      },
      { name: '--no-wait', description: 'Print login URL and session info, then exit' },
      { name: '-y, --yes', description: 'Skip org picker; use current org' },
      {
        name: '--no-skill-install',
        description: 'Skip installing the composio-cli skill for Claude Code',
      },
    ],
  },
  logout: {
    usage: 'composio logout',
    description: 'Log out from the Composio CLI session.',
  },
  whoami: {
    usage: 'composio whoami',
    description: 'Display your account information.',
  },
  setup: {
    usage: 'composio setup [--target auto|claude|codex|all] [--uninstall] [--yes] [--if-present]',
    description: 'Install or uninstall plugins for supported agent hosts.',
    examples: [
      'composio setup',
      'composio setup --target auto --yes',
      'composio setup --uninstall --target auto --yes',
      'composio setup --target all',
    ],
    options: [
      { name: '--target <target>', description: 'auto, claude, codex, or all' },
      { name: '-y, --yes', description: 'Accept setup changes without prompting' },
      {
        name: '--uninstall',
        description: 'Uninstall Composio plugins instead of installing them',
      },
      {
        name: '--if-present',
        description: 'Exit successfully when automatic detection finds no supported host',
      },
    ],
  },
  version: {
    usage: 'composio version',
    description: 'Display the current Composio CLI version.',
  },
  upgrade: {
    usage: 'composio upgrade',
    description: 'Upgrade your Composio CLI to the latest available version.',
  },
  files: {
    usage: 'composio files',
    description: 'Where the Composio CLI stores data on disk.',
    examples: [
      '~/.composio/',
      '  CLI configuration and cache directory.',
      '  user_data.json        Your auth state (API key, org, base URL)',
      '  toolkits.json         Cached toolkit list from the API',
      '  tools.json            Cached tool definitions',
      '  trigger-types.json    Cached trigger type definitions',
      '  consumer-short-term-cache.json   Per-org connected toolkits cache (15-min TTL)',
      '  analytics.json        Anonymous install ID for telemetry',
      '',
      '  All caches are safe to delete — they will be re-fetched on next use.',
      '',
      '$TMPDIR/composio/   (or COMPOSIO_SESSION_DIR / COMPOSIO_CACHE_DIR)',
      '  Session artifacts directory. Each CLI session gets a unique subdirectory',
      '  scoped to your working directory. Stores session history and files',
      '  created during `run` and `execute` (e.g. large tool outputs).',
      '  Use `composio artifacts cwd` to print the current session path.',
      '',
      '.composio/   (per-project, optional)',
      '  Per-directory project config. Scoped to the nearest parent that has one.',
      '  .env             Allows COMPOSIO_ORG_ID and COMPOSIO_PROJECT_ID overrides',
      '  project.json     Project context (org, project binding)',
      '',
      'Environment variables that control paths:',
      '  COMPOSIO_SESSION_DIR     Override session artifacts root',
      '  COMPOSIO_CACHE_DIR       Override cache directory (also used for artifacts fallback)',
      '  COMPOSIO_CACHE_DIR is useful in sandboxed environments where ~/.composio or',
      '  $TMPDIR may not be writable.',
    ],
  },

  // ── Tools commands ────────────────────────────────────────────────────

  tools: {
    usage: 'composio tools <command>',
    description: 'Browse and inspect tools before executing them.',
    examples: ['composio tools list gmail', 'composio tools info GMAIL_SEND_EMAIL'],
    seeAlso: [
      'composio search "<query>"               Find tools by use case',
      "composio execute <slug> -d '{ ... }'    Execute a tool directly",
    ],
  },
  'tools list': {
    usage: 'composio tools list <toolkit> [--query text] [--tags text] [--limit integer]',
    description: 'List available tools for a toolkit.',
    args: [{ name: '<toolkit>', description: 'Toolkit slug to list tools for (e.g. "gmail")' }],
    options: [
      { name: '--query <text>', description: 'Text search by name, slug, or description' },
      { name: '--tags <text>', description: 'Filter by tags (e.g. "important")' },
      { name: '--limit <integer>', description: 'Maximum number of results (1-1000)' },
    ],
  },
  'tools info': {
    usage: 'composio tools info [<slug>]',
    description:
      'View a brief summary of a tool and show the CLI-facing schema used by `composio execute --get-schema`.',
    args: [{ name: '<slug>', description: 'Tool slug (e.g. "GMAIL_SEND_EMAIL")' }],
  },
  'triggers list': {
    usage: 'composio triggers list <toolkit> [--limit integer]',
    description: 'List available trigger types for a toolkit.',
    args: [
      { name: '<toolkit>', description: 'Toolkit slug to list trigger types for (e.g. "gmail")' },
    ],
    options: [{ name: '--limit <integer>', description: 'Number of results' }],
  },
  'triggers info': {
    usage: 'composio triggers info [<slug>]',
    description: 'View details of a specific trigger type.',
    args: [{ name: '<slug>', description: 'Trigger slug' }],
  },

  // ── Generate commands ─────────────────────────────────────────────────

  generate: {
    usage: 'composio generate [--output-dir dir] [--type-tools] --toolkits text...',
    description:
      'Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python).',
    options: [
      { name: '-o, --output-dir <dir>', description: 'Output directory for type stubs' },
      {
        name: '--toolkits <text>... (required)',
        description: 'Toolkits to generate for (repeat for multiple)',
      },
    ],
    flags: [
      {
        name: '--type-tools',
        description: 'Generate typed input/output schemas for each tool (slower)',
      },
    ],
  },
  'generate ts': {
    usage:
      'composio generate ts [--output-dir dir] [--compact] [--transpiled] [--type-tools] --toolkits text...',
    description: 'Generate TypeScript type stubs for toolkits, tools, and triggers.',
    options: [
      {
        name: '-o, --output-dir <dir>',
        description: 'Output directory for generated TypeScript stubs',
      },
      {
        name: '--toolkits <text>... (required)',
        description: 'Toolkits to generate for (repeat for multiple)',
      },
    ],
    flags: [
      { name: '--compact', description: 'Emit a single TypeScript file' },
      {
        name: '--transpiled',
        description: 'Emit transpiled JavaScript alongside TypeScript files',
      },
      {
        name: '--type-tools',
        description: 'Generate typed input/output schemas for each tool (slower)',
      },
    ],
  },
  'generate py': {
    usage: 'composio generate py [--output-dir dir] --toolkits text...',
    description: 'Generate Python type stubs for toolkits, tools, and triggers.',
    options: [
      {
        name: '-o, --output-dir <dir>',
        description: 'Output directory for generated Python stubs',
      },
      {
        name: '--toolkits <text>... (required)',
        description: 'Toolkits to generate for (repeat for multiple)',
      },
    ],
  },

  // ── Dev commands ──────────────────────────────────────────────────────

  'dev init': {
    usage: 'composio dev init [--no-browser] [-y, --yes]',
    description: 'Initialize this directory with a developer project.',
    flags: [
      { name: '--no-browser', description: 'Login without browser interaction' },
      { name: '-y, --yes', description: 'Auto-select the current org project' },
    ],
  },
  'dev playground-execute': {
    usage:
      'composio dev playground-execute <slug> [-d, --data text] [--file path] [--user-id text] [--project-name text] [--dry-run] [--get-schema]',
    description:
      'Test tool executions against playground users using your developer project auth configs.',
    args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],
    options: [
      { name: '-d, --data <text>', description: 'JSON arguments, @file, or - for stdin' },
      {
        name: '--file <path>',
        description: 'Inject a local file path into the single file_uploadable input',
      },
      { name: '--user-id <text>', description: 'Developer-project user ID override' },
      { name: '--project-name <text>', description: 'Developer project name override' },
      {
        name: '--get-schema',
        description: 'Fetch and print the CLI-facing input schema without executing',
      },
      { name: '--dry-run', description: 'Validate and preview without executing' },
    ],
    flags: [
      { name: '--skip-connection-check', description: 'Skip the connected-account check' },
      {
        name: '--skip-tool-params-check',
        description: 'Skip input validation against cached schema',
      },
      { name: '--skip-checks', description: 'Skip both checks above' },
    ],
  },
  'dev listen': {
    usage:
      'composio dev listen [--toolkits text] [--trigger-slug text] [--json] [--table] [--max-events int] [--forward url] [--out file]',
    description:
      'Listen to realtime trigger events for your developer project and optionally forward them.',
    options: [
      { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
      { name: '--trigger-id <text>', description: 'Filter by trigger id' },
      { name: '--connected-account-id <text>', description: 'Filter by connected account id' },
      { name: '--trigger-slug <text>', description: 'Filter by trigger slug, comma-separated' },
      { name: '--user-id <text>', description: 'Filter by user id' },
      { name: '--max-events <int>', description: 'Stop after receiving N matching events' },
      { name: '--forward <url>', description: 'Forward each event to the given URL' },
      { name: '--out <file>', description: 'Append each event to this file' },
    ],
    flags: [
      { name: '--json', description: 'Show raw event payload as JSON' },
      { name: '--table', description: 'Show compact table rows' },
    ],
  },
  // ── Dev admin commands ─────────────────────────────────────────────────

  'dev toolkits list': {
    usage:
      'composio dev toolkits list [--query text] [--limit integer] [--connected] [--user-id text]',
    description: 'List available toolkits with connection status.',
    options: [
      { name: '--query <text>', description: 'Text search by name, slug, or description' },
      { name: '--limit <integer>', description: 'Maximum number of results (1-1000)' },
      { name: '--user-id <text>', description: 'User ID override' },
    ],
    flags: [{ name: '--connected', description: 'Show only connected toolkits' }],
  },
  'dev toolkits info': {
    usage: 'composio dev toolkits info [--user-id text] [-a, --all] [<slug>]',
    description: 'View details of a specific toolkit.',
    args: [{ name: '<slug>', description: 'Toolkit slug (e.g. "github")' }],
    flags: [{ name: '-a, --all', description: 'Show all details' }],
  },
  'dev toolkits search': {
    usage: 'composio dev toolkits search <query> [--limit integer]',
    description: 'Search toolkits by use case.',
    args: [{ name: '<query>', description: 'Search query' }],
    options: [{ name: '--limit <integer>', description: 'Number of results' }],
  },
  'dev toolkits version': {
    usage: 'composio dev toolkits version <slug>',
    description: 'Show latest and recent versions for a toolkit.',
    args: [{ name: '<slug>', description: 'Toolkit slug' }],
  },
  'dev auth-configs list': {
    usage: 'composio dev auth-configs list [--toolkits text] [--query text] [--limit integer]',
    description: 'List auth configs.',
    options: [
      { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
      { name: '--query <text>', description: 'Search text' },
      { name: '--limit <integer>', description: 'Number of results' },
    ],
  },
  'dev auth-configs info': {
    usage: 'composio dev auth-configs info [<id>]',
    description: 'View details of a specific auth config.',
    args: [{ name: '<id>', description: 'Auth config ID' }],
  },
  'dev auth-configs create': {
    usage:
      'composio dev auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>]',
    description: 'Create a new auth config.',
    args: [{ name: '<name>', description: 'Auth config name' }],
    options: [
      { name: '--toolkit <text>', description: 'Toolkit slug' },
      { name: '--auth-scheme <text>', description: 'Authentication scheme' },
      { name: '--scopes <text>', description: 'Comma-separated scopes' },
      { name: '--custom-credentials <text>', description: 'Custom credentials JSON' },
    ],
  },
  'dev connected-accounts list': {
    usage:
      'composio dev connected-accounts list [--toolkits text] [--user-id text] [--status text] [--limit integer]',
    description: 'List connected accounts.',
    options: [
      { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
      { name: '--user-id <text>', description: 'Filter by user id' },
      { name: '--status <text>', description: 'Filter by status (ACTIVE, FAILED, EXPIRED, etc.)' },
      { name: '--limit <integer>', description: 'Number of results' },
    ],
  },
  'dev connected-accounts info': {
    usage: 'composio dev connected-accounts info [<id>]',
    description: 'View details of a specific connected account.',
    args: [{ name: '<id>', description: 'Connected account ID' }],
  },
  'dev connected-accounts whoami': {
    usage: 'composio dev connected-accounts whoami [<id>]',
    description: 'Show the external account profile for a connected account.',
    args: [{ name: '<id>', description: 'Connected account ID' }],
  },
  'dev triggers list': {
    usage: 'composio dev triggers list <toolkit> [--limit integer]',
    description: 'List available trigger types for a toolkit.',
    args: [
      { name: '<toolkit>', description: 'Toolkit slug to list trigger types for (e.g. "gmail")' },
    ],
    options: [{ name: '--limit <integer>', description: 'Number of results' }],
  },
  'dev triggers info': {
    usage: 'composio dev triggers info [<slug>]',
    description: 'View details of a specific trigger type.',
    args: [{ name: '<slug>', description: 'Trigger slug' }],
  },
  'dev triggers status': {
    usage:
      'composio dev triggers status [--user-ids text] [--toolkits text] [--trigger-ids text] [--show-disabled] [--limit integer]',
    description: 'Show active triggers with optional filters.',
    options: [
      { name: '--user-ids <text>', description: 'Filter by user IDs' },
      { name: '--connected-account-ids <text>', description: 'Filter by connected account IDs' },
      { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
      { name: '--trigger-ids <text>', description: 'Filter by trigger IDs' },
      { name: '--trigger-names <text>', description: 'Filter by trigger names' },
      { name: '--limit <integer>', description: 'Number of results' },
    ],
    flags: [{ name: '--show-disabled', description: 'Include disabled triggers' }],
  },
  'dev triggers create': {
    usage:
      'composio dev triggers create [--connected-account-id text] [--trigger-config text] [<trigger-name>]',
    description: 'Create a new trigger instance.',
    args: [{ name: '<trigger-name>', description: 'Trigger type slug' }],
    options: [
      { name: '--connected-account-id <text>', description: 'Connected account to use' },
      { name: '--trigger-config <text>', description: 'Trigger configuration JSON' },
    ],
  },
  'dev triggers enable': {
    usage: 'composio dev triggers enable [<id>]',
    description: 'Enable a trigger instance.',
    args: [{ name: '<id>', description: 'Trigger instance ID' }],
  },
  'dev triggers disable': {
    usage: 'composio dev triggers disable [<id>]',
    description: 'Disable a trigger instance.',
    args: [{ name: '<id>', description: 'Trigger instance ID' }],
  },
  'dev projects list': {
    usage: 'composio dev projects list [--org-id text] [--limit integer]',
    description: 'List developer projects for the current organization.',
    options: [
      { name: '--org-id <text>', description: 'Organization ID override' },
      { name: '--limit <integer>', description: 'Number of results' },
    ],
  },

  // ── Dev logs commands ─────────────────────────────────────────────────

  'dev logs tools': {
    usage:
      'composio dev logs tools [--toolkit text] [--tool text] [--status text] [--limit integer] [<log_id>]',
    description: 'List tool execution logs, or pass a log_id to fetch a specific log.',
    args: [{ name: '<log_id>', description: 'Specific log ID to fetch' }],
    options: [
      { name: '--toolkit <text>', description: 'Filter by toolkit slug' },
      { name: '--tool <text>', description: 'Filter by tool slug' },
      { name: '--status <text>', description: 'Filter by status' },
      { name: '--user-id <text>', description: 'Filter by user id' },
      { name: '--limit <integer>', description: 'Number of results' },
      { name: '--from <integer>', description: 'Start timestamp (epoch ms)' },
      { name: '--to <integer>', description: 'End timestamp (epoch ms)' },
    ],
    flags: [{ name: '--case-sensitive', description: 'Case-sensitive filtering' }],
  },
  config: {
    usage: 'composio config <subcommand>',
    description: 'View and manage CLI configuration.',
    seeAlso: ['composio config experimental'],
  },
  'config experimental': {
    usage: 'composio config experimental [<feature>] [on|off]',
    description: 'View or toggle experimental feature flags.',
    args: [
      { name: '<feature>', description: 'Feature name (e.g., listen, local_tools)' },
      { name: 'on|off', description: 'Enable or disable the feature' },
    ],
    examples: [
      'composio config experimental                     # List all features',
      'composio config experimental listen              # Show current state',
      'composio config experimental local_tools on      # Enable local toolkits',
    ],
  },
  'dev logs triggers': {
    usage:
      'composio dev logs triggers [--trigger text] [--trigger-id text] [--limit integer] [--time 5m|30m|6h|1d|1w] [<log_id>]',
    description: 'List trigger logs.',
    args: [{ name: '<log_id>', description: 'Specific log ID to fetch' }],
    options: [
      { name: '--trigger <text>', description: 'Filter by trigger slug' },
      { name: '--trigger-id <text>', description: 'Filter by trigger id' },
      { name: '--user-id <text>', description: 'Filter by user id' },
      { name: '--connected-account-id <text>', description: 'Filter by connected account id' },
      { name: '--limit <integer>', description: 'Number of results' },
      { name: '--time <period>', description: 'Time window (5m, 30m, 6h, 1d, 1w, 1month, 1y)' },
      { name: '--search <text>', description: 'Search in log content' },
    ],
    flags: [{ name: '--include-payload', description: 'Include full event payload' }],
  },
};

const getVisibleSubcommandHelp = (
  cmd: string,
  visibility: CommandVisibility,
  helpLevel: HelpLevel = 'default'
): Option.Option<SubcommandHelp> => {
  if (cmd === 'dev') {
    return Option.some({
      usage: 'composio dev [--mode on|off]',
      description: 'Developer mode and developer-scoped workflows.',
    });
  }

  if (cmd.startsWith('dev ') && !visibility.isDevModeEnabled) {
    return Option.none();
  }

  const entry = SUBCOMMAND_HELP[cmd];
  if (!entry) {
    return Option.none();
  }

  if (!('value' in entry)) {
    return Option.some(entry);
  }

  return isTaggedValueVisible(entry, visibility) &&
    isTaggedValueVisibleForHelpLevel(entry, helpLevel)
    ? Option.some(entry.value)
    : Option.none();
};

function renderSubcommandHelp(cmd: SubcommandHelp, helpLevel: HelpLevel): string {
  const lines: string[] = [
    '',
    bold('USAGE'),
    `  ${cmd.usage}`,
    '',
    bold('DESCRIPTION'),
    `  ${cmd.description}`,
    '',
  ];

  if (cmd.args && cmd.args.length > 0) {
    lines.push(bold('ARGUMENTS'));
    for (const arg of cmd.args) {
      lines.push(`  ${dim(arg.name.padEnd(24))}${arg.description}`);
    }
    lines.push('');
  }

  if (cmd.options && cmd.options.length > 0) {
    lines.push(bold('OPTIONS'));
    for (const opt of cmd.options) {
      lines.push(`  ${dim(opt.name.padEnd(24))}${opt.description}`);
    }
    lines.push('');
  }

  if (cmd.flags && cmd.flags.length > 0) {
    lines.push(bold('FLAGS'));
    for (const flag of cmd.flags) {
      lines.push(`  ${dim(flag.name.padEnd(28))}${flag.description}`);
    }
    lines.push('');
  }

  if (helpLevel !== 'simple' && cmd.injectedHelpers && cmd.injectedHelpers.length > 0) {
    lines.push(bold('INJECTED HELPERS'));
    const maxLen = Math.max(...cmd.injectedHelpers.map(h => h.name.length));
    for (const helper of cmd.injectedHelpers) {
      lines.push(`  ${dim(helper.name.padEnd(maxLen + 2))}${helper.description}`);
    }
    lines.push('');
  }

  if (helpLevel !== 'simple' && cmd.examples && cmd.examples.length > 0) {
    lines.push(bold('EXAMPLES'));
    for (const ex of cmd.examples) {
      lines.push(`  ${ex}`);
    }
    lines.push('');
  }

  if (helpLevel !== 'simple' && cmd.seeAlso && cmd.seeAlso.length > 0) {
    lines.push(bold('SEE ALSO'));
    for (const sa of cmd.seeAlso) {
      lines.push(`  ${sa}`);
    }
    lines.push('');
  }

  return lines.join('\n');
}

/**
 * Check if argv is `composio <subcommand> --help` for a command we have custom help for.
 * Returns the command name if matched, undefined otherwise.
 */
export function matchSubcommandHelp(
  argv: ReadonlyArray<string>,
  visibility: CommandVisibility
): string | undefined {
  const { args } = splitTrailingHelpLevel(argv.slice(2));
  if (args.length < 2) return undefined;
  const last = args[args.length - 1];
  if (last !== '--help' && last !== '-h') return undefined;

  const cmdParts = args.slice(0, -1);
  // Try longest match first: "dev toolkits list" → "dev toolkits" → "dev"
  for (let len = cmdParts.length; len > 0; len--) {
    const key = cmdParts.slice(0, len).join(' ');
    if (Option.isSome(getVisibleSubcommandHelp(key, visibility))) return key;
  }
  return undefined;
}

export function printSubcommandHelp(
  cmd: string,
  visibility: CommandVisibility,
  helpLevel: HelpLevel = 'default'
): Effect.Effect<void, never, TerminalUI> {
  if (cmd === 'dev') {
    return Effect.flatMap(TerminalUI, ui =>
      ui.output(renderDevHelp(visibility, helpLevel), { force: true })
    );
  }
  const help = getVisibleSubcommandHelp(cmd, visibility, helpLevel);
  if (Option.isNone(help)) {
    return Effect.flatMap(TerminalUI, ui => ui.output(`Unknown command: ${cmd}`, { force: true }));
  }
  return Effect.flatMap(TerminalUI, ui =>
    ui.output(renderSubcommandHelp(help.value, helpLevel), { force: true })
  );
}

/**
 * Match the command name from argv without requiring --help at the end.
 * Used to print contextual help alongside error messages.
 */
export function matchCommandFromArgv(
  argv: ReadonlyArray<string>,
  visibility: CommandVisibility
): string | undefined {
  const { args: helpArgs } = splitTrailingHelpLevel(argv.slice(2));
  const args = helpArgs.filter(a => a !== '--help' && a !== '-h' && !a.startsWith('--'));
  // Try longest match first: "dev toolkits list" → "dev toolkits" → "dev"
  for (let len = Math.min(args.length, 3); len > 0; len--) {
    const key = args.slice(0, len).join(' ');
    if (Option.isSome(getVisibleSubcommandHelp(key, visibility))) return key;
  }
  return undefined;
}

/**
 * Get rendered help text for a command, or undefined if not found.
 */
export function getCommandHelpText(cmd: string, visibility: CommandVisibility): string | undefined {
  if (cmd === 'dev') return renderDevHelp(visibility);
  return Option.match(getVisibleSubcommandHelp(cmd, visibility), {
    onNone: () => undefined,
    onSome: help => renderSubcommandHelp(help, 'default'),
  });
}

// ── Main help output ───────────────────────────────────────────────────

/**
 * Prints the root-level help output.
 * Core workflow commands are shown first with full usage/options.
 * Housekeeping and developer commands are shown compactly at the bottom.
 */
export function printRootHelp(
  visibility: CommandVisibility,
  helpLevel: HelpLevel = 'default'
): Effect.Effect<void, never, TerminalUI> {
  const name = 'composio';
  const developerCommands: ReadonlyArray<CompactCommand> = [
    {
      name: 'dev',
      description: visibility.isDevModeEnabled
        ? 'Developer workflows and management: init, logs, projects, toolkits, accounts, and triggers.'
        : 'Developer mode toggle. Use `composio dev --mode on` to enable developer workflows.',
    },
    GENERATE_COMMAND.value,
  ];
  const coreCommands = visibleValues(CORE_COMMANDS, visibility, helpLevel);
  const otherCommands = visibleValues(OTHER_COMMANDS, visibility, helpLevel);
  const accountCommands = visibleValues(ACCOUNT_COMMANDS, visibility, helpLevel);
  const fullCommands = visibleValues(FULL_COMMANDS, visibility, helpLevel);
  const exampleLines =
    helpLevel === 'simple'
      ? [
          `  ${dim('# Find tools')}`,
          `  ${name} search "send an email"`,
          '',
          `  ${dim('# Execute a tool')}`,
          `  ${name} execute GITHUB_CREATE_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
          '',
          `  ${dim('# Connect an account when execute tells you to')}`,
          `  ${name} link github`,
          '',
        ]
      : [
          `  ${dim('# Find tools — supports multiple queries at once')}`,
          `  ${name} search "send an email" "create github issue"`,
          `  ${name} search "list calendar events" --toolkits google_calendar --limit 5`,
          '',
          `  ${dim('# Connect your account for a toolkit')}`,
          `  ${name} link github`,
          '',
          `  ${dim('# Execute a tool')}`,
          `  ${name} execute GITHUB_CREATE_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
          '',
          `  ${dim('# Execute multiple tools in parallel')}`,
          `  ${name} execute -p GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]", subject: "Hi" }' \\`,
          `                     SLACK_SEND_A_MESSAGE_TO_A_SLACK_CHANNEL -d '{ channel: "general", text: "Hello" }'`,
          '',
          `  ${dim('# Call an API directly through proxy')}`,
          `  ${name} proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail`,
          '',
          `  ${dim('# Run a script with injected helpers')}`,
          `  ${name} run 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,
          '',
          `  ${dim('# Manually install the composio skill when auto-install fails')}`,
          `  ${name} --install-skill claude`,
          `  ${name} --install-skill composio-cli codex`,
          '',
          `  ${dim('# Run a multi-step script with Promise.all')}`,
          `  ${name} run '`,
          `    const [emails, issues] = await Promise.all([`,
          `      execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
          `      execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "acme", repo: "app", state: "open" }),`,
          `    ]);`,
          `    const brief = await experimental_subAgent(\`Summarize:\\n\${emails.prompt()}\\n\${issues.prompt()}\`);`,
          `    console.log(brief);`,
          `  '`,
          '',
        ];

  const lines: string[] = [
    '',
    `Connect AI agents to external tools. ${bold('search')}, ${bold('execute')}, ${bold('link')}, ${bold('proxy')}, and ${bold('run')} let you`,
    'take actions across 1000+ apps directly; if you can describe it, it is probably supported.',
    `Try ${bold('execute')} sooner than you'd think — it validates inputs, checks connections, and tells`,
    'you what to fix.',
    '',
    visibility.isDevModeEnabled
      ? `Use ${bold('dev')} when you are building an agent with Composio's SDK and want scaffolding,`
      : `Use ${bold('dev')} to control access to developer-only workflows.`,
    visibility.isDevModeEnabled
      ? 'playground execution, logs, and developer-scoped management commands.'
      : 'Developer mode is currently off.',
    '',
    bold('USAGE'),
    `  ${name} <command> [options]`,
    `  ${name} --help [simple|default|full]`,
    '',
    bold('MODE'),
    `  ${helpLevel} help`,
    '',
    bold('CORE COMMANDS'),
    ...renderDetailedCommands(name, coreCommands),
    gray('  Typical flow: search → execute (link and tools when needed)'),
    '',
    ...(otherCommands.length > 0
      ? [bold('TOOLS'), ...renderCompactCommands(otherCommands), '']
      : []),
    '',
    bold('EXAMPLES'),
    ...exampleLines,
    ...(developerCommands.length > 0
      ? [bold('DEVELOPER COMMANDS'), ...renderCompactCommands(developerCommands), '']
      : []),
    ...(accountCommands.length > 0
      ? [bold('ACCOUNT'), ...renderCompactCommands(accountCommands), '']
      : []),
    ...(fullCommands.length > 0
      ? [bold('MORE COMMANDS'), ...renderCompactCommands(fullCommands), '']
      : []),
    bold('FILES') + dim('  (composio files --help)'),
    `  ${bold('~/.composio/')}`,
    `    CLI configuration and cache directory. Contains your auth state`,
    `    (user_data.json), runtime settings (config.json), cached tool definitions`,
    `    (tools.json, toolkits.json),`,
    `    trigger types, and per-org consumer caches. These caches speed up`,
    `    repeated commands — safe to delete, they will be re-fetched on next use.`,
    '',
    `  ${bold('/tmp/composio/')}`,
    `    Session artifacts directory. Each CLI session gets a unique subdirectory`,
    `    scoped to your working directory. Stores session history and files`,
    `    created during ${bold('run')} and ${bold('execute')} commands (e.g. downloaded attachments,`,
    `    generated outputs). Use \`${name} artifacts cwd\` to print the path for`,
    `    the current directory's session.`,
    '',
    bold('FLAGS'),
    '  -h, --help [mode]  Show help for command (simple, default, full)',
    `  --version      Show ${name} version`,
    '  --install-skill [skill-name] <claude|codex|openclaw>',
    '                  Manually install the composio skill for a supported agent',
    '',
    bold('LEARN MORE'),
    `  Use \`${name} <command> --help\` for more information about a command.`,
    `  Documentation: https://docs.composio.dev`,
    '',
  ];

  return Effect.flatMap(TerminalUI, ui => ui.output(lines.join('\n'), { force: true }));
}