@blockrun/franklin 3.33.0 → 3.34.1

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 +186 -3
  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
@@ -32,6 +32,8 @@ import { readSwaps } from '../stats/swap-log.js';
32
32
  import { isCloudSyncEnabled, cloudList, cloudSync } from './cloud-sync.js';
33
33
  import { setupAgentWallet, setupAgentSolanaWallet } from '@blockrun/llm';
34
34
  import { retryFetchBalance } from '../commands/balance-retry.js';
35
+ import { AgentHost } from './agent-host.js';
36
+ import { bus } from '../events/bus.js';
35
37
  // qwen3-next-80b-a3b-instruct: cleanest free instruction-follower (no thinking
36
38
  // leak / markdown fences — verified live 2026-07-11). Replaces the EOL'd
37
39
  // nvidia/deepseek-v4-flash the gateway no longer serves.
@@ -219,6 +221,30 @@ export async function startServer(opts) {
219
221
  const chain = loadChain();
220
222
  const apiUrl = API_URLS[chain];
221
223
  const userConfig = loadConfig();
224
+ // ── Multi-agent host (dashboard fleet) ──
225
+ // The legacy single-window path below stays byte-compatible for the
226
+ // desktop app; hosted agents are additive, run in 'default' permission
227
+ // mode, and surface approvals to subscribed clients.
228
+ const host = new AgentHost({
229
+ workDir,
230
+ chain,
231
+ apiUrl,
232
+ defaultModel: userConfig['default-model'] || FREE_DEFAULT_MODEL,
233
+ debug,
234
+ });
235
+ // Per-socket subscription bookkeeping: sessionId → unsubscribe.
236
+ const wsSubs = new WeakMap();
237
+ const subscribedSessions = new Map();
238
+ // Approval pushes reach every socket subscribed to that agent.
239
+ bus.on('approval.requested', (ev) => {
240
+ if (ev.type !== 'approval.requested')
241
+ return;
242
+ for (const [ws, sessions] of subscribedSessions) {
243
+ if (sessions.has(ev.data.sessionId)) {
244
+ send(ws, `agent:${ev.data.sessionId}`, 'approval.request', ev.data);
245
+ }
246
+ }
247
+ });
222
248
  // ── Single long-lived agent session ──
223
249
  // interactiveSession owns the loop; we feed it user turns via a queue and
224
250
  // fan its StreamEvents out to the connected socket.
@@ -234,6 +260,11 @@ export async function startServer(opts) {
234
260
  // The socket + correlation id for the in-flight turn (single-window).
235
261
  let activeWs = null;
236
262
  let activeTurnId = null;
263
+ // Pending approval asks for the legacy desktop session (trade plans).
264
+ // Keyed by askId — the wire contract the desktop UI already declares
265
+ // (agent.permissionAsk / agent.permissionResponse with askId + decision).
266
+ let askSeq = 0;
267
+ const legacyAsks = new Map();
237
268
  // We sometimes inject helper commands (`/model …`, `/clear`) as their own
238
269
  // turns ahead of the real prompt. Each ends with its own turn_done — which
239
270
  // would emit agent.done and clear activeTurnId, killing the real prompt's
@@ -417,10 +448,38 @@ export async function startServer(opts) {
417
448
  capabilities,
418
449
  maxTurns: 100,
419
450
  workingDir: workDir,
420
- permissionMode: 'trust', // the desktop UI has no permission prompt yet
451
+ permissionMode: 'trust', // tools auto-run; money still gates via approvalPromptFn below
421
452
  debug: !!debug,
422
453
  showPrefetchStatus: false,
423
454
  costSaver,
455
+ // Structured approvals (trade plans): surfaced to the desktop over the
456
+ // in-flight turn stream as agent.permissionAsk; the UI answers with
457
+ // agent.permissionResponse {askId, decision}. Without a connected
458
+ // client — or unanswered past the TTL — the approval fails closed,
459
+ // matching the trade-plan gate's deny-by-default posture.
460
+ approvalPromptFn: (req) => new Promise((resolve) => {
461
+ if (!activeWs || !activeTurnId) {
462
+ resolve({ choice: 'deny', message: 'no client connected to approve' });
463
+ return;
464
+ }
465
+ const askId = `ask_${++askSeq}_${Date.now().toString(36)}`;
466
+ const timer = setTimeout(() => {
467
+ if (legacyAsks.delete(askId)) {
468
+ resolve({ choice: 'deny', message: 'approval timed out' });
469
+ }
470
+ }, req.timeoutMs ?? 15 * 60 * 1000);
471
+ timer.unref?.();
472
+ legacyAsks.set(askId, (decision) => {
473
+ clearTimeout(timer);
474
+ resolve(decision);
475
+ });
476
+ emit('agent.permissionAsk', {
477
+ sessionId: '',
478
+ toolName: req.kind === 'trade-plan' ? 'TradePlan' : req.title,
479
+ description: `${req.title}\n\n${req.description}`,
480
+ askId,
481
+ });
482
+ }),
424
483
  };
425
484
  agentConfig = config;
426
485
  interactiveSession(config, getUserInput, onEvent, (abort) => { abortFn = abort; })
@@ -665,8 +724,106 @@ export async function startServer(opts) {
665
724
  if (abortFn)
666
725
  abortFn();
667
726
  break;
668
- case 'agent.permissionResponse':
669
- // permissionMode is 'trust' — nothing to unblock.
727
+ case 'agent.permissionResponse': {
728
+ // Two resolution paths:
729
+ // - Hosted agents: (sessionId, requestId) → AgentHost broker.
730
+ // - Legacy desktop session: (askId, decision y/n/always) → the parked
731
+ // approvalPromptFn promise (trade-plan approvals).
732
+ // A payload with neither stays a no-op (byte-compatible with clients
733
+ // that predate both).
734
+ const sid = p.sessionId ? String(p.sessionId) : '';
735
+ const rid = p.requestId ? String(p.requestId) : '';
736
+ if (sid && rid) {
737
+ const ok = host.respond(sid, rid, String(p.choice ?? p.decision ?? 'no'), p.message ? String(p.message) : undefined);
738
+ send(ws, id, 'response', { ok });
739
+ break;
740
+ }
741
+ const askId = p.askId ? String(p.askId) : '';
742
+ if (askId) {
743
+ const resolver = legacyAsks.get(askId);
744
+ if (resolver) {
745
+ legacyAsks.delete(askId);
746
+ const decision = String(p.decision ?? p.choice ?? 'n').toLowerCase();
747
+ const approve = decision === 'y' || decision === 'yes' || decision === 'always' || decision === 'approve';
748
+ resolver({
749
+ choice: approve ? 'approve' : 'deny',
750
+ message: p.message ? String(p.message) : undefined,
751
+ });
752
+ send(ws, id, 'response', { ok: true });
753
+ }
754
+ else {
755
+ send(ws, id, 'response', { ok: false });
756
+ }
757
+ }
758
+ break;
759
+ }
760
+ // ── Multi-agent host kinds ──
761
+ case 'agents.list':
762
+ send(ws, id, 'response', { agents: host.list() });
763
+ break;
764
+ case 'agents.dispatch': {
765
+ try {
766
+ const sessionId = await host.dispatch({
767
+ prompt: String(p.prompt ?? p.text ?? ''),
768
+ model: p.model ? String(p.model) : undefined,
769
+ label: p.label ? String(p.label) : undefined,
770
+ maxSpendUsd: typeof p.maxSpendUsd === 'number' ? p.maxSpendUsd : undefined,
771
+ });
772
+ send(ws, id, 'response', { sessionId });
773
+ }
774
+ catch (err) {
775
+ send(ws, id, 'error', { message: err instanceof Error ? err.message : 'dispatch failed' });
776
+ }
777
+ break;
778
+ }
779
+ case 'agents.reply':
780
+ send(ws, id, 'response', { ok: host.reply(String(p.sessionId ?? ''), String(p.text ?? '')) });
781
+ break;
782
+ case 'agents.cancel':
783
+ send(ws, id, 'response', { ok: host.cancel(String(p.sessionId ?? '')) });
784
+ break;
785
+ case 'agents.subscribe': {
786
+ const sid = String(p.sessionId ?? '');
787
+ const unsubscribe = host.subscribe(sid, (ev) => send(ws, `agent:${sid}`, 'agent.event', { sessionId: sid, ev }));
788
+ if (unsubscribe) {
789
+ let subs = wsSubs.get(ws);
790
+ if (!subs) {
791
+ subs = new Map();
792
+ wsSubs.set(ws, subs);
793
+ }
794
+ subs.get(sid)?.(); // replace an existing subscription
795
+ subs.set(sid, unsubscribe);
796
+ let sessions = subscribedSessions.get(ws);
797
+ if (!sessions) {
798
+ sessions = new Set();
799
+ subscribedSessions.set(ws, sessions);
800
+ }
801
+ sessions.add(sid);
802
+ // Surface already-pending approvals immediately on subscribe.
803
+ for (const req of host.get(sid)?.pendingApprovals ?? []) {
804
+ send(ws, `agent:${sid}`, 'approval.request', {
805
+ sessionId: sid,
806
+ requestId: req.requestId,
807
+ kind: req.kind,
808
+ title: req.title,
809
+ options: req.options,
810
+ description: req.description,
811
+ });
812
+ }
813
+ }
814
+ send(ws, id, 'response', { ok: !!unsubscribe });
815
+ break;
816
+ }
817
+ case 'agents.unsubscribe': {
818
+ const sid = String(p.sessionId ?? '');
819
+ wsSubs.get(ws)?.get(sid)?.();
820
+ wsSubs.get(ws)?.delete(sid);
821
+ subscribedSessions.get(ws)?.delete(sid);
822
+ send(ws, id, 'response', { ok: true });
823
+ break;
824
+ }
825
+ case 'agent.output.replay':
826
+ send(ws, id, 'response', { events: host.output(String(p.sessionId ?? '')) });
670
827
  break;
671
828
  default:
672
829
  send(ws, id, 'error', { message: `Unknown kind: ${kind}` });
@@ -759,6 +916,15 @@ export async function startServer(opts) {
759
916
  send(ws, msg.id, 'error', { message: err instanceof Error ? err.message : String(err) });
760
917
  });
761
918
  });
