@usabledev/usable-chat 1.230.1 → 1.231.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.
Files changed (2) hide show
  1. package/cli.js +77 -12
  2. package/package.json +1 -1
package/cli.js CHANGED
@@ -28901,6 +28901,16 @@ function safeServingProvider(value) {
28901
28901
  function isRecord(value) {
28902
28902
  return typeof value === "object" && value !== null && !Array.isArray(value);
28903
28903
  }
28904
+ function providerPaymentRequiredFromStructuredBody(payload2) {
28905
+ if (!isRecord(payload2)) return false;
28906
+ const candidate = isRecord(payload2.error) ? payload2.error : payload2;
28907
+ const metadata2 = isRecord(candidate.metadata) ? candidate.metadata : void 0;
28908
+ return [metadata2?.error_type, candidate.type, candidate.code].some((field) => {
28909
+ if (field === 402) return true;
28910
+ if (typeof field !== "string") return false;
28911
+ return ["402", "payment_required", "insufficient_quota"].includes(field.trim().toLowerCase());
28912
+ });
28913
+ }
28904
28914
  function providerErrorCategoryFromStructuredBody(payload2) {
28905
28915
  if (!isRecord(payload2)) return void 0;
28906
28916
  const candidate = isRecord(payload2.error) ? payload2.error : payload2;
@@ -28918,7 +28928,7 @@ function providerErrorCategoryFromStatus(status) {
28918
28928
  }
28919
28929
  if (status >= 500 || status === 408) return "overload";
28920
28930
  if (status === 401 || status === 403) return "auth";
28921
- if (status === 429) return "quota";
28931
+ if (status === 402 || status === 429) return "quota";
28922
28932
  if (status === 404) return "deployment";
28923
28933
  return "schema";
28924
28934
  }
@@ -29167,7 +29177,8 @@ async function structuredErrorDetailsFromResponse(response) {
29167
29177
  const payload2 = JSON.parse(new TextDecoder().decode(bytes));
29168
29178
  return {
29169
29179
  category: providerErrorCategoryFromStructuredBody(payload2),
29170
- servingProvider: servingProviderFromPayload(payload2)
29180
+ servingProvider: servingProviderFromPayload(payload2),
29181
+ ...providerPaymentRequiredFromStructuredBody(payload2) ? { paymentRequired: true } : {}
29171
29182
  };
29172
29183
  } catch {
29173
29184
  return {};
@@ -29197,6 +29208,7 @@ function parseSseData(data, model, requestId2, attemptContext) {
29197
29208
  provider: "openrouter",
29198
29209
  kind: "stream-error",
29199
29210
  providerCode: typeof chunk2.error.code === "number" ? chunk2.error.code : void 0,
29211
+ ...providerPaymentRequiredFromStructuredBody(chunk2) ? { paymentRequired: true } : {},
29200
29212
  ...attemptMetadata(
29201
29213
  attemptContext,
29202
29214
  "failed",
@@ -29393,6 +29405,7 @@ async function callOpenRouter(apiKey, request, options2 = {}) {
29393
29405
  kind: "http-status",
29394
29406
  model: request.model,
29395
29407
  status: response.status,
29408
+ ...structured.paymentRequired ? { paymentRequired: true } : {},
29396
29409
  requestId: requestId2,
29397
29410
  ...attemptMetadata(
29398
29411
  attemptContext,
@@ -52971,7 +52984,7 @@ var init_model_registry = __esm({
52971
52984
  var version2;
52972
52985
  var init_package = __esm({
52973
52986
  "package.json"() {
52974
- version2 = "1.230.1";
52987
+ version2 = "1.231.0";
52975
52988
  }
52976
52989
  });
52977
52990
 
@@ -183072,8 +183085,8 @@ function providerAttemptAbortError(attempt) {
183072
183085
  return reason instanceof ProviderAttemptTimeoutError ? reason : new ProviderAttemptCancelledError();
183073
183086
  }
183074
183087
  function toSafeProviderFailure(error42) {
183075
- const { kind, category, status, requestId: requestId2, servingProvider } = error42.context;
183076
- return { kind, category, status, requestId: requestId2, servingProvider };
183088
+ const { kind, category, status, providerCode, paymentRequired, requestId: requestId2, servingProvider } = error42.context;
183089
+ return { kind, category, status, providerCode, ...paymentRequired ? { paymentRequired: true } : {}, requestId: requestId2, servingProvider };
183077
183090
  }
183078
183091
  function normalizeNativeProviderFailure(provider, error42) {
183079
183092
  if (isProviderError(error42)) return error42;
@@ -183095,12 +183108,14 @@ function normalizeNativeProviderFailure(provider, error42) {
183095
183108
  if (status && Number.isInteger(status) && status >= 100 && status <= 599) {
183096
183109
  const requestId2 = safeProviderIdentifier(candidate?.requestID);
183097
183110
  const structured = providerErrorCategoryFromStructuredBody(candidate?.error);
183098
- const category = status === 413 || structured === "context" ? "context" : providerErrorCategoryFromStatus(status) ?? "schema";
183111
+ const paymentRequired = providerPaymentRequiredFromStructuredBody(candidate?.error);
183112
+ const category = status === 413 || structured === "context" ? "context" : paymentRequired ? "quota" : providerErrorCategoryFromStatus(status) ?? "schema";
183099
183113
  return new ProviderError("Provider request failed.", {
183100
183114
  provider,
183101
183115
  kind: "http-status",
183102
183116
  status,
183103
183117
  category,
183118
+ ...paymentRequired ? { paymentRequired: true } : {},
183104
183119
  ...requestId2 ? { requestId: requestId2 } : {}
183105
183120
  });
183106
183121
  }
@@ -436891,6 +436906,8 @@ var init_gemini_wire = __esm({
436891
436906
  function providerHopTarget(error42) {
436892
436907
  const metadata2 = providerErrorMetadata(error42);
436893
436908
  if (!metadata2 || metadata2.kind === "aborted") return void 0;
436909
+ if (metadata2.status === 402 || metadata2.providerCode === 402 || metadata2.paymentRequired)
436910
+ return void 0;
436894
436911
  if (metadata2.category && REQUEST_SHAPED.has(metadata2.category)) return void 0;
436895
436912
  return safeServingProvider(metadata2.servingProvider);
436896
436913
  }
@@ -436900,6 +436917,8 @@ function isModelFallbackEligible(error42) {
436900
436917
  if (error42 instanceof ProviderRouteUnavailableError) return true;
436901
436918
  const metadata2 = providerErrorMetadata(error42);
436902
436919
  if (!metadata2 || metadata2.kind === "aborted") return false;
436920
+ if (metadata2.status === 402 || metadata2.providerCode === 402 || metadata2.paymentRequired)
436921
+ return false;
436903
436922
  if (metadata2.category) {
436904
436923
  return metadata2.category === "deployment" || metadata2.category === "overload" || metadata2.category === "transport" || metadata2.category === "quota";
436905
436924
  }
@@ -437063,6 +437082,26 @@ var init_openrouter_tool_format = __esm({
437063
437082
  });
437064
437083
 
437065
437084
  // src/lib/reasoning-config.ts
437085
+ function fitReasoningToOutputLimit(config3, maxTokens) {
437086
+ const reasoning = config3.providerOptions?.reasoning;
437087
+ if (!config3.enabled || reasoning?.max_tokens === void 0 || reasoning.max_tokens < maxTokens)
437088
+ return config3;
437089
+ if (maxTokens <= 1024) {
437090
+ return {
437091
+ ...config3,
437092
+ enabled: false,
437093
+ providerOptions: { ...config3.providerOptions, reasoning: void 0 }
437094
+ };
437095
+ }
437096
+ const budget = Math.min(reasoning.max_tokens, Math.max(1024, Math.floor(maxTokens / 2)));
437097
+ return {
437098
+ ...config3,
437099
+ providerOptions: {
437100
+ ...config3.providerOptions,
437101
+ reasoning: { ...reasoning, max_tokens: budget }
437102
+ }
437103
+ };
437104
+ }
437066
437105
  function getReasoningConfig(modelId, hasReasoningCapability = false, forceEnable = true, reasoningEffort) {
437067
437106
  if (reasoningEffort === void 0) {
437068
437107
  return { enabled: false };
@@ -516940,7 +516979,7 @@ async function callLLM({
516940
516979
  const candidate = error42;
516941
516980
  const status = typeof candidate.status === "number" ? candidate.status : typeof candidate.statusCode === "number" ? candidate.statusCode : void 0;
516942
516981
  if (status && Number.isInteger(status) && status >= 100 && status <= 599) {
516943
- const category = status >= 500 ? "overload" : status === 408 || status === 504 ? "transport" : status === 401 || status === 403 ? "auth" : status === 429 ? "quota" : status === 404 ? "deployment" : status >= 400 ? "schema" : void 0;
516982
+ const category = status >= 500 ? "overload" : status === 408 || status === 504 ? "transport" : status === 401 || status === 403 ? "auth" : status === 402 || status === 429 ? "quota" : status === 404 ? "deployment" : status >= 400 ? "schema" : void 0;
516944
516983
  return new ProviderError("Provider request failed.", {
516945
516984
  provider,
516946
516985
  kind: "http-status",
@@ -516994,6 +517033,8 @@ async function callLLM({
516994
517033
  category
516995
517034
  } : {},
516996
517035
  ...typeof failure.status === "number" ? { status: failure.status } : {},
517036
+ ...typeof failure.providerCode === "number" ? { providerCode: failure.providerCode } : {},
517037
+ ...failure.paymentRequired === true ? { paymentRequired: true } : {},
516997
517038
  ...requestId2 ? { requestId: requestId2 } : {},
516998
517039
  ...safeServingProvider(failure.servingProvider) ? { servingProvider: safeServingProvider(failure.servingProvider) } : {}
516999
517040
  });
@@ -520549,7 +520590,14 @@ Re-read them (working_memory on web, bash on the CLI \u2014 grep/sed projection,
520549
520590
  const systemPromptTokens = systemMessage ? countTokens(systemMessage) : 0;
520550
520591
  const inputTokens = preflightTokenCount.total + systemPromptTokens + toolDefTokens;
520551
520592
  const dynamicMaxTokens = calculateMaxOutputTokens(selectedModelId, inputTokens);
520552
- let maxTokens = recommendedMaxTokens || dynamicMaxTokens;
520593
+ const configuredMaxTokens = config3.maxTokens;
520594
+ if (configuredMaxTokens !== void 0 && (!Number.isSafeInteger(configuredMaxTokens) || configuredMaxTokens <= 0)) {
520595
+ throw new Error("maxTokens must be a positive integer.");
520596
+ }
520597
+ let maxTokens = Math.min(
520598
+ recommendedMaxTokens || dynamicMaxTokens,
520599
+ configuredMaxTokens ?? Infinity
520600
+ );
520553
520601
  const modelFromRegistry = getModelById(selectedModelId);
520554
520602
  const contextLength = modelFromRegistry?.capabilities.contextLength || 128e3;
520555
520603
  const contextUsagePercent = inputTokens / contextLength * 100;
@@ -520602,6 +520650,7 @@ Re-read them (working_memory on web, bash on the CLI \u2014 grep/sed projection,
520602
520650
  while (true) {
520603
520651
  let overflowMessage;
520604
520652
  try {
520653
+ const attemptReasoningConfig = fitReasoningToOutputLimit(reasoningConfig, maxTokens);
520605
520654
  if (!config3.__scriptedLlm) {
520606
520655
  await authorizeCreditBeforeProvider(context3.creditAuthorization, {
520607
520656
  inputTokens,
@@ -520615,7 +520664,7 @@ Re-read them (working_memory on web, bash on the CLI \u2014 grep/sed projection,
520615
520664
  systemMessage,
520616
520665
  tools,
520617
520666
  shouldEnableTools: shouldEnableTools ?? false,
520618
- reasoningConfig,
520667
+ reasoningConfig: attemptReasoningConfig,
520619
520668
  reasoningEffort: config3.reasoningEffort,
520620
520669
  maxTokens,
520621
520670
  temperature: config3.temperature ?? 0.7,
@@ -520957,6 +521006,16 @@ Continue once without hiding or replacing your prior response.`
520957
521006
  });
520958
521007
  break;
520959
521008
  }
521009
+ if (result.finishReason === "length") {
521010
+ multiplexer.send(
521011
+ emitter.emit("error", {
521012
+ message: "The response reached its output token limit and may be incomplete. Please try a shorter request.",
521013
+ code: "OUTPUT_TOKEN_LIMIT",
521014
+ recoverable: false
521015
+ })
521016
+ );
521017
+ break;
521018
+ }
520960
521019
  if (result.finishReason === "max_tokens") {
520961
521020
  orchestrationLogger.warn(
520962
521021
  "Model hit max_tokens limit. Attempting to recover and continue...",
@@ -520981,6 +521040,8 @@ Continue once without hiding or replacing your prior response.`
520981
521040
  }
520982
521041
  }
520983
521042
  if (result.finishReason === "error") {
521043
+ const failure = "providerFailure" in result ? result.providerFailure : void 0;
521044
+ const paymentRequired = failure?.status === 402 || failure?.providerCode === 402 || failure?.paymentRequired === true;
520984
521045
  orchestrationLogger.warn("Provider interrupted turn; preserving observed state", {
520985
521046
  step: currentStep,
520986
521047
  model: selectedModelId,
@@ -520990,8 +521051,8 @@ Continue once without hiding or replacing your prior response.`
520990
521051
  interrupted: result.interrupted === true
520991
521052
  });
520992
521053
  const interruptionEvent = emitter.emit("error", {
520993
- message: "The AI provider interrupted this response. Completed work will not be automatically repeated.",
520994
- code: "PROVIDER_INTERRUPTED",
521054
+ message: paymentRequired ? "The AI provider could not complete this response because its credit or payment limit was reached." : "The AI provider interrupted this response. Completed work will not be automatically repeated.",
521055
+ code: paymentRequired ? "PROVIDER_PAYMENT_REQUIRED" : "PROVIDER_INTERRUPTED",
520995
521056
  recoverable: false
520996
521057
  });
520997
521058
  multiplexer.send(interruptionEvent);
@@ -521423,6 +521484,7 @@ Continue once without hiding or replacing your prior response.`
521423
521484
  }
521424
521485
  const isProviderPolicyError = error42 instanceof ProviderPolicyError;
521425
521486
  const providerFailure = providerErrorMetadata(error42);
521487
+ const isProviderPaymentError = providerFailure?.status === 402 || providerFailure?.providerCode === 402 || providerFailure?.paymentRequired === true;
521426
521488
  orchestrationLogger.error("orchestration_generation_failed", {
521427
521489
  code: isProviderPolicyError ? "POLICY_COMPLIANT_ROUTE_REQUIRED" : safeProviderErrorCategory(providerFailure?.category) ?? "orchestration-error"
521428
521490
  });
@@ -521448,6 +521510,9 @@ Continue once without hiding or replacing your prior response.`
521448
521510
  }
521449
521511
  } catch {
521450
521512
  }
521513
+ if (isProviderPaymentError) {
521514
+ errorMessage = "The AI provider could not complete this response because its credit or payment limit was reached.";
521515
+ }
521451
521516
  if (conversationId) {
521452
521517
  try {
521453
521518
  const allPaths = bash.fs.getAllPaths();
@@ -521478,7 +521543,7 @@ Continue once without hiding or replacing your prior response.`
521478
521543
  }
521479
521544
  }
521480
521545
  const rawErrorCode = error42?.code;
521481
- const errorCode = isProviderPolicyError ? "POLICY_COMPLIANT_ROUTE_REQUIRED" : rawErrorCode === "CONTEXT_TOO_LARGE" || rawErrorCode === "MEMBER_CAP_EXCEEDED" || rawErrorCode === "CREDIT_LIMIT_REACHED" || rawErrorCode === "CREDIT_OVERAGE_CAP_REACHED" || rawErrorCode === "CREDIT_PREFLIGHT_UNAVAILABLE" ? rawErrorCode : "ORCHESTRATION_ERROR";
521546
+ const errorCode = isProviderPolicyError ? "POLICY_COMPLIANT_ROUTE_REQUIRED" : isProviderPaymentError ? "PROVIDER_PAYMENT_REQUIRED" : rawErrorCode === "CONTEXT_TOO_LARGE" || rawErrorCode === "MEMBER_CAP_EXCEEDED" || rawErrorCode === "CREDIT_LIMIT_REACHED" || rawErrorCode === "CREDIT_OVERAGE_CAP_REACHED" || rawErrorCode === "CREDIT_PREFLIGHT_UNAVAILABLE" ? rawErrorCode : "ORCHESTRATION_ERROR";
521482
521547
  const errorEvent = emitter.emit("error", {
521483
521548
  message: errorMessage,
521484
521549
  code: errorCode,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usabledev/usable-chat",
3
- "version": "1.230.1",
3
+ "version": "1.231.0",
4
4
  "description": "usable-chat — terminal harness for usable-chat (headless + TUI)",
5
5
  "type": "module",
6
6
  "bin": {