@miphamai/cli 0.85.28 → 0.85.30

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.28
1
+ # Mipham Code v0.85.30
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 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.28",
3
+ "version": "0.85.30",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -44,23 +44,23 @@
44
44
  "mutate": "stryker run"
45
45
  },
46
46
  "dependencies": {
47
- "@larksuiteoapi/node-sdk": "^1.74.0",
47
+ "@larksuiteoapi/node-sdk": "^1.76.0",
48
48
  "commander": "^13.1.0",
49
49
  "ink": "^7.1.1",
50
50
  "ink-text-input": "^6.0.0",
51
- "react": "^19.3.0",
51
+ "react": "^19.3.1",
52
52
  "react-devtools-core": "^8.0.0",
53
53
  "yaml": "^2.9.1"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@mipham/shared": "workspace:*",
57
- "@stryker-mutator/core": "10.0.0",
57
+ "@stryker-mutator/core": "10.1.1",
58
58
  "@stryker-mutator/vitest-runner": "10.0.0",
59
- "@types/bun": "^1.4.2",
60
- "@types/node": "^22.20.4",
59
+ "@types/bun": "^1.4.4",
60
+ "@types/node": "^22.20.5",
61
61
  "@types/react": "^19.3.0",
62
- "@vitest/coverage-v8": "^5.0.2",
62
+ "@vitest/coverage-v8": "^5.0.5",
63
63
  "ink-testing-library": "^4.0.0",
64
- "vitest": "^5.0.2"
64
+ "vitest": "^5.0.5"
65
65
  }
66
66
  }
@@ -484,6 +484,7 @@ export class SubAgent {
484
484
  ruleEngine: this.ruleEngine,
485
485
  llm: this.llm,
486
486
  readFiles: new Set<string>(),
487
+ readFilesComplete: new Set<string>(),
487
488
  // Every tool call from here on is one level down, and a few tools must know
488
489
  // it: `Agent` cannot consume a background handle, so its default flips to
489
490
  // synchronous (see `resolveRunInBackground`). Set on the shared literal so it
@@ -38,7 +38,10 @@ export function AgentViewDashboard({ manager, onAttach, onExit }: DashboardProps
38
38
  // 时会**合并成一个**事件(实测 `'j\r'` → 单个 `input="j\r"`、`key.return` 为 false),
39
39
  // 两个分支都不匹配 ⇒ 症状是「这一拍什么也没发生」,不是「作用在上一行」。
40
40
  // 换句话说这一格没有可复现的故障,迁过去只会让测试**改前改后都绿**。
41
- const [selectedIndex, setSelectedIndex] = useState(0)
41
+ // 选中的是**会话 id**,不是一个位置。列表每次变化都按状态重新分组(一个 agent 跑完
42
+ // 就从 Working 挪到 Done),位置会在两次按键之间指向别的行 —— Enter / Ctrl+X 于是
43
+ // 作用在用户没看着的那个 agent 身上(314-050)。位置由 id 现算。
44
+ const [selectedId, setSelectedId] = useState<string | null>(null)
42
45
  const [peekingSessionId, setPeekingSessionId] = useState<string | null>(null)
43
46
  const [groupBy, setGroupBy] = useState<'status' | 'directory'>('status')
44
47
  const [feedback, setFeedback] = useState<string | null>(null)
@@ -122,6 +125,21 @@ export function AgentViewDashboard({ manager, onAttach, onExit }: DashboardProps
122
125
  [flatList],
123
126
  )
124
127
 
128
+ // 位置**现算**:选中 id 不在列表里(还没选 / 被移除了)时回落到第一行。
129
+ const selectedIndex = useMemo(() => {
130
+ const i = sessionsOnly.findIndex((s) => s.session.id === selectedId)
131
+ return i >= 0 ? i : 0
132
+ }, [sessionsOnly, selectedId])
133
+
134
+ /** 选中第 i 行 —— 记 id,不记位置。 */
135
+ const selectAt = useCallback(
136
+ (i: number) => {
137
+ const next = sessionsOnly[i]
138
+ if (next) setSelectedId(next.session.id)
139
+ },
140
+ [sessionsOnly],
141
+ )
142
+
125
143
  const handleAttach = useCallback(
126
144
  (sessionId: string) => {
127
145
  const session = manager.attach(sessionId)
@@ -225,9 +243,16 @@ export function AgentViewDashboard({ manager, onAttach, onExit }: DashboardProps
225
243
  // stops nothing, and the running sub-agent checks the registry's abort
226
244
  // signal. So: stop the task, then remove the row.
227
245
  const stopped = session.taskId ? getBackgroundAgentRegistry().stop(session.taskId) : false
246
+ // 光标交给**顶上来那一行**(没有就交给上一行),按 id 记 —— 位置在下一次
247
+ // 重新分组时会被别的 agent 占掉。
248
+ const removingIdx = selectedIndex
249
+ const nextId =
250
+ sessionsOnly[removingIdx + 1]?.session.id ??
251
+ sessionsOnly[removingIdx - 1]?.session.id ??
252
+ null
228
253
  manager.remove(session.id)
229
254
  setPeekingSessionId(null)
230
- setSelectedIndex((prev) => Math.max(0, Math.min(prev, sessionsOnly.length - 2)))
255
+ setSelectedId(nextId)
231
256
  showFeedback(
232
257
  stopped
233
258
  ? `Stopped + removed ${session.title || session.id}`
@@ -241,7 +266,7 @@ export function AgentViewDashboard({ manager, onAttach, onExit }: DashboardProps
241
266
  showFeedback('No sessions to navigate — spawn a background agent first')
242
267
  return
243
268
  }
244
- setSelectedIndex((prev) => Math.min(prev + 1, sessionsOnly.length - 1))
269
+ selectAt(Math.min(selectedIndex + 1, sessionsOnly.length - 1))
245
270
  setPeekingSessionId(null)
246
271
  return
247
272
  }
@@ -251,7 +276,7 @@ export function AgentViewDashboard({ manager, onAttach, onExit }: DashboardProps
251
276
  showFeedback('No sessions to navigate — spawn a background agent first')
252
277
  return
253
278
  }
254
- setSelectedIndex((prev) => Math.max(prev - 1, 0))
279
+ selectAt(Math.max(selectedIndex - 1, 0))
255
280
  setPeekingSessionId(null)
256
281
  return
257
282
  }
@@ -358,14 +383,12 @@ export function AgentViewDashboard({ manager, onAttach, onExit }: DashboardProps
358
383
  )
359
384
  }
360
385
 
361
- // Map this session's position in sessionsOnly to selectedIndex
362
- const sessionIdx = sessionsOnly.findIndex((s) => s.session.id === item.session.id)
363
-
364
386
  return (
365
387
  <SessionRow
366
388
  key={item.session.id}
367
389
  session={item.session}
368
- isSelected={sessionIdx === selectedIndex}
390
+ // 按 id 比对:下面这行按位置取到的就是当前选中的那一位
391
+ isSelected={item.session.id === sessionsOnly[selectedIndex]?.session.id}
369
392
  />
370
393
  )
371
394
  })}
