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 151 lines 5.13 KB
Raw
1 /**
2 * @fileoverview Session context implementation injected into custom tool execute functions.
3 */
4 import { Composio as ComposioClient } from '@composio/client';
5 import type {
6 SessionContext,
7 CustomToolsMap,
8 InlineCustomToolsWirePayload,
9 } from '../types/customTool.types';
10 import type {
11 SessionProxyExecuteParams,
12 ToolRouterSessionExecuteResponse,
13 ToolRouterSessionProxyExecuteResponse,
14 } from '../types/toolRouter.types';
15 import {
16 SessionProxyExecuteParamsSchema,
17 ToolRouterSessionExecuteResponseSchema,
18 } from '../types/toolRouter.types';
19 import { ValidationError } from '../errors';
20 import { handleToolExecutionError } from '../errors/ToolErrors';
21 import { transformProxyParams } from './proxyParamsTransform';
22 import {
23 assertUnambiguousCustomToolSlug,
24 findCustomTool,
25 executeCustomTool,
26 } from './customToolExecution';
27 import {
28 transformExecuteResponse,
29 transformProxyExecuteResponse,
30 } from '../utils/transformers/toolRouterResponseTransform';
31 import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session';
32 import { withCancellation } from '../utils/cancellation';
33 import { withoutRetries } from '../utils/retries';
34
35 /**
36 * Concrete implementation of SessionContext.
37 * One instance is created per session (or per multi-execute batch) and shared
38 * across all custom tool invocations, including sibling routing.
39 *
40 * When `customToolsMap` is provided, `execute()` checks local tools first
41 * before falling back to the backend API. This allows tool A to call tool B
42 * via `session.execute('B', ...)` without hitting the network.
43 *
44 * @internal Internal implementation detail. Not exported from `@composio/core`
45 * and not part of the public API surface — custom tools receive a
46 * `SessionContext` instance via their execute function; they never reference
47 * this class directly. Excluded from the generated SDK reference.
48 */
49 export class SessionContextImpl implements SessionContext {
50 public readonly userId: string;
51
52 /**
53 * Per-execution AbortSignal. Never set on the base instance; `executeCustomTool`
54 * grafts it onto a per-call `Object.create` child so concurrent executions
55 * sharing this context don't observe each other's signal. Declared here (rather
56 * than read via a cast) so the contract is explicit.
57 */
58 public readonly signal?: AbortSignal;
59
60 constructor(
61 private readonly client: ComposioClient,
62 userId: string,
63 private readonly sessionId: string,
64 private readonly customToolsMap?: CustomToolsMap,
65 private readonly inlineCustomToolsPayload?: InlineCustomToolsWirePayload
66 ) {
67 this.userId = userId;
68 }
69
70 /**
71 * Execute any tool from within a custom tool.
72 * Routes to sibling local tools in-process when available,
73 * otherwise delegates to the backend API.
74 *
75 * Returns the same response shape as session.execute().
76 */
77 async execute(
78 toolSlug: string,
79 arguments_: Record<string, unknown>
80 ): Promise<ToolRouterSessionExecuteResponse> {
81 const signal = this.signal;
82 const requestOptions = signal ? { signal } : undefined;
83
84 const entry = findCustomTool(this.customToolsMap, toolSlug);
85 if (entry) {
86 const result = await executeCustomTool(entry, arguments_, this, { signal });
87 return ToolRouterSessionExecuteResponseSchema.parse({
88 data: result.data,
89 error: result.error,
90 logId: '',
91 resultType: result.successful ? 'completed' : 'failed',
92 });
93 }
94 assertUnambiguousCustomToolSlug(this.customToolsMap, toolSlug);
95
96 const executeParams: SessionExecuteParams = {
97 tool_slug: toolSlug,
98 arguments: arguments_,
99 };
100 if (this.inlineCustomToolsPayload) {
101 executeParams.experimental = this.inlineCustomToolsPayload;
102 }
103
104 const response = await withCancellation(
105 () =>
106 this.client.toolRouter.session.execute(
107 this.sessionId,
108 executeParams,
109 withoutRetries(requestOptions)
110 ),
111 requestOptions?.signal
112 ).catch((error: unknown) => {
113 throw handleToolExecutionError(toolSlug, error as Error);
114 });
115 return ToolRouterSessionExecuteResponseSchema.parse(
116 transformExecuteResponse(response, toolSlug)
117 );
118 }
119
120 /**
121 * Proxy API calls through Composio's auth layer.
122 * The backend resolves the connected account from the toolkit within the session.
123 */
124 async proxyExecute(
125 params: SessionProxyExecuteParams
126 ): Promise<ToolRouterSessionProxyExecuteResponse> {
127 const validated = SessionProxyExecuteParamsSchema.safeParse(params);
128 if (!validated.success) {
129 throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });
130 }
131
132 const signal = this.signal;
133 const requestOptions = signal ? { signal } : undefined;
134
135 const clientParams = transformProxyParams(validated.data);
136 const response = await withCancellation(
137 () =>
138 this.client.toolRouter.session.proxyExecute(
139 this.sessionId,
140 clientParams,
141 withoutRetries(requestOptions)
142 ),
143 requestOptions?.signal
144 );
145
146 return transformProxyExecuteResponse(
147 response,
148 `${validated.data.method} proxy call for toolkit ${validated.data.toolkit}`
149 );
150 }
151 }