@miphamai/cli 0.85.49 → 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.
@@ -25,12 +25,22 @@ export function recordLlm(inner: Llm): { llm: Llm; turns: RecordedTurn[] } {
25
25
 
26
26
  /** 回放已记录的 turns(确定性、无网络)。按顺序消费,超出则静默结束。 */
27
27
  export function replayLlm(turns: RecordedTurn[]): Llm {
28
+ return replayChunks(turns.map((turn) => turn.chunks))
29
+ }
30
+
31
+ /**
32
+ * 只回放响应流、不带请求。
33
+ *
34
+ * `RecordedTurn.req` 里嵌着录制时的完整系统提示(本机 cwd、指令文件内容),
35
+ * 不适合提交进仓库;而回放本就忽略请求。提交的夹具用这个形状。
36
+ */
37
+ export function replayChunks(sequences: StreamChunk[][]): Llm {
28
38
  let cursor = 0
29
39
  return {
30
40
  async *chat() {
31
- const turn = turns[cursor++]
32
- if (!turn) return
33
- for (const chunk of turn.chunks) yield chunk
41
+ const chunks = sequences[cursor++]
42
+ if (!chunks) return
43
+ for (const chunk of chunks) yield chunk
34
44
  },
35
45
  }
36
46
  }
@@ -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: parsed.usage.prompt_tokens,
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.49' as const
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 = 5332 as const
93
+ export const TEST_COUNT = 5446 as const
@@ -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
- /** API-reported input token count (type: 'usage'). */
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'`).
@@ -3,6 +3,7 @@ import { existsSync } from 'node:fs'
3
3
  import type { ToolDefinition, CredentialMaskingConfig } from '../../shared/index.ts'
4
4
  import { sanitizeCommand } from '../../shared/sanitize.ts'
5
5
  import { DANGEROUS_GIT_PATTERNS } from './git.ts'
6
+ import { getMetrics } from '../../core/metrics'
6
7
  import { isUncOrDevicePath, isWithin } from '../../security/path.ts'
7
8
  import { findWorktreeMarker } from '../../core/paths.ts'
8
9
  import { splitShellSegments, expandKnownPathVars } from '../../core/permission-rules'
@@ -156,7 +157,21 @@ function normalizeEscapes(command: string): string {
156
157
  )
157
158
  }
158
159
 
159
- export function isBlocked(command: string): string | null {
160
+ type BlockReason = 'blocked-command' | 'dangerous-git' | 'unc-path' | 'blocked-pattern'
161
+
162
+ interface BlockVerdict {
163
+ reason: BlockReason
164
+ message: string
165
+ }
166
+
167
+ /**
168
+ * Classify a command against the static policy, keeping *which* rule fired.
169
+ *
170
+ * The reason is the point: a bare "rejected by security policy" is
171
+ * indistinguishable from the SIS / permission gates, so whoever reports on the
172
+ * rejection has to guess — and named the wrong subsystem on 2026-11-26.
173
+ */
174
+ function classifyBlocked(command: string): BlockVerdict | null {
160
175
  // Normalize ANSI-C escape sequences for defense-in-depth
161
176
  const normalized = normalizeEscapes(command)
162
177
  // P0-1: Also sanitize for permission check (strips invisible chars, normalizes homoglyphs)
@@ -172,7 +187,10 @@ export function isBlocked(command: string): string | null {
172
187
  ...commandWords(sanitized),
173
188
  ]) {
174
189
  if (BLOCKED_COMMANDS.includes(word)) {
175
- return `Command "${word}" rejected by security policy.`
190
+ return {
191
+ reason: 'blocked-command',
192
+ message: `Command "${word}" rejected by security policy.`,
193
+ }
176
194
  }
177
195
  }
178
196
 
@@ -184,7 +202,10 @@ export function isBlocked(command: string): string | null {
184
202
  if (/(?:^|[\s;&|])(?:sudo\s+)?git\s+/.test(normalized)) {
185
203
  for (const { pattern, description } of DANGEROUS_GIT_PATTERNS) {
186
204
  if (pattern.test(normalized)) {
187
- return `Dangerous git command blocked: "${description}". Run manually if intended.`
205
+ return {
206
+ reason: 'dangerous-git',
207
+ message: `Dangerous git command blocked: "${description}". Run manually if intended.`,
208
+ }
188
209
  }
189
210
  }
190
211
  }
@@ -192,19 +213,30 @@ export function isBlocked(command: string): string | null {
192
213
  // Reject UNC / device-namespace paths — accessing one triggers SMB negotiation
193
214
  // on Windows and silently leaks NTLM credentials (Claude Code 2.1.233 CVE-class fix).
194
215
  if (isUncOrDevicePath(command) || isUncOrDevicePath(normalized) || isUncOrDevicePath(sanitized)) {
195
- return `Command rejected: references a UNC or device-namespace path (blocked to prevent NTLM credential leakage).`
216
+ return {
217
+ reason: 'unc-path',
218
+ message: `Command rejected: references a UNC or device-namespace path (blocked to prevent NTLM credential leakage).`,
219
+ }
196
220
  }
197
221
 
198
222
  // Check dangerous patterns (on original, normalized, and sanitized)
199
223
  for (const pattern of BLOCKED_PATTERNS) {
200
224
  if (pattern.test(command) || pattern.test(normalized) || pattern.test(sanitized)) {
201
- return 'Command rejected by security policy.'
225
+ return {
226
+ reason: 'blocked-pattern',
227
+ message: `Command rejected by security policy (pattern: ${pattern.source}).`,
228
+ }
202
229
  }
203
230
  }
204
231
 
205
232
  return null // safe
206
233
  }
207
234
 
235
+ /** The user-facing rejection message, or null when the command may run. */
236
+ export function isBlocked(command: string): string | null {
237
+ return classifyBlocked(command)?.message ?? null
238
+ }
239
+
208
240
  /**
209
241
  * Git commands that rewrite refs a worktree **shares with the main checkout**.
210
242
  *
@@ -890,9 +922,12 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
890
922
  }
891
923
 
892
924
  // Security: check command against deny list
893
- const blockedReason = isBlocked(command)
894
- if (blockedReason) {
895
- return { success: false, content: '', error: blockedReason }
925
+ // Counted at the enforcement point, not inside `isBlocked`: the red team and
926
+ // tests call `isBlocked` for diagnosis, and those are not real blocks.
927
+ const blocked = classifyBlocked(command)
928
+ if (blocked) {
929
+ getMetrics().policyBlockInterceptions.inc({ reason: blocked.reason })
930
+ return { success: false, content: '', error: blocked.message }
896
931
  }
897
932
 
898
933
  try {
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 cwd={process.cwd()} ctxPct={contextUsagePct(engine)} />
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. */}