@miphamai/cli 0.85.19 → 0.85.21

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.
@@ -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
  )
@@ -433,13 +521,17 @@ export function InputBar({
433
521
  }
434
522
 
435
523
  // ── Global hotkeys ──
436
- // Shift+Tab → cycle permission mode
437
- 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) {
438
530
  onCyclePermission?.()
439
531
  return
440
532
  }
441
- // Tab → 接受 ghost-text 建议
442
- 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) {
443
535
  const next = valueRef.current + suggestion
444
536
  setValue(next)
445
537
  valueRef.current = next
@@ -617,7 +709,7 @@ export function InputBar({
617
709
  isLoading ? `${verb}...` : completionVerb ? completionVerb : t('ui.input.placeholder')
618
710
  }
619
711
  />
620
- {suggestion && <Text dimColor>{suggestion}</Text>}
712
+ {suggestion && <Text dimColor>{sanitizeInlineField(suggestion)}</Text>}
621
713
  </Box>
622
714
  {/* Slash command hints — shown when typing / (only when picker is NOT active) */}
623
715
  {slashHints.length > 0 && !pickerActive && (
@@ -625,7 +717,7 @@ export function InputBar({
625
717
  <Text dimColor>{t('ui.slash_hints.label')} </Text>
626
718
  {slashHints.map((cmd, _i) => (
627
719
  <Text key={cmd.name} color="cyan">
628
- {cmd.name}
720
+ {sanitizeInlineField(cmd.name)}
629
721
  </Text>
630
722
  ))}
631
723
  <Text dimColor>
@@ -646,7 +738,7 @@ export function InputBar({
646
738
  <Text dimColor>{t('ui.mention_hints.label')} </Text>
647
739
  {mentionHints.map((name) => (
648
740
  <Text key={name} color="green">
649
- {name}
741
+ {sanitizeInlineField(name)}
650
742
  </Text>
651
743
  ))}
652
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,7 @@ 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,
121
141
  effort: opts.effort,
122
142
  allowedTools: undefined, // use all tools by default
123
143
  worktreePath,