@laoyuehanni/dsh-token-usage 0.4.2 → 0.4.4-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +8 -7
  2. package/README.zh.md +8 -7
  3. package/lib/client/SessionTable.d.ts.map +1 -1
  4. package/lib/client/SessionTable.js +10 -4
  5. package/lib/client/SessionTable.js.map +1 -1
  6. package/lib/client/TokenUsageCard.d.ts +7 -2
  7. package/lib/client/TokenUsageCard.d.ts.map +1 -1
  8. package/lib/client/TokenUsageCard.js +15 -5
  9. package/lib/client/TokenUsageCard.js.map +1 -1
  10. package/lib/client/TokenUsageSection.d.ts +9 -5
  11. package/lib/client/TokenUsageSection.d.ts.map +1 -1
  12. package/lib/client/TokenUsageSection.js +44 -16
  13. package/lib/client/TokenUsageSection.js.map +1 -1
  14. package/lib/client/TrendChart.d.ts +1 -1
  15. package/lib/client/TrendChart.d.ts.map +1 -1
  16. package/lib/client/TrendChart.js +39 -15
  17. package/lib/client/TrendChart.js.map +1 -1
  18. package/lib/client/UsageView.js +2 -2
  19. package/lib/client/UsageView.js.map +1 -1
  20. package/lib/client/card-form.d.ts +33 -4
  21. package/lib/client/card-form.d.ts.map +1 -1
  22. package/lib/client/card-form.js +20 -8
  23. package/lib/client/card-form.js.map +1 -1
  24. package/lib/client/format.d.ts.map +1 -1
  25. package/lib/client/format.js +12 -4
  26. package/lib/client/format.js.map +1 -1
  27. package/lib/client/index.d.ts +18 -3
  28. package/lib/client/index.d.ts.map +1 -1
  29. package/lib/client/index.js +137 -25
  30. package/lib/client/index.js.map +1 -1
  31. package/lib/client/locales.d.ts +11 -2
  32. package/lib/client/locales.d.ts.map +1 -1
  33. package/lib/client/locales.js +22 -4
  34. package/lib/client/locales.js.map +1 -1
  35. package/lib/client/trend-chart/index.d.ts +1 -1
  36. package/lib/client/trend-chart/index.d.ts.map +1 -1
  37. package/lib/client/trend-chart/index.js +1 -1
  38. package/lib/client/trend-chart/index.js.map +1 -1
  39. package/lib/client/trend-chart/path.d.ts +46 -0
  40. package/lib/client/trend-chart/path.d.ts.map +1 -1
  41. package/lib/client/trend-chart/path.js +140 -0
  42. package/lib/client/trend-chart/path.js.map +1 -1
  43. package/lib/client/use-color-scheme.d.ts +6 -0
  44. package/lib/client/use-color-scheme.d.ts.map +1 -1
  45. package/lib/client/use-color-scheme.js +53 -1
  46. package/lib/client/use-color-scheme.js.map +1 -1
  47. package/lib/client.js +553 -115
  48. package/lib/client.js.map +1 -1
  49. package/lib/index.d.ts +30 -52
  50. package/lib/index.d.ts.map +1 -1
  51. package/lib/index.js +152 -143
  52. package/lib/index.js.map +1 -1
  53. package/lib/pricing.d.ts +36 -0
  54. package/lib/pricing.d.ts.map +1 -1
  55. package/lib/pricing.js +45 -4
  56. package/lib/pricing.js.map +1 -1
  57. package/lib/stats-route.d.ts.map +1 -1
  58. package/lib/stats-route.js +9 -7
  59. package/lib/stats-route.js.map +1 -1
  60. package/lib/stats.d.ts +23 -9
  61. package/lib/stats.d.ts.map +1 -1
  62. package/lib/stats.js +56 -22
  63. package/lib/stats.js.map +1 -1
  64. package/lib/sync-state.d.ts +17 -6
  65. package/lib/sync-state.d.ts.map +1 -1
  66. package/lib/sync-state.js +28 -6
  67. package/lib/sync-state.js.map +1 -1
  68. package/lib/sync.d.ts +102 -16
  69. package/lib/sync.d.ts.map +1 -1
  70. package/lib/sync.js +121 -13
  71. package/lib/sync.js.map +1 -1
  72. package/lib/usage-log.d.ts +49 -0
  73. package/lib/usage-log.d.ts.map +1 -1
  74. package/lib/usage-log.js +239 -1
  75. package/lib/usage-log.js.map +1 -1
  76. package/lib/usage-record.d.ts +20 -2
  77. package/lib/usage-record.d.ts.map +1 -1
  78. package/lib/usage-record.js +74 -3
  79. package/lib/usage-record.js.map +1 -1
  80. package/lib/wire.d.ts +3 -1
  81. package/lib/wire.d.ts.map +1 -1
  82. package/lib/wire.js +1 -1
  83. 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 settings namespace `token-usage` registers through the settings
