@x12i/ai-tools 1.0.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +146 -204
  3. package/dist/AiModelsCatalogClient-B5FMI9gj.d.cts +58 -0
  4. package/dist/AiModelsCatalogClient-CPPNI6Ry.d.ts +58 -0
  5. package/dist/aliases/index.cjs +4 -3
  6. package/dist/aliases/index.cjs.map +1 -1
  7. package/dist/aliases/index.d.cts +3 -5
  8. package/dist/aliases/index.d.ts +3 -5
  9. package/dist/aliases/index.js +2 -2
  10. package/dist/catalog/index.cjs +18 -9
  11. package/dist/catalog/index.cjs.map +1 -1
  12. package/dist/catalog/index.d.cts +13 -100
  13. package/dist/catalog/index.d.ts +13 -100
  14. package/dist/catalog/index.js +31 -23
  15. package/dist/{chunk-AJEKEWWB.js → chunk-2PTCWPHV.js} +17 -3
  16. package/dist/chunk-2PTCWPHV.js.map +1 -0
  17. package/dist/chunk-56R4XA2S.js +1 -0
  18. package/dist/chunk-5GUKLOEK.cjs +1 -0
  19. package/dist/chunk-5GUKLOEK.cjs.map +1 -0
  20. package/dist/chunk-5XAAMBDO.cjs +1988 -0
  21. package/dist/chunk-5XAAMBDO.cjs.map +1 -0
  22. package/dist/chunk-6BQBKROR.js +95 -0
  23. package/dist/chunk-6BQBKROR.js.map +1 -0
  24. package/dist/chunk-AB5GNXJ4.js +46 -0
  25. package/dist/chunk-AB5GNXJ4.js.map +1 -0
  26. package/dist/{chunk-O2A6OVEH.js → chunk-ANVONYJF.js} +2 -2
  27. package/dist/{chunk-O2A6OVEH.js.map → chunk-ANVONYJF.js.map} +1 -1
  28. package/dist/chunk-B3V2EHRY.js +225 -0
  29. package/dist/chunk-B3V2EHRY.js.map +1 -0
  30. package/dist/{chunk-QWAX7VQO.cjs → chunk-BAHBDADJ.cjs} +11 -11
  31. package/dist/{chunk-QWAX7VQO.cjs.map → chunk-BAHBDADJ.cjs.map} +1 -1
  32. package/dist/{chunk-TF4L2NEC.cjs → chunk-DXZOL3VN.cjs} +62 -313
  33. package/dist/chunk-DXZOL3VN.cjs.map +1 -0
  34. package/dist/chunk-EDMCKHO6.cjs +225 -0
  35. package/dist/chunk-EDMCKHO6.cjs.map +1 -0
  36. package/dist/{chunk-DJ5SWJDY.js → chunk-EYHMQVAL.js} +48 -299
  37. package/dist/chunk-EYHMQVAL.js.map +1 -0
  38. package/dist/chunk-GS7T56RP.cjs +8 -0
  39. package/dist/chunk-GS7T56RP.cjs.map +1 -0
  40. package/dist/chunk-NF2SKQR7.cjs +973 -0
  41. package/dist/chunk-NF2SKQR7.cjs.map +1 -0
  42. package/dist/chunk-OPN6BGNH.js +1985 -0
  43. package/dist/chunk-OPN6BGNH.js.map +1 -0
  44. package/dist/{chunk-7Q742NI3.cjs → chunk-PADNCGZB.cjs} +17 -3
  45. package/dist/chunk-PADNCGZB.cjs.map +1 -0
  46. package/dist/chunk-PRCICORG.cjs +95 -0
  47. package/dist/chunk-PRCICORG.cjs.map +1 -0
  48. package/dist/{chunk-6QGDZTGH.js → chunk-SIH4GPV4.js} +4 -29
  49. package/dist/chunk-SIH4GPV4.js.map +1 -0
  50. package/dist/chunk-U2YDDUVP.js +970 -0
  51. package/dist/chunk-U2YDDUVP.js.map +1 -0
  52. package/dist/{chunk-4NAY6HRP.js → chunk-VJHLO2R3.js} +7 -58
  53. package/dist/chunk-VJHLO2R3.js.map +1 -0
  54. package/dist/chunk-XAWBTX3N.cjs +46 -0
  55. package/dist/chunk-XAWBTX3N.cjs.map +1 -0
  56. package/dist/{chunk-AV6OE2YQ.cjs → chunk-XOKUDUUI.cjs} +14 -39
  57. package/dist/chunk-XOKUDUUI.cjs.map +1 -0
  58. package/dist/chunk-YQDSN6R6.cjs +86 -0
  59. package/dist/chunk-YQDSN6R6.cjs.map +1 -0
  60. package/dist/cli/index.cjs +59 -201
  61. package/dist/cli/index.cjs.map +1 -1
  62. package/dist/cli/index.js +53 -198
  63. package/dist/cli/index.js.map +1 -1
  64. package/dist/cost/index.cjs +19 -3
  65. package/dist/cost/index.cjs.map +1 -1
  66. package/dist/cost/index.d.cts +10 -50
  67. package/dist/cost/index.d.ts +10 -50
  68. package/dist/cost/index.js +18 -3
  69. package/dist/index.cjs +24 -16
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.d.cts +13 -13
  72. package/dist/index.d.ts +13 -13
  73. package/dist/index.js +44 -37
  74. package/dist/modelCache-BzRn6t_C.d.ts +113 -0
  75. package/dist/modelCache-CJftI-Ko.d.cts +113 -0
  76. package/dist/{modelNameResolver-DqFt7g6W.d.ts → modelNameResolver-5XkBMctP.d.ts} +2 -6
  77. package/dist/{modelNameResolver-D9V_GfUK.d.cts → modelNameResolver-C5CSTGFF.d.cts} +2 -6
  78. package/dist/models/index.cjs +9 -6
  79. package/dist/models/index.cjs.map +1 -1
  80. package/dist/models/index.d.cts +9 -31
  81. package/dist/models/index.d.ts +9 -31
  82. package/dist/models/index.js +9 -7
  83. package/dist/resolveUsageModel-BFwf80Hz.d.ts +140 -0
  84. package/dist/resolveUsageModel-C_YmGR1M.d.cts +140 -0
  85. package/dist/sync/index.cjs +7 -9
  86. package/dist/sync/index.cjs.map +1 -1
  87. package/dist/sync/index.d.cts +3 -8
  88. package/dist/sync/index.d.ts +3 -8
  89. package/dist/sync/index.js +8 -11
  90. package/dist/toolbox/index.cjs +1 -0
  91. package/dist/toolbox/index.cjs.map +1 -1
  92. package/dist/types-BrzJWsTU.d.cts +277 -0
  93. package/dist/types-BrzJWsTU.d.ts +277 -0
  94. package/package.json +9 -20
  95. package/src/data/models-catalog.json +670 -0
  96. package/src/data/openrouter-models-catalog.json +857 -0
  97. package/dist/AiModelsCatalogClient-4RF5BCDL.cjs +0 -9
  98. package/dist/AiModelsCatalogClient-4RF5BCDL.cjs.map +0 -1
  99. package/dist/AiModelsCatalogClient-CNeqFiFs.d.cts +0 -30
  100. package/dist/AiModelsCatalogClient-NUF3CBLW.js +0 -9
  101. package/dist/AiModelsCatalogClient-nwFoEaqL.d.ts +0 -30
  102. package/dist/catalox/index.cjs +0 -21
  103. package/dist/catalox/index.cjs.map +0 -1
  104. package/dist/catalox/index.d.cts +0 -11
  105. package/dist/catalox/index.d.ts +0 -11
  106. package/dist/catalox/index.js +0 -21
  107. package/dist/catalox/index.js.map +0 -1
  108. package/dist/chunk-4NAY6HRP.js.map +0 -1
  109. package/dist/chunk-6QGDZTGH.js.map +0 -1
  110. package/dist/chunk-7Q742NI3.cjs.map +0 -1
  111. package/dist/chunk-AJEKEWWB.js.map +0 -1
  112. package/dist/chunk-AV6OE2YQ.cjs.map +0 -1
  113. package/dist/chunk-C3H7RTFR.cjs +0 -1
  114. package/dist/chunk-C3H7RTFR.cjs.map +0 -1
  115. package/dist/chunk-DJ5SWJDY.js.map +0 -1
  116. package/dist/chunk-DKHGWHXP.cjs +0 -169
  117. package/dist/chunk-DKHGWHXP.cjs.map +0 -1
  118. package/dist/chunk-F2F4UEFD.cjs +0 -75
  119. package/dist/chunk-F2F4UEFD.cjs.map +0 -1
  120. package/dist/chunk-FGP3QXWL.cjs +0 -163
  121. package/dist/chunk-FGP3QXWL.cjs.map +0 -1
  122. package/dist/chunk-G2G4KSC5.js +0 -30
  123. package/dist/chunk-G2G4KSC5.js.map +0 -1
  124. package/dist/chunk-HN6UAQAE.cjs +0 -83
  125. package/dist/chunk-HN6UAQAE.cjs.map +0 -1
  126. package/dist/chunk-HS74X2OJ.cjs +0 -172
  127. package/dist/chunk-HS74X2OJ.cjs.map +0 -1
  128. package/dist/chunk-HYGXZY25.js +0 -163
  129. package/dist/chunk-HYGXZY25.js.map +0 -1
  130. package/dist/chunk-KQOALKKX.js +0 -75
  131. package/dist/chunk-KQOALKKX.js.map +0 -1
  132. package/dist/chunk-LYOU7CA2.cjs +0 -30
  133. package/dist/chunk-LYOU7CA2.cjs.map +0 -1
  134. package/dist/chunk-M5TMA73F.js +0 -1
  135. package/dist/chunk-M5TMA73F.js.map +0 -1
  136. package/dist/chunk-MX3AMQFC.js +0 -172
  137. package/dist/chunk-MX3AMQFC.js.map +0 -1
  138. package/dist/chunk-QCRLKVB3.cjs +0 -137
  139. package/dist/chunk-QCRLKVB3.cjs.map +0 -1
  140. package/dist/chunk-TF4L2NEC.cjs.map +0 -1
  141. package/dist/chunk-VRFVF5RH.js +0 -169
  142. package/dist/chunk-VRFVF5RH.js.map +0 -1
  143. package/dist/chunk-YHO57D2V.js +0 -83
  144. package/dist/chunk-YHO57D2V.js.map +0 -1
  145. package/dist/syncAiModelsCatalog-CnXRLm2c.d.cts +0 -32
  146. package/dist/syncAiModelsCatalog-DpkN_w7S.d.ts +0 -32
  147. package/dist/types-BYXnCvKx.d.cts +0 -137
  148. package/dist/types-BYXnCvKx.d.ts +0 -137
  149. package/dist/types-CX6QFNNy.d.cts +0 -144
  150. package/dist/types-CuiPDcVs.d.ts +0 -144
  151. package/dist/upsertAiModelRecord-C831wOIF.d.ts +0 -35
  152. package/dist/upsertAiModelRecord-CjY-sny0.d.cts +0 -35
  153. /package/dist/{AiModelsCatalogClient-NUF3CBLW.js.map → chunk-56R4XA2S.js.map} +0 -0
