@devries-cameron20 / composio Mirror · read-only / commits / a8071e0d3
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 00:45 UTC

Add channel-aware Composio CLI skill builds (#3127)

## Summary - Add a generated `composio-cli` skill source that can render stable and beta variants from a single channel-aware definition. - Introduce build and validation scripts to generate the skill output and verify channel-specific content, references, and reproducibility. - Update the CLI packaging workflow to validate skills and package the correct release-channel build for beta vs stable releases. - Expand the skill content with clearer top-level CLI guidance, troubleshooting, developer-project workflows, and beta-only power-user examples. - Tighten CLI install/upgrade behavior and add tests covering skill installation behavior. - Add example validation to the repo test flow and align example package metadata with workspace expectations. ## Testing - Not run locally. - Added `ts/packages/cli/scripts/validate-skills.ts` checks for stable/beta markers, channel-specific content, and required reference files. - Added `ts/packages/cli/test/src/effects/install-skill.test.ts` coverage for skill installation behavior. - Added `ts/scripts/validate-examples.ts` to validate example package manifests during `pnpm test`. - CI workflow now runs `pnpm run validate:skills` before packaging CLI skill files.

Rahul Tarak committed Apr 7, 2026 at 01:02 UTC a8071e0d35d5d68410f64c01b4f6f8598b73bf5b
29 files changed +1690 -639
.github/workflows/build-cli-binaries.yml
+10 -1
@@ -289,8 +289,17 @@ jobs:
289
290 - name: Package skill files
291 working-directory: ts/packages/cli
292 + env:
293 + PRERELEASE: ${{ needs.prepare.outputs.prerelease }}
294 run: |
293 - cd skills && zip -r ../dist/binaries/composio-skill.zip composio-cli/
295 + pnpm run validate:skills
296 + if [[ "$PRERELEASE" == "true" ]]; then
297 + channel=beta
298 + else
299 + channel=stable
300 + fi
301 + pnpm run build:skills -- --channel "$channel" --output-dir ./dist/skills
302 + cd dist/skills && zip -r ../binaries/composio-skill.zip composio-cli/
303
304 - name: Create GitHub Release
305 env:
package.json
+2 -1
@@ -18,7 +18,8 @@
18 "build:packages": "turbo build --filter=./ts/packages/**",
19 "cli:record": "turbo run record --filter=./ts/packages/cli",
20 "record": "turbo run record",
21 - "test": "turbo test --filter=./ts/packages/** --filter=!@e2e-tests/*",
21 + "test": "turbo test --filter=./ts/packages/** --filter=!@e2e-tests/* && pnpm run test:examples",
22 + "test:examples": "tsx ts/scripts/validate-examples.ts",
23 "test:e2e": "turbo test:e2e --filter='@e2e-tests/*'",
24 "test:e2e:node": "turbo test:e2e:node --filter='@e2e-tests/node-*'",
25 "test:e2e:deno": "turbo test:e2e:deno --filter='@e2e-tests/deno-*'",
ts/examples/cloudflare-wrangler/package.json
+2 -1
@@ -1,7 +1,8 @@
1 {
2 - "name": "cloudflare-wrangler-deploy",
2 + "name": "cloudflare-wrangler-example",
3 "version": "0.0.0",
4 "private": true,
5 + "packageManager": "pnpm@10.28.0",
6 "scripts": {
7 "deploy": "wrangler deploy",
8 "dev": "wrangler dev",
ts/examples/toolkits/src/example.json
+1
@@ -0,0 +1 @@
1 +{}
ts/packages/cli/package.json
+3 -1
@@ -31,13 +31,15 @@
31 "build:binary:all": "bun run ./scripts/build-all-binaries.ts",
32 "build:binary:package": "bun run ./scripts/package-binaries.ts",
33 "build:binary:checksums": "bun run ./scripts/generate-checksums.ts",
34 + "build:skills": "tsx ./scripts/build-skills.ts",
35 + "validate:skills": "tsx ./scripts/validate-skills.ts",
36 "install:binary": "bun run ./scripts/install-binary.ts ./dist/composio",
37 "table:metrics": "bun run ./scripts/optimize-metrics-table.ts",
38 "mock": "bun run ./scripts/copy-mocks-from-cache.ts",
39 "prebuild": "pnpm run typecheck",
40 "build": "pnpm exec tsdown",
41 "bin": "./dist/composio",
40 - "test": "vitest run",
42 + "test": "pnpm run validate:skills && vitest run",
43 "prepublishOnly": "pnpm run build && pnpm run build:binary",
44 "typecheck:src": "pnpm exec tsgo --noEmit -p ./tsconfig.src.json",
45 "typecheck:test": "pnpm exec tsgo --noEmit -p ./tsconfig.test.json",
ts/packages/cli/scripts/build-skills.ts new
+24
@@ -0,0 +1,24 @@
1 +import * as fs from 'node:fs';
2 +import * as path from 'node:path';
3 +import { buildComposioCliSkill, type SkillReleaseChannel } from '../skills-src/composio-cli/index';
4 +
5 +const args = process.argv.slice(2);
6 +
7 +const readArg = (name: string) => {
8 + const index = args.indexOf(name);
9 + return index >= 0 ? args[index + 1] : undefined;
10 +};
11 +
12 +const channelArg = readArg('--channel') ?? 'stable';
13 +if (channelArg !== 'stable' && channelArg !== 'beta') {
14 + throw new Error(`Invalid --channel value "${channelArg}". Expected "stable" or "beta".`);
15 +}
16 +
17 +const outputDirArg = readArg('--output-dir') ?? path.resolve(process.cwd(), 'dist/skills');
18 +const outputDir = path.resolve(process.cwd(), outputDirArg);
19 +const channel = channelArg as SkillReleaseChannel;
20 +
21 +fs.mkdirSync(outputDir, { recursive: true });
22 +const skillDir = buildComposioCliSkill({ channel, outputRoot: outputDir });
23 +
24 +console.log(`Built composio-cli skill for ${channel} at ${skillDir}`);
ts/packages/cli/scripts/validate-skills.ts new
+71
@@ -0,0 +1,71 @@
1 +import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 +import {
5 + buildComposioCliSkill,
6 + renderComposioCliSkill,
7 + validateSkillSources,
8 +} from '../skills-src/composio-cli/index';
9 +
10 +const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-skill-validate-'));
11 +
12 +try {
13 + const sourceErrors = validateSkillSources();
14 + if (sourceErrors.length > 0) {
15 + throw new Error(sourceErrors.join('\n'));
16 + }
17 +
18 + const stableDir = buildComposioCliSkill({
19 + channel: 'stable',
20 + outputRoot: path.join(tempRoot, 'stable'),
21 + });
22 + const betaDir = buildComposioCliSkill({
23 + channel: 'beta',
24 + outputRoot: path.join(tempRoot, 'beta'),
25 + });
26 +
27 + const stableSkill = fs.readFileSync(path.join(stableDir, 'SKILL.md'), 'utf8');
28 + const betaSkill = fs.readFileSync(path.join(betaDir, 'SKILL.md'), 'utf8');
29 +
30 + if (!stableSkill.includes('<!-- release-channel: stable -->')) {
31 + throw new Error('Stable skill output is missing its release channel marker.');
32 + }
33 +
34 + if (!betaSkill.includes('<!-- release-channel: beta -->')) {
35 + throw new Error('Beta skill output is missing its release channel marker.');
36 + }
37 +
38 + if (stableSkill.includes('## `listen` - Subscribe To Trigger Events')) {
39 + throw new Error('Stable skill output unexpectedly includes beta-only listen guidance.');
40 + }
41 +
42 + if (!betaSkill.includes('## `listen` - Subscribe To Trigger Events')) {
43 + throw new Error('Beta skill output is missing beta-only listen guidance.');
44 + }
45 +
46 + if (stableSkill !== renderComposioCliSkill('stable')) {
47 + throw new Error('Stable skill build is not reproducible from the renderer.');
48 + }
49 +
50 + if (betaSkill !== renderComposioCliSkill('beta')) {
51 + throw new Error('Beta skill build is not reproducible from the renderer.');
52 + }
53 +
54 + for (const relativePath of [
55 + 'agents/openai.yaml',
56 + 'references/composio-dev.md',
57 + 'references/power-user-examples.md',
58 + 'references/troubleshooting.md',
59 + ]) {
60 + if (!fs.existsSync(path.join(stableDir, relativePath))) {
61 + throw new Error(`Stable build is missing ${relativePath}`);
62 + }
63 + if (!fs.existsSync(path.join(betaDir, relativePath))) {
64 + throw new Error(`Beta build is missing ${relativePath}`);
65 + }
66 + }
67 +
68 + console.log('Validated composio-cli skill builds for stable and beta.');
69 +} finally {
70 + fs.rmSync(tempRoot, { recursive: true, force: true });
71 +}
ts/packages/cli/skills-src/composio-cli/assets/agents/openai.yaml renamed
ts/packages/cli/skills-src/composio-cli/index.ts new
+369
@@ -0,0 +1,369 @@
1 +import * as fs from 'node:fs';
2 +import * as path from 'node:path';
3 +import { CLI_EXPERIMENTAL_FEATURES } from '../../src/constants';
4 +import { composioDevReference } from './references/composio-dev';
5 +import { powerUserExamplesReference } from './references/power-user-examples';
6 +import { troubleshootingReference } from './references/troubleshooting';
7 +import {
8 + renderReferenceDocument,
9 + resolveSkillBuildContext,
10 + validateReferenceDocument,
11 + type SkillBuildContext,
12 + type SkillFeatureFlag,
13 + type SkillReleaseChannel,
14 +} from './reference-schema';
15 +
16 +type SkillFlag = {
17 + description: string;
18 + name: string;
19 + features?: SkillFeatureFlag[];
20 +};
21 +
22 +type SkillExample = {
23 + code: string;
24 + description?: string;
25 + features?: SkillFeatureFlag[];
26 +};
27 +
28 +type SkillCommand = {
29 + id: string;
30 + title: string;
31 + summary?: string;
32 + features?: SkillFeatureFlag[];
33 + intro?: string[];
34 + flags?: SkillFlag[];
35 + examples?: SkillExample[];
36 + notes?: string[];
37 + extraBody?: Array<{
38 + features?: SkillFeatureFlag[];
39 + markdown: string;
40 + }>;
41 +};
42 +
43 +const isEnabledForBuild = (build: SkillBuildContext, entry?: { features?: SkillFeatureFlag[] }) =>
44 + !entry?.features || entry.features.every(feature => build.experimentalFeatures[feature]);
45 +
46 +const sourceAssetsDir = path.resolve(import.meta.dirname, './assets');
47 +
48 +const frontmatter = {
49 + name: 'composio-cli',
50 + description:
51 + '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.',
52 +};
53 +
54 +const commands: SkillCommand[] = [
55 + {
56 + id: 'execute',
57 + title: '`execute` - Run A Tool',
58 + summary: 'Use `execute` when the tool slug is already known.',
59 + flags: [
60 + {
61 + name: '`--get-schema`',
62 + description: 'Inspect required arguments without executing the tool.',
63 + },
64 + {
65 + name: '`--dry-run`',
66 + description: 'Preview the request shape without performing the action.',
67 + },
68 + {
69 + name: '`--file`',
70 + description:
71 + 'Inject a local file path into a tool that exposes exactly one uploadable file argument.',
72 + },
73 + {
74 + name: '`--parallel`',
75 + description: 'Execute multiple independent tool calls in the same invocation.',
76 + },
77 + ],
78 + examples: [
79 + {
80 + code: "composio execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'",
81 + },
82 + {
83 + description: 'Inspect required inputs without executing',
84 + code: 'composio execute GITHUB_CREATE_AN_ISSUE --get-schema',
85 + },
86 + {
87 + description: 'Preview safely',
88 + code: 'composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d \'{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }\'',
89 + },
90 + {
91 + description: 'Pass data from a file or stdin',
92 + code: 'composio execute GITHUB_CREATE_AN_ISSUE -d @issue.json\ncat issue.json | composio execute GITHUB_CREATE_AN_ISSUE -d -',
93 + },
94 + {
95 + description: 'Upload a local file',
96 + code: 'composio execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK \\\n --file ./image.png \\\n -d \'{ channels: "C123" }\'',
97 + },
98 + {
99 + description: 'Run independent tool calls in parallel',
100 + code: 'composio execute --parallel \\\n GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", subject: "Hi" }\' \\\n GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\'',
101 + },
102 + ],
103 + notes: [
104 + '`--file` only works when the tool exposes a single uploadable file input. Otherwise use explicit `-d` JSON.',
105 + ],
106 + },
107 + {
108 + id: 'search',
109 + title: '`search` - Find The Slug',
110 + summary: 'Use `search` only when the tool slug is not already known.',
111 + examples: [
112 + {
113 + 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',
114 + },
115 + ],
116 + notes: [
117 + 'Batch related discovery work into one `search` invocation, then move back to `execute` once the correct slugs are known.',
118 + ],
119 + },
120 + {
121 + id: 'link',
122 + title: '`link` - Connect An Account',
123 + summary:
124 + 'Use `link` when `execute` reports that a toolkit is not connected, or when the user explicitly wants to authorize an account.',
125 + examples: [
126 + {
127 + code: 'composio link gmail\ncomposio link googlecalendar --no-browser',
128 + },
129 + ],
130 + notes: ['Retry the original `execute` command after linking succeeds.'],
131 + },
132 + {
133 + id: 'listen',
134 + title: '`listen` - Subscribe To Trigger Events',
135 + features: [CLI_EXPERIMENTAL_FEATURES.LISTEN],
136 + summary:
137 + 'Use `listen` for temporary trigger subscriptions in consumer projects, especially when background agents should consume new event payloads from artifact files.',
138 + examples: [
139 + {
140 + 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",
141 + },
142 + ],
143 + flags: [
144 + {
145 + name: '`-p/--params`',
146 + description:
147 + 'Provide only trigger config fields; connected account resolution is automatic.',
148 + },
149 + {
150 + name: '`--stream`',
151 + description: 'Print events inline, optionally narrowed to a JSON path.',
152 + },
153 + {
154 + name: '`--timeout` and `--max-events`',
155 + description: 'Stop long-running listeners cleanly.',
156 + },
157 + ],
158 + notes: [
159 + '`composio artifacts cwd` shows the current artifact root when saved payloads need inspection.',
160 + ],
161 + },
162 + {
163 + id: 'proxy',
164 + title: '`proxy` - Raw API Access',
165 + summary:
166 + 'Use `proxy` when a toolkit supports a raw API operation that is easier than finding a dedicated tool slug.',
167 + examples: [
168 + {
169 + code: 'composio proxy https://api.github.com/user --toolkit github --method GET </dev/null',
170 + },
171 + ],
172 + },
173 + {
174 + id: 'run',
175 + title: '`run` - Scripting, LLMs, and Programmatic Workflows',
176 + summary:
177 + 'For programmatic calls, loops, output plumbing, or anything beyond a single tool call, prefer `composio run`.',
178 + intro: [
179 + '`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.',
180 + ],
181 + examples: [
182 + {
183 + description: 'Chain multiple tools',
184 + 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\'',
185 + },
186 + {
187 + description: 'Fan out with Promise.all',
188 + 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\'',
189 + },
190 + {
191 + description: 'Feed tool output into an LLM and get structured JSON back',
192 + 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\'',
193 + },
194 + ],
195 + notes: [
196 + 'Use top-level `execute --parallel` instead when the user only needs a few independent tool calls and does not need script logic.',
197 + ],
198 + },
199 + {
200 + id: 'auth',
201 + title: 'Auth',
202 + examples: [
203 + {
204 + code: 'composio whoami # check current session\ncomposio login # authenticate if whoami fails',
205 + },
206 + ],
207 + },
208 +];
209 +
210 +const defaultWorkflow = (build: SkillBuildContext) => {
211 + const lines = [
212 + '1. Start with `composio execute <slug>` whenever the slug is known.',
213 + '2. If several independent tool calls must happen at once, use `composio execute -p/--parallel` with repeated `<slug> -d <json>` groups.',
214 + '3. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.',
215 + '4. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.',
216 + '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.',
217 + ];
218 +
219 + if (build.experimentalFeatures[CLI_EXPERIMENTAL_FEATURES.LISTEN]) {
220 + lines.push(
221 + '6. If the CLI build enables the experimental `listen` feature, use it for temporary consumer-project trigger subscriptions.'
222 + );
223 + }
224 +
225 + return lines;
226 +};
227 +
228 +const referenceDocuments = [
229 + composioDevReference,
230 + powerUserExamplesReference,
231 + troubleshootingReference,
232 +] as const;
233 +
234 +const renderExample = (example: SkillExample) => {
235 + const lines = [];
236 +
237 + if (example.description) {
238 + lines.push(example.description + ':');
239 + }
240 +
241 + lines.push('```bash', example.code, '```');
242 + return lines.join('\n');
243 +};
244 +
245 +const renderCommand = (build: SkillBuildContext, command: SkillCommand) => {
246 + const lines: string[] = [`## ${command.title}`];
247 +
248 + if (command.summary) {
249 + lines.push('', command.summary);
250 + }
251 +
252 + for (const intro of command.intro ?? []) {
253 + lines.push('', intro);
254 + }
255 +
256 + const examples = (command.examples ?? []).filter(example => isEnabledForBuild(build, example));
257 + if (examples.length > 0) {
258 + for (const example of examples) {
259 + lines.push('', renderExample(example));
260 + }
261 + }
262 +
263 + const flags = (command.flags ?? []).filter(flag => isEnabledForBuild(build, flag));
264 + if (flags.length > 0) {
265 + lines.push('', 'Key flags:');
266 + for (const flag of flags) {
267 + lines.push(`- ${flag.name}: ${flag.description}`);
268 + }
269 + }
270 +
271 + for (const note of command.notes ?? []) {
272 + lines.push('', `- ${note}`);
273 + }
274 +
275 + for (const extra of (command.extraBody ?? []).filter(block => isEnabledForBuild(build, block))) {
276 + lines.push('', extra.markdown);
277 + }
278 +
279 + return lines.join('\n');
280 +};
281 +
282 +export const renderComposioCliSkill = (channel: SkillReleaseChannel) => {
283 + const build = resolveSkillBuildContext(channel);
284 + const lines: string[] = [
285 + '---',
286 + `name: ${frontmatter.name}`,
287 + `description: ${frontmatter.description}`,
288 + '---',
289 + '',
290 + '<!-- AUTO-GENERATED: edit skills-src/composio-cli/index.ts and rebuild -->',
291 + `<!-- release-channel: ${channel} -->`,
292 + '',
293 + '# Composio CLI',
294 + '',
295 + '## Default Workflow',
296 + '',
297 + ...defaultWorkflow(build),
298 + ];
299 +
300 + const enabledCommands = commands.filter(command => isEnabledForBuild(build, command));
301 + for (const command of enabledCommands) {
302 + lines.push('', renderCommand(build, command));
303 + }
304 +
305 + lines.push(
306 + '',
307 + '## Escalate Only When Needed',
308 + '',
309 + 'If the user is stuck on top-level commands or needs fallback inspection commands, load [references/troubleshooting.md](references/troubleshooting.md).',
310 + '',
311 + '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.'
312 + );
313 +
314 + return lines.join('\n') + '\n';
315 +};
316 +
317 +export const renderReferenceFiles = (channel: SkillReleaseChannel) => {
318 + const build = resolveSkillBuildContext(channel);
319 + return Object.fromEntries(
320 + referenceDocuments.map(document => [
321 + `${document.slug}.md`,
322 + renderReferenceDocument(document, build),
323 + ])
324 + );
325 +};
326 +
327 +export const validateSkillSources = () => referenceDocuments.flatMap(validateReferenceDocument);
328 +
329 +const copyDir = (sourceDir: string, targetDir: string) => {
330 + fs.mkdirSync(targetDir, { recursive: true });
331 + for (const entry of fs.readdirSync(sourceDir, { withFileTypes: true })) {
332 + const sourcePath = path.join(sourceDir, entry.name);
333 + const targetPath = path.join(targetDir, entry.name);
334 +
335 + if (entry.isDirectory()) {
336 + copyDir(sourcePath, targetPath);
337 + continue;
338 + }
339 +
340 + fs.copyFileSync(sourcePath, targetPath);
341 + }
342 +};
343 +
344 +export const buildComposioCliSkill = ({
345 + channel,
346 + outputRoot,
347 +}: {
348 + channel: SkillReleaseChannel;
349 + outputRoot: string;
350 +}) => {
351 + const skillOutputDir = path.join(outputRoot, 'composio-cli');
352 + fs.rmSync(skillOutputDir, { recursive: true, force: true });
353 + fs.mkdirSync(skillOutputDir, { recursive: true });
354 +
355 + fs.writeFileSync(path.join(skillOutputDir, 'SKILL.md'), renderComposioCliSkill(channel), 'utf8');
356 +
357 + const agentsSourceDir = path.join(sourceAssetsDir, 'agents');
358 + if (fs.existsSync(agentsSourceDir)) {
359 + copyDir(agentsSourceDir, path.join(skillOutputDir, 'agents'));
360 + }
361 +
362 + const referencesOutputDir = path.join(skillOutputDir, 'references');
363 + fs.mkdirSync(referencesOutputDir, { recursive: true });
364 + for (const [fileName, markdown] of Object.entries(renderReferenceFiles(channel))) {
365 + fs.writeFileSync(path.join(referencesOutputDir, fileName), markdown, 'utf8');
366 + }
367 +
368 + return skillOutputDir;
369 +};
ts/packages/cli/skills-src/composio-cli/reference-schema.ts new
+161
@@ -0,0 +1,161 @@
1 +import { CLI_EXPERIMENTAL_FEATURES } from '../../src/constants';
2 +
3 +export type SkillReleaseChannel = 'beta' | 'stable';
4 +
5 +export type SkillFeatureFlag =
6 + (typeof CLI_EXPERIMENTAL_FEATURES)[keyof typeof CLI_EXPERIMENTAL_FEATURES];
7 +
8 +export type SkillBuildContext = {
9 + channel: SkillReleaseChannel;
10 + experimentalFeatures: Readonly<Record<SkillFeatureFlag, boolean>>;
11 +};
12 +
13 +export type FeatureScoped = {
14 + features?: SkillFeatureFlag[];
15 +};
16 +
17 +export type CommandSnippet = FeatureScoped & {
18 + code: string;
19 + description?: string;
20 +};
21 +
22 +export type ReferenceSection = FeatureScoped & {
23 + body?: string[];
24 + commands?: CommandSnippet[];
25 + title: string;
26 +};
27 +
28 +export type ReferenceDocument = {
29 + intro?: string[];
30 + slug: string;
31 + title: string;
32 + sections: ReferenceSection[];
33 +};
34 +
35 +const TOP_LEVEL_COMMANDS = new Set([
36 + 'artifacts',
37 + 'dev',
38 + 'execute',
39 + 'link',
40 + 'listen',
41 + 'login',
42 + 'logout',
43 + 'proxy',
44 + 'run',
45 + 'search',
46 + 'tools',
47 + 'whoami',
48 +]);
49 +
50 +export const resolveSkillBuildContext = (channel: SkillReleaseChannel): SkillBuildContext => ({
51 + channel,
52 + experimentalFeatures: {
53 + [CLI_EXPERIMENTAL_FEATURES.LISTEN]: channel === 'beta',
54 + },
55 +});
56 +
57 +const isEnabledForBuild = (build: SkillBuildContext, value?: FeatureScoped) =>
58 + !value?.features || value.features.every(feature => build.experimentalFeatures[feature]);
59 +
60 +export const renderCommandSnippet = (snippet: CommandSnippet) => {
61 + const lines: string[] = [];
62 +
63 + if (snippet.description) {
64 + lines.push(snippet.description + ':');
65 + }
66 +
67 + lines.push('```bash', snippet.code, '```');
68 + return lines.join('\n');
69 +};
70 +
71 +export const renderReferenceDocument = (document: ReferenceDocument, build: SkillBuildContext) => {
72 + const lines = [`# ${document.title}`];
73 +
74 + for (const introLine of document.intro ?? []) {
75 + lines.push('', introLine);
76 + }
77 +
78 + for (const section of document.sections.filter(section => isEnabledForBuild(build, section))) {
79 + lines.push('', `## ${section.title}`);
80 +
81 + for (const bodyLine of section.body ?? []) {
82 + lines.push('', bodyLine);
83 + }
84 +
85 + for (const command of (section.commands ?? []).filter(command =>
86 + isEnabledForBuild(build, command)
87 + )) {
88 + lines.push('', renderCommandSnippet(command));
89 + }
90 + }
91 +
92 + return lines.join('\n') + '\n';
93 +};
94 +
95 +export const validateCommandSnippet = (snippet: CommandSnippet, documentSlug: string) => {
96 + const errors: string[] = [];
97 + const lines = snippet.code.split('\n');
98 + let inQuotedCommand = false;
99 + let expectingContinuation = false;
100 +
101 + for (const rawLine of lines) {
102 + const line = rawLine.trim();
103 + if (line.length === 0 || line.startsWith('#')) {
104 + continue;
105 + }
106 +
107 + if (inQuotedCommand) {
108 + const quoteCount = (line.match(/'/g) ?? []).length;
109 + if (line === "'" || quoteCount % 2 === 1) {
110 + inQuotedCommand = false;
111 + }
112 + continue;
113 + }
114 +
115 + if (expectingContinuation) {
116 + expectingContinuation = line.endsWith('\\');
117 + continue;
118 + }
119 +
120 + if (
121 + line.startsWith('cat ') ||
122 + line.startsWith('echo ') ||
123 + line.startsWith('source ') ||
124 + line.startsWith('export ')
125 + ) {
126 + continue;
127 + }
128 +
129 + if (!line.startsWith('composio ')) {
130 + errors.push(`[${documentSlug}] command must start with "composio": ${line}`);
131 + continue;
132 + }
133 +
134 + const normalized = line.endsWith('\\') ? line.slice(0, -1).trim() : line;
135 + const parts = normalized.split(/\s+/);
136 + const topLevel = parts[1];
137 + if (!TOP_LEVEL_COMMANDS.has(topLevel)) {
138 + errors.push(`[${documentSlug}] unknown top-level command "${topLevel}" in: ${normalized}`);
139 + }
140 +
141 + expectingContinuation = line.endsWith('\\');
142 + const singleQuoteCount = (line.match(/'/g) ?? []).length;
143 + if (singleQuoteCount % 2 === 1) {
144 + inQuotedCommand = true;
145 + }
146 + }
147 +
148 + return errors;
149 +};
150 +
151 +export const validateReferenceDocument = (document: ReferenceDocument) => {
152 + const errors: string[] = [];
153 +
154 + for (const section of document.sections) {
155 + for (const command of section.commands ?? []) {
156 + errors.push(...validateCommandSnippet(command, document.slug));
157 + }
158 + }
159 +
160 + return errors;
161 +};
ts/packages/cli/skills-src/composio-cli/references/composio-dev.ts new
+69
@@ -0,0 +1,69 @@
1 +import type { ReferenceDocument } from '../reference-schema';
2 +
3 +export const composioDevReference: ReferenceDocument = {
4 + slug: 'composio-dev',
5 + title: 'Composio Dev',
6 + intro: [
7 + 'Load this file only when the user explicitly needs developer-project workflows. Do not lead with `composio dev` for ordinary top-level CLI usage.',
8 + ],
9 + sections: [
10 + {
11 + title: 'Use `dev init` To Bind A Directory',
12 + body: [
13 + 'Use `composio dev init` when the user wants to attach the current directory to a developer project.',
14 + 'If later commands complain about missing developer project context, come back to `dev init`.',
15 + ],
16 + commands: [{ code: 'composio dev init -y --no-browser' }],
17 + },
18 + {
19 + title: 'Inspect Toolkits And Versions',
20 + body: ['Use toolkit commands to inspect developer-scoped capabilities:'],
21 + commands: [
22 + {
23 + code: 'composio dev toolkits list\ncomposio dev toolkits info github\ncomposio dev toolkits search "email"\ncomposio dev toolkits version github',
24 + },
25 + ],
26 + },
27 + {
28 + title: 'Manage Auth Configs',
29 + body: [
30 + 'Use auth-config commands when the user is configuring developer-project authentication behavior:',
31 + ],
32 + commands: [{ code: 'composio dev auth-configs list' }],
33 + },
34 + {
35 + title: 'Manage Connected Accounts',
36 + body: [
37 + 'Use developer connected-account commands when the user is working with developer-project users or auth-config-specific flows.',
38 + 'Top-level `composio link` is consumer-only. Use `dev connected-accounts link` for developer-project flows.',
39 + ],
40 + commands: [{ code: 'composio dev connected-accounts list' }],
41 + },
42 + {
43 + title: 'Work With Triggers',
44 + body: [
45 + 'Use trigger commands when the user is creating, inspecting, or listening to developer-project triggers.',
46 + ],
47 + commands: [
48 + {
49 + code: 'composio dev triggers list\ncomposio dev triggers info AGENT_MAIL_NEW_EMAIL_TRIGGER',
50 + },
51 + ],
52 + },
53 + {
54 + title: 'Inspect Logs',
55 + body: [
56 + 'Use logs when the user is debugging tool executions or trigger deliveries inside a developer project.',
57 + ],
58 + commands: [{ code: 'composio dev logs tools\ncomposio dev logs triggers' }],
59 + },
60 + {
61 + title: 'Switch Or Inspect Org And Project Context',
62 + body: [
63 + 'Use these commands when the user needs to confirm or change the active developer scope:',
64 + '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`.',
65 + ],
66 + commands: [{ code: 'composio dev orgs list\ncomposio dev projects list' }],
67 + },
68 + ],
69 +};
ts/packages/cli/skills-src/composio-cli/references/power-user-examples.ts new
+160
@@ -0,0 +1,160 @@
1 +import type { ReferenceDocument } from '../reference-schema';
2 +
3 +export const powerUserExamplesReference: ReferenceDocument = {
4 + slug: 'power-user-examples',
5 + title: 'Power-User Examples',
6 + intro: [
7 + '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`.',
8 + ],
9 + sections: [
10 + {
11 + title: 'Use `run` To Chain Tool Calls',
12 + body: [
13 + 'Fetch from multiple connected tools in one script:',
14 + 'If the user does not need script logic and just wants a few independent calls, prefer top-level parallel execute instead:',
15 + ],
16 + commands: [
17 + {
18 + code: `composio run '
19 + const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
20 + const emails = await execute("GMAIL_FETCH_EMAILS", {
21 + max_results: 2,
22 + });
23 +
24 + console.log({
25 + login: me.data.login,
26 + emailCount: Array.isArray(emails.data?.messages) ? emails.data.messages.length : null,
27 + });
28 +'`,
29 + },
30 + {
31 + code: `composio execute --parallel \\
32 + GMAIL_FETCH_EMAILS -d '{ max_results: 2 }' \\
33 + GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'`,
34 + },
35 + ],
36 + },
37 + {
38 + title: 'Use `Promise.all` To Fan Out',
39 + body: ['Fetch from multiple services at once:'],
40 + commands: [
41 + {
42 + code: `composio run '
43 + const [me, emails] = await Promise.all([
44 + execute("GITHUB_GET_THE_AUTHENTICATED_USER"),
45 + execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),
46 + ]);
47 +
48 + console.log({
49 + login: me.data.login,
50 + emailCount: emails.data.messages?.length ?? null,
51 + });
52 +'`,
53 + },
54 + ],
55 + },
56 + {
57 + title: 'Use `search()` Before `execute()` Inside A Script',
58 + body: [
59 + 'Discover a candidate slug, then execute it:',
60 + 'Batch related discovery work with multiple queries when it keeps the workflow simpler:',
61 + ],
62 + commands: [
63 + {
64 + code: `composio run '
65 + const results = await search("get the authenticated github user", {
66 + toolkits: "github",
67 + limit: 1,
68 + });
69 +
70 + const slug = results.results?.[0]?.primary_tool_slugs?.[0];
71 + if (!slug) throw new Error("No candidate tool found.");
72 +
73 + const output = await execute(slug);
74 +
75 + console.log(output.data.login);
76 +'`,
77 + },
78 + {
79 + code: 'composio search "send an email" "create a github issue" --toolkits gmail,github',
80 + },
81 + ],
82 + },
83 + {
84 + title: 'Use `experimental_subAgent()` With `z` And `result.prompt()`',
85 + body: [
86 + 'Turn a tool result into structured output:',
87 + '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()`.',
88 + ],
89 + commands: [
90 + {
91 + code: `composio run --logs-off '
92 + const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 2 });
93 +
94 + const brief = await experimental_subAgent(
95 + \`Return only valid JSON matching the schema. Summarize these emails in one sentence and report how many items were returned.\\n\\n\${emails.prompt()}\`,
96 + {
97 + schema: z.object({
98 + summary: z.string(),
99 + count: z.number(),
100 + }),
101 + }
102 + );
103 +
104 + console.log(brief.structuredOutput);
105 +'`,
106 + },
107 + ],
108 + },
109 + {
110 + title: 'Use `proxy()` For Raw API Access',
111 + body: [
112 + '`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()`.',
113 + ],
114 + commands: [
115 + {
116 + code: `composio run '
117 + const fetch = await proxy("github");
118 + const profile = await (await fetch("https://api.github.com/user")).json();
119 + console.log(profile);
120 +'`,
121 + },
122 + ],
123 + },
124 + {
125 + title: 'Mix `execute()` And `proxy()`',
126 + body: [
127 + 'Use dedicated tools where they exist, then drop down to raw API calls for the missing step:',
128 + ],
129 + commands: [
130 + {
131 + code: `composio run '
132 + const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
133 +
134 + const fetch = await proxy("github");
135 + const repos = await (await fetch("https://api.github.com/user/repos?per_page=3")).json();
136 +
137 + console.log({
138 + login: me.data.login,
139 + repoCount: Array.isArray(repos) ? repos.length : null,
140 + });
141 +'`,
142 + },
143 + ],
144 + },
145 + {
146 + title: 'Use `run` Flags Intentionally',
147 + body: [
148 + '- Use `--dry-run` to preview every `execute()` call in the script.',
149 + '- Use `--debug` to see helper steps while the script runs.',
150 + '- Use `--logs-off` when `experimental_subAgent()` streaming logs are too noisy for the task.',
151 + 'Example:',
152 + ],
153 + commands: [
154 + {
155 + code: `composio run --dry-run --debug 'await execute("GITHUB_CREATE_AN_ISSUE", { owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." })'`,
156 + },
157 + ],
158 + },
159 + ],
160 +};
ts/packages/cli/skills-src/composio-cli/references/troubleshooting.ts new
+120
@@ -0,0 +1,120 @@
1 +import type { ReferenceDocument } from '../reference-schema';
2 +
3 +export const troubleshootingReference: ReferenceDocument = {
4 + slug: 'troubleshooting',
5 + title: 'Troubleshooting',
6 + intro: ['Load this file when the user is stuck on top-level Composio CLI flows.'],
7 + sections: [
8 + {
9 + title: 'Not Logged In',
10 + body: [
11 + 'Symptoms:',
12 + '- `composio` commands fail because there is no user session',
13 + '- the user is unsure which account the CLI is using',
14 + 'Fix:',
15 + 'If `composio whoami` fails, run `composio login` and then return to the original `execute` or `search` flow.',
16 + ],
17 + commands: [{ code: 'composio whoami' }],
18 + },
19 + {
20 + title: 'No Active Connection Found',
21 + body: [
22 + 'Symptoms:',
23 + '- `execute` reports that no active connection exists for a toolkit',
24 + 'Fix:',
25 + 'After linking, retry the exact same `execute` command.',
26 + ],
27 + commands: [
28 + {
29 + code: 'composio link gmail --no-browser --no-wait\ncomposio link googlecalendar --no-browser --no-wait',
30 + },
31 + ],
32 + },
33 + {
34 + title: 'Invalid JSON Input',
35 + body: [
36 + 'Symptoms:',
37 + '- `execute` rejects `-d` input',
38 + '- the payload is not valid JSON or JS-style object syntax',
39 + 'Fix:',
40 + '- Pass JSON or a JS-style object literal to `-d`',
41 + '- Use `@file` for large payloads',
42 + '- Use `-` to read from stdin',
43 + 'Examples:',
44 + ],
45 + commands: [
46 + {
47 + code: `composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{"owner":"acme","repo":"app","title":"Bug report","body":"Steps to reproduce..."}'
48 +composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'
49 +composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d @payload.json
50 +cat payload.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d -`,
51 + },
52 + ],
53 + },
54 + {
55 + title: 'Unknown Or Wrong Slug',
56 + body: [
57 + 'Symptoms:',
58 + '- the user does not know the tool slug',
59 + '- the slug exists but is not the right tool for the job',
60 + 'Fix:',
61 + '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.',
62 + ],
63 + commands: [
64 + {
65 + code: 'composio search "create a github issue"\ncomposio search "send an email" --toolkits gmail\ncomposio search "send an email" "create a github issue"',
66 + },
67 + ],
68 + },
69 + {
70 + title: 'Confusion About Required Inputs',
71 + body: [
72 + 'Symptoms:',
73 + '- the user is unsure what fields a tool accepts',
74 + '- the first payload attempt failed validation',
75 + 'Fix:',
76 + '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.',
77 + ],
78 + commands: [
79 + {
80 + 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..." }'`,
81 + },
82 + ],
83 + },
84 + {
85 + title: 'Several Independent Tool Calls',
86 + body: [
87 + 'Symptoms:',
88 + '- the user wants to run multiple unrelated tools in one step',
89 + '- the user is about to write a script only to execute a few independent calls',
90 + 'Fix:',
91 + 'Escalate to `composio run` only when the user needs control flow, loops, `Promise.all`, `search()` inside a script, `proxy()`, or `experimental_subAgent()`.',
92 + ],
93 + commands: [
94 + {
95 + code: `composio execute --parallel \\\n GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com", subject: "Hi" }' \\\n GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
96 + },
97 + ],
98 + },
99 + {
100 + title: '`tools info` And `tools list` Are Fallbacks',
101 + body: [
102 + 'Treat these commands as secondary inspection tools:',
103 + 'Do not lead with them when `execute`, `search`, `--get-schema`, or `--dry-run` can get the user unstuck faster.',
104 + ],
105 + commands: [{ code: 'composio tools info GMAIL_SEND_EMAIL\ncomposio tools list gmail' }],
106 + },
107 + {
108 + title: 'Consumer Vs `composio dev`',
109 + body: [
110 + 'Use the top-level commands for normal end-user flows:',
111 + '- `composio execute`',
112 + '- `composio search`',
113 + '- `composio link`',
114 + '- `composio run`',
115 + '- `composio proxy`',
116 + 'Load [composio-dev.md](composio-dev.md) only when the user explicitly needs developer projects, auth configs, connected accounts, triggers, logs, orgs, or projects.',
117 + ],
118 + },
119 + ],
120 +};
ts/packages/cli/skills/composio-cli/SKILL.md deleted
-167
@@ -1,167 +0,0 @@
1 ----
2 -name: composio-cli
3 -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.
4 ----
5 -
6 -# Composio CLI
7 -
8 -## Default Workflow
9 -
10 -1. Start with `composio execute <slug>` whenever the slug is known.
11 -2. If several independent tool calls must happen at once, use `composio execute -p/--parallel` with repeated `<slug> -d <json>` groups.
12 -3. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.
13 -4. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.
14 -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.
15 -
16 -## `execute` — Run A Tool
17 -
18 -```bash
19 -composio execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'
20 -```
21 -
22 -Inspect required inputs without executing:
23 -
24 -```bash
25 -composio execute GITHUB_CREATE_AN_ISSUE --get-schema
26 -```
27 -
28 -Preview safely:
29 -
30 -```bash
31 -composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'
32 -```
33 -
34 -Pass data from a file or stdin:
35 -
36 -```bash
37 -composio execute GITHUB_CREATE_AN_ISSUE -d @issue.json
38 -cat issue.json | composio execute GITHUB_CREATE_AN_ISSUE -d -
39 -```
40 -
41 -Upload a local file when the tool has a single `file_uploadable` input:
42 -
43 -```bash
44 -composio execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK \
45 - --file ./image.png \
46 - -d '{ channels: "C123" }'
47 -```
48 -
49 -`--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.
50 -
51 -Run independent tool calls in parallel:
52 -
53 -```bash
54 -composio execute --parallel \
55 - GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com", subject: "Hi" }' \
56 - GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'
57 -```
58 -
59 -## `search` — Find The Slug
60 -
61 -```bash
62 -composio search "create a github issue"
63 -composio search "send an email" --toolkits gmail
64 -composio search "send an email" "create a github issue"
65 -composio search "my emails" "my github issues" --toolkits gmail,github
66 -```
67 -
68 -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`.
69 -
70 -## `link` — Connect An Account
71 -
72 -Use `link` when `execute` reports the toolkit is not connected, or the user wants to authorize an account.
73 -
74 -```bash
75 -composio link gmail
76 -composio link googlecalendar --no-browser
77 -```
78 -
79 -After linking, retry the original `execute` command.
80 -
81 -## `listen` — Subscribe To Trigger Events
82 -
83 -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.
84 -
85 -The command creates a temporary trigger, subscribes to it, writes each event to the artifact folder, and disables the trigger on cleanup.
86 -
87 -```bash
88 -composio listen GMAIL_NEW_GMAIL_MESSAGE
89 -composio listen SLACK_RECEIVE_MESSAGE -p '{ trigger_config: { channel: "C123" } }'
90 -composio listen GMAIL_NEW_GMAIL_MESSAGE --stream
91 -composio listen GMAIL_NEW_GMAIL_MESSAGE --stream '.data.threadId'
92 -composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 5m
93 -composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5
94 -```
95 -
96 -Key points:
97 -
98 -- `-p/--params` is only for trigger config fields; the connected account is resolved automatically.
99 -- `--stream` prints each event inline, and `--stream '.path.here'` prints only the selected field.
100 -- `--timeout` and `--max-events` are the normal ways to stop long-running listeners cleanly.
101 -- `composio artifacts cwd` shows the current artifact root when the user needs to inspect saved event payloads.
102 -
103 -## `proxy` — Raw API Access
104 -
105 -Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.
106 -
107 -```bash
108 -composio proxy https://api.github.com/user --toolkit github --method GET </dev/null
109 -```
110 -
111 -## `run` — Scripting, LLMs, and Programmatic Workflows
112 -
113 -> **For programmatic calls, LLM workflows, or anything beyond a single tool call — use `composio run`.**
114 -
115 -`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.
116 -
117 -Chain multiple tools:
118 -
119 -```bash
120 -composio run '
121 - const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
122 - const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 1 });
123 - console.log({ login: me.data.login, fetchedEmails: !!emails.data });
124 -'
125 -```
126 -
127 -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.
128 -
129 -Fan out with `Promise.all`:
130 -
131 -```bash
132 -composio run '
133 - const [me, emails] = await Promise.all([
134 - execute("GITHUB_GET_THE_AUTHENTICATED_USER"),
135 - execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),
136 - ]);
137 - console.log({ login: me.data.login, emailCount: emails.data.messages?.length });
138 -'
139 -```
140 -
141 -Feed tool output into an LLM and get structured JSON back:
142 -
143 -```bash
144 -composio run --logs-off '
145 - const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 5 });
146 - const brief = await experimental_subAgent(
147 - `Summarize these emails and count them.\n\n${emails.prompt()}`,
148 - { schema: z.object({ summary: z.string(), count: z.number() }) }
149 - );
150 - console.log(brief.structuredOutput);
151 -'
152 -```
153 -
154 -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).
155 -
156 -## Auth
157 -
158 -```bash
159 -composio whoami # check current session
160 -composio login # authenticate if whoami fails
161 -```
162 -
163 -## Escalate Only When Needed
164 -
165 -If the user is stuck on top-level commands or needs fallback inspection commands, load [references/troubleshooting.md](references/troubleshooting.md).
166 -
167 -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.
ts/packages/cli/skills/composio-cli/references/composio-dev.md deleted
-71
@@ -1,71 +0,0 @@
1 -# Composio Dev
2 -
3 -Load this file only when the user explicitly needs developer-project workflows. Do not lead with `composio dev` for ordinary top-level CLI usage.
4 -
5 -## Use `dev init` To Bind A Directory
6 -
7 -Use `composio dev init` when the user wants to attach the current directory to a developer project.
8 -
9 -```bash
10 -composio dev init -y --no-browser
11 -```
12 -
13 -If later commands complain about missing developer project context, come back to `dev init`.
14 -
15 -## Inspect Toolkits And Versions
16 -
17 -Use toolkit commands to inspect developer-scoped capabilities:
18 -
19 -```bash
20 -composio dev toolkits list
21 -composio dev toolkits info github
22 -composio dev toolkits search "email"
23 -composio dev toolkits version github
24 -```
25 -
26 -## Manage Auth Configs
27 -
28 -Use auth-config commands when the user is configuring developer-project authentication behavior:
29 -
30 -```bash
31 -composio dev auth-configs list
32 -```
33 -
34 -## Manage Connected Accounts
35 -
36 -Use developer connected-account commands when the user is working with developer-project users or auth-config-specific flows.
37 -
38 -```bash
39 -composio dev connected-accounts list
40 -```
41 -
42 -Top-level `composio link` is consumer-only. Use `dev connected-accounts link` for developer-project flows.
43 -
44 -## Work With Triggers
45 -
46 -Use trigger commands when the user is creating, inspecting, or listening to developer-project triggers.
47 -
48 -```bash
49 -composio dev triggers list
50 -composio dev triggers info AGENT_MAIL_NEW_EMAIL_TRIGGER
51 -```
52 -
53 -## Inspect Logs
54 -
55 -Use logs when the user is debugging tool executions or trigger deliveries inside a developer project.
56 -
57 -```bash
58 -composio dev logs tools
59 -composio dev logs triggers
60 -```
61 -
62 -## Switch Or Inspect Org And Project Context
63 -
64 -Use these commands when the user needs to confirm or change the active developer scope:
65 -
66 -```bash
67 -composio dev orgs list
68 -composio dev projects list
69 -```
70 -
71 -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`.
ts/packages/cli/skills/composio-cli/references/power-user-examples.md deleted
-139
@@ -1,139 +0,0 @@
1 -# Power-User Examples
2 -
3 -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`.
4 -
5 -## Use `run` To Chain Tool Calls
6 -
7 -Fetch from multiple connected tools in one script:
8 -
9 -```bash
10 -composio run '
11 - const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
12 - const emails = await execute("GMAIL_FETCH_EMAILS", {
13 - max_results: 2,
14 - });
15 -
16 - console.log({
17 - login: me.data.login,
18 - emailCount: Array.isArray(emails.data?.messages) ? emails.data.messages.length : null,
19 - });
20 -'
21 -```
22 -
23 -If the user does not need script logic and just wants a few independent calls, prefer top-level parallel execute instead:
24 -
25 -```bash
26 -composio execute --parallel \
27 - GMAIL_FETCH_EMAILS -d '{ max_results: 2 }' \
28 - GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'
29 -```
30 -
31 -## Use `Promise.all` To Fan Out
32 -
33 -Fetch from multiple services at once:
34 -
35 -```bash
36 -composio run '
37 - const [me, emails] = await Promise.all([
38 - execute("GITHUB_GET_THE_AUTHENTICATED_USER"),
39 - execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),
40 - ]);
41 -
42 - console.log({
43 - login: me.data.login,
44 - emailCount: emails.data.messages?.length ?? null,
45 - });
46 -'
47 -```
48 -
49 -## Use `search()` Before `execute()` Inside A Script
50 -
51 -Discover a candidate slug, then execute it:
52 -
53 -```bash
54 -composio run '
55 - const results = await search("get the authenticated github user", {
56 - toolkits: "github",
57 - limit: 1,
58 - });
59 -
60 - const slug = results.results?.[0]?.primary_tool_slugs?.[0];
61 - if (!slug) throw new Error("No candidate tool found.");
62 -
63 - const output = await execute(slug);
64 -
65 - console.log(output.data.login);
66 -'
67 -```
68 -
69 -Batch related discovery work with multiple queries when it keeps the workflow simpler:
70 -
71 -```bash
72 -composio search "send an email" "create a github issue" --toolkits gmail,github
73 -```
74 -
75 -## Use `experimental_subAgent()` With `z` And `result.prompt()`
76 -
77 -Turn a tool result into structured output:
78 -
79 -```bash
80 -composio run --logs-off '
81 - const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 2 });
82 -
83 - const brief = await experimental_subAgent(
84 - `Return only valid JSON matching the schema. Summarize these emails in one sentence and report how many items were returned.\n\n${emails.prompt()}`,
85 - {
86 - schema: z.object({
87 - summary: z.string(),
88 - count: z.number(),
89 - }),
90 - }
91 - );
92 -
93 - console.log(brief.structuredOutput);
94 -'
95 -```
96 -
97 -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()`.
98 -
99 -## Use `proxy()` For Raw API Access
100 -
101 -`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()`.
102 -
103 -```bash
104 -composio run '
105 - const fetch = await proxy("github");
106 - const profile = await (await fetch("https://api.github.com/user")).json();
107 - console.log(profile);
108 -'
109 -```
110 -
111 -## Mix `execute()` And `proxy()`
112 -
113 -Use dedicated tools where they exist, then drop down to raw API calls for the missing step:
114 -
115 -```bash
116 -composio run '
117 - const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
118 -
119 - const fetch = await proxy("github");
120 - const repos = await (await fetch("https://api.github.com/user/repos?per_page=3")).json();
121 -
122 - console.log({
123 - login: me.data.login,
124 - repoCount: Array.isArray(repos) ? repos.length : null,
125 - });
126 -'
127 -```
128 -
129 -## Use `run` Flags Intentionally
130 -
131 -- Use `--dry-run` to preview every `execute()` call in the script.
132 -- Use `--debug` to see helper steps while the script runs.
133 -- Use `--logs-off` when `experimental_subAgent()` streaming logs are too noisy for the task.
134 -
135 -Example:
136 -
137 -```bash
138 -composio run --dry-run --debug 'await execute("GITHUB_CREATE_AN_ISSUE", { owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." })'
139 -```
ts/packages/cli/skills/composio-cli/references/troubleshooting.md deleted
-128
@@ -1,128 +0,0 @@
1 -# Troubleshooting
2 -
3 -Load this file when the user is stuck on top-level Composio CLI flows.
4 -
5 -## Not Logged In
6 -
7 -Symptoms:
8 -
9 -- `composio` commands fail because there is no user session
10 -- the user is unsure which account the CLI is using
11 -
12 -Fix:
13 -
14 -```bash
15 -composio whoami
16 -```
17 -
18 -If `composio whoami` fails, run `composio login` and then return to the original `execute` or `search` flow.
19 -
20 -## No Active Connection Found
21 -
22 -Symptoms:
23 -
24 -- `execute` reports that no active connection exists for a toolkit
25 -
26 -Fix:
27 -
28 -```bash
29 -composio link gmail --no-browser --no-wait
30 -composio link googlecalendar --no-browser --no-wait
31 -```
32 -
33 -After linking, retry the exact same `execute` command.
34 -
35 -## Invalid JSON Input
36 -
37 -Symptoms:
38 -
39 -- `execute` rejects `-d` input
40 -- the payload is not valid JSON or JS-style object syntax
41 -
42 -Fix:
43 -
44 -- Pass JSON or a JS-style object literal to `-d`
45 -- Use `@file` for large payloads
46 -- Use `-` to read from stdin
47 -
48 -Examples:
49 -
50 -```bash
51 -composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{"owner":"acme","repo":"app","title":"Bug report","body":"Steps to reproduce..."}'
52 -composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'
53 -composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d @payload.json
54 -cat payload.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d -
55 -```
56 -
57 -## Unknown Or Wrong Slug
58 -
59 -Symptoms:
60 -
61 -- the user does not know the tool slug
62 -- the slug exists but is not the right tool for the job
63 -
64 -Fix:
65 -
66 -```bash
67 -composio search "create a github issue"
68 -composio search "send an email" --toolkits gmail
69 -composio search "send an email" "create a github issue"
70 -```
71 -
72 -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.
73 -
74 -## Confusion About Required Inputs
75 -
76 -Symptoms:
77 -
78 -- the user is unsure what fields a tool accepts
79 -- the first payload attempt failed validation
80 -
81 -Fix:
82 -
83 -```bash
84 -composio execute GITHUB_CREATE_AN_ISSUE --get-schema -d '{}'
85 -composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'
86 -```
87 -
88 -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.
89 -
90 -## Several Independent Tool Calls
91 -
92 -Symptoms:
93 -
94 -- the user wants to run multiple unrelated tools in one step
95 -- the user is about to write a script only to execute a few independent calls
96 -
97 -Fix:
98 -
99 -```bash
100 -composio execute --parallel \
101 - GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com", subject: "Hi" }' \
102 - GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'
103 -```
104 -
105 -Escalate to `composio run` only when the user needs control flow, loops, `Promise.all`, `search()` inside a script, `proxy()`, or `experimental_subAgent()`.
106 -
107 -## `tools info` And `tools list` Are Fallbacks
108 -
109 -Treat these commands as secondary inspection tools:
110 -
111 -```bash
112 -composio tools info GMAIL_SEND_EMAIL
113 -composio tools list gmail
114 -```
115 -
116 -Do not lead with them when `execute`, `search`, `--get-schema`, or `--dry-run` can get the user unstuck faster.
117 -
118 -## Consumer Vs `composio dev`
119 -
120 -Use the top-level commands for normal end-user flows:
121 -
122 -- `composio execute`
123 -- `composio search`
124 -- `composio link`
125 -- `composio run`
126 -- `composio proxy`
127 -
128 -Load [composio-dev.md](composio-dev.md) only when the user explicitly needs developer projects, auth configs, connected accounts, triggers, logs, orgs, or projects.
ts/packages/cli/src/commands/index.ts
+3 -2
@@ -37,9 +37,10 @@ import {
37 formatResolveCommandProjectError,
38 resolveCommandProject,
39 } from 'src/services/command-project';
40 +import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
41 import {
41 - type CommandVisibility,
42 experimental,
43 + type CommandVisibility,
44 type TaggedValue,
45 tagged,
46 visibleValues,
@@ -51,7 +52,7 @@ const ROOT_COMMANDS: ReadonlyArray<TaggedValue<Command.Command<any, any, any, an
52 tagged(upgradeCmd),
53 tagged(whoamiCmd),
54 tagged(loginCmd),
54 - experimental('listen', listenCmd),
55 + experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, listenCmd),
56 tagged(logoutCmd),
57 tagged(runCmd),
58 tagged(proxyCmd),
ts/packages/cli/src/commands/login.cmd.ts
+5 -7
@@ -12,7 +12,8 @@ import { TerminalUI } from 'src/services/terminal-ui';
12 import { commandHintStep } from 'src/services/command-hints';
13 import { runOrgSelection } from 'src/effects/select-org-project';
14 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
15 -import { installSkillSafe } from 'src/effects/install-skill';
15 +import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
16 +import { APP_VERSION } from 'src/constants';
17
18 export const noBrowser = Options.boolean('no-browser').pipe(
19 Options.withDefault(false),
@@ -42,10 +43,7 @@ const noSkillInstall = Options.boolean('no-skill-install').pipe(
43 Options.withDescription('Skip installing the composio-cli skill for Claude Code')
44 );
45
45 -const formatLoginSuccessMessage = (params: {
46 - email?: string;
47 - orgName?: string;
48 -}): string => {
46 +const formatLoginSuccessMessage = (params: { email?: string; orgName?: string }): string => {
47 const { email, orgName } = params;
48 if (email && orgName) {
49 return `Logged in as ${email} in "${orgName}"`;
@@ -482,7 +480,7 @@ export const loginCmd = Command.make(
480 skipOrgProjectPicker: true,
481 });
482 if (!noSkillInstall) {
485 - yield* installSkillSafe();
483 + yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
484 }
485 return;
486 }
@@ -506,7 +504,7 @@ export const loginCmd = Command.make(
504 });
505
506 if (!noSkillInstall && !noWait) {
509 - yield* installSkillSafe();
507 + yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
508 }
509 })
510 ).pipe(Command.withDescription('Log in to the Composio SDK.'));
ts/packages/cli/src/commands/root-help.ts
+45 -31
@@ -1,4 +1,5 @@
1 -import { Console, Effect } from 'effect';
1 +import { Console, Effect, Option } from 'effect';
2 +import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
3 import { bold, dim, gray } from 'src/ui/colors';
4 import {
5 type CommandVisibility,
@@ -79,10 +80,10 @@ const CORE_COMMANDS: ReadonlyArray<TaggedValue<DetailedCommand>> = [
80 { name: '--dry-run', description: 'Preview execute() calls without running remote actions' },
81 ],
82 }),
82 - experimental('listen', {
83 + experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, {
84 name: 'listen',
85 description:
85 - 'Listen to consumer-project realtime events and persist each payload into the session artifact folder.',
86 + 'Create a temporary subscription for consumer-project events and persist each payload into the session artifact folder.',
87 usage:
88 'listen <slug> [-p, --params text] [--max-events integer] [--timeout text] [--stream [text]]',
89 options: [
@@ -207,7 +208,7 @@ type SubcommandHelp = {
208 seeAlso?: ReadonlyArray<string>;
209 };
210
210 -const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
211 +const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHelp>> = {
212 search: {
213 usage: 'composio search <query...> [--toolkits text] [--limit integer] [--human]',
214 description:
@@ -314,23 +315,17 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
315 'composio artifacts cwd Print the current session artifact directory',
316 ],
317 },
317 - listen: {
318 + listen: experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, {
319 usage:
320 'composio listen <slug> [-p, --params text] [--max-events integer] [--timeout text] [--stream [text]]',
321 description:
321 - 'Listen to consumer-project realtime events. Trigger slugs create a temporary trigger; top-level composio.* event types subscribe directly.',
322 - args: [
323 - {
324 - name: '<slug>',
325 - description:
326 - 'Trigger slug to create and listen to, or a project event type such as "composio.connected_account.expired"',
327 - },
328 - ],
322 + 'Create a temporary subscription for consumer-project events so background agents can easily consume new emails, Slack messages, and other trigger payloads from artifacts.',
323 + args: [{ name: '<slug>', description: 'Trigger slug to create and listen to' }],
324 options: [
325 {
326 name: '-p, --params <text>',
327 description:
333 - 'Trigger create params as JSON/JS object, @file, or - for stdin. Only valid for trigger slugs.',
328 + 'Trigger create params as JSON/JS object, @file, or - for stdin. Pass optional trigger config fields only.',
329 },
330 {
331 name: '--max-events <integer>',
@@ -352,7 +347,6 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
347 'composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 5m',
348 "composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 1hr --stream '.data.threadId'",
349 'composio listen SLACK_RECEIVE_MESSAGE -p \'{ trigger_config: { channel: "C123" } }\'',
355 - 'composio listen composio.connected_account.expired --max-events 1',
350 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream',
351 "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
352 ],
@@ -361,7 +355,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
355 'composio triggers info <slug> Inspect trigger type details before listening',
356 'composio link <toolkit> Connect the required account before creating the trigger',
357 ],
364 - },
358 + }),
359 link: {
360 usage: 'composio link [<toolkit>] [--no-wait]',
361 description:
@@ -943,6 +937,28 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
937 },
938 };
939
940 +const getVisibleSubcommandHelp = (
941 + cmd: string,
942 + visibility: CommandVisibility
943 +): Option.Option<SubcommandHelp> => {
944 + const entry = SUBCOMMAND_HELP[cmd];
945 + if (!entry) {
946 + return Option.none();
947 + }
948 +
949 + if (!('value' in entry)) {
950 + return Option.some(entry);
951 + }
952 +
953 + if (!entry.tags || entry.tags.length === 0) {
954 + return Option.some(entry.value);
955 + }
956 +
957 + return entry.tags.every(tag => visibility.isExperimentalFeatureEnabled(tag))
958 + ? Option.some(entry.value)
959 + : Option.none();
960 +};
961 +
962 function renderSubcommandHelp(cmd: SubcommandHelp): string {
963 const lines: string[] = [
964 '',
@@ -1012,7 +1028,7 @@ function renderSubcommandHelp(cmd: SubcommandHelp): string {
1028 */
1029 export function matchSubcommandHelp(
1030 argv: ReadonlyArray<string>,
1015 - _visibility: CommandVisibility
1031 + visibility: CommandVisibility
1032 ): string | undefined {
1033 const args = argv.slice(2);
1034 if (args.length < 2) return undefined;
@@ -1023,18 +1039,18 @@ export function matchSubcommandHelp(
1039 // Try longest match first: "dev toolkits list" → "dev toolkits" → "dev"
1040 for (let len = cmdParts.length; len > 0; len--) {
1041 const key = cmdParts.slice(0, len).join(' ');
1026 - if (key in SUBCOMMAND_HELP) return key;
1042 + if (Option.isSome(getVisibleSubcommandHelp(key, visibility))) return key;
1043 }
1044 return undefined;
1045 }
1046
1047 export function printSubcommandHelp(
1048 cmd: string,
1033 - _visibility: CommandVisibility
1049 + visibility: CommandVisibility
1050 ): Effect.Effect<void> {
1035 - const help = SUBCOMMAND_HELP[cmd];
1036 - if (!help) return Console.log(`Unknown command: ${cmd}`);
1037 - return Console.log(renderSubcommandHelp(help));
1051 + const help = getVisibleSubcommandHelp(cmd, visibility);
1052 + if (Option.isNone(help)) return Console.log(`Unknown command: ${cmd}`);
1053 + return Console.log(renderSubcommandHelp(help.value));
1054 }
1055
1056 /**
@@ -1043,13 +1059,13 @@ export function printSubcommandHelp(
1059 */
1060 export function matchCommandFromArgv(
1061 argv: ReadonlyArray<string>,
1046 - _visibility: CommandVisibility
1062 + visibility: CommandVisibility
1063 ): string | undefined {
1064 const args = argv.slice(2).filter(a => a !== '--help' && a !== '-h' && !a.startsWith('--'));
1065 // Try longest match first: "dev toolkits list" → "dev toolkits" → "dev"
1066 for (let len = Math.min(args.length, 3); len > 0; len--) {
1067 const key = args.slice(0, len).join(' ');
1052 - if (key in SUBCOMMAND_HELP) return key;
1068 + if (Option.isSome(getVisibleSubcommandHelp(key, visibility))) return key;
1069 }
1070 return undefined;
1071 }
@@ -1057,13 +1073,11 @@ export function matchCommandFromArgv(
1073 /**
1074 * Get rendered help text for a command, or undefined if not found.
1075 */
1060 -export function getCommandHelpText(
1061 - cmd: string,
1062 - _visibility: CommandVisibility
1063 -): string | undefined {
1064 - const help = SUBCOMMAND_HELP[cmd];
1065 - if (!help) return undefined;
1066 - return renderSubcommandHelp(help);
1076 +export function getCommandHelpText(cmd: string, visibility: CommandVisibility): string | undefined {
1077 + return Option.match(getVisibleSubcommandHelp(cmd, visibility), {
1078 + onNone: () => undefined,
1079 + onSome: help => renderSubcommandHelp(help),
1080 + });
1081 }
1082
1083 // ── Main help output ───────────────────────────────────────────────────
ts/packages/cli/src/commands/upgrade.cmd.ts
+3 -1
@@ -22,6 +22,8 @@ export const upgradeCmd = Command.make('upgrade', { beta: betaOpt }, ({ beta })
22 Effect.gen(function* () {
23 const upgradeBinary = yield* UpgradeBinary;
24 const newReleaseTag = yield* upgradeBinary.upgrade({ prerelease: beta });
25 - yield* installSkillSafe({ releaseTag: newReleaseTag ?? `@composio/cli@${APP_VERSION}` });
25 + yield* installSkillSafe({
26 + releaseTag: newReleaseTag ?? `@composio/cli@${APP_VERSION}`,
27 + });
28 })
29 ).pipe(Command.withDescription('Upgrade your Composio CLI to the latest available version.'));
ts/packages/cli/src/constants.ts
+4
@@ -85,3 +85,7 @@ export const GITHUB_REPO = {
85 REPO: 'composio',
86 API_BASE_URL: 'https://api.github.com',
87 } as const;
88 +
89 +export const CLI_EXPERIMENTAL_FEATURES = {
90 + LISTEN: 'listen',
91 +} as const;
ts/packages/cli/src/effects/install-skill.ts
+67 -6
@@ -6,10 +6,63 @@ import { NodeOs } from 'src/services/node-os';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { GITHUB_CONFIG } from 'src/effects/github-config';
8 import { APP_VERSION } from 'src/constants';
9 +import {
10 + fetchLatestCliRelease,
11 + type GitHubRelease,
12 + type GitHubRepoConfig,
13 +} from 'src/effects/resolve-cli-release';
14 import decompress from 'decompress';
15
16 const SKILL_NAME = 'composio-cli';
17 const SKILL_ASSET_NAME = 'composio-skill.zip';
18 +export type SkillReleaseChannel = 'beta' | 'stable';
19 +
20 +type GitHubConfig = GitHubRepoConfig & {
21 + TAG: Option.Option<string>;
22 + ACCESS_TOKEN: Option.Option<string>;
23 +};
24 +
25 +const hasSkillAsset = (release: GitHubRelease) =>
26 + release.assets.some(asset => asset.name === SKILL_ASSET_NAME);
27 +
28 +export const inferSkillReleaseChannel = (tagOrVersion: string): SkillReleaseChannel =>
29 + tagOrVersion.includes('-beta.') ? 'beta' : 'stable';
30 +
31 +export const resolveSkillReleaseTag = ({
32 + channel,
33 + githubConfig,
34 + httpClient,
35 + releaseTag,
36 +}: {
37 + channel?: SkillReleaseChannel;
38 + githubConfig: GitHubConfig;
39 + httpClient: HttpClient.HttpClient;
40 + releaseTag?: string;
41 +}) =>
42 + Effect.gen(function* () {
43 + if (releaseTag) {
44 + return releaseTag;
45 + }
46 +
47 + const configTag = Option.getOrUndefined(githubConfig.TAG);
48 + if (configTag) {
49 + return configTag;
50 + }
51 +
52 + if (!channel) {
53 + return `@composio/cli@${APP_VERSION}`;
54 + }
55 +
56 + const latest = yield* fetchLatestCliRelease({
57 + assetDescription: SKILL_ASSET_NAME,
58 + channel,
59 + githubConfig,
60 + hasRequiredAsset: hasSkillAsset,
61 + httpClient,
62 + });
63 +
64 + return latest.tag_name;
65 + });
66
67 /**
68 * Install the composio-cli skill into the user's global agent skills directory.
@@ -20,7 +73,10 @@ const SKILL_ASSET_NAME = 'composio-skill.zip';
73 *
74 * Non-fatal: wrapped version catches all errors.
75 */
23 -export const installSkill = (options?: { readonly releaseTag?: string }) =>
76 +export const installSkill = (options?: {
77 + readonly releaseTag?: string;
78 + readonly channel?: SkillReleaseChannel;
79 +}) =>
80 Effect.gen(function* () {
81 const os = yield* NodeOs;
82 const ui = yield* TerminalUI;
@@ -31,10 +87,12 @@ export const installSkill = (options?: { readonly releaseTag?: string }) =>
87 const agentSkillDir = path.join(home, '.agents', 'skills', SKILL_NAME);
88 const claudeSkillLink = path.join(home, '.claude', 'skills', SKILL_NAME);
89
34 - // Resolve the release tag — prefer explicit override, then env config, then current version
35 - const tag =
36 - options?.releaseTag ??
37 - Option.getOrElse(githubConfig.TAG, () => `@composio/cli@${APP_VERSION}`);
90 + const tag = yield* resolveSkillReleaseTag({
91 + channel: options?.channel,
92 + githubConfig,
93 + httpClient,
94 + releaseTag: options?.releaseTag,
95 + });
96
97 // Find the skill asset URL from the release
98 const 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 }) =>
185 /**
186 * Wrapped version that catches all errors and logs a warning instead of failing.
187 */
130 -export const installSkillSafe = (options?: { readonly releaseTag?: string }) =>
188 +export const installSkillSafe = (options?: {
189 + readonly releaseTag?: string;
190 + readonly channel?: SkillReleaseChannel;
191 +}) =>
192 installSkill(options).pipe(
193 Effect.sandbox,
194 Effect.catchAll(cause =>
ts/packages/cli/src/effects/resolve-cli-release.ts new
+98
@@ -0,0 +1,98 @@
1 +import { Effect } from 'effect';
2 +import { HttpClient } from '@effect/platform';
3 +import { semverComparator } from 'src/effects/compare-semver';
4 +
5 +export type CliReleaseChannel = 'beta' | 'stable';
6 +
7 +export type GitHubReleaseAsset = {
8 + name: string;
9 + browser_download_url: string;
10 +};
11 +
12 +export type GitHubRelease = {
13 + tag_name: string;
14 + prerelease?: boolean;
15 + draft?: boolean;
16 + assets: Array<GitHubReleaseAsset>;
17 +};
18 +
19 +export type GitHubRepoConfig = {
20 + API_BASE_URL: string;
21 + OWNER: string;
22 + REPO: string;
23 +};
24 +
25 +export const CLI_RELEASE_TAG_PATTERN = /^@composio\/cli@\d+\.\d+\.\d+.*$/;
26 +
27 +export const fetchLatestCliRelease = ({
28 + assetDescription,
29 + channel,
30 + githubConfig,
31 + hasRequiredAsset,
32 + httpClient,
33 +}: {
34 + assetDescription: string;
35 + channel: CliReleaseChannel;
36 + githubConfig: GitHubRepoConfig;
37 + hasRequiredAsset: (release: GitHubRelease) => boolean;
38 + httpClient: HttpClient.HttpClient;
39 +}) =>
40 + Effect.gen(function* () {
41 + const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases?per_page=100`;
42 + const releaseResponse = yield* httpClient
43 + .get(releaseUrl)
44 + .pipe(
45 + Effect.catchAll(error =>
46 + Effect.fail(new Error(`Failed to fetch ${channel} releases from GitHub: ${error}`))
47 + )
48 + );
49 +
50 + if (releaseResponse.status < 200 || releaseResponse.status >= 300) {
51 + return yield* Effect.fail(
52 + new Error(
53 + `Failed to fetch ${channel} releases from GitHub (HTTP ${releaseResponse.status})`
54 + )
55 + );
56 + }
57 +
58 + const releases = (yield* releaseResponse.json.pipe(
59 + Effect.catchAll(() => Effect.fail(new Error('Failed to parse GitHub releases JSON')))
60 + )) as unknown;
61 +
62 + if (!Array.isArray(releases)) {
63 + return yield* Effect.fail(new Error('GitHub releases response was not an array'));
64 + }
65 +
66 + const prerelease = channel === 'beta';
67 + const matchingReleases = releases.filter(
68 + (release): release is GitHubRelease =>
69 + typeof release === 'object' &&
70 + release !== null &&
71 + 'tag_name' in release &&
72 + typeof release.tag_name === 'string' &&
73 + ('prerelease' in release ? release.prerelease === prerelease : prerelease === false) &&
74 + ('draft' in release ? release.draft === false : true) &&
75 + CLI_RELEASE_TAG_PATTERN.test(release.tag_name) &&
76 + Array.isArray(release.assets) &&
77 + hasRequiredAsset(release)
78 + );
79 +
80 + if (matchingReleases.length === 0) {
81 + return yield* Effect.fail(
82 + new Error(`No ${channel} CLI releases found with ${assetDescription}`)
83 + );
84 + }
85 +
86 + let latest = matchingReleases[0];
87 + for (const release of matchingReleases.slice(1)) {
88 + const comparison = yield* semverComparator(latest.tag_name, release.tag_name).pipe(
89 + Effect.mapError(error => new Error(`Failed to compare release versions: ${error}`))
90 + );
91 +
92 + if (comparison < 0) {
93 + latest = release;
94 + }
95 + }
96 +
97 + return latest;
98 + });
ts/packages/cli/src/services/upgrade-binary.ts
+19 -82
@@ -6,6 +6,7 @@ import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
6 import { GITHUB_CONFIG } from 'src/effects/github-config';
7 import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform';
8 import { CompareSemverError, semverComparator } from 'src/effects/compare-semver';
9 +import { fetchLatestCliRelease, type GitHubRelease } from 'src/effects/resolve-cli-release';
10
11 // Note: `node:zlib` does not support Github's zip files
12 import decompress from 'decompress';
@@ -28,18 +29,6 @@ export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinary
29 */
30 export const CLI_BINARY_NAME = 'composio';
31
31 -type GitHubRelease = {
32 - tag_name: string;
33 - prerelease?: boolean;
34 - draft?: boolean;
35 - assets: Array<{
36 - name: string;
37 - browser_download_url: string;
38 - }>;
39 -};
40 -
41 -const CLI_RELEASE_TAG_PATTERN = /^@composio\/cli@\d+\.\d+\.\d+.*$/;
42 -
32 const getBinaryAssetName = (platformArch: PlatformArch) =>
33 `${CLI_BINARY_NAME}-${platformArch.platform}-${platformArch.arch}.zip`;
34
@@ -122,78 +111,26 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
111 yield* Effect.logDebug(
112 `No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release`
113 );
125 - const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases?per_page=100`;
126 - const releases = yield* fetchGitHubJson<unknown>({
127 - url,
128 - fetchErrorMessage: 'Failed to fetch releases from GitHub',
129 - parseErrorMessage: 'Failed to parse GitHub releases JSON response',
130 - });
131 -
132 - if (!Array.isArray(releases)) {
133 - return yield* Effect.fail(
134 - new UpgradeBinaryError({
135 - cause: new Error('GitHub releases response was not an array'),
136 - message: 'Unexpected response while resolving latest CLI release',
137 - })
138 - );
139 - }
140 -
141 - const cliReleases = releases.filter(
142 - (release): release is GitHubRelease =>
143 - typeof release === 'object' &&
144 - release !== null &&
145 - 'tag_name' in release &&
146 - typeof release.tag_name === 'string' &&
147 - ('prerelease' in release
148 - ? release.prerelease === prerelease
149 - : prerelease === false) &&
150 - ('draft' in release ? release.draft === false : true) &&
151 - CLI_RELEASE_TAG_PATTERN.test(release.tag_name)
152 - );
153 -
154 - if (cliReleases.length === 0) {
155 - return yield* Effect.fail(
156 - new UpgradeBinaryError({
157 - cause: new Error(
158 - `No package-scoped CLI ${prerelease ? 'beta' : 'stable'} releases found`
159 - ),
160 - message: `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,
161 - })
162 - );
163 - }
164 -
165 - const cliReleasesWithBinary = cliReleases.filter(release =>
166 - hasPlatformBinaryAsset(release, platformArch)
114 + const latest = yield* fetchLatestCliRelease({
115 + assetDescription: getBinaryAssetName(platformArch),
116 + channel: prerelease ? 'beta' : 'stable',
117 + githubConfig,
118 + hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch),
119 + httpClient,
120 + }).pipe(
121 + Effect.mapError(
122 + error =>
123 + new UpgradeBinaryError({
124 + cause: error,
125 + message: error.message.startsWith('Failed to fetch ')
126 + ? 'Failed to fetch releases from GitHub'
127 + : error.message === 'Failed to parse GitHub releases JSON'
128 + ? 'Failed to parse GitHub releases JSON response'
129 + : `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,
130 + })
131 + )
132 );
133
169 - if (cliReleasesWithBinary.length === 0) {
170 - return yield* Effect.fail(
171 - new UpgradeBinaryError({
172 - cause: new Error(
173 - `No package-scoped CLI ${prerelease ? 'beta' : 'stable'} releases found with ${getBinaryAssetName(platformArch)}`
174 - ),
175 - message: `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,
176 - })
177 - );
178 - }
179 -
180 - let latest = cliReleasesWithBinary[0];
181 - for (const release of cliReleasesWithBinary.slice(1)) {
182 - const comparison = yield* semverComparator(latest.tag_name, release.tag_name).pipe(
183 - Effect.mapError(
184 - error =>
185 - new UpgradeBinaryError({
186 - cause: error,
187 - message: 'Failed to compare CLI release versions',
188 - })
189 - )
190 - );
191 -
192 - if (comparison < 0) {
193 - latest = release;
194 - }
195 - }
196 -
134 yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);
135 return latest;
136 }),
ts/packages/cli/test/src/commands/feature-visibility.test.ts new
+45
@@ -0,0 +1,45 @@
1 +import { CommandDescriptor } from '@effect/cli';
2 +import { HashMap } from 'effect';
3 +import { describe, expect, it } from 'vitest';
4 +import { buildRootCommand } from 'src/commands';
5 +import {
6 + getCommandHelpText,
7 + matchCommandFromArgv,
8 + matchSubcommandHelp,
9 +} from 'src/commands/root-help';
10 +
11 +const stableVisibility = {
12 + isExperimentalFeatureEnabled: () => false,
13 +};
14 +
15 +const betaVisibility = {
16 + isExperimentalFeatureEnabled: () => true,
17 +};
18 +
19 +const getSubcommandNames = (visibility: typeof stableVisibility) =>
20 + HashMap.toEntries(CommandDescriptor.getSubcommands(buildRootCommand(visibility).descriptor)).map(
21 + ([name]) => name
22 + );
23 +
24 +describe('CLI experimental feature visibility', () => {
25 + it('hides listen from the stable root command graph', () => {
26 + expect(getSubcommandNames(stableVisibility)).not.toContain('listen');
27 + expect(getSubcommandNames(betaVisibility)).toContain('listen');
28 + });
29 +
30 + it('hides listen help when the feature is disabled', () => {
31 + expect(matchSubcommandHelp(['bun', 'composio', 'listen', '--help'], stableVisibility)).toBe(
32 + undefined
33 + );
34 + expect(matchSubcommandHelp(['bun', 'composio', 'listen', '--help'], betaVisibility)).toBe(
35 + 'listen'
36 + );
37 + });
38 +
39 + it('hides contextual listen help when the feature is disabled', () => {
40 + expect(matchCommandFromArgv(['bun', 'composio', 'listen'], stableVisibility)).toBe(undefined);
41 + expect(matchCommandFromArgv(['bun', 'composio', 'listen'], betaVisibility)).toBe('listen');
42 + expect(getCommandHelpText('listen', stableVisibility)).toBe(undefined);
43 + expect(getCommandHelpText('listen', betaVisibility)).toContain('composio listen');
44 + });
45 +});
ts/packages/cli/test/src/effects/install-skill.test.ts new
+173
@@ -0,0 +1,173 @@
1 +import { describe, expect, it, vi } from '@effect/vitest';
2 +import { Config, ConfigProvider, Effect } from 'effect';
3 +import { FetchHttpClient, HttpClient } from '@effect/platform';
4 +import { withHttpServer } from 'test/__utils__/http-server';
5 +import {
6 + inferSkillReleaseChannel,
7 + resolveSkillReleaseTag,
8 + type SkillReleaseChannel,
9 +} from 'src/effects/install-skill';
10 +import { GITHUB_CONFIG } from 'src/effects/github-config';
11 +
12 +const makeResolveEffect = (
13 + configEntries: ReadonlyArray<[string, string]>,
14 + options: {
15 + channel?: SkillReleaseChannel;
16 + releaseTag?: string;
17 + } = {}
18 +) =>
19 + Effect.gen(function* () {
20 + const httpClient = yield* HttpClient.HttpClient;
21 + const githubConfig = yield* Config.all(GITHUB_CONFIG);
22 +
23 + return yield* resolveSkillReleaseTag({
24 + channel: options.channel,
25 + githubConfig,
26 + httpClient,
27 + releaseTag: options.releaseTag,
28 + });
29 + }).pipe(
30 + Effect.provide(FetchHttpClient.layer),
31 + Effect.withConfigProvider(ConfigProvider.fromMap(new Map(configEntries))),
32 + Effect.scoped
33 + );
34 +
35 +describe('install-skill', () => {
36 + it('infers the stable channel from stable versions', () => {
37 + expect(inferSkillReleaseChannel('0.2.19')).toBe('stable');
38 + expect(inferSkillReleaseChannel('@composio/cli@0.2.19')).toBe('stable');
39 + });
40 +
41 + it('infers the beta channel from beta versions', () => {
42 + expect(inferSkillReleaseChannel('0.2.20-beta.4')).toBe('beta');
43 + expect(inferSkillReleaseChannel('@composio/cli@0.2.20-beta.4')).toBe('beta');
44 + });
45 +
46 + it('resolves the latest stable release when the stable channel is requested', async () => {
47 + vi.stubGlobal('Bun', { which: vi.fn(() => null) });
48 +
49 + try {
50 + await withHttpServer(
51 + (_req, res) => {
52 + res.writeHead(200, { 'content-type': 'application/json' });
53 + res.end(
54 + JSON.stringify([
55 + {
56 + tag_name: '@composio/cli@0.2.20-beta.2',
57 + draft: false,
58 + prerelease: true,
59 + assets: [
60 + {
61 + name: 'composio-skill.zip',
62 + browser_download_url: 'http://127.0.0.1/beta-skill.zip',
63 + },
64 + ],
65 + },
66 + {
67 + tag_name: '@composio/cli@0.2.19',
68 + draft: false,
69 + prerelease: false,
70 + assets: [
71 + {
72 + name: 'composio-skill.zip',
73 + browser_download_url: 'http://127.0.0.1/stable-skill.zip',
74 + },
75 + ],
76 + },
77 + {
78 + tag_name: '@composio/cli@0.2.20',
79 + draft: false,
80 + prerelease: false,
81 + assets: [
82 + {
83 + name: 'composio-linux-x64.zip',
84 + browser_download_url: 'http://127.0.0.1/no-skill.zip',
85 + },
86 + ],
87 + },
88 + ])
89 + );
90 + },
91 + async apiBaseUrl => {
92 + const tag = await makeResolveEffect(
93 + [
94 + ['GITHUB_API_BASE_URL', apiBaseUrl],
95 + ['GITHUB_OWNER', 'test-owner'],
96 + ['GITHUB_REPO', 'test-repo'],
97 + ],
98 + { channel: 'stable' }
99 + ).pipe(Effect.runPromise);
100 +
101 + expect(tag).toBe('@composio/cli@0.2.19');
102 + }
103 + );
104 + } finally {
105 + vi.unstubAllGlobals();
106 + vi.restoreAllMocks();
107 + }
108 + });
109 +
110 + it('resolves the latest beta release when the beta channel is requested', async () => {
111 + vi.stubGlobal('Bun', { which: vi.fn(() => null) });
112 +
113 + try {
114 + await withHttpServer(
115 + (_req, res) => {
116 + res.writeHead(200, { 'content-type': 'application/json' });
117 + res.end(
118 + JSON.stringify([
119 + {
120 + tag_name: '@composio/cli@0.2.20-beta.1',
121 + draft: false,
122 + prerelease: true,
123 + assets: [
124 + {
125 + name: 'composio-skill.zip',
126 + browser_download_url: 'http://127.0.0.1/beta-1-skill.zip',
127 + },
128 + ],
129 + },
130 + {
131 + tag_name: '@composio/cli@0.2.20-beta.3',
132 + draft: false,
133 + prerelease: true,
134 + assets: [
135 + {
136 + name: 'composio-skill.zip',
137 + browser_download_url: 'http://127.0.0.1/beta-3-skill.zip',
138 + },
139 + ],
140 + },
141 + {
142 + tag_name: '@composio/cli@0.2.20',
143 + draft: false,
144 + prerelease: false,
145 + assets: [
146 + {
147 + name: 'composio-skill.zip',
148 + browser_download_url: 'http://127.0.0.1/stable-skill.zip',
149 + },
150 + ],
151 + },
152 + ])
153 + );
154 + },
155 + async apiBaseUrl => {
156 + const tag = await makeResolveEffect(
157 + [
158 + ['GITHUB_API_BASE_URL', apiBaseUrl],
159 + ['GITHUB_OWNER', 'test-owner'],
160 + ['GITHUB_REPO', 'test-repo'],
161 + ],
162 + { channel: 'beta' }
163 + ).pipe(Effect.runPromise);
164 +
165 + expect(tag).toBe('@composio/cli@0.2.20-beta.3');
166 + }
167 + );
168 + } finally {
169 + vi.unstubAllGlobals();
170 + vi.restoreAllMocks();
171 + }
172 + });
173 +});
ts/packages/cli/test/src/services/cli-user-config.test.ts
-1
@@ -104,7 +104,6 @@ describe('ComposioCliUserConfig', () => {
104 assertEquals(parsed.experimental_subagent.target, 'claude');
105 }).pipe(Effect.provide(CliUserConfigTest));
106 });
107 -
107 it.effect('resolves sync config path from COMPOSIO_CACHE_DIR when provided', () => {
108 const cacheDir = tempy.temporaryDirectory();
109 process.env.COMPOSIO_CACHE_DIR = cacheDir;
ts/scripts/validate-examples.ts new
+236
@@ -0,0 +1,236 @@
1 +import * as fs from 'node:fs';
2 +import * as path from 'node:path';
3 +import ts from 'typescript';
4 +
5 +const repoRoot = process.cwd();
6 +const examplesRoot = path.join(repoRoot, 'ts', 'examples');
7 +const allowedSourceExtensions = new Set([
8 + '.cjs',
9 + '.cts',
10 + '.js',
11 + '.jsx',
12 + '.mjs',
13 + '.mts',
14 + '.ts',
15 + '.tsx',
16 + '.json',
17 +]);
18 +
19 +type ValidationIssue = {
20 + example: string;
21 + file: string;
22 + message: string;
23 +};
24 +
25 +const issues: ValidationIssue[] = [];
26 +
27 +const addIssue = (example: string, file: string, message: string) => {
28 + issues.push({ example, file, message });
29 +};
30 +
31 +const collectFiles = (dir: string): string[] => {
32 + const entries = fs.readdirSync(dir, { withFileTypes: true });
33 + return entries.flatMap(entry => {
34 + const fullPath = path.join(dir, entry.name);
35 + if (entry.isDirectory()) {
36 + return collectFiles(fullPath);
37 + }
38 + return [fullPath];
39 + });
40 +};
41 +
42 +const validatePackageJson = (exampleName: string, exampleDir: string) => {
43 + const packageJsonPath = path.join(exampleDir, 'package.json');
44 +
45 + if (!fs.existsSync(packageJsonPath)) {
46 + addIssue(exampleName, packageJsonPath, 'Missing package.json');
47 + return;
48 + }
49 +
50 + try {
51 + const raw = fs.readFileSync(packageJsonPath, 'utf8');
52 + const pkg = JSON.parse(raw) as {
53 + dependencies?: Record<string, string>;
54 + devDependencies?: Record<string, string>;
55 + name?: string;
56 + packageManager?: string;
57 + private?: boolean;
58 + scripts?: Record<string, string>;
59 + };
60 +
61 + if (!pkg.name?.endsWith('-example')) {
62 + addIssue(exampleName, packageJsonPath, 'Package name should end with "-example"');
63 + }
64 +
65 + if (pkg.private !== true) {
66 + addIssue(exampleName, packageJsonPath, 'Examples must be marked private');
67 + }
68 +
69 + if (!pkg.packageManager?.startsWith('pnpm@')) {
70 + addIssue(exampleName, packageJsonPath, 'Examples must declare a pnpm packageManager');
71 + }
72 +
73 + if (!pkg.scripts || (!pkg.scripts.start && !pkg.scripts.dev)) {
74 + addIssue(exampleName, packageJsonPath, 'Examples must expose a start or dev script');
75 + }
76 +
77 + const allDeps = {
78 + ...(pkg.dependencies ?? {}),
79 + ...(pkg.devDependencies ?? {}),
80 + };
81 +
82 + if (!Object.keys(allDeps).some(dep => dep.startsWith('@composio/'))) {
83 + addIssue(exampleName, packageJsonPath, 'Examples must depend on at least one @composio package');
84 + }
85 + } catch (error) {
86 + addIssue(
87 + exampleName,
88 + packageJsonPath,
89 + `Invalid package.json: ${error instanceof Error ? error.message : String(error)}`
90 + );
91 + }
92 +};
93 +
94 +const validateTsconfig = (exampleName: string, exampleDir: string) => {
95 + const tsconfigPath = path.join(exampleDir, 'tsconfig.json');
96 +
97 + if (!fs.existsSync(tsconfigPath)) {
98 + addIssue(exampleName, tsconfigPath, 'Missing tsconfig.json');
99 + return;
100 + }
101 +
102 + try {
103 + const raw = fs.readFileSync(tsconfigPath, 'utf8');
104 + const parsed = ts.parseConfigFileTextToJson(tsconfigPath, raw);
105 +
106 + if (parsed.error) {
107 + const message = ts.flattenDiagnosticMessageText(parsed.error.messageText, '\n');
108 + addIssue(exampleName, tsconfigPath, `Invalid tsconfig.json: ${message}`);
109 + return;
110 + }
111 +
112 + const config = parsed.config as { include?: string[] } | undefined;
113 + if (!Array.isArray(config?.include) || config.include.length === 0) {
114 + addIssue(exampleName, tsconfigPath, 'tsconfig.json should define a non-empty include array');
115 + }
116 + } catch (error) {
117 + addIssue(
118 + exampleName,
119 + tsconfigPath,
120 + `Invalid tsconfig.json: ${error instanceof Error ? error.message : String(error)}`
121 + );
122 + }
123 +};
124 +
125 +const validateSourceFile = (exampleName: string, filePath: string) => {
126 + const extension = path.extname(filePath);
127 + const relativePath = path.relative(repoRoot, filePath);
128 +
129 + if (extension === '.json') {
130 + try {
131 + JSON.parse(fs.readFileSync(filePath, 'utf8'));
132 + } catch (error) {
133 + addIssue(
134 + exampleName,
135 + relativePath,
136 + `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`
137 + );
138 + }
139 + return;
140 + }
141 +
142 + const sourceText = fs.readFileSync(filePath, 'utf8');
143 + const isTsFile = ['.ts', '.tsx', '.mts', '.cts'].includes(extension);
144 + const scriptKind = extension === '.tsx'
145 + ? ts.ScriptKind.TSX
146 + : extension === '.jsx'
147 + ? ts.ScriptKind.JSX
148 + : extension === '.js'
149 + ? ts.ScriptKind.JS
150 + : extension === '.cjs'
151 + ? ts.ScriptKind.JS
152 + : extension === '.mjs'
153 + ? ts.ScriptKind.JS
154 + : ts.ScriptKind.TS;
155 +
156 + const transpiled = ts.transpileModule(sourceText, {
157 + compilerOptions: {
158 + allowJs: true,
159 + module: ts.ModuleKind.ESNext,
160 + target: ts.ScriptTarget.ES2022,
161 + },
162 + fileName: filePath,
163 + reportDiagnostics: true,
164 + });
165 +
166 + for (const diagnostic of transpiled.diagnostics ?? []) {
167 + if (diagnostic.category !== ts.DiagnosticCategory.Error) {
168 + continue;
169 + }
170 +
171 + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
172 + const location =
173 + diagnostic.start !== undefined
174 + ? ts.getLineAndCharacterOfPosition(
175 + ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.ES2022, true, scriptKind),
176 + diagnostic.start
177 + )
178 + : undefined;
179 +
180 + const formattedLocation = location
181 + ? `:${location.line + 1}:${location.character + 1}`
182 + : '';
183 +
184 + addIssue(exampleName, `${relativePath}${formattedLocation}`, `Syntax error: ${message}`);
185 + }
186 +
187 + if (isTsFile && sourceText.trim().length === 0) {
188 + addIssue(exampleName, relativePath, 'Source file must not be empty');
189 + }
190 +};
191 +
192 +const validateExample = (exampleDirName: string) => {
193 + const exampleDir = path.join(examplesRoot, exampleDirName);
194 + const srcDir = path.join(exampleDir, 'src');
195 +
196 + validatePackageJson(exampleDirName, exampleDir);
197 + validateTsconfig(exampleDirName, exampleDir);
198 +
199 + if (!fs.existsSync(srcDir) || !fs.statSync(srcDir).isDirectory()) {
200 + addIssue(exampleDirName, path.relative(repoRoot, srcDir), 'Missing src directory');
201 + return;
202 + }
203 +
204 + const sourceFiles = collectFiles(srcDir).filter(file =>
205 + allowedSourceExtensions.has(path.extname(file))
206 + );
207 +
208 + if (sourceFiles.length === 0) {
209 + addIssue(exampleDirName, path.relative(repoRoot, srcDir), 'No source files found');
210 + return;
211 + }
212 +
213 + for (const filePath of sourceFiles) {
214 + validateSourceFile(exampleDirName, filePath);
215 + }
216 +};
217 +
218 +const exampleDirs = fs
219 + .readdirSync(examplesRoot, { withFileTypes: true })
220 + .filter(entry => entry.isDirectory())
221 + .map(entry => entry.name)
222 + .sort();
223 +
224 +for (const exampleDirName of exampleDirs) {
225 + validateExample(exampleDirName);
226 +}
227 +
228 +if (issues.length > 0) {
229 + for (const issue of issues) {
230 + console.error(`[${issue.example}] ${issue.file}: ${issue.message}`);
231 + }
232 + console.error(`\nExample validation failed with ${issues.length} issue(s).`);
233 + process.exit(1);
234 +}
235 +
236 +console.log(`Validated ${exampleDirs.length} example packages.`);