@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,116 @@
1
+ /**
2
+ * Scheduler persistence — one JSON file per task under
3
+ * ~/.blockrun/scheduler/<id>.json, atomically rewritten (tmp + rename),
4
+ * mirroring the task subsystem's meta.json convention.
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import crypto from 'node:crypto';
9
+ import { BLOCKRUN_DIR } from '../config.js';
10
+ import { DEFAULT_TTL_MS, MAX_LIVE_TASKS, MIN_INTERVAL_SEC, } from './types.js';
11
+ export function schedulerDir() {
12
+ return path.join(BLOCKRUN_DIR, 'scheduler');
13
+ }
14
+ // The Scheduler capability is constructed once at module load (allCapabilities),
15
+ // before any session exists — the current session id is threaded through this
16
+ // setter by the agent loop at session start instead of through the factory.
17
+ let currentSessionId = 'default';
18
+ export function setSchedulerSessionId(id) {
19
+ currentSessionId = id;
20
+ }
21
+ export function getSchedulerSessionId() {
22
+ return currentSessionId;
23
+ }
24
+ function taskPath(id) {
25
+ return path.join(schedulerDir(), `${id}.json`);
26
+ }
27
+ export function saveScheduledTask(task) {
28
+ const dir = schedulerDir();
29
+ fs.mkdirSync(dir, { recursive: true });
30
+ const tmp = path.join(dir, `.${task.id}.tmp`);
31
+ fs.writeFileSync(tmp, JSON.stringify(task, null, 2));
32
+ fs.renameSync(tmp, taskPath(task.id));
33
+ }
34
+ export function deleteScheduledTask(id) {
35
+ try {
36
+ fs.unlinkSync(taskPath(id));
37
+ return true;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ /** All non-expired tasks, pruning expired files as a side effect. */
44
+ export function listScheduledTasks() {
45
+ let files;
46
+ try {
47
+ files = fs.readdirSync(schedulerDir()).filter(f => f.endsWith('.json'));
48
+ }
49
+ catch {
50
+ return [];
51
+ }
52
+ const now = Date.now();
53
+ const tasks = [];
54
+ for (const file of files) {
55
+ try {
56
+ const task = JSON.parse(fs.readFileSync(path.join(schedulerDir(), file), 'utf-8'));
57
+ if (!task?.id || typeof task.prompt !== 'string')
58
+ continue;
59
+ if (task.expiresAt <= now) {
60
+ deleteScheduledTask(task.id); // expired — prune
61
+ continue;
62
+ }
63
+ tasks.push(task);
64
+ }
65
+ catch {
66
+ /* skip unreadable entries */
67
+ }
68
+ }
69
+ return tasks.sort((a, b) => a.nextFireAt - b.nextFireAt);
70
+ }
71
+ export function createScheduledTask(opts) {
72
+ const prompt = opts.prompt.trim();
73
+ if (!prompt)
74
+ return { error: 'prompt must not be empty' };
75
+ const intervalSec = Math.max(MIN_INTERVAL_SEC, Math.floor(opts.intervalSec));
76
+ const live = listScheduledTasks();
77
+ if (live.length >= MAX_LIVE_TASKS) {
78
+ return { error: `scheduler is full (${MAX_LIVE_TASKS} tasks) — delete one first` };
79
+ }
80
+ const now = Date.now();
81
+ const task = {
82
+ id: crypto.randomBytes(6).toString('hex'),
83
+ prompt,
84
+ intervalSec,
85
+ recurring: opts.recurring ?? true,
86
+ durable: opts.durable ?? true,
87
+ createdAt: now,
88
+ expiresAt: now + (opts.ttlMs ?? DEFAULT_TTL_MS),
89
+ nextFireAt: opts.fireImmediately ? now : now + intervalSec * 1000,
90
+ firedCount: 0,
91
+ enabled: true,
92
+ sessionId: opts.sessionId,
93
+ };
94
+ saveScheduledTask(task);
95
+ return task;
96
+ }
97
+ /** Record a firing: advance nextFireAt, or disable a one-shot. */
98
+ export function markFired(task) {
99
+ const now = Date.now();
100
+ const updated = {
101
+ ...task,
102
+ lastFiredAt: now,
103
+ firedCount: task.firedCount + 1,
104
+ // Anchor the next slot to now, not to the missed slot — a task that
105
+ // slept through 10 intervals fires once, not 10 times.
106
+ nextFireAt: now + task.intervalSec * 1000,
107
+ enabled: task.recurring,
108
+ };
109
+ if (!updated.enabled) {
110
+ deleteScheduledTask(task.id);
111
+ }
112
+ else {
113
+ saveScheduledTask(updated);
114
+ }
115
+ return updated;
116
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Durable prompt scheduler — recurring or one-shot prompts that fire as
3
+ * synthetic user inputs at turn boundaries (via the input multiplexer).
4
+ */
5
+ export interface ScheduledTask {
6
+ id: string;
7
+ prompt: string;
8
+ /** Seconds between firings. Minimum 60. */
9
+ intervalSec: number;
10
+ /** Recurring tasks re-arm after each firing; one-shots disable. */
11
+ recurring: boolean;
12
+ /**
13
+ * Durable tasks persist across sessions: if a firing was missed while no
14
+ * session was running, the next session start fires it once (catch-up).
15
+ * Non-durable tasks live only as long as the session that created them.
16
+ */
17
+ durable: boolean;
18
+ createdAt: number;
19
+ /** Hard expiry — the task stops firing and is pruned after this. */
20
+ expiresAt: number;
21
+ nextFireAt: number;
22
+ lastFiredAt?: number;
23
+ firedCount: number;
24
+ enabled: boolean;
25
+ /** Session that created the task — owner of non-durable tasks. */
26
+ sessionId: string;
27
+ }
28
+ export declare const MIN_INTERVAL_SEC = 60;
29
+ export declare const MAX_LIVE_TASKS = 50;
30
+ export declare const DEFAULT_TTL_MS: number;
31
+ /**
32
+ * Parse "90s" / "5m" / "2h" / "1d" into seconds. Bare numbers are seconds.
33
+ * Returns null for unparseable input; callers surface usage help.
34
+ */
35
+ export declare function parseInterval(text: string): number | null;
36
+ export declare function formatInterval(sec: number): string;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Durable prompt scheduler — recurring or one-shot prompts that fire as
3
+ * synthetic user inputs at turn boundaries (via the input multiplexer).
4
+ */
5
+ export const MIN_INTERVAL_SEC = 60;
6
+ export const MAX_LIVE_TASKS = 50;
7
+ export const DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1000; // auto-expire after 7 days
8
+ /**
9
+ * Parse "90s" / "5m" / "2h" / "1d" into seconds. Bare numbers are seconds.
10
+ * Returns null for unparseable input; callers surface usage help.
11
+ */
12
+ export function parseInterval(text) {
13
+ const m = /^(\d+)\s*([smhd]?)$/i.exec(text.trim());
14
+ if (!m)
15
+ return null;
16
+ const n = Number(m[1]);
17
+ if (!Number.isFinite(n) || n <= 0)
18
+ return null;
19
+ const unit = (m[2] || 's').toLowerCase();
20
+ const mult = unit === 's' ? 1 : unit === 'm' ? 60 : unit === 'h' ? 3600 : 86400;
21
+ return n * mult;
22
+ }
23
+ export function formatInterval(sec) {
24
+ if (sec % 86400 === 0)
25
+ return `${sec / 86400}d`;
26
+ if (sec % 3600 === 0)
27
+ return `${sec / 3600}h`;
28
+ if (sec % 60 === 0)
29
+ return `${sec / 60}m`;
30
+ return `${sec}s`;
31
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * AgentHost — multiplexes many interactiveSession loops in one serve
3
+ * process: dispatch new agents, reply to running ones, stream their
4
+ * events to subscribers, and answer their permission/approval requests
5
+ * remotely (the parked-Promise broker pattern).
6
+ *
7
+ * Unlike the legacy single-window desktop path (which runs in trust
8
+ * mode), hosted agents default to permissionMode 'default' — permission
9
+ * prompts and trade-plan approvals surface as ApprovalRequests a
10
+ * dashboard client answers over the wire.
11
+ *
12
+ * Known v1 constraint: a few session-scoped subsystems keep module-level
13
+ * state (monitor registry, scheduler/goal current-session slots, tool
14
+ * dedup caches reset at session start). Concurrent hosted agents share a
15
+ * process, so those degrade last-writer-wins across agents — dedup may
16
+ * miss, monitors/goals are effectively single-agent features here. The
17
+ * money paths (trade-plan gate, spend caps) take explicit session ids
18
+ * and stay correct under concurrency.
19
+ */
20
+ import { type ApprovalRequest } from '../agent/approvals.js';
21
+ import { type AgentRunState } from '../events/types.js';
22
+ import type { AgentConfig, StreamEvent } from '../agent/types.js';
23
+ export interface DispatchOptions {
24
+ prompt: string;
25
+ model?: string;
26
+ label?: string;
27
+ maxSpendUsd?: number;
28
+ /** Default 'default' — permission prompts flow to the dashboard. */
29
+ permissionMode?: AgentConfig['permissionMode'];
30
+ }
31
+ export interface AgentSummary {
32
+ sessionId: string;
33
+ label: string;
34
+ model: string;
35
+ state: AgentRunState;
36
+ startedAt: number;
37
+ lastEventAt: number;
38
+ pendingApprovals: ApprovalRequest[];
39
+ }
40
+ export declare class AgentHost {
41
+ private opts;
42
+ private agents;
43
+ constructor(opts: {
44
+ workDir: string;
45
+ chain: 'base' | 'solana';
46
+ apiUrl: string;
47
+ defaultModel: string;
48
+ debug?: boolean;
49
+ });
50
+ private setState;
51
+ /** Start a new hosted agent; resolves with its sessionId once known. */
52
+ dispatch(options: DispatchOptions): Promise<string>;
53
+ list(): AgentSummary[];
54
+ get(sessionId: string): AgentSummary | null;
55
+ /** Queue a follow-up prompt for a hosted agent (idle → starts a turn). */
56
+ reply(sessionId: string, text: string): boolean;
57
+ cancel(sessionId: string): boolean;
58
+ respond(sessionId: string, requestId: string, choice: string, message?: string): boolean;
59
+ subscribe(sessionId: string, cb: (event: StreamEvent) => void): (() => void) | null;
60
+ /** Ring-buffer replay for peek panels. */
61
+ output(sessionId: string): StreamEvent[];
62
+ shutdown(): void;
63
+ }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * AgentHost — multiplexes many interactiveSession loops in one serve
3
+ * process: dispatch new agents, reply to running ones, stream their
4
+ * events to subscribers, and answer their permission/approval requests
5
+ * remotely (the parked-Promise broker pattern).
6
+ *
7
+ * Unlike the legacy single-window desktop path (which runs in trust
8
+ * mode), hosted agents default to permissionMode 'default' — permission
9
+ * prompts and trade-plan approvals surface as ApprovalRequests a
10
+ * dashboard client answers over the wire.
11
+ *
12
+ * Known v1 constraint: a few session-scoped subsystems keep module-level
13
+ * state (monitor registry, scheduler/goal current-session slots, tool
14
+ * dedup caches reset at session start). Concurrent hosted agents share a
15
+ * process, so those degrade last-writer-wins across agents — dedup may
16
+ * miss, monitors/goals are effectively single-agent features here. The
17
+ * money paths (trade-plan gate, spend caps) take explicit session ids
18
+ * and stay correct under concurrency.
19
+ */
20
+ import { EventEmitter } from 'node:events';
21
+ import { assembleInstructions } from '../agent/context.js';
22
+ import { interactiveSession } from '../agent/loop.js';
23
+ import { allCapabilities, createSubAgentCapability } from '../tools/index.js';
24
+ import { ApprovalBroker } from '../agent/approvals.js';
25
+ import { bus, } from '../events/bus.js';
26
+ import { makeEvent } from '../events/types.js';
27
+ import { writeLiveAgent } from '../session/live-registry.js';
28
+ const RING_BUFFER_SIZE = 200;
29
+ export class AgentHost {
30
+ opts;
31
+ agents = new Map();
32
+ constructor(opts) {
33
+ this.opts = opts;
34
+ }
35
+ setState(agent, state) {
36
+ if (agent.state === state)
37
+ return;
38
+ agent.state = state;
39
+ agent.lastEventAt = Date.now();
40
+ writeLiveAgent({
41
+ sessionId: agent.sessionId,
42
+ pid: process.pid,
43
+ state,
44
+ label: agent.label,
45
+ model: agent.model,
46
+ host: 'serve',
47
+ startedAt: agent.startedAt,
48
+ updatedAt: Date.now(),
49
+ pendingApprovals: agent.broker.pending().length,
50
+ });
51
+ void bus.emit(makeEvent({
52
+ type: 'agent.state',
53
+ source: 'core',
54
+ data: { sessionId: agent.sessionId, state, label: agent.label, model: agent.model },
55
+ }));
56
+ }
57
+ /** Start a new hosted agent; resolves with its sessionId once known. */
58
+ async dispatch(options) {
59
+ const prompt = options.prompt.trim();
60
+ if (!prompt)
61
+ throw new Error('prompt must not be empty');
62
+ const model = options.model || this.opts.defaultModel;
63
+ const label = options.label?.trim() || prompt.replace(/\s+/g, ' ').slice(0, 60);
64
+ // Per-agent input queue (same contract the loop's own multiplexer wraps).
65
+ const queue = [];
66
+ let resolver = null;
67
+ let ended = false;
68
+ const getUserInput = () => new Promise(resolve => {
69
+ if (queue.length > 0)
70
+ return resolve(queue.shift());
71
+ if (ended)
72
+ return resolve(null);
73
+ resolver = resolve;
74
+ });
75
+ const deliver = (v) => {
76
+ if (resolver) {
77
+ const r = resolver;
78
+ resolver = null;
79
+ r(v);
80
+ }
81
+ else if (v !== null) {
82
+ queue.push(v);
83
+ }
84
+ else {
85
+ ended = true;
86
+ }
87
+ };
88
+ const agent = {
89
+ sessionId: '',
90
+ label,
91
+ model,
92
+ state: 'working',
93
+ startedAt: Date.now(),
94
+ lastEventAt: Date.now(),
95
+ broker: new ApprovalBroker(),
96
+ recent: [],
97
+ emitter: new EventEmitter(),
98
+ pushInput: (text) => deliver(text),
99
+ endInput: () => deliver(null),
100
+ };
101
+ agent.emitter.setMaxListeners(50);
102
+ // Approvals park the agent in needs-input until a client responds.
103
+ agent.broker.onRequest(req => {
104
+ this.setState(agent, 'needs-input');
105
+ void bus.emit(makeEvent({
106
+ type: 'approval.requested',
107
+ source: 'core',
108
+ data: {
109
+ sessionId: agent.sessionId,
110
+ requestId: req.requestId,
111
+ kind: req.kind,
112
+ title: req.title,
113
+ options: req.options,
114
+ },
115
+ }));
116
+ });
117
+ let sessionIdResolve;
118
+ const sessionIdReady = new Promise(resolve => {
119
+ sessionIdResolve = resolve;
120
+ });
121
+ const onEvent = (event) => {
122
+ agent.lastEventAt = Date.now();
123
+ agent.recent.push(event);
124
+ if (agent.recent.length > RING_BUFFER_SIZE)
125
+ agent.recent.shift();
126
+ agent.emitter.emit('event', event);
127
+ if (event.kind === 'turn_done') {
128
+ this.setState(agent, event.reason === 'completed' ? 'idle' : agent.state);
129
+ void bus.emit(makeEvent({
130
+ type: 'agent.turn',
131
+ source: 'core',
132
+ data: { sessionId: agent.sessionId, phase: 'done', reason: event.reason },
133
+ }));
134
+ }
135
+ };
136
+ const systemInstructions = assembleInstructions(this.opts.workDir, model);
137
+ const subAgent = createSubAgentCapability(this.opts.apiUrl, this.opts.chain, allCapabilities, model);
138
+ const config = {
139
+ model,
140
+ apiUrl: this.opts.apiUrl,
141
+ chain: this.opts.chain,
142
+ systemInstructions,
143
+ capabilities: [...allCapabilities, subAgent],
144
+ maxTurns: 100,
145
+ workingDir: this.opts.workDir,
146
+ permissionMode: options.permissionMode ?? 'default',
147
+ debug: !!this.opts.debug,
148
+ showPrefetchStatus: false,
149
+ ...(options.maxSpendUsd != null ? { maxSpendUsd: options.maxSpendUsd } : {}),
150
+ onSessionStart: (sessionId) => {
151
+ agent.sessionId = sessionId;
152
+ this.agents.set(sessionId, agent);
153
+ this.setState(agent, 'working');
154
+ sessionIdResolve(sessionId);
155
+ },
156
+ // Remote answering: park on the broker; a dashboard client resolves.
157
+ permissionPromptFn: async (toolName, description) => {
158
+ const decision = await agent.broker.request({
159
+ sessionId: agent.sessionId,
160
+ kind: 'tool-permission',
161
+ title: `Allow ${toolName}?`,
162
+ description,
163
+ options: ['yes', 'no', 'always'],
164
+ });
165
+ this.setState(agent, 'working');
166
+ const choice = decision.choice.toLowerCase();
167
+ return choice === 'yes' || choice === 'always' ? choice : 'no';
168
+ },
169
+ onAskUser: async (question, options2) => {
170
+ const decision = await agent.broker.request({
171
+ sessionId: agent.sessionId,
172
+ kind: 'ask-user',
173
+ title: 'Agent question',
174
+ description: question,
175
+ options: options2 && options2.length ? options2 : [],
176
+ });
177
+ this.setState(agent, 'working');
178
+ return decision.message ?? decision.choice;
179
+ },
180
+ approvalPromptFn: async (req) => {
181
+ const decision = await agent.broker.request({ ...req, sessionId: agent.sessionId });
182
+ this.setState(agent, 'working');
183
+ return decision;
184
+ },
185
+ };
186
+ interactiveSession(config, getUserInput, onEvent, (abort) => { agent.abort = abort; })
187
+ .then(() => this.setState(agent, 'completed'))
188
+ .catch(() => this.setState(agent, 'failed'))
189
+ .finally(() => {
190
+ agent.broker.cancelAll('agent ended');
191
+ });
192
+ agent.pushInput(prompt);
193
+ return sessionIdReady;
194
+ }
195
+ list() {
196
+ return [...this.agents.values()].map(a => ({
197
+ sessionId: a.sessionId,
198
+ label: a.label,
199
+ model: a.model,
200
+ state: a.state,
201
+ startedAt: a.startedAt,
202
+ lastEventAt: a.lastEventAt,
203
+ pendingApprovals: a.broker.pending(),
204
+ }));
205
+ }
206
+ get(sessionId) {
207
+ const a = this.agents.get(sessionId);
208
+ return a
209
+ ? {
210
+ sessionId: a.sessionId,
211
+ label: a.label,
212
+ model: a.model,
213
+ state: a.state,
214
+ startedAt: a.startedAt,
215
+ lastEventAt: a.lastEventAt,
216
+ pendingApprovals: a.broker.pending(),
217
+ }
218
+ : null;
219
+ }
220
+ /** Queue a follow-up prompt for a hosted agent (idle → starts a turn). */
221
+ reply(sessionId, text) {
222
+ const agent = this.agents.get(sessionId);
223
+ if (!agent || agent.state === 'completed' || agent.state === 'failed')
224
+ return false;
225
+ agent.pushInput(text);
226
+ this.setState(agent, 'working');
227
+ return true;
228
+ }
229
+ cancel(sessionId) {
230
+ const agent = this.agents.get(sessionId);
231
+ if (!agent)
232
+ return false;
233
+ agent.broker.cancelAll('cancelled by user');
234
+ agent.abort?.();
235
+ agent.endInput();
236
+ return true;
237
+ }
238
+ respond(sessionId, requestId, choice, message) {
239
+ const agent = this.agents.get(sessionId);
240
+ if (!agent)
241
+ return false;
242
+ const ok = agent.broker.respond(requestId, { choice, message });
243
+ if (ok) {
244
+ void bus.emit(makeEvent({
245
+ type: 'approval.resolved',
246
+ source: 'core',
247
+ data: { sessionId, requestId, choice, by: 'remote' },
248
+ }));
249
+ }
250
+ return ok;
251
+ }
252
+ subscribe(sessionId, cb) {
253
+ const agent = this.agents.get(sessionId);
254
+ if (!agent)
255
+ return null;
256
+ agent.emitter.on('event', cb);
257
+ return () => agent.emitter.off('event', cb);
258
+ }
259
+ /** Ring-buffer replay for peek panels. */
260
+ output(sessionId) {
261
+ return this.agents.get(sessionId)?.recent.slice() ?? [];
262
+ }
263
+ shutdown() {
264
+ for (const agent of this.agents.values()) {
265
+ agent.broker.cancelAll('server shutting down');
266
+ agent.abort?.();
267
+ agent.endInput();
268
+ }
269
+ }
270
+ }
@@ -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
  }