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

next
ts 372 lines 13.7 KB
Raw
1 import {
2 APIError,
3 AuthenticationError,
4 BadRequestError,
5 ConflictError,
6 InternalServerError,
7 NotFoundError,
8 PermissionDeniedError,
9 RateLimitError,
10 UnprocessableEntityError,
11 type APIErrorFields,
12 type APIStatusError,
13 } from '@composio/client/effect';
14 import type {
15 SessionExecuteMetaResponse,
16 SessionExecuteResponse,
17 } from '@composio/client/resources/tool-router';
18 import { Config, Context, Data, Duration, Effect, Layer, Option, Result, Schema } from 'effect';
19 import { FetchHttpClient, HttpClient, HttpClientRequest } from 'effect/http';
20 import * as constants from 'src/constants';
21 import { readInstallIdWhenTelemetryEnabled } from 'src/analytics/dispatch';
22 import { APP_CONFIG } from 'src/config';
23 import { cliRequestHeaders } from 'src/services/client-provenance';
24 import { ComposioUserContext } from 'src/services/user-context';
25 import { toolInputRequiredError } from 'src/utils/tool-input-required';
26
27 export interface DashboardToolExecutionRequest {
28 readonly slug: string;
29 readonly arguments: Record<string, unknown>;
30 /** Sent as `x-org-id`; the Dashboard resolves the consumer project from it. */
31 readonly orgId: string;
32 /** Connected account to run an app tool with; the Dashboard's sessions are multi-account. */
33 readonly account?: string;
34 }
35
36 export class DashboardToolExecutionError extends Data.TaggedError(
37 'services/DashboardToolExecutionError'
38 )<{
39 readonly message: string;
40 /**
41 * - `unauthorized`: the Dashboard rejected the stored login, or there is none.
42 * - `dashboard`: the Dashboard reported a failure of its own.
43 * - `request`: no response arrived.
44 * - `response`: the response was not one the CLI understands.
45 * - `timeout`: no complete response arrived within the deadline.
46 * - `configuration`: the Dashboard URL is not one the CLI will send a key to.
47 */
48 readonly reason:
49 'unauthorized' | 'dashboard' | 'request' | 'response' | 'timeout' | 'configuration';
50 readonly status?: number;
51 /** The Dashboard's error code, e.g. `UNAUTHORIZED`. */
52 readonly code?: string;
53 readonly cause?: unknown;
54 }> {}
55
56 const JsonObject = Schema.Record(Schema.String, Schema.Unknown);
57
58 /** A backend execute answer that carries a result rather than a request for more input. */
59 export type DashboardExecutionResult = Exclude<
60 SessionExecuteResponse | SessionExecuteMetaResponse,
61 { result_type: 'input_required' }
62 >;
63
64 // The backend's answer is relayed as the backend sent it. Like the backend
65 // transport, the CLI checks only what tells a result from a request for input:
66 // the tool has already run (or a session hook blocked it), so a missing field
67 // must not turn its result into an error.
68 const ExecutionResult = Schema.StructWithRest(
69 Schema.Struct({ result_type: Schema.Literals(['completed', 'failed', 'blocked']) }),
70 [JsonObject]
71 );
72
73 const ExecutionResponse = Schema.Union([
74 ExecutionResult,
75 Schema.Struct({
76 result_type: Schema.Literal('input_required'),
77 input_requests: Schema.Record(
78 Schema.String,
79 Schema.Struct({
80 type: Schema.Literal('elicitation'),
81 mode: Schema.Literal('form'),
82 message: Schema.String,
83 requested_schema: JsonObject,
84 })
85 ),
86 request_state: Schema.optional(Schema.String),
87 }),
88 ]);
89
90 // Fields beyond the named ones (a validation failure's `errors`, say) are kept,
91 // so the rebuilt `APIError` carries the same body the backend sent.
92 const ApiErrorEnvelope = Schema.StructWithRest(
93 Schema.Struct({
94 message: Schema.String,
95 code: Schema.optional(Schema.Number),
96 slug: Schema.optional(Schema.String),
97 status: Schema.optional(Schema.Number),
98 request_id: Schema.optional(Schema.String),
99 suggested_fix: Schema.optional(Schema.String),
100 }),
101 [JsonObject]
102 );
103
104 const ExecutionOutcome = Schema.Union([
105 Schema.Struct({ ok: Schema.Literal(true), response: ExecutionResponse }),
106 Schema.Struct({ ok: Schema.Literal(false), status: Schema.Number, error: ApiErrorEnvelope }),
107 ]);
108
109 const ProcedureReply = Schema.Union([
110 Schema.Struct({
111 result: Schema.Struct({ data: Schema.Struct({ json: ExecutionOutcome }) }),
112 }),
113 Schema.Struct({
114 error: Schema.Struct({
115 json: Schema.Struct({
116 message: Schema.String,
117 data: Schema.optional(
118 Schema.Struct({
119 code: Schema.optional(Schema.String),
120 httpStatus: Schema.optional(Schema.Number),
121 })
122 ),
123 }),
124 }),
125 }),
126 ]);
127
128 const decodeProcedureReply = Schema.decodeUnknownEffect(Schema.fromJsonString(ProcedureReply));
129
130 /**
131 * The error `@composio/client` fails with for the same backend response, so
132 * error mapping, connection tips and telemetry need no second code path. The
133 * status classes and the message follow the client's own rules.
134 */
135 const relayedApiError = (
136 url: string,
137 status: number,
138 envelope: Schema.Schema.Type<typeof ApiErrorEnvelope>
139 ): APIStatusError => {
140 const body = { error: envelope };
141 const fields: APIErrorFields = {
142 message: `${status} ${JSON.stringify(body)}`,
143 method: 'POST',
144 url,
145 status,
146 requestId: envelope.request_id,
147 details:
148 envelope.code !== undefined && envelope.slug !== undefined && envelope.status !== undefined
149 ? {
150 ...envelope,
151 code: envelope.code,
152 slug: envelope.slug,
153 status: envelope.status,
154 }
155 : undefined,
156 body,
157 };
158 if (status === 400) return new BadRequestError(fields);
159 if (status === 401) return new AuthenticationError(fields);
160 if (status === 403) return new PermissionDeniedError(fields);
161 if (status === 404) return new NotFoundError(fields);
162 if (status === 409) return new ConflictError(fields);
163 if (status === 422) return new UnprocessableEntityError(fields);
164 if (status === 429) return new RateLimitError(fields);
165 if (status >= 500) return new InternalServerError(fields);
166 return new APIError(fields);
167 };
168
169 const withoutTrailingSlashes = (url: string) => url.replace(/\/+$/, '');
170
171 const LOGIN_HINT = 'Run `composio login`, then retry.';
172
173 /**
174 * Covers the POST and reading its body. The Dashboard allows a tool up to 800
175 * seconds, so anything still pending after this is not coming.
176 */
177 const DASHBOARD_REQUEST_TIMEOUT = Duration.minutes(15);
178
179 const LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);
180
181 // Fixed text: the configured value may itself hold a secret, so it is never echoed.
182 const INVALID_DASHBOARD_URL_MESSAGE =
183 'The Composio Dashboard URL (COMPOSIO_WEB_URL) must be an https:// URL with no credentials, query string, or fragment; http:// is accepted only for localhost. Nothing was sent.';
184
185 /**
186 * The Dashboard base the user API key may be sent to: `origin` for messages,
187 * `base` for building request URLs. Rejects a URL that would put the key on
188 * the wire in clear text, or that carries anything beyond scheme, host and path.
189 */
190 const resolveDashboardBase = (webURL: string) =>
191 Result.try({
192 try: () => new URL(webURL),
193 catch: () => undefined,
194 }).pipe(
195 Result.filterOrFail(
196 url =>
197 url.username === '' &&
198 url.password === '' &&
199 !webURL.includes('?') &&
200 !webURL.includes('#') &&
201 (url.protocol === 'https:' ||
202 (url.protocol === 'http:' && LOOPBACK_HOSTNAMES.has(url.hostname))),
203 () => undefined
204 ),
205 Result.map(url => ({
206 origin: url.origin,
207 base: `${url.origin}${withoutTrailingSlashes(url.pathname)}`,
208 })),
209 Result.mapError(
210 () =>
211 new DashboardToolExecutionError({
212 reason: 'configuration',
213 message: INVALID_DASHBOARD_URL_MESSAGE,
214 })
215 )
216 );
217
218 /**
219 * Which transport a consumer execution uses. The Dashboard is the default; a
220 * backend URL that was overridden without a matching `COMPOSIO_WEB_URL` keeps
221 * the backend transport, so a key for one deployment is never sent to another
222 * deployment's Dashboard.
223 */
224 export const resolveConsumerExecutionTransport = Effect.gen(function* () {
225 const webURL = yield* Config.option(Config.String('COMPOSIO_WEB_URL'));
226 if (Option.isSome(webURL)) return 'dashboard' as const;
227
228 const baseURL = yield* Config.option(Config.String('COMPOSIO_BASE_URL'));
229 if (Option.isNone(baseURL)) return 'dashboard' as const;
230
231 const environment = yield* APP_CONFIG.ENVIRONMENT;
232 const environmentBaseURL =
233 environment === 'staging' ? constants.STAGING_BASE_URL : constants.DEFAULT_BASE_URL;
234
235 return withoutTrailingSlashes(baseURL.value) === withoutTrailingSlashes(environmentBaseURL)
236 ? ('dashboard' as const)
237 : ('backend' as const);
238 });
239
240 const makeDashboardToolExecution = Effect.gen(function* () {
241 const httpClient = yield* HttpClient.HttpClient;
242 const userContext = yield* ComposioUserContext;
243
244 const call = (
245 procedure: 'execute' | 'executeMeta',
246 orgId: string,
247 input: Record<string, unknown>
248 ) =>
249 Effect.gen(function* () {
250 // Read per call: a login earlier in the same process changes the key.
251 const { apiKey, webURL } = userContext.data;
252 if (Option.isNone(apiKey)) {
253 return yield* new DashboardToolExecutionError({
254 reason: 'unauthorized',
255 message: `You are not logged in. ${LOGIN_HINT}`,
256 });
257 }
258
259 // Checked before the key is attached to anything.
260 const dashboard = yield* Effect.fromResult(resolveDashboardBase(webURL));
261 // Lets the Dashboard's product analytics join the CLI's own events. Sent
262 // only while telemetry is enabled, and only on these requests.
263 const installId = yield* readInstallIdWhenTelemetryEnabled;
264 const url = `${dashboard.base}/api/cli/trpc/${procedure}`;
265 const request = HttpClientRequest.post(url).pipe(
266 HttpClientRequest.setHeaders({
267 ...cliRequestHeaders(),
268 accept: 'application/json',
269 authorization: `Bearer ${apiKey.value}`,
270 'x-org-id': orgId,
271 ...(Option.isSome(installId) ? { 'x-cli-install-id': installId.value } : {}),
272 }),
273 HttpClientRequest.bodyJsonUnsafe({ json: input })
274 );
275
276 // Sent exactly once: a retry, or a redirect followed by re-posting, could
277 // run a tool that already acted.
278 const { response, reply } = yield* Effect.gen(function* () {
279 const response = yield* httpClient.execute(request).pipe(
280 Effect.provideService(FetchHttpClient.RequestInit, { redirect: 'error' }),
281 Effect.mapError(
282 cause =>
283 new DashboardToolExecutionError({
284 reason: 'request',
285 message: `Could not reach the Composio Dashboard at ${dashboard.origin}. The request was not retried; if the tool may have already run, check before running it again.`,
286 cause,
287 })
288 )
289 );
290 const reply = yield* response.text.pipe(
291 Effect.flatMap(decodeProcedureReply),
292 Effect.mapError(
293 cause =>
294 new DashboardToolExecutionError({
295 reason: 'response',
296 status: response.status,
297 message: `The Composio Dashboard at ${dashboard.origin} returned an unexpected response (HTTP ${response.status}). The request was not retried.`,
298 cause,
299 })
300 )
301 );
302 return { response, reply };
303 }).pipe(
304 // Expiry interrupts the request, which aborts it; nothing is resent.
305 Effect.timeoutOrElse({
306 duration: DASHBOARD_REQUEST_TIMEOUT,
307 orElse: () =>
308 Effect.fail(
309 new DashboardToolExecutionError({
310 reason: 'timeout',
311 message: `The Composio Dashboard at ${dashboard.origin} did not answer within ${Duration.toMinutes(DASHBOARD_REQUEST_TIMEOUT)} minutes. The tool may still have run; check before running it again. The request was not retried.`,
312 })
313 ),
314 })
315 );
316
317 if ('error' in reply) {
318 const failure = reply.error.json;
319 const unauthorized = failure.data?.code === 'UNAUTHORIZED';
320 return yield* new DashboardToolExecutionError({
321 reason: unauthorized ? 'unauthorized' : 'dashboard',
322 status: failure.data?.httpStatus ?? response.status,
323 code: failure.data?.code,
324 message: unauthorized
325 ? `Authentication failed: ${failure.message}. ${LOGIN_HINT}`
326 : failure.message,
327 });
328 }
329
330 const outcome = reply.result.data.json;
331 if (!outcome.ok) {
332 return yield* Effect.fail(relayedApiError(url, outcome.status, outcome.error));
333 }
334 if (outcome.response.result_type === 'input_required') {
335 return yield* toolInputRequiredError(
336 `Tool ${input.tool_slug ?? input.slug}`,
337 outcome.response
338 );
339 }
340 // Not validated beyond `result_type`; see `ExecutionResult`.
341 return outcome.response as DashboardExecutionResult;
342 });
343
344 return {
345 /** Runs a tool through the Dashboard. Never retried. */
346 execute: (request: DashboardToolExecutionRequest) =>
347 call('execute', request.orgId, {
348 tool_slug: request.slug,
349 arguments: request.arguments,
350 ...(request.account ? { account: request.account } : {}),
351 }),
352 /** Runs a meta tool through the Dashboard. Never retried. */
353 executeMeta: (request: DashboardToolExecutionRequest) =>
354 call('executeMeta', request.orgId, {
355 slug: request.slug,
356 arguments: request.arguments,
357 }),
358 } as const;
359 });
360
361 export type DashboardToolExecutionShape = Effect.Success<typeof makeDashboardToolExecution>;
362
363 /**
364 * Sends consumer tool executions to the Composio Dashboard, which runs them on
365 * the backend and relays the backend's answer.
366 */
367 export class DashboardToolExecution extends Context.Service<
368 DashboardToolExecution,
369 DashboardToolExecutionShape
370 >()('services/DashboardToolExecution') {
371 static readonly Default = Layer.effect(DashboardToolExecution, makeDashboardToolExecution);
372 }