@blockrun/franklin 3.31.0 → 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.
@@ -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
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * agent_talent — hire paid AI skills from the BlockRun agent marketplace.
3
+ *
4
+ * The autonomous counterpart to the `/market` slash command: where `/market`
5
+ * lets a human browse and hire, this capability lets the agent discover and
6
+ * hire talent mid-task. `action: "list"` returns the catalog (free GET);
7
+ * `action: "run"` hires a skill by slug, signing ONE standard `exact` x402
8
+ * USDC payment from the user wallet on Base (only on a successful run), and
9
+ * returns the skill's output plus the USD paid.
10
+ *
11
+ * Both actions delegate to src/market/client.ts, the single payment path
12
+ * shared with the command — see that file for the x402 details.
13
+ */
14
+ import type { CapabilityHandler } from '../agent/types.js';
15
+ export declare const agentTalentCapability: CapabilityHandler;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * agent_talent — hire paid AI skills from the BlockRun agent marketplace.
3
+ *
4
+ * The autonomous counterpart to the `/market` slash command: where `/market`
5
+ * lets a human browse and hire, this capability lets the agent discover and
6
+ * hire talent mid-task. `action: "list"` returns the catalog (free GET);
7
+ * `action: "run"` hires a skill by slug, signing ONE standard `exact` x402
8
+ * USDC payment from the user wallet on Base (only on a successful run), and
9
+ * returns the skill's output plus the USD paid.
10
+ *
11
+ * Both actions delegate to src/market/client.ts, the single payment path
12
+ * shared with the command — see that file for the x402 details.
13
+ */
14
+ import { fetchCatalog, runMarketSkill, fmtUsd } from '../market/client.js';
15
+ import { recordUsage } from '../stats/tracker.js';
16
+ import { frameUntrusted } from './untrusted.js';
17
+ import { logger } from '../logger.js';
18
+ // A model-facing line per skill: enough to choose, not a wall of text.
19
+ function listLine(s) {
20
+ const type = s.execution_type === 'agent' && s.data_sources?.length
21
+ ? `live-data(${s.data_sources.join(',')})`
22
+ : s.execution_type;
23
+ const sample = s.sample_input ? ` | e.g. ${JSON.stringify(s.sample_input)}` : '';
24
+ const by = s.creator?.x ? ` | by @${s.creator.x}` : '';
25
+ return `- ${s.slug} — ${s.name} [${type}] ${fmtUsd(s.price_usd)}/run${by}\n ${s.description}${sample}`;
26
+ }
27
+ export const agentTalentCapability = {
28
+ spec: {
29
+ name: 'agent_talent',
30
+ description: 'Browse and hire paid AI skills ("talents") from the BlockRun agent marketplace — specialized agents other creators published. ' +
31
+ 'action="list" returns the catalog for free. Use it whenever the user asks you to find, search, browse, or recommend an agent / skill / talent for some domain or task (pass their topic as `query`), OR when you yourself need talent for a sub-task you cannot do well (live market/on-chain data, a domain-specific analysis, a niche transform). ' +
32
+ '`query` filters by name, description, and data source; the match is semantic on your part — map the user\'s intent (e.g. "track gas prices" -> "gas", a request in any language) to a sensible keyword. Omit `query` to list the most popular. ' +
33
+ 'action="run" hires one skill by `slug` with your `input`: it signs ONE standard USDC x402 payment from the user wallet on Base and returns the skill\'s output. ' +
34
+ 'The wallet is charged automatically and ONLY on a successful run (the response reports the USD paid); a failed run is free. ' +
35
+ 'Prefer listing first to get the exact slug and price before running.',
36
+ input_schema: {
37
+ type: 'object',
38
+ properties: {
39
+ action: {
40
+ type: 'string',
41
+ enum: ['list', 'run'],
42
+ description: '"list" to browse/search the catalog (free); "run" to hire a skill (paid).',
43
+ },
44
+ query: {
45
+ type: 'string',
46
+ description: 'For list: optional keyword filter over name, description, and data sources.',
47
+ },
48
+ slug: {
49
+ type: 'string',
50
+ description: 'For run: the skill slug to hire (get it from list).',
51
+ },
52
+ input: {
53
+ type: 'string',
54
+ description: 'For run: the input text to send the skill.',
55
+ },
56
+ limit: {
57
+ type: 'number',
58
+ description: 'For list: max skills to return (default 20, max 200).',
59
+ },
60
+ },
61
+ required: ['action'],
62
+ },
63
+ },
64
+ // list is a free read; run signs a payment. Only the read is parallel-safe.
65
+ isConcurrentSafe: (input) => input.action === 'list',
66
+ async execute(input, ctx) {
67
+ const raw = input;
68
+ const action = typeof raw.action === 'string' ? raw.action.toLowerCase() : '';
69
+ if (action === 'list') {
70
+ try {
71
+ const limit = Math.min(Math.max(typeof raw.limit === 'number' ? raw.limit : 20, 1), 200);
72
+ const skills = await fetchCatalog({
73
+ limit,
74
+ query: typeof raw.query === 'string' ? raw.query : undefined,
75
+ signal: ctx.abortSignal,
76
+ });
77
+ if (skills.length === 0) {
78
+ return { output: raw.query ? `No marketplace skills match "${raw.query}".` : 'The marketplace has no runnable skills right now.' };
79
+ }
80
+ const head = raw.query
81
+ ? `BlockRun agent talents — ${skills.length} skill(s) matching "${raw.query}":`
82
+ : `BlockRun agent talents — ${skills.length} skill(s):`;
83
+ const body = frameUntrusted('BlockRun marketplace catalog (untrusted, creator-authored)', skills.map(listLine).join('\n'));
84
+ const out = `${head}\n${body}\n\nTo hire one: agent_talent { action: "run", slug: "<slug>", input: "<input>" }.`;
85
+ return { output: out, fullOutput: out };
86
+ }
87
+ catch (err) {
88
+ return { output: `Could not reach the marketplace: ${err.message}`, isError: true };
89
+ }
90
+ }
91
+ if (action === 'run') {
92
+ const slug = typeof raw.slug === 'string' ? raw.slug.trim() : '';
93
+ const userInput = typeof raw.input === 'string' ? raw.input : '';
94
+ if (!slug)
95
+ return { output: 'Error: `slug` is required for action="run" (list first to find it).', isError: true };
96
+ if (!userInput.trim())
97
+ return { output: 'Error: `input` is required for action="run".', isError: true };
98
+ const outcome = await runMarketSkill(slug, userInput, { signal: ctx.abortSignal });
99
+ try {
100
+ recordUsage(`agent_talent:${slug}`, 0, 0, outcome.paidUsd, 0);
101
+ }
102
+ catch { /* best-effort telemetry */ }
103
+ if (!outcome.ok) {
104
+ logger.warn(`[franklin] agent_talent run ${slug} failed (${outcome.status}): ${outcome.error}`);
105
+ return {
106
+ output: `Hiring "${slug}" failed: ${outcome.error ?? `HTTP ${outcome.status}`}. No charge (the marketplace settles only on success).`,
107
+ isError: true,
108
+ };
109
+ }
110
+ const receipt = `Hired ${slug} — paid ${fmtUsd(outcome.paidUsd)}${outcome.txHash ? ` (tx ${outcome.txHash.slice(0, 10)}…)` : ''}`;
111
+ const out = `${receipt}\n\n${frameUntrusted('BlockRun marketplace skill output (untrusted, third-party)', outcome.result ?? '')}`;
112
+ return { output: out, fullOutput: out };
113
+ }
114
+ return { output: `Error: unknown action "${raw.action}". Use "list" or "run".`, isError: true };
115
+ },
116
+ };
@@ -19,6 +19,7 @@ import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, creat
19
19
  import { loadChain, API_URLS, VERSION } from '../config.js';
