@miphamai/cli 0.85.31 → 0.85.33
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/core/credential-masker/env-filter.ts +37 -0
- package/src/core/permission-rules.ts +96 -2
- package/src/core/permission.ts +14 -1
- package/src/core/workspace-trust.ts +50 -17
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/index.tsx +6 -0
- package/src/mcp/client.ts +41 -6
- package/src/mcp/protocol.ts +16 -2
- package/src/mcp/transport.ts +55 -8
- package/src/plugin/plugin-manager.ts +15 -3
- package/src/providers/fetch-utils.ts +49 -0
- package/src/providers/openai-compat.ts +28 -2
- package/src/shared/git-env.ts +37 -13
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +17 -0
- package/src/tools/computer/browser.ts +13 -0
- package/src/tools/file/edit.ts +19 -3
- package/src/tools/file/grep.ts +5 -1
- package/src/tools/file/write.ts +18 -1
- package/src/tools/network/web-fetch.ts +12 -0
- package/src/tools/system/tool-search.ts +35 -3
- package/src/ui/app.tsx +90 -4
- package/src/ui/chat.tsx +14 -3
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.33
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -5,6 +5,43 @@ import type { CredentialMaskingConfig } from '../../shared/index.ts'
|
|
|
5
5
|
* Filter sensitive environment variables before spawning a subprocess.
|
|
6
6
|
* Returns a sanitized copy of process.env with matching vars removed.
|
|
7
7
|
*/
|
|
8
|
+
/** Which variable names the config calls sensitive (same patterns `filterEnv`
|
|
9
|
+
* uses — one definition of "sensitive", two dispositions). */
|
|
10
|
+
export function isSensitiveEnvKey(key: string, config: CredentialMaskingConfig): boolean {
|
|
11
|
+
for (const pattern of config.env_filter.patterns) {
|
|
12
|
+
try {
|
|
13
|
+
// Strip (?i) inline flags — JS uses the 'i' flag instead
|
|
14
|
+
const clean = pattern.replace(/^\(\?i\)/, '')
|
|
15
|
+
if (new RegExp(clean, 'i').test(key)) return true
|
|
16
|
+
} catch {
|
|
17
|
+
// Invalid regex — skip
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return false
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Remove sensitive variables outright — for processes *this program* starts on
|
|
25
|
+
* its own behalf (git, ripgrep).
|
|
26
|
+
*
|
|
27
|
+
* `filterEnv` keeps the name and swaps in a sentinel so the model's shell can
|
|
28
|
+
* tell a value was withheld. That is the wrong shape here: these children never
|
|
29
|
+
* act on the user's behalf, so a credential helper or hook under them should
|
|
30
|
+
* find nothing at all, not a well-formed string that merely isn't the secret.
|
|
31
|
+
*/
|
|
32
|
+
export function stripEnv(
|
|
33
|
+
env: Record<string, string | undefined>,
|
|
34
|
+
config: CredentialMaskingConfig,
|
|
35
|
+
): Record<string, string | undefined> {
|
|
36
|
+
if (!config.enabled || !config.env_filter.enabled) return { ...env }
|
|
37
|
+
|
|
38
|
+
const stripped: Record<string, string | undefined> = {}
|
|
39
|
+
for (const [key, value] of Object.entries(env)) {
|
|
40
|
+
if (!isSensitiveEnvKey(key, config)) stripped[key] = value
|
|
41
|
+
}
|
|
42
|
+
return stripped
|
|
43
|
+
}
|
|
44
|
+
|
|
8
45
|
export function filterEnv(
|
|
9
46
|
env: Record<string, string | undefined>,
|
|
10
47
|
config: CredentialMaskingConfig,
|
|
@@ -143,6 +143,39 @@ const PREFIX_VALUE_OPTIONS = new Set([
|
|
|
143
143
|
'--max-procs', // xargs
|
|
144
144
|
])
|
|
145
145
|
|
|
146
|
+
/**
|
|
147
|
+
* Flags that collide with a value-taking option spelling but are booleans for
|
|
148
|
+
* this wrapper. The shared table made `sudo -n rm -rf /tmp/x` consume `rm` as
|
|
149
|
+
* `-n`'s value, so the base command came out as `-rf` and a `Bash(rm:*)` deny
|
|
150
|
+
* never saw the command at all. `sudo -E` (xargs' `--eof`) and `sudo -s`
|
|
151
|
+
* (timeout's `--signal`) fail the same way. A boolean flag never takes the next
|
|
152
|
+
* token; without this, the real command is one token further along than the
|
|
153
|
+
* matcher looks.
|
|
154
|
+
*/
|
|
155
|
+
const WRAPPER_BOOLEAN_OPTIONS: Record<string, ReadonlySet<string>> = {
|
|
156
|
+
sudo: new Set([
|
|
157
|
+
'-n',
|
|
158
|
+
'--non-interactive',
|
|
159
|
+
'-E',
|
|
160
|
+
'--preserve-env',
|
|
161
|
+
'-H',
|
|
162
|
+
'--set-home',
|
|
163
|
+
'-A',
|
|
164
|
+
'--askpass',
|
|
165
|
+
'-b',
|
|
166
|
+
'--background',
|
|
167
|
+
'-S',
|
|
168
|
+
'--stdin',
|
|
169
|
+
'-s',
|
|
170
|
+
'--shell',
|
|
171
|
+
'-i',
|
|
172
|
+
'--login',
|
|
173
|
+
'-K',
|
|
174
|
+
'--remove-timestamp',
|
|
175
|
+
]),
|
|
176
|
+
doas: new Set(['-n', '--non-interactive', '-s', '--shell']),
|
|
177
|
+
}
|
|
178
|
+
|
|
146
179
|
/**
|
|
147
180
|
* Shell interpreters whose `-c` argument is itself a complete command line.
|
|
148
181
|
*
|
|
@@ -571,7 +604,16 @@ function effectiveCommand(tokens: string[]): {
|
|
|
571
604
|
while (i < tokens.length && tokens[i]!.startsWith('-')) {
|
|
572
605
|
const opt = tokens[i]!
|
|
573
606
|
i++
|
|
574
|
-
|
|
607
|
+
// A flag that is a boolean for *this* wrapper never consumes the next
|
|
608
|
+
// token, even though another wrapper's table calls the same spelling
|
|
609
|
+
// value-taking (see WRAPPER_BOOLEAN_OPTIONS).
|
|
610
|
+
if (
|
|
611
|
+
PREFIX_VALUE_OPTIONS.has(opt) &&
|
|
612
|
+
!WRAPPER_BOOLEAN_OPTIONS[name]?.has(opt) &&
|
|
613
|
+
i < tokens.length
|
|
614
|
+
) {
|
|
615
|
+
i++ // skip the flag's value
|
|
616
|
+
}
|
|
575
617
|
}
|
|
576
618
|
if (name === 'env') {
|
|
577
619
|
// `VAR=value` assignments. A quoted value spans several whitespace-split
|
|
@@ -977,6 +1019,19 @@ export function matchBashRule(
|
|
|
977
1019
|
return qualifies(paths, (p) => matchPathRule(p, subPattern!, segmentMode))
|
|
978
1020
|
}
|
|
979
1021
|
|
|
1022
|
+
// A `Read` deny/ask rule protects the *path*, not one tool: Write and Edit
|
|
1023
|
+
// touch the same file the rule was written to keep off-limits, so routing
|
|
1024
|
+
// around it by overwriting the file left `Read(secrets/**)` enforceable only
|
|
1025
|
+
// against readers. Only the deny/ask direction bridges — an `allow` bridge
|
|
1026
|
+
// would be a privilege expansion (`Read(X)` never granted Write to X).
|
|
1027
|
+
if (
|
|
1028
|
+
segmentMode !== 'all' &&
|
|
1029
|
+
baseTool === 'Read' &&
|
|
1030
|
+
(toolName === 'Write' || toolName === 'Edit')
|
|
1031
|
+
) {
|
|
1032
|
+
return matchPathRule(String(toolInput.file_path || ''), subPattern!, segmentMode)
|
|
1033
|
+
}
|
|
1034
|
+
|
|
980
1035
|
if (toolName !== baseTool!) return false
|
|
981
1036
|
|
|
982
1037
|
// For Bash: match against the command string (any segment of a compound
|
|
@@ -984,7 +1039,25 @@ export function matchBashRule(
|
|
|
984
1039
|
// `$(...)`/backtick substitution, so `Bash(rm *)` catches `x=$(rm -rf ~)`).
|
|
985
1040
|
if (baseTool === 'Bash') {
|
|
986
1041
|
const cmd = String(toolInput.command || '')
|
|
987
|
-
|
|
1042
|
+
// An allow rule whose first word ends in an attached wildcard (`ls*`) is a
|
|
1043
|
+
// grant bounded by that word — but `^ls.*$` also matched `lsof -i -P`, so
|
|
1044
|
+
// the rule handed over every command that merely starts with the same
|
|
1045
|
+
// letters. Under deny/ask the wide reading stays: there, matching more is
|
|
1046
|
+
// the safe direction.
|
|
1047
|
+
const anchored = segmentMode === 'all' ? /^([\w./-]+)\*/.exec(subPattern!) : null
|
|
1048
|
+
const firstWord = anchored?.[1]
|
|
1049
|
+
return qualifies(flattenCommand(cmd), (seg) => {
|
|
1050
|
+
if (firstWord) {
|
|
1051
|
+
// The wildcard has to start at a word boundary in the command: `ls`
|
|
1052
|
+
// exactly, or `ls` followed by whitespace/`:` — not the `ls` inside
|
|
1053
|
+
// `lsof`.
|
|
1054
|
+
const boundary = new RegExp(
|
|
1055
|
+
'^' + firstWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?:$|[:\\s])',
|
|
1056
|
+
)
|
|
1057
|
+
if (!boundary.test(seg)) return false
|
|
1058
|
+
}
|
|
1059
|
+
return wildcardMatch(subPattern!, seg)
|
|
1060
|
+
})
|
|
988
1061
|
}
|
|
989
1062
|
|
|
990
1063
|
// For Write/Edit/Read: match against the file_path with path-glob semantics.
|
|
@@ -1104,6 +1177,27 @@ export function mcpServerPrefix(pattern: string): string | null {
|
|
|
1104
1177
|
return `mcp__${server.toLowerCase()}__`
|
|
1105
1178
|
}
|
|
1106
1179
|
|
|
1180
|
+
/**
|
|
1181
|
+
* A Bash **allow** rule that puts a `*` inside a variable's *value*
|
|
1182
|
+
* (`Bash(PORT=* npm run dev)`) is a grant nobody means: the `*` is a wildcard
|
|
1183
|
+
* over the whole assignment, so the rule matches **every** value. Returns the
|
|
1184
|
+
* warning text, or `undefined`.
|
|
1185
|
+
*
|
|
1186
|
+
* Deny/ask rules are deliberately not warned — there, a wider match is the safe
|
|
1187
|
+
* direction. This is a warning and not a rejection: the pattern is structurally
|
|
1188
|
+
* valid and the author may genuinely want the wildcard.
|
|
1189
|
+
*/
|
|
1190
|
+
export function variableWildcardWarning(pattern: string): string | undefined {
|
|
1191
|
+
const shape = pattern.match(/^Bash\((.+)\)$/)
|
|
1192
|
+
if (!shape) return undefined
|
|
1193
|
+
const hit = /(?:^|\s)([A-Za-z_][A-Za-z0-9_]*)=[^\s]*\*/.exec(shape[1]!)
|
|
1194
|
+
if (!hit) return undefined
|
|
1195
|
+
return (
|
|
1196
|
+
`allow rule "${pattern}" puts a * in the value of ${hit[1]}: ` +
|
|
1197
|
+
`it matches every value, not one — write the concrete value if that is what you mean`
|
|
1198
|
+
)
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1107
1201
|
/**
|
|
1108
1202
|
* Compile a rule pattern string into a PermissionRuleEntry.
|
|
1109
1203
|
*/
|
package/src/core/permission.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type {
|
|
|
6
6
|
PermissionRestrictions,
|
|
7
7
|
} from '../shared/index.ts'
|
|
8
8
|
import type { PermissionRuleEntry } from '../shared/index.ts'
|
|
9
|
-
import { matchBashRule, compileRule } from './permission-rules'
|
|
9
|
+
import { matchBashRule, compileRule, variableWildcardWarning } from './permission-rules'
|
|
10
10
|
import { detectDangerousRm } from '../security/dangerous-rm'
|
|
11
11
|
import type { DangerousRm } from '../security/dangerous-rm'
|
|
12
12
|
import { detectWorldWritableChmod } from '../security/world-writable-chmod'
|
|
@@ -1118,6 +1118,19 @@ export class PermissionSystem {
|
|
|
1118
1118
|
this.invalidateCache()
|
|
1119
1119
|
}
|
|
1120
1120
|
|
|
1121
|
+
/**
|
|
1122
|
+
* Allow rules that load but cannot mean what they say — currently only a `*`
|
|
1123
|
+
* in a variable's *value* (`Bash(PORT=* npm run dev)`), which grants every
|
|
1124
|
+
* value instead of the one written. Derived on read rather than stored: the
|
|
1125
|
+
* rule arrays are replaced wholesale by `loadConfig`, and a stored copy would
|
|
1126
|
+
* go stale there. Callers print these at start-up, like `getInvalidRules()`.
|
|
1127
|
+
*/
|
|
1128
|
+
getRuleWarnings(): string[] {
|
|
1129
|
+
return this.allowRules
|
|
1130
|
+
.map((entry) => variableWildcardWarning(entry.pattern))
|
|
1131
|
+
.filter((w): w is string => Boolean(w))
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1121
1134
|
/**
|
|
1122
1135
|
* Report any rule whose pattern is structurally invalid and can therefore
|
|
1123
1136
|
* never match (e.g. `Bash(ls) x`, `Read(foo`, `Bash()`). These are silently
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFileSync, existsSync, mkdirSync } from 'node:fs'
|
|
1
|
+
import { readFileSync, existsSync, mkdirSync, realpathSync } from 'node:fs'
|
|
2
2
|
import { join, dirname, resolve } from 'node:path'
|
|
3
3
|
import { atomicWriteFileSync } from '../shared/atomic-write'
|
|
4
4
|
import { miphamHome } from './paths.ts'
|
|
@@ -16,17 +16,39 @@ export interface TrustedWorkspaces {
|
|
|
16
16
|
/**
|
|
17
17
|
* Resolves a directory to its real absolute path, following symlinks.
|
|
18
18
|
* Falls back to the resolved path if realpath fails.
|
|
19
|
+
*
|
|
20
|
+
* This used to be `resolve()` under a comment claiming it followed symlinks —
|
|
21
|
+
* so trust was checked against the **lexical** spelling while the settings and
|
|
22
|
+
* hooks it gates are read through the **canonical** one. A workspace reached
|
|
23
|
+
* through a symlink (`~/work -> /Volumes/proj`, or macOS's `/tmp -> /private/tmp`)
|
|
24
|
+
* was therefore trusted under one path and read under another.
|
|
25
|
+
*
|
|
26
|
+
* A directory that does not exist yet has no realpath; `resolve` keeps
|
|
27
|
+
* `trust()` usable before the folder is created.
|
|
19
28
|
*/
|
|
20
29
|
function realPath(dir: string): string {
|
|
21
30
|
try {
|
|
22
|
-
|
|
23
|
-
const resolved = resolve(dir)
|
|
24
|
-
return resolved
|
|
31
|
+
return realpathSync.native(dir)
|
|
25
32
|
} catch {
|
|
26
33
|
return resolve(dir)
|
|
27
34
|
}
|
|
28
35
|
}
|
|
29
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Both spellings of a directory: what the caller typed (normalised) and what
|
|
39
|
+
* the filesystem calls it.
|
|
40
|
+
*
|
|
41
|
+
* Trust entries written before canonicalisation, and paths passed through a
|
|
42
|
+
* symlink, each match only one of the two. Checking both keeps an existing
|
|
43
|
+
* store valid and cannot widen what is trusted — every candidate must itself
|
|
44
|
+
* be inside a trusted directory.
|
|
45
|
+
*/
|
|
46
|
+
function spellings(dir: string): string[] {
|
|
47
|
+
const literal = resolve(dir)
|
|
48
|
+
const real = realPath(dir)
|
|
49
|
+
return literal === real ? [literal] : [literal, real]
|
|
50
|
+
}
|
|
51
|
+
|
|
30
52
|
/**
|
|
31
53
|
* True if a `.git` file or directory exists anywhere strictly between `dir` and
|
|
32
54
|
* its trusted ancestor `ancestor`. A `.git` marks the root of a separate
|
|
@@ -121,17 +143,24 @@ export class WorkspaceTrust {
|
|
|
121
143
|
* A directory is trusted if it or any ancestor is in the trust list.
|
|
122
144
|
*/
|
|
123
145
|
isTrusted(dir: string): boolean {
|
|
124
|
-
const
|
|
125
|
-
const resolvedLower = resolved.toLowerCase()
|
|
146
|
+
const candidates = spellings(dir)
|
|
126
147
|
|
|
127
148
|
for (const trusted of this.store.directories) {
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
149
|
+
for (const trustedPath of spellings(trusted)) {
|
|
150
|
+
const trustedLower = trustedPath.toLowerCase()
|
|
151
|
+
for (const candidate of candidates) {
|
|
152
|
+
const candidateLower = candidate.toLowerCase()
|
|
153
|
+
// Exact match
|
|
154
|
+
if (candidateLower === trustedLower) return true
|
|
155
|
+
// Ancestor match: trusted dir is a parent of the target. Trust does not
|
|
156
|
+
// cross a nested git-repository boundary (vendored/submodule isolation).
|
|
157
|
+
if (
|
|
158
|
+
candidateLower.startsWith(trustedLower + '/') &&
|
|
159
|
+
!hasGitBoundary(candidate, trustedPath)
|
|
160
|
+
) {
|
|
161
|
+
return true
|
|
162
|
+
}
|
|
163
|
+
}
|
|
135
164
|
}
|
|
136
165
|
}
|
|
137
166
|
|
|
@@ -141,6 +170,10 @@ export class WorkspaceTrust {
|
|
|
141
170
|
/**
|
|
142
171
|
* Add a directory to the trust store.
|
|
143
172
|
*
|
|
173
|
+
* The canonical path is what gets stored: the settings and hooks trust gates
|
|
174
|
+
* are read through the realpath, so recording a symlink's lexical spelling
|
|
175
|
+
* made the two disagree. `isTrusted` still matches older lexical entries.
|
|
176
|
+
*
|
|
144
177
|
* Returns false only when the new entry could not be written to disk; a
|
|
145
178
|
* directory that is already trusted is `true` — it was persisted earlier.
|
|
146
179
|
*/
|
|
@@ -159,13 +192,13 @@ export class WorkspaceTrust {
|
|
|
159
192
|
|
|
160
193
|
/** Remove a directory from the trust store (and any subdirectories). */
|
|
161
194
|
untrust(dir: string): void {
|
|
162
|
-
const
|
|
163
|
-
const resolvedLower = resolved.toLowerCase()
|
|
195
|
+
const targets = spellings(dir).map((p) => p.toLowerCase())
|
|
164
196
|
|
|
165
197
|
this.store.directories = this.store.directories.filter((d) => {
|
|
166
198
|
const lower = d.toLowerCase()
|
|
167
|
-
// Remove exact match and all subdirectories
|
|
168
|
-
|
|
199
|
+
// Remove exact match and all subdirectories, in whichever spelling the
|
|
200
|
+
// entry was recorded.
|
|
201
|
+
return !targets.some((target) => lower === target || lower.startsWith(target + '/'))
|
|
169
202
|
})
|
|
170
203
|
this.save()
|
|
171
204
|
}
|
package/src/index.tsx
CHANGED
|
@@ -879,6 +879,12 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
879
879
|
process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
|
|
880
880
|
}
|
|
881
881
|
|
|
882
|
+
// Valid-but-doesn't-mean-what-it-says: a `*` in a variable's value in an
|
|
883
|
+
// allow rule (`Bash(PORT=* npm run dev)`) grants every value.
|
|
884
|
+
for (const msg of engine.getPermission().getRuleWarnings()) {
|
|
885
|
+
process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
|
|
886
|
+
}
|
|
887
|
+
|
|
882
888
|
// Same warning channel for malformed restrictions (P1) — a typo'd
|
|
883
889
|
// `forbiddenModes`/`maxAllowedMode` used to leave the policy silently inert.
|
|
884
890
|
for (const msg of engine.getPermission().getInvalidRestrictions()) {
|
package/src/mcp/client.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { HttpTransport, McpHttpError } from './http-transport'
|
|
|
11
11
|
import { McpProtocol } from './protocol'
|
|
12
12
|
import { OAuthClient } from './oauth'
|
|
13
13
|
import { TokenStore } from './token-store'
|
|
14
|
+
import { basename } from 'node:path'
|
|
14
15
|
import { createAwakeTimer } from '../providers/fetch-utils'
|
|
15
16
|
import { createT } from '../i18n-core/t'
|
|
16
17
|
import enUS from '../i18n-core/locales/en-US.json'
|
|
@@ -25,16 +26,46 @@ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as Translat
|
|
|
25
26
|
|
|
26
27
|
// Connect-handshake timeout: a hung MCP server should fail startup fast rather
|
|
27
28
|
// than block on the per-request 60s timeout. Overridable via env for tests.
|
|
28
|
-
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
|
|
29
|
+
export const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Budget for a server launched through a package manager (`npx -y <pkg>`, …).
|
|
33
|
+
*
|
|
34
|
+
* `spawn('npx')` returns immediately — the dependency download happens inside
|
|
35
|
+
* the child, so the whole cost lands on `initialize()` waiting for a reply. A
|
|
36
|
+
* cold cache measured 29.9 s here (2× the default), and the server is *working*,
|
|
37
|
+
* not hung: failing at 15 s throws that work away and then races a second
|
|
38
|
+
* install against the first.
|
|
39
|
+
*
|
|
40
|
+
* Kept under `DEFAULT_REQUEST_TIMEOUT_MS` (60 s) on purpose: past it the
|
|
41
|
+
* handshake dies on the request timer instead, which only changes the error
|
|
42
|
+
* message, not the patience.
|
|
43
|
+
*/
|
|
44
|
+
export const PACKAGE_MANAGER_CONNECT_TIMEOUT_MS = 45_000
|
|
45
|
+
|
|
46
|
+
/** Commands whose startup includes package resolution, so the budget is theirs. */
|
|
47
|
+
const PACKAGE_MANAGER_COMMANDS = new Set(['npx', 'bunx', 'npm', 'pnpm', 'yarn'])
|
|
48
|
+
|
|
49
|
+
function isPackageManagerCommand(command: string | undefined): boolean {
|
|
50
|
+
if (!command) return false
|
|
51
|
+
// Windows resolves these as `npx.cmd`; the shape of the wait is the same.
|
|
52
|
+
const base = basename(command)
|
|
53
|
+
.replace(/\.(cmd|exe|ps1)$/i, '')
|
|
54
|
+
.toLowerCase()
|
|
55
|
+
return PACKAGE_MANAGER_COMMANDS.has(base)
|
|
56
|
+
}
|
|
29
57
|
|
|
30
58
|
// How often a caller waiting on a handshake re-checks it. A handshake settles in
|
|
31
59
|
// tens of milliseconds when it settles at all; this only bounds how long the wait
|
|
32
60
|
// can overshoot the moment it actually did.
|
|
33
61
|
const CONNECT_POLL_MS = 50
|
|
34
62
|
|
|
35
|
-
function connectTimeoutMs(): number {
|
|
63
|
+
export function connectTimeoutMs(command?: string): number {
|
|
36
64
|
const env = Number(process.env.MIPHAM_MCP_CONNECT_TIMEOUT_MS)
|
|
37
|
-
|
|
65
|
+
if (Number.isFinite(env) && env > 0) return env
|
|
66
|
+
return isPackageManagerCommand(command)
|
|
67
|
+
? PACKAGE_MANAGER_CONNECT_TIMEOUT_MS
|
|
68
|
+
: DEFAULT_CONNECT_TIMEOUT_MS
|
|
38
69
|
}
|
|
39
70
|
|
|
40
71
|
/**
|
|
@@ -449,7 +480,7 @@ export class McpClient {
|
|
|
449
480
|
// is what an unauthenticated request gets rejected on.
|
|
450
481
|
const env = await this.envWithAuth(config)
|
|
451
482
|
|
|
452
|
-
await this.withConnectTimeout(config.name, async () => {
|
|
483
|
+
await this.withConnectTimeout(config.name, config.command, async () => {
|
|
453
484
|
// Start the transport (transport-specific), then perform the handshake.
|
|
454
485
|
if (transport instanceof HttpTransport) {
|
|
455
486
|
await transport.start(config.url ?? '', config.headers, env)
|
|
@@ -499,8 +530,12 @@ export class McpClient {
|
|
|
499
530
|
* server registers no tools — never give `markIfTransportLost` a chance to
|
|
500
531
|
* reconnect. The server is fine; only the clock moved.
|
|
501
532
|
*/
|
|
502
|
-
private async withConnectTimeout<T>(
|
|
503
|
-
|
|
533
|
+
private async withConnectTimeout<T>(
|
|
534
|
+
name: string,
|
|
535
|
+
command: string | undefined,
|
|
536
|
+
fn: () => Promise<T>,
|
|
537
|
+
): Promise<T> {
|
|
538
|
+
const timeoutMs = connectTimeoutMs(command)
|
|
504
539
|
// Held in an object, not a `let`: the timer is armed inside the Promise
|
|
505
540
|
// executor, and assignments made there are invisible to control-flow
|
|
506
541
|
// narrowing — TS keeps the variable typed `null` and the cleanup call below
|
package/src/mcp/protocol.ts
CHANGED
|
@@ -131,8 +131,22 @@ export class McpProtocol {
|
|
|
131
131
|
}
|
|
132
132
|
|
|
133
133
|
async listTools(): Promise<ToolDefinition[]> {
|
|
134
|
-
const result = (await this.transport.sendRequest('tools/list')) as {
|
|
135
|
-
|
|
134
|
+
const result = (await this.transport.sendRequest('tools/list')) as {
|
|
135
|
+
tools?: ToolDefinition[]
|
|
136
|
+
}
|
|
137
|
+
// A server (or the host embedding it) may put a `null` or a nameless entry
|
|
138
|
+
// in `tools`. That shape used to reach `connection.tools.map(t => t.name)`,
|
|
139
|
+
// throw a TypeError from a background async, and — with our crash handler
|
|
140
|
+
// installed — take the whole CLI down over one malformed server. Drop
|
|
141
|
+
// entries that cannot be addressed instead of trusting the payload.
|
|
142
|
+
const tools = Array.isArray(result?.tools) ? result.tools : []
|
|
143
|
+
return tools.filter(
|
|
144
|
+
(tool): tool is ToolDefinition =>
|
|
145
|
+
!!tool &&
|
|
146
|
+
typeof tool === 'object' &&
|
|
147
|
+
typeof (tool as { name?: unknown }).name === 'string' &&
|
|
148
|
+
(tool as { name: string }).name.length > 0,
|
|
149
|
+
)
|
|
136
150
|
}
|
|
137
151
|
|
|
138
152
|
async callTool(
|
package/src/mcp/transport.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { spawn, type ChildProcess } from 'node:child_process'
|
|
1
|
+
import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
|
|
2
2
|
import type { JsonRpcRequest, JsonRpcResponse, JsonRpcNotification } from './types'
|
|
3
3
|
|
|
4
4
|
export type NotificationHandler = (notification: JsonRpcNotification) => void
|
|
@@ -51,13 +51,17 @@ function waitForExit(proc: ChildProcess, ms: number): Promise<void> {
|
|
|
51
51
|
/**
|
|
52
52
|
* Terminate the server **and its descendants** once the grace period expired.
|
|
53
53
|
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
54
|
+
* Windows has no process group to signal, so `taskkill /T` is the only way to
|
|
55
|
+
* reach the server's own children. On POSIX we do **not** spawn MCP servers
|
|
56
|
+
* detached — the child shares our process group, so `process.kill(-pid)` is
|
|
57
|
+
* ESRCH — and making it a group leader would let servers outlive the CLI, a
|
|
58
|
+
* worse bug than the one being fixed. So the descendants are enumerated from
|
|
59
|
+
* `ps` instead and signalled one by one.
|
|
60
|
+
*
|
|
61
|
+
* Killing only the direct child was wrong for the shape that matters:
|
|
62
|
+
* `npx -y some-mcp` spawns a **wrapper**, and the server that answers JSON-RPC
|
|
63
|
+
* is its child. Killing the wrapper re-parents that child to init and it keeps
|
|
64
|
+
* running — observed as accumulating `ppid=1` `node …/_npx/…/xxx-mcp` processes.
|
|
61
65
|
*/
|
|
62
66
|
function killProcessTree(proc: ChildProcess): void {
|
|
63
67
|
const pid = proc.pid
|
|
@@ -68,6 +72,16 @@ function killProcessTree(proc: ChildProcess): void {
|
|
|
68
72
|
} catch {
|
|
69
73
|
/* fall through to the direct kill */
|
|
70
74
|
}
|
|
75
|
+
} else {
|
|
76
|
+
// Deepest first, while the parent links that identified them still exist:
|
|
77
|
+
// once the wrapper dies its children are re-parented and unfindable.
|
|
78
|
+
for (const descendant of descendantPids(pid).reverse()) {
|
|
79
|
+
try {
|
|
80
|
+
process.kill(descendant)
|
|
81
|
+
} catch {
|
|
82
|
+
/* already gone */
|
|
83
|
+
}
|
|
84
|
+
}
|
|
71
85
|
}
|
|
72
86
|
try {
|
|
73
87
|
proc.kill()
|
|
@@ -76,6 +90,39 @@ function killProcessTree(proc: ChildProcess): void {
|
|
|
76
90
|
}
|
|
77
91
|
}
|
|
78
92
|
|
|
93
|
+
/** Every descendant of `root`, parents before children. */
|
|
94
|
+
function descendantPids(root: number): number[] {
|
|
95
|
+
let listing: string
|
|
96
|
+
try {
|
|
97
|
+
listing = execFileSync('ps', ['-A', '-o', 'pid=,ppid='], {
|
|
98
|
+
encoding: 'utf-8',
|
|
99
|
+
timeout: 2000,
|
|
100
|
+
})
|
|
101
|
+
} catch {
|
|
102
|
+
return [] // No `ps`, or it timed out: fall back to the direct kill.
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const byParent = new Map<number, number[]>()
|
|
106
|
+
for (const line of listing.split('\n')) {
|
|
107
|
+
const [pidText, ppidText] = line.trim().split(/\s+/)
|
|
108
|
+
const pid = Number(pidText)
|
|
109
|
+
const ppid = Number(ppidText)
|
|
110
|
+
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue
|
|
111
|
+
const siblings = byParent.get(ppid)
|
|
112
|
+
if (siblings) siblings.push(pid)
|
|
113
|
+
else byParent.set(ppid, [pid])
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const descendants: number[] = []
|
|
117
|
+
const queue = [...(byParent.get(root) ?? [])]
|
|
118
|
+
while (queue.length > 0) {
|
|
119
|
+
const next = queue.shift()!
|
|
120
|
+
descendants.push(next)
|
|
121
|
+
queue.push(...(byParent.get(next) ?? []))
|
|
122
|
+
}
|
|
123
|
+
return descendants
|
|
124
|
+
}
|
|
125
|
+
|
|
79
126
|
/** Shared timeout error for both stdio and HTTP transports. */
|
|
80
127
|
export function requestTimeoutError(method: string, ms: number): Error {
|
|
81
128
|
return new Error(`MCP request timeout: ${method} (${ms}ms)`)
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
renameSync,
|
|
9
9
|
} from 'node:fs'
|
|
10
10
|
import { join } from 'node:path'
|
|
11
|
-
import {
|
|
11
|
+
import { spawnSync } from 'node:child_process'
|
|
12
12
|
import { validatePlugin } from './plugin-validator'
|
|
13
13
|
import { atomicWriteFileSync } from '../shared/atomic-write'
|
|
14
14
|
import { miphamHome } from '../core/paths.ts'
|
|
@@ -143,7 +143,7 @@ export class PluginManager {
|
|
|
143
143
|
// preinstall/install/postinstall hooks as the current user — arbitrary
|
|
144
144
|
// code execution from any npm package, reachable via `/install-plugin`.
|
|
145
145
|
// A plugin only needs to *be* files on disk; it never needs a build step
|
|
146
|
-
// of its own to be loaded from here. `
|
|
146
|
+
// of its own to be loaded from here. `spawnSync` (argv array, no
|
|
147
147
|
// shell) keeps the command line independent of packageName, so package
|
|
148
148
|
// name validation is not the only thing standing between us and a shell.
|
|
149
149
|
//
|
|
@@ -155,7 +155,12 @@ export class PluginManager {
|
|
|
155
155
|
// resolver. The value is the npm default already declared in this repo's
|
|
156
156
|
// registry chain (`src/shared/update.ts`), not a new literal. The flag is
|
|
157
157
|
// honoured over npm config because command-line flags outrank it.
|
|
158
|
-
execFileSync
|
|
158
|
+
// `spawnSync`, not `execFileSync`: the latter returns stdout only, so
|
|
159
|
+
// whatever npm wrote to stderr on a *successful* install (deprecation
|
|
160
|
+
// notices, funding warnings — the messages that explain what the user got)
|
|
161
|
+
// was discarded. Non-zero exit keeps the old failure shape: the stderr is
|
|
162
|
+
// the error message.
|
|
163
|
+
const npm = spawnSync(
|
|
159
164
|
'npm',
|
|
160
165
|
[
|
|
161
166
|
'install',
|
|
@@ -173,6 +178,12 @@ export class PluginManager {
|
|
|
173
178
|
timeout: 60_000,
|
|
174
179
|
},
|
|
175
180
|
)
|
|
181
|
+
if (npm.error) throw npm.error
|
|
182
|
+
if (npm.status !== 0) {
|
|
183
|
+
const detail = (npm.stderr || npm.stdout || '').trim()
|
|
184
|
+
throw new Error(detail || `npm exited with status ${npm.status}`)
|
|
185
|
+
}
|
|
186
|
+
const npmNote = (npm.stderr || '').trim()
|
|
176
187
|
|
|
177
188
|
// npm installs the package into <stagingDir>/node_modules/<packageName>/ —
|
|
178
189
|
// validate there, then flatten it to the plugin dir root so its layout
|
|
@@ -215,6 +226,7 @@ export class PluginManager {
|
|
|
215
226
|
success: true,
|
|
216
227
|
message:
|
|
217
228
|
`Plugin "${manifestName}" installed from npm` +
|
|
229
|
+
(npmNote ? `\n${npmNote}` : '') +
|
|
218
230
|
(similarWarning ? `\n⚠ ${similarWarning}` : '') +
|
|
219
231
|
warningsBlock(validation.warnings),
|
|
220
232
|
}
|
|
@@ -73,8 +73,44 @@ export function retryDelayMs(
|
|
|
73
73
|
return Math.min(Math.max(requested, RETRY_AFTER_MIN_MS), RETRY_AFTER_MAX_MS)
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
+
/**
|
|
77
|
+
* TLS failures a retry cannot fix.
|
|
78
|
+
*
|
|
79
|
+
* A certificate that has expired, or names another host, fails identically on
|
|
80
|
+
* every attempt — re-sending only delays the explanation the first handshake
|
|
81
|
+
* already gave. Matched on the `code` of the thrown error *and its `cause`
|
|
82
|
+
* chain*: Node's undici throws a bare `TypeError: fetch failed` and hides the
|
|
83
|
+
* OpenSSL verdict one level down, so a check that only looked at the top-level
|
|
84
|
+
* error would classify every certificate failure as transient.
|
|
85
|
+
*/
|
|
86
|
+
const NON_RETRYABLE_TLS_CODES = new Set([
|
|
87
|
+
'DEPTH_ZERO_SELF_SIGNED_CERT',
|
|
88
|
+
'SELF_SIGNED_CERT_IN_CHAIN',
|
|
89
|
+
'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
|
|
90
|
+
'UNABLE_TO_GET_ISSUER_CERT',
|
|
91
|
+
'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
|
|
92
|
+
'ERR_TLS_CERT_ALTNAME_INVALID',
|
|
93
|
+
])
|
|
94
|
+
|
|
95
|
+
/** The certificate verdict anywhere in `err`'s cause chain, if there is one. */
|
|
96
|
+
function tlsCertCode(err: unknown): string | undefined {
|
|
97
|
+
let cur: unknown = err
|
|
98
|
+
for (let depth = 0; cur && depth < 4; depth++) {
|
|
99
|
+
const code = (cur as { code?: unknown }).code
|
|
100
|
+
if (
|
|
101
|
+
typeof code === 'string' &&
|
|
102
|
+
(code.startsWith('CERT_') || NON_RETRYABLE_TLS_CODES.has(code))
|
|
103
|
+
) {
|
|
104
|
+
return code
|
|
105
|
+
}
|
|
106
|
+
cur = (cur as { cause?: unknown }).cause
|
|
107
|
+
}
|
|
108
|
+
return undefined
|
|
109
|
+
}
|
|
110
|
+
|
|
76
111
|
function isRetryableError(err: unknown): boolean {
|
|
77
112
|
if (err instanceof DOMException && err.name === 'AbortError') return false
|
|
113
|
+
if (tlsCertCode(err) !== undefined) return false
|
|
78
114
|
return true
|
|
79
115
|
}
|
|
80
116
|
|
|
@@ -238,6 +274,19 @@ export async function fetchWithRetry(
|
|
|
238
274
|
`API Error: No response from API (timed out after ${Math.round(timeout / 1000)}s)`,
|
|
239
275
|
)
|
|
240
276
|
}
|
|
277
|
+
const certCode = tlsCertCode(err)
|
|
278
|
+
if (certCode) {
|
|
279
|
+
let host = url
|
|
280
|
+
try {
|
|
281
|
+
host = new URL(url).host
|
|
282
|
+
} catch {
|
|
283
|
+
/* keep the raw URL in the message */
|
|
284
|
+
}
|
|
285
|
+
throw new Error(
|
|
286
|
+
`API Error: TLS certificate rejected (${certCode}) for ${host}. ` +
|
|
287
|
+
'The certificate is what it is — check the endpoint or the provider base URL.',
|
|
288
|
+
)
|
|
289
|
+
}
|
|
241
290
|
throw err
|
|
242
291
|
}
|
|
243
292
|
await sleep(baseDelay * Math.pow(2, attempt))
|
|
@@ -9,6 +9,32 @@ import {
|
|
|
9
9
|
readErrorBody,
|
|
10
10
|
} from './fetch-utils'
|
|
11
11
|
import { OLLAMA_PRESET_MODELS } from '../shared/constants'
|
|
12
|
+
import { toWellFormed } from '../shared/sanitize'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* `JSON.stringify` a tool call's input with lone surrogates made well-formed.
|
|
16
|
+
*
|
|
17
|
+
* Tool arguments are re-sent with every later request, so one broken half of an
|
|
18
|
+
* emoji in a parameter name fails every turn after it — strict JSON parsers
|
|
19
|
+
* reject the bare `\uD800` escape `JSON.stringify` produces for it. Repaired at
|
|
20
|
+
* the point of serialization rather than at ingest: the value still reaches the
|
|
21
|
+
* tool as the model wrote it, and the transcript on disk keeps what happened.
|
|
22
|
+
*/
|
|
23
|
+
export function serializeToolArguments(input: unknown): string {
|
|
24
|
+
const walk = (value: unknown): unknown => {
|
|
25
|
+
if (typeof value === 'string') return toWellFormed(value)
|
|
26
|
+
if (Array.isArray(value)) return value.map(walk)
|
|
27
|
+
if (value && typeof value === 'object') {
|
|
28
|
+
const out: Record<string, unknown> = {}
|
|
29
|
+
for (const [key, v] of Object.entries(value as Record<string, unknown>)) {
|
|
30
|
+
out[toWellFormed(key)] = walk(v)
|
|
31
|
+
}
|
|
32
|
+
return out
|
|
33
|
+
}
|
|
34
|
+
return value
|
|
35
|
+
}
|
|
36
|
+
return JSON.stringify(walk(input))
|
|
37
|
+
}
|
|
12
38
|
|
|
13
39
|
export class OpenAICompatProvider implements ProviderInstance {
|
|
14
40
|
constructor(public config: ProviderConfig) {}
|
|
@@ -371,7 +397,7 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
371
397
|
type: 'function',
|
|
372
398
|
function: {
|
|
373
399
|
name: tu.name,
|
|
374
|
-
arguments:
|
|
400
|
+
arguments: serializeToolArguments(tu.input),
|
|
375
401
|
},
|
|
376
402
|
})),
|
|
377
403
|
// DeepSeek V4 thinking mode: every assistant message needs reasoning_content
|
|
@@ -413,7 +439,7 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
413
439
|
type: 'function',
|
|
414
440
|
function: {
|
|
415
441
|
name: tu.name,
|
|
416
|
-
arguments:
|
|
442
|
+
arguments: serializeToolArguments(tu.input),
|
|
417
443
|
},
|
|
418
444
|
})),
|
|
419
445
|
// DeepSeek V4 thinking mode: every assistant message needs reasoning_content
|
package/src/shared/git-env.ts
CHANGED
|
@@ -1,18 +1,42 @@
|
|
|
1
|
+
import { DEFAULT_CREDENTIAL_MASKING_CONFIG } from '../config/defaults'
|
|
2
|
+
import { stripEnv } from '../core/credential-masker/env-filter'
|
|
3
|
+
|
|
1
4
|
/**
|
|
2
|
-
* Environment for
|
|
3
|
-
*
|
|
4
|
-
* run in the user's shell.
|
|
5
|
+
* Environment for processes **this program runs on its own behalf** (creating a
|
|
6
|
+
* worktree, reading the branch, searching with ripgrep, …) — as opposed to
|
|
7
|
+
* commands the model asked to run in the user's shell.
|
|
5
8
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* `
|
|
14
|
-
*
|
|
9
|
+
* Two things are true of these children:
|
|
10
|
+
*
|
|
11
|
+
* 1. **They never need the user's credentials.** A provider API key or token in
|
|
12
|
+
* their environment is not used by them — but it *is* readable by whatever
|
|
13
|
+
* they run: a git credential helper, a `pre-commit` hook, a `.git/config`
|
|
14
|
+
* `filter.*` driver. The keys are ours to keep, so they are stripped rather
|
|
15
|
+
* than handed down (the model's shell keeps the masking contract instead —
|
|
16
|
+
* see `filterEnv`).
|
|
17
|
+
* 2. **They derive no correctness from replace refs.** `GIT_NO_REPLACE_OBJECTS=1`
|
|
18
|
+
* makes git ignore `refs/replace/*`. A replace ref rewrites what a commit
|
|
19
|
+
* *appears to be*: `git replace <a> <b>` makes every reader of `<a>` see
|
|
20
|
+
* `<b>`'s tree, so a checkout / `worktree add` produced from that view
|
|
21
|
+
* contains different files than the real object graph. These are local refs
|
|
22
|
+
* that any process in the repository can write, and this program derives no
|
|
23
|
+
* correctness from replaying them — the isolation boundary (`enter-worktree`,
|
|
24
|
+
* workflow agents, `/fork`, the CRSI sandbox) has to be built from true
|
|
25
|
+
* history. `git` itself still accepts the env var as an escape hatch, so
|
|
26
|
+
* nothing here breaks a repository that genuinely relies on replacements in
|
|
27
|
+
* a user's shell.
|
|
28
|
+
*/
|
|
29
|
+
export function internalProcessEnv(): NodeJS.ProcessEnv {
|
|
30
|
+
return stripEnv(
|
|
31
|
+
process.env as Record<string, string | undefined>,
|
|
32
|
+
DEFAULT_CREDENTIAL_MASKING_CONFIG,
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* `internalProcessEnv()` plus the git-specific replace-ref guard. Kept as a
|
|
38
|
+
* separate name because the reason for the guard is git's, not the credentials'.
|
|
15
39
|
*/
|
|
16
40
|
export function internalGitEnv(): NodeJS.ProcessEnv {
|
|
17
|
-
return { ...
|
|
41
|
+
return { ...internalProcessEnv(), GIT_NO_REPLACE_OBJECTS: '1' }
|
|
18
42
|
}
|
|
@@ -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.33' 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 = 4706 as const
|
package/src/shared/sanitize.ts
CHANGED
|
@@ -311,6 +311,23 @@ export function safeSlice(text: string, max: number): string {
|
|
|
311
311
|
return text.slice(0, end)
|
|
312
312
|
}
|
|
313
313
|
|
|
314
|
+
/**
|
|
315
|
+
* Replace lone UTF-16 surrogates with U+FFFD, leaving valid pairs untouched.
|
|
316
|
+
*
|
|
317
|
+
* `JSON.stringify` emits a lone surrogate as a bare `\uD83D` escape (well-formed
|
|
318
|
+
* stringify does not repair it — it only guarantees *deterministic* output). That
|
|
319
|
+
* escape is what strict JSON parsers reject, so one broken half of an emoji
|
|
320
|
+
* picked up from a tool call would be re-sent with every later request and fail
|
|
321
|
+
* the whole turn. A surrogate that already lost its partner cannot be recovered;
|
|
322
|
+
* the replacement character at least serializes.
|
|
323
|
+
*/
|
|
324
|
+
export function toWellFormed(text: string): string {
|
|
325
|
+
return text.replace(
|
|
326
|
+
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,
|
|
327
|
+
'�',
|
|
328
|
+
)
|
|
329
|
+
}
|
|
330
|
+
|
|
314
331
|
/**
|
|
315
332
|
* Full command sanitization pipeline for permission checks.
|
|
316
333
|
* Applies in order:
|
|
@@ -40,6 +40,19 @@ export async function browserSnapshot(): Promise<string> {
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
export async function browserClick(uid: string): Promise<string> {
|
|
43
|
+
// `uid` goes inside a CSS attribute selector. A quote — or an escape that
|
|
44
|
+
// decodes to one — closes the string early and hands the rest of the value to
|
|
45
|
+
// Playwright's selector parser as new CSS, which is a model-supplied value
|
|
46
|
+
// reaching a different layer than the page node it names. Every uid we emit is
|
|
47
|
+
// alphanumeric, so anything else is a respelling error: say what shape is
|
|
48
|
+
// expected rather than trying to escape it.
|
|
49
|
+
if (!/^[A-Za-z0-9_-]+$/.test(uid)) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`Invalid element uid ${JSON.stringify(uid)}: expected a plain element id ` +
|
|
52
|
+
'([A-Za-z0-9_-]), not a JSON string or an escaped selector. ' +
|
|
53
|
+
'Take the uid from browser_snapshot and pass it unquoted.',
|
|
54
|
+
)
|
|
55
|
+
}
|
|
43
56
|
const page = (await getPage()) as {
|
|
44
57
|
locator: (s: string) => { click: () => Promise<void> }
|
|
45
58
|
}
|
package/src/tools/file/edit.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFileSync, closeSync, constants } from 'node:fs'
|
|
1
|
+
import { readFileSync, closeSync, constants, fstatSync } from 'node:fs'
|
|
2
2
|
import type { ToolDefinition } from '../../shared/index.ts'
|
|
3
3
|
import { resolveSafe } from '../../security/path'
|
|
4
4
|
import { openNoFollow, writeFileNoFollow, isSymlinkLoop, isValidUtf8 } from '../../security/fd'
|
|
@@ -104,9 +104,11 @@ export const editTool: ToolDefinition = {
|
|
|
104
104
|
}
|
|
105
105
|
|
|
106
106
|
// O_NOFOLLOW: fail closed on a symlink swapped in after resolveSafe (TOCTOU).
|
|
107
|
+
// O_NONBLOCK: opening a FIFO blocks until a writer appears, and no timer or
|
|
108
|
+
// signal handler can run inside a synchronous open — same gate as Read.
|
|
107
109
|
let rfd: number
|
|
108
110
|
try {
|
|
109
|
-
rfd = openNoFollow(filePath, constants.O_RDONLY)
|
|
111
|
+
rfd = openNoFollow(filePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
|
|
110
112
|
} catch (err) {
|
|
111
113
|
if (isSymlinkLoop(err)) {
|
|
112
114
|
return { success: false, content: '', error: `Path is a symbolic link: ${filePath}` }
|
|
@@ -115,6 +117,16 @@ export const editTool: ToolDefinition = {
|
|
|
115
117
|
}
|
|
116
118
|
let content: string
|
|
117
119
|
try {
|
|
120
|
+
// O_NONBLOCK only got us past the *open*. It does not bound the read:
|
|
121
|
+
// `/dev/zero` yields bytes forever (OOM) and a FIFO yields whatever a
|
|
122
|
+
// writer chooses to send. Refuse on file type, not on size.
|
|
123
|
+
if (!fstatSync(rfd).isFile()) {
|
|
124
|
+
return {
|
|
125
|
+
success: false,
|
|
126
|
+
content: '',
|
|
127
|
+
error: `Path is not a regular file (FIFO, socket or device): ${filePath}`,
|
|
128
|
+
}
|
|
129
|
+
}
|
|
118
130
|
const raw = readFileSync(rfd)
|
|
119
131
|
if (!isValidUtf8(raw)) {
|
|
120
132
|
return {
|
|
@@ -181,7 +193,11 @@ export const editTool: ToolDefinition = {
|
|
|
181
193
|
// O_NOFOLLOW: reject a symlink swapped in after the read (TOCTOU) instead of
|
|
182
194
|
// writing through it to an out-of-workspace target.
|
|
183
195
|
try {
|
|
184
|
-
writeFileNoFollow(
|
|
196
|
+
writeFileNoFollow(
|
|
197
|
+
filePath,
|
|
198
|
+
result,
|
|
199
|
+
constants.O_WRONLY | constants.O_TRUNC | (constants.O_NONBLOCK ?? 0),
|
|
200
|
+
)
|
|
185
201
|
} catch (err) {
|
|
186
202
|
if (isSymlinkLoop(err)) {
|
|
187
203
|
return { success: false, content: '', error: `Path is a symbolic link: ${filePath}` }
|
package/src/tools/file/grep.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { Service } from '../../vajra'
|
|
|
6
6
|
import { toolKey } from '../seam'
|
|
7
7
|
import { withValidation } from '../validation'
|
|
8
8
|
import { maskSearchOutput } from '../../core/credential-masker'
|
|
9
|
+
import { internalProcessEnv } from '../../shared/git-env'
|
|
9
10
|
|
|
10
11
|
/** Grep stall guard: a search over a huge tree (or a pathological regex) must
|
|
11
12
|
* not hang the session for minutes. Matches the Bash tool's 120s ceiling. */
|
|
@@ -30,7 +31,10 @@ export async function runSearch(
|
|
|
30
31
|
cwd: string,
|
|
31
32
|
timeoutMs: number,
|
|
32
33
|
): Promise<{ stdout: string; stderr: string; timedOut: boolean; exitCode: number | null }> {
|
|
33
|
-
|
|
34
|
+
// Same reasoning as `internalGitEnv`: this search is ours, not the user's
|
|
35
|
+
// shell — ripgrep never needs an API key, and handing one down only makes it
|
|
36
|
+
// reachable from a config file or a `--pre` child of the search.
|
|
37
|
+
const proc = Bun.spawn(cmd, { cwd, stdout: 'pipe', stderr: 'pipe', env: internalProcessEnv() })
|
|
34
38
|
let timedOut = false
|
|
35
39
|
const timers: ReturnType<typeof setTimeout>[] = []
|
|
36
40
|
timers.push(
|
package/src/tools/file/write.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { dirname } from 'node:path'
|
|
|
3
3
|
import type { ToolDefinition } from '../../shared/index.ts'
|
|
4
4
|
import { resolveSafe } from '../../security/path'
|
|
5
5
|
import { writeFileNoFollow, isSymlinkLoop, isValidUtf8 } from '../../security/fd'
|
|
6
|
+
import { isRegularFile } from '../../shared/regular-file'
|
|
6
7
|
|
|
7
8
|
export const writeTool: ToolDefinition = {
|
|
8
9
|
name: 'Write',
|
|
@@ -33,6 +34,20 @@ export const writeTool: ToolDefinition = {
|
|
|
33
34
|
|
|
34
35
|
// ── Read-before-write safety check ──
|
|
35
36
|
const fileExists = existsSync(filePath)
|
|
37
|
+
|
|
38
|
+
// `existsSync` is true for a FIFO, socket, device node or directory, and
|
|
39
|
+
// none of those is a file this tool can overwrite: reading one to probe for
|
|
40
|
+
// non-UTF-8 bytes blocks forever on a writer-less FIFO (no timer can fire
|
|
41
|
+
// inside a synchronous read) and streams `/dev/zero` until memory runs out.
|
|
42
|
+
// Report the type — "not read this session" would be the wrong reason.
|
|
43
|
+
if (fileExists && !isRegularFile(filePath)) {
|
|
44
|
+
return {
|
|
45
|
+
success: false,
|
|
46
|
+
content: '',
|
|
47
|
+
error: `Path is not a regular file (FIFO, socket or device): ${filePath}`,
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
36
51
|
const wasRead = ctx.readFiles?.has(filePath) ?? false // fail closed: no tracking = not read
|
|
37
52
|
if (fileExists && !wasRead) {
|
|
38
53
|
return {
|
|
@@ -89,7 +104,9 @@ export const writeTool: ToolDefinition = {
|
|
|
89
104
|
writeFileNoFollow(
|
|
90
105
|
filePath,
|
|
91
106
|
content,
|
|
92
|
-
|
|
107
|
+
// O_NONBLOCK: a FIFO swapped in after the type check would otherwise
|
|
108
|
+
// block this open until a reader appears — fail with ENXIO instead.
|
|
109
|
+
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NONBLOCK ?? 0),
|
|
93
110
|
)
|
|
94
111
|
} catch (err) {
|
|
95
112
|
if (isSymlinkLoop(err)) {
|
|
@@ -263,6 +263,18 @@ export const webFetchTool: ToolDefinition = {
|
|
|
263
263
|
required: ['url'],
|
|
264
264
|
},
|
|
265
265
|
async execute(params, _ctx) {
|
|
266
|
+
// Rechecked at call time, not only when the registry was built: the
|
|
267
|
+
// registration filter drops this tool when the switch is on at startup, but
|
|
268
|
+
// a policy that turns it on later (or any caller holding the tool directly)
|
|
269
|
+
// must not still reach the network. Same variable, same `'1'` — this can
|
|
270
|
+
// only refuse a call the registry would have refused, never widen it.
|
|
271
|
+
if (process.env.MIPHAM_DISABLE_WEB_FETCH === '1') {
|
|
272
|
+
return {
|
|
273
|
+
success: false,
|
|
274
|
+
content: '',
|
|
275
|
+
error: 'WebFetch is disabled (MIPHAM_DISABLE_WEB_FETCH=1).',
|
|
276
|
+
}
|
|
277
|
+
}
|
|
266
278
|
const rawUrl = params.url as string
|
|
267
279
|
const prompt = (params.prompt as string) || ''
|
|
268
280
|
const offset = Math.max(0, Number(params.offset) || 0)
|
|
@@ -10,6 +10,25 @@ import type { ToolDefinition } from '../../shared/index.ts'
|
|
|
10
10
|
import { McpClient } from '../../mcp/client'
|
|
11
11
|
import { capMcpText } from '../../mcp/instructions'
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* Names a search query may be a *typo'd spelling of a built-in* tool, in which
|
|
15
|
+
* case the right answer is "that one is already on your desk, just call it" —
|
|
16
|
+
* not "no tools matching". `WebSearch`, `web_search` and `web search` are the
|
|
17
|
+
* same tool to a model reaching for it by name.
|
|
18
|
+
*/
|
|
19
|
+
export function builtInToolMatches(
|
|
20
|
+
query: string,
|
|
21
|
+
registry: Map<string, ToolDefinition> | undefined,
|
|
22
|
+
): string[] {
|
|
23
|
+
const q = normalizeToolName(query)
|
|
24
|
+
if (!registry || q.length < 2) return []
|
|
25
|
+
return [...registry.keys()].filter((name) => normalizeToolName(name).includes(q))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function normalizeToolName(value: string): string {
|
|
29
|
+
return value.toLowerCase().replace(/[^a-z0-9]/g, '')
|
|
30
|
+
}
|
|
31
|
+
|
|
13
32
|
export const toolSearchTool: ToolDefinition = {
|
|
14
33
|
name: 'ToolSearch',
|
|
15
34
|
description:
|
|
@@ -37,7 +56,7 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
37
56
|
},
|
|
38
57
|
required: [],
|
|
39
58
|
},
|
|
40
|
-
async execute(params,
|
|
59
|
+
async execute(params, ctx) {
|
|
41
60
|
const query = ((params.query as string) || '').toLowerCase()
|
|
42
61
|
const serverFilter = (params.server as string) || ''
|
|
43
62
|
const limit = (params.limit as number) || 20
|
|
@@ -99,12 +118,25 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
99
118
|
}
|
|
100
119
|
|
|
101
120
|
if (matches.length === 0) {
|
|
121
|
+
// A zero-hit answer is the wrong answer when the name the caller searched
|
|
122
|
+
// for is a *built-in* tool: nothing is missing, it was never an MCP tool.
|
|
123
|
+
// Saying only "no match" sends the model looking for a server to install
|
|
124
|
+
// for a tool it could have called.
|
|
125
|
+
const alreadyAvailable = builtInToolMatches(query, ctx.toolRegistry)
|
|
126
|
+
const hint =
|
|
127
|
+
alreadyAvailable.length > 0
|
|
128
|
+
? `\n\n"${query}" matches a built-in tool that is already available — ` +
|
|
129
|
+
`call ${alreadyAvailable.map((n) => `\`${n}\``).join(', ')} directly; ` +
|
|
130
|
+
`ToolSearch only covers MCP servers.`
|
|
131
|
+
: ''
|
|
102
132
|
return {
|
|
103
133
|
success: true,
|
|
104
134
|
content:
|
|
105
135
|
`── MCP Tool Search ──\n\n` +
|
|
106
|
-
`No tools matching "${query}" across ${servers.length} server(s)
|
|
107
|
-
|
|
136
|
+
`No tools matching "${query}" across ${servers.length} server(s).${hint}\n\n` +
|
|
137
|
+
(alreadyAvailable.length > 0
|
|
138
|
+
? `Try a different query for MCP tools, or omit the query to list all MCP tools.`
|
|
139
|
+
: `Try a different query, or omit the query to list all tools.`),
|
|
108
140
|
}
|
|
109
141
|
}
|
|
110
142
|
|
package/src/ui/app.tsx
CHANGED
|
@@ -90,6 +90,13 @@ export interface ToolMeta {
|
|
|
90
90
|
originalName?: string
|
|
91
91
|
/** Held back by the auto-mode classifier — rendered as a dim "Not run" row (296-056). */
|
|
92
92
|
notRun?: boolean
|
|
93
|
+
/**
|
|
94
|
+
* The call finished without producing output (stopped, or a tool that returns
|
|
95
|
+
* nothing). Rendered as "No result recorded" — without it the collapsed group
|
|
96
|
+
* keeps the call row and says nothing about how it ended, which reads as a
|
|
97
|
+
* call still running.
|
|
98
|
+
*/
|
|
99
|
+
noResult?: boolean
|
|
93
100
|
}
|
|
94
101
|
|
|
95
102
|
export interface ChatMessage {
|
|
@@ -185,6 +192,31 @@ export function cyclePermissionMode(
|
|
|
185
192
|
return permission.getMode()
|
|
186
193
|
}
|
|
187
194
|
|
|
195
|
+
/**
|
|
196
|
+
* A retried turn (`chunk.restart`) supersedes the attempt before it.
|
|
197
|
+
*
|
|
198
|
+
* The engine drops that attempt's accumulated text and tool calls — but the
|
|
199
|
+
* engine's accumulator is not the screen. The bubble the attempt opened stays
|
|
200
|
+
* in the message list, and the retry's text appends to it, so the user reads a
|
|
201
|
+
* reply the model never finished as the beginning of the answer that replaced
|
|
202
|
+
* it. Same class as a stale line left by any retry: what was discarded is still
|
|
203
|
+
* on display.
|
|
204
|
+
*
|
|
205
|
+
* `bubble` is the assistant message *object* this attempt pushed, or `null` if
|
|
206
|
+
* it never got to text (a failure during reasoning has nothing to remove).
|
|
207
|
+
* Identity, not position: tool-result rows can sit after the bubble within the
|
|
208
|
+
* same turn, and a previous answer with identical text must not be the one that
|
|
209
|
+
* disappears.
|
|
210
|
+
*/
|
|
211
|
+
export function dropSupersededAttempt<T extends { role: string }>(
|
|
212
|
+
messages: T[],
|
|
213
|
+
bubble: T | null,
|
|
214
|
+
): T[] {
|
|
215
|
+
if (!bubble || bubble.role !== 'assistant') return messages
|
|
216
|
+
const idx = messages.indexOf(bubble)
|
|
217
|
+
return idx === -1 ? messages : messages.filter((_, i) => i !== idx)
|
|
218
|
+
}
|
|
219
|
+
|
|
188
220
|
/** 预览截断按 UTF-16 码元计数,落点若正好夹在一个代理对中间,切完就留下
|
|
189
221
|
* **半个** emoji(终端渲染成 U+FFFD)。落点是高代理时后退一个码元即可。 */
|
|
190
222
|
export function truncateForDisplay(text: string, max: number): string {
|
|
@@ -664,8 +696,36 @@ export function App({
|
|
|
664
696
|
}
|
|
665
697
|
}
|
|
666
698
|
|
|
699
|
+
// The assistant message object the current attempt pushed, so a retry can
|
|
700
|
+
// remove exactly that one (see `dropSupersededAttempt`). Cleared whenever
|
|
701
|
+
// `isNewTurn` flips, because the next text run opens a fresh bubble.
|
|
702
|
+
let turnBubble: ChatMessage | null = null
|
|
703
|
+
|
|
667
704
|
try {
|
|
668
705
|
for await (const chunk of engine.process(input, ctrl.signal)) {
|
|
706
|
+
if (chunk.restart) {
|
|
707
|
+
// A retried turn: the engine drops what the failed attempt
|
|
708
|
+
// accumulated, and the screen has to drop its bubble too — otherwise
|
|
709
|
+
// the retry's answer is appended to a reply the model never
|
|
710
|
+
// finished and the user reads the two as one.
|
|
711
|
+
const superseded = turnBubble
|
|
712
|
+
turnBubble = null
|
|
713
|
+
assistantContent = ''
|
|
714
|
+
turnContent = ''
|
|
715
|
+
isNewTurn = true
|
|
716
|
+
thinkingRef.current = ''
|
|
717
|
+
if (thinkingTimerRef.current) {
|
|
718
|
+
clearTimeout(thinkingTimerRef.current)
|
|
719
|
+
thinkingTimerRef.current = null
|
|
720
|
+
}
|
|
721
|
+
setThinkingText('')
|
|
722
|
+
if (streamBufferRef.current.timer) {
|
|
723
|
+
clearTimeout(streamBufferRef.current.timer)
|
|
724
|
+
}
|
|
725
|
+
streamBufferRef.current = { turnContent: '', isFirst: false, timer: null }
|
|
726
|
+
setMessages((prev) => dropSupersededAttempt(prev, superseded))
|
|
727
|
+
}
|
|
728
|
+
|
|
669
729
|
// Reasoning content (DeepSeek V4 thinking mode) — surface as a live
|
|
670
730
|
// "thinking" indicator so long reasoning passes don't look like a stall.
|
|
671
731
|
if (chunk.reasoning_content) {
|
|
@@ -709,10 +769,13 @@ export function App({
|
|
|
709
769
|
turnContent = chunk.content
|
|
710
770
|
isNewTurn = false
|
|
711
771
|
streamBufferRef.current = { turnContent: chunk.content, isFirst: false, timer: null }
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
772
|
+
// Keep the object: a retry removes *this* message, by identity.
|
|
773
|
+
const bubble: ChatMessage = {
|
|
774
|
+
role: 'assistant' as const,
|
|
775
|
+
content: chunk.content || '',
|
|
776
|
+
}
|
|
777
|
+
turnBubble = bubble
|
|
778
|
+
setMessages((prev) => [...prev, bubble])
|
|
716
779
|
} else {
|
|
717
780
|
turnContent += chunk.content
|
|
718
781
|
streamBufferRef.current.turnContent = turnContent
|
|
@@ -778,6 +841,8 @@ export function App({
|
|
|
778
841
|
flushStreamBuffer()
|
|
779
842
|
// Mark that next text chunk starts a new turn
|
|
780
843
|
isNewTurn = true
|
|
844
|
+
// The run that bubble held is finished; the next text opens a new one.
|
|
845
|
+
turnBubble = null
|
|
781
846
|
}
|
|
782
847
|
|
|
783
848
|
if (chunk.type === 'tool_result') {
|
|
@@ -838,6 +903,27 @@ export function App({
|
|
|
838
903
|
},
|
|
839
904
|
},
|
|
840
905
|
])
|
|
906
|
+
} else {
|
|
907
|
+
// No output at all — a stopped call, or a tool that returns
|
|
908
|
+
// nothing. The call row above stays, and without this row nothing
|
|
909
|
+
// says how it ended, so a finished call reads as one still
|
|
910
|
+
// running. The input is already on the call line; this row only
|
|
911
|
+
// has to record the ending.
|
|
912
|
+
setMessages((prev) => [
|
|
913
|
+
...prev,
|
|
914
|
+
{
|
|
915
|
+
role: 'system' as const,
|
|
916
|
+
content: '',
|
|
917
|
+
toolMeta: {
|
|
918
|
+
name: '',
|
|
919
|
+
input: '',
|
|
920
|
+
output: '',
|
|
921
|
+
collapsed: true,
|
|
922
|
+
originalName: chunk.toolUse?.name,
|
|
923
|
+
noResult: true,
|
|
924
|
+
},
|
|
925
|
+
},
|
|
926
|
+
])
|
|
841
927
|
}
|
|
842
928
|
}
|
|
843
929
|
|
package/src/ui/chat.tsx
CHANGED
|
@@ -133,6 +133,14 @@ const MessageRow = React.memo(
|
|
|
133
133
|
{t('ui.tool.not_run')}
|
|
134
134
|
{msg.toolMeta.output ? ` — ${safeSlice(display(msg.toolMeta.output), 300)}` : ''}
|
|
135
135
|
</Text>
|
|
136
|
+
) : msg.toolMeta.noResult ? (
|
|
137
|
+
// The call ended without output. Saying so is the point: an empty
|
|
138
|
+
// result line is indistinguishable from a call that is still
|
|
139
|
+
// running (323-079).
|
|
140
|
+
<Text dimColor>
|
|
141
|
+
{' ⎿ '}
|
|
142
|
+
{t('ui.tool.no_result_recorded')}
|
|
143
|
+
</Text>
|
|
136
144
|
) : msg.toolMeta.output ? (
|
|
137
145
|
<Text dimColor>
|
|
138
146
|
{' ⎿ '}
|
|
@@ -256,8 +264,10 @@ function compactToolGroups(messages: ChatMessage[]): ChatMessage[] {
|
|
|
256
264
|
continue
|
|
257
265
|
}
|
|
258
266
|
|
|
259
|
-
// Tool result (no name, has output) → merge
|
|
260
|
-
|
|
267
|
+
// Tool result (no name, has output or records its ending) → merge into
|
|
268
|
+
// the current tool. `noResult` rows carry no output, so a merge condition
|
|
269
|
+
// that only looked at `output` left them as separate nameless rows.
|
|
270
|
+
if (msg.toolMeta && !msg.toolMeta.name && (msg.toolMeta.output || msg.toolMeta.noResult)) {
|
|
261
271
|
if (current) {
|
|
262
272
|
current = {
|
|
263
273
|
...current,
|
|
@@ -268,6 +278,7 @@ function compactToolGroups(messages: ChatMessage[]): ChatMessage[] {
|
|
|
268
278
|
// 结果行上的标记必须跟着合并走:合并把结果行的 toolMeta 并进工具调用行,
|
|
269
279
|
// 漏掉它,`notRun` 就停在**没人渲染的那一份**上(296-056)。
|
|
270
280
|
...(msg.toolMeta.notRun ? { notRun: true } : {}),
|
|
281
|
+
...(msg.toolMeta.noResult ? { noResult: true } : {}),
|
|
271
282
|
},
|
|
272
283
|
}
|
|
273
284
|
}
|
|
@@ -281,7 +292,7 @@ function compactToolGroups(messages: ChatMessage[]): ChatMessage[] {
|
|
|
281
292
|
current = null
|
|
282
293
|
}
|
|
283
294
|
// Skip orphan tool-result messages without a preceding tool_use
|
|
284
|
-
if (msg.toolMeta && !msg.toolMeta.name && msg.toolMeta.output) {
|
|
295
|
+
if (msg.toolMeta && !msg.toolMeta.name && (msg.toolMeta.output || msg.toolMeta.noResult)) {
|
|
285
296
|
continue
|
|
286
297
|
}
|
|
287
298
|
result.push(msg)
|