919
+ ws.on('close', () => {
920
+ // Tear down this socket's agent subscriptions; the agents keep running.
921
+ const subs = wsSubs.get(ws);
922
+ if (subs)
923
+ for (const unsubscribe of subs.values())
924
+ unsubscribe();
925
+ wsSubs.delete(ws);
926
+ subscribedSessions.delete(ws);
927
+ });
762
928
  });
763
929
  await new Promise((resolve) => {
764
930
  httpServer.listen(port, '127.0.0.1', () => {
@@ -767,4 +933,21 @@ export async function startServer(opts) {
767
933
  resolve();
768
934
  });
769
935
  });
936
+ // Discovery file (mirror of the panel-url pattern): lets `franklin panel`
937
+ // point its Agents tab at this server without configuration.
938
+ const serveUrlFile = path.join(BLOCKRUN_DIR, 'serve-url');
939
+ try {
940
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
941
+ fs.writeFileSync(serveUrlFile, `ws://127.0.0.1:${port}/agent`);
942
+ }
943
+ catch { /* best-effort */ }
944
+ const cleanup = () => {
945
+ try {
946
+ fs.unlinkSync(serveUrlFile);
947
+ }
948
+ catch { /* gone */ }
949
+ host.shutdown();
950
+ };
951
+ process.once('SIGINT', () => { cleanup(); process.exit(130); });
952
+ process.once('SIGTERM', () => { cleanup(); process.exit(143); });
770
953
  }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Live-agent registry — which sessions are running RIGHT NOW, and where.