@@ -0,0 +1,973 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+
8
+ var _chunkEDMCKHO6cjs = require('./chunk-EDMCKHO6.cjs');
9
+
10
+
11
+ var _chunkPADNCGZBcjs = require('./chunk-PADNCGZB.cjs');
12
+
13
+
14
+ var _chunkGS7T56RPcjs = require('./chunk-GS7T56RP.cjs');
15
+
16
+ // src/cost/constants.ts
17
+ var DEFAULT_OPENROUTER_MARKUP_RATE = 0.05;
18
+ var PROFILE_TIERED_CONTEXT_THRESHOLD = 2e5;
19
+
20
+ // src/cost/enrichCostResult.ts
21
+ function toCostExtraction(provenance) {
22
+ return {
23
+ model: { field: provenance.model.field, path: provenance.model.path },
24
+ tokens: {
25
+ source: provenance.tokens.source,
26
+ path: provenance.tokens.path,
27
+ estimated: provenance.tokens.estimated
28
+ },
29
+ ...provenance.modelUsed ? {
30
+ modelUsed: {
31
+ field: provenance.modelUsed.field,
32
+ path: provenance.modelUsed.path
33
+ }
34
+ } : {},
35
+ ...provenance.provider ? {
36
+ provider: {
37
+ field: provenance.provider.field,
38
+ path: provenance.provider.path
39
+ }
40
+ } : {}
41
+ };
42
+ }
43
+ function enrichCostResult(result, input, extraction) {
44
+ const receivedModelId = _nullishCoalesce(_nullishCoalesce(input.usedModel, () => ( input.modelUsed)), () => ( input.model));
45
+ return {
46
+ ...result,
47
+ provider: input.provider,
48
+ usage: { ...input.tokens },
49
+ ...receivedModelId ? { usedModel: receivedModelId } : {},
50
+ ...input.model && input.model !== receivedModelId ? { model: input.model } : {},
51
+ ...extraction ? { extraction } : {}
52
+ };
53
+ }
54
+
55
+ // src/cost/extractUsageInput.ts
56
+ var MODEL_FIELD_PRIORITY = [
57
+ { key: "usedModel", score: 1e3 },
58
+ { key: "modelUsed", score: 990 },
59
+ { key: "resolvedModel", score: 980 },
60
+ { key: "model", score: 500 },
61
+ { key: "xynthesisModel", score: 120 },
62
+ { key: "skillModel", score: 110 }
63
+ ];
64
+ var MODEL_PATH_BONUS = [
65
+ { pattern: /(^|\.)response(\.|$)/i, bonus: 40 },
66
+ { pattern: /(^|\.)outer\.input(\.|$)/i, bonus: 35 },
67
+ { pattern: /(^|\.)config(?!\.rawConfig)(\.|$)/i, bonus: 30 },
68
+ { pattern: /(^|\.)outer\.input\.config(\.|$)/i, bonus: 28 },
69
+ { pattern: /(^|\.)usage(\.|$)/i, bonus: 15 },
70
+ { pattern: /(^|\.)rawConfig(\.|$)/i, bonus: -40 },
71
+ { pattern: /workingMemory/i, bonus: -50 },
72
+ { pattern: /requestExample/i, bonus: -80 },
73
+ { pattern: /graphsStudio/i, bonus: -80 }
74
+ ];
75
+ var PROVIDER_FIELD_PRIORITY = [
76
+ { key: "provider", score: 500 },
77
+ { key: "providerId", score: 480 }
78
+ ];
79
+ var PROVIDER_PATH_BONUS = [
80
+ { pattern: /(^|\.)config(?!\.rawConfig)(\.|$)/i, bonus: 30 },
81
+ { pattern: /(^|\.)outer\.input(\.|$)/i, bonus: 20 },
82
+ { pattern: /(^|\.)rawConfig(\.|$)/i, bonus: -20 }
83
+ ];
84
+ var PROMPT_TOKEN_KEYS = /* @__PURE__ */ new Set([
85
+ "prompt",
86
+ "prompt_tokens",
87
+ "promptTokens",
88
+ "input_tokens",
89
+ "inputTokens",
90
+ "estimatedInputTokens",
91
+ "input"
92
+ ]);
93
+ var COMPLETION_TOKEN_KEYS = /* @__PURE__ */ new Set([
94
+ "completion",
95
+ "completion_tokens",
96
+ "completionTokens",
97
+ "output_tokens",
98
+ "outputTokens",
99
+ "estimatedOutputTokens",
100
+ "output"
101
+ ]);
102
+ var OPTIONAL_TOKEN_KEYS = {
103
+ total: "total",
104
+ total_tokens: "total",
105
+ totalTokens: "total",
106
+ cached: "cached",
107
+ cached_tokens: "cached",
108
+ cache_read_tokens: "cached",
109
+ cacheReadTokens: "cached",
110
+ cacheWrite: "cacheWrite",
111
+ cache_write_tokens: "cacheWrite",
112
+ cacheWriteTokens: "cacheWrite",
113
+ reasoning: "reasoning",
114
+ reasoning_tokens: "reasoning",
115
+ reasoningTokens: "reasoning",
116
+ audio: "audio",
117
+ audio_tokens: "audio",
118
+ image: "image",
119
+ image_tokens: "image"
120
+ };
121
+ function isPlainObject(v) {
122
+ return v !== null && typeof v === "object" && !Array.isArray(v);
123
+ }
124
+ function modelKeyScore(key) {
125
+ return _nullishCoalesce(_optionalChain([MODEL_FIELD_PRIORITY, 'access', _ => _.find, 'call', _2 => _2((e) => e.key === key), 'optionalAccess', _3 => _3.score]), () => ( 0));
126
+ }
127
+ function providerKeyScore(key) {
128
+ return _nullishCoalesce(_optionalChain([PROVIDER_FIELD_PRIORITY, 'access', _4 => _4.find, 'call', _5 => _5((e) => e.key === key), 'optionalAccess', _6 => _6.score]), () => ( 0));
129
+ }
130
+ function pathBonus(path, rules) {
131
+ let bonus = 0;
132
+ for (const { pattern, bonus: b } of rules) {
133
+ if (pattern.test(path)) bonus += b;
134
+ }
135
+ return bonus;
136
+ }
137
+ function normalizeModelValue(v) {
138
+ if (typeof v !== "string") return void 0;
139
+ const t = v.trim();
140
+ return t.length > 0 ? t : void 0;
141
+ }
142
+ function normalizeProviderValue(v) {
143
+ if (typeof v !== "string") return void 0;
144
+ const t = v.trim().toLowerCase();
145
+ if (!t || t === "null") return void 0;
146
+ return t;
147
+ }
148
+ function collectModelCandidates(node, path, out, depth, maxDepth) {
149
+ if (depth > maxDepth || node === null || node === void 0) return;
150
+ if (isPlainObject(node)) {
151
+ for (const [key, value] of Object.entries(node)) {
152
+ const childPath = path ? `${path}.${key}` : key;
153
+ const base = modelKeyScore(key);
154
+ if (base > 0) {
155
+ const model = normalizeModelValue(value);
156
+ if (model) {
157
+ out.push({
158
+ field: key,
159
+ path: childPath,
160
+ value: model,
161
+ score: base + pathBonus(childPath, MODEL_PATH_BONUS)
162
+ });
163
+ }
164
+ }
165
+ collectModelCandidates(value, childPath, out, depth + 1, maxDepth);
166
+ }
167
+ return;
168
+ }
169
+ if (Array.isArray(node)) {
170
+ for (let i = 0; i < node.length; i++) {
171
+ collectModelCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);
172
+ }
173
+ }
174
+ }
175
+ function collectProviderCandidates(node, path, out, depth, maxDepth) {
176
+ if (depth > maxDepth || node === null || node === void 0) return;
177
+ if (isPlainObject(node)) {
178
+ for (const [key, value] of Object.entries(node)) {
179
+ const childPath = path ? `${path}.${key}` : key;
180
+ const base = providerKeyScore(key);
181
+ if (base > 0) {
182
+ const provider = normalizeProviderValue(value);
183
+ if (provider) {
184
+ out.push({
185
+ field: key,
186
+ path: childPath,
187
+ value: provider,
188
+ score: base + pathBonus(childPath, PROVIDER_PATH_BONUS)
189
+ });
190
+ }
191
+ }
192
+ collectProviderCandidates(value, childPath, out, depth + 1, maxDepth);
193
+ }
194
+ return;
195
+ }
196
+ if (Array.isArray(node)) {
197
+ for (let i = 0; i < node.length; i++) {
198
+ collectProviderCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);
199
+ }
200
+ }
201
+ }
202
+ function readNumber(obj, keys) {
203
+ for (const [k, v] of Object.entries(obj)) {
204
+ if (!keys.has(k)) continue;
205
+ if (typeof v === "number" && Number.isFinite(v) && v >= 0) return v;
206
+ }
207
+ return void 0;
208
+ }
209
+ function readOptionalNumbers(obj) {
210
+ const extra = {};
211
+ for (const [k, v] of Object.entries(obj)) {
212
+ const target = OPTIONAL_TOKEN_KEYS[k];
213
+ if (!target || typeof v !== "number" || !Number.isFinite(v) || v < 0) continue;
214
+ extra[target] = v;
215
+ }
216
+ return extra;
217
+ }
218
+ function looksLikeUsageObject(obj) {
219
+ const hasPrompt = readNumber(obj, PROMPT_TOKEN_KEYS) !== void 0;
220
+ const hasCompletion = readNumber(obj, COMPLETION_TOKEN_KEYS) !== void 0;
221
+ return hasPrompt && hasCompletion;
222
+ }
223
+ function looksLikeDiagnosticsObject(obj) {
224
+ return typeof obj.estimatedInputTokens === "number" && typeof obj.estimatedOutputTokens === "number";
225
+ }
226
+ function tokensFromObject(obj, source, path, estimated, score) {
227
+ const prompt = readNumber(obj, PROMPT_TOKEN_KEYS);
228
+ const completion = readNumber(obj, COMPLETION_TOKEN_KEYS);
229
+ if (prompt === void 0 || completion === void 0) return null;
230
+ const extra = readOptionalNumbers(obj);
231
+ const total = typeof extra.total === "number" ? extra.total : prompt + completion;
232
+ return {
233
+ tokens: {
234
+ prompt,
235
+ completion,
236
+ total,
237
+ ...extra
238
+ },
239
+ provenance: { source, path, estimated },
240
+ score
241
+ };
242
+ }
243
+ function collectTokenCandidates(node, path, out, depth, maxDepth) {
244
+ if (depth > maxDepth || node === null || node === void 0) return;
245
+ if (isPlainObject(node)) {
246
+ if (path.endsWith("diagnostics") || looksLikeDiagnosticsObject(node)) {
247
+ const cand = tokensFromObject(node, "diagnostics", path, true, 200);
248
+ if (cand) out.push(cand);
249
+ } else if (path.endsWith("usage") || path.endsWith("tokens") || looksLikeUsageObject(node)) {
250
+ const source = path.endsWith("tokens") ? "tokens" : "usage";
251
+ const estimated = false;
252
+ const score = path.endsWith("usage") ? 500 : 450;
253
+ const cand = tokensFromObject(node, source, path, estimated, score);
254
+ if (cand) out.push(cand);
255
+ }
256
+ for (const [key, value] of Object.entries(node)) {
257
+ const childPath = path ? `${path}.${key}` : key;
258
+ if (key === "usage" || key === "tokens" || key === "diagnostics") {
259
+ if (isPlainObject(value)) {
260
+ collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);
261
+ }
262
+ } else {
263
+ collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);
264
+ }
265
+ }
266
+ return;
267
+ }
268
+ if (Array.isArray(node)) {
269
+ for (let i = 0; i < node.length; i++) {
270
+ collectTokenCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);
271
+ }
272
+ }
273
+ }
274
+ function pickBestModel(candidates) {
275
+ if (candidates.length === 0) return null;
276
+ return [...candidates].sort((a, b) => b.score - a.score)[0];
277
+ }
278
+ function pickBestProvider(candidates) {
279
+ if (candidates.length === 0) return null;
280
+ return [...candidates].sort((a, b) => b.score - a.score)[0];
281
+ }
282
+ function pickBestTokens(candidates) {
283
+ if (candidates.length === 0) return null;
284
+ return [...candidates].sort((a, b) => b.score - a.score)[0];
285
+ }
286
+ function inferProviderFromModel(model, fallback) {
287
+ const slash = model.indexOf("/");
288
+ if (slash > 0) {
289
+ const prefix = model.slice(0, slash).toLowerCase();
290
+ if (prefix !== "openrouter") return prefix;
291
+ }
292
+ return fallback;
293
+ }
294
+ function extractUsageInput(record, options = {}) {
295
+ const defaultProvider = _nullishCoalesce(options.defaultProvider, () => ( "openrouter"));
296
+ const maxDepth = 24;
297
+ const modelCandidates = [];
298
+ const providerCandidates = [];
299
+ const tokenCandidates = [];
300
+ collectModelCandidates(record, "", modelCandidates, 0, maxDepth);
301
+ collectProviderCandidates(record, "", providerCandidates, 0, maxDepth);
302
+ collectTokenCandidates(record, "", tokenCandidates, 0, maxDepth);
303
+ const bestModel = pickBestModel(modelCandidates);
304
+ if (!bestModel) {
305
+ throw new Error(
306
+ "[ai-tools] Could not extract a model from the record (looked for usedModel, modelUsed, model, \u2026)."
307
+ );
308
+ }
309
+ const runtimeFields = /* @__PURE__ */ new Set(["usedModel", "modelUsed", "resolvedModel"]);
310
+ const isRuntimeModel = runtimeFields.has(bestModel.field);
311
+ const requestModel = modelCandidates.find(
312
+ (c) => c.field === "model" && c.path !== bestModel.path
313
+ );
314
+ const bestProvider = pickBestProvider(providerCandidates);
315
+ const provider = _nullishCoalesce(_optionalChain([bestProvider, 'optionalAccess', _7 => _7.value]), () => ( inferProviderFromModel(bestModel.value, defaultProvider)));
316
+ const bestTokens = pickBestTokens(tokenCandidates);
317
+ if (!bestTokens) {
318
+ throw new Error(
319
+ "[ai-tools] Could not extract token usage from the record (usage, tokens, or metadata.diagnostics)."
320
+ );
321
+ }
322
+ const input = {
323
+ tokens: bestTokens.tokens,
324
+ provider,
325
+ ...isRuntimeModel ? { modelUsed: bestModel.value, model: _optionalChain([requestModel, 'optionalAccess', _8 => _8.value]) } : { model: bestModel.value }
326
+ };
327
+ const provenance = {
328
+ model: {
329
+ field: bestModel.field,
330
+ path: bestModel.path,
331
+ score: bestModel.score
332
+ },
333
+ tokens: bestTokens.provenance
334
+ };
335
+ if (bestProvider) {
336
+ provenance.provider = {
337
+ field: bestProvider.field,
338
+ path: bestProvider.path,
339
+ score: bestProvider.score
340
+ };
341
+ }
342
+ if (isRuntimeModel && requestModel) {
343
+ provenance.modelUsed = {
344
+ field: bestModel.field,
345
+ path: bestModel.path,
346
+ score: bestModel.score
347
+ };
348
+ } else if (input.modelUsed) {
349
+ provenance.modelUsed = provenance.model;
350
+ }
351
+ return { input, provenance };
352
+ }
353
+
354
+ // src/cost/resolveUsageModel.ts
355
+ function resolveUsageModel(input) {
356
+ const value = _nullishCoalesce(_nullishCoalesce(input.usedModel, () => ( input.modelUsed)), () => ( input.model));
357
+ if (!_optionalChain([value, 'optionalAccess', _9 => _9.trim, 'call', _10 => _10()])) {
358
+ throw new Error(
359
+ "[ai-tools] Cost calculation requires `usedModel`, `modelUsed`, or `model` on usage input."
360
+ );
361
+ }
362
+ return value.trim();
363
+ }
364
+
365
+ // src/cost/aiProfilesMatch.ts
366
+ var _module = require('module');
367
+ var _path = require('path');
368
+ var _aiprofiles = require('@x12i/ai-profiles');
369
+
370
+ // src/cost/costModelResolution.ts
371
+ function isOpenRouterProvider(provider) {
372
+ return _chunkEDMCKHO6cjs.normalizeProvider.call(void 0, provider) === "openrouter";
373
+ }
374
+ function isLocalProvider(provider) {
375
+ const p = _nullishCoalesce(_chunkEDMCKHO6cjs.normalizeProvider.call(void 0, provider), () => ( _chunkEDMCKHO6cjs.normalizeString.call(void 0, _nullishCoalesce(provider, () => ( "")))));
376
+ return _chunkEDMCKHO6cjs.LOCAL_PROVIDERS.has(p);
377
+ }
378
+ function isLocalProviderResolution(resolved, inputProvider) {
379
+ if (!_optionalChain([resolved, 'optionalAccess', _11 => _11.found]) || resolved.record) return false;
380
+ if (resolved.resolvedVia.includes("local-provider-passthrough")) return true;
381
+ return isLocalProvider(inputProvider);
382
+ }
383
+ function underlyingProviderFromModel(model, providerHint) {
384
+ const normalized = _chunkEDMCKHO6cjs.normalizeString.call(void 0, model);
385
+ if (normalized.includes("/")) {
386
+ const prefix = normalized.split("/")[0];
387
+ if (!isOpenRouterProvider(prefix)) return prefix;
388
+ }
389
+ if (providerHint && !isOpenRouterProvider(providerHint)) {
390
+ return _chunkEDMCKHO6cjs.normalizeProvider.call(void 0, providerHint);
391
+ }
392
+ return void 0;
393
+ }
394
+ function providerHintForProfiles(model, provider) {
395
+ if (isOpenRouterProvider(provider)) {
396
+ return underlyingProviderFromModel(model, provider);
397
+ }
398
+ return _chunkEDMCKHO6cjs.normalizeProvider.call(void 0, provider);
399
+ }
400
+ function buildCatalogResolveAttempts(model, provider) {
401
+ const attempts = [];
402
+ const seen = /* @__PURE__ */ new Set();
403
+ const add = (m, p) => {
404
+ const key = `${_nullishCoalesce(p, () => ( ""))}\0${_chunkEDMCKHO6cjs.normalizeString.call(void 0, m)}`;
405
+ if (seen.has(key)) return;
406
+ seen.add(key);
407
+ attempts.push({ model: m, provider: p });
408
+ };
409
+ add(model, provider);
410
+ const underlying = underlyingProviderFromModel(model, provider);
411
+ if (provider) add(model, void 0);
412
+ if (underlying) add(model, underlying);
413
+ if (!isOpenRouterProvider(provider)) {
414
+ add(model, "openrouter");
415
+ }
416
+ return attempts;
417
+ }
418
+ async function resolveFromCatalogAttempts(catalog, attempts, options) {
419
+ let last = null;
420
+ let localPassthrough = null;
421
+ for (const attempt of attempts) {
422
+ const result = await catalog.resolveModel(attempt, options);
423
+ last = result;
424
+ if (result.found && result.record) return result;
425
+ if (result.found && !result.record && isLocalProviderResolution(result, attempt.provider)) {
426
+ localPassthrough = result;
427
+ }
428
+ }
429
+ return _nullishCoalesce(localPassthrough, () => ( last));
430
+ }
431
+ function resolveRoutedViaOpenRouter(inputProvider, resolved, modelId, routingEnv) {
432
+ const env = _nullishCoalesce(routingEnv, () => ( _chunkEDMCKHO6cjs.loadOpenRouterRoutingEnv.call(void 0, )));
433
+ if (isOpenRouterProvider(inputProvider)) return true;
434
+ if (_optionalChain([resolved, 'optionalAccess', _12 => _12.found])) {
435
+ return resolved.routedViaOpenRouter;
436
+ }
437
+ const vendor = underlyingProviderFromModel(
438
+ _nullishCoalesce(_nullishCoalesce(modelId, () => ( (_optionalChain([resolved, 'optionalAccess', _13 => _13.found]) ? resolved.modelId : ""))), () => ( "")),
439
+ inputProvider
440
+ );
441
+ if (vendor && _chunkEDMCKHO6cjs.shouldDefaultRouteViaOpenRouter.call(void 0, vendor, env)) {
442
+ return true;
443
+ }
444
+ return false;
445
+ }
446
+
447
+ // src/cost/aiProfilesMatch.ts
448
+ var require2 = _module.createRequire.call(void 0, _chunkGS7T56RPcjs.importMetaUrl);
449
+ function loadProfilesRegistry() {
450
+ const entry = _path.dirname.call(void 0, require2.resolve("@x12i/ai-profiles"));
451
+ const loader = require2(_path.join.call(void 0, entry, "loader/loadAIProfilesRegistry.js"));
452
+ return loader.loadAIProfilesRegistry({ source: "auto" });
453
+ }
454
+ function profileKey(value) {
455
+ return value.trim().toLowerCase();
456
+ }
457
+ function canonicalModelId(provider, modelId) {
458
+ const normalized = _chunkEDMCKHO6cjs.normalizeString.call(void 0, modelId);
459
+ if (normalized.includes("/")) return normalized;
460
+ const p = _nullishCoalesce(_chunkEDMCKHO6cjs.normalizeProvider.call(void 0, provider), () => ( _chunkEDMCKHO6cjs.normalizeString.call(void 0, provider)));
461
+ return `${p}/${normalized}`;
462
+ }
463
+ var cachedIndex = null;
464
+ function indexRegistry(registry) {
465
+ const byKey = /* @__PURE__ */ new Map();
466
+ const add = (key, entry) => {
467
+ const k = profileKey(key);
468
+ if (!k) return;
469
+ const list = _nullishCoalesce(byKey.get(k), () => ( []));
470
+ if (list.some(
471
+ (e) => e.canonicalModelId === entry.canonicalModelId && e.choice === entry.choice && e.profile === entry.profile
472
+ )) {
473
+ return;
474
+ }
475
+ list.push(entry);
476
+ byKey.set(k, list);
477
+ };
478
+ for (const shortcutKey of Object.keys(registry.shortcuts)) {
479
+ const shortcut = registry.shortcuts[shortcutKey];
480
+ const profile = registry.profiles[shortcut.profile];
481
+ if (!profile) continue;
482
+ const choiceKey = _nullishCoalesce(shortcut.choice, () => ( profile.defaultChoice));
483
+ const choice = profile.choices[choiceKey];
484
+ if (!choice) continue;
485
+ const entry = choiceEntry(choice, profile.profile, choiceKey, "shortcut");
486
+ add(shortcutKey, entry);
487
+ }
488
+ for (const profile of Object.values(registry.profiles)) {
489
+ for (const [choiceKey, choice] of Object.entries(profile.choices)) {
490
+ const entry = choiceEntry(choice, profile.profile, choiceKey, "model-id");
491
+ add(choice.modelId, entry);
492
+ add(canonicalModelId(choice.provider, choice.modelId), entry);
493
+ }
494
+ const defaultChoice = profile.choices[profile.defaultChoice];
495
+ if (defaultChoice) {
496
+ add(
497
+ profile.profile,
498
+ choiceEntry(defaultChoice, profile.profile, profile.defaultChoice, "profile")
499
+ );
500
+ }
501
+ for (const alias of _nullishCoalesce(profile.aliases, () => ( []))) {
502
+ if (defaultChoice) {
503
+ add(
504
+ alias,
505
+ choiceEntry(
506
+ defaultChoice,
507
+ profile.profile,
508
+ profile.defaultChoice,
509
+ "profile-alias"
510
+ )
511
+ );
512
+ }
513
+ }
514
+ }
515
+ return byKey;
516
+ }
517
+ function choiceEntry(choice, profile, choiceKey, matchedVia) {
518
+ const canonical = canonicalModelId(choice.provider, choice.modelId);
519
+ return {
520
+ provider: _nullishCoalesce(_chunkEDMCKHO6cjs.normalizeProvider.call(void 0, choice.provider), () => ( choice.provider)),
521
+ modelId: _chunkEDMCKHO6cjs.normalizeString.call(void 0, choice.modelId),
522
+ canonicalModelId: canonical,
523
+ pricing: choice.pricing,
524
+ matchedVia,
525
+ profile,
526
+ choice: choiceKey
527
+ };
528
+ }
529
+ async function getProfileIndex() {
530
+ const registry = await loadProfilesRegistry();
531
+ const cacheKey = `${registry.version}:${_nullishCoalesce(registry.generatedAt, () => ( ""))}:${registry.source}`;
532
+ if (_optionalChain([cachedIndex, 'optionalAccess', _14 => _14.cacheKey]) === cacheKey) {
533
+ return cachedIndex.byKey;
534
+ }
535
+ const byKey = indexRegistry(registry);
536
+ cachedIndex = { cacheKey, byKey };
537
+ return byKey;
538
+ }
539
+ function scoreCandidate(entry, model, providerHint) {
540
+ const normalized = _chunkEDMCKHO6cjs.normalizeString.call(void 0, model);
541
+ let score = 0;
542
+ if (normalized === entry.canonicalModelId) score += 100;
543
+ if (normalized === entry.modelId) score += 80;
544
+ if (providerHint && entry.provider === providerHint) score += 50;
545
+ if (entry.matchedVia === "model-id") score += 10;
546
+ if (entry.matchedVia === "shortcut") score += 5;
547
+ if (entry.matchedVia === "profile") score += 3;
548
+ if (entry.pricing) score += 2;
549
+ return score;
550
+ }
551
+ function pickBest(candidates, model, providerHint) {
552
+ if (candidates.length === 0) return null;
553
+ if (candidates.length === 1) return candidates[0];
554
+ let best = candidates[0];
555
+ let bestScore = scoreCandidate(best, model, providerHint);
556
+ for (let i = 1; i < candidates.length; i++) {
557
+ const c = candidates[i];
558
+ const s = scoreCandidate(c, model, providerHint);
559
+ if (s > bestScore) {
560
+ best = c;
561
+ bestScore = s;
562
+ }
563
+ }
564
+ return best;
565
+ }
566
+ function fromIndexed(entry) {
567
+ return {
568
+ provider: entry.provider,
569
+ modelId: entry.modelId,
570
+ canonicalModelId: entry.canonicalModelId,
571
+ pricing: entry.pricing,
572
+ matchedVia: entry.matchedVia,
573
+ profile: entry.profile,
574
+ choice: entry.choice
575
+ };
576
+ }
577
+ function lookupInIndex(index, model, provider) {
578
+ const providerHint = provider ? _chunkEDMCKHO6cjs.normalizeProvider.call(void 0, provider) : void 0;
579
+ const keys = [
580
+ profileKey(model),
581
+ profileKey(_chunkEDMCKHO6cjs.normalizeString.call(void 0, model))
582
+ ];
583
+ if (providerHint) {
584
+ keys.push(profileKey(canonicalModelId(providerHint, model)));
585
+ }
586
+ const pooled = [];
587
+ for (const key of keys) {
588
+ const hits = index.get(key);
589
+ if (hits) pooled.push(...hits);
590
+ }
591
+ const bare = _chunkEDMCKHO6cjs.normalizeString.call(void 0, model);
592
+ if (!bare.includes("/")) {
593
+ for (const list of index.values()) {
594
+ for (const entry of list) {
595
+ if (entry.modelId === bare) pooled.push(entry);
596
+ }
597
+ }
598
+ }
599
+ const unique = /* @__PURE__ */ new Map();
600
+ for (const e of pooled) {
601
+ unique.set(`${e.profile}:${e.choice}:${e.canonicalModelId}`, e);
602
+ }
603
+ const best = pickBest([...unique.values()], model, providerHint);
604
+ return best ? fromIndexed(best) : null;
605
+ }
606
+ async function matchModelInAiProfiles(model, provider) {
607
+ try {
608
+ const resolved = await _aiprofiles.resolveAIProfile.call(void 0, model);
609
+ return {
610
+ provider: _nullishCoalesce(_chunkEDMCKHO6cjs.normalizeProvider.call(void 0, resolved.provider), () => ( resolved.provider)),
611
+ modelId: _chunkEDMCKHO6cjs.normalizeString.call(void 0, resolved.modelId),
612
+ canonicalModelId: canonicalModelId(resolved.provider, resolved.modelId),
613
+ pricing: resolved.pricing,
614
+ matchedVia: resolved.shortcut ? "shortcut" : "profile",
615
+ profile: resolved.profile,
616
+ choice: resolved.choice
617
+ };
618
+ } catch (err) {
619
+ if (!(err instanceof _aiprofiles.AIProfilesError) || err.code !== "UNKNOWN_PROFILE") {
620
+ throw err;
621
+ }
622
+ }
623
+ const index = await getProfileIndex();
624
+ const hint = providerHintForProfiles(model, provider);
625
+ const direct = lookupInIndex(index, model, hint);
626
+ if (direct) return direct;
627
+ const stripped = _chunkEDMCKHO6cjs.stripModelVersionSuffix.call(void 0, model);
628
+ if (stripped && stripped !== _chunkEDMCKHO6cjs.normalizeString.call(void 0, model)) {
629
+ return lookupInIndex(index, stripped, providerHintForProfiles(stripped, provider));
630
+ }
631
+ return null;
632
+ }
633
+
634
+ // src/cost/profilePricing.ts
635
+ var TOKENS_PER_UNIT = 1e6;
636
+ function usdPerToken(perMillion) {
637
+ return (_nullishCoalesce(perMillion, () => ( 0))) / TOKENS_PER_UNIT;
638
+ }
639
+ function pickInputRatePerMillion(pricing, promptTokens) {
640
+ if (pricing.inputBelow200k !== void 0 && pricing.inputAbove200k !== void 0) {
641
+ return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD ? pricing.inputBelow200k : pricing.inputAbove200k;
642
+ }
643
+ return _nullishCoalesce(_nullishCoalesce(pricing.input, () => ( pricing.inputBelow200k)), () => ( pricing.inputAbove200k));
644
+ }
645
+ function pickOutputRatePerMillion(pricing, promptTokens) {
646
+ if (pricing.outputBelow200k !== void 0 && pricing.outputAbove200k !== void 0) {
647
+ return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD ? pricing.outputBelow200k : pricing.outputAbove200k;
648
+ }
649
+ return _nullishCoalesce(_nullishCoalesce(pricing.output, () => ( pricing.outputBelow200k)), () => ( pricing.outputAbove200k));
650
+ }
651
+ function aiProfilesPricingToCatalogPricing(pricing, pricedAt, options = {}) {
652
+ const promptTokens = _nullishCoalesce(options.promptTokens, () => ( 0));
653
+ const promptUsdPerToken = usdPerToken(pickInputRatePerMillion(pricing, promptTokens));
654
+ const completionUsdPerToken = usdPerToken(
655
+ pickOutputRatePerMillion(pricing, promptTokens)
656
+ );
657
+ const snapshot = {
658
+ promptUsdPerToken,
659
+ completionUsdPerToken,
660
+ cacheReadUsdPerToken: usdPerToken(_nullishCoalesce(pricing.cachedInput, () => ( pricing.cacheHit))),
661
+ cacheWriteUsdPerToken: usdPerToken(_nullishCoalesce(pricing.cacheWrite5m, () => ( pricing.cacheWrite1h))),
662
+ imageUsdPerUnit: 0,
663
+ requestUsdPerRequest: 0,
664
+ pricedAt,
665
+ source: "manual"
666
+ };
667
+ if (options.routedViaOpenRouter) {
668
+ snapshot.openRouterMarkupUsdPerInputToken = promptUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;
669
+ snapshot.openRouterMarkupUsdPerOutputToken = completionUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;
670
+ }
671
+ return snapshot;
672
+ }
673
+ function computeCostFromPricing(input, pricing, routedViaOpenRouter, includeBreakdown) {
674
+ const { tokens } = input;
675
+ let promptCost = tokens.prompt * pricing.promptUsdPerToken;
676
+ let completionCost = tokens.completion * pricing.completionUsdPerToken;
677
+ const cachingCost = (_nullishCoalesce(tokens.cacheWrite, () => ( 0))) * (_nullishCoalesce(pricing.cacheWriteUsdPerToken, () => ( 0))) + (_nullishCoalesce(tokens.cached, () => ( 0))) * (_nullishCoalesce(pricing.cacheReadUsdPerToken, () => ( 0)));
678
+ const reasoningCost = (_nullishCoalesce(tokens.reasoning, () => ( 0))) * (_nullishCoalesce(pricing.reasoningUsdPerToken, () => ( pricing.promptUsdPerToken)));
679
+ const audioCost = (_nullishCoalesce(tokens.audio, () => ( 0))) * pricing.promptUsdPerToken;
680
+ const imageCost = (_nullishCoalesce(tokens.image, () => ( 0))) * (_nullishCoalesce(pricing.imageUsdPerUnit, () => ( 0)));
681
+ const requestFlat = pricing.requestUsdPerRequest;
682
+ if (routedViaOpenRouter) {
683
+ promptCost += tokens.prompt * (_nullishCoalesce(pricing.openRouterMarkupUsdPerInputToken, () => ( 0)));
684
+ completionCost += tokens.completion * (_nullishCoalesce(pricing.openRouterMarkupUsdPerOutputToken, () => ( 0)));
685
+ }
686
+ const cost = promptCost + completionCost + cachingCost + reasoningCost + audioCost + imageCost + requestFlat;
687
+ if (!includeBreakdown) {
688
+ return { cost };
689
+ }
690
+ return {
691
+ cost,
692
+ breakdown: {
693
+ promptCostUsd: promptCost,
694
+ completionCostUsd: completionCost,
695
+ cachingCostUsd: cachingCost || void 0,
696
+ reasoningCostUsd: reasoningCost || void 0,
697
+ audioCostUsd: audioCost || void 0,
698
+ imageCostUsd: imageCost || void 0,
699
+ requestFlatCostUsd: requestFlat || void 0
700
+ }
701
+ };
702
+ }
703
+
704
+ // src/cost/CostCalculator.ts
705
+ function emptyPricing() {
706
+ return {
707
+ promptUsdPerToken: 0,
708
+ completionUsdPerToken: 0,
709
+ imageUsdPerUnit: 0,
710
+ requestUsdPerRequest: 0,
711
+ pricedAt: (/* @__PURE__ */ new Date()).toISOString(),
712
+ source: "manual"
713
+ };
714
+ }
715
+ function mergeAttempts(...groups) {
716
+ const seen = /* @__PURE__ */ new Set();
717
+ const out = [];
718
+ for (const group of groups) {
719
+ for (const a of group) {
720
+ const key = `${_nullishCoalesce(a.provider, () => ( ""))}\0${a.model}`;
721
+ if (seen.has(key)) continue;
722
+ seen.add(key);
723
+ out.push(a);
724
+ }
725
+ }
726
+ return out;
727
+ }
728
+ var CostCalculator = class {
729
+ constructor(catalog, options = {}) {
730
+ this.catalog = catalog;
731
+ this.aliasRegistry = options.aliasRegistry;
732
+ this.includeBreakdown = _nullishCoalesce(options.includeBreakdown, () => ( true));
733
+ this.resolverOptions = options.resolverOptions;
734
+ this.throwOnUnknownModel = _nullishCoalesce(options.throwOnUnknownModel, () => ( false));
735
+ }
736
+
737
+
738
+
739
+
740
+
741
+ /**
742
+ * Extract model, provider, and token usage from an activity / gateway record
743
+ * (MongoDB export, nested `outer`, `config`, `metadata.diagnostics`, etc.)
744
+ * then run {@link calculate}.
745
+ */
746
+ async calculateFromRecord(record, extractOptions) {
747
+ const { input, provenance } = extractUsageInput(record, extractOptions);
748
+ const warnings = [];
749
+ if (provenance.tokens.estimated) {
750
+ warnings.push({
751
+ code: "ESTIMATED_TOKEN_USAGE",
752
+ message: `Token counts are estimates from ${provenance.tokens.path} (not billed usage).`
753
+ });
754
+ }
755
+ const result = await this.calculate(input);
756
+ const enriched = enrichCostResult(result, input, toCostExtraction(provenance));
757
+ if (warnings.length > 0) {
758
+ enriched.warnings = [..._nullishCoalesce(enriched.warnings, () => ( [])), ...warnings];
759
+ }
760
+ return enriched;
761
+ }
762
+ async calculate(input) {
763
+ const modelInput = resolveUsageModel(input);
764
+ const resolverOpts = {
765
+ ...this.resolverOptions,
766
+ aliasRegistry: _nullishCoalesce(this.aliasRegistry, () => ( _optionalChain([this, 'access', _15 => _15.resolverOptions, 'optionalAccess', _16 => _16.aliasRegistry])))
767
+ };
768
+ let resolved = await resolveFromCatalogAttempts(
769
+ this.catalog,
770
+ buildCatalogResolveAttempts(modelInput, input.provider),
771
+ resolverOpts
772
+ );
773
+ if (isLocalProviderResolution(resolved, input.provider)) {
774
+ return this.localProviderResult(modelInput, input, resolved);
775
+ }
776
+ let profileMatch = null;
777
+ const warnings = [];
778
+ if (!_optionalChain([resolved, 'optionalAccess', _17 => _17.found]) || !resolved.record) {
779
+ if (!isLocalProvider(input.provider)) {
780
+ profileMatch = await matchModelInAiProfiles(modelInput, input.provider);
781
+ }
782
+ if (profileMatch) {
783
+ resolved = await resolveFromCatalogAttempts(
784
+ this.catalog,
785
+ mergeAttempts(
786
+ buildCatalogResolveAttempts(
787
+ profileMatch.canonicalModelId,
788
+ _nullishCoalesce(input.provider, () => ( profileMatch.provider))
789
+ ),
790
+ buildCatalogResolveAttempts(
791
+ profileMatch.canonicalModelId,
792
+ profileMatch.provider
793
+ )
794
+ ),
795
+ resolverOpts
796
+ );
797
+ }
798
+ if (isLocalProviderResolution(resolved, input.provider)) {
799
+ return this.localProviderResult(modelInput, input, resolved);
800
+ }
801
+ if ((!_optionalChain([resolved, 'optionalAccess', _18 => _18.found]) || !resolved.record) && _optionalChain([profileMatch, 'optionalAccess', _19 => _19.pricing])) {
802
+ const routedViaOpenRouter2 = resolveRoutedViaOpenRouter(
803
+ input.provider,
804
+ resolved,
805
+ profileMatch.canonicalModelId,
806
+ _optionalChain([resolverOpts, 'optionalAccess', _20 => _20.routingEnv])
807
+ );
808
+ const pricing2 = aiProfilesPricingToCatalogPricing(
809
+ profileMatch.pricing,
810
+ (/* @__PURE__ */ new Date()).toISOString(),
811
+ {
812
+ promptTokens: input.tokens.prompt,
813
+ routedViaOpenRouter: routedViaOpenRouter2
814
+ }
815
+ );
816
+ const { cost: cost2, breakdown: breakdown2 } = computeCostFromPricing(
817
+ input,
818
+ pricing2,
819
+ routedViaOpenRouter2,
820
+ this.includeBreakdown
821
+ );
822
+ warnings.push({
823
+ code: "AI_PROFILES_ESTIMATE",
824
+ message: `Catalog has no pricing for "${modelInput}"; estimated from ai-profiles (${profileMatch.matchedVia} \u2192 ${profileMatch.canonicalModelId}).`
825
+ });
826
+ if (routedViaOpenRouter2 && pricing2.openRouterMarkupUsdPerInputToken !== void 0) {
827
+ warnings.push({
828
+ code: "OPENROUTER_MARKUP_ESTIMATED",
829
+ message: "OpenRouter markup estimated at 5% of base token rates (catalog markup fields absent)."
830
+ });
831
+ }
832
+ console.warn(`[ai-tools] ${warnings.map((w) => w.message).join(" ")}`);
833
+ return this.finish(
834
+ {
835
+ cost: cost2,
836
+ breakdown: breakdown2,
837
+ resolvedModelId: profileMatch.canonicalModelId,
838
+ routedViaOpenRouter: routedViaOpenRouter2,
839
+ isAuthoritative: false,
840
+ pricingSnapshot: pricing2,
841
+ source: "ai-profiles",
842
+ warnings
843
+ },
844
+ input,
845
+ resolved
846
+ );
847
+ }
848
+ }
849
+ if (!_optionalChain([resolved, 'optionalAccess', _21 => _21.found]) || !resolved.record) {
850
+ return this.unknownModelResult(modelInput, input, resolved);
851
+ }
852
+ const { record, modelId } = resolved;
853
+ const routedViaOpenRouter = resolveRoutedViaOpenRouter(
854
+ input.provider,
855
+ resolved,
856
+ modelId,
857
+ _optionalChain([resolverOpts, 'optionalAccess', _22 => _22.routingEnv])
858
+ );
859
+ const pricing = record.pricing;
860
+ const { cost, breakdown } = computeCostFromPricing(
861
+ input,
862
+ pricing,
863
+ routedViaOpenRouter,
864
+ this.includeBreakdown
865
+ );
866
+ return this.finish(
867
+ {
868
+ cost,
869
+ breakdown,
870
+ resolvedModelId: modelId,
871
+ routedViaOpenRouter,
872
+ isAuthoritative: true,
873
+ pricingSnapshot: pricing,
874
+ source: "catalog"
875
+ },
876
+ input,
877
+ resolved
878
+ );
879
+ }
880
+ versionSuffixWarnings(input, pricedModelId, resolved) {
881
+ const received = _nullishCoalesce(_nullishCoalesce(input.usedModel, () => ( input.modelUsed)), () => ( input.model));
882
+ if (!received) return [];
883
+ const normalizedReceived = _chunkEDMCKHO6cjs.normalizeString.call(void 0, received);
884
+ const normalizedPriced = _chunkEDMCKHO6cjs.normalizeString.call(void 0, pricedModelId);
885
+ if (normalizedReceived === normalizedPriced) return [];
886
+ const stripped = _chunkEDMCKHO6cjs.stripModelVersionSuffix.call(void 0, received);
887
+ const viaResolver = _optionalChain([resolved, 'optionalAccess', _23 => _23.found]) === true && resolved.resolvedVia.some(
888
+ (s) => s === "version-suffix-strip" || s === "date-suffix-strip"
889
+ );
890
+ const pricedViaStrip = stripped !== null && _chunkEDMCKHO6cjs.normalizeString.call(void 0, stripped) === normalizedPriced;
891
+ if (!viaResolver && !pricedViaStrip) return [];
892
+ return [
893
+ {
894
+ code: "VERSION_SUFFIX_PRICING",
895
+ message: `Priced using catalog model "${pricedModelId}" (no exact pricing for "${received}").`
896
+ }
897
+ ];
898
+ }
899
+ finish(partial, input, resolved) {
900
+ const enriched = enrichCostResult(partial, input);
901
+ const suffixWarnings = this.versionSuffixWarnings(
902
+ input,
903
+ partial.resolvedModelId,
904
+ resolved
905
+ );
906
+ if (suffixWarnings.length > 0) {
907
+ enriched.warnings = [..._nullishCoalesce(enriched.warnings, () => ( [])), ...suffixWarnings];
908
+ }
909
+ return enriched;
910
+ }
911
+ localProviderResult(modelInput, input, resolved) {
912
+ const warnings = [
913
+ {
914
+ code: "LOCAL_PROVIDER_NO_PRICING",
915
+ message: `Local provider "${input.provider}" has no catalog pricing for "${modelInput}".`
916
+ }
917
+ ];
918
+ console.warn(`[ai-tools] ${warnings[0].message}`);
919
+ return this.finish(
920
+ {
921
+ cost: 0,
922
+ resolvedModelId: _optionalChain([resolved, 'optionalAccess', _24 => _24.found]) ? resolved.modelId : modelInput,
923
+ routedViaOpenRouter: false,
924
+ isAuthoritative: false,
925
+ pricingSnapshot: emptyPricing(),
926
+ source: "local",
927
+ warnings
928
+ },
929
+ input
930
+ );
931
+ }
932
+ unknownModelResult(modelInput, input, resolved) {
933
+ if (this.throwOnUnknownModel) {
934
+ throw new (0, _chunkPADNCGZBcjs.UnknownModelCostError)(modelInput, input.provider);
935
+ }
936
+ const warnings = [
937
+ {
938
+ code: "UNKNOWN_MODEL",
939
+ message: `Unknown model "${modelInput}" (provider: "${input.provider}") \u2014 returning zero-cost fallback.`
940
+ }
941
+ ];
942
+ console.warn(`[ai-tools] ${warnings[0].message}`);
943
+ return this.finish(
944
+ {
945
+ cost: 0,
946
+ resolvedModelId: modelInput,
947
+ routedViaOpenRouter: resolveRoutedViaOpenRouter(
948
+ input.provider,
949
+ resolved,
950
+ modelInput,
951
+ _optionalChain([this, 'access', _25 => _25.resolverOptions, 'optionalAccess', _26 => _26.routingEnv])
952
+ ),
953
+ isAuthoritative: false,
954
+ pricingSnapshot: emptyPricing(),
955
+ source: "estimate-fallback",
956
+ unknownModel: true,
957
+ warnings
958
+ },
959
+ input
960
+ );
961
+ }
962
+ };
963
+
964
+
965
+
966
+
967
+
968
+
969
+
970
+
971
+
972
+ 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;
973
+ //# sourceMappingURL=chunk-NF2SKQR7.cjs.map