@@ -92,6 +92,17 @@ const MAX_TOOL_TURNS = 100
92
92
  */
93
93
  const TURN_TIMEOUT_MS = 15 * 60 * 1000
94
94
 
95
+ /**
96
+ * How much of a hook's `additionalContext` may be injected into the prompt.
97
+ *
98
+ * A hook is a shell script this CLI did not write; it can print a whole file or
99
+ * an unbounded grep result. Compaction is the one moment the prompt is supposed
100
+ * to get *smaller* — letting a hook paste megabytes back in defeats it and can
101
+ * push the very next request past the model's window. Truncation is visible in
102
+ * the injected text so the model (and the user) can tell it happened.
103
+ */
104
+ const MAX_HOOK_CONTEXT_CHARS = 10_000
105
+
95
106
  /** The turn's stall clock: when it last moved, and whether it ran out. */
96
107
  interface TurnBudget {
97
108
  last: number
@@ -132,6 +143,8 @@ export class QueryEngine {
132
143
  private _selfCritique?: SelfCritique
133
144
  /** Files read this session — tracks what the Read tool has loaded */
134
145
  private readFiles = new Set<string>()
146
+ /** Subset of `readFiles` whose reads covered the whole file (no window) */
147
+ private readFilesComplete = new Set<string>()
135
148
  private goal?: string
136
149
  private maxGoalLoops = 20
137
150
  private lastAssistantContent?: string
@@ -256,6 +269,7 @@ export class QueryEngine {
256
269
  */
257
270
  resetFileTracking(): void {
258
271
  this.readFiles.clear()
272
+ this.readFilesComplete.clear()
259
273
  }
260
274
 
261
275
  /** Set the session identifier (called from index.tsx at startup with the actual session name). */
@@ -1404,7 +1418,7 @@ export class QueryEngine {
1404
1418
  const hint = isMcpTool
1405
1419
  ? `\nMCP tool "${name}" is no longer available. The MCP server may have been removed or disconnected. Use tool-search to discover available tools.`
1406
1420
  : `\nTool "${name}" is not registered. Available tools may have changed — check the tool list.`
1407
- return { success: false, content: '', error: `Unknown tool: ${name}${hint}` }
1421
+ return { success: false, content: '', error: `Unknown tool: ${name}${hint}`, notRun: true }
1408
1422
  }
1409
1423
 
1410
1424
  // Security: check permission before executing.
@@ -1428,10 +1442,11 @@ export class QueryEngine {
1428
1442
  success: false,
1429
1443
  content: '',
1430
1444
  error: baseError + moveOnHint,
1431
- // Held back, not judged: the auto-mode classifier had no usable answer.
1432
- // The display says "Not run" for these instead of showing a result line
1433
- // that reads as if the tool had run and returned that text (296-056).
1434
- notRun: decision.retryable === true,
1445
+ // It did not run. Whatever refused it — a deny rule, the mode, or the
1446
+ // auto-mode classifier with no usable answer — the text below is a
1447
+ // *reason*, not output, and a collapsed tool group otherwise renders it
1448
+ // as a result line (296-056, 314-031).
1449
+ notRun: true,
1435
1450
  }
1436
1451
  }
1437
1452
  // P1-4: Tool allowed — reset block counter
@@ -1447,6 +1462,7 @@ export class QueryEngine {
1447
1462
  success: false,
1448
1463
  content: '',
1449
1464
  error: preResult.reason || t('errors.tool_blocked', { name }),
1465
+ notRun: true,
1450
1466
  }
1451
1467
  }
1452
1468
 
@@ -1463,6 +1479,7 @@ export class QueryEngine {
1463
1479
  success: false,
1464
1480
  content: '',
1465
1481
  error: preResult.reason || t('errors.tool_hook_ask', { name }),
1482
+ notRun: true,
1466
1483
  }
1467
1484
  }
1468
1485
 
@@ -1597,7 +1614,7 @@ export class QueryEngine {
1597
1614
  success: false,
1598
1615
  content: '',
1599
1616
  error: this.buildDenialError(name, tool, effectiveParams, recheck),
1600
- notRun: recheck.retryable === true,
1617
+ notRun: true,
1601
1618
  }
1602
1619
  }
1603
1620
  }
@@ -1635,6 +1652,7 @@ export class QueryEngine {
1635
1652
  ruleEngine: this.ruleEngine,
1636
1653
  llm: this.llm,
1637
1654
  readFiles: this.readFiles,
1655
+ readFilesComplete: this.readFilesComplete,
1638
1656
  })
