@rayadesu/dsh-llm-billing 0.1.0-rc.8

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,163 @@
1
+ /**
2
+ * DeepSeek billing: the peak/off-peak pricing table and the per-session spend
3
+ * pricing. Pure functions over session events and the pricing table, so the
4
+ * Remote gateway stays transport-free and the whole spend is testable without
5
+ * a key.
6
+ * @module @rayadesu/dsh-llm-billing/billing
7
+ */
8
+ /** Published peak-hour windows (Beijing time): 09:00–12:00 and 14:00–18:00. */
9
+ export const DEFAULT_PEAK_HOURS = [
10
+ { start: 9, end: 12 },
11
+ { start: 14, end: 18 },
12
+ ];
13
+ /** Official peak/off-peak rates (CNY per 1M tokens), effective 2026-08-17. */
14
+ export const DEFAULT_MODEL_PRICING = [
15
+ {
16
+ model: 'deepseek-v4-flash',
17
+ peak: { cacheHitInput: 0.10, cacheMissInput: 3.0, output: 9.0 },
18
+ offPeak: { cacheHitInput: 0.05, cacheMissInput: 1.5, output: 4.5 },
19
+ },
20
+ {
21
+ model: 'deepseek-v4-pro',
22
+ peak: { cacheHitInput: 0.30, cacheMissInput: 9.0, output: 27.0 },
23
+ offPeak: { cacheHitInput: 0.15, cacheMissInput: 4.5, output: 13.5 },
24
+ },
25
+ ];
26
+ /**
27
+ * Resolve optional configuration to a pricing table, defaulting omitted or
28
+ * empty rows to the published rates. Schemastery materializes an absent
29
+ * `z.array` as `[]` rather than `undefined`, so emptiness — not just absence —
30
+ * selects the defaults. Explicit non-empty rows override the same model; a
31
+ * supplied non-empty `models` list is authoritative.
32
+ * @param config - optional raw billing configuration.
33
+ * @returns the resolved table and peak-hour windows.
34
+ */
35
+ export function resolveBilling(config) {
36
+ const peakHours = config?.peakHours !== undefined && config.peakHours.length > 0
37
+ ? config.peakHours
38
+ : DEFAULT_PEAK_HOURS;
39
+ const rows = config?.models !== undefined && config.models.length > 0
40
+ ? config.models
41
+ : DEFAULT_MODEL_PRICING;
42
+ const models = new Map();
43
+ for (const row of rows)
44
+ models.set(row.model, { peak: row.peak, offPeak: row.offPeak });
45
+ return { peakHours, models };
46
+ }
47
+ /** The Beijing (Asia/Shanghai, UTC+8, no DST) hour of a timestamp. */
48
+ function beijingHour(now) {
49
+ return new Date(now.getTime() + 8 * 3_600_000).getUTCHours();
50
+ }
51
+ /** The Beijing (Asia/Shanghai, UTC+8, no DST) calendar-day key of a timestamp. */
52
+ function beijingDayKey(now) {
53
+ return new Date(now.getTime() + 8 * 3_600_000).toISOString().slice(0, 10);
54
+ }
55
+ /**
56
+ * Whether a timestamp falls inside any peak-hour window (Beijing time).
57
+ * @param billing - resolved pricing with peak-hour windows.
58
+ * @param now - the moment to classify.
59
+ * @returns true during peak hours.
60
+ */
61
+ export function isPeak(billing, now) {
62
+ const hour = beijingHour(now);
63
+ return billing.peakHours.some(({ start, end }) => hour >= start && hour < end);
64
+ }
65
+ /**
66
+ * Price a set of billed events at the official per-model rates, applying the
67
+ * peak/off-peak table per event by its Beijing-time hour. Each
68
+ * `assistant/message` event with usage contributes cache-hit input, cache-miss
69
+ * input (uncached input plus cache writes), and output (reasoning included)
70
+ * tokens at the rate of its own timestamp, with the three component costs
71
+ * carried separately; a model with usage but no pricing row is omitted (the
72
+ * published table prices only the two V4 rows).
73
+ * @param events - the events to price.
74
+ * @param billing - resolved pricing with peak-hour windows.
75
+ * @param catalog - model display rows, in presentation order.
76
+ * @returns the total cost plus one row per priced model.
77
+ */
78
+ function priceEvents(events, billing, catalog) {
79
+ const names = new Map(catalog.map(model => [model.id, model.name]));
80
+ const rows = new Map();
81
+ for (const event of events) {
82
+ if (event.type !== 'assistant/message')
83
+ continue;
84
+ const reported = event.data.usage;
85
+ if (reported === undefined)
86
+ continue;
87
+ const model = event.data.message.source.model;
88
+ const pricing = billing.models.get(model);
89
+ if (pricing === undefined)
90
+ continue;
91
+ const peak = isPeak(billing, new Date(event.time));
92
+ const price = peak ? pricing.peak : pricing.offPeak;
93
+ const hit = reported.cacheReadTokens ?? 0;
94
+ const miss = reported.inputTokens + (reported.cacheWriteTokens ?? 0);
95
+ const output = reported.outputTokens;
96
+ const hitCost = (hit * price.cacheHitInput) / 1_000_000;
97
+ const missCost = (miss * price.cacheMissInput) / 1_000_000;
98
+ const outputCost = (output * price.output) / 1_000_000;
99
+ const cost = hitCost + missCost + outputCost;
100
+ let row = rows.get(model);
101
+ if (row === undefined) {
102
+ row = {
103
+ cacheHitInputTokens: 0, cacheMissInputTokens: 0, outputTokens: 0,
104
+ cost: 0, peakCost: 0, offPeakCost: 0,
105
+ cacheHitInputCost: 0, cacheMissInputCost: 0, outputCost: 0,
106
+ };
107
+ rows.set(model, row);
108
+ }
109
+ row.cacheHitInputTokens += hit;
110
+ row.cacheMissInputTokens += miss;
111
+ row.outputTokens += output;
112
+ row.cost += cost;
113
+ row.cacheHitInputCost += hitCost;
114
+ row.cacheMissInputCost += missCost;
115
+ row.outputCost += outputCost;
116
+ if (peak)
117
+ row.peakCost += cost;
118
+ else
119
+ row.offPeakCost += cost;
120
+ }
121
+ const models = [...rows.entries()].map(([model, row]) => ({
122
+ model,
123
+ displayName: names.get(model) ?? model,
124
+ cost: row.cost,
125
+ peakCost: row.peakCost,
126
+ offPeakCost: row.offPeakCost,
127
+ cacheHitInputTokens: row.cacheHitInputTokens,
128
+ cacheMissInputTokens: row.cacheMissInputTokens,
129
+ outputTokens: row.outputTokens,
130
+ cacheHitInputCost: row.cacheHitInputCost,
131
+ cacheMissInputCost: row.cacheMissInputCost,
132
+ outputCost: row.outputCost,
133
+ }));
134
+ return {
135
+ total: models.reduce((sum, model) => sum + model.cost, 0),
136
+ models,
137
+ };
138
+ }
139
+ /**
140
+ * Price one session's complete event log at the official per-model rates.
141
+ * @param events - one session's complete event log.
142
+ * @param billing - resolved pricing with peak-hour windows.
143
+ * @param catalog - model display rows, in presentation order.
144
+ * @returns the session's total cost plus one row per priced model.
145
+ */
146
+ export function computeSessionSpend(events, billing, catalog) {
147
+ return priceEvents(events, billing, catalog);
148
+ }
149
+ /**
150
+ * Price every event whose Beijing-time calendar day is the day of `now`,
151
+ * aggregating across every session's event log. Events from other Beijing
152
+ * days are ignored, so a caller passes the concatenated logs of all sessions.
153
+ * @param events - every session's complete event log, concatenated.
154
+ * @param billing - resolved pricing with peak-hour windows.
155
+ * @param catalog - model display rows, in presentation order.
156
+ * @param now - the reference moment whose Beijing-time calendar day is "today".
157
+ * @returns today's total cost plus one row per priced model.
158
+ */
159
+ export function computeTodaySpend(events, billing, catalog, now = new Date()) {
160
+ const day = beijingDayKey(now);
161
+ return priceEvents(events.filter(event => beijingDayKey(new Date(event.time)) === day), billing, catalog);
162
+ }
163
+ //# sourceMappingURL=billing.js.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * DeepSeek account balance and session-spend provider, as a standalone host
3
+ * plugin. It resolves the DeepSeek endpoint and API key from its own config and
4
+ * the credential/environment seams, prices each session's billed usage with the
5
+ * peak/off-peak table, and exposes the `billing` Remote (`getBalance`, the
6
+ * per-session `getSessionSpend`, and the all-sessions `getTodaySpend`).
7
+ * @module @rayadesu/dsh-llm-billing
8
+ */
9
+ import type { Context } from '@deepseek-ai/cordis';
10
+ import z from '@deepseek-ai/schemastery';
11
+ import type { BillingConfig } from './billing.ts';
12
+ export { DeepSeekBalanceGateway, fetchDeepSeekBalance, parseDeepSeekBalance } from './balance.ts';
13
+ export { computeSessionSpend, computeTodaySpend, DEFAULT_MODEL_PRICING, DEFAULT_PEAK_HOURS, isPeak, resolveBilling, } from './billing.ts';
14
+ export type { BillingConfig, BillingConfigModel, DeepSeekModelPricing, DeepSeekTokenPrice, PeakHourWindow, ResolvedBilling, } from './billing.ts';
15
+ export type * from './types.ts';
16
+ export declare const name = "llm-billing";
17
+ /** Public API default; deployments may point elsewhere via $DEEPSEEK_BASE_URL. */
18
+ export declare const PUBLIC_BASE_URL = "https://api.deepseek.com";
19
+ /** One advisory display row; requests are never restricted to this list. */
20
+ export interface BillingModel {
21
+ /** Wire model id, e.g. `deepseek-v4-flash`. */
22
+ id: string;
23
+ /** Selector label; defaults to {@link id}. */
24
+ name?: string;
25
+ }
26
+ /**
27
+ * Plugin config. Every field is optional: the API key resolves per call from
28
+ * {@link Config.apiKeyEnv} (credentials seam, then environment), the endpoint
29
+ * falls back to `$DEEPSEEK_BASE_URL` then the public API, and the pricing
30
+ * table and peak-hour windows fall back to the published DeepSeek rates.
31
+ */
32
+ export interface Config {
33
+ /** Credential reference (environment-variable name); defaults to `DEEPSEEK_API_KEY`. */
34
+ apiKeyEnv?: string;
35
+ /** Endpoint base; defaults to `$DEEPSEEK_BASE_URL`, then `https://api.deepseek.com`. */
36
+ baseURL?: string;
37
+ /** Advisory display rows, in presentation order; defaults to V4 Flash and V4 Pro. */
38
+ models?: BillingModel[];
39
+ /** Pricing table and peak-hour windows; omission uses the published defaults. */
40
+ billing?: BillingConfig;
41
+ }
42
+ export declare const Config: z<Config>;
43
+ /**
44
+ * Register the `billing` Remote under the `billing` namespace.
45
+ * @param ctx - owning plugin context.
46
+ * @param config - validated plugin config.
47
+ */
48
+ export declare function apply(ctx: Context, config: Config): void;
49
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,155 @@
1
+ /**
2
+ * DeepSeek account balance and session-spend provider, as a standalone host
3
+ * plugin. It resolves the DeepSeek endpoint and API key from its own config and
4
+ * the credential/environment seams, prices each session's billed usage with the
5
+ * peak/off-peak table, and exposes the `billing` Remote (`getBalance`, the
6
+ * per-session `getSessionSpend`, and the all-sessions `getTodaySpend`).
7
+ * @module @rayadesu/dsh-llm-billing
8
+ */
9
+ import z from '@deepseek-ai/schemastery';
10
+ import { assertUsableApiKey, LlmError } from '@deepseek-ai/dsh-llm';
11
+ import { credentialRef } from '@deepseek-ai/dsh-credentials';
12
+ import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment';
13
+ import { DeepSeekBalanceGateway, fetchDeepSeekBalance } from "./balance.js";
14
+ import { computeSessionSpend, computeTodaySpend, DEFAULT_MODEL_PRICING, DEFAULT_PEAK_HOURS, resolveBilling, } from "./billing.js";
15
+ export { DeepSeekBalanceGateway, fetchDeepSeekBalance, parseDeepSeekBalance } from "./balance.js";
16
+ export { computeSessionSpend, computeTodaySpend, DEFAULT_MODEL_PRICING, DEFAULT_PEAK_HOURS, isPeak, resolveBilling, } from "./billing.js";
17
+ export const name = 'llm-billing';
18
+ const DEFAULT_API_KEY_ENV = 'DEEPSEEK_API_KEY';
19
+ const BASE_URL_ENV = 'DEEPSEEK_BASE_URL';
20
+ /** Public API default; deployments may point elsewhere via $DEEPSEEK_BASE_URL. */
21
+ export const PUBLIC_BASE_URL = 'https://api.deepseek.com';
22
+ const DEFAULT_MODELS = [
23
+ { id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash' },
24
+ { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro' },
25
+ ];
26
+ const billingModel = z.object({
27
+ id: z.string().required(),
28
+ name: z.string(),
29
+ });
30
+ const tokenPrice = z.object({
31
+ cacheHitInput: z.number().min(0),
32
+ cacheMissInput: z.number().min(0),
33
+ output: z.number().min(0),
34
+ });
35
+ const billingConfig = z.object({
36
+ peakHours: z.array(z.object({
37
+ start: z.number().step(1).min(0).max(23),
38
+ end: z.number().step(1).min(0).max(24),
39
+ })).default(DEFAULT_PEAK_HOURS),
40
+ models: z.array(z.object({
41
+ model: z.string().required(),
42
+ peak: tokenPrice,
43
+ offPeak: tokenPrice,
44
+ })).default(DEFAULT_MODEL_PRICING),
45
+ });
46
+ export const Config = z.object({
47
+ apiKeyEnv: z.string().role('credential-ref').default(DEFAULT_API_KEY_ENV),
48
+ baseURL: z.string(),
49
+ models: z.array(billingModel).default(DEFAULT_MODELS),
50
+ billing: billingConfig,
51
+ });
52
+ /**
53
+ * Read one session's event log: the live SessionStore first, then the
54
+ * persistence backend for a flushed session.
55
+ * @param ctx - plugin context carrying the SessionStore and optional persistence.
56
+ * @param sessionId - the session to read.
57
+ * @returns the session's complete event log.
58
+ * @throws {@link LlmError} with code `NOT_FOUND` when the session is unknown.
59
+ */
60
+ async function sessionEvents(ctx, sessionId) {
61
+ const sessions = ctx.get('sessions');
62
+ const live = sessions?.get(sessionId);
63
+ if (live !== undefined)
64
+ return live.events;
65
+ const persistence = ctx.get('sessionPersistence');
66
+ if (persistence !== undefined) {
67
+ for (const header of await persistence.list()) {
68
+ if (header.id !== sessionId)
69
+ continue;
70
+ const inspection = await persistence.inspect(sessionId);
71
+ return inspection.events;
72
+ }
73
+ }
74
+ throw new LlmError(`llm-billing: session ${sessionId} not found`, 'NOT_FOUND');
75
+ }
76
+ /**
77
+ * Read every session's event log, concatenated: each live SessionStore
78
+ * session first (its log may hold events not yet flushed), then each persisted
79
+ * session that is not live, so no event is counted twice. Events are appended
80
+ * one at a time: spreading a very large log into `push(...)` exceeds the
81
+ * engine's argument limit and throws a stack RangeError.
82
+ * @param ctx - plugin context carrying the SessionStore and optional persistence.
83
+ * @returns every session's complete event log, concatenated.
84
+ */
85
+ async function allSessionEvents(ctx) {
86
+ const events = [];
87
+ const sessions = ctx.get('sessions');
88
+ const liveIds = new Set();
89
+ if (sessions !== undefined) {
90
+ for (const session of sessions.list()) {
91
+ liveIds.add(session.id);
92
+ for (const event of session.events)
93
+ events.push(event);
94
+ }
95
+ }
96
+ const persistence = ctx.get('sessionPersistence');
97
+ if (persistence !== undefined) {
98
+ for (const header of await persistence.list()) {
99
+ if (liveIds.has(header.id))
100
+ continue;
101
+ try {
102
+ const inspection = await persistence.inspect(header.id);
103
+ for (const event of inspection.events)
104
+ events.push(event);
105
+ }
106
+ catch (error) {
107
+ // One unreadable session must not blank the whole-day aggregate.
108
+ ctx.logger.warn(`llm-billing: skipping unreadable session ${header.id}: ${String(error)}`);
109
+ }
110
+ }
111
+ }
112
+ return events;
113
+ }
114
+ /**
115
+ * Register the `billing` Remote under the `billing` namespace.
116
+ * @param ctx - owning plugin context.
117
+ * @param config - validated plugin config.
118
+ */
119
+ export function apply(ctx, config) {
120
+ const baseURL = () => config.baseURL
121
+ ?? launchEnvironmentOf(ctx).get(BASE_URL_ENV)?.value
122
+ ?? PUBLIC_BASE_URL;
123
+ const apiKeyRef = credentialRef(config.apiKeyEnv ?? DEFAULT_API_KEY_ENV);
124
+ const resolveApiKey = async () => {
125
+ const credentials = ctx.get('credentials');
126
+ if (credentials !== undefined) {
127
+ const hit = await credentials.resolve(apiKeyRef);
128
+ if (hit !== undefined)
129
+ return assertUsableApiKey(hit.value, 'llm-billing', apiKeyRef);
130
+ }
131
+ else {
132
+ const ambient = launchEnvironmentOf(ctx).get(apiKeyRef);
133
+ if (ambient !== undefined && ambient.value.length > 0) {
134
+ return assertUsableApiKey(ambient.value, 'llm-billing', apiKeyRef);
135
+ }
136
+ }
137
+ throw new LlmError(`llm-billing: no API key; store ${apiKeyRef} through the credentials service or export it`, 'MISSING_CREDENTIAL');
138
+ };
139
+ const fetchBalance = async () => {
140
+ const apiKey = await resolveApiKey();
141
+ return fetchDeepSeekBalance(baseURL(), apiKey);
142
+ };
143
+ const fetchSessionSpend = async (sessionId) => {
144
+ const billing = resolveBilling(config.billing);
145
+ const catalog = (config.models ?? DEFAULT_MODELS).map(model => ({ id: model.id, name: model.name ?? model.id }));
146
+ return computeSessionSpend(await sessionEvents(ctx, sessionId), billing, catalog);
147
+ };
148
+ const fetchTodaySpend = async () => {
149
+ const billing = resolveBilling(config.billing);
150
+ const catalog = (config.models ?? DEFAULT_MODELS).map(model => ({ id: model.id, name: model.name ?? model.id }));
151
+ return computeTodaySpend(await allSessionEvents(ctx), billing, catalog);
152
+ };
153
+ new DeepSeekBalanceGateway(ctx, { fetchBalance, fetchSessionSpend, fetchTodaySpend });
154
+ }
155
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@rayadesu/dsh-llm-billing`.
3
+ * @module @rayadesu/dsh-llm-billing/invariant
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis';
6
+ /** Cordis companion plugin name. */
7
+ export declare const name = "llm-billing-invariant";
8
+ /** Service required before the companion can reserve package ownership. */
9
+ export declare const inject: string[];
10
+ /**
11
+ * Register this package's invariant companion.
12
+ * @param ctx - Cordis context carrying the invariant service.
13
+ * @returns the installed registration's disposer after setup succeeds.
14
+ */
15
+ export declare const apply: (ctx: Context) => Promise<() => void>;
16
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Package-owned invariant companion for `@rayadesu/dsh-llm-billing`.
3
+ * @module @rayadesu/dsh-llm-billing/invariant
4
+ */
5
+ const PACKAGE_NAME = '@rayadesu/dsh-llm-billing';
6
+ /** Cordis companion plugin name. */
7
+ export const name = 'llm-billing-invariant';
8
+ /** Service required before the companion can reserve package ownership. */
9
+ export const inject = ['invariants'];
10
+ /**
11
+ * No runtime invariant: this package is a read-only Remote projection over the
12
+ * provider balance and session logs, and owns no cross-plugin mutable state.
13
+ */
14
+ const install = () => { };
15
+ /**
16
+ * Register this package's invariant companion.
17
+ * @param ctx - Cordis context carrying the invariant service.
18
+ * @returns the installed registration's disposer after setup succeeds.
19
+ */
20
+ export const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
21
+ /* jscpd:ignore-end */
22
+ //# sourceMappingURL=invariant.js.map
@@ -0,0 +1,71 @@
1
+ /**
2
+ * DeepSeek account-balance capability: the `GET /user/balance` transport and
3
+ * the Remote gateway that exposes one snapshot to trusted clients. The fetch
4
+ * takes an already-resolved endpoint and bearer token so the registering
5
+ * plugin stays the one owner of credential policy; the gateway carries only a
6
+ * `fetchBalance` thunk for the same reason.
7
+ * @module @rayadesu/dsh-llm-billing/balance
8
+ */
9
+ import type { Context } from '@deepseek-ai/cordis';
10
+ import type { SessionId } from '@deepseek-ai/dsh-session';
11
+ import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
12
+ import type { DeepSeekBalance, DeepSeekSessionSpend, DeepSeekTodaySpend } from './types.ts';
13
+ /**
14
+ * Parse and validate the DeepSeek balance response at the wire boundary.
15
+ * @param body - decoded JSON response body.
16
+ * @returns the validated, detached balance snapshot.
17
+ * @throws {@link LlmError} with code `TRANSPORT` when the body is malformed.
18
+ */
19
+ export declare function parseDeepSeekBalance(body: unknown): DeepSeekBalance;
20
+ /**
21
+ * Fetch one account-balance snapshot from `{baseURL}/user/balance`.
22
+ * @param baseURL - resolved endpoint base; `/user/balance` is appended.
23
+ * @param apiKey - resolved bearer token for this endpoint.
24
+ * @param signal - optional cancellation.
25
+ * @returns the validated balance snapshot.
26
+ * @throws {@link LlmError} for transport, HTTP, or malformed-response failures.
27
+ */
28
+ export declare function fetchDeepSeekBalance(baseURL: string, apiKey: string, signal?: AbortSignal): Promise<DeepSeekBalance>;
29
+ /** Thunks the plugin binds to its own resolution and history access. */
30
+ export interface DeepSeekBalanceGatewayOptions {
31
+ /** Fetch one balance snapshot through the plugin's resolved facts. */
32
+ fetchBalance: () => Promise<DeepSeekBalance>;
33
+ /** Compute one session's billed spend through the plugin's resolved facts. */
34
+ fetchSessionSpend: (sessionId: SessionId) => Promise<DeepSeekSessionSpend>;
35
+ /** Compute today's billed spend across every session through the plugin's resolved facts. */
36
+ fetchTodaySpend: () => Promise<DeepSeekTodaySpend>;
37
+ }
38
+ /**
39
+ * Remote-only service exposing the DeepSeek account balance and session spend.
40
+ * The plugin that owns connection, credential, and session-history resolution
41
+ * constructs it with the matching thunks, so the Remote boundary never sees an
42
+ * endpoint, key, or the session store.
43
+ */
44
+ export declare class DeepSeekBalanceGateway extends TypertRemoteService {
45
+ private readonly options;
46
+ /**
47
+ * Register the balance Remote under the `billing` namespace.
48
+ * @param ctx - owning plugin context.
49
+ * @param options - balance and spend thunks bound to the plugin's facts.
50
+ */
51
+ constructor(ctx: Context, options: DeepSeekBalanceGatewayOptions);
52
+ /**
53
+ * Read the current DeepSeek account balance.
54
+ * @returns the validated balance snapshot.
55
+ */
56
+ getBalance(): Promise<DeepSeekBalance>;
57
+ /**
58
+ * Read one session's billed spend, priced per event by its peak/off-peak hour.
59
+ * @param sessionId - the session whose spend to compute.
60
+ * @returns the session's total cost plus one row per priced model.
61
+ */
62
+ getSessionSpend(sessionId: SessionId): Promise<DeepSeekSessionSpend>;
63
+ /**
64
+ * Read today's billed spend across every session, priced per event by its
65
+ * Beijing-time calendar day and peak/off-peak hour.
66
+ * @returns today's total cost plus one row per priced model.
67
+ */
68
+ getTodaySpend(): Promise<DeepSeekTodaySpend>;
69
+ }
70
+ export default DeepSeekBalanceGateway;
71
+ //# sourceMappingURL=balance.d.ts.map
@@ -0,0 +1,187 @@
1
+ /**
2
+ * DeepSeek account-balance capability: the `GET /user/balance` transport and
3
+ * the Remote gateway that exposes one snapshot to trusted clients. The fetch
4
+ * takes an already-resolved endpoint and bearer token so the registering
5
+ * plugin stays the one owner of credential policy; the gateway carries only a
6
+ * `fetchBalance` thunk for the same reason.
7
+ * @module @rayadesu/dsh-llm-billing/balance
8
+ */
9
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
10
+ var useValue = arguments.length > 2;
11
+ for (var i = 0; i < initializers.length; i++) {
12
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
13
+ }
14
+ return useValue ? value : void 0;
15
+ };
16
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
17
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
18
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
19
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
20
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
21
+ var _, done = false;
22
+ for (var i = decorators.length - 1; i >= 0; i--) {
23
+ var context = {};
24
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
25
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
26
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
27
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
28
+ if (kind === "accessor") {
29
+ if (result === void 0) continue;
30
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
31
+ if (_ = accept(result.get)) descriptor.get = _;
32
+ if (_ = accept(result.set)) descriptor.set = _;
33
+ if (_ = accept(result.init)) initializers.unshift(_);
34
+ }
35
+ else if (_ = accept(result)) {
36
+ if (kind === "field") initializers.unshift(_);
37
+ else descriptor[key] = _;
38
+ }
39
+ }
40
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
41
+ done = true;
42
+ };
43
+ import { LlmError } from '@deepseek-ai/dsh-llm';
44
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
45
+ /** Map a balance HTTP status to a stable LlmError code. */
46
+ function httpErrorCode(status) {
47
+ if (status === 401 || status === 403)
48
+ return 'AUTH';
49
+ if (status === 429)
50
+ return 'RATE_LIMIT';
51
+ if (status >= 500)
52
+ return 'SERVER';
53
+ return `HTTP_${status}`;
54
+ }
55
+ /**
56
+ * Parse and validate the DeepSeek balance response at the wire boundary.
57
+ * @param body - decoded JSON response body.
58
+ * @returns the validated, detached balance snapshot.
59
+ * @throws {@link LlmError} with code `TRANSPORT` when the body is malformed.
60
+ */
61
+ export function parseDeepSeekBalance(body) {
62
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
63
+ throw new LlmError('DeepSeek balance response was not a JSON object', 'TRANSPORT');
64
+ }
65
+ const response = body;
66
+ const isAvailable = response['is_available'];
67
+ const infos = response['balance_infos'];
68
+ if (typeof isAvailable !== 'boolean' || !Array.isArray(infos)) {
69
+ throw new LlmError('DeepSeek balance response is missing is_available or balance_infos', 'TRANSPORT');
70
+ }
71
+ const lines = infos.map((info, index) => {
72
+ if (typeof info !== 'object' || info === null || Array.isArray(info)) {
73
+ throw new LlmError(`DeepSeek balance line ${index} is malformed`, 'TRANSPORT');
74
+ }
75
+ const line = info;
76
+ const currency = line['currency'];
77
+ const total = line['total_balance'];
78
+ const granted = line['granted_balance'];
79
+ const toppedUp = line['topped_up_balance'];
80
+ if (typeof currency !== 'string' || currency.length === 0
81
+ || typeof total !== 'string'
82
+ || typeof granted !== 'string'
83
+ || typeof toppedUp !== 'string') {
84
+ throw new LlmError(`DeepSeek balance line ${index} has missing or invalid fields`, 'TRANSPORT');
85
+ }
86
+ return { currency, total, granted, toppedUp };
87
+ });
88
+ return { isAvailable, lines };
89
+ }
90
+ /**
91
+ * Fetch one account-balance snapshot from `{baseURL}/user/balance`.
92
+ * @param baseURL - resolved endpoint base; `/user/balance` is appended.
93
+ * @param apiKey - resolved bearer token for this endpoint.
94
+ * @param signal - optional cancellation.
95
+ * @returns the validated balance snapshot.
96
+ * @throws {@link LlmError} for transport, HTTP, or malformed-response failures.
97
+ */
98
+ export async function fetchDeepSeekBalance(baseURL, apiKey, signal) {
99
+ let response;
100
+ try {
101
+ response = await fetch(`${baseURL}/user/balance`, {
102
+ method: 'GET',
103
+ headers: {
104
+ 'authorization': `Bearer ${apiKey}`,
105
+ 'accept': 'application/json',
106
+ },
107
+ ...(signal === undefined ? {} : { signal }),
108
+ });
109
+ }
110
+ catch (error) {
111
+ if (signal?.aborted)
112
+ throw new LlmError('DeepSeek balance request aborted by caller', 'ABORTED', { cause: error });
113
+ throw new LlmError(`DeepSeek balance request to ${baseURL} failed`, 'TRANSPORT', { cause: error });
114
+ }
115
+ if (!response.ok) {
116
+ throw new LlmError(`DeepSeek balance request failed (HTTP ${response.status})`, httpErrorCode(response.status), { status: response.status });
117
+ }
118
+ let body;
119
+ try {
120
+ body = await response.json();
121
+ }
122
+ catch (error) {
123
+ throw new LlmError('DeepSeek balance response was not valid JSON', 'TRANSPORT', { cause: error });
124
+ }
125
+ return parseDeepSeekBalance(body);
126
+ }
127
+ /**
128
+ * Remote-only service exposing the DeepSeek account balance and session spend.
129
+ * The plugin that owns connection, credential, and session-history resolution
130
+ * constructs it with the matching thunks, so the Remote boundary never sees an
131
+ * endpoint, key, or the session store.
132
+ */
133
+ let DeepSeekBalanceGateway = (() => {
134
+ let _classSuper = TypertRemoteService;
135
+ let _instanceExtraInitializers = [];
136
+ let _getBalance_decorators;
137
+ let _getSessionSpend_decorators;
138
+ let _getTodaySpend_decorators;
139
+ return class DeepSeekBalanceGateway extends _classSuper {
140
+ static {
141
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
142
+ _getBalance_decorators = [Remote('getBalance')];
143
+ _getSessionSpend_decorators = [Remote('getSessionSpend')];
144
+ _getTodaySpend_decorators = [Remote('getTodaySpend')];
145
+ __esDecorate(this, null, _getBalance_decorators, { kind: "method", name: "getBalance", static: false, private: false, access: { has: obj => "getBalance" in obj, get: obj => obj.getBalance }, metadata: _metadata }, null, _instanceExtraInitializers);
146
+ __esDecorate(this, null, _getSessionSpend_decorators, { kind: "method", name: "getSessionSpend", static: false, private: false, access: { has: obj => "getSessionSpend" in obj, get: obj => obj.getSessionSpend }, metadata: _metadata }, null, _instanceExtraInitializers);
147
+ __esDecorate(this, null, _getTodaySpend_decorators, { kind: "method", name: "getTodaySpend", static: false, private: false, access: { has: obj => "getTodaySpend" in obj, get: obj => obj.getTodaySpend }, metadata: _metadata }, null, _instanceExtraInitializers);
148
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
149
+ }
150
+ options = __runInitializers(this, _instanceExtraInitializers);
151
+ /**
152
+ * Register the balance Remote under the `billing` namespace.
153
+ * @param ctx - owning plugin context.
154
+ * @param options - balance and spend thunks bound to the plugin's facts.
155
+ */
156
+ constructor(ctx, options) {
157
+ super(ctx, 'billing');
158
+ this.options = options;
159
+ }
160
+ /**
161
+ * Read the current DeepSeek account balance.
162
+ * @returns the validated balance snapshot.
163
+ */
164
+ getBalance() {
165
+ return this.options.fetchBalance();
166
+ }
167
+ /**
168
+ * Read one session's billed spend, priced per event by its peak/off-peak hour.
169
+ * @param sessionId - the session whose spend to compute.
170
+ * @returns the session's total cost plus one row per priced model.
171
+ */
172
+ getSessionSpend(sessionId) {
173
+ return this.options.fetchSessionSpend(sessionId);
174
+ }
175
+ /**
176
+ * Read today's billed spend across every session, priced per event by its
177
+ * Beijing-time calendar day and peak/off-peak hour.
178
+ * @returns today's total cost plus one row per priced model.
179
+ */
180
+ getTodaySpend() {
181
+ return this.options.fetchTodaySpend();
182
+ }
183
+ };
184
+ })();
185
+ export { DeepSeekBalanceGateway };
186
+ export default DeepSeekBalanceGateway;
187
+ //# sourceMappingURL=balance.js.map