@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
@@ -9,6 +9,7 @@ import type {
9
9
  SessionConfigHistoryResponse,
10
10
  SessionCreateResponse,
11
11
  SessionExecuteMetaParams,
12
+ SessionExecuteParams,
12
13
  } from '@composio/client/resources/tool-router/session/session.mjs';
13
14
  import type {
14
15
  CustomTool,
@@ -109,6 +110,39 @@ export const ToolRouterToolkitsEnabledConfigSchema = z
109
110
  })
110
111
  .strict();
111
112
 
113
+ /**
114
+ * Toolkits whose tools need the user's approval before they run. A call that
115
+ * needs approval doesn't run: `session.execute()` throws
116
+ * `ComposioToolInputRequiredError` with the question to show the user.
117
+ * @experimental
118
+ */
119
+ const ToolRouterToolkitsRequireApprovalSchema = ToolRouterToolkitsParamSchema.describe(
120
+ 'Experimental. Toolkits whose tools need the user approval before they run'
121
+ );
122
+
123
+ /** Session toolkit policy: a list to enable, an enable/disable object, or only an approval list. */
124
+ const ToolRouterSessionToolkitsSchema = z.union([
125
+ ToolRouterToolkitsParamSchema,
126
+ ToolRouterToolkitsDisabledConfigSchema.extend({
127
+ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional(),
128
+ }).strict(),
129
+ ToolRouterToolkitsEnabledConfigSchema.extend({
130
+ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional(),
131
+ }).strict(),
132
+ z.object({ requireApproval: ToolRouterToolkitsRequireApprovalSchema }).strict(),
133
+ ]);
134
+
135
+ /**
136
+ * What happens to a call that needs the user's approval when the session's MCP
137
+ * client can't ask the user.
138
+ * @experimental
139
+ */
140
+ const ToolRouterNoElicitationSupportFallbackSchema = z
141
+ .enum(['deny', 'allow'])
142
+ .describe(
143
+ 'Experimental. What happens to a call that needs approval when the MCP client cannot ask the user'
144
+ );
145
+
112
146
  /** Experimental Instant usage policy for a Session. */
113
147
  export const ToolRouterInstantSchema = z.union([
114
148
  z.literal(false),
@@ -175,6 +209,13 @@ export const ToolRouterTagsEnableDisableSchema = z
175
209
  disable: ToolRouterTagsParamSchema.optional().describe(
176
210
  'The tags to disable in the tool router session'
177
211
  ),
212
+ /**
213
+ * Tools with any of these tags need the user's approval before they run.
214
+ * @experimental
215
+ */
216
+ requireApproval: ToolRouterTagsParamSchema.optional().describe(
217
+ 'Experimental. Tools with any of these tags need the user approval before they run'
218
+ ),
178
219
  })
179
220
  .strict();
180
221
  export const ToolRouterConfigTagsSchema = z
@@ -209,6 +250,14 @@ export const ToolRouterToolsParamSchema = z
209
250
  .describe('The tools to use in the tool router session');
210
251
  export type ToolRouterToolsParam = z.infer<typeof ToolRouterToolsParamSchema>;
211
252
 
253
+ /**
254
+ * Tools of the toolkit that need the user's approval before they run.
255
+ * @experimental
256
+ */
257
+ const ToolRouterToolsRequireApprovalSchema = ToolRouterToolsParamSchema.describe(
258
+ 'Experimental. Tools of this toolkit that need the user approval before they run'
259
+ );
260
+
212
261
  export const ToolRouterConfigToolsSchema = z
213
262
  .union([
214
263
  ToolRouterToolsParamSchema,
@@ -217,6 +266,7 @@ export const ToolRouterConfigToolsSchema = z
217
266
  enable: ToolRouterToolsParamSchema.describe(
218
267
  'The tools to enable in the tool router session'
219
268
  ),
269
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
220
270
  })
221
271
  .strict(),
222
272
  z
@@ -224,6 +274,7 @@ export const ToolRouterConfigToolsSchema = z
224
274
  disable: ToolRouterToolsParamSchema.describe(
225
275
  'The tools to disable in the tool router session'
226
276
  ),
277
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
227
278
  })
228
279
  .strict(),
229
280
  z
