@miphamai/cli 0.85.10 → 0.85.11
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 +27 -1
- package/src/commands/autoloop-journal.ts +16 -1
- package/src/core/context.ts +41 -5
- package/src/core/crsi-producer.ts +86 -6
- package/src/core/engine.ts +89 -25
- 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/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/providers/fetch-utils.ts +5 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +32 -0
- package/src/tools/system/tool-search.ts +1 -1
- package/src/ui/commands.ts +21 -5
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.
|
|
1
|
+
# Mipham Code v0.85.11
|
|
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
package/src/agent/sub-agent.ts
CHANGED
|
@@ -22,6 +22,27 @@ function getPatternAnalyzer(): PatternAnalyzer {
|
|
|
22
22
|
return _patternAnalyzer
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/** 每进程每条只念一次 —— 与 `core/permission-audit.ts` 的 `warnedOnce` 同形。 */
|
|
26
|
+
const warnedAgentCaps = new Set<string>()
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 项目级 agent 想把自己抬到比父会话更宽、被 `resolveAgentMode` 顶回去时,把这件事念出来。
|
|
30
|
+
*
|
|
31
|
+
* **不静默**是本仓库的既有口径 —— `config/loader.ts` 的 `stripProjectPermission` 对项目级
|
|
32
|
+
* 权限是**拒绝并报告**,不是忽略;agent 定义这条路径此前既不拒绝也不报告。stderr 是本仓库
|
|
33
|
+
* 既有的告警通道(`core/permission-audit.ts` / `core/hooks.ts` / `core/workspace-trust.ts` 同形)。
|
|
34
|
+
*
|
|
35
|
+
* 判读与措辞在 `resolveAgentMode` 里,这里只补上它拿不到的那一半 —— agent 的名字。
|
|
36
|
+
*/
|
|
37
|
+
function reportAgentCapWarnings(gate: PermissionSystem, agentName?: string): void {
|
|
38
|
+
for (const warning of gate.getAgentCapWarnings()) {
|
|
39
|
+
const line = `⚠️ agent "${agentName ?? 'unknown'}": ${warning}\n`
|
|
40
|
+
if (warnedAgentCaps.has(line)) continue
|
|
41
|
+
warnedAgentCaps.add(line)
|
|
42
|
+
process.stderr.write(line)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
25
46
|
const TYPE_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
|
|
26
47
|
general: 'You are a focused sub-agent. Complete the assigned task thoroughly and return results.',
|
|
27
48
|
explore:
|
|
@@ -262,7 +283,9 @@ export class SubAgent {
|
|
|
262
283
|
agentDef?.permissionMode && agentDef.permissionMode !== 'inherit'
|
|
263
284
|
? agentDef.permissionMode
|
|
264
285
|
: 'inherit'
|
|
265
|
-
|
|
286
|
+
// `source` decides whether the cap applies: a repository-supplied definition may
|
|
287
|
+
// narrow the parent's gate but not widen it. See `resolveAgentMode`.
|
|
288
|
+
subPermission = this.permission.createSubAgentPermission(agentPermMode, agentDef?.source)
|
|
266
289
|
}
|
|
267
290
|
|
|
268
291
|
// Absence is not a licence to run everything. With no permission system handed in,
|
|
@@ -271,6 +294,9 @@ export class SubAgent {
|
|
|
271
294
|
// what the CLI itself runs under, so this is the same policy, not a stricter one.
|
|
272
295
|
const gate = subPermission ?? new PermissionSystem('default')
|
|
273
296
|
|
|
297
|
+
// The cap is never silent: say which agent asked for what and what it got instead.
|
|
298
|
+
reportAgentCapWarnings(gate, agentDef?.name)
|
|
299
|
+
|
|
274
300
|
// Resolve execution directory: worktree isolation or process cwd
|
|
275
301
|
const execCwd = options.worktreePath || process.cwd()
|
|
276
302
|
|
|
@@ -80,13 +80,28 @@ export function recordLoopTurn(sessionId: string, summary: string, delta: number
|
|
|
80
80
|
}
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
/**
|
|
84
|
+
* The row written when an iteration produced **no visible text**.
|
|
85
|
+
*
|
|
86
|
+
* The summary is the assistant's visible output (`app.tsx` passes
|
|
87
|
+
* `assistantContent`, which only accumulates `type === 'text'` chunks), so a
|
|
88
|
+
* turn that emitted only tool calls — or only thinking, which `formatThinking`
|
|
89
|
+
* hides by default — arrives here as an empty string. Written as `#N: ` that
|
|
90
|
+
* row is indistinguishable from "we recorded nothing at all", which is exactly
|
|
91
|
+
* what `/loop status` must not conflate. So it is spelled out.
|
|
92
|
+
*/
|
|
93
|
+
export const NO_VISIBLE_OUTPUT = '(no visible output — tool calls or thinking only)'
|
|
94
|
+
|
|
83
95
|
/** Log an iteration in the autonomous loop journal. */
|
|
84
96
|
export function logAutoloopIteration(sessionId: string, summary: string): void {
|
|
85
97
|
const journal = readAutoloopJournal(sessionId)
|
|
86
98
|
if (!journal) return
|
|
87
99
|
journal.iterations++
|
|
88
100
|
journal.lastIteration = new Date().toISOString()
|
|
89
|
-
|
|
101
|
+
const text = summary.trim()
|
|
102
|
+
journal.logs.push(
|
|
103
|
+
`[${journal.lastIteration}] #${journal.iterations}: ${text ? text.slice(0, 200) : NO_VISIBLE_OUTPUT}`,
|
|
104
|
+
)
|
|
90
105
|
// Keep last 50 log entries
|
|
91
106
|
if (journal.logs.length > 50) journal.logs = journal.logs.slice(-50)
|
|
92
107
|
atomicWriteFileSync(journalPath(sessionId), JSON.stringify(journal, null, 2), { mode: 0o644 })
|
package/src/core/context.ts
CHANGED
|
@@ -34,6 +34,30 @@ interface Checkpoint {
|
|
|
34
34
|
label: string
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* 一次 `compact()` 的调度表 —— 「压完再判一次,仍超预算就再压、且压得更狠」。
|
|
39
|
+
*
|
|
40
|
+
* 存在的理由:**触发尺与削减尺不是同一把**。`needsCompaction()` 按 token 判,而一趟压缩
|
|
41
|
+
* 只按条数削,于是**一条超大消息(大文本 / 图片 / 长工具结果)可以同时穿过两把尺** ——
|
|
42
|
+
* 判着要压,压完却仍超预算,此后每一轮都带着超长请求打上游,直到用户手动 `/compact`
|
|
43
|
+
* 或上游报错。只压一趟且从不复查,就是那个缺口。
|
|
44
|
+
*
|
|
45
|
+
* - 第一趟 `{keep: 20, minLength: 30}` 与历史行为**逐字等价**(`minLength` 就是原来那条
|
|
46
|
+
* `messages.length <= 30` 的 no-op)。
|
|
47
|
+
* - 第二趟的闸取 `keep` 本身而不是 `keep + 10`:第一趟之后只剩 20 条(截断回落)或 21 条
|
|
48
|
+
* (有 summarizer 时多一条摘要),沿用 `keep + 10 = 20` 会让截断那条路命中 `20 <= 20`
|
|
49
|
+
* 而**永不跑第二趟**,整个改动自我抵消。此时唯一要问的是「还有没有可丢的」。
|
|
50
|
+
* - 表是常量、无 `while` ⇒ 有界,不可能死循环。
|
|
51
|
+
*
|
|
52
|
+
* `recountMessageTokens()` 随每趟一起跑(见 `compactOnce`)—— 它是第二趟那道「仍超预算吗」
|
|
53
|
+
* 的**闸所读的那个数**。放在循环外只算一次,闸读到的就是压缩前的旧值,永远为真 ⇒
|
|
54
|
+
* 第二趟变成无条件跑,「复查」就名存实亡。
|
|
55
|
+
*/
|
|
56
|
+
const COMPACTION_PASSES: ReadonlyArray<{ keep: number; minLength: number }> = [
|
|
57
|
+
{ keep: 20, minLength: 30 },
|
|
58
|
+
{ keep: 10, minLength: 10 },
|
|
59
|
+
]
|
|
60
|
+
|
|
37
61
|
export class ContextManager {
|
|
38
62
|
private messages: Message[] = []
|
|
39
63
|
private systemPrompt = ''
|
|
@@ -296,11 +320,25 @@ export class ContextManager {
|
|
|
296
320
|
async compact(heading: string): Promise<{ before: number; after: number }> {
|
|
297
321
|
const beforeTokens = this.getEstimatedTokens()
|
|
298
322
|
|
|
299
|
-
|
|
300
|
-
|
|
323
|
+
for (let i = 0; i < COMPACTION_PASSES.length; i++) {
|
|
324
|
+
const pass = COMPACTION_PASSES[i]!
|
|
325
|
+
// 第一趟无条件跑(手动 `/compact` 即使未超预算也必须动);之后**只**在复查
|
|
326
|
+
// 仍超预算时继续 —— 这一句就是「压完再判一次」。
|
|
327
|
+
if (i > 0 && !this.needsCompaction()) break
|
|
328
|
+
if (this.messages.length <= pass.minLength) continue
|
|
329
|
+
await this.compactOnce(heading, pass.keep)
|
|
301
330
|
}
|
|
302
331
|
|
|
303
|
-
|
|
332
|
+
return { before: beforeTokens, after: this.getEstimatedTokens() }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* 压缩一趟:把消息削到最近 `keep` 条。
|
|
337
|
+
*
|
|
338
|
+
* body(除 `keep` 外)逐行取自旧 `compact()`,两种分支原样保留:LLM 摘要(失败回落截断)
|
|
339
|
+
* 与纯截断。`recountMessageTokens()` 留在**这里**而不是调用方 —— 下一趟的闸要读它。
|
|
340
|
+
*/
|
|
341
|
+
private async compactOnce(heading: string, keep: number): Promise<void> {
|
|
304
342
|
const toDrop = this.messages.slice(0, -keep)
|
|
305
343
|
|
|
306
344
|
if (this.summarizer && toDrop.length >= 4) {
|
|
@@ -340,8 +378,6 @@ export class ContextManager {
|
|
|
340
378
|
|
|
341
379
|
// Re-estimate the message half (the prompt half is derived on read).
|
|
342
380
|
this.recountMessageTokens()
|
|
343
|
-
|
|
344
|
-
return { before: beforeTokens, after: this.getEstimatedTokens() }
|
|
345
381
|
}
|
|
346
382
|
|
|
347
383
|
/**
|
|
@@ -115,7 +115,27 @@ export function buildLessonContent(
|
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
/**
|
|
118
|
-
*
|
|
118
|
+
* 档位的**来历** —— 这一格回答的是「谁定的档」,不是「档是什么」。
|
|
119
|
+
*
|
|
120
|
+
* - `declared` —— 文件里逐字写了 `- 严重度: critical` 或 `- 严重度: warning`。
|
|
121
|
+
* - `defaulted` —— 没有那一行,或写了但取值在闭集之外(如 `info`、笔误)⇒
|
|
122
|
+
* {@link normalizeLessonSeverity} fail-open 落 `critical`,于是这条进了常驻档。
|
|
123
|
+
*
|
|
124
|
+
* 为什么非记不可:`severity` 是**归一化之后**的读数,而归一化是 fail-open 的 ⇒
|
|
125
|
+
* 「有人判定它该每次请求都在场」与「压根没人写过档位」在 `severity` 上**同形**。
|
|
126
|
+
* 常驻档的成本是人付的、能动手的也只有人(改文件那一行),看不出这条是被判过的
|
|
127
|
+
* 还是漏写的,就无从复核 —— 这正是本仓库记过的「无声消失与从没写过同形」。
|
|
128
|
+
*
|
|
129
|
+
* 不改任何**判定**行为:`severity` 照旧 fail-open 落 `critical`,常驻/择点/预算一概不看
|
|
130
|
+
* 这一格。它只把不可见的默认**变成可复核的清单**(见 {@link buildResidentLessonReport})。
|
|
131
|
+
*
|
|
132
|
+
* 一条不变量:`severity === 'warning'` ⇒ `severitySource === 'declared'`。
|
|
133
|
+
* 因为归一化只有**逐字** `warning` 才落 `warning`,其余一切落 `critical`。
|
|
134
|
+
*/
|
|
135
|
+
export type LessonSeveritySource = 'declared' | 'defaulted'
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 教训精华(标题 + 建议 + 严重度 + 档位来历),用于运行时召回注入系统提示。
|
|
119
139
|
*
|
|
120
140
|
* 严重度决定**注入位置**,不只是标签:`critical` 常驻每一次请求,
|
|
121
141
|
* `warning` 移出常驻块、按需召回(见 {@link isAlwaysOnLesson}),且常驻档整体受
|
|
@@ -127,6 +147,12 @@ export interface CrsiLessonSummary {
|
|
|
127
147
|
title: string
|
|
128
148
|
suggestion: string
|
|
129
149
|
severity: LessonSeverity
|
|
150
|
+
/**
|
|
151
|
+
* 必填而非可选 —— 同 `buildLessonContent` 的 `severity`:可选的话,下一个构造点忘了给
|
|
152
|
+
* 就等于「来历是默认落的」,而那个默认值恰好**说反了**(它说的是「有人判过」)。
|
|
153
|
+
* 忘了要给不出来的东西,必须是编译错误。
|
|
154
|
+
*/
|
|
155
|
+
severitySource: LessonSeveritySource
|
|
130
156
|
}
|
|
131
157
|
|
|
132
158
|
/**
|
|
@@ -153,25 +179,50 @@ export function normalizeLessonSeverity(raw: string | undefined): LessonSeverity
|
|
|
153
179
|
}
|
|
154
180
|
|
|
155
181
|
/**
|
|
156
|
-
*
|
|
157
|
-
*
|
|
182
|
+
* 闭集成员的**运行时**面 —— `LessonSeverity` 是类型,运行时只存在这一份字面量。
|
|
183
|
+
*
|
|
184
|
+
* 定义在**一处**:{@link isDeclaredLessonSeverity} 读它,而它与
|
|
185
|
+
* {@link normalizeLessonSeverity} 必须对**同一个**闭集说话(一个问「折叠前在不在集里」、
|
|
186
|
+
* 一个做折叠)。两处各写一份字面量的话,哪天闭集加一档,会出现「归一是对的、来历却说
|
|
187
|
+
* 它不在闭集」这种自相矛盾的读数 —— 且没有任何东西会报。
|
|
188
|
+
*/
|
|
189
|
+
const LESSON_SEVERITY_SET: ReadonlySet<string> = new Set(['critical', 'warning'])
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* 那一行是否**逐字**落在闭集内(= 档位有人判过)。缺席、空串与闭集外取值一律 false。
|
|
193
|
+
*
|
|
194
|
+
* 参数类型与 {@link normalizeLessonSeverity} 刻意**同形**(`string | undefined`):
|
|
195
|
+
* 两者是同一个原始捕获的一对读者(一个折叠、一个问来历),签名不一致的话,调用点迟早
|
|
196
|
+
* 会把某个缺席的捕获只喂给其中一个。
|
|
197
|
+
*/
|
|
198
|
+
function isDeclaredLessonSeverity(raw: string | undefined): boolean {
|
|
199
|
+
return typeof raw === 'string' && LESSON_SEVERITY_SET.has(raw)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* 从 crsi-lessons.md 提取每条教训的「精华」(标题 + 建议 + 严重度 + 档位来历),
|
|
204
|
+
* 跳过证据段落。这是「只写不读」缺口 → 「写后召回」的读取侧。
|
|
158
205
|
*
|
|
159
206
|
* 按 `##` 块累积、块边界 flush —— 因为 `- 严重度:` 行写在 `- 建议:` **之后**,
|
|
160
207
|
* 「见到建议即 push」的写法读不到它。块级累积对行序不敏感。
|
|
161
208
|
*
|
|
162
|
-
* 缺 `严重度` 时的落档见 {@link DEFAULT_LESSON_SEVERITY}
|
|
209
|
+
* 缺 `严重度` 时的落档见 {@link DEFAULT_LESSON_SEVERITY};**它是怎么落的**记在
|
|
210
|
+
* `severitySource` 里(见 {@link LessonSeveritySource})—— 归一化把「有人判过」与
|
|
211
|
+
* 「没人写过」折叠成了同一个 `critical`,本读取侧把这两者**重新分开**。
|
|
163
212
|
*/
|
|
164
213
|
export function extractCrsiLessonSummaries(content: string): CrsiLessonSummary[] {
|
|
165
214
|
const out: CrsiLessonSummary[] = []
|
|
166
215
|
let title = ''
|
|
167
216
|
let suggestion = ''
|
|
168
217
|
let severity = DEFAULT_LESSON_SEVERITY
|
|
218
|
+
let severitySource: LessonSeveritySource = 'defaulted'
|
|
169
219
|
|
|
170
220
|
const flush = () => {
|
|
171
|
-
if (title && suggestion) out.push({ title, suggestion, severity })
|
|
221
|
+
if (title && suggestion) out.push({ title, suggestion, severity, severitySource })
|
|
172
222
|
title = ''
|
|
173
223
|
suggestion = ''
|
|
174
224
|
severity = DEFAULT_LESSON_SEVERITY
|
|
225
|
+
severitySource = 'defaulted'
|
|
175
226
|
}
|
|
176
227
|
|
|
177
228
|
for (const line of content.split('\n')) {
|
|
@@ -191,6 +242,8 @@ export function extractCrsiLessonSummaries(content: string): CrsiLessonSummary[]
|
|
|
191
242
|
// 闭集外的取值一律落常驻档 —— 未知严重度不倒向「按需」。规则在 normalizeLessonSeverity
|
|
192
243
|
// 一处;写入者同读它(正则已吃掉两侧空白,故传进去的是已经 trim 过的捕获)。
|
|
193
244
|
severity = normalizeLessonSeverity(v[1])
|
|
245
|
+
// 来历与档位**同一处**算出:分开写迟早出现「档是折叠后的、来历说的还是原文」的错配。
|
|
246
|
+
severitySource = isDeclaredLessonSeverity(v[1]) ? 'declared' : 'defaulted'
|
|
194
247
|
}
|
|
195
248
|
}
|
|
196
249
|
flush()
|
|
@@ -380,6 +433,12 @@ export function buildLessonRevisitNudge(
|
|
|
380
433
|
* 报告不可能与真正注入的那一份漂移。逐条成本按**渲染后的文本量**算,且报出可验算的
|
|
381
434
|
* 加法(表头 + 逐条 + 分隔 == 合计)—— 否则「逐条和 ≠ 合计」会被当成 bug 查一遍。
|
|
382
435
|
*
|
|
436
|
+
* 另报**档位来历**({@link LessonSeveritySource}):成本答「这档涨得值不值」,来历答
|
|
437
|
+
* 「这一格是谁定的」。两个读者的输出都不需要它(模型不问档位怎么来的),只有人有这个
|
|
438
|
+
* 问题 —— 而「没人复核谁把一条教训标成 critical」正是因此才存在:归一化 fail-open,
|
|
439
|
+
* 「有人判过」与「没人写过」在 `severity` 上同形,名册里读到的就是一个普通的 critical。
|
|
440
|
+
* 故这里把两者分开列、逐条点名 —— 只报数不点名,读者仍要自己去文件里比对。
|
|
441
|
+
*
|
|
383
442
|
* 只读:**不加写路径**。人的杠杆是改文件那一行;写入侧是生产者与 `/crsi propose`。
|
|
384
443
|
*/
|
|
385
444
|
export function buildResidentLessonReport(
|
|
@@ -415,9 +474,24 @@ export function buildResidentLessonReport(
|
|
|
415
474
|
)
|
|
416
475
|
|
|
417
476
|
if (resident.length > 0) {
|
|
477
|
+
// 档位**来历**与成本分开报:成本答「这档涨得值不值」,来历答「这一格是谁定的」。
|
|
478
|
+
// 两者都要人动手才能改,但改动完全不同(前者缩短、后者补/改 `- 严重度:` 那一行)。
|
|
479
|
+
const defaulted = resident.filter((s) => s.severitySource === 'defaulted')
|
|
480
|
+
// 两个分支**同一个形状**(`**默认落档 N** 条`):形状随取值变的话,读者与判据都得先
|
|
481
|
+
// 分辨自己看到的是哪一支 —— 而「0 条」与「这一支没打印」本来就会长得一样。
|
|
482
|
+
lines.push(
|
|
483
|
+
`档位来历:显式判定 **${resident.length - defaulted.length}** 条 · ` +
|
|
484
|
+
`**默认落档 ${defaulted.length}** 条` +
|
|
485
|
+
(defaulted.length > 0
|
|
486
|
+
? ' —— 文件里没写 `- 严重度:`、或写了闭集外的取值,fail-open 落 critical ⇒ ' +
|
|
487
|
+
'**没有任何人判定过**它们该常驻'
|
|
488
|
+
: ''),
|
|
489
|
+
)
|
|
490
|
+
|
|
418
491
|
lines.push('', '### 逐条成本(渲染后字符)', '')
|
|
419
492
|
for (let i = 0; i < resident.length; i++) {
|
|
420
|
-
|
|
493
|
+
const mark = resident[i]!.severitySource === 'defaulted' ? '(档位默认落档)' : ''
|
|
494
|
+
lines.push(`- ${num(itemChars[i]!)} 字符 — ${resident[i]!.title}${mark}`)
|
|
421
495
|
}
|
|
422
496
|
// 加法自证:表头是每条共担的,逐条和必然大于合计 —— 与其让人去猜差额,
|
|
423
497
|
// 不如把算式写出来,且当场验算(`block` 走的是真渲染器,不是我在这里的手算)。
|
|
@@ -1036,6 +1110,12 @@ export function removeLessonSections(content: string, headers: string[]): string
|
|
|
1036
1110
|
* 3. **不停在「缺省 critical」** —— 那个缺省是给**人类新写**的条目兜底的;合并是**降维**,
|
|
1037
1111
|
* 没有依据说产物比两个源更紧急。实测(真模块):两条 warning 合并曾升进常驻档,
|
|
1038
1112
|
* 常驻 6 条 2,155 字符 → 7 条 2,198,而这一切发生在**没有人决定过**的情况下。
|
|
1113
|
+
*
|
|
1114
|
+
* **已知边界(如实写,不假装覆盖)**:来历**不跨代传递**。产物由 `buildLessonContent`
|
|
1115
|
+
* 逐字写 `- 严重度: <merged>`,于是它读回来的来历恒为 `declared` —— 哪怕两个源都是
|
|
1116
|
+
* 默认落档。也就是说 crossover 会把「没人判过」**洗成**「有人判过」,名册看不出来。
|
|
1117
|
+
* 修它要把来历写进文件(新字段),是改教训文件的格式,不在本格口径内 —— 故此处的
|
|
1118
|
+
* 判据只对**人写进去的**条目成立。见 {@link LessonSeveritySource}。
|
|
1039
1119
|
*/
|
|
1040
1120
|
export function deriveMergedSeverity(a: LessonSeverity, b: LessonSeverity): LessonSeverity {
|
|
1041
1121
|
return a === 'critical' || b === 'critical' ? 'critical' : 'warning'
|
package/src/core/engine.ts
CHANGED
|
@@ -1196,9 +1196,37 @@ export class QueryEngine {
|
|
|
1196
1196
|
error: preResult.reason || t('errors.tool_blocked', { name }),
|
|
1197
1197
|
}
|
|
1198
1198
|
}
|
|
1199
|
+
|
|
1200
|
+
// `permissionDecision` narrows only — never widens. `ask` stops the call here
|
|
1201
|
+
// (this CLI has no interactive approval prompt; `ask` is a hard refusal, the
|
|
1202
|
+
// same as the `default` mode's ask path). `allow` is deliberately **not**
|
|
1203
|
+
// honoured: a hook can come from the repository's own settings, so letting it
|
|
1204
|
+
// auto-approve is the same defect as a project-supplied agent definition that
|
|
1205
|
+
// grants itself `bypassPermissions` — the criterion is the *direction*, not the
|
|
1206
|
+
// key name. `defer` (and an absent decision) means "no override", which is
|
|
1207
|
+
// exactly what happens when we do nothing.
|
|
1208
|
+
if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
|
|
1209
|
+
return {
|
|
1210
|
+
success: false,
|
|
1211
|
+
content: '',
|
|
1212
|
+
error: preResult.reason || t('errors.tool_hook_ask', { name }),
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1199
1216
|
if (preResult.modifiedInput) {
|
|
1200
1217
|
effectiveParams = { ...params, ...preResult.modifiedInput }
|
|
1201
1218
|
}
|
|
1219
|
+
|
|
1220
|
+
// A hook's `additionalContext` is how every non-blocking hook speaks — the
|
|
1221
|
+
// exit-1 stderr, a spawn failure, an unreachable `mcp_tool` server (see
|
|
1222
|
+
// `core/hooks-executor.ts`). This path used to read only `allowed` /
|
|
1223
|
+
// `modifiedInput`, so all of it was produced and then dropped. `hookWarnings`
|
|
1224
|
+
// is the channel that already reaches the model: it is prepended to the tool
|
|
1225
|
+
// result below. A non-`[rule:…]` line is ignored by the effectiveness tracker
|
|
1226
|
+
// further down, so pushing prose here is safe.
|
|
1227
|
+
if (preResult.additionalContext) {
|
|
1228
|
+
hookWarnings.push(preResult.additionalContext)
|
|
1229
|
+
}
|
|
1202
1230
|
}
|
|
1203
1231
|
|
|
1204
1232
|
// CRSI RuleEngine intercept — gated by crsi.preToolHook feature flag
|
|
@@ -1209,7 +1237,11 @@ export class QueryEngine {
|
|
|
1209
1237
|
effectiveParams = ruleResult.modified
|
|
1210
1238
|
}
|
|
1211
1239
|
if (ruleResult.warnings.length > 0) {
|
|
1212
|
-
|
|
1240
|
+
// Append, do not replace: this array may already hold a PreToolUse hook's
|
|
1241
|
+
// `additionalContext`. Every other writer below uses the spread form for the
|
|
1242
|
+
// same reason — assignment here would silently drop whichever was written
|
|
1243
|
+
// first ("two writers, one list").
|
|
1244
|
+
hookWarnings = [...hookWarnings, ...ruleResult.warnings]
|
|
1213
1245
|
}
|
|
1214
1246
|
}
|
|
1215
1247
|
|
|
@@ -1478,9 +1510,12 @@ export class QueryEngine {
|
|
|
1478
1510
|
* Stream a chat response with graceful provider fallback (v2.1.229 alignment).
|
|
1479
1511
|
*
|
|
1480
1512
|
* On a connection/availability failure from the active provider (thrown
|
|
1481
|
-
* network error or an error chunk),
|
|
1482
|
-
* provider and retries
|
|
1483
|
-
*
|
|
1513
|
+
* network error or an error chunk), retries that same provider once, then
|
|
1514
|
+
* switches to the configured default provider and retries again, yielding a
|
|
1515
|
+
* `warning` chunk at each step so the UI can tell the user what happened.
|
|
1516
|
+
* When there is no fallback left, the error names the unavailable model and
|
|
1517
|
+
* the next step instead of re-emitting the raw upstream message.
|
|
1518
|
+
* Abort errors propagate untouched.
|
|
1484
1519
|
*/
|
|
1485
1520
|
private async *chatWithFallback(
|
|
1486
1521
|
messages: import('../shared/types').Message[],
|
|
@@ -1489,30 +1524,49 @@ export class QueryEngine {
|
|
|
1489
1524
|
signal?: AbortSignal,
|
|
1490
1525
|
): AsyncGenerator<StreamChunk> {
|
|
1491
1526
|
const activeId = this.registry.getActive().config.id
|
|
1527
|
+
const activeModel = this.registry.getActiveModel()
|
|
1492
1528
|
const defaultId = this.registry.getDefaultProviderId()
|
|
1493
1529
|
|
|
1494
|
-
// ── Attempt 1: active provider ──
|
|
1530
|
+
// ── Attempt 1 (+ one same-provider retry): active provider ──
|
|
1531
|
+
//
|
|
1532
|
+
// A failed turn is retried once on the *same* provider before the cross-provider
|
|
1533
|
+
// fallback is considered: overloaded and transient errors are commonly answered
|
|
1534
|
+
// by resending, whereas switching providers is the more expensive move — it flips
|
|
1535
|
+
// the registry's active provider and, with it, the model the user chose. A
|
|
1536
|
+
// foreign `Llm` seam owns the whole chat flow, so it is not retried here, for the
|
|
1537
|
+
// same reason the fallback below is skipped for it.
|
|
1538
|
+
//
|
|
1539
|
+
// Chunks already yielded cannot be taken back, so a retry re-streams that turn.
|
|
1540
|
+
// This is not a new property: the cross-provider fallback below already starts a
|
|
1541
|
+
// fresh attempt after a failed one.
|
|
1542
|
+
const ownsFlow = !(this.llm && this.llm !== this.registry)
|
|
1495
1543
|
let failure: string | null = null
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1544
|
+
for (let attempt = 0; ; attempt++) {
|
|
1545
|
+
failure = null
|
|
1546
|
+
try {
|
|
1547
|
+
for await (const chunk of this.llmChat({
|
|
1548
|
+
model: activeModel,
|
|
1549
|
+
messages,
|
|
1550
|
+
systemPrompt,
|
|
1551
|
+
tools: toolDefs,
|
|
1552
|
+
signal,
|
|
1553
|
+
effort: this.effort,
|
|
1554
|
+
})) {
|
|
1555
|
+
if (chunk.type === 'error') {
|
|
1556
|
+
failure = chunk.error ?? 'Unknown error'
|
|
1557
|
+
break
|
|
1558
|
+
}
|
|
1559
|
+
yield chunk
|
|
1508
1560
|
}
|
|
1509
|
-
|
|
1561
|
+
if (failure === null) return
|
|
1562
|
+
} catch (err) {
|
|
1563
|
+
if (isAbortError(err)) throw err
|
|
1564
|
+
failure = String(err)
|
|
1510
1565
|
}
|
|
1511
|
-
if (
|
|
1512
|
-
|
|
1513
|
-
if (isAbortError(err)) throw err
|
|
1514
|
-
failure = String(err)
|
|
1566
|
+
if (!ownsFlow || attempt >= 1) break
|
|
1567
|
+
yield { type: 'warning', content: `${activeId} failed (${failure}) — retrying once` }
|
|
1515
1568
|
}
|
|
1569
|
+
const detail = failure ?? 'Unknown error'
|
|
1516
1570
|
|
|
1517
1571
|
// ── Fallback: configured default provider, once ──
|
|
1518
1572
|
// 若注入了**异己**的 Llm 缝,缝拥有整个 chat 流程——不回退(避免切 registry 状态 + 二次调用)。
|
|
@@ -1520,18 +1574,18 @@ export class QueryEngine {
|
|
|
1520
1574
|
// `mountLlm(vajraContext, registry)` → `setLlm`),按「非空即缝」判定会让本分支
|
|
1521
1575
|
// 在生产恒不可达,而测试里构造引擎时不注入缝 ⇒ 套件全绿也发现不了。
|
|
1522
1576
|
if (this.llm && this.llm !== this.registry) {
|
|
1523
|
-
yield { type: 'error', error:
|
|
1577
|
+
yield { type: 'error', error: detail }
|
|
1524
1578
|
return
|
|
1525
1579
|
}
|
|
1526
1580
|
if (!defaultId || defaultId === activeId || !this.registry.get(defaultId)) {
|
|
1527
|
-
yield { type: 'error', error:
|
|
1581
|
+
yield { type: 'error', error: this.modelUnavailableNotice(activeId, activeModel, detail) }
|
|
1528
1582
|
return
|
|
1529
1583
|
}
|
|
1530
1584
|
const fallbackModel = this.registry
|
|
1531
1585
|
.get(defaultId)!
|
|
1532
1586
|
.config.models.find((m) => m.status === 'active')?.id
|
|
1533
1587
|
if (!fallbackModel) {
|
|
1534
|
-
yield { type: 'error', error:
|
|
1588
|
+
yield { type: 'error', error: this.modelUnavailableNotice(activeId, activeModel, detail) }
|
|
1535
1589
|
return
|
|
1536
1590
|
}
|
|
1537
1591
|
|
|
@@ -1558,6 +1612,16 @@ export class QueryEngine {
|
|
|
1558
1612
|
}
|
|
1559
1613
|
}
|
|
1560
1614
|
|
|
1615
|
+
/**
|
|
1616
|
+
* 「模型不可用、且已无可回退的默认模型」时的说明。
|
|
1617
|
+
*
|
|
1618
|
+
* 裸的 `failure` 读起来像模型答错了,而实际上**这一轮请求根本没发出去**:把
|
|
1619
|
+
* 这一层说破,并给出下一步(换模型 / 查密钥与网络),比把上游错误原样抛出来有用。
|
|
1620
|
+
*/
|
|
1621
|
+
private modelUnavailableNotice(providerId: string, model: string, detail: string): string {
|
|
1622
|
+
return t('errors.model_unavailable', { model, provider: providerId, error: detail })
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1561
1625
|
getTools(): Map<string, ToolDefinition> {
|
|
1562
1626
|
return this.tools
|
|
1563
1627
|
}
|
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.
|
|
@@ -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 {
|
|
@@ -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.
|
|
@@ -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.11' 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 = 3761 as const
|
package/src/shared/sanitize.ts
CHANGED
|
@@ -255,3 +255,35 @@ export function sanitizeForDisplay(input: string): string {
|
|
|
255
255
|
result = result.replace(/\f/g, '⟨FF⟩')
|
|
256
256
|
return result
|
|
257
257
|
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Neutralize text that is about to be **injected into the system prompt** inside a
|
|
261
|
+
* tag-delimited block (memory recall, session summaries).
|
|
262
|
+
*
|
|
263
|
+
* Two steps, both load-bearing:
|
|
264
|
+
*
|
|
265
|
+
* 1. `stripDangerousUnicode` — the same invisible set the command path applies.
|
|
266
|
+
* Without it the text can carry an invisible character that hides part of a
|
|
267
|
+
* delimiter from anything scanning the text, while the model still reads it.
|
|
268
|
+
* 2. Drop `<…>`-shaped runs. The injection point wraps the text in
|
|
269
|
+
* `<system-reminder>…</system-reminder>`, so an entry whose own text contains
|
|
270
|
+
* `</system-reminder>` closes that block early and everything after it reads as
|
|
271
|
+
* ordinary prompt text instead of as recalled data. Stripping the brackets is
|
|
272
|
+
* what makes the wrapper unforgeable: the text stays readable, it just stops
|
|
273
|
+
* being able to *end* the block it was pasted into.
|
|
274
|
+
*
|
|
275
|
+
* Same move as `skills/sanitizer.ts` `sanitizeSkillDescription` (which strips
|
|
276
|
+
* `<[^>]*>` for this exact reason); this one additionally strips the invisible set,
|
|
277
|
+
* which the skill path does not. Both are lossy **on purpose** — an injected entry is
|
|
278
|
+
* prose for a model to read, not markup, so no legitimate entry loses meaning.
|
|
279
|
+
*
|
|
280
|
+
* The run is bounded at 200 characters so a stray `<` in prose cannot swallow the
|
|
281
|
+
* rest of the entry, and a letter must follow `<` (or `</`) immediately — so
|
|
282
|
+
* "a < b and c > d" survives while `</system-reminder>` does not. A forged delimiter
|
|
283
|
+
* with a space inside it (`</ system-reminder>`) is not a form this wrapper emits,
|
|
284
|
+
* and buying that case costs every piece of prose containing `< word >`.
|
|
285
|
+
*/
|
|
286
|
+
export function neutralizeInjectedMarkup(input: string): string {
|
|
287
|
+
if (!input) return input
|
|
288
|
+
return stripDangerousUnicode(input).replace(/<\/?[A-Za-z][^<>]{0,200}>/g, '')
|
|
289
|
+
}
|
|
@@ -50,7 +50,7 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
50
50
|
content:
|
|
51
51
|
'── MCP Tool Search ──\n\n' +
|
|
52
52
|
'No MCP servers connected.\n\n' +
|
|
53
|
-
'Connect MCP servers in .mcp.json or via /mcp
|
|
53
|
+
'Connect MCP servers in .mcp.json or via /mcp connect <server-name>.',
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
|
package/src/ui/commands.ts
CHANGED
|
@@ -3172,6 +3172,23 @@ const loopCmd: CommandHandler = async (ctx, args) => {
|
|
|
3172
3172
|
return { content: lines.join('\n\n') }
|
|
3173
3173
|
}
|
|
3174
3174
|
|
|
3175
|
+
// Shared tail of both autonomous-loop prompts below. It carries two fixes:
|
|
3176
|
+
//
|
|
3177
|
+
// - the journal's per-iteration row is the assistant's **visible text**
|
|
3178
|
+
// (`app.tsx` passes `assistantContent`, which only accumulates
|
|
3179
|
+
// `type === 'text'` chunks), so a loop that never emits text has a
|
|
3180
|
+
// progress log with nothing in it — the prompt now asks for one line;
|
|
3181
|
+
// - the prompts used to say `logAutoloopIteration("<id>", "<summary>")`, a
|
|
3182
|
+
// module export *inside* the CLI that is not a tool and so was never
|
|
3183
|
+
// callable, and to have the model write the journal file itself — which
|
|
3184
|
+
// would clobber the counters the CLI maintains there.
|
|
3185
|
+
const journalNotice = (id: string): string =>
|
|
3186
|
+
`\nEnd each iteration with one line of plain text saying where the loop stands.\n` +
|
|
3187
|
+
`The journal records the text you emit: an iteration that emits none is logged as\n` +
|
|
3188
|
+
`having no visible output, and /loop status shows that instead of progress.\n` +
|
|
3189
|
+
`Do not edit ~/.mipham/autoloop/${id}.json yourself — the CLI writes it (iteration\n` +
|
|
3190
|
+
`count, token totals, status) and a direct write would clobber that accounting.`
|
|
3191
|
+
|
|
3175
3192
|
// ── /loop auto <prompt> — autonomous self-paced loop ──
|
|
3176
3193
|
if (sub === 'auto') {
|
|
3177
3194
|
const prompt = args.slice(1).join(' ')
|
|
@@ -3202,9 +3219,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
|
|
|
3202
3219
|
` - delaySeconds: your best estimate of how long to wait (60-3600)\n` +
|
|
3203
3220
|
` - reason: one sentence explaining why\n` +
|
|
3204
3221
|
` - prompt: include this full autonomous loop ID: ${sessionId}\n` +
|
|
3205
|
-
`3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n
|
|
3206
|
-
|
|
3207
|
-
`Use the autoloop-journal module: logAutoloopIteration("${sessionId}", "<summary>").`
|
|
3222
|
+
`3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n` +
|
|
3223
|
+
journalNotice(sessionId)
|
|
3208
3224
|
|
|
3209
3225
|
return {
|
|
3210
3226
|
content:
|
|
@@ -3259,8 +3275,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
|
|
|
3259
3275
|
`You are in an autonomous loop (auto-detected — no interval specified). Each iteration:\n` +
|
|
3260
3276
|
`1. Make progress on the task above\n` +
|
|
3261
3277
|
`2. When you need to wait, call ScheduleWakeup with your chosen delaySeconds and this loop ID: ${sessionId}\n` +
|
|
3262
|
-
`3. When COMPLETE, call ScheduleWakeup with stop:true\n
|
|
3263
|
-
|
|
3278
|
+
`3. When COMPLETE, call ScheduleWakeup with stop:true\n` +
|
|
3279
|
+
journalNotice(sessionId)
|
|
3264
3280
|
|
|
3265
3281
|
return {
|
|
3266
3282
|
content:
|