@xpert-ai/plugin-sdk 3.17.1 → 3.17.2

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/index.cjs.js CHANGED
@@ -1669,145 +1669,6 @@ exports.AIModelProviderRegistry = __decorate([
1669
1669
  ])
1670
1670
  ], exports.AIModelProviderRegistry);
1671
1671
 
1672
- class AiModelNotFoundException extends common.NotFoundException {
1673
- }
1674
- class CredentialsValidateFailedError extends common.ForbiddenException {
1675
- }
1676
- class AIModelProviderNotFoundException extends common.NotFoundException {
1677
- }
1678
-
1679
- var ModelProvider_1;
1680
- exports.ModelProvider = ModelProvider_1 = class ModelProvider {
1681
- get name() {
1682
- return this.getProviderSchema().provider;
1683
- }
1684
- async validateCredentials(credentials) {
1685
- await this.validateProviderCredentials(credentials);
1686
- }
1687
- /**
1688
- * Get provider lib root path.
1689
- *
1690
- * @returns Root of library
1691
- */ getProviderServerPath() {
1692
- return this.dir;
1693
- }
1694
- getProviderSchema() {
1695
- if (this._meta) {
1696
- return this._meta;
1697
- }
1698
- const yamlPath = path.join(this.getProviderServerPath(), `${this._name}.yaml`);
1699
- const yamlData = loadYamlFile(yamlPath, this.logger);
1700
- try {
1701
- this._meta = yamlData;
1702
- } catch (e) {
1703
- throw new Error(`Invalid provider schema for ${this.name}: ${e.message}`);
1704
- }
1705
- return this._meta;
1706
- }
1707
- async getModels(modelType) {
1708
- const providerSchema = this.getProviderSchema();
1709
- const supported = providerSchema.supported_model_types.includes(modelType) || modelType === contracts.AiModelTypeEnum.IMAGE && providerSchema.supported_model_types.includes(contracts.AiModelTypeEnum.TEXT2IMG);
1710
- if (!supported) {
1711
- return [];
1712
- }
1713
- var _this_modelManagers_get;
1714
- const modelInstance = modelType === contracts.AiModelTypeEnum.IMAGE ? (_this_modelManagers_get = this.modelManagers.get(contracts.AiModelTypeEnum.IMAGE)) != null ? _this_modelManagers_get : this.modelManagers.get(contracts.AiModelTypeEnum.TEXT2IMG) : this.modelManagers.get(modelType);
1715
- if (!modelInstance) {
1716
- throw new AiModelNotFoundException(`Missing AIModel instance for model type ${modelType}`);
1717
- }
1718
- return modelInstance.predefinedModels();
1719
- }
1720
- registerAIModelInstance(modelType, modelInstance) {
1721
- this.modelManagers.set(modelType, modelInstance);
1722
- }
1723
- getModelManager(modelType) {
1724
- const modelInstance = this.modelManagers.get(modelType);
1725
- if (!modelInstance) {
1726
- throw new AiModelNotFoundException(`Missing AIModel instance for model type ${modelType}`);
1727
- }
1728
- return modelInstance;
1729
- }
1730
- /**
1731
- * Get provider models.
1732
- * @param modelType - model type
1733
- * @param onlyActive - only active models
1734
- * @return provider models
1735
- */ getProviderModels(modelType, onlyActive = false) {
1736
- let modelTypes = [];
1737
- if (modelType) {
1738
- modelTypes.push(modelType);
1739
- } else {
1740
- modelTypes = this.getProviderSchema().supported_model_types;
1741
- }
1742
- const providerModels = this.getSystemProviderModels(modelTypes);
1743
- // Resort providerModels
1744
- return providerModels.sort((a, b)=>a.model_type.localeCompare(b.model_type));
1745
- }
1746
- getSystemProviderModels(modelTypes) {
1747
- const models = [];
1748
- modelTypes == null ? void 0 : modelTypes.forEach((modelType)=>{
1749
- var _this_modelManagers_get;
1750
- const modelManager = modelType === contracts.AiModelTypeEnum.IMAGE ? (_this_modelManagers_get = this.modelManagers.get(contracts.AiModelTypeEnum.IMAGE)) != null ? _this_modelManagers_get : this.modelManagers.get(contracts.AiModelTypeEnum.TEXT2IMG) : this.modelManagers.get(modelType);
1751
- if (modelManager) {
1752
- models.push(...modelManager.predefinedModels());
1753
- }
1754
- });
1755
- return models;
1756
- }
1757
- getChatModel(copilotModel, options) {
1758
- var _this_getModelManager;
1759
- return (_this_getModelManager = this.getModelManager(contracts.AiModelTypeEnum.LLM)) == null ? void 0 : _this_getModelManager.getChatModel(copilotModel, options);
1760
- }
1761
- async getModelInstance(type, copilotModel, options) {
1762
- switch(type){
1763
- case contracts.AiModelTypeEnum.LLM:
1764
- var _this_getModelManager;
1765
- return (_this_getModelManager = this.getModelManager(type)) == null ? void 0 : _this_getModelManager.getChatModel(copilotModel, options);
1766
- case contracts.AiModelTypeEnum.TEXT_EMBEDDING:
1767
- var _this_getModelManager1;
1768
- if (!copilotModel.options) {
1769
- var _copilotModel_copilot_copilotModel, _predefinedModels_find;
1770
- const predefinedModels = await this.getModels(contracts.AiModelTypeEnum.TEXT_EMBEDDING);
1771
- const modelName = copilotModel.model || ((_copilotModel_copilot_copilotModel = copilotModel.copilot.copilotModel) == null ? void 0 : _copilotModel_copilot_copilotModel.model);
1772
- copilotModel.options = (_predefinedModels_find = predefinedModels.find((_)=>_.model === modelName)) == null ? void 0 : _predefinedModels_find.model_properties;
1773
- }
1774
- return (_this_getModelManager1 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager1.getEmbeddingInstance(copilotModel, options);
1775
- case contracts.AiModelTypeEnum.TTS:
1776
- var _this_getModelManager2;
1777
- return (_this_getModelManager2 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager2.getChatModel(copilotModel, options);
1778
- case contracts.AiModelTypeEnum.SPEECH2TEXT:
1779
- var _this_getModelManager3;
1780
- return (_this_getModelManager3 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager3.getChatModel(copilotModel, options);
1781
- case contracts.AiModelTypeEnum.RERANK:
1782
- var _this_getModelManager4;
1783
- return (_this_getModelManager4 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager4.getReranker(copilotModel, options);
1784
- case contracts.AiModelTypeEnum.IMAGE:
1785
- var _this;
1786
- var _this_modelManagers_get;
1787
- return (_this = (_this_modelManagers_get = this.modelManagers.get(contracts.AiModelTypeEnum.IMAGE)) != null ? _this_modelManagers_get : this.modelManagers.get(contracts.AiModelTypeEnum.TEXT2IMG)) == null ? void 0 : _this.getAIGCModel(copilotModel, options);
1788
- case contracts.AiModelTypeEnum.TEXT2IMG:
1789
- case contracts.AiModelTypeEnum.VIDEO:
1790
- var _this_getModelManager5;
1791
- return (_this_getModelManager5 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager5.getAIGCModel(copilotModel, options);
1792
- }
1793
- return null;
1794
- }
1795
- constructor(){
1796
- this.logger = new common.Logger(ModelProvider_1.name);
1797
- // protected providerSchema: IAiProviderEntity | null = null
1798
- this.modelManagers = new Map();
1799
- const provider = Reflect.getMetadata(AI_MODEL_PROVIDER, this.constructor);
1800
- this._name = provider;
1801
- // Automatically retrieve provider DIR information from decorator metadata
1802
- const dir = Reflect.getMetadata(`${AI_MODEL_PROVIDER}_DIR`, this.constructor);
1803
- this.dir = dir;
1804
- }
1805
- };
1806
- exports.ModelProvider = ModelProvider_1 = __decorate([
1807
- common.Injectable(),
1808
- __metadata("design:paramtypes", [])
1809
- ], exports.ModelProvider);
1810
-
1811
1672
  function valueOf(enumObj, value) {
1812
1673
  const enumValues = Object.values(enumObj);
1813
1674
  if (enumValues.includes(value)) {
@@ -1953,6 +1814,145 @@ const PARAMETER_RULE_TEMPLATE = {
1953
1814
  }
1954
1815
  };
1955
1816
 
1817
+ class AiModelNotFoundException extends common.NotFoundException {
1818
+ }
1819
+ class CredentialsValidateFailedError extends common.ForbiddenException {
1820
+ }
1821
+ class AIModelProviderNotFoundException extends common.NotFoundException {
1822
+ }
1823
+
1824
+ var ModelProvider_1;
1825
+ exports.ModelProvider = ModelProvider_1 = class ModelProvider {
1826
+ get name() {
1827
+ return this.getProviderSchema().provider;
1828
+ }
1829
+ async validateCredentials(credentials) {
1830
+ await this.validateProviderCredentials(credentials);
1831
+ }
1832
+ /**
1833
+ * Get provider lib root path.
1834
+ *
1835
+ * @returns Root of library
1836
+ */ getProviderServerPath() {
1837
+ return this.dir;
1838
+ }
1839
+ getProviderSchema() {
1840
+ if (this._meta) {
1841
+ return this._meta;
1842
+ }
1843
+ const yamlPath = path.join(this.getProviderServerPath(), `${this._name}.yaml`);
1844
+ const yamlData = loadYamlFile(yamlPath, this.logger);
1845
+ try {
1846
+ this._meta = yamlData;
1847
+ } catch (e) {
1848
+ throw new Error(`Invalid provider schema for ${this.name}: ${e.message}`);
1849
+ }
1850
+ return this._meta;
1851
+ }
1852
+ async getModels(modelType) {
1853
+ const providerSchema = this.getProviderSchema();
1854
+ const supported = providerSchema.supported_model_types.includes(modelType) || modelType === contracts.AiModelTypeEnum.IMAGE && providerSchema.supported_model_types.includes(contracts.AiModelTypeEnum.TEXT2IMG);
1855
+ if (!supported) {
1856
+ return [];
1857
+ }
1858
+ var _this_modelManagers_get;
1859
+ const modelInstance = modelType === contracts.AiModelTypeEnum.IMAGE ? (_this_modelManagers_get = this.modelManagers.get(contracts.AiModelTypeEnum.IMAGE)) != null ? _this_modelManagers_get : this.modelManagers.get(contracts.AiModelTypeEnum.TEXT2IMG) : this.modelManagers.get(modelType);
1860
+ if (!modelInstance) {
1861
+ throw new AiModelNotFoundException(`Missing AIModel instance for model type ${modelType}`);
1862
+ }
1863
+ return modelInstance.predefinedModels();
1864
+ }
1865
+ registerAIModelInstance(modelType, modelInstance) {
1866
+ this.modelManagers.set(modelType, modelInstance);
1867
+ }
1868
+ getModelManager(modelType) {
1869
+ const modelInstance = this.modelManagers.get(modelType);
1870
+ if (!modelInstance) {
1871
+ throw new AiModelNotFoundException(`Missing AIModel instance for model type ${modelType}`);
1872
+ }
1873
+ return modelInstance;
1874
+ }
1875
+ /**
1876
+ * Get provider models.
1877
+ * @param modelType - model type
1878
+ * @param onlyActive - only active models
1879
+ * @return provider models
1880
+ */ getProviderModels(modelType, onlyActive = false) {
1881
+ let modelTypes = [];
1882
+ if (modelType) {
1883
+ modelTypes.push(modelType);
1884
+ } else {
1885
+ modelTypes = this.getProviderSchema().supported_model_types;
1886
+ }
1887
+ const providerModels = this.getSystemProviderModels(modelTypes);
1888
+ // Resort providerModels
1889
+ return providerModels.sort((a, b)=>a.model_type.localeCompare(b.model_type));
1890
+ }
1891
+ getSystemProviderModels(modelTypes) {
1892
+ const models = [];
1893
+ modelTypes == null ? void 0 : modelTypes.forEach((modelType)=>{
1894
+ var _this_modelManagers_get;
1895
+ const modelManager = modelType === contracts.AiModelTypeEnum.IMAGE ? (_this_modelManagers_get = this.modelManagers.get(contracts.AiModelTypeEnum.IMAGE)) != null ? _this_modelManagers_get : this.modelManagers.get(contracts.AiModelTypeEnum.TEXT2IMG) : this.modelManagers.get(modelType);
1896
+ if (modelManager) {
1897
+ models.push(...modelManager.predefinedModels());
1898
+ }
1899
+ });
1900
+ return models;
1901
+ }
1902
+ getChatModel(copilotModel, options) {
1903
+ var _this_getModelManager;
1904
+ return (_this_getModelManager = this.getModelManager(contracts.AiModelTypeEnum.LLM)) == null ? void 0 : _this_getModelManager.getChatModel(copilotModel, options);
1905
+ }
1906
+ async getModelInstance(type, copilotModel, options) {
1907
+ switch(type){
1908
+ case contracts.AiModelTypeEnum.LLM:
1909
+ var _this_getModelManager;
1910
+ return (_this_getModelManager = this.getModelManager(type)) == null ? void 0 : _this_getModelManager.getChatModel(copilotModel, options);
1911
+ case contracts.AiModelTypeEnum.TEXT_EMBEDDING:
1912
+ var _this_getModelManager1;
1913
+ if (!copilotModel.options) {
1914
+ var _copilotModel_copilot_copilotModel, _predefinedModels_find;
1915
+ const predefinedModels = await this.getModels(contracts.AiModelTypeEnum.TEXT_EMBEDDING);
1916
+ const modelName = copilotModel.model || ((_copilotModel_copilot_copilotModel = copilotModel.copilot.copilotModel) == null ? void 0 : _copilotModel_copilot_copilotModel.model);
1917
+ copilotModel.options = (_predefinedModels_find = predefinedModels.find((_)=>_.model === modelName)) == null ? void 0 : _predefinedModels_find.model_properties;
1918
+ }
1919
+ return (_this_getModelManager1 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager1.getEmbeddingInstance(copilotModel, options);
1920
+ case contracts.AiModelTypeEnum.TTS:
1921
+ var _this_getModelManager2;
1922
+ return (_this_getModelManager2 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager2.getChatModel(copilotModel, options);
1923
+ case contracts.AiModelTypeEnum.SPEECH2TEXT:
1924
+ var _this_getModelManager3;
1925
+ return (_this_getModelManager3 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager3.getChatModel(copilotModel, options);
1926
+ case contracts.AiModelTypeEnum.RERANK:
1927
+ var _this_getModelManager4;
1928
+ return (_this_getModelManager4 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager4.getReranker(copilotModel, options);
1929
+ case contracts.AiModelTypeEnum.IMAGE:
1930
+ var _this;
1931
+ var _this_modelManagers_get;
1932
+ return (_this = (_this_modelManagers_get = this.modelManagers.get(contracts.AiModelTypeEnum.IMAGE)) != null ? _this_modelManagers_get : this.modelManagers.get(contracts.AiModelTypeEnum.TEXT2IMG)) == null ? void 0 : _this.getAIGCModel(copilotModel, options);
1933
+ case contracts.AiModelTypeEnum.TEXT2IMG:
1934
+ case contracts.AiModelTypeEnum.VIDEO:
1935
+ var _this_getModelManager5;
1936
+ return (_this_getModelManager5 = this.getModelManager(type)) == null ? void 0 : _this_getModelManager5.getAIGCModel(copilotModel, options);
1937
+ }
1938
+ return null;
1939
+ }
1940
+ constructor(){
1941
+ this.logger = new common.Logger(ModelProvider_1.name);
1942
+ // protected providerSchema: IAiProviderEntity | null = null
1943
+ this.modelManagers = new Map();
1944
+ const provider = Reflect.getMetadata(AI_MODEL_PROVIDER, this.constructor);
1945
+ this._name = provider;
1946
+ // Automatically retrieve provider DIR information from decorator metadata
1947
+ const dir = Reflect.getMetadata(`${AI_MODEL_PROVIDER}_DIR`, this.constructor);
1948
+ this.dir = dir;
1949
+ }
1950
+ };
1951
+ exports.ModelProvider = ModelProvider_1 = __decorate([
1952
+ common.Injectable(),
1953
+ __metadata("design:paramtypes", [])
1954
+ ], exports.ModelProvider);
1955
+
1956
1956
  const CommonParameterRules = [
1957
1957
  {
1958
1958
  name: 'temperature',
@@ -2014,33 +2014,143 @@ function calculateModelPrice(pricing, priceType, tokens, inputTokens = tokens) {
2014
2014
  currency: pricing.currency
2015
2015
  };
2016
2016
  }
2017
+ function calculateLLMUsagePrice(pricing, usage, context = {}) {
2018
+ var _pricing_rules;
2019
+ validateLLMPriceRules((_pricing_rules = pricing.rules) != null ? _pricing_rules : []);
2020
+ const pricingContext = _extends._extends({}, context, {
2021
+ pricingTime: resolvePricingTime(context.pricingTime)
2022
+ });
2023
+ const promptTokens = tokenCount(usage.promptTokens, 'promptTokens');
2024
+ const completionTokens = tokenCount(usage.completionTokens, 'completionTokens');
2025
+ var _usage_cacheReadInputTokens;
2026
+ const cacheReadInputTokens = tokenCount((_usage_cacheReadInputTokens = usage.cacheReadInputTokens) != null ? _usage_cacheReadInputTokens : 0, 'cacheReadInputTokens');
2027
+ var _usage_cacheWriteInputTokens;
2028
+ const cacheWriteInputTokens = tokenCount((_usage_cacheWriteInputTokens = usage.cacheWriteInputTokens) != null ? _usage_cacheWriteInputTokens : 0, 'cacheWriteInputTokens');
2029
+ const cacheTokens = cacheReadInputTokens + cacheWriteInputTokens;
2030
+ const inputTokens = context.inputTokensIncludeCache === false ? promptTokens + cacheTokens : promptTokens;
2031
+ let standardInputTokens = context.inputTokensIncludeCache === false ? promptTokens : promptTokens - cacheTokens;
2032
+ if (standardInputTokens < 0) {
2033
+ throw new Error('Cache read and write tokens cannot exceed prompt tokens when input includes cache tokens');
2034
+ }
2035
+ const selectionContext = {
2036
+ inputTokens,
2037
+ outputTokens: completionTokens,
2038
+ context: pricingContext
2039
+ };
2040
+ const breakdown = [];
2041
+ const cacheReadRule = selectLLMPriceRule(pricing.rules, 'cache_read_input', selectionContext);
2042
+ if (cacheReadInputTokens > 0) {
2043
+ if (cacheReadRule) {
2044
+ breakdown.push(priceRuleComponent(cacheReadRule, cacheReadInputTokens, pricing.currency));
2045
+ } else if (hasLLMPriceRule(pricing.rules, 'cache_read_input')) {
2046
+ breakdown.push(unpricedComponent('cache_read_input', cacheReadInputTokens));
2047
+ } else {
2048
+ standardInputTokens += cacheReadInputTokens;
2049
+ }
2050
+ }
2051
+ for (const cacheWrite of resolveCacheWriteInputTokens(cacheWriteInputTokens, context)){
2052
+ const cacheWriteSelection = _extends._extends({}, selectionContext, {
2053
+ context: _extends._extends({}, pricingContext, {
2054
+ cacheWriteTtl: cacheWrite.cacheTtl
2055
+ })
2056
+ });
2057
+ const cacheWriteRule = selectLLMPriceRule(pricing.rules, 'cache_write_input', cacheWriteSelection);
2058
+ if (cacheWriteRule) {
2059
+ breakdown.push(priceRuleComponent(cacheWriteRule, cacheWrite.quantity, pricing.currency, {
2060
+ cacheTtl: cacheWrite.cacheTtl
2061
+ }));
2062
+ } else if (hasLLMPriceRule(pricing.rules, 'cache_write_input')) {
2063
+ breakdown.push(unpricedComponent('cache_write_input', cacheWrite.quantity, {
2064
+ cacheTtl: cacheWrite.cacheTtl
2065
+ }));
2066
+ } else {
2067
+ standardInputTokens += cacheWrite.quantity;
2068
+ }
2069
+ }
2070
+ if (standardInputTokens > 0) {
2071
+ const inputRule = selectLLMPriceRule(pricing.rules, 'input', selectionContext);
2072
+ breakdown.push(inputRule ? priceRuleComponent(inputRule, standardInputTokens, pricing.currency) : hasLLMPriceRule(pricing.rules, 'input') ? unpricedComponent('input', standardInputTokens) : legacyPriceComponent(pricing, contracts.PriceType.INPUT, standardInputTokens, inputTokens));
2073
+ }
2074
+ if (completionTokens > 0) {
2075
+ const outputRule = selectLLMPriceRule(pricing.rules, 'output', selectionContext);
2076
+ breakdown.push(outputRule ? priceRuleComponent(outputRule, completionTokens, pricing.currency) : hasLLMPriceRule(pricing.rules, 'output') ? unpricedComponent('output', completionTokens) : legacyPriceComponent(pricing, contracts.PriceType.OUTPUT, completionTokens, inputTokens));
2077
+ }
2078
+ const addOns = new Map();
2079
+ var _context_addOns;
2080
+ for (const addOn of (_context_addOns = context.addOns) != null ? _context_addOns : []){
2081
+ const quantity = nonNegativeQuantity(addOn.quantity, `add-on '${addOn.type}'`);
2082
+ if (quantity === 0) continue;
2083
+ var _addOns_get;
2084
+ addOns.set(addOn.type, ((_addOns_get = addOns.get(addOn.type)) != null ? _addOns_get : 0) + quantity);
2085
+ }
2086
+ for (const [addOn, quantity] of addOns){
2087
+ const rule = selectLLMPriceRule(pricing.rules, 'request', selectionContext, addOn);
2088
+ breakdown.push(rule ? priceRuleComponent(rule, quantity, pricing.currency, {
2089
+ addOn
2090
+ }) : unpricedComponent('request', quantity, {
2091
+ addOn
2092
+ }));
2093
+ }
2094
+ var _context_unpricedAddOns;
2095
+ for (const addOn of (_context_unpricedAddOns = context.unpricedAddOns) != null ? _context_unpricedAddOns : []){
2096
+ const quantity = nonNegativeQuantity(addOn.quantity, `unpriced add-on '${addOn.type}'`);
2097
+ if (quantity === 0) continue;
2098
+ breakdown.push(unpricedComponent('request', quantity, {
2099
+ addOn: addOn.type,
2100
+ addOnAuthority: addOn.authority
2101
+ }));
2102
+ }
2103
+ if (context.cacheStorageTokenHours !== undefined) {
2104
+ const quantity = nonNegativeQuantity(context.cacheStorageTokenHours, 'cacheStorageTokenHours');
2105
+ if (quantity > 0) {
2106
+ const rule = selectLLMPriceRule(pricing.rules, 'cache_storage', selectionContext);
2107
+ breakdown.push(rule ? priceRuleComponent(rule, quantity, pricing.currency) : unpricedComponent('cache_storage', quantity));
2108
+ }
2109
+ }
2110
+ return summarizeLLMPrice(pricing.currency, breakdown);
2111
+ }
2017
2112
  function resolveModelUsagePricingSnapshot(pricing, context) {
2018
2113
  var _normalizeDate;
2019
2114
  var _normalizeDate_toISOString;
2020
2115
  const capturedAt = (_normalizeDate_toISOString = (_normalizeDate = normalizeDate(context.startedAt)) == null ? void 0 : _normalizeDate.toISOString()) != null ? _normalizeDate_toISOString : new Date().toISOString();
2021
2116
  if (!isModelUsagePricingConfig(pricing)) {
2022
- return {
2023
- capturedAt,
2117
+ return _extends._extends({
2118
+ capturedAt
2119
+ }, context.pricingDimensions ? {
2120
+ pricingDimensions: context.pricingDimensions
2121
+ } : {}, {
2024
2122
  rules: []
2025
- };
2123
+ });
2026
2124
  }
2027
2125
  const at = new Date(capturedAt);
2028
- const rules = pricing.rules.filter((rule)=>matchesUsagePriceRule(rule, context, at));
2029
- const units = new Set();
2030
- for (const rule of rules){
2126
+ const matchingRules = pricing.rules.filter((rule)=>matchesUsagePriceRule(rule, context, at));
2127
+ const rules = [];
2128
+ for (const rule of matchingRules){
2031
2129
  validateUsagePriceRule(rule);
2032
- if (units.has(rule.unit)) {
2130
+ const selector = usagePriceRuleSelector(rule);
2131
+ const existingIndex = rules.findIndex((candidate)=>usagePriceRuleSelector(candidate) === selector);
2132
+ if (existingIndex < 0) {
2133
+ rules.push(rule);
2134
+ continue;
2135
+ }
2136
+ const existing = rules[existingIndex];
2137
+ const existingHasWindow = Boolean(existing.daily_time_window);
2138
+ const currentHasWindow = Boolean(rule.daily_time_window);
2139
+ if (existingHasWindow === currentHasWindow) {
2033
2140
  throw new Error(`Ambiguous usage pricing rules for unit '${rule.unit}'`);
2034
2141
  }
2035
- units.add(rule.unit);
2142
+ if (currentHasWindow) rules[existingIndex] = rule;
2036
2143
  }
2037
- return {
2038
- capturedAt,
2144
+ return _extends._extends({
2145
+ capturedAt
2146
+ }, context.pricingDimensions ? {
2147
+ pricingDimensions: context.pricingDimensions
2148
+ } : {}, {
2039
2149
  rules
2040
- };
2150
+ });
2041
2151
  }
2042
2152
  function calculateModelUsageCharge(snapshot, metric) {
2043
- const rule = snapshot == null ? void 0 : snapshot.rules.find((candidate)=>candidate.unit === metric.unit);
2153
+ const rule = selectUsagePriceRule(snapshot, metric);
2044
2154
  const fallbackQuantity = metricQuantity(metric);
2045
2155
  if (!rule) {
2046
2156
  return {
@@ -2083,8 +2193,40 @@ function matchesUsagePriceRule(rule, context, at) {
2083
2193
  const effectiveTo = normalizeDate(rule.effective_to);
2084
2194
  if (!effectiveFrom || effectiveFrom > at || effectiveTo && effectiveTo <= at) return false;
2085
2195
  if (((_rule_operations = rule.operations) == null ? void 0 : _rule_operations.length) && !rule.operations.includes(context.operation)) return false;
2196
+ if (rule.daily_time_window) {
2197
+ validateRecurringDailyWindow(rule.daily_time_window);
2198
+ if (!isInRecurringDailyWindow(rule.daily_time_window, at)) return false;
2199
+ }
2086
2200
  var _context_pricingDimensions;
2087
2201
  const dimensions = (_context_pricingDimensions = context.pricingDimensions) != null ? _context_pricingDimensions : {};
2202
+ var _rule_dimensions;
2203
+ return Object.entries((_rule_dimensions = rule.dimensions) != null ? _rule_dimensions : {}).every(([key, value])=>{
2204
+ if (key === 'resolution') return dimensions.resolution === undefined || dimensions.resolution === value;
2205
+ if (key === 'audio') return dimensions.audio === undefined || dimensions.audio === value;
2206
+ if (key === 'videoInput') return dimensions.videoInput === undefined || dimensions.videoInput === value;
2207
+ if (key === 'mode') return dimensions.mode === undefined || dimensions.mode === value;
2208
+ return false;
2209
+ });
2210
+ }
2211
+ function selectUsagePriceRule(snapshot, metric) {
2212
+ var _snapshot_pricingDimensions, _metric_pricingDimensions;
2213
+ const dimensions = _extends._extends({}, (_snapshot_pricingDimensions = snapshot == null ? void 0 : snapshot.pricingDimensions) != null ? _snapshot_pricingDimensions : {}, (_metric_pricingDimensions = metric.pricingDimensions) != null ? _metric_pricingDimensions : {});
2214
+ var _snapshot_rules;
2215
+ const matches = ((_snapshot_rules = snapshot == null ? void 0 : snapshot.rules) != null ? _snapshot_rules : []).filter((rule)=>{
2216
+ if (rule.unit !== metric.unit) return false;
2217
+ if (rule.component && rule.component !== metric.component) return false;
2218
+ return matchesUsagePriceDimensions(rule, dimensions);
2219
+ });
2220
+ if (!matches.length) return undefined;
2221
+ const specificity = Math.max(...matches.map(usagePriceRuleSpecificity));
2222
+ const mostSpecific = matches.filter((rule)=>usagePriceRuleSpecificity(rule) === specificity);
2223
+ if (mostSpecific.length > 1) {
2224
+ var _metric_key;
2225
+ throw new Error(`Ambiguous usage pricing rules for metric '${(_metric_key = metric.key) != null ? _metric_key : metric.unit}'`);
2226
+ }
2227
+ return mostSpecific[0];
2228
+ }
2229
+ function matchesUsagePriceDimensions(rule, dimensions) {
2088
2230
  var _rule_dimensions;
2089
2231
  return Object.entries((_rule_dimensions = rule.dimensions) != null ? _rule_dimensions : {}).every(([key, value])=>{
2090
2232
  if (key === 'resolution') return dimensions.resolution === value;
@@ -2094,15 +2236,36 @@ function matchesUsagePriceRule(rule, context, at) {
2094
2236
  return false;
2095
2237
  });
2096
2238
  }
2239
+ function usagePriceRuleSpecificity(rule) {
2240
+ var _rule_dimensions;
2241
+ return (rule.component ? 1 : 0) + Object.keys((_rule_dimensions = rule.dimensions) != null ? _rule_dimensions : {}).length;
2242
+ }
2243
+ function usagePriceRuleSelector(rule) {
2244
+ var _rule_token_type, _rule_component, _rule_dimensions;
2245
+ return JSON.stringify([
2246
+ rule.unit,
2247
+ (_rule_token_type = rule.token_type) != null ? _rule_token_type : null,
2248
+ (_rule_component = rule.component) != null ? _rule_component : null,
2249
+ Object.entries((_rule_dimensions = rule.dimensions) != null ? _rule_dimensions : {}).sort(([left], [right])=>left.localeCompare(right))
2250
+ ]);
2251
+ }
2097
2252
  function validateUsagePriceRule(rule) {
2098
2253
  var _rule_id, _rule_version;
2099
2254
  if (!((_rule_id = rule.id) == null ? void 0 : _rule_id.trim()) || !((_rule_version = rule.version) == null ? void 0 : _rule_version.trim())) throw new Error('Usage pricing rules require id and version');
2255
+ if (rule.component && ![
2256
+ 'input',
2257
+ 'output',
2258
+ 'request'
2259
+ ].includes(rule.component)) {
2260
+ throw new Error(`Usage pricing rule '${rule.id}' has an invalid component`);
2261
+ }
2100
2262
  if (!Number.isFinite(Number(rule.unit_size)) || Number(rule.unit_size) <= 0) {
2101
2263
  throw new Error(`Usage pricing rule '${rule.id}' requires a positive unit_size`);
2102
2264
  }
2103
2265
  if (rule.unit !== 'token' && rule.token_type) {
2104
2266
  throw new Error(`Usage pricing rule '${rule.id}' can only use token_type with token pricing`);
2105
2267
  }
2268
+ if (rule.daily_time_window) validateRecurringDailyWindow(rule.daily_time_window);
2106
2269
  if (rule.charge_type === 'paid') {
2107
2270
  var _rule_currency;
2108
2271
  if (!Number.isFinite(Number(rule.unit_price)) || Number(rule.unit_price) <= 0 || !((_rule_currency = rule.currency) == null ? void 0 : _rule_currency.trim())) {
@@ -2133,9 +2296,237 @@ function normalizeDate(value) {
2133
2296
  function roundCharge(value) {
2134
2297
  return Number(value.toFixed(10));
2135
2298
  }
2299
+ function hasLLMPriceRule(rules, component) {
2300
+ var _rules_some;
2301
+ return (_rules_some = rules == null ? void 0 : rules.some((rule)=>rule.component === component)) != null ? _rules_some : false;
2302
+ }
2303
+ function selectLLMPriceRule(rules, component, selection, addOn) {
2304
+ const matches = (rules != null ? rules : []).filter((rule)=>{
2305
+ if (rule.component !== component) return false;
2306
+ if (component === 'request' && rule.add_on !== addOn) return false;
2307
+ if (rule.cache_ttl && rule.cache_ttl !== selection.context.cacheWriteTtl) return false;
2308
+ if (rule.mode && rule.mode !== selection.context.mode) return false;
2309
+ if (rule.region && rule.region !== selection.context.region) return false;
2310
+ if (rule.service_tier && rule.service_tier !== selection.context.serviceTier) return false;
2311
+ if (rule.daily_time_window && !isInRecurringDailyWindow(rule.daily_time_window, selection.context.pricingTime)) {
2312
+ return false;
2313
+ }
2314
+ if (rule.min_input_tokens !== undefined && selection.inputTokens < Number(rule.min_input_tokens)) return false;
2315
+ if (rule.max_input_tokens !== undefined && selection.inputTokens > Number(rule.max_input_tokens)) return false;
2316
+ if (rule.min_output_tokens !== undefined && selection.outputTokens < Number(rule.min_output_tokens)) return false;
2317
+ if (rule.max_output_tokens !== undefined && selection.outputTokens > Number(rule.max_output_tokens)) return false;
2318
+ return true;
2319
+ });
2320
+ if (!matches.length) return undefined;
2321
+ const specificity = Math.max(...matches.map(ruleSpecificity));
2322
+ const mostSpecific = matches.filter((rule)=>ruleSpecificity(rule) === specificity);
2323
+ if (mostSpecific.length > 1) {
2324
+ throw new Error(`Ambiguous LLM pricing rules for component '${component}'`);
2325
+ }
2326
+ return mostSpecific[0];
2327
+ }
2328
+ function ruleSpecificity(rule) {
2329
+ return [
2330
+ rule.min_input_tokens,
2331
+ rule.max_input_tokens,
2332
+ rule.min_output_tokens,
2333
+ rule.max_output_tokens,
2334
+ rule.mode,
2335
+ rule.region,
2336
+ rule.service_tier,
2337
+ rule.add_on,
2338
+ rule.cache_ttl,
2339
+ rule.daily_time_window
2340
+ ].filter((value)=>value !== undefined).length;
2341
+ }
2342
+ function validateLLMPriceRules(rules) {
2343
+ for (const rule of rules){
2344
+ if (!Number.isFinite(Number(rule.unit_price)) || Number(rule.unit_price) < 0) {
2345
+ throw new Error(`LLM pricing rule '${rule.component}' requires a non-negative unit_price`);
2346
+ }
2347
+ if (!Number.isFinite(Number(rule.unit_size)) || Number(rule.unit_size) <= 0) {
2348
+ throw new Error(`LLM pricing rule '${rule.component}' requires a positive unit_size`);
2349
+ }
2350
+ if (rule.currency !== undefined && !rule.currency.trim()) {
2351
+ throw new Error(`LLM pricing rule '${rule.component}' requires a non-empty currency when provided`);
2352
+ }
2353
+ validateTokenRange(rule, 'input', rule.min_input_tokens, rule.max_input_tokens);
2354
+ validateTokenRange(rule, 'output', rule.min_output_tokens, rule.max_output_tokens);
2355
+ if (rule.component === 'request' && !rule.add_on) {
2356
+ throw new Error('LLM request pricing rules require add_on');
2357
+ }
2358
+ if (rule.component !== 'request' && rule.add_on) {
2359
+ throw new Error(`LLM pricing rule '${rule.component}' cannot declare add_on`);
2360
+ }
2361
+ if (rule.component !== 'cache_write_input' && rule.cache_ttl) {
2362
+ throw new Error(`LLM pricing rule '${rule.component}' cannot declare cache_ttl`);
2363
+ }
2364
+ if (rule.daily_time_window) validateRecurringDailyWindow(rule.daily_time_window);
2365
+ }
2366
+ }
2367
+ function validateTokenRange(rule, name, min, max) {
2368
+ const normalizedMin = min === undefined ? undefined : Number(min);
2369
+ const normalizedMax = max === undefined ? undefined : Number(max);
2370
+ if (normalizedMin !== undefined) tokenCount(normalizedMin, `min_${name}_tokens`);
2371
+ if (normalizedMax !== undefined) tokenCount(normalizedMax, `max_${name}_tokens`);
2372
+ if (normalizedMin !== undefined && normalizedMax !== undefined && normalizedMin > normalizedMax) {
2373
+ throw new Error(`LLM pricing rule '${rule.component}' has an invalid ${name} token range`);
2374
+ }
2375
+ }
2376
+ function validateRecurringDailyWindow(window) {
2377
+ validateTimeZone(window.time_zone);
2378
+ const start = parseLocalTime(window.start_time, 'start_time');
2379
+ const end = parseLocalTime(window.end_time, 'end_time');
2380
+ if (start === end) {
2381
+ throw new Error('Recurring daily pricing window start_time and end_time must differ');
2382
+ }
2383
+ }
2384
+ function validateTimeZone(timeZone) {
2385
+ try {
2386
+ new Intl.DateTimeFormat('en-US', {
2387
+ timeZone
2388
+ }).format();
2389
+ } catch (e) {
2390
+ throw new Error(`Invalid IANA time zone '${timeZone}'`);
2391
+ }
2392
+ }
2393
+ function parseLocalTime(value, name) {
2394
+ const match = /^(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(value);
2395
+ if (!match) {
2396
+ throw new Error(`Recurring daily pricing window ${name} must use HH:mm or HH:mm:ss`);
2397
+ }
2398
+ const hour = Number(match[1]);
2399
+ const minute = Number(match[2]);
2400
+ var _match_;
2401
+ const second = Number((_match_ = match[3]) != null ? _match_ : 0);
2402
+ if (hour > 23 || minute > 59 || second > 59) {
2403
+ throw new Error(`Recurring daily pricing window ${name} must be a valid wall-clock time`);
2404
+ }
2405
+ return hour * 3600 + minute * 60 + second;
2406
+ }
2407
+ function isInRecurringDailyWindow(window, pricingTime) {
2408
+ const instant = resolvePricingTime(pricingTime);
2409
+ const formatter = new Intl.DateTimeFormat('en-GB', {
2410
+ timeZone: window.time_zone,
2411
+ hourCycle: 'h23',
2412
+ hour: '2-digit',
2413
+ minute: '2-digit',
2414
+ second: '2-digit'
2415
+ });
2416
+ const values = Object.fromEntries(formatter.formatToParts(instant).filter((part)=>part.type === 'hour' || part.type === 'minute' || part.type === 'second').map((part)=>[
2417
+ part.type,
2418
+ Number(part.value)
2419
+ ]));
2420
+ const localTime = values['hour'] * 3600 + values['minute'] * 60 + values['second'];
2421
+ const start = parseLocalTime(window.start_time, 'start_time');
2422
+ const end = parseLocalTime(window.end_time, 'end_time');
2423
+ return start < end ? localTime >= start && localTime < end : localTime >= start || localTime < end;
2424
+ }
2425
+ function resolvePricingTime(value) {
2426
+ const instant = value instanceof Date ? new Date(value.getTime()) : value === undefined ? new Date() : new Date(value);
2427
+ if (!Number.isFinite(instant.getTime())) {
2428
+ throw new Error('pricingTime must be a valid date');
2429
+ }
2430
+ return instant;
2431
+ }
2432
+ function priceRuleComponent(rule, quantity, fallbackCurrency, qualifiers = {}) {
2433
+ const unitPrice = Number(rule.unit_price);
2434
+ const unit = 1 / Number(rule.unit_size);
2435
+ const amount = roundCharge(quantity * unitPrice * unit);
2436
+ var _rule_currency;
2437
+ return _extends._extends({
2438
+ component: rule.component,
2439
+ quantity,
2440
+ pricingStatus: unitPrice === 0 ? 'free' : 'priced',
2441
+ unitPrice,
2442
+ unit,
2443
+ amount,
2444
+ currency: normalizeCurrency((_rule_currency = rule.currency) != null ? _rule_currency : fallbackCurrency)
2445
+ }, qualifiers, {
2446
+ rule
2447
+ });
2448
+ }
2449
+ function legacyPriceComponent(pricing, priceType, quantity, inputTokens) {
2450
+ const price = calculateModelPrice(pricing, priceType, quantity, inputTokens);
2451
+ return {
2452
+ component: priceType,
2453
+ quantity,
2454
+ pricingStatus: price.unitPrice === 0 ? 'free' : 'priced',
2455
+ unitPrice: price.unitPrice,
2456
+ unit: price.unit,
2457
+ amount: price.totalAmount,
2458
+ currency: normalizeCurrency(price.currency)
2459
+ };
2460
+ }
2461
+ function unpricedComponent(component, quantity, qualifiers = {}) {
2462
+ return _extends._extends({
2463
+ component,
2464
+ quantity,
2465
+ pricingStatus: 'unpriced'
2466
+ }, qualifiers);
2467
+ }
2468
+ function tokenCount(value, name) {
2469
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {
2470
+ throw new Error(`${name} must be a finite non-negative integer`);
2471
+ }
2472
+ return value;
2473
+ }
2474
+ function nonNegativeQuantity(value, name) {
2475
+ if (!Number.isFinite(value) || value < 0) {
2476
+ throw new Error(`${name} must be a non-negative number`);
2477
+ }
2478
+ return value;
2479
+ }
2480
+ function resolveCacheWriteInputTokens(total, context) {
2481
+ if (!context.cacheWriteInputTokensByTtl) {
2482
+ return total > 0 ? [
2483
+ {
2484
+ quantity: total,
2485
+ cacheTtl: context.cacheWriteTtl
2486
+ }
2487
+ ] : [];
2488
+ }
2489
+ const cacheWrites = [
2490
+ '5m',
2491
+ '1h'
2492
+ ].map((cacheTtl)=>{
2493
+ var _context_cacheWriteInputTokensByTtl;
2494
+ var _context_cacheWriteInputTokensByTtl_cacheTtl;
2495
+ return {
2496
+ cacheTtl,
2497
+ quantity: tokenCount((_context_cacheWriteInputTokensByTtl_cacheTtl = (_context_cacheWriteInputTokensByTtl = context.cacheWriteInputTokensByTtl) == null ? void 0 : _context_cacheWriteInputTokensByTtl[cacheTtl]) != null ? _context_cacheWriteInputTokensByTtl_cacheTtl : 0, `cacheWriteInputTokensByTtl.${cacheTtl}`)
2498
+ };
2499
+ }).filter(({ quantity })=>quantity > 0);
2500
+ const detailedTotal = cacheWrites.reduce((sum, item)=>sum + item.quantity, 0);
2501
+ if (detailedTotal !== total) {
2502
+ throw new Error('Cache write token counts by TTL must equal cacheWriteInputTokens');
2503
+ }
2504
+ return cacheWrites;
2505
+ }
2506
+ function summarizeLLMPrice(currency, breakdown) {
2507
+ const hasUnpricedComponent = breakdown.some((item)=>item.pricingStatus === 'unpriced');
2508
+ const hasPaidComponent = breakdown.some((item)=>item.pricingStatus === 'priced');
2509
+ const currencies = new Set(breakdown.map((item)=>item.currency).filter((value)=>Boolean(value)).map(normalizeCurrency));
2510
+ if (currencies.size > 1) {
2511
+ throw new Error('LLM pricing calculation cannot mix currencies');
2512
+ }
2513
+ var _currencies_values_next_value;
2514
+ return {
2515
+ pricingStatus: hasUnpricedComponent ? 'unpriced' : hasPaidComponent ? 'priced' : 'free',
2516
+ totalAmount: Number(breakdown.reduce((total, item)=>{
2517
+ var _item_amount;
2518
+ return total + ((_item_amount = item.amount) != null ? _item_amount : 0);
2519
+ }, 0).toFixed(7)),
2520
+ currency: (_currencies_values_next_value = currencies.values().next().value) != null ? _currencies_values_next_value : normalizeCurrency(currency),
2521
+ breakdown
2522
+ };
2523
+ }
2524
+ function normalizeCurrency(currency) {
2525
+ return currency.trim().toUpperCase();
2526
+ }
2136
2527
 
2137
2528
  var AIModel_1;
2138
- let AIModel = AIModel_1 = class AIModel {
2529
+ exports.AIModel = AIModel_1 = class AIModel {
2139
2530
  getChatModel(copilotModel, options) {
2140
2531
  throw new Error(`Unsupport chat model!`);
2141
2532
  }
@@ -2270,13 +2661,21 @@ let AIModel = AIModel_1 = class AIModel {
2270
2661
  ];
2271
2662
  }
2272
2663
  getModelProfile(model, credentials) {
2273
- var _modelSchema_model_properties, _modelSchema_features, _modelSchema_features1, _modelSchema_features2, _modelSchema_features3;
2664
+ var _modelSchema_model_properties, _modelSchema_features, _modelSchema_features1, _modelSchema_features2, _modelSchema_features3, _modelSchema_features4, _modelSchema_features5, _modelSchema_parameter_rules;
2274
2665
  const modelSchema = this.getModelSchema(model, credentials);
2275
- return modelSchema && {
2666
+ if (!modelSchema) return null;
2667
+ const profile = {
2276
2668
  maxInputTokens: (_modelSchema_model_properties = modelSchema.model_properties) == null ? void 0 : _modelSchema_model_properties.context_size,
2277
- toolCalling: ((_modelSchema_features = modelSchema.features) == null ? void 0 : _modelSchema_features.includes(contracts.ModelFeature.TOOL_CALL)) || ((_modelSchema_features1 = modelSchema.features) == null ? void 0 : _modelSchema_features1.includes(contracts.ModelFeature.MULTI_TOOL_CALL)) || ((_modelSchema_features2 = modelSchema.features) == null ? void 0 : _modelSchema_features2.includes(contracts.ModelFeature.STREAM_TOOL_CALL)),
2278
- structuredOutput: (_modelSchema_features3 = modelSchema.features) == null ? void 0 : _modelSchema_features3.includes(contracts.ModelFeature.STRUCTURED_OUTPUT)
2669
+ imageInputs: (_modelSchema_features = modelSchema.features) == null ? void 0 : _modelSchema_features.includes(contracts.ModelFeature.VISION),
2670
+ videoInputs: (_modelSchema_features1 = modelSchema.features) == null ? void 0 : _modelSchema_features1.includes(contracts.ModelFeature.VIDEO),
2671
+ toolCalling: ((_modelSchema_features2 = modelSchema.features) == null ? void 0 : _modelSchema_features2.includes(contracts.ModelFeature.TOOL_CALL)) || ((_modelSchema_features3 = modelSchema.features) == null ? void 0 : _modelSchema_features3.includes(contracts.ModelFeature.MULTI_TOOL_CALL)) || ((_modelSchema_features4 = modelSchema.features) == null ? void 0 : _modelSchema_features4.includes(contracts.ModelFeature.STREAM_TOOL_CALL)),
2672
+ structuredOutput: (_modelSchema_features5 = modelSchema.features) == null ? void 0 : _modelSchema_features5.includes(contracts.ModelFeature.STRUCTURED_OUTPUT)
2279
2673
  };
2674
+ const maxTokensRule = (_modelSchema_parameter_rules = modelSchema.parameter_rules) == null ? void 0 : _modelSchema_parameter_rules.find((rule)=>rule.name === 'max_tokens');
2675
+ if (maxTokensRule) {
2676
+ profile.maxOutputTokens = maxTokensRule.max;
2677
+ }
2678
+ return profile;
2280
2679
  }
2281
2680
  constructor(modelProvider, modelType){
2282
2681
  this.logger = new common.Logger(AIModel_1.name);
@@ -2287,13 +2686,13 @@ let AIModel = AIModel_1 = class AIModel {
2287
2686
  this.modelProvider.registerAIModelInstance(this.modelType, this);
2288
2687
  }
2289
2688
  };
2290
- AIModel = AIModel_1 = __decorate([
2689
+ exports.AIModel = AIModel_1 = __decorate([
2291
2690
  common.Injectable(),
2292
2691
  __metadata("design:paramtypes", [
2293
2692
  exports.ModelProvider,
2294
2693
  String
2295
2694
  ])
2296
- ], AIModel);
2695
+ ], exports.AIModel);
2297
2696
  function getDefaultParameterRuleVariableMap(name) {
2298
2697
  /**
2299
2698
  * Get default parameter rule for given name
@@ -2307,19 +2706,19 @@ function getDefaultParameterRuleVariableMap(name) {
2307
2706
  return defaultParameterRule;
2308
2707
  }
2309
2708
 
2310
- class TextEmbeddingModelManager extends AIModel {
2709
+ class TextEmbeddingModelManager extends exports.AIModel {
2311
2710
  }
2312
2711
 
2313
- class RerankModel extends AIModel {
2712
+ class RerankModel extends exports.AIModel {
2314
2713
  async validateCredentials(model, credentials) {
2315
2714
  //
2316
2715
  }
2317
2716
  }
2318
2717
 
2319
- class SpeechToTextModel extends AIModel {
2718
+ class SpeechToTextModel extends exports.AIModel {
2320
2719
  }
2321
2720
 
2322
- class TextToSpeechModel extends AIModel {
2721
+ class TextToSpeechModel extends exports.AIModel {
2323
2722
  getParameterRules(model, credentials) {
2324
2723
  var _this__commonParameterRules;
2325
2724
  const rules = (_this__commonParameterRules = this._commonParameterRules(model)) != null ? _this__commonParameterRules : [];
@@ -2347,9 +2746,9 @@ class TextToSpeechModel extends AIModel {
2347
2746
  }
2348
2747
  }
2349
2748
 
2350
- class ImageGenerationModel extends AIModel {
2749
+ class ImageGenerationModel extends exports.AIModel {
2351
2750
  }
2352
- class VideoGenerationModel extends AIModel {
2751
+ class VideoGenerationModel extends exports.AIModel {
2353
2752
  }
2354
2753
 
2355
2754
  const PROVIDE_AI_MODEL_LLM = 'provide_ai_model_llm';
@@ -2412,11 +2811,59 @@ class LLMUsage {
2412
2811
  }
2413
2812
  }
2414
2813
  var _logger = /*#__PURE__*/ _class_private_field_loose_key("_logger");
2415
- class LargeLanguageModel extends AIModel {
2814
+ class LargeLanguageModel extends exports.AIModel {
2416
2815
  _commonParameterRules(model) {
2417
2816
  return CommonParameterRules;
2418
2817
  }
2419
- calcResponseUsage(model, credentials, promptTokens, completionTokens, startedAt = this.startedAt) {
2818
+ calcResponseUsage(model, credentials, promptTokens, completionTokens, startedAt = this.startedAt, tokenUsage, pricingContext = {}) {
2819
+ var _this_getModelSchema;
2820
+ const resolvedTokenUsage = tokenUsage != null ? tokenUsage : {
2821
+ promptTokens,
2822
+ completionTokens,
2823
+ totalTokens: promptTokens + completionTokens
2824
+ };
2825
+ const pricing = (_this_getModelSchema = this.getModelSchema(model, credentials)) == null ? void 0 : _this_getModelSchema.pricing;
2826
+ if (pricing && !isModelUsagePricingConfig(pricing)) {
2827
+ const calculation = calculateLLMUsagePrice(pricing, resolvedTokenUsage, pricingContext);
2828
+ const promptBreakdown = calculation.breakdown.filter((item)=>[
2829
+ 'input',
2830
+ 'cache_read_input',
2831
+ 'cache_write_input'
2832
+ ].includes(item.component));
2833
+ const completionBreakdown = calculation.breakdown.filter((item)=>item.component === 'output');
2834
+ var _promptBreakdown_find;
2835
+ const promptRate = (_promptBreakdown_find = promptBreakdown.find((item)=>item.component === 'input')) != null ? _promptBreakdown_find : promptBreakdown[0];
2836
+ const completionRate = completionBreakdown[0];
2837
+ var _promptRate_unitPrice, _promptRate_unit, _completionRate_unitPrice, _completionRate_unit;
2838
+ return _extends._extends({
2839
+ promptTokens,
2840
+ promptUnitPrice: (_promptRate_unitPrice = promptRate == null ? void 0 : promptRate.unitPrice) != null ? _promptRate_unitPrice : 0,
2841
+ promptPriceUnit: (_promptRate_unit = promptRate == null ? void 0 : promptRate.unit) != null ? _promptRate_unit : 0,
2842
+ promptPrice: Number(promptBreakdown.reduce((total, item)=>{
2843
+ var _item_amount;
2844
+ return total + ((_item_amount = item.amount) != null ? _item_amount : 0);
2845
+ }, 0).toFixed(7)),
2846
+ completionTokens,
2847
+ completionUnitPrice: (_completionRate_unitPrice = completionRate == null ? void 0 : completionRate.unitPrice) != null ? _completionRate_unitPrice : 0,
2848
+ completionPriceUnit: (_completionRate_unit = completionRate == null ? void 0 : completionRate.unit) != null ? _completionRate_unit : 0,
2849
+ completionPrice: Number(completionBreakdown.reduce((total, item)=>{
2850
+ var _item_amount;
2851
+ return total + ((_item_amount = item.amount) != null ? _item_amount : 0);
2852
+ }, 0).toFixed(7)),
2853
+ totalTokens: resolvedTokenUsage.totalTokens,
2854
+ totalPrice: calculation.totalAmount,
2855
+ currency: calculation.currency,
2856
+ latency: performance.now() - startedAt
2857
+ }, resolvedTokenUsage.cacheReadInputTokens ? {
2858
+ cacheReadInputTokens: resolvedTokenUsage.cacheReadInputTokens
2859
+ } : {}, resolvedTokenUsage.cacheWriteInputTokens ? {
2860
+ cacheWriteInputTokens: resolvedTokenUsage.cacheWriteInputTokens
2861
+ } : {}, {
2862
+ pricingStatus: calculation.pricingStatus,
2863
+ priceAuthority: 'catalog',
2864
+ pricingBreakdown: calculation.breakdown
2865
+ });
2866
+ }
2420
2867
  const promptPriceInfo = this.getPrice(model, credentials, contracts.PriceType.INPUT, promptTokens, promptTokens);
2421
2868
  const completionPriceInfo = this.getPrice(model, credentials, contracts.PriceType.OUTPUT, completionTokens, promptTokens);
2422
2869
  const totalPrice = Number((promptPriceInfo.totalAmount + completionPriceInfo.totalAmount).toFixed(7));
@@ -2433,32 +2880,50 @@ class LargeLanguageModel extends AIModel {
2433
2880
  totalTokens: promptTokens + completionTokens,
2434
2881
  totalPrice,
2435
2882
  currency: promptPriceInfo.currency,
2436
- latency: performance.now() - startedAt
2883
+ latency: performance.now() - startedAt,
2884
+ pricingStatus: totalPrice === 0 ? 'free' : 'priced',
2885
+ priceAuthority: 'catalog'
2437
2886
  };
2438
2887
  return usage;
2439
2888
  }
2440
- createHandleUsageCallbacks(copilot, model, credentials, handleLLMTokens) {
2889
+ createHandleUsageCallbacks(copilot, model, credentials, handleLLMTokens, pricingConfiguration = {}) {
2890
+ const pricingOptions = normalizeUsagePricingOptions(pricingConfiguration);
2891
+ var _pricingOptions_context;
2892
+ const basePricingContext = (_pricingOptions_context = pricingOptions.context) != null ? _pricingOptions_context : {};
2441
2893
  const runs = new Map();
2442
- const reportUsage = async (requestId, tokenUsage, startedAt, type)=>{
2443
- if (!handleLLMTokens || tokenUsage.totalTokens <= 0) {
2894
+ const reportUsage = async (requestId, tokenUsage, startedAt, pricingTime, type, output)=>{
2895
+ const pricingContext = _extends._extends({}, basePricingContext, output && pricingOptions.resolveContext ? pricingOptions.resolveContext(output) : {}, {
2896
+ pricingTime
2897
+ });
2898
+ const normalizedTokenUsage = normalizeCacheTokenAccounting(tokenUsage, pricingContext);
2899
+ if (!handleLLMTokens || normalizedTokenUsage.totalTokens <= 0) {
2444
2900
  return;
2445
2901
  }
2446
- const usage = _extends._extends({}, this.calcResponseUsage(model, credentials, tokenUsage.promptTokens, tokenUsage.completionTokens, startedAt), type ? {
2902
+ let usage = _extends._extends({}, this.calcResponseUsage(model, credentials, normalizedTokenUsage.promptTokens, normalizedTokenUsage.completionTokens, startedAt, normalizedTokenUsage, _extends._extends({}, pricingContext, {
2903
+ inputTokensIncludeCache: true
2904
+ })), type ? {
2447
2905
  type
2448
2906
  } : {});
2449
- usage.totalTokens = tokenUsage.totalTokens;
2907
+ const reportedPrice = output ? pricingOptions.resolveReportedPrice == null ? void 0 : pricingOptions.resolveReportedPrice.call(pricingOptions, output) : undefined;
2908
+ if (reportedPrice) {
2909
+ usage = applyProviderReportedPrice(usage, reportedPrice);
2910
+ } else if (pricingOptions.reportedPriceRequired) {
2911
+ usage = markUsagePriceUnpriced(usage, 'provider');
2912
+ }
2913
+ usage.totalTokens = normalizedTokenUsage.totalTokens;
2450
2914
  await handleLLMTokens({
2451
2915
  copilot,
2452
2916
  model,
2453
2917
  requestId,
2454
2918
  usage,
2455
- tokenUsed: tokenUsage.totalTokens
2919
+ tokenUsed: normalizedTokenUsage.totalTokens
2456
2920
  });
2457
2921
  };
2458
2922
  const callback = base.BaseCallbackHandler.fromMethods({
2459
2923
  handleLLMStart: (_llm, prompts, runId)=>{
2460
2924
  runs.set(runId, {
2461
2925
  startedAt: performance.now(),
2926
+ pricingTime: new Date(),
2462
2927
  prompts,
2463
2928
  completion: ''
2464
2929
  });
@@ -2474,11 +2939,11 @@ class LargeLanguageModel extends AIModel {
2474
2939
  runs.delete(runId);
2475
2940
  const resolved = resolveTokenUsageWithAuthority(output);
2476
2941
  if (resolved.usage.totalTokens > 0) {
2477
- var _run_startedAt;
2478
- await reportUsage(runId, resolved.usage, (_run_startedAt = run == null ? void 0 : run.startedAt) != null ? _run_startedAt : performance.now(), resolved.type);
2942
+ var _run_startedAt, _run_pricingTime;
2943
+ await reportUsage(runId, resolved.usage, (_run_startedAt = run == null ? void 0 : run.startedAt) != null ? _run_startedAt : performance.now(), (_run_pricingTime = run == null ? void 0 : run.pricingTime) != null ? _run_pricingTime : new Date(), resolved.type, output);
2479
2944
  } else {
2480
- var _run_startedAt1;
2481
- await reportUsage(runId, estimateFallbackUsage(run == null ? void 0 : run.prompts, (run == null ? void 0 : run.completion) || readCompletionText(output)), (_run_startedAt1 = run == null ? void 0 : run.startedAt) != null ? _run_startedAt1 : performance.now(), 'estimated');
2945
+ var _run_startedAt1, _run_pricingTime1;
2946
+ await reportUsage(runId, estimateFallbackUsage(run == null ? void 0 : run.prompts, (run == null ? void 0 : run.completion) || readCompletionText(output)), (_run_startedAt1 = run == null ? void 0 : run.startedAt) != null ? _run_startedAt1 : performance.now(), (_run_pricingTime1 = run == null ? void 0 : run.pricingTime) != null ? _run_pricingTime1 : new Date(), 'estimated', output);
2482
2947
  }
2483
2948
  },
2484
2949
  handleLLMError: async (error, runId)=>{
@@ -2487,8 +2952,8 @@ class LargeLanguageModel extends AIModel {
2487
2952
  if (!(run == null ? void 0 : run.completion) && !isAbortError(error)) {
2488
2953
  return;
2489
2954
  }
2490
- var _run_startedAt;
2491
- await reportUsage(runId, estimateFallbackUsage(run == null ? void 0 : run.prompts, run == null ? void 0 : run.completion), (_run_startedAt = run == null ? void 0 : run.startedAt) != null ? _run_startedAt : performance.now(), 'estimated');
2955
+ var _run_startedAt, _run_pricingTime;
2956
+ await reportUsage(runId, estimateFallbackUsage(run == null ? void 0 : run.prompts, run == null ? void 0 : run.completion), (_run_startedAt = run == null ? void 0 : run.startedAt) != null ? _run_startedAt : performance.now(), (_run_pricingTime = run == null ? void 0 : run.pricingTime) != null ? _run_pricingTime : new Date(), 'estimated');
2492
2957
  }
2493
2958
  });
2494
2959
  callback.awaitHandlers = true;
@@ -2631,6 +3096,37 @@ class LargeLanguageModel extends AIModel {
2631
3096
  }
2632
3097
  }
2633
3098
  _a = LargeLanguageModel;
3099
+ function normalizeUsagePricingOptions(configuration) {
3100
+ if ('context' in configuration || 'resolveContext' in configuration || 'resolveReportedPrice' in configuration || 'reportedPriceRequired' in configuration) {
3101
+ return configuration;
3102
+ }
3103
+ return {
3104
+ context: configuration
3105
+ };
3106
+ }
3107
+ function applyProviderReportedPrice(usage, reportedPrice) {
3108
+ var _reportedPrice_currency;
3109
+ const amount = Number(reportedPrice.amount);
3110
+ const currency = (_reportedPrice_currency = reportedPrice.currency) == null ? void 0 : _reportedPrice_currency.trim();
3111
+ if (!Number.isFinite(amount) || amount < 0 || !currency) {
3112
+ throw new Error('Provider-reported price requires a non-negative amount and currency');
3113
+ }
3114
+ return _extends._extends({}, usage, {
3115
+ totalPrice: amount,
3116
+ currency: currency.toUpperCase(),
3117
+ pricingStatus: amount === 0 ? 'free' : 'priced',
3118
+ priceAuthority: 'provider',
3119
+ pricingBreakdown: undefined
3120
+ });
3121
+ }
3122
+ function markUsagePriceUnpriced(usage, priceAuthority) {
3123
+ return _extends._extends({}, usage, {
3124
+ totalPrice: 0,
3125
+ pricingStatus: 'unpriced',
3126
+ priceAuthority,
3127
+ pricingBreakdown: undefined
3128
+ });
3129
+ }
2634
3130
  function estimateFallbackUsage(prompts, completion) {
2635
3131
  if (!prompts) {
2636
3132
  return {
@@ -2687,16 +3183,25 @@ function calcTokenUsage(output) {
2687
3183
  completionTokens: 0,
2688
3184
  totalTokens: 0
2689
3185
  };
3186
+ let cacheReadInputTokens = 0;
3187
+ let cacheWriteInputTokens = 0;
2690
3188
  (_output_generations = output.generations) == null ? void 0 : _output_generations.forEach((generation)=>{
2691
3189
  generation.forEach((item)=>{
2692
3190
  const message = item.message;
2693
3191
  if (message.usage_metadata) {
3192
+ var _message_usage_metadata_input_token_details, _message_usage_metadata_input_token_details1;
2694
3193
  tokenUsage.promptTokens += message.usage_metadata.input_tokens;
2695
3194
  tokenUsage.completionTokens += message.usage_metadata.output_tokens;
2696
3195
  tokenUsage.totalTokens += message.usage_metadata.total_tokens;
3196
+ var _message_usage_metadata_input_token_details_cache_read;
3197
+ cacheReadInputTokens += (_message_usage_metadata_input_token_details_cache_read = (_message_usage_metadata_input_token_details = message.usage_metadata.input_token_details) == null ? void 0 : _message_usage_metadata_input_token_details.cache_read) != null ? _message_usage_metadata_input_token_details_cache_read : 0;
3198
+ var _message_usage_metadata_input_token_details_cache_creation;
3199
+ cacheWriteInputTokens += (_message_usage_metadata_input_token_details_cache_creation = (_message_usage_metadata_input_token_details1 = message.usage_metadata.input_token_details) == null ? void 0 : _message_usage_metadata_input_token_details1.cache_creation) != null ? _message_usage_metadata_input_token_details_cache_creation : 0;
2697
3200
  }
2698
3201
  });
2699
3202
  });
3203
+ if (cacheReadInputTokens > 0) tokenUsage.cacheReadInputTokens = cacheReadInputTokens;
3204
+ if (cacheWriteInputTokens > 0) tokenUsage.cacheWriteInputTokens = cacheWriteInputTokens;
2700
3205
  return tokenUsage;
2701
3206
  }
2702
3207
  function resolveTokenUsage(output) {
@@ -2743,15 +3248,36 @@ function normalizeTokenUsage(candidate) {
2743
3248
  if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) {
2744
3249
  return null;
2745
3250
  }
2746
- return {
3251
+ var _candidate_cacheReadInputTokens;
3252
+ const cacheReadInputTokens = (_candidate_cacheReadInputTokens = candidate.cacheReadInputTokens) != null ? _candidate_cacheReadInputTokens : 0;
3253
+ var _candidate_cacheWriteInputTokens;
3254
+ const cacheWriteInputTokens = (_candidate_cacheWriteInputTokens = candidate.cacheWriteInputTokens) != null ? _candidate_cacheWriteInputTokens : 0;
3255
+ if (!isValidTokenCount(cacheReadInputTokens) || !isValidTokenCount(cacheWriteInputTokens)) {
3256
+ return null;
3257
+ }
3258
+ return _extends._extends({
2747
3259
  promptTokens,
2748
3260
  completionTokens,
2749
3261
  totalTokens
2750
- };
3262
+ }, cacheReadInputTokens > 0 ? {
3263
+ cacheReadInputTokens
3264
+ } : {}, cacheWriteInputTokens > 0 ? {
3265
+ cacheWriteInputTokens
3266
+ } : {});
2751
3267
  }
2752
3268
  function isValidTokenCount(value) {
2753
3269
  return value === undefined || Number.isFinite(value) && value >= 0;
2754
3270
  }
3271
+ function normalizeCacheTokenAccounting(tokenUsage, context) {
3272
+ if (context.inputTokensIncludeCache !== false) return tokenUsage;
3273
+ var _tokenUsage_cacheReadInputTokens, _tokenUsage_cacheWriteInputTokens;
3274
+ const cacheTokens = ((_tokenUsage_cacheReadInputTokens = tokenUsage.cacheReadInputTokens) != null ? _tokenUsage_cacheReadInputTokens : 0) + ((_tokenUsage_cacheWriteInputTokens = tokenUsage.cacheWriteInputTokens) != null ? _tokenUsage_cacheWriteInputTokens : 0);
3275
+ if (!cacheTokens) return tokenUsage;
3276
+ return _extends._extends({}, tokenUsage, {
3277
+ promptTokens: tokenUsage.promptTokens + cacheTokens,
3278
+ totalTokens: tokenUsage.totalTokens + cacheTokens
3279
+ });
3280
+ }
2755
3281
  /**
2756
3282
  * @deprecated use calcTokenUsage
2757
3283
  */ function sumTokenUsage(output) {
@@ -2776,6 +3302,19 @@ function isValidTokenCount(value) {
2776
3302
  let payload = job.data;
2777
3303
  if (payload.phase === 'succeeded' && payload.result !== undefined) return payload.result;
2778
3304
  if (payload.phase === 'failed') throw new Error(payload.errorCode || 'Provider generation task failed');
3305
+ if (!payload.modelAccess && options.provider.resolveModelAccess) {
3306
+ const modelAccess = await options.provider.resolveModelAccess({
3307
+ requestId: payload.requestId,
3308
+ model: payload.model,
3309
+ operation: payload.operation,
3310
+ modality: payload.modality,
3311
+ pricingDimensions: payload.pricingDimensions,
3312
+ startedAt: payload.startedAt
3313
+ });
3314
+ payload = await checkpoint(job, _extends._extends({}, payload, {
3315
+ modelAccess
3316
+ }));
3317
+ }
2779
3318
  if (!payload.pricingSnapshot) {
2780
3319
  const pricingSnapshot = options.provider.resolvePricingSnapshot ? await options.provider.resolvePricingSnapshot({
2781
3320
  model: payload.model,
@@ -2850,7 +3389,7 @@ async function reportTerminalUsage(job, payload, metrics, provider) {
2850
3389
  pricingSnapshot: payload.pricingSnapshot,
2851
3390
  metrics,
2852
3391
  recordedAt: new Date().toISOString()
2853
- });
3392
+ }, payload.modelAccess);
2854
3393
  return checkpoint(job, _extends._extends({}, payload, {
2855
3394
  usageReported: true
2856
3395
  }));
@@ -5228,6 +5767,7 @@ exports.BaseToolset = modelProvider.BaseToolset;
5228
5767
  exports.BuiltinToolset = modelProvider.BuiltinToolset;
5229
5768
  exports.DefaultAgentMiddlewareRuntimeCapabilityRegistry = modelProvider.DefaultRuntimeCapabilityRegistry;
5230
5769
  exports.DefaultRuntimeCapabilityRegistry = modelProvider.DefaultRuntimeCapabilityRegistry;
5770
+ exports.KnowledgeDocumentVisualAssetsRuntimeCapability = modelProvider.KnowledgeDocumentVisualAssetsRuntimeCapability;
5231
5771
  exports.KnowledgebaseDocumentsRuntimeCapability = modelProvider.KnowledgebaseDocumentsRuntimeCapability;
5232
5772
  exports.KnowledgebaseProvisioningRuntimeCapability = modelProvider.KnowledgebaseProvisioningRuntimeCapability;
5233
5773
  exports.KnowledgebaseRuntimeCapability = modelProvider.KnowledgebaseRuntimeCapability;
@@ -5402,6 +5942,7 @@ exports.als = als;
5402
5942
  exports.appendSandboxMessage = appendSandboxMessage;
5403
5943
  exports.buildSandboxTimeoutMessage = buildSandboxTimeoutMessage;
5404
5944
  exports.calcTokenUsage = calcTokenUsage;
5945
+ exports.calculateLLMUsagePrice = calculateLLMUsagePrice;
5405
5946
  exports.calculateModelPrice = calculateModelPrice;
5406
5947
  exports.calculateModelUsageCharge = calculateModelUsageCharge;
5407
5948
  exports.chunkText = chunkText;