@abhishek944/pi-classifier 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,181 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open, realpath } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { verifyOpenedPath } from "./inputs.js";
5
+ import {
6
+ ClassifierError,
7
+ isRecord,
8
+ type ClassifyTreeParams,
9
+ type ClassificationTree,
10
+ type ClassificationTreeNode,
11
+ } from "./types.js";
12
+ import { validateParams } from "./validation.js";
13
+
14
+ const MAX_TREE_BYTES = 2 * 1024 * 1024;
15
+ const MAX_DEPTH = 32;
16
+
17
+ function invalid(message: string): never {
18
+ throw new ClassifierError("input", message);
19
+ }
20
+
21
+ export async function loadTreeInput(
22
+ value: unknown,
23
+ cwd: string,
24
+ signal?: AbortSignal,
25
+ ): Promise<Omit<ClassifyTreeParams, "tree"> & { tree: ClassificationTree }> {
26
+ cancelled(signal);
27
+ if (
28
+ !isRecord(value) ||
29
+ Object.keys(value).some(
30
+ (key) => !["state", "tree", "instructions", "images"].includes(key),
31
+ )
32
+ )
33
+ invalid(
34
+ "Expected state, tree and optional instructions/images; the route is selected in settings.",
35
+ );
36
+ if (
37
+ value.instructions !== undefined &&
38
+ (typeof value.instructions !== "string" ||
39
+ !value.instructions.trim() || value.instructions.length > 8192)
40
+ )
41
+ invalid("Tree instructions must be a non-empty string of at most 8192 characters.");
42
+ // Reuse existing state/image-path validation without making a provider request.
43
+ const base = validateParams({
44
+ state: value.state,
45
+ questions: { tree: { type: "bool", instructions: "Validate tree input." } },
46
+ ...(value.images !== undefined ? { images: value.images } : {}),
47
+ });
48
+ const raw =
49
+ typeof value.tree === "string"
50
+ ? await readTreeFile(value.tree, cwd, signal)
51
+ : value.tree;
52
+ if (!isRecord(raw) || Object.keys(raw).some((key) => key !== "roots"))
53
+ invalid("Classification tree must be an object containing roots.");
54
+ const ancestors = new Set<object>();
55
+ const roots = nodes(raw.roots, 1, ancestors, { bytes: 0 });
56
+ const tree = { roots };
57
+ if (Buffer.byteLength(JSON.stringify(tree)) > MAX_TREE_BYTES)
58
+ invalid("Classification tree must be at most 2 MiB.");
59
+ cancelled(signal);
60
+ const result: Omit<ClassifyTreeParams, "tree"> & { tree: ClassificationTree } = {
61
+ state: base.state,
62
+ tree,
63
+ };
64
+ if (typeof value.instructions === "string")
65
+ result.instructions = value.instructions;
66
+ if (base.images !== undefined) result.images = base.images;
67
+ return result;
68
+ }
69
+
70
+ function nodes(
71
+ value: unknown,
72
+ depth: number,
73
+ ancestors: Set<object>,
74
+ budget: { bytes: number },
75
+ ): ClassificationTreeNode[] {
76
+ if (!Array.isArray(value) || (depth === 1 && value.length === 0))
77
+ invalid(
78
+ "Classification tree roots must be non-empty and children must be arrays when supplied.",
79
+ );
80
+ if (depth > MAX_DEPTH && value.length > 0)
81
+ invalid("Classification tree must be at most 32 levels deep.");
82
+ const ids = new Set<string>();
83
+ return value.map((entry) => {
84
+ if (
85
+ !isRecord(entry) ||
86
+ Object.keys(entry).some((key) => !["id", "description", "children"].includes(key)) ||
87
+ typeof entry.id !== "string" ||
88
+ !entry.id.trim() || entry.id.length > 128 ||
89
+ (entry.description !== undefined &&
90
+ (typeof entry.description !== "string" || entry.description.length > 4096))
91
+ )
92
+ invalid(
93
+ "Each classification tree node needs a non-empty id of at most 128 characters, optional description up to 4096 characters, and optional children.",
94
+ );
95
+ if (ids.has(entry.id)) invalid("Classification tree node IDs must be unique among siblings.");
96
+ if (ancestors.has(entry)) invalid("Classification tree must not contain cycles.");
97
+ ids.add(entry.id);
98
+ ancestors.add(entry);
99
+ const node: ClassificationTreeNode = { id: entry.id };
100
+ if (typeof entry.description === "string") node.description = entry.description;
101
+ // Bound normalization itself, including shared JS subtrees that expand when serialized.
102
+ budget.bytes += Buffer.byteLength(JSON.stringify(node));
103
+ if (budget.bytes > MAX_TREE_BYTES) invalid("Classification tree must be at most 2 MiB.");
104
+ if (entry.children !== undefined)
105
+ node.children = nodes(entry.children, depth + 1, ancestors, budget);
106
+ ancestors.delete(entry);
107
+ return node;
108
+ });
109
+ }
110
+
111
+ async function readTreeFile(
112
+ path: string,
113
+ cwd: string,
114
+ signal?: AbortSignal,
115
+ ): Promise<unknown> {
116
+ if (!path.trim() || path.length > 4096 || /^[a-z]+:/i.test(path))
117
+ invalid(
118
+ "Classification tree must be an inline roots object or a local JSON path inside cwd, not a URL.",
119
+ );
120
+ let bytes: Buffer;
121
+ try {
122
+ const root = await realpath(cwd);
123
+ const target = resolve(root, path);
124
+ const inside = relative(root, target);
125
+ if (
126
+ !inside || inside === ".." ||
127
+ inside.startsWith(".." + sep) || isAbsolute(inside)
128
+ )
129
+ throw new Error();
130
+ let current = root;
131
+ for (const part of inside.split(sep)) {
132
+ cancelled(signal);
133
+ current = resolve(current, part);
134
+ const entry = await lstat(current);
135
+ if (
136
+ entry.isSymbolicLink() ||
137
+ (current === target ? !entry.isFile() : !entry.isDirectory())
138
+ )
139
+ throw new Error();
140
+ }
141
+ if (await realpath(target) !== target) throw new Error();
142
+ const file = await open(
143
+ target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
144
+ );
145
+ try {
146
+ await verifyOpenedPath(file.fd, root, signal);
147
+ const stat = await file.stat();
148
+ if (!stat.isFile() || stat.size < 1 || stat.size > MAX_TREE_BYTES)
149
+ throw new Error();
150
+ const buffer = Buffer.alloc(MAX_TREE_BYTES + 1);
151
+ let offset = 0;
152
+ while (offset < buffer.length) {
153
+ cancelled(signal);
154
+ const next = await file.read(buffer, offset, buffer.length - offset, null);
155
+ if (!next.bytesRead) break;
156
+ offset += next.bytesRead;
157
+ }
158
+ if (offset > MAX_TREE_BYTES) throw new Error();
159
+ bytes = buffer.subarray(0, offset);
160
+ } finally {
161
+ await file.close();
162
+ }
163
+ } catch (error) {
164
+ cancelled(signal);
165
+ if (error instanceof ClassifierError) throw error;
166
+ invalid(
167
+ "Classification tree must be a readable regular file inside cwd, without symlink components, and at most 2 MiB.",
168
+ );
169
+ }
170
+ cancelled(signal);
171
+ try {
172
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
173
+ } catch {
174
+ invalid("Classification tree file must contain valid UTF-8 JSON.");
175
+ }
176
+ }
177
+
178
+ function cancelled(signal?: AbortSignal): void {
179
+ if (signal?.aborted)
180
+ throw new ClassifierError("aborted", "Classification was cancelled.");
181
+ }
package/src/classify.ts CHANGED
@@ -2,6 +2,7 @@ import { performance } from "node:perf_hooks";
2
2
  import { resolveApiKey } from "./auth.js";
