@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 502 lines 17.9 KB
Raw
1 import {
2 SessionCreateParams,
3 SessionPatchParams,
4 } from '@composio/client/resources/tool-router/session';
5 import {
6 ToolRouterConfigTags,
7 ToolRouterConfigTools,
8 ToolRouterConfigToolsSchema,
9 ToolRouterToolsParam,
10 ToolRouterConfigManageConnectionsSchema,
11 ToolRouterCreateSessionConfigSchema,
12 ToolRouterToolkitsParamSchema,
13 ToolRouterToolkitsDisabledConfigSchema,
14 ToolRouterToolkitsEnabledConfigSchema,
15 ToolRouterUpdateSessionConfigSchema,
16 ToolRouterUpdateManageConnectionsConfig,
17 ToolRouterUpdateManageConnectionsSchema,
18 ToolRouterUpdateExperimentalConfig,
19 ToolRouterSandboxConfig,
20 ToolRouterInstant,
21 ToolRouterProxyExecute,
22 ToolRouterHook,
23 } from '../types/toolRouter.types';
24 import type { LocalTool, LocalToolkit } from '../types/customTool.types';
25 import { ValidationError } from '../errors';
26 import { z } from 'zod';
27 import type { TypeOf } from 'zod/v3';
28
29 /** Parsed create input; the public `ToolRouterCreateSessionConfig` is a union over it. */
30 type ParsedCreateSessionConfig = TypeOf<typeof ToolRouterCreateSessionConfigSchema>;
31 /** Parsed update input; the public `ToolRouterUpdateSessionConfig` is a union over it. */
32 type ParsedUpdateSessionConfig = TypeOf<typeof ToolRouterUpdateSessionConfigSchema>;
33
34 /** A toolkit's entry in the session `tools` map, as sent on create and update. */
35 type SessionToolsEntry = NonNullable<SessionCreateParams['tools']>[string];
36
37 /** `require_approval` when the caller set an approval list, nothing otherwise. */
38 const requireApprovalParam = <T extends string>(
39 requireApproval: T[] | undefined
40 ): { require_approval?: T[] } =>
41 requireApproval !== undefined ? { require_approval: requireApproval } : {};
42
43 export const transformToolRouterToolsParams = (
44 params?: Record<string, ToolRouterToolsParam | ToolRouterConfigTools> | undefined
45 ): Record<string, SessionToolsEntry> | undefined => {
46 if (!params) {
47 return undefined;
48 }
49
50 if (typeof params === 'object') {
51 const result = Object.keys(params).reduce(
52 (acc, key) => {
53 if (Array.isArray(params[key])) {
54 acc[key] = { enable: params[key] };
55 } else if (typeof params[key] === 'object') {
56 const parsedResult = ToolRouterConfigToolsSchema.safeParse(params[key]);
57 if (parsedResult.success) {
58 const data = parsedResult.data;
59 if (Array.isArray(data)) {
60 acc[key] = { enable: data };
61 } else if ('enable' in data) {
62 acc[key] = { enable: data.enable, ...requireApprovalParam(data.requireApproval) };
63 } else if ('disable' in data) {
64 acc[key] = { disable: data.disable, ...requireApprovalParam(data.requireApproval) };
65 } else if ('tags' in data) {
66 const tags = transformToolRouterTagsParams(data.tags);
67 if (tags) {
68 acc[key] = { tags, ...requireApprovalParam(data.requireApproval) };
69 }
70 } else {
71 acc[key] = { require_approval: data.requireApproval };
72 }
73 } else {
74 throw new ValidationError(parsedResult.error.message);
75 }
76 } else {
77 acc[key] = { enable: params[key] };
78 }
79 return acc;
80 },
81 {} as Record<string, SessionToolsEntry>
82 );
83 return result;
84 }
85 };
86
87 export const transformToolRouterTagsParams = (
88 params?: ToolRouterConfigTags
89 ):
90 | Extract<NonNullable<SessionCreateParams['tools']>[string], { tags: unknown }>['tags']
91 | undefined => {
92 if (!params) {
93 return undefined;
94 }
95 if (Array.isArray(params)) {
96 return { enable: params };
97 } else if (typeof params === 'object') {
98 return {
99 enable: params.enable,
100 disable: params.disable,
101 ...requireApprovalParam(params.requireApproval),
102 };
103 }
104 };
105
106 export const transformToolRouterManageConnectionsParams = (
107 params?: boolean | z.infer<typeof ToolRouterConfigManageConnectionsSchema>
108 ): NonNullable<SessionCreateParams['manage_connections']> => {
109 if (params === undefined) {
110 // Default case when params is undefined
111 return {
112 enable: true,
113 };
114 }
115
116 if (typeof params === 'boolean') {
117 return {
118 enable: params,
119 };
120 }
121
122 // Parse the params using the zod schema for type safety
123 const parsedResult = ToolRouterConfigManageConnectionsSchema.safeParse(params);
124 if (!parsedResult.success) {
125 throw new ValidationError('Failed to parse manage connections config', {
126 cause: parsedResult.error,
127 });
128 }
129
130 const config = parsedResult.data;
131 return {
132 enable: config.enable ?? true,
133 callback_url: config.callbackUrl,
134 enable_wait_for_connections: config.waitForConnections,
135 };
136 };
137
138 export const resolveToolRouterSandboxConfig = (
139 config: Pick<ParsedCreateSessionConfig, 'sandbox' | 'workbench'>
140 ): ParsedCreateSessionConfig['sandbox'] | ParsedCreateSessionConfig['workbench'] => {
141 if (config.sandbox !== undefined && config.workbench !== undefined) {
142 throw new ValidationError(
143 'Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.'
144 );
145 }
146 return config.sandbox ?? config.workbench;
147 };
148
149 /** Local tools options, accepted under their current names and the deprecated `custom*` aliases. */
150 export type LocalToolsOptions = {
151 localTools?: LocalTool[];
152 localToolkits?: LocalToolkit[];
153 /** @deprecated Use `localTools` instead. */
154 customTools?: LocalTool[];
155 /** @deprecated Use `localToolkits` instead. */
156 customToolkits?: LocalToolkit[];
157 };
158
159 /**
160 * Resolves local tools and toolkits from `localTools` / `localToolkits` or
161 * their deprecated `customTools` / `customToolkits` aliases. `source` picks
162 * the option path named in the error: `experimental.*` on create, bare on use.
163 */
164 export const resolveLocalToolsOptions = (
165 options: LocalToolsOptions | undefined,
166 source: 'create' | 'use'
167 ): { tools?: LocalTool[]; toolkits?: LocalToolkit[] } => {
168 if (options?.localTools !== undefined && options.customTools !== undefined) {
169 throw new ValidationError(
170 source === 'create'
171 ? 'Pass either experimental.localTools or experimental.customTools, not both. experimental.customTools is a deprecated alias for experimental.localTools.'
172 : 'Pass either localTools or customTools, not both. customTools is a deprecated alias for localTools.'
173 );
174 }
175 if (options?.localToolkits !== undefined && options.customToolkits !== undefined) {
176 throw new ValidationError(
177 source === 'create'
178 ? 'Pass either experimental.localToolkits or experimental.customToolkits, not both. experimental.customToolkits is a deprecated alias for experimental.localToolkits.'
179 : 'Pass either localToolkits or customToolkits, not both. customToolkits is a deprecated alias for localToolkits.'
180 );
181 }
182 return {
183 tools: options?.localTools ?? options?.customTools,
184 toolkits: options?.localToolkits ?? options?.customToolkits,
185 };
186 };
187
188 export const transformToolRouterSandboxParams = (
189 params?: ParsedCreateSessionConfig['sandbox'] | ParsedCreateSessionConfig['workbench']
190 ): NonNullable<SessionCreateParams['workbench']> | undefined => {
191 if (!params) {
192 return undefined;
193 }
194
195 return {
196 enable: params.enable ?? true,
197 enable_proxy_execution: params.enableProxyExecution,
198 auto_offload_threshold: params.autoOffloadThreshold,
199 sandbox_size: params.sandboxSize,
200 };
201 };
202
203 /** @deprecated Renamed — use `transformToolRouterSandboxParams` instead. `workbench` is a backwards-compatible alias for `sandbox`. */
204 export const transformToolRouterWorkbenchParams = transformToolRouterSandboxParams;
205
206 /**
207 * PATCH-safe variant of transformToolRouterManageConnectionsParams.
208 * Does NOT apply defaults — only includes fields explicitly present in the input.
209 */
210 /**
211 * Widens the listed keys of a generated request type so `null` can travel on
212 * the wire. The spec does not mark these nullable until ComposioHQ/platform#13157
213 * lands.
214 */
215 type WithNull<T, K extends keyof T> = Omit<T, K> & { [P in K]?: NonNullable<T[P]> | null };
216
217 /**
218 * `manage_connections` as sent by `session.update()`. Only the supplied
219 * subfields travel; `callback_url: null` removes the stored callback.
220 */
221 export type SessionPatchManageConnectionsBody = WithNull<
222 NonNullable<SessionPatchParams['manage_connections']>,
223 'callback_url'
224 >;
225
226 /** `multi_account` as sent by `session.update()`; `null` removes the stored maximum. */
227 export type SessionPatchMultiAccountBody = WithNull<
228 NonNullable<SessionPatchParams['multi_account']>,
229 'max_accounts_per_toolkit'
230 >;
231
232 /** `experimental` as sent by `session.update()`; `null` removes a stored leaf. */
233 export type SessionPatchExperimentalBody = WithNull<
234 NonNullable<SessionPatchParams['experimental']>,
235 'permissions' | 'link_url_overwrite' | 'fast_mode' | 'submit_feedback'
236 >;
237
238 /**
239 * `hooks` as sent on create and update: `appliesTo` becomes `applies_to`.
240 * Create and patch take the same hook shape.
241 */
242 export const transformToolRouterHooksParams = (
243 hooks: ToolRouterHook[]
244 ): NonNullable<SessionCreateParams['hooks']> =>
245 hooks.map(({ appliesTo, ...hook }) => ({ ...hook, applies_to: appliesTo }));
246
247 /**
248 * Request body of `session.update()`. Extends the generated `SessionPatchParams`
249 * with the nullable policy blocks (`null` removes the stored override) and the
250 * `expected_config_version` root precondition, which the spec does not declare
251 * until ComposioHQ/platform#13157 lands.
252 */
253 export type SessionPatchBody = Omit<
254 WithNull<
255 SessionPatchParams,
256 'toolkits' | 'tools' | 'tags' | 'auth_configs' | 'preload' | 'search' | 'execute'
257 >,
258 'manage_connections' | 'multi_account' | 'experimental'
259 > & {
260 manage_connections?: SessionPatchManageConnectionsBody | null;
261 multi_account?: SessionPatchMultiAccountBody | null;
262 experimental?: SessionPatchExperimentalBody | null;
263 expected_config_version?: number;
264 };
265
266 /** `proxy_execute` as sent on create and update: a boolean becomes `{ enable }`. */
267 export const transformToolRouterProxyExecuteParams = (
268 config: ToolRouterProxyExecute
269 ): NonNullable<SessionCreateParams['proxy_execute']> =>
270 typeof config === 'boolean' ? { enable: config } : config;
271
272 export const transformToolRouterInstantParams = (
273 config: ToolRouterInstant
274 ): NonNullable<SessionCreateParams['instant']> => {
275 if (config === false) return false;
276 return {
277 ...(config.toolkits !== undefined && { toolkits: config.toolkits }),
278 ...(config.tools !== undefined && { tools: config.tools }),
279 ...(config.returnInstantCharge !== undefined && {
280 return_instant_charge: config.returnInstantCharge,
281 }),
282 ...(config.returnPricesInSearch !== undefined && {
283 return_prices_in_search: config.returnPricesInSearch,
284 }),
285 };
286 };
287
288 export const transformToolRouterUpdateManageConnectionsParams = (
289 params: boolean | ToolRouterUpdateManageConnectionsConfig
290 ): SessionPatchManageConnectionsBody => {
291 if (typeof params === 'boolean') {
292 return { enable: params };
293 }
294
295 const parsedResult = ToolRouterUpdateManageConnectionsSchema.safeParse(params);
296 if (!parsedResult.success) {
297 throw new ValidationError('Failed to parse manage connections config', {
298 cause: parsedResult.error,
299 });
300 }
301
302 const config = parsedResult.data;
303 const result: SessionPatchManageConnectionsBody = {};
304 if (config.enable !== undefined) {
305 result.enable = config.enable;
306 }
307 if (config.callbackUrl !== undefined) {
308 result.callback_url = config.callbackUrl;
309 }
310 if (config.waitForConnections !== undefined) {
311 result.enable_wait_for_connections = config.waitForConnections;
312 }
313 if (config.enableConnectionRemoval !== undefined) {
314 result.enable_connection_removal = config.enableConnectionRemoval;
315 }
316 return result;
317 };
318
319 const transformToolRouterUpdateExperimentalParams = (
320 config: ToolRouterUpdateExperimentalConfig
321 ): SessionPatchExperimentalBody => {
322 const result: SessionPatchExperimentalBody = {};
323 if (config.permissions !== undefined) {
324 result.permissions = config.permissions;
325 }
326 if (config.linkUrlOverwrite !== undefined) {
327 result.link_url_overwrite = config.linkUrlOverwrite;
328 }
329 if (config.fastMode !== undefined) {
330 result.fast_mode = config.fastMode;
331 }
332 if (config.submitFeedback !== undefined) {
333 result.submit_feedback = config.submitFeedback;
334 }
335 if (config.sessionConfigId !== undefined) {
336 result.session_config_id = config.sessionConfigId;
337 }
338 if (config.noElicitationSupportFallback !== undefined) {
339 result.no_elicitation_support_fallback = config.noElicitationSupportFallback;
340 }
341 return result;
342 };
343
344 /**
345 * PATCH-safe variant of transformToolRouterSandboxParams.
346 * Does NOT apply `enable ?? true` default — only includes fields explicitly present.
347 */
348 export const transformToolRouterUpdateSandboxParams = (
349 params: Partial<ToolRouterSandboxConfig>
350 ): NonNullable<SessionPatchParams['workbench']> => {
351 const result: Record<string, unknown> = {};
352 if (params.enable !== undefined) {
353 result.enable = params.enable;
354 }
355 if (params.enableProxyExecution !== undefined) {
356 result.enable_proxy_execution = params.enableProxyExecution;
357 }
358 if (params.autoOffloadThreshold !== undefined) {
359 result.auto_offload_threshold = params.autoOffloadThreshold;
360 }
361 if (params.sandboxSize !== undefined) {
362 result.sandbox_size = params.sandboxSize;
363 }
364 return result as NonNullable<SessionPatchParams['workbench']>;
365 };
366
367 /** @deprecated Renamed — use `transformToolRouterUpdateSandboxParams` instead. `workbench` is a backwards-compatible alias for `sandbox`. */
368 export const transformToolRouterUpdateWorkbenchParams = transformToolRouterUpdateSandboxParams;
369
370 export const transformToolRouterMultiAccountParams = (
371 params?: ParsedCreateSessionConfig['multiAccount']
372 ): NonNullable<SessionCreateParams['multi_account']> | undefined => {
373 if (!params) {
374 return undefined;
375 }
376
377 const transformedParams = {
378 enable: params.enable,
379 max_accounts_per_toolkit: params.maxAccountsPerToolkit,
380 require_explicit_selection:
381 params.requireExplicitSelection ?? (params.enable ? true : undefined),
382 };
383
384 if (
385 transformedParams.enable === undefined &&
386 transformedParams.max_accounts_per_toolkit === undefined &&
387 transformedParams.require_explicit_selection === undefined
388 ) {
389 return undefined;
390 }
391
392 return transformedParams;
393 };
394
395 export const transformToolRouterToolkitsParams = (
396 params?: ParsedCreateSessionConfig['toolkits']
397 ): NonNullable<SessionCreateParams['toolkits']> | undefined => {
398 if (!params) {
399 return undefined;
400 }
401
402 // If it's an array, convert to enable format
403 if (Array.isArray(params)) {
404 return { enable: params };
405 }
406
407 if ('enable' in params) {
408 return { enable: params.enable, ...requireApprovalParam(params.requireApproval) };
409 }
410 if ('disable' in params) {
411 return { disable: params.disable, ...requireApprovalParam(params.requireApproval) };
412 }
413 return { require_approval: params.requireApproval };
414 };
415
416 /**
417 * Request body of `session.update()`. Every key present in `config` is sent,
418 * including `null` (remove the stored override) and empty collections (an
419 * empty toolkit allowlist denies every app toolkit). The
420 * `expectedConfigVersion` option is not a body field here: the session
421 * adds it only when the caller explicitly supplies a numeric version.
422 */
423 export const transformToolRouterUpdateParams = (
424 config: ParsedUpdateSessionConfig
425 ): SessionPatchBody => {
426 const params: SessionPatchBody = {};
427
428 if (config.toolkits !== undefined) {
429 params.toolkits =
430 config.toolkits === null ? null : transformToolRouterToolkitsParams(config.toolkits);
431 }
432 if (config.instant !== undefined) {
433 params.instant = transformToolRouterInstantParams(config.instant);
434 }
435 if (config.tools !== undefined) {
436 params.tools = config.tools === null ? null : transformToolRouterToolsParams(config.tools);
437 }
438 if (config.tags !== undefined) {
439 params.tags = config.tags === null ? null : transformToolRouterTagsParams(config.tags);
440 }
441 if (config.authConfigs !== undefined) {
442 params.auth_configs = config.authConfigs;
443 }
444 if (config.connectedAccounts !== undefined) {
445 params.connected_accounts = config.connectedAccounts;
446 }
447 if (config.manageConnections !== undefined) {
448 params.manage_connections =
449 config.manageConnections === null
450 ? null
451 : transformToolRouterUpdateManageConnectionsParams(config.manageConnections);
452 }
453 const sandboxConfig = config.sandbox !== undefined ? config.sandbox : config.workbench;
454 if (sandboxConfig !== undefined) {
455 params.workbench =
456 sandboxConfig === null ? null : transformToolRouterUpdateSandboxParams(sandboxConfig);
457 }
458 if (config.multiAccount !== undefined) {
459 if (config.multiAccount === null) {
460 params.multi_account = null;
461 } else {
462 const ma: SessionPatchMultiAccountBody = {};
463 if (config.multiAccount.enable !== undefined) ma.enable = config.multiAccount.enable;
464 if (config.multiAccount.maxAccountsPerToolkit !== undefined)
465 ma.max_accounts_per_toolkit = config.multiAccount.maxAccountsPerToolkit;
466 if (config.multiAccount.requireExplicitSelection !== undefined)
467 ma.require_explicit_selection = config.multiAccount.requireExplicitSelection;
468 params.multi_account = ma;
469 }
470 }
471 if (config.proxyExecute !== undefined) {
472 params.proxy_execute =
473 config.proxyExecute === null
474 ? null
475 : transformToolRouterProxyExecuteParams(config.proxyExecute);
476 }
477 if (config.hooks !== undefined) {
478 params.hooks = config.hooks === null ? null : transformToolRouterHooksParams(config.hooks);
479 }
480 if (config.preload !== undefined) {
481 params.preload = config.preload;
482 }
483 if (config.search !== undefined) {
484 params.search = config.search;
485 }
486 if (config.execute !== undefined) {
487 params.execute =
488 config.execute === null
489 ? null
490 : config.execute.enableMultiExecute === undefined
491 ? {}
492 : { enable_multi_execute: config.execute.enableMultiExecute };
493 }
494 if (config.experimental !== undefined) {
495 params.experimental =
496 config.experimental === null
497 ? null
498 : transformToolRouterUpdateExperimentalParams(config.experimental);
499 }
500
501 return params;
502 };