@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,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
  };
package/dist/tools/moa.js CHANGED
@@ -15,7 +15,7 @@ import { ModelClient } from '../agent/llm.js';
15
15
  /** Reference models — diverse, cheap/free models for parallel queries. */
16
16
  const REFERENCE_MODELS = [
17
17
  'nvidia/qwen3-next-80b-a3b-instruct', // Free, clean instruction-follower
18
- 'nvidia/llama-4-maverick', // Free, agent-tested general chat (diverse family)
18
+ 'nvidia/mistral-nemotron', // Free, diverse family (maverick left the catalog 2026-07-14)
19
19
  'google/gemini-2.5-flash', // Fast, cheap
20
20
  'deepseek/deepseek-chat', // Cheap, good reasoning
21
21
  ];
@@ -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;
@@ -0,0 +1,79 @@
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 { createScheduledTask, deleteScheduledTask, listScheduledTasks, } from '../scheduler/store.js';
10
+ import { formatInterval, MIN_INTERVAL_SEC } from '../scheduler/types.js';
11
+ export function createSchedulerCapability(opts) {
12
+ return {
13
+ spec: {
14
+ name: 'Scheduler',
15
+ description: 'Schedule prompts to fire later as if the user typed them. Actions: ' +
16
+ '"create" (needs prompt + interval_sec; optional recurring=true, durable=true, fire_immediately=false), ' +
17
+ '"list", "delete" (needs task_id). Recurring tasks repeat every interval; one-shot tasks fire once. ' +
18
+ 'Durable tasks survive restarts and catch up a missed firing at the next session start. ' +
19
+ `Minimum interval ${MIN_INTERVAL_SEC}s. Tasks auto-expire after 7 days. ` +
20
+ 'Use for periodic checks (prices, positions, feeds) instead of sleep-polling in Bash.',
21
+ input_schema: {
22
+ type: 'object',
23
+ properties: {
24
+ action: { type: 'string', enum: ['create', 'list', 'delete'], description: 'Operation to perform.' },
25
+ prompt: { type: 'string', description: 'create: the prompt to fire.' },
26
+ interval_sec: { type: 'number', description: `create: seconds between firings (min ${MIN_INTERVAL_SEC}).` },
27
+ recurring: { type: 'boolean', description: 'create: repeat every interval (default true). false = fire once.' },
28
+ durable: { type: 'boolean', description: 'create: survive across sessions (default true).' },
29
+ fire_immediately: { type: 'boolean', description: 'create: fire at the next turn boundary too (default false).' },
30
+ task_id: { type: 'string', description: 'delete: id of the task to remove.' },
31
+ },
32
+ required: ['action'],
33
+ },
34
+ },
35
+ concurrent: true,
36
+ execute: async (input) => {
37
+ const action = String(input.action || '');
38
+ if (action === 'create') {
39
+ const intervalSec = Number(input.interval_sec);
40
+ if (!Number.isFinite(intervalSec)) {
41
+ return { output: 'Error: interval_sec is required for create.', isError: true };
42
+ }
43
+ const result = createScheduledTask({
44
+ prompt: String(input.prompt || ''),
45
+ intervalSec,
46
+ sessionId: opts.sessionId(),
47
+ recurring: input.recurring !== false,
48
+ durable: input.durable !== false,
49
+ fireImmediately: input.fire_immediately === true,
50
+ });
51
+ if ('error' in result)
52
+ return { output: `Error: ${result.error}`, isError: true };
53
+ return {
54
+ output: `Scheduled task ${result.id}: every ${formatInterval(result.intervalSec)}, ` +
55
+ `${result.recurring ? 'recurring' : 'one-shot'}, ${result.durable ? 'durable' : 'session-only'}, ` +
56
+ `next firing ${new Date(result.nextFireAt).toISOString()}, expires ${new Date(result.expiresAt).toISOString()}.`,
57
+ };
58
+ }
59
+ if (action === 'list') {
60
+ const tasks = listScheduledTasks();
61
+ if (tasks.length === 0)
62
+ return { output: 'No scheduled tasks.' };
63
+ const lines = tasks.map(t => `${t.id} · every ${formatInterval(t.intervalSec)} · ${t.recurring ? 'recurring' : 'one-shot'}` +
64
+ `${t.durable ? '' : ' · session-only'} · fired ${t.firedCount}× · next ${new Date(t.nextFireAt).toISOString()}` +
65
+ `\n ${t.prompt.slice(0, 140)}`);
66
+ return { output: `${tasks.length} scheduled task(s):\n${lines.join('\n')}` };
67
+ }
68
+ if (action === 'delete') {
69
+ const id = String(input.task_id || '');
70
+ if (!id)
71
+ return { output: 'Error: task_id is required for delete.', isError: true };
72
+ return deleteScheduledTask(id)
73
+ ? { output: `Deleted scheduled task ${id}.` }
74
+ : { output: `No scheduled task ${id}.`, isError: true };
75
+ }
76
+ return { output: `Unknown action "${action}". Use create, list, or delete.`, isError: true };
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Spend-tool registry — which capabilities move real money, and how much.
3
+ *
4
+ * Two consumers:
5
+ * 1. HookEngine — PreSpend/PostSpend events fire only for tools listed here,
6
+ * carrying the estimated USD amount so user hooks can enforce caps and
7
+ * blacklists without parsing tool-specific inputs.
8
+ * 2. Trade-plan gating — the trade-execution subset must be covered by an
9
+ * approved trade plan before it can execute.
10
+ *
11
+ * Estimators are conservative: they return a USD number only when the input
12
+ * denominates the spend directly (stablecoin in, explicit USD field, or a
13
+ * known flat price). Anything else returns null = "unknown amount" — hooks
14
+ * still fire and can decide policy for unpriceable spends.
15
+ *
16
+ * Stable-mint tables intentionally mirror the per-tool confirm logic in
17
+ * jupiter.ts / zerox-base.ts (stables price 1:1, everything else unknown).
18
+ */
19
+ type SpendInput = Record<string, unknown>;
20
+ /**
21
+ * Tool name → USD estimator. Presence in this map is what marks a tool as
22
+ * spendful; the estimator may still return null (unknown amount).
23
+ */
24
+ export declare const SPEND_TOOLS: Readonly<Record<string, (input: SpendInput) => number | null>>;
25
+ /**
26
+ * The subset whose invocations are trades — used by the trade-plan gate.
27
+ * PolymarketBet is trade-gated only for order placement (buy/sell with
28
+ * confirm), which the gate itself checks via the invocation input.
29
+ */
30
+ export declare const TRADE_EXECUTION_TOOLS: ReadonlySet<string>;
31
+ export declare function isSpendTool(name: string): boolean;
32
+ export declare function estimateSpendUsd(name: string, input: SpendInput): number | null;
33
+ export {};