@composio/core 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/{CustomTool-CnJxXr07.mjs → CustomTool-BYHB7sPs.mjs} +1 -1
  2. package/dist/{CustomTool-CNJysHMK.d.mts → CustomTool-DfP4ldQl.d.mts} +1 -1
  3. package/dist/{cancellation-BQibgpRG.mjs → cancellation-ZoRh6EJQ.mjs} +55 -3
  4. package/dist/{composio-BFTtZj82.d.mts → composio-BMDH-1Qj.d.mts} +35 -15
  5. package/dist/{customTool.types-D57QrTns.d.mts → customTool.types-BoOELgJF.d.mts} +346 -23
  6. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +10 -10
  7. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +2 -2
  8. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +22 -22
  9. package/dist/docs/reference/sdk-reference/typescript/custom-toolkits.mdx +8 -8
  10. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +2 -2
  11. package/dist/docs/reference/sdk-reference/typescript/index.mdx +1 -1
  12. package/dist/docs/reference/sdk-reference/typescript/keyring.mdx +2 -2
  13. package/dist/docs/reference/sdk-reference/typescript/logs.mdx +5 -5
  14. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +15 -15
  15. package/dist/docs/reference/sdk-reference/typescript/meta.json +1 -1
  16. package/dist/docs/reference/sdk-reference/typescript/session-configs.mdx +5 -5
  17. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +10 -10
  18. package/dist/docs/reference/sdk-reference/typescript/session.mdx +56 -21
  19. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +6 -6
  20. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +22 -22
  21. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +18 -18
  22. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +25 -25
  23. package/dist/docs/reference/sdk-reference/typescript/usage.mdx +6 -6
  24. package/dist/docs/reference/sdk-reference/typescript/webhook-endpoints.mdx +14 -14
  25. package/dist/docs/reference/sdk-reference/typescript/webhook-subscriptions.mdx +13 -13
  26. package/dist/{errors-BN15NcCW.mjs → errors-Cly0vXFh.mjs} +5 -5
  27. package/dist/experimental/index.d.mts +2 -2
  28. package/dist/experimental/index.mjs +1 -1
  29. package/dist/index.d.mts +19 -11
  30. package/dist/index.mjs +693 -196
  31. package/dist/{types-q8TwAngA.d.mts → types-DHNV_T_z.d.mts} +2 -2
  32. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  33. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  34. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  35. package/dist/utils/modifiers/FileToolModifier.node.mjs +2 -2
  36. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  37. package/package.json +5 -5
  38. package/src/composio.ts +81 -67
  39. package/src/errors/ToolRouterErrors.ts +5 -5
  40. package/src/lib/toolRouterMcp.ts +2 -0
  41. package/src/lib/toolRouterParams.ts +28 -16
  42. package/src/models/ConnectedAccounts.ts +7 -16
  43. package/src/models/ToolRouter.ts +8 -1
  44. package/src/models/ToolRouterSession.ts +17 -0
  45. package/src/models/Tools.ts +1 -4
  46. package/src/models/Triggers.ts +14 -7
  47. package/src/services/internal/InternalService.ts +3 -4
  48. package/src/services/pusher/Pusher.ts +170 -92
  49. package/src/types/connectedAccountAuthStates.types.ts +2 -1
  50. package/src/types/pusher.types.ts +2 -0
  51. package/src/types/requestOptions.types.ts +1 -10
  52. package/src/types/toolRouter.types.ts +104 -18
  53. package/src/utils/jsonSchema.ts +76 -4
  54. package/src/utils/sdk.ts +172 -11
  55. package/src/utils/session.ts +25 -47
  56. package/src/utils/toolkitDeprecation.ts +271 -0
  57. package/src/utils/transformers/connectedAccounts.ts +9 -20
  58. package/src/utils/transformers/mcp.ts +3 -10
  59. package/src/utils/userCallback.ts +41 -0
package/dist/index.mjs CHANGED
@@ -1,21 +1,21 @@
1
1
  import { c as DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID, d as USER_DATA_FILE_NAME, f as constants_exports, i as logger, l as IS_DEVELOPMENT_OR_CI, m as getEnvsWithPrefix, n as SsrfErrorCodes, o as COMPOSIO_DIR, p as getEnvVariable, r as ComposioError, s as DEFAULT_BASE_URL, t as ComposioBlockedInternalUrlError, u as TEMP_FILES_DIRECTORY_NAME } from "./SsrfErrors-DiQldIdC.mjs";
2
- import { $ as ComposioAuthConfigNotFoundError, A as ComposioInvalidModifierError, B as ConnectionRequestFailedError, C as ValidationError, D as ToolkitErrorCodes, E as ComposioToolkitNotFoundError, F as ComposioToolNotFoundError, G as ComposioConnectedAccountRevocationNotSupportedError, H as ComposioAclOnlyForSharedError, I as ComposioToolVersionRequiredError, J as ComposioMultipleConnectedAccountsError, K as ComposioFailedToCreateConnectedAccountLink, L as ToolErrorCodes, M as ComposioProviderNotDefinedError, N as ComposioToolExecutionError, O as ComposioGlobalExecuteToolFnNotSetError, P as ComposioToolFetchError, Q as AuthConfigErrorCodes, R as handleToolExecutionError, S as JsonSchemaToZodError, T as ComposioToolkitFetchError, U as ComposioConnectedAccountNotFoundError, V as ConnectionRequestTimeoutError, W as ComposioConnectedAccountNotRevokableError, X as ComposioSharedConnectionNotAccessibleError, Y as ComposioSharedAccessDeniedError, Z as ConnectedAccountErrorCodes, _ as ComposioRequestCancelledError, a as RemoteFileDownloadError, b as isRequestAbortError, c as ComposioFailedToGetSDKRealtimeCredentialsError, d as ComposioTriggerTypeNotFoundError, f as ComposioWebhookPayloadError, g as ComposioNoAPIKeyError, h as ComposioAPIKeyKindError, i as ToolRouterErrorCodes, j as ComposioInvalidToolArgumentsError, k as ComposioInvalidExecuteFunctionError, l as ComposioFailedToSubscribeToPusherChannelError, m as TriggerErrorCodes, n as ComposioSessionConfigConflictError, o as RemoteFileErrorCodes, p as ComposioWebhookSignatureVerificationError, q as ComposioLegacyConnectedAccountsEndpointRetiredError, r as ComposioToolInputRequiredError, s as ComposioFailedToCreatePusherClientError, t as ComposioMCPDestinationError, u as ComposioFailedToUnsubscribeFromPusherChannelError, v as ComposioScopeConfigError, w as ValidationErrorCodes, x as JsonSchemaRefResolutionError, y as SDKErrorCodes, z as ConnectionRequestErrorCodes } from "./errors-BN15NcCW.mjs";
2
+ import { $ as ComposioAuthConfigNotFoundError, A as ComposioInvalidModifierError, B as ConnectionRequestFailedError, C as ValidationError, D as ToolkitErrorCodes, E as ComposioToolkitNotFoundError, F as ComposioToolNotFoundError, G as ComposioConnectedAccountRevocationNotSupportedError, H as ComposioAclOnlyForSharedError, I as ComposioToolVersionRequiredError, J as ComposioMultipleConnectedAccountsError, K as ComposioFailedToCreateConnectedAccountLink, L as ToolErrorCodes, M as ComposioProviderNotDefinedError, N as ComposioToolExecutionError, O as ComposioGlobalExecuteToolFnNotSetError, P as ComposioToolFetchError, Q as AuthConfigErrorCodes, R as handleToolExecutionError, S as JsonSchemaToZodError, T as ComposioToolkitFetchError, U as ComposioConnectedAccountNotFoundError, V as ConnectionRequestTimeoutError, W as ComposioConnectedAccountNotRevokableError, X as ComposioSharedConnectionNotAccessibleError, Y as ComposioSharedAccessDeniedError, Z as ConnectedAccountErrorCodes, _ as ComposioRequestCancelledError, a as RemoteFileDownloadError, b as isRequestAbortError, c as ComposioFailedToGetSDKRealtimeCredentialsError, d as ComposioTriggerTypeNotFoundError, f as ComposioWebhookPayloadError, g as ComposioNoAPIKeyError, h as ComposioAPIKeyKindError, i as ToolRouterErrorCodes, j as ComposioInvalidToolArgumentsError, k as ComposioInvalidExecuteFunctionError, l as ComposioFailedToSubscribeToPusherChannelError, m as TriggerErrorCodes, n as ComposioSessionConfigConflictError, o as RemoteFileErrorCodes, p as ComposioWebhookSignatureVerificationError, q as ComposioLegacyConnectedAccountsEndpointRetiredError, r as ComposioToolInputRequiredError, s as ComposioFailedToCreatePusherClientError, t as ComposioMCPDestinationError, u as ComposioFailedToUnsubscribeFromPusherChannelError, v as ComposioScopeConfigError, w as ValidationErrorCodes, x as JsonSchemaRefResolutionError, y as SDKErrorCodes, z as ConnectionRequestErrorCodes } from "./errors-Cly0vXFh.mjs";
3
3
  import { a as ComposioSensitiveFilePathBlockedError, i as ComposioFileUploadPathNotAllowedError, n as ComposioFileUploadAbortedError, o as FileModifierErrorCodes, r as ComposioFileUploadError, t as ComposioFileNotFoundError } from "./FileModifierErrors-CdGSABoq.mjs";
4
4
  import { n as dropEmptyFileUploads, o as isPlainObject, s as schemaHasFileUploadable } from "./FileToolModifier.utils.neutral-DWFpnsj2.mjs";
5
- import { a as jsonSchemaToZodSchema, c as toStrictJsonSchema, i as ensureObjectTypeOnProperties, n as deduplicateJsonSchemaRequiredArrays, o as omitNullToolArguments, r as dereferenceJsonSchema, s as removeNonRequiredProperties, t as withCancellation } from "./cancellation-BQibgpRG.mjs";
5
+ import { a as jsonSchemaToZodSchema, c as toStrictJsonSchema, i as ensureObjectTypeOnProperties, n as deduplicateJsonSchemaRequiredArrays, o as omitNullToolArguments, r as dereferenceJsonSchema, s as removeNonRequiredProperties, t as withCancellation } from "./cancellation-ZoRh6EJQ.mjs";
6
6
  import { t as telemetry } from "./Telemetry-41JkqpZ7.mjs";
7
7
  import { a as readResponseBodyWithLimit, i as MAX_URL_UPLOAD_SIZE_BYTES, l as getRandomShortId, n as assertSafeFileUploadPath, o as arrayBufferToBase64, r as isBlockedSensitiveFileUploadPath, t as BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS } from "./sensitiveFileUploadPaths-BlLp-Yo2.mjs";
