@miphamai/cli 0.85.25 → 0.85.27

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.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 「这条权限规则写坏了」的告警,每个用户只看一次 —— 直到那条规则本身变了。
3
+ *
4
+ * 规则是从 settings 文件里读的,文件不修,告警就每次启动都会原样重复。重复的
5
+ * 告警不是提醒,是噪音:用户读到第七次时就已经不再读了,于是**新**出现的那条
6
+ * 坏规则混在里面也看不见。认领(ack)按**告警文本**记账,文本变了就是另一条
7
+ * 规则,重新报。
8
+ *
9
+ * 写盘失败一律按「没认领过」处理 —— 宁可多报一次,也不因为盘上写不进去而把
10
+ * 一条本该 fail-closed 的坏规则静默吞掉。
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
14
+ import { dirname } from 'node:path'
15
+ import { miphamHome } from './paths'
16
+ import { atomicWriteFileSync } from '../shared/atomic-write'
17
+
18
+ /** 记账文件里保留的条目上限 —— 规则文本会随编辑不断变新,不设上限就是无限长。 */
19
+ const MAX_ACKS = 200
20
+
21
+ interface AckFile {
22
+ acknowledged: string[]
23
+ }
24
+
25
+ function ackPath(): string {
26
+ return miphamHome('permission-rule-acks.json')
27
+ }
28
+
29
+ function readAcks(): string[] {
30
+ const path = ackPath()
31
+ if (!existsSync(path)) return []
32
+ try {
33
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'))
34
+ const list = (parsed as AckFile | null)?.acknowledged
35
+ if (!Array.isArray(list)) return []
36
+ return list.filter((v): v is string => typeof v === 'string')
37
+ } catch {
38
+ // 文件坏了 = 没有记账。重报一次然后重写。
39
+ return []
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Narrow `messages` to the ones this user has not seen yet, and remember them.
45
+ *
46
+ * Returns the messages to print. A message that was already acknowledged — and
47
+ * whose text has not changed since — is dropped.
48
+ */
49
+ export function unacknowledgedRuleWarnings(messages: readonly string[]): string[] {
50
+ if (messages.length === 0) return []
51
+ const seen = new Set(readAcks())
52
+ const fresh = messages.filter((m) => !seen.has(m))
53
+ if (fresh.length === 0) return []
54
+
55
+ for (const m of fresh) seen.add(m)
56
+ const next = [...seen].slice(-MAX_ACKS)
57
+ try {
58
+ const path = ackPath()
59
+ mkdirSync(dirname(path), { recursive: true })
60
+ atomicWriteFileSync(path, `${JSON.stringify({ acknowledged: next }, null, 2)}\n`, {
61
+ mode: 0o644,
62
+ })
63
+ } catch {
64
+ // 写不进去 ⇒ 下次还会报(见文件头:多报比静默好)
65
+ }
66
+ return fresh
67
+ }
@@ -29,6 +29,7 @@ import type { ProviderRegistry } from '../providers/registry'
29
29
  import { SkillsLoader } from '../skills/loader'
30
30
  import { RulesLoader } from '../core/rules-loader'
31
31
  import { HookEngine } from '../core/hooks'
32
+ import { registerBuiltinHooks } from '../core/merge-gate'
32
33
  import { loadHookConfigs } from '../core/hooks-config'
33
34
  import { isSafeMode } from '../core/safe-mode'
34
35
  import { loadSettingsJson } from '../config/loader'
@@ -101,6 +102,7 @@ function hooksFor(cwd: string, skills: SkillsLoader): HookEngine {
101
102
  for (const skill of skills.list()) {
102
103
  for (const hook of skill.hooks ?? []) engine.register(hook)
103
104
  }
105
+ registerBuiltinHooks(engine)
104
106
  // 项目级 hooks 是仓库可控的代码执行面,且 daemon 这条路径**从不**经过交互式信任
105
107
  // 询问 —— 而 `isCwdAllowed` 只要求会话 cwd 在 daemon 根目录之内(`workspace-guard.ts:27`
106
108
  // `isWithin(cwd, daemonRoot) || isTrusted(cwd)`)⇒ 在未信任的克隆里启动的 daemon,
@@ -155,11 +155,17 @@ export class RemoteEngine {
155
155
 
156
156
  ws.onclose = () => {
157
157
  // Only signal to the generator if there is an active wait.
158
- if (this.resolveNext) {
159
- const doneChunk: StreamChunk = { type: 'stop' }
160
- this.resolveNext(doneChunk)
161
- this.resolveNext = null
162
- }
158
+ if (!this.resolveNext) return
159
+ // 还在等流而连接没了 = 会话进程退出(daemon 停了/被杀),这一轮**没有写完**。
160
+ // 回一个裸 `stop` 会让它在屏幕上与一次正常结束完全同形:用户拿到半截回答,
161
+ // 既不知道被中断,也不知道下一步能做什么。报错并点名恢复动作。
162
+ this.resolveNext({
163
+ type: 'error',
164
+ error:
165
+ 'The daemon stopped — the process running this session has exited, and this turn did not finish. ' +
166
+ `Start it again with "mipham daemon start", then reattach with "mipham attach ${this.sessionId}".`,
167
+ })
168
+ this.resolveNext = null
163
169
  }
164
170
 
165
171
  ws.onerror = () => {
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { DaemonDatabase } from './database'
6
6
  import type { WorkerPool } from './worker-pool'
7
+ import type { SessionWorker } from './session-worker'
7
8
  import type { DaemonSchedule } from './types'
8
9
  import { logger } from './logger'
9
10
  import { computeNextFire } from '../core/cron'
@@ -12,12 +13,26 @@ export class ScheduleManager {
12
13
  private db: DaemonDatabase
13
14
  private pool: WorkerPool
14
15
  private intervalId: Timer | null = null
16
+ private spawnWorker: ((sessionId: string) => SessionWorker | null) | null = null
15
17
 
16
18
  constructor(db: DaemonDatabase, pool: WorkerPool) {
17
19
  this.db = db
18
20
  this.pool = pool
19
21
  }
20
22
 
23
+ /**
24
+ * Register the daemon's "bring this session's worker back" hook.
25
+ *
26
+ * Workers are otherwise created lazily, on an inbound prompt — so a session
27
+ * whose worker was never started, or was recycled by the idle timeout, has
28
+ * nobody to deliver a due schedule to, and the cron entry silently never runs.
29
+ * The daemon wires this once its own engine factory exists (it is created after
30
+ * this manager), which is why it is a setter and not a constructor argument.
31
+ */
32
+ setWorkerSpawner(fn: (sessionId: string) => SessionWorker | null): void {
33
+ this.spawnWorker = fn
34
+ }
35
+
21
36
  createSchedule(sessionId: string, cronExpr: string, prompt: string): number {
22
37
  const now = new Date()
23
38
  const nextFire = computeNextFire(cronExpr, now)
@@ -43,15 +58,29 @@ export class ScheduleManager {
43
58
  * Check for due schedules and fire them.
44
59
  *
45
60
  * For each schedule whose nextFire has passed:
46
- * 1. Look up the session worker — skip if none is active
61
+ * 1. Look up the session worker — start one if none is active and the daemon
62
+ * supplied a spawner (a recycled or never-started session must still get its
63
+ * scheduled prompt; skipping it means the cron entry never runs at all)
47
64
  * 2. Send the prompt to the worker (fire-and-forget)
48
65
  * 3. Update lastFired and compute the next fire time
66
+ *
67
+ * A schedule that still has no worker is left alone — `nextFire` stays in the
68
+ * past, so the next tick tries again rather than dropping the run.
49
69
  */
50
70
  checkAndFire(): void {
51
71
  const due = this.db.getDueSchedules()
52
72
  for (const schedule of due) {
53
- const worker = this.pool.getWorker(schedule.sessionId)
54
- if (!worker) continue
73
+ const worker =
74
+ this.pool.getWorker(schedule.sessionId) ??
75
+ this.spawnWorker?.(schedule.sessionId) ??
76
+ undefined
77
+ if (!worker) {
78
+ logger.warn('scheduled prompt skipped: no worker for session', {
79
+ scheduleId: schedule.id,
80
+ sessionId: schedule.sessionId,
81
+ })
82
+ continue
83
+ }
55
84
 
56
85
  worker.processPrompt(schedule.prompt).catch((err: unknown) => {
57
86
  logger.error('error firing schedule', { scheduleId: schedule.id, error: err })
@@ -325,6 +325,12 @@ export function createServer(config: ServerConfig): Server<WsData> {
325
325
  }
326
326
  }
327
327
 
328
+ // Scheduled prompts must not depend on someone having opened the session: the
329
+ // scheduler fires into whatever worker exists, and workers only exist after an
330
+ // inbound prompt or `set_mode`. Handing it the same factory the WS handlers use
331
+ // makes a due schedule able to bring its own worker up.
332
+ scheduleManager.setWorkerSpawner((sessionId) => getOrCreateWorker(sessionId))
333
+
328
334
  // ── Feishu remote-control adapter(独立签名验证,复用同一 worker 池)──
329
335
  const feishuAdapter = feishu
330
336
  ? createFeishuAdapter(feishu.config, {
@@ -297,7 +297,14 @@
297
297
  "consolidate_result": "Consolidated: {removed} auto-* removed, {merged} lessons written.",
298
298
  "dedup_title": "─ Memory Near-Duplicates ─",
299
299
  "dedup_none": "No near-duplicate memories found.",
300
- "dedup_footer": "Pairs above the TF-IDF cosine threshold. Merge is manual — run /memory consolidate for auto-* clustering, or edit the files directly."
300
+ "dedup_footer": "Pairs above the TF-IDF cosine threshold. Merge is manual — run /memory consolidate for auto-* clustering, or edit the files directly.",
301
+ "doctor_title": "─ Memory Doctor ─",
302
+ "doctor_clean": "Store is consistent: {count} memories, index in sync, no broken links.",
303
+ "doctor_invisible": "Invisible to recall ({count}) — the loader skips these files:",
304
+ "doctor_duplicate": "Duplicate names ({count}) — only one file of each is reachable:",
305
+ "doctor_broken_link": "Broken wikilinks ({count}):",
306
+ "doctor_index": "Index drift ({count}) — MEMORY.md disagrees with the store:",
307
+ "doctor_footer": "Read-only report. Fix the files above by hand; for the rest, run /memory gc, /memory consolidate or /memory dedup."
301
308
  },
302
309
  "upgrade": {
303
310
  "uptodate": "── Upgrade Mipham Code ──\n\nCurrent version: v{current}\nLatest: v{latest}\n\n✓ Already up to date.\n\nTo check manually: https://www.npmjs.com/package/@miphamai/cli",
@@ -968,7 +975,7 @@
968
975
  "max_tool_turns": "Max tool-calling turns ({max}) reached. Some tool calls were not executed.",
969
976
  "max_tool_turns_warning": "You've reached the maximum of {max} tool-calling rounds. {pending} tool call(s) were not executed. Please summarize what you found so far and any next steps the user should take.",
970
977
  "turn_timeout": "Task produced no substantial output for {minutes} minutes and was stopped. Break the task into smaller steps or clarify the next step, then retry.",
971
- "turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed.",
978
+ "turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed. If you reach the provider through a proxy or a corporate gateway, check that first; otherwise check your VPN and firewall rules.",
972
979
  "turn_refused": "The model declined this request and did not answer. This is not a failure — resending it to the same model will usually be declined again.",
973
980
  "turn_refused_reason": "The model declined this request: {reason}",
974
981
  "stop_hook_budget_spent": "The Stop hook asked for more work (\"{reason}\"), but this turn has used all {max} of its tool-calling rounds — stopping here. Send another message to continue.",
@@ -989,7 +996,8 @@
989
996
  "context": {
990
997
  "omitted": "Prior conversation context omitted.",
991
998
  "summary_heading": "[Earlier conversation summary — {heading}]",
992
- "stop_blocked": "[The Stop hook blocked completion]: {reason}"
999
+ "stop_blocked": "[The Stop hook blocked completion]: {reason}",
1000
+ "numbers_unproven": "[Numbers with no source this turn]: {claims}. You reported these counts, but no tool output in this session — and not the user's own words — carries them. Either run the command that produces each one, or say plainly that it is an estimate. Do not restate a guessed number as a measurement."
993
1001
  },
994
1002
  "goal": {
995
1003
  "verified": "✅ Goal verification passed: {script}",
@@ -297,7 +297,14 @@
297
297
  "consolidate_result": "合并完成:删除 {removed} 条 auto-*,写入 {merged} 条 lesson-*。",
298
298
  "dedup_title": "─ 记忆近重复 ─",
299
299
  "dedup_none": "未发现近重复记忆。",
300
- "dedup_footer": "以上为 TF-IDF 余弦超过阈值的近重复对。合并需手动——auto-* 走 /memory consolidate 聚簇,或直接编辑文件。"
300
+ "dedup_footer": "以上为 TF-IDF 余弦超过阈值的近重复对。合并需手动——auto-* 走 /memory consolidate 聚簇,或直接编辑文件。",
301
+ "doctor_title": "─ 记忆体检 ─",
302
+ "doctor_clean": "记忆库一致:{count} 条记忆,索引同步,无断链。",
303
+ "doctor_invisible": "召回看不见({count})—— 加载器会跳过这些文件:",
304
+ "doctor_duplicate": "重名({count})—— 每个同名只有一份够得着:",
305
+ "doctor_broken_link": "断掉的 wikilink({count}):",
306
+ "doctor_index": "索引漂移({count})—— MEMORY.md 与记忆库对不上:",
307
+ "doctor_footer": "只读报告。上面这些需手改或删除文件;其余走 /memory gc、/memory consolidate、/memory dedup。"
301
308
  },
302
309
  "upgrade": {
303
310
  "uptodate": "── 升级 Mipham Code ──\n\n当前版本: v{current}\n最新版本: v{latest}\n\n✓ 已是最新版本。\n\n手动检查: https://www.npmjs.com/package/@miphamai/cli",
@@ -968,7 +975,7 @@
968
975
  "max_tool_turns": "超出最大工具调用轮次({max})。部分工具调用未执行。",
969
976
  "max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
970
977
  "turn_timeout": "任务已超过 {minutes} 分钟无实质产出,已自动停止。建议拆分任务或明确下一步后重新发起。",
971
- "turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。",
978
+ "turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。如果是经代理或公司网关访问提供商,先查那一层;否则检查 VPN 与防火墙规则。",
972
979
  "turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
973
980
  "turn_refused_reason": "模型拒绝了这次请求:{reason}",
974
981
  "stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
@@ -989,7 +996,8 @@
989
996
  "context": {
990
997
  "omitted": "之前的对话上下文已省略。",
991
998
  "summary_heading": "[之前的对话摘要 — {heading}]",
992
- "stop_blocked": "[Stop 钩子阻止完成]:{reason}"
999
+ "stop_blocked": "[Stop 钩子阻止完成]:{reason}",
1000
+ "numbers_unproven": "[本轮没有出处的数字]:{claims}。这些是你汇报的数量,但本次会话的任何工具输出里都没有它们,用户这句话里也没有。要么去跑产它的那一条命令,要么明说这是估算 —— 不要把猜出来的数当量出来的数说出去。"
993
1001
  },
994
1002
  "goal": {
995
1003
  "verified": "✅ 目标验证通过:{script}",
package/src/index.tsx CHANGED
@@ -28,6 +28,8 @@ import { ContextManager } from './core/context'
28
28
  import { PrefixCacheTracker } from './core/context-token'
29
29
  import { QueryEngine } from './core/engine'
30
30
  import { RulesLoader } from './core/rules-loader'
31
+ import { setActiveTaskSession } from './tools/exec/task'
32
+ import { unacknowledgedRuleWarnings } from './core/permission-rule-ack'
31
33
  import { generateSessionName } from './core/session-name'
32
34
  import { ExperienceRuleEngine } from './core/rule-engine.js'
33
35
  import { SessionLog } from './core/session-log'
@@ -50,6 +52,7 @@ import { registerMcpServerTools, syncMcpToolsOnChange } from './mcp/registry'
50
52
  import { formatMcpConnectFailures, type McpConnectFailure } from './mcp/connect-failures'
51
53
  import { AgentRegistry } from './agent/agent-registry'
52
54
  import { HookEngine } from './core/hooks'
55
+ import { registerBuiltinHooks } from './core/merge-gate'
53
56
  import { loadHookConfigs } from './core/hooks-config'
54
57
  import { isSafeMode } from './core/safe-mode'
55
58
  import { ArtifactServer } from './artifacts/server'
@@ -320,7 +323,12 @@ async function connectMcpServers(
320
323
  const name = mcpServers[i]!.name
321
324
  const reason = String(result.reason)
322
325
  failures.push({ name, reason })
323
- console.error(`[mcp] Failed to connect "${name}": ${reason}`)
326
+ // Say the retry out loud when there is one: the client is already trying
327
+ // again in the background, and a bare "failed" reads as a final verdict.
328
+ const retrying = mcp.isRetrying(name)
329
+ ? ' — retrying in the background; /mcp shows the current state'
330
+ : ''
331
+ console.error(`[mcp] Failed to connect "${name}": ${reason}${retrying}`)
324
332
  }
325
333
  }
326
334
  // No success line before the TUI: with five configured servers this was a line
@@ -590,6 +598,10 @@ export async function runApp(options: RunOptions): Promise<void> {
590
598
  compactionThreshold: 0.9,
591
599
  contextWindow: adaptiveThresholds ? modelContextWindow : undefined,
592
600
  })
601
+ // Load this session's task list up front. The Task tool would load it on first
602
+ // touch anyway, but the goal panel renders from it before then — and on a
603
+ // resumed session the whole point is that the plan comes back on screen.
604
+ setActiveTaskSession(sessionName)
593
605
  const sessionLog = new SessionLog(sessionName)
594
606
  sessionLog.append({
595
607
  type: 'session/start',
@@ -620,6 +632,23 @@ export async function runApp(options: RunOptions): Promise<void> {
620
632
  // Adaptive memory budget: scale with model's context window
621
633
  getMemoryManager().setContextWindow(modelContextWindow)
622
634
 
635
+ /**
636
+ * 把系统提示装进上下文,并且留下重建方式。
637
+ *
638
+ * 提示里的指令文件(`CLAUDE.md` / `AGENTS.md` / `USER.md`)是启动那一刻读的,
639
+ * 会话中被改过就只有重启才生效。压缩之后引擎会让提示重建一次,重建器在拼装前
640
+ * 先回读磁盘;**只换指令那一段**,`extra` 原样保留 —— 那是启动时拼进来的会话级
641
+ * 上下文(技能提醒、记忆召回、上一会话摘要、首跑提示),再生成一遍等于把它们
642
+ * 重复塞进每个请求。
643
+ */
644
+ const applySystemPrompt = (base: string, extra: string): void => {
645
+ context.setSystemPrompt(base + extra)
646
+ context.setSystemPromptRebuilder(() => {
647
+ instructions.refresh()
648
+ return instructions.buildSystemPrompt() + extra
649
+ })
650
+ }
651
+
623
652
  if (options.resume) {
624
653
  const log = SessionStore.loadLog(options.resume)
625
654
  const events = log.events()
@@ -654,7 +683,7 @@ export async function runApp(options: RunOptions): Promise<void> {
654
683
  }
655
684
  }
656
685
  context.restoreLog(log)
657
- context.setSystemPrompt(instructions.buildSystemPrompt())
686
+ applySystemPrompt(instructions.buildSystemPrompt(), '')
658
687
  }
659
688
  }
660
689
 
@@ -730,7 +759,7 @@ export async function runApp(options: RunOptions): Promise<void> {
730
759
  prompt = `${prompt}\n\n<system-reminder name="missing-mipham-md">\n${partialReminder}\n</system-reminder>`
731
760
  }
732
761
 
733
- context.setSystemPrompt(prompt)
762
+ applySystemPrompt(basePrompt, prompt.slice(basePrompt.length))
734
763
  }
735
764
 
736
765
  // Initialize credential masking pipeline (strategies: Full, Extract, JWT)
@@ -769,6 +798,7 @@ export async function runApp(options: RunOptions): Promise<void> {
769
798
  }
770
799
  }
771
800
  }
801
+ registerBuiltinHooks(hookEngine)
772
802
  }
773
803
 
774
804
  // Register settings.json hooks (Claude Code convention — additive across levels).
@@ -834,7 +864,9 @@ export async function runApp(options: RunOptions): Promise<void> {
834
864
 
835
865
  // Surface malformed permission rules as warnings instead of silently letting
836
866
  // them never match (e.g. a deny rule typed `Bash(ls) x` would fail closed).
837
- for (const msg of engine.getPermission().getInvalidRules()) {
867
+ // 同一句警告每个用户只报一次:settings 文件不修,它每次启动都一样,重复到第七
868
+ // 次就不再是提醒 —— 而新出现的那条坏规则会混在旧噪音里没人看见。
869
+ for (const msg of unacknowledgedRuleWarnings(engine.getPermission().getInvalidRules())) {
838
870
  process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
839
871
  }
840
872
 
package/src/mcp/client.ts CHANGED
@@ -314,6 +314,14 @@ export class McpClient {
314
314
  this.connections.delete(name)
315
315
 
316
316
  await this.connect(config)
317
+ // The startup path registers tools right after a successful `connect()`;
318
+ // a server that only came up on a retry never goes through it, so the
319
+ // registry would answer "no such tool" for a server that is green in
320
+ // `/mcp`. Push the list this connection just discovered. `applyToolChanges`
321
+ // overwrites by name, so on a mid-session reconnect (tools already known)
322
+ // this is a no-op.
323
+ const fresh = this.connections.get(name)
324
+ if (fresh) this.emit('tools-changed', name, fresh.tools, [])
317
325
  this.emit('reconnected', name)
318
326
  return
319
327
  } catch (err) {
@@ -393,12 +401,33 @@ export class McpClient {
393
401
  this.connecting.set(config.name, attempt)
394
402
  try {
395
403
  await attempt
404
+ } catch (err) {
405
+ // A handshake that never finished is not a verdict. The server that timed
406
+ // out at 15 s is often ready a few seconds later (a cold `npx` download, a
407
+ // Python server still importing), and a refused socket means "not up yet"
408
+ // just as often as "gone". Mid-session losses already come back unaided;
409
+ // a startup failure used to latch 'error' for the rest of the session, so
410
+ // the tools never appeared at all. A definitive refusal (4xx auth) is not
411
+ // retried — see `isTransientConnectError`.
412
+ if (isTransientConnectError(err) && this.autoReconnect && !this.closing) {
413
+ this.scheduleAutoReconnect(config.name)
414
+ }
415
+ throw err
396
416
  } finally {
397
417
  // 无论成败都要放开这个名字:失败后用户重连,得能真的重连。
398
418
  this.connecting.delete(config.name)
399
419
  }
400
420
  }
401
421
 
422
+ /**
423
+ * Whether a server that just failed to connect is being retried in the
424
+ * background. The startup reporter uses this to say so: a bare "failed" line
425
+ * is a verdict the client is about to contradict.
426
+ */
427
+ isRetrying(name: string): boolean {
428
+ return this.reconnecting.has(name)
429
+ }
430
+
402
431
  private async connectOnce(config: McpServerConfig): Promise<void> {
403
432
  const transport: StdioTransport | HttpTransport = config.url
404
433
  ? new HttpTransport(undefined, config.request_timeout_ms)
@@ -504,11 +533,16 @@ export class McpClient {
504
533
  * connecting. A server this client knows nothing about is `true`: there is
505
534
  * nothing to wait for, and `callTool` will say so.
506
535
  */
507
- async waitUntilReady(name: string, timeoutMs: number = connectTimeoutMs()): Promise<boolean> {
536
+ async waitUntilReady(
537
+ name: string,
538
+ timeoutMs: number = connectTimeoutMs(),
539
+ signal?: AbortSignal,
540
+ ): Promise<boolean> {
508
541
  // Awake time, same as the handshake budget it mirrors: a sleep mid-wait must
509
542
  // not spend the deadline the server never got to use.
510
543
  const deadline = performance.now() + timeoutMs
511
544
  for (;;) {
545
+ if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')
512
546
  const conn = this.connections.get(name)
513
547
  if (!conn || conn.status !== 'connecting') return true
514
548
  if (performance.now() >= deadline) return false
@@ -608,6 +642,7 @@ export class McpClient {
608
642
  serverName: string,
609
643
  toolName: string,
610
644
  params?: Record<string, unknown>,
645
+ signal?: AbortSignal,
611
646
  ): Promise<ToolCallResult> {
612
647
  const conn = this.connections.get(serverName)
613
648
  if (!conn || conn.status !== 'connected') {
@@ -618,7 +653,7 @@ export class McpClient {
618
653
  }
619
654
 
620
655
  try {
621
- return await conn.protocol.callTool(toolName, params)
656
+ return await conn.protocol.callTool(toolName, params, signal)
622
657
  } catch (err) {
623
658
  this.markIfTransportLost(serverName, conn)
624
659
  // A scope refusal is actionable and nothing else is: the user has to go
@@ -191,10 +191,17 @@ export class HttpTransport implements Transport {
191
191
  }
192
192
  }
193
193
 
194
- async sendRequest(method: string, params?: Record<string, unknown>): Promise<unknown> {
194
+ async sendRequest(
195
+ method: string,
196
+ params?: Record<string, unknown>,
197
+ signal?: AbortSignal,
198
+ ): Promise<unknown> {
195
199
  if (!this.url || this.closed) {
196
200
  throw new Error('Transport not connected')
197
201
  }
202
+ if (signal?.aborted) {
203
+ throw new DOMException('Aborted', 'AbortError')
204
+ }
198
205
 
199
206
  const id = ++this.msgId
200
207
  const request: JsonRpcRequest = {
@@ -205,6 +212,12 @@ export class HttpTransport implements Transport {
205
212
  }
206
213
 
207
214
  const controller = new AbortController()
215
+ // The turn's cancellation and the per-request timeout share one controller,
216
+ // because `fetch` takes one signal. The caller's abort must not be read as
217
+ // "the endpoint never answered": that branch below marks the transport
218
+ // closed, which would turn an interrupt into a dead MCP server.
219
+ const onAbort = (): void => controller.abort()
220
+ signal?.addEventListener('abort', onAbort, { once: true })
208
221
  const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs)
209
222
 
210
223
  // Did an HTTP response come back at all? A rejected fetch or a timeout means
@@ -251,6 +264,11 @@ export class HttpTransport implements Transport {
251
264
  }
252
265
  return json.result
253
266
  } catch (err) {
267
+ if (signal?.aborted) {
268
+ // The caller cancelled. The server is fine — aborting the fetch says
269
+ // nothing about it — so the transport stays connected.
270
+ throw new DOMException('Aborted', 'AbortError')
271
+ }
254
272
  if (controller.signal.aborted) {
255
273
  // The endpoint never answered. Every later request would hang the same
256
274
  // way, so the transport reports itself disconnected — the same state a
@@ -265,6 +283,7 @@ export class HttpTransport implements Transport {
265
283
  throw err
266
284
  } finally {
267
285
  clearTimeout(timer)
286
+ signal?.removeEventListener('abort', onAbort)
268
287
  }
269
288
  }
270
289
 
@@ -135,11 +135,19 @@ export class McpProtocol {
135
135
  return result.tools || []
136
136
  }
137
137
 
138
- async callTool(name: string, args?: Record<string, unknown>): Promise<ToolCallResult> {
139
- const result = (await this.transport.sendRequest('tools/call', {
140
- name,
141
- arguments: args || {},
142
- })) as ToolCallResult
138
+ async callTool(
139
+ name: string,
140
+ args?: Record<string, unknown>,
141
+ signal?: AbortSignal,
142
+ ): Promise<ToolCallResult> {
143
+ const result = (await this.transport.sendRequest(
144
+ 'tools/call',
145
+ {
146
+ name,
147
+ arguments: args || {},
148
+ },
149
+ signal,
150
+ )) as ToolCallResult
143
151
  return result
144
152
  }
145
153
 
@@ -105,7 +105,7 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
105
105
  category: 'system',
106
106
  permission: 'ask',
107
107
  parameters,
108
- async execute(params: Record<string, unknown>, _ctx: ToolContext): Promise<ToolResult> {
108
+ async execute(params: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult> {
109
109
  const client = McpClient.getInstance()
110
110
 
111
111
  // Startup connects servers without blocking, and a resumed session re-attaches
@@ -114,7 +114,7 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
114
114
  // the only thing missing is patience. Same wait the `mcp_tool` hook already
115
115
  // does (`core/hooks-executor.ts`), so both entry points treat a connecting
116
116
  // server identically. A server that is *not* connecting returns immediately.
117
- await client.waitUntilReady(serverName)
117
+ await client.waitUntilReady(serverName, undefined, ctx.signal)
118
118
 
119
119
  const conn = client.getConnection(serverName)
120
120
  if (!conn || conn.status !== 'connected') {
@@ -125,7 +125,12 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
125
125
  }
126
126
  }
127
127
 
128
- const result: ToolCallResult = await client.callTool(serverName, mcpTool.name, params)
128
+ const result: ToolCallResult = await client.callTool(
129
+ serverName,
130
+ mcpTool.name,
131
+ params,
132
+ ctx.signal,
133
+ )
129
134
 
130
135
  const text = result.content
131
136
  .map((c) => {
@@ -12,7 +12,11 @@ export type NotificationHandler = (notification: JsonRpcNotification) => void
12
12
  * interface — callers invoke the concrete `start(...)` before use.
13
13
  */
14
14
  export interface Transport {
15
- sendRequest(method: string, params?: Record<string, unknown>): Promise<unknown>
15
+ sendRequest(
16
+ method: string,
17
+ params?: Record<string, unknown>,
18
+ signal?: AbortSignal,
19
+ ): Promise<unknown>
16
20
  sendNotification(method: string, params?: Record<string, unknown>): void
17
21
  onNotification(handler: NotificationHandler): void
18
22
  close(): Promise<void>
@@ -214,10 +218,17 @@ export class StdioTransport implements Transport {
214
218
  })
215
219
  }
216
220
 
217
- async sendRequest(method: string, params?: Record<string, unknown>): Promise<unknown> {
221
+ async sendRequest(
222
+ method: string,
223
+ params?: Record<string, unknown>,
224
+ signal?: AbortSignal,
225
+ ): Promise<unknown> {
218
226
  if (!this.proc || this.closed) {
219
227
  throw new Error('Transport not connected')
220
228
  }
229
+ if (signal?.aborted) {
230
+ throw new DOMException('Aborted', 'AbortError')
231
+ }
221
232
 
222
233
  const id = ++this.msgId
223
234
  const request: JsonRpcRequest = {
@@ -228,12 +239,38 @@ export class StdioTransport implements Transport {
228
239
  }
229
240
 
230
241
  return new Promise((resolve, reject) => {
242
+ // Cancellation has to reach the request itself: the caller's turn-level
243
+ // signal used to stop at the tool boundary, so a server that never
244
+ // answered held the turn until the 60s request timeout. Clearing the
245
+ // timer and deleting the pending entry keeps that timer from firing a
246
+ // second rejection on an already-settled promise.
247
+ const onAbort = (): void => {
248
+ const entry = this.pending.get(id)
249
+ if (!entry) return
250
+ this.pending.delete(id)
251
+ clearTimeout(entry.timer)
252
+ reject(new DOMException('Aborted', 'AbortError'))
253
+ }
254
+ signal?.addEventListener('abort', onAbort, { once: true })
255
+ const cleanup = (): void => signal?.removeEventListener('abort', onAbort)
256
+
231
257
  const timer = setTimeout(() => {
232
258
  this.pending.delete(id)
259
+ cleanup()
233
260
  reject(requestTimeoutError(method, this.requestTimeoutMs))
234
261
  }, this.requestTimeoutMs)
235
262
 
236
- this.pending.set(id, { resolve, reject, timer })
263
+ this.pending.set(id, {
264
+ resolve: (v) => {
265
+ cleanup()
266
+ resolve(v)
267
+ },
268
+ reject: (e) => {
269
+ cleanup()
270
+ reject(e)
271
+ },
272
+ timer,
273
+ })
237
274
 
238
275
  // Write to stdin
239
276
  this.proc!.stdin!.write(JSON.stringify(request) + '\n')
@@ -199,7 +199,9 @@ export class AnthropicProvider implements ProviderInstance {
199
199
  yield {
200
200
  type: 'error',
201
201
  error: `Anthropic API error ${response.status}: ${errText}`,
202
- retryable: isRetryableFailure(response.status),
202
+ // 服务端给了 `x-should-retry` 就以它为准:429/5xx 上是「这件事不会有
203
+ // 下一次」,而只看状态会把这一轮挂在一架不可能成功的重试梯子上。
204
+ retryable: isRetryableFailure(response.status, undefined, response.headers),
203
205
  }
204
206
  return
205
207
  }