@blockrun/franklin 3.33.0 → 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.
- 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 +131 -2
- 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,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 {};
|
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
const SOLANA_STABLE_MINTS = new Set([
|
|
20
|
+
'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
|
|
21
|
+
'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', // USDT
|
|
22
|
+
]);
|
|
23
|
+
const BASE_STABLE_ADDRESSES = new Set([
|
|
24
|
+
'0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', // USDC on Base
|
|
25
|
+
'0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', // USDT on Base
|
|
26
|
+
]);
|
|
27
|
+
function num(v) {
|
|
28
|
+
return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null;
|
|
29
|
+
}
|
|
30
|
+
function str(v) {
|
|
31
|
+
return typeof v === 'string' ? v.trim() : '';
|
|
32
|
+
}
|
|
33
|
+
function solanaStableAmount(input) {
|
|
34
|
+
const mint = str(input.input_mint).toUpperCase() === 'USDC'
|
|
35
|
+
? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
|
|
36
|
+
: str(input.input_mint).toUpperCase() === 'USDT'
|
|
37
|
+
? 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'
|
|
38
|
+
: str(input.input_mint);
|
|
39
|
+
if (!SOLANA_STABLE_MINTS.has(mint))
|
|
40
|
+
return null;
|
|
41
|
+
return num(input.amount);
|
|
42
|
+
}
|
|
43
|
+
function baseStableAmount(input) {
|
|
44
|
+
const token = str(input.sell_token);
|
|
45
|
+
const addr = token.toUpperCase() === 'USDC'
|
|
46
|
+
? '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'
|
|
47
|
+
: token.toUpperCase() === 'USDT'
|
|
48
|
+
? '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2'
|
|
49
|
+
: token.toLowerCase();
|
|
50
|
+
if (!BASE_STABLE_ADDRESSES.has(addr))
|
|
51
|
+
return null;
|
|
52
|
+
return num(input.sell_amount);
|
|
53
|
+
}
|
|
54
|
+
function polymarketAmount(input) {
|
|
55
|
+
const action = str(input.action);
|
|
56
|
+
// Only money-out actions count as spend. Sells/redeems/withdraws return
|
|
57
|
+
// funds; setup/orders/positions are reads.
|
|
58
|
+
if (action !== 'buy' && action !== 'fund')
|
|
59
|
+
return null;
|
|
60
|
+
const direct = num(input.amount_usd);
|
|
61
|
+
if (direct != null)
|
|
62
|
+
return direct;
|
|
63
|
+
// Limit buy: price (0–1 probability) × size (shares) ≈ pUSD cost.
|
|
64
|
+
const price = num(input.price);
|
|
65
|
+
const size = num(input.size);
|
|
66
|
+
if (price != null && size != null)
|
|
67
|
+
return price * size;
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Tool name → USD estimator. Presence in this map is what marks a tool as
|
|
72
|
+
* spendful; the estimator may still return null (unknown amount).
|
|
73
|
+
*/
|
|
74
|
+
export const SPEND_TOOLS = {
|
|
75
|
+
JupiterSwap: solanaStableAmount,
|
|
76
|
+
Base0xSwap: baseStableAmount,
|
|
77
|
+
Base0xGaslessSwap: baseStableAmount,
|
|
78
|
+
PolymarketBet: polymarketAmount,
|
|
79
|
+
// Flat-priced gateway services.
|
|
80
|
+
BuyPhoneNumber: () => 5,
|
|
81
|
+
RenewPhoneNumber: () => 5,
|
|
82
|
+
// Variable-priced paid services — amount unknown at call time, but hooks
|
|
83
|
+
// must still see the spend event.
|
|
84
|
+
VoiceCall: () => null,
|
|
85
|
+
agent_talent: (input) => (str(input.action) === 'run' ? null : 0) || null,
|
|
86
|
+
ImageGen: () => null,
|
|
87
|
+
VideoGen: () => null,
|
|
88
|
+
MusicGen: () => null,
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* The subset whose invocations are trades — used by the trade-plan gate.
|
|
92
|
+
* PolymarketBet is trade-gated only for order placement (buy/sell with
|
|
93
|
+
* confirm), which the gate itself checks via the invocation input.
|
|
94
|
+
*/
|
|
95
|
+
export const TRADE_EXECUTION_TOOLS = new Set([
|
|
96
|
+
'JupiterSwap',
|
|
97
|
+
'Base0xSwap',
|
|
98
|
+
'Base0xGaslessSwap',
|
|
99
|
+
'PolymarketBet',
|
|
100
|
+
]);
|
|
101
|
+
export function isSpendTool(name) {
|
|
102
|
+
return Object.prototype.hasOwnProperty.call(SPEND_TOOLS, name);
|
|
103
|
+
}
|
|
104
|
+
export function estimateSpendUsd(name, input) {
|
|
105
|
+
const estimator = SPEND_TOOLS[name];
|
|
106
|
+
if (!estimator)
|
|
107
|
+
return null;
|
|
108
|
+
try {
|
|
109
|
+
return estimator(input);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -53,6 +53,13 @@ export const CORE_TOOL_NAMES = new Set([
|
|
|
53
53
|
// story: setup wallet, fund, buy/sell, positions, redeem, withdraw. Core so
|
|
54
54
|
// the agent reaches for it the moment "place the bet" follows the research.
|
|
55
55
|
'PolymarketBet',
|
|
56
|
+
// Trade-plan approval — the gate in front of every real-money trade. Must
|
|
57
|
+
// be core: the moment a trade is blocked for lacking a plan, the agent
|
|
58
|
+
// needs this tool visible to propose one.
|
|
59
|
+
'TradePlan',
|
|
60
|
+
// Goal-mode control — must be visible whenever /goal armed a goal, and the
|
|
61
|
+
// goal directive references it by name.
|
|
62
|
+
'UpdateGoal',
|
|
56
63
|
// Crypto market data — fear/greed, token rankings, ETF flows, options,
|
|
57
64
|
// liquidations, technical & on-chain indicators. The "what's the crypto
|
|
58
65
|
// mood / which coins are pumping / BTC's RSI" category. Core so the agent
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TradePlan capability — the model's path to trade authorization.
|
|
3
|
+
*
|
|
4
|
+
* `propose` validates the intended trades, persists a pending plan, and
|
|
5
|
+
* BLOCKS until the approval surface decides (TUI prompt, dashboard client,
|
|
6
|
+
* or headless auto-policy). Without any approval surface the proposal fails
|
|
7
|
+
* closed — non-interactive runs reject trades unless --approve-trades was
|
|
8
|
+
* granted and the total fits the --max-spend envelope.
|
|
9
|
+
*/
|
|
10
|
+
import type { CapabilityHandler } from '../agent/types.js';
|
|
11
|
+
export declare function createTradePlanCapability(): CapabilityHandler;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TradePlan capability — the model's path to trade authorization.
|
|
3
|
+
*
|
|
4
|
+
* `propose` validates the intended trades, persists a pending plan, and
|
|
5
|
+
* BLOCKS until the approval surface decides (TUI prompt, dashboard client,
|
|
6
|
+
* or headless auto-policy). Without any approval surface the proposal fails
|
|
7
|
+
* closed — non-interactive runs reject trades unless --approve-trades was
|
|
8
|
+
* granted and the total fits the --max-spend envelope.
|
|
9
|
+
*/
|
|
10
|
+
import { activeTradePlan, createTradePlan, decideTradePlan, formatTradePlanText, listTradePlans, loadTradePlan, validatePlannedTrades, TRADE_PLAN_TTL_MS, } from '../trading/trade-plan.js';
|
|
11
|
+
import { getSchedulerSessionId } from '../scheduler/store.js';
|
|
12
|
+
export function createTradePlanCapability() {
|
|
13
|
+
return {
|
|
14
|
+
spec: {
|
|
15
|
+
name: 'TradePlan',
|
|
16
|
+
description: 'Propose a trade plan for user approval — REQUIRED before any real-money trade ' +
|
|
17
|
+
'(JupiterSwap, Base0xSwap, Base0xGaslessSwap, PolymarketBet orders). ' +
|
|
18
|
+
'Actions: "propose" (needs trades[] + rationale; blocks until the user decides), ' +
|
|
19
|
+
'"status" (show the active plan and its remaining budget), "cancel" (needs plan_id). ' +
|
|
20
|
+
'Each trade: {venue: jupiter|zerox|polymarket, action: buy|sell|swap|bet, asset, amountUsd, ' +
|
|
21
|
+
'direction?, maxSlippageBps?, stopCondition?}. Keep plans tight: only the trades you intend ' +
|
|
22
|
+
'to execute now, with a one-paragraph rationale. Approved plans expire after 15 minutes and ' +
|
|
23
|
+
'their budget draws down as trades execute. If the user requests changes, revise and re-propose.',
|
|
24
|
+
input_schema: {
|
|
25
|
+
type: 'object',
|
|
26
|
+
properties: {
|
|
27
|
+
action: { type: 'string', enum: ['propose', 'status', 'cancel'], description: 'Operation to perform.' },
|
|
28
|
+
trades: {
|
|
29
|
+
type: 'array',
|
|
30
|
+
description: 'propose: the trades to authorize.',
|
|
31
|
+
items: {
|
|
32
|
+
type: 'object',
|
|
33
|
+
properties: {
|
|
34
|
+
venue: { type: 'string', enum: ['jupiter', 'zerox', 'polymarket'] },
|
|
35
|
+
action: { type: 'string', enum: ['buy', 'sell', 'swap', 'bet'] },
|
|
36
|
+
asset: { type: 'string', description: 'Symbol, mint/token address, or market outcome.' },
|
|
37
|
+
direction: { type: 'string', enum: ['long', 'short', 'yes', 'no'] },
|
|
38
|
+
amountUsd: { type: 'number', description: 'USD to commit to this trade.' },
|
|
39
|
+
maxSlippageBps: { type: 'number' },
|
|
40
|
+
stopCondition: { type: 'string', description: 'Exit/stop condition in plain language.' },
|
|
41
|
+
},
|
|
42
|
+
required: ['venue', 'action', 'asset', 'amountUsd'],
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
rationale: { type: 'string', description: 'propose: why these trades, in one paragraph.' },
|
|
46
|
+
plan_id: { type: 'string', description: 'cancel: plan to cancel.' },
|
|
47
|
+
},
|
|
48
|
+
required: ['action'],
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
// Blocks on human input — must not run concurrently with other tools.
|
|
52
|
+
concurrent: false,
|
|
53
|
+
execute: async (input, ctx) => {
|
|
54
|
+
const action = String(input.action || '');
|
|
55
|
+
const sessionId = getSchedulerSessionId();
|
|
56
|
+
if (action === 'status') {
|
|
57
|
+
const active = activeTradePlan(sessionId);
|
|
58
|
+
if (active) {
|
|
59
|
+
const remaining = active.totalSpendUsd - active.consumedUsd;
|
|
60
|
+
return {
|
|
61
|
+
output: `${formatTradePlanText(active)}\n\n Status: APPROVED · $${remaining.toFixed(2)} of ` +
|
|
62
|
+
`$${active.totalSpendUsd.toFixed(2)} remaining · expires ${new Date(active.expiresAt).toLocaleTimeString()}`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const recent = listTradePlans().filter(p => p.sessionId === sessionId).slice(0, 3);
|
|
66
|
+
if (recent.length === 0)
|
|
67
|
+
return { output: 'No trade plans this session. Propose one before trading.' };
|
|
68
|
+
const lines = recent.map(p => ` ${p.id} · ${p.status} · $${p.totalSpendUsd.toFixed(2)} · ${p.trades.length} trade(s)`);
|
|
69
|
+
return { output: `No ACTIVE plan. Recent plans:\n${lines.join('\n')}` };
|
|
70
|
+
}
|
|
71
|
+
if (action === 'cancel') {
|
|
72
|
+
const id = String(input.plan_id || '');
|
|
73
|
+
const plan = id ? loadTradePlan(id) : activeTradePlan(sessionId);
|
|
74
|
+
if (!plan)
|
|
75
|
+
return { output: `No plan ${id || 'active'} to cancel.`, isError: true };
|
|
76
|
+
if (plan.status === 'consumed' || plan.status === 'cancelled') {
|
|
77
|
+
return { output: `Plan ${plan.id} is already ${plan.status}.`, isError: true };
|
|
78
|
+
}
|
|
79
|
+
decideTradePlan(plan, 'cancelled', 'agent');
|
|
80
|
+
return { output: `Plan ${plan.id} cancelled.` };
|
|
81
|
+
}
|
|
82
|
+
if (action !== 'propose') {
|
|
83
|
+
return { output: `Unknown action "${action}". Use propose, status, or cancel.`, isError: true };
|
|
84
|
+
}
|
|
85
|
+
const validated = validatePlannedTrades(input.trades);
|
|
86
|
+
if ('error' in validated)
|
|
87
|
+
return { output: `Invalid plan: ${validated.error}`, isError: true };
|
|
88
|
+
const rationale = String(input.rationale || '').trim();
|
|
89
|
+
if (!rationale)
|
|
90
|
+
return { output: 'Invalid plan: rationale is required.', isError: true };
|
|
91
|
+
const plan = createTradePlan({ sessionId, trades: validated.trades, rationale });
|
|
92
|
+
if (!ctx.onApproval) {
|
|
93
|
+
// No approval surface (piped/scripted run without --approve-trades):
|
|
94
|
+
// fail closed. Autonomy over money is opt-in per run.
|
|
95
|
+
decideTradePlan(plan, 'rejected', 'policy', 'non-interactive run without --approve-trades');
|
|
96
|
+
return {
|
|
97
|
+
output: `Trade plan ${plan.id} REJECTED: this is a non-interactive run and trade approval was not ` +
|
|
98
|
+
'granted. Re-run with --approve-trades (and a --max-spend cap) to authorize trades, or run ' +
|
|
99
|
+
'interactively. Do not retry the proposal in this session.',
|
|
100
|
+
isError: true,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
const decision = await ctx.onApproval({
|
|
104
|
+
sessionId,
|
|
105
|
+
kind: 'trade-plan',
|
|
106
|
+
title: `Trade plan: $${plan.totalSpendUsd.toFixed(2)} across ${plan.trades.length} trade(s)`,
|
|
107
|
+
description: formatTradePlanText(plan),
|
|
108
|
+
options: ['approve', 'request changes', 'deny'],
|
|
109
|
+
timeoutMs: TRADE_PLAN_TTL_MS,
|
|
110
|
+
payload: plan,
|
|
111
|
+
});
|
|
112
|
+
const choice = decision.choice.toLowerCase();
|
|
113
|
+
if (choice === 'approve') {
|
|
114
|
+
decideTradePlan(plan, 'approved', decision.message === 'auto' ? 'flag' : 'user');
|
|
115
|
+
return {
|
|
116
|
+
output: `Trade plan ${plan.id} APPROVED — $${plan.totalSpendUsd.toFixed(2)} authorized until ` +
|
|
117
|
+
`${new Date(plan.expiresAt).toLocaleTimeString()}. Execute ONLY the planned trades; each ` +
|
|
118
|
+
'execution draws down the budget. Per-swap confirmation is skipped — the plan approval was the confirmation.',
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
if (choice === 'request changes') {
|
|
122
|
+
decideTradePlan(plan, 'rejected', 'user', decision.message || 'changes requested');
|
|
123
|
+
return {
|
|
124
|
+
output: `Trade plan ${plan.id} needs changes before approval. User feedback: ` +
|
|
125
|
+
`"${decision.message || '(none given)'}". Revise the plan accordingly and propose again.`,
|
|
126
|
+
isError: true,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
decideTradePlan(plan, 'rejected', choice === 'timeout' ? 'policy' : 'user', choice === 'timeout' ? 'approval timed out' : decision.message);
|
|
130
|
+
return {
|
|
131
|
+
output: `Trade plan ${plan.id} ${choice === 'timeout' ? 'expired unanswered' : 'DENIED by the user'}. ` +
|
|
132
|
+
'Do not execute any trades. Ask the user how they want to proceed.',
|
|
133
|
+
isError: true,
|
|
134
|
+
};
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -9,6 +9,18 @@
|
|
|
9
9
|
* The split mirrors OpenBB's router/engine/view layering and keeps every
|
|
10
10
|
* layer testable in isolation.
|
|
11
11
|
*/
|
|
12
|
+
import { captureTradeEvent } from '../memory/capture.js';
|
|
13
|
+
import { getAddress } from '../wallet/manager.js';
|
|
14
|
+
/** Journal a paper-engine trade into document memory (wallet-keyed; the
|
|
15
|
+
* 'paper' chain tag keeps simulated activity apart from real trades). */
|
|
16
|
+
function capturePaperTrade(event) {
|
|
17
|
+
try {
|
|
18
|
+
captureTradeEvent({ ...event, chain: 'paper', address: getAddress(), ref: 'paper' });
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
/* no wallet yet or memory disabled — journaling is best-effort */
|
|
22
|
+
}
|
|
23
|
+
}
|
|
12
24
|
import { scoreEntry } from '../trading/journal-quality.js';
|
|
13
25
|
import { renderDisciplineFooter } from '../trading/journal-display.js';
|
|
14
26
|
import { renderOrderBlocked, renderOrderFilled, renderPortfolio, renderPositionClosed, renderTradeHistory, windowToSince, } from './trading-views.js';
|
|
@@ -155,6 +167,12 @@ export function createTradingCapabilities(deps) {
|
|
|
155
167
|
const history = tradeLog.all();
|
|
156
168
|
draftEntry.qualityScore = scoreEntry(draftEntry, history);
|
|
157
169
|
tradeLog.append(draftEntry);
|
|
170
|
+
capturePaperTrade({
|
|
171
|
+
kind: 'open',
|
|
172
|
+
asset: symbol,
|
|
173
|
+
amountUsd: outcome.fill.qty * outcome.fill.priceUsd,
|
|
174
|
+
thesis: rationale?.thesis,
|
|
175
|
+
});
|
|
158
176
|
}
|
|
159
177
|
if (onStateChange)
|
|
160
178
|
await onStateChange();
|
|
@@ -226,6 +244,12 @@ export function createTradingCapabilities(deps) {
|
|
|
226
244
|
};
|
|
227
245
|
draftEntry.qualityScore = scoreEntry(draftEntry, tradeLog.all());
|
|
228
246
|
tradeLog.append(draftEntry);
|
|
247
|
+
capturePaperTrade({
|
|
248
|
+
kind: 'close',
|
|
249
|
+
asset: symbol,
|
|
250
|
+
amountUsd: outcome.fill.qty * outcome.fill.priceUsd,
|
|
251
|
+
pnlUsd: tradeRealized,
|
|
252
|
+
});
|
|
229
253
|
}
|
|
230
254
|
if (onStateChange)
|
|
231
255
|
await onStateChange();
|
|
@@ -0,0 +1,75 @@
|
|
|
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 type { CapabilityInvocation, CapabilityResult } from '../agent/types.js';
|
|
17
|
+
export type TradeVenue = 'jupiter' | 'zerox' | 'polymarket';
|
|
18
|
+
export interface PlannedTrade {
|
|
19
|
+
venue: TradeVenue;
|
|
20
|
+
action: 'buy' | 'sell' | 'swap' | 'bet';
|
|
21
|
+
/** Symbol, mint, token address, or market/outcome label. */
|
|
22
|
+
asset: string;
|
|
23
|
+
direction?: 'long' | 'short' | 'yes' | 'no';
|
|
24
|
+
amountUsd: number;
|
|
25
|
+
maxSlippageBps?: number;
|
|
26
|
+
/** Human-readable exit/stop condition — enforced by goal loops, not code. */
|
|
27
|
+
stopCondition?: string;
|
|
28
|
+
}
|
|
29
|
+
export type TradePlanStatus = 'pending' | 'approved' | 'rejected' | 'expired' | 'consumed' | 'cancelled';
|
|
30
|
+
export interface TradePlan {
|
|
31
|
+
id: string;
|
|
32
|
+
sessionId: string;
|
|
33
|
+
createdAt: number;
|
|
34
|
+
expiresAt: number;
|
|
35
|
+
status: TradePlanStatus;
|
|
36
|
+
trades: PlannedTrade[];
|
|
37
|
+
totalSpendUsd: number;
|
|
38
|
+
rationale: string;
|
|
39
|
+
decidedBy?: string;
|
|
40
|
+
changeRequest?: string;
|
|
41
|
+
consumedUsd: number;
|
|
42
|
+
}
|
|
43
|
+
export declare const TRADE_PLAN_TTL_MS: number;
|
|
44
|
+
export declare function tradePlansDir(): string;
|
|
45
|
+
export declare function saveTradePlan(plan: TradePlan): void;
|
|
46
|
+
export declare function loadTradePlan(id: string): TradePlan | null;
|
|
47
|
+
export declare function listTradePlans(): TradePlan[];
|
|
48
|
+
export declare function validatePlannedTrades(trades: unknown): {
|
|
49
|
+
trades: PlannedTrade[];
|
|
50
|
+
} | {
|
|
51
|
+
error: string;
|
|
52
|
+
};
|
|
53
|
+
export declare function createTradePlan(opts: {
|
|
54
|
+
sessionId: string;
|
|
55
|
+
trades: PlannedTrade[];
|
|
56
|
+
rationale: string;
|
|
57
|
+
ttlMs?: number;
|
|
58
|
+
}): TradePlan;
|
|
59
|
+
export declare function decideTradePlan(plan: TradePlan, decision: 'approved' | 'rejected' | 'cancelled', by: string, reason?: string): TradePlan;
|
|
60
|
+
export declare function formatTradePlanText(plan: TradePlan, walletBalanceUsd?: number): string;
|
|
61
|
+
export declare function setTradePlanSessionId(id: string): void;
|
|
62
|
+
/** The session's live (approved, unexpired, unconsumed) plan, if any. */
|
|
63
|
+
export declare function activeTradePlan(sessionId?: string): TradePlan | null;
|
|
64
|
+
/**
|
|
65
|
+
* Trade-plan gate — called from SessionToolGuard.beforeExecute for every
|
|
66
|
+
* invocation. Returns a deny result when a trade-execution call lacks plan
|
|
67
|
+
* coverage; null to proceed. On coverage, flags the invocation so the tool
|
|
68
|
+
* skips its redundant per-swap confirm (the plan approval IS the confirm).
|
|
69
|
+
*/
|
|
70
|
+
export declare function checkTradePlanGate(invocation: CapabilityInvocation, sessionId?: string): CapabilityResult | null;
|
|
71
|
+
/**
|
|
72
|
+
* Draw down the plan budget after a successful gated execution. Called from
|
|
73
|
+
* SessionToolGuard.afterExecute for every invocation (no-op for non-trades).
|
|
74
|
+
*/
|
|
75
|
+
export declare function recordTradeExecution(invocation: CapabilityInvocation, result: CapabilityResult, sessionId?: string): void;
|