@miphamai/cli 0.85.32 → 0.85.34
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/credential-masker/env-filter.ts +37 -0
- package/src/core/engine.ts +59 -140
- package/src/core/permission-rules.ts +163 -14
- package/src/core/permission.ts +14 -1
- package/src/core/session-log.ts +11 -0
- package/src/core/session-store.ts +4 -3
- package/src/core/tool-gate.ts +222 -0
- package/src/core/workspace-trust.ts +50 -17
- package/src/daemon/remote-engine.ts +3 -0
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/index.tsx +6 -0
- package/src/mcp/client.ts +22 -2
- package/src/mcp/protocol.ts +16 -2
- package/src/plugin/plugin-manager.ts +29 -3
- package/src/providers/fetch-utils.ts +49 -0
- package/src/providers/openai-compat.ts +28 -2
- package/src/shared/git-env.ts +37 -13
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +17 -0
- package/src/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/computer/browser.ts +13 -0
- package/src/tools/exec/git.ts +113 -69
- package/src/tools/file/edit.ts +19 -3
- package/src/tools/file/grep.ts +5 -1
- package/src/tools/file/write.ts +18 -1
- package/src/tools/index.ts +2 -2
- package/src/tools/network/web-fetch.ts +12 -0
- package/src/tools/system/tool-search.ts +35 -3
- package/src/ui/app.tsx +105 -4
- package/src/ui/chat.tsx +21 -7
- package/src/ui/commands.ts +127 -18
- 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
|
@@ -143,6 +143,39 @@ const PREFIX_VALUE_OPTIONS = new Set([
|
|
|
143
143
|
'--max-procs', // xargs
|
|
144
144
|
])
|
|
145
145
|
|
|
146
|
+
/**
|
|
147
|
+
* Flags that collide with a value-taking option spelling but are booleans for
|
|
148
|
+
* this wrapper. The shared table made `sudo -n rm -rf /tmp/x` consume `rm` as
|
|
149
|
+
* `-n`'s value, so the base command came out as `-rf` and a `Bash(rm:*)` deny
|
|
150
|
+
* never saw the command at all. `sudo -E` (xargs' `--eof`) and `sudo -s`
|
|
151
|
+
* (timeout's `--signal`) fail the same way. A boolean flag never takes the next
|
|
152
|
+
* token; without this, the real command is one token further along than the
|
|
153
|
+
* matcher looks.
|
|
154
|
+
*/
|
|
155
|
+
const WRAPPER_BOOLEAN_OPTIONS: Record<string, ReadonlySet<string>> = {
|
|
156
|
+
sudo: new Set([
|
|
157
|
+
'-n',
|
|
158
|
+
'--non-interactive',
|
|
159
|
+
'-E',
|
|
160
|
+
'--preserve-env',
|
|
161
|
+
'-H',
|
|
162
|
+
'--set-home',
|
|
163
|
+
'-A',
|
|
164
|
+
'--askpass',
|
|
165
|
+
'-b',
|
|
166
|
+
'--background',
|
|
167
|
+
'-S',
|
|
168
|
+
'--stdin',
|
|
169
|
+
'-s',
|
|
170
|
+
'--shell',
|
|
171
|
+
'-i',
|
|
172
|
+
'--login',
|
|
173
|
+
'-K',
|
|
174
|
+
'--remove-timestamp',
|
|
175
|
+
]),
|
|
176
|
+
doas: new Set(['-n', '--non-interactive', '-s', '--shell']),
|
|
177
|
+
}
|
|
178
|
+
|
|
146
179
|
/**
|
|
147
180
|
* Shell interpreters whose `-c` argument is itself a complete command line.
|
|
148
181
|
*
|
|
@@ -571,7 +604,16 @@ function effectiveCommand(tokens: string[]): {
|
|
|
571
604
|
while (i < tokens.length && tokens[i]!.startsWith('-')) {
|
|
572
605
|
const opt = tokens[i]!
|
|
573
606
|
i++
|
|
574
|
-
|
|
607
|
+
// A flag that is a boolean for *this* wrapper never consumes the next
|
|
608
|
+
// token, even though another wrapper's table calls the same spelling
|
|
609
|
+
// value-taking (see WRAPPER_BOOLEAN_OPTIONS).
|
|
610
|
+
if (
|
|
611
|
+
PREFIX_VALUE_OPTIONS.has(opt) &&
|
|
612
|
+
!WRAPPER_BOOLEAN_OPTIONS[name]?.has(opt) &&
|
|
613
|
+
i < tokens.length
|
|
614
|
+
) {
|
|
615
|
+
i++ // skip the flag's value
|
|
616
|
+
}
|
|
575
617
|
}
|
|
576
618
|
if (name === 'env') {
|
|
577
619
|
// `VAR=value` assignments. A quoted value spans several whitespace-split
|
|
@@ -884,8 +926,20 @@ function lexicallySpelled(p: string): string {
|
|
|
884
926
|
* symlink on purpose, or on a leaf that does not exist yet.
|
|
885
927
|
*/
|
|
886
928
|
function matchPathRule(path: string, pattern: string, segmentMode: 'any' | 'all'): boolean {
|
|
887
|
-
|
|
888
|
-
|
|
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))
|
|
889
943
|
// The pattern canonicalised on the same axes as the path (`/tmp/**` →
|
|
890
944
|
// `/private/tmp/**`). `expandHome` first: `matchPath` expands the pattern but
|
|
891
945
|
// never the path, so a `~` pattern has to be absolute before it is resolved.
|
|
@@ -893,22 +947,30 @@ function matchPathRule(path: string, pattern: string, segmentMode: 'any' | 'all'
|
|
|
893
947
|
|
|
894
948
|
if (segmentMode === 'all') {
|
|
895
949
|
if (!literal) return false
|
|
950
|
+
const landing = resolveLanding(path)
|
|
896
951
|
if (landing === lexicallySpelled(path)) return true
|
|
897
952
|
return matchPath(landing, canon)
|
|
898
953
|
}
|
|
899
954
|
|
|
900
955
|
if (literal) return true
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
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
|
+
}
|
|
911
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)
|
|
912
974
|
}
|
|
913
975
|
|
|
914
976
|
/**
|
|
@@ -977,6 +1039,19 @@ export function matchBashRule(
|
|
|
977
1039
|
return qualifies(paths, (p) => matchPathRule(p, subPattern!, segmentMode))
|
|
978
1040
|
}
|
|
979
1041
|
|
|
1042
|
+
// A `Read` deny/ask rule protects the *path*, not one tool: Write and Edit
|
|
1043
|
+
// touch the same file the rule was written to keep off-limits, so routing
|
|
1044
|
+
// around it by overwriting the file left `Read(secrets/**)` enforceable only
|
|
1045
|
+
// against readers. Only the deny/ask direction bridges — an `allow` bridge
|
|
1046
|
+
// would be a privilege expansion (`Read(X)` never granted Write to X).
|
|
1047
|
+
if (
|
|
1048
|
+
segmentMode !== 'all' &&
|
|
1049
|
+
baseTool === 'Read' &&
|
|
1050
|
+
(toolName === 'Write' || toolName === 'Edit')
|
|
1051
|
+
) {
|
|
1052
|
+
return matchPathRule(String(toolInput.file_path || ''), subPattern!, segmentMode)
|
|
1053
|
+
}
|
|
1054
|
+
|
|
980
1055
|
if (toolName !== baseTool!) return false
|
|
981
1056
|
|
|
982
1057
|
// For Bash: match against the command string (any segment of a compound
|
|
@@ -984,7 +1059,32 @@ export function matchBashRule(
|
|
|
984
1059
|
// `$(...)`/backtick substitution, so `Bash(rm *)` catches `x=$(rm -rf ~)`).
|
|
985
1060
|
if (baseTool === 'Bash') {
|
|
986
1061
|
const cmd = String(toolInput.command || '')
|
|
987
|
-
|
|
1062
|
+
// An allow rule whose first word ends in an attached wildcard (`ls*`) is a
|
|
1063
|
+
// grant bounded by that word — but `^ls.*$` also matched `lsof -i -P`, so
|
|
1064
|
+
// the rule handed over every command that merely starts with the same
|
|
1065
|
+
// letters. Under deny/ask the wide reading stays: there, matching more is
|
|
1066
|
+
// the safe direction.
|
|
1067
|
+
const anchored = segmentMode === 'all' ? /^([\w./-]+)\*/.exec(subPattern!) : null
|
|
1068
|
+
const firstWord = anchored?.[1]
|
|
1069
|
+
return qualifies(flattenCommand(cmd), (seg) => {
|
|
1070
|
+
if (firstWord) {
|
|
1071
|
+
// The wildcard has to start at a word boundary in the command: `ls`
|
|
1072
|
+
// exactly, or `ls` followed by whitespace/`:` — not the `ls` inside
|
|
1073
|
+
// `lsof`.
|
|
1074
|
+
const boundary = new RegExp(
|
|
1075
|
+
'^' + firstWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?:$|[:\\s])',
|
|
1076
|
+
)
|
|
1077
|
+
if (!boundary.test(seg)) return false
|
|
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
|
|
1086
|
+
return wildcardMatch(subPattern!, seg)
|
|
1087
|
+
})
|
|
988
1088
|
}
|
|
989
1089
|
|
|
990
1090
|
// For Write/Edit/Read: match against the file_path with path-glob semantics.
|
|
@@ -1005,6 +1105,34 @@ export function matchBashRule(
|
|
|
1005
1105
|
return false
|
|
1006
1106
|
}
|
|
1007
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
|
+
|
|
1008
1136
|
export function wildcardMatch(pattern: string, input: string): boolean {
|
|
1009
1137
|
const regexStr =
|
|
1010
1138
|
'^' +
|
|
@@ -1104,6 +1232,27 @@ export function mcpServerPrefix(pattern: string): string | null {
|
|
|
1104
1232
|
return `mcp__${server.toLowerCase()}__`
|
|
1105
1233
|
}
|
|
1106
1234
|
|
|
1235
|
+
/**
|
|
1236
|
+
* A Bash **allow** rule that puts a `*` inside a variable's *value*
|
|
1237
|
+
* (`Bash(PORT=* npm run dev)`) is a grant nobody means: the `*` is a wildcard
|
|
1238
|
+
* over the whole assignment, so the rule matches **every** value. Returns the
|
|
1239
|
+
* warning text, or `undefined`.
|
|
1240
|
+
*
|
|
1241
|
+
* Deny/ask rules are deliberately not warned — there, a wider match is the safe
|
|
1242
|
+
* direction. This is a warning and not a rejection: the pattern is structurally
|
|
1243
|
+
* valid and the author may genuinely want the wildcard.
|
|
1244
|
+
*/
|
|
1245
|
+
export function variableWildcardWarning(pattern: string): string | undefined {
|
|
1246
|
+
const shape = pattern.match(/^Bash\((.+)\)$/)
|
|
1247
|
+
if (!shape) return undefined
|
|
1248
|
+
const hit = /(?:^|\s)([A-Za-z_][A-Za-z0-9_]*)=[^\s]*\*/.exec(shape[1]!)
|
|
1249
|
+
if (!hit) return undefined
|
|
1250
|
+
return (
|
|
1251
|
+
`allow rule "${pattern}" puts a * in the value of ${hit[1]}: ` +
|
|
1252
|
+
`it matches every value, not one — write the concrete value if that is what you mean`
|
|
1253
|
+
)
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1107
1256
|
/**
|
|
1108
1257
|
* Compile a rule pattern string into a PermissionRuleEntry.
|
|
1109
1258
|
*/
|
package/src/core/permission.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type {
|
|
|
6
6
|
PermissionRestrictions,
|
|
7
7
|
} from '../shared/index.ts'
|
|
8
8
|
import type { PermissionRuleEntry } from '../shared/index.ts'
|
|
9
|
-
import { matchBashRule, compileRule } from './permission-rules'
|
|
9
|
+
import { matchBashRule, compileRule, variableWildcardWarning } from './permission-rules'
|
|
10
10
|
import { detectDangerousRm } from '../security/dangerous-rm'
|
|
11
11
|
import type { DangerousRm } from '../security/dangerous-rm'
|
|
12
12
|
import { detectWorldWritableChmod } from '../security/world-writable-chmod'
|
|
@@ -1118,6 +1118,19 @@ export class PermissionSystem {
|
|
|
1118
1118
|
this.invalidateCache()
|
|
1119
1119
|
}
|
|
1120
1120
|
|
|
1121
|
+
/**
|
|
1122
|
+
* Allow rules that load but cannot mean what they say — currently only a `*`
|
|
1123
|
+
* in a variable's *value* (`Bash(PORT=* npm run dev)`), which grants every
|
|
1124
|
+
* value instead of the one written. Derived on read rather than stored: the
|
|
1125
|
+
* rule arrays are replaced wholesale by `loadConfig`, and a stored copy would
|
|
1126
|
+
* go stale there. Callers print these at start-up, like `getInvalidRules()`.
|
|
1127
|
+
*/
|
|
1128
|
+
getRuleWarnings(): string[] {
|
|
1129
|
+
return this.allowRules
|
|
1130
|
+
.map((entry) => variableWildcardWarning(entry.pattern))
|
|
1131
|
+
.filter((w): w is string => Boolean(w))
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1121
1134
|
/**
|
|
1122
1135
|
* Report any rule whose pattern is structurally invalid and can therefore
|
|
1123
1136
|
* never match (e.g. `Bash(ls) x`, `Read(foo`, `Bash()`). These are silently
|
package/src/core/session-log.ts
CHANGED
|
@@ -255,8 +255,19 @@ export class SessionLog {
|
|
|
255
255
|
|
|
256
256
|
constructor(private name: string) {}
|
|
257
257
|
|
|
258
|
+
/**
|
|
259
|
+
* Append one event — in memory *and* on disk.
|
|
260
|
+
*
|
|
261
|
+
* Persisting here rather than only at exit is the difference between "the
|
|
262
|
+
* last turn survived" and "it survived if the process happened to shut down
|
|
263
|
+
* cleanly". `save()` writes only the events added since the last call, so
|
|
264
|
+
* this is one line per event; the alternative — a save at exit — never runs
|
|
265
|
+
* under SIGKILL, a crash, or a closed terminal, and the resumed session then
|
|
266
|
+
* ends one or more turns early.
|
|
267
|
+
*/
|
|
258
268
|
append(event: SessionEvent): void {
|
|
259
269
|
this.buf.push(event)
|
|
270
|
+
this.save()
|
|
260
271
|
}
|
|
261
272
|
|
|
262
273
|
/** 不可变快照(浅拷贝,事件本身视为不可变)。 */
|
|
@@ -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
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFileSync, existsSync, mkdirSync } from 'node:fs'
|
|
1
|
+
import { readFileSync, existsSync, mkdirSync, realpathSync } from 'node:fs'
|
|
2
2
|
import { join, dirname, resolve } from 'node:path'
|
|
3
3
|
import { atomicWriteFileSync } from '../shared/atomic-write'
|
|
4
4
|
import { miphamHome } from './paths.ts'
|
|
@@ -16,17 +16,39 @@ export interface TrustedWorkspaces {
|
|
|
16
16
|
/**
|
|
17
17
|
* Resolves a directory to its real absolute path, following symlinks.
|
|
18
18
|
* Falls back to the resolved path if realpath fails.
|
|
19
|
+
*
|
|
20
|
+
* This used to be `resolve()` under a comment claiming it followed symlinks —
|
|
21
|
+
* so trust was checked against the **lexical** spelling while the settings and
|
|
22
|
+
* hooks it gates are read through the **canonical** one. A workspace reached
|
|
23
|
+
* through a symlink (`~/work -> /Volumes/proj`, or macOS's `/tmp -> /private/tmp`)
|
|
24
|
+
* was therefore trusted under one path and read under another.
|
|
25
|
+
*
|
|
26
|
+
* A directory that does not exist yet has no realpath; `resolve` keeps
|
|
27
|
+
* `trust()` usable before the folder is created.
|
|
19
28
|
*/
|
|
20
29
|
function realPath(dir: string): string {
|
|
21
30
|
try {
|
|
22
|
-
|
|
23
|
-
const resolved = resolve(dir)
|
|
24
|
-
return resolved
|
|
31
|
+
return realpathSync.native(dir)
|
|
25
32
|
} catch {
|
|
26
33
|
return resolve(dir)
|
|
27
34
|
}
|
|
28
35
|
}
|
|
29
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Both spellings of a directory: what the caller typed (normalised) and what
|
|
39
|
+
* the filesystem calls it.
|
|
40
|
+
*
|
|
41
|
+
* Trust entries written before canonicalisation, and paths passed through a
|
|
42
|
+
* symlink, each match only one of the two. Checking both keeps an existing
|
|
43
|
+
* store valid and cannot widen what is trusted — every candidate must itself
|
|
44
|
+
* be inside a trusted directory.
|
|
45
|
+
*/
|
|
46
|
+
function spellings(dir: string): string[] {
|
|
47
|
+
const literal = resolve(dir)
|
|
48
|
+
const real = realPath(dir)
|
|
49
|
+
return literal === real ? [literal] : [literal, real]
|
|
50
|
+
}
|
|
51
|
+
|
|
30
52
|
/**
|
|
31
53
|
* True if a `.git` file or directory exists anywhere strictly between `dir` and
|
|
32
54
|
* its trusted ancestor `ancestor`. A `.git` marks the root of a separate
|
|
@@ -121,17 +143,24 @@ export class WorkspaceTrust {
|
|
|
121
143
|
* A directory is trusted if it or any ancestor is in the trust list.
|
|
122
144
|
*/
|
|
123
145
|
isTrusted(dir: string): boolean {
|
|
124
|
-
const
|
|
125
|
-
const resolvedLower = resolved.toLowerCase()
|
|
146
|
+
const candidates = spellings(dir)
|
|
126
147
|
|
|
127
148
|
for (const trusted of this.store.directories) {
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
149
|
+
for (const trustedPath of spellings(trusted)) {
|
|
150
|
+
const trustedLower = trustedPath.toLowerCase()
|
|
151
|
+
for (const candidate of candidates) {
|
|
152
|
+
const candidateLower = candidate.toLowerCase()
|
|
153
|
+
// Exact match
|
|
154
|
+
if (candidateLower === trustedLower) return true
|
|
155
|
+
// Ancestor match: trusted dir is a parent of the target. Trust does not
|
|
156
|
+
// cross a nested git-repository boundary (vendored/submodule isolation).
|
|
157
|
+
if (
|
|
158
|
+
candidateLower.startsWith(trustedLower + '/') &&
|
|
159
|
+
!hasGitBoundary(candidate, trustedPath)
|
|
160
|
+
) {
|
|
161
|
+
return true
|
|
162
|
+
}
|
|
163
|
+
}
|
|
135
164
|
}
|
|
136
165
|
}
|
|
137
166
|
|
|
@@ -141,6 +170,10 @@ export class WorkspaceTrust {
|
|
|
141
170
|
/**
|
|
142
171
|
* Add a directory to the trust store.
|
|
143
172
|
*
|
|
173
|
+
* The canonical path is what gets stored: the settings and hooks trust gates
|
|
174
|
+
* are read through the realpath, so recording a symlink's lexical spelling
|
|
175
|
+
* made the two disagree. `isTrusted` still matches older lexical entries.
|
|
176
|
+
*
|
|
144
177
|
* Returns false only when the new entry could not be written to disk; a
|
|
145
178
|
* directory that is already trusted is `true` — it was persisted earlier.
|
|
146
179
|
*/
|
|
@@ -159,13 +192,13 @@ export class WorkspaceTrust {
|
|
|
159
192
|
|
|
160
193
|
/** Remove a directory from the trust store (and any subdirectories). */
|
|
161
194
|
untrust(dir: string): void {
|
|
162
|
-
const
|
|
163
|
-
const resolvedLower = resolved.toLowerCase()
|
|
195
|
+
const targets = spellings(dir).map((p) => p.toLowerCase())
|
|
164
196
|
|
|
165
197
|
this.store.directories = this.store.directories.filter((d) => {
|
|
166
198
|
const lower = d.toLowerCase()
|
|
167
|
-
// Remove exact match and all subdirectories
|
|
168
|
-
|
|
199
|
+
// Remove exact match and all subdirectories, in whichever spelling the
|
|
200
|
+
// entry was recorded.
|
|
201
|
+
return !targets.some((target) => lower === target || lower.startsWith(target + '/'))
|
|
169
202
|
})
|
|
170
203
|
this.save()
|
|
171
204
|
}
|
|
@@ -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
|