@x12i/ai-tools 1.0.4 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) 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-5IZ7PLY2.cjs +51 -0
  21. package/dist/chunk-5IZ7PLY2.cjs.map +1 -0
  22. package/dist/chunk-5XAAMBDO.cjs +1988 -0
  23. package/dist/chunk-5XAAMBDO.cjs.map +1 -0
  24. package/dist/chunk-6BQBKROR.js +95 -0
  25. package/dist/chunk-6BQBKROR.js.map +1 -0
  26. package/dist/chunk-AB5GNXJ4.js +46 -0
  27. package/dist/chunk-AB5GNXJ4.js.map +1 -0
  28. package/dist/{chunk-O2A6OVEH.js → chunk-ANVONYJF.js} +2 -2
  29. package/dist/{chunk-O2A6OVEH.js.map → chunk-ANVONYJF.js.map} +1 -1
  30. package/dist/chunk-B3V2EHRY.js +225 -0
  31. package/dist/chunk-B3V2EHRY.js.map +1 -0
  32. package/dist/{chunk-QWAX7VQO.cjs → chunk-BAHBDADJ.cjs} +11 -11
  33. package/dist/{chunk-QWAX7VQO.cjs.map → chunk-BAHBDADJ.cjs.map} +1 -1
  34. package/dist/chunk-CTM35DMA.js +948 -0
  35. package/dist/chunk-CTM35DMA.js.map +1 -0
  36. package/dist/{chunk-TF4L2NEC.cjs → chunk-DXZOL3VN.cjs} +62 -313
  37. package/dist/chunk-DXZOL3VN.cjs.map +1 -0
  38. package/dist/chunk-EDMCKHO6.cjs +225 -0
  39. package/dist/chunk-EDMCKHO6.cjs.map +1 -0
  40. package/dist/{chunk-DJ5SWJDY.js → chunk-EYHMQVAL.js} +48 -299
  41. package/dist/chunk-EYHMQVAL.js.map +1 -0
  42. package/dist/chunk-GS7T56RP.cjs +8 -0
  43. package/dist/chunk-GS7T56RP.cjs.map +1 -0
  44. package/dist/chunk-OPN6BGNH.js +1985 -0
  45. package/dist/chunk-OPN6BGNH.js.map +1 -0
  46. package/dist/{chunk-7Q742NI3.cjs → chunk-PADNCGZB.cjs} +17 -3
  47. package/dist/chunk-PADNCGZB.cjs.map +1 -0
  48. package/dist/chunk-PRCICORG.cjs +95 -0
  49. package/dist/chunk-PRCICORG.cjs.map +1 -0
  50. package/dist/{chunk-6QGDZTGH.js → chunk-SIH4GPV4.js} +4 -29
  51. package/dist/chunk-SIH4GPV4.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-WOHMHXRZ.cjs +951 -0
  55. package/dist/chunk-WOHMHXRZ.cjs.map +1 -0
  56. package/dist/chunk-XAWBTX3N.cjs +46 -0
  57. package/dist/chunk-XAWBTX3N.cjs.map +1 -0
  58. package/dist/{chunk-AV6OE2YQ.cjs → chunk-XOKUDUUI.cjs} +14 -39
  59. package/dist/chunk-XOKUDUUI.cjs.map +1 -0
  60. package/dist/chunk-YQDSN6R6.cjs +86 -0
  61. package/dist/chunk-YQDSN6R6.cjs.map +1 -0
  62. package/dist/chunk-YQVY7CWT.js +51 -0
  63. package/dist/chunk-YQVY7CWT.js.map +1 -0
  64. package/dist/cli/index.cjs +59 -201
  65. package/dist/cli/index.cjs.map +1 -1
  66. package/dist/cli/index.js +53 -198
  67. package/dist/cli/index.js.map +1 -1
  68. package/dist/cost/index.cjs +19 -3
  69. package/dist/cost/index.cjs.map +1 -1
  70. package/dist/cost/index.d.cts +10 -50
  71. package/dist/cost/index.d.ts +10 -50
  72. package/dist/cost/index.js +18 -3
  73. package/dist/index.cjs +36 -14
  74. package/dist/index.cjs.map +1 -1
  75. package/dist/index.d.cts +15 -13
  76. package/dist/index.d.ts +15 -13
  77. package/dist/index.js +56 -35
  78. package/dist/modelCache-BzRn6t_C.d.ts +113 -0
  79. package/dist/modelCache-CJftI-Ko.d.cts +113 -0
  80. package/dist/{modelNameResolver-DqFt7g6W.d.ts → modelNameResolver-5XkBMctP.d.ts} +2 -6
  81. package/dist/{modelNameResolver-D9V_GfUK.d.cts → modelNameResolver-C5CSTGFF.d.cts} +2 -6
  82. package/dist/models/index.cjs +9 -6
  83. package/dist/models/index.cjs.map +1 -1
  84. package/dist/models/index.d.cts +9 -31
  85. package/dist/models/index.d.ts +9 -31
  86. package/dist/models/index.js +9 -7
  87. package/dist/profiles/index.cjs +18 -0
  88. package/dist/profiles/index.cjs.map +1 -0
  89. package/dist/profiles/index.d.cts +40 -0
  90. package/dist/profiles/index.d.ts +40 -0
  91. package/dist/profiles/index.js +17 -0
  92. package/dist/resolveUsageModel-BFwf80Hz.d.ts +140 -0
  93. package/dist/resolveUsageModel-C_YmGR1M.d.cts +140 -0
  94. package/dist/sync/index.cjs +7 -9
  95. package/dist/sync/index.cjs.map +1 -1
  96. package/dist/sync/index.d.cts +3 -8
  97. package/dist/sync/index.d.ts +3 -8
  98. package/dist/sync/index.js +8 -11
  99. package/dist/toolbox/index.cjs +1 -0
  100. package/dist/toolbox/index.cjs.map +1 -1
  101. package/dist/types-BrzJWsTU.d.cts +277 -0
  102. package/dist/types-BrzJWsTU.d.ts +277 -0
  103. package/package.json +14 -20
  104. package/src/data/models-catalog.json +670 -0
  105. package/src/data/openrouter-models-catalog.json +857 -0
  106. package/dist/AiModelsCatalogClient-4RF5BCDL.cjs +0 -9
  107. package/dist/AiModelsCatalogClient-4RF5BCDL.cjs.map +0 -1
  108. package/dist/AiModelsCatalogClient-CNeqFiFs.d.cts +0 -30
  109. package/dist/AiModelsCatalogClient-NUF3CBLW.js +0 -9
  110. package/dist/AiModelsCatalogClient-nwFoEaqL.d.ts +0 -30
  111. package/dist/catalox/index.cjs +0 -21
  112. package/dist/catalox/index.cjs.map +0 -1
  113. package/dist/catalox/index.d.cts +0 -11
  114. package/dist/catalox/index.d.ts +0 -11
  115. package/dist/catalox/index.js +0 -21
  116. package/dist/chunk-4NAY6HRP.js.map +0 -1
  117. package/dist/chunk-6QGDZTGH.js.map +0 -1
  118. package/dist/chunk-7Q742NI3.cjs.map +0 -1
  119. package/dist/chunk-AJEKEWWB.js.map +0 -1
  120. package/dist/chunk-AV6OE2YQ.cjs.map +0 -1
  121. package/dist/chunk-C3H7RTFR.cjs +0 -1
  122. package/dist/chunk-C3H7RTFR.cjs.map +0 -1
  123. package/dist/chunk-DJ5SWJDY.js.map +0 -1
  124. package/dist/chunk-DKHGWHXP.cjs +0 -169
  125. package/dist/chunk-DKHGWHXP.cjs.map +0 -1
  126. package/dist/chunk-F2F4UEFD.cjs +0 -75
  127. package/dist/chunk-F2F4UEFD.cjs.map +0 -1
  128. package/dist/chunk-FGP3QXWL.cjs +0 -163
  129. package/dist/chunk-FGP3QXWL.cjs.map +0 -1
  130. package/dist/chunk-G2G4KSC5.js +0 -30
  131. package/dist/chunk-G2G4KSC5.js.map +0 -1
  132. package/dist/chunk-HN6UAQAE.cjs +0 -83
  133. package/dist/chunk-HN6UAQAE.cjs.map +0 -1
  134. package/dist/chunk-HS74X2OJ.cjs +0 -172
  135. package/dist/chunk-HS74X2OJ.cjs.map +0 -1
  136. package/dist/chunk-HYGXZY25.js +0 -163
  137. package/dist/chunk-HYGXZY25.js.map +0 -1
  138. package/dist/chunk-KQOALKKX.js +0 -75
  139. package/dist/chunk-KQOALKKX.js.map +0 -1
  140. package/dist/chunk-LYOU7CA2.cjs +0 -30
  141. package/dist/chunk-LYOU7CA2.cjs.map +0 -1
  142. package/dist/chunk-M5TMA73F.js +0 -1
  143. package/dist/chunk-M5TMA73F.js.map +0 -1
  144. package/dist/chunk-MX3AMQFC.js +0 -172
  145. package/dist/chunk-MX3AMQFC.js.map +0 -1
  146. package/dist/chunk-QCRLKVB3.cjs +0 -137
  147. package/dist/chunk-QCRLKVB3.cjs.map +0 -1
  148. package/dist/chunk-TF4L2NEC.cjs.map +0 -1
  149. package/dist/chunk-VRFVF5RH.js +0 -169
  150. package/dist/chunk-VRFVF5RH.js.map +0 -1
  151. package/dist/chunk-YHO57D2V.js +0 -83
  152. package/dist/chunk-YHO57D2V.js.map +0 -1
  153. package/dist/syncAiModelsCatalog-CnXRLm2c.d.cts +0 -32
  154. package/dist/syncAiModelsCatalog-DpkN_w7S.d.ts +0 -32
  155. package/dist/types-BYXnCvKx.d.cts +0 -137
  156. package/dist/types-BYXnCvKx.d.ts +0 -137
  157. package/dist/types-CX6QFNNy.d.cts +0 -144
  158. package/dist/types-CuiPDcVs.d.ts +0 -144
  159. package/dist/upsertAiModelRecord-C831wOIF.d.ts +0 -35
  160. package/dist/upsertAiModelRecord-CjY-sny0.d.cts +0 -35
  161. /package/dist/{AiModelsCatalogClient-NUF3CBLW.js.map → chunk-56R4XA2S.js.map} +0 -0
  162. /package/dist/{catalox → profiles}/index.js.map +0 -0
