@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.
Files changed (78) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/approvals.d.ts +47 -0
  3. package/dist/agent/approvals.js +66 -0
  4. package/dist/agent/commands.js +230 -7
  5. package/dist/agent/input-queue.d.ts +26 -0
  6. package/dist/agent/input-queue.js +65 -0
  7. package/dist/agent/loop.js +196 -3
  8. package/dist/agent/streaming-executor.d.ts +4 -0
  9. package/dist/agent/streaming-executor.js +52 -0
  10. package/dist/agent/tool-guard.d.ts +7 -0
  11. package/dist/agent/tool-guard.js +21 -0
  12. package/dist/agent/types.d.ts +26 -0
  13. package/dist/audit/approvals.d.ts +20 -0
  14. package/dist/audit/approvals.js +21 -0
  15. package/dist/commands/start.d.ts +10 -1
  16. package/dist/commands/start.js +53 -1
  17. package/dist/events/types.d.ts +38 -1
  18. package/dist/goal/engine.d.ts +39 -0
  19. package/dist/goal/engine.js +182 -0
  20. package/dist/goal/prompts.d.ts +16 -0
  21. package/dist/goal/prompts.js +206 -0
  22. package/dist/goal/runtime.d.ts +20 -0
  23. package/dist/goal/runtime.js +110 -0
  24. package/dist/goal/store.d.ts +22 -0
  25. package/dist/goal/store.js +79 -0
  26. package/dist/goal/types.d.ts +63 -0
  27. package/dist/goal/types.js +26 -0
  28. package/dist/hooks/loader.d.ts +19 -0
  29. package/dist/hooks/loader.js +115 -0
  30. package/dist/hooks/runner.d.ts +31 -0
  31. package/dist/hooks/runner.js +147 -0
  32. package/dist/hooks/types.d.ts +64 -0
  33. package/dist/hooks/types.js +35 -0
  34. package/dist/index.js +5 -1
  35. package/dist/memory/capture.d.ts +40 -0
  36. package/dist/memory/capture.js +95 -0
  37. package/dist/memory/dream.d.ts +24 -0
  38. package/dist/memory/dream.js +147 -0
  39. package/dist/memory/indexer.d.ts +29 -0
  40. package/dist/memory/indexer.js +144 -0
  41. package/dist/memory/store.d.ts +50 -0
  42. package/dist/memory/store.js +163 -0
  43. package/dist/monitors/registry.d.ts +42 -0
  44. package/dist/monitors/registry.js +104 -0
  45. package/dist/panel/html.js +299 -0
  46. package/dist/panel/server.js +41 -0
  47. package/dist/scheduler/service.d.ts +24 -0
  48. package/dist/scheduler/service.js +44 -0
  49. package/dist/scheduler/store.d.ts +26 -0
  50. package/dist/scheduler/store.js +116 -0
  51. package/dist/scheduler/types.d.ts +36 -0
  52. package/dist/scheduler/types.js +31 -0
  53. package/dist/serve/agent-host.d.ts +63 -0
  54. package/dist/serve/agent-host.js +270 -0
  55. package/dist/serve/server.js +131 -2
  56. package/dist/session/live-registry.d.ts +32 -0
  57. package/dist/session/live-registry.js +83 -0
  58. package/dist/session/search.d.ts +6 -0
  59. package/dist/session/search.js +3 -3
  60. package/dist/session/storage.d.ts +6 -0
  61. package/dist/session/storage.js +6 -0
  62. package/dist/tools/goal.d.ts +7 -0
  63. package/dist/tools/goal.js +29 -0
  64. package/dist/tools/index.js +11 -0
  65. package/dist/tools/memory.js +14 -4
  66. package/dist/tools/monitor.d.ts +11 -0
  67. package/dist/tools/monitor.js +96 -0
  68. package/dist/tools/scheduler.d.ts +12 -0
  69. package/dist/tools/scheduler.js +79 -0
  70. package/dist/tools/spend-tools.d.ts +33 -0
  71. package/dist/tools/spend-tools.js +114 -0
  72. package/dist/tools/tool-categories.js +7 -0
  73. package/dist/tools/trade-plan.d.ts +11 -0
  74. package/dist/tools/trade-plan.js +137 -0
  75. package/dist/tools/trading-execute.js +24 -0
  76. package/dist/trading/trade-plan.d.ts +75 -0
  77. package/dist/trading/trade-plan.js +290 -0
  78. package/package.json +2 -2
@@ -12,6 +12,19 @@ import { reduceTokens } from './reduce.js';
12
12
  import { redactSecrets, stashSecretsToEnv, formatRedactionWarning } from './secret-redact.js';
13
13
  import { PermissionManager } from './permissions.js';
14
14
  import { StreamingExecutor } from './streaming-executor.js';