20
20
  import { logger } from '../logger.js';
21
21
  import { recordUsage } from '../stats/tracker.js';
22
+ import { frameUntrusted } from './untrusted.js';
22
23
  const TIMEOUT_MS = 30_000;
23
24
  // ─── Shared GET-with-x402 flow ────────────────────────────────────────────
24
25
  async function getWithPayment(path, ctx) {
@@ -187,7 +188,7 @@ export const defiLlamaProtocolsCapability = {
187
188
  const change = p.change_1d != null ? ` · 24h ${formatPct(p.change_1d)}` : '';
188
189
  lines.push(`${i + 1}. **${p.name}** (${p.slug}) — ${formatUsd(Number(p.tvl))}${cat}${change}\n chains: ${chains}${more}`);
189
190
  });
190
- return { output: lines.join('\n') };
191
+ return { output: frameUntrusted('DefiLlama data (untrusted)', lines.join('\n')) };
191
192
  }
192
193
  catch (err) {
193
194
  return { output: `Error: ${err.message}`, isError: true };
@@ -248,7 +249,7 @@ export const defiLlamaProtocolCapability = {
248
249
  lines.push(`Audits: ${p.audits}`);
249
250
  if (p.description)
250
251
  lines.push('', p.description);
251
- return { output: lines.join('\n') };
252
+ return { output: frameUntrusted('DefiLlama data (untrusted)', lines.join('\n')) };
252
253
  }
253
254
  catch (err) {
254
255
  return { output: `Error: ${err.message}`, isError: true };
@@ -280,7 +281,7 @@ export const defiLlamaChainsCapability = {
280
281
  const sym = c.tokenSymbol ? ` (${c.tokenSymbol})` : '';
281
282
  lines.push(`${i + 1}. **${c.name}**${sym} — ${formatUsd(Number(c.tvl))}`);
282
283
  });
283
- return { output: lines.join('\n') };
284
+ return { output: frameUntrusted('DefiLlama data (untrusted)', lines.join('\n')) };
284
285
  }
