@miphamai/cli 0.85.18 → 0.85.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.18
1
+ # Mipham Code v0.85.19
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 137 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.18",
3
+ "version": "0.85.19",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -521,6 +521,10 @@ export class SubAgent {
521
521
  systemPrompt: currentSystemPrompt,
522
522
  tools: toolDefs,
523
523
  maxTokens: 4096,
524
+ // Scales the provider's streaming idle timeout (fetch-utils
525
+ // `streamIdleTimeoutMs`). Omitted ⇒ 1× base, so a caller that asked for
526
+ // a high-effort sub-agent would otherwise get the default budget.
527
+ effort: options.effort,
524
528
  })) {
525
529
  // Check abort signal mid-stream
526
530
  if (signal?.aborted) {
@@ -43,6 +43,14 @@ export interface SubAgentOptions {
43
43
  systemPrompt?: string
44
44
  allowedTools?: string[]
45
45
  modelOverride?: string
46
+ /**
47
+ * Reasoning effort (`low|medium|high|xhigh|max`) for this run, matching the
48
+ * session-level level `/effort` sets. Threaded into the provider request as
49
+ * `ChatRequest.effort`, where it scales the streaming idle timeout — a
50
+ * sub-agent left at the default would inherit the base timeout regardless of
51
+ * the level the caller asked for.
52
+ */
53
+ effort?: string
46
54
  /** Maximum tool-calling turns (default: 5) to prevent infinite loops. */
47
55
  maxTurns?: number
48
56
  /** When true, execute in background and return immediately with a task ID. */
@@ -126,6 +126,56 @@ export class AgentViewManager {
126
126
  return session
127
127
  }
128
128
 
129
+ /**
130
+ * Mirror background-agent tasks into the panel, and return how many rows were
131
+ * added.
132
+ *
133
+ * Rows created by `/bg` and `/fork` used to be the only ones that existed. The
134
+ * Agent tool — whose sub-agents are **background by default** — registers them
135
+ * with the background registry and nothing else, so the ordinary way to fan out
136
+ * work produced no panel rows at all: the pane stayed empty the whole time the
137
+ * agents ran, which a viewer cannot tell apart from "nothing was spawned".
138
+ *
139
+ * Keyed on the registry's task id. `/bg` and `/fork` already link their row
140
+ * through `session.taskId`, so those are matched and updated rather than
141
+ * duplicated; anything else is a task this panel has not seen.
142
+ *
143
+ * Status is a projection, not a source: the registry owns it, and a row whose
144
+ * status disagrees with the registry is corrected here on the next round.
145
+ */
146
+ syncBackgroundTasks(
147
+ tasks: ReadonlyArray<{ id: string; description: string; status: string }>,
148
+ ): number {
149
+ const byTaskId = new Map<string, AgentSession>()
150
+ for (const id of this.sessionOrder) {
151
+ const session = this.sessions.get(id)
152
+ if (session?.taskId) byTaskId.set(session.taskId, session)
153
+ }
154
+
155
+ let added = 0
156
+ for (const task of tasks) {
157
+ const status: SessionStatus =
158
+ task.status === 'running' ? 'working' : task.status === 'failed' ? 'failed' : 'completed'
159
+
160
+ const existing = byTaskId.get(task.id)
161
+ if (existing) {
162
+ if (existing.status !== status) this.updateStatus(existing.id, status)
163
+ continue
164
+ }
165
+
166
+ const session = this.create(task.description, task.description)
167
+ session.taskId = task.id
168
+ // Not `interactive`: nobody is steering this row, and the dashboard's
169
+ // grouping keys off the kind as well as the status.
170
+ session.kind = 'unattended'
171
+ this.updateStatus(session.id, status)
172
+ byTaskId.set(task.id, session)
173
+ added++
174
+ }
175
+
176
+ return added
177
+ }
178
+
129
179
  /**
130
180
  * List all sessions in creation order (newest first).
131
181
  */
@@ -23,6 +23,7 @@ import type { AgentViewManager } from '../agent-view/agent-view-manager'
23
23
  import type { Skills } from '../skills/seam'
24
24
  import { getBackgroundAgentRegistry } from '../agent/background-registry'
25
25
  import { RulesLoader } from './rules-loader'
26
+ import { extractBashFileAccess } from './permission-rules'
26
27
  import type { InstructionsLoader } from './instructions'
27
28
  import { ExperienceRuleEngine } from './rule-engine.js'
28
29
  import { PatternAnalyzer } from '../agent/pattern-analyzer.js'
@@ -406,6 +407,19 @@ export class QueryEngine {
406
407
 
407
408
  /** Track files touched by tools for rules matching. */
408
409
  private trackTouchedFile(toolName: string, params: Record<string, unknown>): void {
410
+ if (toolName === 'Bash') {
411
+ // A single-file `cat`/`head`/`sed -n`/`grep` reads the same file the Read
412
+ // tool would, so the rules scoped to it have to see that path too. Reuses
413
+ // the extractor the permission layer already runs for Bash↔Read/Write rule
414
+ // bridging rather than a second, drifting spelling of "which paths did this
415
+ // command touch" — it already covers redirects, `$()`/backtick
416
+ // substitutions, `bash -c` payloads and `~`/`$HOME` expansion.
417
+ const command = params.command
418
+ if (typeof command !== 'string') return
419
+ const access = extractBashFileAccess(command)
420
+ for (const p of [...access.read, ...access.write]) this.touchedFiles.add(p)
421
+ return
422
+ }
409
423
  const fileTools = ['Read', 'Write', 'Edit', 'Glob', 'Grep']
410
424
  if (!fileTools.includes(toolName)) return
411
425
  const filePath = (params.file_path || params.path || params.file) as string | undefined
@@ -414,14 +428,32 @@ export class QueryEngine {
414
428
  }
415
429
  }
416
430
 
417
- /** Inject matching rules as context after tool execution. */
431
+ /**
432
+ * Inject path-scoped context for the files touched this round: matching rules
433
+ * (`.mipham/rules/*.md`) and any nested instruction files (`CLAUDE.md` and
434
+ * friends) that were not part of the startup chain.
435
+ *
436
+ * Both halves ride the same trigger on purpose — a rule file and a nested
437
+ * `CLAUDE.md` are the same kind of thing (the loader labels the level
438
+ * "Directory Rules"), and a path that activates one almost always activates
439
+ * the other. They also share the call-timing constraint below.
440
+ *
441
+ * Must run **after** every `tool_result` of the round has been appended:
442
+ * `injectContext` pushes a user message, and landing it between an assistant
443
+ * `tool_use` and its paired user `tool_result` breaks the pairing.
444
+ */
418
445
  private injectRules(): void {
419
- if (!this.rulesLoader || this.touchedFiles.size === 0) return
446
+ if (this.touchedFiles.size === 0) return
420
447
  const files = Array.from(this.touchedFiles)
421
- const block = this.rulesLoader.buildContextBlock(files)
422
- if (!block) return
423
- this.context.injectContext('rules', block)
424
448
  this.touchedFiles.clear()
449
+
450
+ if (this.rulesLoader) {
451
+ const block = this.rulesLoader.buildContextBlock(files)
452
+ if (block) this.context.injectContext('rules', block)
453
+ }
454
+
455
+ const nested = this.instructionsLoader?.loadForPaths(files, process.cwd())
456
+ if (nested) this.context.injectContext('directory-rules', nested)
425
457
  }
426
458
 
427
459
  /**
@@ -459,6 +491,14 @@ export class QueryEngine {
459
491
  const tasks = bgRegistry.list()
460
492
  const chunks: StreamChunk[] = []
461
493
 
494
+ // Mirror every background task into Agent View — including the running ones,
495
+ // which the loop below deliberately skips. The panel previously carried only
496
+ // `/bg` and `/fork` rows, so a background sub-agent spawned by the Agent tool
497
+ // (the default) was invisible in it for its whole lifetime. Projecting from
498
+ // the registry rather than from each spawn site means every present and future
499
+ // producer is covered by one call.
500
+ this.agentViewManager?.syncBackgroundTasks(tasks)
501
+
462
502
  for (const task of tasks) {
463
503
  if (task.status === 'running') continue
464
504
 
@@ -1,5 +1,5 @@
1
- import { readFileSync, existsSync, lstatSync } from 'node:fs'
2
- import { join, resolve, relative, sep, isAbsolute } from 'node:path'
1
+ import { readFileSync, existsSync, lstatSync, statSync } from 'node:fs'
2
+ import { join, resolve, relative, sep, isAbsolute, dirname } from 'node:path'
3
3
  import { execSync } from 'node:child_process'
4
4
  import { parse as parseYaml } from 'yaml'
5
5
  import type { InstructionFile } from '../shared/index.ts'
@@ -84,6 +84,12 @@ export function gitRoot(cwd: string): string {
84
84
  }
85
85
  }
86
86
 
87
+ /** True when `p` is `root` itself or sits underneath it. */
88
+ function isInside(root: string, p: string): boolean {
89
+ const rel = relative(root, p)
90
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
91
+ }
92
+
87
93
  /** 从仓库根到 cwd 的目录链(含两端),就近(cwd)在最后。cwd 不在 root 下时退化为 [cwd]。 */
88
94
  export function discoverDirectories(root: string, cwd: string): string[] {
89
95
  const absRoot = resolve(root)
@@ -252,11 +258,14 @@ export class InstructionsLoader {
252
258
  private instructions: InstructionFile[] = []
253
259
  private crsiLessonSummaries: CrsiLessonSummary[] = []
254
260
  private lessonsPath: string | null = null
261
+ /** Checkout root resolved at `loadAll`, reused by `loadForPaths`. */
262
+ private root: string | null = null
255
263
 
256
264
  loadAll(cwd: string): void {
257
265
  this.instructions = []
258
266
  this.lessonsPath = null
259
267
  const root = gitRoot(cwd)
268
+ this.root = root
260
269
 
261
270
  // Tier 1: 集团/公司策略(锚定仓库根,从任意子目录启动都正确;不读 AGENTS.md)
262
271
  this.tryLoad(join(root, '..', '..', 'CLAUDE.md'), 'group') // Rismed_Ronxin_Capital
@@ -522,6 +531,73 @@ Never omit it or present the work as purely human-authored.`)
522
531
  return [...this.instructions]
523
532
  }
524
533
 
534
+ /**
535
+ * Load the instruction files of the directories a path the model just looked at
536
+ * lives under, and return the text of whatever was **not** already loaded.
537
+ *
538
+ * The baseline chain is git-root → cwd, walked once at startup (`loadAll`). A
539
+ * file deeper than cwd (`src/parser/lex.ts`) or on a sibling branch therefore
540
+ * contributes nothing — even though the `CLAUDE.md` sitting next to it is
541
+ * precisely the rule set that governs it. Upstream reported the Bash half of
542
+ * this (`cat`/`head`/`sed -n`/`grep` on a single file skipped its rules); the
543
+ * Read tool had the same hole, so the gate here is the **path**, not the tool
544
+ * that produced it: "did the model see a file here".
545
+ *
546
+ * Only directories inside the checkout are considered. The tiers above it are
547
+ * anchored deliberately (`loadAll`), and walking the ancestors of, say,
548
+ * `/etc/hosts` would pull arbitrary local files into the prompt on the strength
549
+ * of a command — so an outside path contributes nothing by construction.
550
+ * Directories already visited cost one `existsSync` per candidate name.
551
+ *
552
+ * Returns `null` when nothing new was loaded, so callers can skip an empty
553
+ * injection. Text goes through `instructionPartText` — the same projection the
554
+ * system prompt uses — so `privacy: private` and `prompt-exclude` are honored
555
+ * here too, and the two cannot drift.
556
+ */
557
+ loadForPaths(paths: Iterable<string>, cwd: string): string | null {
558
+ // Reused rather than re-resolved: `gitRoot` spawns `git rev-parse`, and this
559
+ // runs on the tool-execution path once per round. The fallback keeps the
560
+ // method correct for a caller that never ran `loadAll`.
561
+ const root = this.root ?? resolve(gitRoot(cwd))
562
+ const loaded = new Set(this.instructions.map((f) => f.path))
563
+ const added: InstructionFile[] = []
564
+
565
+ for (const raw of paths) {
566
+ let dir = resolve(cwd, raw)
567
+ if (!isInside(root, dir)) continue
568
+ // A touched path is a directory when the tool searched one (Grep's root,
569
+ // Glob) and a file otherwise. A path that does not exist yet is treated as
570
+ // a file, which is the right reading for `Write` on a new path.
571
+ try {
572
+ if (!statSync(dir).isDirectory()) dir = dirname(dir)
573
+ } catch {
574
+ dir = dirname(dir)
575
+ }
576
+
577
+ for (;;) {
578
+ for (const name of INSTRUCTION_FILENAMES) {
579
+ const file = join(dir, name)
580
+ if (loaded.has(file)) continue
581
+ loaded.add(file)
582
+ this.tryLoad(file, 'directory')
583
+ const loadedFile = this.instructions[this.instructions.length - 1]
584
+ if (loadedFile?.path === file) added.push(loadedFile)
585
+ }
586
+ if (dir === root) break
587
+ const parent = dirname(dir)
588
+ if (parent === dir) break
589
+ dir = parent
590
+ }
591
+ }
592
+
593
+ const parts: string[] = []
594
+ for (const inst of added) {
595
+ const text = instructionPartText(inst)
596
+ if (text) parts.push(text)
597
+ }
598
+ return parts.length > 0 ? parts.join('\n\n---\n\n') : null
599
+ }
600
+
525
601
  /**
526
602
  * How much instruction text this loader puts in the system prompt, per file.
527
603
  *
@@ -45,7 +45,14 @@ export async function handleChannelMessage(opts: ChannelMessageOptions): Promise
45
45
  await sendText(externalId, '(会话初始化失败,请稍后重试)')
46
46
  return
47
47
  }
48
- await worker.processPrompt(text)
48
+ const outcome = await worker.processPrompt(text)
49
+ // A `busy` outcome means this turn never ran — the concurrency guard refused
50
+ // it. Reading `getLastAssistantContent()` here would replay the *previous*
51
+ // turn's reply as if it answered the message just sent, so say what happened.
52
+ if (!outcome.ok) {
53
+ await sendText(externalId, '(上一条消息仍在处理中,请稍候再发)')
54
+ return
55
+ }
49
56
  const result = worker.getLastAssistantContent()
50
57
  await sendText(externalId, result ? result.slice(0, maxLen) : '(无回复)')
51
58
  } catch (err) {
@@ -51,6 +51,19 @@ export interface SessionStateSnapshot {
51
51
  permissionMode: PermissionMode
52
52
  }
53
53
 
54
+ // ── Prompt-processing outcome ─────────────────────────────────────────────
55
+
56
+ /**
57
+ * Result of a `processPrompt` call.
58
+ *
59
+ * `busy` is *reported*, not swallowed. A second message arriving mid-turn used to
60
+ * fall out of the concurrency guard — which only broadcasts to WS viewers — and
61
+ * then be answered by the caller with `getLastAssistantContent()`, i.e. the
62
+ * *previous* turn's reply. The user got an answer to a question they had not
63
+ * asked. Naming the refusal lets the channel say "still working" instead.
64
+ */
65
+ export type ProcessPromptResult = { ok: true } | { ok: false; reason: 'busy' }
66
+
54
67
  // ── SessionWorker ─────────────────────────────────────────────────────────
55
68
 
56
69
  export class SessionWorker {
@@ -110,10 +123,10 @@ export class SessionWorker {
110
123
  * 7. On interrupt: save partial content, broadcast `done` with stop_reason
111
124
  * 'interrupted'
112
125
  */
113
- async processPrompt(prompt: string): Promise<void> {
126
+ async processPrompt(prompt: string): Promise<ProcessPromptResult> {
114
127
  if (this.processing) {
115
128
  this.broadcast(this.errorMessage('A prompt is already being processed'))
116
- return
129
+ return { ok: false, reason: 'busy' }
117
130
  }
118
131
 
119
132
  this.processing = true
@@ -215,6 +228,8 @@ export class SessionWorker {
215
228
 
216
229
  this.currentController = null
217
230
  this.processing = false
231
+
232
+ return { ok: true }
218
233
  }
219
234
 
220
235
  // ── Interrupt ──────────────────────────────────────────────────────────
@@ -772,6 +772,7 @@
772
772
  "focus_hint": "Focus",
773
773
  "hidden": "hidden",
774
774
  "toggle_focus_hint": "/focus to toggle",
775
+ "try_focus_tip": "Long turn? Ctrl+F (or /focus) shows just the latest exchange — press it again to switch back.",
775
776
  "expand_hint": "Ctrl+O to expand",
776
777
  "showing_all": "showing all {count} messages",
777
778
  "tool_outputs_folded": "{hidden} tool outputs folded ({toolCount} total tool calls)"
@@ -929,8 +930,8 @@
929
930
  "errors": {
930
931
  "tool_denied_deny_rule": "Tool \"{name}\" blocked by a deny rule (\"{pattern}\"). Deny rules override permission mode — try a different approach, or drop the rule with: /permissions remove \"{pattern}\"",
931
932
  "tool_denied_ask_rule": "Tool \"{name}\" requires approval (ask rule: \"{pattern}\"). Approve when prompted, or stop being asked with: /permissions allow \"{pattern}\"",
932
- "tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\") Treat this denial as covering the outcome, not only this exact command.",
933
- "tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule. Note that `/permissions allow \"{name}\"` skips the classifier for every later call to this tool, not just this one, so prefer making the call acceptable over allowing the tool. Treat this denial as covering the outcome, not only this exact command.",
933
+ "tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\").",
934
+ "tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule. Note that `/permissions allow \"{name}\"` skips the classifier for every later call to this tool, not just this one, so prefer making the call acceptable over allowing the tool.",
934
935
  "tool_denied_dangerous_rm": "Tool \"{name}\" was refused: this is a recursive rm whose target is not a path written in the command (\"{target}\"). The target is produced when the command runs, so neither an allow rule nor the permission mode can bound what it deletes. Name the directory literally instead — `rm -rf node_modules` rather than `rm -rf \"$(pwd)\"` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
935
936
  "tool_denied_world_writable_chmod": "Tool \"{name}\" was refused: this is a recursive chmod that grants world-write to a target the command does not bound (\"{target}\"). A world-writable tree plus a target produced at run time is how permissions end up loosened far past what was asked for, and neither an allow rule nor the permission mode can bound where the grant reaches. Name the directory literally instead — `chmod -R 777 ./dist` rather than `chmod -R 777 $DIR` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_CHMOD_PROMPT=1",
936
937
  "tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
@@ -953,6 +954,7 @@
953
954
  "oauth_no_code": "No authorization code received",
954
955
  "oauth_timeout": "OAuth flow timed out (5 minutes)",
955
956
  "mcp_register_collision": "[mcp] Tool collision: \"{name}\" (from server \"{server}\") conflicts with existing tool. Skipping.",
957
+ "mcp_protocol_version_mismatch": "[mcp] Server negotiated protocol version \"{version}\", which this client does not implement (supported: {supported}). Continuing, but MCP messages may not behave as expected.",
956
958
  "mcp_register_failed": "[mcp] Failed to register tool \"{tool}\" from server \"{server}\": {error}",
957
959
  "max_tool_turns": "Max tool-calling turns ({max}) reached. Some tool calls were not executed.",
958
960
  "max_tool_turns_warning": "You've reached the maximum of {max} tool-calling rounds. {pending} tool call(s) were not executed. Please summarize what you found so far and any next steps the user should take.",
@@ -772,6 +772,7 @@
772
772
  "focus_hint": "聚焦",
773
773
  "hidden": "已折叠",
774
774
  "toggle_focus_hint": "/focus 切换",
775
+ "try_focus_tip": "这一轮较长?Ctrl+F(或 /focus)只显示最近一次往来 —— 再按一次即可切回。",
775
776
  "expand_hint": "Ctrl+O 展开",
776
777
  "showing_all": "显示全部 {count} 条消息",
777
778
  "tool_outputs_folded": "已折叠 {hidden} 个工具输出(共 {toolCount} 个工具调用)"
@@ -929,8 +930,8 @@
929
930
  "errors": {
930
931
  "tool_denied_deny_rule": "工具 \"{name}\" 被拒绝规则(\"{pattern}\")阻止。拒绝规则优先于权限模式 — 请改用其他方式,或移除该规则:/permissions remove \"{pattern}\"",
931
932
  "tool_denied_ask_rule": "工具 \"{name}\" 需要批准(ask 规则:\"{pattern}\")。请在提示时批准,或不再询问:/permissions allow \"{pattern}\"",
932
- "tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可) 请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
933
- "tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则。注意:`/permissions allow \"{name}\"` 会让此后对该工具的**每一次**调用都跳过分类器,而不只是这一次,故优先把这次调用改成可接受的,而不是放行整个工具。请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
933
+ "tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可)。",
934
+ "tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则。注意:`/permissions allow \"{name}\"` 会让此后对该工具的**每一次**调用都跳过分类器,而不只是这一次,故优先把这次调用改成可接受的,而不是放行整个工具。",
934
935
  "tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
935
936
  "tool_denied_world_writable_chmod": "工具 \"{name}\" 被拒绝:这是一条递归 chmod,它把「其他用户可写」授予了一个命令并未界定边界的目标(\"{target}\")。一棵世界可写的树,加上一个要到运行时才产生的目标,正是权限被放宽到远超所求的由来;而任何放行规则与权限模式都无法界定这次授权会伸到哪里。请改为字面写出目录名 —— 用 `chmod -R 777 ./dist` 而不是 `chmod -R 777 $DIR` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_CHMOD_PROMPT=1",
936
937
  "tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
@@ -953,6 +954,7 @@
953
954
  "oauth_no_code": "未收到授权码",
954
955
  "oauth_timeout": "OAuth 流程超时(5 分钟)",
955
956
  "mcp_register_collision": "[mcp] 工具冲突:\"{name}\"(来自服务器 \"{server}\")与已有工具冲突,跳过。",
957
+ "mcp_protocol_version_mismatch": "[mcp] 服务器协商出的协议版本为 \"{version}\",本客户端未实现该版本(支持:{supported})。将继续连接,但 MCP 消息可能不按预期工作。",
956
958
  "mcp_register_failed": "[mcp] 注册工具 \"{tool}\"(来自服务器 \"{server}\")失败:{error}",
957
959
  "max_tool_turns": "超出最大工具调用轮次({max})。部分工具调用未执行。",
958
960
  "max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
@@ -11,6 +11,30 @@ export const MCP_INSTRUCTIONS_PER_SERVER_CAP = 2000
11
11
 
12
12
  const TRUNCATION_MARKER = '… [truncated]'
13
13
 
14
+ /** True when every character is a plain ASCII code point (0x00–0x7F). */
15
+ function isAsciiName(s: string): boolean {
16
+ for (let i = 0; i < s.length; i++) {
17
+ if (s.charCodeAt(i) > 0x7f) return false
18
+ }
19
+ return true
20
+ }
21
+
22
+ /**
23
+ * Order two names for the model-facing block: ASCII names first, then the rest.
24
+ *
25
+ * `localeCompare` is locale-*aware*, which is exactly wrong here: it threads an
26
+ * accented name (`Émile`) in among the ASCII ones and only relegates pure CJK to
27
+ * the end, so the same set of servers can order differently across machines. The
28
+ * reader is a model, not a human locale — the list wants a fixed shape. Within
29
+ * each group, compare by code unit, which is deterministic everywhere.
30
+ */
31
+ export function compareNames(a: string, b: string): number {
32
+ const aAscii = isAsciiName(a)
33
+ const bAscii = isAsciiName(b)
34
+ if (aAscii !== bAscii) return aAscii ? -1 : 1
35
+ return a < b ? -1 : a > b ? 1 : 0
36
+ }
37
+
14
38
  /**
15
39
  * 把已连接 MCP server 自带的 `instructions` 拼成一段**系统提示用**的文本。
16
40
  *
@@ -33,7 +57,7 @@ export function buildMcpInstructionsBlock(connections: ConnectionInfo[]): string
33
57
  const sections = connections
34
58
  .filter((c) => typeof c.instructions === 'string' && c.instructions.trim() !== '')
35
59
  .slice()
36
- .sort((a, b) => a.config.name.localeCompare(b.config.name))
60
+ .sort((a, b) => compareNames(a.config.name, b.config.name))
37
61
  .map((c) => {
38
62
  const raw = c.instructions!.trim()
39
63
  const body =
@@ -6,8 +6,46 @@ import type {
6
6
  ResourceReadResult,
7
7
  } from './types'
8
8
  import type { Transport } from './transport'
9
+ import { createT } from '../i18n-core/t'
10
+ import enUS from '../i18n-core/locales/en-US.json'
11
+ import zhCN from '../i18n-core/locales/zh-CN.json'
12
+ import type { TranslationMap } from '../i18n-core/types'
13
+
14
+ const bundles: Record<string, TranslationMap> = {
15
+ 'en-US': enUS as TranslationMap,
16
+ 'zh-CN': zhCN as TranslationMap,
17
+ }
18
+ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as TranslationMap)
19
+
20
+ /**
21
+ * Protocol revisions this client is prepared to speak, newest first.
22
+ *
23
+ * Only revisions whose wire behaviour the code below actually implements belong
24
+ * here — offering a revision is a claim that its messages will be understood,
25
+ * and a server that takes us at our word would then send shapes we cannot parse.
26
+ * The list exists so that adopting a revision is an edit to a value rather than
27
+ * a change to the handshake, and so the server's answer has something to be
28
+ * checked against.
29
+ */
30
+ export const MCP_SUPPORTED_VERSIONS: readonly string[] = ['2024-11-05']
9
31
 
10
- const MCP_VERSION = '2024-11-05'
32
+ /**
33
+ * The revision to offer in `initialize`.
34
+ *
35
+ * `MCP_PROTOCOL_NEGOTIATION=legacy` pins the oldest supported revision. The
36
+ * handshake used to send one hardcoded literal with no way to ask for anything
37
+ * else, so a server that answers an unrecognized revision by failing the
38
+ * connection — rather than by replying with the one it speaks — was simply
39
+ * unreachable.
40
+ *
41
+ * An unset or unrecognized value offers the newest.
42
+ */
43
+ export function offerVersion(env: NodeJS.ProcessEnv = process.env): string {
44
+ if (env.MCP_PROTOCOL_NEGOTIATION === 'legacy') {
45
+ return MCP_SUPPORTED_VERSIONS[MCP_SUPPORTED_VERSIONS.length - 1]!
46
+ }
47
+ return MCP_SUPPORTED_VERSIONS[0]!
48
+ }
11
49
 
12
50
  /**
13
51
  * MCP protocol layer — implements the initialize/tools/resources
@@ -19,9 +57,24 @@ export class McpProtocol {
19
57
  resources?: { subscribe?: boolean; listChanged?: boolean }
20
58
  } = {}
21
59
  private handlers = new Map<string, Array<(...args: any[]) => void>>()
60
+ /** The revision the last `initialize` agreed on, or null before one ran. */
61
+ private agreedVersion: string | null = null
22
62
 
23
63
  constructor(private transport: Transport) {}
24
64
 
65
+ /**
66
+ * The protocol revision this connection settled on.
67
+ *
68
+ * The server's answer, not the one we offered: `initialize` replies with the
69
+ * revision it will actually speak, which may be older than the offer. Recorded
70
+ * because the field used to be received and dropped — a server that answered
71
+ * with a revision this client never implemented looked exactly like one that
72
+ * agreed.
73
+ */
74
+ get protocolVersion(): string | null {
75
+ return this.agreedVersion
76
+ }
77
+
25
78
  on(event: string, handler: (...args: any[]) => void): void {
26
79
  const list = this.handlers.get(event) || []
27
80
  list.push(handler)
@@ -37,7 +90,7 @@ export class McpProtocol {
37
90
  // Transport must already be started by the caller (McpClient.connect).
38
91
  // Send initialize request
39
92
  const result = (await this.transport.sendRequest('initialize', {
40
- protocolVersion: MCP_VERSION,
93
+ protocolVersion: offerVersion(),
41
94
  capabilities: {
42
95
  tools: {},
43
96
  resources: {},
@@ -48,6 +101,20 @@ export class McpProtocol {
48
101
  },
49
102
  })) as InitializeResult
50
103
 
104
+ this.agreedVersion = result.protocolVersion ?? null
105
+ if (this.agreedVersion && !MCP_SUPPORTED_VERSIONS.includes(this.agreedVersion)) {
106
+ // Not a fatal error: the base lifecycle is stable across revisions, so the
107
+ // connection usually still works. Say so rather than let an unexpected
108
+ // revision look like an agreement — if messages then misbehave, this line
109
+ // is the first thing that explains why.
110
+ console.error(
111
+ t('errors.mcp_protocol_version_mismatch', {
112
+ version: this.agreedVersion,
113
+ supported: MCP_SUPPORTED_VERSIONS.join(', '),
114
+ }),
115
+ )
116
+ }
117
+
51
118
  // Send initialized notification
52
119
  this.transport.sendNotification('notifications/initialized')
53
120
 
@@ -106,6 +106,29 @@ export function isRetryableFailure(status: number | undefined, errorType?: strin
106
106
  return !NON_RETRYABLE_ERROR_TYPES.has(errorType)
107
107
  }
108
108
 
109
+ /** Base backoff between retry attempts, in ms. */
110
+ export const DEFAULT_RETRY_BASE_DELAY_MS = 1_000
111
+
112
+ /**
113
+ * The default backoff, overridable from the environment.
114
+ *
115
+ * One second suits an interactive turn, but a caller pointed at a known-overloaded
116
+ * endpoint (a self-hosted gateway, a batch run) wants longer gaps between attempts
117
+ * — and cannot pass `baseDelay` through the SDK paths that build their own
118
+ * `fetchWithRetry` call. `MIPHAM_OVERLOADED_RETRY_BASE_DELAY_MS` is that knob.
119
+ *
120
+ * A malformed value (non-numeric, negative) is a typo, not an instruction: fall
121
+ * back to the built-in rather than let `sleep(NaN)` become a zero-delay retry
122
+ * loop. Read per call so a test can set it without re-importing the module.
123
+ */
124
+ function resolveBaseDelayMs(): number {
125
+ const raw = process.env.MIPHAM_OVERLOADED_RETRY_BASE_DELAY_MS
126
+ if (raw === undefined || raw.trim() === '') return DEFAULT_RETRY_BASE_DELAY_MS
127
+ const ms = Number(raw)
128
+ if (!Number.isFinite(ms) || ms < 0) return DEFAULT_RETRY_BASE_DELAY_MS
129
+ return ms
130
+ }
131
+
109
132
  /**
110
133
  * Fetch with optional timeout and retry with exponential backoff.
111
134
  *
@@ -118,7 +141,7 @@ export async function fetchWithRetry(
118
141
  init: RequestInit,
119
142
  options: FetchWithRetryOptions = {},
120
143
  ): Promise<Response> {
121
- const { timeout = 60_000, maxRetries = 2, baseDelay = 1000 } = options
144
+ const { timeout = 60_000, maxRetries = 2, baseDelay = resolveBaseDelayMs() } = options
122
145
 
123
146
  let lastErr: unknown
124
147
 
@@ -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.18' as const
12
+ export const PACKAGE_VERSION = '0.85.19' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 4076 as const
93
+ export const TEST_COUNT = 4141 as const
@@ -5,6 +5,9 @@ import { getBackgroundAgentRegistry } from '../../agent/background-registry'
5
5
 
6
6
  const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review']
7
7
 
8
+ /** Same domain as the session-level `/effort` command (`ui/commands.ts`). */
9
+ const VALID_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
10
+
8
11
  /**
9
12
  * Resolve whether a sub-agent should run in the background.
10
13
  *
@@ -64,6 +67,14 @@ export const agentTool: ToolDefinition = {
64
67
  description:
65
68
  'When false, execute synchronously and return the result directly. Default: true (background).',
66
69
  },
70
+ effort: {
71
+ type: 'string',
72
+ enum: ['low', 'medium', 'high', 'xhigh', 'max'],
73
+ description:
74
+ 'Reasoning effort for this sub-agent, same levels as /effort. Higher levels get a longer ' +
75
+ 'streaming idle budget so a long thinking pass is not mistaken for a stalled connection. ' +
76
+ 'Omit to inherit the provider default.',
77
+ },
67
78
  },
68
79
  required: ['description', 'prompt'],
69
80
  },
@@ -80,6 +91,18 @@ export const agentTool: ToolDefinition = {
80
91
  }
81
92
  }
82
93
 
94
+ // Reject rather than pass through: an unrecognized level silently lands on
95
+ // the 1× timeout, i.e. it behaves exactly like omitting the parameter while
96
+ // reading as though it took effect.
97
+ const effort = params.effort as string | undefined
98
+ if (effort !== undefined && !VALID_EFFORTS.includes(effort)) {
99
+ return {
100
+ success: false,
101
+ content: '',
102
+ error: `Invalid effort "${effort}". Valid levels: ${VALID_EFFORTS.join(', ')}`,
103
+ }
104
+ }
105
+
83
106
  const registry = ctx.registry
84
107
  const toolRegistry = ctx.toolRegistry
85
108
  if (!registry || !toolRegistry) {
@@ -112,6 +135,7 @@ export const agentTool: ToolDefinition = {
112
135
  type: agentType,
113
136
  agentDef,
114
137
  runInBackground,
138
+ effort,
115
139
  // Hand the caller's services down: the sub-agent keeps running the same
116
140
  // skills/agents/artifacts, and only the fields it owns are overridden.
117
141
  toolContext: ctx,
@@ -39,6 +39,19 @@ export const skillTool: ToolDefinition = {
39
39
  }
40
40
  }
41
41
 
42
+ // A skill marked `disable-model-invocation` is reserved for the user to run
43
+ // by hand. The broadcast filter (loader.buildSystemReminder) keeps it out of
44
+ // the ambient list, but that is not a gate: the model can still name it —
45
+ // from a compaction summary, a file, or its own memory — and land here. The
46
+ // reservation only holds if it is enforced at the point of use.
47
+ if (skill.disableModelInvocation) {
48
+ return {
49
+ success: false,
50
+ content: '',
51
+ error: `Skill "${skillName}" is reserved for user invocation (disable-model-invocation: true) and cannot be run through the Skill tool. Ask the user to run it.`,
52
+ }
53
+ }
54
+
42
55
  // Extract executable assets (scripts/references) if this skill bundles them.
43
56
  // No-op for every skill that has no entry in BUNDLED_SKILL_ASSETS.
44
57
  // A write failure (EACCES/ENOSPC) must not abort invocation: the skill body
@@ -32,6 +32,16 @@ const BLOCKED_PATTERNS = [
32
32
  // `rm -rf .` and its path spellings `./` and `../` delete the working directory;
33
33
  // `./build` and `../vendor` name an entry inside it and stay allowed.
34
34
  /\brm\s+-(?:rf|fr)\s+['"]?\.\.?(?:\/)?(?=["'\s;&|>]|$)/,
35
+ // The home directory under another name is still the home directory. `$HOME`
36
+ // expands to the same tree as `~`; on Windows `C:\Users\<name>` *is* the profile
37
+ // directory, long or in its 8.3 short form (`C:\Users\GUOHUA~1`). Guarding only
38
+ // the literal spellings above leaves each of these a one-word bypass.
39
+ /\brm\s+-(?:rf|fr)\s+['"]?\$\{?HOME\}?(?:["'\s/]|$)/,
40
+ /\brm\s+-(?:rf|fr)\s+['"]?[A-Za-z]:[\\/](?=["'\s;&|>]|$)/,
41
+ /\brm\s+-(?:rf|fr)\s+['"]?[A-Za-z]:[\\/]Users[\\/][^\\/\s"']+[\\/]?(?=["'\s;&|>]|$)/i,
42
+ // cmd.exe spells the same directories with percent signs; in scope whenever a
43
+ // command hands off to cmd (`cmd /c …`).
44
+ /\brm\s+-(?:rf|fr)\s+['"]?%(?:USERPROFILE|HOMEPATH|HOMEDRIVE)%/i,
35
45
  // Filesystem manipulation
36
46
  /\bmkfs\./,
37
47
  /\bdd\s+if=/,
@@ -94,19 +94,28 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
94
94
  properties: {
95
95
  pattern: { type: 'string', description: 'Regex pattern to search for' },
96
96
  path: { type: 'string', description: 'Directory or file to search in' },
97
+ file_path: {
98
+ type: 'string',
99
+ description:
100
+ 'Alias for "path" — accepted so a caller that names the search root the way Read/Write/Edit do still lands where it meant to.',
101
+ },
97
102
  include: { type: 'string', description: 'File pattern to include (e.g., "*.ts")' },
98
103
  },
99
104
  required: ['pattern'],
100
105
  },
101
106
  async execute(params, ctx) {
102
107
  const pattern = params.pattern as string
103
- const searchPath = resolveSafe(ctx.cwd, (params.path as string) || '.')
108
+ // `file_path` is the alias callers reach for (Read/Write/Edit all use it).
109
+ // Without it the value is dropped and the search silently falls back to `cwd`
110
+ // — answering a question about the wrong tree without saying so.
111
+ const explicitPath = (params.path as string) || (params.file_path as string) || undefined
112
+ const searchPath = resolveSafe(ctx.cwd, explicitPath || '.')
104
113
  const include = params.include as string | undefined
105
114
 
106
115
  // Scope guard: a top-level search root (home or filesystem root) scans an
107
116
  // enormous tree and stalls the find fallback for minutes. Fail fast and
108
117
  // ask for a project-scoped path instead of silently scanning everything.
109
- if (!params.path && isTopLevelScope(searchPath)) {
118
+ if (!explicitPath && isTopLevelScope(searchPath)) {
110
119
  return {
111
120
  success: false,
112
121
  content: '',
package/src/ui/app.tsx CHANGED
@@ -1344,7 +1344,7 @@ export function App({
1344
1344
  ) : (
1345
1345
  <>
1346
1346
  {/* Chat panel */}
1347
- <ChatPanel messages={messages} focusMode={focusMode} />
1347
+ <ChatPanel messages={messages} focusMode={focusMode} turnActive={isLoading} />
1348
1348
  {(() => {
1349
1349
  const indicator = formatThinking(
1350
1350
  config.showThinking ?? 'off',
package/src/ui/chat.tsx CHANGED
@@ -8,6 +8,8 @@ import { homedir } from 'node:os'
8
8
  interface ChatPanelProps {
9
9
  messages: ChatMessage[]
10
10
  focusMode?: boolean
11
+ /** A turn is in flight — the moment the focus tip is worth offering. */
12
+ turnActive?: boolean
11
13
  }
12
14
 
13
15
  /**
@@ -119,7 +121,7 @@ const MessageRow = React.memo(
119
121
  prev.msg.toolMeta?.collapsed === next.msg.toolMeta?.collapsed,
120
122
  )
121
123
 
122
- export function ChatPanel({ messages, focusMode }: ChatPanelProps) {
124
+ export function ChatPanel({ messages, focusMode, turnActive }: ChatPanelProps) {
123
125
  const { t } = useI18n()
124
126
  // Memoize display message computation to avoid O(n) compact on every render.
125
127
  // During streaming, messages changes on every chunk; without memoization,
@@ -140,6 +142,18 @@ export function ChatPanel({ messages, focusMode }: ChatPanelProps) {
140
142
  </Text>
141
143
  </Box>
142
144
  )}
145
+ {/*
146
+ Offer focus while a turn is running — that is when the transcript grows
147
+ fastest and when someone is most likely to want it — rather than only
148
+ documenting it in the idle banner, where it is read before there is
149
+ anything to focus on. Shown only outside focus mode, and the text names
150
+ the way back so trying it cannot strand anyone.
151
+ */}
152
+ {turnActive && !focusMode && messages.length > 0 && (
153
+ <Box marginBottom={1}>
154
+ <Text dimColor>{t('ui.chat.try_focus_tip')}</Text>
155
+ </Box>
156
+ )}
143
157
  {messages.length === 0 && (
144
158
  <Box flexDirection="column">
145
159
  <Box marginBottom={1}>
package/src/ui/input.tsx CHANGED
@@ -323,6 +323,11 @@ export function InputBar({
323
323
  // 下面两个 ref 是**浏览游标**、不是历史本体,随卸载重置才是对的。
324
324
  const historyIndexRef = useRef(-1) // -1 = not browsing history
325
325
  const savedDraftRef = useRef('') // saved user draft before browsing history
326
+ // 被清空的草稿的**可恢复槽**:Escape 清空输入时落这里,下一次 Up(输入为空且未在
327
+ // 翻历史)把它放回去。仅靠 history 不够 —— 半途写了一半的行从没进过 history,
328
+ // 清掉就是没了。与 savedDraftRef 分开:那个槽的语义是「翻历史前的草稿」,会被
329
+ // Down 一路用掉,混用会让 Up 第一下就落到更早的历史条目上。
330
+ const clearedDraftRef = useRef('')
326
331
 
327
332
  // ── Ghost-text 自动补全 ──
328
333
  const [suggestion, setSuggestion] = useState<string | null>(null)
@@ -418,7 +423,9 @@ export function InputBar({
418
423
  onCancel?.()
419
424
  return
420
425
  }
421
- // Idle → clear the draft (the intuitive "cancel")
426
+ // Idle → clear the draft (the intuitive "cancel"), keeping it recoverable:
427
+ // Up from the now-empty input restores it (see the arrow-key branch).
428
+ if (valueRef.current) clearedDraftRef.current = valueRef.current
422
429
  setValue('')
423
430
  valueRef.current = ''
424
431
  clearSuggestion()
@@ -469,6 +476,23 @@ export function InputBar({
469
476
  // Ignore if picker is active (command picker handles its own arrows)
470
477
  if (value.startsWith('/')) return
471
478
 
479
+ // A draft Escape cleared is still the user's text, and it is the *only*
480
+ // copy: unlike a sent message or a slash command it never entered history.
481
+ // Bring it back on the first Up from an empty input instead of walking into
482
+ // history, whose first step would land on an older entry and leave this
483
+ // text with nowhere to come back from.
484
+ if (
485
+ key.upArrow &&
486
+ historyIndexRef.current === -1 &&
487
+ valueRef.current === '' &&
488
+ clearedDraftRef.current
489
+ ) {
490
+ const restored = clearedDraftRef.current
491
+ clearedDraftRef.current = ''
492
+ setValue(restored)
493
+ return
494
+ }
495
+
472
496
  const result = navigateHistory(
473
497
  {
474
498
  history,
@@ -118,6 +118,7 @@ export async function workflowAgent(
118
118
  const textResult = await sub.execute(retryPrompt, opts.label || 'workflow-agent', {
119
119
  type: 'general',
120
120
  modelOverride: opts.model,
121
+ effort: opts.effort,
121
122
  allowedTools: undefined, // use all tools by default
122
123
  worktreePath,
123
124
  // The prompt is computed by the script, not typed by the user — say so,