2
import * as os from 'node:os';
3
import * as path from 'node:path';
4
import process from 'node:process';
5
+import { fileURLToPath, pathToFileURL } from 'node:url';
6
import { Args, Command, Options } from '@effect/cli';
7
import { Effect, Option } from 'effect';
8
import { ts } from 'ts-morph';
30
Options.withDescription('Log helper steps while the script runs'),
31
Options.withDefault(false)
32
);
33
+const logsOff = Options.boolean('logs-off').pipe(
34
+ Options.withDescription('Hide the always-on subAgent streaming logs'),
35
+ Options.withDefault(false)
36
+);
37
const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
38
Options.withDescription('Skip the linked-account check'),
39
Options.withDefault(false)
160
: [process.execPath];
161
};
162
163
+const resolveSiblingModulePath = (relativeNoExtensionFromRunCmd: string): string => {
164
+ const currentFilePath = fileURLToPath(import.meta.url);
165
+ const currentDirectory = path.dirname(currentFilePath);
166
+
167
+ // Source (.ts) — running from `bun src/bin.ts`
168
+ const tsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.ts`);
169
+ if (fs.existsSync(tsPath)) {
170
+ return tsPath;
171
+ }
172
+
173
+ // Built (.js) — running from `bun dist/bin.mjs`
174
+ const jsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.js`);
175
+ if (fs.existsSync(jsPath)) {
176
+ return jsPath;
177
+ }
178
+
179
+ // Compiled binary — import.meta.url points to /$bunfs/, files live next to the executable
180
+ const baseName = path.basename(relativeNoExtensionFromRunCmd);
181
+ const exeDir = path.dirname(process.execPath);
182
+ const mjsPath = path.resolve(exeDir, `${baseName}.mjs`);
183
+ if (fs.existsSync(mjsPath)) {
184
+ return mjsPath;
185
+ }
186
+ const exeJsPath = path.resolve(exeDir, `${baseName}.js`);
187
+ if (fs.existsSync(exeJsPath)) {
188
+ return exeJsPath;
189
+ }
190
+
191
+ // Fallback — return the .js path (will error at runtime with a clear module-not-found)
192
+ return jsPath;
193
+};
194
+
195
+const subAgentSharedModuleUrl = pathToFileURL(
196
+ resolveSiblingModulePath('../services/run-subagent-shared')
197
+).href;
198
+const subAgentAcpModuleUrl = pathToFileURL(
199
+ resolveSiblingModulePath('../services/run-subagent-acp')
200
+).href;
201
+const subAgentLegacyModuleUrl = pathToFileURL(
202
+ resolveSiblingModulePath('../services/run-subagent-legacy')
203
+).href;
204
+
205
type RunHelperContext = {
206
readonly apiKey?: string;
207
readonly baseURL?: string;
219
readonly noVerify?: boolean;
220
readonly master?: MasterKind;
221
readonly debug?: boolean;
222
+ readonly acpOnly?: boolean;
223
+ readonly logsOff?: boolean;
224
readonly runOutputDir?: string;
225
};
226
252
' returns: {',
253
' type: "object",',
254
' additionalProperties: false,',
206
- ' required: ["master", "target", "result", "structuredOutput"],',
255
+ ' required: ["master", "target", "result"],',
256
' properties: {',
257
' master: { type: "string", enum: ["claude", "codex", "user"] },',
258
' target: { type: "string", enum: ["claude", "codex"] },',
293
' console.error(`[perf] ${JSON.stringify(payload)}`);',
294
'};',
295
'const helperDebugEnabled = helperContext.debug === true;',
296
+ 'const helperProgressEnabled = helperContext.logsOff !== true;',
297
'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',
298
+ 'const helperProgressSteps = new Set([',
299
+ ' "subAgent.target",',
300
+ ' "subAgent.acp.message",',
301
+ ' "subAgent.acp.thought",',
302
+ ' "subAgent.acp.tool_call",',
303
+ ' "subAgent.acp.tool_call_update",',
304
+ ' "subAgent.acp.plan",',
305
+ ' "subAgent.acp.fallback",',
306
+ ']);',
307
+ 'const helperDebugUseColor = process.stderr?.isTTY === true && process.env.NO_COLOR !== "1";',
308
+ 'const helperDebugColorize = (line) => helperDebugUseColor ? `\\x1b[90m${line}\\x1b[0m` : line;',
309
+ 'const truncateDebugText = (value, max = 240) => {',
310
+ ' const text = typeof value === "string" ? value : String(value ?? "");',
311
+ ' return text.length > max ? `${text.slice(0, max - 1)}…` : text;',
312
+ '};',
313
+ 'const previewDebugValue = (value) => {',
314
+ ' if (value == null) return "";',
315
+ ' if (typeof value === "string") return truncateDebugText(value.replace(/\\s+/g, " ").trim());',
316
+ ' if (typeof value === "number" || typeof value === "boolean") return String(value);',
317
+ ' if (Array.isArray(value)) return `array(${value.length})`;',
318
+ ' if (typeof value === "object") {',
319
+ ' const preferred = ["message", "error", "title", "summary", "brief", "status"];',
320
+ ' for (const key of preferred) {',
321
+ ' if (typeof value[key] === "string" && value[key].trim().length > 0) {',
322
+ ' return truncateDebugText(value[key].trim());',
323
+ ' }',
324
+ ' }',
325
+ ' return `object{${Object.keys(value).slice(0, 4).join(", ")}}`;',
326
+ ' }',
327
+ ' return truncateDebugText(String(value));',
328
+ '};',
329
+ 'const formatHelperDebugEvent = (step, details = {}) => {',
330
+ ' switch (step) {',
331
+ ' case "subAgent.target":',
332
+ ' return `[subAgent] triggered with ${details.resolvedTarget}`;',
333
+ ' case "subAgent.acp.resolve":',
334
+ ' return `[subAgent] ACP via ${details.source} (${details.target})`;',
335
+ ' case "subAgent.acp.initialized":',
336
+ ' return `[subAgent] ACP initialized (${details.target})`;',
337
+ ' case "subAgent.acp.session":',
338
+ ' return `[subAgent] session ready (${details.target})`;',
339
+ ' case "subAgent.acp.model":',
340
+ ' return details.applied === true',
341
+ ' ? `[subAgent] model=${details.model}`',
342
+ ' : `[subAgent] model unchanged (${details.model})`;',
343
+ ' case "subAgent.acp.message": {',
344
+ ' const text = previewDebugValue(details.text);',
345
+ ' return text ? `[subAgent] ${text}` : null;',
346
+ ' }',
347
+ ' case "subAgent.acp.thought": {',
348
+ ' const text = previewDebugValue(details.text);',
349
+ ' return text ? `[subAgent:thinking] ${text}` : null;',
350
+ ' }',
351
+ ' case "subAgent.acp.tool_call": {',
352
+ ' const where = Array.isArray(details.locations) && details.locations.length > 0 ? ` ${details.locations.slice(0, 2).join(", ")}` : "";',
353
+ ' return `[subAgent:tool] ${details.status || "pending"} ${details.title || details.kind || "tool"}${where}`;',
354
+ ' }',
355
+ ' case "subAgent.acp.tool_call_update": {',
356
+ ' const where = Array.isArray(details.locations) && details.locations.length > 0 ? ` ${details.locations.slice(0, 2).join(", ")}` : "";',
357
+ ' const preview = previewDebugValue(details.rawOutput);',
358
+ ' return `[subAgent:tool] ${details.status || "update"} ${details.title || details.toolCallId || details.kind || "tool"}${where}${preview ? ` -> ${preview}` : ""}`;',
359
+ ' }',
360
+ ' case "subAgent.acp.plan": {',
361
+ ' const entries = Array.isArray(details.entries) ? details.entries : [];',
362
+ ' if (entries.length === 0) return "[subAgent:plan] updated";',
363
+ ' const summary = entries.slice(0, 3).map((entry) => `${entry.status}:${truncateDebugText(entry.content || "", 48)}`).join(" | ");',
364
+ ' return `[subAgent:plan] ${summary}`;',
365
+ ' }',
366
+ ' case "subAgent.acp.fallback":',
367
+ ' return `[subAgent] ACP fallback (${details.code})`;',
368
+ ' case "execute.prepare":',
369
+ ' return `[execute] ${details.slug}`;',
370
+ ' case "search.prepare":',
371
+ ' return `[search] ${truncateDebugText(details.query || "", 96)}`;',
372
+ ' case "proxy.request":',
373
+ ' return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || "", 96)}`;',
374
+ ' case "cli.result": {',
375
+ ' const command = typeof details.command === "string" ? details.command : "cli";',
376
+ ' const state = details.successful === false ? "failed" : "ok";',
377
+ ' const preview = previewDebugValue(details.preview);',
378
+ ' return `[${command}] ${state}${preview ? ` ${preview}` : ""}`;',
379
+ ' }',
380
+ ' case "cli.error": {',
381
+ ' const command = typeof details.command === "string" ? details.command : "cli";',
382
+ ' const stderr = previewDebugValue(details.stderr);',
383
+ ' return `[${command}] failed${stderr ? ` ${stderr}` : ""}`;',
384
+ ' }',
385
+ ' default:',
386
+ ' return null;',
387
+ ' }',
388
+ '};',
389
'const helperDebugLog = (step, details = {}) => {',
390
+ ' const line = formatHelperDebugEvent(step, details);',
391
+ ' if (line && (helperDebugEnabled || (helperProgressEnabled && helperProgressSteps.has(step)))) {',
392
+ ' console.error(helperDebugColorize(line));',
393
+ ' return;',
394
+ ' }',
395
' if (!helperDebugEnabled) return;',
396
' const elapsedMs = Date.now() - perfDebugStart;',
251
- ' console.error(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);',
397
+ ' console.error(helperDebugColorize(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`));',
398
'};',
399
'const parseJson = (text) => {',
400
' const value = text.trim();',
446
' if (value && typeof value === "object") return { type: "object", keys: Object.keys(value).slice(0, 20) };',
447
' return { type: typeof value, value: typeof value === "string" ? value.slice(0, 200) : value ?? null };',
448
'};',
303
- 'const logCliResultPreview = (requestId, result) => {',
449
+ 'const summarizeCliResultPreview = (result) => {',
450
+ ' if (result == null) return null;',
451
+ ' if (typeof result !== "object") return result;',
452
+ ' if ("data" in result && result.data !== undefined) return result.data;',
453
+ ' if ("error" in result && typeof result.error === "string" && result.error.trim().length > 0) return result.error.trim();',
454
+ ' return result;',
455
+ '};',
456
+ 'const logCliResultPreview = (requestId, command, result) => {',
457
' if (!helperDebugEnabled) return;',
458
' if (!result || typeof result !== "object") {',
306
- ' helperDebugLog("cli.result", { requestId, result: describeDebugValue(result) });',
459
+ ' helperDebugLog("cli.result", { requestId, command, preview: result, result: describeDebugValue(result) });',
460
' return;',
461
' }',
462
' helperDebugLog("cli.result", {',
463
' requestId,',
464
+ ' command,',
465
' successful: result.successful ?? null,',
466
' storedInFile: result.storedInFile ?? false,',
467
' outputFilePath: result.outputFilePath ?? null,',
468
' error: result.error ?? null,',
469
' topLevelKeys: Object.keys(result).slice(0, 20),',
470
' data: "data" in result ? describeDebugValue(result.data) : null,',
471
+ ' preview: summarizeCliResultPreview(result),',
472
' });',
473
'};',
474
'const detectInvokeAgentMaster = () => {',
497
' }',
498
' const inputSchema = options.schema ?? options.jsonSchema;',
499
' let structuredSchema;',
500
+ ' let zodSchema;',
501
' if (inputSchema !== undefined) {',
502
' if (inputSchema && typeof inputSchema.safeParse === "function" && inputSchema._def) {',
503
' if (typeof z.toJSONSchema !== "function") {',
504
' throw new Error("subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.");',
505
' }',
506
+ ' zodSchema = inputSchema;',
507
' structuredSchema = z.toJSONSchema(inputSchema);',
508
' } else if (typeof inputSchema === "object" && inputSchema !== null && !Array.isArray(inputSchema)) {',
509
' structuredSchema = inputSchema;',
511
' throw new Error("subAgent() schema must be a Zod schema or JSON Schema object.");',
512
' }',
513
' }',
357
- ' return { ...options, structuredSchema };',
358
- '};',
359
- 'const runExternalCommandText = async (cmd, spawnOptions = {}) => {',
360
- ' helperDebugLog("agent.spawn", { command: cmd[0], args: cmd.slice(1) });',
361
- ' const child = Bun.spawn({',
362
- ' cmd,',
363
- ' env: { ...process.env, ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}), ...(spawnOptions.env || {}) },',
364
- ' cwd: spawnOptions.cwd || process.cwd(),',
365
- ' stdio: ["pipe", "pipe", "pipe"],',
366
- ' });',
367
- ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
368
- ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
369
- ' const exitCode = await child.exited;',
370
- ' if (exitCode !== 0) {',
371
- ' const details = stderr.trim() || stdout.trim();',
372
- ' const suffix = details ? `: ${details}` : "";',
373
- ' helperDebugLog("agent.error", { command: cmd[0], exitCode, stderr: stderr.trim() || undefined });',
374
- ' throw new Error(`${cmd[0]} failed with exit code ${exitCode}${suffix}`);',
375
- ' }',
376
- ' helperDebugLog("agent.done", { command: cmd[0], exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
377
- ' return { stdout, stderr, exitCode };',
514
+ ' return { ...options, structuredSchema, zodSchema };',
515
'};',
516
'const requireConsumerProxyContext = () => {',
517
' if (!helperContext.apiKey) {',
641
' const exitCode = await child.exited;',
642
' if (exitCode !== 0) {',
643
' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',
507
- ' helperDebugLog("cli.error", { requestId, exitCode, stderr: stderr.trim() || undefined });',
644
+ ' helperDebugLog("cli.error", { requestId, command: args[0], exitCode, stderr: stderr.trim() || undefined });',
645
' const error = new Error(`composio ${args.join(" ")} failed with exit code ${exitCode}`);',
646
' Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });',
647
' throw error;',
650
' const details = stderr.trim();',
651
' const suffix = details ? `: ${details}` : "";',
652
' perfDebugLog("error", requestId, { exitCode, stderr: details || undefined, noJson: true });',
516
- ' helperDebugLog("cli.error", { requestId, exitCode, stderr: details || undefined, noJson: true });',
653
+ ' helperDebugLog("cli.error", { requestId, command: args[0], exitCode, stderr: details || undefined, noJson: true });',
654
' const error = new Error(`composio ${args.join(" ")} returned no JSON output${suffix}`);',
655
' Object.assign(error, { exitCode, result, stderr: details || undefined });',
656
' throw error;',
657
' }',
658
' perfDebugLog("end", requestId, { exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
522
- ' logCliResultPreview(requestId, result);',
659
+ ' logCliResultPreview(requestId, args[0], result);',
660
' helperDebugLog("cli.done", { requestId, exitCode });',
661
' return result;',
662
'};',
709
];
710
711
const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [
575
- 'const toInvokeAgentResponse = (master, target, payload = {}) => ({',
576
- ' master,',
577
- ' target,',
578
- ' result: payload.result ?? null,',
579
- ' structuredOutput: payload.structuredOutput ?? null,',
580
- '});',
581
- 'const invokeClaudeAgent = async (prompt, options) => {',
582
- ' helperDebugLog("subAgent.prepare", { target: "claude", hasSchema: options.structuredSchema !== undefined });',
583
- ' const args = ["claude", "--bare", "-p", "--output-format", "json"];',
584
- ' if (typeof options.model === "string" && options.model.trim().length > 0) {',
585
- ' args.push("--model", options.model.trim());',
586
- ' }',
587
- ' if (options.structuredSchema !== undefined) {',
588
- ' args.push("--json-schema", JSON.stringify(options.structuredSchema));',
589
- ' }',
590
- ' args.push(prompt);',
591
- ' const result = await runExternalCommandText(args);',
592
- ' const parsed = parseJson(result.stdout.trim());',
593
- ' if (!parsed || typeof parsed !== "object") {',
594
- ' throw new Error("claude returned non-JSON output in subAgent().");',
595
- ' }',
596
- ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "claude", {',
597
- ' result: typeof parsed.result === "string" ? parsed.result : null,',
598
- ' structuredOutput: parsed.structured_output ?? null,',
599
- ' });',
600
- '};',
601
- 'const invokeCodexAgent = async (prompt, options) => {',
602
- ' const fs = await import("node:fs");',
603
- ' const os = await import("node:os");',
604
- ' const path = await import("node:path");',
605
- ' const tempDir = sharedRunOutputDir',
606
- ' ? fs.mkdtempSync(path.join(sharedRunOutputDir, "invoke-agent-"))',
607
- ' : fs.mkdtempSync(path.join(os.tmpdir(), "composio-invoke-agent-"));',
608
- ' const outputPath = path.join(tempDir, "last-message.txt");',
609
- ' const args = ["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath];',
610
- ' try {',
611
- ' helperDebugLog("subAgent.prepare", { target: "codex", hasSchema: options.structuredSchema !== undefined });',
612
- ' if (typeof options.model === "string" && options.model.trim().length > 0) {',
613
- ' args.push("--model", options.model.trim());',
614
- ' }',
615
- ' if (options.structuredSchema !== undefined) {',
616
- ' const schemaPath = path.join(tempDir, "schema.json");',
617
- ' fs.writeFileSync(schemaPath, JSON.stringify(options.structuredSchema), "utf8");',
618
- ' args.push("--output-schema", schemaPath);',
619
- ' }',
620
- ' args.push(prompt);',
621
- ' await runExternalCommandText(args);',
622
- ' const text = fs.readFileSync(outputPath, "utf8").trim();',
623
- ' const parsed = options.structuredSchema ? parseJson(text) : null;',
624
- ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "codex", {',
625
- ' result: options.structuredSchema ? null : text,',
626
- ' structuredOutput: options.structuredSchema ? parsed : null,',
627
- ' });',
628
- ' } finally {',
629
- ' fs.rmSync(tempDir, { recursive: true, force: true });',
630
- ' }',
631
- '};',
712
'const subAgentImpl = async (prompt, options = {}) => {',
713
' if (typeof prompt !== "string" || prompt.trim().length === 0) {',
714
' throw new Error("subAgent() requires a non-empty prompt string.");',
715
' }',
716
' const normalizedOptions = normalizeInvokeAgentOptions(options);',
717
' const target = resolveInvokeAgentTarget(normalizedOptions.target);',
638
- ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target });',
639
- ' if (target === "claude") {',
640
- ' return invokeClaudeAgent(prompt.trim(), normalizedOptions);',
718
+ ' const master = detectInvokeAgentMaster();',
719
+ ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target, master });',
720
+ ' try {',
721
+ ' return await invokeAcpSubAgent({',
722
+ ' prompt: prompt.trim(),',
723
+ ' options: normalizedOptions,',
724
+ ' master,',
725
+ ' target,',
726
+ ' helperDebugLog,',
727
+ ' });',
728
+ ' } catch (error) {',
729
+ ' if (!isAcpInvokeError(error)) {',
730
+ ' throw error;',
731
+ ' }',
732
+ ' if (helperContext.acpOnly === true) {',
733
+ ' throw error;',
734
+ ' }',
735
+ ' helperDebugLog("subAgent.acp.fallback", { target, code: error.code, message: error.message });',
736
+ ' return invokeLegacySubAgent({',
737
+ ' prompt: prompt.trim(),',
738
+ ' options: normalizedOptions,',
739
+ ' master,',
740
+ ' target,',
741
+ ' helperDebugLog,',
742
+ ' });',
743
' }',
642
- ' return invokeCodexAgent(prompt.trim(), normalizedOptions);',
744
'};',
745
'globalThis.subAgent = subAgentImpl;',
746
'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });',
814
): string =>
815
[
816
'import { z } from "zod";',
817
+ `import { isAcpInvokeError } from ${JSON.stringify(subAgentSharedModuleUrl)};`,
818
+ `import { invokeAcpSubAgent } from ${JSON.stringify(subAgentAcpModuleUrl)};`,
819
+ `import { invokeLegacySubAgent } from ${JSON.stringify(subAgentLegacyModuleUrl)};`,
820
'',
821
`const cliPrefix = ${JSON.stringify(cliPrefix)};`,
822
`const helperContext = ${JSON.stringify(context)};`,
937
file,
938
dryRun,
939
debug,
940
+ logsOff,
941
skipConnectionCheck,
942
skipToolParamsCheck,
943
noVerify,
986
'Flags:',
987
' --debug Log helper steps while the script runs',
988
' --dry-run Preview execute() calls without running them',
989
+ ' --logs-off Hide the always-on subAgent streaming logs',
990
' --skip-connection-check Skip the linked-account check',
991
' --skip-tool-params-check Skip input validation against cached schema',
992
' --no-verify Skip both checks above',
998
].join('\n')
999
),
1000
Command.withHandler(
895
- ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
1001
+ ({ file, dryRun, debug, logsOff, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
1002
Effect.gen(function* () {
1003
const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();
1004
const perfDebug = isPerfDebugEnabled();
1005
const toolDebug = isToolDebugEnabled();
1006
+ const acpOnly = process.env.COMPOSIO_RUN_ACP_ONLY === '1';
1007
if (Option.isNone(file)) {
1008
const [inlineCode] = args;
1009
const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');
1022
perfDebug,
1023
toolDebug,
1024
debug,
1025
+ logsOff,
1026
+ acpOnly,
1027
dryRun,
1028
skipConnectionCheck,
1029
skipToolParamsCheck,