@miphamai/cli 0.85.50 → 0.85.51
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 +1 -1
- package/package.json +1 -1
- package/src/agent/sub-agent.ts +7 -1
- package/src/core/engine.ts +17 -1
- package/src/core/task-performance.ts +6 -1
- package/src/core/usage-tracker.ts +38 -5
- package/src/daemon/attach-protocol.ts +5 -0
- package/src/daemon/remote-engine.ts +2 -0
- package/src/daemon/session-worker.ts +19 -2
- package/src/i18n-core/locales/en-US.json +12 -0
- package/src/i18n-core/locales/zh-CN.json +12 -0
- package/src/providers/anthropic.ts +17 -2
- package/src/providers/openai-compat.ts +11 -2
- package/src/providers/pricing.ts +168 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +17 -1
- package/src/ui/app.tsx +17 -1
- package/src/ui/commands.ts +99 -1
- package/src/ui/graft-status.tsx +24 -2
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.51
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 141 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
|
|
4
4
|
|
package/package.json
CHANGED
package/src/agent/sub-agent.ts
CHANGED
|
@@ -666,7 +666,13 @@ export class SubAgent {
|
|
|
666
666
|
break
|
|
667
667
|
}
|
|
668
668
|
if (chunk.type === 'usage') {
|
|
669
|
-
|
|
669
|
+
// All four billed buckets, not just the uncached ones: a cache read is
|
|
670
|
+
// still this call's usage, and it is usually the largest bucket.
|
|
671
|
+
totalTokens +=
|
|
672
|
+
(chunk.inputTokens ?? 0) +
|
|
673
|
+
(chunk.outputTokens ?? 0) +
|
|
674
|
+
(chunk.cacheReadTokens ?? 0) +
|
|
675
|
+
(chunk.cacheWriteTokens ?? 0)
|
|
670
676
|
if (options.onTokenUsage) options.onTokenUsage(totalTokens)
|
|
671
677
|
}
|
|
672
678
|
}
|
package/src/core/engine.ts
CHANGED
|
@@ -838,6 +838,8 @@ export class QueryEngine {
|
|
|
838
838
|
let truncationCause: 'max_tokens' | 'connection' | undefined
|
|
839
839
|
let turnApiInputTokens = 0
|
|
840
840
|
let turnApiOutputTokens = 0
|
|
841
|
+
let turnApiCacheReadTokens = 0
|
|
842
|
+
let turnApiCacheWriteTokens = 0
|
|
841
843
|
const turnStart = Date.now()
|
|
842
844
|
const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
|
|
843
845
|
|
|
@@ -870,6 +872,8 @@ export class QueryEngine {
|
|
|
870
872
|
// reply twice in `/usage` and in every per-tool attribution.
|
|
871
873
|
turnApiInputTokens = 0
|
|
872
874
|
turnApiOutputTokens = 0
|
|
875
|
+
turnApiCacheReadTokens = 0
|
|
876
|
+
turnApiCacheWriteTokens = 0
|
|
873
877
|
}
|
|
874
878
|
|
|
875
879
|
if (chunk.type === 'error') {
|
|
@@ -908,6 +912,8 @@ export class QueryEngine {
|
|
|
908
912
|
// Accumulate API-reported token counts for this turn
|
|
909
913
|
turnApiInputTokens += chunk.inputTokens
|
|
910
914
|
turnApiOutputTokens += chunk.outputTokens || 0
|
|
915
|
+
turnApiCacheReadTokens += chunk.cacheReadTokens ?? 0
|
|
916
|
+
turnApiCacheWriteTokens += chunk.cacheWriteTokens ?? 0
|
|
911
917
|
}
|
|
912
918
|
|
|
913
919
|
if (chunk.type === 'stop' && chunk.truncated) {
|
|
@@ -1065,7 +1071,12 @@ export class QueryEngine {
|
|
|
1065
1071
|
}
|
|
1066
1072
|
|
|
1067
1073
|
// Record API token usage for this turn, attributed to executed tools
|
|
1068
|
-
if (
|
|
1074
|
+
if (
|
|
1075
|
+
turnApiInputTokens > 0 ||
|
|
1076
|
+
turnApiOutputTokens > 0 ||
|
|
1077
|
+
turnApiCacheReadTokens > 0 ||
|
|
1078
|
+
turnApiCacheWriteTokens > 0
|
|
1079
|
+
) {
|
|
1069
1080
|
if (toolUses.length > 0) {
|
|
1070
1081
|
// Attribute tokens equally across all tools invoked this turn
|
|
1071
1082
|
const perTool = toolUses.length
|
|
@@ -1079,6 +1090,11 @@ export class QueryEngine {
|
|
|
1079
1090
|
} else {
|
|
1080
1091
|
this.usageTracker.recordApiUsage(turnApiInputTokens, turnApiOutputTokens, 'chat')
|
|
1081
1092
|
}
|
|
1093
|
+
// Cache buckets are session-level: a cached prefix is shared context, not
|
|
1094
|
+
// a cost any single tool in this turn caused.
|
|
1095
|
+
if (turnApiCacheReadTokens > 0 || turnApiCacheWriteTokens > 0) {
|
|
1096
|
+
this.usageTracker.recordCacheUsage(turnApiCacheReadTokens, turnApiCacheWriteTokens)
|
|
1097
|
+
}
|
|
1082
1098
|
} else {
|
|
1083
1099
|
// Fallback: API doesn't report usage — use char-based estimate
|
|
1084
1100
|
const estimated = Math.round((assistantContent.length + userInput.length) / 4)
|
|
@@ -187,7 +187,12 @@ async function collectGeneratedCode(
|
|
|
187
187
|
// `usageReported` 与数值分开:报 0 和「没报」不是同一件事,0 会被读成免费。
|
|
188
188
|
if (chunk.type === 'usage') {
|
|
189
189
|
usageReported = true
|
|
190
|
-
|
|
190
|
+
// All four billed buckets — cache reads are usually the bulk of the prompt.
|
|
191
|
+
tokens +=
|
|
192
|
+
(chunk.inputTokens ?? 0) +
|
|
193
|
+
(chunk.outputTokens ?? 0) +
|
|
194
|
+
(chunk.cacheReadTokens ?? 0) +
|
|
195
|
+
(chunk.cacheWriteTokens ?? 0)
|
|
191
196
|
}
|
|
192
197
|
// Both providers already emit `truncated` on the stop chunk; reading it here is
|
|
193
198
|
// what turns the signal into something the score can act on.
|
|
@@ -17,10 +17,14 @@ export interface ToolUsage {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
export interface UsageSummary {
|
|
20
|
-
/**
|
|
20
|
+
/** Uncached input tokens from API (0 if API data unavailable). */
|
|
21
21
|
apiInputTokens: number
|
|
22
22
|
/** Total output tokens from API (0 if API data unavailable). */
|
|
23
23
|
apiOutputTokens: number
|
|
24
|
+
/** Input tokens served from the provider's prompt cache (billed separately). */
|
|
25
|
+
apiCacheReadTokens: number
|
|
26
|
+
/** Input tokens written into the provider's prompt cache (billed separately). */
|
|
27
|
+
apiCacheWriteTokens: number
|
|
24
28
|
/** Estimated total tokens (chars/4 heuristic, always available). */
|
|
25
29
|
estimatedTokens: number
|
|
26
30
|
/** Per-tool breakdown, keyed by tool name. "chat" = text-only turns. */
|
|
@@ -30,16 +34,36 @@ export interface UsageSummary {
|
|
|
30
34
|
export class UsageTracker {
|
|
31
35
|
private _apiInputTokens = 0
|
|
32
36
|
private _apiOutputTokens = 0
|
|
37
|
+
private _apiCacheReadTokens = 0
|
|
38
|
+
private _apiCacheWriteTokens = 0
|
|
33
39
|
private _estimatedTokens = 0
|
|
34
40
|
private _toolUsage = new Map<string, ToolUsage>()
|
|
35
41
|
|
|
36
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* Record API-reported token usage for a turn, attributed to the given tool.
|
|
44
|
+
*
|
|
45
|
+
* The four buckets are disjoint: `inputTokens` is uncached prompt input only
|
|
46
|
+
* (providers normalize cached tokens out of it). Per-tool attribution stays
|
|
47
|
+
* on uncached input + output.
|
|
48
|
+
*/
|
|
37
49
|
recordApiUsage(inputTokens: number, outputTokens: number, toolName?: string): void {
|
|
38
50
|
this._apiInputTokens += inputTokens
|
|
39
51
|
this._apiOutputTokens += outputTokens
|
|
40
52
|
this._recordTool(toolName || 'chat', inputTokens, outputTokens)
|
|
41
53
|
}
|
|
42
54
|
|
|
55
|
+
/**
|
|
56
|
+
* Record API-reported prompt-cache tokens for a turn.
|
|
57
|
+
*
|
|
58
|
+
* Session-level by design: a cached prefix is shared context, so attributing
|
|
59
|
+
* it to whichever tool happened to run in that turn would invent a cost that
|
|
60
|
+
* tool did not cause.
|
|
61
|
+
*/
|
|
62
|
+
recordCacheUsage(cacheReadTokens: number, cacheWriteTokens: number): void {
|
|
63
|
+
this._apiCacheReadTokens += cacheReadTokens
|
|
64
|
+
this._apiCacheWriteTokens += cacheWriteTokens
|
|
65
|
+
}
|
|
66
|
+
|
|
43
67
|
/** Record character-estimated token usage for a turn. */
|
|
44
68
|
recordEstimatedUsage(tokenCount: number, toolName?: string): void {
|
|
45
69
|
this._estimatedTokens += tokenCount
|
|
@@ -55,6 +79,8 @@ export class UsageTracker {
|
|
|
55
79
|
return {
|
|
56
80
|
apiInputTokens: this._apiInputTokens,
|
|
57
81
|
apiOutputTokens: this._apiOutputTokens,
|
|
82
|
+
apiCacheReadTokens: this._apiCacheReadTokens,
|
|
83
|
+
apiCacheWriteTokens: this._apiCacheWriteTokens,
|
|
58
84
|
estimatedTokens: this._estimatedTokens,
|
|
59
85
|
tools,
|
|
60
86
|
}
|
|
@@ -64,18 +90,25 @@ export class UsageTracker {
|
|
|
64
90
|
reset(): void {
|
|
65
91
|
this._apiInputTokens = 0
|
|
66
92
|
this._apiOutputTokens = 0
|
|
93
|
+
this._apiCacheReadTokens = 0
|
|
94
|
+
this._apiCacheWriteTokens = 0
|
|
67
95
|
this._estimatedTokens = 0
|
|
68
96
|
this._toolUsage.clear()
|
|
69
97
|
}
|
|
70
98
|
|
|
71
|
-
/** Total API tokens (input + output). */
|
|
99
|
+
/** Total billed API tokens (uncached input + output + cache reads + cache writes). */
|
|
72
100
|
get totalApiTokens(): number {
|
|
73
|
-
return
|
|
101
|
+
return (
|
|
102
|
+
this._apiInputTokens +
|
|
103
|
+
this._apiOutputTokens +
|
|
104
|
+
this._apiCacheReadTokens +
|
|
105
|
+
this._apiCacheWriteTokens
|
|
106
|
+
)
|
|
74
107
|
}
|
|
75
108
|
|
|
76
109
|
/** Whether any real API usage data has been recorded. */
|
|
77
110
|
get hasApiData(): boolean {
|
|
78
|
-
return this.
|
|
111
|
+
return this.totalApiTokens > 0
|
|
79
112
|
}
|
|
80
113
|
|
|
81
114
|
// ── Private helpers ──
|
|
@@ -49,8 +49,13 @@ export interface ServerToolResultMessage {
|
|
|
49
49
|
export interface ServerUsageMessage {
|
|
50
50
|
type: 'usage'
|
|
51
51
|
sessionId: string
|
|
52
|
+
/** Uncached prompt input only — cached tokens ride the two buckets below. */
|
|
52
53
|
inputTokens: number
|
|
53
54
|
outputTokens: number
|
|
55
|
+
/** Prompt-cache reads, billed separately. Absent when the provider reported none. */
|
|
56
|
+
cacheReadTokens?: number
|
|
57
|
+
/** Prompt-cache writes, billed separately. Absent when the provider reported none. */
|
|
58
|
+
cacheWriteTokens?: number
|
|
54
59
|
}
|
|
55
60
|
export interface ServerTaskNotificationMessage {
|
|
56
61
|
type: 'task_notification'
|
|
@@ -722,6 +722,8 @@ export class RemoteEngine {
|
|
|
722
722
|
type: 'usage',
|
|
723
723
|
inputTokens: msg.inputTokens,
|
|
724
724
|
outputTokens: msg.outputTokens,
|
|
725
|
+
...(msg.cacheReadTokens !== undefined ? { cacheReadTokens: msg.cacheReadTokens } : {}),
|
|
726
|
+
...(msg.cacheWriteTokens !== undefined ? { cacheWriteTokens: msg.cacheWriteTokens } : {}),
|
|
725
727
|
}
|
|
726
728
|
}
|
|
727
729
|
|
|
@@ -142,6 +142,8 @@ export class SessionWorker {
|
|
|
142
142
|
let assistantContent = ''
|
|
143
143
|
let totalInputTokens = 0
|
|
144
144
|
let totalOutputTokens = 0
|
|
145
|
+
let totalCacheReadTokens = 0
|
|
146
|
+
let totalCacheWriteTokens = 0
|
|
145
147
|
let stopReason: string = 'end_turn'
|
|
146
148
|
// The provider hit its output ceiling at least once in this turn. Reported only
|
|
147
149
|
// when nothing worse happened — the three original values keep their precedence.
|
|
@@ -170,6 +172,8 @@ export class SessionWorker {
|
|
|
170
172
|
if (chunk.type === 'usage') {
|
|
171
173
|
if (chunk.inputTokens) totalInputTokens += chunk.inputTokens
|
|
172
174
|
if (chunk.outputTokens) totalOutputTokens += chunk.outputTokens
|
|
175
|
+
if (chunk.cacheReadTokens) totalCacheReadTokens += chunk.cacheReadTokens
|
|
176
|
+
if (chunk.cacheWriteTokens) totalCacheWriteTokens += chunk.cacheWriteTokens
|
|
173
177
|
}
|
|
174
178
|
|
|
175
179
|
// A turn cut off at the provider's output ceiling must not be reported as a
|
|
@@ -211,8 +215,15 @@ export class SessionWorker {
|
|
|
211
215
|
)
|
|
212
216
|
}
|
|
213
217
|
|
|
214
|
-
// Increment turn count with accumulated token usage
|
|
215
|
-
|
|
218
|
+
// Increment turn count with accumulated token usage. The sessions table has
|
|
219
|
+
// only tokenIn/tokenOut, so the three prompt-side buckets fold into tokenIn —
|
|
220
|
+
// dropping cache reads here would under-report a daemon session's cost by
|
|
221
|
+
// roughly the cache-hit share of every prompt.
|
|
222
|
+
this.db.incrementTurn(
|
|
223
|
+
this.session.id,
|
|
224
|
+
totalInputTokens + totalCacheReadTokens + totalCacheWriteTokens,
|
|
225
|
+
totalOutputTokens,
|
|
226
|
+
)
|
|
216
227
|
|
|
217
228
|
// Refresh session metadata from DB so turnCount/tokenIn/tokenOut are up to date
|
|
218
229
|
const refreshed = this.db.getSession(this.session.id)
|
|
@@ -404,6 +415,12 @@ export class SessionWorker {
|
|
|
404
415
|
sessionId: this.session.id,
|
|
405
416
|
inputTokens: chunk.inputTokens ?? 0,
|
|
406
417
|
outputTokens: chunk.outputTokens ?? 0,
|
|
418
|
+
...(chunk.cacheReadTokens !== undefined
|
|
419
|
+
? { cacheReadTokens: chunk.cacheReadTokens }
|
|
420
|
+
: {}),
|
|
421
|
+
...(chunk.cacheWriteTokens !== undefined
|
|
422
|
+
? { cacheWriteTokens: chunk.cacheWriteTokens }
|
|
423
|
+
: {}),
|
|
407
424
|
}
|
|
408
425
|
return msg
|
|
409
426
|
}
|
|
@@ -122,6 +122,17 @@
|
|
|
122
122
|
"prompt_cache": "Prompt cache: ~{cached} cached ({ratio}% hit) · ~{uncached} uncached",
|
|
123
123
|
"footer": "Token counting is approximate (chars/4).\nActual API usage depends on provider and model."
|
|
124
124
|
},
|
|
125
|
+
"cost": {
|
|
126
|
+
"session_title": "── Session billing (API-reported) ──",
|
|
127
|
+
"buckets": "Input {input} · Cache read {cache_read} · Cache write {cache_write} · Output {output}",
|
|
128
|
+
"cache_hit": "Prompt cache hit: {ratio}%",
|
|
129
|
+
"estimate": "Cost estimate: ≈ {symbol}{amount} ({provider}/{model}, prices as of {asOf})",
|
|
130
|
+
"estimate_no_date": "Cost estimate: ≈ {symbol}{amount} ({provider}/{model} prices)",
|
|
131
|
+
"no_price": "Cost estimate: no prices configured — add per-1M-token rates for {provider}/{model} in ~/.mipham/pricing.json.",
|
|
132
|
+
"incomplete": "Cost estimate: cannot estimate — the price book is missing {missing}.",
|
|
133
|
+
"file_error": "Cost estimate: cannot read the price file — {error}",
|
|
134
|
+
"caveat": "(estimated at the current model's rates for the whole session; switching models mid-session skews it)"
|
|
135
|
+
},
|
|
125
136
|
"model": {
|
|
126
137
|
"current": "Current model: {model}\nProvider: {provider}\n\nUse /model <model> or /switch <provider> <model> to change.",
|
|
127
138
|
"unknown": "Unknown model: {model}. Use /models to list the available models.",
|
|
@@ -249,6 +260,7 @@
|
|
|
249
260
|
"title": "── Usage Dashboard ──",
|
|
250
261
|
"api_tokens": "API tokens: {in} in / {out} out ({total} total)",
|
|
251
262
|
"no_api": "API tokens: (no API usage data yet)",
|
|
263
|
+
"cache_tokens": "API cache: {read} read / {write} written ({ratio}% hit)",
|
|
252
264
|
"context_line": "Context tokens: ~{est} / {max} ({pct}%)",
|
|
253
265
|
"messages_line": "Messages: {count}",
|
|
254
266
|
"provider_line": "Provider: {provider}",
|
|
@@ -122,6 +122,17 @@
|
|
|
122
122
|
"prompt_cache": "Prompt 缓存: ~{cached} 命中 ({ratio}% hit) · ~{uncached} 未命中",
|
|
123
123
|
"footer": "Token 计数为近似值(字符数/4)。\n实际 API 用量取决于提供商和模型。"
|
|
124
124
|
},
|
|
125
|
+
"cost": {
|
|
126
|
+
"session_title": "── 会话计费(API 实报)──",
|
|
127
|
+
"buckets": "输入 {input} · 缓存读 {cache_read} · 缓存写 {cache_write} · 输出 {output}",
|
|
128
|
+
"cache_hit": "Prompt 缓存命中: {ratio}%",
|
|
129
|
+
"estimate": "估算费用: ≈ {symbol}{amount}({provider}/{model},单价日期 {asOf})",
|
|
130
|
+
"estimate_no_date": "估算费用: ≈ {symbol}{amount}({provider}/{model} 单价)",
|
|
131
|
+
"no_price": "估算费用: 价格未配置 —— 在 ~/.mipham/pricing.json 写入 {provider}/{model} 的每 1M token 单价。",
|
|
132
|
+
"incomplete": "估算费用: 无法估算 —— 价格表缺少 {missing}。",
|
|
133
|
+
"file_error": "估算费用: 价格文件无法读取 —— {error}",
|
|
134
|
+
"caveat": "(按当前模型单价估算整段会话;中途换过模型会有偏差)"
|
|
135
|
+
},
|
|
125
136
|
"model": {
|
|
126
137
|
"current": "当前模型: {model}\n提供商: {provider}\n\n使用 /model <model> 或 /switch <provider> <model> 切换。",
|
|
127
138
|
"unknown": "未知模型: {model}。用 /models 查看可用模型。",
|
|
@@ -249,6 +260,7 @@
|
|
|
249
260
|
"title": "── 用量面板 ──",
|
|
250
261
|
"api_tokens": "API Token: {in} in / {out} out ({total} total)",
|
|
251
262
|
"no_api": "API Token: (暂无 API 用量数据)",
|
|
263
|
+
"cache_tokens": "API 缓存: {read} 读命中 / {write} 写入(命中率 {ratio}%)",
|
|
252
264
|
"context_line": "上下文 Token: ~{est} / {max} ({pct}%)",
|
|
253
265
|
"messages_line": "消息数: {count}",
|
|
254
266
|
"provider_line": "提供商: {provider}",
|
|
@@ -49,7 +49,14 @@ interface AnthropicSSEEvent {
|
|
|
49
49
|
stop_details?: { category?: string; explanation?: string }
|
|
50
50
|
}
|
|
51
51
|
error?: { type: string; message: string }
|
|
52
|
-
usage?: {
|
|
52
|
+
usage?: {
|
|
53
|
+
input_tokens: number
|
|
54
|
+
output_tokens: number
|
|
55
|
+
/** Prompt-cache write billed separately from `input_tokens`. */
|
|
56
|
+
cache_creation_input_tokens?: number
|
|
57
|
+
/** Prompt-cache read billed separately from `input_tokens`. */
|
|
58
|
+
cache_read_input_tokens?: number
|
|
59
|
+
}
|
|
53
60
|
}
|
|
54
61
|
|
|
55
62
|
/**
|
|
@@ -376,12 +383,20 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
376
383
|
}
|
|
377
384
|
|
|
378
385
|
case 'message_delta': {
|
|
379
|
-
// Capture token usage for accurate cost tracking
|
|
386
|
+
// Capture token usage for accurate cost tracking. Cache buckets are
|
|
387
|
+
// emitted only when the provider reports them, so "not reported" stays
|
|
388
|
+
// distinguishable from a reported zero.
|
|
380
389
|
if (event.usage) {
|
|
381
390
|
yield {
|
|
382
391
|
type: 'usage',
|
|
383
392
|
inputTokens: event.usage.input_tokens,
|
|
384
393
|
outputTokens: event.usage.output_tokens,
|
|
394
|
+
...(event.usage.cache_read_input_tokens !== undefined
|
|
395
|
+
? { cacheReadTokens: event.usage.cache_read_input_tokens }
|
|
396
|
+
: {}),
|
|
397
|
+
...(event.usage.cache_creation_input_tokens !== undefined
|
|
398
|
+
? { cacheWriteTokens: event.usage.cache_creation_input_tokens }
|
|
399
|
+
: {}),
|
|
385
400
|
}
|
|
386
401
|
}
|
|
387
402
|
// Contains stop_reason; also handles late input_json_delta
|
|
@@ -187,12 +187,21 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
187
187
|
const parsed = JSON.parse(data)
|
|
188
188
|
const choice = parsed.choices?.[0]
|
|
189
189
|
|
|
190
|
-
// Capture token usage when available (final chunk with stream_options.include_usage)
|
|
190
|
+
// Capture token usage when available (final chunk with stream_options.include_usage).
|
|
191
|
+
// `prompt_tokens` is inclusive of cache hits here, unlike Anthropic's
|
|
192
|
+
// `input_tokens`; subtract them so the emitted buckets never overlap.
|
|
191
193
|
if (parsed.usage) {
|
|
194
|
+
const promptTokens: number = parsed.usage.prompt_tokens
|
|
195
|
+
const cachedTokens: number | undefined =
|
|
196
|
+
parsed.usage.prompt_tokens_details?.cached_tokens
|
|
192
197
|
yield {
|
|
193
198
|
type: 'usage',
|
|
194
|
-
inputTokens:
|
|
199
|
+
inputTokens:
|
|
200
|
+
cachedTokens === undefined
|
|
201
|
+
? promptTokens
|
|
202
|
+
: Math.max(0, promptTokens - cachedTokens),
|
|
195
203
|
outputTokens: parsed.usage.completion_tokens,
|
|
204
|
+
...(cachedTokens !== undefined ? { cacheReadTokens: cachedTokens } : {}),
|
|
196
205
|
}
|
|
197
206
|
}
|
|
198
207
|
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 单价表 —— 把会话的四个计费 token 桶换算成钱。
|
|
3
|
+
*
|
|
4
|
+
* **本模块不内置任何单价。** 单价随供应商、套餐、网关和折扣漂移,写死在仓库里
|
|
5
|
+
* 就会在每一次调价后静默说谎;而「估算费用」最容易犯的错,正是把编出来的数字
|
|
6
|
+
* 说得像账单。故单价由用户在自己的 `~/.mipham/pricing.json` 里声明,本模块只做
|
|
7
|
+
* 读取、校验与算术;没有对应条目时回答 `'no-price'`,绝不猜。
|
|
8
|
+
*
|
|
9
|
+
* 文件形状(providerId → modelId → 单价):
|
|
10
|
+
*
|
|
11
|
+
* ```json
|
|
12
|
+
* {
|
|
13
|
+
* "providers": {
|
|
14
|
+
* "deepseek": {
|
|
15
|
+
* "deepseek-v4-flash": {
|
|
16
|
+
* "currency": "USD",
|
|
17
|
+
* "inputPerM": 0.28,
|
|
18
|
+
* "outputPerM": 0.42,
|
|
19
|
+
* "cacheReadPerM": 0.028,
|
|
20
|
+
* "cacheWritePerM": 0.35,
|
|
21
|
+
* "asOf": "2026-11-01",
|
|
22
|
+
* "source": "https://…"
|
|
23
|
+
* }
|
|
24
|
+
* }
|
|
25
|
+
* }
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { readFileSync } from 'node:fs'
|
|
31
|
+
import { miphamHome } from '../core/paths'
|
|
32
|
+
|
|
33
|
+
export interface PriceEntry {
|
|
34
|
+
/** 计价币种。不做汇率换算 —— 混币种时由显示层原样标注。 */
|
|
35
|
+
currency: 'USD' | 'CNY'
|
|
36
|
+
/** 每 1M 未缓存输入 token 的价格。 */
|
|
37
|
+
inputPerM: number
|
|
38
|
+
/** 每 1M 输出 token 的价格。 */
|
|
39
|
+
outputPerM: number
|
|
40
|
+
/** 每 1M 缓存读 token 的价格。用到缓存却缺这项 ⇒ 无法估算,不是按 0 算。 */
|
|
41
|
+
cacheReadPerM?: number
|
|
42
|
+
/** 每 1M 缓存写 token 的价格。同上。 */
|
|
43
|
+
cacheWritePerM?: number
|
|
44
|
+
/** 这些单价取自哪一天(ISO 日期),显示时原样带出。 */
|
|
45
|
+
asOf?: string
|
|
46
|
+
/** 单价来源(URL/说明),留给人工复核。 */
|
|
47
|
+
source?: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface PriceBook {
|
|
51
|
+
providers: Record<string, Record<string, PriceEntry>>
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface PriceBookLoad {
|
|
55
|
+
book: PriceBook
|
|
56
|
+
/** 文件存在但读不出/解析失败/校验不过时的原因;undefined = 没配置或配置正常。 */
|
|
57
|
+
error?: string
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface TokenBuckets {
|
|
61
|
+
/** 未缓存输入。 */
|
|
62
|
+
inputTokens: number
|
|
63
|
+
outputTokens: number
|
|
64
|
+
cacheReadTokens: number
|
|
65
|
+
cacheWriteTokens: number
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type CostResult =
|
|
69
|
+
| { kind: 'ok'; amount: number; currency: PriceEntry['currency']; asOf?: string }
|
|
70
|
+
/** 没有该 provider/model 的条目。 */
|
|
71
|
+
| { kind: 'no-price' }
|
|
72
|
+
/** 用到了某个桶,但条目里没有它的单价 —— 缺哪项报哪项。 */
|
|
73
|
+
| { kind: 'incomplete'; missing: string[] }
|
|
74
|
+
|
|
75
|
+
const EMPTY: PriceBook = { providers: {} }
|
|
76
|
+
|
|
77
|
+
const isFiniteNonNegative = (v: unknown): v is number =>
|
|
78
|
+
typeof v === 'number' && Number.isFinite(v) && v >= 0
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 读用户价格表。没有文件是**正常状态**(未配置),不是错误;文件坏了才是错误,
|
|
82
|
+
* 且必须与「未配置」区分开 —— 两者都会得到空表,但一个要告诉用户去修。
|
|
83
|
+
*/
|
|
84
|
+
export function loadPriceBook(filePath = miphamHome('pricing.json')): PriceBookLoad {
|
|
85
|
+
let raw: string
|
|
86
|
+
try {
|
|
87
|
+
raw = readFileSync(filePath, 'utf8')
|
|
88
|
+
} catch (err) {
|
|
89
|
+
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { book: EMPTY }
|
|
90
|
+
return { book: EMPTY, error: `${filePath}: ${(err as Error).message}` }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let parsed: unknown
|
|
94
|
+
try {
|
|
95
|
+
parsed = JSON.parse(raw)
|
|
96
|
+
} catch (err) {
|
|
97
|
+
return { book: EMPTY, error: `${filePath}: ${(err as Error).message}` }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const problem = validate(parsed)
|
|
101
|
+
if (problem) return { book: EMPTY, error: `${filePath}: ${problem}` }
|
|
102
|
+
return { book: parsed as PriceBook }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 校验整份文件;返回第一处问题(带路径),没有则 undefined。 */
|
|
106
|
+
function validate(value: unknown): string | undefined {
|
|
107
|
+
if (typeof value !== 'object' || value === null) return '根节点必须是对象'
|
|
108
|
+
const providers = (value as { providers?: unknown }).providers
|
|
109
|
+
if (typeof providers !== 'object' || providers === null) return '缺少 providers 对象'
|
|
110
|
+
|
|
111
|
+
for (const [providerId, models] of Object.entries(providers as Record<string, unknown>)) {
|
|
112
|
+
if (typeof models !== 'object' || models === null) return `providers.${providerId} 必须是对象`
|
|
113
|
+
for (const [modelId, entry] of Object.entries(models as Record<string, unknown>)) {
|
|
114
|
+
const path = `providers.${providerId}.${modelId}`
|
|
115
|
+
if (typeof entry !== 'object' || entry === null) return `${path} 必须是对象`
|
|
116
|
+
const e = entry as Record<string, unknown>
|
|
117
|
+
if (e.currency !== 'USD' && e.currency !== 'CNY') return `${path}.currency 必须是 USD 或 CNY`
|
|
118
|
+
if (!isFiniteNonNegative(e.inputPerM)) return `${path}.inputPerM 必须是 ≥0 的数字`
|
|
119
|
+
if (!isFiniteNonNegative(e.outputPerM)) return `${path}.outputPerM 必须是 ≥0 的数字`
|
|
120
|
+
if (e.cacheReadPerM !== undefined && !isFiniteNonNegative(e.cacheReadPerM))
|
|
121
|
+
return `${path}.cacheReadPerM 必须是 ≥0 的数字`
|
|
122
|
+
if (e.cacheWritePerM !== undefined && !isFiniteNonNegative(e.cacheWritePerM))
|
|
123
|
+
return `${path}.cacheWritePerM 必须是 ≥0 的数字`
|
|
124
|
+
if (e.asOf !== undefined && typeof e.asOf !== 'string') return `${path}.asOf 必须是字符串`
|
|
125
|
+
if (e.source !== undefined && typeof e.source !== 'string')
|
|
126
|
+
return `${path}.source 必须是字符串`
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return undefined
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 按四个桶分别计价并求和。
|
|
134
|
+
*
|
|
135
|
+
* 用到缓存却没有缓存单价时返回 `'incomplete'` 而不是拿输入价顶替 —— 顶替出来的
|
|
136
|
+
* 「估算」与真实账单的偏差正好落在缓存命中最多的会话上,而那正是缓存价存在的理由。
|
|
137
|
+
*/
|
|
138
|
+
export function estimateCost(
|
|
139
|
+
book: PriceBook,
|
|
140
|
+
providerId: string,
|
|
141
|
+
modelId: string,
|
|
142
|
+
usage: TokenBuckets,
|
|
143
|
+
): CostResult {
|
|
144
|
+
const entry = book.providers[providerId]?.[modelId]
|
|
145
|
+
if (!entry) return { kind: 'no-price' }
|
|
146
|
+
|
|
147
|
+
const missing: string[] = []
|
|
148
|
+
if (usage.cacheReadTokens > 0 && entry.cacheReadPerM === undefined) missing.push('cacheReadPerM')
|
|
149
|
+
if (usage.cacheWriteTokens > 0 && entry.cacheWritePerM === undefined)
|
|
150
|
+
missing.push('cacheWritePerM')
|
|
151
|
+
if (missing.length > 0) return { kind: 'incomplete', missing }
|
|
152
|
+
|
|
153
|
+
const raw =
|
|
154
|
+
(usage.inputTokens / 1_000_000) * entry.inputPerM +
|
|
155
|
+
(usage.outputTokens / 1_000_000) * entry.outputPerM +
|
|
156
|
+
(usage.cacheReadTokens / 1_000_000) * (entry.cacheReadPerM ?? 0) +
|
|
157
|
+
(usage.cacheWriteTokens / 1_000_000) * (entry.cacheWritePerM ?? 0)
|
|
158
|
+
// 1e-9 的粒度(十亿分之一货币单位)足以覆盖最便宜的 token 价,同时把浮点尾巴
|
|
159
|
+
// 挡在显示层之外 —— 否则 0.5+0.2+0.1+0.3 会以 1.0999999999999999 出现在用户面前。
|
|
160
|
+
const amount = Math.round(raw * 1e9) / 1e9
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
kind: 'ok',
|
|
164
|
+
amount,
|
|
165
|
+
currency: entry.currency,
|
|
166
|
+
...(entry.asOf !== undefined ? { asOf: entry.asOf } : {}),
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
export const PACKAGE_NAME = '@miphamai/cli' as const
|
|
10
10
|
|
|
11
11
|
/** 当前发布版本 */
|
|
12
|
-
export const PACKAGE_VERSION = '0.85.
|
|
12
|
+
export const PACKAGE_VERSION = '0.85.51' as const
|
|
13
13
|
|
|
14
14
|
/** npm install 全局安装命令 */
|
|
15
15
|
export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
|
|
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
|
|
|
90
90
|
* —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
|
|
91
91
|
* 但**总数相同**(两边都把被 skip 的算进去)。
|
|
92
92
|
*/
|
|
93
|
-
export const TEST_COUNT =
|
|
93
|
+
export const TEST_COUNT = 5446 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -166,10 +166,26 @@ export interface StreamChunk {
|
|
|
166
166
|
thinking?: string
|
|
167
167
|
/** Background task notification payload (type: 'task_notification'). */
|
|
168
168
|
taskNotification?: TaskNotification
|
|
169
|
-
/**
|
|
169
|
+
/**
|
|
170
|
+
* API-reported **uncached** input token count (type: 'usage').
|
|
171
|
+
*
|
|
172
|
+
* Cached prompt tokens are normalized out of this field into the two buckets
|
|
173
|
+
* below, so the four buckets never overlap: OpenAI-compatible providers report
|
|
174
|
+
* `prompt_tokens` inclusive of cache hits, and the adapter subtracts them.
|
|
175
|
+
*/
|
|
170
176
|
inputTokens?: number
|
|
171
177
|
/** API-reported output token count (type: 'usage'). */
|
|
172
178
|
outputTokens?: number
|
|
179
|
+
/**
|
|
180
|
+
* API-reported input tokens served from the prompt cache (type: 'usage').
|
|
181
|
+
* Absent — not 0 — when the provider reports no cache figures.
|
|
182
|
+
*/
|
|
183
|
+
cacheReadTokens?: number
|
|
184
|
+
/**
|
|
185
|
+
* API-reported input tokens written into the prompt cache (type: 'usage').
|
|
186
|
+
* Absent — not 0 — when the provider reports no cache figures.
|
|
187
|
+
*/
|
|
188
|
+
cacheWriteTokens?: number
|
|
173
189
|
/**
|
|
174
190
|
* The provider stopped because it hit the output token ceiling
|
|
175
191
|
* (OpenAI `finish_reason: 'length'` / Anthropic `stop_reason: 'max_tokens'`).
|
package/src/ui/app.tsx
CHANGED
|
@@ -46,6 +46,18 @@ function contextUsagePct(engine: QueryEngine | RemoteEngine): number | undefined
|
|
|
46
46
|
if (!max || max <= 0) return undefined
|
|
47
47
|
return Math.round((ctx.getEstimatedTokens() / max) * 100)
|
|
48
48
|
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 本会话的计费 token 合计(四桶),给页脚用。
|
|
52
|
+
*
|
|
53
|
+
* 远端 attach 的 tracker 只有 `getStats()`、没有本地账 —— 那类会话返回 undefined,
|
|
54
|
+
* 让页脚省略这一段,而不是编一个 0 出来。
|
|
55
|
+
*/
|
|
56
|
+
export function sessionTokens(engine: QueryEngine | RemoteEngine): number | undefined {
|
|
57
|
+
const tracker = engine.getUsageTracker?.() as { totalApiTokens?: unknown } | undefined
|
|
58
|
+
const total = tracker?.totalApiTokens
|
|
59
|
+
return typeof total === 'number' && total > 0 ? total : undefined
|
|
60
|
+
}
|
|
49
61
|
import { AgentViewDashboard } from '../agent-view/dashboard'
|
|
50
62
|
import { AgentSessionView } from '../agent-view/session-view'
|
|
51
63
|
import type { AgentViewManager } from '../agent-view/agent-view-manager'
|
|
@@ -1674,7 +1686,11 @@ export function App({
|
|
|
1674
1686
|
/>
|
|
1675
1687
|
|
|
1676
1688
|
{/* graft status line — mirrors graft's own "◤ graft · …" bar */}
|
|
1677
|
-
<GraftStatusLine
|
|
1689
|
+
<GraftStatusLine
|
|
1690
|
+
cwd={process.cwd()}
|
|
1691
|
+
ctxPct={contextUsagePct(engine)}
|
|
1692
|
+
tokens={sessionTokens(engine)}
|
|
1693
|
+
/>
|
|
1678
1694
|
|
|
1679
1695
|
{/* Update notification — green, right-aligned, mirrors Claude Code's "Update installed · Restart to apply".
|
|
1680
1696
|
While the startup banner is showing it already carries this line, so the footer copy is suppressed to avoid a duplicate. */}
|
package/src/ui/commands.ts
CHANGED
|
@@ -168,6 +168,8 @@ import { execSync } from 'node:child_process'
|
|
|
168
168
|
import { MIPHAM_DIR, OLLAMA_PRESET_MODELS } from '../shared/constants'
|
|
169
169
|
import { renameActiveSession } from '../agent/cross-session/discovery'
|
|
170
170
|
import { clearTasks, formatTaskList } from '../tools/exec/task'
|
|
171
|
+
import { estimateCost, loadPriceBook } from '../providers/pricing'
|
|
172
|
+
import type { UsageSummary } from '../core/usage-tracker'
|
|
171
173
|
|
|
172
174
|
export interface CommandContext {
|
|
173
175
|
engine: QueryEngine
|
|
@@ -596,6 +598,87 @@ const statusCmd: CommandHandler = async (ctx) => {
|
|
|
596
598
|
}
|
|
597
599
|
}
|
|
598
600
|
|
|
601
|
+
const CURRENCY_SYMBOLS: Record<string, string> = { USD: '$', CNY: '¥' }
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* 金额显示:估算值,不是账单。太小的数不四舍五入成 0 —— 「<$0.0001」与「0」
|
|
605
|
+
* 对用户是两件事(前者说明有花费,只是很小)。
|
|
606
|
+
*/
|
|
607
|
+
function formatCostAmount(amount: number): string {
|
|
608
|
+
if (amount === 0) return '0'
|
|
609
|
+
if (amount < 0.0001) return '<0.0001'
|
|
610
|
+
return String(Number(amount.toFixed(6)))
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** `/cost` 的会话计费段:四桶实报用量 + 按用户价格表估算的费用。 */
|
|
614
|
+
function sessionBillingLines(
|
|
615
|
+
ctx: Parameters<CommandHandler>[0],
|
|
616
|
+
t: (key: string, params?: Record<string, string>) => string,
|
|
617
|
+
): string[] {
|
|
618
|
+
const tracker = ctx.engine.getUsageTracker() as { getSummary?: () => UsageSummary } | undefined
|
|
619
|
+
// 远端 attach 的 tracker 只有 getStats —— 那类会话没有本地计费账,整段省略,
|
|
620
|
+
// 不能因此把 `/cost` 打死。
|
|
621
|
+
if (typeof tracker?.getSummary !== 'function') return []
|
|
622
|
+
const summary = tracker.getSummary()
|
|
623
|
+
|
|
624
|
+
const input = summary.apiInputTokens ?? 0
|
|
625
|
+
const output = summary.apiOutputTokens ?? 0
|
|
626
|
+
const cacheRead = summary.apiCacheReadTokens ?? 0
|
|
627
|
+
const cacheWrite = summary.apiCacheWriteTokens ?? 0
|
|
628
|
+
const billedInput = input + cacheRead + cacheWrite
|
|
629
|
+
const hitRatio = billedInput > 0 ? Math.min(1, cacheRead / billedInput) * 100 : 0
|
|
630
|
+
|
|
631
|
+
const lines = [
|
|
632
|
+
'',
|
|
633
|
+
t('commands.cost.session_title'),
|
|
634
|
+
t('commands.cost.buckets', {
|
|
635
|
+
input: input.toLocaleString(),
|
|
636
|
+
cache_read: cacheRead.toLocaleString(),
|
|
637
|
+
cache_write: cacheWrite.toLocaleString(),
|
|
638
|
+
output: output.toLocaleString(),
|
|
639
|
+
}),
|
|
640
|
+
]
|
|
641
|
+
if (billedInput > 0) {
|
|
642
|
+
lines.push(t('commands.cost.cache_hit', { ratio: hitRatio.toFixed(1) }))
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const loaded = loadPriceBook()
|
|
646
|
+
if (loaded.error !== undefined) {
|
|
647
|
+
lines.push(t('commands.cost.file_error', { error: loaded.error }))
|
|
648
|
+
return lines
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
const result = estimateCost(loaded.book, ctx.providerId, ctx.modelId, {
|
|
652
|
+
inputTokens: input,
|
|
653
|
+
outputTokens: output,
|
|
654
|
+
cacheReadTokens: cacheRead,
|
|
655
|
+
cacheWriteTokens: cacheWrite,
|
|
656
|
+
})
|
|
657
|
+
const route = { provider: ctx.providerId, model: ctx.modelId }
|
|
658
|
+
switch (result.kind) {
|
|
659
|
+
case 'ok':
|
|
660
|
+
lines.push(
|
|
661
|
+
t(result.asOf === undefined ? 'commands.cost.estimate_no_date' : 'commands.cost.estimate', {
|
|
662
|
+
symbol: CURRENCY_SYMBOLS[result.currency] ?? '',
|
|
663
|
+
amount: formatCostAmount(result.amount),
|
|
664
|
+
...route,
|
|
665
|
+
...(result.asOf !== undefined ? { asOf: result.asOf } : {}),
|
|
666
|
+
}),
|
|
667
|
+
// 账是「整段会话的桶 × 当前模型单价」,中途换过模型就不再是精确认账 ——
|
|
668
|
+
// 说在显示上,而不是留给用户自己发现。
|
|
669
|
+
t('commands.cost.caveat'),
|
|
670
|
+
)
|
|
671
|
+
break
|
|
672
|
+
case 'incomplete':
|
|
673
|
+
lines.push(t('commands.cost.incomplete', { missing: result.missing.join(', ') }))
|
|
674
|
+
break
|
|
675
|
+
case 'no-price':
|
|
676
|
+
lines.push(t('commands.cost.no_price', route))
|
|
677
|
+
break
|
|
678
|
+
}
|
|
679
|
+
return lines
|
|
680
|
+
}
|
|
681
|
+
|
|
599
682
|
const costCmd: CommandHandler = (ctx) => {
|
|
600
683
|
const t = resolveT(ctx)
|
|
601
684
|
const c = ctx.engine.getContext()
|
|
@@ -605,6 +688,7 @@ const costCmd: CommandHandler = (ctx) => {
|
|
|
605
688
|
const hitRatio = tokens > 0 ? Math.min(1, cachedTokens / tokens) : 0
|
|
606
689
|
const uncachedTokens = Math.max(0, tokens - cachedTokens)
|
|
607
690
|
const maxTokens = c.getMaxTokens()
|
|
691
|
+
const billing = sessionBillingLines(ctx, t).join('\n')
|
|
608
692
|
return {
|
|
609
693
|
content: stripIndent`
|
|
610
694
|
${t('commands.context_tokens.title')}
|
|
@@ -615,6 +699,7 @@ const costCmd: CommandHandler = (ctx) => {
|
|
|
615
699
|
ratio: (hitRatio * 100).toFixed(1),
|
|
616
700
|
uncached: uncachedTokens.toLocaleString(),
|
|
617
701
|
})}
|
|
702
|
+
${billing}
|
|
618
703
|
|
|
619
704
|
${t('commands.context_tokens.footer')}
|
|
620
705
|
`,
|
|
@@ -3360,6 +3445,19 @@ const usageCmd: CommandHandler = (ctx) => {
|
|
|
3360
3445
|
}
|
|
3361
3446
|
|
|
3362
3447
|
const apiTotal = summary.apiInputTokens + summary.apiOutputTokens
|
|
3448
|
+
// 缓存读/写单独一行:它们不在 inputTokens 里(四桶不相交),不列出来就等于
|
|
3449
|
+
// 告诉用户这次会话没走缓存。
|
|
3450
|
+
const cacheRead = summary.apiCacheReadTokens ?? 0
|
|
3451
|
+
const cacheWrite = summary.apiCacheWriteTokens ?? 0
|
|
3452
|
+
const billedInput = summary.apiInputTokens + cacheRead + cacheWrite
|
|
3453
|
+
const cacheLine =
|
|
3454
|
+
cacheRead > 0 || cacheWrite > 0
|
|
3455
|
+
? `\n${t('commands.usage.cache_tokens', {
|
|
3456
|
+
read: cacheRead.toLocaleString(),
|
|
3457
|
+
write: cacheWrite.toLocaleString(),
|
|
3458
|
+
ratio: billedInput > 0 ? ((cacheRead / billedInput) * 100).toFixed(1) : '0.0',
|
|
3459
|
+
})}`
|
|
3460
|
+
: ''
|
|
3363
3461
|
const apiLine =
|
|
3364
3462
|
summary.apiInputTokens > 0 || summary.apiOutputTokens > 0
|
|
3365
3463
|
? t('commands.usage.api_tokens', {
|
|
@@ -3381,7 +3479,7 @@ const usageCmd: CommandHandler = (ctx) => {
|
|
|
3381
3479
|
return {
|
|
3382
3480
|
content: stripIndent`
|
|
3383
3481
|
${t('commands.usage.title')}
|
|
3384
|
-
${apiLine}
|
|
3482
|
+
${apiLine}${cacheLine}
|
|
3385
3483
|
${t('commands.usage.context_line', { est: estTokens.toLocaleString(), max: maxTokensShown.toLocaleString(), pct })}
|
|
3386
3484
|
${t('commands.usage.messages_line', { count: String(msgs.length) })}
|
|
3387
3485
|
${t('commands.usage.provider_line', { provider: ctx.providerId })}
|
package/src/ui/graft-status.tsx
CHANGED
|
@@ -27,6 +27,17 @@ function sameStats(a: GraftStats | null, b: GraftStats | null): boolean {
|
|
|
27
27
|
/** 重读间隔。与 `goal-progress` / `workflow-progress` 同法(那两处也是 1s 一拍)。 */
|
|
28
28
|
const STATS_REFRESH_MS = 1000
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* 会话计费 token 的紧凑写法:`999 tok` / `12.3k tok` / `1.2M tok`。
|
|
32
|
+
* 页脚是单行,四位以上的原数会把 `ctx` 与 `last:` 挤出去。
|
|
33
|
+
*/
|
|
34
|
+
export function formatCompactTokens(tokens: number): string {
|
|
35
|
+
const trim = (v: number): string => v.toFixed(1).replace(/\.0$/, '')
|
|
36
|
+
if (tokens < 1_000) return `${tokens} tok`
|
|
37
|
+
if (tokens < 1_000_000) return `${trim(tokens / 1_000)}k tok`
|
|
38
|
+
return `${trim(tokens / 1_000_000)}M tok`
|
|
39
|
+
}
|
|
40
|
+
|
|
30
41
|
/**
|
|
31
42
|
* Bottom-of-screen graft status line — mirrors graft's own "◤ graft · …" bar:
|
|
32
43
|
* ◤ graft · N nodes / E edges · ✓ synced · ~T tok saved
|
|
@@ -43,7 +54,16 @@ const STATS_REFRESH_MS = 1000
|
|
|
43
54
|
* 其余同前:tok-saved 每次渲染实时读;只在有 graft 图或有已知 ctx% 时渲染 —— ctx% 行
|
|
44
55
|
* 在本目录没建过 graft 时也照常显示。
|
|
45
56
|
*/
|
|
46
|
-
export function GraftStatusLine({
|
|
57
|
+
export function GraftStatusLine({
|
|
58
|
+
cwd,
|
|
59
|
+
ctxPct,
|
|
60
|
+
tokens,
|
|
61
|
+
}: {
|
|
62
|
+
cwd: string
|
|
63
|
+
ctxPct?: number
|
|
64
|
+
/** 本会话的计费 token 合计(四桶)。0/undefined ⇒ 不显示,不以 0 tok 冒充。 */
|
|
65
|
+
tokens?: number
|
|
66
|
+
}) {
|
|
47
67
|
const [stats, setStats] = useState(() => findGraftStats(cwd))
|
|
48
68
|
|
|
49
69
|
useEffect(() => {
|
|
@@ -54,13 +74,15 @@ export function GraftStatusLine({ cwd, ctxPct }: { cwd: string; ctxPct?: number
|
|
|
54
74
|
return () => clearInterval(timer)
|
|
55
75
|
}, [cwd])
|
|
56
76
|
const showCtx = typeof ctxPct === 'number'
|
|
57
|
-
|
|
77
|
+
const showTokens = typeof tokens === 'number' && tokens > 0
|
|
78
|
+
if (!stats && !showCtx && !showTokens) return null
|
|
58
79
|
const fresh = stats ? freshnessSegment(stats) : null
|
|
59
80
|
const saved = getGraftSavings()
|
|
60
81
|
const lastFile = stats?.lastFile ? basename(stats.lastFile) : null
|
|
61
82
|
|
|
62
83
|
const bottom: string[] = []
|
|
63
84
|
if (typeof ctxPct === 'number') bottom.push(`ctx ${ctxPct}%`)
|
|
85
|
+
if (showTokens) bottom.push(formatCompactTokens(tokens))
|
|
64
86
|
if (lastFile) bottom.push(`last: ${lastFile}`)
|
|
65
87
|
|
|
66
88
|
return (
|