9
import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
10
import { ComposioUserContext } from 'src/services/user-context';
11
import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
12
+import { detectMaster, type MasterKind } from 'src/services/master-detector';
13
+import {
14
+ appendCliSessionHistory,
15
+ resolveCliSessionArtifacts,
16
+} from 'src/services/cli-session-artifacts';
17
18
const file = Options.text('file').pipe(
19
Options.withAlias('f'),
21
Options.optional
22
);
23
19
-const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));
24
+const dryRun = Options.boolean('dry-run').pipe(
25
+ Options.withDescription('Preview execute() calls without running them'),
26
+ Options.withDefault(false)
27
+);
28
+const debug = Options.boolean('debug').pipe(
29
+ Options.withDescription('Log helper steps while the script runs'),
30
+ Options.withDefault(false)
31
+);
32
const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
33
+ Options.withDescription('Skip the linked-account check'),
34
Options.withDefault(false)
35
);
36
const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(
37
+ Options.withDescription('Skip input validation against cached schema'),
38
+ Options.withDefault(false)
39
+);
40
+const noVerify = Options.boolean('no-verify').pipe(
41
+ Options.withDescription('Skip both connection and input validation checks'),
42
Options.withDefault(false)
43
);
26
-const noVerify = Options.boolean('no-verify').pipe(Options.withDefault(false));
44
45
const args = Args.repeated(Args.text({ name: 'arg' })).pipe(
46
Args.withDescription('Inline code followed by arguments, or just arguments when using --file')
81
return [...slugs];
82
};
83
84
+export const wrapInlineCodeForRun = (source: string): string => {
85
+ const parsed = ts.createSourceFile(
86
+ 'composio-run-inline.ts',
87
+ source,
88
+ ts.ScriptTarget.Latest,
89
+ true,
90
+ ts.ScriptKind.TSX
91
+ );
92
+ const statements = [...parsed.statements];
93
+ if (statements.length === 0) {
94
+ return source;
95
+ }
96
+
97
+ const lastStatement = statements.at(-1);
98
+ if (!lastStatement || !ts.isExpressionStatement(lastStatement)) {
99
+ return source;
100
+ }
101
+
102
+ const prefix = source.slice(0, lastStatement.getFullStart());
103
+ const suffix = source.slice(lastStatement.getEnd());
104
+ const expressionText = lastStatement.expression.getText(parsed);
105
+ return `${prefix}return (${expressionText});${suffix}`;
106
+};
107
+
108
+export const wrapFileSourceForRun = (source: string): string => {
109
+ const parsed = ts.createSourceFile(
110
+ 'composio-run-file.ts',
111
+ source,
112
+ ts.ScriptTarget.Latest,
113
+ true,
114
+ ts.ScriptKind.TSX
115
+ );
116
+ const statements = [...parsed.statements];
117
+ const firstNonImportIndex = statements.findIndex(statement => !ts.isImportDeclaration(statement));
118
+ if (firstNonImportIndex === -1) {
119
+ return source;
120
+ }
121
+
122
+ const bodyStart = statements[firstNonImportIndex]!.getFullStart();
123
+ const importPrefix = source.slice(0, bodyStart);
124
+ const body = source.slice(bodyStart);
125
+ return [
126
+ importPrefix,
127
+ 'const __composioResult = await (async () => {',
128
+ wrapInlineCodeForRun(body),
129
+ '})();',
130
+ 'if (__composioResult !== undefined) {',
131
+ ' console.log(__composioResult);',
132
+ '}',
133
+ '',
134
+ ].join('\n');
135
+};
136
+
137
export const inferCliInvocationPrefix = (
138
argv: ReadonlyArray<string> = process.argv
139
): ReadonlyArray<string> => {
169
readonly skipConnectionCheck?: boolean;
170
readonly skipToolParamsCheck?: boolean;
171
readonly noVerify?: boolean;
172
+ readonly master?: MasterKind;
173
+ readonly debug?: boolean;
174
+ readonly runOutputDir?: string;
175
};
176
177
+// eslint-disable-next-line max-lines-per-function
178
+const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
179
+ 'globalThis.z = z;',
180
+ 'globalThis.zod = z;',
181
+ 'const perfDebugEnabled = helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === "1";',
182
+ 'const toolDebugEnabled = helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === "1";',
183
+ 'const perfDebugStart = Date.now();',
184
+ 'let perfDebugSeq = 0;',
185
+ 'const proxySessionCache = new Map();',
186
+ 'const composioBaseURL = (helperContext.baseURL || "https://backend.composio.dev").replace(/\\/$/, "");',
187
+ 'const subAgentSchema = {',
188
+ ' type: "function",',
189
+ ' description: "Prompt a sub-agent from the same agent family as the current main agent (Codex -> Codex, Claude -> Claude) and return its final response.",',
190
+ ' parameters: {',
191
+ ' type: "object",',
192
+ ' additionalProperties: false,',
193
+ ' required: ["prompt"],',
194
+ ' properties: {',
195
+ ' prompt: { type: "string", description: "The prompt to send to the agent CLI." },',
196
+ ' target: { type: "string", enum: ["claude", "codex", "user"], description: "Optional master override. Defaults to the detected current master." },',
197
+ ' model: { type: "string", description: "Optional model override passed through to the agent CLI." },',
198
+ ' schema: { description: "Optional structured-output schema. Accepts a Zod schema or raw JSON Schema object." },',
199
+ ' jsonSchema: { description: "Optional JSON Schema requesting structured output from the agent." },',
200
+ ' },',
201
+ ' },',
202
+ ' returns: {',
203
+ ' type: "object",',
204
+ ' additionalProperties: false,',
205
+ ' required: ["master", "target", "result", "structuredOutput"],',
206
+ ' properties: {',
207
+ ' master: { type: "string", enum: ["claude", "codex", "user"] },',
208
+ ' target: { type: "string", enum: ["claude", "codex"] },',
209
+ ' result: { description: "Final plain-text result when available." },',
210
+ ' structuredOutput: { description: "Structured output when jsonSchema was requested." },',
211
+ ' },',
212
+ ' },',
213
+ '};',
214
+ 'const proxySchema = {',
215
+ ' type: "function",',
216
+ ' description: "Call proxy(toolkit) to get a fetch-compatible function bound to that toolkit\'s connected account.",',
217
+ ' parameters: {',
218
+ ' type: "object",',
219
+ ' additionalProperties: false,',
220
+ ' required: ["toolkit"],',
221
+ ' properties: {',
222
+ ' toolkit: { type: "string", description: "Toolkit slug whose connected account should be used" },',
223
+ ' },',
224
+ ' },',
225
+ ' returns: {',
226
+ ' type: "function",',
227
+ ' signature: "fetch(input, init?) => Promise<Response>",',
228
+ ' requestInit: {',
229
+ ' type: "object",',
230
+ ' additionalProperties: true,',
231
+ ' properties: {',
232
+ ' method: { type: "string", enum: ["GET", "POST", "PUT", "DELETE", "PATCH"] },',
233
+ ' headers: { description: "Standard fetch headers init" },',
234
+ ' body: { description: "String, JSON-ish value, Blob, ArrayBuffer, or Uint8Array" },',
235
+ ' },',
236
+ ' },',
237
+ ' },',
238
+ '};',
239
+ 'const perfDebugLog = (phase, label, details = {}) => {',
240
+ ' if (!perfDebugEnabled) return;',
241
+ ' const elapsedMs = Date.now() - perfDebugStart;',
242
+ ' const payload = { phase, label, elapsedMs, ...details };',
243
+ ' console.error(`[perf] ${JSON.stringify(payload)}`);',
244
+ '};',
245
+ 'const helperDebugEnabled = helperContext.debug === true;',
246
+ 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',
247
+ 'const helperDebugLog = (step, details = {}) => {',
248
+ ' if (!helperDebugEnabled) return;',
249
+ ' const elapsedMs = Date.now() - perfDebugStart;',
250
+ ' console.error(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);',
251
+ '};',
252
+ 'const parseJson = (text) => {',
253
+ ' const value = text.trim();',
254
+ ' if (!value) return undefined;',
255
+ ' try {',
256
+ ' return JSON.parse(value);',
257
+ ' } catch {',
258
+ ' return value;',
259
+ ' }',
260
+ '};',
261
+ 'const stringifyForPrompt = (value) => {',
262
+ ' if (value === undefined) return "undefined";',
263
+ ' if (value === null) return "null";',
264
+ ' if (typeof value === "string") return value;',
265
+ ' if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {',
266
+ ' return String(value);',
267
+ ' }',
268
+ ' try {',
269
+ ' return JSON.stringify(value, null, 2);',
270
+ ' } catch {',
271
+ ' return String(value);',
272
+ ' }',
273
+ '};',
274
+ 'const attachPromptMethod = (value) => {',
275
+ ' if (!value || typeof value !== "object" || Array.isArray(value)) return value;',
276
+ ' if (typeof value.prompt === "function") return value;',
277
+ ' Object.defineProperty(value, "prompt", {',
278
+ ' value: () => stringifyForPrompt("data" in value ? value.data : value),',
279
+ ' enumerable: false,',
280
+ ' });',
281
+ ' return value;',
282
+ '};',
283
+ 'const maybeLoadStoredCliResult = (result) => {',
284
+ ' if (!result || typeof result !== "object" || result.storedInFile !== true) {',
285
+ ' return attachPromptMethod(result);',
286
+ ' }',
287
+ ' helperDebugLog("cli.result.stored_in_file", { outputFilePath: result.outputFilePath ?? null, tokenCount: result.tokenCount ?? null });',
288
+ ' const outputFilePath = typeof result.outputFilePath === "string" ? result.outputFilePath : null;',
289
+ ' return attachPromptMethod({',
290
+ ' ...result,',
291
+ ' data: {',
292
+ ' storedInFilePath: outputFilePath !== null,',
293
+ ' outputFilePath,',
294
+ ' },',
295
+ ' });',
296
+ '};',
297
+ 'const describeDebugValue = (value) => {',
298
+ ' if (Array.isArray(value)) return { type: "array", length: value.length };',
299
+ ' if (value && typeof value === "object") return { type: "object", keys: Object.keys(value).slice(0, 20) };',
300
+ ' return { type: typeof value, value: typeof value === "string" ? value.slice(0, 200) : value ?? null };',
301
+ '};',
302
+ 'const logCliResultPreview = (requestId, result) => {',
303
+ ' if (!helperDebugEnabled) return;',
304
+ ' if (!result || typeof result !== "object") {',
305
+ ' helperDebugLog("cli.result", { requestId, result: describeDebugValue(result) });',
306
+ ' return;',
307
+ ' }',
308
+ ' helperDebugLog("cli.result", {',
309
+ ' requestId,',
310
+ ' successful: result.successful ?? null,',
311
+ ' storedInFile: result.storedInFile ?? false,',
312
+ ' outputFilePath: result.outputFilePath ?? null,',
313
+ ' error: result.error ?? null,',
314
+ ' topLevelKeys: Object.keys(result).slice(0, 20),',
315
+ ' data: "data" in result ? describeDebugValue(result.data) : null,',
316
+ ' });',
317
+ '};',
318
+ 'const detectInvokeAgentMaster = () => {',
319
+ ' if (helperContext.master === "claude" || helperContext.master === "codex" || helperContext.master === "user") {',
320
+ ' return helperContext.master;',
321
+ ' }',
322
+ ' const envKeys = Object.keys(process.env || {});',
323
+ ' if (envKeys.some((key) => key.startsWith("CODEX_"))) return "codex";',
324
+ ' if (envKeys.some((key) => key.startsWith("CLAUDE_"))) return "claude";',
325
+ ' return "user";',
326
+ '};',
327
+ 'const resolveInvokeAgentTarget = (requestedTarget) => {',
328
+ ' if (requestedTarget === "claude" || requestedTarget === "codex") return requestedTarget;',
329
+ ' const detected = requestedTarget === "user" ? "user" : detectInvokeAgentMaster();',
330
+ ' if (detected === "codex" || detected === "claude") return detected;',
331
+ ' if (typeof Bun.which === "function" && Bun.which("codex")) return "codex";',
332
+ ' if (typeof Bun.which === "function" && Bun.which("claude")) return "claude";',
333
+ ' throw new Error("subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: \\"codex\\" | \\"claude\\" }.");',
334
+ '};',
335
+ 'const normalizeInvokeAgentOptions = (options = {}) => {',
336
+ ' if (options == null || typeof options !== "object" || Array.isArray(options)) {',
337
+ ' throw new Error("subAgent() options must be an object when provided.");',
338
+ ' }',
339
+ ' if (options.schema !== undefined && options.jsonSchema !== undefined) {',
340
+ ' throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");',
341
+ ' }',
342
+ ' const inputSchema = options.schema ?? options.jsonSchema;',
343
+ ' let structuredSchema;',
344
+ ' if (inputSchema !== undefined) {',
345
+ ' if (inputSchema && typeof inputSchema.safeParse === "function" && inputSchema._def) {',
346
+ ' if (typeof z.toJSONSchema !== "function") {',
347
+ ' throw new Error("subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.");',
348
+ ' }',
349
+ ' structuredSchema = z.toJSONSchema(inputSchema);',
350
+ ' } else if (typeof inputSchema === "object" && inputSchema !== null && !Array.isArray(inputSchema)) {',
351
+ ' structuredSchema = inputSchema;',
352
+ ' } else {',
353
+ ' throw new Error("subAgent() schema must be a Zod schema or JSON Schema object.");',
354
+ ' }',
355
+ ' }',
356
+ ' return { ...options, structuredSchema };',
357
+ '};',
358
+ 'const runExternalCommandText = async (cmd, spawnOptions = {}) => {',
359
+ ' helperDebugLog("agent.spawn", { command: cmd[0], args: cmd.slice(1) });',
360
+ ' const child = Bun.spawn({',
361
+ ' cmd,',
362
+ ' env: { ...process.env, ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}), ...(spawnOptions.env || {}) },',
363
+ ' cwd: spawnOptions.cwd || process.cwd(),',
364
+ ' stdio: ["pipe", "pipe", "pipe"],',
365
+ ' });',
366
+ ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
367
+ ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
368
+ ' const exitCode = await child.exited;',
369
+ ' if (exitCode !== 0) {',
370
+ ' const details = stderr.trim() || stdout.trim();',
371
+ ' const suffix = details ? `: ${details}` : "";',
372
+ ' helperDebugLog("agent.error", { command: cmd[0], exitCode, stderr: stderr.trim() || undefined });',
373
+ ' throw new Error(`${cmd[0]} failed with exit code ${exitCode}${suffix}`);',
374
+ ' }',
375
+ ' helperDebugLog("agent.done", { command: cmd[0], exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
376
+ ' return { stdout, stderr, exitCode };',
377
+ '};',
378
+ 'const requireConsumerProxyContext = () => {',
379
+ ' if (!helperContext.apiKey) {',
380
+ ' throw new Error("proxy() requires an authenticated Composio user session.");',
381
+ ' }',
382
+ ' if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {',
383
+ ' throw new Error("proxy() requires a consumer project context so it can use the consumer project credentials.");',
384
+ ' }',
385
+ ' return {',
386
+ ' apiKey: helperContext.apiKey,',
387
+ ' orgId: helperContext.orgId,',
388
+ ' projectId: helperContext.consumerProjectId,',
389
+ ' userId: helperContext.consumerUserId,',
390
+ ' };',
391
+ '};',
392
+ 'const normalizeProxyToolkit = (toolkit) => {',
393
+ ' if (typeof toolkit !== "string" || toolkit.trim().length === 0) {',
394
+ ' throw new Error("proxy() requires a non-empty toolkit string.");',
395
+ ' }',
396
+ ' return toolkit.trim();',
397
+ '};',
398
+ 'const normalizeFetchHeaders = (headers) => {',
399
+ ' if (!headers) return [];',
400
+ ' return Array.from(new Headers(headers).entries()).map(([name, value]) => ({',
401
+ ' name,',
402
+ ' type: "header",',
403
+ ' value,',
404
+ ' }));',
405
+ '};',
406
+ 'const normalizeFetchBody = async (body) => {',
407
+ ' if (body === undefined || body === null) return undefined;',
408
+ ' if (typeof body === "string") return body;',
409
+ ' if (typeof body === "number" || typeof body === "boolean") return body;',
410
+ ' if (typeof Blob !== "undefined" && body instanceof Blob) {',
411
+ ' return await body.text();',
412
+ ' }',
413
+ ' if (body instanceof ArrayBuffer) {',
414
+ ' return Buffer.from(body).toString("base64");',
415
+ ' }',
416
+ ' if (ArrayBuffer.isView(body)) {',
417
+ ' return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("base64");',
418
+ ' }',
419
+ ' return body;',
420
+ '};',
421
+ 'const normalizeFetchInput = async (input, init = {}) => {',
422
+ ' if (typeof Request !== "undefined" && input instanceof Request) {',
423
+ ' throw new Error("proxy() does not support passing a Request instance yet. Pass a URL string and init instead.");',
424
+ ' }',
425
+ ' const endpoint = input instanceof URL ? input.toString() : input;',
426
+ ' if (typeof endpoint !== "string" || endpoint.trim().length === 0) {',
427
+ ' throw new Error("proxy fetch requires a non-empty URL string or URL object.");',
428
+ ' }',
429
+ ' const method = typeof init.method === "string" ? init.method.toUpperCase() : "GET";',
430
+ ' if (!["GET", "POST", "PUT", "DELETE", "PATCH"].includes(method)) {',
431
+ ' throw new Error("proxy fetch only supports GET, POST, PUT, DELETE, PATCH.");',
432
+ ' }',
433
+ ' return {',
434
+ ' endpoint: endpoint.trim(),',
435
+ ' method,',
436
+ ' parameters: normalizeFetchHeaders(init.headers),',
437
+ ' body: await normalizeFetchBody(init.body),',
438
+ ' };',
439
+ '};',
440
+ 'const fetchComposioJson = async (pathname, body) => {',
441
+ ' const auth = requireConsumerProxyContext();',
442
+ ' const response = await fetch(`${composioBaseURL}${pathname}`, {',
443
+ ' method: "POST",',
444
+ ' headers: {',
445
+ ' "content-type": "application/json",',
446
+ ' "x-user-api-key": auth.apiKey,',
447
+ ' "x-org-id": auth.orgId,',
448
+ ' "x-project-id": auth.projectId,',
449
+ ' },',
450
+ ' body: JSON.stringify(body),',
451
+ ' });',
452
+ ' const raw = await response.text();',
453
+ ' const parsed = parseJson(raw);',
454
+ ' if (!response.ok) {',
455
+ ' const detail = typeof parsed === "string" ? parsed : (parsed?.message || parsed?.error || raw.trim() || undefined);',
456
+ ' const error = new Error(`Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ""}`);',
457
+ ' Object.assign(error, { status: response.status, response: parsed ?? raw });',
458
+ ' throw error;',
459
+ ' }',
460
+ ' return parsed;',
461
+ '};',
462
+ 'const getProxySessionId = async (toolkit) => {',
463
+ ' const cached = proxySessionCache.get(toolkit);',
464
+ ' if (cached) return cached;',
465
+ ' const auth = requireConsumerProxyContext();',
466
+ ' const created = await fetchComposioJson("/api/v3/tool_router/session", {',
467
+ ' user_id: auth.userId,',
468
+ ' manage_connections: { enable: false },',
469
+ ' toolkits: { enable: [toolkit] },',
470
+ ' });',
471
+ ' const sessionId = created?.session_id;',
472
+ ' if (typeof sessionId !== "string" || sessionId.length === 0) {',
473
+ ' throw new Error("Composio proxy session creation returned no session_id.");',
474
+ ' }',
475
+ ' proxySessionCache.set(toolkit, sessionId);',
476
+ ' return sessionId;',
477
+ '};',
478
+ '',
479
+ 'const runCliJson = async (args) => {',
480
+ ' const requestId = `${args[0] ?? "cli"}#${++perfDebugSeq}`;',
481
+ ' helperDebugLog("cli.start", { requestId, args });',
482
+ ' const env = {',
483
+ ' ...process.env,',
484
+ ' ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),',
485
+ ' ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),',
486
+ ' ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),',
487
+ ' ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),',
488
+ ' ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: "1" } : {}),',
489
+ ' ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: "1" } : {}),',
490
+ ' };',
491
+ ' delete env.BUN_BE_BUN;',
492
+ ' perfDebugLog("start", requestId, { cmd: args });',
493
+ ' const child = Bun.spawn({',
494
+ ' cmd: [...cliPrefix, ...args],',
495
+ ' env,',
496
+ " stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],",
497
+ ' });',
498
+ ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
499
+ ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
500
+ ' const result = maybeLoadStoredCliResult(parseJson(stdout));',
501
+ ' const exitCode = await child.exited;',
502
+ ' if (exitCode !== 0) {',
503
+ ' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',
504
+ ' helperDebugLog("cli.error", { requestId, exitCode, stderr: stderr.trim() || undefined });',
505
+ ' const error = new Error(`composio ${args.join(" ")} failed with exit code ${exitCode}`);',
506
+ ' Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });',
507
+ ' throw error;',
508
+ ' }',
509
+ ' if (result === undefined) {',
510
+ ' const details = stderr.trim();',
511
+ ' const suffix = details ? `: ${details}` : "";',
512
+ ' perfDebugLog("error", requestId, { exitCode, stderr: details || undefined, noJson: true });',
513
+ ' helperDebugLog("cli.error", { requestId, exitCode, stderr: details || undefined, noJson: true });',
514
+ ' const error = new Error(`composio ${args.join(" ")} returned no JSON output${suffix}`);',
515
+ ' Object.assign(error, { exitCode, result, stderr: details || undefined });',
516
+ ' throw error;',
517
+ ' }',
518
+ ' perfDebugLog("end", requestId, { exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
519
+ ' logCliResultPreview(requestId, result);',
520
+ ' helperDebugLog("cli.done", { requestId, exitCode });',
521
+ ' return result;',
522
+ '};',
523
+ '',
524
+ 'globalThis.search = async (query, options = {}) => {',
525
+ ' helperDebugLog("search.prepare", { query, options });',
526
+ ' const args = ["search", query];',
527
+ ' if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {',
528
+ ' args.push("--toolkits", options.toolkits.join(","));',
529
+ ' } else if (typeof options.toolkits === "string" && options.toolkits.trim().length > 0) {',
530
+ ' args.push("--toolkits", options.toolkits);',
531
+ ' }',
532
+ ' if (typeof options.limit === "number") {',
533
+ ' args.push("--limit", String(options.limit));',
534
+ ' }',
535
+ ' return runCliJson(args);',
536
+ '};',
537
+ '',
538
+ 'globalThis.execute = async (slug, data = {}) => {',
539
+ ' helperDebugLog("execute.prepare", { slug, hasData: data !== undefined });',
540
+ ' const args = ["execute", slug];',
541
+ ' if (helperContext.dryRun === true) {',
542
+ ' args.push("--dry-run");',
543
+ ' }',
544
+ ' if (helperContext.skipConnectionCheck === true) {',
545
+ ' args.push("--skip-connection-check");',
546
+ ' }',
547
+ ' if (helperContext.skipToolParamsCheck === true) {',
548
+ ' args.push("--skip-tool-params-check");',
549
+ ' }',
550
+ ' if (helperContext.noVerify === true) {',
551
+ ' args.push("--no-verify");',
552
+ ' }',
553
+ ' if (data !== undefined) {',
554
+ ' const serialized = typeof data === "string" ? data : JSON.stringify(data);',
555
+ ' args.push("--data", serialized);',
556
+ ' }',
557
+ ' const result = await runCliJson(args);',
558
+ ' if (result && typeof result === "object" && result.successful === false) {',
559
+ ' const message = typeof result.error === "string" && result.error.trim().length > 0',
560
+ ' ? result.error.trim()',
561
+ ' : `composio execute ${slug} failed`;',
562
+ ' const error = new Error(message);',
563
+ ' Object.assign(error, { result, slug });',
564
+ ' throw error;',
565
+ ' }',
566
+ ' return result;',
567
+ '};',
568
+ '',
569
+];
570
+
571
+const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [
572
+ 'const toInvokeAgentResponse = (master, target, payload = {}) => ({',
573
+ ' master,',
574
+ ' target,',
575
+ ' result: payload.result ?? null,',
576
+ ' structuredOutput: payload.structuredOutput ?? null,',
577
+ '});',
578
+ 'const invokeClaudeAgent = async (prompt, options) => {',
579
+ ' helperDebugLog("subAgent.prepare", { target: "claude", hasSchema: options.structuredSchema !== undefined });',
580
+ ' const args = ["claude", "--bare", "-p", "--output-format", "json"];',
581
+ ' if (typeof options.model === "string" && options.model.trim().length > 0) {',
582
+ ' args.push("--model", options.model.trim());',
583
+ ' }',
584
+ ' if (options.structuredSchema !== undefined) {',
585
+ ' args.push("--json-schema", JSON.stringify(options.structuredSchema));',
586
+ ' }',
587
+ ' args.push(prompt);',
588
+ ' const result = await runExternalCommandText(args);',
589
+ ' const parsed = parseJson(result.stdout.trim());',
590
+ ' if (!parsed || typeof parsed !== "object") {',
591
+ ' throw new Error("claude returned non-JSON output in subAgent().");',
592
+ ' }',
593
+ ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "claude", {',
594
+ ' result: typeof parsed.result === "string" ? parsed.result : null,',
595
+ ' structuredOutput: parsed.structured_output ?? null,',
596
+ ' });',
597
+ '};',
598
+ 'const invokeCodexAgent = async (prompt, options) => {',
599
+ ' const fs = await import("node:fs");',
600
+ ' const os = await import("node:os");',
601
+ ' const path = await import("node:path");',
602
+ ' const tempDir = sharedRunOutputDir',
603
+ ' ? fs.mkdtempSync(path.join(sharedRunOutputDir, "invoke-agent-"))',
604
+ ' : fs.mkdtempSync(path.join(os.tmpdir(), "composio-invoke-agent-"));',
605
+ ' const outputPath = path.join(tempDir, "last-message.txt");',
606
+ ' const args = ["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath];',
607
+ ' try {',
608
+ ' helperDebugLog("subAgent.prepare", { target: "codex", hasSchema: options.structuredSchema !== undefined });',
609
+ ' if (typeof options.model === "string" && options.model.trim().length > 0) {',
610
+ ' args.push("--model", options.model.trim());',
611
+ ' }',
612
+ ' if (options.structuredSchema !== undefined) {',
613
+ ' const schemaPath = path.join(tempDir, "schema.json");',
614
+ ' fs.writeFileSync(schemaPath, JSON.stringify(options.structuredSchema), "utf8");',
615
+ ' args.push("--output-schema", schemaPath);',
616
+ ' }',
617
+ ' args.push(prompt);',
618
+ ' await runExternalCommandText(args);',
619
+ ' const text = fs.readFileSync(outputPath, "utf8").trim();',
620
+ ' const parsed = options.structuredSchema ? parseJson(text) : null;',
621
+ ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "codex", {',
622
+ ' result: options.structuredSchema ? null : text,',
623
+ ' structuredOutput: options.structuredSchema ? parsed : null,',
624
+ ' });',
625
+ ' } finally {',
626
+ ' fs.rmSync(tempDir, { recursive: true, force: true });',
627
+ ' }',
628
+ '};',
629
+ 'const subAgentImpl = async (prompt, options = {}) => {',
630
+ ' if (typeof prompt !== "string" || prompt.trim().length === 0) {',
631
+ ' throw new Error("subAgent() requires a non-empty prompt string.");',
632
+ ' }',
633
+ ' const normalizedOptions = normalizeInvokeAgentOptions(options);',
634
+ ' const target = resolveInvokeAgentTarget(normalizedOptions.target);',
635
+ ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target });',
636
+ ' if (target === "claude") {',
637
+ ' return invokeClaudeAgent(prompt.trim(), normalizedOptions);',
638
+ ' }',
639
+ ' return invokeCodexAgent(prompt.trim(), normalizedOptions);',
640
+ '};',
641
+ 'globalThis.subAgent = subAgentImpl;',
642
+ 'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });',
643
+ 'globalThis.invokeAgent = subAgentImpl;',
644
+ 'Object.defineProperty(globalThis.invokeAgent, "schema", { value: subAgentSchema });',
645
+ '',
646
+];
647
+
648
+const buildRunProxyHelpersSource = (): ReadonlyArray<string> => [
649
+ 'const toProxyResponse = async (result) => {',
650
+ ' const headers = new Headers(result?.headers || {});',
651
+ ' if (result?.binary_data?.url) {',
652
+ ' const binaryResponse = await fetch(result.binary_data.url);',
653
+ ' binaryResponse.headers.forEach((value, key) => {',
654
+ ' if (!headers.has(key)) headers.set(key, value);',
655
+ ' });',
656
+ ' return new Response(binaryResponse.body, {',
657
+ ' status: result.status ?? binaryResponse.status,',
658
+ ' headers,',
659
+ ' });',
660
+ ' }',
661
+ ' if (result?.data === undefined || result?.data === null) {',
662
+ ' return new Response(null, { status: result?.status ?? 200, headers });',
663
+ ' }',
664
+ ' if (typeof result.data === "string") {',
665
+ ' if (!headers.has("content-type")) headers.set("content-type", "text/plain; charset=utf-8");',
666
+ ' return new Response(result.data, { status: result.status ?? 200, headers });',
667
+ ' }',
668
+ ' if (!headers.has("content-type")) headers.set("content-type", "application/json; charset=utf-8");',
669
+ ' return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });',
670
+ '};',
671
+ 'globalThis.proxy = async (toolkit) => {',
672
+ ' const normalizedToolkit = normalizeProxyToolkit(toolkit);',
673
+ ' helperDebugLog("proxy.session", { toolkit: normalizedToolkit, cached: proxySessionCache.has(normalizedToolkit) });',
674
+ ' const sessionId = await getProxySessionId(normalizedToolkit);',
675
+ ' const proxyFetch = async (input, init = {}) => {',
676
+ ' const request = await normalizeFetchInput(input, init);',
677
+ ' helperDebugLog("proxy.request", { toolkit: normalizedToolkit, method: request.method, endpoint: request.endpoint });',
678
+ ' const result = await fetchComposioJson(`/api/v3/tool_router/session/${sessionId}/proxy_execute`, {',
679
+ ' toolkit_slug: normalizedToolkit,',
680
+ ' endpoint: request.endpoint,',
681
+ ' method: request.method,',
682
+ ' ...(request.body !== undefined ? { body: request.body } : {}),',
683
+ ' ...(request.parameters?.length',
684
+ ' ? {',
685
+ ' parameters: request.parameters.map((parameter) => ({',
686
+ ' name: parameter.name,',
687
+ ' type: parameter.type,',
688
+ ' value: String(parameter.value),',
689
+ ' })),',
690
+ ' }',
691
+ ' : {}),',
692
+ ' });',
693
+ ' return toProxyResponse(result);',
694
+ ' };',
695
+ ' Object.defineProperty(proxyFetch, "toolkit", { value: normalizedToolkit });',
696
+ ' return proxyFetch;',
697
+ '};',
698
+ 'Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });',
699
+ '',
700
+ 'Object.defineProperty(globalThis, "__composioConsumerContext", {',
701
+ ' value: helperContext,',
702
+ ' configurable: true,',
703
+ '});',
704
+ '',
705
+];
706
+
707
export const buildRunHelpersSource = (
708
cliPrefix: ReadonlyArray<string>,
709
context: RunHelperContext = {}
710
): string =>
711
[
712
+ 'import { z } from "zod";',
713
+ '',
714
`const cliPrefix = ${JSON.stringify(cliPrefix)};`,
715
`const helperContext = ${JSON.stringify(context)};`,
716
'',
112
- 'const perfDebugEnabled = helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === "1";',
113
- 'const toolDebugEnabled = helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === "1";',
114
- 'const perfDebugStart = Date.now();',
115
- 'let perfDebugSeq = 0;',
116
- 'const perfDebugLog = (phase, label, details = {}) => {',
117
- ' if (!perfDebugEnabled) return;',
118
- ' const elapsedMs = Date.now() - perfDebugStart;',
119
- ' const payload = { phase, label, elapsedMs, ...details };',
120
- ' console.error(`[perf] ${JSON.stringify(payload)}`);',
121
- '};',
122
- 'const parseJson = (text) => {',
123
- ' const value = text.trim();',
124
- ' if (!value) return undefined;',
125
- ' try {',
126
- ' return JSON.parse(value);',
127
- ' } catch {',
128
- ' return value;',
129
- ' }',
130
- '};',
131
- '',
132
- 'const runCliJson = async (args) => {',
133
- ' const requestId = `${args[0] ?? "cli"}#${++perfDebugSeq}`;',
134
- ' const env = {',
135
- ' ...process.env,',
136
- ' ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),',
137
- ' ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),',
138
- ' ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),',
139
- ' ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: "1" } : {}),',
140
- ' ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: "1" } : {}),',
141
- ' };',
142
- ' delete env.BUN_BE_BUN;',
143
- ' perfDebugLog("start", requestId, { cmd: args });',
144
- ' const child = Bun.spawn({',
145
- ' cmd: [...cliPrefix, ...args],',
146
- ' env,',
147
- " stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],",
148
- ' });',
149
- ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
150
- ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
151
- ' const result = parseJson(stdout);',
152
- ' const exitCode = await child.exited;',
153
- ' if (exitCode !== 0) {',
154
- ' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',
155
- ' const error = new Error(`composio ${args.join(" ")} failed with exit code ${exitCode}`);',
156
- ' Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });',
157
- ' throw error;',
158
- ' }',
159
- ' if (result === undefined) {',
160
- ' const details = stderr.trim();',
161
- ' const suffix = details ? `: ${details}` : "";',
162
- ' perfDebugLog("error", requestId, { exitCode, stderr: details || undefined, noJson: true });',
163
- ' const error = new Error(`composio ${args.join(" ")} returned no JSON output${suffix}`);',
164
- ' Object.assign(error, { exitCode, result, stderr: details || undefined });',
165
- ' throw error;',
166
- ' }',
167
- ' perfDebugLog("end", requestId, { exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
168
- ' return result;',
169
- '};',
170
- '',
171
- 'globalThis.search = async (query, options = {}) => {',
172
- ' const args = ["search", query];',
173
- ' if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {',
174
- ' args.push("--toolkits", options.toolkits.join(","));',
175
- ' } else if (typeof options.toolkits === "string" && options.toolkits.trim().length > 0) {',
176
- ' args.push("--toolkits", options.toolkits);',
177
- ' }',
178
- ' if (typeof options.limit === "number") {',
179
- ' args.push("--limit", String(options.limit));',
180
- ' }',
181
- ' return runCliJson(args);',
182
- '};',
183
- '',
184
- 'globalThis.execute = async (slug, data = {}) => {',
185
- ' const args = ["execute", slug];',
186
- ' if (helperContext.dryRun === true) {',
187
- ' args.push("--dry-run");',
188
- ' }',
189
- ' if (helperContext.skipConnectionCheck === true) {',
190
- ' args.push("--skip-connection-check");',
191
- ' }',
192
- ' if (helperContext.skipToolParamsCheck === true) {',
193
- ' args.push("--skip-tool-params-check");',
194
- ' }',
195
- ' if (helperContext.noVerify === true) {',
196
- ' args.push("--no-verify");',
197
- ' }',
198
- ' if (data !== undefined) {',
199
- ' const serialized = typeof data === "string" ? data : JSON.stringify(data);',
200
- ' args.push("--data", serialized);',
201
- ' }',
202
- ' return runCliJson(args);',
203
- '};',
204
- '',
205
- 'Object.defineProperty(globalThis, "__composioConsumerContext", {',
206
- ' value: helperContext,',
207
- ' configurable: true,',
208
- '});',
209
- '',
717
+ ...buildRunBaseHelpersSource(),
718
+ ...buildRunInvokeAgentHelpersSource(),
719
+ ...buildRunProxyHelpersSource(),
720
].join('\n');
721
722
const createRunHelpersPreloadFile = (
725
) => {
726
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-'));
727
const preloadPath = path.join(directory, 'globals.mjs');
218
- fs.writeFileSync(preloadPath, buildRunHelpersSource(cliPrefix, context), 'utf8');
219
- return { directory, preloadPath };
728
+ const runOutputDir =
729
+ typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0
730
+ ? context.runOutputDir
731
+ : path.join(directory, 'artifacts');
732
+ fs.mkdirSync(runOutputDir, { recursive: true });
733
+ fs.writeFileSync(
734
+ preloadPath,
735
+ buildRunHelpersSource(cliPrefix, { ...context, runOutputDir }),
736
+ 'utf8'
737
+ );
738
+ return { directory, preloadPath, runOutputDir };
739
};
740
741
export const buildRunCommand = ({
742
file,
743
args,
744
preloadPath,
745
+ preloadDirectory,
746
}: {
747
file: Option.Option<string>;
748
args: ReadonlyArray<string>;
749
preloadPath: string;
750
+ preloadDirectory: string;
751
}) => {
752
+ // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1
753
+ // which makes compiled Bun binaries act as a plain Bun runtime.
754
+ // Avoid the `run` subcommand entirely since Bun intercepts it as its own
755
+ // built-in; `bun --preload <file> <script>` works without it.
756
const base = [process.execPath, '--preload', preloadPath];
757
if (Option.isSome(file)) {
233
- return [...base, 'run', file.value, ...withArgDelimiter(args)];
758
+ const filePath = path.resolve(file.value);
759
+ const wrapperFilePath = path.join(
760
+ path.dirname(filePath),
761
+ `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`
762
+ );
763
+ fs.writeFileSync(
764
+ wrapperFilePath,
765
+ wrapFileSourceForRun(fs.readFileSync(filePath, 'utf8')),
766
+ 'utf8'
767
+ );
768
+ return {
769
+ cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],
770
+ cleanupPaths: [wrapperFilePath],
771
+ };
772
}
773
774
const [inlineCode, ...scriptArgs] = args;
775
if (inlineCode) {
238
- return [...base, '--eval', inlineCode, ...withArgDelimiter(scriptArgs)];
776
+ const wrappedInlineCode = [
777
+ '(async () => {',
778
+ wrapInlineCodeForRun(inlineCode),
779
+ '})().then((__composioResult) => {',
780
+ ' if (__composioResult !== undefined) {',
781
+ ' console.log(__composioResult);',
782
+ ' }',
783
+ '});',
784
+ ].join('\n');
785
+ return {
786
+ cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],
787
+ cleanupPaths: [],
788
+ };
789
}
790
791
throw new Error('Provide inline code or use --file to run a script file.');
817
consumerUserId: consumerProject.value.consumerUserId,
818
consumerProjectId: consumerProject.value.projectId,
819
consumerProjectName: consumerProject.value.projectName,
820
+ runOutputDir: Option.getOrUndefined(
821
+ yield* resolveCliSessionArtifacts({
822
+ orgId,
823
+ consumerUserId: consumerProject.value.consumerUserId,
824
+ }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
825
+ ),
826
} satisfies RunHelperContext;
827
});
828
829
export const runCmd = Command.make('run', {
830
file,
831
dryRun,
832
+ debug,
833
skipConnectionCheck,
834
skipToolParamsCheck,
835
noVerify,
837
}).pipe(
838
Command.withDescription(
839
[
283
- 'Run inline TS/JS code or a file with the embedded Bun runtime.',
284
- 'Use this for programmatic multi-step tool workflows when you want to stay in code and not orchestrate everything through bash.',
285
- '',
286
- 'Usage:',
287
- " composio run '<code>' [-- ...args]",
288
- ' composio run --file ./script.ts [-- ...args]',
840
+ 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.',
841
'',
842
'Examples:',
291
- ` composio run 'const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Bug report" }); console.log(issue)'`,
292
- ` composio run --skip-connection-check 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" }); console.log(email)'`,
293
- ` composio run --skip-tool-params-check 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" }); console.log(email)'`,
294
- ` composio run --no-verify 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" }); console.log(email)'`,
295
- ` composio run --dry-run 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" }); console.log(email)'`,
843
+ ` composio run 'const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "composiohq", repo: "composio", title: "Bug report" }); console.log(issue)'`,
844
+ ` composio run --dry-run 'await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" })'`,
845
+ ` composio run --debug 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,
846
+ ` composio run '`,
847
+ ` const [emails, issues] = await Promise.all([`,
848
+ ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
849
+ ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
850
+ ` ]);`,
851
+ ` const brief = await subAgent(`,
852
+ ` \`Create a morning brief from these emails and issues.\\n\\n\${emails.prompt()}\\n\\n\${issues.prompt()}\`,`,
853
+ ` {`,
854
+ ` schema: z.object({`,
855
+ ` brief: z.string(),`,
856
+ ` urgentEmails: z.array(z.string()),`,
857
+ ` urgentIssues: z.array(z.string()),`,
858
+ ` }),`,
859
+ ` }`,
860
+ ` );`,
861
+ ` brief.structuredOutput;`,
862
+ ` '`,
863
' composio run --file ./script.ts -- hello world',
864
'',
298
- 'Injected globals:',
299
- ' await execute(slug, data?)',
300
- ' Primary helper. Wraps `composio execute` and returns parsed JSON output quickly.',
301
- ' It validates arguments against cached tool schemas in `~/.composio/tool_definitions/` when available.',
302
- ' await search(query, { toolkits?: string[] | string, limit?: number })',
303
- ' Secondary discovery helper. Wraps `composio search` and returns parsed JSON stdout.',
304
- ' Both helpers automatically reuse your top level `execute` and `search` auth states, using the toolkits and apps you have already authorized.',
865
+ 'Injected helpers (behave like their CLI counterparts):',
866
+ ' execute(slug, data?) Same as `composio execute` — returns parsed JSON',
867
+ ' search(query, options?) Same as `composio search` — returns matching tools',
868
+ ' subAgent(prompt, options?) Spawn a powerful sub-agent from the same agent family as your current main agent',
869
+ ' (Codex -> Codex, Claude -> Claude) with optional Zod structured output',
870
+ ' result.prompt() Prompt-safe serialization of a helper result, ideal for subAgent(...)',
871
+ ' const f = await proxy(toolkit) Same as `composio proxy` — returns a fetch function',
872
+ ' Example: const f = await proxy("gmail")',
873
+ ' const me = await f("https://gmail.googleapis.com/gmail/v1/users/me/profile")',
874
+ ' z Injected global from `zod` for structured output schemas',
875
+ '',
876
+ 'All helpers reuse your CLI auth state and linked accounts.',
877
'',
306
- 'Hints:',
307
- ' Use `composio search "<query>"` outside `run` to discover tool slugs before writing a script.',
308
- ' Use `composio link <toolkit>` outside `run` to authenticate apps up front before calling `execute(...)`.',
309
- ' Use `composio execute <slug> --get-schema` if you want to inspect tool inputs before scripting.',
310
- ' Since execute responses are parsed back into code almost instantly, it is usually fine to just try `execute(...)` directly in a script.',
311
- ' Treat `run` as the place to compose many tool calls once discovery and auth are already handled.',
878
+ 'Flags:',
879
+ ' --debug Log helper steps while the script runs',
880
+ ' --dry-run Preview execute() calls without running them',
881
+ ' --skip-connection-check Skip the linked-account check',
882
+ ' --skip-tool-params-check Skip input validation against cached schema',
883
+ ' --no-verify Skip both checks above',
884
'',
313
- 'Advanced:',
314
- ' import { $ } from "bun"',
315
- ' await $`${process.execPath} manage toolkits list`',
885
+ 'See also:',
886
+ ' composio search "<query>" Discover tool slugs before scripting',
887
+ ' composio link <toolkit> Connect accounts before scripting',
888
+ ' composio execute <slug> --get-schema Inspect tool inputs before scripting',
889
].join('\n')
890
),
891
Command.withHandler(
319
- ({ file, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
892
+ ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
893
Effect.gen(function* () {
894
const perfDebug = isPerfDebugEnabled();
895
const toolDebug = isToolDebugEnabled();
904
}
905
}
906
334
- const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), {
907
+ const helperContext: RunHelperContext = {
908
...(yield* resolveRunHelperContext()),
909
+ master: detectMaster(),
910
perfDebug,
911
toolDebug,
912
+ debug,
913
dryRun,
914
skipConnectionCheck,
915
skipToolParamsCheck,
916
noVerify,
342
- });
917
+ };
918
+ const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), helperContext);
919
+ let cleanupPaths: ReadonlyArray<string> = [];
920
try {
921
+ yield* appendCliSessionHistory({
922
+ orgId: helperContext.orgId,
923
+ consumerUserId: helperContext.consumerUserId,
924
+ entry: {
925
+ command: 'run',
926
+ status: 'start',
927
+ file: Option.getOrUndefined(file),
928
+ args,
929
+ debug,
930
+ },
931
+ }).pipe(Effect.catchAll(() => Effect.void));
932
+ const runCommand = buildRunCommand({
933
+ file,
934
+ args,
935
+ preloadPath: preload.preloadPath,
936
+ preloadDirectory: preload.directory,
937
+ });
938
+ cleanupPaths = runCommand.cleanupPaths;
939
const child = Bun.spawn({
345
- cmd: buildRunCommand({ file, args, preloadPath: preload.preloadPath }),
940
+ cmd: runCommand.cmd,
941
env: {
942
...process.env,
943
BUN_BE_BUN: '1',
948
});
949
950
const exitCode = yield* Effect.promise(() => child.exited);
356
- fs.rmSync(preload.directory, { recursive: true, force: true });
951
process.exit(exitCode);
952
} finally {
953
+ for (const cleanupPath of cleanupPaths) {
954
+ fs.rmSync(cleanupPath, { force: true });
955
+ }
956
fs.rmSync(preload.directory, { recursive: true, force: true });
957
}
958
})