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
+};