@crocketc/dsh-capability-manager 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Measure one assembled DSH request's initial injected context.
3
+ *
4
+ * This module consumes host-normalized request facts. It deliberately stores no
5
+ * prompt text; callers may persist only the numeric result.
6
+ */
7
+
8
+ const CHARS_PER_TOKEN = 4;
9
+ const BLOCK_OVERHEAD = 4;
10
+
11
+ const PROMPT_KINDS = new Set([
12
+ 'base-system',
13
+ 'automatic',
14
+ 'skill-catalog',
15
+ 'tool-prompt',
16
+ 'other',
17
+ ]);
18
+ const TOOL_SOURCES = new Set(['mcp', 'dsh', 'plugin', 'unknown']);
19
+ const TOOL_MODES = new Set(['native', 'ptc', 'run-code']);
20
+
21
+ function object(value, label) {
22
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
23
+ throw new TypeError(`${label} must be an object`);
24
+ }
25
+ return value;
26
+ }
27
+
28
+ function text(value, label) {
29
+ if (typeof value !== 'string') throw new TypeError(`${label} must be a string`);
30
+ return value;
31
+ }
32
+
33
+ function nonEmpty(value, label) {
34
+ text(value, label);
35
+ if (value.length === 0) throw new TypeError(`${label} must not be empty`);
36
+ return value;
37
+ }
38
+
39
+ /** DSH's fixed-density estimate for one plain-text prompt contribution. */
40
+ export function estimateTextTokens(value) {
41
+ text(value, 'text');
42
+ return Math.ceil(value.length / CHARS_PER_TOKEN);
43
+ }
44
+
45
+ function estimateSchemaTokens(schema) {
46
+ return Math.ceil(JSON.stringify(schema).length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
47
+ }
48
+
49
+ function validInitialRequest(request) {
50
+ object(request, 'request');
51
+ const header = object(request.header, 'request.header');
52
+ if (header.reason !== 'initial' || header.startsSeries !== true) {
53
+ throw new Error('measurement requires the initial request/header for a new session');
54
+ }
55
+ if (!Number.isInteger(request.turn) || request.turn < 0
56
+ || !Number.isInteger(request.step) || request.step < 0) {
57
+ throw new TypeError('request.turn and request.step must be non-negative integers');
58
+ }
59
+ }
60
+
61
+ function addCategory(total, category, tokens) {
62
+ total[category] += tokens;
63
+ }
64
+
65
+ function measurePtcSdk(ptcSdk) {
66
+ if (ptcSdk === undefined) {
67
+ return { sdkTokens: 0, sharedTokens: 0, tools: {}, sources: {} };
68
+ }
69
+ object(ptcSdk, 'ptcSdk');
70
+ const sdkText = text(ptcSdk.text, 'ptcSdk.text');
71
+ const declarations = ptcSdk.declarations ?? [];
72
+ if (!Array.isArray(declarations)) throw new TypeError('ptcSdk.declarations must be an array');
73
+
74
+ // Declarations are exact substrings from the rendered TOOLS_SDK section.
75
+ // Locate each once, in order, so the SDK text's total is allocated without
76
+ // counting the shared template or an item twice.
77
+ const matches = [];
78
+ let cursor = 0;
79
+ for (const [index, declaration] of declarations.entries()) {
80
+ object(declaration, `ptcSdk.declarations[${index}]`);
81
+ const name = nonEmpty(declaration.name, `ptcSdk.declarations[${index}].name`);
82
+ const fragment = nonEmpty(declaration.text, `ptcSdk.declarations[${index}].text`);
83
+ const start = sdkText.indexOf(fragment, cursor);
84
+ if (start < 0) throw new Error(`PTC declaration "${name}" is not present in ptcSdk.text in order`);
85
+ const source = declaration.source ?? 'unknown';
86
+ if (!TOOL_SOURCES.has(source)) throw new TypeError(`ptcSdk.declarations[${index}].source is unsupported`);
87
+ matches.push({ name, source, start, end: start + fragment.length });
88
+ cursor = start + fragment.length;
89
+ }
90
+
91
+ const sdkTokens = estimateTextTokens(sdkText);
92
+ let previousCharacters = 0;
93
+ let previousTokens = 0;
94
+ let sharedTokens = 0;
95
+ const toolTokens = new Map();
96
+ const toolSources = new Map();
97
+ const slices = [];
98
+ cursor = 0;
99
+ for (const match of matches) {
100
+ if (match.start > cursor) slices.push({ start: cursor, end: match.start });
101
+ slices.push({ start: match.start, end: match.end, name: match.name, source: match.source });
102
+ cursor = match.end;
103
+ }
104
+ if (cursor < sdkText.length) slices.push({ start: cursor, end: sdkText.length });
105
+ for (const slice of slices) {
106
+ previousCharacters += slice.end - slice.start;
107
+ const nextTokens = Math.ceil(previousCharacters / CHARS_PER_TOKEN);
108
+ const tokens = nextTokens - previousTokens;
109
+ previousTokens = nextTokens;
110
+ if (slice.name === undefined) sharedTokens += tokens;
111
+ else {
112
+ toolTokens.set(slice.name, (toolTokens.get(slice.name) ?? 0) + tokens);
113
+ toolSources.set(slice.name, slice.source);
114
+ }
115
+ }
116
+ return {
117
+ sdkTokens,
118
+ sharedTokens,
119
+ tools: Object.fromEntries(toolTokens),
120
+ sources: Object.fromEntries(toolSources),
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Measure a newly assembled session's first DSH model request.
126
+ *
127
+ * Input contract:
128
+ * - `request.header` is the durable DSH request/header event data; only
129
+ * `{reason: 'initial', startsSeries: true}` is accepted.
130
+ * - `promptParts` are the final system-prompt contributions, each tagged with
131
+ * provenance. Skill catalog entries may carry `workspace: true`.
132
+ * - `tools` are the actual model-visible schemas. PTC's `TOOLS_SDK` text is
133
+ * supplied once as `ptcSdk`, with exact per-tool declaration substrings for
134
+ * additive attribution. The `run_code` entry is a separate tool row.
135
+ * - `providerUsage` is the completed assistant message's normalized usage and
136
+ * is returned separately as a reference, never added to estimates.
137
+ *
138
+ * The host should call this after the initial assistant/message is committed,
139
+ * using facts captured from the request/header and the request passed to the
140
+ * LLM seam. Do not use later step requests or an existing/resumed session.
141
+ */
142
+ export function measureInitialRequest(input) {
143
+ object(input, 'input');
144
+ validInitialRequest(input.request);
145
+ const promptParts = input.promptParts ?? [];
146
+ const tools = input.tools ?? [];
147
+ if (!Array.isArray(promptParts)) throw new TypeError('promptParts must be an array');
148
+ if (!Array.isArray(tools)) throw new TypeError('tools must be an array');
149
+
150
+ const prompt = {
151
+ baseSystemTokens: 0,
152
+ automaticTokens: 0,
153
+ skillCatalogTokens: 0,
154
+ workspaceSkillCatalogTokens: 0,
155
+ toolPromptTokens: 0,
156
+ otherTokens: 0,
157
+ };
158
+ for (const [index, part] of promptParts.entries()) {
159
+ object(part, `promptParts[${index}]`);
160
+ if (!PROMPT_KINDS.has(part.kind)) throw new TypeError(`promptParts[${index}].kind is unsupported`);
161
+ const tokens = estimateTextTokens(text(part.text, `promptParts[${index}].text`));
162
+ switch (part.kind) {
163
+ case 'base-system': addCategory(prompt, 'baseSystemTokens', tokens); break;
164
+ case 'automatic': addCategory(prompt, 'automaticTokens', tokens); break;
165
+ case 'skill-catalog':
166
+ addCategory(prompt, 'skillCatalogTokens', tokens);
167
+ if (part.workspace === true) addCategory(prompt, 'workspaceSkillCatalogTokens', tokens);
168
+ break;
169
+ case 'tool-prompt': addCategory(prompt, 'toolPromptTokens', tokens); break;
170
+ case 'other': addCategory(prompt, 'otherTokens', tokens); break;
171
+ }
172
+ }
173
+
174
+ const nativeTools = { mcpTokens: 0, dshTokens: 0, pluginTokens: 0, unknownTokens: 0, runCodeTokens: 0 };
175
+ const toolRows = [];
176
+ const names = new Set();
177
+ for (const [index, tool] of tools.entries()) {
178
+ object(tool, `tools[${index}]`);
179
+ const name = nonEmpty(tool.name, `tools[${index}].name`);
180
+ if (names.has(name)) throw new Error(`duplicate model-visible tool "${name}"`);
181
+ names.add(name);
182
+ if (!TOOL_SOURCES.has(tool.source)) throw new TypeError(`tools[${index}].source is unsupported`);
183
+ if (!TOOL_MODES.has(tool.mode)) throw new TypeError(`tools[${index}].mode is unsupported`);
184
+ let tokens = 0;
185
+ if (tool.mode !== 'ptc') tokens = estimateSchemaTokens(object(tool.schema, `tools[${index}].schema`));
186
+ const row = { name, source: tool.source, mode: tool.mode, tokens, enabled: tool.enabled !== false };
187
+ toolRows.push(row);
188
+ if (tool.mode === 'run-code') nativeTools.runCodeTokens += tokens;
189
+ else if (tool.mode === 'native') nativeTools[`${tool.source}Tokens`] += tokens;
190
+ }
191
+
192
+ const ptc = measurePtcSdk(input.ptcSdk);
193
+ const ptcToolAttribution = { mcpTokens: 0, dshTokens: 0, pluginTokens: 0, unknownTokens: 0 };
194
+ for (const row of toolRows) {
195
+ if (row.mode !== 'ptc') continue;
196
+ if (ptc.tools[row.name] === undefined) throw new Error(`PTC tool "${row.name}" has no rendered SDK declaration`);
197
+ if (ptc.sources[row.name] !== row.source) throw new Error(`PTC tool "${row.name}" source disagrees with its rendered declaration`);
198
+ row.tokens = ptc.tools[row.name];
199
+ ptcToolAttribution[`${row.source}Tokens`] += row.tokens;
200
+ }
201
+ const skillCatalogTokens = prompt.skillCatalogTokens;
202
+ const agentCapabilityTokens = skillCatalogTokens + prompt.toolPromptTokens
203
+ + nativeTools.mcpTokens + nativeTools.dshTokens + nativeTools.pluginTokens
204
+ + nativeTools.unknownTokens + nativeTools.runCodeTokens + ptc.sdkTokens;
205
+ const automaticInjectionTokens = prompt.automaticTokens + prompt.otherTokens;
206
+ const estimatedTotalTokens = prompt.baseSystemTokens + automaticInjectionTokens + agentCapabilityTokens;
207
+
208
+ let providerUsageInputTokens;
209
+ if (input.providerUsage !== undefined) {
210
+ object(input.providerUsage, 'providerUsage');
211
+ const count = input.providerUsage.inputTokens;
212
+ if (!Number.isSafeInteger(count) || count < 0) {
213
+ throw new TypeError('providerUsage.inputTokens must be a non-negative safe integer');
214
+ }
215
+ providerUsageInputTokens = count;
216
+ }
217
+
218
+ return {
219
+ prompt,
220
+ nativeTools,
221
+ ptcToolAttribution,
222
+ toolRows,
223
+ ptc: { sdkTokens: ptc.sdkTokens, sharedTokens: ptc.sharedTokens, tools: ptc.tools },
224
+ totals: {
225
+ skillCatalogTokens,
226
+ agentCapabilityTokens,
227
+ automaticInjectionTokens,
228
+ estimatedTotalTokens,
229
+ ...(providerUsageInputTokens === undefined ? {} : { providerUsageInputTokens }),
230
+ },
231
+ };
232
+ }
package/src/policy.js ADDED
@@ -0,0 +1,84 @@
1
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { dirname } from 'node:path'
4
+
5
+ export const reservedTools = new Set(['run_code'])
6
+
7
+ function names(values) {
8
+ if (!Array.isArray(values) || values.some(value => typeof value !== 'string' || !value || value.length > 256)) {
9
+ throw new TypeError('无效的能力名称清单')
10
+ }
11
+ return [...new Set(values)].sort()
12
+ }
13
+
14
+ function normalize(policy) {
15
+ return {
16
+ disabledTools: names(policy.disabledTools ?? []).filter(name => !reservedTools.has(name)),
17
+ enabledTools: names(policy.enabledTools ?? []).filter(name => !reservedTools.has(name)),
18
+ disabledSkills: names(policy.disabledSkills ?? []),
19
+ enabledSkills: names(policy.enabledSkills ?? []),
20
+ }
21
+ }
22
+
23
+ export async function openPolicyStore(file) {
24
+ let persisted
25
+ try {
26
+ persisted = JSON.parse(await readFile(file, 'utf8'))
27
+ } catch (error) {
28
+ if (error.code !== 'ENOENT') throw error
29
+ persisted = { version: 1, presets: {}, importedSkills: [] }
30
+ }
31
+ if (persisted.version !== 1 || !persisted.presets || Array.isArray(persisted.presets)) {
32
+ throw new Error('不支持的能力配置文件格式')
33
+ }
34
+ let state = {
35
+ presets: new Map(Object.entries(persisted.presets).map(([id, policy]) => [id, normalize(policy)])),
36
+ importedSkills: names(persisted.importedSkills ?? []),
37
+ }
38
+ let pending = Promise.resolve()
39
+ const publishing = new Set()
40
+ function update(mutator, publication) {
41
+ const written = pending.then(async () => {
42
+ const next = { presets: new Map(state.presets), importedSkills: [...state.importedSkills] }
43
+ mutator(next)
44
+ await mkdir(dirname(file), { recursive: true })
45
+ const temporary = `${file}.${randomUUID()}.tmp`
46
+ try {
47
+ await writeFile(temporary, JSON.stringify({ version: 1, presets: Object.fromEntries(next.presets), importedSkills: next.importedSkills }, null, 2), { flag: 'wx' })
48
+ if (publication) {
49
+ publishing.add(publication.name)
50
+ await publication.publish()
51
+ }
52
+ await rename(temporary, file)
53
+ state = next
54
+ } finally {
55
+ if (publication) publishing.delete(publication.name)
56
+ await rm(temporary, { force: true })
57
+ }
58
+ })
59
+ pending = written.catch(() => {})
60
+ return written
61
+ }
62
+ return {
63
+ get(id) {
64
+ return { ...normalize(state.presets.get(id) ?? {}), importedSkills: [...new Set([...state.importedSkills, ...publishing])] }
65
+ },
66
+ save(id, policy) {
67
+ if (typeof id !== 'string' || !id || id.length > 256) throw new TypeError('无效的 Agent 预设')
68
+ return update(next => next.presets.set(id, normalize(policy)))
69
+ },
70
+ registerImport(name, publish) {
71
+ return update(next => { next.importedSkills = names([...next.importedSkills, name]) }, { name, publish })
72
+ },
73
+ }
74
+ }
75
+
76
+ export function toolEnabled(policy, name, original) {
77
+ if (reservedTools.has(name)) return original
78
+ return !policy.disabledTools.includes(name) && (original || policy.enabledTools.includes(name))
79
+ }
80
+
81
+ export function skillEnabled(policy, name) {
82
+ return !policy.disabledSkills.includes(name) &&
83
+ (!policy.importedSkills.includes(name) || policy.enabledSkills.includes(name))
84
+ }
package/src/pricing.js ADDED
@@ -0,0 +1,39 @@
1
+ import pricing from './vendor/pricing.cjs'
2
+
3
+ // DSH Usage 39bbf3688ac7673b9f5760609f4a910b3f6a3c1b.
4
+ // The pinned catalog and matching engine are distributed under the upstream MIT license.
5
+ const deepseekRoutes = new Set(['deepseek-official', 'deepseek-messages'])
6
+ const officialAliases = { 'deepseek-flash': 'deepseek-v4-flash', 'deepseek-pro': 'deepseek-v4-pro' }
7
+
8
+ export function quoteMonthly(selection, delta, contextTokens, providerPresent, now = Date.now()) {
9
+ const version = pricing.catalog.version
10
+ if (!selection?.model || !selection?.provider) return { status: '默认模型不可用', version }
11
+ const { provider, model, serviceTier } = selection
12
+ const result = { model: `${provider} / ${model}`, version }
13
+ if (!providerPresent) return { ...result, status: '默认模型不可用' }
14
+ if (provider === 'deepseek-account' || /(?:token-plan|coding|codex|subscription)/i.test(provider)) {
15
+ return { ...result, status: '暂无适用费率' }
16
+ }
17
+
18
+ const isDeepSeek = deepseekRoutes.has(provider)
19
+ const identity = {
20
+ providerId: isDeepSeek ? 'deepseek-official' : provider,
21
+ modelRaw: isDeepSeek ? officialAliases[model] ?? model : model,
22
+ accountType: 'api',
23
+ }
24
+ const quote = pricing.priceUsage({ uncached: 1_000_000, contextTokens, serviceTier, time: now }, identity)
25
+ if (!quote.ruleId || quote.pricing?.basis !== 'provider' || !Number.isFinite(quote.amount)) {
26
+ return { ...result, status: pricing.providerFamilyOf(identity.providerId) === 'unknown' ? '暂无适用费率' : '默认模型不可用' }
27
+ }
28
+ const rule = pricing.RULES.find(item => item.id === quote.ruleId)
29
+ const periods = rule?.timeOfUse ?? rule
30
+ const rates = periods?.offPeak && periods?.peak && (rule.timeOfUse || Date.parse(rule.retrievedAt) < now)
31
+ ? [periods.offPeak.uncached, periods.peak.uncached]
32
+ : [quote.amount]
33
+ if (rates.some(rate => !Number.isFinite(rate))) return { ...result, status: '暂无适用费率' }
34
+ const values = rates.map(rate => rate * delta * 1500 / 1_000_000)
35
+ return {
36
+ ...result, status: 'priced', currency: quote.currency,
37
+ minimum: Math.min(...values), maximum: Math.max(...values),
38
+ }
39
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 rongyi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,95 @@
1
+ // Shared payload guardrails for the host, browser and RPC boundary. A catalog
2
+ // can grow with provider coverage, and custom overrides can be much larger than
3
+ // a single rule; keep these limits in one place so they cannot drift.
4
+ const MAX_CATALOG_BYTES = 8 * 1024 * 1024;
5
+ const MAX_OVERRIDES_BYTES = 1 * 1024 * 1024;
6
+ // JSON encoding a valid catalog string can double its quotes, backslashes and
7
+ // whitespace. Reserve separate space for the signature and cache metadata.
8
+ const MAX_ENVELOPE_BYTES = 2 * MAX_CATALOG_BYTES + 1024;
9
+ const MAX_CACHE_BYTES = MAX_ENVELOPE_BYTES + 1024;
10
+ function utf8ByteLength(value) { return new TextEncoder().encode(value).byteLength; }
11
+ function snapshotJson(value, limit, label) {
12
+ const json = JSON.stringify(value);
13
+ check(utf8ByteLength(json) <= limit, label + ' bytes');
14
+ return json;
15
+ }
16
+
17
+ // Shared, bounded validation for local, remote, and browser price snapshots.
18
+ const FIELDS = ['uncached', 'cacheRead', 'cacheWrite', 'output'];
19
+ const TIERS = ['standard', 'priority', 'batch', 'flex'];
20
+ const RULE_KEYS = new Set(['id', 'family', 'canonical', 'aliases', 'currency', 'sourceUrl', 'retrievedAt', 'rates', 'reasoningIncludedInOutput', 'confidence', 'legacy', 'offPeak', 'peak', 'contextTiers', 'contextThreshold', 'serviceTiers', 'tierMultipliers', 'effectiveFrom', 'effectiveTo', 'observedFrom', 'providerId', 'accountType', 'cacheWriteDurationUnknown', 'cacheStorageUnknown', 'cacheWritePriceUnknown', 'note', 'timeOfUse']);
21
+ function check(ok, label) { if (!ok) throw new TypeError('Invalid pricing: ' + label); }
22
+ function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
23
+ function text(value, limit = 250) { return typeof value === 'string' && value.length > 0 && value.length <= limit && !/[\x00-\x1f]/.test(value); }
24
+ function timestamp(value) { return typeof value === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) && Number.isFinite(Date.parse(value)); }
25
+ function source(value) { try { const u = new URL(value); return u.protocol === 'https:' && !u.username && !u.password && !u.search && !u.hash; } catch { return false; } }
26
+ function rates(value) {
27
+ check(record(value) && Object.keys(value).length === 4, 'rates');
28
+ for (const k of FIELDS) check(value[k] === null || Number.isFinite(value[k]) && value[k] >= 0 && value[k] <= 1e7, k);
29
+ }
30
+ function tiers(value) { check(record(value) && Object.keys(value).length === 2, 'context tiers'); rates(value.short); rates(value.long); }
31
+ function rule(value, custom) {
32
+ check(record(value) && Object.keys(value).every(k => RULE_KEYS.has(k)), 'rule fields');
33
+ for (const k of ['id', 'family', 'canonical']) check(text(value[k]), k);
34
+ check(['CNY', 'USD'].includes(value.currency), 'currency');
35
+ check(['exact', 'estimated'].includes(value.confidence), 'confidence');
36
+ check(value.sourceUrl === null && custom || source(value.sourceUrl), 'source URL');
37
+ check(typeof value.retrievedAt === 'string' && /^\d{4}-\d\d-\d\d$/.test(value.retrievedAt) && Number.isFinite(Date.parse(value.retrievedAt)), 'retrieved date');
38
+ check(Array.isArray(value.aliases) && value.aliases.length > 0 && value.aliases.length <= 30 && value.aliases.every(a => text(a) && a === a.toLowerCase()) && value.aliases.includes(value.canonical.toLowerCase()), 'aliases');
39
+ check(value.reasoningIncludedInOutput === true, 'reasoning billing semantics');
40
+ if (custom || value.providerId !== undefined) check(text(value.providerId), 'provider ID');
41
+ if (value.accountType !== undefined) check(['api', 'relay', 'local'].includes(value.accountType), 'account type');
42
+ for (const k of ['effectiveFrom', 'effectiveTo', 'observedFrom']) if (value[k] !== undefined) check(timestamp(value[k]), k);
43
+ if (value.effectiveFrom && value.effectiveTo) check(Date.parse(value.effectiveFrom) < Date.parse(value.effectiveTo), 'effective interval');
44
+ for (const k of ['cacheWriteDurationUnknown', 'cacheStorageUnknown', 'cacheWritePriceUnknown']) if (value[k] !== undefined) check(typeof value[k] === 'boolean', k);
45
+ if (value.note !== undefined) check(text(value.note, 1000), 'note');
46
+ const modes = [value.rates != null, value.legacy != null, value.contextTiers != null, value.serviceTiers != null, value.timeOfUse != null].filter(Boolean).length;
47
+ check(modes === 1, 'one rate mode required');
48
+ if (value.timeOfUse) {
49
+ const t = value.timeOfUse, c = t.calendar;
50
+ check(value.family === 'deepseek' && record(t) && Object.keys(t).every(k => ['peak', 'offPeak', 'calendar'].includes(k)), 'time of use');
51
+ rates(t.peak); rates(t.offPeak);
52
+ const day = v => typeof v === 'string' && /^\d{4}-\d\d-\d\d$/.test(v) && Number.isFinite(Date.parse(v)) && new Date(v).toISOString().slice(0, 10) === v;
53
+ check(record(c) && Object.keys(c).every(k => ['from', 'to', 'holidays', 'sourceUrl'].includes(k)) && day(c.from) && day(c.to) && c.from <= c.to && source(c.sourceUrl), 'calendar');
54
+ check(Array.isArray(c.holidays) && c.holidays.length <= 1000 && new Set(c.holidays).size === c.holidays.length && c.holidays.every(d => day(d) && d >= c.from && d <= c.to), 'calendar holidays');
55
+ }
56
+ if (value.rates != null) rates(value.rates);
57
+ if (value.legacy) { check(value.family === 'deepseek', 'legacy family'); rates(value.legacy); rates(value.peak); rates(value.offPeak); }
58
+ if (value.contextTiers) { tiers(value.contextTiers); check(Number.isSafeInteger(value.contextThreshold) && value.contextThreshold > 0, 'context threshold'); }
59
+ if (value.serviceTiers) { check(record(value.serviceTiers) && Object.keys(value.serviceTiers).every(k => TIERS.includes(k)), 'service tiers'); for (const v of Object.values(value.serviceTiers)) tiers(v); }
60
+ if (value.tierMultipliers !== undefined) { check(record(value.tierMultipliers) && Object.keys(value.tierMultipliers).every(k => TIERS.includes(k)), 'multipliers'); for (const v of Object.values(value.tierMultipliers)) check(Number.isFinite(v) && v > 0 && v <= 100, 'multiplier'); }
61
+ }
62
+ function freeze(value) { if (value && typeof value === 'object' && !Object.isFrozen(value)) { Object.values(value).forEach(freeze); Object.freeze(value); } return value; }
63
+ function rules(values, custom) {
64
+ check(Array.isArray(values) && values.length <= (custom ? 500 : 20000) && (custom || values.length > 0), 'rule count');
65
+ const ids = new Set(), aliases = new Map();
66
+ for (const value of values) {
67
+ rule(value, custom); check(!ids.has(value.id), 'duplicate rule ID'); ids.add(value.id);
68
+ for (const alias of value.aliases) {
69
+ const key = JSON.stringify([value.providerId || 'family:' + value.family, alias]);
70
+ const spans = aliases.get(key) || [];
71
+ const from = value.effectiveFrom ? Date.parse(value.effectiveFrom) : -Infinity, to = value.effectiveTo ? Date.parse(value.effectiveTo) : Infinity;
72
+ check(!spans.some(([a, b, account]) => from < b && a < to && (!account || !value.accountType || account === value.accountType)), 'overlapping rules: ' + alias);
73
+ spans.push([from, to, value.accountType]); aliases.set(key, spans);
74
+ }
75
+ }
76
+ }
77
+ const validated = new WeakSet();
78
+ function validateCatalog(input) {
79
+ if (validated.has(input)) return input;
80
+ check(record(input) && Object.keys(input).every(k => ['schemaVersion', 'version', 'publishedAt', 'rules', 'fx'].includes(k)), 'catalog fields');
81
+ check([1, 2].includes(input.schemaVersion) && Number.isSafeInteger(input.version) && input.version > 0 && timestamp(input.publishedAt), 'catalog version');
82
+ rules(input.rules, false);
83
+ check(input.schemaVersion >= 2 || input.rules.every(r => !r.timeOfUse), 'time of use requires schema 2');
84
+ check(Array.isArray(input.fx) && input.fx.length > 0 && input.fx.length <= 10000, 'FX entries');
85
+ let previous = -Infinity;
86
+ for (const fx of input.fx) {
87
+ check(record(fx) && Object.keys(fx).every(k => ['date', 'usdCny', 'sourceUrl'].includes(k)), 'FX fields');
88
+ const time = Date.parse(fx.date);
89
+ check(/^\d{4}-\d\d-\d\d$/.test(fx.date) && Number.isFinite(time) && new Date(time).toISOString().slice(0, 10) === fx.date && time > previous, 'FX date order');
90
+ check(Number.isFinite(fx.usdCny) && fx.usdCny > 0 && fx.usdCny <= 100 && typeof fx.sourceUrl === 'string' && (() => { try { const url = new URL(fx.sourceUrl); return url.protocol === 'https:' && !url.username && !url.password && !url.hash; } catch { return false; } })(), 'FX rate'); previous = time;
91
+ }
92
+ const result = freeze(JSON.parse(snapshotJson(input, MAX_CATALOG_BYTES, 'catalog'))); validated.add(result); return result;
93
+ }
94
+ function validateOverrides(input) { rules(input, true); return freeze(JSON.parse(snapshotJson(input, MAX_OVERRIDES_BYTES, 'overrides'))); }
95
+ module.exports = { MAX_CATALOG_BYTES, MAX_OVERRIDES_BYTES, MAX_ENVELOPE_BYTES, MAX_CACHE_BYTES, utf8ByteLength, validateCatalog, validateOverrides };