@miphamai/cli 0.85.48 → 0.85.50

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.
@@ -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
- 'id' | 'occurrences' | 'successCount' | 'successRate' | 'firstSeen' | 'lastSeen' | 'status'
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
- successRate: 0, // starts at 0 — must prove itself before auto-apply
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
- * Updates success rate and may auto-degrade/retire low-performing signatures.
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
- sig.successCount++
206
- }
207
- sig.successRate = sig.occurrences > 0 ? sig.successCount / sig.occurrences : 1.0
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 (sig.successRate < MIN_SUCCESS_RATE && sig.status === 'active') {
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 (sig.successRate < RETIREMENT_RATE && ageDays > 90 && sig.status === 'degraded') {
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
- active.length > 0 ? active.reduce((sum, s) => sum + s.successRate, 0) / active.length : 0
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
  }
@@ -177,14 +177,48 @@ export function appendEvalScore(
177
177
  }
178
178
  }
179
179
 
180
- /** 读取某奖励函数最近一次分数(无记录时返回 null)。旧无 name 记录自然跳过。 */
181
- export function getLastEvalScore(name: string): number | null {
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
- const rec = JSON.parse(lines[i]!) as { name?: string; score?: number }
187
- if (rec.name === name && typeof rec.score === 'number') return rec.score
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
  *
@@ -275,6 +275,29 @@ interface HookProcessResult {
275
275
  error?: { code?: string; message?: string }
276
276
  }
277
277
 
278
+ /**
279
+ * How much of each hook stream is buffered before the rest is dropped.
280
+ *
281
+ * A hook printing without end used to grow this process's heap for the whole
282
+ * timeout window (60s by default) — the event loop stayed live, but a `yes`-style
283
+ * hook still turned into gigabytes. Keep the first 1 MiB of each stream, which is
284
+ * far more than any structured hook payload, and leave a marker so the truncation
285
+ * is visible rather than silently changing the answer.
286
+ */
287
+ const MAX_HOOK_STREAM_CHARS = 1_000_000
288
+
289
+ /** Append one chunk to a capped stream buffer. Pure so the bound is testable. */
290
+ export function appendHookStreamChunk(
291
+ previous: string,
292
+ chunk: string,
293
+ cap: number = MAX_HOOK_STREAM_CHARS,
294
+ ): string {
295
+ if (previous.length > cap) return previous
296
+ const next = previous + chunk
297
+ if (next.length <= cap) return next
298
+ return `${next.slice(0, cap)}\n[hook output truncated: exceeded ${cap.toLocaleString('en-US')} characters]\n`
299
+ }
300
+
278
301
  /**
279
302
  * Run a hook command to completion, bounding **both** halves of the wait.
280
303
  *
@@ -368,10 +391,10 @@ async function runHookCommand(
368
391
  }
369
392
 
370
393
  child.stdout.on('data', (chunk: Buffer) => {
371
- stdout += chunk.toString()
394
+ stdout = appendHookStreamChunk(stdout, chunk.toString())
372
395
  })
373
396
  child.stderr.on('data', (chunk: Buffer) => {
374
- stderr += chunk.toString()
397
+ stderr = appendHookStreamChunk(stderr, chunk.toString())
375
398
  })
376
399
 
377
400
  child.on('error', (err: NodeJS.ErrnoException) => {
@@ -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
- sig.occurrences >= ZERO_SUCCESS_THRESHOLD &&
94
- sig.successCount === 0 &&
95
- sig.status === 'active'
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
  }
@@ -15,6 +15,7 @@ import {
15
15
  } from './crsi-producer'
16
16
  import { miphamHome } from './paths.ts'
17
17
  import { safeSlice } from '../shared/sanitize'
18
+ import { readRegularFileSync } from '../shared/regular-file'
18
19
 
19
20
  export interface FrontmatterResult {
20
21
  data: Record<string, unknown>
@@ -765,9 +766,13 @@ Never omit it or present the work as purely human-authored.`)
765
766
  const changed: string[] = []
766
767
  for (const inst of this.instructions) {
767
768
  if (this.isUnsafePath(inst.path, inst.level)) continue
768
- if (!existsSync(inst.path)) continue
769
+ // Type, not existence: `existsSync` is true for a FIFO, and reading one
770
+ // with no writer blocks forever inside a synchronous call (the same gate
771
+ // `rules-loader.ts` already uses for rule files).
772
+ const raw = readRegularFileSync(inst.path)
773
+ if (raw === null) continue
769
774
  try {
770
- const { data, content } = parseFrontmatter(readFileSync(inst.path, 'utf-8'))
775
+ const { data, content } = parseFrontmatter(raw)
771
776
  const next = capInstructionContent(content, inst.path)
772
777
  if (next !== inst.content) {
773
778
  inst.content = next
@@ -788,8 +793,12 @@ Never omit it or present the work as purely human-authored.`)
788
793
 
789
794
  if (this.isUnsafePath(path, level)) return
790
795
 
796
+ // A FIFO/socket/device here would block the startup read forever; treat it
797
+ // as "nothing to load" instead of waiting on a writer that may never come.
798
+ const raw = readRegularFileSync(path)
799
+ if (raw === null) return
800
+
791
801
  try {
792
- const raw = readFileSync(path, 'utf-8')
793
802
  const { data, content } = parseFrontmatter(raw)
794
803
  this.instructions.push({
795
804
  path,
@@ -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
  /**
@@ -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
- | { ok: true; params: Record<string, unknown>; warnings: string[] }
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 { ok: true, params: effectiveParams, warnings }
240
+ return {
241
+ ok: true,
242
+ params: effectiveParams,
243
+ warnings,
244
+ ...(sisFixSignature ? { sisFixSignature } : {}),
245
+ }
228
246
  }
@@ -593,7 +593,7 @@
593
593
  "no_sigs_for_tool": "No error signatures for tool `{tool}`. CRSI immune memory is clean for this tool.",
594
594
  "no_sigs": "No active error signatures. CRSI immune memory is clean.",
595
595
  "sigs_title": "### 🛡️ Error Signatures{tool}",
596
- "sig_success": " Success: {bar} {pct}% | {occurrences}x | {strategy}",
596
+ "sig_success": " Success: {bar} {pct} | {occurrences}x | {strategy}",
597
597
  "sig_fix": " Fix: `{fix}`",
598
598
  "sigs_more": "... and {count} more signatures",
599
599
  "reflection_title": "### 📊 CRSI Reflection Summary",
@@ -672,7 +672,7 @@
672
672
  "provider": "- **Provider**: {provider}",
673
673
  "model": "- **Model**: {model}",
674
674
  "sigs_title": "### Active Error Signatures",
675
- "sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}x, {pct}% success)",
675
+ "sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}x, {pct} success)",
676
676
  "disabled_hooks": "### Disabled Hooks",
677
677
  "hook_entry": "- `{key}`: {failures} failures, disabled at {time}",
678
678
  "last_dream": "### Last Auto-Dream",
@@ -758,6 +758,9 @@
758
758
  "user": {
759
759
  "role_label": "User"
760
760
  },
761
+ "compaction": {
762
+ "role_label": "Summary"
763
+ },
761
764
  "input": {
762
765
  "placeholder": "Type a message (Esc to clear)..."
763
766
  },
@@ -593,7 +593,7 @@
593
593
  "no_sigs_for_tool": "工具 `{tool}` 没有错误签名。该工具的 CRSI 免疫记忆是干净的。",
594
594
  "no_sigs": "没有活跃的错误签名。CRSI 免疫记忆是干净的。",
595
595
  "sigs_title": "### 🛡️ 错误签名{tool}",
596
- "sig_success": " 成功率: {bar} {pct}% | {occurrences}次 | {strategy}",
596
+ "sig_success": " 成功率: {bar} {pct} | {occurrences}次 | {strategy}",
597
597
  "sig_fix": " 修复: `{fix}`",
598
598
  "sigs_more": "... 还有 {count} 条签名",
599
599
  "reflection_title": "### 📊 CRSI 反思摘要",
@@ -672,7 +672,7 @@
672
672
  "provider": "- **提供商**: {provider}",
673
673
  "model": "- **模型**: {model}",
674
674
  "sigs_title": "### 活跃错误签名",
675
- "sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}次, {pct}% 成功率)",
675
+ "sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}次, {pct} 成功率)",
676
676
  "disabled_hooks": "### 已禁用的 Hooks",
677
677
  "hook_entry": "- `{key}`: {failures} 次失败, 于 {time} 禁用",
678
678
  "last_dream": "### 最近一次 Auto-Dream",
@@ -758,6 +758,9 @@
758
758
  "user": {
759
759
  "role_label": "用户"
760
760
  },
761
+ "compaction": {
762
+ "role_label": "摘要"
763
+ },
761
764
  "input": {
762
765
  "placeholder": "输入消息(Esc 清空)..."
763
766
  },
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) {
@@ -89,9 +89,18 @@ export class PluginManager {
89
89
  }
90
90
  }
91
91
 
92
- // Copy plugin directory
93
- mkdirSync(destDir, { recursive: true })
94
- this.copyDir(sourcePath, destDir)
92
+ // Copy plugin directory. A copy that dies halfway used to leave a partial
93
+ // directory behind, and the `already installed` check above then made every
94
+ // retry fail — a plugin that could never be installed until the user found
95
+ // and deleted the wreckage by hand.
96
+ try {
97
+ mkdirSync(destDir, { recursive: true })
98
+ this.copyDir(sourcePath, destDir)
99
+ } catch (err) {
100
+ rmSync(destDir, { recursive: true, force: true })
101
+ const detail = err instanceof Error ? err.message : String(err)
102
+ return { success: false, message: `Failed to copy plugin: ${detail}` }
103
+ }
95
104
 
96
105
  const similarWarning = this.findSimilarWarning(validation.manifest.name)
97
106
  this.plugins.push({
@@ -11,6 +11,7 @@ import {
11
11
  fetchWithRetry,
12
12
  streamIdleTimeoutMs,
13
13
  isRetryableFailure,
14
+ isAbortError,
14
15
  createAwakeTimer,
15
16
  readErrorBody,
16
17
  } from './fetch-utils'
@@ -263,6 +264,10 @@ export class AnthropicProvider implements ProviderInstance {
263
264
  }),
264
265
  ])
265
266
  } catch (err) {
267
+ // An abort is the caller leaving, not the stream stalling: wrapping it
268
+ // into a retryable error chunk made the engine retry a request the user
269
+ // had just cancelled.
270
+ if (isAbortError(err)) throw err
266
271
  yield { type: 'error', error: `Stream stalled: ${String(err)}` }
267
272
  return
268
273
  } finally {
@@ -108,8 +108,23 @@ function tlsCertCode(err: unknown): string | undefined {
108
108
  return undefined
109
109
  }
110
110
 
111
+ /**
112
+ * Was this failure the caller walking away?
113
+ *
114
+ * Providers used to wrap every stream-read rejection — aborts included — into a
115
+ * retryable `Stream stalled:` error chunk, which turned "the user pressed Esc"
116
+ * into "the request failed once, retrying". Abort has to stay an abort all the
117
+ * way out so the engine's own handler (and the UI) can tell the two apart.
118
+ */
119
+ export function isAbortError(err: unknown): boolean {
120
+ if (err instanceof Error && err.name === 'AbortError') return true
121
+ return (
122
+ typeof DOMException !== 'undefined' && err instanceof DOMException && err.name === 'AbortError'
123
+ )
124
+ }
125
+
111
126
  function isRetryableError(err: unknown): boolean {
112
- if (err instanceof DOMException && err.name === 'AbortError') return false
127
+ if (isAbortError(err)) return false
113
128
  if (tlsCertCode(err) !== undefined) return false
114
129
  return true
115
130
  }
@@ -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
  }
