@sonettogu14/dsh-te-cost 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @sonettogu14/dsh-te-cost
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cache-weighted token accounting for DeepSeek Harness. Raw totals mislead —
4
+ most input tokens are cache reads billed at a fraction of a fresh input
5
+ token — so this component folds the four provider buckets
6
+ (`uncachedInput`, `cacheRead`, `cacheWrite`, `output`) into one
7
+ comparable number: *equivalent fresh-input tokens*.
8
+
9
+ ```sh
10
+ dsh plugin --profile <profile> add @sonettogu14/dsh-te-cost
11
+ ```
12
+
13
+ - Observes `session/event` only; never touches the prompt or the tool surface.
14
+ - Keeps a per-repository ledger in
15
+ `$DSH_HOME/dsh-tokeneconomizer/repos/<key>/cost.json`.
16
+ - `/te-cost [session|repo]` prints the breakdown.
17
+
18
+ Part of [dsh-tokeneconomizer](https://github.com/SonettoGu14/dsh-tokeneconomizer) — install
19
+ `@sonettogu14/dsh-te` for all three components. Configuration, the unknown-model
20
+ fallback and the measurement caveat are documented there.
21
+ Licensed Apache-2.0.
@@ -0,0 +1,5 @@
1
+ # te-cost: inserts this component into a DSH profile roster.
2
+ # Install: dsh plugin --profile <name> add link:<repo>/packages/cost
3
+ - insert:
4
+ - id: te-cost
5
+ name: '@sonettogu14/dsh-te-cost'
package/lib/index.d.ts ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Cache-weighted equivalent-token accounting for DSH sessions.
3
+ *
4
+ * DSH already reports four disjoint provider buckets per request (`inputTokens`
5
+ * uncached, `cacheRead`, `cacheWrite`, `output`). Raw totals are misleading:
6
+ * a cached prompt re-read costs a fraction of a fresh token, so a session that
7
+ * looks 10× more expensive may be the cheaper one. This component converts the
8
+ * buckets into a single unit — *equivalent fresh-input tokens* — using the
9
+ * route's published price ratios, and accumulates it per session and per repo
10
+ * so pruning and fact injection can be judged on the currency that actually
11
+ * bills.
12
+ *
13
+ * The component never changes a prompt: it only observes `session/event`.
14
+ *
15
+ * @module @sonettogu14/dsh-te-cost
16
+ */
17
+ import type { Context } from '@deepseek-ai/cordis';
18
+ import { Service } from '@deepseek-ai/cordis';
19
+ import type { Session, SessionEvent } from '@deepseek-ai/dsh-session';
20
+ import z from '@deepseek-ai/schemastery';
21
+ import { bucketsTotal, type RepoIdentity, type TokenBuckets } from '@sonettogu14/dsh-te-core';
22
+ /** Cordis plugin name; it must match the `cordis.patch.yml` row id/name pair. */
23
+ export declare const name = "dsh-te-cost";
24
+ /** Cache-weighted equivalent-token accounting. */
25
+ export interface Config {
26
+ /** Mount this component. Off contributes nothing at all. */
27
+ enabled: boolean;
28
+ /** Persist per-repo totals under `<DSH_HOME>/dsh-tokeneconomizer/repos/`. */
29
+ persist: boolean;
30
+ }
31
+ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
32
+ enabled: z<boolean, boolean, "defined">;
33
+ persist: z<boolean, boolean, "defined">;
34
+ }>>, Schemastery.ObjectT<NoInfer<{
35
+ enabled: z<boolean, boolean, "defined">;
36
+ persist: z<boolean, boolean, "defined">;
37
+ }>>, "plain">;
38
+ /** What `<...>/repos/<dir>/cost.json` holds. */
39
+ interface RepoCostRecord {
40
+ version: 1;
41
+ key: string;
42
+ equivalent: number;
43
+ buckets: TokenBuckets;
44
+ sessions: number;
45
+ overhead: Record<string, number>;
46
+ updatedAt: string;
47
+ }
48
+ /** A read-only view of one session's accounting. */
49
+ export interface SessionCostSnapshot {
50
+ readonly provider?: string;
51
+ readonly model?: string;
52
+ readonly weightsSource: string;
53
+ readonly repoKey?: string;
54
+ readonly repoSource?: RepoIdentity['source'];
55
+ readonly messages: number;
56
+ readonly equivalent: number;
57
+ readonly overhead: number;
58
+ readonly buckets: TokenBuckets;
59
+ }
60
+ /**
61
+ * The `teCost` service: other components read and bill against one definition
62
+ * of cost instead of each inventing its own.
63
+ */
64
+ export declare class CostLedger extends Service {
65
+ static inject: string[];
66
+ private readonly states;
67
+ private readonly repoKeys;
68
+ private readonly repoCache;
69
+ /** Settles in flight, awaited by the `session/flush` durability checkpoint. */
70
+ private readonly pending;
71
+ /** One write at a time per repository, so concurrent settles cannot drop totals. */
72
+ private readonly settling;
73
+ private readonly config;
74
+ constructor(ctx: Context, config: Config);
75
+ [Service.init](): Promise<void>;
76
+ /** Fold one session event into its running totals. */
77
+ observe(session: Session, event: SessionEvent): void;
78
+ /**
79
+ * Bill this component's own model calls against the same account.
80
+ *
81
+ * A mechanism that spends tokens to save tokens has to say so, or the saving
82
+ * is fiction.
83
+ */
84
+ recordOverhead(session: Session, component: string, equivalent: number): void;
85
+ /** A read-only snapshot of one session. */
86
+ sessionSnapshot(session: Session): SessionCostSnapshot;
87
+ /** Repo totals, reading the persisted record on first use. */
88
+ repoSnapshot(session: Session): Promise<RepoCostRecord | undefined>;
89
+ /** Render the `/te-cost` report. */
90
+ report(session: Session, rawInput: string): string;
91
+ private stateOf;
92
+ private repoOf;
93
+ private recordPath;
94
+ /**
95
+ * Fold a finished session into its repo record.
96
+ *
97
+ * Called on `session/disposed`; exposed so a test (or a host shutdown path)
98
+ * can await the write instead of racing it.
99
+ */
100
+ settle(session: Session): Promise<void>;
101
+ /** One read-modify-write of a repository's cost record. */
102
+ private persist;
103
+ }
104
+ declare module '@deepseek-ai/cordis' {
105
+ interface Context {
106
+ /** Cache-weighted equivalent-token accounting; present while this component is mounted. */
107
+ teCost: CostLedger;
108
+ }
109
+ }
110
+ /**
111
+ * Mount the component on a DSH context.
112
+ *
113
+ * Disabled means absent: no service, no command, no listener.
114
+ */
115
+ export declare function apply(ctx: Context, config: Config): void;
116
+ export { bucketsTotal };
117
+ //# sourceMappingURL=index.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KG;IACG,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAmB7C,2DAA2D;YAC7C,OAAO;CAkBtB;AAkCD,OAAO,QAAQ,qBAAqB,CAAC;IACnC,UAAU,OAAO;QACf,2FAA2F;QAC3F,MAAM,EAAE,UAAU,CAAA;KACnB;CACF;AAED;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAGxD;AAED,OAAO,EAAE,YAAY,EAAE,CAAA"}
package/lib/index.js ADDED
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Cache-weighted equivalent-token accounting for DSH sessions.
3
+ *
4
+ * DSH already reports four disjoint provider buckets per request (`inputTokens`
5
+ * uncached, `cacheRead`, `cacheWrite`, `output`). Raw totals are misleading:
6
+ * a cached prompt re-read costs a fraction of a fresh token, so a session that
7
+ * looks 10× more expensive may be the cheaper one. This component converts the
8
+ * buckets into a single unit — *equivalent fresh-input tokens* — using the
9
+ * route's published price ratios, and accumulates it per session and per repo
10
+ * so pruning and fact injection can be judged on the currency that actually
11
+ * bills.
12
+ *
13
+ * The component never changes a prompt: it only observes `session/event`.
14
+ *
15
+ * @module @sonettogu14/dsh-te-cost
16
+ */
17
+ import { Service } from '@deepseek-ai/cordis';
18
+ import z from '@deepseek-ai/schemastery';
19
+ import { DEFAULT_WEIGHTS, EMPTY_ACCUMULATOR, ZERO_BUCKETS, addBuckets, bucketsTotal, foldUsage, formatTokens, readJson, repoKeyDirName, resolveRepoKey, sampleBuckets, stateRoot, weightsFor, writeJsonAtomic, } from '@sonettogu14/dsh-te-core';
20
+ import { join } from 'node:path';
21
+ /** Cordis plugin name; it must match the `cordis.patch.yml` row id/name pair. */
22
+ export const name = 'dsh-te-cost';
23
+ export const Config = z.object({
24
+ enabled: z.boolean().default(true),
25
+ persist: z.boolean().default(true),
26
+ });
27
+ /**
28
+ * The `teCost` service: other components read and bill against one definition
29
+ * of cost instead of each inventing its own.
30
+ */
31
+ export class CostLedger extends Service {
32
+ static inject = ['commands'];
33
+ states = new WeakMap();
34
+ repoKeys = new Map();
35
+ repoCache = new Map();
36
+ /** Settles in flight, awaited by the `session/flush` durability checkpoint. */
37
+ pending = new Map();
38
+ /** One write at a time per repository, so concurrent settles cannot drop totals. */
39
+ settling = new Map();
40
+ config;
41
+ constructor(ctx, config) {
42
+ super(ctx, 'teCost');
43
+ this.config = config;
44
+ }
45
+ async [Service.init]() {
46
+ const ctx = this.ctx;
47
+ ctx.on('session/event', (session, event) => {
48
+ this.observe(session, event);
49
+ });
50
+ ctx.on('session/disposed', (session) => {
51
+ // Sessions are torn down without awaiting listeners, so the write is
52
+ // handed to the awaited `session/flush` durability checkpoint instead of
53
+ // racing the process exit here.
54
+ this.pending.set(session.id, this.settle(session)
55
+ .catch((error) => {
56
+ this.ctx.logger('dsh-te-cost').warn('session totals not persisted: %s', String(error));
57
+ })
58
+ .finally(() => this.pending.delete(session.id)));
59
+ });
60
+ ctx.on('session/flush', async () => {
61
+ await Promise.all([...this.pending.values()]);
62
+ });
63
+ ctx.effect(() => ctx.commands.register({
64
+ name: 'te-cost',
65
+ description: 'Show cache-weighted equivalent-token spend for this session and repo',
66
+ input: { hint: 'session | repo' },
67
+ handler: async (invocation) => {
68
+ const session = invocation.agent.session;
69
+ // A resumed session has an empty in-memory cache; load the record so
70
+ // `/te-cost repo` answers from disk instead of claiming there is none.
71
+ await this.repoSnapshot(session);
72
+ return { kind: 'success', text: this.report(session, invocation.rawInput) };
73
+ },
74
+ }));
75
+ }
76
+ /** Fold one session event into its running totals. */
77
+ observe(session, event) {
78
+ try {
79
+ const state = this.stateOf(session);
80
+ if (event.type === 'request/header' || event.type === 'request/context') {
81
+ const route = readRoute(event);
82
+ if (route === undefined)
83
+ return;
84
+ state.provider = route.provider;
85
+ state.model = route.model;
86
+ const resolved = weightsFor(route.model ?? '');
87
+ state.weights = resolved.weights;
88
+ state.weightsSource = resolved.source;
89
+ return;
90
+ }
91
+ if (event.type === 'assistant/message') {
92
+ const usage = event.data.usage;
93
+ if (usage === undefined)
94
+ return;
95
+ state.acc = foldUsage(state.acc, {
96
+ inputTokens: usage.inputTokens ?? 0,
97
+ outputTokens: usage.outputTokens ?? 0,
98
+ cacheReadTokens: usage.cacheReadTokens,
99
+ cacheWriteTokens: usage.cacheWriteTokens,
100
+ }, state.weights);
101
+ }
102
+ }
103
+ catch {
104
+ // Accounting must never break the session loop.
105
+ }
106
+ }
107
+ /**
108
+ * Bill this component's own model calls against the same account.
109
+ *
110
+ * A mechanism that spends tokens to save tokens has to say so, or the saving
111
+ * is fiction.
112
+ */
113
+ recordOverhead(session, component, equivalent) {
114
+ if (!(equivalent > 0))
115
+ return;
116
+ const state = this.stateOf(session);
117
+ state.overhead[component] = (state.overhead[component] ?? 0) + equivalent;
118
+ }
119
+ /** A read-only snapshot of one session. */
120
+ sessionSnapshot(session) {
121
+ const state = this.stateOf(session);
122
+ const repo = this.repoOf(session);
123
+ return {
124
+ ...(state.provider === undefined ? {} : { provider: state.provider }),
125
+ ...(state.model === undefined ? {} : { model: state.model }),
126
+ weightsSource: state.weightsSource,
127
+ ...(repo === undefined ? {} : { repoKey: repo.key, repoSource: repo.source }),
128
+ messages: state.acc.messages,
129
+ equivalent: state.acc.equivalent,
130
+ overhead: overheadTotal(state.overhead),
131
+ buckets: state.acc.buckets,
132
+ };
133
+ }
134
+ /** Repo totals, reading the persisted record on first use. */
135
+ async repoSnapshot(session) {
136
+ const repo = this.repoOf(session);
137
+ if (repo === undefined)
138
+ return undefined;
139
+ const cached = this.repoCache.get(repo.key);
140
+ if (cached !== undefined)
141
+ return cached;
142
+ if (!this.config.persist)
143
+ return undefined;
144
+ const record = await readJson(this.recordPath(repo.key));
145
+ if (record !== undefined)
146
+ this.repoCache.set(repo.key, record);
147
+ return record;
148
+ }
149
+ /** Render the `/te-cost` report. */
150
+ report(session, rawInput) {
151
+ const scope = rawInput.trim().toLowerCase();
152
+ const wantRepo = scope === 'repo';
153
+ const wantSession = scope === '' || scope === 'session';
154
+ const state = this.stateOf(session);
155
+ const repo = this.repoOf(session);
156
+ const lines = ['Token economy — equivalent fresh-input tokens (cache-weighted).', ''];
157
+ if (wantSession) {
158
+ lines.push(`session ${session.id.slice(0, 8)}`);
159
+ lines.push(` model ${state.model ?? 'unknown'} · weights ${state.weightsSource}`);
160
+ lines.push(` requests ${state.acc.messages}`);
161
+ lines.push(` equivalent ${formatTokens(state.acc.equivalent)} eq`);
162
+ lines.push(` buckets uncached ${formatTokens(state.acc.buckets.uncachedInput)} · cache read ${formatTokens(state.acc.buckets.cacheRead)} · cache write ${formatTokens(state.acc.buckets.cacheWrite)} · output ${formatTokens(state.acc.buckets.output)}`);
163
+ const overhead = overheadTotal(state.overhead);
164
+ lines.push(` overhead ${formatTokens(overhead)} eq${describeOverhead(state.overhead)}`);
165
+ lines.push('');
166
+ }
167
+ if (wantRepo) {
168
+ if (repo === undefined) {
169
+ lines.push('repo unknown (session has no working directory yet)');
170
+ }
171
+ else {
172
+ const record = this.repoCache.get(repo.key);
173
+ if (record === undefined) {
174
+ lines.push(`repo ${repo.key}`);
175
+ lines.push(' no persisted totals yet (written when this session ends)');
176
+ }
177
+ else {
178
+ lines.push(`repo ${record.key}`);
179
+ lines.push(` equivalent ${formatTokens(record.equivalent)} eq over ${record.sessions} sessions`);
180
+ lines.push(` buckets uncached ${formatTokens(record.buckets.uncachedInput)} · cache read ${formatTokens(record.buckets.cacheRead)} · cache write ${formatTokens(record.buckets.cacheWrite)} · output ${formatTokens(record.buckets.output)}`);
181
+ lines.push(` overhead ${formatTokens(overheadTotal(record.overhead))} eq${describeOverhead(record.overhead)}`);
182
+ }
183
+ }
184
+ }
185
+ return lines.join('\n').trimEnd();
186
+ }
187
+ stateOf(session) {
188
+ const existing = this.states.get(session);
189
+ if (existing !== undefined)
190
+ return existing;
191
+ const created = {
192
+ acc: EMPTY_ACCUMULATOR,
193
+ overhead: {},
194
+ weights: DEFAULT_WEIGHTS,
195
+ weightsSource: 'default',
196
+ repoResolved: false,
197
+ };
198
+ this.states.set(session, created);
199
+ return created;
200
+ }
201
+ repoOf(session) {
202
+ const state = this.stateOf(session);
203
+ if (state.repoResolved)
204
+ return state.repo;
205
+ const cwd = session.header?.cwd;
206
+ if (cwd === undefined || cwd === '')
207
+ return undefined;
208
+ let identity = this.repoKeys.get(cwd);
209
+ if (identity === undefined) {
210
+ identity = resolveRepoKey(cwd);
211
+ this.repoKeys.set(cwd, identity);
212
+ }
213
+ state.repo = identity;
214
+ state.repoResolved = true;
215
+ return identity;
216
+ }
217
+ recordPath(repoKey) {
218
+ return join(stateRoot(), 'repos', repoKeyDirName(repoKey), 'cost.json');
219
+ }
220
+ /**
221
+ * Fold a finished session into its repo record.
222
+ *
223
+ * Called on `session/disposed`; exposed so a test (or a host shutdown path)
224
+ * can await the write instead of racing it.
225
+ */
226
+ async settle(session) {
227
+ const state = this.states.get(session);
228
+ if (state === undefined || !this.config.persist)
229
+ return;
230
+ const repo = this.repoOf(session);
231
+ if (repo === undefined)
232
+ return;
233
+ if (state.acc.equivalent === 0 && overheadTotal(state.overhead) === 0)
234
+ return;
235
+ // Two sessions can end at once (two tabs, desktop plus CLI). Serialize per
236
+ // repository so one read-modify-write cannot drop the other's totals.
237
+ const previous = this.settling.get(repo.key) ?? Promise.resolve();
238
+ const run = previous.then(() => this.persist(session, state, repo));
239
+ this.settling.set(repo.key, run.catch(() => {
240
+ // Kept so the next writer still waits for this one to settle.
241
+ }));
242
+ return run;
243
+ }
244
+ /** One read-modify-write of a repository's cost record. */
245
+ async persist(session, state, repo) {
246
+ try {
247
+ const previous = await this.repoSnapshot(session);
248
+ const next = {
249
+ version: 1,
250
+ key: repo.key,
251
+ equivalent: (previous?.equivalent ?? 0) + state.acc.equivalent,
252
+ buckets: addBuckets(previous?.buckets ?? ZERO_BUCKETS, state.acc.buckets),
253
+ sessions: (previous?.sessions ?? 0) + 1,
254
+ overhead: mergeOverhead(previous?.overhead ?? {}, state.overhead),
255
+ updatedAt: new Date().toISOString(),
256
+ };
257
+ await writeJsonAtomic(this.recordPath(repo.key), next);
258
+ this.repoCache.set(repo.key, next);
259
+ }
260
+ catch (error) {
261
+ this.ctx.logger('dsh-te-cost').warn('repo totals not persisted: %s', String(error));
262
+ }
263
+ }
264
+ }
265
+ function readRoute(event) {
266
+ const data = event.data;
267
+ const fromHeader = data.header?.config;
268
+ if (fromHeader?.provider !== undefined)
269
+ return { provider: fromHeader.provider, model: fromHeader.model };
270
+ if (data.provider !== undefined)
271
+ return { provider: data.provider, model: data.model };
272
+ return undefined;
273
+ }
274
+ function overheadTotal(overhead) {
275
+ let total = 0;
276
+ for (const value of Object.values(overhead))
277
+ total += value;
278
+ return total;
279
+ }
280
+ function mergeOverhead(left, right) {
281
+ const merged = { ...left };
282
+ for (const [key, value] of Object.entries(right))
283
+ merged[key] = (merged[key] ?? 0) + value;
284
+ return merged;
285
+ }
286
+ function describeOverhead(overhead) {
287
+ const parts = Object.entries(overhead)
288
+ .filter(([, value]) => value > 0)
289
+ .sort(([a], [b]) => a.localeCompare(b))
290
+ .map(([key, value]) => `${key} ${formatTokens(value)}`);
291
+ return parts.length === 0 ? '' : ` (${parts.join(' · ')})`;
292
+ }
293
+ /**
294
+ * Mount the component on a DSH context.
295
+ *
296
+ * Disabled means absent: no service, no command, no listener.
297
+ */
298
+ export function apply(ctx, config) {
299
+ if (!config.enabled)
300
+ return;
301
+ ctx.plugin(CostLedger, config);
302
+ }
303
+ export { bucketsTotal };
304
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAG7C,OAAO,CAAC,MAAM,0BAA0B,CAAA;AACxC,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,YA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MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,CAAA;IAC1F,OAAO,MAAM,CAAA;AACf,CAAC;AAED,SAAS,gBAAgB,CAAC,QAAgC;IACxD,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC;SACnC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,GAAG,CAAC,CAAC;SAChC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;SACtC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;IACzD,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAA;AAC5D,CAAC;AASD;;;;GAIG;AACH,MAAM,UAAU,KAAK,CAAC,GAAY,EAAE,MAAc;IAChD,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAM;IAC3B,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;AAChC,CAAC;AAED,OAAO,EAAE,YAAY,EAAE,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@sonettogu14/dsh-te-cost",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Cache-weighted equivalent-token accounting for DSH sessions.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "lib/index.js",
8
+ "types": "lib/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./lib/index.d.ts",
12
+ "import": "./lib/index.js"
13
+ },
14
+ "./cordis.patch.yml": "./cordis.patch.yml",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "lib",
19
+ "src",
20
+ "cordis.patch.yml"
21
+ ],
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/SonettoGu14/dsh-tokeneconomizer.git",
25
+ "directory": "packages/cost"
26
+ },
27
+ "engines": {
28
+ "node": ">=24.9.0",
29
+ "dsh": ">=0.2.2-rc.3 <0.3.0"
30
+ },
31
+ "dsh": {
32
+ "bundle": {
33
+ "patch": "./cordis.patch.yml"
34
+ }
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "@sonettogu14/dsh-te-core": "0.1.1",
41
+ "@deepseek-ai/schemastery": "^3.19.0"
42
+ },
43
+ "peerDependencies": {
44
+ "@deepseek-ai/dsh": ">=0.2.2-rc.3 <0.3.0",
45
+ "@deepseek-ai/cordis": "^4.1.0",
46
+ "@deepseek-ai/dsh-session": ">=0.2.2-rc.3 <0.3.0",
47
+ "@deepseek-ai/dsh-llm": ">=0.2.2-rc.3 <0.3.0",
48
+ "@deepseek-ai/dsh-commands": ">=0.2.2-rc.3 <0.3.0"
49
+ },
50
+ "devDependencies": {
51
+ "@deepseek-ai/cordis": "^4.1.0",
52
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3",
53
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
54
+ "@deepseek-ai/dsh-commands": "0.2.2-rc.3"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "@deepseek-ai/cordis": {
58
+ "optional": false
59
+ },
60
+ "@deepseek-ai/dsh-session": {
61
+ "optional": false
62
+ },
63
+ "@deepseek-ai/dsh-llm": {
64
+ "optional": false
65
+ },
66
+ "@deepseek-ai/dsh-commands": {
67
+ "optional": false
68
+ }
69
+ },
70
+ "homepage": "https://github.com/SonettoGu14/dsh-tokeneconomizer/tree/master/packages/cost#readme",
71
+ "bugs": {
72
+ "url": "https://github.com/SonettoGu14/dsh-tokeneconomizer/issues"
73
+ },
74
+ "scripts": {}
6
75
  }
