@devries-cameron20 / composio Mirror · read-only / commits / 332b1f315
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 07:15 UTC

refactor(cli): move `proxy` into the directory shape (#5138)

This PR: - targets `next`, now that https://github.com/ComposioHQ/composio/pull/5136 has landed there - splits `proxy.cmd.ts` into `proxy/proxy.{cmd,handler,format,errors}.ts`. It is a pure move: flags, description, examples, error classes and tags, messages, stdout JSON and telemetry stay the same - `proxy.cmd.ts` keeps the surface and `withCommandMeta({ requiresLogin: true })` and passes `runProxy` to the three-argument `Command.make`. `runProxy` takes a `ProxyParams` type it declares itself - the two inline stdout renderers move to `proxy.format.ts`. The not-connected JSON that was built inline is now `formatProxyNotConnectedOutput`, and it prints the same bytes - `ProxyRequestError` is now exported from `proxy.errors.ts` so the handler can use it. Its class name and tag stay the same - moves both test suites to `test/src/commands/proxy/` and updates the imports in `errors.test.ts` and `index.ts`. `COMMANDS.md` is regenerated with `commands:map` - includes the acting-user changes from #5127 and #5130 that landed on the old `proxy.cmd.ts`: `runProxy` resolves the user with `actingUser()`, and `ProxyCommandError` is gone from `proxy.errors.ts` because `MissingActingUserError` replaces it. `proxy` imports nothing from `tools.execute.cmd.ts`, and that file imports nothing from `proxy` | Old | New | | --- | --- | | `src/commands/proxy.cmd.ts` | `src/commands/proxy/proxy.cmd.ts`, `proxy.handler.ts`, `proxy.format.ts`, `proxy.errors.ts` | | `test/src/commands/proxy.cmd.test.ts` | `test/src/commands/proxy/proxy.cmd.test.ts` | | `test/src/commands/proxy.client.cmd.test.ts` | `test/src/commands/proxy/proxy.client.cmd.test.ts` | ## Context Verified on the branch tip: root `pnpm typecheck`, `lint:effect` (0 diagnostics), `oxlint ts/packages/cli` (exit 0), and `pnpm --filter @composio/cli test`. The test run covers `validate:boundaries`, `validate:command-tests` (57 commands, 0 exemptions) and Vitest (222 files, 2893 passed, 1 skipped), the same count as the base branch. `composio proxy --help` renders the same description, argument and flags. --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 28, 2026 at 19:56 UTC 332b1f3155d158136d082f1a9dbb56804e099da3
10 files changed +474 -441
ts/packages/cli/src/commands/COMMANDS.md
+1 -1
@@ -75,7 +75,7 @@ Every command registration of the CLI and the file that defines it. To find a co
75 | `orgs` | root | `ts/packages/cli/src/commands/orgs/orgs.cmd.ts` | | | yes | listed |
76 | `orgs list` | root | `ts/packages/cli/src/commands/orgs/list/orgs.list.cmd.ts` | | | yes | listed |
77 | `orgs switch` | root | `ts/packages/cli/src/commands/orgs/switch/orgs.switch.cmd.ts` | | | yes | listed |
78 -| `proxy` | root | `ts/packages/cli/src/commands/proxy.cmd.ts` | | | yes | listed |
78 +| `proxy` | root | `ts/packages/cli/src/commands/proxy/proxy.cmd.ts` | | | yes | listed |
79 | `run` | root | `ts/packages/cli/src/commands/run.cmd.ts` | | | no | listed |
80 | `search` | root | `ts/packages/cli/src/commands/tools/search/tools.search.cmd.ts` | | | yes | listed |
81 | `setup` | root | `ts/packages/cli/src/commands/setup.cmd.ts` | | | no | listed |
ts/packages/cli/src/commands/index.ts
+1 -1
@@ -17,7 +17,7 @@ import { setupCmd } from './setup.cmd';
17 import { listenCmd } from './listen.cmd';
18 import { logoutCmd } from './logout.cmd';
19 import { runCmd } from './run.cmd';
20 -import { proxyCmd } from './proxy.cmd';
20 +import { proxyCmd } from './proxy/proxy.cmd';
21 import { artifactsCmd } from './artifacts/artifacts.cmd';
22 import { installCmd } from './install/install.cmd';
23 import { generateCmd } from './generate/generate.cmd';
ts/packages/cli/src/commands/proxy.cmd.ts deleted
-436
@@ -1,436 +0,0 @@
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 -);
ts/packages/cli/src/commands/proxy/proxy.cmd.ts new
+76
@@ -0,0 +1,76 @@
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 +import { Argument, Command, Flag } from 'effect/cli';
3 +import { runProxy } from './proxy.handler';
4 +
5 +const endpoint = Argument.String('url').pipe(
6 + Argument.withDescription('Absolute or relative API endpoint to call through proxy execute.')
7 +);
8 +
9 +const toolkit = Flag.String('toolkit').pipe(
10 + Flag.withAlias('t'),
11 + Flag.withDescription('Toolkit slug whose connected account should be used')
12 +);
13 +
14 +const account = Flag.String('account').pipe(
15 + Flag.withDescription(
16 + 'Connected account selector. Matches alias, word_id, or connected account id for the toolkit.'
17 + ),
18 + Flag.optional
19 +);
20 +
21 +const method = Flag.String('method').pipe(
22 + Flag.withAlias('X'),
23 + Flag.withDefault('GET'),
24 + Flag.withDescription('HTTP method, curl-style (GET, POST, PUT, DELETE, PATCH)')
25 +);
26 +
27 +const headers = Flag.String('header').pipe(
28 + Flag.withAlias('H'),
29 + Flag.withDescription('Header in "Name: value" format. Repeat for multiple headers.'),
30 + Flag.atLeast(0)
31 +);
32 +
33 +const data = Flag.String('data').pipe(
34 + Flag.withAlias('d'),
35 + Flag.withDescription('Request body as raw text, JSON, @file, or - for stdin'),
36 + Flag.optional
37 +);
38 +
39 +const skipConnectionCheck = Flag.Boolean('skip-connection-check').pipe(
40 + Flag.withDefault(false),
41 + Flag.withDescription(
42 + 'Skip the short-lived connected-account fail-fast check if you just connected an account'
43 + )
44 +);
45 +
46 +export const proxyCmd = Command.make(
47 + 'proxy',
48 + {
49 + endpoint,
50 + toolkit,
51 + account,
52 + method,
53 + headers,
54 + data,
55 + skipConnectionCheck,
56 + },
57 + runProxy
58 +).pipe(
59 + Command.withDescription(
60 + 'curl-like access to any toolkit API through Composio using your connected account.\nComposio handles authentication — just provide the full URL and toolkit.'
61 + ),
62 + Command.withShortDescription(
63 + 'curl-like access to any toolkit API through Composio using your connected account.'
64 + ),
65 + Command.withExamples([
66 + {
67 + command:
68 + 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail --account work',
69 + },
70 + {
71 + command:
72 + 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\\n -X POST -H \'content-type: application/json\' -d \'{"message":{"raw":"..."}}\'',
73 + },
74 + ]),
75 + withCommandMeta({ requiresLogin: true })
76 +);
ts/packages/cli/src/commands/proxy/proxy.errors.ts new
+25
@@ -0,0 +1,25 @@
1 +import { Data, Runtime } from 'effect';
2 +import { requestError } from 'src/effects/request-error';
3 +
4 +/**
5 + * A proxy call refused before sending it because the toolkit is not connected, already reported
6 + * on stderr and as `{ "successful": false, ... }` on stdout. The runtime prints nothing more
7 + * (`[Runtime.errorReported]` is false) and exits 1.
8 + */
9 +export class ReportedProxyCommandError extends Data.TaggedError(
10 + 'commands/ReportedProxyCommandError'
11 +)<{
12 + readonly message: string;
13 + readonly toolkit: string;
14 + readonly endpoint: string;
15 +}> {
16 + get [Runtime.errorReported]() {
17 + return false;
18 + }
19 +
20 + get [Runtime.errorExitCode]() {
21 + return 1;
22 + }
23 +}
24 +
25 +export class ProxyRequestError extends requestError('commands/ProxyRequestError') {}
ts/packages/cli/src/commands/proxy/proxy.format.ts new
+65
@@ -0,0 +1,65 @@
1 +import type { SessionProxyExecuteResponse } from '@composio/client/resources/tool-router/session';
2 +
3 +export const formatProxyOutput = (
4 + result: Pick<
5 + Extract<SessionProxyExecuteResponse, { result_type: 'completed' }>,
6 + 'status' | 'data' | 'headers' | 'binary_data'
7 + >
8 +) => {
9 + if (result.binary_data) {
10 + return JSON.stringify(
11 + {
12 + status: result.status ?? null,
13 + headers: result.headers ?? {},
14 + binary_data: result.binary_data,
15 + },
16 + null,
17 + 2
18 + );
19 + }
20 +
21 + if (typeof result.data === 'string') {
22 + return result.data;
23 + }
24 +
25 + if (result.data === undefined || result.data === null) {
26 + return '';
27 + }
28 +
29 + return JSON.stringify(result.data, null, 2);
30 +};
31 +
32 +export const formatProxyErrorOutput = (params: {
33 + readonly error: string;
34 + readonly toolkit: string;
35 + readonly endpoint: string;
36 + readonly slug?: string;
37 +}) =>
38 + JSON.stringify(
39 + {
40 + successful: false,
41 + error: params.error,
42 + toolkit: params.toolkit,
43 + endpoint: params.endpoint,
44 + slug: params.slug ?? null,
45 + },
46 + null,
47 + 2
48 + );
49 +
50 +/** The stdout result of a call refused because the toolkit is not connected. */
51 +export const formatProxyNotConnectedOutput = (params: {
52 + readonly error: string;
53 + readonly toolkit: string;
54 + readonly endpoint: string;
55 +}) =>
56 + JSON.stringify(
57 + {
58 + successful: false,
59 + error: params.error,
60 + toolkit: params.toolkit,
61 + endpoint: params.endpoint,
62 + },
63 + null,
64 + 2
65 + );
ts/packages/cli/src/commands/proxy/proxy.handler.ts new
+303
@@ -0,0 +1,303 @@
1 +import { Effect, Result, Option } from 'effect';
2 +import type { SessionProxyExecuteParams } from '@composio/client/resources/tool-router/session';
3 +import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
4 +import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
5 +import { gateToolExecution } from 'src/services/tool-permissions';
6 +import {
7 + getFreshConsumerConnectedToolkitsFromCache,
8 + refreshConsumerConnectedToolkitsCache,
9 +} from 'src/services/consumer-short-term-cache';
10 +import { TerminalUI } from 'src/services/terminal-ui';
11 +import { ComposioClientSingleton } from 'src/services/composio-clients';
12 +import { actingUser } from 'src/commands/surface';
13 +import {
14 + ComposioNoActiveConnectionError,
15 + mapComposioError,
16 +} from 'src/services/composio-error-overrides';
17 +import { parseJsonRecord } from 'src/utils/parse-json';
18 +import { toolInputRequiredError } from 'src/utils/tool-input-required';
19 +import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
20 +import { ProxyRequestError, ReportedProxyCommandError } from './proxy.errors';
21 +import {
22 + formatProxyErrorOutput,
23 + formatProxyNotConnectedOutput,
24 + formatProxyOutput,
25 +} from './proxy.format';
26 +
27 +/** The argument and flags of `composio proxy`. */
28 +export type ProxyParams = {
29 + readonly endpoint: string;
30 + readonly toolkit: string;
31 + readonly account: Option.Option<string>;
32 + readonly method: string;
33 + readonly headers: ReadonlyArray<string>;
34 + readonly data: Option.Option<string>;
35 + readonly skipConnectionCheck: boolean;
36 +};
37 +
38 +type ProxyMethod = Extract<
39 + SessionProxyExecuteParams['method'],
40 + 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
41 +>;
42 +
43 +const SUPPORTED_PROXY_METHODS: ReadonlyArray<ProxyMethod> = [
44 + 'GET',
45 + 'POST',
46 + 'PUT',
47 + 'DELETE',
48 + 'PATCH',
49 +];
50 +
51 +export const normalizeProxyMethod = (value: string): ProxyMethod => {
52 + const normalized = value.trim().toUpperCase();
53 + const supported = SUPPORTED_PROXY_METHODS.find(method => method === normalized);
54 + if (!supported) {
55 + throw new Error('Unsupported method. Use one of GET, POST, PUT, DELETE, PATCH.');
56 + }
57 + return supported;
58 +};
59 +
60 +export const parseProxyHeader = (value: string): { name: string; value: string } => {
61 + const idx = value.indexOf(':');
62 + if (idx <= 0) {
63 + throw new Error(`Invalid header "${value}". Use "Name: value".`);
64 + }
65 +
66 + const name = value.slice(0, idx).trim();
67 + const headerValue = value.slice(idx + 1).trim();
68 + if (!name) {
69 + throw new Error(`Invalid header "${value}". Missing header name.`);
70 + }
71 + return { name, value: headerValue };
72 +};
73 +
74 +const resolveBodyInput = (input: Option.Option<string>) => resolveOptionalTextInput(input);
75 +
76 +export const parseProxyBody = (raw: string): unknown =>
77 + Result.getOrElse(parseJsonRecord(raw), (): unknown => raw);
78 +
79 +const handleProxyExecutionError = (params: {
80 + readonly ui: TerminalUI;
81 + readonly error: unknown;
82 + readonly toolkit: string;
83 + readonly endpoint: string;
84 +}) =>
85 + Effect.gen(function* () {
86 + const mapped = mapComposioError({
87 + error: params.error,
88 + toolkit: params.toolkit,
89 + });
90 +
91 + if (mapped.normalized instanceof ComposioNoActiveConnectionError) {
92 + yield* params.ui.log.error(mapped.message);
93 + yield* params.ui.note(
94 + [
95 + `Link the toolkit first: composio link ${params.toolkit}`,
96 + 'Then retry the proxy call.',
97 + ].join('\n'),
98 + 'Tips'
99 + );
100 + } else {
101 + yield* params.ui.log.error(mapped.message);
102 + }
103 + const output = formatProxyErrorOutput({
104 + error: mapped.message,
105 + toolkit: params.toolkit,
106 + endpoint: params.endpoint,
107 + slug: mapped.slugValue,
108 + });
109 + yield* params.ui.output(output);
110 + return yield* Effect.fail(mapped.normalized);
111 + });
112 +
113 +const runProxyConnectedToolkitFailFast = (params: {
114 + readonly toolkit: string;
115 + readonly ui: TerminalUI;
116 + readonly resolvedProject: {
117 + readonly projectType: 'CONSUMER' | 'DEVELOPER';
118 + readonly orgId: string;
119 + };
120 + readonly resolvedUserId: string;
121 + readonly endpoint: string;
122 + readonly skipConnectionCheck: boolean;
123 +}) =>
124 + Effect.gen(function* () {
125 + if (params.skipConnectionCheck) return;
126 + if (params.resolvedProject.projectType !== 'CONSUMER') return;
127 +
128 + yield* refreshConsumerConnectedToolkitsCache({
129 + orgId: params.resolvedProject.orgId,
130 + consumerUserId: params.resolvedUserId,
131 + }).pipe(
132 + Effect.catch(() => Effect.void),
133 + Effect.forkDetach,
134 + Effect.asVoid
135 + );
136 +
137 + const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
138 + orgId: params.resolvedProject.orgId,
139 + consumerUserId: params.resolvedUserId,
140 + });
141 +
142 + if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(params.toolkit)) {
143 + 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.`;
144 + yield* params.ui.log.error(message);
145 + yield* params.ui.note(
146 + [
147 + `Link the toolkit first: composio link ${params.toolkit}`,
148 + 'Then retry the proxy call.',
149 + ].join('\n'),
150 + 'Tips'
151 + );
152 + yield* params.ui.output(
153 + formatProxyNotConnectedOutput({
154 + error: message,
155 + toolkit: params.toolkit,
156 + endpoint: params.endpoint,
157 + })
158 + );
159 + return yield* new ReportedProxyCommandError({
160 + message,
161 + toolkit: params.toolkit,
162 + endpoint: params.endpoint,
163 + });
164 + }
165 + });
166 +
167 +export const runProxy = (params: ProxyParams) =>
168 + Effect.gen(function* () {
169 + const { endpoint, toolkit, account, method, headers, data, skipConnectionCheck } = params;
170 + const ui = yield* TerminalUI;
171 + const clientSingleton = yield* ComposioClientSingleton;
172 + const { userId: consumerUserId, project: resolvedProject } = yield* actingUser();
173 + const normalizedToolkit = toolkit.toLowerCase();
174 +
175 + yield* runProxyConnectedToolkitFailFast({
176 + toolkit: normalizedToolkit,
177 + ui,
178 + resolvedProject,
179 + resolvedUserId: consumerUserId,
180 + endpoint,
181 + skipConnectionCheck,
182 + });
183 +
184 + const normalizedMethod = normalizeProxyMethod(method);
185 + const headerParameters: NonNullable<SessionProxyExecuteParams['parameters']> = headers.map(
186 + header => {
187 + const parsed = parseProxyHeader(header);
188 + return {
189 + name: parsed.name,
190 + type: 'header',
191 + value: parsed.value,
192 + };
193 + }
194 + );
195 + const rawBody = yield* resolveBodyInput(data);
196 + const parsedBody = rawBody === undefined ? undefined : parseProxyBody(rawBody);
197 +
198 + const result = yield* ui.withSpinner(
199 + `Proxying ${normalizedMethod} ${endpoint} via ${normalizedToolkit}...`,
200 + Effect.gen(function* () {
201 + const client = yield* clientSingleton.getFor({
202 + orgId: resolvedProject.orgId,
203 + projectId: resolvedProject.projectId,
204 + });
205 + // Always resolve through here, even with no --account: this is what
206 + // makes the "multiple accounts, none aliased default" case fail
207 + // loudly instead of resolveToolRouterSession silently picking one
208 + // via resolveDefaultConnectedAccountsByToolkit.
209 + const selectedConnectedAccountId = yield* resolveConnectedAccountForToolkit({
210 + client,
211 + toolkitSlug: normalizedToolkit,
212 + userId: consumerUserId,
213 + selector: account,
214 + });
215 + const { sessionId, permissionSnapshot, connectedAccounts, connectedAccountWordIds } =
216 + yield* resolveToolRouterSession(client, consumerUserId, {
217 + toolkits: [normalizedToolkit],
218 + connectedAccounts: selectedConnectedAccountId
219 + ? { [normalizedToolkit]: selectedConnectedAccountId }
220 + : undefined,
221 + cacheScope: {
222 + orgId: resolvedProject.orgId,
223 + projectId: resolvedProject.projectId,
224 + consumerUserId,
225 + },
226 + });
227 +
228 + // Same consumer permission gate as `composio execute`, checked against
229 + // the account the session will use (explicit `--account` or default).
230 + yield* gateToolExecution({
231 + toolSlug: normalizedToolkit,
232 + connectedAccountId: connectedAccounts?.[normalizedToolkit],
233 + connectedAccountWordId: connectedAccountWordIds?.[normalizedToolkit],
234 + snapshot: permissionSnapshot,
235 + });
236 +
237 + const failed = (cause: unknown) =>
238 + new ProxyRequestError({
239 + message: `Failed to proxy ${normalizedMethod} ${endpoint} via "${normalizedToolkit}".`,
240 + cause,
241 + });
242 +
243 + return yield* client.toolRouter.session
244 + .proxyExecute(
245 + sessionId,
246 + {
247 + toolkit_slug: normalizedToolkit,
248 + endpoint,
249 + method: normalizedMethod,
250 + ...(parsedBody !== undefined ? { body: parsedBody } : {}),
251 + ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),
252 + }
253 + // A proxied call is not `idempotent`, so it is sent once: a retry
254 + // after the upstream API already acted duplicates the side
255 + // effect. The response is not validated either, for the same
256 + // reason.
257 + )
258 + .pipe(
259 + Effect.mapError(failed),
260 + Effect.flatMap(response => {
261 + if (response.result_type === 'input_required') {
262 + return Effect.fail(
263 + failed(
264 + toolInputRequiredError(
265 + `${normalizedMethod} proxy call via "${normalizedToolkit}"`,
266 + response
267 + )
268 + )
269 + );
270 + }
271 + // A session hook blocked the request: there is no HTTP
272 + // response to print, only the hook's message.
273 + if (response.result_type === 'blocked') {
274 + return Effect.fail(
275 + new ProxyRequestError({
276 + message: `${normalizedMethod} proxy call via "${normalizedToolkit}" was blocked by session hook "${response.reason.hook_id}": ${response.message}`,
277 + cause: response.reason,
278 + })
279 + );
280 + }
281 + return Effect.succeed(response);
282 + }),
283 + Effect.matchEffect({
284 + onFailure: error =>
285 + handleProxyExecutionError({
286 + ui,
287 + error,
288 + toolkit: normalizedToolkit,
289 + endpoint,
290 + }),
291 + onSuccess: Effect.succeed,
292 + })
293 + );
294 + })
295 + );
296 +
297 + const output = formatProxyOutput(result);
298 + yield* ui.log.info(`Status: ${String(result.status ?? 'unknown')}`);
299 + if (output) {
300 + yield* ui.note(output, 'Proxy Response');
301 + yield* ui.output(output);
302 + }
303 + });
ts/packages/cli/test/src/commands/errors.test.ts
+1 -1
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
3 import { ConnectionPollingError } from 'src/commands/connected-accounts/link/connected-accounts.link.errors';
4 import { commandInputError, isUsageFailure, notLoggedIn } from 'src/commands/errors';
5 import { InvalidOrganizationError } from 'src/commands/login/login.errors';
6 -import { ReportedProxyCommandError } from 'src/commands/proxy.cmd';
6 +import { ReportedProxyCommandError } from 'src/commands/proxy/proxy.errors';
7 import { MissingActingUserError } from 'src/commands/surface';
8 import {
9 ReportedToolExecutionError,
ts/packages/cli/test/src/commands/proxy/proxy.client.cmd.test.ts renamed
ts/packages/cli/test/src/commands/proxy/proxy.cmd.test.ts renamed
+2 -2
@@ -6,12 +6,12 @@ import type {
6 SessionCreateParams,
7 SessionProxyExecuteParams,
8 } from '@composio/client/resources/tool-router';
9 +import { ReportedProxyCommandError } from 'src/commands/proxy/proxy.errors';
10 import {
11 normalizeProxyMethod,
12 parseProxyBody,
13 parseProxyHeader,
13 - ReportedProxyCommandError,
14 -} from 'src/commands/proxy.cmd';
14 +} from 'src/commands/proxy/proxy.handler';
15 import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
16 import * as toolPermissions from 'src/services/tool-permissions';
17 import { cli, MockConsole, TestLive } from 'test/__utils__';