@composio/core 1.0.0-beta.0 → 1.0.0-beta.1

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 (82) hide show
  1. package/dist/{CustomTool-l-j5HtEf.mjs → CustomTool-CM-roKk7.mjs} +16 -6
  2. package/dist/{CustomTool-CwpeQhz2.d.mts → CustomTool-yMQjEyMz.d.mts} +1 -1
  3. package/dist/{FileModifierErrors-B8V8_3VE.mjs → FileModifierErrors-CdGSABoq.mjs} +1 -1
  4. package/dist/{FileToolModifier.utils.neutral-D_YkHwZP.mjs → FileToolModifier.utils.neutral-DWFpnsj2.mjs} +4 -2
  5. package/dist/{SsrfErrors-DNJt57GL.mjs → SsrfErrors-DiQldIdC.mjs} +154 -19
  6. package/dist/{Telemetry-DK1uAWnD.mjs → Telemetry-JRJJYS4I.mjs} +28 -44
  7. package/dist/cancellation-BEpFk2S8.mjs +706 -0
  8. package/dist/{composio-XjF7EMEe.d.mts → composio-BVNJTVYa.d.mts} +2450 -119
  9. package/dist/{customTool.types-DpJbYY5m.d.mts → customTool.types-CY5SXFfF.d.mts} +143 -28
  10. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +1 -1
  11. package/dist/docs/reference/sdk-reference/typescript/session.mdx +4 -3
  12. package/dist/{errors-BcEUHZbq.mjs → errors-CvZjP9CH.mjs} +42 -4
  13. package/dist/experimental/index.d.mts +2 -2
  14. package/dist/experimental/index.mjs +1 -1
  15. package/dist/{fileUtils.node-BwpUOF0s.mjs → fileUtils.node-HQsywtTj.mjs} +11 -9
  16. package/dist/index.d.mts +393 -142
  17. package/dist/index.mjs +1945 -171
  18. package/dist/models/Files.node.d.mts +2 -3
  19. package/dist/models/Files.node.mjs +2 -2
  20. package/dist/models/Files.workerd.d.mts +2 -3
  21. package/dist/platform/node.d.mts +2 -3
  22. package/dist/platform/workerd.d.mts +2 -3
  23. package/dist/{sensitiveFileUploadPaths-B0w8dqpv.mjs → sensitiveFileUploadPaths-BlLp-Yo2.mjs} +10 -7
  24. package/dist/{ssrfGuard.node-DlxO8uzr.mjs → ssrfGuard.node-BK50mYTq.mjs} +187 -24
  25. package/dist/{types-C9kJAurw.d.mts → types-CqGfjlZg.d.mts} +2 -2
  26. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +3 -4
  27. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +3 -4
  28. package/dist/utils/modifiers/FileToolModifier.node.d.mts +3 -4
  29. package/dist/utils/modifiers/FileToolModifier.node.mjs +6 -6
  30. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +3 -4
  31. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  32. package/dist/utils/ssrfGuard.node.d.mts +7 -7
  33. package/dist/utils/ssrfGuard.node.mjs +1 -1
  34. package/dist/utils/ssrfGuard.workerd.d.mts +3 -4
  35. package/dist/utils/ssrfGuard.workerd.mjs +2 -2
  36. package/package.json +25 -7
  37. package/src/composio.ts +86 -2
  38. package/src/errors/ConnectedAccountsErrors.ts +47 -0
  39. package/src/errors/ToolErrors.ts +1 -0
  40. package/src/errors/ValidationErrors.ts +2 -0
  41. package/src/index.ts +21 -0
  42. package/src/models/ConnectedAccounts.ts +118 -2
  43. package/src/models/CustomTool.ts +41 -6
  44. package/src/models/CustomToolkits.ts +169 -0
  45. package/src/models/Experimental.ts +27 -0
  46. package/src/models/Keyring.ts +65 -0
  47. package/src/models/Logs.ts +101 -0
  48. package/src/models/RemoteFile.ts +54 -36
  49. package/src/models/ToolRouterSession.ts +60 -4
  50. package/src/models/Toolkits.ts +180 -0
  51. package/src/models/Tools.ts +3 -1
  52. package/src/models/Triggers.ts +17 -87
  53. package/src/models/Usage.ts +119 -0
  54. package/src/models/Webhooks.ts +520 -0
  55. package/src/services/telemetry/TelemetryService.ts +27 -12
  56. package/src/telemetry/redact.ts +133 -6
  57. package/src/types/authConfigs.types.ts +2 -0
  58. package/src/types/connectedAccounts.types.ts +54 -0
  59. package/src/types/customToolkits.types.ts +102 -0
  60. package/src/types/keyring.types.ts +32 -0
  61. package/src/types/logs.types.ts +108 -0
  62. package/src/types/toolRouter.types.ts +49 -1
  63. package/src/types/toolkit.types.ts +131 -0
  64. package/src/types/usage.types.ts +81 -0
  65. package/src/types/webhooks.types.ts +143 -0
  66. package/src/utils/constants.ts +1 -5
  67. package/src/utils/fileUtils.node.ts +10 -2
  68. package/src/utils/jsonSchema.ts +509 -28
  69. package/src/utils/logger.ts +45 -13
  70. package/src/utils/pinnedDispatcher.node.ts +109 -13
  71. package/src/utils/sdk.ts +1 -1
  72. package/src/utils/ssrfGuard.node.ts +124 -21
  73. package/src/utils/ssrfGuard.workerd.ts +5 -1
  74. package/src/utils/transformers/connectedAccounts.ts +37 -2
  75. package/src/utils/transformers/customToolkits.ts +98 -0
  76. package/src/utils/transformers/keyring.ts +24 -0
  77. package/src/utils/transformers/logs.ts +85 -0
  78. package/src/utils/transformers/toolkits.ts +100 -1
  79. package/src/utils/transformers/triggers.ts +2 -2
  80. package/src/utils/transformers/usage.ts +77 -0
  81. package/src/utils/transformers/webhooks.ts +139 -0
  82. package/dist/cancellation-C-qy8rcj.mjs +0 -364
