@blockrun/franklin 3.32.0 → 3.32.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/dist/agent/media-router.d.ts +98 -0
- package/dist/agent/media-router.js +328 -0
- package/package.json +2 -2
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media router — one LLM call that picks which image/video model fits
|
|
3
|
+
* the user's request, with alternatives and cost estimates, so the agent
|
|
4
|
+
* can show a clean AskUser proposal before spending.
|
|
5
|
+
*
|
|
6
|
+
* Principle (matches turn-analyzer): harness orchestrates, free model
|
|
7
|
+
* decides. No keyword-to-model mapping in TypeScript. Classifier reads
|
|
8
|
+
* the prompt + the current gateway catalog (pulled dynamically), picks
|
|
9
|
+
* one recommended model plus a cheaper + a premium alternative, and
|
|
10
|
+
* explains the choice in one sentence.
|
|
11
|
+
*
|
|
12
|
+
* Cost estimates come from `gateway-models.ts` — always dynamic,
|
|
13
|
+
* margin-adjusted.
|
|
14
|
+
*/
|
|
15
|
+
import type { ModelClient } from './llm.js';
|
|
16
|
+
export type MediaKind = 'image' | 'video';
|
|
17
|
+
export type MediaStyle = 'photoreal' | 'illustration' | 'anime' | 'logo' | 'concept' | 'other';
|
|
18
|
+
export type MediaPriority = 'cost' | 'quality' | 'balanced';
|
|
19
|
+
export interface MediaChoice {
|
|
20
|
+
model: string;
|
|
21
|
+
estimatedCostUsd: number;
|
|
22
|
+
rationale: string;
|
|
23
|
+
}
|
|
24
|
+
export interface MediaProposal {
|
|
25
|
+
kind: MediaKind;
|
|
26
|
+
quantity: number;
|
|
27
|
+
durationSeconds?: number;
|
|
28
|
+
maxDurationSeconds?: number;
|
|
29
|
+
recommended: MediaChoice;
|
|
30
|
+
cheaper?: MediaChoice;
|
|
31
|
+
premium?: MediaChoice;
|
|
32
|
+
intent: {
|
|
33
|
+
style: MediaStyle;
|
|
34
|
+
priority: MediaPriority;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* A fuller rewrite of the user's prompt, following the 5-slot template
|
|
38
|
+
* (scene/subject/details/use-case/constraints). Null when the classifier
|
|
39
|
+
* judged the input already well-specified, or when the env opt-out is set,
|
|
40
|
+
* or when the rewrite was identical to the raw input. When non-null, the
|
|
41
|
+
* AskUser layout surfaces it as "Refined:" with a "Use ORIGINAL" option.
|
|
42
|
+
*/
|
|
43
|
+
refinedPrompt: string | null;
|
|
44
|
+
refinementSummary: string;
|
|
45
|
+
totalCostUsd: number;
|
|
46
|
+
}
|
|
47
|
+
export declare function clearMediaRouterCache(): void;
|
|
48
|
+
/**
|
|
49
|
+
* Normalize a refined prompt: trim, cap length, reject obvious junk.
|
|
50
|
+
* Returns null when the value should be treated as absent (missing,
|
|
51
|
+
* non-string, empty after trim).
|
|
52
|
+
*
|
|
53
|
+
* Exported for testability — invariants matter more here than elsewhere
|
|
54
|
+
* because the output is user-visible and paid for.
|
|
55
|
+
*/
|
|
56
|
+
export declare function validateRefined(raw: unknown, maxChars: number): string | null;
|
|
57
|
+
/**
|
|
58
|
+
* Whitespace-insensitive, case-insensitive identity check — if the
|
|
59
|
+
* classifier's "refinement" is just the input with different spacing,
|
|
60
|
+
* don't bother the user with a "Refined:" block.
|
|
61
|
+
*/
|
|
62
|
+
export declare function isEffectivelyIdentical(a: string, b: string): boolean;
|
|
63
|
+
export declare const REFINED_PROMPT_MAX_CHARS = 500;
|
|
64
|
+
export declare const REFINEMENT_SUMMARY_LIMIT = 80;
|
|
65
|
+
export interface AnalyzeMediaOpts {
|
|
66
|
+
kind: MediaKind;
|
|
67
|
+
prompt: string;
|
|
68
|
+
client: ModelClient;
|
|
69
|
+
quantity?: number;
|
|
70
|
+
durationSeconds?: number;
|
|
71
|
+
signal?: AbortSignal;
|
|
72
|
+
/**
|
|
73
|
+
* One-shot opt-out — caller stripped a `///` prefix from the user's input
|
|
74
|
+
* and wants the proposal rendered without a Refined block or Use-original
|
|
75
|
+
* option. The classifier still runs (for model selection), but the
|
|
76
|
+
* refinement is discarded at parse time.
|
|
77
|
+
*/
|
|
78
|
+
skipRefine?: boolean;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Pick the best model + alternatives for this media request. Returns null
|
|
82
|
+
* on any failure path (classifier timeout, parse error, empty catalog) so
|
|
83
|
+
* the caller can fall back to its old hardcoded default rather than
|
|
84
|
+
* blocking the user.
|
|
85
|
+
*/
|
|
86
|
+
export declare function analyzeMediaRequest(opts: AnalyzeMediaOpts): Promise<MediaProposal | null>;
|
|
87
|
+
/**
|
|
88
|
+
* Render a proposal as the user-facing AskUser question. Layout matches
|
|
89
|
+
* the spec from v3.8.31 planning: recommended first with • bullet,
|
|
90
|
+
* alternatives below with ○ bullets, prices include the 5% margin note.
|
|
91
|
+
*/
|
|
92
|
+
export declare function renderProposalForAskUser(p: MediaProposal, userPrompt: string): {
|
|
93
|
+
question: string;
|
|
94
|
+
options: Array<{
|
|
95
|
+
id: string;
|
|
96
|
+
label: string;
|
|
97
|
+
}>;
|
|
98
|
+
};
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media router — one LLM call that picks which image/video model fits
|
|
3
|
+
* the user's request, with alternatives and cost estimates, so the agent
|
|
4
|
+
* can show a clean AskUser proposal before spending.
|
|
5
|
+
*
|
|
6
|
+
* Principle (matches turn-analyzer): harness orchestrates, free model
|
|
7
|
+
* decides. No keyword-to-model mapping in TypeScript. Classifier reads
|
|
8
|
+
* the prompt + the current gateway catalog (pulled dynamically), picks
|
|
9
|
+
* one recommended model plus a cheaper + a premium alternative, and
|
|
10
|
+
* explains the choice in one sentence.
|
|
11
|
+
*
|
|
12
|
+
* Cost estimates come from `gateway-models.ts` — always dynamic,
|
|
13
|
+
* margin-adjusted.
|
|
14
|
+
*/
|
|
15
|
+
import { getModelsByCategory, estimateCostUsd, defaultDurationSeconds, maxDurationSeconds, } from '../gateway-models.js';
|
|
16
|
+
// ─── Classifier ─────────────────────────────────────────────────────────
|
|
17
|
+
const CLASSIFIER_MODEL = process.env.FRANKLIN_MEDIA_ROUTER_MODEL || 'nvidia/llama-4-maverick';
|
|
18
|
+
const TIMEOUT_MS = 3_500; // slightly more lenient than the turn-analyzer — we're asking for JSON with reasoning
|
|
19
|
+
const MAX_TOKENS = 384; // bumped from 256 to leave room for refined_prompt (≤500 chars) + refinement_summary (≤80)
|
|
20
|
+
const REFINED_MAX_CHARS = 500;
|
|
21
|
+
const REFINEMENT_SUMMARY_MAX_CHARS = 80;
|
|
22
|
+
function buildSystemPrompt(kind, catalog) {
|
|
23
|
+
const catalogLines = catalog.map(m => {
|
|
24
|
+
const p = m.pricing;
|
|
25
|
+
const price = kind === 'image'
|
|
26
|
+
? `$${(p.per_image ?? 0).toFixed(4)}/image`
|
|
27
|
+
: `$${(p.per_second ?? 0).toFixed(2)}/s (default ${p.default_duration_seconds ?? 8}s, max ${p.max_duration_seconds ?? 8}s)`;
|
|
28
|
+
return ` - ${m.id} · ${price} · ${m.description || m.name}`;
|
|
29
|
+
}).join('\n');
|
|
30
|
+
return `You pick the best ${kind} model for a user's Franklin request AND refine the user's prompt. Output ONE LINE of compact JSON. No markdown, no code fences, no explanation.
|
|
31
|
+
|
|
32
|
+
## Catalog (${catalog.length} available ${kind} models)
|
|
33
|
+
${catalogLines}
|
|
34
|
+
|
|
35
|
+
## Output schema
|
|
36
|
+
|
|
37
|
+
{"style":"photoreal|illustration|anime|logo|concept|other",
|
|
38
|
+
"priority":"cost|quality|balanced",
|
|
39
|
+
"refined_prompt":"<rewritten prompt in the user's language, <=${REFINED_MAX_CHARS} chars, or null if already well-specified>",
|
|
40
|
+
"refinement_summary":"<one short sentence, <=${REFINEMENT_SUMMARY_MAX_CHARS} chars, user-visible>",
|
|
41
|
+
"recommended":{"model":"<id from catalog>","rationale":"<one sentence, <=140 chars>"},
|
|
42
|
+
"cheaper":{"model":"<id from catalog | null>","rationale":"<one sentence>"},
|
|
43
|
+
"premium":{"model":"<id from catalog | null>","rationale":"<one sentence>"}}
|
|
44
|
+
|
|
45
|
+
Rules:
|
|
46
|
+
- recommended is always set to an id from the catalog.
|
|
47
|
+
- cheaper / premium may be null if no strictly cheaper / better option exists.
|
|
48
|
+
- Never invent a model id. Use EXACTLY one of the catalog ids.
|
|
49
|
+
- Match style → model: anime/illustration prefers CogView, photoreal prefers Nano Banana Pro / Grok Imagine Pro, budget-conscious picks cheapest-acceptable.
|
|
50
|
+
- One sentence rationale, user-visible.
|
|
51
|
+
|
|
52
|
+
## Refinement (emit refined_prompt + refinement_summary)
|
|
53
|
+
|
|
54
|
+
If the user's prompt is missing ≥3 of these 5 slots, rewrite to fill them. If it already has ≥3 covered, set refined_prompt to null and refinement_summary to "Already well-specified".
|
|
55
|
+
|
|
56
|
+
1. Scene — location, time of day, environment, background
|
|
57
|
+
2. Subject — primary focus (who / what), preserved EXACTLY from the user's input (no substitution)
|
|
58
|
+
3. Details — materials, textures, lighting, camera/lens feel, composition, mood (concrete visual facts, not praise)
|
|
59
|
+
4. Use Case — editorial photo, product mockup, UI screen, logo, storyboard frame, social-media cover, etc.
|
|
60
|
+
5. Constraints — aspect ratio, what must not drift (no watermark, preserve face, no text), hard asks
|
|
61
|
+
|
|
62
|
+
Anti-slop rules:
|
|
63
|
+
- Concrete visual facts ("overcast daylight", "brushed aluminum") beat vague praise ("stunning", "cinematic masterpiece").
|
|
64
|
+
- Wrap literal text that must appear in the image in double quotes. Spell difficult words letter-by-letter.
|
|
65
|
+
- One revision per turn — do not combine conflicting asks.
|
|
66
|
+
- Natural language, not keyword-tag format.
|
|
67
|
+
- refined_prompt stays in the same language as the user input.
|
|
68
|
+
|
|
69
|
+
Examples:
|
|
70
|
+
|
|
71
|
+
Input: "a photo of a cat on Mars, photoreal"
|
|
72
|
+
Output: {"style":"photoreal","priority":"balanced","refined_prompt":"Eye-level photograph of a cat standing on the rust-colored Martian surface, late-afternoon low sun casting long shadows, distant canyon rim in the background, 50mm feel, shallow depth of field, editorial photo use, no watermark.","refinement_summary":"Added scene, lighting, lens, use case, constraint.","recommended":{"model":"google/nano-banana-pro","rationale":"Photoreal scenes — Nano Banana Pro has strong realism at moderate cost."},"cheaper":{"model":"google/nano-banana","rationale":"Same family, lower cost, slightly less detail."},"premium":{"model":"openai/gpt-image-2","rationale":"Best photoreal fidelity when budget allows."}}
|
|
73
|
+
|
|
74
|
+
Input: "cyberpunk-style anime character"
|
|
75
|
+
Output: {"style":"anime","priority":"balanced","refined_prompt":"Cyberpunk-style anime character standing on a neon-lit rainy street at night, wearing a synthetic-fiber jacket with metallic reflective accents, holographic billboards floating overhead, low-angle view, strong cyan-and-pink contrast, poster use, centered composition.","refinement_summary":"Added scene, lighting, materials, use case, composition.","recommended":{"model":"zai/cogview-4","rationale":"CogView-4 specializes in stylized/anime imagery."},"cheaper":{"model":"google/nano-banana","rationale":"Cheaper but less stylized."},"premium":{"model":"xai/grok-imagine-image-pro","rationale":"Premium detail for complex scenes."}}
|
|
76
|
+
|
|
77
|
+
Input: "a 10-second cinematic drone shot over Tokyo at night"
|
|
78
|
+
Output: {"style":"concept","priority":"quality","refined_prompt":null,"refinement_summary":"Already well-specified.","recommended":{"model":"bytedance/seedance-2.0","rationale":"Seedance 2.0 delivers the best cinematic quality."},"cheaper":{"model":"bytedance/seedance-2.0-fast","rationale":"Faster + cheaper, minor quality trade-off."},"premium":{"model":null,"rationale":"2.0 is already the top tier."}}
|
|
79
|
+
|
|
80
|
+
Output JSON only, single line.`;
|
|
81
|
+
}
|
|
82
|
+
const cache = new Map();
|
|
83
|
+
const CACHE_TTL_MS = 30_000;
|
|
84
|
+
const CACHE_MAX = 32;
|
|
85
|
+
function hashKey(parts) {
|
|
86
|
+
const s = parts.join('|');
|
|
87
|
+
let h = 0;
|
|
88
|
+
for (let i = 0; i < s.length; i++)
|
|
89
|
+
h = ((h << 5) - h + s.charCodeAt(i)) | 0;
|
|
90
|
+
return String(h);
|
|
91
|
+
}
|
|
92
|
+
export function clearMediaRouterCache() { cache.clear(); }
|
|
93
|
+
// ─── Parser ─────────────────────────────────────────────────────────────
|
|
94
|
+
const VALID_STYLES = new Set(['photoreal', 'illustration', 'anime', 'logo', 'concept', 'other']);
|
|
95
|
+
const VALID_PRIORITIES = new Set(['cost', 'quality', 'balanced']);
|
|
96
|
+
function validateChoice(raw, catalog) {
|
|
97
|
+
if (!raw || typeof raw !== 'object')
|
|
98
|
+
return null;
|
|
99
|
+
const id = typeof raw.model === 'string' ? raw.model : '';
|
|
100
|
+
const model = catalog.get(id);
|
|
101
|
+
if (!model)
|
|
102
|
+
return null;
|
|
103
|
+
const rationale = typeof raw.rationale === 'string' ? raw.rationale.slice(0, 240) : '';
|
|
104
|
+
return { model, rationale };
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Normalize a refined prompt: trim, cap length, reject obvious junk.
|
|
108
|
+
* Returns null when the value should be treated as absent (missing,
|
|
109
|
+
* non-string, empty after trim).
|
|
110
|
+
*
|
|
111
|
+
* Exported for testability — invariants matter more here than elsewhere
|
|
112
|
+
* because the output is user-visible and paid for.
|
|
113
|
+
*/
|
|
114
|
+
export function validateRefined(raw, maxChars) {
|
|
115
|
+
if (typeof raw !== 'string')
|
|
116
|
+
return null;
|
|
117
|
+
const trimmed = raw.trim();
|
|
118
|
+
if (trimmed.length === 0)
|
|
119
|
+
return null;
|
|
120
|
+
return trimmed.slice(0, maxChars);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Whitespace-insensitive, case-insensitive identity check — if the
|
|
124
|
+
* classifier's "refinement" is just the input with different spacing,
|
|
125
|
+
* don't bother the user with a "Refined:" block.
|
|
126
|
+
*/
|
|
127
|
+
export function isEffectivelyIdentical(a, b) {
|
|
128
|
+
const normalize = (s) => s.toLowerCase().replace(/\s+/g, ' ').trim();
|
|
129
|
+
return normalize(a) === normalize(b);
|
|
130
|
+
}
|
|
131
|
+
export const REFINED_PROMPT_MAX_CHARS = REFINED_MAX_CHARS;
|
|
132
|
+
export const REFINEMENT_SUMMARY_LIMIT = REFINEMENT_SUMMARY_MAX_CHARS;
|
|
133
|
+
/**
|
|
134
|
+
* Pick the best model + alternatives for this media request. Returns null
|
|
135
|
+
* on any failure path (classifier timeout, parse error, empty catalog) so
|
|
136
|
+
* the caller can fall back to its old hardcoded default rather than
|
|
137
|
+
* blocking the user.
|
|
138
|
+
*/
|
|
139
|
+
export async function analyzeMediaRequest(opts) {
|
|
140
|
+
if (process.env.FRANKLIN_NO_MEDIA_ROUTER === '1')
|
|
141
|
+
return null;
|
|
142
|
+
const { kind, prompt, client } = opts;
|
|
143
|
+
if (!prompt || prompt.trim().length === 0)
|
|
144
|
+
return null;
|
|
145
|
+
// Pull catalog first — if the gateway doesn't have any models in this
|
|
146
|
+
// category, there's nothing to recommend.
|
|
147
|
+
const catalog = await getModelsByCategory(kind).catch(() => []);
|
|
148
|
+
if (catalog.length === 0)
|
|
149
|
+
return null;
|
|
150
|
+
// Cache check — classifier output is stable for a given prompt + catalog
|
|
151
|
+
// version, so re-asking within 30s is waste. Cache stores the FULL
|
|
152
|
+
// classifier response (refinement + model picks); the per-call mask for
|
|
153
|
+
// skipRefine / FRANKLIN_NO_MEDIA_PROMPT_REFINE is applied on the way out
|
|
154
|
+
// so the same cache entry serves callers with different opt-out flags.
|
|
155
|
+
const quantity = Math.max(1, Math.floor(opts.quantity ?? 1));
|
|
156
|
+
const globalOptOut = process.env.FRANKLIN_NO_MEDIA_PROMPT_REFINE === '1';
|
|
157
|
+
const shouldDiscard = globalOptOut || opts.skipRefine === true;
|
|
158
|
+
const maskRefinement = (p) => shouldDiscard ? { ...p, refinedPrompt: null, refinementSummary: '' } : p;
|
|
159
|
+
const key = hashKey([kind, prompt.trim().slice(0, 500), String(quantity), String(opts.durationSeconds ?? '')]);
|
|
160
|
+
const hit = cache.get(key);
|
|
161
|
+
if (hit && hit.expiresAt > Date.now())
|
|
162
|
+
return maskRefinement(hit.value);
|
|
163
|
+
// Call the classifier.
|
|
164
|
+
const catalogMap = new Map(catalog.map(m => [m.id, m]));
|
|
165
|
+
const system = buildSystemPrompt(kind, catalog);
|
|
166
|
+
const ctrl = new AbortController();
|
|
167
|
+
const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
|
|
168
|
+
const signal = opts.signal ? combineSignals([opts.signal, ctrl.signal]) : ctrl.signal;
|
|
169
|
+
let raw = '';
|
|
170
|
+
try {
|
|
171
|
+
const response = await client.complete({
|
|
172
|
+
model: CLASSIFIER_MODEL,
|
|
173
|
+
system,
|
|
174
|
+
messages: [{ role: 'user', content: prompt.slice(0, 1000) }],
|
|
175
|
+
tools: [],
|
|
176
|
+
max_tokens: MAX_TOKENS,
|
|
177
|
+
}, signal);
|
|
178
|
+
for (const part of response.content) {
|
|
179
|
+
if (typeof part === 'object' && part.type === 'text' && part.text)
|
|
180
|
+
raw += part.text;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
clearTimeout(timer);
|
|
188
|
+
}
|
|
189
|
+
// Parse one-line JSON (may be wrapped in stray text).
|
|
190
|
+
const match = raw.match(/\{[\s\S]*\}/);
|
|
191
|
+
if (!match)
|
|
192
|
+
return null;
|
|
193
|
+
let parsed;
|
|
194
|
+
try {
|
|
195
|
+
parsed = JSON.parse(match[0]);
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
const style = typeof parsed.style === 'string' && VALID_STYLES.has(parsed.style)
|
|
201
|
+
? parsed.style : 'other';
|
|
202
|
+
const priority = typeof parsed.priority === 'string' && VALID_PRIORITIES.has(parsed.priority)
|
|
203
|
+
? parsed.priority : 'balanced';
|
|
204
|
+
const rec = validateChoice(parsed.recommended, catalogMap);
|
|
205
|
+
if (!rec)
|
|
206
|
+
return null;
|
|
207
|
+
const cheaperChoice = validateChoice(parsed.cheaper, catalogMap);
|
|
208
|
+
const premiumChoice = validateChoice(parsed.premium, catalogMap);
|
|
209
|
+
// Refinement fields. The cache stores the full classifier output; the
|
|
210
|
+
// per-call mask is applied on the way out via maskRefinement() above, so
|
|
211
|
+
// here we just normalize + discard rewrites that are effectively the
|
|
212
|
+
// same as the raw input (drift-proof).
|
|
213
|
+
let refinedPrompt = validateRefined(parsed.refined_prompt, REFINED_MAX_CHARS);
|
|
214
|
+
const refinementSummary = validateRefined(parsed.refinement_summary, REFINEMENT_SUMMARY_MAX_CHARS) ?? '';
|
|
215
|
+
if (refinedPrompt !== null && isEffectivelyIdentical(refinedPrompt, prompt)) {
|
|
216
|
+
refinedPrompt = null;
|
|
217
|
+
}
|
|
218
|
+
// Build proposal with live cost estimates.
|
|
219
|
+
const durationSeconds = kind === 'video'
|
|
220
|
+
? (opts.durationSeconds ?? defaultDurationSeconds(rec.model))
|
|
221
|
+
: undefined;
|
|
222
|
+
const maxDur = kind === 'video' ? (maxDurationSeconds(rec.model) ?? undefined) : undefined;
|
|
223
|
+
const toChoice = (c) => {
|
|
224
|
+
if (!c || c.model.id === rec.model.id)
|
|
225
|
+
return undefined;
|
|
226
|
+
return {
|
|
227
|
+
model: c.model.id,
|
|
228
|
+
estimatedCostUsd: estimateCostUsd(c.model, { quantity, duration_seconds: durationSeconds }),
|
|
229
|
+
rationale: c.rationale,
|
|
230
|
+
};
|
|
231
|
+
};
|
|
232
|
+
const recommended = {
|
|
233
|
+
model: rec.model.id,
|
|
234
|
+
estimatedCostUsd: estimateCostUsd(rec.model, { quantity, duration_seconds: durationSeconds }),
|
|
235
|
+
rationale: rec.rationale,
|
|
236
|
+
};
|
|
237
|
+
const proposal = {
|
|
238
|
+
kind,
|
|
239
|
+
quantity,
|
|
240
|
+
durationSeconds,
|
|
241
|
+
maxDurationSeconds: maxDur,
|
|
242
|
+
recommended,
|
|
243
|
+
cheaper: toChoice(cheaperChoice),
|
|
244
|
+
premium: toChoice(premiumChoice),
|
|
245
|
+
intent: { style, priority },
|
|
246
|
+
refinedPrompt,
|
|
247
|
+
refinementSummary,
|
|
248
|
+
totalCostUsd: recommended.estimatedCostUsd,
|
|
249
|
+
};
|
|
250
|
+
// Evict oldest if bounded
|
|
251
|
+
if (cache.size >= CACHE_MAX) {
|
|
252
|
+
const firstKey = cache.keys().next().value;
|
|
253
|
+
if (firstKey)
|
|
254
|
+
cache.delete(firstKey);
|
|
255
|
+
}
|
|
256
|
+
cache.set(key, { value: proposal, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
257
|
+
return maskRefinement(proposal);
|
|
258
|
+
}
|
|
259
|
+
// ─── Presentation ───────────────────────────────────────────────────────
|
|
260
|
+
/**
|
|
261
|
+
* Render a proposal as the user-facing AskUser question. Layout matches
|
|
262
|
+
* the spec from v3.8.31 planning: recommended first with • bullet,
|
|
263
|
+
* alternatives below with ○ bullets, prices include the 5% margin note.
|
|
264
|
+
*/
|
|
265
|
+
export function renderProposalForAskUser(p, userPrompt) {
|
|
266
|
+
const lines = [];
|
|
267
|
+
lines.push(`*Media generation proposal*`);
|
|
268
|
+
lines.push('');
|
|
269
|
+
lines.push(`Prompt: "${userPrompt.trim().slice(0, 200)}"`);
|
|
270
|
+
if (p.refinedPrompt) {
|
|
271
|
+
lines.push('');
|
|
272
|
+
lines.push(`Refined: ${p.refinedPrompt}`);
|
|
273
|
+
if (p.refinementSummary) {
|
|
274
|
+
lines.push(` (${p.refinementSummary})`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (p.kind === 'video' && p.durationSeconds) {
|
|
278
|
+
const maxNote = p.maxDurationSeconds ? ` (max ${p.maxDurationSeconds}s)` : '';
|
|
279
|
+
lines.push(`Duration: ${p.durationSeconds}s${maxNote}`);
|
|
280
|
+
}
|
|
281
|
+
else if (p.kind === 'image' && p.quantity > 1) {
|
|
282
|
+
lines.push(`Quantity: ${p.quantity} images`);
|
|
283
|
+
}
|
|
284
|
+
lines.push('');
|
|
285
|
+
lines.push(` ● Recommended ${p.recommended.model.padEnd(32)} ~${formatUsd(p.recommended.estimatedCostUsd)} ${p.recommended.rationale}`);
|
|
286
|
+
if (p.cheaper) {
|
|
287
|
+
lines.push(` ○ Cheaper ${p.cheaper.model.padEnd(32)} ~${formatUsd(p.cheaper.estimatedCostUsd)} ${p.cheaper.rationale}`);
|
|
288
|
+
}
|
|
289
|
+
if (p.premium) {
|
|
290
|
+
lines.push(` ○ Premium ${p.premium.model.padEnd(32)} ~${formatUsd(p.premium.estimatedCostUsd)} ${p.premium.rationale}`);
|
|
291
|
+
}
|
|
292
|
+
lines.push('');
|
|
293
|
+
lines.push(` (prices include the 5% gateway fee)`);
|
|
294
|
+
const options = [];
|
|
295
|
+
const recLabel = p.refinedPrompt
|
|
296
|
+
? `Continue with refined prompt + ${p.recommended.model}`
|
|
297
|
+
: `Continue with ${p.recommended.model}`;
|
|
298
|
+
options.push({ id: 'recommended', label: recLabel });
|
|
299
|
+
if (p.cheaper)
|
|
300
|
+
options.push({ id: 'cheaper', label: `Use cheaper (${p.cheaper.model})` });
|
|
301
|
+
if (p.premium)
|
|
302
|
+
options.push({ id: 'premium', label: `Use premium (${p.premium.model})` });
|
|
303
|
+
if (p.refinedPrompt) {
|
|
304
|
+
options.push({ id: 'use-raw', label: `Use ORIGINAL prompt + ${p.recommended.model}` });
|
|
305
|
+
}
|
|
306
|
+
options.push({ id: 'cancel', label: 'Cancel (no charge)' });
|
|
307
|
+
return { question: lines.join('\n'), options };
|
|
308
|
+
}
|
|
309
|
+
function formatUsd(n) {
|
|
310
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
311
|
+
return '$0.00';
|
|
312
|
+
if (n < 0.01)
|
|
313
|
+
return `$${n.toFixed(4)}`;
|
|
314
|
+
if (n < 1)
|
|
315
|
+
return `$${n.toFixed(3)}`;
|
|
316
|
+
return `$${n.toFixed(2)}`;
|
|
317
|
+
}
|
|
318
|
+
function combineSignals(signals) {
|
|
319
|
+
const ctrl = new AbortController();
|
|
320
|
+
for (const s of signals) {
|
|
321
|
+
if (s.aborted) {
|
|
322
|
+
ctrl.abort();
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
325
|
+
s.addEventListener('abort', () => ctrl.abort(), { once: true });
|
|
326
|
+
}
|
|
327
|
+
return ctrl.signal;
|
|
328
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blockrun/franklin",
|
|
3
|
-
"version": "3.32.
|
|
3
|
+
"version": "3.32.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": {
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
"node": ">=20.19.0"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@blockrun/llm": "^
|
|
69
|
+
"@blockrun/llm": "^3.5.2",
|
|
70
70
|
"@colbymchenry/codegraph": "^0.9.7",
|
|
71
71
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
72
72
|
"@polymarket/builder-relayer-client": "^0.0.10",
|