@blockrun/franklin 3.29.15 → 3.30.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.
Files changed (33) hide show
  1. package/dist/commands/start.js +4 -10
  2. package/dist/stats/insights.js +1 -3
  3. package/dist/tools/index.js +3 -1
  4. package/dist/tools/polymarket/client.d.ts +61 -0
  5. package/dist/tools/polymarket/client.js +236 -0
  6. package/dist/tools/polymarket/constants.d.ts +192 -0
  7. package/dist/tools/polymarket/constants.js +205 -0
  8. package/dist/tools/polymarket/creds.d.ts +33 -0
  9. package/dist/tools/polymarket/creds.js +96 -0
  10. package/dist/tools/polymarket/fund.d.ts +5 -0
  11. package/dist/tools/polymarket/fund.js +141 -0
  12. package/dist/tools/polymarket/l1-auth-1271.d.ts +29 -0
  13. package/dist/tools/polymarket/l1-auth-1271.js +198 -0
  14. package/dist/tools/polymarket/orders.d.ts +44 -0
  15. package/dist/tools/polymarket/orders.js +420 -0
  16. package/dist/tools/polymarket/positions.d.ts +26 -0
  17. package/dist/tools/polymarket/positions.js +88 -0
  18. package/dist/tools/polymarket/redeem.d.ts +5 -0
  19. package/dist/tools/polymarket/redeem.js +121 -0
  20. package/dist/tools/polymarket/relayer.d.ts +37 -0
  21. package/dist/tools/polymarket/relayer.js +140 -0
  22. package/dist/tools/polymarket/setup.d.ts +9 -0
  23. package/dist/tools/polymarket/setup.js +360 -0
  24. package/dist/tools/polymarket/wallet-key.d.ts +14 -0
  25. package/dist/tools/polymarket/wallet-key.js +69 -0
  26. package/dist/tools/polymarket/withdraw.d.ts +8 -0
  27. package/dist/tools/polymarket/withdraw.js +108 -0
  28. package/dist/tools/polymarket-bet.d.ts +4 -0
  29. package/dist/tools/polymarket-bet.js +164 -0
  30. package/dist/tools/tool-categories.js +4 -0
  31. package/package.json +7 -2
  32. package/dist/agent/media-router.d.ts +0 -98
  33. package/dist/agent/media-router.js +0 -328