@@ -8,6 +8,33 @@ const MAX_REF_CHAIN_DEPTH = 100;
8
8
  const MAX_NODE_DEPTH = 512;
9
9
  const CYCLE_BREAK_SENTINEL = { type: 'object', additionalProperties: true } as const;
10
10
 
11
+ /** Keywords whose value is a single subschema. */
12
+ const SCHEMA_KEYWORDS = new Set([
13
+ 'additionalItems',
14
+ 'additionalProperties',
15
+ 'contains',
16
+ 'contentSchema',
17
+ 'else',
18
+ 'if',
19
+ 'not',
20
+ 'propertyNames',
21
+ 'then',
22
+ 'unevaluatedItems',
23
+ 'unevaluatedProperties',
24
+ ]);
25
+ /** Keywords whose value is an array of subschemas. */
26
+ const SCHEMA_ARRAY_KEYWORDS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
27
+ /** Keywords whose value is a map from name to subschema. */
28
+ const SCHEMA_MAP_KEYWORDS = new Set([
29
+ '$defs',
30
+ 'definitions',
31
+ 'dependentSchemas',
32
+ 'patternProperties',
33
+ 'properties',
34
+ ]);
35
+ /** Keywords whose values are instance data, never subschemas. */
36
+ const INSTANCE_VALUE_KEYWORDS = new Set(['const', 'default', 'enum', 'examples']);
37
+
11
38
  /**
12
39
  * In-band hint attached to the cycle-break sentinel when lenient mode
13
40
  * substitutes it for a dangling `$ref`. Makes the degradation visible to
@@ -272,28 +299,6 @@ export function dereferenceJsonSchema<T = unknown>(
272
299
  export function ensureObjectTypeOnProperties<T = unknown>(schema: T): T {
273
300
  type WalkMode = 'schema' | 'schema-array' | 'schema-map' | 'dependencies-map' | 'value';
274
301
 
275
- const schemaKeywords = new Set([
276
- 'additionalItems',
277
- 'additionalProperties',
278
- 'contains',
279
- 'contentSchema',
280
- 'else',
281
- 'if',
282
- 'not',
283
- 'propertyNames',
284
- 'then',
285
- 'unevaluatedItems',
286
- 'unevaluatedProperties',
287
- ]);
288
- const schemaArrayKeywords = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
289
- const schemaMapKeywords = new Set([
290
- '$defs',
291
- 'definitions',
292
- 'dependentSchemas',
293
- 'patternProperties',
294
- 'properties',
295
- ]);
296
-
297
302
  function walk(value: unknown, mode: WalkMode, depth = 0): unknown {
298
303
  if (depth > MAX_NODE_DEPTH) {
299
304
  throw new RangeError(`JSON Schema exceeds maximum nesting depth of ${MAX_NODE_DEPTH}`);
@@ -314,11 +319,11 @@ export function ensureObjectTypeOnProperties<T = unknown>(schema: T): T {
314
319
  } else if (mode === 'dependencies-map') {
315
320
  childMode = Array.isArray(child) ? 'value' : 'schema';
316
321
  } else if (mode === 'schema') {
317
- if (schemaMapKeywords.has(key)) {
322
+ if (SCHEMA_MAP_KEYWORDS.has(key)) {
318
323
  childMode = 'schema-map';
319
- } else if (schemaArrayKeywords.has(key) || (key === 'items' && Array.isArray(child))) {
324
+ } else if (SCHEMA_ARRAY_KEYWORDS.has(key) || (key === 'items' && Array.isArray(child))) {
320
325
  childMode = 'schema-array';
321
- } else if (schemaKeywords.has(key) || key === 'items') {
326
+ } else if (SCHEMA_KEYWORDS.has(key) || key === 'items') {
322
327
  childMode = 'schema';
323
328
  } else if (key === 'dependencies') {
324
329
  childMode = 'dependencies-map';
@@ -356,7 +361,6 @@ export function ensureObjectTypeOnProperties<T = unknown>(schema: T): T {
356
361
  export function deduplicateJsonSchemaRequiredArrays<T = unknown>(schema: T): T {
357
362
  const seenSchemaValues = new WeakMap<object, unknown>();
358
363
  const seenInstanceValues = new WeakMap<object, unknown>();
359
- const instanceValueKeywords = new Set(['const', 'default', 'enum', 'examples']);
360
364
 
361
365
  function walk(value: unknown, isSchema: boolean, depth = 0): unknown {
362
366
  if (depth > MAX_NODE_DEPTH) {
@@ -391,7 +395,7 @@ export function deduplicateJsonSchemaRequiredArrays<T = unknown>(schema: T): T {
391
395
  value:
392
396
  isSchema && key === 'required' && Array.isArray(child)
393
397
  ? [...new Set(walk(child, false, depth + 1) as unknown[])]
394
- : walk(child, isSchema && !instanceValueKeywords.has(key), depth + 1),
398
+ : walk(child, isSchema && !INSTANCE_VALUE_KEYWORDS.has(key), depth + 1),
395
399
  writable: true,
396
400
  });
397
401
  }
@@ -491,8 +495,485 @@ export function jsonSchemaToZodSchema<T extends z.ZodTypeAny>(
491
495
  const zodSchema = jsonSchemaToZod(schema) as T;
492
496
  return zodSchema;
493
497
  } catch (error) {
494
- throw new JsonSchemaToZodError('Failed to convert JSON Schema to Zod Schema', {
498
+ // The cause names the offending property path; surface it in the message
499
+ // so a single malformed property is identifiable without unwrapping.
500
+ const detail = error instanceof Error ? `: ${error.message}` : '';
501
+ throw new JsonSchemaToZodError(`Failed to convert JSON Schema to Zod Schema${detail}`, {
495
502
  cause: error,
496
503
  });
497
504
  }
498
505
  }
506
+
507
+ /**
508
+ * Reason recorded when strict normalization rewrites a schema node. Every
509
+ * rewrite is lossless: the model can still express the same values.
510
+ *
511
+ * - `optional-property-nullable` — a property missing from `required` was
512
+ * added to it and widened to accept `null`, the emulation of optional
513
+ * fields that OpenAI structured outputs document.
514
+ * - `unsupported-keyword-stripped` — an annotation keyword the API rejects
515
+ * (`default`, `examples`) was removed.
516
+ * - `one-of-converted` — `oneOf` (unsupported) became `anyOf`.
517
+ */
518
+ export type StrictSchemaChangeReason =
519
+ 'optional-property-nullable' | 'unsupported-keyword-stripped' | 'one-of-converted';
520
+
521
+ /** A single lossless rewrite applied by {@link toStrictJsonSchema}. */
522
+ export interface StrictSchemaChange {
523
+ /** Path to the changed node relative to the root, e.g. `properties.cfg.items`. */
524
+ path: string;
525
+ reason: StrictSchemaChangeReason;
526
+ /** Human-readable detail about what specifically changed. */
527
+ detail?: string;
528
+ }
529
+
530
+ /**
531
+ * A schema construct strict structured outputs cannot express. Rewriting it
532
+ * would change what the tool accepts, so it is reported instead; providers
533
+ * send such a tool without strict mode.
534
+ */
535
+ export interface StrictSchemaIncompatibility {
536
+ /** Path to the offending node relative to the root. */
537
+ path: string;
538
+ /** The keyword (or `$ref`) that has no strict-mode equivalent. */
539
+ keyword: string;
540
+ detail: string;
541
+ }
542
+
543
+ /** Result of {@link toStrictJsonSchema}. */
544
+ export interface StrictJsonSchemaResult {
545
+ /**
546
+ * The strict schema. Only usable when `unsupported` is empty; otherwise it
547
+ * is best-effort and the original schema should be sent without strict mode.
548
+ */
549
+ schema: Record<string, unknown>;
550
+ /**
551
+ * The input schema the rewrite was computed from. Optionality is decided
552
+ * against this schema, so it is what `omitNullToolArguments` needs.
553
+ */
554
+ source: Record<string, unknown>;
555
+ /** Lossless rewrites, capped at 50 entries; see `totalChanges`. */
556
+ changes: StrictSchemaChange[];
557
+ totalChanges: number;
558
+ /** Constructs strict mode cannot express. Non-empty means "do not use `schema`". */
559
+ unsupported: StrictSchemaIncompatibility[];
560
+ }
561
+
562
+ const MAX_STRICT_CHANGES = 50;
563
+
564
+ /** Annotation-only keywords OpenAI structured outputs rejects; safe to strip. */
565
+ const STRICT_STRIP_KEYWORDS = new Set(['examples', 'default']);
566
+
567
+ /** Keywords OpenAI structured outputs reject and that have no lossless rewrite. */
568
+ const STRICT_UNSUPPORTED_KEYWORDS = [
569
+ 'allOf',
570
+ 'prefixItems',
571
+ 'additionalItems',
572
+ 'contains',
573
+ 'dependencies',
574
+ 'dependentSchemas',
575
+ 'else',
576
+ 'if',
577
+ 'not',
578
+ 'propertyNames',
579
+ 'then',
580
+ 'unevaluatedItems',
581
+ 'unevaluatedProperties',
582
+ ];
583
+
584
+ /** Whether a `type` value declares exactly the object type. */
585
+ const isObjectType = (type: unknown): boolean =>
586
+ type === 'object' || (Array.isArray(type) && type.length === 1 && type[0] === 'object');
587
+
588
+ type StrictWalkMode = 'schema' | 'schema-array' | 'schema-map' | 'value';
589
+
590
+ const joinPath = (parent: string, key: string): string => (parent ? `${parent}.${key}` : key);
591
+
592
+ /**
593
+ * Sets an own property regardless of its name: a plain assignment to a key
594
+ * such as `__proto__` would set the prototype instead of storing the value.
595
+ */
596
+ function setOwn(target: Record<string, unknown>, key: string, value: unknown): void {
597
+ Object.defineProperty(target, key, {
598
+ configurable: true,
599
+ enumerable: true,
600
+ value,
601
+ writable: true,
602
+ });
603
+ }
604
+
605
+ /**
606
+ * Widens a property schema so that `null` is an accepted value, without
607
+ * placing `type` beside `anyOf` (the API rejects that combination).
608
+ */
609
+ function widenToNullable(node: Record<string, unknown>): Record<string, unknown> {
610
+ if (Array.isArray(node.anyOf)) {
611
+ const alreadyNullable = node.anyOf.some(
612
+ branch => isPlainObject(branch) && branch.type === 'null'
613
+ );
614
+ return alreadyNullable ? node : { ...node, anyOf: [...node.anyOf, { type: 'null' }] };
615
+ }
616
+ if (typeof node.type === 'string') {
617
+ return node.type === 'null' ? node : { ...node, type: [node.type, 'null'] };
618
+ }
619
+ if (Array.isArray(node.type)) {
620
+ return node.type.includes('null') ? node : { ...node, type: [...node.type, 'null'] };
621
+ }
622
+ if ((Array.isArray(node.enum) && node.enum.includes(null)) || node.const === null) return node;
623
+ // No `type` at all: an empty schema already accepts null; anything else
624
+ // (enum-only, const, composition) is wrapped so the annotation stays outside.
625
+ const { description, title, ...rest } = node;
626
+ if (Object.keys(rest).length === 0) return node;
627
+ return {
628
+ ...(description !== undefined ? { description } : {}),
629
+ ...(title !== undefined ? { title } : {}),
630
+ anyOf: [rest, { type: 'null' }],
631
+ };
632
+ }
633
+
634
+ /**
635
+ * Follows local `$ref` pointers from `node` until a concrete schema node is
636
+ * reached. Unresolvable or over-long chains return the last node seen.
637
+ */
638
+ function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown {
639
+ let current = node;
640
+ for (let hops = 0; hops < MAX_REF_CHAIN_DEPTH; hops++) {
641
+ if (!isPlainObject(current) || typeof current.$ref !== 'string') return current;
642
+ const resolution = tryResolvePointer(root, current.$ref);
643
+ if (resolution.kind === 'unresolved') return current;
644
+ current = resolution.value;
645
+ }
646
+ return current;
647
+ }
648
+
649
+ /** Whether a schema node accepts `null` as an instance. */
650
+ function schemaAcceptsNull(schema: unknown, root: Record<string, unknown>): boolean {
651
+ const node = resolveLocalRefs(schema, root);
652
+ if (!isPlainObject(node)) return true;
653
+ if (typeof node.type === 'string') return node.type === 'null';
654
+ if (Array.isArray(node.type)) return node.type.includes('null');
655
+ if (Array.isArray(node.enum)) return node.enum.includes(null);
656
+ if ('const' in node) return node.const === null;
657
+ for (const keyword of ['anyOf', 'oneOf']) {
658
+ const branches = node[keyword];
659
+ if (Array.isArray(branches)) return branches.some(branch => schemaAcceptsNull(branch, root));
660
+ }
661
+ return true;
662
+ }
663
+
664
+ /**
665
+ * Normalizes a tool parameter schema for OpenAI structured outputs
666
+ * (`strict: true`) at every depth, following the contract OpenAI documents:
667
+ *
668
+ * - every object lists all of its properties in `required` and sets
669
+ * `additionalProperties: false`;
670
+ * - properties that were optional stay available and are widened to accept
671
+ * `null` (`type: ['string', 'null']`, or an extra `anyOf` branch) — the
672
+ * documented way to emulate optional fields. Nothing is dropped, so the
673
+ * model keeps every parameter it could pass before. A `null` the model
674
+ * sends for such a property means "omitted"; the strict providers drop it
675
+ * before executing the tool (see {@link omitNullToolArguments});
676
+ * - `type` arrays are kept as-is (the API accepts them); `oneOf` becomes
677
+ * `anyOf`; `default` and `examples` are stripped;
678
+ * - local `$ref`s into `$defs`/`definitions` are kept (the API supports
679
+ * them, including recursion) and the definitions themselves are
680
+ * normalized; an optional `$ref` property is widened with an `anyOf`
681
+ * null branch;
682
+ * - constructs strict mode cannot express — objects that accept arbitrary
683
+ * keys (schema-valued or `true` `additionalProperties`, `patternProperties`,
684
+ * property-less free-form objects), boolean subschemas, `allOf`,
685
+ * `prefixItems`, tuple-form `items`, conditional and dependency keywords,
686
+ * external or dangling `$ref`s, and a non-object root — are reported in
687
+ * `unsupported` rather than rewritten into something narrower. Callers send
688
+ * such a tool without strict mode.
689
+ *
690
+ * The input is never mutated. Every rewrite is recorded in `changes` (capped
691
+ * at 50 entries; `totalChanges` carries the real count), and `required`
692
+ * arrays are de-duplicated at the end.
693
+ */
694
+ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
695
+ const changes: StrictSchemaChange[] = [];
696
+ const unsupported: StrictSchemaIncompatibility[] = [];
697
+ let totalChanges = 0;
698
+ const recordChange = (change: StrictSchemaChange): void => {
699
+ totalChanges += 1;
700
+ if (changes.length < MAX_STRICT_CHANGES) changes.push(change);
701
+ };
702
+
703
+ const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
704
+
705
+ function walkChildren(
706
+ node: Record<string, unknown>,
707
+ mode: StrictWalkMode,
708
+ depth: number,
709
+ path: string
710
+ ): Record<string, unknown> {
711
+ const clone: Record<string, unknown> = {};
712
+ for (const [key, child] of Object.entries(node)) {
713
+ let childMode: StrictWalkMode = 'value';
714
+ if (mode === 'schema-map') {
715
+ childMode = 'schema';
716
+ } else if (mode === 'schema' && !INSTANCE_VALUE_KEYWORDS.has(key)) {
717
+ if (SCHEMA_MAP_KEYWORDS.has(key)) {
718
+ childMode = 'schema-map';
719
+ } else if (SCHEMA_ARRAY_KEYWORDS.has(key) || (key === 'items' && Array.isArray(child))) {
720
+ childMode = 'schema-array';
721
+ } else if (SCHEMA_KEYWORDS.has(key) || key === 'items') {
722
+ childMode = 'schema';
723
+ }
724
+ }
725
+
726
+ if (childMode === 'schema-map' && isPlainObject(child)) {
727
+ const mapClone: Record<string, unknown> = {};
728
+ for (const [name, subSchema] of Object.entries(child)) {
729
+ setOwn(
730
+ mapClone,
731
+ name,
732
+ walk(subSchema, 'schema', depth + 1, joinPath(joinPath(path, key), name))
733
+ );
734
+ }
735
+ setOwn(clone, key, mapClone);
736
+ continue;
737
+ }
738
+ setOwn(clone, key, walk(child, childMode, depth + 1, joinPath(path, key)));
739
+ }
740
+ return clone;
741
+ }
742
+
743
+ function walk(value: unknown, mode: StrictWalkMode, depth: number, path: string): unknown {
744
+ if (depth > MAX_NODE_DEPTH) {
745
+ throw new RangeError(`JSON Schema exceeds maximum nesting depth of ${MAX_NODE_DEPTH}`);
746
+ }
747
+ if (Array.isArray(value)) {
748
+ const itemMode = mode === 'schema-array' ? 'schema' : 'value';
749
+ return value.map((item, index) => walk(item, itemMode, depth + 1, `${path}[${index}]`));
750
+ }
751
+ if (!isPlainObject(value) || mode === 'value') return value;
752
+
753
+ const node: Record<string, unknown> = {};
754
+ for (const [key, child] of Object.entries(value)) {
755
+ if (STRICT_STRIP_KEYWORDS.has(key)) {
756
+ recordChange({
757
+ path,
758
+ reason: 'unsupported-keyword-stripped',
759
+ detail: `keyword "${key}" removed`,
760
+ });
761
+ continue;
762
+ }
763
+ setOwn(node, key, child);
764
+ }
765
+ if (Array.isArray(node.oneOf) && node.anyOf === undefined) {
766
+ node.anyOf = node.oneOf;
767
+ delete node.oneOf;
768
+ recordChange({ path, reason: 'one-of-converted', detail: 'oneOf became anyOf' });
769
+ }
770
+ for (const keyword of STRICT_UNSUPPORTED_KEYWORDS) {
771
+ if (node[keyword] !== undefined) {
772
+ unsupported.push({
773
+ path,
774
+ keyword,
775
+ detail: `"${keyword}" has no strict-mode equivalent`,
776
+ });
777
+ }
778
+ }
779
+ if (node.oneOf !== undefined) {
780
+ unsupported.push({ path, keyword: 'oneOf', detail: 'oneOf beside anyOf cannot be merged' });
781
+ }
782
+ if (Array.isArray(node.items)) {
783
+ unsupported.push({
784
+ path,
785
+ keyword: 'items',
786
+ detail: 'tuple-form items has no strict-mode equivalent',
787
+ });
788
+ } else if (typeof node.items === 'boolean') {
789
+ unsupported.push({ path, keyword: 'items', detail: 'boolean subschema' });
790
+ }
791
+ if (node.properties !== undefined && !isPlainObject(node.properties)) {
792
+ unsupported.push({ path, keyword: 'properties', detail: 'properties is not an object' });
793
+ }
794
+
795
+ const out = walkChildren(node, mode, depth, path);
796
+
797
+ if (typeof node.$ref === 'string') {
798
+ const resolution =
799
+ node.$ref === '#' || node.$ref.startsWith('#/')
800
+ ? tryResolvePointer(root, node.$ref)
801
+ : ({ kind: 'unresolved', reason: 'malformed-pointer' } as const);
802
+ if (resolution.kind === 'unresolved') {
803
+ unsupported.push({
804
+ path,
805
+ keyword: '$ref',
806
+ detail: `unresolved $ref "${node.$ref}"`,
807
+ });
808
+ }
809
+ // The referenced definition is normalized where it is declared.
810
+ return out;
811
+ }
812
+
813
+ const declaresObjectType =
814
+ out.type === 'object' || (Array.isArray(out.type) && out.type.includes('object'));
815
+ if (!declaresObjectType && !isPlainObject(out.properties)) return out;
816
+ if (out.properties !== undefined && !isPlainObject(out.properties)) return out;
817
+
818
+ const properties: Record<string, unknown> = {};
819
+ if (isPlainObject(out.properties)) {
820
+ for (const [name, propertySchema] of Object.entries(out.properties)) {
821
+ setOwn(properties, name, propertySchema);
822
+ }
823
+ }
824
+ const declaredRequired = new Set(
825
+ Array.isArray(out.required) ? out.required.filter(entry => typeof entry === 'string') : []
826
+ );
827
+ for (const [name, propertySchema] of Object.entries(properties)) {
828
+ if (typeof propertySchema === 'boolean') {
829
+ unsupported.push({
830
+ path: joinPath(path, `properties.${name}`),
831
+ keyword: 'properties',
832
+ detail: 'boolean subschema',
833
+ });
834
+ continue;
835
+ }
836
+ if (declaredRequired.has(name) || !isPlainObject(propertySchema)) continue;
837
+ setOwn(properties, name, widenToNullable(propertySchema));
838
+ recordChange({
839
+ path: joinPath(path, `properties.${name}`),
840
+ reason: 'optional-property-nullable',
841
+ detail: `property "${name}" is now required and accepts null`,
842
+ });
843
+ }
844
+
845
+ const acceptsDynamicKeys =
846
+ out.additionalProperties === true || isPlainObject(out.additionalProperties);
847
+ if (acceptsDynamicKeys) {
848
+ unsupported.push({
849
+ path,
850
+ keyword: 'additionalProperties',
851
+ detail: 'object accepts arbitrary keys',
852
+ });
853
+ } else if (out.patternProperties !== undefined) {
854
+ unsupported.push({
855
+ path,
856
+ keyword: 'patternProperties',
857
+ detail: 'object accepts pattern-matched keys',
858
+ });
859
+ } else if (Object.keys(properties).length === 0 && out.additionalProperties === undefined) {
860
+ unsupported.push({
861
+ path,
862
+ keyword: 'properties',
863
+ detail: 'free-form object accepts arbitrary keys',
864
+ });
865
+ }
866
+
867
+ return {
868
+ ...out,
869
+ ...(out.type === undefined ? { type: 'object' } : {}),
870
+ properties,
871
+ required: Object.keys(properties),
872
+ ...(acceptsDynamicKeys ? {} : { additionalProperties: false }),
873
+ };
874
+ }
875
+
876
+ const normalized = walk(root, 'schema', 0, '');
877
+ if (!isPlainObject(normalized) || !isObjectType(normalized.type)) {
878
+ unsupported.push({
879
+ path: '',
880
+ keyword: 'type',
881
+ detail: 'root must be a non-nullable object',
882
+ });
883
+ }
884
+
885
+ return {
886
+ schema: deduplicateJsonSchemaRequiredArrays(normalized) as Record<string, unknown>,
887
+ source: root,
888
+ changes,
889
+ totalChanges,
890
+ unsupported,
891
+ };
892
+ }
893
+
894
+ /**
895
+ * Drops `null`-valued arguments that the tool's own schema does not accept,
896
+ * recursively through nested objects and arrays.
897
+ *
898
+ * Strict structured outputs cannot express optional parameters, so
899
+ * {@link toStrictJsonSchema} makes every parameter required and nullable. The
900
+ * model then sends `null` for a parameter it would otherwise have omitted;
901
+ * forwarding that `null` to the tool would fail validation against the tool's
902
+ * real schema, so it is treated as "omitted". A `null` the original schema
903
+ * accepts (a nullable field, an explicit "clear this value") is kept.
904
+ *
905
+ * @param args - Normalized tool arguments.
906
+ * @param schema - The dereferenced tool parameter schema the arguments were
907
+ * produced for (`StrictJsonSchemaResult.source`).
908
+ * @returns A new object; the input is not mutated.
909
+ */
910
+ export function omitNullToolArguments(
911
+ args: Record<string, unknown>,
912
+ schema: unknown
913
+ ): Record<string, unknown> {
914
+ const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
915
+ return omitNulls(args, root, root, 0) as Record<string, unknown>;
916
+ }
917
+
918
+ /**
919
+ * Picks the composition branch that describes a value's shape: the first
920
+ * branch with `properties` for an object, the first with `items` for an
921
+ * array. Nodes without a composition are returned as they are.
922
+ */
923
+ function selectBranchFor(
924
+ schema: unknown,
925
+ value: unknown,
926
+ root: Record<string, unknown>
927
+ ): Record<string, unknown> | undefined {
928
+ const resolved = resolveLocalRefs(schema, root);
929
+ if (!isPlainObject(resolved)) return undefined;
930
+ const wanted = Array.isArray(value) ? 'items' : 'properties';
931
+ const find = (node: unknown, depth: number): Record<string, unknown> | undefined => {
932
+ const candidate = resolveLocalRefs(node, root);
933
+ if (!isPlainObject(candidate) || depth > MAX_NODE_DEPTH) return undefined;
934
+ if (candidate[wanted] !== undefined) return candidate;
935
+ for (const keyword of ['anyOf', 'oneOf']) {
936
+ const branches = candidate[keyword];
937
+ if (!Array.isArray(branches)) continue;
938
+ for (const branch of branches) {
939
+ const found = find(branch, depth + 1);
940
+ if (found) return found;
941
+ }
942
+ }
943
+ return undefined;
944
+ };
945
+ return find(resolved, 0) ?? resolved;
946
+ }
947
+
948
+ function omitNulls(
949
+ value: unknown,
950
+ schema: unknown,
951
+ root: Record<string, unknown>,
952
+ depth: number
953
+ ): unknown {
954
+ if (depth > MAX_NODE_DEPTH) {
955
+ throw new RangeError(`Tool arguments exceed maximum nesting depth of ${MAX_NODE_DEPTH}`);
956
+ }
957
+ const node = selectBranchFor(schema, value, root);
958
+ if (Array.isArray(value)) {
959
+ const items = node && isPlainObject(node.items) ? node.items : undefined;
960
+ return value.map(item => omitNulls(item, items, root, depth + 1));
961
+ }
962
+ if (!isPlainObject(value)) return value;
963
+
964
+ const properties = node && isPlainObject(node.properties) ? node.properties : {};
965
+ const clone: Record<string, unknown> = {};
966
+ for (const [key, child] of Object.entries(value)) {
967
+ const propertySchema = Object.prototype.hasOwnProperty.call(properties, key)
968
+ ? properties[key]
969
+ : undefined;
970
+ if (child === null) {
971
+ if (propertySchema === undefined || schemaAcceptsNull(propertySchema, root)) {
972
+ setOwn(clone, key, child);
973
+ }
974
+ continue;
975
+ }
976
+ setOwn(clone, key, omitNulls(child, propertySchema, root, depth + 1));
977
+ }
978
+ return clone;
979
+ }
@@ -1,6 +1,6 @@
1
1
  import pc from 'picocolors';