3
+ *
4
+ * Session JSONL on disk can't distinguish a live session from a dead one;
5
+ * this registry can: one small JSON per session under ~/.blockrun/agents/,
6
+ * refreshed on every state change, with pid-based reconciliation (the same
7
+ * liveness model as the task subsystem). The panel's Agents tab reads it
8
+ * to render the fleet; serve's AgentHost and the CLI loop both write it.
9
+ */
10
+ import type { AgentRunState } from '../events/types.js';
11
+ export interface LiveAgentRecord {
12
+ sessionId: string;
13
+ pid: number;
14
+ state: AgentRunState;
15
+ label: string;
16
+ model: string;
17
+ /** Which process type hosts the loop — panel can only drive 'serve' agents. */
18
+ host: 'serve' | 'cli';
19
+ startedAt: number;
20
+ updatedAt: number;
21
+ /** Count of approvals parked waiting for a human. */
22
+ pendingApprovals?: number;
23
+ }
24
+ export declare function liveAgentsDir(): string;
25
+ export declare function writeLiveAgent(record: LiveAgentRecord): void;
26
+ export declare function removeLiveAgent(sessionId: string): void;
27
+ /**
28
+ * All records, with dead-pid reconciliation: a record whose process is gone
29
+ * flips to 'failed' if it claimed to be running (crash without cleanup), and
30
+ * terminal records older than a day are pruned.
31
+ */
32
+ export declare function readLiveAgents(): LiveAgentRecord[];
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Live-agent registry — which sessions are running RIGHT NOW, and where.
3
+ *
4
+ * Session JSONL on disk can't distinguish a live session from a dead one;
5
+ * this registry can: one small JSON per session under ~/.blockrun/agents/,
6
+ * refreshed on every state change, with pid-based reconciliation (the same
7
+ * liveness model as the task subsystem). The panel's Agents tab reads it
8
+ * to render the fleet; serve's AgentHost and the CLI loop both write it.
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { BLOCKRUN_DIR } from '../config.js';
13
+ export function liveAgentsDir() {
14
+ return path.join(BLOCKRUN_DIR, 'agents');
15
+ }
16
+ function recordPath(sessionId) {
17
+ return path.join(liveAgentsDir(), `${sessionId}.json`);
18
+ }
19
+ export function writeLiveAgent(record) {
20
+ try {
21
+ fs.mkdirSync(liveAgentsDir(), { recursive: true });
22
+ const tmp = path.join(liveAgentsDir(), `.${record.sessionId}.tmp`);
23
+ fs.writeFileSync(tmp, JSON.stringify({ ...record, updatedAt: Date.now() }));
24
+ fs.renameSync(tmp, recordPath(record.sessionId));
25
+ }
26
+ catch {
27
+ /* registry is best-effort — never break the loop over it */
28
+ }
29
+ }
30
+ export function removeLiveAgent(sessionId) {
31
+ try {
32
+ fs.unlinkSync(recordPath(sessionId));
33
+ }
34
+ catch {
35
+ /* already gone */
36
+ }
37
+ }
38
+ function pidAlive(pid) {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
47
+ /**
48
+ * All records, with dead-pid reconciliation: a record whose process is gone
49
+ * flips to 'failed' if it claimed to be running (crash without cleanup), and
50
+ * terminal records older than a day are pruned.
51
+ */
52
+ export function readLiveAgents() {
53
+ let files;
54
+ try {
55
+ files = fs.readdirSync(liveAgentsDir()).filter(f => f.endsWith('.json'));
56
+ }
57
+ catch {
58
+ return [];
59
+ }
60
+ const out = [];
61
+ const dayAgo = Date.now() - 86_400_000;
62
+ for (const f of files) {
63
+ try {
64
+ const record = JSON.parse(fs.readFileSync(path.join(liveAgentsDir(), f), 'utf-8'));
65
+ if (!record?.sessionId)
66
+ continue;
67
+ const terminal = record.state === 'completed' || record.state === 'failed';
68
+ if (!terminal && !pidAlive(record.pid)) {
69
+ record.state = 'failed';
70
+ writeLiveAgent(record); // persist the reconciliation
71
+ }
72
+ if ((record.state === 'completed' || record.state === 'failed') && record.updatedAt < dayAgo) {
73
+ removeLiveAgent(record.sessionId); // prune stale terminals
74
+ continue;
75
+ }
76
+ out.push(record);
77
+ }
78
+ catch {
79
+ /* skip unreadable */
80
+ }
81
+ }
82
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
83
+ }
@@ -25,6 +25,12 @@ export interface SearchOptions {
25
25
  /** Only sessions newer than this timestamp (ms) */
26
26
  since?: number;
27
27
  }
28
+ export declare function tokenize(text: string): string[];
29
+ export declare function parseQuery(query: string): {
30
+ terms: string[];
31
+ phrases: string[];
32
+ };
33
+ export declare function extractSnippet(content: string, query: string, maxLen?: number): string;
28
34
  /**
29
35
  * Search sessions for a query string.
30
36
  * Returns results ranked by relevance (term frequency + recency).
@@ -8,14 +8,14 @@
8
8
  import fs from 'node:fs';
9
9
  import { listSessions, getSessionFilePath } from './storage.js';
10
10
  // ─── Tokenization ─────────────────────────────────────────────────────────
11
- function tokenize(text) {
11
+ export function tokenize(text) {
12
12
  return text
13
13
  .toLowerCase()
14
14
  .replace(/[^\p{L}\p{N}_\s]/gu, ' ')
15
15
  .split(/\s+/u)
16
16
  .filter(t => t.length > 1 || /[^\x00-\x7F]/.test(t));
17
17
  }
18
- function parseQuery(query) {
18
+ export function parseQuery(query) {
19
19
  const phrases = [];
20
20
  // Extract quoted phrases first
21
21
  const cleaned = query.replace(/"([^"]+)"/g, (_, phrase) => {
@@ -26,7 +26,7 @@ function parseQuery(query) {
26
26
  return { terms, phrases };
27
27
  }
28
28
  // ─── Snippet Extraction ───────────────────────────────────────────────────
29
- function extractSnippet(content, query, maxLen = 200) {
29
+ export function extractSnippet(content, query, maxLen = 200) {
30
30
  const lower = content.toLowerCase();
31
31
  const q = query.toLowerCase();
32
32
  const idx = lower.indexOf(q);
@@ -51,6 +51,12 @@ export interface SessionMeta {
51
51
  * meta with imported=true.
52
52
  */
53
53
  imported?: true;
54
+ /**
55
+ * Active goal bound to this session (see src/goal/). Sticky like `chain`
56
+ * so a `--resume` re-hydrates the goal loop; cleared explicitly when the
57
+ * goal completes or is abandoned (updateSessionMeta with goalId: '').
58
+ */
59
+ goalId?: string;
54
60
  }
