@blockrun/franklin 3.30.1 → 3.32.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 (43) hide show
  1. package/dist/agent/commands.js +72 -2
  2. package/dist/agent/compact.js +1 -1
  3. package/dist/agent/evaluator.js +1 -1
  4. package/dist/agent/llm.d.ts +1 -1
  5. package/dist/agent/llm.js +64 -19
  6. package/dist/agent/loop.js +23 -4
  7. package/dist/agent/optimize.js +10 -0
  8. package/dist/agent/permissions.js +17 -0
  9. package/dist/agent/tokens.js +23 -2
  10. package/dist/agent/turn-analyzer.js +1 -1
  11. package/dist/agent/types.d.ts +24 -0
  12. package/dist/agent/verification.js +1 -1
  13. package/dist/commands/predict.d.ts +10 -0
  14. package/dist/commands/predict.js +143 -0
  15. package/dist/commands/slack.js +1 -1
  16. package/dist/commands/social.js +1 -1
  17. package/dist/commands/start.js +24 -7
  18. package/dist/commands/telegram.js +1 -1
  19. package/dist/config.d.ts +1 -0
  20. package/dist/config.js +6 -0
  21. package/dist/index.js +12 -0
  22. package/dist/learnings/extractor.js +2 -2
  23. package/dist/market/client.d.ts +69 -0
  24. package/dist/market/client.js +230 -0
  25. package/dist/plugin-sdk/workflow.js +3 -3
  26. package/dist/pricing.js +27 -6
  27. package/dist/proxy/fallback.js +1 -1
  28. package/dist/proxy/server.js +6 -86
  29. package/dist/router/index.js +14 -13
  30. package/dist/router/vision.js +15 -3
  31. package/dist/serve/server.js +4 -1
  32. package/dist/tools/agent-talent.d.ts +15 -0
  33. package/dist/tools/agent-talent.js +116 -0
  34. package/dist/tools/defillama.js +6 -5
  35. package/dist/tools/index.d.ts +15 -0
  36. package/dist/tools/index.js +28 -0
  37. package/dist/tools/moa.js +3 -3
  38. package/dist/tools/prediction.js +11 -10
  39. package/dist/tools/subagent.js +1 -1
  40. package/dist/tools/trading.js +3 -2
  41. package/dist/ui/model-picker.d.ts +26 -1
  42. package/dist/ui/model-picker.js +107 -38
  43. package/package.json +2 -2
