@miphamai/cli 0.85.19 → 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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/agent/agent-registry.ts +2 -0
- package/src/agent/auto-compact.ts +72 -0
- package/src/agent/sub-agent.ts +22 -1
- package/src/agent/types.ts +10 -0
- package/src/core/context.ts +15 -3
- package/src/core/engine.ts +7 -0
- package/src/i18n-core/locales/en-US.json +9 -1
- package/src/i18n-core/locales/zh-CN.json +9 -1
- package/src/index.tsx +8 -0
- package/src/mcp/client.ts +46 -0
- package/src/mcp/instructions.ts +23 -9
- package/src/mcp/registry.ts +2 -1
- package/src/mcp/transport.ts +70 -9
- package/src/plugin/plugin-manager.ts +29 -8
- package/src/providers/fetch-utils.ts +23 -1
- package/src/security/fd.ts +18 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +6 -2
- package/src/shared/types.ts +16 -0
- package/src/skills/marketplace.ts +15 -5
- package/src/skills/registry.ts +4 -1
- package/src/tools/file/edit.ts +13 -2
- package/src/tools/file/read.ts +30 -6
- package/src/tools/file/write.ts +22 -2
- package/src/tools/system/tool-search.ts +2 -1
- package/src/ui/agent-footer.tsx +16 -3
- package/src/ui/app.tsx +66 -14
- package/src/ui/chat.tsx +58 -10
- package/src/ui/commands.ts +35 -11
- package/src/ui/copy-picker.tsx +73 -0
- package/src/ui/input.tsx +112 -20
- package/src/workflow/primitives/agent.ts +23 -3
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.20
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 137 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -79,6 +79,8 @@ export class AgentRegistry {
|
|
|
79
79
|
: undefined,
|
|
80
80
|
background: typeof data.background === 'boolean' ? data.background : undefined,
|
|
81
81
|
memory: data.memory as 'user' | 'project' | 'local' | undefined,
|
|
82
|
+
autoCompactWindow:
|
|
83
|
+
typeof data.autoCompactWindow === 'number' ? data.autoCompactWindow : undefined,
|
|
82
84
|
source,
|
|
83
85
|
filePath: fullPath,
|
|
84
86
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Message } from '../shared/index.ts'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Ratio of the declared window at which a sub-agent shrinks its context.
|
|
5
|
+
* Kept in step with `ContextManager`'s default `compactionThreshold` so an agent
|
|
6
|
+
* that opted into `autoCompactWindow` compacts at the same fill the main session
|
|
7
|
+
* would.
|
|
8
|
+
*/
|
|
9
|
+
const SHRINK_THRESHOLD = 0.85
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Tail sizes tried, largest first. Mirrors `COMPACTION_PASSES`' shrink-to-fit:
|
|
13
|
+
* keep as much recent context as fits, and only take a shorter tail if the first
|
|
14
|
+
* candidate is still over budget. Bounded so a shrink always terminates.
|
|
15
|
+
*/
|
|
16
|
+
const KEEP_CANDIDATES = [10, 4] as const
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* True iff `msg` is a `user` turn carrying one or more `tool_result` blocks.
|
|
20
|
+
*
|
|
21
|
+
* Such a turn is meaningless without the `tool_use` it answers, and providers
|
|
22
|
+
* reject an orphaned `tool_result` — so truncation must never leave one at the
|
|
23
|
+
* head of what it keeps.
|
|
24
|
+
*/
|
|
25
|
+
export function isToolResultMessage(msg: Message): boolean {
|
|
26
|
+
return (
|
|
27
|
+
msg.role === 'user' &&
|
|
28
|
+
Array.isArray(msg.content) &&
|
|
29
|
+
msg.content.some((b) => b.type === 'tool_result')
|
|
30
|
+
)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Shrink a sub-agent's message list, preserving its task.
|
|
35
|
+
*
|
|
36
|
+
* Unlike `ContextManager.compact` (keep the last N; let a summarizer condense the
|
|
37
|
+
* front), a sub-agent has **no summarizer** and **no persistent goal-bearing
|
|
38
|
+
* system prompt** — `messages[0]` *is* the task. Keeping only a tail would strand
|
|
39
|
+
* the agent with nothing to do, so the opening message is pinned and the middle is
|
|
40
|
+
* dropped instead.
|
|
41
|
+
*
|
|
42
|
+
* Opt-in: the loop only calls this when the agent declared `autoCompactWindow`;
|
|
43
|
+
* without the field the run is byte-identical to before. No-op until the estimate
|
|
44
|
+
* exceeds `window * SHRINK_THRESHOLD`.
|
|
45
|
+
*
|
|
46
|
+
* `estimate` is threaded in rather than reimplemented, so the caller gates on the
|
|
47
|
+
* very number `ContextManager` would report — never a second, divergent estimate.
|
|
48
|
+
* Returns the input array unchanged when no shrink is needed.
|
|
49
|
+
*/
|
|
50
|
+
export function shrinkAgentMessages(
|
|
51
|
+
messages: Message[],
|
|
52
|
+
window: number,
|
|
53
|
+
estimate: (m: Message[]) => number,
|
|
54
|
+
): Message[] {
|
|
55
|
+
if (messages.length < 3) return messages
|
|
56
|
+
if (estimate(messages) <= window * SHRINK_THRESHOLD) return messages
|
|
57
|
+
|
|
58
|
+
const task = messages[0]!
|
|
59
|
+
const rest = messages.slice(1)
|
|
60
|
+
|
|
61
|
+
for (let i = 0; i < KEEP_CANDIDATES.length; i++) {
|
|
62
|
+
let tail = rest.slice(-KEEP_CANDIDATES[i]!)
|
|
63
|
+
// Drop orphaned tool_results at the head (their tool_use was cut away).
|
|
64
|
+
while (tail.length > 0 && isToolResultMessage(tail[0]!)) tail = tail.slice(1)
|
|
65
|
+
const candidate = [task, ...tail]
|
|
66
|
+
if (estimate(candidate) <= window * SHRINK_THRESHOLD || i === KEEP_CANDIDATES.length - 1) {
|
|
67
|
+
return candidate
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return messages
|
|
72
|
+
}
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { Llm } from '../providers/llm'
|
|
|
3
3
|
import type { Message, ToolDefinition, ToolContext } from '../shared/index.ts'
|
|
4
4
|
import type { SubAgentType, SubAgentOptions, AgentDefinition } from './types'
|
|
5
5
|
import { createAgentContext } from './agent-context'
|
|
6
|
+
import { shrinkAgentMessages } from './auto-compact'
|
|
6
7
|
import { getBackgroundAgentRegistry } from './background-registry'
|
|
7
8
|
import { formatInboundMessage, getMessageBus } from './message-bus'
|
|
8
9
|
import type { HookEngine } from '../core/hooks'
|
|
@@ -380,12 +381,20 @@ export class SubAgent {
|
|
|
380
381
|
source: 'builtin',
|
|
381
382
|
}
|
|
382
383
|
const contextWindow = this.registry.findModel(finalModel)?.contextWindow
|
|
384
|
+
// `autoCompactWindow` (frontmatter) lets an agent declare a **tighter** budget
|
|
385
|
+
// than its model's native window so it compacts sooner; it can never widen the
|
|
386
|
+
// real window, so take the min. Absent the field, nothing changes — the
|
|
387
|
+
// sub-agent context is sized exactly as before.
|
|
388
|
+
const declaredWindow = agentDef?.autoCompactWindow
|
|
389
|
+
const compactWindow = declaredWindow
|
|
390
|
+
? Math.min(declaredWindow, contextWindow ?? declaredWindow)
|
|
391
|
+
: undefined
|
|
383
392
|
// 这一份**已含 agent memory**,是发出去的那个提示的唯一来源。
|
|
384
393
|
const {
|
|
385
394
|
context,
|
|
386
395
|
allowedTools,
|
|
387
396
|
systemPrompt: composedSystemPrompt,
|
|
388
|
-
} = createAgentContext(resolvedDef, this.toolRegistry, contextWindow)
|
|
397
|
+
} = createAgentContext(resolvedDef, this.toolRegistry, compactWindow ?? contextWindow)
|
|
389
398
|
|
|
390
399
|
// 别再 `context.setSystemPrompt(systemPrompt)`:`createAgentContext` 已经拿**含记忆**的
|
|
391
400
|
// 那一份设过上下文,这里用裸提示再设一遍只会把记忆从上下文里抹掉,而请求读的又不是
|
|
@@ -507,6 +516,18 @@ export class SubAgent {
|
|
|
507
516
|
throw new DOMException('Aborted', 'AbortError')
|
|
508
517
|
}
|
|
509
518
|
|
|
519
|
+
// Opt-in shrink for agents that declared `autoCompactWindow`. The engine
|
|
520
|
+
// compacts through `ContextManager`, but this loop keeps `currentMessages`
|
|
521
|
+
// locally and never calls it — so without this line the field would be
|
|
522
|
+
// decoration. Task-pinned: `shrinkAgentMessages` never drops `messages[0]`,
|
|
523
|
+
// because here that message *is* the task (no summarizer, no system prompt
|
|
524
|
+
// restating it). Gated on the estimate `context` itself would report.
|
|
525
|
+
if (compactWindow) {
|
|
526
|
+
currentMessages = shrinkAgentMessages(currentMessages, compactWindow, (m) =>
|
|
527
|
+
context.estimateTokensForMessages(m),
|
|
528
|
+
)
|
|
529
|
+
}
|
|
530
|
+
|
|
510
531
|
// Per turn, not once per run: a peer can write while this agent is mid
|
|
511
532
|
// task, and the point of the channel is to steer the work in progress.
|
|
512
533
|
this.drainInboundMessages(agentId, currentMessages)
|
package/src/agent/types.ts
CHANGED
|
@@ -18,6 +18,14 @@ export interface AgentFrontmatter {
|
|
|
18
18
|
skills?: string
|
|
19
19
|
background?: boolean
|
|
20
20
|
memory?: 'user' | 'project' | 'local' // agent memory scope
|
|
21
|
+
/**
|
|
22
|
+
* Opt-in context budget (tokens) for this agent's own conversation. When set,
|
|
23
|
+
* the sub-agent shrinks its context on the first turn it crosses this window
|
|
24
|
+
* (the same 0.85 ratio the main session uses) — so a long-running agent
|
|
25
|
+
* compacts on its own terms instead of growing until `maxTurns`. Never widens
|
|
26
|
+
* the model's real window: the effective value is `min(field, modelWindow)`.
|
|
27
|
+
*/
|
|
28
|
+
autoCompactWindow?: number
|
|
21
29
|
}
|
|
22
30
|
|
|
23
31
|
export interface AgentDefinition {
|
|
@@ -35,6 +43,8 @@ export interface AgentDefinition {
|
|
|
35
43
|
source: 'builtin' | 'project' | 'user'
|
|
36
44
|
filePath?: string
|
|
37
45
|
memory?: 'user' | 'project' | 'local' // agent memory scope
|
|
46
|
+
/** Opt-in per-agent context budget; see `AgentFrontmatter.autoCompactWindow`. */
|
|
47
|
+
autoCompactWindow?: number
|
|
38
48
|
}
|
|
39
49
|
|
|
40
50
|
export interface SubAgentOptions {
|
package/src/core/context.ts
CHANGED
|
@@ -569,12 +569,24 @@ export class ContextManager {
|
|
|
569
569
|
|
|
570
570
|
/** 从当前消息**重算消息那半**的估值(提示那半不在这里 —— 它是读时派生的)。 */
|
|
571
571
|
private recountMessageTokens(): void {
|
|
572
|
-
this.messageTokens =
|
|
573
|
-
|
|
574
|
-
|
|
572
|
+
this.messageTokens = this.estimateTokensForMessages(this.messages)
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* 任意消息列表的 token 估值,用的就是 `recountMessageTokens` 那套逐条估计器 ——
|
|
577
|
+
* 纯函数、不碰实例状态。
|
|
578
|
+
*
|
|
579
|
+
* 存在的理由:`ContextManager` 之外的调用方(子代理循环的 `autoCompactWindow`
|
|
580
|
+
* 收缩)要**按 manager 自己会报的那个数**设闸,而不是另养一份会漂移的估计。
|
|
581
|
+
*/
|
|
582
|
+
estimateTokensForMessages(messages: Message[]): number {
|
|
583
|
+
let total = 0
|
|
584
|
+
for (const msg of messages) {
|
|
585
|
+
total += this.estimateTokens(
|
|
575
586
|
typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
|
|
576
587
|
)
|
|
577
588
|
}
|
|
589
|
+
return total
|
|
578
590
|
}
|
|
579
591
|
|
|
580
592
|
/** 提示那半的估值 —— 每次读数现拼现算,见 `getEstimatedTokens()`。 */
|
package/src/core/engine.ts
CHANGED
|
@@ -841,6 +841,7 @@ export class QueryEngine {
|
|
|
841
841
|
tool_use_id: toolUse.id,
|
|
842
842
|
content: result.success ? result.content : result.error || result.content,
|
|
843
843
|
isError: !result.success,
|
|
844
|
+
notRun: result.notRun === true,
|
|
844
845
|
}
|
|
845
846
|
|
|
846
847
|
// Collect tool call record for CRSI auto-reflection
|
|
@@ -1204,6 +1205,7 @@ export class QueryEngine {
|
|
|
1204
1205
|
// —— 直接发 `content` 会让模型收到一个**空** tool_result,错误文案整个丢失。
|
|
1205
1206
|
content: result.success ? result.content : result.error || result.content,
|
|
1206
1207
|
isError: !result.success,
|
|
1208
|
+
notRun: result.notRun === true,
|
|
1207
1209
|
}
|
|
1208
1210
|
|
|
1209
1211
|
// DeepSeek V4 thinking mode requires reasoning_content on every assistant message
|
|
@@ -1263,6 +1265,10 @@ export class QueryEngine {
|
|
|
1263
1265
|
success: false,
|
|
1264
1266
|
content: '',
|
|
1265
1267
|
error: baseError + moveOnHint,
|
|
1268
|
+
// Held back, not judged: the auto-mode classifier had no usable answer.
|
|
1269
|
+
// The display says "Not run" for these instead of showing a result line
|
|
1270
|
+
// that reads as if the tool had run and returned that text (296-056).
|
|
1271
|
+
notRun: decision.retryable === true,
|
|
1266
1272
|
}
|
|
1267
1273
|
}
|
|
1268
1274
|
// P1-4: Tool allowed — reset block counter
|
|
@@ -1428,6 +1434,7 @@ export class QueryEngine {
|
|
|
1428
1434
|
success: false,
|
|
1429
1435
|
content: '',
|
|
1430
1436
|
error: this.buildDenialError(name, tool, effectiveParams, recheck),
|
|
1437
|
+
notRun: recheck.retryable === true,
|
|
1431
1438
|
}
|
|
1432
1439
|
}
|
|
1433
1440
|
}
|
|
@@ -173,7 +173,8 @@
|
|
|
173
173
|
"copy": {
|
|
174
174
|
"confirmed": "✓ Copied {count} assistant response(s) to clipboard.",
|
|
175
175
|
"no_responses": "No assistant responses to copy.",
|
|
176
|
-
"usage": "Usage: /copy [N]\nN = number of recent assistant responses to copy (default: 1)"
|
|
176
|
+
"usage": "Usage: /copy [N]\nN = number of recent assistant responses to copy (default: 1)",
|
|
177
|
+
"pick_prompt": "Select a response to copy:"
|
|
177
178
|
},
|
|
178
179
|
"recap": {
|
|
179
180
|
"title": "── Session Recap ──",
|
|
@@ -859,6 +860,13 @@
|
|
|
859
860
|
"unknown": "Unknown rendering error",
|
|
860
861
|
"recovery": "The terminal interface encountered a rendering issue. Auto-recovery in 5 seconds... Press Enter to attempt immediate recovery.",
|
|
861
862
|
"preserved": "Your session data and conversation history are preserved."
|
|
863
|
+
},
|
|
864
|
+
"tool": {
|
|
865
|
+
"not_run": "Not run"
|
|
866
|
+
},
|
|
867
|
+
"copy_picker": {
|
|
868
|
+
"title": "/copy",
|
|
869
|
+
"nav_help": "(↑↓ to move, Enter to copy, Esc to cancel)"
|
|
862
870
|
}
|
|
863
871
|
},
|
|
864
872
|
"tools": {
|
|
@@ -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": "── 会话回顾 ──",
|
|
@@ -859,6 +860,13 @@
|
|
|
859
860
|
"unknown": "未知渲染错误",
|
|
860
861
|
"recovery": "终端界面遇到渲染问题,5 秒后自动恢复... 按 Enter 尝试立即恢复。",
|
|
861
862
|
"preserved": "你的会话数据和对话历史已保留。"
|
|
863
|
+
},
|
|
864
|
+
"tool": {
|
|
865
|
+
"not_run": "未运行"
|
|
866
|
+
},
|
|
867
|
+
"copy_picker": {
|
|
868
|
+
"title": "/copy",
|
|
869
|
+
"nav_help": "(↑↓ 移动,回车复制,Esc 取消)"
|
|
862
870
|
}
|
|
863
871
|
},
|
|
864
872
|
"tools": {
|
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
|
}
|
package/src/mcp/instructions.ts
CHANGED
|
@@ -1,16 +1,33 @@
|
|
|
1
1
|
import type { ConnectionInfo } from './types'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* 一段「给模型看的 MCP 文本」的统一上限 —— 单 server 的 instructions、
|
|
5
|
+
* 单个工具的描述,都用它。
|
|
5
6
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
7
|
+
* 这是**不受我们控制**的第三方文本,且**每次请求都要重新付一遍前缀**:一个啰嗦的 server
|
|
8
|
+
* 能靠一段自带说明把别人的预算吃光。三个面此前各是各的数字(server instructions 2000 /
|
|
9
|
+
* up-front 工具定义**无上限** / tool-search 命中列表 120)—— 无上限那面最危险,120 那面则把
|
|
10
|
+
* 「该不该用这个工具」的依据砍到看不见。统一到一个数,让「一屏 MCP 文本有多长」只有一个答案。
|
|
9
11
|
*/
|
|
10
|
-
export const
|
|
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
|
+
|
|
14
31
|
/** True when every character is a plain ASCII code point (0x00–0x7F). */
|
|
15
32
|
function isAsciiName(s: string): boolean {
|
|
16
33
|
for (let i = 0; i < s.length; i++) {
|
|
@@ -60,10 +77,7 @@ export function buildMcpInstructionsBlock(connections: ConnectionInfo[]): string
|
|
|
60
77
|
.sort((a, b) => compareNames(a.config.name, b.config.name))
|
|
61
78
|
.map((c) => {
|
|
62
79
|
const raw = c.instructions!.trim()
|
|
63
|
-
const body =
|
|
64
|
-
raw.length > MCP_INSTRUCTIONS_PER_SERVER_CAP
|
|
65
|
-
? `${raw.slice(0, MCP_INSTRUCTIONS_PER_SERVER_CAP)}\n${TRUNCATION_MARKER}`
|
|
66
|
-
: raw
|
|
80
|
+
const body = capMcpText(raw, MCP_INSTRUCTIONS_PER_SERVER_CAP)
|
|
67
81
|
return `### ${c.config.name}\n${body}`
|
|
68
82
|
})
|
|
69
83
|
|
package/src/mcp/registry.ts
CHANGED
|
@@ -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,
|
package/src/mcp/transport.ts
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
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
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
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()
|
|
@@ -129,6 +130,27 @@ function resolveBaseDelayMs(): number {
|
|
|
129
130
|
return ms
|
|
130
131
|
}
|
|
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
|
+
|
|
132
154
|
/**
|
|
133
155
|
* Fetch with optional timeout and retry with exponential backoff.
|
|
134
156
|
*
|