@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
|
@@ -71,6 +71,37 @@ export const DEFAULT_CONSTITUTION: MiphamConstitution = {
|
|
|
71
71
|
|
|
72
72
|
// ── Loader ──
|
|
73
73
|
|
|
74
|
+
/** `"Write,Edit,Bash"` → `["Write","Edit","Bash"]`; surrounding spaces dropped. */
|
|
75
|
+
function splitScope(scope: string): string[] {
|
|
76
|
+
return scope
|
|
77
|
+
.split(',')
|
|
78
|
+
.map((part) => part.trim())
|
|
79
|
+
.filter(Boolean)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 写侧:一律用 JSON 字符串。JSON 的双引号标量是合法 YAML,`"` 与 `\` 都被转义 ——
|
|
84
|
+
* 从前 `audit_pattern` 是原样塞进双引号里的,而它自己含 `['"]` 与 `\s`:标量提前闭合,
|
|
85
|
+
* 整份文件不是合法 YAML(自家那枚逐行解析器读得回,任何 YAML 工具读不了)。
|
|
86
|
+
*/
|
|
87
|
+
function quoteYaml(value: string): string {
|
|
88
|
+
return JSON.stringify(value)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 读侧:双引号值按 JSON 解(写侧就是 JSON.stringify),单引号去壳,其余原样。 */
|
|
92
|
+
function parseScalar(raw: string): string {
|
|
93
|
+
const value = raw.trim()
|
|
94
|
+
if (value.startsWith('"')) {
|
|
95
|
+
try {
|
|
96
|
+
const decoded: unknown = JSON.parse(value)
|
|
97
|
+
if (typeof decoded === 'string') return decoded
|
|
98
|
+
} catch {
|
|
99
|
+
// 手写的引号坏掉了 —— 退回去壳,与从前一致
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return value.replace(/^['"]|['"]$/g, '')
|
|
103
|
+
}
|
|
104
|
+
|
|
74
105
|
export class ConstitutionLoader {
|
|
75
106
|
private path: string
|
|
76
107
|
private cached: MiphamConstitution | null = null
|
|
@@ -81,26 +112,41 @@ export class ConstitutionLoader {
|
|
|
81
112
|
|
|
82
113
|
/**
|
|
83
114
|
* Load the constitution from disk.
|
|
84
|
-
* Falls back to the built-in DEFAULT_CONSTITUTION
|
|
115
|
+
* Falls back to the built-in DEFAULT_CONSTITUTION when the file is missing
|
|
116
|
+
* (and writes it out) or when an existing file cannot be read or validated
|
|
117
|
+
* (and leaves it untouched).
|
|
85
118
|
*/
|
|
86
119
|
load(): MiphamConstitution {
|
|
87
120
|
if (this.cached) return this.cached
|
|
88
121
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
122
|
+
// 文件在、但读不通或不合 schema:本次会话用内置默认原则,**但不动那个文件**。
|
|
123
|
+
// 覆盖它等于把用户手改的内容静默丢掉,而这个文件头正写着「改这里即可自定义」。
|
|
124
|
+
const fileExists = existsSync(this.path)
|
|
125
|
+
if (fileExists) {
|
|
126
|
+
try {
|
|
127
|
+
const parsed = this.parseYaml(readFileSync(this.path, 'utf-8'))
|
|
93
128
|
if (this.validate(parsed)) {
|
|
94
129
|
this.cached = parsed
|
|
95
130
|
return parsed
|
|
96
131
|
}
|
|
132
|
+
process.stderr.write(
|
|
133
|
+
`⚠ Mipham Code: ${this.path} does not match the guardrails schema ` +
|
|
134
|
+
'(every principle needs id, text and enforce) — using the built-in defaults this session\n' +
|
|
135
|
+
' (the file was left as-is: fix it, or delete it to have it regenerated)\n',
|
|
136
|
+
)
|
|
137
|
+
} catch (err) {
|
|
138
|
+
const reason = err instanceof Error ? err.message : String(err)
|
|
139
|
+
process.stderr.write(
|
|
140
|
+
`⚠ Mipham Code: could not read ${this.path} (${reason}) — ` +
|
|
141
|
+
'using the built-in defaults this session\n',
|
|
142
|
+
)
|
|
97
143
|
}
|
|
98
|
-
} catch {
|
|
99
|
-
// Fall through to default
|
|
100
144
|
}
|
|
101
145
|
|
|
102
|
-
// Write the default constitution to disk for visibility
|
|
103
146
|
this.cached = DEFAULT_CONSTITUTION
|
|
147
|
+
if (fileExists) return this.cached
|
|
148
|
+
|
|
149
|
+
// Only a missing file gets the default written out.
|
|
104
150
|
try {
|
|
105
151
|
const dir = miphamHome()
|
|
106
152
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
@@ -123,6 +169,12 @@ export class ConstitutionLoader {
|
|
|
123
169
|
return constitution.principles.filter((p) => {
|
|
124
170
|
if (p.scope === 'all-tools') return true
|
|
125
171
|
if (p.tools && p.tools.includes(toolName)) return true
|
|
172
|
+
// `scope` is also used as a comma-separated tool list — the vocabulary
|
|
173
|
+
// spells `no-credential-leak` as `"Write,Edit,Bash"` and gives it no
|
|
174
|
+
// `tools` array. Reading only `tools` made exactly that entry inert: a
|
|
175
|
+
// rule whose whole purpose is to block a leaked key never ran for any
|
|
176
|
+
// tool, while its neighbours (which declare both keys) ran fine.
|
|
177
|
+
if (p.scope && splitScope(p.scope).includes(toolName)) return true
|
|
126
178
|
return false
|
|
127
179
|
})
|
|
128
180
|
}
|
|
@@ -172,14 +224,20 @@ export class ConstitutionLoader {
|
|
|
172
224
|
const trimmed = line.trim()
|
|
173
225
|
if (!trimmed || trimmed.startsWith('#')) continue
|
|
174
226
|
|
|
175
|
-
//
|
|
176
|
-
|
|
227
|
+
// 缩进只能从**原始行**读:`trimmed` 已经把缩进剥掉了,任何
|
|
228
|
+
// `trimmed.startsWith(' ')` 都是恒假 —— 从前就是这样,每个缩进字段
|
|
229
|
+
// 都掉进「顶层键」分支被丢掉,parse 出来的 principle 只剩 id。
|
|
230
|
+
const indented = line.startsWith(' ') || line.startsWith('\t')
|
|
231
|
+
|
|
232
|
+
// Top-level keys (no indentation, not a list item)
|
|
233
|
+
if (!indented && !trimmed.startsWith('-')) {
|
|
177
234
|
const kv = trimmed.match(/^(\w[\w_]*):\s*(.*)$/)
|
|
178
235
|
if (kv) {
|
|
179
236
|
const key = kv[1]!
|
|
180
|
-
const val = kv[2]
|
|
237
|
+
const val = parseScalar(kv[2]!)
|
|
181
238
|
if (key === 'version') result.version = val
|
|
182
239
|
else if (key === 'last_modified') result.last_modified = val
|
|
240
|
+
else if (key === 'preamble') result.preamble = val
|
|
183
241
|
if (key === 'principles') inPrinciples = true
|
|
184
242
|
}
|
|
185
243
|
continue
|
|
@@ -199,18 +257,18 @@ export class ConstitutionLoader {
|
|
|
199
257
|
const kv = trimmed.substring(2).match(/^(\w[\w_]*):\s*(.*)$/)
|
|
200
258
|
if (kv) {
|
|
201
259
|
const key = kv[1]!
|
|
202
|
-
const val = kv[2]
|
|
260
|
+
const val = parseScalar(kv[2]!)
|
|
203
261
|
this.setPrincipleField(currentPrinciple, key, val)
|
|
204
262
|
}
|
|
205
263
|
continue
|
|
206
264
|
}
|
|
207
265
|
|
|
208
266
|
// Indented fields of current principle
|
|
209
|
-
if (inPrinciples &&
|
|
210
|
-
const kv = trimmed.match(
|
|
267
|
+
if (inPrinciples && indented && currentPrinciple) {
|
|
268
|
+
const kv = trimmed.match(/^(\w[\w_]*):\s*(.*)$/)
|
|
211
269
|
if (kv) {
|
|
212
270
|
const key = kv[1]!
|
|
213
|
-
const val = kv[2]
|
|
271
|
+
const val = parseScalar(kv[2]!)
|
|
214
272
|
this.setPrincipleField(currentPrinciple, key, val)
|
|
215
273
|
}
|
|
216
274
|
}
|
|
@@ -279,20 +337,23 @@ export class ConstitutionLoader {
|
|
|
279
337
|
'# Edit this file to customize principles. Delete it to restore defaults.',
|
|
280
338
|
'# Changes take effect after /constitution reload or session restart.',
|
|
281
339
|
'',
|
|
282
|
-
`version:
|
|
283
|
-
`last_modified:
|
|
340
|
+
`version: ${quoteYaml(constitution.version)}`,
|
|
341
|
+
`last_modified: ${quoteYaml(constitution.last_modified)}`,
|
|
342
|
+
// 序言从前只活在内存里的 DEFAULT_CONSTITUTION 上 —— 落到盘上的文件没有它,
|
|
343
|
+
// 于是「读回来的那份」和「内置那份」不是同一份宪法。
|
|
344
|
+
...(constitution.preamble ? [`preamble: ${quoteYaml(constitution.preamble)}`] : []),
|
|
284
345
|
'',
|
|
285
346
|
'principles:',
|
|
286
347
|
]
|
|
287
348
|
|
|
288
349
|
for (const p of constitution.principles) {
|
|
289
|
-
lines.push(` - id:
|
|
290
|
-
lines.push(` text:
|
|
291
|
-
lines.push(` enforce: ${p.enforce}`)
|
|
292
|
-
if (p.facet) lines.push(` facet: ${p.facet}`)
|
|
293
|
-
if (p.audit_pattern) lines.push(` audit_pattern:
|
|
294
|
-
if (p.scope) lines.push(` scope:
|
|
295
|
-
if (p.hook) lines.push(` hook: ${p.hook}`)
|
|
350
|
+
lines.push(` - id: ${quoteYaml(p.id)}`)
|
|
351
|
+
lines.push(` text: ${quoteYaml(p.text)}`)
|
|
352
|
+
lines.push(` enforce: ${quoteYaml(p.enforce)}`)
|
|
353
|
+
if (p.facet) lines.push(` facet: ${quoteYaml(p.facet)}`)
|
|
354
|
+
if (p.audit_pattern) lines.push(` audit_pattern: ${quoteYaml(p.audit_pattern)}`)
|
|
355
|
+
if (p.scope) lines.push(` scope: ${quoteYaml(p.scope)}`)
|
|
356
|
+
if (p.hook) lines.push(` hook: ${quoteYaml(p.hook)}`)
|
|
296
357
|
if (p.tools) lines.push(` tools: [${p.tools.join(', ')}]`)
|
|
297
358
|
if (p.rationale) lines.push(` rationale: "${p.rationale}"`)
|
|
298
359
|
}
|
|
@@ -5,6 +5,43 @@ import type { CredentialMaskingConfig } from '../../shared/index.ts'
|
|
|
5
5
|
* Filter sensitive environment variables before spawning a subprocess.
|
|
6
6
|
* Returns a sanitized copy of process.env with matching vars removed.
|
|
7
7
|
*/
|
|
8
|
+
/** Which variable names the config calls sensitive (same patterns `filterEnv`
|
|
9
|
+
* uses — one definition of "sensitive", two dispositions). */
|
|
10
|
+
export function isSensitiveEnvKey(key: string, config: CredentialMaskingConfig): boolean {
|
|
11
|
+
for (const pattern of config.env_filter.patterns) {
|
|
12
|
+
try {
|
|
13
|
+
// Strip (?i) inline flags — JS uses the 'i' flag instead
|
|
14
|
+
const clean = pattern.replace(/^\(\?i\)/, '')
|
|
15
|
+
if (new RegExp(clean, 'i').test(key)) return true
|
|
16
|
+
} catch {
|
|
17
|
+
// Invalid regex — skip
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return false
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Remove sensitive variables outright — for processes *this program* starts on
|
|
25
|
+
* its own behalf (git, ripgrep).
|
|
26
|
+
*
|
|
27
|
+
* `filterEnv` keeps the name and swaps in a sentinel so the model's shell can
|
|
28
|
+
* tell a value was withheld. That is the wrong shape here: these children never
|
|
29
|
+
* act on the user's behalf, so a credential helper or hook under them should
|
|
30
|
+
* find nothing at all, not a well-formed string that merely isn't the secret.
|
|
31
|
+
*/
|
|
32
|
+
export function stripEnv(
|
|
33
|
+
env: Record<string, string | undefined>,
|
|
34
|
+
config: CredentialMaskingConfig,
|
|
35
|
+
): Record<string, string | undefined> {
|
|
36
|
+
if (!config.enabled || !config.env_filter.enabled) return { ...env }
|
|
37
|
+
|
|
38
|
+
const stripped: Record<string, string | undefined> = {}
|
|
39
|
+
for (const [key, value] of Object.entries(env)) {
|
|
40
|
+
if (!isSensitiveEnvKey(key, config)) stripped[key] = value
|
|
41
|
+
}
|
|
42
|
+
return stripped
|
|
43
|
+
}
|
|
44
|
+
|
|
8
45
|
export function filterEnv(
|
|
9
46
|
env: Record<string, string | undefined>,
|
|
10
47
|
config: CredentialMaskingConfig,
|
package/src/core/engine.ts
CHANGED
|
@@ -47,6 +47,8 @@ import { SelfCritique } from './self-critique.js'
|
|
|
47
47
|
import { UsageTracker } from './usage-tracker'
|
|
48
48
|
import { getMetrics } from './metrics'
|
|
49
49
|
import { buildRequest, sendInferenceCheck, isInferenceHookEnabled } from './inference-hook'
|
|
50
|
+
import { runPreToolGate, type ToolGateDeps } from './tool-gate'
|
|
51
|
+
import type { SubAgentServices } from '../agent/services'
|
|
50
52
|
import { getFileInboxTransport } from '../agent/cross-session/file-inbox'
|
|
51
53
|
import { registerWakeupHandler, unregisterWakeupHandler } from '../tools/scheduling/schedule-wakeup'
|
|
52
54
|
import { accumulateGraftSavings } from '../shared/graft-savings'
|
|
@@ -124,6 +126,17 @@ export function filterExpiredMessages(
|
|
|
124
126
|
}
|
|
125
127
|
|
|
126
128
|
export class QueryEngine {
|
|
129
|
+
/**
|
|
130
|
+
* `false` for the local engine; `true` for the attach-mode `RemoteEngine`.
|
|
131
|
+
*
|
|
132
|
+
* Commands that would otherwise *pretend* to change something the daemon owns
|
|
133
|
+
* (`/switch`, the model picker) read this: in attach mode `switchProvider` is a
|
|
134
|
+
* no-op, so the old code reported "✓ Switched" and moved the footer while the
|
|
135
|
+
* daemon kept running the previous model — a change that never happened looking
|
|
136
|
+
* exactly like one that did.
|
|
137
|
+
*/
|
|
138
|
+
readonly isRemote = false
|
|
139
|
+
|
|
127
140
|
private hookEngine?: HookEngine
|
|
128
141
|
private artifactServer?: ArtifactServer
|
|
129
142
|
private agentRegistry?: AgentRegistry
|
|
@@ -1452,150 +1465,22 @@ export class QueryEngine {
|
|
|
1452
1465
|
// P1-4: Tool allowed — reset block counter
|
|
1453
1466
|
this.permission.resetBlockCounter()
|
|
1454
1467
|
|
|
1455
|
-
// Run
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
success: false,
|
|
1463
|
-
content: '',
|
|
1464
|
-
error: preResult.reason || t('errors.tool_blocked', { name }),
|
|
1465
|
-
notRun: true,
|
|
1466
|
-
}
|
|
1467
|
-
}
|
|
1468
|
-
|
|
1469
|
-
// `permissionDecision` narrows only — never widens. `ask` stops the call here
|
|
1470
|
-
// (this CLI has no interactive approval prompt; `ask` is a hard refusal, the
|
|
1471
|
-
// same as the `default` mode's ask path). `allow` is deliberately **not**
|
|
1472
|
-
// honoured: a hook can come from the repository's own settings, so letting it
|
|
1473
|
-
// auto-approve is the same defect as a project-supplied agent definition that
|
|
1474
|
-
// grants itself `bypassPermissions` — the criterion is the *direction*, not the
|
|
1475
|
-
// key name. `defer` (and an absent decision) means "no override", which is
|
|
1476
|
-
// exactly what happens when we do nothing.
|
|
1477
|
-
if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
|
|
1478
|
-
return {
|
|
1479
|
-
success: false,
|
|
1480
|
-
content: '',
|
|
1481
|
-
error: preResult.reason || t('errors.tool_hook_ask', { name }),
|
|
1482
|
-
notRun: true,
|
|
1483
|
-
}
|
|
1484
|
-
}
|
|
1485
|
-
|
|
1486
|
-
if (preResult.modifiedInput) {
|
|
1487
|
-
effectiveParams = { ...params, ...preResult.modifiedInput }
|
|
1488
|
-
}
|
|
1489
|
-
|
|
1490
|
-
// A hook's `additionalContext` is how every non-blocking hook speaks — the
|
|
1491
|
-
// exit-1 stderr, a spawn failure, an unreachable `mcp_tool` server (see
|
|
1492
|
-
// `core/hooks-executor.ts`). This path used to read only `allowed` /
|
|
1493
|
-
// `modifiedInput`, so all of it was produced and then dropped. `hookWarnings`
|
|
1494
|
-
// is the channel that already reaches the model: it is prepended to the tool
|
|
1495
|
-
// result below. A non-`[rule:…]` line is ignored by the effectiveness tracker
|
|
1496
|
-
// further down, so pushing prose here is safe.
|
|
1497
|
-
if (preResult.additionalContext) {
|
|
1498
|
-
hookWarnings.push(preResult.additionalContext)
|
|
1499
|
-
}
|
|
1500
|
-
}
|
|
1501
|
-
|
|
1502
|
-
// CRSI RuleEngine intercept — gated by crsi.preToolHook feature flag
|
|
1503
|
-
if (this.crsiConfig?.preToolHook !== false && this.ruleEngine) {
|
|
1504
|
-
const ruleResult = this.ruleEngine.intercept(name, effectiveParams)
|
|
1505
|
-
if (Object.keys(ruleResult.modified).length > 0) {
|
|
1506
|
-
getMetrics().crsiRuleApplications.inc()
|
|
1507
|
-
effectiveParams = ruleResult.modified
|
|
1508
|
-
}
|
|
1509
|
-
if (ruleResult.warnings.length > 0) {
|
|
1510
|
-
// Append, do not replace: this array may already hold a PreToolUse hook's
|
|
1511
|
-
// `additionalContext`. Every other writer below uses the spread form for the
|
|
1512
|
-
// same reason — assignment here would silently drop whichever was written
|
|
1513
|
-
// first ("two writers, one list").
|
|
1514
|
-
hookWarnings = [...hookWarnings, ...ruleResult.warnings]
|
|
1515
|
-
}
|
|
1516
|
-
}
|
|
1517
|
-
|
|
1518
|
-
// ── SIS PreFlightChecker — known error pattern interception ──
|
|
1519
|
-
const preflight = this.getPreFlightChecker().check(name, effectiveParams)
|
|
1520
|
-
if (preflight.action === 'block') {
|
|
1521
|
-
getMetrics().sisInterceptions.inc()
|
|
1468
|
+
// Run every pre-execution gate. The chain is defined once, in
|
|
1469
|
+
// `core/tool-gate.ts`, because it used to live only in this loop: a `Write`
|
|
1470
|
+
// carrying an `apiKey = "sk-…"` was blocked here and executed verbatim by
|
|
1471
|
+
// `SubAgent`, which runs its own tool loop (`sub-agent.ts`). Two copies of a
|
|
1472
|
+
// gate drift; one definition called from both loops cannot.
|
|
1473
|
+
const gateOutcome = await runPreToolGate(name, params, this.getToolGateDeps(), this.sessionId)
|
|
1474
|
+
if (!gateOutcome.ok) {
|
|
1522
1475
|
return {
|
|
1523
1476
|
success: false,
|
|
1524
|
-
content:
|
|
1525
|
-
error:
|
|
1526
|
-
|
|
1527
|
-
}
|
|
1528
|
-
if (preflight.action === 'fix' && preflight.modifiedParams) {
|
|
1529
|
-
getMetrics().sisInterceptions.inc()
|
|
1530
|
-
effectiveParams = preflight.modifiedParams
|
|
1531
|
-
if (preflight.warning) {
|
|
1532
|
-
hookWarnings = [...hookWarnings, preflight.warning]
|
|
1533
|
-
}
|
|
1534
|
-
}
|
|
1535
|
-
if (preflight.action === 'warn' && preflight.warning) {
|
|
1536
|
-
hookWarnings = [...hookWarnings, preflight.warning]
|
|
1537
|
-
}
|
|
1538
|
-
|
|
1539
|
-
// ── Mipham Constitution — constitutional principle enforcement ──
|
|
1540
|
-
// Checks the tool + params against the machine-readable constitution.
|
|
1541
|
-
// Block-level violations (enforce: block) halt execution immediately.
|
|
1542
|
-
// Warn-level violations (enforce: warn) are appended to hookWarnings.
|
|
1543
|
-
const constitution = this.getConstitutionLoader()
|
|
1544
|
-
const principles = constitution.getPrinciplesForTool(name)
|
|
1545
|
-
for (const principle of principles) {
|
|
1546
|
-
if (principle.enforce === 'block') {
|
|
1547
|
-
// Audit: check if the tool params or command match a violation pattern
|
|
1548
|
-
if (principle.audit_pattern) {
|
|
1549
|
-
try {
|
|
1550
|
-
const regex = new RegExp(principle.audit_pattern, 'i')
|
|
1551
|
-
const paramsStr = JSON.stringify(effectiveParams)
|
|
1552
|
-
if (regex.test(paramsStr)) {
|
|
1553
|
-
return {
|
|
1554
|
-
success: false,
|
|
1555
|
-
content: `🚫 Constitution violation blocked: **${principle.id}** — ${principle.text}`,
|
|
1556
|
-
error: `Constitutional principle "${principle.id}" blocked this operation.`,
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
} catch {
|
|
1560
|
-
// Invalid regex — skip this principle
|
|
1561
|
-
}
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
|
-
if (principle.enforce === 'warn') {
|
|
1565
|
-
hookWarnings = [...hookWarnings, `⚖️ Constitution: ${principle.id} — ${principle.text}`]
|
|
1566
|
-
}
|
|
1567
|
-
}
|
|
1568
|
-
|
|
1569
|
-
// ── Self-Critique Hook — RLAIF-style tool-call safety verification ──
|
|
1570
|
-
// Uses a fast model (Flash) to critique the tool call before execution.
|
|
1571
|
-
// Safe + correct + necessary check with <200ms target latency.
|
|
1572
|
-
// Fail-open: if the critique times out or errors, the tool still executes.
|
|
1573
|
-
const selfCritique = this.getSelfCritique()
|
|
1574
|
-
if (selfCritique.getConfig().enabled) {
|
|
1575
|
-
const critiqueResult = await selfCritique.critique(
|
|
1576
|
-
name,
|
|
1577
|
-
effectiveParams,
|
|
1578
|
-
this.registry,
|
|
1579
|
-
this.llm,
|
|
1580
|
-
)
|
|
1581
|
-
if (critiqueResult) {
|
|
1582
|
-
if (critiqueResult.score < selfCritique.getConfig().threshold) {
|
|
1583
|
-
// Score too low — block with explanation
|
|
1584
|
-
if (!critiqueResult.safe) {
|
|
1585
|
-
return {
|
|
1586
|
-
success: false,
|
|
1587
|
-
content: `🔍 Self-Critique blocked: ${critiqueResult.reasoning}`,
|
|
1588
|
-
error: `Self-Critique safety check failed (score: ${(critiqueResult.score * 100).toFixed(0)}%). ${critiqueResult.correction || ''}`,
|
|
1589
|
-
}
|
|
1590
|
-
}
|
|
1591
|
-
// Score low but safe — warn but allow
|
|
1592
|
-
hookWarnings = [
|
|
1593
|
-
...hookWarnings,
|
|
1594
|
-
`🔍 Self-Critique: ${critiqueResult.reasoning}${critiqueResult.correction ? ` — Suggestion: ${critiqueResult.correction}` : ''}`,
|
|
1595
|
-
]
|
|
1596
|
-
}
|
|
1477
|
+
content: gateOutcome.content,
|
|
1478
|
+
error: gateOutcome.error,
|
|
1479
|
+
...(gateOutcome.notRun ? { notRun: true } : {}),
|
|
1597
1480
|
}
|
|
1598
1481
|
}
|
|
1482
|
+
const effectiveParams = gateOutcome.params
|
|
1483
|
+
const hookWarnings = gateOutcome.warnings
|
|
1599
1484
|
|
|
1600
1485
|
// The gate at the top of this method ruled on `params`. Everything since —
|
|
1601
1486
|
// the PreToolUse hook's `modifiedInput`, the CRSI RuleEngine's `modified`, the
|
|
@@ -1650,6 +1535,7 @@ export class QueryEngine {
|
|
|
1650
1535
|
backgroundAgentRegistry: getBackgroundAgentRegistry(),
|
|
1651
1536
|
permissionSystem: this.permission,
|
|
1652
1537
|
ruleEngine: this.ruleEngine,
|
|
1538
|
+
subAgentServices: this.getSubAgentServices(),
|
|
1653
1539
|
llm: this.llm,
|
|
1654
1540
|
readFiles: this.readFiles,
|
|
1655
1541
|
readFilesComplete: this.readFilesComplete,
|
|
@@ -2141,6 +2027,39 @@ export class QueryEngine {
|
|
|
2141
2027
|
return this._errorSignatureDB
|
|
2142
2028
|
}
|
|
2143
2029
|
|
|
2030
|
+
/**
|
|
2031
|
+
* The pre-execution chain's dependencies, as a value.
|
|
2032
|
+
*
|
|
2033
|
+
* Built on every tool call rather than cached: `hookEngine` is assigned after
|
|
2034
|
+
* construction (`setHooks`), and the three lazy singletons must stay lazy.
|
|
2035
|
+
*/
|
|
2036
|
+
getToolGateDeps(): ToolGateDeps {
|
|
2037
|
+
return {
|
|
2038
|
+
hookEngine: this.hookEngine,
|
|
2039
|
+
ruleEngine: this.ruleEngine,
|
|
2040
|
+
preflight: () => this.getPreFlightChecker(),
|
|
2041
|
+
constitution: () => this.getConstitutionLoader(),
|
|
2042
|
+
selfCritique: () => this.getSelfCritique(),
|
|
2043
|
+
crsiPreToolHook: this.crsiConfig?.preToolHook !== false,
|
|
2044
|
+
registry: this.registry,
|
|
2045
|
+
llm: this.llm,
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
/**
|
|
2050
|
+
* What a sub-agent needs to run the same gates as this loop.
|
|
2051
|
+
*
|
|
2052
|
+
* One producer (`Engine`) and one consumer (`SubAgent`). Before this existed,
|
|
2053
|
+
* all five production `new SubAgent(...)` sites passed `undefined` for the
|
|
2054
|
+
* hook engine and none of them reached the constitution / SIS / CRSI chain.
|
|
2055
|
+
*/
|
|
2056
|
+
getSubAgentServices(): SubAgentServices {
|
|
2057
|
+
return {
|
|
2058
|
+
gate: this.getToolGateDeps(),
|
|
2059
|
+
inferenceHook: this.inferenceHookConfig,
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2144
2063
|
/**
|
|
2145
2064
|
* SIS Phase 0: Lazily-initialized PreFlightChecker singleton.
|
|
2146
2065
|
* Checks tool calls against ErrorSignatureDB + ExperienceRuleEngine
|