@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
package/src/mcp/registry.ts
CHANGED
|
@@ -39,8 +39,14 @@ function sanitizeName(name: string): string {
|
|
|
39
39
|
/**
|
|
40
40
|
* Build a namespaced MCP tool name.
|
|
41
41
|
* Format: mcp__<sanitizedServerName>__<sanitizedToolName>
|
|
42
|
+
*
|
|
43
|
+
* Exported because every surface that *names* an MCP tool must use this
|
|
44
|
+
* spelling: the registered name is what the model has to call, and a display
|
|
45
|
+
* path that builds its own (`tool-search`) handed back names that did not
|
|
46
|
+
* exist for any server or tool with an uppercase or non-alphanumeric
|
|
47
|
+
* character in its name.
|
|
42
48
|
*/
|
|
43
|
-
function buildToolName(serverName: string, toolName: string): string {
|
|
49
|
+
export function buildToolName(serverName: string, toolName: string): string {
|
|
44
50
|
const base = `${MCP_TOOL_PREFIX}${sanitizeName(serverName)}__${sanitizeName(toolName)}`
|
|
45
51
|
if (base.length <= MAX_NAME_LENGTH) return base
|
|
46
52
|
const prefix = `${MCP_TOOL_PREFIX}${sanitizeName(serverName)}__`
|
|
@@ -216,7 +222,7 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
|
|
|
216
222
|
ctx.signal,
|
|
217
223
|
)
|
|
218
224
|
|
|
219
|
-
const text = result.content
|
|
225
|
+
const text = (result.content ?? [])
|
|
220
226
|
.map((c) => {
|
|
221
227
|
if (c.type === 'text' && c.text) return c.text
|
|
222
228
|
if (c.type === 'image') return `[Image: ${c.mimeType || 'unknown'}]`
|
|
@@ -224,10 +230,18 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
|
|
|
224
230
|
})
|
|
225
231
|
.join('\n')
|
|
226
232
|
|
|
233
|
+
// A server may answer only in `structuredContent` (MCP 2025-06). Dropping
|
|
234
|
+
// it turned a real payload into "(empty result)" — indistinguishable from
|
|
235
|
+
// a tool that genuinely returned nothing.
|
|
236
|
+
const structured =
|
|
237
|
+
text === '' && result.structuredContent !== undefined
|
|
238
|
+
? JSON.stringify(result.structuredContent, null, 2)
|
|
239
|
+
: ''
|
|
240
|
+
|
|
227
241
|
return {
|
|
228
242
|
success: !result.isError,
|
|
229
|
-
content: text || '(empty result)',
|
|
230
|
-
error: result.isError ? text : undefined,
|
|
243
|
+
content: text || structured || '(empty result)',
|
|
244
|
+
error: result.isError ? text || structured : undefined,
|
|
231
245
|
}
|
|
232
246
|
},
|
|
233
247
|
}
|
package/src/mcp/transport.ts
CHANGED
|
@@ -348,6 +348,21 @@ export class StdioTransport implements Transport {
|
|
|
348
348
|
this.notificationHandlers.push(handler)
|
|
349
349
|
}
|
|
350
350
|
|
|
351
|
+
/**
|
|
352
|
+
* Synchronous teardown for `process.on('exit')`, where nothing can be
|
|
353
|
+
* awaited and no grace period can run. Kills the process tree now: a server
|
|
354
|
+
* that does not read stdin EOF otherwise outlives the CLI (the shape Claude
|
|
355
|
+
* Code fixed twice: 1.0.21.003 and 1.0.36).
|
|
356
|
+
*/
|
|
357
|
+
closeSync(): void {
|
|
358
|
+
this.closed = true
|
|
359
|
+
const proc = this.proc
|
|
360
|
+
this.proc = null
|
|
361
|
+
if (proc && proc.exitCode === null && proc.signalCode === null) {
|
|
362
|
+
killProcessTree(proc)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
351
366
|
async close(): Promise<void> {
|
|
352
367
|
this.closed = true
|
|
353
368
|
|
package/src/mcp/types.ts
CHANGED
|
@@ -83,6 +83,12 @@ export interface ToolCallContent {
|
|
|
83
83
|
|
|
84
84
|
export interface ToolCallResult {
|
|
85
85
|
content: ToolCallContent[]
|
|
86
|
+
/**
|
|
87
|
+
* MCP 2025-06 `structuredContent`: a machine-readable payload some servers
|
|
88
|
+
* return *instead of* (or alongside) text blocks. Ignoring it made such a
|
|
89
|
+
* server look like it answered nothing at all.
|
|
90
|
+
*/
|
|
91
|
+
structuredContent?: unknown
|
|
86
92
|
isError?: boolean
|
|
87
93
|
}
|
|
88
94
|
|
|
@@ -121,6 +121,12 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
121
121
|
// off at the output ceiling rather than ended by the model.
|
|
122
122
|
let truncated = false
|
|
123
123
|
|
|
124
|
+
// Why it was cut. `'max_tokens'` is recoverable (ask the model to continue);
|
|
125
|
+
// a stream that ends without `message_stop` is not (re-asking re-writes the
|
|
126
|
+
// fragment). Same terminal stop either way — this is the only distinction the
|
|
127
|
+
// provider can supply, so it has to travel with the chunk.
|
|
128
|
+
let truncationCause: 'max_tokens' | 'connection' | undefined
|
|
129
|
+
|
|
124
130
|
// Set when the provider reports `stop_reason: 'refusal'`. A refusal is a
|
|
125
131
|
// **successful** response (HTTP 200) that declines to answer, and it may carry
|
|
126
132
|
// an empty content array — so without this the turn ends as a blank screen,
|
|
@@ -142,6 +148,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
142
148
|
const terminalStop = (): StreamChunk => ({
|
|
143
149
|
type: 'stop',
|
|
144
150
|
...(truncated ? { truncated: true } : {}),
|
|
151
|
+
...(truncationCause ? { truncationCause } : {}),
|
|
145
152
|
...(refusal ? { refusal } : {}),
|
|
146
153
|
})
|
|
147
154
|
|
|
@@ -376,6 +383,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
376
383
|
const stopReason = event.delta?.stop_reason
|
|
377
384
|
if (stopReason === 'max_tokens') {
|
|
378
385
|
truncated = true
|
|
386
|
+
truncationCause = 'max_tokens'
|
|
379
387
|
}
|
|
380
388
|
// A refusal is a successful response that declines to answer, and
|
|
381
389
|
// it can arrive with no content at all. Capture the provider's own
|
|
@@ -414,7 +422,12 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
414
422
|
// The stream ran out without `message_stop`. Whatever stopped it, the turn is
|
|
415
423
|
// incomplete — and this is the only place that knows, because a cleanly
|
|
416
424
|
// closed connection and a finished response are otherwise the same stream.
|
|
417
|
-
if (!sawTerminalEvent)
|
|
425
|
+
if (!sawTerminalEvent) {
|
|
426
|
+
truncated = true
|
|
427
|
+
// A `max_tokens` stop seen earlier is the real cause; only an otherwise
|
|
428
|
+
// ordinary stream that just dies is a connection cut.
|
|
429
|
+
truncationCause ??= 'connection'
|
|
430
|
+
}
|
|
418
431
|
|
|
419
432
|
yield terminalStop()
|
|
420
433
|
} finally {
|
|
@@ -34,5 +34,18 @@ export function bootstrapProviders(
|
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
// Resolve a tier alias (`haiku` / `sonnet` / `opus`) to the concrete model id
|
|
38
|
+
// **before** anything reads the active model.
|
|
39
|
+
//
|
|
40
|
+
// `findModel` already resolves these against the active provider, but it was
|
|
41
|
+
// only consulted when sizing the context window: the registry kept the raw
|
|
42
|
+
// string, so `--model haiku` sent the literal id "haiku" to the provider and
|
|
43
|
+
// matched no row in the model picker. Doing it here gives the CLI, the daemon
|
|
44
|
+
// and the bin entry the same answer from one place.
|
|
45
|
+
const resolved = registry.findModel(defaultModel)
|
|
46
|
+
if (resolved && resolved.id !== defaultModel) {
|
|
47
|
+
registry.switchProvider(defaultProvider, resolved.id)
|
|
48
|
+
}
|
|
49
|
+
|
|
37
50
|
return registry
|
|
38
51
|
}
|
|
@@ -266,7 +266,12 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
266
266
|
// their JSON is incomplete. Drop them rather than dispatching a broken
|
|
267
267
|
// call, and clear the map so the `[DONE]` handler can't emit them either.
|
|
268
268
|
pendingToolCalls.clear()
|
|
269
|
-
yield {
|
|
269
|
+
yield {
|
|
270
|
+
type: 'stop',
|
|
271
|
+
reasoning_content: reasoningContent,
|
|
272
|
+
truncated: true,
|
|
273
|
+
truncationCause: 'max_tokens',
|
|
274
|
+
}
|
|
270
275
|
}
|
|
271
276
|
} catch {
|
|
272
277
|
// skip unparseable chunks
|
|
@@ -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.44' as const
|
|
13
13
|
|
|
14
14
|
/** npm install 全局安装命令 */
|
|
15
15
|
export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
|
|
@@ -75,7 +75,7 @@ export const COMPANY_SHORT = '华安麦逄科技' as const
|
|
|
75
75
|
*/
|
|
76
76
|
|
|
77
77
|
/** Slash 命令总数(真源:`getCommandNames().length`,`apps/cli/src/ui/commands.ts`) */
|
|
78
|
-
export const SLASH_COMMAND_COUNT =
|
|
78
|
+
export const SLASH_COMMAND_COUNT = 140 as const
|
|
79
79
|
|
|
80
80
|
/** 内置提供商总数(真源:`DEFAULT_PROVIDERS.length`,`apps/cli/src/shared/constants.ts`) */
|
|
81
81
|
export const PROVIDER_COUNT = 12 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 = 5171 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -179,6 +179,15 @@ export interface StreamChunk {
|
|
|
179
179
|
* either way, and tool calls cut off mid-arguments are dropped silently.
|
|
180
180
|
*/
|
|
181
181
|
truncated?: boolean
|
|
182
|
+
/**
|
|
183
|
+
* Why the turn was cut, when the provider can tell.
|
|
184
|
+
*
|
|
185
|
+
* `'max_tokens'` means the model hit its output ceiling — there is more to say
|
|
186
|
+
* and asking it to continue is meaningful. `'connection'` (or absent) means the
|
|
187
|
+
* stream died; continuing would re-ask the model to write the same fragment
|
|
188
|
+
* again, so the engine must not auto-continue on it.
|
|
189
|
+
*/
|
|
190
|
+
truncationCause?: 'max_tokens' | 'connection'
|
|
182
191
|
/**
|
|
183
192
|
* Set on the `warning` chunk a retried turn emits just before it re-streams
|
|
184
193
|
* (`chatWithFallback`). Everything the failed attempt already yielded is on
|
|
@@ -403,6 +412,15 @@ export interface HookResult {
|
|
|
403
412
|
permissionDecision?: 'allow' | 'deny' | 'ask' | 'defer'
|
|
404
413
|
additionalContext?: string
|
|
405
414
|
updatedOutput?: string
|
|
415
|
+
/**
|
|
416
|
+
* Warning text the hook wants the **user** to see (Claude Code's root-level
|
|
417
|
+
* `systemMessage`). Distinct from `additionalContext`, which goes into the
|
|
418
|
+
* model's prompt. Only events with a live user channel surface it:
|
|
419
|
+
* UserPromptSubmit and Stop yield a warning chunk; SessionStart/SessionEnd
|
|
420
|
+
* write it to stderr before/at exit. A hook that emits it on an event with
|
|
421
|
+
* no such channel is not silently reinterpreted as model context.
|
|
422
|
+
*/
|
|
423
|
+
systemMessage?: string
|
|
406
424
|
}
|
|
407
425
|
|
|
408
426
|
// ── Instruction Types ──
|
package/src/skills/loader.ts
CHANGED
|
@@ -332,6 +332,36 @@ export class SkillsLoader implements Skills {
|
|
|
332
332
|
this.loadExternal([userSkillsPath])
|
|
333
333
|
}
|
|
334
334
|
|
|
335
|
+
/**
|
|
336
|
+
* Load skills from `<base>/.mipham/skills/` — the project scope.
|
|
337
|
+
*
|
|
338
|
+
* This path is what the product tells users to use: `/project` ("Create a
|
|
339
|
+
* .SKILL.md file in .mipham/skills/"), the Skill tool's not-found message, and
|
|
340
|
+
* `loop-scaffold` (which creates `.mipham/skills/<domain>/`). Until now nothing
|
|
341
|
+
* scanned it, so a skill written exactly where the instructions said was never
|
|
342
|
+
* loaded and `/reload-skills` reported an unchanged count.
|
|
343
|
+
*
|
|
344
|
+
* One level of subdirectories is scanned on purpose: the scaffold's layout is
|
|
345
|
+
* `<domain>/<name>.SKILL.md`, and the Claude-plugin shape is
|
|
346
|
+
* `<name>/SKILL.md`. Symlinked directories are skipped — following them can
|
|
347
|
+
* loop, and the flat `loadDirectory` deliberately does not recurse for the
|
|
348
|
+
* same reason.
|
|
349
|
+
*/
|
|
350
|
+
loadProjectSkills(basePath: string = process.cwd()): void {
|
|
351
|
+
const projectDir = join(basePath, '.mipham', 'skills')
|
|
352
|
+
if (!existsSync(projectDir)) return
|
|
353
|
+
this.loadDirectory(projectDir, 'standard')
|
|
354
|
+
try {
|
|
355
|
+
for (const entry of readdirSync(projectDir, { withFileTypes: true })) {
|
|
356
|
+
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
357
|
+
this.loadDirectory(join(projectDir, entry.name), 'standard')
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
} catch {
|
|
361
|
+
// Unreadable directory: the flat scan above already ran.
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
335
365
|
private nameFromPath(path: string): string {
|
|
336
366
|
const parts = path.split('/').filter(Boolean)
|
|
337
367
|
const base = parts.pop() ?? ''
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -111,12 +111,11 @@ const BLOCKED_PATTERNS = [
|
|
|
111
111
|
// command as `bash -c 'rm -rf /'`. `ash`, `fish`, `csh` and `tcsh` are added
|
|
112
112
|
// because the payload only has to be a POSIX-ish shell, not bash.
|
|
113
113
|
/\b(?:bash|sh|zsh|dash|ksh|ash|fish|csh|tcsh)\b(?:\s+-{1,2}[\w=.-]+)*\s+-[A-Za-z]*c[A-Za-z]*\b/,
|
|
114
|
-
// P0 hardening — eval builtin (obfuscation vector)
|
|
115
|
-
/\beval\s+/,
|
|
116
114
|
// P0 hardening — exec redirect bypass (e.g. exec >/dev/sda)
|
|
117
115
|
/\bexec\s+\d*>/,
|
|
118
|
-
//
|
|
119
|
-
|
|
116
|
+
// `eval` / `source` are handled by `commandWords()` below, not as substring
|
|
117
|
+
// patterns: the word appearing in an argument is not the builtin running
|
|
118
|
+
// (`git commit -m "source config cleanup"`).
|
|
120
119
|
// P0 hardening — base64 decode + pipe
|
|
121
120
|
/\bbase64\s+(?:-d|--decode)\b/,
|
|
122
121
|
]
|
|
@@ -163,19 +162,18 @@ export function isBlocked(command: string): string | null {
|
|
|
163
162
|
// P0-1: Also sanitize for permission check (strips invisible chars, normalizes homoglyphs)
|
|
164
163
|
const sanitized = sanitizeCommand(command)
|
|
165
164
|
|
|
166
|
-
// Check
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
return `Command "${sanitizedFirstWord}" rejected by security policy.`
|
|
165
|
+
// Check every simple command's base word, not a substring of the line: the
|
|
166
|
+
// word may be a quoted argument (`git commit -m "source config cleanup"`),
|
|
167
|
+
// and a compound command may hide it after a separator (`ok && source x`).
|
|
168
|
+
// Command substitutions are scanned too (`echo "$(eval …)"`).
|
|
169
|
+
for (const word of [
|
|
170
|
+
...commandWords(command),
|
|
171
|
+
...commandWords(normalized),
|
|
172
|
+
...commandWords(sanitized),
|
|
173
|
+
]) {
|
|
174
|
+
if (BLOCKED_COMMANDS.includes(word)) {
|
|
175
|
+
return `Command "${word}" rejected by security policy.`
|
|
176
|
+
}
|
|
179
177
|
}
|
|
180
178
|
|
|
181
179
|
// Detect dangerous git operations invoked via Bash — anywhere in the command,
|
|
@@ -503,6 +501,174 @@ export function shellWords(segment: string): string[] {
|
|
|
503
501
|
return words
|
|
504
502
|
}
|
|
505
503
|
|
|
504
|
+
/**
|
|
505
|
+
* Split a command into simple commands on **unquoted** separators.
|
|
506
|
+
*
|
|
507
|
+
* Deliberately different from `splitShellSegments` (permission-rules), which
|
|
508
|
+
* splits regardless of quoting: over-matching is the safe direction for a
|
|
509
|
+
* *deny* rule, but here it is the bug — `rg 'eval|source'` is one command with
|
|
510
|
+
* a quoted argument, not two commands.
|
|
511
|
+
*/
|
|
512
|
+
function splitUnquotedSegments(command: string): string[] {
|
|
513
|
+
const segments: string[] = []
|
|
514
|
+
let cur = ''
|
|
515
|
+
let quote: '"' | "'" | null = null
|
|
516
|
+
for (let i = 0; i < command.length; i++) {
|
|
517
|
+
const ch = command[i]!
|
|
518
|
+
if (quote === "'") {
|
|
519
|
+
cur += ch
|
|
520
|
+
if (ch === "'") quote = null
|
|
521
|
+
continue
|
|
522
|
+
}
|
|
523
|
+
if (quote === '"') {
|
|
524
|
+
cur += ch
|
|
525
|
+
if (ch === '\\' && i + 1 < command.length) cur += command[++i]
|
|
526
|
+
else if (ch === '"') quote = null
|
|
527
|
+
continue
|
|
528
|
+
}
|
|
529
|
+
if (ch === "'" || ch === '"') {
|
|
530
|
+
quote = ch
|
|
531
|
+
cur += ch
|
|
532
|
+
continue
|
|
533
|
+
}
|
|
534
|
+
if (ch === '\\' && i + 1 < command.length) {
|
|
535
|
+
cur += ch + command[++i]
|
|
536
|
+
continue
|
|
537
|
+
}
|
|
538
|
+
if (
|
|
539
|
+
ch === ';' ||
|
|
540
|
+
ch === '\n' ||
|
|
541
|
+
ch === '\r' ||
|
|
542
|
+
ch === '|' ||
|
|
543
|
+
ch === '&' ||
|
|
544
|
+
ch === '(' ||
|
|
545
|
+
ch === ')'
|
|
546
|
+
) {
|
|
547
|
+
segments.push(cur)
|
|
548
|
+
cur = ''
|
|
549
|
+
if ((ch === '&' || ch === '|') && command[i + 1] === ch) i++
|
|
550
|
+
continue
|
|
551
|
+
}
|
|
552
|
+
cur += ch
|
|
553
|
+
}
|
|
554
|
+
segments.push(cur)
|
|
555
|
+
return segments.map((s) => s.trim()).filter((s) => s.length > 0)
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Bodies of command substitutions — `$(…)`, `` `…` ``, `<(…)` and `>(…)`.
|
|
560
|
+
*
|
|
561
|
+
* They run commands too, and they can sit inside double quotes:
|
|
562
|
+
* `echo "$(eval …)"` executes `eval` even though the outer command word is
|
|
563
|
+
* `echo`. Single-quoted text is skipped because it is literal there.
|
|
564
|
+
* Nested groups are left to the caller's recursion.
|
|
565
|
+
*/
|
|
566
|
+
function substitutionBodies(command: string): string[] {
|
|
567
|
+
const bodies: string[] = []
|
|
568
|
+
for (let i = 0; i < command.length; i++) {
|
|
569
|
+
const ch = command[i]!
|
|
570
|
+
if (ch === '\\') {
|
|
571
|
+
i++
|
|
572
|
+
continue
|
|
573
|
+
}
|
|
574
|
+
if (ch === "'") {
|
|
575
|
+
const end = command.indexOf("'", i + 1)
|
|
576
|
+
if (end === -1) break
|
|
577
|
+
i = end
|
|
578
|
+
continue
|
|
579
|
+
}
|
|
580
|
+
const isDollarParen = ch === '$' && command[i + 1] === '('
|
|
581
|
+
const isProcSub = (ch === '<' || ch === '>') && command[i + 1] === '('
|
|
582
|
+
if (ch === '`') {
|
|
583
|
+
const end = command.indexOf('`', i + 1)
|
|
584
|
+
if (end === -1) break
|
|
585
|
+
bodies.push(command.slice(i + 1, end))
|
|
586
|
+
i = end
|
|
587
|
+
continue
|
|
588
|
+
}
|
|
589
|
+
if (!isDollarParen && !isProcSub) continue
|
|
590
|
+
let depth = 1
|
|
591
|
+
let j = i + 2
|
|
592
|
+
let quote: '"' | "'" | null = null
|
|
593
|
+
for (; j < command.length; j++) {
|
|
594
|
+
const c = command[j]!
|
|
595
|
+
if (c === '\\') {
|
|
596
|
+
j++
|
|
597
|
+
continue
|
|
598
|
+
}
|
|
599
|
+
if (quote === "'") {
|
|
600
|
+
if (c === "'") quote = null
|
|
601
|
+
continue
|
|
602
|
+
}
|
|
603
|
+
if (quote === '"') {
|
|
604
|
+
if (c === '"') quote = null
|
|
605
|
+
continue
|
|
606
|
+
}
|
|
607
|
+
if (c === "'" || c === '"') {
|
|
608
|
+
quote = c
|
|
609
|
+
continue
|
|
610
|
+
}
|
|
611
|
+
if (c === '(') depth++
|
|
612
|
+
else if (c === ')') {
|
|
613
|
+
depth--
|
|
614
|
+
if (depth === 0) break
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
if (j < command.length) {
|
|
618
|
+
bodies.push(command.slice(i + 2, j))
|
|
619
|
+
i = j
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return bodies
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* The base command word of every simple command in `command`, including
|
|
627
|
+
* commands run inside substitutions (recursively, depth-limited).
|
|
628
|
+
*
|
|
629
|
+
* This is what tells a *mention* from an *invocation*: `git commit -m "source
|
|
630
|
+
* config cleanup"` has the command word `git`; `echo ok && source /etc/x` has
|
|
631
|
+
* `echo` and `source`. Prior to this, `eval` / `source` were matched anywhere
|
|
632
|
+
* in the string and refused ordinary commands that merely quoted the words
|
|
633
|
+
* (CC 1.0.73: "reduced false security warnings").
|
|
634
|
+
*/
|
|
635
|
+
export function commandWords(command: string, depth = 0): string[] {
|
|
636
|
+
const words: string[] = []
|
|
637
|
+
for (const segment of splitUnquotedSegments(command)) {
|
|
638
|
+
const tokens = shellWords(segment)
|
|
639
|
+
let i = 0
|
|
640
|
+
for (;;) {
|
|
641
|
+
while (i < tokens.length && LEADING_ASSIGNMENT.test(tokens[i]!)) i++
|
|
642
|
+
const word = tokens[i]
|
|
643
|
+
if (word === undefined) break
|
|
644
|
+
if (LEADING_SHELL_PUNCT.has(word)) {
|
|
645
|
+
i++
|
|
646
|
+
continue
|
|
647
|
+
}
|
|
648
|
+
if (LEADING_SHELL_KEYWORDS.has(word)) {
|
|
649
|
+
i++
|
|
650
|
+
// A keyword's own flags (`time -p eval …`) are not the command word.
|
|
651
|
+
while (i < tokens.length && /^-[A-Za-z]+$/.test(tokens[i]!)) i++
|
|
652
|
+
continue
|
|
653
|
+
}
|
|
654
|
+
if (WRAPPERS.has(word)) {
|
|
655
|
+
i++
|
|
656
|
+
continue
|
|
657
|
+
}
|
|
658
|
+
break
|
|
659
|
+
}
|
|
660
|
+
if (tokens[i] !== undefined) words.push(tokens[i]!)
|
|
661
|
+
}
|
|
662
|
+
// A substitution can nest (`$( … $( … ) … )`); three levels is enough to
|
|
663
|
+
// reach any spelling a guard needs to see, and bounds the recursion.
|
|
664
|
+
if (depth < 3) {
|
|
665
|
+
for (const body of substitutionBodies(command)) {
|
|
666
|
+
words.push(...commandWords(body, depth + 1))
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
return words
|
|
670
|
+
}
|
|
671
|
+
|
|
506
672
|
/**
|
|
507
673
|
* Every directory this simple command changes the shell's cwd to.
|
|
508
674
|
*
|
|
@@ -764,14 +930,15 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
764
930
|
// ── Sandbox violation detection ──
|
|
765
931
|
const violations = detectViolations(rawStderr)
|
|
766
932
|
|
|
933
|
+
// Mask stderr once, for both outcomes. It used to be masked only on the
|
|
934
|
+
// failure path, so a credential echoed to stderr by a command that then
|
|
935
|
+
// exited 0 would reach the model unmasked.
|
|
936
|
+
const stderr =
|
|
937
|
+
credentialConfig?.enabled && credentialConfig.output_scrubbing.enabled
|
|
938
|
+
? (await import('../../core/credential-masker')).maskOutput(rawStderr, credentialConfig)
|
|
939
|
+
: rawStderr
|
|
940
|
+
|
|
767
941
|
if (exitCode !== 0) {
|
|
768
|
-
const stderr =
|
|
769
|
-
credentialConfig?.enabled && credentialConfig.output_scrubbing.enabled
|
|
770
|
-
? (await import('../../core/credential-masker')).maskOutput(
|
|
771
|
-
rawStderr,
|
|
772
|
-
credentialConfig,
|
|
773
|
-
)
|
|
774
|
-
: rawStderr
|
|
775
942
|
let errorContent = output.slice(0, 5_000)
|
|
776
943
|
if (violations.length > 0) {
|
|
777
944
|
errorContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
|
|
@@ -814,7 +981,19 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
814
981
|
return { success: false, content: output.slice(0, 5_000), error: 'Command cancelled' }
|
|
815
982
|
}
|
|
816
983
|
|
|
817
|
-
let successContent = output.slice(0, 100_000)
|
|
984
|
+
let successContent = output.slice(0, 100_000)
|
|
985
|
+
// Exit 0 does not mean stderr was noise: `git clone` progress, package
|
|
986
|
+
// manager peer warnings and deprecation notices all land there, and the
|
|
987
|
+
// tool advertises "Returns stdout and stderr". Dropping it left the
|
|
988
|
+
// model reading a clean success where the warning it needed sat one
|
|
989
|
+
// stream over (CC 1.0.77 stderr handling).
|
|
990
|
+
const stderrText =
|
|
991
|
+
stderr.length > 5_000 ? stderr.slice(0, 5_000) + '\n[stderr truncated]' : stderr
|
|
992
|
+
if (stderrText.trim().length > 0) {
|
|
993
|
+
successContent +=
|
|
994
|
+
(successContent.length > 0 ? '\n\n' : '') + '── stderr ──\n' + stderrText
|
|
995
|
+
}
|
|
996
|
+
if (successContent.length === 0) successContent = '(no output)'
|
|
818
997
|
if (violations.length > 0) {
|
|
819
998
|
successContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
|
|
820
999
|
}
|
package/src/tools/file/glob.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Glob } from 'bun'
|
|
2
|
+
import { spawnSync } from 'node:child_process'
|
|
2
3
|
import type { ToolDefinition, CredentialMaskingConfig } from '../../shared/index.ts'
|
|
3
4
|
import { resolveSafe } from '../../security/path'
|
|
4
5
|
import type { Service } from '../../vajra'
|
|
@@ -10,10 +11,45 @@ import { maskGlobOutput } from '../../core/credential-masker'
|
|
|
10
11
|
* 与 Grep 的 `truncateGrepOutput` 同一约定)。 */
|
|
11
12
|
const GLOB_MAX_RESULTS = 500
|
|
12
13
|
|
|
14
|
+
/** 每批向 `git check-ignore` 询问的路径数(一次进程,摊薄启动成本)。 */
|
|
15
|
+
const GLOB_IGNORE_BATCH = 500
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Drop the paths git would ignore.
|
|
19
|
+
*
|
|
20
|
+
* `Bun.Glob` knows nothing about `.gitignore`, so `Glob **\/*` in a repository
|
|
21
|
+
* returned `node_modules/…` and build output alongside real sources. This asks
|
|
22
|
+
* git itself (`check-ignore --stdin -z`, paths echoed verbatim), so the answer
|
|
23
|
+
* is the repository's own rule set — nested `.gitignore` files, negations,
|
|
24
|
+
* core.excludesFile and all.
|
|
25
|
+
*
|
|
26
|
+
* Fail-open by design: outside a work tree, when git is missing, or when the
|
|
27
|
+
* call errors (status 1 = "nothing ignored", 128 = fatal), every path is kept.
|
|
28
|
+
* Filtering is a convenience; silently returning *nothing* because git could
|
|
29
|
+
* not answer would be indistinguishable from "no matches".
|
|
30
|
+
*/
|
|
31
|
+
export function filterGitIgnored(paths: string[], cwd: string): string[] {
|
|
32
|
+
if (paths.length === 0) return paths
|
|
33
|
+
const ignored = new Set<string>()
|
|
34
|
+
for (let i = 0; i < paths.length; i += GLOB_IGNORE_BATCH) {
|
|
35
|
+
const batch = paths.slice(i, i + GLOB_IGNORE_BATCH)
|
|
36
|
+
const res = spawnSync('git', ['check-ignore', '--stdin', '-z'], {
|
|
37
|
+
cwd,
|
|
38
|
+
input: batch.join('\0') + '\0',
|
|
39
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
40
|
+
})
|
|
41
|
+
// status 0 = at least one ignored; 1 = none; null/128 = not a repo or no git.
|
|
42
|
+
if (res.status !== 0 || !res.stdout) continue
|
|
43
|
+
for (const p of res.stdout.toString().split('\0')) if (p) ignored.add(p)
|
|
44
|
+
}
|
|
45
|
+
return paths.filter((p) => !ignored.has(p))
|
|
46
|
+
}
|
|
47
|
+
|
|
13
48
|
export function createGlobTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
|
|
14
49
|
return {
|
|
15
50
|
name: 'Glob',
|
|
16
|
-
description:
|
|
51
|
+
description:
|
|
52
|
+
'Find files matching a glob pattern. Inside a git repository, files ignored by .gitignore are excluded.',
|
|
17
53
|
category: 'file',
|
|
18
54
|
permission: 'self',
|
|
19
55
|
parameters: {
|
|
@@ -30,14 +66,30 @@ export function createGlobTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
30
66
|
const glob = new Glob(pattern)
|
|
31
67
|
const results: string[] = []
|
|
32
68
|
let truncated = false
|
|
69
|
+
let pending: string[] = []
|
|
70
|
+
// 过滤放在**取满 500 之前**:先收 500 个再过滤,忽略项多的树会只剩几十条
|
|
71
|
+
// 却仍报「截断到 500」;反过来先过滤再数,截断标记描述的才是真实结果集。
|
|
72
|
+
const keep = (batch: string[]) => {
|
|
73
|
+
if (batch.length === 0) return
|
|
74
|
+
for (const p of filterGitIgnored(batch, basePath)) results.push(p)
|
|
75
|
+
}
|
|
33
76
|
for await (const file of glob.scan({ cwd: basePath, absolute: true })) {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
77
|
+
pending.push(file)
|
|
78
|
+
if (pending.length >= GLOB_IGNORE_BATCH) {
|
|
79
|
+
keep(pending)
|
|
80
|
+
pending = []
|
|
81
|
+
if (results.length > GLOB_MAX_RESULTS) {
|
|
82
|
+
// 只有真的还有第 501 个**未被忽略**的匹配时才叫截断 —— 恰好 500 个是完整结果。
|
|
83
|
+
truncated = true
|
|
84
|
+
break
|
|
85
|
+
}
|
|
38
86
|
}
|
|
39
|
-
results.push(file)
|
|
40
87
|
}
|
|
88
|
+
if (!truncated) {
|
|
89
|
+
keep(pending)
|
|
90
|
+
truncated = results.length > GLOB_MAX_RESULTS
|
|
91
|
+
}
|
|
92
|
+
results.length = Math.min(results.length, GLOB_MAX_RESULTS)
|
|
41
93
|
// 先掩码正文、再拼注解:`maskGlobOutput` 是**逐行当路径**去比对的
|
|
42
94
|
// (每行都过 `matchCredentialFile`),注解不是路径,不该喂给它。
|
|
43
95
|
const content = maskGlobOutput(results.join('\n') || '(no matches)', credentialConfig)
|
package/src/tools/file/grep.ts
CHANGED
|
@@ -34,7 +34,15 @@ export async function runSearch(
|
|
|
34
34
|
// Same reasoning as `internalGitEnv`: this search is ours, not the user's
|
|
35
35
|
// shell — ripgrep never needs an API key, and handing one down only makes it
|
|
36
36
|
// reachable from a config file or a `--pre` child of the search.
|
|
37
|
-
|
|
37
|
+
//
|
|
38
|
+
// `RIPGREP_CONFIG_PATH` is the user's *global* ripgrep configuration: it can
|
|
39
|
+
// inject `--glob` / `--type` / `--ignore-file` flags that silently change or
|
|
40
|
+
// empty every search this tool performs. The args here are fixed, so the
|
|
41
|
+
// config file is the only other input — a search must answer for the
|
|
42
|
+
// repository being searched, not for a file the user forgot about.
|
|
43
|
+
const env = internalProcessEnv()
|
|
44
|
+
delete env.RIPGREP_CONFIG_PATH
|
|
45
|
+
const proc = Bun.spawn(cmd, { cwd, stdout: 'pipe', stderr: 'pipe', env })
|
|
38
46
|
let timedOut = false
|
|
39
47
|
const timers: ReturnType<typeof setTimeout>[] = []
|
|
40
48
|
timers.push(
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import type { ToolDefinition } from '../../shared/index.ts'
|
|
10
10
|
import { McpClient } from '../../mcp/client'
|
|
11
|
+
import { buildToolName } from '../../mcp/registry'
|
|
11
12
|
import { capMcpText } from '../../mcp/instructions'
|
|
12
13
|
|
|
13
14
|
/**
|
|
@@ -162,7 +163,7 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
162
163
|
lines.push(` ${server} (${tools.length}):`)
|
|
163
164
|
for (const t of tools) {
|
|
164
165
|
const desc = t.description ? ` — ${t.description}` : ''
|
|
165
|
-
lines.push(`
|
|
166
|
+
lines.push(` ${buildToolName(server, t.tool)}${desc}`)
|
|
166
167
|
}
|
|
167
168
|
lines.push('')
|
|
168
169
|
}
|