@blockrun/llm 4.2.1 → 4.3.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/dist/index.js CHANGED
@@ -593,6 +593,38 @@ function withCost(body, response, bookedUsd, scheme) {
593
593
  return body;
594
594
  }
595
595
 
596
+ // src/decisions.ts
597
+ var DECISIONS_DEFAULT_MODEL = "gpt-6-luna";
598
+ var QUESTION_TYPES = /* @__PURE__ */ new Set(["predicate", "choice", "score"]);
599
+ function invalid(message) {
600
+ throw withDisposition(new Error(`decisions: ${message}`), "unpaid");
601
+ }
602
+ function buildDecisionsBody(request) {
603
+ if (!request || typeof request !== "object") invalid("request must be an object");
604
+ const { input, questions } = request;
605
+ const emptyInput = typeof input === "string" ? input.length === 0 : !Array.isArray(input) || input.length === 0;
606
+ if (emptyInput) invalid("input must be a non-empty string or a non-empty array of messages");
607
+ if (!Array.isArray(questions) || questions.length === 0) invalid("questions must be a non-empty array");
608
+ const names = /* @__PURE__ */ new Set();
609
+ questions.forEach((q, i) => {
610
+ if (!q || typeof q !== "object") invalid(`questions[${i}] must be an object`);
611
+ if (!QUESTION_TYPES.has(q.type)) invalid(`questions[${i}].type must be "predicate", "choice" or "score"`);
612
+ if (typeof q.name !== "string" || q.name.length === 0) invalid(`questions[${i}].name must be a non-empty string`);
613
+ if (typeof q.instructions !== "string" || q.instructions.length === 0) {
614
+ invalid(`questions[${i}].instructions must be a non-empty string`);
615
+ }
616
+ if (names.has(q.name)) invalid(`questions[${i}].name "${q.name}" is used twice; answers are keyed by name`);
617
+ names.add(q.name);
618
+ if (q.type === "choice" && (!Array.isArray(q.choices) || q.choices.length === 0)) {
619
+ invalid(`questions[${i}] (choice) needs a non-empty choices array`);
620
+ }
621
+ if (q.type === "score" && (!Array.isArray(q.levels) || q.levels.length === 0)) {
622
+ invalid(`questions[${i}] (score) needs a non-empty levels array, lowest first`);
623
+ }
624
+ });
625
+ return { ...request, model: request.model ?? DECISIONS_DEFAULT_MODEL };
626
+ }
627
+
596
628
  // src/client.ts
597
629
  import { privateKeyToAccount } from "viem/accounts";
598
630
 
@@ -5179,7 +5211,7 @@ function getCostSummary() {
5179
5211
  }
5180
5212
 
5181
5213
  // src/version.ts
5182
- var SDK_VERSION = "4.2.1";
5214
+ var SDK_VERSION = "4.3.0";
5183
5215
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5184
5216
 
5185
5217
  // src/client.ts
@@ -6399,6 +6431,34 @@ var LLMClient = class _LLMClient {
6399
6431
  const data = await this.requestWithPaymentRaw("/v1/search", body);
6400
6432
  return data;
6401
6433
  }