8
- import { a as createCustomToolkit, c as getPreloadedCustomToolSlugs, d as CreateCustomToolBaseSchema, f as CreateCustomToolkitBaseSchema, i as createCustomTool, l as serializeCustomToolkits, n as buildCustomToolsMap, o as findCustomToolMapEntryByFinalSlug, p as CustomToolSlugSchema, r as buildCustomToolsMapFromResponse, s as findCustomToolMapEntryByToolkitAndOriginalSlug, t as assertNoCustomToolSlugsInPreload, u as serializeCustomTools } from "./CustomTool-CnJxXr07.mjs";
9
- import ComposioClient, { APIError, BadRequestError, ConflictError, VERSION } from "@composio/client";
8
+ import { a as createCustomToolkit, c as getPreloadedCustomToolSlugs, d as CreateCustomToolBaseSchema, f as CreateCustomToolkitBaseSchema, i as createCustomTool, l as serializeCustomToolkits, n as buildCustomToolsMap, o as findCustomToolMapEntryByFinalSlug, p as CustomToolSlugSchema, r as buildCustomToolsMapFromResponse, s as findCustomToolMapEntryByToolkitAndOriginalSlug, t as assertNoCustomToolSlugsInPreload, u as serializeCustomTools } from "./CustomTool-BYHB7sPs.mjs";
9
+ import ComposioClient, { APIError, Auth, BadRequestError, ConflictError, createFetchTransport } from "@composio/client";
10
10
  import { FileToolModifier } from "#file_tool_modifier";
11
11
  import z, { z as z$1 } from "zod/v3";
12
12
  import { CONFIG_DEFAULTS } from "#config_defaults";
13
13
  import { platform } from "#platform";
14
14
  import semver from "semver";
15
15
  import { Files } from "#files";
16
- import identity from "#client_identity" with { type: "json" };
17
- import { z as z$2 } from "zod";
16
+ import manifest from "#client_identity" with { type: "json" };
18
17
  import { ssrfSafeFetch, ssrfSafeFetchWhereSupported } from "#ssrf_guard";
18
+ import { z as z$2 } from "zod";
19
19
 
20
20
  //#region src/types/authConfigs.types.ts
21
21
  const AuthConfigTypes = {
@@ -332,7 +332,7 @@ const S2SOauth2ConnectionDataSchema = z$1.discriminatedUnion("status", [
332
332
  }).catchall(z$1.unknown())
333
333
  ]);
