@miphamai/cli 0.85.11 → 0.85.13

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.
Files changed (38) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/sub-agent.ts +22 -0
  4. package/src/config/loader.ts +101 -6
  5. package/src/core/context-microcompact.ts +3 -5
  6. package/src/core/context.ts +17 -11
  7. package/src/core/credential-masker/output-scrub.ts +7 -1
  8. package/src/core/crsi-sandbox.ts +101 -49
  9. package/src/core/engine.ts +22 -2
  10. package/src/core/hooks-executor.ts +165 -16
  11. package/src/core/permission-classifier.ts +36 -12
  12. package/src/core/permission.ts +45 -0
  13. package/src/core/self-critique.ts +3 -15
  14. package/src/core/task-performance.ts +32 -4
  15. package/src/i18n-core/locales/en-US.json +1 -0
  16. package/src/i18n-core/locales/zh-CN.json +1 -0
  17. package/src/index.tsx +15 -1
  18. package/src/plugin/plugin-loader.ts +10 -9
  19. package/src/providers/anthropic.ts +11 -3
  20. package/src/providers/fetch-utils.ts +29 -0
  21. package/src/providers/openai-compat.ts +24 -2
  22. package/src/providers/registry.ts +38 -0
  23. package/src/security/world-writable-chmod.ts +157 -0
  24. package/src/shared/package-info.ts +2 -2
  25. package/src/shared/sanitize.ts +33 -0
  26. package/src/shared/types.ts +30 -0
  27. package/src/tools/agent/agent.ts +18 -3
  28. package/src/tools/agent/exit-plan.ts +49 -9
  29. package/src/tools/artifact/artifact.ts +0 -1
  30. package/src/tools/exec/bash.ts +28 -3
  31. package/src/tools/index.ts +7 -1
  32. package/src/tools/network/web-fetch.ts +2 -1
  33. package/src/ui/chat.tsx +2 -1
  34. package/src/ui/commands.ts +7 -6
  35. package/src/ui/input.tsx +5 -0
  36. package/src/workflow/event-bus.ts +13 -0
  37. package/src/workflow/journal.ts +8 -0
  38. package/src/workflow/runtime.ts +59 -11
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.11
1
+ # Mipham Code v0.85.13
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.13",
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 {
@@ -414,7 +414,23 @@ export interface SettingsJson {
414
414
  * validator here would be a second value domain, and the two would drift the
415
415
  * day a mode is added.
416
416
  */
417
- permissions: { allow: string[]; deny: string[]; defaultMode?: string }
417
+ permissions: {
418
+ allow: string[]
419
+ deny: string[]
420
+ defaultMode?: string
421
+ /**
422
+ * Which model rules in `auto` mode. Absent ⇒ the model the operator has
423
+ * active; `'active'` says the same thing out loud; `'fast'` picks the
424
+ * Flash-class model; any other string is a model id, passed through
425
+ * unvalidated (the provider is the only thing that can say what exists).
426
+ */
427
+ classifierModel?: string
428
+ /**
429
+ * Milliseconds a single ruling may take before it is abandoned. Absent ⇒
430
+ * `DEFAULT_CLASSIFIER_TIMEOUT_MS`.
431
+ */
432
+ classifierTimeoutMs?: number
433
+ }
418
434
  /**
419
435
  * Present (and `true`) only when the project-level file really did declare
420
436
  * hooks and they were withheld because the caller did not vouch for the
@@ -439,6 +455,14 @@ export interface SettingsJson {
439
455
  * that declares `allow` but no mode sets this one and not the other.
440
456
  */
441
457
  projectAllowSkipped?: true
458
+ /**
459
+ * Same shape, for `permissions.classifierModel` / `classifierTimeoutMs`: the
460
+ * two knobs on **how** the `auto` gate rules rather than on what it permits.
461
+ * Both can widen it — a weaker judge, or more time for a ruling that would
462
+ * otherwise time out into a denial — so both are withheld from a project file
463
+ * for the same reason `defaultMode` is, and the one marker covers both.
464
+ */
465
+ projectClassifierSkipped?: true
442
466
  /**
443
467
  * The subset of `hooks` that came from the project-level file — the entries
444
468
  * the workspace-trust gate governs. Absent unless the caller vouched for the
@@ -489,13 +513,20 @@ export function loadSettingsJson(
489
513
  options: { includeProjectHooks?: boolean } = {},
490
514
  ): SettingsJson {
491
515
  const hooks: SettingsHooks = {}
492
- const permissions: { allow: string[]; deny: string[]; defaultMode?: string } = {
516
+ const permissions: {
517
+ allow: string[]
518
+ deny: string[]
519
+ defaultMode?: string
520
+ classifierModel?: string
521
+ classifierTimeoutMs?: number
522
+ } = {
493
523
  allow: [],
494
524
  deny: [],
495
525
  }
496
526
  let projectHooksSkipped = false
497
527
  let projectModeSkipped = false
498
528
  let projectAllowSkipped = false
529
+ let projectClassifierSkipped = false
499
530
  // The project file's entries, kept out of the merge so provenance survives it.
500
531
  const projectHooks: SettingsHooks = {}
501
532
 
@@ -519,11 +550,31 @@ export function loadSettingsJson(
519
550
 
520
551
  for (const { path, readHooks, isProject } of searchPaths) {
521
552
  try {
553
+ // `readRegularFileSync` folds "absent" and "present but unreadable"
554
+ // (EACCES, a directory, a FIFO) into the same `null`. Absent is the ordinary
555
+ // case here — most of these paths simply do not exist — so it stays quiet.
556
+ // But a settings file that *is* there and could not be read drops its
557
+ // `permissions.deny` wholesale, and the direction of that failure is
558
+ // **looser**. A security-relevant file must not fail open in silence.
559
+ const present = existsSync(path)
522
560
  const raw = readRegularFileSync(path)
523
- if (raw === null) continue
561
+ if (raw === null) {
562
+ if (present) {
563
+ process.stderr.write(
564
+ `⚠ Mipham Code: settings file (${path}) is not a readable regular file — ignoring it.\n`,
565
+ )
566
+ }
567
+ continue
568
+ }
524
569
  const parsed = JSON.parse(raw) as {
525
570
  hooks?: Record<string, unknown>
526
- permissions?: { allow?: unknown; deny?: unknown; defaultMode?: unknown }
571
+ permissions?: {
572
+ allow?: unknown
573
+ deny?: unknown
574
+ defaultMode?: unknown
575
+ classifierModel?: unknown
576
+ classifierTimeoutMs?: unknown
577
+ }
527
578
  }
528
579
 
529
580
  if (!readHooks) {
@@ -583,9 +634,52 @@ export function loadSettingsJson(
583
634
  if (!permissions[key].includes(p)) permissions[key].push(p)
584
635
  }
585
636
  }
637
+
638
+ // The two knobs on **how** the gate rules, rather than on what it lets
639
+ // through. Both can widen it — a weaker judge (measured 2026-09-30: the
640
+ // fast model allows 8/20 borderline calls the reasoning one blocks), or
641
+ // more time, since a ruling that does not finish in budget is a denial —
642
+ // so both are withheld from a project file like `defaultMode`.
643
+ //
644
+ // Unlike `defaultMode`, a value that cannot be used is dropped **here**
645
+ // and said so: there is no applier downstream that knows these spellings,
646
+ // and silently ignoring a knob the user wrote is indistinguishable from
647
+ // never reading their file.
648
+ const rawClassifierModel = parsed.permissions.classifierModel
649
+ if (rawClassifierModel !== undefined) {
650
+ if (typeof rawClassifierModel === 'string' && rawClassifierModel.trim() !== '') {
651
+ if (isProject) projectClassifierSkipped = true
652
+ else permissions.classifierModel = rawClassifierModel.trim()
653
+ } else {
654
+ process.stderr.write(
655
+ `⚠ Mipham Code: ignoring permissions.classifierModel from ${path} — expected a non-empty model id.\n`,
656
+ )
657
+ }
658
+ }
659
+ const rawClassifierTimeout = parsed.permissions.classifierTimeoutMs
660
+ if (rawClassifierTimeout !== undefined) {
661
+ if (
662
+ typeof rawClassifierTimeout === 'number' &&
663
+ Number.isFinite(rawClassifierTimeout) &&
664
+ rawClassifierTimeout > 0
665
+ ) {
666
+ if (isProject) projectClassifierSkipped = true
667
+ else permissions.classifierTimeoutMs = rawClassifierTimeout
668
+ } else {
669
+ process.stderr.write(
670
+ `⚠ Mipham Code: ignoring permissions.classifierTimeoutMs from ${path} — expected a positive number of milliseconds.\n`,
671
+ )
672
+ }
673
+ }
586
674
  }
587
- } catch {
588
- // Silently skip malformed or missing settings.json files
675
+ } catch (err: unknown) {
676
+ // Malformed JSON is the other half of the same problem: the file exists and
677
+ // declares a `deny` list we cannot see. Say so, with the parse reason, the
678
+ // same way `safeParseYaml` does for `config.yml`.
679
+ const msg = err instanceof Error ? err.message : String(err)
680
+ process.stderr.write(
681
+ `⚠ Mipham Code: failed to parse settings file (${path}): ${msg} — ignoring it.\n`,
682
+ )
589
683
  }
590
684
  }
591
685
 
@@ -597,6 +691,7 @@ export function loadSettingsJson(
597
691
  if (projectHooksSkipped) result.projectHooksSkipped = true
598
692
  if (projectModeSkipped) result.projectModeSkipped = true
599
693
  if (projectAllowSkipped) result.projectAllowSkipped = true
694
+ if (projectClassifierSkipped) result.projectClassifierSkipped = true
600
695
  if (Object.values(projectHooks).some((entries) => Array.isArray(entries) && entries.length > 0)) {
601
696
  result.projectHooks = projectHooks
602
697
  }
@@ -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})`,
@@ -1663,6 +1681,8 @@ export class QueryEngine {
1663
1681
  return t('errors.tool_denied_ask_rule', { name, pattern: rulePattern ?? '?' })
1664
1682
  case 'dangerous-rm':
1665
1683
  return t('errors.tool_denied_dangerous_rm', { name, target: target ?? '?' })
1684
+ case 'world-writable-chmod':
1685
+ return t('errors.tool_denied_world_writable_chmod', { name, target: target ?? '?' })
1666
1686
  default:
1667
1687
  // mode-baseline / tool-default / legacy-rule / system-default — a mode
1668
1688
  // switch (or /permissions) resolves it.