@miphamai/cli 0.85.10 → 0.85.12
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/sub-agent.ts +49 -1
- package/src/commands/autoloop-journal.ts +16 -1
- package/src/config/loader.ts +23 -3
- package/src/core/context-microcompact.ts +3 -5
- package/src/core/context.ts +58 -16
- package/src/core/credential-masker/output-scrub.ts +7 -1
- package/src/core/crsi-producer.ts +86 -6
- package/src/core/crsi-sandbox.ts +101 -49
- package/src/core/engine.ts +108 -26
- package/src/core/hooks-executor.ts +165 -16
- package/src/core/instructions.ts +6 -5
- package/src/core/memory/memory-manager.ts +9 -1
- package/src/core/permission-config.ts +28 -0
- package/src/core/permission.ts +51 -5
- package/src/core/rules-loader.ts +96 -5
- package/src/core/task-performance.ts +32 -4
- package/src/i18n-core/locales/en-US.json +2 -0
- package/src/i18n-core/locales/zh-CN.json +2 -0
- package/src/mcp/registry.ts +8 -0
- package/src/plugin/plugin-loader.ts +10 -9
- package/src/providers/anthropic.ts +11 -3
- package/src/providers/fetch-utils.ts +34 -1
- package/src/providers/openai-compat.ts +24 -2
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +65 -0
- package/src/shared/types.ts +30 -0
- package/src/tools/agent/agent.ts +18 -3
- package/src/tools/agent/exit-plan.ts +49 -9
- package/src/tools/artifact/artifact.ts +0 -1
- package/src/tools/exec/bash.ts +28 -3
- package/src/tools/index.ts +7 -1
- package/src/tools/network/web-fetch.ts +2 -1
- package/src/tools/system/tool-search.ts +1 -1
- package/src/ui/chat.tsx +2 -1
- package/src/ui/commands.ts +28 -11
- package/src/ui/input.tsx +5 -0
- package/src/workflow/event-bus.ts +13 -0
- package/src/workflow/journal.ts +8 -0
- package/src/workflow/runtime.ts +59 -11
package/src/core/instructions.ts
CHANGED
|
@@ -401,11 +401,12 @@ say so explicitly instead of claiming it exists.`)
|
|
|
401
401
|
Before answering ANY question about this codebase — whether a file,
|
|
402
402
|
function, feature, or capability exists, how it works, or whether
|
|
403
403
|
something is missing — you MUST first read the actual code with the
|
|
404
|
-
Read, Grep,
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
404
|
+
Read, Grep, or Glob tools. When the repository is graft-indexed you also
|
|
405
|
+
have graft — a CLI you run through Bash, not one of your own tools. Do
|
|
406
|
+
not infer or assert from memory, naming conventions, or static tool
|
|
407
|
+
lists. If you have not read the code, say so and read it first, rather
|
|
408
|
+
than answering hastily and retracting afterwards. This applies to every
|
|
409
|
+
code question, not only research or borrow-analysis tasks.`)
|
|
409
410
|
|
|
410
411
|
// CRSI code-review 合并门 — 合并 PR 前必须先 review,勿靠「碰巧触发」
|
|
411
412
|
parts.push(`## Code-Review Merge Gate
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
} from 'node:fs'
|
|
10
10
|
import { join, extname, basename } from 'node:path'
|
|
11
11
|
import { atomicWriteFileSync } from '../../shared/atomic-write'
|
|
12
|
+
import { neutralizeInjectedMarkup } from '../../shared/sanitize.ts'
|
|
12
13
|
import { similarities, findNearDuplicates } from './tfidf'
|
|
13
14
|
|
|
14
15
|
export interface MemoryMetadata {
|
|
@@ -368,7 +369,14 @@ export class MemoryManager {
|
|
|
368
369
|
|
|
369
370
|
let tokenBudget = 50 // opening tags
|
|
370
371
|
for (const entry of relevant) {
|
|
371
|
-
|
|
372
|
+
// Both halves are file contents, written by earlier sessions — worth
|
|
373
|
+
// neutralizing before they land inside the `<system-reminder>` wrapper below.
|
|
374
|
+
// Neutralize *before* the 200-char slice, so a tag straddling the boundary is
|
|
375
|
+
// removed whole instead of being truncated into an unterminated `<…` that the
|
|
376
|
+
// wrapper's own `>` could then complete.
|
|
377
|
+
const name = neutralizeInjectedMarkup(entry.name)
|
|
378
|
+
const content = neutralizeInjectedMarkup(entry.content).slice(0, 200)
|
|
379
|
+
const line = `- ${name}: ${content}`
|
|
372
380
|
const lineTokens = Math.ceil(line.length / 4)
|
|
373
381
|
if (tokenBudget + lineTokens > effectiveMaxTokens) break
|
|
374
382
|
lines.push(line)
|
|
@@ -310,6 +310,34 @@ export function clampMode(
|
|
|
310
310
|
return allowed[0] ?? 'default'
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
+
/**
|
|
314
|
+
* 「`desired` **确定**不比 `ceiling` 宽」—— 仓库带来的 agent 定义能过的那道门。
|
|
315
|
+
*
|
|
316
|
+
* **刻意不用 `PERMISSION_MODE_HIERARCHY.indexOf` 判宽窄。** 层级表自己(本文件顶部)写明:
|
|
317
|
+
* 那几档**在现实中不是全序**,数组只承载「能测出来的那几条关系」—— `acceptEdits` 与
|
|
318
|
+
* `default` **不可比**(前者自动批 Write/Edit,后者自动批 git/task/web-fetch 这类
|
|
319
|
+
* `'self'` 工具),`auto` 的静态基线什么都不批、只因运行期分类器可能放行更多才被摆到
|
|
320
|
+
* `acceptEdits` 之上。拿下标当安全顶会**两个方向都错**:
|
|
321
|
+
*
|
|
322
|
+
* - **漏判**(危险的那一侧):父 `acceptEdits` + 项目级声明 `default`(下标 1 < 2 ⇒ 放过),
|
|
323
|
+
* 或父 `auto`(无分类器)+ 声明 `acceptEdits`(下标 2 < 3 ⇒ 放过)—— 两者都让子代理
|
|
324
|
+
* 比派它的会话**更宽**,而那正是要挡的。
|
|
325
|
+
* - **误判**(安全但多挡):父 `default` + 声明 `acceptEdits`。
|
|
326
|
+
*
|
|
327
|
+
* 故改用**性质表**:只放行能证明是子集的三类,其余一律 fail-closed。
|
|
328
|
+
* - `plan` —— 层级表已证它「严格最窄」,是任何档的子集;
|
|
329
|
+
* - 与父同档 —— 即 `inherit` 解析后的形状;
|
|
330
|
+
* - 父为 `bypassPermissions` —— 它不挡任何调用 ⇒ 任何档都是它的子集。
|
|
331
|
+
* 表**故意**不完备:不可比的那几对既证不出是子集,就不放行。多拒绝落在安全侧,
|
|
332
|
+
* 而「子代理比派它的会话还宽」不是。
|
|
333
|
+
*/
|
|
334
|
+
export function narrowsWithin(desired: PermissionMode, ceiling: PermissionMode): boolean {
|
|
335
|
+
if (desired === ceiling) return true
|
|
336
|
+
if (desired === 'plan') return true
|
|
337
|
+
if (ceiling === 'bypassPermissions') return true
|
|
338
|
+
return false
|
|
339
|
+
}
|
|
340
|
+
|
|
313
341
|
/**
|
|
314
342
|
* 从**仓库带来的** `forbiddenModes` 里挑出会造成「放宽」的条目 —— 判据是 `clampMode` 的回落。
|
|
315
343
|
*
|
package/src/core/permission.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
loadPermissionConfig,
|
|
14
14
|
nextMode,
|
|
15
15
|
clampMode,
|
|
16
|
+
narrowsWithin,
|
|
16
17
|
normalizeRestrictions,
|
|
17
18
|
ALL_MODES,
|
|
18
19
|
} from './permission-config'
|
|
@@ -184,6 +185,14 @@ export class PermissionSystem {
|
|
|
184
185
|
private restrictionWarnings: string[] = []
|
|
185
186
|
/** Unrecognized `permission:` value from the last `setDefaultLevel` — third of the warning family. */
|
|
186
187
|
private levelWarnings: string[] = []
|
|
188
|
+
/**
|
|
189
|
+
* 仓库带来的 agent 定义请求了比父会话更宽的档、被顶回去的记录 —— 第四位。
|
|
190
|
+
*
|
|
191
|
+
* 与上面三位不同:那三位是**配置**有问题(写错了),读的是入口;这条是**输入合法、
|
|
192
|
+
* 但方向不允许**(项目级 agent 想把自己抬宽),产生在**派发那一刻**、读的是派发处
|
|
193
|
+
* (`agent/sub-agent.ts`,那里才有 agent 的名字)。故不进那两条入口的读法守卫。
|
|
194
|
+
*/
|
|
195
|
+
private agentCapWarnings: string[] = []
|
|
187
196
|
/** Legacy exact-name rules for backward compat (set via setRule with 'self' level). */
|
|
188
197
|
private legacyRules = new Map<string, PermissionLevel>()
|
|
189
198
|
/** Legacy default level from constructor when passed non-mode values like 'ask' or 'bypass'. */
|
|
@@ -339,9 +348,10 @@ export class PermissionSystem {
|
|
|
339
348
|
*
|
|
340
349
|
* Returns a new PermissionSystem instance — NOT shared with the parent.
|
|
341
350
|
*/
|
|
342
|
-
createSubAgentPermission(agentPermissionMode: string): PermissionSystem {
|
|
343
|
-
const resolvedMode = this.resolveAgentMode(agentPermissionMode)
|
|
351
|
+
createSubAgentPermission(agentPermissionMode: string, source?: string): PermissionSystem {
|
|
352
|
+
const { mode: resolvedMode, capWarning } = this.resolveAgentMode(agentPermissionMode, source)
|
|
344
353
|
const subPerm = new PermissionSystem(resolvedMode)
|
|
354
|
+
if (capWarning) subPerm.agentCapWarnings.push(capWarning)
|
|
345
355
|
|
|
346
356
|
// Propagate org restrictions to sub-agent
|
|
347
357
|
if (this.restrictions) {
|
|
@@ -377,8 +387,16 @@ export class PermissionSystem {
|
|
|
377
387
|
* Resolve an agent's permissionMode string to a clamped PermissionMode.
|
|
378
388
|
* 'inherit' means "use the parent's current mode".
|
|
379
389
|
* 'bypass' is treated as an alias for 'bypassPermissions'.
|
|
390
|
+
*
|
|
391
|
+
* `source` is the agent definition's provenance (`agent/types.ts`). Only
|
|
392
|
+
* `'project'` is capped — see the comment on the cap. Returns the warning
|
|
393
|
+
* (if any) rather than printing, so the one caller that knows the agent's
|
|
394
|
+
* *name* owns the message; the judgement stays here, in one place.
|
|
380
395
|
*/
|
|
381
|
-
private resolveAgentMode(
|
|
396
|
+
private resolveAgentMode(
|
|
397
|
+
agentMode: string,
|
|
398
|
+
source?: string,
|
|
399
|
+
): { mode: PermissionMode; capWarning?: string } {
|
|
382
400
|
// Normalize aliases
|
|
383
401
|
const normalized = agentMode === 'bypass' ? 'bypassPermissions' : agentMode
|
|
384
402
|
|
|
@@ -395,8 +413,36 @@ export class PermissionSystem {
|
|
|
395
413
|
inherit: this.mode,
|
|
396
414
|
}
|
|
397
415
|
|
|
398
|
-
|
|
399
|
-
|
|
416
|
+
let desired: PermissionMode = modeMap[normalized] || 'default'
|
|
417
|
+
let capWarning: string | undefined
|
|
418
|
+
|
|
419
|
+
// 仓库带来的东西可以**收窄**,不得**放宽** —— 与 `config/loader.ts` 的
|
|
420
|
+
// `stripProjectPermission`(项目级 config/settings 不是门)同一条判据,加上
|
|
421
|
+
// agent 定义这条当初没被那句话覆盖的路径。判据是**方向**、不是键名。
|
|
422
|
+
//
|
|
423
|
+
// 判在 `desired` 算完之后,是为了同时盖住上面那条 `|| 'default'` 回落:项目级把档位
|
|
424
|
+
// 名写错(拼错/大小写)会落到 `default`,若父档是 `plan`/`acceptEdits`,那同样是放宽。
|
|
425
|
+
//
|
|
426
|
+
// 边界(**有意**,不是遗漏):只收 `source === 'project'`。插件安装的 agent 由
|
|
427
|
+
// `plugin-loader.ts` / `claude-plugin.ts` 记为 `'user'`,是用户自己装的东西,
|
|
428
|
+
// 不在「仓库带来的」这一侧。
|
|
429
|
+
if (source === 'project' && !narrowsWithin(desired, this.mode)) {
|
|
430
|
+
capWarning =
|
|
431
|
+
`requested permission mode "${desired}", which is wider than the parent session's ` +
|
|
432
|
+
`"${this.mode}" — capped to "${this.mode}" (agent definitions from the repository may ` +
|
|
433
|
+
`narrow the approval gate, not widen it)`
|
|
434
|
+
desired = this.mode
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return { mode: clampMode(desired, this.restrictions), capWarning }
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* 被顶回去的「项目级 agent 想放宽」记录,一条一句。与 `getInvalidRestrictions()` 同形 ——
|
|
442
|
+
* 消费者在派发处(`agent/sub-agent.ts`),那里才有 agent 的名字和 stderr。
|
|
443
|
+
*/
|
|
444
|
+
getAgentCapWarnings(): string[] {
|
|
445
|
+
return this.agentCapWarnings
|
|
400
446
|
}
|
|
401
447
|
|
|
402
448
|
// ── Rule management ──
|
package/src/core/rules-loader.ts
CHANGED
|
@@ -17,12 +17,21 @@
|
|
|
17
17
|
* ---
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
|
-
import { readdirSync, readFileSync, existsSync } from 'node:fs'
|
|
20
|
+
import { readdirSync, readFileSync, existsSync, lstatSync, realpathSync } from 'node:fs'
|
|
21
21
|
import { join } from 'node:path'
|
|
22
22
|
import { globToRegexSource } from './credential-masker/matcher'
|
|
23
23
|
import { findWorktreeMarker } from './paths.ts'
|
|
24
24
|
import { MIPHAM_DIR } from '../shared/constants.ts'
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* 每个被拒的规则路径**只报告一次**(同 `core/permission-audit.ts` 的 `warnedOnce`)。
|
|
28
|
+
*
|
|
29
|
+
* 按路径去重而不是全局一次:两个坏文件是两件事。若只记一个全局布尔,daemon
|
|
30
|
+
* 那条路径(`daemon/engine-capabilities.ts` 每会话新建一只 loader)会让第二个
|
|
31
|
+
* 会话遇到同一个坏文件时一片沉默 —— 而「沉默」正是这里要消掉的东西。
|
|
32
|
+
*/
|
|
33
|
+
const reportedRefusals = new Set<string>()
|
|
34
|
+
|
|
26
35
|
interface RuleFile {
|
|
27
36
|
name: string
|
|
28
37
|
paths: string[] // glob patterns, empty = always loaded
|
|
@@ -48,12 +57,18 @@ export class RulesLoader {
|
|
|
48
57
|
* `.claude/worktrees/` is not covered.
|
|
49
58
|
*/
|
|
50
59
|
private projectRulesDir: string | null
|
|
60
|
+
/** Project directory owning `rulesDir` — i.e. `rulesDir` is `<rulesRoot>/.mipham/rules`. */
|
|
61
|
+
private rulesRoot: string
|
|
62
|
+
/** Project directory owning `projectRulesDir`; unused when that is `null`. */
|
|
63
|
+
private projectRoot: string
|
|
51
64
|
|
|
52
65
|
constructor(cwd: string) {
|
|
66
|
+
this.rulesRoot = cwd
|
|
53
67
|
this.rulesDir = join(cwd, MIPHAM_DIR, 'rules')
|
|
54
68
|
const marker = findWorktreeMarker(cwd)
|
|
55
69
|
const projectRulesDir = marker ? join(marker.root, MIPHAM_DIR, 'rules') : null
|
|
56
70
|
this.projectRulesDir = projectRulesDir === this.rulesDir ? null : projectRulesDir
|
|
71
|
+
this.projectRoot = marker?.root ?? cwd
|
|
57
72
|
}
|
|
58
73
|
|
|
59
74
|
/**
|
|
@@ -61,24 +76,93 @@ export class RulesLoader {
|
|
|
61
76
|
*/
|
|
62
77
|
load(): void {
|
|
63
78
|
this.rules = []
|
|
64
|
-
this.readDir(this.rulesDir)
|
|
65
|
-
if (this.projectRulesDir) this.readDir(this.projectRulesDir)
|
|
79
|
+
this.readDir(this.rulesDir, this.rulesRoot)
|
|
80
|
+
if (this.projectRulesDir) this.readDir(this.projectRulesDir, this.projectRoot)
|
|
66
81
|
}
|
|
67
82
|
|
|
68
83
|
/**
|
|
69
84
|
* Read every `.md` in `dir` into `this.rules`. A name already loaded wins —
|
|
70
85
|
* "nearest first": a rule the worktree defines overrides the project copy.
|
|
86
|
+
*
|
|
87
|
+
* `root` is the project directory that owns `dir` (i.e. `dir` is exactly
|
|
88
|
+
* `<root>/.mipham/rules`); it bounds what a symlink may resolve to.
|
|
89
|
+
*
|
|
90
|
+
* ### Why every path here is checked before it is read
|
|
91
|
+
*
|
|
92
|
+
* A rule's body is injected into the conversation **verbatim** and shipped to
|
|
93
|
+
* the model provider. So `.mipham/rules/*.md` is not just config — it is an
|
|
94
|
+
* **egress** path that the repository alone controls, and `readFileSync` is
|
|
95
|
+
* the point where a name becomes content. Three shapes are refused:
|
|
96
|
+
*
|
|
97
|
+
* 1. **The rules directory reached through a symlink** — `.mipham/rules ->
|
|
98
|
+
* ~/.mipham/memory` would inject the user's private notes as project
|
|
99
|
+
* rules. It has to be checked on the *directory*: `.mipham` is one segment
|
|
100
|
+
* above the entries, so no per-entry check can see it.
|
|
101
|
+
* 2. **A symlinked rule file** — `-> ~/.ssh/id_rsa`, `-> ../../.env`. Note
|
|
102
|
+
* that "resolve it and require the target to be inside the project" is
|
|
103
|
+
* *not* a safe rule: the project root is exactly where the user's own
|
|
104
|
+
* gitignored secrets live. A rule must be a plain file, not a link.
|
|
105
|
+
* 3. **A non-regular file** — `readFileSync` on a FIFO blocks until a writer
|
|
106
|
+
* appears, and `/dev/zero` reads unboundedly: both *synchronously*, at
|
|
107
|
+
* startup. Same family as the audited non-regular-file hang on the daemon
|
|
108
|
+
* token path.
|
|
109
|
+
*
|
|
110
|
+
* Refusals are **reported, not skipped silently** (once per path, on stderr —
|
|
111
|
+
* this repo's warning channel). The rules directory exists so that its
|
|
112
|
+
* contents are always obeyed; a rule that is present but not loaded must say
|
|
113
|
+
* so. `config/loader.ts`'s `stripProjectPermission` made the same call.
|
|
114
|
+
*
|
|
115
|
+
* Honest boundary: in *this* repo `.mipham/` is gitignored, so these entries
|
|
116
|
+
* cannot be committed from here — the surface is a project that tracks
|
|
117
|
+
* `.mipham/` (or one where the file is placed on disk by other means). And
|
|
118
|
+
* the check is not TOCTOU-proof: it holds at the moment of the `lstat`.
|
|
71
119
|
*/
|
|
72
|
-
private readDir(dir: string): void {
|
|
120
|
+
private readDir(dir: string, root: string): void {
|
|
73
121
|
if (!existsSync(dir)) return
|
|
122
|
+
|
|
123
|
+
// Resolved against the *resolved* root, so a symlink anywhere above the
|
|
124
|
+
// project (macOS `/var -> /private/var`, a symlinked home) is not counted —
|
|
125
|
+
// only the `<root>/.mipham/rules` tail has to be link-free.
|
|
126
|
+
try {
|
|
127
|
+
if (realpathSync(dir) !== join(realpathSync(root), MIPHAM_DIR, 'rules')) {
|
|
128
|
+
this.refuse(dir, '规则目录不是本工程的真实目录(路径中有符号链接)')
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
} catch {
|
|
132
|
+
this.refuse(dir, '无法解析规则目录的真实路径')
|
|
133
|
+
return
|
|
134
|
+
}
|
|
135
|
+
|
|
74
136
|
try {
|
|
75
137
|
const seen = new Set(this.rules.map((r) => r.name))
|
|
76
138
|
const files = readdirSync(dir).filter((f) => f.endsWith('.md'))
|
|
77
139
|
for (const file of files) {
|
|
78
140
|
const name = file.replace(/\.md$/, '')
|
|
79
141
|
if (seen.has(name)) continue
|
|
142
|
+
const full = join(dir, file)
|
|
143
|
+
|
|
144
|
+
let entry
|
|
145
|
+
try {
|
|
146
|
+
entry = lstatSync(full)
|
|
147
|
+
} catch {
|
|
148
|
+
this.refuse(full, '无法读取文件状态')
|
|
149
|
+
continue
|
|
150
|
+
}
|
|
151
|
+
// `lstat` (not `stat`) — so a symlink reports as itself, not as its
|
|
152
|
+
// target. The `isFile` gate below would refuse a link anyway (a link is
|
|
153
|
+
// not a regular file); this branch exists to say **which** shape it was,
|
|
154
|
+
// because "refused" with the wrong reason is its own kind of silent.
|
|
155
|
+
if (entry.isSymbolicLink()) {
|
|
156
|
+
this.refuse(full, '是符号链接 —— 规则必须是普通文件')
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
if (!entry.isFile()) {
|
|
160
|
+
this.refuse(full, '不是普通文件(目录/FIFO/设备)')
|
|
161
|
+
continue
|
|
162
|
+
}
|
|
163
|
+
|
|
80
164
|
try {
|
|
81
|
-
const raw = readFileSync(
|
|
165
|
+
const raw = readFileSync(full, 'utf-8')
|
|
82
166
|
const { paths, description, content } = this.parseRule(raw, file)
|
|
83
167
|
this.rules.push({ name, paths, description, content })
|
|
84
168
|
seen.add(name)
|
|
@@ -91,6 +175,13 @@ export class RulesLoader {
|
|
|
91
175
|
}
|
|
92
176
|
}
|
|
93
177
|
|
|
178
|
+
/** Report a refused rule path once per process, on stderr. */
|
|
179
|
+
private refuse(path: string, reason: string): void {
|
|
180
|
+
if (reportedRefusals.has(path)) return
|
|
181
|
+
reportedRefusals.add(path)
|
|
182
|
+
process.stderr.write(`⚠️ 规则未被加载(之后不再重复报告): ${path} — ${reason}\n`)
|
|
183
|
+
}
|
|
184
|
+
|
|
94
185
|
/**
|
|
95
186
|
* Get rules that match the given file paths.
|
|
96
187
|
* Rules with no paths filter ("always") are always included.
|
|
@@ -60,14 +60,26 @@ export interface TaskPerformanceResult {
|
|
|
60
60
|
description: string
|
|
61
61
|
passed: boolean
|
|
62
62
|
detail?: string
|
|
63
|
+
/**
|
|
64
|
+
* The generation hit the output cap, so the code is incomplete by construction and
|
|
65
|
+
* a failing test cannot distinguish "did not solve it" from "was cut off". Kept on
|
|
66
|
+
* the result and excluded from `score` — mixing the two biases the readout low.
|
|
67
|
+
*/
|
|
68
|
+
truncated?: boolean
|
|
63
69
|
}
|
|
64
70
|
|
|
65
71
|
export interface TaskPerformanceReport {
|
|
66
72
|
total: number
|
|
67
73
|
passed: number
|
|
74
|
+
/**
|
|
75
|
+
* Percent of **non-truncated** tasks that passed (100 when there are none). A
|
|
76
|
+
* truncated task is reported in `total`/`truncated` but never scored.
|
|
77
|
+
*/
|
|
68
78
|
score: number
|
|
69
79
|
results: TaskPerformanceResult[]
|
|
70
80
|
failures: string[]
|
|
81
|
+
/** Tasks whose generation was cut off at the output cap; counted, not scored. */
|
|
82
|
+
truncated: number
|
|
71
83
|
/** B2 代价维:整轮(LLM 生成 + 冻结测试判定)的墙钟耗时。只记录,不参与任何判定。 */
|
|
72
84
|
durationMs: number
|
|
73
85
|
}
|
|
@@ -82,8 +94,9 @@ async function collectGeneratedCode(
|
|
|
82
94
|
llm: Llm,
|
|
83
95
|
prompt: string,
|
|
84
96
|
systemPrompt?: string,
|
|
85
|
-
): Promise<string> {
|
|
97
|
+
): Promise<{ code: string; truncated: boolean }> {
|
|
86
98
|
let text = ''
|
|
99
|
+
let truncated = false
|
|
87
100
|
const req = {
|
|
88
101
|
model: '', // falsy → registry 回退到 active model
|
|
89
102
|
messages: [{ role: 'user' as const, content: prompt }],
|
|
@@ -92,8 +105,11 @@ async function collectGeneratedCode(
|
|
|
92
105
|
}
|
|
93
106
|
for await (const chunk of llm.chat(req)) {
|
|
94
107
|
if (chunk.type === 'text' && chunk.content) text += chunk.content
|
|
108
|
+
// Both providers already emit `truncated` on the stop chunk; reading it here is
|
|
109
|
+
// what turns the signal into something the score can act on.
|
|
110
|
+
if (chunk.truncated) truncated = true
|
|
95
111
|
}
|
|
96
|
-
return stripCodeFences(text)
|
|
112
|
+
return { code: stripCodeFences(text), truncated }
|
|
97
113
|
}
|
|
98
114
|
|
|
99
115
|
export async function runTaskPerformance(
|
|
@@ -105,13 +121,14 @@ export async function runTaskPerformance(
|
|
|
105
121
|
const results: TaskPerformanceResult[] = []
|
|
106
122
|
const startedAt = Date.now()
|
|
107
123
|
for (const task of tasks) {
|
|
108
|
-
const code = await collectGeneratedCode(llm, task.prompt, opts?.skill?.text)
|
|
124
|
+
const { code, truncated } = await collectGeneratedCode(llm, task.prompt, opts?.skill?.text)
|
|
109
125
|
if (!code) {
|
|
110
126
|
results.push({
|
|
111
127
|
id: task.id,
|
|
112
128
|
description: task.prompt,
|
|
113
129
|
passed: false,
|
|
114
130
|
detail: 'LLM 未生成代码',
|
|
131
|
+
...(truncated ? { truncated: true } : {}),
|
|
115
132
|
})
|
|
116
133
|
continue
|
|
117
134
|
}
|
|
@@ -121,15 +138,26 @@ export async function runTaskPerformance(
|
|
|
121
138
|
description: task.prompt,
|
|
122
139
|
passed: verdict.passed,
|
|
123
140
|
detail: verdict.detail,
|
|
141
|
+
...(truncated ? { truncated: true } : {}),
|
|
124
142
|
})
|
|
125
143
|
}
|
|
126
144
|
const passed = results.filter((r) => r.passed).length
|
|
145
|
+
// Score only what the model was actually given a chance to finish. A truncated
|
|
146
|
+
// generation is incomplete by construction; folding those failures into the mean
|
|
147
|
+
// makes the readout (and any improved/regressed verdict derived from it) depend on
|
|
148
|
+
// the output cap rather than on the work.
|
|
149
|
+
const scored = results.filter((r) => !r.truncated)
|
|
150
|
+
const truncated = results.length - scored.length
|
|
127
151
|
return {
|
|
128
152
|
total: results.length,
|
|
129
153
|
passed,
|
|
130
|
-
score:
|
|
154
|
+
score:
|
|
155
|
+
scored.length > 0
|
|
156
|
+
? Math.round((scored.filter((r) => r.passed).length / scored.length) * 100)
|
|
157
|
+
: 100,
|
|
131
158
|
results,
|
|
132
159
|
failures: results.filter((r) => !r.passed).map((r) => r.id),
|
|
160
|
+
truncated,
|
|
133
161
|
durationMs: Date.now() - startedAt,
|
|
134
162
|
}
|
|
135
163
|
}
|
|
@@ -940,9 +940,11 @@
|
|
|
940
940
|
"tool_denied_dangerous_rm": "Tool \"{name}\" was refused: this is a recursive rm whose target is not a path written in the command (\"{target}\"). The target is produced when the command runs, so neither an allow rule nor the permission mode can bound what it deletes. Name the directory literally instead — `rm -rf node_modules` rather than `rm -rf \"$(pwd)\"` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
941
941
|
"tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
|
|
942
942
|
"tool_blocked": "Tool \"{name}\" blocked by hook",
|
|
943
|
+
"tool_hook_ask": "Tool \"{name}\" was marked by a hook as needing approval, and this environment has no interactive prompt — so it is refused. A repository-supplied hook may narrow the gate but not approve a call; if this hook is your own, make it block outright or relax it.",
|
|
943
944
|
"user_input_blocked": "User input blocked by hook.",
|
|
944
945
|
"dlp_blocked": "Request blocked by DLP policy.",
|
|
945
946
|
"model_error": "Error: {error}",
|
|
947
|
+
"model_unavailable": "Model \"{model}\" (provider {provider}) is unavailable, and no default fallback model is configured — this turn produced no model output. Switch models with Ctrl+P, or check that provider's key and network, then retry. Underlying error: {error}",
|
|
946
948
|
"tool_collision": "[mcp] Tool collision: \"{name}\" already registered. Skipping.",
|
|
947
949
|
"missing_param": "Missing required parameter: \"{param}\"",
|
|
948
950
|
"invalid_params": "Invalid parameters: {errors}",
|
|
@@ -940,9 +940,11 @@
|
|
|
940
940
|
"tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
941
941
|
"tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
|
|
942
942
|
"tool_blocked": "工具 \"{name}\" 被钩子拦截",
|
|
943
|
+
"tool_hook_ask": "工具 \"{name}\" 被钩子标为需要批准,而本环境没有交互批准 —— 已按拒绝处理。仓库带来的钩子只能收紧闸门、不能放行;若这是你自己的钩子,请让它直接拦截,或放宽它。",
|
|
943
944
|
"user_input_blocked": "用户输入被钩子拦截。",
|
|
944
945
|
"dlp_blocked": "请求被 DLP 策略阻止。",
|
|
945
946
|
"model_error": "错误:{error}",
|
|
947
|
+
"model_unavailable": "模型 \"{model}\"(提供商 {provider})当前不可用,且没有可回退的默认模型 —— 本轮没有拿到任何模型输出。用 Ctrl+P 换一个模型,或检查该提供商的密钥与网络后重试。底层错误:{error}",
|
|
946
948
|
"tool_collision": "[mcp] 工具冲突:\"{name}\" 已注册,跳过。",
|
|
947
949
|
"missing_param": "缺少必需参数:\"{param}\"",
|
|
948
950
|
"invalid_params": "参数无效:{errors}",
|
package/src/mcp/registry.ts
CHANGED
|
@@ -72,6 +72,14 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
|
|
|
72
72
|
async execute(params: Record<string, unknown>, _ctx: ToolContext): Promise<ToolResult> {
|
|
73
73
|
const client = McpClient.getInstance()
|
|
74
74
|
|
|
75
|
+
// Startup connects servers without blocking, and a resumed session re-attaches
|
|
76
|
+
// them the same way — so a call can arrive while its server is still
|
|
77
|
+
// handshaking. Failing outright then is wrong twice over: the tool exists, and
|
|
78
|
+
// the only thing missing is patience. Same wait the `mcp_tool` hook already
|
|
79
|
+
// does (`core/hooks-executor.ts`), so both entry points treat a connecting
|
|
80
|
+
// server identically. A server that is *not* connecting returns immediately.
|
|
81
|
+
await client.waitUntilReady(serverName)
|
|
82
|
+
|
|
75
83
|
const conn = client.getConnection(serverName)
|
|
76
84
|
if (!conn || conn.status !== 'connected') {
|
|
77
85
|
return {
|
|
@@ -5,7 +5,7 @@ import type { AgentRegistry } from '../agent/agent-registry'
|
|
|
5
5
|
import type { SkillsLoader } from '../skills/loader'
|
|
6
6
|
import type { HookEngine } from '../core/hooks'
|
|
7
7
|
import type { McpClient } from '../mcp/client'
|
|
8
|
-
import { registerMcpServerTools } from '../mcp/registry'
|
|
8
|
+
import { registerMcpServerTools, unregisterMcpServerTools } from '../mcp/registry'
|
|
9
9
|
import { executeHook } from '../core/hooks-executor'
|
|
10
10
|
import { detectPluginFormat, isLoadableMcpConfig } from './plugin-validator'
|
|
11
11
|
import { loadClaudePlugin } from './claude-plugin'
|
|
@@ -37,10 +37,12 @@ export function loadPlugins(
|
|
|
37
37
|
pluginManager.onRemove(plugin.name, () => {
|
|
38
38
|
for (const serverName of claudeMcpServers) {
|
|
39
39
|
try {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
40
|
+
mcpClient.disconnect(serverName)
|
|
41
|
+
// Register-time names go through `sanitizeName`; deleting by a raw
|
|
42
|
+
// `mcp__<serverName>__<toolName>` key silently missed every tool whose
|
|
43
|
+
// server name needed sanitizing, leaving orphans in the registry. The
|
|
44
|
+
// shared helper deletes by the same sanitized prefix registration used.
|
|
45
|
+
unregisterMcpServerTools(serverName, toolsMap)
|
|
44
46
|
} catch {
|
|
45
47
|
/* best effort */
|
|
46
48
|
}
|
|
@@ -163,10 +165,9 @@ export function loadPlugins(
|
|
|
163
165
|
// Disconnect MCP servers and unregister their tools
|
|
164
166
|
for (const serverName of mcpServers) {
|
|
165
167
|
try {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
168
|
+
mcpClient.disconnect(serverName)
|
|
169
|
+
// Same sanitized-prefix deletion as the Claude-format branch above.
|
|
170
|
+
unregisterMcpServerTools(serverName, toolsMap)
|
|
170
171
|
} catch {
|
|
171
172
|
/* best effort */
|
|
172
173
|
}
|
|
@@ -6,7 +6,7 @@ import type {
|
|
|
6
6
|
ContentBlock,
|
|
7
7
|
} from '../shared/index.ts'
|
|
8
8
|
import type { ProviderInstance, ChatRequest } from './registry'
|
|
9
|
-
import { fetchWithRetry, streamIdleTimeoutMs } from './fetch-utils'
|
|
9
|
+
import { fetchWithRetry, streamIdleTimeoutMs, isRetryableFailure } from './fetch-utils'
|
|
10
10
|
|
|
11
11
|
interface AnthropicContentBlock {
|
|
12
12
|
type: string
|
|
@@ -139,7 +139,11 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
139
139
|
|
|
140
140
|
if (!response.ok) {
|
|
141
141
|
const errText = await response.text()
|
|
142
|
-
yield {
|
|
142
|
+
yield {
|
|
143
|
+
type: 'error',
|
|
144
|
+
error: `Anthropic API error ${response.status}: ${errText}`,
|
|
145
|
+
retryable: isRetryableFailure(response.status),
|
|
146
|
+
}
|
|
143
147
|
return
|
|
144
148
|
}
|
|
145
149
|
|
|
@@ -304,7 +308,11 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
304
308
|
}
|
|
305
309
|
|
|
306
310
|
case 'error': {
|
|
307
|
-
yield {
|
|
311
|
+
yield {
|
|
312
|
+
type: 'error',
|
|
313
|
+
error: event.error?.message || 'Unknown Anthropic error',
|
|
314
|
+
retryable: isRetryableFailure(undefined, event.error?.type),
|
|
315
|
+
}
|
|
308
316
|
return
|
|
309
317
|
}
|
|
310
318
|
}
|
|
@@ -14,7 +14,11 @@ export interface FetchWithRetryOptions {
|
|
|
14
14
|
baseDelay?: number
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
// 529 is Anthropic's non-standard "overloaded" status: the request is rejected
|
|
18
|
+
// *before* the stream starts, on exactly the same terms as a 503 — transient,
|
|
19
|
+
// retryable, and already bounded by the `Retry-After` clamp below. Without it
|
|
20
|
+
// here, a 529 answers `!response.ok` and the whole turn dies at the first byte.
|
|
21
|
+
const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504, 529])
|
|
18
22
|
|
|
19
23
|
/**
|
|
20
24
|
* Upper bound on a server-supplied `Retry-After`, in ms.
|
|
@@ -73,6 +77,35 @@ function isRetryableError(err: unknown): boolean {
|
|
|
73
77
|
return true
|
|
74
78
|
}
|
|
75
79
|
|
|
80
|
+
/**
|
|
81
|
+
* Provider error types that are decided, not transient. A content filter or a
|
|
82
|
+
* malformed request answers the same way on every attempt, so re-sending it only
|
|
83
|
+
* makes the user wait for an error that was final the first time.
|
|
84
|
+
*/
|
|
85
|
+
const NON_RETRYABLE_ERROR_TYPES = new Set([
|
|
86
|
+
'invalid_request_error',
|
|
87
|
+
'authentication_error',
|
|
88
|
+
'permission_error',
|
|
89
|
+
'not_found_error',
|
|
90
|
+
'request_too_large',
|
|
91
|
+
'content_filter',
|
|
92
|
+
'content_policy_violation',
|
|
93
|
+
])
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Should the engine re-send a turn the provider reported as failed?
|
|
97
|
+
*
|
|
98
|
+
* Two call shapes: an HTTP status, or a provider error object's `type`/`code`.
|
|
99
|
+
* Statuses follow the same rule as `fetchWithRetry` (429 and 5xx are transient).
|
|
100
|
+
* For an error type, only the *known* deterministic ones say no — an unrecognised
|
|
101
|
+
* type stays retryable, because guessing "final" would lose a recoverable turn.
|
|
102
|
+
*/
|
|
103
|
+
export function isRetryableFailure(status: number | undefined, errorType?: string): boolean {
|
|
104
|
+
if (status !== undefined) return RETRYABLE_STATUSES.has(status) || status >= 500
|
|
105
|
+
if (errorType === undefined) return true
|
|
106
|
+
return !NON_RETRYABLE_ERROR_TYPES.has(errorType)
|
|
107
|
+
}
|
|
108
|
+
|
|
76
109
|
/**
|
|
77
110
|
* Fetch with optional timeout and retry with exponential backoff.
|
|
78
111
|
*
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { execSync } from 'node:child_process'
|
|
2
2
|
import type { ProviderConfig, ModelInfo, Message, StreamChunk } from '../shared/index.ts'
|
|
3
3
|
import type { ProviderInstance, ChatRequest } from './registry'
|
|
4
|
-
import { fetchWithRetry, streamIdleTimeoutMs } from './fetch-utils'
|
|
4
|
+
import { fetchWithRetry, streamIdleTimeoutMs, isRetryableFailure } from './fetch-utils'
|
|
5
5
|
import { OLLAMA_PRESET_MODELS } from '../shared/constants'
|
|
6
6
|
|
|
7
7
|
export class OpenAICompatProvider implements ProviderInstance {
|
|
@@ -46,7 +46,11 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
46
46
|
|
|
47
47
|
if (!response.ok) {
|
|
48
48
|
const errText = await response.text()
|
|
49
|
-
yield {
|
|
49
|
+
yield {
|
|
50
|
+
type: 'error',
|
|
51
|
+
error: `OpenAI API error ${response.status}: ${errText}`,
|
|
52
|
+
retryable: isRetryableFailure(response.status),
|
|
53
|
+
}
|
|
50
54
|
return
|
|
51
55
|
}
|
|
52
56
|
|
|
@@ -141,6 +145,24 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
141
145
|
}
|
|
142
146
|
}
|
|
143
147
|
|
|
148
|
+
// A mid-stream error arrives as `data: {"error": {...}}` — no `choices`.
|
|
149
|
+
// Previously it fell through `if (!choice) continue`, the loop ran to its
|
|
150
|
+
// end, and the trailing `yield { type: 'stop' }` below made the turn look
|
|
151
|
+
// like a clean finish: no error surfaced, so the engine neither retried
|
|
152
|
+
// nor fell back and the user got a silently empty answer. Surface it as
|
|
153
|
+
// an error chunk instead, which is also what feeds the "name the model and
|
|
154
|
+
// offer a way out" path.
|
|
155
|
+
if (parsed.error) {
|
|
156
|
+
const e = parsed.error as { message?: string; code?: string; type?: string }
|
|
157
|
+
const detail = e.message ?? JSON.stringify(parsed.error)
|
|
158
|
+
yield {
|
|
159
|
+
type: 'error',
|
|
160
|
+
error: `${this.config.id}: ${detail}`,
|
|
161
|
+
retryable: isRetryableFailure(undefined, e.type ?? e.code),
|
|
162
|
+
}
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
|
|
144
166
|
if (!choice) continue
|
|
145
167
|
|
|
146
168
|
const delta = choice.delta
|
|
@@ -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.12' 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 = 3839 as const
|