@composio/core 0.12.0 → 0.13.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 (144) hide show
  1. package/dist/BaseProvider-Brb3o86-.d.mts +29425 -0
  2. package/dist/{CustomTool-DEB4BQPl.mjs → CustomTool-D9qwyMrv.mjs} +1 -1
  3. package/dist/{CustomTool-DH18rVQu.d.mts → CustomTool-Dmi6ti3I.d.mts} +1 -1
  4. package/dist/CustomTool-DrJpOhY2.d.mts +74 -0
  5. package/dist/{composio-CHnEggnv.d.mts → composio-DHIKRdeG.d.mts} +253 -37
  6. package/dist/composio-vMwhASRc.d.mts +5698 -0
  7. package/dist/{customTool.types-DpIdOJjL.d.mts → customTool.types-CKH2R2ia.d.mts} +344 -25
  8. package/dist/customTool.types-DXin7Cfc.d.mts +2773 -0
  9. package/dist/docs/error-consistency.md +97 -0
  10. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +306 -0
  11. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +205 -0
  12. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +488 -0
  13. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +94 -0
  14. package/dist/docs/reference/sdk-reference/typescript/index.mdx +67 -0
  15. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +304 -0
  16. package/dist/docs/reference/sdk-reference/typescript/meta.json +17 -0
  17. package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +107 -0
  18. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +163 -0
  19. package/dist/docs/reference/sdk-reference/typescript/session.mdx +229 -0
  20. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +131 -0
  21. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +169 -0
  22. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +453 -0
  23. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +434 -0
  24. package/dist/{errors-D5f4pfvI.mjs → errors-DSIlYfl5.mjs} +2 -2
  25. package/dist/experimental/index.d.mts +2 -2
  26. package/dist/experimental/index.mjs +1 -1
  27. package/dist/index.d.mts +27 -4
  28. package/dist/index.mjs +423 -123
  29. package/dist/{jsonSchema-daqF3S3d.mjs → jsonSchema-CFKdONpP.mjs} +1 -1
  30. package/dist/{types-CaI5Z4PA.d.mts → types-D4Id3wXA.d.mts} +1 -1
  31. package/dist/types-qTbYYBJw.d.mts +12 -0
  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.mjs +2 -2
  35. package/docs/error-consistency.md +97 -0
  36. package/package.json +4 -3
  37. package/src/composio.ts +509 -0
  38. package/src/errors/AuthConfigErrors.ts +23 -0
  39. package/src/errors/ComposioError.ts +408 -0
  40. package/src/errors/ConnectedAccountsErrors.ts +158 -0
  41. package/src/errors/ConnectionRequestErrors.ts +32 -0
  42. package/src/errors/FileModifierErrors.ts +100 -0
  43. package/src/errors/PusherErrors.ts +28 -0
  44. package/src/errors/RemoteFileErrors.ts +62 -0
  45. package/src/errors/SDKErrors.ts +92 -0
  46. package/src/errors/ToolErrors.ts +244 -0
  47. package/src/errors/ToolkitErrors.ts +39 -0
  48. package/src/errors/TriggerErrors.ts +120 -0
  49. package/src/errors/ValidationErrors.ts +99 -0
  50. package/src/errors/index.ts +41 -0
  51. package/src/experimental/index.ts +28 -0
  52. package/src/index.ts +64 -0
  53. package/src/lib/toolRouterConstants.ts +1 -0
  54. package/src/lib/toolRouterParams.ts +306 -0
  55. package/src/models/AuthConfigs.ts +398 -0
  56. package/src/models/AuthScheme.ts +206 -0
  57. package/src/models/ConnectedAccounts.ts +735 -0
  58. package/src/models/ConnectionRequest.ts +150 -0
  59. package/src/models/CustomTool.ts +676 -0
  60. package/src/models/Experimental.ts +202 -0
  61. package/src/models/Files.node.ts +93 -0
  62. package/src/models/Files.workerd.ts +49 -0
  63. package/src/models/MCP.ts +478 -0
  64. package/src/models/RemoteFile.ts +172 -0
  65. package/src/models/SessionContext.ts +147 -0
  66. package/src/models/Sessions.ts +21 -0
  67. package/src/models/ToolRouter.ts +391 -0
  68. package/src/models/ToolRouterSession.ts +827 -0
  69. package/src/models/ToolRouterSessionFileMount.ts +389 -0
  70. package/src/models/Toolkits.ts +412 -0
  71. package/src/models/Tools.ts +1260 -0
  72. package/src/models/Triggers.ts +1381 -0
  73. package/src/models/customToolExecution.ts +118 -0
  74. package/src/models/inlineCustomToolsPayload.ts +17 -0
  75. package/src/models/proxyParamsTransform.ts +26 -0
  76. package/src/provider/BaseProvider.ts +138 -0
  77. package/src/provider/ComposioProvider.ts +29 -0
  78. package/src/provider/OpenAIProvider.ts +547 -0
  79. package/src/services/internal/InternalService.ts +50 -0
  80. package/src/services/internal/InternalService.types.ts +14 -0
  81. package/src/services/pusher/Pusher.ts +230 -0
  82. package/src/services/telemetry/TelemetryService.ts +48 -0
  83. package/src/services/telemetry/TelemetryService.types.ts +67 -0
  84. package/src/telemetry/BatchProcessor.ts +77 -0
  85. package/src/telemetry/README.md +123 -0
  86. package/src/telemetry/Telemetry.ts +356 -0
  87. package/src/types/ToolRouterSessionFilesMount.types.ts +96 -0
  88. package/src/types/authConfigs.types.ts +174 -0
  89. package/src/types/composio.types.ts +1 -0
  90. package/src/types/connectedAccountAuthStates.types.ts +852 -0
  91. package/src/types/connectedAccounts.types.ts +395 -0
  92. package/src/types/connectionRequest.types.ts +16 -0
  93. package/src/types/customTool.types.ts +261 -0
  94. package/src/types/files.types.ts +15 -0
  95. package/src/types/mcp.experimental.types.ts +163 -0
  96. package/src/types/mcp.types.ts +362 -0
  97. package/src/types/modifiers.types.ts +663 -0
  98. package/src/types/org.types.ts +0 -0
  99. package/src/types/provider.types.ts +41 -0
  100. package/src/types/pusher.types.ts +18 -0
  101. package/src/types/requestOptions.types.ts +62 -0
  102. package/src/types/telemetry.types.ts +89 -0
  103. package/src/types/tool.types.ts +408 -0
  104. package/src/types/toolRouter.types.ts +761 -0
  105. package/src/types/toolkit.types.ts +130 -0
  106. package/src/types/triggers.types.ts +401 -0
  107. package/src/types/webhookEvents.types.ts +219 -0
  108. package/src/utils/buffer.ts +30 -0
  109. package/src/utils/cancellation.ts +22 -0
  110. package/src/utils/config-defaults/ConfigDefaults.node.ts +7 -0
  111. package/src/utils/config-defaults/ConfigDefaults.workerd.ts +10 -0
  112. package/src/utils/config-defaults/index.ts +1 -0
  113. package/src/utils/config-defaults/types.ts +14 -0
  114. package/src/utils/constants.ts +22 -0
  115. package/src/utils/crypto.ts +34 -0
  116. package/src/utils/env.ts +34 -0
  117. package/src/utils/fileDirs.ts +81 -0
  118. package/src/utils/fileUtils.node.ts +458 -0
  119. package/src/utils/json-schema.ts +1 -0
  120. package/src/utils/jsonSchema.ts +355 -0
  121. package/src/utils/logger.ts +99 -0
  122. package/src/utils/mime.ts +75 -0
  123. package/src/utils/modifiers/FileToolModifier.node.ts +477 -0
  124. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +132 -0
  125. package/src/utils/modifiers/FileToolModifier.workerd.ts +51 -0
  126. package/src/utils/pagination.ts +73 -0
  127. package/src/utils/pusher.ts +286 -0
  128. package/src/utils/schemaPropertyKeys.ts +433 -0
  129. package/src/utils/sdk.ts +110 -0
  130. package/src/utils/sensitiveFileUploadPaths.node.ts +105 -0
  131. package/src/utils/session.ts +114 -0
  132. package/src/utils/toolArguments.ts +73 -0
  133. package/src/utils/toolkitVersion.ts +26 -0
  134. package/src/utils/transform.ts +42 -0
  135. package/src/utils/transformers/authConfigs.ts +107 -0
  136. package/src/utils/transformers/connectedAccounts.ts +119 -0
  137. package/src/utils/transformers/mcp.ts +164 -0
  138. package/src/utils/transformers/toolRouterResponseTransform.ts +160 -0
  139. package/src/utils/transformers/toolkits.ts +100 -0
  140. package/src/utils/transformers/triggers.ts +118 -0
  141. package/src/utils/uploadDirAllowlist.node.ts +178 -0
  142. package/src/utils/uuid.ts +7 -0
  143. package/src/utils/version.ts +58 -0
  144. package/src/utils/zodSchema.ts +90 -0