285
286
  catch (err) {
286
287
  return { output: `Error: ${err.message}`, isError: true };
@@ -354,7 +355,7 @@ export const defiLlamaYieldsCapability = {
354
355
  const il = p.ilRisk ? ` · IL: ${p.ilRisk}` : '';
355
356
  lines.push(`${i + 1}. **${p.project}** / ${p.chain} / ${p.symbol} — ${(p.apy ?? 0).toFixed(2)}% APY${breakdown}\n TVL: ${formatUsd(p.tvlUsd)}${il} · pool: ${p.pool}`);
356
357
  });
357
- return { output: lines.join('\n') };
358
+ return { output: frameUntrusted('DefiLlama data (untrusted)', lines.join('\n')) };
358
359
  }
359
360
  catch (err) {
360
361
  return { output: `Error: ${err.message}`, isError: true };
@@ -409,7 +410,7 @@ export const defiLlamaPriceCapability = {
409
410
  const ts = entry.timestamp ? ` · ${new Date(entry.timestamp * 1000).toISOString().slice(0, 19)}Z` : '';
410
411
  lines.push(`- **${id}**${sym}: $${entry.price.toFixed(entry.price < 0.01 ? 8 : 4)}${conf}${ts}`);
411
412
  }
412
- return { output: lines.join('\n') };
413
+ return { output: frameUntrusted('DefiLlama data (untrusted)', lines.join('\n')) };
413
414
  }