15
+ import { HookEngine } from '../hooks/runner.js';
16
+ import { createInputMultiplexer } from './input-queue.js';
17
+ import { startSchedulerService } from '../scheduler/service.js';
18
+ import { setSchedulerSessionId } from '../scheduler/store.js';
19
+ import { sweepMonitors } from '../monitors/registry.js';
20
+ import { setTradePlanSessionId } from '../trading/trade-plan.js';
21
+ import { getActiveGoal, setActiveGoal, loadGoal, loadPlan, updateActiveGoal } from '../goal/store.js';
22
+ import { searchMemory, formatMemoryContext } from '../memory/indexer.js';
23
+ import { writeSessionMetadataSummary } from '../memory/capture.js';
24
+ import { setGoalEngineDeps } from '../goal/runtime.js';
25
+ import { continuationDirective } from '../goal/prompts.js';
26
+ import { mineNextStep } from '../goal/engine.js';
27
+ import { goalMaxTurns } from '../goal/types.js';
15
28
  import { optimizeHistory, CAPPED_MAX_TOKENS, ESCALATED_MAX_TOKENS, getMaxOutputTokens } from './optimize.js';
16
29
  import { classifyAgentError } from './error-classifier.js';
17
30
  import { SessionToolGuard } from './tool-guard.js';
@@ -25,7 +38,8 @@ import { appendAudit, extractLastUserPrompt } from '../stats/audit.js';
25
38
  import { logger, setDebugMode } from '../logger.js';
26
39
  import { runDataHygiene } from '../storage/hygiene.js';
27
40
  import { isTestFixtureModel } from '../stats/test-fixture.js';
28
- import { setSessionPersistenceDisabled } from '../session/storage.js';
41
+ import { setSessionPersistenceDisabled, isSessionPersistenceDisabled } from '../session/storage.js';
42
+ import { writeLiveAgent } from '../session/live-registry.js';
29
43
  import { estimateCost, OPUS_PRICING } from '../pricing.js';
30
44
  import { maybeMidSessionExtract } from '../learnings/extractor.js';
31
45
  import { extractMentions, buildEntityContext, loadEntities } from '../brain/store.js';
@@ -539,6 +553,42 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
539
553
  const maxTurns = config.maxTurns ?? 15;
540
554
  const workDir = config.workingDir ?? process.cwd();
541
555
  const permissions = new PermissionManager(config.permissionMode ?? 'default', config.permissionPromptFn);
556
+ // ── Lifecycle hooks ──
557
+ // User-authored guardrails (spend caps, blacklists, audit) loaded once per
558
+ // session. Built here so every driver (TUI, headless, serve, bots) gets
559
+ // them without per-driver wiring. FRANKLIN_HOOKS=0 disables entirely.
560
+ const hookEngine = process.env.FRANKLIN_HOOKS === '0' ? undefined : (config.hooks ?? new HookEngine({ workDir }));
561
+ let schedulerService;
562
+ const fireLifecycleHook = (event) => {
563
+ if (event === 'SessionEnd') {
564
+ schedulerService?.stop();
565
+ schedulerService = undefined;
566
+ publishLiveState('completed');
567
+ // Zero-cost memory: a metadata-only session log (topics + counts, no
568
+ // LLM call). Trivial sessions are skipped inside.
569
+ try {
570
+ writeSessionMetadataSummary({ workDir, sessionId, history });
571
+ }
572
+ catch { /* memory is best-effort */ }
573
+ }
574
+ if (!hookEngine?.hasHooks(event))
575
+ return;
576
+ void hookEngine
577
+ .dispatch(event, {
578
+ hookEventName: event,
579
+ sessionId,
580
+ cwd: workDir,
581
+ timestamp: new Date().toISOString(),
582
+ })
583
+ .catch(() => { });
584
+ };
585
+ // ── Input multiplexer ──
586
+ // Harness-injected inputs (scheduler firings, goal continuations) merge
587
+ // with the driver's input source and win the race at turn boundaries —
588
+ // an idle interactive session still fires its scheduled prompts without
589
+ // waiting for the user to press enter. The user's pending input is never
590
+ // dropped (delivered at the next boundary).
591
+ const inputMux = createInputMultiplexer(getUserInput);
542
592
  const history = [];
543
593
  let lastUserInput = ''; // For /retry
544
594
  config.baseModel = config.model; // User's intended model — /model command updates this
@@ -564,6 +614,61 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
564
614
  // Session persistence — reuse existing session ID when resuming, else create new
565
615
  const sessionId = config.resumeSessionId || createSessionId();
566
616
  config.onSessionStart?.(sessionId);
