@miphamai/cli 0.85.18 → 0.85.20

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 (43) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/agent-registry.ts +2 -0
  4. package/src/agent/auto-compact.ts +72 -0
  5. package/src/agent/sub-agent.ts +26 -1
  6. package/src/agent/types.ts +18 -0
  7. package/src/agent-view/agent-view-manager.ts +50 -0
  8. package/src/core/context.ts +15 -3
  9. package/src/core/engine.ts +52 -5
  10. package/src/core/instructions.ts +78 -2
  11. package/src/daemon/channel-message.ts +8 -1
  12. package/src/daemon/session-worker.ts +17 -2
  13. package/src/i18n-core/locales/en-US.json +13 -3
  14. package/src/i18n-core/locales/zh-CN.json +13 -3
  15. package/src/index.tsx +8 -0
  16. package/src/mcp/client.ts +46 -0
  17. package/src/mcp/instructions.ts +48 -10
  18. package/src/mcp/protocol.ts +69 -2
  19. package/src/mcp/registry.ts +2 -1
  20. package/src/mcp/transport.ts +70 -9
  21. package/src/plugin/plugin-manager.ts +29 -8
  22. package/src/providers/fetch-utils.ts +47 -2
  23. package/src/security/fd.ts +18 -0
  24. package/src/shared/package-info.ts +2 -2
  25. package/src/shared/sanitize.ts +6 -2
  26. package/src/shared/types.ts +16 -0
  27. package/src/skills/marketplace.ts +15 -5
  28. package/src/skills/registry.ts +4 -1
  29. package/src/tools/agent/agent.ts +24 -0
  30. package/src/tools/agent/skill.ts +13 -0
  31. package/src/tools/exec/bash.ts +10 -0
  32. package/src/tools/file/edit.ts +13 -2
  33. package/src/tools/file/grep.ts +11 -2
  34. package/src/tools/file/read.ts +30 -6
  35. package/src/tools/file/write.ts +22 -2
  36. package/src/tools/system/tool-search.ts +2 -1
  37. package/src/ui/agent-footer.tsx +16 -3
  38. package/src/ui/app.tsx +67 -15
  39. package/src/ui/chat.tsx +73 -11
  40. package/src/ui/commands.ts +35 -11
  41. package/src/ui/copy-picker.tsx +73 -0
  42. package/src/ui/input.tsx +137 -21
  43. package/src/workflow/primitives/agent.ts +24 -3
@@ -173,7 +173,8 @@
173
173
  "copy": {
174
174
  "confirmed": "✓ 已复制 {count} 条助手回复到剪贴板。",
175
175
  "no_responses": "没有可复制的助手回复。",
176
- "usage": "用法: /copy [N]\nN = 要复制的最近助手回复数量(默认: 1)"
176
+ "usage": "用法: /copy [N]\nN = 要复制的最近助手回复数量(默认: 1)",
177
+ "pick_prompt": "选择要复制的回复:"
177
178
  },
178
179
  "recap": {
179
180
  "title": "── 会话回顾 ──",
@@ -772,6 +773,7 @@
772
773
  "focus_hint": "聚焦",
773
774
  "hidden": "已折叠",
774
775
  "toggle_focus_hint": "/focus 切换",
776
+ "try_focus_tip": "这一轮较长?Ctrl+F(或 /focus)只显示最近一次往来 —— 再按一次即可切回。",
775
777
  "expand_hint": "Ctrl+O 展开",
776
778
  "showing_all": "显示全部 {count} 条消息",
777
779
  "tool_outputs_folded": "已折叠 {hidden} 个工具输出(共 {toolCount} 个工具调用)"
@@ -858,6 +860,13 @@
858
860
  "unknown": "未知渲染错误",
859
861
  "recovery": "终端界面遇到渲染问题,5 秒后自动恢复... 按 Enter 尝试立即恢复。",
860
862
  "preserved": "你的会话数据和对话历史已保留。"
863
+ },
864
+ "tool": {
865
+ "not_run": "未运行"
866
+ },
867
+ "copy_picker": {
868
+ "title": "/copy",
869
+ "nav_help": "(↑↓ 移动,回车复制,Esc 取消)"
861
870
  }
862
871
  },