414
415
  catch (err) {
415
416
  return { output: `Error: ${err.message}`, isError: true };
@@ -21,4 +21,19 @@ export declare function resetToolSessionState(): void;
21
21
  /** All capabilities available to the Franklin agent (excluding sub-agent, which needs config). */
22
22
  export declare const allCapabilities: CapabilityHandler[];
23
23
  export { readCapability, writeCapability, editCapability, bashCapability, globCapability, grepCapability, webFetchCapability, webSearchCapability, taskCapability, detachCapability, };
24
+ /**
25
+ * "Franklin prediction mode" toolset.
26
+ *
27
+ * A deliberately tight, research-only capability set for forecasting a single
28
+ * real-world event the way a careful bettor would: gather current facts, read
29
+ * sources, check live prediction-market odds and a little market data — then
30
+ * decide. Everything else (filesystem, shell, media generation, swaps/trade
31
+ * execution, phone/voice, GPU sandbox, posting) is intentionally excluded:
32
+ * a forecaster looks things up, it does not act on the world or spend beyond
33
+ * the cheap read calls these tools make.
34
+ *
35
+ * Used by the `franklin predict` command and reusable by any headless caller
36
+ * (e.g. franklin.bet) that wants a grounded prediction.
37
+ */
38
+ export declare const predictionCapabilities: CapabilityHandler[];
24
39
  export { createSubAgentCapability } from './subagent.js';
@@ -35,6 +35,7 @@ import { predictionMarketCapability } from './prediction.js';
35
35
  import { polymarketBetCapability } from './polymarket-bet.js';
36
36
  import { modalCapabilities } from './modal.js';
37
37
  import { blockrunCapability } from './blockrun.js';
38
+ import { agentTalentCapability } from './agent-talent.js';
38
39
  import { surfCapabilities } from './surf.js';
39
40
  import { realFaceCapability } from './realface.js';
40
41
  import { listPhoneNumbersCapability, buyPhoneNumberCapability, renewPhoneNumberCapability, releasePhoneNumberCapability, phoneLookupCapability, phoneFraudCheckCapability, } from './phone.js';
@@ -173,6 +174,7 @@ export const allCapabilities = [
173
174
  predictionMarketCapability, // Polymarket / Kalshi / matching / smart money via Predexon (read-only research)
174
175
  polymarketBetCapability, // PolymarketBet — real-money betting execution: setup/fund/buy/sell/redeem/withdraw (CLOB V2)
175
176
  blockrunCapability, // Generic x402-paid gateway primitive — future partners + long-tail Surf paths
177
+ agentTalentCapability, // Hire paid skills from the BlockRun agent marketplace (business.blockrun.ai)
176
178
  ...surfCapabilities, // SurfMarket / SurfChain / SurfSocial — endpoint-enum function tools (no path guessing, auto x402)
177
179
  // Phone & Voice — typed surface so the agent pattern-matches on the user
178
180
  // intent ("buy a number", "make a call") without needing to consult the
@@ -194,4 +196,30 @@ export const allCapabilities = [
194
196
  ...modalCapabilities, // ModalCreate, ModalExec, ModalStatus, ModalTerminate
195
197
  ];
196
198
  export { readCapability, writeCapability, editCapability, bashCapability, globCapability, grepCapability, webFetchCapability, webSearchCapability, taskCapability, detachCapability, };
199
+ /**
200
+ * "Franklin prediction mode" toolset.
201
+ *
202
+ * A deliberately tight, research-only capability set for forecasting a single
203
+ * real-world event the way a careful bettor would: gather current facts, read
204
+ * sources, check live prediction-market odds and a little market data — then
205
+ * decide. Everything else (filesystem, shell, media generation, swaps/trade
206
+ * execution, phone/voice, GPU sandbox, posting) is intentionally excluded:
207
+ * a forecaster looks things up, it does not act on the world or spend beyond
208
+ * the cheap read calls these tools make.
209
+ *
210
+ * Used by the `franklin predict` command and reusable by any headless caller
211
+ * (e.g. franklin.bet) that wants a grounded prediction.
212
+ */
213
+ export const predictionCapabilities = [
214
+ webSearchCapability, // web_search — current news & facts
215
+ webFetchCapability, // webfetch — read a specific source URL
216
+ exaSearchCapability, // exa search — higher-quality web research
217
+ exaAnswerCapability, // exa answer — direct sourced answers
218
+ exaReadUrlsCapability, // exa read — pull full text of found URLs
219
+ searchXCapability, // search X — live sentiment / breaking signal
220
+ predictionMarketCapability, // search_prediction_markets — live implied odds
221
+ tradingSignalCapability, // market signal/indicators (for market-type events)
222
+ tradingMarketCapability, // market snapshot data
223
+ defiLlamaPriceCapability, // token price lookup (crypto-type events)
224
+ ];
197
225
  export { createSubAgentCapability } from './subagent.js';
@@ -37,6 +37,7 @@ import { loadChain, API_URLS, VERSION } from '../config.js';
37
37
  import { logger } from '../logger.js';
38
38
  import { recordFetch } from '../trading/providers/telemetry.js';
39
39
  import { recordUsage } from '../stats/tracker.js';
40
+ import { frameUntrusted } from './untrusted.js';
40
41
  const TIMEOUT_MS = 30_000;
41
42
  const DEFAULT_LIMIT = 20;
42
43
  const MAX_LIMIT = 50;
@@ -395,7 +396,7 @@ async function execute(input, ctx) {
395
396
  });
396
397
  }
