@miphamai/cli 0.85.15 → 0.85.17
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/message-router.ts +20 -1
- package/src/agent/sub-agent.ts +20 -1
- package/src/core/engine.ts +60 -19
- package/src/core/hooks-config.ts +20 -1
- package/src/core/session-log.ts +31 -1
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/index.tsx +4 -15
- package/src/mcp/client.ts +67 -10
- package/src/mcp/http-transport.ts +48 -4
- package/src/mcp/oauth.ts +9 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +40 -0
- package/src/tools/agent/agent.ts +10 -1
- package/src/tools/agent/send-message.ts +23 -6
- package/src/tools/exec/bash.ts +18 -9
- package/src/ui/chat.tsx +18 -5
- package/src/ui/commands.ts +134 -30
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.17
|
|
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
|
@@ -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 {
|
|
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
|
}
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
package/src/core/engine.ts
CHANGED
|
@@ -704,25 +704,34 @@ export class QueryEngine {
|
|
|
704
704
|
turnApiInputTokens += chunk.inputTokens
|
|
705
705
|
turnApiOutputTokens += chunk.outputTokens || 0
|
|
706
706
|
}
|
|
707
|
+
}
|
|
707
708
|
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
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)
|
|
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:
|
|
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 {
|
package/src/core/hooks-config.ts
CHANGED
|
@@ -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
|
-
|
|
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({
|
package/src/core/session-log.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
@@ -963,6 +963,7 @@
|
|
|
963
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.",
|
|
964
964
|
"mcp_not_connected": "Error: MCP server \"{server}\" not connected",
|
|
965
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}",
|
|
966
967
|
"mcp_no_connection": "No connection for \"{name}\""
|
|
967
968
|
},
|
|
968
969
|
"system": {
|
|
@@ -963,6 +963,7 @@
|
|
|
963
963
|
"stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
|
|
964
964
|
"mcp_not_connected": "错误:MCP 服务器 \"{server}\" 未连接",
|
|
965
965
|
"mcp_tool_error": "MCP 工具错误:{error}",
|
|
966
|
+
"mcp_auth_required": "MCP 服务器 \"{server}\" 需要为该工具授权(服务器要求更多 OAuth 作用域)。请重新认证:/mcp connect {server}",
|
|
966
967
|
"mcp_no_connection": "未找到 \"{name}\" 的连接"
|
|
967
968
|
},
|
|
968
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
|
-
|
|
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
|
-
//
|
|
324
|
-
//
|
|
325
|
-
//
|
|
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
|
-
/**
|
|
127
|
-
|
|
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
|
|
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,
|
|
366
|
+
await transport.start(config.url ?? '', config.headers, env)
|
|
318
367
|
} else {
|
|
319
|
-
await transport.start(config.command ?? '', config.args ?? [],
|
|
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 =
|
|
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,
|
|
@@ -4,6 +4,41 @@ import { DEFAULT_REQUEST_TIMEOUT_MS, requestTimeoutError } from './transport'
|
|
|
4
4
|
|
|
5
5
|
type FetchFn = (input: string, init?: RequestInit) => Promise<Response>
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* A non-2xx HTTP answer from an MCP server.
|
|
9
|
+
*
|
|
10
|
+
* Carries `needsAuth` — the server said our credentials are missing or too
|
|
11
|
+
* narrow. Callers turn that into "re-authenticate", which a bare status code
|
|
12
|
+
* cannot express: `403` also means "this tool is forbidden to you", and telling
|
|
13
|
+
* the user to re-authenticate then sends them round a loop that cannot help.
|
|
14
|
+
* The signal is the `WWW-Authenticate` challenge the server attaches
|
|
15
|
+
* (RFC 6750/9728), which the transport used to discard.
|
|
16
|
+
*/
|
|
17
|
+
export class McpHttpError extends Error {
|
|
18
|
+
constructor(
|
|
19
|
+
readonly status: number,
|
|
20
|
+
detail: string,
|
|
21
|
+
readonly needsAuth: boolean,
|
|
22
|
+
) {
|
|
23
|
+
super(`MCP HTTP error ${status}: ${detail}`)
|
|
24
|
+
this.name = 'McpHttpError'
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Does this challenge say the token we sent was missing or insufficient?
|
|
30
|
+
*
|
|
31
|
+
* `insufficient_scope` is the RFC 6750 code for "authenticated, but not for
|
|
32
|
+
* this"; a bare `Bearer` on a 401 means no usable token at all. A 403 whose
|
|
33
|
+
* challenge carries neither is a flat refusal and gets no auth hint.
|
|
34
|
+
*/
|
|
35
|
+
export function challengeNeedsAuth(status: number, challenge: string): boolean {
|
|
36
|
+
if (!challenge) return false
|
|
37
|
+
if (status === 401) return /^bearer\b/i.test(challenge.trim())
|
|
38
|
+
if (status === 403) return /insufficient_scope/i.test(challenge)
|
|
39
|
+
return false
|
|
40
|
+
}
|
|
41
|
+
|
|
7
42
|
/**
|
|
8
43
|
* Merge multiple SSE `data:` events into a single JSON-RPC result.
|
|
9
44
|
*
|
|
@@ -99,10 +134,14 @@ export class HttpTransport implements Transport {
|
|
|
99
134
|
this.closed = false
|
|
100
135
|
|
|
101
136
|
// Build base headers: explicit headers override, then auto-derive a
|
|
102
|
-
// Bearer token from
|
|
103
|
-
//
|
|
137
|
+
// Bearer token from the env so the secret stays out of the config file.
|
|
138
|
+
// MCP_ACCESS_TOKEN is what the OAuth flow produces (McpClient.connectOnce);
|
|
139
|
+
// FORGE_API_KEY mirrors Forge's verify_api_key for a static deployment.
|
|
140
|
+
// Before this, an OAuth-configured server got its token minted and dropped
|
|
141
|
+
// into env where nothing read it: the request went out unauthenticated.
|
|
142
|
+
const bearer = env?.MCP_ACCESS_TOKEN ?? env?.FORGE_API_KEY
|
|
104
143
|
this.headers = {
|
|
105
|
-
...(
|
|
144
|
+
...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),
|
|
106
145
|
...(headers ?? {}),
|
|
107
146
|
}
|
|
108
147
|
}
|
|
@@ -148,7 +187,12 @@ export class HttpTransport implements Transport {
|
|
|
148
187
|
} catch {
|
|
149
188
|
/* keep status-only detail */
|
|
150
189
|
}
|
|
151
|
-
|
|
190
|
+
// The challenge is the server telling us *how* to authenticate. Keep it
|
|
191
|
+
// — dropping it leaves "403 {…}" as the only clue the user gets.
|
|
192
|
+
const challenge = response.headers.get('www-authenticate') ?? ''
|
|
193
|
+
const needsAuth = challengeNeedsAuth(response.status, challenge)
|
|
194
|
+
if (challenge) detail += ` (WWW-Authenticate: ${challenge})`
|
|
195
|
+
throw new McpHttpError(response.status, detail, needsAuth)
|
|
152
196
|
}
|
|
153
197
|
|
|
154
198
|
const contentType = response.headers.get('content-type') || ''
|
package/src/mcp/oauth.ts
CHANGED
|
@@ -184,6 +184,15 @@ export class OAuthClient {
|
|
|
184
184
|
return saved.boundTo === credentialBinding(config) ? saved : null
|
|
185
185
|
}
|
|
186
186
|
|
|
187
|
+
/**
|
|
188
|
+
* Discard the stored credentials so the next token request runs the PKCE flow
|
|
189
|
+
* again. Called when the server has said the current token is not enough:
|
|
190
|
+
* keeping it would answer every retry with the same refused token.
|
|
191
|
+
*/
|
|
192
|
+
forget(serverName: string): void {
|
|
193
|
+
this.store.delete(serverName)
|
|
194
|
+
}
|
|
195
|
+
|
|
187
196
|
async getValidAccessToken(serverName: string, config: McpServerConfig): Promise<string> {
|
|
188
197
|
const saved = this.loadBoundToken(serverName, config)
|
|
189
198
|
if (saved && new Date(saved.expiresAt).getTime() > Date.now() + 60000) {
|
|
@@ -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.17' 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 = 4020 as const
|
package/src/shared/sanitize.ts
CHANGED
|
@@ -246,6 +246,46 @@ export function sanitizeInlineField(input: string): string {
|
|
|
246
246
|
return stripDangerousUnicode(input).replace(/[\x00-\x1f\x7f]/g, '')
|
|
247
247
|
}
|
|
248
248
|
|
|
249
|
+
/**
|
|
250
|
+
* Control-character stripping for **multi-line** display text — tool output, tool
|
|
251
|
+
* arguments, model prose.
|
|
252
|
+
*
|
|
253
|
+
* `sanitizeInlineField` covers one-line values, but it drops `\n` with everything
|
|
254
|
+
* else: right for a name in a listing, wrong for a command's output, which is
|
|
255
|
+
* legitimately multi-line. This is the same recipe minus that one character.
|
|
256
|
+
*
|
|
257
|
+
* `\n` is what stays — a line break, whose width is measured line by line. `\t` does
|
|
258
|
+
* **not** stay: Ink lays text out with `string-width`, which scores a tab as **0
|
|
259
|
+
* columns**, then writes the tab through to the frame, while the terminal advances a
|
|
260
|
+
* tab to the next tab stop (up to +8 columns). The row ends up wider than the width
|
|
261
|
+
* Ink budgeted and draws over the row below. That a tab cannot move the cursor
|
|
262
|
+
* *backwards* or open an escape sequence is the wrong test — its danger is advancing
|
|
263
|
+
* *unknowingly*. So `\t` → a single space, the same move `stripControlCharsForCheck`
|
|
264
|
+
* makes, so words do not merge. Everything else goes, ESC and DEL included, so a file
|
|
265
|
+
* name or a `printf` payload cannot reach the terminal as CR (overwrite the line —
|
|
266
|
+
* `printf 'safe.txt\rrm -rf /'` shows the second half), BEL, or a CSI/OSC
|
|
267
|
+
* introducer. C1 (U+0080–U+009F) goes with them: its 8-bit CSI is the same
|
|
268
|
+
* introducer in a different encoding.
|
|
269
|
+
*
|
|
270
|
+
* Ink is not a substitute for this. Measured on ink 7.1.1 (`renderToString`): it
|
|
271
|
+
* drops a bare CSI sequence like `\x1b[2J`, but passes CR, BS, BEL, VT, FF, DEL and
|
|
272
|
+
* NUL straight through — and it *parses* SGR, re-emitting `\x1b[8m` (conceal) as
|
|
273
|
+
* `\x1b[28m`. So the sequences that matter here survive it.
|
|
274
|
+
*
|
|
275
|
+
* The cost is real and accepted: colour escapes in tool output (`ls --color`) are
|
|
276
|
+
* dropped, so that text renders uncoloured rather than as invisible markup. Display
|
|
277
|
+
* integrity — that what is shown is what was produced — outranks it.
|
|
278
|
+
*/
|
|
279
|
+
export function stripControlCharsForDisplay(input: string): string {
|
|
280
|
+
if (!input) return input
|
|
281
|
+
return (
|
|
282
|
+
stripDangerousUnicode(input)
|
|
283
|
+
// `\t` first (→ space), so it cannot reach the terminal as a tab stop jump.
|
|
284
|
+
.replace(/\t/g, ' ')
|
|
285
|
+
.replace(/[\x00-\x08\x0b-\x1f\x7f\x80-\x9f]/g, '')
|
|
286
|
+
)
|
|
287
|
+
}
|
|
288
|
+
|
|
249
289
|
/**
|
|
250
290
|
* Full command sanitization pipeline for permission checks.
|
|
251
291
|
* Applies in order:
|
package/src/tools/agent/agent.ts
CHANGED
|
@@ -40,7 +40,16 @@ export const agentTool: ToolDefinition = {
|
|
|
40
40
|
'retrievable via the Task tool (output action) or Agent View. ' +
|
|
41
41
|
'Set run_in_background: false to run synchronously.',
|
|
42
42
|
category: 'agent',
|
|
43
|
-
|
|
43
|
+
// Dispatch is not a separately-gated act. The child is built with the caller's
|
|
44
|
+
// own `permissionSystem` (below: `new SubAgent(..., ctx.permissionSystem, ...)`)
|
|
45
|
+
// and re-runs the same gate on every tool call it makes (`sub-agent.ts`
|
|
46
|
+
// `permission: subPermission`), so `'ask'` here was a **duplicate** gate — and
|
|
47
|
+
// this CLI has no interactive approval prompt, which makes `ask` a hard refusal.
|
|
48
|
+
// The observable result was that `default` (manual) mode could not dispatch a
|
|
49
|
+
// single agent: the advertised fan-out had no landing point on the branch
|
|
50
|
+
// production runs. `'self'` matches `Git` / `Task` / `SendMessage`: the spawn is
|
|
51
|
+
// free, and the child still cannot do anything the caller could not.
|
|
52
|
+
permission: 'self',
|
|
44
53
|
parameters: {
|
|
45
54
|
type: 'object',
|
|
46
55
|
properties: {
|
|
@@ -61,14 +61,31 @@ export const sendMessageTool: ToolDefinition = {
|
|
|
61
61
|
|
|
62
62
|
const routedLabel = result.routedTo === 'bus' ? 'in-process' : 'cross-session'
|
|
63
63
|
|
|
64
|
+
const body =
|
|
65
|
+
`ID: ${result.messageId}\n` +
|
|
66
|
+
`From: ${from}\n` +
|
|
67
|
+
`To: ${to}\n` +
|
|
68
|
+
`Summary: ${truncatedSummary.slice(0, 100)}`
|
|
69
|
+
|
|
70
|
+
// A cross-session message written to the inbox of a session that holds
|
|
71
|
+
// inbound messages has NOT been delivered — that session's user decides
|
|
72
|
+
// first, and may decline. Reporting "Sent" there tells the sender to expect
|
|
73
|
+
// a reply to a message that was never read. Name the session holding it.
|
|
74
|
+
if (result.routedTo === 'inbox' && result.held) {
|
|
75
|
+
const who = result.targetName ?? to
|
|
76
|
+
return {
|
|
77
|
+
success: true,
|
|
78
|
+
content:
|
|
79
|
+
`── Message Queued (${routedLabel}) ──\n\n` +
|
|
80
|
+
`Not yet delivered: "${who}" holds inbound messages for approval. ` +
|
|
81
|
+
`It will see this only if it accepts.\n\n` +
|
|
82
|
+
body,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
64
86
|
return {
|
|
65
87
|
success: true,
|
|
66
|
-
content:
|
|
67
|
-
`── Message Sent (${routedLabel}) ──\n\n` +
|
|
68
|
-
`ID: ${result.messageId}\n` +
|
|
69
|
-
`From: ${from}\n` +
|
|
70
|
-
`To: ${to}\n` +
|
|
71
|
-
`Summary: ${truncatedSummary.slice(0, 100)}`,
|
|
88
|
+
content: `── Message Sent (${routedLabel}) ──\n\n${body}`,
|
|
72
89
|
}
|
|
73
90
|
},
|
|
74
91
|
}
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -17,16 +17,21 @@ import { withValidation } from '../validation'
|
|
|
17
17
|
// `rm -rf /* > log`, `rm -rf /* foo` and `rm -rf /*; echo x` — the same
|
|
18
18
|
// deletion — were not.
|
|
19
19
|
const BLOCKED_PATTERNS = [
|
|
20
|
-
// Recursive root deletion without preserve-root safeguard
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
// Recursive root deletion without preserve-root safeguard.
|
|
21
|
+
// The operand may be quoted: `rm -rf '/'` reaches the same path as `rm -rf /`, so
|
|
22
|
+
// the quote belongs to the *delimiter* class, not to the path — `['"]?` opens the
|
|
23
|
+
// operand and the lookahead accepts the closing quote.
|
|
24
|
+
/\brm\s+-rf\s+['"]?\/(?=["'\s]|$)/,
|
|
25
|
+
/\brm\s+-rf\s+['"]?\/\*(?=["'\s;&|>]|$)/,
|
|
23
26
|
/\bsudo\s+rm\s+.*\//,
|
|
24
27
|
// rm -rf on home directory or any absolute path (relative dirs like node_modules stay allowed)
|
|
25
|
-
/\brm\s+-(?:rf|fr)\s
|
|
26
|
-
/\brm\s+-(?:rf|fr)\s
|
|
28
|
+
/\brm\s+-(?:rf|fr)\s+['"]?~(?:["'\s\/]|$)/,
|
|
29
|
+
/\brm\s+-(?:rf|fr)\s+['"]?\/(?![\s*])/,
|
|
27
30
|
// rm -rf on dangerous cwd globs
|
|
28
|
-
/\brm\s+-(?:rf|fr)\s
|
|
29
|
-
|
|
31
|
+
/\brm\s+-(?:rf|fr)\s+['"]?\*(?=["'\s;&|>]|$)/,
|
|
32
|
+
// `rm -rf .` and its path spellings `./` and `../` delete the working directory;
|
|
33
|
+
// `./build` and `../vendor` name an entry inside it and stay allowed.
|
|
34
|
+
/\brm\s+-(?:rf|fr)\s+['"]?\.\.?(?:\/)?(?=["'\s;&|>]|$)/,
|
|
30
35
|
// Filesystem manipulation
|
|
31
36
|
/\bmkfs\./,
|
|
32
37
|
/\bdd\s+if=/,
|
|
@@ -68,8 +73,12 @@ const BLOCKED_PATTERNS = [
|
|
|
68
73
|
/>\s*\/(?:etc|usr|boot|sys|proc)\//,
|
|
69
74
|
// P0 hardening — ANSI-C quoting bypass (e.g. $'\x72\x6d' = rm)
|
|
70
75
|
/\$'\\x[0-9a-fA-F]{2}/,
|
|
71
|
-
// P0 hardening — nested interpreter invocation
|
|
72
|
-
|
|
76
|
+
// P0 hardening — nested interpreter invocation.
|
|
77
|
+
// The interpreter word may be separated from `-c` by any run of options, and `-c`
|
|
78
|
+
// may sit inside a cluster (`-lc`, `-ec`) — `bash -lc 'rm -rf /'` runs the same
|
|
79
|
+
// command as `bash -c 'rm -rf /'`. `ash`, `fish`, `csh` and `tcsh` are added
|
|
80
|
+
// because the payload only has to be a POSIX-ish shell, not bash.
|
|
81
|
+
/\b(?:bash|sh|zsh|dash|ksh|ash|fish|csh|tcsh)\b(?:\s+-{1,2}[\w=.-]+)*\s+-[A-Za-z]*c[A-Za-z]*\b/,
|
|
73
82
|
// P0 hardening — eval builtin (obfuscation vector)
|
|
74
83
|
/\beval\s+/,
|
|
75
84
|
// P0 hardening — exec redirect bypass (e.g. exec >/dev/sda)
|
package/src/ui/chat.tsx
CHANGED
|
@@ -2,7 +2,7 @@ import React, { useMemo } from 'react'
|
|
|
2
2
|
import { Box, Text } from 'ink'
|
|
3
3
|
import { useI18n } from '../i18n-context'
|
|
4
4
|
import type { ChatMessage } from './app'
|
|
5
|
-
import { decodeDisplayEntities } from '../shared/sanitize'
|
|
5
|
+
import { decodeDisplayEntities, stripControlCharsForDisplay } from '../shared/sanitize'
|
|
6
6
|
import { homedir } from 'node:os'
|
|
7
7
|
|
|
8
8
|
interface ChatPanelProps {
|
|
@@ -10,6 +10,19 @@ interface ChatPanelProps {
|
|
|
10
10
|
focusMode?: boolean
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* The single point where untrusted text becomes terminal output.
|
|
15
|
+
*
|
|
16
|
+
* Everything this component prints that did not come from a literal in the file —
|
|
17
|
+
* tool arguments, tool output, model prose — passes through here. Control
|
|
18
|
+
* characters in those strings are not visible content; they are terminal
|
|
19
|
+
* instructions (CR overwrites the row, ESC starts a sequence), so they are removed
|
|
20
|
+
* rather than shown. See `stripControlCharsForDisplay` for what is kept and why.
|
|
21
|
+
*/
|
|
22
|
+
function display(text: string): string {
|
|
23
|
+
return stripControlCharsForDisplay(text)
|
|
24
|
+
}
|
|
25
|
+
|
|
13
26
|
/** Format cwd for display: replace HOME with ~, truncate if too long */
|
|
14
27
|
function displayCwd(): string {
|
|
15
28
|
const cwd = process.cwd()
|
|
@@ -66,17 +79,17 @@ const MessageRow = React.memo(
|
|
|
66
79
|
{msg.toolMeta.name ? (
|
|
67
80
|
<Text color={toolColor(msg.toolMeta.name)}>
|
|
68
81
|
{msg.toolMeta.collapsed ? '⏺' : '⏺ ▼'} {msg.toolMeta.name}
|
|
69
|
-
{msg.toolMeta.input ? ` (${msg.toolMeta.input.slice(0, 120)})` : ''}
|
|
82
|
+
{msg.toolMeta.input ? ` (${display(msg.toolMeta.input).slice(0, 120)})` : ''}
|
|
70
83
|
</Text>
|
|
71
84
|
) : null}
|
|
72
85
|
{/* Tool result line: ⎿ summary text */}
|
|
73
86
|
{msg.toolMeta.output ? (
|
|
74
87
|
<Text dimColor>
|
|
75
88
|
{' ⎿ '}
|
|
76
|
-
{msg.toolMeta.output.slice(0, 300)}
|
|
89
|
+
{display(msg.toolMeta.output).slice(0, 300)}
|
|
77
90
|
</Text>
|
|
78
91
|
) : msg.content && !msg.toolMeta.collapsed ? (
|
|
79
|
-
<Text dimColor>{msg.content}</Text>
|
|
92
|
+
<Text dimColor>{display(msg.content)}</Text>
|
|
80
93
|
) : null}
|
|
81
94
|
</Box>
|
|
82
95
|
) : (
|
|
@@ -94,7 +107,7 @@ const MessageRow = React.memo(
|
|
|
94
107
|
⚠ {t('ui.system.role_label')}:
|
|
95
108
|
</Text>
|
|
96
109
|
) : null}
|
|
97
|
-
<Text>{
|
|
110
|
+
<Text>{display(decodeDisplayEntities(msg.content))}</Text>
|
|
98
111
|
</>
|
|
99
112
|
)}
|
|
100
113
|
</Box>
|
package/src/ui/commands.ts
CHANGED
|
@@ -14,7 +14,7 @@ import type { PluginManager } from '../plugin/plugin-manager'
|
|
|
14
14
|
import type { Message } from '../shared/types.js'
|
|
15
15
|
import type { InstallState, UpdateStatus } from '../shared/update'
|
|
16
16
|
import { McpClient } from '../mcp/client'
|
|
17
|
-
import { unregisterMcpServerTools } from '../mcp/registry'
|
|
17
|
+
import { registerMcpServerTools, unregisterMcpServerTools } from '../mcp/registry'
|
|
18
18
|
import { buildCapabilityReport } from '../core/capability-inventory'
|
|
19
19
|
import { InstructionsLoader } from '../core/instructions'
|
|
20
20
|
import { findDerivableSections, DERIVABLE_HINTS } from '../core/claude-md-audit'
|
|
@@ -70,7 +70,7 @@ import {
|
|
|
70
70
|
shouldBlockApproval,
|
|
71
71
|
} from '../core/improvement-track'
|
|
72
72
|
import { NPM_UPDATE_COMMAND, PACKAGE_VERSION, COAUTHOR_TRAILER } from '../shared/index.ts'
|
|
73
|
-
import { getPreference } from '../config/preferences'
|
|
73
|
+
import { getPreference, setPreference } from '../config/preferences'
|
|
74
74
|
import { loadCrossSessionConfig, tryRestoreFromBackup } from '../config/loader'
|
|
75
75
|
import { getWorkspaceTrust } from '../core/workspace-trust'
|
|
76
76
|
import { getMemoryManager } from '../core/memory/memory-loader'
|
|
@@ -3669,9 +3669,13 @@ function gitDiffBridgeCmd(opts: {
|
|
|
3669
3669
|
noChangesKey: string
|
|
3670
3670
|
runningKey: string
|
|
3671
3671
|
errorKey: string
|
|
3672
|
-
|
|
3672
|
+
/** Either a fixed prompt, or a builder that reads the command args. A builder
|
|
3673
|
+
* may return an `{ error }` envelope instead — used when the args are
|
|
3674
|
+
* unusable, so the command reports that rather than forwarding a prompt the
|
|
3675
|
+
* user's flag never reached. */
|
|
3676
|
+
forwardToAI: string | ((args: string[]) => string | { error: string })
|
|
3673
3677
|
}): CommandHandler {
|
|
3674
|
-
return async (ctx) => {
|
|
3678
|
+
return async (ctx, args) => {
|
|
3675
3679
|
const t = resolveT(ctx)
|
|
3676
3680
|
try {
|
|
3677
3681
|
const { execSync } = await import('node:child_process')
|
|
@@ -3679,9 +3683,14 @@ function gitDiffBridgeCmd(opts: {
|
|
|
3679
3683
|
if (!diff) {
|
|
3680
3684
|
return { content: `─ ${opts.label} ─\n\n${t(opts.noChangesKey)}` }
|
|
3681
3685
|
}
|
|
3686
|
+
const forwarded =
|
|
3687
|
+
typeof opts.forwardToAI === 'function' ? opts.forwardToAI(args) : opts.forwardToAI
|
|
3688
|
+
if (typeof forwarded === 'object') {
|
|
3689
|
+
return { content: `─ ${opts.label} ─\n\n${forwarded.error}` }
|
|
3690
|
+
}
|
|
3682
3691
|
return {
|
|
3683
3692
|
content: `─ ${opts.label} ─\n\n${t(opts.runningKey)}\n\nChanged files:\n${diff}`,
|
|
3684
|
-
forwardToAI:
|
|
3693
|
+
forwardToAI: forwarded,
|
|
3685
3694
|
}
|
|
3686
3695
|
} catch {
|
|
3687
3696
|
return { content: `─ ${opts.label} ─\n\n${t(opts.errorKey)}` }
|
|
@@ -3689,13 +3698,60 @@ function gitDiffBridgeCmd(opts: {
|
|
|
3689
3698
|
}
|
|
3690
3699
|
}
|
|
3691
3700
|
|
|
3701
|
+
/**
|
|
3702
|
+
* `/code-review --max-findings <n>|all|default` — how many findings to report.
|
|
3703
|
+
*
|
|
3704
|
+
* The choice is persisted like the effort level and reused by the next
|
|
3705
|
+
* `/code-review` until `--max-findings default` restores the usual limit.
|
|
3706
|
+
* `all` means "no cap"; a positive integer caps the count. An unusable value is
|
|
3707
|
+
* reported back rather than ignored: silently dropping it would leave the user
|
|
3708
|
+
* believing the cap took effect when it never left the command line.
|
|
3709
|
+
*/
|
|
3710
|
+
function resolveMaxFindings(
|
|
3711
|
+
args: string[],
|
|
3712
|
+
): { ok: true; value: string } | { ok: false; error: string } {
|
|
3713
|
+
let token: string | undefined
|
|
3714
|
+
for (let i = 0; i < args.length; i++) {
|
|
3715
|
+
const a = args[i]!
|
|
3716
|
+
if (a === '--max-findings') {
|
|
3717
|
+
token = args[i + 1]
|
|
3718
|
+
break
|
|
3719
|
+
}
|
|
3720
|
+
if (a.startsWith('--max-findings=')) {
|
|
3721
|
+
token = a.slice('--max-findings='.length)
|
|
3722
|
+
break
|
|
3723
|
+
}
|
|
3724
|
+
}
|
|
3725
|
+
if (token === undefined) {
|
|
3726
|
+
// No flag this time — reuse whatever was chosen last.
|
|
3727
|
+
return { ok: true, value: getPreference('lastCodeReviewMaxFindings', 'default') }
|
|
3728
|
+
}
|
|
3729
|
+
if (token === 'all' || token === 'default' || /^[1-9]\d*$/.test(token)) {
|
|
3730
|
+
setPreference('lastCodeReviewMaxFindings', token)
|
|
3731
|
+
return { ok: true, value: token }
|
|
3732
|
+
}
|
|
3733
|
+
return {
|
|
3734
|
+
ok: false,
|
|
3735
|
+
error: `--max-findings expects a positive integer, "all", or "default" (got "${token}")`,
|
|
3736
|
+
}
|
|
3737
|
+
}
|
|
3738
|
+
|
|
3692
3739
|
const codeReviewCmd = gitDiffBridgeCmd({
|
|
3693
3740
|
label: 'Code Review',
|
|
3694
3741
|
noChangesKey: 'commands.code_review.no_changes',
|
|
3695
3742
|
runningKey: 'commands.code_review.running',
|
|
3696
3743
|
errorKey: 'commands.code_review.error',
|
|
3697
|
-
forwardToAI: () =>
|
|
3698
|
-
|
|
3744
|
+
forwardToAI: (args) => {
|
|
3745
|
+
const maxFindings = resolveMaxFindings(args)
|
|
3746
|
+
if (!maxFindings.ok) return { error: maxFindings.error }
|
|
3747
|
+
const cap =
|
|
3748
|
+
maxFindings.value === 'all'
|
|
3749
|
+
? ' Report every finding, however many there are.'
|
|
3750
|
+
: maxFindings.value === 'default'
|
|
3751
|
+
? ''
|
|
3752
|
+
: ` Report at most ${maxFindings.value} findings, most severe first.`
|
|
3753
|
+
return `use the code-review skill to review all uncommitted changes. Check all 7 dimensions: correctness, security, performance, code quality, architecture & design, testing, and language-specific issues. Use effort level: ${getPreference('lastCodeReviewEffort', 'high')}.${cap}`
|
|
3754
|
+
},
|
|
3699
3755
|
})
|
|
3700
3756
|
|
|
3701
3757
|
const simplifyCmd = gitDiffBridgeCmd({
|
|
@@ -4934,31 +4990,53 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
|
|
|
4934
4990
|
content: `Server "${sanitizeInlineField(name)}" not found in config.\n\nConfigured: ${mcpServers.map((s) => sanitizeInlineField(s.name)).join(', ') || '(none)'}`,
|
|
4935
4991
|
}
|
|
4936
4992
|
}
|
|
4937
|
-
|
|
4993
|
+
const isOAuth = config.auth?.type === 'oauth'
|
|
4994
|
+
const label = isOAuth ? `${name} (OAuth)` : name
|
|
4995
|
+
try {
|
|
4996
|
+
// Connect here rather than handing the AI a prompt to "call
|
|
4997
|
+
// McpClient.getInstance().connect(config)". No tool exposes that call, so
|
|
4998
|
+
// the prompt was unactionable and the command connected nothing — it just
|
|
4999
|
+
// printed a status line. `/mcp reconnect` already awaits in the handler;
|
|
5000
|
+
// this is the same shape.
|
|
5001
|
+
//
|
|
5002
|
+
// An already-connected OAuth server is the re-authenticate case: the only
|
|
5003
|
+
// reason to ask again is that the current token was refused.
|
|
5004
|
+
if (isOAuth && client.getConnection(name)?.status === 'connected') {
|
|
5005
|
+
await client.reauthenticate(config)
|
|
5006
|
+
} else {
|
|
5007
|
+
await client.connect(config)
|
|
5008
|
+
}
|
|
5009
|
+
const registered = registerMcpServerTools(name, ctx.engine.getTools())
|
|
5010
|
+
const lines = [`── MCP Connect: ${sanitizeInlineField(label)} ──`, '']
|
|
5011
|
+
lines.push(
|
|
5012
|
+
isOAuth
|
|
5013
|
+
? 'Authenticated via OAuth PKCE.'
|
|
5014
|
+
: `Connected via ${config.url ? 'HTTP' : 'stdio'}.`,
|
|
5015
|
+
)
|
|
5016
|
+
lines.push(
|
|
5017
|
+
registered > 0 ? `${registered} tool(s) registered.` : 'No tools reported by the server.',
|
|
5018
|
+
)
|
|
5019
|
+
if (config.url) {
|
|
5020
|
+
const headerKeys = config.headers ? Object.keys(config.headers) : []
|
|
5021
|
+
if (headerKeys.length > 0) {
|
|
5022
|
+
lines.push('')
|
|
5023
|
+
lines.push(
|
|
5024
|
+
`⚠️ These headers were sent to ${sanitizeInlineField(config.url)}: ${headerKeys.join(', ')}`,
|
|
5025
|
+
)
|
|
5026
|
+
}
|
|
5027
|
+
}
|
|
5028
|
+
return { content: lines.join('\n') }
|
|
5029
|
+
} catch (err) {
|
|
4938
5030
|
return {
|
|
4939
5031
|
content: [
|
|
4940
|
-
`── MCP Connect: ${
|
|
5032
|
+
`── MCP Connect: ${sanitizeInlineField(label)} ──`,
|
|
5033
|
+
'',
|
|
5034
|
+
`Failed: ${sanitizeInlineField(String(err))}`,
|
|
4941
5035
|
'',
|
|
4942
|
-
|
|
4943
|
-
`Authorization: ${config.auth.authorizationUrl}`,
|
|
4944
|
-
`Scopes: ${config.auth.scopes?.join(', ') || '(default)'}`,
|
|
5036
|
+
`Check the server with /mcp, or retry with backoff: /mcp reconnect ${sanitizeInlineField(name)}`,
|
|
4945
5037
|
].join('\n'),
|
|
4946
|
-
forwardToAI: `Connect to MCP server "${name}" using OAuth. Call McpClient.getInstance().connectWithOAuth() with the server config, then register its tools. Report the result.`,
|
|
4947
|
-
}
|
|
4948
|
-
}
|
|
4949
|
-
const via = config.url ? 'HTTP' : 'stdio'
|
|
4950
|
-
if (config.url) {
|
|
4951
|
-
const headerKeys = config.headers ? Object.keys(config.headers) : []
|
|
4952
|
-
const headerLine = headerKeys.length > 0 ? `\nHeaders to send: ${headerKeys.join(', ')}` : ''
|
|
4953
|
-
return {
|
|
4954
|
-
content: `── MCP Connect: ${sanitizeInlineField(name)} ──\n\nConnecting via HTTP\nURL: ${sanitizeInlineField(config.url)}${headerLine}\n\n⚠️ Verify the URL — any configured headers (e.g. Authorization) will be sent to this server.`,
|
|
4955
|
-
forwardToAI: `Connect to MCP server "${name}" using McpClient.getInstance().connect(config), then register its tools. Report the result.`,
|
|
4956
5038
|
}
|
|
4957
5039
|
}
|
|
4958
|
-
return {
|
|
4959
|
-
content: `── MCP Connect: ${name} ──\n\nConnecting via ${via}...`,
|
|
4960
|
-
forwardToAI: `Connect to MCP server "${name}" using McpClient.getInstance().connect(config), then register its tools. Report the result.`,
|
|
4961
|
-
}
|
|
4962
5040
|
}
|
|
4963
5041
|
|
|
4964
5042
|
// /mcp disconnect <name>
|
|
@@ -5012,11 +5090,37 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
|
|
|
5012
5090
|
|
|
5013
5091
|
// /mcp reload
|
|
5014
5092
|
if (sub === 'reload') {
|
|
5015
|
-
|
|
5016
|
-
|
|
5017
|
-
|
|
5018
|
-
|
|
5093
|
+
const mcpServers = ctx.config.skills?.mcpServers ?? []
|
|
5094
|
+
// Same defect `/mcp connect` had: the forwarded prompt told the AI to call
|
|
5095
|
+
// `McpClient.getInstance().closeAll()` — an internal method no tool exposes —
|
|
5096
|
+
// so the command disconnected and reconnected nothing, it only printed a
|
|
5097
|
+
// status line. Do the work in the handler, like `/mcp reconnect` already does.
|
|
5098
|
+
await client.closeAll()
|
|
5099
|
+
// `closeAll()` nulls the singleton, so the reference captured above is spent.
|
|
5100
|
+
const fresh = McpClient.getInstance()
|
|
5101
|
+
|
|
5102
|
+
if (mcpServers.length === 0) {
|
|
5103
|
+
return { content: '── MCP Reload ──\n\nNo MCP servers configured.' }
|
|
5019
5104
|
}
|
|
5105
|
+
|
|
5106
|
+
const toolsMap = ctx.engine.getTools()
|
|
5107
|
+
const lines: string[] = ['── MCP Reload ──', '']
|
|
5108
|
+
for (const config of mcpServers) {
|
|
5109
|
+
// Tools live in the engine registry, not in the connection: drop them before
|
|
5110
|
+
// reconnecting so a server that no longer offers a tool does not leave a
|
|
5111
|
+
// dead entry registered.
|
|
5112
|
+
unregisterMcpServerTools(config.name, toolsMap)
|
|
5113
|
+
try {
|
|
5114
|
+
await fresh.connect(config)
|
|
5115
|
+
const registered = registerMcpServerTools(config.name, toolsMap)
|
|
5116
|
+
lines.push(`🟢 ${sanitizeInlineField(config.name)} — ${registered} tool(s) registered.`)
|
|
5117
|
+
} catch (err) {
|
|
5118
|
+
lines.push(
|
|
5119
|
+
`🔴 ${sanitizeInlineField(config.name)} — Failed: ${sanitizeInlineField(String(err))}`,
|
|
5120
|
+
)
|
|
5121
|
+
}
|
|
5122
|
+
}
|
|
5123
|
+
return { content: lines.join('\n') }
|
|
5020
5124
|
}
|
|
5021
5125
|
|
|
5022
5126
|
// /mcp (default status)
|