@miphamai/cli 0.85.11 → 0.85.12

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 CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.11
1
+ # Mipham Code v0.85.12
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.11",
3
+ "version": "0.85.12",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -458,10 +458,32 @@ export class SubAgent {
458
458
  model: finalModel,
459
459
  registry: this.registry,
460
460
  toolRegistry: this.toolRegistry,
461
+ // 交出去的是**上面那个 `subPermission`**,不是缺省时新建的 `gate`。两者在生产路径上
462
+ // 恒为同一个对象 —— `Engine` 的 `permission` 字段有默认值(`engine.ts` 的构造参数),
463
+ // `getPermission()` 的返回类型不含 `undefined`,而全仓五个 `new SubAgent(...)` 生产
464
+ // 构造点全部追溯到它(`agent.ts` / `workflow/runtime.ts` / `skill.ts` 各自的
465
+ // `ctx.permissionSystem`,以及 `ui/commands.ts` 的两处 `engine.getPermission()`)。
466
+ // 所以 `subPermission` 为 `undefined` 只在「没人递闸门」时出现,那时下层自建 `default`。
467
+ //
468
+ // **别把它改成 `gate`。** 喂进去一个真实的 `default` 闸门,会让下层的 agent 定义从
469
+ // 「`permissionMode` 被整段忽略」变成「被兑现」(`resolveAgentMode` 那一支整个挂在
470
+ // `if (this.permission)` 下),其中 `acceptEdits` / `bypassPermissions` 比 `default`
471
+ // **宽** —— 为消掉一处对象身份的不一致而放宽闸门,方向是反的。要收口就该往另一边走:
472
+ // 让「无父闸」时对**所有**来源都按合成的 `default` 顶回去(那样 `plan` 这类**收窄**的
473
+ // 声明才不会被丢掉),但为一条生产不可达的路径加参数不值当,故记在这里。
474
+ //
475
+ // 生产侧那条不变量 ——「交出去的就是替它自己裁决的那一个,不是父系统、也不是新建的
476
+ // default」—— 由 `test/agent/sub-agent.test.ts` 的
477
+ // "hands nested tools the clamped permission, never the parent permission" 钉住。
461
478
  permissionSystem: subPermission,
462
479
  ruleEngine: this.ruleEngine,
463
480
  llm: this.llm,
464
481
  readFiles: new Set<string>(),
482
+ // Every tool call from here on is one level down, and a few tools must know
483
+ // it: `Agent` cannot consume a background handle, so its default flips to
484
+ // synchronous (see `resolveRunInBackground`). Set on the shared literal so it
485
+ // covers the synchronous *and* background runs — both go through here.
486
+ isSubAgent: true,
465
487
  }
466
488
 
