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,
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 = (
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 };