@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.
- package/README.md +23 -2
- package/dist/agent/approvals.d.ts +47 -0
- package/dist/agent/approvals.js +66 -0
- package/dist/agent/commands.js +230 -7
- package/dist/agent/input-queue.d.ts +26 -0
- package/dist/agent/input-queue.js +65 -0
- package/dist/agent/loop.js +196 -3
- package/dist/agent/streaming-executor.d.ts +4 -0
- package/dist/agent/streaming-executor.js +52 -0
- package/dist/agent/tool-guard.d.ts +7 -0
- package/dist/agent/tool-guard.js +21 -0
- package/dist/agent/types.d.ts +26 -0
- package/dist/audit/approvals.d.ts +20 -0
- package/dist/audit/approvals.js +21 -0
- package/dist/commands/start.d.ts +10 -1
- package/dist/commands/start.js +53 -1
- package/dist/events/types.d.ts +38 -1
- package/dist/goal/engine.d.ts +39 -0
- package/dist/goal/engine.js +182 -0
- package/dist/goal/prompts.d.ts +16 -0
- package/dist/goal/prompts.js +206 -0
- package/dist/goal/runtime.d.ts +20 -0
- package/dist/goal/runtime.js +110 -0
- package/dist/goal/store.d.ts +22 -0
- package/dist/goal/store.js +79 -0
- package/dist/goal/types.d.ts +63 -0
- package/dist/goal/types.js +26 -0
- package/dist/hooks/loader.d.ts +19 -0
- package/dist/hooks/loader.js +115 -0
- package/dist/hooks/runner.d.ts +31 -0
- package/dist/hooks/runner.js +147 -0
- package/dist/hooks/types.d.ts +64 -0
- package/dist/hooks/types.js +35 -0
- package/dist/index.js +5 -1
- package/dist/memory/capture.d.ts +40 -0
- package/dist/memory/capture.js +95 -0
- package/dist/memory/dream.d.ts +24 -0
- package/dist/memory/dream.js +147 -0
- package/dist/memory/indexer.d.ts +29 -0
- package/dist/memory/indexer.js +144 -0
- package/dist/memory/store.d.ts +50 -0
- package/dist/memory/store.js +163 -0
- package/dist/monitors/registry.d.ts +42 -0
- package/dist/monitors/registry.js +104 -0
- package/dist/panel/html.js +299 -0
- package/dist/panel/server.js +41 -0
- package/dist/scheduler/service.d.ts +24 -0
- package/dist/scheduler/service.js +44 -0
- package/dist/scheduler/store.d.ts +26 -0
- package/dist/scheduler/store.js +116 -0
- package/dist/scheduler/types.d.ts +36 -0
- package/dist/scheduler/types.js +31 -0
- package/dist/serve/agent-host.d.ts +63 -0
- package/dist/serve/agent-host.js +270 -0
- package/dist/serve/server.js +186 -3
- package/dist/session/live-registry.d.ts +32 -0
- package/dist/session/live-registry.js +83 -0
- package/dist/session/search.d.ts +6 -0
- package/dist/session/search.js +3 -3
- package/dist/session/storage.d.ts +6 -0
- package/dist/session/storage.js +6 -0
- package/dist/tools/goal.d.ts +7 -0
- package/dist/tools/goal.js +29 -0
- package/dist/tools/index.js +11 -0
- package/dist/tools/memory.js +14 -4
- package/dist/tools/monitor.d.ts +11 -0
- package/dist/tools/monitor.js +96 -0
- package/dist/tools/scheduler.d.ts +12 -0
- package/dist/tools/scheduler.js +79 -0
- package/dist/tools/spend-tools.d.ts +33 -0
- package/dist/tools/spend-tools.js +114 -0
- package/dist/tools/tool-categories.js +7 -0
- package/dist/tools/trade-plan.d.ts +11 -0
- package/dist/tools/trade-plan.js +137 -0
- package/dist/tools/trading-execute.js +24 -0
- package/dist/trading/trade-plan.d.ts +75 -0
- package/dist/trading/trade-plan.js +290 -0
- package/package.json +2 -2
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trade plans — the approval artifact standing between the agent and real
|
|
3
|
+
* money. Before any trade-execution tool (swaps, prediction-market orders)
|
|
4
|
+
* can run, the session must hold an APPROVED, unexpired plan whose remaining
|
|
5
|
+
* budget covers the trade. The model proposes a structured plan (assets,
|
|
6
|
+
* sizes, rationale, total spend); the user approves, requests changes, or
|
|
7
|
+
* denies; executions draw down the plan's budget until it is consumed.
|
|
8
|
+
*
|
|
9
|
+
* This gate applies in EVERY permission mode including trust — moving money
|
|
10
|
+
* differs in kind from editing files, the same reasoning that keeps
|
|
11
|
+
* dangerous bash commands always-prompting.
|
|
12
|
+
*
|
|
13
|
+
* Persistence: one JSON per plan under ~/.blockrun/trade-plans/. Decisions
|
|
14
|
+
* are audited to ~/.blockrun/approvals.jsonl.
|
|
15
|
+
*/
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
import { BLOCKRUN_DIR } from '../config.js';
|
|
20
|
+
import { appendApprovalRecord } from '../audit/approvals.js';
|
|
21
|
+
import { estimateSpendUsd, TRADE_EXECUTION_TOOLS } from '../tools/spend-tools.js';
|
|
22
|
+
import { captureTradeEvent } from '../memory/capture.js';
|
|
23
|
+
import { getAddress } from '../wallet/manager.js';
|
|
24
|
+
export const TRADE_PLAN_TTL_MS = 15 * 60 * 1000;
|
|
25
|
+
const VENUE_BY_TOOL = {
|
|
26
|
+
JupiterSwap: 'jupiter',
|
|
27
|
+
Base0xSwap: 'zerox',
|
|
28
|
+
Base0xGaslessSwap: 'zerox',
|
|
29
|
+
PolymarketBet: 'polymarket',
|
|
30
|
+
};
|
|
31
|
+
// ─── Store ─────────────────────────────────────────────────────────────────
|
|
32
|
+
export function tradePlansDir() {
|
|
33
|
+
return path.join(BLOCKRUN_DIR, 'trade-plans');
|
|
34
|
+
}
|
|
35
|
+
function planPath(id) {
|
|
36
|
+
return path.join(tradePlansDir(), `${id}.json`);
|
|
37
|
+
}
|
|
38
|
+
export function saveTradePlan(plan) {
|
|
39
|
+
fs.mkdirSync(tradePlansDir(), { recursive: true });
|
|
40
|
+
const tmp = path.join(tradePlansDir(), `.${plan.id}.tmp`);
|
|
41
|
+
fs.writeFileSync(tmp, JSON.stringify(plan, null, 2));
|
|
42
|
+
fs.renameSync(tmp, planPath(plan.id));
|
|
43
|
+
}
|
|
44
|
+
export function loadTradePlan(id) {
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(fs.readFileSync(planPath(id), 'utf-8'));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function listTradePlans() {
|
|
53
|
+
let files;
|
|
54
|
+
try {
|
|
55
|
+
files = fs.readdirSync(tradePlansDir()).filter(f => f.endsWith('.json'));
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
const plans = [];
|
|
61
|
+
for (const f of files) {
|
|
62
|
+
try {
|
|
63
|
+
const plan = JSON.parse(fs.readFileSync(path.join(tradePlansDir(), f), 'utf-8'));
|
|
64
|
+
if (plan?.id)
|
|
65
|
+
plans.push(plan);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
/* skip */
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return plans.sort((a, b) => b.createdAt - a.createdAt);
|
|
72
|
+
}
|
|
73
|
+
export function validatePlannedTrades(trades) {
|
|
74
|
+
if (!Array.isArray(trades) || trades.length === 0) {
|
|
75
|
+
return { error: 'trades must be a non-empty array' };
|
|
76
|
+
}
|
|
77
|
+
const cleaned = [];
|
|
78
|
+
for (const [i, raw] of trades.entries()) {
|
|
79
|
+
const t = raw;
|
|
80
|
+
if (!t || typeof t !== 'object')
|
|
81
|
+
return { error: `trades[${i}] must be an object` };
|
|
82
|
+
if (t.venue !== 'jupiter' && t.venue !== 'zerox' && t.venue !== 'polymarket') {
|
|
83
|
+
return { error: `trades[${i}].venue must be jupiter | zerox | polymarket` };
|
|
84
|
+
}
|
|
85
|
+
if (t.action !== 'buy' && t.action !== 'sell' && t.action !== 'swap' && t.action !== 'bet') {
|
|
86
|
+
return { error: `trades[${i}].action must be buy | sell | swap | bet` };
|
|
87
|
+
}
|
|
88
|
+
if (typeof t.asset !== 'string' || !t.asset.trim()) {
|
|
89
|
+
return { error: `trades[${i}].asset is required` };
|
|
90
|
+
}
|
|
91
|
+
if (typeof t.amountUsd !== 'number' || !Number.isFinite(t.amountUsd) || t.amountUsd <= 0) {
|
|
92
|
+
return { error: `trades[${i}].amountUsd must be a positive number` };
|
|
93
|
+
}
|
|
94
|
+
cleaned.push({
|
|
95
|
+
venue: t.venue,
|
|
96
|
+
action: t.action,
|
|
97
|
+
asset: t.asset.trim(),
|
|
98
|
+
direction: t.direction,
|
|
99
|
+
amountUsd: t.amountUsd,
|
|
100
|
+
maxSlippageBps: typeof t.maxSlippageBps === 'number' ? t.maxSlippageBps : undefined,
|
|
101
|
+
stopCondition: typeof t.stopCondition === 'string' ? t.stopCondition : undefined,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return { trades: cleaned };
|
|
105
|
+
}
|
|
106
|
+
export function createTradePlan(opts) {
|
|
107
|
+
const plan = {
|
|
108
|
+
id: `tp_${crypto.randomBytes(6).toString('hex')}`,
|
|
109
|
+
sessionId: opts.sessionId,
|
|
110
|
+
createdAt: Date.now(),
|
|
111
|
+
expiresAt: Date.now() + (opts.ttlMs ?? TRADE_PLAN_TTL_MS),
|
|
112
|
+
status: 'pending',
|
|
113
|
+
trades: opts.trades,
|
|
114
|
+
totalSpendUsd: opts.trades.reduce((sum, t) => sum + t.amountUsd, 0),
|
|
115
|
+
rationale: opts.rationale,
|
|
116
|
+
consumedUsd: 0,
|
|
117
|
+
};
|
|
118
|
+
saveTradePlan(plan);
|
|
119
|
+
return plan;
|
|
120
|
+
}
|
|
121
|
+
export function decideTradePlan(plan, decision, by, reason) {
|
|
122
|
+
const updated = {
|
|
123
|
+
...plan,
|
|
124
|
+
status: decision,
|
|
125
|
+
decidedBy: by,
|
|
126
|
+
changeRequest: decision === 'rejected' ? reason : plan.changeRequest,
|
|
127
|
+
};
|
|
128
|
+
saveTradePlan(updated);
|
|
129
|
+
appendApprovalRecord({
|
|
130
|
+
ts: Date.now(),
|
|
131
|
+
sessionId: plan.sessionId,
|
|
132
|
+
kind: 'trade-plan',
|
|
133
|
+
subject: plan.id,
|
|
134
|
+
decision: decision === 'approved' ? 'approve' : decision === 'rejected' ? 'reject' : 'cancel',
|
|
135
|
+
by,
|
|
136
|
+
reason,
|
|
137
|
+
});
|
|
138
|
+
return updated;
|
|
139
|
+
}
|
|
140
|
+
export function formatTradePlanText(plan, walletBalanceUsd) {
|
|
141
|
+
const lines = [];
|
|
142
|
+
lines.push(`TRADE PLAN ${plan.id}`);
|
|
143
|
+
lines.push('');
|
|
144
|
+
for (const [i, t] of plan.trades.entries()) {
|
|
145
|
+
const dir = t.direction ? ` ${t.direction.toUpperCase()}` : '';
|
|
146
|
+
const slip = t.maxSlippageBps != null ? ` · max slippage ${t.maxSlippageBps} bps` : '';
|
|
147
|
+
const stop = t.stopCondition ? ` · stop: ${t.stopCondition}` : '';
|
|
148
|
+
lines.push(` ${i + 1}. [${t.venue}] ${t.action.toUpperCase()}${dir} ${t.asset} — $${t.amountUsd.toFixed(2)}${slip}${stop}`);
|
|
149
|
+
}
|
|
150
|
+
lines.push('');
|
|
151
|
+
lines.push(` Total spend: $${plan.totalSpendUsd.toFixed(2)}${walletBalanceUsd != null ? ` (wallet: $${walletBalanceUsd.toFixed(2)})` : ''}`);
|
|
152
|
+
lines.push(` Valid until: ${new Date(plan.expiresAt).toLocaleTimeString()}`);
|
|
153
|
+
lines.push('');
|
|
154
|
+
lines.push(` Rationale: ${plan.rationale}`);
|
|
155
|
+
return lines.join('\n');
|
|
156
|
+
}
|
|
157
|
+
// ─── Session gate ──────────────────────────────────────────────────────────
|
|
158
|
+
// Session context threaded via setter (same pattern as the scheduler) because
|
|
159
|
+
// SessionToolGuard is constructed without session identity.
|
|
160
|
+
let gateSessionId = 'default';
|
|
161
|
+
export function setTradePlanSessionId(id) {
|
|
162
|
+
gateSessionId = id;
|
|
163
|
+
}
|
|
164
|
+
function planIsLive(plan) {
|
|
165
|
+
return plan.status === 'approved' && plan.expiresAt > Date.now() && plan.consumedUsd < plan.totalSpendUsd;
|
|
166
|
+
}
|
|
167
|
+
/** The session's live (approved, unexpired, unconsumed) plan, if any. */
|
|
168
|
+
export function activeTradePlan(sessionId = gateSessionId) {
|
|
169
|
+
return listTradePlans().find(p => p.sessionId === sessionId && planIsLive(p)) ?? null;
|
|
170
|
+
}
|
|
171
|
+
/** Does the tool input plausibly reference the planned asset? Lenient by design:
|
|
172
|
+
* symbols vs mint addresses vs market ids all count as a mention anywhere in
|
|
173
|
+
* the input values. A mismatch denies, so false negatives (blocking a covered
|
|
174
|
+
* trade) are worse than false positives here — the budget cap still binds. */
|
|
175
|
+
function assetMentioned(asset, input) {
|
|
176
|
+
const needle = asset.toLowerCase();
|
|
177
|
+
for (const value of Object.values(input)) {
|
|
178
|
+
if (typeof value === 'string' && value.toLowerCase().includes(needle))
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
function isGatedInvocation(invocation) {
|
|
184
|
+
if (!TRADE_EXECUTION_TOOLS.has(invocation.name))
|
|
185
|
+
return false;
|
|
186
|
+
if (invocation.name === 'PolymarketBet') {
|
|
187
|
+
// Only order placement is gated; setup/positions/redeem/withdraw and
|
|
188
|
+
// dry-run previews (no confirm) stay free so the model can research
|
|
189
|
+
// and preview before proposing a plan.
|
|
190
|
+
const action = String(invocation.input.action ?? '');
|
|
191
|
+
if (action !== 'buy' && action !== 'sell')
|
|
192
|
+
return false;
|
|
193
|
+
if (invocation.input.confirm !== true)
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Trade-plan gate — called from SessionToolGuard.beforeExecute for every
|
|
200
|
+
* invocation. Returns a deny result when a trade-execution call lacks plan
|
|
201
|
+
* coverage; null to proceed. On coverage, flags the invocation so the tool
|
|
202
|
+
* skips its redundant per-swap confirm (the plan approval IS the confirm).
|
|
203
|
+
*/
|
|
204
|
+
export function checkTradePlanGate(invocation, sessionId = gateSessionId) {
|
|
205
|
+
if (!isGatedInvocation(invocation))
|
|
206
|
+
return null;
|
|
207
|
+
const plan = activeTradePlan(sessionId);
|
|
208
|
+
const venue = VENUE_BY_TOOL[invocation.name];
|
|
209
|
+
const estimate = estimateSpendUsd(invocation.name, invocation.input);
|
|
210
|
+
if (!plan) {
|
|
211
|
+
appendApprovalRecord({
|
|
212
|
+
ts: Date.now(),
|
|
213
|
+
sessionId,
|
|
214
|
+
kind: 'trade-plan',
|
|
215
|
+
subject: invocation.name,
|
|
216
|
+
decision: 'deny',
|
|
217
|
+
by: 'policy',
|
|
218
|
+
reason: 'no approved trade plan',
|
|
219
|
+
});
|
|
220
|
+
return {
|
|
221
|
+
output: `Trade blocked: no approved trade plan covers this ${invocation.name} call. ` +
|
|
222
|
+
'Real-money trades require prior approval. Call the TradePlan tool with action "propose" — ' +
|
|
223
|
+
'list every intended trade (venue, action, asset, amountUsd, slippage, stop condition) plus a ' +
|
|
224
|
+
'one-paragraph rationale, wait for the user decision, then retry the trade.',
|
|
225
|
+
isError: true,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
const remaining = plan.totalSpendUsd - plan.consumedUsd;
|
|
229
|
+
const matched = plan.trades.find(t => t.venue === venue && assetMentioned(t.asset, invocation.input));
|
|
230
|
+
if (!matched) {
|
|
231
|
+
return {
|
|
232
|
+
output: `Trade blocked: approved plan ${plan.id} does not include a ${venue} trade matching this call's asset. ` +
|
|
233
|
+
'Either execute only the planned trades, or propose a new plan via the TradePlan tool.',
|
|
234
|
+
isError: true,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
const spendNeeded = estimate ?? matched.amountUsd;
|
|
238
|
+
if (spendNeeded > remaining + 0.01) {
|
|
239
|
+
return {
|
|
240
|
+
output: `Trade blocked: this call needs ~$${spendNeeded.toFixed(2)} but plan ${plan.id} has only ` +
|
|
241
|
+
`$${remaining.toFixed(2)} of its approved $${plan.totalSpendUsd.toFixed(2)} budget left. ` +
|
|
242
|
+
'Propose a new plan for the additional spend.',
|
|
243
|
+
isError: true,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
// Covered: the plan approval already carried the human decision — skip the
|
|
247
|
+
// tool's own per-swap AskUser confirm (all swap tools honor auto_approve).
|
|
248
|
+
if (invocation.name !== 'PolymarketBet') {
|
|
249
|
+
invocation.input.auto_approve = true;
|
|
250
|
+
}
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Draw down the plan budget after a successful gated execution. Called from
|
|
255
|
+
* SessionToolGuard.afterExecute for every invocation (no-op for non-trades).
|
|
256
|
+
*/
|
|
257
|
+
export function recordTradeExecution(invocation, result, sessionId = gateSessionId) {
|
|
258
|
+
if (result.isError || !isGatedInvocation(invocation))
|
|
259
|
+
return;
|
|
260
|
+
const plan = activeTradePlan(sessionId);
|
|
261
|
+
if (!plan)
|
|
262
|
+
return;
|
|
263
|
+
const venue = VENUE_BY_TOOL[invocation.name];
|
|
264
|
+
const matched = plan.trades.find(t => t.venue === venue && assetMentioned(t.asset, invocation.input));
|
|
265
|
+
const spent = estimateSpendUsd(invocation.name, invocation.input) ?? matched?.amountUsd ?? 0;
|
|
266
|
+
const consumedUsd = plan.consumedUsd + spent;
|
|
267
|
+
const updated = {
|
|
268
|
+
...plan,
|
|
269
|
+
consumedUsd,
|
|
270
|
+
status: consumedUsd >= plan.totalSpendUsd - 0.01 ? 'consumed' : plan.status,
|
|
271
|
+
};
|
|
272
|
+
saveTradePlan(updated);
|
|
273
|
+
// Journal the real-money execution into wallet-keyed document memory —
|
|
274
|
+
// the trade journal follows the wallet, not the working directory.
|
|
275
|
+
try {
|
|
276
|
+
const chain = venue === 'jupiter' ? 'solana' : 'base';
|
|
277
|
+
captureTradeEvent({
|
|
278
|
+
kind: venue === 'polymarket' ? 'bet' : matched?.action === 'sell' ? 'close' : 'open',
|
|
279
|
+
chain,
|
|
280
|
+
address: getAddress(),
|
|
281
|
+
asset: matched?.asset ?? String(invocation.input.asset ?? invocation.name),
|
|
282
|
+
amountUsd: spent > 0 ? spent : undefined,
|
|
283
|
+
thesis: plan.rationale,
|
|
284
|
+
ref: plan.id,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
/* no wallet or memory disabled — journaling is best-effort */
|
|
289
|
+
}
|
|
290
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blockrun/franklin",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.34.1",
|
|
4
4
|
"description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"build": "tsc && node scripts/copy-plugin-assets.mjs",
|
|
32
32
|
"dev": "tsc --watch",
|
|
33
33
|
"start": "node dist/index.js",
|
|
34
|
-
"test": "npm run build && node --test --test-reporter=spec test/local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs",
|
|
34
|
+
"test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs",
|
|
35
35
|
"test:e2e": "npm run build && node --test --test-reporter=spec test/e2e.mjs",
|
|
36
36
|
"test:free-models": "npm run build && node --test --test-reporter=spec test/free-model-matrix.mjs",
|
|
37
37
|
"test:all": "npm run test && npm run test:e2e",
|