@devries-cameron20 / composio-1 / commits / 7814b61e6
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.

fix(cli): fix typecheck errors in run-helpers-runtime and extract run globals (#3079)

## Summary Fixes 8 TypeScript strict-mode errors in `run-helpers-runtime.ts` that were blocking the CLI build, and extracts the run helper runtime out of `run.cmd.ts` into its own module for better maintainability. ## Changes ### Refactor: extract run helper runtime - Moved ~650 lines of run globals/helpers (`execute`, `search`, `proxy`, `experimental_subAgent`) from `run.cmd.ts` into `src/services/run-helpers-runtime.ts` - `run.cmd.ts` now imports and calls the extracted module, keeping the command definition lean - Updated `run-companion-modules.ts` to include the new module - Updated tests to match the new structure ### Bug fixes in `tools-executor.ts` - Pass execute data via temp file to avoid shell escaping issues - Use random UUID for temp file names - Guard `detectInBandError` against null/undefined data - Surface in-band errors as warnings instead of overriding success - Add `successfull`/`successful` boolean check to `detectInBandWarning` ### TypeScript fixes in `run-helpers-runtime.ts` - **`Headers.entries()` type error** (line 511): Cast `Headers` to `Iterable<[string, string]>` since the type target doesn't include the `entries()` method - **`BUN_BE_BUN` env property** (line 614): Cast env to `Record<string, string | undefined>` for the delete operation - **`NormalizedInvokeAgentOptions` vs `InvokeAgentNormalizedOptions`** (lines 728, 747): Added explicit type casts at the two call sites where the local type is passed to shared/acp/legacy sub-agent functions - **`allowedReadRoots` on legacy sub-agent** (line 749): Removed the property from the `invokeLegacySubAgent` call — only the ACP path accepts it - **`parameter` is `unknown`** (lines 819-821): Added explicit type annotation to the `.map()` callback in proxy execute ## Automated testing Tested both locally-built and CI-bundled binaries against real Slack APIs in `#buzz-skill-based-cli-testing`: ### Local binary (built from source) | Command | Result | |---|---| | `composio version` | ✅ 0.2.16 | | `composio whoami` | ✅ | | `composio search` (Slack tools) | ✅ | | `composio execute SLACK_FIND_CHANNELS` | ✅ found channel | | `composio execute SLACK_FIND_USER_BY_EMAIL_ADDRESS` | ✅ found user | | `composio execute SLACK_SEND_MESSAGE` | ✅ posted to channel | | `composio run -f` (read channel history) | ✅ | | `composio run` + `experimental_subAgent` (claude) | ✅ summarized channel | | `composio run` + post summary back to channel | ✅ | ### CI bundled binary (darwin-aarch64, [run #23786292303](https://github.com/ComposioHQ/composio/actions/runs/23786292303)) | Command | Result | |---|---| | `composio version` | ✅ 0.2.16 | | `composio whoami` | ✅ | | `composio --help` | ✅ | | `composio run -f` (read channel history) | ✅ | | `composio run` + `experimental_subAgent` (claude) | ✅ | | `composio run` + post summary back to channel | ✅ | All 4 platform builds (darwin-aarch64, darwin-x64, linux-x64, linux-aarch64) succeeded. Install script test failures are pre-existing and unrelated. ## Type of change - [x] Bug fix - [x] Refactor/Chore --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Rahul Tarak committed Mar 31, 2026 at 01:34 UTC 7814b61e6cd21c693c7d4f8576904f336be2bc96
6 files changed +933 -731
ts/packages/cli/src/commands/run.cmd.ts
+17 -645
@@ -8,10 +8,11 @@ import { Effect, Option } from 'effect';
8 import { ts } from 'ts-morph';
9 import { APP_VERSION } from 'src/constants';
10 import { resolveCommandProject } from 'src/services/command-project';
11 +import { type RunHelperContext } from 'src/services/run-helpers-runtime';
12 import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
13 import { ComposioUserContext } from 'src/services/user-context';
14 import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
14 -import { detectMaster, type MasterKind } from 'src/services/master-detector';
15 +import { detectMaster } from 'src/services/master-detector';
16 import {
17 repairMissingInstalledRunCompanionModules,
18 resolveRunCompanionModulePath,
@@ -169,661 +170,28 @@ export const inferCliInvocationPrefix = (
170 };
171
172 type RunHelperModuleUrls = {
172 - readonly subAgentSharedModuleUrl: string;
173 - readonly subAgentAcpModuleUrl: string;
174 - readonly subAgentLegacyModuleUrl: string;
173 + readonly helpersRuntimeModuleUrl: string;
174 };
175
176 const resolveRunHelperModuleUrls = (): RunHelperModuleUrls => ({
178 - subAgentSharedModuleUrl: pathToFileURL(
177 + helpersRuntimeModuleUrl: pathToFileURL(
178 resolveRunCompanionModulePath({
179 callerImportMetaUrl: import.meta.url,
180 execPath: process.execPath,
182 - relativeNoExtensionFromCaller: '../services/run-subagent-shared',
183 - })
184 - ).href,
185 - subAgentAcpModuleUrl: pathToFileURL(
186 - resolveRunCompanionModulePath({
187 - callerImportMetaUrl: import.meta.url,
188 - execPath: process.execPath,
189 - relativeNoExtensionFromCaller: '../services/run-subagent-acp',
190 - })
191 - ).href,
192 - subAgentLegacyModuleUrl: pathToFileURL(
193 - resolveRunCompanionModulePath({
194 - callerImportMetaUrl: import.meta.url,
195 - execPath: process.execPath,
196 - relativeNoExtensionFromCaller: '../services/run-subagent-legacy',
181 + relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
182 })
183 ).href,
184 });
185
201 -type RunHelperContext = {
202 - readonly apiKey?: string;
203 - readonly baseURL?: string;
204 - readonly webURL?: string;
205 - readonly orgId?: string;
206 - readonly runId?: string;
207 - readonly consumerUserId?: string;
208 - readonly consumerProjectId?: string;
209 - readonly consumerProjectName?: string;
210 - readonly perfDebug?: boolean;
211 - readonly toolDebug?: boolean;
212 - readonly dryRun?: boolean;
213 - readonly skipConnectionCheck?: boolean;
214 - readonly skipToolParamsCheck?: boolean;
215 - readonly skipChecks?: boolean;
216 - readonly master?: MasterKind;
217 - readonly debug?: boolean;
218 - readonly acpOnly?: boolean;
219 - readonly logsOff?: boolean;
220 - readonly runOutputDir?: string;
221 - readonly runLogFilePath?: string;
222 - readonly readAccessRoots?: ReadonlyArray<string>;
223 -};
224 -
225 -// eslint-disable-next-line max-lines-per-function
226 -const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
227 - 'globalThis.z = z;',
228 - 'globalThis.zod = z;',
229 - 'const perfDebugEnabled = helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === "1";',
230 - 'const toolDebugEnabled = helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === "1";',
231 - 'const perfDebugStart = Date.now();',
232 - 'let perfDebugSeq = 0;',
233 - 'const proxySessionCache = new Map();',
234 - 'const composioBaseURL = (helperContext.baseURL || "https://backend.composio.dev").replace(/\\/$/, "");',
235 - 'const experimentalSubAgentSchema = {',
236 - ' type: "function",',
237 - ' description: "Experimental helper: prompt a sub-agent from the same agent family as the current main agent (Codex -> Codex, Claude -> Claude) and return its final response.",',
238 - ' parameters: {',
239 - ' type: "object",',
240 - ' additionalProperties: false,',
241 - ' required: ["prompt"],',
242 - ' properties: {',
243 - ' prompt: { type: "string", description: "The prompt to send to the agent CLI." },',
244 - ' target: { type: "string", enum: ["claude", "codex", "user"], description: "Optional master override. Defaults to the detected current master." },',
245 - ' model: { type: "string", description: "Optional model override passed through to the agent CLI." },',
246 - ' schema: { description: "Optional structured-output schema. Accepts a Zod schema or raw JSON Schema object." },',
247 - ' jsonSchema: { description: "Optional JSON Schema requesting structured output from the agent." },',
248 - ' },',
249 - ' },',
250 - ' returns: {',
251 - ' type: "object",',
252 - ' additionalProperties: false,',
253 - ' required: ["master", "target", "result"],',
254 - ' properties: {',
255 - ' master: { type: "string", enum: ["claude", "codex", "user"] },',
256 - ' target: { type: "string", enum: ["claude", "codex"] },',
257 - ' result: { description: "Final plain-text result when available." },',
258 - ' structuredOutput: { description: "Structured output when jsonSchema was requested." },',
259 - ' logFilePath: { description: "Path to the local run log file for helper execution details." },',
260 - ' },',
261 - ' },',
262 - '};',
263 - 'const proxySchema = {',
264 - ' type: "function",',
265 - ' description: "Call proxy(toolkit) to get a fetch-compatible function bound to that toolkit\'s connected account.",',
266 - ' parameters: {',
267 - ' type: "object",',
268 - ' additionalProperties: false,',
269 - ' required: ["toolkit"],',
270 - ' properties: {',
271 - ' toolkit: { type: "string", description: "Toolkit slug whose connected account should be used" },',
272 - ' },',
273 - ' },',
274 - ' returns: {',
275 - ' type: "function",',
276 - ' signature: "fetch(input, init?) => Promise<Response>",',
277 - ' requestInit: {',
278 - ' type: "object",',
279 - ' additionalProperties: true,',
280 - ' properties: {',
281 - ' method: { type: "string", enum: ["GET", "POST", "PUT", "DELETE", "PATCH"] },',
282 - ' headers: { description: "Standard fetch headers init" },',
283 - ' body: { description: "String, JSON-ish value, Blob, ArrayBuffer, or Uint8Array" },',
284 - ' },',
285 - ' },',
286 - ' },',
287 - '};',
288 - 'const perfDebugLog = (phase, label, details = {}) => {',
289 - ' if (!perfDebugEnabled) return;',
290 - ' const elapsedMs = Date.now() - perfDebugStart;',
291 - ' const payload = { phase, label, elapsedMs, ...details };',
292 - ' console.error(`[perf] ${JSON.stringify(payload)}`);',
293 - '};',
294 - 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',
295 - 'const sharedRunLogFilePath = typeof helperContext.runLogFilePath === "string" && helperContext.runLogFilePath.length > 0 ? helperContext.runLogFilePath : null;',
296 - 'const appendRunLogLine = (line) => {',
297 - ' if (!sharedRunLogFilePath || typeof line !== "string" || line.length === 0) return;',
298 - ' fs.appendFileSync(sharedRunLogFilePath, `${line}\\n`, "utf8");',
299 - '};',
300 - 'const truncateDebugText = (value, max = 240) => {',
301 - ' const text = typeof value === "string" ? value : String(value ?? "");',
302 - ' return text.length > max ? `${text.slice(0, max - 1)}…` : text;',
303 - '};',
304 - 'const previewDebugValue = (value) => {',
305 - ' if (value == null) return "";',
306 - ' if (typeof value === "string") return truncateDebugText(value.replace(/\\s+/g, " ").trim());',
307 - ' if (typeof value === "number" || typeof value === "boolean") return String(value);',
308 - ' if (Array.isArray(value)) return `array(${value.length})`;',
309 - ' if (typeof value === "object") {',
310 - ' const preferred = ["message", "error", "title", "summary", "brief", "status"];',
311 - ' for (const key of preferred) {',
312 - ' if (typeof value[key] === "string" && value[key].trim().length > 0) {',
313 - ' return truncateDebugText(value[key].trim());',
314 - ' }',
315 - ' }',
316 - ' return `object{${Object.keys(value).slice(0, 4).join(", ")}}`;',
317 - ' }',
318 - ' return truncateDebugText(String(value));',
319 - '};',
320 - 'const formatHelperDebugEvent = (step, details = {}) => {',
321 - ' switch (step) {',
322 - ' case "subAgent.target":',
323 - ' return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;',
324 - ' case "subAgent.acp.resolve":',
325 - ' return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;',
326 - ' case "subAgent.acp.initialized":',
327 - ' return `[experimental_subAgent] ACP initialized (${details.target})`;',
328 - ' case "subAgent.acp.session":',
329 - ' return `[experimental_subAgent] session ready (${details.target})`;',
330 - ' case "subAgent.acp.model":',
331 - ' return details.applied === true',
332 - ' ? `[experimental_subAgent] model=${details.model}`',
333 - ' : `[experimental_subAgent] model unchanged (${details.model})`;',
334 - ' case "subAgent.acp.message": {',
335 - ' const text = previewDebugValue(details.text);',
336 - ' return text ? `[experimental_subAgent] ${text}` : null;',
337 - ' }',
338 - ' case "subAgent.acp.thought": {',
339 - ' const text = previewDebugValue(details.text);',
340 - ' return text ? `[experimental_subAgent:thinking] ${text}` : null;',
341 - ' }',
342 - ' case "subAgent.acp.tool_call": {',
343 - ' const where = Array.isArray(details.locations) && details.locations.length > 0 ? ` ${details.locations.slice(0, 2).join(", ")}` : "";',
344 - ' return `[experimental_subAgent:tool] ${details.status || "pending"} ${details.title || details.kind || "tool"}${where}`;',
345 - ' }',
346 - ' case "subAgent.acp.tool_call_update": {',
347 - ' const where = Array.isArray(details.locations) && details.locations.length > 0 ? ` ${details.locations.slice(0, 2).join(", ")}` : "";',
348 - ' const preview = previewDebugValue(details.rawOutput);',
349 - ' return `[experimental_subAgent:tool] ${details.status || "update"} ${details.title || details.toolCallId || details.kind || "tool"}${where}${preview ? ` -> ${preview}` : ""}`;',
350 - ' }',
351 - ' case "subAgent.acp.plan": {',
352 - ' const entries = Array.isArray(details.entries) ? details.entries : [];',
353 - ' if (entries.length === 0) return "[experimental_subAgent:plan] updated";',
354 - ' const summary = entries.slice(0, 3).map((entry) => `${entry.status}:${truncateDebugText(entry.content || "", 48)}`).join(" | ");',
355 - ' return `[experimental_subAgent:plan] ${summary}`;',
356 - ' }',
357 - ' case "subAgent.acp.fallback":',
358 - ' return `[experimental_subAgent] ACP fallback (${details.code})`;',
359 - ' case "execute.prepare":',
360 - ' return `[execute] ${details.slug}`;',
361 - ' case "search.prepare":',
362 - ' return `[search] ${truncateDebugText(details.query || "", 96)}`;',
363 - ' case "proxy.request":',
364 - ' return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || "", 96)}`;',
365 - ' case "cli.result": {',
366 - ' const command = typeof details.command === "string" ? details.command : "cli";',
367 - ' const state = details.successful === false ? "failed" : "ok";',
368 - ' const preview = previewDebugValue(details.preview);',
369 - ' return `[${command}] ${state}${preview ? ` ${preview}` : ""}`;',
370 - ' }',
371 - ' case "cli.error": {',
372 - ' const command = typeof details.command === "string" ? details.command : "cli";',
373 - ' const stderr = previewDebugValue(details.stderr);',
374 - ' return `[${command}] failed${stderr ? ` ${stderr}` : ""}`;',
375 - ' }',
376 - ' default:',
377 - ' return null;',
378 - ' }',
379 - '};',
380 - 'const helperDebugLog = (step, details = {}) => {',
381 - ' const line = formatHelperDebugEvent(step, details);',
382 - ' const elapsedMs = Date.now() - perfDebugStart;',
383 - ' appendRunLogLine(line ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);',
384 - '};',
385 - 'const parseJson = (text) => {',
386 - ' const value = text.trim();',
387 - ' if (!value) return undefined;',
388 - ' try {',
389 - ' return JSON.parse(value);',
390 - ' } catch {',
391 - ' return value;',
392 - ' }',
393 - '};',
394 - 'const stringifyForPrompt = (value) => {',
395 - ' if (value === undefined) return "undefined";',
396 - ' if (value === null) return "null";',
397 - ' if (typeof value === "string") return value;',
398 - ' if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {',
399 - ' return String(value);',
400 - ' }',
401 - ' try {',
402 - ' return JSON.stringify(value, null, 2);',
403 - ' } catch {',
404 - ' return String(value);',
405 - ' }',
406 - '};',
407 - 'const attachPromptMethod = (value) => {',
408 - ' if (!value || typeof value !== "object" || Array.isArray(value)) return value;',
409 - ' if (typeof value.prompt === "function") return value;',
410 - ' Object.defineProperty(value, "prompt", {',
411 - ' value: () => stringifyForPrompt("data" in value ? value.data : value),',
412 - ' enumerable: false,',
413 - ' });',
414 - ' return value;',
415 - '};',
416 - 'const maybeLoadStoredCliResult = (result) => {',
417 - ' if (!result || typeof result !== "object" || result.storedInFile !== true) {',
418 - ' return attachPromptMethod(result);',
419 - ' }',
420 - ' helperDebugLog("cli.result.stored_in_file", { outputFilePath: result.outputFilePath ?? null, tokenCount: result.tokenCount ?? null });',
421 - ' const outputFilePath = typeof result.outputFilePath === "string" ? result.outputFilePath : null;',
422 - ' return attachPromptMethod({',
423 - ' ...result,',
424 - ' data: {',
425 - ' storedInFilePath: outputFilePath !== null,',
426 - ' outputFilePath,',
427 - ' },',
428 - ' });',
429 - '};',
430 - 'const describeDebugValue = (value) => {',
431 - ' if (Array.isArray(value)) return { type: "array", length: value.length };',
432 - ' if (value && typeof value === "object") return { type: "object", keys: Object.keys(value).slice(0, 20) };',
433 - ' return { type: typeof value, value: typeof value === "string" ? value.slice(0, 200) : value ?? null };',
434 - '};',
435 - 'const summarizeCliResultPreview = (result) => {',
436 - ' if (result == null) return null;',
437 - ' if (typeof result !== "object") return result;',
438 - ' if ("data" in result && result.data !== undefined) return result.data;',
439 - ' if ("error" in result && typeof result.error === "string" && result.error.trim().length > 0) return result.error.trim();',
440 - ' return result;',
441 - '};',
442 - 'const logCliResultPreview = (requestId, command, result) => {',
443 - ' if (!result || typeof result !== "object") {',
444 - ' helperDebugLog("cli.result", { requestId, command, preview: result, result: describeDebugValue(result) });',
445 - ' return;',
446 - ' }',
447 - ' helperDebugLog("cli.result", {',
448 - ' requestId,',
449 - ' command,',
450 - ' successful: result.successful ?? null,',
451 - ' storedInFile: result.storedInFile ?? false,',
452 - ' outputFilePath: result.outputFilePath ?? null,',
453 - ' error: result.error ?? null,',
454 - ' topLevelKeys: Object.keys(result).slice(0, 20),',
455 - ' data: "data" in result ? describeDebugValue(result.data) : null,',
456 - ' preview: summarizeCliResultPreview(result),',
457 - ' });',
458 - '};',
459 - 'const detectInvokeAgentMaster = () => {',
460 - ' if (helperContext.master === "claude" || helperContext.master === "codex" || helperContext.master === "user") {',
461 - ' return helperContext.master;',
462 - ' }',
463 - ' const envKeys = Object.keys(process.env || {});',
464 - ' if (envKeys.some((key) => key.startsWith("CODEX_"))) return "codex";',
465 - ' if (envKeys.some((key) => key.startsWith("CLAUDE_"))) return "claude";',
466 - ' return "user";',
467 - '};',
468 - 'const resolveInvokeAgentTarget = (requestedTarget) => {',
469 - ' if (requestedTarget === "claude" || requestedTarget === "codex") return requestedTarget;',
470 - ' const detected = requestedTarget === "user" ? "user" : detectInvokeAgentMaster();',
471 - ' if (detected === "codex" || detected === "claude") return detected;',
472 - ' if (typeof Bun.which === "function" && Bun.which("codex")) return "codex";',
473 - ' if (typeof Bun.which === "function" && Bun.which("claude")) return "claude";',
474 - ' throw new Error("experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: \\"codex\\" | \\"claude\\" }.");',
475 - '};',
476 - 'const normalizeInvokeAgentOptions = (options = {}) => {',
477 - ' if (options == null || typeof options !== "object" || Array.isArray(options)) {',
478 - ' throw new Error("experimental_subAgent() options must be an object when provided.");',
479 - ' }',
480 - ' if (options.schema !== undefined && options.jsonSchema !== undefined) {',
481 - ' throw new Error("experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.");',
482 - ' }',
483 - ' const inputSchema = options.schema ?? options.jsonSchema;',
484 - ' let structuredSchema;',
485 - ' let zodSchema;',
486 - ' if (inputSchema !== undefined) {',
487 - ' if (inputSchema && typeof inputSchema.safeParse === "function" && inputSchema._def) {',
488 - ' if (typeof z.toJSONSchema !== "function") {',
489 - ' throw new Error("experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.");',
490 - ' }',
491 - ' zodSchema = inputSchema;',
492 - ' structuredSchema = z.toJSONSchema(inputSchema);',
493 - ' } else if (typeof inputSchema === "object" && inputSchema !== null && !Array.isArray(inputSchema)) {',
494 - ' structuredSchema = inputSchema;',
495 - ' } else {',
496 - ' throw new Error("experimental_subAgent() schema must be a Zod schema or JSON Schema object.");',
497 - ' }',
498 - ' }',
499 - ' return { ...options, structuredSchema, zodSchema };',
500 - '};',
501 - 'const requireConsumerProxyContext = () => {',
502 - ' if (!helperContext.apiKey) {',
503 - ' throw new Error("proxy() requires an authenticated Composio user session.");',
504 - ' }',
505 - ' if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {',
506 - ' throw new Error("proxy() requires a consumer project context so it can use the consumer project credentials.");',
507 - ' }',
508 - ' return {',
509 - ' apiKey: helperContext.apiKey,',
510 - ' orgId: helperContext.orgId,',
511 - ' projectId: helperContext.consumerProjectId,',
512 - ' userId: helperContext.consumerUserId,',
513 - ' };',
514 - '};',
515 - 'const normalizeProxyToolkit = (toolkit) => {',
516 - ' if (typeof toolkit !== "string" || toolkit.trim().length === 0) {',
517 - ' throw new Error("proxy() requires a non-empty toolkit string.");',
518 - ' }',
519 - ' return toolkit.trim();',
520 - '};',
521 - 'const normalizeFetchHeaders = (headers) => {',
522 - ' if (!headers) return [];',
523 - ' return Array.from(new Headers(headers).entries()).map(([name, value]) => ({',
524 - ' name,',
525 - ' type: "header",',
526 - ' value,',
527 - ' }));',
528 - '};',
529 - 'const normalizeFetchBody = async (body) => {',
530 - ' if (body === undefined || body === null) return undefined;',
531 - ' if (typeof body === "string") return body;',
532 - ' if (typeof body === "number" || typeof body === "boolean") return body;',
533 - ' if (typeof Blob !== "undefined" && body instanceof Blob) {',
534 - ' return await body.text();',
535 - ' }',
536 - ' if (body instanceof ArrayBuffer) {',
537 - ' return Buffer.from(body).toString("base64");',
538 - ' }',
539 - ' if (ArrayBuffer.isView(body)) {',
540 - ' return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("base64");',
541 - ' }',
542 - ' return body;',
543 - '};',
544 - 'const normalizeFetchInput = async (input, init = {}) => {',
545 - ' if (typeof Request !== "undefined" && input instanceof Request) {',
546 - ' throw new Error("proxy() does not support passing a Request instance yet. Pass a URL string and init instead.");',
547 - ' }',
548 - ' const endpoint = input instanceof URL ? input.toString() : input;',
549 - ' if (typeof endpoint !== "string" || endpoint.trim().length === 0) {',
550 - ' throw new Error("proxy fetch requires a non-empty URL string or URL object.");',
551 - ' }',
552 - ' const method = typeof init.method === "string" ? init.method.toUpperCase() : "GET";',
553 - ' if (!["GET", "POST", "PUT", "DELETE", "PATCH"].includes(method)) {',
554 - ' throw new Error("proxy fetch only supports GET, POST, PUT, DELETE, PATCH.");',
555 - ' }',
556 - ' return {',
557 - ' endpoint: endpoint.trim(),',
558 - ' method,',
559 - ' parameters: normalizeFetchHeaders(init.headers),',
560 - ' body: await normalizeFetchBody(init.body),',
561 - ' };',
562 - '};',
563 - 'const fetchComposioJson = async (pathname, body) => {',
564 - ' const auth = requireConsumerProxyContext();',
565 - ' const response = await fetch(`${composioBaseURL}${pathname}`, {',
566 - ' method: "POST",',
567 - ' headers: {',
568 - ' "content-type": "application/json",',
569 - ' "x-user-api-key": auth.apiKey,',
570 - ' "x-org-id": auth.orgId,',
571 - ' "x-project-id": auth.projectId,',
572 - ' },',
573 - ' body: JSON.stringify(body),',
574 - ' });',
575 - ' const raw = await response.text();',
576 - ' const parsed = parseJson(raw);',
577 - ' if (!response.ok) {',
578 - ' const detail = typeof parsed === "string" ? parsed : (parsed?.message || parsed?.error || raw.trim() || undefined);',
579 - ' const error = new Error(`Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ""}`);',
580 - ' Object.assign(error, { status: response.status, response: parsed ?? raw });',
581 - ' throw error;',
582 - ' }',
583 - ' return parsed;',
584 - '};',
585 - 'const getProxySessionId = async (toolkit) => {',
586 - ' const cached = proxySessionCache.get(toolkit);',
587 - ' if (cached) return cached;',
588 - ' const auth = requireConsumerProxyContext();',
589 - ' const created = await fetchComposioJson("/api/v3/tool_router/session", {',
590 - ' user_id: auth.userId,',
591 - ' manage_connections: { enable: false },',
592 - ' toolkits: { enable: [toolkit] },',
593 - ' });',
594 - ' const sessionId = created?.session_id;',
595 - ' if (typeof sessionId !== "string" || sessionId.length === 0) {',
596 - ' throw new Error("Composio proxy session creation returned no session_id.");',
597 - ' }',
598 - ' proxySessionCache.set(toolkit, sessionId);',
599 - ' return sessionId;',
600 - '};',
601 - '',
602 - 'const runCliJson = async (args) => {',
603 - ' const requestId = `${args[0] ?? "cli"}#${++perfDebugSeq}`;',
604 - ' helperDebugLog("cli.start", { requestId, args });',
605 - ' const env = {',
606 - ' ...process.env,',
607 - ' ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),',
608 - ' ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),',
609 - ' ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),',
610 - ' COMPOSIO_CLI_INVOCATION_ORIGIN: "run",',
611 - ' ...(helperContext.runId ? { COMPOSIO_CLI_PARENT_RUN_ID: helperContext.runId } : {}),',
612 - ' ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),',
613 - ' ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: "1" } : {}),',
614 - ' ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: "1" } : {}),',
615 - ' };',
616 - ' delete env.BUN_BE_BUN;',
617 - ' perfDebugLog("start", requestId, { cmd: args });',
618 - ' const child = Bun.spawn({',
619 - ' cmd: [...cliPrefix, ...args],',
620 - ' env,',
621 - " stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],",
622 - ' });',
623 - ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
624 - ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
625 - ' const result = maybeLoadStoredCliResult(parseJson(stdout));',
626 - ' const exitCode = await child.exited;',
627 - ' if (exitCode !== 0) {',
628 - ' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',
629 - ' helperDebugLog("cli.error", { requestId, command: args[0], exitCode, stderr: stderr.trim() || undefined });',
630 - ' const error = new Error(`composio ${args.join(" ")} failed with exit code ${exitCode}`);',
631 - ' Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });',
632 - ' throw error;',
633 - ' }',
634 - ' if (result === undefined) {',
635 - ' const details = stderr.trim();',
636 - ' const suffix = details ? `: ${details}` : "";',
637 - ' perfDebugLog("error", requestId, { exitCode, stderr: details || undefined, noJson: true });',
638 - ' helperDebugLog("cli.error", { requestId, command: args[0], exitCode, stderr: details || undefined, noJson: true });',
639 - ' const error = new Error(`composio ${args.join(" ")} returned no JSON output${suffix}`);',
640 - ' Object.assign(error, { exitCode, result, stderr: details || undefined });',
641 - ' throw error;',
642 - ' }',
643 - ' perfDebugLog("end", requestId, { exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
644 - ' logCliResultPreview(requestId, args[0], result);',
645 - ' helperDebugLog("cli.done", { requestId, exitCode });',
646 - ' return result;',
647 - '};',
648 - '',
649 - 'globalThis.search = async (query, options = {}) => {',
650 - ' helperDebugLog("search.prepare", { query, options });',
651 - ' const args = ["search", query];',
652 - ' if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {',
653 - ' args.push("--toolkits", options.toolkits.join(","));',
654 - ' } else if (typeof options.toolkits === "string" && options.toolkits.trim().length > 0) {',
655 - ' args.push("--toolkits", options.toolkits);',
656 - ' }',
657 - ' if (typeof options.limit === "number") {',
658 - ' args.push("--limit", String(options.limit));',
659 - ' }',
660 - ' return runCliJson(args);',
661 - '};',
662 - '',
663 - 'globalThis.execute = async (slug, data = {}) => {',
664 - ' helperDebugLog("execute.prepare", { slug, hasData: data !== undefined });',
665 - ' const args = ["execute", slug];',
666 - ' if (helperContext.dryRun === true) {',
667 - ' args.push("--dry-run");',
668 - ' }',
669 - ' if (helperContext.skipConnectionCheck === true) {',
670 - ' args.push("--skip-connection-check");',
671 - ' }',
672 - ' if (helperContext.skipToolParamsCheck === true) {',
673 - ' args.push("--skip-tool-params-check");',
674 - ' }',
675 - ' if (helperContext.skipChecks === true) {',
676 - ' args.push("--skip-checks");',
677 - ' }',
678 - ' if (data !== undefined) {',
679 - ' const serialized = typeof data === "string" ? data : JSON.stringify(data);',
680 - ' args.push("--data", serialized);',
681 - ' }',
682 - ' const result = await runCliJson(args);',
683 - ' if (result && typeof result === "object" && result.successful === false) {',
684 - ' const message = typeof result.error === "string" && result.error.trim().length > 0',
685 - ' ? result.error.trim()',
686 - ' : `composio execute ${slug} failed`;',
687 - ' const error = new Error(message);',
688 - ' Object.assign(error, { result, slug });',
689 - ' throw error;',
690 - ' }',
691 - ' return result;',
692 - '};',
693 - '',
694 -];
695 -
696 -const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [
697 - 'const experimentalSubAgentImpl = async (prompt, options = {}) => {',
698 - ' if (typeof prompt !== "string" || prompt.trim().length === 0) {',
699 - ' throw new Error("experimental_subAgent() requires a non-empty prompt string.");',
700 - ' }',
701 - ' const logFilePath = typeof helperContext.runLogFilePath === "string" && helperContext.runLogFilePath.length > 0 ? helperContext.runLogFilePath : undefined;',
702 - ' const normalizedOptions = normalizeInvokeAgentOptions(options);',
703 - ' const target = resolveInvokeAgentTarget(normalizedOptions.target);',
704 - ' const master = detectInvokeAgentMaster();',
705 - ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target, master });',
706 - ' try {',
707 - ' const response = await invokeAcpSubAgent({',
708 - ' prompt: prompt.trim(),',
709 - ' options: normalizedOptions,',
710 - ' master,',
711 - ' target,',
712 - ' allowedReadRoots: Array.isArray(helperContext.readAccessRoots) ? helperContext.readAccessRoots : [],',
713 - ' helperDebugLog,',
714 - ' });',
715 - ' return logFilePath ? { ...response, logFilePath } : response;',
716 - ' } catch (error) {',
717 - ' if (!isAcpInvokeError(error)) {',
718 - ' throw error;',
719 - ' }',
720 - ' if (helperContext.acpOnly === true) {',
721 - ' throw error;',
722 - ' }',
723 - ' helperDebugLog("subAgent.acp.fallback", { target, code: error.code, message: error.message });',
724 - ' const response = await invokeLegacySubAgent({',
725 - ' prompt: prompt.trim(),',
726 - ' options: normalizedOptions,',
727 - ' master,',
728 - ' target,',
729 - ' allowedReadRoots: Array.isArray(helperContext.readAccessRoots) ? helperContext.readAccessRoots : [],',
730 - ' helperDebugLog,',
731 - ' });',
732 - ' return logFilePath ? { ...response, logFilePath } : response;',
733 - ' }',
734 - '};',
735 - 'globalThis.experimental_subAgent = experimentalSubAgentImpl;',
736 - 'Object.defineProperty(globalThis.experimental_subAgent, "schema", { value: experimentalSubAgentSchema });',
737 - 'globalThis.invokeAgent = experimentalSubAgentImpl;',
738 - 'Object.defineProperty(globalThis.invokeAgent, "schema", { value: experimentalSubAgentSchema });',
739 - '',
740 -];
741 -
742 -const buildRunProxyHelpersSource = (): ReadonlyArray<string> => [
743 - 'const toProxyResponse = async (result) => {',
744 - ' const headers = new Headers(result?.headers || {});',
745 - ' if (result?.binary_data?.url) {',
746 - ' const binaryResponse = await fetch(result.binary_data.url);',
747 - ' binaryResponse.headers.forEach((value, key) => {',
748 - ' if (!headers.has(key)) headers.set(key, value);',
749 - ' });',
750 - ' return new Response(binaryResponse.body, {',
751 - ' status: result.status ?? binaryResponse.status,',
752 - ' headers,',
753 - ' });',
754 - ' }',
755 - ' if (result?.data === undefined || result?.data === null) {',
756 - ' return new Response(null, { status: result?.status ?? 200, headers });',
757 - ' }',
758 - ' if (typeof result.data === "string") {',
759 - ' if (!headers.has("content-type")) headers.set("content-type", "text/plain; charset=utf-8");',
760 - ' return new Response(result.data, { status: result.status ?? 200, headers });',
761 - ' }',
762 - ' if (!headers.has("content-type")) headers.set("content-type", "application/json; charset=utf-8");',
763 - ' return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });',
764 - '};',
765 - 'globalThis.proxy = async (toolkit) => {',
766 - ' const normalizedToolkit = normalizeProxyToolkit(toolkit);',
767 - ' helperDebugLog("proxy.session", { toolkit: normalizedToolkit, cached: proxySessionCache.has(normalizedToolkit) });',
768 - ' const sessionId = await getProxySessionId(normalizedToolkit);',
769 - ' const proxyFetch = async (input, init = {}) => {',
770 - ' const request = await normalizeFetchInput(input, init);',
771 - ' helperDebugLog("proxy.request", { toolkit: normalizedToolkit, method: request.method, endpoint: request.endpoint });',
772 - ' const result = await fetchComposioJson(`/api/v3/tool_router/session/${sessionId}/proxy_execute`, {',
773 - ' toolkit_slug: normalizedToolkit,',
774 - ' endpoint: request.endpoint,',
775 - ' method: request.method,',
776 - ' ...(request.body !== undefined ? { body: request.body } : {}),',
777 - ' ...(request.parameters?.length',
778 - ' ? {',
779 - ' parameters: request.parameters.map((parameter) => ({',
780 - ' name: parameter.name,',
781 - ' type: parameter.type,',
782 - ' value: String(parameter.value),',
783 - ' })),',
784 - ' }',
785 - ' : {}),',
786 - ' });',
787 - ' return toProxyResponse(result);',
788 - ' };',
789 - ' Object.defineProperty(proxyFetch, "toolkit", { value: normalizedToolkit });',
790 - ' return proxyFetch;',
791 - '};',
792 - 'Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });',
793 - '',
794 - 'Object.defineProperty(globalThis, "__composioRunContext", {',
795 - ' value: Object.freeze({',
796 - ' outputDir: sharedRunOutputDir,',
797 - ' logFilePath: sharedRunLogFilePath,',
798 - ' }),',
799 - ' configurable: true,',
800 - '});',
801 - '',
802 - 'Object.defineProperty(globalThis, "__composioConsumerContext", {',
803 - ' value: helperContext,',
804 - ' configurable: true,',
805 - '});',
806 - '',
807 -];
808 -
186 export const buildRunHelpersSource = (
187 cliPrefix: ReadonlyArray<string>,
188 context: RunHelperContext = {},
189 moduleUrls: RunHelperModuleUrls = resolveRunHelperModuleUrls()
190 ): string =>
191 [
815 - 'import * as fs from "node:fs";',
816 - 'import { z } from "zod";',
817 - `import { isAcpInvokeError } from ${JSON.stringify(moduleUrls.subAgentSharedModuleUrl)};`,
818 - `import { invokeAcpSubAgent } from ${JSON.stringify(moduleUrls.subAgentAcpModuleUrl)};`,
819 - `import { invokeLegacySubAgent } from ${JSON.stringify(moduleUrls.subAgentLegacyModuleUrl)};`,
820 - '',
821 - `const cliPrefix = ${JSON.stringify(cliPrefix)};`,
822 - `const helperContext = ${JSON.stringify(context)};`,
192 + `import { installRunHelpers } from ${JSON.stringify(moduleUrls.helpersRuntimeModuleUrl)};`,
193 '',
824 - ...buildRunBaseHelpersSource(),
825 - ...buildRunInvokeAgentHelpersSource(),
826 - ...buildRunProxyHelpersSource(),
194 + `await installRunHelpers(${JSON.stringify({ cliPrefix, helperContext: context })});`,
195 ].join('\n');
196
197 const createRunHelpersPreloadFile = (
@@ -850,12 +218,16 @@ const createRunHelpersPreloadFile = (
218 fs.writeFileSync(runLogFilePath, '', 'utf8');
219 fs.writeFileSync(
220 preloadPath,
853 - buildRunHelpersSource(cliPrefix, {
854 - ...context,
855 - runOutputDir,
856 - runLogFilePath,
857 - readAccessRoots,
858 - }, moduleUrls),
221 + buildRunHelpersSource(
222 + cliPrefix,
223 + {
224 + ...context,
225 + runOutputDir,
226 + runLogFilePath,
227 + readAccessRoots,
228 + },
229 + moduleUrls
230 + ),
231 'utf8'
232 );
233 return { directory, preloadPath, runOutputDir, runLogFilePath };
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+7 -1
@@ -17,7 +17,7 @@ import {
17 validateToolInputArgumentsWithDefinition,
18 } from 'src/services/tool-input-validation';
19 import { TerminalUI } from 'src/services/terminal-ui';
20 -import { ToolsExecutor } from 'src/services/tools-executor';
20 +import { ToolsExecutor, detectInBandWarning } from 'src/services/tools-executor';
21 import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';
22 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
23 import { ComposioUserContext } from 'src/services/user-context';
@@ -1188,6 +1188,12 @@ const runExecuteWithSpinner = (params: {
1188 ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
1189 : '';
1190 yield* spinner.stop(`Execution successful${logId}`);
1191 + const inBandWarning = detectInBandWarning(result.data);
1192 + if (inBandWarning) {
1193 + yield* params.ui.log.warn(
1194 + `The tool executed successfully but the response may contain an error: ${inBandWarning}`
1195 + );
1196 + }
1197 const output = yield* prepareExecuteOutput(params.slug, result, params.executeOutputDir);
1198 if (output.kind === 'file') {
1199 yield* params.ui.log.message(
ts/packages/cli/src/services/run-companion-modules.ts
+1
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'node:url';
5 import decompress from 'decompress';
6
7 export const RUN_COMPANION_MODULE_BASENAMES = [
8 + 'run-helpers-runtime',
9 'run-subagent-shared',
10 'run-subagent-acp',
11 'run-subagent-legacy',
ts/packages/cli/src/services/run-helpers-runtime.ts new
+853
@@ -0,0 +1,853 @@
1 +import * as fs from 'node:fs';
2 +import process from 'node:process';
3 +import { z } from 'zod';
4 +import type { MasterKind } from 'src/services/master-detector';
5 +import { isAcpInvokeError, type InvokeAgentTarget } from 'src/services/run-subagent-shared';
6 +import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';
7 +import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';
8 +
9 +export type RunHelperContext = {
10 + readonly apiKey?: string;
11 + readonly baseURL?: string;
12 + readonly webURL?: string;
13 + readonly orgId?: string;
14 + readonly runId?: string;
15 + readonly consumerUserId?: string;
16 + readonly consumerProjectId?: string;
17 + readonly consumerProjectName?: string;
18 + readonly perfDebug?: boolean;
19 + readonly toolDebug?: boolean;
20 + readonly dryRun?: boolean;
21 + readonly skipConnectionCheck?: boolean;
22 + readonly skipToolParamsCheck?: boolean;
23 + readonly skipChecks?: boolean;
24 + readonly master?: MasterKind;
25 + readonly debug?: boolean;
26 + readonly acpOnly?: boolean;
27 + readonly logsOff?: boolean;
28 + readonly runOutputDir?: string;
29 + readonly runLogFilePath?: string;
30 + readonly readAccessRoots?: ReadonlyArray<string>;
31 +};
32 +
33 +type RunHelpersInstallParams = {
34 + readonly cliPrefix: ReadonlyArray<string>;
35 + readonly helperContext?: RunHelperContext;
36 +};
37 +
38 +type RunCliResult =
39 + | undefined
40 + | string
41 + | number
42 + | boolean
43 + | {
44 + readonly successful?: boolean;
45 + readonly storedInFile?: boolean;
46 + readonly outputFilePath?: string | null;
47 + readonly tokenCount?: number | null;
48 + readonly error?: string | null;
49 + readonly data?: unknown;
50 + readonly [key: string]: unknown;
51 + };
52 +
53 +type PromptableResult = {
54 + readonly prompt?: () => string;
55 + readonly data?: unknown;
56 + readonly [key: string]: unknown;
57 +};
58 +
59 +type StructuredSchemaInput =
60 + | {
61 + readonly safeParse?: (value: unknown) => unknown;
62 + readonly _def?: unknown;
63 + }
64 + | Record<string, unknown>;
65 +
66 +type NormalizedInvokeAgentOptions = {
67 + readonly target?: string;
68 + readonly model?: string;
69 + readonly schema?: StructuredSchemaInput;
70 + readonly jsonSchema?: Record<string, unknown>;
71 + readonly structuredSchema?: Record<string, unknown>;
72 + readonly zodSchema?: StructuredSchemaInput;
73 +};
74 +
75 +type RunGlobalScope = typeof globalThis & {
76 + z: typeof z;
77 + zod: typeof z;
78 + search: (query: string, options?: Record<string, unknown>) => Promise<RunCliResult>;
79 + execute: (slug: string, data?: unknown) => Promise<RunCliResult>;
80 + experimental_subAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;
81 + invokeAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;
82 + proxy: (
83 + toolkit: string
84 + ) => Promise<(input: string | URL, init?: RequestInit) => Promise<Response>>;
85 + __composioRunContext: {
86 + readonly outputDir: string | null;
87 + readonly logFilePath: string | null;
88 + };
89 + __composioConsumerContext: RunHelperContext;
90 +};
91 +
92 +const experimentalSubAgentSchema = {
93 + type: 'function',
94 + description:
95 + 'Experimental helper: prompt a sub-agent from the same agent family as the current main agent (Codex -> Codex, Claude -> Claude) and return its final response.',
96 + parameters: {
97 + type: 'object',
98 + additionalProperties: false,
99 + required: ['prompt'],
100 + properties: {
101 + prompt: { type: 'string', description: 'The prompt to send to the agent CLI.' },
102 + target: {
103 + type: 'string',
104 + enum: ['claude', 'codex', 'user'],
105 + description: 'Optional master override. Defaults to the detected current master.',
106 + },
107 + model: {
108 + type: 'string',
109 + description: 'Optional model override passed through to the agent CLI.',
110 + },
111 + schema: {
112 + description:
113 + 'Optional structured-output schema. Accepts a Zod schema or raw JSON Schema object.',
114 + },
115 + jsonSchema: {
116 + description: 'Optional JSON Schema requesting structured output from the agent.',
117 + },
118 + },
119 + },
120 + returns: {
121 + type: 'object',
122 + additionalProperties: false,
123 + required: ['master', 'target', 'result'],
124 + properties: {
125 + master: { type: 'string', enum: ['claude', 'codex', 'user'] },
126 + target: { type: 'string', enum: ['claude', 'codex'] },
127 + result: { description: 'Final plain-text result when available.' },
128 + structuredOutput: { description: 'Structured output when jsonSchema was requested.' },
129 + logFilePath: { description: 'Path to the local run log file for helper execution details.' },
130 + },
131 + },
132 +} as const;
133 +
134 +const proxySchema = {
135 + type: 'function',
136 + description:
137 + "Call proxy(toolkit) to get a fetch-compatible function bound to that toolkit's connected account.",
138 + parameters: {
139 + type: 'object',
140 + additionalProperties: false,
141 + required: ['toolkit'],
142 + properties: {
143 + toolkit: {
144 + type: 'string',
145 + description: 'Toolkit slug whose connected account should be used',
146 + },
147 + },
148 + },
149 + returns: {
150 + type: 'function',
151 + signature: 'fetch(input, init?) => Promise<Response>',
152 + requestInit: {
153 + type: 'object',
154 + additionalProperties: true,
155 + properties: {
156 + method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] },
157 + headers: { description: 'Standard fetch headers init' },
158 + body: { description: 'String, JSON-ish value, Blob, ArrayBuffer, or Uint8Array' },
159 + },
160 + },
161 + },
162 +} as const;
163 +
164 +const runGlobals = globalThis as RunGlobalScope;
165 +
166 +const encodeBase64 = (bytes: Uint8Array): string => {
167 + let binary = '';
168 + for (const byte of bytes) {
169 + binary += String.fromCharCode(byte);
170 + }
171 + return btoa(binary);
172 +};
173 +
174 +// eslint-disable-next-line max-lines-per-function
175 +export const installRunHelpers = async ({
176 + cliPrefix,
177 + helperContext = {},
178 +}: RunHelpersInstallParams): Promise<void> => {
179 + runGlobals.z = z;
180 + runGlobals.zod = z;
181 +
182 + const perfDebugEnabled =
183 + helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';
184 + const toolDebugEnabled =
185 + helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';
186 + const perfDebugStart = Date.now();
187 + let perfDebugSeq = 0;
188 + const executeId = () => crypto.randomUUID().slice(0, 8);
189 + const proxySessionCache = new Map<string, string>();
190 + const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(
191 + /\/$/,
192 + ''
193 + );
194 + const sharedRunOutputDir =
195 + typeof helperContext.runOutputDir === 'string' && helperContext.runOutputDir.length > 0
196 + ? helperContext.runOutputDir
197 + : null;
198 + const sharedRunLogFilePath =
199 + typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0
200 + ? helperContext.runLogFilePath
201 + : null;
202 +
203 + const appendRunLogLine = (line: string) => {
204 + if (!sharedRunLogFilePath || line.length === 0) return;
205 + fs.appendFileSync(sharedRunLogFilePath, `${line}\n`, 'utf8');
206 + };
207 +
208 + const perfDebugLog = (phase: string, label: string, details: Record<string, unknown> = {}) => {
209 + if (!perfDebugEnabled) return;
210 + const elapsedMs = Date.now() - perfDebugStart;
211 + const payload = { phase, label, elapsedMs, ...details };
212 + console.error(`[perf] ${JSON.stringify(payload)}`);
213 + };
214 +
215 + const truncateDebugText = (value: unknown, max = 240) => {
216 + const text = typeof value === 'string' ? value : String(value ?? '');
217 + return text.length > max ? `${text.slice(0, max - 1)}…` : text;
218 + };
219 +
220 + const previewDebugValue = (value: unknown): string => {
221 + if (value == null) return '';
222 + if (typeof value === 'string') return truncateDebugText(value.replace(/\s+/g, ' ').trim());
223 + if (typeof value === 'number' || typeof value === 'boolean') return String(value);
224 + if (Array.isArray(value)) return `array(${value.length})`;
225 + if (typeof value === 'object') {
226 + const record = value as Record<string, unknown>;
227 + const preferred = ['message', 'error', 'title', 'summary', 'brief', 'status'];
228 + for (const key of preferred) {
229 + if (typeof record[key] === 'string' && record[key].trim().length > 0) {
230 + return truncateDebugText(record[key].trim());
231 + }
232 + }
233 + return `object{${Object.keys(record).slice(0, 4).join(', ')}}`;
234 + }
235 + return truncateDebugText(String(value));
236 + };
237 +
238 + const formatHelperDebugEvent = (step: string, details: Record<string, unknown> = {}) => {
239 + switch (step) {
240 + case 'subAgent.target':
241 + return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;
242 + case 'subAgent.acp.resolve':
243 + return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;
244 + case 'subAgent.acp.initialized':
245 + return `[experimental_subAgent] ACP initialized (${details.target})`;
246 + case 'subAgent.acp.session':
247 + return `[experimental_subAgent] session ready (${details.target})`;
248 + case 'subAgent.acp.model':
249 + return details.applied === true
250 + ? `[experimental_subAgent] model=${details.model}`
251 + : `[experimental_subAgent] model unchanged (${details.model})`;
252 + case 'subAgent.acp.message': {
253 + const text = previewDebugValue(details.text);
254 + return text ? `[experimental_subAgent] ${text}` : null;
255 + }
256 + case 'subAgent.acp.thought': {
257 + const text = previewDebugValue(details.text);
258 + return text ? `[experimental_subAgent:thinking] ${text}` : null;
259 + }
260 + case 'subAgent.acp.tool_call': {
261 + const locations = Array.isArray(details.locations) ? details.locations : [];
262 + const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
263 + return `[experimental_subAgent:tool] ${details.status || 'pending'} ${
264 + details.title || details.kind || 'tool'
265 + }${where}`;
266 + }
267 + case 'subAgent.acp.tool_call_update': {
268 + const locations = Array.isArray(details.locations) ? details.locations : [];
269 + const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
270 + const preview = previewDebugValue(details.rawOutput);
271 + return `[experimental_subAgent:tool] ${details.status || 'update'} ${
272 + details.title || details.toolCallId || details.kind || 'tool'
273 + }${where}${preview ? ` -> ${preview}` : ''}`;
274 + }
275 + case 'subAgent.acp.plan': {
276 + const entries = Array.isArray(details.entries)
277 + ? (details.entries as Array<{ status?: string; content?: string }>)
278 + : [];
279 + if (entries.length === 0) return '[experimental_subAgent:plan] updated';
280 + const summary = entries
281 + .slice(0, 3)
282 + .map(entry => `${entry.status}:${truncateDebugText(entry.content || '', 48)}`)
283 + .join(' | ');
284 + return `[experimental_subAgent:plan] ${summary}`;
285 + }
286 + case 'subAgent.acp.fallback':
287 + return `[experimental_subAgent] ACP fallback (${details.code})`;
288 + case 'execute.prepare':
289 + return `[execute] ${details.slug}`;
290 + case 'search.prepare':
291 + return `[search] ${truncateDebugText(details.query || '', 96)}`;
292 + case 'proxy.request':
293 + return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || '', 96)}`;
294 + case 'cli.result': {
295 + const command = typeof details.command === 'string' ? details.command : 'cli';
296 + const state = details.successful === false ? 'failed' : 'ok';
297 + const preview = previewDebugValue(details.preview);
298 + return `[${command}] ${state}${preview ? ` ${preview}` : ''}`;
299 + }
300 + case 'cli.error': {
301 + const command = typeof details.command === 'string' ? details.command : 'cli';
302 + const stderr = previewDebugValue(details.stderr);
303 + return `[${command}] failed${stderr ? ` ${stderr}` : ''}`;
304 + }
305 + default:
306 + return null;
307 + }
308 + };
309 +
310 + const helperDebugLog = (step: string, details: Record<string, unknown> = {}) => {
311 + const line = formatHelperDebugEvent(step, details);
312 + const elapsedMs = Date.now() - perfDebugStart;
313 + appendRunLogLine(line ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);
314 + };
315 +
316 + const parseJson = (text: string): unknown => {
317 + const value = text.trim();
318 + if (!value) return undefined;
319 + try {
320 + return JSON.parse(value);
321 + } catch {
322 + return value;
323 + }
324 + };
325 +
326 + const stringifyForPrompt = (value: unknown): string => {
327 + if (value === undefined) return 'undefined';
328 + if (value === null) return 'null';
329 + if (typeof value === 'string') return value;
330 + if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
331 + return String(value);
332 + }
333 + try {
334 + return JSON.stringify(value, null, 2);
335 + } catch {
336 + return String(value);
337 + }
338 + };
339 +
340 + const attachPromptMethod = <T>(value: T): T => {
341 + if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
342 + const promptable = value as PromptableResult;
343 + if (typeof promptable.prompt === 'function') return value;
344 + Object.defineProperty(promptable, 'prompt', {
345 + value: () => stringifyForPrompt('data' in promptable ? promptable.data : promptable),
346 + enumerable: false,
347 + });
348 + return value;
349 + };
350 +
351 + const maybeLoadStoredCliResult = (result: RunCliResult): RunCliResult => {
352 + if (!result || typeof result !== 'object' || result.storedInFile !== true) {
353 + return attachPromptMethod(result);
354 + }
355 + helperDebugLog('cli.result.stored_in_file', {
356 + outputFilePath: result.outputFilePath ?? null,
357 + tokenCount: result.tokenCount ?? null,
358 + });
359 + const outputFilePath = typeof result.outputFilePath === 'string' ? result.outputFilePath : null;
360 + return attachPromptMethod({
361 + ...result,
362 + data: {
363 + storedInFilePath: outputFilePath !== null,
364 + outputFilePath,
365 + },
366 + });
367 + };
368 +
369 + const describeDebugValue = (value: unknown) => {
370 + if (Array.isArray(value)) return { type: 'array', length: value.length };
371 + if (value && typeof value === 'object') {
372 + return { type: 'object', keys: Object.keys(value as Record<string, unknown>).slice(0, 20) };
373 + }
374 + return {
375 + type: typeof value,
376 + value: typeof value === 'string' ? value.slice(0, 200) : (value ?? null),
377 + };
378 + };
379 +
380 + const summarizeCliResultPreview = (result: RunCliResult): unknown => {
381 + if (result == null || typeof result !== 'object') return result;
382 + if ('data' in result && result.data !== undefined) return result.data;
383 + if (typeof result.error === 'string' && result.error.trim().length > 0)
384 + return result.error.trim();
385 + return result;
386 + };
387 +
388 + const logCliResultPreview = (
389 + requestId: string,
390 + command: string | undefined,
391 + result: RunCliResult
392 + ) => {
393 + if (!result || typeof result !== 'object') {
394 + helperDebugLog('cli.result', {
395 + requestId,
396 + command,
397 + preview: result,
398 + result: describeDebugValue(result),
399 + });
400 + return;
401 + }
402 + helperDebugLog('cli.result', {
403 + requestId,
404 + command,
405 + successful: result.successful ?? null,
406 + storedInFile: result.storedInFile ?? false,
407 + outputFilePath: result.outputFilePath ?? null,
408 + error: result.error ?? null,
409 + topLevelKeys: Object.keys(result).slice(0, 20),
410 + data: 'data' in result ? describeDebugValue(result.data) : null,
411 + preview: summarizeCliResultPreview(result),
412 + });
413 + };
414 +
415 + const detectInvokeAgentMaster = (): MasterKind | 'user' => {
416 + if (
417 + helperContext.master === 'claude' ||
418 + helperContext.master === 'codex' ||
419 + helperContext.master === 'user'
420 + ) {
421 + return helperContext.master;
422 + }
423 + const envKeys = Object.keys(process.env || {});
424 + if (envKeys.some(key => key.startsWith('CODEX_'))) return 'codex';
425 + if (envKeys.some(key => key.startsWith('CLAUDE_'))) return 'claude';
426 + return 'user';
427 + };
428 +
429 + const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {
430 + if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;
431 + const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();
432 + if (detected === 'codex' || detected === 'claude') return detected;
433 + if (typeof Bun.which === 'function' && Bun.which('codex')) return 'codex';
434 + if (typeof Bun.which === 'function' && Bun.which('claude')) return 'claude';
435 + throw new Error(
436 + 'experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: "codex" | "claude" }.'
437 + );
438 + };
439 +
440 + const normalizeInvokeAgentOptions = (
441 + options: Record<string, unknown> = {}
442 + ): NormalizedInvokeAgentOptions => {
443 + if (options == null || typeof options !== 'object' || Array.isArray(options)) {
444 + throw new Error('experimental_subAgent() options must be an object when provided.');
445 + }
446 + if (options.schema !== undefined && options.jsonSchema !== undefined) {
447 + throw new Error(
448 + 'experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.'
449 + );
450 + }
451 + const inputSchema = (options.schema ?? options.jsonSchema) as StructuredSchemaInput | undefined;
452 + let structuredSchema: Record<string, unknown> | undefined;
453 + let zodSchema: StructuredSchemaInput | undefined;
454 + if (inputSchema !== undefined) {
455 + if (
456 + typeof inputSchema === 'object' &&
457 + inputSchema !== null &&
458 + 'safeParse' in inputSchema &&
459 + typeof inputSchema.safeParse === 'function' &&
460 + '_def' in inputSchema
461 + ) {
462 + if (typeof z.toJSONSchema !== 'function') {
463 + throw new Error(
464 + 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
465 + );
466 + }
467 + zodSchema = inputSchema;
468 + structuredSchema = z.toJSONSchema(inputSchema as never) as Record<string, unknown>;
469 + } else if (
470 + typeof inputSchema === 'object' &&
471 + inputSchema !== null &&
472 + !Array.isArray(inputSchema)
473 + ) {
474 + structuredSchema = inputSchema;
475 + } else {
476 + throw new Error(
477 + 'experimental_subAgent() schema must be a Zod schema or JSON Schema object.'
478 + );
479 + }
480 + }
481 + return { ...options, structuredSchema, zodSchema };
482 + };
483 +
484 + const requireConsumerProxyContext = () => {
485 + if (!helperContext.apiKey) {
486 + throw new Error('proxy() requires an authenticated Composio user session.');
487 + }
488 + if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {
489 + throw new Error(
490 + 'proxy() requires a consumer project context so it can use the consumer project credentials.'
491 + );
492 + }
493 + return {
494 + apiKey: helperContext.apiKey,
495 + orgId: helperContext.orgId,
496 + projectId: helperContext.consumerProjectId,
497 + userId: helperContext.consumerUserId,
498 + };
499 + };
500 +
501 + const normalizeProxyToolkit = (toolkit: string) => {
502 + if (typeof toolkit !== 'string' || toolkit.trim().length === 0) {
503 + throw new Error('proxy() requires a non-empty toolkit string.');
504 + }
505 + return toolkit.trim();
506 + };
507 +
508 + const normalizeFetchHeaders = (headers: HeadersInit | undefined) => {
509 + if (!headers) return [];
510 + return [...(new Headers(headers) as unknown as Iterable<[string, string]>)].map(
511 + ([name, value]) => ({
512 + name,
513 + type: 'header',
514 + value,
515 + })
516 + );
517 + };
518 +
519 + const normalizeFetchBody = async (body: unknown) => {
520 + if (body === undefined || body === null) return undefined;
521 + if (typeof body === 'string' || typeof body === 'number' || typeof body === 'boolean')
522 + return body;
523 + if (typeof Blob !== 'undefined' && body instanceof Blob) return await body.text();
524 + if (body instanceof ArrayBuffer) return encodeBase64(new Uint8Array(body));
525 + if (ArrayBuffer.isView(body)) {
526 + return encodeBase64(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
527 + }
528 + return body;
529 + };
530 +
531 + const normalizeFetchInput = async (input: unknown, init: RequestInit = {}) => {
532 + if (typeof Request !== 'undefined' && input instanceof Request) {
533 + throw new Error(
534 + 'proxy() does not support passing a Request instance yet. Pass a URL string and init instead.'
535 + );
536 + }
537 + const endpoint = input instanceof URL ? input.toString() : input;
538 + if (typeof endpoint !== 'string' || endpoint.trim().length === 0) {
539 + throw new Error('proxy fetch requires a non-empty URL string or URL object.');
540 + }
541 + const method = typeof init.method === 'string' ? init.method.toUpperCase() : 'GET';
542 + if (!['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {
543 + throw new Error('proxy fetch only supports GET, POST, PUT, DELETE, PATCH.');
544 + }
545 + return {
546 + endpoint: endpoint.trim(),
547 + method,
548 + parameters: normalizeFetchHeaders(init.headers),
549 + body: await normalizeFetchBody(init.body),
550 + };
551 + };
552 +
553 + const fetchComposioJson = async (pathname: string, body: Record<string, unknown>) => {
554 + const auth = requireConsumerProxyContext();
555 + const response = await fetch(`${composioBaseURL}${pathname}`, {
556 + method: 'POST',
557 + headers: {
558 + 'content-type': 'application/json',
559 + 'x-user-api-key': auth.apiKey,
560 + 'x-org-id': auth.orgId,
561 + 'x-project-id': auth.projectId,
562 + },
563 + body: JSON.stringify(body),
564 + });
565 + const raw = await response.text();
566 + const parsed = parseJson(raw);
567 + if (!response.ok) {
568 + const detail =
569 + typeof parsed === 'string'
570 + ? parsed
571 + : (((parsed as { message?: string; error?: string } | undefined)?.message ||
572 + (parsed as { message?: string; error?: string } | undefined)?.error ||
573 + raw.trim()) ??
574 + undefined);
575 + const error = new Error(
576 + `Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ''}`
577 + );
578 + Object.assign(error, { status: response.status, response: parsed ?? raw });
579 + throw error;
580 + }
581 + return parsed;
582 + };
583 +
584 + const getProxySessionId = async (toolkit: string) => {
585 + const cached = proxySessionCache.get(toolkit);
586 + if (cached) return cached;
587 + const auth = requireConsumerProxyContext();
588 + const created = (await fetchComposioJson('/api/v3/tool_router/session', {
589 + user_id: auth.userId,
590 + manage_connections: { enable: false },
591 + toolkits: { enable: [toolkit] },
592 + })) as { session_id?: string };
593 + const sessionId = created?.session_id;
594 + if (typeof sessionId !== 'string' || sessionId.length === 0) {
595 + throw new Error('Composio proxy session creation returned no session_id.');
596 + }
597 + proxySessionCache.set(toolkit, sessionId);
598 + return sessionId;
599 + };
600 +
601 + const runCliJson = async (args: ReadonlyArray<string>): Promise<RunCliResult> => {
602 + const requestId = `${args[0] ?? 'cli'}#${++perfDebugSeq}`;
603 + helperDebugLog('cli.start', { requestId, args });
604 + const env = {
605 + ...process.env,
606 + ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),
607 + ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),
608 + ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),
609 + COMPOSIO_CLI_INVOCATION_ORIGIN: 'run',
610 + ...(helperContext.runId ? { COMPOSIO_CLI_PARENT_RUN_ID: helperContext.runId } : {}),
611 + ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),
612 + ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: '1' } : {}),
613 + ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),
614 + };
615 + delete (env as Record<string, string | undefined>).BUN_BE_BUN;
616 + perfDebugLog('start', requestId, { cmd: args });
617 + const child = Bun.spawn({
618 + cmd: [...cliPrefix, ...args],
619 + env,
620 + stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],
621 + });
622 + const stdout = child.stdout ? await new Response(child.stdout).text() : '';
623 + const stderr = child.stderr ? await new Response(child.stderr).text() : '';
624 + const result = maybeLoadStoredCliResult(parseJson(stdout) as RunCliResult);
625 + const exitCode = await child.exited;
626 + if (exitCode !== 0) {
627 + perfDebugLog('error', requestId, { exitCode, stderr: stderr.trim() || undefined });
628 + helperDebugLog('cli.error', {
629 + requestId,
630 + command: args[0],
631 + exitCode,
632 + stderr: stderr.trim() || undefined,
633 + });
634 + const error = new Error(`composio ${args.join(' ')} failed with exit code ${exitCode}`);
635 + Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });
636 + throw error;
637 + }
638 + if (result === undefined) {
639 + const details = stderr.trim();
640 + const suffix = details ? `: ${details}` : '';
641 + perfDebugLog('error', requestId, { exitCode, stderr: details || undefined, noJson: true });
642 + helperDebugLog('cli.error', {
643 + requestId,
644 + command: args[0],
645 + exitCode,
646 + stderr: details || undefined,
647 + noJson: true,
648 + });
649 + const error = new Error(`composio ${args.join(' ')} returned no JSON output${suffix}`);
650 + Object.assign(error, { exitCode, result, stderr: details || undefined });
651 + throw error;
652 + }
653 + perfDebugLog('end', requestId, {
654 + exitCode,
655 + stdoutBytes: stdout.length,
656 + stderrBytes: stderr.length,
657 + });
658 + logCliResultPreview(requestId, args[0], result);
659 + helperDebugLog('cli.done', { requestId, exitCode });
660 + return result;
661 + };
662 +
663 + runGlobals.search = async (query, options = {}) => {
664 + helperDebugLog('search.prepare', { query, options });
665 + const args = ['search', query];
666 + if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {
667 + args.push('--toolkits', options.toolkits.join(','));
668 + } else if (typeof options.toolkits === 'string' && options.toolkits.trim().length > 0) {
669 + args.push('--toolkits', options.toolkits);
670 + }
671 + if (typeof options.limit === 'number') {
672 + args.push('--limit', String(options.limit));
673 + }
674 + return runCliJson(args);
675 + };
676 +
677 + runGlobals.execute = async (slug, data = {}) => {
678 + helperDebugLog('execute.prepare', { slug, hasData: data !== undefined });
679 + const args = ['execute', slug];
680 + if (helperContext.dryRun === true) args.push('--dry-run');
681 + if (helperContext.skipConnectionCheck === true) args.push('--skip-connection-check');
682 + if (helperContext.skipToolParamsCheck === true) args.push('--skip-tool-params-check');
683 + if (helperContext.skipChecks === true) args.push('--skip-checks');
684 + if (data !== undefined) {
685 + const serialized = typeof data === 'string' ? data : JSON.stringify(data);
686 + if (sharedRunOutputDir) {
687 + const tmpFile = `${sharedRunOutputDir}/execute-data-${slug}-${executeId()}.json`;
688 + fs.writeFileSync(tmpFile, serialized, 'utf8');
689 + args.push('--data', `@${tmpFile}`);
690 + } else {
691 + args.push('--data', serialized);
692 + }
693 + }
694 + const result = await runCliJson(args);
695 + if (result && typeof result === 'object' && result.successful === false) {
696 + const message =
697 + typeof result.error === 'string' && result.error.trim().length > 0
698 + ? result.error.trim()
699 + : `composio execute ${slug} failed`;
700 + const error = new Error(message);
701 + Object.assign(error, { result, slug });
702 + throw error;
703 + }
704 + return result;
705 + };
706 +
707 + const experimentalSubAgentImpl = async (
708 + prompt: string,
709 + options: Record<string, unknown> = {}
710 + ) => {
711 + if (typeof prompt !== 'string' || prompt.trim().length === 0) {
712 + throw new Error('experimental_subAgent() requires a non-empty prompt string.');
713 + }
714 + const logFilePath =
715 + typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0
716 + ? helperContext.runLogFilePath
717 + : undefined;
718 + const normalizedOptions = normalizeInvokeAgentOptions(options);
719 + const target = resolveInvokeAgentTarget(normalizedOptions.target);
720 + const master = detectInvokeAgentMaster();
721 + helperDebugLog('subAgent.target', {
722 + requestedTarget: normalizedOptions.target ?? null,
723 + resolvedTarget: target,
724 + master,
725 + });
726 + try {
727 + const response = await invokeAcpSubAgent({
728 + prompt: prompt.trim(),
729 + options:
730 + normalizedOptions as import('src/services/run-subagent-shared').InvokeAgentNormalizedOptions,
731 + master,
732 + target,
733 + allowedReadRoots: Array.isArray(helperContext.readAccessRoots)
734 + ? helperContext.readAccessRoots
735 + : [],
736 + helperDebugLog,
737 + });
738 + return logFilePath ? { ...response, logFilePath } : response;
739 + } catch (error) {
740 + if (!isAcpInvokeError(error)) throw error;
741 + if (helperContext.acpOnly === true) throw error;
742 + helperDebugLog('subAgent.acp.fallback', {
743 + target,
744 + code: error.code,
745 + message: error.message,
746 + });
747 + const response = await invokeLegacySubAgent({
748 + prompt: prompt.trim(),
749 + options:
750 + normalizedOptions as import('src/services/run-subagent-shared').InvokeAgentNormalizedOptions,
751 + master,
752 + target,
753 + helperDebugLog,
754 + });
755 + return logFilePath ? { ...response, logFilePath } : response;
756 + }
757 + };
758 +
759 + runGlobals.experimental_subAgent = experimentalSubAgentImpl;
760 + Object.defineProperty(runGlobals.experimental_subAgent, 'schema', {
761 + value: experimentalSubAgentSchema,
762 + });
763 + runGlobals.invokeAgent = experimentalSubAgentImpl;
764 + Object.defineProperty(runGlobals.invokeAgent, 'schema', { value: experimentalSubAgentSchema });
765 +
766 + const toProxyResponse = async (result: {
767 + readonly headers?: Record<string, string>;
768 + readonly binary_data?: { readonly url?: string };
769 + readonly data?: unknown;
770 + readonly status?: number;
771 + }) => {
772 + const headers = new Headers(result?.headers || {});
773 + if (result?.binary_data?.url) {
774 + const binaryResponse = await fetch(result.binary_data.url);
775 + binaryResponse.headers.forEach((value, key) => {
776 + if (!headers.has(key)) headers.set(key, value);
777 + });
778 + return new Response(binaryResponse.body, {
779 + status: result.status ?? binaryResponse.status,
780 + headers,
781 + });
782 + }
783 + if (result?.data === undefined || result?.data === null) {
784 + return new Response(null, { status: result?.status ?? 200, headers });
785 + }
786 + if (typeof result.data === 'string') {
787 + if (!headers.has('content-type')) headers.set('content-type', 'text/plain; charset=utf-8');
788 + return new Response(result.data, { status: result.status ?? 200, headers });
789 + }
790 + if (!headers.has('content-type'))
791 + headers.set('content-type', 'application/json; charset=utf-8');
792 + return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });
793 + };
794 +
795 + runGlobals.proxy = async (toolkit: string) => {
796 + const normalizedToolkit = normalizeProxyToolkit(toolkit);
797 + helperDebugLog('proxy.session', {
798 + toolkit: normalizedToolkit,
799 + cached: proxySessionCache.has(normalizedToolkit),
800 + });
801 + const sessionId = await getProxySessionId(normalizedToolkit);
802 + const proxyFetch = async (input: string | URL, init: RequestInit = {}) => {
803 + const request = await normalizeFetchInput(input, init);
804 + helperDebugLog('proxy.request', {
805 + toolkit: normalizedToolkit,
806 + method: request.method,
807 + endpoint: request.endpoint,
808 + });
809 + const result = (await fetchComposioJson(
810 + `/api/v3/tool_router/session/${sessionId}/proxy_execute`,
811 + {
812 + toolkit_slug: normalizedToolkit,
813 + endpoint: request.endpoint,
814 + method: request.method,
815 + ...(request.body !== undefined ? { body: request.body } : {}),
816 + ...(request.parameters.length > 0
817 + ? {
818 + parameters: request.parameters.map(
819 + (parameter: { name: string; type: string; value: string }) => ({
820 + name: parameter.name,
821 + type: parameter.type,
822 + value: String(parameter.value),
823 + })
824 + ),
825 + }
826 + : {}),
827 + }
828 + )) as {
829 + readonly headers?: Record<string, string>;
830 + readonly binary_data?: { readonly url?: string };
831 + readonly data?: unknown;
832 + readonly status?: number;
833 + };
834 + return toProxyResponse(result);
835 + };
836 + Object.defineProperty(proxyFetch, 'toolkit', { value: normalizedToolkit });
837 + return proxyFetch;
838 + };
839 + Object.defineProperty(runGlobals.proxy, 'schema', { value: proxySchema });
840 +
841 + Object.defineProperty(runGlobals, '__composioRunContext', {
842 + value: Object.freeze({
843 + outputDir: sharedRunOutputDir,
844 + logFilePath: sharedRunLogFilePath,
845 + }),
846 + configurable: true,
847 + });
848 +
849 + Object.defineProperty(runGlobals, '__composioConsumerContext', {
850 + value: helperContext,
851 + configurable: true,
852 + });
853 +};
ts/packages/cli/src/services/tools-executor.ts
+31
@@ -76,6 +76,37 @@ const normalizeResponse = (
76 logId: raw.log_id,
77 });
78
79 +/**
80 + * Detect in-band error hints in tool response data.
81 + *
82 + * Some external services (e.g. Metabase) return HTTP 200 with the error
83 + * embedded inside the data payload. This does NOT override `successful` —
84 + * the tool execution itself succeeded — but returns a warning message so
85 + * the CLI display layer can surface it to the user.
86 + */
87 +export const detectInBandWarning = (
88 + data: Record<string, unknown> | null | undefined
89 +): string | null => {
90 + if (data == null) return null;
91 +
92 + if (typeof data.status === 'string') {
93 + const status = data.status.toLowerCase();
94 + if (status === 'failed' || status === 'error') {
95 + if (typeof data.error === 'string') return data.error;
96 + if (typeof data.message === 'string') return data.message;
97 + return `Tool response contains status: ${data.status}`;
98 + }
99 + }
100 +
101 + if (data.successfull === false || data.successful === false) {
102 + if (typeof data.error === 'string') return data.error;
103 + if (typeof data.message === 'string') return data.message;
104 + return 'Tool response indicates unsuccessful execution';
105 + }
106 +
107 + return null;
108 +};
109 +
110 export const ToolsExecutorLive = Layer.effect(
111 ToolsExecutor,
112 Effect.gen(function* () {
ts/packages/cli/test/src/commands/run.cmd.test.ts
+24 -85
@@ -257,95 +257,14 @@ describe('buildRunHelpersSource', () => {
257 runLogFilePath: '/tmp/composio-run/run.log',
258 });
259
260 - expect(source).toContain('import * as fs from "node:fs";');
261 - expect(source).toContain('import { z } from "zod";');
262 - expect(source).toContain('import { isAcpInvokeError } from "file://');
263 - expect(source).toContain('import { invokeAcpSubAgent } from "file://');
264 - expect(source).toContain('import { invokeLegacySubAgent } from "file://');
265 - expect(source).toContain('globalThis.z = z;');
266 - expect(source).toContain('globalThis.zod = z;');
267 - expect(source).toContain('const stringifyForPrompt = (value) => {');
268 - expect(source).toContain('const attachPromptMethod = (value) => {');
269 - expect(source).toContain('typeof value.prompt === "function"');
270 - expect(source).toContain(
271 - 'value: () => stringifyForPrompt("data" in value ? value.data : value),'
272 - );
273 - expect(source).toContain(
274 - 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string"'
275 - );
276 - expect(source).toContain(
277 - 'const sharedRunLogFilePath = typeof helperContext.runLogFilePath === "string"'
278 - );
279 - expect(source).toContain('const appendRunLogLine = (line) => {');
280 - expect(source).toContain('COMPOSIO_RUN_OUTPUT_DIR');
281 - expect(source).toContain('const maybeLoadStoredCliResult = (result) => {');
282 - expect(source).toContain('storedInFilePath: outputFilePath !== null,');
283 - expect(source).toContain('outputFilePath,');
284 - expect(source).toContain('const formatHelperDebugEvent = (step, details = {}) => {');
285 - expect(source).toContain(
286 - 'return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;'
287 - );
288 - expect(source).toContain('const logCliResultPreview = (requestId, command, result) => {');
289 - expect(source).toContain('helperDebugLog("cli.result", {');
290 - expect(source).toContain('helperDebugLog("cli.result.stored_in_file"');
291 - expect(source).toContain('case "subAgent.acp.message":');
292 - expect(source).toContain('COMPOSIO_USER_API_KEY');
260 + expect(source).toContain('import { installRunHelpers } from "file://');
261 + expect(source).toContain('await installRunHelpers(');
262 + expect(source).toContain('"cliPrefix":["/tmp/composio"]');
263 expect(source).toContain('"acpOnly":true');
264 expect(source).toContain('"logsOff":true');
265 expect(source).toContain('"runLogFilePath":"/tmp/composio-run/run.log"');
266 expect(source).toContain('"consumerUserId":"consumer_user_test"');
297 - expect(source).toContain('Object.defineProperty(globalThis, "__composioRunContext", {');
298 - expect(source).toContain('__composioConsumerContext');
299 - expect(source).toContain('globalThis.execute = async (slug, data = {}) => {');
300 - expect(source).toContain(
301 - 'if (result && typeof result === "object" && result.successful === false) {'
302 - );
303 - expect(source).toContain('Object.assign(error, { result, slug });');
304 - expect(source).toContain('globalThis.experimental_subAgent = experimentalSubAgentImpl;');
305 - expect(source).toContain(
306 - 'Object.defineProperty(globalThis.experimental_subAgent, "schema", { value: experimentalSubAgentSchema });'
307 - );
308 - expect(source).toContain('globalThis.invokeAgent = experimentalSubAgentImpl;');
309 - expect(source).toContain(
310 - 'const logFilePath = typeof helperContext.runLogFilePath === "string"'
311 - );
312 - expect(source).toContain('const response = await invokeAcpSubAgent({');
313 - expect(source).toContain('return logFilePath ? { ...response, logFilePath } : response;');
314 - expect(source).toContain('if (!isAcpInvokeError(error)) {');
315 - expect(source).toContain('if (helperContext.acpOnly === true) {');
316 - expect(source).toContain('helperDebugLog("subAgent.acp.fallback"');
317 - expect(source).toContain('const response = await invokeLegacySubAgent({');
318 - expect(source).toContain('const detectInvokeAgentMaster = () => {');
319 - expect(source).toContain(
320 - 'throw new Error("experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.");'
321 - );
322 - expect(source).toContain('const inputSchema = options.schema ?? options.jsonSchema;');
323 - expect(source).toContain('if (typeof z.toJSONSchema !== "function") {');
324 - expect(source).toContain(
325 - 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
326 - );
327 - expect(source).toContain('let zodSchema;');
328 - expect(source).toContain('zodSchema = inputSchema;');
329 - expect(source).toContain('structuredSchema = z.toJSONSchema(inputSchema);');
330 - expect(source).not.toContain(
331 - 'const runExternalCommandText = async (cmd, spawnOptions = {}) => {'
332 - );
333 - expect(source).toContain('globalThis.proxy = async (toolkit) => {');
334 - expect(source).toContain('const proxyFetch = async (input, init = {}) => {');
335 - expect(source).toContain('return toProxyResponse(result);');
336 - expect(source).toContain(
337 - 'Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });'
338 - );
339 - expect(source).toContain('`/api/v3/tool_router/session/${sessionId}/proxy_execute`');
340 - expect(source).toContain('"proxy() requires a consumer project context');
341 - expect(source).toContain('returned no JSON output');
342 - expect(source).toContain('args.push("--dry-run");');
343 - expect(source).toContain('args.push("--skip-connection-check");');
344 - expect(source).toContain('args.push("--skip-tool-params-check");');
345 - expect(source).toContain('args.push("--skip-checks");');
346 - expect(source).toContain(
347 - "stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe']"
348 - );
267 + expect(source).not.toContain('globalThis.execute = async (slug, data = {}) => {');
268 });
269 });
270
@@ -531,6 +450,11 @@ describe('run companion install metadata', () => {
450 const servicesDir = path.join(tempDir, 'services');
451 fs.mkdirSync(servicesDir, { recursive: true });
452
453 + fs.writeFileSync(
454 + path.join(tempDir, 'run-helpers-runtime.mjs'),
455 + 'export * from "./services/run-helpers-runtime.mjs";\n',
456 + 'utf8'
457 + );
458 fs.writeFileSync(
459 path.join(tempDir, 'run-subagent-shared.mjs'),
460 'export * from "./services/run-subagent-shared.mjs";\n',
@@ -552,6 +476,11 @@ describe('run companion install metadata', () => {
476 'utf8'
477 );
478
479 + fs.writeFileSync(
480 + path.join(servicesDir, 'run-helpers-runtime.mjs'),
481 + 'export const runtimeValue = 1;\n',
482 + 'utf8'
483 + );
484 fs.writeFileSync(
485 path.join(servicesDir, 'run-subagent-shared.mjs'),
486 'export const x = 1;\n',
@@ -584,6 +513,11 @@ describe('run companion install metadata', () => {
513 const servicesDir = path.join(tempDir, 'services');
514 fs.mkdirSync(servicesDir, { recursive: true });
515
516 + fs.writeFileSync(
517 + path.join(tempDir, 'run-helpers-runtime.mjs'),
518 + 'export * from "./services/run-helpers-runtime.mjs";\n',
519 + 'utf8'
520 + );
521 fs.writeFileSync(
522 path.join(tempDir, 'run-subagent-shared.mjs'),
523 'export * from "./services/run-subagent-shared.mjs";\n',
@@ -605,6 +539,11 @@ describe('run companion install metadata', () => {
539 'utf8'
540 );
541
542 + fs.writeFileSync(
543 + path.join(servicesDir, 'run-helpers-runtime.mjs'),
544 + 'export const runtimeValue = 1;\n',
545 + 'utf8'
546 + );
547 fs.writeFileSync(
548 path.join(servicesDir, 'run-subagent-shared.mjs'),
549 'export const sharedValue = 1;\n',