@miphamai/cli 0.85.17 → 0.85.19
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/sub-agent.ts +11 -0
- package/src/agent/types.ts +8 -0
- package/src/agent-view/agent-view-manager.ts +50 -0
- package/src/config/defaults.ts +6 -1
- package/src/core/credential-masker/output-scrub.ts +8 -1
- package/src/core/engine.ts +88 -9
- package/src/core/instructions.ts +97 -2
- package/src/core/permission-rules.ts +52 -4
- package/src/core/permission.ts +6 -2
- package/src/core/session-log.ts +10 -0
- package/src/daemon/channel-message.ts +8 -1
- package/src/daemon/session-worker.ts +17 -2
- package/src/i18n-core/locales/en-US.json +4 -2
- package/src/i18n-core/locales/zh-CN.json +4 -2
- package/src/index.tsx +22 -1
- package/src/mcp/client.ts +20 -1
- package/src/mcp/http-transport.ts +48 -3
- package/src/mcp/instructions.ts +25 -1
- package/src/mcp/protocol.ts +69 -2
- package/src/providers/anthropic.ts +47 -12
- package/src/providers/fetch-utils.ts +72 -4
- package/src/providers/openai-compat.ts +13 -10
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +12 -0
- package/src/skills/loader.ts +13 -2
- package/src/skills/sanitizer.ts +16 -8
- package/src/tools/agent/agent.ts +24 -0
- package/src/tools/agent/skill.ts +13 -0
- package/src/tools/artifact/artifact.ts +9 -9
- package/src/tools/exec/bash.ts +10 -0
- package/src/tools/file/grep.ts +11 -2
- package/src/tools/file/read.ts +21 -0
- package/src/tools/network/web-fetch.ts +87 -22
- package/src/tools/scheduling/schedule-wakeup.ts +156 -32
- package/src/ui/app.tsx +47 -6
- package/src/ui/chat.tsx +15 -1
- package/src/ui/input.tsx +25 -1
- package/src/workflow/primitives/agent.ts +1 -0
|
@@ -772,6 +772,7 @@
|
|
|
772
772
|
"focus_hint": "Focus",
|
|
773
773
|
"hidden": "hidden",
|
|
774
774
|
"toggle_focus_hint": "/focus to toggle",
|
|
775
|
+
"try_focus_tip": "Long turn? Ctrl+F (or /focus) shows just the latest exchange — press it again to switch back.",
|
|
775
776
|
"expand_hint": "Ctrl+O to expand",
|
|
776
777
|
"showing_all": "showing all {count} messages",
|
|
777
778
|
"tool_outputs_folded": "{hidden} tool outputs folded ({toolCount} total tool calls)"
|
|
@@ -929,8 +930,8 @@
|
|
|
929
930
|
"errors": {
|
|
930
931
|
"tool_denied_deny_rule": "Tool \"{name}\" blocked by a deny rule (\"{pattern}\"). Deny rules override permission mode — try a different approach, or drop the rule with: /permissions remove \"{pattern}\"",
|
|
931
932
|
"tool_denied_ask_rule": "Tool \"{name}\" requires approval (ask rule: \"{pattern}\"). Approve when prompted, or stop being asked with: /permissions allow \"{pattern}\"",
|
|
932
|
-
"tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\")
|
|
933
|
-
"tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule
|
|
933
|
+
"tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\").",
|
|
934
|
+
"tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule. Note that `/permissions allow \"{name}\"` skips the classifier for every later call to this tool, not just this one, so prefer making the call acceptable over allowing the tool.",
|
|
934
935
|
"tool_denied_dangerous_rm": "Tool \"{name}\" was refused: this is a recursive rm whose target is not a path written in the command (\"{target}\"). The target is produced when the command runs, so neither an allow rule nor the permission mode can bound what it deletes. Name the directory literally instead — `rm -rf node_modules` rather than `rm -rf \"$(pwd)\"` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
935
936
|
"tool_denied_world_writable_chmod": "Tool \"{name}\" was refused: this is a recursive chmod that grants world-write to a target the command does not bound (\"{target}\"). A world-writable tree plus a target produced at run time is how permissions end up loosened far past what was asked for, and neither an allow rule nor the permission mode can bound where the grant reaches. Name the directory literally instead — `chmod -R 777 ./dist` rather than `chmod -R 777 $DIR` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_CHMOD_PROMPT=1",
|
|
936
937
|
"tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
|
|
@@ -953,6 +954,7 @@
|
|
|
953
954
|
"oauth_no_code": "No authorization code received",
|
|
954
955
|
"oauth_timeout": "OAuth flow timed out (5 minutes)",
|
|
955
956
|
"mcp_register_collision": "[mcp] Tool collision: \"{name}\" (from server \"{server}\") conflicts with existing tool. Skipping.",
|
|
957
|
+
"mcp_protocol_version_mismatch": "[mcp] Server negotiated protocol version \"{version}\", which this client does not implement (supported: {supported}). Continuing, but MCP messages may not behave as expected.",
|
|
956
958
|
"mcp_register_failed": "[mcp] Failed to register tool \"{tool}\" from server \"{server}\": {error}",
|
|
957
959
|
"max_tool_turns": "Max tool-calling turns ({max}) reached. Some tool calls were not executed.",
|
|
958
960
|
"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.",
|
|
@@ -772,6 +772,7 @@
|
|
|
772
772
|
"focus_hint": "聚焦",
|
|
773
773
|
"hidden": "已折叠",
|
|
774
774
|
"toggle_focus_hint": "/focus 切换",
|
|
775
|
+
"try_focus_tip": "这一轮较长?Ctrl+F(或 /focus)只显示最近一次往来 —— 再按一次即可切回。",
|
|
775
776
|
"expand_hint": "Ctrl+O 展开",
|
|
776
777
|
"showing_all": "显示全部 {count} 条消息",
|
|
777
778
|
"tool_outputs_folded": "已折叠 {hidden} 个工具输出(共 {toolCount} 个工具调用)"
|
|
@@ -929,8 +930,8 @@
|
|
|
929
930
|
"errors": {
|
|
930
931
|
"tool_denied_deny_rule": "工具 \"{name}\" 被拒绝规则(\"{pattern}\")阻止。拒绝规则优先于权限模式 — 请改用其他方式,或移除该规则:/permissions remove \"{pattern}\"",
|
|
931
932
|
"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})。这是策略裁决、不是故障 ——
|
|
933
|
+
"tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可)。",
|
|
934
|
+
"tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则。注意:`/permissions allow \"{name}\"` 会让此后对该工具的**每一次**调用都跳过分类器,而不只是这一次,故优先把这次调用改成可接受的,而不是放行整个工具。",
|
|
934
935
|
"tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
935
936
|
"tool_denied_world_writable_chmod": "工具 \"{name}\" 被拒绝:这是一条递归 chmod,它把「其他用户可写」授予了一个命令并未界定边界的目标(\"{target}\")。一棵世界可写的树,加上一个要到运行时才产生的目标,正是权限被放宽到远超所求的由来;而任何放行规则与权限模式都无法界定这次授权会伸到哪里。请改为字面写出目录名 —— 用 `chmod -R 777 ./dist` 而不是 `chmod -R 777 $DIR` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_CHMOD_PROMPT=1",
|
|
936
937
|
"tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
|
|
@@ -953,6 +954,7 @@
|
|
|
953
954
|
"oauth_no_code": "未收到授权码",
|
|
954
955
|
"oauth_timeout": "OAuth 流程超时(5 分钟)",
|
|
955
956
|
"mcp_register_collision": "[mcp] 工具冲突:\"{name}\"(来自服务器 \"{server}\")与已有工具冲突,跳过。",
|
|
957
|
+
"mcp_protocol_version_mismatch": "[mcp] 服务器协商出的协议版本为 \"{version}\",本客户端未实现该版本(支持:{supported})。将继续连接,但 MCP 消息可能不按预期工作。",
|
|
956
958
|
"mcp_register_failed": "[mcp] 注册工具 \"{tool}\"(来自服务器 \"{server}\")失败:{error}",
|
|
957
959
|
"max_tool_turns": "超出最大工具调用轮次({max})。部分工具调用未执行。",
|
|
958
960
|
"max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
|
package/src/index.tsx
CHANGED
|
@@ -570,6 +570,7 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
570
570
|
provider: defaultProvider,
|
|
571
571
|
model: defaultModel,
|
|
572
572
|
cwd: process.cwd(),
|
|
573
|
+
permissionMode: permission.getMode(),
|
|
573
574
|
})
|
|
574
575
|
context.setLog(sessionLog)
|
|
575
576
|
// Cache-aware microcompaction: track the provider's prompt-cache prefix.
|
|
@@ -596,7 +597,7 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
596
597
|
const events = log.events()
|
|
597
598
|
if (events.length > 0) {
|
|
598
599
|
const start = events.find((e) => e.type === 'session/start') as
|
|
599
|
-
{ type: 'session/start'; cwd?: string } | undefined
|
|
600
|
+
{ type: 'session/start'; cwd?: string; permissionMode?: string } | undefined
|
|
600
601
|
if (start?.cwd && existsSync(start.cwd)) {
|
|
601
602
|
try {
|
|
602
603
|
process.chdir(start.cwd)
|
|
@@ -604,6 +605,26 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
604
605
|
// cwd 可能已不存在
|
|
605
606
|
}
|
|
606
607
|
}
|
|
608
|
+
// Put the permission mode back. It is part of what this session *was* —
|
|
609
|
+
// plan mode especially, which is lost on every resume otherwise. An
|
|
610
|
+
// explicit `--permission` on this invocation still wins: that is the
|
|
611
|
+
// operator's word, typed seconds ago, against a value written days ago.
|
|
612
|
+
// The restore is announced whenever it widens away from the configured
|
|
613
|
+
// default, because "the gate you were running under changed" is exactly
|
|
614
|
+
// the kind of difference that must not be silent (same reason a withheld
|
|
615
|
+
// project-level mode is announced above).
|
|
616
|
+
const resumedMode = start?.permissionMode
|
|
617
|
+
if (resumedMode && !options.permission) {
|
|
618
|
+
const before = permission.getMode()
|
|
619
|
+
permission.setDefaultLevel(resumedMode as PermissionLevel)
|
|
620
|
+
const after = permission.getMode()
|
|
621
|
+
if (after !== before) {
|
|
622
|
+
process.stderr.write(
|
|
623
|
+
`⚠ Mipham Code: resumed permission mode "${after}" from this session ` +
|
|
624
|
+
`(was "${before}"). Shift+Tab to change it.\n`,
|
|
625
|
+
)
|
|
626
|
+
}
|
|
627
|
+
}
|
|
607
628
|
context.restoreLog(log)
|
|
608
629
|
context.setSystemPrompt(instructions.buildSystemPrompt())
|
|
609
630
|
}
|
package/src/mcp/client.ts
CHANGED
|
@@ -36,6 +36,24 @@ function connectTimeoutMs(): number {
|
|
|
36
36
|
return Number.isFinite(env) && env > 0 ? env : DEFAULT_CONNECT_TIMEOUT_MS
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
/**
|
|
40
|
+
* Will retrying this connect failure change the answer?
|
|
41
|
+
*
|
|
42
|
+
* A 4xx is the server stating a verdict about *this request* — a rejected token,
|
|
43
|
+
* a path that does not exist, a malformed handshake. It says the same thing on
|
|
44
|
+
* attempt 10 as on attempt 1, so the ten-attempt backoff (~8 minutes) only
|
|
45
|
+
* delays telling the user what is wrong. 408 (request timeout) and 429 (rate
|
|
46
|
+
* limited) are the two 4xx that explicitly mean "try again", so they stay
|
|
47
|
+
* retryable along with everything that is not an HTTP verdict at all (connection
|
|
48
|
+
* refused, DNS, a 5xx).
|
|
49
|
+
*/
|
|
50
|
+
function isTransientConnectError(err: unknown): boolean {
|
|
51
|
+
if (err instanceof McpHttpError) {
|
|
52
|
+
return !(err.status >= 400 && err.status < 500) || err.status === 408 || err.status === 429
|
|
53
|
+
}
|
|
54
|
+
return true
|
|
55
|
+
}
|
|
56
|
+
|
|
39
57
|
/**
|
|
40
58
|
* Render a connect failure for the user, adding the one hint a bare error
|
|
41
59
|
* cannot carry: that the fix is to authenticate.
|
|
@@ -279,7 +297,8 @@ export class McpClient {
|
|
|
279
297
|
this.emit('reconnected', name)
|
|
280
298
|
return
|
|
281
299
|
} catch (err) {
|
|
282
|
-
|
|
300
|
+
// Stop early on a definitive refusal — see `isTransientConnectError`.
|
|
301
|
+
if (!isTransientConnectError(err) || attempt === maxAttempts) {
|
|
283
302
|
connection.status = 'error'
|
|
284
303
|
connection.error = String(err)
|
|
285
304
|
this.emit('disconnected', name, err)
|
|
@@ -106,6 +106,51 @@ function parseSseResponse(
|
|
|
106
106
|
return { content: [{ type: 'text', text: texts.join('') }], isError: false }
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/**
|
|
110
|
+
* Upper bound on a single response body, in bytes.
|
|
111
|
+
*
|
|
112
|
+
* `response.text()` / `.json()` buffer whatever the server sends, so a buggy
|
|
113
|
+
* server (a runaway log line) or a hostile one (an 8 GB "result") would be
|
|
114
|
+
* pulled into memory in full before any comparison could run. The cap has to
|
|
115
|
+
* be part of the read, not a check after it.
|
|
116
|
+
*/
|
|
117
|
+
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024
|
|
118
|
+
|
|
119
|
+
/** Read a response body, refusing anything past `maxBytes`. */
|
|
120
|
+
async function readBodyCapped(
|
|
121
|
+
response: Response,
|
|
122
|
+
maxBytes: number = MAX_RESPONSE_BYTES,
|
|
123
|
+
): Promise<string> {
|
|
124
|
+
// A declared Content-Length lets us refuse before reading a single byte.
|
|
125
|
+
const declared = Number(response.headers.get('content-length'))
|
|
126
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
127
|
+
throw new Error(`MCP response body declared ${declared} bytes (limit ${maxBytes})`)
|
|
128
|
+
}
|
|
129
|
+
// Header absent or lying — fall back to a streaming read with a running total.
|
|
130
|
+
if (!response.body) return await response.text()
|
|
131
|
+
|
|
132
|
+
const reader = response.body.getReader()
|
|
133
|
+
const decoder = new TextDecoder()
|
|
134
|
+
let text = ''
|
|
135
|
+
let total = 0
|
|
136
|
+
try {
|
|
137
|
+
for (;;) {
|
|
138
|
+
const { done, value } = await reader.read()
|
|
139
|
+
if (done) break
|
|
140
|
+
if (!value) continue
|
|
141
|
+
total += value.byteLength
|
|
142
|
+
if (total > maxBytes) {
|
|
143
|
+
await reader.cancel().catch(() => {})
|
|
144
|
+
throw new Error(`MCP response body exceeded the ${maxBytes}-byte limit`)
|
|
145
|
+
}
|
|
146
|
+
text += decoder.decode(value, { stream: true })
|
|
147
|
+
}
|
|
148
|
+
} finally {
|
|
149
|
+
reader.releaseLock()
|
|
150
|
+
}
|
|
151
|
+
return text + decoder.decode()
|
|
152
|
+
}
|
|
153
|
+
|
|
109
154
|
/**
|
|
110
155
|
* MCP Streamable HTTP transport — speaks JSON-RPC 2.0 to an HTTP endpoint
|
|
111
156
|
* (e.g. Forge's `POST /mcp`), returning plain JSON or reassembled SSE streams.
|
|
@@ -183,7 +228,7 @@ export class HttpTransport implements Transport {
|
|
|
183
228
|
if (!response.ok) {
|
|
184
229
|
let detail = `HTTP ${response.status}`
|
|
185
230
|
try {
|
|
186
|
-
detail = JSON.stringify(await response
|
|
231
|
+
detail = JSON.stringify(JSON.parse(await readBodyCapped(response)))
|
|
187
232
|
} catch {
|
|
188
233
|
/* keep status-only detail */
|
|
189
234
|
}
|
|
@@ -197,10 +242,10 @@ export class HttpTransport implements Transport {
|
|
|
197
242
|
|
|
198
243
|
const contentType = response.headers.get('content-type') || ''
|
|
199
244
|
if (contentType.includes('text/event-stream')) {
|
|
200
|
-
return parseSseResponse(await response
|
|
245
|
+
return parseSseResponse(await readBodyCapped(response), (n) => this.dispatchNotification(n))
|
|
201
246
|
}
|
|
202
247
|
|
|
203
|
-
const json = (await response
|
|
248
|
+
const json = JSON.parse(await readBodyCapped(response)) as JsonRpcResponse
|
|
204
249
|
if (json.error) {
|
|
205
250
|
throw new Error(`MCP error ${json.error.code}: ${json.error.message}`)
|
|
206
251
|
}
|
package/src/mcp/instructions.ts
CHANGED
|
@@ -11,6 +11,30 @@ export const MCP_INSTRUCTIONS_PER_SERVER_CAP = 2000
|
|
|
11
11
|
|
|
12
12
|
const TRUNCATION_MARKER = '… [truncated]'
|
|
13
13
|
|
|
14
|
+
/** True when every character is a plain ASCII code point (0x00–0x7F). */
|
|
15
|
+
function isAsciiName(s: string): boolean {
|
|
16
|
+
for (let i = 0; i < s.length; i++) {
|
|
17
|
+
if (s.charCodeAt(i) > 0x7f) return false
|
|
18
|
+
}
|
|
19
|
+
return true
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Order two names for the model-facing block: ASCII names first, then the rest.
|
|
24
|
+
*
|
|
25
|
+
* `localeCompare` is locale-*aware*, which is exactly wrong here: it threads an
|
|
26
|
+
* accented name (`Émile`) in among the ASCII ones and only relegates pure CJK to
|
|
27
|
+
* the end, so the same set of servers can order differently across machines. The
|
|
28
|
+
* reader is a model, not a human locale — the list wants a fixed shape. Within
|
|
29
|
+
* each group, compare by code unit, which is deterministic everywhere.
|
|
30
|
+
*/
|
|
31
|
+
export function compareNames(a: string, b: string): number {
|
|
32
|
+
const aAscii = isAsciiName(a)
|
|
33
|
+
const bAscii = isAsciiName(b)
|
|
34
|
+
if (aAscii !== bAscii) return aAscii ? -1 : 1
|
|
35
|
+
return a < b ? -1 : a > b ? 1 : 0
|
|
36
|
+
}
|
|
37
|
+
|
|
14
38
|
/**
|
|
15
39
|
* 把已连接 MCP server 自带的 `instructions` 拼成一段**系统提示用**的文本。
|
|
16
40
|
*
|
|
@@ -33,7 +57,7 @@ export function buildMcpInstructionsBlock(connections: ConnectionInfo[]): string
|
|
|
33
57
|
const sections = connections
|
|
34
58
|
.filter((c) => typeof c.instructions === 'string' && c.instructions.trim() !== '')
|
|
35
59
|
.slice()
|
|
36
|
-
.sort((a, b) => a.config.name
|
|
60
|
+
.sort((a, b) => compareNames(a.config.name, b.config.name))
|
|
37
61
|
.map((c) => {
|
|
38
62
|
const raw = c.instructions!.trim()
|
|
39
63
|
const body =
|
package/src/mcp/protocol.ts
CHANGED
|
@@ -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
|
-
|
|
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:
|
|
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
|
|
|
@@ -6,7 +6,12 @@ import type {
|
|
|
6
6
|
ContentBlock,
|
|
7
7
|
} from '../shared/index.ts'
|
|
8
8
|
import type { ProviderInstance, ChatRequest } from './registry'
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
fetchWithRetry,
|
|
11
|
+
streamIdleTimeoutMs,
|
|
12
|
+
isRetryableFailure,
|
|
13
|
+
createAwakeTimer,
|
|
14
|
+
} from './fetch-utils'
|
|
10
15
|
|
|
11
16
|
interface AnthropicContentBlock {
|
|
12
17
|
type: string
|
|
@@ -66,11 +71,43 @@ function isEmptyTextBlock(block: Record<string, unknown>): boolean {
|
|
|
66
71
|
}
|
|
67
72
|
|
|
68
73
|
export class AnthropicProvider implements ProviderInstance {
|
|
69
|
-
private baseUrl = 'https://api.anthropic.com/v1'
|
|
70
74
|
private anthropicVersion = '2023-06-01'
|
|
71
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Honour a user-level `baseUrl` override the way `openai-compat` does.
|
|
78
|
+
*
|
|
79
|
+
* The config loader treats `baseUrl` as a **routing** field — it decides where
|
|
80
|
+
* the user's API key is sent, so only trusted (user-level) config may set it
|
|
81
|
+
* (see `config/loader.ts`). Hard-coding the endpoint here silently dropped that
|
|
82
|
+
* override: a user who pointed the provider at a proxy or gateway still had
|
|
83
|
+
* every request sent to `api.anthropic.com`. Read it, with the official
|
|
84
|
+
* endpoint as the fallback the default config (which sets no `baseUrl`) relies
|
|
85
|
+
* on. `baseURL` is accepted too — the same common typo `openai-compat` allows.
|
|
86
|
+
*/
|
|
87
|
+
private get baseUrl(): string {
|
|
88
|
+
const raw = this.config.baseUrl ?? (this.config as { baseURL?: string }).baseURL
|
|
89
|
+
return raw?.replace(/\/+$/, '') || 'https://api.anthropic.com/v1'
|
|
90
|
+
}
|
|
91
|
+
|
|
72
92
|
constructor(public config: ProviderConfig) {}
|
|
73
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Are we talking to api.anthropic.com itself, or to a custom `baseUrl`?
|
|
96
|
+
*
|
|
97
|
+
* `anthropic-beta` is a header for Anthropic's own gateway. A custom base URL
|
|
98
|
+
* is by definition some other gateway — a proxy, a corporate relay, an
|
|
99
|
+
* Anthropic-compatible shim — and sending a beta flag that gateway does not
|
|
100
|
+
* implement is a way to turn a working setup into `400 Bad Request` the moment
|
|
101
|
+
* the endpoint changes, with nothing in the message pointing at the header.
|
|
102
|
+
*/
|
|
103
|
+
private get isDefaultApiHost(): boolean {
|
|
104
|
+
try {
|
|
105
|
+
return new URL(this.baseUrl).host === 'api.anthropic.com'
|
|
106
|
+
} catch {
|
|
107
|
+
return false
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
74
111
|
async *chat(req: ChatRequest): AsyncGenerator<StreamChunk> {
|
|
75
112
|
const apiKey = this.resolveApiKey(this.config.apiKey)
|
|
76
113
|
|
|
@@ -149,7 +186,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
149
186
|
'Content-Type': 'application/json',
|
|
150
187
|
'x-api-key': apiKey,
|
|
151
188
|
'anthropic-version': this.anthropicVersion,
|
|
152
|
-
'anthropic-beta': 'prompt-caching-2024-07-31',
|
|
189
|
+
...(this.isDefaultApiHost ? { 'anthropic-beta': 'prompt-caching-2024-07-31' } : {}),
|
|
153
190
|
},
|
|
154
191
|
body: JSON.stringify(body),
|
|
155
192
|
// Same as `openai-compat`: without this the caller's signal never reaches
|
|
@@ -190,19 +227,17 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
190
227
|
try {
|
|
191
228
|
while (true) {
|
|
192
229
|
let readResult: Awaited<ReturnType<typeof reader.read>>
|
|
193
|
-
let
|
|
230
|
+
let cancelIdle: (() => void) | undefined
|
|
194
231
|
try {
|
|
195
232
|
readResult = await Promise.race([
|
|
196
233
|
reader.read(),
|
|
197
234
|
new Promise<never>((_, reject) => {
|
|
198
|
-
|
|
199
|
-
(
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
`Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
203
|
-
),
|
|
235
|
+
cancelIdle = createAwakeTimer(STREAM_READ_TIMEOUT_MS, () =>
|
|
236
|
+
reject(
|
|
237
|
+
new Error(
|
|
238
|
+
`Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
204
239
|
),
|
|
205
|
-
|
|
240
|
+
),
|
|
206
241
|
)
|
|
207
242
|
}),
|
|
208
243
|
])
|
|
@@ -210,7 +245,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
210
245
|
yield { type: 'error', error: `Stream stalled: ${String(err)}` }
|
|
211
246
|
return
|
|
212
247
|
} finally {
|
|
213
|
-
|
|
248
|
+
cancelIdle?.()
|
|
214
249
|
}
|
|
215
250
|
const { done, value } = readResult
|
|
216
251
|
if (done) break
|
|
@@ -106,6 +106,29 @@ export function isRetryableFailure(status: number | undefined, errorType?: strin
|
|
|
106
106
|
return !NON_RETRYABLE_ERROR_TYPES.has(errorType)
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/** Base backoff between retry attempts, in ms. */
|
|
110
|
+
export const DEFAULT_RETRY_BASE_DELAY_MS = 1_000
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The default backoff, overridable from the environment.
|
|
114
|
+
*
|
|
115
|
+
* One second suits an interactive turn, but a caller pointed at a known-overloaded
|
|
116
|
+
* endpoint (a self-hosted gateway, a batch run) wants longer gaps between attempts
|
|
117
|
+
* — and cannot pass `baseDelay` through the SDK paths that build their own
|
|
118
|
+
* `fetchWithRetry` call. `MIPHAM_OVERLOADED_RETRY_BASE_DELAY_MS` is that knob.
|
|
119
|
+
*
|
|
120
|
+
* A malformed value (non-numeric, negative) is a typo, not an instruction: fall
|
|
121
|
+
* back to the built-in rather than let `sleep(NaN)` become a zero-delay retry
|
|
122
|
+
* loop. Read per call so a test can set it without re-importing the module.
|
|
123
|
+
*/
|
|
124
|
+
function resolveBaseDelayMs(): number {
|
|
125
|
+
const raw = process.env.MIPHAM_OVERLOADED_RETRY_BASE_DELAY_MS
|
|
126
|
+
if (raw === undefined || raw.trim() === '') return DEFAULT_RETRY_BASE_DELAY_MS
|
|
127
|
+
const ms = Number(raw)
|
|
128
|
+
if (!Number.isFinite(ms) || ms < 0) return DEFAULT_RETRY_BASE_DELAY_MS
|
|
129
|
+
return ms
|
|
130
|
+
}
|
|
131
|
+
|
|
109
132
|
/**
|
|
110
133
|
* Fetch with optional timeout and retry with exponential backoff.
|
|
111
134
|
*
|
|
@@ -118,17 +141,19 @@ export async function fetchWithRetry(
|
|
|
118
141
|
init: RequestInit,
|
|
119
142
|
options: FetchWithRetryOptions = {},
|
|
120
143
|
): Promise<Response> {
|
|
121
|
-
const { timeout = 60_000, maxRetries = 2, baseDelay =
|
|
144
|
+
const { timeout = 60_000, maxRetries = 2, baseDelay = resolveBaseDelayMs() } = options
|
|
122
145
|
|
|
123
146
|
let lastErr: unknown
|
|
124
147
|
|
|
125
148
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
126
149
|
const controller = new AbortController()
|
|
127
150
|
let timedOut = false
|
|
128
|
-
|
|
151
|
+
// Awake-time, not wall-clock: a machine that slept through the window has
|
|
152
|
+
// not actually waited `timeout` ms for a first byte (see `createAwakeTimer`).
|
|
153
|
+
const cancelTimer = createAwakeTimer(timeout, () => {
|
|
129
154
|
timedOut = true
|
|
130
155
|
controller.abort()
|
|
131
|
-
}
|
|
156
|
+
})
|
|
132
157
|
// `AbortSignal.any` (node ≥22 / bun ≥1.2, both in `engines`) instead of a
|
|
133
158
|
// hand-rolled combiner: it keeps a *weak* reference to the source signals, so
|
|
134
159
|
// the combination stays live for the reader without pinning the caller's
|
|
@@ -161,7 +186,7 @@ export async function fetchWithRetry(
|
|
|
161
186
|
}
|
|
162
187
|
await sleep(baseDelay * Math.pow(2, attempt))
|
|
163
188
|
} finally {
|
|
164
|
-
|
|
189
|
+
cancelTimer()
|
|
165
190
|
// Nothing to release: the combination is natively managed. Do NOT abort
|
|
166
191
|
// anything here — `fetch` holds that signal and the caller reads the body
|
|
167
192
|
// *after* we return, so aborting it at this point errored every response at
|
|
@@ -199,3 +224,46 @@ export function streamIdleTimeoutMs(effort?: string): number {
|
|
|
199
224
|
const multiplier = effort ? (EFFORT_TIMEOUT_MULTIPLIER[effort] ?? 1) : 1
|
|
200
225
|
return STREAM_IDLE_TIMEOUT_BASE_MS * multiplier
|
|
201
226
|
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* A timeout that measures *awake* time, and so survives the machine sleeping.
|
|
230
|
+
*
|
|
231
|
+
* `setTimeout` runs on the wall clock. A laptop suspended for an hour fires every
|
|
232
|
+
* pending timer the instant it wakes, so a 90-second idle budget is reported the
|
|
233
|
+
* moment the user opens the lid — the stream is declared stalled and the turn is
|
|
234
|
+
* killed, even though the connection sat idle for zero seconds of real time.
|
|
235
|
+
*
|
|
236
|
+
* `performance.now()` is monotonic and does not advance while the host is
|
|
237
|
+
* suspended, so the difference it reports is time the machine was actually awake.
|
|
238
|
+
* When the timer fires with less than `budgetMs` of awake time behind it, the
|
|
239
|
+
* shortfall was a sleep: re-arm for the remainder instead of firing.
|
|
240
|
+
*
|
|
241
|
+
* Returns a cancel function.
|
|
242
|
+
*/
|
|
243
|
+
export function createAwakeTimer(budgetMs: number, onExpire: () => void): () => void {
|
|
244
|
+
// The epoch the budget is measured from. Kept across a re-arm so the next
|
|
245
|
+
// check compares against the total awake time, not just the last slice.
|
|
246
|
+
const start = performance.now()
|
|
247
|
+
let handle: ReturnType<typeof setTimeout> | undefined
|
|
248
|
+
let cancelled = false
|
|
249
|
+
|
|
250
|
+
const arm = (remainingMs: number): void => {
|
|
251
|
+
handle = setTimeout(() => {
|
|
252
|
+
if (cancelled) return
|
|
253
|
+
const elapsed = performance.now() - start
|
|
254
|
+
if (elapsed < budgetMs) {
|
|
255
|
+
// Woke from sleep: only part of the budget was really spent. Keep the
|
|
256
|
+
// epoch and re-arm for what is left.
|
|
257
|
+
arm(Math.max(0, budgetMs - elapsed))
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
onExpire()
|
|
261
|
+
}, remainingMs)
|
|
262
|
+
}
|
|
263
|
+
arm(budgetMs)
|
|
264
|
+
|
|
265
|
+
return () => {
|
|
266
|
+
cancelled = true
|
|
267
|
+
if (handle !== undefined) clearTimeout(handle)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { execSync } from 'node:child_process'
|
|
2
2
|
import type { ProviderConfig, ModelInfo, Message, StreamChunk } from '../shared/index.ts'
|
|
3
3
|
import type { ProviderInstance, ChatRequest } from './registry'
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
fetchWithRetry,
|
|
6
|
+
streamIdleTimeoutMs,
|
|
7
|
+
isRetryableFailure,
|
|
8
|
+
createAwakeTimer,
|
|
9
|
+
} from './fetch-utils'
|
|
5
10
|
import { OLLAMA_PRESET_MODELS } from '../shared/constants'
|
|
6
11
|
|
|
7
12
|
export class OpenAICompatProvider implements ProviderInstance {
|
|
@@ -81,19 +86,17 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
81
86
|
try {
|
|
82
87
|
while (true) {
|
|
83
88
|
let readResult: Awaited<ReturnType<typeof reader.read>>
|
|
84
|
-
let
|
|
89
|
+
let cancelIdle: (() => void) | undefined
|
|
85
90
|
try {
|
|
86
91
|
readResult = await Promise.race([
|
|
87
92
|
reader.read(),
|
|
88
93
|
new Promise<never>((_, reject) => {
|
|
89
|
-
|
|
90
|
-
(
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
`Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
94
|
-
),
|
|
94
|
+
cancelIdle = createAwakeTimer(STREAM_READ_TIMEOUT_MS, () =>
|
|
95
|
+
reject(
|
|
96
|
+
new Error(
|
|
97
|
+
`Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
95
98
|
),
|
|
96
|
-
|
|
99
|
+
),
|
|
97
100
|
)
|
|
98
101
|
}),
|
|
99
102
|
])
|
|
@@ -101,7 +104,7 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
101
104
|
yield { type: 'error', error: `Stream stalled: ${String(err)}` }
|
|
102
105
|
return
|
|
103
106
|
} finally {
|
|
104
|
-
|
|
107
|
+
cancelIdle?.()
|
|
105
108
|
}
|
|
106
109
|
const { done, value } = readResult
|
|
107
110
|
if (done) break
|
|
@@ -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.
|
|
12
|
+
export const PACKAGE_VERSION = '0.85.19' 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 =
|
|
93
|
+
export const TEST_COUNT = 4141 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -639,6 +639,18 @@ export interface ToolContext {
|
|
|
639
639
|
* the experience logs use. Absent for the main session.
|
|
640
640
|
*/
|
|
641
641
|
agentName?: string
|
|
642
|
+
/**
|
|
643
|
+
* The bucket an artifact belongs in, when that is not `sessionId`.
|
|
644
|
+
*
|
|
645
|
+
* A sub-agent's `sessionId` is the literal `'sub-agent'` — `SendMessage` keys
|
|
646
|
+
* off that literal to address the parent, so it cannot be changed. Artifacts
|
|
647
|
+
* keyed off the same field therefore put **every** sub-agent in every session
|
|
648
|
+
* into one bucket, and `archiveVersion` then treats an unrelated agent's
|
|
649
|
+
* same-named artifact as "the previous version" of this one. Set by
|
|
650
|
+
* `SubAgent.runExecution` to the parent session plus the agent's name; absent
|
|
651
|
+
* everywhere else, where `sessionId` is already the right answer.
|
|
652
|
+
*/
|
|
653
|
+
artifactSessionId?: string
|
|
642
654
|
}
|
|
643
655
|
|
|
644
656
|
export interface ToolDefinition {
|