@@ -0,0 +1,164 @@
1
+ import { recordUsage } from '../stats/tracker.js';
2
+ import { logger } from '../logger.js';
3
+ import { ensurePolymarketWallet } from './polymarket/wallet-key.js';
4
+ import { executeTrade, listOpenOrders, cancelOrdersAction, getSessionLedger, } from './polymarket/orders.js';
5
+ import { listPositions } from './polymarket/positions.js';
6
+ import { redeemPosition } from './polymarket/redeem.js';
7
+ import { runSetup } from './polymarket/setup.js';
8
+ import { withdrawFunds } from './polymarket/withdraw.js';
9
+ import { fundVault } from './polymarket/fund.js';
10
+ // Actions that SIGN or MOVE money when confirm:true — these get the interactive
11
+ // human gate. reads (orders/positions) and cancel never spend, so they don't.
12
+ const PLACEMENT_ACTIONS = new Set(['setup', 'fund', 'buy', 'sell', 'redeem', 'withdraw']);
13
+ const FUND_FEE_USD = 0.01;
14
+ /** Route one action to its ported handler. `confirm` is threaded through so the
15
+ * caller can request a dry-run (confirm:false) or the real thing (confirm:true). */
16
+ async function dispatch(input, confirm) {
17
+ switch (input.action) {
18
+ case 'setup': {
19
+ const r = await runSetup({ confirm });
20
+ return { text: r.text, structured: r.structured };
21
+ }
22
+ case 'fund':
23
+ return fundVault({ amount_usd: input.amount_usd, confirm });
24
+ case 'buy':
25
+ case 'sell':
26
+ return executeTrade({
27
+ action: input.action,
28
+ token_id: input.token_id,
29
+ condition_id: input.condition_id,
30
+ outcome: input.outcome,
31
+ price: input.price,
32
+ size: input.size,
33
+ amount_usd: input.amount_usd,
34
+ order_type: input.order_type,
35
+ expires_at: input.expires_at,
36
+ post_only: input.post_only,
37
+ confirm,
38
+ agent_id: input.agent_id,
39
+ });
40
+ case 'orders':
41
+ return listOpenOrders({ condition_id: input.condition_id });
42
+ case 'cancel':
43
+ return cancelOrdersAction({ order_id: input.order_id, all: input.all });
44
+ case 'positions':
45
+ return listPositions();
46
+ case 'redeem':
47
+ return redeemPosition({ condition_id: input.condition_id, confirm });
48
+ case 'withdraw':
49
+ return withdrawFunds({ amount_usd: input.amount_usd, to_address: input.to_address, confirm });
50
+ default:
51
+ return { text: `Unknown action: ${String(input.action)}`, isError: true };
52
+ }
53
+ }
54
+ async function execute(raw, ctx) {
55
+ const input = raw;
56
+ if (!input.action) {
57
+ return { output: 'Pass an action: setup | fund | buy | sell | cancel | orders | positions | redeem | withdraw.', isError: true };
58
+ }
59
+ // Load-or-create the EVM session key so the synchronous signer inside the
60
+ // ported client can serve it. Must run before any dispatch.
61
+ try {
62
+ await ensurePolymarketWallet();
63
+ }
64
+ catch (err) {
65
+ return { output: `Wallet unavailable: ${err instanceof Error ? err.message : String(err)}`, isError: true };
66
+ }
67
+ const wantsConfirm = input.confirm === true;
68
+ const autoApprove = input.auto_approve === true || process.env.FRANKLIN_POLYMARKET_AUTO_APPROVE === '1';
69
+ // Interactive human gate — the agent proposed a real, signing action. Show the
70
+ // ACTUAL dry-run preview (built by the underlying handler) and require an
71
+ // explicit user Confirm before we sign anything on-chain.
72
+ if (PLACEMENT_ACTIONS.has(input.action) && wantsConfirm && !autoApprove && ctx.onAskUser) {
73
+ let previewText;
74
+ try {
75
+ const preview = await dispatch(input, false);
76
+ previewText = preview.text;
77
+ if (preview.isError) {
78
+ // The dry-run itself failed (bad params, insufficient balance, not set
79
+ // up) — surface that instead of prompting to sign a doomed action.
80
+ return { output: preview.text, isError: true, fullOutput: preview.text };
81
+ }
82
+ }
83
+ catch (err) {
84
+ return { output: `Preview failed: ${err instanceof Error ? err.message : String(err)}`, isError: true };
85
+ }
86
+ const answer = await ctx.onAskUser([
87
+ previewText,
88
+ '',
89
+ '⚠ REAL MONEY — confirming signs and submits this on-chain (Polygon). Proceed?',
90
+ ].join('\n'), ['Confirm', 'Cancel']);
91
+ if (answer.toLowerCase() !== 'confirm') {
92
+ return { output: 'Polymarket action cancelled by user.' };
93
+ }
94
+ }
95
+ // Execute for real (or return the dry-run when confirm was never requested).
96
+ const startedAt = Date.now();
97
+ let result;
98
+ try {
99
+ result = await dispatch(input, wantsConfirm);
100
+ }
101
+ catch (err) {
102
+ return { output: `Polymarket ${input.action} error: ${err instanceof Error ? err.message : String(err)}`, isError: true };
103
+ }
104
+ // Meter the $0.01 fund fee as x402 spend (it IS a BlockRun gateway charge on
105
+ // Base). Bet stakes are NOT metered here — they're the user's own pUSD, tracked
106
+ // separately by the session betting ledger in orders.ts.
107
+ if (input.action === 'fund' && !result.isError && result.structured?.success === true) {
108
+ try {
109
+ recordUsage('PolymarketBet:fund', 0, 0, FUND_FEE_USD, Date.now() - startedAt);
110
+ }
111
+ catch (err) {
112
+ logger.debug?.(`PolymarketBet: recordUsage failed: ${err instanceof Error ? err.message : String(err)}`);
113
+ }
114
+ }
115
+ if (result.isError) {
116
+ return { output: result.text, isError: true, fullOutput: result.text };
117
+ }
118
+ return { output: result.text, fullOutput: result.text };
119
+ }
120
+ export const polymarketBetCapability = {
121
+ spec: {
122
+ name: 'PolymarketBet',
123
+ description: 'Place and manage REAL-MONEY bets on Polymarket prediction markets (CLOB V2, Polygon). Orders spend pUSD in your Polymarket deposit wallet, signed locally by your BlockRun key. Discover markets/prices/token IDs with PredictionMarket first; this tool executes. ' +
124
+ 'Run action:"setup" FIRST (and again after funding) — it creates a gasless deposit wallet, checks pUSD balance + approvals, and reports your region status. Actions: ' +
125
+ '`setup` (create/inspect deposit wallet + approvals; confirm:true signs the approval batch), ' +
126
+ '`fund` (top up the vault from your OWN Base USDC, gasless, $0.01 fee; amount_usd required, confirm:true), ' +
127
+ '`buy`/`sell` (token_id or condition_id+outcome, plus price+size for a limit order or amount_usd for a market buy / size for a market sell; confirm:true to place, otherwise a dry-run preview — per-order cap POLYMARKET_MAX_BET_USD default $25), ' +
128
+ '`orders` (list open orders), `cancel` (order_id or all:true), ' +
129
+ '`positions` (holdings incl. redeemable winnings), ' +
130
+ '`redeem` (claim resolved winnings for condition_id; confirm:true), ' +
131
+ '`withdraw` (cash out pUSD → USDC on Base to your agent wallet; confirm:true). ' +
132
+ 'Prices are probabilities 0–1 on the market tick grid. Every confirm:true placement is shown to the user for approval before signing unless auto_approve is set. Order placement is geoblocked in some regions (setup reports status).',
133
+ input_schema: {
134
+ type: 'object',
135
+ properties: {
136
+ action: {
137
+ type: 'string',
138
+ enum: ['setup', 'fund', 'buy', 'sell', 'cancel', 'orders', 'positions', 'redeem', 'withdraw'],
139
+ description: 'Operation to perform.',
140
+ },
141
+ token_id: { type: 'string', description: 'Outcome token ID (decimal ERC-1155 id from PredictionMarket clobTokenIds).' },
142
+ condition_id: { type: 'string', description: 'Market condition ID (0x…). With `outcome` it resolves token_id; required for redeem.' },
143
+ outcome: { type: 'string', description: "Outcome label (e.g. 'Yes') — used with condition_id when token_id is omitted." },
144
+ price: { type: 'number', description: 'Limit price as probability (0–1). Omit for a market order.' },
145
+ size: { type: 'number', description: 'Shares — required for limit orders and market sells.' },
146
+ amount_usd: { type: 'number', description: 'pUSD dollars — to spend (market buy / fund) or cash out (withdraw; default full balance).' },
147
+ order_type: { type: 'string', enum: ['GTC', 'GTD', 'FOK', 'FAK'], description: 'Default GTC for limit orders, FOK for market orders.' },
148
+ expires_at: { type: 'number', description: 'Unix seconds expiry (GTD only, ≥ ~3 min in the future).' },
149
+ post_only: { type: 'boolean', description: 'Maker-only limit order (rejected if it would cross the book).' },
150
+ order_id: { type: 'string', description: 'Order ID to cancel.' },
151
+ all: { type: 'boolean', description: 'cancel: cancel ALL open orders.' },
152
+ to_address: { type: 'string', description: 'withdraw: destination address on Base (default: your agent wallet).' },
153
+ confirm: { type: 'boolean', description: 'Must be true to place orders / sign approvals / redeem. Omit for a dry-run preview.' },
154
+ auto_approve: { type: 'boolean', description: 'Skip the interactive user confirmation prompt (headless use). Caps still apply.' },
155
+ agent_id: { type: 'string', description: 'Tag for the session betting ledger (bets do NOT draw from the x402 API budget).' },
156
+ },
157
+ required: ['action'],
158
+ },
159
+ },
160
+ execute,
161
+ // Betting mutates order/wallet state; serialize rather than run in parallel.
162
+ concurrent: false,
163
+ };
164
+ export { getSessionLedger };
@@ -49,6 +49,10 @@ export const CORE_TOOL_NAMES = new Set([
49
49
  // category. Cross-platform pair lookup is unique to the gateway and
50
50
  // is the kind of data a non-wallet agent fundamentally cannot reach.
51
51
  'PredictionMarket',
52
+ // Real-money Polymarket betting — the execution half of the prediction-market
53
+ // story: setup wallet, fund, buy/sell, positions, redeem, withdraw. Core so
54
+ // the agent reaches for it the moment "place the bet" follows the research.
55
+ 'PolymarketBet',
52
56
  // Crypto market data — fear/greed, token rankings, ETF flows, options,
53
57
  // liquidations, technical & on-chain indicators. The "what's the crypto
54
58
  // mood / which coins are pumping / BTC's RSI" category. Core so the agent
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.29.15",
3
+ "version": "3.30.0",
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/exa.local.mjs test/audit-batch.local.mjs",
34
+ "test": "npm run build && node --test --test-reporter=spec test/local.mjs test/skills.local.mjs test/repair.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.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",
@@ -69,13 +69,18 @@
69
69
  "@blockrun/llm": "^2.0.0",
70
70
  "@colbymchenry/codegraph": "^0.9.7",
71
71
  "@modelcontextprotocol/sdk": "^1.29.0",
72
+ "@polymarket/builder-relayer-client": "^0.0.10",
73
+ "@polymarket/builder-signing-sdk": "0.0.8",
74
+ "@polymarket/clob-client-v2": "1.0.8",
72
75
  "@slack/bolt": "^4.7.3",
73
76
  "@solana/spl-token": "^0.4.14",
74
77
  "@solana/web3.js": "^1.98.4",
75
78
  "@types/react": "^19.2.14",
79
+ "axios": "^1.18.1",
76
80
  "bs58": "^6.0.0",
77
81
  "chalk": "^5.4.0",
78
82
  "commander": "^13.0.0",
83
+ "https-proxy-agent": "^9.1.0",
79
84
  "ink": "^6.8.0",
80
85
  "ink-spinner": "^5.0.0",
81
86
  "ink-text-input": "^6.0.0",
@@ -1,98 +0,0 @@
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
- };
@@ -1,328 +0,0 @@
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
- }