1
-import { withCommandMeta } from 'src/invocation/command-identity';
2
-import { Argument, Command, Flag } from 'effect/cli';
3
-import { Data, Effect, Result, Option, Runtime } from 'effect';
4
-import type {
5
- SessionProxyExecuteParams,
6
- SessionProxyExecuteResponse,
7
-} from '@composio/client/resources/tool-router/session';
8
-import { requestError } from 'src/effects/request-error';
9
-import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
10
-import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
11
-import { gateToolExecution } from 'src/services/tool-permissions';
12
-import {
13
- getFreshConsumerConnectedToolkitsFromCache,
14
- refreshConsumerConnectedToolkitsCache,
15
-} from 'src/services/consumer-short-term-cache';
16
-import { TerminalUI } from 'src/services/terminal-ui';
17
-import { ComposioClientSingleton } from 'src/services/composio-clients';
18
-import { actingUser } from 'src/commands/surface';
19
-import {
20
- ComposioNoActiveConnectionError,
21
- mapComposioError,
22
-} from 'src/services/composio-error-overrides';
23
-import { parseJsonRecord } from 'src/utils/parse-json';
24
-import { toolInputRequiredError } from 'src/utils/tool-input-required';
25
-import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
26
-
27
-const endpoint = Argument.String('url').pipe(
28
- Argument.withDescription('Absolute or relative API endpoint to call through proxy execute.')
29
-);
30
-
31
-const toolkit = Flag.String('toolkit').pipe(
32
- Flag.withAlias('t'),
33
- Flag.withDescription('Toolkit slug whose connected account should be used')
34
-);
35
-
36
-const account = Flag.String('account').pipe(
37
- Flag.withDescription(
38
- 'Connected account selector. Matches alias, word_id, or connected account id for the toolkit.'
39
- ),
40
- Flag.optional
41
-);
42
-
43
-const method = Flag.String('method').pipe(
44
- Flag.withAlias('X'),
45
- Flag.withDefault('GET'),
46
- Flag.withDescription('HTTP method, curl-style (GET, POST, PUT, DELETE, PATCH)')
47
-);
48
-
49
-const headers = Flag.String('header').pipe(
50
- Flag.withAlias('H'),
51
- Flag.withDescription('Header in "Name: value" format. Repeat for multiple headers.'),
52
- Flag.atLeast(0)
53
-);
54
-
55
-const data = Flag.String('data').pipe(
56
- Flag.withAlias('d'),
57
- Flag.withDescription('Request body as raw text, JSON, @file, or - for stdin'),
58
- Flag.optional
59
-);
60
-
61
-const skipConnectionCheck = Flag.Boolean('skip-connection-check').pipe(
62
- Flag.withDefault(false),
63
- Flag.withDescription(
64
- 'Skip the short-lived connected-account fail-fast check if you just connected an account'
65
- )
66
-);
67
-
68
-type ProxyMethod = Extract<
69
- SessionProxyExecuteParams['method'],
70
- 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
71
->;
72
-
73
-const SUPPORTED_PROXY_METHODS: ReadonlyArray<ProxyMethod> = [
74
- 'GET',
75
- 'POST',
76
- 'PUT',
77
- 'DELETE',
78
- 'PATCH',
79
-];
80
-
81
-/**
82
- * A proxy call refused before sending it because the toolkit is not connected, already reported
83
- * on stderr and as `{ "successful": false, ... }` on stdout. The runtime prints nothing more
84
- * (`[Runtime.errorReported]` is false) and exits 1.
85
- */
86
-export class ReportedProxyCommandError extends Data.TaggedError(
87
- 'commands/ReportedProxyCommandError'
88
-)<{
89
- readonly message: string;
90
- readonly toolkit: string;
91
- readonly endpoint: string;
92
-}> {
93
- get [Runtime.errorReported]() {
94
- return false;
95
- }
96
-
97
- get [Runtime.errorExitCode]() {
98
- return 1;
99
- }
100
-}
101
-
102
-class ProxyRequestError extends requestError('commands/ProxyRequestError') {}
103
-
104
-export const normalizeProxyMethod = (value: string): ProxyMethod => {
105
- const normalized = value.trim().toUpperCase();
106
- const supported = SUPPORTED_PROXY_METHODS.find(method => method === normalized);
107
- if (!supported) {
108
- throw new Error('Unsupported method. Use one of GET, POST, PUT, DELETE, PATCH.');
109
- }
110
- return supported;
111
-};
112
-
113
-export const parseProxyHeader = (value: string): { name: string; value: string } => {
114
- const idx = value.indexOf(':');
115
- if (idx <= 0) {
116
- throw new Error(`Invalid header "${value}". Use "Name: value".`);
117
- }
118
-
119
- const name = value.slice(0, idx).trim();
120
- const headerValue = value.slice(idx + 1).trim();
121
- if (!name) {
122
- throw new Error(`Invalid header "${value}". Missing header name.`);
123
- }
124
- return { name, value: headerValue };
125
-};
126
-
127
-const resolveBodyInput = (input: Option.Option<string>) => resolveOptionalTextInput(input);
128
-
129
-export const parseProxyBody = (raw: string): unknown =>
130
- Result.getOrElse(parseJsonRecord(raw), (): unknown => raw);
131
-
132
-const formatProxyOutput = (
133
- result: Pick<
134
- Extract<SessionProxyExecuteResponse, { result_type: 'completed' }>,
135
- 'status' | 'data' | 'headers' | 'binary_data'
136
- >
137
-) => {
138
- if (result.binary_data) {
139
- return JSON.stringify(
140
- {
141
- status: result.status ?? null,
142
- headers: result.headers ?? {},
143
- binary_data: result.binary_data,
144
- },
145
- null,
146
- 2
147
- );
148
- }
149
-
150
- if (typeof result.data === 'string') {
151
- return result.data;
152
- }
153
-
154
- if (result.data === undefined || result.data === null) {
155
- return '';
156
- }
157
-
158
- return JSON.stringify(result.data, null, 2);
159
-};
160
-
161
-const formatProxyErrorOutput = (params: {
162
- readonly error: string;
163
- readonly toolkit: string;
164
- readonly endpoint: string;
165
- readonly slug?: string;
166
-}) =>
167
- JSON.stringify(
168
- {
169
- successful: false,
170
- error: params.error,
171
- toolkit: params.toolkit,
172
- endpoint: params.endpoint,
173
- slug: params.slug ?? null,
174
- },
175
- null,
176
- 2
177
- );
178
-
179
-const handleProxyExecutionError = (params: {
180
- readonly ui: TerminalUI;
181
- readonly error: unknown;
182
- readonly toolkit: string;
183
- readonly endpoint: string;
184
-}) =>
185
- Effect.gen(function* () {
186
- const mapped = mapComposioError({
187
- error: params.error,
188
- toolkit: params.toolkit,
189
- });
190
-
191
- if (mapped.normalized instanceof ComposioNoActiveConnectionError) {
192
- yield* params.ui.log.error(mapped.message);
193
- yield* params.ui.note(
194
- [
195
- `Link the toolkit first: composio link ${params.toolkit}`,
196
- 'Then retry the proxy call.',
197
- ].join('\n'),
198
- 'Tips'
199
- );
200
- } else {
201
- yield* params.ui.log.error(mapped.message);
202
- }
203
- const output = formatProxyErrorOutput({
204
- error: mapped.message,
205
- toolkit: params.toolkit,
206
- endpoint: params.endpoint,
207
- slug: mapped.slugValue,
208
- });
209
- yield* params.ui.output(output);
210
- return yield* Effect.fail(mapped.normalized);
211
- });
212
-
213
-const runProxyConnectedToolkitFailFast = (params: {
214
- readonly toolkit: string;
215
- readonly ui: TerminalUI;
216
- readonly resolvedProject: {
217
- readonly projectType: 'CONSUMER' | 'DEVELOPER';
218
- readonly orgId: string;
219
- };
220
- readonly resolvedUserId: string;
221
- readonly endpoint: string;
222
- readonly skipConnectionCheck: boolean;
223
-}) =>
224
- Effect.gen(function* () {
225
- if (params.skipConnectionCheck) return;
226
- if (params.resolvedProject.projectType !== 'CONSUMER') return;
227
-
228
- yield* refreshConsumerConnectedToolkitsCache({
229
- orgId: params.resolvedProject.orgId,
230
- consumerUserId: params.resolvedUserId,
231
- }).pipe(
232
- Effect.catch(() => Effect.void),
233
- Effect.forkDetach,
234
- Effect.asVoid
235
- );
236
-
237
- const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
238
- orgId: params.resolvedProject.orgId,
239
- consumerUserId: params.resolvedUserId,
240
- });
241
-
242
- if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(params.toolkit)) {
243
- const message = `Toolkit "${params.toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`;
244
- yield* params.ui.log.error(message);
245
- yield* params.ui.note(
246
- [
247
- `Link the toolkit first: composio link ${params.toolkit}`,
248
- 'Then retry the proxy call.',
249
- ].join('\n'),
250
- 'Tips'
251
- );
252
- yield* params.ui.output(
253
- JSON.stringify(
254
- {
255
- successful: false,
256
- error: message,
257
- toolkit: params.toolkit,
258
- endpoint: params.endpoint,
259
- },
260
- null,
261
- 2
262
- )
263
- );
264
- return yield* new ReportedProxyCommandError({
265
- message,
266
- toolkit: params.toolkit,
267
- endpoint: params.endpoint,
268
- });
269
- }
270
- });
271
-
272
-export const proxyCmd = Command.make('proxy', {
273
- endpoint,
274
- toolkit,
275
- account,
276
- method,
277
- headers,
278
- data,
279
- skipConnectionCheck,
280
-}).pipe(
281
- Command.withDescription(
282
- 'curl-like access to any toolkit API through Composio using your connected account.\nComposio handles authentication — just provide the full URL and toolkit.'
283
- ),
284
- Command.withShortDescription(
285
- 'curl-like access to any toolkit API through Composio using your connected account.'
286
- ),
287
- Command.withExamples([
288
- {
289
- command:
290
- 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail --account work',
291
- },
292
- {
293
- command:
294
- 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\\n -X POST -H \'content-type: application/json\' -d \'{"message":{"raw":"..."}}\'',
295
- },
296
- ]),
297
- Command.withHandler(options =>
298
- Effect.gen(function* () {
299
- const { endpoint, toolkit, account, method, headers, data, skipConnectionCheck } = options;
300
- const ui = yield* TerminalUI;
301
- const clientSingleton = yield* ComposioClientSingleton;
302
- const { userId: consumerUserId, project: resolvedProject } = yield* actingUser();
303
- const normalizedToolkit = toolkit.toLowerCase();
304
-
305
- yield* runProxyConnectedToolkitFailFast({
306
- toolkit: normalizedToolkit,
307
- ui,
308
- resolvedProject,
309
- resolvedUserId: consumerUserId,
310
- endpoint,
311
- skipConnectionCheck,
312
- });
313
-
314
- const normalizedMethod = normalizeProxyMethod(method);
315
- const headerParameters: NonNullable<SessionProxyExecuteParams['parameters']> = headers.map(
316
- header => {
317
- const parsed = parseProxyHeader(header);
318
- return {
319
- name: parsed.name,
320
- type: 'header',
321
- value: parsed.value,
322
- };
323
- }
324
- );
325
- const rawBody = yield* resolveBodyInput(data);
326
- const parsedBody = rawBody === undefined ? undefined : parseProxyBody(rawBody);
327
-
328
- const result = yield* ui.withSpinner(
329
- `Proxying ${normalizedMethod} ${endpoint} via ${normalizedToolkit}...`,
330
- Effect.gen(function* () {
331
- const client = yield* clientSingleton.getFor({
332
- orgId: resolvedProject.orgId,
333
- projectId: resolvedProject.projectId,
334
- });
335
- // Always resolve through here, even with no --account: this is what
336
- // makes the "multiple accounts, none aliased default" case fail
337
- // loudly instead of resolveToolRouterSession silently picking one
338
- // via resolveDefaultConnectedAccountsByToolkit.
339
- const selectedConnectedAccountId = yield* resolveConnectedAccountForToolkit({
340
- client,
341
- toolkitSlug: normalizedToolkit,
342
- userId: consumerUserId,
343
- selector: account,
344
- });
345
- const { sessionId, permissionSnapshot, connectedAccounts, connectedAccountWordIds } =
346
- yield* resolveToolRouterSession(client, consumerUserId, {
347
- toolkits: [normalizedToolkit],
348
- connectedAccounts: selectedConnectedAccountId
349
- ? { [normalizedToolkit]: selectedConnectedAccountId }
350
- : undefined,
351
- cacheScope: {
352
- orgId: resolvedProject.orgId,
353
- projectId: resolvedProject.projectId,
354
- consumerUserId,
355
- },
356
- });
357
-
358
- // Same consumer permission gate as `composio execute`, checked against
359
- // the account the session will use (explicit `--account` or default).
360
- yield* gateToolExecution({
361
- toolSlug: normalizedToolkit,
362
- connectedAccountId: connectedAccounts?.[normalizedToolkit],
363
- connectedAccountWordId: connectedAccountWordIds?.[normalizedToolkit],
364
- snapshot: permissionSnapshot,
365
- });
366
-
367
- const failed = (cause: unknown) =>
368
- new ProxyRequestError({
369
- message: `Failed to proxy ${normalizedMethod} ${endpoint} via "${normalizedToolkit}".`,
370
- cause,
371
- });
372
-
373
- return yield* client.toolRouter.session
374
- .proxyExecute(
375
- sessionId,
376
- {
377
- toolkit_slug: normalizedToolkit,
378
- endpoint,
379
- method: normalizedMethod,
380
- ...(parsedBody !== undefined ? { body: parsedBody } : {}),
381
- ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),
382
- }
383
- // A proxied call is not `idempotent`, so it is sent once: a retry
384
- // after the upstream API already acted duplicates the side
385
- // effect. The response is not validated either, for the same
386
- // reason.
387
- )
388
- .pipe(
389
- Effect.mapError(failed),
390
- Effect.flatMap(response => {
391
- if (response.result_type === 'input_required') {
392
- return Effect.fail(
393
- failed(
394
- toolInputRequiredError(
395
- `${normalizedMethod} proxy call via "${normalizedToolkit}"`,
396
- response
397
- )
398
- )
399
- );
400
- }
401
- // A session hook blocked the request: there is no HTTP
402
- // response to print, only the hook's message.
403
- if (response.result_type === 'blocked') {
404
- return Effect.fail(
405
- new ProxyRequestError({
406
- message: `${normalizedMethod} proxy call via "${normalizedToolkit}" was blocked by session hook "${response.reason.hook_id}": ${response.message}`,
407
- cause: response.reason,
408
- })
409
- );
410
- }
411
- return Effect.succeed(response);
412
- }),
413
- Effect.matchEffect({
414
- onFailure: error =>
415
- handleProxyExecutionError({
416
- ui,
417
- error,
418
- toolkit: normalizedToolkit,
419
- endpoint,
420
- }),
421
- onSuccess: Effect.succeed,
422
- })
423
- );
424
- })
425
- );
426
-
427
- const output = formatProxyOutput(result);
428
- yield* ui.log.info(`Status: ${String(result.status ?? 'unknown')}`);
429
- if (output) {
430
- yield* ui.note(output, 'Proxy Response');
431
- yield* ui.output(output);
432
- }
433
- })
434
- ),
435
- withCommandMeta({ requiresLogin: true })
436
-);