@blockrun/franklin 3.32.1 → 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 (97) 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/compact.js +1 -1
  6. package/dist/agent/context.js +1 -1
  7. package/dist/agent/input-queue.d.ts +26 -0
  8. package/dist/agent/input-queue.js +65 -0
  9. package/dist/agent/loop.js +198 -5
  10. package/dist/agent/optimize.js +1 -1
  11. package/dist/agent/streaming-executor.d.ts +4 -0
  12. package/dist/agent/streaming-executor.js +52 -0
  13. package/dist/agent/tokens.js +2 -0
  14. package/dist/agent/tool-guard.d.ts +7 -0
  15. package/dist/agent/tool-guard.js +21 -0
  16. package/dist/agent/types.d.ts +26 -0
  17. package/dist/audit/approvals.d.ts +20 -0
  18. package/dist/audit/approvals.js +21 -0
  19. package/dist/commands/init.js +1 -1
  20. package/dist/commands/models.d.ts +11 -0
  21. package/dist/commands/models.js +157 -37
  22. package/dist/commands/start.d.ts +10 -1
  23. package/dist/commands/start.js +53 -1
  24. package/dist/events/types.d.ts +38 -1
  25. package/dist/gateway-models.d.ts +14 -2
  26. package/dist/gateway-models.js +8 -0
  27. package/dist/goal/engine.d.ts +39 -0
  28. package/dist/goal/engine.js +182 -0
  29. package/dist/goal/prompts.d.ts +16 -0
  30. package/dist/goal/prompts.js +206 -0
  31. package/dist/goal/runtime.d.ts +20 -0
  32. package/dist/goal/runtime.js +110 -0
  33. package/dist/goal/store.d.ts +22 -0
  34. package/dist/goal/store.js +79 -0
  35. package/dist/goal/types.d.ts +63 -0
  36. package/dist/goal/types.js +26 -0
  37. package/dist/hooks/loader.d.ts +19 -0
  38. package/dist/hooks/loader.js +115 -0
  39. package/dist/hooks/runner.d.ts +31 -0
  40. package/dist/hooks/runner.js +147 -0
  41. package/dist/hooks/types.d.ts +64 -0
  42. package/dist/hooks/types.js +35 -0
  43. package/dist/index.js +5 -1
  44. package/dist/learnings/extractor.js +1 -1
  45. package/dist/memory/capture.d.ts +40 -0
  46. package/dist/memory/capture.js +95 -0
  47. package/dist/memory/dream.d.ts +24 -0
  48. package/dist/memory/dream.js +147 -0
  49. package/dist/memory/indexer.d.ts +29 -0
  50. package/dist/memory/indexer.js +144 -0
  51. package/dist/memory/store.d.ts +50 -0
  52. package/dist/memory/store.js +163 -0
  53. package/dist/monitors/registry.d.ts +42 -0
  54. package/dist/monitors/registry.js +104 -0
  55. package/dist/panel/html.js +299 -0
  56. package/dist/panel/server.js +41 -0
  57. package/dist/pricing.js +4 -1
  58. package/dist/router/index.js +15 -9
  59. package/dist/router/vision.js +5 -4
  60. package/dist/scheduler/service.d.ts +24 -0
  61. package/dist/scheduler/service.js +44 -0
  62. package/dist/scheduler/store.d.ts +26 -0
  63. package/dist/scheduler/store.js +116 -0
  64. package/dist/scheduler/types.d.ts +36 -0
  65. package/dist/scheduler/types.js +31 -0
  66. package/dist/serve/agent-host.d.ts +63 -0
  67. package/dist/serve/agent-host.js +270 -0
  68. package/dist/serve/server.js +131 -2
  69. package/dist/session/live-registry.d.ts +32 -0
  70. package/dist/session/live-registry.js +83 -0
  71. package/dist/session/search.d.ts +6 -0
  72. package/dist/session/search.js +3 -3
  73. package/dist/session/storage.d.ts +6 -0
  74. package/dist/session/storage.js +6 -0
  75. package/dist/tools/goal.d.ts +7 -0
  76. package/dist/tools/goal.js +29 -0
  77. package/dist/tools/index.js +11 -0
  78. package/dist/tools/memory.js +14 -4
  79. package/dist/tools/moa.js +1 -1
  80. package/dist/tools/monitor.d.ts +11 -0
  81. package/dist/tools/monitor.js +96 -0
  82. package/dist/tools/scheduler.d.ts +12 -0
  83. package/dist/tools/scheduler.js +79 -0
  84. package/dist/tools/spend-tools.d.ts +33 -0
  85. package/dist/tools/spend-tools.js +114 -0
  86. package/dist/tools/tool-categories.js +7 -0
  87. package/dist/tools/trade-plan.d.ts +11 -0
  88. package/dist/tools/trade-plan.js +137 -0
  89. package/dist/tools/trading-execute.js +24 -0
  90. package/dist/trading/trade-plan.d.ts +75 -0
  91. package/dist/trading/trade-plan.js +290 -0
  92. package/dist/ui/app.js +54 -9
  93. package/dist/ui/model-picker.d.ts +40 -0
  94. package/dist/ui/model-picker.js +135 -25
  95. package/package.json +2 -2
  96. package/dist/agent/media-router.d.ts +0 -98
  97. package/dist/agent/media-router.js +0 -328
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Document-memory search — pure-TS chunked TF scoring (no native deps).
3
+ *
4
+ * Chunks of ~1600 chars with 320 overlap; term-frequency scoring reusing
5
+ * the session-search tokenizer; TEMPORAL DECAY applies ONLY to session-log
6
+ * chunks (half-life 7 days) — curated global/workspace/trading files are
7
+ * long-term knowledge and never decay. Old session hits carry a staleness
8
+ * note so the model verifies before trusting. An mtime-keyed cache keeps
9
+ * re-index cost at zero for unchanged files.
10
+ */
11
+ import fs from 'node:fs';
12
+ import { parseQuery, tokenize } from '../session/search.js';
13
+ import { listMemoryFiles, memoryEnabled } from './store.js';
14
+ export const CHUNK_CHARS = 1600;
15
+ export const CHUNK_OVERLAP = 320;
16
+ export const SESSION_HALF_LIFE_DAYS = 7;
17
+ const STALE_AFTER_DAYS = 3;
18
+ // mtime-keyed chunk cache per file.
19
+ const chunkCache = new Map();
20
+ export function resetMemoryIndexCache() {
21
+ chunkCache.clear();
22
+ }
23
+ function chunkFile(ref) {
24
+ const cached = chunkCache.get(ref.path);
25
+ if (cached && cached.mtimeMs === ref.mtimeMs)
26
+ return cached.chunks;
27
+ let content = '';
28
+ try {
29
+ content = fs.readFileSync(ref.path, 'utf-8');
30
+ }
31
+ catch {
32
+ return [];
33
+ }
34
+ const chunks = [];
35
+ for (let start = 0; start < content.length; start += CHUNK_CHARS - CHUNK_OVERLAP) {
36
+ const text = content.slice(start, start + CHUNK_CHARS);
37
+ if (!text.trim())
38
+ continue;
39
+ const tokens = new Map();
40
+ for (const tok of tokenize(text)) {
41
+ tokens.set(tok, (tokens.get(tok) ?? 0) + 1);
42
+ }
43
+ chunks.push({ file: ref.path, scope: ref.scope, mtimeMs: ref.mtimeMs, text, tokens });
44
+ if (text.length < CHUNK_CHARS)
45
+ break;
46
+ }
47
+ chunkCache.set(ref.path, { mtimeMs: ref.mtimeMs, chunks });
48
+ return chunks;
49
+ }
50
+ function ageDays(mtimeMs) {
51
+ return Math.max(0, (Date.now() - mtimeMs) / 86_400_000);
52
+ }
53
+ function scoreChunk(chunk, terms, phrases) {
54
+ let score = 0;
55
+ for (const term of terms) {
56
+ const tf = chunk.tokens.get(term) ?? 0;
57
+ if (tf > 0)
58
+ score += 1 + Math.log(1 + tf);
59
+ }
60
+ const lower = chunk.text.toLowerCase();
61
+ for (const phrase of phrases) {
62
+ if (lower.includes(phrase.toLowerCase()))
63
+ score += 3;
64
+ }
65
+ if (score === 0)
66
+ return 0;
67
+ if (chunk.scope === 'session') {
68
+ // Exponential half-life decay — ephemeral observations fade.
69
+ score *= Math.pow(0.5, ageDays(chunk.mtimeMs) / SESSION_HALF_LIFE_DAYS);
70
+ }
71
+ return score;
72
+ }
73
+ function snippetAround(text, terms, maxLen = 280) {
74
+ const lower = text.toLowerCase();
75
+ let at = -1;
76
+ for (const term of terms) {
77
+ at = lower.indexOf(term);
78
+ if (at !== -1)
79
+ break;
80
+ }
81
+ if (at === -1)
82
+ at = 0;
83
+ const start = Math.max(0, at - Math.floor(maxLen / 3));
84
+ const cut = text.slice(start, start + maxLen).trim();
85
+ return `${start > 0 ? '…' : ''}${cut}${start + maxLen < text.length ? '…' : ''}`;
86
+ }
87
+ export function searchMemory(query, workDir, opts = {}) {
88
+ if (!memoryEnabled())
89
+ return [];
90
+ const { terms, phrases } = parseQuery(query);
91
+ if (terms.length === 0 && phrases.length === 0)
92
+ return [];
93
+ const limit = opts.limit ?? 6;
94
+ const minScore = opts.minScore ?? 0.5;
95
+ const hits = [];
96
+ for (const ref of listMemoryFiles(workDir)) {
97
+ for (const chunk of chunkFile(ref)) {
98
+ const score = scoreChunk(chunk, terms, phrases);
99
+ if (score < minScore)
100
+ continue;
101
+ const hit = {
102
+ file: ref.path,
103
+ scope: ref.scope,
104
+ snippet: snippetAround(chunk.text, terms),
105
+ score,
106
+ };
107
+ if (ref.scope === 'session' && ageDays(ref.mtimeMs) > STALE_AFTER_DAYS) {
108
+ const days = Math.round(ageDays(ref.mtimeMs));
109
+ hit.stalenessNote = `note: this is a session memory from ~${days} days ago — verify current state before relying on it`;
110
+ }
111
+ hits.push(hit);
112
+ }
113
+ }
114
+ hits.sort((a, b) => b.score - a.score);
115
+ // One hit per file — chunk overlap otherwise floods the result set with
116
+ // near-duplicates from the same document.
117
+ const seen = new Set();
118
+ const deduped = [];
119
+ for (const hit of hits) {
120
+ if (seen.has(hit.file))
121
+ continue;
122
+ seen.add(hit.file);
123
+ deduped.push(hit);
124
+ if (deduped.length >= limit)
125
+ break;
126
+ }
127
+ return deduped;
128
+ }
129
+ /** Compact context block for prompt injection; ~1.5k-token budget. */
130
+ export function formatMemoryContext(hits, budgetChars = 6000) {
131
+ if (hits.length === 0)
132
+ return '';
133
+ const lines = ['<memory-recall>'];
134
+ let used = 0;
135
+ for (const hit of hits) {
136
+ const entry = `[${hit.scope}] ${hit.snippet}${hit.stalenessNote ? `\n (${hit.stalenessNote})` : ''}`;
137
+ if (used + entry.length > budgetChars)
138
+ break;
139
+ lines.push(entry);
140
+ used += entry.length;
141
+ }
142
+ lines.push('</memory-recall>');
143
+ return lines.length > 2 ? lines.join('\n') : '';
144
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Document memory — curated markdown files with identity-keyed scoping.
3
+ *
4
+ * Layout under ~/.blockrun/memory/:
5
+ * MEMORY.md global, cross-project facts
6
+ * <slug>-<hash8>/MEMORY.md workspace-scoped (curated)
7
+ * <slug>-<hash8>/sessions/YYYY-MM-DD-*.md per-session logs (decaying)
8
+ * trading-<chain>-<addr8>/JOURNAL.md trade journal (curated)
9
+ * trading-<chain>-<addr8>/theses/<asset>.md one thesis file per asset
10
+ *
11
+ * Identity keying: a workspace is keyed by its git origin (org/repo form)
12
+ * so clones and worktrees of the same repo share memory; non-repos fall
13
+ * back to the directory path. Trading memory is keyed by WALLET ADDRESS —
14
+ * the journal follows the money, not the directory.
15
+ *
16
+ * This subsystem is additive to the Brain entity graph (src/brain/): the
17
+ * graph answers "what do I know about entity X", documents answer "what
18
+ * was my SOL thesis" / "what did we do last week". MemoryRecall facades
19
+ * both. Kill switch: FRANKLIN_MEMORY=0.
20
+ */
21
+ export declare function memoryEnabled(): boolean;
22
+ export declare function memoryRoot(): string;
23
+ export declare function globalMemoryPath(): string;
24
+ /** org/repo from the git origin remote, or null outside a repo. */
25
+ export declare function repoIdentity(workDir: string): string | null;
26
+ export declare function workspaceKey(workDir: string): {
27
+ slug: string;
28
+ hash8: string;
29
+ };
30
+ export declare function workspaceDir(workDir: string): string;
31
+ export declare function workspaceMemoryPath(workDir: string): string;
32
+ export declare function sessionLogsDir(workDir: string): string;
33
+ export declare function tradingDir(chain: string, address: string): string;
34
+ export declare function tradingJournalPath(chain: string, address: string): string;
35
+ export declare function thesisPath(chain: string, address: string, asset: string): string;
36
+ /**
37
+ * Append a note under a markdown heading, creating file/heading as needed.
38
+ * Used by /remember and the trading capture.
39
+ */
40
+ export declare function appendUnderHeading(filePath: string, heading: string, note: string): void;
41
+ /** Dated session log path for today. */
42
+ export declare function sessionLogPath(workDir: string, sessionId: string): string;
43
+ export declare function writeSessionLog(workDir: string, sessionId: string, content: string): void;
44
+ export interface MemoryFileRef {
45
+ path: string;
46
+ /** Curated files never decay; session logs do. */
47
+ scope: 'global' | 'workspace' | 'trading' | 'session';
48
+ mtimeMs: number;
49
+ }
50
+ export declare function listMemoryFiles(workDir: string): MemoryFileRef[];
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Document memory — curated markdown files with identity-keyed scoping.
3
+ *
4
+ * Layout under ~/.blockrun/memory/:
5
+ * MEMORY.md global, cross-project facts
6
+ * <slug>-<hash8>/MEMORY.md workspace-scoped (curated)
7
+ * <slug>-<hash8>/sessions/YYYY-MM-DD-*.md per-session logs (decaying)
8
+ * trading-<chain>-<addr8>/JOURNAL.md trade journal (curated)
9
+ * trading-<chain>-<addr8>/theses/<asset>.md one thesis file per asset
10
+ *
11
+ * Identity keying: a workspace is keyed by its git origin (org/repo form)
12
+ * so clones and worktrees of the same repo share memory; non-repos fall
13
+ * back to the directory path. Trading memory is keyed by WALLET ADDRESS —
14
+ * the journal follows the money, not the directory.
15
+ *
16
+ * This subsystem is additive to the Brain entity graph (src/brain/): the
17
+ * graph answers "what do I know about entity X", documents answer "what
18
+ * was my SOL thesis" / "what did we do last week". MemoryRecall facades
19
+ * both. Kill switch: FRANKLIN_MEMORY=0.
20
+ */
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import crypto from 'node:crypto';
24
+ import { execFileSync } from 'node:child_process';
25
+ import { BLOCKRUN_DIR } from '../config.js';
26
+ export function memoryEnabled() {
27
+ return process.env.FRANKLIN_MEMORY !== '0';
28
+ }
29
+ export function memoryRoot() {
30
+ return path.join(BLOCKRUN_DIR, 'memory');
31
+ }
32
+ export function globalMemoryPath() {
33
+ return path.join(memoryRoot(), 'MEMORY.md');
34
+ }
35
+ // ─── Identity keying ───────────────────────────────────────────────────────
36
+ function slugify(text) {
37
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) || 'workspace';
38
+ }
39
+ /** org/repo from the git origin remote, or null outside a repo. */
40
+ export function repoIdentity(workDir) {
41
+ try {
42
+ const url = execFileSync('git', ['-C', workDir, 'remote', 'get-url', 'origin'], {
43
+ encoding: 'utf-8',
44
+ timeout: 2000,
45
+ stdio: ['ignore', 'pipe', 'ignore'],
46
+ }).trim();
47
+ const m = url.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/);
48
+ return m ? m[1] : url || null;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ export function workspaceKey(workDir) {
55
+ const identity = repoIdentity(workDir) ?? workDir;
56
+ return {
57
+ slug: slugify(path.basename(identity)),
58
+ hash8: crypto.createHash('sha256').update(identity).digest('hex').slice(0, 8),
59
+ };
60
+ }
61
+ export function workspaceDir(workDir) {
62
+ const { slug, hash8 } = workspaceKey(workDir);
63
+ return path.join(memoryRoot(), `${slug}-${hash8}`);
64
+ }
65
+ export function workspaceMemoryPath(workDir) {
66
+ return path.join(workspaceDir(workDir), 'MEMORY.md');
67
+ }
68
+ export function sessionLogsDir(workDir) {
69
+ return path.join(workspaceDir(workDir), 'sessions');
70
+ }
71
+ export function tradingDir(chain, address) {
72
+ return path.join(memoryRoot(), `trading-${chain}-${address.slice(0, 8).toLowerCase()}`);
73
+ }
74
+ export function tradingJournalPath(chain, address) {
75
+ return path.join(tradingDir(chain, address), 'JOURNAL.md');
76
+ }
77
+ export function thesisPath(chain, address, asset) {
78
+ return path.join(tradingDir(chain, address), 'theses', `${slugify(asset)}.md`);
79
+ }
80
+ // ─── Writes ────────────────────────────────────────────────────────────────
81
+ function appendToFile(filePath, text) {
82
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
83
+ fs.appendFileSync(filePath, text.endsWith('\n') ? text : text + '\n');
84
+ }
85
+ /**
86
+ * Append a note under a markdown heading, creating file/heading as needed.
87
+ * Used by /remember and the trading capture.
88
+ */
89
+ export function appendUnderHeading(filePath, heading, note) {
90
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
91
+ const stamp = new Date().toISOString().slice(0, 10);
92
+ const line = `- (${stamp}) ${note.trim()}`;
93
+ let content = '';
94
+ try {
95
+ content = fs.readFileSync(filePath, 'utf-8');
96
+ }
97
+ catch { /* new file */ }
98
+ const headingLine = `## ${heading}`;
99
+ if (!content.includes(headingLine)) {
100
+ appendToFile(filePath, `${content && !content.endsWith('\n') ? '\n' : ''}${headingLine}\n${line}`);
101
+ return;
102
+ }
103
+ // Insert directly after the heading's existing block (before the next ##).
104
+ const lines = content.split('\n');
105
+ const idx = lines.findIndex(l => l.trim() === headingLine);
106
+ let insertAt = lines.length;
107
+ for (let i = idx + 1; i < lines.length; i++) {
108
+ if (lines[i].startsWith('## ')) {
109
+ insertAt = i;
110
+ break;
111
+ }
112
+ }
113
+ lines.splice(insertAt, 0, line);
114
+ fs.writeFileSync(filePath, lines.join('\n'));
115
+ }
116
+ /** Dated session log path for today. */
117
+ export function sessionLogPath(workDir, sessionId) {
118
+ const day = new Date().toISOString().slice(0, 10);
119
+ return path.join(sessionLogsDir(workDir), `${day}-${sessionId.slice(0, 8)}.md`);
120
+ }
121
+ export function writeSessionLog(workDir, sessionId, content) {
122
+ const p = sessionLogPath(workDir, sessionId);
123
+ fs.mkdirSync(path.dirname(p), { recursive: true });
124
+ fs.writeFileSync(p, content.endsWith('\n') ? content : content + '\n');
125
+ }
126
+ export function listMemoryFiles(workDir) {
127
+ const refs = [];
128
+ const push = (p, scope) => {
129
+ try {
130
+ const stat = fs.statSync(p);
131
+ if (stat.isFile())
132
+ refs.push({ path: p, scope, mtimeMs: stat.mtimeMs });
133
+ }
134
+ catch { /* missing */ }
135
+ };
136
+ push(globalMemoryPath(), 'global');
137
+ push(workspaceMemoryPath(workDir), 'workspace');
138
+ try {
139
+ for (const f of fs.readdirSync(sessionLogsDir(workDir))) {
140
+ if (f.endsWith('.md'))
141
+ push(path.join(sessionLogsDir(workDir), f), 'session');
142
+ }
143
+ }
144
+ catch { /* no session logs yet */ }
145
+ // Every trading identity the user has — journals + theses.
146
+ try {
147
+ for (const dir of fs.readdirSync(memoryRoot())) {
148
+ if (!dir.startsWith('trading-'))
149
+ continue;
150
+ const base = path.join(memoryRoot(), dir);
151
+ push(path.join(base, 'JOURNAL.md'), 'trading');
152
+ try {
153
+ for (const f of fs.readdirSync(path.join(base, 'theses'))) {
154
+ if (f.endsWith('.md'))
155
+ push(path.join(base, 'theses', f), 'trading');
156
+ }
157
+ }
158
+ catch { /* no theses */ }
159
+ }
160
+ }
161
+ catch { /* no memory root yet */ }
162
+ return refs;
163
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Monitor registry — session-scoped bookkeeping for line-oriented monitors.
3
+ *
4
+ * A monitor is a detached background command (task subsystem) whose log is
5
+ * swept at turn boundaries; new lines land in the next turn's user content
6
+ * as a bracketed block. The registry owns read offsets so the task-side
7
+ * meta.json single-writer contract (runner only) stays intact.
8
+ *
9
+ * Volume cutoff: a monitor producing more than MAX_LINES_PER_SWEEP lines in
10
+ * one sweep, or MAX_EVENTS_PER_SESSION lines overall, is auto-paused with a
11
+ * note — a flooding monitor must not drown the conversation. Restart it
12
+ * with a tighter filter pattern instead.
13
+ */
14
+ export declare const MAX_LINES_PER_SWEEP = 50;
15
+ export declare const MAX_EVENTS_PER_SESSION = 200;
16
+ export interface MonitorEntry {
17
+ taskRunId: string;
18
+ label: string;
19
+ pattern?: RegExp;
20
+ byteOffset: number;
21
+ eventsDelivered: number;
22
+ paused: boolean;
23
+ pausedReason?: string;
24
+ }
25
+ export declare function resetMonitors(): void;
26
+ export declare function registerMonitor(entry: {
27
+ taskRunId: string;
28
+ label: string;
29
+ pattern?: RegExp;
30
+ }): void;
31
+ export declare function getMonitor(taskRunId: string): MonitorEntry | undefined;
32
+ export declare function removeMonitor(taskRunId: string): boolean;
33
+ export declare function listMonitors(): MonitorEntry[];
34
+ export interface MonitorSweepResult {
35
+ /** Ready-to-append blocks, one per monitor with fresh lines. */
36
+ blocks: string[];
37
+ }
38
+ /**
39
+ * Read fresh log lines for every active monitor. Called at turn boundaries
40
+ * by the agent loop; safe to call often (offset-tracked, no re-reads).
41
+ */
42
+ export declare function sweepMonitors(): MonitorSweepResult;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Monitor registry — session-scoped bookkeeping for line-oriented monitors.
3
+ *
4
+ * A monitor is a detached background command (task subsystem) whose log is
5
+ * swept at turn boundaries; new lines land in the next turn's user content
6
+ * as a bracketed block. The registry owns read offsets so the task-side
7
+ * meta.json single-writer contract (runner only) stays intact.
8
+ *
9
+ * Volume cutoff: a monitor producing more than MAX_LINES_PER_SWEEP lines in
10
+ * one sweep, or MAX_EVENTS_PER_SESSION lines overall, is auto-paused with a
11
+ * note — a flooding monitor must not drown the conversation. Restart it
12
+ * with a tighter filter pattern instead.
13
+ */
14
+ import fs from 'node:fs';
15
+ import { taskLogPath } from '../tasks/paths.js';
16
+ import { readTaskMeta } from '../tasks/store.js';
17
+ import { isTerminalTaskStatus } from '../tasks/types.js';
18
+ export const MAX_LINES_PER_SWEEP = 50;
19
+ export const MAX_EVENTS_PER_SESSION = 200;
20
+ const monitors = new Map();
21
+ export function resetMonitors() {
22
+ monitors.clear();
23
+ }
24
+ export function registerMonitor(entry) {
25
+ monitors.set(entry.taskRunId, {
26
+ ...entry,
27
+ byteOffset: 0,
28
+ eventsDelivered: 0,
29
+ paused: false,
30
+ });
31
+ }
32
+ export function getMonitor(taskRunId) {
33
+ return monitors.get(taskRunId);
34
+ }
35
+ export function removeMonitor(taskRunId) {
36
+ return monitors.delete(taskRunId);
37
+ }
38
+ export function listMonitors() {
39
+ return [...monitors.values()];
40
+ }
41
+ /**
42
+ * Read fresh log lines for every active monitor. Called at turn boundaries
43
+ * by the agent loop; safe to call often (offset-tracked, no re-reads).
44
+ */
45
+ export function sweepMonitors() {
46
+ const blocks = [];
47
+ for (const entry of monitors.values()) {
48
+ if (entry.paused)
49
+ continue;
50
+ const meta = readTaskMeta(entry.taskRunId);
51
+ const logPath = taskLogPath(entry.taskRunId);
52
+ let fresh = '';
53
+ try {
54
+ const stat = fs.statSync(logPath);
55
+ if (stat.size > entry.byteOffset) {
56
+ const fd = fs.openSync(logPath, 'r');
57
+ try {
58
+ const len = stat.size - entry.byteOffset;
59
+ const buf = Buffer.alloc(len);
60
+ fs.readSync(fd, buf, 0, len, entry.byteOffset);
61
+ fresh = buf.toString('utf-8');
62
+ }
63
+ finally {
64
+ fs.closeSync(fd);
65
+ }
66
+ entry.byteOffset = stat.size;
67
+ }
68
+ }
69
+ catch {
70
+ /* log not readable yet — nothing fresh */
71
+ }
72
+ let lines = fresh.split('\n').map(l => l.trimEnd()).filter(l => l.length > 0);
73
+ if (entry.pattern) {
74
+ const re = entry.pattern;
75
+ lines = lines.filter(l => re.test(l));
76
+ }
77
+ const ended = meta ? isTerminalTaskStatus(meta.status) : false;
78
+ if (lines.length > MAX_LINES_PER_SWEEP) {
79
+ const dropped = lines.length - MAX_LINES_PER_SWEEP;
80
+ lines = lines.slice(0, MAX_LINES_PER_SWEEP);
81
+ entry.paused = true;
82
+ entry.pausedReason = `flooded (${dropped} lines dropped in one sweep) — restart with a tighter filter pattern`;
83
+ }
84
+ entry.eventsDelivered += lines.length;
85
+ if (!entry.paused && entry.eventsDelivered > MAX_EVENTS_PER_SESSION) {
86
+ entry.paused = true;
87
+ entry.pausedReason = `delivered ${entry.eventsDelivered} events this session — restart with a tighter filter pattern`;
88
+ }
89
+ if (lines.length > 0 || ended || entry.paused) {
90
+ const parts = [];
91
+ if (lines.length > 0)
92
+ parts.push(lines.join('\n'));
93
+ if (entry.paused)
94
+ parts.push(`(monitor auto-paused: ${entry.pausedReason})`);
95
+ if (ended && meta) {
96
+ parts.push(`(monitored command ended: ${meta.status}${meta.exitCode != null ? `, exit ${meta.exitCode}` : ''})`);
97
+ }
98
+ blocks.push(`[monitor: ${entry.label}]\n${parts.join('\n')}`);
99
+ }
100
+ if (ended)
101
+ monitors.delete(entry.taskRunId);
102
+ }
103
+ return { blocks };
104
+ }