617
+ fireLifecycleHook('SessionStart');
618
+ // Durable prompt scheduler: catch up missed firings now, then tick every
619
+ // 30s for the life of the session. Firings arrive via the input mux.
620
+ setSchedulerSessionId(sessionId);
621
+ setTradePlanSessionId(sessionId);
622
+ // Goal engine: fresh slot per session; deps let UpdateGoal reach the model.
623
+ setActiveGoal(null);
624
+ setGoalEngineDeps({
625
+ client,
626
+ getModel: () => config.model,
627
+ capabilities: config.capabilities,
628
+ });
629
+ if (config.resumeSessionId) {
630
+ const resumedMeta = loadSessionMeta(config.resumeSessionId);
631
+ if (resumedMeta?.goalId) {
632
+ const resumedGoal = loadGoal(resumedMeta.goalId);
633
+ if (resumedGoal && resumedGoal.status !== 'completed' && resumedGoal.status !== 'abandoned') {
634
+ setActiveGoal(resumedGoal);
635
+ onEvent({ kind: 'text_delta', text: `*[goal] resumed: ${resumedGoal.objective.slice(0, 80)} (${resumedGoal.status})*\n` });
636
+ }
637
+ }
638
+ }
639
+ let goalSpendSnapshot = getLiveSpendUsd();
640
+ // Document-memory injection state — see the per-turn block below.
641
+ let memoryInjectionPending = true;
642
+ let historyLenAtTurnEnd = 0;
643
+ // ── Live-agent registry (fleet visibility) ──
644
+ // CLI sessions publish their liveness so the panel's Agents tab can show
645
+ // them (read-only — cross-process control is out of scope). Serve-hosted
646
+ // agents publish through AgentHost instead. Suppressed alongside session
647
+ // persistence so test-fixture runs never touch the registry.
648
+ const liveRegistryStartedAt = Date.now();
649
+ const publishLiveState = (state) => {
650
+ if (isSessionPersistenceDisabled() || config.sessionChannel?.startsWith('serve'))
651
+ return;
652
+ try {
653
+ writeLiveAgent({
654
+ sessionId,
655
+ pid: process.pid,
656
+ state,
657
+ label: config.sessionChannel || `cli · ${workDir.split('/').pop() || 'session'}`,
658
+ model: config.model,
659
+ host: 'cli',
660
+ startedAt: liveRegistryStartedAt,
661
+ updatedAt: Date.now(),
662
+ });
663
+ }
664
+ catch { /* registry is best-effort */ }
665
+ };
666
+ publishLiveState('idle');
667
+ schedulerService = startSchedulerService({
668
+ sessionId,
669
+ enqueue: (text) => inputMux.enqueue(text),
670
+ notify: (line) => onEvent({ kind: 'text_delta', text: `*${line.trimEnd()}*\n` }),
671
+ });
567
672
  let turnCount = 0;
568
673
  // Resume: hydrate history from the saved JSONL transcript.
569
674
  // Sanitize to drop any orphaned tool_use / tool_result pairs from a crash.
@@ -611,7 +716,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
611
716
  // per-turn. Counts the *name* of each tool invocation only — no inputs,
612
717
  // outputs, or paths. Fed into opt-in telemetry at session end.
613
718
  const sessionToolCounts = new Map();
614
- const toolGuard = new SessionToolGuard();
719
+ const toolGuard = new SessionToolGuard(sessionId);
615
720
  // Recovers tool calls that the model leaked into the text or thinking
616
721
  // channels instead of the structured tool_use channel. See
617
722
  // src/agent/repair/scavenge.ts for the failure modes — most common on
@@ -678,7 +783,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
678
783
  process.once('SIGINT', exitFlush);
679
784
  process.once('SIGTERM', exitFlush);
680
785
  while (true) {
681
- let input = await getUserInput();
786
+ let input = await inputMux.getUserInput();
682
787
  if (input === null)
683
788
  break; // User wants to exit
684
789
  if (input === '')
@@ -727,6 +832,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
727
832
  input = redactedText;
728
833
  }
729
834
  lastUserInput = input;
835
+ fireLifecycleHook('UserPromptSubmit');
730
836
  // ── Skill trigger auto-invoke ──
731
837
  // Match the user message against every skill's `triggers:` list. Strong
732
838
  // matches surface as a soft hint appended to this turn's system prompt
@@ -747,6 +853,18 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
747
853
  }
748
854
  }
749
855
  catch { /* trigger matching is best-effort */ }
856
+ // ── Monitor sweep (turn boundary) ──
857
+ // Fresh lines from active monitors ride into this turn's user content
858
+ // as bracketed blocks. Appended AFTER lastUserInput capture so /retry
859
+ // replays the clean message, and after skill-trigger matching so
860
+ // monitor noise can't fire skills.
861
+ try {
862
+ const { blocks: monitorBlocks } = sweepMonitors();
863
+ if (monitorBlocks.length > 0) {
864
+ input = `${input}\n\n${monitorBlocks.join('\n\n')}`;
865
+ }
866
+ }
867
+ catch { /* monitors are best-effort */ }
750
868
  // Push the user's clean message; any harness-injected annotations
