@x12i/ai-tools 2.2.0 → 2.3.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/{AiModelsCatalogClient-DgBdVFk-.d.cts → AiModelsCatalogClient-CQf-zHc6.d.cts} +1 -1
- package/dist/{AiModelsCatalogClient-C9ZJHhv3.d.ts → AiModelsCatalogClient-Cohl3zfe.d.ts} +1 -1
- package/dist/aliases/index.d.cts +4 -3
- package/dist/aliases/index.d.ts +4 -3
- package/dist/catalog/index.cjs +5 -4
- package/dist/catalog/index.cjs.map +1 -1
- package/dist/catalog/index.d.cts +5 -4
- package/dist/catalog/index.d.ts +5 -4
- package/dist/catalog/index.js +4 -3
- package/dist/{chunk-FWPH5YE6.cjs → chunk-3JDAPUZM.cjs} +8 -6
- package/dist/chunk-3JDAPUZM.cjs.map +1 -0
- package/dist/chunk-6T7QT6YH.cjs +7 -0
- package/dist/chunk-6T7QT6YH.cjs.map +1 -0
- package/dist/{chunk-TFQUMP2O.js → chunk-A7JKTDSD.js} +5 -3
- package/dist/{chunk-TFQUMP2O.js.map → chunk-A7JKTDSD.js.map} +1 -1
- package/dist/{chunk-GHRUS5UF.cjs → chunk-AGLZXZCH.cjs} +23 -21
- package/dist/chunk-AGLZXZCH.cjs.map +1 -0
- package/dist/{chunk-QILRLRA4.cjs → chunk-EE3Z75GO.cjs} +5 -5
- package/dist/{chunk-QILRLRA4.cjs.map → chunk-EE3Z75GO.cjs.map} +1 -1
- package/dist/{chunk-M35MNKDY.js → chunk-FHJDIYPJ.js} +3 -3
- package/dist/{chunk-XD5RQKYL.cjs → chunk-H7W5LMP6.cjs} +25 -14
- package/dist/chunk-H7W5LMP6.cjs.map +1 -0
- package/dist/{chunk-XJQODPN6.js → chunk-LHJV2YLY.js} +13 -3
- package/dist/{chunk-XJQODPN6.js.map → chunk-LHJV2YLY.js.map} +1 -1
- package/dist/chunk-OPKL4YNL.js +7 -0
- package/dist/chunk-OPKL4YNL.js.map +1 -0
- package/dist/{chunk-MLMQ5LGW.js → chunk-U2LOUZP7.js} +2 -1
- package/dist/chunk-U2LOUZP7.js.map +1 -0
- package/dist/{chunk-WMB3YEQQ.js → chunk-VR4P5QB2.js} +5 -3
- package/dist/{chunk-WMB3YEQQ.js.map → chunk-VR4P5QB2.js.map} +1 -1
- package/dist/{chunk-UIDCBJXR.cjs → chunk-VVCG536Q.cjs} +7 -7
- package/dist/{chunk-UIDCBJXR.cjs.map → chunk-VVCG536Q.cjs.map} +1 -1
- package/dist/{chunk-PP75SWKY.js → chunk-WVJZCVI7.js} +2 -2
- package/dist/{chunk-33AAM7KQ.cjs → chunk-XKJFO6VG.cjs} +16 -6
- package/dist/chunk-XKJFO6VG.cjs.map +1 -0
- package/dist/{chunk-TLUM25FM.js → chunk-YERYMWKM.js} +21 -10
- package/dist/chunk-YERYMWKM.js.map +1 -0
- package/dist/{chunk-FYRPN3N2.cjs → chunk-YGOZDVK3.cjs} +2 -1
- package/dist/chunk-YGOZDVK3.cjs.map +1 -0
- package/dist/cli/index.cjs +16 -15
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +7 -6
- package/dist/cli/index.js.map +1 -1
- package/dist/cost/index.cjs +5 -4
- package/dist/cost/index.cjs.map +1 -1
- package/dist/cost/index.d.cts +6 -5
- package/dist/cost/index.d.ts +6 -5
- package/dist/cost/index.js +4 -3
- package/dist/index.cjs +12 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.js +11 -7
- package/dist/{modelCache-xzoTUue2.d.ts → modelCache-Bbw8Yc8Y.d.ts} +1 -1
- package/dist/{modelCache-sL3dBfRM.d.cts → modelCache-_mEwDBW7.d.cts} +1 -1
- package/dist/{modelNameResolver-2WroQlqt.d.ts → modelNameResolver-6k18Wvys.d.ts} +1 -1
- package/dist/{modelNameResolver-Bxlehrbp.d.cts → modelNameResolver-MoyOpdC3.d.cts} +1 -1
- package/dist/models/index.cjs +6 -5
- package/dist/models/index.cjs.map +1 -1
- package/dist/models/index.d.cts +5 -4
- package/dist/models/index.d.ts +5 -4
- package/dist/models/index.js +5 -4
- package/dist/profiles/index.cjs +6 -2
- package/dist/profiles/index.cjs.map +1 -1
- package/dist/profiles/index.d.cts +8 -3
- package/dist/profiles/index.d.ts +8 -3
- package/dist/profiles/index.js +5 -1
- package/dist/{resolveModelVendor-DQpJpk0w.d.ts → resolveModelVendor-Bb-TvXHF.d.ts} +3 -3
- package/dist/{resolveModelVendor-uphYBFMY.d.ts → resolveModelVendor-CF9l_SVN.d.ts} +1 -1
- package/dist/{resolveModelVendor-XvmXsVzo.d.cts → resolveModelVendor-CI64t5sk.d.cts} +3 -3
- package/dist/{resolveModelVendor-B0t5nq-v.d.cts → resolveModelVendor-Ck059GDf.d.cts} +1 -1
- package/dist/sync/index.d.cts +5 -4
- package/dist/sync/index.d.ts +5 -4
- package/dist/{types-BZYGjN2O.d.cts → types-CILRAzjr.d.cts} +4 -0
- package/dist/{types-BZYGjN2O.d.ts → types-CILRAzjr.d.ts} +4 -0
- package/package.json +2 -2
- package/dist/chunk-33AAM7KQ.cjs.map +0 -1
- package/dist/chunk-FWPH5YE6.cjs.map +0 -1
- package/dist/chunk-FYRPN3N2.cjs.map +0 -1
- package/dist/chunk-GHRUS5UF.cjs.map +0 -1
- package/dist/chunk-MLMQ5LGW.js.map +0 -1
- package/dist/chunk-TLUM25FM.js.map +0 -1
- package/dist/chunk-XD5RQKYL.cjs.map +0 -1
- /package/dist/{chunk-M35MNKDY.js.map → chunk-FHJDIYPJ.js.map} +0 -0
- /package/dist/{chunk-PP75SWKY.js.map → chunk-WVJZCVI7.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AiModelRecord, l as ModelResolverOptions, h as ModelResolutionInput, j as ModelResolutionResult } from './types-
|
|
1
|
+
import { a as AiModelRecord, l as ModelResolverOptions, h as ModelResolutionInput, j as ModelResolutionResult } from './types-CILRAzjr.cjs';
|
|
2
2
|
|
|
3
3
|
type LoadCatalogOptions = {
|
|
4
4
|
directCatalogUrl?: string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AiModelRecord, l as ModelResolverOptions, h as ModelResolutionInput, j as ModelResolutionResult } from './types-
|
|
1
|
+
import { a as AiModelRecord, l as ModelResolverOptions, h as ModelResolutionInput, j as ModelResolutionResult } from './types-CILRAzjr.js';
|
|
2
2
|
|
|
3
3
|
type LoadCatalogOptions = {
|
|
4
4
|
directCatalogUrl?: string;
|
package/dist/aliases/index.d.cts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { d as AliasRegistry, u as ResolvedModelRef, f as AliasValidationReport } from '../types-
|
|
2
|
-
export { b as AliasEntry, c as AliasFileSchema, e as AliasRegistryOptions } from '../types-
|
|
3
|
-
import { A as AiModelsCatalogClient } from '../AiModelsCatalogClient-
|
|
1
|
+
import { d as AliasRegistry, u as ResolvedModelRef, f as AliasValidationReport } from '../types-CILRAzjr.cjs';
|
|
2
|
+
export { b as AliasEntry, c as AliasFileSchema, e as AliasRegistryOptions } from '../types-CILRAzjr.cjs';
|
|
3
|
+
import { A as AiModelsCatalogClient } from '../AiModelsCatalogClient-CQf-zHc6.cjs';
|
|
4
|
+
import '@x12i/ai-profiles';
|
|
4
5
|
|
|
5
6
|
type AliasResolverOptions = {
|
|
6
7
|
registry: AliasRegistry;
|
package/dist/aliases/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { d as AliasRegistry, u as ResolvedModelRef, f as AliasValidationReport } from '../types-
|
|
2
|
-
export { b as AliasEntry, c as AliasFileSchema, e as AliasRegistryOptions } from '../types-
|
|
3
|
-
import { A as AiModelsCatalogClient } from '../AiModelsCatalogClient-
|
|
1
|
+
import { d as AliasRegistry, u as ResolvedModelRef, f as AliasValidationReport } from '../types-CILRAzjr.js';
|
|
2
|
+
export { b as AliasEntry, c as AliasFileSchema, e as AliasRegistryOptions } from '../types-CILRAzjr.js';
|
|
3
|
+
import { A as AiModelsCatalogClient } from '../AiModelsCatalogClient-Cohl3zfe.js';
|
|
4
|
+
import '@x12i/ai-profiles';
|
|
4
5
|
|
|
5
6
|
type AliasResolverOptions = {
|
|
6
7
|
registry: AliasRegistry;
|
package/dist/catalog/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkVVCG536Qcjs = require('../chunk-VVCG536Q.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
@@ -15,11 +15,12 @@ var _chunkUIDCBJXRcjs = require('../chunk-UIDCBJXR.cjs');
|
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
|
|
18
|
-
var
|
|
19
|
-
require('../chunk-
|
|
18
|
+
var _chunkXKJFO6VGcjs = require('../chunk-XKJFO6VG.cjs');
|
|
19
|
+
require('../chunk-H7W5LMP6.cjs');
|
|
20
20
|
require('../chunk-2KPWVOOT.cjs');
|
|
21
21
|
require('../chunk-OZE336BL.cjs');
|
|
22
22
|
require('../chunk-PADNCGZB.cjs');
|
|
23
|
+
require('../chunk-6T7QT6YH.cjs');
|
|
23
24
|
require('../chunk-GS7T56RP.cjs');
|
|
24
25
|
|
|
25
26
|
|
|
@@ -36,5 +37,5 @@ require('../chunk-GS7T56RP.cjs');
|
|
|
36
37
|
|
|
37
38
|
|
|
38
39
|
|
|
39
|
-
exports.AiModelsCatalogClient =
|
|
40
|
+
exports.AiModelsCatalogClient = _chunkXKJFO6VGcjs.AiModelsCatalogClient; exports.DEFAULT_CATALOG_CACHE_TTL_MS = _chunkXKJFO6VGcjs.DEFAULT_CATALOG_CACHE_TTL_MS; exports.DEFAULT_DIRECT_CATALOG_URL = _chunkXKJFO6VGcjs.DEFAULT_DIRECT_CATALOG_URL; exports.DEFAULT_OPENROUTER_CATALOG_URL = _chunkXKJFO6VGcjs.DEFAULT_OPENROUTER_CATALOG_URL; exports.canonicalCatalogModelId = _chunkXKJFO6VGcjs.canonicalCatalogModelId; exports.invalidateCatalogLoadCache = _chunkXKJFO6VGcjs.invalidateCatalogLoadCache; exports.loadCatalogSources = _chunkXKJFO6VGcjs.loadCatalogSources; exports.loadCatalogSourcesCached = _chunkXKJFO6VGcjs.loadCatalogSourcesCached; exports.modelsFromX12iCatalogFile = _chunkXKJFO6VGcjs.modelsFromX12iCatalogFile; exports.normalizeX12iCatalogModel = _chunkXKJFO6VGcjs.normalizeX12iCatalogModel; exports.readBundledCatalogFiles = _chunkXKJFO6VGcjs.readBundledCatalogFiles; exports.refreshAiModelsCatalog = _chunkVVCG536Qcjs.refreshAiModelsCatalog; exports.resolveCatalogCacheTtlMs = _chunkXKJFO6VGcjs.resolveCatalogCacheTtlMs; exports.verifyAiModelsCatalog = _chunkVVCG536Qcjs.verifyAiModelsCatalog;
|
|
40
41
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/catalog/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,ilCAAC","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/catalog/index.cjs"}
|
|
1
|
+
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/catalog/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,ilCAAC","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/catalog/index.cjs"}
|
package/dist/catalog/index.d.cts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export { A as AiModelsCatalogClient, a as AiModelsCatalogClientOptions, L as LoadCatalogOptions, b as LoadedCatalogs, l as loadCatalogSources, r as readBundledCatalogFiles } from '../AiModelsCatalogClient-
|
|
2
|
-
import { a as AiModelRecord } from '../types-
|
|
3
|
-
import { X as X12iCatalogModelEntry, b as CatalogSourceKind } from '../modelCache-
|
|
4
|
-
export { C as CatalogRefreshOptions, a as CatalogRefreshResult, c as CatalogVerifyOptions, d as CatalogVerifyReport, D as DEFAULT_CATALOG_CACHE_TTL_MS, e as DEFAULT_DIRECT_CATALOG_URL, f as DEFAULT_OPENROUTER_CATALOG_URL, L as LoadCatalogCachedOptions, g as X12iModelsCatalogFile, i as invalidateCatalogLoadCache, l as loadCatalogSourcesCached, r as refreshAiModelsCatalog, h as resolveCatalogCacheTtlMs, v as verifyAiModelsCatalog } from '../modelCache-
|
|
1
|
+
export { A as AiModelsCatalogClient, a as AiModelsCatalogClientOptions, L as LoadCatalogOptions, b as LoadedCatalogs, l as loadCatalogSources, r as readBundledCatalogFiles } from '../AiModelsCatalogClient-CQf-zHc6.cjs';
|
|
2
|
+
import { a as AiModelRecord } from '../types-CILRAzjr.cjs';
|
|
3
|
+
import { X as X12iCatalogModelEntry, b as CatalogSourceKind } from '../modelCache-_mEwDBW7.cjs';
|
|
4
|
+
export { C as CatalogRefreshOptions, a as CatalogRefreshResult, c as CatalogVerifyOptions, d as CatalogVerifyReport, D as DEFAULT_CATALOG_CACHE_TTL_MS, e as DEFAULT_DIRECT_CATALOG_URL, f as DEFAULT_OPENROUTER_CATALOG_URL, L as LoadCatalogCachedOptions, g as X12iModelsCatalogFile, i as invalidateCatalogLoadCache, l as loadCatalogSourcesCached, r as refreshAiModelsCatalog, h as resolveCatalogCacheTtlMs, v as verifyAiModelsCatalog } from '../modelCache-_mEwDBW7.cjs';
|
|
5
|
+
import '@x12i/ai-profiles';
|
|
5
6
|
|
|
6
7
|
declare function canonicalCatalogModelId(provider: string, modelId: string): string;
|
|
7
8
|
declare function normalizeX12iCatalogModel(entry: X12iCatalogModelEntry, kind: CatalogSourceKind, verifiedAt: string): AiModelRecord | null;
|
package/dist/catalog/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export { A as AiModelsCatalogClient, a as AiModelsCatalogClientOptions, L as LoadCatalogOptions, b as LoadedCatalogs, l as loadCatalogSources, r as readBundledCatalogFiles } from '../AiModelsCatalogClient-
|
|
2
|
-
import { a as AiModelRecord } from '../types-
|
|
3
|
-
import { X as X12iCatalogModelEntry, b as CatalogSourceKind } from '../modelCache-
|
|
4
|
-
export { C as CatalogRefreshOptions, a as CatalogRefreshResult, c as CatalogVerifyOptions, d as CatalogVerifyReport, D as DEFAULT_CATALOG_CACHE_TTL_MS, e as DEFAULT_DIRECT_CATALOG_URL, f as DEFAULT_OPENROUTER_CATALOG_URL, L as LoadCatalogCachedOptions, g as X12iModelsCatalogFile, i as invalidateCatalogLoadCache, l as loadCatalogSourcesCached, r as refreshAiModelsCatalog, h as resolveCatalogCacheTtlMs, v as verifyAiModelsCatalog } from '../modelCache-
|
|
1
|
+
export { A as AiModelsCatalogClient, a as AiModelsCatalogClientOptions, L as LoadCatalogOptions, b as LoadedCatalogs, l as loadCatalogSources, r as readBundledCatalogFiles } from '../AiModelsCatalogClient-Cohl3zfe.js';
|
|
2
|
+
import { a as AiModelRecord } from '../types-CILRAzjr.js';
|
|
3
|
+
import { X as X12iCatalogModelEntry, b as CatalogSourceKind } from '../modelCache-Bbw8Yc8Y.js';
|
|
4
|
+
export { C as CatalogRefreshOptions, a as CatalogRefreshResult, c as CatalogVerifyOptions, d as CatalogVerifyReport, D as DEFAULT_CATALOG_CACHE_TTL_MS, e as DEFAULT_DIRECT_CATALOG_URL, f as DEFAULT_OPENROUTER_CATALOG_URL, L as LoadCatalogCachedOptions, g as X12iModelsCatalogFile, i as invalidateCatalogLoadCache, l as loadCatalogSourcesCached, r as refreshAiModelsCatalog, h as resolveCatalogCacheTtlMs, v as verifyAiModelsCatalog } from '../modelCache-Bbw8Yc8Y.js';
|
|
5
|
+
import '@x12i/ai-profiles';
|
|
5
6
|
|
|
6
7
|
declare function canonicalCatalogModelId(provider: string, modelId: string): string;
|
|
7
8
|
declare function normalizeX12iCatalogModel(entry: X12iCatalogModelEntry, kind: CatalogSourceKind, verifiedAt: string): AiModelRecord | null;
|
package/dist/catalog/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
refreshAiModelsCatalog,
|
|
3
3
|
verifyAiModelsCatalog
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-WVJZCVI7.js";
|
|
5
5
|
import {
|
|
6
6
|
AiModelsCatalogClient,
|
|
7
7
|
DEFAULT_CATALOG_CACHE_TTL_MS,
|
|
@@ -15,11 +15,12 @@ import {
|
|
|
15
15
|
normalizeX12iCatalogModel,
|
|
16
16
|
readBundledCatalogFiles,
|
|
17
17
|
resolveCatalogCacheTtlMs
|
|
18
|
-
} from "../chunk-
|
|
19
|
-
import "../chunk-
|
|
18
|
+
} from "../chunk-LHJV2YLY.js";
|
|
19
|
+
import "../chunk-YERYMWKM.js";
|
|
20
20
|
import "../chunk-SQ6NOF4Z.js";
|
|
21
21
|
import "../chunk-OB44D7RG.js";
|
|
22
22
|
import "../chunk-2PTCWPHV.js";
|
|
23
|
+
import "../chunk-OPKL4YNL.js";
|
|
23
24
|
export {
|
|
24
25
|
AiModelsCatalogClient,
|
|
25
26
|
DEFAULT_CATALOG_CACHE_TTL_MS,
|
|
@@ -8,19 +8,21 @@ var _chunkEDZOFPLVcjs = require('./chunk-EDZOFPLV.cjs');
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
var
|
|
11
|
+
var _chunkH7W5LMP6cjs = require('./chunk-H7W5LMP6.cjs');
|
|
12
12
|
|
|
13
13
|
// src/cost/resolveModelVendor.ts
|
|
14
14
|
async function resolveModelVendor(model, catalog, options) {
|
|
15
15
|
const exact = _chunkEDZOFPLVcjs.modelVendorRefFromIdentity.call(void 0, model, options);
|
|
16
16
|
if (exact) return exact;
|
|
17
|
-
const attempts =
|
|
18
|
-
const result = await
|
|
17
|
+
const attempts = _chunkH7W5LMP6cjs.buildCatalogResolveAttempts.call(void 0, model);
|
|
18
|
+
const result = await _chunkH7W5LMP6cjs.resolveFromCatalogAttempts.call(void 0, catalog, attempts, options);
|
|
19
19
|
if (_optionalChain([result, 'optionalAccess', _ => _.found])) {
|
|
20
20
|
const ref = _chunkEDZOFPLVcjs.resolveModelVendorFromResolution.call(void 0, result, model, options);
|
|
21
21
|
if (ref) return ref;
|
|
22
22
|
}
|
|
23
|
-
const profileMatch = await
|
|
23
|
+
const profileMatch = await _chunkH7W5LMP6cjs.matchModelInAiProfiles.call(void 0, model, void 0, {
|
|
24
|
+
catalogLane: _optionalChain([options, 'optionalAccess', _2 => _2.catalogLane])
|
|
25
|
+
});
|
|
24
26
|
if (profileMatch) {
|
|
25
27
|
return _chunkEDZOFPLVcjs.modelVendorRefFromVendorAndSlug.call(void 0,
|
|
26
28
|
profileMatch.provider,
|
|
@@ -28,7 +30,7 @@ async function resolveModelVendor(model, catalog, options) {
|
|
|
28
30
|
options
|
|
29
31
|
);
|
|
30
32
|
}
|
|
31
|
-
if (!_optionalChain([result, 'optionalAccess',
|
|
33
|
+
if (!_optionalChain([result, 'optionalAccess', _3 => _3.found]) && _optionalChain([result, 'optionalAccess', _4 => _4.bestRejectedCandidate])) {
|
|
32
34
|
const ref = _chunkEDZOFPLVcjs.resolveModelVendorFromResolution.call(void 0, result, model, options);
|
|
33
35
|
if (ref) return ref;
|
|
34
36
|
}
|
|
@@ -38,4 +40,4 @@ async function resolveModelVendor(model, catalog, options) {
|
|
|
38
40
|
|
|
39
41
|
|
|
40
42
|
exports.resolveModelVendor = resolveModelVendor;
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
43
|
+
//# sourceMappingURL=chunk-3JDAPUZM.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-3JDAPUZM.cjs","../src/cost/resolveModelVendor.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACUA,MAAA,SAAsB,kBAAA,CACpB,KAAA,EACA,OAAA,EACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,EAAQ,0DAAA,KAA2B,EAAO,OAAO,CAAA;AACvD,EAAA,GAAA,CAAI,KAAA,EAAO,OAAO,KAAA;AAElB,EAAA,MAAM,SAAA,EAAW,2DAAA,KAAiC,CAAA;AAClD,EAAA,MAAM,OAAA,EAAS,MAAM,0DAAA,OAA2B,EAAS,QAAA,EAAU,OAAO,CAAA;AAE1E,EAAA,GAAA,iBAAI,MAAA,2BAAQ,OAAA,EAAO;AACjB,IAAA,MAAM,IAAA,EAAM,gEAAA,MAAiC,EAAQ,KAAA,EAAO,OAAO,CAAA;AACnE,IAAA,GAAA,CAAI,GAAA,EAAK,OAAO,GAAA;AAAA,EAClB;AAEA,EAAA,MAAM,aAAA,EAAe,MAAM,sDAAA,KAAuB,EAAO,KAAA,CAAA,EAAW;AAAA,IAClE,WAAA,kBAAa,OAAA,6BAAS;AAAA,EACxB,CAAC,CAAA;AACD,EAAA,GAAA,CAAI,YAAA,EAAc;AAChB,IAAA,OAAO,+DAAA;AAAA,MACL,YAAA,CAAa,QAAA;AAAA,MACb,YAAA,CAAa,OAAA;AAAA,MACb;AAAA,IACF,CAAA;AAAA,EACF;AAEA,EAAA,GAAA,CAAI,iBAAC,MAAA,6BAAQ,QAAA,mBAAS,MAAA,6BAAQ,uBAAA,EAAuB;AACnD,IAAA,MAAM,IAAA,EAAM,gEAAA,MAAiC,EAAQ,KAAA,EAAO,OAAO,CAAA;AACnE,IAAA,GAAA,CAAI,GAAA,EAAK,OAAO,GAAA;AAAA,EAClB;AAEA,EAAA,OAAO,4DAAA,KAA6B,EAAO,OAAO,CAAA;AACpD;ADjBA;AACA;AACE;AACF,gDAAC","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-3JDAPUZM.cjs","sourcesContent":[null,"import type { AiModelsCatalogClient } from \"../catalog/AiModelsCatalogClient.js\";\nimport {\n modelVendorRefFromIdentity,\n modelVendorRefFromVendorAndSlug,\n resolveModelVendorFromResolution,\n resolveModelVendorLastResort,\n type ModelVendorRef,\n type ResolveModelVendorOptions,\n} from \"../sync/modelNameResolver/resolveModelVendor.js\";\nimport { matchModelInAiProfiles } from \"./aiProfilesMatch.js\";\nimport { buildCatalogResolveAttempts, resolveFromCatalogAttempts } from \"./costModelResolution.js\";\n\nexport type { ModelVendorRef, ResolveModelVendorOptions };\nexport {\n resolveModelVendorFromResolution,\n resolveModelVendorSync,\n resolveModelVendorLastResort,\n modelVendorRefFromIdentity,\n modelVendorRefFromVendorAndSlug,\n} from \"../sync/modelNameResolver/resolveModelVendor.js\";\n\n/** Best-effort vendor lookup from a model name alone (catalog + ai-profiles). */\nexport async function resolveModelVendor(\n model: string,\n catalog: AiModelsCatalogClient,\n options?: ResolveModelVendorOptions,\n): Promise<ModelVendorRef | null> {\n const exact = modelVendorRefFromIdentity(model, options);\n if (exact) return exact;\n\n const attempts = buildCatalogResolveAttempts(model);\n const result = await resolveFromCatalogAttempts(catalog, attempts, options);\n\n if (result?.found) {\n const ref = resolveModelVendorFromResolution(result, model, options);\n if (ref) return ref;\n }\n\n const profileMatch = await matchModelInAiProfiles(model, undefined, {\n catalogLane: options?.catalogLane,\n });\n if (profileMatch) {\n return modelVendorRefFromVendorAndSlug(\n profileMatch.provider,\n profileMatch.modelId,\n options,\n );\n }\n\n if (!result?.found && result?.bestRejectedCandidate) {\n const ref = resolveModelVendorFromResolution(result, model, options);\n if (ref) return ref;\n }\n\n return resolveModelVendorLastResort(model, options);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-6T7QT6YH.cjs","../src/profiles/catalogLane.ts"],"names":[],"mappings":"AAAA;ACKO,IAAM,kBAAA,EAAwC,MAAA;ADHrD;AACA;AACE;AACF,8CAAC","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-6T7QT6YH.cjs","sourcesContent":[null,"import type { ProfileCatalogLane } from \"@x12i/ai-profiles\";\n\nexport type { ProfileCatalogLane };\n\n/** Default OpenRouter lane for token-priced LLM usage in this package. */\nexport const TEXT_CATALOG_LANE: ProfileCatalogLane = \"text\";\n"]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
matchModelInAiProfiles,
|
|
6
6
|
resolveFromCatalogAttempts,
|
|
7
7
|
resolveRoutedViaOpenRouter
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-YERYMWKM.js";
|
|
9
9
|
import {
|
|
10
10
|
normalizeString,
|
|
11
11
|
stripModelVersionSuffix
|
|
@@ -509,7 +509,9 @@ var CostCalculator = class {
|
|
|
509
509
|
const warnings = [];
|
|
510
510
|
if (!resolved?.found || !resolved.record) {
|
|
511
511
|
if (!isLocalProvider(input.provider)) {
|
|
512
|
-
profileMatch = await matchModelInAiProfiles(modelInput, input.provider
|
|
512
|
+
profileMatch = await matchModelInAiProfiles(modelInput, input.provider, {
|
|
513
|
+
catalogLane: this.resolverOptions?.catalogLane
|
|
514
|
+
});
|
|
513
515
|
}
|
|
514
516
|
if (profileMatch) {
|
|
515
517
|
resolved = await resolveFromCatalogAttempts(
|
|
@@ -702,4 +704,4 @@ export {
|
|
|
702
704
|
resolveUsageModel,
|
|
703
705
|
CostCalculator
|
|
704
706
|
};
|
|
705
|
-
//# sourceMappingURL=chunk-
|
|
707
|
+
//# sourceMappingURL=chunk-A7JKTDSD.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cost/constants.ts","../src/cost/enrichCostResult.ts","../src/cost/extractUsageInput.ts","../src/cost/resolveUsageModel.ts","../src/cost/profilePricing.ts","../src/cost/CostCalculator.ts"],"sourcesContent":["/** Default OpenRouter platform surcharge when catalog markup fields are absent (5%). */\nexport const DEFAULT_OPENROUTER_MARKUP_RATE = 0.05;\n\n/** ai-profiles tiered pricing threshold (tokens). */\nexport const PROFILE_TIERED_CONTEXT_THRESHOLD = 200_000;\n","import type { ExtractUsageInputResult } from \"./extractUsageInput.js\";\nimport type { AiCostExtraction, AiCostResult, AiUsageInput } from \"./types.js\";\n\nexport function toCostExtraction(\n provenance: ExtractUsageInputResult[\"provenance\"],\n): AiCostExtraction {\n return {\n model: { field: provenance.model.field, path: provenance.model.path },\n tokens: {\n source: provenance.tokens.source,\n path: provenance.tokens.path,\n estimated: provenance.tokens.estimated,\n },\n ...(provenance.modelUsed\n ? {\n modelUsed: {\n field: provenance.modelUsed.field,\n path: provenance.modelUsed.path,\n },\n }\n : {}),\n ...(provenance.provider\n ? {\n provider: {\n field: provenance.provider.field,\n path: provenance.provider.path,\n },\n }\n : {}),\n };\n}\n\n/** Attach usage, provider, and model fields callers expect on every cost response. */\nexport function enrichCostResult(\n result: Omit<\n AiCostResult,\n \"usage\" | \"provider\" | \"usedModel\" | \"model\" | \"extraction\"\n >,\n input: AiUsageInput,\n extraction?: AiCostExtraction,\n): AiCostResult {\n /** Original model id from the caller — never replaced by catalog resolution. */\n const receivedModelId = input.usedModel ?? input.modelUsed ?? input.model;\n\n return {\n ...result,\n provider: input.provider,\n usage: { ...input.tokens },\n ...(receivedModelId ? { usedModel: receivedModelId } : {}),\n ...(input.model && input.model !== receivedModelId ? { model: input.model } : {}),\n ...(extraction ? { extraction } : {}),\n };\n}\n","import type { AiUsageInput } from \"./types.js\";\n\n/** Model id field priority (higher wins). Runtime ids beat request/config aliases. */\nexport const MODEL_FIELD_PRIORITY: readonly { key: string; score: number }[] = [\n { key: \"usedModel\", score: 1000 },\n { key: \"modelUsed\", score: 990 },\n { key: \"resolvedModel\", score: 980 },\n { key: \"model\", score: 500 },\n { key: \"xynthesisModel\", score: 120 },\n { key: \"skillModel\", score: 110 },\n] as const;\n\n/** Path segments that boost or penalize a model candidate. */\nconst MODEL_PATH_BONUS: readonly { pattern: RegExp; bonus: number }[] = [\n { pattern: /(^|\\.)response(\\.|$)/i, bonus: 40 },\n { pattern: /(^|\\.)outer\\.input(\\.|$)/i, bonus: 35 },\n { pattern: /(^|\\.)config(?!\\.rawConfig)(\\.|$)/i, bonus: 30 },\n { pattern: /(^|\\.)outer\\.input\\.config(\\.|$)/i, bonus: 28 },\n { pattern: /(^|\\.)usage(\\.|$)/i, bonus: 15 },\n { pattern: /(^|\\.)rawConfig(\\.|$)/i, bonus: -40 },\n { pattern: /workingMemory/i, bonus: -50 },\n { pattern: /requestExample/i, bonus: -80 },\n { pattern: /graphsStudio/i, bonus: -80 },\n];\n\nconst PROVIDER_FIELD_PRIORITY: readonly { key: string; score: number }[] = [\n { key: \"provider\", score: 500 },\n { key: \"providerId\", score: 480 },\n] as const;\n\nconst PROVIDER_PATH_BONUS: readonly { pattern: RegExp; bonus: number }[] = [\n { pattern: /(^|\\.)config(?!\\.rawConfig)(\\.|$)/i, bonus: 30 },\n { pattern: /(^|\\.)outer\\.input(\\.|$)/i, bonus: 20 },\n { pattern: /(^|\\.)rawConfig(\\.|$)/i, bonus: -20 },\n];\n\nconst PROMPT_TOKEN_KEYS = new Set([\n \"prompt\",\n \"prompt_tokens\",\n \"promptTokens\",\n \"input_tokens\",\n \"inputTokens\",\n \"estimatedInputTokens\",\n \"input\",\n]);\n\nconst COMPLETION_TOKEN_KEYS = new Set([\n \"completion\",\n \"completion_tokens\",\n \"completionTokens\",\n \"output_tokens\",\n \"outputTokens\",\n \"estimatedOutputTokens\",\n \"output\",\n]);\n\nconst OPTIONAL_TOKEN_KEYS: Record<string, keyof AiUsageInput[\"tokens\"]> = {\n total: \"total\",\n total_tokens: \"total\",\n totalTokens: \"total\",\n cached: \"cached\",\n cached_tokens: \"cached\",\n cache_read_tokens: \"cached\",\n cacheReadTokens: \"cached\",\n cacheWrite: \"cacheWrite\",\n cache_write_tokens: \"cacheWrite\",\n cacheWriteTokens: \"cacheWrite\",\n reasoning: \"reasoning\",\n reasoning_tokens: \"reasoning\",\n reasoningTokens: \"reasoning\",\n audio: \"audio\",\n audio_tokens: \"audio\",\n image: \"image\",\n image_tokens: \"image\",\n};\n\nexport type FieldProvenance = {\n field: string;\n path: string;\n score: number;\n};\n\nexport type TokenExtractionProvenance = {\n source: \"usage\" | \"tokens\" | \"diagnostics\" | \"estimated\";\n path: string;\n estimated?: boolean;\n};\n\nexport type ExtractUsageInputResult = {\n input: AiUsageInput;\n provenance: {\n model: FieldProvenance;\n modelUsed?: FieldProvenance;\n provider?: FieldProvenance;\n tokens: TokenExtractionProvenance;\n };\n};\n\nexport type ExtractUsageInputOptions = {\n /** Default when no provider field is found (default: `openrouter`). */\n defaultProvider?: string;\n};\n\ntype ModelCandidate = FieldProvenance & { value: string };\ntype ProviderCandidate = FieldProvenance & { value: string };\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction modelKeyScore(key: string): number {\n return MODEL_FIELD_PRIORITY.find((e) => e.key === key)?.score ?? 0;\n}\n\nfunction providerKeyScore(key: string): number {\n return PROVIDER_FIELD_PRIORITY.find((e) => e.key === key)?.score ?? 0;\n}\n\nfunction pathBonus(path: string, rules: readonly { pattern: RegExp; bonus: number }[]): number {\n let bonus = 0;\n for (const { pattern, bonus: b } of rules) {\n if (pattern.test(path)) bonus += b;\n }\n return bonus;\n}\n\nfunction normalizeModelValue(v: unknown): string | undefined {\n if (typeof v !== \"string\") return undefined;\n const t = v.trim();\n return t.length > 0 ? t : undefined;\n}\n\nfunction normalizeProviderValue(v: unknown): string | undefined {\n if (typeof v !== \"string\") return undefined;\n const t = v.trim().toLowerCase();\n if (!t || t === \"null\") return undefined;\n return t;\n}\n\nfunction collectModelCandidates(\n node: unknown,\n path: string,\n out: ModelCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n const base = modelKeyScore(key);\n if (base > 0) {\n const model = normalizeModelValue(value);\n if (model) {\n out.push({\n field: key,\n path: childPath,\n value: model,\n score: base + pathBonus(childPath, MODEL_PATH_BONUS),\n });\n }\n }\n collectModelCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectModelCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction collectProviderCandidates(\n node: unknown,\n path: string,\n out: ProviderCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n const base = providerKeyScore(key);\n if (base > 0) {\n const provider = normalizeProviderValue(value);\n if (provider) {\n out.push({\n field: key,\n path: childPath,\n value: provider,\n score: base + pathBonus(childPath, PROVIDER_PATH_BONUS),\n });\n }\n }\n collectProviderCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectProviderCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction readNumber(obj: Record<string, unknown>, keys: Set<string>): number | undefined {\n for (const [k, v] of Object.entries(obj)) {\n if (!keys.has(k)) continue;\n if (typeof v === \"number\" && Number.isFinite(v) && v >= 0) return v;\n }\n return undefined;\n}\n\nfunction readOptionalNumbers(\n obj: Record<string, unknown>,\n): Partial<AiUsageInput[\"tokens\"]> {\n const extra: Partial<AiUsageInput[\"tokens\"]> = {};\n for (const [k, v] of Object.entries(obj)) {\n const target = OPTIONAL_TOKEN_KEYS[k];\n if (!target || typeof v !== \"number\" || !Number.isFinite(v) || v < 0) continue;\n extra[target] = v;\n }\n return extra;\n}\n\nfunction looksLikeUsageObject(obj: Record<string, unknown>): boolean {\n const hasPrompt = readNumber(obj, PROMPT_TOKEN_KEYS) !== undefined;\n const hasCompletion = readNumber(obj, COMPLETION_TOKEN_KEYS) !== undefined;\n return hasPrompt && hasCompletion;\n}\n\nfunction looksLikeDiagnosticsObject(obj: Record<string, unknown>): boolean {\n return (\n typeof obj.estimatedInputTokens === \"number\" &&\n typeof obj.estimatedOutputTokens === \"number\"\n );\n}\n\ntype TokenCandidate = {\n tokens: AiUsageInput[\"tokens\"];\n provenance: TokenExtractionProvenance;\n score: number;\n};\n\nfunction tokensFromObject(\n obj: Record<string, unknown>,\n source: TokenExtractionProvenance[\"source\"],\n path: string,\n estimated: boolean,\n score: number,\n): TokenCandidate | null {\n const prompt = readNumber(obj, PROMPT_TOKEN_KEYS);\n const completion = readNumber(obj, COMPLETION_TOKEN_KEYS);\n if (prompt === undefined || completion === undefined) return null;\n\n const extra = readOptionalNumbers(obj);\n const total =\n typeof extra.total === \"number\" ? extra.total : prompt + completion;\n\n return {\n tokens: {\n prompt,\n completion,\n total,\n ...extra,\n },\n provenance: { source, path, estimated },\n score,\n };\n}\n\nfunction collectTokenCandidates(\n node: unknown,\n path: string,\n out: TokenCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n if (path.endsWith(\"diagnostics\") || looksLikeDiagnosticsObject(node)) {\n const cand = tokensFromObject(node, \"diagnostics\", path, true, 200);\n if (cand) out.push(cand);\n } else if (path.endsWith(\"usage\") || path.endsWith(\"tokens\") || looksLikeUsageObject(node)) {\n const source = path.endsWith(\"tokens\") ? \"tokens\" : \"usage\";\n const estimated = false;\n const score = path.endsWith(\"usage\") ? 500 : 450;\n const cand = tokensFromObject(node, source, path, estimated, score);\n if (cand) out.push(cand);\n }\n\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n if (key === \"usage\" || key === \"tokens\" || key === \"diagnostics\") {\n if (isPlainObject(value)) {\n collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n } else {\n collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectTokenCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction pickBestModel(candidates: ModelCandidate[]): ModelCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction pickBestProvider(candidates: ProviderCandidate[]): ProviderCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction pickBestTokens(candidates: TokenCandidate[]): TokenCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction inferProviderFromModel(model: string, fallback: string): string {\n const slash = model.indexOf(\"/\");\n if (slash > 0) {\n const prefix = model.slice(0, slash).toLowerCase();\n if (prefix !== \"openrouter\") return prefix;\n }\n return fallback;\n}\n\n/**\n * Extract {@link AiUsageInput} from activity logs, gateway records, MongoDB exports,\n * or any nested JSON shape (e.g. `outer.input`, `config`, `metadata.diagnostics`).\n */\nexport function extractUsageInput(\n record: unknown,\n options: ExtractUsageInputOptions = {},\n): ExtractUsageInputResult {\n const defaultProvider = options.defaultProvider ?? \"openrouter\";\n const maxDepth = 24;\n\n const modelCandidates: ModelCandidate[] = [];\n const providerCandidates: ProviderCandidate[] = [];\n const tokenCandidates: TokenCandidate[] = [];\n\n collectModelCandidates(record, \"\", modelCandidates, 0, maxDepth);\n collectProviderCandidates(record, \"\", providerCandidates, 0, maxDepth);\n collectTokenCandidates(record, \"\", tokenCandidates, 0, maxDepth);\n\n const bestModel = pickBestModel(modelCandidates);\n if (!bestModel) {\n throw new Error(\n \"[ai-tools] Could not extract a model from the record (looked for usedModel, modelUsed, model, …).\",\n );\n }\n\n const runtimeFields = new Set([\"usedModel\", \"modelUsed\", \"resolvedModel\"]);\n const isRuntimeModel = runtimeFields.has(bestModel.field);\n const requestModel = modelCandidates.find(\n (c) => c.field === \"model\" && c.path !== bestModel.path,\n );\n\n const bestProvider = pickBestProvider(providerCandidates);\n const provider =\n bestProvider?.value ??\n inferProviderFromModel(bestModel.value, defaultProvider);\n\n const bestTokens = pickBestTokens(tokenCandidates);\n if (!bestTokens) {\n throw new Error(\n \"[ai-tools] Could not extract token usage from the record (usage, tokens, or metadata.diagnostics).\",\n );\n }\n\n const input: AiUsageInput = {\n tokens: bestTokens.tokens,\n provider,\n ...(isRuntimeModel\n ? { modelUsed: bestModel.value, model: requestModel?.value }\n : { model: bestModel.value }),\n };\n\n const provenance: ExtractUsageInputResult[\"provenance\"] = {\n model: {\n field: bestModel.field,\n path: bestModel.path,\n score: bestModel.score,\n },\n tokens: bestTokens.provenance,\n };\n\n if (bestProvider) {\n provenance.provider = {\n field: bestProvider.field,\n path: bestProvider.path,\n score: bestProvider.score,\n };\n }\n\n if (isRuntimeModel && requestModel) {\n provenance.modelUsed = {\n field: bestModel.field,\n path: bestModel.path,\n score: bestModel.score,\n };\n } else if (input.modelUsed) {\n provenance.modelUsed = provenance.model;\n }\n\n return { input, provenance };\n}\n","import type { AiUsageInput } from \"./types.js\";\n\n/** Prefer runtime id (`usedModel` / `modelUsed`); fall back to `model`. */\nexport function resolveUsageModel(input: AiUsageInput): string {\n const value = input.usedModel ?? input.modelUsed ?? input.model;\n if (!value?.trim()) {\n throw new Error(\n \"[ai-tools] Cost calculation requires `usedModel`, `modelUsed`, or `model` on usage input.\",\n );\n }\n return value.trim();\n}\n","import type { AIModelPricing } from \"@x12i/ai-profiles\";\nimport {\n DEFAULT_OPENROUTER_MARKUP_RATE,\n PROFILE_TIERED_CONTEXT_THRESHOLD,\n} from \"./constants.js\";\nimport type { AiModelPricing, AiUsageInput } from \"./types.js\";\n\nconst TOKENS_PER_UNIT = 1_000_000;\n\nfunction usdPerToken(perMillion?: number): number {\n return (perMillion ?? 0) / TOKENS_PER_UNIT;\n}\n\nfunction pickInputRatePerMillion(\n pricing: AIModelPricing,\n promptTokens: number,\n): number | undefined {\n if (\n pricing.inputBelow200k !== undefined &&\n pricing.inputAbove200k !== undefined\n ) {\n return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD\n ? pricing.inputBelow200k\n : pricing.inputAbove200k;\n }\n return pricing.input ?? pricing.inputBelow200k ?? pricing.inputAbove200k;\n}\n\nfunction pickOutputRatePerMillion(\n pricing: AIModelPricing,\n promptTokens: number,\n): number | undefined {\n if (\n pricing.outputBelow200k !== undefined &&\n pricing.outputAbove200k !== undefined\n ) {\n return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD\n ? pricing.outputBelow200k\n : pricing.outputAbove200k;\n }\n return pricing.output ?? pricing.outputBelow200k ?? pricing.outputAbove200k;\n}\n\nexport type AiProfilesPricingOptions = {\n promptTokens?: number;\n routedViaOpenRouter?: boolean;\n};\n\nexport function aiProfilesPricingToCatalogPricing(\n pricing: AIModelPricing,\n pricedAt: string,\n options: AiProfilesPricingOptions = {},\n): AiModelPricing {\n const promptTokens = options.promptTokens ?? 0;\n const promptUsdPerToken = usdPerToken(pickInputRatePerMillion(pricing, promptTokens));\n const completionUsdPerToken = usdPerToken(\n pickOutputRatePerMillion(pricing, promptTokens),\n );\n\n const snapshot: AiModelPricing = {\n promptUsdPerToken,\n completionUsdPerToken,\n cacheReadUsdPerToken: usdPerToken(pricing.cachedInput ?? pricing.cacheHit),\n cacheWriteUsdPerToken: usdPerToken(pricing.cacheWrite5m ?? pricing.cacheWrite1h),\n imageUsdPerUnit: 0,\n requestUsdPerRequest: 0,\n pricedAt,\n source: \"manual\",\n };\n\n if (options.routedViaOpenRouter) {\n snapshot.openRouterMarkupUsdPerInputToken =\n promptUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;\n snapshot.openRouterMarkupUsdPerOutputToken =\n completionUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;\n }\n\n return snapshot;\n}\n\nexport function computeCostFromPricing(\n input: AiUsageInput,\n pricing: AiModelPricing,\n routedViaOpenRouter: boolean,\n includeBreakdown: boolean,\n): { cost: number; breakdown?: import(\"./types.js\").AiCostResult[\"breakdown\"] } {\n const { tokens } = input;\n\n let promptCost = tokens.prompt * pricing.promptUsdPerToken;\n let completionCost = tokens.completion * pricing.completionUsdPerToken;\n\n const cachingCost =\n (tokens.cacheWrite ?? 0) * (pricing.cacheWriteUsdPerToken ?? 0) +\n (tokens.cached ?? 0) * (pricing.cacheReadUsdPerToken ?? 0);\n\n const reasoningCost =\n (tokens.reasoning ?? 0) *\n (pricing.reasoningUsdPerToken ?? pricing.promptUsdPerToken);\n\n const audioCost = (tokens.audio ?? 0) * pricing.promptUsdPerToken;\n const imageCost = (tokens.image ?? 0) * (pricing.imageUsdPerUnit ?? 0);\n const requestFlat = pricing.requestUsdPerRequest;\n\n if (routedViaOpenRouter) {\n promptCost +=\n tokens.prompt * (pricing.openRouterMarkupUsdPerInputToken ?? 0);\n completionCost +=\n tokens.completion * (pricing.openRouterMarkupUsdPerOutputToken ?? 0);\n }\n\n const cost =\n promptCost +\n completionCost +\n cachingCost +\n reasoningCost +\n audioCost +\n imageCost +\n requestFlat;\n\n if (!includeBreakdown) {\n return { cost };\n }\n\n return {\n cost,\n breakdown: {\n promptCostUsd: promptCost,\n completionCostUsd: completionCost,\n cachingCostUsd: cachingCost || undefined,\n reasoningCostUsd: reasoningCost || undefined,\n audioCostUsd: audioCost || undefined,\n imageCostUsd: imageCost || undefined,\n requestFlatCostUsd: requestFlat || undefined,\n },\n };\n}\n","import type { AliasRegistry } from \"../aliases/AliasRegistry.js\";\nimport type { AiModelsCatalogClient } from \"../catalog/AiModelsCatalogClient.js\";\nimport { UnknownModelCostError } from \"../errors.js\";\nimport { normalizeString } from \"../sync/modelNameResolver/normalize.js\";\nimport { stripModelVersionSuffix } from \"../sync/modelNameResolver/stripVersionSuffix.js\";\nimport type {\n ModelResolutionResult,\n ModelResolverOptions,\n} from \"../sync/modelNameResolver/types.js\";\nimport { matchModelInAiProfiles } from \"./aiProfilesMatch.js\";\nimport {\n buildCatalogResolveAttempts,\n isLocalProvider,\n isLocalProviderResolution,\n resolveFromCatalogAttempts,\n resolveRoutedViaOpenRouter,\n} from \"./costModelResolution.js\";\nimport {\n aiProfilesPricingToCatalogPricing,\n computeCostFromPricing,\n} from \"./profilePricing.js\";\nimport { enrichCostResult, toCostExtraction } from \"./enrichCostResult.js\";\nimport {\n extractUsageInput,\n type ExtractUsageInputOptions,\n} from \"./extractUsageInput.js\";\nimport { resolveUsageModel } from \"./resolveUsageModel.js\";\nimport type { AiCostResult, AiCostWarning, AiModelPricing, AiUsageInput } from \"./types.js\";\n\nexport type CostCalculatorOptions = {\n aliasRegistry?: AliasRegistry;\n includeBreakdown?: boolean;\n resolverOptions?: ModelResolverOptions;\n /** When true, throw {@link UnknownModelCostError} instead of zero-cost fallback. */\n throwOnUnknownModel?: boolean;\n};\n\nfunction emptyPricing(): AiModelPricing {\n return {\n promptUsdPerToken: 0,\n completionUsdPerToken: 0,\n imageUsdPerUnit: 0,\n requestUsdPerRequest: 0,\n pricedAt: new Date().toISOString(),\n source: \"manual\",\n };\n}\n\nfunction mergeAttempts(\n ...groups: ReturnType<typeof buildCatalogResolveAttempts>[]\n): ReturnType<typeof buildCatalogResolveAttempts> {\n const seen = new Set<string>();\n const out: ReturnType<typeof buildCatalogResolveAttempts> = [];\n for (const group of groups) {\n for (const a of group) {\n const key = `${a.provider ?? \"\"}\\0${a.model}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(a);\n }\n }\n return out;\n}\n\nexport class CostCalculator {\n private readonly aliasRegistry?: AliasRegistry;\n private readonly includeBreakdown: boolean;\n private readonly resolverOptions?: ModelResolverOptions;\n private readonly throwOnUnknownModel: boolean;\n\n constructor(\n private readonly catalog: AiModelsCatalogClient,\n options: CostCalculatorOptions = {},\n ) {\n this.aliasRegistry = options.aliasRegistry;\n this.includeBreakdown = options.includeBreakdown ?? true;\n this.resolverOptions = options.resolverOptions;\n this.throwOnUnknownModel = options.throwOnUnknownModel ?? false;\n }\n\n /**\n * Extract model, provider, and token usage from an activity / gateway record\n * (MongoDB export, nested `outer`, `config`, `metadata.diagnostics`, etc.)\n * then run {@link calculate}.\n */\n async calculateFromRecord(\n record: unknown,\n extractOptions?: ExtractUsageInputOptions,\n ): Promise<AiCostResult> {\n const { input, provenance } = extractUsageInput(record, extractOptions);\n const warnings: AiCostWarning[] = [];\n if (provenance.tokens.estimated) {\n warnings.push({\n code: \"ESTIMATED_TOKEN_USAGE\",\n message: `Token counts are estimates from ${provenance.tokens.path} (not billed usage).`,\n });\n }\n const result = await this.calculate(input);\n const enriched = enrichCostResult(result, input, toCostExtraction(provenance));\n if (warnings.length > 0) {\n enriched.warnings = [...(enriched.warnings ?? []), ...warnings];\n }\n return enriched;\n }\n\n async calculate(input: AiUsageInput): Promise<AiCostResult> {\n const modelInput = resolveUsageModel(input);\n const resolverOpts = {\n ...this.resolverOptions,\n aliasRegistry: this.aliasRegistry ?? this.resolverOptions?.aliasRegistry,\n };\n\n let resolved = await resolveFromCatalogAttempts(\n this.catalog,\n buildCatalogResolveAttempts(modelInput, input.provider),\n resolverOpts,\n );\n\n if (isLocalProviderResolution(resolved, input.provider)) {\n return this.localProviderResult(modelInput, input, resolved);\n }\n\n let profileMatch = null as Awaited<ReturnType<typeof matchModelInAiProfiles>>;\n const warnings: AiCostWarning[] = [];\n\n if (!resolved?.found || !resolved.record) {\n if (!isLocalProvider(input.provider)) {\n profileMatch = await matchModelInAiProfiles(modelInput, input.provider);\n }\n if (profileMatch) {\n resolved = await resolveFromCatalogAttempts(\n this.catalog,\n mergeAttempts(\n buildCatalogResolveAttempts(\n profileMatch.canonicalModelId,\n input.provider ?? profileMatch.provider,\n ),\n buildCatalogResolveAttempts(\n profileMatch.canonicalModelId,\n profileMatch.provider,\n ),\n ),\n resolverOpts,\n );\n }\n\n if (isLocalProviderResolution(resolved, input.provider)) {\n return this.localProviderResult(modelInput, input, resolved);\n }\n\n if ((!resolved?.found || !resolved.record) && profileMatch?.pricing) {\n const routedViaOpenRouter = resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n profileMatch.canonicalModelId,\n resolverOpts?.routingEnv,\n );\n const pricing = aiProfilesPricingToCatalogPricing(\n profileMatch.pricing,\n new Date().toISOString(),\n {\n promptTokens: input.tokens.prompt,\n routedViaOpenRouter,\n },\n );\n const { cost, breakdown } = computeCostFromPricing(\n input,\n pricing,\n routedViaOpenRouter,\n this.includeBreakdown,\n );\n\n warnings.push({\n code: \"AI_PROFILES_ESTIMATE\",\n message: `Catalog has no pricing for \"${modelInput}\"; estimated from ai-profiles (${profileMatch.matchedVia} → ${profileMatch.canonicalModelId}).`,\n });\n if (\n routedViaOpenRouter &&\n pricing.openRouterMarkupUsdPerInputToken !== undefined\n ) {\n warnings.push({\n code: \"OPENROUTER_MARKUP_ESTIMATED\",\n message:\n \"OpenRouter markup estimated at 5% of base token rates (catalog markup fields absent).\",\n });\n }\n\n console.warn(`[ai-tools] ${warnings.map((w) => w.message).join(\" \")}`);\n\n return this.finish(\n {\n cost,\n breakdown,\n resolvedModelId: profileMatch.canonicalModelId,\n routedViaOpenRouter,\n isAuthoritative: false,\n pricingSnapshot: pricing,\n source: \"ai-profiles\",\n warnings,\n },\n input,\n resolved,\n );\n }\n }\n\n if (!resolved?.found || !resolved.record) {\n return this.unknownModelResult(modelInput, input, resolved);\n }\n\n const { record, modelId } = resolved;\n const routedViaOpenRouter = resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n modelId,\n resolverOpts?.routingEnv,\n );\n const pricing = record.pricing;\n const { cost, breakdown } = computeCostFromPricing(\n input,\n pricing,\n routedViaOpenRouter,\n this.includeBreakdown,\n );\n\n return this.finish(\n {\n cost,\n breakdown,\n resolvedModelId: modelId,\n routedViaOpenRouter,\n isAuthoritative: true,\n pricingSnapshot: pricing,\n source: \"catalog\",\n },\n input,\n resolved,\n );\n }\n\n private versionSuffixWarnings(\n input: AiUsageInput,\n pricedModelId: string,\n resolved?: ModelResolutionResult | null,\n ): AiCostWarning[] {\n const received = input.usedModel ?? input.modelUsed ?? input.model;\n if (!received) return [];\n\n const normalizedReceived = normalizeString(received);\n const normalizedPriced = normalizeString(pricedModelId);\n if (normalizedReceived === normalizedPriced) return [];\n\n const stripped = stripModelVersionSuffix(received);\n const viaResolver =\n resolved?.found === true &&\n resolved.resolvedVia.some(\n (s) => s === \"version-suffix-strip\" || s === \"date-suffix-strip\",\n );\n const pricedViaStrip =\n stripped !== null && normalizeString(stripped) === normalizedPriced;\n\n if (!viaResolver && !pricedViaStrip) return [];\n\n return [\n {\n code: \"VERSION_SUFFIX_PRICING\",\n message: `Priced using catalog model \"${pricedModelId}\" (no exact pricing for \"${received}\").`,\n },\n ];\n }\n\n private finish(\n partial: Omit<\n AiCostResult,\n \"usage\" | \"provider\" | \"usedModel\" | \"model\" | \"extraction\"\n >,\n input: AiUsageInput,\n resolved?: ModelResolutionResult | null,\n ): AiCostResult {\n const enriched = enrichCostResult(partial, input);\n const suffixWarnings = this.versionSuffixWarnings(\n input,\n partial.resolvedModelId,\n resolved,\n );\n if (suffixWarnings.length > 0) {\n enriched.warnings = [...(enriched.warnings ?? []), ...suffixWarnings];\n }\n return enriched;\n }\n\n private localProviderResult(\n modelInput: string,\n input: AiUsageInput,\n resolved: Awaited<ReturnType<typeof resolveFromCatalogAttempts>>,\n ): AiCostResult {\n const warnings: AiCostWarning[] = [\n {\n code: \"LOCAL_PROVIDER_NO_PRICING\",\n message: `Local provider \"${input.provider}\" has no catalog pricing for \"${modelInput}\".`,\n },\n ];\n console.warn(`[ai-tools] ${warnings[0]!.message}`);\n return this.finish(\n {\n cost: 0,\n resolvedModelId: resolved?.found ? resolved.modelId : modelInput,\n routedViaOpenRouter: false,\n isAuthoritative: false,\n pricingSnapshot: emptyPricing(),\n source: \"local\",\n warnings,\n },\n input,\n );\n }\n\n private unknownModelResult(\n modelInput: string,\n input: AiUsageInput,\n resolved: Awaited<ReturnType<typeof resolveFromCatalogAttempts>>,\n ): AiCostResult {\n if (this.throwOnUnknownModel) {\n throw new UnknownModelCostError(modelInput, input.provider);\n }\n\n const warnings: AiCostWarning[] = [\n {\n code: \"UNKNOWN_MODEL\",\n message: `Unknown model \"${modelInput}\" (provider: \"${input.provider}\") — returning zero-cost fallback.`,\n },\n ];\n console.warn(`[ai-tools] ${warnings[0]!.message}`);\n\n return this.finish(\n {\n cost: 0,\n resolvedModelId: modelInput,\n routedViaOpenRouter: resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n modelInput,\n this.resolverOptions?.routingEnv,\n ),\n isAuthoritative: false,\n pricingSnapshot: emptyPricing(),\n source: \"estimate-fallback\",\n unknownModel: true,\n warnings,\n },\n input,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AACO,IAAM,iCAAiC;AAGvC,IAAM,mCAAmC;;;ACDzC,SAAS,iBACd,YACkB;AAClB,SAAO;AAAA,IACL,OAAO,EAAE,OAAO,WAAW,MAAM,OAAO,MAAM,WAAW,MAAM,KAAK;AAAA,IACpE,QAAQ;AAAA,MACN,QAAQ,WAAW,OAAO;AAAA,MAC1B,MAAM,WAAW,OAAO;AAAA,MACxB,WAAW,WAAW,OAAO;AAAA,IAC/B;AAAA,IACA,G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AChC;AAAA,QACE,MAAM;AAAA,QACN,SAAS,mBAAmB,MAAM,QAAQ,iCAAiC,UAAU;AAAA,MACvF;AAAA,IACF;AACA,YAAQ,KAAK,cAAc,SAAS,CAAC,EAAG,OAAO,EAAE;AACjD,WAAO,KAAK;AAAA,MACV;AAAA,QACE,MAAM;AAAA,QACN,iBAAiB,UAAU,QAAQ,SAAS,UAAU;AAAA,QACtD,qBAAqB;AAAA,QACrB,iBAAiB;AAAA,QACjB,iBAAiB,aAAa;AAAA,QAC9B,QAAQ;AAAA,QACR;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,mBACN,YACA,OACA,UACc;AACd,QAAI,KAAK,qBAAqB;AAC5B,YAAM,IAAI,sBAAsB,YAAY,MAAM,QAAQ;AAAA,IAC5D;AAEA,UAAM,WAA4B;AAAA,MAChC;AAAA,QACE,MAAM;AAAA,QACN,SAAS,kBAAkB,UAAU,iBAAiB,MAAM,QAAQ;AAAA,MACtE;AAAA,IACF;AACA,YAAQ,KAAK,cAAc,SAAS,CAAC,EAAG,OAAO,EAAE;AAEjD,WAAO,KAAK;AAAA,MACV;AAAA,QACE,MAAM;AAAA,QACN,iBAAiB;AAAA,QACjB,qBAAqB;AAAA,UACnB,MAAM;AAAA,UACN;AAAA,UACA;AAAA,UACA,KAAK,iBAAiB;AAAA,QACxB;AAAA,QACA,iBAAiB;AAAA,QACjB,iBAAiB,aAAa;AAAA,QAC9B,QAAQ;AAAA,QACR,cAAc;AAAA,QACd;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":["routedViaOpenRouter","pricing","cost","breakdown"]}
|
|
1
|
+
{"version":3,"sources":["../src/cost/constants.ts","../src/cost/enrichCostResult.ts","../src/cost/extractUsageInput.ts","../src/cost/resolveUsageModel.ts","../src/cost/profilePricing.ts","../src/cost/CostCalculator.ts"],"sourcesContent":["/** Default OpenRouter platform surcharge when catalog markup fields are absent (5%). */\nexport const DEFAULT_OPENROUTER_MARKUP_RATE = 0.05;\n\n/** ai-profiles tiered pricing threshold (tokens). */\nexport const PROFILE_TIERED_CONTEXT_THRESHOLD = 200_000;\n","import type { ExtractUsageInputResult } from \"./extractUsageInput.js\";\nimport type { AiCostExtraction, AiCostResult, AiUsageInput } from \"./types.js\";\n\nexport function toCostExtraction(\n provenance: ExtractUsageInputResult[\"provenance\"],\n): AiCostExtraction {\n return {\n model: { field: provenance.model.field, path: provenance.model.path },\n tokens: {\n source: provenance.tokens.source,\n path: provenance.tokens.path,\n estimated: provenance.tokens.estimated,\n },\n ...(provenance.modelUsed\n ? {\n modelUsed: {\n field: provenance.modelUsed.field,\n path: provenance.modelUsed.path,\n },\n }\n : {}),\n ...(provenance.provider\n ? {\n provider: {\n field: provenance.provider.field,\n path: provenance.provider.path,\n },\n }\n : {}),\n };\n}\n\n/** Attach usage, provider, and model fields callers expect on every cost response. */\nexport function enrichCostResult(\n result: Omit<\n AiCostResult,\n \"usage\" | \"provider\" | \"usedModel\" | \"model\" | \"extraction\"\n >,\n input: AiUsageInput,\n extraction?: AiCostExtraction,\n): AiCostResult {\n /** Original model id from the caller — never replaced by catalog resolution. */\n const receivedModelId = input.usedModel ?? input.modelUsed ?? input.model;\n\n return {\n ...result,\n provider: input.provider,\n usage: { ...input.tokens },\n ...(receivedModelId ? { usedModel: receivedModelId } : {}),\n ...(input.model && input.model !== receivedModelId ? { model: input.model } : {}),\n ...(extraction ? { extraction } : {}),\n };\n}\n","import type { AiUsageInput } from \"./types.js\";\n\n/** Model id field priority (higher wins). Runtime ids beat request/config aliases. */\nexport const MODEL_FIELD_PRIORITY: readonly { key: string; score: number }[] = [\n { key: \"usedModel\", score: 1000 },\n { key: \"modelUsed\", score: 990 },\n { key: \"resolvedModel\", score: 980 },\n { key: \"model\", score: 500 },\n { key: \"xynthesisModel\", score: 120 },\n { key: \"skillModel\", score: 110 },\n] as const;\n\n/** Path segments that boost or penalize a model candidate. */\nconst MODEL_PATH_BONUS: readonly { pattern: RegExp; bonus: number }[] = [\n { pattern: /(^|\\.)response(\\.|$)/i, bonus: 40 },\n { pattern: /(^|\\.)outer\\.input(\\.|$)/i, bonus: 35 },\n { pattern: /(^|\\.)config(?!\\.rawConfig)(\\.|$)/i, bonus: 30 },\n { pattern: /(^|\\.)outer\\.input\\.config(\\.|$)/i, bonus: 28 },\n { pattern: /(^|\\.)usage(\\.|$)/i, bonus: 15 },\n { pattern: /(^|\\.)rawConfig(\\.|$)/i, bonus: -40 },\n { pattern: /workingMemory/i, bonus: -50 },\n { pattern: /requestExample/i, bonus: -80 },\n { pattern: /graphsStudio/i, bonus: -80 },\n];\n\nconst PROVIDER_FIELD_PRIORITY: readonly { key: string; score: number }[] = [\n { key: \"provider\", score: 500 },\n { key: \"providerId\", score: 480 },\n] as const;\n\nconst PROVIDER_PATH_BONUS: readonly { pattern: RegExp; bonus: number }[] = [\n { pattern: /(^|\\.)config(?!\\.rawConfig)(\\.|$)/i, bonus: 30 },\n { pattern: /(^|\\.)outer\\.input(\\.|$)/i, bonus: 20 },\n { pattern: /(^|\\.)rawConfig(\\.|$)/i, bonus: -20 },\n];\n\nconst PROMPT_TOKEN_KEYS = new Set([\n \"prompt\",\n \"prompt_tokens\",\n \"promptTokens\",\n \"input_tokens\",\n \"inputTokens\",\n \"estimatedInputTokens\",\n \"input\",\n]);\n\nconst COMPLETION_TOKEN_KEYS = new Set([\n \"completion\",\n \"completion_tokens\",\n \"completionTokens\",\n \"output_tokens\",\n \"outputTokens\",\n \"estimatedOutputTokens\",\n \"output\",\n]);\n\nconst OPTIONAL_TOKEN_KEYS: Record<string, keyof AiUsageInput[\"tokens\"]> = {\n total: \"total\",\n total_tokens: \"total\",\n totalTokens: \"total\",\n cached: \"cached\",\n cached_tokens: \"cached\",\n cache_read_tokens: \"cached\",\n cacheReadTokens: \"cached\",\n cacheWrite: \"cacheWrite\",\n cache_write_tokens: \"cacheWrite\",\n cacheWriteTokens: \"cacheWrite\",\n reasoning: \"reasoning\",\n reasoning_tokens: \"reasoning\",\n reasoningTokens: \"reasoning\",\n audio: \"audio\",\n audio_tokens: \"audio\",\n image: \"image\",\n image_tokens: \"image\",\n};\n\nexport type FieldProvenance = {\n field: string;\n path: string;\n score: number;\n};\n\nexport type TokenExtractionProvenance = {\n source: \"usage\" | \"tokens\" | \"diagnostics\" | \"estimated\";\n path: string;\n estimated?: boolean;\n};\n\nexport type ExtractUsageInputResult = {\n input: AiUsageInput;\n provenance: {\n model: FieldProvenance;\n modelUsed?: FieldProvenance;\n provider?: FieldProvenance;\n tokens: TokenExtractionProvenance;\n };\n};\n\nexport type ExtractUsageInputOptions = {\n /** Default when no provider field is found (default: `openrouter`). */\n defaultProvider?: string;\n};\n\ntype ModelCandidate = FieldProvenance & { value: string };\ntype ProviderCandidate = FieldProvenance & { value: string };\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction modelKeyScore(key: string): number {\n return MODEL_FIELD_PRIORITY.find((e) => e.key === key)?.score ?? 0;\n}\n\nfunction providerKeyScore(key: string): number {\n return PROVIDER_FIELD_PRIORITY.find((e) => e.key === key)?.score ?? 0;\n}\n\nfunction pathBonus(path: string, rules: readonly { pattern: RegExp; bonus: number }[]): number {\n let bonus = 0;\n for (const { pattern, bonus: b } of rules) {\n if (pattern.test(path)) bonus += b;\n }\n return bonus;\n}\n\nfunction normalizeModelValue(v: unknown): string | undefined {\n if (typeof v !== \"string\") return undefined;\n const t = v.trim();\n return t.length > 0 ? t : undefined;\n}\n\nfunction normalizeProviderValue(v: unknown): string | undefined {\n if (typeof v !== \"string\") return undefined;\n const t = v.trim().toLowerCase();\n if (!t || t === \"null\") return undefined;\n return t;\n}\n\nfunction collectModelCandidates(\n node: unknown,\n path: string,\n out: ModelCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n const base = modelKeyScore(key);\n if (base > 0) {\n const model = normalizeModelValue(value);\n if (model) {\n out.push({\n field: key,\n path: childPath,\n value: model,\n score: base + pathBonus(childPath, MODEL_PATH_BONUS),\n });\n }\n }\n collectModelCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectModelCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction collectProviderCandidates(\n node: unknown,\n path: string,\n out: ProviderCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n const base = providerKeyScore(key);\n if (base > 0) {\n const provider = normalizeProviderValue(value);\n if (provider) {\n out.push({\n field: key,\n path: childPath,\n value: provider,\n score: base + pathBonus(childPath, PROVIDER_PATH_BONUS),\n });\n }\n }\n collectProviderCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectProviderCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction readNumber(obj: Record<string, unknown>, keys: Set<string>): number | undefined {\n for (const [k, v] of Object.entries(obj)) {\n if (!keys.has(k)) continue;\n if (typeof v === \"number\" && Number.isFinite(v) && v >= 0) return v;\n }\n return undefined;\n}\n\nfunction readOptionalNumbers(\n obj: Record<string, unknown>,\n): Partial<AiUsageInput[\"tokens\"]> {\n const extra: Partial<AiUsageInput[\"tokens\"]> = {};\n for (const [k, v] of Object.entries(obj)) {\n const target = OPTIONAL_TOKEN_KEYS[k];\n if (!target || typeof v !== \"number\" || !Number.isFinite(v) || v < 0) continue;\n extra[target] = v;\n }\n return extra;\n}\n\nfunction looksLikeUsageObject(obj: Record<string, unknown>): boolean {\n const hasPrompt = readNumber(obj, PROMPT_TOKEN_KEYS) !== undefined;\n const hasCompletion = readNumber(obj, COMPLETION_TOKEN_KEYS) !== undefined;\n return hasPrompt && hasCompletion;\n}\n\nfunction looksLikeDiagnosticsObject(obj: Record<string, unknown>): boolean {\n return (\n typeof obj.estimatedInputTokens === \"number\" &&\n typeof obj.estimatedOutputTokens === \"number\"\n );\n}\n\ntype TokenCandidate = {\n tokens: AiUsageInput[\"tokens\"];\n provenance: TokenExtractionProvenance;\n score: number;\n};\n\nfunction tokensFromObject(\n obj: Record<string, unknown>,\n source: TokenExtractionProvenance[\"source\"],\n path: string,\n estimated: boolean,\n score: number,\n): TokenCandidate | null {\n const prompt = readNumber(obj, PROMPT_TOKEN_KEYS);\n const completion = readNumber(obj, COMPLETION_TOKEN_KEYS);\n if (prompt === undefined || completion === undefined) return null;\n\n const extra = readOptionalNumbers(obj);\n const total =\n typeof extra.total === \"number\" ? extra.total : prompt + completion;\n\n return {\n tokens: {\n prompt,\n completion,\n total,\n ...extra,\n },\n provenance: { source, path, estimated },\n score,\n };\n}\n\nfunction collectTokenCandidates(\n node: unknown,\n path: string,\n out: TokenCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n if (path.endsWith(\"diagnostics\") || looksLikeDiagnosticsObject(node)) {\n const cand = tokensFromObject(node, \"diagnostics\", path, true, 200);\n if (cand) out.push(cand);\n } else if (path.endsWith(\"usage\") || path.endsWith(\"tokens\") || looksLikeUsageObject(node)) {\n const source = path.endsWith(\"tokens\") ? \"tokens\" : \"usage\";\n const estimated = false;\n const score = path.endsWith(\"usage\") ? 500 : 450;\n const cand = tokensFromObject(node, source, path, estimated, score);\n if (cand) out.push(cand);\n }\n\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n if (key === \"usage\" || key === \"tokens\" || key === \"diagnostics\") {\n if (isPlainObject(value)) {\n collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n } else {\n collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectTokenCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction pickBestModel(candidates: ModelCandidate[]): ModelCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction pickBestProvider(candidates: ProviderCandidate[]): ProviderCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction pickBestTokens(candidates: TokenCandidate[]): TokenCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction inferProviderFromModel(model: string, fallback: string): string {\n const slash = model.indexOf(\"/\");\n if (slash > 0) {\n const prefix = model.slice(0, slash).toLowerCase();\n if (prefix !== \"openrouter\") return prefix;\n }\n return fallback;\n}\n\n/**\n * Extract {@link AiUsageInput} from activity logs, gateway records, MongoDB exports,\n * or any nested JSON shape (e.g. `outer.input`, `config`, `metadata.diagnostics`).\n */\nexport function extractUsageInput(\n record: unknown,\n options: ExtractUsageInputOptions = {},\n): ExtractUsageInputResult {\n const defaultProvider = options.defaultProvider ?? \"openrouter\";\n const maxDepth = 24;\n\n const modelCandidates: ModelCandidate[] = [];\n const providerCandidates: ProviderCandidate[] = [];\n const tokenCandidates: TokenCandidate[] = [];\n\n collectModelCandidates(record, \"\", modelCandidates, 0, maxDepth);\n collectProviderCandidates(record, \"\", providerCandidates, 0, maxDepth);\n collectTokenCandidates(record, \"\", tokenCandidates, 0, maxDepth);\n\n const bestModel = pickBestModel(modelCandidates);\n if (!bestModel) {\n throw new Error(\n \"[ai-tools] Could not extract a model from the record (looked for usedModel, modelUsed, model, …).\",\n );\n }\n\n const runtimeFields = new Set([\"usedModel\", \"modelUsed\", \"resolvedModel\"]);\n const isRuntimeModel = runtimeFields.has(bestModel.field);\n const requestModel = modelCandidates.find(\n (c) => c.field === \"model\" && c.path !== bestModel.path,\n );\n\n const bestProvider = pickBestProvider(providerCandidates);\n const provider =\n bestProvider?.value ??\n inferProviderFromModel(bestModel.value, defaultProvider);\n\n const bestTokens = pickBestTokens(tokenCandidates);\n if (!bestTokens) {\n throw new Error(\n \"[ai-tools] Could not extract token usage from the record (usage, tokens, or metadata.diagnostics).\",\n );\n }\n\n const input: AiUsageInput = {\n tokens: bestTokens.tokens,\n provider,\n ...(isRuntimeModel\n ? { modelUsed: bestModel.value, model: requestModel?.value }\n : { model: bestModel.value }),\n };\n\n const provenance: ExtractUsageInputResult[\"provenance\"] = {\n model: {\n field: bestModel.field,\n path: bestModel.path,\n score: bestModel.score,\n },\n tokens: bestTokens.provenance,\n };\n\n if (bestProvider) {\n provenance.provider = {\n field: bestProvider.field,\n path: bestProvider.path,\n score: bestProvider.score,\n };\n }\n\n if (isRuntimeModel && requestModel) {\n provenance.modelUsed = {\n field: bestModel.field,\n path: bestModel.path,\n score: bestModel.score,\n };\n } else if (input.modelUsed) {\n provenance.modelUsed = provenance.model;\n }\n\n return { input, provenance };\n}\n","import type { AiUsageInput } from \"./types.js\";\n\n/** Prefer runtime id (`usedModel` / `modelUsed`); fall back to `model`. */\nexport function resolveUsageModel(input: AiUsageInput): string {\n const value = input.usedModel ?? input.modelUsed ?? input.model;\n if (!value?.trim()) {\n throw new Error(\n \"[ai-tools] Cost calculation requires `usedModel`, `modelUsed`, or `model` on usage input.\",\n );\n }\n return value.trim();\n}\n","import type { AIModelPricing } from \"@x12i/ai-profiles\";\nimport {\n DEFAULT_OPENROUTER_MARKUP_RATE,\n PROFILE_TIERED_CONTEXT_THRESHOLD,\n} from \"./constants.js\";\nimport type { AiModelPricing, AiUsageInput } from \"./types.js\";\n\nconst TOKENS_PER_UNIT = 1_000_000;\n\nfunction usdPerToken(perMillion?: number): number {\n return (perMillion ?? 0) / TOKENS_PER_UNIT;\n}\n\nfunction pickInputRatePerMillion(\n pricing: AIModelPricing,\n promptTokens: number,\n): number | undefined {\n if (\n pricing.inputBelow200k !== undefined &&\n pricing.inputAbove200k !== undefined\n ) {\n return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD\n ? pricing.inputBelow200k\n : pricing.inputAbove200k;\n }\n return pricing.input ?? pricing.inputBelow200k ?? pricing.inputAbove200k;\n}\n\nfunction pickOutputRatePerMillion(\n pricing: AIModelPricing,\n promptTokens: number,\n): number | undefined {\n if (\n pricing.outputBelow200k !== undefined &&\n pricing.outputAbove200k !== undefined\n ) {\n return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD\n ? pricing.outputBelow200k\n : pricing.outputAbove200k;\n }\n return pricing.output ?? pricing.outputBelow200k ?? pricing.outputAbove200k;\n}\n\nexport type AiProfilesPricingOptions = {\n promptTokens?: number;\n routedViaOpenRouter?: boolean;\n};\n\nexport function aiProfilesPricingToCatalogPricing(\n pricing: AIModelPricing,\n pricedAt: string,\n options: AiProfilesPricingOptions = {},\n): AiModelPricing {\n const promptTokens = options.promptTokens ?? 0;\n const promptUsdPerToken = usdPerToken(pickInputRatePerMillion(pricing, promptTokens));\n const completionUsdPerToken = usdPerToken(\n pickOutputRatePerMillion(pricing, promptTokens),\n );\n\n const snapshot: AiModelPricing = {\n promptUsdPerToken,\n completionUsdPerToken,\n cacheReadUsdPerToken: usdPerToken(pricing.cachedInput ?? pricing.cacheHit),\n cacheWriteUsdPerToken: usdPerToken(pricing.cacheWrite5m ?? pricing.cacheWrite1h),\n imageUsdPerUnit: 0,\n requestUsdPerRequest: 0,\n pricedAt,\n source: \"manual\",\n };\n\n if (options.routedViaOpenRouter) {\n snapshot.openRouterMarkupUsdPerInputToken =\n promptUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;\n snapshot.openRouterMarkupUsdPerOutputToken =\n completionUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;\n }\n\n return snapshot;\n}\n\nexport function computeCostFromPricing(\n input: AiUsageInput,\n pricing: AiModelPricing,\n routedViaOpenRouter: boolean,\n includeBreakdown: boolean,\n): { cost: number; breakdown?: import(\"./types.js\").AiCostResult[\"breakdown\"] } {\n const { tokens } = input;\n\n let promptCost = tokens.prompt * pricing.promptUsdPerToken;\n let completionCost = tokens.completion * pricing.completionUsdPerToken;\n\n const cachingCost =\n (tokens.cacheWrite ?? 0) * (pricing.cacheWriteUsdPerToken ?? 0) +\n (tokens.cached ?? 0) * (pricing.cacheReadUsdPerToken ?? 0);\n\n const reasoningCost =\n (tokens.reasoning ?? 0) *\n (pricing.reasoningUsdPerToken ?? pricing.promptUsdPerToken);\n\n const audioCost = (tokens.audio ?? 0) * pricing.promptUsdPerToken;\n const imageCost = (tokens.image ?? 0) * (pricing.imageUsdPerUnit ?? 0);\n const requestFlat = pricing.requestUsdPerRequest;\n\n if (routedViaOpenRouter) {\n promptCost +=\n tokens.prompt * (pricing.openRouterMarkupUsdPerInputToken ?? 0);\n completionCost +=\n tokens.completion * (pricing.openRouterMarkupUsdPerOutputToken ?? 0);\n }\n\n const cost =\n promptCost +\n completionCost +\n cachingCost +\n reasoningCost +\n audioCost +\n imageCost +\n requestFlat;\n\n if (!includeBreakdown) {\n return { cost };\n }\n\n return {\n cost,\n breakdown: {\n promptCostUsd: promptCost,\n completionCostUsd: completionCost,\n cachingCostUsd: cachingCost || undefined,\n reasoningCostUsd: reasoningCost || undefined,\n audioCostUsd: audioCost || undefined,\n imageCostUsd: imageCost || undefined,\n requestFlatCostUsd: requestFlat || undefined,\n },\n };\n}\n","import type { AliasRegistry } from \"../aliases/AliasRegistry.js\";\nimport type { AiModelsCatalogClient } from \"../catalog/AiModelsCatalogClient.js\";\nimport { UnknownModelCostError } from \"../errors.js\";\nimport { normalizeString } from \"../sync/modelNameResolver/normalize.js\";\nimport { stripModelVersionSuffix } from \"../sync/modelNameResolver/stripVersionSuffix.js\";\nimport type {\n ModelResolutionResult,\n ModelResolverOptions,\n} from \"../sync/modelNameResolver/types.js\";\nimport { matchModelInAiProfiles } from \"./aiProfilesMatch.js\";\nimport {\n buildCatalogResolveAttempts,\n isLocalProvider,\n isLocalProviderResolution,\n resolveFromCatalogAttempts,\n resolveRoutedViaOpenRouter,\n} from \"./costModelResolution.js\";\nimport {\n aiProfilesPricingToCatalogPricing,\n computeCostFromPricing,\n} from \"./profilePricing.js\";\nimport { enrichCostResult, toCostExtraction } from \"./enrichCostResult.js\";\nimport {\n extractUsageInput,\n type ExtractUsageInputOptions,\n} from \"./extractUsageInput.js\";\nimport { resolveUsageModel } from \"./resolveUsageModel.js\";\nimport type { AiCostResult, AiCostWarning, AiModelPricing, AiUsageInput } from \"./types.js\";\n\nexport type CostCalculatorOptions = {\n aliasRegistry?: AliasRegistry;\n includeBreakdown?: boolean;\n resolverOptions?: ModelResolverOptions;\n /** When true, throw {@link UnknownModelCostError} instead of zero-cost fallback. */\n throwOnUnknownModel?: boolean;\n};\n\nfunction emptyPricing(): AiModelPricing {\n return {\n promptUsdPerToken: 0,\n completionUsdPerToken: 0,\n imageUsdPerUnit: 0,\n requestUsdPerRequest: 0,\n pricedAt: new Date().toISOString(),\n source: \"manual\",\n };\n}\n\nfunction mergeAttempts(\n ...groups: ReturnType<typeof buildCatalogResolveAttempts>[]\n): ReturnType<typeof buildCatalogResolveAttempts> {\n const seen = new Set<string>();\n const out: ReturnType<typeof buildCatalogResolveAttempts> = [];\n for (const group of groups) {\n for (const a of group) {\n const key = `${a.provider ?? \"\"}\\0${a.model}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(a);\n }\n }\n return out;\n}\n\nexport class CostCalculator {\n private readonly aliasRegistry?: AliasRegistry;\n private readonly includeBreakdown: boolean;\n private readonly resolverOptions?: ModelResolverOptions;\n private readonly throwOnUnknownModel: boolean;\n\n constructor(\n private readonly catalog: AiModelsCatalogClient,\n options: CostCalculatorOptions = {},\n ) {\n this.aliasRegistry = options.aliasRegistry;\n this.includeBreakdown = options.includeBreakdown ?? true;\n this.resolverOptions = options.resolverOptions;\n this.throwOnUnknownModel = options.throwOnUnknownModel ?? false;\n }\n\n /**\n * Extract model, provider, and token usage from an activity / gateway record\n * (MongoDB export, nested `outer`, `config`, `metadata.diagnostics`, etc.)\n * then run {@link calculate}.\n */\n async calculateFromRecord(\n record: unknown,\n extractOptions?: ExtractUsageInputOptions,\n ): Promise<AiCostResult> {\n const { input, provenance } = extractUsageInput(record, extractOptions);\n const warnings: AiCostWarning[] = [];\n if (provenance.tokens.estimated) {\n warnings.push({\n code: \"ESTIMATED_TOKEN_USAGE\",\n message: `Token counts are estimates from ${provenance.tokens.path} (not billed usage).`,\n });\n }\n const result = await this.calculate(input);\n const enriched = enrichCostResult(result, input, toCostExtraction(provenance));\n if (warnings.length > 0) {\n enriched.warnings = [...(enriched.warnings ?? []), ...warnings];\n }\n return enriched;\n }\n\n async calculate(input: AiUsageInput): Promise<AiCostResult> {\n const modelInput = resolveUsageModel(input);\n const resolverOpts = {\n ...this.resolverOptions,\n aliasRegistry: this.aliasRegistry ?? this.resolverOptions?.aliasRegistry,\n };\n\n let resolved = await resolveFromCatalogAttempts(\n this.catalog,\n buildCatalogResolveAttempts(modelInput, input.provider),\n resolverOpts,\n );\n\n if (isLocalProviderResolution(resolved, input.provider)) {\n return this.localProviderResult(modelInput, input, resolved);\n }\n\n let profileMatch = null as Awaited<ReturnType<typeof matchModelInAiProfiles>>;\n const warnings: AiCostWarning[] = [];\n\n if (!resolved?.found || !resolved.record) {\n if (!isLocalProvider(input.provider)) {\n profileMatch = await matchModelInAiProfiles(modelInput, input.provider, {\n catalogLane: this.resolverOptions?.catalogLane,\n });\n }\n if (profileMatch) {\n resolved = await resolveFromCatalogAttempts(\n this.catalog,\n mergeAttempts(\n buildCatalogResolveAttempts(\n profileMatch.canonicalModelId,\n input.provider ?? profileMatch.provider,\n ),\n buildCatalogResolveAttempts(\n profileMatch.canonicalModelId,\n profileMatch.provider,\n ),\n ),\n resolverOpts,\n );\n }\n\n if (isLocalProviderResolution(resolved, input.provider)) {\n return this.localProviderResult(modelInput, input, resolved);\n }\n\n if ((!resolved?.found || !resolved.record) && profileMatch?.pricing) {\n const routedViaOpenRouter = resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n profileMatch.canonicalModelId,\n resolverOpts?.routingEnv,\n );\n const pricing = aiProfilesPricingToCatalogPricing(\n profileMatch.pricing,\n new Date().toISOString(),\n {\n promptTokens: input.tokens.prompt,\n routedViaOpenRouter,\n },\n );\n const { cost, breakdown } = computeCostFromPricing(\n input,\n pricing,\n routedViaOpenRouter,\n this.includeBreakdown,\n );\n\n warnings.push({\n code: \"AI_PROFILES_ESTIMATE\",\n message: `Catalog has no pricing for \"${modelInput}\"; estimated from ai-profiles (${profileMatch.matchedVia} → ${profileMatch.canonicalModelId}).`,\n });\n if (\n routedViaOpenRouter &&\n pricing.openRouterMarkupUsdPerInputToken !== undefined\n ) {\n warnings.push({\n code: \"OPENROUTER_MARKUP_ESTIMATED\",\n message:\n \"OpenRouter markup estimated at 5% of base token rates (catalog markup fields absent).\",\n });\n }\n\n console.warn(`[ai-tools] ${warnings.map((w) => w.message).join(\" \")}`);\n\n return this.finish(\n {\n cost,\n breakdown,\n resolvedModelId: profileMatch.canonicalModelId,\n routedViaOpenRouter,\n isAuthoritative: false,\n pricingSnapshot: pricing,\n source: \"ai-profiles\",\n warnings,\n },\n input,\n resolved,\n );\n }\n }\n\n if (!resolved?.found || !resolved.record) {\n return this.unknownModelResult(modelInput, input, resolved);\n }\n\n const { record, modelId } = resolved;\n const routedViaOpenRouter = resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n modelId,\n resolverOpts?.routingEnv,\n );\n const pricing = record.pricing;\n const { cost, breakdown } = computeCostFromPricing(\n input,\n pricing,\n routedViaOpenRouter,\n this.includeBreakdown,\n );\n\n return this.finish(\n {\n cost,\n breakdown,\n resolvedModelId: modelId,\n routedViaOpenRouter,\n isAuthoritative: true,\n pricingSnapshot: pricing,\n source: \"catalog\",\n },\n input,\n resolved,\n );\n }\n\n private versionSuffixWarnings(\n input: AiUsageInput,\n pricedModelId: string,\n resolved?: ModelResolutionResult | null,\n ): AiCostWarning[] {\n const received = input.usedModel ?? input.modelUsed ?? input.model;\n if (!received) return [];\n\n const normalizedReceived = normalizeString(received);\n const normalizedPriced = normalizeString(pricedModelId);\n if (normalizedReceived === normalizedPriced) return [];\n\n const stripped = stripModelVersionSuffix(received);\n const viaResolver =\n resolved?.found === true &&\n resolved.resolvedVia.some(\n (s) => s === \"version-suffix-strip\" || s === \"date-suffix-strip\",\n );\n const pricedViaStrip =\n stripped !== null && normalizeString(stripped) === normalizedPriced;\n\n if (!viaResolver && !pricedViaStrip) return [];\n\n return [\n {\n code: \"VERSION_SUFFIX_PRICING\",\n message: `Priced using catalog model \"${pricedModelId}\" (no exact pricing for \"${received}\").`,\n },\n ];\n }\n\n private finish(\n partial: Omit<\n AiCostResult,\n \"usage\" | \"provider\" | \"usedModel\" | \"model\" | \"extraction\"\n >,\n input: AiUsageInput,\n resolved?: ModelResolutionResult | null,\n ): AiCostResult {\n const enriched = enrichCostResult(partial, input);\n const suffixWarnings = this.versionSuffixWarnings(\n input,\n partial.resolvedModelId,\n resolved,\n );\n if (suffixWarnings.length > 0) {\n enriched.warnings = [...(enriched.warnings ?? []), ...suffixWarnings];\n }\n return enriched;\n }\n\n private localProviderResult(\n modelInput: string,\n input: AiUsageInput,\n resolved: Awaited<ReturnType<typeof resolveFromCatalogAttempts>>,\n ): AiCostResult {\n const warnings: AiCostWarning[] = [\n {\n code: \"LOCAL_PROVIDER_NO_PRICING\",\n message: `Local provider \"${input.provider}\" has no catalog pricing for \"${modelInput}\".`,\n },\n ];\n console.warn(`[ai-tools] ${warnings[0]!.message}`);\n return this.finish(\n {\n cost: 0,\n resolvedModelId: resolved?.found ? resolved.modelId : modelInput,\n routedViaOpenRouter: false,\n isAuthoritative: false,\n pricingSnapshot: emptyPricing(),\n source: \"local\",\n warnings,\n },\n input,\n );\n }\n\n private unknownModelResult(\n modelInput: string,\n input: AiUsageInput,\n resolved: Awaited<ReturnType<typeof resolveFromCatalogAttempts>>,\n ): AiCostResult {\n if (this.throwOnUnknownModel) {\n throw new UnknownModelCostError(modelInput, input.provider);\n }\n\n const warnings: AiCostWarning[] = [\n {\n code: \"UNKNOWN_MODEL\",\n message: `Unknown model \"${modelInput}\" (provider: \"${input.provider}\") — returning zero-cost fallback.`,\n },\n ];\n console.warn(`[ai-tools] ${warnings[0]!.message}`);\n\n return this.finish(\n {\n cost: 0,\n resolvedModelId: modelInput,\n routedViaOpenRouter: resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n modelInput,\n this.resolverOptions?.routingEnv,\n ),\n isAuthoritative: false,\n pricingSnapshot: emptyPricing(),\n source: \"estimate-fallback\",\n unknownModel: true,\n warnings,\n },\n input,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AACO,IAAM,iCAAiC;AAGvC,IAAM,mCAAmC;;;ACDzC,SAAS,iBACd,YACkB;AAClB,SAAO;AAAA,IACL,OAAO,EAAE,OAAO,WAAW,MAAM,OAAO,MAAM,WAAW,MAAM,KAAK;AAAA,IACpE,QAAQ;AAAA,MACN,QAAQ,WAAW,OAAO;AAAA,MAC1B,MAAM,WAAW,OAAO;AAAA,MACxB,WAAW,WAAW,OAAO;AAAA,IAC/B;AAAA,IACA,GAAI,WAAW,YACX;AAAA,MACE,WAAW;AAAA,QACT,OAAO,WAAW,UAAU;AAAA,QAC5B,MAAM,WAAW,UAAU;AAAA,MAC7B;AAAA,IACF,IACA,CAAC;AAAA,IACL,GAAI,WAAW,WACX;AAAA,MACE,UAAU;AAAA,QACR,OAAO,WAAW,SAAS;AAAA,QAC3B,MAAM,WAAW,SAAS;AAAA,MAC5B;AAAA,IACF,IACA,CAAC;AAAA,EACP;AACF;AAGO,SAAS,iBACd,QAIA,OACA,YACc;AAEd,QAAM,kBAAkB,MAAM,aAAa,MAAM,aAAa,MAAM;AAEpE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,U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;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,mBACN,YACA,OACA,UACc;AACd,QAAI,KAAK,qBAAqB;AAC5B,YAAM,IAAI,sBAAsB,YAAY,MAAM,QAAQ;AAAA,IAC5D;AAEA,UAAM,WAA4B;AAAA,MAChC;AAAA,QACE,MAAM;AAAA,QACN,SAAS,kBAAkB,UAAU,iBAAiB,MAAM,QAAQ;AAAA,MACtE;AAAA,IACF;AACA,YAAQ,KAAK,cAAc,SAAS,CAAC,EAAG,OAAO,EAAE;AAEjD,WAAO,KAAK;AAAA,MACV;AAAA,QACE,MAAM;AAAA,QACN,iBAAiB;AAAA,QACjB,qBAAqB;AAAA,UACnB,MAAM;AAAA,UACN;AAAA,UACA;AAAA,UACA,KAAK,iBAAiB;AAAA,QACxB;AAAA,QACA,iBAAiB;AAAA,QACjB,iBAAiB,aAAa;AAAA,QAC9B,QAAQ;AAAA,QACR,cAAc;AAAA,QACd;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":["routedViaOpenRouter","pricing","cost","breakdown"]}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
|
-
var
|
|
8
|
+
var _chunkH7W5LMP6cjs = require('./chunk-H7W5LMP6.cjs');
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
|
|
@@ -497,29 +497,31 @@ var CostCalculator = class {
|
|
|
497
497
|
...this.resolverOptions,
|
|
498
498
|
aliasRegistry: _nullishCoalesce(this.aliasRegistry, () => ( _optionalChain([this, 'access', _11 => _11.resolverOptions, 'optionalAccess', _12 => _12.aliasRegistry])))
|
|
499
499
|
};
|
|
500
|
-
let resolved = await
|
|
500
|
+
let resolved = await _chunkH7W5LMP6cjs.resolveFromCatalogAttempts.call(void 0,
|
|
501
501
|
this.catalog,
|
|
502
|
-
|
|
502
|
+
_chunkH7W5LMP6cjs.buildCatalogResolveAttempts.call(void 0, modelInput, input.provider),
|
|
503
503
|
resolverOpts
|
|
504
504
|
);
|
|
505
|
-
if (
|
|
505
|
+
if (_chunkH7W5LMP6cjs.isLocalProviderResolution.call(void 0, resolved, input.provider)) {
|
|
506
506
|
return this.localProviderResult(modelInput, input, resolved);
|
|
507
507
|
}
|
|
508
508
|
let profileMatch = null;
|
|
509
509
|
const warnings = [];
|
|
510
510
|
if (!_optionalChain([resolved, 'optionalAccess', _13 => _13.found]) || !resolved.record) {
|
|
511
|
-
if (!
|
|
512
|
-
profileMatch = await
|
|
511
|
+
if (!_chunkH7W5LMP6cjs.isLocalProvider.call(void 0, input.provider)) {
|
|
512
|
+
profileMatch = await _chunkH7W5LMP6cjs.matchModelInAiProfiles.call(void 0, modelInput, input.provider, {
|
|
513
|
+
catalogLane: _optionalChain([this, 'access', _14 => _14.resolverOptions, 'optionalAccess', _15 => _15.catalogLane])
|
|
514
|
+
});
|
|
513
515
|
}
|
|
514
516
|
if (profileMatch) {
|
|
515
|
-
resolved = await
|
|
517
|
+
resolved = await _chunkH7W5LMP6cjs.resolveFromCatalogAttempts.call(void 0,
|
|
516
518
|
this.catalog,
|
|
517
519
|
mergeAttempts(
|
|
518
|
-
|
|
520
|
+
_chunkH7W5LMP6cjs.buildCatalogResolveAttempts.call(void 0,
|
|
519
521
|
profileMatch.canonicalModelId,
|
|
520
522
|
_nullishCoalesce(input.provider, () => ( profileMatch.provider))
|
|
521
523
|
),
|
|
522
|
-
|
|
524
|
+
_chunkH7W5LMP6cjs.buildCatalogResolveAttempts.call(void 0,
|
|
523
525
|
profileMatch.canonicalModelId,
|
|
524
526
|
profileMatch.provider
|
|
525
527
|
)
|
|
@@ -527,15 +529,15 @@ var CostCalculator = class {
|
|
|
527
529
|
resolverOpts
|
|
528
530
|
);
|
|
529
531
|
}
|
|
530
|
-
if (
|
|
532
|
+
if (_chunkH7W5LMP6cjs.isLocalProviderResolution.call(void 0, resolved, input.provider)) {
|
|
531
533
|
return this.localProviderResult(modelInput, input, resolved);
|
|
532
534
|
}
|
|
533
|
-
if ((!_optionalChain([resolved, 'optionalAccess',
|
|
534
|
-
const routedViaOpenRouter2 =
|
|
535
|
+
if ((!_optionalChain([resolved, 'optionalAccess', _16 => _16.found]) || !resolved.record) && _optionalChain([profileMatch, 'optionalAccess', _17 => _17.pricing])) {
|
|
536
|
+
const routedViaOpenRouter2 = _chunkH7W5LMP6cjs.resolveRoutedViaOpenRouter.call(void 0,
|
|
535
537
|
input.provider,
|
|
536
538
|
resolved,
|
|
537
539
|
profileMatch.canonicalModelId,
|
|
538
|
-
_optionalChain([resolverOpts, 'optionalAccess',
|
|
540
|
+
_optionalChain([resolverOpts, 'optionalAccess', _18 => _18.routingEnv])
|
|
539
541
|
);
|
|
540
542
|
const pricing2 = aiProfilesPricingToCatalogPricing(
|
|
541
543
|
profileMatch.pricing,
|
|
@@ -578,15 +580,15 @@ var CostCalculator = class {
|
|
|
578
580
|
);
|
|
579
581
|
}
|
|
580
582
|
}
|
|
581
|
-
if (!_optionalChain([resolved, 'optionalAccess',
|
|
583
|
+
if (!_optionalChain([resolved, 'optionalAccess', _19 => _19.found]) || !resolved.record) {
|
|
582
584
|
return this.unknownModelResult(modelInput, input, resolved);
|
|
583
585
|
}
|
|
584
586
|
const { record, modelId } = resolved;
|
|
585
|
-
const routedViaOpenRouter =
|
|
587
|
+
const routedViaOpenRouter = _chunkH7W5LMP6cjs.resolveRoutedViaOpenRouter.call(void 0,
|
|
586
588
|
input.provider,
|
|
587
589
|
resolved,
|
|
588
590
|
modelId,
|
|
589
|
-
_optionalChain([resolverOpts, 'optionalAccess',
|
|
591
|
+
_optionalChain([resolverOpts, 'optionalAccess', _20 => _20.routingEnv])
|
|
590
592
|
);
|
|
591
593
|
const pricing = record.pricing;
|
|
592
594
|
const { cost, breakdown } = computeCostFromPricing(
|
|
@@ -616,7 +618,7 @@ var CostCalculator = class {
|
|
|
616
618
|
const normalizedPriced = _chunkOZE336BLcjs.normalizeString.call(void 0, pricedModelId);
|
|
617
619
|
if (normalizedReceived === normalizedPriced) return [];
|
|
618
620
|
const stripped = _chunkOZE336BLcjs.stripModelVersionSuffix.call(void 0, received);
|
|
619
|
-
const viaResolver = _optionalChain([resolved, 'optionalAccess',
|
|
621
|
+
const viaResolver = _optionalChain([resolved, 'optionalAccess', _21 => _21.found]) === true && resolved.resolvedVia.some(
|
|
620
622
|
(s) => s === "version-suffix-strip" || s === "date-suffix-strip"
|
|
621
623
|
);
|
|
622
624
|
const pricedViaStrip = stripped !== null && _chunkOZE336BLcjs.normalizeString.call(void 0, stripped) === normalizedPriced;
|
|
@@ -651,7 +653,7 @@ var CostCalculator = class {
|
|
|
651
653
|
return this.finish(
|
|
652
654
|
{
|
|
653
655
|
cost: 0,
|
|
654
|
-
resolvedModelId: _optionalChain([resolved, 'optionalAccess',
|
|
656
|
+
resolvedModelId: _optionalChain([resolved, 'optionalAccess', _22 => _22.found]) ? resolved.modelId : modelInput,
|
|
655
657
|
routedViaOpenRouter: false,
|
|
656
658
|
isAuthoritative: false,
|
|
657
659
|
pricingSnapshot: emptyPricing(),
|
|
@@ -676,11 +678,11 @@ var CostCalculator = class {
|
|
|
676
678
|
{
|
|
677
679
|
cost: 0,
|
|
678
680
|
resolvedModelId: modelInput,
|
|
679
|
-
routedViaOpenRouter:
|
|
681
|
+
routedViaOpenRouter: _chunkH7W5LMP6cjs.resolveRoutedViaOpenRouter.call(void 0,
|
|
680
682
|
input.provider,
|
|
681
683
|
resolved,
|
|
682
684
|
modelInput,
|
|
683
|
-
_optionalChain([this, 'access',
|
|
685
|
+
_optionalChain([this, 'access', _23 => _23.resolverOptions, 'optionalAccess', _24 => _24.routingEnv])
|
|
684
686
|
),
|
|
685
687
|
isAuthoritative: false,
|
|
686
688
|
pricingSnapshot: emptyPricing(),
|
|
@@ -702,4 +704,4 @@ var CostCalculator = class {
|
|
|
702
704
|
|
|
703
705
|
|
|
704
706
|
exports.DEFAULT_OPENROUTER_MARKUP_RATE = DEFAULT_OPENROUTER_MARKUP_RATE; exports.toCostExtraction = toCostExtraction; exports.enrichCostResult = enrichCostResult; exports.MODEL_FIELD_PRIORITY = MODEL_FIELD_PRIORITY; exports.extractUsageInput = extractUsageInput; exports.resolveUsageModel = resolveUsageModel; exports.CostCalculator = CostCalculator;
|
|
705
|
-
//# sourceMappingURL=chunk-
|
|
707
|
+
//# sourceMappingURL=chunk-AGLZXZCH.cjs.map
|