@appilots/sdk 0.5.0 → 0.6.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.
@@ -1,4 +1,4 @@
1
- import { useAppilotsContext, setNavigationRef, setCurrentScreen } from './chunk-BIEF6MNR.mjs';
1
+ import { useAppilotsContext, setNavigationRef, setCurrentScreen } from './chunk-R4D34FEW.mjs';
2
2
  import React, { useRef, useCallback, useEffect } from 'react';
3
3
 
4
4
  function getActiveRouteName(state) {
@@ -42,6 +42,21 @@ var StreamAbortError = class extends Error {
42
42
  this.partialContent = partialContent;
43
43
  }
44
44
  };
45
+ var RateLimitedError = class extends Error {
46
+ retryAfterSeconds;
47
+ constructor(message, retryAfterSeconds) {
48
+ super(message);
49
+ this.name = "RateLimitedError";
50
+ this.retryAfterSeconds = retryAfterSeconds;
51
+ }
52
+ };
53
+ function parseRetryAfter(...candidates) {
54
+ for (const candidate of candidates) {
55
+ const seconds = Number(candidate);
56
+ if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds);
57
+ }
58
+ return 60;
59
+ }
45
60
  var CONTINUATION_TIMEOUT_MS = 15e4;
46
61
  var AppilotsClient = class {
47
62
  baseUrl;
@@ -106,6 +121,15 @@ var AppilotsClient = class {
106
121
  }
107
122
  if (!response.ok) {
108
123
  const errorMsg = json?.error?.message ?? json?.error ?? `HTTP ${response.status}`;
124
+ if (response.status === 429) {
125
+ throw new RateLimitedError(
126
+ errorMsg,
127
+ parseRetryAfter(
128
+ json?.error?.retryAfterSeconds,
129
+ response.headers?.get?.("retry-after")
130
+ )
131
+ );
132
+ }
109
133
  throw new Error(errorMsg);
110
134
  }
111
135
  return json.data ?? json;
@@ -350,11 +374,25 @@ var AppilotsClient = class {
350
374
  const contentType = String(xhr.getResponseHeader?.("content-type") ?? "");
351
375
  if (xhr.status !== 200 || !contentType.includes("text/event-stream")) {
352
376
  let message2 = `HTTP ${xhr.status || 0}`;
377
+ let retryAfterSeconds;
353
378
  try {
354
379
  const json = JSON.parse(xhr.responseText || "{}");
355
380
  message2 = json?.error?.message ?? json?.error ?? message2;
381
+ retryAfterSeconds = json?.error?.retryAfterSeconds;
356
382
  } catch {
357
383
  }
384
+ if (xhr.status === 429) {
385
+ fail(
386
+ new RateLimitedError(
387
+ message2,
388
+ parseRetryAfter(
389
+ retryAfterSeconds,
390
+ xhr.getResponseHeader?.("retry-after")
391
+ )
392
+ )
393
+ );
394
+ return;
395
+ }
358
396
  fail(
359
397
  sawAnyEvent ? new Error(message2) : new StreamTransportError(message2)
360
398
  );
@@ -942,25 +980,41 @@ function detectLocaleFromUserTexts(texts) {
942
980
  var copy = {
943
981
  pt: {
944
982
  rateLimit: "O provedor de IA atingiu o limite de uso durante a automa\xE7\xE3o. Aguarde um momento e pe\xE7a para continuar, ou aumente o limite de tokens por minuto.",
983
+ platformRateLimit: (wait) => `Recebi pedidos demais em pouco tempo e precisei pausar. Tente de novo em ${wait}.`,
945
984
  invalidInput: "N\xE3o consegui continuar a automa\xE7\xE3o por um problema interno de sincroniza\xE7\xE3o. Pode tentar de novo ou fazer essa parte manualmente?",
946
985
  generic: (detail) => `Perdi o fio da automa\xE7\xE3o (${detail}). Pode continuar manualmente ou me pedir de novo?`
947
986
  },
948
987
  es: {
949
988
  rateLimit: "El proveedor de IA alcanz\xF3 su l\xEDmite de uso durante la automatizaci\xF3n. Espera un momento y p\xEDdeme continuar, o aumenta el l\xEDmite de tokens por minuto.",
989
+ platformRateLimit: (wait) => `Recib\xED demasiadas solicitudes en poco tiempo y tuve que pausar. Int\xE9ntalo de nuevo en ${wait}.`,
950
990
  invalidInput: "No pude continuar la automatizaci\xF3n por un problema interno de sincronizaci\xF3n. \xBFPuedes intentarlo de nuevo o hacer esta parte manualmente?",
951
991
  generic: (detail) => `Perd\xED el hilo de la automatizaci\xF3n (${detail}). \xBFPuedes continuar manualmente o ped\xEDrmelo de nuevo?`
952
992
  },
953
993
  fr: {
954
994
  rateLimit: "Le fournisseur d'IA a atteint sa limite d'utilisation pendant l'automatisation. Attendez un instant et demandez-moi de continuer, ou augmentez la limite de tokens par minute.",
995
+ platformRateLimit: (wait) => `J'ai re\xE7u trop de demandes en peu de temps et j'ai d\xFB faire une pause. R\xE9essayez dans ${wait}.`,
955
996
  invalidInput: "Je n'ai pas pu poursuivre l'automatisation \xE0 cause d'un probl\xE8me interne de synchronisation. Pouvez-vous r\xE9essayer ou faire cette \xE9tape manuellement ?",
956
997
  generic: (detail) => `J'ai perdu le fil de l'automatisation (${detail}). Vous pouvez continuer manuellement ou me redemander ?`
957
998
  },
958
999
  en: {
959
1000
  rateLimit: "Your AI provider hit its rate limit during automation. Wait a moment and ask me to continue, or raise your TPM limit.",
1001
+ platformRateLimit: (wait) => `I got too many requests in a short time and had to pause. Try again in ${wait}.`,
960
1002
  invalidInput: "I could not continue the automation because of an internal sync issue. You can try again or take over manually.",
961
1003
  generic: (detail) => `I lost my footing during automation (${detail}). You can take over from here.`
962
1004
  }
963
1005
  };
1006
+ var waitPhrase = {
1007
+ pt: (s) => s < 90 ? `${Math.ceil(s)} segundos` : `cerca de ${Math.ceil(s / 60)} minutos`,
1008
+ es: (s) => s < 90 ? `${Math.ceil(s)} segundos` : `unos ${Math.ceil(s / 60)} minutos`,
1009
+ fr: (s) => s < 90 ? `${Math.ceil(s)} secondes` : `environ ${Math.ceil(s / 60)} minutes`,
1010
+ en: (s) => s < 90 ? `${Math.ceil(s)} seconds` : `about ${Math.ceil(s / 60)} minutes`
1011
+ };
1012
+ function buildRateLimitedMessage(retryAfterSeconds, recentUserTexts) {
1013
+ const locale = detectLocaleFromUserTexts(recentUserTexts);
1014
+ const strings = copy[locale] ?? copy.en;
1015
+ const seconds = Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0 ? retryAfterSeconds : 60;
1016
+ return strings.platformRateLimit(waitPhrase[locale](seconds));
1017
+ }
964
1018
  function buildContinuationFailureMessage(rawError, recentUserTexts) {
965
1019
  const locale = detectLocaleFromUserTexts(recentUserTexts);
966
1020
  const strings = copy[locale] ?? copy.en;
@@ -1564,7 +1618,7 @@ var ChatSessionMachine = class {
1564
1618
  const raw = err instanceof Error ? err.message : "Continuation failed";
1565
1619
  this.warn("ChatSessionMachine: continuation failed \u2014", raw);
1566
1620
  const recentUserTexts = this.state.messages.filter((m) => m.role === "user").slice(-4).map((m) => m.content);
1567
- const friendly = buildContinuationFailureMessage(raw, recentUserTexts);
1621
+ const friendly = err instanceof RateLimitedError ? buildRateLimitedMessage(err.retryAfterSeconds, recentUserTexts) : buildContinuationFailureMessage(raw, recentUserTexts);
1568
1622
  this.addAssistantMessage({
1569
1623
  id: `error_${++this.messageIdCounter}`,
1570
1624
  role: "assistant",
@@ -1726,6 +1780,17 @@ var ChatSessionMachine = class {
1726
1780
  removeStreamingPlaceholder();
1727
1781
  const errorMessage = err instanceof Error ? err.message : "Failed to send message";
1728
1782
  this.setState({ error: errorMessage });
1783
+ if (err instanceof RateLimitedError) {
1784
+ const recentUserTexts = this.state.messages.filter((m) => m.role === "user").slice(-4).map((m) => m.content);
1785
+ this.addAssistantMessage({
1786
+ id: `error_${++this.messageIdCounter}`,
1787
+ role: "assistant",
1788
+ content: buildRateLimitedMessage(err.retryAfterSeconds, recentUserTexts),
1789
+ timestamp: Date.now()
1790
+ });
1791
+ this.setState({ isLoading: false, loadingStatusKey: "thinking" });
1792
+ return;
1793
+ }
1729
1794
  this.addAssistantMessage({
1730
1795
  id: `error_${++this.messageIdCounter}`,
1731
1796
  role: "assistant",
@@ -4333,6 +4398,7 @@ exports.AppilotsProvider = AppilotsProvider;
4333
4398
  exports.AppilotsRegistryProvider = AppilotsRegistryProvider;
4334
4399
  exports.ChatSessionMachine = ChatSessionMachine;
4335
4400
  exports.OPTIONAL_STEP_AUTOMATION_HINT = OPTIONAL_STEP_AUTOMATION_HINT;
4401
+ exports.RateLimitedError = RateLimitedError;
4336
4402
  exports.SDK_VERSION = SDK_VERSION;
4337
4403
  exports._patchJsxRuntimes = _patchJsxRuntimes;
4338
4404
  exports.actionPressTargetId = actionPressTargetId;