@miphamai/cli 0.85.14 → 0.85.16

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 CHANGED
@@ -1,6 +1,6 @@
1
- # Mipham Code v0.85.14
1
+ # Mipham Code v0.85.16
2
2
 
3
- **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
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
 
5
5
  Built by [One Mipham Corporation](https://onemipham.com) (北京华安麦逄科技有限公司) | Brand: MiphamAI
6
6
 
@@ -16,7 +16,7 @@ Requirements: **Bun 1.2+** (recommended) or **Node.js 22+**
16
16
  ## Features
17
17
 
18
18
  - **12 AI Providers** — Anthropic Claude · OpenAI GPT · DeepSeek · Kimi (Moonshot) · Google Gemini · Doubao 豆包 · Tencent Hunyuan 混元 · Qwen 通义千问 · MiniMax(国内 / 国际)· Ollama(本地)· MiphamAI
19
- - **138 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **137 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
20
20
  - **31 Built-in Tools** — File ops, shell execution, agent dispatch, MCP integration, web search
21
21
  - **28 Skills + Marketplace** — 22 standard + 6 Mipham-exclusive skills. `/browse-skills` `/install-skill` community marketplace
22
22
  - **Self-Update** — `mipham update` / `/upgrade` — one command to check, backup config, upgrade, restore. API keys preserved
@@ -59,7 +59,7 @@ mipham update
59
59
  | Category | Commands |
60
60
  | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
61
61
  | Session | `/help` `/version` `/clear` `/exit` `/quit` `/compact` `/context` `/status` `/cost` `/rename` `/goal` `/recap` `/export` `/doctor` `/resume` |
62
- | Model | `/pick` `/model` `/models` `/provider` `/providers` `/switch` `/fast` `/effort` `/theme` `/upgrade` |
62
+ | Model | `/pick` `/model` `/models` `/provider` `/providers` `/switch` `/effort` `/theme` `/upgrade` |
63
63
  | Skills | `/skills` `/browse-skills` `/install-skill` `/remove-skill` `/reload-skills` |
64
64
  | Tools | `/tools` `/commands` `/mcp` |
65
65
  | Workflow | `/plan` `/no-plan` `/review` `/diff` `/todos` `/tasks` `/workflows` `/loop` `/agents` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.14",
3
+ "version": "0.85.16",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -513,7 +513,7 @@ Start a conversation and verify:
513
513
  | ------------------------- | -------------------------------------- | ------------------------------------------------ |
514
514
  | "Provider not registered" | Missing or invalid API key | `env \| grep API_KEY`; check key format |
515
515
  | "Model not found" | Model ID mismatch or disabled provider | `/models` to list available; `/switch` to change |
516
- | Slow responses | Large model, network, or context full | `/fast on` or switch to Flash model; `/compact` |
516
+ | Slow responses | Large model, network, or context full | Switch to Flash model; `/compact` |
517
517
  | Context full | Too many messages in history | `/compact` to compress; `/clear` to reset |
518
518
  | Permission denied | Tool blocked by permission mode | `/permissions` to check; adjust mode |
519
519
  | "Workspace not trusted" | New directory, not yet trusted | Accept startup prompt or run `/trust` |
@@ -9,6 +9,16 @@ export interface RouteResult {
9
9
  routedTo: 'bus' | 'inbox' | 'unknown'
10
10
  error?: string
11
11
  messageId?: string
12
+ /**
13
+ * Cross-session only: the recipient holds inbound messages for approval, so
14
+ * the file landing in its inbox is not the same as it being delivered.
15
+ * `success` stays true (the send did work) — this is what the *notice* has to
16
+ * distinguish, so the sender is not told a message was delivered that the
17
+ * recipient has not seen and may decline.
18
+ */
19
+ held?: boolean
20
+ /** Cross-session only: the resolved recipient's display name. */
21
+ targetName?: string
12
22
  }
13
23
 
14
24
  export interface SessionResolution {
@@ -123,7 +133,16 @@ export class MessageRouter {
123
133
  return { success: false, routedTo: 'inbox', error: 'Failed to write message to inbox.' }
124
134
  }
125
135
 
126
- return { success: true, routedTo: 'inbox', messageId: msg.id }
136
+ return {
137
+ success: true,
138
+ routedTo: 'inbox',
139
+ messageId: msg.id,
140
+ // 'ask' is the default: the recipient's engine holds the message for a
141
+ // user decision before it is ever seen. Writing the file is still the
142
+ // right thing to do — it is the *notice* that must not say "delivered".
143
+ held: targetSession.crossSessionInbound === 'ask',
144
+ targetName: targetSession.name,
145
+ }
127
146
  } catch (err) {
128
147
  return { success: false, routedTo: 'inbox', error: String(err) }
129
148
  }
@@ -506,6 +506,7 @@ export class SubAgent {
506
506
 
507
507
  const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
508
508
  let turnText = ''
509
+ let streamError: string | null = null
509
510
 
510
511
  for await (const chunk of (this.llm ?? this.registry).chat({
511
512
  model: finalModel,
@@ -534,7 +535,14 @@ export class SubAgent {
534
535
  })
535
536
  }
536
537
  if (chunk.type === 'error') {
537
- throw new Error(`Sub-agent execution failed (model ${finalModel}): ${chunk.error}`)
538
+ // A mid-stream failure (timeout, dropped socket) is not a failed run.
539
+ // What the model already produced is real output, and throwing here
540
+ // fails the *whole* sub-agent — every earlier turn with it, since
541
+ // `chunks` is only handed back on a clean exit. Keep the partial turn
542
+ // and stop streaming: a shorter answer beats none. Same call the
543
+ // engine makes when it keeps a turn alive through a failure.
544
+ streamError = chunk.error ?? 'Unknown error'
545
+ break
538
546
  }
539
547
  if (chunk.type === 'stop') {
540
548
  break
@@ -547,6 +555,17 @@ export class SubAgent {
547
555
 
548
556
  chunks.push(turnText)
549
557
 
558
+ // Nothing came back at all, so there is no partial response to continue
559
+ // from — that is a genuine failure and is reported as one.
560
+ if (streamError && !turnText) {
561
+ throw new Error(`Sub-agent execution failed (model ${finalModel}): ${streamError}`)
562
+ }
563
+
564
+ // A partial response *is* the turn's output. Stop here rather than acting
565
+ // on tool calls that arrived before the stream died: they belong to a turn
566
+ // that never finished, and the model never saw their results.
567
+ if (streamError) break
568
+
550
569
  // No tools used — we're done
551
570
  if (toolUses.length === 0) break
552
571
 
@@ -704,25 +704,34 @@ export class QueryEngine {
704
704
  turnApiInputTokens += chunk.inputTokens
705
705
  turnApiOutputTokens += chunk.outputTokens || 0
706
706
  }
707
+ }
707
708
 
708
- if (chunk.type === 'stop') {
709
- // Add assistant response to context
710
- if (assistantContent || reasoningContent || thinkingContent) {
711
- const contentBlocks: import('../shared/types').ContentBlock[] = []
712
- if (thinkingContent) {
713
- contentBlocks.push({ type: 'thinking', thinking: thinkingContent })
714
- }
715
- if (assistantContent) {
716
- contentBlocks.push({ type: 'text', text: assistantContent })
717
- }
718
- const msg: import('../shared/types').Message = {
719
- role: 'assistant',
720
- content: thinkingContent ? contentBlocks : assistantContent || '',
721
- }
722
- if (reasoningContent) msg.reasoning_content = reasoningContent
723
- this.context.addMessage(msg)
724
- }
709
+ // Commit the assistant turn **once, after the stream** — not on each `stop`
710
+ // chunk. Two reasons, both real:
711
+ // 1. The commit used to hang off `chunk.type === 'stop'`, but an ordinary
712
+ // OpenAI-compatible turn emits `stop` twice: once on
713
+ // `finish_reason: "stop"` and again on the trailing `[DONE]`
714
+ // (`openai-compat.ts`). Committing on each added the same assistant
715
+ // message to context twice — the model then saw its own answer doubled.
716
+ // `continueWithTools` already commits after its loop; this matches it.
717
+ // 2. A retried turn re-streams (`restart`), so an attempt that is about to
718
+ // be discarded must not have committed anything yet — otherwise the
719
+ // reasoning-only retry in `chatWithFallback` would leave the blank turn
720
+ // in context beside the answer that replaced it.
721
+ if (assistantContent || reasoningContent || thinkingContent) {
722
+ const contentBlocks: import('../shared/types').ContentBlock[] = []
723
+ if (thinkingContent) {
724
+ contentBlocks.push({ type: 'thinking', thinking: thinkingContent })
725
725
  }
726
+ if (assistantContent) {
727
+ contentBlocks.push({ type: 'text', text: assistantContent })
728
+ }
729
+ const msg: import('../shared/types').Message = {
730
+ role: 'assistant',
731
+ content: thinkingContent ? contentBlocks : assistantContent || '',
732
+ }
733
+ if (reasoningContent) msg.reasoning_content = reasoningContent
734
+ this.context.addMessage(msg)
726
735
  }
727
736
  } catch (err) {
728
737
  if (isAbortError(err)) {
@@ -1576,6 +1585,16 @@ export class QueryEngine {
1576
1585
  let retryable = true
1577
1586
  for (let attempt = 0; ; attempt++) {
1578
1587
  failure = null
1588
+ // A turn can also come back *empty of an answer*: the stream ends cleanly
1589
+ // but carried only reasoning (`thinking` chunks / `reasoning_content`) and
1590
+ // no `text` or `tool_use`. Reasoning models that spend their whole output
1591
+ // budget thinking emit exactly this, and the user is left with a blank
1592
+ // turn. It is not a failed request, but it is not an answer either, so it
1593
+ // gets the same single same-provider retry an error does, and is accepted
1594
+ // if the retry does it again (a shorter answer beats none).
1595
+ let reasoningOnly = false
1596
+ let sawThinking = false
1597
+ let sawOutput = false
1579
1598
  try {
1580
1599
  for await (const chunk of this.llmChat({
1581
1600
  model: activeModel,
@@ -1590,9 +1609,23 @@ export class QueryEngine {
1590
1609
  if (chunk.retryable === false) retryable = false
1591
1610
  break
1592
1611
  }
1612
+ if (chunk.type === 'thinking' && chunk.thinking) sawThinking = true
1613
+ if (chunk.reasoning_content) sawThinking = true
1614
+ if (
1615
+ (chunk.type === 'text' && chunk.content) ||
1616
+ (chunk.type === 'tool_use' && chunk.toolUse)
1617
+ ) {
1618
+ sawOutput = true
1619
+ }
1593
1620
  yield chunk
1594
1621
  }
1595
- if (failure === null) return
1622
+ if (failure === null) {
1623
+ reasoningOnly = sawThinking && !sawOutput
1624
+ // Accept the turn unless it is a reasoning-only attempt we have not yet
1625
+ // retried. A foreign `Llm` seam owns the whole flow and is never
1626
+ // second-guessed, so its reasoning-only turn is accepted as-is.
1627
+ if (!reasoningOnly || !ownsFlow || attempt >= 1) return
1628
+ }
1596
1629
  } catch (err) {
1597
1630
  if (isAbortError(err)) throw err
1598
1631
  failure = String(err)
@@ -1604,7 +1637,9 @@ export class QueryEngine {
1604
1637
  // downstream dedupes them and a side-effecting tool runs twice.
1605
1638
  yield {
1606
1639
  type: 'warning',
1607
- content: `${activeId} failed (${failure}) — retrying once`,
1640
+ content: reasoningOnly
1641
+ ? `${activeId} returned only reasoning and no answer — retrying once`
1642
+ : `${activeId} failed (${failure}) — retrying once`,
1608
1643
  restart: true,
1609
1644
  }
1610
1645
  }
@@ -1657,6 +1692,12 @@ export class QueryEngine {
1657
1692
  yield {
1658
1693
  type: 'warning',
1659
1694
  content: `${activeId} unreachable — degraded to ${defaultId} (${fallbackModel})${windowNote}`,
1695
+ // Same reason as the same-provider retry above: the fallback is a *new*
1696
+ // attempt, and the consumer only drops the failed attempts' accumulated
1697
+ // tool calls on `restart`. Without it the fallback's tool calls are added
1698
+ // to the ones the failures already yielded, and a side-effecting tool runs
1699
+ // once per attempt.
1700
+ restart: true,
1660
1701
  }
1661
1702
 
1662
1703
  try {
@@ -35,7 +35,26 @@ export function loadHookConfigs(configs: SettingsHooks): HookDefinition[] {
35
35
  if (!entries || !Array.isArray(entries)) continue
36
36
 
37
37
  for (const entry of entries) {
38
- const matcherRegex = entry.matcher ? new RegExp(entry.matcher) : null
38
+ // A matcher is only a *filter*, so a malformed one must not take the whole
39
+ // hook set down with it. `new RegExp` throws here, and both callers register
40
+ // the result in a plain `for…of` (`index.tsx:742`,
41
+ // `daemon/engine-capabilities.ts:104`) — so one typo aborts startup, or the
42
+ // session's entire hook wiring, before a single hook is registered. The
43
+ // remaining entries are independent and still work; only this one is
44
+ // degraded, and it is degraded in the direction `HookEngine.matchesMatcher`
45
+ // already documents: matcher absent ⇒ run on every invocation — the
46
+ // fail-closed choice for a guard.
47
+ let matcherRegex: RegExp | null = null
48
+ if (entry.matcher) {
49
+ try {
50
+ matcherRegex = new RegExp(entry.matcher)
51
+ } catch {
52
+ process.stderr.write(
53
+ `⚠️ Hook matcher ${JSON.stringify(entry.matcher)} on ${eventName} is not a valid regex — ` +
54
+ `running that hook on every invocation.\n`,
55
+ )
56
+ }
57
+ }
39
58
 
40
59
  for (const hookCfg of entry.hooks) {
41
60
  definitions.push({
@@ -393,6 +393,7 @@ async function executeCommand(
393
393
  if (failure) {
394
394
  return {
395
395
  allowed: true,
396
+ hookError: failure,
396
397
  additionalContext: `Hook error ${failingLabel(cfg.command, source)}: ${failure}`,
397
398
  }
398
399
  }
@@ -411,6 +412,7 @@ async function executeCommand(
411
412
 
412
413
  return {
413
414
  allowed: true,
415
+ hookError: message,
414
416
  additionalContext: `Hook error ${failingLabel(cfg.command, source)}: ${message}`,
415
417
  }
416
418
  }
package/src/core/hooks.ts CHANGED
@@ -365,8 +365,16 @@ export class HookEngine {
365
365
  try {
366
366
  const hookResult = await hook.handler(ctx)
367
367
 
368
- // Record success
369
- this.recordSuccess(key)
368
+ // Record health. A hook that could not run is a failure even though it
369
+ // returns `allowed: true` and does not throw — the executor reports a
370
+ // missing command, a spawn failure or a rejected option on the result
371
+ // rather than by throwing, so reading only the `catch` left those
372
+ // counted as successes and the auto-disable unreachable.
373
+ if (hookResult.hookError) {
374
+ this.recordFailure(key)
375
+ } else {
376
+ this.recordSuccess(key)
377
+ }
370
378
 
371
379
  // Block on first deny — stops further hook execution
372
380
  if (!hookResult.allowed) {
@@ -220,8 +220,16 @@ export const INSTRUCTION_BUDGET_CHARS = 40_000
220
220
  *
221
221
  * The **total** is the point: no file has to be large for the instruction
222
222
  * payload to crowd out the work, so a per-file check cannot see a dozen
223
- * mid-sized rule files and a lessons block adding up. Naming the largest few
223
+ * mid-sized rule files and a lessons block adding up. The per-file breakdown
224
224
  * is what makes the number actionable.
225
+ *
226
+ * **Every file is listed, largest first.** An earlier version named the top
227
+ * three and folded the rest into `+N more` — but the folded files are exactly
228
+ * the ones a reader has to open to act, and the truncation made the notice
229
+ * unfalsifiable from the outside (a file that appeared only as part of a count
230
+ * could not be checked against the number it contributed). The list is short
231
+ * by construction anyway: instruction discovery yields a handful of files, not
232
+ * hundreds.
225
233
  */
226
234
  export function formatInstructionSizeNotice(
227
235
  report: InstructionSizeReport,
@@ -229,12 +237,13 @@ export function formatInstructionSizeNotice(
229
237
  ): string | null {
230
238
  if (report.totalChars <= budget) return null
231
239
  const num = (n: number) => n.toLocaleString('en-US')
232
- const shown = report.files.slice(0, 3).map((f) => `${f.path} — ${num(f.chars)}`)
233
- if (report.files.length > shown.length) shown.push(`+${report.files.length - shown.length} more`)
240
+ const width = Math.max(...report.files.map((f) => num(f.chars).length))
241
+ const rows = report.files.map((f) => ` ${num(f.chars).padStart(width)} ${f.path}`)
234
242
  return (
235
243
  `⚠ Instruction files total ${num(report.totalChars)} characters (budget ${num(budget)}), ` +
236
244
  `sent with every request.\n` +
237
- ` Largest: ${shown.join(' · ')}\n` +
245
+ ` Largest first:\n` +
246
+ `${rows.join('\n')}\n` +
238
247
  ` Trim them, or move doc-only sections under a \`prompt-exclude\` frontmatter key.`
239
248
  )
240
249
  }
@@ -124,6 +124,22 @@ export function deriveMessages(events: SessionEvent[]): Message[] {
124
124
 
125
125
  const LOG_DIR = miphamHome('sessions')
126
126
 
127
+ /**
128
+ * `open()` 读到「结尾没有换行」的一段,就是撞上了并发写入。
129
+ *
130
+ * 写入方(`save()`)逐行 append,每一行都以 `\n` 收尾 ⇒ 文件末尾那段没有换行的
131
+ * 字节**只可能是还没写完的一行**。按损坏行跳过它,等于把这一条**静默丢掉**,于是
132
+ * 同一个会话在它自己保存的同时被 resume,读回来的对话少一轮。等写入方写完再读一次
133
+ * 即可 —— 它只差一次 `write` 的距离。
134
+ */
135
+ const OPEN_TAIL_RETRIES = 5
136
+ const OPEN_TAIL_RETRY_MS = 20
137
+
138
+ /** 同步睡眠:`open()` 是同步 API,`Atomics.wait` 是 Node 上不借子进程的唯一写法。 */
139
+ function sleepSyncMs(ms: number): void {
140
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
141
+ }
142
+
127
143
  /** 补上的那条结果的正文:说明事情本身,并给出下一步,而不是只报一个状态。 */
128
144
  function interruptedCallNotice(): string {
129
145
  return (
@@ -242,8 +258,22 @@ export class SessionLog {
242
258
  const path = join(LOG_DIR, `${sanitizeSessionName(name)}.jsonl`)
243
259
  // 类型闸在读取之前:`SessionStore.load` 在快照读不出来时**回落到这里**,所以路径上
244
260
  // 是个 FIFO 时不能在这里换个函数继续等 —— 读不动就当空日志(见 shared/regular-file.ts)。
245
- const raw = readRegularFileSync(path)
261
+ let raw = readRegularFileSync(path)
246
262
  if (raw === null) return log
263
+ // 并发 append:写入方每行都以 `\n` 收尾,所以「末尾无换行」= 那一行还在写。
264
+ // 直接把它当损坏行跳过,就是**静默丢一轮对话**(保存中的会话被 resume 时命中)。
265
+ // 等一小会再读,只在这一段上重试。
266
+ // `raw !== ''`:空文件末尾也没有换行,但它没有「半行」可等 —— 不空转一个重试窗口。
267
+ for (
268
+ let attempt = 0;
269
+ attempt < OPEN_TAIL_RETRIES && raw !== '' && !raw.endsWith('\n');
270
+ attempt++
271
+ ) {
272
+ sleepSyncMs(OPEN_TAIL_RETRY_MS)
273
+ const reread = readRegularFileSync(path)
274
+ if (reread === null) break
275
+ raw = reread
276
+ }
247
277
  for (const line of raw.split('\n')) {
248
278
  const trimmed = line.trim()
249
279
  if (!trimmed) continue
@@ -39,6 +39,12 @@ export function createDingtalkApi(
39
39
  const res = await fetchImpl(GATEWAY_URL, {
40
40
  method: 'POST',
41
41
  headers: { 'Content-Type': 'application/json' },
42
+ // A gateway that accepts the connection and then goes quiet would leave
43
+ // this promise pending forever, so the reconnect that follows a failed
44
+ // register would never be scheduled — the channel would go silent with no
45
+ // error to show for it. The ticket expires in 90s, so 10s is already
46
+ // generous for a request whose only job is to hand one back.
47
+ signal: AbortSignal.timeout(10_000),
42
48
  body: JSON.stringify({
43
49
  clientId: config.clientId,
44
50
  clientSecret: config.clientSecret,
@@ -261,12 +261,6 @@
261
261
  "no_restore": "No checkpoint to restore.",
262
262
  "confirmed": "✓ Rewound to checkpoint \"{label}\"\nRestored {count} messages.\n\nRemaining checkpoints: {remaining}\nUse /rewind again to go back further, or continue chatting."
263
263
  },
264
- "fast": {
265
- "on": "✓ Fast mode ON — responses will prioritize speed over depth.",
266
- "off": "✓ Fast mode OFF — standard quality mode.",
267
- "usage": "Usage: /fast [on|off]\nToggle fast mode for faster responses.",
268
- "unknown": "Usage: /fast [on|off]\n\nFast mode prioritizes speed over depth. Currently available as a configuration toggle.\n\nExample:\n /fast on — enable fast mode\n /fast off — disable fast mode"
269
- },
270
264
  "effort": {
271
265
  "usage": "Usage: /effort <level>\n\nSet reasoning effort level:\n low — Fast, simple tasks\n medium — Balanced quality and speed\n high — Thorough reasoning (default)\n xhigh — Maximum depth for coding/agentic use\n max — Absolute ceiling, very thorough\n\nCurrent model: {model}\nEffort levels require compatible providers (Anthropic Opus 4.6+, Sonnet 4.6).",
272
266
  "confirmed": "✓ Reasoning effort set to \"{level}\""
@@ -969,6 +963,7 @@
969
963
  "stop_hook_budget_spent": "The Stop hook asked for more work (\"{reason}\"), but this turn has used all {max} of its tool-calling rounds — stopping here. Send another message to continue.",
970
964
  "mcp_not_connected": "Error: MCP server \"{server}\" not connected",
971
965
  "mcp_tool_error": "MCP tool error: {error}",
966
+ "mcp_auth_required": "MCP server \"{server}\" needs authorization for this tool (the server asked for more OAuth scope). Re-authenticate with: /mcp connect {server}",
972
967
  "mcp_no_connection": "No connection for \"{name}\""
973
968
  },
974
969
  "system": {
@@ -261,12 +261,6 @@
261
261
  "no_restore": "没有可恢复的检查点。",
262
262
  "confirmed": "✓ 已回退到检查点 \"{label}\"\n已恢复 {count} 条消息。\n\n剩余检查点: {remaining}\n再次使用 /rewind 继续回退,或继续对话。"
263
263
  },
264
- "fast": {
265
- "on": "✓ 快速模式已开启 — 回复将优先速度而非深度。",
266
- "off": "✓ 快速模式已关闭 — 标准质量模式。",
267
- "usage": "用法: /fast [on|off]\n切换快速模式以获取更快的回复。",
268
- "unknown": "用法: /fast [on|off]\n\n快速模式优先速度而非深度。当前可作为配置开关使用。\n\n示例:\n /fast on — 启用快速模式\n /fast off — 禁用快速模式"
269
- },
270
264
  "effort": {
271
265
  "usage": "用法: /effort <level>\n\n设置推理深度:\n low — 快速、简单任务\n medium — 质量与速度平衡\n high — 深入推理(默认)\n xhigh — 编码/Agent 最大深度\n max — 绝对上限,非常彻底\n\n当前模型: {model}\n推理深度需要兼容的提供商(Anthropic Opus 4.6+, Sonnet 4.6)。",
272
266
  "confirmed": "✓ 推理深度设置为 \"{level}\""
@@ -969,6 +963,7 @@
969
963
  "stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
970
964
  "mcp_not_connected": "错误:MCP 服务器 \"{server}\" 未连接",
971
965
  "mcp_tool_error": "MCP 工具错误:{error}",
966
+ "mcp_auth_required": "MCP 服务器 \"{server}\" 需要为该工具授权(服务器要求更多 OAuth 作用域)。请重新认证:/mcp connect {server}",
972
967
  "mcp_no_connection": "未找到 \"{name}\" 的连接"
973
968
  },
974
969
  "system": {
package/src/index.tsx CHANGED
@@ -296,18 +296,10 @@ async function connectMcpServers(
296
296
  const mcp = McpClient.getInstance()
297
297
  // Wire runtime tool-list changes before connect so mid-connect updates land.
298
298
  syncMcpToolsOnChange(mcp, tools)
299
- let registeredServers = 0
300
- let registeredTools = 0
301
299
  const results = await Promise.allSettled(
302
300
  mcpServers.map(async (server) => {
303
301
  await mcp.connect(server)
304
- const count = registerMcpServerTools(server.name, tools)
305
- // Same `count > 0` test that used to gate the per-server line, so the total
306
- // counts exactly the servers that would have spoken before.
307
- if (count > 0) {
308
- registeredServers++
309
- registeredTools += count
310
- }
302
+ registerMcpServerTools(server.name, tools)
311
303
  }),
312
304
  )
313
305
  const failures: McpConnectFailure[] = []
@@ -320,12 +312,9 @@ async function connectMcpServers(
320
312
  console.error(`[mcp] Failed to connect "${name}": ${reason}`)
321
313
  }
322
314
  }
323
- // One line for the batch, not one per server: with five configured servers this
324
- // was five lines of scrollback before the TUI ever drew. The quiet path is the
325
- // one with nothing to report — each failure still speaks for itself, above.
326
- if (registeredServers > 0) {
327
- console.log(`[mcp] ${registeredServers} server(s), ${registeredTools} tools registered`)
328
- }
315
+ // No success line before the TUI: with five configured servers this was a line
316
+ // of scrollback before first paint, and it told the user nothing they act on.
317
+ // Failures still speak for themselves, above.
329
318
  return failures
330
319
  }
331
320
 
package/src/mcp/client.ts CHANGED
@@ -7,7 +7,7 @@ import type {
7
7
  InitializeResult,
8
8
  } from './types'
9
9
  import { StdioTransport, type Transport } from './transport'
10
- import { HttpTransport } from './http-transport'
10
+ import { HttpTransport, McpHttpError } from './http-transport'
11
11
  import { McpProtocol } from './protocol'
12
12
  import { OAuthClient } from './oauth'
13
13
  import { TokenStore } from './token-store'
@@ -36,6 +36,21 @@ function connectTimeoutMs(): number {
36
36
  return Number.isFinite(env) && env > 0 ? env : DEFAULT_CONNECT_TIMEOUT_MS
37
37
  }
38
38
 
39
+ /**
40
+ * Render a connect failure for the user, adding the one hint a bare error
41
+ * cannot carry: that the fix is to authenticate.
42
+ *
43
+ * Without this a rejected handshake surfaced as `MCP HTTP error 401: {…}` — the
44
+ * user saw a credential problem and no way to act on it.
45
+ */
46
+ function describeMcpError(err: unknown, serverName: string): string {
47
+ const base = err instanceof Error ? err.message : String(err)
48
+ if (err instanceof McpHttpError && err.needsAuth) {
49
+ return `${base} — the server rejected these credentials. Re-authenticate with: /mcp connect ${serverName}`
50
+ }
51
+ return base
52
+ }
53
+
39
54
  // A server may emit `notifications/tools/list_changed` once per tool it adds, or
40
55
  // in a tight loop. Each notification used to trigger its own `tools/list` round
41
56
  // trip plus a full downstream re-registration, so a burst produced sustained CPU
@@ -123,13 +138,19 @@ export class McpClient {
123
138
  for (const h of list) h(...args)
124
139
  }
125
140
 
126
- /** Connect with OAuth PKCE flow — injects access token into env vars. */
127
- async connectWithOAuth(config: McpServerConfig): Promise<void> {
141
+ /**
142
+ * Obtain the credentials a server's config calls for, as transport env.
143
+ *
144
+ * An OAuth-configured server is rejected by its own handshake without a live
145
+ * token, so this runs *before* the transport starts — and on every connect
146
+ * path, not just a forced one. The result is keyed `MCP_ACCESS_TOKEN`, which
147
+ * `HttpTransport` turns into a Bearer header and `StdioTransport` passes to
148
+ * the child process.
149
+ */
150
+ private async envWithAuth(config: McpServerConfig): Promise<Record<string, string> | undefined> {
151
+ if (config.auth?.type !== 'oauth') return config.env
128
152
  const accessToken = await this.oauthClient.getValidAccessToken(config.name, config)
129
- return this.connect({
130
- ...config,
131
- env: { ...config.env, MCP_ACCESS_TOKEN: accessToken },
132
- })
153
+ return { ...config.env, MCP_ACCESS_TOKEN: accessToken }
133
154
  }
134
155
 
135
156
  /**
@@ -275,6 +296,30 @@ export class McpClient {
275
296
  McpClient.instance = null
276
297
  }
277
298
 
299
+ /**
300
+ * Run the OAuth flow again and connect with the fresh token.
301
+ *
302
+ * `/mcp connect <name>` on a server that is already connected *is* this
303
+ * request: the only reason to ask again is that the current credentials no
304
+ * longer do (a tool call came back "insufficient scope"). Reusing the stored
305
+ * token — or letting `connect()` early-return on the live connection — would
306
+ * send the same refused token a second time.
307
+ */
308
+ async reauthenticate(config: McpServerConfig): Promise<void> {
309
+ this.oauthClient.forget(config.name)
310
+ const existing = this.connections.get(config.name)
311
+ if (existing) {
312
+ this.cancelToolsRefresh(existing)
313
+ try {
314
+ await existing.transport.close()
315
+ } catch {
316
+ /* best effort */
317
+ }
318
+ this.connections.delete(config.name)
319
+ }
320
+ await this.connect(config)
321
+ }
322
+
278
323
  async connect(config: McpServerConfig): Promise<void> {
279
324
  // Skip if already connected
280
325
  const existing = this.connections.get(config.name)
@@ -311,12 +356,16 @@ export class McpClient {
311
356
  this.connections.set(config.name, connection)
312
357
 
313
358
  try {
359
+ // Resolve credentials before the transport starts: the handshake itself
360
+ // is what an unauthenticated request gets rejected on.
361
+ const env = await this.envWithAuth(config)
362
+
314
363
  await this.withConnectTimeout(config.name, async () => {
315
364
  // Start the transport (transport-specific), then perform the handshake.
316
365
  if (transport instanceof HttpTransport) {
317
- await transport.start(config.url ?? '', config.headers, config.env)
366
+ await transport.start(config.url ?? '', config.headers, env)
318
367
  } else {
319
- await transport.start(config.command ?? '', config.args ?? [], config.env)
368
+ await transport.start(config.command ?? '', config.args ?? [], env)
320
369
  }
321
370
  const initResult: InitializeResult = await protocol.initialize()
322
371
 
@@ -336,7 +385,7 @@ export class McpClient {
336
385
  })
337
386
  } catch (err) {
338
387
  connection.status = 'error'
339
- connection.error = String(err)
388
+ connection.error = describeMcpError(err, config.name)
340
389
  try {
341
390
  await transport.close()
342
391
  } catch {
@@ -495,6 +544,14 @@ export class McpClient {
495
544
  return await conn.protocol.callTool(toolName, params)
496
545
  } catch (err) {
497
546
  this.markIfTransportLost(serverName, conn)
547
+ // A scope refusal is actionable and nothing else is: the user has to go
548
+ // through the OAuth flow again, and only the server can say so.
549
+ if (err instanceof McpHttpError && err.needsAuth) {
550
+ return {
551
+ content: [{ type: 'text', text: t('errors.mcp_auth_required', { server: serverName }) }],
552
+ isError: true,
553
+ }
554
+ }
498
555
  return {
499
556
  content: [{ type: 'text', text: t('errors.mcp_tool_error', { error: String(err) }) }],
500
557
  isError: true,