@devries-cameron20 / composio Mirror · read-only
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 21, 04:45 UTC

next
ts 162 lines 6.45 KB
Raw
1 /**
2 * Keeps `src/commands/COMMANDS.md` in step with the command tree: one row per command
3 * registration, with its help summary and the file that defines it.
4 * `pnpm --filter @composio/cli run commands:map` rewrites the file; `pnpm test` fails while it is stale.
5 *
6 * A registration's source file is the `.cmd.ts` module that exports its definition.
7 * Effect 4.1 resolves examples anew when copying a command, so match their values,
8 * the name and description instead of array identity. Ambiguous definitions and
9 * commands assembled by a function are listed explicitly in `ASSEMBLED`.
10 */
11 import * as path from 'node:path';
12 import { isDeepStrictEqual } from 'node:util';
13 import { describe, expect, it } from '@effect/vitest';
14 import { Command } from 'effect/cli';
15 import * as prettier from 'prettier';
16 import { buildRootCommand } from 'src/commands';
17 import { commandPathOf } from 'src/invocation/command-identity';
18 import { EVERY_FEATURE, type Registration, registrationsOf } from 'test/__utils__/command-tree';
19 import { collectCommandTests } from '../../../scripts/command-tests';
20
21 const packageRoot = path.resolve(import.meta.dirname, '../../..');
22 const repoRoot = path.resolve(packageRoot, '../../..');
23 const commandsDir = path.join(packageRoot, 'src', 'commands');
24
25 const repoPath = (file: string) => path.relative(repoRoot, file).split(path.sep).join('/');
26
27 /** Commands built by a function at assembly time, by command path, with the file that builds them. */
28 const ASSEMBLED: Readonly<Record<string, string>> = {
29 dev: 'dev.cmd.ts',
30 help: 'root-help.ts',
31 signup: 'signup/signup.cmd.ts',
32 'agent signup': 'agent/signup/agent.signup.cmd.ts',
33 };
34
35 const definitions = await Promise.all(
36 collectCommandTests(packageRoot).commands.map(async file => {
37 const module: Record<string, unknown> = await import(path.join(commandsDir, file));
38 return {
39 file: repoPath(path.join(commandsDir, file)),
40 commands: Object.values(module).filter(Command.isCommand),
41 };
42 })
43 );
44
45 const sameDefinition = (a: Command.Command.Any, b: Command.Command.Any) =>
46 a.name === b.name && a.description === b.description && isDeepStrictEqual(a.examples, b.examples);
47
48 /** The `.cmd.ts` file that exports `registration`'s definition, or why there is not one. */
49 const sourceOf = ({ identity, command }: Registration): string => {
50 const assembled = ASSEMBLED[identity.path.join(' ')];
51 if (assembled !== undefined) {
52 return repoPath(path.join(commandsDir, assembled));
53 }
54 const files = [
55 ...new Set(
56 definitions
57 .filter(({ commands }) => commands.some(candidate => sameDefinition(candidate, command)))
58 .map(({ file }) => file)
59 ),
60 ];
61 if (files.length !== 1) {
62 throw new Error(
63 `\`${commandPathOf(identity)}\` matches ${files.length === 0 ? 'no exported command' : files.join(', ')}; export its definition from one .cmd.ts file, or list it in ASSEMBLED.`
64 );
65 }
66 return files[0]!;
67 };
68
69 const registrations = registrationsOf();
70 const withoutExperiments = new Set(
71 registrationsOf(
72 buildRootCommand({ ...EVERY_FEATURE, isExperimentalFeatureEnabled: () => false })
73 ).map(({ identity }) => commandPathOf(identity))
74 );
75
76 const rows = registrations
77 .map(registration => ({
78 registration,
79 path: commandPathOf(registration.identity),
80 source: sourceOf(registration),
81 }))
82 .toSorted((a, b) =>
83 a.path === 'composio'
84 ? -1
85 : b.path === 'composio'
86 ? 1
87 : a.path < b.path
88 ? -1
89 : a.path > b.path
90 ? 1
91 : 0
92 );
93
94 /** Other registrations of the same definition: a root shortcut and its place in a group. */
95 const alsoAt = (row: (typeof rows)[number]) =>
96 rows
97 .filter(
98 other =>
99 other !== row &&
100 other.source === row.source &&
101 sameDefinition(other.registration.command, row.registration.command)
102 )
103 .map(other => `\`${other.path}\``)
104 .join(', ');
105
106 const visibility = ({ registration, path }: (typeof rows)[number]) =>
107 registration.unlisted ? 'unlisted' : withoutExperiments.has(path) ? 'listed' : 'experimental';
108
109 const code = (text: string | undefined) => (text ? `\`${text}\`` : '');
110
111 /** Quote command help without letting table separators or placeholders change the Markdown. */
112 const helpSummary = (command: Command.Command.Any): string => {
113 const summary = (command.shortDescription ?? command.description)?.split('\n')[0]?.trim();
114 return summary
115 ? `“${summary.replace(/\|/g, '\\|').replace(/</g, '&lt;').replace(/>/g, '&gt;')}”`
116 : '';
117 };
118
119 const COMMANDS_MD = [
120 '<!-- Generated from the command tree by `pnpm --filter @composio/cli run commands:map`. Do not edit; `pnpm test` fails while it is stale. -->',
121 '',
122 '# Commands',
123 '',
124 'Every command registration of the CLI, its help summary, and the file that defines it. The help summaries quote the command definitions.',
125 '',
126 '- **Help summary**: the command’s short description, or the first line of its description when no short description exists.',
127 '- **Tree**: `dev` for commands in the dev tree, `root` otherwise.',
128 '- **Also at**: other registrations of the same definition, such as a root shortcut.',
129 '- **Login**: the command needs a logged-in user (`requiresLogin`, inherited from its group).',
130 '- **Visibility**: `unlisted` commands are left out of help but still run; `experimental` ones exist only while their experimental feature is enabled.',
131 '- `composio help <command>` mirrors every row and is not listed.',
132 '',
133 '| Command | Help summary | Tree | Source | Alias | Also at | Login | Visibility |',
134 '| --- | --- | --- | --- | --- | --- | --- | --- |',
135 ...rows.map(row => {
136 const { registration, path, source } = row;
137 const cells = [
138 code(path),
139 helpSummary(registration.command),
140 registration.identity.path[0] === 'dev' ? 'dev' : 'root',
141 code(source),
142 code(registration.command.alias),
143 alsoAt(row),
144 registration.identity.meta.requiresLogin ? 'yes' : 'no',
145 visibility(row),
146 ];
147 return `| ${cells.join(' | ')} |`;
148 }),
149 '',
150 ].join('\n');
151
152 describe('src/commands/COMMANDS.md', () => {
153 it('is current (regenerate with `pnpm --filter @composio/cli run commands:map`)', async () => {
154 const file = path.join(commandsDir, 'COMMANDS.md');
155 // Formatted as the commit hook formats Markdown, so a commit leaves the file current.
156 const formatted = await prettier.format(COMMANDS_MD, {
157 ...(await prettier.resolveConfig(file)),
158 filepath: file,
159 });
160 await expect(formatted).toMatchFileSnapshot(file);
161 });
162 });