@laoyuehanni/dsh-token-usage 0.3.7
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/LICENSE +21 -0
- package/README.md +178 -0
- package/README.zh.md +182 -0
- package/cordis.patch.yml +7 -0
- package/lib/client/CostDeltaFlyLabel.d.ts +8 -0
- package/lib/client/CostDeltaFlyLabel.d.ts.map +1 -0
- package/lib/client/CostDeltaFlyLabel.js +24 -0
- package/lib/client/CostDeltaFlyLabel.js.map +1 -0
- package/lib/client/HitRateText.d.ts +21 -0
- package/lib/client/HitRateText.d.ts.map +1 -0
- package/lib/client/HitRateText.js +16 -0
- package/lib/client/HitRateText.js.map +1 -0
- package/lib/client/QuotaButton.d.ts +70 -0
- package/lib/client/QuotaButton.d.ts.map +1 -0
- package/lib/client/QuotaButton.js +346 -0
- package/lib/client/QuotaButton.js.map +1 -0
- package/lib/client/SessionStatsChip.d.ts +47 -0
- package/lib/client/SessionStatsChip.d.ts.map +1 -0
- package/lib/client/SessionStatsChip.js +141 -0
- package/lib/client/SessionStatsChip.js.map +1 -0
- package/lib/client/StatCard.d.ts +26 -0
- package/lib/client/StatCard.d.ts.map +1 -0
- package/lib/client/StatCard.js +10 -0
- package/lib/client/StatCard.js.map +1 -0
- package/lib/client/TokenUsageCard.d.ts +41 -0
- package/lib/client/TokenUsageCard.d.ts.map +1 -0
- package/lib/client/TokenUsageCard.js +164 -0
- package/lib/client/TokenUsageCard.js.map +1 -0
- package/lib/client/TokenUsageSection.d.ts +32 -0
- package/lib/client/TokenUsageSection.d.ts.map +1 -0
- package/lib/client/TokenUsageSection.js +266 -0
- package/lib/client/TokenUsageSection.js.map +1 -0
- package/lib/client/TrendChart.d.ts +53 -0
- package/lib/client/TrendChart.d.ts.map +1 -0
- package/lib/client/TrendChart.js +141 -0
- package/lib/client/TrendChart.js.map +1 -0
- package/lib/client/UsageView.d.ts +42 -0
- package/lib/client/UsageView.d.ts.map +1 -0
- package/lib/client/UsageView.js +158 -0
- package/lib/client/UsageView.js.map +1 -0
- package/lib/client/async-resource.d.ts +54 -0
- package/lib/client/async-resource.d.ts.map +1 -0
- package/lib/client/async-resource.js +90 -0
- package/lib/client/async-resource.js.map +1 -0
- package/lib/client/card-form.d.ts +171 -0
- package/lib/client/card-form.d.ts.map +1 -0
- package/lib/client/card-form.js +300 -0
- package/lib/client/card-form.js.map +1 -0
- package/lib/client/cost-inflate-motion.d.ts +17 -0
- package/lib/client/cost-inflate-motion.d.ts.map +1 -0
- package/lib/client/cost-inflate-motion.js +61 -0
- package/lib/client/cost-inflate-motion.js.map +1 -0
- package/lib/client/cost-inflate.d.ts +28 -0
- package/lib/client/cost-inflate.d.ts.map +1 -0
- package/lib/client/cost-inflate.js +49 -0
- package/lib/client/cost-inflate.js.map +1 -0
- package/lib/client/day.d.ts +49 -0
- package/lib/client/day.d.ts.map +1 -0
- package/lib/client/day.js +84 -0
- package/lib/client/day.js.map +1 -0
- package/lib/client/format.d.ts +120 -0
- package/lib/client/format.d.ts.map +1 -0
- package/lib/client/format.js +163 -0
- package/lib/client/format.js.map +1 -0
- package/lib/client/index.d.ts +26 -0
- package/lib/client/index.d.ts.map +1 -0
- package/lib/client/index.js +131 -0
- package/lib/client/index.js.map +1 -0
- package/lib/client/locales.d.ts +131 -0
- package/lib/client/locales.d.ts.map +1 -0
- package/lib/client/locales.js +230 -0
- package/lib/client/locales.js.map +1 -0
- package/lib/client/quota-format.d.ts +69 -0
- package/lib/client/quota-format.d.ts.map +1 -0
- package/lib/client/quota-format.js +147 -0
- package/lib/client/quota-format.js.map +1 -0
- package/lib/client/session-stats.d.ts +105 -0
- package/lib/client/session-stats.d.ts.map +1 -0
- package/lib/client/session-stats.js +142 -0
- package/lib/client/session-stats.js.map +1 -0
- package/lib/client/trend-chart/axis.d.ts +21 -0
- package/lib/client/trend-chart/axis.d.ts.map +1 -0
- package/lib/client/trend-chart/axis.js +33 -0
- package/lib/client/trend-chart/axis.js.map +1 -0
- package/lib/client/trend-chart/bucket.d.ts +24 -0
- package/lib/client/trend-chart/bucket.d.ts.map +1 -0
- package/lib/client/trend-chart/bucket.js +28 -0
- package/lib/client/trend-chart/bucket.js.map +1 -0
- package/lib/client/trend-chart/index.d.ts +12 -0
- package/lib/client/trend-chart/index.d.ts.map +1 -0
- package/lib/client/trend-chart/index.js +9 -0
- package/lib/client/trend-chart/index.js.map +1 -0
- package/lib/client/trend-chart/points.d.ts +46 -0
- package/lib/client/trend-chart/points.d.ts.map +1 -0
- package/lib/client/trend-chart/points.js +82 -0
- package/lib/client/trend-chart/points.js.map +1 -0
- package/lib/client/trend-chart/scale.d.ts +47 -0
- package/lib/client/trend-chart/scale.d.ts.map +1 -0
- package/lib/client/trend-chart/scale.js +75 -0
- package/lib/client/trend-chart/scale.js.map +1 -0
- package/lib/client/use-color-scheme.d.ts +18 -0
- package/lib/client/use-color-scheme.d.ts.map +1 -0
- package/lib/client/use-color-scheme.js +37 -0
- package/lib/client/use-color-scheme.js.map +1 -0
- package/lib/client/use-cost-inflate.d.ts +33 -0
- package/lib/client/use-cost-inflate.d.ts.map +1 -0
- package/lib/client/use-cost-inflate.js +108 -0
- package/lib/client/use-cost-inflate.js.map +1 -0
- package/lib/client.js +3892 -0
- package/lib/client.js.map +1 -0
- package/lib/index.d.ts +132 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +599 -0
- package/lib/index.js.map +1 -0
- package/lib/migrate.d.ts +60 -0
- package/lib/migrate.d.ts.map +1 -0
- package/lib/migrate.js +126 -0
- package/lib/migrate.js.map +1 -0
- package/lib/pricing.d.ts +212 -0
- package/lib/pricing.d.ts.map +1 -0
- package/lib/pricing.js +492 -0
- package/lib/pricing.js.map +1 -0
- package/lib/quota/adapters/deepseek-balance.d.ts +18 -0
- package/lib/quota/adapters/deepseek-balance.d.ts.map +1 -0
- package/lib/quota/adapters/deepseek-balance.js +76 -0
- package/lib/quota/adapters/deepseek-balance.js.map +1 -0
- package/lib/quota/adapters/kimi.d.ts +26 -0
- package/lib/quota/adapters/kimi.d.ts.map +1 -0
- package/lib/quota/adapters/kimi.js +91 -0
- package/lib/quota/adapters/kimi.js.map +1 -0
- package/lib/quota/adapters/minimax.d.ts +24 -0
- package/lib/quota/adapters/minimax.d.ts.map +1 -0
- package/lib/quota/adapters/minimax.js +136 -0
- package/lib/quota/adapters/minimax.js.map +1 -0
- package/lib/quota/adapters/opencode-go.d.ts +25 -0
- package/lib/quota/adapters/opencode-go.d.ts.map +1 -0
- package/lib/quota/adapters/opencode-go.js +105 -0
- package/lib/quota/adapters/opencode-go.js.map +1 -0
- package/lib/quota/adapters/openrouter.d.ts +15 -0
- package/lib/quota/adapters/openrouter.d.ts.map +1 -0
- package/lib/quota/adapters/openrouter.js +54 -0
- package/lib/quota/adapters/openrouter.js.map +1 -0
- package/lib/quota/adapters/zhipu.d.ts +38 -0
- package/lib/quota/adapters/zhipu.d.ts.map +1 -0
- package/lib/quota/adapters/zhipu.js +246 -0
- package/lib/quota/adapters/zhipu.js.map +1 -0
- package/lib/quota/credentials.d.ts +79 -0
- package/lib/quota/credentials.d.ts.map +1 -0
- package/lib/quota/credentials.js +130 -0
- package/lib/quota/credentials.js.map +1 -0
- package/lib/quota/http.d.ts +49 -0
- package/lib/quota/http.d.ts.map +1 -0
- package/lib/quota/http.js +114 -0
- package/lib/quota/http.js.map +1 -0
- package/lib/quota/provider-tracking.d.ts +45 -0
- package/lib/quota/provider-tracking.d.ts.map +1 -0
- package/lib/quota/provider-tracking.js +52 -0
- package/lib/quota/provider-tracking.js.map +1 -0
- package/lib/quota/quota-route.d.ts +22 -0
- package/lib/quota/quota-route.d.ts.map +1 -0
- package/lib/quota/quota-route.js +57 -0
- package/lib/quota/quota-route.js.map +1 -0
- package/lib/quota/quota-service.d.ts +54 -0
- package/lib/quota/quota-service.d.ts.map +1 -0
- package/lib/quota/quota-service.js +171 -0
- package/lib/quota/quota-service.js.map +1 -0
- package/lib/quota/registry.d.ts +24 -0
- package/lib/quota/registry.d.ts.map +1 -0
- package/lib/quota/registry.js +38 -0
- package/lib/quota/registry.js.map +1 -0
- package/lib/quota/types.d.ts +79 -0
- package/lib/quota/types.d.ts.map +1 -0
- package/lib/quota/types.js +24 -0
- package/lib/quota/types.js.map +1 -0
- package/lib/record-cache.d.ts +38 -0
- package/lib/record-cache.d.ts.map +1 -0
- package/lib/record-cache.js +143 -0
- package/lib/record-cache.js.map +1 -0
- package/lib/rollup.d.ts +52 -0
- package/lib/rollup.d.ts.map +1 -0
- package/lib/rollup.js +117 -0
- package/lib/rollup.js.map +1 -0
- package/lib/stats-route.d.ts +88 -0
- package/lib/stats-route.d.ts.map +1 -0
- package/lib/stats-route.js +313 -0
- package/lib/stats-route.js.map +1 -0
- package/lib/stats.d.ts +158 -0
- package/lib/stats.d.ts.map +1 -0
- package/lib/stats.js +426 -0
- package/lib/stats.js.map +1 -0
- package/lib/sync-state.d.ts +27 -0
- package/lib/sync-state.d.ts.map +1 -0
- package/lib/sync-state.js +56 -0
- package/lib/sync-state.js.map +1 -0
- package/lib/sync.d.ts +74 -0
- package/lib/sync.d.ts.map +1 -0
- package/lib/sync.js +64 -0
- package/lib/sync.js.map +1 -0
- package/lib/trend-bucket.d.ts +48 -0
- package/lib/trend-bucket.d.ts.map +1 -0
- package/lib/trend-bucket.js +87 -0
- package/lib/trend-bucket.js.map +1 -0
- package/lib/usage-log.d.ts +64 -0
- package/lib/usage-log.d.ts.map +1 -0
- package/lib/usage-log.js +144 -0
- package/lib/usage-log.js.map +1 -0
- package/lib/usage-record.d.ts +59 -0
- package/lib/usage-record.d.ts.map +1 -0
- package/lib/usage-record.js +115 -0
- package/lib/usage-record.js.map +1 -0
- package/lib/wire.d.ts +452 -0
- package/lib/wire.d.ts.map +1 -0
- package/lib/wire.js +144 -0
- package/lib/wire.js.map +1 -0
- package/package.json +100 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token-usage local plugin: a live hook persisting one JSONL row per
|
|
3
|
+
* successful model request. On the FIRST startup the plugin auto-syncs the
|
|
4
|
+
* historical session logs once (requests recorded before the plugin was
|
|
5
|
+
* installed). When a webServer exists, the plugin also serves the stats
|
|
6
|
+
* route backing the web settings page (browser half in `src/client`).
|
|
7
|
+
*
|
|
8
|
+
* The settings namespace `token-usage` registers through
|
|
9
|
+
* `installSettingsSection` with the composition entry as its base layer, and
|
|
10
|
+
* both of its fields take effect live. A stored region pick (or a mirror
|
|
11
|
+
* override) re-resolves the feed URL and re-syncs the mirror; a stored data
|
|
12
|
+
* directory switches writes to the new location and migrates every row and
|
|
13
|
+
* companion file across (verbatim file copy, then source cleanup), so no
|
|
14
|
+
* restart and no manual data move is needed.
|
|
15
|
+
*
|
|
16
|
+
* @module token-usage
|
|
17
|
+
*/
|
|
18
|
+
import { homedir } from 'node:os';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { credentialRef } from '@deepseek-ai/dsh-credentials';
|
|
21
|
+
import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings';
|
|
22
|
+
import z from '@deepseek-ai/schemastery';
|
|
23
|
+
import { UsageLog } from "./usage-log.js";
|
|
24
|
+
import { cleanSource, copyData } from "./migrate.js";
|
|
25
|
+
import { resolvePricingUrl, syncCloudPricing } from "./pricing.js";
|
|
26
|
+
import { recordFromEvent } from "./usage-record.js";
|
|
27
|
+
import { autoSyncIfNeeded, syncHistory } from "./sync.js";
|
|
28
|
+
import { clearRecordCache, warmRecordCache } from "./record-cache.js";
|
|
29
|
+
import { createDirectoryGuardRoute, createFullSyncRoute, createMigrationRoute, createStatsRoute } from "./stats-route.js";
|
|
30
|
+
import { currencyOfRegion } from "./wire.js";
|
|
31
|
+
import { createQuotaRoute } from "./quota/quota-route.js";
|
|
32
|
+
import { QuotaService } from "./quota/quota-service.js";
|
|
33
|
+
import { ProviderTracker, resolveCurrentProvider } from "./quota/provider-tracking.js";
|
|
34
|
+
import { resolveQuotaCredentials, withCatalogBaseUrl, } from "./quota/credentials.js";
|
|
35
|
+
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
36
|
+
export function validateConfig(config) {
|
|
37
|
+
const unknown = Object.keys(config).find(key => key !== 'path' && key !== 'pricingUrl' && key !== 'pricingUrlDomestic'
|
|
38
|
+
&& key !== 'pricingUrlOverseas' && key !== 'pricingRegion' && key !== 'startupDeferMs'
|
|
39
|
+
&& key !== 'quota');
|
|
40
|
+
if (unknown !== undefined) {
|
|
41
|
+
throw new Error(`TokenUsageConfig: unknown key "${unknown}"`);
|
|
42
|
+
}
|
|
43
|
+
if (config.path !== undefined && (typeof config.path !== 'string' || config.path.length === 0)) {
|
|
44
|
+
throw new Error('TokenUsageConfig: "path" must be a non-empty string');
|
|
45
|
+
}
|
|
46
|
+
if (config.pricingUrl !== undefined && (typeof config.pricingUrl !== 'string' || config.pricingUrl.length === 0)) {
|
|
47
|
+
throw new Error('TokenUsageConfig: "pricingUrl" must be a non-empty string');
|
|
48
|
+
}
|
|
49
|
+
if (config.pricingUrlDomestic !== undefined
|
|
50
|
+
&& (typeof config.pricingUrlDomestic !== 'string' || config.pricingUrlDomestic.length === 0)) {
|
|
51
|
+
throw new Error('TokenUsageConfig: "pricingUrlDomestic" must be a non-empty string');
|
|
52
|
+
}
|
|
53
|
+
if (config.pricingUrlOverseas !== undefined
|
|
54
|
+
&& (typeof config.pricingUrlOverseas !== 'string' || config.pricingUrlOverseas.length === 0)) {
|
|
55
|
+
throw new Error('TokenUsageConfig: "pricingUrlOverseas" must be a non-empty string');
|
|
56
|
+
}
|
|
57
|
+
if (config.pricingRegion !== undefined
|
|
58
|
+
&& config.pricingRegion !== 'domestic' && config.pricingRegion !== 'overseas') {
|
|
59
|
+
throw new Error('TokenUsageConfig: "pricingRegion" must be "domestic" or "overseas"');
|
|
60
|
+
}
|
|
61
|
+
if (config.startupDeferMs !== undefined
|
|
62
|
+
&& (!Number.isFinite(config.startupDeferMs) || config.startupDeferMs < 0)) {
|
|
63
|
+
throw new Error('TokenUsageConfig: "startupDeferMs" must be a non-negative number');
|
|
64
|
+
}
|
|
65
|
+
if (config.quota !== undefined) {
|
|
66
|
+
if (typeof config.quota !== 'object' || config.quota === null) {
|
|
67
|
+
throw new Error('TokenUsageConfig: "quota" must be an object');
|
|
68
|
+
}
|
|
69
|
+
const quotaUnknown = Object.keys(config.quota).find(key => key !== 'enabled' && key !== 'intervalSec');
|
|
70
|
+
if (quotaUnknown !== undefined) {
|
|
71
|
+
throw new Error(`TokenUsageConfig: unknown quota key "${quotaUnknown}"`);
|
|
72
|
+
}
|
|
73
|
+
const { enabled, intervalSec } = config.quota;
|
|
74
|
+
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
|
75
|
+
throw new Error('TokenUsageConfig: quota "enabled" must be a boolean');
|
|
76
|
+
}
|
|
77
|
+
if (intervalSec !== undefined
|
|
78
|
+
&& (!Number.isFinite(intervalSec) || intervalSec < 15 || intervalSec > 3600)) {
|
|
79
|
+
throw new Error('TokenUsageConfig: quota "intervalSec" must be a number within 15–3600');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Resolve the data directory: an explicit `path` wins; otherwise
|
|
85
|
+
* `$DSH_HOME/token-usage` (a blank `$DSH_HOME` counts as unset), else
|
|
86
|
+
* `~/.dsh/token-usage`.
|
|
87
|
+
*/
|
|
88
|
+
export function resolveDataDir(configPath) {
|
|
89
|
+
if (configPath !== undefined)
|
|
90
|
+
return configPath;
|
|
91
|
+
const envHome = process.env.DSH_HOME;
|
|
92
|
+
const base = typeof envHome === 'string' && envHome.trim() !== ''
|
|
93
|
+
? envHome
|
|
94
|
+
: join(homedir(), '.dsh');
|
|
95
|
+
return join(base, 'token-usage');
|
|
96
|
+
}
|
|
97
|
+
export const name = 'token-usage';
|
|
98
|
+
export const inject = ['sessions', 'sessionPersistence'];
|
|
99
|
+
/**
|
|
100
|
+
* Coalescing window for pricing re-sync requests. Startup arrives as several
|
|
101
|
+
* near-simultaneous requests (the entry-config fallback and the settings
|
|
102
|
+
* attach's change callback, order not guaranteed); collapsing them into one
|
|
103
|
+
* fetch means a restart logs a single "pricing sync" line at the effective
|
|
104
|
+
* URL even when the user picked a region.
|
|
105
|
+
*/
|
|
106
|
+
const PRICING_SYNC_COALESCE_MS = 250;
|
|
107
|
+
/**
|
|
108
|
+
* Startup grace period: within it, a re-published section that resolves to the
|
|
109
|
+
* URL the startup already synced is not fetched again. The file settings
|
|
110
|
+
* provider can re-commit the same section during boot (a watcher reconcile),
|
|
111
|
+
* and such a transient must never turn one startup sync into two.
|
|
112
|
+
*/
|
|
113
|
+
const PRICING_SYNC_STARTUP_GRACE_MS = 5_000;
|
|
114
|
+
/** The settings namespace this plugin serves; its browser card spells the same string. */
|
|
115
|
+
export const TOKEN_USAGE_NS = settingsNamespace('token-usage');
|
|
116
|
+
/** Schema resolving the `token-usage` settings section. */
|
|
117
|
+
export const sectionSchema = z.object({
|
|
118
|
+
path: z.string(),
|
|
119
|
+
pricingRegion: z.union([z.const('domestic'), z.const('overseas')]),
|
|
120
|
+
});
|
|
121
|
+
/** The section-shaped view of a config: absent keys stay absent (`exactOptionalPropertyTypes`). */
|
|
122
|
+
function sectionOf(config) {
|
|
123
|
+
return {
|
|
124
|
+
...(config.path === undefined ? {} : { path: config.path }),
|
|
125
|
+
...(config.pricingRegion === undefined ? {} : { pricingRegion: config.pricingRegion }),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Reject an empty stored path: the schema cannot (an empty string is a valid
|
|
130
|
+
* string), and it would silently disable the explicit-directory intent.
|
|
131
|
+
* @param value - the resolved section, schema-valid by construction.
|
|
132
|
+
*/
|
|
133
|
+
export function validateSection(value) {
|
|
134
|
+
if (value.path !== undefined && value.path.length === 0) {
|
|
135
|
+
throw new Error('token-usage: "path" must be a non-empty string');
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Count the sessions still mid-conversation: a session whose event log ends
|
|
140
|
+
* inside an open turn (its last turn event is a `turn/start` with no closing
|
|
141
|
+
* `turn/end`). Existence alone must not count — an idle open tab stays in the
|
|
142
|
+
* store while its conversation ended, and events only append while a turn is
|
|
143
|
+
* open, which is exactly the window that makes a migration unsafe.
|
|
144
|
+
* @param sessions - the store's live sessions (creation order; irrelevant here).
|
|
145
|
+
* @returns how many of them are mid-conversation right now.
|
|
146
|
+
*/
|
|
147
|
+
export function countInteractingSessions(sessions) {
|
|
148
|
+
let interacting = 0;
|
|
149
|
+
for (const session of sessions) {
|
|
150
|
+
// The turn a log ends in is the one that matters; scan back to its edge.
|
|
151
|
+
const events = session.events;
|
|
152
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
153
|
+
const type = events[i]?.type;
|
|
154
|
+
if (type === 'turn/start') {
|
|
155
|
+
interacting++;
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
if (type === 'turn/end')
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return interacting;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The refusal facts of one would-be directory save: `blocked` says the
|
|
166
|
+
* section validator would refuse that save right now (a directory change
|
|
167
|
+
* while any session is mid-conversation), `interactingSessions` counts those
|
|
168
|
+
* sessions for the card's notice. The write veto ({@link validateSectionChange})
|
|
169
|
+
* and the browser card's pre-save check (the `dir-guard` route) both answer
|
|
170
|
+
* through this function, so the two can never disagree.
|
|
171
|
+
* @param proposed - the stored path the save would land (`undefined` when the
|
|
172
|
+
* save clears the override back to the default location).
|
|
173
|
+
* @param guard - the running directory and mid-conversation session count.
|
|
174
|
+
* @returns the verdict the card renders.
|
|
175
|
+
*/
|
|
176
|
+
export function directoryGuard(proposed, guard) {
|
|
177
|
+
if (guard.runningDir === undefined)
|
|
178
|
+
return { blocked: false, interactingSessions: guard.interactingSessions };
|
|
179
|
+
if (resolveDataDir(proposed) === guard.runningDir)
|
|
180
|
+
return { blocked: false, interactingSessions: guard.interactingSessions };
|
|
181
|
+
return { blocked: guard.interactingSessions > 0, interactingSessions: guard.interactingSessions };
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Vet one section write before it persists: a directory change is refused
|
|
185
|
+
* outright while any session is mid-conversation — their events append to the
|
|
186
|
+
* source mid-copy, so a stored move could not run safely, and a silently stored
|
|
187
|
+
* move that never runs is worse than a refused save. Region-only edits and
|
|
188
|
+
* no-op path writes pass freely; the first start (no running directory yet)
|
|
189
|
+
* adopts the stored path without migration, so it passes too.
|
|
190
|
+
* @param value - the resolved section, schema-valid by construction.
|
|
191
|
+
* @param guard - the running directory and mid-conversation session count.
|
|
192
|
+
*/
|
|
193
|
+
export function validateSectionChange(value, guard) {
|
|
194
|
+
validateSection(value);
|
|
195
|
+
const verdict = directoryGuard(value.path, guard);
|
|
196
|
+
if (verdict.blocked) {
|
|
197
|
+
throw new Error(`cannot change the data directory while ${String(verdict.interactingSessions)} session(s) are mid-conversation; let them finish and save again`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
export function apply(ctx, config = {}) {
|
|
201
|
+
validateConfig(config);
|
|
202
|
+
// The section source: the composition entry until a settings service
|
|
203
|
+
// attaches, then `setSource` repoints it at the resolved settings scope.
|
|
204
|
+
// A thunk, not a snapshot — reads see the current resolution at call time,
|
|
205
|
+
// so both the pricing region and the data directory follow a stored edit.
|
|
206
|
+
let sectionSource = () => sectionOf(config);
|
|
207
|
+
// The directory and log currently in force. Registrations below read them
|
|
208
|
+
// per event and per request, so a settings-driven move swaps the running
|
|
209
|
+
// directory without re-registering anything.
|
|
210
|
+
let current;
|
|
211
|
+
// Serialized relocations: a move runs to settlement before the next begins,
|
|
212
|
+
// so two quick edits cannot interleave two migrations of the same files.
|
|
213
|
+
let relocating = Promise.resolve();
|
|
214
|
+
// Live migration progress, polled by the browser card while a move runs.
|
|
215
|
+
let migration;
|
|
216
|
+
// Live full-sync state, polled by the browser card while a manual scan runs.
|
|
217
|
+
// The default `idle` means "never triggered" (or "the last run settled and
|
|
218
|
+
// the card cleared it"); a card opening this section does not auto-clear
|
|
219
|
+
// a terminal `done` / `failed` — those linger so the user can read the
|
|
220
|
+
// result, and the next `triggerFullSync` overwrites them.
|
|
221
|
+
let fullSyncStatus = { status: 'idle' };
|
|
222
|
+
// At most one manual scan at a time: a second POST returns 409 and the card
|
|
223
|
+
// shows the button as disabled until the running scan settles.
|
|
224
|
+
let fullSyncRunning = false;
|
|
225
|
+
/**
|
|
226
|
+
* The directory currently in force; before the first start it resolves
|
|
227
|
+
* through the section source, matching the directory `start` is about to
|
|
228
|
+
* open (and the one the startup pricing sync targets).
|
|
229
|
+
*/
|
|
230
|
+
const currentDir = () => current?.dir ?? resolveDataDir(sectionSource().path);
|
|
231
|
+
/**
|
|
232
|
+
* Move the running data directory as a two-phase commit: refuse while any
|
|
233
|
+
* session is live (their events append to the source mid-copy), copy every
|
|
234
|
+
* owned file verbatim with size verification, flip the running directory,
|
|
235
|
+
* and only then remove the source files that verifiably landed. A failure
|
|
236
|
+
* at any point leaves the source intact — data exists in both places or
|
|
237
|
+
* only in the source, never only in the target.
|
|
238
|
+
* @param nextDir - the resolved directory to move to.
|
|
239
|
+
*/
|
|
240
|
+
const relocateTo = async (nextDir) => {
|
|
241
|
+
const previous = current;
|
|
242
|
+
if (previous === undefined || previous.dir === nextDir)
|
|
243
|
+
return;
|
|
244
|
+
// A mid-conversation session's events append to the source while the copy
|
|
245
|
+
// runs; a copied file would then be stale the moment it lands. Refuse the
|
|
246
|
+
// move and keep the current directory — the user lets the conversation
|
|
247
|
+
// finish and retries.
|
|
248
|
+
const interacting = countInteractingSessions(ctx.sessions.list());
|
|
249
|
+
if (interacting > 0) {
|
|
250
|
+
throw new Error(`cannot move the data directory while ${String(interacting)} session(s) are mid-conversation; let them finish and save again`);
|
|
251
|
+
}
|
|
252
|
+
// Quiesce the source: drain queued appends so the files on disk are final.
|
|
253
|
+
await previous.log.flush();
|
|
254
|
+
migration = { phase: 'copying', done: 0, total: 0 };
|
|
255
|
+
const report = (progress) => {
|
|
256
|
+
migration = { ...progress };
|
|
257
|
+
console.log(`[token-usage] moving ${String(progress.done)}/${String(progress.total)} (${progress.phase})`);
|
|
258
|
+
};
|
|
259
|
+
// Phase 1: copy everything, verbatim. An existing same-named target file
|
|
260
|
+
// wins (live data or a user placement); a failure aborts before the flip.
|
|
261
|
+
await copyData(previous.dir, nextDir, report);
|
|
262
|
+
// Phase 2: flip the running configuration. A fresh log knows the rows the
|
|
263
|
+
// target already holds, so post-flip events dedupe against them.
|
|
264
|
+
const log = new UsageLog(nextDir);
|
|
265
|
+
await log.scan();
|
|
266
|
+
current = { dir: nextDir, log };
|
|
267
|
+
clearRecordCache(previous.dir);
|
|
268
|
+
void warmRecordCache(nextDir);
|
|
269
|
+
// Phase 3: remove the source files that verifiably landed, then the
|
|
270
|
+
// emptied directory. Nothing unknown is touched.
|
|
271
|
+
migration = { phase: 'cleaning', done: 0, total: 0 };
|
|
272
|
+
const result = await cleanSource(previous.dir, nextDir, report);
|
|
273
|
+
migration = undefined;
|
|
274
|
+
console.log(`[token-usage] data directory moved to ${nextDir} (${String(result.cleaned)} files relocated)`);
|
|
275
|
+
};
|
|
276
|
+
// The feed URL the latest dispatch targeted; the startup gate reads only
|
|
277
|
+
// its presence (the first sync has gone out), not the URL itself.
|
|
278
|
+
let lastSyncedUrl;
|
|
279
|
+
// Coalescing handle: startup requests — the entry-config fallback below and
|
|
280
|
+
// the settings attach's onChange, whose arrival order is not guaranteed —
|
|
281
|
+
// collapse into one sync at the latest effective URL, so a restart logs a
|
|
282
|
+
// single "pricing sync" line even when the user has set a region.
|
|
283
|
+
let pendingSync;
|
|
284
|
+
// Within this window a section re-published to an already-synced URL is a
|
|
285
|
+
// boot transient, not an edit, and must not re-fetch.
|
|
286
|
+
const startupUntil = Date.now() + PRICING_SYNC_STARTUP_GRACE_MS;
|
|
287
|
+
/**
|
|
288
|
+
* The effective URL inputs: the composition URL overrides and explicit
|
|
289
|
+
* `pricingUrl`, plus the settings-resolved region pick. The section's URL
|
|
290
|
+
* fields are composition-only now the card exposes just the switch, so
|
|
291
|
+
* they ride on `config`; only `pricingRegion` crosses the settings wire
|
|
292
|
+
* into the URL resolution (`path` is a directory concern, not a URL one).
|
|
293
|
+
* Conditional spreads keep absent keys absent under
|
|
294
|
+
* `exactOptionalPropertyTypes`.
|
|
295
|
+
*/
|
|
296
|
+
const effectiveInput = () => ({
|
|
297
|
+
...(config.pricingUrlDomestic !== undefined ? { pricingUrlDomestic: config.pricingUrlDomestic } : {}),
|
|
298
|
+
...(config.pricingUrlOverseas !== undefined ? { pricingUrlOverseas: config.pricingUrlOverseas } : {}),
|
|
299
|
+
...(sectionSource().pricingRegion !== undefined ? { pricingRegion: sectionSource().pricingRegion } : {}),
|
|
300
|
+
...(config.pricingUrl !== undefined ? { pricingUrl: config.pricingUrl } : {}),
|
|
301
|
+
});
|
|
302
|
+
/**
|
|
303
|
+
* Refresh the cloud pricing mirror at the currently resolved feed URL: the
|
|
304
|
+
* feed is cheap to fetch (small JSON) and the mirror is written atomically,
|
|
305
|
+
* so a failed or stale fetch keeps the previous mirror and the stats page
|
|
306
|
+
* keeps working. The URL resolves through resolvePricingUrl: an explicit
|
|
307
|
+
* `pricingUrl` (composition) wins, otherwise `pricingRegion` picks the
|
|
308
|
+
* domestic or overseas mirror. The mirror lands in the directory currently
|
|
309
|
+
* in force, so a completed relocation re-seeds the new location even
|
|
310
|
+
* though the pricing files traveled with the migration.
|
|
311
|
+
*/
|
|
312
|
+
const syncPricing = () => {
|
|
313
|
+
// Resolve once and capture: the .then below runs when its fetch settles,
|
|
314
|
+
// by which time a newer dispatch may have repointed `lastSyncedUrl`, so
|
|
315
|
+
// the log line must read the URL this fetch actually used.
|
|
316
|
+
const url = resolvePricingUrl(effectiveInput());
|
|
317
|
+
lastSyncedUrl = url;
|
|
318
|
+
void syncCloudPricing(currentDir(), url)
|
|
319
|
+
.then((result) => {
|
|
320
|
+
console.log(`[token-usage] pricing sync (${url}): version ${result.version} (${result.models} models, ${result.aliases} aliases, USD rate ${result.usdExchangeRate})`);
|
|
321
|
+
})
|
|
322
|
+
.catch((error) => {
|
|
323
|
+
// Offline or a slow network must never break the plugin: the previous
|
|
324
|
+
// mirror (if any) stays active until a later sync retries the fetch.
|
|
325
|
+
console.warn('[token-usage] pricing sync failed:', error instanceof Error ? error.message : String(error));
|
|
326
|
+
});
|
|
327
|
+
};
|
|
328
|
+
/**
|
|
329
|
+
* Request a refresh of the mirror at the currently effective URL. Two
|
|
330
|
+
* constraints keep one restart to exactly one fetch:
|
|
331
|
+
*
|
|
332
|
+
* - **Startup gate**: once the first sync has been dispatched, every request
|
|
333
|
+
* until `PRICING_SYNC_STARTUP_GRACE_MS` passes is a boot transient (the
|
|
334
|
+
* settings attach's callback, the file provider's watcher reconcile, a
|
|
335
|
+
* transient value flap) and is dropped.
|
|
336
|
+
* - **Coalescing**: bursts of requests collapse into one fetch at the latest
|
|
337
|
+
* effective URL, so post-startup edits re-sync at most once per burst.
|
|
338
|
+
*/
|
|
339
|
+
const requestSync = () => {
|
|
340
|
+
if (lastSyncedUrl !== undefined && Date.now() < startupUntil)
|
|
341
|
+
return;
|
|
342
|
+
if (pendingSync !== undefined)
|
|
343
|
+
return;
|
|
344
|
+
pendingSync = setTimeout(() => {
|
|
345
|
+
pendingSync = undefined;
|
|
346
|
+
syncPricing();
|
|
347
|
+
}, PRICING_SYNC_COALESCE_MS);
|
|
348
|
+
};
|
|
349
|
+
// Drop a queued sync when this plugin's fiber disposes before the window
|
|
350
|
+
// closes (a reload within the first ~250ms), so no stray fetch outlives it.
|
|
351
|
+
ctx.effect(() => () => {
|
|
352
|
+
if (pendingSync !== undefined)
|
|
353
|
+
clearTimeout(pendingSync);
|
|
354
|
+
}, 'token-usage: pricing sync coalescer');
|
|
355
|
+
/**
|
|
356
|
+
* Kick off one full scan over every persisted session log and stream the
|
|
357
|
+
* live counts into {@link fullSyncStatus}. The scan is the same shape as
|
|
358
|
+
* the one-shot startup sync (list + inspect + UsageLog dedupe) — there is
|
|
359
|
+
* no watermark shortcut here, so the user gets a guarantee that every
|
|
360
|
+
* persisted request row the log does not yet hold will land. The run is
|
|
361
|
+
* fire-and-forget: a second trigger while one is in flight returns
|
|
362
|
+
* `{ started: false, reason: 'already-running' }` and the route answers
|
|
363
|
+
* 409 so the card can keep its button disabled.
|
|
364
|
+
*/
|
|
365
|
+
const triggerFullSync = () => {
|
|
366
|
+
if (fullSyncRunning)
|
|
367
|
+
return { started: false, reason: 'already-running' };
|
|
368
|
+
const target = current;
|
|
369
|
+
if (target === undefined)
|
|
370
|
+
return { started: false, reason: 'already-running' };
|
|
371
|
+
fullSyncRunning = true;
|
|
372
|
+
fullSyncStatus = { status: 'running', processed: 0, total: 0, added: 0, skipped: 0 };
|
|
373
|
+
void syncHistory({ persistence: ctx.sessionPersistence, log: target.log }, (tick) => {
|
|
374
|
+
// The route's status thunk reads `fullSyncStatus` by reference, so each
|
|
375
|
+
// tick is visible to the next poll without any other wiring.
|
|
376
|
+
fullSyncStatus = { status: 'running', ...tick };
|
|
377
|
+
})
|
|
378
|
+
.then((result) => {
|
|
379
|
+
// `syncHistory` always emits a final tick at `processed: total`, but
|
|
380
|
+
// we re-stamp the done state from the resolved result so the
|
|
381
|
+
// `added` / `skipped` totals match the function's return exactly
|
|
382
|
+
// (the last tick carries the in-loop counters; this stamp aligns
|
|
383
|
+
// them with the result in case of any trailing read).
|
|
384
|
+
const last = fullSyncStatus.status === 'running' ? fullSyncStatus
|
|
385
|
+
: { processed: 0, total: 0, added: 0, skipped: 0 };
|
|
386
|
+
fullSyncStatus = {
|
|
387
|
+
status: 'done',
|
|
388
|
+
processed: last.processed,
|
|
389
|
+
total: last.total,
|
|
390
|
+
added: result.added,
|
|
391
|
+
skipped: result.skipped,
|
|
392
|
+
};
|
|
393
|
+
console.log(`[token-usage] full sync done: ${String(result.added)} added, ${String(result.skipped)} skipped`);
|
|
394
|
+
})
|
|
395
|
+
.catch((error) => {
|
|
396
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
397
|
+
fullSyncStatus = { status: 'failed', error: message };
|
|
398
|
+
console.error('[token-usage] full sync failed:', error);
|
|
399
|
+
})
|
|
400
|
+
.finally(() => {
|
|
401
|
+
fullSyncRunning = false;
|
|
402
|
+
});
|
|
403
|
+
return { started: true };
|
|
404
|
+
};
|
|
405
|
+
// ---- Provider quota feature (input-bar button, `/token-usage/quota`) ----
|
|
406
|
+
// Live tracking of which provider route each session uses: fed by the
|
|
407
|
+
// same session events the recorder reads, but registered at apply scope
|
|
408
|
+
// so tracking works before (and regardless of) the data directory start.
|
|
409
|
+
const quotaTracker = new ProviderTracker();
|
|
410
|
+
ctx.on('session/event', (session, event) => {
|
|
411
|
+
// request/context fires at dispatch — the provider is known before the
|
|
412
|
+
// first token; assistant/message re-confirms it from the provenance.
|
|
413
|
+
if (event.type === 'request/context') {
|
|
414
|
+
quotaTracker.observe(session.id, event.data.provider, event.data.model);
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
if (event.type === 'assistant/message') {
|
|
418
|
+
quotaTracker.observe(session.id, event.data.message.source.provider, event.data.message.source.model);
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
// The three seams the credential chain runs over. Each starts as a no-op
|
|
422
|
+
// and upgrades when its (optional) host service attaches; a missing seam
|
|
423
|
+
// shortens the chain rather than breaking it.
|
|
424
|
+
let quotaDirectory;
|
|
425
|
+
let quotaReadSettings = () => undefined;
|
|
426
|
+
let quotaResolveCredential;
|
|
427
|
+
let quotaReadRecord;
|
|
428
|
+
ctx.inject(['llm'], (llmCtx) => {
|
|
429
|
+
// The provider directory maps a route key to its settings location —
|
|
430
|
+
// the one authoritative source (the built-in fallback in
|
|
431
|
+
// credentials.ts covers hosts without the llm service).
|
|
432
|
+
llmCtx.effect(() => {
|
|
433
|
+
quotaDirectory = (provider) => {
|
|
434
|
+
const entry = llmCtx.llm.listConfigurableProviders().find(item => item.provider === provider);
|
|
435
|
+
return entry === undefined ? undefined : {
|
|
436
|
+
settingsNs: entry.settingsNs,
|
|
437
|
+
settingsPath: entry.settingsPath,
|
|
438
|
+
displayName: entry.displayName,
|
|
439
|
+
};
|
|
440
|
+
};
|
|
441
|
+
return () => { quotaDirectory = undefined; };
|
|
442
|
+
}, 'token-usage: quota provider directory');
|
|
443
|
+
});
|
|
444
|
+
ctx.inject(['settings'], (settingsCtx) => {
|
|
445
|
+
settingsCtx.effect(() => {
|
|
446
|
+
quotaReadSettings = (ns) => settingsCtx.settings.get(settingsNamespace(ns));
|
|
447
|
+
return () => { quotaReadSettings = () => undefined; };
|
|
448
|
+
}, 'token-usage: quota settings reader');
|
|
449
|
+
});
|
|
450
|
+
ctx.inject(['credentials'], (credentialsCtx) => {
|
|
451
|
+
credentialsCtx.effect(() => {
|
|
452
|
+
quotaResolveCredential = async (ref) => (await credentialsCtx.credentials.resolve(credentialRef(ref)))?.value;
|
|
453
|
+
// The record store is newer than the installed typings; read it
|
|
454
|
+
// feature-detected (absent on older hosts — the env layer covers).
|
|
455
|
+
const recordReader = credentialsCtx.credentials.readRecord;
|
|
456
|
+
if (typeof recordReader === 'function') {
|
|
457
|
+
quotaReadRecord = key => recordReader.call(credentialsCtx.credentials, key);
|
|
458
|
+
}
|
|
459
|
+
return () => {
|
|
460
|
+
quotaResolveCredential = undefined;
|
|
461
|
+
quotaReadRecord = undefined;
|
|
462
|
+
};
|
|
463
|
+
}, 'token-usage: quota credential seam');
|
|
464
|
+
});
|
|
465
|
+
const quotaEnabled = config.quota?.enabled !== false;
|
|
466
|
+
const quotaIntervalSec = Math.min(3600, Math.max(15, Math.round(config.quota?.intervalSec ?? 60)));
|
|
467
|
+
const quotaService = new QuotaService({
|
|
468
|
+
resolveProvider: sessionId => resolveCurrentProvider({
|
|
469
|
+
tracker: quotaTracker,
|
|
470
|
+
...(sessionId !== undefined ? { sessionId } : {}),
|
|
471
|
+
defaultProvider: () => {
|
|
472
|
+
// A brand-new, never-requesting session would use the host's
|
|
473
|
+
// default model selection; absent or unregistered → undefined.
|
|
474
|
+
const section = quotaReadSettings('agent-default-model');
|
|
475
|
+
if (typeof section !== 'object' || section === null)
|
|
476
|
+
return undefined;
|
|
477
|
+
const provider = section.provider;
|
|
478
|
+
return typeof provider === 'string' && provider !== '' ? provider : undefined;
|
|
479
|
+
},
|
|
480
|
+
}),
|
|
481
|
+
resolveCredentials: async (provider) => withCatalogBaseUrl(provider, await resolveQuotaCredentials({
|
|
482
|
+
provider,
|
|
483
|
+
...(quotaDirectory !== undefined ? { directory: quotaDirectory } : {}),
|
|
484
|
+
readSettings: quotaReadSettings,
|
|
485
|
+
...(quotaResolveCredential !== undefined ? { resolveCredential: quotaResolveCredential } : {}),
|
|
486
|
+
...(quotaReadRecord !== undefined ? { readRecord: quotaReadRecord } : {}),
|
|
487
|
+
})),
|
|
488
|
+
intervalSec: quotaIntervalSec,
|
|
489
|
+
});
|
|
490
|
+
/**
|
|
491
|
+
* Open (or move) the running data directory at the section-resolved
|
|
492
|
+
* location. Idempotent: the first call opens the directory and registers
|
|
493
|
+
* the listeners and routes; a later call with a different resolved
|
|
494
|
+
* directory enqueues a serialized relocation, and one with the same
|
|
495
|
+
* directory is a no-op. A refusal (active sessions) or a migration
|
|
496
|
+
* failure leaves the running directory unchanged.
|
|
497
|
+
*/
|
|
498
|
+
const start = () => {
|
|
499
|
+
const resolved = resolveDataDir(sectionSource().path);
|
|
500
|
+
if (current !== undefined) {
|
|
501
|
+
if (resolved !== current.dir) {
|
|
502
|
+
relocating = relocating.then(() => relocateTo(resolved)).catch((error) => {
|
|
503
|
+
migration = undefined;
|
|
504
|
+
console.error('[token-usage] data directory move failed:', error);
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
const dir = resolved;
|
|
510
|
+
const log = new UsageLog(dir);
|
|
511
|
+
current = { dir, log };
|
|
512
|
+
void warmRecordCache(dir);
|
|
513
|
+
ctx.on('session/event', (session, event) => {
|
|
514
|
+
if (event.type !== 'assistant/message')
|
|
515
|
+
return;
|
|
516
|
+
const record = recordFromEvent(event, session.id);
|
|
517
|
+
// Fire-and-forget: the log serializes appends and reports its own failures.
|
|
518
|
+
void current?.log.record(record);
|
|
519
|
+
});
|
|
520
|
+
// One-shot backfill for requests recorded before this plugin was installed.
|
|
521
|
+
// Fire-and-forget: a failure leaves the marker unwritten and the next
|
|
522
|
+
// startup retries; a crash mid-run is absorbed by the sync's dedupe.
|
|
523
|
+
void autoSyncIfNeeded({ persistence: ctx.sessionPersistence, log }, dir)
|
|
524
|
+
.then((result) => {
|
|
525
|
+
if (result !== null) {
|
|
526
|
+
console.log(`[token-usage] first-run sync: ${result.added} added, ${result.skipped} skipped`);
|
|
527
|
+
}
|
|
528
|
+
return warmRecordCache(dir);
|
|
529
|
+
})
|
|
530
|
+
.catch((error) => {
|
|
531
|
+
console.error('[token-usage] first-run sync failed:', error);
|
|
532
|
+
});
|
|
533
|
+
// The stats endpoint backing the web settings page. Optional by design:
|
|
534
|
+
// profiles without a webserver (headless runs) keep the logging plugin
|
|
535
|
+
// and simply never mount the route; the browser half of this package
|
|
536
|
+
// shows the page only when the host half serves the route. Both routes
|
|
537
|
+
// read the running state per request, so a relocation serves from the
|
|
538
|
+
// new location and reports its own progress without re-registering.
|
|
539
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
540
|
+
// The display currency follows the region pick live: the thunk reads the
|
|
541
|
+
// settings-resolved section at request time, so a saved region switch
|
|
542
|
+
// re-prices the page's currency on the next fetch without a restart.
|
|
543
|
+
webCtx.effect(() => webCtx.webServer.register(createStatsRoute(currentDir, { currency: () => currencyOfRegion(effectiveInput().pricingRegion) })), 'token-usage: stats route');
|
|
544
|
+
webCtx.effect(() => webCtx.webServer.register(createMigrationRoute(() => migration)), 'token-usage: migration route');
|
|
545
|
+
// The card's pre-save check for a staged directory edit: the settings
|
|
546
|
+
// wire never delivers a refused write's reason (the bound scope recovers
|
|
547
|
+
// silently), so this route answers the same verdict the validator will
|
|
548
|
+
// enforce — before the write, with the mid-conversation count to show.
|
|
549
|
+
webCtx.effect(() => webCtx.webServer.register(createDirectoryGuardRoute((proposed) => directoryGuard(proposed, {
|
|
550
|
+
runningDir: current?.dir,
|
|
551
|
+
interactingSessions: countInteractingSessions(ctx.sessions.list()),
|
|
552
|
+
}))), 'token-usage: directory guard route');
|
|
553
|
+
// The card's manual "scan again" affordance: `POST` kicks off a run,
|
|
554
|
+
// `GET` returns the live progress. The route is read-only over the
|
|
555
|
+
// shared status; the actual scan runs as the closure above.
|
|
556
|
+
webCtx.effect(() => webCtx.webServer.register(createFullSyncRoute(() => fullSyncStatus, triggerFullSync)), 'token-usage: full sync route');
|
|
557
|
+
// The input-bar quota button's data channel: the current provider's
|
|
558
|
+
// quota snapshot (rate-limit windows / balance), served by the quota
|
|
559
|
+
// service. A disabled feature still answers — with the `disabled`
|
|
560
|
+
// variant the button hides behind, rather than a 404.
|
|
561
|
+
webCtx.effect(() => webCtx.webServer.register(createQuotaRoute((sessionId, providerHint) => quotaEnabled
|
|
562
|
+
? quotaService.snapshot(sessionId, providerHint)
|
|
563
|
+
: Promise.resolve({ status: 'disabled', intervalSec: quotaIntervalSec }))), 'token-usage: quota route');
|
|
564
|
+
});
|
|
565
|
+
console.log(`[token-usage] plugin loaded (data dir: ${dir})`);
|
|
566
|
+
};
|
|
567
|
+
// A stored section acts on both concerns live: a directory change
|
|
568
|
+
// relocates, a region switch (any effective-URL change) re-syncs the
|
|
569
|
+
// pricing mirror. The first start intentionally defers (see the deferred
|
|
570
|
+
// startup below): the settings inject's onChange fires after setSource and
|
|
571
|
+
// opens the plugin on the settings-resolved directory; with no settings
|
|
572
|
+
// service the fallback timer opens the composition entry instead.
|
|
573
|
+
installSettingsSection(ctx, TOKEN_USAGE_NS, sectionSchema, sectionOf(config), {
|
|
574
|
+
validate: (value) => validateSectionChange(value, {
|
|
575
|
+
runningDir: current?.dir,
|
|
576
|
+
interactingSessions: countInteractingSessions(ctx.sessions.list()),
|
|
577
|
+
}),
|
|
578
|
+
setSource: (source) => { sectionSource = source; },
|
|
579
|
+
onChange: () => { start(); requestSync(); },
|
|
580
|
+
});
|
|
581
|
+
// The bootstrap defers the first start briefly. The dsh Loader mounts every
|
|
582
|
+
// profile entry CONCURRENTLY, so this plugin's apply() runs in no guaranteed
|
|
583
|
+
// order relative to the base bundle's settings-file provider: probing the
|
|
584
|
+
// settings service synchronously cannot tell "not attached yet" from "never
|
|
585
|
+
// attached", and starting on the composition entry first would open the
|
|
586
|
+
// DEFAULT directory and then relocate default → stored on every boot. So the
|
|
587
|
+
// first start waits a short window for the settings inject (whose onChange
|
|
588
|
+
// fires after setSource, on the settings-resolved directory), then falls
|
|
589
|
+
// back to the composition entry — the idempotent start makes the deferred
|
|
590
|
+
// call a no-op when the inject already won the window. No settings service
|
|
591
|
+
// mounted: the inject stays dormant and the fallback is the one start.
|
|
592
|
+
const startupDeferMs = config.startupDeferMs ?? 500;
|
|
593
|
+
const startup = setTimeout(() => {
|
|
594
|
+
start();
|
|
595
|
+
requestSync();
|
|
596
|
+
}, startupDeferMs);
|
|
597
|
+
ctx.effect(() => () => clearTimeout(startup), 'token-usage: deferred startup');
|
|
598
|
+
}
|
|
599
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAEhC,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAA;AAC5D,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAA;AACrF,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAQxC,OAAO,EAAE,QAAQ,EAAE,M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