@blockrun/franklin 3.44.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 +36 -24
- 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/balance.js +37 -5
- 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 +39 -19
- package/dist/payments/auth-mode.js +54 -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 +70 -0
- package/dist/payments/price-catalog.js +154 -6
- 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.d.ts +5 -5
- package/dist/tools/defillama.js +13 -13
- package/dist/tools/exa.d.ts +1 -1
- package/dist/tools/exa.js +27 -18
- 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 +13 -11
- package/dist/tools/realface.js +3 -3
- package/dist/tools/rpc.d.ts +1 -1
- package/dist/tools/rpc.js +5 -5
- package/dist/tools/sensitive-paths.d.ts +1 -1
- package/dist/tools/sensitive-paths.js +13 -4
- package/dist/tools/surf.js +33 -5
- 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
package/dist/commands/doctor.js
CHANGED
|
@@ -287,6 +287,24 @@ async function runChecks() {
|
|
|
287
287
|
remedy: 'Add /opt/homebrew/bin to PATH in ~/.zshrc',
|
|
288
288
|
});
|
|
289
289
|
}
|
|
290
|
+
// ── Solana wallet divergence (blockrun#119) ───────────────────────
|
|
291
|
+
// A tightened SDK selection can leave a user spending from a different
|
|
292
|
+
// address than the one holding their USDC, with nothing printed. Report it
|
|
293
|
+
// where they already look when money seems missing.
|
|
294
|
+
try {
|
|
295
|
+
const { detectSolanaWalletDivergence } = await import('../wallet/solana-migration.js');
|
|
296
|
+
const divergence = await detectSolanaWalletDivergence();
|
|
297
|
+
if (divergence) {
|
|
298
|
+
out.push({
|
|
299
|
+
name: 'Solana wallet',
|
|
300
|
+
status: 'warn',
|
|
301
|
+
detail: `active ${divergence.active}; ${divergence.alternatives.length} other wallet(s) found: ` +
|
|
302
|
+
divergence.alternatives.map((w) => w.address).join(', '),
|
|
303
|
+
remedy: 'If your USDC is on one of those: franklin wallet-adopt <address>',
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
catch { /* a diagnostic must never take down `franklin doctor` */ }
|
|
290
308
|
return out;
|
|
291
309
|
}
|
|
292
310
|
function printHuman(checks) {
|
|
@@ -0,0 +1,14 @@
|
|
|
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
|
+
export declare function usageCommand(opts?: {
|
|
12
|
+
days?: string;
|
|
13
|
+
json?: boolean;
|
|
14
|
+
}): Promise<void>;
|
|
@@ -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,13 +67,47 @@ 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,
|
|
79
74
|
* where payment rides on the PAYMENT-SIGNATURE header instead.
|
|
80
75
|
*/
|
|
81
76
|
export declare function gatewayHeaders(mode?: PayMode): Record<string, string>;
|
|
77
|
+
/**
|
|
78
|
+
* A key's credit standing, from GET /v1/credits. The authoritative figure for
|
|
79
|
+
* display — the per-response `x-blockrun-credit-remaining-usd` header can
|
|
80
|
+
* understate under concurrency and is for warnings, not for showing a user.
|
|
81
|
+
*/
|
|
82
|
+
export interface CreditBalance {
|
|
83
|
+
accountId: string;
|
|
84
|
+
/**
|
|
85
|
+
* `ungated` accounts have NO ceiling, so `remainingUsd` is legitimately null.
|
|
86
|
+
* Never coalesce that to 0 — it would tell a paying customer they are broke.
|
|
87
|
+
* Branch on this field instead.
|
|
88
|
+
*/
|
|
89
|
+
billingMode: string;
|
|
90
|
+
currency: string;
|
|
91
|
+
grantedUsd: number;
|
|
92
|
+
spentUsd: number;
|
|
93
|
+
remainingUsd: number | null;
|
|
94
|
+
blocked: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* A stable CODE to map, not a string to show: ACCOUNT_SUSPENDED,
|
|
97
|
+
* CREDIT_LIMIT_REACHED, BALANCE_EXHAUSTED. Treated as append-only, so an
|
|
98
|
+
* unrecognised value must degrade gracefully rather than throw.
|
|
99
|
+
*/
|
|
100
|
+
blockedReason: string | null;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Fetch the key's credit standing. Null when there is no key, the gateway is
|
|
104
|
+
* unreachable, or it answers with something unexpected — callers show what they
|
|
105
|
+
* do know rather than inventing a number.
|
|
106
|
+
*
|
|
107
|
+
* `blocked` describes what the gateway would do with the NEXT call, so it is
|
|
108
|
+
* safe to gate an autonomous run on.
|
|
109
|
+
*/
|
|
110
|
+
export declare function fetchCreditBalance(timeoutMs?: number): Promise<CreditBalance | null>;
|
|
82
111
|
/**
|
|
83
112
|
* Merge this mode's auth into a header bag that may already carry a client's
|
|
84
113
|
* own credential, in place.
|
|
@@ -94,20 +123,11 @@ export declare function gatewayHeaders(mode?: PayMode): Record<string, string>;
|
|
|
94
123
|
* `gatewayHeaders()` instead.
|
|
95
124
|
*/
|
|
96
125
|
export declare function applyGatewayAuth(headers: Record<string, string>, mode?: PayMode): Record<string, string>;
|
|
97
|
-
/**
|
|
98
|
-
* Classify a key-mode failure so callers know whether falling back to the
|
|
99
|
-
* wallet is safe.
|
|
100
|
-
*
|
|
101
|
-
* Only two statuses are worth retrying elsewhere. A 401 means the key itself
|
|
102
|
-
* is bad, so the whole process demotes. A 404 `unsupported_endpoint` means
|
|
103
|
-
* this one path is not served on the key host, so only that call falls back.
|
|
104
|
-
* Everything else — 400, 402, 5xx — surfaces as-is, so a malformed request
|
|
105
|
-
* never silently drains wallet USDC on a second attempt.
|
|
106
|
-
*/
|
|
126
|
+
/** Classify account errors for display; neither error authorizes wallet billing. */
|
|
107
127
|
export type KeyFailure = 'invalid-key' | 'unsupported-endpoint' | null;
|
|
108
128
|
export declare function classifyKeyFailure(status: number, body: string): KeyFailure;
|
|
109
129
|
/**
|
|
110
|
-
* Rewrite a key-host URL
|
|
130
|
+
* Rewrite a key-host URL after the user explicitly selects wallet mode. The two
|
|
111
131
|
* differ by the `/api` segment the wallet hosts carry, so this swaps the
|
|
112
132
|
* origin and re-adds it rather than a plain string replace.
|
|
113
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
|
}
|
|
@@ -142,6 +140,45 @@ export function gatewayHeaders(mode = resolvePayMode()) {
|
|
|
142
140
|
headers['Authorization'] = `Bearer ${mode.key}`;
|
|
143
141
|
return headers;
|
|
144
142
|
}
|
|
143
|
+
/**
|
|
144
|
+
* Fetch the key's credit standing. Null when there is no key, the gateway is
|
|
145
|
+
* unreachable, or it answers with something unexpected — callers show what they
|
|
146
|
+
* do know rather than inventing a number.
|
|
147
|
+
*
|
|
148
|
+
* `blocked` describes what the gateway would do with the NEXT call, so it is
|
|
149
|
+
* safe to gate an autonomous run on.
|
|
150
|
+
*/
|
|
151
|
+
export async function fetchCreditBalance(timeoutMs = 15_000) {
|
|
152
|
+
const key = loadApiKey();
|
|
153
|
+
if (!key)
|
|
154
|
+
return null;
|
|
155
|
+
try {
|
|
156
|
+
const res = await fetch(`${KEY_API_URL}/v1/credits`, {
|
|
157
|
+
headers: { Authorization: `Bearer ${key}`, 'User-Agent': USER_AGENT },
|
|
158
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
159
|
+
});
|
|
160
|
+
if (!res.ok)
|
|
161
|
+
return null;
|
|
162
|
+
const b = (await res.json());
|
|
163
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
164
|
+
return {
|
|
165
|
+
accountId: typeof b.account_id === 'string' ? b.account_id : 'unknown',
|
|
166
|
+
billingMode: typeof b.billing_mode === 'string' ? b.billing_mode : 'unknown',
|
|
167
|
+
currency: typeof b.currency === 'string' ? b.currency : 'USD',
|
|
168
|
+
grantedUsd: num(b.granted_usd),
|
|
169
|
+
spentUsd: num(b.spent_usd),
|
|
170
|
+
// Explicitly preserve null — the whole point of this field.
|
|
171
|
+
remainingUsd: typeof b.remaining_usd === 'number' && Number.isFinite(b.remaining_usd)
|
|
172
|
+
? b.remaining_usd
|
|
173
|
+
: null,
|
|
174
|
+
blocked: b.blocked === true,
|
|
175
|
+
blockedReason: typeof b.blocked_reason === 'string' ? b.blocked_reason : null,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
145
182
|
/**
|
|
146
183
|
* Merge this mode's auth into a header bag that may already carry a client's
|
|
147
184
|
* own credential, in place.
|
|
@@ -175,7 +212,7 @@ export function classifyKeyFailure(status, body) {
|
|
|
175
212
|
return null;
|
|
176
213
|
}
|
|
177
214
|
/**
|
|
178
|
-
* Rewrite a key-host URL
|
|
215
|
+
* Rewrite a key-host URL after the user explicitly selects wallet mode. The two
|
|
179
216
|
* differ by the `/api` segment the wallet hosts carry, so this swaps the
|
|
180
217
|
* origin and re-adds it rather than a plain string replace.
|
|
181
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
|
+
}
|