2
- import { getEnvVariable } from './env';
3
2
  import { COMPOSIO_LOG_LEVEL } from './constants';
3
+ import { redactSensitiveText } from '../telemetry/redact';
4
4
 
5
5
  // Define log levels with corresponding priorities
6
6
  export const LOG_LEVELS = {
@@ -23,20 +23,52 @@ export const getLogLevel = (): LogLevel => {
23
23
  return envLevel && envLevel in LOG_LEVELS ? (envLevel as LogLevel) : 'info';
24
24
  };
25
25
 
26
+ /**
27
+ * Destination for SDK log output. Each method receives the already
28
+ * formatted and redacted message as its single argument. `console` satisfies
29
+ * this interface, and so do most structured loggers (pino, winston, ...).
30
+ */
31
+ export interface ComposioLogger {
32
+ error: (...args: unknown[]) => void;
33
+ warn: (...args: unknown[]) => void;
34
+ info: (...args: unknown[]) => void;
35
+ debug: (...args: unknown[]) => void;
36
+ }
37
+
26
38
  interface LoggerOptions {
27
39
  level?: LogLevel;
28
40
  includeTimestamp?: boolean;
41
+ /** Where formatted output is written. Defaults to `console`. */
42
+ sink?: ComposioLogger;
43
+ }
44
+
45
+ export interface LoggerConfigureOptions {
46
+ level?: LogLevel;
47
+ sink?: ComposioLogger;
29
48
  }
30
49
 
31
- class Logger {
32
- private readonly level: LogLevel;
50
+ export class Logger {
51
+ private level: LogLevel;
33
52
  private readonly includeTimestamp: boolean;
34
- private readonly console: Console;
53
+ private sink: ComposioLogger;
35
54
 
36
55
  constructor(options: LoggerOptions = {}) {
37
56
  this.level = options.level ?? getLogLevel();
38
57
  this.includeTimestamp = options.includeTimestamp ?? true;
39
- this.console = console;
58
+ this.sink = options.sink ?? console;
59
+ }
60
+
61
+ /**
62
+ * Reconfigure the level and/or sink in place. Omitted fields are left
63
+ * unchanged, so `configure({ level: 'debug' })` keeps the current sink.
64
+ */
65
+ configure(options: LoggerConfigureOptions): void {
66
+ if (options.level !== undefined) this.level = options.level;
67
+ if (options.sink !== undefined) this.sink = options.sink;
68
+ }
69
+
70
+ getLevel(): LogLevel {
71
+ return this.level;
40
72
  }
41
73
 
42
74
  private formatMessage(args: unknown[]): string {
@@ -57,12 +89,12 @@ class Logger {
57
89
  })
58
90
  .join('\n');
59
91
 
60
- if (!this.includeTimestamp) {
61
- return formattedArgs;
62
- }
92
+ const redactedArgs = redactSensitiveText(formattedArgs) ?? formattedArgs;
93
+
94
+ if (!this.includeTimestamp) return redactedArgs;
63
95
 
64
96
  const timestamp = new Date().toISOString();
65
- return `${pc.gray(timestamp)} - ${formattedArgs}`;
97
+ return `${pc.gray(timestamp)} - ${redactedArgs}`;
66
98
  }
67
99
 
68
100
  private shouldLog(level: LogLevel): boolean {
@@ -71,25 +103,25 @@ class Logger {
71
103
 
72
104
  error(...args: unknown[]): void {
73
105
  if (this.shouldLog('error')) {
74
- this.console.error(this.formatMessage(args));
106
+ this.sink.error(this.formatMessage(args));
75
107
  }
76
108
  }
77
109
 
78
110
  warn(...args: unknown[]): void {
79
111
  if (this.shouldLog('warn')) {
80
- this.console.warn(this.formatMessage(args));
112
+ this.sink.warn(this.formatMessage(args));
81
113
  }
82
114
  }
83
115
 
84
116
  info(...args: unknown[]): void {
85
117
  if (this.shouldLog('info')) {
86
- this.console.info(this.formatMessage(args));
118
+ this.sink.info(this.formatMessage(args));
87
119
  }
88
120
  }
89
121
 
90
122
  debug(...args: unknown[]): void {
91
123
  if (this.shouldLog('debug')) {
92
- this.console.debug(this.formatMessage(args));
124
+ this.sink.debug(this.formatMessage(args));
93
125
  }
94
126
  }
95
127
  }