3
3
  import { configuredDefault, configuredRoutes, resolveModel } from "./config.js";
4
4
  import { prepareInput } from "./inputs.js";
5
+ import { choicePolicy, executeChoices } from "./choices.js";
5
6
  import { classifyWithProvider } from "./providers.js";
6
7
  import {
7
8
  ClassifierError,
@@ -15,7 +16,7 @@ import {
15
16
  } from "./types.js";
16
17
  import { validateParams } from "./validation.js";
17
18
 
18
- type ClassifyOptions = {
19
+ export type ClassifyOptions = {
19
20
  settings: ClassifierSettings;
20
21
  cwd: string;
21
22
  signal?: AbortSignal;
@@ -43,7 +44,14 @@ async function classifyOnce(
43
44
  const prepared = await prepareInput(input, route, options.cwd, options.signal);
44
45
  checkCancelled(options.signal);
45
46
  const key = resolveApiKey(route);
46
- const result = await classifyWithProvider(route, prepared, key, options.signal);
47
+ const result = await executeChoices(
48
+ prepared,
49
+ route,
50
+ choicePolicy(options.settings),
51
+ (questions) =>
52
+ classifyWithProvider(route, { ...prepared, questions }, key, options.signal),
53
+ options.signal,
54
+ );
47
55
  if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
48
56
  throw new ClassifierError(
49
57
  "response",
@@ -65,6 +73,7 @@ export async function classify(
65
73
  params: unknown,
66
74
  options: ClassifyOptions,
67
75
  ): Promise<ClassifierResult> {
76
+ choicePolicy(options.settings);
68
77
  const input = validateParams(params);
69
78
  const candidates = [
70
79
  configuredDefault(options.settings),
@@ -98,6 +107,7 @@ export async function compareClassifiers(
98
107
  params: unknown,
99
108
  options: ClassifyOptions,
100
109
  ): Promise<ClassifierComparisonResult> {
110
+ choicePolicy(options.settings);
101
111
  const input = validateParams(params);
102
112
  const candidates = configuredRoutes(options.settings, "compare");
103
113
  if (candidates.length === 0)
package/src/config.ts CHANGED
@@ -6,6 +6,8 @@ import {
6
6
  resolveConfigDir,
7
7
  } from "@amaster.ai/pi-shared/settings";
8
8
  import { cloudflareAccountId } from "./auth.js";
9
+ import { resolvePricing } from "./cost.js";
10
+ import { choicePolicy } from "./choices.js";
9
11
  import {
10
12
  ClassifierError,
11
13
  isRecord,
@@ -253,6 +255,7 @@ export function resolveModel(
253
255
  settings: ClassifierSettings,
254
256
  selected: ClassifierRoute = configuredDefault(settings),
255
257
  ): ResolvedModel {
258
+ choicePolicy(settings);
256
259
  const { provider: routeId, model: modelId } = routePair(selected, "route");
257
260
  if (
258
261
  !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(routeId) ||
@@ -372,11 +375,59 @@ export function resolveModel(
372
375
  experimentalImages: raw.experimentalImages === true,
373
376
  requestTimeoutMs: timeout,
374
377
  };
378
+ const pricing = resolvePricing(
379
+ result.provider,
380
+ modelId,
381
+ result.baseUrl,
382
+ raw.pricing,
383
+ );
384
+ if (pricing) result.pricing = pricing;
385
+ if (raw.maxChoices !== undefined) {
386
+ if (
387
+ typeof raw.maxChoices !== "number" ||
388
+ !Number.isSafeInteger(raw.maxChoices) ||
389
+ raw.maxChoices < 2
390
+ )
391
+ return configuration(
392
+ "Provider maxChoices must be a safe integer of at least 2.",
393
+ );
394
+ result.maxChoices = raw.maxChoices;
395
+ } else {
396
+ const knownLimit = knownMaxChoices(result);
397
+ if (knownLimit !== undefined) result.maxChoices = knownLimit;
398
+ }
375
399
  if (configuredApiKey) result.configuredApiKey = configuredApiKey;
376
400
  if (builtIn?.envVar) result.envVar = builtIn.envVar;
377
401
  return result;
378
402
  }
379
403
 
404
+ function knownMaxChoices(route: ResolvedModel): number | undefined {
405
+ const directJev =
406
+ route.provider === "typesafe" &&
407
+ route.baseUrl === "https://api.typesafe.ai/v1" &&
408
+ ["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"].includes(route.model);
409
+ const openai =
410
+ route.provider === "openai" &&
411
+ route.baseUrl === "https://api.openai.com/v1" &&
412
+ route.model === "gpt-6-luna";
413
+ const perplexity =
414
+ route.provider === "perplexity" &&
415
+ route.baseUrl === "https://api.perplexity.ai/v1" &&
416
+ [
417
+ "pplx-decider-v1.1-27b",
418
+ "pplx-decider-v1-27b",
419
+ "pplx-decider-v1.2",
420
+ "pplx-decider-latest",
421
+ "pplx-decider-flash-v1.2",
422
+ "pplx-decider-flash-latest",
423
+ ].includes(route.model);
424
+ const clef =
425
+ route.provider === "cloudflare" &&
426
+ /^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(route.baseUrl) &&
427
+ ["@cf/cloudflare/clef", "@cf/cloudflare/clef-flash"].includes(route.model);
428
+ return directJev || openai || perplexity || clef ? 255 : undefined;
429
+ }
430
+
380
431
  export function listModels(settings: ClassifierSettings): string {
381
432
  const lines = BUILT_INS.flatMap((provider) =>
382
433
  provider.models.map((model) => provider.route + " " + model.id),
package/src/cost.ts ADDED
@@ -0,0 +1,250 @@
1
+ import {
2
+ ClassifierError,
3
+ isRecord,
4
+ type ClassifierCost,
5
+ type ClassifierResult,
6
+ type ResolvedModel,
7
+ type TokenPricing,
8
+ } from "./types.js";
9
+
10
+ // Standard public USD rates, not account-specific billing. Sources and caveats are in README.
11
+ // Keep exact model matches: newer IDs and other hosts must not inherit guessed prices.
12
+ const PRICES: Record<string, Record<string, TokenPricing>> = {
13
+ openai: {
14
+ "gpt-6-luna": {
15
+ inputPerMillion: 0.1,
16
+ outputPerMillion: 0,
17
+ cachedInputPerMillion: 0.01,
18
+ cacheWritePerMillion: 0.125,
19
+ },
20
+ },
21
+ typesafe: Object.fromEntries(
22
+ ["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"].map((id) => [
23
+ id,
24
+ { inputPerMillion: 0.042, outputPerMillion: 0 },
25
+ ]),
26
+ ),
27
+ perplexity: {
28
+ "pplx-decider-v1.1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
29
+ "pplx-decider-v1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
30
+ "pplx-decider-v1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
31
+ "pplx-decider-latest": { inputPerMillion: 0.02, outputPerMillion: 0 },
32
+ "pplx-decider-flash-v1.2": { inputPerMillion: 0.01, outputPerMillion: 0 },
33
+ "pplx-decider-flash-latest": { inputPerMillion: 0.01, outputPerMillion: 0 },
34
+ },
35
+ cloudflare: {
36
+ "@cf/cloudflare/clef": { inputPerMillion: 0.24, outputPerMillion: 0 },
37
+ "@cf/cloudflare/clef-flash": { inputPerMillion: 0.038, outputPerMillion: 0 },
38
+ "typesafe/jev": {
39
+ inputPerMillion: 0.042,
40
+ outputPerMillion: 0,
41
+ cachedInputPerMillion: 0,
42
+ },
43
+ },
44
+ };
45
+
46
+ /** Validate overrides before a request; use public prices only for known official endpoints. */
47
+ export function resolvePricing(
48
+ provider: string,
49
+ model: string,
50
+ baseUrl: string,
51
+ overrides: unknown,
52
+ ): ResolvedModel["pricing"] {
53
+ if (overrides !== undefined) {
54
+ if (!isRecord(overrides))
55
+ throw new ClassifierError(
56
+ "configuration",
57
+ "Provider pricing must be a model-keyed object.",
58
+ );
59
+ if (Object.hasOwn(overrides, model)) {
60
+ const value = overrides[model];
61
+ const keys = [
62
+ "inputPerMillion",
63
+ "outputPerMillion",
64
+ "cachedInputPerMillion",
65
+ "cacheWritePerMillion",
66
+ ];
67
+ if (
68
+ !isRecord(value) ||
69
+ Object.keys(value).some((key) => !keys.includes(key)) ||
70
+ !validRate(value.inputPerMillion) ||
71
+ !validRate(value.outputPerMillion) ||
72
+ keys.slice(2).some(
73
+ (key) => value[key] !== undefined && !validRate(value[key]),
74
+ )
75
+ )
76
+ throw new ClassifierError(
77
+ "configuration",
78
+ "Model pricing requires finite, non-negative inputPerMillion and outputPerMillion USD rates, with optional cachedInputPerMillion and cacheWritePerMillion.",
79
+ );
80
+ const rates: TokenPricing = {
81
+ inputPerMillion: value.inputPerMillion,
82
+ outputPerMillion: value.outputPerMillion,
83
+ };
84
+ if (validRate(value.cachedInputPerMillion))
85
+ rates.cachedInputPerMillion = value.cachedInputPerMillion;
86
+ if (validRate(value.cacheWritePerMillion))
87
+ rates.cacheWritePerMillion = value.cacheWritePerMillion;
88
+ return { rates, source: "configured" };
89
+ }
90
+ }
91
+ const official =
92
+ (provider === "openai" && baseUrl === "https://api.openai.com/v1") ||
93
+ (provider === "typesafe" && baseUrl === "https://api.typesafe.ai/v1") ||
94
+ (provider === "perplexity" && baseUrl === "https://api.perplexity.ai/v1") ||
95
+ (provider === "cloudflare" &&
96
+ /^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(baseUrl));
97
+ const catalog = Object.hasOwn(PRICES, provider) ? PRICES[provider] : undefined;
98
+ const rates =
99
+ official && catalog && Object.hasOwn(catalog, model)
100
+ ? catalog[model]
101
+ : undefined;
102
+ return rates ? { rates: { ...rates }, source: "builtin" } : undefined;
103
+ }
104
+
105
+ function validRate(value: unknown): value is number {
106
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
107
+ }
108
+
109
+ export function tokenCount(value: unknown): number | undefined {
110
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
111
+ ? value
112
+ : undefined;
113
+ }
114
+
115
+ function unavailable(
116
+ reason: Extract<ClassifierCost, { status: "unavailable" }>["reason"],
117
+ ): ClassifierCost {
118
+ return { status: "unavailable", currency: "USD", reason };
119
+ }
120
+
121
+ /** Raw usage is intentional: legacy normalized usage fills missing counters with zero. */
122
+ export function estimateCost(
123
+ route: ResolvedModel,
124
+ usage: unknown,
125
+ ): ClassifierCost {
126
+ if (!route.pricing) return unavailable("unknown_pricing");
127
+ if (!isRecord(usage) || usage.input_tokens === undefined)
128
+ return unavailable("missing_usage");
129
+ const inputTokens = tokenCount(usage.input_tokens);
130
+ if (
131
+ usage.output_tokens === undefined &&
132
+ route.pricing.rates.outputPerMillion !== 0
133
+ )
134
+ return unavailable("missing_usage");
135
+ // Missing output usage is harmless only when the output rate is zero.
136
+ const outputTokens =
137
+ usage.output_tokens === undefined ? 0 : tokenCount(usage.output_tokens);
138
+ if (inputTokens === undefined || outputTokens === undefined)
139
+ return unavailable("invalid_usage");
140
+ const details = usage.input_tokens_details;
141
+ if (details !== undefined && !isRecord(details))
142
+ return unavailable("invalid_usage");
143
+ const cached =
144
+ isRecord(details) && details.cached_tokens !== undefined
145
+ ? tokenCount(details.cached_tokens)
146
+ : 0;
147
+ const writes =
148
+ isRecord(details) && details.cache_write_tokens !== undefined
149
+ ? tokenCount(details.cache_write_tokens)
150
+ : 0;
151
+ if (
152
+ cached === undefined ||
153
+ writes === undefined ||
154
+ cached > inputTokens ||
155
+ writes > inputTokens - cached
156
+ )
157
+ return unavailable("invalid_usage");
158
+ const rates = { ...route.pricing.rates };
159
+ // The extension uses default 30m cache writes. Do not misprice an unexpected 12h write.
160
+ if (isRecord(details) && details.cache_write_tokens_details !== undefined) {
161
+ const writeDetails = details.cache_write_tokens_details;
162
+ if (!isRecord(writeDetails)) return unavailable("invalid_usage");
163
+ const shortWrites = tokenCount(writeDetails.ttl_30m_tokens);
164
+ const longWrites = tokenCount(writeDetails.ttl_12h_tokens);
165
+ if (
166
+ shortWrites === undefined ||
167
+ longWrites === undefined ||
168
+ shortWrites > writes ||
169
+ longWrites !== writes - shortWrites
170
+ )
171
+ return unavailable("invalid_usage");
172
+ if (longWrites > 0) return unavailable("missing_cache_pricing");
173
+ }
174
+ if (
175
+ (cached > 0 && rates.cachedInputPerMillion === undefined) ||
176
+ (writes > 0 && rates.cacheWritePerMillion === undefined)
177
+ )
178
+ return unavailable("missing_cache_pricing");
179
+ // OpenAI doubles input rates for >272K context. Overrides already define effective rates.
180
+ if (
181
+ route.provider === "openai" &&
182
+ route.pricing.source === "builtin" &&
183
+ inputTokens > 272_000
184
+ ) {
185
+ rates.inputPerMillion *= 2;
186
+ if (rates.cachedInputPerMillion !== undefined)
187
+ rates.cachedInputPerMillion *= 2;
188
+ if (rates.cacheWritePerMillion !== undefined)
189
+ rates.cacheWritePerMillion *= 2;
190
+ }
191
+ const input =
192
+ ((inputTokens - cached - writes) / 1_000_000) * rates.inputPerMillion +
193
+ (cached / 1_000_000) * (rates.cachedInputPerMillion ?? 0) +
194
+ (writes / 1_000_000) * (rates.cacheWritePerMillion ?? 0);
195
+ const output = (outputTokens / 1_000_000) * rates.outputPerMillion;
196
+ const total = input + output;
197
+ if (![input, output, total].every(Number.isFinite))
198
+ return unavailable("calculation_overflow");
199
+ return {
200
+ status: "estimated",
201
+ currency: "USD",
202
+ input,
203
+ output,
204
+ total,
205
+ rates,
206
+ source: route.pricing.source,
207
+ };
208
+ }
209
+
210
+ export function sumUsage(
211
+ left: ClassifierResult["usage"],
212
+ right: ClassifierResult["usage"],
213
+ ): ClassifierResult["usage"] {
214
+ if (!left || !right) return undefined;
215
+ const result: NonNullable<ClassifierResult["usage"]> = {
216
+ inputTokens: left.inputTokens + right.inputTokens,
217
+ outputTokens: left.outputTokens + right.outputTokens,
218
+ totalTokens: left.totalTokens + right.totalTokens,
219
+ };
220
+ if (!Object.values(result).every(Number.isSafeInteger)) return undefined;
221
+ for (const field of ["cachedInputTokens", "cacheWriteTokens"] as const) {
222
+ if (left[field] !== undefined && right[field] !== undefined) {
223
+ const total = left[field] + right[field];
224
+ if (Number.isSafeInteger(total)) result[field] = total;
225
+ }
226
+ }
227
+ return result;
228
+ }
229
+
230
+ export function sumCost(left: ClassifierCost, right: ClassifierCost): ClassifierCost {
231
+ if (left.status === "unavailable") return left;
232
+ if (right.status === "unavailable") return right;
233
+ const input = left.input + right.input;
234
+ const output = left.output + right.output;
235
+ const total = input + output;
236
+ if (![input, output, total].every(Number.isFinite))
237
+ return {
238
+ status: "unavailable",
239
+ currency: "USD",
240
+ reason: "calculation_overflow",
241
+ };
242
+ return {
243
+ status: "estimated",
244
+ currency: "USD",
245
+ source: "aggregated",
246
+ input,
247
+ output,
248
+ total,
249
+ };
250
+ }