@blockrun/franklin 3.33.0 → 3.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/approvals.d.ts +47 -0
  3. package/dist/agent/approvals.js +66 -0
  4. package/dist/agent/commands.js +230 -7
  5. package/dist/agent/input-queue.d.ts +26 -0
  6. package/dist/agent/input-queue.js +65 -0
  7. package/dist/agent/loop.js +196 -3
  8. package/dist/agent/streaming-executor.d.ts +4 -0
  9. package/dist/agent/streaming-executor.js +52 -0
  10. package/dist/agent/tool-guard.d.ts +7 -0
  11. package/dist/agent/tool-guard.js +21 -0
  12. package/dist/agent/types.d.ts +26 -0
  13. package/dist/audit/approvals.d.ts +20 -0
  14. package/dist/audit/approvals.js +21 -0
  15. package/dist/commands/start.d.ts +10 -1
  16. package/dist/commands/start.js +53 -1
  17. package/dist/events/types.d.ts +38 -1
  18. package/dist/goal/engine.d.ts +39 -0
  19. package/dist/goal/engine.js +182 -0
  20. package/dist/goal/prompts.d.ts +16 -0
  21. package/dist/goal/prompts.js +206 -0
  22. package/dist/goal/runtime.d.ts +20 -0
  23. package/dist/goal/runtime.js +110 -0
  24. package/dist/goal/store.d.ts +22 -0
  25. package/dist/goal/store.js +79 -0
  26. package/dist/goal/types.d.ts +63 -0
  27. package/dist/goal/types.js +26 -0
  28. package/dist/hooks/loader.d.ts +19 -0
  29. package/dist/hooks/loader.js +115 -0
  30. package/dist/hooks/runner.d.ts +31 -0
  31. package/dist/hooks/runner.js +147 -0
  32. package/dist/hooks/types.d.ts +64 -0
  33. package/dist/hooks/types.js +35 -0
  34. package/dist/index.js +5 -1
  35. package/dist/memory/capture.d.ts +40 -0
  36. package/dist/memory/capture.js +95 -0
  37. package/dist/memory/dream.d.ts +24 -0
  38. package/dist/memory/dream.js +147 -0
  39. package/dist/memory/indexer.d.ts +29 -0
  40. package/dist/memory/indexer.js +144 -0
  41. package/dist/memory/store.d.ts +50 -0
  42. package/dist/memory/store.js +163 -0
  43. package/dist/monitors/registry.d.ts +42 -0
  44. package/dist/monitors/registry.js +104 -0
  45. package/dist/panel/html.js +299 -0
  46. package/dist/panel/server.js +41 -0
  47. package/dist/scheduler/service.d.ts +24 -0
  48. package/dist/scheduler/service.js +44 -0
  49. package/dist/scheduler/store.d.ts +26 -0
  50. package/dist/scheduler/store.js +116 -0
  51. package/dist/scheduler/types.d.ts +36 -0
  52. package/dist/scheduler/types.js +31 -0
  53. package/dist/serve/agent-host.d.ts +63 -0
  54. package/dist/serve/agent-host.js +270 -0
  55. package/dist/serve/server.js +186 -3
  56. package/dist/session/live-registry.d.ts +32 -0
  57. package/dist/session/live-registry.js +83 -0
  58. package/dist/session/search.d.ts +6 -0
  59. package/dist/session/search.js +3 -3
  60. package/dist/session/storage.d.ts +6 -0
  61. package/dist/session/storage.js +6 -0
  62. package/dist/tools/goal.d.ts +7 -0
  63. package/dist/tools/goal.js +29 -0
  64. package/dist/tools/index.js +11 -0
  65. package/dist/tools/memory.js +14 -4
  66. package/dist/tools/monitor.d.ts +11 -0
  67. package/dist/tools/monitor.js +96 -0
  68. package/dist/tools/scheduler.d.ts +12 -0
  69. package/dist/tools/scheduler.js +79 -0
  70. package/dist/tools/spend-tools.d.ts +33 -0
  71. package/dist/tools/spend-tools.js +114 -0
  72. package/dist/tools/tool-categories.js +7 -0
  73. package/dist/tools/trade-plan.d.ts +11 -0
  74. package/dist/tools/trade-plan.js +137 -0
  75. package/dist/tools/trading-execute.js +24 -0
  76. package/dist/trading/trade-plan.d.ts +75 -0
  77. package/dist/trading/trade-plan.js +290 -0
  78. package/package.json +2 -2
@@ -21,6 +21,8 @@ import { listTasks, readTaskMeta, readTaskEvents, } from '../tasks/store.js';
21
21
  import { reconcileLostTasks } from '../tasks/lost-detection.js';
22
22
  import { taskLogPath } from '../tasks/paths.js';
23
23
  import { isTerminalTaskStatus } from '../tasks/types.js';
24
+ import { readLiveAgents } from '../session/live-registry.js';
25
+ import { BLOCKRUN_DIR } from '../config.js';
24
26
  import { getHTML } from './html.js';
25
27
  const sseClients = new Set();