334
334
  const CustomS2SOauth2ConnectionDataSchema = BaseSchemeRaw.extend({
335
- access_token: z$1.string().optional(),
335
+ access_token: z$1.string(),
336
336
  id_token: z$1.string().optional(),
337
337
  token_type: z$1.string().optional(),
338
338
  refresh_token: z$1.string().nullish().optional(),
@@ -3053,7 +3053,6 @@ const ConnectedAccountCompleteAuthResponseSchema = z$1.object({
3053
3053
  * @private
3054
3054
  */
3055
3055
  function transformConnectedAccountResponse(response) {
3056
- const responseWithLabels = response;
3057
3056
  const parseState = (state) => {
3058
3057
  try {
3059
3058
  return state ? ConnectionDataSchema.parse(state) : void 0;
@@ -3071,8 +3070,8 @@ function transformConnectedAccountResponse(response) {
3071
3070
  isComposioManaged: response.auth_config.is_composio_managed,
3072
3071
  isDisabled: response.auth_config.is_disabled
3073
3072
  },
3074
- wordId: responseWithLabels.word_id ?? null,
3075
- alias: responseWithLabels.alias ?? null,
3073
+ wordId: response.word_id ?? null,
3074
+ alias: response.alias ?? null,
3076
3075
  data: response.data ?? void 0,
3077
3076
  state: parseState(response.state),
3078
3077
  status: response.status,
@@ -3081,12 +3080,12 @@ function transformConnectedAccountResponse(response) {
3081
3080
  createdAt: response.created_at,
3082
3081
  updatedAt: response.updated_at,
3083
3082
  testRequestEndpoint: response.test_request_endpoint,
3084
- experimental: responseWithLabels.experimental ? {
3085
- accountType: responseWithLabels.experimental.account_type,
3086
- aclConfigForShared: responseWithLabels.experimental.acl_config_for_shared ? {
3087
- allowAllUsers: responseWithLabels.experimental.acl_config_for_shared.allow_all_users,
3088
- allowedUserIds: responseWithLabels.experimental.acl_config_for_shared.allowed_user_ids,
3089
- notAllowedUserIds: responseWithLabels.experimental.acl_config_for_shared.not_allowed_user_ids
3083
+ experimental: response.experimental ? {
3084
+ accountType: response.experimental.account_type,
3085
+ aclConfigForShared: response.experimental.acl_config_for_shared ? {
3086
+ allowAllUsers: response.experimental.acl_config_for_shared.allow_all_users,
3087
+ allowedUserIds: response.experimental.acl_config_for_shared.allowed_user_ids,
3088
+ notAllowedUserIds: response.experimental.acl_config_for_shared.not_allowed_user_ids
3090
3089
  } : void 0
3091
3090
  } : void 0
3092
3091
  }));
@@ -5503,10 +5502,7 @@ var InternalService = class {
5503
5502
  * @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials
5504
5503
  */
5505
5504
  async getSDKRealtimeCredentials() {
5506
- const response = await this.client.request({
5507
- method: "get",
5508
- path: SDK_REALTIME_CREDENTIALS_ENDPOINT
5509
- });
5505
+ const response = await this.client.get(SDK_REALTIME_CREDENTIALS_ENDPOINT);
5510
5506
  const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
5511
5507
  pusherKey: response.pusher_key,
5512
5508
  projectId: response.project_id,
@@ -5518,6 +5514,47 @@ var InternalService = class {
5518
5514
  }
5519
5515
  };
5520
5516
 
5517
+ //#endregion
5518
+ //#region src/utils/userCallback.ts
5519
+ /**
5520
+ * Describes a thrown or rejected value for a log line without ever throwing.
5521
+ *
5522
+ * The logger serializes object arguments with `JSON.stringify`, which turns an `Error` into `{}`
5523
+ * and throws on a circular value, so callers log this string instead of the raw value.
5524
+ * `JSON.stringify` and `String()` can both throw (a circular value, an object without a
5525
+ * prototype), so each is tried in turn.
5526
+ */
5527
+ function describeThrown(value) {
5528
+ try {
5529
+ if (value instanceof Error) return value.message;
5530
+ if (typeof value === "object" && value !== null) return JSON.stringify(value) ?? String(value);
5531
+ return String(value);
5532
+ } catch {
5533
+ try {
5534
+ return String(value);
5535
+ } catch {
5536
+ return "[unprintable value]";
5537
+ }
5538
+ }
5539
+ }
5540
+ /**
5541
+ * Calls a user-supplied event callback so that neither a synchronous throw nor a rejected promise
5542
+ * escapes into the event emitter that invoked it. Failures are logged after `label`.
5543
+ *
5544
+ * pusher-js does not catch listener exceptions, and nothing awaits the promise an `async`
5545
+ * listener returns, so an escaped failure would end a Node process.
5546
+ */
5547
+ function invokeUserCallback(label, callback) {
5548
+ const logFailure = (error) => {
5549
+ logger.error(label, describeThrown(error));
5550
+ };
5551
+ try {
5552
+ Promise.resolve(callback()).catch(logFailure);
5553
+ } catch (error) {
5554
+ logFailure(error);
5555
+ }
5556
+ }
5557
+
5521
5558
  //#endregion
5522
5559
  //#region src/utils/sdk.ts
5523
5560
  /**
@@ -5533,10 +5570,25 @@ const USER_API_KEY_PREFIX = "uak_";
5533
5570
  * when project-key auth is disabled.
5534
5571
  */
5535
5572
  const PROJECT_API_KEY_HEADER = "x-api-key";
5573
+ /** Header that carries the organization API key (`oak_...`). */
5574
+ const ORG_API_KEY_HEADER = "x-org-api-key";
5536
5575
  /** Header carrying the organization nano ID that scopes user-key requests. */
5537
5576
  const ORG_ID_HEADER = "x-org-id";
5538
5577
  /** Header carrying the project nano ID that scopes user-key requests. */
5539
5578
  const PROJECT_ID_HEADER = "x-project-id";
5579
+ /**
5580
+ * Header names the SDK owns: the API client sends a credential from its
5581
+ * `auth` and the scope from its `scope`, and refuses these names in its
5582
+ * `defaultHeaders`. The SDK folds caller-supplied entries into its own
5583
+ * credential and scope options instead of forwarding them.
5584
+ */
5585
+ const SDK_OWNED_HEADERS = [
5586
+ PROJECT_API_KEY_HEADER,
5587
+ USER_API_KEY_HEADER,
5588
+ ORG_API_KEY_HEADER,
5589
+ ORG_ID_HEADER,
5590
+ PROJECT_ID_HEADER
5591
+ ];
5540
5592
  const userDataPath = () => {
5541
5593
  try {
5542
5594
  const homeDir = platform.homedir();
@@ -5612,8 +5664,9 @@ const findHeader = (headers, name) => {
5612
5664
  * non-empty value. Matches the header name case-insensitively and ignores
5613
5665
  * every other header.
5614
5666
  */
5615
- const getUserApiKeyHeader = (headers) => {
5616
- const header = findHeader(headers, USER_API_KEY_HEADER);
5667
+ const getUserApiKeyHeader = (headers) => getCredentialHeader(headers, USER_API_KEY_HEADER);
5668
+ const getCredentialHeader = (headers, name) => {
5669
+ const header = findHeader(headers, name);
5617
5670
  return header && typeof header.value === "string" && header.value.length > 0 ? header : void 0;
5618
5671
  };
5619
5672
  /**
@@ -5622,14 +5675,16 @@ const getUserApiKeyHeader = (headers) => {
5622
5675
  * headers wins: the client treats a caller-placed credential header as the
5623
5676
  * credential and suppresses the configured keys. Otherwise the project key
5624
5677
  * travels as `x-api-key`, otherwise the resolved user API key as
5625
- * `x-user-api-key`. Empty when no credential is held. The environment is
5626
- * never consulted here.
5678
+ * `x-user-api-key`, otherwise the organization API key as `x-org-api-key`
5679
+ * (the order {@link toClientAuth} picks them in). Empty when no credential is
5680
+ * held. The environment is never consulted here.
5627
5681
  */
5628
5682
  const resolveCredentialHeaders = (input) => {
5629
5683
  const userApiKeyHeader = getUserApiKeyHeader(input.defaultHeaders);
5630
5684
  if (userApiKeyHeader) return { [USER_API_KEY_HEADER]: userApiKeyHeader.value };
5631
5685
  if (hasValue(input.apiKey)) return { [PROJECT_API_KEY_HEADER]: input.apiKey };
5632
5686
  if (hasValue(input.userApiKey)) return { [USER_API_KEY_HEADER]: input.userApiKey };
5687
+ if (hasValue(input.orgApiKey)) return { [ORG_API_KEY_HEADER]: input.orgApiKey };
5633
5688
  return {};
5634
5689
  };
5635
5690
  const resolveScopeValue = (option, headers, headerName, optionName) => {
@@ -5670,11 +5725,21 @@ function resolveSDKScope(options) {
5670
5725
  projectId
5671
5726
  };
5672
5727
  }
5673
- /** The `x-org-id` / `x-project-id` headers for a resolved scope. */
5674
- const getScopeHeaders = (scope) => scope.orgId && scope.projectId ? {
5675
- [ORG_ID_HEADER]: scope.orgId,
5676
- [PROJECT_ID_HEADER]: scope.projectId
5677
- } : {};
5728
+ /**
5729
+ * The API client `scope` for a resolved SDK scope: the organization and
5730
+ * project nano IDs the client sends as `x-org-id` / `x-project-id`, or
5731
+ * `undefined` when the instance is unscoped.
5732
+ */
5733
+ const toClientScope = (scope) => scope.orgId && scope.projectId ? {
5734
+ organizationId: scope.orgId,
5735
+ projectId: scope.projectId
5736
+ } : void 0;
5737
+ /**
5738
+ * `headers` without the credential and scope entries the SDK owns (matched
5739
+ * case-insensitively). Those travel through the API client's `auth` and
5740
+ * `scope`, which refuse the same names in `defaultHeaders`.
5741
+ */
5742
+ const withoutSDKOwnedHeaders = (headers) => headers === void 0 ? void 0 : Object.fromEntries(Object.entries(headers).filter(([name]) => !SDK_OWNED_HEADERS.includes(name.toLowerCase())));
5678
5743
  const hasValue = (value) => typeof value === "string" && value.length > 0;
5679
5744
  /**
5680
5745
  * Mirrors how the API client resolves `userApiKey` / `orgApiKey`: an explicit
@@ -5692,11 +5757,96 @@ const resolveAlternateCredential = (explicit, envName) => {
5692
5757
  */
5693
5758
  const resolveUserApiKey = (userApiKey) => resolveAlternateCredential(userApiKey, "COMPOSIO_USER_API_KEY");
5694
5759
  /**
5760
+ * The organization API key the instance holds: the `orgApiKey` option when it
5761
+ * was passed (including `null`, which disables the fallback), otherwise
5762
+ * `COMPOSIO_ORG_API_KEY`.
5763
+ */
5764
+ const resolveOrgApiKey = (orgApiKey) => resolveAlternateCredential(orgApiKey, "COMPOSIO_ORG_API_KEY");
5765
+ /**
5695
5766
  * Whether the instance holds a credential other than the project key: a user
5696
5767
  * or organization API key (explicit or environment-resolved, as the API client
5697
- * will see it), or a user API key placed in the default headers.
5698
- */
5699
- const hasAlternateCredential = (options) => resolveUserApiKey(options.userApiKey) !== void 0 || resolveAlternateCredential(options.orgApiKey, "COMPOSIO_ORG_API_KEY") !== void 0 || getUserApiKeyHeader(options.defaultHeaders) !== void 0;
5768
+ * will see it), or a user or organization API key placed in the default
5769
+ * headers, which {@link resolveSDKCredentials} folds in.
5770
+ */
5771
+ const hasAlternateCredential = (options) => resolveUserApiKey(options.userApiKey) !== void 0 || resolveOrgApiKey(options.orgApiKey) !== void 0 || getUserApiKeyHeader(options.defaultHeaders) !== void 0 || getCredentialHeader(options.defaultHeaders, "x-org-api-key") !== void 0;
5772
+ const CREDENTIAL_HEADERS = [
5773
+ PROJECT_API_KEY_HEADER,
5774
+ USER_API_KEY_HEADER,
5775
+ ORG_API_KEY_HEADER
5776
+ ];
5777
+ /**
5778
+ * Resolves the credentials of an SDK instance.
5779
+ *
5780
+ * The user and organization keys fall back to `COMPOSIO_USER_API_KEY` and
5781
+ * `COMPOSIO_ORG_API_KEY` when their option is omitted. A non-empty credential
5782
+ * header in `defaultHeaders` (any letter case) is folded in as the credential
5783
+ * it names, and it is the credential the instance sends, as it was when the
5784
+ * header itself went on the wire: an `x-user-api-key` or `x-org-api-key` entry
5785
+ * disables the project key and takes the place of the configured user or
5786
+ * organization key, and an `x-api-key` entry takes the place of the project
5787
+ * key. At most one credential header may be set: the API rejects a request
5788
+ * that carries two.
5789
+ */
5790
+ function resolveSDKCredentials(input) {
5791
+ const headers = CREDENTIAL_HEADERS.flatMap((name) => {
5792
+ const header = findHeader(input.defaultHeaders, name);
5793
+ return header && hasValue(header.value) ? [{
5794
+ ...header,
5795
+ canonical: name
5796
+ }] : [];
5797
+ });
5798
+ if (headers.length > 1) throw new ComposioError("`defaultHeaders` carries more than one credential header", {
5799
+ cause: `The API accepts exactly one credential per request, and \`defaultHeaders\` sets ${headers.map((header) => `\`${header.name}\``).join(" and ")}`,
5800
+ possibleFixes: ["Pass credentials through `apiKey`, `userApiKey` and `orgApiKey` instead of default headers", "Keep at most one of `x-api-key`, `x-user-api-key` and `x-org-api-key` in `defaultHeaders`"]
5801
+ });
5802
+ const userApiKey = resolveUserApiKey(input.userApiKey) ?? null;
5803
+ const orgApiKey = resolveOrgApiKey(input.orgApiKey) ?? null;
5804
+ const [header] = headers;
5805
+ switch (header?.canonical) {
5806
+ case USER_API_KEY_HEADER: return {
5807
+ apiKey: null,
5808
+ userApiKey: header.value,
5809
+ orgApiKey
5810
+ };
5811
+ case ORG_API_KEY_HEADER: return {
5812
+ apiKey: null,
5813
+ userApiKey: null,
5814
+ orgApiKey: header.value
5815
+ };
5816
+ case PROJECT_API_KEY_HEADER: return {
5817
+ apiKey: header.value,
5818
+ userApiKey,
5819
+ orgApiKey
5820
+ };
5821
+ default: return {
5822
+ apiKey: input.apiKey,
5823
+ userApiKey,
5824
+ orgApiKey
5825
+ };
5826
+ }
5827
+ }
5828
+ /**
5829
+ * The API client `auth` for the credentials of an SDK instance.
5830
+ *
5831
+ * - A project key alone authenticates every request with it.
5832
+ * - A project key with a user and/or organization key selects one per
5833
+ * operation: the project key wherever the operation accepts it, otherwise
5834
+ * the first declared scheme a key is held for.
5835
+ * - Without a project key, the user key authenticates every request (sessions
5836
+ * included, whose operations declare no scheme), and the organization key
5837
+ * does when it is the only one held.
5838
+ */
5839
+ const toClientAuth = (credentials) => {
5840
+ const { apiKey, userApiKey, orgApiKey } = credentials;
5841
+ if (apiKey !== null) return userApiKey === null && orgApiKey === null ? Auth.project(apiKey) : Auth.auto({
5842
+ project: apiKey,
5843
+ user: userApiKey ?? void 0,
5844
+ organization: orgApiKey ?? void 0
5845
+ });
5846
+ if (userApiKey !== null) return Auth.user(userApiKey);
5847
+ if (orgApiKey !== null) return Auth.organization(orgApiKey);
5848
+ throw new ComposioNoAPIKeyError();
5849
+ };
5700
5850
  /**
5701
5851
  * Resolves the base URL and project API key the SDK will use.
5702
5852
  *
@@ -5708,7 +5858,8 @@ const hasAlternateCredential = (options) => resolveUserApiKey(options.userApiKey
5708
5858
  * `api_key` is read, and the resolver only succeeds when the instance holds
5709
5859
  * another credential: a `userApiKey` or `orgApiKey` (explicit, or resolved
5710
5860
  * from `COMPOSIO_USER_API_KEY` / `COMPOSIO_ORG_API_KEY` the way the API
5711
- * client does), or a non-empty `x-user-api-key` entry in `defaultHeaders`.
5861
+ * client does), or a non-empty `x-user-api-key` or `x-org-api-key` entry in
5862
+ * `defaultHeaders`.
5712
5863
  * An `x-api-key` entry in `defaultHeaders` (any letter case) is rejected in
5713
5864
  * that mode: the project credential is only ever set from `apiKey`.
5714
5865
  *
@@ -5804,60 +5955,97 @@ function getToolkitVersionsFromEnv(defaultVersions) {
5804
5955
 
5805
5956
  //#endregion
5806
5957
  //#region src/services/pusher/Pusher.ts
5958
+ /**
5959
+ * Owns the realtime connection that delivers trigger events.
5960
+ *
5961
+ * Each subscription period gets its own pusher-js client, which `unsubscribe()` disconnects.
5962
+ * Reusing one client across periods is unsafe: pusher-js keeps a channel, its bound handlers and
5963
+ * its cancellation flag through `disconnect()` and resubscribes every kept channel on the next
5964
+ * `connect()`, and a channel-auth reply requested on the old socket can arrive after a reconnect
5965
+ * and be sent on the new one.
5966
+ */
5807
5967
  var PusherService = class {
5808
- clientId;
5809
- pusherKey;
5810
- pusherCluster;
5811
- pusherChannel;
5812
5968
  pusherBaseURL;
5813
5969
  authHeaders;
5814
- pusherClient;
5815
5970
  composioClient;
5971
+ attempt;
5972
+ connection;
5816
5973
  constructor(client, options = {}) {
5817
5974
  this.composioClient = client;
5818
5975
  this.pusherBaseURL = client.baseURL;
5819
5976
  this.authHeaders = resolveCredentialHeaders({
5820
- apiKey: client.apiKey,
5821
- userApiKey: client.userApiKey,
5977
+ apiKey: options.apiKey,
5978
+ userApiKey: options.userApiKey,
5979
+ orgApiKey: options.orgApiKey,
5822
5980
  defaultHeaders: options.defaultHeaders
5823
5981
  });
5824
5982
  telemetry.instrument(this, "PusherService");
5825
5983
  }
5826
5984
  /**
5827
- * Creates a Pusher client
5828
- *
5829
- * This method is called when the Pusher client is first used.
5830
- * It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.
5985
+ * Returns the connection attempt of the current subscription period, starting one if needed.
5986
+ * A failed attempt is forgotten, so the next `subscribe()` retries.
5831
5987
  */
5832
- async getPusherClient() {
5833
- if (!this.pusherClient) {
5834
- const internalService = new InternalService(this.composioClient);
5835
- let sdkRealtimeCredentials;
5836
- try {
5837
- sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
5838
- } catch (error) {
5839
- throw new ComposioFailedToGetSDKRealtimeCredentialsError("Failed to get SDK realtime credentials", { cause: error });
5840
- }
5841
- this.clientId = sdkRealtimeCredentials.projectId;
5842
- this.pusherKey = sdkRealtimeCredentials.pusherKey;
5843
- this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
5844
- this.pusherChannel = `private-${this.clientId}_triggers`;
5845
- logger.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`);
5846
- try {
5847
- const { default: Pusher } = await import("pusher-js");
5848
- this.pusherClient = new Pusher(this.pusherKey, {
5849
- cluster: this.pusherCluster,
5850
- channelAuthorization: {
5851
- endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
5852
- headers: { ...this.authHeaders },
5853
- transport: "ajax"
5854
- }
5855
- });
5856
- } catch (error) {
5857
- throw new ComposioFailedToCreatePusherClientError("Failed to create Pusher client", { cause: error });
5858
- }
5988
+ connect() {
5989
+ if (this.attempt) return this.attempt;
5990
+ const controller = new AbortController();
5991
+ const ready = this.openConnection(controller.signal);
5992
+ const attempt = {
5993
+ controller,
5994
+ ready
5995
+ };
5996
+ this.attempt = attempt;
5997
+ ready.catch(() => {
5998
+ if (this.attempt === attempt) this.attempt = void 0;
5999
+ });
6000
+ return attempt;
6001
+ }
6002
+ /**
6003
+ * Fetches the SDK realtime credentials from the Apollo API, creates a Pusher client and
6004
+ * subscribes it to the triggers channel.
6005
+ */
6006
+ async openConnection(signal) {
6007
+ const internalService = new InternalService(this.composioClient);
6008
+ let sdkRealtimeCredentials;
6009
+ try {
6010
+ sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
6011
+ } catch (error) {
6012
+ throw new ComposioFailedToGetSDKRealtimeCredentialsError("Failed to get SDK realtime credentials", { cause: error });
6013
+ }
6014
+ const { projectId, pusherKey, pusherCluster } = sdkRealtimeCredentials;
6015
+ const channelName = `private-${projectId}_triggers`;
6016
+ let Pusher;
6017
+ try {
6018
+ ({default: Pusher} = await import("pusher-js"));
6019
+ } catch (error) {
6020
+ throw new ComposioFailedToCreatePusherClientError("Failed to create Pusher client", { cause: error });
5859
6021
  }
5860
- return this.pusherClient;
6022
+ if (signal.aborted) throw new Error("Connection attempt cancelled by unsubscribe()");
6023
+ logger.debug(`[PusherService] Creating Pusher client for client ID: ${projectId} in cluster ${pusherCluster}`);
6024
+ let client;
6025
+ try {
6026
+ client = new Pusher(pusherKey, {
6027
+ cluster: pusherCluster,
6028
+ channelAuthorization: {
6029
+ endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
6030
+ headers: { ...this.authHeaders },
6031
+ transport: "ajax"
6032
+ }
6033
+ });
6034
+ } catch (error) {
6035
+ throw new ComposioFailedToCreatePusherClientError("Failed to create Pusher client", { cause: error });
6036
+ }
6037
+ logger.debug(`[PusherService] Subscribing to channel: ${channelName}`);
6038
+ try {
6039
+ this.connection = {
6040
+ client,
6041
+ channel: client.subscribe(channelName),
6042
+ channelName
6043
+ };
6044
+ } catch (error) {
6045
+ client.disconnect();
6046
+ throw error;
6047
+ }
6048
+ return this.connection;
5861
6049
  }
5862
6050
  /**
5863
6051
  * Binds a chunked event to a Pusher client
@@ -5905,42 +6093,42 @@ var PusherService = class {
5905
6093
  /**
5906
6094
  * Subscribes to pusher to receive events from the server
5907
6095
  *
5908
- * This method is used to subscribe to a Pusher channel.
5909
- * It will create a Pusher client if it doesn't exist.
6096
+ * The first call of a subscription period creates the Pusher client; concurrent calls share
6097
+ * it. A call still waiting for the client when `unsubscribe()` runs resolves without
6098
+ * subscribing.
5910
6099
  *
5911
- * @param channelName - The name of the Pusher channel to subscribe to
5912
- * @param event - The event to subscribe to
5913
6100
  * @param fn - The function to call when the event is received
5914
6101
  * @param onSubscriptionError - Optional callback invoked with the raw payload when the
5915
6102
  * Pusher subscription fails (for example on auth or permission rejection). Errors thrown
5916
6103
  * from — or promises rejected by — this callback are contained and logged, never rethrown.
5917
6104
  */
5918
6105
  async subscribe(fn, onSubscriptionError) {
6106
+ const attempt = this.connect();
6107
+ let connection;
5919
6108
  try {
5920
- logger.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
5921
- const channel = await (await this.getPusherClient()).subscribe(this.pusherChannel);
5922
- const logCallbackFailure = (callbackError) => {
5923
- const errorMessage = callbackError instanceof Error ? callbackError.message : String(callbackError);
5924
- logger.error("❌ Error in subscription error callback:", errorMessage);
5925
- };
6109
+ connection = await attempt.ready;
6110
+ } catch (error) {
6111
+ if (attempt.controller.signal.aborted) {
6112
+ logger.debug("[PusherService] Subscribe cancelled by unsubscribe() before it connected");
6113
+ return;
6114
+ }
6115
+ throw new ComposioFailedToSubscribeToPusherChannelError("Failed to subscribe to Pusher channel", { cause: error });
6116
+ }
6117
+ if (attempt.controller.signal.aborted) {
6118
+ logger.debug("[PusherService] Subscribe cancelled by unsubscribe() before it connected");
6119
+ return;
6120
+ }
6121
+ try {
6122
+ const { channel } = connection;
5926
6123
  channel.bind("pusher:subscription_error", (data) => {
5927
6124
  logger.error("Trigger subscription error:", data);
5928
- try {
5929
- Promise.resolve(onSubscriptionError?.(data)).catch(logCallbackFailure);
5930
- } catch (callbackError) {
5931
- logCallbackFailure(callbackError);
5932
- }
6125
+ invokeUserCallback("❌ Error in subscription error callback:", () => onSubscriptionError?.(data));
5933
6126
  });
5934
6127
  channel.bind("pusher:subscription_succeeded", () => {
5935
6128
  logger.info(`✅ Subscribed to triggers. You should start receiving events now.`);
5936
6129
  });
5937
6130
  const safeCallback = (data) => {
5938
- try {
5939
- fn(data);
5940
- } catch (error) {
5941
- const errorMessage = error instanceof Error ? error.message : String(error);
5942
- logger.error("❌ Error in trigger callback:", errorMessage);
5943
- }
6131
+ invokeUserCallback("❌ Error in trigger callback:", () => fn(data));
5944
6132
  };
5945
6133
  this.bindWithChunking(channel, "trigger_to_client", safeCallback);
5946
6134
  } catch (error) {
@@ -5948,21 +6136,31 @@ var PusherService = class {
5948
6136
  }
5949
6137
  }
5950
6138
  /**
5951
- * Unsubscribes from a Pusher channel
6139
+ * Unsubscribes from the triggers channel and closes the connection
5952
6140
  *
5953
- * This method is used to unsubscribe from a Pusher channel.
5954
- * It will create a Pusher client if it doesn't exist.
5955
- *
5956
- * @param channelName - The name of the Pusher channel to unsubscribe from
6141
+ * This ends the subscription period: setup still in flight is cancelled, the handlers bound by
6142
+ * every `subscribe()` call are removed, and the Pusher client is disconnected. Without a prior
6143
+ * `subscribe()` this does nothing; it never creates a client or fetches credentials.
5957
6144
  */
5958
6145
  async unsubscribe() {
6146
+ const { attempt, connection } = this;
6147
+ this.attempt = void 0;
6148
+ this.connection = void 0;
6149
+ attempt?.controller.abort();
6150
+ if (!connection) {
6151
+ logger.debug("[PusherService] No open connection to unsubscribe from");
6152
+ return;
6153
+ }
6154
+ logger.debug(`[PusherService] Unsubscribing from channel: ${connection.channelName}`);
5959
6155
  try {
5960
- logger.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
5961
- await (await this.getPusherClient()).unsubscribe(this.pusherChannel);
5962
- logger.info(`✅ Unsubscribed from triggers.`);
6156
+ connection.channel.unbind_all();
6157
+ connection.client.unsubscribe(connection.channelName);
5963
6158
  } catch (error) {
5964
6159
  throw new ComposioFailedToSubscribeToPusherChannelError("Failed to unsubscribe from Pusher channel", { cause: error });
6160
+ } finally {
6161
+ connection.client.disconnect();
5965
6162
  }
6163
+ logger.info(`✅ Unsubscribed from triggers.`);
5966
6164
  }
5967
6165
  };
5968
6166
 
@@ -6136,7 +6334,12 @@ var Triggers = class {
6136
6334
  toolkitVersions;
6137
6335
  constructor(client, config) {
6138
6336
  this.client = client;
6139
- this.pusherService = new PusherService(client, { defaultHeaders: config?.defaultHeaders });
6337
+ this.pusherService = new PusherService(client, {
6338
+ apiKey: config?.apiKey,
6339
+ userApiKey: config?.userApiKey,
6340
+ orgApiKey: config?.orgApiKey,
6341
+ defaultHeaders: config?.defaultHeaders
6342
+ });
6140
6343
  this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
6141
6344
  telemetry.instrument(this, "Triggers");
6142
6345
  }
@@ -6343,7 +6546,8 @@ var Triggers = class {
6343
6546
  /**
6344
6547
  * Subscribe to all the triggers
6345
6548
  *
6346
- * @param fn - The function to call when a trigger is received
6549
+ * @param fn - The function to call when a trigger is received. It may be `async`. Errors
6550
+ * thrown from — or promises rejected by — the function are contained and logged.
6347
6551
  * @param filters - The filters to apply to the triggers
6348
6552
  * @param onSubscriptionError - Optional callback invoked with the raw Pusher payload when
6349
6553
  * the underlying subscription fails (for example on auth or permission rejection). The
@@ -6366,11 +6570,7 @@ var Triggers = class {
6366
6570
  await this.pusherService.subscribe((_data) => {
6367
6571
  logger.debug("Received raw trigger data", JSON.stringify(_data, null, 2));
6368
6572
  const parsedData = this.parsePusherPayload(_data);
6369
- if (this.shouldSendTriggerAfterFilters(parsedFilters.data, parsedData)) try {
6370
- fn(parsedData);
6371
- } catch (error) {
6372
- logger.error("❌ Error in trigger callback:", error);
6373
- }
6573
+ if (this.shouldSendTriggerAfterFilters(parsedFilters.data, parsedData)) invokeUserCallback("❌ Error in trigger callback:", () => fn(parsedData));
6374
6574
  else logger.debug("Trigger does not match filters", JSON.stringify(parsedFilters.data, null, 2));
6375
6575
  }, onSubscriptionError);
6376
6576
  }
@@ -6457,6 +6657,10 @@ var Triggers = class {
6457
6657
  /**
6458
6658
  * Unsubscribe from all the triggers
6459
6659
  *
6660
+ * Ends every subscription made with {@link subscribe} on this instance, including one that is
6661
+ * still connecting, and closes the realtime connection so that a script can exit. A later
6662
+ * `subscribe()` opens a new connection.
6663
+ *
6460
6664
  * @returns {Promise<void>}
6461
6665
  *
6462
6666
  * @example
@@ -7590,6 +7794,26 @@ const ToolRouterConfigManageConnectionsSchema = z.object({
7590
7794
  const ToolRouterToolkitsParamSchema = z.array(z.string()).describe("List of toolkits to enable in the tool router session");
7591
7795
  const ToolRouterToolkitsDisabledConfigSchema = z.object({ disable: ToolRouterToolkitsParamSchema.describe("List of toolkits to disable in the tool router session") }).strict();
7592
7796
  const ToolRouterToolkitsEnabledConfigSchema = z.object({ enable: ToolRouterToolkitsParamSchema.describe("List of toolkits to enable in the tool router session") }).strict();
7797
+ /**
7798
+ * Toolkits whose tools need the user's approval before they run. A call that
7799
+ * needs approval doesn't run: `session.execute()` throws
7800
+ * `ComposioToolInputRequiredError` with the question to show the user.
7801
+ * @experimental
7802
+ */
7803
+ const ToolRouterToolkitsRequireApprovalSchema = ToolRouterToolkitsParamSchema.describe("Experimental. Toolkits whose tools need the user approval before they run");
7804
+ /** Session toolkit policy: a list to enable, an enable/disable object, or only an approval list. */
7805
+ const ToolRouterSessionToolkitsSchema = z.union([
7806
+ ToolRouterToolkitsParamSchema,
7807
+ ToolRouterToolkitsDisabledConfigSchema.extend({ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional() }).strict(),
7808
+ ToolRouterToolkitsEnabledConfigSchema.extend({ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional() }).strict(),
7809
+ z.object({ requireApproval: ToolRouterToolkitsRequireApprovalSchema }).strict()
7810
+ ]);
7811
+ /**
7812
+ * What happens to a call that needs the user's approval when the session's MCP
7813
+ * client can't ask the user.
7814
+ * @experimental
7815
+ */
7816
+ const ToolRouterNoElicitationSupportFallbackSchema = z.enum(["deny", "allow"]).describe("Experimental. What happens to a call that needs approval when the MCP client cannot ask the user");
7593
7817
  /** Experimental Instant usage policy for a Session. */
7594
7818
  const ToolRouterInstantSchema = z.union([z.literal(false), z.object({
7595
7819
  toolkits: z.union([ToolRouterToolkitsEnabledConfigSchema, ToolRouterToolkitsDisabledConfigSchema]).optional(),
@@ -7621,7 +7845,12 @@ const ToolRouterTagsParamSchema = z.array(z.enum([
7621
7845
  ])).describe("The tags to filter the tools by");
7622
7846
  const ToolRouterTagsEnableDisableSchema = z.object({
7623
7847
  enable: ToolRouterTagsParamSchema.optional().describe("The tags to enable in the tool router session"),
7624
- disable: ToolRouterTagsParamSchema.optional().describe("The tags to disable in the tool router session")
7848
+ disable: ToolRouterTagsParamSchema.optional().describe("The tags to disable in the tool router session"),
7849
+ /**
7850
+ * Tools with any of these tags need the user's approval before they run.
7851
+ * @experimental
7852
+ */
7853
+ requireApproval: ToolRouterTagsParamSchema.optional().describe("Experimental. Tools with any of these tags need the user approval before they run")
7625
7854
  }).strict();
7626
7855
  const ToolRouterConfigTagsSchema = z.union([ToolRouterTagsParamSchema, ToolRouterTagsEnableDisableSchema]).describe("The tags to use in the tool router session");
7627
7856
  /**
@@ -7647,14 +7876,29 @@ const ToolRouterConfigTagsSchema = z.union([ToolRouterTagsParamSchema, ToolRoute
7647
7876
  * ```
7648
7877
  */
7649
7878
  const ToolRouterToolsParamSchema = z.array(z.string()).describe("The tools to use in the tool router session");
7879
+ /**
7880
+ * Tools of the toolkit that need the user's approval before they run.
7881
+ * @experimental
7882
+ */
7883
+ const ToolRouterToolsRequireApprovalSchema = ToolRouterToolsParamSchema.describe("Experimental. Tools of this toolkit that need the user approval before they run");
7650
7884
  const ToolRouterConfigToolsSchema = z.union([
7651
7885
  ToolRouterToolsParamSchema,
7652
- z.object({ enable: ToolRouterToolsParamSchema.describe("The tools to enable in the tool router session") }).strict(),
7653
- z.object({ disable: ToolRouterToolsParamSchema.describe("The tools to disable in the tool router session") }).strict(),
7654
- z.object({ tags: ToolRouterConfigTagsSchema.describe("The tags to filter the tools by, this will override the global tags") }).strict()
7886
+ z.object({
7887
+ enable: ToolRouterToolsParamSchema.describe("The tools to enable in the tool router session"),
7888
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
7889
+ }).strict(),
7890
+ z.object({
7891
+ disable: ToolRouterToolsParamSchema.describe("The tools to disable in the tool router session"),
7892
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
7893
+ }).strict(),
7894
+ z.object({
7895
+ tags: ToolRouterConfigTagsSchema.describe("The tags to filter the tools by, this will override the global tags"),
7896
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
7897
+ }).strict(),
7898
+ z.object({ requireApproval: ToolRouterToolsRequireApprovalSchema }).strict()
7655
7899
  ]).superRefine((val, ctx) => {
7656
7900
  if (typeof val === "object" && !Array.isArray(val)) {
7657
- const keys = Object.keys(val);
7901
+ const keys = Object.keys(val).filter((key) => key !== "requireApproval");
7658
7902
  if (keys.length > 1) ctx.addIssue({
7659
7903
  code: z.ZodIssueCode.custom,
7660
7904
  message: `Only one of 'enable', 'disable', or 'tags' can be specified, but found: ${keys.join(", ")}`,
@@ -7679,11 +7923,7 @@ const ToolRouterCreateSessionConfigBaseSchema = z.object({
7679
7923
  mcp: z.boolean().optional().describe("When true, the returned session surfaces its hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`) in the type, and an MCP URL that is not on the API base URL origin throws `ComposioMCPDestinationError` instead of leaving `session.mcp.headers` empty with a warning. The endpoint exists on every session at runtime regardless of this flag, but is only typed when `mcp: true` is passed. Default native tools (`session.tools()`) are unaffected. See https://docs.composio.dev/docs/sessions-via-mcp"),
7680
7924
  tools: z.record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema])).optional().describe("The tools to use in the tool router session"),
7681
7925
  tags: ToolRouterConfigTagsSchema.optional().describe("Global tags to filter the tools by"),
7682
- toolkits: z.union([
7683
- ToolRouterToolkitsParamSchema,
7684
- ToolRouterToolkitsDisabledConfigSchema,
7685
- ToolRouterToolkitsEnabledConfigSchema
7686
- ]).optional().describe("The toolkits to use in the tool router session"),
7926
+ toolkits: ToolRouterSessionToolkitsSchema.optional().describe("The toolkits to use in the tool router session"),
7687
7927
  instant: ToolRouterInstantSchema.optional().describe("Experimental Instant usage policy. Omission permits eligible tools when the project allows Instant usage; false disables it for this Session."),
7688
7928
  authConfigs: z.record(z.string(), z.string()).describe("The auth configs to use in the tool router session. The key is the toolkit slug, the value is the auth config id.").default({}),
7689
7929
  connectedAccounts: z.record(z.string(), z.union([z.string(), z.array(z.string())])).describe("The connected accounts to use in the tool router session. The key is the toolkit slug, the value is a connected account id or an array of ids. Only one account per toolkit is allowed when multi-account mode is disabled.").default({}),
@@ -7701,7 +7941,14 @@ const ToolRouterCreateSessionConfigBaseSchema = z.object({
7701
7941
  assistivePrompt: z.object({ userTimezone: z.string().optional().describe("IANA timezone identifier (e.g., \"America/New_York\", \"Europe/London\") for timezone-aware assistive prompts") }).optional().describe("Configuration for assistive prompt generation"),
7702
7942
  customTools: z.array(z.custom()).optional().describe("Custom tools to include in this session. Created via createCustomTool() from @composio/core/experimental."),
7703
7943
  customToolkits: z.array(z.custom()).optional().describe("Custom toolkits to include in this session. Created via createCustomToolkit() from @composio/core/experimental."),
7704
- sessionConfigId: z.string().min(1).optional().describe("ID of a saved Session config (`sc_…`) to apply when the session is created. Cannot be combined with toolkits, tools, tags, customTools or customToolkits.")
7944
+ sessionConfigId: z.string().min(1).optional().describe("ID of a saved Session config (`sc_…`) to apply when the session is created. Cannot be combined with toolkits, tools, tags, customTools or customToolkits."),
7945
+ /**
7946
+ * What happens to a call that needs the user's approval when the
7947
+ * session's MCP client can't ask the user: `deny` (the default) or
7948
+ * `allow`.
7949
+ * @experimental
7950
+ */
7951
+ noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional()
7705
7952
  }).optional().describe("Experimental features configuration - not stable, may be modified or removed")
7706
7953
  }).partial().superRefine((config, ctx) => {
7707
7954
  if (config.experimental?.sessionConfigId !== void 0) addSessionConfigConflictIssue(ctx, [
@@ -7908,6 +8155,12 @@ const ToolRouterUpdateExperimentalSchema = z.object({
7908
8155
  linkUrlOverwrite: z.string().nullable().optional().describe("Base URL override for connection link redirects. `null` removes the stored override"),
7909
8156
  fastMode: z.boolean().nullable().optional().describe("Fast search mode. `null` removes the stored override"),
7910
8157
  submitFeedback: z.object({ enable: z.boolean() }).strict().nullable().optional().describe("Exposes the COMPOSIO_SUBMIT_FEEDBACK helper tool. `null` removes the stored block"),
8158
+ /**
8159
+ * What happens to a call that needs the user's approval when the session's
8160
+ * MCP client can't ask the user: `deny` or `allow`.
8161
+ * @experimental
8162
+ */
8163
+ noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
7911
8164
  sessionConfigId: z.string().min(1).optional().describe("Apply the latest active saved Session config (`sc_…`) from this project to this session. Replaces the session's toolkit, tool and tag access and cannot be combined with toolkits, tools or tags")
7912
8165
  }).strict();
7913
8166
  /**
@@ -7918,11 +8171,7 @@ const ToolRouterUpdateExperimentalSchema = z.object({
7918
8171
  */
7919
8172
  const ToolRouterUpdateSessionConfigSchema = z.object({
7920
8173
  instant: ToolRouterInstantSchema.optional().describe("Experimental Instant usage policy. False disables it. Any supplied object, even one that only sets returnInstantCharge, re-enables it. Omitted subfields keep their stored values."),
7921
- toolkits: z.union([
7922
- ToolRouterToolkitsParamSchema,
7923
- ToolRouterToolkitsDisabledConfigSchema,
7924
- ToolRouterToolkitsEnabledConfigSchema
7925
- ]).nullable().optional().describe("Toolkit policy. An empty allowlist (`[]` or `{ enable: [] }`) is sent as-is and denies every app toolkit; `null` removes the stored policy and restores the unrestricted default"),
8174
+ toolkits: ToolRouterSessionToolkitsSchema.nullable().optional().describe("Toolkit policy. An empty allowlist (`[]` or `{ enable: [] }`) is sent as-is and denies every app toolkit; `null` removes the stored policy and restores the unrestricted default"),
7926
8175
  tools: z.record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema])).nullable().optional().describe("Replaces the entire stored tools map; `null` removes the override"),
7927
8176
  tags: ToolRouterConfigTagsSchema.nullable().optional().describe("Replaces the global tag policy; `null` removes the override"),
7928
8177
  authConfigs: z.record(z.string(), z.string()).nullable().optional().describe("Replaces the entire stored auth config map; `null` removes the override"),
@@ -8550,7 +8799,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
8550
8799
 
8551
8800
  //#endregion
8552
8801
  //#region package.json
8553
- var version = "0.24.0";
8802
+ var version = "0.26.0";
8554
8803
 
8555
8804
  //#endregion
8556
8805
  //#region src/utils/session.ts
@@ -8575,44 +8824,35 @@ function detectRuntime() {
8575
8824
  return "UNKNOWN";
8576
8825
  }
8577
8826
  const RUNTIME_ENV = detectRuntime();
8578
- const runtimeVersions = z$2.object({
8579
- Bun: z$2.object({ version: z$2.string() }).optional(),
8580
- Deno: z$2.object({ version: z$2.object({ deno: z$2.string() }) }).optional()
8581
- }).safeParse(globalThis);
8582
- const detectRuntimeVersion = () => {
8583
- switch (RUNTIME_ENV) {
8584
- case "BUN": return runtimeVersions.success ? runtimeVersions.data.Bun?.version : void 0;
8585
- case "DENO": return runtimeVersions.success ? runtimeVersions.data.Deno?.version.deno : void 0;
8586
- case "NODEJS": return process.versions.node;
8587
- default: return;
8588
- }
8589
- };
8590
- const RUNTIME_VERSION = detectRuntimeVersion();
8591
- function getSessionHeaders(provider) {
8827
+ /**
8828
+ * An identity value is sent as a header, so the client accepts only non-empty
8829
+ * printable ASCII with no leading or trailing whitespace.
8830
+ */
8831
+ const HEADER_SAFE = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/;
8832
+ /**
8833
+ * The identity the API client reports for this SDK: its product headers
8834
+ * (`x-client-provenance`, `x-client-version`, `x-sdk-version`) and the legacy
8835
+ * `x-source`, `x-framework` and `x-runtime` labels. The client adds the
8836
+ * library headers and detects the runtime and its version itself.
8837
+ *
8838
+ * A custom provider whose name cannot be sent as a header value is reported
8839
+ * as `unknown` rather than making the SDK fail to construct.
8840
+ */
8841
+ function getClientIdentity(provider) {
8842
+ const framework = provider?.name;
8592
8843
  return {
8593
- "x-framework": provider?.name || "unknown",
8594
- "x-source": "TYPESCRIPT_SDK",
8595
- "x-runtime": RUNTIME_ENV,
8596
- "x-client-runtime": RUNTIME_ENV === "CLOUDFLARE_WORKERS" ? "cloudflare" : RUNTIME_ENV.toLowerCase(),
8597
- "x-sdk-version": identity.version,
8598
- "x-client-provenance": identity.name,
8599
- "x-client-version": identity.version,
8600
- "x-client-language": "typescript",
8601
- "x-client-library": "@composio/client",
8602
- "x-client-library-version": VERSION,
8603
- ...RUNTIME_VERSION ? { "x-runtime-version": RUNTIME_VERSION } : {}
8844
+ product: manifest.name,
8845
+ version: manifest.version,
8846
+ source: "TYPESCRIPT_SDK",
8847
+ framework: framework && HEADER_SAFE.test(framework) ? framework : "unknown",
8848
+ runtime: RUNTIME_ENV
8604
8849
  };
8605
8850
  }
8606
- const getDefaultHeaders = (headers, provider) => {
8607
- const sessionHeaders = getSessionHeaders(provider);
8608
- return {
8609
- ...headers || {},
8610
- ...sessionHeaders
8611
- };
8612
- };
8613
8851
 
8614
8852
  //#endregion
8615
8853
  //#region src/lib/toolRouterParams.ts
8854
+ /** `require_approval` when the caller set an approval list, nothing otherwise. */
8855
+ const requireApprovalParam = (requireApproval) => requireApproval !== void 0 ? { require_approval: requireApproval } : {};
8616
8856
  const transformToolRouterToolsParams = (params) => {
8617
8857
  if (!params) return;
8618
8858
  if (typeof params === "object") return Object.keys(params).reduce((acc, key) => {
@@ -8622,12 +8862,21 @@ const transformToolRouterToolsParams = (params) => {
8622
8862
  if (parsedResult.success) {
8623
8863
  const data = parsedResult.data;
8624
8864
  if (Array.isArray(data)) acc[key] = { enable: data };
8625
- else if ("enable" in data) acc[key] = { enable: data.enable };
8626
- else if ("disable" in data) acc[key] = { disable: data.disable };
8865
+ else if ("enable" in data) acc[key] = {
8866
+ enable: data.enable,
8867
+ ...requireApprovalParam(data.requireApproval)
8868
+ };
8869
+ else if ("disable" in data) acc[key] = {
8870
+ disable: data.disable,
8871
+ ...requireApprovalParam(data.requireApproval)
8872
+ };
8627
8873
  else if ("tags" in data) {
8628
8874
  const tags = transformToolRouterTagsParams(data.tags);
8629
- if (tags) acc[key] = { tags };
8630
- }
8875
+ if (tags) acc[key] = {
8876
+ tags,
8877
+ ...requireApprovalParam(data.requireApproval)
8878
+ };
8879
+ } else acc[key] = { require_approval: data.requireApproval };
8631
8880
  } else throw new ValidationError(parsedResult.error.message);
8632
8881
  } else acc[key] = { enable: params[key] };
8633
8882
  return acc;
@@ -8638,7 +8887,8 @@ const transformToolRouterTagsParams = (params) => {
8638
8887
  if (Array.isArray(params)) return { enable: params };
8639
8888
  else if (typeof params === "object") return {
8640
8889
  enable: params.enable,
8641
- disable: params.disable
8890
+ disable: params.disable,
8891
+ ...requireApprovalParam(params.requireApproval)
8642
8892
  };
8643
8893
  };
8644
8894
  const transformToolRouterManageConnectionsParams = (params) => {
@@ -8696,6 +8946,7 @@ const transformToolRouterUpdateExperimentalParams = (config) => {
8696
8946
  if (config.fastMode !== void 0) result.fast_mode = config.fastMode;
8697
8947
  if (config.submitFeedback !== void 0) result.submit_feedback = config.submitFeedback;
8698
8948
  if (config.sessionConfigId !== void 0) result.session_config_id = config.sessionConfigId;
8949
+ if (config.noElicitationSupportFallback !== void 0) result.no_elicitation_support_fallback = config.noElicitationSupportFallback;
8699
8950
  return result;
8700
8951
  };
8701
8952
  /**
@@ -8723,7 +8974,15 @@ const transformToolRouterMultiAccountParams = (params) => {
8723
8974
  const transformToolRouterToolkitsParams = (params) => {
8724
8975
  if (!params) return;
8725
8976
  if (Array.isArray(params)) return { enable: params };
8726
- return params;
8977
+ if ("enable" in params) return {
8978
+ enable: params.enable,
8979
+ ...requireApprovalParam(params.requireApproval)
8980
+ };
8981
+ if ("disable" in params) return {
8982
+ disable: params.disable,
8983
+ ...requireApprovalParam(params.requireApproval)
8984
+ };
8985
+ return { require_approval: params.requireApproval };
8727
8986
  };
8728
8987
  /**
8729
8988
  * Request body of `session.update()`. Every key present in `config` is sent,
@@ -9781,6 +10040,13 @@ async function deleteToolRouterSession(client, sessionId, requestOptions) {
9781
10040
  //#endregion
9782
10041
  //#region src/models/ToolRouterSession.ts
9783
10042
  const COMPOSIO_MULTI_EXECUTE_TOOL = "COMPOSIO_MULTI_EXECUTE_TOOL";
10043
+ /** The request fields that carry the user's answers to an earlier `input_required` call. */
10044
+ function inputResponseParams(options) {
10045
+ return {
10046
+ ...options?.inputResponses !== void 0 && { input_responses: options.inputResponses },
10047
+ ...options?.requestState !== void 0 && { request_state: options.requestState }
10048
+ };
10049
+ }
9784
10050
  const DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX = "[Direct tool - call directly, no search needed beforehand.]";
9785
10051
  /**
9786
10052
  * Options accepted by {@link ToolRouterSession.authorize}.
@@ -10168,6 +10434,8 @@ var ToolRouterSession = class {
10168
10434
  * @param arguments_ - Optional tool arguments
10169
10435
  * @param options - Optional execution options
10170
10436
  * @param options.account - Account identifier for direct app tool execution. Accepted on every project: in multi-account sessions it picks the account; on single-account projects it must match one of the session's active connections for the toolkit. Helper/meta tools either ignore this top-level field or define their own account-selection fields.
10437
+ * @param options.inputResponses - Experimental. The user's answers to an earlier `ComposioToolInputRequiredError`, keyed by the IDs in its `inputRequests`. Repeat the same call with them.
10438
+ * @param options.requestState - Experimental. The `requestState` of that error, sent back unchanged.
10171
10439
  * @returns The tool execution result
10172
10440
  * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run
10173
10441
  */
@@ -10186,7 +10454,8 @@ var ToolRouterSession = class {
10186
10454
  assertUnambiguousCustomToolSlug(this.customToolsMap, toolSlug);
10187
10455
  const executeParams = {
10188
10456
  tool_slug: toolSlug,
10189
- arguments: arguments_ ?? {}
10457
+ arguments: arguments_ ?? {},
10458
+ ...inputResponseParams(options)
10190
10459
  };
10191
10460
  if (options?.account) executeParams.account = options.account;
10192
10461
  const experimental = inlineCustomToolsExperimental(this.inlineCustomToolsPayload);
@@ -10205,6 +10474,7 @@ var ToolRouterSession = class {
10205
10474
  *
10206
10475
  * @param slug - The meta tool slug to execute
10207
10476
  * @param arguments_ - Optional meta tool arguments
10477
+ * @param options - Experimental. The user's answers to an earlier `ComposioToolInputRequiredError` (`inputResponses`) and its `requestState`, as in `session.execute()`
10208
10478
  * @returns The tool execution result, in the same shape as `session.execute()`
10209
10479
  * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run
10210
10480
  *
@@ -10215,10 +10485,11 @@ var ToolRouterSession = class {
10215
10485
  * });
10216
10486
  * ```
10217
10487
  */
10218
- async executeMeta(slug, arguments_, requestOptions) {
10488
+ async executeMeta(slug, arguments_, options, requestOptions) {
10219
10489
  const executeMetaParams = {
10220
10490
  slug,
10221
- arguments: arguments_ ?? {}
10491
+ arguments: arguments_ ?? {},
10492
+ ...inputResponseParams(options)
10222
10493
  };
10223
10494
  const experimental = inlineCustomToolsExperimental(this.inlineCustomToolsPayload);
10224
10495
  if (experimental) executeMetaParams.experimental = experimental;
@@ -10532,7 +10803,8 @@ var ToolRouter = class {
10532
10803
  /**
10533
10804
  * Derives the MCP config for a session from the auth context the session
10534
10805
  * request was made with: the project key when one is configured, otherwise
10535
- * the resolved user API key, plus the org/project scope when configured.
10806
+ * the resolved user API key, otherwise the organization API key, plus the
10807
+ * org/project scope when configured.
10536
10808
  * Headers are only attached when the MCP URL shares the client's API
10537
10809
  * origin. Any other destination throws when the caller passed `mcp: true`
10538
10810
  * and otherwise yields empty headers plus a warning; see
@@ -10545,6 +10817,7 @@ var ToolRouter = class {
10545
10817
  apiBaseURL: this.client.baseURL,
10546
10818
  apiKey: this.config?.apiKey,
10547
10819
  userApiKey: this.config?.userApiKey,
10820
+ orgApiKey: this.config?.orgApiKey,
10548
10821
  defaultHeaders: this.config?.defaultHeaders,
10549
10822
  orgId: this.config?.orgId,
10550
10823
  projectId: this.config?.projectId,
@@ -10565,6 +10838,7 @@ var ToolRouter = class {
10565
10838
  });
10566
10839
  const experimentalPayload = {};
10567
10840
  if (routerConfig.experimental?.sessionConfigId !== void 0) experimentalPayload.session_config_id = routerConfig.experimental.sessionConfigId;
10841
+ if (routerConfig.experimental?.noElicitationSupportFallback !== void 0) experimentalPayload.no_elicitation_support_fallback = routerConfig.experimental.noElicitationSupportFallback;
10568
10842
  if (routerConfig.experimental?.assistivePrompt?.userTimezone) experimentalPayload.assistive_prompt_config = { user_timezone: routerConfig.experimental.assistivePrompt.userTimezone };
10569
10843
  if (inlineCustomToolsPayload?.custom_tools) experimentalPayload.custom_tools = inlineCustomToolsPayload.custom_tools;
10570
10844
  if (inlineCustomToolsPayload?.custom_toolkits) experimentalPayload.custom_toolkits = inlineCustomToolsPayload.custom_toolkits;
@@ -10663,6 +10937,231 @@ var Sessions = class extends ToolRouter {
10663
10937
  }
10664
10938
  };
10665
10939
 
10940
+ //#endregion
10941
+ //#region src/utils/toolkitDeprecation.ts
10942
+ /**
10943
+ * Toolkit version deprecation warnings.
10944
+ *
10945
+ * When a request resolves to a deprecated toolkit version, the API adds a
10946
+ * `Composio-Deprecated-Toolkits` response header (an RFC 9651 structured-field
10947
+ * list). This module parses that header below the generated client, through a
10948
+ * `fetch` wrapper, and warns once per process for each deprecated toolkit
10949
+ * version it sees. The response itself is never read, cloned or altered.
10950
+ *
10951
+ * Example header:
10952
+ *
10953
+ * "GMAIL";version="20250114_00";deprecated=@1779840000;sunset=@1787788800;reason="lifecycle"
10954
+ */
10955
+ /** Response header name. `Headers.get` is case-insensitive. */
10956
+ const TOOLKIT_DEPRECATION_HEADER = "composio-deprecated-toolkits";
10957
+ /** Anchor of the docs section every warning points at. */
10958
+ const TOOLKIT_DEPRECATION_DOCS_URL = "https://docs.composio.dev/docs/tools-direct/toolkit-versioning#deprecation-and-sunset";
10959
+ /** Versions named per toolkit before the formatter collapses the rest into "and N more". */
10960
+ const MAX_VERSIONS_PER_LINE = 5;
10961
+ /**
10962
+ * The three limits below mirror the `@composio/client` deprecation module,
10963
+ * which reads the same kind of server-controlled header.
10964
+ */
10965
+ /** A header longer than this is ignored whole rather than parsed. */
10966
+ const MAX_HEADER_LENGTH = 2048;
10967
+ /** A header holding any of these is ignored whole, so nothing partially cleaned reaches the log. */
10968
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
10969
+ /** Keys the process will ever record; past this, new versions are neither recorded nor warned about. */
10970
+ const MAX_TRACKED_VERSIONS = 1024;
10971
+ const DeprecatedToolkitEntrySchema = z$2.object({
10972
+ slug: z$2.string().min(1),
10973
+ version: z$2.string().min(1),
10974
+ deprecatedAt: z$2.date().optional(),
10975
+ sunsetAt: z$2.date().optional(),
10976
+ reason: z$2.string().min(1).optional()
10977
+ });
10978
+ /** Keys (`UPPER(slug)@version`) already warned about in this process. */
10979
+ const warnedToolkitVersions = /* @__PURE__ */ new Set();
10980
+ const dedupeKey = (entry) => `${entry.slug.toUpperCase()}@${entry.version}`;
10981
+ /**
10982
+ * Splits `value` on `delimiter` characters that sit outside double-quoted
10983
+ * strings, honouring backslash escapes inside the quotes. Empty pieces are
10984
+ * dropped and the rest are trimmed.
10985
+ */
10986
+ const splitOutsideQuotes = (value, delimiter) => {
10987
+ const pieces = [];
10988
+ let current = "";
10989
+ let inString = false;
10990
+ for (let index = 0; index < value.length; index++) {
10991
+ const char = value[index];
10992
+ if (inString) {
10993
+ current += char;
10994
+ if (char === "\\" && index + 1 < value.length) {
10995
+ index += 1;
10996
+ current += value[index];
10997
+ } else if (char === "\"") inString = false;
10998
+ } else if (char === "\"") {
10999
+ inString = true;
11000
+ current += char;
11001
+ } else if (char === delimiter) {
11002
+ pieces.push(current);
11003
+ current = "";
11004
+ } else current += char;
11005
+ }
11006
+ pieces.push(current);
11007
+ return pieces.map((piece) => piece.trim()).filter((piece) => piece.length > 0);
11008
+ };
11009
+ /**
11010
+ * Decodes an sf-string (`"..."` with `\"` and `\\` escapes). Returns
11011
+ * `undefined` for anything that is not a complete, validly escaped sf-string.
11012
+ */
11013
+ const decodeSfString = (raw) => {
11014
+ const match = /^"((?:[^"\\]|\\.)*)"$/.exec(raw);
11015
+ if (match === null) return void 0;
11016
+ let invalidEscape = false;
11017
+ const decoded = match[1].replace(/\\(.)/g, (_whole, escaped) => {
11018
+ if (escaped === "\"" || escaped === "\\") return escaped;
11019
+ invalidEscape = true;
11020
+ return "";
11021
+ });
11022
+ return invalidEscape ? void 0 : decoded;
11023
+ };
11024
+ /** Decodes an sf-date (`@` followed by Unix seconds). */
11025
+ const decodeSfDate = (raw) => {
11026
+ const match = /^@(-?\d{1,15})$/.exec(raw);
11027
+ if (match === null) return void 0;
11028
+ const date = /* @__PURE__ */ new Date(Number(match[1]) * 1e3);
11029
+ return Number.isNaN(date.getTime()) ? void 0 : date;
11030
+ };
11031
+ /** Header parameters the SDK understands, by wire name. */
11032
+ const KNOWN_PARAMETERS = /* @__PURE__ */ new Map([
11033
+ ["version", {
11034
+ name: "version",
11035
+ kind: "string"
11036
+ }],
11037
+ ["reason", {
11038
+ name: "reason",
11039
+ kind: "string"
11040
+ }],
11041
+ ["deprecated", {
11042
+ name: "deprecatedAt",
11043
+ kind: "date"
11044
+ }],
11045
+ ["sunset", {
11046
+ name: "sunsetAt",
11047
+ kind: "date"
11048
+ }]
11049
+ ]);
11050
+ /**
11051
+ * Parses one list item: an sf-string slug followed by `;key=value` parameters.
11052
+ * Unknown parameters are ignored; a known parameter with the wrong type drops
11053
+ * the item.
11054
+ */
11055
+ const parseItem = (item) => {
11056
+ const [head, ...params] = splitOutsideQuotes(item, ";");
11057
+ if (head === void 0) return void 0;
11058
+ const candidate = { slug: decodeSfString(head) };
11059
+ for (const param of params) {
11060
+ const separator = param.indexOf("=");
11061
+ if (separator === -1) continue;
11062
+ const key = param.slice(0, separator).trim();
11063
+ const rawValue = param.slice(separator + 1).trim();
11064
+ const field = KNOWN_PARAMETERS.get(key);
11065
+ if (field === void 0) continue;
11066
+ const decoded = field.kind === "string" ? decodeSfString(rawValue) : decodeSfDate(rawValue);
11067
+ if (decoded === void 0) return void 0;
11068
+ candidate[field.name] = decoded;
11069
+ }
11070
+ const parsed = DeprecatedToolkitEntrySchema.safeParse(candidate);
11071
+ return parsed.success ? parsed.data : void 0;
11072
+ };
11073
+ /**
11074
+ * Parses a `Composio-Deprecated-Toolkits` header value. Items that fail to
11075
+ * parse are dropped silently; garbage input yields an empty array. Never throws.
11076
+ */
11077
+ function parseDeprecatedToolkitsHeader(value) {
11078
+ try {
11079
+ const entries = [];
11080
+ for (const item of splitOutsideQuotes(value, ",")) {
11081
+ const entry = parseItem(item);
11082
+ if (entry !== void 0) entries.push(entry);
11083
+ }
11084
+ return entries;
11085
+ } catch {
11086
+ return [];
11087
+ }
11088
+ }
11089
+ const isoDate = (date) => date.toISOString().slice(0, 10);
11090
+ const pinHint = (slug, docsUrl) => {
11091
+ return `Pin a newer version with toolkitVersions: { ${normalizeToolkitSlug(slug)}: '<version>' } or ${`COMPOSIO_TOOLKIT_VERSION_${slug.toUpperCase()}`}. See ${docsUrl}.`;
11092
+ };
11093
+ const formatSingle = (entry, docsUrl) => {
11094
+ let sentence = `[Deprecation] Toolkit ${entry.slug.toUpperCase()} version ${entry.version} was deprecated`;
11095
+ if (entry.deprecatedAt !== void 0) sentence += ` on ${isoDate(entry.deprecatedAt)}`;
11096
+ if (entry.reason !== void 0) sentence += ` (${entry.reason})`;
11097
+ if (entry.sunsetAt !== void 0) sentence += ` and will stop working on ${isoDate(entry.sunsetAt)}`;
11098
+ return `${sentence}. ${pinHint(entry.slug, docsUrl)}`;
11099
+ };
11100
+ const formatGroup = (slug, entries, docsUrl) => {
11101
+ const versions = entries.map((entry) => entry.version);
11102
+ const named = versions.slice(0, MAX_VERSIONS_PER_LINE).join(", ");
11103
+ const remaining = versions.length - MAX_VERSIONS_PER_LINE;
11104
+ let sentence = `[Deprecation] Toolkit ${slug} versions ${remaining > 0 ? `${named} and ${remaining} more` : named} are deprecated`;
11105
+ const sunsets = entries.map((entry) => entry.sunsetAt).filter((date) => date !== void 0).sort((a, b) => a.getTime() - b.getTime());
11106
+ if (sunsets.length > 0) sentence += ` and the earliest will stop working on ${isoDate(sunsets[0])}`;
11107
+ return `${sentence}. ${pinHint(slug, docsUrl)}`;
11108
+ };
11109
+ /**
11110
+ * Renders one warning line per toolkit slug. A slug with a single deprecated
11111
+ * version gets the full sentence with its dates and reason; a slug with several
11112
+ * names at most five versions and collapses the rest into "and N more".
11113
+ */
11114
+ function formatToolkitDeprecationWarnings(entries, docsUrl = TOOLKIT_DEPRECATION_DOCS_URL) {
11115
+ const groups = /* @__PURE__ */ new Map();
11116
+ for (const entry of entries) {
11117
+ const slug = entry.slug.toUpperCase();
11118
+ const group = groups.get(slug);
11119
+ if (group === void 0) groups.set(slug, [entry]);
11120
+ else group.push(entry);
11121
+ }
11122
+ return Array.from(groups, ([slug, group]) => group.length === 1 ? formatSingle(group[0], docsUrl) : formatGroup(slug, group, docsUrl));
11123
+ }
11124
+ /**
11125
+ * Parses the header on `response`, drops versions already warned about in this
11126
+ * process, records the new ones and warns once per formatted line.
11127
+ */
11128
+ const warnDeprecatedToolkits = (response) => {
11129
+ const value = response.headers.get(TOOLKIT_DEPRECATION_HEADER);
11130
+ if (value === null || value.length === 0) return;
11131
+ if (value.length > MAX_HEADER_LENGTH || CONTROL_CHARACTERS.test(value)) return;
11132
+ if (warnedToolkitVersions.size >= MAX_TRACKED_VERSIONS) return;
11133
+ const fresh = [];
11134
+ for (const entry of parseDeprecatedToolkitsHeader(value)) {
11135
+ const key = dedupeKey(entry);
11136
+ if (warnedToolkitVersions.has(key) || warnedToolkitVersions.size >= MAX_TRACKED_VERSIONS) continue;
11137
+ warnedToolkitVersions.add(key);
11138
+ fresh.push(entry);
11139
+ }
11140
+ for (const line of formatToolkitDeprecationWarnings(fresh)) logger.warn(line);
11141
+ };
11142
+ /**
11143
+ * Wraps a `fetch` implementation so every response is checked for the
11144
+ * `Composio-Deprecated-Toolkits` header. The wrapper is `this`-independent,
11145
+ * returns the response unchanged on every path and never fails a call over
11146
+ * the header: any error while inspecting it is logged at debug and swallowed.
11147
+ *
11148
+ * When no `baseFetch` is given, `globalThis.fetch` is resolved per call so a
11149
+ * runtime that installs or replaces `fetch` after construction still works.
11150
+ */
11151
+ function createToolkitDeprecationFetch(baseFetch) {
11152
+ return async (input, init) => {
11153
+ const response = await (baseFetch ?? globalThis.fetch)(input, init);
11154
+ try {
11155
+ warnDeprecatedToolkits(response);
11156
+ } catch (error) {
11157
+ try {
11158
+ logger.debug("Failed to inspect the toolkit deprecation header", error);
11159
+ } catch {}
11160
+ }
11161
+ return response;
11162
+ };
11163
+ }
11164
+
10666
11165
  //#endregion
10667
11166
  //#region src/composio.ts
10668
11167
  /**
@@ -10682,7 +11181,7 @@ const toClientLogLevel = (level) => {
10682
11181
  * at call time so a later `logger.configure()` is honoured. The client's
10683
11182
  * `info` records (per-request lifecycle) are forwarded as SDK `debug`.
10684
11183
  */
10685
- const clientLoggerAdapter = {
11184
+ const clientLogForwarder = {
10686
11185
  error: (...args) => logger.error(...args),
10687
11186
  warn: (...args) => logger.warn(...args),
10688
11187
  info: (...args) => logger.debug(...args),
@@ -10850,11 +11349,13 @@ var Composio = class Composio {
10850
11349
  userApiKey: config?.userApiKey,
10851
11350
  orgApiKey: config?.orgApiKey
10852
11351
  });
10853
- const userApiKey = apiKeyParsed === null ? resolveUserApiKey(config?.userApiKey) : void 0;
10854
- const defaultHeadersInput = userApiKey !== void 0 && !getUserApiKeyHeader(config?.defaultHeaders) ? {
10855
- ...config?.defaultHeaders,
10856
- [USER_API_KEY_HEADER]: userApiKey
10857
- } : config?.defaultHeaders;
11352
+ const credentials = resolveSDKCredentials({
11353
+ apiKey: apiKeyParsed,
11354
+ userApiKey: config?.userApiKey,
11355
+ orgApiKey: config?.orgApiKey,
11356
+ defaultHeaders: config?.defaultHeaders
11357
+ });
11358
+ const defaultHeaders = withoutSDKOwnedHeaders(config?.defaultHeaders);
10858
11359
  if (config?.logger !== void 0 || config?.logLevel !== void 0) logger.configure({
10859
11360
  level: config.logLevel,
10860
11361
  sink: config.logger
@@ -10871,8 +11372,10 @@ var Composio = class Composio {
10871
11372
  this.config = {
10872
11373
  ...config,
10873
11374
  baseURL: baseURLParsed,
10874
- apiKey: apiKeyParsed,
10875
- defaultHeaders: defaultHeadersInput,
11375
+ apiKey: credentials.apiKey,
11376
+ userApiKey: credentials.userApiKey,
11377
+ orgApiKey: credentials.orgApiKey,
11378
+ defaultHeaders,
10876
11379
  toolkitVersions: getToolkitVersionsFromEnv(config?.toolkitVersions),
10877
11380
  allowTracking: config?.allowTracking ?? CONFIG_DEFAULTS.allowTracking,
10878
11381
  dangerouslyAllowAutoUploadDownloadFiles: config?.dangerouslyAllowAutoUploadDownloadFiles ?? CONFIG_DEFAULTS.dangerouslyAllowAutoUploadDownloadFiles,
@@ -10884,25 +11387,24 @@ var Composio = class Composio {
10884
11387
  orgId: scope.orgId,
10885
11388
  projectId: scope.projectId
10886
11389
  };
10887
- const defaultHeaders = getDefaultHeaders({
10888
- ...this.config.defaultHeaders,
10889
- ...getScopeHeaders(scope)
10890
- }, this.provider);
10891
11390
  /**
10892
11391
  * Initialize the Composio SDK client.
10893
- * The client is used to make API calls to the Composio API.
11392
+ * The client is used to make API calls to the Composio API. It sends the
11393
+ * credential from `auth`, the resolved org/project scope from `scope`, and
11394
+ * the SDK's identity headers from `identity`, and refuses all three in
11395
+ * `defaultHeaders`.
10894
11396
  */
10895
11397
  this.client = new ComposioClient({
10896
- apiKey: apiKeyParsed,
10897
- userApiKey: config?.userApiKey,
10898
- orgApiKey: config?.orgApiKey,
11398
+ auth: toClientAuth(credentials),
11399
+ scope: toClientScope(scope),
10899
11400
  baseURL: baseURLParsed,
11401
+ ...getEnvVariable("COMPOSIO_ALLOW_INSECURE_HTTP") === "1" ? { allowInsecureHTTP: true } : {},
10900
11402
  defaultHeaders,
10901
- logger: clientLoggerAdapter,
10902
- logLevel: toClientLogLevel(logger.getLevel())
11403
+ identity: getClientIdentity(this.provider),
11404
+ logger: clientLogForwarder,
11405
+ logLevel: toClientLogLevel(logger.getLevel()),
11406
+ transport: createFetchTransport({ fetch: createToolkitDeprecationFetch() })
10903
11407
  });
10904
- this.config.userApiKey = this.client.userApiKey;
10905
- this.config.orgApiKey = this.client.orgApiKey;
10906
11408
  this.tools = new Tools(this.client, this.config);
10907
11409
  this.mcp = new MCP(this.client);
10908
11410
  this.toolkits = new Toolkits(this.client);
@@ -10931,7 +11433,7 @@ var Composio = class Composio {
10931
11433
  * Initialize the client telemetry.
10932
11434
  */
10933
11435
  if (this.config.allowTracking) telemetry.setup({
10934
- apiKey: apiKeyParsed ?? "",
11436
+ apiKey: credentials.apiKey ?? "",
10935
11437
  baseUrl: baseURLParsed ?? "",
10936
11438
  isAgentic: this.provider?._isAgentic || false,
10937
11439
  version,
@@ -10981,8 +11483,8 @@ var Composio = class Composio {
10981
11483
  * instance directly with the headers you need: `new Composio({ ...existingConfig, defaultHeaders })`.
10982
11484
  * For one-off overrides, pass per-call `requestOptions` where supported.
10983
11485
  *
10984
- * @param {MergedRequestInit} fetchOptions - Custom request options to be used for all API calls in this session.
10985
- * This follows the Fetch API RequestInit interface with additional options.
11486
+ * @param {object} [options] - Options for the new instance.
11487
+ * @param {ComposioRequestHeaders} [options.headers] - Headers sent with every API call the new instance makes.
10986
11488
  * @returns {Composio<TProvider>} A new Composio instance with the custom request options applied.
10987
11489
  *
10988
11490
  * @example
@@ -11006,14 +11508,9 @@ var Composio = class Composio {
11006
11508
  * ```
11007
11509
  */
11008
11510
  createSession(options) {
11009
- const userApiKeyHeader = getUserApiKeyHeader(options?.headers) ? void 0 : getUserApiKeyHeader(this.config.defaultHeaders);
11010
- const sessionHeaders = getDefaultHeaders(userApiKeyHeader ? {
11011
- [userApiKeyHeader.name]: userApiKeyHeader.value,
11012
- ...options?.headers
11013
- } : options?.headers, this.provider);
11014
11511
  return new Composio({
11015
11512
  ...this.config,
11016
- defaultHeaders: sessionHeaders
11513
+ defaultHeaders: options?.headers
11017
11514
  });
11018
11515
  }
11019
11516
  /**