@@ -5,6 +5,7 @@ import {
5
5
  fetchWithRetry,
6
6
  streamIdleTimeoutMs,
7
7
  isRetryableFailure,
8
+ isAbortError,
8
9
  createAwakeTimer,
9
10
  readErrorBody,
10
11
  } from './fetch-utils'
@@ -142,6 +143,9 @@ export class OpenAICompatProvider implements ProviderInstance {
142
143
  }),
143
144
  ])
144
145
  } catch (err) {
146
+ // See anthropic.ts: an abort must stay an abort, not become a
147
+ // retryable "stream stalled" error chunk.
148
+ if (isAbortError(err)) throw err
145
149
  yield { type: 'error', error: `Stream stalled: ${String(err)}` }
146
150
  return
147
151
  } finally {
@@ -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.48' as const
12
+ export const PACKAGE_VERSION = '0.85.50' 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 = 5313 as const
93
+ export const TEST_COUNT = 5416 as const
@@ -29,12 +29,19 @@ export interface ShadowCheck {
29
29
  shadowed: boolean
30
30
  /** Name of the conflicting command/tool */
31
31
  conflictsWith: string
32
- /** Type of conflict: 'command' | 'mcp-tool' */
33
- conflictType: 'command' | 'mcp-tool'
32
+ /** Type of conflict: 'command' | 'mcp-tool' | 'reserved-name' */
33
+ conflictType: 'command' | 'mcp-tool' | 'reserved-name'
34
34
  }
35
35
 
36
36
  // ── Constants ──
37
37
 
38
+ /**
39
+ * Tool names the CLI gives a native capability. A skill with one of these names
40
+ * is not shadowing a slash command or an MCP tool, so it used to pass every
41
+ * check — and the model then had two different things called `computer-use`.
42
+ */
43
+ const RESERVED_SKILL_NAMES = new Set(['computer-use'])
44
+
38
45
  /** Known local command names that skills should not shadow */
39
46
  const BUILTIN_COMMANDS = new Set([
40
47
  '/help',
@@ -193,6 +200,13 @@ export function checkSkillShadow(
193
200
  return { shadowed: true, conflictsWith: skillName, conflictType: 'command' }
194
201
  }
195
202
 
203
+ // Names the CLI itself gives a native capability. These are tools, not slash
204
+ // commands, so the command check above does not see them — a same-named skill
205
+ // loaded silently and left the model with two different `computer-use`s.
206
+ if (RESERVED_SKILL_NAMES.has(skillName)) {
207
+ return { shadowed: true, conflictsWith: skillName, conflictType: 'reserved-name' }
208
+ }
209
+
196
210
  // Check description for embedded command names
197
211
  for (const cmd of BUILTIN_COMMANDS) {
198
212
  const cmdPattern = cmd.replace(/\//g, '')