@@ -0,0 +1,143 @@
1
+ /**
2
+ * `franklin predict` — Franklin prediction mode (headless).
3
+ *
4
+ * Runs ONE model as a disciplined forecaster: it researches a single real-world
5
+ * event with a tight, read-only toolset (web search, source fetch, Exa, X, live
6
+ * prediction markets, a little market data) the way a bettor would before
7
+ * putting money down — then commits to a pick with a confidence.
8
+ *
9
+ * Designed for machine callers (e.g. BlockRun Oracle): with --json it emits a
10
+ * single JSON envelope on stdout containing the model's final answer, the full
11
+ * tool-call trace (what it searched and what it found), the terminal reason and
12
+ * token usage. Human-readable streaming otherwise.
13
+ *
14
+ * franklin predict --model anthropic/claude-opus-4.8 \
15
+ * --question "Who wins the 2026 FIFA World Cup? Pick one country." --json
16
+ */
17
+ import { interactiveSession } from '../agent/loop.js';
18
+ import { predictionCapabilities, resetToolSessionState } from '../tools/index.js';
19
+ import { loadChain, API_URLS } from '../config.js';
20
+ import { resolveModel } from '../ui/model-picker.js';
21
+ const PREDICTION_SYSTEM = [
22
+ 'You are a sharp, disciplined forecasting analyst — think like a professional who is about to put real money on this question.',
23
+ 'Your job: predict the outcome of ONE real-world event. Before answering you MUST do research the way a bettor would:',
24
+ "1. Use web_search (and webfetch / exa tools) for the most CURRENT facts and news — today's real-world state matters far more than your training data.",
25
+ '2. Use search_prediction_markets to read the CURRENT market-implied odds (Polymarket, Kalshi, etc.) for this or a closely related question.',
26
+ '3. Weigh it: where is the consensus, where might the market be mispriced, what is your edge.',
27
+ 'Budget your research: make AT MOST 4-5 focused tool calls in total. As soon as you have enough to decide, STOP calling tools and output the JSON. Do not keep researching — an answer with light research beats no answer.',
28
+ 'Your FINAL message must end with EXACTLY ONE single-line minified JSON object and NOTHING after it:',
29
+ '{"pick": string, "confidence": number, "rationale": string, "analysis": string, "marketOdds": string}',
30
+ '- pick: one option from the question (a short label, e.g. a country, party, bucket, or Yes/No).',
31
+ '- confidence: your probability (0-1) that THIS pick is correct.',
32
+ '- rationale: one sharp sentence (max 22 words).',
33
+ '- analysis: 3-5 sentences citing what your research found, the strongest counter-argument, and why you still land here. No literal newlines inside the string.',
34
+ "- marketOdds: what the prediction market currently implies (e.g. 'Polymarket: France 18%'), or 'n/a' if none found.",
35
+ 'Be decisive. Do not hedge with "it depends".',
36
+ ];
37
+ export async function predictCommand(options) {
38
+ const question = options.question?.trim();
39
+ if (!question) {
40
+ process.stderr.write('predict: --question is required\n');
41
+ process.exitCode = 1;
42
+ return;
43
+ }
44
+ if (!options.model) {
45
+ process.stderr.write('predict: --model is required\n');
46
+ process.exitCode = 1;
47
+ return;
48
+ }
49
+ const chain = loadChain();
50
+ const apiUrl = API_URLS[chain];
51
+ const model = resolveModel(options.model);
52
+ const asJson = options.json !== false;
53
+ resetToolSessionState();
54
+ const agentConfig = {
55
+ model,
56
+ apiUrl,
57
+ chain,
58
+ systemInstructions: PREDICTION_SYSTEM,
59
+ capabilities: predictionCapabilities,
60
+ maxTurns: options.maxTurns != null ? Number(options.maxTurns) : 8,
61
+ permissionMode: 'trust',
62
+ debug: !!options.debug,
63
+ showPrefetchStatus: false,
64
+ // Governance for one-shot forecasting: bound research by tool-call count and
65
+ // force an answer; don't silently switch models or fight a grounding retry.
66
+ // Tool budget (5) is the real research limiter; maxTurns (8) is just slack
67
+ // above it for a thinking turn + the forced-answer turn.
68
+ forceAnswerOnFinalTurn: true,
69
+ maxToolCalls: options.maxToolCalls != null ? Number(options.maxToolCalls) : 6,
70
+ disableModelFallback: true,
71
+ disableGroundingRetry: true,
72
+ ...(options.maxSpend != null ? { maxSpendUsd: Number(options.maxSpend) } : {}),
73
+ };
74
+ let finalText = '';
75
+ let turnReason = 'completed';
76
+ let turnError;
77
+ let inputTokens = 0;
78
+ let outputTokens = 0;
79
+ const trace = [];
80
+ const nameById = new Map();
81
+ const inputById = new Map();
82
+ const previewById = new Map();
83
+ let delivered = false;
84
+ const getInput = async () => {
85
+ if (delivered)
86
+ return null;
87
+ delivered = true;
88
+ return question;
89
+ };
90
+ await interactiveSession(agentConfig, getInput, (event) => {
91
+ switch (event.kind) {
92
+ case 'text_delta':
93
+ finalText += event.text;
94
+ if (!asJson)
95
+ process.stdout.write(event.text);
96
+ break;
97
+ case 'capability_start':
98
+ nameById.set(event.id, event.name);
99
+ inputById.set(event.id, '');
100
+ if (event.preview)
101
+ previewById.set(event.id, event.preview);
102
+ if (!asJson)
103
+ process.stderr.write(`\n · ${event.name}${event.preview ? ` ${event.preview}` : ''}\n`);
104
+ break;
105
+ case 'capability_input_delta':
106
+ inputById.set(event.id, (inputById.get(event.id) || '') + event.delta);
107
+ break;
108
+ case 'capability_done': {
109
+ const tool = nameById.get(event.id) || 'tool';
110
+ const input = (inputById.get(event.id) || '').trim() || previewById.get(event.id) || '';
111
+ const output = event.result?.fullOutput || event.result?.output || '';
112
+ trace.push({ tool, input, output: output.slice(0, 1500), isError: event.result?.isError });
113
+ break;
114
+ }
115
+ case 'usage':
116
+ // Fires once per LLM call; accumulate across research turns so the
117
+ // --json envelope reports total spend, not just the final turn.
118
+ inputTokens += event.inputTokens;
119
+ outputTokens += event.outputTokens;
120
+ break;
121
+ case 'turn_done':
122
+ turnReason = event.reason;
123
+ turnError = event.error;
124
+ break;
125
+ }
126
+ });
127
+ if (asJson) {
128
+ const envelope = {
129
+ model,
130
+ question,
131
+ finalText: finalText.trim(),
132
+ trace,
133
+ turnReason,
134
+ ...(turnError ? { error: turnError } : {}),
135
+ usage: { inputTokens, outputTokens },
136
+ };
137
+ process.stdout.write(JSON.stringify(envelope) + '\n');
138
+ }
139
+ else if (turnReason !== 'completed' && turnError) {
140
+ process.stderr.write(`\n${turnError}\n`);
141
+ }
142
+ process.exitCode = turnReason === 'completed' ? 0 : 1;
143
+ }
@@ -41,7 +41,7 @@ export async function slackCommand(opts) {
41
41
  const config = loadConfig();
42
42
  const model = opts.model ||
43
43
  config['default-model'] ||
44
- 'nvidia/llama-4-maverick';
44
+ 'nvidia/qwen3-next-80b-a3b-instruct';
45
45
  const workingDir = process.cwd();
46
46
  const systemInstructions = assembleInstructions(workingDir, model);
47
47
  // Connect MCP servers (Notion, etc.) so the bot exposes their tools — mirrors
@@ -159,7 +159,7 @@ async function runCommand(options) {
159
159
  const chain = loadChain();
160
160
  const apiUrl = API_URLS[chain];
161
161
  const appConfig = loadAppConfig();
162
- const model = options.model || appConfig['default-model'] || 'nvidia/llama-4-maverick';
162
+ const model = options.model || appConfig['default-model'] || 'nvidia/qwen3-next-80b-a3b-instruct';
163
163
  console.log(chalk.dim(` Model: ${model}`));
164
164
  console.log('');
165
165
  let result;
@@ -13,7 +13,7 @@ import { interactiveSession } from '../agent/loop.js';
13
13
  import { allCapabilities, createSubAgentCapability } from '../tools/index.js';
14
14
  import { validateToolDescriptions } from '../tools/validate.js';
15
15
  import { launchInkUI } from '../ui/app.js';
16
- import { pickModel, resolveModel } from '../ui/model-picker.js';
16
+ import { pickModel, resolveModel, resolveModelStrict } from '../ui/model-picker.js';
17
17
  import { loadMcpConfig } from '../mcp/config.js';
18
18
  import { connectMcpServers, disconnectMcpServers, getMcpServerInstructions } from '../mcp/client.js';
19
19
  import { ensureCodegraphIndex } from '../mcp/codegraph.js';
@@ -620,9 +620,16 @@ async function runWithBasicUI(agentConfig, model, workDir, initialInput) {
620
620
  continue;
621
621
  }
622
622
  if (input.startsWith('/model ')) {
623
- const newModel = resolveModel(input.slice(7).trim());
624
- agentConfig.model = newModel;
625
- console.error(chalk.green(` Model → ${newModel}`));
623
+ const resolved = resolveModelStrict(input.slice(7).trim());
624
+ if (!resolved.ok) {
625
+ console.error(chalk.yellow(` ${resolved.suggestion}`));
626
+ continue;
627
+ }
628
+ agentConfig.model = resolved.id;
629
+ console.error(chalk.green(` Model → ${resolved.id}`));
630
+ if (resolved.viaShortcut) {
631
+ console.error(chalk.dim(` (alias ${input.slice(7).trim()} → ${resolved.id})`));
632
+ }
626
633
  continue;
627
634
  }
628
635
  // /retry — resend last prompt
@@ -739,9 +746,19 @@ async function handleSlashCommand(cmd, config, ui) {
739
746
  case '/model': {
740
747
  const newModel = parts[1];
741
748
  if (newModel) {
742
- config.model = resolveModel(newModel);
743
- config.baseModel = config.model;
744
- console.error(chalk.green(` Model → ${config.model}`));
749
+ const resolved = resolveModelStrict(newModel);
750
+ if (!resolved.ok) {
751
+ console.error(chalk.yellow(` ${resolved.suggestion}`));
752
+ return null;
753
+ }
754
+ config.model = resolved.id;
755
+ config.baseModel = resolved.id;
756
+ const suffix = resolved.viaShortcut
757
+ ? chalk.dim(` (alias ${newModel} → ${resolved.id})`)
758
+ : '';
759
+ console.error(chalk.green(` Model → ${resolved.id}`));
760
+ if (suffix)
761
+ console.error(suffix);
745
762
  return null;
746
763
  }
747
764
  const picked = await pickModel(config.model);
@@ -44,7 +44,7 @@ export async function telegramCommand(opts) {
44
44
  // Model: --model flag > config default > free default.
45
45
  const model = opts.model ||
46
46
  config['default-model'] ||
47
- 'nvidia/llama-4-maverick';
47
+ 'nvidia/qwen3-next-80b-a3b-instruct';
48
48
  const workingDir = process.cwd();
49
49
  const systemInstructions = assembleInstructions(workingDir, model);
50
50
  // Resume the most recent session tagged for THIS owner so a process
package/dist/config.d.ts CHANGED
@@ -5,5 +5,6 @@ export declare const BLOCKRUN_DIR: string;
5
5
  export declare const CHAIN_FILE: string;
6
6
  export declare const API_URLS: Record<Chain, string>;
7
7
  export declare const DEFAULT_PROXY_PORT = 8402;
8
+ export declare const MARKET_URL: string;
8
9
  export declare function saveChain(chain: Chain): void;
9
10
  export declare function loadChain(): Chain;
package/dist/config.js CHANGED
@@ -19,6 +19,12 @@ export const API_URLS = {
19
19
  solana: 'https://sol.blockrun.ai/api',
20
20
  };
21
21
  export const DEFAULT_PROXY_PORT = 8402;
22
+ // BlockRun agent-market (the paid skill marketplace Franklin browses with
23
+ // `/market` and hires with the agent_talent tool). It speaks standard
24
+ // single-leg `exact` x402 on Base, so Franklin pays it with the same EVM
25
+ // wallet it uses for the gateway. Overridable via env for local end-to-end
26
+ // testing against a dev server.
27
+ export const MARKET_URL = (process.env.BLOCKRUN_MARKET_URL || 'https://business.blockrun.ai').replace(/\/+$/, '');
22
28
  export function saveChain(chain) {
23
29
  fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
24
30
  fs.writeFileSync(CHAIN_FILE, chain + '\n', { mode: 0o600 });
package/dist/index.js CHANGED
@@ -28,6 +28,7 @@ import { uninitCommand } from './commands/uninit.js';
28
28
  import { proxyCommand } from './commands/proxy.js';
29
29
  import { buildTaskCommand } from './commands/task.js';
30
30
  import { buildContentCommand } from './commands/content.js';
31
+ import { predictCommand } from './commands/predict.js';
31
32
  import { VERSION as version } from './config.js';
32
33
  const program = new Command();
33
34
  program
@@ -68,6 +69,17 @@ program
68
69
  .option('--no-fallback', 'Disable automatic fallback to backup models')
69
70
  .option('--debug', 'Enable debug logging')
70
71
  .action((options) => proxyCommand({ ...options, version }));
72
+ program
73
+ .command('predict')
74
+ .description('Prediction mode — forecast one real-world event with a research-only toolset (web/markets), headless')
75
+ .requiredOption('-m, --model <model>', 'Model to use (e.g. anthropic/claude-opus-4.8, openai/gpt-5.5)')
76
+ .requiredOption('-q, --question <text>', 'The event question to forecast (include the allowed options)')
77
+ .option('--max-turns <n>', 'Max agent turns before forcing an answer', '8')
78
+ .option('--max-tool-calls <n>', 'Max tool calls before forcing an answer', '6')
79
+ .option('--max-spend <usd>', 'Hard USD cap on this prediction run')
80
+ .option('--no-json', 'Human-readable streaming instead of a JSON envelope')
81
+ .option('--debug', 'Enable debug logging')
82
+ .action((options) => predictCommand(options));
71
83
  program
72
84
  .command('init')
73
85
  .description('Configure franklin auto-start (writes ~/.claude/settings.json + installs LaunchAgent on macOS)')
@@ -9,8 +9,8 @@ import { loadLearnings, mergeLearning, saveLearnings, loadSkills, saveSkill } fr
9
9
  // Free models for learning extraction — JSON extraction is simple enough.
10
10
  // Ordered by reliability: try the best free model first, fall back to others.
11
11
  const EXTRACTION_MODELS = [
12
- 'nvidia/llama-4-maverick', // Agent-tested free model; reliable for JSON tasks
13
- 'nvidia/deepseek-v4-flash', // 1M-ctx fallback (qwen3-coder-480b EOL 2026-06-11)
12
+ 'nvidia/qwen3-next-80b-a3b-instruct', // Clean JSON output, no thinking leak (verified live)
13
+ 'nvidia/llama-4-maverick', // Diverse-family free fallback
14
14
  ];
15
15
  const VALID_CATEGORIES = new Set([
16
16
  'language', 'model_preference', 'tool_pattern', 'coding_style',
@@ -0,0 +1,69 @@
1
+ /**
2
+ * BlockRun agent-market client — the shared engine behind the `/market`
3
+ * slash command (a human browsing + hiring talent) and the agent_talent
4
+ * tool (the agent hiring talent autonomously, mid-task).
5
+ *
6
+ * The market is business.blockrun.ai: a catalog of paid AI skills, each
7
+ * runnable for ONE standard single-leg `exact` x402 USDC payment on Base.
8
+ * Discovery is a free public GET; running a skill is a paid POST that
9
+ * answers a 402 challenge with a wallet-signed payment — the same dance as
10
+ * the gateway capability in src/tools/blockrun.ts, only the payment header
11
+ * name (`x-payment`) and the base URL differ.
12
+ *
13
+ * Base-only by design: the market settles USDC on Base, so a hire always
14
+ * pays from the EVM wallet (getOrCreateWallet) regardless of the session's
15
+ * configured chain.
16
+ */
17
+ export interface MarketSkill {
18
+ slug: string;
19
+ name: string;
20
+ description: string;
21
+ price_usd: number;
22
+ backing_model: string;
23
+ run_count: number;
24
+ execution_type: 'prompt' | 'agent' | string;
25
+ /** Live-data hostnames an `agent` skill fetches at run time (empty for `prompt`). */
26
+ data_sources: string[];
27
+ sample_input?: string;
28
+ sample_output?: string;
29
+ creator: {
30
+ wallet: string;
31
+ x: string | null;
32
+ };
33
+ run_url: string;
34
+ }
35
+ /** GET the public catalog. No payment. Optional client-side keyword filter. */
36
+ export declare function fetchCatalog(opts?: {
37
+ limit?: number;
38
+ query?: string;
39
+ signal?: AbortSignal;
40
+ }): Promise<MarketSkill[]>;
41
+ /** Filter the catalog by the fields a buyer searches on (AND over terms). */
42
+ export declare function filterCatalog(skills: MarketSkill[], query: string): MarketSkill[];
43
+ export interface RunOutcome {
44
+ ok: boolean;
45
+ status: number;
46
+ result?: string;
47
+ /** USD authorized on the paid attempt (0 if unpaid / pre-payment 4xx). */
48
+ paidUsd: number;
49
+ txHash: string | null;
50
+ error?: string;
51
+ }
52
+ /**
53
+ * Hire a skill: POST the input, answer the 402 with a signed payment, retry,
54
+ * return the result. Fails closed — the marketplace settles ONLY on a
55
+ * successful run, so any non-2xx means the wallet was not charged.
56
+ */
57
+ export declare function runMarketSkill(slug: string, input: string, opts?: {
58
+ signal?: AbortSignal;
59
+ timeoutMs?: number;
60
+ runUrl?: string;
61
+ maxUsd?: number;
62
+ }): Promise<RunOutcome>;
63
+ export declare function fmtUsd(n: number): string;
64
+ /** A compact numbered list for the terminal (one row per skill). */
65
+ export declare function formatCatalogList(skills: MarketSkill[], opts?: {
66
+ heading?: string;
67
+ }): string;
68
+ /** A fuller detail card for a single skill (shown by `/market info`). */
69
+ export declare function formatSkillCard(s: MarketSkill): string;
@@ -0,0 +1,230 @@
1
+ /**
2
+ * BlockRun agent-market client — the shared engine behind the `/market`
3
+ * slash command (a human browsing + hiring talent) and the agent_talent
4
+ * tool (the agent hiring talent autonomously, mid-task).
5
+ *
6
+ * The market is business.blockrun.ai: a catalog of paid AI skills, each
7
+ * runnable for ONE standard single-leg `exact` x402 USDC payment on Base.
8
+ * Discovery is a free public GET; running a skill is a paid POST that
9
+ * answers a 402 challenge with a wallet-signed payment — the same dance as
10
+ * the gateway capability in src/tools/blockrun.ts, only the payment header
11
+ * name (`x-payment`) and the base URL differ.
12
+ *
13
+ * Base-only by design: the market settles USDC on Base, so a hire always
14
+ * pays from the EVM wallet (getOrCreateWallet) regardless of the session's
15
+ * configured chain.
16
+ */
17
+ import { getOrCreateWallet, createPaymentPayload, extractPaymentDetails, } from '@blockrun/llm';
18
+ import { MARKET_URL, USER_AGENT } from '../config.js';
19
+ const DEFAULT_TIMEOUT_MS = 45_000;
20
+ const MAX_TIMEOUT_MS = 120_000;
21
+ // Absolute backstop on a single hire. The 402 amount is only known after the
22
+ // permission gate has already been passed, so nothing downstream re-confirms
23
+ // it with the user — a compromised or misconfigured marketplace could answer a
24
+ // $0.02 listing with a $500 challenge. Cap the blast radius here; callers that
25
+ // know the catalog price pass `maxUsd` to tighten it further.
26
+ const HARD_MAX_HIRE_USD = 5;
27
+ // Small slack over the catalog price so an honest sub-cent rounding difference
28
+ // between the listing and the live 402 doesn't reject a legitimate hire.
29
+ const PRICE_TOLERANCE_USD = 0.001;
30
+ // ─── Discovery (free) ───────────────────────────────────────────────────────
31
+ /** GET the public catalog. No payment. Optional client-side keyword filter. */
32
+ export async function fetchCatalog(opts = {}) {
33
+ const limit = Math.min(Math.max(opts.limit ?? 100, 1), 200);
34
+ const url = `${MARKET_URL}/api/v1/skills?limit=${limit}`;
35
+ const ctrl = new AbortController();
36
+ const onAbort = () => ctrl.abort();
37
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
38
+ const timer = setTimeout(() => ctrl.abort(), DEFAULT_TIMEOUT_MS);
39
+ try {
40
+ const res = await fetch(url, {
41
+ method: 'GET',
42
+ headers: { Accept: 'application/json', 'User-Agent': USER_AGENT },
43
+ signal: ctrl.signal,
44
+ });
45
+ if (!res.ok)
46
+ throw new Error(`marketplace returned HTTP ${res.status}`);
47
+ const body = (await res.json());
48
+ const skills = Array.isArray(body.skills) ? body.skills : [];
49
+ // Rank by call volume, highest first — the catalog's ordering contract for
50
+ // every surface (the /market list, the agent_talent tool, the web panel).
51
+ // The discovery API already sorts this way; enforce it here too so the
52
+ // top-N slice is correct regardless. Stable sort keeps the API's recency
53
+ // tiebreak within an equal call count.
54
+ skills.sort((a, b) => (b.run_count ?? 0) - (a.run_count ?? 0));
55
+ return opts.query ? filterCatalog(skills, opts.query) : skills;
56
+ }
57
+ finally {
58
+ clearTimeout(timer);
59
+ opts.signal?.removeEventListener('abort', onAbort);
60
+ }
61
+ }
62
+ /** Filter the catalog by the fields a buyer searches on (AND over terms). */
63
+ export function filterCatalog(skills, query) {
64
+ const q = query.trim().toLowerCase();
65
+ if (!q)
66
+ return skills;
67
+ const terms = q.split(/\s+/);
68
+ return skills.filter((s) => {
69
+ const hay = [s.slug, s.name, s.description, s.backing_model, ...(s.data_sources || [])]
70
+ .join(' ')
71
+ .toLowerCase();
72
+ return terms.every((t) => hay.includes(t));
73
+ });
74
+ }
75
+ async function signMarketPayment(challenge, runUrl, skillName) {
76
+ // `challenge` is the marketplace's 402 body, already parsed:
77
+ // { x402Version, accepts:[{ scheme, network, amount, asset, payTo, ... }], resource }.
78
+ // extractPaymentDetails reads accepts[0] directly (amount + payTo) — no need
79
+ // to round-trip through base64, which would choke on a non-Latin1 skill name
80
+ // in the resource description.
81
+ const details = extractPaymentDetails(challenge);
82
+ const wallet = getOrCreateWallet();
83
+ const header = await createPaymentPayload(wallet.privateKey, wallet.address, details.recipient, details.amount, details.network || 'eip155:8453', {
84
+ resourceUrl: details.resource?.url || runUrl,
85
+ // createPaymentPayload base64s the payload with btoa (Latin1-only), so the
86
+ // description must stay ASCII — strip anything else out of the skill name.
87
+ resourceDescription: `Run ${skillName}`.replace(/[^\x20-\x7E]/g, ''),
88
+ maxTimeoutSeconds: details.maxTimeoutSeconds || 300,
89
+ extra: details.extra,
90
+ });
91
+ const amountUsd = Number(details.amount) / 1_000_000;
92
+ return { header, amountUsd: Number.isFinite(amountUsd) ? amountUsd : 0 };
93
+ }
94
+ /** Read the demanded USD amount from a 402 challenge without signing it. */
95
+ function challengeAmountUsd(challenge) {
96
+ try {
97
+ return Number(extractPaymentDetails(challenge).amount) / 1_000_000;
98
+ }
99
+ catch {
100
+ return NaN;
101
+ }
102
+ }
103
+ /**
104
+ * Hire a skill: POST the input, answer the 402 with a signed payment, retry,
105
+ * return the result. Fails closed — the marketplace settles ONLY on a
106
+ * successful run, so any non-2xx means the wallet was not charged.
107
+ */
108
+ export async function runMarketSkill(slug, input, opts = {}) {
109
+ const runUrl = opts.runUrl || `${MARKET_URL}/api/v1/skills/${encodeURIComponent(slug)}/run`;
110
+ const timeoutMs = Math.min(Math.max(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, 1_000), MAX_TIMEOUT_MS);
111
+ const ctrl = new AbortController();
112
+ const onAbort = () => ctrl.abort();
113
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
114
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
115
+ const headers = {
116
+ Accept: 'application/json',
117
+ 'Content-Type': 'application/json',
118
+ 'User-Agent': USER_AGENT,
119
+ };
120
+ const payload = JSON.stringify({ input });
121
+ try {
122
+ let res = await fetch(runUrl, { method: 'POST', headers, body: payload, signal: ctrl.signal });
123
+ let paidUsd = 0;
124
+ if (res.status === 402) {
125
+ const challenge = (await res.json().catch(() => null));
126
+ if (!challenge?.accepts?.length) {
127
+ return { ok: false, status: 402, paidUsd: 0, txHash: null, error: 'could not read payment requirements from the marketplace' };
128
+ }
129
+ // Bound the amount BEFORE signing. The user already cleared the permission
130
+ // gate blind to the price (it isn't known until this 402), so this is the
131
+ // only place that can stop a runaway charge.
132
+ const demandedUsd = challengeAmountUsd(challenge);
133
+ const ceilingUsd = Math.min(HARD_MAX_HIRE_USD, opts.maxUsd != null ? opts.maxUsd + PRICE_TOLERANCE_USD : Infinity);
134
+ if (!Number.isFinite(demandedUsd) || demandedUsd < 0) {
135
+ return { ok: false, status: 402, paidUsd: 0, txHash: null, error: 'marketplace sent an unreadable payment amount' };
136
+ }
137
+ if (demandedUsd > ceilingUsd) {
138
+ return {
139
+ ok: false,
140
+ status: 402,
141
+ paidUsd: 0,
142
+ txHash: null,
143
+ error: `marketplace demanded ${fmtUsd(demandedUsd)}, over the ${fmtUsd(ceilingUsd)} ceiling — refusing to pay`,
144
+ };
145
+ }
146
+ let signed;
147
+ try {
148
+ signed = await signMarketPayment(challenge, runUrl, slug);
149
+ }
150
+ catch (err) {
151
+ return { ok: false, status: 402, paidUsd: 0, txHash: null, error: `payment signing failed: ${err.message}` };
152
+ }
153
+ paidUsd = signed.amountUsd;
154
+ res = await fetch(runUrl, {
155
+ method: 'POST',
156
+ headers: { ...headers, 'x-payment': signed.header },
157
+ body: payload,
158
+ signal: ctrl.signal,
159
+ });
160
+ }
161
+ const txHash = res.headers.get('x-payment-receipt');
162
+ const body = (await res.json().catch(() => ({})));
163
+ if (!res.ok) {
164
+ const detail = typeof body.error === 'string' ? body.error : `HTTP ${res.status}`;
165
+ // No charge on a non-2xx: the route fails closed before settle.
166
+ return { ok: false, status: res.status, paidUsd: 0, txHash, error: detail };
167
+ }
168
+ const result = typeof body.result === 'string' ? body.result : '';
169
+ return { ok: true, status: res.status, result, paidUsd, txHash };
170
+ }
171
+ catch (err) {
172
+ return { ok: false, status: 0, paidUsd: 0, txHash: null, error: err.message || 'request failed' };
173
+ }
174
+ finally {
175
+ clearTimeout(timer);
176
+ opts.signal?.removeEventListener('abort', onAbort);
177
+ }
178
+ }
179
+ // ─── Formatting (shared by the /market command + agent_talent tool) ─────────
180
+ export function fmtUsd(n) {
181
+ if (!Number.isFinite(n) || n <= 0)
182
+ return '$0.00';
183
+ return n < 0.01 ? `$${n.toFixed(4)}` : `$${n.toFixed(2)}`;
184
+ }
185
+ function typeBadge(s) {
186
+ if (s.execution_type === 'agent' && s.data_sources?.length)
187
+ return `live:${s.data_sources.join(',')}`;
188
+ return s.execution_type === 'agent' ? 'live' : 'prompt';
189
+ }
190
+ // Truncate to a column width at a word boundary, with an ellipsis when cut —
191
+ // so a row never shows a half-word like "across cha".
192
+ function truncate(text, max) {
193
+ const t = (text || '').replace(/\s+/g, ' ').trim();
194
+ if (t.length <= max)
195
+ return t;
196
+ const cut = t.slice(0, max - 1).replace(/\s+$/, '');
197
+ const sp = cut.lastIndexOf(' ');
198
+ const base = sp >= Math.floor(max * 0.6) ? cut.slice(0, sp) : cut; // word boundary, unless that loses too much
199
+ return `${base}…`;
200
+ }
201
+ /** A compact numbered list for the terminal (one row per skill). */
202
+ export function formatCatalogList(skills, opts = {}) {
203
+ if (skills.length === 0)
204
+ return 'No matching skills in the marketplace.\n';
205
+ const lines = skills.map((s, i) => {
206
+ const n = String(i + 1).padStart(2, ' ');
207
+ // Never truncate the slug — it's the identifier the user types into
208
+ // `/market run <slug>`; pad short ones, let a rare long one overflow.
209
+ const slug = s.slug.padEnd(18);
210
+ const price = fmtUsd(s.price_usd).padStart(7);
211
+ const desc = truncate(s.description || '', 40).padEnd(40);
212
+ const by = s.creator?.x ? ` @${s.creator.x}` : '';
213
+ return ` ${n}. ${slug} ${price} ${desc}${by}`.replace(/\s+$/, '');
214
+ });
215
+ const head = opts.heading ? `${opts.heading}\n` : '';
216
+ const foot = '\n > /market <keyword> to search . /market info <slug> . /market run <slug> <input>\n';
217
+ return `${head}${lines.join('\n')}\n${foot}`;
218
+ }
219
+ /** A fuller detail card for a single skill (shown by `/market info`). */
220
+ export function formatSkillCard(s) {
221
+ const by = s.creator?.x ? ` . by @${s.creator.x}` : '';
222
+ const sample = s.sample_input
223
+ ? ` e.g. ${JSON.stringify(s.sample_input)}${s.sample_output ? ` -> ${JSON.stringify(s.sample_output)}` : ''}\n`
224
+ : '';
225
+ return (` ${s.name} . ${fmtUsd(s.price_usd)}/run . ${s.backing_model}\n` +
226
+ ` ${s.description}\n` +
227
+ ` [${typeBadge(s)}]${by}\n` +
228
+ sample +
229
+ ` > /market run ${s.slug} <your input>\n`);
230
+ }
@@ -5,7 +5,7 @@
5
5
  * Plugins implement Workflow; core orchestrates execution and provides infrastructure.
6
6
  */
7
7
  export const DEFAULT_MODEL_TIERS = {
8
- free: 'nvidia/llama-4-maverick',
9
- cheap: 'nvidia/llama-4-maverick', // Free by default; opt-in to paid flat-rate via 'zai/glm-5.1'.
10
- premium: 'anthropic/claude-sonnet-4.6',
8
+ free: 'nvidia/qwen3-next-80b-a3b-instruct',
9
+ cheap: 'nvidia/qwen3-next-80b-a3b-instruct', // Free by default; opt-in to paid flat-rate via 'zai/glm-5.1'.
10
+ premium: 'anthropic/claude-sonnet-5',
11
11
  };