@miphamai/cli 0.85.13 → 0.85.15
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 +4 -4
- package/package.json +6 -6
- package/skills/standard/mipham-code-setup.SKILL.md +1 -1
- 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/core/hooks-executor.ts +2 -0
- package/src/core/hooks.ts +10 -2
- package/src/core/instructions.ts +13 -4
- package/src/daemon/dingtalk/api.ts +6 -0
- package/src/i18n-core/locales/en-US.json +2 -6
- package/src/i18n-core/locales/zh-CN.json +2 -6
- 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 +3 -3
- package/src/shared/types.ts +44 -0
- package/src/skills/bundled-skills.ts +1 -1
- package/src/tools/agent/send-message.ts +9 -2
- package/src/tools/exec/bash.ts +10 -4
- package/src/ui/app.tsx +0 -2
- package/src/ui/command-picker.tsx +0 -1
- package/src/ui/commands.ts +17 -26
- package/src/ui/input.tsx +10 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.15
|
|
2
2
|
|
|
3
|
-
**Multi-model open-core intelligent coding terminal** — 12 AI providers,
|
|
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
|
-
- **
|
|
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` `/
|
|
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.
|
|
3
|
+
"version": "0.85.15",
|
|
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
|
}
|
|
@@ -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 |
|
|
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` |
|
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) {
|
|
@@ -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
|
|
369
|
-
|
|
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) {
|
package/src/core/instructions.ts
CHANGED
|
@@ -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.
|
|
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
|
|
233
|
-
|
|
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
|
|
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
|
}
|
|
@@ -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}\""
|
|
@@ -964,6 +958,8 @@
|
|
|
964
958
|
"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
959
|
"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
960
|
"turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed.",
|
|
961
|
+
"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.",
|
|
962
|
+
"turn_refused_reason": "The model declined this request: {reason}",
|
|
967
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.",
|
|
968
964
|
"mcp_not_connected": "Error: MCP server \"{server}\" not connected",
|
|
969
965
|
"mcp_tool_error": "MCP tool error: {error}",
|
|
@@ -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}\""
|
|
@@ -964,6 +958,8 @@
|
|
|
964
958
|
"max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
|
|
965
959
|
"turn_timeout": "任务已超过 {minutes} 分钟无实质产出,已自动停止。建议拆分任务或明确下一步后重新发起。",
|
|
966
960
|
"turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。",
|
|
961
|
+
"turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
|
|
962
|
+
"turn_refused_reason": "模型拒绝了这次请求:{reason}",
|
|
967
963
|
"stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
|
|
968
964
|
"mcp_not_connected": "错误:MCP 服务器 \"{server}\" 未连接",
|
|
969
965
|
"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.15' as const
|
|
13
13
|
|
|
14
14
|
/** npm install 全局安装命令 */
|
|
15
15
|
export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
|
|
@@ -75,7 +75,7 @@ export const COMPANY_SHORT = '华安麦逄科技' as const
|
|
|
75
75
|
*/
|
|
76
76
|
|
|
77
77
|
/** Slash 命令总数(真源:`getCommandNames().length`,`apps/cli/src/ui/commands.ts`) */
|
|
78
|
-
export const SLASH_COMMAND_COUNT =
|
|
78
|
+
export const SLASH_COMMAND_COUNT = 137 as const
|
|
79
79
|
|
|
80
80
|
/** 内置提供商总数(真源:`DEFAULT_PROVIDERS.length`,`apps/cli/src/shared/constants.ts`) */
|
|
81
81
|
export const PROVIDER_COUNT = 12 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 = 3942 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 ──
|
|
@@ -331,6 +354,15 @@ export interface HookContext {
|
|
|
331
354
|
export interface HookResult {
|
|
332
355
|
allowed: boolean
|
|
333
356
|
reason?: string
|
|
357
|
+
/**
|
|
358
|
+
* Set when the hook could not *run* (missing command, spawn failure, option
|
|
359
|
+
* rejected) — as opposed to running and choosing to allow, warn or block.
|
|
360
|
+
* The engine counts these toward auto-disable, which is why they have to be
|
|
361
|
+
* distinguishable from a plain `allowed: true`; a `command` hook that exits
|
|
362
|
+
* non-zero is left out on purpose, since some hooks use that to signal a
|
|
363
|
+
* policy decision rather than a broken installation.
|
|
364
|
+
*/
|
|
365
|
+
hookError?: string
|
|
334
366
|
modifiedInput?: Record<string, unknown>
|
|
335
367
|
decision?: 'allow' | 'block'
|
|
336
368
|
permissionDecision?: 'allow' | 'deny' | 'ask' | 'defer'
|
|
@@ -595,6 +627,18 @@ export interface ToolContext {
|
|
|
595
627
|
* consume a background handle, so its default flips to synchronous.
|
|
596
628
|
*/
|
|
597
629
|
isSubAgent?: boolean
|
|
630
|
+
/**
|
|
631
|
+
* The agent's own name, when this call is being executed by a sub-agent.
|
|
632
|
+
*
|
|
633
|
+
* `isSubAgent` says *that* we are one level down; this says *which* agent, so a
|
|
634
|
+
* peer reading `Message from @…` can tell two agents apart, and can recognise the
|
|
635
|
+
* same agent across two messages. Without it `SendMessage` has only the anonymous
|
|
636
|
+
* `'sub-agent'` session string to go on and mints a fresh `sub-agent-<ms>` sender
|
|
637
|
+
* per message — the parent neither sees who sent it nor can address a reply. Set
|
|
638
|
+
* by `SubAgent.runExecution` from the same `agentDef.name || type` the footer and
|
|
639
|
+
* the experience logs use. Absent for the main session.
|
|
640
|
+
*/
|
|
641
|
+
agentName?: string
|
|
598
642
|
}
|
|
599
643
|
|
|
600
644
|
export interface ToolDefinition {
|
|
@@ -18,7 +18,7 @@ export const BUNDLED_SKILLS: ReadonlyArray<BundledSkill> = [
|
|
|
18
18
|
{ type: 'standard', raw: "---\nname: grill-with-docs\ndescription: A relentless interview to sharpen a plan or design, creating CONTEXT.md (shared language) and ADRs (architectural decisions) as we go. Use before any non-trivial implementation to align on requirements and terminology.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Write\n - Edit\n - Bash\n - Glob\n - Grep\n - WebSearch\n - WebFetch\n---\n\n# Grill With Docs — Deep Requirements Alignment\n\nInspired by Matt Pocock's `grill-with-docs` and `domain-modeling` skills. Before writing code, run a structured interview to align on requirements, establish shared language, and record architectural decisions.\n\n## When to Use\n\n- Before any non-trivial feature implementation\n- When requirements are fuzzy (\"make it faster\", \"add X\")\n- When you need to establish project terminology\n- When architectural decisions need to be recorded\n- User says: \"plan X\", \"design Y\", \"what should we do about Z\"\n\n## When NOT to Use\n\n- Trivial bug fixes with clear expected behavior\n- One-line changes\n- Tasks where the requirements are already crystal clear\n\n---\n\n## The Interview Flow\n\n### Phase 1: Understand the Intent\n\nStart by understanding what the user actually wants. Don't ask \"what should I build?\" — ask about their goal.\n\n**Core Questions:**\n\n1. What problem are you solving? (Not what feature you're building)\n2. Who is this for? (End user, developer, internal tool?)\n3. What does success look like? (How will you know when it's done?)\n4. What's the deadline or priority context?\n\n**Anti-pattern**: Jumping to implementation questions (\"Do you want REST or GraphQL?\") before understanding the problem.\n\n### Phase 2: Sharpen the Language\n\nIdentify vague or overloaded terms and pin them down **immediately**. This is the single highest-leverage activity — shared language reduces token waste and prevents misunderstandings.\n\n**Technique: The Canonical Term**\n\n- When the user uses multiple words for the same thing, pick one as canonical\n- List rejected alternatives under `_Avoid_`\n- Be opinionated — the glossary is prescriptive, not descriptive\n\n```\nUser: \"We need a way for users to save articles for later.\"\nYou: \"Let's pin that down. 'Save for later' could mean bookmarking, or a reading list, or offline download. Which one?\"\nUser: \"Like a reading list — they can come back to it.\"\nYou: \"Got it. Let's call it a **Reading List**. Avoid 'bookmark', 'save', 'favorites'.\"\n→ Write to CONTEXT.md immediately.\n```\n\n**Technique: The Boundary Test**\n\n- When a term is proposed, test its boundaries with edge cases\n- \"Does X include Y? What about Z?\"\n\n**Technique: The Code Cross-Reference**\n\n- When the user describes how something works, check if existing code agrees\n- Surface contradictions immediately\n\n### Phase 3: Probe Edge Cases\n\nBefore accepting any requirement, stress-test it with edge cases.\n\n**Edge Case Inventory:**\n\n- **Empty state**: What does the user see when there's nothing yet?\n- **Error state**: What happens when things go wrong?\n- **Extreme values**: What about 0? What about 10,000?\n- **Concurrency**: What if two people do this at the same time?\n- **Permissions**: Who can do this? Who cannot?\n- **Scale**: What changes at 10x the current volume?\n\n**Technique: The 5 Whys**\nWhen a requirement seems odd, dig deeper:\n\n```\nUser: \"We need real-time updates.\"\nYou: \"Why real-time?\"\nUser: \"Because users need to see changes immediately.\"\nYou: \"Why do they need to see changes immediately?\"\nUser: \"Because they're collaborating on the same document.\"\n→ Now you know the REAL requirement is collaboration, not real-time.\n```\n\n### Phase 4: Make Architecture Decisions\n\nWhen a design decision meets ALL three criteria, offer to record it as an ADR:\n\n1. **Hard to reverse** — changing your mind later has real cost\n2. **Surprising without context** — a future reader would wonder \"why?\"\n3. **The result of a real trade-off** — there were genuine alternatives\n\n**What qualifies for an ADR:**\n\n- Architecture shape (monorepo vs polyrepo, event sourcing vs CRUD)\n- Integration patterns between contexts\n- Technology choices with lock-in (database, message bus, auth provider)\n- Deliberate deviations from convention (\"we use raw SQL because...\")\n- Constraints not visible in code (\"we can't use X because compliance\")\n\n**ADR Format** (write to `docs/adr/NNNN-slug.md`):\n\n```markdown\n# {Short title of the decision}\n\n{1-3 sentences: context, decision, and why.}\n```\n\nOnly add optional sections (Status, Considered Options, Consequences) when they add genuine value. Most ADRs are a single paragraph.\n\n### Phase 5: Write the CONTEXT.md\n\nAfter the interview, synthesize everything into `CONTEXT.md`.\n\n**Format** (`CONTEXT.md` at project root):\n\n```markdown\n# {Project Name} Context\n\n{One or two sentence description of the project domain.}\n\n## Language\n\n**{Term}**:\n{One or two sentence definition of what it IS.}\n_Avoid_: {alternative terms that should not be used}\n\n## Decisions\n\n- [ADR 0001: {Title}](docs/adr/0001-slug.md) — {one-line summary}\n```\n\n**Rules:**\n\n- Be opinionated — pick the best term, ban the rest\n- Only include domain-specific terms (not general programming concepts)\n- Keep definitions tight — one or two sentences\n- Update inline during the conversation, don't batch\n- CONTEXT.md is a glossary, NOT a spec or implementation plan\n\n---\n\n## During the Conversation\n\n### DO\n\n- Challenge the user when they use vague terms — \"What do you mean by 'fast'?\"\n- Propose canonical terms and write them down immediately\n- Invent edge cases and probe boundaries\n- Offer ADRs sparingly (only when all 3 criteria are met)\n- Cross-reference with existing code if available\n- Call out contradictions between what the user says and what the code does\n\n### DON'T\n\n- Rush to implementation questions before understanding the problem\n- Write ADRs for trivial decisions\n- Let fuzzy language slide — pin it down now or pay later\n- Treat CONTEXT.md as a spec or scratch pad\n- Ask yes/no questions when open-ended ones would reveal more\n\n---\n\n## Output\n\nAfter the interview, the user should have:\n\n1. **CONTEXT.md** — shared language glossary (created or updated)\n2. **ADRs** (if needed) — architectural decisions in `docs/adr/`\n3. **Clear requirements** — edge cases explored, assumptions surfaced\n4. **Shared understanding** — you and the user now mean the same thing by the same words\n\n---\n\n## Integration with Mipham Code\n\n- **Memory System**: Key terms go to project memory for persistence across sessions\n- **Critical Thinking Layer**: Apply the 5-dimension self-check (evidence standard, equivalence verification, counter-example search, confidence calibration, depth check) to your own interview questions\n- **Workflow**: For complex projects, the output of this skill feeds directly into `/implement`\n" },
|
|
19
19
|
{ type: 'standard', raw: "---\nname: implement\ndescription: Build work from a spec or tickets with systematic discipline — TDD at pre-agreed seams, incremental verification, code review before commit. Use when implementing features, bugfixes, or any planned work.\nversion: 1.0.0\nuser-invocable: true\n---\n\n# Implement — Structured Build Execution\n\n融合 Superpowers executing-plans(计划审阅 + 隔离工作区)+ Matt Pocock implement(TDD 接缝 + 增量验证 + 提交前审查)。\n\n## When to Use\n\n- Implementing work from a written spec or ticket set\n- Executing a development plan with clear deliverables\n- Building a feature with predefined success criteria\n\n## When NOT to Use\n\n- Exploratory coding / prototyping → use `prototype` skill\n- Quick one-line fixes → just fix it\n- No spec or tickets exist → use `to-tickets` or `to-spec` first\n\n---\n\n## Step 1: Load and Review\n\n### 1.1 Ensure isolated workspace\n\nUse git worktree or a feature branch. Never implement on main/master without explicit consent.\n\n### 1.2 Read the plan/spec/tickets\n\nRead the full spec or ticket set. Understand:\n\n- What is being built?\n- What are the acceptance criteria?\n- What are the pre-agreed seams (where TDD should be applied)?\n\n### 1.3 Review critically\n\nBefore writing any code:\n\n- Are there gaps or ambiguities in the spec?\n- Are the success criteria testable?\n- Do you understand every instruction?\n\n**If concerns exist, raise them before starting.** Don't guess.\n\n---\n\n## Step 2: Execute Tasks\n\nFor each task in order:\n\n### 2.1 At pre-agreed seams: TDD\n\nWhere the spec specifies (or where interfaces are well-defined):\n\n1. Write a **failing test** that asserts the expected behavior\n2. Watch it fail (red)\n3. Write the **minimum code** to make it pass (green)\n4. Refactor if needed, keeping tests green\n\nUse the `tdd` skill for full red-green-refactor discipline.\n\n### 2.2 Incremental verification\n\nDuring implementation:\n\n- **Run typecheck** after each significant change: `pnpm typecheck`\n- **Run relevant test file** after each task: `pnpm test -- <file>`\n- **Don't wait** until everything is done to discover type errors\n\n### 2.3 One task at a time\n\n- Follow each step exactly — the plan has bite-sized steps for a reason\n- One change at a time. No \"while I'm here\" improvements.\n- Mark tasks as complete after verification passes\n\n---\n\n## Step 3: Final Verification\n\nAfter all tasks are complete:\n\n### 3.1 Full test suite\n\n```bash\npnpm test\n```\n\nAll tests must pass. If any fail, fix before proceeding.\n\n### 3.2 Lint and format\n\n```bash\npnpm lint\npnpm format\n```\n\nCI must be green.\n\n---\n\n## Step 4: Code Review\n\n**Before committing**, run code review:\n\nUse the `code-review` skill for a two-axis review:\n\n- **Standards**: Does the diff follow the repo's coding standards?\n- **Spec**: Does it faithfully implement the originating issue/spec?\n\nFix any findings before committing.\n\n---\n\n## Step 5: Commit\n\nCommit your work to the current branch.\n\n```bash\ngit add -A\ngit commit -m \"<type>: <description>\"\n```\n\n- Follow Conventional Commits\n- Reference the spec/ticket in the commit message\n- **Do NOT commit unless explicitly asked** (per CLAUDE.md §关键约束)\n\n---\n\n## When to Stop and Ask\n\n**STOP immediately when:**\n\n- A task is blocked (missing dependency, unclear instruction, verification fails repeatedly)\n- The spec has a critical gap that prevents starting\n- You don't understand an instruction\n- 3+ fix attempts fail — this may be an architectural issue\n\n**Ask for clarification rather than guessing.**\n\n---\n\n## Quick Reference\n\n| Step | Key Activities | Done When |\n| -------------- | ------------------------------------------------------------ | -------------------------------- |\n| **1. Review** | Load spec, isolate workspace, review critically | All concerns raised and resolved |\n| **2. Execute** | TDD at seams, incremental typecheck/test, one task at a time | All tasks complete and verified |\n| **3. Verify** | Full test suite, lint, format | CI-ready (all green) |\n| **4. Review** | Two-axis code review (standards + spec) | Findings addressed |\n| **5. Commit** | Conventional Commits, reference spec/ticket | Work committed to branch |\n" },
|
|
20
20
|
{ type: 'standard', raw: "---\nname: memory\ndescription: Read and write persistent memory files for context retention across sessions — one fact per file with frontmatter\nversion: 2.0.0\n---\n\n# Memory Skill\n\nManage persistent memory stored as markdown files with YAML frontmatter.\n\n## File Format\n\nEach memory is one `.md` file under the `memory/` directory:\n\n```markdown\n---\nname: <kebab-case-slug>\ndescription: <one-line summary>\nmetadata:\n type: user | feedback | project | reference\n---\n\n<the fact body>\n\n**Why:** <rationale>\n**How to apply:** <practical guidance>\n```\n\n## File Path Conventions\n\n- Directory: `~/.mipham/memory/` (user-level) or `./.mipham/memory/` (project-level)\n- Filename: `<name-slug>.md` (lowercase, hyphens)\n- Index: `MEMORY.md` — one line per memory file, maintained automatically\n\n## Operations\n\n### List Memories\n\nScan `MEMORY.md` index for available memories. The index has one line per memory:\n\n```markdown\n- [Title](file.md) — brief hook\n```\n\n### Read Memory\n\nRead the full markdown file including frontmatter. Parse YAML frontmatter for metadata.\n\n### Write Memory\n\n1. Check for existing file with same `name:` slug — update if found\n2. Create new file if no match\n3. Add/update entry in `MEMORY.md` index\n4. Never write what the repo already records (code structure, git history, CLAUDE.md)\n\n### Delete Memory\n\nRemove the file and its index entry. Use when a memory is incorrect or superseded.\n\n## Best Practices\n\n- **One fact per file** — atomic, focused, easy to find\n- **Descriptive slugs** — `npm-publish-workflow` not `memory-1`\n- **Link related memories** — use `[[slug-name]]` wikilinks in body\n- **Check before writing** — search existing memories to avoid duplicates\n- **Types matter**: `user` (who), `feedback` (corrections), `project` (goals), `reference` (external)\n\n## Example\n\n```markdown\n---\nname: api-rate-limit\ndescription: OpenAI API has 500 RPM limit on our tier\nmetadata:\n type: reference\n---\n\nThe OpenAI API key for production has a hard 500 requests/minute limit.\nExceeding it returns HTTP 429 with a Retry-After header.\n\n**Why:** We hit this in production during peak usage\n**How to apply:** Use exponential backoff; batch requests where possible\n```\n" },
|
|
21
|
-
{ type: 'standard', raw: "---\nname: mipham-code-setup\ndescription: Install, configure, diagnose, and troubleshoot Mipham Code — the multi-model open-core intelligent coding terminal. Covers setup wizard, API keys, providers, models, skills, permissions, workspace trust, shell/IDE integration, and first-run onboarding.\nversion: 2.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Write\n - Edit\n - Bash\n - Skill\n---\n\n# Mipham Code Setup — Executable Setup Workflow\n\n**Type**: Rigid — follow the decision tree exactly. Don't skip diagnostic phases.\n\n**Purpose**: Guide users from zero to fully configured Mipham Code. This skill is BOTH:\n\n1. A self-contained diagnostic + configuration workflow the AI can execute\n2. A reference for `/setup` command behavior and slash commands\n\n**Triggers**: \"setup mipham\", \"configure mipham\", \"install mipham code\", \"mipham not working\", \"mipham setup\", \"first time using mipham\", \"help me set up\", \"getting started\", `/setup`\n\n---\n\n## Phase 0: Environment Detection (ALWAYS RUN FIRST)\n\nBefore doing anything, run these diagnostic checks. Report results in a status table.\n\n### 0.1 — Detect Installation\n\n```bash\nwhich mipham 2>/dev/null\nmipham --version 2>/dev/null\nbun --version 2>/dev/null\nnode --version 2>/dev/null\n```\n\n### 0.2 — Detect Configuration\n\n```bash\nls -la .mipham/config.yml 2>/dev/null\nls -la ~/.mipham/config.yml 2>/dev/null\nls -la MIPHAM.md 2>/dev/null\nls -la CLAUDE.md 2>/dev/null\n```\n\n### 0.3 — Detect API Keys\n\n```bash\nenv | grep -E 'ANTHROPIC_API_KEY|OPENAI_API_KEY|DEEPSEEK_API_KEY|QWEN_API_KEY|DOUBAO_API_KEY|HUNYUAN_API_KEY|GEMINI_API_KEY' | cut -d= -f1\n```\n\n### 0.4 — Detect Skills & Permissions\n\n```bash\nls .mipham/skills/ 2>/dev/null\ncat .mipham/config.yml 2>/dev/null | grep -E 'permission|trust' || echo \"no config\"\n```\n\n### 0.5 — Detect Workspace Trust\n\n```bash\ncat ~/.mipham/trusted-workspaces.json 2>/dev/null || echo \"no trust store\"\n```\n\n### Status Report Format\n\nAfter detection, present results as:\n\n```\n── Mipham Code Status ──\n\nInstallation: [✅/⬜] mipham CLI [✅/⬜] Bun [✅/⬜] Node.js\nProject: [✅/⬜] .mipham/ [✅/⬜] config.yml [✅/⬜] MIPHAM.md\nUser Config: [✅/⬜] ~/.mipham/config.yml\nAPI Keys: [N] set (list names or \"none\")\nSkills: [N] installed\nPermissions: [mode] (default/acceptEdits/plan/auto/bypassPermissions)\nTrust: [✅/⬜] workspace trusted\n```\n\nThen proceed to ONLY the phases where something is missing. Don't re-run already-configured steps unless asked.\n\n---\n\n## Phase 1: Installation\n\n**Trigger**: `mipham --version` fails.\n\n### Option A: Quick Install (recommended)\n\n```bash\ncurl -fsSL https://mipham.ai/install.sh | bash\n```\n\nThen restart the shell or run:\n\n```bash\nexport PATH=\"$HOME/.mipham/bin:$PATH\"\n```\n\n### Option B: npm Global Install\n\n```bash\nnpm install -g @miphamai/cli\nmipham\n```\n\n### Option C: From Source (developers)\n\n```bash\ngit clone https://github.com/One-Mipham/mipham-code\ncd mipham-code/apps/cli\nbun install && bun run bin/mipham\n```\n\n### ✅ Verification\n\n```bash\nmipham --version # Should print version ≥ 0.24.0\nmipham --help # Should print usage\n```\n\n---\n\n## Phase 2: Project Initialization\n\n**Trigger**: Missing `.mipham/` directory or `MIPHAM.md`.\n\n### 2.1 — Create .mipham/ directory\n\n```bash\nmkdir -p .mipham\n```\n\n### 2.2 — Create .mipham/config.yml\n\nWrite a minimal config. Ask the user which provider they want to use first, or pick a sensible default:\n\n```yaml\ndefaultProvider: anthropic\ndefaultModel: claude-sonnet-4-6\npermission: default\n```\n\n**Providers available** (alphabetical):\n\n| Provider | Type | Example Models |\n| --------- | ------------- | -------------------------------------- |\n| anthropic | Native SDK | Claude Haiku 4.5, Sonnet 4.6, Opus 4.8 |\n| deepseek | OpenAI Compat | V4 Flash, V4 Pro |\n| doubao | OpenAI Compat | Seed 1.6, Seed 2.0 |\n| gemini | OpenAI Compat | 3.0 Flash, 3.0 Pro, 2.5 Pro |\n| hunyuan | OpenAI Compat | Lite, TurboS, 2.0, T1 |\n| openai | OpenAI Compat | GPT-5.4 Mini, GPT-5.4, GPT-5.5, Codex |\n| qwen | OpenAI Compat | Qwen Plus, Qwen Max |\n\n### 2.3 — Create MIPHAM.md (optional but recommended)\n\nCreate `MIPHAM.md` in project root to define AI personality:\n\n```markdown\n# MIPHAM.md\n\n## Project Context\n\n- **Project**: [name]\n- **Language**: [zh-CN / en]\n- **Stack**: [TypeScript / Python / etc.]\n\n## Preferences\n\n- Code style: [e.g., functional, OOP]\n- Comment language: [e.g., English]\n- Test framework: [e.g., Vitest]\n```\n\n### ✅ Verification\n\n```bash\nls -la .mipham/config.yml MIPHAM.md\n```\n\n---\n\n## Phase 3: API Key Configuration\n\n**Trigger**: Missing API keys in environment.\n\n### 3.1 — Identify Required Providers\n\nAsk the user which providers they plan to use. For each, set the env var.\n\n### 3.2 — Set API Keys\n\n**Recommended: Environment variables** (not in config files — avoids accidental commits):\n\n```bash\nexport ANTHROPIC_API_KEY=\"sk-ant-...\"\nexport OPENAI_API_KEY=\"sk-...\"\nexport DEEPSEEK_API_KEY=\"sk-...\"\nexport QWEN_API_KEY=\"sk-...\"\nexport DOUBAO_API_KEY=\"...\"\nexport HUNYUAN_API_KEY=\"...\"\nexport GEMINI_API_KEY=\"...\"\n```\n\nAdd these to `~/.zshrc` or `~/.bashrc` for persistence:\n\n```bash\necho 'export ANTHROPIC_API_KEY=\"sk-ant-...\"' >> ~/.zshrc\nsource ~/.zshrc\n```\n\n**Alternative**: Store in `~/.mipham/config.yml`:\n\n```yaml\nproviders:\n - id: anthropic\n apiKey: $ANTHROPIC_API_KEY\n - id: openai\n apiKey: $OPENAI_API_KEY\n```\n\n### 3.3 — Verify Keys\n\n```bash\nenv | grep API_KEY\n```\n\n### ❗Security Rules\n\n- NEVER hardcode API keys in project config files (`.mipham/config.yml` in project root should use `$ENV_VAR` references, not raw keys)\n- NEVER commit API keys to git\n- Add to `.gitignore`: `.mipham/config.yml` (if it contains keys), `.env`, `*.pem`\n\n---\n\n## Phase 4: Provider & Model Configuration\n\n**Trigger**: Need to set default or enable/disable providers.\n\n### 4.1 — Set Default Provider & Model\n\nIn `.mipham/config.yml`:\n\n```yaml\ndefaultProvider: anthropic\ndefaultModel: claude-sonnet-4-6\n```\n\nOr use slash commands:\n\n```\n/model # Interactive model picker (Ctrl+P)\n/switch # Switch provider\n/providers # List all configured providers\n```\n\n### 4.2 — Enable/Disable Providers\n\n```yaml\nproviders:\n - id: anthropic\n status: active\n - id: openai\n status: active\n - id: deepseek\n status: disabled\n```\n\n### ✅ Verification\n\n```\n/model # Should show available models\n/providers # Should list active providers\n```\n\n---\n\n## Phase 5: Skills Installation\n\n**Trigger**: No or few skills installed.\n\n### 5.1 — Built-in Skills\n\nMipham Code ships with 28 built-in skills loaded automatically:\n\n- **Standard (22)**: code-review, codebase-design, compassionate-communication, debug-loop, doc-generator, domain-modeling, github-ops, grill-with-docs, implement, memory, mipham-code-setup, research, safe-coding, security-review, self-review, superpower, tdd, to-spec, triage, trim-process-prose, web-access, web-search\n- **Mipham (6)**: doc-sync, om-artifact, om-model-optimize, om-security, save-to-wiki, self-audit\n\n### 5.2 — Community Skills\n\nInstall from the community registry:\n\n```\n/setup 4 # Guided skill browser\n```\n\nOr directly:\n\n```bash\n# Skills are loaded from:\n# - apps/cli/skills/standard/ (built-in standard)\n# - apps/cli/skills/mipham/ (built-in mipham)\n# - ~/.mipham/skills/ (user-installed)\n# - .mipham/skills/ (project-local)\n```\n\n### 5.3 — Install Specific Skills\n\n```\n/skills install <name> # Install from registry\n/skills list # List available\n/skills search <query> # Search registry\n```\n\n### ✅ Verification\n\n```\n/skills list # Should show installed skills with counts\n```\n\n---\n\n## Phase 6: Permissions Configuration\n\n**Trigger**: Permission mode not configured or wrong for use case.\n\n### 6.1 — Permission Modes\n\n| Mode | Behavior | Use Case |\n| ------------------- | -------------------------------------- | ----------------------------------------- |\n| `default` | Ask-first tools are refused (see note) | Normal development (recommended) |\n| `acceptEdits` | Auto-allow edits, ask for other tools | Active coding sessions |\n| `plan` | Plan-only, no tool execution | Design & architecture work |\n| `auto` | A classifier rules on every call | Long unattended runs you still want gated |\n| `bypassPermissions` | Skip all checks | ⚠️ Only for fully trusted codebases |\n\n**Note on `default`**: Mipham Code has no interactive approval prompt, so \"ask\"\nmeans the call is **refused** with a message naming the mode — it is not queued\nfor your answer. That makes `default` the strictest _usable_ mode for Bash and\nfile writes; `auto` is the mode that lets gated calls proceed without a human,\nby having a classifier rule on each one.\n\n**What `auto` actually gates.** Reads (Read/Grep/Glob) are never sent to the\nclassifier — gating them would make `auto` the only mode in the ladder that cannot\nopen a file without a round-trip to another model. Everything else that the static\nchain would refuse goes to the classifier, which can only **lift** a refusal: a\ndeny rule or an `ask` rule is never overridden. If the classifier cannot be reached\nor answers unusably, the call is refused (fail-closed) with a message saying the\nrefusal is _not_ a policy decision and can be retried.\n\n### 6.2 — Configure\n\nPress **Shift+Tab** to change the mode live; it cycles\n`default → acceptEdits → plan → auto` and lasts for the session only.\n`bypassPermissions` is a legal mode but is deliberately **not** on the wheel —\nit is reached by naming it in config, where the user has said what they mean.\n\nTo persist a mode, name it in `~/.mipham/config.yml`:\n\n```yaml\npermission: default\n```\n\nOr in `~/.mipham/settings.json` as `permissions.defaultMode` (the key Claude Code\nusers already have). Any mode name from the table above is accepted in either,\nincluding `bypassPermissions`.\n\nA **project-level** `.mipham/config.yml` cannot set a mode — that file arrives with\nthe code, so whoever wrote the repository would be choosing the approval gate. A\nmode found there is ignored and reported; the fix is to move the line to the user\nlevel, or to pass `--permission <mode>` for one invocation.\n\nOr via slash command:\n\n```\n/permissions # View current settings\n/setup 5 # Permission setup wizard\n```\n\n### 6.3 — CI/CD Safety\n\nFor CI/CD environments, use the `default` mode (the daemon default): headless\nsessions never prompt, so `ask`-level tools (Bash/Write/Edit) are blocked rather\nthan auto-approved.\n\n### ✅ Verification\n\n```\n/permissions # Should show current mode\n```\n\n---\n\n## Phase 7: Workspace Trust\n\n**Trigger**: Untrusted workspace (prompted on startup in v0.24.3+).\n\n### 7.1 — Understanding Workspace Trust\n\nWorkspace trust is a security mechanism that prevents AI from operating in untrusted directories. Trust is **hierarchical**: trusting `/Users/me/Projects` implicitly trusts all subdirectories.\n\n### 7.2 — Trust a Workspace\n\n**Interactive**: Accept the trust prompt when launching Mipham Code in a new directory.\n\n**Manual**:\n\n```\n/trust # Show trust status\n/trust add <dir> # Trust a directory\n/trust remove <dir> # Revoke trust\n```\n\n### 7.3 — Trust Store\n\n```\n~/.mipham/trusted-workspaces.json\n```\n\n### 7.4 — Auto-Trust for Worktrees\n\nWhen using git worktrees, Mipham Code automatically trusts worktree directories if the parent workspace is already trusted (via `EnterWorktree`).\n\n### ✅ Verification\n\n```\n/trust # Should show \"✅ Yes\" for current directory\n```\n\n---\n\n## Phase 8: Shell & IDE Integration\n\n**Trigger**: Want terminal integration, aliases, or IDE plugins.\n\n### 8.1 — Shell Alias\n\nAdd to `~/.zshrc` or `~/.bashrc`:\n\n```bash\nalias mipham='cd ~/your-project && bun run ~/path/to/mipham-code/apps/cli/bin/mipham.ts'\n# Or if installed globally:\nalias mipham='mipham'\n```\n\n### 8.2 — VS Code Integration\n\nRun `/ide` to auto-generate `.vscode/` config files:\n\n- `settings.json` — terminal profile \"mipham\" using Bun\n- `keybindings.json` — Cmd+Esc to focus terminal, Cmd+Shift+M for new terminal\n- `extensions.json` — recommends `miphamai.mipham-code` extension\n\nTo use after generation:\n\n1. Restart VS Code (or Cmd+Shift+P → Reload Window)\n2. Open terminal: Ctrl+` or Cmd+Esc\n3. Select \"mipham\" profile from terminal dropdown\n\nInstall the VS Code extension:\n\n```bash\ncode --install-extension miphamai.mipham-code\n```\n\n### 8.3 — JetBrains Integration\n\nSettings → Tools → Terminal → Shell path → `bun run mipham`\n\n### 8.4 — Terminal Setup\n\n```\n/terminal-setup # Shell & terminal config wizard\n/setup 6 # Shell integration (part of full wizard)\n```\n\n### ✅ Verification\n\n```bash\nwhich mipham # Should resolve\n# In VS Code: Ctrl+` → select \"mipham\" profile\n```\n\n---\n\n## Phase 9: Full Verification\n\nRun after all configuration phases complete.\n\n### 9.1 — System Diagnostics\n\n```\n/doctor # System diagnostics check\n```\n\n### 9.2 — End-to-End Test\n\nStart a conversation and verify:\n\n1. Model responds (not stuck on \"connecting...\")\n2. File tools work: \"read CLAUDE.md\"\n3. Bash works: \"list files in current directory\"\n4. Skills load: `/skills list`\n\n### 9.3 — Common Issues & Fixes\n\n| Symptom | Diagnosis | Fix |\n| ------------------------- | -------------------------------------- | ------------------------------------------------ |\n| \"Provider not registered\" | Missing or invalid API key | `env \\| grep API_KEY`; check key format |\n| \"Model not found\" | Model ID mismatch or disabled provider | `/models` to list available; `/switch` to change |\n| Slow responses | Large model, network, or context full | `/fast on` or switch to Flash model; `/compact` |\n| Context full | Too many messages in history | `/compact` to compress; `/clear` to reset |\n| Permission denied | Tool blocked by permission mode | `/permissions` to check; adjust mode |\n| \"Workspace not trusted\" | New directory, not yet trusted | Accept startup prompt or run `/trust` |\n| MCP tools not available | Server not connected | `/mcp connect <name>` or check config |\n| Update not applying | Cached binary | `mipham update --force` then restart |\n| Config changes ignored | YAML syntax error | Validate with `mipham --check-config` |\n\n### 9.4 — Get Help\n\n```\n/help # Full command reference\n/setup # Re-run setup wizard\n/doctor # Run diagnostics\n```\n\nChat-based help: \"help me configure X\" or \"why isn't Y working?\"\n\n---\n\n## Quick Reference: Essential Slash Commands\n\n| Category | Command | Purpose |\n| ------------- | ----------------- | ------------------------------------------------------ |\n| **Setup** | `/setup` | Full 6-step setup wizard |\n| | `/setup 1` | Initialize project (.mipham/ + MIPHAM.md + config.yml) |\n| | `/setup 2` | Configure providers & API keys |\n| | `/setup 3` | Choose default model |\n| | `/setup 4` | Browse & install skills |\n| | `/setup 5` | Configure permissions |\n| | `/setup 6` | Shell & IDE integration |\n| **Diagnosis** | `/doctor` | System diagnostics |\n| | `/trust` | Workspace trust status |\n| | `/permissions` | Tool permission settings |\n| **Model** | `/model` | Interactive model picker (Ctrl+P) |\n| | `/switch` | Switch provider |\n| | `/models` | List available models |\n| **Session** | `/clear` | Reset conversation |\n| | `/compact` | Compress context |\n| | `/rename` | Rename session |\n| **Workflow** | `/plan` | Enter plan mode |\n| | `/review` | Code review |\n| | `/todos` | Task list |\n| **IDE** | `/ide` | Generate VS Code integration files |\n| | `/terminal-setup` | Shell & terminal config |\n| **Skills** | `/skills list` | List installed skills |\n| | `/skills search` | Search skill registry |\n| | `/skills install` | Install a skill |\n\n---\n\n## Post-Setup: What to Do Next\n\nAfter configuration is verified:\n\n1. **Initialize your project**: \"help me understand this codebase\"\n2. **Set up CLAUDE.md**: `/init` to generate project documentation for the AI\n3. **Install relevant skills**: `/setup 4` or `/skills search`\n4. **Configure MCP servers**: `/mcp connect` for external tool integration\n5. **Start coding**: Just start a conversation — the AI will use tools and skills automatically\n" },
|
|
21
|
+
{ type: 'standard', raw: "---\nname: mipham-code-setup\ndescription: Install, configure, diagnose, and troubleshoot Mipham Code — the multi-model open-core intelligent coding terminal. Covers setup wizard, API keys, providers, models, skills, permissions, workspace trust, shell/IDE integration, and first-run onboarding.\nversion: 2.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Write\n - Edit\n - Bash\n - Skill\n---\n\n# Mipham Code Setup — Executable Setup Workflow\n\n**Type**: Rigid — follow the decision tree exactly. Don't skip diagnostic phases.\n\n**Purpose**: Guide users from zero to fully configured Mipham Code. This skill is BOTH:\n\n1. A self-contained diagnostic + configuration workflow the AI can execute\n2. A reference for `/setup` command behavior and slash commands\n\n**Triggers**: \"setup mipham\", \"configure mipham\", \"install mipham code\", \"mipham not working\", \"mipham setup\", \"first time using mipham\", \"help me set up\", \"getting started\", `/setup`\n\n---\n\n## Phase 0: Environment Detection (ALWAYS RUN FIRST)\n\nBefore doing anything, run these diagnostic checks. Report results in a status table.\n\n### 0.1 — Detect Installation\n\n```bash\nwhich mipham 2>/dev/null\nmipham --version 2>/dev/null\nbun --version 2>/dev/null\nnode --version 2>/dev/null\n```\n\n### 0.2 — Detect Configuration\n\n```bash\nls -la .mipham/config.yml 2>/dev/null\nls -la ~/.mipham/config.yml 2>/dev/null\nls -la MIPHAM.md 2>/dev/null\nls -la CLAUDE.md 2>/dev/null\n```\n\n### 0.3 — Detect API Keys\n\n```bash\nenv | grep -E 'ANTHROPIC_API_KEY|OPENAI_API_KEY|DEEPSEEK_API_KEY|QWEN_API_KEY|DOUBAO_API_KEY|HUNYUAN_API_KEY|GEMINI_API_KEY' | cut -d= -f1\n```\n\n### 0.4 — Detect Skills & Permissions\n\n```bash\nls .mipham/skills/ 2>/dev/null\ncat .mipham/config.yml 2>/dev/null | grep -E 'permission|trust' || echo \"no config\"\n```\n\n### 0.5 — Detect Workspace Trust\n\n```bash\ncat ~/.mipham/trusted-workspaces.json 2>/dev/null || echo \"no trust store\"\n```\n\n### Status Report Format\n\nAfter detection, present results as:\n\n```\n── Mipham Code Status ──\n\nInstallation: [✅/⬜] mipham CLI [✅/⬜] Bun [✅/⬜] Node.js\nProject: [✅/⬜] .mipham/ [✅/⬜] config.yml [✅/⬜] MIPHAM.md\nUser Config: [✅/⬜] ~/.mipham/config.yml\nAPI Keys: [N] set (list names or \"none\")\nSkills: [N] installed\nPermissions: [mode] (default/acceptEdits/plan/auto/bypassPermissions)\nTrust: [✅/⬜] workspace trusted\n```\n\nThen proceed to ONLY the phases where something is missing. Don't re-run already-configured steps unless asked.\n\n---\n\n## Phase 1: Installation\n\n**Trigger**: `mipham --version` fails.\n\n### Option A: Quick Install (recommended)\n\n```bash\ncurl -fsSL https://mipham.ai/install.sh | bash\n```\n\nThen restart the shell or run:\n\n```bash\nexport PATH=\"$HOME/.mipham/bin:$PATH\"\n```\n\n### Option B: npm Global Install\n\n```bash\nnpm install -g @miphamai/cli\nmipham\n```\n\n### Option C: From Source (developers)\n\n```bash\ngit clone https://github.com/One-Mipham/mipham-code\ncd mipham-code/apps/cli\nbun install && bun run bin/mipham\n```\n\n### ✅ Verification\n\n```bash\nmipham --version # Should print version ≥ 0.24.0\nmipham --help # Should print usage\n```\n\n---\n\n## Phase 2: Project Initialization\n\n**Trigger**: Missing `.mipham/` directory or `MIPHAM.md`.\n\n### 2.1 — Create .mipham/ directory\n\n```bash\nmkdir -p .mipham\n```\n\n### 2.2 — Create .mipham/config.yml\n\nWrite a minimal config. Ask the user which provider they want to use first, or pick a sensible default:\n\n```yaml\ndefaultProvider: anthropic\ndefaultModel: claude-sonnet-4-6\npermission: default\n```\n\n**Providers available** (alphabetical):\n\n| Provider | Type | Example Models |\n| --------- | ------------- | -------------------------------------- |\n| anthropic | Native SDK | Claude Haiku 4.5, Sonnet 4.6, Opus 4.8 |\n| deepseek | OpenAI Compat | V4 Flash, V4 Pro |\n| doubao | OpenAI Compat | Seed 1.6, Seed 2.0 |\n| gemini | OpenAI Compat | 3.0 Flash, 3.0 Pro, 2.5 Pro |\n| hunyuan | OpenAI Compat | Lite, TurboS, 2.0, T1 |\n| openai | OpenAI Compat | GPT-5.4 Mini, GPT-5.4, GPT-5.5, Codex |\n| qwen | OpenAI Compat | Qwen Plus, Qwen Max |\n\n### 2.3 — Create MIPHAM.md (optional but recommended)\n\nCreate `MIPHAM.md` in project root to define AI personality:\n\n```markdown\n# MIPHAM.md\n\n## Project Context\n\n- **Project**: [name]\n- **Language**: [zh-CN / en]\n- **Stack**: [TypeScript / Python / etc.]\n\n## Preferences\n\n- Code style: [e.g., functional, OOP]\n- Comment language: [e.g., English]\n- Test framework: [e.g., Vitest]\n```\n\n### ✅ Verification\n\n```bash\nls -la .mipham/config.yml MIPHAM.md\n```\n\n---\n\n## Phase 3: API Key Configuration\n\n**Trigger**: Missing API keys in environment.\n\n### 3.1 — Identify Required Providers\n\nAsk the user which providers they plan to use. For each, set the env var.\n\n### 3.2 — Set API Keys\n\n**Recommended: Environment variables** (not in config files — avoids accidental commits):\n\n```bash\nexport ANTHROPIC_API_KEY=\"sk-ant-...\"\nexport OPENAI_API_KEY=\"sk-...\"\nexport DEEPSEEK_API_KEY=\"sk-...\"\nexport QWEN_API_KEY=\"sk-...\"\nexport DOUBAO_API_KEY=\"...\"\nexport HUNYUAN_API_KEY=\"...\"\nexport GEMINI_API_KEY=\"...\"\n```\n\nAdd these to `~/.zshrc` or `~/.bashrc` for persistence:\n\n```bash\necho 'export ANTHROPIC_API_KEY=\"sk-ant-...\"' >> ~/.zshrc\nsource ~/.zshrc\n```\n\n**Alternative**: Store in `~/.mipham/config.yml`:\n\n```yaml\nproviders:\n - id: anthropic\n apiKey: $ANTHROPIC_API_KEY\n - id: openai\n apiKey: $OPENAI_API_KEY\n```\n\n### 3.3 — Verify Keys\n\n```bash\nenv | grep API_KEY\n```\n\n### ❗Security Rules\n\n- NEVER hardcode API keys in project config files (`.mipham/config.yml` in project root should use `$ENV_VAR` references, not raw keys)\n- NEVER commit API keys to git\n- Add to `.gitignore`: `.mipham/config.yml` (if it contains keys), `.env`, `*.pem`\n\n---\n\n## Phase 4: Provider & Model Configuration\n\n**Trigger**: Need to set default or enable/disable providers.\n\n### 4.1 — Set Default Provider & Model\n\nIn `.mipham/config.yml`:\n\n```yaml\ndefaultProvider: anthropic\ndefaultModel: claude-sonnet-4-6\n```\n\nOr use slash commands:\n\n```\n/model # Interactive model picker (Ctrl+P)\n/switch # Switch provider\n/providers # List all configured providers\n```\n\n### 4.2 — Enable/Disable Providers\n\n```yaml\nproviders:\n - id: anthropic\n status: active\n - id: openai\n status: active\n - id: deepseek\n status: disabled\n```\n\n### ✅ Verification\n\n```\n/model # Should show available models\n/providers # Should list active providers\n```\n\n---\n\n## Phase 5: Skills Installation\n\n**Trigger**: No or few skills installed.\n\n### 5.1 — Built-in Skills\n\nMipham Code ships with 28 built-in skills loaded automatically:\n\n- **Standard (22)**: code-review, codebase-design, compassionate-communication, debug-loop, doc-generator, domain-modeling, github-ops, grill-with-docs, implement, memory, mipham-code-setup, research, safe-coding, security-review, self-review, superpower, tdd, to-spec, triage, trim-process-prose, web-access, web-search\n- **Mipham (6)**: doc-sync, om-artifact, om-model-optimize, om-security, save-to-wiki, self-audit\n\n### 5.2 — Community Skills\n\nInstall from the community registry:\n\n```\n/setup 4 # Guided skill browser\n```\n\nOr directly:\n\n```bash\n# Skills are loaded from:\n# - apps/cli/skills/standard/ (built-in standard)\n# - apps/cli/skills/mipham/ (built-in mipham)\n# - ~/.mipham/skills/ (user-installed)\n# - .mipham/skills/ (project-local)\n```\n\n### 5.3 — Install Specific Skills\n\n```\n/skills install <name> # Install from registry\n/skills list # List available\n/skills search <query> # Search registry\n```\n\n### ✅ Verification\n\n```\n/skills list # Should show installed skills with counts\n```\n\n---\n\n## Phase 6: Permissions Configuration\n\n**Trigger**: Permission mode not configured or wrong for use case.\n\n### 6.1 — Permission Modes\n\n| Mode | Behavior | Use Case |\n| ------------------- | -------------------------------------- | ----------------------------------------- |\n| `default` | Ask-first tools are refused (see note) | Normal development (recommended) |\n| `acceptEdits` | Auto-allow edits, ask for other tools | Active coding sessions |\n| `plan` | Plan-only, no tool execution | Design & architecture work |\n| `auto` | A classifier rules on every call | Long unattended runs you still want gated |\n| `bypassPermissions` | Skip all checks | ⚠️ Only for fully trusted codebases |\n\n**Note on `default`**: Mipham Code has no interactive approval prompt, so \"ask\"\nmeans the call is **refused** with a message naming the mode — it is not queued\nfor your answer. That makes `default` the strictest _usable_ mode for Bash and\nfile writes; `auto` is the mode that lets gated calls proceed without a human,\nby having a classifier rule on each one.\n\n**What `auto` actually gates.** Reads (Read/Grep/Glob) are never sent to the\nclassifier — gating them would make `auto` the only mode in the ladder that cannot\nopen a file without a round-trip to another model. Everything else that the static\nchain would refuse goes to the classifier, which can only **lift** a refusal: a\ndeny rule or an `ask` rule is never overridden. If the classifier cannot be reached\nor answers unusably, the call is refused (fail-closed) with a message saying the\nrefusal is _not_ a policy decision and can be retried.\n\n### 6.2 — Configure\n\nPress **Shift+Tab** to change the mode live; it cycles\n`default → acceptEdits → plan → auto` and lasts for the session only.\n`bypassPermissions` is a legal mode but is deliberately **not** on the wheel —\nit is reached by naming it in config, where the user has said what they mean.\n\nTo persist a mode, name it in `~/.mipham/config.yml`:\n\n```yaml\npermission: default\n```\n\nOr in `~/.mipham/settings.json` as `permissions.defaultMode` (the key Claude Code\nusers already have). Any mode name from the table above is accepted in either,\nincluding `bypassPermissions`.\n\nA **project-level** `.mipham/config.yml` cannot set a mode — that file arrives with\nthe code, so whoever wrote the repository would be choosing the approval gate. A\nmode found there is ignored and reported; the fix is to move the line to the user\nlevel, or to pass `--permission <mode>` for one invocation.\n\nOr via slash command:\n\n```\n/permissions # View current settings\n/setup 5 # Permission setup wizard\n```\n\n### 6.3 — CI/CD Safety\n\nFor CI/CD environments, use the `default` mode (the daemon default): headless\nsessions never prompt, so `ask`-level tools (Bash/Write/Edit) are blocked rather\nthan auto-approved.\n\n### ✅ Verification\n\n```\n/permissions # Should show current mode\n```\n\n---\n\n## Phase 7: Workspace Trust\n\n**Trigger**: Untrusted workspace (prompted on startup in v0.24.3+).\n\n### 7.1 — Understanding Workspace Trust\n\nWorkspace trust is a security mechanism that prevents AI from operating in untrusted directories. Trust is **hierarchical**: trusting `/Users/me/Projects` implicitly trusts all subdirectories.\n\n### 7.2 — Trust a Workspace\n\n**Interactive**: Accept the trust prompt when launching Mipham Code in a new directory.\n\n**Manual**:\n\n```\n/trust # Show trust status\n/trust add <dir> # Trust a directory\n/trust remove <dir> # Revoke trust\n```\n\n### 7.3 — Trust Store\n\n```\n~/.mipham/trusted-workspaces.json\n```\n\n### 7.4 — Auto-Trust for Worktrees\n\nWhen using git worktrees, Mipham Code automatically trusts worktree directories if the parent workspace is already trusted (via `EnterWorktree`).\n\n### ✅ Verification\n\n```\n/trust # Should show \"✅ Yes\" for current directory\n```\n\n---\n\n## Phase 8: Shell & IDE Integration\n\n**Trigger**: Want terminal integration, aliases, or IDE plugins.\n\n### 8.1 — Shell Alias\n\nAdd to `~/.zshrc` or `~/.bashrc`:\n\n```bash\nalias mipham='cd ~/your-project && bun run ~/path/to/mipham-code/apps/cli/bin/mipham.ts'\n# Or if installed globally:\nalias mipham='mipham'\n```\n\n### 8.2 — VS Code Integration\n\nRun `/ide` to auto-generate `.vscode/` config files:\n\n- `settings.json` — terminal profile \"mipham\" using Bun\n- `keybindings.json` — Cmd+Esc to focus terminal, Cmd+Shift+M for new terminal\n- `extensions.json` — recommends `miphamai.mipham-code` extension\n\nTo use after generation:\n\n1. Restart VS Code (or Cmd+Shift+P → Reload Window)\n2. Open terminal: Ctrl+` or Cmd+Esc\n3. Select \"mipham\" profile from terminal dropdown\n\nInstall the VS Code extension:\n\n```bash\ncode --install-extension miphamai.mipham-code\n```\n\n### 8.3 — JetBrains Integration\n\nSettings → Tools → Terminal → Shell path → `bun run mipham`\n\n### 8.4 — Terminal Setup\n\n```\n/terminal-setup # Shell & terminal config wizard\n/setup 6 # Shell integration (part of full wizard)\n```\n\n### ✅ Verification\n\n```bash\nwhich mipham # Should resolve\n# In VS Code: Ctrl+` → select \"mipham\" profile\n```\n\n---\n\n## Phase 9: Full Verification\n\nRun after all configuration phases complete.\n\n### 9.1 — System Diagnostics\n\n```\n/doctor # System diagnostics check\n```\n\n### 9.2 — End-to-End Test\n\nStart a conversation and verify:\n\n1. Model responds (not stuck on \"connecting...\")\n2. File tools work: \"read CLAUDE.md\"\n3. Bash works: \"list files in current directory\"\n4. Skills load: `/skills list`\n\n### 9.3 — Common Issues & Fixes\n\n| Symptom | Diagnosis | Fix |\n| ------------------------- | -------------------------------------- | ------------------------------------------------ |\n| \"Provider not registered\" | Missing or invalid API key | `env \\| grep API_KEY`; check key format |\n| \"Model not found\" | Model ID mismatch or disabled provider | `/models` to list available; `/switch` to change |\n| Slow responses | Large model, network, or context full | Switch to Flash model; `/compact` |\n| Context full | Too many messages in history | `/compact` to compress; `/clear` to reset |\n| Permission denied | Tool blocked by permission mode | `/permissions` to check; adjust mode |\n| \"Workspace not trusted\" | New directory, not yet trusted | Accept startup prompt or run `/trust` |\n| MCP tools not available | Server not connected | `/mcp connect <name>` or check config |\n| Update not applying | Cached binary | `mipham update --force` then restart |\n| Config changes ignored | YAML syntax error | Validate with `mipham --check-config` |\n\n### 9.4 — Get Help\n\n```\n/help # Full command reference\n/setup # Re-run setup wizard\n/doctor # Run diagnostics\n```\n\nChat-based help: \"help me configure X\" or \"why isn't Y working?\"\n\n---\n\n## Quick Reference: Essential Slash Commands\n\n| Category | Command | Purpose |\n| ------------- | ----------------- | ------------------------------------------------------ |\n| **Setup** | `/setup` | Full 6-step setup wizard |\n| | `/setup 1` | Initialize project (.mipham/ + MIPHAM.md + config.yml) |\n| | `/setup 2` | Configure providers & API keys |\n| | `/setup 3` | Choose default model |\n| | `/setup 4` | Browse & install skills |\n| | `/setup 5` | Configure permissions |\n| | `/setup 6` | Shell & IDE integration |\n| **Diagnosis** | `/doctor` | System diagnostics |\n| | `/trust` | Workspace trust status |\n| | `/permissions` | Tool permission settings |\n| **Model** | `/model` | Interactive model picker (Ctrl+P) |\n| | `/switch` | Switch provider |\n| | `/models` | List available models |\n| **Session** | `/clear` | Reset conversation |\n| | `/compact` | Compress context |\n| | `/rename` | Rename session |\n| **Workflow** | `/plan` | Enter plan mode |\n| | `/review` | Code review |\n| | `/todos` | Task list |\n| **IDE** | `/ide` | Generate VS Code integration files |\n| | `/terminal-setup` | Shell & terminal config |\n| **Skills** | `/skills list` | List installed skills |\n| | `/skills search` | Search skill registry |\n| | `/skills install` | Install a skill |\n\n---\n\n## Post-Setup: What to Do Next\n\nAfter configuration is verified:\n\n1. **Initialize your project**: \"help me understand this codebase\"\n2. **Set up CLAUDE.md**: `/init` to generate project documentation for the AI\n3. **Install relevant skills**: `/setup 4` or `/skills search`\n4. **Configure MCP servers**: `/mcp connect` for external tool integration\n5. **Start coding**: Just start a conversation — the AI will use tools and skills automatically\n" },
|
|
22
22
|
{ type: 'standard', raw: "---\nname: research\ndescription: Deep research against primary sources, executed as a background agent. Collects findings into a single cited Markdown file. Use for investigation that requires reading official docs, source code, specs, or first-party APIs — not secondary summaries.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - WebSearch\n - WebFetch\n - Agent\n - Bash\n - Write\n - Read\n---\n\n# Research — Background Deep Research\n\n融合 Mipham web-search v3.0(查询构建+验证)+ Matt Pocock research(后台代理+一手来源+Markdown 报告)。\n\n## When to Use\n\n- \"Research X for me\"\n- \"Find out everything about Y from primary sources\"\n- \"Investigate Z and write up findings\"\n- Any question where googling + reading multiple sources is the right answer\n\n## When NOT to Use\n\n- Quick fact lookup → use `/web-search` directly\n- Question answerable from code already in context\n- Pure logic/algorithmic question\n\n---\n\n## Phase 0: Route\n\n```\nResearch task is...\n├── Quick (1-2 sources, immediate answer)?\n│ └── → Use web-search skill directly (Phase 0-4)\n│\n├── Deep (multiple sources, needs synthesis)?\n│ └── → THIS SKILL — background agent\n│\n└── Login-walled / SPA-only sources?\n └── → web-access skill (ComputerUse browser)\n```\n\n---\n\n## Phase 1: Spin Up Background Agent\n\nLaunch a **background agent** to do the heavy reading, so you keep working while it researches.\n\nThe agent's instructions:\n\n```\nYou are a research agent. Your task:\n\n1. Investigate the question against PRIMARY SOURCES ONLY:\n - Official documentation (docs.*.com, *.org)\n - Source code repositories (GitHub, GitLab)\n - Technical specifications (RFCs, standards)\n - First-party API references\n - NOT: blog posts, Medium articles, forum threads, secondary summaries\n\n2. For every claim, follow it back to the source that owns it.\n If a secondary source makes a claim, find the primary source and cite that.\n\n3. Use WebSearch to find sources.\n Use WebFetch to deep-read promising pages.\n Cross-reference critical claims across 2+ independent primary sources.\n\n4. Write findings to a SINGLE Markdown file.\n - Cite every claim with its primary source URL\n - Distinguish between facts (needs citation) and reasoning (your own)\n - Flag outdated content (\"article from 2024, may be stale\")\n - Note if a source is official docs vs community\n\n5. Save the file where the repo already keeps such notes.\n Match existing conventions. If none exist, put it in docs/research/.\n```\n\n---\n\n## Phase 2: Report Format\n\nThe agent writes findings in this structure:\n\n```markdown\n# [Research Topic]\n\n**Date**: YYYY-MM-DD\n**Sources**: N primary, M cross-references\n\n## Key Findings\n\n- [Finding 1] — [Source](URL)\n- [Finding 2] — [Source](URL)\n\n## Detailed Analysis\n\n### [Subtopic A]\n\n[Claim and citation]\n\n### [Subtopic B]\n\n[Claim and citation]\n\n## Source Evaluation\n\n| Source | Type | Authority | Notes |\n| ----------- | ------------- | --------- | --------------------- |\n| [Name](URL) | Official docs | High | Current as of YYYY-MM |\n| [Name](URL) | Source code | High | Tag vX.Y.Z |\n\n## Open Questions\n\n- [Question 1]\n- [Question 2]\n\nSources:\n\n- [Title](URL) — brief note\n```\n\n---\n\n## Phase 3: Review\n\nWhen the background agent completes:\n\n1. Read the output file\n2. Spot-check: did it follow the chain back to primary sources?\n3. Flag any claims that need further verification\n4. Surface uncertainties to the user\n\n---\n\n## Research Quality Checklist\n\n- [ ] Every factual claim has a primary source citation\n- [ ] At least one critical claim is cross-referenced (2+ sources)\n- [ ] Source type is clearly identified (official docs / source code / spec / community)\n- [ ] Outdated content is flagged with publication year\n- [ ] Reasoning vs facts are clearly distinguished\n- [ ] File saved in repo-appropriate location\n" },
|
|
23
23
|
{ type: 'standard', raw: "---\nname: safe-coding\ndescription: Safe coding rules for code generation — validate external/user input before use and throw RangeError on invalid input\nversion: 1.0.0\n---\n\n# Safe Coding\n\n处理外部/用户输入前必须校验:`null`、`undefined`、空字符串、格式非法时,抛出 `RangeError`,消息为 `'invalid input'`。\n" },
|
|
24
24
|
{ type: 'standard', raw: "---\nname: security-review\ndescription: Security audit skill — vulnerability scanning, OWASP Top 10, secrets detection, supply chain analysis, and compliance checking\nversion: 1.0.0\n---\n\n# Security Review\n\nComprehensive security audit for codebases. Covers vulnerability detection, compliance, and hardening recommendations.\n\n## Audit Checklist\n\n### 1. Secrets & Credentials\n\n- [ ] No hardcoded API keys, tokens, or passwords in source files\n- [ ] `.env` and `*.pem` files in `.gitignore`\n- [ ] API keys use environment variables or secret managers\n- [ ] No credentials in git history (check `git log -p`)\n- [ ] CI/CD secrets stored securely (not in workflow files)\n\n### 2. OWASP Top 10\n\n- [ ] **Injection**: SQL, NoSQL, OS command, LDAP injection points\n- [ ] **Broken Authentication**: Weak password policies, missing MFA\n- [ ] **Sensitive Data Exposure**: Unencrypted PII, missing TLS\n- [ ] **XXE**: XML external entity processing\n- [ ] **Broken Access Control**: Missing authorization checks\n- [ ] **Security Misconfiguration**: Default credentials, verbose errors\n- [ ] **XSS**: Reflected, stored, DOM-based cross-site scripting\n- [ ] **Insecure Deserialization**: Untrusted data deserialization\n- [ ] **Using Vulnerable Components**: Outdated dependencies with CVEs\n- [ ] **Insufficient Logging**: Missing audit trails for auth events\n\n### 3. Supply Chain\n\n- [ ] All dependencies have known licenses (no copyleft/GPL)\n- [ ] No dependencies with critical CVEs\n- [ ] Lock files committed (pnpm-lock.yaml, package-lock.json)\n- [ ] Dependency update policy in place\n- [ ] SBOM (Software Bill of Materials) available\n\n### 4. Network & API Security\n\n- [ ] TLS 1.3 enforced for all external communications\n- [ ] API endpoints have rate limiting\n- [ ] CORS configured with explicit origins (not `*`)\n- [ ] SSRF protections in place (URL validation, IP filtering)\n- [ ] WebSocket connections use WSS\n- [ ] GraphQL endpoints have query depth limits\n\n### 5. File System & Path Security\n\n- [ ] Path traversal protections (no `../../../etc/passwd`)\n- [ ] File upload validation (type, size, content inspection)\n- [ ] Symlink attacks prevented\n- [ ] Sensitive directories blocked (`/etc`, `/proc`, `/sys`)\n- [ ] Temporary files cleaned up after use\n\n### 6. Code-Level Security\n\n- [ ] No `eval()` or `Function()` with user input\n- [ ] No `child_process.exec()` with unsanitized input\n- [ ] Regex patterns safe from ReDoS\n- [ ] Prototype pollution prevented\n- [ ] No `dangerouslySetInnerHTML` without sanitization (React)\n- [ ] SQL queries use parameterized statements\n\n### 7. Authentication & Sessions\n\n- [ ] Passwords hashed with bcrypt/argon2 (not MD5/SHA1)\n- [ ] Session tokens use `httpOnly`, `secure`, `SameSite=Strict`\n- [ ] JWT tokens have reasonable expiration\n- [ ] Account lockout after failed attempts\n- [ ] Password reset tokens expire and are single-use\n\n### 8. Data Protection\n\n- [ ] PII data encrypted at rest (AES-256-GCM)\n- [ ] Data encrypted in transit (TLS 1.3)\n- [ ] Logs do not contain sensitive data\n- [ ] Database backups encrypted\n- [ ] Data retention policies defined\n\n### 9. Infrastructure\n\n- [ ] Infrastructure as Code (Terraform/Pulumi) used\n- [ ] Cloud resources not publicly exposed unless intended\n- [ ] Security groups / firewalls restrict inbound traffic\n- [ ] Container images scanned for vulnerabilities\n- [ ] Kubernetes pods run as non-root\n\n### 10. Logging & Monitoring\n\n- [ ] Authentication events logged\n- [ ] Failed access attempts logged and alerted\n- [ ] Structured logging format (JSON)\n- [ ] No PII in log messages\n- [ ] Alert thresholds configured for critical events\n\n## Report Format\n\n```\nSecurity Review Report\n======================\nDate: YYYY-MM-DD\nSeverity: Critical | High | Medium | Low\n\nFinding #N: [Title]\nSeverity: Critical/High/Medium/Low\nLocation: file:line\nDescription: [What was found]\nRisk: [What could happen]\nFix: [How to resolve]\n```\n\n## Compliance Standards\n\n- OWASP ASVS Level 2\n- PCI DSS (if handling payment data)\n- GDPR (if handling EU personal data)\n- SOC 2 Type II\n- ISO 27001\n" },
|
|
@@ -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)
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -10,17 +10,23 @@ import { toolKey } from '../seam'
|
|
|
10
10
|
import { withValidation } from '../validation'
|
|
11
11
|
|
|
12
12
|
// ── Dangerous command patterns ──
|
|
13
|
+
//
|
|
14
|
+
// The `rm` patterns below end the operand with a separator class `(?=[\s;&|>]|$)`
|
|
15
|
+
// rather than `$`. Anchoring to end-of-string made the refusal depend on the
|
|
16
|
+
// target being the last thing on the line, so `rm -rf /*` was refused while
|
|
17
|
+
// `rm -rf /* > log`, `rm -rf /* foo` and `rm -rf /*; echo x` — the same
|
|
18
|
+
// deletion — were not.
|
|
13
19
|
const BLOCKED_PATTERNS = [
|
|
14
20
|
// Recursive root deletion without preserve-root safeguard
|
|
15
21
|
/\brm\s+-rf\s+\/(\s|$)/,
|
|
16
|
-
/\brm\s+-rf\s
|
|
22
|
+
/\brm\s+-rf\s+\/\*(?=[\s;&|>]|$)/,
|
|
17
23
|
/\bsudo\s+rm\s+.*\//,
|
|
18
24
|
// rm -rf on home directory or any absolute path (relative dirs like node_modules stay allowed)
|
|
19
25
|
/\brm\s+-(?:rf|fr)\s+~(?:$|\s|\/)/,
|
|
20
26
|
/\brm\s+-(?:rf|fr)\s+\/(?![\s*])/,
|
|
21
27
|
// rm -rf on dangerous cwd globs
|
|
22
|
-
/\brm\s+-(?:rf|fr)\s
|
|
23
|
-
/\brm\s+-(?:rf|fr)\s
|
|
28
|
+
/\brm\s+-(?:rf|fr)\s+\*(?=[\s;&|>]|$)/,
|
|
29
|
+
/\brm\s+-(?:rf|fr)\s+\.(?=[\s;&|>]|$)/,
|
|
24
30
|
// Filesystem manipulation
|
|
25
31
|
/\bmkfs\./,
|
|
26
32
|
/\bdd\s+if=/,
|
|
@@ -153,7 +159,7 @@ export function isBlocked(command: string): string | null {
|
|
|
153
159
|
// Check dangerous patterns (on original, normalized, and sanitized)
|
|
154
160
|
for (const pattern of BLOCKED_PATTERNS) {
|
|
155
161
|
if (pattern.test(command) || pattern.test(normalized) || pattern.test(sanitized)) {
|
|
156
|
-
return
|
|
162
|
+
return 'Command rejected by security policy.'
|
|
157
163
|
}
|
|
158
164
|
}
|
|
159
165
|
|
package/src/ui/app.tsx
CHANGED
|
@@ -337,7 +337,6 @@ export function App({
|
|
|
337
337
|
} | null>(null)
|
|
338
338
|
const [apiKeyInput, setApiKeyInput] = useState('')
|
|
339
339
|
const [_sessionTitle, setSessionTitle] = useState('')
|
|
340
|
-
const [_fastMode, setFastMode] = useState(false)
|
|
341
340
|
const [_effort, setEffort] = useState('high')
|
|
342
341
|
const [focusMode, setFocusMode] = useState(false)
|
|
343
342
|
const [_ultracodeMode, setUltracodeMode] = useState(false)
|
|
@@ -487,7 +486,6 @@ export function App({
|
|
|
487
486
|
version: version || '0.0.0',
|
|
488
487
|
sessionId: sessionId || '',
|
|
489
488
|
setSessionTitle: (title: string) => setSessionTitle(title),
|
|
490
|
-
setFastMode: (on: boolean) => setFastMode(on),
|
|
491
489
|
setEffort: (level: string) => {
|
|
492
490
|
setEffort(level)
|
|
493
491
|
setPreference('lastCodeReviewEffort', level)
|
|
@@ -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
|
@@ -128,7 +128,6 @@ export interface CommandContext {
|
|
|
128
128
|
sessionId: string
|
|
129
129
|
// Callbacks for commands that mutate App state
|
|
130
130
|
setSessionTitle: (title: string) => void
|
|
131
|
-
setFastMode: (on: boolean) => void
|
|
132
131
|
setEffort: (level: string) => void
|
|
133
132
|
setFocusMode: (on: boolean) => void
|
|
134
133
|
setGoal: (text: string) => void
|
|
@@ -225,7 +224,6 @@ const helpCmd: CommandHandler = (ctx) => {
|
|
|
225
224
|
/providers List configured providers
|
|
226
225
|
/switch <p> <m> Switch provider and model
|
|
227
226
|
/config View configuration
|
|
228
|
-
/fast [on|off] Toggle fast mode
|
|
229
227
|
/effort <lvl> Set reasoning effort (low|medium|high|xhigh|max)
|
|
230
228
|
/theme [dark|light|auto] Set terminal theme
|
|
231
229
|
/ollama-refresh Refresh Ollama model list at runtime
|
|
@@ -2954,22 +2952,6 @@ const diffCmd: CommandHandler = async (_ctx) => {
|
|
|
2954
2952
|
// Phase 1 — Model Control Commands
|
|
2955
2953
|
// ═══════════════════════════════════════════════════════════════
|
|
2956
2954
|
|
|
2957
|
-
const fastCmd: CommandHandler = (ctx, args) => {
|
|
2958
|
-
const t = resolveT(ctx)
|
|
2959
|
-
const arg = args[0]?.toLowerCase()
|
|
2960
|
-
if (arg === 'on') {
|
|
2961
|
-
ctx.setFastMode(true)
|
|
2962
|
-
return { content: t('commands.fast.on') }
|
|
2963
|
-
} else if (arg === 'off') {
|
|
2964
|
-
ctx.setFastMode(false)
|
|
2965
|
-
return { content: t('commands.fast.off') }
|
|
2966
|
-
} else if (arg) {
|
|
2967
|
-
return { content: t('commands.fast.usage') }
|
|
2968
|
-
} else {
|
|
2969
|
-
return { content: t('commands.fast.unknown') }
|
|
2970
|
-
}
|
|
2971
|
-
}
|
|
2972
|
-
|
|
2973
2955
|
const effortCmd: CommandHandler = (ctx, args) => {
|
|
2974
2956
|
const t = resolveT(ctx)
|
|
2975
2957
|
const VALID_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max']
|
|
@@ -5117,7 +5099,13 @@ const loginCmd: CommandHandler = (ctx) => {
|
|
|
5117
5099
|
|
|
5118
5100
|
for (const p of activeProviders) {
|
|
5119
5101
|
const envVar = providerEnvMap[p.id] ?? `${p.id.toUpperCase()}_API_KEY`
|
|
5120
|
-
|
|
5102
|
+
// An env var is only one of the two ways a provider gets a key: `ctx.config`
|
|
5103
|
+
// already carries the merged (and, for `enc:v1:`, decrypted) `apiKey` from
|
|
5104
|
+
// config.yml. An env-only check reports a fully configured provider as ⬜.
|
|
5105
|
+
// Reuse `isApiKeyMissing` — the same predicate `/switch` uses — so the two
|
|
5106
|
+
// readouts agree on what "has a key" means (and an empty row stays ⬜).
|
|
5107
|
+
const configSet = !isApiKeyMissing(p.apiKey)
|
|
5108
|
+
const isSet = (typeof process !== 'undefined' && !!process.env[envVar]) || configSet
|
|
5121
5109
|
const icon = isSet ? '✅' : '⬜'
|
|
5122
5110
|
lines.push(` ${icon} ${p.id.padEnd(14)} $${envVar}${isSet ? ' (set)' : ''}`)
|
|
5123
5111
|
}
|
|
@@ -5439,7 +5427,7 @@ const forkCmd: CommandHandler = async (ctx, args) => {
|
|
|
5439
5427
|
}
|
|
5440
5428
|
}
|
|
5441
5429
|
|
|
5442
|
-
const { execSync } = await import('node:child_process')
|
|
5430
|
+
const { execSync, execFileSync } = await import('node:child_process')
|
|
5443
5431
|
const { join } = await import('node:path')
|
|
5444
5432
|
|
|
5445
5433
|
try {
|
|
@@ -5463,15 +5451,21 @@ const forkCmd: CommandHandler = async (ctx, args) => {
|
|
|
5463
5451
|
const wtPath = join(worktreeRoot(process.cwd()), name)
|
|
5464
5452
|
|
|
5465
5453
|
try {
|
|
5466
|
-
|
|
5454
|
+
// argv array, no shell — `wtPath` is derived from the current directory and can
|
|
5455
|
+
// contain a space or a metacharacter, which a shell string would split or misfire on.
|
|
5456
|
+
// Same reason the add/remove/branch trio all go through execFileSync here.
|
|
5457
|
+
execFileSync('git', ['worktree', 'add', '-b', branch, wtPath, 'HEAD'], {
|
|
5458
|
+
stdio: 'ignore',
|
|
5459
|
+
timeout: 30_000,
|
|
5460
|
+
})
|
|
5467
5461
|
} catch (err) {
|
|
5468
5462
|
try {
|
|
5469
|
-
|
|
5463
|
+
execFileSync('git', ['worktree', 'remove', '--force', wtPath], { stdio: 'ignore' })
|
|
5470
5464
|
} catch {
|
|
5471
5465
|
/* ok */
|
|
5472
5466
|
}
|
|
5473
5467
|
try {
|
|
5474
|
-
|
|
5468
|
+
execFileSync('git', ['branch', '-D', branch], { stdio: 'ignore' })
|
|
5475
5469
|
} catch {
|
|
5476
5470
|
/* ok */
|
|
5477
5471
|
}
|
|
@@ -5727,7 +5721,6 @@ const commandsListCmd: CommandHandler = () => {
|
|
|
5727
5721
|
'/providers': 'Model & Provider',
|
|
5728
5722
|
'/switch': 'Model & Provider',
|
|
5729
5723
|
'/config': 'Model & Provider',
|
|
5730
|
-
'/fast': 'Model & Provider',
|
|
5731
5724
|
'/effort': 'Model & Provider',
|
|
5732
5725
|
'/theme': 'Model & Provider',
|
|
5733
5726
|
'/upgrade': 'Model & Provider',
|
|
@@ -5889,7 +5882,6 @@ registry.set('/ollama-refresh', ollamaRefreshCmd)
|
|
|
5889
5882
|
registry.set('/provider', providerCmd)
|
|
5890
5883
|
registry.set('/providers', providersCmd)
|
|
5891
5884
|
registry.set('/config', configCmd)
|
|
5892
|
-
registry.set('/fast', fastCmd)
|
|
5893
5885
|
registry.set('/effort', effortCmd)
|
|
5894
5886
|
registry.set('/switch', switchCmd)
|
|
5895
5887
|
|
|
@@ -6123,7 +6115,6 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
|
|
|
6123
6115
|
'/providers': 'List configured providers',
|
|
6124
6116
|
'/switch': 'Switch provider and model',
|
|
6125
6117
|
'/config': 'View configuration',
|
|
6126
|
-
'/fast': 'Toggle fast mode',
|
|
6127
6118
|
'/effort': 'Set reasoning effort',
|
|
6128
6119
|
'/theme': 'Set terminal theme',
|
|
6129
6120
|
'/lang': 'Set display language (en-US, zh-CN)',
|
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) ──
|