@laoyuehanni/dsh-token-usage 0.4.3 → 0.4.5
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/README.md +4 -3
- package/README.zh.md +4 -3
- package/lib/client/CostDeltaFlyLabel.js +1 -1
- package/lib/client/CostDeltaFlyLabel.js.map +1 -1
- package/lib/client/CostPill.d.ts +74 -0
- package/lib/client/CostPill.d.ts.map +1 -0
- package/lib/client/CostPill.js +242 -0
- package/lib/client/CostPill.js.map +1 -0
- package/lib/client/SessionTable.d.ts.map +1 -1
- package/lib/client/SessionTable.js +10 -4
- package/lib/client/SessionTable.js.map +1 -1
- package/lib/client/TokenUsageCard.d.ts +7 -2
- package/lib/client/TokenUsageCard.d.ts.map +1 -1
- package/lib/client/TokenUsageCard.js +11 -4
- package/lib/client/TokenUsageCard.js.map +1 -1
- package/lib/client/TokenUsageSection.d.ts +4 -1
- package/lib/client/TokenUsageSection.d.ts.map +1 -1
- package/lib/client/TokenUsageSection.js +30 -4
- package/lib/client/TokenUsageSection.js.map +1 -1
- package/lib/client/TrendChart.d.ts +1 -1
- package/lib/client/TrendChart.d.ts.map +1 -1
- package/lib/client/TrendChart.js +39 -15
- package/lib/client/TrendChart.js.map +1 -1
- package/lib/client/UsageView.js +2 -2
- package/lib/client/UsageView.js.map +1 -1
- package/lib/client/card-form.d.ts +33 -4
- package/lib/client/card-form.d.ts.map +1 -1
- package/lib/client/card-form.js +20 -8
- package/lib/client/card-form.js.map +1 -1
- package/lib/client/cost-inflate-motion.d.ts +7 -2
- package/lib/client/cost-inflate-motion.d.ts.map +1 -1
- package/lib/client/cost-inflate-motion.js +14 -10
- package/lib/client/cost-inflate-motion.js.map +1 -1
- package/lib/client/format.d.ts +7 -5
- package/lib/client/format.d.ts.map +1 -1
- package/lib/client/format.js +11 -7
- package/lib/client/format.js.map +1 -1
- package/lib/client/index.d.ts +18 -3
- package/lib/client/index.d.ts.map +1 -1
- package/lib/client/index.js +154 -47
- package/lib/client/index.js.map +1 -1
- package/lib/client/locales.d.ts +13 -3
- package/lib/client/locales.d.ts.map +1 -1
- package/lib/client/locales.js +26 -6
- package/lib/client/locales.js.map +1 -1
- package/lib/client/trend-chart/index.d.ts +1 -1
- package/lib/client/trend-chart/index.d.ts.map +1 -1
- package/lib/client/trend-chart/index.js +1 -1
- package/lib/client/trend-chart/index.js.map +1 -1
- package/lib/client/trend-chart/path.d.ts +46 -0
- package/lib/client/trend-chart/path.d.ts.map +1 -1
- package/lib/client/trend-chart/path.js +140 -0
- package/lib/client/trend-chart/path.js.map +1 -1
- package/lib/client/use-color-scheme.d.ts +6 -0
- package/lib/client/use-color-scheme.d.ts.map +1 -1
- package/lib/client/use-color-scheme.js +53 -1
- package/lib/client/use-color-scheme.js.map +1 -1
- package/lib/client/use-cost-inflate.d.ts +4 -4
- package/lib/client/use-cost-inflate.js +5 -5
- package/lib/client/use-cost-inflate.js.map +1 -1
- package/lib/client.js +1913 -1250
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +30 -52
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +140 -133
- package/lib/index.js.map +1 -1
- package/lib/stats.d.ts +1 -1
- package/lib/stats.d.ts.map +1 -1
- package/lib/stats.js +1 -1
- package/lib/stats.js.map +1 -1
- package/lib/sync-state.d.ts +17 -6
- package/lib/sync-state.d.ts.map +1 -1
- package/lib/sync-state.js +28 -6
- package/lib/sync-state.js.map +1 -1
- package/lib/sync.d.ts +25 -0
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +35 -4
- package/lib/sync.js.map +1 -1
- package/lib/usage-log.d.ts +14 -0
- package/lib/usage-log.d.ts.map +1 -1
- package/lib/usage-log.js +128 -1
- package/lib/usage-log.js.map +1 -1
- package/lib/usage-record.d.ts +20 -2
- package/lib/usage-record.d.ts.map +1 -1
- package/lib/usage-record.js +74 -3
- package/lib/usage-record.js.map +1 -1
- package/package.json +42 -36
package/lib/index.d.ts
CHANGED
|
@@ -5,51 +5,45 @@
|
|
|
5
5
|
* installed). When a webServer exists, the plugin also serves the stats
|
|
6
6
|
* route backing the web settings page (browser half in `src/client`).
|
|
7
7
|
*
|
|
8
|
-
* The
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
8
|
+
* The user-editable Config fields (`path`, `pricingRegion`) are declared
|
|
9
|
+
* `.volatile()` so the dsh 0.1.7 settings service projects them into the
|
|
10
|
+
* `token-usage` settings form (the browser card edits them through
|
|
11
|
+
* `configForms`; saves land in the profile patch and commit live through
|
|
12
|
+
* the loader without a plugin reload). A region pick re-resolves the feed
|
|
13
|
+
* URL and re-syncs the mirror; a data directory change switches writes to
|
|
14
|
+
* the new location and migrates every row and companion file across
|
|
15
|
+
* (verbatim file copy, then source cleanup), so no restart and no manual
|
|
16
|
+
* data move is needed.
|
|
15
17
|
*
|
|
16
18
|
* @module token-usage
|
|
17
19
|
*/
|
|
18
|
-
import type { Context } from '@deepseek-ai/cordis';
|
|
20
|
+
import type { Context, Volatile } from '@deepseek-ai/cordis';
|
|
19
21
|
import z from '@deepseek-ai/schemastery';
|
|
20
22
|
import { type DirectoryGuardView } from './wire.ts';
|
|
21
23
|
export interface Config {
|
|
22
24
|
/** Data directory; defaults to `$DSH_HOME/token-usage` (`~/.dsh/token-usage`). */
|
|
23
|
-
path?: string;
|
|
25
|
+
path?: Volatile<string | undefined> | string;
|
|
24
26
|
/** Explicit cloud pricing feed URL mirrored on every startup; wins over
|
|
25
27
|
* every region setting. Defaults to the model-price-table repository the
|
|
26
|
-
* analyzer also pulls from.
|
|
28
|
+
* analyzer also pulls from. Composition-only — never projected into the
|
|
29
|
+
* settings form. */
|
|
27
30
|
pricingUrl?: string;
|
|
28
|
-
/** Domestic (China) mirror; defaults to the gitee model-price-table feed.
|
|
31
|
+
/** Domestic (China) mirror; defaults to the gitee model-price-table feed.
|
|
32
|
+
* Composition-only. */
|
|
29
33
|
pricingUrlDomestic?: string;
|
|
30
|
-
/** Overseas mirror; defaults to the github model-price-table feed.
|
|
34
|
+
/** Overseas mirror; defaults to the github model-price-table feed.
|
|
35
|
+
* Composition-only. */
|
|
31
36
|
pricingUrlOverseas?: string;
|
|
32
37
|
/** Which mirror to pull when `pricingUrl` is unset: `domestic` (default,
|
|
33
38
|
* gitee) or `overseas` (github). Set once per install — no IP sniffing. */
|
|
34
|
-
pricingRegion?: 'domestic' | 'overseas';
|
|
35
|
-
/** How long the first start waits for a settings service to repoint the
|
|
36
|
-
* section source before falling back to the composition entry. Only armed
|
|
37
|
-
* when the composition entry pins an explicit `path`; otherwise the first
|
|
38
|
-
* start comes from the settings attach itself. Never user-facing — a
|
|
39
|
-
* test-only tilt at the boot deferral. */
|
|
40
|
-
startupDeferMs?: number;
|
|
41
|
-
/** How long the first start waits for a settings service before starting
|
|
42
|
-
* the default directory when the composition entry pins no explicit
|
|
43
|
-
* `path`. The cap only ever fires on hosts that mount no settings service
|
|
44
|
-
* at all, so it must outlast any real boot. Never user-facing — a
|
|
45
|
-
* test-only tilt at the settings-less cap. */
|
|
46
|
-
startupCapMs?: number;
|
|
39
|
+
pricingRegion?: Volatile<'domestic' | 'overseas' | undefined> | 'domestic' | 'overseas';
|
|
47
40
|
/** The provider quota feature (the input-bar button): enabled by default,
|
|
48
|
-
* with the poll cadence the host asks the browser to follow.
|
|
41
|
+
* with the poll cadence the host asks the browser to follow.
|
|
42
|
+
* Composition-only. */
|
|
49
43
|
quota?: QuotaConfig;
|
|
50
44
|
/** Whether compaction summarize requests (`compaction/summary` events)
|
|
51
45
|
* are recorded and billed like plain requests (default `true`). `false`
|
|
52
|
-
* skips them in both the live hook and the history sync. */
|
|
46
|
+
* skips them in both the live hook and the history sync. Composition-only. */
|
|
53
47
|
recordCompaction?: boolean;
|
|
54
48
|
}
|
|
55
49
|
/** Composition knobs of the quota feature (cordis.yml level). */
|
|
@@ -62,13 +56,16 @@ export interface QuotaConfig {
|
|
|
62
56
|
/**
|
|
63
57
|
* Loading-time schema of the composition config (the official Cordis shape:
|
|
64
58
|
* a `Config` type plus a same-named standard schema, validated by the loader
|
|
65
|
-
* before `apply` runs).
|
|
66
|
-
* the
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
59
|
+
* before `apply` runs). The `.volatile()` fields (`path`, `pricingRegion`)
|
|
60
|
+
* are what the 0.1.7 settings service projects into the settings form — a
|
|
61
|
+
* namespace with no volatile field is skipped by `settings.describe()` and
|
|
62
|
+
* its browser card never appears. Keys stay optional — absent keys stay
|
|
63
|
+
* absent, because the plugin's own resolution (`validateConfig` +
|
|
64
|
+
* section-based defaults) is where defaults and unknown-key rejection live.
|
|
65
|
+
* Schemastery's object keeps unknown keys in non-strict mode, so
|
|
66
|
+
* `validateConfig` remains the loud rejection point for misspelled keys.
|
|
70
67
|
*/
|
|
71
|
-
export declare const Config: z<
|
|
68
|
+
export declare const Config: z<any>;
|
|
72
69
|
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
73
70
|
export declare function validateConfig(config: Config): void;
|
|
74
71
|
/**
|
|
@@ -95,14 +92,6 @@ export interface SectionConfig {
|
|
|
95
92
|
/** Mirror to pull when no explicit `pricingUrl` is set: `domestic` (default) or `overseas`. */
|
|
96
93
|
pricingRegion?: 'domestic' | 'overseas';
|
|
97
94
|
}
|
|
98
|
-
/** Schema resolving the `token-usage` settings section. */
|
|
99
|
-
export declare const sectionSchema: z<SectionConfig>;
|
|
100
|
-
/**
|
|
101
|
-
* Reject an empty stored path: the schema cannot (an empty string is a valid
|
|
102
|
-
* string), and it would silently disable the explicit-directory intent.
|
|
103
|
-
* @param value - the resolved section, schema-valid by construction.
|
|
104
|
-
*/
|
|
105
|
-
export declare function validateSection(value: SectionConfig): void;
|
|
106
95
|
/** Live facts a section write is vetted against. */
|
|
107
96
|
export interface SectionGuard {
|
|
108
97
|
/** Directory currently in force; undefined before the first start. */
|
|
@@ -137,16 +126,5 @@ export declare function countInteractingSessions(eventLogs: readonly (readonly {
|
|
|
137
126
|
* @returns the verdict the card renders.
|
|
138
127
|
*/
|
|
139
128
|
export declare function directoryGuard(proposed: string | undefined, guard: SectionGuard): DirectoryGuardView;
|
|
140
|
-
/**
|
|
141
|
-
* Vet one section write before it persists: a directory change is refused
|
|
142
|
-
* outright while any session is mid-conversation — their events append to the
|
|
143
|
-
* source mid-copy, so a stored move could not run safely, and a silently stored
|
|
144
|
-
* move that never runs is worse than a refused save. Region-only edits and
|
|
145
|
-
* no-op path writes pass freely; the first start (no running directory yet)
|
|
146
|
-
* adopts the stored path without migration, so it passes too.
|
|
147
|
-
* @param value - the resolved section, schema-valid by construction.
|
|
148
|
-
* @param guard - the running directory and mid-conversation session count.
|
|
149
|
-
*/
|
|
150
|
-
export declare function validateSectionChange(value: SectionConfig, guard: SectionGuard): void;
|
|
151
129
|
export declare function apply(ctx: Context, config?: Config): void;
|
|
152
130
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAKH,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAO5D,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAsBxC,OAAO,EAAoB,KAAK,kBAAkB,EAAwC,MAAM,WAAW,CAAA;AAuB3G,MAAM,WAAW,MAAM;IACrB,kFAAkF;IAClF,IAAI,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM,CAAA;IAC5C;;;wBAGoB;IACpB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;2BACuB;IACvB,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B;2BACuB;IACvB,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B;+EAC2E;IAC3E,aAAa,CAAC,EAAE,QAAQ,CAAC,UAAU,GAAG,UAAU,GAAG,SAAS,CAAC,GAAG,UAAU,GAAG,UAAU,CAAA;IACvF;;2BAEuB;IACvB,KAAK,CAAC,EAAE,WAAW,CAAA;IACnB;;kFAE8E;IAC9E,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B;AAED,iEAAiE;AACjE,MAAM,WAAW,WAAW;IAC1B,+EAA+E;IAC/E,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,qEAAqE;IACrE,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED;;;;;;;;;;;GAWG;AAIH,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,GAAG,CAWxB,CAAA;AAEF,4EAA4E;AAC5E,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAiDnD;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAOrE;AAED,eAAO,MAAM,IAAI,gBAAgB,CAAA;AACjC,eAAO,MAAM,MAAM,UAAqC,CAAA;AAmBxD,0FAA0F;AAC1F,eAAO,MAAM,cAAc,gBAAgB,CAAA;AAE3C;;;;;;;GAOG;AACH,MAAM,WAAW,aAAa;IAC5B,qEAAqE;IACrE,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,+FAA+F;IAC/F,aAAa,CAAC,EAAE,UAAU,GAAG,UAAU,CAAA;CACxC;AAaD,oDAAoD;AACpD,MAAM,WAAW,YAAY;IAC3B,sEAAsE;IACtE,UAAU,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B,mEAAmE;IACnE,mBAAmB,EAAE,MAAM,CAAA;CAC5B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,SAAS,CAAC,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC,EAAE,GAAG,MAAM,CAcpG;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,YAAY,GAAG,kBAAkB,CAIpG;AAED,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,MAAW,QAgkBtD"}
|
package/lib/index.js
CHANGED
|
@@ -5,13 +5,15 @@
|
|
|
5
5
|
* installed). When a webServer exists, the plugin also serves the stats
|
|
6
6
|
* route backing the web settings page (browser half in `src/client`).
|
|
7
7
|
*
|
|
8
|
-
* The
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
8
|
+
* The user-editable Config fields (`path`, `pricingRegion`) are declared
|
|
9
|
+
* `.volatile()` so the dsh 0.1.7 settings service projects them into the
|
|
10
|
+
* `token-usage` settings form (the browser card edits them through
|
|
11
|
+
* `configForms`; saves land in the profile patch and commit live through
|
|
12
|
+
* the loader without a plugin reload). A region pick re-resolves the feed
|
|
13
|
+
* URL and re-syncs the mirror; a data directory change switches writes to
|
|
14
|
+
* the new location and migrates every row and companion file across
|
|
15
|
+
* (verbatim file copy, then source cleanup), so no restart and no manual
|
|
16
|
+
* data move is needed.
|
|
15
17
|
*
|
|
16
18
|
* @module token-usage
|
|
17
19
|
*/
|
|
@@ -24,7 +26,8 @@ import { UsageLog } from "./usage-log.js";
|
|
|
24
26
|
import { SessionMetaStore } from "./session-meta.js";
|
|
25
27
|
import { cleanSource, copyData } from "./migrate.js";
|
|
26
28
|
import { resolvePricingUrl, syncCloudPricing } from "./pricing.js";
|
|
27
|
-
import { modelOfEvent, recordOfEvent } from "./usage-record.js";
|
|
29
|
+
import { extractFirstTokenTimeFromStream, modelOfEvent, recordOfEvent } from "./usage-record.js";
|
|
30
|
+
import { markTimingSynced, readSyncState } from "./sync-state.js";
|
|
28
31
|
import { autoSyncIfNeeded, syncHistory, titleOfEvent } from "./sync.js";
|
|
29
32
|
import { clearRecordCache, warmRecordCache } from "./record-cache.js";
|
|
30
33
|
import { ROLLUP_FILE_NAME, ROLLUP_TMP_FILE_NAME } from "./rollup.js";
|
|
@@ -34,23 +37,41 @@ import { createQuotaRoute } from "./quota/quota-route.js";
|
|
|
34
37
|
import { QuotaService } from "./quota/quota-service.js";
|
|
35
38
|
import { ProviderTracker, resolveCurrentProvider } from "./quota/provider-tracking.js";
|
|
36
39
|
import { resolveQuotaCredentials, withCatalogBaseUrl, } from "./quota/credentials.js";
|
|
40
|
+
/**
|
|
41
|
+
* Read through the volatile wrapper the dsh 0.1.7 loader places over
|
|
42
|
+
* `.volatile()` Config fields: volatile commits swap the snapshot in place
|
|
43
|
+
* without a reload, so every read resolves at call time. A bare value (test
|
|
44
|
+
* doubles, the pre-wrap apply argument) passes through unchanged.
|
|
45
|
+
*/
|
|
46
|
+
function readVolatile(value) {
|
|
47
|
+
if (value === undefined)
|
|
48
|
+
return undefined;
|
|
49
|
+
if (typeof value === 'object' && value !== null && 'get' in value && typeof value.get === 'function') {
|
|
50
|
+
return value.get();
|
|
51
|
+
}
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
37
54
|
/**
|
|
38
55
|
* Loading-time schema of the composition config (the official Cordis shape:
|
|
39
56
|
* a `Config` type plus a same-named standard schema, validated by the loader
|
|
40
|
-
* before `apply` runs).
|
|
41
|
-
* the
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
57
|
+
* before `apply` runs). The `.volatile()` fields (`path`, `pricingRegion`)
|
|
58
|
+
* are what the 0.1.7 settings service projects into the settings form — a
|
|
59
|
+
* namespace with no volatile field is skipped by `settings.describe()` and
|
|
60
|
+
* its browser card never appears. Keys stay optional — absent keys stay
|
|
61
|
+
* absent, because the plugin's own resolution (`validateConfig` +
|
|
62
|
+
* section-based defaults) is where defaults and unknown-key rejection live.
|
|
63
|
+
* Schemastery's object keeps unknown keys in non-strict mode, so
|
|
64
|
+
* `validateConfig` remains the loud rejection point for misspelled keys.
|
|
45
65
|
*/
|
|
66
|
+
// (No `z<Config>` annotation: the `.volatile()` wrappers widen the schema's
|
|
67
|
+
// inferred type past the plain `Config` shape, exactly as the reference
|
|
68
|
+
// migration in dsh-git-worktree does it.)
|
|
46
69
|
export const Config = z.object({
|
|
47
|
-
path: z.string(),
|
|
70
|
+
path: z.string().volatile(),
|
|
48
71
|
pricingUrl: z.string(),
|
|
49
72
|
pricingUrlDomestic: z.string(),
|
|
50
73
|
pricingUrlOverseas: z.string(),
|
|
51
|
-
pricingRegion: z.union([z.const('domestic'), z.const('overseas')]),
|
|
52
|
-
startupDeferMs: z.number().min(0),
|
|
53
|
-
startupCapMs: z.number().min(0),
|
|
74
|
+
pricingRegion: z.union([z.const('domestic'), z.const('overseas')]).volatile(),
|
|
54
75
|
recordCompaction: z.boolean(),
|
|
55
76
|
quota: z.object({
|
|
56
77
|
enabled: z.boolean(),
|
|
@@ -60,14 +81,14 @@ export const Config = z.object({
|
|
|
60
81
|
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
61
82
|
export function validateConfig(config) {
|
|
62
83
|
const unknown = Object.keys(config).find(key => key !== 'path' && key !== 'pricingUrl' && key !== 'pricingUrlDomestic'
|
|
63
|
-
&& key !== 'pricingUrlOverseas' && key !== 'pricingRegion'
|
|
64
|
-
&& key !== 'startupCapMs'
|
|
84
|
+
&& key !== 'pricingUrlOverseas' && key !== 'pricingRegion'
|
|
65
85
|
&& key !== 'recordCompaction'
|
|
66
86
|
&& key !== 'quota');
|
|
67
87
|
if (unknown !== undefined) {
|
|
68
88
|
throw new Error(`TokenUsageConfig: unknown key "${unknown}"`);
|
|
69
89
|
}
|
|
70
|
-
|
|
90
|
+
const path = readVolatile(config.path);
|
|
91
|
+
if (path !== undefined && (typeof path !== 'string' || path.length === 0)) {
|
|
71
92
|
throw new Error('TokenUsageConfig: "path" must be a non-empty string');
|
|
72
93
|
}
|
|
73
94
|
if (config.pricingUrl !== undefined && (typeof config.pricingUrl !== 'string' || config.pricingUrl.length === 0)) {
|
|
@@ -81,18 +102,11 @@ export function validateConfig(config) {
|
|
|
81
102
|
&& (typeof config.pricingUrlOverseas !== 'string' || config.pricingUrlOverseas.length === 0)) {
|
|
82
103
|
throw new Error('TokenUsageConfig: "pricingUrlOverseas" must be a non-empty string');
|
|
83
104
|
}
|
|
84
|
-
|
|
85
|
-
|
|
105
|
+
const pricingRegion = readVolatile(config.pricingRegion);
|
|
106
|
+
if (pricingRegion !== undefined
|
|
107
|
+
&& pricingRegion !== 'domestic' && pricingRegion !== 'overseas') {
|
|
86
108
|
throw new Error('TokenUsageConfig: "pricingRegion" must be "domestic" or "overseas"');
|
|
87
109
|
}
|
|
88
|
-
if (config.startupDeferMs !== undefined
|
|
89
|
-
&& (!Number.isFinite(config.startupDeferMs) || config.startupDeferMs < 0)) {
|
|
90
|
-
throw new Error('TokenUsageConfig: "startupDeferMs" must be a non-negative number');
|
|
91
|
-
}
|
|
92
|
-
if (config.startupCapMs !== undefined
|
|
93
|
-
&& (!Number.isFinite(config.startupCapMs) || config.startupCapMs < 0)) {
|
|
94
|
-
throw new Error('TokenUsageConfig: "startupCapMs" must be a non-negative number');
|
|
95
|
-
}
|
|
96
110
|
if (config.recordCompaction !== undefined && typeof config.recordCompaction !== 'boolean') {
|
|
97
111
|
throw new Error('TokenUsageConfig: "recordCompaction" must be a boolean');
|
|
98
112
|
}
|
|
@@ -147,28 +161,16 @@ const PRICING_SYNC_COALESCE_MS = 250;
|
|
|
147
161
|
const PRICING_SYNC_STARTUP_GRACE_MS = 5_000;
|
|
148
162
|
/** The settings namespace this plugin serves; its browser card spells the same string. */
|
|
149
163
|
export const TOKEN_USAGE_NS = 'token-usage';
|
|
150
|
-
/**
|
|
151
|
-
|
|
152
|
-
path: z.string(),
|
|
153
|
-
pricingRegion: z.union([z.const('domestic'), z.const('overseas')]),
|
|
154
|
-
});
|
|
155
|
-
/** The section-shaped view of a config: absent keys stay absent (`exactOptionalPropertyTypes`). */
|
|
164
|
+
/** The section-shaped view of a config: absent keys stay absent
|
|
165
|
+
* (`exactOptionalPropertyTypes`); volatile fields resolve at call time. */
|
|
156
166
|
function sectionOf(config) {
|
|
167
|
+
const path = readVolatile(config.path);
|
|
168
|
+
const pricingRegion = readVolatile(config.pricingRegion);
|
|
157
169
|
return {
|
|
158
|
-
...(
|
|
159
|
-
...(
|
|
170
|
+
...(path === undefined ? {} : { path }),
|
|
171
|
+
...(pricingRegion === undefined ? {} : { pricingRegion }),
|
|
160
172
|
};
|
|
161
173
|
}
|
|
162
|
-
/**
|
|
163
|
-
* Reject an empty stored path: the schema cannot (an empty string is a valid
|
|
164
|
-
* string), and it would silently disable the explicit-directory intent.
|
|
165
|
-
* @param value - the resolved section, schema-valid by construction.
|
|
166
|
-
*/
|
|
167
|
-
export function validateSection(value) {
|
|
168
|
-
if (value.path !== undefined && value.path.length === 0) {
|
|
169
|
-
throw new Error('token-usage: "path" must be a non-empty string');
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
174
|
/**
|
|
173
175
|
* Count the sessions still mid-conversation: a session whose event log ends
|
|
174
176
|
* inside an open turn (its last turn event is a `turn/start` with no closing
|
|
@@ -215,33 +217,19 @@ export function directoryGuard(proposed, guard) {
|
|
|
215
217
|
return { blocked: false, interactingSessions: guard.interactingSessions };
|
|
216
218
|
return { blocked: guard.interactingSessions > 0, interactingSessions: guard.interactingSessions };
|
|
217
219
|
}
|
|
218
|
-
/**
|
|
219
|
-
* Vet one section write before it persists: a directory change is refused
|
|
220
|
-
* outright while any session is mid-conversation — their events append to the
|
|
221
|
-
* source mid-copy, so a stored move could not run safely, and a silently stored
|
|
222
|
-
* move that never runs is worse than a refused save. Region-only edits and
|
|
223
|
-
* no-op path writes pass freely; the first start (no running directory yet)
|
|
224
|
-
* adopts the stored path without migration, so it passes too.
|
|
225
|
-
* @param value - the resolved section, schema-valid by construction.
|
|
226
|
-
* @param guard - the running directory and mid-conversation session count.
|
|
227
|
-
*/
|
|
228
|
-
export function validateSectionChange(value, guard) {
|
|
229
|
-
validateSection(value);
|
|
230
|
-
const verdict = directoryGuard(value.path, guard);
|
|
231
|
-
if (verdict.blocked) {
|
|
232
|
-
throw new Error(`cannot change the data directory while ${String(verdict.interactingSessions)} session(s) are mid-conversation; let them finish and save again`);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
220
|
export function apply(ctx, config = {}) {
|
|
236
221
|
validateConfig(config);
|
|
237
222
|
// The plugin's named logger: every diagnostic joins the framework's log
|
|
238
223
|
// pipeline instead of raw console output (the Cordis logging service).
|
|
239
224
|
const logger = ctx.logger('token-usage');
|
|
240
|
-
// The
|
|
241
|
-
//
|
|
242
|
-
//
|
|
243
|
-
|
|
244
|
-
|
|
225
|
+
// The live entry config: volatile commits swap the snapshot inside
|
|
226
|
+
// ctx.fiber.config in place (no reload), so every read goes through the
|
|
227
|
+
// fiber first and falls back to the apply argument only off-fiber.
|
|
228
|
+
const currentConfig = () => ctx.fiber?.config ?? config;
|
|
229
|
+
// The section source, as a thunk: reads see the current resolution at
|
|
230
|
+
// call time, so both the pricing region and the data directory follow a
|
|
231
|
+
// stored edit the moment the loader commits it.
|
|
232
|
+
const sectionSource = () => sectionOf(currentConfig());
|
|
245
233
|
// The directory, log, and metadata index currently in force. Registrations
|
|
246
234
|
// below read them per event and per request, so a settings-driven move
|
|
247
235
|
// swaps the running directory without re-registering anything.
|
|
@@ -502,10 +490,30 @@ export function apply(ctx, config = {}) {
|
|
|
502
490
|
});
|
|
503
491
|
ctx.inject(['settings'], (settingsCtx) => {
|
|
504
492
|
settingsCtx.effect(() => {
|
|
505
|
-
|
|
493
|
+
// 0.1.7 SettingsForms serves every live namespace value through
|
|
494
|
+
// describe() (the per-namespace get is gone); the credentials chain
|
|
495
|
+
// reads provider sections (e.g. an apiKeyEnv placement) through it.
|
|
496
|
+
quotaReadSettings = (ns) => settingsCtx.settings.describe().find(entry => entry.ns === ns)?.value;
|
|
506
497
|
return () => { quotaReadSettings = () => undefined; };
|
|
507
498
|
}, 'token-usage: quota settings reader');
|
|
508
499
|
});
|
|
500
|
+
// The host's default model selection: what a brand-new, never-requesting
|
|
501
|
+
// session would dispatch to. Optional seam — a deployment without the
|
|
502
|
+
// service leaves the quota button hidden until the session's first
|
|
503
|
+
// request names its provider.
|
|
504
|
+
let defaultProviderSelection;
|
|
505
|
+
ctx.inject(['agentDefaultModel'], (agentCtx) => {
|
|
506
|
+
agentCtx.effect(() => {
|
|
507
|
+
const service = agentCtx.agentDefaultModel;
|
|
508
|
+
if (service !== undefined && typeof service.currentSelection === 'function') {
|
|
509
|
+
defaultProviderSelection = () => {
|
|
510
|
+
const provider = service.currentSelection?.().provider;
|
|
511
|
+
return typeof provider === 'string' && provider !== '' ? provider : undefined;
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
return () => { defaultProviderSelection = undefined; };
|
|
515
|
+
}, 'token-usage: default model selection seam');
|
|
516
|
+
});
|
|
509
517
|
ctx.inject(['credentials'], (credentialsCtx) => {
|
|
510
518
|
credentialsCtx.effect(() => {
|
|
511
519
|
quotaResolveCredential = async (ref) => (await credentialsCtx.credentials.resolve(credentialRef(ref)))?.value;
|
|
@@ -543,15 +551,7 @@ export function apply(ctx, config = {}) {
|
|
|
543
551
|
resolveProvider: sessionId => resolveCurrentProvider({
|
|
544
552
|
tracker: quotaTracker,
|
|
545
553
|
...(sessionId !== undefined ? { sessionId } : {}),
|
|
546
|
-
defaultProvider: () =>
|
|
547
|
-
// A brand-new, never-requesting session would use the host's
|
|
548
|
-
// default model selection; absent or unregistered → undefined.
|
|
549
|
-
const section = quotaReadSettings('agent-default-model');
|
|
550
|
-
if (typeof section !== 'object' || section === null)
|
|
551
|
-
return undefined;
|
|
552
|
-
const provider = section.provider;
|
|
553
|
-
return typeof provider === 'string' && provider !== '' ? provider : undefined;
|
|
554
|
-
},
|
|
554
|
+
defaultProvider: () => defaultProviderSelection?.(),
|
|
555
555
|
}),
|
|
556
556
|
resolveCredentials: async (provider) => withCatalogBaseUrl(provider, await resolveQuotaCredentials({
|
|
557
557
|
provider,
|
|
@@ -591,6 +591,7 @@ export function apply(ctx, config = {}) {
|
|
|
591
591
|
// events the sync walk does (request/context route changes, then
|
|
592
592
|
// assistant/message confirmations). Bounded by the session count.
|
|
593
593
|
const lastModel = new Map();
|
|
594
|
+
const activeSteps = new Map();
|
|
594
595
|
// Header facts are immutable, so one upsert per session is enough even
|
|
595
596
|
// though events keep arriving; the index store dedupes the write anyway.
|
|
596
597
|
const headerSeen = new Set();
|
|
@@ -619,10 +620,43 @@ export function apply(ctx, config = {}) {
|
|
|
619
620
|
if (Object.keys(patch).length > 0)
|
|
620
621
|
void meta.upsert(session.id, patch).catch(error => logger.warn('[token-usage] session header upsert failed:', error));
|
|
621
622
|
}
|
|
623
|
+
if (event.type === 'step/start') {
|
|
624
|
+
activeSteps.set(session.id, {
|
|
625
|
+
turn: event.data.turn,
|
|
626
|
+
step: event.data.step,
|
|
627
|
+
startTime: event.time,
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
let timing;
|
|
631
|
+
if (event.type === 'assistant/message') {
|
|
632
|
+
const currentStep = activeSteps.get(session.id);
|
|
633
|
+
if (currentStep !== undefined
|
|
634
|
+
&& currentStep.turn === event.data.turn
|
|
635
|
+
&& currentStep.step === event.data.step) {
|
|
636
|
+
const latencyMs = Math.max(0, event.time - currentStep.startTime);
|
|
637
|
+
// dsh 0.1.7 embeds the timed model stream inside assistant/message
|
|
638
|
+
// (the assistant/chunk event is gone); the first token delta's
|
|
639
|
+
// timestamp is read from those compact records.
|
|
640
|
+
const firstTokenTime = 'stream' in event.data && event.data.stream
|
|
641
|
+
? extractFirstTokenTimeFromStream(event.data.stream)
|
|
642
|
+
: undefined;
|
|
643
|
+
const firstTokenLatencyMs = firstTokenTime !== undefined
|
|
644
|
+
? Math.max(0, firstTokenTime - currentStep.startTime)
|
|
645
|
+
: undefined;
|
|
646
|
+
timing = {
|
|
647
|
+
latencyMs,
|
|
648
|
+
...(firstTokenLatencyMs !== undefined ? { firstTokenLatencyMs } : {}),
|
|
649
|
+
};
|
|
650
|
+
activeSteps.delete(session.id);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
else if (event.type === 'step/end' || event.type === 'turn/end') {
|
|
654
|
+
activeSteps.delete(session.id);
|
|
655
|
+
}
|
|
622
656
|
const revealed = modelOfEvent(event);
|
|
623
657
|
if (revealed !== undefined)
|
|
624
658
|
lastModel.set(session.id, revealed);
|
|
625
|
-
const record = recordOfEvent(event, session.id, lastModel.get(session.id) ?? '', recordCompaction);
|
|
659
|
+
const record = recordOfEvent(event, session.id, lastModel.get(session.id) ?? '', recordCompaction, timing);
|
|
626
660
|
if (record === null)
|
|
627
661
|
return;
|
|
628
662
|
// Fire-and-forget: the log serializes appends and reports its own failures.
|
|
@@ -643,7 +677,7 @@ export function apply(ctx, config = {}) {
|
|
|
643
677
|
logger.warn(`[token-usage] session ${id} unreadable, skipped:`, error instanceof Error ? error.message : String(error));
|
|
644
678
|
} }, dir);
|
|
645
679
|
})
|
|
646
|
-
.then((result) => {
|
|
680
|
+
.then(async (result) => {
|
|
647
681
|
if (result !== null) {
|
|
648
682
|
logger.info(`[token-usage] first-run sync: ${result.added} added, ${result.skipped} skipped, ${String(result.removed)} removed, ${String(result.failedSessions)} failed sessions`);
|
|
649
683
|
// Appended rows (compactions backfilled by an upgrade, or requests
|
|
@@ -654,6 +688,15 @@ export function apply(ctx, config = {}) {
|
|
|
654
688
|
if (result.added > 0 || result.removed > 0)
|
|
655
689
|
invalidateDerivedState(dir);
|
|
656
690
|
}
|
|
691
|
+
const state = await readSyncState(dir, logger);
|
|
692
|
+
if (state !== null && state.timingSyncedAt === undefined && ctx.sessionPersistence !== undefined) {
|
|
693
|
+
const patched = await log.backfillTiming(ctx.sessionPersistence);
|
|
694
|
+
if (patched > 0) {
|
|
695
|
+
logger.info(`[token-usage] backfilled timing figures for ${String(patched)} historical records`);
|
|
696
|
+
invalidateDerivedState(dir);
|
|
697
|
+
}
|
|
698
|
+
await markTimingSynced(dir);
|
|
699
|
+
}
|
|
657
700
|
return warmRecordCache(dir, undefined, logger);
|
|
658
701
|
})
|
|
659
702
|
.catch((error) => {
|
|
@@ -697,58 +740,22 @@ export function apply(ctx, config = {}) {
|
|
|
697
740
|
});
|
|
698
741
|
logger.info(`[token-usage] plugin loaded (data dir: ${dir})`);
|
|
699
742
|
};
|
|
700
|
-
|
|
701
|
-
//
|
|
702
|
-
//
|
|
703
|
-
//
|
|
704
|
-
//
|
|
705
|
-
// service the long cap opens the default directory instead.
|
|
706
|
-
// dsh 0.1.2 folded installSettingsSection into the settings service
|
|
707
|
-
// itself (installSection takes the consumer context as its first
|
|
708
|
-
// argument); the wiring semantics — inject-time registration, entry
|
|
709
|
-
// fallback when the provider detaches, onChange after setSource — are the
|
|
710
|
-
// ones the old helper performed around register().
|
|
743
|
+
const startFromSource = () => { start(); requestSync(); };
|
|
744
|
+
// dsh 0.1.7 settings wiring. The volatile Config fields above are what the
|
|
745
|
+
// settings service projects into the `token-usage` form; `auto: false`
|
|
746
|
+
// declares that this plugin renders its own card (the browser half's
|
|
747
|
+
// `plugins.bundle.config` entry) rather than a schema-generated page.
|
|
711
748
|
ctx.inject(['settings'], (settingsCtx) => {
|
|
712
|
-
settingsCtx.settings
|
|
713
|
-
validate: (value) => validateSectionChange(value, {
|
|
714
|
-
runningDir: current?.dir,
|
|
715
|
-
interactingSessions: countInteractingSessions(ctx.sessions.list().map(session => session.snapshotEvents())),
|
|
716
|
-
}),
|
|
717
|
-
setSource: (source) => { sectionSource = source; },
|
|
718
|
-
onChange: () => { start(); requestSync(); },
|
|
719
|
-
});
|
|
749
|
+
settingsCtx.effect(() => settingsCtx.settings?.configure?.({ auto: false }, ctx.fiber), 'token-usage: settings presentation policy');
|
|
720
750
|
});
|
|
721
|
-
// The
|
|
722
|
-
//
|
|
723
|
-
//
|
|
724
|
-
//
|
|
725
|
-
//
|
|
726
|
-
//
|
|
727
|
-
//
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
// window). So the short-deferred fallback only fires for an explicit
|
|
731
|
-
// composition `path` — an explicit placement is intent, and a differing
|
|
732
|
-
// stored path later relocates as a genuine edit; an entry without one waits
|
|
733
|
-
// for the settings inject (whose onChange start()s on the resolved
|
|
734
|
-
// directory) and only the long cap below starts the default directory when
|
|
735
|
-
// no settings service ever mounts. The idempotent start makes every
|
|
736
|
-
// overlapping call a no-op.
|
|
737
|
-
const startFromSource = () => { start(); requestSync(); };
|
|
738
|
-
const startupDeferMs = config.startupDeferMs ?? 500;
|
|
739
|
-
const startup = config.path === undefined
|
|
740
|
-
? undefined
|
|
741
|
-
: setTimeout(startFromSource, startupDeferMs);
|
|
742
|
-
const startupCapMs = config.startupCapMs ?? 30_000;
|
|
743
|
-
const settingsless = setTimeout(() => {
|
|
744
|
-
if (current !== undefined)
|
|
745
|
-
return;
|
|
746
|
-
startFromSource();
|
|
747
|
-
}, startupCapMs);
|
|
748
|
-
ctx.effect(() => () => {
|
|
749
|
-
if (startup !== undefined)
|
|
750
|
-
clearTimeout(startup);
|
|
751
|
-
clearTimeout(settingsless);
|
|
752
|
-
}, 'token-usage: deferred startup');
|
|
751
|
+
// The loader resolves the composition entry's config (composition layer
|
|
752
|
+
// under the profile patch) before apply runs, so the first start reads the
|
|
753
|
+
// final values directly — no deferred settings-attach wait. Saves from the
|
|
754
|
+
// browser card commit volatile fields in place without a reload;
|
|
755
|
+
// `loader/volatile-update` (dispatched to this fiber only) re-runs the
|
|
756
|
+
// section-driven start: a directory change relocates, a region switch
|
|
757
|
+
// re-syncs the pricing mirror.
|
|
758
|
+
startFromSource();
|
|
759
|
+
ctx.on('loader/volatile-update', () => { start(); requestSync(); });
|
|
753
760
|
}
|
|
754
761
|
//# sourceMappingURL=index.js.map
|