@composio/core 0.22.0 → 0.24.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.
- package/dist/{CustomTool-CKBCElpT.d.mts → CustomTool-CNJysHMK.d.mts} +1 -1
- package/dist/{CustomTool-B-_VjWpy.mjs → CustomTool-CnJxXr07.mjs} +1 -1
- package/dist/{cancellation-DV8CIi52.mjs → cancellation-BQibgpRG.mjs} +166 -34
- package/dist/{composio-C-418N1P.d.mts → composio-BFTtZj82.d.mts} +62 -80
- package/dist/{customTool.types-CK408sI-.d.mts → customTool.types-D57QrTns.d.mts} +309 -204
- package/dist/docs/reference/sdk-reference/typescript/logs.mdx +4 -4
- package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +1 -1
- package/dist/docs/reference/sdk-reference/typescript/session.mdx +2 -2
- package/dist/docs/reference/sdk-reference/typescript/tools.mdx +2 -2
- package/dist/docs/reference/sdk-reference/typescript/usage.mdx +2 -2
- package/dist/{errors-Dyiu3ifQ.mjs → errors-BN15NcCW.mjs} +34 -2
- package/dist/experimental/index.d.mts +2 -2
- package/dist/experimental/index.mjs +1 -1
- package/dist/index.d.mts +66 -4
- package/dist/index.mjs +3321 -3103
- package/dist/platform/node.d.mts +1 -1
- package/dist/platform/node.mjs +13 -0
- package/dist/platform/workerd.d.mts +1 -1
- package/dist/platform/workerd.mjs +3 -0
- package/dist/{types-D5A2wzBl.d.mts → types-DuVZKrXO.d.mts} +2 -0
- package/dist/{types-RpMRVn4D.d.mts → types-q8TwAngA.d.mts} +2 -2
- package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
- package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.mjs +2 -2
- package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
- package/package.json +12 -9
- package/src/errors/ToolRouterErrors.ts +65 -0
- package/src/lib/toolRouterParams.ts +19 -13
- package/src/models/CustomToolkits.ts +1 -1
- package/src/models/MCP.ts +20 -1
- package/src/models/RemoteFile.ts +24 -5
- package/src/models/SessionContext.ts +24 -4
- package/src/models/ToolRouter.ts +6 -4
- package/src/models/ToolRouterSession.ts +95 -13
- package/src/models/Tools.ts +20 -36
- package/src/models/customToolExecution.ts +10 -0
- package/src/platform/node.ts +16 -0
- package/src/platform/types.ts +3 -0
- package/src/platform/workerd.ts +4 -0
- package/src/provider/BaseProvider.ts +2 -1
- package/src/types/tool.types.ts +5 -0
- package/src/types/toolRouter.types.ts +97 -26
- package/src/utils/jsonSchema.ts +191 -36
- package/src/utils/retries.ts +20 -0
- package/src/utils/safePath.ts +135 -54
- package/src/utils/session.ts +31 -2
- package/src/utils/transformers/toolRouterResponseTransform.ts +72 -27
- package/src/utils/transformers/usage.ts +1 -4
package/src/utils/jsonSchema.ts
CHANGED
|
@@ -6,6 +6,9 @@ import { isPlainObject } from './modifiers/FileToolModifier.utils.neutral';
|
|
|
6
6
|
|
|
7
7
|
const MAX_REF_CHAIN_DEPTH = 100;
|
|
8
8
|
const MAX_NODE_DEPTH = 512;
|
|
9
|
+
// Bounds on one null-acceptance check; past either, null is not proven accepted.
|
|
10
|
+
const MAX_NULL_CHECK_DEPTH = 64;
|
|
11
|
+
const MAX_NULL_CHECK_NODES = 2_000;
|
|
9
12
|
const CYCLE_BREAK_SENTINEL = { type: 'object', additionalProperties: true } as const;
|
|
10
13
|
|
|
11
14
|
/** Keywords whose value is a single subschema. */
|
|
@@ -603,27 +606,44 @@ function setOwn(target: Record<string, unknown>, key: string, value: unknown): v
|
|
|
603
606
|
}
|
|
604
607
|
|
|
605
608
|
/**
|
|
606
|
-
*
|
|
607
|
-
*
|
|
609
|
+
* The only keywords that can reject a `null` instance; every other keyword
|
|
610
|
+
* constrains strings, numbers, arrays or objects and ignores `null`.
|
|
608
611
|
*/
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
612
|
+
const NULL_CONSTRAINT_KEYWORDS = [
|
|
613
|
+
'type',
|
|
614
|
+
'enum',
|
|
615
|
+
'const',
|
|
616
|
+
'$ref',
|
|
617
|
+
'anyOf',
|
|
618
|
+
'oneOf',
|
|
619
|
+
'allOf',
|
|
620
|
+
'not',
|
|
621
|
+
'if',
|
|
622
|
+
'then',
|
|
623
|
+
'else',
|
|
624
|
+
] as const;
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Widens a property schema so that `null` is an accepted value while keeping
|
|
628
|
+
* every other constraint it declares. A node whose only obstacle is `type` or
|
|
629
|
+
* `anyOf` is widened in place. Anything else is wrapped whole, because JSON
|
|
630
|
+
* Schema keywords apply together: adding `null` to `type` does not lift a
|
|
631
|
+
* sibling `enum`. `acceptsNull` must answer for the strict output.
|
|
632
|
+
*/
|
|
633
|
+
function widenToNullable(
|
|
634
|
+
node: Record<string, unknown>,
|
|
635
|
+
acceptsNull: (schema: unknown) => boolean
|
|
636
|
+
): Record<string, unknown> {
|
|
637
|
+
if (acceptsNull(node)) return node;
|
|
638
|
+
const constraints = NULL_CONSTRAINT_KEYWORDS.filter(key => key in node);
|
|
639
|
+
if (constraints.length === 1 && constraints[0] === 'type') {
|
|
640
|
+
const members = Array.isArray(node.type) ? node.type : [node.type];
|
|
641
|
+
return { ...node, type: [...members, 'null'] };
|
|
618
642
|
}
|
|
619
|
-
if (Array.isArray(node.
|
|
620
|
-
return
|
|
643
|
+
if (constraints.length === 1 && constraints[0] === 'anyOf' && Array.isArray(node.anyOf)) {
|
|
644
|
+
return { ...node, anyOf: [...node.anyOf, { type: 'null' }] };
|
|
621
645
|
}
|
|
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
646
|
const { description, title, ...rest } = node;
|
|
626
|
-
if (Object.keys(rest).length === 0) return node;
|
|
627
647
|
return {
|
|
628
648
|
...(description !== undefined ? { description } : {}),
|
|
629
649
|
...(title !== undefined ? { title } : {}),
|
|
@@ -646,19 +666,136 @@ function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown
|
|
|
646
666
|
return current;
|
|
647
667
|
}
|
|
648
668
|
|
|
649
|
-
/**
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
669
|
+
/**
|
|
670
|
+
* Creates the check for whether schemas of one document accept `null` as an
|
|
671
|
+
* instance: every keyword in `NULL_CONSTRAINT_KEYWORDS` that is present must
|
|
672
|
+
* accept it. This is the single definition of null acceptance; the strict
|
|
673
|
+
* rewrite and `omitNullToolArguments` both decide with it.
|
|
674
|
+
*
|
|
675
|
+
* `strictOutput` answers for the schema `toStrictJsonSchema` emits instead of
|
|
676
|
+
* the one it was given: the rewrite types every node that declares
|
|
677
|
+
* `properties` as an object, so such a node stops accepting null.
|
|
678
|
+
*
|
|
679
|
+
* One check serves a whole document, and an answer is computed once per node.
|
|
680
|
+
* A reference cycle never yields a null by itself, so a node met again while
|
|
681
|
+
* it is being evaluated counts as rejecting. An answer that leans on that is
|
|
682
|
+
* provisional until the node it leans on is done: it is kept if that node
|
|
683
|
+
* does reject null and discarded otherwise.
|
|
684
|
+
*
|
|
685
|
+
* Each check is bounded in depth and in nodes visited. A check that meets a
|
|
686
|
+
* bound proves nothing, so it rejects null whatever its other branches say,
|
|
687
|
+
* which costs at most a redundant null branch or a dropped null. The nodes it
|
|
688
|
+
* went through stay marked as unproven, so a later check that reaches one of
|
|
689
|
+
* them neither repeats the work nor trusts the answer.
|
|
690
|
+
*/
|
|
691
|
+
function createNullCheck(
|
|
692
|
+
root: Record<string, unknown>,
|
|
693
|
+
strictOutput = false
|
|
694
|
+
): (schema: unknown) => boolean {
|
|
695
|
+
// Markers for what an answer leans on, besides the depth of a node on the path.
|
|
696
|
+
const NOTHING = MAX_NULL_CHECK_DEPTH + 1;
|
|
697
|
+
const A_BOUND = -1;
|
|
698
|
+
const answers = new Map<object, { answer: boolean; leansOn: number }>();
|
|
699
|
+
// Nodes whose answer is provisional, oldest first.
|
|
700
|
+
const provisional: object[] = [];
|
|
701
|
+
// Nodes being evaluated, mapped to their depth on the current path.
|
|
702
|
+
const path = new Map<object, number>();
|
|
703
|
+
// Depths of the path nodes that were met again below themselves.
|
|
704
|
+
const metAgain = new Set<number>();
|
|
705
|
+
let budget = 0;
|
|
706
|
+
// Shallowest thing the answers used since the last reset lean on.
|
|
707
|
+
let leansOn = NOTHING;
|
|
708
|
+
|
|
709
|
+
const accepts = (schema: unknown): boolean => {
|
|
710
|
+
if (typeof schema === 'boolean') return schema;
|
|
711
|
+
if (!isPlainObject(schema)) return true;
|
|
712
|
+
const remembered = answers.get(schema);
|
|
713
|
+
if (remembered !== undefined) {
|
|
714
|
+
if (path.size === 0) return remembered.answer && remembered.leansOn !== A_BOUND;
|
|
715
|
+
leansOn = Math.min(leansOn, remembered.leansOn);
|
|
716
|
+
return remembered.answer;
|
|
717
|
+
}
|
|
718
|
+
const onPath = path.get(schema);
|
|
719
|
+
if (onPath !== undefined) {
|
|
720
|
+
metAgain.add(onPath);
|
|
721
|
+
leansOn = Math.min(leansOn, onPath);
|
|
722
|
+
return false;
|
|
723
|
+
}
|
|
724
|
+
const depth = path.size;
|
|
725
|
+
if (depth === 0) budget = MAX_NULL_CHECK_NODES;
|
|
726
|
+
if (depth >= MAX_NULL_CHECK_DEPTH || budget <= 0) {
|
|
727
|
+
leansOn = A_BOUND;
|
|
728
|
+
return false;
|
|
729
|
+
}
|
|
730
|
+
budget -= 1;
|
|
731
|
+
|
|
732
|
+
const outer = leansOn;
|
|
733
|
+
leansOn = NOTHING;
|
|
734
|
+
const mark = provisional.length;
|
|
735
|
+
path.set(schema, depth);
|
|
736
|
+
let answer = keywordsAccept(schema);
|
|
737
|
+
path.delete(schema);
|
|
738
|
+
|
|
739
|
+
const own = leansOn;
|
|
740
|
+
const settled = own >= depth;
|
|
741
|
+
const below = provisional.splice(mark);
|
|
742
|
+
if (answer && metAgain.has(depth)) {
|
|
743
|
+
// The answers below took this node for rejecting null.
|
|
744
|
+
for (const other of below) answers.delete(other);
|
|
745
|
+
} else {
|
|
746
|
+
for (const other of below) {
|
|
747
|
+
const entry = answers.get(other);
|
|
748
|
+
if (entry === undefined) continue;
|
|
749
|
+
if (settled) {
|
|
750
|
+
entry.leansOn = NOTHING;
|
|
751
|
+
} else {
|
|
752
|
+
if (entry.leansOn >= depth) entry.leansOn = own;
|
|
753
|
+
provisional.push(other);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
metAgain.delete(depth);
|
|
758
|
+
|
|
759
|
+
if (depth === 0 && own === A_BOUND) answer = false;
|
|
760
|
+
answers.set(schema, { answer, leansOn: settled ? NOTHING : own });
|
|
761
|
+
if (!settled) provisional.push(schema);
|
|
762
|
+
leansOn = settled ? outer : Math.min(outer, own);
|
|
763
|
+
if (depth === 0) {
|
|
764
|
+
// Whatever is still provisional leans on a bound, and stays so.
|
|
765
|
+
provisional.length = 0;
|
|
766
|
+
leansOn = NOTHING;
|
|
767
|
+
}
|
|
768
|
+
return answer;
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
const keywordsAccept = (node: Record<string, unknown>): boolean => {
|
|
772
|
+
if (typeof node.type === 'string' && node.type !== 'null') return false;
|
|
773
|
+
if (Array.isArray(node.type) && !node.type.includes('null')) return false;
|
|
774
|
+
if (strictOutput && !('type' in node) && isPlainObject(node.properties)) return false;
|
|
775
|
+
if (Array.isArray(node.enum) && !node.enum.includes(null)) return false;
|
|
776
|
+
if ('const' in node && node.const !== null) return false;
|
|
777
|
+
if ('$ref' in node) {
|
|
778
|
+
const resolution =
|
|
779
|
+
typeof node.$ref === 'string' ? tryResolvePointer(root, node.$ref) : undefined;
|
|
780
|
+
if (resolution === undefined || resolution.kind === 'unresolved') return false;
|
|
781
|
+
if (!accepts(resolution.value)) return false;
|
|
782
|
+
}
|
|
783
|
+
if (Array.isArray(node.anyOf) && !node.anyOf.some(accepts)) return false;
|
|
784
|
+
if (Array.isArray(node.oneOf)) {
|
|
785
|
+
const matches = node.oneOf.filter(accepts).length;
|
|
786
|
+
// The strict rewrite turns oneOf into anyOf.
|
|
787
|
+
if (matches === 0 || (matches > 1 && !strictOutput)) return false;
|
|
788
|
+
}
|
|
789
|
+
if (Array.isArray(node.allOf) && !node.allOf.every(accepts)) return false;
|
|
790
|
+
if ('not' in node && accepts(node.not)) return false;
|
|
791
|
+
if ('if' in node) {
|
|
792
|
+
const branch = accepts(node.if) ? 'then' : 'else';
|
|
793
|
+
if (branch in node && !accepts(node[branch])) return false;
|
|
794
|
+
}
|
|
795
|
+
return true;
|
|
796
|
+
};
|
|
797
|
+
|
|
798
|
+
return accepts;
|
|
662
799
|
}
|
|
663
800
|
|
|
664
801
|
/**
|
|
@@ -694,6 +831,8 @@ function schemaAcceptsNull(schema: unknown, root: Record<string, unknown>): bool
|
|
|
694
831
|
export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
695
832
|
const changes: StrictSchemaChange[] = [];
|
|
696
833
|
const unsupported: StrictSchemaIncompatibility[] = [];
|
|
834
|
+
// Resolved references, re-checked against the rewritten schema.
|
|
835
|
+
const references: { path: string; ref: string }[] = [];
|
|
697
836
|
let totalChanges = 0;
|
|
698
837
|
const recordChange = (change: StrictSchemaChange): void => {
|
|
699
838
|
totalChanges += 1;
|
|
@@ -701,6 +840,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
|
701
840
|
};
|
|
702
841
|
|
|
703
842
|
const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
|
|
843
|
+
const acceptsNullInOutput = createNullCheck(root, true);
|
|
704
844
|
|
|
705
845
|
function walkChildren(
|
|
706
846
|
node: Record<string, unknown>,
|
|
@@ -805,6 +945,8 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
|
805
945
|
keyword: '$ref',
|
|
806
946
|
detail: `unresolved $ref "${node.$ref}"`,
|
|
807
947
|
});
|
|
948
|
+
} else {
|
|
949
|
+
references.push({ path, ref: node.$ref });
|
|
808
950
|
}
|
|
809
951
|
// The referenced definition is normalized where it is declared.
|
|
810
952
|
return out;
|
|
@@ -834,7 +976,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
|
834
976
|
continue;
|
|
835
977
|
}
|
|
836
978
|
if (declaredRequired.has(name) || !isPlainObject(propertySchema)) continue;
|
|
837
|
-
setOwn(properties, name, widenToNullable(propertySchema));
|
|
979
|
+
setOwn(properties, name, widenToNullable(propertySchema, acceptsNullInOutput));
|
|
838
980
|
recordChange({
|
|
839
981
|
path: joinPath(path, `properties.${name}`),
|
|
840
982
|
reason: 'optional-property-nullable',
|
|
@@ -874,6 +1016,18 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
|
874
1016
|
}
|
|
875
1017
|
|
|
876
1018
|
const normalized = walk(root, 'schema', 0, '');
|
|
1019
|
+
if (isPlainObject(normalized)) {
|
|
1020
|
+
// Wrapping a property in a null branch moves everything nested in it.
|
|
1021
|
+
for (const { path, ref } of references) {
|
|
1022
|
+
if (tryResolvePointer(normalized, ref).kind === 'unresolved') {
|
|
1023
|
+
unsupported.push({
|
|
1024
|
+
path,
|
|
1025
|
+
keyword: '$ref',
|
|
1026
|
+
detail: `$ref "${ref}" target moved by the rewrite`,
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
877
1031
|
if (!isPlainObject(normalized) || !isObjectType(normalized.type)) {
|
|
878
1032
|
unsupported.push({
|
|
879
1033
|
path: '',
|
|
@@ -912,7 +1066,7 @@ export function omitNullToolArguments(
|
|
|
912
1066
|
schema: unknown
|
|
913
1067
|
): Record<string, unknown> {
|
|
914
1068
|
const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
|
|
915
|
-
return omitNulls(args, root, root, 0) as Record<string, unknown>;
|
|
1069
|
+
return omitNulls(args, root, root, 0, createNullCheck(root)) as Record<string, unknown>;
|
|
916
1070
|
}
|
|
917
1071
|
|
|
918
1072
|
/**
|
|
@@ -949,7 +1103,8 @@ function omitNulls(
|
|
|
949
1103
|
value: unknown,
|
|
950
1104
|
schema: unknown,
|
|
951
1105
|
root: Record<string, unknown>,
|
|
952
|
-
depth: number
|
|
1106
|
+
depth: number,
|
|
1107
|
+
acceptsNull: (schema: unknown) => boolean
|
|
953
1108
|
): unknown {
|
|
954
1109
|
if (depth > MAX_NODE_DEPTH) {
|
|
955
1110
|
throw new RangeError(`Tool arguments exceed maximum nesting depth of ${MAX_NODE_DEPTH}`);
|
|
@@ -957,7 +1112,7 @@ function omitNulls(
|
|
|
957
1112
|
const node = selectBranchFor(schema, value, root);
|
|
958
1113
|
if (Array.isArray(value)) {
|
|
959
1114
|
const items = node && isPlainObject(node.items) ? node.items : undefined;
|
|
960
|
-
return value.map(item => omitNulls(item, items, root, depth + 1));
|
|
1115
|
+
return value.map(item => omitNulls(item, items, root, depth + 1, acceptsNull));
|
|
961
1116
|
}
|
|
962
1117
|
if (!isPlainObject(value)) return value;
|
|
963
1118
|
|
|
@@ -968,12 +1123,12 @@ function omitNulls(
|
|
|
968
1123
|
? properties[key]
|
|
969
1124
|
: undefined;
|
|
970
1125
|
if (child === null) {
|
|
971
|
-
if (propertySchema === undefined ||
|
|
1126
|
+
if (propertySchema === undefined || acceptsNull(propertySchema)) {
|
|
972
1127
|
setOwn(clone, key, child);
|
|
973
1128
|
}
|
|
974
1129
|
continue;
|
|
975
1130
|
}
|
|
976
|
-
setOwn(clone, key, omitNulls(child, propertySchema, root, depth + 1));
|
|
1131
|
+
setOwn(clone, key, omitNulls(child, propertySchema, root, depth + 1, acceptsNull));
|
|
977
1132
|
}
|
|
978
1133
|
return clone;
|
|
979
1134
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ComposioRequestOptions } from '../types/requestOptions.types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Request options for a call that executes a tool or proxies an API call: the
|
|
5
|
+
* caller's options with retries disabled.
|
|
6
|
+
*
|
|
7
|
+
* These calls are non-idempotent writes. The client retries timeouts,
|
|
8
|
+
* connection errors, and 408/409/429/5xx responses by default, and a retry
|
|
9
|
+
* after the backend already acted duplicates the side effect (e.g. sends the
|
|
10
|
+
* same email twice). The backend does not deduplicate executions, so every
|
|
11
|
+
* execution path must go through this helper. Reads keep the default retries.
|
|
12
|
+
* See https://github.com/ComposioHQ/composio/issues/3654.
|
|
13
|
+
*
|
|
14
|
+
* @internal
|
|
15
|
+
*/
|
|
16
|
+
export function withoutRetries(
|
|
17
|
+
requestOptions?: ComposioRequestOptions
|
|
18
|
+
): ComposioRequestOptions & { maxRetries: 0 } {
|
|
19
|
+
return { ...requestOptions, maxRetries: 0 };
|
|
20
|
+
}
|
package/src/utils/safePath.ts
CHANGED
|
@@ -17,14 +17,21 @@ import { ValidationError } from '../errors/ValidationErrors';
|
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* Upper bound on a filename, well under the 255-byte limit common to
|
|
20
|
-
* ext4/APFS/NTFS.
|
|
21
|
-
* `ENAMETOOLONG` mid-write. Matches
|
|
20
|
+
* ext4/APFS/NTFS. A longer server-supplied name is truncated to fit rather
|
|
21
|
+
* than failing with a raw `ENAMETOOLONG` mid-write. Matches
|
|
22
|
+
* `MAX_COMPONENT_LENGTH` in the Python SDK.
|
|
22
23
|
*/
|
|
23
24
|
export const MAX_FILENAME_BYTES = 128;
|
|
24
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Longest extension, in bytes and including its dot, that truncation keeps.
|
|
28
|
+
* Anything longer is not a real extension and is truncated with the rest.
|
|
29
|
+
*/
|
|
30
|
+
const MAX_PRESERVED_EXTENSION_BYTES = 32;
|
|
31
|
+
|
|
25
32
|
/**
|
|
26
33
|
* Reserved DOS device names. Writing to one on Windows targets the device
|
|
27
|
-
* rather than a file.
|
|
34
|
+
* rather than a file. Prefixed on every platform so behavior does not diverge
|
|
28
35
|
* between a POSIX developer machine and a Windows deployment.
|
|
29
36
|
*/
|
|
30
37
|
const WINDOWS_RESERVED_NAMES: ReadonlySet<string> = new Set([
|
|
@@ -38,7 +45,28 @@ const WINDOWS_RESERVED_NAMES: ReadonlySet<string> = new Set([
|
|
|
38
45
|
]);
|
|
39
46
|
|
|
40
47
|
/** Control characters and characters reserved by Windows. */
|
|
41
|
-
const WINDOWS_INVALID_CHARS = /[\u0000-\u001f<>:"|?*]
|
|
48
|
+
const WINDOWS_INVALID_CHARS = /[\u0000-\u001f<>:"|?*]/g;
|
|
49
|
+
|
|
50
|
+
/** Windows drops trailing spaces and dots from a filename. */
|
|
51
|
+
const TRAILING_SPACES_AND_DOTS = /[. ]+$/;
|
|
52
|
+
|
|
53
|
+
const utf8Length = (value: string): number => new TextEncoder().encode(value).length;
|
|
54
|
+
|
|
55
|
+
const FNV_OFFSET_BASIS_64 = 0xcbf29ce484222325n;
|
|
56
|
+
const FNV_PRIME_64 = 0x100000001b3n;
|
|
57
|
+
const UINT64_MASK = 0xffffffffffffffffn;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 64-bit FNV-1a of the UTF-8 bytes, as 16 hex digits. Pure and synchronous, so
|
|
61
|
+
* it runs on every runtime; `_fnv1a64_hex` in the Python SDK matches it.
|
|
62
|
+
*/
|
|
63
|
+
function fnv1a64Hex(value: string): string {
|
|
64
|
+
let hash = FNV_OFFSET_BASIS_64;
|
|
65
|
+
for (const byte of new TextEncoder().encode(value)) {
|
|
66
|
+
hash = ((hash ^ BigInt(byte)) * FNV_PRIME_64) & UINT64_MASK;
|
|
67
|
+
}
|
|
68
|
+
return hash.toString(16).padStart(16, '0');
|
|
69
|
+
}
|
|
42
70
|
|
|
43
71
|
/**
|
|
44
72
|
* Python str.strip() whitespace: Unicode White_Space plus U+001C–U+001F.
|
|
@@ -93,80 +121,133 @@ function hasLoneSurrogate(value: string): boolean {
|
|
|
93
121
|
return false;
|
|
94
122
|
}
|
|
95
123
|
|
|
124
|
+
/** The longest prefix of `value`, by whole code points, that fits in `maxBytes`. */
|
|
125
|
+
function truncateToBytes(value: string, maxBytes: number): string {
|
|
126
|
+
let truncated = '';
|
|
127
|
+
let bytes = 0;
|
|
128
|
+
for (const char of value) {
|
|
129
|
+
bytes += utf8Length(char);
|
|
130
|
+
if (bytes > maxBytes) {
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
truncated += char;
|
|
134
|
+
}
|
|
135
|
+
return truncated;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Splits off a short trailing extension (with its dot); a leading dot is not one. */
|
|
139
|
+
function splitExtension(name: string): [stem: string, extension: string] {
|
|
140
|
+
const dot = name.lastIndexOf('.');
|
|
141
|
+
const extension = dot > 0 ? name.slice(dot) : '';
|
|
142
|
+
return extension && utf8Length(extension) <= MAX_PRESERVED_EXTENSION_BYTES
|
|
143
|
+
? [name.slice(0, dot), extension]
|
|
144
|
+
: [name, ''];
|
|
145
|
+
}
|
|
146
|
+
|
|
96
147
|
/**
|
|
97
|
-
*
|
|
148
|
+
* Truncates `name` to `maxBytes`, keeping a short extension so the file still
|
|
149
|
+
* opens with the right application.
|
|
150
|
+
*/
|
|
151
|
+
function fitFilenameBytes(name: string, maxBytes: number = MAX_FILENAME_BYTES): string {
|
|
152
|
+
if (utf8Length(name) <= maxBytes) {
|
|
153
|
+
return name;
|
|
154
|
+
}
|
|
155
|
+
const [stem, extension] = splitExtension(name);
|
|
156
|
+
return truncateToBytes(stem, maxBytes - utf8Length(extension)) + extension;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Adds a copy number before the extension without exceeding the filename byte limit. */
|
|
160
|
+
export function numberedBasename(name: string, copy: number): string {
|
|
161
|
+
const suffix = `-${copy}`;
|
|
162
|
+
const [stem, extension] = splitExtension(name);
|
|
163
|
+
return (
|
|
164
|
+
truncateToBytes(stem, MAX_FILENAME_BYTES - utf8Length(extension) - suffix.length) +
|
|
165
|
+
suffix +
|
|
166
|
+
extension
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Tags a name that portability changed with a digest of the name it came
|
|
172
|
+
* from, before the extension: `report?.png` and `report*.png` both become
|
|
173
|
+
* `report_.png`, and two long names can share a truncated prefix, so without
|
|
174
|
+
* the tag one download would overwrite the other in a shared directory.
|
|
175
|
+
*/
|
|
176
|
+
function tagWithOriginal(portable: string, original: string): string {
|
|
177
|
+
const tag = `-${fnv1a64Hex(original)}`;
|
|
178
|
+
const [stem, extension] = splitExtension(
|
|
179
|
+
fitFilenameBytes(portable, MAX_FILENAME_BYTES - tag.length)
|
|
180
|
+
);
|
|
181
|
+
return stem + tag + extension;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Collapses an untrusted filename to a bare basename that is safe to write on
|
|
186
|
+
* every platform.
|
|
98
187
|
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
188
|
+
* Names that cannot be written at all are refused: a NUL byte, invalid
|
|
189
|
+
* Unicode, or no usable basename (empty or a run of dots). A response that
|
|
190
|
+
* cannot name its own file is malformed or hostile, and inventing a name would
|
|
191
|
+
* hide that. `""`, `"."` and `".."` make an output path equal to, or escape,
|
|
192
|
+
* its own directory, which surfaces as a raw `EISDIR` at write time instead of
|
|
193
|
+
* a validation error.
|
|
105
194
|
*
|
|
106
|
-
* Names that
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
195
|
+
* Names that are merely unportable are made portable instead, because ordinary
|
|
196
|
+
* files have them (`report_2026-09-29T10:30:00.csv`, `What is this?.png`), on
|
|
197
|
+
* every platform so a name does not depend on where the SDK runs:
|
|
198
|
+
* control and Windows-reserved characters become `_`, names over
|
|
199
|
+
* {@link MAX_FILENAME_BYTES} are truncated with their extension kept, trailing
|
|
200
|
+
* spaces and dots are dropped as Windows would, and a resulting reserved
|
|
201
|
+
* device name gets a `_` prefix. A name any of these rules changed is then
|
|
202
|
+
* tagged with a digest of the original before its extension
|
|
203
|
+
* (`report_-<16 hex>.png`) to distinguish ordinary normalization collisions;
|
|
204
|
+
* a name that was already portable is returned unchanged. A result can still
|
|
205
|
+
* equal a literal server name, so default saves create files exclusively.
|
|
206
|
+
* `safe_basename` in
|
|
207
|
+
* the Python SDK applies the same rules in the same order.
|
|
111
208
|
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
* hazard checks that follow run on the raw segment so a trailing ASCII space or
|
|
116
|
-
* dot is refused, not trimmed away. Check the stripped value for trailing dots
|
|
117
|
-
* too, since stripping whitespace can expose one.
|
|
209
|
+
* Python-compatible stripping removes surrounding whitespace first, and the
|
|
210
|
+
* usability check runs last, on the value that gets written, so neither
|
|
211
|
+
* `"\u00a0.\u00a0"` nor `". ."` can be written as `.` or as its own directory.
|
|
118
212
|
*
|
|
119
213
|
* @param name - The untrusted filename or relative path to reduce.
|
|
120
214
|
* @param label - How the value is described in error messages.
|
|
121
|
-
* @returns The
|
|
122
|
-
* @throws ValidationError if `name`
|
|
215
|
+
* @returns The bare basename to write, adjusted to be portable.
|
|
216
|
+
* @throws ValidationError if `name` contains a NUL byte or invalid Unicode, or
|
|
217
|
+
* leaves no usable basename.
|
|
123
218
|
*/
|
|
124
219
|
export function safeBasename(name: string, label: string = 'filename'): string {
|
|
125
|
-
const
|
|
126
|
-
const basename = rawBasename.replace(SURROUNDING_WHITESPACE, '');
|
|
220
|
+
const basename = untrustedBasename(name).replace(SURROUNDING_WHITESPACE, '');
|
|
127
221
|
|
|
128
|
-
if (
|
|
129
|
-
throw new ValidationError(
|
|
130
|
-
`Path traversal detected: ${label} ${JSON.stringify(name)} leaves no usable basename to write to.`
|
|
131
|
-
);
|
|
132
|
-
}
|
|
133
|
-
if (rawBasename.includes('\u0000')) {
|
|
222
|
+
if (basename.includes('\u0000')) {
|
|
134
223
|
throw new ValidationError(
|
|
135
224
|
`Refusing to write ${label} containing a NUL byte: ${JSON.stringify(name)}`
|
|
136
225
|
);
|
|
137
226
|
}
|
|
138
|
-
if (WINDOWS_INVALID_CHARS.test(rawBasename)) {
|
|
139
|
-
throw new ValidationError(
|
|
140
|
-
`Refusing to write ${label} containing characters reserved by Windows: ${JSON.stringify(name)}`
|
|
141
|
-
);
|
|
142
|
-
}
|
|
143
|
-
if (rawBasename.endsWith(' ') || rawBasename.endsWith('.') || basename.endsWith('.')) {
|
|
144
|
-
throw new ValidationError(
|
|
145
|
-
`Refusing to write ${label} ending in a space or dot: ${JSON.stringify(name)}`
|
|
146
|
-
);
|
|
147
|
-
}
|
|
148
227
|
if (hasLoneSurrogate(basename)) {
|
|
149
228
|
throw new ValidationError(
|
|
150
229
|
`Refusing to write ${label} containing invalid Unicode: ${JSON.stringify(name)}`
|
|
151
230
|
);
|
|
152
231
|
}
|
|
153
232
|
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
233
|
+
const fit = (value: string): string =>
|
|
234
|
+
fitFilenameBytes(value).replace(TRAILING_SPACES_AND_DOTS, '');
|
|
235
|
+
let portable = fit(basename.replace(WINDOWS_INVALID_CHARS, '_'));
|
|
236
|
+
// Checked on the fitted name, because truncation and trailing-dot removal
|
|
237
|
+
// can expose one (`NUL` followed by spaces and a long tail). Compare
|
|
238
|
+
// everything before the first dot: on Windows `NUL.tar.gz` opens the null
|
|
239
|
+
// device just as `NUL` does, so extensions provide no protection. Fitting
|
|
240
|
+
// again keeps the byte bound, and a `_`-prefixed name is never a device.
|
|
241
|
+
const deviceName = portable.split('.', 1)[0].replace(/ +$/, '').toUpperCase();
|
|
242
|
+
if (WINDOWS_RESERVED_NAMES.has(deviceName)) {
|
|
243
|
+
portable = fit(`_${portable}`);
|
|
160
244
|
}
|
|
161
245
|
|
|
162
|
-
|
|
163
|
-
// null device just as `NUL` does, so extensions provide no protection.
|
|
164
|
-
const deviceName = basename.split('.', 1)[0].replace(/ +$/, '').toUpperCase();
|
|
165
|
-
if (WINDOWS_RESERVED_NAMES.has(deviceName)) {
|
|
246
|
+
if (!portable) {
|
|
166
247
|
throw new ValidationError(
|
|
167
|
-
`
|
|
248
|
+
`Path traversal detected: ${label} ${JSON.stringify(name)} leaves no usable basename to write to.`
|
|
168
249
|
);
|
|
169
250
|
}
|
|
170
251
|
|
|
171
|
-
return basename;
|
|
252
|
+
return portable === basename ? portable : tagWithOriginal(portable, basename);
|
|
172
253
|
}
|
package/src/utils/session.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { BaseComposioProvider } from '../provider/BaseProvider';
|
|
2
|
-
|
|
2
|
+
// Resolve against the installed package, including slim's copy of the core build.
|
|
3
|
+
import identity from '#client_identity' with { type: 'json' };
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { VERSION as clientLibraryVersion } from '@composio/client';
|
|
3
6
|
import type { ComposioRequestHeaders } from '../types/composio.types';
|
|
4
7
|
|
|
5
8
|
/**
|
|
@@ -90,6 +93,24 @@ function detectRuntime(): string {
|
|
|
90
93
|
|
|
91
94
|
// Detect once at module initialization
|
|
92
95
|
const RUNTIME_ENV = detectRuntime();
|
|
96
|
+
const RuntimeVersionsSchema = z.object({
|
|
97
|
+
Bun: z.object({ version: z.string() }).optional(),
|
|
98
|
+
Deno: z.object({ version: z.object({ deno: z.string() }) }).optional(),
|
|
99
|
+
});
|
|
100
|
+
const runtimeVersions = RuntimeVersionsSchema.safeParse(globalThis);
|
|
101
|
+
const detectRuntimeVersion = (): string | undefined => {
|
|
102
|
+
switch (RUNTIME_ENV) {
|
|
103
|
+
case 'BUN':
|
|
104
|
+
return runtimeVersions.success ? runtimeVersions.data.Bun?.version : undefined;
|
|
105
|
+
case 'DENO':
|
|
106
|
+
return runtimeVersions.success ? runtimeVersions.data.Deno?.version.deno : undefined;
|
|
107
|
+
case 'NODEJS':
|
|
108
|
+
return process.versions.node;
|
|
109
|
+
default:
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const RUNTIME_VERSION = detectRuntimeVersion();
|
|
93
114
|
|
|
94
115
|
export function getSessionHeaders(
|
|
95
116
|
provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
|
|
@@ -98,7 +119,15 @@ export function getSessionHeaders(
|
|
|
98
119
|
'x-framework': provider?.name || 'unknown',
|
|
99
120
|
'x-source': 'TYPESCRIPT_SDK',
|
|
100
121
|
'x-runtime': RUNTIME_ENV,
|
|
101
|
-
'x-
|
|
122
|
+
'x-client-runtime':
|
|
123
|
+
RUNTIME_ENV === 'CLOUDFLARE_WORKERS' ? 'cloudflare' : RUNTIME_ENV.toLowerCase(),
|
|
124
|
+
'x-sdk-version': identity.version,
|
|
125
|
+
'x-client-provenance': identity.name,
|
|
126
|
+
'x-client-version': identity.version,
|
|
127
|
+
'x-client-language': 'typescript',
|
|
128
|
+
'x-client-library': '@composio/client',
|
|
129
|
+
'x-client-library-version': clientLibraryVersion,
|
|
130
|
+
...(RUNTIME_VERSION ? { 'x-runtime-version': RUNTIME_VERSION } : {}),
|
|
102
131
|
};
|
|
103
132
|
}
|
|
104
133
|
|