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, 04:45 UTC
| 1 | import { Effect, Result, Option } from 'effect'; |
| 2 | import type { SessionProxyExecuteParams } from '@composio/client/resources/tool-router/session'; |
| 3 | import { resolveExplicitTextInput } 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 { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text'; |
| 12 | import { ComposioClientSingleton } from 'src/services/composio-clients'; |
| 13 | import { actingUser, warnOnStderr } from 'src/commands/surface'; |
| 14 | import { Stdin } from 'src/services/stdin'; |
| 15 | import { |
| 16 | ComposioNoActiveConnectionError, |
| 17 | mapComposioError, |
| 18 | } from 'src/services/composio-error-overrides'; |
| 19 | import { parseJsonRecord } from 'src/utils/parse-json'; |
| 20 | import { toolInputRequiredError } from 'src/utils/tool-input-required'; |
| 21 | import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection'; |
| 22 | import { ProxyRequestError, ReportedProxyCommandError } from './proxy.errors'; |
| 23 | import { |
| 24 | formatProxyErrorOutput, |
| 25 | formatProxyNotConnectedOutput, |
| 26 | formatProxyOutput, |
| 27 | } from './proxy.format'; |
| 28 | |
| 29 | /** The argument and flags of `composio proxy`. */ |
| 30 | export type ProxyParams = { |
| 31 | readonly endpoint: string; |
| 32 | readonly toolkit: string; |
| 33 | readonly account: Option.Option<string>; |
| 34 | readonly method: string; |
| 35 | readonly headers: ReadonlyArray<string>; |
| 36 | readonly data: Option.Option<string>; |
| 37 | readonly skipConnectionCheck: boolean; |
| 38 | }; |
| 39 | |
| 40 | type ProxyMethod = Extract< |
| 41 | SessionProxyExecuteParams['method'], |
| 42 | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' |
| 43 | >; |
| 44 | |
| 45 | const SUPPORTED_PROXY_METHODS: ReadonlyArray<ProxyMethod> = [ |
| 46 | 'GET', |
| 47 | 'POST', |
| 48 | 'PUT', |
| 49 | 'DELETE', |
| 50 | 'PATCH', |
| 51 | ]; |
| 52 | |
| 53 | export const normalizeProxyMethod = (value: string): ProxyMethod => { |
| 54 | const normalized = value.trim().toUpperCase(); |
| 55 | const supported = SUPPORTED_PROXY_METHODS.find(method => method === normalized); |
| 56 | if (!supported) { |
| 57 | throw new Error('Unsupported method. Use one of GET, POST, PUT, DELETE, PATCH.'); |
| 58 | } |
| 59 | return supported; |
| 60 | }; |
| 61 | |
| 62 | export const parseProxyHeader = (value: string): { name: string; value: string } => { |
| 63 | const idx = value.indexOf(':'); |
| 64 | if (idx <= 0) { |
| 65 | throw new Error(`Invalid header "${value}". Use "Name: value".`); |
| 66 | } |
| 67 | |
| 68 | const name = value.slice(0, idx).trim(); |
| 69 | const headerValue = value.slice(idx + 1).trim(); |
| 70 | if (!name) { |
| 71 | throw new Error(`Invalid header "${value}". Missing header name.`); |
| 72 | } |
| 73 | return { name, value: headerValue }; |
| 74 | }; |
| 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 | // The message can quote the upstream API; the stdout result keeps it as it is. |
| 92 | const displayMessage = escapeTerminalText(mapped.message); |
| 93 | if (mapped.normalized instanceof ComposioNoActiveConnectionError) { |
| 94 | yield* params.ui.log.error(displayMessage); |
| 95 | yield* params.ui.note( |
| 96 | [ |
| 97 | `Link the toolkit first: composio link ${params.toolkit}`, |
| 98 | 'Then retry the proxy call.', |
| 99 | ].join('\n'), |
| 100 | 'Tips' |
| 101 | ); |
| 102 | } else { |
| 103 | yield* params.ui.log.error(displayMessage); |
| 104 | } |
| 105 | const output = formatProxyErrorOutput({ |
| 106 | error: mapped.message, |
| 107 | toolkit: params.toolkit, |
| 108 | endpoint: params.endpoint, |
| 109 | slug: mapped.slugValue, |
| 110 | }); |
| 111 | yield* params.ui.output(output); |
| 112 | return yield* Effect.fail(mapped.normalized); |
| 113 | }); |
| 114 | |
| 115 | const runProxyConnectedToolkitFailFast = (params: { |
| 116 | readonly toolkit: string; |
| 117 | readonly ui: TerminalUI; |
| 118 | readonly resolvedProject: { |
| 119 | readonly projectType: 'CONSUMER' | 'DEVELOPER'; |
| 120 | readonly orgId: string; |
| 121 | }; |
| 122 | readonly resolvedUserId: string; |
| 123 | readonly endpoint: string; |
| 124 | readonly skipConnectionCheck: boolean; |
| 125 | }) => |
| 126 | Effect.gen(function* () { |
| 127 | if (params.skipConnectionCheck) return; |
| 128 | if (params.resolvedProject.projectType !== 'CONSUMER') return; |
| 129 | |
| 130 | yield* refreshConsumerConnectedToolkitsCache({ |
| 131 | orgId: params.resolvedProject.orgId, |
| 132 | consumerUserId: params.resolvedUserId, |
| 133 | }).pipe( |
| 134 | Effect.catch(() => Effect.void), |
| 135 | Effect.forkDetach, |
| 136 | Effect.asVoid |
| 137 | ); |
| 138 | |
| 139 | const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({ |
| 140 | orgId: params.resolvedProject.orgId, |
| 141 | consumerUserId: params.resolvedUserId, |
| 142 | }); |
| 143 | |
| 144 | if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(params.toolkit)) { |
| 145 | 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.`; |
| 146 | yield* params.ui.log.error(message); |
| 147 | yield* params.ui.note( |
| 148 | [ |
| 149 | `Link the toolkit first: composio link ${params.toolkit}`, |
| 150 | 'Then retry the proxy call.', |
| 151 | ].join('\n'), |
| 152 | 'Tips' |
| 153 | ); |
| 154 | yield* params.ui.output( |
| 155 | formatProxyNotConnectedOutput({ |
| 156 | error: message, |
| 157 | toolkit: params.toolkit, |
| 158 | endpoint: params.endpoint, |
| 159 | }) |
| 160 | ); |
| 161 | return yield* new ReportedProxyCommandError({ |
| 162 | message, |
| 163 | toolkit: params.toolkit, |
| 164 | endpoint: params.endpoint, |
| 165 | }); |
| 166 | } |
| 167 | }); |
| 168 | |
| 169 | export const runProxy = (params: ProxyParams) => |
| 170 | Effect.gen(function* () { |
| 171 | const { endpoint, toolkit, account, method, headers, data, skipConnectionCheck } = params; |
| 172 | const ui = yield* TerminalUI; |
| 173 | const clientSingleton = yield* ComposioClientSingleton; |
| 174 | const { userId: consumerUserId, project: resolvedProject } = yield* actingUser(); |
| 175 | const normalizedToolkit = toolkit.toLowerCase(); |
| 176 | |
| 177 | yield* runProxyConnectedToolkitFailFast({ |
| 178 | toolkit: normalizedToolkit, |
| 179 | ui, |
| 180 | resolvedProject, |
| 181 | resolvedUserId: consumerUserId, |
| 182 | endpoint, |
| 183 | skipConnectionCheck, |
| 184 | }); |
| 185 | |
| 186 | const normalizedMethod = normalizeProxyMethod(method); |
| 187 | const headerParameters: NonNullable<SessionProxyExecuteParams['parameters']> = headers.map( |
| 188 | header => { |
| 189 | const parsed = parseProxyHeader(header); |
| 190 | return { |
| 191 | name: parsed.name, |
| 192 | type: 'header', |
| 193 | value: parsed.value, |
| 194 | }; |
| 195 | } |
| 196 | ); |
| 197 | // Only `-d -` reads stdin: reading a pipe the caller left open would hang the request before |
| 198 | // it is sent, and agents run with such pipes. |
| 199 | const rawBody = yield* resolveExplicitTextInput(data); |
| 200 | if (rawBody === undefined && normalizedMethod !== 'GET' && !(yield* Stdin).isTTY()) { |
| 201 | // A body piped in without `-d` used to be sent; say why it no longer is, without reading |
| 202 | // stdin, which an agent harness may hold open. A GET stays quiet: it is the bodiless read |
| 203 | // agents run with such a pipe, and a warning on every one would be noise. |
| 204 | yield* warnOnStderr( |
| 205 | 'Sending the request without a body: composio proxy reads stdin only with -d -. Pass -d - to send piped input as the body.' |
| 206 | ); |
| 207 | } |
| 208 | const parsedBody = rawBody === undefined ? undefined : parseProxyBody(rawBody); |
| 209 | |
| 210 | const result = yield* ui.withSpinner( |
| 211 | `Proxying ${normalizedMethod} ${endpoint} via ${normalizedToolkit}...`, |
| 212 | Effect.gen(function* () { |
| 213 | const client = yield* clientSingleton.getFor({ |
| 214 | orgId: resolvedProject.orgId, |
| 215 | projectId: resolvedProject.projectId, |
| 216 | }); |
| 217 | // Always resolve through here, even with no --account: this is what |
| 218 | // makes the "multiple accounts, none aliased default" case fail |
| 219 | // loudly instead of resolveToolRouterSession silently picking one |
| 220 | // via resolveDefaultConnectedAccountsByToolkit. |
| 221 | const selectedConnectedAccountId = yield* resolveConnectedAccountForToolkit({ |
| 222 | client, |
| 223 | toolkitSlug: normalizedToolkit, |
| 224 | userId: consumerUserId, |
| 225 | selector: account, |
| 226 | }); |
| 227 | const { sessionId, permissionSnapshot, connectedAccounts, connectedAccountWordIds } = |
| 228 | yield* resolveToolRouterSession(client, consumerUserId, { |
| 229 | toolkits: [normalizedToolkit], |
| 230 | connectedAccounts: selectedConnectedAccountId |
| 231 | ? { [normalizedToolkit]: selectedConnectedAccountId } |
| 232 | : undefined, |
| 233 | cacheScope: { |
| 234 | orgId: resolvedProject.orgId, |
| 235 | projectId: resolvedProject.projectId, |
| 236 | consumerUserId, |
| 237 | }, |
| 238 | }); |
| 239 | |
| 240 | // Same consumer permission gate as `composio execute`, checked against |
| 241 | // the account the session will use (explicit `--account` or default). |
| 242 | yield* gateToolExecution({ |
| 243 | toolSlug: normalizedToolkit, |
| 244 | connectedAccountId: connectedAccounts?.[normalizedToolkit], |
| 245 | connectedAccountWordId: connectedAccountWordIds?.[normalizedToolkit], |
| 246 | snapshot: permissionSnapshot, |
| 247 | }); |
| 248 | |
| 249 | const failed = (cause: unknown) => |
| 250 | new ProxyRequestError({ |
| 251 | message: `Failed to proxy ${normalizedMethod} ${endpoint} via "${normalizedToolkit}".`, |
| 252 | cause, |
| 253 | }); |
| 254 | |
| 255 | return yield* client.toolRouter.session |
| 256 | .proxyExecute( |
| 257 | sessionId, |
| 258 | { |
| 259 | toolkit_slug: normalizedToolkit, |
| 260 | endpoint, |
| 261 | method: normalizedMethod, |
| 262 | ...(parsedBody !== undefined ? { body: parsedBody } : {}), |
| 263 | ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}), |
| 264 | } |
| 265 | // A proxied call is not `idempotent`, so it is sent once: a retry |
| 266 | // after the upstream API already acted duplicates the side |
| 267 | // effect. The response is not validated either, for the same |
| 268 | // reason. |
| 269 | ) |
| 270 | .pipe( |
| 271 | Effect.mapError(failed), |
| 272 | Effect.flatMap(response => { |
| 273 | if (response.result_type === 'input_required') { |
| 274 | return Effect.fail( |
| 275 | failed( |
| 276 | toolInputRequiredError( |
| 277 | `${normalizedMethod} proxy call via "${normalizedToolkit}"`, |
| 278 | response |
| 279 | ) |
| 280 | ) |
| 281 | ); |
| 282 | } |
| 283 | // A session hook blocked the request: there is no HTTP |
| 284 | // response to print, only the hook's message. |
| 285 | if (response.result_type === 'blocked') { |
| 286 | return Effect.fail( |
| 287 | new ProxyRequestError({ |
| 288 | message: `${normalizedMethod} proxy call via "${normalizedToolkit}" was blocked by session hook "${response.reason.hook_id}": ${response.message}`, |
| 289 | cause: response.reason, |
| 290 | }) |
| 291 | ); |
| 292 | } |
| 293 | return Effect.succeed(response); |
| 294 | }), |
| 295 | Effect.matchEffect({ |
| 296 | onFailure: error => |
| 297 | handleProxyExecutionError({ |
| 298 | ui, |
| 299 | error, |
| 300 | toolkit: normalizedToolkit, |
| 301 | endpoint, |
| 302 | }), |
| 303 | onSuccess: Effect.succeed, |
| 304 | }) |
| 305 | ); |
| 306 | }) |
| 307 | ); |
| 308 | |
| 309 | const output = formatProxyOutput(result); |
| 310 | yield* ui.log.info(`Status: ${escapeTerminalText(String(result.status ?? 'unknown'))}`); |
| 311 | if (output) { |
| 312 | // The note shows the response on the terminal; redirected stdout gets the body as it is. |
| 313 | yield* ui.note(escapeTerminalLines(output), 'Proxy Response'); |
| 314 | yield* ui.output(output); |
| 315 | } |
| 316 | }); |