9
- * service's `installSection` (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.
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). Keys stay optional — absent keys stay absent, because
66
- * the plugin's own resolution (`validateConfig` + section-based defaults)
67
- * is where defaults and unknown-key rejection live. Schemastery's object
68
- * keeps unknown keys in non-strict mode, so `validateConfig` remains the
69
- * loud rejection point for misspelled keys.
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<Config>;
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
@@ -1 +1 @@
1
- {"version":3,"file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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 settings namespace `token-usage` registers through the settings
9
- * service's `installSection` (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.
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). Keys stay optional — absent keys stay absent, because
41
- * the plugin's own resolution (`validateConfig` + section-based defaults)
42
- * is where defaults and unknown-key rejection live. Schemastery's object
43
- * keeps unknown keys in non-strict mode, so `validateConfig` remains the
44
- * loud rejection point for misspelled keys.
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' && key !== 'startupDeferMs'
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
- if (config.path !== undefined && (typeof config.path !== 'string' || config.path.length === 0)) {
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
- if (config.pricingRegion !== undefined
85
- && config.pricingRegion !== 'domestic' && config.pricingRegion !== 'overseas') {
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
- /** Schema resolving the `token-usage` settings section. */
151
- export const sectionSchema = z.object({
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
- ...(config.path === undefined ? {} : { path: config.path }),
159
- ...(config.pricingRegion === undefined ? {} : { pricingRegion: config.pricingRegion }),
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 section source: the composition entry until a settings service
241
- // attaches, then `setSource` repoints it at the resolved settings scope.
242
- // A thunk, not a snapshot — reads see the current resolution at call time,
243
- // so both the pricing region and the data directory follow a stored edit.
244
- let sectionSource = () => sectionOf(config);
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.
@@ -400,7 +388,7 @@ export function apply(ctx, config = {}) {
400
388
  /**
401
389
  * Kick off one full scan over every persisted session log and stream the
402
390
  * live counts into {@link fullSyncStatus}. The scan is the same shape as
403
- * the one-shot startup sync (list + inspect + UsageLog dedupe) — there is
391
+ * the one-shot startup sync (list + per-session read + UsageLog dedupe) — there is
404
392
  * no watermark shortcut here, so the user gets a guarantee that every
405
393
  * persisted request row the log does not yet hold will land. The run is
406
394
  * fire-and-forget: a second trigger while one is in flight returns
@@ -414,7 +402,7 @@ export function apply(ctx, config = {}) {
414
402
  if (target === undefined)
415
403
  return { started: false, reason: 'already-running' };
416
404
  fullSyncRunning = true;
417
- fullSyncStatus = { status: 'running', processed: 0, total: 0, added: 0, skipped: 0, failedSessions: 0 };
405
+ fullSyncStatus = { status: 'running', processed: 0, total: 0, added: 0, skipped: 0, removed: 0, failedSessions: 0 };
418
406
  void syncHistory({ persistence: ctx.sessionPersistence, log: target.log, meta: target.meta, recordCompaction,
419
407
  onSessionFailure: (id, error) => {
420
408
  logger.warn(`[token-usage] session ${id} unreadable, skipped:`, error instanceof Error ? error.message : String(error));
@@ -430,25 +418,26 @@ export function apply(ctx, config = {}) {
430
418
  // (the last tick carries the in-loop counters; this stamp aligns
431
419
  // them with the result in case of any trailing read).
432
420
  const last = fullSyncStatus.status === 'running' ? fullSyncStatus
433
- : { processed: 0, total: 0, added: 0, skipped: 0, failedSessions: 0 };
421
+ : { processed: 0, total: 0, added: 0, skipped: 0, removed: 0, failedSessions: 0 };
434
422
  fullSyncStatus = {
435
423
  status: 'done',
436
424
  processed: last.processed,
437
425
  total: last.total,
438
426
  added: result.added,
439
427
  skipped: result.skipped,
428
+ removed: result.removed,
440
429
  failedSessions: result.failedSessions,
441
430
  };
442
431
  // A manual scan usually backfills compactions this version just
443
432
  // learned to record (or rows a crash dropped): drop the derived
444
433
  // stats state so the next read aggregates over the appended rows.
445
434
  const moved = await target.log.refileByEventDay();
446
- if (result.added > 0 || moved > 0)
435
+ if (result.added > 0 || result.removed > 0 || moved > 0)
447
436
  invalidateDerivedState(target.dir);
448
437
  if (moved > 0) {
449
438
  logger.info(`[token-usage] refiled ${String(moved)} rows onto event-day files`);
450
439
  }
451
- logger.info(`[token-usage] full sync done: ${String(result.added)} added, ${String(result.skipped)} skipped, ${String(result.failedSessions)} failed sessions`);
440
+ logger.info(`[token-usage] full sync done: ${String(result.added)} added, ${String(result.skipped)} skipped, ${String(result.removed)} removed, ${String(result.failedSessions)} failed sessions`);
452
441
  })
453
442
  .catch((error) => {
454
443
  const message = error instanceof Error ? error.message : String(error);
@@ -501,10 +490,30 @@ export function apply(ctx, config = {}) {
501
490
  });
502
491
  ctx.inject(['settings'], (settingsCtx) => {
503
492
  settingsCtx.effect(() => {
504
- quotaReadSettings = (ns) => settingsCtx.settings.get(ns);
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;
505
497
  return () => { quotaReadSettings = () => undefined; };
506
498
  }, 'token-usage: quota settings reader');
507
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
+ });
508
517
  ctx.inject(['credentials'], (credentialsCtx) => {
509
518
  credentialsCtx.effect(() => {
510
519
  quotaResolveCredential = async (ref) => (await credentialsCtx.credentials.resolve(credentialRef(ref)))?.value;
@@ -542,15 +551,7 @@ export function apply(ctx, config = {}) {
542
551
  resolveProvider: sessionId => resolveCurrentProvider({
543
552
  tracker: quotaTracker,
544
553
  ...(sessionId !== undefined ? { sessionId } : {}),
545
- defaultProvider: () => {
546
- // A brand-new, never-requesting session would use the host's
547
- // default model selection; absent or unregistered → undefined.
548
- const section = quotaReadSettings('agent-default-model');
549
- if (typeof section !== 'object' || section === null)
550
- return undefined;
551
- const provider = section.provider;
552
- return typeof provider === 'string' && provider !== '' ? provider : undefined;
553
- },
554
+ defaultProvider: () => defaultProviderSelection?.(),
554
555
  }),
555
556
  resolveCredentials: async (provider) => withCatalogBaseUrl(provider, await resolveQuotaCredentials({
556
557
  provider,
@@ -590,6 +591,7 @@ export function apply(ctx, config = {}) {
590
591
  // events the sync walk does (request/context route changes, then
591
592
  // assistant/message confirmations). Bounded by the session count.
592
593
  const lastModel = new Map();
594
+ const activeSteps = new Map();
593
595
  // Header facts are immutable, so one upsert per session is enough even
594
596
  // though events keep arriving; the index store dedupes the write anyway.
595
597
  const headerSeen = new Set();
@@ -618,10 +620,43 @@ export function apply(ctx, config = {}) {
618
620
  if (Object.keys(patch).length > 0)
619
621
  void meta.upsert(session.id, patch).catch(error => logger.warn('[token-usage] session header upsert failed:', error));
620
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
+ }
621
656
  const revealed = modelOfEvent(event);
622
657
  if (revealed !== undefined)
623
658
  lastModel.set(session.id, revealed);
624
- const record = recordOfEvent(event, session.id, lastModel.get(session.id) ?? '', recordCompaction);
659
+ const record = recordOfEvent(event, session.id, lastModel.get(session.id) ?? '', recordCompaction, timing);
625
660
  if (record === null)
626
661
  return;
627
662
  // Fire-and-forget: the log serializes appends and reports its own failures.
@@ -642,16 +677,26 @@ export function apply(ctx, config = {}) {
642
677
  logger.warn(`[token-usage] session ${id} unreadable, skipped:`, error instanceof Error ? error.message : String(error));
643
678
  } }, dir);
644
679
  })
645
- .then((result) => {
680
+ .then(async (result) => {
646
681
  if (result !== null) {
647
- logger.info(`[token-usage] first-run sync: ${result.added} added, ${result.skipped} skipped, ${String(result.failedSessions)} failed sessions`);
682
+ logger.info(`[token-usage] first-run sync: ${result.added} added, ${result.skipped} skipped, ${String(result.removed)} removed, ${String(result.failedSessions)} failed sessions`);
648
683
  // Appended rows (compactions backfilled by an upgrade, or requests
649
- // a previous run missed) invalidate the derived stats state before
650
- // the cache re-warms over the new contents — including writes into
651
- // frozen day files the rollup may already have absorbed.
652
- if (result.added > 0)
684
+ // a previous run missed) and rows the reconcile pass dropped both
685
+ // invalidate the derived stats state before the cache re-warms over
686
+ // the new contents — including writes into frozen day files the
687
+ // rollup may already have absorbed.
688
+ if (result.added > 0 || result.removed > 0)
653
689
  invalidateDerivedState(dir);
654
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
+ }
655
700
  return warmRecordCache(dir, undefined, logger);
656
701
  })
657
702
  .catch((error) => {
@@ -695,58 +740,22 @@ export function apply(ctx, config = {}) {
695
740
  });
696
741
  logger.info(`[token-usage] plugin loaded (data dir: ${dir})`);
697
742
  };
698
- // A stored section acts on both concerns live: a directory change
699
- // relocates, a region switch (any effective-URL change) re-syncs the
700
- // pricing mirror. The first start intentionally defers (see the deferred
701
- // startup below): the settings inject's onChange fires after setSource and
702
- // opens the plugin on the settings-resolved directory; with no settings
703
- // service the long cap opens the default directory instead.
704
- // dsh 0.1.2 folded installSettingsSection into the settings service
705
- // itself (installSection takes the consumer context as its first
706
- // argument); the wiring semantics — inject-time registration, entry
707
- // fallback when the provider detaches, onChange after setSource — are the
708
- // 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.
709
748
  ctx.inject(['settings'], (settingsCtx) => {
710
- settingsCtx.settings.installSection(ctx, TOKEN_USAGE_NS, sectionSchema, sectionOf(config), {
711
- validate: (value) => validateSectionChange(value, {
712
- runningDir: current?.dir,
713
- interactingSessions: countInteractingSessions(ctx.sessions.list().map(session => session.snapshotEvents())),
714
- }),
715
- setSource: (source) => { sectionSource = source; },
716
- onChange: () => { start(); requestSync(); },
717
- });
749
+ settingsCtx.effect(() => settingsCtx.settings?.configure?.({ auto: false }, ctx.fiber), 'token-usage: settings presentation policy');
718
750
  });
719
- // The bootstrap defers the first start. The dsh Loader mounts every profile
720
- // entry CONCURRENTLY, so this plugin's apply() runs in no guaranteed order
721
- // relative to the base bundle's settings-file provider: probing the settings
722
- // service synchronously cannot tell "not attached yet" from "never
723
- // attached", and starting before the attach on an entry without an explicit
724
- // `path` opens the DEFAULT directory — the boot's own pricing sync and state
725
- // writes then land there and relocate away the moment settings attach,
726
- // churning every boot on hosts whose settings provider mounts late (the
727
- // 0.1.2 base bundle rows ahead of it push the attach past any sub-second
728
- // window). So the short-deferred fallback only fires for an explicit
729
- // composition `path` — an explicit placement is intent, and a differing
730
- // stored path later relocates as a genuine edit; an entry without one waits
731
- // for the settings inject (whose onChange start()s on the resolved
732
- // directory) and only the long cap below starts the default directory when
733
- // no settings service ever mounts. The idempotent start makes every
734
- // overlapping call a no-op.
735
- const startFromSource = () => { start(); requestSync(); };
736
- const startupDeferMs = config.startupDeferMs ?? 500;
737
- const startup = config.path === undefined
738
- ? undefined
739
- : setTimeout(startFromSource, startupDeferMs);
740
- const startupCapMs = config.startupCapMs ?? 30_000;
741
- const settingsless = setTimeout(() => {
742
- if (current !== undefined)
743
- return;
744
- startFromSource();
745
- }, startupCapMs);
746
- ctx.effect(() => () => {
747
- if (startup !== undefined)
748
- clearTimeout(startup);
749
- clearTimeout(settingsless);
750
- }, '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(); });
751
760
  }
752
761
  //# sourceMappingURL=index.js.map