@miphamai/cli 0.85.18 → 0.85.20

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.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/agent-registry.ts +2 -0
  4. package/src/agent/auto-compact.ts +72 -0
  5. package/src/agent/sub-agent.ts +26 -1
  6. package/src/agent/types.ts +18 -0
  7. package/src/agent-view/agent-view-manager.ts +50 -0
  8. package/src/core/context.ts +15 -3
  9. package/src/core/engine.ts +52 -5
  10. package/src/core/instructions.ts +78 -2
  11. package/src/daemon/channel-message.ts +8 -1
  12. package/src/daemon/session-worker.ts +17 -2
  13. package/src/i18n-core/locales/en-US.json +13 -3
  14. package/src/i18n-core/locales/zh-CN.json +13 -3
  15. package/src/index.tsx +8 -0
  16. package/src/mcp/client.ts +46 -0
  17. package/src/mcp/instructions.ts +48 -10
  18. package/src/mcp/protocol.ts +69 -2
  19. package/src/mcp/registry.ts +2 -1
  20. package/src/mcp/transport.ts +70 -9
  21. package/src/plugin/plugin-manager.ts +29 -8
  22. package/src/providers/fetch-utils.ts +47 -2
  23. package/src/security/fd.ts +18 -0
  24. package/src/shared/package-info.ts +2 -2
  25. package/src/shared/sanitize.ts +6 -2
  26. package/src/shared/types.ts +16 -0
  27. package/src/skills/marketplace.ts +15 -5
  28. package/src/skills/registry.ts +4 -1
  29. package/src/tools/agent/agent.ts +24 -0
  30. package/src/tools/agent/skill.ts +13 -0
  31. package/src/tools/exec/bash.ts +10 -0
  32. package/src/tools/file/edit.ts +13 -2
  33. package/src/tools/file/grep.ts +11 -2
  34. package/src/tools/file/read.ts +30 -6
  35. package/src/tools/file/write.ts +22 -2
  36. package/src/tools/system/tool-search.ts +2 -1
  37. package/src/ui/agent-footer.tsx +16 -3
  38. package/src/ui/app.tsx +67 -15
  39. package/src/ui/chat.tsx +73 -11
  40. package/src/ui/commands.ts +35 -11
  41. package/src/ui/copy-picker.tsx +73 -0
  42. package/src/ui/input.tsx +137 -21
  43. package/src/workflow/primitives/agent.ts +24 -3
package/src/ui/chat.tsx CHANGED
@@ -2,27 +2,65 @@ import React, { useMemo } from 'react'
2
2
  import { Box, Text } from 'ink'
3
3
  import { useI18n } from '../i18n-context'
4
4
  import type { ChatMessage } from './app'
5
- import { decodeDisplayEntities, stripControlCharsForDisplay } from '../shared/sanitize'
5
+ import {
6
+ decodeDisplayEntities,
7
+ sanitizeInlineField,
8
+ stripControlCharsForDisplay,
9
+ } from '../shared/sanitize'
6
10
  import { homedir } from 'node:os'
7
11
 
8
12
  interface ChatPanelProps {
9
13
  messages: ChatMessage[]
10
14
  focusMode?: boolean
15
+ /** A turn is in flight — the moment the focus tip is worth offering. */
16
+ turnActive?: boolean
11
17
  }
12
18
 
13
19
  /**
14
- * The single point where untrusted text becomes terminal output.
20
+ * The port untrusted **multi-line** text takes to terminal output.
15
21
  *
16
- * Everything this component prints that did not come from a literal in the file —
17
- * tool arguments, tool output, model prose — passes through here. Control
18
- * characters in those strings are not visible content; they are terminal
19
- * instructions (CR overwrites the row, ESC starts a sequence), so they are removed
20
- * rather than shown. See `stripControlCharsForDisplay` for what is kept and why.
22
+ * Tool arguments, tool output and model prose pass through here; `\n` is kept
23
+ * because those are legitimately multi-line. Control characters in them are not
24
+ * visible content; they are terminal instructions (CR overwrites the row, ESC
25
+ * starts a sequence), so they are removed rather than shown. See
26
+ * `stripControlCharsForDisplay` for what is kept and why.
27
+ *
28
+ * **One-line fields do not come through here.** A tool *name* is rendered on a row
29
+ * of its own, where the `\n` this function keeps forges an extra row — so names go
30
+ * through `sanitizeInlineField` (the same recipe minus `\n`), the way
31
+ * `agent-footer.tsx` and `input.tsx` already do. The name below used to be
32
+ * interpolated raw, on the theory that this function was the only way in; it is not.
21
33
  */
