@miphamai/cli 0.85.29 → 0.85.31

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.29
1
+ # Mipham Code v0.85.31
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.29",
3
+ "version": "0.85.31",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -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
  })}
@@ -46,6 +46,12 @@ function safeParseYaml(path: string, label: string): Partial<MiphamConfig> | nul
46
46
  )
47
47
  return null
48
48
  }
49
+ // An empty document (0 bytes, or whitespace) parses to `null` — the same
50
+ // value a broken file yields. Reading it as corruption sent the loader down
51
+ // the backup-restore path and warned on every start, even though "empty" is
52
+ // exactly what `: > config.yml` leaves behind. Absent and empty mean the
53
+ // same thing here: nothing to apply, nothing to recover (318-044).
54
+ if (raw.trim() === '') return {}
49
55
  return parseYaml(raw) as Partial<MiphamConfig>
50
56
  } catch (err: unknown) {
51
57
  const msg = err instanceof Error ? err.message : String(err)
@@ -1418,7 +1418,7 @@ export class QueryEngine {
1418
1418
  const hint = isMcpTool
1419
1419
  ? `\nMCP tool "${name}" is no longer available. The MCP server may have been removed or disconnected. Use tool-search to discover available tools.`
1420
1420
  : `\nTool "${name}" is not registered. Available tools may have changed — check the tool list.`
1421
- return { success: false, content: '', error: `Unknown tool: ${name}${hint}` }
1421
+ return { success: false, content: '', error: `Unknown tool: ${name}${hint}`, notRun: true }
1422
1422
  }
1423
1423
 
1424
1424
  // Security: check permission before executing.
@@ -1442,10 +1442,11 @@ export class QueryEngine {
1442
1442
  success: false,
1443
1443
  content: '',
1444
1444
  error: baseError + moveOnHint,
1445
- // Held back, not judged: the auto-mode classifier had no usable answer.
1446
- // The display says "Not run" for these instead of showing a result line
1447
- // that reads as if the tool had run and returned that text (296-056).
1448
- 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,
1449
1450
  }
1450
1451
  }
1451
1452
  // P1-4: Tool allowed — reset block counter
@@ -1461,6 +1462,7 @@ export class QueryEngine {
1461
1462
  success: false,
1462
1463
  content: '',
1463
1464
  error: preResult.reason || t('errors.tool_blocked', { name }),
1465
+ notRun: true,
1464
1466
  }
1465
1467
  }
1466
1468
 
@@ -1477,6 +1479,7 @@ export class QueryEngine {
1477
1479
  success: false,
1478
1480
  content: '',
1479
1481
  error: preResult.reason || t('errors.tool_hook_ask', { name }),
1482
+ notRun: true,
1480
1483
  }
1481
1484
  }
1482
1485
 
@@ -1611,7 +1614,7 @@ export class QueryEngine {
1611
1614
  success: false,
1612
1615
  content: '',
1613
1616
  error: this.buildDenialError(name, tool, effectiveParams, recheck),
1614
- notRun: recheck.retryable === true,
1617
+ notRun: true,
1615
1618
  }
1616
1619
  }
1617
1620
  }
