@miphamai/cli 0.85.42 → 0.85.44
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 +3 -3
- package/package.json +1 -1
- package/src/agent/agent-context.ts +49 -0
- package/src/agent/agent-registry.ts +6 -0
- package/src/agent/sub-agent.ts +5 -0
- package/src/commands/project.ts +3 -1
- package/src/config/loader.ts +38 -1
- package/src/core/engine.ts +155 -16
- package/src/core/hooks-executor.ts +40 -6
- package/src/core/hooks.ts +8 -0
- package/src/core/permission-rules.ts +168 -29
- package/src/core/permission.ts +20 -0
- package/src/core/session-log.ts +39 -1
- package/src/core/session-store.ts +33 -1
- package/src/core/tool-gate.ts +7 -1
- package/src/daemon/engine-capabilities.ts +9 -1
- package/src/i18n-core/locales/en-US.json +10 -2
- package/src/i18n-core/locales/zh-CN.json +10 -2
- package/src/index.tsx +31 -6
- package/src/mcp/client.ts +27 -0
- package/src/mcp/registry.ts +18 -4
- package/src/mcp/transport.ts +15 -0
- package/src/mcp/types.ts +6 -0
- package/src/providers/anthropic.ts +14 -1
- package/src/providers/bootstrap.ts +13 -0
- package/src/providers/openai-compat.ts +6 -1
- package/src/shared/package-info.ts +3 -3
- package/src/shared/types.ts +18 -0
- package/src/skills/loader.ts +30 -0
- package/src/tools/exec/bash.ts +204 -25
- package/src/tools/file/glob.ts +58 -6
- package/src/tools/file/grep.ts +9 -1
- package/src/tools/system/tool-search.ts +2 -1
- package/src/ui/app.tsx +41 -21
- package/src/ui/command-picker.tsx +2 -5
- package/src/ui/commands.ts +143 -9
- package/src/ui/input.tsx +35 -10
- package/src/ui/picker.tsx +1 -1
|
@@ -544,43 +544,176 @@ function skipEnvAssignment(tokens: string[], start: number): number {
|
|
|
544
544
|
* `bash -c 'rm -rf /'`. Over-matching is the safe direction for a deny rule.
|
|
545
545
|
*/
|
|
546
546
|
export function flattenCommand(command: string, depth = 0): string[] {
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
547
|
+
return flattenCommandGroups(command, depth).flatMap((group) => group.variants)
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** One shell segment plus every normalized reading of it. */
|
|
551
|
+
export interface CommandSegmentGroup {
|
|
552
|
+
/** The segment as written — guards about what the command *really* runs judge this. */
|
|
553
|
+
raw: string
|
|
554
|
+
/** Readings of the same segment; a rule matching **any** of them matches the segment. */
|
|
555
|
+
variants: string[]
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Like `flattenCommand`, but keeps each command segment's normalizations
|
|
560
|
+
* together.
|
|
561
|
+
*
|
|
562
|
+
* Why the grouping matters for an **allow** rule: a rule is a grant, and a
|
|
563
|
+
* compound command must satisfy it in every segment. The normalizations of one
|
|
564
|
+
* segment are alternative readings of the *same* command, so the grant needs
|
|
565
|
+
* only one of them to match — flattening everything into one list made the raw
|
|
566
|
+
* spelling mandatory too, and `NODE_ENV=production npm run build` stopped
|
|
567
|
+
* matching `Bash(npm:*)` (nor did `sudo npm run build`).
|
|
568
|
+
*
|
|
569
|
+
* The raw spelling is still what the foreign-command guard reads (see
|
|
570
|
+
* `matchBashRule`): stripping `--exec-path=…` must not let the normalized form
|
|
571
|
+
* pass a grant the raw form was refused.
|
|
572
|
+
*/
|
|
573
|
+
export function flattenCommandGroups(command: string, depth = 0): CommandSegmentGroup[] {
|
|
574
|
+
const groups: CommandSegmentGroup[] = []
|
|
575
|
+
for (const seg of splitShellSegments(joinLineContinuations(command))) {
|
|
576
|
+
const variants: string[] = [seg]
|
|
550
577
|
// The shell removes quotes before running the command, so `rm "-rf" /tmp`
|
|
551
578
|
// *is* `rm -rf /tmp` — but the rule text is written without quotes, so the
|
|
552
579
|
// quoted spelling used to slip past `Bash(rm -rf *)`.
|
|
553
|
-
const
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
580
|
+
const push = (v: string) => {
|
|
581
|
+
if (v !== seg && !variants.includes(v)) variants.push(v)
|
|
582
|
+
}
|
|
583
|
+
push(dequoteSimpleTokens(seg))
|
|
584
|
+
push(stripPrefixCommand(seg))
|
|
557
585
|
// 剥掉前导噪声后的形态也要参与匹配:`IFS=x rm -rf x` / `( rm -rf x )` /
|
|
558
586
|
// `for …; do rm -rf x; done` 执行的仍是 `rm`,规则必须看得见它。同一个函数
|
|
559
587
|
// 也被 scanReaderWriterCommands 用(Read/Write/Edit 桥接那条路径)—— 两条
|
|
560
588
|
// 路径共用一份归一化,只接一条就是只修一半。
|
|
561
|
-
|
|
562
|
-
if (denoised !== seg) out.push(denoised)
|
|
563
|
-
for (const inner of extractSubstitutions(seg)) {
|
|
564
|
-
out.push(...flattenCommand(inner, depth + 1))
|
|
565
|
-
}
|
|
589
|
+
push(stripLeadingShellNoise(seg))
|
|
566
590
|
// Wrapper prefixes (`env`, `sudo`, `timeout`, …) are not the command being
|
|
567
591
|
// run. Without their removal `env X="a b" rm -rf /` matched no `rm …`
|
|
568
592
|
// rule at all, because the matcher never saw past the assignment.
|
|
569
593
|
const { base, args, payload } = effectiveCommand(seg.split(/\s+/).filter(Boolean))
|
|
570
|
-
if (base)
|
|
571
|
-
|
|
572
|
-
|
|
594
|
+
if (base) push([base, ...args].join(' '))
|
|
595
|
+
// Global options before a subcommand (`git -C /path log`). The allow rule
|
|
596
|
+
// `Bash(git log:*)` names the subcommand, and the option only decides where
|
|
597
|
+
// it runs — not which program does. Guarded variants are judged on `raw`.
|
|
598
|
+
const subcommand = stripGlobalOptions(seg)
|
|
599
|
+
if (subcommand) push(subcommand)
|
|
600
|
+
|
|
601
|
+
groups.push({ raw: seg, variants })
|
|
602
|
+
|
|
603
|
+
for (const inner of extractSubstitutions(seg)) {
|
|
604
|
+
groups.push(...flattenCommandGroups(inner, depth + 1))
|
|
573
605
|
}
|
|
574
606
|
// A shell `-c` payload is a command line in its own right, so `Bash(rm *)`
|
|
575
607
|
// must also match `bash -c 'rm -rf /'`. Past the depth bound recursion stops
|
|
576
608
|
// outright rather than pushing the raw payload: the raw text
|
|
577
609
|
// (`bash -c 'rm -rf /'`) matches no `rm …` pattern anyway, and stopping
|
|
578
610
|
// keeps the boundary predictable.
|
|
579
|
-
if (payload && depth < MAX_COMMAND_DEPTH)
|
|
611
|
+
if (payload && depth < MAX_COMMAND_DEPTH)
|
|
612
|
+
groups.push(...flattenCommandGroups(payload, depth + 1))
|
|
613
|
+
}
|
|
614
|
+
return groups
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Remove backslash-newline continuations before splitting a command into
|
|
619
|
+
* segments.
|
|
620
|
+
*
|
|
621
|
+
* `splitShellSegments` splits on `\n`, but a shell removes `\` + newline
|
|
622
|
+
* *before* parsing, so `npm install \⏎left-pad` is one command. Splitting first
|
|
623
|
+
* produced two segments — the first (`npm install \`) matched no allow rule and
|
|
624
|
+
* the whole command fell back to "ask". Inside single quotes the backslash is
|
|
625
|
+
* literal, so the pair stays.
|
|
626
|
+
*/
|
|
627
|
+
export function joinLineContinuations(command: string): string {
|
|
628
|
+
let out = ''
|
|
629
|
+
let quote: "'" | '"' | null = null
|
|
630
|
+
for (let i = 0; i < command.length; i++) {
|
|
631
|
+
const ch = command[i]!
|
|
632
|
+
if (ch === '\\' && quote !== "'") {
|
|
633
|
+
if (command[i + 1] === '\n') {
|
|
634
|
+
i += 1
|
|
635
|
+
continue
|
|
636
|
+
}
|
|
637
|
+
if (command[i + 1] === '\r' && command[i + 2] === '\n') {
|
|
638
|
+
i += 2
|
|
639
|
+
continue
|
|
640
|
+
}
|
|
641
|
+
// Any other escaped character: keep both, and do not let the escaped
|
|
642
|
+
// character toggle quote state (`\"` is a literal quote).
|
|
643
|
+
out += ch
|
|
644
|
+
if (i + 1 < command.length) {
|
|
645
|
+
out += command[i + 1]
|
|
646
|
+
i += 1
|
|
647
|
+
}
|
|
648
|
+
continue
|
|
649
|
+
}
|
|
650
|
+
if (ch === "'" && quote !== '"') {
|
|
651
|
+
quote = quote === "'" ? null : "'"
|
|
652
|
+
} else if (ch === '"' && quote !== "'") {
|
|
653
|
+
quote = quote === '"' ? null : '"'
|
|
654
|
+
}
|
|
655
|
+
out += ch
|
|
580
656
|
}
|
|
581
657
|
return out
|
|
582
658
|
}
|
|
583
659
|
|
|
660
|
+
/** git global options that consume the next token. */
|
|
661
|
+
const GIT_GLOBAL_WITH_ARG = new Set([
|
|
662
|
+
'-C',
|
|
663
|
+
'-c',
|
|
664
|
+
'--git-dir',
|
|
665
|
+
'--work-tree',
|
|
666
|
+
'--namespace',
|
|
667
|
+
'--exec-path',
|
|
668
|
+
'--config-env',
|
|
669
|
+
'--super-prefix',
|
|
670
|
+
])
|
|
671
|
+
/** git global options that stand alone. */
|
|
672
|
+
const GIT_GLOBAL_FLAGS = new Set([
|
|
673
|
+
'-p',
|
|
674
|
+
'--paginate',
|
|
675
|
+
'-P',
|
|
676
|
+
'--no-pager',
|
|
677
|
+
'--bare',
|
|
678
|
+
'--no-replace-objects',
|
|
679
|
+
'--literal-pathspecs',
|
|
680
|
+
'--no-optional-locks',
|
|
681
|
+
'--no-advice',
|
|
682
|
+
'--no-lazy-fetch',
|
|
683
|
+
])
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Normalize a known command by dropping global options that precede its
|
|
687
|
+
* subcommand (`git -C /path log` → `git log`).
|
|
688
|
+
*
|
|
689
|
+
* Only commands whose global-option grammar is known are normalized — a generic
|
|
690
|
+
* "skip everything that starts with -" would drop flags that *are* the command's
|
|
691
|
+
* behaviour. Returns null when there is nothing to strip.
|
|
692
|
+
*/
|
|
693
|
+
export function stripGlobalOptions(segment: string): string | null {
|
|
694
|
+
const tokens = segment.trim().split(/\s+/)
|
|
695
|
+
if (tokens[0] !== 'git') return null
|
|
696
|
+
let i = 1
|
|
697
|
+
while (i < tokens.length) {
|
|
698
|
+
const token = tokens[i]!
|
|
699
|
+
if (GIT_GLOBAL_FLAGS.has(token)) {
|
|
700
|
+
i += 1
|
|
701
|
+
continue
|
|
702
|
+
}
|
|
703
|
+
if (GIT_GLOBAL_WITH_ARG.has(token)) {
|
|
704
|
+
i += 2
|
|
705
|
+
continue
|
|
706
|
+
}
|
|
707
|
+
if ([...GIT_GLOBAL_WITH_ARG].some((opt) => token.startsWith(`${opt}=`))) {
|
|
708
|
+
i += 1
|
|
709
|
+
continue
|
|
710
|
+
}
|
|
711
|
+
break
|
|
712
|
+
}
|
|
713
|
+
if (i === 1 || i >= tokens.length) return null
|
|
714
|
+
return ['git', ...tokens.slice(i)].join(' ')
|
|
715
|
+
}
|
|
716
|
+
|
|
584
717
|
/**
|
|
585
718
|
* Resolve the effective command and its arguments after any wrapper prefix
|
|
586
719
|
* commands (`sudo`, `env`, `timeout`, …). Skips the wrapper and its own options
|
|
@@ -1016,7 +1149,7 @@ export function matchBashRule(
|
|
|
1016
1149
|
// The `length > 0` guard is load-bearing: `[].every()` is `true`, so a
|
|
1017
1150
|
// command with no matchable segment (or no extracted file access) would
|
|
1018
1151
|
// otherwise satisfy **any** allow rule — a fail-open of its own.
|
|
1019
|
-
const qualifies = (items:
|
|
1152
|
+
const qualifies = <T>(items: T[], match: (item: T) => boolean): boolean =>
|
|
1020
1153
|
segmentMode === 'all' ? items.length > 0 && items.every(match) : items.some(match)
|
|
1021
1154
|
|
|
1022
1155
|
// A Read/Write/Edit rule must also refuse a Bash command that touches the
|
|
@@ -1066,24 +1199,30 @@ export function matchBashRule(
|
|
|
1066
1199
|
// the safe direction.
|
|
1067
1200
|
const anchored = segmentMode === 'all' ? /^([\w./-]+)\*/.exec(subPattern!) : null
|
|
1068
1201
|
const firstWord = anchored?.[1]
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
)
|
|
1077
|
-
if (!boundary.test(seg)) return false
|
|
1078
|
-
}
|
|
1202
|
+
// The wildcard has to start at a word boundary in the command: `ls`
|
|
1203
|
+
// exactly, or `ls` followed by whitespace/`:` — not the `ls` inside
|
|
1204
|
+
// `lsof`.
|
|
1205
|
+
const boundary = firstWord
|
|
1206
|
+
? new RegExp('^' + firstWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?:$|[:\\s])')
|
|
1207
|
+
: null
|
|
1208
|
+
return qualifies(flattenCommandGroups(cmd), (group) => {
|
|
1079
1209
|
// An allow rule names a program; these options make that program run a
|
|
1080
1210
|
// **different** one (`find -exec rm`, `git --upload-pack=…`,
|
|
1081
1211
|
// `awk system(…)`). Matching the outer word alone would hand over the
|
|
1082
1212
|
// inner command too, so the segment is not covered by the grant. This
|
|
1083
1213
|
// list is a floor, not a ceiling — every entry is a construct that
|
|
1084
1214
|
// executes a command the rule did not name.
|
|
1085
|
-
|
|
1086
|
-
|
|
1215
|
+
//
|
|
1216
|
+
// Judged on the segment **as written**: the normalized variants exist to
|
|
1217
|
+
// let benign prefixes match, and letting them carry a stripped
|
|
1218
|
+
// `--exec-path=…` past this guard would turn the fix into a bypass.
|
|
1219
|
+
if (segmentMode === 'all' && embedsForeignCommand(group.raw)) return false
|
|
1220
|
+
// The variants are alternative readings of *this* command — any one of
|
|
1221
|
+
// them matching is enough. (Across segments the caller still applies
|
|
1222
|
+
// 'all' / 'any'; this is the within-segment OR.)
|
|
1223
|
+
return group.variants.some(
|
|
1224
|
+
(seg) => (!boundary || boundary.test(seg)) && wildcardMatch(subPattern!, seg),
|
|
1225
|
+
)
|
|
1087
1226
|
})
|
|
1088
1227
|
}
|
|
1089
1228
|
|
package/src/core/permission.ts
CHANGED
|
@@ -514,6 +514,26 @@ export class PermissionSystem {
|
|
|
514
514
|
return this.agentCapWarnings
|
|
515
515
|
}
|
|
516
516
|
|
|
517
|
+
/**
|
|
518
|
+
* Does a deny rule name this tool **outright**?
|
|
519
|
+
*
|
|
520
|
+
* A rule with an input pattern (`Bash(rm:*)`, a path-scoped `Read`) denies
|
|
521
|
+
* *some* invocations, not the tool — those stay visible. A bare name, or a
|
|
522
|
+
* server wildcard (`mcp__srv__*`), denies every call; a tool the model can
|
|
523
|
+
* never run is not worth offering, and naming it in the request only invites
|
|
524
|
+
* calls that are guaranteed to fail.
|
|
525
|
+
*
|
|
526
|
+
* Read by `QueryEngine.getToolDefinitions()` to keep denied tools out of the
|
|
527
|
+
* model-facing list (the rule itself still decides at call time — this is a
|
|
528
|
+
* visibility filter, not a second gate).
|
|
529
|
+
*/
|
|
530
|
+
isToolNameDenied(toolName: string): boolean {
|
|
531
|
+
return this.denyRules.some(
|
|
532
|
+
(rule) =>
|
|
533
|
+
!rule.pattern.includes('(') && (rule.pattern === toolName || rule.compiled.test(toolName)),
|
|
534
|
+
)
|
|
535
|
+
}
|
|
536
|
+
|
|
517
537
|
// ── Rule management ──
|
|
518
538
|
|
|
519
539
|
allow(rule: string): void {
|
package/src/core/session-log.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdirSync, openSync, readSync, closeSync, statSync } from 'node:fs'
|
|
1
|
+
import { mkdirSync, openSync, readSync, closeSync, statSync, existsSync, renameSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { createHash } from 'node:crypto'
|
|
4
4
|
import type { Message, ToolUseContent, ToolResultContent, ToolResult } from '../shared/types'
|
|
@@ -278,6 +278,44 @@ export class SessionLog {
|
|
|
278
278
|
this.save()
|
|
279
279
|
}
|
|
280
280
|
|
|
281
|
+
/** 当前会话名(`/rename` 之后是**新**名字 —— 落盘路径按它推导)。 */
|
|
282
|
+
getName(): string {
|
|
283
|
+
return this.name
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* 把会话日志改名 —— 让 `/rename` 与 `/resume <name>` 落在**同一个命名空间**。
|
|
288
|
+
*
|
|
289
|
+
* 从前 `/rename` 只改内存标题与跨会话登记表,`<旧名>.jsonl` 原封不动:用户
|
|
290
|
+
* `/rename Bug Fix` 之后 `/resume Bug Fix` 找不到任何东西,而 `/resume <旧名>`
|
|
291
|
+
* 又读得到 —— 两个名字指向同一段对话,却只有一个是活的。
|
|
292
|
+
*
|
|
293
|
+
* 必须改 `this.name` 而不是只搬文件:`save()` 每次都按名字重算路径,文件搬走了
|
|
294
|
+
* 而字段没变,下一次 `append` 会**新建一个旧名字的空文件**,历史当场分叉。
|
|
295
|
+
*
|
|
296
|
+
* 返回 `'conflict'` 时什么都没动(目标名已有别的会话),调用方必须如实说出来:
|
|
297
|
+
* 静默覆盖别人的会话,或静默假称已改名,都是把「失败」渲染成「成功」。
|
|
298
|
+
*/
|
|
299
|
+
rename(newName: string): 'renamed' | 'unchanged' | 'conflict' {
|
|
300
|
+
if (newName === this.name) return 'unchanged'
|
|
301
|
+
const oldPath = join(this.dir, `${sanitizeSessionName(this.name)}.jsonl`)
|
|
302
|
+
const newPath = join(this.dir, `${sanitizeSessionName(newName)}.jsonl`)
|
|
303
|
+
// 两个不同名字可能消毒到同一个文件名(`a/b` 与 `a_b`):此时文件已经是
|
|
304
|
+
// 目标路径,不需要也不能 rename。
|
|
305
|
+
if (oldPath !== newPath) {
|
|
306
|
+
if (existsSync(newPath)) return 'conflict'
|
|
307
|
+
if (existsSync(oldPath)) {
|
|
308
|
+
try {
|
|
309
|
+
renameSync(oldPath, newPath)
|
|
310
|
+
} catch {
|
|
311
|
+
return 'conflict'
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
this.name = newName
|
|
316
|
+
return 'renamed'
|
|
317
|
+
}
|
|
318
|
+
|
|
281
319
|
/** 不可变快照(浅拷贝,事件本身视为不可变)。 */
|
|
282
320
|
events(): SessionEvent[] {
|
|
283
321
|
return [...this.buf]
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdirSync, readdirSync, unlinkSync, existsSync, statSync } from 'node:fs'
|
|
1
|
+
import { mkdirSync, readdirSync, unlinkSync, existsSync, statSync, renameSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { createHash } from 'node:crypto'
|
|
4
4
|
import type { Message } from '../shared/types'
|
|
@@ -333,6 +333,38 @@ export class SessionStore {
|
|
|
333
333
|
atomicWriteFileSync(INDEX_FILE, JSON.stringify(index, null, 2), { mode: 0o600 })
|
|
334
334
|
}
|
|
335
335
|
|
|
336
|
+
/**
|
|
337
|
+
* Move a session's **index entry** (and its saved summary) to a new name.
|
|
338
|
+
*
|
|
339
|
+
* `/rename` renames the transcript file via `SessionLog.rename`; the index is a
|
|
340
|
+
* separate store, and leaving the old row behind makes `/resume last` point at
|
|
341
|
+
* a file that no longer exists. Returns false when there is no old entry or the
|
|
342
|
+
* new name is already taken — in both cases *nothing* is changed, so a caller
|
|
343
|
+
* that reports failure is telling the truth.
|
|
344
|
+
*/
|
|
345
|
+
static renameEntry(oldName: string, newName: string): boolean {
|
|
346
|
+
ensureDir()
|
|
347
|
+
const index = SessionStore.loadIndexRaw()
|
|
348
|
+
const entry = index.find((e) => e.name === oldName)
|
|
349
|
+
if (!entry) return false
|
|
350
|
+
if (index.some((e) => e.name === newName)) return false
|
|
351
|
+
entry.name = newName
|
|
352
|
+
atomicWriteFileSync(INDEX_FILE, JSON.stringify(index, null, 2), { mode: 0o600 })
|
|
353
|
+
|
|
354
|
+
// The summary file is named after the session, so it has to follow too —
|
|
355
|
+
// otherwise the renamed session silently loses the recap the user generated.
|
|
356
|
+
const oldSummary = join(SUMMARIES_DIR, `${sanitizeSessionName(oldName)}.md`)
|
|
357
|
+
const newSummary = join(SUMMARIES_DIR, `${sanitizeSessionName(newName)}.md`)
|
|
358
|
+
if (oldSummary !== newSummary && existsSync(oldSummary) && !existsSync(newSummary)) {
|
|
359
|
+
try {
|
|
360
|
+
renameSync(oldSummary, newSummary)
|
|
361
|
+
} catch {
|
|
362
|
+
// Summary is a cache; a failed move must not fail the rename.
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return true
|
|
366
|
+
}
|
|
367
|
+
|
|
336
368
|
/**
|
|
337
369
|
* Persist an LLM-generated summary for a session.
|
|
338
370
|
* Writes a markdown file to .summaries/ and updates the index entry.
|
package/src/core/tool-gate.ts
CHANGED
|
@@ -95,10 +95,16 @@ export async function runPreToolGate(
|
|
|
95
95
|
// key name. `defer` (and an absent decision) means "no override", which is
|
|
96
96
|
// exactly what happens when we do nothing.
|
|
97
97
|
if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
|
|
98
|
+
// A hook that also supplied `updatedInput` proposed a rewrite; there is no
|
|
99
|
+
// approval path to carry it through, so we refuse — but say the rewrite
|
|
100
|
+
// existed. Silently discarding it is the failure mode this note removes.
|
|
101
|
+
const rewriteNote = preResult.modifiedInput
|
|
102
|
+
? ` ${t('errors.tool_hook_ask_rewrite', { name })}`
|
|
103
|
+
: ''
|
|
98
104
|
return {
|
|
99
105
|
ok: false,
|
|
100
106
|
content: '',
|
|
101
|
-
error: preResult.reason || t('errors.tool_hook_ask', { name }),
|
|
107
|
+
error: (preResult.reason || t('errors.tool_hook_ask', { name })) + rewriteNote,
|
|
102
108
|
notRun: true,
|
|
103
109
|
}
|
|
104
110
|
}
|
|
@@ -79,6 +79,10 @@ function skillsFor(cwd: string, paths?: string[]): SkillsLoader {
|
|
|
79
79
|
loader.loadBuiltinFromPackage()
|
|
80
80
|
if (!isSafeMode()) {
|
|
81
81
|
loader.loadUserSkills()
|
|
82
|
+
// Project scope follows the workspace (`<cwd>/.mipham/skills`), same as the
|
|
83
|
+
// CLI — the two entry points must load the same set or a skill works in one
|
|
84
|
+
// and silently not in the other.
|
|
85
|
+
loader.loadProjectSkills(cwd)
|
|
82
86
|
if (paths && paths.length > 0) loader.loadExternal(paths)
|
|
83
87
|
}
|
|
84
88
|
skillsCache.set(cwd, loader)
|
|
@@ -117,7 +121,11 @@ function hooksFor(cwd: string, skills: SkillsLoader): HookEngine {
|
|
|
117
121
|
const projectHooksTrusted = getWorkspaceTrust().isTrusted(cwd)
|
|
118
122
|
const settings = loadSettingsJson(cwd, { includeProjectHooks: projectHooksTrusted })
|
|
119
123
|
if (settings.projectHooksSkipped) warnProjectHooksSkipped(cwd)
|
|
120
|
-
|
|
124
|
+
// Same setting, same meaning on the daemon path — a session started by the
|
|
125
|
+
// daemon must not run hooks the CLI would have skipped.
|
|
126
|
+
if (!settings.disableAllHooks) {
|
|
127
|
+
for (const def of loadHookConfigs(settings.hooks)) engine.register(def)
|
|
128
|
+
}
|
|
121
129
|
hookCache.set(cwd, engine)
|
|
122
130
|
return engine
|
|
123
131
|
}
|
|
@@ -92,7 +92,8 @@
|
|
|
92
92
|
"rename": {
|
|
93
93
|
"usage": "Usage: /rename <session-name>\nExample: /rename Bug Fix Session",
|
|
94
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
|
+
"unsaved": "⚠ Session title set to \"{name}\" for this run, but it could not be saved to the session registry — the name may not last.",
|
|
96
|
+
"log_conflict": "⚠ Title set to \"{name}\", but a saved session already uses that name — the transcript stays under \"{old}\" (/resume {old})."
|
|
96
97
|
},
|
|
97
98
|
"plan": {
|
|
98
99
|
"entered": "Entered plan mode.",
|
|
@@ -122,7 +123,9 @@
|
|
|
122
123
|
"footer": "Token counting is approximate (chars/4).\nActual API usage depends on provider and model."
|
|
123
124
|
},
|
|
124
125
|
"model": {
|
|
125
|
-
"current": "Current model: {model}\nProvider: {provider}\n\nUse /switch <provider> <model> to change."
|
|
126
|
+
"current": "Current model: {model}\nProvider: {provider}\n\nUse /model <model> or /switch <provider> <model> to change.",
|
|
127
|
+
"unknown": "Unknown model: {model}. Use /models to list the available models.",
|
|
128
|
+
"ambiguous": "Model \"{model}\" is available from more than one provider ({providers}). Use /switch <provider> {model}."
|
|
126
129
|
},
|
|
127
130
|
"models": {
|
|
128
131
|
"title": "Available models ({count} active):",
|
|
@@ -483,6 +486,7 @@
|
|
|
483
486
|
"source_project": "project",
|
|
484
487
|
"gated": "⚠️ workspace not trusted — will not run",
|
|
485
488
|
"undispatched": "⚠️ no dispatch point in this version — will not run",
|
|
489
|
+
"disabled_all": "⚠️ disableAllHooks is set — will not run",
|
|
486
490
|
"found": "{count} hook(s) found.",
|
|
487
491
|
"error": "── Hooks ──\n\nCould not read hooks directory."
|
|
488
492
|
},
|
|
@@ -957,6 +961,7 @@
|
|
|
957
961
|
"tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
|
|
958
962
|
"tool_blocked": "Tool \"{name}\" blocked by hook",
|
|
959
963
|
"tool_hook_ask": "Tool \"{name}\" was marked by a hook as needing approval, and this environment has no interactive prompt — so it is refused. A repository-supplied hook may narrow the gate but not approve a call; if this hook is your own, make it block outright or relax it.",
|
|
964
|
+
"tool_hook_ask_rewrite": "The hook also proposed a rewritten input for \"{name}\"; it was discarded, because a refusal has no approval path to carry it through.",
|
|
960
965
|
"user_input_blocked": "User input blocked by hook.",
|
|
961
966
|
"dlp_blocked": "Request blocked by DLP policy.",
|
|
962
967
|
"model_error": "Error: {error}",
|
|
@@ -982,6 +987,9 @@
|
|
|
982
987
|
"max_tool_turns_warning": "You've reached the maximum of {max} tool-calling rounds. {pending} tool call(s) were not executed. Please summarize what you found so far and any next steps the user should take.",
|
|
983
988
|
"turn_timeout": "Task produced no substantial output for {minutes} minutes and was stopped. Break the task into smaller steps or clarify the next step, then retry.",
|
|
984
989
|
"turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed. If you reach the provider through a proxy or a corporate gateway, check that first; otherwise check your VPN and firewall rules.",
|
|
990
|
+
"turn_continuing": "The reply hit the model's output limit — continuing automatically.",
|
|
991
|
+
"turn_truncated_limit": "The reply hit the model's output limit and was cut off; this turn will not be continued further.",
|
|
992
|
+
"continuation_prompt": "Your previous reply was cut off at the output limit. Continue exactly where it stopped — do not repeat anything already written.",
|
|
985
993
|
"turn_refused": "The model declined this request and did not answer. This is not a failure — resending it to the same model will usually be declined again.",
|
|
986
994
|
"turn_refused_reason": "The model declined this request: {reason}",
|
|
987
995
|
"stop_hook_budget_spent": "The Stop hook asked for more work (\"{reason}\"), but this turn has used all {max} of its tool-calling rounds — stopping here. Send another message to continue.",
|
|
@@ -92,7 +92,8 @@
|
|
|
92
92
|
"rename": {
|
|
93
93
|
"usage": "用法: /rename <session-name>\n示例: /rename 修复 Bug 的会话",
|
|
94
94
|
"confirmed": "✓ 会话重命名为 \"{name}\"",
|
|
95
|
-
"unsaved": "⚠ 本次会话已改名为 \"{name}\",但没能写入会话登记表 —— 这个名字可能不会保留。"
|
|
95
|
+
"unsaved": "⚠ 本次会话已改名为 \"{name}\",但没能写入会话登记表 —— 这个名字可能不会保留。",
|
|
96
|
+
"log_conflict": "⚠ 标题已改为 \"{name}\",但已存在同名会话存档 —— 对话记录仍保存在 \"{old}\" 下(可用 /resume {old} 找回)。"
|
|
96
97
|
},
|
|
97
98
|
"plan": {
|
|
98
99
|
"entered": "已进入计划模式。",
|
|
@@ -122,7 +123,9 @@
|
|
|
122
123
|
"footer": "Token 计数为近似值(字符数/4)。\n实际 API 用量取决于提供商和模型。"
|
|
123
124
|
},
|
|
124
125
|
"model": {
|
|
125
|
-
"current": "当前模型: {model}\n提供商: {provider}\n\n使用 /switch <provider> <model> 切换。"
|
|
126
|
+
"current": "当前模型: {model}\n提供商: {provider}\n\n使用 /model <model> 或 /switch <provider> <model> 切换。",
|
|
127
|
+
"unknown": "未知模型: {model}。用 /models 查看可用模型。",
|
|
128
|
+
"ambiguous": "模型 \"{model}\" 在多个提供商下都有({providers})。请用 /switch <provider> {model}。"
|
|
126
129
|
},
|
|
127
130
|
"models": {
|
|
128
131
|
"title": "可用模型({count} 个活跃):",
|
|
@@ -483,6 +486,7 @@
|
|
|
483
486
|
"source_project": "项目级",
|
|
484
487
|
"gated": "⚠️ 工作区未受信任,不会运行",
|
|
485
488
|
"undispatched": "⚠️ 本版本没有派发点,不会运行",
|
|
489
|
+
"disabled_all": "⚠️ 已设 disableAllHooks,不会运行",
|
|
486
490
|
"found": "找到 {count} 个钩子。",
|
|
487
491
|
"error": "── 钩子 ──\n\n无法读取钩子目录。"
|
|
488
492
|
},
|
|
@@ -957,6 +961,7 @@
|
|
|
957
961
|
"tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
|
|
958
962
|
"tool_blocked": "工具 \"{name}\" 被钩子拦截",
|
|
959
963
|
"tool_hook_ask": "工具 \"{name}\" 被钩子标为需要批准,而本环境没有交互批准 —— 已按拒绝处理。仓库带来的钩子只能收紧闸门、不能放行;若这是你自己的钩子,请让它直接拦截,或放宽它。",
|
|
964
|
+
"tool_hook_ask_rewrite": "该钩子同时为 \"{name}\" 提出了改写后的输入;因为本次是拒绝、没有批准通道可以承接它,改写已丢弃。",
|
|
960
965
|
"user_input_blocked": "用户输入被钩子拦截。",
|
|
961
966
|
"dlp_blocked": "请求被 DLP 策略阻止。",
|
|
962
967
|
"model_error": "错误:{error}",
|
|
@@ -982,6 +987,9 @@
|
|
|
982
987
|
"max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
|
|
983
988
|
"turn_timeout": "任务已超过 {minutes} 分钟无实质产出,已自动停止。建议拆分任务或明确下一步后重新发起。",
|
|
984
989
|
"turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。如果是经代理或公司网关访问提供商,先查那一层;否则检查 VPN 与防火墙规则。",
|
|
990
|
+
"turn_continuing": "回复到达模型输出上限 —— 正在自动续写。",
|
|
991
|
+
"turn_truncated_limit": "回复到达模型输出上限,已被截断;本轮不再继续续写。",
|
|
992
|
+
"continuation_prompt": "你上一条回复在输出上限处被截断了。请从断掉的地方原样接着写 —— 不要重复已经写过的内容。",
|
|
985
993
|
"turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
|
|
986
994
|
"turn_refused_reason": "模型拒绝了这次请求:{reason}",
|
|
987
995
|
"stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
|
package/src/index.tsx
CHANGED
|
@@ -554,6 +554,8 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
554
554
|
skillsLoader.loadBuiltinFromPackage()
|
|
555
555
|
if (!safeMode) {
|
|
556
556
|
skillsLoader.loadUserSkills()
|
|
557
|
+
// The documented project scope (`.mipham/skills/`) — see `loadProjectSkills`.
|
|
558
|
+
skillsLoader.loadProjectSkills(process.cwd())
|
|
557
559
|
if (config.skills?.paths) {
|
|
558
560
|
skillsLoader.loadExternal(config.skills.paths)
|
|
559
561
|
}
|
|
@@ -819,7 +821,10 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
819
821
|
// skip is announced, since silence would look the same as having passed.
|
|
820
822
|
// `settingsJson` itself was read up top, next to the permission it also feeds.
|
|
821
823
|
if (settingsJson.projectHooksSkipped) warnProjectHooksSkipped(process.cwd())
|
|
822
|
-
|
|
824
|
+
// `disableAllHooks` is the Claude Code setting name; honour it at the same
|
|
825
|
+
// wiring point as `--safe-mode` so a migrated settings file cannot keep
|
|
826
|
+
// spawning hook commands the operator believes are off.
|
|
827
|
+
if (!safeMode && !settingsJson.disableAllHooks) {
|
|
823
828
|
for (const def of loadHookConfigs(settingsJson.hooks)) {
|
|
824
829
|
hookEngine.register(def)
|
|
825
830
|
}
|
|
@@ -963,9 +968,16 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
963
968
|
}
|
|
964
969
|
|
|
965
970
|
// P2-1: Trigger SessionStart hooks after full initialization
|
|
966
|
-
hookEngine
|
|
967
|
-
|
|
968
|
-
|
|
971
|
+
hookEngine
|
|
972
|
+
.executeSessionStart(sessionName)
|
|
973
|
+
.then((result) => {
|
|
974
|
+
// No live stream exists yet at startup, so a user-facing `systemMessage`
|
|
975
|
+
// goes to stderr — the same channel the hook's other startup warnings use.
|
|
976
|
+
if (result.systemMessage) process.stderr.write(`⚠ ${result.systemMessage}\n`)
|
|
977
|
+
})
|
|
978
|
+
.catch(() => {
|
|
979
|
+
// Hook failures never block session startup
|
|
980
|
+
})
|
|
969
981
|
|
|
970
982
|
// Auto-save session on exit
|
|
971
983
|
let saved = false
|
|
@@ -977,7 +989,10 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
977
989
|
if (context.getMessageCount() === 0) return
|
|
978
990
|
const log = context.getLog()
|
|
979
991
|
if (log) {
|
|
980
|
-
|
|
992
|
+
// `/rename` moves the transcript file; the index entry must follow the
|
|
993
|
+
// log's *current* name, not the one this process started with — otherwise
|
|
994
|
+
// the row points at a file that was just renamed away.
|
|
995
|
+
SessionStore.saveLog(log.getName(), log, {
|
|
981
996
|
provider: defaultProvider,
|
|
982
997
|
model: defaultModel,
|
|
983
998
|
cwd: process.cwd(),
|
|
@@ -998,11 +1013,18 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
998
1013
|
// hooks and exiting in the same tick meant they never ran — the await is
|
|
999
1014
|
// the difference between "best effort" and "never". Bounded, because a
|
|
1000
1015
|
// hook waiting on an unreachable server must not hold the terminal open.
|
|
1001
|
-
await withTimeout(
|
|
1016
|
+
const endResult = await withTimeout(
|
|
1002
1017
|
hookEngine.executeSessionEnd(sessionName).catch(() => undefined),
|
|
1003
1018
|
SESSION_END_HOOK_TIMEOUT_MS,
|
|
1004
1019
|
)
|
|
1020
|
+
// The Ink tree is being torn down; stderr is the only channel left that the
|
|
1021
|
+
// operator will still see.
|
|
1022
|
+
if (endResult?.systemMessage) process.stderr.write(`⚠ ${endResult.systemMessage}\n`)
|
|
1005
1023
|
artifactServer.stop()
|
|
1024
|
+
// MCP servers are our children. `closeAll()` waits for stdin EOF, which is
|
|
1025
|
+
// the right thing during `/mcp reload`; at exit there is no time to wait,
|
|
1026
|
+
// and a server that ignores EOF would outlive the CLI.
|
|
1027
|
+
McpClient.shutdownSync()
|
|
1006
1028
|
persistSession()
|
|
1007
1029
|
// Finalize the session — write session summary + flush CRSI effectiveness
|
|
1008
1030
|
// (evaluate rules and apply auto-degrade/disable). Best-effort: the
|
|
@@ -1036,6 +1058,9 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
1036
1058
|
process.on('exit', () => {
|
|
1037
1059
|
clearInterval(heartbeatInterval)
|
|
1038
1060
|
unregisterSession(sessionName)
|
|
1061
|
+
// The last synchronous word on MCP children — `shutdown` covers the normal
|
|
1062
|
+
// paths; this covers `process.exit()` called from code that never saw it.
|
|
1063
|
+
McpClient.shutdownSync()
|
|
1039
1064
|
// Finalize the session on non-interactive exit paths
|
|
1040
1065
|
// (daemon worker / crash / kill) that bypass saveAndExit.
|
|
1041
1066
|
if (!saved) {
|
package/src/mcp/client.ts
CHANGED
|
@@ -651,6 +651,33 @@ export class McpClient {
|
|
|
651
651
|
McpClient.instance = null
|
|
652
652
|
}
|
|
653
653
|
|
|
654
|
+
/**
|
|
655
|
+
* Last-resort teardown for the `exit` event, where awaiting is impossible.
|
|
656
|
+
*
|
|
657
|
+
* `closeAll()` gives each server the stdin-EOF grace period; this one kills
|
|
658
|
+
* the process trees immediately. Without it, a server that ignores EOF
|
|
659
|
+
* survives the CLI — and the process group is not ours to rely on, since MCP
|
|
660
|
+
* children are deliberately not spawned detached.
|
|
661
|
+
*/
|
|
662
|
+
closeAllSync(): void {
|
|
663
|
+
this.closing = true
|
|
664
|
+
for (const [name, conn] of this.connections) {
|
|
665
|
+
try {
|
|
666
|
+
const transport = conn.transport as { closeSync?: () => void }
|
|
667
|
+
transport.closeSync?.()
|
|
668
|
+
} catch {
|
|
669
|
+
/* best effort */
|
|
670
|
+
}
|
|
671
|
+
this.connections.delete(name)
|
|
672
|
+
}
|
|
673
|
+
McpClient.instance = null
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** No-op when no client was ever created — the exit path must not create one. */
|
|
677
|
+
static shutdownSync(): void {
|
|
678
|
+
McpClient.instance?.closeAllSync()
|
|
679
|
+
}
|
|
680
|
+
|
|
654
681
|
getConnection(name: string): ConnectionInfo | undefined {
|
|
655
682
|
const conn = this.connections.get(name)
|
|
656
683
|
if (!conn) return undefined
|