@miphamai/cli 0.85.30 → 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 +1 -1
- package/package.json +1 -1
- package/src/config/loader.ts +6 -0
- package/src/core/engine.ts +1 -1
- package/src/core/hooks-executor.ts +3 -1
- package/src/core/hooks.ts +14 -4
- package/src/core/permission-rules.ts +158 -32
- package/src/core/permission.ts +44 -36
- package/src/core/workspace-trust.ts +22 -8
- package/src/i18n-core/locales/en-US.json +3 -1
- package/src/i18n-core/locales/zh-CN.json +3 -1
- package/src/index.tsx +11 -2
- package/src/mcp/client.ts +7 -1
- package/src/mcp/oauth.ts +15 -4
- package/src/mcp/transport.ts +11 -3
- package/src/shared/constants.ts +9 -0
- package/src/shared/package-info.ts +2 -2
- package/src/tools/file/edit.ts +13 -0
- package/src/ui/commands.ts +16 -1
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
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
package/src/config/loader.ts
CHANGED
|
@@ -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)
|
package/src/core/engine.ts
CHANGED
|
@@ -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
|
-
|
|
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 >
|
|
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
|
-
|
|
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 >
|
|
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
|
-
|
|
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
|
-
//
|
|
436
|
-
//
|
|
437
|
-
//
|
|
438
|
-
//
|
|
439
|
-
//
|
|
440
|
-
//
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
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
|
-
|
|
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
|
|
654
|
-
if (
|
|
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
|
|
669
|
-
if (
|
|
670
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/core/permission.ts
CHANGED
|
@@ -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
|
-
//
|
|
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
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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(
|
|
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
|
-
/**
|
|
91
|
-
|
|
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
|
-
//
|
|
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
|
-
/**
|
|
133
|
-
|
|
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
|
-
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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,
|
package/src/mcp/transport.ts
CHANGED
|
@@ -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.
|
|
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
|
package/src/shared/constants.ts
CHANGED
|
@@ -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.
|
|
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 =
|
|
93
|
+
export const TEST_COUNT = 4658 as const
|
package/src/tools/file/edit.ts
CHANGED
|
@@ -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/commands.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|