22
34
  function display(text: string): string {
23
35
  return stripControlCharsForDisplay(text)
24
36
  }
25
37
 
38
+ /**
39
+ * Render at most this many lines of a message body.
40
+ *
41
+ * Ink lays out the *whole* string on every render, and a streamed turn re-renders
42
+ * continuously — so a model answer of tens of thousands of lines (a dumped file,
43
+ * a runaway loop) makes every chunk reflow the entire body, at ~16 fps. The tail
44
+ * is dropped with a visible count rather than silently: the model may well have
45
+ * written something worth scrolling to, and a truncated view that says so lets
46
+ * the user ask for the rest instead of believing they saw all of it.
47
+ *
48
+ * Applied to every non-tool body (user pastes hit the same wall).
49
+ */
50
+ const MAX_RENDERED_LINES = 50
51
+
52
+ function capRenderedLines(text: string): string {
53
+ let newlines = 0
54
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) newlines++
55
+ if (newlines < MAX_RENDERED_LINES) return text
56
+ const lines = text.split('\n')
57
+ const hidden = lines.length - MAX_RENDERED_LINES
58
+ return (
59
+ lines.slice(0, MAX_RENDERED_LINES).join('\n') +
60
+ `\n… ${hidden} more line${hidden === 1 ? '' : 's'}`
61
+ )
62
+ }
63
+
26
64
  /** Format cwd for display: replace HOME with ~, truncate if too long */