863
872
  "tools": {
@@ -929,8 +938,8 @@
929
938
  "errors": {
930
939
  "tool_denied_deny_rule": "工具 \"{name}\" 被拒绝规则(\"{pattern}\")阻止。拒绝规则优先于权限模式 — 请改用其他方式,或移除该规则:/permissions remove \"{pattern}\"",
931
940
  "tool_denied_ask_rule": "工具 \"{name}\" 需要批准(ask 规则:\"{pattern}\")。请在提示时批准,或不再询问:/permissions allow \"{pattern}\"",
932
- "tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可) 请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
933
- "tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则。注意:`/permissions allow \"{name}\"` 会让此后对该工具的**每一次**调用都跳过分类器,而不只是这一次,故优先把这次调用改成可接受的,而不是放行整个工具。请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
941
+ "tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可)。",
942
+ "tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则。注意:`/permissions allow \"{name}\"` 会让此后对该工具的**每一次**调用都跳过分类器,而不只是这一次,故优先把这次调用改成可接受的,而不是放行整个工具。",
934
943
  "tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
935
944
  "tool_denied_world_writable_chmod": "工具 \"{name}\" 被拒绝:这是一条递归 chmod,它把「其他用户可写」授予了一个命令并未界定边界的目标(\"{target}\")。一棵世界可写的树,加上一个要到运行时才产生的目标,正是权限被放宽到远超所求的由来;而任何放行规则与权限模式都无法界定这次授权会伸到哪里。请改为字面写出目录名 —— 用 `chmod -R 777 ./dist` 而不是 `chmod -R 777 $DIR` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_CHMOD_PROMPT=1",
936
945
  "tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
@@ -953,6 +962,7 @@
953
962
  "oauth_no_code": "未收到授权码",
954
963
  "oauth_timeout": "OAuth 流程超时(5 分钟)",
955
964
  "mcp_register_collision": "[mcp] 工具冲突:\"{name}\"(来自服务器 \"{server}\")与已有工具冲突,跳过。",
965
+ "mcp_protocol_version_mismatch": "[mcp] 服务器协商出的协议版本为 \"{version}\",本客户端未实现该版本(支持:{supported})。将继续连接,但 MCP 消息可能不按预期工作。",
956
966
  "mcp_register_failed": "[mcp] 注册工具 \"{tool}\"(来自服务器 \"{server}\")失败:{error}",
957
967
  "max_tool_turns": "超出最大工具调用轮次({max})。部分工具调用未执行。",
958
968
  "max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
package/src/index.tsx CHANGED
@@ -294,6 +294,10 @@ async function connectMcpServers(
294
294
  ): Promise<McpConnectFailure[]> {
295
295
  if (mcpServers.length === 0) return []
296
296
  const mcp = McpClient.getInstance()
297
+ // A server that dies mid-session should come back on its own; the retry is
298
+ // bounded and stops early on a definitive refusal. `MIPHAM_MCP_AUTO_RECONNECT=0`
299
+ // turns it off (e.g. for a scripted session that must not spawn processes).
300
+ mcp.setAutoReconnect(process.env.MIPHAM_MCP_AUTO_RECONNECT !== '0')
297
301
  // Wire runtime tool-list changes before connect so mid-connect updates land.
298
302
  syncMcpToolsOnChange(mcp, tools)
299
303
  const results = await Promise.allSettled(
@@ -519,6 +523,10 @@ export async function runApp(options: RunOptions): Promise<void> {
519
523
 
520
524
  // Initialize plugin manager
521
525
  const pluginManager = new PluginManager()
526
+ // A corrupt state file is loaded as an empty list so the CLI still starts — but
527
+ // the next save would persist that emptiness over the real records. Say so.
528
+ const pluginStateWarning = pluginManager.getLoadWarning()
529
+ if (pluginStateWarning) console.error(`⚠ ${pluginStateWarning}`)
522
530
 
523
531
  // Generate session name for tracking (used by /cd to persist cwd)
524
532
  const sessionName = generateSessionName(options.resume)
package/src/mcp/client.ts CHANGED
@@ -126,6 +126,19 @@ export class McpClient {
126
126
  private _tokenStore: TokenStore | null = null
127
127
  private _oauthClient: OAuthClient | null = null
128
128
  private eventHandlers = new Map<string, Array<(...args: any[]) => void>>()
129
+ /**
130
+ * Reconnect a server on its own after an *unexpected* transport loss.
131
+ *
132
+ * Off by default so a unit test that fakes a dead transport does not also
133
+ * start a real reconnect loop; the CLI entry point turns it on. `reconnect()`
134
+ * already bounds the attempts and stops early on a definitive refusal, so this
135
+ * is only about *when* it is called — not how it behaves.
136
+ */
137
+ private autoReconnect = false
138
+ /** Servers with an auto-reconnect in flight — one at a time per name. */
139
+ private reconnecting = new Set<string>()
140
+ /** Set by `closeAll` so a teardown is never undone by an in-flight reconnect. */
141
+ private closing = false
129
142
 
130
143
  private get tokenStore(): TokenStore {
131
144
  if (!this._tokenStore) this._tokenStore = new TokenStore()
@@ -156,6 +169,11 @@ export class McpClient {
156
169
  for (const h of list) h(...args)
157
170
  }
158
171
 
172
+ /** Turn automatic reconnect-after-loss on or off (see `autoReconnect`). */
173
+ setAutoReconnect(enabled: boolean): void {
174
+ this.autoReconnect = enabled
175
+ }
176
+
159
177
  /**
160
178
  * Obtain the credentials a server's config calls for, as transport env.
161
179
  *
@@ -282,6 +300,7 @@ export class McpClient {
282
300
  const maxAttempts = 10
283
301
 
284
302
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
303
+ if (this.closing) return
285
304
  try {
286
305
  try {
287
306
  await connection.transport.close()
@@ -310,6 +329,27 @@ export class McpClient {
310
329
  }
311
330
  }
312
331
 
332
+ /**
333
+ * Fire-and-forget auto-reconnect after an unexpected loss.
334
+ *
335
+ * The loss itself is detected synchronously inside a tool call, so the retry
336
+ * must not be awaited there — the caller wants its error back now, and a
337
+ * reconnect can take up to the full backoff. One attempt per server at a time;
338
+ * a rejection is already recorded on the connection and re-emitted as
339
+ * `disconnected`, so it is swallowed here rather than surfacing as an
340
+ * unhandled rejection.
341
+ */
342
+ private scheduleAutoReconnect(name: string): void {
343
+ if (!this.autoReconnect || this.closing) return
344
+ if (this.reconnecting.has(name)) return
345
+ this.reconnecting.add(name)
346
+ void this.reconnect(name)
347
+ .catch(() => {
348
+ /* reconnect() records the error and emits 'disconnected' */
349
+ })
350
+ .finally(() => this.reconnecting.delete(name))
351
+ }
352
+
313
353
  /** Reset the singleton (useful for testing). */
314
354
  static resetInstance(): void {
315
355
  McpClient.instance = null
@@ -484,6 +524,10 @@ export class McpClient {
484
524
  }
485
525
 
486
526
  async closeAll(): Promise<void> {
527
+ // Nothing we tear down here should be resurrected by an auto-reconnect that
528
+ // is mid-backoff — that reconnect holds the old config and would spawn a
529
+ // fresh subprocess after the client is gone.
530
+ this.closing = true
487
531
  const names = Array.from(this.connections.keys())
488
532
  for (const name of names) {
489
533
  const conn = this.connections.get(name)
@@ -593,5 +637,7 @@ export class McpClient {
593
637
  connection.status = 'error'
594
638
  connection.error = 'Connection lost — the transport is no longer connected'
595
639
  this.emit('disconnected', name, connection.error)
640
+ // The server is gone through no intent of ours — bring it back unaided.
641
+ this.scheduleAutoReconnect(name)
596
642
  }
597
643
  }
@@ -1,16 +1,57 @@
1
1
  import type { ConnectionInfo } from './types'
2
2
 
3
3
  /**
4
- * 单个 server 的 instructions 上限。
4
+ * 一段「给模型看的 MCP 文本」的统一上限 —— 单 server 的 instructions、
5
+ * 单个工具的描述,都用它。
5
6
  *
6
- * 这是**不受我们控制**的第三方文本,且**每次请求都要重新付一遍前缀** ——
7
- * 一个啰嗦的 server 能靠一段自带说明把别人的预算吃光。截断而非拒绝:
8
- * 前半段通常正是「这个 server 该怎么用」那部分。
7
+ * 这是**不受我们控制**的第三方文本,且**每次请求都要重新付一遍前缀**:一个啰嗦的 server
8
+ * 能靠一段自带说明把别人的预算吃光。三个面此前各是各的数字(server instructions 2000 /
9
+ * up-front 工具定义**无上限** / tool-search 命中列表 120)—— 无上限那面最危险,120 那面则把
10
+ * 「该不该用这个工具」的依据砍到看不见。统一到一个数,让「一屏 MCP 文本有多长」只有一个答案。
9
11
  */
10
- export const MCP_INSTRUCTIONS_PER_SERVER_CAP = 2000
12
+ export const MCP_TEXT_CAP = 4096
13
+
14
+ /** 单个 server 的 instructions 上限(与 {@link MCP_TEXT_CAP} 同一个数)。 */
15
+ export const MCP_INSTRUCTIONS_PER_SERVER_CAP = MCP_TEXT_CAP
11
16
 
12
17
  const TRUNCATION_MARKER = '… [truncated]'
13
18
 
19
+ /**
20
+ * 截到 `cap` 个字符;被截时补一个可见标记。
21
+ *
22
+ * 截断而非拒绝(前半段通常正是「怎么用」那部分),但**必须让模型看见被截了** ——
23
+ * 一个悄悄变短的定义,模型会当成完整定义来信任。三处调用共用这一个口,免得各自的
24
+ * 截法(补不补标记、按不按字符)又漂开。
25
+ */
26
+ export function capMcpText(text: string, cap: number = MCP_TEXT_CAP): string {
27
+ if (text.length <= cap) return text
28
+ return `${text.slice(0, cap)}\n${TRUNCATION_MARKER}`
29
+ }
30
+
31
+ /** True when every character is a plain ASCII code point (0x00–0x7F). */
32
+ function isAsciiName(s: string): boolean {
33
+ for (let i = 0; i < s.length; i++) {
34
+ if (s.charCodeAt(i) > 0x7f) return false
35
+ }
36
+ return true
37
+ }
38
+
39
+ /**
40
+ * Order two names for the model-facing block: ASCII names first, then the rest.
41
+ *
42
+ * `localeCompare` is locale-*aware*, which is exactly wrong here: it threads an
43
+ * accented name (`Émile`) in among the ASCII ones and only relegates pure CJK to
44
+ * the end, so the same set of servers can order differently across machines. The
45
+ * reader is a model, not a human locale — the list wants a fixed shape. Within
46
+ * each group, compare by code unit, which is deterministic everywhere.
47
+ */
48
+ export function compareNames(a: string, b: string): number {
49
+ const aAscii = isAsciiName(a)
50
+ const bAscii = isAsciiName(b)
51
+ if (aAscii !== bAscii) return aAscii ? -1 : 1
52
+ return a < b ? -1 : a > b ? 1 : 0
53
+ }
54
+
14
55
  /**
15
56
  * 把已连接 MCP server 自带的 `instructions` 拼成一段**系统提示用**的文本。
16
57
  *
@@ -33,13 +74,10 @@ export function buildMcpInstructionsBlock(connections: ConnectionInfo[]): string
33
74
  const sections = connections
34
75
  .filter((c) => typeof c.instructions === 'string' && c.instructions.trim() !== '')
35
76
  .slice()
36
- .sort((a, b) => a.config.name.localeCompare(b.config.name))
77
+ .sort((a, b) => compareNames(a.config.name, b.config.name))
37
78
  .map((c) => {
38
79
  const raw = c.instructions!.trim()
39
- const body =
40
- raw.length > MCP_INSTRUCTIONS_PER_SERVER_CAP
41
- ? `${raw.slice(0, MCP_INSTRUCTIONS_PER_SERVER_CAP)}\n${TRUNCATION_MARKER}`
42
- : raw
80
+ const body = capMcpText(raw, MCP_INSTRUCTIONS_PER_SERVER_CAP)
43
81
  return `### ${c.config.name}\n${body}`
44
82
  })
45
83
 
@@ -6,8 +6,46 @@ import type {
6
6
  ResourceReadResult,
7
7
  } from './types'
8
8
  import type { Transport } from './transport'
9
+ import { createT } from '../i18n-core/t'
10
+ import enUS from '../i18n-core/locales/en-US.json'
11
+ import zhCN from '../i18n-core/locales/zh-CN.json'
12
+ import type { TranslationMap } from '../i18n-core/types'
13
+
14
+ const bundles: Record<string, TranslationMap> = {
15
+ 'en-US': enUS as TranslationMap,
16
+ 'zh-CN': zhCN as TranslationMap,
17
+ }
18
+ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as TranslationMap)
19
+
20
+ /**
21
+ * Protocol revisions this client is prepared to speak, newest first.
22
+ *
23
+ * Only revisions whose wire behaviour the code below actually implements belong
24
+ * here — offering a revision is a claim that its messages will be understood,
25
+ * and a server that takes us at our word would then send shapes we cannot parse.
26
+ * The list exists so that adopting a revision is an edit to a value rather than
27
+ * a change to the handshake, and so the server's answer has something to be
28
+ * checked against.
29
+ */
30
+ export const MCP_SUPPORTED_VERSIONS: readonly string[] = ['2024-11-05']
9
31
 
10
- const MCP_VERSION = '2024-11-05'
32
+ /**
33
+ * The revision to offer in `initialize`.
34
+ *
35
+ * `MCP_PROTOCOL_NEGOTIATION=legacy` pins the oldest supported revision. The
36
+ * handshake used to send one hardcoded literal with no way to ask for anything
37
+ * else, so a server that answers an unrecognized revision by failing the
38
+ * connection — rather than by replying with the one it speaks — was simply
39
+ * unreachable.
40
+ *
41
+ * An unset or unrecognized value offers the newest.
42
+ */
43
+ export function offerVersion(env: NodeJS.ProcessEnv = process.env): string {
44
+ if (env.MCP_PROTOCOL_NEGOTIATION === 'legacy') {
45
+ return MCP_SUPPORTED_VERSIONS[MCP_SUPPORTED_VERSIONS.length - 1]!
46
+ }
47
+ return MCP_SUPPORTED_VERSIONS[0]!
48
+ }
11
49
 
12
50
  /**
13
51
  * MCP protocol layer — implements the initialize/tools/resources
@@ -19,9 +57,24 @@ export class McpProtocol {
19
57
  resources?: { subscribe?: boolean; listChanged?: boolean }
20
58
  } = {}
21
59
  private handlers = new Map<string, Array<(...args: any[]) => void>>()
60
+ /** The revision the last `initialize` agreed on, or null before one ran. */
61
+ private agreedVersion: string | null = null
22
62
 
23
63
  constructor(private transport: Transport) {}
24
64
 
65
+ /**
66
+ * The protocol revision this connection settled on.
67
+ *
68
+ * The server's answer, not the one we offered: `initialize` replies with the
69
+ * revision it will actually speak, which may be older than the offer. Recorded
70
+ * because the field used to be received and dropped — a server that answered
71
+ * with a revision this client never implemented looked exactly like one that
72
+ * agreed.
73
+ */
74
+ get protocolVersion(): string | null {
75
+ return this.agreedVersion
76
+ }
77
+
25
78
  on(event: string, handler: (...args: any[]) => void): void {
26
79
  const list = this.handlers.get(event) || []
27
80
  list.push(handler)
@@ -37,7 +90,7 @@ export class McpProtocol {
37
90
  // Transport must already be started by the caller (McpClient.connect).
38
91
  // Send initialize request
39
92
  const result = (await this.transport.sendRequest('initialize', {
40
- protocolVersion: MCP_VERSION,
93
+ protocolVersion: offerVersion(),
41
94
  capabilities: {
42
95
  tools: {},
43
96
  resources: {},
@@ -48,6 +101,20 @@ export class McpProtocol {
48
101
  },
49
102
  })) as InitializeResult
50
103
 
104
+ this.agreedVersion = result.protocolVersion ?? null
105
+ if (this.agreedVersion && !MCP_SUPPORTED_VERSIONS.includes(this.agreedVersion)) {
106
+ // Not a fatal error: the base lifecycle is stable across revisions, so the
107
+ // connection usually still works. Say so rather than let an unexpected
108
+ // revision look like an agreement — if messages then misbehave, this line
109
+ // is the first thing that explains why.
110
+ console.error(
111
+ t('errors.mcp_protocol_version_mismatch', {
112
+ version: this.agreedVersion,
113
+ supported: MCP_SUPPORTED_VERSIONS.join(', '),
114
+ }),
115
+ )
116
+ }
117
+
51
118
  // Send initialized notification
52
119
  this.transport.sendNotification('notifications/initialized')
53
120
 
@@ -9,6 +9,7 @@
9
9
  import type { ToolDefinition as McpToolDefinition, ToolCallResult } from './types'
10
10
  import type { ToolDefinition, ToolResult, ToolContext } from '../shared/types'
11
11
  import { McpClient } from './client'
12
+ import { capMcpText } from './instructions'
12
13
  import { createT } from '../i18n-core/t'
13
14
  import enUS from '../i18n-core/locales/en-US.json'
14
15
  import zhCN from '../i18n-core/locales/zh-CN.json'
@@ -65,7 +66,7 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
65
66
 
66
67
  return {
67
68
  name: toolName,
68
- description: `[MCP:${serverName}] ${mcpTool.description || mcpTool.name}`,
69
+ description: `[MCP:${serverName}] ${capMcpText(mcpTool.description || mcpTool.name)}`,
69
70
  category: 'system',
70
71
  permission: 'ask',
71
72
  parameters,
@@ -21,6 +21,57 @@ export interface Transport {
21
21
 
22
22
  export const DEFAULT_REQUEST_TIMEOUT_MS = 60_000
23
23
 
24
+ /**
25
+ * How long a stdio MCP server gets to exit on its own after its stdin is closed,
26
+ * before we kill it (296-048).
27
+ *
28
+ * Closing stdin **is** the protocol's shutdown signal — a well-behaved server
29
+ * sees EOF, flushes, and exits. Killing it in the same tick gives it no chance
30
+ * to do that; on Windows the kill also left the server's own children running.
31
+ */
32
+ export const MCP_SHUTDOWN_GRACE_MS = 300
33
+
34
+ /** Resolve when `proc` exits, or after `ms` — whichever comes first. */
35
+ function waitForExit(proc: ChildProcess, ms: number): Promise<void> {
36
+ if (proc.exitCode !== null || proc.signalCode !== null) return Promise.resolve()
37
+ return new Promise((resolve) => {
38
+ const onExit = (): void => {
39
+ clearTimeout(timer)
40
+ resolve()
41
+ }
42
+ const timer = setTimeout(onExit, ms)
43
+ proc.once('exit', onExit)
44
+ })
45
+ }
46
+
47
+ /**
48
+ * Terminate the server **and its descendants** once the grace period expired.
49
+ *
50
+ * The tree half is Windows-only, and deliberately so: Windows gives us no
51
+ * process group to signal, so `taskkill /T` is the only way to reach the
52
+ * server's own children. On POSIX we do **not** spawn MCP servers detached, so
53
+ * the child shares our process group and has no group of its own —
54
+ * `process.kill(-pid)` would be ESRCH, and making it a group leader would let
55
+ * servers outlive the CLI, a worse bug than the one being fixed. There, the
56
+ * grace period above *is* the fix; killing the direct child is what we always did.
57
+ */
58
+ function killProcessTree(proc: ChildProcess): void {
59
+ const pid = proc.pid
60
+ if (pid === undefined) return
61
+ if (process.platform === 'win32') {
62
+ try {
63
+ spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
64
+ } catch {
65
+ /* fall through to the direct kill */
66
+ }
67
+ }
68
+ try {
69
+ proc.kill()
70
+ } catch {
71
+ /* already gone */
72
+ }
73
+ }
74
+
24
75
  /** Shared timeout error for both stdio and HTTP transports. */
25
76
  export function requestTimeoutError(method: string, ms: number): Error {
26
77
  return new Error(`MCP request timeout: ${method} (${ms}ms)`)
@@ -74,7 +125,11 @@ function buildProcEnv(extra?: Record<string, string>): Record<string, string> {
74
125
  * Uses Node.js child_process for portability across Bun and Node runtimes.
75
126
  */
76
127
  export class StdioTransport implements Transport {
77
- constructor(private requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {}
128
+ constructor(
129
+ private requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
130
+ /** Seam for tests: how long `close()` waits for a self-exit before killing. */
131
+ private shutdownGraceMs = MCP_SHUTDOWN_GRACE_MS,
132
+ ) {}
78
133
  private proc: ChildProcess | null = null
79
134
  private msgId = 0
80
135
  private pending = new Map<
@@ -211,14 +266,20 @@ export class StdioTransport implements Transport {
211
266
  }
212
267
  this.pending.clear()
213
268
 
214
- if (this.proc) {
215
- try {
216
- this.proc.stdin?.end()
217
- } catch {
218
- /* ignore */
219
- }
220
- this.proc.kill()
221
- this.proc = null
269
+ const proc = this.proc
270
+ this.proc = null
271
+ if (!proc) return
272
+
273
+ // stdin EOF is the shutdown signal. Wait for the server to take it; only a
274
+ // server still running after the grace period gets killed (296-048).
275
+ try {
276
+ proc.stdin?.end()
277
+ } catch {
278
+ /* ignore */
279
+ }
280
+ await waitForExit(proc, this.shutdownGraceMs)
281
+ if (proc.exitCode === null && proc.signalCode === null) {
282
+ killProcessTree(proc)
222
283
  }
223
284
  }
224
285
 
@@ -40,6 +40,7 @@ export class PluginManager {
40
40
  private pluginDir: string
41
41
  private statePath: string
42
42
  private cleanupCallbacks = new Map<string, () => void>()
43
+ private loadWarning: string | null = null
43
44
 
44
45
  constructor(pluginDir?: string) {
45
46
  this.pluginDir = pluginDir ?? PLUGIN_DIR
@@ -48,6 +49,20 @@ export class PluginManager {
48
49
  this.loadState()
49
50
  }
50
51
 
52
+ /**
53
+ * Set when `state.json` was **present but unusable** (unreadable, or valid
54
+ * JSON of the wrong shape). Null when the file was simply absent — that is the
55
+ * ordinary first run, not something to warn about.
56
+ *
57
+ * The distinction is the whole point: `loadState` starts empty either way, and
58
+ * the *next* `saveState` persists that empty list — so a corrupt file used to
59
+ * become a silently wiped one. The caller (the CLI entry point) surfaces this
60
+ * so the operator learns before the records are gone for good.
61
+ */
62
+ getLoadWarning(): string | null {
63
+ return this.loadWarning
64
+ }
65
+
51
66
  install(sourcePath: string): { success: boolean; message: string } {
52
67
  const validation = validatePlugin(sourcePath)
53
68
  if (!validation.valid || !validation.manifest) {
@@ -318,17 +333,23 @@ export class PluginManager {
318
333
  }
319
334
 
320
335
  private loadState(): void {
336
+ if (!existsSync(this.statePath)) {
337
+ this.plugins = []
338
+ return
339
+ }
321
340
  try {
322
- if (existsSync(this.statePath)) {
323
- const parsed: unknown = JSON.parse(readFileSync(this.statePath, 'utf-8'))
324
- // Parsing is not validating: `{}` / `null` / `"x"` are all valid JSON and
325
- // all make the readers below throw (`.find`/`.filter`/`.map` on a
326
- // non-array), so a file that is merely *shaped* wrong took down every
327
- // plugin command instead of starting empty.
328
- this.plugins = Array.isArray(parsed) ? (parsed as InstalledPlugin[]) : []
341
+ const parsed: unknown = JSON.parse(readFileSync(this.statePath, 'utf-8'))
342
+ // Parsing is not validating: `{}` / `null` / `"x"` are all valid JSON and
343
+ // all make the readers below throw (`.find`/`.filter`/`.map` on a
344
+ // non-array), so a file that is merely *shaped* wrong took down every
345
+ // plugin command instead of starting empty.
346
+ this.plugins = Array.isArray(parsed) ? (parsed as InstalledPlugin[]) : []
347
+ if (!Array.isArray(parsed)) {
348
+ this.loadWarning = `Plugin state file is not a list; starting empty (${this.statePath})`
329
349
  }
330
- } catch {
350
+ } catch (err) {
331
351
  this.plugins = []
352
+ this.loadWarning = `Could not read plugin state (${this.statePath}): ${String(err)}`
332
353
  }
333
354
  }
334
355
 
@@ -54,8 +54,9 @@ export function retryDelayMs(
54
54
  retryAfter: string | null,
55
55
  attempt: number,
56
56
  baseDelay: number,
57
+ maxDelay: number = resolveMaxDelayMs(),
57
58
  ): number {
58
- const backoff = baseDelay * Math.pow(2, attempt)
59
+ const backoff = Math.min(baseDelay * Math.pow(2, attempt), maxDelay)
59
60
  if (retryAfter === null) return backoff
60
61
 
61
62
  const header = retryAfter.trim()
@@ -106,6 +107,50 @@ export function isRetryableFailure(status: number | undefined, errorType?: strin
106
107
  return !NON_RETRYABLE_ERROR_TYPES.has(errorType)
107
108
  }
108
109
 
110
+ /** Base backoff between retry attempts, in ms. */
111
+ export const DEFAULT_RETRY_BASE_DELAY_MS = 1_000
112
+
113
+ /**
114
+ * The default backoff, overridable from the environment.
115
+ *
116
+ * One second suits an interactive turn, but a caller pointed at a known-overloaded
117
+ * endpoint (a self-hosted gateway, a batch run) wants longer gaps between attempts
118
+ * — and cannot pass `baseDelay` through the SDK paths that build their own
119
+ * `fetchWithRetry` call. `MIPHAM_OVERLOADED_RETRY_BASE_DELAY_MS` is that knob.
120
+ *
121
+ * A malformed value (non-numeric, negative) is a typo, not an instruction: fall
122
+ * back to the built-in rather than let `sleep(NaN)` become a zero-delay retry
123
+ * loop. Read per call so a test can set it without re-importing the module.
124
+ */
125
+ function resolveBaseDelayMs(): number {
126
+ const raw = process.env.MIPHAM_OVERLOADED_RETRY_BASE_DELAY_MS
127
+ if (raw === undefined || raw.trim() === '') return DEFAULT_RETRY_BASE_DELAY_MS
128
+ const ms = Number(raw)
129
+ if (!Number.isFinite(ms) || ms < 0) return DEFAULT_RETRY_BASE_DELAY_MS
130
+ return ms
131
+ }
132
+
133
+ /** Default ceiling on the exponential backoff, in ms. */
134
+ export const DEFAULT_RETRY_MAX_DELAY_MS = 60_000
135
+
136
+ /**
137
+ * Upper bound on the exponential backoff, overridable from the environment.
138
+ *
139
+ * `baseDelay * 2^attempt` has no natural ceiling: a caller that raises
140
+ * `maxRetries` (or pairs a large `baseDelay` with several attempts) can park a
141
+ * turn for minutes with nothing on screen. `MIPHAM_OVERLOADED_RETRY_MAX_DELAY_MS`
142
+ * sets the cap; a malformed value (non-numeric, negative) is a typo, not an
143
+ * instruction, so it falls back to the built-in rather than let the cap become
144
+ * `sleep(NaN)`. Read per call so a test can set it without re-importing.
145
+ */
146
+ function resolveMaxDelayMs(): number {
147
+ const raw = process.env.MIPHAM_OVERLOADED_RETRY_MAX_DELAY_MS
148
+ if (raw === undefined || raw.trim() === '') return DEFAULT_RETRY_MAX_DELAY_MS
149
+ const ms = Number(raw)
150
+ if (!Number.isFinite(ms) || ms < 0) return DEFAULT_RETRY_MAX_DELAY_MS
151
+ return ms
152
+ }
153
+
109
154
  /**
110
155
  * Fetch with optional timeout and retry with exponential backoff.
111
156
  *
@@ -118,7 +163,7 @@ export async function fetchWithRetry(
118
163
  init: RequestInit,
119
164
  options: FetchWithRetryOptions = {},
120
165
  ): Promise<Response> {
121
- const { timeout = 60_000, maxRetries = 2, baseDelay = 1000 } = options
166
+ const { timeout = 60_000, maxRetries = 2, baseDelay = resolveBaseDelayMs() } = options
122
167
 
123
168
  let lastErr: unknown
124
169
 
@@ -29,6 +29,24 @@ export function isSymlinkLoop(err: unknown): boolean {
29
29
  return (err as NodeJS.ErrnoException)?.code === 'ELOOP'
30
30
  }
31
31
 
32
+ /**
33
+ * True iff `buf` is well-formed UTF-8.
34
+ *
35
+ * Read-modify-write tools (Edit, Write) decode with 'utf-8' and re-encode the
36
+ * result. For a *valid* UTF-8 file that round-trips byte-for-byte, but a
37
+ * Windows-1252 / Shift-JIS / GBK / Latin-1 file decodes every invalid byte to
38
+ * U+FFFD and writing it back destroys the original bytes — with no error. This
39
+ * gate lets the caller refuse instead of corrupting silently.
40
+ */
41
+ export function isValidUtf8(buf: Buffer): boolean {
42
+ try {
43
+ new TextDecoder('utf-8', { fatal: true }).decode(buf)
44
+ return true
45
+ } catch {
46
+ return false
47
+ }
48
+ }
49
+
32
50
  /**
33
51
  * Open a file O_WRONLY|O_NOFOLLOW, write `content`, and close. Used by Write
34
52
  * and Edit so a symlink swapped in after `resolveSafe` is rejected rather than
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.18' as const
12
+ export const PACKAGE_VERSION = '0.85.20' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 4076 as const
93
+ export const TEST_COUNT = 4228 as const
@@ -239,11 +239,15 @@ export function decodeDisplayEntities(input: string): string {
239
239
  *
240
240
  * Newlines are stripped as well, unlike `stripControlCharsForCheck` (which keeps
241
241
  * `\n` for multi-line shell commands): these values sit on one output line, so an
242
- * embedded newline forges an extra row in the listing.
242
+ * embedded newline forges an extra row in the listing. C1 (U+0080–U+009F) goes with
243
+ * them — its 8-bit CSI is the same introducer as ESC's, in a different encoding (see
244
+ * `stripControlCharsForDisplay`, which drops the same family); leaving it out here
245
+ * would mean the one-line port and the multi-line one disagree about it, and a
246
+ * one-line field is exactly where a `\u009b…` payload is cheapest to hide.
243
247
  */
244
248
  export function sanitizeInlineField(input: string): string {
245
249
  if (!input) return input
246
- return stripDangerousUnicode(input).replace(/[\x00-\x1f\x7f]/g, '')
250
+ return stripDangerousUnicode(input).replace(/[\x00-\x1f\x7f\x80-\x9f]/g, '')
247
251
  }
248
252
 
249
253
  /**