55
61
  /** Get the absolute path to a session's JSONL file (for external readers like search). */
56
62
  export declare function getSessionFilePath(id: string): string;
@@ -137,6 +137,12 @@ export function updateSessionMeta(sessionId, meta) {
137
137
  // shielding the session from auto-deletion. Without preservation, the
138
138
  // first turn added via `--resume` would silently drop the flag.
139
139
  ...(meta.imported || existing?.imported ? { imported: true } : {}),
140
+ // goalId: explicit empty string clears; undefined preserves existing.
141
+ ...(meta.goalId !== undefined
142
+ ? (meta.goalId ? { goalId: meta.goalId } : {})
143
+ : existing?.goalId
144
+ ? { goalId: existing.goalId }
145
+ : {}),
140
146
  };
141
147
  // Atomic write: tmp file + rename. Prevents corruption when parent
142
148
  // and sub-agent update the same session meta concurrently.
@@ -0,0 +1,7 @@
1
+ /**
2
+ * UpdateGoal capability — the model's control surface for an active goal.
3
+ * Completion claims are intercepted by an adversarial verifier panel before
4
+ * they are accepted; blocked claims escalate to the user.
5
+ */
6
+ import type { CapabilityHandler } from '../agent/types.js';
7
+ export declare function createUpdateGoalCapability(): CapabilityHandler;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * UpdateGoal capability — the model's control surface for an active goal.
3
+ * Completion claims are intercepted by an adversarial verifier panel before
4
+ * they are accepted; blocked claims escalate to the user.
5
+ */
6
+ import { processGoalClaim } from '../goal/runtime.js';
7
+ export function createUpdateGoalCapability() {
8
+ return {
9
+ spec: {
10
+ name: 'UpdateGoal',
11
+ description: 'Update the active goal (started with /goal). Set completed: true ONLY when every acceptance ' +
12
+ 'criterion in the goal plan is demonstrably met and you have run the plan\'s verification yourself — ' +
13
+ 'an adversarial reviewer panel audits the claim and refutes anything unsupported by real evidence. ' +
14
+ 'Set blocked_reason when you genuinely need a user decision to proceed. ' +
15
+ 'Use message alone for a progress note. No active goal = this tool errors.',
16
+ input_schema: {
17
+ type: 'object',
18
+ properties: {
19
+ completed: { type: 'boolean', description: 'true = claim the goal is fully achieved (triggers verification).' },
20
+ blocked_reason: { type: 'string', description: 'Why the goal cannot proceed without a user decision.' },
21
+ message: { type: 'string', description: 'Progress note, or evidence summary accompanying a completion claim.' },
22
+ },
23
+ },
24
+ },
25
+ // Verification can take minutes and must not race other tools.
26
+ concurrent: false,
27
+ execute: (input, ctx) => processGoalClaim(input, ctx),
28
+ };
29
+ }
@@ -13,6 +13,12 @@ import { webFetchCapability, clearSessionState as clearWebFetchSessionState } fr
13
13
  import { webSearchCapability } from './websearch.js';
