Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(core): expose the owned client surface on @composio/client 2.0.0-rc.7
jkomynoe8e1d67a7189
diff --git a/.changeset/owned-client-surface.md b/.changeset/owned-client-surface.mdnew file mode 100644index 000000000..a1becd807--- /dev/null+++ b/.changeset/owned-client-surface.md@@ -0,0 +1,20 @@+---+'@composio/core': minor+---++Expose the rest of the owned client surface on the `Composio` class:++- `composio.webhooks.subscriptions` (`list`, `get`, `set`, `update`, `delete`, `rotateSecret`, `listEventTypes`) and `composio.webhooks.endpoints` (`list`, `get`, `create`, `replace`, `update`). `composio.triggers.setWebhookSubscription()` now delegates to the same upsert as `webhooks.subscriptions.set()`. Its behaviour for well-formed API responses is unchanged; malformed responses are now rejected with a `ValidationError` instead of being read leniently.+- `composio.logs.search()` and `composio.logs.get()` for tool-execution logs.+- `composio.connectedAccounts.revoke()`, which surfaces the API's 400/409 as `ComposioConnectedAccountRevocationNotSupportedError` / `ComposioConnectedAccountNotRevokableError`. `connectedAccounts.refresh()` is marked `@deprecated` (the endpoint is deprecated upstream).+- `composio.toolkits.getMany(slugs)` and `composio.toolkits.changelog()`.+- `session.configHistory()` on sessions.+- `composio.experimental.usage.summary()` and `composio.experimental.usage.breakdown()` (experimental, shape may change).+- `composio.toolkits.recommendScopes(toolkitSlug, { tools, ... })` and `composio.toolkits.listGrantContexts(toolkitSlug)` for OAuth scope recommendations (the API marks both beta).+- `composio.connectedAccounts.completeAuth({ userId, sessionUri })`, which completes a deferred OAuth connection after your OAuth callback verifier has confirmed the user's identity.+- `composio.keyring.listTransferKeys()`, which returns the public JWKs of the organization's customer-managed keyring.+- `composio.experimental.customToolkits` (`upsert`, `sync`, `delete`) for project-owned custom toolkits (in pilot, shape may change).+- `CIMD_OAUTH` joins `AuthSchemeTypes`.+- `triggers.listActive()` returns `{}` for `state` and `triggerConfig` when the API sends `null`.+- `@composio/client` moves to `2.0.0-rc.7`. The API removed `validate_credentials` from the connected-account refresh, so `connectedAccounts.refresh()` now ignores `validateCredentials` and logs a warning when it is set.+- `logger` and `logLevel` options on `new Composio({...})`. `logger` accepts any `{ error, warn, info, debug }` sink (`console`, pino, winston, ...) and receives the SDK's formatted, credential-redacted output; `logLevel` (`'silent' | 'error' | 'warn' | 'info' | 'debug'`) overrides `COMPOSIO_LOG_LEVEL`. The owned client's runtime deprecation warnings (response `Deprecation`/`Sunset` headers and deprecated request inputs) are now routed through that SDK logger instead of `console`. The client's per-request lifecycle logs are emitted only at `'debug'`. `tools.get`/`getRawComposioTools` send the API's `query` parameter in place of the deprecated `search` wire parameter; the SDK's public `search` option is unchanged.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d987f32bc..5337e3167 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -28,8 +28,8 @@ catalogs:specifier: ^5.20260905.1version: 5.20260905.1'@composio/client':- specifier: 2.0.0-rc.6- version: 2.0.0-rc.6+ specifier: 2.0.0-rc.7+ version: 2.0.0-rc.7'@effect/cli':specifier: ^0.77.0version: 0.77.0@@ -1187,7 +1187,7 @@ importers:version: link:../cli-local-tools'@composio/client':specifier: 'catalog:'- version: 2.0.0-rc.6+ version: 2.0.0-rc.7'@composio/core':specifier: workspace:*version: link:../core@@ -1348,7 +1348,7 @@ importers:dependencies:'@composio/client':specifier: 'catalog:'- version: 2.0.0-rc.6+ version: 2.0.0-rc.7'@composio/json-schema-to-zod':specifier: workspace:*version: link:../json-schema-to-zod@@ -1708,7 +1708,7 @@ importers:dependencies:'@composio/client':specifier: 'catalog:'- version: 2.0.0-rc.6+ version: 2.0.0-rc.7'@composio/json-schema-to-zod':specifier: workspace:*version: link:../json-schema-to-zod@@ -2252,8 +2252,8 @@ packages:resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}engines: {node: '>=0.1.90'}- '@composio/[email protected]':- resolution: {integrity: sha512-l8swDeD2vN9DA2v7OE9GaairWBVFNlPvmRtqqhU8m+uvsOEkfR1n67NXyOHTa6SqHMCGdyeq8KsQqlVAf6vGGQ==}+ '@composio/[email protected]':+ resolution: {integrity: sha512-E4D5nmjMPdhbUgWlOKKVkGXgbunJqDerXxZjgJUZn68ZHTiSR4dDrzXnGTL6b3eaN3AwBT4sRM/dz4x286yApQ==}engines: {node: '>=22'}'@cspotcode/[email protected]':@@ -7369,7 +7369,7 @@ snapshots:'@colors/[email protected]':optional: true- '@composio/[email protected]': {}+ '@composio/[email protected]': {}'@cspotcode/[email protected]':dependencies:diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 83d3736be..a6c221094 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -35,7 +35,7 @@ catalog:'@clack/prompts': '^1.7.0''@cloudflare/vitest-pool-workers': 0.22.0'@cloudflare/workers-types': ^5.20260905.1- '@composio/client': 2.0.0-rc.6+ '@composio/client': 2.0.0-rc.7'@effect/cli': ^0.77.0'@effect/language-service': ^0.87.2'@effect/platform': ^0.97.1diff --git a/ts/packages/core/src/composio.ts b/ts/packages/core/src/composio.tsindex cbf69364c..1e7947685 100644--- a/ts/packages/core/src/composio.ts+++ b/ts/packages/core/src/composio.ts@@ -1,5 +1,6 @@import type { BaseComposioProvider } from './provider/BaseProvider';import ComposioClient from '@composio/client';+import type { Logger as ClientLogger, LogLevel as ClientLogLevel } from '@composio/client';import { Tools } from './models/Tools';import { Toolkits } from './models/Toolkits';import { Triggers } from './models/Triggers';@@ -7,10 +8,14 @@ import { AuthConfigs } from './models/AuthConfigs';import { ConnectedAccounts } from './models/ConnectedAccounts';import { Experimental } from './models/Experimental';import { MCP } from './models/MCP';+import { Webhooks } from './models/Webhooks';+import { Logs } from './models/Logs';+import { Keyring } from './models/Keyring';import { telemetry } from './telemetry/Telemetry';import { getSDKConfig, getToolkitVersionsFromEnv } from './utils/sdk';import logger from './utils/logger';-import { COMPOSIO_LOG_LEVEL, IS_DEVELOPMENT_OR_CI } from './utils/constants';+import type { ComposioLogger, LogLevel } from './utils/logger';+import { IS_DEVELOPMENT_OR_CI } from './utils/constants';import { checkForLatestVersionFromNPM } from './utils/version';import { OpenAIProvider } from './provider/OpenAIProvider';import { version } from '../package.json';@@ -156,6 +161,68 @@ export type ComposioConfig<* ```*/toolkitVersions?: ToolkitVersionParam;+ /**+ * Destination for SDK log output. Messages are formatted and have+ * credential-shaped values redacted before they reach the sink, so any+ * object with `error`/`warn`/`info`/`debug` methods works (`console`, pino,+ * winston, ...).+ *+ * Runtime deprecation warnings raised by the underlying API client (response+ * `Deprecation`/`Sunset` headers and deprecated request inputs) are routed+ * through this logger as well.+ *+ * The SDK logger is process-wide: configuring it on one `Composio` instance+ * affects every instance, and the last configured instance wins.+ *+ * @default console+ * @example+ * ```typescript+ * const composio = new Composio({+ * apiKey: 'your-api-key',+ * logger: pino(),+ * logLevel: 'warn',+ * });+ * ```+ */+ logger?: ComposioLogger;+ /**+ * Minimum level to emit: `'silent' | 'error' | 'warn' | 'info' | 'debug'`.+ * Takes precedence over the `COMPOSIO_LOG_LEVEL` environment variable.+ * Also gates the API client's runtime deprecation warnings (`'silent'` turns+ * them off). The client's per-request lifecycle logs are emitted at+ * `'debug'` only.+ *+ * Like `logger`, this applies process-wide and the last configured instance+ * wins. The API client's own level is fixed when each instance is created.+ *+ * @default 'info' (or `COMPOSIO_LOG_LEVEL` when set)+ */+ logLevel?: LogLevel;+};++/**+ * Level for the API client given the SDK level. The client logs each request's+ * lifecycle at `info`, which is debug-grade for SDK users, so the client stays+ * at `warn` unless the SDK is at `debug`. The client's `LogLevel` has+ * `'off'` where the SDK has `'silent'`.+ */+const toClientLogLevel = (level: LogLevel): ClientLogLevel => {+ if (level === 'silent') return 'off';+ if (level === 'info') return 'warn';+ return level;+};++/**+ * Forwards the API client's log records to the SDK singleton so they pick up+ * the SDK's formatting, redaction, and configured sink. Methods are looked up+ * at call time so a later `logger.configure()` is honoured. The client's+ * `info` records (per-request lifecycle) are forwarded as SDK `debug`.+ */+const clientLoggerAdapter: ClientLogger = {+ error: (...args) => logger.error(...args),+ warn: (...args) => logger.warn(...args),+ info: (...args) => logger.debug(...args),+ debug: (...args) => logger.debug(...args),};/**@@ -195,6 +262,15 @@ export class Composio<authConfigs: AuthConfigs;/** Manage authenticated connections */connectedAccounts: ConnectedAccounts;+ /**+ * Manage the project's webhook subscription (`webhooks.subscriptions`) and+ * inbound per-toolkit webhook endpoints (`webhooks.endpoints`).+ */+ webhooks: Webhooks;+ /** Search and inspect tool-execution logs */+ logs: Logs;+ /** Public transfer keys of the organization's customer-managed keyring */+ keyring: Keyring;/*** Experimental SDK methods whose shape may change in future releases.* Prefer domain-specific mounts (for example@@ -307,6 +383,10 @@ export class Composio<config?.apiKey);+ if (config?.logger !== undefined || config?.logLevel !== undefined) {+ logger.configure({ level: config.logLevel, sink: config.logger });+ }+if (IS_DEVELOPMENT_OR_CI) {logger.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);}@@ -346,7 +426,8 @@ export class Composio<apiKey: apiKeyParsed,baseURL: baseURLParsed,defaultHeaders: defaultHeaders,- logLevel: COMPOSIO_LOG_LEVEL,+ logger: clientLoggerAdapter,+ logLevel: toClientLogLevel(logger.getLevel()),});this.tools = new Tools(this.client, this.config);@@ -360,6 +441,9 @@ export class Composio<fileDownloadDir: this.config.fileDownloadDir,});this.connectedAccounts = new ConnectedAccounts(this.client);+ this.webhooks = new Webhooks(this.client);+ this.logs = new Logs(this.client);+ this.keyring = new Keyring(this.client);this.experimental = new Experimental(this.client);this.sessions = new Sessions(this.client, this.config);this.toolRouter = this.sessions;diff --git a/ts/packages/core/src/errors/ConnectedAccountsErrors.ts b/ts/packages/core/src/errors/ConnectedAccountsErrors.tsindex bd18f5f23..fe38cdc09 100644--- a/ts/packages/core/src/errors/ConnectedAccountsErrors.ts+++ b/ts/packages/core/src/errors/ConnectedAccountsErrors.ts@@ -8,6 +8,8 @@ export const ConnectedAccountErrorCodes = {SHARED_ACCESS_DENIED: 'SHARED_ACCESS_DENIED',ACL_ONLY_FOR_SHARED: 'ACL_ONLY_FOR_SHARED',SHARED_CONNECTION_NOT_ACCESSIBLE: 'SHARED_CONNECTION_NOT_ACCESSIBLE',+ REVOCATION_NOT_SUPPORTED: 'CONNECTED_ACCOUNT_REVOCATION_NOT_SUPPORTED',+ NOT_REVOKABLE: 'CONNECTED_ACCOUNT_NOT_REVOKABLE',} as const;export class ComposioConnectedAccountNotFoundError extends ComposioError {@@ -156,3 +158,48 @@ export class ComposioLegacyConnectedAccountsEndpointRetiredError extends Composithis.name = 'ComposioLegacyConnectedAccountsEndpointRetiredError';}}++/**+ * Thrown by `composio.connectedAccounts.revoke()` when the toolkit behind the+ * connection does not support programmatic revocation at the provider (API+ * 400).+ */+export class ComposioConnectedAccountRevocationNotSupportedError extends ComposioError {+ constructor(+ message: string = 'This toolkit does not support programmatic revocation of connected accounts',+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}+ ) {+ super(message, {+ ...options,+ code: ConnectedAccountErrorCodes.REVOCATION_NOT_SUPPORTED,+ statusCode: 400,+ possibleFixes: options.possibleFixes || [+ "Revoke the grant from the provider's own settings page, then disable or delete the connected account with composio.connectedAccounts.disable() / delete().",+ ],+ });+ this.name = 'ComposioConnectedAccountRevocationNotSupportedError';+ }+}++/**+ * Thrown by `composio.connectedAccounts.revoke()` when the connection is not+ * in a state that can be revoked (API 409), for example it never completed+ * authentication. Revoking an already revoked connection is not an error: it+ * returns an empty `revokedTokens` list.+ */+export class ComposioConnectedAccountNotRevokableError extends ComposioError {+ constructor(+ message: string = 'The connected account is not in a revokable state',+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}+ ) {+ super(message, {+ ...options,+ code: ConnectedAccountErrorCodes.NOT_REVOKABLE,+ statusCode: 409,+ possibleFixes: options.possibleFixes || [+ 'Check the connection status with composio.connectedAccounts.get(); only ACTIVE connections can be revoked.',+ ],+ });+ this.name = 'ComposioConnectedAccountNotRevokableError';+ }+}diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.tsindex dbd491633..3e1b7df66 100644--- a/ts/packages/core/src/index.ts+++ b/ts/packages/core/src/index.ts@@ -45,6 +45,11 @@ export {export type { KeyMapping, KeySanitizationPolicy } from './utils/schemaPropertyKeys';export { AuthScheme } from './models/AuthScheme';export { MCP } from './models/MCP';+export { Webhooks, WebhookSubscriptions, WebhookEndpoints } from './models/Webhooks';+export { Logs } from './models/Logs';+export { Usage } from './models/Usage';+export { Keyring } from './models/Keyring';+export { CustomToolkits } from './models/CustomToolkits';export { RemoteFile } from './models/RemoteFile';export { createConnectionRequest } from './models/ConnectionRequest';export { ToolRouterSession } from './models/ToolRouterSession';@@ -59,6 +64,11 @@ export * from './types/connectedAccounts.types';export * from './types/toolkit.types';export * from './types/triggers.types';export * from './types/webhookEvents.types';+export * from './types/webhooks.types';+export * from './types/logs.types';+export * from './types/usage.types';+export * from './types/keyring.types';+export * from './types/customToolkits.types';export * from './types/mcp.types';export * from './types/files.types';export * from './types/connectionRequest.types';@@ -68,6 +78,7 @@ export * from './types/requestOptions.types';export * as constants from './utils/constants';export { default as logger } from './utils/logger';+export type { ComposioLogger, LogLevel } from './utils/logger';export { telemetry } from './telemetry/Telemetry';// Experimental custom tools — exported with experimental_ prefix for top-level importdiff --git a/ts/packages/core/src/models/ConnectedAccounts.ts b/ts/packages/core/src/models/ConnectedAccounts.tsindex 7bdb3939f..fb4cf678f 100644--- a/ts/packages/core/src/models/ConnectedAccounts.ts+++ b/ts/packages/core/src/models/ConnectedAccounts.ts@@ -5,7 +5,7 @@* @date 2025-05-05* @module ConnectedAccounts*/-import ComposioClient, { BadRequestError } from '@composio/client';+import ComposioClient, { BadRequestError, ConflictError } from '@composio/client';import {ConnectedAccountCreateResponse,ConnectedAccountDeleteResponse,@@ -29,6 +29,10 @@ import {ConnectedAccountStatuses,ConnectedAccountRefreshOptions,ConnectedAccountRefreshOptionsSchema,+ ConnectedAccountRevokeResponse,+ ConnectedAccountCompleteAuthParams,+ ConnectedAccountCompleteAuthParamsSchema,+ ConnectedAccountCompleteAuthResponse,UpdateConnectedAccountAclParams,UpdateConnectedAccountParams,UpdateConnectedAccountParamsSchema,@@ -45,9 +49,13 @@ import { telemetry } from '../telemetry/Telemetry';import {transformConnectedAccountListResponse,transformConnectedAccountResponse,+ transformConnectedAccountRevokeResponse,+ transformConnectedAccountCompleteAuthResponse,} from '../utils/transformers/connectedAccounts';import {ComposioAclOnlyForSharedError,+ ComposioConnectedAccountNotRevokableError,+ ComposioConnectedAccountRevocationNotSupportedError,ComposioFailedToCreateConnectedAccountLink,ComposioLegacyConnectedAccountsEndpointRetiredError,ComposioMultipleConnectedAccountsError,@@ -554,6 +562,11 @@ export class ConnectedAccounts {* // Refresh a connected account's credentials* const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');* ```+ *+ * @deprecated The `POST /connected_accounts/{id}/refresh` endpoint is deprecated by the+ * Composio API. Re-initiate authentication instead: `composio.connectedAccounts.link(userId, authConfigId)`+ * for a fresh connection, or `session.authorize(toolkit)` from a session. Behaviour is unchanged+ * while the endpoint remains available; do not generate new code against `refresh`.*/async refresh(nanoid: string,@@ -570,9 +583,14 @@ export class ConnectedAccounts {});}+ if (parsedOptions.data.validateCredentials !== undefined) {+ logger.warn(+ 'connectedAccounts.refresh(): the Composio API no longer accepts `validateCredentials`; the option is ignored.'+ );+ }+params = {query_redirect_url: parsedOptions.data.redirectUrl,- validate_credentials: parsedOptions.data.validateCredentials,};}@@ -582,6 +600,104 @@ export class ConnectedAccounts {);}+ /**+ * Revoke a connected account at the upstream provider.+ *+ * Best-effort upstream revocation of the stored tokens/credentials; on+ * success the connection status becomes `REVOKED`. Revoking an already+ * revoked connection returns an empty `revokedTokens` list without an+ * upstream call.+ *+ * @param {string} nanoid - The unique identifier of the connected account to revoke+ * @returns {Promise<ConnectedAccountRevokeResponse>} Which tokens were revoked and the resulting status+ * @throws {ComposioConnectedAccountRevocationNotSupportedError} If the toolkit does not support programmatic revocation (400)+ * @throws {ComposioConnectedAccountNotRevokableError} If the connection is not in a revokable state (409)+ *+ * @example+ * ```typescript+ * const result = await composio.connectedAccounts.revoke('conn_abc123');+ * console.log(result.connectedAccount.status); // 'REVOKED'+ * console.log(result.revokedTokens); // e.g. ['access_token', 'refresh_token']+ * ```+ */+ async revoke(+ nanoid: string,+ requestOptions?: ComposioRequestOptions+ ): Promise<ConnectedAccountRevokeResponse> {+ try {+ const result = await withCancellation(+ () => this.client.connectedAccounts.revoke(nanoid, requestOptions),+ requestOptions?.signal+ );+ return transformConnectedAccountRevokeResponse(result);+ } catch (error) {+ if (error instanceof BadRequestError) {+ throw new ComposioConnectedAccountRevocationNotSupportedError(+ `Connected account ${nanoid} cannot be revoked programmatically: ${error.message}`,+ { cause: error, meta: { nanoid } }+ );+ }+ if (error instanceof ConflictError) {+ throw new ComposioConnectedAccountNotRevokableError(+ `Connected account ${nanoid} is not in a revokable state: ${error.message}`,+ { cause: error, meta: { nanoid } }+ );+ }+ throw error;+ }+ }++ /**+ * Complete a deferred OAuth connection once you have verified the user's+ * identity.+ *+ * When your project has an OAuth callback verifier configured, Composio+ * does not activate a new OAuth connection by itself: it redirects to your+ * verifier with a single-use session URI. After confirming who the user is,+ * redeem that session URI here; Composio checks that your project owns the+ * pending connection and that `userId` is its owner, completes the token+ * exchange, and the connection becomes `ACTIVE`.+ *+ * The session URI is single-use: redeeming it twice, or after it expires,+ * fails with a 404 from the API.+ *+ * @param {ConnectedAccountCompleteAuthParams} params - `userId` the connection was initiated for and the verifier's `sessionUri`+ * @returns {Promise<ConnectedAccountCompleteAuthResponse>} The completed connection's ID and toolkit+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * // In your verifier route, after authenticating the user:+ * const { connectedAccountId, toolkitSlug } = await composio.connectedAccounts.completeAuth({+ * userId: 'user_123',+ * sessionUri, // the session URI from the verifier redirect+ * });+ * ```+ */+ async completeAuth(+ params: ConnectedAccountCompleteAuthParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<ConnectedAccountCompleteAuthResponse> {+ const parsedParams = ConnectedAccountCompleteAuthParamsSchema.safeParse(params);+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse connected account completeAuth params', {+ cause: parsedParams.error,+ });+ }+ const result = await withCancellation(+ () =>+ this.client.connectedAccounts.completeAuth(+ {+ user_id: parsedParams.data.userId,+ session_uri: parsedParams.data.sessionUri,+ },+ requestOptions+ ),+ requestOptions?.signal+ );+ return transformConnectedAccountCompleteAuthResponse(result);+ }+/*** Update the status of a connected account* @param {string} nanoid - Unique identifier of the connected accountdiff --git a/ts/packages/core/src/models/CustomToolkits.ts b/ts/packages/core/src/models/CustomToolkits.tsnew file mode 100644index 000000000..2fa91ecdb--- /dev/null+++ b/ts/packages/core/src/models/CustomToolkits.ts@@ -0,0 +1,169 @@+/**+ * @fileoverview `composio.experimental.customToolkits`: register and manage+ * project-owned custom toolkits.+ * **Experimental — custom toolkits are in pilot; shape may change.**+ *+ * @module CustomToolkits+ */+import ComposioClient from '@composio/client';+import {+ CustomToolkitDeleteResponse,+ CustomToolkitSyncParams,+ CustomToolkitSyncParamsSchema,+ CustomToolkitSyncResponse,+ CustomToolkitUpsertParams,+ CustomToolkitUpsertParamsSchema,+ CustomToolkitUpsertResponse,+} from '../types/customToolkits.types';+import { ComposioRequestOptions } from '../types/requestOptions.types';+import { ValidationError } from '../errors/ValidationErrors';+import { telemetry } from '../telemetry/Telemetry';+import { withCancellation } from '../utils/cancellation';+import {+ transformCustomToolkitDeleteResponse,+ transformCustomToolkitSyncParams,+ transformCustomToolkitSyncResponse,+ transformCustomToolkitUpsertParams,+ transformCustomToolkitUpsertResponse,+} from '../utils/transformers/customToolkits';++/**+ * `composio.experimental.customToolkits` — toolkits your project registers+ * from its own app or MCP server, with their own auth configs and connected+ * accounts. **Experimental — custom toolkits are in pilot; shape may change.**+ *+ * These live on the Composio platform. They are unrelated to the in-process+ * toolkits built with `experimental_createToolkit()`, which run inside your+ * application.+ *+ * @example+ * ```typescript+ * const { slug } = await composio.experimental.customToolkits.upsert({+ * slug: 'MY_TOOLKIT',+ * toolkitConfig: {+ * name: 'My Toolkit',+ * appUrl: 'https://mcp.example.com/mcp',+ * authSchemes: [{ mode: 'DCR_OAUTH', discoveryUrl: 'https://mcp.example.com/.well-known/oauth-authorization-server' }],+ * },+ * });+ * await composio.experimental.customToolkits.sync(slug);+ * ```+ */+export class CustomToolkits {+ private client: ComposioClient;++ constructor(client: ComposioClient) {+ this.client = client;+ telemetry.instrument(this, 'CustomToolkits');+ }++ /**+ * Creates a custom toolkit, or updates its display metadata (name, API key+ * field copy) when the project already owns a toolkit with this slug.+ * **Experimental — custom toolkits are in pilot; shape may change.**+ *+ * `appUrl` and `authSchemes` cannot change on an existing toolkit:+ * re-sending them unchanged is a no-op, and changing them fails with a 409.+ * Delete and re-register the toolkit instead, which revokes its connections.+ *+ * @param {CustomToolkitUpsertParams} params - The slug and toolkit configuration+ * @returns {Promise<CustomToolkitUpsertResponse>} The toolkit's slug+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * await composio.experimental.customToolkits.upsert({+ * slug: 'INTERNAL_API',+ * toolkitConfig: {+ * name: 'Internal API',+ * appUrl: 'https://mcp.internal.example.com/mcp',+ * authSchemes: [+ * { mode: 'API_KEY', headers: { Authorization: 'Bearer {{generic_api_key}}' } },+ * ],+ * },+ * });+ * ```+ */+ async upsert(+ params: CustomToolkitUpsertParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<CustomToolkitUpsertResponse> {+ const parsedParams = CustomToolkitUpsertParamsSchema.safeParse(params);+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse custom toolkit upsert params', {+ cause: parsedParams.error,+ });+ }+ const body = transformCustomToolkitUpsertParams(parsedParams.data);+ const result = await withCancellation(+ () => this.client.custom.upsert(body, requestOptions),+ requestOptions?.signal+ );+ return transformCustomToolkitUpsertResponse(result);+ }++ /**+ * Re-fetches the tool definitions of a custom toolkit from its remote MCP+ * server. Call it when automatic sync fails or the remote tools change.+ * **Experimental — custom toolkits are in pilot; shape may change.**+ *+ * @param {string} slug - The custom toolkit slug (`CUSTOM_...`)+ * @param {CustomToolkitSyncParams} [params] - Optional connected account to fetch the definitions with+ * @returns {Promise<CustomToolkitSyncResponse>} The toolkit version and number of tools synced+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * const { version, syncedCount } = await composio.experimental.customToolkits.sync(+ * 'CUSTOM_MY_TOOLKIT',+ * { connectedAccountId: 'ca_abc123' }+ * );+ * ```+ */+ async sync(+ slug: string,+ params?: CustomToolkitSyncParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<CustomToolkitSyncResponse> {+ const parsedParams = CustomToolkitSyncParamsSchema.safeParse(params ?? {});+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse custom toolkit sync params', {+ cause: parsedParams.error,+ });+ }+ const body = transformCustomToolkitSyncParams(slug, parsedParams.data);+ const result = await withCancellation(+ () => this.client.custom.sync(body, requestOptions),+ requestOptions?.signal+ );+ return transformCustomToolkitSyncResponse(result);+ }++ /**+ * Deletes a custom toolkit owned by the project, with its tools, auth+ * configs and connected accounts. The credentials behind those connected+ * accounts are revoked in background jobs (`revokeJobIds`).+ * **Experimental — custom toolkits are in pilot; shape may change.**+ *+ * Composio-managed toolkits cannot be deleted; the API answers 403.+ *+ * @param {string} slug - The custom toolkit slug (`CUSTOM_...`)+ * @returns {Promise<CustomToolkitDeleteResponse>} What was deleted+ *+ * @example+ * ```typescript+ * const result = await composio.experimental.customToolkits.delete('CUSTOM_MY_TOOLKIT');+ * console.log(result.connectedAccountsDeleted);+ * ```+ */+ async delete(+ slug: string,+ requestOptions?: ComposioRequestOptions+ ): Promise<CustomToolkitDeleteResponse> {+ const result = await withCancellation(+ () => this.client.custom.deleteToolkit(slug, requestOptions),+ requestOptions?.signal+ );+ return transformCustomToolkitDeleteResponse(result);+ }+}diff --git a/ts/packages/core/src/models/Experimental.ts b/ts/packages/core/src/models/Experimental.tsindex 971d97c81..e0202a543 100644--- a/ts/packages/core/src/models/Experimental.ts+++ b/ts/packages/core/src/models/Experimental.ts@@ -21,6 +21,8 @@ import {import { ValidationError } from '../errors/ValidationErrors';import { ComposioAclOnlyForSharedError } from '../errors';import { telemetry } from '../telemetry/Telemetry';+import { Usage } from './Usage';+import { CustomToolkits } from './CustomToolkits';/*** Server-side 400 message the API uses to reject ACL writes against a@@ -129,8 +131,33 @@ export async function updateConnectedAccountAcl(export class Experimental {private client: ComposioClient;+ /**+ * Project-scoped usage metering (`summary()` / `breakdown()`).+ * **Experimental — shape may change in future releases.**+ *+ * @example+ * ```typescript+ * const summary = await composio.experimental.usage.summary();+ * const byTool = await composio.experimental.usage.breakdown('tool_calls');+ * ```+ */+ usage: Usage;++ /**+ * Register and manage project-owned custom toolkits (`upsert()` / `sync()` / `delete()`).+ * **Experimental — custom toolkits are in pilot; shape may change.**+ *+ * @example+ * ```typescript+ * await composio.experimental.customToolkits.sync('CUSTOM_MY_TOOLKIT');+ * ```+ */+ customToolkits: CustomToolkits;+constructor(client: ComposioClient) {this.client = client;+ this.usage = new Usage(client);+ this.customToolkits = new CustomToolkits(client);telemetry.instrument(this, 'Experimental');}diff --git a/ts/packages/core/src/models/Keyring.ts b/ts/packages/core/src/models/Keyring.tsnew file mode 100644index 000000000..a7739484e--- /dev/null+++ b/ts/packages/core/src/models/Keyring.ts@@ -0,0 +1,65 @@+/**+ * @fileoverview The `composio.keyring` namespace: the public transfer keys of+ * the organization's customer-managed keyring.+ *+ * @module Keyring+ */+import ComposioClient from '@composio/client';+import { KeyringTransferKeysResponse } from '../types/keyring.types';+import { ComposioRequestOptions } from '../types/requestOptions.types';+import { telemetry } from '../telemetry/Telemetry';+import { withCancellation } from '../utils/cancellation';+import { transformKeyringTransferKeysResponse } from '../utils/transformers/keyring';++/**+ * `composio.keyring` — the organization's customer-managed keyring.+ *+ * @example+ * ```typescript+ * const { activeKid, keys } = await composio.keyring.listTransferKeys();+ * const sealingKey = keys.find(key => key.kid === activeKid);+ * ```+ */+export class Keyring {+ private client: ComposioClient;++ constructor(client: ComposioClient) {+ this.client = client;+ telemetry.instrument(this, 'Keyring');+ }++ /**+ * Lists the public transfer keys of the organization's active customer+ * keyring, the keys a secret is sealed to before it is sent to Composio.+ *+ * Always seal new secrets to the key whose `kid` is `activeKid`: a JWE with+ * `RSA-OAEP-256` key management, `A256GCM` content encryption, and the+ * `kid` in the protected header. Older keys stay listed so values sealed to+ * them remain openable.+ *+ * The organization behind the API key must have an ACTIVE customer keyring+ * instance; otherwise the API answers 404.+ *+ * @returns {Promise<KeyringTransferKeysResponse>} The active key ID and every accepted public JWK, newest first+ *+ * @example+ * ```typescript+ * import { CompactEncrypt, importJWK } from 'jose';+ *+ * const { activeKid, keys } = await composio.keyring.listTransferKeys();+ * const jwk = keys.find(key => key.kid === activeKid)!;+ * const sealed = await new CompactEncrypt(new TextEncoder().encode(secret))+ * .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: activeKid })+ * .encrypt(await importJWK(jwk, 'RSA-OAEP-256'));+ * ```+ */+ async listTransferKeys(+ requestOptions?: ComposioRequestOptions+ ): Promise<KeyringTransferKeysResponse> {+ const result = await withCancellation(+ () => this.client.keyring.listTransferKeys(requestOptions),+ requestOptions?.signal+ );+ return transformKeyringTransferKeysResponse(result);+ }+}diff --git a/ts/packages/core/src/models/Logs.ts b/ts/packages/core/src/models/Logs.tsnew file mode 100644index 000000000..fd2676e16--- /dev/null+++ b/ts/packages/core/src/models/Logs.ts@@ -0,0 +1,101 @@+/**+ * @fileoverview The `composio.logs` namespace: search and inspect+ * tool-execution logs for the project.+ *+ * @module Logs+ */+import ComposioClient from '@composio/client';+import {+ LogSearchParams,+ LogSearchParamsSchema,+ LogSearchResponse,+ ToolExecutionLogDetail,+} from '../types/logs.types';+import { ComposioRequestOptions } from '../types/requestOptions.types';+import { ValidationError } from '../errors/ValidationErrors';+import { telemetry } from '../telemetry/Telemetry';+import { withCancellation } from '../utils/cancellation';+import {+ transformLogSearchParams,+ transformLogSearchResponse,+ transformToolExecutionLogDetail,+} from '../utils/transformers/logs';++/**+ * `composio.logs` — tool-execution logs.+ *+ * @example+ * ```typescript+ * const { logs, nextCursor } = await composio.logs.search({+ * filters: [{ field: 'toolkit_slug', operator: '==', value: 'github' }],+ * limit: 20,+ * });+ * const detail = await composio.logs.get(logs[0].id);+ * ```+ */+export class Logs {+ private client: ComposioClient;++ constructor(client: ComposioClient) {+ this.client = client;+ telemetry.instrument(this, 'Logs');+ }++ /**+ * Search tool-execution logs with filters, a time range and cursor+ * pagination.+ *+ * @param {LogSearchParams} [params] - Filters, `timeRange`, `limit` and `cursor`+ * @returns {Promise<LogSearchResponse>} Matching logs and the next cursor+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * const { logs } = await composio.logs.search({+ * filters: [+ * { field: 'status', operator: '==', value: 'failed' },+ * { field: 'user_id', operator: '==', value: 'user_123' },+ * ],+ * timeRange: { from: Date.now() - 24 * 60 * 60 * 1000, to: Date.now() },+ * });+ * ```+ */+ async search(+ params?: LogSearchParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<LogSearchResponse> {+ const parsedParams = LogSearchParamsSchema.safeParse(params ?? {});+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse log search params', {+ cause: parsedParams.error,+ });+ }+ const body = transformLogSearchParams(parsedParams.data);+ const result = await withCancellation(+ () => this.client.logs.createToolExecution(body, requestOptions),+ requestOptions?.signal+ );+ return transformLogSearchResponse(result);+ }++ /**+ * Retrieve one tool-execution log with its full detail (timings, context,+ * source and raw `data`).+ *+ * @param {string} id - The log id+ * @returns {Promise<ToolExecutionLogDetail>} The log detail+ *+ * @example+ * ```typescript+ * const log = await composio.logs.get('log_abc123');+ * console.log(log.status, log.timings?.endTime);+ * ```+ */+ async get(id: string, requestOptions?: ComposioRequestOptions): Promise<ToolExecutionLogDetail> {+ const result = await withCancellation(+ () => this.client.logs.retrieveToolExecution(id, requestOptions),+ requestOptions?.signal+ );+ return transformToolExecutionLogDetail(result);+ }+}diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.tsindex 97f896d1b..1573db15a 100644--- a/ts/packages/core/src/models/ToolRouterSession.ts+++ b/ts/packages/core/src/models/ToolRouterSession.ts@@ -22,6 +22,9 @@ import {ToolRouterSessionWarning,ToolRouterUpdateSessionConfig,ToolRouterUpdateSessionConfigSchema,+ ToolRouterSessionConfigHistoryOptions,+ ToolRouterSessionConfigHistoryOptionsSchema,+ type ToolRouterSessionConfigHistoryResponse,type ToolRouterSessionDeleteResponse,} from '../types/toolRouter.types';import {@@ -692,6 +695,54 @@ export class ToolRouterSession<return deleteToolRouterSession(this.client, this.sessionId, requestOptions);}+ /**+ * Page through this session's configuration history, newest first. The+ * first page starts with the live config (`isCurrent: true`); every+ * `session.update()` archives the previous version as a history row.+ *+ * @param options - Optional `cursor` and `limit` (max 100)+ * @returns The config versions on this page plus pagination info+ * @throws {ValidationError} If the options fail validation+ *+ * @example+ * ```typescript+ * const { items, nextCursor } = await session.configHistory({ limit: 10 });+ * console.log(items[0].version, items[0].isCurrent); // e.g. 3, true+ * console.log(items[1].config.toolkits);+ * ```+ */+ async configHistory(+ options?: ToolRouterSessionConfigHistoryOptions,+ requestOptions?: ComposioRequestOptions+ ): Promise<ToolRouterSessionConfigHistoryResponse> {+ const parsedOptions = ToolRouterSessionConfigHistoryOptionsSchema.safeParse(options ?? {});+ if (!parsedOptions.success) {+ throw new ValidationError('Failed to parse config history options', {+ cause: parsedOptions.error,+ });+ }+ const query = {+ cursor: parsedOptions.data.cursor,+ limit: parsedOptions.data.limit,+ };+ const response = await withCancellation(+ () => this.client.toolRouter.session.configHistory(this.sessionId, query, requestOptions),+ requestOptions?.signal+ );+ return {+ items: response.items.map(item => ({+ version: item.version,+ createdAt: item.created_at,+ isCurrent: item.is_current,+ config: item.config,+ })),+ nextCursor: response.next_cursor ?? null,+ totalPages: response.total_pages,+ currentPage: response.current_page,+ totalItems: response.total_items,+ };+ }+// ── Private helpers ──────────────────────────────────────────/** Check if this session has any custom tools bound. */diff --git a/ts/packages/core/src/models/Toolkits.ts b/ts/packages/core/src/models/Toolkits.tsindex 086e87a5e..9d8fb03de 100644--- a/ts/packages/core/src/models/Toolkits.ts+++ b/ts/packages/core/src/models/Toolkits.ts@@ -6,6 +6,16 @@ import {ToolkitsListParamsSchema,ToolkitRetrieveCategoriesResponse,ToolkitAuthFieldsResponse,+ ToolkitGetManyParams,+ ToolkitGetManySlugsSchema,+ ToolkitsGetManyParamsSchema,+ ToolkitChangelogResponse,+ ToolkitRecommendScopesParams,+ ToolkitRecommendScopesParamsSchema,+ ToolkitRecommendScopesResponse,+ ToolkitListGrantContextsParams,+ ToolkitListGrantContextsParamsSchema,+ ToolkitListGrantContextsResponse,} from '../types/toolkit.types';import { ComposioToolkitFetchError, ComposioToolkitNotFoundError } from '../errors';import { ValidationError } from '../errors/ValidationErrors';@@ -18,7 +28,12 @@ import { AuthSchemeType } from '../types/authConfigs.types';import logger from '../utils/logger';import { APIError } from 'openai';import {+ transformToolkitChangelogResponse,+ transformToolkitListGrantContextsParams,+ transformToolkitListGrantContextsResponse,transformToolkitListResponse,+ transformToolkitRecommendScopesParams,+ transformToolkitRecommendScopesResponse,transformToolkitRetrieveCategoriesResponse,transformToolkitRetrieveResponse,} from '../utils/transformers/toolkits';@@ -191,6 +206,171 @@ export class Toolkits {return this.getToolkits(arg ?? {}, requestOptions);}+ /**+ * Retrieves several toolkits by slug in a single request.+ *+ * Returns the same transformed shape as `composio.toolkits.get({ ... })`.+ * Unknown slugs are simply absent from the result.+ *+ * @param {string[]} slugs - The toolkit slugs to retrieve (at least one)+ * @param {ToolkitGetManyParams} [params] - Optional filters and pagination, as for `list`+ * @returns {Promise<ToolKitListResponse>} The matching toolkits+ * @throws {ValidationError} If `slugs` is empty or the params fail validation+ * @throws {ComposioToolkitFetchError} If the request fails+ *+ * @example+ * ```typescript+ * const toolkits = await composio.toolkits.getMany(['github', 'slack']);+ * console.log(toolkits.map(toolkit => toolkit.name)); // ['GitHub', 'Slack']+ * ```+ */+ async getMany(+ slugs: string[],+ params?: ToolkitGetManyParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<ToolKitListResponse> {+ const parsedSlugs = ToolkitGetManySlugsSchema.safeParse(slugs);+ if (!parsedSlugs.success) {+ throw new ValidationError('Failed to parse toolkit slugs', {+ cause: parsedSlugs.error,+ });+ }+ const parsedParams = ToolkitsGetManyParamsSchema.safeParse(params ?? {});+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse toolkit getMany params', {+ cause: parsedParams.error,+ });+ }+ const body = {+ toolkits: parsedSlugs.data,+ category: parsedParams.data.category,+ managed_by: parsedParams.data.managedBy,+ sort_by: parsedParams.data.sortBy,+ cursor: parsedParams.data.cursor,+ limit: parsedParams.data.limit,+ };+ try {+ const result = await withCancellation(+ () => this.client.toolkits.retrieveMulti(body, requestOptions),+ requestOptions?.signal+ );+ return transformToolkitListResponse(result);+ } catch (error) {+ if (error instanceof ComposioRequestCancelledError) {+ throw error;+ }+ throw new ComposioToolkitFetchError('Failed to fetch toolkits', {+ meta: { slugs: parsedSlugs.data },+ cause: error,+ });+ }+ }++ /**+ * Retrieves the version changelog of every toolkit (the last 10 versions+ * per toolkit).+ *+ * @returns {Promise<ToolkitChangelogResponse>} Toolkits with their recent version changelogs+ *+ * @example+ * ```typescript+ * const { items } = await composio.toolkits.changelog();+ * const github = items.find(item => item.slug === 'github');+ * console.log(github?.versions[0]); // { version: '20250909_00', changelog: '...' }+ * ```+ */+ async changelog(requestOptions?: ComposioRequestOptions): Promise<ToolkitChangelogResponse> {+ const result = await withCancellation(+ () => this.client.toolkits.retrieveChangelog(requestOptions),+ requestOptions?.signal+ );+ return transformToolkitChangelogResponse(result);+ }++ /**+ * Recommends the OAuth scopes to request so a connection can run the given+ * tools.+ * **Experimental — the API marks this endpoint beta; shape may change.**+ *+ * The answer comes in two variants: `leastPrivilege` (narrowest documented+ * scope per requirement) and `fewest` (smallest set covering everything).+ * Pass `toolkitVersion` from a previous answer to pin the computation.+ *+ * @param {string} toolkitSlug - The toolkit to recommend scopes for+ * @param {ToolkitRecommendScopesParams} params - Tools to cover (`[]` for the whole toolkit), auth scheme, grant context and scope constraints+ * @returns {Promise<ToolkitRecommendScopesResponse>} The recommended scope sets+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * const { scopes } = await composio.toolkits.recommendScopes('gmail', {+ * tools: ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'],+ * });+ * console.log(scopes.leastPrivilege);+ * ```+ */+ async recommendScopes(+ toolkitSlug: string,+ params: ToolkitRecommendScopesParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<ToolkitRecommendScopesResponse> {+ const parsedParams = ToolkitRecommendScopesParamsSchema.safeParse(params);+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse toolkit recommendScopes params', {+ cause: parsedParams.error,+ });+ }+ const body = transformToolkitRecommendScopesParams(parsedParams.data);+ const result = await withCancellation(+ () => this.client.toolkits.recommendScopes(toolkitSlug, body, requestOptions),+ requestOptions?.signal+ );+ return transformToolkitRecommendScopesResponse(result);+ }++ /**+ * Lists the grant-context dimensions a toolkit's scope recommendation+ * depends on (for example the Google account type), with their allowed+ * values and the default the API assumes.+ * **Experimental — the API marks this endpoint beta; shape may change.**+ *+ * Pass a dimension and a value as `grantContext` to+ * `composio.toolkits.recommendScopes()` to tailor the recommendation.+ *+ * @param {string} toolkitSlug - The toolkit to list grant contexts for+ * @param {ToolkitListGrantContextsParams} [params] - Optional auth scheme and toolkit version+ * @returns {Promise<ToolkitListGrantContextsResponse>} The dimensions and the default grant context+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * const { grantContextDimensions } = await composio.toolkits.listGrantContexts('gmail');+ * const [accountType] = grantContextDimensions;+ * const { scopes } = await composio.toolkits.recommendScopes('gmail', {+ * tools: ['GMAIL_SEND_EMAIL'],+ * grantContext: { [accountType.dimension]: accountType.values[0] },+ * });+ * ```+ */+ async listGrantContexts(+ toolkitSlug: string,+ params?: ToolkitListGrantContextsParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<ToolkitListGrantContextsResponse> {+ const parsedParams = ToolkitListGrantContextsParamsSchema.safeParse(params ?? {});+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse toolkit listGrantContexts params', {+ cause: parsedParams.error,+ });+ }+ const query = transformToolkitListGrantContextsParams(parsedParams.data);+ const result = await withCancellation(+ () => this.client.toolkits.retrieveScopesGrantContext(toolkitSlug, query, requestOptions),+ requestOptions?.signal+ );+ return transformToolkitListGrantContextsResponse(result);+ }+private async getAuthConfigFields(toolkitSlug: string,authScheme: AuthSchemeType | null,diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.tsindex 922abfde3..b9065c728 100644--- a/ts/packages/core/src/models/Tools.ts+++ b/ts/packages/core/src/models/Tools.ts@@ -540,7 +540,9 @@ export class Tools<...(limit ? { limit } : {}),...('tags' in queryParams.data ? { tags: queryParams.data.tags } : {}),...('scopes' in queryParams.data ? { scopes: queryParams.data.scopes } : {}),- ...('search' in queryParams.data ? { search: queryParams.data.search } : {}),+ // `search` is the SDK's public option; the API deprecated the `search`+ // wire param in favour of `query`, so send the replacement.+ ...('search' in queryParams.data ? { query: queryParams.data.search } : {}),...('authConfigIds' in queryParams.data? { auth_config_ids: queryParams.data.authConfigIds }: {}),diff --git a/ts/packages/core/src/models/Triggers.ts b/ts/packages/core/src/models/Triggers.tsindex e38ac7b36..d5000c2d0 100644--- a/ts/packages/core/src/models/Triggers.ts+++ b/ts/packages/core/src/models/Triggers.ts@@ -33,11 +33,10 @@ import {WebhookTriggerPayloadV3Schema,WebhookVersion,WebhookVersions,- DefaultWebhookSubscriptionEvents,SetWebhookSubscriptionParams,- SetWebhookSubscriptionParamsSchema,WebhookSubscription,} from '../types/triggers.types';+import { upsertWebhookSubscription } from './Webhooks';import logger from '../utils/logger';import { telemetry } from '../telemetry/Telemetry';import { ValidationError } from '../errors';@@ -75,63 +74,6 @@ const toStringOrDefault = (value: unknown, defaultValue: string): string => {return str.length > 0 ? str : defaultValue;};-const WEBHOOK_SUBSCRIPTIONS_PATH = '/api/v3.1/webhook_subscriptions';--type RawWebhookSubscription = Record<string, unknown> & {- id?: unknown;- webhook_url?: unknown;- webhookUrl?: unknown;- version?: unknown;- enabled_events?: unknown;- enabledEvents?: unknown;- secret?: unknown;- created_at?: unknown;- createdAt?: unknown;- updated_at?: unknown;- updatedAt?: unknown;-};--type RawWebhookSubscriptionListResponse = Record<string, unknown> & {- items?: unknown;-};--const asRecord = (value: unknown): Record<string, unknown> =>- value !== null && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : {};--const firstString = (value: unknown): string | undefined =>- typeof value === 'string' && value.length > 0 ? value : undefined;--const stringArray = (value: unknown): string[] =>- Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];--const transformWebhookSubscription = (subscription: unknown): WebhookSubscription => {- const raw = asRecord(subscription) as RawWebhookSubscription;-- // Map to camelCase explicitly — do NOT spread `...raw`, or the response's- // snake_case keys (webhook_url, enabled_events, created_at, ...) leak into the- // public object alongside their camelCase counterparts.- return {- id: firstString(raw.id) ?? '',- webhookUrl: firstString(raw.webhook_url) ?? firstString(raw.webhookUrl) ?? '',- version: (firstString(raw.version) ?? WebhookVersions.V3) as WebhookVersion,- enabledEvents: stringArray(raw.enabled_events).length- ? stringArray(raw.enabled_events)- : stringArray(raw.enabledEvents),- secret: firstString(raw.secret),- createdAt: firstString(raw.created_at) ?? firstString(raw.createdAt),- updatedAt: firstString(raw.updated_at) ?? firstString(raw.updatedAt),- };-};--const firstWebhookSubscriptionId = (- response: RawWebhookSubscriptionListResponse-): string | undefined => {- const firstItem = Array.isArray(response.items) ? response.items[0] : undefined;- return firstString(asRecord(firstItem).id);-};-/*** The signature header names Composio sends with every webhook delivery.* @private@@ -234,34 +176,7 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u* ```*/async setWebhookSubscription(params: SetWebhookSubscriptionParams): Promise<WebhookSubscription> {- const parsedParams = SetWebhookSubscriptionParamsSchema.safeParse(params);-- if (!parsedParams.success) {- throw new ValidationError(`Invalid parameters passed to set webhook subscription`, {- cause: parsedParams.error,- });- }-- const body = {- webhook_url: parsedParams.data.webhookUrl,- enabled_events: parsedParams.data.enabledEvents ?? [...DefaultWebhookSubscriptionEvents],- version: parsedParams.data.version ?? WebhookVersions.V3,- };-- const existing = await this.client.get<RawWebhookSubscriptionListResponse>(- WEBHOOK_SUBSCRIPTIONS_PATH,- { query: { limit: 1 } }- );- const subscriptionId = firstWebhookSubscriptionId(existing);-- const subscription = subscriptionId- ? await this.client.patch<RawWebhookSubscription>(- `${WEBHOOK_SUBSCRIPTIONS_PATH}/${encodeURIComponent(subscriptionId)}`,- { body }- )- : await this.client.post<RawWebhookSubscription>(WEBHOOK_SUBSCRIPTIONS_PATH, { body });-- return transformWebhookSubscription(subscription);+ return upsertWebhookSubscription(this.client, params);}/**diff --git a/ts/packages/core/src/models/Usage.ts b/ts/packages/core/src/models/Usage.tsnew file mode 100644index 000000000..777ce641b--- /dev/null+++ b/ts/packages/core/src/models/Usage.ts@@ -0,0 +1,119 @@+/**+ * @fileoverview `composio.experimental.usage`: project-scoped metering.+ * **Experimental — shape may change in future releases.**+ *+ * @module Usage+ */+import ComposioClient from '@composio/client';+import {+ UsageBreakdownParams,+ UsageBreakdownParamsSchema,+ UsageBreakdownResponse,+ UsageSummaryParams,+ UsageSummaryParamsSchema,+ UsageSummaryResponse,+} from '../types/usage.types';+import { ComposioRequestOptions } from '../types/requestOptions.types';+import { ValidationError } from '../errors/ValidationErrors';+import { telemetry } from '../telemetry/Telemetry';+import { withCancellation } from '../utils/cancellation';+import {+ transformUsageBreakdownParams,+ transformUsageBreakdownResponse,+ transformUsageSummaryParams,+ transformUsageSummaryResponse,+} from '../utils/transformers/usage';++/**+ * `composio.experimental.usage` — metering for the project the API key+ * belongs to. **Experimental — shape may change in future releases.**+ *+ * @example+ * ```typescript+ * const summary = await composio.experimental.usage.summary();+ * console.log(summary.entities.tool_calls?.totalQuantity);+ *+ * const byTool = await composio.experimental.usage.breakdown('tool_calls', {+ * groupBy: 'tool_slug',+ * limit: 10,+ * });+ * ```+ */+export class Usage {+ private client: ComposioClient;++ constructor(client: ComposioClient) {+ this.client = client;+ telemetry.instrument(this, 'Usage');+ }++ /**+ * Usage totals per metering entity type for a time range.+ * **Experimental — shape may change in future releases.**+ *+ * @param {UsageSummaryParams} [params] - Optional range, `entityTypes` and filters+ * @returns {Promise<UsageSummaryResponse>} Totals keyed by entity type+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * const summary = await composio.experimental.usage.summary({+ * from: Date.now() - 7 * 24 * 60 * 60 * 1000,+ * filters: { userId: ['user_123'] },+ * });+ * ```+ */+ async summary(+ params?: UsageSummaryParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<UsageSummaryResponse> {+ const parsedParams = UsageSummaryParamsSchema.safeParse(params ?? {});+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse usage summary params', {+ cause: parsedParams.error,+ });+ }+ const body = transformUsageSummaryParams(parsedParams.data);+ const result = await withCancellation(+ () => this.client.project.usage.retrieveSummary(body, requestOptions),+ requestOptions?.signal+ );+ return transformUsageSummaryResponse(result);+ }++ /**+ * Usage for one metering entity type, grouped by a dimension.+ * **Experimental — shape may change in future releases.**+ *+ * @param {string} entityType - Entity type to break down (e.g. `tool_calls`, `sessions`)+ * @param {UsageBreakdownParams} [params] - Optional range, `groupBy`, ordering, `limit` and filters+ * @returns {Promise<UsageBreakdownResponse>} Totals plus per-group rows+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * const byUser = await composio.experimental.usage.breakdown('sessions', {+ * groupBy: 'user_id',+ * orderBy: 'event_count',+ * });+ * ```+ */+ async breakdown(+ entityType: string,+ params?: UsageBreakdownParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<UsageBreakdownResponse> {+ const parsedParams = UsageBreakdownParamsSchema.safeParse(params ?? {});+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse usage breakdown params', {+ cause: parsedParams.error,+ });+ }+ const body = transformUsageBreakdownParams(parsedParams.data);+ const result = await withCancellation(+ () => this.client.project.usage.retrieve(entityType, body, requestOptions),+ requestOptions?.signal+ );+ return transformUsageBreakdownResponse(result);+ }+}diff --git a/ts/packages/core/src/models/Webhooks.ts b/ts/packages/core/src/models/Webhooks.tsnew file mode 100644index 000000000..fe2c044eb--- /dev/null+++ b/ts/packages/core/src/models/Webhooks.ts@@ -0,0 +1,520 @@+/**+ * @fileoverview The `composio.webhooks` namespace: project webhook+ * subscriptions (outbound event delivery) and webhook endpoints (inbound+ * per-toolkit ingress URLs).+ *+ * @module Webhooks+ */+import ComposioClient from '@composio/client';+import { z } from 'zod/v3';+import {+ DefaultWebhookSubscriptionEvents,+ WebhookSubscription,+ WebhookVersions,+} from '../types/triggers.types';+import {+ WebhookEndpoint,+ WebhookEndpointCreateParams,+ WebhookEndpointCreateParamsSchema,+ WebhookEndpointListParams,+ WebhookEndpointListParamsSchema,+ WebhookEndpointListResponse,+ WebhookEndpointReplaceParams,+ WebhookEndpointReplaceParamsSchema,+ WebhookEndpointUpdateParams,+ WebhookEndpointUpdateParamsSchema,+ WebhookSubscriptionEventTypesResponse,+ WebhookSubscriptionDeleteResponse,+ WebhookSubscriptionListParams,+ WebhookSubscriptionListParamsSchema,+ WebhookSubscriptionListResponse,+ WebhookSubscriptionRotateSecretResponse,+ WebhookSubscriptionSetParams,+ WebhookSubscriptionSetParamsSchema,+ WebhookSubscriptionUpdateParams,+ WebhookSubscriptionUpdateParamsSchema,+} from '../types/webhooks.types';+import { ComposioRequestOptions } from '../types/requestOptions.types';+import { ValidationError } from '../errors/ValidationErrors';+import { telemetry } from '../telemetry/Telemetry';+import { withCancellation } from '../utils/cancellation';+import {+ transformWebhookEndpoint,+ transformWebhookEndpointListResponse,+ transformWebhookSubscriptionEventTypesResponse,+ transformWebhookSubscription,+ transformWebhookSubscriptionDeleteResponse,+ transformWebhookSubscriptionListResponse,+ transformWebhookSubscriptionRotateSecretResponse,+} from '../utils/transformers/webhooks';++/**+ * The only part of the `list({ limit: 1 })` probe the upsert needs: the id of+ * the first (and, since the API allows one subscription per project, only)+ * subscription. Parsed at the boundary so a malformed payload never reaches+ * the update path.+ */+const FirstWebhookSubscriptionIdSchema = z+ .object({+ items: z.array(z.object({ id: z.string().min(1) }).passthrough()).optional(),+ })+ .passthrough()+ .transform(response => response.items?.[0]?.id);++/**+ * Create-or-update the project webhook subscription.+ *+ * Shared by `composio.webhooks.subscriptions.set()` and the legacy+ * `composio.triggers.setWebhookSubscription()` so both issue the exact same+ * call sequence: `webhookSubscriptions.list({ limit: 1 })`, then+ * `webhookSubscriptions.update(id, body)` when a subscription exists,+ * otherwise `webhookSubscriptions.create(body)`.+ *+ * @internal+ */+export async function upsertWebhookSubscription(+ client: ComposioClient,+ params: WebhookSubscriptionSetParams,+ requestOptions?: ComposioRequestOptions+): Promise<WebhookSubscription> {+ const parsedParams = WebhookSubscriptionSetParamsSchema.safeParse(params);++ if (!parsedParams.success) {+ throw new ValidationError(`Invalid parameters passed to set webhook subscription`, {+ cause: parsedParams.error,+ });+ }++ const body = {+ webhook_url: parsedParams.data.webhookUrl,+ enabled_events: parsedParams.data.enabledEvents ?? [...DefaultWebhookSubscriptionEvents],+ version: parsedParams.data.version ?? WebhookVersions.V3,+ };++ const existing = await withCancellation(+ () => client.webhookSubscriptions.list({ limit: 1 }, requestOptions),+ requestOptions?.signal+ );+ const parsedExisting = FirstWebhookSubscriptionIdSchema.safeParse(existing);+ if (!parsedExisting.success) {+ throw new ValidationError('Failed to parse webhook subscription list response', {+ cause: parsedExisting.error,+ });+ }+ const subscriptionId = parsedExisting.data;++ const subscription = await withCancellation(+ () =>+ subscriptionId+ ? client.webhookSubscriptions.update(subscriptionId, body, requestOptions)+ : client.webhookSubscriptions.create(body, requestOptions),+ requestOptions?.signal+ );++ return transformWebhookSubscription(subscription);+}++/**+ * `composio.webhooks.subscriptions` — the project's outbound webhook+ * subscription. The API allows one subscription per project; every response+ * includes the signing `secret` used to verify deliveries with+ * `composio.triggers.verifyWebhook()` / `composio.triggers.parse()`.+ */+export class WebhookSubscriptions {+ private client: ComposioClient;++ constructor(client: ComposioClient) {+ this.client = client;+ telemetry.instrument(this, 'WebhookSubscriptions');+ }++ /**+ * List the project's webhook subscriptions.+ *+ * @param {WebhookSubscriptionListParams} [query] - Pagination options+ * @returns {Promise<WebhookSubscriptionListResponse>} Paginated subscriptions+ *+ * @example+ * ```typescript+ * const { items } = await composio.webhooks.subscriptions.list();+ * console.log(items[0]?.webhookUrl);+ * ```+ */+ async list(+ query?: WebhookSubscriptionListParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookSubscriptionListResponse> {+ const parsedQuery = WebhookSubscriptionListParamsSchema.safeParse(query ?? {});+ if (!parsedQuery.success) {+ throw new ValidationError('Failed to parse webhook subscription list query', {+ cause: parsedQuery.error,+ });+ }+ const listParams = {+ limit: parsedQuery.data.limit,+ cursor: parsedQuery.data.cursor,+ };+ const result = await withCancellation(+ () => this.client.webhookSubscriptions.list(listParams, requestOptions),+ requestOptions?.signal+ );+ return transformWebhookSubscriptionListResponse(result);+ }++ /**+ * Retrieve a webhook subscription by id.+ *+ * @param {string} id - The subscription id+ * @returns {Promise<WebhookSubscription>} The subscription, including its signing secret+ *+ * @example+ * ```typescript+ * const subscription = await composio.webhooks.subscriptions.get('whs_abc123');+ * console.log(subscription.enabledEvents);+ * ```+ */+ async get(id: string, requestOptions?: ComposioRequestOptions): Promise<WebhookSubscription> {+ const result = await withCancellation(+ () => this.client.webhookSubscriptions.retrieve(id, requestOptions),+ requestOptions?.signal+ );+ return transformWebhookSubscription(result);+ }++ /**+ * Create or update the project webhook subscription.+ *+ * If a subscription already exists it is updated in place, otherwise a new+ * one is created. By default this subscribes to V3 trigger message events.+ *+ * @param {WebhookSubscriptionSetParams} params - `webhookUrl`, optional `enabledEvents` and `version`+ * @returns {Promise<WebhookSubscription>} The resulting subscription+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * const subscription = await composio.webhooks.subscriptions.set({+ * webhookUrl: `${APP_URL}/webhooks/composio`,+ * enabledEvents: ['composio.trigger.message', 'composio.connected_account.expired'],+ * });+ * process.env.COMPOSIO_WEBHOOK_SECRET = subscription.secret;+ * ```+ */+ async set(+ params: WebhookSubscriptionSetParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookSubscription> {+ return upsertWebhookSubscription(this.client, params, requestOptions);+ }++ /**+ * Update an existing webhook subscription. Only the provided fields change.+ *+ * @param {string} id - The subscription id+ * @param {WebhookSubscriptionUpdateParams} params - Fields to update+ * @returns {Promise<WebhookSubscription>} The updated subscription+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * await composio.webhooks.subscriptions.update('whs_abc123', {+ * enabledEvents: ['composio.trigger.message'],+ * });+ * ```+ */+ async update(+ id: string,+ params: WebhookSubscriptionUpdateParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookSubscription> {+ const parsedParams = WebhookSubscriptionUpdateParamsSchema.safeParse(params);+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse webhook subscription update params', {+ cause: parsedParams.error,+ });+ }+ const body = {+ webhook_url: parsedParams.data.webhookUrl,+ enabled_events: parsedParams.data.enabledEvents,+ version: parsedParams.data.version,+ };+ const result = await withCancellation(+ () => this.client.webhookSubscriptions.update(id, body, requestOptions),+ requestOptions?.signal+ );+ return transformWebhookSubscription(result);+ }++ /**+ * Delete a webhook subscription. Deliveries stop immediately.+ *+ * @param {string} id - The subscription id+ * @returns {Promise<WebhookSubscriptionDeleteResponse>} `{ success }`+ *+ * @example+ * ```typescript+ * await composio.webhooks.subscriptions.delete('whs_abc123');+ * ```+ */+ async delete(+ id: string,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookSubscriptionDeleteResponse> {+ const result = await withCancellation(+ () => this.client.webhookSubscriptions.delete(id, requestOptions),+ requestOptions?.signal+ );+ return transformWebhookSubscriptionDeleteResponse(result);+ }++ /**+ * Rotate the signing secret of a webhook subscription. The previous secret+ * stops validating, so update your verifier with the returned `secret`.+ *+ * @param {string} id - The subscription id+ * @returns {Promise<WebhookSubscriptionRotateSecretResponse>} `{ id, secret }`+ *+ * @example+ * ```typescript+ * const { secret } = await composio.webhooks.subscriptions.rotateSecret('whs_abc123');+ * ```+ */+ async rotateSecret(+ id: string,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookSubscriptionRotateSecretResponse> {+ const result = await withCancellation(+ () => this.client.webhookSubscriptions.rotateSecret(id, requestOptions),+ requestOptions?.signal+ );+ return transformWebhookSubscriptionRotateSecretResponse(result);+ }++ /**+ * List the event types a subscription can enable, with the payload+ * versions each one supports.+ *+ * @returns {Promise<WebhookSubscriptionEventTypesResponse>} The available event types+ *+ * @example+ * ```typescript+ * const { items } = await composio.webhooks.subscriptions.listEventTypes();+ * console.log(items.map(item => item.eventType));+ * ```+ */+ async listEventTypes(+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookSubscriptionEventTypesResponse> {+ const result = await withCancellation(+ () => this.client.webhookSubscriptions.listEventTypes(requestOptions),+ requestOptions?.signal+ );+ return transformWebhookSubscriptionEventTypesResponse(result);+ }+}++/**+ * `composio.webhooks.endpoints` — inbound webhook endpoints. Each endpoint is+ * the ingress URL Composio exposes for one toolkit + OAuth app pair, which you+ * register with the third-party provider so it can push events to Composio.+ */+export class WebhookEndpoints {+ private client: ComposioClient;++ constructor(client: ComposioClient) {+ this.client = client;+ telemetry.instrument(this, 'WebhookEndpoints');+ }++ /**+ * List webhook endpoints, optionally filtered by toolkit.+ *+ * @param {WebhookEndpointListParams} [query] - Optional `toolkitSlug` filter+ * @returns {Promise<WebhookEndpointListResponse>} The endpoints+ *+ * @example+ * ```typescript+ * const { items } = await composio.webhooks.endpoints.list({ toolkitSlug: 'slack' });+ * ```+ */+ async list(+ query?: WebhookEndpointListParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookEndpointListResponse> {+ const parsedQuery = WebhookEndpointListParamsSchema.safeParse(query ?? {});+ if (!parsedQuery.success) {+ throw new ValidationError('Failed to parse webhook endpoint list query', {+ cause: parsedQuery.error,+ });+ }+ const listParams = { toolkit_slug: parsedQuery.data.toolkitSlug };+ const result = await withCancellation(+ () => this.client.webhookEndpoints.list(listParams, requestOptions),+ requestOptions?.signal+ );+ return transformWebhookEndpointListResponse(result);+ }++ /**+ * Retrieve a webhook endpoint by its nano id.+ *+ * @param {string} nanoId - The endpoint nano id (e.g. `we_abc123`)+ * @returns {Promise<WebhookEndpoint>} The endpoint, with secret setup values masked+ *+ * @example+ * ```typescript+ * const endpoint = await composio.webhooks.endpoints.get('we_abc123');+ * console.log(endpoint.webhookUrl);+ * ```+ */+ async get(nanoId: string, requestOptions?: ComposioRequestOptions): Promise<WebhookEndpoint> {+ const result = await withCancellation(+ () => this.client.webhookEndpoints.retrieve(nanoId, requestOptions),+ requestOptions?.signal+ );+ return transformWebhookEndpoint(result);+ }++ /**+ * Create a webhook endpoint for a toolkit + OAuth app pair. Returns the+ * existing endpoint when one already exists for that pair.+ *+ * @param {WebhookEndpointCreateParams} params - `toolkitSlug` and `clientId`+ * @returns {Promise<WebhookEndpoint>} The endpoint; register `webhookUrl` with the provider+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * const endpoint = await composio.webhooks.endpoints.create({+ * toolkitSlug: 'slack',+ * clientId: 'my-slack-app-client-id',+ * });+ * ```+ */+ async create(+ params: WebhookEndpointCreateParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookEndpoint> {+ const parsedParams = WebhookEndpointCreateParamsSchema.safeParse(params);+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse webhook endpoint create params', {+ cause: parsedParams.error,+ });+ }+ const body = {+ toolkit_slug: parsedParams.data.toolkitSlug,+ client_id: parsedParams.data.clientId,+ };+ const result = await withCancellation(+ () => this.client.webhookEndpoints.create(body, requestOptions),+ requestOptions?.signal+ );+ return transformWebhookEndpoint(result);+ }++ /**+ * Replace the setup fields of a webhook endpoint. All required setup fields+ * for the toolkit must be provided — this is the initial configuration.+ *+ * @param {string} nanoId - The endpoint nano id+ * @param {WebhookEndpointReplaceParams} params - `data` with every required setup field+ * @returns {Promise<WebhookEndpoint>} The configured endpoint+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * await composio.webhooks.endpoints.replace('we_abc123', {+ * data: { signing_secret: process.env.SLACK_SIGNING_SECRET! },+ * });+ * ```+ */+ async replace(+ nanoId: string,+ params: WebhookEndpointReplaceParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookEndpoint> {+ const parsedParams = WebhookEndpointReplaceParamsSchema.safeParse(params);+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse webhook endpoint replace params', {+ cause: parsedParams.error,+ });+ }+ const result = await withCancellation(+ () =>+ this.client.webhookEndpoints.replace(+ nanoId,+ { data: parsedParams.data.data },+ requestOptions+ ),+ requestOptions?.signal+ );+ return transformWebhookEndpoint(result);+ }++ /**+ * Merge setup fields into a webhook endpoint. Omitted fields are preserved.+ *+ * @param {string} nanoId - The endpoint nano id+ * @param {WebhookEndpointUpdateParams} params - `data` with the fields to change+ * @returns {Promise<WebhookEndpoint>} The updated endpoint+ * @throws {ValidationError} If the params fail validation+ *+ * @example+ * ```typescript+ * await composio.webhooks.endpoints.update('we_abc123', {+ * data: { signing_secret: 'rotated-secret' },+ * });+ * ```+ */+ async update(+ nanoId: string,+ params: WebhookEndpointUpdateParams,+ requestOptions?: ComposioRequestOptions+ ): Promise<WebhookEndpoint> {+ const parsedParams = WebhookEndpointUpdateParamsSchema.safeParse(params);+ if (!parsedParams.success) {+ throw new ValidationError('Failed to parse webhook endpoint update params', {+ cause: parsedParams.error,+ });+ }+ const result = await withCancellation(+ () =>+ this.client.webhookEndpoints.update(+ nanoId,+ { data: parsedParams.data.data },+ requestOptions+ ),+ requestOptions?.signal+ );+ return transformWebhookEndpoint(result);+ }+}++/**+ * `composio.webhooks` namespace.+ *+ * - `subscriptions`: the project's outbound webhook subscription (where+ * Composio delivers trigger and lifecycle events).+ * - `endpoints`: inbound ingress URLs for third-party providers, one per+ * toolkit + OAuth app pair.+ *+ * @example+ * ```typescript+ * const subscription = await composio.webhooks.subscriptions.set({+ * webhookUrl: 'https://example.com/webhooks/composio',+ * });+ * const endpoints = await composio.webhooks.endpoints.list({ toolkitSlug: 'slack' });+ * ```+ */+export class Webhooks {+ /** Manage the project's outbound webhook subscription. */+ subscriptions: WebhookSubscriptions;+ /** Manage inbound webhook endpoints per toolkit + OAuth app. */+ endpoints: WebhookEndpoints;++ constructor(client: ComposioClient) {+ this.subscriptions = new WebhookSubscriptions(client);+ this.endpoints = new WebhookEndpoints(client);+ telemetry.instrument(this, 'Webhooks');+ }+}diff --git a/ts/packages/core/src/types/authConfigs.types.ts b/ts/packages/core/src/types/authConfigs.types.tsindex bb1f7a0be..840dbc0fc 100644--- a/ts/packages/core/src/types/authConfigs.types.ts+++ b/ts/packages/core/src/types/authConfigs.types.ts@@ -20,6 +20,7 @@ export const AuthSchemeTypes = {SERVICE_ACCOUNT: 'SERVICE_ACCOUNT',SAML: 'SAML',DCR_OAUTH: 'DCR_OAUTH',+ CIMD_OAUTH: 'CIMD_OAUTH',S2S_OAUTH2: 'S2S_OAUTH2',} as const;export type AuthSchemeType = (typeof AuthSchemeTypes)[keyof typeof AuthSchemeTypes];@@ -47,6 +48,7 @@ export const AuthSchemeEnum = z.enum(['SERVICE_ACCOUNT','SAML','DCR_OAUTH',+ 'CIMD_OAUTH','S2S_OAUTH2',]);export const CreateCustomAuthConfigParamsSchema = z.object({diff --git a/ts/packages/core/src/types/connectedAccounts.types.ts b/ts/packages/core/src/types/connectedAccounts.types.tsindex dd16fb1c2..8c6bb3ba8 100644--- a/ts/packages/core/src/types/connectedAccounts.types.ts+++ b/ts/packages/core/src/types/connectedAccounts.types.ts@@ -356,6 +356,10 @@ export type CreateConnectedAccountLinkResponse = z.infer<export const ConnectedAccountRefreshOptionsSchema = z.object({redirectUrl: z.string().optional(),+ /**+ * @deprecated The Composio API no longer accepts this field. It is ignored+ * and `refresh()` logs a warning when it is set.+ */validateCredentials: z.boolean().optional(),});export type ConnectedAccountRefreshOptions = z.infer<typeof ConnectedAccountRefreshOptionsSchema>;@@ -393,3 +397,53 @@ export const UpdateConnectedAccountAclParamsSchema = ConnectedAccountAclConfigSc});export type UpdateConnectedAccountAclParams = z.infer<typeof UpdateConnectedAccountAclParamsSchema>;++/**+ * Response of `composio.connectedAccounts.revoke()`.+ */+export const ConnectedAccountRevokedTokenSchema = z.enum([+ 'access_token',+ 'refresh_token',+ 'credential',+]);+export type ConnectedAccountRevokedToken = z.infer<typeof ConnectedAccountRevokedTokenSchema>;++export const ConnectedAccountRevokeResponseSchema = z.object({+ /**+ * Tokens revoked at the provider on this call. An empty array means the+ * connection was already revoked (no upstream dispatch).+ */+ revokedTokens: z.array(ConnectedAccountRevokedTokenSchema),+ connectedAccount: z.object({+ id: z.string(),+ /** The connection status after this call (`REVOKED` on success). */+ status: ConnectedAccountStatusSchema,+ }),+});+export type ConnectedAccountRevokeResponse = z.infer<typeof ConnectedAccountRevokeResponseSchema>;++/**+ * Params for `composio.connectedAccounts.completeAuth()`.+ */+export const ConnectedAccountCompleteAuthParamsSchema = z.object({+ /** The user the connection was initiated for. Must match the connection owner. */+ userId: z.string().min(1),+ /** The opaque, single-use session URI your OAuth callback verifier received. */+ sessionUri: z.string().min(1),+});+export type ConnectedAccountCompleteAuthParams = z.infer<+ typeof ConnectedAccountCompleteAuthParamsSchema+>;++/**+ * Response of `composio.connectedAccounts.completeAuth()`.+ */+export const ConnectedAccountCompleteAuthResponseSchema = z.object({+ /** The connection that was completed; it is now `ACTIVE`. */+ connectedAccountId: z.string(),+ /** The toolkit the connection belongs to. */+ toolkitSlug: z.string(),+});+export type ConnectedAccountCompleteAuthResponse = z.infer<+ typeof ConnectedAccountCompleteAuthResponseSchema+>;diff --git a/ts/packages/core/src/types/customToolkits.types.ts b/ts/packages/core/src/types/customToolkits.types.tsnew file mode 100644index 000000000..803758c99--- /dev/null+++ b/ts/packages/core/src/types/customToolkits.types.ts@@ -0,0 +1,102 @@+import { z } from 'zod/v3';++/**+ * How end users authenticate to a custom toolkit.+ * **Experimental — custom toolkits are in pilot; shape may change.**+ */+export const CustomToolkitAuthSchemeSchema = z.discriminatedUnion('mode', [+ z.object({ mode: z.literal('NO_AUTH') }),+ z.object({+ mode: z.literal('API_KEY'),+ /**+ * Headers sent with each request. Write `{{generic_api_key}}` where the+ * end user's API key goes, for example+ * `{ Authorization: 'Bearer {{generic_api_key}}' }`.+ */+ headers: z.record(z.string(), z.string()),+ /** End-user copy for the API key input on the connect page. */+ apiKeyField: z+ .object({+ displayName: z.string().min(1).max(100).optional(),+ description: z.string().min(1).max(500).optional(),+ })+ .optional(),+ }),+ z.object({+ mode: z.literal('DCR_OAUTH'),+ /**+ * Where to fetch the full auth scheme, usually the+ * `/.well-known/oauth-authorization-server` path of your MCP URL.+ */+ discoveryUrl: z.string().url(),+ }),+]);+export type CustomToolkitAuthScheme = z.infer<typeof CustomToolkitAuthSchemeSchema>;++/**+ * Params for `composio.experimental.customToolkits.upsert()`.+ * **Experimental — custom toolkits are in pilot; shape may change.**+ */+export const CustomToolkitUpsertParamsSchema = z.object({+ /**+ * Letters, digits, underscores or spaces, up to 30 characters. The API+ * prefixes it with `CUSTOM_` and turns spaces into underscores.+ */+ slug: z+ .string()+ .min(1)+ .max(30)+ .regex(/^[a-zA-Z0-9_\s]+$/),+ toolkitConfig: z.object({+ /** Human-readable toolkit name. */+ name: z.string().min(1).max(200),+ /** The app URL. For an MCP app, the MCP server URL. */+ appUrl: z.string().url(),+ /** Square PNG or JPEG logo (256-1024px, max 3MB), base64-encoded. Defaults to the Composio logo. */+ logoFile: z+ .object({+ content: z.string().min(1),+ mimeType: z.enum(['image/png', 'image/jpeg']),+ })+ .optional(),+ /** At least one scheme. The schemes cannot change once the toolkit exists. */+ authSchemes: z.array(CustomToolkitAuthSchemeSchema).min(1),+ }),+});+export type CustomToolkitUpsertParams = z.infer<typeof CustomToolkitUpsertParamsSchema>;++export const CustomToolkitUpsertResponseSchema = z.object({+ /** Slug of the created or updated toolkit. */+ slug: z.string(),+});+export type CustomToolkitUpsertResponse = z.infer<typeof CustomToolkitUpsertResponseSchema>;++/**+ * Params for `composio.experimental.customToolkits.sync()`.+ * **Experimental — custom toolkits are in pilot; shape may change.**+ */+export const CustomToolkitSyncParamsSchema = z.object({+ /** Connected account to use when fetching the remote tool definitions. */+ connectedAccountId: z.string().optional(),+});+export type CustomToolkitSyncParams = z.infer<typeof CustomToolkitSyncParamsSchema>;++export const CustomToolkitSyncResponseSchema = z.object({+ slug: z.string(),+ /** Toolkit version after the sync. */+ version: z.string(),+ /** Number of tools synced. */+ syncedCount: z.number(),+});+export type CustomToolkitSyncResponse = z.infer<typeof CustomToolkitSyncResponseSchema>;++export const CustomToolkitDeleteResponseSchema = z.object({+ /** Slug of the deleted toolkit. */+ slug: z.string(),+ deleted: z.boolean(),+ /** Background jobs revoking the credentials of the toolkit's connected accounts. */+ revokeJobIds: z.array(z.string()),+ authConfigsDeleted: z.number(),+ connectedAccountsDeleted: z.number(),+});+export type CustomToolkitDeleteResponse = z.infer<typeof CustomToolkitDeleteResponseSchema>;diff --git a/ts/packages/core/src/types/keyring.types.ts b/ts/packages/core/src/types/keyring.types.tsnew file mode 100644index 000000000..b63760e34--- /dev/null+++ b/ts/packages/core/src/types/keyring.types.ts@@ -0,0 +1,32 @@+import { z } from 'zod/v3';++/**+ * A public JWK a secret can be sealed to. Fields keep their JWK names so a+ * key can be handed straight to WebCrypto or a JOSE library.+ */+export const KeyringTransferKeySchema = z.object({+ /** Key type. Always `RSA`. */+ kty: z.string(),+ /** RSA modulus, base64url-encoded. */+ n: z.string(),+ /** RSA public exponent, base64url-encoded. */+ e: z.string(),+ /** Key-management algorithm for the JWE (`RSA-OAEP-256`). Pair it with `A256GCM` content encryption. */+ alg: z.string(),+ /** Key use. Always `enc`. */+ use: z.string(),+ /** Key identifier. Put it in the JWE protected header. */+ kid: z.string(),+});+export type KeyringTransferKey = z.infer<typeof KeyringTransferKeySchema>;++/**+ * Response of `composio.keyring.listTransferKeys()`.+ */+export const KeyringTransferKeysResponseSchema = z.object({+ /** The `kid` of the key to seal new secrets to. */+ activeKid: z.string(),+ /** Every currently accepted transfer key, newest first. */+ keys: z.array(KeyringTransferKeySchema),+});+export type KeyringTransferKeysResponse = z.infer<typeof KeyringTransferKeysResponseSchema>;diff --git a/ts/packages/core/src/types/logs.types.ts b/ts/packages/core/src/types/logs.types.tsnew file mode 100644index 000000000..c07b9df15--- /dev/null+++ b/ts/packages/core/src/types/logs.types.ts@@ -0,0 +1,108 @@+import { z } from 'zod/v3';++/**+ * Fields a tool-execution log search can filter on.+ */+export const LogSearchFilterFieldSchema = z.enum([+ 'tool_slug',+ 'toolkit_slug',+ 'connected_account_id',+ 'auth_config_id',+ 'status',+ 'user_id',+ 'session_id',+ 'sandbox_id',+ 'request_id',+ 'log_id',+]);+export type LogSearchFilterField = z.infer<typeof LogSearchFilterFieldSchema>;++export const LogSearchFilterOperatorSchema = z.enum(['==', '!=', 'contains', 'not_contains']);+export type LogSearchFilterOperator = z.infer<typeof LogSearchFilterOperatorSchema>;++export const LogSearchFilterSchema = z.object({+ field: LogSearchFilterFieldSchema,+ operator: LogSearchFilterOperatorSchema,+ value: z.string(),+});+export type LogSearchFilter = z.infer<typeof LogSearchFilterSchema>;++export const LogSearchTimeRangeSchema = z.object({+ /** Start time in epoch milliseconds (inclusive). */+ from: z.number(),+ /** End time in epoch milliseconds. */+ to: z.number(),+});+export type LogSearchTimeRange = z.infer<typeof LogSearchTimeRangeSchema>;++/**+ * Params for `composio.logs.search()`.+ */+export const LogSearchParamsSchema = z.object({+ limit: z.number().optional(),+ cursor: z.string().nullable().optional(),+ filters: z.array(LogSearchFilterSchema).optional(),+ timeRange: LogSearchTimeRangeSchema.optional(),+});+export type LogSearchParams = z.infer<typeof LogSearchParamsSchema>;++export const ToolExecutionLogStatusSchema = z.enum(['success', 'failed']);+export const ToolExecutionLogLevelSchema = z.enum(['info', 'error', 'warn']);++export const ToolExecutionLogParentSchema = z+ .object({+ logId: z.string(),+ toolSlug: z.string(),+ })+ .nullable();++/**+ * A tool-execution log entry as returned by `composio.logs.search()`.+ */+export const ToolExecutionLogSchema = z.object({+ id: z.string(),+ /** ISO 8601 timestamp. */+ timestamp: z.string(),+ /** Log event type, e.g. `tool.execution`. */+ type: z.string(),+ status: ToolExecutionLogStatusSchema,+ level: ToolExecutionLogLevelSchema,+ message: z.string().optional(),+ metadata: z.record(z.string(), z.unknown()),+ metrics: z.record(z.string(), z.unknown()),+ parent: ToolExecutionLogParentSchema,+});+export type ToolExecutionLog = z.infer<typeof ToolExecutionLogSchema>;++export const LogSearchResponseSchema = z.object({+ logs: z.array(ToolExecutionLogSchema),+ nextCursor: z.string().nullable(),+});+export type LogSearchResponse = z.infer<typeof LogSearchResponseSchema>;++/**+ * A single tool-execution log with its full detail, as returned by+ * `composio.logs.get()`.+ */+export const ToolExecutionLogDetailSchema = ToolExecutionLogSchema.extend({+ timings: z+ .object({+ /** Epoch milliseconds. */+ startTime: z.number(),+ /** Epoch milliseconds. */+ endTime: z.number(),+ })+ .optional(),+ context: z.object({+ sessionId: z.string().optional(),+ traceId: z.string().optional(),+ requestId: z.string().optional(),+ }),+ source: z.object({+ host: z.string().optional(),+ framework: z.string().optional(),+ language: z.string().optional(),+ }),+ data: z.record(z.string(), z.unknown()),+});+export type ToolExecutionLogDetail = z.infer<typeof ToolExecutionLogDetailSchema>;diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.tsindex 6f6bbf8cc..4eb053244 100644--- a/ts/packages/core/src/types/toolRouter.types.ts+++ b/ts/packages/core/src/types/toolRouter.types.ts@@ -4,7 +4,10 @@ import { SessionMetaToolOptions } from './modifiers.types';import { ConnectionRequest } from './connectionRequest.types';import type { ComposioRequestOptions } from './requestOptions.types';import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';-import type { SessionCreateResponse } from '@composio/client/resources/tool-router/session/session.mjs';+import type {+ SessionConfigHistoryResponse,+ SessionCreateResponse,+} from '@composio/client/resources/tool-router/session/session.mjs';import type {CustomTool,CustomToolkit,@@ -707,6 +710,49 @@ export const ToolRouterSessionDeleteResponseSchema = z.object({});export type ToolRouterSessionDeleteResponse = z.infer<typeof ToolRouterSessionDeleteResponseSchema>;+/**+ * Options for `session.configHistory()`.+ */+export const ToolRouterSessionConfigHistoryOptionsSchema = z.object({+ /** Cursor from a previous response's `nextCursor`. */+ cursor: z.string().optional(),+ /** Number of items per page, max allowed is 100. */+ limit: z.number().optional(),+});+export type ToolRouterSessionConfigHistoryOptions = z.infer<+ typeof ToolRouterSessionConfigHistoryOptionsSchema+>;++/**+ * The session configuration at one version, as stored by the API. This is+ * the wire shape (snake_case), typed from the generated client.+ */+export type ToolRouterSessionConfigHistoryConfig = SessionConfigHistoryResponse.Item.Config;++export type ToolRouterSessionConfigHistoryItem = {+ /** The config version this entry represents. */+ version: number;+ /** ISO timestamp — for archived rows, when the version was superseded by an update. */+ createdAt: string;+ /** True only for the live (current) config, present on the first page. */+ isCurrent: boolean;+ /** The session configuration at this version. */+ config: ToolRouterSessionConfigHistoryConfig;+};++export type ToolRouterSessionConfigHistoryResponse = {+ items: ToolRouterSessionConfigHistoryItem[];+ nextCursor: string | null;+ totalPages: number;+ currentPage: number;+ totalItems: number;+};++export type ToolRouterSessionConfigHistoryFn = (+ options?: ToolRouterSessionConfigHistoryOptions,+ requestOptions?: ComposioRequestOptions+) => Promise<ToolRouterSessionConfigHistoryResponse>;+export type ToolRouterSessionDeleteFn = (requestOptions?: ComposioRequestOptions) => Promise<ToolRouterSessionDeleteResponse>;@@ -748,6 +794,8 @@ export interface Session<update: ToolRouterSessionUpdateFn;/** Delete the session. Deleted sessions are no longer retrievable or executable. */delete: ToolRouterSessionDeleteFn;+ /** Page through the session's configuration history (newest first). */+ configHistory: ToolRouterSessionConfigHistoryFn;/** Proxy an API call through Composio's auth layer using the session's connected account */proxyExecute: ToolRouterSessionProxyExecuteFn;/** List custom tools registered in this session, with their final slugs and schemas */diff --git a/ts/packages/core/src/types/toolkit.types.ts b/ts/packages/core/src/types/toolkit.types.tsindex ef5fb4ac9..d1418fcef 100644--- a/ts/packages/core/src/types/toolkit.types.ts+++ b/ts/packages/core/src/types/toolkit.types.ts@@ -18,6 +18,14 @@ export type ToolkitMangedByEnum = z.infer<typeof ToolkitMangedByEnumSchema>;export type ToolkitSortByEnum = z.infer<typeof ToolkitSortByEnumSchema>;export type ToolkitListParams = z.infer<typeof ToolkitsListParamsSchema>;+/**+ * Toolkit getMany params — the slugs to fetch plus the same filters `list`+ * accepts.+ */+export const ToolkitGetManySlugsSchema = z.array(z.string().min(1)).min(1);+export const ToolkitsGetManyParamsSchema = ToolkitsListParamsSchema;+export type ToolkitGetManyParams = z.infer<typeof ToolkitsGetManyParamsSchema>;+/*** Toolkits response*/@@ -121,6 +129,129 @@ export type ToolkitRetrieveCategoriesResponse = z.infer<typeof ToolkitRetrieveCategoriesResponseSchema>;+/**+ * Toolkit changelog response+ */+export const ToolkitVersionChangelogSchema = z.object({+ version: z.string(),+ changelog: z.string(),+});+export const ToolkitChangelogItemSchema = z.object({+ slug: z.string(),+ name: z.string(),+ displayName: z.string(),+ /** Most recent versions first; the API returns up to the last 10 per toolkit. */+ versions: z.array(ToolkitVersionChangelogSchema),+});+export const ToolkitChangelogResponseSchema = z.object({+ items: z.array(ToolkitChangelogItemSchema),+});++export type ToolkitVersionChangelog = z.infer<typeof ToolkitVersionChangelogSchema>;+export type ToolkitChangelogItem = z.infer<typeof ToolkitChangelogItemSchema>;+export type ToolkitChangelogResponse = z.infer<typeof ToolkitChangelogResponseSchema>;++/**+ * Params for `composio.toolkits.recommendScopes()`.+ * **Experimental — shape may change in future releases.**+ */+export const ToolkitRecommendScopesParamsSchema = z.object({+ /** Tool slugs to cover. Pass `[]` to cover every tool in the toolkit. */+ tools: z.array(z.string()),+ /** Auth scheme the connection will use. The API defaults to `OAUTH2`. */+ authScheme: AuthSchemeEnum.optional(),+ /** Toolkit version to compute from. The API defaults to the latest published version. */+ toolkitVersion: z.string().min(1).optional(),+ /**+ * Context the scopes will be granted in, as dimension → selected value,+ * for example `{ account_type: 'Google Workspace' }`. Discover the+ * dimensions with `composio.toolkits.listGrantContexts()`.+ */+ grantContext: z.record(z.string(), z.string()).optional(),+ /** Scopes the recommendation must include, whether or not the tools need them. */+ include: z.array(z.string()).optional(),+ /** Scopes the recommendation must not include; the API picks documented alternatives or fails. */+ exclude: z.array(z.string()).optional(),+ /** Scopes your OAuth app can request. The recommendation never goes outside this list. */+ availableScopes: z.array(z.string()).optional(),+});+export type ToolkitRecommendScopesParams = z.infer<typeof ToolkitRecommendScopesParamsSchema>;++export const ToolkitConditionalScopeSchema = z.object({+ /** The scope needed only when the `when` guard matches. */+ scope: z.string(),+ /** Input field name → qualifying values. Any value matches within a field; all fields must match. */+ when: z.record(z.string(), z.array(z.string())),+ /** Tool slugs that need this scope under the guard. */+ for: z.array(z.string()),+});+export type ToolkitConditionalScope = z.infer<typeof ToolkitConditionalScopeSchema>;++/**+ * Response of `composio.toolkits.recommendScopes()`.+ * **Experimental — shape may change in future releases.**+ */+export const ToolkitRecommendScopesResponseSchema = z.object({+ /** Auth scheme the recommendation was computed under. */+ authScheme: z.string(),+ /** Concrete toolkit version the answer was computed from; pass it back as `toolkitVersion` to pin. */+ toolkitVersion: z.string(),+ /** The effective grant context: the toolkit default overlaid with your overrides. */+ grantContext: z.record(z.string(), z.string()),+ scopes: z.object({+ /** Narrowest documented option per requirement. */+ leastPrivilege: z.array(z.string()),+ /** Smallest scope set covering all requirements. */+ fewest: z.array(z.string()),+ /**+ * Scopes needed only for particular call-time inputs. Both lists above+ * already include them, so a caller that knows its inputs may drop the rest.+ */+ conditional: z.array(ToolkitConditionalScopeSchema),+ }),+});+export type ToolkitRecommendScopesResponse = z.infer<typeof ToolkitRecommendScopesResponseSchema>;++/**+ * Params for `composio.toolkits.listGrantContexts()`.+ * **Experimental — shape may change in future releases.**+ */+export const ToolkitListGrantContextsParamsSchema = z.object({+ /** Auth scheme the connection will use. The API defaults to `OAUTH2`. */+ authScheme: AuthSchemeEnum.optional(),+ /** Toolkit version to read the scope catalog from. The API defaults to the latest published version. */+ toolkitVersion: z.string().min(1).optional(),+});+export type ToolkitListGrantContextsParams = z.infer<typeof ToolkitListGrantContextsParamsSchema>;++export const ToolkitGrantContextDimensionSchema = z.object({+ /** Dimension name to use as a `grantContext` key. */+ dimension: z.string(),+ /** What the dimension means and when to pass it. */+ description: z.string(),+ /** Values the dimension can take. */+ values: z.array(z.string()),+});+export type ToolkitGrantContextDimension = z.infer<typeof ToolkitGrantContextDimensionSchema>;++/**+ * Response of `composio.toolkits.listGrantContexts()`.+ * **Experimental — shape may change in future releases.**+ */+export const ToolkitListGrantContextsResponseSchema = z.object({+ /** Auth scheme whose scope catalog the dimensions were read from. */+ authScheme: z.string(),+ /** Concrete toolkit version the answer was computed from. */+ toolkitVersion: z.string(),+ /** Dimensions the toolkit accepts in `grantContext`; empty when no scope depends on one. */+ grantContextDimensions: z.array(ToolkitGrantContextDimensionSchema),+ /** The grant context assumed when you pass none. */+ defaultGrantContext: z.record(z.string(), z.string()),+});+export type ToolkitListGrantContextsResponse = z.infer<+ typeof ToolkitListGrantContextsResponseSchema+>;+export const ToolkitAuthFieldsResponseSchema = z.array(ToolkitAuthFieldSchema.extend({required: z.boolean().optional(),diff --git a/ts/packages/core/src/types/usage.types.ts b/ts/packages/core/src/types/usage.types.tsnew file mode 100644index 000000000..3c7693ce7--- /dev/null+++ b/ts/packages/core/src/types/usage.types.ts@@ -0,0 +1,81 @@+import { z } from 'zod/v3';++/**+ * Filters shared by the usage summary and breakdown queries.+ * **Experimental — shape may change in future releases.**+ */+export const UsageFiltersSchema = z.object({+ /** Only count events for these external end-user IDs (OR logic). */+ userId: z.array(z.string()).nullable().optional(),+ /** Only count events for these session IDs (OR logic). */+ sessionId: z.array(z.string()).nullable().optional(),+});+export type UsageFilters = z.infer<typeof UsageFiltersSchema>;++/**+ * Params for `composio.experimental.usage.summary()`.+ * **Experimental — shape may change in future releases.**+ */+export const UsageSummaryParamsSchema = z.object({+ /** Inclusive range start (Unix epoch milliseconds). Defaults to 30 days before `to`. */+ from: z.number().optional(),+ /** Exclusive range end (Unix epoch milliseconds). Defaults to now. */+ to: z.number().optional(),+ /** Restrict to these metering entity types. Omit for all types. */+ entityTypes: z.array(z.string()).optional(),+ filters: UsageFiltersSchema.optional(),+});+export type UsageSummaryParams = z.infer<typeof UsageSummaryParamsSchema>;++export const UsageOrderBySchema = z.enum(['key', 'total_quantity', 'event_count']);+export const UsageOrderDirectionSchema = z.enum(['asc', 'desc']);++/**+ * Params for `composio.experimental.usage.breakdown()`.+ * **Experimental — shape may change in future releases.**+ */+export const UsageBreakdownParamsSchema = z.object({+ /** Inclusive range start (Unix epoch milliseconds). Defaults to 30 days before `to`. */+ from: z.number().optional(),+ /** Exclusive range end (Unix epoch milliseconds). Defaults to now. */+ to: z.number().optional(),+ /** Dimension to group by. Defaults to `tool_slug` for tool_calls and `user_id` for sessions. */+ groupBy: z.string().optional(),+ /** Field to order groups by. Defaults to `total_quantity`. */+ orderBy: UsageOrderBySchema.optional(),+ /** Sort direction. Defaults to `desc`. */+ orderDirection: UsageOrderDirectionSchema.optional(),+ /** Maximum number of groups to return. Defaults to 100, max 1000. */+ limit: z.number().optional(),+ filters: UsageFiltersSchema.optional(),+});+export type UsageBreakdownParams = z.infer<typeof UsageBreakdownParamsSchema>;++export const UsageEntitySummarySchema = z.object({+ unit: z.string(),+ totalQuantity: z.string(),+ eventCount: z.number(),+});+export type UsageEntitySummary = z.infer<typeof UsageEntitySummarySchema>;++export const UsageSummaryResponseSchema = z.object({+ /** Aggregates keyed by metering entity type (e.g. `tool_calls`, `sessions`). */+ entities: z.record(z.string(), UsageEntitySummarySchema),+});+export type UsageSummaryResponse = z.infer<typeof UsageSummaryResponseSchema>;++export const UsageBreakdownGroupSchema = z.object({+ key: z.string(),+ totalQuantity: z.string(),+ eventCount: z.number(),+});+export type UsageBreakdownGroup = z.infer<typeof UsageBreakdownGroupSchema>;++export const UsageBreakdownResponseSchema = z.object({+ entityType: z.string(),+ unit: z.string(),+ totalQuantity: z.string(),+ eventCount: z.number(),+ groups: z.array(UsageBreakdownGroupSchema),+});+export type UsageBreakdownResponse = z.infer<typeof UsageBreakdownResponseSchema>;diff --git a/ts/packages/core/src/types/webhooks.types.ts b/ts/packages/core/src/types/webhooks.types.tsnew file mode 100644index 000000000..51b6b81f8--- /dev/null+++ b/ts/packages/core/src/types/webhooks.types.ts@@ -0,0 +1,143 @@+import { z } from 'zod/v3';+import { SetWebhookSubscriptionParamsSchema } from './triggers.types';++/**+ * Webhook payload versions accepted by the webhook subscription endpoints.+ */+export const WebhookVersionSchema = z.enum(['V1', 'V2', 'V3']);++// ---------------------------------------------------------------------------+// Webhook subscriptions+// ---------------------------------------------------------------------------++/**+ * A project webhook subscription in the SDK's camelCase shape. The signing+ * `secret` is returned by the API on every subscription read/write.+ */+export const WebhookSubscriptionSchema = z.object({+ id: z.string(),+ webhookUrl: z.string(),+ version: WebhookVersionSchema,+ enabledEvents: z.array(z.string()),+ secret: z.string().optional(),+ createdAt: z.string().optional(),+ updatedAt: z.string().optional(),+});++export const WebhookSubscriptionListParamsSchema = z.object({+ /** Number of items per page, max allowed is 50. */+ limit: z.number().optional(),+ /** Cursor for pagination, taken from a previous response's `nextCursor`. */+ cursor: z.string().optional(),+});+export type WebhookSubscriptionListParams = z.infer<typeof WebhookSubscriptionListParamsSchema>;++export const WebhookSubscriptionListResponseSchema = z.object({+ items: z.array(WebhookSubscriptionSchema),+ nextCursor: z.string().nullable(),+ totalPages: z.number(),+ currentPage: z.number(),+ totalItems: z.number(),+});+export type WebhookSubscriptionListResponse = z.infer<typeof WebhookSubscriptionListResponseSchema>;++/**+ * Params for `composio.webhooks.subscriptions.set()`. Identical to the+ * params accepted by `composio.triggers.setWebhookSubscription()`.+ */+export const WebhookSubscriptionSetParamsSchema = SetWebhookSubscriptionParamsSchema;+export type WebhookSubscriptionSetParams = z.infer<typeof WebhookSubscriptionSetParamsSchema>;++export const WebhookSubscriptionUpdateParamsSchema = z.object({+ /** HTTPS URL to receive webhook events. */+ webhookUrl: z.string().min(1).optional(),+ /** Event types to subscribe to. */+ enabledEvents: z.array(z.string()).min(1).optional(),+ /** Webhook payload version. */+ version: WebhookVersionSchema.optional(),+});+export type WebhookSubscriptionUpdateParams = z.infer<typeof WebhookSubscriptionUpdateParamsSchema>;++export const WebhookSubscriptionDeleteResponseSchema = z.object({+ success: z.boolean(),+});+export type WebhookSubscriptionDeleteResponse = z.infer<+ typeof WebhookSubscriptionDeleteResponseSchema+>;++export const WebhookSubscriptionRotateSecretResponseSchema = z.object({+ id: z.string(),+ /** The new signing secret. Store it — the previous secret stops validating. */+ secret: z.string(),+});+export type WebhookSubscriptionRotateSecretResponse = z.infer<+ typeof WebhookSubscriptionRotateSecretResponseSchema+>;++export const WebhookSubscriptionEventTypeSchema = z.object({+ eventType: z.string(),+ description: z.string(),+ supportedVersions: z.array(WebhookVersionSchema),+});+export type WebhookSubscriptionEventType = z.infer<typeof WebhookSubscriptionEventTypeSchema>;++export const WebhookSubscriptionEventTypesResponseSchema = z.object({+ items: z.array(WebhookSubscriptionEventTypeSchema),+});+export type WebhookSubscriptionEventTypesResponse = z.infer<+ typeof WebhookSubscriptionEventTypesResponseSchema+>;++// ---------------------------------------------------------------------------+// Webhook endpoints (per toolkit + OAuth app inbound ingress URLs)+// ---------------------------------------------------------------------------++export const WebhookEndpointListParamsSchema = z.object({+ /** Only return endpoints for this toolkit slug. */+ toolkitSlug: z.string().optional(),+});+export type WebhookEndpointListParams = z.infer<typeof WebhookEndpointListParamsSchema>;++export const WebhookEndpointListItemSchema = z.object({+ id: z.string(),+ toolkitSlug: z.string(),+ clientId: z.string().nullable(),+});+export type WebhookEndpointListItem = z.infer<typeof WebhookEndpointListItemSchema>;++export const WebhookEndpointListResponseSchema = z.object({+ items: z.array(WebhookEndpointListItemSchema),+});+export type WebhookEndpointListResponse = z.infer<typeof WebhookEndpointListResponseSchema>;++export const WebhookEndpointSchema = z.object({+ id: z.string(),+ toolkitSlug: z.string(),+ clientId: z.string().nullable(),+ /** The inbound URL to register with the third-party provider. */+ webhookUrl: z.string(),+ /** Configured setup fields with secret values masked. */+ data: z.record(z.string(), z.string()).nullable(),+ createdAt: z.string(),+});+export type WebhookEndpoint = z.infer<typeof WebhookEndpointSchema>;++export const WebhookEndpointCreateParamsSchema = z.object({+ /** Toolkit identifier (e.g. `slack`, `discord`). */+ toolkitSlug: z.string().min(1),+ /** OAuth app client ID — identifies which app this endpoint is for. */+ clientId: z.string().min(1),+});+export type WebhookEndpointCreateParams = z.infer<typeof WebhookEndpointCreateParamsSchema>;++export const WebhookEndpointReplaceParamsSchema = z.object({+ /** Key-value pairs for ALL required setup fields of the toolkit. */+ data: z.record(z.string(), z.string()),+});+export type WebhookEndpointReplaceParams = z.infer<typeof WebhookEndpointReplaceParamsSchema>;++export const WebhookEndpointUpdateParamsSchema = z.object({+ /** Key-value pairs to merge into the setup fields. Omitted fields are preserved. */+ data: z.record(z.string(), z.string()),+});+export type WebhookEndpointUpdateParams = z.infer<typeof WebhookEndpointUpdateParamsSchema>;diff --git a/ts/packages/core/src/utils/constants.ts b/ts/packages/core/src/utils/constants.tsindex 87c030e1d..4c6d34789 100644--- a/ts/packages/core/src/utils/constants.ts+++ b/ts/packages/core/src/utils/constants.ts@@ -11,11 +11,7 @@ export const TELEMETRY_URL = 'https://app.composio.dev';export const CLIENT_PUSHER_KEY = getEnvVariable('CLIENT_PUSHER_KEY') || 'ff9f18c208855d77a152';export const COMPOSIO_LOG_LEVEL = getEnvVariable('COMPOSIO_LOG_LEVEL') as- | 'debug'- | 'info'- | 'warn'- | 'error'- | undefined;+ 'silent' | 'debug' | 'info' | 'warn' | 'error' | undefined;export const IS_DEVELOPMENT_OR_CI = getEnvVariable('DEVELOPMENT') || getEnvVariable('CI') || false;diff --git a/ts/packages/core/src/utils/logger.ts b/ts/packages/core/src/utils/logger.tsindex ac8b4207b..d8aded84a 100644--- a/ts/packages/core/src/utils/logger.ts+++ b/ts/packages/core/src/utils/logger.ts@@ -23,20 +23,52 @@ export const getLogLevel = (): LogLevel => {return envLevel && envLevel in LOG_LEVELS ? (envLevel as LogLevel) : 'info';};+/**+ * Destination for SDK log output. Each method receives the already+ * formatted and redacted message as its single argument. `console` satisfies+ * this interface, and so do most structured loggers (pino, winston, ...).+ */+export interface ComposioLogger {+ error: (...args: unknown[]) => void;+ warn: (...args: unknown[]) => void;+ info: (...args: unknown[]) => void;+ debug: (...args: unknown[]) => void;+}+interface LoggerOptions {level?: LogLevel;includeTimestamp?: boolean;+ /** Where formatted output is written. Defaults to `console`. */+ sink?: ComposioLogger;+}++export interface LoggerConfigureOptions {+ level?: LogLevel;+ sink?: ComposioLogger;}export class Logger {- private readonly level: LogLevel;+ private level: LogLevel;private readonly includeTimestamp: boolean;- private readonly console: Console;+ private sink: ComposioLogger;constructor(options: LoggerOptions = {}) {this.level = options.level ?? getLogLevel();this.includeTimestamp = options.includeTimestamp ?? true;- this.console = console;+ this.sink = options.sink ?? console;+ }++ /**+ * Reconfigure the level and/or sink in place. Omitted fields are left+ * unchanged, so `configure({ level: 'debug' })` keeps the current sink.+ */+ configure(options: LoggerConfigureOptions): void {+ if (options.level !== undefined) this.level = options.level;+ if (options.sink !== undefined) this.sink = options.sink;+ }++ getLevel(): LogLevel {+ return this.level;}private formatMessage(args: unknown[]): string {@@ -71,25 +103,25 @@ export class Logger {error(...args: unknown[]): void {if (this.shouldLog('error')) {- this.console.error(this.formatMessage(args));+ this.sink.error(this.formatMessage(args));}}warn(...args: unknown[]): void {if (this.shouldLog('warn')) {- this.console.warn(this.formatMessage(args));+ this.sink.warn(this.formatMessage(args));}}info(...args: unknown[]): void {if (this.shouldLog('info')) {- this.console.info(this.formatMessage(args));+ this.sink.info(this.formatMessage(args));}}debug(...args: unknown[]): void {if (this.shouldLog('debug')) {- this.console.debug(this.formatMessage(args));+ this.sink.debug(this.formatMessage(args));}}}diff --git a/ts/packages/core/src/utils/transformers/connectedAccounts.ts b/ts/packages/core/src/utils/transformers/connectedAccounts.tsindex 852a78cc9..29d79b1c5 100644--- a/ts/packages/core/src/utils/transformers/connectedAccounts.ts+++ b/ts/packages/core/src/utils/transformers/connectedAccounts.ts@@ -1,20 +1,30 @@import {ConnectedAccountListResponse as RawConnectedAccountListResponse,ConnectedAccountRetrieveResponse as RawConnectedAccountRetrieveResponse,+ type ConnectedAccounts as ClientConnectedAccounts,} from '@composio/client/resources/connected-accounts';import {ConnectedAccountListResponse,ConnectedAccountListResponseSchema,ConnectedAccountRetrieveResponse,ConnectedAccountRetrieveResponseSchema,+ ConnectedAccountRevokeResponse,+ ConnectedAccountRevokeResponseSchema,+ ConnectedAccountCompleteAuthResponse,+ ConnectedAccountCompleteAuthResponseSchema,} from '../../types/connectedAccounts.types';++// The revoke and complete-auth response types are only reachable through the+// resource class namespace on the published subpath.+type RawConnectedAccountRevokeResponse = ClientConnectedAccounts.ConnectedAccountRevokeResponse;+type RawConnectedAccountCompleteAuthResponse =+ ClientConnectedAccounts.ConnectedAccountCompleteAuthResponse;import { ConnectionDataSchema } from '../../types/connectedAccountAuthStates.types';import logger from '../logger';import { transform } from '../transform';type RawConnectedAccountResponseWithLabels = (- | RawConnectedAccountRetrieveResponse- | RawConnectedAccountListResponse['items'][0]+ RawConnectedAccountRetrieveResponse | RawConnectedAccountListResponse['items'][0]) & {word_id?: string | null;alias?: string | null;@@ -117,3 +127,28 @@ export function transformConnectedAccountListResponse(totalPages: response.total_pages,}));}++export const transformConnectedAccountRevokeResponse = (+ response: RawConnectedAccountRevokeResponse+): ConnectedAccountRevokeResponse => {+ return transform(response)+ .with(ConnectedAccountRevokeResponseSchema)+ .using(response => ({+ revokedTokens: response.revoked_tokens,+ connectedAccount: {+ id: response.connected_account.id,+ status: response.connected_account.status,+ },+ }));+};++export const transformConnectedAccountCompleteAuthResponse = (+ response: RawConnectedAccountCompleteAuthResponse+): ConnectedAccountCompleteAuthResponse => {+ return transform(response)+ .with(ConnectedAccountCompleteAuthResponseSchema)+ .using(response => ({+ connectedAccountId: response.connected_account_id,+ toolkitSlug: response.toolkit_slug,+ }));+};diff --git a/ts/packages/core/src/utils/transformers/customToolkits.ts b/ts/packages/core/src/utils/transformers/customToolkits.tsnew file mode 100644index 000000000..0a415dec3--- /dev/null+++ b/ts/packages/core/src/utils/transformers/customToolkits.ts@@ -0,0 +1,98 @@+import type {+ CustomDeleteToolkitResponse as RawCustomDeleteToolkitResponse,+ CustomSyncParams as RawCustomSyncParams,+ CustomSyncResponse as RawCustomSyncResponse,+ CustomUpsertParams as RawCustomUpsertParams,+ CustomUpsertResponse as RawCustomUpsertResponse,+} from '@composio/client/resources/custom';+import {+ CustomToolkitAuthScheme,+ CustomToolkitDeleteResponse,+ CustomToolkitDeleteResponseSchema,+ CustomToolkitSyncParams,+ CustomToolkitSyncResponse,+ CustomToolkitSyncResponseSchema,+ CustomToolkitUpsertParams,+ CustomToolkitUpsertResponse,+ CustomToolkitUpsertResponseSchema,+} from '../../types/customToolkits.types';+import { transform } from '../transform';++type RawCustomToolkitAuthScheme = RawCustomUpsertParams['toolkit_config']['auth_schemes'][number];++const transformCustomToolkitAuthScheme = (+ scheme: CustomToolkitAuthScheme+): RawCustomToolkitAuthScheme => {+ switch (scheme.mode) {+ case 'NO_AUTH':+ return { mode: 'NO_AUTH' };+ case 'API_KEY':+ return {+ mode: 'API_KEY',+ headers: scheme.headers,+ api_key_field: scheme.apiKeyField && {+ display_name: scheme.apiKeyField.displayName,+ description: scheme.apiKeyField.description,+ },+ };+ case 'DCR_OAUTH':+ return { mode: 'DCR_OAUTH', discovery_url: scheme.discoveryUrl };+ }+};++export const transformCustomToolkitUpsertParams = (+ params: CustomToolkitUpsertParams+): RawCustomUpsertParams => ({+ slug: params.slug,+ toolkit_config: {+ name: params.toolkitConfig.name,+ app_url: params.toolkitConfig.appUrl,+ logo_file: params.toolkitConfig.logoFile && {+ content: params.toolkitConfig.logoFile.content,+ mime_type: params.toolkitConfig.logoFile.mimeType,+ },+ auth_schemes: params.toolkitConfig.authSchemes.map(transformCustomToolkitAuthScheme),+ },+});++export const transformCustomToolkitUpsertResponse = (+ response: RawCustomUpsertResponse+): CustomToolkitUpsertResponse => {+ return transform(response)+ .with(CustomToolkitUpsertResponseSchema)+ .using(response => ({ slug: response.slug }));+};++export const transformCustomToolkitSyncParams = (+ slug: string,+ params: CustomToolkitSyncParams+): RawCustomSyncParams => ({+ slug,+ connected_account_id: params.connectedAccountId,+});++export const transformCustomToolkitSyncResponse = (+ response: RawCustomSyncResponse+): CustomToolkitSyncResponse => {+ return transform(response)+ .with(CustomToolkitSyncResponseSchema)+ .using(response => ({+ slug: response.slug,+ version: response.version,+ syncedCount: response.synced_count,+ }));+};++export const transformCustomToolkitDeleteResponse = (+ response: RawCustomDeleteToolkitResponse+): CustomToolkitDeleteResponse => {+ return transform(response)+ .with(CustomToolkitDeleteResponseSchema)+ .using(response => ({+ slug: response.slug,+ deleted: response.deleted,+ revokeJobIds: response.revoke_job_ids,+ authConfigsDeleted: response.auth_configs_deleted,+ connectedAccountsDeleted: response.connected_accounts_deleted,+ }));+};diff --git a/ts/packages/core/src/utils/transformers/keyring.ts b/ts/packages/core/src/utils/transformers/keyring.tsnew file mode 100644index 000000000..18415ab70--- /dev/null+++ b/ts/packages/core/src/utils/transformers/keyring.ts@@ -0,0 +1,24 @@+import type { KeyringListTransferKeysResponse as RawKeyringListTransferKeysResponse } from '@composio/client/resources/keyring';+import {+ KeyringTransferKeysResponse,+ KeyringTransferKeysResponseSchema,+} from '../../types/keyring.types';+import { transform } from '../transform';++export const transformKeyringTransferKeysResponse = (+ response: RawKeyringListTransferKeysResponse+): KeyringTransferKeysResponse => {+ return transform(response)+ .with(KeyringTransferKeysResponseSchema)+ .using(response => ({+ activeKid: response.active_kid,+ keys: response.keys.map(key => ({+ kty: key.kty,+ n: key.n,+ e: key.e,+ alg: key.alg,+ use: key.use,+ kid: key.kid,+ })),+ }));+};diff --git a/ts/packages/core/src/utils/transformers/logs.ts b/ts/packages/core/src/utils/transformers/logs.tsnew file mode 100644index 000000000..d5cf07eaf--- /dev/null+++ b/ts/packages/core/src/utils/transformers/logs.ts@@ -0,0 +1,85 @@+import type {+ LogCreateToolExecutionParams as RawLogSearchParams,+ LogCreateToolExecutionResponse as RawLogSearchResponse,+ LogRetrieveToolExecutionResponse as RawToolExecutionLogDetail,+} from '@composio/client/resources/logs';+import {+ LogSearchParams,+ LogSearchResponse,+ LogSearchResponseSchema,+ ToolExecutionLog,+ ToolExecutionLogDetail,+ ToolExecutionLogDetailSchema,+ ToolExecutionLogSchema,+} from '../../types/logs.types';+import { transform } from '../transform';++export const transformLogSearchParams = (params: LogSearchParams): RawLogSearchParams => ({+ limit: params.limit,+ cursor: params.cursor,+ filters: params.filters,+ time_range: params.timeRange,+});++export const transformToolExecutionLog = (+ response: RawLogSearchResponse['logs'][number]+): ToolExecutionLog => {+ return transform(response)+ .with(ToolExecutionLogSchema)+ .using(response => ({+ id: response.id,+ timestamp: response.timestamp,+ type: response.type,+ status: response.status,+ level: response.level,+ message: response.message,+ metadata: response.metadata,+ metrics: response.metrics,+ parent: response.parent+ ? { logId: response.parent.log_id, toolSlug: response.parent.tool_slug }+ : null,+ }));+};++export const transformLogSearchResponse = (response: RawLogSearchResponse): LogSearchResponse => {+ return transform(response)+ .with(LogSearchResponseSchema)+ .using(response => ({+ logs: response.logs.map(transformToolExecutionLog),+ nextCursor: response.next_cursor,+ }));+};++export const transformToolExecutionLogDetail = (+ response: RawToolExecutionLogDetail+): ToolExecutionLogDetail => {+ return transform(response)+ .with(ToolExecutionLogDetailSchema)+ .using(response => ({+ id: response.id,+ timestamp: response.timestamp,+ type: response.type,+ status: response.status,+ level: response.level,+ message: response.message,+ metadata: response.metadata,+ metrics: response.metrics,+ parent: response.parent+ ? { logId: response.parent.log_id, toolSlug: response.parent.tool_slug }+ : null,+ timings: response.timings+ ? { startTime: response.timings.start_time, endTime: response.timings.end_time }+ : undefined,+ context: {+ sessionId: response.context.session_id,+ traceId: response.context.trace_id,+ requestId: response.context.request_id,+ },+ source: {+ host: response.source.host,+ framework: response.source.framework,+ language: response.source.language,+ },+ data: response.data,+ }));+};diff --git a/ts/packages/core/src/utils/transformers/toolkits.ts b/ts/packages/core/src/utils/transformers/toolkits.tsindex a26140b8f..560e51632 100644--- a/ts/packages/core/src/utils/transformers/toolkits.ts+++ b/ts/packages/core/src/utils/transformers/toolkits.ts@@ -2,7 +2,19 @@ import {ToolkitRetrieveResponse as RawToolkitRetrieveResponse,ToolkitListResponse as RawToolkitListResponse,ToolkitRetrieveCategoriesResponse as RawToolkitRetrieveCategoriesResponse,+ type Toolkits as ClientToolkits,} from '@composio/client/resources/toolkits';++// The `/toolkits/multi` and `/toolkits/changelog` response types are only+// reachable through the resource class namespace on the published subpath.+type RawToolkitRetrieveChangelogResponse = ClientToolkits.ToolkitRetrieveChangelogResponse;+type RawToolkitRetrieveMultiResponse = ClientToolkits.ToolkitRetrieveMultiResponse;+type RawToolkitRecommendScopesParams = ClientToolkits.ToolkitRecommendScopesParams;+type RawToolkitRecommendScopesResponse = ClientToolkits.ToolkitRecommendScopesResponse;+type RawToolkitRetrieveScopesGrantContextParams =+ ClientToolkits.ToolkitRetrieveScopesGrantContextParams;+type RawToolkitRetrieveScopesGrantContextResponse =+ ClientToolkits.ToolkitRetrieveScopesGrantContextResponse;import {ToolKitListResponse,ToolKitListResponseSchema,@@ -10,11 +22,23 @@ import {ToolkitRetrieveResponseSchema,ToolkitRetrieveCategoriesResponse,ToolkitRetrieveCategoriesResponseSchema,+ ToolkitChangelogResponse,+ ToolkitChangelogResponseSchema,+ ToolkitRecommendScopesParams,+ ToolkitRecommendScopesResponse,+ ToolkitRecommendScopesResponseSchema,+ ToolkitListGrantContextsParams,+ ToolkitListGrantContextsResponse,+ ToolkitListGrantContextsResponseSchema,} from '../../types/toolkit.types';import { transform } from '../transform';+/**+ * `GET /toolkits` and `POST /toolkits/multi` return the same item shape; the+ * generated client only names them differently per operation.+ */export const transformToolkitListResponse = (- response: RawToolkitListResponse+ response: RawToolkitListResponse | RawToolkitRetrieveMultiResponse): ToolKitListResponse => {return transform(response).with(ToolKitListResponseSchema)@@ -84,6 +108,24 @@ export const transformToolkitRetrieveResponse = (}));};+export const transformToolkitChangelogResponse = (+ response: RawToolkitRetrieveChangelogResponse+): ToolkitChangelogResponse => {+ return transform(response)+ .with(ToolkitChangelogResponseSchema)+ .using(response => ({+ items: response.items.map(item => ({+ slug: item.slug,+ name: item.name,+ displayName: item.display_name,+ versions: item.versions.map(version => ({+ version: version.version,+ changelog: version.changelog,+ })),+ })),+ }));+};+export const transformToolkitRetrieveCategoriesResponse = (response: RawToolkitRetrieveCategoriesResponse): ToolkitRetrieveCategoriesResponse => {@@ -98,3 +140,60 @@ export const transformToolkitRetrieveCategoriesResponse = (totalPages: response.total_pages,}));};++export const transformToolkitRecommendScopesParams = (+ params: ToolkitRecommendScopesParams+): RawToolkitRecommendScopesParams => ({+ tools: params.tools,+ auth_scheme: params.authScheme,+ toolkit_version: params.toolkitVersion,+ grant_context: params.grantContext,+ include: params.include,+ exclude: params.exclude,+ available_scopes: params.availableScopes,+});++export const transformToolkitRecommendScopesResponse = (+ response: RawToolkitRecommendScopesResponse+): ToolkitRecommendScopesResponse => {+ return transform(response)+ .with(ToolkitRecommendScopesResponseSchema)+ .using(response => ({+ authScheme: response.auth_scheme,+ toolkitVersion: response.toolkit_version,+ grantContext: response.grant_context,+ scopes: {+ leastPrivilege: response.scopes.least_privilege,+ fewest: response.scopes.fewest,+ conditional: response.scopes.conditional.map(condition => ({+ scope: condition.scope,+ when: condition.when,+ for: condition.for,+ })),+ },+ }));+};++export const transformToolkitListGrantContextsParams = (+ params: ToolkitListGrantContextsParams+): RawToolkitRetrieveScopesGrantContextParams => ({+ auth_scheme: params.authScheme,+ toolkit_version: params.toolkitVersion,+});++export const transformToolkitListGrantContextsResponse = (+ response: RawToolkitRetrieveScopesGrantContextResponse+): ToolkitListGrantContextsResponse => {+ return transform(response)+ .with(ToolkitListGrantContextsResponseSchema)+ .using(response => ({+ authScheme: response.auth_scheme,+ toolkitVersion: response.toolkit_version,+ grantContextDimensions: response.grant_context_dimensions.map(dimension => ({+ dimension: dimension.dimension,+ description: dimension.description,+ values: dimension.values,+ })),+ defaultGrantContext: response.default_grant_context,+ }));+};diff --git a/ts/packages/core/src/utils/transformers/triggers.ts b/ts/packages/core/src/utils/transformers/triggers.tsindex fc0e20119..daacc3db5 100644--- a/ts/packages/core/src/utils/transformers/triggers.ts+++ b/ts/packages/core/src/utils/transformers/triggers.ts@@ -96,8 +96,8 @@ export function transformTriggerInstanceListActiveItem(id: response.id,connectedAccountId: response.connected_account_id,disabledAt: response.disabled_at,- state: response.state,- triggerConfig: response.trigger_config,+ state: response.state ?? {},+ triggerConfig: response.trigger_config ?? {},triggerName: response.trigger_name,updatedAt: response.updated_at,triggerData: response.trigger_data,diff --git a/ts/packages/core/src/utils/transformers/usage.ts b/ts/packages/core/src/utils/transformers/usage.tsnew file mode 100644index 000000000..d710ddbd4--- /dev/null+++ b/ts/packages/core/src/utils/transformers/usage.ts@@ -0,0 +1,77 @@+import type {+ UsageRetrieveParams as RawUsageBreakdownParams,+ UsageRetrieveResponse as RawUsageBreakdownResponse,+ UsageRetrieveSummaryParams as RawUsageSummaryParams,+ UsageRetrieveSummaryResponse as RawUsageSummaryResponse,+} from '@composio/client/resources/project/usage';+import {+ UsageBreakdownParams,+ UsageBreakdownResponse,+ UsageBreakdownResponseSchema,+ UsageFilters,+ UsageSummaryParams,+ UsageSummaryResponse,+ UsageSummaryResponseSchema,+} from '../../types/usage.types';+import { transform } from '../transform';++const transformUsageFilters = (+ filters: UsageFilters | undefined+): RawUsageSummaryParams['filters'] =>+ filters ? { user_id: filters.userId, session_id: filters.sessionId } : undefined;++export const transformUsageSummaryParams = (params: UsageSummaryParams): RawUsageSummaryParams => ({+ from: params.from,+ to: params.to,+ entity_types: params.entityTypes,+ filters: transformUsageFilters(params.filters),+});++export const transformUsageBreakdownParams = (+ params: UsageBreakdownParams+): RawUsageBreakdownParams => ({+ from: params.from,+ to: params.to,+ group_by: params.groupBy,+ order_by: params.orderBy,+ order_direction: params.orderDirection,+ limit: params.limit,+ filters: transformUsageFilters(params.filters),+});++export const transformUsageSummaryResponse = (+ response: RawUsageSummaryResponse+): UsageSummaryResponse => {+ return transform(response)+ .with(UsageSummaryResponseSchema)+ .using(response => ({+ entities: Object.fromEntries(+ Object.entries(response.entities).map(([entityType, entity]) => [+ entityType,+ {+ unit: entity.unit,+ totalQuantity: entity.total_quantity,+ eventCount: entity.event_count,+ },+ ])+ ),+ }));+};++export const transformUsageBreakdownResponse = (+ response: RawUsageBreakdownResponse+): UsageBreakdownResponse => {+ return transform(response)+ .with(UsageBreakdownResponseSchema)+ .using(response => ({+ entityType: response.entity_type,+ unit: response.unit,+ totalQuantity: response.total_quantity,+ eventCount: response.event_count,+ groups: response.groups.map(group => ({+ key: group.key,+ totalQuantity: group.total_quantity,+ eventCount: group.event_count,+ })),+ }));+};diff --git a/ts/packages/core/src/utils/transformers/webhooks.ts b/ts/packages/core/src/utils/transformers/webhooks.tsnew file mode 100644index 000000000..a37509b7c--- /dev/null+++ b/ts/packages/core/src/utils/transformers/webhooks.ts@@ -0,0 +1,139 @@+import type {+ WebhookSubscriptionCreateResponse as RawWebhookSubscriptionCreateResponse,+ WebhookSubscriptionDeleteResponse as RawWebhookSubscriptionDeleteResponse,+ WebhookSubscriptionListEventTypesResponse as RawWebhookSubscriptionListEventTypesResponse,+ WebhookSubscriptionListResponse as RawWebhookSubscriptionListResponse,+ WebhookSubscriptionRetrieveResponse as RawWebhookSubscriptionRetrieveResponse,+ WebhookSubscriptionRotateSecretResponse as RawWebhookSubscriptionRotateSecretResponse,+ WebhookSubscriptionUpdateResponse as RawWebhookSubscriptionUpdateResponse,+} from '@composio/client/resources/webhook-subscriptions';+import type {+ WebhookEndpointCreateResponse as RawWebhookEndpointCreateResponse,+ WebhookEndpointListResponse as RawWebhookEndpointListResponse,+ WebhookEndpointReplaceResponse as RawWebhookEndpointReplaceResponse,+ WebhookEndpointRetrieveResponse as RawWebhookEndpointRetrieveResponse,+ WebhookEndpointUpdateResponse as RawWebhookEndpointUpdateResponse,+} from '@composio/client/resources/webhook-endpoints';+import type { WebhookSubscription } from '../../types/triggers.types';+import {+ WebhookEndpoint,+ WebhookEndpointListResponse,+ WebhookEndpointListResponseSchema,+ WebhookEndpointSchema,+ WebhookSubscriptionEventTypesResponse,+ WebhookSubscriptionEventTypesResponseSchema,+ WebhookSubscriptionDeleteResponse,+ WebhookSubscriptionDeleteResponseSchema,+ WebhookSubscriptionListResponse,+ WebhookSubscriptionListResponseSchema,+ WebhookSubscriptionRotateSecretResponse,+ WebhookSubscriptionRotateSecretResponseSchema,+ WebhookSubscriptionSchema,+} from '../../types/webhooks.types';+import { transform } from '../transform';++/**+ * Every subscription read/write on the wire returns the same object; the+ * generated client only gives it a different nominal name per operation.+ */+export type RawWebhookSubscription =+ | RawWebhookSubscriptionCreateResponse+ | RawWebhookSubscriptionRetrieveResponse+ | RawWebhookSubscriptionUpdateResponse+ | RawWebhookSubscriptionListResponse['items'][number];++export const transformWebhookSubscription = (+ response: RawWebhookSubscription+): WebhookSubscription => {+ // Map to camelCase explicitly — do NOT spread `...response`, or the wire's+ // snake_case keys (webhook_url, enabled_events, created_at, ...) leak into+ // the public object alongside their camelCase counterparts.+ return transform(response)+ .with(WebhookSubscriptionSchema)+ .using(response => ({+ id: response.id,+ webhookUrl: response.webhook_url,+ version: response.version,+ enabledEvents: response.enabled_events,+ secret: response.secret,+ createdAt: response.created_at,+ updatedAt: response.updated_at,+ }));+};++export const transformWebhookSubscriptionListResponse = (+ response: RawWebhookSubscriptionListResponse+): WebhookSubscriptionListResponse => {+ return transform(response)+ .with(WebhookSubscriptionListResponseSchema)+ .using(response => ({+ items: response.items.map(transformWebhookSubscription),+ nextCursor: response.next_cursor ?? null,+ totalPages: response.total_pages,+ currentPage: response.current_page,+ totalItems: response.total_items,+ }));+};++export const transformWebhookSubscriptionDeleteResponse = (+ response: RawWebhookSubscriptionDeleteResponse+): WebhookSubscriptionDeleteResponse => {+ return transform(response)+ .with(WebhookSubscriptionDeleteResponseSchema)+ .using(response => ({ success: response.success }));+};++export const transformWebhookSubscriptionRotateSecretResponse = (+ response: RawWebhookSubscriptionRotateSecretResponse+): WebhookSubscriptionRotateSecretResponse => {+ return transform(response)+ .with(WebhookSubscriptionRotateSecretResponseSchema)+ .using(response => ({ id: response.id, secret: response.secret }));+};++export const transformWebhookSubscriptionEventTypesResponse = (+ response: RawWebhookSubscriptionListEventTypesResponse+): WebhookSubscriptionEventTypesResponse => {+ return transform(response)+ .with(WebhookSubscriptionEventTypesResponseSchema)+ .using(response => ({+ items: response.items.map(item => ({+ eventType: item.event_type,+ description: item.description,+ supportedVersions: item.supported_versions,+ })),+ }));+};++export type RawWebhookEndpoint =+ | RawWebhookEndpointCreateResponse+ | RawWebhookEndpointRetrieveResponse+ | RawWebhookEndpointReplaceResponse+ | RawWebhookEndpointUpdateResponse;++export const transformWebhookEndpoint = (response: RawWebhookEndpoint): WebhookEndpoint => {+ return transform(response)+ .with(WebhookEndpointSchema)+ .using(response => ({+ id: response.id,+ toolkitSlug: response.toolkit_slug,+ clientId: response.client_id,+ webhookUrl: response.webhook_url,+ data: response.data,+ createdAt: response.created_at,+ }));+};++export const transformWebhookEndpointListResponse = (+ response: RawWebhookEndpointListResponse+): WebhookEndpointListResponse => {+ return transform(response)+ .with(WebhookEndpointListResponseSchema)+ .using(response => ({+ items: response.items.map(item => ({+ id: item.id,+ toolkitSlug: item.toolkit_slug,+ clientId: item.client_id,+ })),+ }));+};diff --git a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.tsindex f7e9d72e2..3b70561db 100644--- a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts+++ b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts@@ -7,14 +7,22 @@ import { ConnectedAccountRetrieveResponse } from '@composio/client/resources/conimport {ComposioAclOnlyForSharedError,ComposioConnectedAccountNotFoundError,+ ComposioConnectedAccountNotRevokableError,+ ComposioConnectedAccountRevocationNotSupportedError,ComposioFailedToCreateConnectedAccountLink,} from '../../src/errors';-import { BadRequestError } from '@composio/client';+import {+ BadRequestError,+ ConflictError,+ InternalServerError,+ NotFoundError,+} from '@composio/client';import { ConnectedAccountStatuses } from '../../src/types/connectedAccounts.types';import { ComposioMultipleConnectedAccountsError } from '../../src/errors';import { AuthSchemeTypes } from '../../src/types/authConfigs.types';import { AuthScheme } from '../../src/models/AuthScheme';import { ConnectionStatuses } from '../../src/types/connectedAccountAuthStates.types';+import logger from '../../src/utils/logger';// Extend the mock client object for ConnectedAccounts testingconst extendedMockClient = {@@ -25,6 +33,8 @@ const extendedMockClient = {retrieve: vi.fn(),delete: vi.fn(),refresh: vi.fn(),+ revoke: vi.fn(),+ completeAuth: vi.fn(),patch: vi.fn(),updateStatus: vi.fn(),createConnectedAccountLink: vi.fn(),@@ -808,16 +818,16 @@ describe('ConnectedAccounts', () => {nanoid,{query_redirect_url: redirectUrl,- validate_credentials: undefined,},undefined);expect(result).toEqual(mockResponse);});- it('should refresh a connected account with validateCredentials option', async () => {+ it('should ignore the removed validateCredentials option and warn', async () => {const nanoid = 'conn_123';const mockResponse = { id: nanoid, refreshed: true };+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);@@ -827,11 +837,12 @@ describe('ConnectedAccounts', () => {nanoid,{query_redirect_url: undefined,- validate_credentials: true,},undefined);+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('validateCredentials'));expect(result).toEqual(mockResponse);+ warnSpy.mockRestore();});it('should refresh a connected account with both options', async () => {@@ -850,7 +861,6 @@ describe('ConnectedAccounts', () => {nanoid,{query_redirect_url: options.redirectUrl,- validate_credentials: options.validateCredentials,},undefined);@@ -880,7 +890,6 @@ describe('ConnectedAccounts', () => {nanoid,{query_redirect_url: undefined,- validate_credentials: undefined,},undefined);@@ -1874,4 +1883,120 @@ describe('ConnectedAccounts', () => {);});});++ describe('revoke', () => {+ const nanoid = 'conn_123';++ it('should revoke a connected account and transform the response', async () => {+ extendedMockClient.connectedAccounts.revoke.mockResolvedValueOnce({+ revoked_tokens: ['access_token', 'refresh_token'],+ connected_account: { id: nanoid, status: 'REVOKED' },+ });++ const result = await connectedAccounts.revoke(nanoid);++ expect(extendedMockClient.connectedAccounts.revoke).toHaveBeenCalledWith(nanoid, undefined);+ expect(result).toEqual({+ revokedTokens: ['access_token', 'refresh_token'],+ connectedAccount: { id: nanoid, status: 'REVOKED' },+ });+ });++ it('should forward request options', async () => {+ extendedMockClient.connectedAccounts.revoke.mockResolvedValueOnce({+ revoked_tokens: [],+ connected_account: { id: nanoid, status: 'REVOKED' },+ });+ const signal = new AbortController().signal;++ await connectedAccounts.revoke(nanoid, { signal });++ expect(extendedMockClient.connectedAccounts.revoke).toHaveBeenCalledWith(nanoid, { signal });+ });++ it('should surface a 400 as ComposioConnectedAccountRevocationNotSupportedError', async () => {+ extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(+ new BadRequestError(400, undefined, 'Toolkit does not support revocation', {})+ );++ const error = await connectedAccounts.revoke(nanoid).catch((caught: unknown) => caught);++ expect(error).toBeInstanceOf(ComposioConnectedAccountRevocationNotSupportedError);+ expect(error).toMatchObject({+ message: expect.stringContaining('does not support revocation'),+ meta: { nanoid },+ });+ });++ it('should surface a 409 as ComposioConnectedAccountNotRevokableError', async () => {+ extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(+ new ConflictError(409, undefined, 'Connection is not in a revokable state', {})+ );++ await expect(connectedAccounts.revoke(nanoid)).rejects.toThrow(+ ComposioConnectedAccountNotRevokableError+ );+ });++ it('should rethrow other errors unchanged', async () => {+ const serverError = new InternalServerError(500, undefined, 'boom', {});+ extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(serverError);++ await expect(connectedAccounts.revoke(nanoid)).rejects.toBe(serverError);+ });+ });++ describe('completeAuth', () => {+ it('should redeem the session and transform the response', async () => {+ extendedMockClient.connectedAccounts.completeAuth.mockResolvedValueOnce({+ connected_account_id: 'ca_123',+ toolkit_slug: 'github',+ });++ const result = await connectedAccounts.completeAuth({+ userId: 'user_1',+ sessionUri: 'session_abc',+ });++ expect(extendedMockClient.connectedAccounts.completeAuth).toHaveBeenCalledWith(+ { user_id: 'user_1', session_uri: 'session_abc' },+ undefined+ );+ expect(result).toEqual({ connectedAccountId: 'ca_123', toolkitSlug: 'github' });+ });++ it('should forward request options', async () => {+ extendedMockClient.connectedAccounts.completeAuth.mockResolvedValueOnce({+ connected_account_id: 'ca_123',+ toolkit_slug: 'github',+ });+ const signal = new AbortController().signal;++ await connectedAccounts.completeAuth(+ { userId: 'user_1', sessionUri: 'session_abc' },+ { signal }+ );++ expect(extendedMockClient.connectedAccounts.completeAuth).toHaveBeenCalledWith(+ { user_id: 'user_1', session_uri: 'session_abc' },+ { signal }+ );+ });++ it('should reject an empty userId before calling the API', async () => {+ await expect(+ connectedAccounts.completeAuth({ userId: '', sessionUri: 'session_abc' })+ ).rejects.toThrow('Failed to parse connected account completeAuth params');+ expect(extendedMockClient.connectedAccounts.completeAuth).not.toHaveBeenCalled();+ });++ it('should rethrow API errors unchanged', async () => {+ const notFound = new NotFoundError(404, undefined, 'Session not found', {});+ extendedMockClient.connectedAccounts.completeAuth.mockRejectedValueOnce(notFound);++ await expect(+ connectedAccounts.completeAuth({ userId: 'user_1', sessionUri: 'session_abc' })+ ).rejects.toBe(notFound);+ });+ });});diff --git a/ts/packages/core/test/core/loggerConfig.test.ts b/ts/packages/core/test/core/loggerConfig.test.tsnew file mode 100644index 000000000..91e5f79c4--- /dev/null+++ b/ts/packages/core/test/core/loggerConfig.test.ts@@ -0,0 +1,181 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { Composio } from '../../src/composio';+import logger from '../../src/utils/logger';+import { MockProvider } from '../utils/mocks/provider.mock';++const DEPRECATION_HEADER = '@1688169599';++const jsonResponse = (body: unknown, headers: Record<string, string> = {}): Response =>+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { 'content-type': 'application/json', ...headers },+ });++const createSink = () => ({+ error: vi.fn(),+ warn: vi.fn(),+ info: vi.fn(),+ debug: vi.fn(),+});++const createComposio = (config: Partial<ConstructorParameters<typeof Composio>[0]> = {}) =>+ new Composio({+ apiKey: 'uak_test_secret',+ baseURL: 'https://backend.composio.test',+ provider: new MockProvider(),+ allowTracking: false,+ disableVersionCheck: true,+ ...config,+ });++describe('Composio logger and logLevel configuration', () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ // The SDK logger is a process-wide singleton; restore the defaults so+ // later tests in this file start from a known state.+ logger.configure({ level: 'info', sink: console });+ });++ it('routes response Deprecation header warnings through the configured logger', async () => {+ const sink = createSink();+ fetchMock.mockResolvedValue(jsonResponse({ items: [] }, { Deprecation: DEPRECATION_HEADER }));+ const composio = createComposio({ logger: sink });++ await composio.getClient().toolkits.list();++ expect(sink.warn).toHaveBeenCalledTimes(1);+ const message = String(sink.warn.mock.calls[0]?.[0]);+ expect(message).toContain('deprecated');+ expect(message).toContain('toolkits.list');+ });++ it('formats and redacts client warnings with the SDK logger before they reach the sink', async () => {+ const sink = createSink();+ fetchMock.mockResolvedValue(+ jsonResponse(+ { items: [] },+ {+ Deprecation: DEPRECATION_HEADER,+ Link: '<https://backend.composio.test/docs?api_key=uak_leaked_secret>; rel="deprecation"',+ }+ )+ );+ const composio = createComposio({ logger: sink });++ await composio.getClient().toolkits.list();++ expect(sink.warn).toHaveBeenCalledTimes(1);+ const message = String(sink.warn.mock.calls[0]?.[0]);+ // SDK formatting prepends an ISO timestamp.+ expect(message).toMatch(/^\S*\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\S* - /);+ expect(message).not.toContain('uak_leaked_secret');+ expect(message).toContain('[REDACTED]');+ });++ it('warns about deprecated request inputs before the request is dispatched', async () => {+ const sink = createSink();+ const order: string[] = [];+ sink.warn.mockImplementation(() => order.push('warn'));+ fetchMock.mockImplementation(async () => {+ order.push('fetch');+ return jsonResponse({ items: [], total_pages: 1, current_page: 1, total_items: 0 });+ });+ const composio = createComposio({ logger: sink });++ await composio.getClient().tools.list({ search: 'x' });++ expect(sink.warn).toHaveBeenCalledTimes(1);+ const message = String(sink.warn.mock.calls[0]?.[0]);+ expect(message).toContain('`search`');+ expect(message).toContain('deprecated');+ expect(order).toEqual(['warn', 'fetch']);+ });++ it("suppresses both deprecation warnings when logLevel is 'silent'", async () => {+ const sink = createSink();+ fetchMock.mockResolvedValue(jsonResponse({ items: [] }, { Deprecation: DEPRECATION_HEADER }));+ const composio = createComposio({ logger: sink, logLevel: 'silent' });++ await composio.getClient().toolkits.list();+ await composio.getClient().tools.list({ search: 'x' });++ expect(sink.warn).not.toHaveBeenCalled();+ expect(sink.info).not.toHaveBeenCalled();+ expect(sink.debug).not.toHaveBeenCalled();+ expect(sink.error).not.toHaveBeenCalled();+ });++ it("suppresses warnings when logLevel is 'error'", async () => {+ const sink = createSink();+ fetchMock.mockResolvedValue(jsonResponse({ items: [] }, { Deprecation: DEPRECATION_HEADER }));+ const composio = createComposio({ logger: sink, logLevel: 'error' });++ await composio.getClient().toolkits.list();+ await composio.getClient().tools.list({ search: 'x' });++ expect(sink.warn).not.toHaveBeenCalled();+ expect(logger.getLevel()).toBe('error');+ });++ it('keeps per-request client logs out of the default info level', async () => {+ const sink = createSink();+ fetchMock.mockResolvedValue(jsonResponse({ items: [] }));+ const composio = createComposio({ logger: sink });++ await composio.getClient().toolkits.list();++ expect(sink.info).not.toHaveBeenCalled();+ expect(sink.debug).not.toHaveBeenCalled();+ expect(sink.warn).not.toHaveBeenCalled();+ });++ it("routes per-request client logs to debug when logLevel is 'debug'", async () => {+ const sink = createSink();+ fetchMock.mockResolvedValue(jsonResponse({ items: [] }));+ const composio = createComposio({ logger: sink, logLevel: 'debug' });++ await composio.getClient().toolkits.list();++ expect(sink.info).not.toHaveBeenCalled();+ expect(sink.debug.mock.calls.map(call => String(call[0])).join('\n')).toContain('/toolkits');+ });++ it('leaves the singleton untouched when neither option is provided', () => {+ const sink = createSink();+ logger.configure({ level: 'debug', sink });++ createComposio();++ expect(logger.getLevel()).toBe('debug');+ logger.debug('still routed');+ expect(String(sink.debug.mock.lastCall?.[0])).toContain('still routed');+ });++ it('applies logLevel without replacing the sink, and the last instance wins', () => {+ const first = createSink();+ const second = createSink();++ createComposio({ logger: first, logLevel: 'warn' });+ expect(logger.getLevel()).toBe('warn');++ createComposio({ logLevel: 'debug' });+ expect(logger.getLevel()).toBe('debug');+ logger.debug('to first');+ expect(String(first.debug.mock.lastCall?.[0])).toContain('to first');+ expect(second.debug).not.toHaveBeenCalled();++ createComposio({ logger: second });+ const firstCallsBefore = first.debug.mock.calls.length;+ logger.debug('to second');+ expect(first.debug.mock.calls.length).toBe(firstCallsBefore);+ expect(String(second.debug.mock.lastCall?.[0])).toContain('to second');+ });+});diff --git a/ts/packages/core/test/models/customToolkits.test.ts b/ts/packages/core/test/models/customToolkits.test.tsnew file mode 100644index 000000000..3a1ff1671--- /dev/null+++ b/ts/packages/core/test/models/customToolkits.test.ts@@ -0,0 +1,197 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import ComposioClient from '@composio/client';+import { CustomToolkits } from '../../src/models/CustomToolkits';+import { Experimental } from '../../src/models/Experimental';+import { telemetry } from '../../src/telemetry/Telemetry';+import { ValidationError } from '../../src/errors/ValidationErrors';++vi.mock('../../src/telemetry/Telemetry', () => ({+ telemetry: {+ instrument: vi.fn(),+ },+}));++const createMockClient = () => ({+ custom: {+ upsert: vi.fn(),+ sync: vi.fn(),+ deleteToolkit: vi.fn(),+ },+});++describe('Experimental.customToolkits', () => {+ let customToolkits: CustomToolkits;+ let mockClient: ReturnType<typeof createMockClient>;++ beforeEach(() => {+ vi.clearAllMocks();+ mockClient = createMockClient();+ customToolkits = new Experimental(mockClient as unknown as ComposioClient).customToolkits;+ });++ it('mounts on the experimental namespace and instruments it', () => {+ expect(customToolkits).toBeInstanceOf(CustomToolkits);+ expect(telemetry.instrument).toHaveBeenCalledWith(customToolkits, 'CustomToolkits');+ });++ describe('upsert', () => {+ it('maps every auth scheme and the logo to the wire', async () => {+ mockClient.custom.upsert.mockResolvedValue({ slug: 'CUSTOM_MY_TOOLKIT' });++ const result = await customToolkits.upsert({+ slug: 'MY TOOLKIT',+ toolkitConfig: {+ name: 'My Toolkit',+ appUrl: 'https://mcp.example.com/mcp',+ logoFile: { content: 'aGVsbG8=', mimeType: 'image/png' },+ authSchemes: [+ { mode: 'NO_AUTH' },+ {+ mode: 'API_KEY',+ headers: { Authorization: 'Bearer {{generic_api_key}}' },+ apiKeyField: { displayName: 'API key', description: 'From your settings page' },+ },+ {+ mode: 'DCR_OAUTH',+ discoveryUrl: 'https://mcp.example.com/.well-known/oauth-authorization-server',+ },+ ],+ },+ });++ expect(mockClient.custom.upsert).toHaveBeenCalledWith(+ {+ slug: 'MY TOOLKIT',+ toolkit_config: {+ name: 'My Toolkit',+ app_url: 'https://mcp.example.com/mcp',+ logo_file: { content: 'aGVsbG8=', mime_type: 'image/png' },+ auth_schemes: [+ { mode: 'NO_AUTH' },+ {+ mode: 'API_KEY',+ headers: { Authorization: 'Bearer {{generic_api_key}}' },+ api_key_field: { display_name: 'API key', description: 'From your settings page' },+ },+ {+ mode: 'DCR_OAUTH',+ discovery_url: 'https://mcp.example.com/.well-known/oauth-authorization-server',+ },+ ],+ },+ },+ undefined+ );+ expect(result).toEqual({ slug: 'CUSTOM_MY_TOOLKIT' });+ });++ it('omits the optional logo and API key copy', async () => {+ mockClient.custom.upsert.mockResolvedValue({ slug: 'CUSTOM_MY_TOOLKIT' });++ await customToolkits.upsert({+ slug: 'MY_TOOLKIT',+ toolkitConfig: {+ name: 'My Toolkit',+ appUrl: 'https://mcp.example.com/mcp',+ authSchemes: [{ mode: 'API_KEY', headers: { 'x-api-key': '{{generic_api_key}}' } }],+ },+ });++ const [body] = mockClient.custom.upsert.mock.calls[0];+ expect(JSON.parse(JSON.stringify(body))).toEqual({+ slug: 'MY_TOOLKIT',+ toolkit_config: {+ name: 'My Toolkit',+ app_url: 'https://mcp.example.com/mcp',+ auth_schemes: [{ mode: 'API_KEY', headers: { 'x-api-key': '{{generic_api_key}}' } }],+ },+ });+ });++ it.each([+ ['a slug outside the API grammar', { slug: 'my-toolkit' }],+ ['no auth schemes', { authSchemes: [] }],+ ['an app URL that is not a URL', { appUrl: 'not a url' }],+ ])('rejects %s before calling the API', async (_label, override) => {+ const { slug = 'MY_TOOLKIT', ...config } = override as Record<string, unknown>;++ await expect(+ customToolkits.upsert({+ slug: slug as string,+ toolkitConfig: {+ name: 'My Toolkit',+ appUrl: 'https://mcp.example.com/mcp',+ authSchemes: [{ mode: 'NO_AUTH' }],+ ...config,+ },+ })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.custom.upsert).not.toHaveBeenCalled();+ });+ });++ describe('sync', () => {+ it('sends the slug and connected account and transforms the response', async () => {+ mockClient.custom.sync.mockResolvedValue({+ slug: 'CUSTOM_MY_TOOLKIT',+ version: '20260911_00',+ synced_count: 12,+ });+ const signal = new AbortController().signal;++ const result = await customToolkits.sync(+ 'CUSTOM_MY_TOOLKIT',+ { connectedAccountId: 'ca_abc123' },+ { signal }+ );++ expect(mockClient.custom.sync).toHaveBeenCalledWith(+ { slug: 'CUSTOM_MY_TOOLKIT', connected_account_id: 'ca_abc123' },+ { signal }+ );+ expect(result).toEqual({+ slug: 'CUSTOM_MY_TOOLKIT',+ version: '20260911_00',+ syncedCount: 12,+ });+ });++ it('sends only the slug when called without params', async () => {+ mockClient.custom.sync.mockResolvedValue({+ slug: 'CUSTOM_MY_TOOLKIT',+ version: '20260911_00',+ synced_count: 0,+ });++ await customToolkits.sync('CUSTOM_MY_TOOLKIT');++ expect(mockClient.custom.sync).toHaveBeenCalledWith(+ { slug: 'CUSTOM_MY_TOOLKIT', connected_account_id: undefined },+ undefined+ );+ });+ });++ describe('delete', () => {+ it('deletes the toolkit and transforms the response', async () => {+ mockClient.custom.deleteToolkit.mockResolvedValue({+ slug: 'CUSTOM_MY_TOOLKIT',+ deleted: true,+ revoke_job_ids: ['job_1'],+ auth_configs_deleted: 1,+ connected_accounts_deleted: 2,+ });++ const result = await customToolkits.delete('CUSTOM_MY_TOOLKIT');++ expect(mockClient.custom.deleteToolkit).toHaveBeenCalledWith('CUSTOM_MY_TOOLKIT', undefined);+ expect(result).toEqual({+ slug: 'CUSTOM_MY_TOOLKIT',+ deleted: true,+ revokeJobIds: ['job_1'],+ authConfigsDeleted: 1,+ connectedAccountsDeleted: 2,+ });+ });+ });+});diff --git a/ts/packages/core/test/models/keyring.test.ts b/ts/packages/core/test/models/keyring.test.tsnew file mode 100644index 000000000..df120b145--- /dev/null+++ b/ts/packages/core/test/models/keyring.test.ts@@ -0,0 +1,69 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import ComposioClient from '@composio/client';+import { Keyring } from '../../src/models/Keyring';+import { telemetry } from '../../src/telemetry/Telemetry';++vi.mock('../../src/telemetry/Telemetry', () => ({+ telemetry: {+ instrument: vi.fn(),+ },+}));++const createMockClient = () => ({+ keyring: {+ listTransferKeys: vi.fn(),+ },+});++const rawKey = {+ kty: 'RSA',+ n: 'sXch3m2k0Yg',+ e: 'AQAB',+ alg: 'RSA-OAEP-256',+ use: 'enc',+ kid: 'kid_2',+};++describe('Keyring', () => {+ let keyring: Keyring;+ let mockClient: ReturnType<typeof createMockClient>;++ beforeEach(() => {+ vi.clearAllMocks();+ mockClient = createMockClient();+ keyring = new Keyring(mockClient as unknown as ComposioClient);+ });++ it('instruments itself', () => {+ expect(telemetry.instrument).toHaveBeenCalledWith(keyring, 'Keyring');+ });++ it('returns the active kid and keeps the JWK field names', async () => {+ mockClient.keyring.listTransferKeys.mockResolvedValue({+ success: true,+ active_kid: 'kid_2',+ keys: [rawKey, { ...rawKey, kid: 'kid_1' }],+ });++ const result = await keyring.listTransferKeys();++ expect(mockClient.keyring.listTransferKeys).toHaveBeenCalledWith(undefined);+ expect(result).toEqual({+ activeKid: 'kid_2',+ keys: [rawKey, { ...rawKey, kid: 'kid_1' }],+ });+ });++ it('forwards request options', async () => {+ mockClient.keyring.listTransferKeys.mockResolvedValue({+ success: true,+ active_kid: 'kid_2',+ keys: [rawKey],+ });+ const signal = new AbortController().signal;++ await keyring.listTransferKeys({ signal });++ expect(mockClient.keyring.listTransferKeys).toHaveBeenCalledWith({ signal });+ });+});diff --git a/ts/packages/core/test/models/logs.test.ts b/ts/packages/core/test/models/logs.test.tsnew file mode 100644index 000000000..eacb61a2c--- /dev/null+++ b/ts/packages/core/test/models/logs.test.ts@@ -0,0 +1,153 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import ComposioClient from '@composio/client';+import { Logs } from '../../src/models/Logs';+import { telemetry } from '../../src/telemetry/Telemetry';+import { ValidationError } from '../../src/errors/ValidationErrors';++vi.mock('../../src/telemetry/Telemetry', () => ({+ telemetry: {+ instrument: vi.fn(),+ },+}));++const createMockClient = () => ({+ baseURL: 'https://api.composio.dev',+ apiKey: 'test-api-key',+ logs: {+ createToolExecution: vi.fn(),+ retrieveToolExecution: vi.fn(),+ },+});++const rawLog = {+ id: 'log_1',+ timestamp: '2026-01-01T00:00:00Z',+ type: 'tool.execution',+ status: 'success',+ level: 'info',+ message: 'ok',+ metadata: { tool_slug: 'GITHUB_GET_REPO' },+ metrics: { duration_ms: 12 },+ parent: { log_id: 'log_0', tool_slug: 'COMPOSIO_MULTI_EXECUTE_TOOL' },+};+const transformedLog = {+ id: 'log_1',+ timestamp: '2026-01-01T00:00:00Z',+ type: 'tool.execution',+ status: 'success',+ level: 'info',+ message: 'ok',+ metadata: { tool_slug: 'GITHUB_GET_REPO' },+ metrics: { duration_ms: 12 },+ parent: { logId: 'log_0', toolSlug: 'COMPOSIO_MULTI_EXECUTE_TOOL' },+};++describe('Logs', () => {+ let logs: Logs;+ let mockClient: ReturnType<typeof createMockClient>;++ beforeEach(() => {+ vi.clearAllMocks();+ mockClient = createMockClient();+ logs = new Logs(mockClient as unknown as ComposioClient);+ });++ it('instruments the class with telemetry', () => {+ expect(telemetry.instrument).toHaveBeenCalledWith(logs, 'Logs');+ });++ describe('search', () => {+ it('sends an empty body when called without params', async () => {+ mockClient.logs.createToolExecution.mockResolvedValue({ logs: [], next_cursor: null });++ const result = await logs.search();++ expect(mockClient.logs.createToolExecution).toHaveBeenCalledWith(+ { limit: undefined, cursor: undefined, filters: undefined, time_range: undefined },+ undefined+ );+ expect(result).toEqual({ logs: [], nextCursor: null });+ });++ it('maps camelCase params to the wire and transforms the response', async () => {+ mockClient.logs.createToolExecution.mockResolvedValue({+ logs: [rawLog, { ...rawLog, id: 'log_2', parent: null, message: undefined }],+ next_cursor: 'cursor_2',+ });+ const signal = new AbortController().signal;++ const result = await logs.search(+ {+ limit: 2,+ cursor: 'cursor_1',+ filters: [{ field: 'toolkit_slug', operator: '==', value: 'github' }],+ timeRange: { from: 1, to: 2 },+ },+ { signal }+ );++ expect(mockClient.logs.createToolExecution).toHaveBeenCalledWith(+ {+ limit: 2,+ cursor: 'cursor_1',+ filters: [{ field: 'toolkit_slug', operator: '==', value: 'github' }],+ time_range: { from: 1, to: 2 },+ },+ { signal }+ );+ expect(result).toEqual({+ logs: [+ transformedLog,+ { ...transformedLog, id: 'log_2', parent: null, message: undefined },+ ],+ nextCursor: 'cursor_2',+ });+ });++ it('throws a ValidationError for an unknown filter field', async () => {+ await expect(+ logs.search({+ filters: [{ field: 'nope' as 'tool_slug', operator: '==', value: 'x' }],+ })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.logs.createToolExecution).not.toHaveBeenCalled();+ });+ });++ describe('get', () => {+ it('retrieves a log by id and transforms the detail fields', async () => {+ mockClient.logs.retrieveToolExecution.mockResolvedValue({+ ...rawLog,+ timings: { start_time: 10, end_time: 22 },+ context: { session_id: 'trs_1', trace_id: 'trace_1', request_id: 'req_1' },+ source: { host: 'node', framework: 'vercel', language: 'typescript' },+ data: { input: { owner: 'composio' } },+ });++ const result = await logs.get('log_1');++ expect(mockClient.logs.retrieveToolExecution).toHaveBeenCalledWith('log_1', undefined);+ expect(result).toEqual({+ ...transformedLog,+ timings: { startTime: 10, endTime: 22 },+ context: { sessionId: 'trs_1', traceId: 'trace_1', requestId: 'req_1' },+ source: { host: 'node', framework: 'vercel', language: 'typescript' },+ data: { input: { owner: 'composio' } },+ });+ });++ it('leaves timings undefined when the API omits them', async () => {+ mockClient.logs.retrieveToolExecution.mockResolvedValue({+ ...rawLog,+ context: {},+ source: {},+ data: {},+ });++ const result = await logs.get('log_1');++ expect(result.timings).toBeUndefined();+ expect(result.context).toEqual({});+ });+ });+});diff --git a/ts/packages/core/test/models/toolRouter.test.ts b/ts/packages/core/test/models/toolRouter.test.tsindex 263374736..00c277db4 100644--- a/ts/packages/core/test/models/toolRouter.test.ts+++ b/ts/packages/core/test/models/toolRouter.test.ts@@ -13,6 +13,7 @@ import {} from '../../src/types/toolRouter.types';import { createCustomTool } from '../../src/models/CustomTool';import { DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX } from '../../src/models/ToolRouterSession';+import { ValidationError } from '../../src/errors/ValidationErrors';// Mock dependenciesvi.mock('../../src/telemetry/Telemetry', () => ({@@ -50,6 +51,7 @@ const createMockClient = () => ({toolkits: vi.fn(),search: vi.fn(),execute: vi.fn(),+ configHistory: vi.fn(),},},tools: {@@ -3658,4 +3660,92 @@ describe('ToolRouter', () => {expect(mockClient.post).not.toHaveBeenCalled();});});++ describe('session.configHistory', () => {+ const sessionId = 'session_123';+ const rawHistoryItem = {+ version: 2,+ created_at: '2026-01-02T00:00:00Z',+ is_current: true,+ config: {+ user_id: 'user_123',+ toolkits: { enabled: ['github'] },+ preload: { tools: [] },+ search: {},+ execute: {},+ },+ };++ it('should page through the session config history', async () => {+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(mockSessionRetrieveResponse);+ mockClient.toolRouter.session.configHistory.mockResolvedValueOnce({+ items: [rawHistoryItem, { ...rawHistoryItem, version: 1, is_current: false }],+ next_cursor: 'cursor_2',+ total_pages: 2,+ current_page: 1,+ total_items: 3,+ });++ const session = await toolRouter.use(sessionId);+ const result = await session.configHistory({ limit: 2 });++ expect(mockClient.toolRouter.session.configHistory).toHaveBeenCalledWith(+ sessionId,+ { cursor: undefined, limit: 2 },+ undefined+ );+ expect(result).toEqual({+ items: [+ {+ version: 2,+ createdAt: '2026-01-02T00:00:00Z',+ isCurrent: true,+ config: rawHistoryItem.config,+ },+ {+ version: 1,+ createdAt: '2026-01-02T00:00:00Z',+ isCurrent: false,+ config: rawHistoryItem.config,+ },+ ],+ nextCursor: 'cursor_2',+ totalPages: 2,+ currentPage: 1,+ totalItems: 3,+ });+ });++ it('should default nextCursor to null and forward request options', async () => {+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(mockSessionRetrieveResponse);+ mockClient.toolRouter.session.configHistory.mockResolvedValueOnce({+ items: [],+ total_pages: 0,+ current_page: 1,+ total_items: 0,+ });+ const signal = new AbortController().signal;++ const session = await toolRouter.use(sessionId);+ const result = await session.configHistory(undefined, { signal });++ expect(mockClient.toolRouter.session.configHistory).toHaveBeenCalledWith(+ sessionId,+ { cursor: undefined, limit: undefined },+ { signal }+ );+ expect(result.nextCursor).toBeNull();+ });++ it('should throw a ValidationError for invalid options', async () => {+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(mockSessionRetrieveResponse);++ const session = await toolRouter.use(sessionId);++ await expect(session.configHistory({ limit: 'ten' as unknown as number })).rejects.toThrow(+ ValidationError+ );+ expect(mockClient.toolRouter.session.configHistory).not.toHaveBeenCalled();+ });+ });});diff --git a/ts/packages/core/test/models/toolkitScopes.test.ts b/ts/packages/core/test/models/toolkitScopes.test.tsnew file mode 100644index 000000000..5a320d90a--- /dev/null+++ b/ts/packages/core/test/models/toolkitScopes.test.ts@@ -0,0 +1,191 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import ComposioClient from '@composio/client';+import { Toolkits } from '../../src/models/Toolkits';+import { ValidationError } from '../../src/errors/ValidationErrors';++vi.mock('../../src/telemetry/Telemetry', () => ({+ telemetry: {+ instrument: vi.fn(),+ },+}));++const createMockClient = () => ({+ toolkits: {+ recommendScopes: vi.fn(),+ retrieveScopesGrantContext: vi.fn(),+ },+});++const rawRecommendation = {+ auth_scheme: 'OAUTH2',+ toolkit_version: '20250909_00',+ grant_context: { account_type: 'Google Workspace' },+ scopes: {+ least_privilege: ['https://www.googleapis.com/auth/gmail.send'],+ fewest: ['https://mail.google.com/'],+ conditional: [+ {+ scope: 'https://www.googleapis.com/auth/gmail.modify',+ when: { label_ids: ['TRASH'] },+ for: ['GMAIL_FETCH_EMAILS'],+ },+ ],+ },+};++describe('Toolkits scope recommendation', () => {+ let toolkits: Toolkits;+ let mockClient: ReturnType<typeof createMockClient>;++ beforeEach(() => {+ vi.clearAllMocks();+ mockClient = createMockClient();+ toolkits = new Toolkits(mockClient as unknown as ComposioClient);+ });++ describe('recommendScopes', () => {+ it('covers every tool when tools is empty', async () => {+ mockClient.toolkits.recommendScopes.mockResolvedValue(rawRecommendation);++ await toolkits.recommendScopes('gmail', { tools: [] });++ expect(mockClient.toolkits.recommendScopes).toHaveBeenCalledWith(+ 'gmail',+ {+ tools: [],+ auth_scheme: undefined,+ toolkit_version: undefined,+ grant_context: undefined,+ include: undefined,+ exclude: undefined,+ available_scopes: undefined,+ },+ undefined+ );+ });++ it('maps params to the wire and transforms the response', async () => {+ mockClient.toolkits.recommendScopes.mockResolvedValue(rawRecommendation);+ const signal = new AbortController().signal;++ const result = await toolkits.recommendScopes(+ 'gmail',+ {+ tools: ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'],+ authScheme: 'OAUTH2',+ toolkitVersion: '20250909_00',+ grantContext: { account_type: 'Google Workspace' },+ include: ['openid'],+ exclude: ['https://mail.google.com/'],+ availableScopes: ['openid', 'https://www.googleapis.com/auth/gmail.send'],+ },+ { signal }+ );++ expect(mockClient.toolkits.recommendScopes).toHaveBeenCalledWith(+ 'gmail',+ {+ tools: ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'],+ auth_scheme: 'OAUTH2',+ toolkit_version: '20250909_00',+ grant_context: { account_type: 'Google Workspace' },+ include: ['openid'],+ exclude: ['https://mail.google.com/'],+ available_scopes: ['openid', 'https://www.googleapis.com/auth/gmail.send'],+ },+ { signal }+ );+ expect(result).toEqual({+ authScheme: 'OAUTH2',+ toolkitVersion: '20250909_00',+ grantContext: { account_type: 'Google Workspace' },+ scopes: {+ leastPrivilege: ['https://www.googleapis.com/auth/gmail.send'],+ fewest: ['https://mail.google.com/'],+ conditional: [+ {+ scope: 'https://www.googleapis.com/auth/gmail.modify',+ when: { label_ids: ['TRASH'] },+ for: ['GMAIL_FETCH_EMAILS'],+ },+ ],+ },+ });+ });++ it('rejects a missing tools list before calling the API', async () => {+ await expect(+ toolkits.recommendScopes('gmail', {} as Parameters<Toolkits['recommendScopes']>[1])+ ).rejects.toThrow(ValidationError);+ expect(mockClient.toolkits.recommendScopes).not.toHaveBeenCalled();+ });++ it('rejects an unknown auth scheme before calling the API', async () => {+ await expect(+ toolkits.recommendScopes('gmail', { tools: [], authScheme: 'NOT_A_SCHEME' as never })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.toolkits.recommendScopes).not.toHaveBeenCalled();+ });+ });++ describe('listGrantContexts', () => {+ const rawGrantContexts = {+ auth_scheme: 'OAUTH2',+ toolkit_version: '20250909_00',+ grant_context_dimensions: [+ {+ dimension: 'account_type',+ description: 'Kind of Google account the user connects',+ values: ['Google Workspace', 'Personal'],+ },+ ],+ default_grant_context: { account_type: 'Personal' },+ };++ it('sends an empty query when called without params', async () => {+ mockClient.toolkits.retrieveScopesGrantContext.mockResolvedValue(rawGrantContexts);++ await toolkits.listGrantContexts('gmail');++ expect(mockClient.toolkits.retrieveScopesGrantContext).toHaveBeenCalledWith(+ 'gmail',+ { auth_scheme: undefined, toolkit_version: undefined },+ undefined+ );+ });++ it('maps params to the wire and transforms the response', async () => {+ mockClient.toolkits.retrieveScopesGrantContext.mockResolvedValue(rawGrantContexts);++ const result = await toolkits.listGrantContexts('gmail', {+ authScheme: 'OAUTH2',+ toolkitVersion: '20250909_00',+ });++ expect(mockClient.toolkits.retrieveScopesGrantContext).toHaveBeenCalledWith(+ 'gmail',+ { auth_scheme: 'OAUTH2', toolkit_version: '20250909_00' },+ undefined+ );+ expect(result).toEqual({+ authScheme: 'OAUTH2',+ toolkitVersion: '20250909_00',+ grantContextDimensions: [+ {+ dimension: 'account_type',+ description: 'Kind of Google account the user connects',+ values: ['Google Workspace', 'Personal'],+ },+ ],+ defaultGrantContext: { account_type: 'Personal' },+ });+ });++ it('rejects an empty toolkit version before calling the API', async () => {+ await expect(toolkits.listGrantContexts('gmail', { toolkitVersion: '' })).rejects.toThrow(+ ValidationError+ );+ expect(mockClient.toolkits.retrieveScopesGrantContext).not.toHaveBeenCalled();+ });+ });+});diff --git a/ts/packages/core/test/models/toolkits.test.ts b/ts/packages/core/test/models/toolkits.test.tsindex 772333bfe..f506bb900 100644--- a/ts/packages/core/test/models/toolkits.test.ts+++ b/ts/packages/core/test/models/toolkits.test.ts@@ -3,6 +3,8 @@ import { Toolkits } from '../../src/models/Toolkits';import ComposioClient from '@composio/client';import { telemetry } from '../../src/telemetry/Telemetry';import { ComposioAuthConfigNotFoundError } from '../../src/errors/AuthConfigErrors';+import { ValidationError } from '../../src/errors/ValidationErrors';+import { ComposioToolkitFetchError } from '../../src/errors/ToolkitErrors';import { AuthSchemeTypes } from '../../src/types/authConfigs.types';import { APIError } from '@composio/client';import type { ToolkitListParams } from '../../src/types/toolkit.types';@@ -28,6 +30,8 @@ const createMockClient = () => ({list: vi.fn(),retrieve: vi.fn(),retrieveCategories: vi.fn(),+ retrieveMulti: vi.fn(),+ retrieveChangelog: vi.fn(),listCategories: vi.fn(),authorize: vi.fn(),get: vi.fn(),@@ -275,6 +279,107 @@ describe('Toolkits', () => {});});+ describe('getMany', () => {+ it('should fetch toolkits by slug and return the list shape', async () => {+ mockClient.toolkits.retrieveMulti.mockResolvedValue(mockToolkitListResponse);++ const result = await toolkits.getMany(['github', 'slack']);++ expect(mockClient.toolkits.retrieveMulti).toHaveBeenCalledWith(+ {+ toolkits: ['github', 'slack'],+ category: undefined,+ managed_by: undefined,+ sort_by: undefined,+ cursor: undefined,+ limit: undefined,+ },+ undefined+ );+ expect(result).toEqual([+ {+ name: 'GitHub',+ slug: 'github',+ meta: {+ createdAt: '2024-01-01',+ updatedAt: '2024-01-02',+ toolsCount: 10,+ triggersCount: 5,+ },+ isLocalToolkit: false,+ authSchemes: ['oauth2'],+ composioManagedAuthSchemes: ['oauth2'],+ noAuth: false,+ },+ ]);+ });++ it('should forward filters and request options', async () => {+ mockClient.toolkits.retrieveMulti.mockResolvedValue({ items: [] });+ const signal = new AbortController().signal;++ await toolkits.getMany(+ ['github'],+ { managedBy: 'composio', sortBy: 'usage', limit: 5 },+ {+ signal,+ }+ );++ expect(mockClient.toolkits.retrieveMulti).toHaveBeenCalledWith(+ {+ toolkits: ['github'],+ category: undefined,+ managed_by: 'composio',+ sort_by: 'usage',+ cursor: undefined,+ limit: 5,+ },+ { signal }+ );+ });++ it('should throw a ValidationError for an empty slug list', async () => {+ await expect(toolkits.getMany([])).rejects.toThrow(ValidationError);+ expect(mockClient.toolkits.retrieveMulti).not.toHaveBeenCalled();+ });++ it('should wrap request failures in ComposioToolkitFetchError', async () => {+ mockClient.toolkits.retrieveMulti.mockRejectedValue(new Error('boom'));++ await expect(toolkits.getMany(['github'])).rejects.toThrow(ComposioToolkitFetchError);+ });+ });++ describe('changelog', () => {+ it('should return the toolkit changelog in camelCase', async () => {+ mockClient.toolkits.retrieveChangelog.mockResolvedValue({+ items: [+ {+ slug: 'github',+ name: 'github',+ display_name: 'GitHub',+ versions: [{ version: '20250909_00', changelog: 'Added issues tools' }],+ },+ ],+ });++ const result = await toolkits.changelog();++ expect(mockClient.toolkits.retrieveChangelog).toHaveBeenCalledWith(undefined);+ expect(result).toEqual({+ items: [+ {+ slug: 'github',+ name: 'github',+ displayName: 'GitHub',+ versions: [{ version: '20250909_00', changelog: 'Added issues tools' }],+ },+ ],+ });+ });+ });+describe('authorize', () => {const userId = 'user_123';const toolkitSlug = 'test-toolkit';diff --git a/ts/packages/core/test/models/triggers.test.ts b/ts/packages/core/test/models/triggers.test.tsindex c84c2710a..b3fda9c70 100644--- a/ts/packages/core/test/models/triggers.test.ts+++ b/ts/packages/core/test/models/triggers.test.ts@@ -30,9 +30,11 @@ vi.mock('../../src/services/pusher/Pusher');const createMockClient = () => ({baseURL: 'https://api.composio.dev',apiKey: 'test-api-key',- get: vi.fn(),- post: vi.fn(),- patch: vi.fn(),+ webhookSubscriptions: {+ list: vi.fn(),+ create: vi.fn(),+ update: vi.fn(),+ },triggerInstances: {listActive: vi.fn(),upsert: vi.fn(),@@ -257,22 +259,21 @@ describe('Triggers', () => {};it('should create a webhook subscription when none exists', async () => {- mockClient.get.mockResolvedValue({ items: [] });- mockClient.post.mockResolvedValue(rawSubscription);+ mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [] });+ mockClient.webhookSubscriptions.create.mockResolvedValue(rawSubscription);const result = await triggers.setWebhookSubscription({ webhookUrl });- expect(mockClient.get).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions', {- query: { limit: 1 },- });- expect(mockClient.post).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions', {- body: {+ expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith({ limit: 1 }, undefined);+ expect(mockClient.webhookSubscriptions.create).toHaveBeenCalledWith(+ {webhook_url: webhookUrl,enabled_events: ['composio.trigger.message'],version: 'V3',},- });- expect(mockClient.patch).not.toHaveBeenCalled();+ undefined+ );+ expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();// Only camelCase keys — the snake_case wire fields must not leak through.expect(result).toEqual({id: 'sub_123',@@ -286,8 +287,8 @@ describe('Triggers', () => {});it('should update the first webhook subscription when one exists', async () => {- mockClient.get.mockResolvedValue({ items: [{ id: 'sub_123' }] });- mockClient.patch.mockResolvedValue(rawSubscription);+ mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [{ id: 'sub_123' }] });+ mockClient.webhookSubscriptions.update.mockResolvedValue(rawSubscription);await triggers.setWebhookSubscription({webhookUrl,@@ -295,21 +296,23 @@ describe('Triggers', () => {version: 'V3',});- expect(mockClient.patch).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions/sub_123', {- body: {+ expect(mockClient.webhookSubscriptions.update).toHaveBeenCalledWith(+ 'sub_123',+ {webhook_url: webhookUrl,enabled_events: ['composio.trigger.message', 'composio.connected_account.expired'],version: 'V3',},- });- expect(mockClient.post).not.toHaveBeenCalled();+ undefined+ );+ expect(mockClient.webhookSubscriptions.create).not.toHaveBeenCalled();});it('should throw validation error for invalid webhook subscription parameters', async () => {await expect(triggers.setWebhookSubscription({ webhookUrl, enabledEvents: [] })).rejects.toThrow(ValidationError);- expect(mockClient.get).not.toHaveBeenCalled();+ expect(mockClient.webhookSubscriptions.list).not.toHaveBeenCalled();});});diff --git a/ts/packages/core/test/models/usage.test.ts b/ts/packages/core/test/models/usage.test.tsnew file mode 100644index 000000000..c2527fc36--- /dev/null+++ b/ts/packages/core/test/models/usage.test.ts@@ -0,0 +1,148 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import ComposioClient from '@composio/client';+import { Experimental } from '../../src/models/Experimental';+import { Usage } from '../../src/models/Usage';+import { telemetry } from '../../src/telemetry/Telemetry';+import { ValidationError } from '../../src/errors/ValidationErrors';++vi.mock('../../src/telemetry/Telemetry', () => ({+ telemetry: {+ instrument: vi.fn(),+ },+}));++const createMockClient = () => ({+ baseURL: 'https://api.composio.dev',+ apiKey: 'test-api-key',+ connectedAccounts: {+ patch: vi.fn(),+ },+ project: {+ usage: {+ retrieveSummary: vi.fn(),+ retrieve: vi.fn(),+ },+ },+});++describe('Experimental.usage', () => {+ let experimental: Experimental;+ let mockClient: ReturnType<typeof createMockClient>;++ beforeEach(() => {+ vi.clearAllMocks();+ mockClient = createMockClient();+ experimental = new Experimental(mockClient as unknown as ComposioClient);+ });++ it('mounts usage on the experimental namespace and instruments it', () => {+ expect(experimental.usage).toBeInstanceOf(Usage);+ expect(telemetry.instrument).toHaveBeenCalledWith(experimental.usage, 'Usage');+ expect(telemetry.instrument).toHaveBeenCalledWith(experimental, 'Experimental');+ });++ describe('summary', () => {+ it('sends an empty body when called without params', async () => {+ mockClient.project.usage.retrieveSummary.mockResolvedValue({ entities: {} });++ const result = await experimental.usage.summary();++ expect(mockClient.project.usage.retrieveSummary).toHaveBeenCalledWith(+ { from: undefined, to: undefined, entity_types: undefined, filters: undefined },+ undefined+ );+ expect(result).toEqual({ entities: {} });+ });++ it('maps params to the wire and transforms the response', async () => {+ mockClient.project.usage.retrieveSummary.mockResolvedValue({+ entities: {+ tool_calls: { unit: 'call', total_quantity: '42', event_count: 42 },+ sessions: { unit: 'session', total_quantity: '3', event_count: 3 },+ },+ });+ const signal = new AbortController().signal;++ const result = await experimental.usage.summary(+ {+ from: 1,+ to: 2,+ entityTypes: ['tool_calls', 'sessions'],+ filters: { userId: ['user_1'], sessionId: null },+ },+ { signal }+ );++ expect(mockClient.project.usage.retrieveSummary).toHaveBeenCalledWith(+ {+ from: 1,+ to: 2,+ entity_types: ['tool_calls', 'sessions'],+ filters: { user_id: ['user_1'], session_id: null },+ },+ { signal }+ );+ expect(result).toEqual({+ entities: {+ tool_calls: { unit: 'call', totalQuantity: '42', eventCount: 42 },+ sessions: { unit: 'session', totalQuantity: '3', eventCount: 3 },+ },+ });+ });++ it('throws a ValidationError for invalid params', async () => {+ await expect(+ experimental.usage.summary({ from: 'yesterday' as unknown as number })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.project.usage.retrieveSummary).not.toHaveBeenCalled();+ });+ });++ describe('breakdown', () => {+ it('passes the entity type positionally and maps params', async () => {+ mockClient.project.usage.retrieve.mockResolvedValue({+ entity_type: 'tool_calls',+ unit: 'call',+ total_quantity: '10',+ event_count: 10,+ groups: [{ key: 'GITHUB_GET_REPO', total_quantity: '10', event_count: 10 }],+ });++ const result = await experimental.usage.breakdown('tool_calls', {+ groupBy: 'tool_slug',+ orderBy: 'event_count',+ orderDirection: 'asc',+ limit: 5,+ filters: { sessionId: ['trs_1'] },+ });++ expect(mockClient.project.usage.retrieve).toHaveBeenCalledWith(+ 'tool_calls',+ {+ from: undefined,+ to: undefined,+ group_by: 'tool_slug',+ order_by: 'event_count',+ order_direction: 'asc',+ limit: 5,+ filters: { user_id: undefined, session_id: ['trs_1'] },+ },+ undefined+ );+ expect(result).toEqual({+ entityType: 'tool_calls',+ unit: 'call',+ totalQuantity: '10',+ eventCount: 10,+ groups: [{ key: 'GITHUB_GET_REPO', totalQuantity: '10', eventCount: 10 }],+ });+ });++ it('throws a ValidationError for an unknown orderBy', async () => {+ await expect(+ experimental.usage.breakdown('tool_calls', { orderBy: 'name' as 'key' })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.project.usage.retrieve).not.toHaveBeenCalled();+ });+ });+});diff --git a/ts/packages/core/test/models/webhooks.test.ts b/ts/packages/core/test/models/webhooks.test.tsnew file mode 100644index 000000000..1a4f808a7--- /dev/null+++ b/ts/packages/core/test/models/webhooks.test.ts@@ -0,0 +1,427 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import ComposioClient from '@composio/client';+import { Webhooks, WebhookSubscriptions, WebhookEndpoints } from '../../src/models/Webhooks';+import { telemetry } from '../../src/telemetry/Telemetry';+import { ValidationError } from '../../src/errors/ValidationErrors';++vi.mock('../../src/telemetry/Telemetry', () => ({+ telemetry: {+ instrument: vi.fn(),+ },+}));++const createMockClient = () => ({+ baseURL: 'https://api.composio.dev',+ apiKey: 'test-api-key',+ webhookSubscriptions: {+ list: vi.fn(),+ retrieve: vi.fn(),+ create: vi.fn(),+ update: vi.fn(),+ delete: vi.fn(),+ rotateSecret: vi.fn(),+ listEventTypes: vi.fn(),+ },+ webhookEndpoints: {+ list: vi.fn(),+ retrieve: vi.fn(),+ create: vi.fn(),+ replace: vi.fn(),+ update: vi.fn(),+ },+});++const webhookUrl = 'https://example.com/webhooks/composio';+const rawSubscription = {+ id: 'sub_123',+ webhook_url: webhookUrl,+ version: 'V3',+ enabled_events: ['composio.trigger.message'],+ secret: 'whsec_123',+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+};+const transformedSubscription = {+ id: 'sub_123',+ webhookUrl,+ version: 'V3',+ enabledEvents: ['composio.trigger.message'],+ secret: 'whsec_123',+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+};++const rawEndpoint = {+ id: 'we_abc123',+ toolkit_slug: 'slack',+ client_id: 'client_1',+ webhook_url: 'https://backend.composio.dev/webhook/slack/we_abc123',+ data: { signing_secret: '***' },+ created_at: '2026-01-01T00:00:00Z',+};+const transformedEndpoint = {+ id: 'we_abc123',+ toolkitSlug: 'slack',+ clientId: 'client_1',+ webhookUrl: 'https://backend.composio.dev/webhook/slack/we_abc123',+ data: { signing_secret: '***' },+ createdAt: '2026-01-01T00:00:00Z',+};++describe('Webhooks', () => {+ let webhooks: Webhooks;+ let mockClient: ReturnType<typeof createMockClient>;++ beforeEach(() => {+ vi.clearAllMocks();+ mockClient = createMockClient();+ webhooks = new Webhooks(mockClient as unknown as ComposioClient);+ });++ describe('constructor', () => {+ it('mounts the subscriptions and endpoints sub-namespaces', () => {+ expect(webhooks.subscriptions).toBeInstanceOf(WebhookSubscriptions);+ expect(webhooks.endpoints).toBeInstanceOf(WebhookEndpoints);+ });++ it('instruments every class with telemetry', () => {+ expect(telemetry.instrument).toHaveBeenCalledWith(webhooks, 'Webhooks');+ expect(telemetry.instrument).toHaveBeenCalledWith(+ webhooks.subscriptions,+ 'WebhookSubscriptions'+ );+ expect(telemetry.instrument).toHaveBeenCalledWith(webhooks.endpoints, 'WebhookEndpoints');+ });+ });++ describe('subscriptions', () => {+ describe('list', () => {+ it('lists subscriptions and transforms the response', async () => {+ mockClient.webhookSubscriptions.list.mockResolvedValue({+ items: [rawSubscription],+ next_cursor: null,+ total_pages: 1,+ current_page: 1,+ total_items: 1,+ });++ const result = await webhooks.subscriptions.list();++ expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith(+ { limit: undefined, cursor: undefined },+ undefined+ );+ expect(result).toEqual({+ items: [transformedSubscription],+ nextCursor: null,+ totalPages: 1,+ currentPage: 1,+ totalItems: 1,+ });+ });++ it('forwards pagination params and request options', async () => {+ mockClient.webhookSubscriptions.list.mockResolvedValue({+ items: [],+ next_cursor: 'next',+ total_pages: 2,+ current_page: 1,+ total_items: 3,+ });+ const signal = new AbortController().signal;++ const result = await webhooks.subscriptions.list({ limit: 2, cursor: 'abc' }, { signal });++ expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith(+ { limit: 2, cursor: 'abc' },+ { signal }+ );+ expect(result.nextCursor).toBe('next');+ });++ it('throws a ValidationError for invalid params', async () => {+ await expect(+ webhooks.subscriptions.list({ limit: 'ten' } as unknown as { limit: number })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.webhookSubscriptions.list).not.toHaveBeenCalled();+ });+ });++ describe('get', () => {+ it('retrieves a subscription by id', async () => {+ mockClient.webhookSubscriptions.retrieve.mockResolvedValue(rawSubscription);++ const result = await webhooks.subscriptions.get('sub_123');++ expect(mockClient.webhookSubscriptions.retrieve).toHaveBeenCalledWith('sub_123', undefined);+ expect(result).toEqual(transformedSubscription);+ });+ });++ describe('set', () => {+ it('creates a subscription when none exists', async () => {+ mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [] });+ mockClient.webhookSubscriptions.create.mockResolvedValue(rawSubscription);++ const result = await webhooks.subscriptions.set({ webhookUrl });++ expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith({ limit: 1 }, undefined);+ expect(mockClient.webhookSubscriptions.create).toHaveBeenCalledWith(+ {+ webhook_url: webhookUrl,+ enabled_events: ['composio.trigger.message'],+ version: 'V3',+ },+ undefined+ );+ expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();+ expect(result).toEqual(transformedSubscription);+ });++ it('updates the existing subscription when one exists', async () => {+ mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [{ id: 'sub_123' }] });+ mockClient.webhookSubscriptions.update.mockResolvedValue(rawSubscription);++ await webhooks.subscriptions.set({+ webhookUrl,+ enabledEvents: ['composio.trigger.message', 'composio.connected_account.expired'],+ version: 'V2',+ });++ expect(mockClient.webhookSubscriptions.update).toHaveBeenCalledWith(+ 'sub_123',+ {+ webhook_url: webhookUrl,+ enabled_events: ['composio.trigger.message', 'composio.connected_account.expired'],+ version: 'V2',+ },+ undefined+ );+ expect(mockClient.webhookSubscriptions.create).not.toHaveBeenCalled();+ });++ it('forwards request options to both calls', async () => {+ mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [] });+ mockClient.webhookSubscriptions.create.mockResolvedValue(rawSubscription);+ const signal = new AbortController().signal;++ await webhooks.subscriptions.set({ webhookUrl }, { signal });++ expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith({ limit: 1 }, { signal });+ expect(mockClient.webhookSubscriptions.create).toHaveBeenCalledWith(expect.any(Object), {+ signal,+ });+ });++ it('throws a ValidationError for invalid params before any request', async () => {+ await expect(webhooks.subscriptions.set({ webhookUrl, enabledEvents: [] })).rejects.toThrow(+ ValidationError+ );+ expect(mockClient.webhookSubscriptions.list).not.toHaveBeenCalled();+ });++ it('throws a ValidationError when the list probe is malformed', async () => {+ mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [{ id: 42 }] });++ await expect(webhooks.subscriptions.set({ webhookUrl })).rejects.toThrow(ValidationError);+ expect(mockClient.webhookSubscriptions.create).not.toHaveBeenCalled();+ expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();+ });+ });++ describe('update', () => {+ it('updates only the provided fields', async () => {+ mockClient.webhookSubscriptions.update.mockResolvedValue(rawSubscription);++ const result = await webhooks.subscriptions.update('sub_123', {+ enabledEvents: ['composio.trigger.message'],+ });++ expect(mockClient.webhookSubscriptions.update).toHaveBeenCalledWith(+ 'sub_123',+ {+ webhook_url: undefined,+ enabled_events: ['composio.trigger.message'],+ version: undefined,+ },+ undefined+ );+ expect(result).toEqual(transformedSubscription);+ });++ it('throws a ValidationError for invalid params', async () => {+ await expect(+ webhooks.subscriptions.update('sub_123', { version: 'V9' as 'V3' })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();+ });+ });++ describe('delete', () => {+ it('deletes a subscription', async () => {+ mockClient.webhookSubscriptions.delete.mockResolvedValue({ success: true });++ const result = await webhooks.subscriptions.delete('sub_123');++ expect(mockClient.webhookSubscriptions.delete).toHaveBeenCalledWith('sub_123', undefined);+ expect(result).toEqual({ success: true });+ });+ });++ describe('rotateSecret', () => {+ it('rotates the signing secret', async () => {+ mockClient.webhookSubscriptions.rotateSecret.mockResolvedValue({+ id: 'sub_123',+ secret: 'whsec_new',+ });++ const result = await webhooks.subscriptions.rotateSecret('sub_123');++ expect(mockClient.webhookSubscriptions.rotateSecret).toHaveBeenCalledWith(+ 'sub_123',+ undefined+ );+ expect(result).toEqual({ id: 'sub_123', secret: 'whsec_new' });+ });+ });++ describe('listEventTypes', () => {+ it('lists event types in camelCase', async () => {+ mockClient.webhookSubscriptions.listEventTypes.mockResolvedValue({+ items: [+ {+ event_type: 'composio.trigger.message',+ description: 'Trigger fired',+ supported_versions: ['V2', 'V3'],+ },+ ],+ });++ const result = await webhooks.subscriptions.listEventTypes();++ expect(mockClient.webhookSubscriptions.listEventTypes).toHaveBeenCalledWith(undefined);+ expect(result).toEqual({+ items: [+ {+ eventType: 'composio.trigger.message',+ description: 'Trigger fired',+ supportedVersions: ['V2', 'V3'],+ },+ ],+ });+ });+ });+ });++ describe('endpoints', () => {+ describe('list', () => {+ it('lists endpoints without a filter', async () => {+ mockClient.webhookEndpoints.list.mockResolvedValue({+ items: [{ id: 'we_abc123', toolkit_slug: 'slack', client_id: null }],+ });++ const result = await webhooks.endpoints.list();++ expect(mockClient.webhookEndpoints.list).toHaveBeenCalledWith(+ { toolkit_slug: undefined },+ undefined+ );+ expect(result).toEqual({+ items: [{ id: 'we_abc123', toolkitSlug: 'slack', clientId: null }],+ });+ });++ it('maps the toolkitSlug filter to toolkit_slug', async () => {+ mockClient.webhookEndpoints.list.mockResolvedValue({ items: [] });++ await webhooks.endpoints.list({ toolkitSlug: 'slack' });++ expect(mockClient.webhookEndpoints.list).toHaveBeenCalledWith(+ { toolkit_slug: 'slack' },+ undefined+ );+ });+ });++ describe('get', () => {+ it('retrieves an endpoint by nano id', async () => {+ mockClient.webhookEndpoints.retrieve.mockResolvedValue(rawEndpoint);++ const result = await webhooks.endpoints.get('we_abc123');++ expect(mockClient.webhookEndpoints.retrieve).toHaveBeenCalledWith('we_abc123', undefined);+ expect(result).toEqual(transformedEndpoint);+ });+ });++ describe('create', () => {+ it('creates an endpoint for a toolkit and OAuth app', async () => {+ mockClient.webhookEndpoints.create.mockResolvedValue(rawEndpoint);++ const result = await webhooks.endpoints.create({+ toolkitSlug: 'slack',+ clientId: 'client_1',+ });++ expect(mockClient.webhookEndpoints.create).toHaveBeenCalledWith(+ { toolkit_slug: 'slack', client_id: 'client_1' },+ undefined+ );+ expect(result).toEqual(transformedEndpoint);+ });++ it('throws a ValidationError when required fields are missing', async () => {+ await expect(+ webhooks.endpoints.create({ toolkitSlug: 'slack' } as {+ toolkitSlug: string;+ clientId: string;+ })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.webhookEndpoints.create).not.toHaveBeenCalled();+ });+ });++ describe('replace', () => {+ it('replaces the setup fields', async () => {+ mockClient.webhookEndpoints.replace.mockResolvedValue(rawEndpoint);++ const result = await webhooks.endpoints.replace('we_abc123', {+ data: { signing_secret: 'secret' },+ });++ expect(mockClient.webhookEndpoints.replace).toHaveBeenCalledWith(+ 'we_abc123',+ { data: { signing_secret: 'secret' } },+ undefined+ );+ expect(result).toEqual(transformedEndpoint);+ });++ it('throws a ValidationError for non-string values', async () => {+ await expect(+ webhooks.endpoints.replace('we_abc123', {+ data: { enabled: true } as unknown as Record<string, string>,+ })+ ).rejects.toThrow(ValidationError);+ expect(mockClient.webhookEndpoints.replace).not.toHaveBeenCalled();+ });+ });++ describe('update', () => {+ it('merges the setup fields', async () => {+ mockClient.webhookEndpoints.update.mockResolvedValue(rawEndpoint);++ const result = await webhooks.endpoints.update('we_abc123', {+ data: { signing_secret: 'rotated' },+ });++ expect(mockClient.webhookEndpoints.update).toHaveBeenCalledWith(+ 'we_abc123',+ { data: { signing_secret: 'rotated' } },+ undefined+ );+ expect(result).toEqual(transformedEndpoint);+ });+ });+ });+});diff --git a/ts/packages/core/test/tools/tools.test.ts b/ts/packages/core/test/tools/tools.test.tsindex 4ca7f75dd..c53315782 100644--- a/ts/packages/core/test/tools/tools.test.ts+++ b/ts/packages/core/test/tools/tools.test.ts@@ -150,7 +150,7 @@ describe('Tools', () => {{toolkit_slug: 'github',limit: 10,- search: 'test',+ query: 'test',toolkit_versions: 'latest',},undefined@@ -200,7 +200,7 @@ describe('Tools', () => {{toolkit_slug: 'todoist',limit: 10,- search: 'add task',+ query: 'add task',scopes: ['task:add'],toolkit_versions: 'latest',},@@ -1783,7 +1783,7 @@ describe('Tools', () => {expect(mockClient.tools.list).toHaveBeenCalledWith({- search: 'create issue',+ query: 'create issue',toolkit_versions: 'latest',},undefineddiff --git a/ts/packages/core/test/utils/logger.test.ts b/ts/packages/core/test/utils/logger.test.tsindex 440bb5436..f782c1a18 100644--- a/ts/packages/core/test/utils/logger.test.ts+++ b/ts/packages/core/test/utils/logger.test.ts@@ -25,3 +25,70 @@ describe('Logger credential redaction', () => {expect(output).toContain('visible');});});++describe('Logger sink and configure', () => {+ afterEach(() => vi.restoreAllMocks());++ const createSink = () => ({+ error: vi.fn(),+ warn: vi.fn(),+ info: vi.fn(),+ debug: vi.fn(),+ });++ it('writes formatted, redacted output to a custom sink instead of console', () => {+ const sink = createSink();+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ const logger = new Logger({ level: 'warn', includeTimestamp: false, sink });++ logger.warn('token', { apiKey: 'uak_test_secret' });++ expect(consoleWarn).not.toHaveBeenCalled();+ expect(sink.warn).toHaveBeenCalledTimes(1);+ const output = String(sink.warn.mock.calls[0]?.[0]);+ expect(output).not.toContain('uak_test_secret');+ expect(output).toContain('[REDACTED]');+ });++ it('configure updates the level in place', () => {+ const sink = createSink();+ const logger = new Logger({ level: 'error', includeTimestamp: false, sink });++ logger.warn('dropped');+ expect(sink.warn).not.toHaveBeenCalled();++ logger.configure({ level: 'warn' });+ expect(logger.getLevel()).toBe('warn');+ logger.warn('emitted');+ expect(sink.warn).toHaveBeenCalledWith('emitted');+ });++ it('configure swaps the sink and keeps the level when level is omitted', () => {+ const first = createSink();+ const second = createSink();+ const logger = new Logger({ level: 'debug', includeTimestamp: false, sink: first });++ logger.configure({ sink: second });+ logger.debug('hello');++ expect(logger.getLevel()).toBe('debug');+ expect(first.debug).not.toHaveBeenCalled();+ expect(second.debug).toHaveBeenCalledWith('hello');+ });++ it("'silent' suppresses every level", () => {+ const sink = createSink();+ const logger = new Logger({ level: 'debug', includeTimestamp: false, sink });++ logger.configure({ level: 'silent' });+ logger.error('e');+ logger.warn('w');+ logger.info('i');+ logger.debug('d');++ expect(sink.error).not.toHaveBeenCalled();+ expect(sink.warn).not.toHaveBeenCalled();+ expect(sink.info).not.toHaveBeenCalled();+ expect(sink.debug).not.toHaveBeenCalled();+ });+});