@@ -0,0 +1,951 @@
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 profile of Object.values(registry.profiles)) {
479
+ for (const [choiceKey, choice] of Object.entries(profile.choices)) {
480
+ const entry = choiceEntry(choice, profile.profile, choiceKey);
481
+ add(choice.modelId, entry);
482
+ add(canonicalModelId(choice.provider, choice.modelId), entry);
483
+ }
484
+ }
485
+ return byKey;
486
+ }
487
+ function choiceEntry(choice, profile, choiceKey) {
488
+ const canonical = canonicalModelId(choice.provider, choice.modelId);
489
+ return {
490
+ provider: _nullishCoalesce(_chunkEDMCKHO6cjs.normalizeProvider.call(void 0, choice.provider), () => ( choice.provider)),
491
+ modelId: _chunkEDMCKHO6cjs.normalizeString.call(void 0, choice.modelId),
492
+ canonicalModelId: canonical,
493
+ pricing: choice.pricing,
494
+ profile,
495
+ choice: choiceKey
496
+ };
497
+ }
498
+ async function getProfileIndex() {
499
+ const registry = await loadProfilesRegistry();
500
+ const cacheKey = `${registry.version}:${_nullishCoalesce(registry.generatedAt, () => ( ""))}:${registry.source}`;
501
+ if (_optionalChain([cachedIndex, 'optionalAccess', _14 => _14.cacheKey]) === cacheKey) {
502
+ return cachedIndex.byKey;
503
+ }
504
+ const byKey = indexRegistry(registry);
505
+ cachedIndex = { cacheKey, byKey };
506
+ return byKey;
507
+ }
508
+ function scoreCandidate(entry, model, providerHint) {
509
+ const normalized = _chunkEDMCKHO6cjs.normalizeString.call(void 0, model);
510
+ let score = 0;
511
+ if (normalized === entry.canonicalModelId) score += 100;
512
+ if (normalized === entry.modelId) score += 80;
513
+ if (providerHint && entry.provider === providerHint) score += 50;
514
+ if (entry.pricing) score += 2;
515
+ return score;
516
+ }
517
+ function pickBest(candidates, model, providerHint) {
518
+ if (candidates.length === 0) return null;
519
+ if (candidates.length === 1) return candidates[0];
520
+ let best = candidates[0];
521
+ let bestScore = scoreCandidate(best, model, providerHint);
522
+ for (let i = 1; i < candidates.length; i++) {
523
+ const c = candidates[i];
524
+ const s = scoreCandidate(c, model, providerHint);
525
+ if (s > bestScore) {
526
+ best = c;
527
+ bestScore = s;
528
+ }
529
+ }
530
+ return best;
531
+ }
532
+ function resolvedToMatch(resolved) {
533
+ return {
534
+ provider: _nullishCoalesce(_chunkEDMCKHO6cjs.normalizeProvider.call(void 0, resolved.provider), () => ( resolved.provider)),
535
+ modelId: _chunkEDMCKHO6cjs.normalizeString.call(void 0, resolved.modelId),
536
+ canonicalModelId: canonicalModelId(resolved.provider, resolved.modelId),
537
+ pricing: resolved.pricing,
538
+ instructionTier: resolved.instructionTier,
539
+ backend: resolved.backend,
540
+ matchedVia: resolved.shortcut ? "shortcut" : "profile",
541
+ profile: resolved.profile,
542
+ choice: resolved.choice
543
+ };
544
+ }
545
+ async function fromIndexed(entry) {
546
+ const resolved = await _aiprofiles.resolveAIProfile.call(void 0, entry.profile, { choice: entry.choice });
547
+ return {
548
+ provider: _nullishCoalesce(_chunkEDMCKHO6cjs.normalizeProvider.call(void 0, resolved.provider), () => ( resolved.provider)),
549
+ modelId: _chunkEDMCKHO6cjs.normalizeString.call(void 0, resolved.modelId),
550
+ canonicalModelId: canonicalModelId(resolved.provider, resolved.modelId),
551
+ pricing: _nullishCoalesce(resolved.pricing, () => ( entry.pricing)),
552
+ instructionTier: resolved.instructionTier,
553
+ backend: resolved.backend,
554
+ matchedVia: "model-id",
555
+ profile: resolved.profile,
556
+ choice: resolved.choice
557
+ };
558
+ }
559
+ async function lookupInIndex(index, model, provider) {
560
+ const providerHint = provider ? _chunkEDMCKHO6cjs.normalizeProvider.call(void 0, provider) : void 0;
561
+ const keys = [
562
+ profileKey(model),
563
+ profileKey(_chunkEDMCKHO6cjs.normalizeString.call(void 0, model))
564
+ ];
565
+ if (providerHint) {
566
+ keys.push(profileKey(canonicalModelId(providerHint, model)));
567
+ }
568
+ const pooled = [];
569
+ for (const key of keys) {
570
+ const hits = index.get(key);
571
+ if (hits) pooled.push(...hits);
572
+ }
573
+ const bare = _chunkEDMCKHO6cjs.normalizeString.call(void 0, model);
574
+ if (!bare.includes("/")) {
575
+ for (const list of index.values()) {
576
+ for (const entry of list) {
577
+ if (entry.modelId === bare) pooled.push(entry);
578
+ }
579
+ }
580
+ }
581
+ const unique = /* @__PURE__ */ new Map();
582
+ for (const e of pooled) {
583
+ unique.set(`${e.profile}:${e.choice}:${e.canonicalModelId}`, e);
584
+ }
585
+ const best = pickBest([...unique.values()], model, providerHint);
586
+ return best ? fromIndexed(best) : null;
587
+ }
588
+ async function matchModelInAiProfiles(model, provider) {
589
+ try {
590
+ const resolved = await _aiprofiles.resolveAIProfile.call(void 0, model);
591
+ return resolvedToMatch(resolved);
592
+ } catch (err) {
593
+ if (!(err instanceof _aiprofiles.AIProfilesError) || err.code !== "UNKNOWN_PROFILE") {
594
+ throw err;
595
+ }
596
+ }
597
+ const index = await getProfileIndex();
598
+ const hint = providerHintForProfiles(model, provider);
599
+ const direct = await lookupInIndex(index, model, hint);
600
+ if (direct) return direct;
601
+ const stripped = _chunkEDMCKHO6cjs.stripModelVersionSuffix.call(void 0, model);
602
+ if (stripped && stripped !== _chunkEDMCKHO6cjs.normalizeString.call(void 0, model)) {
603
+ return lookupInIndex(
604
+ index,
605
+ stripped,
606
+ providerHintForProfiles(stripped, provider)
607
+ );
608
+ }
609
+ return null;
610
+ }
611
+
612
+ // src/cost/profilePricing.ts
613
+ var TOKENS_PER_UNIT = 1e6;
614
+ function usdPerToken(perMillion) {
615
+ return (_nullishCoalesce(perMillion, () => ( 0))) / TOKENS_PER_UNIT;
616
+ }
617
+ function pickInputRatePerMillion(pricing, promptTokens) {
618
+ if (pricing.inputBelow200k !== void 0 && pricing.inputAbove200k !== void 0) {
619
+ return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD ? pricing.inputBelow200k : pricing.inputAbove200k;
620
+ }
621
+ return _nullishCoalesce(_nullishCoalesce(pricing.input, () => ( pricing.inputBelow200k)), () => ( pricing.inputAbove200k));
622
+ }
623
+ function pickOutputRatePerMillion(pricing, promptTokens) {
624
+ if (pricing.outputBelow200k !== void 0 && pricing.outputAbove200k !== void 0) {
625
+ return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD ? pricing.outputBelow200k : pricing.outputAbove200k;
626
+ }
627
+ return _nullishCoalesce(_nullishCoalesce(pricing.output, () => ( pricing.outputBelow200k)), () => ( pricing.outputAbove200k));
628
+ }
629
+ function aiProfilesPricingToCatalogPricing(pricing, pricedAt, options = {}) {
630
+ const promptTokens = _nullishCoalesce(options.promptTokens, () => ( 0));
631
+ const promptUsdPerToken = usdPerToken(pickInputRatePerMillion(pricing, promptTokens));
632
+ const completionUsdPerToken = usdPerToken(
633
+ pickOutputRatePerMillion(pricing, promptTokens)
634
+ );
635
+ const snapshot = {
636
+ promptUsdPerToken,
637
+ completionUsdPerToken,
638
+ cacheReadUsdPerToken: usdPerToken(_nullishCoalesce(pricing.cachedInput, () => ( pricing.cacheHit))),
639
+ cacheWriteUsdPerToken: usdPerToken(_nullishCoalesce(pricing.cacheWrite5m, () => ( pricing.cacheWrite1h))),
640
+ imageUsdPerUnit: 0,
641
+ requestUsdPerRequest: 0,
642
+ pricedAt,
643
+ source: "manual"
644
+ };
645
+ if (options.routedViaOpenRouter) {
646
+ snapshot.openRouterMarkupUsdPerInputToken = promptUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;
647
+ snapshot.openRouterMarkupUsdPerOutputToken = completionUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;
648
+ }
649
+ return snapshot;
650
+ }
651
+ function computeCostFromPricing(input, pricing, routedViaOpenRouter, includeBreakdown) {
652
+ const { tokens } = input;
653
+ let promptCost = tokens.prompt * pricing.promptUsdPerToken;
654
+ let completionCost = tokens.completion * pricing.completionUsdPerToken;
655
+ const cachingCost = (_nullishCoalesce(tokens.cacheWrite, () => ( 0))) * (_nullishCoalesce(pricing.cacheWriteUsdPerToken, () => ( 0))) + (_nullishCoalesce(tokens.cached, () => ( 0))) * (_nullishCoalesce(pricing.cacheReadUsdPerToken, () => ( 0)));
656
+ const reasoningCost = (_nullishCoalesce(tokens.reasoning, () => ( 0))) * (_nullishCoalesce(pricing.reasoningUsdPerToken, () => ( pricing.promptUsdPerToken)));
657
+ const audioCost = (_nullishCoalesce(tokens.audio, () => ( 0))) * pricing.promptUsdPerToken;
658
+ const imageCost = (_nullishCoalesce(tokens.image, () => ( 0))) * (_nullishCoalesce(pricing.imageUsdPerUnit, () => ( 0)));
659
+ const requestFlat = pricing.requestUsdPerRequest;
660
+ if (routedViaOpenRouter) {
661
+ promptCost += tokens.prompt * (_nullishCoalesce(pricing.openRouterMarkupUsdPerInputToken, () => ( 0)));
662
+ completionCost += tokens.completion * (_nullishCoalesce(pricing.openRouterMarkupUsdPerOutputToken, () => ( 0)));
663
+ }
664
+ const cost = promptCost + completionCost + cachingCost + reasoningCost + audioCost + imageCost + requestFlat;
665
+ if (!includeBreakdown) {
666
+ return { cost };
667
+ }
668
+ return {
669
+ cost,
670
+ breakdown: {
671
+ promptCostUsd: promptCost,
672
+ completionCostUsd: completionCost,
673
+ cachingCostUsd: cachingCost || void 0,
674
+ reasoningCostUsd: reasoningCost || void 0,
675
+ audioCostUsd: audioCost || void 0,
676
+ imageCostUsd: imageCost || void 0,
677
+ requestFlatCostUsd: requestFlat || void 0
678
+ }
679
+ };
680
+ }
681
+
682
+ // src/cost/CostCalculator.ts
683
+ function emptyPricing() {
684
+ return {
685
+ promptUsdPerToken: 0,
686
+ completionUsdPerToken: 0,
687
+ imageUsdPerUnit: 0,
688
+ requestUsdPerRequest: 0,
689
+ pricedAt: (/* @__PURE__ */ new Date()).toISOString(),
690
+ source: "manual"
691
+ };
692
+ }
693
+ function mergeAttempts(...groups) {
694
+ const seen = /* @__PURE__ */ new Set();
695
+ const out = [];
696
+ for (const group of groups) {
697
+ for (const a of group) {
698
+ const key = `${_nullishCoalesce(a.provider, () => ( ""))}\0${a.model}`;
699
+ if (seen.has(key)) continue;
700
+ seen.add(key);
701
+ out.push(a);
702
+ }
703
+ }
704
+ return out;
705
+ }
706
+ var CostCalculator = class {
707
+ constructor(catalog, options = {}) {
708
+ this.catalog = catalog;
709
+ this.aliasRegistry = options.aliasRegistry;
710
+ this.includeBreakdown = _nullishCoalesce(options.includeBreakdown, () => ( true));
711
+ this.resolverOptions = options.resolverOptions;
712
+ this.throwOnUnknownModel = _nullishCoalesce(options.throwOnUnknownModel, () => ( false));
713
+ }
714
+
715
+
716
+
717
+
718
+
719
+ /**
720
+ * Extract model, provider, and token usage from an activity / gateway record
721
+ * (MongoDB export, nested `outer`, `config`, `metadata.diagnostics`, etc.)
722
+ * then run {@link calculate}.
723
+ */
724
+ async calculateFromRecord(record, extractOptions) {
725
+ const { input, provenance } = extractUsageInput(record, extractOptions);
726
+ const warnings = [];
727
+ if (provenance.tokens.estimated) {
728
+ warnings.push({
729
+ code: "ESTIMATED_TOKEN_USAGE",
730
+ message: `Token counts are estimates from ${provenance.tokens.path} (not billed usage).`
731
+ });
732
+ }
733
+ const result = await this.calculate(input);
734
+ const enriched = enrichCostResult(result, input, toCostExtraction(provenance));
735
+ if (warnings.length > 0) {
736
+ enriched.warnings = [..._nullishCoalesce(enriched.warnings, () => ( [])), ...warnings];
737
+ }
738
+ return enriched;
739
+ }
740
+ async calculate(input) {
741
+ const modelInput = resolveUsageModel(input);
742
+ const resolverOpts = {
743
+ ...this.resolverOptions,
744
+ aliasRegistry: _nullishCoalesce(this.aliasRegistry, () => ( _optionalChain([this, 'access', _15 => _15.resolverOptions, 'optionalAccess', _16 => _16.aliasRegistry])))
745
+ };
746
+ let resolved = await resolveFromCatalogAttempts(
747
+ this.catalog,
748
+ buildCatalogResolveAttempts(modelInput, input.provider),
749
+ resolverOpts
750
+ );
751
+ if (isLocalProviderResolution(resolved, input.provider)) {
752
+ return this.localProviderResult(modelInput, input, resolved);
753
+ }
754
+ let profileMatch = null;
755
+ const warnings = [];
756
+ if (!_optionalChain([resolved, 'optionalAccess', _17 => _17.found]) || !resolved.record) {
757
+ if (!isLocalProvider(input.provider)) {
758
+ profileMatch = await matchModelInAiProfiles(modelInput, input.provider);
759
+ }
760
+ if (profileMatch) {
761
+ resolved = await resolveFromCatalogAttempts(
762
+ this.catalog,
763
+ mergeAttempts(
764
+ buildCatalogResolveAttempts(
765
+ profileMatch.canonicalModelId,
766
+ _nullishCoalesce(input.provider, () => ( profileMatch.provider))
767
+ ),
768
+ buildCatalogResolveAttempts(
769
+ profileMatch.canonicalModelId,
770
+ profileMatch.provider
771
+ )
772
+ ),
773
+ resolverOpts
774
+ );
775
+ }
776
+ if (isLocalProviderResolution(resolved, input.provider)) {
777
+ return this.localProviderResult(modelInput, input, resolved);
778
+ }
779
+ if ((!_optionalChain([resolved, 'optionalAccess', _18 => _18.found]) || !resolved.record) && _optionalChain([profileMatch, 'optionalAccess', _19 => _19.pricing])) {
780
+ const routedViaOpenRouter2 = resolveRoutedViaOpenRouter(
781
+ input.provider,
782
+ resolved,
783
+ profileMatch.canonicalModelId,
784
+ _optionalChain([resolverOpts, 'optionalAccess', _20 => _20.routingEnv])
785
+ );
786
+ const pricing2 = aiProfilesPricingToCatalogPricing(
787
+ profileMatch.pricing,
788
+ (/* @__PURE__ */ new Date()).toISOString(),
789
+ {
790
+ promptTokens: input.tokens.prompt,
791
+ routedViaOpenRouter: routedViaOpenRouter2
792
+ }
793
+ );
794
+ const { cost: cost2, breakdown: breakdown2 } = computeCostFromPricing(
795
+ input,
796
+ pricing2,
797
+ routedViaOpenRouter2,
798
+ this.includeBreakdown
799
+ );
800
+ warnings.push({
801
+ code: "AI_PROFILES_ESTIMATE",
802
+ message: `Catalog has no pricing for "${modelInput}"; estimated from ai-profiles (${profileMatch.matchedVia} \u2192 ${profileMatch.canonicalModelId}).`
803
+ });
804
+ if (routedViaOpenRouter2 && pricing2.openRouterMarkupUsdPerInputToken !== void 0) {
805
+ warnings.push({
806
+ code: "OPENROUTER_MARKUP_ESTIMATED",
807
+ message: "OpenRouter markup estimated at 5% of base token rates (catalog markup fields absent)."
808
+ });
809
+ }
810
+ console.warn(`[ai-tools] ${warnings.map((w) => w.message).join(" ")}`);
811
+ return this.finish(
812
+ {
813
+ cost: cost2,
814
+ breakdown: breakdown2,
815
+ resolvedModelId: profileMatch.canonicalModelId,
816
+ routedViaOpenRouter: routedViaOpenRouter2,
817
+ isAuthoritative: false,
818
+ pricingSnapshot: pricing2,
819
+ source: "ai-profiles",
820
+ warnings
821
+ },
822
+ input,
823
+ resolved
824
+ );
825
+ }
826
+ }
827
+ if (!_optionalChain([resolved, 'optionalAccess', _21 => _21.found]) || !resolved.record) {
828
+ return this.unknownModelResult(modelInput, input, resolved);
829
+ }
830
+ const { record, modelId } = resolved;
831
+ const routedViaOpenRouter = resolveRoutedViaOpenRouter(
832
+ input.provider,
833
+ resolved,
834
+ modelId,
835
+ _optionalChain([resolverOpts, 'optionalAccess', _22 => _22.routingEnv])
836
+ );
837
+ const pricing = record.pricing;
838
+ const { cost, breakdown } = computeCostFromPricing(
839
+ input,
840
+ pricing,
841
+ routedViaOpenRouter,
842
+ this.includeBreakdown
843
+ );
844
+ return this.finish(
845
+ {
846
+ cost,
847
+ breakdown,
848
+ resolvedModelId: modelId,
849
+ routedViaOpenRouter,
850
+ isAuthoritative: true,
851
+ pricingSnapshot: pricing,
852
+ source: "catalog"
853
+ },
854
+ input,
855
+ resolved
856
+ );
857
+ }
858
+ versionSuffixWarnings(input, pricedModelId, resolved) {
859
+ const received = _nullishCoalesce(_nullishCoalesce(input.usedModel, () => ( input.modelUsed)), () => ( input.model));
860
+ if (!received) return [];
861
+ const normalizedReceived = _chunkEDMCKHO6cjs.normalizeString.call(void 0, received);
862
+ const normalizedPriced = _chunkEDMCKHO6cjs.normalizeString.call(void 0, pricedModelId);
863
+ if (normalizedReceived === normalizedPriced) return [];
864
+ const stripped = _chunkEDMCKHO6cjs.stripModelVersionSuffix.call(void 0, received);
865
+ const viaResolver = _optionalChain([resolved, 'optionalAccess', _23 => _23.found]) === true && resolved.resolvedVia.some(
866
+ (s) => s === "version-suffix-strip" || s === "date-suffix-strip"
867
+ );
868
+ const pricedViaStrip = stripped !== null && _chunkEDMCKHO6cjs.normalizeString.call(void 0, stripped) === normalizedPriced;
869
+ if (!viaResolver && !pricedViaStrip) return [];
870
+ return [
871
+ {
872
+ code: "VERSION_SUFFIX_PRICING",
873
+ message: `Priced using catalog model "${pricedModelId}" (no exact pricing for "${received}").`
874
+ }
875
+ ];
876
+ }
877
+ finish(partial, input, resolved) {
878
+ const enriched = enrichCostResult(partial, input);
879
+ const suffixWarnings = this.versionSuffixWarnings(
880
+ input,
881
+ partial.resolvedModelId,
882
+ resolved
883
+ );
884
+ if (suffixWarnings.length > 0) {
885
+ enriched.warnings = [..._nullishCoalesce(enriched.warnings, () => ( [])), ...suffixWarnings];
886
+ }
887
+ return enriched;
888
+ }
889
+ localProviderResult(modelInput, input, resolved) {
890
+ const warnings = [
891
+ {
892
+ code: "LOCAL_PROVIDER_NO_PRICING",
893
+ message: `Local provider "${input.provider}" has no catalog pricing for "${modelInput}".`
894
+ }
895
+ ];
896
+ console.warn(`[ai-tools] ${warnings[0].message}`);
897
+ return this.finish(
898
+ {
899
+ cost: 0,
900
+ resolvedModelId: _optionalChain([resolved, 'optionalAccess', _24 => _24.found]) ? resolved.modelId : modelInput,
901
+ routedViaOpenRouter: false,
902
+ isAuthoritative: false,
903
+ pricingSnapshot: emptyPricing(),
904
+ source: "local",
905
+ warnings
906
+ },
907
+ input
908
+ );
909
+ }
910
+ unknownModelResult(modelInput, input, resolved) {
911
+ if (this.throwOnUnknownModel) {
912
+ throw new (0, _chunkPADNCGZBcjs.UnknownModelCostError)(modelInput, input.provider);
913
+ }
914
+ const warnings = [
915
+ {
916
+ code: "UNKNOWN_MODEL",
917
+ message: `Unknown model "${modelInput}" (provider: "${input.provider}") \u2014 returning zero-cost fallback.`
918
+ }
919
+ ];
920
+ console.warn(`[ai-tools] ${warnings[0].message}`);
921
+ return this.finish(
922
+ {
923
+ cost: 0,
924
+ resolvedModelId: modelInput,
925
+ routedViaOpenRouter: resolveRoutedViaOpenRouter(
926
+ input.provider,
927
+ resolved,
928
+ modelInput,
929
+ _optionalChain([this, 'access', _25 => _25.resolverOptions, 'optionalAccess', _26 => _26.routingEnv])
930
+ ),
931
+ isAuthoritative: false,
932
+ pricingSnapshot: emptyPricing(),
933
+ source: "estimate-fallback",
934
+ unknownModel: true,
935
+ warnings
936
+ },
937
+ input
938
+ );
939
+ }
940
+ };
941
+
942
+
943
+
944
+
945
+
946
+
947
+
948
+
949
+
950
+ 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;
951
+ //# sourceMappingURL=chunk-WOHMHXRZ.cjs.map