751
869
  // (pushback SYSTEM NOTE, prefetch context block) are applied AFTER
752
870
  // the turn analyzer runs so they get driven by model-decided flags
@@ -754,6 +872,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
754
872
  history.push({ role: 'user', content: input });
755
873
  turnCount++;
756
874
  toolGuard.startTurn();
875
+ publishLiveState('working');
757
876
  persistSessionMessage({ role: 'user', content: input });
758
877
  // ── Model recovery: try original model at the start of each new turn ──
759
878
  // If we fell back to a free model last turn due to a transient error, try original again.
@@ -764,6 +883,21 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
764
883
  config.onModelChange?.(baseModel, 'system');
765
884
  }
766
885
  turnFailedModels = new Set(); // Fresh slate for transient failures this turn
886
+ // ── Document-memory injection ──
887
+ // Injected on the FIRST turn of a session (recall what this workspace /
888
+ // wallet already knows) and re-injected after compaction shrinks history
889
+ // (compaction may have discarded recalled context). Detected by history
890
+ // length dropping between turns.
891
+ if (history.length < historyLenAtTurnEnd)
892
+ memoryInjectionPending = true;
893
+ let turnMemoryContext = '';
894
+ if (memoryInjectionPending) {
895
+ memoryInjectionPending = false;
896
+ try {
897
+ turnMemoryContext = formatMemoryContext(searchMemory(input, workDir, { limit: 6 }));
898
+ }
899
+ catch { /* memory is best-effort */ }
900
+ }
767
901
  // ── Brain auto-recall (computed once per user turn) ──
768
902
  // Scan the new user message plus the previous assistant reply (so
769
903
  // cross-turn references like "that company we discussed" still resolve)
@@ -1169,6 +1303,19 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1169
1303
  // ── Brain auto-recall (computed once per user turn above) ──
1170
1304
  if (turnBrainContext)
1171
1305
  systemParts.push(turnBrainContext);
1306
+ if (turnMemoryContext)
1307
+ systemParts.push(turnMemoryContext);
1308
+ // ── Goal continuation directive ──
1309
+ // While a goal is active, every turn carries the frozen plan, open
1310
+ // verification gaps, next checklist step, and task discipline. Spend
1311
+ // is bucketed (25/50/75/100% of budget) for prompt-cache stability.
1312
+ {
1313
+ const turnGoal = getActiveGoal();
1314
+ if (turnGoal && (turnGoal.status === 'active' || turnGoal.status === 'verifying')) {
1315
+ const planMd = loadPlan(turnGoal.id);
1316
+ systemParts.push(continuationDirective(turnGoal, planMd, mineNextStep(planMd)));
1317
+ }
1318
+ }
1172
1319
  const systemPrompt = systemParts.join('\n\n');
1173
1320
  const modelMaxOut = getMaxOutputTokens(config.model);
1174
1321
  let maxTokens = Math.min(maxTokensOverride ?? CAPPED_MAX_TOKENS, modelMaxOut);
@@ -1183,6 +1330,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1183
1330
  workingDir: workDir,
1184
1331
  abortSignal: abort.signal,
1185
1332
  onAskUser: config.onAskUser,
1333
+ onApproval: config.approvalPromptFn,
1186
1334
  parentContext: {
1187
1335
  goal: lastUserInput?.slice(0, 200),
1188
1336
  recentFiles: [...readFileCache].slice(-10),
@@ -1190,6 +1338,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1190
1338
  },
1191
1339
  permissions,
1192
1340
  guard: toolGuard,
1341
+ hooks: hookEngine,
1193
1342
  onStart: (id, name, preview) => onEvent({ kind: 'capability_start', id, name, preview }),
1194
1343
  onProgress: (id, text) => onEvent({ kind: 'capability_progress', id, text }),
1195
1344
  sessionId,
@@ -1516,6 +1665,12 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1516
1665
  }
1517
1666
  lastSessionActivity = Date.now();
1518
1667
  persistSessionMeta();
1668
+ // User interrupt pauses an active goal — Esc must always regain
1669
+ // control from an autonomous loop. /goal resume re-arms it.
1670
+ if (getActiveGoal()?.status === 'active') {
1671
+ updateActiveGoal({ status: 'paused', blockedReason: 'user interrupt' });
1672
+ onEvent({ kind: 'text_delta', text: '\n*[goal] paused by interrupt — /goal resume to continue*\n' });
1673
+ }
1519
1674
  onEvent({ kind: 'turn_done', reason: 'aborted' });
1520
1675
  break;
1521
1676
  }