package/src/index.ts ADDED
@@ -0,0 +1,411 @@
1
+ /**
2
+ * Cache-weighted equivalent-token accounting for DSH sessions.
3
+ *
4
+ * DSH already reports four disjoint provider buckets per request (`inputTokens`
5
+ * uncached, `cacheRead`, `cacheWrite`, `output`). Raw totals are misleading:
6
+ * a cached prompt re-read costs a fraction of a fresh token, so a session that
7
+ * looks 10× more expensive may be the cheaper one. This component converts the
8
+ * buckets into a single unit — *equivalent fresh-input tokens* — using the
9
+ * route's published price ratios, and accumulates it per session and per repo
10
+ * so pruning and fact injection can be judged on the currency that actually
11
+ * bills.
12
+ *
13
+ * The component never changes a prompt: it only observes `session/event`.
14
+ *
15
+ * @module @sonettogu14/dsh-te-cost
16
+ */
17
+
18
+ import type { Context } from '@deepseek-ai/cordis'
19
+ import { Service } from '@deepseek-ai/cordis'
20
+ import type {} from '@deepseek-ai/dsh-commands'
21
+ import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
22
+ import z from '@deepseek-ai/schemastery'
23
+ import {
24
+ DEFAULT_WEIGHTS,
25
+ EMPTY_ACCUMULATOR,
26
+ ZERO_BUCKETS,
27
+ addBuckets,
28
+ bucketsTotal,
29
+ foldUsage,
30
+ formatTokens,
31
+ readJson,
32
+ repoKeyDirName,
33
+ resolveRepoKey,
34
+ sampleBuckets,
35
+ stateRoot,
36
+ weightsFor,
37
+ writeJsonAtomic,
38
+ type CostAccumulator,
39
+ type RepoIdentity,
40
+ type TokenBuckets,
41
+ type TokenWeights,
42
+ } from '@sonettogu14/dsh-te-core'
43
+ import { join } from 'node:path'
44
+
45
+ /** Cordis plugin name; it must match the `cordis.patch.yml` row id/name pair. */
46
+ export const name = 'dsh-te-cost'
47
+
48
+ /** Cache-weighted equivalent-token accounting. */
49
+ export interface Config {
50
+ /** Mount this component. Off contributes nothing at all. */
51
+ enabled: boolean
52
+ /** Persist per-repo totals under `<DSH_HOME>/dsh-tokeneconomizer/repos/`. */
53
+ persist: boolean
54
+ }
55
+
56
+ export const Config = z.object({
57
+ enabled: z.boolean().default(true),
58
+ persist: z.boolean().default(true),
59
+ })
60
+
61
+ /** The usage fields one assistant message reports, as this component reads them. */
62
+ interface ReportedUsage {
63
+ readonly inputTokens?: number
64
+ readonly outputTokens?: number
65
+ readonly cacheReadTokens?: number
66
+ readonly cacheWriteTokens?: number
67
+ }
68
+
69
+ /** One session's running totals. */
70
+ interface SessionCost {
71
+ acc: CostAccumulator
72
+ overhead: Record<string, number>
73
+ provider?: string
74
+ model?: string
75
+ weights: TokenWeights
76
+ weightsSource: string
77
+ repo?: RepoIdentity
78
+ repoResolved: boolean
79
+ }
80
+
81
+ /** What `<...>/repos/<dir>/cost.json` holds. */
82
+ interface RepoCostRecord {
83
+ version: 1
84
+ key: string
85
+ equivalent: number
86
+ buckets: TokenBuckets
87
+ sessions: number
88
+ overhead: Record<string, number>
89
+ updatedAt: string
90
+ }
91
+
92
+ /** A read-only view of one session's accounting. */
93
+ export interface SessionCostSnapshot {
94
+ readonly provider?: string
95
+ readonly model?: string
96
+ readonly weightsSource: string
97
+ readonly repoKey?: string
98
+ readonly repoSource?: RepoIdentity['source']
99
+ readonly messages: number
100
+ readonly equivalent: number
101
+ readonly overhead: number
102
+ readonly buckets: TokenBuckets
103
+ }
104
+
105
+ /**
106
+ * The `teCost` service: other components read and bill against one definition
107
+ * of cost instead of each inventing its own.
108
+ */
109
+ export class CostLedger extends Service {
110
+ static inject = ['commands']
111
+
112
+ private readonly states = new WeakMap<Session, SessionCost>()
113
+ private readonly repoKeys = new Map<string, RepoIdentity>()
114
+ private readonly repoCache = new Map<string, RepoCostRecord>()
115
+
116
+ /** Settles in flight, awaited by the `session/flush` durability checkpoint. */
117
+ private readonly pending = new Map<string, Promise<void>>()
118
+
119
+ /** One write at a time per repository, so concurrent settles cannot drop totals. */
120
+ private readonly settling = new Map<string, Promise<void>>()
121
+
122
+ private readonly config: Config
123
+
124
+ constructor(ctx: Context, config: Config) {
125
+ super(ctx, 'teCost')
126
+ this.config = config
127
+ }
128
+
129
+ async [Service.init](): Promise<void> {
130
+ const ctx = this.ctx
131
+ ctx.on('session/event', (session: Session, event: SessionEvent) => {
132
+ this.observe(session, event)
133
+ })
134
+ ctx.on('session/disposed', (session: Session) => {
135
+ // Sessions are torn down without awaiting listeners, so the write is
136
+ // handed to the awaited `session/flush` durability checkpoint instead of
137
+ // racing the process exit here.
138
+ this.pending.set(
139
+ session.id,
140
+ this.settle(session)
141
+ .catch((error: unknown) => {
142
+ this.ctx.logger('dsh-te-cost').warn('session totals not persisted: %s', String(error))
143
+ })
144
+ .finally(() => this.pending.delete(session.id)),
145
+ )
146
+ })
147
+ ctx.on('session/flush', async () => {
148
+ await Promise.all([...this.pending.values()])
149
+ })
150
+ ctx.effect(() =>
151
+ ctx.commands.register({
152
+ name: 'te-cost',
153
+ description: 'Show cache-weighted equivalent-token spend for this session and repo',
154
+ input: { hint: 'session | repo' },
155
+ handler: async (invocation) => {
156
+ const session = invocation.agent.session
157
+ // A resumed session has an empty in-memory cache; load the record so
158
+ // `/te-cost repo` answers from disk instead of claiming there is none.
159
+ await this.repoSnapshot(session)
160
+ return { kind: 'success', text: this.report(session, invocation.rawInput) }
161
+ },
162
+ }),
163
+ )
164
+ }
165
+
166
+ /** Fold one session event into its running totals. */
167
+ observe(session: Session, event: SessionEvent): void {
168
+ try {
169
+ const state = this.stateOf(session)
170
+ if (event.type === 'request/header' || event.type === 'request/context') {
171
+ const route = readRoute(event)
172
+ if (route === undefined) return
173
+ state.provider = route.provider
174
+ state.model = route.model
175
+ const resolved = weightsFor(route.model ?? '')
176
+ state.weights = resolved.weights
177
+ state.weightsSource = resolved.source
178
+ return
179
+ }
180
+ if (event.type === 'assistant/message') {
181
+ const usage = (event.data as { usage?: ReportedUsage }).usage
182
+ if (usage === undefined) return
183
+ state.acc = foldUsage(
184
+ state.acc,
185
+ {
186
+ inputTokens: usage.inputTokens ?? 0,
187
+ outputTokens: usage.outputTokens ?? 0,
188
+ cacheReadTokens: usage.cacheReadTokens,
189
+ cacheWriteTokens: usage.cacheWriteTokens,
190
+ },
191
+ state.weights,
192
+ )
193
+ }
194
+ } catch {
195
+ // Accounting must never break the session loop.
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Bill this component's own model calls against the same account.
201
+ *
202
+ * A mechanism that spends tokens to save tokens has to say so, or the saving
203
+ * is fiction.
204
+ */
205
+ recordOverhead(session: Session, component: string, equivalent: number): void {
206
+ if (!(equivalent > 0)) return
207
+ const state = this.stateOf(session)
208
+ state.overhead[component] = (state.overhead[component] ?? 0) + equivalent
209
+ }
210
+
211
+ /** A read-only snapshot of one session. */
212
+ sessionSnapshot(session: Session): SessionCostSnapshot {
213
+ const state = this.stateOf(session)
214
+ const repo = this.repoOf(session)
215
+ return {
216
+ ...(state.provider === undefined ? {} : { provider: state.provider }),
217
+ ...(state.model === undefined ? {} : { model: state.model }),
218
+ weightsSource: state.weightsSource,
219
+ ...(repo === undefined ? {} : { repoKey: repo.key, repoSource: repo.source }),
220
+ messages: state.acc.messages,
221
+ equivalent: state.acc.equivalent,
222
+ overhead: overheadTotal(state.overhead),
223
+ buckets: state.acc.buckets,
224
+ }
225
+ }
226
+
227
+ /** Repo totals, reading the persisted record on first use. */
228
+ async repoSnapshot(session: Session): Promise<RepoCostRecord | undefined> {
229
+ const repo = this.repoOf(session)
230
+ if (repo === undefined) return undefined
231
+ const cached = this.repoCache.get(repo.key)
232
+ if (cached !== undefined) return cached
233
+ if (!this.config.persist) return undefined
234
+ const record = await readJson<RepoCostRecord>(this.recordPath(repo.key))
235
+ if (record !== undefined) this.repoCache.set(repo.key, record)
236
+ return record
237
+ }
238
+
239
+ /** Render the `/te-cost` report. */
240
+ report(session: Session, rawInput: string): string {
241
+ const scope = rawInput.trim().toLowerCase()
242
+ const wantRepo = scope === 'repo'
243
+ const wantSession = scope === '' || scope === 'session'
244
+ const state = this.stateOf(session)
245
+ const repo = this.repoOf(session)
246
+ const lines: string[] = ['Token economy — equivalent fresh-input tokens (cache-weighted).', '']
247
+
248
+ if (wantSession) {
249
+ lines.push(`session ${session.id.slice(0, 8)}`)
250
+ lines.push(` model ${state.model ?? 'unknown'} · weights ${state.weightsSource}`)
251
+ lines.push(` requests ${state.acc.messages}`)
252
+ lines.push(` equivalent ${formatTokens(state.acc.equivalent)} eq`)
253
+ lines.push(
254
+ ` buckets uncached ${formatTokens(state.acc.buckets.uncachedInput)} · cache read ${formatTokens(state.acc.buckets.cacheRead)} · cache write ${formatTokens(state.acc.buckets.cacheWrite)} · output ${formatTokens(state.acc.buckets.output)}`,
255
+ )
256
+ const overhead = overheadTotal(state.overhead)
257
+ lines.push(` overhead ${formatTokens(overhead)} eq${describeOverhead(state.overhead)}`)
258
+ lines.push('')
259
+ }
260
+
261
+ if (wantRepo) {
262
+ if (repo === undefined) {
263
+ lines.push('repo unknown (session has no working directory yet)')
264
+ } else {
265
+ const record = this.repoCache.get(repo.key)
266
+ if (record === undefined) {
267
+ lines.push(`repo ${repo.key}`)
268
+ lines.push(' no persisted totals yet (written when this session ends)')
269
+ } else {
270
+ lines.push(`repo ${record.key}`)
271
+ lines.push(` equivalent ${formatTokens(record.equivalent)} eq over ${record.sessions} sessions`)
272
+ lines.push(
273
+ ` buckets uncached ${formatTokens(record.buckets.uncachedInput)} · cache read ${formatTokens(record.buckets.cacheRead)} · cache write ${formatTokens(record.buckets.cacheWrite)} · output ${formatTokens(record.buckets.output)}`,
274
+ )
275
+ lines.push(` overhead ${formatTokens(overheadTotal(record.overhead))} eq${describeOverhead(record.overhead)}`)
276
+ }
277
+ }
278
+ }
279
+
280
+ return lines.join('\n').trimEnd()
281
+ }
282
+
283
+ private stateOf(session: Session): SessionCost {
284
+ const existing = this.states.get(session)
285
+ if (existing !== undefined) return existing
286
+ const created: SessionCost = {
287
+ acc: EMPTY_ACCUMULATOR,
288
+ overhead: {},
289
+ weights: DEFAULT_WEIGHTS,
290
+ weightsSource: 'default',
291
+ repoResolved: false,
292
+ }
293
+ this.states.set(session, created)
294
+ return created
295
+ }
296
+
297
+ private repoOf(session: Session): RepoIdentity | undefined {
298
+ const state = this.stateOf(session)
299
+ if (state.repoResolved) return state.repo
300
+ const cwd = session.header?.cwd
301
+ if (cwd === undefined || cwd === '') return undefined
302
+ let identity = this.repoKeys.get(cwd)
303
+ if (identity === undefined) {
304
+ identity = resolveRepoKey(cwd)
305
+ this.repoKeys.set(cwd, identity)
306
+ }
307
+ state.repo = identity
308
+ state.repoResolved = true
309
+ return identity
310
+ }
311
+
312
+ private recordPath(repoKey: string): string {
313
+ return join(stateRoot(), 'repos', repoKeyDirName(repoKey), 'cost.json')
314
+ }
315
+
316
+ /**
317
+ * Fold a finished session into its repo record.
318
+ *
319
+ * Called on `session/disposed`; exposed so a test (or a host shutdown path)
320
+ * can await the write instead of racing it.
321
+ */
322
+ async settle(session: Session): Promise<void> {
323
+ const state = this.states.get(session)
324
+ if (state === undefined || !this.config.persist) return
325
+ const repo = this.repoOf(session)
326
+ if (repo === undefined) return
327
+ if (state.acc.equivalent === 0 && overheadTotal(state.overhead) === 0) return
328
+ // Two sessions can end at once (two tabs, desktop plus CLI). Serialize per
329
+ // repository so one read-modify-write cannot drop the other's totals.
330
+ const previous = this.settling.get(repo.key) ?? Promise.resolve()
331
+ const run = previous.then(() => this.persist(session, state, repo))
332
+ this.settling.set(
333
+ repo.key,
334
+ run.catch(() => {
335
+ // Kept so the next writer still waits for this one to settle.
336
+ }),
337
+ )
338
+ return run
339
+ }
340
+
341
+ /** One read-modify-write of a repository's cost record. */
342
+ private async persist(session: Session, state: SessionCost, repo: RepoIdentity): Promise<void> {
343
+ try {
344
+ const previous = await this.repoSnapshot(session)
345
+ const next: RepoCostRecord = {
346
+ version: 1,
347
+ key: repo.key,
348
+ equivalent: (previous?.equivalent ?? 0) + state.acc.equivalent,
349
+ buckets: addBuckets(previous?.buckets ?? ZERO_BUCKETS, state.acc.buckets),
350
+ sessions: (previous?.sessions ?? 0) + 1,
351
+ overhead: mergeOverhead(previous?.overhead ?? {}, state.overhead),
352
+ updatedAt: new Date().toISOString(),
353
+ }
354
+ await writeJsonAtomic(this.recordPath(repo.key), next)
355
+ this.repoCache.set(repo.key, next)
356
+ } catch (error) {
357
+ this.ctx.logger('dsh-te-cost').warn('repo totals not persisted: %s', String(error))
358
+ }
359
+ }
360
+ }
361
+
362
+ function readRoute(event: SessionEvent): { provider?: string; model?: string } | undefined {
363
+ const data = event.data as {
364
+ header?: { config?: { provider?: string; model?: string } }
365
+ provider?: string
366
+ model?: string
367
+ }
368
+ const fromHeader = data.header?.config
369
+ if (fromHeader?.provider !== undefined) return { provider: fromHeader.provider, model: fromHeader.model }
370
+ if (data.provider !== undefined) return { provider: data.provider, model: data.model }
371
+ return undefined
372
+ }
373
+
374
+ function overheadTotal(overhead: Record<string, number>): number {
375
+ let total = 0
376
+ for (const value of Object.values(overhead)) total += value
377
+ return total
378
+ }
379
+
380
+ function mergeOverhead(left: Record<string, number>, right: Record<string, number>): Record<string, number> {
381
+ const merged: Record<string, number> = { ...left }
382
+ for (const [key, value] of Object.entries(right)) merged[key] = (merged[key] ?? 0) + value
383
+ return merged
384
+ }
385
+
386
+ function describeOverhead(overhead: Record<string, number>): string {
387
+ const parts = Object.entries(overhead)
388
+ .filter(([, value]) => value > 0)
389
+ .sort(([a], [b]) => a.localeCompare(b))
390
+ .map(([key, value]) => `${key} ${formatTokens(value)}`)
391
+ return parts.length === 0 ? '' : ` (${parts.join(' · ')})`
392
+ }
393
+
394
+ declare module '@deepseek-ai/cordis' {
395
+ interface Context {
396
+ /** Cache-weighted equivalent-token accounting; present while this component is mounted. */
397
+ teCost: CostLedger
398
+ }
399
+ }
400
+
401
+ /**
402
+ * Mount the component on a DSH context.
403
+ *
404
+ * Disabled means absent: no service, no command, no listener.
405
+ */
406
+ export function apply(ctx: Context, config: Config): void {
407
+ if (!config.enabled) return
408
+ ctx.plugin(CostLedger, config)
409
+ }
410
+
411
+ export { bucketsTotal }