@miphamai/cli 0.85.45 → 0.85.46
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/agent/agent-context.ts +20 -13
- package/src/agent/background-registry.ts +5 -0
- package/src/agent/sub-agent.ts +13 -5
- package/src/core/engine.ts +14 -3
- package/src/core/git-pr.ts +17 -1
- package/src/core/hooks-config.ts +9 -0
- package/src/core/permission-classifier.ts +1 -1
- package/src/core/permission-rules.ts +190 -12
- package/src/core/permission.ts +7 -0
- package/src/mcp/oauth.ts +19 -2
- package/src/mcp/protocol.ts +31 -8
- package/src/mcp/transport.ts +4 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +9 -0
- package/src/skills/loader.ts +74 -6
- package/src/tools/agent/agent.ts +18 -0
- package/src/tools/exec/bash.ts +66 -1
- package/src/tools/exec/git.ts +11 -0
- package/src/tools/file/edit.ts +14 -1
- package/src/tools/file/glob.ts +12 -1
- package/src/tools/file/grep.ts +17 -1
- package/src/tools/system/tool-search.ts +29 -5
- package/src/tools/validation.ts +34 -1
- package/src/ui/app.tsx +6 -17
- 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.46
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 141 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
|
@@ -207,13 +207,14 @@ export function selectAgentTools(
|
|
|
207
207
|
.split(',')
|
|
208
208
|
.map((s) => s.trim())
|
|
209
209
|
.filter(Boolean)
|
|
210
|
-
// `mcp__server` / `mcp__server__*` mean "every tool on that server"
|
|
211
|
-
// Without expansion these exact-match
|
|
212
|
-
// whole server silently receives no
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
const
|
|
210
|
+
// `mcp__server` / `mcp__server__*` mean "every tool on that server", and
|
|
211
|
+
// `mcp__*` means every MCP tool. Without expansion these exact-match
|
|
212
|
+
// nothing, so an agent that asks for a whole server silently receives no
|
|
213
|
+
// tools at all.
|
|
214
|
+
const serverPrefix = (r: string): string | null =>
|
|
215
|
+
r === 'mcp__*' ? 'mcp__' : mcpServerPrefix(r)
|
|
216
|
+
const serverPrefixes = allowRules.map(serverPrefix).filter((p): p is string => p !== null)
|
|
217
|
+
const allowSet = new Set(allowRules.filter((r) => serverPrefix(r) === null))
|
|
217
218
|
allowedTools = allowedTools.filter(
|
|
218
219
|
(t) => allowSet.has(t.name) || serverPrefixes.some((p) => t.name.startsWith(p)),
|
|
219
220
|
)
|
|
@@ -225,13 +226,19 @@ export function selectAgentTools(
|
|
|
225
226
|
}
|
|
226
227
|
|
|
227
228
|
if (agentDef.disallowedTools) {
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
229
|
+
// The deny side needs the same server expansion as the allow side. With
|
|
230
|
+
// exact matching, `disallowedTools: mcp__server` denied nothing — the agent
|
|
231
|
+
// kept every tool on the server it was told to avoid (CC 2.1.178-021).
|
|
232
|
+
const denyRules = agentDef.disallowedTools
|
|
233
|
+
.split(',')
|
|
234
|
+
.map((s) => s.trim())
|
|
235
|
+
.filter(Boolean)
|
|
236
|
+
const denyPrefix = (r: string): string | null => (r === 'mcp__*' ? 'mcp__' : mcpServerPrefix(r))
|
|
237
|
+
const denySet = new Set(denyRules.filter((r) => denyPrefix(r) === null))
|
|
238
|
+
const denyPrefixes = denyRules.map(denyPrefix).filter((p): p is string => p !== null)
|
|
239
|
+
allowedTools = allowedTools.filter(
|
|
240
|
+
(t) => !denySet.has(t.name) && !denyPrefixes.some((p) => t.name.startsWith(p)),
|
|
233
241
|
)
|
|
234
|
-
allowedTools = allowedTools.filter((t) => !denySet.has(t.name))
|
|
235
242
|
}
|
|
236
243
|
|
|
237
244
|
return allowedTools
|
|
@@ -95,6 +95,11 @@ export class BackgroundAgentRegistry {
|
|
|
95
95
|
executor: (signal: AbortSignal, id: string) => Promise<string>,
|
|
96
96
|
kind: BackgroundTaskKind = 'interactive',
|
|
97
97
|
): string {
|
|
98
|
+
// Completed tasks keep their full result string forever unless something
|
|
99
|
+
// calls `prune()`, and nothing did — a long session with many subagents
|
|
100
|
+
// grew without bound (CC 2.1.50-016 / -023 / -008). Each spawn is a
|
|
101
|
+
// natural, bounded moment to drop finished tasks older than the TTL.
|
|
102
|
+
this.prune()
|
|
98
103
|
const id = `bg-${++this.idCounter}-${Date.now().toString(36)}`
|
|
99
104
|
const now = new Date()
|
|
100
105
|
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -516,6 +516,9 @@ export class SubAgent {
|
|
|
516
516
|
// synchronous (see `resolveRunInBackground`). Set on the shared literal so it
|
|
517
517
|
// covers the synchronous *and* background runs — both go through here.
|
|
518
518
|
isSubAgent: true,
|
|
519
|
+
// One level deeper than the caller. The Agent tool refuses past
|
|
520
|
+
// MAX_AGENT_DEPTH; without the increment every nested call reads as 0.
|
|
521
|
+
agentDepth: (options.toolContext?.agentDepth ?? 0) + 1,
|
|
519
522
|
// Tools that keep per-session state (the Task list) must file it under the
|
|
520
523
|
// session this work belongs to, not under the literal 'sub-agent' — that
|
|
521
524
|
// one bucket is shared by every nested call from every session.
|
|
@@ -870,11 +873,16 @@ export class SubAgent {
|
|
|
870
873
|
// `fix`) is how the model learns the call went through under a
|
|
871
874
|
// caution. The engine prepends them to a successful result; without
|
|
872
875
|
// the same line here the warnings were produced and dropped.
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
876
|
+
// On failure the warning goes into `error` — the field a failed
|
|
877
|
+
// result is actually projected from (same fix as the main engine,
|
|
878
|
+
// CC 2.1.110-027).
|
|
879
|
+
if (gateWarnings.length > 0) {
|
|
880
|
+
const warning = gateWarnings.join('\n')
|
|
881
|
+
displayResult = displayResult.success
|
|
882
|
+
? { ...displayResult, content: warning + '\n' + (displayResult.content || '') }
|
|
883
|
+
: displayResult.error
|
|
884
|
+
? { ...displayResult, error: warning + '\n' + displayResult.error }
|
|
885
|
+
: { ...displayResult, content: warning + '\n' + (displayResult.content || '') }
|
|
878
886
|
}
|
|
879
887
|
|
|
880
888
|
currentMessages.push({
|
package/src/core/engine.ts
CHANGED
|
@@ -1657,9 +1657,20 @@ export class QueryEngine {
|
|
|
1657
1657
|
// permit a merge. Recorded on the one funnel every tool call passes.
|
|
1658
1658
|
noteToolOutcome(reviewLedger, this.sessionId, name, effectiveParams, result.success)
|
|
1659
1659
|
|
|
1660
|
-
// Prepend
|
|
1661
|
-
|
|
1662
|
-
|
|
1660
|
+
// Prepend PreToolUse `additionalContext` to the result — on failure too.
|
|
1661
|
+
// It used to ride only on success, so a hook that warned "this command is
|
|
1662
|
+
// about to fail because X" lost its warning at exactly the moment the
|
|
1663
|
+
// command failed (CC 2.1.110-027). A failed result is projected as
|
|
1664
|
+
// `error || content`, so the warning goes where it is actually read.
|
|
1665
|
+
if (hookWarnings.length > 0) {
|
|
1666
|
+
const warning = hookWarnings.join('\n')
|
|
1667
|
+
if (result.success) {
|
|
1668
|
+
result.content = warning + '\n' + (result.content || '')
|
|
1669
|
+
} else if (result.error) {
|
|
1670
|
+
result.error = warning + '\n' + result.error
|
|
1671
|
+
} else {
|
|
1672
|
+
result.content = warning + '\n' + (result.content || '')
|
|
1673
|
+
}
|
|
1663
1674
|
}
|
|
1664
1675
|
|
|
1665
1676
|
// Run PostToolUse hooks
|
package/src/core/git-pr.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { exec } from 'node:child_process'
|
|
1
|
+
import { exec, execFileSync } from 'node:child_process'
|
|
2
2
|
|
|
3
3
|
export interface GitPr {
|
|
4
4
|
number: number
|
|
@@ -39,6 +39,22 @@ export function prColor(pr: GitPr): PrColor {
|
|
|
39
39
|
return 'white'
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
/** The current branch of `cwd`, or null when it is not a git repo / detached HEAD.
|
|
43
|
+
* Read on demand rather than once at mount: `/cd` changes the directory, and a
|
|
44
|
+
* cached branch then describes the previous repository (CC 2.1.176-012). */
|
|
45
|
+
export function readGitBranch(cwd: string = process.cwd()): string | null {
|
|
46
|
+
try {
|
|
47
|
+
const branch = execFileSync('git', ['branch', '--show-current'], {
|
|
48
|
+
cwd,
|
|
49
|
+
encoding: 'utf-8',
|
|
50
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
51
|
+
}).trim()
|
|
52
|
+
return branch || null
|
|
53
|
+
} catch {
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
42
58
|
/** Detect the PR whose head is `branch`. gh unavailable / no PR / non-zero exit → null.
|
|
43
59
|
* Async so the status line never blocks startup. */
|
|
44
60
|
export function resolveGitPr(branch: string): Promise<GitPr | null> {
|
package/src/core/hooks-config.ts
CHANGED
|
@@ -67,6 +67,15 @@ export function loadHookConfigs(configs: SettingsHooks): HookDefinition[] {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
for (const entry of entries) {
|
|
70
|
+
// A group with no `hooks` array used to throw at `for … of entry.hooks`
|
|
71
|
+
// and take *every* hook with it — one malformed group disabled the entire
|
|
72
|
+
// wiring (CC 2.1.122-017). Skip that group, keep the rest.
|
|
73
|
+
if (!entry || typeof entry !== 'object' || !Array.isArray(entry.hooks)) {
|
|
74
|
+
process.stderr.write(
|
|
75
|
+
`⚠️ Hook group on ${eventName} has no "hooks" array — skipped; other hooks still load.\n`,
|
|
76
|
+
)
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
70
79
|
// A matcher is only a *filter*, so a malformed one must not take the whole
|
|
71
80
|
// hook set down with it. `new RegExp` throws here, and both callers register
|
|
72
81
|
// the result in a plain `for…of` (`index.tsx:742`,
|
|
@@ -202,7 +202,7 @@ export const CLASSIFIER_RULES: ClassifierRule[] = [
|
|
|
202
202
|
{
|
|
203
203
|
tier: 'soft',
|
|
204
204
|
name: 'Irreversible Local Destruction',
|
|
205
|
-
text: 'deleting or overwriting work that cannot be recovered: `rm -rf`, `git reset --hard`, `git clean -f`, `git checkout .`, truncating a file, dropping a table or bucket. Uncommitted work counts as at risk.',
|
|
205
|
+
text: 'deleting or overwriting work that cannot be recovered: `rm -rf`, `git reset --hard`, `git clean -f`, `git checkout .`, `git stash drop`, `git commit --amend` (on a commit this session did not make), `terraform destroy` / `pulumi destroy` / `cdk destroy` (unless the user named that stack), truncating a file, dropping a table or bucket. Uncommitted work counts as at risk.',
|
|
206
206
|
},
|
|
207
207
|
{
|
|
208
208
|
tier: 'soft',
|
|
@@ -107,6 +107,12 @@ const PREFIX_COMMANDS = new Set([
|
|
|
107
107
|
'xargs',
|
|
108
108
|
'eval',
|
|
109
109
|
'stdbuf',
|
|
110
|
+
// Schedulers/session leaders: they run the command that follows. Without
|
|
111
|
+
// these, `watch rm -rf x` / `setsid rm -rf x` / `ionice -c3 rm -rf x` ran
|
|
112
|
+
// past a deny rule that named `rm` (CC 2.1.113-015).
|
|
113
|
+
'watch',
|
|
114
|
+
'setsid',
|
|
115
|
+
'ionice',
|
|
110
116
|
])
|
|
111
117
|
|
|
112
118
|
/** `timeout` 的 duration 形态:`5` / `0.5` / `30s` / `2m` / `1h` / `1d`。 */
|
|
@@ -572,7 +578,7 @@ export interface CommandSegmentGroup {
|
|
|
572
578
|
*/
|
|
573
579
|
export function flattenCommandGroups(command: string, depth = 0): CommandSegmentGroup[] {
|
|
574
580
|
const groups: CommandSegmentGroup[] = []
|
|
575
|
-
for (const seg of
|
|
581
|
+
for (const seg of splitSegmentsForMatching(joinLineContinuations(command))) {
|
|
576
582
|
const variants: string[] = [seg]
|
|
577
583
|
// The shell removes quotes before running the command, so `rm "-rf" /tmp`
|
|
578
584
|
// *is* `rm -rf /tmp` — but the rule text is written without quotes, so the
|
|
@@ -657,6 +663,135 @@ export function joinLineContinuations(command: string): string {
|
|
|
657
663
|
return out
|
|
658
664
|
}
|
|
659
665
|
|
|
666
|
+
/** Commands whose heredoc body is itself shell code, not data. */
|
|
667
|
+
const SHELL_INTERPRETERS = new Set([
|
|
668
|
+
'bash',
|
|
669
|
+
'sh',
|
|
670
|
+
'zsh',
|
|
671
|
+
'ksh',
|
|
672
|
+
'dash',
|
|
673
|
+
'fish',
|
|
674
|
+
'eval',
|
|
675
|
+
'source',
|
|
676
|
+
'.',
|
|
677
|
+
])
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Heredoc delimiters declared on one line (`cat <<EOF`, `cat <<-'EOF'`).
|
|
681
|
+
*
|
|
682
|
+
* Scanned with quote state rather than a bare regex: `echo "a << b"` mentions a
|
|
683
|
+
* heredoc without opening one, and a regex would take `b` for the delimiter.
|
|
684
|
+
*/
|
|
685
|
+
function heredocSpecs(line: string): Array<{ delim: string; stripTabs: boolean }> {
|
|
686
|
+
const specs: Array<{ delim: string; stripTabs: boolean }> = []
|
|
687
|
+
let quote: "'" | '"' | null = null
|
|
688
|
+
for (let i = 0; i < line.length; i++) {
|
|
689
|
+
const ch = line[i]!
|
|
690
|
+
if (quote) {
|
|
691
|
+
if (ch === '\\' && quote === '"') i += 1
|
|
692
|
+
else if (ch === quote) quote = null
|
|
693
|
+
continue
|
|
694
|
+
}
|
|
695
|
+
if (ch === "'" || ch === '"') {
|
|
696
|
+
quote = ch
|
|
697
|
+
continue
|
|
698
|
+
}
|
|
699
|
+
if (ch === '\\') {
|
|
700
|
+
i += 1
|
|
701
|
+
continue
|
|
702
|
+
}
|
|
703
|
+
// `<<<` is a here-string, not a heredoc.
|
|
704
|
+
if (ch !== '<' || line[i + 1] !== '<' || line[i + 2] === '<') continue
|
|
705
|
+
let j = i + 2
|
|
706
|
+
let stripTabs = false
|
|
707
|
+
if (line[j] === '-') {
|
|
708
|
+
stripTabs = true
|
|
709
|
+
j += 1
|
|
710
|
+
}
|
|
711
|
+
while (line[j] === ' ' || line[j] === '\t') j += 1
|
|
712
|
+
let delimQuote: string | null = null
|
|
713
|
+
if (line[j] === "'" || line[j] === '"') {
|
|
714
|
+
delimQuote = line[j]!
|
|
715
|
+
j += 1
|
|
716
|
+
}
|
|
717
|
+
const start = j
|
|
718
|
+
while (j < line.length) {
|
|
719
|
+
const c = line[j]!
|
|
720
|
+
if (delimQuote) {
|
|
721
|
+
if (c === delimQuote) break
|
|
722
|
+
j += 1
|
|
723
|
+
} else if (/[A-Za-z0-9_]/.test(c)) j += 1
|
|
724
|
+
else break
|
|
725
|
+
}
|
|
726
|
+
const delim = line.slice(start, j)
|
|
727
|
+
if (delim) {
|
|
728
|
+
specs.push({ delim, stripTabs })
|
|
729
|
+
i = j
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return specs
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* Split a command for **permission matching**, keeping a heredoc body attached
|
|
737
|
+
* to the command that reads it.
|
|
738
|
+
*
|
|
739
|
+
* `splitShellSegments` splits on every newline, so `cat <<EOF\nhello\nEOF`
|
|
740
|
+
* became three segments and an allow rule `Bash(cat:*)` required `hello` to
|
|
741
|
+
* match it too — the rule that names the command never matched its most common
|
|
742
|
+
* form (same class as the no-argument case in `wildcardMatch`). The body of a
|
|
743
|
+
* heredoc is data the command consumes, not another command.
|
|
744
|
+
*
|
|
745
|
+
* The exception is a heredoc that feeds a shell interpreter (`bash <<EOF …`):
|
|
746
|
+
* that body *is* shell code, and folding it into the parent segment would hide
|
|
747
|
+
* `rm -rf /` from a deny rule. Those keep the plain line split, i.e. today's
|
|
748
|
+
* conservative behaviour.
|
|
749
|
+
*/
|
|
750
|
+
export function splitSegmentsForMatching(command: string): string[] {
|
|
751
|
+
const lines = command.split(/\r?\n/)
|
|
752
|
+
// A heredoc that feeds a shell interpreter keeps the plain split for the
|
|
753
|
+
// whole command: its body is executable and must stay visible to deny rules.
|
|
754
|
+
const feedsShell = (line: string): boolean => {
|
|
755
|
+
if (heredocSpecs(line).length === 0) return false
|
|
756
|
+
const base = (effectiveCommand(line.split(/\s+/).filter(Boolean)).base || '').split('/').pop()
|
|
757
|
+
return !!base && SHELL_INTERPRETERS.has(base)
|
|
758
|
+
}
|
|
759
|
+
if (lines.some(feedsShell)) return splitShellSegments(command)
|
|
760
|
+
|
|
761
|
+
const out: string[] = []
|
|
762
|
+
// Heredoc-declaring segments still waiting for their body lines. The body
|
|
763
|
+
// belongs to the segment that declared it — `cat <<EOF && rm -rf /` runs `rm`
|
|
764
|
+
// *after* cat, so that half must stay its own segment.
|
|
765
|
+
const pending: Array<{ lines: string[]; delims: Array<{ delim: string; stripTabs: boolean }> }> =
|
|
766
|
+
[]
|
|
767
|
+
for (const line of lines) {
|
|
768
|
+
if (pending.length > 0) {
|
|
769
|
+
const head = pending[0]!
|
|
770
|
+
head.lines.push(line)
|
|
771
|
+
const spec = head.delims[0]!
|
|
772
|
+
const candidate = spec.stripTabs ? line.replace(/^\t+/, '') : line
|
|
773
|
+
if (candidate === spec.delim) {
|
|
774
|
+
head.delims.shift()
|
|
775
|
+
if (head.delims.length === 0) {
|
|
776
|
+
out.push(head.lines.join('\n').trim())
|
|
777
|
+
pending.shift()
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
continue
|
|
781
|
+
}
|
|
782
|
+
for (const part of line.split(/&&|\|\||;|\||&/)) {
|
|
783
|
+
const seg = part.trim()
|
|
784
|
+
if (!seg) continue
|
|
785
|
+
const specs = heredocSpecs(seg)
|
|
786
|
+
if (specs.length > 0) pending.push({ lines: [seg], delims: specs })
|
|
787
|
+
else out.push(seg)
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
// An unterminated heredoc still has to be judged: keep what was read.
|
|
791
|
+
for (const p of pending) out.push(p.lines.join('\n').trim())
|
|
792
|
+
return out.filter((s) => s.length > 0)
|
|
793
|
+
}
|
|
794
|
+
|
|
660
795
|
/** git global options that consume the next token. */
|
|
661
796
|
const GIT_GLOBAL_WITH_ARG = new Set([
|
|
662
797
|
'-C',
|
|
@@ -1261,8 +1396,10 @@ export function matchBashRule(
|
|
|
1261
1396
|
*/
|
|
1262
1397
|
function embedsForeignCommand(segment: string): boolean {
|
|
1263
1398
|
return (
|
|
1264
|
-
// find(1): -exec / -execdir / -ok / -okdir take a command
|
|
1265
|
-
|
|
1399
|
+
// find(1): -exec / -execdir / -ok / -okdir take a command; -delete removes
|
|
1400
|
+
// files outright. `Bash(find:*)` granted `find . -name '*.log' -delete` —
|
|
1401
|
+
// a deletion the rule never named (CC 2.1.113-016).
|
|
1402
|
+
/\s-(?:exec|execdir|ok|okdir|delete)(?:\s|$)/.test(segment) ||
|
|
1266
1403
|
// git(1) / tar(1): options that name a program to run.
|
|
1267
1404
|
/--(?:upload-pack|receive-pack|exec-path|to-command|checkpoint-action)(?:=|\s)/.test(segment) ||
|
|
1268
1405
|
// git(1) `-c core.pager=…`-style config that ends in an executed command.
|
|
@@ -1272,16 +1409,57 @@ function embedsForeignCommand(segment: string): boolean {
|
|
|
1272
1409
|
)
|
|
1273
1410
|
}
|
|
1274
1411
|
|
|
1412
|
+
/**
|
|
1413
|
+
* Match one rule pattern against a command, **without a regex**.
|
|
1414
|
+
*
|
|
1415
|
+
* The pattern used to be compiled to a regex with every `*` becoming `.*`.
|
|
1416
|
+
* Nested wildcards (`git:*a*a*a*a*a*b`) then backtracked exponentially: a
|
|
1417
|
+
* 200-character argument held the permission prompt at 100 % CPU for minutes —
|
|
1418
|
+
* a freeze reachable from the command line the rule was supposed to guard
|
|
1419
|
+
* (CC 2.1.73-003). This is the classic two-pointer wildcard match: `*` may
|
|
1420
|
+
* match any run (newlines included), `?` exactly one character, and `:` one
|
|
1421
|
+
* colon or whitespace. It is O(pattern × input) with no backtracking tree.
|
|
1422
|
+
*
|
|
1423
|
+
* A trailing `:*` also matches the **no-argument** form: `Bash(ls:*)` grants
|
|
1424
|
+
* `ls` itself, not only `ls -la`.
|
|
1425
|
+
*/
|
|
1275
1426
|
export function wildcardMatch(pattern: string, input: string): boolean {
|
|
1276
|
-
const
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
'
|
|
1284
|
-
|
|
1427
|
+
const chars = Array.from(pattern)
|
|
1428
|
+
const subject = Array.from(input)
|
|
1429
|
+
let p = 0
|
|
1430
|
+
let s = 0
|
|
1431
|
+
let star = -1
|
|
1432
|
+
let mark = 0
|
|
1433
|
+
while (s < subject.length) {
|
|
1434
|
+
if (p < chars.length && chars[p] === '*') {
|
|
1435
|
+
star = p
|
|
1436
|
+
mark = s
|
|
1437
|
+
p += 1
|
|
1438
|
+
continue
|
|
1439
|
+
}
|
|
1440
|
+
if (p < chars.length && tokenMatches(chars[p]!, subject[s]!)) {
|
|
1441
|
+
p += 1
|
|
1442
|
+
s += 1
|
|
1443
|
+
continue
|
|
1444
|
+
}
|
|
1445
|
+
if (star !== -1) {
|
|
1446
|
+
// Extend the last `*` by one and retry from just after it.
|
|
1447
|
+
p = star + 1
|
|
1448
|
+
mark += 1
|
|
1449
|
+
s = mark
|
|
1450
|
+
continue
|
|
1451
|
+
}
|
|
1452
|
+
return false
|
|
1453
|
+
}
|
|
1454
|
+
// `foo:*` also matches a bare `foo`: a separator at the very end is optional.
|
|
1455
|
+
while (p < chars.length && (chars[p] === '*' || chars[p] === ':')) p += 1
|
|
1456
|
+
return p === chars.length
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
function tokenMatches(patternChar: string, inputChar: string): boolean {
|
|
1460
|
+
if (patternChar === '?') return true
|
|
1461
|
+
if (patternChar === ':') return inputChar === ':' || /\s/.test(inputChar)
|
|
1462
|
+
return patternChar === inputChar
|
|
1285
1463
|
}
|
|
1286
1464
|
|
|
1287
1465
|
/**
|
package/src/core/permission.ts
CHANGED
|
@@ -663,6 +663,13 @@ export class PermissionSystem {
|
|
|
663
663
|
// 3. Check allow rules — but an org ceiling still applies (see allowRuleDecision)
|
|
664
664
|
for (const rule of this.allowRules) {
|
|
665
665
|
if (!this.ruleMatches(rule, tool, input)) continue
|
|
666
|
+
// A file *write* is the one thing plan mode exists to forbid: with
|
|
667
|
+
// `Edit(src/**)` allowed, plan mode wrote files — the rule sat ahead of
|
|
668
|
+
// the mode baseline and the mode never got a say (CC 2.1.136-008).
|
|
669
|
+
// Scoped to file-mutating tools so an allow rule still grants exactly
|
|
670
|
+
// what it did in every other category (the pinned tests for `allow('Bash')`
|
|
671
|
+
// and bare-name validity rely on that).
|
|
672
|
+
if (this.mode === 'plan' && tool.category === 'file' && !isReadOnlyTool(tool)) continue
|
|
666
673
|
// In `auto`, a rule that names no program does not stand in for the safety
|
|
667
674
|
// classifier. An allow rule sits *ahead* of the mode baseline, so
|
|
668
675
|
// `allow: ["Bash(*)"]` would otherwise make the one mode that examines
|
package/src/mcp/oauth.ts
CHANGED
|
@@ -256,10 +256,27 @@ export class OAuthClient {
|
|
|
256
256
|
const fresh = await this.executePkceFlow(config)
|
|
257
257
|
return fresh.accessToken
|
|
258
258
|
}
|
|
259
|
-
|
|
260
|
-
access_token
|
|
259
|
+
let data: {
|
|
260
|
+
access_token?: unknown
|
|
261
261
|
refresh_token?: string
|
|
262
262
|
expires_in?: number
|
|
263
|
+
error?: unknown
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
data = (await response.json()) as typeof data
|
|
267
|
+
} catch {
|
|
268
|
+
// A non-JSON body on a 2xx is not a token either.
|
|
269
|
+
data = {}
|
|
270
|
+
}
|
|
271
|
+
// Some providers (Slack is the documented one) answer a dead refresh token
|
|
272
|
+
// with HTTP 200 and `{"error":"invalid_grant"}`. Checking `response.ok`
|
|
273
|
+
// alone saved that object as a token, and every later call failed until the
|
|
274
|
+
// user cleared credentials by hand (CC 2.1.74-007). A refresh is only
|
|
275
|
+
// successful if it actually returned an access token.
|
|
276
|
+
if (typeof data.access_token !== 'string' || data.access_token === '') {
|
|
277
|
+
this.store.delete(serverName)
|
|
278
|
+
const fresh = await this.executePkceFlow(config)
|
|
279
|
+
return fresh.accessToken
|
|
263
280
|
}
|
|
264
281
|
this.store.save(serverName, {
|
|
265
282
|
accessToken: data.access_token,
|
package/src/mcp/protocol.ts
CHANGED
|
@@ -29,6 +29,9 @@ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as Translat
|
|
|
29
29
|
*/
|
|
30
30
|
export const MCP_SUPPORTED_VERSIONS: readonly string[] = ['2024-11-05']
|
|
31
31
|
|
|
32
|
+
/** Upper bound on paged list reads, so a server that always returns a cursor cannot loop forever. */
|
|
33
|
+
const MAX_LIST_PAGES = 100
|
|
34
|
+
|
|
32
35
|
/**
|
|
33
36
|
* The revision to offer in `initialize`.
|
|
34
37
|
*
|
|
@@ -130,16 +133,39 @@ export class McpProtocol {
|
|
|
130
133
|
return result
|
|
131
134
|
}
|
|
132
135
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
+
/**
|
|
137
|
+
* Read every page of a paged MCP list method.
|
|
138
|
+
*
|
|
139
|
+
* Servers cap a page (commonly 100 entries) and return `nextCursor` for the
|
|
140
|
+
* rest. Sending a single request and dropping the cursor silently hid every
|
|
141
|
+
* tool past page 1 — the server looked healthy and half its tools did not
|
|
142
|
+
* exist (CC 2.1.144-019). The page cap only bounds a server that keeps
|
|
143
|
+
* answering with a fresh cursor; it does not change normal pagination.
|
|
144
|
+
*/
|
|
145
|
+
private async listAllPages<T>(method: string, key: string): Promise<T[]> {
|
|
146
|
+
const out: T[] = []
|
|
147
|
+
let cursor: string | undefined
|
|
148
|
+
for (let page = 0; page < MAX_LIST_PAGES; page++) {
|
|
149
|
+
const result = (await this.transport.sendRequest(
|
|
150
|
+
method,
|
|
151
|
+
cursor ? { cursor } : undefined,
|
|
152
|
+
)) as Record<string, unknown> | null
|
|
153
|
+
const items = result?.[key]
|
|
154
|
+
if (Array.isArray(items)) out.push(...(items as T[]))
|
|
155
|
+
const next = result?.nextCursor
|
|
156
|
+
if (typeof next !== 'string' || next === '' || next === cursor) break
|
|
157
|
+
cursor = next
|
|
136
158
|
}
|
|
159
|
+
return out
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async listTools(): Promise<ToolDefinition[]> {
|
|
163
|
+
const tools = await this.listAllPages<ToolDefinition>('tools/list', 'tools')
|
|
137
164
|
// A server (or the host embedding it) may put a `null` or a nameless entry
|
|
138
165
|
// in `tools`. That shape used to reach `connection.tools.map(t => t.name)`,
|
|
139
166
|
// throw a TypeError from a background async, and — with our crash handler
|
|
140
167
|
// installed — take the whole CLI down over one malformed server. Drop
|
|
141
168
|
// entries that cannot be addressed instead of trusting the payload.
|
|
142
|
-
const tools = Array.isArray(result?.tools) ? result.tools : []
|
|
143
169
|
return tools.filter(
|
|
144
170
|
(tool): tool is ToolDefinition =>
|
|
145
171
|
!!tool &&
|
|
@@ -169,10 +195,7 @@ export class McpProtocol {
|
|
|
169
195
|
if (!this.serverCapabilities.resources) {
|
|
170
196
|
return []
|
|
171
197
|
}
|
|
172
|
-
|
|
173
|
-
resources: ResourceDefinition[]
|
|
174
|
-
}
|
|
175
|
-
return result.resources || []
|
|
198
|
+
return this.listAllPages<ResourceDefinition>('resources/list', 'resources')
|
|
176
199
|
}
|
|
177
200
|
|
|
178
201
|
async readResource(uri: string): Promise<ResourceReadResult> {
|
package/src/mcp/transport.ts
CHANGED
|
@@ -165,6 +165,10 @@ const SENSITIVE_ENV_PATTERNS = [
|
|
|
165
165
|
/^GCLOUD_/, // GCP credentials
|
|
166
166
|
/^AZURE_/, // Azure credentials
|
|
167
167
|
/^DOCKER_/, // DOCKER_TOKEN, DOCKER_PASSWORD
|
|
168
|
+
// OTLP endpoint headers carry an ingestion token, and the endpoint itself is
|
|
169
|
+
// the operator's telemetry destination. A subprocess inheriting `OTEL_*`
|
|
170
|
+
// exports its own spans to it (CC 2.1.128-006).
|
|
171
|
+
/^OTEL_/,
|
|
168
172
|
]
|
|
169
173
|
|
|
170
174
|
/**
|
|
@@ -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.46' 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 = 5228 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -706,6 +706,15 @@ export interface ToolContext {
|
|
|
706
706
|
* consume a background handle, so its default flips to synchronous.
|
|
707
707
|
*/
|
|
708
708
|
isSubAgent?: boolean
|
|
709
|
+
/**
|
|
710
|
+
* How many `Agent` calls deep this tool context is (main loop = 0 / absent).
|
|
711
|
+
*
|
|
712
|
+
* A sub-agent's tool set includes `Agent`, so nesting is reachable from the
|
|
713
|
+
* model. The Agent tool refuses past `MAX_AGENT_DEPTH`; this field is what it
|
|
714
|
+
* counts. Incremented by `SubAgent.runExecution` when it builds its children's
|
|
715
|
+
* context, so a foreground chain is bounded exactly like a background one.
|
|
716
|
+
*/
|
|
717
|
+
agentDepth?: number
|
|
709
718
|
/**
|
|
710
719
|
* The session a sub-agent is running on behalf of.
|
|
711
720
|
*
|
package/src/skills/loader.ts
CHANGED
|
@@ -20,10 +20,49 @@ export function parseFrontmatter(raw: string): FrontmatterResult {
|
|
|
20
20
|
if (!match) {
|
|
21
21
|
return { data: {}, content: src }
|
|
22
22
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
// A plain scalar containing ": " (`description: Fix: a bug`) is invalid YAML:
|
|
24
|
+
// the parser sees a second mapping colon. Strict parsing threw, the per-file
|
|
25
|
+
// catch swallowed it, and the skill disappeared with no message. Frontmatter
|
|
26
|
+
// is hand-written, so recover the top-level scalar keys line by line instead
|
|
27
|
+
// of losing the whole file.
|
|
28
|
+
let data: Record<string, unknown>
|
|
29
|
+
try {
|
|
30
|
+
const parsed = parseYaml(match[1] || '')
|
|
31
|
+
data =
|
|
32
|
+
parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
33
|
+
? (parsed as Record<string, unknown>)
|
|
34
|
+
: {}
|
|
35
|
+
} catch {
|
|
36
|
+
data = parseLooseFrontmatter(match[1] || '')
|
|
26
37
|
}
|
|
38
|
+
return { data, content: match[2] || '' }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Last-resort reader for frontmatter that strict YAML rejects.
|
|
43
|
+
*
|
|
44
|
+
* Only top-level `key: scalar` pairs are recovered — nested maps and block
|
|
45
|
+
* lists are lost. That is already better than dropping the skill, and it is
|
|
46
|
+
* limited to files that would otherwise fail entirely.
|
|
47
|
+
*/
|
|
48
|
+
function parseLooseFrontmatter(text: string): Record<string, unknown> {
|
|
49
|
+
const out: Record<string, unknown> = {}
|
|
50
|
+
for (const line of text.split('\n')) {
|
|
51
|
+
const m = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/)
|
|
52
|
+
if (!m) continue
|
|
53
|
+
let value = m[2]!.trim()
|
|
54
|
+
if (!value) continue
|
|
55
|
+
// Block scalars / flow collections are not recoverable this way.
|
|
56
|
+
if (/^[|>[{&*!]/.test(value)) continue
|
|
57
|
+
if (
|
|
58
|
+
(value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
|
|
59
|
+
(value.startsWith("'") && value.endsWith("'") && value.length >= 2)
|
|
60
|
+
) {
|
|
61
|
+
value = value.slice(1, -1)
|
|
62
|
+
}
|
|
63
|
+
out[m[1]!] = value
|
|
64
|
+
}
|
|
65
|
+
return out
|
|
27
66
|
}
|
|
28
67
|
|
|
29
68
|
/**
|
|
@@ -195,7 +234,30 @@ export class SkillsLoader implements Skills {
|
|
|
195
234
|
try {
|
|
196
235
|
const { data, content } = parseFrontmatter(raw)
|
|
197
236
|
|
|
198
|
-
|
|
237
|
+
// `description: [a, b]` (a YAML list) is a legal frontmatter value but not
|
|
238
|
+
// a string. Casting it and letting `sanitizeSkillDescription` call
|
|
239
|
+
// `.replace` on it threw inside the per-file try/catch, which swallowed the
|
|
240
|
+
// error — the skill vanished with no message. Only a string counts; say so
|
|
241
|
+
// instead of dropping it silently.
|
|
242
|
+
// `description: 3000` is a bare number; coerce it rather than dropping what
|
|
243
|
+
// the author wrote (CC 2.1.47-028). A list/object cannot be a description.
|
|
244
|
+
const descriptionValue = data.description
|
|
245
|
+
const rawDescription =
|
|
246
|
+
typeof descriptionValue === 'string'
|
|
247
|
+
? descriptionValue
|
|
248
|
+
: typeof descriptionValue === 'number' || typeof descriptionValue === 'boolean'
|
|
249
|
+
? String(descriptionValue)
|
|
250
|
+
: ''
|
|
251
|
+
if (
|
|
252
|
+
descriptionValue !== undefined &&
|
|
253
|
+
typeof descriptionValue !== 'string' &&
|
|
254
|
+
typeof descriptionValue !== 'number' &&
|
|
255
|
+
typeof descriptionValue !== 'boolean'
|
|
256
|
+
) {
|
|
257
|
+
process.stderr.write(
|
|
258
|
+
`⚠️ Skill at ${sourceName}: frontmatter description is not a string — ignored.\n`,
|
|
259
|
+
)
|
|
260
|
+
}
|
|
199
261
|
const rawBody = content.trim() || undefined
|
|
200
262
|
|
|
201
263
|
// Name gate (see `invalidSkillNameReason`). A declared name that fails is
|
|
@@ -282,8 +344,14 @@ export class SkillsLoader implements Skills {
|
|
|
282
344
|
}
|
|
283
345
|
this.skills.set(skill.name, skill)
|
|
284
346
|
this.sources.set(skill.name, sourceName)
|
|
285
|
-
} catch {
|
|
286
|
-
//
|
|
347
|
+
} catch (err) {
|
|
348
|
+
// Never drop a skill silently: to the user a skill that vanished and a
|
|
349
|
+
// skill that was never installed look identical, and the frontmatter is
|
|
350
|
+
// hand-written (CC 2.1.69-068 / 2.1.47-028).
|
|
351
|
+
const detail = err instanceof Error ? err.message : String(err)
|
|
352
|
+
process.stderr.write(
|
|
353
|
+
`⚠️ Skill at ${sourceName}: could not be loaded — skipped (${detail.split('\n')[0]})\n`,
|
|
354
|
+
)
|
|
287
355
|
}
|
|
288
356
|
}
|
|
289
357
|
|
package/src/tools/agent/agent.ts
CHANGED
|
@@ -24,6 +24,9 @@ const VALID_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
|
|
|
24
24
|
* honoured, in both directions: that is a request, not a default chosen on the
|
|
25
25
|
* caller's behalf.
|
|
26
26
|
*/
|
|
27
|
+
/** Deepest nesting of `Agent` calls (CC parity: 5). */
|
|
28
|
+
export const MAX_AGENT_DEPTH = 5
|
|
29
|
+
|
|
27
30
|
export function resolveRunInBackground(
|
|
28
31
|
runInBackground: boolean | undefined,
|
|
29
32
|
agentDef?: { background?: boolean },
|
|
@@ -85,6 +88,21 @@ export const agentTool: ToolDefinition = {
|
|
|
85
88
|
const prompt = params.prompt as string
|
|
86
89
|
const agentType = (params.subagent_type as SubAgentType) || 'general'
|
|
87
90
|
|
|
91
|
+
// A sub-agent's tool set includes `Agent`, so a model can nest calls. Without
|
|
92
|
+
// a depth bound one run could spawn children that spawn children until the
|
|
93
|
+
// token budget or the process dies (CC 2.1.181-019). Background sub-agents
|
|
94
|
+
// already had a limit; this applies the same one to foreground runs.
|
|
95
|
+
const depth = ctx.agentDepth ?? 0
|
|
96
|
+
if (depth >= MAX_AGENT_DEPTH) {
|
|
97
|
+
return {
|
|
98
|
+
success: false,
|
|
99
|
+
content: '',
|
|
100
|
+
error:
|
|
101
|
+
`Sub-agent nesting limit reached (${MAX_AGENT_DEPTH} levels). ` +
|
|
102
|
+
"Finish this level's work directly instead of spawning another agent.",
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
88
106
|
if (!VALID_TYPES.includes(agentType)) {
|
|
89
107
|
return {
|
|
90
108
|
success: false,
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -757,6 +757,64 @@ function changeDirectoryTargets(words: string[], depth = 0): string[] {
|
|
|
757
757
|
return out
|
|
758
758
|
}
|
|
759
759
|
|
|
760
|
+
/** Commands whose exit code 1 means "answered, found nothing" — not failure. */
|
|
761
|
+
const NO_MATCH_READERS = new Set(['grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack'])
|
|
762
|
+
/** Commands whose exit code 1 means "the files differ" — not failure. */
|
|
763
|
+
const NO_DIFF_COMMANDS = new Set(['diff', 'cmp'])
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Resolve the base command of the first shell segment, skipping leading
|
|
767
|
+
* assignments, wrappers and their options.
|
|
768
|
+
*/
|
|
769
|
+
function firstCommandWords(command: string): string[] {
|
|
770
|
+
const seg = splitShellSegments(command).find((s) => s.trim().length > 0)
|
|
771
|
+
if (!seg) return []
|
|
772
|
+
const words = seg.trim().split(/\s+/)
|
|
773
|
+
let i = 0
|
|
774
|
+
while (
|
|
775
|
+
i < words.length &&
|
|
776
|
+
(/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]!) ||
|
|
777
|
+
['sudo', 'doas', 'env', 'command', 'exec', 'time', 'nice', 'nohup'].includes(words[i]!))
|
|
778
|
+
) {
|
|
779
|
+
i += 1
|
|
780
|
+
}
|
|
781
|
+
while (i < words.length && words[i]!.startsWith('-')) i += 1
|
|
782
|
+
return words.slice(i)
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* Does exit code 1 from this command mean "no matches / no differences"?
|
|
787
|
+
*
|
|
788
|
+
* `grep` answered the question and found nothing; `git diff` found no change.
|
|
789
|
+
* Reporting those as command failures made the model retry a search that had
|
|
790
|
+
* already succeeded, and taught it to read exit 1 as breakage. The detection is
|
|
791
|
+
* deliberately narrow: the command must be a known reader/differ, the exit code
|
|
792
|
+
* exactly 1, and stderr empty (a real error — unreadable file, bad regex — also
|
|
793
|
+
* exits non-zero but writes a diagnostic).
|
|
794
|
+
*
|
|
795
|
+
* Returns the note to attach, or null when this is an ordinary failure.
|
|
796
|
+
*/
|
|
797
|
+
export function noMatchExitNote(command: string, exitCode: number, stderr: string): string | null {
|
|
798
|
+
if (exitCode !== 1 || stderr.trim() !== '') return null
|
|
799
|
+
const words = firstCommandWords(command)
|
|
800
|
+
const base = (words[0] || '').split('/').pop()
|
|
801
|
+
if (!base) return null
|
|
802
|
+
if (NO_MATCH_READERS.has(base)) return 'no matches found'
|
|
803
|
+
if (NO_DIFF_COMMANDS.has(base)) return 'no differences found'
|
|
804
|
+
if (base === 'git') {
|
|
805
|
+
let j = 1
|
|
806
|
+
while (j < words.length && words[j]!.startsWith('-')) {
|
|
807
|
+
const opt = words[j]!
|
|
808
|
+
j += 1
|
|
809
|
+
if (['-C', '-c', '--git-dir', '--work-tree'].includes(opt) && j < words.length) j += 1
|
|
810
|
+
}
|
|
811
|
+
const sub = (words[j] || '').split('/').pop()
|
|
812
|
+
if (sub === 'grep') return 'no matches found'
|
|
813
|
+
if (sub === 'diff') return 'no differences found'
|
|
814
|
+
}
|
|
815
|
+
return null
|
|
816
|
+
}
|
|
817
|
+
|
|
760
818
|
export function createBashTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
|
|
761
819
|
return {
|
|
762
820
|
name: 'Bash',
|
|
@@ -938,7 +996,11 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
938
996
|
? (await import('../../core/credential-masker')).maskOutput(rawStderr, credentialConfig)
|
|
939
997
|
: rawStderr
|
|
940
998
|
|
|
941
|
-
|
|
999
|
+
// `grep`/`git diff` exit 1 when they answered and found nothing. That is
|
|
1000
|
+
// a result, not a failure (CC 2.1.144-012).
|
|
1001
|
+
const noMatchNote = aborted || timedOut ? null : noMatchExitNote(command, exitCode, stderr)
|
|
1002
|
+
|
|
1003
|
+
if (exitCode !== 0 && !noMatchNote) {
|
|
942
1004
|
let errorContent = output.slice(0, 5_000)
|
|
943
1005
|
if (violations.length > 0) {
|
|
944
1006
|
errorContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
|
|
@@ -994,6 +1056,9 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
994
1056
|
(successContent.length > 0 ? '\n\n' : '') + '── stderr ──\n' + stderrText
|
|
995
1057
|
}
|
|
996
1058
|
if (successContent.length === 0) successContent = '(no output)'
|
|
1059
|
+
if (noMatchNote) {
|
|
1060
|
+
successContent += `\n\n[exit code 1: ${noMatchNote} — not a failure]`
|
|
1061
|
+
}
|
|
997
1062
|
if (violations.length > 0) {
|
|
998
1063
|
successContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
|
|
999
1064
|
}
|
package/src/tools/exec/git.ts
CHANGED
|
@@ -382,6 +382,17 @@ export function createGitTool(
|
|
|
382
382
|
|
|
383
383
|
if (exitCode !== 0) {
|
|
384
384
|
const stderr = await new Response(proc.stderr).text()
|
|
385
|
+
// `git diff` exits 1 when the trees differ and `git grep` exits 1 when
|
|
386
|
+
// nothing matched. Both answered the question; neither is a failure
|
|
387
|
+
// (CC 2.1.144-012). A real error also exits non-zero but writes a
|
|
388
|
+
// diagnostic to stderr, so that half stays on the error path.
|
|
389
|
+
const sub = argv[subcommandIndex(argv)]
|
|
390
|
+
if (exitCode === 1 && stderr.trim() === '' && (sub === 'diff' || sub === 'grep')) {
|
|
391
|
+
return {
|
|
392
|
+
success: true,
|
|
393
|
+
content: (await scrub(output)).slice(0, 50_000) || '(no output)',
|
|
394
|
+
}
|
|
395
|
+
}
|
|
385
396
|
return {
|
|
386
397
|
success: false,
|
|
387
398
|
content: '',
|
package/src/tools/file/edit.ts
CHANGED
|
@@ -120,13 +120,26 @@ export const editTool: ToolDefinition = {
|
|
|
120
120
|
// O_NONBLOCK only got us past the *open*. It does not bound the read:
|
|
121
121
|
// `/dev/zero` yields bytes forever (OOM) and a FIFO yields whatever a
|
|
122
122
|
// writer chooses to send. Refuse on file type, not on size.
|
|
123
|
-
|
|
123
|
+
const stat = fstatSync(rfd)
|
|
124
|
+
if (!stat.isFile()) {
|
|
124
125
|
return {
|
|
125
126
|
success: false,
|
|
126
127
|
content: '',
|
|
127
128
|
error: `Path is not a regular file (FIFO, socket or device): ${filePath}`,
|
|
128
129
|
}
|
|
129
130
|
}
|
|
131
|
+
// Bound the read *before* it happens. The 10 MB check below runs on
|
|
132
|
+
// `content.length` — by then the whole file is already in memory, so a
|
|
133
|
+
// multi-GB file OOMs the process before the guard can speak. 4 is the
|
|
134
|
+
// UTF-8 bytes-per-code-unit ceiling, so `size > 4 × MAX` guarantees the
|
|
135
|
+
// post-read character check would have refused it anyway.
|
|
136
|
+
if (stat.size > MAX_FILE_SIZE * 4) {
|
|
137
|
+
return {
|
|
138
|
+
success: false,
|
|
139
|
+
content: '',
|
|
140
|
+
error: `File too large (${(stat.size / 1e6).toFixed(1)} MB). Max: 10 MB.`,
|
|
141
|
+
}
|
|
142
|
+
}
|
|
130
143
|
const raw = readFileSync(rfd)
|
|
131
144
|
if (!isValidUtf8(raw)) {
|
|
132
145
|
return {
|
package/src/tools/file/glob.ts
CHANGED
|
@@ -28,6 +28,16 @@ const GLOB_IGNORE_BATCH = 500
|
|
|
28
28
|
* Filtering is a convenience; silently returning *nothing* because git could
|
|
29
29
|
* not answer would be indistinguishable from "no matches".
|
|
30
30
|
*/
|
|
31
|
+
/**
|
|
32
|
+
* Jujutsu (`.jj`) and Sapling (`.sl`) keep repository metadata in those
|
|
33
|
+
* directories — the equivalent of `.git`. ripgrep and `Bun.Glob` only know the
|
|
34
|
+
* older VCS names, so without this a search descends into a second copy of the
|
|
35
|
+
* worktree (CC 2.1.86-002).
|
|
36
|
+
*/
|
|
37
|
+
export function isVcsMetadataPath(path: string): boolean {
|
|
38
|
+
return path.split(/[\\/]/).some((segment) => segment === '.jj' || segment === '.sl')
|
|
39
|
+
}
|
|
40
|
+
|
|
31
41
|
export function filterGitIgnored(paths: string[], cwd: string): string[] {
|
|
32
42
|
if (paths.length === 0) return paths
|
|
33
43
|
const ignored = new Set<string>()
|
|
@@ -71,7 +81,8 @@ export function createGlobTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
71
81
|
// 却仍报「截断到 500」;反过来先过滤再数,截断标记描述的才是真实结果集。
|
|
72
82
|
const keep = (batch: string[]) => {
|
|
73
83
|
if (batch.length === 0) return
|
|
74
|
-
|
|
84
|
+
const visible = batch.filter((p) => !isVcsMetadataPath(p))
|
|
85
|
+
for (const p of filterGitIgnored(visible, basePath)) results.push(p)
|
|
75
86
|
}
|
|
76
87
|
for await (const file of glob.scan({ cwd: basePath, absolute: true })) {
|
|
77
88
|
pending.push(file)
|
package/src/tools/file/grep.ts
CHANGED
|
@@ -173,7 +173,23 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
173
173
|
}
|
|
174
174
|
|
|
175
175
|
// 1. ripgrep (fast path)
|
|
176
|
-
|
|
176
|
+
// `.jj`/`.sl` are Jujutsu/Sapling metadata; ripgrep only ignores `.git`,
|
|
177
|
+
// `.hg`, `.svn` and `.bzr` by default, so a search would descend into the
|
|
178
|
+
// other VCS's copy of the worktree (CC 2.1.86-002). First, so an explicit
|
|
179
|
+
// `include` can still name them.
|
|
180
|
+
const rgArgs = [
|
|
181
|
+
'rg',
|
|
182
|
+
'-n',
|
|
183
|
+
'--heading',
|
|
184
|
+
'--color=never',
|
|
185
|
+
'-M',
|
|
186
|
+
'500',
|
|
187
|
+
'--glob',
|
|
188
|
+
'!.jj',
|
|
189
|
+
'--glob',
|
|
190
|
+
'!.sl',
|
|
191
|
+
pattern,
|
|
192
|
+
]
|
|
177
193
|
if (include) rgArgs.push('--glob', include)
|
|
178
194
|
rgArgs.push(searchPath)
|
|
179
195
|
try {
|
|
@@ -58,8 +58,15 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
58
58
|
required: [],
|
|
59
59
|
},
|
|
60
60
|
async execute(params, ctx) {
|
|
61
|
-
const
|
|
62
|
-
|
|
61
|
+
const rawQuery = ((params.query as string) || '').toLowerCase()
|
|
62
|
+
// A caller often pastes the *fully qualified* name it saw in a tool listing
|
|
63
|
+
// (`mcp__server__tool`). Matching that whole string against the bare tool
|
|
64
|
+
// name found nothing, and the fallback description matcher surfaced
|
|
65
|
+
// unrelated siblings — the tool that was named did not appear at all
|
|
66
|
+
// (CC 2.1.113-031). Split it back into server + tool name.
|
|
67
|
+
const qualified = /^mcp__(.+?)__(.+)$/.exec(rawQuery)
|
|
68
|
+
const query = qualified ? qualified[2]!.replace(/\*+$/, '') : rawQuery
|
|
69
|
+
const serverFilter = (params.server as string) || (qualified ? qualified[1]! : '')
|
|
63
70
|
const limit = (params.limit as number) || 20
|
|
64
71
|
|
|
65
72
|
const client = McpClient.getInstance()
|
|
@@ -95,6 +102,8 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
95
102
|
server: string
|
|
96
103
|
tool: string
|
|
97
104
|
description: string
|
|
105
|
+
/** Exact name > name prefix > name substring > description only. */
|
|
106
|
+
score: number
|
|
98
107
|
}
|
|
99
108
|
|
|
100
109
|
const matches: Match[] = []
|
|
@@ -103,13 +112,24 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
103
112
|
try {
|
|
104
113
|
const tools = client.getTools(serverName)
|
|
105
114
|
for (const tool of tools) {
|
|
106
|
-
const
|
|
107
|
-
const
|
|
108
|
-
|
|
115
|
+
const name = tool.name.toLowerCase()
|
|
116
|
+
const score = !query
|
|
117
|
+
? 1
|
|
118
|
+
: name === query
|
|
119
|
+
? 4
|
|
120
|
+
: name.startsWith(query)
|
|
121
|
+
? 3
|
|
122
|
+
: name.includes(query)
|
|
123
|
+
? 2
|
|
124
|
+
: (tool.description || '').toLowerCase().includes(query)
|
|
125
|
+
? 1
|
|
126
|
+
: 0
|
|
127
|
+
if (score > 0) {
|
|
109
128
|
matches.push({
|
|
110
129
|
server: serverName,
|
|
111
130
|
tool: tool.name,
|
|
112
131
|
description: capMcpText(tool.description || ''),
|
|
132
|
+
score,
|
|
113
133
|
})
|
|
114
134
|
}
|
|
115
135
|
}
|
|
@@ -118,6 +138,10 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
118
138
|
}
|
|
119
139
|
}
|
|
120
140
|
|
|
141
|
+
// The name the caller typed must come first; description-only siblings are
|
|
142
|
+
// the noise that buried it.
|
|
143
|
+
matches.sort((a, b) => b.score - a.score || a.tool.localeCompare(b.tool))
|
|
144
|
+
|
|
121
145
|
if (matches.length === 0) {
|
|
122
146
|
// A zero-hit answer is the wrong answer when the name the caller searched
|
|
123
147
|
// for is a *built-in* tool: nothing is missing, it was never an MCP tool.
|
package/src/tools/validation.ts
CHANGED
|
@@ -11,6 +11,39 @@ const bundles: Record<string, TranslationMap> = {
|
|
|
11
11
|
}
|
|
12
12
|
const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as TranslationMap)
|
|
13
13
|
|
|
14
|
+
/**
|
|
15
|
+
* Coerce scalars the model sent as strings into the type the schema declares.
|
|
16
|
+
*
|
|
17
|
+
* Models occasionally emit `"true"` for a boolean, or `" 5 "` / `"+5"` for a
|
|
18
|
+
* numeric `offset`/`limit`. Type-checking those verbatim rejected an otherwise
|
|
19
|
+
* well-formed call ("expected boolean, received string"), so the model spent a
|
|
20
|
+
* turn re-typing a value it had already supplied. Only the exact spellings that
|
|
21
|
+
* cannot mean anything else are converted; everything else is left for
|
|
22
|
+
* `validateParams` to refuse.
|
|
23
|
+
*/
|
|
24
|
+
function coerceScalars(
|
|
25
|
+
schema: Record<string, unknown>,
|
|
26
|
+
params: Record<string, unknown>,
|
|
27
|
+
): Record<string, unknown> {
|
|
28
|
+
const properties = schema.properties as Record<string, { type: string }> | undefined
|
|
29
|
+
if (!properties) return params
|
|
30
|
+
const out = { ...params }
|
|
31
|
+
for (const [key, def] of Object.entries(properties)) {
|
|
32
|
+
const value = out[key]
|
|
33
|
+
if (typeof value !== 'string') continue
|
|
34
|
+
const trimmed = value.trim()
|
|
35
|
+
if (def.type === 'boolean') {
|
|
36
|
+
if (trimmed === 'true') out[key] = true
|
|
37
|
+
else if (trimmed === 'false') out[key] = false
|
|
38
|
+
} else if (def.type === 'integer') {
|
|
39
|
+
if (/^[+-]?\d+$/.test(trimmed)) out[key] = Number(trimmed)
|
|
40
|
+
} else if (def.type === 'number') {
|
|
41
|
+
if (/^[+-]?\d+(?:\.\d+)?$/.test(trimmed)) out[key] = Number(trimmed)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return out
|
|
45
|
+
}
|
|
46
|
+
|
|
14
47
|
/**
|
|
15
48
|
* Validate tool parameters against the tool's JSON Schema definition.
|
|
16
49
|
* Returns an array of error messages (empty = valid).
|
|
@@ -87,7 +120,7 @@ export function withValidation(tool: ToolDefinition): ToolDefinition {
|
|
|
87
120
|
}
|
|
88
121
|
}
|
|
89
122
|
|
|
90
|
-
const cleanParams = sanitizeParams(params)
|
|
123
|
+
const cleanParams = coerceScalars(schema, sanitizeParams(params))
|
|
91
124
|
const errors = validateParams(schema, cleanParams)
|
|
92
125
|
if (errors.length > 0) {
|
|
93
126
|
return {
|
package/src/ui/app.tsx
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import React, { useState, useCallback, useEffect, useRef, useMemo } from 'react'
|
|
2
2
|
import { Box, Text, useInput } from 'ink'
|
|
3
3
|
import TextInput from 'ink-text-input'
|
|
4
|
-
import { execSync } from 'node:child_process'
|
|
5
4
|
import { ErrorBoundary } from './error-boundary'
|
|
6
5
|
import { useCtrlCConfirm } from './ctrl-c-confirm'
|
|
7
6
|
import { formatThinking } from './thinking'
|
|
@@ -11,7 +10,7 @@ import type { MiphamConfig } from '../shared/index.ts'
|
|
|
11
10
|
import type { Llm } from '../providers/llm'
|
|
12
11
|
import { AUTOCOMPLETE_MAX_CONTEXT, type RecentMessage } from '../core/autocomplete'
|
|
13
12
|
import { MODE_CYCLE } from '../core/permission-config'
|
|
14
|
-
import { resolveGitPr, prColor, type GitPr } from '../core/git-pr'
|
|
13
|
+
import { readGitBranch, resolveGitPr, prColor, type GitPr } from '../core/git-pr'
|
|
15
14
|
import type { SkillsLoader } from '../skills/loader'
|
|
16
15
|
import type { PluginManager } from '../plugin/plugin-manager'
|
|
17
16
|
import { setPreference } from '../config/preferences'
|
|
@@ -388,21 +387,10 @@ export function App({
|
|
|
388
387
|
// InputBar is unmounted by the picker / API-key prompt / agent view.
|
|
389
388
|
const [inputDraft, setInputDraft] = useState('')
|
|
390
389
|
const [updateStatus, setUpdateStatus] = useState<UpdateStatus | null>(null)
|
|
391
|
-
// Current git branch
|
|
392
|
-
//
|
|
393
|
-
//
|
|
394
|
-
|
|
395
|
-
const [gitBranch] = useState<string | null>(() => {
|
|
396
|
-
try {
|
|
397
|
-
const b = execSync('git branch --show-current', {
|
|
398
|
-
encoding: 'utf-8',
|
|
399
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
400
|
-
}).trim()
|
|
401
|
-
return b || null
|
|
402
|
-
} catch {
|
|
403
|
-
return null
|
|
404
|
-
}
|
|
405
|
-
})
|
|
390
|
+
// Current git branch. Read on demand rather than frozen at mount: `/cd`
|
|
391
|
+
// moves the session into another repository and the footer used to keep
|
|
392
|
+
// naming the previous one's branch (CC 2.1.176-012).
|
|
393
|
+
const [gitBranch, setGitBranch] = useState<string | null>(() => readGitBranch())
|
|
406
394
|
// Current branch's PR (head = branch) — async detect; gh unavailable / no PR → null.
|
|
407
395
|
const [gitPr, setGitPr] = useState<GitPr | null>(null)
|
|
408
396
|
useEffect(() => {
|
|
@@ -599,6 +587,7 @@ export function App({
|
|
|
599
587
|
version: version || '0.0.0',
|
|
600
588
|
sessionId: sessionId || '',
|
|
601
589
|
setSessionTitle: (title: string) => setSessionTitle(title),
|
|
590
|
+
setGitBranch: (branch: string | null) => setGitBranch(branch),
|
|
602
591
|
setEffort: (level: string) => {
|
|
603
592
|
setEffort(level)
|
|
604
593
|
setPreference('lastCodeReviewEffort', level)
|
package/src/ui/commands.ts
CHANGED
|
@@ -159,6 +159,8 @@ export interface CommandContext {
|
|
|
159
159
|
sessionId: string
|
|
160
160
|
// Callbacks for commands that mutate App state
|
|
161
161
|
setSessionTitle: (title: string) => void
|
|
162
|
+
/** Refresh the footer's git branch after the session moves directory (`/cd`). */
|
|
163
|
+
setGitBranch?: (branch: string | null) => void
|
|
162
164
|
setEffort: (level: string) => void
|
|
163
165
|
setFocusMode: (on: boolean) => void
|
|
164
166
|
/** Current focus-view state — `/focus` toggles from this, not from `true`. */
|
|
@@ -4883,6 +4885,10 @@ const cdCmd: CommandHandler = async (ctx, args) => {
|
|
|
4883
4885
|
|
|
4884
4886
|
try {
|
|
4885
4887
|
process.chdir(resolved)
|
|
4888
|
+
// The branch badge describes the session's directory, not the one it was
|
|
4889
|
+
// opened in; refresh it or `/cd` leaves the previous repository's branch
|
|
4890
|
+
// on screen (CC 2.1.176-012).
|
|
4891
|
+
ctx.setGitBranch?.((await import('../core/git-pr')).readGitBranch())
|
|
4886
4892
|
|
|
4887
4893
|
// `/cd` 只搬了 cwd,而**按目录装载的闸门**分两半:
|
|
4888
4894
|
// • 能在这里重放的 —— `.mipham/rules/*.md` 与 settings.json 的 permission 规则;
|
|
@@ -5445,7 +5451,16 @@ const resumeCmd: CommandHandler = async (ctx, args) => {
|
|
|
5445
5451
|
}
|
|
5446
5452
|
}
|
|
5447
5453
|
|
|
5448
|
-
|
|
5454
|
+
// The running session is on disk too (events are appended as they happen), so
|
|
5455
|
+
// listing every file offered the conversation the user is already in — and
|
|
5456
|
+
// resuming it is a no-op that looks like a broken restore (CC 2.1.73-008).
|
|
5457
|
+
// The live name comes from the log, which `/rename` updates.
|
|
5458
|
+
const { sanitizeSessionName } = await import('../core/session-log')
|
|
5459
|
+
const currentName = ctx.engine.getContext().getLog?.()?.getName() ?? ctx.sessionId
|
|
5460
|
+
const sessions = SessionStore.list().filter(
|
|
5461
|
+
(s) =>
|
|
5462
|
+
s.name !== currentName && sanitizeSessionName(s.name) !== sanitizeSessionName(currentName),
|
|
5463
|
+
)
|
|
5449
5464
|
|
|
5450
5465
|
if (sessions.length === 0) {
|
|
5451
5466
|
return {
|