@@ -1531,6 +1686,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1531
1686
  });
1532
1687
  persistSessionMeta();
1533
1688
  onEvent({ kind: 'turn_done', reason: 'budget' });
1689
+ fireLifecycleHook('SessionEnd');
1534
1690
  return history;
1535
1691
  }
1536
1692
  const errMsg = err.message || '';
@@ -1898,6 +2054,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1898
2054
  });
1899
2055
  persistSessionMeta();
1900
2056
  onEvent({ kind: 'turn_done', reason: 'budget' });
2057
+ fireLifecycleHook('SessionEnd');
1901
2058
  return history;
1902
2059
  }
1903
2060
  // ── Max output tokens recovery ──
@@ -2150,6 +2307,40 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
2150
2307
  if (endedWithQuestion(responseParts)) {
2151
2308
  onEvent({ kind: 'text_delta', text: '\n*▸ awaiting your reply (or type a new message)*\n' });
2152
2309
  }
2310
+ // ── Goal auto-continuation ──
2311
+ // An active goal re-engages the agent at the next turn boundary,
2312
+ // bounded by the goal turn cap and budget (plus the session-level
2313
+ // --max-spend the loop already enforces). A turn that ended with a
2314
+ // question to the user yields to the user instead.
2315
+ {
2316
+ const spendNow = getLiveSpendUsd();
2317
+ const goalPreSpend = getActiveGoal();
2318
+ if (goalPreSpend && spendNow > goalSpendSnapshot) {
2319
+ updateActiveGoal({
2320
+ budget: { ...goalPreSpend.budget, spentUsd: goalPreSpend.budget.spentUsd + (spendNow - goalSpendSnapshot) },
2321
+ });
2322
+ }
2323
+ goalSpendSnapshot = spendNow;
2324
+ const goal = getActiveGoal();
2325
+ if (goal && goal.status === 'active' && config.autoContinueGoals !== false && !endedWithQuestion(responseParts)) {
2326
+ if (goal.turnsUsed + 1 >= goalMaxTurns()) {
2327
+ updateActiveGoal({ status: 'blocked', blockedReason: `goal turn cap (${goalMaxTurns()}) reached` });
2328
+ onEvent({ kind: 'text_delta', text: `\n*[goal] paused: turn cap (${goalMaxTurns()}) reached — /goal resume to continue*\n` });
2329
+ }
2330
+ else if (goal.budget.maxUsd && goal.budget.spentUsd >= goal.budget.maxUsd) {
2331
+ updateActiveGoal({ status: 'blocked', blockedReason: 'goal budget exhausted' });
2332
+ onEvent({ kind: 'text_delta', text: '\n*[goal] paused: budget exhausted — /goal resume to continue*\n' });
2333
+ }
2334
+ else {
2335
+ updateActiveGoal({ turnsUsed: goal.turnsUsed + 1 });
2336
+ inputMux.enqueue('Continue working the active goal. Address open verification gaps first; when every acceptance ' +
2337
+ 'criterion is met, run the verification plan yourself and claim completion via UpdateGoal.');
2338
+ }
2339
+ }
2340
+ }
2341
+ historyLenAtTurnEnd = history.length;
2342
+ publishLiveState('idle');
2343
+ fireLifecycleHook('Stop');
2153
2344
  onEvent({ kind: 'turn_done', reason: 'completed' });
2154
2345
  break;
2155
2346
  }
@@ -2180,6 +2371,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
2180
2371
  });
2181
2372
  persistSessionMeta();
2182
2373
  onEvent({ kind: 'turn_done', reason: 'budget' });
2374
+ fireLifecycleHook('SessionEnd');
2183
2375
  return history;
2184
2376
  }
2185
2377
  }
@@ -2399,6 +2591,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
2399
2591
  onEvent({ kind: 'turn_done', reason: 'max_turns' });
2400
2592
  }
2401
2593
  }
2594
+ fireLifecycleHook('SessionEnd');
2402
2595
  return history;
2403
2596
  }
2404
2597
  // Cost estimation now uses shared pricing from src/pricing.ts
@@ -6,11 +6,13 @@
6
6
  import type { CapabilityHandler, CapabilityInvocation, CapabilityResult, ExecutionScope } from './types.js';
7
7
  import type { PermissionManager } from './permissions.js';
8
8
  import type { SessionToolGuard } from './tool-guard.js';
9
+ import type { HookEngine } from '../hooks/runner.js';
9
10
  export declare class StreamingExecutor {
10
11
  private handlers;
11
12
  private scope;
12
13
  private permissions?;
13
14
  private guard?;
15
+ private hooks?;
14
16
  private onStart;
15
17
  private onProgress?;
16
18
  private pending;
@@ -20,10 +22,12 @@ export declare class StreamingExecutor {
20
22
  scope: ExecutionScope;
21
23
  permissions?: PermissionManager;
22
24
  guard?: SessionToolGuard;
25
+ hooks?: HookEngine;
23
26
  onStart: (id: string, name: string, preview?: string) => void;
24
27
  onProgress?: (id: string, text: string) => void;
25
28
  sessionId?: string;
26
29
  });
