@devries-cameron20 / composio Mirror · read-only
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, 04:45 UTC

next
ts 141 lines 5.13 KB
Raw
1 import { isAPIError, type ComposioClientShape } from '@composio/client/effect';
2 import type { SessionExecuteMetaParams } from '@composio/client/resources/tool-router';
3 import { Effect, Layer, Schema } from 'effect';
4 import { HttpClient, HttpClientError, HttpClientResponse } from 'effect/http';
5 import { DashboardToolExecution } from 'src/services/dashboard-tool-execution';
6
7 /** One request the CLI sent to the test Dashboard. */
8 export interface DashboardTestRequest {
9 readonly method: string;
10 readonly url: string;
11 readonly headers: Readonly<Record<string, string>>;
12 /** The decoded JSON body, or `undefined` when there is none. */
13 readonly body: unknown;
14 }
15
16 /** Answers a Dashboard request; a rejection reaches the CLI as a network failure. */
17 export type DashboardTestResponder = (
18 request: DashboardTestRequest
19 ) => Response | Promise<Response>;
20
21 const DashboardProcedureInput = Schema.Struct({
22 json: Schema.Struct({
23 tool_slug: Schema.optional(Schema.String),
24 slug: Schema.optional(Schema.String),
25 arguments: Schema.Record(Schema.String, Schema.Unknown),
26 account: Schema.optional(Schema.String),
27 session: Schema.optional(Schema.Unknown),
28 }),
29 });
30
31 /** A Dashboard procedure answer in the wire envelope the CLI decodes. */
32 export const dashboardProcedureResult = (outcome: unknown, status = 200): Response =>
33 Response.json({ result: { data: { json: outcome } } }, { status });
34
35 /** A Dashboard-level failure in the wire envelope the CLI decodes. */
36 export const dashboardProcedureError = (params: {
37 readonly code: string;
38 readonly httpStatus: number;
39 readonly message: string;
40 }): Response =>
41 Response.json(
42 {
43 error: {
44 json: {
45 message: params.message,
46 data: { code: params.code, httpStatus: params.httpStatus },
47 },
48 },
49 },
50 { status: params.httpStatus }
51 );
52
53 /**
54 * What the real Dashboard does with a request: it creates a Tool Router
55 * session itself and executes on `toolRouter`, relaying the answer, or a
56 * backend 4xx as data. Session settings from the CLI are refused.
57 */
58 export const relayThroughToolRouter =
59 (toolRouter: ComposioClientShape['toolRouter']) => (request: DashboardTestRequest) =>
60 Effect.gen(function* () {
61 const { session, account, ...call } = Schema.decodeUnknownSync(DashboardProcedureInput)(
62 request.body
63 ).json;
64 if (session !== undefined) {
65 return dashboardProcedureError({
66 code: 'BAD_REQUEST',
67 httpStatus: 400,
68 message: "Unrecognized key(s) in object: 'session'",
69 });
70 }
71 const created = yield* toolRouter.session.create({ user_id: 'user_resolved_by_dashboard' });
72 const response = yield* request.url.endsWith('/executeMeta')
73 ? toolRouter.session.executeMeta(created.session_id, {
74 slug: call.slug as SessionExecuteMetaParams['slug'],
75 arguments: call.arguments,
76 })
77 : toolRouter.session.execute(created.session_id, {
78 tool_slug: call.tool_slug ?? '',
79 arguments: call.arguments,
80 ...(account ? { account } : {}),
81 });
82 return dashboardProcedureResult({ ok: true, response });
83 }).pipe(
84 Effect.catch(error =>
85 Effect.succeed(
86 isAPIError(error) && error.status < 500
87 ? dashboardProcedureResult({
88 ok: false,
89 status: error.status,
90 error: error.details ?? { message: error.message },
91 })
92 : dashboardProcedureError({
93 code: 'INTERNAL_SERVER_ERROR',
94 httpStatus: 500,
95 message: error instanceof Error ? error.message : `${error}`,
96 })
97 )
98 )
99 );
100
101 /**
102 * The real `DashboardToolExecution` over an `HttpClient` that answers with
103 * `respond`, or relays to `toolRouter` like the real Dashboard when the test
104 * leaves it out, so the request the CLI builds and the reply it decodes are
105 * both exercised. Needs `ComposioUserContext` for the login it sends.
106 */
107 export const DashboardToolExecutionTest = (params: {
108 readonly toolRouter: ComposioClientShape['toolRouter'];
109 readonly respond?: DashboardTestResponder;
110 }) => {
111 const relay = relayThroughToolRouter(params.toolRouter);
112 const answer = (request: DashboardTestRequest) =>
113 params.respond
114 ? Effect.tryPromise({ try: async () => params.respond!(request), catch: cause => cause })
115 : relay(request);
116 return Layer.provide(
117 DashboardToolExecution.Default,
118 Layer.succeed(
119 HttpClient.HttpClient,
120 HttpClient.make((request, url) =>
121 answer({
122 method: request.method,
123 url: url.toString(),
124 headers: { ...request.headers },
125 body:
126 request.body._tag === 'Uint8Array'
127 ? JSON.parse(new TextDecoder().decode(request.body.body))
128 : undefined,
129 }).pipe(
130 Effect.map(response => HttpClientResponse.fromWeb(request, response)),
131 Effect.mapError(
132 cause =>
133 new HttpClientError.HttpClientError({
134 reason: new HttpClientError.TransportError({ request, cause }),
135 })
136 )
137 )
138 )
139 )
140 );
141 };