@@ -231,13 +282,15 @@ export const ToolRouterConfigToolsSchema = z
231
282
  tags: ToolRouterConfigTagsSchema.describe(
232
283
  'The tags to filter the tools by, this will override the global tags'
233
284
  ),
285
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
234
286
  })
235
287
  .strict(),
288
+ z.object({ requireApproval: ToolRouterToolsRequireApprovalSchema }).strict(),
236
289
  ])
237
290
  .superRefine((val, ctx) => {
238
- // If it's an object (not an array), ensure only one property is present
291
+ // If it's an object (not an array), allow at most one of enable, disable and tags
239
292
  if (typeof val === 'object' && !Array.isArray(val)) {
240
- const keys = Object.keys(val);
293
+ const keys = Object.keys(val).filter(key => key !== 'requireApproval');
241
294
  if (keys.length > 1) {
242
295
  ctx.addIssue({
243
296
  code: z.ZodIssueCode.custom,
@@ -299,14 +352,9 @@ const ToolRouterCreateSessionConfigBaseSchema = z
299
352
 
300
353
  tags: ToolRouterConfigTagsSchema.optional().describe('Global tags to filter the tools by'),
301
354
 
302
- toolkits: z
303
- .union([
304
- ToolRouterToolkitsParamSchema,
305
- ToolRouterToolkitsDisabledConfigSchema,
306
- ToolRouterToolkitsEnabledConfigSchema,
307
- ])
308
- .optional()
309
- .describe('The toolkits to use in the tool router session'),
355
+ toolkits: ToolRouterSessionToolkitsSchema.optional().describe(
356
+ 'The toolkits to use in the tool router session'
357
+ ),
310
358
 
311
359
  instant: ToolRouterInstantSchema.optional().describe(
312
360
  'Experimental Instant usage policy. Omission permits eligible tools when the project allows Instant usage; false disables it for this Session.'
@@ -411,6 +459,13 @@ const ToolRouterCreateSessionConfigBaseSchema = z
411
459
  .describe(
412
460
  'ID of a saved Session config (`sc_…`) to apply when the session is created. Cannot be combined with toolkits, tools, tags, customTools or customToolkits.'
413
461
  ),
462
+ /**
463
+ * What happens to a call that needs the user's approval when the
464
+ * session's MCP client can't ask the user: `deny` (the default) or
465
+ * `allow`.
466
+ * @experimental
467
+ */
468
+ noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
414
469
  })
415
470
  .optional()
416
471
  .describe('Experimental features configuration - not stable, may be modified or removed'),
@@ -470,7 +525,7 @@ export const ToolRouterCreateSessionConfigSchema = z
470
525
  * @param {SessionPreset} [sessionPreset] - Shortcut that exposes every tool allowed by the session filters directly in session.tools() and the MCP tool list. Disables search, multi-execute, manage-connections, and sandbox by default; explicit overrides for supported fields still win. Without this preset, ToolRouter uses the default configuration with meta tools enabled.
471
526
  * @param {ToolRouterToolkitsParamSchema | ToolRouterToolkitsDisabledConfigSchema | ToolRouterToolkitsEnabledConfigSchema} toolkits - The toolkits to use in the tool router session
472
527
  * @param {Record<string, ToolRouterToolsParam | ToolRouterConfigTools>} tools - The tools to configure per toolkit (key is toolkit slug)
473
- * @param {Array<'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'>} tags - Global tags to filter tools by behavior
528
+ * @param {Array<'readOnlyHint' | 'createHint' | 'updateHint' | 'destructiveHint'>} tags - Global tags to filter tools by the type of action they take
474
529
  * @param {Record<string, string>} authConfigs - The auth configs to use in the tool router session
475
530
  * @param {Record<string, string | string[]>} connectedAccounts - The connected accounts to use in the tool router session. A single string is coerced to a single-element array before being sent to the backend.
476
531
  * @param {ToolRouterInstant} [instant] - Experimental Instant usage policy. The project must allow Instant usage.
@@ -773,17 +828,48 @@ export interface ToolRouterSessionExecuteOptions {
773
828
  * COMPOSIO_MULTI_EXECUTE_TOOL.tools[].account.
774
829
  */
775
830
  account?: string;
831
+ /**
832
+ * The user's answers to the questions of a `ComposioToolInputRequiredError`,
833
+ * keyed by the IDs in its `inputRequests`. Send them by repeating the same
834
+ * call (same tool and arguments). An approved call runs; a denied or
835
+ * declined one returns `resultType: 'failed'`.
836
+ * @experimental
837
+ */
838
+ inputResponses?: Record<string, ToolRouterInputResponse>;
839
+ /**
840
+ * The `requestState` of the `ComposioToolInputRequiredError`, sent back
841
+ * unchanged with `inputResponses`.
842
+ * @experimental
843
+ */
844
+ requestState?: string;
776
845
  }
777
846
 
847
+ /**
848
+ * The user's answer to one question, in the shape of an MCP elicitation
849
+ * result: `accept` with the form's fields in `content`, `decline` when they
850
+ * said no, or `cancel` when they dismissed it. For an approval, `content` is
851
+ * `{ decision: 'approve' }`, `{ decision: 'always_approve' }` or
852
+ * `{ decision: 'deny' }`.
853
+ * @experimental
854
+ */
855
+ export type ToolRouterInputResponse = NonNullable<SessionExecuteParams['input_responses']>[string];
856
+
778
857
  /**
779
858
  * Slug of a Composio meta tool (`COMPOSIO_*`) that `session.executeMeta()` can
780
859
  * run, for example `COMPOSIO_SEARCH_TOOLS`.
781
860
  */
782
861
  export type ToolRouterSessionMetaToolSlug = SessionExecuteMetaParams['slug'];
783
862
 
863
+ /** Options for `session.executeMeta()`: the user's answers to an earlier `input_required` call. */
864
+ export type ToolRouterSessionExecuteMetaOptions = Pick<
865
+ ToolRouterSessionExecuteOptions,
866
+ 'inputResponses' | 'requestState'
867
+ >;
868
+
784
869
  export type ToolRouterSessionExecuteMetaFn = (
785
870
  slug: ToolRouterSessionMetaToolSlug,
786
871
  arguments_?: Record<string, unknown>,
872
+ options?: ToolRouterSessionExecuteMetaOptions,
787
873
  requestOptions?: ComposioRequestOptions
788
874
  ) => Promise<ToolRouterSessionExecuteResponse>;
789
875
 
@@ -925,6 +1011,12 @@ export const ToolRouterUpdateExperimentalSchema = z
925
1011
  .describe(
926
1012
  'Exposes the COMPOSIO_SUBMIT_FEEDBACK helper tool. `null` removes the stored block'
927
1013
  ),
1014
+ /**
1015
+ * What happens to a call that needs the user's approval when the session's
1016
+ * MCP client can't ask the user: `deny` or `allow`.
1017
+ * @experimental
1018
+ */
1019
+ noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
928
1020
  sessionConfigId: z
929
1021
  .string()
930
1022
  .min(1)
@@ -947,13 +1039,7 @@ export const ToolRouterUpdateSessionConfigSchema = z
947
1039
  instant: ToolRouterInstantSchema.optional().describe(
948
1040
  '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.'
949
1041
  ),
950
- toolkits: z
951
- .union([
952
- ToolRouterToolkitsParamSchema,
953
- ToolRouterToolkitsDisabledConfigSchema,
954
- ToolRouterToolkitsEnabledConfigSchema,
955
- ])
956
- .nullable()
1042
+ toolkits: ToolRouterSessionToolkitsSchema.nullable()
957
1043
  .optional()
958
1044
  .describe(
959
1045
  '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'
@@ -515,11 +515,17 @@ export function jsonSchemaToZodSchema<T extends z.ZodTypeAny>(
515
515
  * added to it and widened to accept `null`, the emulation of optional
516
516
  * fields that OpenAI structured outputs document.
517
517
  * - `unsupported-keyword-stripped` — an annotation keyword the API rejects
518
- * (`default`, `examples`) was removed.
518
+ * (`default`, `examples`, or a string `format` outside the accepted list)
519
+ * was removed.
519
520
  * - `one-of-converted` — `oneOf` (unsupported) became `anyOf`.
521
+ * - `nullable-converted` — OpenAPI `nullable: true`, which Anthropic rejects
522
+ * on an object, became a `null` member of `type` or a null branch.
520
523
  */
521
524
  export type StrictSchemaChangeReason =
522
- 'optional-property-nullable' | 'unsupported-keyword-stripped' | 'one-of-converted';
525
+ | 'optional-property-nullable'
526
+ | 'unsupported-keyword-stripped'
527
+ | 'one-of-converted'
528
+ | 'nullable-converted';
523
529
 
524
530
  /** A single lossless rewrite applied by {@link toStrictJsonSchema}. */
525
531
  export interface StrictSchemaChange {
@@ -567,6 +573,27 @@ const MAX_STRICT_CHANGES = 50;
567
573
  /** Annotation-only keywords OpenAI structured outputs rejects; safe to strip. */
568
574
  const STRICT_STRIP_KEYWORDS = new Set(['examples', 'default']);
569
575
 
576
+ /**
577
+ * The `format` values OpenAI structured outputs accepts on a string schema,
578
+ * matched case-sensitively; any other value there is rejected with a 400.
579
+ * Formats on number and integer schemas are not checked.
580
+ */
581
+ const STRICT_STRING_FORMATS = new Set([
582
+ 'date-time',
583
+ 'time',
584
+ 'date',
585
+ 'duration',
586
+ 'email',
587
+ 'hostname',
588
+ 'ipv4',
589
+ 'ipv6',
590
+ 'uuid',
591
+ ]);
592
+
593
+ /** Whether a `type` value admits strings; an absent `type` admits every type. */
594
+ const admitsString = (type: unknown): boolean =>
595
+ type === undefined || type === 'string' || (Array.isArray(type) && type.includes('string'));
596
+
570
597
  /** Keywords OpenAI structured outputs reject and that have no lossless rewrite. */
571
598
  const STRICT_UNSUPPORTED_KEYWORDS = [
572
599
  'allOf',
@@ -676,6 +703,11 @@ function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown
676
703
  * the one it was given: the rewrite types every node that declares
677
704
  * `properties` as an object, so such a node stops accepting null.
678
705
  *
706
+ * `followRefs: false` makes every `$ref` reject null without resolving it.
707
+ * Folding `nullable` needs that, because a `$ref` can lead back to the node
708
+ * being folded, whose source still accepts null. It costs at most a
709
+ * redundant null branch.
710
+ *
679
711
  * One check serves a whole document, and an answer is computed once per node.
680
712
  * A reference cycle never yields a null by itself, so a node met again while
681
713
  * it is being evaluated counts as rejecting. An answer that leans on that is
@@ -690,7 +722,8 @@ function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown
690
722
  */
691
723
  function createNullCheck(
692
724
  root: Record<string, unknown>,
693
- strictOutput = false
725
+ strictOutput = false,
726
+ followRefs = true
694
727
  ): (schema: unknown) => boolean {
695
728
  // Markers for what an answer leans on, besides the depth of a node on the path.
696
729
  const NOTHING = MAX_NULL_CHECK_DEPTH + 1;
@@ -769,12 +802,16 @@ function createNullCheck(
769
802
  };
770
803
 
771
804
  const keywordsAccept = (node: Record<string, unknown>): boolean => {
805
+ // OpenAPI `nullable: true` admits null whatever the other keywords say,
806
+ // as the Zod conversion reads it.
807
+ if (node.nullable === true) return true;
772
808
  if (typeof node.type === 'string' && node.type !== 'null') return false;
773
809
  if (Array.isArray(node.type) && !node.type.includes('null')) return false;
774
810
  if (strictOutput && !('type' in node) && isPlainObject(node.properties)) return false;
775
811
  if (Array.isArray(node.enum) && !node.enum.includes(null)) return false;
776
812
  if ('const' in node && node.const !== null) return false;
777
813
  if ('$ref' in node) {
814
+ if (!followRefs) return false;
778
815
  const resolution =
779
816
  typeof node.$ref === 'string' ? tryResolvePointer(root, node.$ref) : undefined;
780
817
  if (resolution === undefined || resolution.kind === 'unresolved') return false;
@@ -811,7 +848,9 @@ function createNullCheck(
811
848
  * sends for such a property means "omitted"; the strict providers drop it
812
849
  * before executing the tool (see {@link omitNullToolArguments});
813
850
  * - `type` arrays are kept as-is (the API accepts them); `oneOf` becomes
814
- * `anyOf`; `default` and `examples` are stripped;
851
+ * `anyOf`; `default`, `examples`, and a string `format` the API does
852
+ * not accept are stripped; OpenAPI `nullable` is stripped too, and a
853
+ * node that set it to `true` is widened to accept `null`;
815
854
  * - local `$ref`s into `$defs`/`definitions` are kept (the API supports
816
855
  * them, including recursion) and the definitions themselves are
817
856
  * normalized; an optional `$ref` property is widened with an `anyOf`
@@ -841,6 +880,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
841
880
 
842
881
  const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
843
882
  const acceptsNullInOutput = createNullCheck(root, true);
883
+ const acceptsNullWithoutRefs = createNullCheck(root, true, false);
844
884
 
845
885
  function walkChildren(
846
886
  node: Record<string, unknown>,
@@ -892,6 +932,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
892
932
 
893
933
  const node: Record<string, unknown> = {};
894
934
  for (const [key, child] of Object.entries(value)) {
935
+ if (key === 'nullable') continue;
895
936
  if (STRICT_STRIP_KEYWORDS.has(key)) {
896
937
  recordChange({
897
938
  path,
@@ -900,6 +941,19 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
900
941
  });
901
942
  continue;
902
943
  }
944
+ if (
945
+ key === 'format' &&
946
+ typeof child === 'string' &&
947
+ !STRICT_STRING_FORMATS.has(child) &&
948
+ admitsString(value.type)
949
+ ) {
950
+ recordChange({
951
+ path,
952
+ reason: 'unsupported-keyword-stripped',
953
+ detail: `format "${child}" removed`,
954
+ });
955
+ continue;
956
+ }
903
957
  setOwn(node, key, child);
904
958
  }
905
959
  if (Array.isArray(node.oneOf) && node.anyOf === undefined) {
@@ -932,6 +986,24 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
932
986
  unsupported.push({ path, keyword: 'properties', detail: 'properties is not an object' });
933
987
  }
934
988
 
989
+ const normalized = normalizeNode(node, mode, depth, path);
990
+ if (!('nullable' in value)) return normalized;
991
+ const widened =
992
+ value.nullable === true ? widenToNullable(normalized, acceptsNullWithoutRefs) : normalized;
993
+ recordChange(
994
+ widened === normalized
995
+ ? { path, reason: 'unsupported-keyword-stripped', detail: 'keyword "nullable" removed' }
996
+ : { path, reason: 'nullable-converted', detail: 'nullable became a null type' }
997
+ );
998
+ return widened;
999
+ }
1000
+
1001
+ function normalizeNode(
1002
+ node: Record<string, unknown>,
1003
+ mode: StrictWalkMode,
1004
+ depth: number,
1005
+ path: string
1006
+ ): Record<string, unknown> {
935
1007
  const out = walkChildren(node, mode, depth, path);
936
1008
 
937
1009
  if (typeof node.$ref === 'string') {
package/src/utils/sdk.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { z } from 'zod/v3';
2
+ import { Auth } from '@composio/client';
3
+ import type { Scope } from '@composio/client';
2
4
  import {
3
5
  ComposioAPIKeyKindError,
4
6
  ComposioNoAPIKeyError,
@@ -29,12 +31,29 @@ const USER_API_KEY_PREFIX = 'uak_';
29
31
  */
30
32
  export const PROJECT_API_KEY_HEADER = 'x-api-key';
31
33
 
34
+ /** Header that carries the organization API key (`oak_...`). */
35
+ export const ORG_API_KEY_HEADER = 'x-org-api-key';
36
+
32
37
  /** Header carrying the organization nano ID that scopes user-key requests. */
33
38
  export const ORG_ID_HEADER = 'x-org-id';
34
39
 
35
40
  /** Header carrying the project nano ID that scopes user-key requests. */
36
41
  export const PROJECT_ID_HEADER = 'x-project-id';
37
42
 
43
+ /**
44
+ * Header names the SDK owns: the API client sends a credential from its
45
+ * `auth` and the scope from its `scope`, and refuses these names in its
46
+ * `defaultHeaders`. The SDK folds caller-supplied entries into its own
47
+ * credential and scope options instead of forwarding them.
48
+ */
49
+ const SDK_OWNED_HEADERS = [
50
+ PROJECT_API_KEY_HEADER,
51
+ USER_API_KEY_HEADER,
52
+ ORG_API_KEY_HEADER,
53
+ ORG_ID_HEADER,
54
+ PROJECT_ID_HEADER,
55
+ ];
56
+
38
57
  // File path helpers
39
58
  export const userDataPath = () => {
40
59
  try {
@@ -138,8 +157,13 @@ const findHeader = (
138
157
  */
139
158
  export const getUserApiKeyHeader = (
140
159
  headers: ComposioRequestHeaders | undefined
160
+ ): { name: string; value: string } | undefined => getCredentialHeader(headers, USER_API_KEY_HEADER);
161
+
162
+ const getCredentialHeader = (
163
+ headers: ComposioRequestHeaders | undefined,
164
+ name: string
141
165
  ): { name: string; value: string } | undefined => {
142
- const header = findHeader(headers, USER_API_KEY_HEADER);
166
+ const header = findHeader(headers, name);
143
167
  return header && typeof header.value === 'string' && header.value.length > 0 ? header : undefined;
144
168
  };
145
169
 
@@ -148,6 +172,8 @@ export type CredentialHeaderInput = {
148
172
  apiKey: string | null | undefined;
149
173
  /** The user API key the client resolved (`userApiKey` option or `COMPOSIO_USER_API_KEY`). */
150
174
  userApiKey: string | null | undefined;
175
+ /** The organization API key the client resolved (`orgApiKey` option or `COMPOSIO_ORG_API_KEY`). */
176
+ orgApiKey?: string | null;
151
177
  /** The default headers configured on the SDK instance; only `x-user-api-key` is consulted. */
152
178
  defaultHeaders: ComposioRequestHeaders | undefined;
153
179
  };
@@ -158,8 +184,9 @@ export type CredentialHeaderInput = {
158
184
  * headers wins: the client treats a caller-placed credential header as the
159
185
  * credential and suppresses the configured keys. Otherwise the project key
160
186
  * travels as `x-api-key`, otherwise the resolved user API key as
161
- * `x-user-api-key`. Empty when no credential is held. The environment is
162
- * never consulted here.
187
+ * `x-user-api-key`, otherwise the organization API key as `x-org-api-key`
188
+ * (the order {@link toClientAuth} picks them in). Empty when no credential is
189
+ * held. The environment is never consulted here.
163
190
  */
164
191
  export const resolveCredentialHeaders = (input: CredentialHeaderInput): Record<string, string> => {
165
192
  const userApiKeyHeader = getUserApiKeyHeader(input.defaultHeaders);
@@ -172,6 +199,9 @@ export const resolveCredentialHeaders = (input: CredentialHeaderInput): Record<s
172
199
  if (hasValue(input.userApiKey)) {
173
200
  return { [USER_API_KEY_HEADER]: input.userApiKey };
174
201
  }
202
+ if (hasValue(input.orgApiKey)) {
203
+ return { [ORG_API_KEY_HEADER]: input.orgApiKey };
204
+ }
175
205
  return {};
176
206
  };
177
207
 
@@ -242,11 +272,29 @@ export function resolveSDKScope(options: SDKScopeOptions): SDKScope {
242
272
  return orgId === undefined || projectId === undefined ? {} : { orgId, projectId };
243
273
  }
244
274
 
245
- /** The `x-org-id` / `x-project-id` headers for a resolved scope. */
246
- export const getScopeHeaders = (scope: SDKScope): ComposioRequestHeaders =>
275
+ /**
276
+ * The API client `scope` for a resolved SDK scope: the organization and
277
+ * project nano IDs the client sends as `x-org-id` / `x-project-id`, or
278
+ * `undefined` when the instance is unscoped.
279
+ */
280
+ export const toClientScope = (scope: SDKScope): Scope | undefined =>
247
281
  scope.orgId && scope.projectId
248
- ? { [ORG_ID_HEADER]: scope.orgId, [PROJECT_ID_HEADER]: scope.projectId }
249
- : {};
282
+ ? { organizationId: scope.orgId, projectId: scope.projectId }
283
+ : undefined;
284
+
285
+ /**
286
+ * `headers` without the credential and scope entries the SDK owns (matched
287
+ * case-insensitively). Those travel through the API client's `auth` and
288
+ * `scope`, which refuse the same names in `defaultHeaders`.
289
+ */
290
+ export const withoutSDKOwnedHeaders = (
291
+ headers: ComposioRequestHeaders | undefined
292
+ ): ComposioRequestHeaders | undefined =>
293
+ headers === undefined
294
+ ? undefined
295
+ : Object.fromEntries(
296
+ Object.entries(headers).filter(([name]) => !SDK_OWNED_HEADERS.includes(name.toLowerCase()))
297
+ );
250
298
 
251
299
  export type SDKConfigOptions = {
252
300
  /** Default headers the SDK will attach to every request. */
@@ -297,15 +345,127 @@ const resolveAlternateCredential = (
297
345
  export const resolveUserApiKey = (userApiKey: string | null | undefined): string | undefined =>
298
346
  resolveAlternateCredential(userApiKey, 'COMPOSIO_USER_API_KEY');
299
347
 
348
+ /**
349
+ * The organization API key the instance holds: the `orgApiKey` option when it
350
+ * was passed (including `null`, which disables the fallback), otherwise
351
+ * `COMPOSIO_ORG_API_KEY`.
352
+ */
353
+ export const resolveOrgApiKey = (orgApiKey: string | null | undefined): string | undefined =>
354
+ resolveAlternateCredential(orgApiKey, 'COMPOSIO_ORG_API_KEY');
355
+
300
356
  /**
301
357
  * Whether the instance holds a credential other than the project key: a user
302
358
  * or organization API key (explicit or environment-resolved, as the API client
303
- * will see it), or a user API key placed in the default headers.
359
+ * will see it), or a user or organization API key placed in the default
360
+ * headers, which {@link resolveSDKCredentials} folds in.
304
361
  */
305
362
  const hasAlternateCredential = (options: SDKConfigOptions): boolean =>
306
363
  resolveUserApiKey(options.userApiKey) !== undefined ||
307
- resolveAlternateCredential(options.orgApiKey, 'COMPOSIO_ORG_API_KEY') !== undefined ||
308
- getUserApiKeyHeader(options.defaultHeaders) !== undefined;
364
+ resolveOrgApiKey(options.orgApiKey) !== undefined ||
365
+ getUserApiKeyHeader(options.defaultHeaders) !== undefined ||
366
+ getCredentialHeader(options.defaultHeaders, ORG_API_KEY_HEADER) !== undefined;
367
+
368
+ /**
369
+ * The credentials an SDK instance authenticates with, after the environment
370
+ * fallbacks and the credential default headers are applied. `null` is a
371
+ * credential the instance does not hold.
372
+ */
373
+ export type SDKCredentials = {
374
+ /** The project API key, or `null` when project-key auth is disabled. */
375
+ apiKey: string | null;
376
+ /** The user API key (`uak_...`), or `null`. */
377
+ userApiKey: string | null;
378
+ /** The organization API key (`oak_...`), or `null`. */
379
+ orgApiKey: string | null;
380
+ };
381
+
382
+ export type SDKCredentialsInput = {
383
+ /** The project API key {@link getSDKConfig} resolved. */
384
+ apiKey: string | null;
385
+ /** The `userApiKey` option as passed: `undefined` falls back to `COMPOSIO_USER_API_KEY`. */
386
+ userApiKey?: string | null;
387
+ /** The `orgApiKey` option as passed: `undefined` falls back to `COMPOSIO_ORG_API_KEY`. */
388
+ orgApiKey?: string | null;
389
+ /** Default headers the caller configured; only the credential headers are read. */
390
+ defaultHeaders?: ComposioRequestHeaders;
391
+ };
392
+
393
+ const CREDENTIAL_HEADERS = [PROJECT_API_KEY_HEADER, USER_API_KEY_HEADER, ORG_API_KEY_HEADER];
394
+
395
+ /**
396
+ * Resolves the credentials of an SDK instance.
397
+ *
398
+ * The user and organization keys fall back to `COMPOSIO_USER_API_KEY` and
399
+ * `COMPOSIO_ORG_API_KEY` when their option is omitted. A non-empty credential
400
+ * header in `defaultHeaders` (any letter case) is folded in as the credential
401
+ * it names, and it is the credential the instance sends, as it was when the
402
+ * header itself went on the wire: an `x-user-api-key` or `x-org-api-key` entry
403
+ * disables the project key and takes the place of the configured user or
404
+ * organization key, and an `x-api-key` entry takes the place of the project
405
+ * key. At most one credential header may be set: the API rejects a request
406
+ * that carries two.
407
+ */
408
+ export function resolveSDKCredentials(input: SDKCredentialsInput): SDKCredentials {
409
+ const headers = CREDENTIAL_HEADERS.flatMap(name => {
410
+ const header = findHeader(input.defaultHeaders, name);
411
+ return header && hasValue(header.value) ? [{ ...header, canonical: name }] : [];
412
+ });
413
+ if (headers.length > 1) {
414
+ throw new ComposioError('`defaultHeaders` carries more than one credential header', {
415
+ cause: `The API accepts exactly one credential per request, and \`defaultHeaders\` sets ${headers
416
+ .map(header => `\`${header.name}\``)
417
+ .join(' and ')}`,
418
+ possibleFixes: [
419
+ 'Pass credentials through `apiKey`, `userApiKey` and `orgApiKey` instead of default headers',
420
+ 'Keep at most one of `x-api-key`, `x-user-api-key` and `x-org-api-key` in `defaultHeaders`',
421
+ ],
422
+ });
423
+ }
424
+ const userApiKey = resolveUserApiKey(input.userApiKey) ?? null;
425
+ const orgApiKey = resolveOrgApiKey(input.orgApiKey) ?? null;
426
+ const [header] = headers;
427
+ switch (header?.canonical) {
428
+ case USER_API_KEY_HEADER:
429
+ return { apiKey: null, userApiKey: header.value, orgApiKey };
430
+ case ORG_API_KEY_HEADER:
431
+ return { apiKey: null, userApiKey: null, orgApiKey: header.value };
432
+ case PROJECT_API_KEY_HEADER:
433
+ return { apiKey: header.value, userApiKey, orgApiKey };
434
+ default:
435
+ return { apiKey: input.apiKey, userApiKey, orgApiKey };
436
+ }
437
+ }
438
+
439
+ /**
440
+ * The API client `auth` for the credentials of an SDK instance.
441
+ *
442
+ * - A project key alone authenticates every request with it.
443
+ * - A project key with a user and/or organization key selects one per
444
+ * operation: the project key wherever the operation accepts it, otherwise
445
+ * the first declared scheme a key is held for.
446
+ * - Without a project key, the user key authenticates every request (sessions
447
+ * included, whose operations declare no scheme), and the organization key
448
+ * does when it is the only one held.
449
+ */
450
+ export const toClientAuth = (credentials: SDKCredentials): Auth => {
451
+ const { apiKey, userApiKey, orgApiKey } = credentials;
452
+ if (apiKey !== null) {
453
+ return userApiKey === null && orgApiKey === null
454
+ ? Auth.project(apiKey)
455
+ : Auth.auto({
456
+ project: apiKey,
457
+ user: userApiKey ?? undefined,
458
+ organization: orgApiKey ?? undefined,
459
+ });
460
+ }
461
+ if (userApiKey !== null) {
462
+ return Auth.user(userApiKey);
463
+ }
464
+ if (orgApiKey !== null) {
465
+ return Auth.organization(orgApiKey);
466
+ }
467
+ throw new ComposioNoAPIKeyError();
468
+ };
309
469
 
310
470
  /**
311
471
  * Resolves the base URL and project API key the SDK will use.
@@ -318,7 +478,8 @@ const hasAlternateCredential = (options: SDKConfigOptions): boolean =>
318
478
  * `api_key` is read, and the resolver only succeeds when the instance holds
319
479
  * another credential: a `userApiKey` or `orgApiKey` (explicit, or resolved
320
480
  * from `COMPOSIO_USER_API_KEY` / `COMPOSIO_ORG_API_KEY` the way the API
321
- * client does), or a non-empty `x-user-api-key` entry in `defaultHeaders`.
481
+ * client does), or a non-empty `x-user-api-key` or `x-org-api-key` entry in
482
+ * `defaultHeaders`.
322
483
  * An `x-api-key` entry in `defaultHeaders` (any letter case) is rejected in
323
484
  * that mode: the project credential is only ever set from `apiKey`.
324
485
  *