@miphamai/cli 0.85.52 → 0.85.54

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/src/ui/picker.tsx CHANGED
@@ -10,6 +10,28 @@ const wrap = (i: number, len: number) => ((i % len) + len) % len
10
10
  /** 只列启用中的模型(与 `providerList` 的 `upcoming` 过滤同一条口径)。 */
11
11
  const activeModels = (p: ProviderConfig) => p.models.filter((m) => m.status === 'active')
12
12
 
13
+ type ModelInfo = ProviderConfig['models'][number]
14
+
15
+ /**
16
+ * 超过这个数量才开搜索框。
17
+ *
18
+ * 阈值存在的理由:少量模型时逐行看比先打字再选更快,且搜索开启会吃掉 `h`/`l`
19
+ * 两个单键导航;因此只在「列表长到需要筛选」时才接管可打印字符。
20
+ */
21
+ export const MODEL_SEARCH_THRESHOLD = 25
22
+
23
+ /**
24
+ * 按 id 或 name 做大小写无关的子串匹配。
25
+ *
26
+ * 渲染与判据(Enter/方向键)都走这一个函数 —— 判据若读渲染闭包里的列表,
27
+ * 同一个 burst 里「输入 + Enter」确认的就是筛选前那一行。
28
+ */
29
+ const filterModelList = (list: ModelInfo[], query: string): ModelInfo[] => {
30
+ const q = query.trim().toLowerCase()
31
+ if (!q) return list
32
+ return list.filter((m) => m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q))
33
+ }
34
+
13
35
  interface PickerProps {
14
36
  config: MiphamConfig
15
37
  currentProvider: string
@@ -53,14 +75,22 @@ export function ModelPicker({
53
75
  const idx = models.findIndex((m) => m.id === currentModel)
54
76
  return idx >= 0 ? idx : 0
55
77
  })
78
+ // 搜索词同样走 `useKeyState`:同一个 burst 里「输入 d、e、e、Enter」时,
79
+ // Enter 那次回调读到的必须已经包含刚敲下的那几个字符。
80
+ const modelQuery = useKeyState('')
56
81
 
57
82
  const selectedProvider = providers[providerIdx.value]
58
83
  const models = selectedProvider ? activeModels(selectedProvider) : []
84
+ const searchEnabled = activePanel.value === 'model' && models.length > MODEL_SEARCH_THRESHOLD
85
+ const visibleModels = filterModelList(models, modelQuery.value)
59
86
 
60
87
  // Reset model index when provider changes
61
88
  const goToProvider = useCallback(
62
89
  (idx: number) => {
63
90
  providerIdx.set(wrap(idx, providers.length))
91
+ // 换 provider 后旧搜索词已无意义:留着会让新列表看起来少了模型,而搜索行
92
+ // 在 provider 面板上又看不见。
93
+ modelQuery.set('')
64
94
  // Land on the session's current model when this is its provider; any
65
95
  // other provider stays at row 0.
66
96
  const provider = providers[wrap(idx, providers.length)]
@@ -69,25 +99,26 @@ export function ModelPicker({
69
99
  modelIdx.set(current >= 0 ? current : 0)
70
100
  activePanel.set('model') // auto-switch to model panel
71
101
  },
72
- [providers, providerIdx, modelIdx, currentModel],
102
+ [providers, providerIdx, modelIdx, modelQuery, currentModel],
73
103
  )
74
104
 
75
105
  /** 相对移动 —— 按 `read()` 叠加,同一拍里的两次 ↓ 就是两步。 */
76
106
  const stepModel = useCallback(
77
107
  (delta: number) => {
78
108
  if (!selectedProvider) return
79
- const len = models.length
109
+ // 长度从 `read()` 重新算:同一 burst 里刚敲下的搜索词可能还没进渲染闭包。
110
+ const len = filterModelList(activeModels(selectedProvider), modelQuery.read()).length
80
111
  if (len === 0) return
81
112
  modelIdx.set((prev) => wrap(prev + delta, len))
82
113
  },
83
- [selectedProvider, models.length, modelIdx],
114
+ [selectedProvider, modelQuery, modelIdx],
84
115
  )
85
116
 
86
117
  const confirmSelection = useCallback(() => {
87
118
  // 按 `read()` 取当前光标,而不是渲染时那份闭包 —— 否则「↓ Enter」确认的是上一行。
88
119
  const provider = providers[providerIdx.read()]
89
120
  if (!provider) return
90
- const model = activeModels(provider)[modelIdx.read()]
121
+ const model = filterModelList(activeModels(provider), modelQuery.read())[modelIdx.read()]
91
122
  if (model) {
92
123
  // Check API key before confirming switch
93
124
  const apiKey = provider.apiKey
@@ -99,11 +130,20 @@ export function ModelPicker({
99
130
  }
100
131
  onSelect(provider.id, model.id)
101
132
  }
102
- }, [providers, providerIdx, modelIdx, onSelect, onNeedsApiKey])
133
+ }, [providers, providerIdx, modelIdx, modelQuery, onSelect, onNeedsApiKey])
103
134
 
104
135
  useInput((input, key) => {
136
+ const searching = activePanel.read() === 'model' && models.length > MODEL_SEARCH_THRESHOLD
137
+
105
138
  // Global keys
106
139
  if (key.escape) {
140
+ // Esc 先清搜索词、再关面板 —— 有词时直接关会让「打字打错了想退一步」变成
141
+ // 整个选择器消失。
142
+ if (searching && modelQuery.read() !== '') {
143
+ modelQuery.set('')
144
+ modelIdx.set(0)
145
+ return
146
+ }
107
147
  onClose()
108
148
  return
109
149
  }
@@ -117,18 +157,6 @@ export function ModelPicker({
117
157
  return
118
158
  }
119
159
 
120
- // Tab or right arrow → switch to model panel
121
- if (key.tab || key.rightArrow || (activePanel.read() === 'provider' && input === 'l')) {
122
- activePanel.set('model')
123
- return
124
- }
125
-
126
- // Left arrow → switch to provider panel
127
- if (key.leftArrow || (activePanel.read() === 'model' && input === 'h')) {
128
- activePanel.set('provider')
129
- return
130
- }
131
-
132
160
  // Up/Down navigation
133
161
  if (key.upArrow) {
134
162
  if (activePanel.read() === 'provider') {
@@ -147,6 +175,63 @@ export function ModelPicker({
147
175
  }
148
176
  return
149
177
  }
178
+
179
+ // Tab or right arrow → switch to model panel
180
+ if (key.tab || key.rightArrow) {
181
+ activePanel.set('model')
182
+ return
183
+ }
184
+
185
+ // Left arrow → switch to provider panel
186
+ if (key.leftArrow) {
187
+ modelQuery.set('')
188
+ activePanel.set('provider')
189
+ return
190
+ }
191
+
192
+ // 搜索输入只接管「既不是导航键、也不是控制键」的可打印字符。放在 `h`/`l`
193
+ // 导航之前:搜索框开着时敲 h 是在筛选,不是在切面板。
194
+ if (searching) {
195
+ if (key.backspace || key.delete) {
196
+ const q = modelQuery.read()
197
+ if (q !== '') {
198
+ modelQuery.set(q.slice(0, -1))
199
+ modelIdx.set(0)
200
+ }
201
+ return
202
+ }
203
+ if (input !== '' && !key.ctrl && !key.meta) {
204
+ // 粘贴/远端会把「文字 + Enter」作为一个 chunk 送到(Ink 对不以转义序列
205
+ // 开头的 chunk 不拆分,`key.return` 也不会置位)。只把字符写进搜索词、
206
+ // 丢掉尾部回车,等于「粘贴的确认永远不生效」。
207
+ const confirm = input.includes('\r') || input.includes('\n')
208
+ // chunk 里还可能夹着 DEL/BS(粘贴+退格+回车一次到达)。逐字符处理,
209
+ // 否则那个 DEL 会被当成普通字符写进搜索词。
210
+ let next = modelQuery.read()
211
+ for (const ch of input) {
212
+ if (ch === '\r' || ch === '\n') break
213
+ if (ch === '\x7f' || ch === '\b') next = next.slice(0, -1)
214
+ else next += ch
215
+ }
216
+ modelQuery.set(next)
217
+ modelIdx.set(0)
218
+ // `useKeyState.set` 同步更新镜像,所以紧接着的 `confirmSelection` 读到的
219
+ // 已经是处理完这个 chunk 的那份搜索词。
220
+ if (confirm) confirmSelection()
221
+ return
222
+ }
223
+ }
224
+
225
+ if (activePanel.read() === 'provider' && input === 'l') {
226
+ activePanel.set('model')
227
+ return
228
+ }
229
+
230
+ if (activePanel.read() === 'model' && input === 'h') {
231
+ modelQuery.set('')
232
+ activePanel.set('provider')
233
+ return
234
+ }
150
235
  })
151
236
 
152
237
  // Provider labels
@@ -208,9 +293,23 @@ export function ModelPicker({
208
293
  <Text bold underline dimColor>
209
294
  {t('ui.picker.models_label')} {activePanel.value === 'model' ? '◀' : ''}
210
295
  {selectedProvider ? ` — ${selectedProvider.name}` : ''}
296
+ {searchEnabled && modelQuery.value.trim() !== ''
297
+ ? ` (${visibleModels.length}/${models.length})`
298
+ : ''}
211
299
  </Text>
300
+ {searchEnabled && (
301
+ <Box>
302
+ <Text dimColor>⌕ </Text>
303
+ <Text>
304
+ {modelQuery.value !== '' ? modelQuery.value : t('ui.picker.search_placeholder')}
305
+ </Text>
306
+ </Box>
307
+ )}
212
308
  {models.length === 0 && <Text dimColor> {t('ui.picker.no_active_models')}</Text>}
213
- {models.map((m, i) => {
309
+ {models.length > 0 && visibleModels.length === 0 && (
310
+ <Text dimColor> {t('ui.picker.search_no_match')}</Text>
311
+ )}
312
+ {visibleModels.map((m, i) => {
214
313
  const isCurrentModel = selectedProvider?.id === currentProvider && m.id === currentModel
215
314
  const isSelected = i === modelIdx.value
216
315
  return (
@@ -239,7 +338,9 @@ export function ModelPicker({
239
338
  <Text dimColor>
240
339
  {activePanel.value === 'provider'
241
340
  ? t('ui.picker.select_provider_hint')
242
- : t('ui.picker.select_model_hint')}
341
+ : searchEnabled
342
+ ? t('ui.picker.search_hint')
343
+ : t('ui.picker.select_model_hint')}
243
344
  </Text>
244
345
  </Box>
245
346
  </Box>
@@ -42,6 +42,11 @@ export interface WorkflowAgentOpts {
42
42
  services?: SubAgentServices
43
43
  /** Run the agent in an isolated git worktree (optional). */
44
44
  isolation?: 'worktree'
45
+ /**
46
+ * Abort this call without touching its siblings (`stopAgent(id)` in the
47
+ * workflow sandbox aborts the controller behind this signal).
48
+ */
49
+ signal?: AbortSignal
45
50
  }
46
51
 
47
52
  /**
@@ -168,6 +173,7 @@ export async function workflowAgent(
168
173
  effort: opts.effort,
169
174
  allowedTools: undefined, // use all tools by default
170
175
  worktreePath,
176
+ signal: opts.signal,
171
177
  // The prompt is computed by the script, not typed by the user — say so,
172
178
  // so text the script relayed from a file or another agent cannot pass
173
179
  // as the user's own opening instruction.
@@ -107,6 +107,17 @@ export async function runWorkflow(
107
107
 
108
108
  const budget = createBudget(budgetTotal)
109
109
 
110
+ /**
111
+ * Running agent calls by id, so the script can stop **one** of them.
112
+ *
113
+ * A Set per id because labels are script-chosen and two live calls may share
114
+ * one (a fan-out with the same `label`); stopping an id stops all of them.
115
+ * The controller is registered synchronously inside `runAgent` — before its
116
+ * first `await` — so `const p = agent(...); stopAgent('x')` works even though
117
+ * the call has not yielded yet.
118
+ */
119
+ const runningAgents = new Map<string, Set<AbortController>>()
120
+
110
121
  // Wrap primitives with journal recording + cache support
111
122
  const runAgent = async (prompt: string, opts?: Record<string, unknown>) => {
112
123
  // Check cache first
@@ -123,10 +134,16 @@ export async function runWorkflow(
123
134
  const phase = (opts?.phase as string) || 'default'
124
135
  const startTime = Date.now()
125
136
 
137
+ const controller = new AbortController()
138
+ const controllers = runningAgents.get(agentId) ?? new Set<AbortController>()
139
+ controllers.add(controller)
140
+ runningAgents.set(agentId, controllers)
141
+
126
142
  bus.emitEvent({ type: 'agent:start', agentId, label: agentId, phase })
127
143
 
128
144
  let result: unknown
129
145
  try {
146
+ if (controller.signal.aborted) throw new DOMException('Aborted', 'AbortError')
130
147
  result = await workflowAgent(
131
148
  prompt,
132
149
  registry,
@@ -135,6 +152,7 @@ export async function runWorkflow(
135
152
  ...(opts || {}),
136
153
  permissionSystem: permission,
137
154
  services: engine.getSubAgentServices(),
155
+ signal: controller.signal,
138
156
  } as Record<string, unknown>,
139
157
  llm,
140
158
  )
@@ -161,6 +179,9 @@ export async function runWorkflow(
161
179
  // Still rethrow: a script that awaits this call must see the rejection, and
162
180
  // the catch below turns it into the run's own error message.
163
181
  throw err
182
+ } finally {
183
+ controllers.delete(controller)
184
+ if (controllers.size === 0) runningAgents.delete(agentId)
164
185
  }
165
186
 
166
187
  const durationMs = Date.now() - startTime
@@ -197,6 +218,29 @@ export async function runWorkflow(
197
218
  return pending
198
219
  }
199
220
 
221
+ /**
222
+ * Abort the agent(s) running under `id` (the `label` given to `agent()`), and
223
+ * leave every other call untouched. Returns how many live calls were stopped,
224
+ * so a script can tell "stopped it" from "it had already finished".
225
+ *
226
+ * The abort surfaces as a rejected `agent()` promise (`AbortError`) — a script
227
+ * that awaited it sees the rejection, and one that fire-and-forgot gets the
228
+ * run's journal/error handling for free. There is no path from here to "the
229
+ * whole workflow stops": that is the point of this being per-call.
230
+ */
231
+ const stopAgent = (id: string): number => {
232
+ const controllers = runningAgents.get(id)
233
+ if (!controllers) return 0
234
+ let stopped = 0
235
+ for (const controller of controllers) {
236
+ if (!controller.signal.aborted) {
237
+ controller.abort()
238
+ stopped++
239
+ }
240
+ }
241
+ return stopped
242
+ }
243
+
200
244
  const wrappedPhase = (title: string) => {
201
245
  phasePrimitive(title)
202
246
  bus.emitEvent({ type: 'phase:start', phase: title, timestamp: Date.now() })
@@ -222,6 +266,7 @@ export async function runWorkflow(
222
266
  // Inject primitives into the context (sealed so their constructor chain
223
267
  // can't reach host globals via `fn.constructor('return process')()`).
224
268
  sandboxCtx.agent = sealValue(agent)
269
+ sandboxCtx.stopAgent = sealValue(stopAgent)
225
270
  sandboxCtx.parallel = sealValue(parallel)
226
271
  sandboxCtx.pipeline = sealValue(pipeline)
227
272
  // verify()/judge() fan out their own agent calls, so they need the run's agent