@miphamai/cli 0.85.13 → 0.85.14
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 +6 -6
- package/src/agent/sub-agent.ts +15 -1
- package/src/core/credential-masker/output-scrub.ts +120 -7
- package/src/core/engine.ts +77 -12
- package/src/i18n-core/locales/en-US.json +2 -0
- package/src/i18n-core/locales/zh-CN.json +2 -0
- package/src/mcp/oauth.ts +14 -0
- package/src/plugin/plugin-manager.ts +19 -1
- package/src/providers/anthropic.ts +38 -3
- package/src/providers/openai-compat.ts +3 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +35 -0
- package/src/tools/agent/send-message.ts +9 -2
- package/src/ui/command-picker.tsx +0 -1
- package/src/ui/commands.ts +17 -5
- package/src/ui/input.tsx +10 -1
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.14
|
|
2
2
|
|
|
3
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.
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@miphamai/cli",
|
|
3
|
-
"version": "0.85.
|
|
3
|
+
"version": "0.85.14",
|
|
4
4
|
"description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -44,23 +44,23 @@
|
|
|
44
44
|
"mutate": "stryker run"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@larksuiteoapi/node-sdk": "^1.
|
|
47
|
+
"@larksuiteoapi/node-sdk": "^1.74.0",
|
|
48
48
|
"commander": "^13.1.0",
|
|
49
49
|
"ink": "^7.1.1",
|
|
50
50
|
"ink-text-input": "^6.0.0",
|
|
51
51
|
"react": "^19.3.0",
|
|
52
52
|
"react-devtools-core": "^8.0.0",
|
|
53
|
-
"yaml": "^2.9.
|
|
53
|
+
"yaml": "^2.9.1"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@mipham/shared": "workspace:*",
|
|
57
57
|
"@stryker-mutator/core": "10.0.0",
|
|
58
58
|
"@stryker-mutator/vitest-runner": "10.0.0",
|
|
59
59
|
"@types/bun": "^1.4.2",
|
|
60
|
-
"@types/node": "^22.
|
|
60
|
+
"@types/node": "^22.20.4",
|
|
61
61
|
"@types/react": "^19.3.0",
|
|
62
|
-
"@vitest/coverage-v8": "^5.0.
|
|
62
|
+
"@vitest/coverage-v8": "^5.0.2",
|
|
63
63
|
"ink-testing-library": "^4.0.0",
|
|
64
|
-
"vitest": "^5.0.
|
|
64
|
+
"vitest": "^5.0.2"
|
|
65
65
|
}
|
|
66
66
|
}
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -484,6 +484,13 @@ export class SubAgent {
|
|
|
484
484
|
// synchronous (see `resolveRunInBackground`). Set on the shared literal so it
|
|
485
485
|
// covers the synchronous *and* background runs — both go through here.
|
|
486
486
|
isSubAgent: true,
|
|
487
|
+
// A name a peer can hold onto. `sessionId` is the literal 'sub-agent' for
|
|
488
|
+
// every sub-agent, so `SendMessage` had nothing stable to put on the
|
|
489
|
+
// envelope and minted `sub-agent-<ms>` afresh per message — two messages
|
|
490
|
+
// from one agent arrived under two senders. Same derivation as the footer
|
|
491
|
+
// (`ui/app.tsx`) and the experience logs below: the definition's name, else
|
|
492
|
+
// the type.
|
|
493
|
+
agentName: agentDef?.name || agentType,
|
|
487
494
|
}
|
|
488
495
|
|
|
489
496
|
try {
|
|
@@ -714,9 +721,16 @@ export class SubAgent {
|
|
|
714
721
|
|
|
715
722
|
const result = chunks.join('')
|
|
716
723
|
if (hitMaxTurns) {
|
|
724
|
+
// Only advertise the SendMessage route where a route exists. A background
|
|
725
|
+
// agent has an address (`bg-…`, minted by the registry and handed to the
|
|
726
|
+
// executor) and drains it every turn, so a peer can genuinely continue it.
|
|
727
|
+
// The synchronous path is called without one, and by the time this notice
|
|
728
|
+
// is built the run is over — there is no loop left to drain anything, so
|
|
729
|
+
// "Use SendMessage to continue this sub-agent" there points at nothing.
|
|
730
|
+
const canContinue = agentId ? ' Use SendMessage to continue this sub-agent.' : ''
|
|
717
731
|
return (
|
|
718
732
|
`[partial result — sub-agent reached its ${MAX_TOOL_TURNS}-turn limit; ` +
|
|
719
|
-
|
|
733
|
+
`task may be incomplete.${canContinue}]\n\n` +
|
|
720
734
|
result
|
|
721
735
|
)
|
|
722
736
|
}
|
|
@@ -27,6 +27,47 @@ const TOKEN_REDACTION_PATTERN =
|
|
|
27
27
|
// goes and the host survives.
|
|
28
28
|
const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s]+)@/gi
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* Zero-width and formatting characters stripped before anything is matched.
|
|
32
|
+
*
|
|
33
|
+
* They carry no meaning in command output, and their only effect here is to
|
|
34
|
+
* split a key name so a name-based pattern cannot see it: `"apiKey": "…"`
|
|
35
|
+
* reads as `apiKey` to a human and as nothing at all to the regex. Stripping
|
|
36
|
+
* first means every pattern below sees the name the reader sees.
|
|
37
|
+
*
|
|
38
|
+
* ZWJ (U+200D) and ZWNJ (U+200C) are **deliberately kept** — they are
|
|
39
|
+
* load-bearing in emoji sequences and in several writing systems, so stripping
|
|
40
|
+
* them would mangle output this has no business touching. A key split with
|
|
41
|
+
* those two therefore still evades; that is a narrower gap than the one closed
|
|
42
|
+
* here, and the only residue that keeps the fix from corrupting real text.
|
|
43
|
+
*/
|
|
44
|
+
const FORMAT_CHARS = /[\u00ad\u061c\u200b\u200e\u200f\u2060\ufeff]/g
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* `Authorization: Bearer <token>` — the header name is the one credential
|
|
48
|
+
* carrier the configured patterns do not cover, because neither `authorization`
|
|
49
|
+
* nor the scheme words are key-shaped (`apiKey`, `secret`, `token`, `…_pat`).
|
|
50
|
+
* The secret sits behind `Bearer ` and leaks untouched.
|
|
51
|
+
*
|
|
52
|
+
* Keeps the header name and the scheme so the line stays readable; redacts only
|
|
53
|
+
* the credential, quoted or not.
|
|
54
|
+
*/
|
|
55
|
+
const AUTH_HEADER_PATTERN =
|
|
56
|
+
/(\b(?:authorization|proxy-authorization)\b\s*["']?\s*[:=]\s*["']?(?:bearer|basic|digest|token)\s+)("[^"]*"|'[^']*'|[^\s"']+)/gi
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* A bare `Bearer <token>` / `Basic <b64>` with no header name in front of it —
|
|
60
|
+
* how the value looks once it is in a shell argument, a log line, or a `.env`.
|
|
61
|
+
*
|
|
62
|
+
* The lookahead is the guard against prose: `Bearer authentication` must not be
|
|
63
|
+
* redacted, so the credential has to contain a digit or a base64/JWT punctuation
|
|
64
|
+
* character. An all-lowercase-letter run of that length is a word, not a token.
|
|
65
|
+
*/
|
|
66
|
+
const BARE_AUTH_SCHEME_PATTERNS: RegExp[] = [
|
|
67
|
+
/\b(bearer)(\s+)(?=[A-Za-z0-9\-._~+/]*[0-9._~+/=\-])[A-Za-z0-9\-._~+/]{12,}=*/gi,
|
|
68
|
+
/\b(basic)(\s+)(?=[A-Za-z0-9+/]*[0-9+/=A-Z])[A-Za-z0-9+/]{12,}={0,2}/g,
|
|
69
|
+
]
|
|
70
|
+
|
|
30
71
|
/**
|
|
31
72
|
* Scrub credential patterns from stdout/stderr output.
|
|
32
73
|
* Uses the configured output_scrubbing patterns to detect and replace
|
|
@@ -35,7 +76,8 @@ const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s]+)@/gi
|
|
|
35
76
|
export function maskOutput(output: string, config: CredentialMaskingConfig): string {
|
|
36
77
|
if (!config.enabled || !config.output_scrubbing.enabled) return output
|
|
37
78
|
|
|
38
|
-
|
|
79
|
+
// Normalize away zero-width padding before any name is matched (see FORMAT_CHARS).
|
|
80
|
+
let masked = output.replace(FORMAT_CHARS, '')
|
|
39
81
|
|
|
40
82
|
// Redact bare secret tokens by prefix (always on, independent of config patterns).
|
|
41
83
|
masked = masked.replace(TOKEN_REDACTION_PATTERN, CREDENTIAL_SENTINEL)
|
|
@@ -43,6 +85,12 @@ export function maskOutput(output: string, config: CredentialMaskingConfig): str
|
|
|
43
85
|
// Redact URL-embedded passwords — also shape-based, also always on.
|
|
44
86
|
masked = masked.replace(URL_USERINFO_PATTERN, `$1$2:${CREDENTIAL_SENTINEL}@`)
|
|
45
87
|
|
|
88
|
+
// Redact Authorization-header credentials — also shape-based, also always on.
|
|
89
|
+
masked = masked.replace(AUTH_HEADER_PATTERN, `$1${CREDENTIAL_SENTINEL}`)
|
|
90
|
+
for (const regex of BARE_AUTH_SCHEME_PATTERNS) {
|
|
91
|
+
masked = masked.replace(regex, `$1$2${CREDENTIAL_SENTINEL}`)
|
|
92
|
+
}
|
|
93
|
+
|
|
46
94
|
// Redact bare sk-/sk-ant-/JWT tokens — wire the SecurityGate credential-leak
|
|
47
95
|
// detection into the output path (defense-in-depth beyond the config patterns).
|
|
48
96
|
masked = SecurityGate.redactCredentialLeak(masked)
|
|
@@ -51,15 +99,80 @@ export function maskOutput(output: string, config: CredentialMaskingConfig): str
|
|
|
51
99
|
try {
|
|
52
100
|
// Strip (?i) inline flags — JS uses the 'i' flag instead
|
|
53
101
|
const clean = pattern.replace(/^\(\?i\)/, '')
|
|
54
|
-
|
|
55
|
-
masked = masked.replace(regex, (match) => {
|
|
56
|
-
// Replace everything after the separator (= or :), swallowing the quote
|
|
57
|
-
// a JSON-shaped hit puts in front of it (`"apiKey": "…"`).
|
|
58
|
-
return match.replace(/\s*["']?\s*[:=]\s*["']?\S+/, `=${CREDENTIAL_SENTINEL}`)
|
|
59
|
-
})
|
|
102
|
+
masked = redactValues(masked, new RegExp(clean, 'gim'))
|
|
60
103
|
} catch {
|
|
61
104
|
// Invalid regex — skip
|
|
62
105
|
}
|
|
63
106
|
}
|
|
64
107
|
return masked
|
|
65
108
|
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The separator and the value it introduces, in whichever quoting they arrive.
|
|
112
|
+
*
|
|
113
|
+
* The prefix stops **before** the value's opening quote, deliberately: let it
|
|
114
|
+
* swallow that quote and the quoted branch can no longer match, so the bare
|
|
115
|
+
* branch takes `value"}` whole and the closing quote and brace go with it.
|
|
116
|
+
*
|
|
117
|
+
* `bareQuote` carries a value's opening quote when it has no partner inside the
|
|
118
|
+
* match — what a value containing whitespace looks like, since the configured
|
|
119
|
+
* pattern's own `\S+` cut its match short mid-value. Keeping that quote is what
|
|
120
|
+
* leaves `{"pwd": "<SENTINEL> rest"}` parseable instead of quote-less.
|
|
121
|
+
*/
|
|
122
|
+
const SEPARATOR_AND_VALUE = /(\s*["']?\s*[:=]\s*)(?:"([^"]*)"|'([^']*)'|(["']?)([^\s"']+))/
|
|
123
|
+
|
|
124
|
+
/** Redact the value inside one pattern match, keeping separator and quoting. */
|
|
125
|
+
function redactValue(match: string): string {
|
|
126
|
+
return match.replace(
|
|
127
|
+
SEPARATOR_AND_VALUE,
|
|
128
|
+
(_m, prefix: string, dbl: string | undefined, sgl: string | undefined, bareQuote: string) => {
|
|
129
|
+
if (dbl !== undefined) return `${prefix}"${CREDENTIAL_SENTINEL}"`
|
|
130
|
+
if (sgl !== undefined) return `${prefix}'${CREDENTIAL_SENTINEL}'`
|
|
131
|
+
return `${prefix}${bareQuote}${CREDENTIAL_SENTINEL}`
|
|
132
|
+
},
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Run one configured pattern over `input`, redacting every value it names.
|
|
138
|
+
*
|
|
139
|
+
* An explicit scan rather than `String.replace`, because the resume point has to
|
|
140
|
+
* land **inside** the match. A compact JSON line has no whitespace, so the
|
|
141
|
+
* pattern's own `\S+` runs to the end of it: the first pair's match *contains*
|
|
142
|
+
* every pair after it, and `String.replace` resumes past all of them — redacting
|
|
143
|
+
* only the first. That is not a hypothetical shape; `/config` prints
|
|
144
|
+
* `JSON.stringify(config)`, which is exactly this, several `apiKey`s and all.
|
|
145
|
+
* Resuming just past the value we redacted lets the same pattern see the next
|
|
146
|
+
* pair. (The redaction that destroys the tail instead — replacing `\S+` wholesale
|
|
147
|
+
* — hides the leak rather than fixing it, and mangles the line doing so.)
|
|
148
|
+
*/
|
|
149
|
+
function redactValues(input: string, scan: RegExp): string {
|
|
150
|
+
const out: string[] = []
|
|
151
|
+
let emitted = 0
|
|
152
|
+
let match: RegExpExecArray | null
|
|
153
|
+
scan.lastIndex = 0
|
|
154
|
+
while ((match = scan.exec(input)) !== null) {
|
|
155
|
+
const hit = match[0]
|
|
156
|
+
if (hit.length === 0) {
|
|
157
|
+
// Zero-length match: step over it or `exec` will not advance.
|
|
158
|
+
scan.lastIndex++
|
|
159
|
+
continue
|
|
160
|
+
}
|
|
161
|
+
const inner = SEPARATOR_AND_VALUE.exec(hit)
|
|
162
|
+
if (!inner) {
|
|
163
|
+
// No separator in the match, so nothing here to redact — emit it untouched
|
|
164
|
+
// and let the scan carry on past it.
|
|
165
|
+
out.push(input.slice(emitted, match.index + hit.length))
|
|
166
|
+
emitted = match.index + hit.length
|
|
167
|
+
continue
|
|
168
|
+
}
|
|
169
|
+
const consumed = inner.index + inner[0].length
|
|
170
|
+
out.push(input.slice(emitted, match.index), redactValue(hit.slice(0, consumed)))
|
|
171
|
+
emitted = match.index + consumed
|
|
172
|
+
// Not `scan.lastIndex = emitted + hit.length`: the rest of the match has to stay
|
|
173
|
+
// in view. It is emitted unchanged by a later iteration (or by the tail below).
|
|
174
|
+
scan.lastIndex = emitted
|
|
175
|
+
}
|
|
176
|
+
out.push(input.slice(emitted))
|
|
177
|
+
return out.join('')
|
|
178
|
+
}
|
package/src/core/engine.ts
CHANGED
|
@@ -657,6 +657,16 @@ export class QueryEngine {
|
|
|
657
657
|
)) {
|
|
658
658
|
yield chunk
|
|
659
659
|
|
|
660
|
+
if (chunk.restart) {
|
|
661
|
+
// A retried turn: everything the failed attempt accumulated is
|
|
662
|
+
// superseded. Drop it here or `toolUses` would carry both attempts'
|
|
663
|
+
// calls and each would execute (see `restart` in StreamChunk).
|
|
664
|
+
assistantContent = ''
|
|
665
|
+
reasoningContent = ''
|
|
666
|
+
thinkingContent = ''
|
|
667
|
+
toolUses.length = 0
|
|
668
|
+
}
|
|
669
|
+
|
|
660
670
|
if (chunk.type === 'error') {
|
|
661
671
|
// #23: client-generated errors are system lines, not model output —
|
|
662
672
|
// store as `system` so resume renders an error line (⚠) rather than
|
|
@@ -998,15 +1008,23 @@ export class QueryEngine {
|
|
|
998
1008
|
const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
|
|
999
1009
|
|
|
1000
1010
|
try {
|
|
1001
|
-
for await (const chunk of this.
|
|
1002
|
-
model: this.registry.getActiveModel(),
|
|
1011
|
+
for await (const chunk of this.chatWithFallback(
|
|
1003
1012
|
messages,
|
|
1004
1013
|
systemPrompt,
|
|
1005
|
-
|
|
1014
|
+
toolDefs.length > 0 ? toolDefs : undefined,
|
|
1006
1015
|
signal,
|
|
1007
|
-
|
|
1016
|
+
)) {
|
|
1008
1017
|
yield chunk
|
|
1009
1018
|
|
|
1019
|
+
if (chunk.restart) {
|
|
1020
|
+
// Tool continuation rounds get the same retry + fallback as the first
|
|
1021
|
+
// call via `chatWithFallback`; a retry re-streams the round, so drop
|
|
1022
|
+
// the failed attempt's accumulation or its tools execute twice.
|
|
1023
|
+
assistantContent = ''
|
|
1024
|
+
reasoningContent = ''
|
|
1025
|
+
thinkingContent = ''
|
|
1026
|
+
toolUses.length = 0
|
|
1027
|
+
}
|
|
1010
1028
|
if (chunk.type === 'error') return
|
|
1011
1029
|
if (chunk.type === 'text' && chunk.content) {
|
|
1012
1030
|
assistantContent += chunk.content
|
|
@@ -1083,13 +1101,12 @@ export class QueryEngine {
|
|
|
1083
1101
|
try {
|
|
1084
1102
|
const finalSystemPrompt = this.context.getSystemPrompt()
|
|
1085
1103
|
const finalMessages = this.context.getMessages()
|
|
1086
|
-
for await (const chunk of this.
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
tools: undefined, // no tools — force text-only summary
|
|
1104
|
+
for await (const chunk of this.chatWithFallback(
|
|
1105
|
+
finalMessages,
|
|
1106
|
+
finalSystemPrompt,
|
|
1107
|
+
undefined, // no tools — force text-only summary
|
|
1091
1108
|
signal,
|
|
1092
|
-
|
|
1109
|
+
)) {
|
|
1093
1110
|
yield chunk
|
|
1094
1111
|
if (chunk.type === 'error') return
|
|
1095
1112
|
}
|
|
@@ -1497,12 +1514,23 @@ export class QueryEngine {
|
|
|
1497
1514
|
* 被干净地关掉、正常写完,在字节流上是同一个形状),而这里是**每一处消费
|
|
1498
1515
|
* chat 流的地方都必经的唯一出口** —— 转发的循环有两个(`process` 与
|
|
1499
1516
|
* `continueWithTools`),各自补一次正是「两条渲染路径只接一条」的老毛病。
|
|
1517
|
+
*
|
|
1518
|
+
* 被拒绝的一轮同理:`refusal` 也只有 provider 能判(200 拒答与正常 `end_turn`
|
|
1519
|
+
* 在下游是同一个终止 `stop`),而拒答可能**一个字都没有** —— 没有这里点名,
|
|
1520
|
+
* 那一轮就是一块空白屏,用户连「被拒了」都看不出。
|
|
1500
1521
|
*/
|
|
1501
1522
|
private async *llmChat(req: ChatRequest): AsyncGenerator<StreamChunk> {
|
|
1502
1523
|
for await (const chunk of (this.llm ?? this.registry).chat(req)) {
|
|
1503
1524
|
if (chunk.type === 'stop' && chunk.truncated) {
|
|
1504
1525
|
yield { type: 'warning', content: t('errors.turn_truncated') }
|
|
1505
1526
|
}
|
|
1527
|
+
if (chunk.type === 'stop' && chunk.refusal) {
|
|
1528
|
+
const reason = chunk.refusal.explanation
|
|
1529
|
+
yield {
|
|
1530
|
+
type: 'warning',
|
|
1531
|
+
content: reason ? t('errors.turn_refused_reason', { reason }) : t('errors.turn_refused'),
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1506
1534
|
yield chunk
|
|
1507
1535
|
}
|
|
1508
1536
|
}
|
|
@@ -1570,7 +1598,15 @@ export class QueryEngine {
|
|
|
1570
1598
|
failure = String(err)
|
|
1571
1599
|
}
|
|
1572
1600
|
if (!retryable || !ownsFlow || attempt >= 1) break
|
|
1573
|
-
|
|
1601
|
+
// `restart: true` tells the consumer to drop what the failed attempt already
|
|
1602
|
+
// yielded. Without it the retry's tool calls are *added* to the failed
|
|
1603
|
+
// attempt's, and their ids are regenerated per attempt, so nothing
|
|
1604
|
+
// downstream dedupes them and a side-effecting tool runs twice.
|
|
1605
|
+
yield {
|
|
1606
|
+
type: 'warning',
|
|
1607
|
+
content: `${activeId} failed (${failure}) — retrying once`,
|
|
1608
|
+
restart: true,
|
|
1609
|
+
}
|
|
1574
1610
|
}
|
|
1575
1611
|
const detail = failure ?? 'Unknown error'
|
|
1576
1612
|
|
|
@@ -1607,10 +1643,20 @@ export class QueryEngine {
|
|
|
1607
1643
|
// window than the one we fell back from (1M → 128K). Switching the registry
|
|
1608
1644
|
// alone left compaction armed to the *old* model's window, so the summary would
|
|
1609
1645
|
// not trigger until ~950K — long past the point the fallback model overflows.
|
|
1646
|
+
const beforeWindow = this.effectiveWindow(activeModel)
|
|
1610
1647
|
this.switchProvider(defaultId, fallbackModel)
|
|
1648
|
+
// Say so when the switch shrank the window. The user picked a model for what
|
|
1649
|
+
// it could hold; a fallback to a 200K model silently cuts how much of the
|
|
1650
|
+
// conversation still fits (1M → 200K), and that is not obvious from the model
|
|
1651
|
+
// name alone — the same fact the switch itself already acted on.
|
|
1652
|
+
const afterWindow = this.effectiveWindow(fallbackModel)
|
|
1653
|
+
const windowNote =
|
|
1654
|
+
beforeWindow !== undefined && afterWindow !== undefined && afterWindow < beforeWindow
|
|
1655
|
+
? ` (context window ${this.fmtWindow(beforeWindow)} → ${this.fmtWindow(afterWindow)})`
|
|
1656
|
+
: ''
|
|
1611
1657
|
yield {
|
|
1612
1658
|
type: 'warning',
|
|
1613
|
-
content: `${activeId} unreachable — degraded to ${defaultId} (${fallbackModel})`,
|
|
1659
|
+
content: `${activeId} unreachable — degraded to ${defaultId} (${fallbackModel})${windowNote}`,
|
|
1614
1660
|
}
|
|
1615
1661
|
|
|
1616
1662
|
try {
|
|
@@ -1862,6 +1908,25 @@ export class QueryEngine {
|
|
|
1862
1908
|
}
|
|
1863
1909
|
}
|
|
1864
1910
|
|
|
1911
|
+
/**
|
|
1912
|
+
* The context window a model actually gets in this process: its nominal size,
|
|
1913
|
+
* unless the 1M cap is disabled and it exceeds 200K — the same rule
|
|
1914
|
+
* `switchProvider` applies, so the fallback notice reports the *effective*
|
|
1915
|
+
* window, not the model sheet's.
|
|
1916
|
+
*/
|
|
1917
|
+
private effectiveWindow(modelId: string): number | undefined {
|
|
1918
|
+
const model = this.registry.findModel(modelId)
|
|
1919
|
+
if (!model) return undefined
|
|
1920
|
+
return process.env.MIPHAM_DISABLE_1M_CONTEXT === '1' && model.contextWindow > 200_000
|
|
1921
|
+
? 200_000
|
|
1922
|
+
: model.contextWindow
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
/** `1000000` → `1M`, `128000` → `128K` — for the fallback context-window notice. */
|
|
1926
|
+
private fmtWindow(n: number): string {
|
|
1927
|
+
return n >= 1_000_000 ? `${Math.round(n / 100_000) / 10}M` : `${Math.round(n / 1000)}K`
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1865
1930
|
/** Wrap context compaction with PreCompact/PostCompact hooks. */
|
|
1866
1931
|
private async compactWithHooks(heading: string): Promise<void> {
|
|
1867
1932
|
if (this.hookEngine) {
|
|
@@ -964,6 +964,8 @@
|
|
|
964
964
|
"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.",
|
|
965
965
|
"turn_timeout": "Task produced no substantial output for {minutes} minutes and was stopped. Break the task into smaller steps or clarify the next step, then retry.",
|
|
966
966
|
"turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed.",
|
|
967
|
+
"turn_refused": "The model declined this request and did not answer. This is not a failure — resending it to the same model will usually be declined again.",
|
|
968
|
+
"turn_refused_reason": "The model declined this request: {reason}",
|
|
967
969
|
"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.",
|
|
968
970
|
"mcp_not_connected": "Error: MCP server \"{server}\" not connected",
|
|
969
971
|
"mcp_tool_error": "MCP tool error: {error}",
|
|
@@ -964,6 +964,8 @@
|
|
|
964
964
|
"max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
|
|
965
965
|
"turn_timeout": "任务已超过 {minutes} 分钟无实质产出,已自动停止。建议拆分任务或明确下一步后重新发起。",
|
|
966
966
|
"turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。",
|
|
967
|
+
"turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
|
|
968
|
+
"turn_refused_reason": "模型拒绝了这次请求:{reason}",
|
|
967
969
|
"stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
|
|
968
970
|
"mcp_not_connected": "错误:MCP 服务器 \"{server}\" 未连接",
|
|
969
971
|
"mcp_tool_error": "MCP 工具错误:{error}",
|
package/src/mcp/oauth.ts
CHANGED
|
@@ -88,10 +88,24 @@ export class OAuthClient {
|
|
|
88
88
|
res.end(
|
|
89
89
|
`<html><body><h1>${t('system.oauth.authenticated')}</h1><p>${t('system.oauth.close_window')}</p></body></html>`,
|
|
90
90
|
)
|
|
91
|
+
clearTimeout(timer)
|
|
91
92
|
server.close()
|
|
92
93
|
resolve(receivedCode)
|
|
93
94
|
}
|
|
94
95
|
})
|
|
96
|
+
// A listen failure (`EADDRINUSE` — the port is taken, or a second flow
|
|
97
|
+
// raced this one) arrives as an `'error'` event. With no listener Node
|
|
98
|
+
// re-throws it as an uncaught exception and takes the whole process down:
|
|
99
|
+
// the flow cannot *fail cleanly* if the failure signal itself is fatal.
|
|
100
|
+
// Reject instead so the caller sees an error and the attempt ends here.
|
|
101
|
+
const timer = setTimeout(() => {
|
|
102
|
+
server.close()
|
|
103
|
+
reject(new Error(t('errors.oauth_timeout')))
|
|
104
|
+
}, 300_000)
|
|
105
|
+
server.on('error', (err) => {
|
|
106
|
+
clearTimeout(timer)
|
|
107
|
+
reject(err)
|
|
108
|
+
})
|
|
95
109
|
server.listen(port, '127.0.0.1', () => {
|
|
96
110
|
const authUrl = new URL(auth.authorizationUrl)
|
|
97
111
|
authUrl.searchParams.set('response_type', 'code')
|
|
@@ -131,9 +131,27 @@ export class PluginManager {
|
|
|
131
131
|
// of its own to be loaded from here. `execFileSync` (argv array, no
|
|
132
132
|
// shell) keeps the command line independent of packageName, so package
|
|
133
133
|
// name validation is not the only thing standing between us and a shell.
|
|
134
|
+
//
|
|
135
|
+
// `--registry`: name validation constrains the *top-level* name only —
|
|
136
|
+
// every transitive dependency is resolved by npm from whatever registry
|
|
137
|
+
// the user's config/env points at, so a hijacked `npm_config_registry` (or
|
|
138
|
+
// an `.npmrc` in scope) gets to serve code that lands on this machine.
|
|
139
|
+
// Pinning to an explicit HTTPS registry takes the environment out of the
|
|
140
|
+
// resolver. The value is the npm default already declared in this repo's
|
|
141
|
+
// registry chain (`src/shared/update.ts`), not a new literal. The flag is
|
|
142
|
+
// honoured over npm config because command-line flags outrank it.
|
|
134
143
|
execFileSync(
|
|
135
144
|
'npm',
|
|
136
|
-
[
|
|
145
|
+
[
|
|
146
|
+
'install',
|
|
147
|
+
packageName,
|
|
148
|
+
'--prefix',
|
|
149
|
+
stagingDir,
|
|
150
|
+
'--no-save',
|
|
151
|
+
'--ignore-scripts',
|
|
152
|
+
'--registry',
|
|
153
|
+
'https://registry.npmjs.org',
|
|
154
|
+
],
|
|
137
155
|
{
|
|
138
156
|
encoding: 'utf-8',
|
|
139
157
|
stdio: 'pipe',
|
|
@@ -34,6 +34,11 @@ interface AnthropicSSEEvent {
|
|
|
34
34
|
thinking?: string
|
|
35
35
|
partial_json?: string
|
|
36
36
|
stop_reason?: string | null
|
|
37
|
+
/**
|
|
38
|
+
* Sits beside `stop_reason` on the `message_delta` event, and is the only
|
|
39
|
+
* explanation that exists when a refusal comes back with no content at all.
|
|
40
|
+
*/
|
|
41
|
+
stop_details?: { category?: string; explanation?: string }
|
|
37
42
|
}
|
|
38
43
|
error?: { type: string; message: string }
|
|
39
44
|
usage?: { input_tokens: number; output_tokens: number }
|
|
@@ -78,6 +83,12 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
78
83
|
// off at the output ceiling rather than ended by the model.
|
|
79
84
|
let truncated = false
|
|
80
85
|
|
|
86
|
+
// Set when the provider reports `stop_reason: 'refusal'`. A refusal is a
|
|
87
|
+
// **successful** response (HTTP 200) that declines to answer, and it may carry
|
|
88
|
+
// an empty content array — so without this the turn ends as a blank screen,
|
|
89
|
+
// because `end_turn` and `refusal` both arrive at the same terminal stop below.
|
|
90
|
+
let refusal: { category?: string; explanation?: string } | undefined
|
|
91
|
+
|
|
81
92
|
// Whether this stream reached `message_stop`. A stream that runs out without
|
|
82
93
|
// one was cut — a proxy or gateway closing the connection cleanly looks
|
|
83
94
|
// exactly like a finished response otherwise.
|
|
@@ -87,6 +98,15 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
87
98
|
// second one; emitting it twice makes the engine run the tool twice.
|
|
88
99
|
const emittedToolIds = new Set<string>()
|
|
89
100
|
|
|
101
|
+
// Both terminal emissions go through here so the two flags can never drift
|
|
102
|
+
// apart on one path. Reads `truncated`/`refusal` at call time, so it is
|
|
103
|
+
// declared before either is set.
|
|
104
|
+
const terminalStop = (): StreamChunk => ({
|
|
105
|
+
type: 'stop',
|
|
106
|
+
...(truncated ? { truncated: true } : {}),
|
|
107
|
+
...(refusal ? { refusal } : {}),
|
|
108
|
+
})
|
|
109
|
+
|
|
90
110
|
const messages = this.convertMessages(req.messages)
|
|
91
111
|
this.markPrefixCacheBreakpoint(messages)
|
|
92
112
|
|
|
@@ -298,12 +318,22 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
298
318
|
if (stopReason === 'max_tokens') {
|
|
299
319
|
truncated = true
|
|
300
320
|
}
|
|
321
|
+
// A refusal is a successful response that declines to answer, and
|
|
322
|
+
// it can arrive with no content at all. Capture the provider's own
|
|
323
|
+
// reason here — it is the only one that will ever exist, and the
|
|
324
|
+
// stream is the only place it appears.
|
|
325
|
+
if (stopReason === 'refusal') {
|
|
326
|
+
refusal = {}
|
|
327
|
+
const details = event.delta?.stop_details
|
|
328
|
+
if (details?.category !== undefined) refusal.category = details.category
|
|
329
|
+
if (details?.explanation !== undefined) refusal.explanation = details.explanation
|
|
330
|
+
}
|
|
301
331
|
break
|
|
302
332
|
}
|
|
303
333
|
|
|
304
334
|
case 'message_stop': {
|
|
305
335
|
sawTerminalEvent = true
|
|
306
|
-
yield
|
|
336
|
+
yield terminalStop()
|
|
307
337
|
return
|
|
308
338
|
}
|
|
309
339
|
|
|
@@ -327,7 +357,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
327
357
|
// closed connection and a finished response are otherwise the same stream.
|
|
328
358
|
if (!sawTerminalEvent) truncated = true
|
|
329
359
|
|
|
330
|
-
yield
|
|
360
|
+
yield terminalStop()
|
|
331
361
|
} finally {
|
|
332
362
|
await reader.cancel().catch(() => {})
|
|
333
363
|
}
|
|
@@ -434,7 +464,12 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
434
464
|
tool_use_id: block.tool_use_id,
|
|
435
465
|
// 空 content 同样整条请求被拒(见 NO_TOOL_OUTPUT)。`||` 而非 `=== ''`:
|
|
436
466
|
// 投影层缺失该字段时这里是 `undefined`,空数组同理。
|
|
437
|
-
|
|
467
|
+
// 非字符串(工具/MCP/插件违约返回对象或数字)同样要先成文本 ——
|
|
468
|
+
// 直接透传会作为 JSON 值进请求体,而 API 只收字符串。
|
|
469
|
+
content:
|
|
470
|
+
(typeof block.content === 'string'
|
|
471
|
+
? block.content
|
|
472
|
+
: JSON.stringify(block.content)) || NO_TOOL_OUTPUT,
|
|
438
473
|
// 只在失败时下发 —— 成功请求体与改动前逐字节相同,不引入 prompt-cache 前缀抖动
|
|
439
474
|
...(block.is_error === true ? { is_error: true } : {}),
|
|
440
475
|
}
|
|
@@ -417,7 +417,9 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
417
417
|
result.push({
|
|
418
418
|
role: 'tool',
|
|
419
419
|
tool_call_id: tr.tool_use_id,
|
|
420
|
-
content
|
|
420
|
+
// 非字符串 content 需成文本:tool 消息的 content 只收字符串,透传对象
|
|
421
|
+
// 会让它作为 JSON 值进请求体。空串保持空串(此处无占位回退)。
|
|
422
|
+
content: typeof tr.content === 'string' ? tr.content : JSON.stringify(tr.content),
|
|
421
423
|
})
|
|
422
424
|
}
|
|
423
425
|
continue
|
|
@@ -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.14' 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 = 3922 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -162,6 +162,29 @@ export interface StreamChunk {
|
|
|
162
162
|
* either way, and tool calls cut off mid-arguments are dropped silently.
|
|
163
163
|
*/
|
|
164
164
|
truncated?: boolean
|
|
165
|
+
/**
|
|
166
|
+
* Set on the `warning` chunk a retried turn emits just before it re-streams
|
|
167
|
+
* (`chatWithFallback`). Everything the failed attempt already yielded is on
|
|
168
|
+
* screen and cannot be recalled, so a consumer that accumulates a turn's
|
|
169
|
+
* output — assistant text, tool calls — must **discard the previous attempt**
|
|
170
|
+
* when it sees this. Without it a retry re-executes the tool calls that
|
|
171
|
+
* attempt already emitted: their ids are regenerated per attempt, so nothing
|
|
172
|
+
* downstream de-duplicates them and a side-effecting tool runs twice.
|
|
173
|
+
*/
|
|
174
|
+
restart?: boolean
|
|
175
|
+
/**
|
|
176
|
+
* The provider declined to answer — a terminal outcome, not a failure.
|
|
177
|
+
*
|
|
178
|
+
* Anthropic reports this as `stop_reason: 'refusal'` on a **successful**
|
|
179
|
+
* response (HTTP 200, not an error), sending `stop_details` alongside it on
|
|
180
|
+
* the same `message_delta`. A refusal may carry an **empty content array**,
|
|
181
|
+
* so without this the turn is a blank screen with nothing to explain it;
|
|
182
|
+
* `explanation` is the provider's own stated reason for the decline.
|
|
183
|
+
*
|
|
184
|
+
* Set **only on refusal** — absent on every normal stop, so the success path
|
|
185
|
+
* stays byte-identical (same shape as `truncated` above).
|
|
186
|
+
*/
|
|
187
|
+
refusal?: { category?: string; explanation?: string }
|
|
165
188
|
}
|
|
166
189
|
|
|
167
190
|
// ── Config Types ──
|
|
@@ -595,6 +618,18 @@ export interface ToolContext {
|
|
|
595
618
|
* consume a background handle, so its default flips to synchronous.
|
|
596
619
|
*/
|
|
597
620
|
isSubAgent?: boolean
|
|
621
|
+
/**
|
|
622
|
+
* The agent's own name, when this call is being executed by a sub-agent.
|
|
623
|
+
*
|
|
624
|
+
* `isSubAgent` says *that* we are one level down; this says *which* agent, so a
|
|
625
|
+
* peer reading `Message from @…` can tell two agents apart, and can recognise the
|
|
626
|
+
* same agent across two messages. Without it `SendMessage` has only the anonymous
|
|
627
|
+
* `'sub-agent'` session string to go on and mints a fresh `sub-agent-<ms>` sender
|
|
628
|
+
* per message — the parent neither sees who sent it nor can address a reply. Set
|
|
629
|
+
* by `SubAgent.runExecution` from the same `agentDef.name || type` the footer and
|
|
630
|
+
* the experience logs use. Absent for the main session.
|
|
631
|
+
*/
|
|
632
|
+
agentName?: string
|
|
598
633
|
}
|
|
599
634
|
|
|
600
635
|
export interface ToolDefinition {
|
|
@@ -36,10 +36,17 @@ export const sendMessageTool: ToolDefinition = {
|
|
|
36
36
|
// P1-1: Truncate long summaries instead of rejecting (max 200 chars)
|
|
37
37
|
const truncatedSummary = summary.length > 200 ? summary.slice(0, 197) + '...' : summary
|
|
38
38
|
|
|
39
|
+
// Prefer the agent's own name when it has one (a sub-agent gets it from
|
|
40
|
+
// `SubAgent.runExecution`): `sessionId` is the literal 'sub-agent' for every
|
|
41
|
+
// sub-agent, so keying off it alone gave the parent an opaque sender — and one
|
|
42
|
+
// minted per message, so two messages from the same agent could not be grouped
|
|
43
|
+
// or replied to. Callers with no identity (the main session) keep the previous
|
|
44
|
+
// shape byte-for-byte.
|
|
39
45
|
const from =
|
|
40
|
-
ctx.
|
|
46
|
+
ctx.agentName ||
|
|
47
|
+
(ctx.sessionId === 'sub-agent'
|
|
41
48
|
? `sub-agent-${Date.now().toString(36)}`
|
|
42
|
-
: ctx.sessionId || 'main'
|
|
49
|
+
: ctx.sessionId || 'main')
|
|
43
50
|
|
|
44
51
|
const router = getMessageRouter()
|
|
45
52
|
const result = await router.route(from, to, truncatedSummary, message)
|
|
@@ -85,7 +85,6 @@ export function CommandPicker({
|
|
|
85
85
|
Math.min(cursorIdx.value - Math.floor(maxVisible / 2), filtered.length - maxVisible),
|
|
86
86
|
)
|
|
87
87
|
const visible = filtered.slice(scrollStart, scrollStart + maxVisible)
|
|
88
|
-
const _adjustedCursor = cursorIdx.value - scrollStart
|
|
89
88
|
|
|
90
89
|
// Wrap cursor safely
|
|
91
90
|
const safeCursor = (i: number) =>
|
package/src/ui/commands.ts
CHANGED
|
@@ -5117,7 +5117,13 @@ const loginCmd: CommandHandler = (ctx) => {
|
|
|
5117
5117
|
|
|
5118
5118
|
for (const p of activeProviders) {
|
|
5119
5119
|
const envVar = providerEnvMap[p.id] ?? `${p.id.toUpperCase()}_API_KEY`
|
|
5120
|
-
|
|
5120
|
+
// An env var is only one of the two ways a provider gets a key: `ctx.config`
|
|
5121
|
+
// already carries the merged (and, for `enc:v1:`, decrypted) `apiKey` from
|
|
5122
|
+
// config.yml. An env-only check reports a fully configured provider as ⬜.
|
|
5123
|
+
// Reuse `isApiKeyMissing` — the same predicate `/switch` uses — so the two
|
|
5124
|
+
// readouts agree on what "has a key" means (and an empty row stays ⬜).
|
|
5125
|
+
const configSet = !isApiKeyMissing(p.apiKey)
|
|
5126
|
+
const isSet = (typeof process !== 'undefined' && !!process.env[envVar]) || configSet
|
|
5121
5127
|
const icon = isSet ? '✅' : '⬜'
|
|
5122
5128
|
lines.push(` ${icon} ${p.id.padEnd(14)} $${envVar}${isSet ? ' (set)' : ''}`)
|
|
5123
5129
|
}
|
|
@@ -5439,7 +5445,7 @@ const forkCmd: CommandHandler = async (ctx, args) => {
|
|
|
5439
5445
|
}
|
|
5440
5446
|
}
|
|
5441
5447
|
|
|
5442
|
-
const { execSync } = await import('node:child_process')
|
|
5448
|
+
const { execSync, execFileSync } = await import('node:child_process')
|
|
5443
5449
|
const { join } = await import('node:path')
|
|
5444
5450
|
|
|
5445
5451
|
try {
|
|
@@ -5463,15 +5469,21 @@ const forkCmd: CommandHandler = async (ctx, args) => {
|
|
|
5463
5469
|
const wtPath = join(worktreeRoot(process.cwd()), name)
|
|
5464
5470
|
|
|
5465
5471
|
try {
|
|
5466
|
-
|
|
5472
|
+
// argv array, no shell — `wtPath` is derived from the current directory and can
|
|
5473
|
+
// contain a space or a metacharacter, which a shell string would split or misfire on.
|
|
5474
|
+
// Same reason the add/remove/branch trio all go through execFileSync here.
|
|
5475
|
+
execFileSync('git', ['worktree', 'add', '-b', branch, wtPath, 'HEAD'], {
|
|
5476
|
+
stdio: 'ignore',
|
|
5477
|
+
timeout: 30_000,
|
|
5478
|
+
})
|
|
5467
5479
|
} catch (err) {
|
|
5468
5480
|
try {
|
|
5469
|
-
|
|
5481
|
+
execFileSync('git', ['worktree', 'remove', '--force', wtPath], { stdio: 'ignore' })
|
|
5470
5482
|
} catch {
|
|
5471
5483
|
/* ok */
|
|
5472
5484
|
}
|
|
5473
5485
|
try {
|
|
5474
|
-
|
|
5486
|
+
execFileSync('git', ['branch', '-D', branch], { stdio: 'ignore' })
|
|
5475
5487
|
} catch {
|
|
5476
5488
|
/* ok */
|
|
5477
5489
|
}
|
package/src/ui/input.tsx
CHANGED
|
@@ -356,7 +356,16 @@ export function InputBar({
|
|
|
356
356
|
if (!value.startsWith('/')) return []
|
|
357
357
|
const filter = value.slice(1).toLowerCase()
|
|
358
358
|
if (!filter) return allCommands.slice(0, 12) // show first 12 when just "/"
|
|
359
|
-
|
|
359
|
+
// Match name OR description — the same rule the CommandPicker uses. A name-only
|
|
360
|
+
// filter hid commands a user was plainly looking for ("fork" should surface a
|
|
361
|
+
// command described as "fork the conversation"), so the two slash surfaces now
|
|
362
|
+
// agree on one semantic.
|
|
363
|
+
return allCommands
|
|
364
|
+
.filter(
|
|
365
|
+
(c) =>
|
|
366
|
+
c.name.toLowerCase().includes(filter) || c.description.toLowerCase().includes(filter),
|
|
367
|
+
)
|
|
368
|
+
.slice(0, 8)
|
|
360
369
|
}, [value, allCommands])
|
|
361
370
|
|
|
362
371
|
// ── @mention hints (cross-session recipients) ──
|