@blockrun/llm 4.2.1 → 4.3.1
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 +105 -36
- package/dist/index.cjs +188 -10
- package/dist/index.d.cts +222 -2
- package/dist/index.d.ts +222 -2
- package/dist/index.js +185 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
### Cut your LLM bill by <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->%. One line of TypeScript.
|
|
6
6
|
|
|
7
|
-
The smart-routing SDK for <!-- br:models.chatVisible -->
|
|
7
|
+
The smart-routing SDK for <!-- br:models.chatVisible -->93<!-- /br:models.chatVisible --> models — every request goes to the cheapest model that can handle it,
|
|
8
8
|
paid with an API key or per-request USDC on Solana, Base or Arc. No vendor lock-in.
|
|
9
9
|
|
|
10
10
|
[](https://www.npmjs.com/package/@blockrun/llm)
|
|
@@ -56,7 +56,7 @@ console.log(r.response); // the proof
|
|
|
56
56
|
| | OpenAI SDK | OpenRouter | LiteLLM | **@blockrun/llm** |
|
|
57
57
|
| ------------------ | -------------- | ----------------- | ---------------- | ----------------------------------------------------------------------- |
|
|
58
58
|
| **Cost routing** | ✗ one vendor | Manual selection | Manual selection | **Automatic — <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% cheaper** |
|
|
59
|
-
| **Models** | GPT only | 200+ | 100+ (BYO keys) | **<!-- br:models.chatVisible -->
|
|
59
|
+
| **Models** | GPT only | 200+ | 100+ (BYO keys) | **<!-- br:models.chatVisible -->93<!-- /br:models.chatVisible -->, one credential** |
|
|
60
60
|
| **Free tier** | ✗ | Rate-limited | ✗ | **<!-- br:models.free -->9<!-- /br:models.free --> models, no signup** |
|
|
61
61
|
| **Auth** | API key | Account + API key | Your API keys | **API key *or* wallet signature** |
|
|
62
62
|
| **Payment** | Card + invoice | Credit card | BYO keys | **Account credit or USDC per-request** |
|
|
@@ -115,6 +115,7 @@ The Anthropic SDK is a runtime dependency because the public compatibility wrapp
|
|
|
115
115
|
| Enable metered batch settlement | [Batch settlement](#batch-settlement-optional-metered-billing) and the [full reference](https://github.com/BlockRunAI/blockrun-llm-ts/blob/main/docs/solana-batch.md) |
|
|
116
116
|
| Stream tokens, use tools | [Chat, Tools and Streaming](#chat-tools-and-streaming) |
|
|
117
117
|
| Generate media or query data services | [Models and Service APIs](#models-and-service-apis) |
|
|
118
|
+
| Get typed yes/no, choice or score answers | [Decisions](#decisions-typed-judgments) |
|
|
118
119
|
| Use the OpenAI or Anthropic SDK surface | [OpenAI and Anthropic Compatibility](#openai-and-anthropic-compatibility) |
|
|
119
120
|
| Create, find or import a wallet | [Wallets](#wallets) |
|
|
120
121
|
| Configure production credentials safely | [Configuration and Environment Variables](#configuration-and-environment-variables) and [Security](#security) |
|
|
@@ -581,7 +582,27 @@ console.log(`Lifetime: $${summary.totalUsd.toFixed(2)} over ${summary.calls} cal
|
|
|
581
582
|
console.log('By model:', summary.byModel);
|
|
582
583
|
```
|
|
583
584
|
|
|
584
|
-
|
|
585
|
+
#### Per-call cost and timeouts
|
|
586
|
+
|
|
587
|
+
Each paid chat response on `LLMClient` and `SolanaLLMClient` carries what it
|
|
588
|
+
cost. `costUsd` is what the call added to `getSpending()`: the signed price
|
|
589
|
+
under `exact`, the metered `extra.chargedAmount` under Solana batch settlement,
|
|
590
|
+
`0` for a free model; it is undefined in API-key mode (billed to the account).
|
|
591
|
+
`settlement` holds the scheme, the quote and the transaction. When the gateway
|
|
592
|
+
answers a paid request from a free fallback model it skips settlement:
|
|
593
|
+
`costUsd` is `0`, `settlement.skipped` is `"free-fallback"`, and nothing is
|
|
594
|
+
added to `getSpending()`.
|
|
595
|
+
|
|
596
|
+
Both clients default to a 600 s request timeout (`BLOCKRUN_CHAT_TIMEOUT`, in
|
|
597
|
+
seconds, overrides it; the per-call `timeout` option, in ms, overrides both).
|
|
598
|
+
A call aborted after its payment was sent may already have been charged, so it
|
|
599
|
+
is never paid again automatically; under Solana batch settlement it raises
|
|
600
|
+
`BatchPaymentUnresolvedError` (see
|
|
601
|
+
[Batch settlement](#batch-settlement-optional-metered-billing)).
|
|
602
|
+
|
|
603
|
+
#### Cost log and on-chain records
|
|
604
|
+
|
|
605
|
+
Only `LLMClient` wallet settlements (Base / Arc) are appended to
|
|
585
606
|
`~/.blockrun/cost_log.jsonl` automatically. Other clients count their payments
|
|
586
607
|
in their own `getSpending()`. Account usage lives on the
|
|
587
608
|
[Activity](https://user.blockrun.ai/dashboard/activity) page, not in-process.
|
|
@@ -647,19 +668,8 @@ const quick = await client.chatCompletion('reflection/beam-1.0-501b-a23b', messa
|
|
|
647
668
|
});
|
|
648
669
|
```
|
|
649
670
|
|
|
650
|
-
`costUsd`, `settlement` and the
|
|
651
|
-
|
|
652
|
-
(`BLOCKRUN_CHAT_TIMEOUT`, in seconds, overrides it; the `timeout` option, in
|
|
653
|
-
ms, overrides both). A call aborted after its payment was sent may already
|
|
654
|
-
have been charged; under Solana batch settlement such a call raises
|
|
655
|
-
`BatchPaymentUnresolvedError` rather than being paid again (see
|
|
656
|
-
[Batch settlement](#batch-settlement-optional-metered-billing)).
|
|
657
|
-
|
|
658
|
-
`costUsd` is what the call added to `getSpending()`: the signed price under `exact`, the metered `extra.chargedAmount` under batch settlement,
|
|
659
|
-
`0` for a free model; it is undefined in API-key mode (billed to the account).
|
|
660
|
-
When the gateway answers a paid request from a free fallback model it skips
|
|
661
|
-
settlement: `costUsd` is `0`, `settlement.skipped` is `"free-fallback"`, and
|
|
662
|
-
nothing is added to `getSpending()`.
|
|
671
|
+
`costUsd`, `settlement` and the request timeout work as on `LLMClient`: see
|
|
672
|
+
[Per-call cost and timeouts](#per-call-cost-and-timeouts).
|
|
663
673
|
|
|
664
674
|
**Setup:**
|
|
665
675
|
1. Export your Solana wallet key: `export SOLANA_WALLET_KEY="your-bs58-key"`
|
|
@@ -737,9 +747,9 @@ await client.closeBatchChannel();
|
|
|
737
747
|
- **Explicit trust.** `operators` has no default, and the SDK never learns a trusted key from a 402.
|
|
738
748
|
- **Bounded exposure.** `maxDeposit` caps the escrow deposited and not yet settled on-chain; it is the most the operator could claim without another authorization from you.
|
|
739
749
|
- **Never pays twice.** Anything that goes wrong before a batch payment is sent falls back to `exact`. Once one is sent, a call whose payment may have been charged throws `BatchPaymentUnresolvedError` and is never paid again (no new payment, no `exact`, no fallback model).
|
|
740
|
-
- **Chat, buffered and streamed.** `chat`, `chatCompletion`, `smartChat`, `smartChatCompletion` and `
|
|
750
|
+
- **Chat, buffered and streamed, and Decisions.** `chat`, `chatCompletion`, `smartChat`, `smartChatCompletion`, `stream()` and `decisions()` use batch; media jobs pay `exact`. A stream's receipt arrives as a final SSE event the SDK reads and removes before your loop sees it (it never reaches your chunks), or, for a stream that is cut, from `POST /v1/batch/receipt` afterwards. Its charge is booked in `getSpending()` once that receipt is in, which can be a few seconds after your loop ends: the model may keep generating after a disconnect, and that is charged too.
|
|
741
751
|
- **One channel per wallet.** All clients for a wallet share one channel, saved to `~/.blockrun/solana-batch/<wallet>.json` (mode `0600`) so a restart reuses it.
|
|
742
|
-
- **One call at a time per wallet.** A channel carries one pending authorization, and each voucher builds on the previous call's metered charge, which is known only once that call's answer is in. So the wallet stays busy from payment until the answer is reconciled: the whole generation, and for `stream()` the whole stream (including a stream your loop stopped reading: the SDK keeps reading it to its receipt, because everything generated is charged). A concurrent
|
|
752
|
+
- **One call at a time per wallet.** A channel carries one pending authorization, and each voucher builds on the previous call's metered charge, which is known only once that call's answer is in. So the wallet stays busy from payment until the answer is reconciled: the whole generation, and for `stream()` the whole stream (including a stream your loop stopped reading: the SDK keeps reading it to its receipt, because everything generated is charged). A concurrent batch call on the same wallet (`chat`, `chatCompletion`, `smartChat`, `smartChatCompletion`, `stream()`, `decisions()`) falls back to `exact` meanwhile, reported as `channel_busy`. `batch.onBusy: "wait"` makes it wait up to `batch.busyWaitMs` (default 60 s) and pay with batch instead, trading latency for price; `"throw"` raises `BatchChannelBusyError` (unpaid, nothing signed). The gateway allows one live channel per payer, so for parallel batch calls give each worker its own wallet.
|
|
743
753
|
- **One process per wallet.** The process that opens the channel holds its store's lock until it exits. Other processes on that wallet (worker pools, PM2/cluster workers, parallel runs) pay `exact`, reported as `channel_store_locked`. Give each worker its own wallet, or route calls through one process. `batch.onLocked: "wait"` waits up to `batch.lockWaitMs` (default 60 s) for the lock, and `"throw"` raises `BatchChannelLockedError` (unpaid, nothing signed) instead of paying `exact`.
|
|
744
754
|
- **Observable.** Every fallback, backoff, recovery and re-read writes one stderr line; `batch.onEvent` and `client.getBatchStats()` expose the same events and counters.
|
|
745
755
|
|
|
@@ -1375,6 +1385,69 @@ const info = await phone.lookup('+14155552671');
|
|
|
1375
1385
|
const { phone_number } = await phone.buyNumber({ country: 'US', areaCode: '415' });
|
|
1376
1386
|
```
|
|
1377
1387
|
|
|
1388
|
+
### Decisions (typed judgments)
|
|
1389
|
+
|
|
1390
|
+
`decisions()` asks `gpt-6-luna` questions with a fixed answer space and gets one
|
|
1391
|
+
typed answer per question back instead of text: a `predicate` (probability that
|
|
1392
|
+
it holds), a `choice` (one of your values, with per-value probabilities) or a
|
|
1393
|
+
`score` (position on an ordered rubric). Request and response match OpenAI's
|
|
1394
|
+
Decisions API. It is on `LLMClient`, `SolanaLLMClient` and the OpenAI wrapper
|
|
1395
|
+
(`client.decisions.create()`), with an API key or a wallet.
|
|
1396
|
+
|
|
1397
|
+
```typescript
|
|
1398
|
+
import { LLMClient } from '@blockrun/llm';
|
|
1399
|
+
|
|
1400
|
+
const client = new LLMClient();
|
|
1401
|
+
|
|
1402
|
+
const { answers, costUsd } = await client.decisions({
|
|
1403
|
+
input: 'My card was charged twice for one order and nobody answers my emails.',
|
|
1404
|
+
questions: [
|
|
1405
|
+
{ type: 'predicate', name: 'urgent', instructions: 'Does this need a reply today?' },
|
|
1406
|
+
{
|
|
1407
|
+
type: 'choice', name: 'team', instructions: 'Which team owns this?',
|
|
1408
|
+
choices: [
|
|
1409
|
+
{ value: 'billing', description: 'payments and refunds' },
|
|
1410
|
+
{ value: 'shipping', description: 'delivery' },
|
|
1411
|
+
{ value: 'none', description: 'fits no team' },
|
|
1412
|
+
],
|
|
1413
|
+
},
|
|
1414
|
+
{
|
|
1415
|
+
type: 'score', name: 'anger', instructions: 'How upset is the writer?',
|
|
1416
|
+
levels: [{ label: 'calm', description: '' }, { label: 'annoyed', description: '' }, { label: 'furious', description: '' }], // lowest first
|
|
1417
|
+
},
|
|
1418
|
+
],
|
|
1419
|
+
});
|
|
1420
|
+
// [{ type: 'predicate', name: 'urgent', probability: 0.85 },
|
|
1421
|
+
// { type: 'choice', name: 'team', choice: 'billing', probabilities: [...], confidence: 1 },
|
|
1422
|
+
// { type: 'score', name: 'anger', score: 1, probabilities: [...], confidence: 1 }]
|
|
1423
|
+
```
|
|
1424
|
+
|
|
1425
|
+
A `score` answer is the probability-weighted position on the rubric (0 = the
|
|
1426
|
+
first level), so it can be fractional: Gemini answered this example with 1.43
|
|
1427
|
+
(2% calm, 53% annoyed, 45% furious) where luna, all on "annoyed", gave 1. For a
|
|
1428
|
+
single level, take the entry in `probabilities` with the highest probability,
|
|
1429
|
+
or round.
|
|
1430
|
+
|
|
1431
|
+
Only input tokens are billed. A wallet call pays the 402's quote: an
|
|
1432
|
+
upper-bound estimate of the input tokens plus the $0.001 transaction fee. Under
|
|
1433
|
+
Solana [batch settlement](#batch-settlement-optional-metered-billing) it pays
|
|
1434
|
+
the input tokens the provider reports and no per-call fee instead, so a short
|
|
1435
|
+
question costs a few thousandths of a cent. With an API key the account is
|
|
1436
|
+
billed on reported tokens.
|
|
1437
|
+
|
|
1438
|
+
`input` is a string or messages with text and inline `data:image/*` images
|
|
1439
|
+
(hosted image URLs are refused). The gateway caps a call at 64 questions,
|
|
1440
|
+
255 choices or levels each, 120,000 characters of text and 8 images, and
|
|
1441
|
+
refuses an over-limit request with a 400 before any payment. A `choice` always
|
|
1442
|
+
picks one of your values, so give it a `none` value for inputs that fit
|
|
1443
|
+
nothing.
|
|
1444
|
+
|
|
1445
|
+
Pass `model: 'gemini-decision-1'` to use Google's Gemini Decision 1 (same price,
|
|
1446
|
+
up to 1,000 questions). It needs a `description` string on every choice and every
|
|
1447
|
+
score level; an empty string is fine. The SDK throws before sending when one is
|
|
1448
|
+
missing. `gpt-6-luna` accepts descriptions too, so the example above works on
|
|
1449
|
+
both models.
|
|
1450
|
+
|
|
1378
1451
|
### Standalone Search
|
|
1379
1452
|
|
|
1380
1453
|
`SearchClient` wraps `POST /v1/search` — Grok Live Search over `web` and
|
|
@@ -1397,33 +1470,29 @@ for (const c of result.citations ?? []) console.log(c.url);
|
|
|
1397
1470
|
The same endpoint is available as `search()` on `LLMClient` and
|
|
1398
1471
|
`SolanaLLMClient`.
|
|
1399
1472
|
|
|
1400
|
-
### Market Data
|
|
1473
|
+
### Market Data
|
|
1401
1474
|
|
|
1402
|
-
`PriceClient` wraps the
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1475
|
+
`PriceClient` wraps the market-data endpoints: crypto, FX and commodity prices,
|
|
1476
|
+
history and symbol lists, **free and without a wallet**. They are daily closes,
|
|
1477
|
+
not realtime (every response carries `realtime: false`), sourced from Chainlink
|
|
1478
|
+
feeds and Backpack.
|
|
1406
1479
|
|
|
1407
1480
|
```typescript
|
|
1408
1481
|
import { PriceClient } from '@blockrun/llm';
|
|
1409
1482
|
|
|
1410
1483
|
const p = new PriceClient({ requireWallet: false });
|
|
1411
|
-
const btc = await p.price('crypto', 'BTC-USD');
|
|
1484
|
+
const btc = await p.price('crypto', 'BTC-USD'); // btc.price, btc.source, btc.realtime === false
|
|
1412
1485
|
const eur = await p.price('fx', 'EUR-USD');
|
|
1486
|
+
const gold = await p.price('commodity', 'XAU-USD');
|
|
1487
|
+
const bars = await p.history('crypto', 'ETH-USD', { resolution: 'D', from: 1760000000, to: 1762000000 });
|
|
1413
1488
|
const symbols = await p.listSymbols('crypto', { query: 'sol', limit: 20 });
|
|
1414
|
-
|
|
1415
|
-
// Paid: requires an API key or a wallet
|
|
1416
|
-
const p2 = new PriceClient();
|
|
1417
|
-
const aapl = await p2.price('stocks', 'AAPL', { market: 'us' });
|
|
1418
|
-
const bars = await p2.history('stocks', 'AAPL', {
|
|
1419
|
-
market: 'us',
|
|
1420
|
-
resolution: 'D',
|
|
1421
|
-
from: 1700000000,
|
|
1422
|
-
to: 1710000000,
|
|
1423
|
-
});
|
|
1424
1489
|
```
|
|
1425
1490
|
|
|
1426
|
-
|
|
1491
|
+
**Equities are catalog-only for now.** `listSymbols('stocks', { market })` still
|
|
1492
|
+
lists the 12 markets' tickers (`us, hk, jp, kr, gb, de, fr, nl, ie, lu, cn, ca`),
|
|
1493
|
+
but stock `price()` and `history()` answer `501` (an `APIError` with
|
|
1494
|
+
`statusCode` 501): BlockRun does not currently serve equity prices. Nothing is
|
|
1495
|
+
charged for them.
|
|
1427
1496
|
|
|
1428
1497
|
### Prediction Markets (Powered by Predexon)
|
|
1429
1498
|
|
|
@@ -1843,7 +1912,7 @@ to pick up security fixes.
|
|
|
1843
1912
|
## Frequently Asked Questions
|
|
1844
1913
|
|
|
1845
1914
|
### What is @blockrun/llm?
|
|
1846
|
-
A TypeScript SDK that cuts LLM costs by <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% on a realistic workload with built-in smart routing: every request goes to the cheapest of <!-- br:models.chatVisible -->
|
|
1915
|
+
A TypeScript SDK that cuts LLM costs by <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% on a realistic workload with built-in smart routing: every request goes to the cheapest of <!-- br:models.chatVisible -->93<!-- /br:models.chatVisible --> models (OpenAI, Anthropic, Google, xAI, DeepSeek, Moonshot, and more) that can handle it, paid with an account API key or per-request USDC via x402 on Solana, Base or Arc.
|
|
1847
1916
|
|
|
1848
1917
|
### What is smart routing?
|
|
1849
1918
|
Router Core V3, bundled into the SDK: the same deterministic engine that powers ClawRouter. It analyzes each request across <!-- br:clawrouter.dimensions -->15<!-- /br:clawrouter.dimensions --> dimensions locally, in under 1ms, and picks the cheapest capable model. Use `smartChat()`, `smartChatCompletion()`, or the `blockrun/auto` model alias. See [Smart Routing](#smart-routing-router-core-v3).
|
package/dist/index.cjs
CHANGED
|
@@ -36,11 +36,14 @@ __export(index_exports, {
|
|
|
36
36
|
AnthropicClient: () => AnthropicClient,
|
|
37
37
|
BASE_CHAIN_ID: () => BASE_CHAIN_ID,
|
|
38
38
|
BLOCKRUN_SOL_OPERATOR: () => BLOCKRUN_SOL_OPERATOR,
|
|
39
|
+
BatchChannelBusyError: () => BatchChannelBusyError,
|
|
39
40
|
BatchChannelLockedError: () => BatchChannelLockedError,
|
|
40
41
|
BatchCloseDeferredError: () => BatchCloseDeferredError,
|
|
41
42
|
BatchPaymentUnresolvedError: () => BatchPaymentUnresolvedError,
|
|
42
43
|
BlockrunClient: () => BlockrunClient,
|
|
43
44
|
BlockrunError: () => BlockrunError,
|
|
45
|
+
DECISIONS_DEFAULT_MODEL: () => DECISIONS_DEFAULT_MODEL,
|
|
46
|
+
DEFAULT_BATCH_BUSY_WAIT_MS: () => DEFAULT_BATCH_BUSY_WAIT_MS,
|
|
44
47
|
DEFAULT_BATCH_IN_DOUBT: () => DEFAULT_BATCH_IN_DOUBT,
|
|
45
48
|
DEFAULT_BATCH_LOCK_WAIT_MS: () => DEFAULT_BATCH_LOCK_WAIT_MS,
|
|
46
49
|
DEFAULT_BATCH_RATE_LIMIT: () => DEFAULT_BATCH_RATE_LIMIT,
|
|
@@ -731,6 +734,51 @@ function withCost(body, response, bookedUsd, scheme) {
|
|
|
731
734
|
return body;
|
|
732
735
|
}
|
|
733
736
|
|
|
737
|
+
// src/decisions.ts
|
|
738
|
+
var DECISIONS_DEFAULT_MODEL = "gpt-6-luna";
|
|
739
|
+
var QUESTION_TYPES = /* @__PURE__ */ new Set(["predicate", "choice", "score"]);
|
|
740
|
+
var GEMINI_DECISIONS_MODEL = "gemini-decision-1";
|
|
741
|
+
function isGemini(model) {
|
|
742
|
+
return typeof model === "string" && model.trim().replace(/^google\//, "") === GEMINI_DECISIONS_MODEL;
|
|
743
|
+
}
|
|
744
|
+
function invalid(message) {
|
|
745
|
+
throw withDisposition(new Error(`decisions: ${message}`), "unpaid");
|
|
746
|
+
}
|
|
747
|
+
function buildDecisionsBody(request) {
|
|
748
|
+
if (!request || typeof request !== "object") invalid("request must be an object");
|
|
749
|
+
const { input, questions } = request;
|
|
750
|
+
const emptyInput = typeof input === "string" ? input.length === 0 : !Array.isArray(input) || input.length === 0;
|
|
751
|
+
if (emptyInput) invalid("input must be a non-empty string or a non-empty array of messages");
|
|
752
|
+
if (!Array.isArray(questions) || questions.length === 0) invalid("questions must be a non-empty array");
|
|
753
|
+
const names = /* @__PURE__ */ new Set();
|
|
754
|
+
questions.forEach((q, i) => {
|
|
755
|
+
if (!q || typeof q !== "object") invalid(`questions[${i}] must be an object`);
|
|
756
|
+
if (!QUESTION_TYPES.has(q.type)) invalid(`questions[${i}].type must be "predicate", "choice" or "score"`);
|
|
757
|
+
if (typeof q.name !== "string" || q.name.length === 0) invalid(`questions[${i}].name must be a non-empty string`);
|
|
758
|
+
if (typeof q.instructions !== "string" || q.instructions.length === 0) {
|
|
759
|
+
invalid(`questions[${i}].instructions must be a non-empty string`);
|
|
760
|
+
}
|
|
761
|
+
if (names.has(q.name)) invalid(`questions[${i}].name "${q.name}" is used twice; answers are keyed by name`);
|
|
762
|
+
names.add(q.name);
|
|
763
|
+
if (q.type === "choice" && (!Array.isArray(q.choices) || q.choices.length === 0)) {
|
|
764
|
+
invalid(`questions[${i}] (choice) needs a non-empty choices array`);
|
|
765
|
+
}
|
|
766
|
+
if (q.type === "score" && (!Array.isArray(q.levels) || q.levels.length === 0)) {
|
|
767
|
+
invalid(`questions[${i}] (score) needs a non-empty levels array, lowest first`);
|
|
768
|
+
}
|
|
769
|
+
if (isGemini(request.model) && (q.type === "choice" || q.type === "score")) {
|
|
770
|
+
const key = q.type === "choice" ? "choices" : "levels";
|
|
771
|
+
const items = (q.type === "choice" ? q.choices : q.levels) ?? [];
|
|
772
|
+
items.forEach((item, j) => {
|
|
773
|
+
if (!item || typeof item !== "object" || typeof item.description !== "string") {
|
|
774
|
+
invalid(`questions[${i}].${key}[${j}].description must be a string for ${GEMINI_DECISIONS_MODEL} (it may be empty: "")`);
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
});
|
|
779
|
+
return { ...request, model: request.model ?? DECISIONS_DEFAULT_MODEL };
|
|
780
|
+
}
|
|
781
|
+
|
|
734
782
|
// src/client.ts
|
|
735
783
|
var import_accounts2 = require("viem/accounts");
|
|
736
784
|
|
|
@@ -5317,7 +5365,7 @@ function getCostSummary() {
|
|
|
5317
5365
|
}
|
|
5318
5366
|
|
|
5319
5367
|
// src/version.ts
|
|
5320
|
-
var SDK_VERSION = "4.
|
|
5368
|
+
var SDK_VERSION = "4.3.1";
|
|
5321
5369
|
var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
|
|
5322
5370
|
|
|
5323
5371
|
// src/client.ts
|
|
@@ -6537,6 +6585,36 @@ var LLMClient = class _LLMClient {
|
|
|
6537
6585
|
const data = await this.requestWithPaymentRaw("/v1/search", body);
|
|
6538
6586
|
return data;
|
|
6539
6587
|
}
|
|
6588
|
+
/**
|
|
6589
|
+
* Typed judgments (OpenAI Decisions-compatible, `gpt-6-luna`): send
|
|
6590
|
+
* evidence and questions with a fixed answer space, get one typed answer
|
|
6591
|
+
* per question instead of text.
|
|
6592
|
+
*
|
|
6593
|
+
* Priced on input tokens only. With a wallet the 402 quotes an upper-bound
|
|
6594
|
+
* estimate of them plus the $0.001 transaction fee, and that quote settles;
|
|
6595
|
+
* with an API key the account is billed on the tokens the provider reports.
|
|
6596
|
+
* A request over the gateway's limits is refused with a 400 before payment.
|
|
6597
|
+
*
|
|
6598
|
+
* A `choice` always picks one of your values, so give it a `none` value for
|
|
6599
|
+
* inputs that fit nothing.
|
|
6600
|
+
*
|
|
6601
|
+
* @example
|
|
6602
|
+
* const { answers } = await client.decisions({
|
|
6603
|
+
* input: 'My card was charged twice for one order.',
|
|
6604
|
+
* questions: [
|
|
6605
|
+
* { type: 'predicate', name: 'urgent', instructions: 'Does this need a reply today?' },
|
|
6606
|
+
* { type: 'choice', name: 'team', instructions: 'Which team owns this?',
|
|
6607
|
+
* choices: [{ value: 'billing', description: 'payments and refunds' },
|
|
6608
|
+
* { value: 'shipping', description: 'delivery' },
|
|
6609
|
+
* { value: 'none', description: 'fits no team' }] },
|
|
6610
|
+
* ],
|
|
6611
|
+
* });
|
|
6612
|
+
*/
|
|
6613
|
+
async decisions(request) {
|
|
6614
|
+
const body = buildDecisionsBody(request);
|
|
6615
|
+
const response = await this.requestWithPayment("/v1/decisions", body);
|
|
6616
|
+
return response;
|
|
6617
|
+
}
|
|
6540
6618
|
/**
|
|
6541
6619
|
* Generic Exa endpoint proxy (POST). Useful when you need an Exa API
|
|
6542
6620
|
* surface that the typed wrappers below don't expose.
|
|
@@ -8927,7 +9005,9 @@ var PriceClient = class {
|
|
|
8927
9005
|
assetType: data.assetType,
|
|
8928
9006
|
category: data.category,
|
|
8929
9007
|
source: data.source,
|
|
8930
|
-
free: data.free
|
|
9008
|
+
free: data.free,
|
|
9009
|
+
realtime: data.realtime,
|
|
9010
|
+
note: data.note
|
|
8931
9011
|
};
|
|
8932
9012
|
}
|
|
8933
9013
|
async history(category, symbol, options) {
|
|
@@ -10585,6 +10665,8 @@ var DEFAULT_BATCH_RATE_LIMIT = { maxAttempts: 3, maxWaitMs: 6e4 };
|
|
|
10585
10665
|
var DEFAULT_BATCH_IN_DOUBT = { maxWaitMs: 3e5 };
|
|
10586
10666
|
var DEFAULT_BATCH_LOCK_WAIT_MS = 6e4;
|
|
10587
10667
|
var LOCK_POLL_MS = 500;
|
|
10668
|
+
var DEFAULT_BATCH_BUSY_WAIT_MS = 6e4;
|
|
10669
|
+
var BUSY_POLL_MS = 100;
|
|
10588
10670
|
var BatchPaymentUnresolvedError = class extends PaymentError {
|
|
10589
10671
|
/** The {@link SolanaBatchEvent.reason} of the `unresolved` event reported with it. */
|
|
10590
10672
|
reason;
|
|
@@ -10646,6 +10728,21 @@ var BatchChannelLockedError = class extends BlockrunError {
|
|
|
10646
10728
|
withDisposition(this, "unpaid");
|
|
10647
10729
|
}
|
|
10648
10730
|
};
|
|
10731
|
+
var BatchChannelBusyError = class extends BlockrunError {
|
|
10732
|
+
/** The paying wallet's address. */
|
|
10733
|
+
wallet;
|
|
10734
|
+
/** How long this call waited for the wallet, in ms (0 unless `onBusy` is `"wait"`). */
|
|
10735
|
+
waitedMs;
|
|
10736
|
+
constructor(init) {
|
|
10737
|
+
super(
|
|
10738
|
+
`batch-settlement busy for wallet ${init.wallet}: another batch call is in flight` + (init.waitedMs > 0 ? ` (waited ${init.waitedMs} ms)` : "")
|
|
10739
|
+
);
|
|
10740
|
+
this.name = "BatchChannelBusyError";
|
|
10741
|
+
this.wallet = init.wallet;
|
|
10742
|
+
this.waitedMs = init.waitedMs;
|
|
10743
|
+
withDisposition(this, "unpaid");
|
|
10744
|
+
}
|
|
10745
|
+
};
|
|
10649
10746
|
var INSTALL_HINT2 = "npm install @x402/core@~2.30.0 @x402/svm@~2.30.0 @solana/kit@^8";
|
|
10650
10747
|
async function load(pkg, importer) {
|
|
10651
10748
|
try {
|
|
@@ -10825,20 +10922,20 @@ var FileIntentJournal = class _FileIntentJournal {
|
|
|
10825
10922
|
if (err.code === "ENOENT") return {};
|
|
10826
10923
|
throw err;
|
|
10827
10924
|
}
|
|
10828
|
-
const
|
|
10925
|
+
const invalid2 = (why) => new Error(`deposit-intent journal ${this.file} is not valid (${why})`);
|
|
10829
10926
|
let parsed;
|
|
10830
10927
|
try {
|
|
10831
10928
|
parsed = JSON.parse(text);
|
|
10832
10929
|
} catch (err) {
|
|
10833
|
-
throw
|
|
10930
|
+
throw invalid2(err instanceof Error ? err.message : String(err));
|
|
10834
10931
|
}
|
|
10835
|
-
if (!isPlainObject(parsed)) throw
|
|
10836
|
-
if (parsed.version !== 1) throw
|
|
10932
|
+
if (!isPlainObject(parsed)) throw invalid2("not a JSON object");
|
|
10933
|
+
if (parsed.version !== 1) throw invalid2(`unsupported version ${JSON.stringify(parsed.version)}`);
|
|
10837
10934
|
const { intents } = parsed;
|
|
10838
|
-
if (!isPlainObject(intents)) throw
|
|
10935
|
+
if (!isPlainObject(intents)) throw invalid2("intents is not an object");
|
|
10839
10936
|
for (const [key, intent] of Object.entries(intents)) {
|
|
10840
10937
|
const why = intentProblem(key, intent);
|
|
10841
|
-
if (why) throw
|
|
10938
|
+
if (why) throw invalid2(`intent ${JSON.stringify(key)}: ${why}`);
|
|
10842
10939
|
}
|
|
10843
10940
|
return intents;
|
|
10844
10941
|
}
|
|
@@ -11718,6 +11815,14 @@ var SolanaBatchPayer = class {
|
|
|
11718
11815
|
if (!Number.isFinite(this.lockWaitMs) || this.lockWaitMs < 0) {
|
|
11719
11816
|
throw new Error("batch.lockWaitMs must be a finite number of ms >= 0");
|
|
11720
11817
|
}
|
|
11818
|
+
this.onBusy = init.options.onBusy ?? "exact";
|
|
11819
|
+
if (this.onBusy !== "exact" && this.onBusy !== "wait" && this.onBusy !== "throw") {
|
|
11820
|
+
throw new Error('batch.onBusy must be "exact", "wait" or "throw"');
|
|
11821
|
+
}
|
|
11822
|
+
this.busyWaitMs = init.options.busyWaitMs ?? DEFAULT_BATCH_BUSY_WAIT_MS;
|
|
11823
|
+
if (!Number.isFinite(this.busyWaitMs) || this.busyWaitMs < 0) {
|
|
11824
|
+
throw new Error("batch.busyWaitMs must be a finite number of ms >= 0");
|
|
11825
|
+
}
|
|
11721
11826
|
}
|
|
11722
11827
|
init;
|
|
11723
11828
|
state;
|
|
@@ -11726,6 +11831,8 @@ var SolanaBatchPayer = class {
|
|
|
11726
11831
|
inDoubtMaxWaitMs;
|
|
11727
11832
|
onLocked;
|
|
11728
11833
|
lockWaitMs;
|
|
11834
|
+
onBusy;
|
|
11835
|
+
busyWaitMs;
|
|
11729
11836
|
counters = {
|
|
11730
11837
|
fallbacks: 0,
|
|
11731
11838
|
fallbacksByReason: {},
|
|
@@ -12187,6 +12294,22 @@ var SolanaBatchPayer = class {
|
|
|
12187
12294
|
});
|
|
12188
12295
|
return { kind: "failed", error };
|
|
12189
12296
|
}
|
|
12297
|
+
/**
|
|
12298
|
+
* `onBusy: "wait"`: look at the wallet every {@link BUSY_POLL_MS} until no
|
|
12299
|
+
* batch call holds it or `deadline` passes. True when it is free.
|
|
12300
|
+
*/
|
|
12301
|
+
async waitWhileBusy(wallet, deadline) {
|
|
12302
|
+
while (wallet.busy) {
|
|
12303
|
+
const left = deadline - Date.now();
|
|
12304
|
+
if (left <= 0) return false;
|
|
12305
|
+
await sleep2(Math.min(BUSY_POLL_MS, left));
|
|
12306
|
+
}
|
|
12307
|
+
return true;
|
|
12308
|
+
}
|
|
12309
|
+
/** `onBusy` other than `"exact"`: the call's `"unpaid"` error, nothing signed. */
|
|
12310
|
+
async busyOut(waitedMs) {
|
|
12311
|
+
return { kind: "failed", error: new BatchChannelBusyError({ wallet: await this.init.address(), waitedMs }) };
|
|
12312
|
+
}
|
|
12190
12313
|
/**
|
|
12191
12314
|
* The close fence for a call about to send its first request: how many
|
|
12192
12315
|
* closes this wallet has completed so far, to hand to {@link pay}.
|
|
@@ -12212,6 +12335,8 @@ var SolanaBatchPayer = class {
|
|
|
12212
12335
|
const budget = { attempt: 1, waited: 0 };
|
|
12213
12336
|
let waitedUntil = 0;
|
|
12214
12337
|
let backedOff;
|
|
12338
|
+
let busySince;
|
|
12339
|
+
let rechallengeAfterBusy = false;
|
|
12215
12340
|
let holding = false;
|
|
12216
12341
|
let sent;
|
|
12217
12342
|
const release = () => {
|
|
@@ -12247,7 +12372,8 @@ var SolanaBatchPayer = class {
|
|
|
12247
12372
|
await sleep2(wait);
|
|
12248
12373
|
continue;
|
|
12249
12374
|
}
|
|
12250
|
-
if (budget.attempt > 1 || budget.waited > 0) {
|
|
12375
|
+
if (budget.attempt > 1 || budget.waited > 0 || rechallengeAfterBusy) {
|
|
12376
|
+
rechallengeAfterBusy = false;
|
|
12251
12377
|
let fresh;
|
|
12252
12378
|
try {
|
|
12253
12379
|
fresh = await rechallenge();
|
|
@@ -12275,7 +12401,28 @@ var SolanaBatchPayer = class {
|
|
|
12275
12401
|
detail: "closeBatchChannel() closed this wallet's channel after this call started; it opens no channel"
|
|
12276
12402
|
});
|
|
12277
12403
|
}
|
|
12278
|
-
if (wallet.busy)
|
|
12404
|
+
if (wallet.busy) {
|
|
12405
|
+
if (this.onBusy === "exact") return fallback({ reason: "channel_busy", attempt: budget.attempt });
|
|
12406
|
+
const waited = busySince === void 0 ? 0 : Date.now() - busySince;
|
|
12407
|
+
if (this.onBusy === "throw") return this.busyOut(waited);
|
|
12408
|
+
if (busySince === void 0) {
|
|
12409
|
+
busySince = Date.now();
|
|
12410
|
+
if (this.busyWaitMs > 0) {
|
|
12411
|
+
await this.report({
|
|
12412
|
+
type: "backoff",
|
|
12413
|
+
reason: "channel_busy",
|
|
12414
|
+
retryAfterMs: this.busyWaitMs,
|
|
12415
|
+
attempt: budget.attempt,
|
|
12416
|
+
detail: 'another batch call for this wallet is in flight; waiting for it (onBusy: "wait")'
|
|
12417
|
+
});
|
|
12418
|
+
}
|
|
12419
|
+
}
|
|
12420
|
+
if (!await this.waitWhileBusy(wallet, busySince + this.busyWaitMs)) {
|
|
12421
|
+
return this.busyOut(Date.now() - busySince);
|
|
12422
|
+
}
|
|
12423
|
+
rechallengeAfterBusy = true;
|
|
12424
|
+
continue;
|
|
12425
|
+
}
|
|
12279
12426
|
if (wallet.file && !holdsChannelFile(wallet.file)) {
|
|
12280
12427
|
const detail = `this process no longer holds the lock on ${wallet.file}; another owner may be paying into its channels`;
|
|
12281
12428
|
if (this.onLocked !== "exact") return this.lockedOut(detail, void 0, 0);
|
|
@@ -13900,6 +14047,22 @@ var SolanaLLMClient = class {
|
|
|
13900
14047
|
const data = await this.requestWithPaymentRaw("/v1/search", body);
|
|
13901
14048
|
return data;
|
|
13902
14049
|
}
|
|
14050
|
+
/**
|
|
14051
|
+
* Typed judgments (OpenAI Decisions-compatible, `gpt-6-luna`), paid on
|
|
14052
|
+
* Solana: one typed answer per question instead of text. See
|
|
14053
|
+
* {@link LLMClient.decisions} for the request shape.
|
|
14054
|
+
*
|
|
14055
|
+
* Under `exact` the 402's quote settles (an upper-bound estimate of the
|
|
14056
|
+
* input tokens plus the $0.001 fee). With the `batch` option the call pays
|
|
14057
|
+
* with a channel voucher and is charged the input tokens the provider
|
|
14058
|
+
* reports, with no per-call fee; `costUsd` is that metered charge. It shares
|
|
14059
|
+
* the wallet's channel with chat, one batch call at a time.
|
|
14060
|
+
*/
|
|
14061
|
+
async decisions(request) {
|
|
14062
|
+
const body = buildDecisionsBody(request);
|
|
14063
|
+
const response = await this.requestWithPayment("/v1/decisions", body);
|
|
14064
|
+
return response;
|
|
14065
|
+
}
|
|
13903
14066
|
// ── Prediction Markets (Powered by Predexon) ────────────────────────────
|
|
13904
14067
|
async pm(path7, params) {
|
|
13905
14068
|
return this.getWithPaymentRaw(`/v1/pm/${path7}`, params);
|
|
@@ -15063,8 +15226,19 @@ var Chat = class {
|
|
|
15063
15226
|
this.completions = new ChatCompletions(client, apiUrl, timeout);
|
|
15064
15227
|
}
|
|
15065
15228
|
};
|
|
15229
|
+
var Decisions = class {
|
|
15230
|
+
constructor(client) {
|
|
15231
|
+
this.client = client;
|
|
15232
|
+
}
|
|
15233
|
+
client;
|
|
15234
|
+
/** Same as {@link LLMClient.decisions}. */
|
|
15235
|
+
async create(params) {
|
|
15236
|
+
return this.client.decisions(params);
|
|
15237
|
+
}
|
|
15238
|
+
};
|
|
15066
15239
|
var OpenAI = class {
|
|
15067
15240
|
chat;
|
|
15241
|
+
decisions;
|
|
15068
15242
|
get authMode() {
|
|
15069
15243
|
return this.client.authMode;
|
|
15070
15244
|
}
|
|
@@ -15081,6 +15255,7 @@ var OpenAI = class {
|
|
|
15081
15255
|
timeout
|
|
15082
15256
|
});
|
|
15083
15257
|
this.chat = new Chat(this.client, apiUrl, timeout);
|
|
15258
|
+
this.decisions = new Decisions(this.client);
|
|
15084
15259
|
}
|
|
15085
15260
|
/**
|
|
15086
15261
|
* Get the wallet address being used for payments.
|
|
@@ -15229,11 +15404,14 @@ var AnthropicClient = class {
|
|
|
15229
15404
|
AnthropicClient,
|
|
15230
15405
|
BASE_CHAIN_ID,
|
|
15231
15406
|
BLOCKRUN_SOL_OPERATOR,
|
|
15407
|
+
BatchChannelBusyError,
|
|
15232
15408
|
BatchChannelLockedError,
|
|
15233
15409
|
BatchCloseDeferredError,
|
|
15234
15410
|
BatchPaymentUnresolvedError,
|
|
15235
15411
|
BlockrunClient,
|
|
15236
15412
|
BlockrunError,
|
|
15413
|
+
DECISIONS_DEFAULT_MODEL,
|
|
15414
|
+
DEFAULT_BATCH_BUSY_WAIT_MS,
|
|
15237
15415
|
DEFAULT_BATCH_IN_DOUBT,
|
|
15238
15416
|
DEFAULT_BATCH_LOCK_WAIT_MS,
|
|
15239
15417
|
DEFAULT_BATCH_RATE_LIMIT,
|