Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Add channel-aware Composio CLI skill builds (#3127)
Rahul Taraka8071e0d35d5
diff --git a/.github/workflows/build-cli-binaries.yml b/.github/workflows/build-cli-binaries.ymlindex 126c37c94..c96dcd1fa 100644--- a/.github/workflows/build-cli-binaries.yml+++ b/.github/workflows/build-cli-binaries.yml@@ -289,8 +289,17 @@ jobs:- name: Package skill filesworking-directory: ts/packages/cli+ env:+ PRERELEASE: ${{ needs.prepare.outputs.prerelease }}run: |- cd skills && zip -r ../dist/binaries/composio-skill.zip composio-cli/+ pnpm run validate:skills+ if [[ "$PRERELEASE" == "true" ]]; then+ channel=beta+ else+ channel=stable+ fi+ pnpm run build:skills -- --channel "$channel" --output-dir ./dist/skills+ cd dist/skills && zip -r ../binaries/composio-skill.zip composio-cli/- name: Create GitHub Releaseenv:diff --git a/package.json b/package.jsonindex 4b9b6b13d..e9e1b31aa 100644--- a/package.json+++ b/package.json@@ -18,7 +18,8 @@"build:packages": "turbo build --filter=./ts/packages/**","cli:record": "turbo run record --filter=./ts/packages/cli","record": "turbo run record",- "test": "turbo test --filter=./ts/packages/** --filter=!@e2e-tests/*",+ "test": "turbo test --filter=./ts/packages/** --filter=!@e2e-tests/* && pnpm run test:examples",+ "test:examples": "tsx ts/scripts/validate-examples.ts","test:e2e": "turbo test:e2e --filter='@e2e-tests/*'","test:e2e:node": "turbo test:e2e:node --filter='@e2e-tests/node-*'","test:e2e:deno": "turbo test:e2e:deno --filter='@e2e-tests/deno-*'",diff --git a/ts/examples/cloudflare-wrangler/package.json b/ts/examples/cloudflare-wrangler/package.jsonindex d822bd72e..8e9ffbdcd 100644--- a/ts/examples/cloudflare-wrangler/package.json+++ b/ts/examples/cloudflare-wrangler/package.json@@ -1,7 +1,8 @@{- "name": "cloudflare-wrangler-deploy",+ "name": "cloudflare-wrangler-example","version": "0.0.0","private": true,+ "packageManager": "[email protected]","scripts": {"deploy": "wrangler deploy","dev": "wrangler dev",diff --git a/ts/examples/toolkits/src/example.json b/ts/examples/toolkits/src/example.jsonindex e69de29bb..0967ef424 100644--- a/ts/examples/toolkits/src/example.json+++ b/ts/examples/toolkits/src/example.json@@ -0,0 +1 @@+{}diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.jsonindex d5c1e3d1d..7a9edb26e 100644--- a/ts/packages/cli/package.json+++ b/ts/packages/cli/package.json@@ -31,13 +31,15 @@"build:binary:all": "bun run ./scripts/build-all-binaries.ts","build:binary:package": "bun run ./scripts/package-binaries.ts","build:binary:checksums": "bun run ./scripts/generate-checksums.ts",+ "build:skills": "tsx ./scripts/build-skills.ts",+ "validate:skills": "tsx ./scripts/validate-skills.ts","install:binary": "bun run ./scripts/install-binary.ts ./dist/composio","table:metrics": "bun run ./scripts/optimize-metrics-table.ts","mock": "bun run ./scripts/copy-mocks-from-cache.ts","prebuild": "pnpm run typecheck","build": "pnpm exec tsdown","bin": "./dist/composio",- "test": "vitest run",+ "test": "pnpm run validate:skills && vitest run","prepublishOnly": "pnpm run build && pnpm run build:binary","typecheck:src": "pnpm exec tsgo --noEmit -p ./tsconfig.src.json","typecheck:test": "pnpm exec tsgo --noEmit -p ./tsconfig.test.json",diff --git a/ts/packages/cli/scripts/build-skills.ts b/ts/packages/cli/scripts/build-skills.tsnew file mode 100644index 000000000..675f97564--- /dev/null+++ b/ts/packages/cli/scripts/build-skills.ts@@ -0,0 +1,24 @@+import * as fs from 'node:fs';+import * as path from 'node:path';+import { buildComposioCliSkill, type SkillReleaseChannel } from '../skills-src/composio-cli/index';++const args = process.argv.slice(2);++const readArg = (name: string) => {+ const index = args.indexOf(name);+ return index >= 0 ? args[index + 1] : undefined;+};++const channelArg = readArg('--channel') ?? 'stable';+if (channelArg !== 'stable' && channelArg !== 'beta') {+ throw new Error(`Invalid --channel value "${channelArg}". Expected "stable" or "beta".`);+}++const outputDirArg = readArg('--output-dir') ?? path.resolve(process.cwd(), 'dist/skills');+const outputDir = path.resolve(process.cwd(), outputDirArg);+const channel = channelArg as SkillReleaseChannel;++fs.mkdirSync(outputDir, { recursive: true });+const skillDir = buildComposioCliSkill({ channel, outputRoot: outputDir });++console.log(`Built composio-cli skill for ${channel} at ${skillDir}`);diff --git a/ts/packages/cli/scripts/validate-skills.ts b/ts/packages/cli/scripts/validate-skills.tsnew file mode 100644index 000000000..0732ef6e7--- /dev/null+++ b/ts/packages/cli/scripts/validate-skills.ts@@ -0,0 +1,71 @@+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {+ buildComposioCliSkill,+ renderComposioCliSkill,+ validateSkillSources,+} from '../skills-src/composio-cli/index';++const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-skill-validate-'));++try {+ const sourceErrors = validateSkillSources();+ if (sourceErrors.length > 0) {+ throw new Error(sourceErrors.join('\n'));+ }++ const stableDir = buildComposioCliSkill({+ channel: 'stable',+ outputRoot: path.join(tempRoot, 'stable'),+ });+ const betaDir = buildComposioCliSkill({+ channel: 'beta',+ outputRoot: path.join(tempRoot, 'beta'),+ });++ const stableSkill = fs.readFileSync(path.join(stableDir, 'SKILL.md'), 'utf8');+ const betaSkill = fs.readFileSync(path.join(betaDir, 'SKILL.md'), 'utf8');++ if (!stableSkill.includes('<!-- release-channel: stable -->')) {+ throw new Error('Stable skill output is missing its release channel marker.');+ }++ if (!betaSkill.includes('<!-- release-channel: beta -->')) {+ throw new Error('Beta skill output is missing its release channel marker.');+ }++ if (stableSkill.includes('## `listen` - Subscribe To Trigger Events')) {+ throw new Error('Stable skill output unexpectedly includes beta-only listen guidance.');+ }++ if (!betaSkill.includes('## `listen` - Subscribe To Trigger Events')) {+ throw new Error('Beta skill output is missing beta-only listen guidance.');+ }++ if (stableSkill !== renderComposioCliSkill('stable')) {+ throw new Error('Stable skill build is not reproducible from the renderer.');+ }++ if (betaSkill !== renderComposioCliSkill('beta')) {+ throw new Error('Beta skill build is not reproducible from the renderer.');+ }++ for (const relativePath of [+ 'agents/openai.yaml',+ 'references/composio-dev.md',+ 'references/power-user-examples.md',+ 'references/troubleshooting.md',+ ]) {+ if (!fs.existsSync(path.join(stableDir, relativePath))) {+ throw new Error(`Stable build is missing ${relativePath}`);+ }+ if (!fs.existsSync(path.join(betaDir, relativePath))) {+ throw new Error(`Beta build is missing ${relativePath}`);+ }+ }++ console.log('Validated composio-cli skill builds for stable and beta.');+} finally {+ fs.rmSync(tempRoot, { recursive: true, force: true });+}diff --git a/ts/packages/cli/skills/composio-cli/agents/openai.yaml b/ts/packages/cli/skills-src/composio-cli/assets/agents/openai.yamlsimilarity index 100%rename from ts/packages/cli/skills/composio-cli/agents/openai.yamlrename to ts/packages/cli/skills-src/composio-cli/assets/agents/openai.yamldiff --git a/ts/packages/cli/skills-src/composio-cli/index.ts b/ts/packages/cli/skills-src/composio-cli/index.tsnew file mode 100644index 000000000..781356ef5--- /dev/null+++ b/ts/packages/cli/skills-src/composio-cli/index.ts@@ -0,0 +1,369 @@+import * as fs from 'node:fs';+import * as path from 'node:path';+import { CLI_EXPERIMENTAL_FEATURES } from '../../src/constants';+import { composioDevReference } from './references/composio-dev';+import { powerUserExamplesReference } from './references/power-user-examples';+import { troubleshootingReference } from './references/troubleshooting';+import {+ renderReferenceDocument,+ resolveSkillBuildContext,+ validateReferenceDocument,+ type SkillBuildContext,+ type SkillFeatureFlag,+ type SkillReleaseChannel,+} from './reference-schema';++type SkillFlag = {+ description: string;+ name: string;+ features?: SkillFeatureFlag[];+};++type SkillExample = {+ code: string;+ description?: string;+ features?: SkillFeatureFlag[];+};++type SkillCommand = {+ id: string;+ title: string;+ summary?: string;+ features?: SkillFeatureFlag[];+ intro?: string[];+ flags?: SkillFlag[];+ examples?: SkillExample[];+ notes?: string[];+ extraBody?: Array<{+ features?: SkillFeatureFlag[];+ markdown: string;+ }>;+};++const isEnabledForBuild = (build: SkillBuildContext, entry?: { features?: SkillFeatureFlag[] }) =>+ !entry?.features || entry.features.every(feature => build.experimentalFeatures[feature]);++const sourceAssetsDir = path.resolve(import.meta.dirname, './assets');++const frontmatter = {+ name: 'composio-cli',+ description:+ 'Help users operate the published Composio CLI to find the right tool, connect accounts, inspect schemas, execute tools, subscribe to trigger events with `composio listen`, script workflows with `composio run`, and call authenticated app APIs with `composio proxy`. Use when the user asks how to do something with `composio`, wants to run a known tool slug, needs to discover a slug with `composio search`, fix a missing connection with `composio link`, inspect tool inputs with `--get-schema` or `--dry-run`, troubleshoot top-level CLI flows, or explicitly needs `composio dev` guidance.',+};++const commands: SkillCommand[] = [+ {+ id: 'execute',+ title: '`execute` - Run A Tool',+ summary: 'Use `execute` when the tool slug is already known.',+ flags: [+ {+ name: '`--get-schema`',+ description: 'Inspect required arguments without executing the tool.',+ },+ {+ name: '`--dry-run`',+ description: 'Preview the request shape without performing the action.',+ },+ {+ name: '`--file`',+ description:+ 'Inject a local file path into a tool that exposes exactly one uploadable file argument.',+ },+ {+ name: '`--parallel`',+ description: 'Execute multiple independent tool calls in the same invocation.',+ },+ ],+ examples: [+ {+ code: "composio execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'",+ },+ {+ description: 'Inspect required inputs without executing',+ code: 'composio execute GITHUB_CREATE_AN_ISSUE --get-schema',+ },+ {+ description: 'Preview safely',+ code: 'composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d \'{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }\'',+ },+ {+ description: 'Pass data from a file or stdin',+ code: 'composio execute GITHUB_CREATE_AN_ISSUE -d @issue.json\ncat issue.json | composio execute GITHUB_CREATE_AN_ISSUE -d -',+ },+ {+ description: 'Upload a local file',+ code: 'composio execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK \\\n --file ./image.png \\\n -d \'{ channels: "C123" }\'',+ },+ {+ description: 'Run independent tool calls in parallel',+ code: 'composio execute --parallel \\\n GMAIL_SEND_EMAIL -d \'{ recipient_email: "[email protected]", subject: "Hi" }\' \\\n GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\'',+ },+ ],+ notes: [+ '`--file` only works when the tool exposes a single uploadable file input. Otherwise use explicit `-d` JSON.',+ ],+ },+ {+ id: 'search',+ title: '`search` - Find The Slug',+ summary: 'Use `search` only when the tool slug is not already known.',+ examples: [+ {+ code: 'composio search "create a github issue"\ncomposio search "send an email" --toolkits gmail\ncomposio search "send an email" "create a github issue"\ncomposio search "my emails" "my github issues" --toolkits gmail,github',+ },+ ],+ notes: [+ 'Batch related discovery work into one `search` invocation, then move back to `execute` once the correct slugs are known.',+ ],+ },+ {+ id: 'link',+ title: '`link` - Connect An Account',+ summary:+ 'Use `link` when `execute` reports that a toolkit is not connected, or when the user explicitly wants to authorize an account.',+ examples: [+ {+ code: 'composio link gmail\ncomposio link googlecalendar --no-browser',+ },+ ],+ notes: ['Retry the original `execute` command after linking succeeds.'],+ },+ {+ id: 'listen',+ title: '`listen` - Subscribe To Trigger Events',+ features: [CLI_EXPERIMENTAL_FEATURES.LISTEN],+ summary:+ 'Use `listen` for temporary trigger subscriptions in consumer projects, especially when background agents should consume new event payloads from artifact files.',+ examples: [+ {+ code: "composio listen GMAIL_NEW_GMAIL_MESSAGE\ncomposio listen SLACK_RECEIVE_MESSAGE -p '{ trigger_config: { channel: \"C123\" } }'\ncomposio listen GMAIL_NEW_GMAIL_MESSAGE --stream\ncomposio listen GMAIL_NEW_GMAIL_MESSAGE --stream '.data.threadId'\ncomposio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 5m\ncomposio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5",+ },+ ],+ flags: [+ {+ name: '`-p/--params`',+ description:+ 'Provide only trigger config fields; connected account resolution is automatic.',+ },+ {+ name: '`--stream`',+ description: 'Print events inline, optionally narrowed to a JSON path.',+ },+ {+ name: '`--timeout` and `--max-events`',+ description: 'Stop long-running listeners cleanly.',+ },+ ],+ notes: [+ '`composio artifacts cwd` shows the current artifact root when saved payloads need inspection.',+ ],+ },+ {+ id: 'proxy',+ title: '`proxy` - Raw API Access',+ summary:+ 'Use `proxy` when a toolkit supports a raw API operation that is easier than finding a dedicated tool slug.',+ examples: [+ {+ code: 'composio proxy https://api.github.com/user --toolkit github --method GET </dev/null',+ },+ ],+ },+ {+ id: 'run',+ title: '`run` - Scripting, LLMs, and Programmatic Workflows',+ summary:+ 'For programmatic calls, loops, output plumbing, or anything beyond a single tool call, prefer `composio run`.',+ intro: [+ '`composio run` executes an inline ESM JavaScript/TypeScript snippet with authenticated `execute()`, `search()`, `proxy()`, and the experimental `experimental_subAgent()` helper pre-injected. No SDK setup required.',+ ],+ examples: [+ {+ description: 'Chain multiple tools',+ code: 'composio run \'\n const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");\n const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 1 });\n console.log({ login: me.data.login, fetchedEmails: !!emails.data });\n\'',+ },+ {+ description: 'Fan out with Promise.all',+ code: 'composio run \'\n const [me, emails] = await Promise.all([\n execute("GITHUB_GET_THE_AUTHENTICATED_USER"),\n execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),\n ]);\n console.log({ login: me.data.login, emailCount: emails.data.messages?.length });\n\'',+ },+ {+ description: 'Feed tool output into an LLM and get structured JSON back',+ code: 'composio run --logs-off \'\n const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 5 });\n const brief = await experimental_subAgent(\n `Summarize these emails and count them.\\n\\n${emails.prompt()}`,\n { schema: z.object({ summary: z.string(), count: z.number() }) }\n );\n console.log(brief.structuredOutput);\n\'',+ },+ ],+ notes: [+ 'Use top-level `execute --parallel` instead when the user only needs a few independent tool calls and does not need script logic.',+ ],+ },+ {+ id: 'auth',+ title: 'Auth',+ examples: [+ {+ code: 'composio whoami # check current session\ncomposio login # authenticate if whoami fails',+ },+ ],+ },+];++const defaultWorkflow = (build: SkillBuildContext) => {+ const lines = [+ '1. Start with `composio execute <slug>` whenever the slug is known.',+ '2. If several independent tool calls must happen at once, use `composio execute -p/--parallel` with repeated `<slug> -d <json>` groups.',+ '3. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.',+ '4. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.',+ '5. Reach for `composio search "<task>"` only when the slug is unknown. `search` accepts one or more queries, so batch related discovery work into a single command when useful.',+ ];++ if (build.experimentalFeatures[CLI_EXPERIMENTAL_FEATURES.LISTEN]) {+ lines.push(+ '6. If the CLI build enables the experimental `listen` feature, use it for temporary consumer-project trigger subscriptions.'+ );+ }++ return lines;+};++const referenceDocuments = [+ composioDevReference,+ powerUserExamplesReference,+ troubleshootingReference,+] as const;++const renderExample = (example: SkillExample) => {+ const lines = [];++ if (example.description) {+ lines.push(example.description + ':');+ }++ lines.push('```bash', example.code, '```');+ return lines.join('\n');+};++const renderCommand = (build: SkillBuildContext, command: SkillCommand) => {+ const lines: string[] = [`## ${command.title}`];++ if (command.summary) {+ lines.push('', command.summary);+ }++ for (const intro of command.intro ?? []) {+ lines.push('', intro);+ }++ const examples = (command.examples ?? []).filter(example => isEnabledForBuild(build, example));+ if (examples.length > 0) {+ for (const example of examples) {+ lines.push('', renderExample(example));+ }+ }++ const flags = (command.flags ?? []).filter(flag => isEnabledForBuild(build, flag));+ if (flags.length > 0) {+ lines.push('', 'Key flags:');+ for (const flag of flags) {+ lines.push(`- ${flag.name}: ${flag.description}`);+ }+ }++ for (const note of command.notes ?? []) {+ lines.push('', `- ${note}`);+ }++ for (const extra of (command.extraBody ?? []).filter(block => isEnabledForBuild(build, block))) {+ lines.push('', extra.markdown);+ }++ return lines.join('\n');+};++export const renderComposioCliSkill = (channel: SkillReleaseChannel) => {+ const build = resolveSkillBuildContext(channel);+ const lines: string[] = [+ '---',+ `name: ${frontmatter.name}`,+ `description: ${frontmatter.description}`,+ '---',+ '',+ '<!-- AUTO-GENERATED: edit skills-src/composio-cli/index.ts and rebuild -->',+ `<!-- release-channel: ${channel} -->`,+ '',+ '# Composio CLI',+ '',+ '## Default Workflow',+ '',+ ...defaultWorkflow(build),+ ];++ const enabledCommands = commands.filter(command => isEnabledForBuild(build, command));+ for (const command of enabledCommands) {+ lines.push('', renderCommand(build, command));+ }++ lines.push(+ '',+ '## Escalate Only When Needed',+ '',+ 'If the user is stuck on top-level commands or needs fallback inspection commands, load [references/troubleshooting.md](references/troubleshooting.md).',+ '',+ 'If the user explicitly asks about developer projects, auth configs, connected accounts, triggers, logs, orgs, or projects, load [references/composio-dev.md](references/composio-dev.md). `composio dev` is not the default end-user path.'+ );++ return lines.join('\n') + '\n';+};++export const renderReferenceFiles = (channel: SkillReleaseChannel) => {+ const build = resolveSkillBuildContext(channel);+ return Object.fromEntries(+ referenceDocuments.map(document => [+ `${document.slug}.md`,+ renderReferenceDocument(document, build),+ ])+ );+};++export const validateSkillSources = () => referenceDocuments.flatMap(validateReferenceDocument);++const copyDir = (sourceDir: string, targetDir: string) => {+ fs.mkdirSync(targetDir, { recursive: true });+ for (const entry of fs.readdirSync(sourceDir, { withFileTypes: true })) {+ const sourcePath = path.join(sourceDir, entry.name);+ const targetPath = path.join(targetDir, entry.name);++ if (entry.isDirectory()) {+ copyDir(sourcePath, targetPath);+ continue;+ }++ fs.copyFileSync(sourcePath, targetPath);+ }+};++export const buildComposioCliSkill = ({+ channel,+ outputRoot,+}: {+ channel: SkillReleaseChannel;+ outputRoot: string;+}) => {+ const skillOutputDir = path.join(outputRoot, 'composio-cli');+ fs.rmSync(skillOutputDir, { recursive: true, force: true });+ fs.mkdirSync(skillOutputDir, { recursive: true });++ fs.writeFileSync(path.join(skillOutputDir, 'SKILL.md'), renderComposioCliSkill(channel), 'utf8');++ const agentsSourceDir = path.join(sourceAssetsDir, 'agents');+ if (fs.existsSync(agentsSourceDir)) {+ copyDir(agentsSourceDir, path.join(skillOutputDir, 'agents'));+ }++ const referencesOutputDir = path.join(skillOutputDir, 'references');+ fs.mkdirSync(referencesOutputDir, { recursive: true });+ for (const [fileName, markdown] of Object.entries(renderReferenceFiles(channel))) {+ fs.writeFileSync(path.join(referencesOutputDir, fileName), markdown, 'utf8');+ }++ return skillOutputDir;+};diff --git a/ts/packages/cli/skills-src/composio-cli/reference-schema.ts b/ts/packages/cli/skills-src/composio-cli/reference-schema.tsnew file mode 100644index 000000000..fc73cae73--- /dev/null+++ b/ts/packages/cli/skills-src/composio-cli/reference-schema.ts@@ -0,0 +1,161 @@+import { CLI_EXPERIMENTAL_FEATURES } from '../../src/constants';++export type SkillReleaseChannel = 'beta' | 'stable';++export type SkillFeatureFlag =+ (typeof CLI_EXPERIMENTAL_FEATURES)[keyof typeof CLI_EXPERIMENTAL_FEATURES];++export type SkillBuildContext = {+ channel: SkillReleaseChannel;+ experimentalFeatures: Readonly<Record<SkillFeatureFlag, boolean>>;+};++export type FeatureScoped = {+ features?: SkillFeatureFlag[];+};++export type CommandSnippet = FeatureScoped & {+ code: string;+ description?: string;+};++export type ReferenceSection = FeatureScoped & {+ body?: string[];+ commands?: CommandSnippet[];+ title: string;+};++export type ReferenceDocument = {+ intro?: string[];+ slug: string;+ title: string;+ sections: ReferenceSection[];+};++const TOP_LEVEL_COMMANDS = new Set([+ 'artifacts',+ 'dev',+ 'execute',+ 'link',+ 'listen',+ 'login',+ 'logout',+ 'proxy',+ 'run',+ 'search',+ 'tools',+ 'whoami',+]);++export const resolveSkillBuildContext = (channel: SkillReleaseChannel): SkillBuildContext => ({+ channel,+ experimentalFeatures: {+ [CLI_EXPERIMENTAL_FEATURES.LISTEN]: channel === 'beta',+ },+});++const isEnabledForBuild = (build: SkillBuildContext, value?: FeatureScoped) =>+ !value?.features || value.features.every(feature => build.experimentalFeatures[feature]);++export const renderCommandSnippet = (snippet: CommandSnippet) => {+ const lines: string[] = [];++ if (snippet.description) {+ lines.push(snippet.description + ':');+ }++ lines.push('```bash', snippet.code, '```');+ return lines.join('\n');+};++export const renderReferenceDocument = (document: ReferenceDocument, build: SkillBuildContext) => {+ const lines = [`# ${document.title}`];++ for (const introLine of document.intro ?? []) {+ lines.push('', introLine);+ }++ for (const section of document.sections.filter(section => isEnabledForBuild(build, section))) {+ lines.push('', `## ${section.title}`);++ for (const bodyLine of section.body ?? []) {+ lines.push('', bodyLine);+ }++ for (const command of (section.commands ?? []).filter(command =>+ isEnabledForBuild(build, command)+ )) {+ lines.push('', renderCommandSnippet(command));+ }+ }++ return lines.join('\n') + '\n';+};++export const validateCommandSnippet = (snippet: CommandSnippet, documentSlug: string) => {+ const errors: string[] = [];+ const lines = snippet.code.split('\n');+ let inQuotedCommand = false;+ let expectingContinuation = false;++ for (const rawLine of lines) {+ const line = rawLine.trim();+ if (line.length === 0 || line.startsWith('#')) {+ continue;+ }++ if (inQuotedCommand) {+ const quoteCount = (line.match(/'/g) ?? []).length;+ if (line === "'" || quoteCount % 2 === 1) {+ inQuotedCommand = false;+ }+ continue;+ }++ if (expectingContinuation) {+ expectingContinuation = line.endsWith('\\');+ continue;+ }++ if (+ line.startsWith('cat ') ||+ line.startsWith('echo ') ||+ line.startsWith('source ') ||+ line.startsWith('export ')+ ) {+ continue;+ }++ if (!line.startsWith('composio ')) {+ errors.push(`[${documentSlug}] command must start with "composio": ${line}`);+ continue;+ }++ const normalized = line.endsWith('\\') ? line.slice(0, -1).trim() : line;+ const parts = normalized.split(/\s+/);+ const topLevel = parts[1];+ if (!TOP_LEVEL_COMMANDS.has(topLevel)) {+ errors.push(`[${documentSlug}] unknown top-level command "${topLevel}" in: ${normalized}`);+ }++ expectingContinuation = line.endsWith('\\');+ const singleQuoteCount = (line.match(/'/g) ?? []).length;+ if (singleQuoteCount % 2 === 1) {+ inQuotedCommand = true;+ }+ }++ return errors;+};++export const validateReferenceDocument = (document: ReferenceDocument) => {+ const errors: string[] = [];++ for (const section of document.sections) {+ for (const command of section.commands ?? []) {+ errors.push(...validateCommandSnippet(command, document.slug));+ }+ }++ return errors;+};diff --git a/ts/packages/cli/skills-src/composio-cli/references/composio-dev.ts b/ts/packages/cli/skills-src/composio-cli/references/composio-dev.tsnew file mode 100644index 000000000..140058254--- /dev/null+++ b/ts/packages/cli/skills-src/composio-cli/references/composio-dev.ts@@ -0,0 +1,69 @@+import type { ReferenceDocument } from '../reference-schema';++export const composioDevReference: ReferenceDocument = {+ slug: 'composio-dev',+ title: 'Composio Dev',+ intro: [+ 'Load this file only when the user explicitly needs developer-project workflows. Do not lead with `composio dev` for ordinary top-level CLI usage.',+ ],+ sections: [+ {+ title: 'Use `dev init` To Bind A Directory',+ body: [+ 'Use `composio dev init` when the user wants to attach the current directory to a developer project.',+ 'If later commands complain about missing developer project context, come back to `dev init`.',+ ],+ commands: [{ code: 'composio dev init -y --no-browser' }],+ },+ {+ title: 'Inspect Toolkits And Versions',+ body: ['Use toolkit commands to inspect developer-scoped capabilities:'],+ commands: [+ {+ code: 'composio dev toolkits list\ncomposio dev toolkits info github\ncomposio dev toolkits search "email"\ncomposio dev toolkits version github',+ },+ ],+ },+ {+ title: 'Manage Auth Configs',+ body: [+ 'Use auth-config commands when the user is configuring developer-project authentication behavior:',+ ],+ commands: [{ code: 'composio dev auth-configs list' }],+ },+ {+ title: 'Manage Connected Accounts',+ body: [+ 'Use developer connected-account commands when the user is working with developer-project users or auth-config-specific flows.',+ 'Top-level `composio link` is consumer-only. Use `dev connected-accounts link` for developer-project flows.',+ ],+ commands: [{ code: 'composio dev connected-accounts list' }],+ },+ {+ title: 'Work With Triggers',+ body: [+ 'Use trigger commands when the user is creating, inspecting, or listening to developer-project triggers.',+ ],+ commands: [+ {+ code: 'composio dev triggers list\ncomposio dev triggers info AGENT_MAIL_NEW_EMAIL_TRIGGER',+ },+ ],+ },+ {+ title: 'Inspect Logs',+ body: [+ 'Use logs when the user is debugging tool executions or trigger deliveries inside a developer project.',+ ],+ commands: [{ code: 'composio dev logs tools\ncomposio dev logs triggers' }],+ },+ {+ title: 'Switch Or Inspect Org And Project Context',+ body: [+ 'Use these commands when the user needs to confirm or change the active developer scope:',+ 'If the user only wants to connect and execute tools as an end user, return to the top-level workflow instead of staying in `composio dev`.',+ ],+ commands: [{ code: 'composio dev orgs list\ncomposio dev projects list' }],+ },+ ],+};diff --git a/ts/packages/cli/skills-src/composio-cli/references/power-user-examples.ts b/ts/packages/cli/skills-src/composio-cli/references/power-user-examples.tsnew file mode 100644index 000000000..297a18c68--- /dev/null+++ b/ts/packages/cli/skills-src/composio-cli/references/power-user-examples.ts@@ -0,0 +1,160 @@+import type { ReferenceDocument } from '../reference-schema';++export const powerUserExamplesReference: ReferenceDocument = {+ slug: 'power-user-examples',+ title: 'Power-User Examples',+ intro: [+ 'Load this file when the user needs more than one top-level command, wants to script workflows, or wants to use `experimental_subAgent()` inside `composio run`.',+ ],+ sections: [+ {+ title: 'Use `run` To Chain Tool Calls',+ body: [+ 'Fetch from multiple connected tools in one script:',+ 'If the user does not need script logic and just wants a few independent calls, prefer top-level parallel execute instead:',+ ],+ commands: [+ {+ code: `composio run '+ const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");+ const emails = await execute("GMAIL_FETCH_EMAILS", {+ max_results: 2,+ });++ console.log({+ login: me.data.login,+ emailCount: Array.isArray(emails.data?.messages) ? emails.data.messages.length : null,+ });+'`,+ },+ {+ code: `composio execute --parallel \\+ GMAIL_FETCH_EMAILS -d '{ max_results: 2 }' \\+ GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'`,+ },+ ],+ },+ {+ title: 'Use `Promise.all` To Fan Out',+ body: ['Fetch from multiple services at once:'],+ commands: [+ {+ code: `composio run '+ const [me, emails] = await Promise.all([+ execute("GITHUB_GET_THE_AUTHENTICATED_USER"),+ execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),+ ]);++ console.log({+ login: me.data.login,+ emailCount: emails.data.messages?.length ?? null,+ });+'`,+ },+ ],+ },+ {+ title: 'Use `search()` Before `execute()` Inside A Script',+ body: [+ 'Discover a candidate slug, then execute it:',+ 'Batch related discovery work with multiple queries when it keeps the workflow simpler:',+ ],+ commands: [+ {+ code: `composio run '+ const results = await search("get the authenticated github user", {+ toolkits: "github",+ limit: 1,+ });++ const slug = results.results?.[0]?.primary_tool_slugs?.[0];+ if (!slug) throw new Error("No candidate tool found.");++ const output = await execute(slug);++ console.log(output.data.login);+'`,+ },+ {+ code: 'composio search "send an email" "create a github issue" --toolkits gmail,github',+ },+ ],+ },+ {+ title: 'Use `experimental_subAgent()` With `z` And `result.prompt()`',+ body: [+ 'Turn a tool result into structured output:',+ 'Use `result.prompt()` when the helper result is too noisy for a raw object dump but you still want to feed it into `experimental_subAgent()`.',+ ],+ commands: [+ {+ code: `composio run --logs-off '+ const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 2 });++ const brief = await experimental_subAgent(+ \`Return only valid JSON matching the schema. Summarize these emails in one sentence and report how many items were returned.\\n\\n\${emails.prompt()}\`,+ {+ schema: z.object({+ summary: z.string(),+ count: z.number(),+ }),+ }+ );++ console.log(brief.structuredOutput);+'`,+ },+ ],+ },+ {+ title: 'Use `proxy()` For Raw API Access',+ body: [+ '`proxy(toolkit)` returns a fetch-compatible function bound to the connected account. Name it like `fetch` if that keeps the script clearer. It returns a real `Response`, so call `.json()` or `.text()`.',+ ],+ commands: [+ {+ code: `composio run '+ const fetch = await proxy("github");+ const profile = await (await fetch("https://api.github.com/user")).json();+ console.log(profile);+'`,+ },+ ],+ },+ {+ title: 'Mix `execute()` And `proxy()`',+ body: [+ 'Use dedicated tools where they exist, then drop down to raw API calls for the missing step:',+ ],+ commands: [+ {+ code: `composio run '+ const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");++ const fetch = await proxy("github");+ const repos = await (await fetch("https://api.github.com/user/repos?per_page=3")).json();++ console.log({+ login: me.data.login,+ repoCount: Array.isArray(repos) ? repos.length : null,+ });+'`,+ },+ ],+ },+ {+ title: 'Use `run` Flags Intentionally',+ body: [+ '- Use `--dry-run` to preview every `execute()` call in the script.',+ '- Use `--debug` to see helper steps while the script runs.',+ '- Use `--logs-off` when `experimental_subAgent()` streaming logs are too noisy for the task.',+ 'Example:',+ ],+ commands: [+ {+ code: `composio run --dry-run --debug 'await execute("GITHUB_CREATE_AN_ISSUE", { owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." })'`,+ },+ ],+ },+ ],+};diff --git a/ts/packages/cli/skills-src/composio-cli/references/troubleshooting.ts b/ts/packages/cli/skills-src/composio-cli/references/troubleshooting.tsnew file mode 100644index 000000000..81b22f3b5--- /dev/null+++ b/ts/packages/cli/skills-src/composio-cli/references/troubleshooting.ts@@ -0,0 +1,120 @@+import type { ReferenceDocument } from '../reference-schema';++export const troubleshootingReference: ReferenceDocument = {+ slug: 'troubleshooting',+ title: 'Troubleshooting',+ intro: ['Load this file when the user is stuck on top-level Composio CLI flows.'],+ sections: [+ {+ title: 'Not Logged In',+ body: [+ 'Symptoms:',+ '- `composio` commands fail because there is no user session',+ '- the user is unsure which account the CLI is using',+ 'Fix:',+ 'If `composio whoami` fails, run `composio login` and then return to the original `execute` or `search` flow.',+ ],+ commands: [{ code: 'composio whoami' }],+ },+ {+ title: 'No Active Connection Found',+ body: [+ 'Symptoms:',+ '- `execute` reports that no active connection exists for a toolkit',+ 'Fix:',+ 'After linking, retry the exact same `execute` command.',+ ],+ commands: [+ {+ code: 'composio link gmail --no-browser --no-wait\ncomposio link googlecalendar --no-browser --no-wait',+ },+ ],+ },+ {+ title: 'Invalid JSON Input',+ body: [+ 'Symptoms:',+ '- `execute` rejects `-d` input',+ '- the payload is not valid JSON or JS-style object syntax',+ 'Fix:',+ '- Pass JSON or a JS-style object literal to `-d`',+ '- Use `@file` for large payloads',+ '- Use `-` to read from stdin',+ 'Examples:',+ ],+ commands: [+ {+ code: `composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{"owner":"acme","repo":"app","title":"Bug report","body":"Steps to reproduce..."}'+composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'+composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d @payload.json+cat payload.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d -`,+ },+ ],+ },+ {+ title: 'Unknown Or Wrong Slug',+ body: [+ 'Symptoms:',+ '- the user does not know the tool slug',+ '- the slug exists but is not the right tool for the job',+ 'Fix:',+ 'Use multiple queries in one `search` call when the user is exploring several related tasks at once. Use `composio tools list <toolkit>` only when the user already knows the toolkit and needs to browse the available slugs manually.',+ ],+ commands: [+ {+ code: 'composio search "create a github issue"\ncomposio search "send an email" --toolkits gmail\ncomposio search "send an email" "create a github issue"',+ },+ ],+ },+ {+ title: 'Confusion About Required Inputs',+ body: [+ 'Symptoms:',+ '- the user is unsure what fields a tool accepts',+ '- the first payload attempt failed validation',+ 'Fix:',+ 'Use `composio tools info <slug>` only when the user wants a compact summary of a known slug and the `execute --get-schema` output is still not enough.',+ ],+ commands: [+ {+ code: `composio execute GITHUB_CREATE_AN_ISSUE --get-schema -d '{}'\ncomposio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'`,+ },+ ],+ },+ {+ title: 'Several Independent Tool Calls',+ body: [+ 'Symptoms:',+ '- the user wants to run multiple unrelated tools in one step',+ '- the user is about to write a script only to execute a few independent calls',+ 'Fix:',+ 'Escalate to `composio run` only when the user needs control flow, loops, `Promise.all`, `search()` inside a script, `proxy()`, or `experimental_subAgent()`.',+ ],+ commands: [+ {+ code: `composio execute --parallel \\\n GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]", subject: "Hi" }' \\\n GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,+ },+ ],+ },+ {+ title: '`tools info` And `tools list` Are Fallbacks',+ body: [+ 'Treat these commands as secondary inspection tools:',+ 'Do not lead with them when `execute`, `search`, `--get-schema`, or `--dry-run` can get the user unstuck faster.',+ ],+ commands: [{ code: 'composio tools info GMAIL_SEND_EMAIL\ncomposio tools list gmail' }],+ },+ {+ title: 'Consumer Vs `composio dev`',+ body: [+ 'Use the top-level commands for normal end-user flows:',+ '- `composio execute`',+ '- `composio search`',+ '- `composio link`',+ '- `composio run`',+ '- `composio proxy`',+ 'Load [composio-dev.md](composio-dev.md) only when the user explicitly needs developer projects, auth configs, connected accounts, triggers, logs, orgs, or projects.',+ ],+ },+ ],+};diff --git a/ts/packages/cli/skills/composio-cli/SKILL.md b/ts/packages/cli/skills/composio-cli/SKILL.mddeleted file mode 100644index b6240aa93..000000000--- a/ts/packages/cli/skills/composio-cli/SKILL.md+++ /dev/null@@ -1,167 +0,0 @@-----name: composio-cli-description: Help users operate the published Composio CLI to find the right tool, connect accounts, inspect schemas, execute tools, subscribe to trigger events with `composio listen`, script workflows with `composio run`, and call authenticated app APIs with `composio proxy`. Use when the user asks how to do something with `composio`, wants to run a known tool slug, needs to discover a slug with `composio search`, fix a missing connection with `composio link`, inspect tool inputs with `--get-schema` or `--dry-run`, troubleshoot top-level CLI flows, or explicitly needs `composio dev` guidance.------# Composio CLI--## Default Workflow--1. Start with `composio execute <slug>` whenever the slug is known.-2. If several independent tool calls must happen at once, use `composio execute -p/--parallel` with repeated `<slug> -d <json>` groups.-3. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.-4. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.-5. Reach for `composio search "<task>"` only when the slug is unknown. `search` accepts one or more queries, so batch related discovery work into a single command when useful.--## `execute` — Run A Tool--```bash-composio execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'-```--Inspect required inputs without executing:--```bash-composio execute GITHUB_CREATE_AN_ISSUE --get-schema-```--Preview safely:--```bash-composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'-```--Pass data from a file or stdin:--```bash-composio execute GITHUB_CREATE_AN_ISSUE -d @issue.json-cat issue.json | composio execute GITHUB_CREATE_AN_ISSUE -d --```--Upload a local file when the tool has a single `file_uploadable` input:--```bash-composio execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK \- --file ./image.png \- -d '{ channels: "C123" }'-```--`--file` injects the local path into the tool's single uploadable file field. If a tool has no uploadable file input, or has more than one, use explicit `-d` JSON instead.--Run independent tool calls in parallel:--```bash-composio execute --parallel \- GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]", subject: "Hi" }' \- GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'-```--## `search` — Find The Slug--```bash-composio search "create a github issue"-composio search "send an email" --toolkits gmail-composio search "send an email" "create a github issue"-composio search "my emails" "my github issues" --toolkits gmail,github-```--Use multiple quoted queries when the user is exploring more than one task or a small cross-app workflow. Read the returned slugs, choose the best match, and move back to `execute`.--## `link` — Connect An Account--Use `link` when `execute` reports the toolkit is not connected, or the user wants to authorize an account.--```bash-composio link gmail-composio link googlecalendar --no-browser-```--After linking, retry the original `execute` command.--## `listen` — Subscribe To Trigger Events--Use `composio listen` when the user wants a temporary subscription for consumer-project events, especially for background agents that should consume new emails, Slack messages, or similar trigger payloads from artifact files.--The command creates a temporary trigger, subscribes to it, writes each event to the artifact folder, and disables the trigger on cleanup.--```bash-composio listen GMAIL_NEW_GMAIL_MESSAGE-composio listen SLACK_RECEIVE_MESSAGE -p '{ trigger_config: { channel: "C123" } }'-composio listen GMAIL_NEW_GMAIL_MESSAGE --stream-composio listen GMAIL_NEW_GMAIL_MESSAGE --stream '.data.threadId'-composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 5m-composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5-```--Key points:--- `-p/--params` is only for trigger config fields; the connected account is resolved automatically.-- `--stream` prints each event inline, and `--stream '.path.here'` prints only the selected field.-- `--timeout` and `--max-events` are the normal ways to stop long-running listeners cleanly.-- `composio artifacts cwd` shows the current artifact root when the user needs to inspect saved event payloads.--## `proxy` — Raw API Access--Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.--```bash-composio proxy https://api.github.com/user --toolkit github --method GET </dev/null-```--## `run` — Scripting, LLMs, and Programmatic Workflows--> **For programmatic calls, LLM workflows, or anything beyond a single tool call — use `composio run`.**--`composio run` executes an inline ESM JavaScript/Typescript (bun compatible) snippet with authenticated `execute()`, `search()`, `proxy()`, and the experimental `experimental_subAgent()` helper pre-injected. No SDK setup required.--Chain multiple tools:--```bash-composio run '- const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");- const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 1 });- console.log({ login: me.data.login, fetchedEmails: !!emails.data });-'-```--Use top-level `execute --parallel` when the user just needs a few independent tool calls and does not need script logic, loops, or output plumbing.--Fan out with `Promise.all`:--```bash-composio run '- const [me, emails] = await Promise.all([- execute("GITHUB_GET_THE_AUTHENTICATED_USER"),- execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),- ]);- console.log({ login: me.data.login, emailCount: emails.data.messages?.length });-'-```--Feed tool output into an LLM and get structured JSON back:--```bash-composio run --logs-off '- const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 5 });- const brief = await experimental_subAgent(- `Summarize these emails and count them.\n\n${emails.prompt()}`,- { schema: z.object({ summary: z.string(), count: z.number() }) }- );- console.log(brief.structuredOutput);-'-```--For more patterns — multi-query top-level `search`, `proxy()` inside scripts, mixed `execute()` + `proxy()`, and `--dry-run`/`--debug` flags — load [references/power-user-examples.md](references/power-user-examples.md).--## Auth--```bash-composio whoami # check current session-composio login # authenticate if whoami fails-```--## Escalate Only When Needed--If the user is stuck on top-level commands or needs fallback inspection commands, load [references/troubleshooting.md](references/troubleshooting.md).--If the user explicitly asks about developer projects, auth configs, connected accounts, triggers, logs, orgs, or projects, load [references/composio-dev.md](references/composio-dev.md). `composio dev` is not the default end-user path.diff --git a/ts/packages/cli/skills/composio-cli/references/composio-dev.md b/ts/packages/cli/skills/composio-cli/references/composio-dev.mddeleted file mode 100644index e460b30df..000000000--- a/ts/packages/cli/skills/composio-cli/references/composio-dev.md+++ /dev/null@@ -1,71 +0,0 @@-# Composio Dev--Load this file only when the user explicitly needs developer-project workflows. Do not lead with `composio dev` for ordinary top-level CLI usage.--## Use `dev init` To Bind A Directory--Use `composio dev init` when the user wants to attach the current directory to a developer project.--```bash-composio dev init -y --no-browser-```--If later commands complain about missing developer project context, come back to `dev init`.--## Inspect Toolkits And Versions--Use toolkit commands to inspect developer-scoped capabilities:--```bash-composio dev toolkits list-composio dev toolkits info github-composio dev toolkits search "email"-composio dev toolkits version github-```--## Manage Auth Configs--Use auth-config commands when the user is configuring developer-project authentication behavior:--```bash-composio dev auth-configs list-```--## Manage Connected Accounts--Use developer connected-account commands when the user is working with developer-project users or auth-config-specific flows.--```bash-composio dev connected-accounts list-```--Top-level `composio link` is consumer-only. Use `dev connected-accounts link` for developer-project flows.--## Work With Triggers--Use trigger commands when the user is creating, inspecting, or listening to developer-project triggers.--```bash-composio dev triggers list-composio dev triggers info AGENT_MAIL_NEW_EMAIL_TRIGGER-```--## Inspect Logs--Use logs when the user is debugging tool executions or trigger deliveries inside a developer project.--```bash-composio dev logs tools-composio dev logs triggers-```--## Switch Or Inspect Org And Project Context--Use these commands when the user needs to confirm or change the active developer scope:--```bash-composio dev orgs list-composio dev projects list-```--If the user only wants to connect and execute tools as an end user, return to the top-level workflow instead of staying in `composio dev`.diff --git a/ts/packages/cli/skills/composio-cli/references/power-user-examples.md b/ts/packages/cli/skills/composio-cli/references/power-user-examples.mddeleted file mode 100644index 44b5b2726..000000000--- a/ts/packages/cli/skills/composio-cli/references/power-user-examples.md+++ /dev/null@@ -1,139 +0,0 @@-# Power-User Examples--Load this file when the user needs more than one top-level command, wants to script workflows, or wants to use `experimental_subAgent()` inside `composio run`.--## Use `run` To Chain Tool Calls--Fetch from multiple connected tools in one script:--```bash-composio run '- const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");- const emails = await execute("GMAIL_FETCH_EMAILS", {- max_results: 2,- });-- console.log({- login: me.data.login,- emailCount: Array.isArray(emails.data?.messages) ? emails.data.messages.length : null,- });-'-```--If the user does not need script logic and just wants a few independent calls, prefer top-level parallel execute instead:--```bash-composio execute --parallel \- GMAIL_FETCH_EMAILS -d '{ max_results: 2 }' \- GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'-```--## Use `Promise.all` To Fan Out--Fetch from multiple services at once:--```bash-composio run '- const [me, emails] = await Promise.all([- execute("GITHUB_GET_THE_AUTHENTICATED_USER"),- execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),- ]);-- console.log({- login: me.data.login,- emailCount: emails.data.messages?.length ?? null,- });-'-```--## Use `search()` Before `execute()` Inside A Script--Discover a candidate slug, then execute it:--```bash-composio run '- const results = await search("get the authenticated github user", {- toolkits: "github",- limit: 1,- });-- const slug = results.results?.[0]?.primary_tool_slugs?.[0];- if (!slug) throw new Error("No candidate tool found.");-- const output = await execute(slug);-- console.log(output.data.login);-'-```--Batch related discovery work with multiple queries when it keeps the workflow simpler:--```bash-composio search "send an email" "create a github issue" --toolkits gmail,github-```--## Use `experimental_subAgent()` With `z` And `result.prompt()`--Turn a tool result into structured output:--```bash-composio run --logs-off '- const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 2 });-- const brief = await experimental_subAgent(- `Return only valid JSON matching the schema. Summarize these emails in one sentence and report how many items were returned.\n\n${emails.prompt()}`,- {- schema: z.object({- summary: z.string(),- count: z.number(),- }),- }- );-- console.log(brief.structuredOutput);-'-```--Use `result.prompt()` when the helper result is too noisy for a raw object dump but you still want to feed it into `experimental_subAgent()`.--## Use `proxy()` For Raw API Access--`proxy(toolkit)` returns a fetch-compatible function bound to the connected account. Name it like `fetch` if that keeps the script clearer. It returns a real `Response`, so call `.json()` or `.text()`.--```bash-composio run '- const fetch = await proxy("github");- const profile = await (await fetch("https://api.github.com/user")).json();- console.log(profile);-'-```--## Mix `execute()` And `proxy()`--Use dedicated tools where they exist, then drop down to raw API calls for the missing step:--```bash-composio run '- const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");-- const fetch = await proxy("github");- const repos = await (await fetch("https://api.github.com/user/repos?per_page=3")).json();-- console.log({- login: me.data.login,- repoCount: Array.isArray(repos) ? repos.length : null,- });-'-```--## Use `run` Flags Intentionally--- Use `--dry-run` to preview every `execute()` call in the script.-- Use `--debug` to see helper steps while the script runs.-- Use `--logs-off` when `experimental_subAgent()` streaming logs are too noisy for the task.--Example:--```bash-composio run --dry-run --debug 'await execute("GITHUB_CREATE_AN_ISSUE", { owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." })'-```diff --git a/ts/packages/cli/skills/composio-cli/references/troubleshooting.md b/ts/packages/cli/skills/composio-cli/references/troubleshooting.mddeleted file mode 100644index 101e2f853..000000000--- a/ts/packages/cli/skills/composio-cli/references/troubleshooting.md+++ /dev/null@@ -1,128 +0,0 @@-# Troubleshooting--Load this file when the user is stuck on top-level Composio CLI flows.--## Not Logged In--Symptoms:--- `composio` commands fail because there is no user session-- the user is unsure which account the CLI is using--Fix:--```bash-composio whoami-```--If `composio whoami` fails, run `composio login` and then return to the original `execute` or `search` flow.--## No Active Connection Found--Symptoms:--- `execute` reports that no active connection exists for a toolkit--Fix:--```bash-composio link gmail --no-browser --no-wait-composio link googlecalendar --no-browser --no-wait-```--After linking, retry the exact same `execute` command.--## Invalid JSON Input--Symptoms:--- `execute` rejects `-d` input-- the payload is not valid JSON or JS-style object syntax--Fix:--- Pass JSON or a JS-style object literal to `-d`-- Use `@file` for large payloads-- Use `-` to read from stdin--Examples:--```bash-composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{"owner":"acme","repo":"app","title":"Bug report","body":"Steps to reproduce..."}'-composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'-composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d @payload.json-cat payload.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d --```--## Unknown Or Wrong Slug--Symptoms:--- the user does not know the tool slug-- the slug exists but is not the right tool for the job--Fix:--```bash-composio search "create a github issue"-composio search "send an email" --toolkits gmail-composio search "send an email" "create a github issue"-```--Use multiple queries in one `search` call when the user is exploring several related tasks at once. Use `composio tools list <toolkit>` only when the user already knows the toolkit and needs to browse the available slugs manually.--## Confusion About Required Inputs--Symptoms:--- the user is unsure what fields a tool accepts-- the first payload attempt failed validation--Fix:--```bash-composio execute GITHUB_CREATE_AN_ISSUE --get-schema -d '{}'-composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'-```--Use `composio tools info <slug>` only when the user wants a compact summary of a known slug and the `execute --get-schema` output is still not enough.--## Several Independent Tool Calls--Symptoms:--- the user wants to run multiple unrelated tools in one step-- the user is about to write a script only to execute a few independent calls--Fix:--```bash-composio execute --parallel \- GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]", subject: "Hi" }' \- GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'-```--Escalate to `composio run` only when the user needs control flow, loops, `Promise.all`, `search()` inside a script, `proxy()`, or `experimental_subAgent()`.--## `tools info` And `tools list` Are Fallbacks--Treat these commands as secondary inspection tools:--```bash-composio tools info GMAIL_SEND_EMAIL-composio tools list gmail-```--Do not lead with them when `execute`, `search`, `--get-schema`, or `--dry-run` can get the user unstuck faster.--## Consumer Vs `composio dev`--Use the top-level commands for normal end-user flows:--- `composio execute`-- `composio search`-- `composio link`-- `composio run`-- `composio proxy`--Load [composio-dev.md](composio-dev.md) only when the user explicitly needs developer projects, auth configs, connected accounts, triggers, logs, orgs, or projects.diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.tsindex b6960e665..9335b7dc0 100644--- a/ts/packages/cli/src/commands/index.ts+++ b/ts/packages/cli/src/commands/index.ts@@ -37,9 +37,10 @@ import {formatResolveCommandProjectError,resolveCommandProject,} from 'src/services/command-project';+import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';import {- type CommandVisibility,experimental,+ type CommandVisibility,type TaggedValue,tagged,visibleValues,@@ -51,7 +52,7 @@ const ROOT_COMMANDS: ReadonlyArray<TaggedValue<Command.Command<any, any, any, antagged(upgradeCmd),tagged(whoamiCmd),tagged(loginCmd),- experimental('listen', listenCmd),+ experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, listenCmd),tagged(logoutCmd),tagged(runCmd),tagged(proxyCmd),diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.tsindex ec627d356..be41a3ca5 100644--- a/ts/packages/cli/src/commands/login.cmd.ts+++ b/ts/packages/cli/src/commands/login.cmd.ts@@ -12,7 +12,8 @@ import { TerminalUI } from 'src/services/terminal-ui';import { commandHintStep } from 'src/services/command-hints';import { runOrgSelection } from 'src/effects/select-org-project';import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';-import { installSkillSafe } from 'src/effects/install-skill';+import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';+import { APP_VERSION } from 'src/constants';export const noBrowser = Options.boolean('no-browser').pipe(Options.withDefault(false),@@ -42,10 +43,7 @@ const noSkillInstall = Options.boolean('no-skill-install').pipe(Options.withDescription('Skip installing the composio-cli skill for Claude Code'));-const formatLoginSuccessMessage = (params: {- email?: string;- orgName?: string;-}): string => {+const formatLoginSuccessMessage = (params: { email?: string; orgName?: string }): string => {const { email, orgName } = params;if (email && orgName) {return `Logged in as ${email} in "${orgName}"`;@@ -482,7 +480,7 @@ export const loginCmd = Command.make(skipOrgProjectPicker: true,});if (!noSkillInstall) {- yield* installSkillSafe();+ yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });}return;}@@ -506,7 +504,7 @@ export const loginCmd = Command.make(});if (!noSkillInstall && !noWait) {- yield* installSkillSafe();+ yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });}})).pipe(Command.withDescription('Log in to the Composio SDK.'));diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.tsindex 0924a07b2..c965063d8 100644--- a/ts/packages/cli/src/commands/root-help.ts+++ b/ts/packages/cli/src/commands/root-help.ts@@ -1,4 +1,5 @@-import { Console, Effect } from 'effect';+import { Console, Effect, Option } from 'effect';+import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';import { bold, dim, gray } from 'src/ui/colors';import {type CommandVisibility,@@ -79,10 +80,10 @@ const CORE_COMMANDS: ReadonlyArray<TaggedValue<DetailedCommand>> = [{ name: '--dry-run', description: 'Preview execute() calls without running remote actions' },],}),- experimental('listen', {+ experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, {name: 'listen',description:- 'Listen to consumer-project realtime events and persist each payload into the session artifact folder.',+ 'Create a temporary subscription for consumer-project events and persist each payload into the session artifact folder.',usage:'listen <slug> [-p, --params text] [--max-events integer] [--timeout text] [--stream [text]]',options: [@@ -207,7 +208,7 @@ type SubcommandHelp = {seeAlso?: ReadonlyArray<string>;};-const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {+const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHelp>> = {search: {usage: 'composio search <query...> [--toolkits text] [--limit integer] [--human]',description:@@ -314,23 +315,17 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {'composio artifacts cwd Print the current session artifact directory',],},- listen: {+ listen: experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, {usage:'composio listen <slug> [-p, --params text] [--max-events integer] [--timeout text] [--stream [text]]',description:- 'Listen to consumer-project realtime events. Trigger slugs create a temporary trigger; top-level composio.* event types subscribe directly.',- args: [- {- name: '<slug>',- description:- 'Trigger slug to create and listen to, or a project event type such as "composio.connected_account.expired"',- },- ],+ '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. Only valid for trigger slugs.',+ 'Trigger create params as JSON/JS object, @file, or - for stdin. Pass optional trigger config fields only.',},{name: '--max-events <integer>',@@ -352,7 +347,6 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {'composio listen GMAIL_NEW_GMAIL_MESSAGE --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 composio.connected_account.expired --max-events 1','composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream',"composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",],@@ -361,7 +355,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {'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]',description:@@ -943,6 +937,28 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {},};+const getVisibleSubcommandHelp = (+ cmd: string,+ visibility: CommandVisibility+): Option.Option<SubcommandHelp> => {+ const entry = SUBCOMMAND_HELP[cmd];+ if (!entry) {+ return Option.none();+ }++ if (!('value' in entry)) {+ return Option.some(entry);+ }++ if (!entry.tags || entry.tags.length === 0) {+ return Option.some(entry.value);+ }++ return entry.tags.every(tag => visibility.isExperimentalFeatureEnabled(tag))+ ? Option.some(entry.value)+ : Option.none();+};+function renderSubcommandHelp(cmd: SubcommandHelp): string {const lines: string[] = ['',@@ -1012,7 +1028,7 @@ function renderSubcommandHelp(cmd: SubcommandHelp): string {*/export function matchSubcommandHelp(argv: ReadonlyArray<string>,- _visibility: CommandVisibility+ visibility: CommandVisibility): string | undefined {const args = argv.slice(2);if (args.length < 2) return undefined;@@ -1023,18 +1039,18 @@ export function matchSubcommandHelp(// 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 (key in SUBCOMMAND_HELP) return key;+ if (Option.isSome(getVisibleSubcommandHelp(key, visibility))) return key;}return undefined;}export function printSubcommandHelp(cmd: string,- _visibility: CommandVisibility+ visibility: CommandVisibility): Effect.Effect<void> {- const help = SUBCOMMAND_HELP[cmd];- if (!help) return Console.log(`Unknown command: ${cmd}`);- return Console.log(renderSubcommandHelp(help));+ const help = getVisibleSubcommandHelp(cmd, visibility);+ if (Option.isNone(help)) return Console.log(`Unknown command: ${cmd}`);+ return Console.log(renderSubcommandHelp(help.value));}/**@@ -1043,13 +1059,13 @@ export function printSubcommandHelp(*/export function matchCommandFromArgv(argv: ReadonlyArray<string>,- _visibility: CommandVisibility+ visibility: CommandVisibility): string | undefined {const args = argv.slice(2).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 (key in SUBCOMMAND_HELP) return key;+ if (Option.isSome(getVisibleSubcommandHelp(key, visibility))) return key;}return undefined;}@@ -1057,13 +1073,11 @@ export function matchCommandFromArgv(/*** Get rendered help text for a command, or undefined if not found.*/-export function getCommandHelpText(- cmd: string,- _visibility: CommandVisibility-): string | undefined {- const help = SUBCOMMAND_HELP[cmd];- if (!help) return undefined;- return renderSubcommandHelp(help);+export function getCommandHelpText(cmd: string, visibility: CommandVisibility): string | undefined {+ return Option.match(getVisibleSubcommandHelp(cmd, visibility), {+ onNone: () => undefined,+ onSome: help => renderSubcommandHelp(help),+ });}// ── Main help output ───────────────────────────────────────────────────diff --git a/ts/packages/cli/src/commands/upgrade.cmd.ts b/ts/packages/cli/src/commands/upgrade.cmd.tsindex d769b2f3b..26f883521 100644--- a/ts/packages/cli/src/commands/upgrade.cmd.ts+++ b/ts/packages/cli/src/commands/upgrade.cmd.ts@@ -22,6 +22,8 @@ export const upgradeCmd = Command.make('upgrade', { beta: betaOpt }, ({ beta })Effect.gen(function* () {const upgradeBinary = yield* UpgradeBinary;const newReleaseTag = yield* upgradeBinary.upgrade({ prerelease: beta });- yield* installSkillSafe({ releaseTag: newReleaseTag ?? `@composio/cli@${APP_VERSION}` });+ yield* installSkillSafe({+ releaseTag: newReleaseTag ?? `@composio/cli@${APP_VERSION}`,+ });})).pipe(Command.withDescription('Upgrade your Composio CLI to the latest available version.'));diff --git a/ts/packages/cli/src/constants.ts b/ts/packages/cli/src/constants.tsindex c3a29bc39..61d4c9dc5 100644--- a/ts/packages/cli/src/constants.ts+++ b/ts/packages/cli/src/constants.ts@@ -85,3 +85,7 @@ export const GITHUB_REPO = {REPO: 'composio',API_BASE_URL: 'https://api.github.com',} as const;++export const CLI_EXPERIMENTAL_FEATURES = {+ LISTEN: 'listen',+} as const;diff --git a/ts/packages/cli/src/effects/install-skill.ts b/ts/packages/cli/src/effects/install-skill.tsindex 3b4d1b14f..648fec32a 100644--- a/ts/packages/cli/src/effects/install-skill.ts+++ b/ts/packages/cli/src/effects/install-skill.ts@@ -6,10 +6,63 @@ import { NodeOs } from 'src/services/node-os';import { TerminalUI } from 'src/services/terminal-ui';import { GITHUB_CONFIG } from 'src/effects/github-config';import { APP_VERSION } from 'src/constants';+import {+ fetchLatestCliRelease,+ type GitHubRelease,+ type GitHubRepoConfig,+} from 'src/effects/resolve-cli-release';import decompress from 'decompress';const SKILL_NAME = 'composio-cli';const SKILL_ASSET_NAME = 'composio-skill.zip';+export type SkillReleaseChannel = 'beta' | 'stable';++type GitHubConfig = GitHubRepoConfig & {+ TAG: Option.Option<string>;+ ACCESS_TOKEN: Option.Option<string>;+};++const hasSkillAsset = (release: GitHubRelease) =>+ release.assets.some(asset => asset.name === SKILL_ASSET_NAME);++export const inferSkillReleaseChannel = (tagOrVersion: string): SkillReleaseChannel =>+ tagOrVersion.includes('-beta.') ? 'beta' : 'stable';++export const resolveSkillReleaseTag = ({+ channel,+ githubConfig,+ httpClient,+ releaseTag,+}: {+ channel?: SkillReleaseChannel;+ githubConfig: GitHubConfig;+ httpClient: HttpClient.HttpClient;+ releaseTag?: string;+}) =>+ Effect.gen(function* () {+ if (releaseTag) {+ return releaseTag;+ }++ const configTag = Option.getOrUndefined(githubConfig.TAG);+ if (configTag) {+ return configTag;+ }++ if (!channel) {+ return `@composio/cli@${APP_VERSION}`;+ }++ const latest = yield* fetchLatestCliRelease({+ assetDescription: SKILL_ASSET_NAME,+ channel,+ githubConfig,+ hasRequiredAsset: hasSkillAsset,+ httpClient,+ });++ return latest.tag_name;+ });/*** Install the composio-cli skill into the user's global agent skills directory.@@ -20,7 +73,10 @@ const SKILL_ASSET_NAME = 'composio-skill.zip';** Non-fatal: wrapped version catches all errors.*/-export const installSkill = (options?: { readonly releaseTag?: string }) =>+export const installSkill = (options?: {+ readonly releaseTag?: string;+ readonly channel?: SkillReleaseChannel;+}) =>Effect.gen(function* () {const os = yield* NodeOs;const ui = yield* TerminalUI;@@ -31,10 +87,12 @@ export const installSkill = (options?: { readonly releaseTag?: string }) =>const agentSkillDir = path.join(home, '.agents', 'skills', SKILL_NAME);const claudeSkillLink = path.join(home, '.claude', 'skills', SKILL_NAME);- // Resolve the release tag — prefer explicit override, then env config, then current version- const tag =- options?.releaseTag ??- Option.getOrElse(githubConfig.TAG, () => `@composio/cli@${APP_VERSION}`);+ const tag = yield* resolveSkillReleaseTag({+ channel: options?.channel,+ githubConfig,+ httpClient,+ releaseTag: options?.releaseTag,+ });// Find the skill asset URL from the releaseconst releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodeURIComponent(tag)}`;@@ -127,7 +185,10 @@ export const installSkill = (options?: { readonly releaseTag?: string }) =>/*** Wrapped version that catches all errors and logs a warning instead of failing.*/-export const installSkillSafe = (options?: { readonly releaseTag?: string }) =>+export const installSkillSafe = (options?: {+ readonly releaseTag?: string;+ readonly channel?: SkillReleaseChannel;+}) =>installSkill(options).pipe(Effect.sandbox,Effect.catchAll(cause =>diff --git a/ts/packages/cli/src/effects/resolve-cli-release.ts b/ts/packages/cli/src/effects/resolve-cli-release.tsnew file mode 100644index 000000000..687e64624--- /dev/null+++ b/ts/packages/cli/src/effects/resolve-cli-release.ts@@ -0,0 +1,98 @@+import { Effect } from 'effect';+import { HttpClient } from '@effect/platform';+import { semverComparator } from 'src/effects/compare-semver';++export type CliReleaseChannel = 'beta' | 'stable';++export type GitHubReleaseAsset = {+ name: string;+ browser_download_url: string;+};++export type GitHubRelease = {+ tag_name: string;+ prerelease?: boolean;+ draft?: boolean;+ assets: Array<GitHubReleaseAsset>;+};++export type GitHubRepoConfig = {+ API_BASE_URL: string;+ OWNER: string;+ REPO: string;+};++export const CLI_RELEASE_TAG_PATTERN = /^@composio\/cli@\d+\.\d+\.\d+.*$/;++export const fetchLatestCliRelease = ({+ assetDescription,+ channel,+ githubConfig,+ hasRequiredAsset,+ httpClient,+}: {+ assetDescription: string;+ channel: CliReleaseChannel;+ githubConfig: GitHubRepoConfig;+ hasRequiredAsset: (release: GitHubRelease) => boolean;+ httpClient: HttpClient.HttpClient;+}) =>+ Effect.gen(function* () {+ const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases?per_page=100`;+ const releaseResponse = yield* httpClient+ .get(releaseUrl)+ .pipe(+ Effect.catchAll(error =>+ Effect.fail(new Error(`Failed to fetch ${channel} releases from GitHub: ${error}`))+ )+ );++ if (releaseResponse.status < 200 || releaseResponse.status >= 300) {+ return yield* Effect.fail(+ new Error(+ `Failed to fetch ${channel} releases from GitHub (HTTP ${releaseResponse.status})`+ )+ );+ }++ const releases = (yield* releaseResponse.json.pipe(+ Effect.catchAll(() => Effect.fail(new Error('Failed to parse GitHub releases JSON')))+ )) as unknown;++ if (!Array.isArray(releases)) {+ return yield* Effect.fail(new Error('GitHub releases response was not an array'));+ }++ const prerelease = channel === 'beta';+ const matchingReleases = releases.filter(+ (release): release is GitHubRelease =>+ typeof release === 'object' &&+ release !== null &&+ 'tag_name' in release &&+ typeof release.tag_name === 'string' &&+ ('prerelease' in release ? release.prerelease === prerelease : prerelease === false) &&+ ('draft' in release ? release.draft === false : true) &&+ CLI_RELEASE_TAG_PATTERN.test(release.tag_name) &&+ Array.isArray(release.assets) &&+ hasRequiredAsset(release)+ );++ if (matchingReleases.length === 0) {+ return yield* Effect.fail(+ new Error(`No ${channel} CLI releases found with ${assetDescription}`)+ );+ }++ let latest = matchingReleases[0];+ for (const release of matchingReleases.slice(1)) {+ const comparison = yield* semverComparator(latest.tag_name, release.tag_name).pipe(+ Effect.mapError(error => new Error(`Failed to compare release versions: ${error}`))+ );++ if (comparison < 0) {+ latest = release;+ }+ }++ return latest;+ });diff --git a/ts/packages/cli/src/services/upgrade-binary.ts b/ts/packages/cli/src/services/upgrade-binary.tsindex 27c0d5773..076c9eb37 100644--- a/ts/packages/cli/src/services/upgrade-binary.ts+++ b/ts/packages/cli/src/services/upgrade-binary.ts@@ -6,6 +6,7 @@ import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';import { GITHUB_CONFIG } from 'src/effects/github-config';import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform';import { CompareSemverError, semverComparator } from 'src/effects/compare-semver';+import { fetchLatestCliRelease, type GitHubRelease } from 'src/effects/resolve-cli-release';// Note: `node:zlib` does not support Github's zip filesimport decompress from 'decompress';@@ -28,18 +29,6 @@ export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinary*/export const CLI_BINARY_NAME = 'composio';-type GitHubRelease = {- tag_name: string;- prerelease?: boolean;- draft?: boolean;- assets: Array<{- name: string;- browser_download_url: string;- }>;-};--const CLI_RELEASE_TAG_PATTERN = /^@composio\/cli@\d+\.\d+\.\d+.*$/;-const getBinaryAssetName = (platformArch: PlatformArch) =>`${CLI_BINARY_NAME}-${platformArch.platform}-${platformArch.arch}.zip`;@@ -122,78 +111,26 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upgyield* Effect.logDebug(`No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release`);- const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases?per_page=100`;- const releases = yield* fetchGitHubJson<unknown>({- url,- fetchErrorMessage: 'Failed to fetch releases from GitHub',- parseErrorMessage: 'Failed to parse GitHub releases JSON response',- });-- if (!Array.isArray(releases)) {- return yield* Effect.fail(- new UpgradeBinaryError({- cause: new Error('GitHub releases response was not an array'),- message: 'Unexpected response while resolving latest CLI release',- })- );- }-- const cliReleases = releases.filter(- (release): release is GitHubRelease =>- typeof release === 'object' &&- release !== null &&- 'tag_name' in release &&- typeof release.tag_name === 'string' &&- ('prerelease' in release- ? release.prerelease === prerelease- : prerelease === false) &&- ('draft' in release ? release.draft === false : true) &&- CLI_RELEASE_TAG_PATTERN.test(release.tag_name)- );-- if (cliReleases.length === 0) {- return yield* Effect.fail(- new UpgradeBinaryError({- cause: new Error(- `No package-scoped CLI ${prerelease ? 'beta' : 'stable'} releases found`- ),- message: `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,- })- );- }-- const cliReleasesWithBinary = cliReleases.filter(release =>- hasPlatformBinaryAsset(release, platformArch)+ const latest = yield* fetchLatestCliRelease({+ assetDescription: getBinaryAssetName(platformArch),+ channel: prerelease ? 'beta' : 'stable',+ githubConfig,+ hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch),+ httpClient,+ }).pipe(+ Effect.mapError(+ error =>+ new UpgradeBinaryError({+ cause: error,+ message: error.message.startsWith('Failed to fetch ')+ ? 'Failed to fetch releases from GitHub'+ : error.message === 'Failed to parse GitHub releases JSON'+ ? 'Failed to parse GitHub releases JSON response'+ : `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,+ })+ ));- if (cliReleasesWithBinary.length === 0) {- return yield* Effect.fail(- new UpgradeBinaryError({- cause: new Error(- `No package-scoped CLI ${prerelease ? 'beta' : 'stable'} releases found with ${getBinaryAssetName(platformArch)}`- ),- message: `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,- })- );- }-- let latest = cliReleasesWithBinary[0];- for (const release of cliReleasesWithBinary.slice(1)) {- const comparison = yield* semverComparator(latest.tag_name, release.tag_name).pipe(- Effect.mapError(- error =>- new UpgradeBinaryError({- cause: error,- message: 'Failed to compare CLI release versions',- })- )- );-- if (comparison < 0) {- latest = release;- }- }-yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);return latest;}),diff --git a/ts/packages/cli/test/src/commands/feature-visibility.test.ts b/ts/packages/cli/test/src/commands/feature-visibility.test.tsnew file mode 100644index 000000000..5fac96013--- /dev/null+++ b/ts/packages/cli/test/src/commands/feature-visibility.test.ts@@ -0,0 +1,45 @@+import { CommandDescriptor } from '@effect/cli';+import { HashMap } from 'effect';+import { describe, expect, it } from 'vitest';+import { buildRootCommand } from 'src/commands';+import {+ getCommandHelpText,+ matchCommandFromArgv,+ matchSubcommandHelp,+} from 'src/commands/root-help';++const stableVisibility = {+ isExperimentalFeatureEnabled: () => false,+};++const betaVisibility = {+ isExperimentalFeatureEnabled: () => true,+};++const getSubcommandNames = (visibility: typeof stableVisibility) =>+ HashMap.toEntries(CommandDescriptor.getSubcommands(buildRootCommand(visibility).descriptor)).map(+ ([name]) => name+ );++describe('CLI experimental feature visibility', () => {+ it('hides listen from the stable root command graph', () => {+ expect(getSubcommandNames(stableVisibility)).not.toContain('listen');+ expect(getSubcommandNames(betaVisibility)).toContain('listen');+ });++ it('hides listen help when the feature is disabled', () => {+ expect(matchSubcommandHelp(['bun', 'composio', 'listen', '--help'], stableVisibility)).toBe(+ undefined+ );+ expect(matchSubcommandHelp(['bun', 'composio', 'listen', '--help'], betaVisibility)).toBe(+ 'listen'+ );+ });++ it('hides contextual listen help when the feature is disabled', () => {+ expect(matchCommandFromArgv(['bun', 'composio', 'listen'], stableVisibility)).toBe(undefined);+ expect(matchCommandFromArgv(['bun', 'composio', 'listen'], betaVisibility)).toBe('listen');+ expect(getCommandHelpText('listen', stableVisibility)).toBe(undefined);+ expect(getCommandHelpText('listen', betaVisibility)).toContain('composio listen');+ });+});diff --git a/ts/packages/cli/test/src/effects/install-skill.test.ts b/ts/packages/cli/test/src/effects/install-skill.test.tsnew file mode 100644index 000000000..0766e80d1--- /dev/null+++ b/ts/packages/cli/test/src/effects/install-skill.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it, vi } from '@effect/vitest';+import { Config, ConfigProvider, Effect } from 'effect';+import { FetchHttpClient, HttpClient } from '@effect/platform';+import { withHttpServer } from 'test/__utils__/http-server';+import {+ inferSkillReleaseChannel,+ resolveSkillReleaseTag,+ type SkillReleaseChannel,+} from 'src/effects/install-skill';+import { GITHUB_CONFIG } from 'src/effects/github-config';++const makeResolveEffect = (+ configEntries: ReadonlyArray<[string, string]>,+ options: {+ channel?: SkillReleaseChannel;+ releaseTag?: string;+ } = {}+) =>+ Effect.gen(function* () {+ const httpClient = yield* HttpClient.HttpClient;+ const githubConfig = yield* Config.all(GITHUB_CONFIG);++ return yield* resolveSkillReleaseTag({+ channel: options.channel,+ githubConfig,+ httpClient,+ releaseTag: options.releaseTag,+ });+ }).pipe(+ Effect.provide(FetchHttpClient.layer),+ Effect.withConfigProvider(ConfigProvider.fromMap(new Map(configEntries))),+ Effect.scoped+ );++describe('install-skill', () => {+ it('infers the stable channel from stable versions', () => {+ expect(inferSkillReleaseChannel('0.2.19')).toBe('stable');+ expect(inferSkillReleaseChannel('@composio/[email protected]')).toBe('stable');+ });++ it('infers the beta channel from beta versions', () => {+ expect(inferSkillReleaseChannel('0.2.20-beta.4')).toBe('beta');+ expect(inferSkillReleaseChannel('@composio/[email protected]')).toBe('beta');+ });++ it('resolves the latest stable release when the stable channel is requested', async () => {+ vi.stubGlobal('Bun', { which: vi.fn(() => null) });++ try {+ await withHttpServer(+ (_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(+ JSON.stringify([+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: true,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/beta-skill.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: false,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/stable-skill.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: false,+ assets: [+ {+ name: 'composio-linux-x64.zip',+ browser_download_url: 'http://127.0.0.1/no-skill.zip',+ },+ ],+ },+ ])+ );+ },+ async apiBaseUrl => {+ const tag = await makeResolveEffect(+ [+ ['GITHUB_API_BASE_URL', apiBaseUrl],+ ['GITHUB_OWNER', 'test-owner'],+ ['GITHUB_REPO', 'test-repo'],+ ],+ { channel: 'stable' }+ ).pipe(Effect.runPromise);++ expect(tag).toBe('@composio/[email protected]');+ }+ );+ } finally {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ }+ });++ it('resolves the latest beta release when the beta channel is requested', async () => {+ vi.stubGlobal('Bun', { which: vi.fn(() => null) });++ try {+ await withHttpServer(+ (_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(+ JSON.stringify([+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: true,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/beta-1-skill.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: true,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/beta-3-skill.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: false,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/stable-skill.zip',+ },+ ],+ },+ ])+ );+ },+ async apiBaseUrl => {+ const tag = await makeResolveEffect(+ [+ ['GITHUB_API_BASE_URL', apiBaseUrl],+ ['GITHUB_OWNER', 'test-owner'],+ ['GITHUB_REPO', 'test-repo'],+ ],+ { channel: 'beta' }+ ).pipe(Effect.runPromise);++ expect(tag).toBe('@composio/[email protected]');+ }+ );+ } finally {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ }+ });+});diff --git a/ts/packages/cli/test/src/services/cli-user-config.test.ts b/ts/packages/cli/test/src/services/cli-user-config.test.tsindex 0e96c03ba..05e767797 100644--- a/ts/packages/cli/test/src/services/cli-user-config.test.ts+++ b/ts/packages/cli/test/src/services/cli-user-config.test.ts@@ -104,7 +104,6 @@ describe('ComposioCliUserConfig', () => {assertEquals(parsed.experimental_subagent.target, 'claude');}).pipe(Effect.provide(CliUserConfigTest));});-it.effect('resolves sync config path from COMPOSIO_CACHE_DIR when provided', () => {const cacheDir = tempy.temporaryDirectory();process.env.COMPOSIO_CACHE_DIR = cacheDir;diff --git a/ts/scripts/validate-examples.ts b/ts/scripts/validate-examples.tsnew file mode 100644index 000000000..739f7f468--- /dev/null+++ b/ts/scripts/validate-examples.ts@@ -0,0 +1,236 @@+import * as fs from 'node:fs';+import * as path from 'node:path';+import ts from 'typescript';++const repoRoot = process.cwd();+const examplesRoot = path.join(repoRoot, 'ts', 'examples');+const allowedSourceExtensions = new Set([+ '.cjs',+ '.cts',+ '.js',+ '.jsx',+ '.mjs',+ '.mts',+ '.ts',+ '.tsx',+ '.json',+]);++type ValidationIssue = {+ example: string;+ file: string;+ message: string;+};++const issues: ValidationIssue[] = [];++const addIssue = (example: string, file: string, message: string) => {+ issues.push({ example, file, message });+};++const collectFiles = (dir: string): string[] => {+ const entries = fs.readdirSync(dir, { withFileTypes: true });+ return entries.flatMap(entry => {+ const fullPath = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ return collectFiles(fullPath);+ }+ return [fullPath];+ });+};++const validatePackageJson = (exampleName: string, exampleDir: string) => {+ const packageJsonPath = path.join(exampleDir, 'package.json');++ if (!fs.existsSync(packageJsonPath)) {+ addIssue(exampleName, packageJsonPath, 'Missing package.json');+ return;+ }++ try {+ const raw = fs.readFileSync(packageJsonPath, 'utf8');+ const pkg = JSON.parse(raw) as {+ dependencies?: Record<string, string>;+ devDependencies?: Record<string, string>;+ name?: string;+ packageManager?: string;+ private?: boolean;+ scripts?: Record<string, string>;+ };++ if (!pkg.name?.endsWith('-example')) {+ addIssue(exampleName, packageJsonPath, 'Package name should end with "-example"');+ }++ if (pkg.private !== true) {+ addIssue(exampleName, packageJsonPath, 'Examples must be marked private');+ }++ if (!pkg.packageManager?.startsWith('pnpm@')) {+ addIssue(exampleName, packageJsonPath, 'Examples must declare a pnpm packageManager');+ }++ if (!pkg.scripts || (!pkg.scripts.start && !pkg.scripts.dev)) {+ addIssue(exampleName, packageJsonPath, 'Examples must expose a start or dev script');+ }++ const allDeps = {+ ...(pkg.dependencies ?? {}),+ ...(pkg.devDependencies ?? {}),+ };++ if (!Object.keys(allDeps).some(dep => dep.startsWith('@composio/'))) {+ addIssue(exampleName, packageJsonPath, 'Examples must depend on at least one @composio package');+ }+ } catch (error) {+ addIssue(+ exampleName,+ packageJsonPath,+ `Invalid package.json: ${error instanceof Error ? error.message : String(error)}`+ );+ }+};++const validateTsconfig = (exampleName: string, exampleDir: string) => {+ const tsconfigPath = path.join(exampleDir, 'tsconfig.json');++ if (!fs.existsSync(tsconfigPath)) {+ addIssue(exampleName, tsconfigPath, 'Missing tsconfig.json');+ return;+ }++ try {+ const raw = fs.readFileSync(tsconfigPath, 'utf8');+ const parsed = ts.parseConfigFileTextToJson(tsconfigPath, raw);++ if (parsed.error) {+ const message = ts.flattenDiagnosticMessageText(parsed.error.messageText, '\n');+ addIssue(exampleName, tsconfigPath, `Invalid tsconfig.json: ${message}`);+ return;+ }++ const config = parsed.config as { include?: string[] } | undefined;+ if (!Array.isArray(config?.include) || config.include.length === 0) {+ addIssue(exampleName, tsconfigPath, 'tsconfig.json should define a non-empty include array');+ }+ } catch (error) {+ addIssue(+ exampleName,+ tsconfigPath,+ `Invalid tsconfig.json: ${error instanceof Error ? error.message : String(error)}`+ );+ }+};++const validateSourceFile = (exampleName: string, filePath: string) => {+ const extension = path.extname(filePath);+ const relativePath = path.relative(repoRoot, filePath);++ if (extension === '.json') {+ try {+ JSON.parse(fs.readFileSync(filePath, 'utf8'));+ } catch (error) {+ addIssue(+ exampleName,+ relativePath,+ `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`+ );+ }+ return;+ }++ const sourceText = fs.readFileSync(filePath, 'utf8');+ const isTsFile = ['.ts', '.tsx', '.mts', '.cts'].includes(extension);+ const scriptKind = extension === '.tsx'+ ? ts.ScriptKind.TSX+ : extension === '.jsx'+ ? ts.ScriptKind.JSX+ : extension === '.js'+ ? ts.ScriptKind.JS+ : extension === '.cjs'+ ? ts.ScriptKind.JS+ : extension === '.mjs'+ ? ts.ScriptKind.JS+ : ts.ScriptKind.TS;++ const transpiled = ts.transpileModule(sourceText, {+ compilerOptions: {+ allowJs: true,+ module: ts.ModuleKind.ESNext,+ target: ts.ScriptTarget.ES2022,+ },+ fileName: filePath,+ reportDiagnostics: true,+ });++ for (const diagnostic of transpiled.diagnostics ?? []) {+ if (diagnostic.category !== ts.DiagnosticCategory.Error) {+ continue;+ }++ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');+ const location =+ diagnostic.start !== undefined+ ? ts.getLineAndCharacterOfPosition(+ ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.ES2022, true, scriptKind),+ diagnostic.start+ )+ : undefined;++ const formattedLocation = location+ ? `:${location.line + 1}:${location.character + 1}`+ : '';++ addIssue(exampleName, `${relativePath}${formattedLocation}`, `Syntax error: ${message}`);+ }++ if (isTsFile && sourceText.trim().length === 0) {+ addIssue(exampleName, relativePath, 'Source file must not be empty');+ }+};++const validateExample = (exampleDirName: string) => {+ const exampleDir = path.join(examplesRoot, exampleDirName);+ const srcDir = path.join(exampleDir, 'src');++ validatePackageJson(exampleDirName, exampleDir);+ validateTsconfig(exampleDirName, exampleDir);++ if (!fs.existsSync(srcDir) || !fs.statSync(srcDir).isDirectory()) {+ addIssue(exampleDirName, path.relative(repoRoot, srcDir), 'Missing src directory');+ return;+ }++ const sourceFiles = collectFiles(srcDir).filter(file =>+ allowedSourceExtensions.has(path.extname(file))+ );++ if (sourceFiles.length === 0) {+ addIssue(exampleDirName, path.relative(repoRoot, srcDir), 'No source files found');+ return;+ }++ for (const filePath of sourceFiles) {+ validateSourceFile(exampleDirName, filePath);+ }+};++const exampleDirs = fs+ .readdirSync(examplesRoot, { withFileTypes: true })+ .filter(entry => entry.isDirectory())+ .map(entry => entry.name)+ .sort();++for (const exampleDirName of exampleDirs) {+ validateExample(exampleDirName);+}++if (issues.length > 0) {+ for (const issue of issues) {+ console.error(`[${issue.example}] ${issue.file}: ${issue.message}`);+ }+ console.error(`\nExample validation failed with ${issues.length} issue(s).`);+ process.exit(1);+}++console.log(`Validated ${exampleDirs.length} example packages.`);