@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.
- 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/compact.js +1 -1
- package/dist/agent/context.js +1 -1
- package/dist/agent/input-queue.d.ts +26 -0
- package/dist/agent/input-queue.js +65 -0
- package/dist/agent/loop.js +198 -5
- package/dist/agent/optimize.js +1 -1
- package/dist/agent/streaming-executor.d.ts +4 -0
- package/dist/agent/streaming-executor.js +52 -0
- package/dist/agent/tokens.js +2 -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/init.js +1 -1
- package/dist/commands/models.d.ts +11 -0
- package/dist/commands/models.js +157 -37
- 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/gateway-models.d.ts +14 -2
- package/dist/gateway-models.js +8 -0
- 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/learnings/extractor.js +1 -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/pricing.js +4 -1
- package/dist/router/index.js +15 -9
- package/dist/router/vision.js +5 -4
- 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/moa.js +1 -1
- 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/dist/ui/app.js +54 -9
- package/dist/ui/model-picker.d.ts +40 -0
- package/dist/ui/model-picker.js +135 -25
- package/package.json +2 -2
- package/dist/agent/media-router.d.ts +0 -98
- package/dist/agent/media-router.js +0 -328
|
@@ -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/dist/ui/app.js
CHANGED
|
@@ -8,13 +8,13 @@ import fs from 'node:fs';
|
|
|
8
8
|
import os from 'node:os';
|
|
9
9
|
import path from 'node:path';
|
|
10
10
|
import { execFileSync } from 'node:child_process';
|
|
11
|
-
import { useState, useEffect, useCallback, useRef } from 'react';
|
|
11
|
+
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
|
|
12
12
|
import { render, Static, Box, Text, useApp, useInput, useStdout } from 'ink';
|
|
13
13
|
import Spinner from 'ink-spinner';
|
|
14
14
|
import TextInput from 'ink-text-input';
|
|
15
15
|
import VimInput from './vim-input.js';
|
|
16
16
|
import { renderMarkdown, renderMarkdownStreaming } from './markdown.js';
|
|
17
|
-
import { resolveModel, PICKER_CATEGORIES, PICKER_MODELS_FLAT, } from './model-picker.js';
|
|
17
|
+
import { resolveModel, getPickerCategories, PICKER_CATEGORIES, PICKER_MODELS_FLAT, } from './model-picker.js';
|
|
18
18
|
import { estimateCost } from '../pricing.js';
|
|
19
19
|
import { formatTokens, shortModelName } from '../stats/format.js';
|
|
20
20
|
import { mouse, forceDisableMouseTracking } from './mouse.js';
|
|
@@ -716,6 +716,16 @@ function RunCodeApp({ initialModel, workDir, walletAddress, walletBalance, chain
|
|
|
716
716
|
// Short preview of latest response shown in dynamic area (last ~5 lines, cleared on next turn)
|
|
717
717
|
const [responsePreview, setResponsePreview] = useState('');
|
|
718
718
|
const [currentModel, setCurrentModel] = useState(initialModel || PICKER_MODELS_FLAT[0].id);
|
|
719
|
+
// Gateway-reconciled picker list. Seeded with the static curation so the
|
|
720
|
+
// first paint is instant and an offline session still gets a usable picker;
|
|
721
|
+
// replaced by the hydrated list once the catalog fetch lands.
|
|
722
|
+
const [pickerCats, setPickerCats] = useState(PICKER_CATEGORIES);
|
|
723
|
+
const [pickerMoreCount, setPickerMoreCount] = useState(0);
|
|
724
|
+
const pickerFlat = useMemo(() => pickerCats.flatMap(c => c.models), [pickerCats]);
|
|
725
|
+
// Track the live model without re-firing the hydration effect on every model
|
|
726
|
+
// change — the effect should run when the picker opens, not when the model
|
|
727
|
+
// switches, but it still needs the current id to re-anchor the cursor.
|
|
728
|
+
const currentModelRef = useRef(initialModel);
|
|
719
729
|
const [ready, setReady] = useState(!startWithPicker);
|
|
720
730
|
const [mode, setMode] = useState(startWithPicker ? 'model-picker' : 'input');
|
|
721
731
|
const [pickerIdx, setPickerIdx] = useState(0);
|
|
@@ -751,6 +761,35 @@ function RunCodeApp({ initialModel, workDir, walletAddress, walletBalance, chain
|
|
|
751
761
|
// tab and the agent stops to ask for approval — verified 2026-05-04
|
|
752
762
|
// from a real screenshot where the user missed the dialog because the
|
|
753
763
|
// input box still read "Working...". Opt-out via FRANKLIN_NO_BELL=1.
|
|
764
|
+
// Single sync point for currentModelRef — cheaper to keep correct than
|
|
765
|
+
// updating the ref at every setCurrentModel call site.
|
|
766
|
+
useEffect(() => { currentModelRef.current = currentModel; }, [currentModel]);
|
|
767
|
+
// Reconcile the picker against the live gateway catalog whenever it opens —
|
|
768
|
+
// covers both /model with no args and --model-picker startup. Runs in the
|
|
769
|
+
// background: the picker has already painted from the static curation (or the
|
|
770
|
+
// 5-min cached catalog), so a slow gateway delays nothing. gateway-models.ts
|
|
771
|
+
// dedupes concurrent fetches and serves stale-on-error, so re-opening the
|
|
772
|
+
// picker is cheap and an offline session simply keeps the static list.
|
|
773
|
+
useEffect(() => {
|
|
774
|
+
if (mode !== 'model-picker')
|
|
775
|
+
return;
|
|
776
|
+
let cancelled = false;
|
|
777
|
+
void getPickerCategories()
|
|
778
|
+
.then(({ categories, moreCount, live }) => {
|
|
779
|
+
if (cancelled || !live)
|
|
780
|
+
return;
|
|
781
|
+
setPickerCats(categories);
|
|
782
|
+
setPickerMoreCount(moreCount);
|
|
783
|
+
// Rows may have dropped out from under the cursor — re-anchor on the
|
|
784
|
+
// model actually in use rather than leaving the highlight on whatever
|
|
785
|
+
// slid into that index.
|
|
786
|
+
const flat = categories.flatMap(c => c.models);
|
|
787
|
+
const at = flat.findIndex(m => m.id === currentModelRef.current);
|
|
788
|
+
setPickerIdx(at >= 0 ? at : 0);
|
|
789
|
+
})
|
|
790
|
+
.catch(() => { });
|
|
791
|
+
return () => { cancelled = true; };
|
|
792
|
+
}, [mode]);
|
|
754
793
|
const bellPlayedRef = useRef(false);
|
|
755
794
|
useEffect(() => {
|
|
756
795
|
const dialogActive = !!permissionRequest || !!askUserRequest;
|
|
@@ -939,9 +978,13 @@ function RunCodeApp({ initialModel, workDir, walletAddress, walletBalance, chain
|
|
|
939
978
|
if (key.upArrow)
|
|
940
979
|
setPickerIdx(i => Math.max(0, i - 1));
|
|
941
980
|
else if (key.downArrow)
|
|
942
|
-
setPickerIdx(i => Math.min(
|
|
981
|
+
setPickerIdx(i => Math.min(pickerFlat.length - 1, i + 1));
|
|
943
982
|
else if (key.return) {
|
|
944
|
-
|
|
983
|
+
// Hydration can shrink the list under the cursor (a retired row drops
|
|
984
|
+
// out), so treat the index as untrusted rather than assuming a hit.
|
|
985
|
+
const selected = pickerFlat[pickerIdx] ?? pickerFlat[0];
|
|
986
|
+
if (!selected)
|
|
987
|
+
return;
|
|
945
988
|
setCurrentModel(selected.id);
|
|
946
989
|
onModelChange(selected.id, 'user');
|
|
947
990
|
showStatus(`Model → ${selected.label}`, 'success', 3000);
|
|
@@ -1025,8 +1068,10 @@ function RunCodeApp({ initialModel, workDir, walletAddress, walletBalance, chain
|
|
|
1025
1068
|
showStatus(`Model → ${resolved}`, 'success', 3000);
|
|
1026
1069
|
}
|
|
1027
1070
|
else {
|
|
1028
|
-
const idx =
|
|
1071
|
+
const idx = pickerFlat.findIndex(m => m.id === currentModel);
|
|
1029
1072
|
setPickerIdx(idx >= 0 ? idx : 0);
|
|
1073
|
+
// Gateway reconciliation is kicked off by an effect on picker mode
|
|
1074
|
+
// (see below), so it covers this path and --model-picker startup.
|
|
1030
1075
|
// Defensive: ensure no draft text survives into the picker —
|
|
1031
1076
|
// closing handlers clear input too, so both ends are covered.
|
|
1032
1077
|
setInput('');
|
|
@@ -1439,7 +1484,7 @@ function RunCodeApp({ initialModel, workDir, walletAddress, walletBalance, chain
|
|
|
1439
1484
|
const { rendered, partial } = renderMarkdownStreaming(visible);
|
|
1440
1485
|
return (_jsxs(Box, { flexDirection: "column", marginTop: 0, marginBottom: 0, marginLeft: 2, children: [truncated && (_jsxs(Text, { dimColor: true, children: ["\u2191 ", lines.length - maxLines, " earlier line", lines.length - maxLines === 1 ? '' : 's', " \u2014 full response will appear in scrollback when this turn finishes"] })), _jsxs(Text, { wrap: "wrap", children: [rendered, rendered && partial ? '\n' : '', partial] })] }));
|
|
1441
1486
|
})(), responsePreview && !streamText && !permissionRequest && !askUserRequest && (_jsx(Box, { flexDirection: "column", marginBottom: 0, marginLeft: 2, children: _jsx(Text, { wrap: "wrap", children: renderMarkdown(responsePreview) }) })), inPicker && (() => {
|
|
1442
|
-
const totalModels =
|
|
1487
|
+
const totalModels = pickerFlat.length;
|
|
1443
1488
|
const maxModels = Math.max(6, termRows - 12);
|
|
1444
1489
|
let start = Math.max(0, pickerIdx - Math.floor(maxModels / 2));
|
|
1445
1490
|
let end = Math.min(totalModels, start + maxModels);
|
|
@@ -1452,12 +1497,12 @@ function RunCodeApp({ initialModel, workDir, walletAddress, walletBalance, chain
|
|
|
1452
1497
|
// Pre-compute each category's base offset into the flat model list so
|
|
1453
1498
|
// we can map (cat, localIdx) → globalIdx in one pass without re-walking.
|
|
1454
1499
|
let cursor = 0;
|
|
1455
|
-
const catBases =
|
|
1500
|
+
const catBases = pickerCats.map((cat) => {
|
|
1456
1501
|
const base = cursor;
|
|
1457
1502
|
cursor += cat.models.length;
|
|
1458
1503
|
return base;
|
|
1459
1504
|
});
|
|
1460
|
-
return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Box, { marginLeft: 2, children: [_jsx(Text, { bold: true, children: "Select a model " }), _jsx(Text, { dimColor: true, children: "(\u2191\u2193 navigate, Enter select, Esc cancel)" })] }), hiddenAbove > 0 && (_jsx(Box, { marginLeft: 2, marginTop: 1, children: _jsxs(Text, { dimColor: true, children: ["\u2191 ", hiddenAbove, " more above"] }) })),
|
|
1505
|
+
return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Box, { marginLeft: 2, children: [_jsx(Text, { bold: true, children: "Select a model " }), _jsx(Text, { dimColor: true, children: "(\u2191\u2193 navigate, Enter select, Esc cancel)" })] }), hiddenAbove > 0 && (_jsx(Box, { marginLeft: 2, marginTop: 1, children: _jsxs(Text, { dimColor: true, children: ["\u2191 ", hiddenAbove, " more above"] }) })), pickerCats.map((cat, catIdx) => {
|
|
1461
1506
|
const base = catBases[catIdx];
|
|
1462
1507
|
const visible = cat.models
|
|
1463
1508
|
.map((m, localIdx) => ({ m, globalIdx: base + localIdx }))
|
|
@@ -1470,7 +1515,7 @@ function RunCodeApp({ initialModel, workDir, walletAddress, walletBalance, chain
|
|
|
1470
1515
|
const isHighlight = m.highlight === true;
|
|
1471
1516
|
return (_jsxs(Box, { marginLeft: 2, children: [_jsxs(Text, { inverse: isSelected, color: isSelected ? 'cyan' : isHighlight ? 'yellow' : undefined, bold: isSelected || isHighlight, children: [' ', m.label.padEnd(26), ' '] }), _jsxs(Text, { dimColor: true, children: [" ", m.shortcut.padEnd(14)] }), _jsx(Text, { color: m.price === 'FREE' ? 'green' : isHighlight ? 'yellow' : undefined, dimColor: !isHighlight && m.price !== 'FREE', children: m.price }), isCurrent && _jsx(Text, { color: "green", children: " \u2190" })] }, m.id));
|
|
1472
1517
|
})] }, cat.category));
|
|
1473
|
-
}), hiddenBelow > 0 && (_jsx(Box, { marginLeft: 2, marginTop: 1, children: _jsxs(Text, { dimColor: true, children: ["\u2193 ", hiddenBelow, " more below"] }) })), _jsx(Box, { marginTop: 1, marginLeft: 2, children: _jsx(Text, { dimColor: true, children: "Your conversation stays above \u2014 picking a model keeps all history intact." }) })] }));
|
|
1518
|
+
}), hiddenBelow > 0 && (_jsx(Box, { marginLeft: 2, marginTop: 1, children: _jsxs(Text, { dimColor: true, children: ["\u2193 ", hiddenBelow, " more below"] }) })), pickerMoreCount > 0 && (_jsx(Box, { marginTop: 1, marginLeft: 2, children: _jsxs(Text, { dimColor: true, children: ["+ ", pickerMoreCount, " more on gateway \u2014 `franklin models` to list, or /model <id> to pick one"] }) })), _jsx(Box, { marginTop: 1, marginLeft: 2, children: _jsx(Text, { dimColor: true, children: "Your conversation stays above \u2014 picking a model keeps all history intact." }) })] }));
|
|
1474
1519
|
})(), !inPicker && !permissionRequest && !askUserRequest && (_jsx(InputBox, { input: input, setInput: setInput, onSubmit: handleSubmit, model: currentModel, balance: liveBalance, chain: chain, walletTail: walletAddress && walletAddress.length >= 4 && !walletAddress.startsWith('not set') ? walletAddress.slice(-4) : undefined, sessionCost: totalCost, queued: queuedInputs[0] || undefined, queuedCount: queuedInputs.length, focused: !permissionRequest && !askUserRequest, busy: !askUserRequest && (waiting || thinking || tools.size > 0), awaitingApproval: !!permissionRequest, awaitingAnswer: !!askUserRequest, contextPct: contextPct, vimMode: vimEnabled, onVimModeChange: setCurrentVimMode }))] }));
|
|
1475
1520
|
}
|
|
1476
1521
|
export function launchInkUI(opts) {
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Interactive model picker for Franklin.
|
|
3
3
|
* Shows categorized model list, supports shortcuts and arrow-key selection.
|
|
4
4
|
*/
|
|
5
|
+
import { type GatewayModel } from '../gateway-models.js';
|
|
5
6
|
export declare const MODEL_SHORTCUTS: Record<string, string>;
|
|
6
7
|
/**
|
|
7
8
|
* Resolve a model name — supports shortcuts. Returns the canonical model id.
|
|
@@ -55,6 +56,45 @@ export interface ModelCategory {
|
|
|
55
56
|
export declare const PICKER_CATEGORIES: ModelCategory[];
|
|
56
57
|
/** Flat list of all picker models (for index-based navigation). */
|
|
57
58
|
export declare const PICKER_MODELS_FLAT: ModelEntry[];
|
|
59
|
+
export interface HydratedPicker {
|
|
60
|
+
categories: ModelCategory[];
|
|
61
|
+
/** Chat models live on the gateway that aren't curated into the picker. */
|
|
62
|
+
moreCount: number;
|
|
63
|
+
/** False when the gateway was unreachable and this is the static fallback. */
|
|
64
|
+
live: boolean;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The picker list, reconciled against the live gateway catalog.
|
|
68
|
+
*
|
|
69
|
+
* {@link PICKER_CATEGORIES} stays the editorial layer — which models are worth
|
|
70
|
+
* featuring, in what order, under which heading, with which shortcut. The
|
|
71
|
+
* gateway is the source of truth for everything factual: whether a model still
|
|
72
|
+
* exists, its display name, and its price. That split is deliberate: the
|
|
73
|
+
* gateway lists 57 chat models and the picker deliberately shows ~21 (see the
|
|
74
|
+
* v3.9.3 trim), so we can't just render the catalog.
|
|
75
|
+
*
|
|
76
|
+
* Reconciliation rules:
|
|
77
|
+
* - Curated row present in the catalog → refresh its label + price from the
|
|
78
|
+
* gateway, so a price change upstream can't leave a stale number on screen.
|
|
79
|
+
* - Curated row absent → drop it. This is the self-healing half: an id the
|
|
80
|
+
* gateway retired (the `claude-haiku-4.5-20251001` case) stops being
|
|
81
|
+
* offered without waiting on a Franklin release. Its MODEL_SHORTCUTS alias
|
|
82
|
+
* survives, matching the long-standing "hide the row, keep the shortcut"
|
|
83
|
+
* pattern.
|
|
84
|
+
* - Gateway unreachable → serve the static list verbatim (`live: false`).
|
|
85
|
+
* An offline picker showing a slightly stale list beats an empty one.
|
|
86
|
+
*
|
|
87
|
+
* Note the catalog hides some models that still resolve (grok-3 and the xAI
|
|
88
|
+
* fast family, for instance). Hidden-but-working ids are therefore dropped from
|
|
89
|
+
* the *visible* list while remaining reachable by typing the shortcut — which
|
|
90
|
+
* is the intended behavior, not a bug.
|
|
91
|
+
*/
|
|
92
|
+
export declare function getPickerCategories(): Promise<HydratedPicker>;
|
|
93
|
+
/**
|
|
94
|
+
* Pure reconciliation step behind {@link getPickerCategories} — exported so the
|
|
95
|
+
* rules can be tested against a synthetic catalog without touching the network.
|
|
96
|
+
*/
|
|
97
|
+
export declare function reconcilePicker(catalog: GatewayModel[]): HydratedPicker;
|
|
58
98
|
/**
|
|
59
99
|
* Show interactive model picker. Returns the selected model ID.
|
|
60
100
|
* Falls back to text input if terminal doesn't support raw mode.
|