6434
+ /**
6435
+ * Typed judgments (OpenAI Decisions-compatible, `gpt-6-luna`): send
6436
+ * evidence and questions with a fixed answer space, get one typed answer
6437
+ * per question instead of text.
6438
+ *
6439
+ * Priced on input tokens only. With a wallet the 402 quotes an upper-bound
6440
+ * estimate of them plus the $0.001 transaction fee, and that quote settles;
6441
+ * with an API key the account is billed on the tokens the provider reports.
6442
+ * A request over the gateway's limits is refused with a 400 before payment.
6443
+ *
6444
+ * A `choice` always picks one of your values, so give it a `none` value for
6445
+ * inputs that fit nothing.
6446
+ *
6447
+ * @example
6448
+ * const { answers } = await client.decisions({
6449
+ * input: 'My card was charged twice for one order.',
6450
+ * questions: [
6451
+ * { type: 'predicate', name: 'urgent', instructions: 'Does this need a reply today?' },
6452
+ * { type: 'choice', name: 'team', instructions: 'Which team owns this?',
6453
+ * choices: [{ value: 'billing' }, { value: 'shipping' }, { value: 'none' }] },
6454
+ * ],
6455
+ * });
6456
+ */
6457
+ async decisions(request) {
6458
+ const body = buildDecisionsBody(request);
6459
+ const response = await this.requestWithPayment("/v1/decisions", body);
6460
+ return response;
6461
+ }
6402
6462
  /**
6403
6463
  * Generic Exa endpoint proxy (POST). Useful when you need an Exa API
6404
6464
  * surface that the typed wrappers below don't expose.
@@ -8789,7 +8849,9 @@ var PriceClient = class {
8789
8849
  assetType: data.assetType,
8790
8850
  category: data.category,
8791
8851
  source: data.source,
8792
- free: data.free
8852
+ free: data.free,
8853
+ realtime: data.realtime,
8854
+ note: data.note
8793
8855
  };
8794
8856
  }
8795
8857
  async history(category, symbol, options) {
@@ -10447,6 +10509,8 @@ var DEFAULT_BATCH_RATE_LIMIT = { maxAttempts: 3, maxWaitMs: 6e4 };
10447
10509
  var DEFAULT_BATCH_IN_DOUBT = { maxWaitMs: 3e5 };
10448
10510
  var DEFAULT_BATCH_LOCK_WAIT_MS = 6e4;
10449
10511
  var LOCK_POLL_MS = 500;
10512
+ var DEFAULT_BATCH_BUSY_WAIT_MS = 6e4;
10513
+ var BUSY_POLL_MS = 100;
10450
10514
  var BatchPaymentUnresolvedError = class extends PaymentError {
10451
10515
  /** The {@link SolanaBatchEvent.reason} of the `unresolved` event reported with it. */
10452
10516
  reason;
@@ -10508,6 +10572,21 @@ var BatchChannelLockedError = class extends BlockrunError {
10508
10572
  withDisposition(this, "unpaid");
10509
10573
  }
10510
10574
  };
10575
+ var BatchChannelBusyError = class extends BlockrunError {
10576
+ /** The paying wallet's address. */
10577
+ wallet;
10578
+ /** How long this call waited for the wallet, in ms (0 unless `onBusy` is `"wait"`). */
10579
+ waitedMs;
10580
+ constructor(init) {
10581
+ super(
10582
+ `batch-settlement busy for wallet ${init.wallet}: another batch call is in flight` + (init.waitedMs > 0 ? ` (waited ${init.waitedMs} ms)` : "")
10583
+ );
10584
+ this.name = "BatchChannelBusyError";
10585
+ this.wallet = init.wallet;
10586
+ this.waitedMs = init.waitedMs;
10587
+ withDisposition(this, "unpaid");
10588
+ }
10589
+ };
10511
10590
  var INSTALL_HINT2 = "npm install @x402/core@~2.30.0 @x402/svm@~2.30.0 @solana/kit@^8";
