@miphamai/cli 0.85.10 → 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.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/sub-agent.ts +49 -1
  4. package/src/commands/autoloop-journal.ts +16 -1
  5. package/src/config/loader.ts +23 -3
  6. package/src/core/context-microcompact.ts +3 -5
  7. package/src/core/context.ts +58 -16
  8. package/src/core/credential-masker/output-scrub.ts +7 -1
  9. package/src/core/crsi-producer.ts +86 -6
  10. package/src/core/crsi-sandbox.ts +101 -49
  11. package/src/core/engine.ts +108 -26
  12. package/src/core/hooks-executor.ts +165 -16
  13. package/src/core/instructions.ts +6 -5
  14. package/src/core/memory/memory-manager.ts +9 -1
  15. package/src/core/permission-config.ts +28 -0
  16. package/src/core/permission.ts +51 -5
  17. package/src/core/rules-loader.ts +96 -5
  18. package/src/core/task-performance.ts +32 -4
  19. package/src/i18n-core/locales/en-US.json +2 -0
  20. package/src/i18n-core/locales/zh-CN.json +2 -0
  21. package/src/mcp/registry.ts +8 -0
  22. package/src/plugin/plugin-loader.ts +10 -9
  23. package/src/providers/anthropic.ts +11 -3
  24. package/src/providers/fetch-utils.ts +34 -1
  25. package/src/providers/openai-compat.ts +24 -2
  26. package/src/shared/package-info.ts +2 -2
  27. package/src/shared/sanitize.ts +65 -0
  28. package/src/shared/types.ts +30 -0
  29. package/src/tools/agent/agent.ts +18 -3
  30. package/src/tools/agent/exit-plan.ts +49 -9
  31. package/src/tools/artifact/artifact.ts +0 -1
  32. package/src/tools/exec/bash.ts +28 -3
  33. package/src/tools/index.ts +7 -1
  34. package/src/tools/network/web-fetch.ts +2 -1
  35. package/src/tools/system/tool-search.ts +1 -1
  36. package/src/ui/chat.tsx +2 -1
  37. package/src/ui/commands.ts +28 -11
  38. package/src/ui/input.tsx +5 -0
  39. package/src/workflow/event-bus.ts +13 -0
  40. package/src/workflow/journal.ts +8 -0
  41. package/src/workflow/runtime.ts +59 -11
@@ -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
  }
@@ -1196,9 +1196,37 @@ export class QueryEngine {
1196
1196
  error: preResult.reason || t('errors.tool_blocked', { name }),
1197
1197
  }
1198
1198
  }
1199
+
1200
+ // `permissionDecision` narrows only — never widens. `ask` stops the call here
1201
+ // (this CLI has no interactive approval prompt; `ask` is a hard refusal, the
1202
+ // same as the `default` mode's ask path). `allow` is deliberately **not**
1203
+ // honoured: a hook can come from the repository's own settings, so letting it
1204
+ // auto-approve is the same defect as a project-supplied agent definition that
1205
+ // grants itself `bypassPermissions` — the criterion is the *direction*, not the
1206
+ // key name. `defer` (and an absent decision) means "no override", which is
1207
+ // exactly what happens when we do nothing.
1208
+ if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
1209
+ return {
1210
+ success: false,
1211
+ content: '',
1212
+ error: preResult.reason || t('errors.tool_hook_ask', { name }),
1213
+ }
1214
+ }
1215
+
1199
1216
  if (preResult.modifiedInput) {
1200
1217
  effectiveParams = { ...params, ...preResult.modifiedInput }
1201
1218
  }
1219
+
1220
+ // A hook's `additionalContext` is how every non-blocking hook speaks — the
1221
+ // exit-1 stderr, a spawn failure, an unreachable `mcp_tool` server (see
1222
+ // `core/hooks-executor.ts`). This path used to read only `allowed` /
1223
+ // `modifiedInput`, so all of it was produced and then dropped. `hookWarnings`
1224
+ // is the channel that already reaches the model: it is prepended to the tool
1225
+ // result below. A non-`[rule:…]` line is ignored by the effectiveness tracker
1226
+ // further down, so pushing prose here is safe.
1227
+ if (preResult.additionalContext) {
1228
+ hookWarnings.push(preResult.additionalContext)
1229
+ }
1202
1230
  }