26
28
  function json(res, data, status = 200) {
@@ -169,6 +171,45 @@ export function createPanelServer(port) {
169
171
  }
170
172
  // ─── API ──
171
173
  try {
174
+ // Read-only agent fleet view: live registry joined with session meta.
175
+ // All agent CONTROL flows through serve's gated WebSocket — the panel's
176
+ // REST surface stays read-only by design (no new mutating routes).
177
+ if (p === '/api/agents') {
178
+ const metas = new Map(listSessions().map((m) => [m.id, m]));
179
+ const agents = readLiveAgents().map((r) => {
180
+ const meta = metas.get(r.sessionId);
181
+ return {
182
+ ...r,
183
+ costUsd: meta?.costUsd,
184
+ turnCount: meta?.turnCount,
185
+ workDir: meta?.workDir,
186
+ };
187
+ });
188
+ json(res, { agents });
189
+ return;
190
+ }
191
+ if (p === '/api/serve-info') {
192
+ // serve writes ~/.blockrun/serve-url on listen (removed on clean
193
+ // exit); a 300ms probe distinguishes a live server from a stale file.
194
+ let wsUrl = null;
195
+ try {
196
+ wsUrl = fs.readFileSync(path.join(BLOCKRUN_DIR, 'serve-url'), 'utf-8').trim() || null;
197
+ }
198
+ catch { /* serve never ran */ }
199
+ let alive = false;
200
+ const hostMatch = wsUrl?.match(/^ws:\/\/([^/]+)\//);
201
+ if (hostMatch) {
202
+ try {
203
+ await fetch(`http://${hostMatch[1]}/`, { signal: AbortSignal.timeout(300) });
204
+ alive = true; // any HTTP response (even 404) = server is up
205
+ }
206
+ catch {
207
+ alive = false;
208
+ }
209
+ }
210
+ json(res, { url: wsUrl, alive });
211
+ return;
212
+ }
172
213
  if (p === '/api/stats') {
173
214
  const summary = getStatsSummary();
174
215
  json(res, {
@@ -0,0 +1,24 @@
1
+ /**
2
+ * In-session scheduler service. A 30s tick checks due tasks and fires them
3
+ * by enqueueing the prompt into the session's input multiplexer — firings
4
+ * always land at turn boundaries, never mid-turn.
5
+ *
6
+ * Catch-up semantics: on service start, durable tasks whose nextFireAt
7
+ * passed while no session was running fire once (a slept-through task
8
+ * fires once, not once per missed interval — see markFired).
9
+ *
10
+ * Firing when NO session is running is out of scope here: the launchd
11
+ * agent hosts the payment proxy, not an agent loop. Durable tasks simply
12
+ * wait for the next session.
13
+ */
14
+ export interface SchedulerService {
15
+ stop: () => void;
16
+ /** Immediate due-check — used by tests and session-start catch-up. */
17
+ tick: () => number;
18
+ }
19
+ export declare function startSchedulerService(opts: {
20
+ sessionId: string;
21
+ enqueue: (text: string) => void;
22
+ /** Visibility line pushed to the transcript when a task fires. */
23
+ notify?: (line: string) => void;
24
+ }): SchedulerService;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * In-session scheduler service. A 30s tick checks due tasks and fires them
3
+ * by enqueueing the prompt into the session's input multiplexer — firings
4
+ * always land at turn boundaries, never mid-turn.
5
+ *
6
+ * Catch-up semantics: on service start, durable tasks whose nextFireAt
7
+ * passed while no session was running fire once (a slept-through task
8
+ * fires once, not once per missed interval — see markFired).
9
+ *
10
+ * Firing when NO session is running is out of scope here: the launchd
11
+ * agent hosts the payment proxy, not an agent loop. Durable tasks simply
12
+ * wait for the next session.
13
+ */
14
+ import { listScheduledTasks, markFired } from './store.js';
15
+ const TICK_MS = 30_000;
16
+ export function startSchedulerService(opts) {
17
+ const fire = (task) => {
18
+ markFired(task);
19
+ opts.notify?.(`[scheduler] firing task ${task.id} (${task.firedCount + 1}× so far): ${task.prompt.slice(0, 120)}\n`);
20
+ opts.enqueue(task.prompt);
21
+ };
22
+ const tick = () => {
23
+ const now = Date.now();
24
+ let fired = 0;
25
+ for (const task of listScheduledTasks()) {
26
+ if (!task.enabled || task.nextFireAt > now)
27
+ continue;
28
+ // Non-durable tasks belong to the session that created them.
29
+ if (!task.durable && task.sessionId !== opts.sessionId)
30
+ continue;
31
+ fire(task);
32
+ fired++;
33
+ }
34
+ return fired;
35
+ };
36
+ // Session-start catch-up for durable tasks that slept through their slot.
37
+ tick();
38
+ const timer = setInterval(tick, TICK_MS);
39
+ timer.unref(); // never keep the process alive just for the scheduler
40
+ return {
41
+ stop: () => clearInterval(timer),
42
+ tick,
43
+ };
44
+ }
@@ -0,0 +1,26 @@
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 { type ScheduledTask } from './types.js';
7
+ export declare function schedulerDir(): string;
8
+ export declare function setSchedulerSessionId(id: string): void;
9
+ export declare function getSchedulerSessionId(): string;
10
+ export declare function saveScheduledTask(task: ScheduledTask): void;
11
+ export declare function deleteScheduledTask(id: string): boolean;
12
+ /** All non-expired tasks, pruning expired files as a side effect. */
13
+ export declare function listScheduledTasks(): ScheduledTask[];
14
+ export declare function createScheduledTask(opts: {
15
+ prompt: string;
16
+ intervalSec: number;
17
+ sessionId: string;
18
+ recurring?: boolean;
19
+ durable?: boolean;
20
+ fireImmediately?: boolean;
21
+ ttlMs?: number;
22
+ }): ScheduledTask | {
23
+ error: string;
24
+ };
25
+ /** Record a firing: advance nextFireAt, or disable a one-shot. */
26
+ export declare function markFired(task: ScheduledTask): ScheduledTask;
@@ -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
+ }