27
65
  function displayCwd(): string {
28
66
  const cwd = process.cwd()
@@ -78,12 +116,21 @@ const MessageRow = React.memo(
78
116
  {/* Tool call line: ⏺ ToolName(detail) — Claude Code parity */}
79
117
  {msg.toolMeta.name ? (
80
118
  <Text color={toolColor(msg.toolMeta.name)}>
81
- {msg.toolMeta.collapsed ? '⏺' : '⏺ ▼'} {msg.toolMeta.name}
119
+ {msg.toolMeta.collapsed ? '⏺' : '⏺ ▼'} {sanitizeInlineField(msg.toolMeta.name)}
82
120
  {msg.toolMeta.input ? ` (${display(msg.toolMeta.input).slice(0, 120)})` : ''}
83
121
  </Text>
84
122
  ) : null}
85
123
  {/* Tool result line: ⎿ summary text */}
86
- {msg.toolMeta.output ? (
124
+ {msg.toolMeta.notRun ? (
125
+ // Held back by the auto-mode classifier: it never ran, so the text
126
+ // below is the *reason*, not output. Labelling it keeps a held-back
127
+ // call from reading as a tool that ran and returned this (296-056).
128
+ <Text dimColor>
129
+ {' ⎿ '}
130
+ {t('ui.tool.not_run')}
131
+ {msg.toolMeta.output ? ` — ${display(msg.toolMeta.output).slice(0, 300)}` : ''}
132
+ </Text>
133
+ ) : msg.toolMeta.output ? (
87
134
  <Text dimColor>
88
135
  {' ⎿ '}
89
136
  {display(msg.toolMeta.output).slice(0, 300)}
@@ -107,7 +154,7 @@ const MessageRow = React.memo(
107
154
  ⚠ {t('ui.system.role_label')}:
108
155
  </Text>
109
156
  ) : null}
110
- <Text>{display(decodeDisplayEntities(msg.content))}</Text>
157
+ <Text>{capRenderedLines(display(decodeDisplayEntities(msg.content)))}</Text>
111
158
  </>
112
159
  )}
113
160
  </Box>
@@ -119,7 +166,7 @@ const MessageRow = React.memo(
119
166
  prev.msg.toolMeta?.collapsed === next.msg.toolMeta?.collapsed,
120
167
  )
121
168
 
122
- export function ChatPanel({ messages, focusMode }: ChatPanelProps) {
169
+ export function ChatPanel({ messages, focusMode, turnActive }: ChatPanelProps) {
123
170
  const { t } = useI18n()
124
171
  // Memoize display message computation to avoid O(n) compact on every render.
125
172
  // During streaming, messages changes on every chunk; without memoization,
@@ -140,6 +187,18 @@ export function ChatPanel({ messages, focusMode }: ChatPanelProps) {
140
187
  </Text>
141
188
  </Box>
142
189
  )}
190
+ {/*
191
+ Offer focus while a turn is running — that is when the transcript grows
192
+ fastest and when someone is most likely to want it — rather than only
193
+ documenting it in the idle banner, where it is read before there is
194
+ anything to focus on. Shown only outside focus mode, and the text names
195
+ the way back so trying it cannot strand anyone.
196
+ */}
197
+ {turnActive && !focusMode && messages.length > 0 && (
198
+ <Box marginBottom={1}>
199
+ <Text dimColor>{t('ui.chat.try_focus_tip')}</Text>
200
+ </Box>
201
+ )}
143
202
  {messages.length === 0 && (
144
203
  <Box flexDirection="column">
145
204
  <Box marginBottom={1}>
@@ -203,6 +262,9 @@ function compactToolGroups(messages: ChatMessage[]): ChatMessage[] {
203
262
  toolMeta: {
204
263
  ...current.toolMeta!,
205
264
  output: msg.toolMeta.output,
265
+ // 结果行上的标记必须跟着合并走:合并把结果行的 toolMeta 并进工具调用行,
266
+ // 漏掉它,`notRun` 就停在**没人渲染的那一份**上(296-056)。
267
+ ...(msg.toolMeta.notRun ? { notRun: true } : {}),
206
268
  },
207
269
  }
208
270
  }
@@ -12,6 +12,7 @@ import type { SkillsLoader } from '../skills/loader'
12
12
  import { loadSkillUsage } from '../skills/usage'
13
13
  import type { PluginManager } from '../plugin/plugin-manager'
14
14
  import type { Message } from '../shared/types.js'
15
+ import type { CopyPickerItem } from './copy-picker'
15
16
  import type { InstallState, UpdateStatus } from '../shared/update'
16
17
  import { McpClient } from '../mcp/client'
17
18
  import { registerMcpServerTools, unregisterMcpServerTools } from '../mcp/registry'
@@ -153,6 +154,8 @@ export interface CommandResult {
153
154
  clearMessages?: boolean
154
155
  /** Content to copy to clipboard (handled by caller) */
155
156
  copyContent?: string
157
+ /** If set, open the `/copy` picker with these candidates (handled by caller). */
158
+ openCopyPicker?: CopyPickerItem[]
156
159
  /** If set, route this message to the AI engine — bridges slash commands → skill/agent invocation.
157
160
  * The app layer replaces the user input with this string and falls through to AI processing. */
158
161
  forwardToAI?: string
@@ -2624,7 +2627,10 @@ const marketplaceCmd: CommandHandler = async (_ctx, args) => {
2624
2627
  const { dirname } = await import('node:path')
2625
2628
 
2626
2629
  const readSources = () =>
2627
- readMarketplaces((p) => (existsSync(p) ? readFileSync(p, 'utf-8') : null))
2630
+ readMarketplaces(
2631
+ (p) => (existsSync(p) ? readFileSync(p, 'utf-8') : null),
2632
+ (m) => console.error(`⚠ ${m}`),
2633
+ )
2628
2634
 
2629
2635
  const sub = args[0]
2630
2636
  const ref = args[1]
@@ -2674,7 +2680,10 @@ const browseMarketplaceCmd: CommandHandler = async (_ctx) => {
2674
2680
  const { readMarketplaces, discoverSkills, downloadFile } = await import('../skills/marketplace')
2675
2681
  const { readFileSync, existsSync } = await import('node:fs')
2676
2682
 
2677
- const sources = readMarketplaces((p) => (existsSync(p) ? readFileSync(p, 'utf-8') : null))
2683
+ const sources = readMarketplaces(
2684
+ (p) => (existsSync(p) ? readFileSync(p, 'utf-8') : null),
2685
+ (m) => console.error(`⚠ ${m}`),
2686
+ )
2678
2687
  const lines = ['── Marketplace Skills ──', '']
2679
2688
  for (const source of sources) {
2680
2689
  lines.push(` ${source.owner}/${source.repo}:`)
@@ -2900,23 +2909,38 @@ const copyCmd: CommandHandler = (ctx, args) => {
2900
2909
  return { content: t('commands.copy.no_responses') }
2901
2910
  }
2902
2911
 
2903
- // Determine which response to copy: last N or last 1
2904
- let n = 1
2912
+ const textOf = (m: (typeof assistantMsgs)[number]) =>
2913
+ typeof m.content === 'string' ? m.content : JSON.stringify(m.content)
2914
+
2915
+ // `/copy N` — explicit count, unchanged: no picker, straight to the clipboard.
2905
2916
  if (args[0]) {
2906
- n = parseInt(args[0]!, 10)
2917
+ const n = parseInt(args[0]!, 10)
2907
2918
  if (isNaN(n) || n < 1) {
2908
2919
  return { content: t('commands.copy.usage') }
2909
2920
  }
2921
+ const toCopy = assistantMsgs.slice(-n)
2922
+ return {
2923
+ content: t('commands.copy.confirmed', { count: String(toCopy.length) }),
2924
+ copyContent: toCopy.map(textOf).join('\n\n---\n\n'),
2925
+ }
2910
2926
  }
2911
2927
 
2912
- const toCopy = assistantMsgs.slice(-n)
2913
- const text = toCopy
2914
- .map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content)))
2915
- .join('\n\n---\n\n')
2928
+ // Bare `/copy` — one response has nothing to choose between, so copy it; a
2929
+ // stock of them opens the picker instead of guessing at "the last one".
2930
+ if (assistantMsgs.length === 1) {
2931
+ return {
2932
+ content: t('commands.copy.confirmed', { count: '1' }),
2933
+ copyContent: textOf(assistantMsgs[0]!),
2934
+ }
2935
+ }
2916
2936
 
2917
2937
  return {
2918
- content: t('commands.copy.confirmed', { count: String(toCopy.length) }),
2919
- copyContent: text,
2938
+ content: t('commands.copy.pick_prompt'),
2939
+ openCopyPicker: assistantMsgs.map((m, i) => {
2940
+ const body = textOf(m)
2941
+ const firstLine = (body.split('\n', 1)[0] ?? '').slice(0, 60)
2942
+ return { label: `#${assistantMsgs.length - i} · ${firstLine}`, text: body }
2943
+ }),
2920
2944
  }
2921
2945
  }
2922
2946
 
@@ -0,0 +1,73 @@
1
+ import React from 'react'
2
+ import { Box, Text, useInput } from 'ink'
3
+ import { useI18n } from '../i18n-context'
4
+ import { useKeyState } from './use-key-state'
5
+
6
+ /**
7
+ * One candidate for `/copy`: a preview line to show, and the full text to put on
8
+ * the clipboard. The preview is deliberately a *summary* — the body can be huge,
9
+ * and the picker is about telling responses apart, not reading them.
10
+ */
11
+ export interface CopyPickerItem {
12
+ label: string
13
+ text: string
14
+ }
15
+
16
+ const wrap = (i: number, len: number) => ((i % len) + len) % len
17
+
18
+ /**
19
+ * `/copy` 无参数时的交互选择器。
20
+ *
21
+ * 此前 `/copy` 只会「复制最近 N 条」—— 想复制第 3 条近的回复,得先数清顺序、再敲
22
+ * `/copy` 一个数字,且看不到任何候选。这里把最近几条助手回复列出来,上下键选、回车复制。
23
+ * 键位与 `ModelPicker` 同源(↑↓ 移动、Enter 确认、Esc 关闭),并且和它一样走
24
+ * `useKeyState` —— 判据读 `read()` 而不是渲染闭包,否则「↓ Enter」会复制到上一行。
25
+ */
26
+ export function CopyPicker({
27
+ items,
28
+ onSelect,
29
+ onClose,
30
+ }: {
31
+ items: CopyPickerItem[]
32
+ onSelect: (item: CopyPickerItem) => void
33
+ onClose: () => void
34
+ }) {
35
+ const { t } = useI18n()
36
+ const idx = useKeyState(() => items.length - 1) // 默认停在最近一条
37
+
38
+ useInput((_input, key) => {
39
+ if (key.escape) {
40
+ onClose()
41
+ return
42
+ }
43
+ if (key.return) {
44
+ const item = items[idx.read()]
45
+ if (item) onSelect(item)
46
+ return
47
+ }
48
+ if (key.upArrow) idx.set((prev) => wrap(prev - 1, items.length))
49
+ if (key.downArrow) idx.set((prev) => wrap(prev + 1, items.length))
50
+ })
51
+
52
+ return (
53
+ <Box flexDirection="column" borderStyle="round" borderColor="cyan" padding={1}>
54
+ <Box marginBottom={1}>
55
+ <Text bold color="cyan">
56
+ {t('ui.copy_picker.title')}
57
+ </Text>
58
+ <Text dimColor> {t('ui.copy_picker.nav_help')}</Text>
59
+ </Box>
60
+ {items.map((item, i) => {
61
+ const isSelected = i === idx.value
62
+ return (
63
+ <Box key={i}>
64
+ <Text color={isSelected ? 'cyan' : 'white'} bold={isSelected}>
65
+ {isSelected ? '▶ ' : ' '}
66
+ {item.label}
67
+ </Text>
68
+ </Box>
69
+ )
70
+ })}
71
+ </Box>
72
+ )
73
+ }
package/src/ui/input.tsx CHANGED
@@ -6,6 +6,7 @@ import { useI18n } from '../i18n-context'
6
6
  import { discoverSessions } from '../agent/cross-session/discovery'
7
7
  import { requestSuggestion, shouldAutocomplete, type RecentMessage } from '../core/autocomplete'
8
8
  import type { Llm } from '../providers/llm'
9
+ import { sanitizeInlineField } from '../shared/sanitize'
9
10
 
10
11
  interface InputBarProps {
11
12
  onSubmit: (input: string) => void
@@ -108,26 +109,101 @@ export type EditAction =
108
109
  | { type: 'delete' }
109
110
  | { type: 'insert'; text: string }
110
111
 
112
+ const graphemeSegmenter =
113
+ typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
114
+ ? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
115
+ : null
116
+
117
+ /**
118
+ * Split a string into user-perceived characters (grapheme clusters), each with
119
+ * its start offset in UTF-16 code units.
120
+ *
121
+ * The cursor used to count code units, so on macOS filesystem names — stored NFD,
122
+ * where `é` is `e` + a combining accent — an arrow key could park the caret
123
+ * *inside* a character, and Backspace deleted half of one. `Intl.Segmenter` is the
124
+ * only thing that gets this right across emoji ZWJ sequences and combining marks;
125
+ * `Array.from` (code-point split) is the fallback when the runtime lacks it, and
126
+ * still beats splitting surrogates.
127
+ */
128
+ function graphemes(value: string): Array<{ segment: string; index: number }> {
129
+ if (graphemeSegmenter) {
130
+ return Array.from(graphemeSegmenter.segment(value), (s) => ({
131
+ segment: s.segment,
132
+ index: s.index,
133
+ }))
134
+ }
135
+ const out: Array<{ segment: string; index: number }> = []
136
+ let index = 0
137
+ for (const segment of value) {
138
+ out.push({ segment, index })
139
+ index += segment.length
140
+ }
141
+ return out
142
+ }
143
+
144
+ /** Start offset of the grapheme immediately before `cursor` (0 at the beginning). */
145
+ function prevGraphemeStart(value: string, cursor: number): number {
146
+ let start = 0
147
+ for (const { index } of graphemes(value)) {
148
+ if (index >= cursor) break
149
+ start = index
150
+ }
151
+ return start
152
+ }
153
+
154
+ /** End offset of the grapheme at or immediately after `cursor`. */
155
+ function nextGraphemeEnd(value: string, cursor: number): number {
156
+ for (const { segment, index } of graphemes(value)) {
157
+ if (index + segment.length > cursor) return index + segment.length
158
+ }
159
+ return value.length
160
+ }
161
+
162
+ /**
163
+ * The grapheme starting exactly at `cursor`, or null when the cursor sits at the
164
+ * end (or, defensively, mid-cluster). Used to draw one whole character under the
165
+ * block cursor instead of a single code unit.
166
+ */
167
+ export function graphemeAt(
168
+ value: string,
169
+ cursor: number,
170
+ ): { segment: string; start: number; end: number } | null {
171
+ for (const { segment, index } of graphemes(value)) {
172
+ if (index === cursor) return { segment, start: index, end: index + segment.length }
173
+ if (index > cursor) break
174
+ }
175
+ return null
176
+ }
177
+
111
178
  /**
112
179
  * Pure cursor-editing transition. Returns a new state (or the same state when
113
- * the action is a no-op). Cursor is always clamped to [0, value.length].
180
+ * the action is a no-op). The cursor always lands on a grapheme boundary, so a
181
+ * step never splits a character the user sees as one.
114
182
  */
115
183
  export function applyEdit(state: EditState, action: EditAction): EditState {
116
184
  const { value, cursor } = state
117
185
  switch (action.type) {
118
- case 'moveLeft':
119
- return { value, cursor: Math.max(0, cursor - 1) }
120
- case 'moveRight':
121
- return { value, cursor: Math.min(value.length, cursor + 1) }
122
- case 'backspace':
186
+ case 'moveLeft': {
187
+ const prev = prevGraphemeStart(value, cursor)
188
+ return prev === cursor ? state : { value, cursor: prev }
189
+ }
190
+ case 'moveRight': {
191
+ const next = nextGraphemeEnd(value, cursor)
192
+ return next === cursor ? state : { value, cursor: next }
193
+ }
194
+ case 'backspace': {
123
195
  if (cursor === 0) return state
196
+ const start = prevGraphemeStart(value, cursor)
124
197
  return {
125
- value: value.slice(0, cursor - 1) + value.slice(cursor),
126
- cursor: cursor - 1,
198
+ value: value.slice(0, start) + value.slice(cursor),
199
+ cursor: start,
127
200
  }
128
- case 'delete':
201
+ }
202
+ case 'delete': {
129
203
  if (cursor >= value.length) return state
130
- return { value: value.slice(0, cursor) + value.slice(cursor + 1), cursor }
204
+ const end = nextGraphemeEnd(value, cursor)
205
+ return { value: value.slice(0, cursor) + value.slice(end), cursor }
206
+ }
131
207
  case 'insert': {
132
208
  if (!action.text) return state
133
209
  return {
@@ -280,13 +356,25 @@ function MiphamTextInput({
280
356
  // **前景色**,主题一换就变成别的颜色;而「白色直立长方形」是定死的形状要求。
281
357
  // 落在字符上时即「白块挖空一个黑字」;落在末尾时 `value[cursor]` 是 undefined,
282
358
  // 用空格补 —— 空格加背景色就是一整个实心方块。
359
+ // The block covers one whole grapheme, not one code unit: `value[cursor]` on a
360
+ // surrogate pair (emoji) or an NFD accent is half a character, and rendering a
361
+ // lone surrogate puts a replacement glyph on screen.
362
+ const atCursor = graphemeAt(value, cursor)
363
+ // 回显是通往终端的**一道口**(chat.tsx 的 `display()` 管的是转录,不是这里):
364
+ // 从终端复制来的命令常带颜色转义(`\x1b[31m…`),而 value 除 `\r\n\t` 外不做净化
365
+ // (见 `normalizeInput`)—— 原样渲染时终端把它当控制序列执行,而不是当文字显示。
366
+ // 逐段过单行口,且**前缀与后缀分开净化**:方块的位置由净化后的前缀长度决定,
367
+ // 整串先净化再按原 cursor 切会把方块挪到别的字上。
368
+ const before = sanitizeInlineField(value.slice(0, cursor))
369
+ const atChar = atCursor ? sanitizeInlineField(atCursor.segment) : ''
370
+ const after = atCursor ? sanitizeInlineField(value.slice(atCursor.end)) : ''
283
371
  return (
284
372
  <Text>
285
- {value.slice(0, cursor)}
373
+ {before}
286
374
  <Text backgroundColor="white" color="black">
287
- {value[cursor] ?? ' '}
375
+ {atChar || ' '}
288
376
  </Text>
289
- {value.slice(cursor + 1)}
377
+ {after}
290
378
  {value.length === 0 && placeholder ? <Text dimColor>{placeholder}</Text> : null}
291
379
  </Text>
292
380
  )
@@ -323,6 +411,11 @@ export function InputBar({
323
411
  // 下面两个 ref 是**浏览游标**、不是历史本体,随卸载重置才是对的。
324
412
  const historyIndexRef = useRef(-1) // -1 = not browsing history
325
413
  const savedDraftRef = useRef('') // saved user draft before browsing history
414
+ // 被清空的草稿的**可恢复槽**:Escape 清空输入时落这里,下一次 Up(输入为空且未在
415
+ // 翻历史)把它放回去。仅靠 history 不够 —— 半途写了一半的行从没进过 history,
416
+ // 清掉就是没了。与 savedDraftRef 分开:那个槽的语义是「翻历史前的草稿」,会被
417
+ // Down 一路用掉,混用会让 Up 第一下就落到更早的历史条目上。
418
+ const clearedDraftRef = useRef('')
326
419
 
327
420
  // ── Ghost-text 自动补全 ──
328
421
  const [suggestion, setSuggestion] = useState<string | null>(null)
@@ -418,7 +511,9 @@ export function InputBar({
418
511
  onCancel?.()
419
512
  return
420
513
  }
421
- // Idle → clear the draft (the intuitive "cancel")
514
+ // Idle → clear the draft (the intuitive "cancel"), keeping it recoverable:
515
+ // Up from the now-empty input restores it (see the arrow-key branch).
516
+ if (valueRef.current) clearedDraftRef.current = valueRef.current
422
517
  setValue('')
423
518
  valueRef.current = ''
424
519
  clearSuggestion()
@@ -426,13 +521,17 @@ export function InputBar({
426
521
  }
427
522
 
428
523
  // ── Global hotkeys ──
429
- // Shift+Tab → cycle permission mode
430
- if (key.shift && key.tab) {
524
+ // Shift+Tab → cycle permission mode.
525
+ // The modifiers are excluded deliberately: Ink's parser reports
526
+ // Ctrl+Shift+Tab (`\x1b[1;5Z`) and Alt+Shift+Tab (`\x1b[1;3Z`) as
527
+ // `{tab:true, shift:true, ctrl/meta:true}` — without these guards those
528
+ // combos would also cycle the mode, hijacking a chord the user did not ask for.
529
+ if (key.shift && key.tab && !key.ctrl && !key.meta) {
431
530
  onCyclePermission?.()
432
531
  return
433
532
  }
434
- // Tab → 接受 ghost-text 建议
435
- if (key.tab && !key.shift && suggestion) {
533
+ // Tab → 接受 ghost-text 建议(同样排除 ctrl/meta —— Ctrl+Tab / Alt+Tab 不是「接受」)
534
+ if (key.tab && !key.shift && !key.ctrl && !key.meta && suggestion) {
436
535
  const next = valueRef.current + suggestion
437
536
  setValue(next)
438
537
  valueRef.current = next
@@ -469,6 +568,23 @@ export function InputBar({
469
568
  // Ignore if picker is active (command picker handles its own arrows)
470
569
  if (value.startsWith('/')) return
471
570
 
571
+ // A draft Escape cleared is still the user's text, and it is the *only*
572
+ // copy: unlike a sent message or a slash command it never entered history.
573
+ // Bring it back on the first Up from an empty input instead of walking into
574
+ // history, whose first step would land on an older entry and leave this
575
+ // text with nowhere to come back from.
576
+ if (
577
+ key.upArrow &&
578
+ historyIndexRef.current === -1 &&
579
+ valueRef.current === '' &&
580
+ clearedDraftRef.current
581
+ ) {
582
+ const restored = clearedDraftRef.current
583
+ clearedDraftRef.current = ''
584
+ setValue(restored)
585
+ return
586
+ }
587
+
472
588
  const result = navigateHistory(
473
589
  {
474
590
  history,
@@ -593,7 +709,7 @@ export function InputBar({
593
709
  isLoading ? `${verb}...` : completionVerb ? completionVerb : t('ui.input.placeholder')
594
710
  }
595
711
  />
596
- {suggestion && <Text dimColor>{suggestion}</Text>}
712
+ {suggestion && <Text dimColor>{sanitizeInlineField(suggestion)}</Text>}
597
713
  </Box>
598
714
  {/* Slash command hints — shown when typing / (only when picker is NOT active) */}
599
715
  {slashHints.length > 0 && !pickerActive && (
@@ -601,7 +717,7 @@ export function InputBar({
601
717
  <Text dimColor>{t('ui.slash_hints.label')} </Text>
602
718
  {slashHints.map((cmd, _i) => (
603
719
  <Text key={cmd.name} color="cyan">
604
- {cmd.name}
720
+ {sanitizeInlineField(cmd.name)}
605
721
  </Text>
606
722
  ))}
607
723
  <Text dimColor>
@@ -622,7 +738,7 @@ export function InputBar({
622
738
  <Text dimColor>{t('ui.mention_hints.label')} </Text>
623
739
  {mentionHints.map((name) => (
624
740
  <Text key={name} color="green">
625
- {name}
741
+ {sanitizeInlineField(name)}
626
742
  </Text>
627
743
  ))}
628
744
  </Box>
@@ -7,6 +7,21 @@ import type { PermissionSystem } from '../../core/permission'
7
7
  import { worktreeRoot } from '../../core/paths.ts'
8
8
  import { validateJSONSchema, formatValidationErrors } from '../schema-validator'
9
9
 
10
+ /**
11
+ * Effective model for a workflow agent.
12
+ *
13
+ * Precedence: an explicit per-call `model` (the script named one) wins; else the
14
+ * environment default `MIPHAM_WORKFLOW_AGENT_MODEL`; else none (the session model
15
+ * routing the registry already holds). Read *here* on purpose — the env is scoped
16
+ * to workflow agents only, so a SubAgent spawned by the engine or `/bg` is
17
+ * unaffected. Read per call so a test can set it without re-importing.
18
+ */
19
+ export function resolveWorkflowAgentModel(model?: string): string | undefined {
20
+ if (model !== undefined) return model
21
+ const raw = process.env.MIPHAM_WORKFLOW_AGENT_MODEL
22
+ return raw && raw.trim() !== '' ? raw.trim() : undefined
23
+ }
24
+
10
25
  export interface WorkflowAgentOpts {
11
26
  label?: string
12
27
  phase?: string
@@ -47,6 +62,11 @@ export async function workflowAgent(
47
62
  llm?: Llm,
48
63
  ): Promise<unknown> {
49
64
  const maxRetries = opts.maxRetries ?? 2
65
+ // The model actually applied this call — per-call `opts.model` else the
66
+ // `MIPHAM_WORKFLOW_AGENT_MODEL` default. Used both for the temporary provider
67
+ // switch below and for the sub-agent's own `modelOverride` (they must agree,
68
+ // or the switch would route one model while the sub-agent asked for another).
69
+ const effectiveModel = resolveWorkflowAgentModel(opts.model)
50
70
 
51
71
  // ── Worktree isolation setup ──
52
72
  let worktreePath: string | undefined
@@ -98,11 +118,11 @@ export async function workflowAgent(
98
118
  //
99
119
  // 切在这里而不是函数开头:上面那段建 worktree 会抛(`git worktree add` 非 0 即
100
120
  // throw),抛在切走之前就不该已经切走。
101
- if (opts.provider || opts.model) {
121
+ if (opts.provider || effectiveModel) {
102
122
  const prevProviderId = registry.getActive().config.id
103
123
  const prevModelId = registry.getActiveModel()
104
124
  // `opts.provider` 缺席时只换模型 —— provider 保持这一次调用开始时的那一个。
105
- registry.switchProvider(opts.provider ?? prevProviderId, opts.model)
125
+ registry.switchProvider(opts.provider ?? prevProviderId, effectiveModel)
106
126
  restore = () => registry.switchProvider(prevProviderId, prevModelId)
107
127
  }
108
128
 
@@ -117,7 +137,8 @@ export async function workflowAgent(
117
137
 
118
138
  const textResult = await sub.execute(retryPrompt, opts.label || 'workflow-agent', {
119
139
  type: 'general',
120
- modelOverride: opts.model,
140
+ modelOverride: effectiveModel,
141
+ effort: opts.effort,
121
142
  allowedTools: undefined, // use all tools by default
122
143
  worktreePath,
123
144
  // The prompt is computed by the script, not typed by the user — say so,