@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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/agent/sub-agent.ts +24 -1
- package/src/core/auto-corrector.ts +0 -8
- package/src/core/auto-memory.ts +13 -0
- package/src/core/capability-inventory.ts +112 -18
- package/src/core/crsi-inbox.ts +230 -0
- package/src/core/engine.ts +37 -1
- package/src/core/error-signature-db.ts +68 -11
- package/src/core/eval-harness.ts +43 -4
- package/src/core/immune-memory-gc.ts +5 -5
- package/src/core/metrics.ts +13 -0
- package/src/core/preflight-checker.ts +12 -0
- package/src/core/task-performance.ts +6 -1
- package/src/core/tool-gate.ts +20 -2
- 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 +14 -2
- package/src/i18n-core/locales/zh-CN.json +14 -2
- package/src/index.tsx +15 -0
- package/src/providers/anthropic.ts +17 -2
- package/src/providers/llm-replay.ts +13 -3
- 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/tools/exec/bash.ts +43 -8
- package/src/ui/app.tsx +17 -1
- package/src/ui/commands.ts +215 -17
- package/src/ui/graft-status.tsx +24 -2
|
@@ -41,6 +41,8 @@ export interface ErrorSignature {
|
|
|
41
41
|
occurrences: number
|
|
42
42
|
/** Number of times the fix was applied successfully */
|
|
43
43
|
successCount: number
|
|
44
|
+
/** Number of times the fix was applied and the call still failed */
|
|
45
|
+
failureCount: number
|
|
44
46
|
/** ISO timestamp of first encounter */
|
|
45
47
|
firstSeen: string
|
|
46
48
|
/** ISO timestamp of most recent encounter */
|
|
@@ -56,6 +58,12 @@ export interface ErrorSignatureStats {
|
|
|
56
58
|
active: number
|
|
57
59
|
degraded: number
|
|
58
60
|
retired: number
|
|
61
|
+
/**
|
|
62
|
+
* Active signatures whose strategy applies a fix (`replace`/`prepend`/`append`).
|
|
63
|
+
* `avgSuccessRate` is averaged over these only — `warn`/`block` have no fix to
|
|
64
|
+
* succeed, and counting their 0es made every advisory look like a failed fix.
|
|
65
|
+
*/
|
|
66
|
+
fixable: number
|
|
59
67
|
avgSuccessRate: number
|
|
60
68
|
totalInterceptions: number
|
|
61
69
|
}
|
|
@@ -66,6 +74,24 @@ const DEFAULT_STORE_DIR = miphamHome('sis')
|
|
|
66
74
|
const STORE_FILE = 'error-signatures.json'
|
|
67
75
|
const MIN_SUCCESS_RATE = 0.5 // below this → degraded
|
|
68
76
|
const RETIREMENT_RATE = 0.2 // below this and > 90 days old → retired
|
|
77
|
+
/**
|
|
78
|
+
* Attempts needed before an outcome can degrade a signature. One failed call is
|
|
79
|
+
* noise, not a verdict — degrading on it would retire a fix the first time it
|
|
80
|
+
* met a flaky command.
|
|
81
|
+
*/
|
|
82
|
+
const MIN_ATTEMPTS_FOR_DEGRADE = 3
|
|
83
|
+
|
|
84
|
+
/** Strategies that actually apply a fix. `warn`/`block` never do. */
|
|
85
|
+
export function isAutoFixable(sig: Pick<ErrorSignature, 'fixStrategy'>): boolean {
|
|
86
|
+
return (
|
|
87
|
+
sig.fixStrategy === 'replace' || sig.fixStrategy === 'prepend' || sig.fixStrategy === 'append'
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The fix-success rate, or `—` when the strategy does not apply a fix. */
|
|
92
|
+
export function formatFixRate(sig: ErrorSignature): string {
|
|
93
|
+
return isAutoFixable(sig) ? `${Math.round(sig.successRate * 100)}%` : '—'
|
|
94
|
+
}
|
|
69
95
|
const RETENTION_DAYS = 90 // auto-clean retired signatures older than this
|
|
70
96
|
|
|
71
97
|
// ── Database ──
|
|
@@ -94,6 +120,9 @@ export class ErrorSignatureDB {
|
|
|
94
120
|
if (!Array.isArray(parsed)) return
|
|
95
121
|
for (const sig of parsed) {
|
|
96
122
|
if (!sig || typeof sig !== 'object' || typeof sig.id !== 'string') continue
|
|
123
|
+
// Stores written before 2026-11-26 have no `failureCount`; without this,
|
|
124
|
+
// the first `failureCount + 1` is NaN and the rate silently becomes NaN.
|
|
125
|
+
if (typeof sig.failureCount !== 'number') sig.failureCount = 0
|
|
97
126
|
this.signatures.set(sig.id, sig)
|
|
98
127
|
}
|
|
99
128
|
} catch {
|
|
@@ -123,7 +152,14 @@ export class ErrorSignatureDB {
|
|
|
123
152
|
insert(
|
|
124
153
|
sig: Omit<
|
|
125
154
|
ErrorSignature,
|
|
126
|
-
|
|
155
|
+
| 'id'
|
|
156
|
+
| 'occurrences'
|
|
157
|
+
| 'successCount'
|
|
158
|
+
| 'failureCount'
|
|
159
|
+
| 'successRate'
|
|
160
|
+
| 'firstSeen'
|
|
161
|
+
| 'lastSeen'
|
|
162
|
+
| 'status'
|
|
127
163
|
>,
|
|
128
164
|
): ErrorSignature {
|
|
129
165
|
// Dedup: same pattern + toolName + category → update existing
|
|
@@ -145,7 +181,8 @@ export class ErrorSignatureDB {
|
|
|
145
181
|
id,
|
|
146
182
|
occurrences: 1,
|
|
147
183
|
successCount: 0,
|
|
148
|
-
|
|
184
|
+
failureCount: 0,
|
|
185
|
+
successRate: 0,
|
|
149
186
|
firstSeen: now,
|
|
150
187
|
lastSeen: now,
|
|
151
188
|
status: 'active',
|
|
@@ -195,24 +232,40 @@ export class ErrorSignatureDB {
|
|
|
195
232
|
|
|
196
233
|
/**
|
|
197
234
|
* Record the result of applying a fix for a given signature.
|
|
198
|
-
*
|
|
235
|
+
*
|
|
236
|
+
* Only signatures whose strategy actually applies a fix are scored — `warn`
|
|
237
|
+
* and `block` have no outcome, and counting one drove every advisory to 0%
|
|
238
|
+
* (2026-11-26: 10 signatures, 202 occurrences, 0 successes, while this method
|
|
239
|
+
* had no production caller). The denominator is **attempts**, not occurrences:
|
|
240
|
+
* a signature seen ten times but tried once has a rate of one trial.
|
|
199
241
|
*/
|
|
200
242
|
recordResult(id: string, success: boolean): void {
|
|
201
243
|
const sig = this.signatures.get(id)
|
|
202
244
|
if (!sig) return
|
|
245
|
+
if (!isAutoFixable(sig)) return
|
|
203
246
|
|
|
204
|
-
if (success)
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
247
|
+
if (success) sig.successCount++
|
|
248
|
+
else sig.failureCount++
|
|
249
|
+
|
|
250
|
+
const attempts = sig.successCount + sig.failureCount
|
|
251
|
+
sig.successRate = attempts > 0 ? sig.successCount / attempts : 0
|
|
208
252
|
|
|
209
|
-
// Auto-degrade
|
|
210
|
-
if (
|
|
253
|
+
// Auto-degrade — only after a real attempt history; one failure is noise.
|
|
254
|
+
if (
|
|
255
|
+
attempts >= MIN_ATTEMPTS_FOR_DEGRADE &&
|
|
256
|
+
sig.successRate < MIN_SUCCESS_RATE &&
|
|
257
|
+
sig.status === 'active'
|
|
258
|
+
) {
|
|
211
259
|
sig.status = 'degraded'
|
|
212
260
|
}
|
|
213
261
|
// Auto-retire
|
|
214
262
|
const ageDays = (Date.now() - new Date(sig.firstSeen).getTime()) / (1000 * 60 * 60 * 24)
|
|
215
|
-
if (
|
|
263
|
+
if (
|
|
264
|
+
attempts >= MIN_ATTEMPTS_FOR_DEGRADE &&
|
|
265
|
+
sig.successRate < RETIREMENT_RATE &&
|
|
266
|
+
ageDays > 90 &&
|
|
267
|
+
sig.status === 'degraded'
|
|
268
|
+
) {
|
|
216
269
|
sig.status = 'retired'
|
|
217
270
|
}
|
|
218
271
|
|
|
@@ -251,14 +304,18 @@ export class ErrorSignatureDB {
|
|
|
251
304
|
const degraded = all.filter((s) => s.status === 'degraded')
|
|
252
305
|
const retired = all.filter((s) => s.status === 'retired')
|
|
253
306
|
|
|
307
|
+
const fixableActive = active.filter(isAutoFixable)
|
|
254
308
|
const avgSuccessRate =
|
|
255
|
-
|
|
309
|
+
fixableActive.length > 0
|
|
310
|
+
? fixableActive.reduce((sum, s) => sum + s.successRate, 0) / fixableActive.length
|
|
311
|
+
: 0
|
|
256
312
|
|
|
257
313
|
return {
|
|
258
314
|
total: all.length,
|
|
259
315
|
active: active.length,
|
|
260
316
|
degraded: degraded.length,
|
|
261
317
|
retired: retired.length,
|
|
318
|
+
fixable: fixableActive.length,
|
|
262
319
|
avgSuccessRate: Math.round(avgSuccessRate * 100) / 100,
|
|
263
320
|
totalInterceptions: all.reduce((sum, s) => sum + s.occurrences, 0),
|
|
264
321
|
}
|
package/src/core/eval-harness.ts
CHANGED
|
@@ -177,14 +177,48 @@ export function appendEvalScore(
|
|
|
177
177
|
}
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
-
/**
|
|
181
|
-
|
|
180
|
+
/** One eval ledger line. Old records may lack counts or a timestamp. */
|
|
181
|
+
interface EvalLedgerLine {
|
|
182
|
+
name?: string
|
|
183
|
+
score?: number
|
|
184
|
+
passed?: number
|
|
185
|
+
total?: number
|
|
186
|
+
timestamp?: string
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** One eval ledger entry, with the timestamp that makes it citable. */
|
|
190
|
+
export interface LastEvalEntry {
|
|
191
|
+
score: number
|
|
192
|
+
passed: number
|
|
193
|
+
total: number
|
|
194
|
+
/** ISO timestamp, or `unknown` for records written before timestamps were kept. */
|
|
195
|
+
timestamp: string
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* 读取某奖励函数最近一次分数**及其时间戳**。
|
|
200
|
+
*
|
|
201
|
+
* 分数单独一个数字无法回答「什么时候测的」—— 而不可追溯的数字正是 2026-11-26
|
|
202
|
+
* 那次自评里被文档值冒充实测值的缺口。报告层要的是带出处的数。
|
|
203
|
+
*/
|
|
204
|
+
export function getLastEvalEntry(name: string): LastEvalEntry | null {
|
|
182
205
|
try {
|
|
183
206
|
if (!existsSync(SCORES_FILE)) return null
|
|
184
207
|
const lines = readFileSync(SCORES_FILE, 'utf-8').trim().split('\n').filter(Boolean)
|
|
185
208
|
for (let i = lines.length - 1; i >= 0; i--) {
|
|
186
|
-
|
|
187
|
-
|
|
209
|
+
let rec: EvalLedgerLine
|
|
210
|
+
try {
|
|
211
|
+
rec = JSON.parse(lines[i]!) as EvalLedgerLine
|
|
212
|
+
} catch {
|
|
213
|
+
continue
|
|
214
|
+
}
|
|
215
|
+
if (rec.name !== name || typeof rec.score !== 'number') continue
|
|
216
|
+
return {
|
|
217
|
+
score: rec.score,
|
|
218
|
+
passed: typeof rec.passed === 'number' ? rec.passed : 0,
|
|
219
|
+
total: typeof rec.total === 'number' ? rec.total : 0,
|
|
220
|
+
timestamp: typeof rec.timestamp === 'string' ? rec.timestamp : 'unknown',
|
|
221
|
+
}
|
|
188
222
|
}
|
|
189
223
|
return null
|
|
190
224
|
} catch {
|
|
@@ -192,6 +226,11 @@ export function getLastEvalScore(name: string): number | null {
|
|
|
192
226
|
}
|
|
193
227
|
}
|
|
194
228
|
|
|
229
|
+
/** 读取某奖励函数最近一次分数(无记录时返回 null)。旧无 name 记录自然跳过。 */
|
|
230
|
+
export function getLastEvalScore(name: string): number | null {
|
|
231
|
+
return getLastEvalEntry(name)?.score ?? null
|
|
232
|
+
}
|
|
233
|
+
|
|
195
234
|
/**
|
|
196
235
|
* 某奖励函数最近 n 次**按契约粒度**落盘的记录,新→旧。
|
|
197
236
|
*
|
|
@@ -89,11 +89,11 @@ export class ImmuneMemoryGC {
|
|
|
89
89
|
const active = this.errorDB.getActive()
|
|
90
90
|
|
|
91
91
|
for (const sig of active) {
|
|
92
|
-
if
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
) {
|
|
92
|
+
// "Never succeeded" only means something if the fix was ever *tried*.
|
|
93
|
+
// `warn`/`block` signatures have no fix (attempts stay 0), so retiring
|
|
94
|
+
// them here would delete exactly the advisories that fire most.
|
|
95
|
+
const attempts = sig.successCount + sig.failureCount
|
|
96
|
+
if (attempts >= ZERO_SUCCESS_THRESHOLD && sig.successCount === 0) {
|
|
97
97
|
this.errorDB.retire(sig.id)
|
|
98
98
|
count++
|
|
99
99
|
}
|
package/src/core/metrics.ts
CHANGED
|
@@ -302,6 +302,14 @@ export class MetricsRegistry {
|
|
|
302
302
|
/** SIS immune system interceptions (block/fix of known error patterns). */
|
|
303
303
|
readonly sisInterceptions: Counter
|
|
304
304
|
|
|
305
|
+
/**
|
|
306
|
+
* Bash commands blocked by the **static** security policy, labelled by rule
|
|
307
|
+
* class. Deliberately *not* in `COUNTER_WHITELIST`: it exists so the caller can
|
|
308
|
+
* tell a static-policy block from an SIS / permission block, which is local
|
|
309
|
+
* diagnosis, not a telemetry dimension.
|
|
310
|
+
*/
|
|
311
|
+
readonly policyBlockInterceptions: Counter
|
|
312
|
+
|
|
305
313
|
constructor() {
|
|
306
314
|
// Pre-register standard metrics
|
|
307
315
|
this.cliInvocations = this.counter(
|
|
@@ -348,6 +356,11 @@ export class MetricsRegistry {
|
|
|
348
356
|
'mipham_code_sis_interceptions_total',
|
|
349
357
|
'Number of SIS immune system interceptions',
|
|
350
358
|
)
|
|
359
|
+
|
|
360
|
+
this.policyBlockInterceptions = this.counter(
|
|
361
|
+
'mipham_code_policy_block_interceptions_total',
|
|
362
|
+
'Number of Bash commands blocked by the static security policy',
|
|
363
|
+
)
|
|
351
364
|
}
|
|
352
365
|
|
|
353
366
|
// ── Factory methods ─────────────────────────────────────────────
|
|
@@ -95,6 +95,18 @@ export class PreFlightChecker {
|
|
|
95
95
|
this.ruleEngine = ruleEngine
|
|
96
96
|
}
|
|
97
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Score an outcome against a signature this checker matched and fixed.
|
|
100
|
+
*
|
|
101
|
+
* The pre-flight applies `replace`/`prepend`/`append` fixes before the tool
|
|
102
|
+
* runs; only the caller sees whether that call succeeded, so the outcome comes
|
|
103
|
+
* back through here. Both tool funnels (engine and sub-agent) call it — one
|
|
104
|
+
* path alone would leave half the fixes unrated.
|
|
105
|
+
*/
|
|
106
|
+
recordOutcome(signatureId: string, success: boolean): void {
|
|
107
|
+
this.errorDB.recordResult(signatureId, success)
|
|
108
|
+
}
|
|
109
|
+
|
|
98
110
|
// ── Private: Signature Conversion ──
|
|
99
111
|
|
|
100
112
|
/**
|
|
@@ -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.
|
package/src/core/tool-gate.ts
CHANGED
|
@@ -39,7 +39,17 @@ export interface ToolGateDeps {
|
|
|
39
39
|
|
|
40
40
|
export type ToolGateOutcome =
|
|
41
41
|
| { ok: false; content: string; error: string; notRun?: boolean }
|
|
42
|
-
| {
|
|
42
|
+
| {
|
|
43
|
+
ok: true
|
|
44
|
+
params: Record<string, unknown>
|
|
45
|
+
warnings: string[]
|
|
46
|
+
/**
|
|
47
|
+
* Set when the SIS pre-flight applied a signature's fix. The caller scores
|
|
48
|
+
* the outcome against this id after the tool runs — without it, `successRate`
|
|
49
|
+
* can never move and the confidence gate never opens (2026-11-26).
|
|
50
|
+
*/
|
|
51
|
+
sisFixSignature?: string
|
|
52
|
+
}
|
|
43
53
|
|
|
44
54
|
/**
|
|
45
55
|
* The text a principle's `audit_pattern` is matched against.
|
|
@@ -73,6 +83,8 @@ export async function runPreToolGate(
|
|
|
73
83
|
): Promise<ToolGateOutcome> {
|
|
74
84
|
let effectiveParams = params
|
|
75
85
|
const warnings: string[] = []
|
|
86
|
+
/** The SIS signature whose fix was applied, if any — scored by the caller. */
|
|
87
|
+
let sisFixSignature: string | undefined
|
|
76
88
|
|
|
77
89
|
// ── PreToolUse hook ──
|
|
78
90
|
if (deps.hookEngine) {
|
|
@@ -155,6 +167,7 @@ export async function runPreToolGate(
|
|
|
155
167
|
if (preflight.action === 'fix' && preflight.modifiedParams) {
|
|
156
168
|
getMetrics().sisInterceptions.inc()
|
|
157
169
|
effectiveParams = preflight.modifiedParams
|
|
170
|
+
sisFixSignature = preflight.matchedSignature
|
|
158
171
|
if (preflight.warning) {
|
|
159
172
|
warnings.push(preflight.warning)
|
|
160
173
|
}
|
|
@@ -224,5 +237,10 @@ export async function runPreToolGate(
|
|
|
224
237
|
}
|
|
225
238
|
}
|
|
226
239
|
|
|
227
|
-
return {
|
|
240
|
+
return {
|
|
241
|
+
ok: true,
|
|
242
|
+
params: effectiveParams,
|
|
243
|
+
warnings,
|
|
244
|
+
...(sisFixSignature ? { sisFixSignature } : {}),
|
|
245
|
+
}
|
|
228
246
|
}
|
|
@@ -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}",
|
|
@@ -593,7 +605,7 @@
|
|
|
593
605
|
"no_sigs_for_tool": "No error signatures for tool `{tool}`. CRSI immune memory is clean for this tool.",
|
|
594
606
|
"no_sigs": "No active error signatures. CRSI immune memory is clean.",
|
|
595
607
|
"sigs_title": "### 🛡️ Error Signatures{tool}",
|
|
596
|
-
"sig_success": " Success: {bar} {pct}
|
|
608
|
+
"sig_success": " Success: {bar} {pct} | {occurrences}x | {strategy}",
|
|
597
609
|
"sig_fix": " Fix: `{fix}`",
|
|
598
610
|
"sigs_more": "... and {count} more signatures",
|
|
599
611
|
"reflection_title": "### 📊 CRSI Reflection Summary",
|
|
@@ -672,7 +684,7 @@
|
|
|
672
684
|
"provider": "- **Provider**: {provider}",
|
|
673
685
|
"model": "- **Model**: {model}",
|
|
674
686
|
"sigs_title": "### Active Error Signatures",
|
|
675
|
-
"sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}x, {pct}
|
|
687
|
+
"sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}x, {pct} success)",
|
|
676
688
|
"disabled_hooks": "### Disabled Hooks",
|
|
677
689
|
"hook_entry": "- `{key}`: {failures} failures, disabled at {time}",
|
|
678
690
|
"last_dream": "### Last Auto-Dream",
|
|
@@ -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}",
|
|
@@ -593,7 +605,7 @@
|
|
|
593
605
|
"no_sigs_for_tool": "工具 `{tool}` 没有错误签名。该工具的 CRSI 免疫记忆是干净的。",
|
|
594
606
|
"no_sigs": "没有活跃的错误签名。CRSI 免疫记忆是干净的。",
|
|
595
607
|
"sigs_title": "### 🛡️ 错误签名{tool}",
|
|
596
|
-
"sig_success": " 成功率: {bar} {pct}
|
|
608
|
+
"sig_success": " 成功率: {bar} {pct} | {occurrences}次 | {strategy}",
|
|
597
609
|
"sig_fix": " 修复: `{fix}`",
|
|
598
610
|
"sigs_more": "... 还有 {count} 条签名",
|
|
599
611
|
"reflection_title": "### 📊 CRSI 反思摘要",
|
|
@@ -672,7 +684,7 @@
|
|
|
672
684
|
"provider": "- **提供商**: {provider}",
|
|
673
685
|
"model": "- **模型**: {model}",
|
|
674
686
|
"sigs_title": "### 活跃错误签名",
|
|
675
|
-
"sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}次, {pct}
|
|
687
|
+
"sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}次, {pct} 成功率)",
|
|
676
688
|
"disabled_hooks": "### 已禁用的 Hooks",
|
|
677
689
|
"hook_entry": "- `{key}`: {failures} 次失败, 于 {time} 禁用",
|
|
678
690
|
"last_dream": "### 最近一次 Auto-Dream",
|
package/src/index.tsx
CHANGED
|
@@ -905,6 +905,21 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
905
905
|
process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
|
|
906
906
|
}
|
|
907
907
|
|
|
908
|
+
// CRSI 收件箱:上个会话(或更早)攒下的失败信号 → 自动渲染成待并入教训。
|
|
909
|
+
// 这一段不需要人在场 —— 信号在每轮 persist 时已同步落盘,这里只负责产出。
|
|
910
|
+
// 合并仍走 `/crsi propose --pending` → 沙箱 → 批准,自动化的是「产出」不是「合并」。
|
|
911
|
+
try {
|
|
912
|
+
const { refreshPendingLessons } = await import('./core/crsi-inbox')
|
|
913
|
+
const pending = refreshPendingLessons(process.cwd())
|
|
914
|
+
if (pending.total > 0) {
|
|
915
|
+
process.stderr.write(
|
|
916
|
+
`📚 CRSI: ${pending.total} 条教训已自动生成(/crsi propose --pending 并入)\n`,
|
|
917
|
+
)
|
|
918
|
+
}
|
|
919
|
+
} catch {
|
|
920
|
+
// 非关键路径:收件箱坏了不该影响启动
|
|
921
|
+
}
|
|
922
|
+
|
|
908
923
|
// Initialize agent registry and load plugin agents/skills/MCP/hooks
|
|
909
924
|
const agentRegistry = new AgentRegistry()
|
|
910
925
|
if (!safeMode) {
|
|
@@ -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
|