@miphamai/cli 0.85.30 → 0.85.32

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.30
1
+ # Mipham Code v0.85.32
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.30",
3
+ "version": "0.85.32",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -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)
@@ -2442,7 +2442,7 @@ function toolResultText(content: ContentBlock[]): string {
2442
2442
  */
2443
2443
  export function isContextOverflowError(message: string | null | undefined): boolean {
2444
2444
  if (!message) return false
2445
- 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(
2446
2446
  message,
2447
2447
  )
2448
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
@@ -11,6 +11,7 @@ import { HttpTransport, McpHttpError } from './http-transport'
11
11
  import { McpProtocol } from './protocol'
12
12
  import { OAuthClient } from './oauth'
13
13
  import { TokenStore } from './token-store'
14
+ import { basename } from 'node:path'
14
15
  import { createAwakeTimer } from '../providers/fetch-utils'
15
16
  import { createT } from '../i18n-core/t'
16
17
  import enUS from '../i18n-core/locales/en-US.json'
@@ -25,16 +26,46 @@ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as Translat
25
26
 
26
27
  // Connect-handshake timeout: a hung MCP server should fail startup fast rather
27
28
  // than block on the per-request 60s timeout. Overridable via env for tests.
28
- const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
29
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
30
+
31
+ /**
32
+ * Budget for a server launched through a package manager (`npx -y <pkg>`, …).
33
+ *
34
+ * `spawn('npx')` returns immediately — the dependency download happens inside
35
+ * the child, so the whole cost lands on `initialize()` waiting for a reply. A
36
+ * cold cache measured 29.9 s here (2× the default), and the server is *working*,
37
+ * not hung: failing at 15 s throws that work away and then races a second
38
+ * install against the first.
39
+ *
40
+ * Kept under `DEFAULT_REQUEST_TIMEOUT_MS` (60 s) on purpose: past it the
41
+ * handshake dies on the request timer instead, which only changes the error
42
+ * message, not the patience.
43
+ */
44
+ export const PACKAGE_MANAGER_CONNECT_TIMEOUT_MS = 45_000
45
+
46
+ /** Commands whose startup includes package resolution, so the budget is theirs. */
47
+ const PACKAGE_MANAGER_COMMANDS = new Set(['npx', 'bunx', 'npm', 'pnpm', 'yarn'])
48
+
49
+ function isPackageManagerCommand(command: string | undefined): boolean {
50
+ if (!command) return false
51
+ // Windows resolves these as `npx.cmd`; the shape of the wait is the same.
52
+ const base = basename(command)
53
+ .replace(/\.(cmd|exe|ps1)$/i, '')
54
+ .toLowerCase()
55
+ return PACKAGE_MANAGER_COMMANDS.has(base)
56
+ }
29
57
 
30
58
  // How often a caller waiting on a handshake re-checks it. A handshake settles in
31
59
  // tens of milliseconds when it settles at all; this only bounds how long the wait
32
60
  // can overshoot the moment it actually did.
33
61
  const CONNECT_POLL_MS = 50
34
62
 
35
- function connectTimeoutMs(): number {
63
+ export function connectTimeoutMs(command?: string): number {
36
64
  const env = Number(process.env.MIPHAM_MCP_CONNECT_TIMEOUT_MS)
37
- return Number.isFinite(env) && env > 0 ? env : DEFAULT_CONNECT_TIMEOUT_MS
65
+ if (Number.isFinite(env) && env > 0) return env
66
+ return isPackageManagerCommand(command)
67
+ ? PACKAGE_MANAGER_CONNECT_TIMEOUT_MS
68
+ : DEFAULT_CONNECT_TIMEOUT_MS
38
69
  }
39
70
 
40
71
  /**
@@ -449,7 +480,7 @@ export class McpClient {
449
480
  // is what an unauthenticated request gets rejected on.
450
481
  const env = await this.envWithAuth(config)
451
482
 
452
- await this.withConnectTimeout(config.name, async () => {
483
+ await this.withConnectTimeout(config.name, config.command, async () => {
453
484
  // Start the transport (transport-specific), then perform the handshake.
454
485
  if (transport instanceof HttpTransport) {
455
486
  await transport.start(config.url ?? '', config.headers, env)
@@ -458,7 +489,6 @@ export class McpClient {
458
489
  }
459
490
  const initResult: InitializeResult = await protocol.initialize()
460
491
 
461
- connection.status = 'connected'
462
492
  connection.serverInfo = initResult.serverInfo
463
493
  connection.instructions = initResult.instructions
464
494
 
@@ -471,6 +501,13 @@ export class McpClient {
471
501
  if (initResult.capabilities.tools) {
472
502
  connection.tools = await protocol.listTools()
473
503
  }
504
+
505
+ // `connected` is a claim about the server *and* its tool list. Setting
506
+ // it right after the handshake made `connect()` (and `reconnect()`)
507
+ // early-return while `tools/list` was still in flight, so a concurrent
508
+ // caller registered zero tools and nothing re-emitted when the list
509
+ // landed. The `connecting` promise covers this window instead.
510
+ connection.status = 'connected'
474
511
  })
475
512
  } catch (err) {
476
513
  connection.status = 'error'
@@ -493,8 +530,12 @@ export class McpClient {
493
530
  * server registers no tools — never give `markIfTransportLost` a chance to
494
531
  * reconnect. The server is fine; only the clock moved.
495
532
  */
496
- private async withConnectTimeout<T>(name: string, fn: () => Promise<T>): Promise<T> {
497
- const timeoutMs = connectTimeoutMs()
533
+ private async withConnectTimeout<T>(
534
+ name: string,
535
+ command: string | undefined,
536
+ fn: () => Promise<T>,
537
+ ): Promise<T> {
538
+ const timeoutMs = connectTimeoutMs(command)
498
539
  // Held in an object, not a `let`: the timer is armed inside the Promise
499
540
  // executor, and assignments made there are invisible to control-flow
500
541
  // narrowing — TS keeps the variable typed `null` and the cleanup call below
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,
@@ -1,4 +1,4 @@
1
- import { spawn, type ChildProcess } from 'node:child_process'
1
+ import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
2
2
  import type { JsonRpcRequest, JsonRpcResponse, JsonRpcNotification } from './types'
3
3
 
4
4
  export type NotificationHandler = (notification: JsonRpcNotification) => void
@@ -51,13 +51,17 @@ function waitForExit(proc: ChildProcess, ms: number): Promise<void> {
51
51
  /**
52
52
  * Terminate the server **and its descendants** once the grace period expired.
53
53
  *
54
- * The tree half is Windows-only, and deliberately so: Windows gives us no
55
- * process group to signal, so `taskkill /T` is the only way to reach the
56
- * server's own children. On POSIX we do **not** spawn MCP servers detached, so
57
- * the child shares our process group and has no group of its own —
58
- * `process.kill(-pid)` would be ESRCH, and making it a group leader would let
59
- * servers outlive the CLI, a worse bug than the one being fixed. There, the
60
- * grace period above *is* the fix; killing the direct child is what we always did.
54
+ * Windows has no process group to signal, so `taskkill /T` is the only way to
55
+ * reach the server's own children. On POSIX we do **not** spawn MCP servers
56
+ * detached — the child shares our process group, so `process.kill(-pid)` is
57
+ * ESRCH — and making it a group leader would let servers outlive the CLI, a
58
+ * worse bug than the one being fixed. So the descendants are enumerated from
59
+ * `ps` instead and signalled one by one.
60
+ *
61
+ * Killing only the direct child was wrong for the shape that matters:
62
+ * `npx -y some-mcp` spawns a **wrapper**, and the server that answers JSON-RPC
63
+ * is its child. Killing the wrapper re-parents that child to init and it keeps
64
+ * running — observed as accumulating `ppid=1` `node …/_npx/…/xxx-mcp` processes.
61
65
  */
62
66
  function killProcessTree(proc: ChildProcess): void {
63
67
  const pid = proc.pid
@@ -68,6 +72,16 @@ function killProcessTree(proc: ChildProcess): void {
68
72
  } catch {
69
73
  /* fall through to the direct kill */
70
74
  }
75
+ } else {
76
+ // Deepest first, while the parent links that identified them still exist:
77
+ // once the wrapper dies its children are re-parented and unfindable.
78
+ for (const descendant of descendantPids(pid).reverse()) {
79
+ try {
80
+ process.kill(descendant)
81
+ } catch {
82
+ /* already gone */
83
+ }
84
+ }
71
85
  }
72
86
  try {
73
87
  proc.kill()
@@ -76,6 +90,39 @@ function killProcessTree(proc: ChildProcess): void {
76
90
  }
77
91
  }
78
92
 
93
+ /** Every descendant of `root`, parents before children. */
94
+ function descendantPids(root: number): number[] {
95
+ let listing: string
96
+ try {
97
+ listing = execFileSync('ps', ['-A', '-o', 'pid=,ppid='], {
98
+ encoding: 'utf-8',
99
+ timeout: 2000,
100
+ })
101
+ } catch {
102
+ return [] // No `ps`, or it timed out: fall back to the direct kill.
103
+ }
104
+
105
+ const byParent = new Map<number, number[]>()
106
+ for (const line of listing.split('\n')) {
107
+ const [pidText, ppidText] = line.trim().split(/\s+/)
108
+ const pid = Number(pidText)
109
+ const ppid = Number(ppidText)
110
+ if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue
111
+ const siblings = byParent.get(ppid)
112
+ if (siblings) siblings.push(pid)
113
+ else byParent.set(ppid, [pid])
114
+ }
115
+
116
+ const descendants: number[] = []
117
+ const queue = [...(byParent.get(root) ?? [])]
118
+ while (queue.length > 0) {
119
+ const next = queue.shift()!
120
+ descendants.push(next)
121
+ queue.push(...(byParent.get(next) ?? []))
122
+ }
123
+ return descendants
124
+ }
125
+
79
126
  /** Shared timeout error for both stdio and HTTP transports. */
80
127
  export function requestTimeoutError(method: string, ms: number): Error {
81
128
  return new Error(`MCP request timeout: ${method} (${ms}ms)`)
@@ -105,7 +152,7 @@ const SENSITIVE_ENV_PATTERNS = [
105
152
  * Build a sanitised environment for MCP subprocesses.
106
153
  * Strips sensitive vars; allows explicit overrides via `extra`.
107
154
  */
108
- function buildProcEnv(extra?: Record<string, string>): Record<string, string> {
155
+ export function buildProcEnv(extra?: Record<string, string>): Record<string, string> {
109
156
  const sanitized: Record<string, string> = {}
110
157
 
111
158
  for (const [key, value] of Object.entries(process.env as Record<string, string>)) {
@@ -114,9 +161,17 @@ function buildProcEnv(extra?: Record<string, string>): Record<string, string> {
114
161
  sanitized[key] = value
115
162
  }
116
163
 
117
- // Explicit overrides take precedence (for intentionally shared secrets)
164
+ // Explicit overrides take precedence (for intentionally shared secrets).
165
+ //
166
+ // An empty override means "not set", not "set to empty": passing
167
+ // `AWS_BEARER_TOKEN_BEDROCK=""` makes the SDK skip the machine's own
168
+ // credential chain and fail auth, while an unset variable lets it fall back.
169
+ // `Object.assign` used to copy the empty string verbatim.
118
170
  if (extra) {
119
- Object.assign(sanitized, extra)
171
+ for (const [key, value] of Object.entries(extra)) {
172
+ if (value === '') delete sanitized[key]
173
+ else sanitized[key] = value
174
+ }
120
175
  }
121
176
 
122
177
  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.30' as const
12
+ export const PACKAGE_VERSION = '0.85.32' 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 = 4620 as const
93
+ export const TEST_COUNT = 4662 as const
@@ -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
@@ -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