@miphamai/cli 0.85.33 → 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/engine.ts +59 -140
- package/src/core/permission-rules.ts +67 -12
- 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/daemon/remote-engine.ts +3 -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 +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
|
}
|
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
|
|
@@ -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
|
@@ -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 {
|