@blockrun/franklin 3.33.0 → 3.34.0
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 +23 -2
- package/dist/agent/approvals.d.ts +47 -0
- package/dist/agent/approvals.js +66 -0
- package/dist/agent/commands.js +230 -7
- package/dist/agent/input-queue.d.ts +26 -0
- package/dist/agent/input-queue.js +65 -0
- package/dist/agent/loop.js +196 -3
- package/dist/agent/streaming-executor.d.ts +4 -0
- package/dist/agent/streaming-executor.js +52 -0
- package/dist/agent/tool-guard.d.ts +7 -0
- package/dist/agent/tool-guard.js +21 -0
- package/dist/agent/types.d.ts +26 -0
- package/dist/audit/approvals.d.ts +20 -0
- package/dist/audit/approvals.js +21 -0
- package/dist/commands/start.d.ts +10 -1
- package/dist/commands/start.js +53 -1
- package/dist/events/types.d.ts +38 -1
- package/dist/goal/engine.d.ts +39 -0
- package/dist/goal/engine.js +182 -0
- package/dist/goal/prompts.d.ts +16 -0
- package/dist/goal/prompts.js +206 -0
- package/dist/goal/runtime.d.ts +20 -0
- package/dist/goal/runtime.js +110 -0
- package/dist/goal/store.d.ts +22 -0
- package/dist/goal/store.js +79 -0
- package/dist/goal/types.d.ts +63 -0
- package/dist/goal/types.js +26 -0
- package/dist/hooks/loader.d.ts +19 -0
- package/dist/hooks/loader.js +115 -0
- package/dist/hooks/runner.d.ts +31 -0
- package/dist/hooks/runner.js +147 -0
- package/dist/hooks/types.d.ts +64 -0
- package/dist/hooks/types.js +35 -0
- package/dist/index.js +5 -1
- package/dist/memory/capture.d.ts +40 -0
- package/dist/memory/capture.js +95 -0
- package/dist/memory/dream.d.ts +24 -0
- package/dist/memory/dream.js +147 -0
- package/dist/memory/indexer.d.ts +29 -0
- package/dist/memory/indexer.js +144 -0
- package/dist/memory/store.d.ts +50 -0
- package/dist/memory/store.js +163 -0
- package/dist/monitors/registry.d.ts +42 -0
- package/dist/monitors/registry.js +104 -0
- package/dist/panel/html.js +299 -0
- package/dist/panel/server.js +41 -0
- package/dist/scheduler/service.d.ts +24 -0
- package/dist/scheduler/service.js +44 -0
- package/dist/scheduler/store.d.ts +26 -0
- package/dist/scheduler/store.js +116 -0
- package/dist/scheduler/types.d.ts +36 -0
- package/dist/scheduler/types.js +31 -0
- package/dist/serve/agent-host.d.ts +63 -0
- package/dist/serve/agent-host.js +270 -0
- package/dist/serve/server.js +131 -2
- package/dist/session/live-registry.d.ts +32 -0
- package/dist/session/live-registry.js +83 -0
- package/dist/session/search.d.ts +6 -0
- package/dist/session/search.js +3 -3
- package/dist/session/storage.d.ts +6 -0
- package/dist/session/storage.js +6 -0
- package/dist/tools/goal.d.ts +7 -0
- package/dist/tools/goal.js +29 -0
- package/dist/tools/index.js +11 -0
- package/dist/tools/memory.js +14 -4
- package/dist/tools/monitor.d.ts +11 -0
- package/dist/tools/monitor.js +96 -0
- package/dist/tools/scheduler.d.ts +12 -0
- package/dist/tools/scheduler.js +79 -0
- package/dist/tools/spend-tools.d.ts +33 -0
- package/dist/tools/spend-tools.js +114 -0
- package/dist/tools/tool-categories.js +7 -0
- package/dist/tools/trade-plan.d.ts +11 -0
- package/dist/tools/trade-plan.js +137 -0
- package/dist/tools/trading-execute.js +24 -0
- package/dist/trading/trade-plan.d.ts +75 -0
- package/dist/trading/trade-plan.js +290 -0
- package/package.json +2 -2
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal runtime — bridges the UpdateGoal capability (constructed at module
|
|
3
|
+
* load, before any session exists) to the session's model client and
|
|
4
|
+
* capability set, and processes completion claims through the verifier
|
|
5
|
+
* panel. The loop installs the dependencies at session start.
|
|
6
|
+
*/
|
|
7
|
+
import { getActiveGoal, loadPlan, saveVerdicts, updateActiveGoal, } from './store.js';
|
|
8
|
+
import { needsStrategist, runStrategist, runSummarizer, runVerifierPanel, } from './engine.js';
|
|
9
|
+
import { goalMaxRounds } from './types.js';
|
|
10
|
+
let deps = null;
|
|
11
|
+
export function setGoalEngineDeps(d) {
|
|
12
|
+
deps = d;
|
|
13
|
+
}
|
|
14
|
+
function engineContext(scope) {
|
|
15
|
+
if (!deps)
|
|
16
|
+
return null;
|
|
17
|
+
return {
|
|
18
|
+
client: deps.client,
|
|
19
|
+
model: deps.getModel(),
|
|
20
|
+
capabilities: deps.capabilities,
|
|
21
|
+
workingDir: scope.workingDir,
|
|
22
|
+
signal: scope.abortSignal,
|
|
23
|
+
onProgress: scope.onProgress,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export async function processGoalClaim(input, scope) {
|
|
27
|
+
const goal = getActiveGoal();
|
|
28
|
+
if (!goal) {
|
|
29
|
+
return { output: 'No active goal. Start one with the /goal command.', isError: true };
|
|
30
|
+
}
|
|
31
|
+
if (input.blocked_reason) {
|
|
32
|
+
updateActiveGoal({ status: 'blocked', blockedReason: String(input.blocked_reason) });
|
|
33
|
+
return {
|
|
34
|
+
output: `Goal marked blocked: ${input.blocked_reason}. Explain the blocker to the user and ` +
|
|
35
|
+
'what decision you need from them. The goal resumes with /goal resume.',
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
if (!input.completed) {
|
|
39
|
+
// Progress note — recorded, no verification.
|
|
40
|
+
return {
|
|
41
|
+
output: `Progress noted${input.message ? `: ${String(input.message).slice(0, 200)}` : ''}. Keep working the plan.`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const ctx = engineContext(scope);
|
|
45
|
+
if (!ctx) {
|
|
46
|
+
return { output: 'Goal engine is not initialized in this session.', isError: true };
|
|
47
|
+
}
|
|
48
|
+
const round = goal.rounds.length + 1;
|
|
49
|
+
if (round > goalMaxRounds()) {
|
|
50
|
+
updateActiveGoal({
|
|
51
|
+
status: 'blocked',
|
|
52
|
+
blockedReason: `verification round cap (${goalMaxRounds()}) reached`,
|
|
53
|
+
});
|
|
54
|
+
return {
|
|
55
|
+
output: `Verification round cap reached (${goalMaxRounds()} rounds). The goal is now blocked — ` +
|
|
56
|
+
'summarize for the user what passed, what kept failing, and ask how they want to proceed.',
|
|
57
|
+
isError: true,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
updateActiveGoal({ status: 'verifying' });
|
|
61
|
+
const planMd = loadPlan(goal.id);
|
|
62
|
+
const outcome = await runVerifierPanel(ctx, goal, planMd, String(input.message ?? ''));
|
|
63
|
+
saveVerdicts(goal.id, round, outcome.verdicts);
|
|
64
|
+
const rounds = [...goal.rounds, { round, refuted: outcome.refuted, gaps: outcome.gaps, at: Date.now() }];
|
|
65
|
+
if (!outcome.refuted) {
|
|
66
|
+
let summary = '';
|
|
67
|
+
try {
|
|
68
|
+
summary = await runSummarizer(ctx, { ...goal, rounds }, planMd);
|
|
69
|
+
}
|
|
70
|
+
catch { /* summary is best-effort */ }
|
|
71
|
+
updateActiveGoal({ status: 'completed', rounds, verifierGaps: [], summary });
|
|
72
|
+
return {
|
|
73
|
+
output: `GOAL VERIFIED COMPLETE (round ${round}, ${outcome.verdicts.length}-reviewer panel).\n\n` +
|
|
74
|
+
`${summary || 'Deliverable verified against every acceptance criterion.'}\n\n` +
|
|
75
|
+
'Relay this closing summary to the user verbatim, then stop working the goal.',
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
if (outcome.blocking !== 'none') {
|
|
79
|
+
updateActiveGoal({
|
|
80
|
+
status: 'blocked',
|
|
81
|
+
rounds,
|
|
82
|
+
verifierGaps: outcome.gaps,
|
|
83
|
+
blockedReason: `verifiers judged the goal ${outcome.blocking}`,
|
|
84
|
+
});
|
|
85
|
+
return {
|
|
86
|
+
output: `Completion claim REFUTED as ${outcome.blocking.toUpperCase()} — this is not fixable by more work.\n` +
|
|
87
|
+
`Findings:\n${outcome.gaps.map(g => `- ${g}`).join('\n')}\n\n` +
|
|
88
|
+
'Escalate to the user: explain the contradiction/unverifiable evidence and ask for a decision.',
|
|
89
|
+
isError: true,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
const updated = updateActiveGoal({ status: 'active', rounds, verifierGaps: outcome.gaps });
|
|
93
|
+
let strategistLine = '';
|
|
94
|
+
if (updated && needsStrategist(updated)) {
|
|
95
|
+
try {
|
|
96
|
+
const note = await runStrategist(ctx, updated, planMd);
|
|
97
|
+
updateActiveGoal({ strategistNote: note });
|
|
98
|
+
strategistLine = `\n\nStrategist intervention (structural — apply this rather than patching symptoms):\n${note}`;
|
|
99
|
+
}
|
|
100
|
+
catch { /* strategist is best-effort */ }
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
output: `Completion claim REFUTED by the verifier panel (round ${round}).\n` +
|
|
104
|
+
`Gaps to close:\n${outcome.gaps.map(g => `- ${g}`).join('\n')}` +
|
|
105
|
+
strategistLine +
|
|
106
|
+
'\n\nAddress every gap, re-run the plan\'s verification yourself, then claim completion again. ' +
|
|
107
|
+
'The panel judges only against the plan\'s acceptance criteria — no new requirements will appear.',
|
|
108
|
+
isError: true,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal persistence — ~/.blockrun/goals/<id>/ holding goal.json (atomic),
|
|
3
|
+
* plan.md (frozen by the planner), and verdicts/round-N.json. Plus the
|
|
4
|
+
* process-scoped active-goal slot the loop and /goal command share.
|
|
5
|
+
*/
|
|
6
|
+
import type { GoalKind, GoalState, VerifierVerdict } from './types.js';
|
|
7
|
+
export declare function goalsDir(): string;
|
|
8
|
+
export declare function goalDir(id: string): string;
|
|
9
|
+
export declare function saveGoal(goal: GoalState): void;
|
|
10
|
+
export declare function loadGoal(id: string): GoalState | null;
|
|
11
|
+
export declare function savePlan(id: string, planMd: string): void;
|
|
12
|
+
export declare function loadPlan(id: string): string;
|
|
13
|
+
export declare function saveVerdicts(id: string, round: number, verdicts: VerifierVerdict[]): void;
|
|
14
|
+
export declare function createGoal(opts: {
|
|
15
|
+
objective: string;
|
|
16
|
+
kind: GoalKind;
|
|
17
|
+
maxUsd?: number;
|
|
18
|
+
}): GoalState;
|
|
19
|
+
export declare function setActiveGoal(goal: GoalState | null): void;
|
|
20
|
+
export declare function getActiveGoal(): GoalState | null;
|
|
21
|
+
/** Mutate + persist + keep the in-memory slot coherent. */
|
|
22
|
+
export declare function updateActiveGoal(patch: Partial<GoalState>): GoalState | null;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal persistence — ~/.blockrun/goals/<id>/ holding goal.json (atomic),
|
|
3
|
+
* plan.md (frozen by the planner), and verdicts/round-N.json. Plus the
|
|
4
|
+
* process-scoped active-goal slot the loop and /goal command share.
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import { BLOCKRUN_DIR } from '../config.js';
|
|
10
|
+
export function goalsDir() {
|
|
11
|
+
return path.join(BLOCKRUN_DIR, 'goals');
|
|
12
|
+
}
|
|
13
|
+
export function goalDir(id) {
|
|
14
|
+
return path.join(goalsDir(), id);
|
|
15
|
+
}
|
|
16
|
+
export function saveGoal(goal) {
|
|
17
|
+
const dir = goalDir(goal.id);
|
|
18
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
19
|
+
const tmp = path.join(dir, '.goal.tmp');
|
|
20
|
+
fs.writeFileSync(tmp, JSON.stringify({ ...goal, updatedAt: Date.now() }, null, 2));
|
|
21
|
+
fs.renameSync(tmp, path.join(dir, 'goal.json'));
|
|
22
|
+
}
|
|
23
|
+
export function loadGoal(id) {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(fs.readFileSync(path.join(goalDir(id), 'goal.json'), 'utf-8'));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export function savePlan(id, planMd) {
|
|
32
|
+
fs.mkdirSync(goalDir(id), { recursive: true });
|
|
33
|
+
fs.writeFileSync(path.join(goalDir(id), 'plan.md'), planMd);
|
|
34
|
+
}
|
|
35
|
+
export function loadPlan(id) {
|
|
36
|
+
try {
|
|
37
|
+
return fs.readFileSync(path.join(goalDir(id), 'plan.md'), 'utf-8');
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return '';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function saveVerdicts(id, round, verdicts) {
|
|
44
|
+
const dir = path.join(goalDir(id), 'verdicts');
|
|
45
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
46
|
+
fs.writeFileSync(path.join(dir, `round-${round}.json`), JSON.stringify(verdicts, null, 2));
|
|
47
|
+
}
|
|
48
|
+
export function createGoal(opts) {
|
|
49
|
+
const goal = {
|
|
50
|
+
id: `g_${crypto.randomBytes(5).toString('hex')}`,
|
|
51
|
+
objective: opts.objective,
|
|
52
|
+
kind: opts.kind,
|
|
53
|
+
status: 'active',
|
|
54
|
+
createdAt: Date.now(),
|
|
55
|
+
updatedAt: Date.now(),
|
|
56
|
+
rounds: [],
|
|
57
|
+
verifierGaps: [],
|
|
58
|
+
turnsUsed: 0,
|
|
59
|
+
budget: { maxUsd: opts.maxUsd, spentUsd: 0 },
|
|
60
|
+
};
|
|
61
|
+
saveGoal(goal);
|
|
62
|
+
return goal;
|
|
63
|
+
}
|
|
64
|
+
// ─── Active-goal slot (process-scoped, one per session) ────────────────────
|
|
65
|
+
let activeGoal = null;
|
|
66
|
+
export function setActiveGoal(goal) {
|
|
67
|
+
activeGoal = goal;
|
|
68
|
+
}
|
|
69
|
+
export function getActiveGoal() {
|
|
70
|
+
return activeGoal;
|
|
71
|
+
}
|
|
72
|
+
/** Mutate + persist + keep the in-memory slot coherent. */
|
|
73
|
+
export function updateActiveGoal(patch) {
|
|
74
|
+
if (!activeGoal)
|
|
75
|
+
return null;
|
|
76
|
+
activeGoal = { ...activeGoal, ...patch, updatedAt: Date.now() };
|
|
77
|
+
saveGoal(activeGoal);
|
|
78
|
+
return activeGoal;
|
|
79
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal engine — cross-turn autonomous objectives.
|
|
3
|
+
*
|
|
4
|
+
* A goal freezes an objective into a plan (outcomes, not implementation),
|
|
5
|
+
* steers the main model with per-turn directives, and gates every
|
|
6
|
+
* completion claim behind an adversarial verifier panel that defaults to
|
|
7
|
+
* refuting. The architecture is deliberately defensive: plausible-but-
|
|
8
|
+
* incomplete work must not survive verification, and verification must not
|
|
9
|
+
* ratchet (re-reviews may not raise fresh demands — see the verifier
|
|
10
|
+
* prompt), or goals become unfinishable.
|
|
11
|
+
*/
|
|
12
|
+
export type GoalKind = 'trading' | 'research' | 'general';
|
|
13
|
+
export type GoalStatus = 'active' | 'verifying' | 'paused' | 'blocked' | 'completed' | 'abandoned';
|
|
14
|
+
export interface GoalBudget {
|
|
15
|
+
/** Ceiling captured from --max-spend at creation (undefined = uncapped). */
|
|
16
|
+
maxUsd?: number;
|
|
17
|
+
/** Cumulative USD spent on this goal across sessions. */
|
|
18
|
+
spentUsd: number;
|
|
19
|
+
}
|
|
20
|
+
export interface GoalRoundRecord {
|
|
21
|
+
round: number;
|
|
22
|
+
refuted: boolean;
|
|
23
|
+
gaps: string[];
|
|
24
|
+
at: number;
|
|
25
|
+
}
|
|
26
|
+
export interface GoalState {
|
|
27
|
+
id: string;
|
|
28
|
+
objective: string;
|
|
29
|
+
kind: GoalKind;
|
|
30
|
+
status: GoalStatus;
|
|
31
|
+
createdAt: number;
|
|
32
|
+
updatedAt: number;
|
|
33
|
+
/** Verification rounds run so far. */
|
|
34
|
+
rounds: GoalRoundRecord[];
|
|
35
|
+
/** Latest verifier gaps, inlined into the next continuation directive. */
|
|
36
|
+
verifierGaps: string[];
|
|
37
|
+
/** One structural recommendation from the strategist, if it ran. */
|
|
38
|
+
strategistNote?: string;
|
|
39
|
+
/** Implementer turns consumed (continuation bound). */
|
|
40
|
+
turnsUsed: number;
|
|
41
|
+
budget: GoalBudget;
|
|
42
|
+
blockedReason?: string;
|
|
43
|
+
/** Closing user-facing summary, once completed. */
|
|
44
|
+
summary?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface VerifierVerdict {
|
|
47
|
+
refuted: boolean;
|
|
48
|
+
/** Concrete, actionable gaps (empty when not refuted). */
|
|
49
|
+
findings: string[];
|
|
50
|
+
confidence: 'low' | 'medium' | 'high';
|
|
51
|
+
/**
|
|
52
|
+
* none — implementer-fixable, iterate
|
|
53
|
+
* contradiction — the objective precludes itself; user must decide
|
|
54
|
+
* unverifiable — the needed evidence cannot exist here; user must decide
|
|
55
|
+
*/
|
|
56
|
+
blocking: 'none' | 'contradiction' | 'unverifiable';
|
|
57
|
+
}
|
|
58
|
+
export declare const GOAL_MAX_ROUNDS_DEFAULT = 5;
|
|
59
|
+
export declare const GOAL_MAX_TURNS_DEFAULT = 25;
|
|
60
|
+
export declare const GOAL_VERIFIERS_DEFAULT = 3;
|
|
61
|
+
export declare function goalMaxRounds(): number;
|
|
62
|
+
export declare function goalMaxTurns(): number;
|
|
63
|
+
export declare function goalVerifierCount(): number;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal engine — cross-turn autonomous objectives.
|
|
3
|
+
*
|
|
4
|
+
* A goal freezes an objective into a plan (outcomes, not implementation),
|
|
5
|
+
* steers the main model with per-turn directives, and gates every
|
|
6
|
+
* completion claim behind an adversarial verifier panel that defaults to
|
|
7
|
+
* refuting. The architecture is deliberately defensive: plausible-but-
|
|
8
|
+
* incomplete work must not survive verification, and verification must not
|
|
9
|
+
* ratchet (re-reviews may not raise fresh demands — see the verifier
|
|
10
|
+
* prompt), or goals become unfinishable.
|
|
11
|
+
*/
|
|
12
|
+
export const GOAL_MAX_ROUNDS_DEFAULT = 5;
|
|
13
|
+
export const GOAL_MAX_TURNS_DEFAULT = 25;
|
|
14
|
+
export const GOAL_VERIFIERS_DEFAULT = 3;
|
|
15
|
+
export function goalMaxRounds() {
|
|
16
|
+
const n = Number(process.env.FRANKLIN_GOAL_MAX_ROUNDS);
|
|
17
|
+
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : GOAL_MAX_ROUNDS_DEFAULT;
|
|
18
|
+
}
|
|
19
|
+
export function goalMaxTurns() {
|
|
20
|
+
const n = Number(process.env.FRANKLIN_GOAL_MAX_TURNS);
|
|
21
|
+
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : GOAL_MAX_TURNS_DEFAULT;
|
|
22
|
+
}
|
|
23
|
+
export function goalVerifierCount() {
|
|
24
|
+
const n = Number(process.env.FRANKLIN_GOAL_VERIFIERS);
|
|
25
|
+
return Number.isFinite(n) && n >= 1 ? Math.min(5, Math.floor(n)) : GOAL_VERIFIERS_DEFAULT;
|
|
26
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook discovery and validation.
|
|
3
|
+
*
|
|
4
|
+
* Sources, in load order:
|
|
5
|
+
* 1. ~/.blockrun/hooks/*.json — user scope, always trusted
|
|
6
|
+
* 2. <project>/.franklin/hooks/*.json — project scope, loads ONLY when the
|
|
7
|
+
* project dir is trusted (same trusted-projects.json marker that gates
|
|
8
|
+
* project .mcp.json — one mental model for "this repo may run code").
|
|
9
|
+
*
|
|
10
|
+
* Malformed files or entries warn once and are skipped; unknown event names
|
|
11
|
+
* are ignored so config files can carry events from other harnesses or
|
|
12
|
+
* future versions without breaking.
|
|
13
|
+
*/
|
|
14
|
+
import { type LoadedHook } from './types.js';
|
|
15
|
+
export declare function userHooksDir(): string;
|
|
16
|
+
export declare function projectHooksDir(workDir: string): string;
|
|
17
|
+
/** Same trust marker that gates project .mcp.json (see src/mcp/config.ts). */
|
|
18
|
+
export declare function isProjectTrusted(workDir: string): boolean;
|
|
19
|
+
export declare function loadHooks(workDir: string): LoadedHook[];
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook discovery and validation.
|
|
3
|
+
*
|
|
4
|
+
* Sources, in load order:
|
|
5
|
+
* 1. ~/.blockrun/hooks/*.json — user scope, always trusted
|
|
6
|
+
* 2. <project>/.franklin/hooks/*.json — project scope, loads ONLY when the
|
|
7
|
+
* project dir is trusted (same trusted-projects.json marker that gates
|
|
8
|
+
* project .mcp.json — one mental model for "this repo may run code").
|
|
9
|
+
*
|
|
10
|
+
* Malformed files or entries warn once and are skipped; unknown event names
|
|
11
|
+
* are ignored so config files can carry events from other harnesses or
|
|
12
|
+
* future versions without breaking.
|
|
13
|
+
*/
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { BLOCKRUN_DIR } from '../config.js';
|
|
17
|
+
import { logger } from '../logger.js';
|
|
18
|
+
import { HOOK_EVENTS, LIFECYCLE_EVENTS, } from './types.js';
|
|
19
|
+
export function userHooksDir() {
|
|
20
|
+
return path.join(BLOCKRUN_DIR, 'hooks');
|
|
21
|
+
}
|
|
22
|
+
export function projectHooksDir(workDir) {
|
|
23
|
+
return path.join(workDir, '.franklin', 'hooks');
|
|
24
|
+
}
|
|
25
|
+
/** Same trust marker that gates project .mcp.json (see src/mcp/config.ts). */
|
|
26
|
+
export function isProjectTrusted(workDir) {
|
|
27
|
+
const trustMarker = path.join(BLOCKRUN_DIR, 'trusted-projects.json');
|
|
28
|
+
try {
|
|
29
|
+
if (fs.existsSync(trustMarker)) {
|
|
30
|
+
const trustedDirs = JSON.parse(fs.readFileSync(trustMarker, 'utf-8'));
|
|
31
|
+
return Array.isArray(trustedDirs) && trustedDirs.includes(workDir);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
/* unreadable marker = not trusted */
|
|
36
|
+
}
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
export function loadHooks(workDir) {
|
|
40
|
+
const loaded = [];
|
|
41
|
+
collectDir(userHooksDir(), 'user', loaded);
|
|
42
|
+
const projDir = projectHooksDir(workDir);
|
|
43
|
+
if (fs.existsSync(projDir)) {
|
|
44
|
+
if (isProjectTrusted(workDir)) {
|
|
45
|
+
collectDir(projDir, 'project', loaded);
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
logger.info(`[hooks] Skipping untrusted project hooks in ${projDir} — run /mcp trust to enable`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return loaded;
|
|
52
|
+
}
|
|
53
|
+
function collectDir(dir, scope, out) {
|
|
54
|
+
let entries;
|
|
55
|
+
try {
|
|
56
|
+
entries = fs.readdirSync(dir).filter(f => f.endsWith('.json')).sort();
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return; // dir missing — nothing to load
|
|
60
|
+
}
|
|
61
|
+
for (const file of entries) {
|
|
62
|
+
const sourceFile = path.join(dir, file);
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = JSON.parse(fs.readFileSync(sourceFile, 'utf-8'));
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
logger.warn(`[hooks] Skipping malformed hook file ${sourceFile}: ${err.message}`);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (!parsed || typeof parsed.hooks !== 'object' || parsed.hooks === null) {
|
|
72
|
+
logger.warn(`[hooks] Skipping ${sourceFile}: missing top-level "hooks" object`);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
for (const [eventName, matchers] of Object.entries(parsed.hooks)) {
|
|
76
|
+
if (!HOOK_EVENTS.has(eventName))
|
|
77
|
+
continue; // foreign/future event — ignore
|
|
78
|
+
const event = eventName;
|
|
79
|
+
if (!Array.isArray(matchers)) {
|
|
80
|
+
logger.warn(`[hooks] ${sourceFile}: "${eventName}" must be an array — skipped`);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
for (const entry of matchers) {
|
|
84
|
+
collectMatcherEntry(entry, event, sourceFile, scope, out);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function collectMatcherEntry(entry, event, sourceFile, scope, out) {
|
|
90
|
+
if (!entry || !Array.isArray(entry.hooks)) {
|
|
91
|
+
logger.warn(`[hooks] ${sourceFile}: entry for ${event} lacks a "hooks" array — skipped`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
let matcher;
|
|
95
|
+
if (typeof entry.matcher === 'string' && entry.matcher.length > 0) {
|
|
96
|
+
if (LIFECYCLE_EVENTS.has(event)) {
|
|
97
|
+
logger.warn(`[hooks] ${sourceFile}: ${event} carries no tool context — matcher "${entry.matcher}" rejected, entry skipped`);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
matcher = new RegExp(entry.matcher);
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
logger.warn(`[hooks] ${sourceFile}: invalid matcher regex "${entry.matcher}" for ${event}: ${err.message} — entry skipped`);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (const handler of entry.hooks) {
|
|
109
|
+
if (!handler || handler.type !== 'command' || typeof handler.command !== 'string' || !handler.command.trim()) {
|
|
110
|
+
logger.warn(`[hooks] ${sourceFile}: handler for ${event} must be {type:"command", command:"..."} — skipped`);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
out.push({ event, matcher, handler, sourceFile, scope });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HookEngine — dispatches lifecycle events to loaded hooks.
|
|
3
|
+
*
|
|
4
|
+
* Decision semantics (blocking events only):
|
|
5
|
+
* exit 0 → allow
|
|
6
|
+
* exit 2 → deny
|
|
7
|
+
* stdout {"decision":"deny",...} → deny, regardless of exit code
|
|
8
|
+
* timeout / crash / spawn failure → allow (fail-open) + logged
|
|
9
|
+
*
|
|
10
|
+
* Handlers run sequentially per event; the first deny short-circuits.
|
|
11
|
+
* Non-blocking events run every matching handler and always resolve allow.
|
|
12
|
+
*/
|
|
13
|
+
import { type HookDecision, type HookEvent, type HookInput, type LoadedHook } from './types.js';
|
|
14
|
+
export declare class HookEngine {
|
|
15
|
+
private hooks;
|
|
16
|
+
private byEvent;
|
|
17
|
+
/** Hooks are read once at engine construction (session start). */
|
|
18
|
+
constructor(opts: {
|
|
19
|
+
workDir: string;
|
|
20
|
+
hooks?: LoadedHook[];
|
|
21
|
+
});
|
|
22
|
+
/** Fast path so call sites skip envelope construction when nothing listens. */
|
|
23
|
+
hasHooks(event: HookEvent): boolean;
|
|
24
|
+
listHooks(): ReadonlyArray<LoadedHook>;
|
|
25
|
+
/**
|
|
26
|
+
* Run every hook registered for `event` whose matcher accepts the tool name.
|
|
27
|
+
* Returns the aggregate decision; always 'allow' for non-blocking events.
|
|
28
|
+
*/
|
|
29
|
+
dispatch(event: HookEvent, input: HookInput): Promise<HookDecision>;
|
|
30
|
+
private runHandler;
|
|
31
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HookEngine — dispatches lifecycle events to loaded hooks.
|
|
3
|
+
*
|
|
4
|
+
* Decision semantics (blocking events only):
|
|
5
|
+
* exit 0 → allow
|
|
6
|
+
* exit 2 → deny
|
|
7
|
+
* stdout {"decision":"deny",...} → deny, regardless of exit code
|
|
8
|
+
* timeout / crash / spawn failure → allow (fail-open) + logged
|
|
9
|
+
*
|
|
10
|
+
* Handlers run sequentially per event; the first deny short-circuits.
|
|
11
|
+
* Non-blocking events run every matching handler and always resolve allow.
|
|
12
|
+
*/
|
|
13
|
+
import { execFile } from 'node:child_process';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import { logger } from '../logger.js';
|
|
17
|
+
import { appendApprovalRecord } from '../audit/approvals.js';
|
|
18
|
+
import { loadHooks } from './loader.js';
|
|
19
|
+
import { BLOCKING_EVENTS, } from './types.js';
|
|
20
|
+
const DEFAULT_TIMEOUT_SECS = 5;
|
|
21
|
+
const MAX_STDOUT_BYTES = 64 * 1024;
|
|
22
|
+
export class HookEngine {
|
|
23
|
+
hooks;
|
|
24
|
+
byEvent = new Map();
|
|
25
|
+
/** Hooks are read once at engine construction (session start). */
|
|
26
|
+
constructor(opts) {
|
|
27
|
+
this.hooks = opts.hooks ?? loadHooks(opts.workDir);
|
|
28
|
+
for (const hook of this.hooks) {
|
|
29
|
+
const list = this.byEvent.get(hook.event) ?? [];
|
|
30
|
+
list.push(hook);
|
|
31
|
+
this.byEvent.set(hook.event, list);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Fast path so call sites skip envelope construction when nothing listens. */
|
|
35
|
+
hasHooks(event) {
|
|
36
|
+
return (this.byEvent.get(event)?.length ?? 0) > 0;
|
|
37
|
+
}
|
|
38
|
+
listHooks() {
|
|
39
|
+
return this.hooks;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Run every hook registered for `event` whose matcher accepts the tool name.
|
|
43
|
+
* Returns the aggregate decision; always 'allow' for non-blocking events.
|
|
44
|
+
*/
|
|
45
|
+
async dispatch(event, input) {
|
|
46
|
+
const candidates = this.byEvent.get(event);
|
|
47
|
+
if (!candidates || candidates.length === 0)
|
|
48
|
+
return { decision: 'allow' };
|
|
49
|
+
const toolName = input.toolName ?? input.spend?.tool ?? '';
|
|
50
|
+
const blocking = BLOCKING_EVENTS.has(event);
|
|
51
|
+
for (const hook of candidates) {
|
|
52
|
+
if (hook.matcher && !hook.matcher.test(toolName))
|
|
53
|
+
continue;
|
|
54
|
+
const result = await this.runHandler(hook, input);
|
|
55
|
+
if (blocking && result.decision === 'deny') {
|
|
56
|
+
appendApprovalRecord({
|
|
57
|
+
ts: Date.now(),
|
|
58
|
+
sessionId: input.sessionId,
|
|
59
|
+
kind: 'hook',
|
|
60
|
+
subject: toolName || event,
|
|
61
|
+
decision: 'deny',
|
|
62
|
+
by: `hook:${path.basename(hook.sourceFile)}`,
|
|
63
|
+
reason: result.reason,
|
|
64
|
+
});
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return { decision: 'allow' };
|
|
69
|
+
}
|
|
70
|
+
runHandler(hook, input) {
|
|
71
|
+
const timeoutMs = Math.max(1, hook.handler.timeout ?? DEFAULT_TIMEOUT_SECS) * 1000;
|
|
72
|
+
// A bare relative path resolves against the hook file's directory so hook
|
|
73
|
+
// bundles are relocatable; anything with shell syntax runs as written.
|
|
74
|
+
let command = hook.handler.command;
|
|
75
|
+
const looksLikeBarePath = !/[\s;&|<>$`]/.test(command);
|
|
76
|
+
if (looksLikeBarePath && !path.isAbsolute(command)) {
|
|
77
|
+
const resolved = path.resolve(path.dirname(hook.sourceFile), command);
|
|
78
|
+
if (fs.existsSync(resolved))
|
|
79
|
+
command = resolved;
|
|
80
|
+
}
|
|
81
|
+
return new Promise(resolve => {
|
|
82
|
+
const child = execFile('/bin/sh', ['-c', command], {
|
|
83
|
+
timeout: timeoutMs,
|
|
84
|
+
maxBuffer: MAX_STDOUT_BYTES,
|
|
85
|
+
env: {
|
|
86
|
+
...process.env,
|
|
87
|
+
...hook.handler.env,
|
|
88
|
+
// Reserved vars always win over handler env.
|
|
89
|
+
FRANKLIN_HOOK_EVENT: input.hookEventName,
|
|
90
|
+
FRANKLIN_SESSION_ID: input.sessionId,
|
|
91
|
+
FRANKLIN_CWD: input.cwd,
|
|
92
|
+
},
|
|
93
|
+
}, (err, stdout) => {
|
|
94
|
+
// Explicit stdout deny wins regardless of exit code.
|
|
95
|
+
const parsed = parseDecision(stdout);
|
|
96
|
+
if (parsed?.decision === 'deny') {
|
|
97
|
+
resolve({ decision: 'deny', reason: parsed.reason || `denied by ${path.basename(hook.sourceFile)}` });
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (!err) {
|
|
101
|
+
resolve({ decision: 'allow' });
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
// child_process sets `code` to the numeric exit status on non-zero
|
|
105
|
+
// exit (typed as string|number across Node versions — normalize).
|
|
106
|
+
const code = err.code;
|
|
107
|
+
if (code !== undefined && Number(code) === 2) {
|
|
108
|
+
resolve({ decision: 'deny', reason: `denied by ${path.basename(hook.sourceFile)} (exit 2)` });
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
// Timeout, crash, missing binary, other exit codes: fail open.
|
|
112
|
+
logger.warn(`[hooks] ${path.basename(hook.sourceFile)} ${input.hookEventName} handler failed open: ${err.message.slice(0, 160)}`);
|
|
113
|
+
resolve({ decision: 'allow' });
|
|
114
|
+
});
|
|
115
|
+
try {
|
|
116
|
+
child.stdin?.write(JSON.stringify(input));
|
|
117
|
+
child.stdin?.end();
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
// EPIPE from a handler that never reads stdin — fine, decision comes
|
|
121
|
+
// from its exit code / stdout.
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function parseDecision(stdout) {
|
|
127
|
+
const text = String(stdout ?? '').trim();
|
|
128
|
+
if (!text)
|
|
129
|
+
return null;
|
|
130
|
+
// Handlers may print human noise before the JSON — scan lines from the end.
|
|
131
|
+
const lines = text.split('\n');
|
|
132
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
133
|
+
const line = lines[i].trim();
|
|
134
|
+
if (!line.startsWith('{'))
|
|
135
|
+
continue;
|
|
136
|
+
try {
|
|
137
|
+
const obj = JSON.parse(line);
|
|
138
|
+
if (obj && (obj.decision === 'deny' || obj.decision === 'allow')) {
|
|
139
|
+
return { decision: obj.decision, reason: typeof obj.reason === 'string' ? obj.reason : undefined };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
/* not JSON — keep scanning */
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lifecycle hooks — user-authored guardrails and automations.
|
|
3
|
+
*
|
|
4
|
+
* Hooks are external commands the harness runs at fixed lifecycle points.
|
|
5
|
+
* They receive a JSON envelope on stdin and can veto the action (blocking
|
|
6
|
+
* events only) by exiting 2 or printing {"decision":"deny"} on stdout.
|
|
7
|
+
*
|
|
8
|
+
* Safety model: hooks are a convenience layer, not a security boundary.
|
|
9
|
+
* A hook that crashes, times out, or is missing FAILS OPEN — work proceeds
|
|
10
|
+
* and the failure is logged. Only an explicit deny blocks. This keeps a
|
|
11
|
+
* buggy hook from bricking the agent while still letting deliberate policy
|
|
12
|
+
* (spend caps, token blacklists) intercept actions.
|
|
13
|
+
*/
|
|
14
|
+
export type HookEvent = 'SessionStart' | 'UserPromptSubmit' | 'PreToolUse' | 'PostToolUse' | 'Stop' | 'SessionEnd' | 'PreSpend' | 'PostSpend';
|
|
15
|
+
/** Events whose handlers can veto the action. All others are notify-only. */
|
|
16
|
+
export declare const BLOCKING_EVENTS: ReadonlySet<HookEvent>;
|
|
17
|
+
/** Events that carry no tool context — a matcher on these is a config error. */
|
|
18
|
+
export declare const LIFECYCLE_EVENTS: ReadonlySet<HookEvent>;
|
|
19
|
+
export declare const HOOK_EVENTS: ReadonlySet<string>;
|
|
20
|
+
export interface HookHandlerDef {
|
|
21
|
+
type: 'command';
|
|
22
|
+
/** Shell command. A bare relative path resolves against the hook file's dir. */
|
|
23
|
+
command: string;
|
|
24
|
+
/** Seconds before the handler is killed and treated as allow. Default 5. */
|
|
25
|
+
timeout?: number;
|
|
26
|
+
env?: Record<string, string>;
|
|
27
|
+
}
|
|
28
|
+
export interface HookMatcherDef {
|
|
29
|
+
/** Regex tested against the tool name. Absent/empty = match all. */
|
|
30
|
+
matcher?: string;
|
|
31
|
+
hooks: HookHandlerDef[];
|
|
32
|
+
}
|
|
33
|
+
/** On-disk file shape: { "hooks": { "<Event>": [ {matcher, hooks:[...]} ] } } */
|
|
34
|
+
export interface HookConfigFile {
|
|
35
|
+
hooks: Partial<Record<string, HookMatcherDef[]>>;
|
|
36
|
+
}
|
|
37
|
+
/** Loaded + validated handler with provenance for logs and the /hooks UI. */
|
|
38
|
+
export interface LoadedHook {
|
|
39
|
+
event: HookEvent;
|
|
40
|
+
matcher?: RegExp;
|
|
41
|
+
handler: HookHandlerDef;
|
|
42
|
+
/** Absolute path of the JSON file this hook came from. */
|
|
43
|
+
sourceFile: string;
|
|
44
|
+
scope: 'user' | 'project';
|
|
45
|
+
}
|
|
46
|
+
/** stdin envelope delivered to every handler. */
|
|
47
|
+
export interface HookInput {
|
|
48
|
+
hookEventName: HookEvent;
|
|
49
|
+
sessionId: string;
|
|
50
|
+
cwd: string;
|
|
51
|
+
timestamp: string;
|
|
52
|
+
toolName?: string;
|
|
53
|
+
toolInput?: Record<string, unknown>;
|
|
54
|
+
/** Present on PreSpend/PostSpend. estimatedUsd is null when unknown. */
|
|
55
|
+
spend?: {
|
|
56
|
+
estimatedUsd: number | null;
|
|
57
|
+
tool: string;
|
|
58
|
+
params: Record<string, unknown>;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export interface HookDecision {
|
|
62
|
+
decision: 'allow' | 'deny';
|
|
63
|
+
reason?: string;
|
|
64
|
+
}
|