397
398
  lines.push(`_$0.005 paid via x402._`);
398
- return { output: lines.join('\n') };
399
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
399
400
  }
400
401
  case 'leaderboard': {
401
402
  // Global top-wallet ranking. Cheap ($0.001) — the right answer to
@@ -443,7 +444,7 @@ async function execute(input, ctx) {
443
444
  lines.push(`${i + 1}. \`${w}\`${handle}` + (parts.length > 0 ? ` — ${parts.join(' · ')}` : ''));
444
445
  });
445
446
  lines.push('', `_$0.001 paid via x402._`);
446
- return { output: lines.join('\n') };
447
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
447
448
  }
448
449
  case 'walletProfile': {
449
450
  if (!wallets || !wallets.trim()) {
@@ -558,7 +559,7 @@ async function execute(input, ctx) {
558
559
  lines.push(` ${recent.join(' · ')}`);
559
560
  });
560
561
  lines.push('', `_$0.005 paid via x402._`);
561
- return { output: lines.join('\n') };
562
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
562
563
  }
563
564
  case 'walletPnl': {
564
565
  // Single-wallet P&L summary + time series.
@@ -634,7 +635,7 @@ async function execute(input, ctx) {
634
635
  }
635
636
  }
636
637
  lines.push('', `_$0.005 paid via x402._`);
637
- return { output: lines.join('\n') };
638
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
638
639
  }
639
640
  case 'walletPositions': {
640
641
  // Single-wallet positions (open + historical).
@@ -700,7 +701,7 @@ async function execute(input, ctx) {
700
701
  lines.push(`${i + 1}. **${title}** — ${parts.join(' · ')}`);
701
702
  });
702
703
  lines.push('', `_$0.005 paid via x402._`);
703
- return { output: lines.join('\n') };
704
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
704
705
  }
705
706
  case 'smartActivity': {
706
707
  // "Discover markets where high-performing wallets are active right now."
@@ -741,7 +742,7 @@ async function execute(input, ctx) {
741
742
  lines.push(`${i + 1}. **${title}**${cidTag}` + (stats.length > 0 ? `\n ${stats.join(' · ')}` : ''));
742
743
  });
743
744
  lines.push('', `_$0.005 paid via x402._`);
744
- return { output: lines.join('\n') };
745
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
745
746
  }
746
747
  case 'smartMoney': {
747
748
  if (!conditionId) {
@@ -796,7 +797,7 @@ async function execute(input, ctx) {
796
797
  lines.push(`**Smart performance:** ${perf.join(' · ')}`);
797
798
  }
798
799
  lines.push('', `_$0.005 paid via x402._`);
799
- return { output: lines.join('\n') };
800
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
800
801
  }
801
802
  case 'searchPolymarket': {
802
803
  const raw = await getWithPayment('/v1/pm/polymarket/markets', {
@@ -843,7 +844,7 @@ async function execute(input, ctx) {
843
844
  (end ? ` · ends ${String(end).slice(0, 10)}` : ''));
844
845
  });
845
846
  lines.push('', `_$0.001 paid via x402._`);
846
- return { output: lines.join('\n') };
847
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
847
848
  }
848
849
  case 'searchKalshi': {
849
850
  const raw = await getWithPayment('/v1/pm/kalshi/markets', {
@@ -879,7 +880,7 @@ async function execute(input, ctx) {
879
880
  (m.close_time ? ` · closes ${String(m.close_time).slice(0, 10)}` : ''));
880
881
  });
881
882
  lines.push('', `_$0.001 paid via x402._`);
882
- return { output: lines.join('\n') };
883
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
883
884
  }
884
885
  case 'crossPlatform': {
885
886
  const raw = await getWithPayment('/v1/pm/matching-markets/pairs', {
@@ -917,7 +918,7 @@ async function execute(input, ctx) {
917
918
  }
918
919
  });
919
920
  lines.push('', `_$0.005 paid via x402._`);
920
- return { output: lines.join('\n') };
921
+ return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
921
922
  }
922
923
  default:
923
924
  return {