Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { telemetry } from '../telemetry/Telemetry'; |
| 2 | import { Composio as ComposioClient, BadRequestError, ConflictError } from '@composio/client'; |
| 3 | import type { BaseComposioProvider } from '../provider/BaseProvider'; |
| 4 | import type { ComposioConfig } from '../composio'; |
| 5 | import type { ComposioRequestOptions } from '../types/requestOptions.types'; |
| 6 | import { withCancellation } from '../utils/cancellation'; |
| 7 | import { withoutRetries } from '../utils/retries'; |
| 8 | import { ComposioRequestCancelledError } from '../errors/SDKErrors'; |
| 9 | import { handleToolExecutionError } from '../errors/ToolErrors'; |
| 10 | import { |
| 11 | ComposioSessionConfigConflictError, |
| 12 | ComposioToolInputRequiredError, |
| 13 | } from '../errors/ToolRouterErrors'; |
| 14 | import { |
| 15 | ToolRouterMCPServerConfig, |
| 16 | SessionExperimental, |
| 17 | ToolRouterToolkitsOptions, |
| 18 | ToolRouterToolkitsOptionsSchema, |
| 19 | ToolRouterSessionSearchResponse, |
| 20 | ToolRouterSessionSearchResponseSchema, |
| 21 | ToolRouterSessionExecuteResponse, |
| 22 | ToolRouterSessionExecuteResponseSchema, |
| 23 | ToolRouterSessionProxyExecuteResponse, |
| 24 | ToolRouterSessionExecuteOptions, |
| 25 | ToolRouterSessionExecuteMetaOptions, |
| 26 | ToolRouterSessionMetaToolSlug, |
| 27 | ToolRouterSessionConfig, |
| 28 | ToolRouterSessionMetadata, |
| 29 | ToolRouterSessionPreloadConfig, |
| 30 | ToolRouterSessionWorkbenchConfig, |
| 31 | ToolRouterSessionWarning, |
| 32 | ToolRouterUpdateSessionConfig, |
| 33 | ToolRouterUpdateSessionConfigSchema, |
| 34 | ToolRouterSessionEnsureConnectedOptions, |
| 35 | ToolRouterSessionEnsureConnectedOptionsSchema, |
| 36 | ToolRouterSessionEnsureConnectedResult, |
| 37 | ToolRouterSessionListConfigHistoryOptions, |
| 38 | ToolRouterSessionListConfigHistoryOptionsSchema, |
| 39 | type ToolRouterSessionListConfigHistoryResponse, |
| 40 | type ToolRouterSessionDeleteResponse, |
| 41 | } from '../types/toolRouter.types'; |
| 42 | import { |
| 43 | transformSearchResponse, |
| 44 | transformExecuteResponse, |
| 45 | transformProxyExecuteResponse, |
| 46 | } from '../utils/transformers/toolRouterResponseTransform'; |
| 47 | import { SessionMetaToolOptions } from '../types/modifiers.types'; |
| 48 | import { ConnectionRequest } from '../types/connectionRequest.types'; |
| 49 | import { createConnectionRequest } from './ConnectionRequest'; |
| 50 | import { |
| 51 | ConnectedAccountExperimentalSchema, |
| 52 | ConnectedAccountStatuses, |
| 53 | ConnectedAccountType, |
| 54 | ConnectedAccountAclConfig, |
| 55 | } from '../types/connectedAccounts.types'; |
| 56 | import { ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT, serializeExperimentalForWire } from './Experimental'; |
| 57 | import { z } from 'zod/v3'; |
| 58 | import { transform } from '../utils/transform'; |
| 59 | import { ToolkitConnectionStateSchema } from '../types/toolRouter.types'; |
| 60 | import { |
| 61 | ComposioAclOnlyForSharedError, |
| 62 | ComposioInvalidModifierError, |
| 63 | ValidationError, |
| 64 | } from '../errors'; |
| 65 | import { Tools } from './Tools'; |
| 66 | import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount'; |
| 67 | import type { |
| 68 | CustomToolsMap, |
| 69 | CustomToolsMapEntry, |
| 70 | SessionContext, |
| 71 | RegisteredLocalTool, |
| 72 | RegisteredLocalToolkit, |
| 73 | } from '../types/customTool.types'; |
| 74 | import { ToolSchema, type Tool, type ToolExecuteResponse } from '../types/tool.types'; |
| 75 | import type { SessionProxyExecuteParams } from '../types/toolRouter.types'; |
| 76 | import type { |
| 77 | SessionExecuteMetaParams, |
| 78 | SessionExecuteParams, |
| 79 | SessionLinkParams, |
| 80 | SessionPatchParams, |
| 81 | SessionPatchResponse, |
| 82 | } from '@composio/client/resources/tool-router/session'; |
| 83 | import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types'; |
| 84 | import { SessionContextImpl } from './SessionContext'; |
| 85 | import { |
| 86 | assertUnambiguousCustomToolSlug, |
| 87 | findCustomTool, |
| 88 | executeCustomTool, |
| 89 | } from './customToolExecution'; |
| 90 | import { |
| 91 | findCustomToolMapEntryByFinalSlug, |
| 92 | findCustomToolMapEntryByToolkitAndOriginalSlug, |
| 93 | } from './CustomTool'; |
| 94 | import { transformProxyParams } from './proxyParamsTransform'; |
| 95 | import { transformToolRouterUpdateParams } from '../lib/toolRouterParams'; |
| 96 | import { parseSessionConfigInput } from '../lib/sessionConfigConflict'; |
| 97 | import { getSourceSessionConfig } from '../lib/toolRouterSourceSessionConfig'; |
| 98 | import { deleteToolRouterSession } from '../lib/toolRouterSessionDelete'; |
| 99 | |
| 100 | const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL'; |
| 101 | |
| 102 | /** The request fields that carry the user's answers to an earlier `input_required` call. */ |
| 103 | function inputResponseParams( |
| 104 | options: ToolRouterSessionExecuteMetaOptions | undefined |
| 105 | ): Pick<SessionExecuteParams, 'input_responses' | 'request_state'> { |
| 106 | return { |
| 107 | ...(options?.inputResponses !== undefined && { input_responses: options.inputResponses }), |
| 108 | ...(options?.requestState !== undefined && { request_state: options.requestState }), |
| 109 | }; |
| 110 | } |
| 111 | export const DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX = |
| 112 | '[Direct tool - call directly, no search needed beforehand.]'; |
| 113 | |
| 114 | /** |
| 115 | * Options accepted by {@link ToolRouterSession.authorize}. |
| 116 | * |
| 117 | * Validated at the SDK boundary so callers get clear `ValidationError`s for |
| 118 | * oversized ACL lists or invalid `userId`s — same caps as the equivalent |
| 119 | * `composio.connectedAccounts.link()` path (≤1000 entries per list, each |
| 120 | * `userId` 1..256 characters). |
| 121 | */ |
| 122 | const AuthorizeOptionsSchema = z.object({ |
| 123 | callbackUrl: z.string().optional(), |
| 124 | alias: z.string().optional(), |
| 125 | experimental: ConnectedAccountExperimentalSchema.optional(), |
| 126 | }); |
| 127 | |
| 128 | /** |
| 129 | * A Composio session — the object returned by `composio.sessions.create(...)` |
| 130 | * and `composio.sessions.use(...)` (also reachable via the top-level |
| 131 | * `composio.create(...)` / `composio.use(...)` aliases). |
| 132 | * |
| 133 | * This is the canonical session surface. Use it to fetch session-scoped tools, |
| 134 | * authorize toolkits, search, and execute tools. The public return type is |
| 135 | * `Session` (with `mcp` surfaced, returned when `{ mcp: true }` is passed) or |
| 136 | * `SessionWithoutMcp` (the default, with `mcp` omitted from the type); this |
| 137 | * class is the concrete runtime form behind both. |
| 138 | * |
| 139 | * @see {@link Sessions} for the `composio.sessions` factory. |
| 140 | */ |
| 141 | export class ToolRouterSession< |
| 142 | TToolCollection, |
| 143 | TTool, |
| 144 | TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>, |
| 145 | > { |
| 146 | public readonly sessionId: string; |
| 147 | /** Hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`). Exists on every session at runtime, but only surfaced in the type when the session is created with `{ mcp: true }` (which returns `Session`); the default `SessionWithoutMcp` omits `mcp`, so MCP is an explicit opt-in. See https://docs.composio.dev/docs/sessions-via-mcp */ |
| 148 | public readonly mcp: ToolRouterMCPServerConfig; |
| 149 | public readonly experimental: SessionExperimental; |
| 150 | /** |
| 151 | * The session's current configuration (policy snapshot and runtime |
| 152 | * settings). Refreshed in place by `update()`. For saved, reusable Session |
| 153 | * configs, see `composio.sessionConfigs`. |
| 154 | */ |
| 155 | public config: ToolRouterSessionConfig; |
| 156 | public preload: ToolRouterSessionPreloadConfig; |
| 157 | /** Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side. */ |
| 158 | public sandbox?: ToolRouterSessionWorkbenchConfig; |
| 159 | /** |
| 160 | * Version of the server-side configuration this object last observed. |
| 161 | * Refreshed in place by `update()`. Pass it as `expectedConfigVersion` to |
| 162 | * make an update conditional. |
| 163 | */ |
| 164 | public configVersion?: number; |
| 165 | public warnings: ToolRouterSessionWarning[]; |
| 166 | private readonly preloadedCustomToolSlugs: string[]; |
| 167 | private readonly inlineCustomToolsPayload: ToolRouterSessionMetadata['inlineCustomToolsPayload']; |
| 168 | |
| 169 | /** Singleton session context — shared across all custom tool executions */ |
| 170 | private readonly sessionContext?: SessionContext; |
| 171 | |
| 172 | constructor( |
| 173 | private readonly client: ComposioClient, |
| 174 | private readonly sdkConfig: ComposioConfig<TProvider> | undefined, |
| 175 | sessionId: string, |
| 176 | mcp: ToolRouterMCPServerConfig, |
| 177 | experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt' | 'sourceSessionConfig'>, |
| 178 | private readonly customToolsMap?: CustomToolsMap, |
| 179 | private readonly userId?: string, |
| 180 | metadata?: ToolRouterSessionMetadata |
| 181 | ) { |
| 182 | const config: ToolRouterSessionConfig = metadata?.config ?? { |
| 183 | user_id: userId ?? '', |
| 184 | execute: {}, |
| 185 | search: {}, |
| 186 | preload: { tools: [] }, |
| 187 | instant: false, |
| 188 | }; |
| 189 | if (customToolsMap && !userId) { |
| 190 | throw new Error('userId is required when custom tools are bound to a session.'); |
| 191 | } |
| 192 | this.sessionId = sessionId; |
| 193 | this.mcp = mcp; |
| 194 | this.experimental = { |
| 195 | assistivePrompt: experimentalOverrides?.assistivePrompt, |
| 196 | files: new ToolRouterSessionFilesMount(client, sessionId), |
| 197 | sourceSessionConfig: experimentalOverrides?.sourceSessionConfig, |
| 198 | }; |
| 199 | this.config = config; |
| 200 | this.preload = metadata?.preload ?? config.preload; |
| 201 | this.sandbox = metadata?.workbench ?? config.workbench; |
| 202 | this.configVersion = metadata?.configVersion; |
| 203 | this.warnings = metadata?.warnings ?? []; |
| 204 | this.preloadedCustomToolSlugs = metadata?.preloadedCustomToolSlugs ?? []; |
| 205 | this.inlineCustomToolsPayload = metadata?.inlineCustomToolsPayload; |
| 206 | |
| 207 | // Create singleton session context if custom tools are bound |
| 208 | if (customToolsMap && userId) { |
| 209 | this.sessionContext = new SessionContextImpl( |
| 210 | client, |
| 211 | userId, |
| 212 | sessionId, |
| 213 | customToolsMap, |
| 214 | this.inlineCustomToolsPayload |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | telemetry.instrument(this, 'ToolRouterSession'); |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * Resolved sandbox config for the session. |
| 223 | * |
| 224 | * @deprecated Use `session.sandbox` instead. `workbench` is a backwards-compatible alias and will be removed in a future release. |
| 225 | */ |
| 226 | public get workbench(): ToolRouterSessionWorkbenchConfig | undefined { |
| 227 | return this.sandbox; |
| 228 | } |
| 229 | |
| 230 | public set workbench(value: ToolRouterSessionWorkbenchConfig | undefined) { |
| 231 | this.sandbox = value; |
| 232 | } |
| 233 | |
| 234 | /** |
| 235 | * Get the tools available in the session, formatted for your AI framework. |
| 236 | * Requires a provider to be configured in the Composio constructor. |
| 237 | * |
| 238 | * When custom tools are bound to the session, execution of COMPOSIO_MULTI_EXECUTE_TOOL |
| 239 | * is intercepted: local tools are executed in-process, remote tools are sent to the backend. |
| 240 | */ |
| 241 | async tools( |
| 242 | modifiers?: SessionMetaToolOptions, |
| 243 | requestOptions?: ComposioRequestOptions |
| 244 | ): Promise<ReturnType<TProvider['wrapTools']>> { |
| 245 | const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.sdkConfig); |
| 246 | const rawTools = await ToolsModel.getRawToolRouterSessionTools( |
| 247 | this.sessionId, |
| 248 | undefined, |
| 249 | requestOptions |
| 250 | ); |
| 251 | const tools = await this.applySchemaModifier(rawTools, modifiers?.modifySchema); |
| 252 | const sessionTools = await this.addPreloadedCustomTools(tools, modifiers); |
| 253 | const rawToolBySlug = new Map(rawTools.map(tool => [tool.slug.toUpperCase(), tool])); |
| 254 | |
| 255 | if (this.hasCustomTools()) { |
| 256 | // Create an execute function that splits local/remote tools in COMPOSIO_MULTI_EXECUTE_TOOL |
| 257 | const routingExecuteFn = async ( |
| 258 | toolSlug: string, |
| 259 | input: Record<string, unknown> |
| 260 | ): Promise<ToolExecuteResponse> => { |
| 261 | if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) { |
| 262 | return this.routeMultiExecute(input, ToolsModel, rawTools, modifiers); |
| 263 | } |
| 264 | const customTool = findCustomTool(this.customToolsMap, toolSlug); |
| 265 | if (customTool) { |
| 266 | return executeCustomTool(customTool, input, this.sessionContext!); |
| 267 | } |
| 268 | assertUnambiguousCustomToolSlug(this.customToolsMap, toolSlug); |
| 269 | return this.executeBackendSessionTool( |
| 270 | ToolsModel, |
| 271 | toolSlug, |
| 272 | input, |
| 273 | modifiers, |
| 274 | rawToolBySlug.get(toolSlug.toUpperCase()) |
| 275 | ); |
| 276 | }; |
| 277 | |
| 278 | if (!this.sdkConfig?.provider) { |
| 279 | throw new Error( |
| 280 | 'A provider is required when using custom tools with session.tools(). ' + |
| 281 | 'Pass a provider in the Composio constructor.' |
| 282 | ); |
| 283 | } |
| 284 | return this.sdkConfig.provider.wrapTools(sessionTools, routingExecuteFn) as ReturnType< |
| 285 | TProvider['wrapTools'] |
| 286 | >; |
| 287 | } |
| 288 | |
| 289 | // Standard path (no local tools) |
| 290 | const wrappedTools = modifiers?.modifySchema |
| 291 | ? ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers, rawTools) |
| 292 | : ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers); |
| 293 | return wrappedTools as ReturnType<TProvider['wrapTools']>; |
| 294 | } |
| 295 | |
| 296 | private async applySchemaModifier( |
| 297 | tools: Tool[], |
| 298 | modifier?: SessionMetaToolOptions['modifySchema'] |
| 299 | ): Promise<Tool[]> { |
| 300 | if (!modifier) { |
| 301 | return tools; |
| 302 | } |
| 303 | if (typeof modifier !== 'function') { |
| 304 | throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.'); |
| 305 | } |
| 306 | return Promise.all( |
| 307 | tools.map(tool => |
| 308 | modifier({ |
| 309 | toolSlug: tool.slug, |
| 310 | toolkitSlug: tool.toolkit?.slug ?? 'unknown', |
| 311 | schema: ToolSchema.parse(tool), |
| 312 | }) |
| 313 | ) |
| 314 | ); |
| 315 | } |
| 316 | |
| 317 | private async addPreloadedCustomTools( |
| 318 | tools: Tool[], |
| 319 | modifiers?: SessionMetaToolOptions |
| 320 | ): Promise<Tool[]> { |
| 321 | const customTools = await this.getPreloadedCustomToolSchemas(modifiers); |
| 322 | if (!customTools.length) { |
| 323 | return tools; |
| 324 | } |
| 325 | |
| 326 | const existingSlugs = new Set(tools.map(tool => tool.slug.toUpperCase())); |
| 327 | const appendedTools = customTools.filter(tool => !existingSlugs.has(tool.slug.toUpperCase())); |
| 328 | if (!appendedTools.length) { |
| 329 | return tools; |
| 330 | } |
| 331 | |
| 332 | return [...tools, ...appendedTools]; |
| 333 | } |
| 334 | |
| 335 | private async getPreloadedCustomToolSchemas(modifiers?: SessionMetaToolOptions): Promise<Tool[]> { |
| 336 | if (!this.customToolsMap || !this.preloadedCustomToolSlugs.length) { |
| 337 | return []; |
| 338 | } |
| 339 | |
| 340 | const tools: Tool[] = []; |
| 341 | for (const slug of this.preloadedCustomToolSlugs) { |
| 342 | const entry = findCustomToolMapEntryByFinalSlug(this.customToolsMap, slug); |
| 343 | if (!entry) { |
| 344 | continue; |
| 345 | } |
| 346 | |
| 347 | let tool = this.customToolEntryToTool(entry); |
| 348 | if (modifiers?.modifySchema) { |
| 349 | tool = await modifiers.modifySchema({ |
| 350 | toolSlug: tool.slug, |
| 351 | toolkitSlug: tool.toolkit?.slug ?? 'custom', |
| 352 | schema: tool, |
| 353 | }); |
| 354 | } |
| 355 | tools.push(tool); |
| 356 | } |
| 357 | return tools; |
| 358 | } |
| 359 | |
| 360 | private customToolEntryToTool(entry: CustomToolsMapEntry): Tool { |
| 361 | const toolkitSlug = entry.toolkit ?? 'custom'; |
| 362 | const customToolkit = this.customToolsMap?.toolkits?.find( |
| 363 | toolkit => toolkit.slug.toLowerCase() === toolkitSlug.toLowerCase() |
| 364 | ); |
| 365 | const toolkitName = customToolkit?.name ?? entry.toolkit ?? 'Custom'; |
| 366 | |
| 367 | return { |
| 368 | slug: entry.finalSlug, |
| 369 | name: entry.handle.name, |
| 370 | description: `${DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX}\n${entry.handle.description}`, |
| 371 | inputParameters: entry.handle.inputSchema as Tool['inputParameters'], |
| 372 | outputParameters: entry.handle.outputSchema as Tool['outputParameters'], |
| 373 | tags: [], |
| 374 | toolkit: { |
| 375 | slug: toolkitSlug, |
| 376 | name: toolkitName, |
| 377 | }, |
| 378 | isDeprecated: false, |
| 379 | availableVersions: [], |
| 380 | scopes: [], |
| 381 | isNoAuth: !entry.handle.extendsToolkit, |
| 382 | }; |
| 383 | } |
| 384 | |
| 385 | /** |
| 386 | * List all local tools registered in this session. |
| 387 | * Returns tools with their final slugs, schemas, and resolved toolkit. |
| 388 | * |
| 389 | * @param options.toolkit - Filter by toolkit slug (e.g. 'gmail', 'DEV_TOOLS') |
| 390 | * @returns Array of registered local tools |
| 391 | */ |
| 392 | localTools(options?: { toolkit?: string }): RegisteredLocalTool[] { |
| 393 | if (!this.customToolsMap) return []; |
| 394 | |
| 395 | const entries = Array.from(this.customToolsMap.byFinalSlug.values()); |
| 396 | const filtered = options?.toolkit |
| 397 | ? entries.filter(e => e.toolkit?.toLowerCase() === options.toolkit!.toLowerCase()) |
| 398 | : entries; |
| 399 | |
| 400 | return filtered.map(entry => ({ |
| 401 | slug: entry.finalSlug, |
| 402 | name: entry.handle.name, |
| 403 | description: entry.handle.description, |
| 404 | toolkit: entry.toolkit, |
| 405 | inputSchema: entry.handle.inputSchema, |
| 406 | outputSchema: entry.handle.outputSchema, |
| 407 | })); |
| 408 | } |
| 409 | |
| 410 | /** |
| 411 | * @deprecated Use `localTools()` instead. |
| 412 | */ |
| 413 | customTools(options?: { toolkit?: string }): RegisteredLocalTool[] { |
| 414 | return this.localTools(options); |
| 415 | } |
| 416 | |
| 417 | /** |
| 418 | * List all toolkits of local tools registered in this session. |
| 419 | * Returns toolkits with their tools showing final slugs. |
| 420 | * |
| 421 | * @returns Array of registered toolkits of local tools |
| 422 | */ |
| 423 | localToolkits(): RegisteredLocalToolkit[] { |
| 424 | const toolkits = this.customToolsMap?.toolkits; |
| 425 | if (!toolkits?.length) return []; |
| 426 | |
| 427 | return toolkits.map(tk => ({ |
| 428 | slug: tk.slug, |
| 429 | name: tk.name, |
| 430 | description: tk.description, |
| 431 | tools: tk.tools.map(tool => { |
| 432 | // Look up by toolkit + original slug so toolkits can safely reuse common names |
| 433 | // like VERSION, CLICK, or SEARCH without losing the backend-assigned final slug. |
| 434 | // Only trust a bare alias that belongs to this toolkit. |
| 435 | const bare = this.customToolsMap!.byOriginalSlug.get(tool.slug.toUpperCase()); |
| 436 | const entry = |
| 437 | findCustomToolMapEntryByToolkitAndOriginalSlug(this.customToolsMap, tk.slug, tool.slug) ?? |
| 438 | (bare?.toolkit && bare.toolkit.toLowerCase() === tk.slug.toLowerCase() |
| 439 | ? bare |
| 440 | : undefined); |
| 441 | return { |
| 442 | slug: entry?.finalSlug ?? tool.slug, |
| 443 | name: tool.name, |
| 444 | description: tool.description, |
| 445 | toolkit: tk.slug, |
| 446 | inputSchema: tool.inputSchema, |
| 447 | outputSchema: tool.outputSchema, |
| 448 | }; |
| 449 | }), |
| 450 | })); |
| 451 | } |
| 452 | |
| 453 | /** |
| 454 | * @deprecated Use `localToolkits()` instead. |
| 455 | */ |
| 456 | customToolkits(): RegisteredLocalToolkit[] { |
| 457 | return this.localToolkits(); |
| 458 | } |
| 459 | |
| 460 | /** |
| 461 | * Initiate an authorization flow for a toolkit. |
| 462 | * Returns a ConnectionRequest with a redirect URL for the user. |
| 463 | * |
| 464 | * Pass `experimental: { accountType: 'SHARED', aclConfigForShared }` to |
| 465 | * create a SHARED connection with a per-user ACL in one flow. Default |
| 466 | * behaviour (omit the block) creates a PRIVATE connection. |
| 467 | * |
| 468 | * Experimental — shape may change in future releases. |
| 469 | * |
| 470 | * `aclConfigForShared` is validated against the same caps as |
| 471 | * `composio.connectedAccounts.link()` (≤1000 entries per list, each |
| 472 | * `userId` 1..256 characters). Invalid input throws `ValidationError` |
| 473 | * at the SDK boundary. |
| 474 | */ |
| 475 | async authorize( |
| 476 | toolkit: string, |
| 477 | options?: { |
| 478 | callbackUrl?: string; |
| 479 | alias?: string; |
| 480 | experimental?: { |
| 481 | accountType?: ConnectedAccountType; |
| 482 | aclConfigForShared?: ConnectedAccountAclConfig; |
| 483 | }; |
| 484 | }, |
| 485 | requestOptions?: ComposioRequestOptions |
| 486 | ): Promise<ConnectionRequest> { |
| 487 | const parsedAuthorizeOptions = AuthorizeOptionsSchema.safeParse(options ?? {}); |
| 488 | if (!parsedAuthorizeOptions.success) { |
| 489 | throw new ValidationError('Failed to parse tool router authorize options', { |
| 490 | cause: parsedAuthorizeOptions.error, |
| 491 | }); |
| 492 | } |
| 493 | const opts = parsedAuthorizeOptions.data; |
| 494 | const experimentalWire = serializeExperimentalForWire(opts.experimental); |
| 495 | const body: SessionLinkParams = { |
| 496 | toolkit, |
| 497 | ...(opts.callbackUrl !== undefined && { callback_url: opts.callbackUrl }), |
| 498 | ...(opts.alias !== undefined && { alias: opts.alias }), |
| 499 | ...(experimentalWire !== undefined && { |
| 500 | experimental: experimentalWire as NonNullable<SessionLinkParams['experimental']>, |
| 501 | }), |
| 502 | }; |
| 503 | |
| 504 | let response; |
| 505 | try { |
| 506 | response = await withCancellation( |
| 507 | () => this.client.toolRouter.session.link(this.sessionId, body, requestOptions), |
| 508 | requestOptions?.signal |
| 509 | ); |
| 510 | } catch (error) { |
| 511 | // Caller-initiated cancellation must surface as the typed error, |
| 512 | // not get remapped to a domain error below. |
| 513 | if (error instanceof ComposioRequestCancelledError) { |
| 514 | throw error; |
| 515 | } |
| 516 | // The server rejects ACL on PRIVATE connections — surface that as a |
| 517 | // typed error mirroring `composio.connectedAccounts.link()`. |
| 518 | if ( |
| 519 | error instanceof BadRequestError && |
| 520 | typeof error.message === 'string' && |
| 521 | error.message.includes(ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT) |
| 522 | ) { |
| 523 | throw new ComposioAclOnlyForSharedError(error.message, { cause: error }); |
| 524 | } |
| 525 | throw error; |
| 526 | } |
| 527 | |
| 528 | return createConnectionRequest( |
| 529 | this.client, |
| 530 | response.connected_account_id, |
| 531 | ConnectedAccountStatuses.INITIATED, |
| 532 | response.redirect_url |
| 533 | ); |
| 534 | } |
| 535 | |
| 536 | /** |
| 537 | * Ensure a toolkit has an active connection in this session, reconciling |
| 538 | * `authorize()`/`session.link` with the session's active connection state. |
| 539 | * |
| 540 | * If the session already resolves an ACTIVE connection (or the toolkit is |
| 541 | * no-auth), this returns immediately without creating a link — unlike |
| 542 | * `authorize()`, which always starts a new link flow, even when one is |
| 543 | * already connected. Otherwise it starts the authorization flow and waits |
| 544 | * for the new connection to become ACTIVE. |
| 545 | * |
| 546 | * For interactive flows that should surface the redirect URL instead of |
| 547 | * blocking, use `authorize()` and its `waitForConnection()` directly. |
| 548 | * |
| 549 | * @param toolkit - The toolkit slug to ensure a connection for (e.g. 'github') |
| 550 | * @param options - Optional authorization options plus `timeout` (ms to wait |
| 551 | * for a newly-initiated connection, default 60000) |
| 552 | * @returns The toolkit's canonical slug, whether it was already connected, |
| 553 | * and the active connected account (omitted for no-auth toolkits) |
| 554 | * @throws {ValidationError} If the options fail validation |
| 555 | * @throws {ConnectionRequestTimeoutError} If a newly-initiated connection does |
| 556 | * not become active within `timeout` |
| 557 | * @throws {ConnectionRequestFailedError} If the new connection enters a failed, |
| 558 | * expired, or revoked state |
| 559 | * |
| 560 | * @example |
| 561 | * ```typescript |
| 562 | * const session = await composio.sessions.create({ toolkits: ['github'] }); |
| 563 | * const { wasConnected, connectedAccount } = await session.ensureConnected('github'); |
| 564 | * if (!wasConnected) console.log('Newly linked:', connectedAccount?.id); |
| 565 | * ``` |
| 566 | */ |
| 567 | async ensureConnected( |
| 568 | toolkit: string, |
| 569 | options?: ToolRouterSessionEnsureConnectedOptions, |
| 570 | requestOptions?: ComposioRequestOptions |
| 571 | ): Promise<ToolRouterSessionEnsureConnectedResult> { |
| 572 | const parsedOptions = ToolRouterSessionEnsureConnectedOptionsSchema.safeParse(options ?? {}); |
| 573 | if (!parsedOptions.success) { |
| 574 | throw new ValidationError('Failed to parse tool router ensureConnected options', { |
| 575 | cause: parsedOptions.error, |
| 576 | }); |
| 577 | } |
| 578 | const { callbackUrl, alias, experimental, timeout } = parsedOptions.data; |
| 579 | |
| 580 | const state = await this.toolkits({ toolkits: [toolkit] }, requestOptions); |
| 581 | const existing = state.items.find(item => item.slug.toLowerCase() === toolkit.toLowerCase()); |
| 582 | |
| 583 | if (existing?.isNoAuth) { |
| 584 | return { toolkit: existing.slug, wasConnected: true }; |
| 585 | } |
| 586 | const activeAccount = existing?.connection?.connectedAccount; |
| 587 | if (existing?.connection?.isActive && activeAccount) { |
| 588 | return { |
| 589 | toolkit: existing.slug, |
| 590 | wasConnected: true, |
| 591 | connectedAccount: { id: activeAccount.id, status: activeAccount.status }, |
| 592 | }; |
| 593 | } |
| 594 | |
| 595 | const request = await this.authorize( |
| 596 | toolkit, |
| 597 | { |
| 598 | ...(callbackUrl !== undefined && { callbackUrl }), |
| 599 | ...(alias !== undefined && { alias }), |
| 600 | ...(experimental !== undefined && { experimental }), |
| 601 | }, |
| 602 | requestOptions |
| 603 | ); |
| 604 | const account = await request.waitForConnection(timeout); |
| 605 | |
| 606 | return { |
| 607 | toolkit: existing?.slug ?? toolkit, |
| 608 | wasConnected: false, |
| 609 | connectedAccount: { id: account.id, status: account.status }, |
| 610 | }; |
| 611 | } |
| 612 | |
| 613 | /** |
| 614 | * Query the connection state of toolkits in the session. |
| 615 | * Supports pagination and filtering by toolkit slugs. |
| 616 | */ |
| 617 | async toolkits(options?: ToolRouterToolkitsOptions, requestOptions?: ComposioRequestOptions) { |
| 618 | const toolkitOptions = ToolRouterToolkitsOptionsSchema.safeParse(options ?? {}); |
| 619 | if (!toolkitOptions.success) { |
| 620 | throw new ValidationError('Failed to parse toolkits options', { |
| 621 | cause: toolkitOptions.error, |
| 622 | }); |
| 623 | } |
| 624 | |
| 625 | const toolkitsParams = { |
| 626 | cursor: toolkitOptions.data.cursor, |
| 627 | limit: toolkitOptions.data.limit, |
| 628 | toolkits: toolkitOptions.data.toolkits, |
| 629 | is_connected: toolkitOptions.data.isConnected, |
| 630 | search: toolkitOptions.data.search, |
| 631 | }; |
| 632 | const result = await withCancellation( |
| 633 | () => this.client.toolRouter.session.toolkits(this.sessionId, toolkitsParams, requestOptions), |
| 634 | requestOptions?.signal |
| 635 | ); |
| 636 | |
| 637 | const toolkitConnectedStates = result.items.map(item => { |
| 638 | const connectedState = transform(item) |
| 639 | .with(ToolkitConnectionStateSchema) |
| 640 | .using(item => ({ |
| 641 | slug: item.slug, |
| 642 | name: item.name, |
| 643 | logo: item.meta?.logo, |
| 644 | isNoAuth: item.is_no_auth, |
| 645 | connection: item.is_no_auth |
| 646 | ? undefined |
| 647 | : { |
| 648 | isActive: item.connected_account?.status === 'ACTIVE', |
| 649 | authConfig: item.connected_account && { |
| 650 | id: item.connected_account?.auth_config.id, |
| 651 | mode: item.connected_account?.auth_config.auth_scheme, |
| 652 | isComposioManaged: item.connected_account?.auth_config.is_composio_managed, |
| 653 | }, |
| 654 | connectedAccount: item.connected_account |
| 655 | ? { |
| 656 | id: item.connected_account.id, |
| 657 | status: item.connected_account.status, |
| 658 | } |
| 659 | : undefined, |
| 660 | }, |
| 661 | })); |
| 662 | return connectedState; |
| 663 | }); |
| 664 | |
| 665 | return { |
| 666 | items: toolkitConnectedStates, |
| 667 | cursor: result.next_cursor ?? undefined, |
| 668 | totalPages: result.total_pages, |
| 669 | }; |
| 670 | } |
| 671 | |
| 672 | /** |
| 673 | * Search for tools by semantic use case. |
| 674 | * Returns relevant tools for the given query with schemas and guidance. |
| 675 | */ |
| 676 | async search( |
| 677 | params: { |
| 678 | query: string; |
| 679 | toolkits?: string[]; |
| 680 | }, |
| 681 | requestOptions?: ComposioRequestOptions |
| 682 | ): Promise<ToolRouterSessionSearchResponse> { |
| 683 | const searchParams = { |
| 684 | queries: [{ use_case: params.query }], |
| 685 | ...(params.toolkits?.length ? { toolkits: params.toolkits } : {}), |
| 686 | ...(this.inlineCustomToolsPayload && { experimental: this.inlineCustomToolsPayload }), |
| 687 | }; |
| 688 | const response = await withCancellation( |
| 689 | () => this.client.toolRouter.session.search(this.sessionId, searchParams, requestOptions), |
| 690 | requestOptions?.signal |
| 691 | ); |
| 692 | const transformed = transformSearchResponse(response); |
| 693 | return ToolRouterSessionSearchResponseSchema.parse(transformed); |
| 694 | } |
| 695 | |
| 696 | /** |
| 697 | * Execute a tool within the session. |
| 698 | * |
| 699 | * For custom tools, accepts the full slug (e.g. "LOCAL_GREP") or the |
| 700 | * original slug (e.g. "GREP") when that original slug is unique across |
| 701 | * the session's custom tools and toolkits. Custom tools are executed |
| 702 | * in-process; remote tools are sent to the Composio backend. |
| 703 | * |
| 704 | * @param toolSlug - The tool slug to execute |
| 705 | * @param arguments_ - Optional tool arguments |
| 706 | * @param options - Optional execution options |
| 707 | * @param options.account - Account identifier for direct app tool execution. Accepted on every project: in multi-account sessions it picks the account; on single-account projects it must match one of the session's active connections for the toolkit. Helper/meta tools either ignore this top-level field or define their own account-selection fields. |
| 708 | * @param options.inputResponses - Experimental. The user's answers to an earlier `ComposioToolInputRequiredError`, keyed by the IDs in its `inputRequests`. Repeat the same call with them. |
| 709 | * @param options.requestState - Experimental. The `requestState` of that error, sent back unchanged. |
| 710 | * @returns The tool execution result. `resultType: 'blocked'` means a session hook blocked the call; `error` then holds the hook's message |
| 711 | * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run |
| 712 | */ |
| 713 | async execute( |
| 714 | toolSlug: string, |
| 715 | arguments_?: Record<string, unknown>, |
| 716 | options?: ToolRouterSessionExecuteOptions, |
| 717 | requestOptions?: ComposioRequestOptions |
| 718 | ): Promise<ToolRouterSessionExecuteResponse> { |
| 719 | // Check if this is a local tool (by original or final slug) |
| 720 | const entry = findCustomTool(this.customToolsMap, toolSlug); |
| 721 | if (entry) { |
| 722 | // Bail before invoking user code if the caller has already aborted. |
| 723 | // Custom-tool execution is *cooperative*: long-running user code |
| 724 | // won't observe later aborts unless the user wires the signal into |
| 725 | // their own fetch/work — we pass it through via the executeCustomTool |
| 726 | // session context so they can. |
| 727 | if (requestOptions?.signal?.aborted) { |
| 728 | throw new ComposioRequestCancelledError(); |
| 729 | } |
| 730 | const result = await executeCustomTool(entry, arguments_ ?? {}, this.sessionContext!, { |
| 731 | signal: requestOptions?.signal, |
| 732 | }); |
| 733 | return { |
| 734 | data: result.data, |
| 735 | error: result.error, |
| 736 | logId: '', |
| 737 | resultType: result.successful ? 'completed' : 'failed', |
| 738 | }; |
| 739 | } |
| 740 | assertUnambiguousCustomToolSlug(this.customToolsMap, toolSlug); |
| 741 | |
| 742 | // Remote execution |
| 743 | const executeParams: SessionExecuteParams = { |
| 744 | tool_slug: toolSlug, |
| 745 | arguments: arguments_ ?? {}, |
| 746 | ...inputResponseParams(options), |
| 747 | }; |
| 748 | if (options?.account) { |
| 749 | executeParams.account = options.account; |
| 750 | } |
| 751 | if (this.inlineCustomToolsPayload) { |
| 752 | executeParams.experimental = this.inlineCustomToolsPayload; |
| 753 | } |
| 754 | |
| 755 | const response = await withCancellation( |
| 756 | () => |
| 757 | this.client.toolRouter.session.execute( |
| 758 | this.sessionId, |
| 759 | executeParams, |
| 760 | withoutRetries(requestOptions) |
| 761 | ), |
| 762 | requestOptions?.signal |
| 763 | ).catch((error: unknown) => { |
| 764 | throw handleToolExecutionError(toolSlug, error as Error); |
| 765 | }); |
| 766 | const transformed = transformExecuteResponse(response, toolSlug); |
| 767 | return ToolRouterSessionExecuteResponseSchema.parse(transformed); |
| 768 | } |
| 769 | |
| 770 | /** |
| 771 | * Execute a Composio meta tool (`COMPOSIO_*`) within the session. |
| 772 | * |
| 773 | * `session.execute()` also runs meta tools. This method only accepts meta |
| 774 | * tool slugs, so a typo is a type error instead of a failed request. The call |
| 775 | * is sent to the Composio backend as is: custom tools named in a |
| 776 | * `COMPOSIO_MULTI_EXECUTE_TOOL` call are not run in-process here. |
| 777 | * |
| 778 | * @param slug - The meta tool slug to execute |
| 779 | * @param arguments_ - Optional meta tool arguments |
| 780 | * @param options - Experimental. The user's answers to an earlier `ComposioToolInputRequiredError` (`inputResponses`) and its `requestState`, as in `session.execute()` |
| 781 | * @returns The tool execution result, in the same shape as `session.execute()` |
| 782 | * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run |
| 783 | * |
| 784 | * @example |
| 785 | * ```typescript |
| 786 | * const { data, resultType } = await session.executeMeta('COMPOSIO_SEARCH_TOOLS', { |
| 787 | * queries: [{ use_case: 'send an email' }], |
| 788 | * }); |
| 789 | * ``` |
| 790 | */ |
| 791 | async executeMeta( |
| 792 | slug: ToolRouterSessionMetaToolSlug, |
| 793 | arguments_?: Record<string, unknown>, |
| 794 | options?: ToolRouterSessionExecuteMetaOptions, |
| 795 | requestOptions?: ComposioRequestOptions |
| 796 | ): Promise<ToolRouterSessionExecuteResponse> { |
| 797 | const executeMetaParams: SessionExecuteMetaParams = { |
| 798 | slug, |
| 799 | arguments: arguments_ ?? {}, |
| 800 | ...inputResponseParams(options), |
| 801 | }; |
| 802 | if (this.inlineCustomToolsPayload) { |
| 803 | executeMetaParams.experimental = this.inlineCustomToolsPayload; |
| 804 | } |
| 805 | |
| 806 | const response = await withCancellation( |
| 807 | () => |
| 808 | this.client.toolRouter.session.executeMeta( |
| 809 | this.sessionId, |
| 810 | executeMetaParams, |
| 811 | withoutRetries(requestOptions) |
| 812 | ), |
| 813 | requestOptions?.signal |
| 814 | ).catch((error: unknown) => { |
| 815 | throw handleToolExecutionError(slug, error as Error); |
| 816 | }); |
| 817 | const transformed = transformExecuteResponse(response, slug); |
| 818 | return ToolRouterSessionExecuteResponseSchema.parse(transformed); |
| 819 | } |
| 820 | |
| 821 | /** |
| 822 | * Proxy an API call through Composio's auth layer using the session's connected account. |
| 823 | * The backend resolves the connected account from the toolkit within the session. |
| 824 | * |
| 825 | * @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params) |
| 826 | * @returns The proxied API response with status, data and headers (`resultType: 'completed'`), or `resultType: 'blocked'` with the hook's message when a session hook blocked the request |
| 827 | * @throws {ComposioToolInputRequiredError} If the call needs input from the user before it can run |
| 828 | */ |
| 829 | async proxyExecute( |
| 830 | params: SessionProxyExecuteParams, |
| 831 | requestOptions?: ComposioRequestOptions |
| 832 | ): Promise<ToolRouterSessionProxyExecuteResponse> { |
| 833 | const validated = SessionProxyExecuteParamsSchema.safeParse(params); |
| 834 | if (!validated.success) { |
| 835 | throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error }); |
| 836 | } |
| 837 | |
| 838 | const clientParams = transformProxyParams(validated.data); |
| 839 | const response = await withCancellation( |
| 840 | () => |
| 841 | this.client.toolRouter.session.proxyExecute( |
| 842 | this.sessionId, |
| 843 | clientParams, |
| 844 | withoutRetries(requestOptions) |
| 845 | ), |
| 846 | requestOptions?.signal |
| 847 | ); |
| 848 | |
| 849 | return transformProxyExecuteResponse( |
| 850 | response, |
| 851 | `${validated.data.method} proxy call for toolkit ${validated.data.toolkit}` |
| 852 | ); |
| 853 | } |
| 854 | |
| 855 | /** |
| 856 | * Partially update the session configuration. |
| 857 | * |
| 858 | * Only the fields provided are changed; omitted fields are preserved. For |
| 859 | * each policy block `null` removes the stored override (which can increase |
| 860 | * access: `toolkits: null` restores the unrestricted default, while |
| 861 | * `toolkits: []` denies every app toolkit and is sent as-is). Supplied |
| 862 | * `tools`, `authConfigs` and `connectedAccounts` maps replace the stored |
| 863 | * map entirely. `manageConnections.callbackUrl: null` removes only the |
| 864 | * stored callback URL. |
| 865 | * |
| 866 | * By default the request carries no precondition: the last writer wins. |
| 867 | * Pass `expectedConfigVersion` (for example `session.configVersion`) to make |
| 868 | * the update conditional: the API then applies it only when the stored |
| 869 | * version still matches, and a concurrent change surfaces as |
| 870 | * {@link ComposioSessionConfigConflictError} (HTTP 409) instead of being |
| 871 | * overwritten. The API must support the `expected_config_version` field; |
| 872 | * otherwise it rejects the request with a 400. `expectedConfigVersion: false` |
| 873 | * is the same as omitting it. The PATCH is never retried by the transport, |
| 874 | * so a 409 is reported exactly once. On conflict this object is left |
| 875 | * unchanged: re-fetch the session with `sessions.use(sessionId)` and retry |
| 876 | * against the fresh `configVersion`. |
| 877 | * |
| 878 | * `experimental.sessionConfigId` applies a saved Session config: it |
| 879 | * replaces the session's toolkit, tool and tag access and cannot be combined |
| 880 | * with `toolkits`, `tools` or `tags` (a `ValidationError` is thrown before |
| 881 | * any request). A 409 while applying it means the session or the config |
| 882 | * changed; re-fetch the session and retry. Backend 400, 403 and 404 errors, |
| 883 | * for example for an archived or missing config, surface unchanged. |
| 884 | * |
| 885 | * `config`, `configVersion`, `preload`, `sandbox`, `warnings` and |
| 886 | * `experimental.sourceSessionConfig` are refreshed in place only after a |
| 887 | * successful response, and the updated `config` is returned. |
| 888 | */ |
| 889 | async update( |
| 890 | config: ToolRouterUpdateSessionConfig, |
| 891 | requestOptions?: ComposioRequestOptions |
| 892 | ): Promise<ToolRouterSessionConfig> { |
| 893 | const parsed = parseSessionConfigInput(ToolRouterUpdateSessionConfigSchema, config); |
| 894 | const body = transformToolRouterUpdateParams(parsed); |
| 895 | const expectedConfigVersion = |
| 896 | parsed.expectedConfigVersion === false ? undefined : parsed.expectedConfigVersion; |
| 897 | if (expectedConfigVersion !== undefined) { |
| 898 | body.expected_config_version = expectedConfigVersion; |
| 899 | } |
| 900 | |
| 901 | let response: SessionPatchResponse; |
| 902 | try { |
| 903 | response = await withCancellation( |
| 904 | () => |
| 905 | this.client.toolRouter.session.patch( |
| 906 | this.sessionId, |
| 907 | // `expected_config_version` and the nullable policy blocks are not in |
| 908 | // the spec until ComposioHQ/platform#13157 lands; the body is |
| 909 | // serialized as-is. |
| 910 | body as SessionPatchParams, |
| 911 | { ...requestOptions, maxRetries: 0 } |
| 912 | ), |
| 913 | requestOptions?.signal |
| 914 | ); |
| 915 | } catch (error) { |
| 916 | if (error instanceof ConflictError) { |
| 917 | const sessionConfigId = parsed.experimental?.sessionConfigId; |
| 918 | if (sessionConfigId !== undefined) { |
| 919 | throw new ComposioSessionConfigConflictError( |
| 920 | `Session ${this.sessionId} or Session config ${sessionConfigId} changed while the config was being applied; re-fetch the session and retry the update`, |
| 921 | { |
| 922 | cause: error, |
| 923 | meta: { sessionId: this.sessionId, sessionConfigId, expectedConfigVersion }, |
| 924 | } |
| 925 | ); |
| 926 | } |
| 927 | throw new ComposioSessionConfigConflictError( |
| 928 | expectedConfigVersion === undefined |
| 929 | ? `Session ${this.sessionId} configuration changed while this update was in flight; re-fetch the session and retry the update` |
| 930 | : `Session ${this.sessionId} configuration is no longer at version ${expectedConfigVersion}; re-fetch the session and retry the update`, |
| 931 | { |
| 932 | cause: error, |
| 933 | meta: { sessionId: this.sessionId, expectedConfigVersion }, |
| 934 | } |
| 935 | ); |
| 936 | } |
| 937 | throw error; |
| 938 | } |
| 939 | |
| 940 | this.configVersion = response.config_version; |
| 941 | this.config = response.config; |
| 942 | this.preload = response.config.preload; |
| 943 | this.sandbox = response.config.workbench; |
| 944 | this.warnings = response.warnings ?? []; |
| 945 | this.experimental.sourceSessionConfig = getSourceSessionConfig(response); |
| 946 | return this.config; |
| 947 | } |
| 948 | |
| 949 | /** |
| 950 | * Delete this session. |
| 951 | * |
| 952 | * Deleted sessions immediately stop being retrievable or executable. Deleting |
| 953 | * an already-deleted session surfaces the backend 404. |
| 954 | */ |
| 955 | async delete(requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionDeleteResponse> { |
| 956 | return deleteToolRouterSession(this.client, this.sessionId, requestOptions); |
| 957 | } |
| 958 | |
| 959 | /** |
| 960 | * Page through this session's configuration history, newest first. The |
| 961 | * first page starts with the live config (`isCurrent: true`); every |
| 962 | * `session.update()` archives the previous version as a history row. |
| 963 | * |
| 964 | * @param options - Optional `cursor` and `limit` (max 100) |
| 965 | * @returns The config versions on this page plus pagination info |
| 966 | * @throws {ValidationError} If the options fail validation |
| 967 | * |
| 968 | * @example |
| 969 | * ```typescript |
| 970 | * const { items, nextCursor } = await session.listConfigHistory({ limit: 10 }); |
| 971 | * console.log(items[0].version, items[0].isCurrent); // e.g. 3, true |
| 972 | * console.log(items[1].config.toolkits); |
| 973 | * ``` |
| 974 | */ |
| 975 | async listConfigHistory( |
| 976 | options?: ToolRouterSessionListConfigHistoryOptions, |
| 977 | requestOptions?: ComposioRequestOptions |
| 978 | ): Promise<ToolRouterSessionListConfigHistoryResponse> { |
| 979 | const parsedOptions = ToolRouterSessionListConfigHistoryOptionsSchema.safeParse(options ?? {}); |
| 980 | if (!parsedOptions.success) { |
| 981 | throw new ValidationError('Failed to parse config history options', { |
| 982 | cause: parsedOptions.error, |
| 983 | }); |
| 984 | } |
| 985 | const query = { |
| 986 | cursor: parsedOptions.data.cursor, |
| 987 | limit: parsedOptions.data.limit, |
| 988 | }; |
| 989 | const response = await withCancellation( |
| 990 | () => this.client.toolRouter.session.configHistory(this.sessionId, query, requestOptions), |
| 991 | requestOptions?.signal |
| 992 | ); |
| 993 | return { |
| 994 | items: response.items.map(item => ({ |
| 995 | version: item.version, |
| 996 | createdAt: item.created_at, |
| 997 | isCurrent: item.is_current, |
| 998 | config: item.config, |
| 999 | })), |
| 1000 | nextCursor: response.next_cursor ?? null, |
| 1001 | totalPages: response.total_pages, |
| 1002 | currentPage: response.current_page, |
| 1003 | totalItems: response.total_items, |
| 1004 | }; |
| 1005 | } |
| 1006 | |
| 1007 | // ── Private helpers ────────────────────────────────────────── |
| 1008 | |
| 1009 | /** Check if this session has any custom tools bound. */ |
| 1010 | private hasCustomTools(): boolean { |
| 1011 | return (this.customToolsMap?.byFinalSlug.size ?? 0) > 0; |
| 1012 | } |
| 1013 | |
| 1014 | private executeBackendSessionTool( |
| 1015 | ToolsModel: Tools<TToolCollection, TTool, TProvider>, |
| 1016 | toolSlug: string, |
| 1017 | input: Record<string, unknown>, |
| 1018 | modifiers?: SessionMetaToolOptions, |
| 1019 | tool?: Tool |
| 1020 | ): Promise<ToolExecuteResponse> { |
| 1021 | const body = { sessionId: this.sessionId, arguments: input }; |
| 1022 | if (this.inlineCustomToolsPayload) { |
| 1023 | return ToolsModel.executeSessionTool(toolSlug, body, modifiers, tool, { |
| 1024 | experimental: this.inlineCustomToolsPayload, |
| 1025 | }); |
| 1026 | } |
| 1027 | return ToolsModel.executeSessionTool(toolSlug, body, modifiers, tool); |
| 1028 | } |
| 1029 | |
| 1030 | /** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */ |
| 1031 | private parseToolItem(item: unknown): { tool_slug: string; arguments: Record<string, unknown> } { |
| 1032 | if (typeof item !== 'object' || item === null) { |
| 1033 | return { tool_slug: '', arguments: {} }; |
| 1034 | } |
| 1035 | const obj = item as Record<string, unknown>; |
| 1036 | return { |
| 1037 | tool_slug: String(obj.tool_slug ?? ''), |
| 1038 | arguments: (obj.arguments as Record<string, unknown> | undefined) ?? {}, |
| 1039 | }; |
| 1040 | } |
| 1041 | |
| 1042 | /** |
| 1043 | * Route a COMPOSIO_MULTI_EXECUTE_TOOL call. |
| 1044 | * Splits the tools[] array into local and remote, executes each appropriately, |
| 1045 | * and merges results preserving original order. |
| 1046 | */ |
| 1047 | private async routeMultiExecute( |
| 1048 | input: Record<string, unknown>, |
| 1049 | ToolsModel: Tools<TToolCollection, TTool, TProvider>, |
| 1050 | tools: Tool[], |
| 1051 | modifiers?: SessionMetaToolOptions |
| 1052 | ): Promise<ToolExecuteResponse> { |
| 1053 | const multiExecuteTool = tools.find(tool => tool.slug === COMPOSIO_MULTI_EXECUTE_TOOL); |
| 1054 | const toolItems = input.tools as unknown[]; |
| 1055 | if (!Array.isArray(toolItems) || toolItems.length === 0) { |
| 1056 | // Fallback: send to backend as-is |
| 1057 | return this.executeBackendSessionTool( |
| 1058 | ToolsModel, |
| 1059 | COMPOSIO_MULTI_EXECUTE_TOOL, |
| 1060 | input, |
| 1061 | modifiers, |
| 1062 | multiExecuteTool |
| 1063 | ); |
| 1064 | } |
| 1065 | |
| 1066 | const parsed = toolItems.map(item => this.parseToolItem(item)); |
| 1067 | |
| 1068 | // Partition into local (with resolved entry) and remote |
| 1069 | const localItems: Array<{ index: number; entry: CustomToolsMapEntry }> = []; |
| 1070 | const remoteIndices: number[] = []; |
| 1071 | for (let i = 0; i < parsed.length; i++) { |
| 1072 | const entry = findCustomTool(this.customToolsMap, parsed[i].tool_slug); |
| 1073 | if (entry) { |
| 1074 | localItems.push({ index: i, entry }); |
| 1075 | } else { |
| 1076 | assertUnambiguousCustomToolSlug(this.customToolsMap, parsed[i].tool_slug); |
| 1077 | remoteIndices.push(i); |
| 1078 | } |
| 1079 | } |
| 1080 | |
| 1081 | // All remote — just forward entire payload |
| 1082 | if (localItems.length === 0) { |
| 1083 | return this.executeBackendSessionTool( |
| 1084 | ToolsModel, |
| 1085 | COMPOSIO_MULTI_EXECUTE_TOOL, |
| 1086 | input, |
| 1087 | modifiers, |
| 1088 | multiExecuteTool |
| 1089 | ); |
| 1090 | } |
| 1091 | |
| 1092 | // Execute local tools in parallel (shared singleton context) |
| 1093 | const ctx = this.sessionContext!; |
| 1094 | const localPromises = localItems.map(async ({ index, entry }) => { |
| 1095 | const result = await executeCustomTool(entry, parsed[index].arguments, ctx); |
| 1096 | return { index, result }; |
| 1097 | }); |
| 1098 | |
| 1099 | // Execute remote tools via backend in parallel with local |
| 1100 | let remotePromise: Promise<ToolExecuteResponse> | undefined; |
| 1101 | if (remoteIndices.length > 0) { |
| 1102 | const remoteToolItems = remoteIndices.map(i => toolItems[i]); |
| 1103 | const remoteInput = { ...input, tools: remoteToolItems }; |
| 1104 | remotePromise = this.executeBackendSessionTool( |
| 1105 | ToolsModel, |
| 1106 | COMPOSIO_MULTI_EXECUTE_TOOL, |
| 1107 | remoteInput, |
| 1108 | modifiers, |
| 1109 | multiExecuteTool |
| 1110 | ); |
| 1111 | } |
| 1112 | |
| 1113 | const [localResults, remoteOutcome] = await Promise.all([ |
| 1114 | Promise.all(localPromises), |
| 1115 | remotePromise |
| 1116 | ? remotePromise.then(result => ({ result })).catch(error => ({ error })) |
| 1117 | : undefined, |
| 1118 | ]); |
| 1119 | |
| 1120 | const remoteTransportFailed = !!remoteOutcome && 'error' in remoteOutcome; |
| 1121 | const remoteTransportError = remoteTransportFailed ? remoteOutcome.error : null; |
| 1122 | // An input request is not a per-tool failure: rethrow it so the caller gets |
| 1123 | // `inputRequests` and `requestState`. |
| 1124 | // Accepted: local tools in this batch already ran and their results are discarded. |
| 1125 | if (remoteTransportError instanceof ComposioToolInputRequiredError) { |
| 1126 | throw remoteTransportError; |
| 1127 | } |
| 1128 | const remoteErrorMessage = remoteTransportFailed |
| 1129 | ? (remoteTransportError instanceof Error |
| 1130 | ? remoteTransportError.message |
| 1131 | : String(remoteTransportError)) || 'Remote tool execution failed' |
| 1132 | : null; |
| 1133 | const remoteResult = |
| 1134 | remoteOutcome && 'result' in remoteOutcome ? remoteOutcome.result : undefined; |
| 1135 | |
| 1136 | // If only local tools, return the single/first result unwrapped |
| 1137 | if (remoteIndices.length === 0 && localResults.length === 1) { |
| 1138 | return localResults[0].result; |
| 1139 | } |
| 1140 | |
| 1141 | // Merge results into the backend's results[] format. |
| 1142 | const remoteData = ( |
| 1143 | remoteResult?.data && |
| 1144 | typeof remoteResult.data === 'object' && |
| 1145 | !Array.isArray(remoteResult.data) |
| 1146 | ? remoteResult.data |
| 1147 | : {} |
| 1148 | ) as Record<string, unknown>; |
| 1149 | const remoteResults = remoteErrorMessage |
| 1150 | ? remoteIndices.map(index => ({ |
| 1151 | response: { successful: false, data: {}, error: remoteErrorMessage }, |
| 1152 | tool_slug: parsed[index].tool_slug, |
| 1153 | error: remoteErrorMessage, |
| 1154 | })) |
| 1155 | : ((Array.isArray(remoteData.results) ? remoteData.results : []) as Array< |
| 1156 | Record<string, unknown> |
| 1157 | >); |
| 1158 | |
| 1159 | // Build local result entries matching backend format |
| 1160 | const localEntries = localResults.map(({ index, result }) => ({ |
| 1161 | response: { |
| 1162 | successful: result.successful, |
| 1163 | data: result.data, |
| 1164 | ...(result.error ? { error: result.error } : {}), |
| 1165 | }, |
| 1166 | tool_slug: parsed[index].tool_slug, |
| 1167 | index, |
| 1168 | ...(result.error ? { error: result.error } : {}), |
| 1169 | })); |
| 1170 | |
| 1171 | // Restore original request order, then re-index sequentially so there are no collisions. |
| 1172 | const merged: Array<Record<string, unknown>> = [ |
| 1173 | ...remoteResults.map((entry, remotePosition) => ({ |
| 1174 | ...entry, |
| 1175 | index: remoteIndices[remotePosition] ?? remotePosition, |
| 1176 | })), |
| 1177 | ...localEntries, |
| 1178 | ].sort((a, b) => Number(a.index) - Number(b.index)); |
| 1179 | const allResults = merged.map((entry, i): Record<string, unknown> => ({ |
| 1180 | ...entry, |
| 1181 | index: i, |
| 1182 | })); |
| 1183 | const failedCount = allResults.filter(r => r.error).length; |
| 1184 | const mergedData: Record<string, unknown> = { |
| 1185 | ...remoteData, |
| 1186 | results: allResults, |
| 1187 | }; |
| 1188 | if ( |
| 1189 | localEntries.length > 0 && |
| 1190 | (remoteErrorMessage || |
| 1191 | ['total_count', 'success_count', 'error_count'].some(key => key in remoteData)) |
| 1192 | ) { |
| 1193 | mergedData.total_count = allResults.length; |
| 1194 | mergedData.success_count = allResults.length - failedCount; |
| 1195 | mergedData.error_count = failedCount; |
| 1196 | } |
| 1197 | const remoteError = |
| 1198 | remoteErrorMessage ?? (typeof remoteResult?.error === 'string' ? remoteResult.error : null); |
| 1199 | // A failed execution can carry no error text, so success is read from each |
| 1200 | // result's own verdict and not from the absence of an error message. |
| 1201 | const hasAnyFailure = |
| 1202 | localResults.some(r => !r.result.successful) || |
| 1203 | remoteResult?.successful === false || |
| 1204 | !!remoteError; |
| 1205 | |
| 1206 | return { |
| 1207 | data: mergedData, |
| 1208 | error: hasAnyFailure |
| 1209 | ? failedCount > 0 |
| 1210 | ? `${failedCount} out of ${allResults.length} tools failed` |
| 1211 | : remoteError |
| 1212 | : null, |
| 1213 | successful: !hasAnyFailure, |
| 1214 | ...(remoteResult?.instantCharge !== undefined && { |
| 1215 | instantCharge: remoteResult.instantCharge, |
| 1216 | }), |
| 1217 | }; |
| 1218 | } |
| 1219 | } |