@miphamai/cli 0.85.33 → 0.85.35
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/services.ts +21 -0
- package/src/agent/sub-agent.ts +129 -21
- package/src/commands/environment.ts +14 -11
- package/src/commands/project.ts +43 -12
- package/src/config/loader.ts +65 -35
- package/src/core/alignment-vocabulary.json +2 -2
- package/src/core/constitution-loader.ts +85 -24
- package/src/core/context.ts +22 -5
- package/src/core/engine.ts +62 -143
- package/src/core/hooks-config.ts +32 -0
- package/src/core/memory/memory-loader.ts +2 -2
- package/src/core/permission-rules.ts +67 -12
- package/src/core/session-log.ts +26 -7
- package/src/core/session-store.ts +4 -3
- package/src/core/tool-gate.ts +222 -0
- package/src/daemon/engine-capabilities.ts +124 -2
- package/src/daemon/remote-engine.ts +3 -0
- package/src/daemon/server.ts +13 -1
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/mcp/client.ts +22 -2
- package/src/plugin/plugin-manager.ts +14 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +8 -0
- package/src/skills/fork-executor.ts +11 -1
- package/src/skills/marketplace.ts +44 -13
- package/src/skills/registry.ts +12 -1
- package/src/tools/agent/agent.ts +3 -0
- package/src/tools/agent/enter-plan.ts +22 -4
- package/src/tools/agent/exit-plan.ts +9 -1
- package/src/tools/agent/skill.ts +1 -0
- package/src/tools/agent/workflow.ts +1 -0
- package/src/tools/exec/git.ts +113 -69
- package/src/tools/index.ts +2 -2
- package/src/ui/app.tsx +15 -0
- package/src/ui/chat.tsx +7 -4
- package/src/ui/commands.ts +140 -20
- package/src/workflow/primitives/agent.ts +12 -1
- package/src/workflow/primitives/loop.ts +14 -0
- package/src/workflow/primitives/verify.ts +13 -1
- package/src/workflow/runtime.ts +1 -0
|
@@ -926,8 +926,20 @@ function lexicallySpelled(p: string): string {
|
|
|
926
926
|
* symlink on purpose, or on a leaf that does not exist yet.
|
|
927
927
|
*/
|
|
928
928
|
function matchPathRule(path: string, pattern: string, segmentMode: 'any' | 'all'): boolean {
|
|
929
|
-
|
|
930
|
-
|
|
929
|
+
// The pattern side already gets a second, anchored spelling from
|
|
930
|
+
// `resolveLanding` below; the **path** side did not. A relative path reaches
|
|
931
|
+
// here from two places: a tool call the model spelled relatively, and — the
|
|
932
|
+
// case that was silently open — a Bash argument extracted by
|
|
933
|
+
// `extractBashFileAccess` (`cat .env` yields `.env`). A deny rule written as
|
|
934
|
+
// `Read(./.env)` therefore matched an absolute `Read` but missed the same
|
|
935
|
+
// file read through the shell. Under deny/ask an extra spelling can only
|
|
936
|
+
// *add* matches, so this direction stays fail-closed; the allow direction is
|
|
937
|
+
// deliberately left alone (a grant is the direction where a second spelling
|
|
938
|
+
// widens what runs).
|
|
939
|
+
const pathSpellings =
|
|
940
|
+
segmentMode === 'any' && !isAbsolutePath(path) ? [path, lexicallySpelled(path)] : [path]
|
|
941
|
+
|
|
942
|
+
const literal = pathSpellings.some((p) => matchPath(p, pattern))
|
|
931
943
|
// The pattern canonicalised on the same axes as the path (`/tmp/**` →
|
|
932
944
|
// `/private/tmp/**`). `expandHome` first: `matchPath` expands the pattern but
|
|
933
945
|
// never the path, so a `~` pattern has to be absolute before it is resolved.
|
|
@@ -935,22 +947,30 @@ function matchPathRule(path: string, pattern: string, segmentMode: 'any' | 'all'
|
|
|
935
947
|
|
|
936
948
|
if (segmentMode === 'all') {
|
|
937
949
|
if (!literal) return false
|
|
950
|
+
const landing = resolveLanding(path)
|
|
938
951
|
if (landing === lexicallySpelled(path)) return true
|
|
939
952
|
return matchPath(landing, canon)
|
|
940
953
|
}
|
|
941
954
|
|
|
942
955
|
if (literal) return true
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
956
|
+
for (const p of pathSpellings) {
|
|
957
|
+
if (matchPath(resolveLanding(p), canon)) return true
|
|
958
|
+
try {
|
|
959
|
+
// The pre-existing check, kept verbatim so this direction stays a
|
|
960
|
+
// mechanical superset of what it used to match (it differs only for a path
|
|
961
|
+
// whose own name contains a glob character).
|
|
962
|
+
if (matchPath(realpathSync(p), expandHome(pattern))) return true
|
|
963
|
+
} catch {
|
|
964
|
+
// Nothing on disk to resolve (ENOENT, EACCES, a path the model invented) —
|
|
965
|
+
// there is no second spelling to try, and the literal already missed.
|
|
966
|
+
}
|
|
953
967
|
}
|
|
968
|
+
return false
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/** Absolute in either spelling the tools accept (POSIX `/…` or Windows `C:\…`). */
|
|
972
|
+
function isAbsolutePath(p: string): boolean {
|
|
973
|
+
return isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p)
|
|
954
974
|
}
|
|
955
975
|
|
|
956
976
|
/**
|
|
@@ -1056,6 +1076,13 @@ export function matchBashRule(
|
|
|
1056
1076
|
)
|
|
1057
1077
|
if (!boundary.test(seg)) return false
|
|
1058
1078
|
}
|
|
1079
|
+
// An allow rule names a program; these options make that program run a
|
|
1080
|
+
// **different** one (`find -exec rm`, `git --upload-pack=…`,
|
|
1081
|
+
// `awk system(…)`). Matching the outer word alone would hand over the
|
|
1082
|
+
// inner command too, so the segment is not covered by the grant. This
|
|
1083
|
+
// list is a floor, not a ceiling — every entry is a construct that
|
|
1084
|
+
// executes a command the rule did not name.
|
|
1085
|
+
if (segmentMode === 'all' && embedsForeignCommand(seg)) return false
|
|
1059
1086
|
return wildcardMatch(subPattern!, seg)
|
|
1060
1087
|
})
|
|
1061
1088
|
}
|
|
@@ -1078,6 +1105,34 @@ export function matchBashRule(
|
|
|
1078
1105
|
return false
|
|
1079
1106
|
}
|
|
1080
1107
|
|
|
1108
|
+
/**
|
|
1109
|
+
* A command segment that runs a program other than the one an allow rule named.
|
|
1110
|
+
*
|
|
1111
|
+
* `Bash(find:*)` is a grant for `find`, not for whatever `-exec` names;
|
|
1112
|
+
* `Bash(git:*)` is not a grant for `--upload-pack`'s payload. The inner command
|
|
1113
|
+
* is never a separate shell segment, so the per-segment allow test sees only
|
|
1114
|
+
* the outer word and passes it. Under deny/ask the wide reading stays — that
|
|
1115
|
+
* direction is about not missing a match.
|
|
1116
|
+
*
|
|
1117
|
+
* Deliberately a short list of *demonstrated* forms rather than every
|
|
1118
|
+
* exec-capable flag in Unix; widening it is safe (the failure mode is one extra
|
|
1119
|
+
* prompt), but an entry that misfires on an ordinary argument would make allow
|
|
1120
|
+
* rules unusable, so each pattern requires the option spelling, not a bare
|
|
1121
|
+
* word.
|
|
1122
|
+
*/
|
|
1123
|
+
function embedsForeignCommand(segment: string): boolean {
|
|
1124
|
+
return (
|
|
1125
|
+
// find(1): -exec / -execdir / -ok / -okdir take a command.
|
|
1126
|
+
/\s-(?:exec|execdir|ok|okdir)(?:\s|$)/.test(segment) ||
|
|
1127
|
+
// git(1) / tar(1): options that name a program to run.
|
|
1128
|
+
/--(?:upload-pack|receive-pack|exec-path|to-command|checkpoint-action)(?:=|\s)/.test(segment) ||
|
|
1129
|
+
// git(1) `-c core.pager=…`-style config that ends in an executed command.
|
|
1130
|
+
/\bcore\.(?:pager|sshcommand|editor)\s*=/i.test(segment) ||
|
|
1131
|
+
// awk(1): system() runs a shell command.
|
|
1132
|
+
/\bsystem\s*\(/.test(segment)
|
|
1133
|
+
)
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1081
1136
|
export function wildcardMatch(pattern: string, input: string): boolean {
|
|
1082
1137
|
const regexStr =
|
|
1083
1138
|
'^' +
|
package/src/core/session-log.ts
CHANGED
|
@@ -253,10 +253,29 @@ export class SessionLog {
|
|
|
253
253
|
private buf: SessionEvent[] = []
|
|
254
254
|
private flushed = 0
|
|
255
255
|
|
|
256
|
-
|
|
257
|
-
|
|
256
|
+
/**
|
|
257
|
+
* @param dir 落盘目录,**默认 `~/.mipham/sessions`**(CLI 的历史真源)。
|
|
258
|
+
* daemon 传自己的目录:它的日志是**审计增量**而不是可恢复历史(真源是 SQLite),
|
|
259
|
+
* 落进 `sessions/` 会被 `--resume` 当成一个"历史不全"的会话列出来。
|
|
260
|
+
*/
|
|
261
|
+
constructor(
|
|
262
|
+
private name: string,
|
|
263
|
+
private dir: string = LOG_DIR,
|
|
264
|
+
) {}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Append one event — in memory *and* on disk.
|
|
268
|
+
*
|
|
269
|
+
* Persisting here rather than only at exit is the difference between "the
|
|
270
|
+
* last turn survived" and "it survived if the process happened to shut down
|
|
271
|
+
* cleanly". `save()` writes only the events added since the last call, so
|
|
272
|
+
* this is one line per event; the alternative — a save at exit — never runs
|
|
273
|
+
* under SIGKILL, a crash, or a closed terminal, and the resumed session then
|
|
274
|
+
* ends one or more turns early.
|
|
275
|
+
*/
|
|
258
276
|
append(event: SessionEvent): void {
|
|
259
277
|
this.buf.push(event)
|
|
278
|
+
this.save()
|
|
260
279
|
}
|
|
261
280
|
|
|
262
281
|
/** 不可变快照(浅拷贝,事件本身视为不可变)。 */
|
|
@@ -268,8 +287,8 @@ export class SessionLog {
|
|
|
268
287
|
save(): void {
|
|
269
288
|
// Session logs contain full conversation + tool results (possibly credentials):
|
|
270
289
|
// restrict to owner-only (dir 0700, file 0600).
|
|
271
|
-
mkdirSync(
|
|
272
|
-
const path = join(
|
|
290
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 })
|
|
291
|
+
const path = join(this.dir, `${sanitizeSessionName(this.name)}.jsonl`)
|
|
273
292
|
|
|
274
293
|
// A writer killed mid-append can leave a partial line with no trailing
|
|
275
294
|
// newline. `open()` skips that line, but the next append would glue the new
|
|
@@ -298,9 +317,9 @@ export class SessionLog {
|
|
|
298
317
|
}
|
|
299
318
|
|
|
300
319
|
/** 从既有 JSONL 打开,逐行解析为事件(已落盘事件标记为已 flush)。 */
|
|
301
|
-
static open(name: string): SessionLog {
|
|
302
|
-
const log = new SessionLog(name)
|
|
303
|
-
const path = join(
|
|
320
|
+
static open(name: string, dir: string = LOG_DIR): SessionLog {
|
|
321
|
+
const log = new SessionLog(name, dir)
|
|
322
|
+
const path = join(dir, `${sanitizeSessionName(name)}.jsonl`)
|
|
304
323
|
// 类型闸在读取之前:`SessionStore.load` 在快照读不出来时**回落到这里**,所以路径上
|
|
305
324
|
// 是个 FIFO 时不能在这里换个函数继续等 —— 读不动就当空日志(见 shared/regular-file.ts)。
|
|
306
325
|
let raw = readRegularFileSync(path)
|
|
@@ -147,7 +147,10 @@ export class SessionStore {
|
|
|
147
147
|
if (raw === null) return SessionLog.open(name)
|
|
148
148
|
const old = asStoredSnapshot(JSON.parse(raw))
|
|
149
149
|
if (old) {
|
|
150
|
-
// 旧格式快照 → 迁移为事件日志(重写文件,避免后续 append
|
|
150
|
+
// 旧格式快照 → 迁移为事件日志(重写文件,避免后续 append 混格式)。
|
|
151
|
+
// 旧文件必须在 append **之前**删掉:append 现在自己就落盘(325-009),
|
|
152
|
+
// 先 append 再 unlink 会把刚写好的事件日志一并删掉。
|
|
153
|
+
unlinkSync(path)
|
|
151
154
|
const log = new SessionLog(name)
|
|
152
155
|
log.append({
|
|
153
156
|
type: 'session/start',
|
|
@@ -158,8 +161,6 @@ export class SessionStore {
|
|
|
158
161
|
cwd: old.metadata.cwd,
|
|
159
162
|
})
|
|
160
163
|
for (const m of old.messages) for (const e of messageToEvents(m)) log.append(e)
|
|
161
|
-
unlinkSync(path)
|
|
162
|
-
log.save()
|
|
163
164
|
return log
|
|
164
165
|
}
|
|
165
166
|
} catch {
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import type { HookEngine } from './hooks'
|
|
2
|
+
import type { ExperienceRuleEngine } from './rule-engine'
|
|
3
|
+
import type { PreFlightChecker } from './preflight-checker'
|
|
4
|
+
import type { ConstitutionLoader } from './constitution-loader'
|
|
5
|
+
import type { SelfCritique } from './self-critique'
|
|
6
|
+
import type { ProviderRegistry } from '../providers/registry'
|
|
7
|
+
import type { Llm } from '../providers/llm'
|
|
8
|
+
import { getMetrics } from './metrics'
|
|
9
|
+
import { createT } from '../i18n-core/t'
|
|
10
|
+
import enUS from '../i18n-core/locales/en-US.json'
|
|
11
|
+
import type { TranslationMap } from '../i18n-core/types'
|
|
12
|
+
|
|
13
|
+
const t = createT(enUS as TranslationMap, enUS as TranslationMap)
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Everything the pre-execution chain needs, resolved lazily.
|
|
17
|
+
*
|
|
18
|
+
* The chain was written inline in `Engine.executeTool`; `SubAgent` runs its own
|
|
19
|
+
* tool loop and called none of it, so a `Write` carrying an `apiKey = "sk-…"`
|
|
20
|
+
* was blocked in the main loop and executed verbatim one level down. This module
|
|
21
|
+
* is the single definition both loops call — duplicating the chain in the
|
|
22
|
+
* sub-agent would let the two drift again, which is the defect being fixed.
|
|
23
|
+
*
|
|
24
|
+
* The three constructors are getters, not instances: the engine creates them
|
|
25
|
+
* lazily on first use and that laziness is deliberate (`PreFlightChecker` builds
|
|
26
|
+
* the error-signature DB, `ConstitutionLoader` reads the vocabulary).
|
|
27
|
+
*/
|
|
28
|
+
export interface ToolGateDeps {
|
|
29
|
+
hookEngine?: HookEngine
|
|
30
|
+
ruleEngine?: ExperienceRuleEngine
|
|
31
|
+
preflight?: () => PreFlightChecker
|
|
32
|
+
constitution?: () => ConstitutionLoader
|
|
33
|
+
selfCritique?: () => SelfCritique
|
|
34
|
+
/** `crsi.preToolHook !== false` — read once by the caller, same as the engine. */
|
|
35
|
+
crsiPreToolHook: boolean
|
|
36
|
+
registry: ProviderRegistry
|
|
37
|
+
llm?: Llm
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type ToolGateOutcome =
|
|
41
|
+
| { ok: false; content: string; error: string; notRun?: boolean }
|
|
42
|
+
| { ok: true; params: Record<string, unknown>; warnings: string[] }
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The text a principle's `audit_pattern` is matched against.
|
|
46
|
+
*
|
|
47
|
+
* Not `JSON.stringify(params)`. Patterns are written against source text —
|
|
48
|
+
* `apiKey = "sk-…"` — while JSON spells that value `apiKey = \"sk-…\"`, so the
|
|
49
|
+
* quote class `['"]` never met the escaped quote and **the most idiomatic
|
|
50
|
+
* spelling was the one that could not match**. Rendering each parameter as
|
|
51
|
+
* `name=value` (strings verbatim) removes the escaping question entirely and
|
|
52
|
+
* also lets the key carry the signal (`{ apiKey: '…' }` → `apiKey=…`).
|
|
53
|
+
*/
|
|
54
|
+
export function toolAuditSurface(params: Record<string, unknown>): string {
|
|
55
|
+
return Object.entries(params)
|
|
56
|
+
.map(([key, value]) => `${key}=${typeof value === 'string' ? value : JSON.stringify(value)}`)
|
|
57
|
+
.join('\n')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Run every pre-execution gate for one tool call, in the engine's order:
|
|
62
|
+
* PreToolUse hook → CRSI rules → SIS preflight → constitution → self-critique.
|
|
63
|
+
*
|
|
64
|
+
* `params` is returned by reference when nothing rewrote it; callers use that
|
|
65
|
+
* identity (`effectiveParams !== params`) to decide whether the permission gate
|
|
66
|
+
* has to rule again on what will actually run.
|
|
67
|
+
*/
|
|
68
|
+
export async function runPreToolGate(
|
|
69
|
+
name: string,
|
|
70
|
+
params: Record<string, unknown>,
|
|
71
|
+
deps: ToolGateDeps,
|
|
72
|
+
sessionId: string,
|
|
73
|
+
): Promise<ToolGateOutcome> {
|
|
74
|
+
let effectiveParams = params
|
|
75
|
+
const warnings: string[] = []
|
|
76
|
+
|
|
77
|
+
// ── PreToolUse hook ──
|
|
78
|
+
if (deps.hookEngine) {
|
|
79
|
+
const preResult = await deps.hookEngine.executePreToolUse(name, params, sessionId)
|
|
80
|
+
if (!preResult.allowed) {
|
|
81
|
+
return {
|
|
82
|
+
ok: false,
|
|
83
|
+
content: '',
|
|
84
|
+
error: preResult.reason || t('errors.tool_blocked', { name }),
|
|
85
|
+
notRun: true,
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// `permissionDecision` narrows only — never widens. `ask` stops the call here
|
|
90
|
+
// (this CLI has no interactive approval prompt; `ask` is a hard refusal, the
|
|
91
|
+
// same as the `default` mode's ask path). `allow` is deliberately **not**
|
|
92
|
+
// honoured: a hook can come from the repository's own settings, so letting it
|
|
93
|
+
// auto-approve is the same defect as a project-supplied agent definition that
|
|
94
|
+
// grants itself `bypassPermissions` — the criterion is the *direction*, not the
|
|
95
|
+
// key name. `defer` (and an absent decision) means "no override", which is
|
|
96
|
+
// exactly what happens when we do nothing.
|
|
97
|
+
if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
content: '',
|
|
101
|
+
error: preResult.reason || t('errors.tool_hook_ask', { name }),
|
|
102
|
+
notRun: true,
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (preResult.modifiedInput) {
|
|
107
|
+
effectiveParams = { ...params, ...preResult.modifiedInput }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// A hook's `additionalContext` is how every non-blocking hook speaks — the
|
|
111
|
+
// exit-1 stderr, a spawn failure, an unreachable `mcp_tool` server (see
|
|
112
|
+
// `core/hooks-executor.ts`). This path used to read only `allowed` /
|
|
113
|
+
// `modifiedInput`, so all of it was produced and then dropped. The warnings
|
|
114
|
+
// channel already reaches the model: it is prepended to the tool result.
|
|
115
|
+
// A non-`[rule:…]` line is ignored by the effectiveness tracker, so pushing
|
|
116
|
+
// prose here is safe.
|
|
117
|
+
if (preResult.additionalContext) {
|
|
118
|
+
warnings.push(preResult.additionalContext)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ── CRSI RuleEngine intercept ──
|
|
123
|
+
if (deps.crsiPreToolHook !== false && deps.ruleEngine) {
|
|
124
|
+
const ruleResult = deps.ruleEngine.intercept(name, effectiveParams)
|
|
125
|
+
if (Object.keys(ruleResult.modified).length > 0) {
|
|
126
|
+
getMetrics().crsiRuleApplications.inc()
|
|
127
|
+
effectiveParams = ruleResult.modified
|
|
128
|
+
}
|
|
129
|
+
if (ruleResult.warnings.length > 0) {
|
|
130
|
+
// Append, do not replace: this array may already hold a PreToolUse hook's
|
|
131
|
+
// `additionalContext`. Every other writer below uses the spread form for the
|
|
132
|
+
// same reason — assignment here would silently drop whichever was written
|
|
133
|
+
// first ("two writers, one list").
|
|
134
|
+
warnings.push(...ruleResult.warnings)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ── SIS PreFlightChecker — known error pattern interception ──
|
|
139
|
+
if (deps.preflight) {
|
|
140
|
+
const preflight = deps.preflight().check(name, effectiveParams)
|
|
141
|
+
if (preflight.action === 'block') {
|
|
142
|
+
getMetrics().sisInterceptions.inc()
|
|
143
|
+
return {
|
|
144
|
+
ok: false,
|
|
145
|
+
content: preflight.warning || 'SIS 免疫系统拦截了此操作',
|
|
146
|
+
error: preflight.warning || 'SIS 免疫系统拦截了此操作',
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (preflight.action === 'fix' && preflight.modifiedParams) {
|
|
150
|
+
getMetrics().sisInterceptions.inc()
|
|
151
|
+
effectiveParams = preflight.modifiedParams
|
|
152
|
+
if (preflight.warning) {
|
|
153
|
+
warnings.push(preflight.warning)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (preflight.action === 'warn' && preflight.warning) {
|
|
157
|
+
warnings.push(preflight.warning)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ── Mipham Constitution — constitutional principle enforcement ──
|
|
162
|
+
// Block-level violations (enforce: block) halt execution immediately.
|
|
163
|
+
// Warn-level violations (enforce: warn) are appended to the warnings.
|
|
164
|
+
if (deps.constitution) {
|
|
165
|
+
const principles = deps.constitution().getPrinciplesForTool(name)
|
|
166
|
+
for (const principle of principles) {
|
|
167
|
+
if (principle.enforce === 'block') {
|
|
168
|
+
// Audit: check if the tool params match a violation pattern
|
|
169
|
+
if (principle.audit_pattern) {
|
|
170
|
+
try {
|
|
171
|
+
const regex = new RegExp(principle.audit_pattern, 'i')
|
|
172
|
+
if (regex.test(toolAuditSurface(effectiveParams))) {
|
|
173
|
+
return {
|
|
174
|
+
ok: false,
|
|
175
|
+
content: `🚫 Constitution violation blocked: **${principle.id}** — ${principle.text}`,
|
|
176
|
+
error: `Constitutional principle "${principle.id}" blocked this operation.`,
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
} catch {
|
|
180
|
+
// Invalid regex — skip this principle
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (principle.enforce === 'warn') {
|
|
185
|
+
warnings.push(`⚖️ Constitution: ${principle.id} — ${principle.text}`)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ── Self-Critique Hook — RLAIF-style tool-call safety verification ──
|
|
191
|
+
// Uses a fast model to critique the tool call before execution.
|
|
192
|
+
// Fail-open: if the critique times out or errors, the tool still executes.
|
|
193
|
+
if (deps.selfCritique) {
|
|
194
|
+
const selfCritique = deps.selfCritique()
|
|
195
|
+
if (selfCritique.getConfig().enabled) {
|
|
196
|
+
const critiqueResult = await selfCritique.critique(
|
|
197
|
+
name,
|
|
198
|
+
effectiveParams,
|
|
199
|
+
deps.registry,
|
|
200
|
+
deps.llm,
|
|
201
|
+
)
|
|
202
|
+
if (critiqueResult) {
|
|
203
|
+
if (critiqueResult.score < selfCritique.getConfig().threshold) {
|
|
204
|
+
// Score too low — block with explanation
|
|
205
|
+
if (!critiqueResult.safe) {
|
|
206
|
+
return {
|
|
207
|
+
ok: false,
|
|
208
|
+
content: `🔍 Self-Critique blocked: ${critiqueResult.reasoning}`,
|
|
209
|
+
error: `Self-Critique safety check failed (score: ${(critiqueResult.score * 100).toFixed(0)}%). ${critiqueResult.correction || ''}`,
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
// Score low but safe — warn but allow
|
|
213
|
+
warnings.push(
|
|
214
|
+
`🔍 Self-Critique: ${critiqueResult.reasoning}${critiqueResult.correction ? ` — Suggestion: ${critiqueResult.correction}` : ''}`,
|
|
215
|
+
)
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return { ok: true, params: effectiveParams, warnings }
|
|
222
|
+
}
|
|
@@ -20,8 +20,9 @@
|
|
|
20
20
|
* `test/integrity/daemon-capability-parity.test.ts` 能咬住的源码差异,而不是靠人记得。
|
|
21
21
|
*
|
|
22
22
|
* 不搬 `index.tsx` 的整套装配:ArtifactServer 是 TUI 画廊的 localhost 监听器、
|
|
23
|
-
* AgentViewManager 的唯一消费者是 TUI slash
|
|
24
|
-
*
|
|
23
|
+
* AgentViewManager 的唯一消费者是 TUI slash 命令。这里接**有后果的六条**
|
|
24
|
+
* (skills / rulesLoader / hookEngine / agentRegistry / instructions + 系统提示 / llm);
|
|
25
|
+
* 其余按后果分级进守卫的具名豁免表,逐条写理由。
|
|
25
26
|
*/
|
|
26
27
|
|
|
27
28
|
import type { QueryEngine } from '../core/engine'
|
|
@@ -35,6 +36,10 @@ import { isSafeMode } from '../core/safe-mode'
|
|
|
35
36
|
import { loadSettingsJson } from '../config/loader'
|
|
36
37
|
import { getWorkspaceTrust, warnProjectHooksSkipped } from '../core/workspace-trust'
|
|
37
38
|
import { AgentRegistry } from '../agent/agent-registry'
|
|
39
|
+
import { InstructionsLoader } from '../core/instructions'
|
|
40
|
+
import { loadSessionMemories } from '../core/memory/memory-loader'
|
|
41
|
+
import { SessionLog } from '../core/session-log'
|
|
42
|
+
import { miphamHome } from '../core/paths'
|
|
38
43
|
|
|
39
44
|
export interface DaemonEngineCapabilities {
|
|
40
45
|
/** 会话工作目录 —— 三者的派生源(外部 skill 路径 / hooks / agents 都从它算)。 */
|
|
@@ -43,6 +48,8 @@ export interface DaemonEngineCapabilities {
|
|
|
43
48
|
registry: ProviderRegistry
|
|
44
49
|
/** `config.skills.paths`(外部 skill 目录)。省略即只加载内置与用户 skill。 */
|
|
45
50
|
skillsPaths?: string[]
|
|
51
|
+
/** `config.skills.reminder`。省略即 `full`,与 CLI 侧的默认同。 */
|
|
52
|
+
skillsReminder?: 'full' | 'compact' | 'off'
|
|
46
53
|
}
|
|
47
54
|
|
|
48
55
|
/**
|
|
@@ -127,6 +134,22 @@ function agentsFor(cwd: string): AgentRegistry {
|
|
|
127
134
|
return registry
|
|
128
135
|
}
|
|
129
136
|
|
|
137
|
+
/**
|
|
138
|
+
* 指令装载器,**每会话新建、不记忆化** —— 与 `RulesLoader` 同一个理由(见 D7):
|
|
139
|
+
* 一个长命 daemon 服务多个会话,按 cwd 共享一只的话,会话期间改过的 `CLAUDE.md` /
|
|
140
|
+
* `MIPHAM.md` 对所有后来新建的会话都**永远看不见**,直到那个 loader 自己 `refresh()`。
|
|
141
|
+
* 代价只是每次建引擎多读几个小文件 —— 与「配额规则」那点成本同量级。
|
|
142
|
+
*
|
|
143
|
+
* 它是**系统提示里「项目规则」那一段**的唯一来源(`MIPHAM.md` / `CLAUDE.md` / `AGENTS.md`
|
|
144
|
+
* / `USER.md` 链 + CRSI 教训),也是 CRSI 召回扳机的指针来源 —— 两者必须是同一份选择,
|
|
145
|
+
* 否则「扳机说去读那份文件」与「提示里写的是另一份」会分叉。
|
|
146
|
+
*/
|
|
147
|
+
function loadInstructionsFor(cwd: string): InstructionsLoader {
|
|
148
|
+
const loader = new InstructionsLoader()
|
|
149
|
+
loader.loadAll(cwd)
|
|
150
|
+
return loader
|
|
151
|
+
}
|
|
152
|
+
|
|
130
153
|
/**
|
|
131
154
|
* 把一个 daemon 引擎接成「和交互式 CLI 同等能干活」的样子。
|
|
132
155
|
*
|
|
@@ -146,7 +169,106 @@ export function wireDaemonEngine(engine: QueryEngine, opts: DaemonEngineCapabili
|
|
|
146
169
|
engine.setHookEngine(hooksFor(opts.cwd, skills))
|
|
147
170
|
engine.setAgentRegistry(agentsFor(opts.cwd))
|
|
148
171
|
|
|
172
|
+
// ── 系统提示:daemon 此前**一条都没有** ──────────────────────────────
|
|
173
|
+
// 后果不是「提示朴素一点」,而是整条 headless 路径上模型不知道自己是谁:
|
|
174
|
+
// MIPHAM.md 的身份段(集团 MIPHAM.md §〇,强制性)、CLAUDE.md 的项目规则、
|
|
175
|
+
// 记忆、skills 提醒**一条都到不了**经渠道(飞书 / Telegram / 企微 / 钉钉)、
|
|
176
|
+
// `attach` 远端、以及基准 harness 驱动的会话。
|
|
177
|
+
//
|
|
178
|
+
// 与 CLI 同源、同顺序(`index.tsx:524` + `:605-771`),只少三样**会话脚手架**:
|
|
179
|
+
// 首跑引导 / 密钥到期提醒 / 上一会话摘要 —— 它们属于「一次性的终端会话」,
|
|
180
|
+
// 而 daemon 一个进程服务多个会话,把它们烘进每个会话的提示只是噪音。
|
|
181
|
+
const instructions = loadInstructionsFor(opts.cwd)
|
|
182
|
+
engine.setInstructions(instructions)
|
|
183
|
+
|
|
184
|
+
const context = engine.getContext()
|
|
185
|
+
// 权限段**读时派生**。烘进去的会是模式的一份拷贝,而 daemon 的档位会经 `set_mode`
|
|
186
|
+
// 在会话中途变(`server.ts` 的 `sessionModes`):往窄切是自纠正的,**往宽切**则让
|
|
187
|
+
// 模型拿着旧指令拒绝做它已被允许做的事。接的是 live 的 `permission`,同一实例也交给
|
|
188
|
+
// 引擎去执行,故下一次请求就与新档一致。
|
|
189
|
+
context.setPermissionContextSource(() =>
|
|
190
|
+
instructions.buildPermissionBlock(engine.getPermission().getMode()),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
const basePrompt = instructions.buildSystemPrompt()
|
|
194
|
+
const extras = [
|
|
195
|
+
skills.buildSystemReminder(5000, opts.skillsReminder ?? 'full'),
|
|
196
|
+
// 预算显式给 5000:`getMemoryManager()` 是进程级单例,跟着某个会话的窗口走会让
|
|
197
|
+
// 后建的会话改掉前一个的预算 —— daemon 的会话窗口各不相同,这是唯一不互相干扰的取值。
|
|
198
|
+
loadSessionMemories(basePrompt, 5000),
|
|
199
|
+
]
|
|
200
|
+
.filter((part) => part.length > 0)
|
|
201
|
+
.join('\n\n')
|
|
202
|
+
|
|
203
|
+
// `buildSystemPrompt()` 结尾**没有换行**,`extras` 以 `<system-reminder>` 开头:
|
|
204
|
+
// 直接相加会把标签粘在上一句末尾(CLI 侧 `index.tsx` 是 `\n\n` 连接)。建提示与
|
|
205
|
+
// 压缩后的重建必须走同一个连接方式,否则两条路径的提示形状会分叉。
|
|
206
|
+
const withExtras = (base: string): string => (extras ? `${base}\n\n${extras}` : base)
|
|
207
|
+
context.setSystemPrompt(withExtras(basePrompt))
|
|
208
|
+
// 压缩之后引擎会让提示重建一次;重建前先回读磁盘,**只换指令那一段**,`extras`
|
|
209
|
+
// 原样保留 —— 那是建会话时拼进来的会话级上下文,再生成一遍等于把它们重复塞进每个请求。
|
|
210
|
+
context.setSystemPromptRebuilder(() => {
|
|
211
|
+
instructions.refresh()
|
|
212
|
+
return withExtras(instructions.buildSystemPrompt())
|
|
213
|
+
})
|
|
214
|
+
|
|
149
215
|
// 语义等价于不接(`llmChat` 本就是 `this.llm ?? this.registry`),接上是为了让
|
|
150
216
|
// 两个入口的能力集合真的相等;D2 靠它证明「先修语义再对等」这条顺序约束。
|
|
151
217
|
engine.setLlm(opts.registry)
|
|
152
218
|
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* daemon 会话日志目录 —— **与 CLI 的 `~/.mipham/sessions` 分开**是设计的一部分。
|
|
222
|
+
*
|
|
223
|
+
* daemon 的历史真源是它自己的 SQLite(`daemon.db`,REST API 也读它),日志只记**本进程
|
|
224
|
+
* 窗口内**发生的事。若落进 `sessions/`,`SessionStore.list()` 会把它当成一个可恢复会话
|
|
225
|
+
* 列出来,而它的历史是不全的 —— 那就造出一个「看起来能恢复、恢复出来缺半截」的假广告,
|
|
226
|
+
* 正是本仓反复在修的那一类。分目录之后,`--resume` **结构上**够不到它。
|
|
227
|
+
*/
|
|
228
|
+
export function daemonSessionLogDir(): string {
|
|
229
|
+
return miphamHome('daemon-sessions')
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export interface DaemonSessionLogFacts {
|
|
233
|
+
sessionId: string
|
|
234
|
+
cwd: string
|
|
235
|
+
provider: string
|
|
236
|
+
model: string
|
|
237
|
+
permissionMode: string
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 给 daemon 会话挂一份**审计用**日志 —— 收口「daemon 会话一条 JSONL 都不写」(ROADMAP T5)。
|
|
242
|
+
*
|
|
243
|
+
* 三条约束,每条都有后果:
|
|
244
|
+
*
|
|
245
|
+
* 1. **必须在 DB 回灌之后调用**(`server.ts` 里紧跟 `wireDaemonEngine`)。日志记的是
|
|
246
|
+
* 「本进程期间发生了什么」。把回灌的历史镜像进来会**重复追加**同一批消息 ——
|
|
247
|
+
* `WorkerPool` 会驱逐空闲 worker,重建引擎时那段历史会被再写一遍 ——
|
|
248
|
+
* 而且把一个审计增量伪装成完整历史。
|
|
249
|
+
* 2. **`authoritative: false`**:`ContextManager` 的「model-visible means logged」断言
|
|
250
|
+
* 只对**完整**日志有意义。残缺日志会让它对每一行旧历史报警,开着的调试断言会因此
|
|
251
|
+
* 炸掉整个 daemon 会话。关掉的是**断言**,写通照常。
|
|
252
|
+
* 3. 名字取 `daemon-<uuid>`:让人一眼看出它不是 CLI 的会话名。
|
|
253
|
+
*
|
|
254
|
+
* **已知边界(如实记)**:日志里 `compaction/summary` 的 `replacedCount` 是按**日志窗口**
|
|
255
|
+
* 算的(`context.ts` 用 `deriveMessages(log)` 的长度),不是按整段对话 —— 旧历史从没进过
|
|
256
|
+
* 这份日志。读审计文件时要知道这个数只对「被记录的那一段」成立。
|
|
257
|
+
*/
|
|
258
|
+
export function attachDaemonSessionLog(
|
|
259
|
+
engine: QueryEngine,
|
|
260
|
+
facts: DaemonSessionLogFacts,
|
|
261
|
+
): SessionLog {
|
|
262
|
+
const log = new SessionLog(`daemon-${facts.sessionId}`, daemonSessionLogDir())
|
|
263
|
+
log.append({
|
|
264
|
+
type: 'session/start',
|
|
265
|
+
at: Date.now(),
|
|
266
|
+
sessionId: facts.sessionId,
|
|
267
|
+
provider: facts.provider,
|
|
268
|
+
model: facts.model,
|
|
269
|
+
cwd: facts.cwd,
|
|
270
|
+
permissionMode: facts.permissionMode,
|
|
271
|
+
})
|
|
272
|
+
engine.getContext().setLog(log, { authoritative: false })
|
|
273
|
+
return log
|
|
274
|
+
}
|
|
@@ -45,6 +45,9 @@ export interface RemoteEngineOptions {
|
|
|
45
45
|
* consumes from the local engine.
|
|
46
46
|
*/
|
|
47
47
|
export class RemoteEngine {
|
|
48
|
+
/** Attach mode: provider/model are the daemon's choice, not this process's. */
|
|
49
|
+
readonly isRemote = true
|
|
50
|
+
|
|
48
51
|
private sessionId: string
|
|
49
52
|
private port: number
|
|
50
53
|
private token: string
|
package/src/daemon/server.ts
CHANGED
|
@@ -37,7 +37,7 @@ import { createDingtalkAdapter } from './dingtalk/adapter.js'
|
|
|
37
37
|
import { createDingtalkApi } from './dingtalk/api.js'
|
|
38
38
|
import type { DingtalkConfig } from './dingtalk/types.js'
|
|
39
39
|
import { startHeartbeat } from './heartbeat'
|
|
40
|
-
import { wireDaemonEngine } from './engine-capabilities'
|
|
40
|
+
import { wireDaemonEngine, attachDaemonSessionLog } from './engine-capabilities'
|
|
41
41
|
import {
|
|
42
42
|
cancelAllSessionTimers,
|
|
43
43
|
unregisterWakeupHandler,
|
|
@@ -293,6 +293,18 @@ export function createServer(config: ServerConfig): Server<WsData> {
|
|
|
293
293
|
cwd,
|
|
294
294
|
registry: sharedRegistry,
|
|
295
295
|
skillsPaths: daemonConfig.skills?.paths,
|
|
296
|
+
skillsReminder: daemonConfig.skills?.reminder,
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
// 审计日志必须在上面那次 DB 回灌**之后**挂 —— 它只记本进程窗口内发生的事,
|
|
300
|
+
// 镜像历史会在引擎重建时重复追加(WorkerPool 会驱逐空闲 worker)。
|
|
301
|
+
// 见 `attachDaemonSessionLog` 的三条约束。
|
|
302
|
+
attachDaemonSessionLog(engine, {
|
|
303
|
+
sessionId,
|
|
304
|
+
cwd,
|
|
305
|
+
provider,
|
|
306
|
+
model,
|
|
307
|
+
permissionMode: permission.getMode(),
|
|
296
308
|
})
|
|
297
309
|
engineCache.set(sessionId, engine)
|
|
298
310
|
return engine
|
|
@@ -481,6 +481,7 @@
|
|
|
481
481
|
"source_user": "user",
|
|
482
482
|
"source_project": "project",
|
|
483
483
|
"gated": "⚠️ workspace not trusted — will not run",
|
|
484
|
+
"undispatched": "⚠️ no dispatch point in this version — will not run",
|
|
484
485
|
"found": "{count} hook(s) found.",
|
|
485
486
|
"error": "── Hooks ──\n\nCould not read hooks directory."
|
|
486
487
|
},
|