cladogram 0.6.0-beta.7 → 0.6.0-beta.9

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.
@@ -0,0 +1,621 @@
1
+ /**
2
+ * Clado Pi 1.x Native Hooks Engine & Permissions / Safety Guard
3
+ *
4
+ * Persists user-level (`~/.pi/agent/`) and project-level (`<workspace>/.clado/`)
5
+ * deterministic lifecycle hooks (Claude Code / ZCode style) and tool permission
6
+ * policies (Claude Code / Codex style), and registers them as a built-in Pi 1.x
7
+ * Extension so every session & subagent enforces them natively.
8
+ */
9
+
10
+ import { spawn } from 'node:child_process';
11
+ import { randomUUID } from 'node:crypto';
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
13
+ import { isAbsolute, join, relative, resolve } from 'node:path';
14
+
15
+ export const HOOK_EVENTS = [
16
+ { id: 'PreToolUse', piEvent: 'tool_call', label: '工具调用前 (PreToolUse)', canBlock: true, desc: '在执行任意工具前触发;退出码 2 或返回 {"decision":"deny"} 可阻断调用' },
17
+ { id: 'PostToolUse', piEvent: 'tool_result', label: '工具调用后 (PostToolUse)', canBlock: false, desc: '工具执行完成后触发,可用于审计日志、通知或校验' },
18
+ { id: 'UserPromptSubmit', piEvent: 'input', label: '用户输入提交 (UserPromptSubmit)', canBlock: true, desc: '用户发送消息进入模型前触发,可附加提示词或拦截' },
19
+ { id: 'TurnStart', piEvent: 'before_agent_start', label: '回合开始前 (TurnStart)', canBlock: false, desc: '每轮模型推理开始前触发,可注入动态上下文' },
20
+ { id: 'Stop', piEvent: 'agent_end', label: '回合结束后 (Stop)', canBlock: false, desc: '模型完成本轮回复后触发,可用于构建/测试提醒或通知' },
21
+ { id: 'SessionStart', piEvent: 'session_start', label: '会话启动时 (SessionStart)', canBlock: false, desc: 'Pi 会话初始化完成时触发' },
22
+ { id: 'SessionEnd', piEvent: 'session_shutdown', label: '会话关闭时 (SessionEnd)', canBlock: false, desc: 'Pi 会话优雅关闭时触发' },
23
+ { id: 'PreCompact', piEvent: 'session_before_compact', label: '上下文压缩前 (PreCompact)', canBlock: false, desc: '触发自动或手动上下文压缩前执行' },
24
+ ];
25
+
26
+ export const PERMISSION_MODES = [
27
+ { id: 'full-access', label: '全自动模式 (Full Access)', desc: '放行所有工具与工作区写入(Deny 规则仍生效)' },
28
+ { id: 'workspace-write', label: '工作区安全写入 (Workspace Write)', desc: '工作区内读写自动放行;越界路径与高危 Shell 命令需确认或拦截' },
29
+ { id: 'ask-before-write', label: '写操作前确认 (Ask Before Write)', desc: '修改文件、写画布或执行 Shell 命令前弹窗请用户确认' },
30
+ { id: 'read-only', label: '只读评审模式 (Read-Only)', desc: '仅允许只读与检索工具,阻断一切文件写入、画布修改与 Shell 执行' },
31
+ ];
32
+
33
+ const WRITE_TOOL_NAMES = new Set([
34
+ 'write', 'edit', 'bash',
35
+ 'clado_create', 'clado_update', 'clado_delete', 'clado_move', 'clado_copy',
36
+ 'clado_links', 'canvas_objects_upsert',
37
+ ]);
38
+
39
+ const DANGEROUS_BASH_PATTERNS = [
40
+ /\brm\s+-[a-z]*r[a-z]*f\s+\/(?:\s|$|\*)/i,
41
+ /\bmkfs\b/i,
42
+ /\bdd\s+if=/i,
43
+ /\bshutdown\b|\breboot\b/i,
44
+ /\bsudo\b/i,
45
+ /\bgit\s+push\s+.*--force/i,
46
+ /\bgit\s+reset\s+--hard/i,
47
+ /:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;/,
48
+ ];
49
+
50
+ function readJsonSafe(file, fallback) {
51
+ if (!existsSync(file)) return fallback;
52
+ try {
53
+ return JSON.parse(readFileSync(file, 'utf8'));
54
+ } catch {
55
+ return fallback;
56
+ }
57
+ }
58
+
59
+ function writeJsonSafe(file, value) {
60
+ const dir = resolve(file, '..');
61
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
62
+ writeFileSync(file, JSON.stringify(value, null, 2) + '\n', 'utf8');
63
+ }
64
+
65
+ export function hooksFilePath(scope, workspace, agentDir) {
66
+ if (scope === 'project' && workspace) return join(resolve(workspace), '.clado', 'hooks.json');
67
+ return join(resolve(agentDir), 'clado-hooks.json');
68
+ }
69
+
70
+ export function permissionsFilePath(scope, workspace, agentDir) {
71
+ if (scope === 'project' && workspace) return join(resolve(workspace), '.clado', 'permissions.json');
72
+ return join(resolve(agentDir), 'clado-permissions.json');
73
+ }
74
+
75
+ function normalizeHook(raw, fallbackScope = 'user') {
76
+ const validEvent = HOOK_EVENTS.some(e => e.id === raw?.event) ? raw.event : 'PreToolUse';
77
+ const type = ['command', 'webhook', 'prompt'].includes(raw?.type) ? raw.type : 'command';
78
+ const timeoutMs = Number(raw?.timeoutMs);
79
+ return {
80
+ id: String(raw?.id || '').trim() || ('hook_' + randomUUID().slice(0, 8)),
81
+ name: String(raw?.name || '').trim() || `${validEvent} Hook`,
82
+ event: validEvent,
83
+ matcher: String(raw?.matcher || '*').trim() || '*',
84
+ type,
85
+ command: String(raw?.command || ''),
86
+ url: String(raw?.url || ''),
87
+ headers: raw?.headers && typeof raw.headers === 'object' && !Array.isArray(raw.headers) ? raw.headers : {},
88
+ prompt: String(raw?.prompt || ''),
89
+ timeoutMs: Number.isFinite(timeoutMs) && timeoutMs >= 500 ? Math.min(120000, Math.round(timeoutMs)) : 10000,
90
+ onFailure: raw?.onFailure === 'block' ? 'block' : 'allow',
91
+ enabled: raw?.enabled !== false,
92
+ scope: raw?.scope === 'project' ? 'project' : fallbackScope,
93
+ };
94
+ }
95
+
96
+ export function readHooksConfig(workspace, agentDir) {
97
+ const userPath = hooksFilePath('user', workspace, agentDir);
98
+ const projectPath = workspace ? hooksFilePath('project', workspace, agentDir) : '';
99
+ const userData = readJsonSafe(userPath, { version: 1, hooks: [] });
100
+ const projectData = projectPath ? readJsonSafe(projectPath, { version: 1, hooks: [] }) : { version: 1, hooks: [] };
101
+ const userHooks = (Array.isArray(userData?.hooks) ? userData.hooks : []).map(h => normalizeHook(h, 'user'));
102
+ const projectHooks = (Array.isArray(projectData?.hooks) ? projectData.hooks : []).map(h => normalizeHook(h, 'project'));
103
+ return {
104
+ userPath,
105
+ projectPath,
106
+ userHooks,
107
+ projectHooks,
108
+ hooks: [...userHooks, ...projectHooks],
109
+ events: HOOK_EVENTS,
110
+ };
111
+ }
112
+
113
+ export function saveHookRule(input, workspace, agentDir) {
114
+ const scope = input?.scope === 'project' && workspace ? 'project' : 'user';
115
+ const filePath = hooksFilePath(scope, workspace, agentDir);
116
+ const data = readJsonSafe(filePath, { version: 1, hooks: [] });
117
+ const list = Array.isArray(data?.hooks) ? data.hooks.map(h => normalizeHook(h, scope)) : [];
118
+ const next = normalizeHook({ ...input, scope }, scope);
119
+ const idx = list.findIndex(h => h.id === next.id);
120
+ if (idx >= 0) list[idx] = next;
121
+ else list.push(next);
122
+ writeJsonSafe(filePath, { version: 1, hooks: list });
123
+ return { ok: true, hook: next, hooksConfig: readHooksConfig(workspace, agentDir) };
124
+ }
125
+
126
+ export function deleteHookRule(id, scope, workspace, agentDir) {
127
+ const cleanId = String(id || '').trim();
128
+ if (!cleanId) return { ok: false };
129
+ const scopes = scope === 'user' || scope === 'project' ? [scope] : ['user', 'project'];
130
+ for (const sc of scopes) {
131
+ if (sc === 'project' && !workspace) continue;
132
+ const filePath = hooksFilePath(sc, workspace, agentDir);
133
+ if (!existsSync(filePath)) continue;
134
+ const data = readJsonSafe(filePath, { version: 1, hooks: [] });
135
+ const list = Array.isArray(data?.hooks) ? data.hooks : [];
136
+ const filtered = list.filter(h => h?.id !== cleanId);
137
+ if (filtered.length !== list.length) {
138
+ writeJsonSafe(filePath, { version: 1, hooks: filtered });
139
+ }
140
+ }
141
+ return { ok: true, id: cleanId, hooksConfig: readHooksConfig(workspace, agentDir) };
142
+ }
143
+
144
+ export function saveHooksRawJson(scope, jsonText, workspace, agentDir) {
145
+ const sc = scope === 'project' && workspace ? 'project' : 'user';
146
+ let parsed;
147
+ try {
148
+ parsed = JSON.parse(String(jsonText || '{}'));
149
+ } catch (err) {
150
+ throw new Error('Hooks JSON 语法错误:' + err.message);
151
+ }
152
+ const hooks = Array.isArray(parsed?.hooks) ? parsed.hooks.map(h => normalizeHook(h, sc)) : [];
153
+ writeJsonSafe(hooksFilePath(sc, workspace, agentDir), { version: 1, hooks });
154
+ return { ok: true, count: hooks.length, hooksConfig: readHooksConfig(workspace, agentDir) };
155
+ }
156
+
157
+ function normalizeStringList(v) {
158
+ if (!Array.isArray(v)) return [];
159
+ return [...new Set(v.map(s => String(s || '').trim()).filter(Boolean))];
160
+ }
161
+
162
+ function normalizePermissionsObj(raw) {
163
+ const mode = PERMISSION_MODES.some(m => m.id === raw?.mode) ? raw.mode : '';
164
+ return {
165
+ version: 1,
166
+ ...(mode ? { mode } : {}),
167
+ allow: normalizeStringList(raw?.allow),
168
+ ask: normalizeStringList(raw?.ask),
169
+ deny: normalizeStringList(raw?.deny),
170
+ shellEnvExclude: normalizeStringList(raw?.shellEnvExclude),
171
+ };
172
+ }
173
+
174
+ export function readPermissionsConfig(workspace, agentDir) {
175
+ const userPath = permissionsFilePath('user', workspace, agentDir);
176
+ const projectPath = workspace ? permissionsFilePath('project', workspace, agentDir) : '';
177
+ const userRaw = readJsonSafe(userPath, {});
178
+ const projectRaw = projectPath ? readJsonSafe(projectPath, {}) : {};
179
+ const user = normalizePermissionsObj(userRaw);
180
+ const project = normalizePermissionsObj(projectRaw);
181
+ const merged = {
182
+ mode: project.mode || user.mode || 'full-access',
183
+ allow: [...new Set([...user.allow, ...project.allow])],
184
+ ask: [...new Set([...user.ask, ...project.ask])],
185
+ deny: [...new Set([...user.deny, ...project.deny])],
186
+ shellEnvExclude: [...new Set([...user.shellEnvExclude, ...project.shellEnvExclude])],
187
+ };
188
+ return {
189
+ userPath,
190
+ projectPath,
191
+ user: { ...user, mode: user.mode || 'full-access' },
192
+ project: { ...project, mode: project.mode || '' },
193
+ effective: merged,
194
+ modes: PERMISSION_MODES,
195
+ };
196
+ }
197
+
198
+ export function savePermissionsConfig(input = {}, workspace, agentDir) {
199
+ const scope = input?.scope === 'project' && workspace ? 'project' : 'user';
200
+ const filePath = permissionsFilePath(scope, workspace, agentDir);
201
+ const prev = readJsonSafe(filePath, {});
202
+ const next = {
203
+ version: 1,
204
+ mode: input.mode === '' ? undefined : (PERMISSION_MODES.some(m => m.id === input.mode) ? input.mode : (prev.mode || (scope === 'user' ? 'full-access' : undefined))),
205
+ allow: input.allow !== undefined ? normalizeStringList(input.allow) : normalizeStringList(prev.allow),
206
+ ask: input.ask !== undefined ? normalizeStringList(input.ask) : normalizeStringList(prev.ask),
207
+ deny: input.deny !== undefined ? normalizeStringList(input.deny) : normalizeStringList(prev.deny),
208
+ shellEnvExclude: input.shellEnvExclude !== undefined ? normalizeStringList(input.shellEnvExclude) : normalizeStringList(prev.shellEnvExclude),
209
+ };
210
+ if (next.mode === undefined) delete next.mode;
211
+ writeJsonSafe(filePath, next);
212
+ return { ok: true, scope, permissions: readPermissionsConfig(workspace, agentDir) };
213
+ }
214
+
215
+ export function savePermissionsRawJson(scope, jsonText, workspace, agentDir) {
216
+ const sc = scope === 'project' && workspace ? 'project' : 'user';
217
+ let parsed;
218
+ try {
219
+ parsed = JSON.parse(String(jsonText || '{}'));
220
+ } catch (err) {
221
+ throw new Error('Permissions JSON 语法错误:' + err.message);
222
+ }
223
+ const normalized = normalizePermissionsObj(parsed);
224
+ writeJsonSafe(permissionsFilePath(sc, workspace, agentDir), normalized);
225
+ return { ok: true, scope: sc, permissions: readPermissionsConfig(workspace, agentDir) };
226
+ }
227
+
228
+ // ============================================================================
229
+ // Pattern matching for Rules & Hook Matchers
230
+ // ============================================================================
231
+
232
+ function globToRegExp(glob) {
233
+ const escaped = String(glob || '').replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
234
+ return new RegExp('^' + escaped + '$', 'i');
235
+ }
236
+
237
+ export function matchesHookMatcher(matcher, target) {
238
+ const raw = String(matcher || '*').trim();
239
+ if (!raw || raw === '*') return true;
240
+ const val = String(target || '');
241
+ // Support pipe-separated tokens or regex-like patterns (e.g. "edit|write" or "mcp__*")
242
+ const parts = raw.split('|').map(s => s.trim()).filter(Boolean);
243
+ for (const part of parts) {
244
+ if (part === '*') return true;
245
+ if (part.includes('*') || part.includes('?')) {
246
+ if (globToRegExp(part).test(val)) return true;
247
+ } else if (part.toLowerCase() === val.toLowerCase()) {
248
+ return true;
249
+ }
250
+ }
251
+ return false;
252
+ }
253
+
254
+ function extractToolTargetString(toolName, input) {
255
+ if (!input || typeof input !== 'object') return '';
256
+ if (toolName === 'bash') return String(input.command || input.cmd || '');
257
+ return String(input.path || input.file || input.filePath || input.target || input.pattern || input.query || input.url || '');
258
+ }
259
+
260
+ export function matchesToolRule(ruleStr, toolName, input = {}) {
261
+ const clean = String(ruleStr || '').trim();
262
+ if (!clean) return false;
263
+ const m = clean.match(/^([^(]+)\((.*)\)$/);
264
+ if (!m) {
265
+ return matchesHookMatcher(clean, toolName);
266
+ }
267
+ const toolPattern = m[1].trim();
268
+ const argPattern = m[2].trim();
269
+ if (!matchesHookMatcher(toolPattern, toolName)) return false;
270
+ if (!argPattern || argPattern === '*') return true;
271
+ const target = extractToolTargetString(toolName, input);
272
+ if (!target) return false;
273
+ return globToRegExp(argPattern).test(target) || target.toLowerCase().includes(argPattern.replace(/\*/g, '').toLowerCase());
274
+ }
275
+
276
+ export function isPathOutsideWorkspace(candidatePath, workspace) {
277
+ if (!candidatePath || !workspace) return false;
278
+ const ws = resolve(workspace);
279
+ const full = isAbsolute(candidatePath) ? resolve(candidatePath) : resolve(ws, candidatePath);
280
+ const rel = relative(ws, full);
281
+ return rel.startsWith('..') || isAbsolute(rel);
282
+ }
283
+
284
+ export function buildSanitizedEnv(shellEnvExclude = []) {
285
+ const env = { ...process.env };
286
+ const patterns = normalizeStringList(shellEnvExclude);
287
+ if (!patterns.length) return env;
288
+ const regexes = patterns.map(p => globToRegExp(p));
289
+ for (const key of Object.keys(env)) {
290
+ if (regexes.some(rx => rx.test(key))) delete env[key];
291
+ }
292
+ return env;
293
+ }
294
+
295
+ export function evaluatePermission({ toolName, input = {}, workspace = '', perms }) {
296
+ const p = perms || { mode: 'full-access', allow: [], ask: [], deny: [] };
297
+ for (const rule of p.deny || []) {
298
+ if (matchesToolRule(rule, toolName, input)) {
299
+ return { decision: 'deny', reason: `被安全策略 Deny 规则拦截:${rule}` };
300
+ }
301
+ }
302
+ for (const rule of p.allow || []) {
303
+ if (matchesToolRule(rule, toolName, input)) {
304
+ return { decision: 'allow', reason: `匹配 Allow 规则:${rule}` };
305
+ }
306
+ }
307
+ for (const rule of p.ask || []) {
308
+ if (matchesToolRule(rule, toolName, input)) {
309
+ return { decision: 'ask', reason: `匹配 Ask 规则(${rule}),需要用户确认` };
310
+ }
311
+ }
312
+
313
+ const mode = p.mode || 'full-access';
314
+ if (mode === 'read-only') {
315
+ if (WRITE_TOOL_NAMES.has(toolName) || /^(write|edit|delete|remove|create|update|move|bash|exec|run)/i.test(toolName)) {
316
+ return { decision: 'deny', reason: `当前处于只读评审模式 (read-only),已拦截写操作工具 ${toolName}` };
317
+ }
318
+ return { decision: 'allow' };
319
+ }
320
+ if (mode === 'ask-before-write') {
321
+ if (WRITE_TOOL_NAMES.has(toolName)) {
322
+ return { decision: 'ask', reason: `当前处于写操作前确认模式 (ask-before-write),工具 ${toolName} 需要确认` };
323
+ }
324
+ return { decision: 'allow' };
325
+ }
326
+ if (mode === 'workspace-write') {
327
+ if (toolName === 'bash') {
328
+ const cmd = String(input?.command || '');
329
+ if (DANGEROUS_BASH_PATTERNS.some(rx => rx.test(cmd))) {
330
+ return { decision: 'ask', reason: `检测到高危 Shell 命令,工作区安全模式要求确认:${cmd.slice(0, 120)}` };
331
+ }
332
+ }
333
+ if ((toolName === 'write' || toolName === 'edit') && isPathOutsideWorkspace(input?.path || input?.filePath, workspace)) {
334
+ return { decision: 'deny', reason: `工作区安全模式禁止修改工作区之外的路径:${input?.path || input?.filePath}` };
335
+ }
336
+ return { decision: 'allow' };
337
+ }
338
+ return { decision: 'allow' };
339
+ }
340
+
341
+ // ============================================================================
342
+ // Hook Execution Engine (Command / Webhook / Prompt)
343
+ // ============================================================================
344
+
345
+ export async function runSingleHook(hook, payload = {}, workspace = '', shellEnvExclude = []) {
346
+ const start = Date.now();
347
+ if (hook.type === 'prompt') {
348
+ const text = String(hook.prompt || '').trim();
349
+ return {
350
+ ok: true,
351
+ exitCode: 0,
352
+ decision: 'allow',
353
+ additionalContext: text,
354
+ stdout: text,
355
+ stderr: '',
356
+ durationMs: Date.now() - start,
357
+ };
358
+ }
359
+
360
+ if (hook.type === 'webhook') {
361
+ const url = String(hook.url || '').trim();
362
+ if (!url) {
363
+ return { ok: false, exitCode: 1, decision: hook.onFailure === 'block' ? 'deny' : 'allow', reason: 'Webhook URL 不能为空', stdout: '', stderr: 'Missing URL', durationMs: Date.now() - start };
364
+ }
365
+ const ctrl = new AbortController();
366
+ const timer = setTimeout(() => ctrl.abort(), hook.timeoutMs || 10000);
367
+ try {
368
+ const res = await fetch(url, {
369
+ method: 'POST',
370
+ headers: { 'content-type': 'application/json', ...(hook.headers || {}) },
371
+ body: JSON.stringify(payload),
372
+ signal: ctrl.signal,
373
+ });
374
+ const text = await res.text();
375
+ let parsed = null;
376
+ try { parsed = JSON.parse(text); } catch {}
377
+ const decision = parsed?.decision === 'deny' || parsed?.block === true
378
+ ? 'deny'
379
+ : (!res.ok && hook.onFailure === 'block' ? 'deny' : 'allow');
380
+ return {
381
+ ok: res.ok,
382
+ exitCode: res.ok ? 0 : res.status,
383
+ decision,
384
+ reason: parsed?.reason || (!res.ok ? `Webhook HTTP ${res.status}` : ''),
385
+ additionalContext: parsed?.additionalContext || '',
386
+ stdout: text.slice(0, 4000),
387
+ stderr: res.ok ? '' : `HTTP ${res.status}`,
388
+ durationMs: Date.now() - start,
389
+ };
390
+ } catch (err) {
391
+ return {
392
+ ok: false,
393
+ exitCode: 1,
394
+ decision: hook.onFailure === 'block' ? 'deny' : 'allow',
395
+ reason: err?.message || 'Webhook 调用失败',
396
+ stdout: '',
397
+ stderr: err?.message || 'Webhook failed',
398
+ durationMs: Date.now() - start,
399
+ };
400
+ } finally {
401
+ clearTimeout(timer);
402
+ }
403
+ }
404
+
405
+ // type === 'command'
406
+ const cmd = String(hook.command || '').trim();
407
+ if (!cmd) {
408
+ return { ok: false, exitCode: 1, decision: hook.onFailure === 'block' ? 'deny' : 'allow', reason: '命令为空', stdout: '', stderr: 'Empty command', durationMs: Date.now() - start };
409
+ }
410
+ return await new Promise(resolveRun => {
411
+ const child = spawn(cmd, {
412
+ cwd: workspace && existsSync(workspace) ? workspace : process.cwd(),
413
+ shell: true,
414
+ env: {
415
+ ...buildSanitizedEnv(shellEnvExclude),
416
+ CLADO_HOOK_EVENT: String(payload.event || hook.event || ''),
417
+ CLADO_WORKSPACE: String(workspace || ''),
418
+ },
419
+ stdio: ['pipe', 'pipe', 'pipe'],
420
+ });
421
+ let stdout = '';
422
+ let stderr = '';
423
+ let finished = false;
424
+ const timer = setTimeout(() => {
425
+ if (finished) return;
426
+ finished = true;
427
+ try { child.kill('SIGTERM'); } catch {}
428
+ resolveRun({
429
+ ok: false,
430
+ exitCode: 124,
431
+ decision: hook.onFailure === 'block' ? 'deny' : 'allow',
432
+ reason: `Hook 执行超时(>${hook.timeoutMs || 10000}ms)`,
433
+ stdout: stdout.slice(0, 4000),
434
+ stderr: (stderr || 'Timed out').slice(0, 4000),
435
+ durationMs: Date.now() - start,
436
+ });
437
+ }, hook.timeoutMs || 10000);
438
+
439
+ child.stdout.on('data', chunk => { if (stdout.length < 16000) stdout += String(chunk); });
440
+ child.stderr.on('data', chunk => { if (stderr.length < 16000) stderr += String(chunk); });
441
+ child.on('error', err => {
442
+ if (finished) return;
443
+ finished = true;
444
+ clearTimeout(timer);
445
+ resolveRun({
446
+ ok: false,
447
+ exitCode: 1,
448
+ decision: hook.onFailure === 'block' ? 'deny' : 'allow',
449
+ reason: err.message,
450
+ stdout: stdout.slice(0, 4000),
451
+ stderr: err.message,
452
+ durationMs: Date.now() - start,
453
+ });
454
+ });
455
+ child.on('close', code => {
456
+ if (finished) return;
457
+ finished = true;
458
+ clearTimeout(timer);
459
+ const trimmed = stdout.trim();
460
+ let parsed = null;
461
+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
462
+ try { parsed = JSON.parse(trimmed); } catch {}
463
+ }
464
+ // Claude Code convention: exit code 2 ALWAYS blocks (stderr or JSON reason explains why)
465
+ const isBlocked = code === 2
466
+ || parsed?.decision === 'deny'
467
+ || parsed?.permissionDecision === 'deny'
468
+ || parsed?.block === true
469
+ || (code !== 0 && hook.onFailure === 'block');
470
+ const reason = parsed?.reason || (isBlocked ? (stderr.trim() || trimmed || `Hook 拦截(exit ${code})`) : '');
471
+ resolveRun({
472
+ ok: code === 0,
473
+ exitCode: code ?? 1,
474
+ decision: isBlocked ? 'deny' : 'allow',
475
+ reason,
476
+ additionalContext: parsed?.additionalContext || (!parsed && code === 0 && trimmed ? trimmed : ''),
477
+ stdout: stdout.slice(0, 4000),
478
+ stderr: stderr.slice(0, 4000),
479
+ durationMs: Date.now() - start,
480
+ });
481
+ });
482
+ try {
483
+ child.stdin.write(JSON.stringify(payload));
484
+ child.stdin.end();
485
+ } catch {}
486
+ });
487
+ }
488
+
489
+ export async function testHookRule(rule, samplePayload = {}, workspace = '', agentDir = '') {
490
+ const normalized = normalizeHook(rule, rule?.scope || 'user');
491
+ const perms = agentDir ? readPermissionsConfig(workspace, agentDir).effective : { shellEnvExclude: [] };
492
+ const payload = {
493
+ event: normalized.event,
494
+ toolName: samplePayload.toolName || 'bash',
495
+ input: samplePayload.input || { command: 'echo hello' },
496
+ workspace: workspace || process.cwd(),
497
+ dryRunTest: true,
498
+ ...samplePayload,
499
+ };
500
+ return await runSingleHook(normalized, payload, workspace, perms.shellEnvExclude);
501
+ }
502
+
503
+ // ============================================================================
504
+ // Built-in Pi 1.x Extension Factory: Enforces Permissions + Lifecycle Hooks
505
+ // ============================================================================
506
+
507
+ export function createCladoGuardAndHooksExtension({ workspace, agentDir, getAskUser, getRoleTools }) {
508
+ return pi => {
509
+ const runMatchingHooks = async (eventId, matchTarget, payload) => {
510
+ const cfg = readHooksConfig(workspace, agentDir);
511
+ const perms = readPermissionsConfig(workspace, agentDir).effective;
512
+ const matched = cfg.hooks.filter(h => h.enabled && h.event === eventId && matchesHookMatcher(h.matcher, matchTarget));
513
+ const contexts = [];
514
+ for (const hook of matched) {
515
+ const res = await runSingleHook(hook, { event: eventId, workspace, ...payload }, workspace, perms.shellEnvExclude);
516
+ if (res.decision === 'deny') {
517
+ return { blocked: true, reason: res.reason || `被 Hook 「${hook.name}」拦截`, contexts };
518
+ }
519
+ if (res.additionalContext) contexts.push(res.additionalContext);
520
+ }
521
+ return { blocked: false, reason: '', contexts };
522
+ };
523
+
524
+ // 1. PreToolUse + Permissions + Role Tool Restrictions
525
+ pi.on('tool_call', async event => {
526
+ const toolName = String(event?.toolName || '');
527
+ const input = event?.input || {};
528
+
529
+ // Per-role tool allowlist / denylist enforcement (Zed Agent Profile parity)
530
+ const roleTools = typeof getRoleTools === 'function' ? getRoleTools() : null;
531
+ if (roleTools) {
532
+ if (Array.isArray(roleTools.disabledTools) && roleTools.disabledTools.length) {
533
+ if (roleTools.disabledTools.some(rule => matchesToolRule(rule, toolName, input))) {
534
+ return { block: true, reason: `当前智能体角色已禁用工具 ${toolName}` };
535
+ }
536
+ }
537
+ if (Array.isArray(roleTools.tools) && roleTools.tools.length) {
538
+ if (!roleTools.tools.some(rule => matchesToolRule(rule, toolName, input))) {
539
+ return { block: true, reason: `当前智能体角色仅允许使用白名单工具(${roleTools.tools.join(', ')})` };
540
+ }
541
+ }
542
+ }
543
+
544
+ // Workspace/User permission policy evaluation
545
+ const perms = readPermissionsConfig(workspace, agentDir).effective;
546
+ const evalRes = evaluatePermission({ toolName, input, workspace, perms });
547
+ if (evalRes.decision === 'deny') {
548
+ return { block: true, reason: evalRes.reason };
549
+ }
550
+ if (evalRes.decision === 'ask') {
551
+ const askFn = typeof getAskUser === 'function' ? getAskUser() : null;
552
+ if (askFn) {
553
+ const preview = extractToolTargetString(toolName, input).slice(0, 200);
554
+ const ans = await askFn({
555
+ question: `${evalRes.reason}\n\n工具:${toolName}${preview ? '\n目标:' + preview : ''}\n是否放行本次操作?`,
556
+ options: ['放行本次操作', '拒绝执行'],
557
+ });
558
+ if (!ans || String(ans).includes('拒绝')) {
559
+ return { block: true, reason: `用户拒绝执行工具 ${toolName}` };
560
+ }
561
+ } else {
562
+ return { block: true, reason: `${evalRes.reason}(当前无交互通道,已保守拦截)` };
563
+ }
564
+ }
565
+
566
+ // PreToolUse Hooks
567
+ const hookRes = await runMatchingHooks('PreToolUse', toolName, { toolName, input });
568
+ if (hookRes.blocked) {
569
+ return { block: true, reason: hookRes.reason };
570
+ }
571
+ return undefined;
572
+ });
573
+
574
+ // 2. PostToolUse Hooks
575
+ pi.on('tool_result', async event => {
576
+ const toolName = String(event?.toolName || '');
577
+ await runMatchingHooks('PostToolUse', toolName, {
578
+ toolName,
579
+ input: event?.input || {},
580
+ isError: Boolean(event?.isError),
581
+ });
582
+ return undefined;
583
+ });
584
+
585
+ // 3. UserPromptSubmit Hooks
586
+ pi.on('input', async event => {
587
+ const text = String(event?.text || '');
588
+ const hookRes = await runMatchingHooks('UserPromptSubmit', '*', { text });
589
+ if (hookRes.blocked) {
590
+ return { action: 'handled' };
591
+ }
592
+ if (hookRes.contexts.length) {
593
+ return { action: 'transform', text: text + '\n\n' + hookRes.contexts.join('\n') };
594
+ }
595
+ return undefined;
596
+ });
597
+
598
+ // 4. TurnStart Hooks (before_agent_start)
599
+ pi.on('before_agent_start', async event => {
600
+ const hookRes = await runMatchingHooks('TurnStart', '*', { prompt: String(event?.prompt || '') });
601
+ if (hookRes.contexts.length) {
602
+ return { systemPrompt: (event?.systemPrompt || '') + '\n\n' + hookRes.contexts.join('\n') };
603
+ }
604
+ return undefined;
605
+ });
606
+
607
+ // 5. Stop / SessionStart / SessionEnd / PreCompact Hooks
608
+ pi.on('agent_end', async () => {
609
+ await runMatchingHooks('Stop', '*', {});
610
+ });
611
+ pi.on('session_start', async () => {
612
+ await runMatchingHooks('SessionStart', '*', {});
613
+ });
614
+ pi.on('session_shutdown', async () => {
615
+ await runMatchingHooks('SessionEnd', '*', {});
616
+ });
617
+ pi.on('session_before_compact', async () => {
618
+ await runMatchingHooks('PreCompact', '*', {});
619
+ });
620
+ };
621
+ }
@@ -15,7 +15,11 @@ const screenshotAssets = [
15
15
  { path: '/canvas-screenshot.js', file: new URL('canvas-screenshot.js', import.meta.url) },
16
16
  ];
17
17
  const workspaceAssets = [...canvasAssets, ...packageAssets('directory'), ...screenshotAssets];
18
- const agentAssets = packageAssets('agent');
18
+ const agentAssets = [
19
+ { path: '/plugins/agent/style.css', file: new URL('../../plugins/agent/style.css', import.meta.url) },
20
+ { path: '/plugins/agent/settings.js', file: new URL('../../plugins/agent/settings.js', import.meta.url) },
21
+ { path: '/plugins/agent/index.js', file: new URL('../../plugins/agent/index.js', import.meta.url) },
22
+ ];
19
23
  export const workspacePluginAssets = new Map([...workspaceAssets, ...agentAssets].map(({ path, file }) => [path, file]));
20
24
 
21
25
  export function pluginMarkup({ workspace = false, inline = false, agent = false, materialOnly = false } = {}) {