@blockrun/franklin 3.45.0 → 3.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -11
- package/dist/agent/context.js +58 -10
- package/dist/agent/llm.js +14 -6
- package/dist/agent/loop.js +34 -6
- package/dist/agent/optimize.d.ts +1 -1
- package/dist/agent/optimize.js +17 -7
- package/dist/agent/secret-redact.d.ts +26 -0
- package/dist/agent/secret-redact.js +48 -0
- package/dist/agent/streaming-executor.js +15 -0
- package/dist/commands/doctor.js +18 -0
- package/dist/commands/usage.d.ts +14 -0
- package/dist/commands/usage.js +86 -0
- package/dist/commands/wallet-adopt.d.ts +12 -0
- package/dist/commands/wallet-adopt.js +49 -0
- package/dist/index.js +16 -0
- package/dist/payments/account.d.ts +17 -0
- package/dist/payments/account.js +105 -0
- package/dist/payments/auth-mode.d.ts +5 -19
- package/dist/payments/auth-mode.js +15 -17
- package/dist/payments/billing-copy.d.ts +37 -0
- package/dist/payments/billing-copy.js +57 -0
- package/dist/payments/post-with-payment.js +8 -15
- package/dist/payments/price-catalog.d.ts +9 -0
- package/dist/payments/price-catalog.js +13 -0
- package/dist/payments/usage.d.ts +106 -0
- package/dist/payments/usage.js +168 -0
- package/dist/stats/tracker.d.ts +9 -1
- package/dist/stats/tracker.js +6 -1
- package/dist/tools/bash.js +17 -7
- package/dist/tools/blockrun.js +1 -1
- package/dist/tools/defillama.js +2 -2
- package/dist/tools/imagegen.js +5 -4
- package/dist/tools/modal.js +12 -6
- package/dist/tools/musicgen.js +4 -3
- package/dist/tools/phone.js +16 -15
- package/dist/tools/prediction.js +12 -11
- package/dist/tools/realface.js +2 -2
- package/dist/tools/rpc.js +2 -2
- package/dist/tools/sensitive-paths.d.ts +1 -1
- package/dist/tools/sensitive-paths.js +13 -4
- package/dist/tools/surf.js +2 -2
- package/dist/tools/videogen.js +6 -5
- package/dist/tools/voice.d.ts +1 -1
- package/dist/tools/voice.js +5 -4
- package/dist/wallet/reservation.d.ts +24 -0
- package/dist/wallet/reservation.js +50 -4
- package/dist/wallet/solana-migration.d.ts +48 -0
- package/dist/wallet/solana-migration.js +81 -0
- package/package.json +2 -2
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `franklin usage` — what the account actually charged, joined to what
|
|
3
|
+
* Franklin recorded.
|
|
4
|
+
*
|
|
5
|
+
* `franklin stats` reports Franklin's own tally, which in key mode is built
|
|
6
|
+
* from catalog prices because the account gateway settles without returning a
|
|
7
|
+
* charge. This command reports the gateway's ledger, which is authoritative,
|
|
8
|
+
* and lines the two up per request rather than comparing totals — a total that
|
|
9
|
+
* matches can still be two errors cancelling out.
|
|
10
|
+
*/
|
|
11
|
+
import chalk from 'chalk';
|
|
12
|
+
import { isKeyMode } from '../payments/auth-mode.js';
|
|
13
|
+
import { fetchUsage, reconcile } from '../payments/usage.js';
|
|
14
|
+
import { loadStats } from '../stats/tracker.js';
|
|
15
|
+
import { DASHBOARD_URL } from '../config.js';
|
|
16
|
+
function usd(n) {
|
|
17
|
+
return `$${n.toFixed(n < 0.01 && n > 0 ? 4 : 2)}`;
|
|
18
|
+
}
|
|
19
|
+
export async function usageCommand(opts = {}) {
|
|
20
|
+
if (!isKeyMode()) {
|
|
21
|
+
console.log('Account usage is a key-mode ledger. This session pays from a wallet —');
|
|
22
|
+
console.log('its settled amounts are already exact, and `franklin stats` reports them.');
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const days = Math.max(1, Math.min(Number(opts.days) || 30, 365));
|
|
26
|
+
const from = new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10);
|
|
27
|
+
const ledger = await fetchUsage({ from });
|
|
28
|
+
if (!ledger) {
|
|
29
|
+
console.log(chalk.yellow('Could not read the account ledger.'));
|
|
30
|
+
console.log(`Check your key, or view it at ${DASHBOARD_URL}/dashboard.`);
|
|
31
|
+
process.exitCode = 1;
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const local = loadStats().history.map((h) => ({ requestId: h.requestId, costUsd: h.costUsd }));
|
|
35
|
+
const r = reconcile(ledger, local);
|
|
36
|
+
if (opts.json) {
|
|
37
|
+
console.log(JSON.stringify(r, null, 2));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const t = r.totals;
|
|
41
|
+
console.log(chalk.bold(`\nAccount ledger — last ${days} day(s)\n`));
|
|
42
|
+
console.log(` Charged: ${chalk.green(usd(t.pricedUsd))} across ${t.pricedCount} request(s) ${chalk.dim('(BlockRun, authoritative)')}`);
|
|
43
|
+
if (t.pendingCount > 0) {
|
|
44
|
+
// Not settled zeros — these can still be priced.
|
|
45
|
+
console.log(` Pending: ${chalk.yellow(String(t.pendingCount))} request(s) with no charge yet ${chalk.dim('— not free, not final')}`);
|
|
46
|
+
}
|
|
47
|
+
if (t.freeCount > 0)
|
|
48
|
+
console.log(` Free: ${t.freeCount} request(s) ${chalk.dim('(explicitly not charged)')}`);
|
|
49
|
+
console.log(chalk.dim(` Mix: ${t.chatCount} chat, ${t.serviceCount} service`));
|
|
50
|
+
if (r.unavailableDays.length > 0) {
|
|
51
|
+
// A hidden gap makes two correct ledgers look like they disagree.
|
|
52
|
+
console.log(chalk.yellow(`\n ${r.unavailableDays.length} day(s) could not be listed: ${r.unavailableDays.join(', ')}`));
|
|
53
|
+
console.log(chalk.dim(' Totals above exclude them — this is a short read, not a quiet period.'));
|
|
54
|
+
}
|
|
55
|
+
console.log(chalk.bold('\nAgainst Franklin\'s own journal\n'));
|
|
56
|
+
if (r.matched.length === 0 && r.missingLocally.length === 0) {
|
|
57
|
+
console.log(chalk.dim(' No ledger row could be joined yet. Request ids are recorded from now on,'));
|
|
58
|
+
console.log(chalk.dim(' so calls made before this version have nothing to match against.'));
|
|
59
|
+
}
|
|
60
|
+
const off = r.matched
|
|
61
|
+
.filter((m) => Math.abs(m.deltaUsd) > 0.000_05)
|
|
62
|
+
.sort((a, b) => Math.abs(b.deltaUsd) - Math.abs(a.deltaUsd));
|
|
63
|
+
if (r.matched.length > 0) {
|
|
64
|
+
console.log(` Joined: ${r.matched.length} request(s); ${off.length} where Franklin's estimate differs`);
|
|
65
|
+
}
|
|
66
|
+
for (const m of off.slice(0, 10)) {
|
|
67
|
+
const sign = m.deltaUsd > 0 ? '+' : '';
|
|
68
|
+
// A service charge is a per-call figure only the gateway holds, so a local
|
|
69
|
+
// estimate for one is a guess by construction — say so rather than letting
|
|
70
|
+
// it read as a defect.
|
|
71
|
+
const note = m.row.kind === 'service' ? chalk.dim(' (service — locally an estimate by construction)') : '';
|
|
72
|
+
console.log(` ${m.row.endpoint.padEnd(30)} gateway ${usd(m.row.costUsd)} local ${usd(m.localUsd)} ${sign}${m.deltaUsd.toFixed(4)}${note}`);
|
|
73
|
+
}
|
|
74
|
+
if (r.missingLocally.length > 0) {
|
|
75
|
+
const sum = r.missingLocally.reduce((a, b) => a + b.costUsd, 0);
|
|
76
|
+
console.log(chalk.yellow(`\n ${r.missingLocally.length} charged request(s) have no local row (${usd(sum)}).`));
|
|
77
|
+
console.log(chalk.dim(' Franklin never counted these, so they never reached --max-spend either.'));
|
|
78
|
+
for (const row of r.missingLocally.slice(0, 5)) {
|
|
79
|
+
console.log(chalk.dim(` ${row.timestamp} ${row.endpoint} ${usd(row.costUsd)}`));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (r.unjoinable > 0) {
|
|
83
|
+
console.log(chalk.dim(`\n ${r.unjoinable} local row(s) carry no request id and were not compared.`));
|
|
84
|
+
}
|
|
85
|
+
console.log(chalk.dim(`\n Full activity: ${DASHBOARD_URL}/dashboard\n`));
|
|
86
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `franklin wallet-adopt <address>` — switch to a Solana wallet Franklin can
|
|
3
|
+
* see but is not using (blockrun#119).
|
|
4
|
+
*
|
|
5
|
+
* Explicit by design. The complaint behind #119 is that an upgrade changed the
|
|
6
|
+
* active address without asking, so the remedy must not do the same thing in
|
|
7
|
+
* the other direction: the user names the address, and only then does anything
|
|
8
|
+
* move. `importSolanaWallet` matches against the address DERIVED from each
|
|
9
|
+
* discovered key (never the file's own `address` field) and backs up the
|
|
10
|
+
* current `~/.blockrun/.solana-session` before replacing it.
|
|
11
|
+
*/
|
|
12
|
+
export declare function walletAdoptCommand(address: string): Promise<void>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `franklin wallet-adopt <address>` — switch to a Solana wallet Franklin can
|
|
3
|
+
* see but is not using (blockrun#119).
|
|
4
|
+
*
|
|
5
|
+
* Explicit by design. The complaint behind #119 is that an upgrade changed the
|
|
6
|
+
* active address without asking, so the remedy must not do the same thing in
|
|
7
|
+
* the other direction: the user names the address, and only then does anything
|
|
8
|
+
* move. `importSolanaWallet` matches against the address DERIVED from each
|
|
9
|
+
* discovered key (never the file's own `address` field) and backs up the
|
|
10
|
+
* current `~/.blockrun/.solana-session` before replacing it.
|
|
11
|
+
*/
|
|
12
|
+
import chalk from 'chalk';
|
|
13
|
+
import { detectSolanaWalletDivergence, activeSolanaAddress } from '../wallet/solana-migration.js';
|
|
14
|
+
export async function walletAdoptCommand(address) {
|
|
15
|
+
const wanted = address.trim();
|
|
16
|
+
const current = activeSolanaAddress();
|
|
17
|
+
if (current === wanted) {
|
|
18
|
+
console.log(`Already active: ${wanted}`);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const divergence = await detectSolanaWalletDivergence();
|
|
22
|
+
const candidates = divergence?.alternatives ?? [];
|
|
23
|
+
const match = candidates.find((w) => w.address === wanted);
|
|
24
|
+
if (!match) {
|
|
25
|
+
console.log(chalk.red(`No discovered wallet derives to ${wanted}.`));
|
|
26
|
+
if (candidates.length > 0) {
|
|
27
|
+
console.log('\nFound on this machine:');
|
|
28
|
+
for (const w of candidates)
|
|
29
|
+
console.log(` ${w.address} (${w.source})`);
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
console.log('Franklin found no other Solana wallets on this machine.');
|
|
33
|
+
}
|
|
34
|
+
process.exitCode = 1;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
const { importSolanaWallet } = await import('@blockrun/llm');
|
|
39
|
+
const adopted = await importSolanaWallet(wanted);
|
|
40
|
+
console.log(chalk.green(`Active Solana wallet is now ${adopted}`));
|
|
41
|
+
console.log(chalk.dim(` was: ${current ?? 'none'}`));
|
|
42
|
+
console.log(chalk.dim(` source: ${match.source}`));
|
|
43
|
+
console.log(chalk.dim(' the previous session file was backed up before it was replaced'));
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
console.log(chalk.red(`Could not adopt ${wanted}: ${err.message}`));
|
|
47
|
+
process.exitCode = 1;
|
|
48
|
+
}
|
|
49
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -246,6 +246,22 @@ program
|
|
|
246
246
|
const { doctorCommand } = await import('./commands/doctor.js');
|
|
247
247
|
await doctorCommand(opts);
|
|
248
248
|
});
|
|
249
|
+
program
|
|
250
|
+
.command('usage')
|
|
251
|
+
.description('Account ledger from the gateway, reconciled against the local journal')
|
|
252
|
+
.option('--days <n>', 'Days to read (default 30, max 365)')
|
|
253
|
+
.option('--json', 'Machine-readable output')
|
|
254
|
+
.action(async (opts) => {
|
|
255
|
+
const { usageCommand } = await import('./commands/usage.js');
|
|
256
|
+
await usageCommand(opts);
|
|
257
|
+
});
|
|
258
|
+
program
|
|
259
|
+
.command('wallet-adopt <address>')
|
|
260
|
+
.description('Make a discovered Solana wallet the active one (backs up the current session)')
|
|
261
|
+
.action(async (address) => {
|
|
262
|
+
const { walletAdoptCommand } = await import('./commands/wallet-adopt.js');
|
|
263
|
+
await walletAdoptCommand(address);
|
|
264
|
+
});
|
|
249
265
|
program
|
|
250
266
|
.command('telemetry [action]')
|
|
251
267
|
.description('Manage opt-in local telemetry (status|enable|disable|view|summary)')
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Shared account authentication for Franklin's direct gateway requests. */
|
|
2
|
+
export declare const ACCOUNT_PORTAL = "https://user.blockrun.ai";
|
|
3
|
+
export declare function accountMode(): boolean;
|
|
4
|
+
export declare function accountBaseURL(): string;
|
|
5
|
+
export declare function accountStatus(): {
|
|
6
|
+
authMode: string;
|
|
7
|
+
address: string;
|
|
8
|
+
chain: string;
|
|
9
|
+
balance: null;
|
|
10
|
+
balanceUsd: undefined;
|
|
11
|
+
portalUrl: string;
|
|
12
|
+
creditsUrl: string;
|
|
13
|
+
};
|
|
14
|
+
export declare function validateAccountConfig(): void;
|
|
15
|
+
export declare function gatewayFetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
16
|
+
/** Poll direct API jobs with an abortable deadline; never resubmit a job. */
|
|
17
|
+
export declare function pollAccountJob(response: Response, signal?: AbortSignal, intervalMs?: number): Promise<Response>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** Shared account authentication for Franklin's direct gateway requests. */
|
|
2
|
+
export const ACCOUNT_PORTAL = 'https://user.blockrun.ai';
|
|
3
|
+
export function accountMode() { return process.env.BLOCKRUN_API_KEY !== undefined; }
|
|
4
|
+
export function accountBaseURL() {
|
|
5
|
+
const raw = (process.env.BLOCKRUN_API_BASE_URL || 'https://api.blockrun.ai').replace(/\/+$/, '').replace(/\/v1$/, '');
|
|
6
|
+
const url = new URL(raw);
|
|
7
|
+
if (url.username || url.password || url.search || url.hash ||
|
|
8
|
+
(url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) {
|
|
9
|
+
throw new Error('BLOCKRUN_API_BASE_URL requires HTTPS (except localhost) and no credentials, query or fragment.');
|
|
10
|
+
}
|
|
11
|
+
return raw;
|
|
12
|
+
}
|
|
13
|
+
export function accountStatus() {
|
|
14
|
+
return { authMode: 'api-key', address: '', chain: 'account', balance: null, balanceUsd: undefined, portalUrl: ACCOUNT_PORTAL, creditsUrl: `${ACCOUNT_PORTAL}/dashboard/credits` };
|
|
15
|
+
}
|
|
16
|
+
function key() {
|
|
17
|
+
const value = process.env.BLOCKRUN_API_KEY?.trim() || '';
|
|
18
|
+
if (!/^brk_[A-Za-z0-9_-]+$/.test(value))
|
|
19
|
+
throw new Error(`Invalid BLOCKRUN_API_KEY. Create a key at ${ACCOUNT_PORTAL}/dashboard/keys.`);
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
export function validateAccountConfig() { if (accountMode()) {
|
|
23
|
+
key();
|
|
24
|
+
accountBaseURL();
|
|
25
|
+
} }
|
|
26
|
+
function accountRequestURL(input) {
|
|
27
|
+
const base = new URL(accountBaseURL());
|
|
28
|
+
const source = new URL(input instanceof Request ? input.url : String(input), `${base}/`);
|
|
29
|
+
const gateways = new Set(['https://blockrun.ai', 'https://sol.blockrun.ai', 'https://api.blockrun.ai', base.origin]);
|
|
30
|
+
if (!gateways.has(source.origin) || source.username || source.password)
|
|
31
|
+
throw new Error('Refusing to forward an account key to an unknown gateway or polling origin.');
|
|
32
|
+
source.protocol = base.protocol;
|
|
33
|
+
source.host = base.host;
|
|
34
|
+
source.pathname = source.pathname.replace(/^\/api\/v1\//, '/v1/');
|
|
35
|
+
return source;
|
|
36
|
+
}
|
|
37
|
+
// Caller receives the actual HTTP status, so existing stream parsers and proxy
|
|
38
|
+
// clients keep their error semantics. No x402 branch may run in account mode.
|
|
39
|
+
export async function gatewayFetch(input, init) {
|
|
40
|
+
if (!accountMode())
|
|
41
|
+
return globalThis.fetch(input, init);
|
|
42
|
+
const credential = key();
|
|
43
|
+
const url = accountRequestURL(input);
|
|
44
|
+
const request = input instanceof Request ? input : undefined;
|
|
45
|
+
const headers = new Headers(init?.headers ?? request?.headers);
|
|
46
|
+
for (const name of [...headers.keys()])
|
|
47
|
+
if (/payment/i.test(name) || /^(x-api-key|authorization)$/i.test(name))
|
|
48
|
+
headers.delete(name);
|
|
49
|
+
headers.set('authorization', `Bearer ${credential}`);
|
|
50
|
+
const response = await globalThis.fetch(request ? new Request(url, request) : url, { ...init, headers, redirect: 'error' });
|
|
51
|
+
if (response.ok)
|
|
52
|
+
return response;
|
|
53
|
+
let body;
|
|
54
|
+
try {
|
|
55
|
+
body = await response.json();
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
body = {};
|
|
59
|
+
}
|
|
60
|
+
const outer = body && typeof body === 'object' ? body : {};
|
|
61
|
+
const detail = outer.error && typeof outer.error === 'object' ? outer.error : outer;
|
|
62
|
+
const safe = Object.fromEntries(['message', 'code', 'type', 'param'].flatMap(name => typeof detail[name] === 'string' ? [[name, detail[name].split(credential).join('[REDACTED]')]] : []));
|
|
63
|
+
if (response.status === 402)
|
|
64
|
+
safe.message = `BlockRun account credits exhausted (402). Top up at ${ACCOUNT_PORTAL}/dashboard/credits.`;
|
|
65
|
+
if (response.status === 401)
|
|
66
|
+
safe.message = `BlockRun account authentication failed (401). Check your key at ${ACCOUNT_PORTAL}/dashboard/keys.`;
|
|
67
|
+
const safeHeaders = new Headers({ 'content-type': 'application/json' });
|
|
68
|
+
const retryAfter = response.headers.get('retry-after');
|
|
69
|
+
if (retryAfter)
|
|
70
|
+
safeHeaders.set('retry-after', retryAfter);
|
|
71
|
+
return new Response(JSON.stringify({ error: safe }), { status: response.status, headers: safeHeaders });
|
|
72
|
+
}
|
|
73
|
+
/** Poll direct API jobs with an abortable deadline; never resubmit a job. */
|
|
74
|
+
export async function pollAccountJob(response, signal, intervalMs = 2000) {
|
|
75
|
+
if (!accountMode() || response.status !== 202)
|
|
76
|
+
return response;
|
|
77
|
+
const initial = await response.clone().json();
|
|
78
|
+
if (!initial.poll_url)
|
|
79
|
+
throw new Error('Account async response missing poll_url');
|
|
80
|
+
const endpoint = accountRequestURL(initial.poll_url);
|
|
81
|
+
const deadline = AbortSignal.timeout(15 * 60_000);
|
|
82
|
+
const abort = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
83
|
+
while (!abort.aborted) {
|
|
84
|
+
await new Promise((resolve, reject) => {
|
|
85
|
+
const onAbort = () => { clearTimeout(timer); reject(abort.reason); };
|
|
86
|
+
const timer = setTimeout(() => { abort.removeEventListener('abort', onAbort); resolve(); }, intervalMs);
|
|
87
|
+
abort.addEventListener('abort', onAbort, { once: true });
|
|
88
|
+
if (abort.aborted)
|
|
89
|
+
onAbort();
|
|
90
|
+
});
|
|
91
|
+
const polled = await gatewayFetch(endpoint, { signal: abort });
|
|
92
|
+
if ([502, 503, 504, 522, 524].includes(polled.status)) {
|
|
93
|
+
await polled.body?.cancel();
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (!polled.ok)
|
|
97
|
+
return polled;
|
|
98
|
+
const data = await polled.clone().json();
|
|
99
|
+
if (data.status === 'completed')
|
|
100
|
+
return polled;
|
|
101
|
+
if (['failed', 'cancelled', 'canceled'].includes(data.status || ''))
|
|
102
|
+
throw new Error('Account job failed or was cancelled');
|
|
103
|
+
}
|
|
104
|
+
throw new Error('Account job polling stopped; check job before resubmitting');
|
|
105
|
+
}
|
|
@@ -44,12 +44,7 @@ export declare function maskApiKey(key: string): string;
|
|
|
44
44
|
* from the wallet for one run.
|
|
45
45
|
*/
|
|
46
46
|
export declare function useWalletMode(): void;
|
|
47
|
-
/**
|
|
48
|
-
* Demote to wallet mode after the gateway rejected the key (401). Called once
|
|
49
|
-
* per process — a key that does not authenticate will not authenticate on the
|
|
50
|
-
* next call either, and retrying it on every request would double the latency
|
|
51
|
-
* of an entire session.
|
|
52
|
-
*/
|
|
47
|
+
/** Refresh a rejected credential without changing the user's payment method. */
|
|
53
48
|
export declare function invalidateKey(): void;
|
|
54
49
|
/** Test seam — drop the memoised mode so env/file changes are re-read. */
|
|
55
50
|
export declare function resetPayModeCache(): void;
|
|
@@ -61,7 +56,7 @@ export declare function clearApiKey(): boolean;
|
|
|
61
56
|
* Resolve the active payment mode. Memoised per process — the resolution reads
|
|
62
57
|
* the filesystem and is hit on every gateway call.
|
|
63
58
|
*
|
|
64
|
-
* Precedence: `--wallet`
|
|
59
|
+
* Precedence: `--wallet` > BLOCKRUN_API_KEY > ~/.blockrun/api-key
|
|
65
60
|
* > wallet on the active chain.
|
|
66
61
|
*/
|
|
67
62
|
export declare function resolvePayMode(): PayMode;
|
|
@@ -72,7 +67,7 @@ export declare function isKeyMode(): boolean;
|
|
|
72
67
|
* `API_URLS[loadChain()]` that call sites used before key mode.
|
|
73
68
|
*/
|
|
74
69
|
export declare function gatewayBase(): string;
|
|
75
|
-
/** The x402 base
|
|
70
|
+
/** The x402 base for an explicitly selected wallet chain. */
|
|
76
71
|
export declare function walletBase(chain?: Chain): string;
|
|
77
72
|
/**
|
|
78
73
|
* Auth + identity headers for the active mode. Empty of auth in wallet mode,
|
|
@@ -128,20 +123,11 @@ export declare function fetchCreditBalance(timeoutMs?: number): Promise<CreditBa
|
|
|
128
123
|
* `gatewayHeaders()` instead.
|
|
129
124
|
*/
|
|
130
125
|
export declare function applyGatewayAuth(headers: Record<string, string>, mode?: PayMode): Record<string, string>;
|
|
131
|
-
/**
|
|
132
|
-
* Classify a key-mode failure so callers know whether falling back to the
|
|
133
|
-
* wallet is safe.
|
|
134
|
-
*
|
|
135
|
-
* Only two statuses are worth retrying elsewhere. A 401 means the key itself
|
|
136
|
-
* is bad, so the whole process demotes. A 404 `unsupported_endpoint` means
|
|
137
|
-
* this one path is not served on the key host, so only that call falls back.
|
|
138
|
-
* Everything else — 400, 402, 5xx — surfaces as-is, so a malformed request
|
|
139
|
-
* never silently drains wallet USDC on a second attempt.
|
|
140
|
-
*/
|
|
126
|
+
/** Classify account errors for display; neither error authorizes wallet billing. */
|
|
141
127
|
export type KeyFailure = 'invalid-key' | 'unsupported-endpoint' | null;
|
|
142
128
|
export declare function classifyKeyFailure(status: number, body: string): KeyFailure;
|
|
143
129
|
/**
|
|
144
|
-
* Rewrite a key-host URL
|
|
130
|
+
* Rewrite a key-host URL after the user explicitly selects wallet mode. The two
|
|
145
131
|
* differ by the `/api` segment the wallet hosts carry, so this swaps the
|
|
146
132
|
* origin and re-adds it rather than a plain string replace.
|
|
147
133
|
*/
|
|
@@ -48,16 +48,9 @@ export function useWalletMode() {
|
|
|
48
48
|
forceWallet = true;
|
|
49
49
|
cached = null;
|
|
50
50
|
}
|
|
51
|
-
/**
|
|
52
|
-
* Demote to wallet mode after the gateway rejected the key (401). Called once
|
|
53
|
-
* per process — a key that does not authenticate will not authenticate on the
|
|
54
|
-
* next call either, and retrying it on every request would double the latency
|
|
55
|
-
* of an entire session.
|
|
56
|
-
*/
|
|
51
|
+
/** Refresh a rejected credential without changing the user's payment method. */
|
|
57
52
|
export function invalidateKey() {
|
|
58
|
-
|
|
59
|
-
cached = null;
|
|
60
|
-
forceWallet = true;
|
|
53
|
+
cached = null;
|
|
61
54
|
}
|
|
62
55
|
/** Test seam — drop the memoised mode so env/file changes are re-read. */
|
|
63
56
|
export function resetPayModeCache() {
|
|
@@ -67,16 +60,18 @@ export function resetPayModeCache() {
|
|
|
67
60
|
function readKeyFile() {
|
|
68
61
|
try {
|
|
69
62
|
const raw = fs.readFileSync(API_KEY_FILE, 'utf-8').trim();
|
|
70
|
-
return raw
|
|
63
|
+
return raw;
|
|
71
64
|
}
|
|
72
|
-
catch {
|
|
73
|
-
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === 'ENOENT')
|
|
67
|
+
return null;
|
|
68
|
+
throw new Error('Cannot read the saved API key. Fix its permissions or explicitly use --wallet.');
|
|
74
69
|
}
|
|
75
70
|
}
|
|
76
71
|
/** The key Franklin would use, from env first then disk. Null when unset. */
|
|
77
72
|
export function loadApiKey() {
|
|
78
73
|
const fromEnv = process.env.BLOCKRUN_API_KEY?.trim();
|
|
79
|
-
if (fromEnv)
|
|
74
|
+
if (fromEnv !== undefined)
|
|
80
75
|
return fromEnv;
|
|
81
76
|
return readKeyFile();
|
|
82
77
|
}
|
|
@@ -100,7 +95,7 @@ export function clearApiKey() {
|
|
|
100
95
|
* Resolve the active payment mode. Memoised per process — the resolution reads
|
|
101
96
|
* the filesystem and is hit on every gateway call.
|
|
102
97
|
*
|
|
103
|
-
* Precedence: `--wallet`
|
|
98
|
+
* Precedence: `--wallet` > BLOCKRUN_API_KEY > ~/.blockrun/api-key
|
|
104
99
|
* > wallet on the active chain.
|
|
105
100
|
*/
|
|
106
101
|
export function resolvePayMode() {
|
|
@@ -108,7 +103,10 @@ export function resolvePayMode() {
|
|
|
108
103
|
return cached;
|
|
109
104
|
if (!forceWallet) {
|
|
110
105
|
const key = loadApiKey();
|
|
111
|
-
if (key
|
|
106
|
+
if (key !== null) {
|
|
107
|
+
if (!isApiKeyShaped(key)) {
|
|
108
|
+
throw new Error('Invalid API key in BLOCKRUN_API_KEY or the saved key file. Correct it, remove it, or explicitly use --wallet.');
|
|
109
|
+
}
|
|
112
110
|
cached = { kind: 'key', apiBase: KEY_API_URL, key };
|
|
113
111
|
return cached;
|
|
114
112
|
}
|
|
@@ -128,7 +126,7 @@ export function isKeyMode() {
|
|
|
128
126
|
export function gatewayBase() {
|
|
129
127
|
return resolvePayMode().apiBase;
|
|
130
128
|
}
|
|
131
|
-
/** The x402 base
|
|
129
|
+
/** The x402 base for an explicitly selected wallet chain. */
|
|
132
130
|
export function walletBase(chain = loadChain()) {
|
|
133
131
|
return API_URLS[chain];
|
|
134
132
|
}
|
|
@@ -214,7 +212,7 @@ export function classifyKeyFailure(status, body) {
|
|
|
214
212
|
return null;
|
|
215
213
|
}
|
|
216
214
|
/**
|
|
217
|
-
* Rewrite a key-host URL
|
|
215
|
+
* Rewrite a key-host URL after the user explicitly selects wallet mode. The two
|
|
218
216
|
* differ by the `/api` segment the wallet hosts carry, so this swaps the
|
|
219
217
|
* origin and re-adds it rather than a plain string replace.
|
|
220
218
|
*/
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How Franklin describes a charge to the user and to the model.
|
|
3
|
+
*
|
|
4
|
+
* Key mode spends prepaid account credits; wallet mode signs USDC over x402.
|
|
5
|
+
* Saying "USDC charged" or "paid via x402" in key mode is not a cosmetic slip:
|
|
6
|
+
* these strings are the receipt the user reads, the approval prompt they say
|
|
7
|
+
* yes to, and the text the model reasons over when it decides whether it can
|
|
8
|
+
* afford the next call. Naming the wrong instrument makes all three wrong.
|
|
9
|
+
*
|
|
10
|
+
* Two rules, and the split matters:
|
|
11
|
+
*
|
|
12
|
+
* Runtime output — receipts, approval prompts, cancellations — calls these
|
|
13
|
+
* helpers, which read the mode at call time. `invalidateKey()` can demote a
|
|
14
|
+
* session to wallet mode mid-run, so the mode must not be captured earlier.
|
|
15
|
+
*
|
|
16
|
+
* Static `spec.description` text is built once at module load, before any
|
|
17
|
+
* mode is settled and with no way to re-render afterwards. It must be
|
|
18
|
+
* phrased so it is true in BOTH modes — state the price, not the rail:
|
|
19
|
+
* "Costs $0.001 per call", never "Costs $0.001 USDC from the wallet".
|
|
20
|
+
* These helpers deliberately do not serve that case.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Parenthetical for a completed charge, e.g. `($5.00 USDC charged)` or
|
|
24
|
+
* `(billed to account credits)`. Key mode states no amount: the local figure
|
|
25
|
+
* is an estimate and the account ledger is authoritative.
|
|
26
|
+
*/
|
|
27
|
+
export declare function chargedNote(usd: number): string;
|
|
28
|
+
/** Sentence for an action that was cancelled or never dispatched. */
|
|
29
|
+
export declare function noChargeNote(): string;
|
|
30
|
+
/** Trailing reassurance on an approval prompt, before the user answers. */
|
|
31
|
+
export declare function cancelHint(): string;
|
|
32
|
+
/**
|
|
33
|
+
* Italic receipt line appended to a markdown tool result, e.g.
|
|
34
|
+
* `_$0.005 paid via x402._`. In key mode the rail is wrong AND the amount is
|
|
35
|
+
* unverifiable locally, so it names neither.
|
|
36
|
+
*/
|
|
37
|
+
export declare function receiptLine(usd: number): string;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How Franklin describes a charge to the user and to the model.
|
|
3
|
+
*
|
|
4
|
+
* Key mode spends prepaid account credits; wallet mode signs USDC over x402.
|
|
5
|
+
* Saying "USDC charged" or "paid via x402" in key mode is not a cosmetic slip:
|
|
6
|
+
* these strings are the receipt the user reads, the approval prompt they say
|
|
7
|
+
* yes to, and the text the model reasons over when it decides whether it can
|
|
8
|
+
* afford the next call. Naming the wrong instrument makes all three wrong.
|
|
9
|
+
*
|
|
10
|
+
* Two rules, and the split matters:
|
|
11
|
+
*
|
|
12
|
+
* Runtime output — receipts, approval prompts, cancellations — calls these
|
|
13
|
+
* helpers, which read the mode at call time. `invalidateKey()` can demote a
|
|
14
|
+
* session to wallet mode mid-run, so the mode must not be captured earlier.
|
|
15
|
+
*
|
|
16
|
+
* Static `spec.description` text is built once at module load, before any
|
|
17
|
+
* mode is settled and with no way to re-render afterwards. It must be
|
|
18
|
+
* phrased so it is true in BOTH modes — state the price, not the rail:
|
|
19
|
+
* "Costs $0.001 per call", never "Costs $0.001 USDC from the wallet".
|
|
20
|
+
* These helpers deliberately do not serve that case.
|
|
21
|
+
*/
|
|
22
|
+
import { isKeyMode } from './auth-mode.js';
|
|
23
|
+
function fmt(usd) {
|
|
24
|
+
// Sub-cent prices are real here ($0.001 tiers), so keep enough places to
|
|
25
|
+
// avoid rendering them as $0.00.
|
|
26
|
+
return usd < 0.01 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Parenthetical for a completed charge, e.g. `($5.00 USDC charged)` or
|
|
30
|
+
* `(billed to account credits)`. Key mode states no amount: the local figure
|
|
31
|
+
* is an estimate and the account ledger is authoritative.
|
|
32
|
+
*/
|
|
33
|
+
export function chargedNote(usd) {
|
|
34
|
+
return isKeyMode()
|
|
35
|
+
? 'billed to account credits — see Activity at user.blockrun.ai'
|
|
36
|
+
: `${fmt(usd)} USDC charged`;
|
|
37
|
+
}
|
|
38
|
+
/** Sentence for an action that was cancelled or never dispatched. */
|
|
39
|
+
export function noChargeNote() {
|
|
40
|
+
return isKeyMode() ? 'No account credits were spent.' : 'No USDC was spent.';
|
|
41
|
+
}
|
|
42
|
+
/** Trailing reassurance on an approval prompt, before the user answers. */
|
|
43
|
+
export function cancelHint() {
|
|
44
|
+
return isKeyMode()
|
|
45
|
+
? 'No account credits are spent if you cancel.'
|
|
46
|
+
: 'No USDC is spent if you cancel.';
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Italic receipt line appended to a markdown tool result, e.g.
|
|
50
|
+
* `_$0.005 paid via x402._`. In key mode the rail is wrong AND the amount is
|
|
51
|
+
* unverifiable locally, so it names neither.
|
|
52
|
+
*/
|
|
53
|
+
export function receiptLine(usd) {
|
|
54
|
+
return isKeyMode()
|
|
55
|
+
? '_Billed to account credits._'
|
|
56
|
+
: `_${fmt(usd)} paid via x402._`;
|
|
57
|
+
}
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
15
15
|
import { loadChain, USER_AGENT } from '../config.js';
|
|
16
|
-
import {
|
|
16
|
+
import { gatewayHeaders, resolvePayMode, } from './auth-mode.js';
|
|
17
17
|
async function extractPaymentReq(response) {
|
|
18
18
|
let header = response.headers.get('payment-required');
|
|
19
19
|
if (!header) {
|
|
@@ -83,21 +83,14 @@ export async function postWithPayment(endpoint, body, resourceDescription, timeo
|
|
|
83
83
|
body: payload,
|
|
84
84
|
});
|
|
85
85
|
const keyRaw = await keyResponse.text().catch(() => '');
|
|
86
|
-
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
let parsedKey = {};
|
|
92
|
-
try {
|
|
93
|
-
parsedKey = keyRaw ? JSON.parse(keyRaw) : {};
|
|
94
|
-
}
|
|
95
|
-
catch { /* leave as {} */ }
|
|
96
|
-
return { ok: keyResponse.ok, status: keyResponse.status, body: parsedKey, raw: keyRaw, settled: false };
|
|
86
|
+
// An account failure is never permission to spend from a wallet.
|
|
87
|
+
// The user can explicitly select --wallet and retry the command.
|
|
88
|
+
let parsedKey = {};
|
|
89
|
+
try {
|
|
90
|
+
parsedKey = keyRaw ? JSON.parse(keyRaw) : {};
|
|
97
91
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
endpoint = toWalletUrl(endpoint, chain);
|
|
92
|
+
catch { /* leave as {} */ }
|
|
93
|
+
return { ok: keyResponse.ok, status: keyResponse.status, body: parsedKey, raw: keyRaw, settled: false };
|
|
101
94
|
}
|
|
102
95
|
const headers = {
|
|
103
96
|
'Content-Type': 'application/json',
|
|
@@ -92,6 +92,15 @@ export declare function basePriceForPath(apiPath: string): number | null;
|
|
|
92
92
|
* in JS, which would book $0 against a billed call.
|
|
93
93
|
*/
|
|
94
94
|
export declare function chargeFromResponse(res: HeaderBag): number | null;
|
|
95
|
+
/**
|
|
96
|
+
* The gateway's id for this request, from `x-blockrun-request-id`.
|
|
97
|
+
*
|
|
98
|
+
* Recorded locally so `franklin usage` can join Franklin's journal to the
|
|
99
|
+
* account ledger row by row. Comparing totals is not the same check: two
|
|
100
|
+
* errors of opposite sign produce a total that matches and a ledger that is
|
|
101
|
+
* wrong in two places.
|
|
102
|
+
*/
|
|
103
|
+
export declare function requestIdFromResponse(res: HeaderBag): string | null;
|
|
95
104
|
/**
|
|
96
105
|
* Credit left on the account after this call, from
|
|
97
106
|
* `x-blockrun-credit-remaining-usd`. Absent on ungated accounts, which have no
|
|
@@ -397,6 +397,19 @@ export function basePriceForPath(apiPath) {
|
|
|
397
397
|
export function chargeFromResponse(res) {
|
|
398
398
|
return usdHeader(res, 'x-blockrun-cost-usd');
|
|
399
399
|
}
|
|
400
|
+
/**
|
|
401
|
+
* The gateway's id for this request, from `x-blockrun-request-id`.
|
|
402
|
+
*
|
|
403
|
+
* Recorded locally so `franklin usage` can join Franklin's journal to the
|
|
404
|
+
* account ledger row by row. Comparing totals is not the same check: two
|
|
405
|
+
* errors of opposite sign produce a total that matches and a ledger that is
|
|
406
|
+
* wrong in two places.
|
|
407
|
+
*/
|
|
408
|
+
export function requestIdFromResponse(res) {
|
|
409
|
+
const raw = res.headers?.get?.('x-blockrun-request-id');
|
|
410
|
+
const id = typeof raw === 'string' ? raw.trim() : '';
|
|
411
|
+
return id.length > 0 && id.length <= 128 ? id : null;
|
|
412
|
+
}
|
|
400
413
|
/**
|
|
401
414
|
* Credit left on the account after this call, from
|
|
402
415
|
* `x-blockrun-credit-remaining-usd`. Absent on ungated accounts, which have no
|