@x12i/ai-tools 2.1.3 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/catalog/index.cjs +4 -4
- package/dist/catalog/index.js +3 -3
- package/dist/{chunk-UY2VLJN6.cjs → chunk-33AAM7KQ.cjs} +3 -3
- package/dist/{chunk-UY2VLJN6.cjs.map → chunk-33AAM7KQ.cjs.map} +1 -1
- package/dist/{chunk-4ILJWO64.js → chunk-3CUSLNEV.js} +8 -1
- package/dist/chunk-3CUSLNEV.js.map +1 -0
- package/dist/{chunk-SYDW33AL.cjs → chunk-EDZOFPLV.cjs} +8 -1
- package/dist/chunk-EDZOFPLV.cjs.map +1 -0
- package/dist/{chunk-ZHRU337O.cjs → chunk-FWPH5YE6.cjs} +11 -11
- package/dist/{chunk-ZHRU337O.cjs.map → chunk-FWPH5YE6.cjs.map} +1 -1
- package/dist/{chunk-5IZ7PLY2.cjs → chunk-FYRPN3N2.cjs} +3 -3
- package/dist/chunk-FYRPN3N2.cjs.map +1 -0
- package/dist/{chunk-H6HDETJK.cjs → chunk-GHRUS5UF.cjs} +14 -14
- package/dist/{chunk-H6HDETJK.cjs.map → chunk-GHRUS5UF.cjs.map} +1 -1
- package/dist/{chunk-5RW5ARLO.js → chunk-M35MNKDY.js} +3 -3
- package/dist/{chunk-YQVY7CWT.js → chunk-MLMQ5LGW.js} +2 -2
- package/dist/{chunk-YQVY7CWT.js.map → chunk-MLMQ5LGW.js.map} +1 -1
- package/dist/{chunk-7VGEQTJA.js → chunk-PP75SWKY.js} +2 -2
- package/dist/{chunk-IJTDND4V.cjs → chunk-QILRLRA4.cjs} +5 -5
- package/dist/{chunk-IJTDND4V.cjs.map → chunk-QILRLRA4.cjs.map} +1 -1
- package/dist/{chunk-DSDN65JH.js → chunk-TFQUMP2O.js} +2 -2
- package/dist/{chunk-RNSXRGIA.js → chunk-TLUM25FM.js} +32 -14
- package/dist/chunk-TLUM25FM.js.map +1 -0
- package/dist/{chunk-RVQPQI63.cjs → chunk-UIDCBJXR.cjs} +7 -7
- package/dist/{chunk-RVQPQI63.cjs.map → chunk-UIDCBJXR.cjs.map} +1 -1
- package/dist/{chunk-UQ4NSEXF.js → chunk-WMB3YEQQ.js} +3 -3
- package/dist/{chunk-GNOZFRKR.cjs → chunk-XD5RQKYL.cjs} +35 -17
- package/dist/chunk-XD5RQKYL.cjs.map +1 -0
- package/dist/{chunk-TZHPZGDB.js → chunk-XJQODPN6.js} +2 -2
- package/dist/cli/index.cjs +16 -16
- package/dist/cli/index.js +7 -7
- package/dist/cost/index.cjs +5 -5
- package/dist/cost/index.js +4 -4
- package/dist/index.cjs +9 -9
- package/dist/index.js +8 -8
- package/dist/models/index.cjs +6 -6
- package/dist/models/index.js +5 -5
- package/dist/profiles/index.cjs +2 -2
- package/dist/profiles/index.js +1 -1
- package/dist/sync/index.cjs +2 -2
- package/dist/sync/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-4ILJWO64.js.map +0 -1
- package/dist/chunk-5IZ7PLY2.cjs.map +0 -1
- package/dist/chunk-GNOZFRKR.cjs.map +0 -1
- package/dist/chunk-RNSXRGIA.js.map +0 -1
- package/dist/chunk-SYDW33AL.cjs.map +0 -1
- /package/dist/{chunk-5RW5ARLO.js.map → chunk-M35MNKDY.js.map} +0 -0
- /package/dist/{chunk-7VGEQTJA.js.map → chunk-PP75SWKY.js.map} +0 -0
- /package/dist/{chunk-DSDN65JH.js.map → chunk-TFQUMP2O.js.map} +0 -0
- /package/dist/{chunk-UQ4NSEXF.js.map → chunk-WMB3YEQQ.js.map} +0 -0
- /package/dist/{chunk-TZHPZGDB.js.map → chunk-XJQODPN6.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sync/modelNameResolver/resolveModelVendor.ts"],"sourcesContent":["import {\n buildModelInvocation,\n buildOpenRouterModelId,\n resolveModelIdentity,\n} from \"@x12i/ai-profiles\";\nimport type { ModelInvocationEndpoint } from \"@x12i/ai-profiles\";\nimport type { AiModelRecord } from \"../../models/types.js\";\nimport { ModelNameResolver } from \"./ModelNameResolver.js\";\nimport { PROVIDER_INFERENCE_MAP } from \"./constants.js\";\nimport { normalizeProvider, normalizeString } from \"./normalize.js\";\nimport type {\n ModelResolutionInput,\n ModelResolutionResult,\n ModelResolverOptions,\n} from \"./types.js\";\n\nfunction isOpenRouterProvider(provider?: string): boolean {\n return normalizeProvider(provider) === \"openrouter\";\n}\n\nfunction buildVendorResolveAttempts(model: string): ModelResolutionInput[] {\n const attempts: ModelResolutionInput[] = [];\n const seen = new Set<string>();\n const add = (m: string, p?: string) => {\n const key = `${p ?? \"\"}\\0${normalizeString(m)}`;\n if (seen.has(key)) return;\n seen.add(key);\n attempts.push({ model: m, provider: p });\n };\n\n add(model, undefined);\n\n const normalised = normalizeString(model);\n if (normalised.includes(\"/\")) {\n const prefix = normalised.split(\"/\")[0]!;\n if (!isOpenRouterProvider(prefix)) {\n add(model, normalizeProvider(prefix));\n }\n }\n\n add(model, \"openrouter\");\n return attempts;\n}\n\nexport type ModelVendorRef = {\n provider: string;\n model: string;\n};\n\nexport type ResolveModelVendorOptions = ModelResolverOptions & {\n /** Return OpenRouter transport shape: provider `openrouter`, model `vendor/slug`. */\n asOpenRouter?: boolean;\n};\n\nfunction endpointToRef(endpoint: ModelInvocationEndpoint): ModelVendorRef {\n return { provider: endpoint.provider, model: endpoint.modelId };\n}\n\nfunction invocationToRef(\n providerHint: string,\n modelId: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef {\n const invocation = buildModelInvocation(providerHint, normalizeString(modelId));\n if (options?.asOpenRouter) {\n return endpointToRef(\n invocation.openrouter ?? {\n provider: \"openrouter\",\n modelId: buildOpenRouterModelId(providerHint, modelId),\n },\n );\n }\n return endpointToRef(invocation.direct);\n}\n\nfunction fromAiProfilesIdentity(\n ref: NonNullable<ReturnType<typeof resolveModelIdentity>>,\n): ModelVendorRef {\n return { provider: ref.provider, model: ref.modelId };\n}\n\n/** Exact registry / bundled-catalog lookup via @x12i/ai-profiles. */\nexport function modelVendorRefFromIdentity(\n model: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n const normalised = normalizeString(model);\n if (normalised.includes(\"/\")) {\n const prefix = normalised.split(\"/\")[0]!;\n if (!isOpenRouterProvider(prefix)) {\n return invocationToRef(prefix, normalised, options);\n }\n }\n\n const identity = resolveModelIdentity(model, {\n asOpenRouter: options?.asOpenRouter,\n });\n return identity ? fromAiProfilesIdentity(identity) : null;\n}\n\n/** Build `{ provider, model }` using @x12i/ai-profiles transport mapping. */\nexport function modelVendorRefFromVendorAndSlug(\n providerHint: string,\n modelId: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef {\n return invocationToRef(providerHint, modelId, options);\n}\n\nfunction inferProviderFromSlug(\n slug: string,\n options?: ResolveModelVendorOptions,\n): string | undefined {\n const patterns = [\n ...(options?.additionalProviderPatterns ?? []),\n ...PROVIDER_INFERENCE_MAP,\n ];\n for (const { pattern, provider } of patterns) {\n if (pattern.test(slug)) return provider;\n }\n return undefined;\n}\n\nfunction providerHintForModelId(\n modelId: string,\n record: AiModelRecord | null | undefined,\n options?: ResolveModelVendorOptions,\n): string | undefined {\n if (record?.providerId) {\n const vendor = normalizeProvider(record.providerId);\n if (vendor && !isOpenRouterProvider(vendor)) return vendor;\n }\n\n const normalised = normalizeString(modelId);\n if (normalised.includes(\"/\")) {\n const prefix = normalised.split(\"/\")[0]!;\n if (!isOpenRouterProvider(prefix)) {\n return normalizeProvider(prefix) ?? prefix;\n }\n }\n\n return inferProviderFromSlug(normalised, options);\n}\n\nfunction formatModelVendorRef(\n modelId: string,\n record: AiModelRecord | null | undefined,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n const hint = providerHintForModelId(modelId, record, options);\n if (!hint) return null;\n return invocationToRef(hint, modelId, options);\n}\n\n/** Pattern inference when registry and catalog both miss. */\nexport function resolveModelVendorLastResort(\n model: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n const hint = providerHintForModelId(model, null, options);\n if (!hint) return null;\n return invocationToRef(hint, model, options);\n}\n\n/** Map a fuzzy catalog resolution result to `{ provider, model }`. */\nexport function resolveModelVendorFromResolution(\n result: ModelResolutionResult,\n inputModel: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n if (result.found) {\n const ref = formatModelVendorRef(result.modelId, result.record, options);\n if (ref) return ref;\n }\n\n if (!result.found && result.bestRejectedCandidate) {\n const ref = formatModelVendorRef(result.bestRejectedCandidate.modelId, null, options);\n if (ref) return ref;\n }\n\n return resolveModelVendorLastResort(inputModel, options);\n}\n\n/** Best-effort vendor lookup from a model name alone (sync, catalog map only). */\nexport function resolveModelVendorSync(\n model: string,\n catalog: Map<string, AiModelRecord>,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n const exact = modelVendorRefFromIdentity(model, options);\n if (exact) return exact;\n\n const resolver = new ModelNameResolver(catalog, options);\n const attempts = buildVendorResolveAttempts(model);\n let last: ModelResolutionResult | null = null;\n\n for (const attempt of attempts) {\n const result = resolver.resolve(attempt);\n last = result;\n if (result.found) {\n const ref = resolveModelVendorFromResolution(result, model, options);\n if (ref) return ref;\n }\n }\n\n return resolveModelVendorFromResolution(\n last ?? {\n found: false,\n modelId: null,\n record: null,\n attemptedStrategies: [],\n reason: \"Model not found in catalog\",\n },\n model,\n options,\n );\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,SAAS,qBAAqB,UAA4B;AACxD,SAAO,kBAAkB,QAAQ,MAAM;AACzC;AAEA,SAAS,2BAA2B,OAAuC;AACzE,QAAM,WAAmC,CAAC;AAC1C,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,MAAM,CAAC,GAAW,MAAe;AACrC,UAAM,MAAM,GAAG,KAAK,EAAE,KAAK,gBAAgB,CAAC,CAAC;AAC7C,QAAI,KAAK,IAAI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MAAM,OAAO;AACpF,QAAI,IAAK,QAAO;AAAA,EAClB;AAEA,SAAO,6BAA6B,YAAY,OAAO;AACzD;AAGO,SAAS,uBACd,OACA,SACA,SACuB;AACvB,QAAM,QAAQ,2BAA2B,OAAO,OAAO;AACvD,MAAI,MAAO,QAAO;AAElB,QAAM,WAAW,IAAI,kBAAkB,SAAS,OAAO;AACvD,QAAM,WAAW,2BAA2B,KAAK;AACjD,MAAI,OAAqC;AAEzC,aAAW,WAAW,UAAU;AAC9B,UAAM,SAAS,SAAS,QAAQ,OAAO;AACvC,WAAO;AACP,QAAI,OAAO,OAAO;AAChB,YAAM,MAAM,iCAAiC,QAAQ,OAAO,OAAO;AACnE,UAAI,IAAK,QAAO;AAAA,IAClB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,QAAQ;AAAA,MACN,OAAO;AAAA,MACP,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,qBAAqB,CAAC;AAAA,MACtB,QAAQ;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
@@ -53,6 +53,13 @@ function fromAiProfilesIdentity(ref) {
|
|
|
53
53
|
return { provider: ref.provider, model: ref.modelId };
|
|
54
54
|
}
|
|
55
55
|
function modelVendorRefFromIdentity(model, options) {
|
|
56
|
+
const normalised = _chunkOZE336BLcjs.normalizeString.call(void 0, model);
|
|
57
|
+
if (normalised.includes("/")) {
|
|
58
|
+
const prefix = normalised.split("/")[0];
|
|
59
|
+
if (!isOpenRouterProvider(prefix)) {
|
|
60
|
+
return invocationToRef(prefix, normalised, options);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
56
63
|
const identity = _aiprofiles.resolveModelIdentity.call(void 0, model, {
|
|
57
64
|
asOpenRouter: _optionalChain([options, 'optionalAccess', _2 => _2.asOpenRouter])
|
|
58
65
|
});
|
|
@@ -140,4 +147,4 @@ function resolveModelVendorSync(model, catalog, options) {
|
|
|
140
147
|
|
|
141
148
|
|
|
142
149
|
exports.modelVendorRefFromIdentity = modelVendorRefFromIdentity; exports.modelVendorRefFromVendorAndSlug = modelVendorRefFromVendorAndSlug; exports.resolveModelVendorLastResort = resolveModelVendorLastResort; exports.resolveModelVendorFromResolution = resolveModelVendorFromResolution; exports.resolveModelVendorSync = resolveModelVendorSync;
|
|
143
|
-
//# sourceMappingURL=chunk-
|
|
150
|
+
//# sourceMappingURL=chunk-EDZOFPLV.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-EDZOFPLV.cjs","../src/sync/modelNameResolver/resolveModelVendor.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACPA;AACE;AACA;AACA;AAAA,+CACK;AAYP,SAAS,oBAAA,CAAqB,QAAA,EAA4B;AACxD,EAAA,OAAO,iDAAA,QAA0B,EAAA,IAAM,YAAA;AACzC;AAEA,SAAS,0BAAA,CAA2B,KAAA,EAAuC;AACzE,EAAA,MAAM,SAAA,EAAmC,CAAC,CAAA;AAC1C,EAAA,MAAM,KAAA,kBAAO,IAAI,GAAA,CAAY,CAAA;AAC7B,EAAA,MAAM,IAAA,EAAM,CAAC,CAAA,EAAW,CAAA,EAAA,GAAe;AACrC,IAAA,MAAM,IAAA,EAAM,CAAA,mBAAA;AACC,IAAA;AACD,IAAA;AACH,IAAA;AACX,EAAA;AAEW,EAAA;AAEL,EAAA;AACS,EAAA;AACP,IAAA;AACD,IAAA;AACQ,MAAA;AACb,IAAA;AACF,EAAA;AAEW,EAAA;AACJ,EAAA;AACT;AAYS;AACE,EAAA;AACX;AAES;AAKD,EAAA;AACO,EAAA;AACJ,IAAA;AACM,uBAAA;AACT,QAAA;AACS,QAAA;AACX,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAES;AAGE,EAAA;AACX;AAGgB;AAIR,EAAA;AACS,EAAA;AACP,IAAA;AACD,IAAA;AACI,MAAA;AACT,IAAA;AACF,EAAA;AAEM,EAAA;AACJ,IAAA;AACD,EAAA;AACM,EAAA;AACT;AAGgB;AAKP,EAAA;AACT;AAES;AAID,EAAA;AACS,IAAA;AACV,IAAA;AACL,EAAA;AACa,EAAA;AACC,IAAA;AACd,EAAA;AACO,EAAA;AACT;AAES;AAKK,EAAA;AACJ,IAAA;AACF,IAAA;AACN,EAAA;AAEM,EAAA;AACS,EAAA;AACP,IAAA;AACD,IAAA;AACI,MAAA;AACT,IAAA;AACF,EAAA;AAEO,EAAA;AACT;AAES;AAKM,EAAA;AACF,EAAA;AACJ,EAAA;AACT;AAGgB;AAID,EAAA;AACF,EAAA;AACJ,EAAA;AACT;AAGgB;AAKH,EAAA;AACG,IAAA;AACH,IAAA;AACX,EAAA;AAEY,EAAA;AACE,IAAA;AACH,IAAA;AACX,EAAA;AAEO,EAAA;AACT;AAGgB;AAKA,EAAA;AACH,EAAA;AAEL,EAAA;AACA,EAAA;AACmC,EAAA;AAE9B,EAAA;AACH,IAAA;AACC,IAAA;AACI,IAAA;AACH,MAAA;AACG,MAAA;AACX,IAAA;AACF,EAAA;AAEO,EAAA;AACG,qBAAA;AACC,MAAA;AACE,MAAA;AACD,MAAA;AACR,MAAA;AACQ,MAAA;AACV,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACF;AD3EiB;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-EDZOFPLV.cjs","sourcesContent":[null,"import {\n buildModelInvocation,\n buildOpenRouterModelId,\n resolveModelIdentity,\n} from \"@x12i/ai-profiles\";\nimport type { ModelInvocationEndpoint } from \"@x12i/ai-profiles\";\nimport type { AiModelRecord } from \"../../models/types.js\";\nimport { ModelNameResolver } from \"./ModelNameResolver.js\";\nimport { PROVIDER_INFERENCE_MAP } from \"./constants.js\";\nimport { normalizeProvider, normalizeString } from \"./normalize.js\";\nimport type {\n ModelResolutionInput,\n ModelResolutionResult,\n ModelResolverOptions,\n} from \"./types.js\";\n\nfunction isOpenRouterProvider(provider?: string): boolean {\n return normalizeProvider(provider) === \"openrouter\";\n}\n\nfunction buildVendorResolveAttempts(model: string): ModelResolutionInput[] {\n const attempts: ModelResolutionInput[] = [];\n const seen = new Set<string>();\n const add = (m: string, p?: string) => {\n const key = `${p ?? \"\"}\\0${normalizeString(m)}`;\n if (seen.has(key)) return;\n seen.add(key);\n attempts.push({ model: m, provider: p });\n };\n\n add(model, undefined);\n\n const normalised = normalizeString(model);\n if (normalised.includes(\"/\")) {\n const prefix = normalised.split(\"/\")[0]!;\n if (!isOpenRouterProvider(prefix)) {\n add(model, normalizeProvider(prefix));\n }\n }\n\n add(model, \"openrouter\");\n return attempts;\n}\n\nexport type ModelVendorRef = {\n provider: string;\n model: string;\n};\n\nexport type ResolveModelVendorOptions = ModelResolverOptions & {\n /** Return OpenRouter transport shape: provider `openrouter`, model `vendor/slug`. */\n asOpenRouter?: boolean;\n};\n\nfunction endpointToRef(endpoint: ModelInvocationEndpoint): ModelVendorRef {\n return { provider: endpoint.provider, model: endpoint.modelId };\n}\n\nfunction invocationToRef(\n providerHint: string,\n modelId: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef {\n const invocation = buildModelInvocation(providerHint, normalizeString(modelId));\n if (options?.asOpenRouter) {\n return endpointToRef(\n invocation.openrouter ?? {\n provider: \"openrouter\",\n modelId: buildOpenRouterModelId(providerHint, modelId),\n },\n );\n }\n return endpointToRef(invocation.direct);\n}\n\nfunction fromAiProfilesIdentity(\n ref: NonNullable<ReturnType<typeof resolveModelIdentity>>,\n): ModelVendorRef {\n return { provider: ref.provider, model: ref.modelId };\n}\n\n/** Exact registry / bundled-catalog lookup via @x12i/ai-profiles. */\nexport function modelVendorRefFromIdentity(\n model: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n const normalised = normalizeString(model);\n if (normalised.includes(\"/\")) {\n const prefix = normalised.split(\"/\")[0]!;\n if (!isOpenRouterProvider(prefix)) {\n return invocationToRef(prefix, normalised, options);\n }\n }\n\n const identity = resolveModelIdentity(model, {\n asOpenRouter: options?.asOpenRouter,\n });\n return identity ? fromAiProfilesIdentity(identity) : null;\n}\n\n/** Build `{ provider, model }` using @x12i/ai-profiles transport mapping. */\nexport function modelVendorRefFromVendorAndSlug(\n providerHint: string,\n modelId: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef {\n return invocationToRef(providerHint, modelId, options);\n}\n\nfunction inferProviderFromSlug(\n slug: string,\n options?: ResolveModelVendorOptions,\n): string | undefined {\n const patterns = [\n ...(options?.additionalProviderPatterns ?? []),\n ...PROVIDER_INFERENCE_MAP,\n ];\n for (const { pattern, provider } of patterns) {\n if (pattern.test(slug)) return provider;\n }\n return undefined;\n}\n\nfunction providerHintForModelId(\n modelId: string,\n record: AiModelRecord | null | undefined,\n options?: ResolveModelVendorOptions,\n): string | undefined {\n if (record?.providerId) {\n const vendor = normalizeProvider(record.providerId);\n if (vendor && !isOpenRouterProvider(vendor)) return vendor;\n }\n\n const normalised = normalizeString(modelId);\n if (normalised.includes(\"/\")) {\n const prefix = normalised.split(\"/\")[0]!;\n if (!isOpenRouterProvider(prefix)) {\n return normalizeProvider(prefix) ?? prefix;\n }\n }\n\n return inferProviderFromSlug(normalised, options);\n}\n\nfunction formatModelVendorRef(\n modelId: string,\n record: AiModelRecord | null | undefined,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n const hint = providerHintForModelId(modelId, record, options);\n if (!hint) return null;\n return invocationToRef(hint, modelId, options);\n}\n\n/** Pattern inference when registry and catalog both miss. */\nexport function resolveModelVendorLastResort(\n model: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n const hint = providerHintForModelId(model, null, options);\n if (!hint) return null;\n return invocationToRef(hint, model, options);\n}\n\n/** Map a fuzzy catalog resolution result to `{ provider, model }`. */\nexport function resolveModelVendorFromResolution(\n result: ModelResolutionResult,\n inputModel: string,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n if (result.found) {\n const ref = formatModelVendorRef(result.modelId, result.record, options);\n if (ref) return ref;\n }\n\n if (!result.found && result.bestRejectedCandidate) {\n const ref = formatModelVendorRef(result.bestRejectedCandidate.modelId, null, options);\n if (ref) return ref;\n }\n\n return resolveModelVendorLastResort(inputModel, options);\n}\n\n/** Best-effort vendor lookup from a model name alone (sync, catalog map only). */\nexport function resolveModelVendorSync(\n model: string,\n catalog: Map<string, AiModelRecord>,\n options?: ResolveModelVendorOptions,\n): ModelVendorRef | null {\n const exact = modelVendorRefFromIdentity(model, options);\n if (exact) return exact;\n\n const resolver = new ModelNameResolver(catalog, options);\n const attempts = buildVendorResolveAttempts(model);\n let last: ModelResolutionResult | null = null;\n\n for (const attempt of attempts) {\n const result = resolver.resolve(attempt);\n last = result;\n if (result.found) {\n const ref = resolveModelVendorFromResolution(result, model, options);\n if (ref) return ref;\n }\n }\n\n return resolveModelVendorFromResolution(\n last ?? {\n found: false,\n modelId: null,\n record: null,\n attemptedStrategies: [],\n reason: \"Model not found in catalog\",\n },\n model,\n options,\n );\n}\n"]}
|
|
@@ -3,39 +3,39 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkEDZOFPLVcjs = require('./chunk-EDZOFPLV.cjs');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
var
|
|
11
|
+
var _chunkXD5RQKYLcjs = require('./chunk-XD5RQKYL.cjs');
|
|
12
12
|
|
|
13
13
|
// src/cost/resolveModelVendor.ts
|
|
14
14
|
async function resolveModelVendor(model, catalog, options) {
|
|
15
|
-
const exact =
|
|
15
|
+
const exact = _chunkEDZOFPLVcjs.modelVendorRefFromIdentity.call(void 0, model, options);
|
|
16
16
|
if (exact) return exact;
|
|
17
|
-
const attempts =
|
|
18
|
-
const result = await
|
|
17
|
+
const attempts = _chunkXD5RQKYLcjs.buildCatalogResolveAttempts.call(void 0, model);
|
|
18
|
+
const result = await _chunkXD5RQKYLcjs.resolveFromCatalogAttempts.call(void 0, catalog, attempts, options);
|
|
19
19
|
if (_optionalChain([result, 'optionalAccess', _ => _.found])) {
|
|
20
|
-
const ref =
|
|
20
|
+
const ref = _chunkEDZOFPLVcjs.resolveModelVendorFromResolution.call(void 0, result, model, options);
|
|
21
21
|
if (ref) return ref;
|
|
22
22
|
}
|
|
23
|
-
const profileMatch = await
|
|
23
|
+
const profileMatch = await _chunkXD5RQKYLcjs.matchModelInAiProfiles.call(void 0, model);
|
|
24
24
|
if (profileMatch) {
|
|
25
|
-
return
|
|
25
|
+
return _chunkEDZOFPLVcjs.modelVendorRefFromVendorAndSlug.call(void 0,
|
|
26
26
|
profileMatch.provider,
|
|
27
27
|
profileMatch.modelId,
|
|
28
28
|
options
|
|
29
29
|
);
|
|
30
30
|
}
|
|
31
31
|
if (!_optionalChain([result, 'optionalAccess', _2 => _2.found]) && _optionalChain([result, 'optionalAccess', _3 => _3.bestRejectedCandidate])) {
|
|
32
|
-
const ref =
|
|
32
|
+
const ref = _chunkEDZOFPLVcjs.resolveModelVendorFromResolution.call(void 0, result, model, options);
|
|
33
33
|
if (ref) return ref;
|
|
34
34
|
}
|
|
35
|
-
return
|
|
35
|
+
return _chunkEDZOFPLVcjs.resolveModelVendorLastResort.call(void 0, model, options);
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
|
|
39
39
|
|
|
40
40
|
exports.resolveModelVendor = resolveModelVendor;
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
//# sourceMappingURL=chunk-FWPH5YE6.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-FWPH5YE6.cjs","../src/cost/resolveModelVendor.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACUA,MAAA,SAAsB,kBAAA,CACpB,KAAA,EACA,OAAA,EACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,EAAQ,0DAAA,KAA2B,EAAO,OAAO,CAAA;AACvD,EAAA,GAAA,CAAI,KAAA,EAAO,OAAO,KAAA;AAElB,EAAA,MAAM,SAAA,EAAW,2DAAA,KAAiC,CAAA;AAClD,EAAA,MAAM,OAAA,EAAS,MAAM,0DAAA,OAA2B,EAAS,QAAA,EAAU,OAAO,CAAA;AAE1E,EAAA,GAAA,iBAAI,MAAA,2BAAQ,OAAA,EAAO;AACjB,IAAA,MAAM,IAAA,EAAM,gEAAA,MAAiC,EAAQ,KAAA,EAAO,OAAO,CAAA;AACnE,IAAA,GAAA,CAAI,GAAA,EAAK,OAAO,GAAA;AAAA,EAClB;AAEA,EAAA,MAAM,aAAA,EAAe,MAAM,sDAAA,KAA4B,CAAA;AACvD,EAAA,GAAA,CAAI,YAAA,EAAc;AAChB,IAAA,OAAO,+DAAA;AAAA,MACL,YAAA,CAAa,QAAA;AAAA,MACb,YAAA,CAAa,OAAA;AAAA,MACb;AAAA,IACF,CAAA;AAAA,EACF;AAEA,EAAA,GAAA,CAAI,iBAAC,MAAA,6BAAQ,QAAA,mBAAS,MAAA,6BAAQ,uBAAA,EAAuB;AACnD,IAAA,MAAM,IAAA,EAAM,gEAAA,MAAiC,EAAQ,KAAA,EAAO,OAAO,CAAA;AACnE,IAAA,GAAA,CAAI,GAAA,EAAK,OAAO,GAAA;AAAA,EAClB;AAEA,EAAA,OAAO,4DAAA,KAA6B,EAAO,OAAO,CAAA;AACpD;ADjBA;AACA;AACE;AACF,gDAAC","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-FWPH5YE6.cjs","sourcesContent":[null,"import type { AiModelsCatalogClient } from \"../catalog/AiModelsCatalogClient.js\";\nimport {\n modelVendorRefFromIdentity,\n modelVendorRefFromVendorAndSlug,\n resolveModelVendorFromResolution,\n resolveModelVendorLastResort,\n type ModelVendorRef,\n type ResolveModelVendorOptions,\n} from \"../sync/modelNameResolver/resolveModelVendor.js\";\nimport { matchModelInAiProfiles } from \"./aiProfilesMatch.js\";\nimport { buildCatalogResolveAttempts, resolveFromCatalogAttempts } from \"./costModelResolution.js\";\n\nexport type { ModelVendorRef, ResolveModelVendorOptions };\nexport {\n resolveModelVendorFromResolution,\n resolveModelVendorSync,\n resolveModelVendorLastResort,\n modelVendorRefFromIdentity,\n modelVendorRefFromVendorAndSlug,\n} from \"../sync/modelNameResolver/resolveModelVendor.js\";\n\n/** Best-effort vendor lookup from a model name alone (catalog + ai-profiles). */\nexport async function resolveModelVendor(\n model: string,\n catalog: AiModelsCatalogClient,\n options?: ResolveModelVendorOptions,\n): Promise<ModelVendorRef | null> {\n const exact = modelVendorRefFromIdentity(model, options);\n if (exact) return exact;\n\n const attempts = buildCatalogResolveAttempts(model);\n const result = await resolveFromCatalogAttempts(catalog, attempts, options);\n\n if (result?.found) {\n const ref = resolveModelVendorFromResolution(result, model, options);\n if (ref) return ref;\n }\n\n const profileMatch = await matchModelInAiProfiles(model);\n if (profileMatch) {\n return modelVendorRefFromVendorAndSlug(\n profileMatch.provider,\n profileMatch.modelId,\n options,\n );\n }\n\n if (!result?.found && result?.bestRejectedCandidate) {\n const ref = resolveModelVendorFromResolution(result, model, options);\n if (ref) return ref;\n }\n\n return resolveModelVendorLastResort(model, options);\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true})
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/profiles/resolveProfileForAsk.ts
|
|
2
2
|
var _aiprofiles = require('@x12i/ai-profiles');
|
|
3
3
|
function profileConfigFromResolved(resolved) {
|
|
4
4
|
return {
|
|
@@ -27,7 +27,7 @@ async function resolveProfileForAsk(input) {
|
|
|
27
27
|
const resolved = await _aiprofiles.resolveAIProfile.call(void 0, input.profile, {
|
|
28
28
|
choice: input.choice,
|
|
29
29
|
source: input.source,
|
|
30
|
-
refresh: input.refresh
|
|
30
|
+
refresh: _nullishCoalesce(input.refresh, () => ( (input.source !== void 0 && input.source !== "auto" ? true : void 0)))
|
|
31
31
|
});
|
|
32
32
|
return profileConfigFromResolved(resolved);
|
|
33
33
|
}
|
|
@@ -48,4 +48,4 @@ async function resolveProfileForAsk(input) {
|
|
|
48
48
|
|
|
49
49
|
|
|
50
50
|
exports.profileConfigFromResolved = profileConfigFromResolved; exports.resolveProfileForAsk = resolveProfileForAsk; exports.resolveAIProfile = _aiprofiles.resolveAIProfile; exports.listAIProfiles = _aiprofiles.listAIProfiles; exports.listAIShortcuts = _aiprofiles.listAIShortcuts; exports.isKnownProfileOrShortcut = _aiprofiles.isKnownProfileOrShortcut;
|
|
51
|
-
//# sourceMappingURL=chunk-
|
|
51
|
+
//# sourceMappingURL=chunk-FYRPN3N2.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-FYRPN3N2.cjs","../src/profiles/resolveProfileForAsk.ts","../src/profiles/index.ts"],"names":[],"mappings":"AAAA;ACAA,+CAAiC;AAsC1B,SAAS,yBAAA,CACd,QAAA,EACuB;AACvB,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,QAAA,CAAS,QAAA;AAAA,IACnB,KAAA,EAAO,QAAA,CAAS,OAAA;AAAA,IAChB,eAAA,EAAiB,QAAA,CAAS,eAAA;AAAA,IAC1B,OAAA,EAAS,QAAA,CAAS,OAAA;AAAA,IAClB,OAAA,EAAS,QAAA,CAAS,OAAA;AAAA,IAClB,MAAA,EAAQ,QAAA,CAAS,MAAA;AAAA,IACjB,WAAA,EAAa,QAAA,CAAS,OAAA,CAAQ,WAAA;AAAA,IAC9B,UAAA,EAAY,QA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;AFkBF;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,iWAAC","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-FYRPN3N2.cjs","sourcesContent":[null,"import { resolveAIProfile } from \"@x12i/ai-profiles\";\nimport type {\n AIProfileBackend,\n InstructionTier,\n RegistrySourceMode,\n ResolvedAIProfile,\n} from \"@x12i/ai-profiles\";\n\nexport type ResolveProfileForAskInput = {\n profile: string;\n choice?: string;\n source?: RegistrySourceMode;\n refresh?: boolean;\n};\n\n/** FuncX / ask-node model config derived from {@link ResolvedAIProfile}. */\nexport type AskProfileModelConfig = {\n provider: ResolvedAIProfile[\"provider\"];\n model: string;\n instructionTier: InstructionTier;\n backend: AIProfileBackend;\n profile: string;\n choice: string;\n temperature: number;\n outputMode: ResolvedAIProfile[\"runtime\"][\"outputMode\"];\n toolPolicy: ResolvedAIProfile[\"runtime\"][\"toolPolicy\"];\n reasoningEffort: ResolvedAIProfile[\"runtime\"][\"reasoningEffort\"];\n executionMode: ResolvedAIProfile[\"runtime\"][\"executionMode\"];\n requireCitations: boolean;\n allowWeb: boolean;\n allowFileSearch: boolean;\n allowCodeExecution: boolean;\n humanReview: ResolvedAIProfile[\"runtime\"][\"humanReview\"];\n metadata?: Record<string, unknown>;\n pricing?: ResolvedAIProfile[\"pricing\"];\n resolved: ResolvedAIProfile;\n};\n\nexport function profileConfigFromResolved(\n resolved: ResolvedAIProfile,\n): AskProfileModelConfig {\n return {\n provider: resolved.provider,\n model: resolved.modelId,\n instructionTier: resolved.instructionTier,\n backend: resolved.backend,\n profile: resolved.profile,\n choice: resolved.choice,\n temperature: resolved.runtime.temperature,\n outputMode: resolved.runtime.outputMode,\n toolPolicy: resolved.runtime.toolPolicy,\n reasoningEffort: resolved.runtime.reasoningEffort,\n executionMode: resolved.runtime.executionMode,\n requireCitations: resolved.runtime.requireCitations,\n allowWeb: resolved.runtime.allowWeb,\n allowFileSearch: resolved.runtime.allowFileSearch,\n allowCodeExecution: resolved.runtime.allowCodeExecution,\n humanReview: resolved.runtime.humanReview,\n ...(resolved.metadata !== undefined ? { metadata: resolved.metadata } : {}),\n ...(resolved.pricing !== undefined ? { pricing: resolved.pricing } : {}),\n resolved,\n };\n}\n\n/**\n * Resolve a profile (+ optional choice) into ask-node / FuncX model configuration.\n * Uses {@link ResolvedAIProfile.instructionTier} and {@link ResolvedAIProfile.backend}\n * from `@x12i/ai-profiles` — do not duplicate preset tables locally.\n */\nexport async function resolveProfileForAsk(\n input: ResolveProfileForAskInput,\n): Promise<AskProfileModelConfig> {\n const resolved = await resolveAIProfile(input.profile, {\n choice: input.choice,\n source: input.source,\n refresh:\n input.refresh ??\n (input.source !== undefined && input.source !== \"auto\" ? true : undefined),\n });\n return profileConfigFromResolved(resolved);\n}\n","export {\n resolveProfileForAsk,\n profileConfigFromResolved,\n} from \"./resolveProfileForAsk.js\";\nexport type {\n AskProfileModelConfig,\n ResolveProfileForAskInput,\n} from \"./resolveProfileForAsk.js\";\n\nexport type {\n ResolvedAIProfile,\n InstructionTier,\n AIProfileBackend,\n AIProfileSummary,\n AIShortcutSummary,\n ResolveAIProfileOptions,\n RegistrySourceMode,\n} from \"@x12i/ai-profiles\";\n\nexport {\n resolveAIProfile,\n listAIProfiles,\n listAIShortcuts,\n isKnownProfileOrShortcut,\n} from \"@x12i/ai-profiles\";\n"]}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
|
-
var
|
|
8
|
+
var _chunkXD5RQKYLcjs = require('./chunk-XD5RQKYL.cjs');
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
|
|
@@ -497,29 +497,29 @@ var CostCalculator = class {
|
|
|
497
497
|
...this.resolverOptions,
|
|
498
498
|
aliasRegistry: _nullishCoalesce(this.aliasRegistry, () => ( _optionalChain([this, 'access', _11 => _11.resolverOptions, 'optionalAccess', _12 => _12.aliasRegistry])))
|
|
499
499
|
};
|
|
500
|
-
let resolved = await
|
|
500
|
+
let resolved = await _chunkXD5RQKYLcjs.resolveFromCatalogAttempts.call(void 0,
|
|
501
501
|
this.catalog,
|
|
502
|
-
|
|
502
|
+
_chunkXD5RQKYLcjs.buildCatalogResolveAttempts.call(void 0, modelInput, input.provider),
|
|
503
503
|
resolverOpts
|
|
504
504
|
);
|
|
505
|
-
if (
|
|
505
|
+
if (_chunkXD5RQKYLcjs.isLocalProviderResolution.call(void 0, resolved, input.provider)) {
|
|
506
506
|
return this.localProviderResult(modelInput, input, resolved);
|
|
507
507
|
}
|
|
508
508
|
let profileMatch = null;
|
|
509
509
|
const warnings = [];
|
|
510
510
|
if (!_optionalChain([resolved, 'optionalAccess', _13 => _13.found]) || !resolved.record) {
|
|
511
|
-
if (!
|
|
512
|
-
profileMatch = await
|
|
511
|
+
if (!_chunkXD5RQKYLcjs.isLocalProvider.call(void 0, input.provider)) {
|
|
512
|
+
profileMatch = await _chunkXD5RQKYLcjs.matchModelInAiProfiles.call(void 0, modelInput, input.provider);
|
|
513
513
|
}
|
|
514
514
|
if (profileMatch) {
|
|
515
|
-
resolved = await
|
|
515
|
+
resolved = await _chunkXD5RQKYLcjs.resolveFromCatalogAttempts.call(void 0,
|
|
516
516
|
this.catalog,
|
|
517
517
|
mergeAttempts(
|
|
518
|
-
|
|
518
|
+
_chunkXD5RQKYLcjs.buildCatalogResolveAttempts.call(void 0,
|
|
519
519
|
profileMatch.canonicalModelId,
|
|
520
520
|
_nullishCoalesce(input.provider, () => ( profileMatch.provider))
|
|
521
521
|
),
|
|
522
|
-
|
|
522
|
+
_chunkXD5RQKYLcjs.buildCatalogResolveAttempts.call(void 0,
|
|
523
523
|
profileMatch.canonicalModelId,
|
|
524
524
|
profileMatch.provider
|
|
525
525
|
)
|
|
@@ -527,11 +527,11 @@ var CostCalculator = class {
|
|
|
527
527
|
resolverOpts
|
|
528
528
|
);
|
|
529
529
|
}
|
|
530
|
-
if (
|
|
530
|
+
if (_chunkXD5RQKYLcjs.isLocalProviderResolution.call(void 0, resolved, input.provider)) {
|
|
531
531
|
return this.localProviderResult(modelInput, input, resolved);
|
|
532
532
|
}
|
|
533
533
|
if ((!_optionalChain([resolved, 'optionalAccess', _14 => _14.found]) || !resolved.record) && _optionalChain([profileMatch, 'optionalAccess', _15 => _15.pricing])) {
|
|
534
|
-
const routedViaOpenRouter2 =
|
|
534
|
+
const routedViaOpenRouter2 = _chunkXD5RQKYLcjs.resolveRoutedViaOpenRouter.call(void 0,
|
|
535
535
|
input.provider,
|
|
536
536
|
resolved,
|
|
537
537
|
profileMatch.canonicalModelId,
|
|
@@ -582,7 +582,7 @@ var CostCalculator = class {
|
|
|
582
582
|
return this.unknownModelResult(modelInput, input, resolved);
|
|
583
583
|
}
|
|
584
584
|
const { record, modelId } = resolved;
|
|
585
|
-
const routedViaOpenRouter =
|
|
585
|
+
const routedViaOpenRouter = _chunkXD5RQKYLcjs.resolveRoutedViaOpenRouter.call(void 0,
|
|
586
586
|
input.provider,
|
|
587
587
|
resolved,
|
|
588
588
|
modelId,
|
|
@@ -676,7 +676,7 @@ var CostCalculator = class {
|
|
|
676
676
|
{
|
|
677
677
|
cost: 0,
|
|
678
678
|
resolvedModelId: modelInput,
|
|
679
|
-
routedViaOpenRouter:
|
|
679
|
+
routedViaOpenRouter: _chunkXD5RQKYLcjs.resolveRoutedViaOpenRouter.call(void 0,
|
|
680
680
|
input.provider,
|
|
681
681
|
resolved,
|
|
682
682
|
modelInput,
|
|
@@ -702,4 +702,4 @@ var CostCalculator = class {
|
|
|
702
702
|
|
|
703
703
|
|
|
704
704
|
exports.DEFAULT_OPENROUTER_MARKUP_RATE = DEFAULT_OPENROUTER_MARKUP_RATE; exports.toCostExtraction = toCostExtraction; exports.enrichCostResult = enrichCostResult; exports.MODEL_FIELD_PRIORITY = MODEL_FIELD_PRIORITY; exports.extractUsageInput = extractUsageInput; exports.resolveUsageModel = resolveUsageModel; exports.CostCalculator = CostCalculator;
|
|
705
|
-
//# sourceMappingURL=chunk-
|
|
705
|
+
//# sourceMappingURL=chunk-GHRUS5UF.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-H6HDETJK.cjs","../src/cost/constants.ts","../src/cost/enrichCostResult.ts","../src/cost/extractUsageInput.ts","../src/cost/resolveUsageModel.ts","../src/cost/profilePricing.ts","../src/cost/CostCalculator.ts"],"names":["routedViaOpenRouter","pricing","cost","breakdown"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACfO,IAAM,+BAAA,EAAiC,IAAA;AAGvC,IAAM,iCAAA,EAAmC,GAAA;ADehD;AACA;AEjBO,SAAS,gBAAA,CACd,UAAA,EACkB;AAClB,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,EAAE,KAAA,EAAO,UAAA,CAAW,KAAA,CAAM,KAAA,EAAO,IAAA,EAAM,UAAA,CAAW,KAAA,CAAM,KAAK,CAAA;AAAA,IACpE,MAAA,EAAQ;AAAA,MACN,MAAA,EAAQ,UAAA,CAAW,MAAA,CAAO,MAAA;AAAA,MAC1B,IAAA,EAAM,UAAA,CAAW,MAAA,CAAO,IAAA;AAAA,MACxB,SAAA,EAAW,UAAA,CAAW,MAAA,CAAO;AAAA,IAC/B,CAAA;AAAA,IACA,GAAI,UAAA,CAAW,UAAA,EACX;AAAA,MACE,SAAA,EAAW;AAAA,QACT,KAAA,EAAO,UAAA,CAAW,SAAA,CAAU,KAAA;AAAA,QAC5B,IAAA,EAAM,UAAA,CAAW,SAAA,CAAU;AAAA,MAC7B;AAAA,IACF,EAAA,EACA,CAAC,CAAA;AAAA,IACL,GAAI,UAAA,CAAW,SAAA,EACX;AAAA,MACE,QAAA,EAAU;AAAA,QACR,KAAA,EAAO,UAAA,CAAW,QAAA,CAAS,KAAA;AAAA,QAC3B,IAAA,EAAM,UAAA,CAAW,QAAA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A,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AAIE,EAAA;AAGuB,IAAA;AACA,IAAA;AAEI,IAAA;AACF,IAAA;AACE,IAAA;AAEV,IAAA;AAEf,IAAA;AAEe,MAAA;AACf,IAAA;AAEA,IAAA;AAEmB,IAAA;AAEd,IAAA;AACL,MAAA;AACQ,QAAA;AACG,QAAA;AACX,MAAA;AACF,IAAA;AACF,EAAA;AAQE,EAAA;AAEiB,IAAA;AACW,IAAA;AAC1B,MAAA;AACQ,MAAA;AACR,MAAA;AACF,IAAA;AAC4B,IAAA;AACD,MAAA;AAC3B,IAAA;AACO,IAAA;AACT,EAAA;AAGE,EAAA;AAIkC,IAAA;AAChC,MAAA;AACQ,QAAA;AACG,QAAA;AACX,MAAA;AACF,IAAA;AAC2B,IAAA;AACf,IAAA;AACV,MAAA;AACQ,QAAA;AACW,QAAA;AACI,QAAA;AACJ,QAAA;AACA,QAAA;AACT,QAAA;AACR,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AAGE,EAAA;AAIS,IAAA;AACG,MAAA;AACZ,IAAA;AAEkC,IAAA;AAChC,MAAA;AACQ,QAAA;AACG,QAAA;AACX,MAAA;AACF,IAAA;AAC2B,IAAA;AAEf,IAAA;AACV,MAAA;AACQ,QAAA;AACW,QAAA;AACI,QAAA;AACb,UAAA;AACN,UAAA;AACA,UAAA;AACsB,0BAAA;AACxB,QAAA;AACiB,QAAA;AACA,QAAA;AACT,QAAA;AACM,QAAA;AACd,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AACF;ANqVgC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-H6HDETJK.cjs","sourcesContent":[null,"/** Default OpenRouter platform surcharge when catalog markup fields are absent (5%). */\nexport const DEFAULT_OPENROUTER_MARKUP_RATE = 0.05;\n\n/** ai-profiles tiered pricing threshold (tokens). */\nexport const PROFILE_TIERED_CONTEXT_THRESHOLD = 200_000;\n","import type { ExtractUsageInputResult } from \"./extractUsageInput.js\";\nimport type { AiCostExtraction, AiCostResult, AiUsageInput } from \"./types.js\";\n\nexport function toCostExtraction(\n provenance: ExtractUsageInputResult[\"provenance\"],\n): AiCostExtraction {\n return {\n model: { field: provenance.model.field, path: provenance.model.path },\n tokens: {\n source: provenance.tokens.source,\n path: provenance.tokens.path,\n estimated: provenance.tokens.estimated,\n },\n ...(provenance.modelUsed\n ? {\n modelUsed: {\n field: provenance.modelUsed.field,\n path: provenance.modelUsed.path,\n },\n }\n : {}),\n ...(provenance.provider\n ? {\n provider: {\n field: provenance.provider.field,\n path: provenance.provider.path,\n },\n }\n : {}),\n };\n}\n\n/** Attach usage, provider, and model fields callers expect on every cost response. */\nexport function enrichCostResult(\n result: Omit<\n AiCostResult,\n \"usage\" | \"provider\" | \"usedModel\" | \"model\" | \"extraction\"\n >,\n input: AiUsageInput,\n extraction?: AiCostExtraction,\n): AiCostResult {\n /** Original model id from the caller — never replaced by catalog resolution. */\n const receivedModelId = input.usedModel ?? input.modelUsed ?? input.model;\n\n return {\n ...result,\n provider: input.provider,\n usage: { ...input.tokens },\n ...(receivedModelId ? { usedModel: receivedModelId } : {}),\n ...(input.model && input.model !== receivedModelId ? { model: input.model } : {}),\n ...(extraction ? { extraction } : {}),\n };\n}\n","import type { AiUsageInput } from \"./types.js\";\n\n/** Model id field priority (higher wins). Runtime ids beat request/config aliases. */\nexport const MODEL_FIELD_PRIORITY: readonly { key: string; score: number }[] = [\n { key: \"usedModel\", score: 1000 },\n { key: \"modelUsed\", score: 990 },\n { key: \"resolvedModel\", score: 980 },\n { key: \"model\", score: 500 },\n { key: \"xynthesisModel\", score: 120 },\n { key: \"skillModel\", score: 110 },\n] as const;\n\n/** Path segments that boost or penalize a model candidate. */\nconst MODEL_PATH_BONUS: readonly { pattern: RegExp; bonus: number }[] = [\n { pattern: /(^|\\.)response(\\.|$)/i, bonus: 40 },\n { pattern: /(^|\\.)outer\\.input(\\.|$)/i, bonus: 35 },\n { pattern: /(^|\\.)config(?!\\.rawConfig)(\\.|$)/i, bonus: 30 },\n { pattern: /(^|\\.)outer\\.input\\.config(\\.|$)/i, bonus: 28 },\n { pattern: /(^|\\.)usage(\\.|$)/i, bonus: 15 },\n { pattern: /(^|\\.)rawConfig(\\.|$)/i, bonus: -40 },\n { pattern: /workingMemory/i, bonus: -50 },\n { pattern: /requestExample/i, bonus: -80 },\n { pattern: /graphsStudio/i, bonus: -80 },\n];\n\nconst PROVIDER_FIELD_PRIORITY: readonly { key: string; score: number }[] = [\n { key: \"provider\", score: 500 },\n { key: \"providerId\", score: 480 },\n] as const;\n\nconst PROVIDER_PATH_BONUS: readonly { pattern: RegExp; bonus: number }[] = [\n { pattern: /(^|\\.)config(?!\\.rawConfig)(\\.|$)/i, bonus: 30 },\n { pattern: /(^|\\.)outer\\.input(\\.|$)/i, bonus: 20 },\n { pattern: /(^|\\.)rawConfig(\\.|$)/i, bonus: -20 },\n];\n\nconst PROMPT_TOKEN_KEYS = new Set([\n \"prompt\",\n \"prompt_tokens\",\n \"promptTokens\",\n \"input_tokens\",\n \"inputTokens\",\n \"estimatedInputTokens\",\n \"input\",\n]);\n\nconst COMPLETION_TOKEN_KEYS = new Set([\n \"completion\",\n \"completion_tokens\",\n \"completionTokens\",\n \"output_tokens\",\n \"outputTokens\",\n \"estimatedOutputTokens\",\n \"output\",\n]);\n\nconst OPTIONAL_TOKEN_KEYS: Record<string, keyof AiUsageInput[\"tokens\"]> = {\n total: \"total\",\n total_tokens: \"total\",\n totalTokens: \"total\",\n cached: \"cached\",\n cached_tokens: \"cached\",\n cache_read_tokens: \"cached\",\n cacheReadTokens: \"cached\",\n cacheWrite: \"cacheWrite\",\n cache_write_tokens: \"cacheWrite\",\n cacheWriteTokens: \"cacheWrite\",\n reasoning: \"reasoning\",\n reasoning_tokens: \"reasoning\",\n reasoningTokens: \"reasoning\",\n audio: \"audio\",\n audio_tokens: \"audio\",\n image: \"image\",\n image_tokens: \"image\",\n};\n\nexport type FieldProvenance = {\n field: string;\n path: string;\n score: number;\n};\n\nexport type TokenExtractionProvenance = {\n source: \"usage\" | \"tokens\" | \"diagnostics\" | \"estimated\";\n path: string;\n estimated?: boolean;\n};\n\nexport type ExtractUsageInputResult = {\n input: AiUsageInput;\n provenance: {\n model: FieldProvenance;\n modelUsed?: FieldProvenance;\n provider?: FieldProvenance;\n tokens: TokenExtractionProvenance;\n };\n};\n\nexport type ExtractUsageInputOptions = {\n /** Default when no provider field is found (default: `openrouter`). */\n defaultProvider?: string;\n};\n\ntype ModelCandidate = FieldProvenance & { value: string };\ntype ProviderCandidate = FieldProvenance & { value: string };\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction modelKeyScore(key: string): number {\n return MODEL_FIELD_PRIORITY.find((e) => e.key === key)?.score ?? 0;\n}\n\nfunction providerKeyScore(key: string): number {\n return PROVIDER_FIELD_PRIORITY.find((e) => e.key === key)?.score ?? 0;\n}\n\nfunction pathBonus(path: string, rules: readonly { pattern: RegExp; bonus: number }[]): number {\n let bonus = 0;\n for (const { pattern, bonus: b } of rules) {\n if (pattern.test(path)) bonus += b;\n }\n return bonus;\n}\n\nfunction normalizeModelValue(v: unknown): string | undefined {\n if (typeof v !== \"string\") return undefined;\n const t = v.trim();\n return t.length > 0 ? t : undefined;\n}\n\nfunction normalizeProviderValue(v: unknown): string | undefined {\n if (typeof v !== \"string\") return undefined;\n const t = v.trim().toLowerCase();\n if (!t || t === \"null\") return undefined;\n return t;\n}\n\nfunction collectModelCandidates(\n node: unknown,\n path: string,\n out: ModelCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n const base = modelKeyScore(key);\n if (base > 0) {\n const model = normalizeModelValue(value);\n if (model) {\n out.push({\n field: key,\n path: childPath,\n value: model,\n score: base + pathBonus(childPath, MODEL_PATH_BONUS),\n });\n }\n }\n collectModelCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectModelCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction collectProviderCandidates(\n node: unknown,\n path: string,\n out: ProviderCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n const base = providerKeyScore(key);\n if (base > 0) {\n const provider = normalizeProviderValue(value);\n if (provider) {\n out.push({\n field: key,\n path: childPath,\n value: provider,\n score: base + pathBonus(childPath, PROVIDER_PATH_BONUS),\n });\n }\n }\n collectProviderCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectProviderCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction readNumber(obj: Record<string, unknown>, keys: Set<string>): number | undefined {\n for (const [k, v] of Object.entries(obj)) {\n if (!keys.has(k)) continue;\n if (typeof v === \"number\" && Number.isFinite(v) && v >= 0) return v;\n }\n return undefined;\n}\n\nfunction readOptionalNumbers(\n obj: Record<string, unknown>,\n): Partial<AiUsageInput[\"tokens\"]> {\n const extra: Partial<AiUsageInput[\"tokens\"]> = {};\n for (const [k, v] of Object.entries(obj)) {\n const target = OPTIONAL_TOKEN_KEYS[k];\n if (!target || typeof v !== \"number\" || !Number.isFinite(v) || v < 0) continue;\n extra[target] = v;\n }\n return extra;\n}\n\nfunction looksLikeUsageObject(obj: Record<string, unknown>): boolean {\n const hasPrompt = readNumber(obj, PROMPT_TOKEN_KEYS) !== undefined;\n const hasCompletion = readNumber(obj, COMPLETION_TOKEN_KEYS) !== undefined;\n return hasPrompt && hasCompletion;\n}\n\nfunction looksLikeDiagnosticsObject(obj: Record<string, unknown>): boolean {\n return (\n typeof obj.estimatedInputTokens === \"number\" &&\n typeof obj.estimatedOutputTokens === \"number\"\n );\n}\n\ntype TokenCandidate = {\n tokens: AiUsageInput[\"tokens\"];\n provenance: TokenExtractionProvenance;\n score: number;\n};\n\nfunction tokensFromObject(\n obj: Record<string, unknown>,\n source: TokenExtractionProvenance[\"source\"],\n path: string,\n estimated: boolean,\n score: number,\n): TokenCandidate | null {\n const prompt = readNumber(obj, PROMPT_TOKEN_KEYS);\n const completion = readNumber(obj, COMPLETION_TOKEN_KEYS);\n if (prompt === undefined || completion === undefined) return null;\n\n const extra = readOptionalNumbers(obj);\n const total =\n typeof extra.total === \"number\" ? extra.total : prompt + completion;\n\n return {\n tokens: {\n prompt,\n completion,\n total,\n ...extra,\n },\n provenance: { source, path, estimated },\n score,\n };\n}\n\nfunction collectTokenCandidates(\n node: unknown,\n path: string,\n out: TokenCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n if (path.endsWith(\"diagnostics\") || looksLikeDiagnosticsObject(node)) {\n const cand = tokensFromObject(node, \"diagnostics\", path, true, 200);\n if (cand) out.push(cand);\n } else if (path.endsWith(\"usage\") || path.endsWith(\"tokens\") || looksLikeUsageObject(node)) {\n const source = path.endsWith(\"tokens\") ? \"tokens\" : \"usage\";\n const estimated = false;\n const score = path.endsWith(\"usage\") ? 500 : 450;\n const cand = tokensFromObject(node, source, path, estimated, score);\n if (cand) out.push(cand);\n }\n\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n if (key === \"usage\" || key === \"tokens\" || key === \"diagnostics\") {\n if (isPlainObject(value)) {\n collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n } else {\n collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectTokenCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction pickBestModel(candidates: ModelCandidate[]): ModelCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction pickBestProvider(candidates: ProviderCandidate[]): ProviderCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction pickBestTokens(candidates: TokenCandidate[]): TokenCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction inferProviderFromModel(model: string, fallback: string): string {\n const slash = model.indexOf(\"/\");\n if (slash > 0) {\n const prefix = model.slice(0, slash).toLowerCase();\n if (prefix !== \"openrouter\") return prefix;\n }\n return fallback;\n}\n\n/**\n * Extract {@link AiUsageInput} from activity logs, gateway records, MongoDB exports,\n * or any nested JSON shape (e.g. `outer.input`, `config`, `metadata.diagnostics`).\n */\nexport function extractUsageInput(\n record: unknown,\n options: ExtractUsageInputOptions = {},\n): ExtractUsageInputResult {\n const defaultProvider = options.defaultProvider ?? \"openrouter\";\n const maxDepth = 24;\n\n const modelCandidates: ModelCandidate[] = [];\n const providerCandidates: ProviderCandidate[] = [];\n const tokenCandidates: TokenCandidate[] = [];\n\n collectModelCandidates(record, \"\", modelCandidates, 0, maxDepth);\n collectProviderCandidates(record, \"\", providerCandidates, 0, maxDepth);\n collectTokenCandidates(record, \"\", tokenCandidates, 0, maxDepth);\n\n const bestModel = pickBestModel(modelCandidates);\n if (!bestModel) {\n throw new Error(\n \"[ai-tools] Could not extract a model from the record (looked for usedModel, modelUsed, model, …).\",\n );\n }\n\n const runtimeFields = new Set([\"usedModel\", \"modelUsed\", \"resolvedModel\"]);\n const isRuntimeModel = runtimeFields.has(bestModel.field);\n const requestModel = modelCandidates.find(\n (c) => c.field === \"model\" && c.path !== bestModel.path,\n );\n\n const bestProvider = pickBestProvider(providerCandidates);\n const provider =\n bestProvider?.value ??\n inferProviderFromModel(bestModel.value, defaultProvider);\n\n const bestTokens = pickBestTokens(tokenCandidates);\n if (!bestTokens) {\n throw new Error(\n \"[ai-tools] Could not extract token usage from the record (usage, tokens, or metadata.diagnostics).\",\n );\n }\n\n const input: AiUsageInput = {\n tokens: bestTokens.tokens,\n provider,\n ...(isRuntimeModel\n ? { modelUsed: bestModel.value, model: requestModel?.value }\n : { model: bestModel.value }),\n };\n\n const provenance: ExtractUsageInputResult[\"provenance\"] = {\n model: {\n field: bestModel.field,\n path: bestModel.path,\n score: bestModel.score,\n },\n tokens: bestTokens.provenance,\n };\n\n if (bestProvider) {\n provenance.provider = {\n field: bestProvider.field,\n path: bestProvider.path,\n score: bestProvider.score,\n };\n }\n\n if (isRuntimeModel && requestModel) {\n provenance.modelUsed = {\n field: bestModel.field,\n path: bestModel.path,\n score: bestModel.score,\n };\n } else if (input.modelUsed) {\n provenance.modelUsed = provenance.model;\n }\n\n return { input, provenance };\n}\n","import type { AiUsageInput } from \"./types.js\";\n\n/** Prefer runtime id (`usedModel` / `modelUsed`); fall back to `model`. */\nexport function resolveUsageModel(input: AiUsageInput): string {\n const value = input.usedModel ?? input.modelUsed ?? input.model;\n if (!value?.trim()) {\n throw new Error(\n \"[ai-tools] Cost calculation requires `usedModel`, `modelUsed`, or `model` on usage input.\",\n );\n }\n return value.trim();\n}\n","import type { AIModelPricing } from \"@x12i/ai-profiles\";\nimport {\n DEFAULT_OPENROUTER_MARKUP_RATE,\n PROFILE_TIERED_CONTEXT_THRESHOLD,\n} from \"./constants.js\";\nimport type { AiModelPricing, AiUsageInput } from \"./types.js\";\n\nconst TOKENS_PER_UNIT = 1_000_000;\n\nfunction usdPerToken(perMillion?: number): number {\n return (perMillion ?? 0) / TOKENS_PER_UNIT;\n}\n\nfunction pickInputRatePerMillion(\n pricing: AIModelPricing,\n promptTokens: number,\n): number | undefined {\n if (\n pricing.inputBelow200k !== undefined &&\n pricing.inputAbove200k !== undefined\n ) {\n return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD\n ? pricing.inputBelow200k\n : pricing.inputAbove200k;\n }\n return pricing.input ?? pricing.inputBelow200k ?? pricing.inputAbove200k;\n}\n\nfunction pickOutputRatePerMillion(\n pricing: AIModelPricing,\n promptTokens: number,\n): number | undefined {\n if (\n pricing.outputBelow200k !== undefined &&\n pricing.outputAbove200k !== undefined\n ) {\n return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD\n ? pricing.outputBelow200k\n : pricing.outputAbove200k;\n }\n return pricing.output ?? pricing.outputBelow200k ?? pricing.outputAbove200k;\n}\n\nexport type AiProfilesPricingOptions = {\n promptTokens?: number;\n routedViaOpenRouter?: boolean;\n};\n\nexport function aiProfilesPricingToCatalogPricing(\n pricing: AIModelPricing,\n pricedAt: string,\n options: AiProfilesPricingOptions = {},\n): AiModelPricing {\n const promptTokens = options.promptTokens ?? 0;\n const promptUsdPerToken = usdPerToken(pickInputRatePerMillion(pricing, promptTokens));\n const completionUsdPerToken = usdPerToken(\n pickOutputRatePerMillion(pricing, promptTokens),\n );\n\n const snapshot: AiModelPricing = {\n promptUsdPerToken,\n completionUsdPerToken,\n cacheReadUsdPerToken: usdPerToken(pricing.cachedInput ?? pricing.cacheHit),\n cacheWriteUsdPerToken: usdPerToken(pricing.cacheWrite5m ?? pricing.cacheWrite1h),\n imageUsdPerUnit: 0,\n requestUsdPerRequest: 0,\n pricedAt,\n source: \"manual\",\n };\n\n if (options.routedViaOpenRouter) {\n snapshot.openRouterMarkupUsdPerInputToken =\n promptUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;\n snapshot.openRouterMarkupUsdPerOutputToken =\n completionUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;\n }\n\n return snapshot;\n}\n\nexport function computeCostFromPricing(\n input: AiUsageInput,\n pricing: AiModelPricing,\n routedViaOpenRouter: boolean,\n includeBreakdown: boolean,\n): { cost: number; breakdown?: import(\"./types.js\").AiCostResult[\"breakdown\"] } {\n const { tokens } = input;\n\n let promptCost = tokens.prompt * pricing.promptUsdPerToken;\n let completionCost = tokens.completion * pricing.completionUsdPerToken;\n\n const cachingCost =\n (tokens.cacheWrite ?? 0) * (pricing.cacheWriteUsdPerToken ?? 0) +\n (tokens.cached ?? 0) * (pricing.cacheReadUsdPerToken ?? 0);\n\n const reasoningCost =\n (tokens.reasoning ?? 0) *\n (pricing.reasoningUsdPerToken ?? pricing.promptUsdPerToken);\n\n const audioCost = (tokens.audio ?? 0) * pricing.promptUsdPerToken;\n const imageCost = (tokens.image ?? 0) * (pricing.imageUsdPerUnit ?? 0);\n const requestFlat = pricing.requestUsdPerRequest;\n\n if (routedViaOpenRouter) {\n promptCost +=\n tokens.prompt * (pricing.openRouterMarkupUsdPerInputToken ?? 0);\n completionCost +=\n tokens.completion * (pricing.openRouterMarkupUsdPerOutputToken ?? 0);\n }\n\n const cost =\n promptCost +\n completionCost +\n cachingCost +\n reasoningCost +\n audioCost +\n imageCost +\n requestFlat;\n\n if (!includeBreakdown) {\n return { cost };\n }\n\n return {\n cost,\n breakdown: {\n promptCostUsd: promptCost,\n completionCostUsd: completionCost,\n cachingCostUsd: cachingCost || undefined,\n reasoningCostUsd: reasoningCost || undefined,\n audioCostUsd: audioCost || undefined,\n imageCostUsd: imageCost || undefined,\n requestFlatCostUsd: requestFlat || undefined,\n },\n };\n}\n","import type { AliasRegistry } from \"../aliases/AliasRegistry.js\";\nimport type { AiModelsCatalogClient } from \"../catalog/AiModelsCatalogClient.js\";\nimport { UnknownModelCostError } from \"../errors.js\";\nimport { normalizeString } from \"../sync/modelNameResolver/normalize.js\";\nimport { stripModelVersionSuffix } from \"../sync/modelNameResolver/stripVersionSuffix.js\";\nimport type {\n ModelResolutionResult,\n ModelResolverOptions,\n} from \"../sync/modelNameResolver/types.js\";\nimport { matchModelInAiProfiles } from \"./aiProfilesMatch.js\";\nimport {\n buildCatalogResolveAttempts,\n isLocalProvider,\n isLocalProviderResolution,\n resolveFromCatalogAttempts,\n resolveRoutedViaOpenRouter,\n} from \"./costModelResolution.js\";\nimport {\n aiProfilesPricingToCatalogPricing,\n computeCostFromPricing,\n} from \"./profilePricing.js\";\nimport { enrichCostResult, toCostExtraction } from \"./enrichCostResult.js\";\nimport {\n extractUsageInput,\n type ExtractUsageInputOptions,\n} from \"./extractUsageInput.js\";\nimport { resolveUsageModel } from \"./resolveUsageModel.js\";\nimport type { AiCostResult, AiCostWarning, AiModelPricing, AiUsageInput } from \"./types.js\";\n\nexport type CostCalculatorOptions = {\n aliasRegistry?: AliasRegistry;\n includeBreakdown?: boolean;\n resolverOptions?: ModelResolverOptions;\n /** When true, throw {@link UnknownModelCostError} instead of zero-cost fallback. */\n throwOnUnknownModel?: boolean;\n};\n\nfunction emptyPricing(): AiModelPricing {\n return {\n promptUsdPerToken: 0,\n completionUsdPerToken: 0,\n imageUsdPerUnit: 0,\n requestUsdPerRequest: 0,\n pricedAt: new Date().toISOString(),\n source: \"manual\",\n };\n}\n\nfunction mergeAttempts(\n ...groups: ReturnType<typeof buildCatalogResolveAttempts>[]\n): ReturnType<typeof buildCatalogResolveAttempts> {\n const seen = new Set<string>();\n const out: ReturnType<typeof buildCatalogResolveAttempts> = [];\n for (const group of groups) {\n for (const a of group) {\n const key = `${a.provider ?? \"\"}\\0${a.model}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(a);\n }\n }\n return out;\n}\n\nexport class CostCalculator {\n private readonly aliasRegistry?: AliasRegistry;\n private readonly includeBreakdown: boolean;\n private readonly resolverOptions?: ModelResolverOptions;\n private readonly throwOnUnknownModel: boolean;\n\n constructor(\n private readonly catalog: AiModelsCatalogClient,\n options: CostCalculatorOptions = {},\n ) {\n this.aliasRegistry = options.aliasRegistry;\n this.includeBreakdown = options.includeBreakdown ?? true;\n this.resolverOptions = options.resolverOptions;\n this.throwOnUnknownModel = options.throwOnUnknownModel ?? false;\n }\n\n /**\n * Extract model, provider, and token usage from an activity / gateway record\n * (MongoDB export, nested `outer`, `config`, `metadata.diagnostics`, etc.)\n * then run {@link calculate}.\n */\n async calculateFromRecord(\n record: unknown,\n extractOptions?: ExtractUsageInputOptions,\n ): Promise<AiCostResult> {\n const { input, provenance } = extractUsageInput(record, extractOptions);\n const warnings: AiCostWarning[] = [];\n if (provenance.tokens.estimated) {\n warnings.push({\n code: \"ESTIMATED_TOKEN_USAGE\",\n message: `Token counts are estimates from ${provenance.tokens.path} (not billed usage).`,\n });\n }\n const result = await this.calculate(input);\n const enriched = enrichCostResult(result, input, toCostExtraction(provenance));\n if (warnings.length > 0) {\n enriched.warnings = [...(enriched.warnings ?? []), ...warnings];\n }\n return enriched;\n }\n\n async calculate(input: AiUsageInput): Promise<AiCostResult> {\n const modelInput = resolveUsageModel(input);\n const resolverOpts = {\n ...this.resolverOptions,\n aliasRegistry: this.aliasRegistry ?? this.resolverOptions?.aliasRegistry,\n };\n\n let resolved = await resolveFromCatalogAttempts(\n this.catalog,\n buildCatalogResolveAttempts(modelInput, input.provider),\n resolverOpts,\n );\n\n if (isLocalProviderResolution(resolved, input.provider)) {\n return this.localProviderResult(modelInput, input, resolved);\n }\n\n let profileMatch = null as Awaited<ReturnType<typeof matchModelInAiProfiles>>;\n const warnings: AiCostWarning[] = [];\n\n if (!resolved?.found || !resolved.record) {\n if (!isLocalProvider(input.provider)) {\n profileMatch = await matchModelInAiProfiles(modelInput, input.provider);\n }\n if (profileMatch) {\n resolved = await resolveFromCatalogAttempts(\n this.catalog,\n mergeAttempts(\n buildCatalogResolveAttempts(\n profileMatch.canonicalModelId,\n input.provider ?? profileMatch.provider,\n ),\n buildCatalogResolveAttempts(\n profileMatch.canonicalModelId,\n profileMatch.provider,\n ),\n ),\n resolverOpts,\n );\n }\n\n if (isLocalProviderResolution(resolved, input.provider)) {\n return this.localProviderResult(modelInput, input, resolved);\n }\n\n if ((!resolved?.found || !resolved.record) && profileMatch?.pricing) {\n const routedViaOpenRouter = resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n profileMatch.canonicalModelId,\n resolverOpts?.routingEnv,\n );\n const pricing = aiProfilesPricingToCatalogPricing(\n profileMatch.pricing,\n new Date().toISOString(),\n {\n promptTokens: input.tokens.prompt,\n routedViaOpenRouter,\n },\n );\n const { cost, breakdown } = computeCostFromPricing(\n input,\n pricing,\n routedViaOpenRouter,\n this.includeBreakdown,\n );\n\n warnings.push({\n code: \"AI_PROFILES_ESTIMATE\",\n message: `Catalog has no pricing for \"${modelInput}\"; estimated from ai-profiles (${profileMatch.matchedVia} → ${profileMatch.canonicalModelId}).`,\n });\n if (\n routedViaOpenRouter &&\n pricing.openRouterMarkupUsdPerInputToken !== undefined\n ) {\n warnings.push({\n code: \"OPENROUTER_MARKUP_ESTIMATED\",\n message:\n \"OpenRouter markup estimated at 5% of base token rates (catalog markup fields absent).\",\n });\n }\n\n console.warn(`[ai-tools] ${warnings.map((w) => w.message).join(\" \")}`);\n\n return this.finish(\n {\n cost,\n breakdown,\n resolvedModelId: profileMatch.canonicalModelId,\n routedViaOpenRouter,\n isAuthoritative: false,\n pricingSnapshot: pricing,\n source: \"ai-profiles\",\n warnings,\n },\n input,\n resolved,\n );\n }\n }\n\n if (!resolved?.found || !resolved.record) {\n return this.unknownModelResult(modelInput, input, resolved);\n }\n\n const { record, modelId } = resolved;\n const routedViaOpenRouter = resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n modelId,\n resolverOpts?.routingEnv,\n );\n const pricing = record.pricing;\n const { cost, breakdown } = computeCostFromPricing(\n input,\n pricing,\n routedViaOpenRouter,\n this.includeBreakdown,\n );\n\n return this.finish(\n {\n cost,\n breakdown,\n resolvedModelId: modelId,\n routedViaOpenRouter,\n isAuthoritative: true,\n pricingSnapshot: pricing,\n source: \"catalog\",\n },\n input,\n resolved,\n );\n }\n\n private versionSuffixWarnings(\n input: AiUsageInput,\n pricedModelId: string,\n resolved?: ModelResolutionResult | null,\n ): AiCostWarning[] {\n const received = input.usedModel ?? input.modelUsed ?? input.model;\n if (!received) return [];\n\n const normalizedReceived = normalizeString(received);\n const normalizedPriced = normalizeString(pricedModelId);\n if (normalizedReceived === normalizedPriced) return [];\n\n const stripped = stripModelVersionSuffix(received);\n const viaResolver =\n resolved?.found === true &&\n resolved.resolvedVia.some(\n (s) => s === \"version-suffix-strip\" || s === \"date-suffix-strip\",\n );\n const pricedViaStrip =\n stripped !== null && normalizeString(stripped) === normalizedPriced;\n\n if (!viaResolver && !pricedViaStrip) return [];\n\n return [\n {\n code: \"VERSION_SUFFIX_PRICING\",\n message: `Priced using catalog model \"${pricedModelId}\" (no exact pricing for \"${received}\").`,\n },\n ];\n }\n\n private finish(\n partial: Omit<\n AiCostResult,\n \"usage\" | \"provider\" | \"usedModel\" | \"model\" | \"extraction\"\n >,\n input: AiUsageInput,\n resolved?: ModelResolutionResult | null,\n ): AiCostResult {\n const enriched = enrichCostResult(partial, input);\n const suffixWarnings = this.versionSuffixWarnings(\n input,\n partial.resolvedModelId,\n resolved,\n );\n if (suffixWarnings.length > 0) {\n enriched.warnings = [...(enriched.warnings ?? []), ...suffixWarnings];\n }\n return enriched;\n }\n\n private localProviderResult(\n modelInput: string,\n input: AiUsageInput,\n resolved: Awaited<ReturnType<typeof resolveFromCatalogAttempts>>,\n ): AiCostResult {\n const warnings: AiCostWarning[] = [\n {\n code: \"LOCAL_PROVIDER_NO_PRICING\",\n message: `Local provider \"${input.provider}\" has no catalog pricing for \"${modelInput}\".`,\n },\n ];\n console.warn(`[ai-tools] ${warnings[0]!.message}`);\n return this.finish(\n {\n cost: 0,\n resolvedModelId: resolved?.found ? resolved.modelId : modelInput,\n routedViaOpenRouter: false,\n isAuthoritative: false,\n pricingSnapshot: emptyPricing(),\n source: \"local\",\n warnings,\n },\n input,\n );\n }\n\n private unknownModelResult(\n modelInput: string,\n input: AiUsageInput,\n resolved: Awaited<ReturnType<typeof resolveFromCatalogAttempts>>,\n ): AiCostResult {\n if (this.throwOnUnknownModel) {\n throw new UnknownModelCostError(modelInput, input.provider);\n }\n\n const warnings: AiCostWarning[] = [\n {\n code: \"UNKNOWN_MODEL\",\n message: `Unknown model \"${modelInput}\" (provider: \"${input.provider}\") — returning zero-cost fallback.`,\n },\n ];\n console.warn(`[ai-tools] ${warnings[0]!.message}`);\n\n return this.finish(\n {\n cost: 0,\n resolvedModelId: modelInput,\n routedViaOpenRouter: resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n modelInput,\n this.resolverOptions?.routingEnv,\n ),\n isAuthoritative: false,\n pricingSnapshot: emptyPricing(),\n source: \"estimate-fallback\",\n unknownModel: true,\n warnings,\n },\n input,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-GHRUS5UF.cjs","../src/cost/constants.ts","../src/cost/enrichCostResult.ts","../src/cost/extractUsageInput.ts","../src/cost/resolveUsageModel.ts","../src/cost/profilePricing.ts","../src/cost/CostCalculator.ts"],"names":["routedViaOpenRouter","pricing","cost","breakdown"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACfO,IAAM,+BAAA,EAAiC,IAAA;AAGvC,IAAM,iCAAA,EAAmC,GAAA;ADehD;AACA;AEjBO,SAAS,gBAAA,CACd,UAAA,EACkB;AAClB,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,EAAE,KAAA,EAAO,UAAA,CAAW,KAAA,CAAM,KAAA,EAAO,IAAA,EAAM,UAAA,CAAW,KAAA,CAAM,KAAK,CAAA;AAAA,IACpE,MAAA,EAAQ;AAAA,MACN,MAAA,EAAQ,UAAA,CAAW,MAAA,CAAO,MAAA;AAAA,MAC1B,IAAA,EAAM,UAAA,CAAW,MAAA,CAAO,IAAA;AAAA,MACxB,SAAA,EAAW,UAAA,CAAW,MAAA,CAAO;AAAA,IAC/B,CAAA;AAAA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BAAA;AACxB,QAAA;AACiB,QAAA;AACA,QAAA;AACT,QAAA;AACM,QAAA;AACd,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AACF;ANqVgC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/ami/Documents/prometheus/x12i/ai-tools/dist/chunk-GHRUS5UF.cjs","sourcesContent":[null,"/** Default OpenRouter platform surcharge when catalog markup fields are absent (5%). */\nexport const DEFAULT_OPENROUTER_MARKUP_RATE = 0.05;\n\n/** ai-profiles tiered pricing threshold (tokens). */\nexport const PROFILE_TIERED_CONTEXT_THRESHOLD = 200_000;\n","import type { ExtractUsageInputResult } from \"./extractUsageInput.js\";\nimport type { AiCostExtraction, AiCostResult, AiUsageInput } from \"./types.js\";\n\nexport function toCostExtraction(\n provenance: ExtractUsageInputResult[\"provenance\"],\n): AiCostExtraction {\n return {\n model: { field: provenance.model.field, path: provenance.model.path },\n tokens: {\n source: provenance.tokens.source,\n path: provenance.tokens.path,\n estimated: provenance.tokens.estimated,\n },\n ...(provenance.modelUsed\n ? {\n modelUsed: {\n field: provenance.modelUsed.field,\n path: provenance.modelUsed.path,\n },\n }\n : {}),\n ...(provenance.provider\n ? {\n provider: {\n field: provenance.provider.field,\n path: provenance.provider.path,\n },\n }\n : {}),\n };\n}\n\n/** Attach usage, provider, and model fields callers expect on every cost response. */\nexport function enrichCostResult(\n result: Omit<\n AiCostResult,\n \"usage\" | \"provider\" | \"usedModel\" | \"model\" | \"extraction\"\n >,\n input: AiUsageInput,\n extraction?: AiCostExtraction,\n): AiCostResult {\n /** Original model id from the caller — never replaced by catalog resolution. */\n const receivedModelId = input.usedModel ?? input.modelUsed ?? input.model;\n\n return {\n ...result,\n provider: input.provider,\n usage: { ...input.tokens },\n ...(receivedModelId ? { usedModel: receivedModelId } : {}),\n ...(input.model && input.model !== receivedModelId ? { model: input.model } : {}),\n ...(extraction ? { extraction } : {}),\n };\n}\n","import type { AiUsageInput } from \"./types.js\";\n\n/** Model id field priority (higher wins). Runtime ids beat request/config aliases. */\nexport const MODEL_FIELD_PRIORITY: readonly { key: string; score: number }[] = [\n { key: \"usedModel\", score: 1000 },\n { key: \"modelUsed\", score: 990 },\n { key: \"resolvedModel\", score: 980 },\n { key: \"model\", score: 500 },\n { key: \"xynthesisModel\", score: 120 },\n { key: \"skillModel\", score: 110 },\n] as const;\n\n/** Path segments that boost or penalize a model candidate. */\nconst MODEL_PATH_BONUS: readonly { pattern: RegExp; bonus: number }[] = [\n { pattern: /(^|\\.)response(\\.|$)/i, bonus: 40 },\n { pattern: /(^|\\.)outer\\.input(\\.|$)/i, bonus: 35 },\n { pattern: /(^|\\.)config(?!\\.rawConfig)(\\.|$)/i, bonus: 30 },\n { pattern: /(^|\\.)outer\\.input\\.config(\\.|$)/i, bonus: 28 },\n { pattern: /(^|\\.)usage(\\.|$)/i, bonus: 15 },\n { pattern: /(^|\\.)rawConfig(\\.|$)/i, bonus: -40 },\n { pattern: /workingMemory/i, bonus: -50 },\n { pattern: /requestExample/i, bonus: -80 },\n { pattern: /graphsStudio/i, bonus: -80 },\n];\n\nconst PROVIDER_FIELD_PRIORITY: readonly { key: string; score: number }[] = [\n { key: \"provider\", score: 500 },\n { key: \"providerId\", score: 480 },\n] as const;\n\nconst PROVIDER_PATH_BONUS: readonly { pattern: RegExp; bonus: number }[] = [\n { pattern: /(^|\\.)config(?!\\.rawConfig)(\\.|$)/i, bonus: 30 },\n { pattern: /(^|\\.)outer\\.input(\\.|$)/i, bonus: 20 },\n { pattern: /(^|\\.)rawConfig(\\.|$)/i, bonus: -20 },\n];\n\nconst PROMPT_TOKEN_KEYS = new Set([\n \"prompt\",\n \"prompt_tokens\",\n \"promptTokens\",\n \"input_tokens\",\n \"inputTokens\",\n \"estimatedInputTokens\",\n \"input\",\n]);\n\nconst COMPLETION_TOKEN_KEYS = new Set([\n \"completion\",\n \"completion_tokens\",\n \"completionTokens\",\n \"output_tokens\",\n \"outputTokens\",\n \"estimatedOutputTokens\",\n \"output\",\n]);\n\nconst OPTIONAL_TOKEN_KEYS: Record<string, keyof AiUsageInput[\"tokens\"]> = {\n total: \"total\",\n total_tokens: \"total\",\n totalTokens: \"total\",\n cached: \"cached\",\n cached_tokens: \"cached\",\n cache_read_tokens: \"cached\",\n cacheReadTokens: \"cached\",\n cacheWrite: \"cacheWrite\",\n cache_write_tokens: \"cacheWrite\",\n cacheWriteTokens: \"cacheWrite\",\n reasoning: \"reasoning\",\n reasoning_tokens: \"reasoning\",\n reasoningTokens: \"reasoning\",\n audio: \"audio\",\n audio_tokens: \"audio\",\n image: \"image\",\n image_tokens: \"image\",\n};\n\nexport type FieldProvenance = {\n field: string;\n path: string;\n score: number;\n};\n\nexport type TokenExtractionProvenance = {\n source: \"usage\" | \"tokens\" | \"diagnostics\" | \"estimated\";\n path: string;\n estimated?: boolean;\n};\n\nexport type ExtractUsageInputResult = {\n input: AiUsageInput;\n provenance: {\n model: FieldProvenance;\n modelUsed?: FieldProvenance;\n provider?: FieldProvenance;\n tokens: TokenExtractionProvenance;\n };\n};\n\nexport type ExtractUsageInputOptions = {\n /** Default when no provider field is found (default: `openrouter`). */\n defaultProvider?: string;\n};\n\ntype ModelCandidate = FieldProvenance & { value: string };\ntype ProviderCandidate = FieldProvenance & { value: string };\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction modelKeyScore(key: string): number {\n return MODEL_FIELD_PRIORITY.find((e) => e.key === key)?.score ?? 0;\n}\n\nfunction providerKeyScore(key: string): number {\n return PROVIDER_FIELD_PRIORITY.find((e) => e.key === key)?.score ?? 0;\n}\n\nfunction pathBonus(path: string, rules: readonly { pattern: RegExp; bonus: number }[]): number {\n let bonus = 0;\n for (const { pattern, bonus: b } of rules) {\n if (pattern.test(path)) bonus += b;\n }\n return bonus;\n}\n\nfunction normalizeModelValue(v: unknown): string | undefined {\n if (typeof v !== \"string\") return undefined;\n const t = v.trim();\n return t.length > 0 ? t : undefined;\n}\n\nfunction normalizeProviderValue(v: unknown): string | undefined {\n if (typeof v !== \"string\") return undefined;\n const t = v.trim().toLowerCase();\n if (!t || t === \"null\") return undefined;\n return t;\n}\n\nfunction collectModelCandidates(\n node: unknown,\n path: string,\n out: ModelCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n const base = modelKeyScore(key);\n if (base > 0) {\n const model = normalizeModelValue(value);\n if (model) {\n out.push({\n field: key,\n path: childPath,\n value: model,\n score: base + pathBonus(childPath, MODEL_PATH_BONUS),\n });\n }\n }\n collectModelCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectModelCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction collectProviderCandidates(\n node: unknown,\n path: string,\n out: ProviderCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n const base = providerKeyScore(key);\n if (base > 0) {\n const provider = normalizeProviderValue(value);\n if (provider) {\n out.push({\n field: key,\n path: childPath,\n value: provider,\n score: base + pathBonus(childPath, PROVIDER_PATH_BONUS),\n });\n }\n }\n collectProviderCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectProviderCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction readNumber(obj: Record<string, unknown>, keys: Set<string>): number | undefined {\n for (const [k, v] of Object.entries(obj)) {\n if (!keys.has(k)) continue;\n if (typeof v === \"number\" && Number.isFinite(v) && v >= 0) return v;\n }\n return undefined;\n}\n\nfunction readOptionalNumbers(\n obj: Record<string, unknown>,\n): Partial<AiUsageInput[\"tokens\"]> {\n const extra: Partial<AiUsageInput[\"tokens\"]> = {};\n for (const [k, v] of Object.entries(obj)) {\n const target = OPTIONAL_TOKEN_KEYS[k];\n if (!target || typeof v !== \"number\" || !Number.isFinite(v) || v < 0) continue;\n extra[target] = v;\n }\n return extra;\n}\n\nfunction looksLikeUsageObject(obj: Record<string, unknown>): boolean {\n const hasPrompt = readNumber(obj, PROMPT_TOKEN_KEYS) !== undefined;\n const hasCompletion = readNumber(obj, COMPLETION_TOKEN_KEYS) !== undefined;\n return hasPrompt && hasCompletion;\n}\n\nfunction looksLikeDiagnosticsObject(obj: Record<string, unknown>): boolean {\n return (\n typeof obj.estimatedInputTokens === \"number\" &&\n typeof obj.estimatedOutputTokens === \"number\"\n );\n}\n\ntype TokenCandidate = {\n tokens: AiUsageInput[\"tokens\"];\n provenance: TokenExtractionProvenance;\n score: number;\n};\n\nfunction tokensFromObject(\n obj: Record<string, unknown>,\n source: TokenExtractionProvenance[\"source\"],\n path: string,\n estimated: boolean,\n score: number,\n): TokenCandidate | null {\n const prompt = readNumber(obj, PROMPT_TOKEN_KEYS);\n const completion = readNumber(obj, COMPLETION_TOKEN_KEYS);\n if (prompt === undefined || completion === undefined) return null;\n\n const extra = readOptionalNumbers(obj);\n const total =\n typeof extra.total === \"number\" ? extra.total : prompt + completion;\n\n return {\n tokens: {\n prompt,\n completion,\n total,\n ...extra,\n },\n provenance: { source, path, estimated },\n score,\n };\n}\n\nfunction collectTokenCandidates(\n node: unknown,\n path: string,\n out: TokenCandidate[],\n depth: number,\n maxDepth: number,\n): void {\n if (depth > maxDepth || node === null || node === undefined) return;\n\n if (isPlainObject(node)) {\n if (path.endsWith(\"diagnostics\") || looksLikeDiagnosticsObject(node)) {\n const cand = tokensFromObject(node, \"diagnostics\", path, true, 200);\n if (cand) out.push(cand);\n } else if (path.endsWith(\"usage\") || path.endsWith(\"tokens\") || looksLikeUsageObject(node)) {\n const source = path.endsWith(\"tokens\") ? \"tokens\" : \"usage\";\n const estimated = false;\n const score = path.endsWith(\"usage\") ? 500 : 450;\n const cand = tokensFromObject(node, source, path, estimated, score);\n if (cand) out.push(cand);\n }\n\n for (const [key, value] of Object.entries(node)) {\n const childPath = path ? `${path}.${key}` : key;\n if (key === \"usage\" || key === \"tokens\" || key === \"diagnostics\") {\n if (isPlainObject(value)) {\n collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n } else {\n collectTokenCandidates(value, childPath, out, depth + 1, maxDepth);\n }\n }\n return;\n }\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n collectTokenCandidates(node[i], `${path}[${i}]`, out, depth + 1, maxDepth);\n }\n }\n}\n\nfunction pickBestModel(candidates: ModelCandidate[]): ModelCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction pickBestProvider(candidates: ProviderCandidate[]): ProviderCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction pickBestTokens(candidates: TokenCandidate[]): TokenCandidate | null {\n if (candidates.length === 0) return null;\n return [...candidates].sort((a, b) => b.score - a.score)[0]!;\n}\n\nfunction inferProviderFromModel(model: string, fallback: string): string {\n const slash = model.indexOf(\"/\");\n if (slash > 0) {\n const prefix = model.slice(0, slash).toLowerCase();\n if (prefix !== \"openrouter\") return prefix;\n }\n return fallback;\n}\n\n/**\n * Extract {@link AiUsageInput} from activity logs, gateway records, MongoDB exports,\n * or any nested JSON shape (e.g. `outer.input`, `config`, `metadata.diagnostics`).\n */\nexport function extractUsageInput(\n record: unknown,\n options: ExtractUsageInputOptions = {},\n): ExtractUsageInputResult {\n const defaultProvider = options.defaultProvider ?? \"openrouter\";\n const maxDepth = 24;\n\n const modelCandidates: ModelCandidate[] = [];\n const providerCandidates: ProviderCandidate[] = [];\n const tokenCandidates: TokenCandidate[] = [];\n\n collectModelCandidates(record, \"\", modelCandidates, 0, maxDepth);\n collectProviderCandidates(record, \"\", providerCandidates, 0, maxDepth);\n collectTokenCandidates(record, \"\", tokenCandidates, 0, maxDepth);\n\n const bestModel = pickBestModel(modelCandidates);\n if (!bestModel) {\n throw new Error(\n \"[ai-tools] Could not extract a model from the record (looked for usedModel, modelUsed, model, …).\",\n );\n }\n\n const runtimeFields = new Set([\"usedModel\", \"modelUsed\", \"resolvedModel\"]);\n const isRuntimeModel = runtimeFields.has(bestModel.field);\n const requestModel = modelCandidates.find(\n (c) => c.field === \"model\" && c.path !== bestModel.path,\n );\n\n const bestProvider = pickBestProvider(providerCandidates);\n const provider =\n bestProvider?.value ??\n inferProviderFromModel(bestModel.value, defaultProvider);\n\n const bestTokens = pickBestTokens(tokenCandidates);\n if (!bestTokens) {\n throw new Error(\n \"[ai-tools] Could not extract token usage from the record (usage, tokens, or metadata.diagnostics).\",\n );\n }\n\n const input: AiUsageInput = {\n tokens: bestTokens.tokens,\n provider,\n ...(isRuntimeModel\n ? { modelUsed: bestModel.value, model: requestModel?.value }\n : { model: bestModel.value }),\n };\n\n const provenance: ExtractUsageInputResult[\"provenance\"] = {\n model: {\n field: bestModel.field,\n path: bestModel.path,\n score: bestModel.score,\n },\n tokens: bestTokens.provenance,\n };\n\n if (bestProvider) {\n provenance.provider = {\n field: bestProvider.field,\n path: bestProvider.path,\n score: bestProvider.score,\n };\n }\n\n if (isRuntimeModel && requestModel) {\n provenance.modelUsed = {\n field: bestModel.field,\n path: bestModel.path,\n score: bestModel.score,\n };\n } else if (input.modelUsed) {\n provenance.modelUsed = provenance.model;\n }\n\n return { input, provenance };\n}\n","import type { AiUsageInput } from \"./types.js\";\n\n/** Prefer runtime id (`usedModel` / `modelUsed`); fall back to `model`. */\nexport function resolveUsageModel(input: AiUsageInput): string {\n const value = input.usedModel ?? input.modelUsed ?? input.model;\n if (!value?.trim()) {\n throw new Error(\n \"[ai-tools] Cost calculation requires `usedModel`, `modelUsed`, or `model` on usage input.\",\n );\n }\n return value.trim();\n}\n","import type { AIModelPricing } from \"@x12i/ai-profiles\";\nimport {\n DEFAULT_OPENROUTER_MARKUP_RATE,\n PROFILE_TIERED_CONTEXT_THRESHOLD,\n} from \"./constants.js\";\nimport type { AiModelPricing, AiUsageInput } from \"./types.js\";\n\nconst TOKENS_PER_UNIT = 1_000_000;\n\nfunction usdPerToken(perMillion?: number): number {\n return (perMillion ?? 0) / TOKENS_PER_UNIT;\n}\n\nfunction pickInputRatePerMillion(\n pricing: AIModelPricing,\n promptTokens: number,\n): number | undefined {\n if (\n pricing.inputBelow200k !== undefined &&\n pricing.inputAbove200k !== undefined\n ) {\n return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD\n ? pricing.inputBelow200k\n : pricing.inputAbove200k;\n }\n return pricing.input ?? pricing.inputBelow200k ?? pricing.inputAbove200k;\n}\n\nfunction pickOutputRatePerMillion(\n pricing: AIModelPricing,\n promptTokens: number,\n): number | undefined {\n if (\n pricing.outputBelow200k !== undefined &&\n pricing.outputAbove200k !== undefined\n ) {\n return promptTokens <= PROFILE_TIERED_CONTEXT_THRESHOLD\n ? pricing.outputBelow200k\n : pricing.outputAbove200k;\n }\n return pricing.output ?? pricing.outputBelow200k ?? pricing.outputAbove200k;\n}\n\nexport type AiProfilesPricingOptions = {\n promptTokens?: number;\n routedViaOpenRouter?: boolean;\n};\n\nexport function aiProfilesPricingToCatalogPricing(\n pricing: AIModelPricing,\n pricedAt: string,\n options: AiProfilesPricingOptions = {},\n): AiModelPricing {\n const promptTokens = options.promptTokens ?? 0;\n const promptUsdPerToken = usdPerToken(pickInputRatePerMillion(pricing, promptTokens));\n const completionUsdPerToken = usdPerToken(\n pickOutputRatePerMillion(pricing, promptTokens),\n );\n\n const snapshot: AiModelPricing = {\n promptUsdPerToken,\n completionUsdPerToken,\n cacheReadUsdPerToken: usdPerToken(pricing.cachedInput ?? pricing.cacheHit),\n cacheWriteUsdPerToken: usdPerToken(pricing.cacheWrite5m ?? pricing.cacheWrite1h),\n imageUsdPerUnit: 0,\n requestUsdPerRequest: 0,\n pricedAt,\n source: \"manual\",\n };\n\n if (options.routedViaOpenRouter) {\n snapshot.openRouterMarkupUsdPerInputToken =\n promptUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;\n snapshot.openRouterMarkupUsdPerOutputToken =\n completionUsdPerToken * DEFAULT_OPENROUTER_MARKUP_RATE;\n }\n\n return snapshot;\n}\n\nexport function computeCostFromPricing(\n input: AiUsageInput,\n pricing: AiModelPricing,\n routedViaOpenRouter: boolean,\n includeBreakdown: boolean,\n): { cost: number; breakdown?: import(\"./types.js\").AiCostResult[\"breakdown\"] } {\n const { tokens } = input;\n\n let promptCost = tokens.prompt * pricing.promptUsdPerToken;\n let completionCost = tokens.completion * pricing.completionUsdPerToken;\n\n const cachingCost =\n (tokens.cacheWrite ?? 0) * (pricing.cacheWriteUsdPerToken ?? 0) +\n (tokens.cached ?? 0) * (pricing.cacheReadUsdPerToken ?? 0);\n\n const reasoningCost =\n (tokens.reasoning ?? 0) *\n (pricing.reasoningUsdPerToken ?? pricing.promptUsdPerToken);\n\n const audioCost = (tokens.audio ?? 0) * pricing.promptUsdPerToken;\n const imageCost = (tokens.image ?? 0) * (pricing.imageUsdPerUnit ?? 0);\n const requestFlat = pricing.requestUsdPerRequest;\n\n if (routedViaOpenRouter) {\n promptCost +=\n tokens.prompt * (pricing.openRouterMarkupUsdPerInputToken ?? 0);\n completionCost +=\n tokens.completion * (pricing.openRouterMarkupUsdPerOutputToken ?? 0);\n }\n\n const cost =\n promptCost +\n completionCost +\n cachingCost +\n reasoningCost +\n audioCost +\n imageCost +\n requestFlat;\n\n if (!includeBreakdown) {\n return { cost };\n }\n\n return {\n cost,\n breakdown: {\n promptCostUsd: promptCost,\n completionCostUsd: completionCost,\n cachingCostUsd: cachingCost || undefined,\n reasoningCostUsd: reasoningCost || undefined,\n audioCostUsd: audioCost || undefined,\n imageCostUsd: imageCost || undefined,\n requestFlatCostUsd: requestFlat || undefined,\n },\n };\n}\n","import type { AliasRegistry } from \"../aliases/AliasRegistry.js\";\nimport type { AiModelsCatalogClient } from \"../catalog/AiModelsCatalogClient.js\";\nimport { UnknownModelCostError } from \"../errors.js\";\nimport { normalizeString } from \"../sync/modelNameResolver/normalize.js\";\nimport { stripModelVersionSuffix } from \"../sync/modelNameResolver/stripVersionSuffix.js\";\nimport type {\n ModelResolutionResult,\n ModelResolverOptions,\n} from \"../sync/modelNameResolver/types.js\";\nimport { matchModelInAiProfiles } from \"./aiProfilesMatch.js\";\nimport {\n buildCatalogResolveAttempts,\n isLocalProvider,\n isLocalProviderResolution,\n resolveFromCatalogAttempts,\n resolveRoutedViaOpenRouter,\n} from \"./costModelResolution.js\";\nimport {\n aiProfilesPricingToCatalogPricing,\n computeCostFromPricing,\n} from \"./profilePricing.js\";\nimport { enrichCostResult, toCostExtraction } from \"./enrichCostResult.js\";\nimport {\n extractUsageInput,\n type ExtractUsageInputOptions,\n} from \"./extractUsageInput.js\";\nimport { resolveUsageModel } from \"./resolveUsageModel.js\";\nimport type { AiCostResult, AiCostWarning, AiModelPricing, AiUsageInput } from \"./types.js\";\n\nexport type CostCalculatorOptions = {\n aliasRegistry?: AliasRegistry;\n includeBreakdown?: boolean;\n resolverOptions?: ModelResolverOptions;\n /** When true, throw {@link UnknownModelCostError} instead of zero-cost fallback. */\n throwOnUnknownModel?: boolean;\n};\n\nfunction emptyPricing(): AiModelPricing {\n return {\n promptUsdPerToken: 0,\n completionUsdPerToken: 0,\n imageUsdPerUnit: 0,\n requestUsdPerRequest: 0,\n pricedAt: new Date().toISOString(),\n source: \"manual\",\n };\n}\n\nfunction mergeAttempts(\n ...groups: ReturnType<typeof buildCatalogResolveAttempts>[]\n): ReturnType<typeof buildCatalogResolveAttempts> {\n const seen = new Set<string>();\n const out: ReturnType<typeof buildCatalogResolveAttempts> = [];\n for (const group of groups) {\n for (const a of group) {\n const key = `${a.provider ?? \"\"}\\0${a.model}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(a);\n }\n }\n return out;\n}\n\nexport class CostCalculator {\n private readonly aliasRegistry?: AliasRegistry;\n private readonly includeBreakdown: boolean;\n private readonly resolverOptions?: ModelResolverOptions;\n private readonly throwOnUnknownModel: boolean;\n\n constructor(\n private readonly catalog: AiModelsCatalogClient,\n options: CostCalculatorOptions = {},\n ) {\n this.aliasRegistry = options.aliasRegistry;\n this.includeBreakdown = options.includeBreakdown ?? true;\n this.resolverOptions = options.resolverOptions;\n this.throwOnUnknownModel = options.throwOnUnknownModel ?? false;\n }\n\n /**\n * Extract model, provider, and token usage from an activity / gateway record\n * (MongoDB export, nested `outer`, `config`, `metadata.diagnostics`, etc.)\n * then run {@link calculate}.\n */\n async calculateFromRecord(\n record: unknown,\n extractOptions?: ExtractUsageInputOptions,\n ): Promise<AiCostResult> {\n const { input, provenance } = extractUsageInput(record, extractOptions);\n const warnings: AiCostWarning[] = [];\n if (provenance.tokens.estimated) {\n warnings.push({\n code: \"ESTIMATED_TOKEN_USAGE\",\n message: `Token counts are estimates from ${provenance.tokens.path} (not billed usage).`,\n });\n }\n const result = await this.calculate(input);\n const enriched = enrichCostResult(result, input, toCostExtraction(provenance));\n if (warnings.length > 0) {\n enriched.warnings = [...(enriched.warnings ?? []), ...warnings];\n }\n return enriched;\n }\n\n async calculate(input: AiUsageInput): Promise<AiCostResult> {\n const modelInput = resolveUsageModel(input);\n const resolverOpts = {\n ...this.resolverOptions,\n aliasRegistry: this.aliasRegistry ?? this.resolverOptions?.aliasRegistry,\n };\n\n let resolved = await resolveFromCatalogAttempts(\n this.catalog,\n buildCatalogResolveAttempts(modelInput, input.provider),\n resolverOpts,\n );\n\n if (isLocalProviderResolution(resolved, input.provider)) {\n return this.localProviderResult(modelInput, input, resolved);\n }\n\n let profileMatch = null as Awaited<ReturnType<typeof matchModelInAiProfiles>>;\n const warnings: AiCostWarning[] = [];\n\n if (!resolved?.found || !resolved.record) {\n if (!isLocalProvider(input.provider)) {\n profileMatch = await matchModelInAiProfiles(modelInput, input.provider);\n }\n if (profileMatch) {\n resolved = await resolveFromCatalogAttempts(\n this.catalog,\n mergeAttempts(\n buildCatalogResolveAttempts(\n profileMatch.canonicalModelId,\n input.provider ?? profileMatch.provider,\n ),\n buildCatalogResolveAttempts(\n profileMatch.canonicalModelId,\n profileMatch.provider,\n ),\n ),\n resolverOpts,\n );\n }\n\n if (isLocalProviderResolution(resolved, input.provider)) {\n return this.localProviderResult(modelInput, input, resolved);\n }\n\n if ((!resolved?.found || !resolved.record) && profileMatch?.pricing) {\n const routedViaOpenRouter = resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n profileMatch.canonicalModelId,\n resolverOpts?.routingEnv,\n );\n const pricing = aiProfilesPricingToCatalogPricing(\n profileMatch.pricing,\n new Date().toISOString(),\n {\n promptTokens: input.tokens.prompt,\n routedViaOpenRouter,\n },\n );\n const { cost, breakdown } = computeCostFromPricing(\n input,\n pricing,\n routedViaOpenRouter,\n this.includeBreakdown,\n );\n\n warnings.push({\n code: \"AI_PROFILES_ESTIMATE\",\n message: `Catalog has no pricing for \"${modelInput}\"; estimated from ai-profiles (${profileMatch.matchedVia} → ${profileMatch.canonicalModelId}).`,\n });\n if (\n routedViaOpenRouter &&\n pricing.openRouterMarkupUsdPerInputToken !== undefined\n ) {\n warnings.push({\n code: \"OPENROUTER_MARKUP_ESTIMATED\",\n message:\n \"OpenRouter markup estimated at 5% of base token rates (catalog markup fields absent).\",\n });\n }\n\n console.warn(`[ai-tools] ${warnings.map((w) => w.message).join(\" \")}`);\n\n return this.finish(\n {\n cost,\n breakdown,\n resolvedModelId: profileMatch.canonicalModelId,\n routedViaOpenRouter,\n isAuthoritative: false,\n pricingSnapshot: pricing,\n source: \"ai-profiles\",\n warnings,\n },\n input,\n resolved,\n );\n }\n }\n\n if (!resolved?.found || !resolved.record) {\n return this.unknownModelResult(modelInput, input, resolved);\n }\n\n const { record, modelId } = resolved;\n const routedViaOpenRouter = resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n modelId,\n resolverOpts?.routingEnv,\n );\n const pricing = record.pricing;\n const { cost, breakdown } = computeCostFromPricing(\n input,\n pricing,\n routedViaOpenRouter,\n this.includeBreakdown,\n );\n\n return this.finish(\n {\n cost,\n breakdown,\n resolvedModelId: modelId,\n routedViaOpenRouter,\n isAuthoritative: true,\n pricingSnapshot: pricing,\n source: \"catalog\",\n },\n input,\n resolved,\n );\n }\n\n private versionSuffixWarnings(\n input: AiUsageInput,\n pricedModelId: string,\n resolved?: ModelResolutionResult | null,\n ): AiCostWarning[] {\n const received = input.usedModel ?? input.modelUsed ?? input.model;\n if (!received) return [];\n\n const normalizedReceived = normalizeString(received);\n const normalizedPriced = normalizeString(pricedModelId);\n if (normalizedReceived === normalizedPriced) return [];\n\n const stripped = stripModelVersionSuffix(received);\n const viaResolver =\n resolved?.found === true &&\n resolved.resolvedVia.some(\n (s) => s === \"version-suffix-strip\" || s === \"date-suffix-strip\",\n );\n const pricedViaStrip =\n stripped !== null && normalizeString(stripped) === normalizedPriced;\n\n if (!viaResolver && !pricedViaStrip) return [];\n\n return [\n {\n code: \"VERSION_SUFFIX_PRICING\",\n message: `Priced using catalog model \"${pricedModelId}\" (no exact pricing for \"${received}\").`,\n },\n ];\n }\n\n private finish(\n partial: Omit<\n AiCostResult,\n \"usage\" | \"provider\" | \"usedModel\" | \"model\" | \"extraction\"\n >,\n input: AiUsageInput,\n resolved?: ModelResolutionResult | null,\n ): AiCostResult {\n const enriched = enrichCostResult(partial, input);\n const suffixWarnings = this.versionSuffixWarnings(\n input,\n partial.resolvedModelId,\n resolved,\n );\n if (suffixWarnings.length > 0) {\n enriched.warnings = [...(enriched.warnings ?? []), ...suffixWarnings];\n }\n return enriched;\n }\n\n private localProviderResult(\n modelInput: string,\n input: AiUsageInput,\n resolved: Awaited<ReturnType<typeof resolveFromCatalogAttempts>>,\n ): AiCostResult {\n const warnings: AiCostWarning[] = [\n {\n code: \"LOCAL_PROVIDER_NO_PRICING\",\n message: `Local provider \"${input.provider}\" has no catalog pricing for \"${modelInput}\".`,\n },\n ];\n console.warn(`[ai-tools] ${warnings[0]!.message}`);\n return this.finish(\n {\n cost: 0,\n resolvedModelId: resolved?.found ? resolved.modelId : modelInput,\n routedViaOpenRouter: false,\n isAuthoritative: false,\n pricingSnapshot: emptyPricing(),\n source: \"local\",\n warnings,\n },\n input,\n );\n }\n\n private unknownModelResult(\n modelInput: string,\n input: AiUsageInput,\n resolved: Awaited<ReturnType<typeof resolveFromCatalogAttempts>>,\n ): AiCostResult {\n if (this.throwOnUnknownModel) {\n throw new UnknownModelCostError(modelInput, input.provider);\n }\n\n const warnings: AiCostWarning[] = [\n {\n code: \"UNKNOWN_MODEL\",\n message: `Unknown model \"${modelInput}\" (provider: \"${input.provider}\") — returning zero-cost fallback.`,\n },\n ];\n console.warn(`[ai-tools] ${warnings[0]!.message}`);\n\n return this.finish(\n {\n cost: 0,\n resolvedModelId: modelInput,\n routedViaOpenRouter: resolveRoutedViaOpenRouter(\n input.provider,\n resolved,\n modelInput,\n this.resolverOptions?.routingEnv,\n ),\n isAuthoritative: false,\n pricingSnapshot: emptyPricing(),\n source: \"estimate-fallback\",\n unknownModel: true,\n warnings,\n },\n input,\n );\n }\n}\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveModelVendor
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-WMB3YEQQ.js";
|
|
4
4
|
import {
|
|
5
5
|
AiModelsCatalogClient
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-XJQODPN6.js";
|
|
7
7
|
|
|
8
8
|
// src/models/filterModels.ts
|
|
9
9
|
function matchesSearch(record, search) {
|
|
@@ -89,4 +89,4 @@ export {
|
|
|
89
89
|
AiModelsService,
|
|
90
90
|
getModelInfo
|
|
91
91
|
};
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
92
|
+
//# sourceMappingURL=chunk-M35MNKDY.js.map
|
|
@@ -27,7 +27,7 @@ async function resolveProfileForAsk(input) {
|
|
|
27
27
|
const resolved = await resolveAIProfile(input.profile, {
|
|
28
28
|
choice: input.choice,
|
|
29
29
|
source: input.source,
|
|
30
|
-
refresh: input.refresh
|
|
30
|
+
refresh: input.refresh ?? (input.source !== void 0 && input.source !== "auto" ? true : void 0)
|
|
31
31
|
});
|
|
32
32
|
return profileConfigFromResolved(resolved);
|
|
33
33
|
}
|
|
@@ -48,4 +48,4 @@ export {
|
|
|
48
48
|
listAIShortcuts,
|
|
49
49
|
isKnownProfileOrShortcut
|
|
50
50
|
};
|
|
51
|
-
//# sourceMappingURL=chunk-
|
|
51
|
+
//# sourceMappingURL=chunk-MLMQ5LGW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/profiles/resolveProfileForAsk.ts","../src/profiles/index.ts"],"sourcesContent":["import { resolveAIProfile } from \"@x12i/ai-profiles\";\nimport type {\n AIProfileBackend,\n InstructionTier,\n RegistrySourceMode,\n ResolvedAIProfile,\n} from \"@x12i/ai-profiles\";\n\nexport type ResolveProfileForAskInput = {\n profile: string;\n choice?: string;\n source?: RegistrySourceMode;\n refresh?: boolean;\n};\n\n/** FuncX / ask-node model config derived from {@link ResolvedAIProfile}. */\nexport type AskProfileModelConfig = {\n provider: ResolvedAIProfile[\"provider\"];\n model: string;\n instructionTier: InstructionTier;\n backend: AIProfileBackend;\n profile: string;\n choice: string;\n temperature: number;\n outputMode: ResolvedAIProfile[\"runtime\"][\"outputMode\"];\n toolPolicy: ResolvedAIProfile[\"runtime\"][\"toolPolicy\"];\n reasoningEffort: ResolvedAIProfile[\"runtime\"][\"reasoningEffort\"];\n executionMode: ResolvedAIProfile[\"runtime\"][\"executionMode\"];\n requireCitations: boolean;\n allowWeb: boolean;\n allowFileSearch: boolean;\n allowCodeExecution: boolean;\n humanReview: ResolvedAIProfile[\"runtime\"][\"humanReview\"];\n metadata?: Record<string, unknown>;\n pricing?: ResolvedAIProfile[\"pricing\"];\n resolved: ResolvedAIProfile;\n};\n\nexport function profileConfigFromResolved(\n resolved: ResolvedAIProfile,\n): AskProfileModelConfig {\n return {\n provider: resolved.provider,\n model: resolved.modelId,\n instructionTier: resolved.instructionTier,\n backend: resolved.backend,\n profile: resolved.profile,\n choice: resolved.choice,\n temperature: resolved.runtime.temperature,\n outputMode: resolved.runtime.outputMode,\n toolPolicy: resolved.runtime.toolPolicy,\n reasoningEffort: resolved.runtime.reasoningEffort,\n executionMode: resolved.runtime.executionMode,\n requireCitations: resolved.runtime.requireCitations,\n allowWeb: resolved.runtime.allowWeb,\n allowFileSearch: resolved.runtime.allowFileSearch,\n allowCodeExecution: resolved.runtime.allowCodeExecution,\n humanReview: resolved.runtime.humanReview,\n ...(resolved.metadata !== undefined ? { metadata: resolved.metadata } : {}),\n ...(resolved.pricing !== undefined ? { pricing: resolved.pricing } : {}),\n resolved,\n };\n}\n\n/**\n * Resolve a profile (+ optional choice) into ask-node / FuncX model configuration.\n * Uses {@link ResolvedAIProfile.instructionTier} and {@link ResolvedAIProfile.backend}\n * from `@x12i/ai-profiles` — do not duplicate preset tables locally.\n */\nexport async function resolveProfileForAsk(\n input: ResolveProfileForAskInput,\n): Promise<AskProfileModelConfig> {\n const resolved = await resolveAIProfile(input.profile, {\n choice: input.choice,\n source: input.source,\n refresh
|
|
1
|
+
{"version":3,"sources":["../src/profiles/resolveProfileForAsk.ts","../src/profiles/index.ts"],"sourcesContent":["import { resolveAIProfile } from \"@x12i/ai-profiles\";\nimport type {\n AIProfileBackend,\n InstructionTier,\n RegistrySourceMode,\n ResolvedAIProfile,\n} from \"@x12i/ai-profiles\";\n\nexport type ResolveProfileForAskInput = {\n profile: string;\n choice?: string;\n source?: RegistrySourceMode;\n refresh?: boolean;\n};\n\n/** FuncX / ask-node model config derived from {@link ResolvedAIProfile}. */\nexport type AskProfileModelConfig = {\n provider: ResolvedAIProfile[\"provider\"];\n model: string;\n instructionTier: InstructionTier;\n backend: AIProfileBackend;\n profile: string;\n choice: string;\n temperature: number;\n outputMode: ResolvedAIProfile[\"runtime\"][\"outputMode\"];\n toolPolicy: ResolvedAIProfile[\"runtime\"][\"toolPolicy\"];\n reasoningEffort: ResolvedAIProfile[\"runtime\"][\"reasoningEffort\"];\n executionMode: ResolvedAIProfile[\"runtime\"][\"executionMode\"];\n requireCitations: boolean;\n allowWeb: boolean;\n allowFileSearch: boolean;\n allowCodeExecution: boolean;\n humanReview: ResolvedAIProfile[\"runtime\"][\"humanReview\"];\n metadata?: Record<string, unknown>;\n pricing?: ResolvedAIProfile[\"pricing\"];\n resolved: ResolvedAIProfile;\n};\n\nexport function profileConfigFromResolved(\n resolved: ResolvedAIProfile,\n): AskProfileModelConfig {\n return {\n provider: resolved.provider,\n model: resolved.modelId,\n instructionTier: resolved.instructionTier,\n backend: resolved.backend,\n profile: resolved.profile,\n choice: resolved.choice,\n temperature: resolved.runtime.temperature,\n outputMode: resolved.runtime.outputMode,\n toolPolicy: resolved.runtime.toolPolicy,\n reasoningEffort: resolved.runtime.reasoningEffort,\n executionMode: resolved.runtime.executionMode,\n requireCitations: resolved.runtime.requireCitations,\n allowWeb: resolved.runtime.allowWeb,\n allowFileSearch: resolved.runtime.allowFileSearch,\n allowCodeExecution: resolved.runtime.allowCodeExecution,\n humanReview: resolved.runtime.humanReview,\n ...(resolved.metadata !== undefined ? { metadata: resolved.metadata } : {}),\n ...(resolved.pricing !== undefined ? { pricing: resolved.pricing } : {}),\n resolved,\n };\n}\n\n/**\n * Resolve a profile (+ optional choice) into ask-node / FuncX model configuration.\n * Uses {@link ResolvedAIProfile.instructionTier} and {@link ResolvedAIProfile.backend}\n * from `@x12i/ai-profiles` — do not duplicate preset tables locally.\n */\nexport async function resolveProfileForAsk(\n input: ResolveProfileForAskInput,\n): Promise<AskProfileModelConfig> {\n const resolved = await resolveAIProfile(input.profile, {\n choice: input.choice,\n source: input.source,\n refresh:\n input.refresh ??\n (input.source !== undefined && input.source !== \"auto\" ? true : undefined),\n });\n return profileConfigFromResolved(resolved);\n}\n","export {\n resolveProfileForAsk,\n profileConfigFromResolved,\n} from \"./resolveProfileForAsk.js\";\nexport type {\n AskProfileModelConfig,\n ResolveProfileForAskInput,\n} from \"./resolveProfileForAsk.js\";\n\nexport type {\n ResolvedAIProfile,\n InstructionTier,\n AIProfileBackend,\n AIProfileSummary,\n AIShortcutSummary,\n ResolveAIProfileOptions,\n RegistrySourceMode,\n} from \"@x12i/ai-profiles\";\n\nexport {\n resolveAIProfile,\n listAIProfiles,\n listAIShortcuts,\n isKnownProfileOrShortcut,\n} from \"@x12i/ai-profiles\";\n"],"mappings":";AAAA,SAAS,wBAAwB;AAsC1B,SAAS,0BACd,UACuB;AACvB,SAAO;AAAA,IACL,UAAU,SAAS;AAAA,IACnB,OAAO,SAAS;AAAA,IAChB,iBAAiB,SAAS;AAAA,IAC1B,SAAS,SAAS;AAAA,IAClB,SAAS,SAAS;AAAA,IAClB,QAAQ,SAAS;AAAA,IACjB,aAAa,SAAS,QAAQ;AAAA,IAC9B,YAAY,SAAS,QAAQ;AAAA,IAC7B,YAAY,SAAS,QAAQ;AAAA,IAC7B,iBAAiB,SAAS,QAAQ;AAAA,IAClC,eAAe,SAAS,QAAQ;AAAA,IAChC,kBAAkB,SAAS,QAAQ;AAAA,IACnC,UAAU,SAAS,QAAQ;AAAA,IAC3B,iBAAiB,SAAS,QAAQ;AAAA,IAClC,oBAAoB,SAAS,QAAQ;AAAA,IACrC,aAAa,SAAS,QAAQ;AAAA,IAC9B,GAAI,SAAS,aAAa,SAAY,EAAE,UAAU,SAAS,SAAS,IAAI,CAAC;AAAA,IACzE,GAAI,SAAS,YAAY,SAAY,EAAE,SAAS,SAAS,QAAQ,IAAI,CAAC;AAAA,IACtE;AAAA,EACF;AACF;AAOA,eAAsB,qBACpB,OACgC;AAChC,QAAM,WAAW,MAAM,iBAAiB,MAAM,SAAS;AAAA,IACrD,QAAQ,MAAM;AAAA,IACd,QAAQ,MAAM;AAAA,IACd,SACE,MAAM,YACL,MAAM,WAAW,UAAa,MAAM,WAAW,SAAS,OAAO;AAAA,EACpE,CAAC;AACD,SAAO,0BAA0B,QAAQ;AAC3C;;;AC7DA;AAAA,EACE,oBAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["resolveAIProfile"]}
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
DEFAULT_DIRECT_CATALOG_URL,
|
|
4
4
|
DEFAULT_OPENROUTER_CATALOG_URL,
|
|
5
5
|
loadCatalogSourcesCached
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-XJQODPN6.js";
|
|
7
7
|
|
|
8
8
|
// src/catalog/catalogMaintenance.ts
|
|
9
9
|
async function refreshAiModelsCatalog(options = {}) {
|
|
@@ -43,4 +43,4 @@ export {
|
|
|
43
43
|
refreshAiModelsCatalog,
|
|
44
44
|
verifyAiModelsCatalog
|
|
45
45
|
};
|
|
46
|
-
//# sourceMappingURL=chunk-
|
|
46
|
+
//# sourceMappingURL=chunk-PP75SWKY.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkFWPH5YE6cjs = require('./chunk-FWPH5YE6.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunk33AAM7KQcjs = require('./chunk-33AAM7KQ.cjs');
|
|
7
7
|
|
|
8
8
|
// src/models/filterModels.ts
|
|
9
9
|
function matchesSearch(record, search) {
|
|
@@ -49,7 +49,7 @@ function countModels(models, filters = {}) {
|
|
|
49
49
|
var AiModelsService = class {
|
|
50
50
|
|
|
51
51
|
constructor(options = {}) {
|
|
52
|
-
this.client = new (0,
|
|
52
|
+
this.client = new (0, _chunk33AAM7KQcjs.AiModelsCatalogClient)(options);
|
|
53
53
|
}
|
|
54
54
|
async getAllModels() {
|
|
55
55
|
return this.client.getAllModels();
|
|
@@ -73,7 +73,7 @@ var AiModelsService = class {
|
|
|
73
73
|
return this.client.resolveModel({ model: modelIdOrAlias, provider });
|
|
74
74
|
}
|
|
75
75
|
async resolveVendor(model, options) {
|
|
76
|
-
return
|
|
76
|
+
return _chunkFWPH5YE6cjs.resolveModelVendor.call(void 0, model, this.client, options);
|
|
77
77
|
}
|
|
78
78
|
async refresh() {
|
|
79
79
|
await this.client.refresh();
|
|
@@ -89,4 +89,4 @@ async function getModelInfo(modelIdOrAlias, options = {}, provider) {
|
|
|
89
89
|
|
|
90
90
|
|
|
91
91
|
exports.filterModels = filterModels; exports.countModels = countModels; exports.AiModelsService = AiModelsService; exports.getModelInfo = getModelInfo;
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
92
|
+
//# sourceMappingURL=chunk-QILRLRA4.cjs.map
|