14
14
  import { taskCapability } from './task.js';
15
15
  import { detachCapability } from './detach.js';
16
+ import { createMonitorCapability } from './monitor.js';
17
+ import { createSchedulerCapability } from './scheduler.js';
18
+ import { createTradePlanCapability } from './trade-plan.js';
19
+ import { createUpdateGoalCapability } from './goal.js';
20
+ import { resetMonitors } from '../monitors/registry.js';
21
+ import { getSchedulerSessionId } from '../scheduler/store.js';
16
22
  import { createImageGenCapability } from './imagegen.js';
17
23
  import { createVideoGenCapability } from './videogen.js';
18
24
  import { createMusicGenCapability } from './musicgen.js';
@@ -129,6 +135,7 @@ export function resetToolSessionState() {
129
135
  clearReadSessionState();
130
136
  clearWebFetchSessionState();
131
137
  clearBashSessionState();
138
+ resetMonitors();
132
139
  }
133
140
  /** All capabilities available to the Franklin agent (excluding sub-agent, which needs config). */
134
141
  export const allCapabilities = [
@@ -142,6 +149,10 @@ export const allCapabilities = [
142
149
  webSearchCapability,
143
150
  taskCapability,
144
151
  detachCapability,
152
+ createMonitorCapability(), // Monitor — watch long-running commands, lines delivered at turn boundaries
153
+ createSchedulerCapability({ sessionId: getSchedulerSessionId }), // Scheduler — durable recurring/one-shot prompts
154
+ createTradePlanCapability(), // TradePlan — approval artifact required before real-money trades
155
+ createUpdateGoalCapability(), // UpdateGoal — goal-mode control (verified completion claims)
145
156
  defaultImageGenCapability,
146
157
  defaultVideoGenCapability,
147
158
  defaultMusicGenCapability,
@@ -13,6 +13,7 @@
13
13
  * invites fabricated "facts" that never saw a real conversation.
14
14
  */
15
15
  import { searchEntities, getEntityObservations, getEntityRelations, loadEntities, getBrainStats, } from '../brain/store.js';
16
+ import { searchMemory } from '../memory/indexer.js';
16
17
  const MAX_OBS_PER_ENTITY = 5;
17
18
  const MAX_REL_PER_ENTITY = 3;
18
19
  export const memoryRecallCapability = {
@@ -39,7 +40,7 @@ export const memoryRecallCapability = {
39
40
  required: ['query'],
40
41
  },
41
42
  },
42
- execute: async (input) => {
43
+ execute: async (input, ctx) => {
43
44
  const { query, limit } = input;
44
45
  if (!query || !query.trim()) {
45
46
  return { output: 'Error: query is required', isError: true };
@@ -47,10 +48,19 @@ export const memoryRecallCapability = {
47
48
  const cap = Math.min(Math.max(1, limit ?? 5), 15);
48
49
  const hits = searchEntities(query, cap);
49
50
  const stats = getBrainStats();
51
+ // Document memory (curated MEMORY.md files, session logs, trade
52
+ // journal/theses) — merged into the same recall surface as the graph.
53
+ const docHits = searchMemory(query, ctx?.workingDir ?? process.cwd(), { limit: 5 });
54
+ const docSection = docHits.length > 0
55
+ ? '\n\n# Documents\n' +
56
+ docHits
57
+ .map(h => `- [${h.scope}] ${h.snippet}${h.stalenessNote ? `\n (${h.stalenessNote})` : ''}`)
58
+ .join('\n')
59
+ : '';
50
60
  if (hits.length === 0) {
51
61
  return {
52
- output: `No memory match for "${query}".\n\n` +
53
- `Brain holds ${stats.entities} entities, ${stats.observations} observations.`,
62
+ output: `${docHits.length === 0 ? `No memory match for "${query}".\n\n` : `No entity match for "${query}".`}${docSection}` +
63
+ `${docHits.length === 0 ? `Brain holds ${stats.entities} entities, ${stats.observations} observations.` : ''}`,
54
64
  };
55
65
  }
56
66
  const entities = loadEntities();
@@ -80,7 +90,7 @@ export const memoryRecallCapability = {
80
90
  }
81
91
  }
82
92
  }
83
- return { output: lines.join('\n') };
93
+ return { output: lines.join('\n') + docSection };
84
94
  },
85
95
  concurrent: true,
86
96
  };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Monitor capability — watch a long-running command and receive its output
3
+ * as conversation events at turn boundaries.
4
+ *
5
+ * Built on the detached-task substrate: the command runs as a background
6
+ * task (survives turn ends), and the monitor registry sweeps its log at
7
+ * each turn boundary, delivering fresh lines as a [monitor: <label>] block
8
+ * in the next turn. Flooding monitors auto-pause (volume cutoff).
9
+ */
10
+ import type { CapabilityHandler } from '../agent/types.js';
11
+ export declare function createMonitorCapability(): CapabilityHandler;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Monitor capability — watch a long-running command and receive its output
3
+ * as conversation events at turn boundaries.
4
+ *
5
+ * Built on the detached-task substrate: the command runs as a background
6
+ * task (survives turn ends), and the monitor registry sweeps its log at
7
+ * each turn boundary, delivering fresh lines as a [monitor: <label>] block
8
+ * in the next turn. Flooding monitors auto-pause (volume cutoff).
9
+ */
10
+ import { startDetachedTask } from '../tasks/spawn.js';
11
+ import { readTaskMeta } from '../tasks/store.js';
12
+ import { listMonitors, registerMonitor, removeMonitor, getMonitor, MAX_EVENTS_PER_SESSION, MAX_LINES_PER_SWEEP, } from '../monitors/registry.js';
13
+ export function createMonitorCapability() {
14
+ return {
15
+ spec: {
16
+ name: 'Monitor',
17
+ description: 'Watch a long-running shell command; each new stdout/stderr line is delivered to you ' +
18
+ 'at the next turn boundary as a [monitor] block — you can keep working meanwhile. ' +
19
+ 'Actions: "start" (needs command + description; optional pattern regex to filter lines), ' +
20
+ '"stop" (needs monitor_id), "list". ' +
21
+ 'Use for price feeds, position watchers, log tails, or slow jobs — never sleep-poll in Bash. ' +
22
+ `Filter aggressively: a monitor is auto-paused after ${MAX_LINES_PER_SWEEP} lines in one sweep ` +
23
+ `or ${MAX_EVENTS_PER_SESSION} lines per session. In shell pipelines use grep --line-buffered ` +
24
+ 'so lines flush promptly.',
25
+ input_schema: {
26
+ type: 'object',
27
+ properties: {
28
+ action: { type: 'string', enum: ['start', 'stop', 'list'], description: 'Operation to perform.' },
29
+ command: { type: 'string', description: 'start: shell command to run and watch.' },
30
+ description: { type: 'string', description: 'start: short label shown on delivered blocks (3-6 words).' },
31
+ pattern: { type: 'string', description: 'start: optional regex — only matching lines are delivered.' },
32
+ monitor_id: { type: 'string', description: 'stop: id returned by start.' },
33
+ },
34
+ required: ['action'],
35
+ },
36
+ },
37
+ concurrent: true,
38
+ execute: async (input, ctx) => {
39
+ const action = String(input.action || '');
40
+ if (action === 'start') {
41
+ const command = String(input.command || '').trim();
42
+ const label = String(input.description || '').trim() || command.slice(0, 40);
43
+ if (!command)
44
+ return { output: 'Error: command is required for start.', isError: true };
45
+ let pattern;
46
+ if (typeof input.pattern === 'string' && input.pattern.length > 0) {
47
+ try {
48
+ pattern = new RegExp(input.pattern);
49
+ }
50
+ catch (err) {
51
+ return { output: `Error: invalid pattern regex: ${err.message}`, isError: true };
52
+ }
53
+ }
54
+ const runId = startDetachedTask({
55
+ label: `monitor: ${label}`,
56
+ command,
57
+ workingDir: ctx.workingDir,
58
+ });
59
+ registerMonitor({ taskRunId: runId, label, pattern });
60
+ return {
61
+ output: `Monitor ${runId} started: "${label}". New${pattern ? ' matching' : ''} output lines will arrive ` +
62
+ 'as [monitor] blocks at turn boundaries. Stop it with action "stop" when no longer needed.',
63
+ };
64
+ }
65
+ if (action === 'stop') {
66
+ const id = String(input.monitor_id || '');
67
+ if (!id)
68
+ return { output: 'Error: monitor_id is required for stop.', isError: true };
69
+ const entry = getMonitor(id);
70
+ if (!entry)
71
+ return { output: `No active monitor ${id}.`, isError: true };
72
+ removeMonitor(id);
73
+ // Best-effort terminate the underlying task process.
74
+ const meta = readTaskMeta(id);
75
+ if (meta?.pid) {
76
+ try {
77
+ process.kill(meta.pid, 'SIGTERM');
78
+ }
79
+ catch {
80
+ /* already gone */
81
+ }
82
+ }
83
+ return { output: `Monitor ${id} ("${entry.label}") stopped.` };
84
+ }
85
+ if (action === 'list') {
86
+ const entries = listMonitors();
87
+ if (entries.length === 0)
88
+ return { output: 'No active monitors.' };
89
+ const lines = entries.map(e => `${e.taskRunId} · "${e.label}" · ${e.eventsDelivered} lines delivered` +
90
+ `${e.pattern ? ` · filter /${e.pattern.source}/` : ''}${e.paused ? ` · PAUSED (${e.pausedReason})` : ''}`);
91
+ return { output: `${entries.length} monitor(s):\n${lines.join('\n')}` };
92
+ }
93
+ return { output: `Unknown action "${action}". Use start, stop, or list.`, isError: true };
94
+ },
95
+ };
96
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Scheduler capability — lets the model self-schedule recurring or one-shot
3
+ * prompts ("check the BTC funding rate every hour and alert me on a flip").
4
+ *
5
+ * Firings are synthetic user inputs delivered at turn boundaries; every
6
+ * fired prompt flows through the normal permission/hook/spend pipeline, so
7
+ * self-scheduling grants no extra authority.
8
+ */
9
+ import type { CapabilityHandler } from '../agent/types.js';
10
+ export declare function createSchedulerCapability(opts: {
11
+ sessionId: () => string;
12
+ }): CapabilityHandler;