1
+// This module is preloaded into the user's spawned child process, where no Effect
2
+// runtime or @effect/platform layers are provided, so it uses sync Node builtins.
3
// eslint-disable-next-line no-restricted-imports -- sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime
4
import * as fs from 'node:fs';
5
// eslint-disable-next-line no-restricted-imports -- os.tmpdir() locates the fallback run-files directory in the child process, outside the Effect runtime
6
import * as os from 'node:os';
5
-// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
6
-import * as path from 'node:path';
7
import process from 'node:process';
8
+import { Path } from '@effect/platform';
9
+import { Effect, Predicate, Schema } from 'effect';
10
import { z } from 'zod';
11
+import { JsonRecordSchema } from 'src/effects/json';
12
import { resolveCliConfigPathSync } from 'src/services/cli-user-config';
10
-import type { MasterKind } from 'src/services/master-detector';
11
-import { isAcpInvokeError } from 'src/services/run-subagent-shared';
13
+import { detectMaster, type MasterKind } from 'src/services/master-detector';
14
+import {
15
+ isAcpInvokeError,
16
+ parseJson,
17
+ type HelperDebugLog,
18
+ type InvokeAgentNormalizedOptions,
19
+} from 'src/services/run-subagent-shared';
20
import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';
21
import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';
22
+import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
23
24
export type RunHelperContext = {
25
readonly apiKey?: string;
50
readonly helperContext?: RunHelperContext;
51
};
52
44
-type RunCliResult =
45
- | undefined
46
- | string
47
- | number
48
- | boolean
49
- | {
50
- readonly successful?: boolean;
51
- readonly storedInFile?: boolean;
52
- readonly outputFilePath?: string | null;
53
- readonly tokenCount?: number | null;
54
- readonly error?: string | null;
55
- readonly data?: unknown;
56
- readonly [key: string]: unknown;
57
- };
53
+type RunCliResult = unknown;
54
59
-type PromptableResult = {
60
- readonly prompt?: () => string;
61
- readonly data?: unknown;
62
- readonly [key: string]: unknown;
63
-};
64
-
65
-type StructuredSchemaInput =
66
- | {
67
- readonly safeParse?: (value: unknown) => unknown;
68
- readonly _def?: unknown;
69
- }
70
- | Record<string, unknown>;
71
-
72
-type NormalizedInvokeAgentOptions = {
73
- readonly target?: string;
74
- readonly model?: string;
75
- readonly schema?: StructuredSchemaInput;
76
- readonly jsonSchema?: Record<string, unknown>;
77
- readonly structuredSchema?: Record<string, unknown>;
78
- readonly zodSchema?: StructuredSchemaInput;
79
-};
80
-
81
-type RunGlobalScope = typeof globalThis & {
82
- z: typeof z;
83
- zod: typeof z;
84
- search: (query: string, options?: Record<string, unknown>) => Promise<RunCliResult>;
85
- execute: (slug: string, data?: unknown, options?: { account?: string }) => Promise<RunCliResult>;
86
- experimental_subAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;
87
- invokeAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;
88
- proxy: (
89
- toolkit: string
90
- ) => Promise<(input: string | URL, init?: RequestInit) => Promise<Response>>;
91
- __composioRunContext: {
92
- readonly outputDir: string | null;
93
- readonly logFilePath: string | null;
94
- };
95
- __composioConsumerContext: RunHelperContext;
96
-};
55
+const JsonObject = JsonRecordSchema;
56
+const ExperimentalSubagentConfig = Schema.Struct({
57
+ experimental_subagent: Schema.optional(
58
+ Schema.Struct({ target: Schema.optional(Schema.Unknown) })
59
+ ),
60
+});
61
+const decodeExperimentalSubagentConfig = Schema.decodeUnknownSync(
62
+ Schema.parseJson(ExperimentalSubagentConfig)
63
+);
64
+const ProxySessionResponse = Schema.Struct({ session_id: Schema.NonEmptyString });
65
+const ProxyExecuteResponse = Schema.Struct({
66
+ headers: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.String })),
67
+ binary_data: Schema.optional(Schema.Struct({ url: Schema.optional(Schema.String) })),
68
+ data: Schema.optional(Schema.Unknown),
69
+ status: Schema.optional(Schema.Number),
70
+});
71
+type ProxyExecuteResponse = Schema.Schema.Type<typeof ProxyExecuteResponse>;
72
73
const experimentalSubAgentSchema = {
74
type: 'function',
110
logFilePath: { description: 'Path to the local run log file for helper execution details.' },
111
},
112
},
138
-} as const;
113
+};
114
115
const proxySchema = {
116
type: 'function',
140
},
141
},
142
},
168
-} as const;
169
-
170
-const runGlobals = globalThis as RunGlobalScope;
143
+};
144
145
const encodeBase64 = (bytes: Uint8Array): string => {
146
let binary = '';
150
return btoa(binary);
151
};
152
180
-// eslint-disable-next-line max-lines-per-function
181
-export const installRunHelpers = async ({
182
- cliPrefix,
183
- helperContext = {},
184
-}: RunHelpersInstallParams): Promise<void> => {
185
- runGlobals.z = z;
186
- runGlobals.zod = z;
153
+// ---------------------------------------------------------------------------
154
+// Pure helpers — no run-context captures, hoisted to module scope
155
+// ---------------------------------------------------------------------------
156
188
- const perfDebugEnabled =
189
- helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';
190
- const toolDebugEnabled =
191
- helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';
192
- const perfDebugStart = Date.now();
193
- let perfDebugSeq = 0;
194
- const executeId = () => crypto.randomUUID().slice(0, 8);
195
- const proxySessionCache = new Map<string, string>();
196
- const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(
197
- /\/$/,
198
- ''
199
- );
200
- const sharedRunOutputDir =
201
- typeof helperContext.runOutputDir === 'string' && helperContext.runOutputDir.length > 0
202
- ? helperContext.runOutputDir
203
- : null;
204
- const sharedRunLogFilePath =
205
- typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0
206
- ? helperContext.runLogFilePath
207
- : null;
157
+const executeId = () => crypto.randomUUID().slice(0, 8);
158
209
- const appendRunLogLine = (line: string) => {
210
- if (!sharedRunLogFilePath || line.length === 0) return;
211
- fs.appendFileSync(sharedRunLogFilePath, `${line}\n`, 'utf8');
212
- };
159
+const truncateDebugText = (value: unknown, max = 240) => {
160
+ const text = typeof value === 'string' ? value : String(value ?? '');
161
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
162
+};
163
214
- const perfDebugLog = (phase: string, label: string, details: Record<string, unknown> = {}) => {
215
- if (!perfDebugEnabled) return;
216
- const elapsedMs = Date.now() - perfDebugStart;
217
- const payload = { phase, label, elapsedMs, ...details };
218
- // eslint-disable-next-line no-console
219
- console.error(`[perf] ${JSON.stringify(payload)}`);
164
+const previewDebugValue = (value: unknown): string => {
165
+ if (value == null) return '';
166
+ if (typeof value === 'string') return truncateDebugText(value.replace(/\s+/g, ' ').trim());
167
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
168
+ if (Array.isArray(value)) return `array(${value.length})`;
169
+ if (Predicate.isRecord(value)) {
170
+ const preferred = ['message', 'error', 'title', 'summary', 'brief', 'status'];
171
+ for (const key of preferred) {
172
+ const candidate = value[key];
173
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
174
+ return truncateDebugText(candidate.trim());
175
+ }
176
+ }
177
+ return `object{${Object.keys(value).slice(0, 4).join(', ')}}`;
178
+ }
179
+ return truncateDebugText(String(value));
180
+};
181
+
182
+const formatHelperDebugEvent = (step: string, details: Record<string, unknown> = {}) => {
183
+ switch (step) {
184
+ case 'subAgent.target':
185
+ return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;
186
+ case 'subAgent.acp.resolve':
187
+ return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;
188
+ case 'subAgent.acp.initialized':
189
+ return `[experimental_subAgent] ACP initialized (${details.target})`;
190
+ case 'subAgent.acp.session':
191
+ return `[experimental_subAgent] session ready (${details.target})`;
192
+ case 'subAgent.acp.model':
193
+ return details.applied === true
194
+ ? `[experimental_subAgent] model=${details.model}`
195
+ : `[experimental_subAgent] model unchanged (${details.model})`;
196
+ case 'subAgent.acp.message': {
197
+ const text = previewDebugValue(details.text);
198
+ return text ? `[experimental_subAgent] ${text}` : null;
199
+ }
200
+ case 'subAgent.acp.thought': {
201
+ const text = previewDebugValue(details.text);
202
+ return text ? `[experimental_subAgent:thinking] ${text}` : null;
203
+ }
204
+ case 'subAgent.acp.tool_call': {
205
+ const locations = Array.isArray(details.locations) ? details.locations : [];
206
+ const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
207
+ return `[experimental_subAgent:tool] ${details.status || 'pending'} ${
208
+ details.title || details.kind || 'tool'
209
+ }${where}`;
210
+ }
211
+ case 'subAgent.acp.tool_call_update': {
212
+ const locations = Array.isArray(details.locations) ? details.locations : [];
213
+ const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
214
+ const preview = previewDebugValue(details.rawOutput);
215
+ return `[experimental_subAgent:tool] ${details.status || 'update'} ${
216
+ details.title || details.toolCallId || details.kind || 'tool'
217
+ }${where}${preview ? ` -> ${preview}` : ''}`;
218
+ }
219
+ case 'subAgent.acp.plan': {
220
+ const entries = Array.isArray(details.entries)
221
+ ? details.entries.filter(Predicate.isRecord)
222
+ : [];
223
+ if (entries.length === 0) return '[experimental_subAgent:plan] updated';
224
+ const summary = entries
225
+ .slice(0, 3)
226
+ .map(entry => {
227
+ const status = typeof entry.status === 'string' ? entry.status : 'pending';
228
+ const content = typeof entry.content === 'string' ? entry.content : '';
229
+ return `${status}:${truncateDebugText(content, 48)}`;
230
+ })
231
+ .join(' | ');
232
+ return `[experimental_subAgent:plan] ${summary}`;
233
+ }
234
+ case 'subAgent.acp.fallback':
235
+ return `[experimental_subAgent] ACP fallback (${details.code})`;
236
+ case 'execute.prepare':
237
+ return `[execute] ${details.slug}`;
238
+ case 'search.prepare':
239
+ return `[search] ${truncateDebugText(details.query || '', 96)}`;
240
+ case 'proxy.request':
241
+ return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || '', 96)}`;
242
+ case 'cli.result': {
243
+ const command = typeof details.command === 'string' ? details.command : 'cli';
244
+ const state = details.successful === false ? 'failed' : 'ok';
245
+ const preview = previewDebugValue(details.preview);
246
+ return `[${command}] ${state}${preview ? ` ${preview}` : ''}`;
247
+ }
248
+ case 'cli.error': {
249
+ const command = typeof details.command === 'string' ? details.command : 'cli';
250
+ const stderr = previewDebugValue(details.stderr);
251
+ return `[${command}] failed${stderr ? ` ${stderr}` : ''}`;
252
+ }
253
+ default:
254
+ return null;
255
+ }
256
+};
257
+
258
+const stringifyForPrompt = (value: unknown): string => {
259
+ if (value === undefined) return 'undefined';
260
+ if (value === null) return 'null';
261
+ if (typeof value === 'string') return value;
262
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
263
+ return String(value);
264
+ }
265
+ try {
266
+ return JSON.stringify(value, null, 2);
267
+ } catch {
268
+ return String(value);
269
+ }
270
+};
271
+
272
+const attachPromptMethod = <T>(value: T): T => {
273
+ if (!Predicate.isRecord(value)) return value;
274
+ if (typeof value.prompt === 'function') return value;
275
+ Object.defineProperty(value, 'prompt', {
276
+ value: () => stringifyForPrompt('data' in value ? value.data : value),
277
+ enumerable: false,
278
+ });
279
+ return value;
280
+};
281
+
282
+const isPlainObjectForExecute = Predicate.isRecord;
283
+
284
+const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {
285
+ if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';
286
+ const normalized = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';
287
+ const explicit: Record<string, string> = {
288
+ 'text/plain': 'txt',
289
+ 'application/json': 'json',
290
+ 'application/pdf': 'pdf',
291
+ 'image/jpeg': 'jpg',
292
+ 'image/png': 'png',
293
+ 'image/webp': 'webp',
294
+ 'image/gif': 'gif',
295
};
296
+ if (explicit[normalized]) return explicit[normalized];
297
+ const subtype = normalized.split('/')[1] || 'bin';
298
+ return subtype.includes('+') ? (subtype.split('+').pop() ?? 'bin') : subtype;
299
+};
300
222
- const truncateDebugText = (value: unknown, max = 240) => {
223
- const text = typeof value === 'string' ? value : String(value ?? '');
224
- return text.length > max ? `${text.slice(0, max - 1)}…` : text;
301
+const describeDebugValue = (value: unknown) => {
302
+ if (Array.isArray(value)) return { type: 'array', length: value.length };
303
+ if (Predicate.isRecord(value)) {
304
+ return { type: 'object', keys: Object.keys(value).slice(0, 20) };
305
+ }
306
+ return {
307
+ type: typeof value,
308
+ value: typeof value === 'string' ? value.slice(0, 200) : (value ?? null),
309
};
310
+};
311
227
- const previewDebugValue = (value: unknown): string => {
228
- if (value == null) return '';
229
- if (typeof value === 'string') return truncateDebugText(value.replace(/\s+/g, ' ').trim());
230
- if (typeof value === 'number' || typeof value === 'boolean') return String(value);
231
- if (Array.isArray(value)) return `array(${value.length})`;
232
- if (typeof value === 'object') {
233
- const record = value as Record<string, unknown>;
234
- const preferred = ['message', 'error', 'title', 'summary', 'brief', 'status'];
235
- for (const key of preferred) {
236
- if (typeof record[key] === 'string' && record[key].trim().length > 0) {
237
- return truncateDebugText(record[key].trim());
238
- }
312
+const summarizeCliResultPreview = (result: RunCliResult): unknown => {
313
+ if (!Predicate.isRecord(result)) return result;
314
+ if ('data' in result && result.data !== undefined) return result.data;
315
+ if (typeof result.error === 'string' && result.error.trim().length > 0)
316
+ return result.error.trim();
317
+ return result;
318
+};
319
+
320
+const readConfiguredExperimentalSubagentTarget = (): 'auto' | 'claude' | 'codex' => {
321
+ try {
322
+ const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');
323
+ const parsed = decodeExperimentalSubagentConfig(raw);
324
+ const target = parsed.experimental_subagent?.target;
325
+ return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';
326
+ } catch {
327
+ return 'auto';
328
+ }
329
+};
330
+
331
+const normalizeInvokeAgentOptions = (
332
+ options: Record<string, unknown> = {}
333
+): InvokeAgentNormalizedOptions => {
334
+ if (options == null || typeof options !== 'object' || Array.isArray(options)) {
335
+ throw new Error('experimental_subAgent() options must be an object when provided.');
336
+ }
337
+ if (options.schema !== undefined && options.jsonSchema !== undefined) {
338
+ throw new Error(
339
+ 'experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.'
340
+ );
341
+ }
342
+ const requestedTarget = options.target;
343
+ if (
344
+ requestedTarget !== undefined &&
345
+ requestedTarget !== 'claude' &&
346
+ requestedTarget !== 'codex' &&
347
+ requestedTarget !== 'user'
348
+ ) {
349
+ throw new Error(
350
+ 'experimental_subAgent() target must be "claude", "codex", or "user" when provided.'
351
+ );
352
+ }
353
+ const inputSchema = options.schema ?? options.jsonSchema;
354
+ let structuredSchema: Record<string, unknown> | undefined;
355
+ let zodSchema: z.ZodType | undefined;
356
+ if (inputSchema !== undefined) {
357
+ if (inputSchema instanceof z.ZodType) {
358
+ if (typeof z.toJSONSchema !== 'function') {
359
+ throw new Error(
360
+ 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
361
+ );
362
}
240
- return `object{${Object.keys(record).slice(0, 4).join(', ')}}`;
363
+ zodSchema = inputSchema;
364
+ const generatedSchema = z.toJSONSchema(inputSchema);
365
+ structuredSchema = Schema.decodeUnknownSync(JsonObject)(generatedSchema);
366
+ } else if (Predicate.isRecord(inputSchema)) {
367
+ structuredSchema = inputSchema;
368
+ } else {
369
+ throw new Error('experimental_subAgent() schema must be a Zod schema or JSON Schema object.');
370
}
242
- return truncateDebugText(String(value));
371
+ }
372
+ return {
373
+ ...(requestedTarget === undefined ? {} : { target: requestedTarget }),
374
+ ...(typeof options.model === 'string' ? { model: options.model } : {}),
375
+ ...(options.schema === undefined ? {} : { schema: options.schema }),
376
+ ...(options.jsonSchema === undefined ? {} : { jsonSchema: options.jsonSchema }),
377
+ ...(structuredSchema === undefined ? {} : { structuredSchema }),
378
+ ...(zodSchema === undefined ? {} : { zodSchema }),
379
};
380
+};
381
245
- const formatHelperDebugEvent = (step: string, details: Record<string, unknown> = {}) => {
246
- switch (step) {
247
- case 'subAgent.target':
248
- return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;
249
- case 'subAgent.acp.resolve':
250
- return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;
251
- case 'subAgent.acp.initialized':
252
- return `[experimental_subAgent] ACP initialized (${details.target})`;
253
- case 'subAgent.acp.session':
254
- return `[experimental_subAgent] session ready (${details.target})`;
255
- case 'subAgent.acp.model':
256
- return details.applied === true
257
- ? `[experimental_subAgent] model=${details.model}`
258
- : `[experimental_subAgent] model unchanged (${details.model})`;
259
- case 'subAgent.acp.message': {
260
- const text = previewDebugValue(details.text);
261
- return text ? `[experimental_subAgent] ${text}` : null;
262
- }
263
- case 'subAgent.acp.thought': {
264
- const text = previewDebugValue(details.text);
265
- return text ? `[experimental_subAgent:thinking] ${text}` : null;
266
- }
267
- case 'subAgent.acp.tool_call': {
268
- const locations = Array.isArray(details.locations) ? details.locations : [];
269
- const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
270
- return `[experimental_subAgent:tool] ${details.status || 'pending'} ${
271
- details.title || details.kind || 'tool'
272
- }${where}`;
273
- }
274
- case 'subAgent.acp.tool_call_update': {
275
- const locations = Array.isArray(details.locations) ? details.locations : [];
276
- const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
277
- const preview = previewDebugValue(details.rawOutput);
278
- return `[experimental_subAgent:tool] ${details.status || 'update'} ${
279
- details.title || details.toolCallId || details.kind || 'tool'
280
- }${where}${preview ? ` -> ${preview}` : ''}`;
281
- }
282
- case 'subAgent.acp.plan': {
283
- const entries = Array.isArray(details.entries)
284
- ? (details.entries as Array<{ status?: string; content?: string }>)
285
- : [];
286
- if (entries.length === 0) return '[experimental_subAgent:plan] updated';
287
- const summary = entries
288
- .slice(0, 3)
289
- .map(entry => `${entry.status}:${truncateDebugText(entry.content || '', 48)}`)
290
- .join(' | ');
291
- return `[experimental_subAgent:plan] ${summary}`;
292
- }
293
- case 'subAgent.acp.fallback':
294
- return `[experimental_subAgent] ACP fallback (${details.code})`;
295
- case 'execute.prepare':
296
- return `[execute] ${details.slug}`;
297
- case 'search.prepare':
298
- return `[search] ${truncateDebugText(details.query || '', 96)}`;
299
- case 'proxy.request':
300
- return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || '', 96)}`;
301
- case 'cli.result': {
302
- const command = typeof details.command === 'string' ? details.command : 'cli';
303
- const state = details.successful === false ? 'failed' : 'ok';
304
- const preview = previewDebugValue(details.preview);
305
- return `[${command}] ${state}${preview ? ` ${preview}` : ''}`;
306
- }
307
- case 'cli.error': {
308
- const command = typeof details.command === 'string' ? details.command : 'cli';
309
- const stderr = previewDebugValue(details.stderr);
310
- return `[${command}] failed${stderr ? ` ${stderr}` : ''}`;
311
- }
312
- default:
313
- return null;
314
- }
382
+const normalizeProxyToolkit = (toolkit: string) => {
383
+ if (typeof toolkit !== 'string' || toolkit.trim().length === 0) {
384
+ throw new Error('proxy() requires a non-empty toolkit string.');
385
+ }
386
+ return toolkit.trim();
387
+};
388
+
389
+const normalizeFetchHeaders = (headers: HeadersInit | undefined) => {
390
+ if (!headers) return [];
391
+ const normalized: Array<{ name: string; type: string; value: string }> = [];
392
+ new Headers(headers).forEach((value, name) => {
393
+ normalized.push({ name, type: 'header', value });
394
+ });
395
+ return normalized;
396
+};
397
+
398
+const normalizeFetchBody = async (body: unknown) => {
399
+ if (body === undefined || body === null) return undefined;
400
+ if (typeof body === 'string' || typeof body === 'number' || typeof body === 'boolean')
401
+ return body;
402
+ if (typeof Blob !== 'undefined' && body instanceof Blob) return await body.text();
403
+ if (body instanceof ArrayBuffer) return encodeBase64(new Uint8Array(body));
404
+ if (ArrayBuffer.isView(body)) {
405
+ return encodeBase64(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
406
+ }
407
+ return body;
408
+};
409
+
410
+const normalizeFetchInput = async (input: unknown, init: RequestInit = {}) => {
411
+ if (typeof Request !== 'undefined' && input instanceof Request) {
412
+ throw new Error(
413
+ 'proxy() does not support passing a Request instance yet. Pass a URL string and init instead.'
414
+ );
415
+ }
416
+ const endpoint = input instanceof URL ? input.toString() : input;
417
+ if (typeof endpoint !== 'string' || endpoint.trim().length === 0) {
418
+ throw new Error('proxy fetch requires a non-empty URL string or URL object.');
419
+ }
420
+ const method = typeof init.method === 'string' ? init.method.toUpperCase() : 'GET';
421
+ if (!['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {
422
+ throw new Error('proxy fetch only supports GET, POST, PUT, DELETE, PATCH.');
423
+ }
424
+ return {
425
+ endpoint: endpoint.trim(),
426
+ method,
427
+ parameters: normalizeFetchHeaders(init.headers),
428
+ body: await normalizeFetchBody(init.body),
429
+ };
430
+};
431
+
432
+const toProxyResponse = async (result: ProxyExecuteResponse) => {
433
+ const headers = new Headers(result?.headers || {});
434
+ if (result?.binary_data?.url) {
435
+ const binaryResponse = await fetch(result.binary_data.url);
436
+ binaryResponse.headers.forEach((value, key) => {
437
+ if (!headers.has(key)) headers.set(key, value);
438
+ });
439
+ return new Response(binaryResponse.body, {
440
+ status: result.status ?? binaryResponse.status,
441
+ headers,
442
+ });
443
+ }
444
+ if (result?.data === undefined || result?.data === null) {
445
+ return new Response(null, { status: result?.status ?? 200, headers });
446
+ }
447
+ if (typeof result.data === 'string') {
448
+ if (!headers.has('content-type')) headers.set('content-type', 'text/plain; charset=utf-8');
449
+ return new Response(result.data, { status: result.status ?? 200, headers });
450
+ }
451
+ if (!headers.has('content-type')) headers.set('content-type', 'application/json; charset=utf-8');
452
+ return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });
453
+};
454
+
455
+// ---------------------------------------------------------------------------
456
+// Helper factories — capture the per-run context passed by installRunHelpers
457
+// ---------------------------------------------------------------------------
458
+
459
+type RunHelperLoggers = {
460
+ readonly perfDebugLog: (phase: string, label: string, details?: Record<string, unknown>) => void;
461
+ readonly helperDebugLog: HelperDebugLog;
462
+};
463
+
464
+const createRunHelperLoggers = (params: {
465
+ readonly helperContext: RunHelperContext;
466
+ readonly writeError: (line: string) => void;
467
+ readonly sharedRunLogFilePath: string | null;
468
+ readonly perfDebugEnabled: boolean;
469
+ readonly perfDebugStart: number;
470
+}): RunHelperLoggers => {
471
+ const { helperContext, writeError, sharedRunLogFilePath, perfDebugEnabled, perfDebugStart } =
472
+ params;
473
+
474
+ const appendRunLogLine = (line: string) => {
475
+ if (!sharedRunLogFilePath || line.length === 0) return;
476
+ fs.appendFileSync(sharedRunLogFilePath, `${line}\n`, 'utf8');
477
+ };
478
+
479
+ const perfDebugLog = (phase: string, label: string, details: Record<string, unknown> = {}) => {
480
+ if (!perfDebugEnabled) return;
481
+ const elapsedMs = Date.now() - perfDebugStart;
482
+ const payload = { phase, label, elapsedMs, ...details };
483
+ writeError(`[perf] ${JSON.stringify(payload)}`);
484
};
485
486
const shouldStreamHelperLog = (step: string, formattedLine: string | null): boolean => {
489
return formattedLine !== null && (step.startsWith('subAgent.') || step.startsWith('agent.'));
490
};
491
323
- const helperDebugLog = (step: string, details: Record<string, unknown> = {}) => {
492
+ const helperDebugLog: HelperDebugLog = (step, details = {}) => {
493
const formattedLine = formatHelperDebugEvent(step, details);
494
const elapsedMs = Date.now() - perfDebugStart;
495
const line = formattedLine ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`;
496
appendRunLogLine(line);
497
if (shouldStreamHelperLog(step, formattedLine)) {
329
- // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
330
- process.stderr.write(`${line}\n`);
331
- }
332
- };
333
-
334
- const parseJson = (text: string): unknown => {
335
- const value = text.trim();
336
- if (!value) return undefined;
337
- try {
338
- return JSON.parse(value);
339
- } catch {
340
- return value;
341
- }
342
- };
343
-
344
- const stringifyForPrompt = (value: unknown): string => {
345
- if (value === undefined) return 'undefined';
346
- if (value === null) return 'null';
347
- if (typeof value === 'string') return value;
348
- if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
349
- return String(value);
350
- }
351
- try {
352
- return JSON.stringify(value, null, 2);
353
- } catch {
354
- return String(value);
498
+ writeError(line);
499
}
500
};
501
358
- const attachPromptMethod = <T>(value: T): T => {
359
- if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
360
- const promptable = value as PromptableResult;
361
- if (typeof promptable.prompt === 'function') return value;
362
- Object.defineProperty(promptable, 'prompt', {
363
- value: () => stringifyForPrompt('data' in promptable ? promptable.data : promptable),
364
- enumerable: false,
365
- });
366
- return value;
367
- };
502
+ return { perfDebugLog, helperDebugLog };
503
+};
504
369
- const isPlainObjectForExecute = (value: unknown): value is Record<string, unknown> =>
370
- typeof value === 'object' && value !== null && !Array.isArray(value);
371
-
372
- const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {
373
- if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';
374
- const normalized = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';
375
- const explicit: Record<string, string> = {
376
- 'text/plain': 'txt',
377
- 'application/json': 'json',
378
- 'application/pdf': 'pdf',
379
- 'image/jpeg': 'jpg',
380
- 'image/png': 'png',
381
- 'image/webp': 'webp',
382
- 'image/gif': 'gif',
383
- };
384
- if (explicit[normalized]) return explicit[normalized];
385
- const subtype = normalized.split('/')[1] || 'bin';
386
- return subtype.includes('+') ? (subtype.split('+').pop() ?? 'bin') : subtype;
387
- };
505
+const createExecutePayloadMaterializer = (params: {
506
+ readonly path: Path.Path;
507
+ readonly sharedRunOutputDir: string | null;
508
+}): ((value: unknown) => Promise<unknown>) => {
509
+ const { path, sharedRunOutputDir } = params;
510
511
const writeTempExecuteFile = async (value: unknown): Promise<unknown> => {
512
const outputDir = sharedRunOutputDir || path.join(os.tmpdir(), 'composio-run-files');
549
return value;
550
};
551
552
+ return materializeExecutePayload;
553
+};
554
+
555
+const createCliRunner = (params: {
556
+ readonly cliPrefix: ReadonlyArray<string>;
557
+ readonly helperContext: RunHelperContext;
558
+ readonly sharedRunOutputDir: string | null;
559
+ readonly perfDebugEnabled: boolean;
560
+ readonly toolDebugEnabled: boolean;
561
+ readonly loggers: RunHelperLoggers;
562
+}): ((args: ReadonlyArray<string>) => Promise<RunCliResult>) => {
563
+ const { cliPrefix, helperContext, sharedRunOutputDir, perfDebugEnabled, toolDebugEnabled } =
564
+ params;
565
+ const { perfDebugLog, helperDebugLog } = params.loggers;
566
+ let perfDebugSeq = 0;
567
+
568
const maybeLoadStoredCliResult = (result: RunCliResult): RunCliResult => {
431
- if (!result || typeof result !== 'object' || result.storedInFile !== true) {
569
+ if (!Predicate.isRecord(result) || result.storedInFile !== true) {
570
return attachPromptMethod(result);
571
}
572
helperDebugLog('cli.result.stored_in_file', {
583
});
584
};
585
448
- const describeDebugValue = (value: unknown) => {
449
- if (Array.isArray(value)) return { type: 'array', length: value.length };
450
- if (value && typeof value === 'object') {
451
- return { type: 'object', keys: Object.keys(value as Record<string, unknown>).slice(0, 20) };
452
- }
453
- return {
454
- type: typeof value,
455
- value: typeof value === 'string' ? value.slice(0, 200) : (value ?? null),
456
- };
457
- };
458
-
459
- const summarizeCliResultPreview = (result: RunCliResult): unknown => {
460
- if (result == null || typeof result !== 'object') return result;
461
- if ('data' in result && result.data !== undefined) return result.data;
462
- if (typeof result.error === 'string' && result.error.trim().length > 0)
463
- return result.error.trim();
464
- return result;
465
- };
466
-
586
const logCliResultPreview = (
587
requestId: string,
588
command: string | undefined,
589
result: RunCliResult
590
) => {
472
- if (!result || typeof result !== 'object') {
591
+ if (!Predicate.isRecord(result)) {
592
helperDebugLog('cli.result', {
593
requestId,
594
command,
610
});
611
};
612
494
- const detectInvokeAgentMaster = (): MasterKind | 'user' => {
495
- if (
496
- helperContext.master === 'claude' ||
497
- helperContext.master === 'codex' ||
498
- helperContext.master === 'user'
499
- ) {
500
- return helperContext.master;
501
- }
502
- const envKeys = Object.keys(process.env || {});
503
- if (envKeys.some(key => key.startsWith('CODEX_'))) return 'codex';
504
- if (envKeys.some(key => key.startsWith('CLAUDE_'))) return 'claude';
505
- return 'user';
506
- };
507
-
508
- const readConfiguredExperimentalSubagentTarget = (): 'auto' | 'claude' | 'codex' => {
509
- try {
510
- const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');
511
- const parsed = JSON.parse(raw) as {
512
- experimental_subagent?: { target?: unknown };
513
- };
514
- const target = parsed.experimental_subagent?.target;
515
- return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';
516
- } catch {
517
- return 'auto';
518
- }
519
- };
520
-
521
- const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {
522
- if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;
523
- const configuredTarget = readConfiguredExperimentalSubagentTarget();
524
- if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;
525
- const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();
526
- if (detected === 'codex' || detected === 'claude') return detected;
527
- if (typeof Bun.which === 'function' && Bun.which('codex')) return 'codex';
528
- if (typeof Bun.which === 'function' && Bun.which('claude')) return 'claude';
529
- throw new Error(
530
- 'experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: "codex" | "claude" }.'
531
- );
532
- };
533
-
534
- const normalizeInvokeAgentOptions = (
535
- options: Record<string, unknown> = {}
536
- ): NormalizedInvokeAgentOptions => {
537
- if (options == null || typeof options !== 'object' || Array.isArray(options)) {
538
- throw new Error('experimental_subAgent() options must be an object when provided.');
539
- }
540
- if (options.schema !== undefined && options.jsonSchema !== undefined) {
541
- throw new Error(
542
- 'experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.'
543
- );
544
- }
545
- const inputSchema = (options.schema ?? options.jsonSchema) as StructuredSchemaInput | undefined;
546
- let structuredSchema: Record<string, unknown> | undefined;
547
- let zodSchema: StructuredSchemaInput | undefined;
548
- if (inputSchema !== undefined) {
549
- if (
550
- typeof inputSchema === 'object' &&
551
- inputSchema !== null &&
552
- 'safeParse' in inputSchema &&
553
- typeof inputSchema.safeParse === 'function' &&
554
- '_def' in inputSchema
555
- ) {
556
- if (typeof z.toJSONSchema !== 'function') {
557
- throw new Error(
558
- 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
559
- );
560
- }
561
- zodSchema = inputSchema;
562
- structuredSchema = z.toJSONSchema(inputSchema as never) as Record<string, unknown>;
563
- } else if (
564
- typeof inputSchema === 'object' &&
565
- inputSchema !== null &&
566
- !Array.isArray(inputSchema)
567
- ) {
568
- structuredSchema = inputSchema;
569
- } else {
570
- throw new Error(
571
- 'experimental_subAgent() schema must be a Zod schema or JSON Schema object.'
572
- );
573
- }
574
- }
575
- return { ...options, structuredSchema, zodSchema };
576
- };
577
-
578
- const requireConsumerProxyContext = () => {
579
- if (!helperContext.apiKey) {
580
- throw new Error('proxy() requires an authenticated Composio user session.');
581
- }
582
- if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {
583
- throw new Error(
584
- 'proxy() requires a consumer project context so it can use the consumer project credentials.'
585
- );
586
- }
587
- return {
588
- apiKey: helperContext.apiKey,
589
- orgId: helperContext.orgId,
590
- projectId: helperContext.consumerProjectId,
591
- userId: helperContext.consumerUserId,
592
- };
593
- };
594
-
595
- const normalizeProxyToolkit = (toolkit: string) => {
596
- if (typeof toolkit !== 'string' || toolkit.trim().length === 0) {
597
- throw new Error('proxy() requires a non-empty toolkit string.');
598
- }
599
- return toolkit.trim();
600
- };
601
-
602
- const normalizeFetchHeaders = (headers: HeadersInit | undefined) => {
603
- if (!headers) return [];
604
- return [...(new Headers(headers) as unknown as Iterable<[string, string]>)].map(
605
- ([name, value]) => ({
606
- name,
607
- type: 'header',
608
- value,
609
- })
610
- );
611
- };
612
-
613
- const normalizeFetchBody = async (body: unknown) => {
614
- if (body === undefined || body === null) return undefined;
615
- if (typeof body === 'string' || typeof body === 'number' || typeof body === 'boolean')
616
- return body;
617
- if (typeof Blob !== 'undefined' && body instanceof Blob) return await body.text();
618
- if (body instanceof ArrayBuffer) return encodeBase64(new Uint8Array(body));
619
- if (ArrayBuffer.isView(body)) {
620
- return encodeBase64(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
621
- }
622
- return body;
623
- };
624
-
625
- const normalizeFetchInput = async (input: unknown, init: RequestInit = {}) => {
626
- if (typeof Request !== 'undefined' && input instanceof Request) {
627
- throw new Error(
628
- 'proxy() does not support passing a Request instance yet. Pass a URL string and init instead.'
629
- );
630
- }
631
- const endpoint = input instanceof URL ? input.toString() : input;
632
- if (typeof endpoint !== 'string' || endpoint.trim().length === 0) {
633
- throw new Error('proxy fetch requires a non-empty URL string or URL object.');
634
- }
635
- const method = typeof init.method === 'string' ? init.method.toUpperCase() : 'GET';
636
- if (!['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {
637
- throw new Error('proxy fetch only supports GET, POST, PUT, DELETE, PATCH.');
638
- }
639
- return {
640
- endpoint: endpoint.trim(),
641
- method,
642
- parameters: normalizeFetchHeaders(init.headers),
643
- body: await normalizeFetchBody(init.body),
644
- };
645
- };
646
-
647
- const fetchComposioJson = async (pathname: string, body: Record<string, unknown>) => {
648
- const auth = requireConsumerProxyContext();
649
- const response = await fetch(`${composioBaseURL}${pathname}`, {
650
- method: 'POST',
651
- headers: {
652
- 'content-type': 'application/json',
653
- 'x-user-api-key': auth.apiKey,
654
- 'x-org-id': auth.orgId,
655
- 'x-project-id': auth.projectId,
656
- },
657
- body: JSON.stringify(body),
658
- });
659
- const raw = await response.text();
660
- const parsed = parseJson(raw);
661
- if (!response.ok) {
662
- const detail =
663
- typeof parsed === 'string'
664
- ? parsed
665
- : (((parsed as { message?: string; error?: string } | undefined)?.message ||
666
- (parsed as { message?: string; error?: string } | undefined)?.error ||
667
- raw.trim()) ??
668
- undefined);
669
- const error = new Error(
670
- `Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ''}`
671
- );
672
- Object.assign(error, { status: response.status, response: parsed ?? raw });
673
- throw error;
674
- }
675
- return parsed;
676
- };
677
-
678
- const getProxySessionId = async (toolkit: string) => {
679
- const cached = proxySessionCache.get(toolkit);
680
- if (cached) return cached;
681
- const auth = requireConsumerProxyContext();
682
- const created = (await fetchComposioJson('/api/v3/tool_router/session', {
683
- user_id: auth.userId,
684
- manage_connections: { enable: false },
685
- toolkits: { enable: [toolkit] },
686
- })) as { session_id?: string };
687
- const sessionId = created?.session_id;
688
- if (typeof sessionId !== 'string' || sessionId.length === 0) {
689
- throw new Error('Composio proxy session creation returned no session_id.');
690
- }
691
- proxySessionCache.set(toolkit, sessionId);
692
- return sessionId;
693
- };
694
-
613
const runCliJson = async (args: ReadonlyArray<string>): Promise<RunCliResult> => {
614
const requestId = `${args[0] ?? 'cli'}#${++perfDebugSeq}`;
615
helperDebugLog('cli.start', { requestId, args });
698
- const env = {
616
+ const env: Record<string, string | undefined> = {
617
...process.env,
618
...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),
619
...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),
624
...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: '1' } : {}),
625
...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),
626
};
709
- delete (env as Record<string, string | undefined>).BUN_BE_BUN;
627
+ delete env.BUN_BE_BUN;
628
perfDebugLog('start', requestId, { cmd: args });
629
const child = Bun.spawn({
630
cmd: [...cliPrefix, ...args],
633
});
634
const stdout = child.stdout ? await new Response(child.stdout).text() : '';
635
const stderr = child.stderr ? await new Response(child.stderr).text() : '';
718
- const result = maybeLoadStoredCliResult(parseJson(stdout) as RunCliResult);
636
+ const result = maybeLoadStoredCliResult(parseJson(stdout));
637
const exitCode = await child.exited;
638
if (exitCode !== 0) {
639
perfDebugLog('error', requestId, { exitCode, stderr: stderr.trim() || undefined });
672
return result;
673
};
674
757
- runGlobals.search = async (query, options = {}) => {
675
+ return runCliJson;
676
+};
677
+
678
+const createSearchAndExecuteHelpers = (params: {
679
+ readonly helperContext: RunHelperContext;
680
+ readonly sharedRunOutputDir: string | null;
681
+ readonly runCliJson: (args: ReadonlyArray<string>) => Promise<RunCliResult>;
682
+ readonly materializeExecutePayload: (value: unknown) => Promise<unknown>;
683
+ readonly helperDebugLog: HelperDebugLog;
684
+}) => {
685
+ const {
686
+ helperContext,
687
+ sharedRunOutputDir,
688
+ runCliJson,
689
+ materializeExecutePayload,
690
+ helperDebugLog,
691
+ } = params;
692
+
693
+ const search = async (
694
+ query: string,
695
+ options: Record<string, unknown> = {}
696
+ ): Promise<RunCliResult> => {
697
helperDebugLog('search.prepare', { query, options });
698
const args = ['search', query];
699
if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {
707
return runCliJson(args);
708
};
709
771
- runGlobals.execute = async (slug, data = {}, options = {}) => {
710
+ const execute = async (
711
+ slug: string,
712
+ data: unknown = {},
713
+ options: { account?: string } = {}
714
+ ): Promise<RunCliResult> => {
715
helperDebugLog('execute.prepare', {
716
slug,
717
hasData: data !== undefined,
738
}
739
}
740
const result = await runCliJson(args);
798
- if (result && typeof result === 'object' && result.successful === false) {
741
+ if (Predicate.isRecord(result) && result.successful === false) {
742
const message =
743
typeof result.error === 'string' && result.error.trim().length > 0
744
? result.error.trim()
750
return result;
751
};
752
753
+ return { search, execute };
754
+};
755
+
756
+const createExperimentalSubAgent = (params: {
757
+ readonly helperContext: RunHelperContext;
758
+ readonly helperDebugLog: HelperDebugLog;
759
+}) => {
760
+ const { helperContext, helperDebugLog } = params;
761
+
762
+ const detectInvokeAgentMaster = (): MasterKind | 'user' => {
763
+ if (
764
+ helperContext.master === 'claude' ||
765
+ helperContext.master === 'codex' ||
766
+ helperContext.master === 'user'
767
+ ) {
768
+ return helperContext.master;
769
+ }
770
+ return detectMaster();
771
+ };
772
+
773
+ const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {
774
+ if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;
775
+ const configuredTarget = readConfiguredExperimentalSubagentTarget();
776
+ if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;
777
+ const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();
778
+ if (detected === 'codex' || detected === 'claude') return detected;
779
+ if (typeof Bun.which === 'function' && Bun.which('codex')) return 'codex';
780
+ if (typeof Bun.which === 'function' && Bun.which('claude')) return 'claude';
781
+ throw new Error(
782
+ 'experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: "codex" | "claude" }.'
783
+ );
784
+ };
785
+
786
const experimentalSubAgentImpl = async (
787
prompt: string,
788
options: Record<string, unknown> = {}
805
try {
806
const response = await invokeAcpSubAgent({
807
prompt: prompt.trim(),
832
- options:
833
- normalizedOptions as import('src/services/run-subagent-shared').InvokeAgentNormalizedOptions,
808
+ options: normalizedOptions,
809
master,
810
target,
811
allowedReadRoots: Array.isArray(helperContext.readAccessRoots)
824
});
825
const response = await invokeLegacySubAgent({
826
prompt: prompt.trim(),
852
- options:
853
- normalizedOptions as import('src/services/run-subagent-shared').InvokeAgentNormalizedOptions,
827
+ options: normalizedOptions,
828
master,
829
target,
830
helperDebugLog,
833
}
834
};
835
862
- runGlobals.experimental_subAgent = experimentalSubAgentImpl;
863
- Object.defineProperty(runGlobals.experimental_subAgent, 'schema', {
864
- value: experimentalSubAgentSchema,
865
- });
866
- runGlobals.invokeAgent = experimentalSubAgentImpl;
867
- Object.defineProperty(runGlobals.invokeAgent, 'schema', { value: experimentalSubAgentSchema });
868
-
869
- const toProxyResponse = async (result: {
870
- readonly headers?: Record<string, string>;
871
- readonly binary_data?: { readonly url?: string };
872
- readonly data?: unknown;
873
- readonly status?: number;
874
- }) => {
875
- const headers = new Headers(result?.headers || {});
876
- if (result?.binary_data?.url) {
877
- const binaryResponse = await fetch(result.binary_data.url);
878
- binaryResponse.headers.forEach((value, key) => {
879
- if (!headers.has(key)) headers.set(key, value);
880
- });
881
- return new Response(binaryResponse.body, {
882
- status: result.status ?? binaryResponse.status,
883
- headers,
884
- });
836
+ Object.defineProperty(experimentalSubAgentImpl, 'schema', { value: experimentalSubAgentSchema });
837
+ return experimentalSubAgentImpl;
838
+};
839
+
840
+const createProxyHelper = (params: {
841
+ readonly helperContext: RunHelperContext;
842
+ readonly composioBaseURL: string;
843
+ readonly helperDebugLog: HelperDebugLog;
844
+}) => {
845
+ const { helperContext, composioBaseURL, helperDebugLog } = params;
846
+ const proxySessionCache = new Map<string, string>();
847
+
848
+ const requireConsumerProxyContext = () => {
849
+ if (!helperContext.apiKey) {
850
+ throw new Error('proxy() requires an authenticated Composio user session.');
851
}
886
- if (result?.data === undefined || result?.data === null) {
887
- return new Response(null, { status: result?.status ?? 200, headers });
852
+ if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {
853
+ throw new Error(
854
+ 'proxy() requires a consumer project context so it can use the consumer project credentials.'
855
+ );
856
}
889
- if (typeof result.data === 'string') {
890
- if (!headers.has('content-type')) headers.set('content-type', 'text/plain; charset=utf-8');
891
- return new Response(result.data, { status: result.status ?? 200, headers });
857
+ return {
858
+ apiKey: helperContext.apiKey,
859
+ orgId: helperContext.orgId,
860
+ projectId: helperContext.consumerProjectId,
861
+ userId: helperContext.consumerUserId,
862
+ };
863
+ };
864
+
865
+ const fetchComposioJson = async (pathname: string, body: Record<string, unknown>) => {
866
+ const auth = requireConsumerProxyContext();
867
+ const response = await fetch(`${composioBaseURL}${pathname}`, {
868
+ method: 'POST',
869
+ headers: {
870
+ 'content-type': 'application/json',
871
+ 'x-user-api-key': auth.apiKey,
872
+ 'x-org-id': auth.orgId,
873
+ 'x-project-id': auth.projectId,
874
+ },
875
+ body: JSON.stringify(body),
876
+ });
877
+ const raw = await response.text();
878
+ const parsed = parseJson(raw);
879
+ if (!response.ok) {
880
+ const responseMessage = Predicate.isRecord(parsed) ? parsed.message : undefined;
881
+ const responseError = Predicate.isRecord(parsed) ? parsed.error : undefined;
882
+ const detail =
883
+ typeof parsed === 'string'
884
+ ? parsed
885
+ : typeof responseMessage === 'string'
886
+ ? responseMessage
887
+ : typeof responseError === 'string'
888
+ ? responseError
889
+ : raw.trim() || undefined;
890
+ const error = new Error(
891
+ `Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ''}`
892
+ );
893
+ Object.assign(error, { status: response.status, response: parsed ?? raw });
894
+ throw error;
895
}
893
- if (!headers.has('content-type'))
894
- headers.set('content-type', 'application/json; charset=utf-8');
895
- return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });
896
+ return parsed;
897
+ };
898
+
899
+ const getProxySessionId = async (toolkit: string) => {
900
+ const cached = proxySessionCache.get(toolkit);
901
+ if (cached) return cached;
902
+ const auth = requireConsumerProxyContext();
903
+ const created = await Schema.decodeUnknownPromise(ProxySessionResponse)(
904
+ await fetchComposioJson('/api/v3/tool_router/session', {
905
+ user_id: auth.userId,
906
+ manage_connections: { enable: false },
907
+ toolkits: { enable: [toolkit] },
908
+ })
909
+ );
910
+ const sessionId = created.session_id;
911
+ proxySessionCache.set(toolkit, sessionId);
912
+ return sessionId;
913
};
914
898
- runGlobals.proxy = async (toolkit: string) => {
915
+ const proxy = async (toolkit: string) => {
916
const normalizedToolkit = normalizeProxyToolkit(toolkit);
917
helperDebugLog('proxy.session', {
918
toolkit: normalizedToolkit,
926
method: request.method,
927
endpoint: request.endpoint,
928
});
912
- const result = (await fetchComposioJson(
913
- `/api/v3/tool_router/session/${sessionId}/proxy_execute`,
914
- {
929
+ const result = await Schema.decodeUnknownPromise(ProxyExecuteResponse)(
930
+ await fetchComposioJson(`/api/v3/tool_router/session/${sessionId}/proxy_execute`, {
931
toolkit_slug: normalizedToolkit,
932
endpoint: request.endpoint,
933
method: request.method,
934
...(request.body !== undefined ? { body: request.body } : {}),
935
...(request.parameters.length > 0
936
? {
921
- parameters: request.parameters.map(
922
- (parameter: { name: string; type: string; value: string }) => ({
923
- name: parameter.name,
924
- type: parameter.type,
925
- value: String(parameter.value),
926
- })
927
- ),
937
+ parameters: request.parameters.map(parameter => ({
938
+ name: parameter.name,
939
+ type: parameter.type,
940
+ value: String(parameter.value),
941
+ })),
942
}
943
: {}),
930
- }
931
- )) as {
932
- readonly headers?: Record<string, string>;
933
- readonly binary_data?: { readonly url?: string };
934
- readonly data?: unknown;
935
- readonly status?: number;
936
- };
944
+ })
945
+ );
946
return toProxyResponse(result);
947
};
948
Object.defineProperty(proxyFetch, 'toolkit', { value: normalizedToolkit });
949
return proxyFetch;
950
};
942
- Object.defineProperty(runGlobals.proxy, 'schema', { value: proxySchema });
951
944
- Object.defineProperty(runGlobals, '__composioRunContext', {
952
+ Object.defineProperty(proxy, 'schema', { value: proxySchema });
953
+ return proxy;
954
+};
955
+
956
+export const installRunHelpers = async ({
957
+ cliPrefix,
958
+ helperContext = {},
959
+}: RunHelpersInstallParams): Promise<void> => {
960
+ // This preload runs in the user's child process, outside the CLI runtime.
961
+ // Resolve the live services once at that boundary and keep all writes centralized.
962
+ const terminal = Effect.runSync(TerminalUI.pipe(Effect.provide(TerminalUILive)));
963
+ const path = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));
964
+ const writeError = (line: string) => Effect.runSync(terminal.error(line));
965
+
966
+ Reflect.set(globalThis, 'z', z);
967
+ Reflect.set(globalThis, 'zod', z);
968
+
969
+ const perfDebugEnabled =
970
+ helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';
971
+ const toolDebugEnabled =
972
+ helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';
973
+ const perfDebugStart = Date.now();
974
+ const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(
975
+ /\/$/,
976
+ ''
977
+ );
978
+ const sharedRunOutputDir =
979
+ typeof helperContext.runOutputDir === 'string' && helperContext.runOutputDir.length > 0
980
+ ? helperContext.runOutputDir
981
+ : null;
982
+ const sharedRunLogFilePath =
983
+ typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0
984
+ ? helperContext.runLogFilePath
985
+ : null;
986
+
987
+ const loggers = createRunHelperLoggers({
988
+ helperContext,
989
+ writeError,
990
+ sharedRunLogFilePath,
991
+ perfDebugEnabled,
992
+ perfDebugStart,
993
+ });
994
+ const { helperDebugLog } = loggers;
995
+
996
+ const materializeExecutePayload = createExecutePayloadMaterializer({
997
+ path,
998
+ sharedRunOutputDir,
999
+ });
1000
+ const runCliJson = createCliRunner({
1001
+ cliPrefix,
1002
+ helperContext,
1003
+ sharedRunOutputDir,
1004
+ perfDebugEnabled,
1005
+ toolDebugEnabled,
1006
+ loggers,
1007
+ });
1008
+ const { search, execute } = createSearchAndExecuteHelpers({
1009
+ helperContext,
1010
+ sharedRunOutputDir,
1011
+ runCliJson,
1012
+ materializeExecutePayload,
1013
+ helperDebugLog,
1014
+ });
1015
+
1016
+ const experimentalSubAgentImpl = createExperimentalSubAgent({ helperContext, helperDebugLog });
1017
+ Reflect.set(globalThis, 'experimental_subAgent', experimentalSubAgentImpl);
1018
+ Reflect.set(globalThis, 'invokeAgent', experimentalSubAgentImpl);
1019
+
1020
+ const proxy = createProxyHelper({ helperContext, composioBaseURL, helperDebugLog });
1021
+
1022
+ Reflect.set(globalThis, 'search', search);
1023
+ Reflect.set(globalThis, 'execute', execute);
1024
+ Reflect.set(globalThis, 'proxy', proxy);
1025
+
1026
+ Object.defineProperty(globalThis, '__composioRunContext', {
1027
value: Object.freeze({
1028
outputDir: sharedRunOutputDir,
1029
logFilePath: sharedRunLogFilePath,
1031
configurable: true,
1032
});
1033
952
- Object.defineProperty(runGlobals, '__composioConsumerContext', {
1034
+ Object.defineProperty(globalThis, '__composioConsumerContext', {
1035
value: helperContext,
1036
configurable: true,
1037
});