10512
10591
  async function load(pkg, importer) {
10513
10592
  try {
@@ -10687,20 +10766,20 @@ var FileIntentJournal = class _FileIntentJournal {
10687
10766
  if (err.code === "ENOENT") return {};
10688
10767
  throw err;
10689
10768
  }
10690
- const invalid = (why) => new Error(`deposit-intent journal ${this.file} is not valid (${why})`);
10769
+ const invalid2 = (why) => new Error(`deposit-intent journal ${this.file} is not valid (${why})`);
10691
10770
  let parsed;
10692
10771
  try {
10693
10772
  parsed = JSON.parse(text);
10694
10773
  } catch (err) {
10695
- throw invalid(err instanceof Error ? err.message : String(err));
10774
+ throw invalid2(err instanceof Error ? err.message : String(err));
10696
10775
  }
10697
- if (!isPlainObject(parsed)) throw invalid("not a JSON object");
10698
- if (parsed.version !== 1) throw invalid(`unsupported version ${JSON.stringify(parsed.version)}`);
10776
+ if (!isPlainObject(parsed)) throw invalid2("not a JSON object");
10777
+ if (parsed.version !== 1) throw invalid2(`unsupported version ${JSON.stringify(parsed.version)}`);
10699
10778
  const { intents } = parsed;
10700
- if (!isPlainObject(intents)) throw invalid("intents is not an object");
10779
+ if (!isPlainObject(intents)) throw invalid2("intents is not an object");
10701
10780
  for (const [key, intent] of Object.entries(intents)) {
10702
10781
  const why = intentProblem(key, intent);
10703
- if (why) throw invalid(`intent ${JSON.stringify(key)}: ${why}`);
10782
+ if (why) throw invalid2(`intent ${JSON.stringify(key)}: ${why}`);
10704
10783
  }
10705
10784
  return intents;
10706
10785
  }
@@ -11580,6 +11659,14 @@ var SolanaBatchPayer = class {
11580
11659
  if (!Number.isFinite(this.lockWaitMs) || this.lockWaitMs < 0) {
11581
11660
  throw new Error("batch.lockWaitMs must be a finite number of ms >= 0");
11582
11661
  }
11662
+ this.onBusy = init.options.onBusy ?? "exact";
11663
+ if (this.onBusy !== "exact" && this.onBusy !== "wait" && this.onBusy !== "throw") {
11664
+ throw new Error('batch.onBusy must be "exact", "wait" or "throw"');
11665
+ }
11666
+ this.busyWaitMs = init.options.busyWaitMs ?? DEFAULT_BATCH_BUSY_WAIT_MS;
11667
+ if (!Number.isFinite(this.busyWaitMs) || this.busyWaitMs < 0) {
11668
+ throw new Error("batch.busyWaitMs must be a finite number of ms >= 0");
11669
+ }
11583
11670
  }
11584
11671
  init;
11585
11672
  state;
@@ -11588,6 +11675,8 @@ var SolanaBatchPayer = class {
11588
11675
  inDoubtMaxWaitMs;
11589
11676
  onLocked;
11590
11677
  lockWaitMs;
11678
+ onBusy;
11679
+ busyWaitMs;
11591
11680
  counters = {
11592
11681
  fallbacks: 0,
11593
11682
  fallbacksByReason: {},
@@ -12049,6 +12138,22 @@ var SolanaBatchPayer = class {
12049
12138
  });
12050
12139
  return { kind: "failed", error };
12051
12140
  }
12141
+ /**
12142
+ * `onBusy: "wait"`: look at the wallet every {@link BUSY_POLL_MS} until no
12143
+ * batch call holds it or `deadline` passes. True when it is free.
12144
+ */
12145
+ async waitWhileBusy(wallet, deadline) {
12146
+ while (wallet.busy) {
12147
+ const left = deadline - Date.now();
12148
+ if (left <= 0) return false;
12149
+ await sleep2(Math.min(BUSY_POLL_MS, left));
12150
+ }
12151
+ return true;
12152
+ }
12153
+ /** `onBusy` other than `"exact"`: the call's `"unpaid"` error, nothing signed. */
12154
+ async busyOut(waitedMs) {
12155
+ return { kind: "failed", error: new BatchChannelBusyError({ wallet: await this.init.address(), waitedMs }) };
12156
+ }
12052
12157
  /**
12053
12158
  * The close fence for a call about to send its first request: how many
12054
12159
  * closes this wallet has completed so far, to hand to {@link pay}.
@@ -12074,6 +12179,8 @@ var SolanaBatchPayer = class {
12074
12179
  const budget = { attempt: 1, waited: 0 };
12075
12180
  let waitedUntil = 0;
12076
12181
  let backedOff;
12182
+ let busySince;
12183
+ let rechallengeAfterBusy = false;
12077
12184
  let holding = false;
12078
12185
  let sent;
12079
12186
  const release = () => {
@@ -12109,7 +12216,8 @@ var SolanaBatchPayer = class {
12109
12216
  await sleep2(wait);
12110
12217
  continue;
12111
12218
  }
12112
- if (budget.attempt > 1 || budget.waited > 0) {
12219
+ if (budget.attempt > 1 || budget.waited > 0 || rechallengeAfterBusy) {
12220
+ rechallengeAfterBusy = false;
12113
12221
  let fresh;
12114
12222
  try {
12115
12223
  fresh = await rechallenge();
@@ -12137,7 +12245,28 @@ var SolanaBatchPayer = class {
12137
12245
  detail: "closeBatchChannel() closed this wallet's channel after this call started; it opens no channel"
12138
12246
  });
12139
12247
  }
12140
- if (wallet.busy) return fallback({ reason: "channel_busy", attempt: budget.attempt });
12248
+ if (wallet.busy) {
12249
+ if (this.onBusy === "exact") return fallback({ reason: "channel_busy", attempt: budget.attempt });
12250
+ const waited = busySince === void 0 ? 0 : Date.now() - busySince;
12251
+ if (this.onBusy === "throw") return this.busyOut(waited);
12252
+ if (busySince === void 0) {
12253
+ busySince = Date.now();
12254
+ if (this.busyWaitMs > 0) {
12255
+ await this.report({
12256
+ type: "backoff",
12257
+ reason: "channel_busy",
12258
+ retryAfterMs: this.busyWaitMs,
12259
+ attempt: budget.attempt,
12260
+ detail: 'another batch call for this wallet is in flight; waiting for it (onBusy: "wait")'
12261
+ });
12262
+ }
12263
+ }
12264
+ if (!await this.waitWhileBusy(wallet, busySince + this.busyWaitMs)) {
12265
+ return this.busyOut(Date.now() - busySince);
12266
+ }
12267
+ rechallengeAfterBusy = true;
12268
+ continue;
12269
+ }
12141
12270
  if (wallet.file && !holdsChannelFile(wallet.file)) {
12142
12271
  const detail = `this process no longer holds the lock on ${wallet.file}; another owner may be paying into its channels`;
12143
12272
  if (this.onLocked !== "exact") return this.lockedOut(detail, void 0, 0);
@@ -13762,6 +13891,22 @@ var SolanaLLMClient = class {
13762
13891
  const data = await this.requestWithPaymentRaw("/v1/search", body);
13763
13892
  return data;
13764
13893
  }
13894
+ /**
13895
+ * Typed judgments (OpenAI Decisions-compatible, `gpt-6-luna`), paid on
13896
+ * Solana: one typed answer per question instead of text. See
13897
+ * {@link LLMClient.decisions} for the request shape.
13898
+ *
13899
+ * Under `exact` the 402's quote settles (an upper-bound estimate of the
13900
+ * input tokens plus the $0.001 fee). With the `batch` option the call pays
13901
+ * with a channel voucher and is charged the input tokens the provider
13902
+ * reports, with no per-call fee; `costUsd` is that metered charge. It shares
13903
+ * the wallet's channel with chat, one batch call at a time.
13904
+ */
13905
+ async decisions(request) {
13906
+ const body = buildDecisionsBody(request);
13907
+ const response = await this.requestWithPayment("/v1/decisions", body);
13908
+ return response;
13909
+ }
13765
13910
  // ── Prediction Markets (Powered by Predexon) ────────────────────────────
13766
13911
  async pm(path7, params) {
13767
13912
  return this.getWithPaymentRaw(`/v1/pm/${path7}`, params);
@@ -14925,8 +15070,19 @@ var Chat = class {
14925
15070
  this.completions = new ChatCompletions(client, apiUrl, timeout);
14926
15071
  }
14927
15072
  };
15073
+ var Decisions = class {
15074
+ constructor(client) {
15075
+ this.client = client;
15076
+ }
15077
+ client;
15078
+ /** Same as {@link LLMClient.decisions}. */
15079
+ async create(params) {
15080
+ return this.client.decisions(params);
15081
+ }
15082
+ };
14928
15083
  var OpenAI = class {
14929
15084
  chat;
15085
+ decisions;
14930
15086
  get authMode() {
14931
15087
  return this.client.authMode;
14932
15088
  }
@@ -14943,6 +15099,7 @@ var OpenAI = class {
14943
15099
  timeout
14944
15100
  });
14945
15101
  this.chat = new Chat(this.client, apiUrl, timeout);
15102
+ this.decisions = new Decisions(this.client);
14946
15103
  }