1203
1231
 
1204
1232
  // CRSI RuleEngine intercept — gated by crsi.preToolHook feature flag
@@ -1209,7 +1237,11 @@ export class QueryEngine {
1209
1237
  effectiveParams = ruleResult.modified
1210
1238
  }
1211
1239
  if (ruleResult.warnings.length > 0) {
1212
- hookWarnings = ruleResult.warnings
1240
+ // Append, do not replace: this array may already hold a PreToolUse hook's
1241
+ // `additionalContext`. Every other writer below uses the spread form for the
1242
+ // same reason — assignment here would silently drop whichever was written
1243
+ // first ("two writers, one list").
1244
+ hookWarnings = [...hookWarnings, ...ruleResult.warnings]
1213
1245
  }
1214
1246
  }
1215
1247
 
@@ -1320,6 +1352,7 @@ export class QueryEngine {
1320
1352
  skillsLoader: this.skillsProvider,
1321
1353
  registry: this.registry,
1322
1354
  toolRegistry: this.tools,
1355
+ signal,
1323
1356
  artifactServer: this.artifactServer,
1324
1357
  agentRegistry: this.agentRegistry,
1325
1358
  backgroundAgentRegistry: getBackgroundAgentRegistry(),
@@ -1478,9 +1511,12 @@ export class QueryEngine {
1478
1511
  * Stream a chat response with graceful provider fallback (v2.1.229 alignment).
1479
1512
  *
1480
1513
  * On a connection/availability failure from the active provider (thrown
1481
- * network error or an error chunk), switches to the configured default
1482
- * provider and retries once, yielding a `warning` chunk so the UI can tell
1483
- * the user the provider degraded. Abort errors propagate untouched.
1514
+ * network error or an error chunk), retries that same provider once, then
1515
+ * switches to the configured default provider and retries again, yielding a
1516
+ * `warning` chunk at each step so the UI can tell the user what happened.
1517
+ * When there is no fallback left, the error names the unavailable model and
1518
+ * the next step instead of re-emitting the raw upstream message.
1519
+ * Abort errors propagate untouched.
1484
1520
  */
1485
1521
  private async *chatWithFallback(
1486
1522
  messages: import('../shared/types').Message[],
@@ -1489,29 +1525,60 @@ export class QueryEngine {
1489
1525
  signal?: AbortSignal,
1490
1526
  ): AsyncGenerator<StreamChunk> {
1491
1527
  const activeId = this.registry.getActive().config.id
1528
+ const activeModel = this.registry.getActiveModel()
1492
1529
  const defaultId = this.registry.getDefaultProviderId()
1493
1530
 
1494
- // ── Attempt 1: active provider ──
1531
+ // ── Attempt 1 (+ one same-provider retry): active provider ──
1532
+ //
1533
+ // A failed turn is retried once on the *same* provider before the cross-provider
1534
+ // fallback is considered: overloaded and transient errors are commonly answered
1535
+ // by resending, whereas switching providers is the more expensive move — it flips
1536
+ // the registry's active provider and, with it, the model the user chose. A
1537
+ // foreign `Llm` seam owns the whole chat flow, so it is not retried here, for the
1538
+ // same reason the fallback below is skipped for it.
1539
+ //
1540
+ // Chunks already yielded cannot be taken back, so a retry re-streams that turn.
1541
+ // This is not a new property: the cross-provider fallback below already starts a
1542
+ // fresh attempt after a failed one.
1543
+ const ownsFlow = !(this.llm && this.llm !== this.registry)
1495
1544
  let failure: string | null = null
1496
- try {
1497
- for await (const chunk of this.llmChat({
1498
- model: this.registry.getActiveModel(),
1499
- messages,
1500
- systemPrompt,
1501
- tools: toolDefs,
1502
- signal,
1503
- effort: this.effort,
1504
- })) {
1505
- if (chunk.type === 'error') {
1506
- failure = chunk.error ?? 'Unknown error'
1507
- break
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
1549
+ for (let attempt = 0; ; attempt++) {
1550
+ failure = null
1551
+ try {
1552
+ for await (const chunk of this.llmChat({
1553
+ model: activeModel,
1554
+ messages,
1555
+ systemPrompt,
1556
+ tools: toolDefs,
1557
+ signal,
1558
+ effort: this.effort,
1559
+ })) {
1560
+ if (chunk.type === 'error') {
1561
+ failure = chunk.error ?? 'Unknown error'
1562
+ if (chunk.retryable === false) retryable = false
1563
+ break
1564
+ }
1565
+ yield chunk
1508
1566
  }
1509
- yield chunk
1567
+ if (failure === null) return
1568
+ } catch (err) {
1569
+ if (isAbortError(err)) throw err
1570
+ failure = String(err)
1510
1571
  }
1511
- if (failure === null) return
1512
- } catch (err) {
1513
- if (isAbortError(err)) throw err
1514
- failure = String(err)
1572
+ if (!retryable || !ownsFlow || attempt >= 1) break
1573
+ yield { type: 'warning', content: `${activeId} failed (${failure}) — retrying once` }
1574
+ }
1575
+ const detail = failure ?? 'Unknown error'
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
1515
1582
  }
1516
1583
 
1517
1584
  // ── Fallback: configured default provider, once ──
@@ -1520,22 +1587,27 @@ export class QueryEngine {
1520
1587
  // `mountLlm(vajraContext, registry)` → `setLlm`),按「非空即缝」判定会让本分支
1521
1588
  // 在生产恒不可达,而测试里构造引擎时不注入缝 ⇒ 套件全绿也发现不了。
1522
1589
  if (this.llm && this.llm !== this.registry) {
1523
- yield { type: 'error', error: failure }
1590
+ yield { type: 'error', error: detail }
1524
1591
  return
1525
1592
  }
1526
1593
  if (!defaultId || defaultId === activeId || !this.registry.get(defaultId)) {
1527
- yield { type: 'error', error: failure }
1594
+ yield { type: 'error', error: this.modelUnavailableNotice(activeId, activeModel, detail) }
1528
1595
  return
1529
1596
  }
1530
1597
  const fallbackModel = this.registry
1531
1598
  .get(defaultId)!
1532
1599
  .config.models.find((m) => m.status === 'active')?.id
1533
1600
  if (!fallbackModel) {
1534
- yield { type: 'error', error: failure }
1601
+ yield { type: 'error', error: this.modelUnavailableNotice(activeId, activeModel, detail) }
1535
1602
  return
1536
1603
  }
1537
1604
 
1538
- 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)
1539
1611
  yield {
1540
1612
  type: 'warning',
1541
1613
  content: `${activeId} unreachable — degraded to ${defaultId} (${fallbackModel})`,
@@ -1558,6 +1630,16 @@ export class QueryEngine {
1558
1630
  }
1559
1631
  }
1560
1632
 
1633
+ /**
1634
+ * 「模型不可用、且已无可回退的默认模型」时的说明。
1635
+ *
1636
+ * 裸的 `failure` 读起来像模型答错了,而实际上**这一轮请求根本没发出去**:把
1637
+ * 这一层说破,并给出下一步(换模型 / 查密钥与网络),比把上游错误原样抛出来有用。
1638
+ */
1639
+ private modelUnavailableNotice(providerId: string, model: string, detail: string): string {
1640
+ return t('errors.model_unavailable', { model, provider: providerId, error: detail })
1641
+ }
1642
+
1561
1643
  getTools(): Map<string, ToolDefinition> {
1562
1644
  return this.tools
1563
1645
  }
@@ -1,4 +1,4 @@
1
- import { spawnSync } from 'node:child_process'
1
+ import { spawn } from 'node:child_process'
2
2
  import { McpClient } from '../mcp/client'
3
3
  import type { ToolCallResult } from '../mcp/types'
4
4
  import type { HookConfig, HookContext, HookResult } from '../shared/index.ts'
@@ -115,9 +115,9 @@ export function parseHookStdout(stdout: string | null | undefined, _ctx: HookCon
115
115
  /**
116
116
  * Why the hook subprocess failed to run to completion, or `null` if it did exit.
117
117
  *
118
- * `spawnSync` does **not** throw for a failed spawn or a timeout — it reports them
119
- * on the result, and all three shapes arrive with **empty stderr**: `error.code`
120
- * is `ETIMEDOUT` for the timeout, `ENOENT` when the command does not exist, and an
118
+ * The spawn does **not** throw for a failed spawn or a timeout — it reports them on
119
+ * the result, and all three shapes arrive with **empty stderr**: `error.code` is
120
+ * `ETIMEDOUT` for the timeout, `ENOENT` when the command does not exist, and an
121
121
  * externally killed child comes back as `status: null` + `signal` with no `error`
122
122
  * at all. Empty stderr is what made them one string with a benign non-zero exit
123
123
  * that printed nothing — `Hook warning (<cmd>): ` with the reason left blank.
@@ -133,7 +133,7 @@ export function parseHookStdout(stdout: string | null | undefined, _ctx: HookCon
133
133
  * is exempt from the two decisions below, and speaks only when nothing else can.
134
134
  *
135
135
  * Named here rather than in the caller's `catch`, which cannot see any of them:
136
- * it runs only when `spawnSync` itself throws.
136
+ * it runs only when the spawn machinery itself throws.
137
137
  */
138
138
  function spawnFailureCause(
139
139
  result: { status?: number | null; signal?: string | null; error?: unknown },
@@ -176,6 +176,156 @@ function failingLabel(command: string | undefined, source?: string): string {
176
176
  return `(${command})${source ? ` from "${source}"` : ''}`
177
177
  }
178
178
 
179
+ /** Grace given to a descendant still holding a stdio pipe after the hook itself exited. */
180
+ const HOOK_PIPE_GRACE_MS = 1_000
181
+
182
+ /** The `spawnSync`-shaped outcome `spawnFailureCause` and the caller already read. */
183
+ interface HookProcessResult {
184
+ status: number | null
185
+ signal: string | null
186
+ stdout: string
187
+ stderr: string
188
+ error?: { code?: string; message?: string }
189
+ }
190
+
191
+ /**
192
+ * Run a hook command to completion, bounding **both** halves of the wait.
193
+ *
194
+ * `spawnSync` was the wrong tool here. It returns only when the child's stdout and
195
+ * stderr reach EOF — not when the child exits — so a hook that backgrounds anything
196
+ * (`daemon &`, a watcher, an ssh tunnel) leaves a descendant holding the pipe and
197
+ * the read never sees EOF. Because `spawnSync` blocks the thread, the whole event
198
+ * loop froze with it: the terminal stopped responding for the full 60s default, and
199
+ * the error that finally surfaced (`timed out after 60s`) was a misdiagnosis — the
200
+ * hook itself had already exited. Measured on this host with a grandchild holding
201
+ * the pipe: 60,0xx ms with the default timeout, and no return at all without one.
202
+ *
203
+ * The async version keeps the event loop live (Escape and Ctrl+C keep working) and
204
+ * gives a pipe-holding descendant the same grace-then-group-kill that the Bash tool
205
+ * already uses, so the wait is bounded by the hook, not by whatever it left behind.
206
+ * `detached` makes the child a process-group leader, which is what lets the group
207
+ * kill reach descendants rather than only the direct child.
208
+ */
209
+ async function runHookCommand(
210
+ command: string,
211
+ args: string[],
212
+ opts: { input: string; cwd: string; env: NodeJS.ProcessEnv | undefined; timeoutMs: number },
213
+ ): Promise<HookProcessResult> {
214
+ return await new Promise<HookProcessResult>((resolve) => {
215
+ let stdout = ''
216
+ let stderr = ''
217
+ let status: number | null = null
218
+ let signal: string | null = null
219
+ let spawnError: { code?: string; message?: string } | undefined
220
+ let timedOut = false
221
+ let settled = false
222
+ // `finish()` 先于计时器存在(它读 `timer`),而计时器只能在 `spawn` 之后开 ——
223
+ // 顺序反过来就是「还没起进程就先超时」。所以这里必须是 `let`。
224
+ // eslint-disable-next-line prefer-const -- 唯一那次赋值在 `finish` 之后
225
+ let timer: ReturnType<typeof setTimeout> | undefined
226
+ let graceTimer: ReturnType<typeof setTimeout> | undefined
227
+
228
+ const child = spawn(command, args, {
229
+ cwd: opts.cwd,
230
+ env: opts.env,
231
+ stdio: ['pipe', 'pipe', 'pipe'],
232
+ detached: true,
233
+ })
234
+
235
+ const killGroup = () => {
236
+ if (child.pid === undefined) return
237
+ try {
238
+ process.kill(-child.pid, 'SIGKILL')
239
+ } catch {
240
+ try {
241
+ child.kill('SIGKILL')
242
+ } catch {
243
+ // Already gone.
244
+ }
245
+ }
246
+ }
247
+
248
+ const finish = () => {
249
+ if (settled) return
250
+ settled = true
251
+ clearTimeout(timer)
252
+ clearTimeout(graceTimer)
253
+ // Keep the timeout distinguishable from an external kill: both arrive as
254
+ // `status: null`, and only this flag separates "the hook was too slow" from
255
+ // "something killed it" for the message the operator reads.
256
+ if (timedOut && !spawnError) {
257
+ spawnError = {
258
+ code: 'ETIMEDOUT',
259
+ message: `timed out after ${Math.round(opts.timeoutMs / 1000)}s`,
260
+ }
261
+ }
262
+ resolve({ status, signal, stdout, stderr, ...(spawnError ? { error: spawnError } : {}) })
263
+ }
264
+
265
+ timer = setTimeout(() => {
266
+ timedOut = true
267
+ killGroup()
268
+ // Resolve on the decision, not on a `close` the killed group may never
269
+ // produce: a descendant can outlive the SIGKILL's delivery and keep holding
270
+ // the pipe, and the old `spawnSync` had a hard bound here (a misdiagnosed
271
+ // one, but a bound). Without this, the pipe-holding case would wait forever
272
+ // instead of for the timeout.
273
+ finish()
274
+ }, opts.timeoutMs)
275
+
276
+ // The hook exited, but its stdio may still be held by a descendant it spawned.
277
+ // Give that descendant a short grace, then take the group down — otherwise the
278
+ // caller waits out the full timeout and blames the hook for a timeout it never had.
279
+ const startPipeGrace = () => {
280
+ graceTimer = setTimeout(killGroup, HOOK_PIPE_GRACE_MS)
281
+ }
282
+
283
+ child.stdout.on('data', (chunk: Buffer) => {
284
+ stdout += chunk.toString()
285
+ })
286
+ child.stderr.on('data', (chunk: Buffer) => {
287
+ stderr += chunk.toString()
288
+ })
289
+
290
+ child.on('error', (err: NodeJS.ErrnoException) => {
291
+ // A failed spawn (ENOENT, EACCES) never produces an exit or a close.
292
+ spawnError = { code: err.code, message: err.message }
293
+ finish()
294
+ })
295
+
296
+ child.on('exit', (code, sig) => {
297
+ status = code
298
+ signal = sig
299
+ startPipeGrace()
300
+ })
301
+
302
+ // `close` fires once stdio is closed *and* the child has exited — the exact
303
+ // event `spawnSync` was waiting on, minus the frozen thread.
304
+ child.on('close', (code, sig) => {
305
+ status = code
306
+ signal = sig
307
+ finish()
308
+ })
309
+
310
+ // The payload races the child's exit: a child that ignores stdin is gone before
311
+ // the write lands, and the EPIPE that results is a scheduler property, not a hook
312
+ // failure (see `spawnFailureCause`). Recorded as the result's `error` so the
313
+ // existing EPIPE exemption still applies.
314
+ child.stdin.on('error', (err: NodeJS.ErrnoException) => {
315
+ // Only EPIPE is recorded: any other failure here has already been reported by
316
+ // the `error` handler above with a more useful code.
317
+ if (err.code === 'EPIPE' && !spawnError) {
318
+ spawnError = { code: 'EPIPE', message: err.message }
319
+ }
320
+ })
321
+ try {
322
+ child.stdin.end(opts.input)
323
+ } catch {
324
+ // The stream surfaced it through the `error` handler.
325
+ }
326
+ })
327
+ }
328
+
179
329
  async function executeCommand(
180
330
  cfg: HookConfig,
181
331
  ctx: HookContext,
@@ -186,8 +336,8 @@ async function executeCommand(
186
336
  try {
187
337
  const args = cfg.args ? cfg.args.map((a) => substituteVars(a, ctx)) : []
188
338
 
189
- // A hook command is a child of this process, so a bare `spawnSync` would hand
190
- // it the whole environment — every provider key and bot secret included. Bash
339
+ // A hook command is a child of this process, so inheriting the environment
340
+ // would hand it everything — every provider key and bot secret included. Bash
191
341
  // has been masking these since E1; hooks were the remaining door, so they use
192
342
  // the same policy. Resolved at **user level** — the same choice E1 made for
193
343
  // every spawn it could not scope to one session's project section
@@ -207,13 +357,10 @@ async function executeCommand(
207
357
  // hand, and is exactly right for the one-shot CLI.
208
358
  const cwd = ctx.cwd ?? process.cwd()
209
359
 
210
- // Use spawnSync with array args — no shell, no command injection.
211
- // Pass the Claude-protocol stdin JSON so scripts can read structured context.
360
+ // Array args — no shell, so no command injection. The Claude-protocol stdin JSON
361
+ // goes in so scripts can read structured context.
212
362
  const input = JSON.stringify(buildHookStdin(ctx, cwd))
213
- const result = spawnSync(cfg.command, args, {
214
- timeout: (cfg.timeout ?? 60) * 1000,
215
- encoding: 'utf-8',
216
- stdio: ['pipe', 'pipe', 'pipe'],
363
+ const result = await runHookCommand(cfg.command, args, {
217
364
  input,
218
365
  // Both halves of "where is this hook": the directory it runs in, and the
219
366
  // `cwd` it reads off stdin. Fixing only one leaves the hook told it is
@@ -222,6 +369,7 @@ async function executeCommand(
222
369
  // `undefined` = inherit, which is what node does by default; passing it
223
370
  // explicitly keeps the two branches visible at one site.
224
371
  env,
372
+ timeoutMs: (cfg.timeout ?? 60) * 1000,
225
373
  })
226
374
 
227
375
  // Exit code 0 = success — parse the stdout JSON for structured decisions.
@@ -255,9 +403,10 @@ async function executeCommand(
255
403
  additionalContext: `Hook warning ${failingLabel(cfg.command, source)}: ${stderr.trim()}`,
256
404
  }
257
405
  } catch (err) {
258
- // Only reached when `spawnSync` itself throws — masking-policy load, env
259
- // filter, or an option it rejects outright. Its comment used to name timeouts
260
- // and missing commands, neither of which can arrive here.
406
+ // Only reached when the setup around the spawn throws — masking-policy load,
407
+ // env filter, or an option `spawn` rejects synchronously. A failed exec or a
408
+ // timeout is *not* a throw here: both are reported on the result (see
409
+ // `spawnFailureCause`), which is why this comment used to name them wrongly.
261
410
  const message = (err as { message?: string }).message || String(err)
262
411
 
263
412
  return {