@@ -2439,7 +2442,7 @@ function toolResultText(content: ContentBlock[]): string {
2439
2442
  */
2440
2443
  export function isContextOverflowError(message: string | null | undefined): boolean {
2441
2444
  if (!message) return false
2442
- return /context[_ ]length|context window|prompt is too long|too many tokens|maximum context length|exceeds? the (?:model'?s )?(?:maximum )?context|usage credits required for 1m context/i.test(
2445
+ return /context[_ ]length|context window|prompt is too long|input is too long|too many tokens|maximum context length|exceeds? the (?:model'?s )?(?:maximum )?context|usage credits required for 1m context/i.test(
2443
2446
  message,
2444
2447
  )
2445
2448
  }
@@ -128,7 +128,9 @@ export function parseHookStdout(stdout: string | null | undefined, _ctx: HookCon
128
128
  }
129
129
  }
130
130
  if (decision === 'ask') {
131
- return { allowed: true, permissionDecision: 'ask', additionalContext }
131
+ // The engine stops the call on `ask` and prints `reason`, so the hook's
132
+ // `permissionDecisionReason` is the only place its explanation can land.
133
+ return { allowed: true, permissionDecision: 'ask', reason, additionalContext }
132
134
  }
133
135
  if (decision === 'defer') {
134
136
  return { allowed: true, permissionDecision: 'defer', additionalContext }
package/src/core/hooks.ts CHANGED
@@ -31,7 +31,7 @@ const COOLDOWN_MS = 5 * 60 * 1000
31
31
 
32
32
  /**
33
33
  * Merge two permission decisions, keeping the more restrictive one.
34
- * Priority: deny > defer > ask > allow
34
+ * Priority: deny > ask > defer > allow
35
35
  */
36
36
  /**
37
37
  * Does a failure to run this hook block the call?
@@ -48,7 +48,10 @@ export function mergePermissionDecision(
48
48
  current: HookResult['permissionDecision'],
49
49
  incoming: NonNullable<HookResult['permissionDecision']>,
50
50
  ): HookResult['permissionDecision'] {
51
- const priority: Record<string, number> = { deny: 3, defer: 2, ask: 1, allow: 0 }
51
+ // deny > ask > defer > allow. `ask` must outrank `defer`: the engine treats
52
+ // `defer` as "no override" (it runs the normal permission flow), so letting
53
+ // defer win would discard a sibling hook's explicit ask and let the call run.
54
+ const priority: Record<string, number> = { deny: 3, ask: 2, defer: 1, allow: 0 }
52
55
  const currScore = current ? (priority[current] ?? 0) : -1
53
56
  const incScore = priority[incoming] ?? 0
54
57
  return incScore > currScore ? incoming : current
@@ -416,12 +419,19 @@ export class HookEngine {
416
419
  return { ...hookResult }
417
420
  }
418
421
 
419
- // Merge permission decisions (deny > defer > ask > allow)
422
+ // Merge permission decisions (deny > ask > defer > allow). The reason
423
+ // travels with the decision that wins: the engine prints it when `ask`
424
+ // stops the call, and dropping it here meant the user got the generic
425
+ // "hook asked" text no matter what the hook explained.
420
426
  if (hookResult.permissionDecision) {
421
- result.permissionDecision = mergePermissionDecision(
427
+ const merged = mergePermissionDecision(
422
428
  result.permissionDecision,
423
429
  hookResult.permissionDecision,
424
430
  )
431
+ if (merged !== result.permissionDecision && hookResult.reason) {
432
+ result.reason = hookResult.reason
433
+ }
434
+ result.permissionDecision = merged
425
435
  }
426
436
 
427
437
  // Stop hook: block decision takes precedence
@@ -1,6 +1,6 @@
1
1
  import { homedir } from 'node:os'
2
2
  import { isAbsolute, join, normalize } from 'node:path'
3
- import { realpathSync } from 'node:fs'
3
+ import { realpathSync, statSync } from 'node:fs'
4
4
  import type { PermissionRuleEntry } from '../shared/index.ts'
5
5
  import { expandHome, matchPath } from './credential-masker/matcher'
6
6
 
@@ -392,6 +392,22 @@ function uniq(items: string[]): string[] {
392
392
  return [...new Set(items)]
393
393
  }
394
394
 
395
+ /**
396
+ * Remove quotes that wrap a single, metacharacter-free token.
397
+ *
398
+ * `rm "-rf" /tmp` and `git "push" origin` run the same commands as their
399
+ * unquoted spellings; the quotes only reached the matcher. Tokens that contain
400
+ * whitespace or shell syntax are left alone — de-quoting those would rewrite
401
+ * token boundaries and could turn one segment into a different command.
402
+ */
403
+ function dequoteSimpleTokens(segment: string): string {
404
+ // The three quote characters are written as \x27 / \x22 / \x60 on purpose:
405
+ // the tool-reference integrity guard's literal lexer has no regex-literal
406
+ // support, and a raw one here opens a string it never closes — the rest of
407
+ // the file is then scanned as one literal (this file was the first to trip it).
408
+ return segment.replace(/([\x27\x22])([^\x27\x22\x60;&|<>()\s]*?)\1/g, '$2')
409
+ }
410
+
395
411
  /** File paths a Bash command reads or writes. */
396
412
  export interface BashFileAccess {
397
413
  read: string[]
@@ -432,26 +448,15 @@ export function extractBashFileAccess(command: string): BashFileAccess {
432
448
  const read: string[] = []
433
449
  const write: string[] = []
434
450
 
435
- // 1. Redirect targets. Handles `> file`, `>file`, and the same operators
436
- // right after a substitution/subshell (`(echo x)>file`, `x=$(date)>file`).
437
- // Requiring a separator before the operator (the old shape) missed every
438
- // no-space form, so `Edit(path)`/`Write(path)` deny rules were bypassable
439
- // with `echo hi>path`. Heredocs (`<<`) and fd-dup targets (`2>&1`) are
440
- // skipped — their "target" is a delimiter or file descriptor, not a path.
441
- const redirectRe = /([0-9]*&?)?(>>|<<|<|>)\s*([^\s;|&<>]+)/g
442
- let m: RegExpExecArray | null
443
- while ((m = redirectRe.exec(command)) !== null) {
444
- const op = m[2]!
445
- if (op === '<<') continue // heredoc delimiter
446
- // Process substitution `<(...)` / `>(...)` is not a redirect to a file.
447
- if (m[3]!.startsWith('(')) continue
448
- const target = stripQuotes(m[3]!)
449
- if (op === '<') read.push(target)
450
- else write.push(target)
451
- }
452
-
453
- // 2. Reader/writer command arguments (non-flag args are candidate paths),
454
- // recursing into `$(...)` / backtick substitutions.
451
+ // Redirect targets and reader/writer arguments are collected in **one** pass,
452
+ // because both have to resolve relative paths against the folder the shell is
453
+ // in at that point in the command line. Splitting them into two passes is how
454
+ // `cd /etc && cat passwd` and `cd /etc && echo x > passwd` would disagree
455
+ // about where `passwd` is (321-005). Redirect notes from the dedicated pass
456
+ // still apply: `> file`, `>file`, and the same operators right after a
457
+ // substitution/subshell (`(echo x)>file`, `x=$(date)>file`) all count;
458
+ // heredocs (`<<`) and fd-dup targets (`2>&1`) are skipped — their "target" is
459
+ // a delimiter or file descriptor, not a path.
455
460
  scanReaderWriterCommands(command, read, write)
456
461
 
457
462
  // 展开放在出口这一处,而不是每个 push 点 —— 重定向与读/写命令、以及它们的
@@ -478,6 +483,25 @@ function extractSubstitutions(command: string): string[] {
478
483
  return inners
479
484
  }
480
485
 
486
+ /**
487
+ * Index just past one `VAR=value` assignment in an `env` token list, following
488
+ * shell quoting so a value containing spaces is consumed whole.
489
+ */
490
+ function skipEnvAssignment(tokens: string[], start: number): number {
491
+ let quote: string | null = null
492
+ for (let i = start; i < tokens.length; i++) {
493
+ for (const ch of tokens[i]!) {
494
+ if (quote) {
495
+ if (ch === quote) quote = null
496
+ } else if (ch === '"' || ch === "'") {
497
+ quote = ch
498
+ }
499
+ }
500
+ if (quote === null) return i + 1
501
+ }
502
+ return tokens.length
503
+ }
504
+
481
505
  /**
482
506
  * Flatten a command into every matchable sub-command: its shell segments plus
483
507
  * the commands nested inside `$(...)`/backtick substitutions and shell `-c`
@@ -490,6 +514,11 @@ export function flattenCommand(command: string, depth = 0): string[] {
490
514
  const out: string[] = []
491
515
  for (const seg of splitShellSegments(command)) {
492
516
  out.push(seg)
517
+ // The shell removes quotes before running the command, so `rm "-rf" /tmp`
518
+ // *is* `rm -rf /tmp` — but the rule text is written without quotes, so the
519
+ // quoted spelling used to slip past `Bash(rm -rf *)`.
520
+ const unquoted = dequoteSimpleTokens(seg)
521
+ if (unquoted !== seg) out.push(unquoted)
493
522
  const stripped = stripPrefixCommand(seg)
494
523
  if (stripped !== seg) out.push(stripped)
495
524
  // 剥掉前导噪声后的形态也要参与匹配:`IFS=x rm -rf x` / `( rm -rf x )` /
@@ -501,12 +530,19 @@ export function flattenCommand(command: string, depth = 0): string[] {
501
530
  for (const inner of extractSubstitutions(seg)) {
502
531
  out.push(...flattenCommand(inner, depth + 1))
503
532
  }
533
+ // Wrapper prefixes (`env`, `sudo`, `timeout`, …) are not the command being
534
+ // run. Without their removal `env X="a b" rm -rf /` matched no `rm …`
535
+ // rule at all, because the matcher never saw past the assignment.
536
+ const { base, args, payload } = effectiveCommand(seg.split(/\s+/).filter(Boolean))
537
+ if (base) {
538
+ const unwrapped = [base, ...args].join(' ')
539
+ if (unwrapped !== seg) out.push(unwrapped)
540
+ }
504
541
  // A shell `-c` payload is a command line in its own right, so `Bash(rm *)`
505
542
  // must also match `bash -c 'rm -rf /'`. Past the depth bound recursion stops
506
543
  // outright rather than pushing the raw payload: the raw text
507
544
  // (`bash -c 'rm -rf /'`) matches no `rm …` pattern anyway, and stopping
508
545
  // keeps the boundary predictable.
509
- const { payload } = effectiveCommand(seg.split(/\s+/).filter(Boolean))
510
546
  if (payload && depth < MAX_COMMAND_DEPTH) out.push(...flattenCommand(payload, depth + 1))
511
547
  }
512
548
  return out
@@ -538,7 +574,11 @@ function effectiveCommand(tokens: string[]): {
538
574
  if (PREFIX_VALUE_OPTIONS.has(opt) && i < tokens.length) i++ // skip the flag's value
539
575
  }
540
576
  if (name === 'env') {
541
- while (i < tokens.length && tokens[i]!.includes('=')) i++ // `VAR=value` assignments
577
+ // `VAR=value` assignments. A quoted value spans several whitespace-split
578
+ // tokens (`X="a b"` → `X="a` + `b"`), so skipping one token per `=` left
579
+ // the base command as `b"` and every gate reading this normalized form
580
+ // missed the real command afterwards (319-080).
581
+ while (i < tokens.length && tokens[i]!.includes('=')) i = skipEnvAssignment(tokens, i)
542
582
  }
543
583
  // `timeout` 的位置参数是 duration,**不是**必然存在:`timeout 5 cmd` 有,
544
584
  // `timeout --preserve-status cmd` 没有。无条件 `i++` 会把后者真正的命令
@@ -616,18 +656,83 @@ function stripPrefixCommand(command: string): string {
616
656
  return [base, ...args].join(' ')
617
657
  }
618
658
 
659
+ /**
660
+ * Whether a writer command's destination names a directory — in which case the
661
+ * file actually written is `dest/basename(src)`, not the directory itself.
662
+ */
663
+ function isDirectoryTarget(path: string): boolean {
664
+ // A trailing slash (or `.`/`..`) is taken at its word: `cp` treats it as a
665
+ // directory even when nothing is there yet. Otherwise ask the disk.
666
+ if (path.endsWith('/') || path === '.' || path === '..') return true
667
+ try {
668
+ return statSync(expandHome(path)).isDirectory()
669
+ } catch {
670
+ return false
671
+ }
672
+ }
673
+
674
+ /**
675
+ * The folder a `cd` segment moves the shell into, or `undefined` when the
676
+ * segment is not a `cd`. `null` means the destination cannot be known
677
+ * (`cd -`), and later relative paths stay as written.
678
+ */
679
+ function cdDestination(segment: string): string | null | undefined {
680
+ const tokens = stripLeadingShellNoise(segment).split(/\s+/).filter(Boolean)
681
+ if (tokens.length === 0) return undefined
682
+ const { base, args } = effectiveCommand(tokens)
683
+ if (base !== 'cd') return undefined
684
+ const target = args[0]
685
+ if (target === '-') return null
686
+ if (!target || target === '~' || target.startsWith('~/')) return expandHome(target ?? '~')
687
+ return stripQuotes(target)
688
+ }
689
+
619
690
  /**
620
691
  * Detect reader/writer commands at the front of each shell segment and recurse
621
692
  * into command substitutions and shell `-c` payloads, so both
622
693
  * `echo $(cat .git-credentials)` and `bash -c 'cat .git-credentials'` are caught.
694
+ *
695
+ * `cwd` is the folder a relative path in this segment resolves against: the
696
+ * shell evaluates a command line left to right, so a `cd` in an earlier segment
697
+ * moves everything after it. Without that, `cd /etc && cat passwd` looked like a
698
+ * read of `./passwd`, and a `Read(/etc/passwd)` deny rule never saw it
699
+ * (321-005). A `cd` inside a substitution or `-c` payload is scoped to that
700
+ * recursion — the shell runs it in a subshell / child process — which is why
701
+ * the tracker is passed down by value.
623
702
  */
624
703
  function scanReaderWriterCommands(
625
704
  command: string,
626
705
  read: string[],
627
706
  write: string[],
628
707
  depth = 0,
708
+ cwd: string | null = null,
629
709
  ): void {
710
+ const resolve = (p: string): string =>
711
+ cwd && !isAbsolute(p) && !p.startsWith('~') ? join(cwd, p) : p
712
+
630
713
  for (const seg of splitShellSegments(command)) {
714
+ const dest = cdDestination(seg)
715
+ if (dest !== undefined) {
716
+ cwd = dest === null ? null : isAbsolute(dest) ? dest : cwd ? join(cwd, dest) : dest
717
+ continue
718
+ }
719
+ // Redirect targets. Handles `> file`, `>file`, and the same operators right
720
+ // after a substitution/subshell (`(echo x)>file`, `x=$(date)>file`).
721
+ // Requiring a separator before the operator (the old shape) missed every
722
+ // no-space form, so `Edit(path)`/`Write(path)` deny rules were bypassable
723
+ // with `echo hi>path`. Heredocs (`<<`) and fd-dup targets (`2>&1`) are
724
+ // skipped — their "target" is a delimiter or file descriptor, not a path.
725
+ const redirectRe = /([0-9]*&?)?(>>|<<|<|>)\s*([^\s;|&<>]+)/g
726
+ let m: RegExpExecArray | null
727
+ while ((m = redirectRe.exec(seg)) !== null) {
728
+ const op = m[2]!
729
+ if (op === '<<') continue // heredoc delimiter
730
+ // Process substitution `<(...)` / `>(...)` is not a redirect to a file.
731
+ if (m[3]!.startsWith('(')) continue
732
+ const target = resolve(stripQuotes(m[3]!))
733
+ if (op === '<') read.push(target)
734
+ else write.push(target)
735
+ }
631
736
  // 先剥前导噪声再 tokenize:`IFS=x cat secret` / `! cat secret` /
632
737
  // `time -p cat secret` 读的是同一个文件,Read() 规则必须看得见 `cat`。
633
738
  // 与 flattenCommand 共用 stripLeadingShellNoise —— 两条路径一份归一化。
@@ -650,37 +755,58 @@ function scanReaderWriterCommands(
650
755
  // — the value is already a separate, non-`-` token handled below.)
651
756
  const eq = arg.indexOf('=')
652
757
  if (eq === -1) continue
653
- const v = stripQuotes(arg.slice(eq + 1))
654
- if (v === '' || v.startsWith('-')) continue
758
+ const raw = stripQuotes(arg.slice(eq + 1))
759
+ if (raw === '' || raw.startsWith('-')) continue
760
+ const v = resolve(raw)
655
761
  read.push(v)
656
762
  if (inPlace) write.push(v)
657
763
  continue
658
764
  }
659
- const p = stripQuotes(arg)
765
+ const p = resolve(stripQuotes(arg))
660
766
  read.push(p)
661
767
  if (inPlace) write.push(p)
662
768
  }
663
769
  } else if (WRITER_COMMANDS.has(base)) {
770
+ const paths: string[] = []
664
771
  for (const arg of args) {
665
772
  if (arg.startsWith('-')) {
666
773
  const eq = arg.indexOf('=')
667
774
  if (eq === -1) continue
668
- const v = stripQuotes(arg.slice(eq + 1))
669
- if (v === '' || v.startsWith('-')) continue
670
- write.push(v)
775
+ const raw = stripQuotes(arg.slice(eq + 1))
776
+ if (raw === '' || raw.startsWith('-')) continue
777
+ paths.push(resolve(raw))
671
778
  continue
672
779
  }
673
- write.push(stripQuotes(arg))
780
+ paths.push(resolve(stripQuotes(arg)))
781
+ }
782
+ write.push(...paths)
783
+ // `cp x /etc/` writes `/etc/x`, not `/etc/` — recording only the
784
+ // directory let a `Write(/etc/*)` deny rule (and the protected-file
785
+ // prompt) miss the file that was actually created. The destination is
786
+ // the `-t` option value when given, otherwise the last positional path
787
+ // (321-006).
788
+ if (base === 'cp' || base === 'mv') {
789
+ const tIdx = args.findIndex((a) => a === '-t' || a === '--target-directory')
790
+ const tRaw = tIdx !== -1 ? stripQuotes(args[tIdx + 1] ?? '') : ''
791
+ const dest =
792
+ tIdx !== -1 ? (tRaw === '' ? undefined : resolve(tRaw)) : paths[paths.length - 1]
793
+ if (dest && isDirectoryTarget(dest)) {
794
+ for (const src of paths) {
795
+ if (src === dest) continue
796
+ const name = src.replace(/\/+$/, '').split('/').pop()
797
+ if (name && name !== '.' && name !== '..') write.push(join(dest, name))
798
+ }
799
+ }
674
800
  }
675
801
  }
676
802
  // Re-parse a shell `-c` payload: `bash -c 'cat secret'` reads `secret`
677
803
  // just as directly as `cat secret` does.
678
804
  if (payload && depth < MAX_COMMAND_DEPTH) {
679
- scanReaderWriterCommands(payload, read, write, depth + 1)
805
+ scanReaderWriterCommands(payload, read, write, depth + 1, cwd)
680
806
  }
681
807
  }
682
808
  for (const inner of extractSubstitutions(seg)) {
683
- scanReaderWriterCommands(inner, read, write, depth + 1)
809
+ scanReaderWriterCommands(inner, read, write, depth + 1, cwd)
684
810
  }
685
811
  }
686
812
  }
@@ -53,44 +53,52 @@ function isVerificationCommand(input: Record<string, unknown>): boolean {
53
53
  // not `cat secret` — auto-approving it would read files a `Read(...)` rule
54
54
  // means to protect.
55
55
  if (/[;&|><`$*?\[\]]/.test(cmd)) return false
56
- // Patterns for verification-only commands (no side effects on codebase)
56
+ // `timeout 30 cat f` runs `cat f`; a plain duration wrapper is not part of
57
+ // the command. Without this the whitelist read the wrapper as the command
58
+ // name and every wrapped read-only call fell through to `ask` — which in
59
+ // this CLI means refused, not prompted (319-056). Flags are not stripped:
60
+ // only the plain `timeout DURATION` spelling the entry names.
61
+ const trimmed = cmd.trim()
62
+ const unwrapped = trimmed.replace(/^timeout\s+\d+(?:\.\d+)?[smhd]?\s+/, '')
63
+ const target = unwrapped !== trimmed ? unwrapped : trimmed
64
+ // Patterns for verification-only commands (no side effects on codebase).
65
+ //
66
+ // Every pattern is anchored at the start. An unanchored `\bcat\b` matches
67
+ // wherever the word appears — `sed -i 's/cat/dog/' f` and `rm -rf cat.txt`
68
+ // both contain it, so acceptEdits auto-approved *writes* on the strength of a
69
+ // filename. The whitelist is a statement about the command being run, so it
70
+ // has to read the command's first word, not any word in its arguments.
57
71
  const verifyPatterns = [
58
- /\bpnpm\s+test\b/, // test runner
59
- /\bpnpm\s+t\b/, // shorthand test
60
- /\bpnpm\s+typecheck\b/, // type checking
61
- /\bpnpm\s+lint\b/, // linting
62
- /\bpnpm\s+format:check\b/, // format check
63
- /\bnpm\s+test\b/, // npm test
64
- /\bnpm\s+run\s+test\b/, // npm run test
65
- /\bvitest\b/, // vitest runner
66
- /\bjest\b/, // jest runner
67
- /\btsc\s+(?!init)/, // TypeScript compiler (not tsc init)
68
- /\btsc\s+--noEmit\b/, // type check only
69
- /\beslint\b/, // eslint
70
- /\bprettier\s+--check\b/, // prettier check
71
- /\bpytest\b/, // python test runner
72
- /\bruff\s+check\b/, // python linter
73
- /\bcargo\s+test\b/, // rust test
74
- /\bcargo\s+check\b/, // rust check
75
- /\bgo\s+test\b/, // go test
76
- /\bgo\s+vet\b/, // go vet
77
- /\bmake\s+test\b/, // make test
78
- /\bgit\s+status\b/, // git status (read-only)
79
- /\bgit\s+diff\b/, // git diff (read-only)
80
- /\bgit\s+log\b/, // git log (read-only)
81
- /\bgit\s+branch\b/, // git branch (read-only)
82
- /\bls\b/, // list files
83
- /\bcat\b/, // read file
84
- /\bhead\b/, // read file start
85
- /\btail\b/, // read file end
86
- /\bwhich\b/, // find binary
87
- /\becho\b/, // print text
88
- /\bnode\s+-v\b/, // node version
89
- /\bpython\s+--version\b/, // python version
90
- /\bwhoami\b/, // current user
91
- /\bpwd\b/, // current directory
72
+ /^pnpm\s+(?:test|t|typecheck|lint|format:check)\b/, // test/lint/typecheck
73
+ /^npm\s+(?:test|run\s+test)\b/, // npm test
74
+ /^vitest\b/, // vitest runner
75
+ /^jest\b/, // jest runner
76
+ /^tsc\s+(?!init)/, // TypeScript compiler (not tsc init)
77
+ /^eslint\b/, // eslint
78
+ /^prettier\s+--check\b/, // prettier check
79
+ /^pytest\b/, // python test runner
80
+ /^ruff\s+check\b/, // python linter
81
+ /^cargo\s+(?:test|check)\b/, // rust test/check
82
+ /^go\s+(?:test|vet)\b/, // go test/vet
83
+ /^make\s+test\b/, // make test
84
+ /^git\s+status\b/, // git status (read-only)
85
+ /^git\s+diff\b/, // git diff (read-only)
86
+ /^git\s+log\b/, // git log (read-only)
87
+ // `git branch -d/-D/-m/-f` deletes or rewrites branches; only the listing
88
+ // spellings are read-only. `git branch` with no flag lists.
89
+ /^git\s+branch(?:\s+(?:--list|-a|-r|-v|--verbose|--show-current))*\s*$/,
90
+ /^ls\b/, // list files
91
+ /^cat\b/, // read file
92
+ /^head\b/, // read file start
93
+ /^tail\b/, // read file end
94
+ /^which\b/, // find binary
95
+ /^echo\b/, // print text
96
+ /^node\s+-v\b/, // node version
97
+ /^python\s+--version\b/, // python version
98
+ /^whoami\b/, // current user
99
+ /^pwd\b/, // current directory
92
100
  ]
93
- return verifyPatterns.some((p) => p.test(cmd))
101
+ return verifyPatterns.some((p) => p.test(target))
94
102
  }
95
103
 
96
104
  /**
@@ -87,8 +87,15 @@ export class WorkspaceTrust {
87
87
  }
88
88
  }
89
89
 
90
- /** Persist the trust store to disk. */
91
- private save(): void {
90
+ /**
91
+ * Persist the trust store to disk.
92
+ *
93
+ * Returns whether the write happened. The caller prints "✓ Workspace
94
+ * trusted", so a swallowed failure here made the UI claim a fact the disk
95
+ * never received — on a read-only or full shared home the next run asked
96
+ * again with no explanation (318-009).
97
+ */
98
+ private save(): boolean {
92
99
  try {
93
100
  if (!existsSync(MIPHAM_HOME)) {
94
101
  mkdirSync(MIPHAM_HOME, { recursive: true })
@@ -102,8 +109,10 @@ export class WorkspaceTrust {
102
109
  atomicWriteFileSync(TRUST_STORE_PATH, JSON.stringify(this.store, null, 2) + '\n', {
103
110
  mode: 0o600,
104
111
  })
112
+ return true
105
113
  } catch {
106
- // Best-effort: don't crash if we can't save
114
+ // Don't crash if we can't save — but do report it.
115
+ return false
107
116
  }
108
117
  }
109
118
 
@@ -129,18 +138,23 @@ export class WorkspaceTrust {
129
138
  return false
130
139
  }
131
140
 
132
- /** Add a directory to the trust store. */
133
- trust(dir: string): void {
141
+ /**
142
+ * Add a directory to the trust store.
143
+ *
144
+ * Returns false only when the new entry could not be written to disk; a
145
+ * directory that is already trusted is `true` — it was persisted earlier.
146
+ */
147
+ trust(dir: string): boolean {
134
148
  const resolved = realPath(dir)
135
149
  // Don't add duplicates
136
- if (this.store.directories.includes(resolved)) return
150
+ if (this.store.directories.includes(resolved)) return true
137
151
  // Don't add subdirectories of already-trusted paths
138
- if (this.isTrusted(resolved)) return
152
+ if (this.isTrusted(resolved)) return true
139
153
 
140
154
  this.store.directories.push(resolved)
141
155
  // Sort for readability
142
156
  this.store.directories.sort()
143
- this.save()
157
+ return this.save()
144
158
  }
145
159
 
146
160
  /** Remove a directory from the trust store (and any subdirectories). */
@@ -91,7 +91,8 @@
91
91
  },
92
92
  "rename": {
93
93
  "usage": "Usage: /rename <session-name>\nExample: /rename Bug Fix Session",
94
- "confirmed": "✓ Session renamed to \"{name}\""
94
+ "confirmed": "✓ Session renamed to \"{name}\"",
95
+ "unsaved": "⚠ Session title set to \"{name}\" for this run, but it could not be saved to the session registry — the name may not last."
95
96
  },
96
97
  "plan": {
97
98
  "entered": "Entered plan mode.",
@@ -205,6 +206,7 @@
205
206
  "delete_usage": "Usage: /resume delete <session-name>\n\nDelete a saved session. Use /resume to list all sessions.",
206
207
  "delete_confirmed": "✓ Session \"{name}\" deleted.",
207
208
  "delete_not_found": "✗ Session \"{name}\" not found. Use /resume to list all sessions.",
209
+ "delete_current": "✗ Session \"{name}\" is the one you are in — it would be written again when this session exits, so deleting it here would not stick. Exit first, then delete it.",
208
210
  "empty_footer": "Sessions are auto-saved to ~/.mipham/sessions/ when Mipham Code exits.\nStart a conversation — it will be saved automatically.",
209
211
  "total_footer": "Total: {count} session(s) • Location: ~/.mipham/sessions/",
210
212
  "resume_hint": "Session details: /resume <name>",
@@ -91,7 +91,8 @@
91
91
  },
92
92
  "rename": {
93
93
  "usage": "用法: /rename <session-name>\n示例: /rename 修复 Bug 的会话",
94
- "confirmed": "✓ 会话重命名为 \"{name}\""
94
+ "confirmed": "✓ 会话重命名为 \"{name}\"",
95
+ "unsaved": "⚠ 本次会话已改名为 \"{name}\",但没能写入会话登记表 —— 这个名字可能不会保留。"
95
96
  },
96
97
  "plan": {
97
98
  "entered": "已进入计划模式。",
@@ -205,6 +206,7 @@
205
206
  "delete_usage": "用法: /resume delete <session-name>\n\n删除已保存的会话。使用 /resume 列出所有会话。",
206
207
  "delete_confirmed": "✓ 会话 \"{name}\" 已删除。",
207
208
  "delete_not_found": "✗ 未找到会话 \"{name}\"。使用 /resume 列出所有会话。",
209
+ "delete_current": "✗ \"{name}\" 是你当前所在的会话 —— 退出时它会被重新写回,所以在这里删掉不会生效。请先退出,再删除。",
208
210
  "empty_footer": "会话在 Mipham Code 退出时自动保存到 ~/.mipham/sessions/。\n开始对话 — 它将自动保存。",
209
211
  "total_footer": "总计: {count} 个会话 • 位置: ~/.mipham/sessions/",
210
212
  "resume_hint": "查看会话详情: /resume <name>",
package/src/index.tsx CHANGED
@@ -151,8 +151,17 @@ async function checkWorkspaceTrust(): Promise<void> {
151
151
  try {
152
152
  const answer = await question('Trust this workspace? [Y/N]: ')
153
153
  if (answer === 'y' || answer === 'yes') {
154
- trust.trust(cwd)
155
- process.stderr.write(`✓ Workspace trusted: ${cwd}\n\n`)
154
+ if (trust.trust(cwd)) {
155
+ process.stderr.write(`✓ Workspace trusted: ${cwd}\n\n`)
156
+ } else {
157
+ // The in-memory list now covers this run, but the write failed — so the
158
+ // next run will ask again. Saying "trusted" alone would be a claim the
159
+ // disk never received (318-009).
160
+ process.stderr.write(
161
+ `⚠ Workspace trusted for this run only: ${cwd}\n` +
162
+ ` The trust store could not be written, so this directory will not be remembered.\n\n`,
163
+ )
164
+ }
156
165
  } else {
157
166
  process.stderr.write('✗ Workspace not trusted. Exiting.\n')
158
167
  rl.close()
package/src/mcp/client.ts CHANGED
@@ -458,7 +458,6 @@ export class McpClient {
458
458
  }
459
459
  const initResult: InitializeResult = await protocol.initialize()
460
460
 
461
- connection.status = 'connected'
462
461
  connection.serverInfo = initResult.serverInfo
463
462
  connection.instructions = initResult.instructions
464
463
 
@@ -471,6 +470,13 @@ export class McpClient {
471
470
  if (initResult.capabilities.tools) {
472
471
  connection.tools = await protocol.listTools()
473
472
  }
473
+
474
+ // `connected` is a claim about the server *and* its tool list. Setting
475
+ // it right after the handshake made `connect()` (and `reconnect()`)
476
+ // early-return while `tools/list` was still in flight, so a concurrent
477
+ // caller registered zero tools and nothing re-emitted when the list
478
+ // landed. The `connecting` promise covers this window instead.
479
+ connection.status = 'connected'
474
480
  })
475
481
  } catch (err) {
476
482
  connection.status = 'error'
package/src/mcp/oauth.ts CHANGED
@@ -127,15 +127,23 @@ export class OAuthClient {
127
127
  /* fire-and-forget */
128
128
  })
129
129
  })
130
- setTimeout(() => {
131
- server.close()
132
- reject(new Error(t('errors.oauth_timeout')))
133
- }, 300_000)
130
+ // Only one timeout exists, and it is the `timer` above so the callback can
131
+ // clear it. A second, uncancelled 5-minute timer used to be armed here: it
132
+ // kept the event loop alive long after a successful flow and fired
133
+ // `reject` on an already-settled promise.
134
134
  })
135
135
 
136
136
  const tokenResponse = await fetch(auth.tokenUrl, {
137
137
  method: 'POST',
138
138
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
139
+ // A redirect here is not a hop to retry on — it re-POSTs the
140
+ // authorization code and PKCE verifier to whatever host the redirect
141
+ // names. Refuse it instead of following.
142
+ redirect: 'error',
143
+ // The callback has already returned, so a server that accepts the
144
+ // connection and then says nothing would leave this promise (and the
145
+ // interactive flow) pending forever.
146
+ signal: AbortSignal.timeout(60_000),
139
147
  body: new URLSearchParams({
140
148
  grant_type: 'authorization_code',
141
149
  code,
@@ -221,6 +229,9 @@ export class OAuthClient {
221
229
  {
222
230
  method: 'POST',
223
231
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
232
+ // Same rule as the code exchange: a 307/308 would carry the refresh
233
+ // token to the redirect target. Fail closed rather than leak it.
234
+ redirect: 'error',
224
235
  body: new URLSearchParams({
225
236
  grant_type: 'refresh_token',
226
237
  refresh_token: saved.refreshToken,
@@ -105,7 +105,7 @@ const SENSITIVE_ENV_PATTERNS = [
105
105
  * Build a sanitised environment for MCP subprocesses.
106
106
  * Strips sensitive vars; allows explicit overrides via `extra`.
107
107
  */
108
- function buildProcEnv(extra?: Record<string, string>): Record<string, string> {
108
+ export function buildProcEnv(extra?: Record<string, string>): Record<string, string> {
109
109
  const sanitized: Record<string, string> = {}
110
110
 
111
111
  for (const [key, value] of Object.entries(process.env as Record<string, string>)) {
@@ -114,9 +114,17 @@ function buildProcEnv(extra?: Record<string, string>): Record<string, string> {
114
114
  sanitized[key] = value
115
115
  }
116
116
 
117
- // Explicit overrides take precedence (for intentionally shared secrets)
117
+ // Explicit overrides take precedence (for intentionally shared secrets).
118
+ //
119
+ // An empty override means "not set", not "set to empty": passing
120
+ // `AWS_BEARER_TOKEN_BEDROCK=""` makes the SDK skip the machine's own
121
+ // credential chain and fail auth, while an unset variable lets it fall back.
122
+ // `Object.assign` used to copy the empty string verbatim.
118
123
  if (extra) {
119
- Object.assign(sanitized, extra)
124
+ for (const [key, value] of Object.entries(extra)) {
125
+ if (value === '') delete sanitized[key]
126
+ else sanitized[key] = value
127
+ }
120
128
  }
121
129
 
122
130
  return sanitized
@@ -113,6 +113,15 @@ export const DEFAULT_PROVIDERS: ProviderConfig[] = [
113
113
  vision: true,
114
114
  status: 'active',
115
115
  },
116
+ {
117
+ id: 'claude-fable-5-2',
118
+ name: 'Claude Fable 5.2',
119
+ providerId: 'anthropic',
120
+ contextWindow: 1_000_000,
121
+ maxOutput: 128_000,
122
+ vision: true,
123
+ status: 'active',
124
+ },
116
125
  ],
117
126
  },
118
127
  {
@@ -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.29' as const
12
+ export const PACKAGE_VERSION = '0.85.31' 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 = 4612 as const
93
+ export const TEST_COUNT = 4658 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
@@ -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], {
@@ -89,6 +89,19 @@ export const editTool: ToolDefinition = {
89
89
  error: `String too large. Max: 5 MB per string.`,
90
90
  }
91
91
  }
92
+ // An empty `old_string` finds a match at every position. With replace_all it
93
+ // spliced the new text in at every character boundary and reported success —
94
+ // a corrupted file that looked like a completed edit. There is no
95
+ // replacement an empty needle expresses: creation is Write, insertion is
96
+ // anchored on surrounding text.
97
+ if (oldStr.length === 0) {
98
+ return {
99
+ success: false,
100
+ content: '',
101
+ error:
102
+ 'old_string must not be empty. Use Write to create a file, or include the surrounding text to insert at a specific place.',
103
+ }
104
+ }
92
105
 
93
106
  // O_NOFOLLOW: fail closed on a symlink swapped in after resolveSafe (TOCTOU).
94
107
  let rfd: number
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
@@ -2394,7 +2394,14 @@ const renameCmd: CommandHandler = (ctx, args) => {
2394
2394
  // Persist to the cross-session registry so `@name` can address this session.
2395
2395
  // Returns the (possibly uniquified) final name — surface that to the user.
2396
2396
  const finalName = renameActiveSession(ctx.sessionId, name.trim())
2397
- return { content: t('commands.rename.confirmed', { name: finalName ?? name.trim() }) }
2397
+ // The in-memory title changed either way, so this run shows the new name.
2398
+ // But when the registry write did not happen, the name will not survive the
2399
+ // session — reporting plain success left the user believing it would
2400
+ // (319-089).
2401
+ if (finalName === null) {
2402
+ return { content: t('commands.rename.unsaved', { name: name.trim() }) }
2403
+ }
2404
+ return { content: t('commands.rename.confirmed', { name: finalName }) }
2398
2405
  }
2399
2406
 
2400
2407
  const goalCmd: CommandHandler = (ctx, args) => {
@@ -4496,6 +4503,14 @@ const resumeDeleteCmd: CommandHandler = async (ctx, args) => {
4496
4503
  return { content: t('commands.resume.delete_usage') }
4497
4504
  }
4498
4505
 
4506
+ // Deleting the session you are in does not stick: the exit auto-save writes
4507
+ // the transcript back with its last prompt, so the name reappears. Refusing
4508
+ // here is the honest answer — the deletion would look done and be undone
4509
+ // (318-021).
4510
+ if (name === ctx.sessionId) {
4511
+ return { content: t('commands.resume.delete_current', { name }) }
4512
+ }
4513
+
4499
4514
  const { SessionStore } = await import('../core/session-store')
4500
4515
  const deleted = SessionStore.delete(name)
4501
4516