30
+ private hookInput;
27
31
  /**
28
32
  * Called when a tool_use block is fully received from the stream.
29
33
  * If the tool is concurrent-safe, start executing immediately.
@@ -6,6 +6,7 @@
6
6
  import { mkdirSync, writeFileSync } from 'node:fs';
7
7
  import { join } from 'node:path';
8
8
  import { recordFailure } from '../stats/failures.js';
9
+ import { estimateSpendUsd, isSpendTool } from '../tools/spend-tools.js';
9
10
  import { BLOCKRUN_DIR } from '../config.js';
10
11
  import { logger } from '../logger.js';
11
12
  /** Persist a large tool result to disk and return a preview string. */
@@ -36,6 +37,7 @@ export class StreamingExecutor {
36
37
  scope;
37
38
  permissions;
38
39
  guard;
40
+ hooks;
39
41
  onStart;
40
42
  onProgress;
41
43
  pending = [];
@@ -45,10 +47,29 @@ export class StreamingExecutor {
45
47
  this.scope = opts.scope;
46
48
  this.permissions = opts.permissions;
47
49
  this.guard = opts.guard;
50
+ this.hooks = opts.hooks;
48
51
  this.onStart = opts.onStart;
49
52
  this.onProgress = opts.onProgress;
50
53
  this.sessionId = opts.sessionId || 'default';
51
54
  }
55
+ hookInput(invocation, event) {
56
+ const base = {
57
+ hookEventName: event,
58
+ sessionId: this.sessionId,
59
+ cwd: this.scope.workingDir,
60
+ timestamp: new Date().toISOString(),
61
+ toolName: invocation.name,
62
+ toolInput: invocation.input,
63
+ };
64
+ if (event === 'PreSpend' || event === 'PostSpend') {
65
+ base.spend = {
66
+ estimatedUsd: estimateSpendUsd(invocation.name, invocation.input),
67
+ tool: invocation.name,
68
+ params: invocation.input,
69
+ };
70
+ }
71
+ return base;
72
+ }
52
73
  /**
53
74
  * Called when a tool_use block is fully received from the stream.
54
75
  * If the tool is concurrent-safe, start executing immediately.
@@ -113,6 +134,18 @@ export class StreamingExecutor {
113
134
  }
114
135
  async executeWithPermissions(invocation, pendingCount = 1, callStart = true // false for concurrent tools (already called in onToolReceived)
115
136
  ) {
137
+ // User hooks fire first — before built-in policy — so an explicit deny
138
+ // is reported with the hook's own reason rather than a generic one.
139
+ if (this.hooks?.hasHooks('PreToolUse')) {
140
+ const decision = await this.hooks.dispatch('PreToolUse', this.hookInput(invocation, 'PreToolUse'));
141
+ if (decision.decision === 'deny') {
142
+ this.guard?.cancelInvocation(invocation.id);
143
+ return {
144
+ output: `Blocked by a user hook: ${decision.reason || 'denied'}. Do not retry the same call — explain to the user what you were trying to do and ask how they'd like to proceed.`,
145
+ isError: true,
146
+ };
147
+ }
148
+ }
116
149
  const guardResult = this.guard
117
150
  ? await this.guard.beforeExecute(invocation, this.scope)
118
151
  : null;
@@ -213,9 +246,28 @@ export class StreamingExecutor {
213
246
  // yesterday and what did it run". 30s threshold is conservative
214
247
  // (Read/Glob/Grep finish in <1s; only network or shell work
215
248
  // crosses).
249
+ // Spend gate: fires only for tools that move real money. Blocking, so a
250
+ // user hook (spend cap, asset blacklist) can veto before funds move.
251
+ if (isSpendTool(invocation.name) && this.hooks?.hasHooks('PreSpend')) {
252
+ const decision = await this.hooks.dispatch('PreSpend', this.hookInput(invocation, 'PreSpend'));
253
+ if (decision.decision === 'deny') {
254
+ this.guard?.cancelInvocation(invocation.id);
255
+ return {
256
+ output: `Spend blocked by a user hook: ${decision.reason || 'denied'}. Do not retry the same call — explain what you were trying to spend and ask the user how to proceed.`,
257
+ isError: true,
258
+ };
259
+ }
260
+ }
216
261
  const execStart = Date.now();
217
262
  let result = await handler.execute(invocation.input, progressScope);
218
263
  this.guard?.afterExecute(invocation, result);
264
+ // Notify-only hooks — never block, never delay the result.
265
+ if (this.hooks?.hasHooks('PostToolUse')) {
266
+ void this.hooks.dispatch('PostToolUse', this.hookInput(invocation, 'PostToolUse')).catch(() => { });
267
+ }
268
+ if (!result.isError && isSpendTool(invocation.name) && this.hooks?.hasHooks('PostSpend')) {
269
+ void this.hooks.dispatch('PostSpend', this.hookInput(invocation, 'PostSpend')).catch(() => { });
270
+ }
219
271
  const execElapsed = Date.now() - execStart;
220
272
  if (execElapsed >= 30_000) {
221
273
  const status = result.isError ? 'error' : 'ok';
@@ -6,6 +6,12 @@ export declare function normalizeSearchQuery(query: string): {
6
6
  };
7
7
  export declare function isToolClassFailure(name: string, result: CapabilityResult): boolean;
8
8
  export declare class SessionToolGuard {
9
+ /**
10
+ * Session identity for the trade-plan gate. Explicit (not module-global)
11
+ * so multiple concurrent sessions in one process (AgentHost) can never
12
+ * check trades against another session's approved plan.
13
+ */
14
+ private sessionId?;
9
15
  private turn;
10
16
  private webSearchesThisTurn;
11
17
  private searchFamilies;
@@ -19,6 +25,7 @@ export declare class SessionToolGuard {
19
25
  private recentGreps;
20
26
  private recentGlobs;
21
27
  private recentBash;
28
+ constructor(sessionId?: string);
22
29
  startTurn(): void;
23
30
  beforeExecute(invocation: CapabilityInvocation, scope: ExecutionScope): Promise<CapabilityResult | null>;
24
31
  private beforeBash;
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { checkTradePlanGate, recordTradeExecution } from '../trading/trade-plan.js';
3
4
  const MAX_WEBSEARCHES_PER_TURN = 8;
4
5
  const MAX_SIMILAR_SEARCHES_PER_TURN = 4;
5
6
  const MAX_NO_SIGNAL_SEARCHES_PER_FAMILY = 2;
@@ -165,6 +166,12 @@ export function isToolClassFailure(name, result) {
165
166
  return true;
166
167
  }
167
168
  export class SessionToolGuard {
169
+ /**
170
+ * Session identity for the trade-plan gate. Explicit (not module-global)
171
+ * so multiple concurrent sessions in one process (AgentHost) can never
172
+ * check trades against another session's approved plan.
173
+ */
174
+ sessionId;
168
175
  turn = 0;
169
176
  webSearchesThisTurn = 0;
170
177
  searchFamilies = [];
@@ -180,6 +187,9 @@ export class SessionToolGuard {
180
187
  recentGreps = new Map();
181
188
  recentGlobs = new Map();
182
189
  recentBash = new Map();
190
+ constructor(sessionId) {
191
+ this.sessionId = sessionId;
192
+ }
183
193
  startTurn() {
184
194
  this.turn++;
185
195
  this.webSearchesThisTurn = 0;
@@ -218,6 +228,11 @@ export class SessionToolGuard {
218
228
  isError: true,
219
229
  };
220
230
  }
231
+ // Trade-plan gate: real-money trades require an approved plan with
232
+ // remaining budget — in every permission mode, trust included.
233
+ const tradeGate = checkTradePlanGate(invocation, this.sessionId);
234
+ if (tradeGate)
235
+ return tradeGate;
221
236
  switch (invocation.name) {
222
237
  case 'WebSearch':
223
238
  case 'SearchX':
@@ -334,6 +349,12 @@ export class SessionToolGuard {
334
349
  return null;
335
350
  }
336
351
  afterExecute(invocation, result) {
352
+ // Draw down the approved trade plan's budget on successful executions
353
+ // (no-op for non-trade tools).
354
+ try {
355
+ recordTradeExecution(invocation, result, this.sessionId);
356
+ }
357
+ catch { /* budget accounting must never break tool results */ }
337
358
  // Per-tool circuit breaker: count consecutive tool-class failures, reset on
338
359
  // any success. Agent-input errors (e.g. WebFetch 404 on a guessed URL) are
339
360
  // not tool failures and must not trip the breaker.
@@ -88,6 +88,12 @@ export interface ExecutionScope {
88
88
  onProgress?: (text: string) => void;
89
89
  /** Routes AskUser questions through ink UI input to avoid raw-mode stdin conflict */
90
90
  onAskUser?: (question: string, options?: string[]) => Promise<string>;
91
+ /**
92
+ * Structured approval surface (trade plans, dashboard-answered prompts).
93
+ * Wired from AgentConfig.approvalPromptFn. Absent = fail closed for
94
+ * anything that requires an explicit decision.
95
+ */
96
+ onApproval?: import('./approvals.js').ApprovalPromptFn;
91
97
  /** Context from parent agent — helps sub-agents avoid duplicate work */
92
98
  parentContext?: {
93
99
  goal?: string;
@@ -215,4 +221,24 @@ export interface AgentConfig {
215
221
  * racks up many tool calls + spend, to cut input-replay cost. Default on;
216
222
  * set false to disable (the desktop exposes this as a toggle). */
217
223
  costSaver?: boolean;
224
+ /**
225
+ * Lifecycle hook engine. When unset, the loop builds one from the working
226
+ * directory's hook files (~/.blockrun/hooks + trusted project .franklin/hooks).
227
+ * Callers inject a prebuilt engine to share it across sessions or to stub
228
+ * hooks in tests. FRANKLIN_HOOKS=0 disables hooks regardless.
229
+ */
230
+ hooks?: import('../hooks/runner.js').HookEngine;
231
+ /**
232
+ * Structured approval prompt (trade plans and future approvables). The TUI
233
+ * routes it through the ask-user modal; serve routes it through a broker to
234
+ * remote clients; headless runs install an auto-policy honoring
235
+ * --approve-trades + --max-spend. Absent = approvals fail closed.
236
+ */
237
+ approvalPromptFn?: import('./approvals.js').ApprovalPromptFn;
238
+ /**
239
+ * Goal auto-continuation: an active goal re-engages the agent at each turn
240
+ * boundary. Default on for interactive sessions; one-shot/headless runs set
241
+ * false so a goal never extends a bounded scripted run.
242
+ */
243
+ autoContinueGoals?: boolean;
218
244
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Unified approval/decision audit log — one book for every gate decision:
3
+ * hook denies, permission prompts, and trade-plan verdicts. Append-only
4
+ * JSONL at ~/.blockrun/approvals.jsonl so `franklin panel` and post-hoc
5
+ * forensics read a single stream instead of three.
6
+ */
7
+ export interface ApprovalRecord {
8
+ ts: number;
9
+ sessionId: string;
10
+ /** What kind of gate produced this record. */
11
+ kind: 'hook' | 'permission' | 'trade-plan';
12
+ /** What was being decided — tool name, plan id, hook source. */
13
+ subject: string;
14
+ decision: 'allow' | 'deny' | 'approve' | 'reject' | 'expire' | 'cancel';
15
+ /** Who decided: 'hook:<file>', 'user:tui', 'user:panel', 'policy', 'flag'. */
16
+ by: string;
17
+ reason?: string;
18
+ }
19
+ export declare function approvalsLogPath(): string;
20
+ export declare function appendApprovalRecord(record: ApprovalRecord): void;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Unified approval/decision audit log — one book for every gate decision:
3
+ * hook denies, permission prompts, and trade-plan verdicts. Append-only
4
+ * JSONL at ~/.blockrun/approvals.jsonl so `franklin panel` and post-hoc
5
+ * forensics read a single stream instead of three.
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { BLOCKRUN_DIR } from '../config.js';
10
+ export function approvalsLogPath() {
11
+ return path.join(BLOCKRUN_DIR, 'approvals.jsonl');
12
+ }
13
+ export function appendApprovalRecord(record) {
14
+ try {
15
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
16
+ fs.appendFileSync(approvalsLogPath(), JSON.stringify(record) + '\n');
17
+ }
18
+ catch {
19
+ // Audit is best-effort — never block the agent on a log write.
20
+ }
21
+ }
@@ -1,4 +1,4 @@
1
- import type { StreamTurnDone } from '../agent/types.js';
1
+ import type { AgentConfig, StreamTurnDone } from '../agent/types.js';
2
2
  interface StartOptions {
3
3
  model?: string;
4
4
  debug?: boolean;
@@ -16,7 +16,16 @@ interface StartOptions {
16
16
  maxSpend?: string | number;
17
17
  /** Run a single prompt non-interactively, then exit. For batch/scripted use. */
18
18
  prompt?: string;
19
+ /** Non-interactive runs: auto-approve trade plans that fit --max-spend. */
20
+ approveTrades?: boolean;
19
21
  }
20
22
  export declare function startCommand(options: StartOptions): Promise<void>;
21
23
  export declare function oneShotExitCodeForTurnReason(reason: StreamTurnDone['reason']): number;
24
+ /**
25
+ * Headless approval policy. No human is present, so:
26
+ * - without --approve-trades: every trade plan is denied
27
+ * - with it: auto-approve only when the plan total fits what's left of the
28
+ * --max-spend envelope (no flag combination bypasses --max-spend)
29
+ */
30
+ export declare function createHeadlessApprovalFn(approveTrades: boolean, maxSpendUsd?: number): NonNullable<AgentConfig['approvalPromptFn']>;
22
31
  export {};