14947
15104
  /**
14948
15105
  * Get the wallet address being used for payments.
@@ -15090,11 +15247,14 @@ export {
15090
15247
  AnthropicClient,
15091
15248
  BASE_CHAIN_ID,
15092
15249
  BLOCKRUN_SOL_OPERATOR,
15250
+ BatchChannelBusyError,
15093
15251
  BatchChannelLockedError,
15094
15252
  BatchCloseDeferredError,
15095
15253
  BatchPaymentUnresolvedError,
15096
15254
  BlockrunClient,
15097
15255
  BlockrunError,
15256
+ DECISIONS_DEFAULT_MODEL,
15257
+ DEFAULT_BATCH_BUSY_WAIT_MS,
15098
15258
  DEFAULT_BATCH_IN_DOUBT,
15099
15259
  DEFAULT_BATCH_LOCK_WAIT_MS,
15100
15260
  DEFAULT_BATCH_RATE_LIMIT,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/llm",
3
- "version": "4.2.1",
3
+ "version": "4.3.0",
4
4
  "type": "module",
5
5
  "description": "TypeScript SDK for BlockRun - every frontier model behind one OpenAI-compatible client. Pay with a BlockRun API key or per-call in USDC. Smart routing picks the cheapest capable model. No rate limits.",
6
6
  "main": "dist/index.cjs",