1639
1657
 
1640
1658
  // Track touched files for rules matching
@@ -2222,18 +2240,30 @@ export class QueryEngine {
2222
2240
  }
2223
2241
  }
2224
2242
 
2225
- switchProvider(providerId: string, modelId?: string): void {
2243
+ /**
2244
+ * Switch the active provider/model.
2245
+ *
2246
+ * Returns a warning when the model id is not in the registry: the context
2247
+ * window cannot be resized, so compaction keeps the *previous* model's limit.
2248
+ * Saying "✓ Switched" and nothing else made that silent — the user reads
2249
+ * success, then the next request is refused by a model whose window is
2250
+ * smaller than the size we are still willing to send.
2251
+ */
2252
+ switchProvider(providerId: string, modelId?: string): string | undefined {
2226
2253
  this.registry.switchProvider(providerId, modelId)
2227
2254
  // Update context manager's max tokens to match the new model's context window
2228
- if (modelId) {
2229
- const model = this.registry.findModel(modelId)
2230
- if (model) {
2231
- const DISABLE_1M = process.env.MIPHAM_DISABLE_1M_CONTEXT === '1'
2232
- const maxTokens =
2233
- DISABLE_1M && model.contextWindow > 200_000 ? 200_000 : model.contextWindow
2234
- this.context.updateMaxTokens(maxTokens, model.contextWindow)
2235
- }
2255
+ if (!modelId) return undefined
2256
+ const model = this.registry.findModel(modelId)
2257
+ if (!model) {
2258
+ return t('errors.model_window_unknown', {
2259
+ model: modelId,
2260
+ window: this.context.getMaxTokens().toLocaleString('en-US'),
2261
+ })
2236
2262
  }
2263
+ const DISABLE_1M = process.env.MIPHAM_DISABLE_1M_CONTEXT === '1'
2264
+ const maxTokens = DISABLE_1M && model.contextWindow > 200_000 ? 200_000 : model.contextWindow
2265
+ this.context.updateMaxTokens(maxTokens, model.contextWindow)
2266
+ return undefined
2237
2267
  }
2238
2268
 
2239
2269
  /**
@@ -2255,6 +2285,16 @@ export class QueryEngine {
2255
2285
  return n >= 1_000_000 ? `${Math.round(n / 100_000) / 10}M` : `${Math.round(n / 1000)}K`
2256
2286
  }
2257
2287
 
2288
+ /** Bound a hook's `additionalContext` — see `MAX_HOOK_CONTEXT_CHARS`. */
2289
+ private capHookContext(text: string): string {
2290
+ if (text.length <= MAX_HOOK_CONTEXT_CHARS) return text
2291
+ return (
2292
+ `${text.slice(0, MAX_HOOK_CONTEXT_CHARS)}\n` +
2293
+ `[…truncated: hook additionalContext was ${text.length.toLocaleString('en-US')} characters, ` +
2294
+ `only the first ${MAX_HOOK_CONTEXT_CHARS.toLocaleString('en-US')} were kept]`
2295
+ )
2296
+ }
2297
+
2258
2298
  /** Wrap context compaction with PreCompact/PostCompact hooks. */
2259
2299
  private async compactWithHooks(heading: string, signal?: AbortSignal): Promise<void> {
2260
2300
  if (this.hookEngine) {
@@ -2262,7 +2302,7 @@ export class QueryEngine {
2262
2302
  if (preResult.additionalContext) {
2263
2303
  this.context.injectContext(
2264
2304
  'pre-compact',
2265
- `[Pre-compact context]: ${preResult.additionalContext}`,
2305
+ `[Pre-compact context]: ${this.capHookContext(preResult.additionalContext)}`,
2266
2306
  )
2267
2307
  }
2268
2308
  }
@@ -2280,7 +2320,7 @@ export class QueryEngine {
2280
2320
  if (postResult.additionalContext) {
2281
2321
  this.context.injectContext(
2282
2322
  'post-compact',
2283
- `[Post-compact context]: ${postResult.additionalContext}`,
2323
+ `[Post-compact context]: ${this.capHookContext(postResult.additionalContext)}`,
2284
2324
  )
2285
2325
  }
2286
2326
  }
@@ -218,6 +218,24 @@ function failingLabel(command: string | undefined, source?: string): string {
218
218
  /** Grace given to a descendant still holding a stdio pipe after the hook itself exited. */
219
219
  const HOOK_PIPE_GRACE_MS = 1_000
220
220
 
221
+ /**
222
+ * Shortest timeout a hook may be given, in seconds.
223
+ *
224
+ * `"timeout": 0` is a plausible thing to write meaning "no limit" or "as long as
225
+ * it needs", but it arms the kill timer with a zero delay: the hook is torn down
226
+ * before the shell has even exec'd its command, and the operator is told
227
+ * `timed out after 0s` — a hook that never ran, reported as a slow one. One
228
+ * second is the smallest value that can still let a real command finish.
229
+ */
230
+ const MIN_HOOK_TIMEOUT_SECONDS = 1
231
+
232
+ /** Effective timeout in seconds — configured value floored, defaulting to 60. */
233
+ function hookTimeoutSeconds(cfg: HookConfig): number {
234
+ const configured = cfg.timeout
235
+ if (typeof configured !== 'number' || !Number.isFinite(configured)) return 60
236
+ return Math.max(MIN_HOOK_TIMEOUT_SECONDS, configured)
237
+ }
238
+
221
239
  /** The `spawnSync`-shaped outcome `spawnFailureCause` and the caller already read. */
222
240
  interface HookProcessResult {
223
241
  status: number | null
@@ -417,7 +435,7 @@ async function executeCommand(
417
435
  // `undefined` = inherit, which is what node does by default; passing it
418
436
  // explicitly keeps the two branches visible at one site.
419
437
  env,
420
- timeoutMs: (cfg.timeout ?? 60) * 1000,
438
+ timeoutMs: hookTimeoutSeconds(cfg) * 1000,
421
439
  })
422
440
 
423
441
  // Exit code 0 = success — parse the stdout JSON for structured decisions.
@@ -437,7 +455,7 @@ async function executeCommand(
437
455
  }
438
456
  }
439
457
 
440
- const failure = spawnFailureCause(result, cfg.timeout ?? 60)
458
+ const failure = spawnFailureCause(result, hookTimeoutSeconds(cfg))
441
459
  if (failure) {
442
460
  return failureResult(
443
461
  cfg,
@@ -957,6 +957,7 @@
957
957
  "model_error": "Error: {error}",
958
958
  "model_unavailable": "Model \"{model}\" (provider {provider}) is unavailable, and no default fallback model is configured — this turn produced no model output. Switch models with Ctrl+P, or check that provider's key and network, then retry. Underlying error: {error}",
959
959
  "tool_collision": "[mcp] Tool collision: \"{name}\" already registered. Skipping.",
960
+ "model_window_unknown": "⚠ Model \"{model}\" is not in the registry, so the context window could not be resized — compaction keeps using {window} tokens (the previous model's limit). If the new model is smaller, requests will start failing before compaction runs; switch to a known model or add this one to your provider config.",
960
961
  "missing_param": "Missing required parameter: \"{param}\"",
961
962
  "invalid_params": "Invalid parameters: {errors}",
962
963
  "unparseable_args": "The arguments for this tool call were not valid JSON ({detail}). Nothing was executed. Re-issue the call with complete JSON — do not infer the parameters from the fragment.",
@@ -957,6 +957,7 @@
957
957
  "model_error": "错误:{error}",
958
958
  "model_unavailable": "模型 \"{model}\"(提供商 {provider})当前不可用,且没有可回退的默认模型 —— 本轮没有拿到任何模型输出。用 Ctrl+P 换一个模型,或检查该提供商的密钥与网络后重试。底层错误:{error}",
959
959
  "tool_collision": "[mcp] 工具冲突:\"{name}\" 已注册,跳过。",
960
+ "model_window_unknown": "⚠ 模型 \"{model}\" 不在注册表中,上下文窗口无法重设 —— 压缩仍按 {window} tokens(上一个模型的限额)判断。新模型若更小,请求会在压缩触发前就开始失败;请切到已知模型,或把该模型加进提供商配置。",
960
961
  "missing_param": "缺少必需参数:\"{param}\"",
961
962
  "invalid_params": "参数无效:{errors}",
962
963
  "unparseable_args": "这次工具调用的参数不是合法 JSON({detail}),没有执行任何操作。请带着完整的 JSON 重新发起调用 —— 不要从这段残片里猜参数。",
@@ -11,6 +11,7 @@ import {
11
11
  streamIdleTimeoutMs,
12
12
  isRetryableFailure,
13
13
  createAwakeTimer,
14
+ readErrorBody,
14
15
  } from './fetch-utils'
15
16
 
16
17
  interface AnthropicContentBlock {
@@ -195,7 +196,7 @@ export class AnthropicProvider implements ProviderInstance {
195
196
  })
196
197
 
197
198
  if (!response.ok) {
198
- const errText = await response.text()
199
+ const errText = await readErrorBody(response)
199
200
  yield {
200
201
  type: 'error',
201
202
  error: `Anthropic API error ${response.status}: ${errText}`,
@@ -259,6 +259,37 @@ function sleep(ms: number): Promise<void> {
259
259
  return new Promise((resolve) => setTimeout(resolve, ms))
260
260
  }
261
261
 
262
+ /**
263
+ * Read a provider's error body, bounded in **both** size and time.
264
+ *
265
+ * `await response.text()` on an error path has neither. A gateway that accepts
266
+ * the connection and then streams forever (or a CDN's HTML error page for a
267
+ * multi-MB trace) parks the turn *before* the status code is ever shown — the
268
+ * one thing the caller needed. The body only exists to explain the status, so a
269
+ * truncated prefix is enough; past the deadline an empty string still leaves the
270
+ * status line to report.
271
+ */
272
+ export async function readErrorBody(
273
+ response: Response,
274
+ maxChars = 2_000,
275
+ timeoutMs = 5_000,
276
+ ): Promise<string> {
277
+ let timer: ReturnType<typeof setTimeout> | undefined
278
+ try {
279
+ // `.catch` first so a body that fails *after* the race is lost does not
280
+ // surface as an unhandled rejection.
281
+ const text = await Promise.race([
282
+ response.text().catch(() => ''),
283
+ new Promise<string>((resolve) => {
284
+ timer = setTimeout(() => resolve(''), timeoutMs)
285
+ }),
286
+ ])
287
+ return text.length > maxChars ? `${text.slice(0, maxChars)}… (truncated)` : text
288
+ } finally {
289
+ clearTimeout(timer)
290
+ }
291
+ }
292
+
262
293
  // ── Streaming idle-timeout (stall guard) with effort multiplier ──────────
263
294
  //
264
295
  // Reasoning models think silently for long stretches. The idle timeout between
@@ -6,6 +6,7 @@ import {
6
6
  streamIdleTimeoutMs,
7
7
  isRetryableFailure,
8
8
  createAwakeTimer,
9
+ readErrorBody,
9
10
  } from './fetch-utils'
10
11
  import { OLLAMA_PRESET_MODELS } from '../shared/constants'
11
12
 
@@ -55,7 +56,7 @@ export class OpenAICompatProvider implements ProviderInstance {
55
56
  })
56
57
 
57
58
  if (!response.ok) {
58
- const errText = await response.text()
59
+ const errText = await readErrorBody(response)
59
60
  yield {
60
61
  type: 'error',
61
62
  error: `OpenAI API error ${response.status}: ${errText}`,
@@ -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.28' as const
12
+ export const PACKAGE_VERSION = '0.85.30' 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 = 4593 as const
93
+ export const TEST_COUNT = 4620 as const
@@ -102,13 +102,14 @@ export interface ToolResult {
102
102
  content: string
103
103
  error?: string
104
104
  /**
105
- * The call was **held back, not judged** — `auto` mode asked the classifier and
106
- * got no usable answer, so nothing ran and asking again is appropriate (296-056).
105
+ * The call **never ran** — refused before execution by the permission gate, a
106
+ * PreToolUse hook, or `auto` mode's classifier, or the tool was not found.
107
107
  *
108
108
  * It is not a third failure state: `success` stays `false` and `error` still
109
109
  * carries the text the model reads. This bit exists only so the *display* can
110
- * tell "held back" from "ran and returned this", which are otherwise the same
111
- * shape (both are `success: false` + an error string).
110
+ * tell "did not run" from "ran and returned this", which are otherwise the same
111
+ * shape (both are `success: false` + an error string). A collapsed tool group
112
+ * that renders every failure as a result line reads as if the command ran.
112
113
  */
113
114
  notRun?: boolean
114
115
  }
@@ -145,9 +146,9 @@ export interface StreamChunk {
145
146
  */
146
147
  isError?: boolean
147
148
  /**
148
- * `type: 'tool_result'` only. The call never ran because `auto` mode's
149
- * classifier had no usable answer — held back, not judged (296-056). Distinct
150
- * from the `retryable` field below, which describes a *provider* error.
149
+ * `type: 'tool_result'` only. The call never ran — refused by the permission
150
+ * gate, a PreToolUse hook, or `auto` mode's classifier. Distinct from the
151
+ * `retryable` field below, which describes a *provider* error.
151
152
  */
152
153
  notRun?: boolean
153
154
  error?: string
@@ -639,6 +640,14 @@ export interface ToolContext {
639
640
  llm?: import('../providers/llm').Llm
640
641
  /** Files read this session — used by Write tool to check read-before-write */
641
642
  readFiles?: Set<string>
643
+ /**
644
+ * The subset of `readFiles` whose reads covered the **whole file** (no
645
+ * offset/limit, and not a credential-masked view). Write requires membership
646
+ * to overwrite an existing file: a partial read is context for Edit, not a
647
+ * licence to replace the file with the slice the model happened to see.
648
+ * Absent means "no completeness tracking" and is treated as not complete.
649
+ */
650
+ readFilesComplete?: Set<string>
642
651
  /**
643
652
  * Cancellation for the turn this tool call belongs to.
644
653
  *
@@ -614,10 +614,23 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
614
614
 
615
615
  try {
616
616
  // ── Credential masking: filter sensitive env vars ──
617
- let spawnEnv: Record<string, string | undefined> | undefined
617
+ let spawnEnv: Record<string, string | undefined> = {
618
+ ...(process.env as Record<string, string | undefined>),
619
+ }
620
+ // bash reads these *before* it runs the command, so an exported one
621
+ // silently reconfigures every command we start:
622
+ // SHELLOPTS — `set -o` options. Exported `errexit` stops a whole
623
+ // script at its first failing statement (`a; false; b` printed only
624
+ // `a`, exit 1), which reads as "the command did less than asked".
625
+ // BASHOPTS — the `shopt` equivalents (`nullglob`, `globstar`, …).
626
+ // BASH_ENV — a file non-interactive bash sources first: arbitrary
627
+ // code from the parent process ahead of the user's command.
628
+ // The parent's shell is not the model's shell; the tool's contract is
629
+ // that the command runs as written.
630
+ for (const key of ['SHELLOPTS', 'BASHOPTS', 'BASH_ENV']) delete spawnEnv[key]
618
631
  if (credentialConfig?.enabled && credentialConfig.env_filter.enabled) {
619
632
  const { filterEnv } = await import('../../core/credential-masker')
620
- spawnEnv = filterEnv(process.env as Record<string, string | undefined>, credentialConfig)
633
+ spawnEnv = filterEnv(spawnEnv, credentialConfig)
621
634
  }
622
635
 
623
636
  const proc = Bun.spawn(['bash', '-c', command], {
@@ -631,6 +644,9 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
631
644
  // the wrong group and fails (or, worse, hits the parent's).
632
645
  detached: true,
633
646
  })
647
+ // Tracked until it exits: `detached` also means the group is not taken
648
+ // down when this process goes away (see `liveProcessGroups`).
649
+ trackProcessGroup(proc.pid)
634
650
 
635
651
  // Start reading at once — a child that fills the pipe buffer blocks on
636
652
  // write and would then never exit — but do **not** await here: if a
@@ -663,6 +679,7 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
663
679
  }
664
680
 
665
681
  const exitCode = await proc.exited
682
+ liveProcessGroups.delete(proc.pid)
666
683
  clearTimeout(timer)
667
684
  ctx.signal?.removeEventListener('abort', onAbort)
668
685
 
@@ -766,6 +783,41 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
766
783
  /** Grace given to a descendant still holding the output pipe after the shell itself has exited. */
767
784
  const PIPE_GRACE_MS = 1_000
768
785
 
786
+ /**
787
+ * Process groups this tool spawned that have not exited yet.
788
+ *
789
+ * `detached: true` is what makes the group kill work — and it is also what lets
790
+ * the command outlive the CLI: the group is no longer in our process group, so
791
+ * nothing is delivered to it when the parent goes away. A long `build` or
792
+ * `npm test` started a second before Ctrl+C keeps writing to the user's disk
793
+ * with no CLI attached, and the next run finds a locked directory it cannot
794
+ * explain. Killing these on `exit` is the only cleanup that can still run there
795
+ * (the handler must be synchronous, and `killProcessGroup` is).
796
+ */
797
+ const liveProcessGroups = new Set<number>()
798
+
799
+ /** Kill every still-running group. Registered once against `process.on('exit')`. */
800
+ export function killLiveProcessGroups(): void {
801
+ for (const pid of liveProcessGroups) killProcessGroup(pid)
802
+ liveProcessGroups.clear()
803
+ }
804
+
805
+ /** How many groups are currently tracked (test observability). */
806
+ export function liveProcessGroupCount(): number {
807
+ return liveProcessGroups.size
808
+ }
809
+
810
+ let exitHookInstalled = false
811
+
812
+ /** Start tracking a freshly spawned group; installs the exit handler on first use. */
813
+ function trackProcessGroup(pid: number | undefined): void {
814
+ if (pid === undefined || pid <= 0) return
815
+ liveProcessGroups.add(pid)
816
+ if (exitHookInstalled) return
817
+ exitHookInstalled = true
818
+ process.on('exit', killLiveProcessGroups)
819
+ }
820
+
769
821
  /**
770
822
  * Kill a whole process group. `proc.kill()` reaches only the direct child, so a
771
823
  * `bash -c` that spawned its own children leaves them orphaned and unnotified.
@@ -11,6 +11,19 @@ import { maskSearchOutput } from '../../core/credential-masker'
11
11
  * not hang the session for minutes. Matches the Bash tool's 120s ceiling. */
12
12
  const GREP_TIMEOUT_MS = 120_000
13
13
 
14
+ /** How long `runSearch` waits after SIGTERM before escalating to SIGKILL. */
15
+ const KILL_GRACE_MS = 2_000
16
+
17
+ /**
18
+ * How long the pipes may stay open after the escalate-to-SIGKILL deadline before
19
+ * the search is abandoned outright.
20
+ *
21
+ * SIGKILL ends the child, but a *grandchild* that inherited the write end keeps
22
+ * EOF from ever arriving, and `new Response(pipe).text()` has no timeout of its
23
+ * own. Without this bound the tool's own "timed out" report would itself hang.
24
+ */
25
+ const PIPE_DRAIN_GRACE_MS = 2_000
26
+
14
27
  /** Run a search command with a kill-timer; report whether the timeout fired. */
15
28
  export async function runSearch(
16
29
  cmd: string[],
@@ -19,20 +32,41 @@ export async function runSearch(
19
32
  ): Promise<{ stdout: string; stderr: string; timedOut: boolean; exitCode: number | null }> {
20
33
  const proc = Bun.spawn(cmd, { cwd, stdout: 'pipe', stderr: 'pipe' })
21
34
  let timedOut = false
22
- const timer = setTimeout(() => {
23
- timedOut = true
24
- proc.kill()
25
- }, timeoutMs)
35
+ const timers: ReturnType<typeof setTimeout>[] = []
36
+ timers.push(
37
+ setTimeout(() => {
38
+ timedOut = true
39
+ // SIGTERM first: rg releases its walker and flushes what it has. A process
40
+ // that ignores it (or is stuck in uninterruptible I/O) would otherwise keep
41
+ // the pipes open forever — the timeout would never reach the caller.
42
+ proc.kill()
43
+ timers.push(setTimeout(() => proc.kill(9), KILL_GRACE_MS))
44
+ }, timeoutMs),
45
+ )
26
46
  // 两条管道必须**并发**读。先读满 stdout 再读 stderr 会在子进程写满
27
47
  // stderr(~64 KB 管道缓冲)时死锁:它阻塞在 write 上不退出,stdout 也就
28
48
  // 永远读不到 EOF —— 只能等超时兜底,而超时会把「慢」和「错」说成同一件事。
29
- const [stdout, stderr] = await Promise.all([
30
- new Response(proc.stdout).text(),
31
- new Response(proc.stderr).text(),
32
- ])
33
- await proc.exited
34
- clearTimeout(timer)
35
- return { stdout, stderr, timedOut, exitCode: proc.exitCode }
49
+ const finished = (async () => {
50
+ const [stdout, stderr] = await Promise.all([
51
+ new Response(proc.stdout).text(),
52
+ new Response(proc.stderr).text(),
53
+ ])
54
+ await proc.exited
55
+ return { stdout, stderr, exitCode: proc.exitCode }
56
+ })()
57
+
58
+ const abandoned = new Promise<null>((resolve) => {
59
+ timers.push(setTimeout(() => resolve(null), timeoutMs + KILL_GRACE_MS + PIPE_DRAIN_GRACE_MS))
60
+ })
61
+
62
+ const result = await Promise.race([finished, abandoned])
63
+ for (const t of timers) clearTimeout(t)
64
+ if (result === null) {
65
+ // Nothing readable came back and the process would not die. Report it as the
66
+ // timeout it is instead of waiting on fds nobody owns anymore.
67
+ return { stdout: '', stderr: '', timedOut: true, exitCode: null }
68
+ }
69
+ return { ...result, timedOut }
36
70
  }
37
71
 
38
72
  /** grep 输出上限:超过则显式截断并附标记(不能静默丢内容——模型会误以为看全了)。 */
@@ -73,14 +73,20 @@ function windowFromString(content: string, offset: number, limit: number): strin
73
73
  * and the decoded range starts and ends on a newline — so neither pass can split
74
74
  * a character. Returns null when the window cannot be located within
75
75
  * `MAX_SCAN_BYTES`.
76
+ *
77
+ * `complete` answers a different question from the one the window answers: did
78
+ * this read cover the **whole file**? A 2,000-line window of a 50,000-line file
79
+ * is a correct answer to "show me the start" and a dangerous basis for
80
+ * "overwrite it" — the model would rewrite what it never saw. The Write tool
81
+ * reads this flag (see `ToolContext.readFilesComplete`).
76
82
  */
77
83
  function windowFromFd(
78
84
  fd: number,
79
85
  offset: number,
80
86
  limit: number,
81
87
  maxScanBytes: number = MAX_SCAN_BYTES,
82
- ): string[] | null {
83
- if (limit <= 0) return []
88
+ ): { lines: string[]; complete: boolean } | null {
89
+ if (limit <= 0) return { lines: [], complete: false }
84
90
 
85
91
  const buf = Buffer.allocUnsafe(CHUNK_BYTES)
86
92
  let scanned = 0 // bytes consumed by the scan
@@ -113,13 +119,28 @@ function windowFromFd(
113
119
  scanned += n
114
120
  }
115
121
 
122
+ // `complete` = this window is the whole file: it starts at line 0 and nothing
123
+ // follows its last line. The window ended on a terminating newline, which is
124
+ // also what a file whose final byte is that newline looks like — one probe
125
+ // byte past it tells the two apart. A read error here means "unknown", and
126
+ // unknown must not grant overwrite permission.
127
+ let complete: boolean
116
128
  if (windowEnd === -1) {
117
129
  // Either the file ended (the window is everything that is left) or the scan
118
130
  // budget ran out before the window's last line was reached.
119
131
  if (!eof) return null
120
132
  windowEnd = scanned
133
+ complete = offset <= 0
134
+ } else {
135
+ let hasMore = true
136
+ try {
137
+ hasMore = readSync(fd, Buffer.allocUnsafe(1), 0, 1, windowEnd + 1) > 0
138
+ } catch {
139
+ hasMore = true
140
+ }
141
+ complete = offset <= 0 && !hasMore
121
142
  }
122
- if (windowStart === -1) return [] // `offset` is past the end of the file
143
+ if (windowStart === -1) return { lines: [], complete: false } // `offset` is past the end of the file
123
144
 
124
145
  const out = Buffer.allocUnsafe(windowEnd - windowStart)
125
146
  let got = 0
@@ -128,7 +149,7 @@ function windowFromFd(
128
149
  if (n <= 0) break
129
150
  got += n
130
151
  }
131
- return out.toString('utf-8', 0, got).split('\n')
152
+ return { lines: out.toString('utf-8', 0, got).split('\n'), complete }
132
153
  }
133
154
 
134
155
  export function createReadTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
@@ -199,6 +220,11 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
199
220
  // *first* is what used to make `offset`/`limit` useless on large files —
200
221
  // the size check ran before the window was ever applied.
201
222
  let result: string | null = null
223
+ // Did this read see the whole file? Only then may the Write tool replace
224
+ // the file outright; a window is an excerpt, not a basis for overwriting.
225
+ // Credential-masked content is never "whole": what was returned to the
226
+ // model is a sentinel or a redaction of the real bytes.
227
+ let complete = false
202
228
  if (credentialConfig) {
203
229
  const { matchCredentialFile, maskContent, CREDENTIAL_SENTINEL } =
204
230
  await import('../../core/credential-masker')
@@ -216,8 +242,8 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
216
242
  if (result === null) {
217
243
  const allowLarge = params.allow_large === true
218
244
  const scanBudget = allowLarge ? MAX_SCAN_BYTES_LARGE : MAX_SCAN_BYTES
219
- const lines = windowFromFd(fd, offset, limit, scanBudget)
220
- if (lines === null) {
245
+ const window = windowFromFd(fd, offset, limit, scanBudget)
246
+ if (window === null) {
221
247
  return {
222
248
  success: false,
223
249
  content: '',
@@ -228,7 +254,8 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
228
254
  `, or use a shell tool to slice the file.`,
229
255
  }
230
256
  }
231
- result = formatLines(lines, offset)
257
+ result = formatLines(window.lines, offset)
258
+ complete = window.complete
232
259
  }
233
260
 
234
261
  // ── Binary sniff ──
@@ -254,6 +281,7 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
254
281
 
255
282
  // ── Read tracking: mark file as read for Write tool safety ──
256
283
  ctx.readFiles?.add(filePath)
284
+ if (complete) ctx.readFilesComplete?.add(filePath)
257
285
  return { success: true, content: result }
258
286
  } finally {
259
287
  closeSync(fd)
@@ -42,6 +42,25 @@ export const writeTool: ToolDefinition = {
42
42
  }
43
43
  }
44
44
 
45
+ // ── Whole-file check: a window is not the file ──
46
+ // `offset`/`limit` exist so a huge file can be inspected a slice at a time.
47
+ // Treating that slice as "the file has been read" lets the next Write erase
48
+ // every line outside it without a trace — the model rewrites a file it only
49
+ // half-saw. Only a read that covered the whole file grants overwrite;
50
+ // anything less must go through Edit, which is anchored on content the model
51
+ // actually has.
52
+ const completelyRead = ctx.readFilesComplete?.has(filePath) ?? false
53
+ if (fileExists && wasRead && !completelyRead) {
54
+ return {
55
+ success: false,
56
+ content: '',
57
+ error:
58
+ `File "${filePath}" was only partially read (an offset/limit window). ` +
59
+ 'Overwriting it would discard the rest of the file. Use Edit for targeted ' +
60
+ 'changes, or Read the whole file first (no offset/limit).',
61
+ }
62
+ }
63
+
45
64
  // ── Non-UTF-8 guard: refuse to clobber a file we cannot represent ──
46
65
  // A Windows-1252 / Shift-JIS / GBK file read into the model came back as
47
66
  // U+FFFD garbage; writing UTF-8 content over it would erase the originals
@@ -83,8 +102,10 @@ export const writeTool: ToolDefinition = {
83
102
  throw err
84
103
  }
85
104
 
86
- // Track as read since we just wrote it (future writes allowed)
105
+ // Track as read since we just wrote it (future writes allowed). The model
106
+ // authored every byte of the new content, so this is a whole-file read too.
87
107
  ctx.readFiles?.add(filePath)
108
+ ctx.readFilesComplete?.add(filePath)
88
109
 
89
110
  const lines = content.split('\n').length
90
111
  const action = fileExists ? 'Updated' : 'Wrote'
@@ -202,6 +202,41 @@ function withOffsetNotice(
202
202
  return header + window + notice
203
203
  }
204
204
 
205
+ /**
206
+ * Flatten an error and its `cause` chain into one line.
207
+ *
208
+ * Bun/undici wrap the actual failure in `cause`; the top-level message is often
209
+ * only "Unable to connect", which says nothing about *why*.
210
+ */
211
+ function errorChain(err: unknown, depth = 0): string {
212
+ if (!(err instanceof Error)) return String(err)
213
+ const head = `${err.name}: ${err.message}`
214
+ const cause = (err as { cause?: unknown }).cause
215
+ if (!cause || depth >= 3) return head
216
+ return `${head} ← ${errorChain(cause, depth + 1)}`
217
+ }
218
+
219
+ /**
220
+ * Turn a thrown fetch error into a diagnosis the reader can act on.
221
+ *
222
+ * A TLS failure (expired, self-signed, wrong host, or a proxy intercepting the
223
+ * connection) otherwise reads exactly like "the site is down" — and the model
224
+ * responds by trying mirrors that are just as unreachable. Naming the class is
225
+ * the difference between fixing the cause and guessing.
226
+ */
227
+ export function describeFetchFailure(err: unknown): string {
228
+ const text = errorChain(err)
229
+ if (/certificate|CERT_|ERR_TLS|\bSSL\b|\bTLS\b|self[- ]signed|unable to verify/i.test(text)) {
230
+ return (
231
+ `TLS/certificate failure: ${text}. The server's certificate could not be verified ` +
232
+ '(expired, self-signed, wrong host, or replaced by a proxy on the network path). ' +
233
+ 'Retrying a mirror will not help and certificate verification must not be disabled — ' +
234
+ 'the user needs to trust the proxy CA or use a reachable source.'
235
+ )
236
+ }
237
+ return `Fetch failed: ${text}. If direct network is blocked, retry via the web-access skill (CDP through the user's logged-in Chrome).`
238
+ }
239
+
205
240
  // ── Tool Definition ──
206
241
 
207
242
  export const webFetchTool: ToolDefinition = {
@@ -348,7 +383,7 @@ export const webFetchTool: ToolDefinition = {
348
383
  const message =
349
384
  err instanceof Error && err.name === 'AbortError'
350
385
  ? 'Request timed out (30s)'
351
- : `Fetch failed: ${String(err)}. If direct network is blocked, retry via the web-access skill (CDP through the user's logged-in Chrome).`
386
+ : describeFetchFailure(err)
352
387
  return { success: false, content: '', error: message }
353
388
  } finally {
354
389
  clearTimeout(timer)
package/src/ui/app.tsx CHANGED
@@ -1024,6 +1024,11 @@ export function App({
1024
1024
  async (input: string) => {
1025
1025
  if (!input.trim()) return
1026
1026
 
1027
+ // 用户真正敲的那串。转发型斜杠命令会把 `input` 换成给模型的指令正文
1028
+ // (`input = forwardToAI`),而会话名取自**用户**的话 —— 否则第一条命令就能
1029
+ // 把会话命名成一段内部指令(314-025)。
1030
+ const typedInput = input
1031
+
1027
1032
  // ── @mention: direct cross-session message — only when the name resolves
1028
1033
  // to a live session; otherwise fall through to normal AI processing so a
1029
1034
  // leading `@word` (e.g. "@bob please review") isn't hijacked as a send. ──
@@ -1219,7 +1224,7 @@ export function App({
1219
1224
  ) {
1220
1225
  const currentName = discoverSessions().find((s) => s.id === sessionId)?.name
1221
1226
  if (isDefaultSessionName(currentName, process.cwd())) {
1222
- const title = deriveSessionTitle(input)
1227
+ const title = deriveSessionTitle(typedInput)
1223
1228
  if (title && sessionId) renameActiveSession(sessionId, title)
1224
1229
  }
1225
1230
  }
@@ -1299,6 +1304,10 @@ export function App({
1299
1304
  }
1300
1305
  // Escape: close apiKeyPrompt → close picker → abort loading (does NOT exit app)
1301
1306
  if (key.escape) {
1307
+ // 面板开着时 Esc 归面板(关看板 / 从会话视图退回)。Ink 把同一个按键派发给
1308
+ // **所有**挂载的 `useInput`,所以这里若再跑一遍 `dismissTopmost()`,关面板的
1309
+ // 那一下会顺带 abort 正在跑的主回合 —— 用户想关的是面板,不是停掉对话(314-056)。
1310
+ if (agentViewOpen || attachedSessionId) return
1302
1311
  if (dismissTopmost()) return
1303
1312
  // Otherwise let InputBar handle Escape (clear draft)
1304
1313
  return
@@ -660,9 +660,11 @@ const switchCmd: CommandHandler = (ctx, args) => {
660
660
  }
661
661
  }
662
662
 
663
- ctx.engine.switchProvider(newProvider, newModel)
663
+ const warning = ctx.engine.switchProvider(newProvider, newModel)
664
664
  return {
665
- content: t('commands.switch.confirmed', { provider: newProvider, model: newModel }),
665
+ content:
666
+ t('commands.switch.confirmed', { provider: newProvider, model: newModel }) +
667
+ (warning ? `\n${warning}` : ''),
666
668
  nextProvider: newProvider,
667
669
  nextModel: newModel,
668
670
  }