467
489
  try {
@@ -519,8 +519,22 @@ export function loadSettingsJson(
519
519
 
520
520
  for (const { path, readHooks, isProject } of searchPaths) {
521
521
  try {
522
+ // `readRegularFileSync` folds "absent" and "present but unreadable"
523
+ // (EACCES, a directory, a FIFO) into the same `null`. Absent is the ordinary
524
+ // case here — most of these paths simply do not exist — so it stays quiet.
525
+ // But a settings file that *is* there and could not be read drops its
526
+ // `permissions.deny` wholesale, and the direction of that failure is
527
+ // **looser**. A security-relevant file must not fail open in silence.
528
+ const present = existsSync(path)
522
529
  const raw = readRegularFileSync(path)
523
- if (raw === null) continue
530
+ if (raw === null) {
531
+ if (present) {
532
+ process.stderr.write(
533
+ `⚠ Mipham Code: settings file (${path}) is not a readable regular file — ignoring it.\n`,
534
+ )
535
+ }
536
+ continue
537
+ }
524
538
  const parsed = JSON.parse(raw) as {
525
539
  hooks?: Record<string, unknown>
526
540
  permissions?: { allow?: unknown; deny?: unknown; defaultMode?: unknown }
@@ -584,8 +598,14 @@ export function loadSettingsJson(
584
598
  }
585
599
  }
586
600
  }
587
- } catch {
588
- // Silently skip malformed or missing settings.json files
601
+ } catch (err: unknown) {
602
+ // Malformed JSON is the other half of the same problem: the file exists and
603
+ // declares a `deny` list we cannot see. Say so, with the parse reason, the
604
+ // same way `safeParseYaml` does for `config.yml`.
605
+ const msg = err instanceof Error ? err.message : String(err)
606
+ process.stderr.write(
607
+ `⚠ Mipham Code: failed to parse settings file (${path}): ${msg} — ignoring it.\n`,
608
+ )
589
609
  }
590
610
  }
591
611
 
@@ -108,12 +108,10 @@ function compressToolResult(msg: Message): Message {
108
108
  *
109
109
  * Only compress when tokens saved > tokens lost from cache invalidation.
110
110
  * The multiplier of 1.5 provides a safety margin.
111
+ *
112
+ * 与「要不要压缩」的触发尺无关:那把尺在 `checkCompression`(本函数只在它之后被问)。
111
113
  */
112
- export function shouldMicrocompact(
113
- messages: Message[],
114
- cacheTracker: CacheTracker,
115
- _threshold: number,
116
- ): boolean {
114
+ export function shouldMicrocompact(messages: Message[], cacheTracker: CacheTracker): boolean {
117
115
  let savingsTokens = 0
118
116
  let cacheLossTokens = 0
119
117
 
@@ -1,6 +1,6 @@
1
1
  import type { Message, ToolResult } from '../shared/index.ts'
2
2
  import { snipMessages } from './context-snip'
3
- import { microcompact } from './context-microcompact'
3
+ import { microcompact, shouldMicrocompact } from './context-microcompact'
4
4
  import { NoopCacheTracker, type CacheTracker, type CacheStatus } from './context-token'
5
5
  import {
6
6
  SessionLog,
@@ -514,12 +514,7 @@ export class ContextManager {
514
514
 
515
515
  const usage = this.getEstimatedTokens() / this.config.maxTokens
516
516
 
517
- // Adaptive microcompact threshold: 200K→0.70, 500K→0.80, 1M→0.85
518
- const microThreshold = this.config.contextWindow
519
- ? Math.max(0.7, 1 - 150000 / this.config.contextWindow)
520
- : 0.7
521
-
522
- if (usage > microThreshold) {
517
+ if (usage > this.microcompactThreshold()) {
523
518
  this.compressionPending = true
524
519
  // Schedule microcompact asynchronously (fire-and-forget)
525
520
  void Promise.resolve().then(() => {
@@ -529,6 +524,11 @@ export class ContextManager {
529
524
  }
530
525
  }
531
526
 
527
+ /** Adaptive microcompact threshold: 200K→0.70, 500K→0.80, 1M→0.85 */
528
+ private microcompactThreshold(): number {
529
+ return this.config.contextWindow ? Math.max(0.7, 1 - 150000 / this.config.contextWindow) : 0.7
530
+ }
531
+
532
532
  /** Run snip + microcompact inline and update stats. */
533
533
  private runMicrocompact(): void {
534
534
  const { messages: snipped, removed } = snipMessages(this.messages)
@@ -538,11 +538,17 @@ export class ContextManager {
538
538
  this.compactionStats.snipMessagesRemoved += removed
539
539
  }
540
540
 
541
- // Microcompact: compress tool_results not needed for recent context
541
+ // Microcompact: compress tool_results not needed for recent context.
542
+ // 先问 `shouldMicrocompact` —— 它比的是「省下的」与「因缓存失效赔掉的」:压掉一条消息会让
543
+ // 它**之后**的整段前缀缓存失效,赔的常常比省的多。不闸这一道的话,这次压在有缓存时纯属白跑
544
+ // (实测:带 PrefixCacheTracker 时 `microcompact` 的 tokensSaved 恒为 0 —— 它能碰的只有最新
545
+ // 那条,而那条被下面这个 keepRecent 护着)。**只闸这一步**:上面的 snip 是另一层(零成本裁剪
546
+ // 空 tool_result),与缓存经济无关,照跑。
542
547
  const keepRecent = 3
543
- const { messages: compacted, tokensSaved } = microcompact(snipped, this.cacheTracker, {
544
- keepRecent,
545
- })
548
+ const worthCompacting = shouldMicrocompact(snipped, this.cacheTracker)
549
+ const { messages: compacted, tokensSaved } = worthCompacting
550
+ ? microcompact(snipped, this.cacheTracker, { keepRecent })
551
+ : { messages: snipped, tokensSaved: 0 }
546
552
 
547
553
  if (tokensSaved > 0) {
548
554
  this.compactionStats.microcompactCount++
@@ -19,7 +19,13 @@ const TOKEN_REDACTION_PATTERN =
19
19
  * out every non-secret endpoint too). The shape is the only reliable tell.
20
20
  * Redacts the password and keeps user + host, or the line stops being readable.
21
21
  */
22
- const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s@]+)@/gi
22
+ // The password group must NOT exclude `@`: a literal `@` inside a password is
23
+ // illegal per URL syntax, yet `postgres://user:p@ss@host` is exactly how people
24
+ // paste connection strings into a shell. Excluding `@` made the group stop at the
25
+ // *first* `@`, redacting only `p` and leaving `ss@host` in the clear. Greedy
26
+ // `[^/\s]+` runs to the last `@` on the line and backtracks, so the whole password
27
+ // goes and the host survives.
28
+ const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s]+)@/gi
23
29
 
24
30
  /**
25
31
  * Scrub credential patterns from stdout/stderr output.
@@ -14,8 +14,16 @@
14
14
  * if fail → auto-discards worktree → logs failure for CRSI learning
15
15
  */
16
16
 
17
- import { execSync } from 'node:child_process'
18
- import { mkdirSync, rmSync, existsSync, writeFileSync, readFileSync, readdirSync } from 'node:fs'
17
+ import { execSync, type StdioOptions } from 'node:child_process'
18
+ import {
19
+ mkdirSync,
20
+ rmSync,
21
+ existsSync,
22
+ writeFileSync,
23
+ readFileSync,
24
+ readdirSync,
25
+ realpathSync,
26
+ } from 'node:fs'
19
27
  import { atomicWriteFileSync } from '../shared/atomic-write'
20
28
  import { join, resolve, sep, posix } from 'node:path'
21
29
  import { tmpdir } from 'node:os'
@@ -269,6 +277,76 @@ export function validateMergeConvergence(proposal: {
269
277
  return `合并型提案必须收敛,但脚手架增长了:${rose.join(';')}。`
270
278
  }
271
279
 
280
+ /** POSIX 单引号包裹 —— 路径里的空格 / `$` / 反引号都不会被 shell 再解释。 */
281
+ function shq(s: string): string {
282
+ return `'${s.split("'").join("'\\''")}'`
283
+ }
284
+
285
+ /**
286
+ * 在 `root` 下跑一条命令 —— 把「在哪儿」写进**命令字符串本身**,而不是 `options.cwd`。
287
+ *
288
+ * 为什么不能只靠 `cwd`:那个 options 是**对象字面量**,而变异测试的 `ObjectLiteral`
289
+ * 变异体正会把整个字面量换成 `{}` —— `cwd` 随之消失,子进程落回 `process.cwd()`。
290
+ * 全量 `pnpm mutate` 时 `process.cwd()` 是 Stryker 的 `.stryker-tmp/sandbox-*`,
291
+ * 一个**有意不带 `.git`** 的副本目录 ⇒ 里面任何 git 命令都上溯到外面那棵**真仓库**,
292
+ * `worktree add` / `cherry-pick` / `branch -D` 于是全写进用户没点名过的仓库
293
+ * (2026-09-30 受控复现;现存的 `crsi-sandbox-*` 残留分支就是那次的痕迹)。
294
+ *
295
+ * git 子命令用 `-C`(git 自己的「在哪儿」参数),其余用 `cd`:**两者都在字符串里**,
296
+ * 对象字面量怎么变都动不了它们。下面那个字面量被抹成 `{}` 只会丢掉超时与编码,
297
+ * 丢不掉「哪棵树」。**有意不再传 `cwd`** —— 留着它,下一个人会以为承重的是它。
298
+ *
299
+ * 守卫 `test/integrity/crsi-sandbox-command-root.test.ts` 静态钉住这个形状。
300
+ */
301
+ function runIn(
302
+ root: string,
303
+ cmd: string,
304
+ opts: { timeoutMs?: number; quiet?: boolean } = {},
305
+ ): string {
306
+ const rooted = cmd.startsWith('git ')
307
+ ? `git -C ${shq(root)} ${cmd.slice(4)}`
308
+ : `cd ${shq(root)} && ${cmd}`
309
+ return execSync(rooted, {
310
+ timeout: opts.timeoutMs ?? 10_000,
311
+ encoding: 'utf-8',
312
+ ...(opts.quiet ? { stdio: ['ignore', 'pipe', 'ignore'] as StdioOptions } : {}),
313
+ })
314
+ }
315
+
316
+ /**
317
+ * 沙箱根的形状闸:只接受**它自己那棵工作树的根**。
318
+ *
319
+ * 判据为什么是「等于自己的工作树根」,而不是「落在某个仓库里」:这两件事在 git 层
320
+ * **没有区别**。一个不带 `.git` 的副本目录(如 Stryker 的 `.stryker-tmp/sandbox-*`,
321
+ * 它有意不带 `.git`)与「用户在仓库子目录里启动 CLI」,对 `rev-parse` 是同一种输入 ——
322
+ * 都会静默上溯到**外面那棵真仓库**。于是 `repoRoot` 这个名字承诺的东西(「只动这棵树」)
323
+ * 在那种情形下是假的:`git worktree add` / `git cherry-pick` / `git branch -D` 全都落进
324
+ * 用户从没点名过的那棵仓库里,而类的注释写的却是「用户的工作树永不被触碰」。
325
+ * ⇒ fail-closed 拒绝,并**点名那棵外层仓库**(否则用户只知道被拒,不知道被谁拦的)。
326
+ *
327
+ * 有意**不**做「静默改判为外层仓库的根」:那正是上面那个缺陷,只是把它变得看不见。
328
+ * 代价已认下:在仓库子目录里跑 CRSI 会被拒,须到仓库根运行。
329
+ * 边界:非 TOCTOU 安全(构造后 repoRoot 那棵树被换掉,本闸不再复查)。
330
+ */
331
+ export function assertSandboxRepoRoot(repoRoot: string): void {
332
+ let top: string
333
+ try {
334
+ top = runIn(repoRoot, 'git rev-parse --show-toplevel', { quiet: true }).trim()
335
+ } catch {
336
+ throw new Error(`CRSI 沙箱需要一个 git 仓库,但 ${repoRoot} 不在任何仓库内。请在仓库根运行。`)
337
+ }
338
+ // realpath 两侧都做:macOS 上 /var → /private/var,而 git 回的是物理路径。
339
+ if (realpathSync(top) !== realpathSync(repoRoot)) {
340
+ throw new Error(
341
+ `CRSI 沙箱的 repoRoot 必须是**它自己那棵仓库的根**:给定 ${repoRoot},` +
342
+ `但它属于外层仓库 ${top}。` +
343
+ `(副本目录、构建产物目录、仓库子目录都会落到这里 —— 若放行,` +
344
+ `worktree add / cherry-pick 会写进那棵外层仓库,而那是用户没有点名的仓库。)` +
345
+ `请在仓库根运行。`,
346
+ )
347
+ }
348
+ }
349
+
272
350
  // ── Sandbox ──
273
351
 
274
352
  export class CrsiSandbox {
@@ -280,6 +358,9 @@ export class CrsiSandbox {
280
358
 
281
359
  constructor(repoRoot: string = process.cwd()) {
282
360
  this.repoRoot = resolve(repoRoot)
361
+ // 先立形状闸,再建任何东西 —— 它必须在第一条 `runIn(this.repoRoot, …)` 的 git 命令之前,
362
+ // 也必须早于 mkdirSync(REPORT_DIR)(拒绝时零副作用)。
363
+ assertSandboxRepoRoot(this.repoRoot)
283
364
  this.sessionReport = {
284
365
  sessionId: `crsi-session-${Date.now().toString(36)}`,
285
366
  modifications: [],
@@ -313,10 +394,8 @@ export class CrsiSandbox {
313
394
  }
314
395
 
315
396
  try {
316
- execSync(`git worktree add -b "${branchName}" "${worktreeDir}" HEAD`, {
317
- cwd: this.repoRoot,
318
- timeout: 30_000,
319
- encoding: 'utf-8',
397
+ runIn(this.repoRoot, `git worktree add -b "${branchName}" "${worktreeDir}" HEAD`, {
398
+ timeoutMs: 30_000,
320
399
  })
321
400
  } catch (err) {
322
401
  throw new Error(`Failed to create CRSI worktree: ${String(err)}`)
@@ -407,11 +486,7 @@ export class CrsiSandbox {
407
486
 
408
487
  // Generate diff
409
488
  try {
410
- result.diff = execSync(`git diff -- "${normalizedFilePath}"`, {
411
- cwd: this.worktreePath,
412
- timeout: 10_000,
413
- encoding: 'utf-8',
414
- })
489
+ result.diff = runIn(this.worktreePath, `git diff -- "${normalizedFilePath}"`)
415
490
  } catch {
416
491
  // Diff generation is best-effort
417
492
  }
@@ -439,11 +514,7 @@ export class CrsiSandbox {
439
514
  const result: CrsiTestResult = { passed: false, totalTests: 0, failedTests: 0, output: '' }
440
515
 
441
516
  try {
442
- const output = execSync('pnpm test 2>&1', {
443
- cwd: this.worktreePath,
444
- timeout: TEST_TIMEOUT_MS,
445
- encoding: 'utf-8',
446
- })
517
+ const output = runIn(this.worktreePath, 'pnpm test 2>&1', { timeoutMs: TEST_TIMEOUT_MS })
447
518
 
448
519
  result.output = output.slice(-5000) // Keep last 5000 chars
449
520
 
@@ -500,11 +571,7 @@ export class CrsiSandbox {
500
571
  if (!this.worktreePath) return ''
501
572
 
502
573
  try {
503
- return execSync('git diff', {
504
- cwd: this.worktreePath,
505
- timeout: 10_000,
506
- encoding: 'utf-8',
507
- })
574
+ return runIn(this.worktreePath, 'git diff')
508
575
  } catch {
509
576
  return '(diff unavailable)'
510
577
  }
@@ -535,23 +602,16 @@ export class CrsiSandbox {
535
602
 
536
603
  try {
537
604
  // Commit in worktree
538
- execSync('git add -A', { cwd: this.worktreePath, timeout: 10_000 })
539
- execSync(
605
+ runIn(this.worktreePath, 'git add -A')
606
+ runIn(
607
+ this.worktreePath,
540
608
  `git commit -m "CRSI auto-modification: ${this.sessionReport.sessionId}" --allow-empty`,
541
- { cwd: this.worktreePath, timeout: 10_000 },
542
609
  )
543
610
 
544
611
  // Cherry-pick to main repo
545
- const commitHash = execSync('git rev-parse HEAD', {
546
- cwd: this.worktreePath,
547
- timeout: 10_000,
548
- encoding: 'utf-8',
549
- }).trim()
550
-
551
- execSync(`git cherry-pick "${commitHash}"`, {
552
- cwd: this.repoRoot,
553
- timeout: 30_000,
554
- })
612
+ const commitHash = runIn(this.worktreePath, 'git rev-parse HEAD').trim()
613
+
614
+ runIn(this.repoRoot, `git cherry-pick "${commitHash}"`, { timeoutMs: 30_000 })
555
615
 
556
616
  // Mark as merged
557
617
  for (const modResult of this.sessionReport.modifications) {
@@ -611,9 +671,8 @@ export class CrsiSandbox {
611
671
 
612
672
  try {
613
673
  // Remove worktree
614
- execSync(`git worktree remove --force "${this.worktreePath}"`, {
615
- cwd: this.repoRoot,
616
- timeout: 15_000,
674
+ runIn(this.repoRoot, `git worktree remove --force "${this.worktreePath}"`, {
675
+ timeoutMs: 15_000,
617
676
  })
618
677
  } catch {
619
678
  // Best-effort: if worktree remove fails, try manual cleanup
@@ -621,7 +680,7 @@ export class CrsiSandbox {
621
680
  if (existsSync(this.worktreePath)) {
622
681
  rmSync(this.worktreePath, { recursive: true, force: true })
623
682
  }
624
- execSync(`git worktree prune`, { cwd: this.repoRoot, timeout: 10_000 })
683
+ runIn(this.repoRoot, `git worktree prune`)
625
684
  } catch {
626
685
  // Give up — stale worktrees will be cleaned up on next createWorktree()
627
686
  }
@@ -629,10 +688,7 @@ export class CrsiSandbox {
629
688
 
630
689
  // Delete the branch
631
690
  try {
632
- execSync(`git branch -D "${this.worktreeBranch}"`, {
633
- cwd: this.repoRoot,
634
- timeout: 10_000,
635
- })
691
+ runIn(this.repoRoot, `git branch -D "${this.worktreeBranch}"`)
636
692
  } catch {
637
693
  // Branch may already be gone
638
694
  }
@@ -703,11 +759,7 @@ export class CrsiSandbox {
703
759
  */
704
760
  private cleanupStaleWorktrees(): void {
705
761
  try {
706
- const listOutput = execSync('git worktree list --porcelain', {
707
- cwd: this.repoRoot,
708
- timeout: 10_000,
709
- encoding: 'utf-8',
710
- })
762
+ const listOutput = runIn(this.repoRoot, 'git worktree list --porcelain')
711
763
 
712
764
  const worktrees = this.parseWorktreeList(listOutput)
713
765
 
@@ -719,8 +771,8 @@ export class CrsiSandbox {
719
771
  if (!existsSync(wt.path)) {
720
772
  // Stale entry — prune it
721
773
  try {
722
- execSync(`git worktree prune`, { cwd: this.repoRoot, timeout: 5_000 })
723
- execSync(`git branch -D "${wt.branch}"`, { cwd: this.repoRoot, timeout: 5_000 })
774
+ runIn(this.repoRoot, `git worktree prune`, { timeoutMs: 5_000 })
775
+ runIn(this.repoRoot, `git branch -D "${wt.branch}"`, { timeoutMs: 5_000 })
724
776
  } catch {
725
777
  // Best-effort cleanup
726
778
  }
@@ -1352,6 +1352,7 @@ export class QueryEngine {
1352
1352
  skillsLoader: this.skillsProvider,
1353
1353
  registry: this.registry,
1354
1354
  toolRegistry: this.tools,
1355
+ signal,
1355
1356
  artifactServer: this.artifactServer,
1356
1357
  agentRegistry: this.agentRegistry,
1357
1358
  backgroundAgentRegistry: getBackgroundAgentRegistry(),
@@ -1541,6 +1542,10 @@ export class QueryEngine {
1541
1542
  // fresh attempt after a failed one.
1542
1543
  const ownsFlow = !(this.llm && this.llm !== this.registry)
1543
1544
  let failure: string | null = null
1545
+ // A provider that marks the failure deterministic opts out of both retries. Only
1546
+ // an explicit `false` counts: an absent flag means "unknown", which keeps the
1547
+ // old try-again behaviour for every provider that says nothing.
1548
+ let retryable = true
1544
1549
  for (let attempt = 0; ; attempt++) {
1545
1550
  failure = null
1546
1551
  try {
@@ -1554,6 +1559,7 @@ export class QueryEngine {
1554
1559
  })) {
1555
1560
  if (chunk.type === 'error') {
1556
1561
  failure = chunk.error ?? 'Unknown error'
1562
+ if (chunk.retryable === false) retryable = false
1557
1563
  break
1558
1564
  }
1559
1565
  yield chunk
@@ -1563,11 +1569,18 @@ export class QueryEngine {
1563
1569
  if (isAbortError(err)) throw err
1564
1570
  failure = String(err)
1565
1571
  }
1566
- if (!ownsFlow || attempt >= 1) break
1572
+ if (!retryable || !ownsFlow || attempt >= 1) break
1567
1573
  yield { type: 'warning', content: `${activeId} failed (${failure}) — retrying once` }
1568
1574
  }
1569
1575
  const detail = failure ?? 'Unknown error'
1570
1576
 
1577
+ // Deterministic failure: re-sending it to another provider cannot change the
1578
+ // answer, so surface it once rather than burning the fallback on it.
1579
+ if (!retryable) {
1580
+ yield { type: 'error', error: detail }
1581
+ return
1582
+ }
1583
+
1571
1584
  // ── Fallback: configured default provider, once ──
1572
1585
  // 若注入了**异己**的 Llm 缝,缝拥有整个 chat 流程——不回退(避免切 registry 状态 + 二次调用)。
1573
1586
  // `!== this.registry` 不可省:生产路径注入的正是 registry 自己(`index.tsx` →
@@ -1589,7 +1602,12 @@ export class QueryEngine {
1589
1602
  return
1590
1603
  }
1591
1604
 
1592
- this.registry.switchProvider(defaultId, fallbackModel)
1605
+ // Go through the engine's own switcher, not the registry directly: only it
1606
+ // calls `context.updateMaxTokens`, and a fallback model routinely has a smaller
1607
+ // window than the one we fell back from (1M → 128K). Switching the registry
1608
+ // alone left compaction armed to the *old* model's window, so the summary would
1609
+ // not trigger until ~950K — long past the point the fallback model overflows.
1610
+ this.switchProvider(defaultId, fallbackModel)
1593
1611
  yield {
1594
1612
  type: 'warning',
1595
1613
  content: `${activeId} unreachable — degraded to ${defaultId} (${fallbackModel})`,