@@ -0,0 +1,433 @@
1
+ /**
2
+ * JSON-schema property-key sanitization.
3
+ *
4
+ * Some providers constrain the characters and/or length of tool `input_schema`
5
+ * property keys (e.g. Anthropic's Messages API validates every key against
6
+ * `^[a-zA-Z0-9_.-]{1,64}$` and rejects the whole `tools` array on a single
7
+ * violation). Composio tool schemas can surface keys that break such rules —
8
+ * OData parameters like `$top` / `@microsoft.graph.conflictBehavior`, or
9
+ * over-long `__`-flattened keys.
10
+ *
11
+ * This module rewrites offending keys to conforming aliases before the schema is
12
+ * sent to the provider, and records a reverse mapping so the original parameter
13
+ * names can be restored before a tool call is executed against the Composio
14
+ * backend. The *constraint* (which keys are valid and how an illegal key is
15
+ * rewritten) is injected as a {@link KeySanitizationPolicy} so the mechanism
16
+ * stays provider-agnostic; the traversal, collision handling, reverse mapping,
17
+ * prototype safety and depth cap live here.
18
+ *
19
+ * The reverse mapping mirrors the schema's nesting (object `properties`, array
20
+ * `items`/`prefixItems`, and the composition keywords `allOf`/`anyOf`/`oneOf` /
21
+ * `not`/`if`/`then`/`else`, whose renames fold into the value level they share)
22
+ * rather than being a single flat lookup. This matters because an alias generated
23
+ * at one nesting level (e.g. `$top` -> `dollar_top`) must not rewrite a
24
+ * legitimately-named `dollar_top` key that happens to exist at a different level.
25
+ * Keys nested only under dynamic / `$ref` positions (`additionalProperties`,
26
+ * `patternProperties`, `$defs`/`definitions`, `contains`) are still rewritten so
27
+ * the provider accepts the schema, but are not restored — see the keyword lists
28
+ * below. Dereferencing the schema first (see `dereferenceJsonSchema`) inlines
29
+ * `$ref`/`$defs` into restorable value positions, shrinking that residual gap.
30
+ *
31
+ * @packageDocumentation
32
+ * @module utils/schemaPropertyKeys
33
+ */
34
+
35
+ import { isPlainObject } from './modifiers/FileToolModifier.utils.neutral';
36
+
37
+ /** Maximum schema nesting we traverse, matching `dereferenceJsonSchema`'s cap. */
38
+ const MAX_SCHEMA_DEPTH = 512;
39
+
40
+ /**
41
+ * Provider-specific key constraint. The mechanism reserves every already-valid
42
+ * sibling key before aliasing, so {@link aliasKey} only needs to produce a
43
+ * conforming alias that is distinct from the supplied `taken` set.
44
+ */
45
+ export interface KeySanitizationPolicy {
46
+ /** Whether a key already conforms to the provider's constraint. */
47
+ isValidKey(key: string): boolean;
48
+ /**
49
+ * Produce a conforming alias for an illegal `key`, guaranteed distinct from
50
+ * every entry in `taken` (the already-assigned keys at the same object level).
51
+ */
52
+ aliasKey(key: string, taken: ReadonlySet<string>): string;
53
+ }
54
+
55
+ /**
56
+ * Reverse mapping used to restore original property names at execution time.
57
+ *
58
+ * It is shaped like the schema it was derived from so restoration is scoped to
59
+ * the exact location a rename happened:
60
+ * - `renames` — `sanitized -> original` for keys renamed at *this* value level
61
+ * (including renames folded in from composition keywords).
62
+ * - `children` — restoration mapping for the value under each (sanitized) key,
63
+ * keyed by the sanitized key. Only present for children that contain renames.
64
+ * - `items` — restoration mapping for array element values. A single mapping
65
+ * applies to every element; an array of mappings applies positionally (JSON
66
+ * Schema tuple validation / `prefixItems`). Only present when array elements
67
+ * contain renames.
68
+ * - `restItems` — restoration mapping for array elements *past* a positional
69
+ * `items`/`prefixItems` tuple (a 2020-12 single `items` schema sitting next to
70
+ * `prefixItems`). Only present when those trailing elements contain renames.
71
+ */
72
+ export interface KeyMapping {
73
+ renames: Record<string, string>;
74
+ children: Record<string, KeyMapping>;
75
+ items?: KeyMapping | (KeyMapping | null)[];
76
+ restItems?: KeyMapping;
77
+ }
78
+
79
+ /** Whether a mapping (or any of its descendants) actually renames a key. */
80
+ export function mappingHasRenames(mapping: KeyMapping): boolean {
81
+ // `children` and `items` are only populated when they carry renames (see
82
+ // `sanitizeNode`), so this stays a shallow check.
83
+ return (
84
+ Object.keys(mapping.renames).length > 0 ||
85
+ Object.keys(mapping.children).length > 0 ||
86
+ mapping.items != null ||
87
+ mapping.restItems != null
88
+ );
89
+ }
90
+
91
+ /**
92
+ * Composition/applicator keywords whose sub-schema(s) constrain the *same* value
93
+ * as the parent. Property-key renames generated inside them are merged into the
94
+ * parent's value level, because the value carries no extra nesting for these
95
+ * keywords. `not`/`if`/`then`/`else` hold a single sub-schema; `allOf`/`anyOf`/
96
+ * `oneOf` hold an array of sub-schemas.
97
+ */
98
+ const COMPOSITION_SINGLE_KEYWORDS = ['not', 'if', 'then', 'else'] as const;
99
+ const COMPOSITION_LIST_KEYWORDS = ['allOf', 'anyOf', 'oneOf'] as const;
100
+
101
+ /**
102
+ * Positions whose nested keys are rewritten so the provider accepts the schema,
103
+ * but which we cannot tie to a concrete value position for restoration: dynamic
104
+ * keys (`additionalProperties`, `patternProperties`) and `$ref` targets (`$defs`/
105
+ * `definitions`, unresolved unless the caller dereferences first), plus
106
+ * `contains`. A value filled via an alias generated here reaches the backend
107
+ * un-restored — strictly better than the whole `tools` array being rejected.
108
+ */
109
+ const REWRITE_ONLY_SINGLE_KEYWORDS = ['additionalProperties', 'contains'] as const;
110
+ const REWRITE_ONLY_MAP_KEYWORDS = ['patternProperties', '$defs', 'definitions'] as const;
111
+
112
+ /**
113
+ * Sanitizes a single sub-schema. Returns the rewritten node and its mapping, or
114
+ * a `null` mapping when nothing inside it was renamed (keeps mappings sparse).
115
+ */
116
+ function sanitizeSubschema(
117
+ value: unknown,
118
+ policy: KeySanitizationPolicy,
119
+ depth: number
120
+ ): { node: unknown; mapping: KeyMapping | null } {
121
+ if (!isPlainObject(value)) {
122
+ return { node: value, mapping: null };
123
+ }
124
+ const { node, mapping } = sanitizeNode(value, policy, depth + 1);
125
+ return { node, mapping: mappingHasRenames(mapping) ? mapping : null };
126
+ }
127
+
128
+ /** Sanitizes an array of positional sub-schemas (tuple `items` / `prefixItems`). */
129
+ function sanitizeTuple(
130
+ entries: unknown[],
131
+ policy: KeySanitizationPolicy,
132
+ depth: number
133
+ ): { nodes: unknown[]; mappings: (KeyMapping | null)[] | undefined } {
134
+ const nodes: unknown[] = [];
135
+ const mappings: (KeyMapping | null)[] = [];
136
+ let anyRenamed = false;
137
+ for (const entry of entries) {
138
+ const { node, mapping } = sanitizeSubschema(entry, policy, depth);
139
+ nodes.push(node);
140
+ mappings.push(mapping);
141
+ if (mapping) anyRenamed = true;
142
+ }
143
+ return { nodes, mappings: anyRenamed ? mappings : undefined };
144
+ }
145
+
146
+ /**
147
+ * Rewrites the nested keys of a `{ name -> sub-schema }` map (e.g. `$defs`,
148
+ * `patternProperties`). The map's own keys are names/patterns, not value
149
+ * property keys, so they are left untouched and no restoration mapping is kept.
150
+ */
151
+ function sanitizeSchemaMap(
152
+ map: Record<string, unknown>,
153
+ policy: KeySanitizationPolicy,
154
+ depth: number
155
+ ): Record<string, unknown> {
156
+ const out: Record<string, unknown> = Object.create(null);
157
+ for (const [key, value] of Object.entries(map)) {
158
+ out[key] = sanitizeSubschema(value, policy, depth).node;
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /**
164
+ * Merges `source`'s renames into `target`, both describing the same value level
165
+ * (used to fold composition branches into their parent). `target` wins on
166
+ * conflict, since it is the more direct (`properties`-level) mapping.
167
+ *
168
+ * Known limitation: folding sibling `allOf`/`anyOf`/`oneOf` branches into one
169
+ * value level is lossy when two branches disagree on an alias. If branch A aliases
170
+ * an illegal key to `X` while branch B has a distinct illegal key that also aliases
171
+ * to `X` — or a *legitimate* property literally named `X` — only the first-seen
172
+ * entry survives, so an argument that satisfied the other branch restores to the
173
+ * wrong original name. Which branch a runtime value matched can't be recovered from
174
+ * the value alone (that needs full schema evaluation against the value), so these
175
+ * cross-branch collisions stay effectively rewrite-only — still strictly better
176
+ * than the whole `tools` array being rejected. They are rare in practice.
177
+ */
178
+ function mergeMappingInto(target: KeyMapping, source: KeyMapping): void {
179
+ for (const [alias, original] of Object.entries(source.renames)) {
180
+ if (!(alias in target.renames)) {
181
+ target.renames[alias] = original;
182
+ }
183
+ }
184
+ for (const [key, childSource] of Object.entries(source.children)) {
185
+ const existing = target.children[key];
186
+ if (existing) {
187
+ mergeMappingInto(existing, childSource);
188
+ } else {
189
+ target.children[key] = childSource;
190
+ }
191
+ }
192
+ if (target.items === undefined && source.items !== undefined) {
193
+ target.items = source.items;
194
+ if (source.restItems !== undefined) {
195
+ target.restItems = source.restItems;
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Recursively sanitizes the property keys of a JSON-schema node, returning the
202
+ * rewritten node and a {@link KeyMapping} shaped like the node. Traversal covers
203
+ * object `properties`, array `items`/`prefixItems`, the composition keywords
204
+ * (`allOf`/`anyOf`/`oneOf`, `not`/`if`/`then`/`else` — whose renames merge into
205
+ * this level), and the rewrite-only positions in {@link REWRITE_ONLY_SINGLE_KEYWORDS}
206
+ * / {@link REWRITE_ONLY_MAP_KEYWORDS}.
207
+ *
208
+ * The input node is never mutated; a new node is returned.
209
+ */
210
+ function sanitizeNode(
211
+ node: Record<string, unknown>,
212
+ policy: KeySanitizationPolicy,
213
+ depth = 0
214
+ ): {
215
+ node: Record<string, unknown>;
216
+ mapping: KeyMapping;
217
+ } {
218
+ if (depth >= MAX_SCHEMA_DEPTH) {
219
+ throw new Error(
220
+ `Tool schema nesting exceeded the maximum supported depth (${MAX_SCHEMA_DEPTH})`
221
+ );
222
+ }
223
+
224
+ const result: Record<string, unknown> = { ...node };
225
+ // Lookup/result tables are prototype-free so a property key that collides with
226
+ // an `Object.prototype` member (`__proto__`, `constructor`, `toString`, …)
227
+ // becomes a plain own entry instead of resolving to (or reparenting via) the
228
+ // inherited member. Mirrors the `POLLUTING_KEYS` defense in `jsonSchema.ts`.
229
+ const renames: Record<string, string> = Object.create(null);
230
+ const children: Record<string, KeyMapping> = Object.create(null);
231
+ const mapping: KeyMapping = { renames, children };
232
+
233
+ const properties = node.properties;
234
+ if (isPlainObject(properties)) {
235
+ const newProperties: Record<string, unknown> = Object.create(null);
236
+ const renamedOriginalToSanitized: Record<string, string> = Object.create(null);
237
+
238
+ // Reserve all already-valid keys up front so they keep their exact names and
239
+ // sanitized aliases are generated around them (a valid `dollar_top` must not
240
+ // be clobbered by a sanitized `$top`).
241
+ const taken = new Set<string>();
242
+ for (const key of Object.keys(properties)) {
243
+ if (policy.isValidKey(key)) {
244
+ taken.add(key);
245
+ }
246
+ }
247
+
248
+ for (const [key, rawValue] of Object.entries(properties)) {
249
+ const safeKey = policy.isValidKey(key) ? key : policy.aliasKey(key, taken);
250
+ taken.add(safeKey);
251
+
252
+ const { node: childNode, mapping: childMapping } = sanitizeSubschema(rawValue, policy, depth);
253
+ newProperties[safeKey] = childNode;
254
+ if (childMapping) {
255
+ children[safeKey] = childMapping;
256
+ }
257
+
258
+ if (safeKey !== key) {
259
+ renames[safeKey] = key;
260
+ renamedOriginalToSanitized[key] = safeKey;
261
+ }
262
+ }
263
+
264
+ result.properties = newProperties;
265
+
266
+ // Keep `required` in sync with the renamed keys at this level.
267
+ if (Array.isArray(node.required)) {
268
+ result.required = node.required.map(name =>
269
+ typeof name === 'string' && renamedOriginalToSanitized[name]
270
+ ? renamedOriginalToSanitized[name]
271
+ : name
272
+ );
273
+ }
274
+ }
275
+
276
+ // Array element schemas come from up to two positional sources — a Draft-7
277
+ // `items` tuple and the 2020-12 `prefixItems` tuple — plus one "applies to every
278
+ // element" source, a single `items` schema. When `prefixItems` provides the
279
+ // positional mapping, a sibling single `items` schema constrains the elements
280
+ // *past* the tuple (2020-12 semantics); its renames are kept separately as
281
+ // `restItems` so those tail elements restore too instead of being dropped (or
282
+ // the rest mapping bleeding onto the tuple positions). Restoration reaches array
283
+ // elements through `mapping.items`/`mapping.restItems` — a `properties`-only walk
284
+ // would let illegal keys nested in elements through and still be rejected.
285
+ const itemsSchema = node.items;
286
+ let positionalItems: (KeyMapping | null)[] | undefined;
287
+ let uniformItems: KeyMapping | undefined;
288
+ if (isPlainObject(itemsSchema)) {
289
+ const { node: childNode, mapping: childMapping } = sanitizeSubschema(
290
+ itemsSchema,
291
+ policy,
292
+ depth
293
+ );
294
+ result.items = childNode;
295
+ if (childMapping) {
296
+ uniformItems = childMapping;
297
+ }
298
+ } else if (Array.isArray(itemsSchema)) {
299
+ const { nodes, mappings } = sanitizeTuple(itemsSchema, policy, depth);
300
+ result.items = nodes;
301
+ positionalItems = mappings;
302
+ }
303
+ if (Array.isArray(node.prefixItems)) {
304
+ const { nodes, mappings } = sanitizeTuple(node.prefixItems, policy, depth);
305
+ result.prefixItems = nodes;
306
+ // `prefixItems` is the 2020-12 positional keyword; use it for the positional
307
+ // mapping when a Draft-7 `items` tuple didn't already provide one.
308
+ if (positionalItems === undefined) {
309
+ positionalItems = mappings;
310
+ }
311
+ }
312
+ if (positionalItems) {
313
+ mapping.items = positionalItems;
314
+ // A single `items` schema sitting next to a `prefixItems` tuple describes the
315
+ // elements after the tuple; keep its mapping so they restore positionally.
316
+ if (uniformItems && Array.isArray(node.prefixItems)) {
317
+ mapping.restItems = uniformItems;
318
+ }
319
+ } else if (uniformItems) {
320
+ mapping.items = uniformItems;
321
+ }
322
+
323
+ // Composition keywords constrain the *same* value, so renames generated inside
324
+ // them are merged into this level (the value has no extra nesting for them).
325
+ for (const keyword of COMPOSITION_SINGLE_KEYWORDS) {
326
+ const sub = node[keyword];
327
+ if (isPlainObject(sub)) {
328
+ const { node: childNode, mapping: childMapping } = sanitizeSubschema(sub, policy, depth);
329
+ result[keyword] = childNode;
330
+ if (childMapping) {
331
+ mergeMappingInto(mapping, childMapping);
332
+ }
333
+ }
334
+ }
335
+ for (const keyword of COMPOSITION_LIST_KEYWORDS) {
336
+ const list = node[keyword];
337
+ if (Array.isArray(list)) {
338
+ result[keyword] = list.map(entry => {
339
+ const { node: childNode, mapping: childMapping } = sanitizeSubschema(entry, policy, depth);
340
+ if (childMapping) {
341
+ mergeMappingInto(mapping, childMapping);
342
+ }
343
+ return childNode;
344
+ });
345
+ }
346
+ }
347
+
348
+ // Rewrite-only positions: keys are made compliant, but no restoration mapping
349
+ // is kept (see the keyword lists above for why).
350
+ for (const keyword of REWRITE_ONLY_SINGLE_KEYWORDS) {
351
+ const sub = node[keyword];
352
+ if (isPlainObject(sub)) {
353
+ result[keyword] = sanitizeSubschema(sub, policy, depth).node;
354
+ }
355
+ }
356
+ for (const keyword of REWRITE_ONLY_MAP_KEYWORDS) {
357
+ const sub = node[keyword];
358
+ if (isPlainObject(sub)) {
359
+ result[keyword] = sanitizeSchemaMap(sub, policy, depth);
360
+ }
361
+ }
362
+
363
+ return { node: result, mapping };
364
+ }
365
+
366
+ /**
367
+ * Sanitizes a tool `input_schema` so all property keys conform to `policy`.
368
+ *
369
+ * @param schema - The tool input schema to sanitize.
370
+ * @param policy - Provider constraint describing valid keys and how to rewrite
371
+ * illegal ones.
372
+ * @returns The sanitized schema (a copy) and a {@link KeyMapping} for restoring
373
+ * the original keys. Use {@link mappingHasRenames} to tell whether
374
+ * anything was rewritten.
375
+ */
376
+ export function sanitizeSchemaPropertyKeys<T extends Record<string, unknown>>(
377
+ schema: T,
378
+ policy: KeySanitizationPolicy
379
+ ): { schema: T; mapping: KeyMapping } {
380
+ const { node, mapping } = sanitizeNode(schema, policy);
381
+ return { schema: node as T, mapping };
382
+ }
383
+
384
+ /**
385
+ * Restores original property names in a tool-call argument object using the
386
+ * mapping produced by {@link sanitizeSchemaPropertyKeys}. The mapping is walked
387
+ * in lockstep with the value, so a key is only renamed at the nesting level where
388
+ * its alias was actually generated. Nested objects and arrays are handled
389
+ * recursively. Returns a new value; the input is not mutated.
390
+ */
391
+ export function restoreOriginalKeys(value: unknown, mapping: KeyMapping, depth = 0): unknown {
392
+ if (depth >= MAX_SCHEMA_DEPTH) {
393
+ throw new Error(
394
+ `Tool arguments nesting exceeded the maximum supported depth (${MAX_SCHEMA_DEPTH})`
395
+ );
396
+ }
397
+
398
+ if (Array.isArray(value)) {
399
+ const { items, restItems } = mapping;
400
+ if (Array.isArray(items)) {
401
+ return value.map((item, index) => {
402
+ // Elements inside the tuple use their positional mapping; elements past it
403
+ // use the trailing single-`items` rest mapping (2020-12), if any.
404
+ const itemMapping = index < items.length ? items[index] : restItems;
405
+ return itemMapping ? restoreOriginalKeys(item, itemMapping, depth + 1) : item;
406
+ });
407
+ }
408
+ if (items) {
409
+ return value.map(item => restoreOriginalKeys(item, items, depth + 1));
410
+ }
411
+ return value;
412
+ }
413
+
414
+ if (isPlainObject(value)) {
415
+ // Prototype-free so a model-supplied key equal to an `Object.prototype`
416
+ // member name (`__proto__`, `constructor`, …) is written as a plain own
417
+ // property rather than reparenting the result or hitting an inherited member.
418
+ const restored: Record<string, unknown> = Object.create(null);
419
+ for (const [key, val] of Object.entries(value)) {
420
+ // `renames`/`children` are themselves prototype-free (see `sanitizeNode`),
421
+ // so these lookups return `undefined` for non-own keys instead of an
422
+ // inherited function — no spurious rename and no crash on recursion.
423
+ const originalKey = mapping.renames[key] ?? key;
424
+ const childMapping = mapping.children[key];
425
+ restored[originalKey] = childMapping
426
+ ? restoreOriginalKeys(val, childMapping, depth + 1)
427
+ : val;
428
+ }
429
+ return restored;
430
+ }
431
+
432
+ return value;
433
+ }
@@ -0,0 +1,110 @@
1
+ import { ComposioNoAPIKeyError } from '../errors/SDKErrors';
2
+ import { COMPOSIO_DIR, DEFAULT_BASE_URL, USER_DATA_FILE_NAME } from './constants';
3
+ import { getEnvsWithPrefix, getEnvVariable } from './env';
4
+ import logger from './logger';
5
+ import { ComposioError } from '../errors/ComposioError';
6
+ import { ToolkitVersion, ToolkitVersionParam, ToolkitVersions } from '../types/tool.types';
7
+ import { platform } from '#platform';
8
+
9
+ // File path helpers
10
+ export const userDataPath = () => {
11
+ try {
12
+ const homeDir = platform.homedir();
13
+ if (!homeDir) {
14
+ return null;
15
+ }
16
+ return platform.joinPath(homeDir, COMPOSIO_DIR, USER_DATA_FILE_NAME);
17
+ } catch (_error) {
18
+ logger.debug('Environment', `Unable to get user data path`);
19
+ return null;
20
+ }
21
+ };
22
+
23
+ /**
24
+ * Reads and parses the user data JSON file from the Composio directory.
25
+ *
26
+ * @returns The parsed user data object containing user configuration (api_key, base_url, etc.), or empty object if file doesn't exist or can't be read
27
+ */
28
+ export const getUserDataJson = () => {
29
+ try {
30
+ const dataPath = userDataPath();
31
+ if (!dataPath || !platform.supportsFileSystem) {
32
+ return {};
33
+ }
34
+ const data = platform.readFileSync(dataPath, 'utf8');
35
+ return JSON.parse(data as string);
36
+ } catch (_error) {
37
+ logger.debug('Environment', 'No user data file found');
38
+ return {};
39
+ }
40
+ };
41
+
42
+ // Client configuration functions
43
+ export function getSDKConfig(baseUrl?: string | null, apiKey?: string | null) {
44
+ const userData = getUserDataJson();
45
+ const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
46
+
47
+ const baseURLParsed =
48
+ baseUrl || getEnvVariable('COMPOSIO_BASE_URL') || baseURLFromUserConfig || DEFAULT_BASE_URL;
49
+ const apiKeyParsed = apiKey || getEnvVariable('COMPOSIO_API_KEY') || apiKeyFromUserConfig || '';
50
+
51
+ if (!apiKeyParsed) {
52
+ ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
53
+ }
54
+
55
+ logger.debug('Environment', `API Key: ${apiKeyParsed}`);
56
+ logger.debug('Environment', `Base URL: ${baseURLParsed}`);
57
+
58
+ return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
59
+ }
60
+
61
+ /**
62
+ * Gets toolkit versions configuration by merging environment variables, user-provided defaults, and fallbacks.
63
+ *
64
+ * Priority order:
65
+ * 1. If defaultVersions is a string, use it as global version for all toolkits
66
+ * 2. Environment variables (COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME>)
67
+ * 3. User-provided toolkit version mappings (defaultVersions object)
68
+ * 4. Fallback to 'latest' if no versions are configured
69
+ *
70
+ * @param defaultVersions - Optional default versions configuration (string for global version or object mapping toolkit names to versions)
71
+ * @returns Toolkit versions configuration - either a global version string, toolkit-specific version mapping, or 'latest'
72
+ */
73
+ export function getToolkitVersionsFromEnv(
74
+ defaultVersions?: ToolkitVersionParam
75
+ ): ToolkitVersionParam {
76
+ // if already set by user either a single version or 'latest' use that as is / override everything else
77
+ if (defaultVersions && typeof defaultVersions === 'string') {
78
+ return defaultVersions;
79
+ }
80
+
81
+ // check if there are envs similar to COMPOSIO_TOOLKIT_VERSION_GITHUB then extract the toolkit name
82
+ const envPrefixedVersions = getEnvsWithPrefix(`COMPOSIO_TOOLKIT_VERSION_`);
83
+ const toolkitVersionsFromEnv = Object.entries(envPrefixedVersions).reduce((acc, [key, value]) => {
84
+ const toolkitName = key.replace('COMPOSIO_TOOLKIT_VERSION_', '');
85
+ acc[toolkitName.toLowerCase()] = value as ToolkitVersion;
86
+ return acc;
87
+ }, {} as ToolkitVersions);
88
+
89
+ // if the provided default versions is an object, normalize the keys to be lower case
90
+ // use user provided values as overrides
91
+ let userProvidedToolkitVersions = {};
92
+ if (defaultVersions && typeof defaultVersions === 'object') {
93
+ userProvidedToolkitVersions = Object.fromEntries(
94
+ Object.entries(defaultVersions).map(([key, value]) => [key.toLowerCase(), value])
95
+ );
96
+ }
97
+
98
+ // final toolkit versions
99
+ const toolkitVersions = {
100
+ ...toolkitVersionsFromEnv,
101
+ ...userProvidedToolkitVersions,
102
+ };
103
+
104
+ // if the toolkitVersions are empty, use 'latest'
105
+ if (Object.keys(toolkitVersions).length === 0) {
106
+ return 'latest';
107
+ }
108
+
109
+ return toolkitVersions;
110
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Blocks accidental upload of local files from well-known secret/credential locations
3
+ * during auto file upload (and {@link getFileDataAfterUploadingToS3}).
4
+ */
5
+ import * as path from 'node:path';
6
+ import fs from 'node:fs';
7
+ import { ComposioSensitiveFilePathBlockedError } from '../errors/FileModifierErrors';
8
+
9
+ /**
10
+ * Path segments (a single path component) that indicate a sensitive directory when
11
+ * they appear anywhere in a resolved local path. Compared case-insensitively on Windows.
12
+ */
13
+ export const BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS: readonly string[] = [
14
+ '.ssh',
15
+ '.aws',
16
+ '.azure',
17
+ '.gnupg',
18
+ '.kube',
19
+ '.docker',
20
+ '.claude', // may contain API keys and project context read by assistants
21
+ '.password-store',
22
+ 'keychains', // e.g. ~/Library/Keychains
23
+ ];
24
+
25
+ const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
26
+ /** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
27
+ const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
28
+
29
+ /**
30
+ * Returns normalized path segments, resolving symlinks when the path exists.
31
+ */
32
+ function normalizePathSegments(filePath: string): string[] {
33
+ const absolute = path.resolve(filePath);
34
+ let resolved = absolute;
35
+ try {
36
+ if (fs.existsSync(absolute)) {
37
+ resolved = fs.realpathSync(absolute);
38
+ }
39
+ } catch {
40
+ // If realpath fails (e.g. race), use resolved path
41
+ }
42
+ return resolved.split(/[/\\]+/).filter(Boolean);
43
+ }
44
+
45
+ /**
46
+ * True if the path is under a built-in or extra deny segment, or the basename
47
+ * looks like an env / netrc / default SSH private key name.
48
+ */
49
+ export function isBlockedSensitiveFileUploadPath(
50
+ filePath: string,
51
+ additionalDenySegments?: string[]
52
+ ): boolean {
53
+ return getSensitiveFileUploadPathBlockReason(filePath, additionalDenySegments) != null;
54
+ }
55
+
56
+ function getSensitiveFileUploadPathBlockReason(
57
+ filePath: string,
58
+ additionalDenySegments?: string[]
59
+ ): string | null {
60
+ const segments = normalizePathSegments(filePath);
61
+ const isWin = process.platform === 'win32';
62
+ const deny = new Set(
63
+ [
64
+ ...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
65
+ ...(additionalDenySegments ?? []).map(s => s.trim()).filter(Boolean),
66
+ ].map(s => (isWin ? s.toLowerCase() : s))
67
+ );
68
+
69
+ // Windows: compare segments case-insensitively; map once instead of toLowerCase per iteration.
70
+ const segmentsForMatch = isWin ? segments.map(s => s.toLowerCase()) : segments;
71
+ for (let i = 0; i < segments.length; i++) {
72
+ if (deny.has(segmentsForMatch[i]!)) {
73
+ return `path segment "${segments[i]}" is in the sensitive file upload denylist`;
74
+ }
75
+ }
76
+
77
+ const basename = segments.length > 0 ? segments[segments.length - 1] : '';
78
+ if (basename) {
79
+ if (SECRET_LIKE_BASENAME.test(basename) || DEFAULT_PRIVATE_KEY_BASENAME.test(basename)) {
80
+ return `file name "${basename}" looks like a credential, env, or private key file`;
81
+ }
82
+ if (basename.toLowerCase() === 'credentials') {
83
+ return 'file name "credentials" is often used for cloud/API credential stores';
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ /**
90
+ * @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed
91
+ */
92
+ export function assertSafeFileUploadPath(
93
+ filePath: string,
94
+ options?: { additionalDenySegments?: string[] }
95
+ ): void {
96
+ const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);
97
+ if (reason) {
98
+ throw new ComposioSensitiveFilePathBlockedError(
99
+ `Refusing to upload: ${reason}. ` +
100
+ `To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio ` +
101
+ `(not recommended) or use a copy outside sensitive locations.`,
102
+ { meta: { filePath, reason } }
103
+ );
104
+ }
105
+ }