@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
@@ -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.
@@ -665,8 +691,85 @@ export async function startServer(opts) {
665
691
  if (abortFn)
666
692
  abortFn();
667
693
  break;
668
- case 'agent.permissionResponse':
669
- // permissionMode is 'trust' — nothing to unblock.
694
+ case 'agent.permissionResponse': {
695
+ // Hosted agents: resolve the parked approval by (sessionId, requestId).
696
+ // Legacy desktop path runs in trust mode — nothing to unblock there,
697
+ // so a payload without ids stays a no-op (byte-compatible).
698
+ const sid = p.sessionId ? String(p.sessionId) : '';
699
+ const rid = p.requestId ? String(p.requestId) : '';
700
+ if (sid && rid) {
701
+ const ok = host.respond(sid, rid, String(p.choice ?? p.decision ?? 'no'), p.message ? String(p.message) : undefined);
702
+ send(ws, id, 'response', { ok });
703
+ }
704
+ break;
705
+ }
706
+ // ── Multi-agent host kinds ──
707
+ case 'agents.list':
708
+ send(ws, id, 'response', { agents: host.list() });
709
+ break;
710
+ case 'agents.dispatch': {
711
+ try {
712
+ const sessionId = await host.dispatch({
713
+ prompt: String(p.prompt ?? p.text ?? ''),
714
+ model: p.model ? String(p.model) : undefined,
715
+ label: p.label ? String(p.label) : undefined,
716
+ maxSpendUsd: typeof p.maxSpendUsd === 'number' ? p.maxSpendUsd : undefined,
717
+ });
718
+ send(ws, id, 'response', { sessionId });
719
+ }
720
+ catch (err) {
721
+ send(ws, id, 'error', { message: err instanceof Error ? err.message : 'dispatch failed' });
722
+ }
723
+ break;
724
+ }
725
+ case 'agents.reply':
726
+ send(ws, id, 'response', { ok: host.reply(String(p.sessionId ?? ''), String(p.text ?? '')) });
727
+ break;
728
+ case 'agents.cancel':
729
+ send(ws, id, 'response', { ok: host.cancel(String(p.sessionId ?? '')) });
730
+ break;
731
+ case 'agents.subscribe': {
732
+ const sid = String(p.sessionId ?? '');
733
+ const unsubscribe = host.subscribe(sid, (ev) => send(ws, `agent:${sid}`, 'agent.event', { sessionId: sid, ev }));
734
+ if (unsubscribe) {
735
+ let subs = wsSubs.get(ws);
736
+ if (!subs) {
737
+ subs = new Map();
738
+ wsSubs.set(ws, subs);
739
+ }
740
+ subs.get(sid)?.(); // replace an existing subscription
741
+ subs.set(sid, unsubscribe);
742
+ let sessions = subscribedSessions.get(ws);
743
+ if (!sessions) {
744
+ sessions = new Set();
745
+ subscribedSessions.set(ws, sessions);
746
+ }
747
+ sessions.add(sid);
748
+ // Surface already-pending approvals immediately on subscribe.
749
+ for (const req of host.get(sid)?.pendingApprovals ?? []) {
750
+ send(ws, `agent:${sid}`, 'approval.request', {
751
+ sessionId: sid,
752
+ requestId: req.requestId,
753
+ kind: req.kind,
754
+ title: req.title,
755
+ options: req.options,
756
+ description: req.description,
757
+ });
758
+ }
759
+ }
760
+ send(ws, id, 'response', { ok: !!unsubscribe });
761
+ break;
762
+ }
763
+ case 'agents.unsubscribe': {
764
+ const sid = String(p.sessionId ?? '');
765
+ wsSubs.get(ws)?.get(sid)?.();
766
+ wsSubs.get(ws)?.delete(sid);
767
+ subscribedSessions.get(ws)?.delete(sid);
768
+ send(ws, id, 'response', { ok: true });
769
+ break;
770
+ }
771
+ case 'agent.output.replay':
772
+ send(ws, id, 'response', { events: host.output(String(p.sessionId ?? '')) });
670
773
  break;
671
774
  default:
672
775
  send(ws, id, 'error', { message: `Unknown kind: ${kind}` });
@@ -759,6 +862,15 @@ export async function startServer(opts) {
759
862
  send(ws, msg.id, 'error', { message: err instanceof Error ? err.message : String(err) });
760
863
  });
761
864
  });
865
+ ws.on('close', () => {
866
+ // Tear down this socket's agent subscriptions; the agents keep running.
867
+ const subs = wsSubs.get(ws);
868
+ if (subs)
869
+ for (const unsubscribe of subs.values())
870
+ unsubscribe();
871
+ wsSubs.delete(ws);
872
+ subscribedSessions.delete(ws);
873
+ });
762
874
  });
763
875
  await new Promise((resolve) => {
764
876
  httpServer.listen(port, '127.0.0.1', () => {
@@ -767,4 +879,21 @@ export async function startServer(opts) {
767
879
  resolve();
768
880
  });
769
881
  });
882
+ // Discovery file (mirror of the panel-url pattern): lets `franklin panel`
883
+ // point its Agents tab at this server without configuration.
884
+ const serveUrlFile = path.join(BLOCKRUN_DIR, 'serve-url');
885
+ try {
886
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
887
+ fs.writeFileSync(serveUrlFile, `ws://127.0.0.1:${port}/agent`);
888
+ }
889
+ catch { /* best-effort */ }
890
+ const cleanup = () => {
891
+ try {
892
+ fs.unlinkSync(serveUrlFile);
893
+ }
894
+ catch { /* gone */ }
895
+ host.shutdown();
896
+ };
897
+ process.once('SIGINT', () => { cleanup(); process.exit(130); });
898
+ process.once('SIGTERM', () => { cleanup(); process.exit(143); });
770
899
  }
@@ -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;