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

next
ts 97 lines 2.7 KB
Raw
1 /**
2 * Source rewrites that `composio run` applies to a user script before handing it
3 * to Bun: slug extraction for definition warming, and the two wrappers that turn
4 * a trailing expression into a return value.
5 *
6 * These live outside `run/run.handler.ts` because they are the CLI's only
7 * consumer of the TypeScript compiler, which costs roughly 95ms to evaluate. The
8 * handler imports this module dynamically, so a `composio execute` or `composio
9 * whoami` invocation never pays for it.
10 */
11 import ts from 'typescript';
12
13 export const extractInlineExecuteToolSlugs = (source: string): ReadonlyArray<string> => {
14 if (!source.trim()) {
15 return [];
16 }
17
18 const parsed = ts.createSourceFile(
19 'composio-run-inline.ts',
20 source,
21 ts.ScriptTarget.Latest,
22 true,
23 ts.ScriptKind.TSX
24 );
25 const slugs = new Set<string>();
26
27 const visit = (node: ts.Node) => {
28 if (
29 ts.isCallExpression(node) &&
30 ts.isIdentifier(node.expression) &&
31 node.expression.text === 'execute'
32 ) {
33 const [slugArg] = node.arguments;
34 if (slugArg && ts.isStringLiteralLike(slugArg)) {
35 slugs.add(slugArg.text);
36 }
37 }
38
39 ts.forEachChild(node, visit);
40 };
41
42 visit(parsed);
43 return [...slugs];
44 };
45
46 export const wrapInlineCodeForRun = (source: string): string => {
47 const parsed = ts.createSourceFile(
48 'composio-run-inline.ts',
49 source,
50 ts.ScriptTarget.Latest,
51 true,
52 ts.ScriptKind.TSX
53 );
54 const statements = [...parsed.statements];
55 if (statements.length === 0) {
56 return source;
57 }
58
59 const lastStatement = statements.at(-1);
60 if (!lastStatement || !ts.isExpressionStatement(lastStatement)) {
61 return source;
62 }
63
64 const prefix = source.slice(0, lastStatement.getFullStart());
65 const suffix = source.slice(lastStatement.getEnd());
66 const expressionText = lastStatement.expression.getText(parsed);
67 return `${prefix}return (${expressionText});${suffix}`;
68 };
69
70 export const wrapFileSourceForRun = (source: string): string => {
71 const parsed = ts.createSourceFile(
72 'composio-run-file.ts',
73 source,
74 ts.ScriptTarget.Latest,
75 true,
76 ts.ScriptKind.TSX
77 );
78 const statements = [...parsed.statements];
79 const firstNonImportIndex = statements.findIndex(statement => !ts.isImportDeclaration(statement));
80 if (firstNonImportIndex === -1) {
81 return source;
82 }
83
84 const bodyStart = statements[firstNonImportIndex]!.getFullStart();
85 const importPrefix = source.slice(0, bodyStart);
86 const body = source.slice(bodyStart);
87 return [
88 importPrefix,
89 'const __composioResult = await (async () => {',
90 wrapInlineCodeForRun(body),
91 '})();',
92 'if (__composioResult !== undefined) {',
93 ' console.log(__composioResult);',
94 '}',
95 '',
96 ].join('\n');
97 };