@bastani/atomic-ai 0.9.90 → 0.10.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 (84) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/api/anthropic-messages.d.ts.map +1 -1
  3. package/dist/api/anthropic-messages.js +12 -9
  4. package/dist/api/anthropic-messages.js.map +1 -1
  5. package/dist/api/azure-openai-responses.d.ts.map +1 -1
  6. package/dist/api/azure-openai-responses.js +6 -4
  7. package/dist/api/azure-openai-responses.js.map +1 -1
  8. package/dist/api/classifier-shared.d.ts.map +1 -1
  9. package/dist/api/classifier-shared.js +4 -3
  10. package/dist/api/classifier-shared.js.map +1 -1
  11. package/dist/api/google-generative-ai.d.ts.map +1 -1
  12. package/dist/api/google-generative-ai.js +6 -3
  13. package/dist/api/google-generative-ai.js.map +1 -1
  14. package/dist/api/google-shared.d.ts +2 -1
  15. package/dist/api/google-shared.d.ts.map +1 -1
  16. package/dist/api/google-shared.js +3 -2
  17. package/dist/api/google-shared.js.map +1 -1
  18. package/dist/api/google-vertex.d.ts.map +1 -1
  19. package/dist/api/google-vertex.js +8 -4
  20. package/dist/api/google-vertex.js.map +1 -1
  21. package/dist/api/llama-cpp-classify.d.ts.map +1 -1
  22. package/dist/api/llama-cpp-classify.js +6 -4
  23. package/dist/api/llama-cpp-classify.js.map +1 -1
  24. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  25. package/dist/api/openai-codex-responses.js +9 -16
  26. package/dist/api/openai-codex-responses.js.map +1 -1
  27. package/dist/api/openai-completions.d.ts.map +1 -1
  28. package/dist/api/openai-completions.js +34 -6
  29. package/dist/api/openai-completions.js.map +1 -1
  30. package/dist/api/openai-decisions.d.ts.map +1 -1
  31. package/dist/api/openai-decisions.js +2 -1
  32. package/dist/api/openai-decisions.js.map +1 -1
  33. package/dist/api/openai-images.d.ts.map +1 -1
  34. package/dist/api/openai-images.js +6 -4
  35. package/dist/api/openai-images.js.map +1 -1
  36. package/dist/api/openai-responses.d.ts.map +1 -1
  37. package/dist/api/openai-responses.js +6 -4
  38. package/dist/api/openai-responses.js.map +1 -1
  39. package/dist/api/openrouter-images.d.ts.map +1 -1
  40. package/dist/api/openrouter-images.js +6 -4
  41. package/dist/api/openrouter-images.js.map +1 -1
  42. package/dist/api/simple-options.d.ts.map +1 -1
  43. package/dist/api/simple-options.js +1 -0
  44. package/dist/api/simple-options.js.map +1 -1
  45. package/dist/api/system-one-shared.d.ts.map +1 -1
  46. package/dist/api/system-one-shared.js +2 -1
  47. package/dist/api/system-one-shared.js.map +1 -1
  48. package/dist/index.d.ts +1 -0
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1 -0
  51. package/dist/index.js.map +1 -1
  52. package/dist/providers/data/.manifest.json +1 -1
  53. package/dist/providers/data/amazon-bedrock.json +1 -1
  54. package/dist/providers/data/fireworks.json +1 -1
  55. package/dist/providers/data/opencode.json +1 -1
  56. package/dist/providers/data/openrouter.json +1 -1
  57. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  58. package/dist/providers/github-copilot-stop-reason.d.ts +14 -0
  59. package/dist/providers/github-copilot-stop-reason.d.ts.map +1 -0
  60. package/dist/providers/github-copilot-stop-reason.js +27 -0
  61. package/dist/providers/github-copilot-stop-reason.js.map +1 -0
  62. package/dist/types.d.ts +11 -0
  63. package/dist/types.d.ts.map +1 -1
  64. package/dist/types.js.map +1 -1
  65. package/dist/utils/provider-retry.d.ts +20 -1
  66. package/dist/utils/provider-retry.d.ts.map +1 -1
  67. package/dist/utils/provider-retry.js +46 -19
  68. package/dist/utils/provider-retry.js.map +1 -1
  69. package/dist/utils/retry-sleep.d.ts +10 -0
  70. package/dist/utils/retry-sleep.d.ts.map +1 -0
  71. package/dist/utils/retry-sleep.js +38 -0
  72. package/dist/utils/retry-sleep.js.map +1 -0
  73. package/dist/utils/retry.d.ts +6 -2
  74. package/dist/utils/retry.d.ts.map +1 -1
  75. package/dist/utils/retry.js +9 -1
  76. package/dist/utils/retry.js.map +1 -1
  77. package/dist/utils/sse.d.ts +11 -0
  78. package/dist/utils/sse.d.ts.map +1 -1
  79. package/dist/utils/sse.js +131 -0
  80. package/dist/utils/sse.js.map +1 -1
  81. package/dist/utils/version.d.ts +1 -1
  82. package/dist/utils/version.js +1 -1
  83. package/dist/utils/version.js.map +1 -1
  84. package/package.json +3 -3
@@ -0,0 +1,10 @@
1
+ import type { RetryDeadline } from "../types.ts";
2
+ /** Refuse an expired retry and let the timer owner deliver its usual timeout before returning. */
3
+ export declare function retryDeadlineReached(deadline: RetryDeadline | undefined): boolean;
4
+ /** Distinguish a refused retry from an unrelated provider error when no abort event has fired. */
5
+ export declare class RetryDeadlineError extends Error {
6
+ constructor(message?: string);
7
+ }
8
+ /** Resolve directly from the backoff timer; ordinary retries must not yield to other due timers. */
9
+ export declare function sleepForRetry(ms: number, signal: AbortSignal | undefined, abortError: () => Error): Promise<void>;
10
+ //# sourceMappingURL=retry-sleep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry-sleep.d.ts","sourceRoot":"","sources":["../../src/utils/retry-sleep.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,kGAAkG;AAClG,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,aAAa,GAAG,SAAS,GAAG,OAAO,CAKjF;AAED,kGAAkG;AAClG,qBAAa,kBAAmB,SAAQ,KAAK;IAC5C,YAAY,OAAO,SAAoB,EAGtC;CACD;AAED,oGAAoG;AACpG,wBAAgB,aAAa,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBjH"}
@@ -0,0 +1,38 @@
1
+ /** Refuse an expired retry and let the timer owner deliver its usual timeout before returning. */
2
+ export function retryDeadlineReached(deadline) {
3
+ const at = typeof deadline === "number" ? deadline : deadline?.at;
4
+ if (typeof at !== "number" || !(performance.now() >= at))
5
+ return false;
6
+ if (typeof deadline === "object")
7
+ deadline.onExpired();
8
+ return true;
9
+ }
10
+ /** Distinguish a refused retry from an unrelated provider error when no abort event has fired. */
11
+ export class RetryDeadlineError extends Error {
12
+ constructor(message = "Request aborted") {
13
+ super(message);
14
+ this.name = "AbortError";
15
+ }
16
+ }
17
+ /** Resolve directly from the backoff timer; ordinary retries must not yield to other due timers. */
18
+ export function sleepForRetry(ms, signal, abortError) {
19
+ if (!signal)
20
+ return new Promise((resolve) => setTimeout(resolve, ms));
21
+ return new Promise((resolve, reject) => {
22
+ if (signal.aborted) {
23
+ reject(abortError());
24
+ return;
25
+ }
26
+ const finish = () => {
27
+ signal.removeEventListener("abort", onAbort);
28
+ resolve();
29
+ };
30
+ const timer = setTimeout(finish, ms);
31
+ const onAbort = () => {
32
+ clearTimeout(timer);
33
+ reject(abortError());
34
+ };
35
+ signal.addEventListener("abort", onAbort, { once: true });
36
+ });
37
+ }
38
+ //# sourceMappingURL=retry-sleep.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry-sleep.js","sourceRoot":"","sources":["../../src/utils/retry-sleep.ts"],"names":[],"mappings":"AAEA,kGAAkG;AAClG,MAAM,UAAU,oBAAoB,CAAC,QAAmC;IACvE,MAAM,EAAE,GAAG,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC;IAClE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,WAAW,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;QAAE,OAAO,KAAK,CAAC;IACvE,IAAI,OAAO,QAAQ,KAAK,QAAQ;QAAE,QAAQ,CAAC,SAAS,EAAE,CAAC;IACvD,OAAO,IAAI,CAAC;AACb,CAAC;AAED,kGAAkG;AAClG,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAC5C,YAAY,OAAO,GAAG,iBAAiB;QACtC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;IAC1B,CAAC;CACD;AAED,oGAAoG;AACpG,MAAM,UAAU,aAAa,CAAC,EAAU,EAAE,MAA+B,EAAE,UAAuB;IACjG,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;IACtE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;YACrB,OAAO;QACR,CAAC;QACD,MAAM,MAAM,GAAG,GAAG,EAAE;YACnB,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC7C,OAAO,EAAE,CAAC;QACX,CAAC,CAAC;QACF,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACrC,MAAM,OAAO,GAAG,GAAG,EAAE;YACpB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;QACtB,CAAC,CAAC;QACF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3D,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { RetryDeadline } from \"../types.ts\";\n\n/** Refuse an expired retry and let the timer owner deliver its usual timeout before returning. */\nexport function retryDeadlineReached(deadline: RetryDeadline | undefined): boolean {\n\tconst at = typeof deadline === \"number\" ? deadline : deadline?.at;\n\tif (typeof at !== \"number\" || !(performance.now() >= at)) return false;\n\tif (typeof deadline === \"object\") deadline.onExpired();\n\treturn true;\n}\n\n/** Distinguish a refused retry from an unrelated provider error when no abort event has fired. */\nexport class RetryDeadlineError extends Error {\n\tconstructor(message = \"Request aborted\") {\n\t\tsuper(message);\n\t\tthis.name = \"AbortError\";\n\t}\n}\n\n/** Resolve directly from the backoff timer; ordinary retries must not yield to other due timers. */\nexport function sleepForRetry(ms: number, signal: AbortSignal | undefined, abortError: () => Error): Promise<void> {\n\tif (!signal) return new Promise((resolve) => setTimeout(resolve, ms));\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal.aborted) {\n\t\t\treject(abortError());\n\t\t\treturn;\n\t\t}\n\t\tconst finish = () => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t};\n\t\tconst timer = setTimeout(finish, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(abortError());\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { AssistantMessage } from "../types.ts";
1
+ import type { AssistantMessage, RetryDeadline } from "../types.ts";
2
2
  /**
3
3
  * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).
4
4
  * Each delay is capped by `maxAgentDelayMs` (60 seconds by default).
@@ -42,6 +42,10 @@ export interface RetryCallbacks {
42
42
  /** Emitted once when the loop ends: success if a later call completed normally. */
43
43
  onRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;
44
44
  }
45
+ export interface RetryCallOptions extends RetryCallbacks {
46
+ /** Do not start a retry at or after this performance.now() timestamp. Does not cancel a running call. */
47
+ retryDeadline?: RetryDeadline;
48
+ }
45
49
  /**
46
50
  * Run a single assistant-producing call with bounded retry on transient errors.
47
51
  *
@@ -61,7 +65,7 @@ export interface RetryCallbacks {
61
65
  * When `policy` is undefined or disabled, the first response is returned unchanged
62
66
  * (equivalent to calling `produce()` directly).
63
67
  */
64
- export declare function retryAssistantCall(produce: () => Promise<AssistantMessage>, policy: RetryPolicy | undefined, signal: AbortSignal | undefined, callbacks?: RetryCallbacks): Promise<AssistantMessage>;
68
+ export declare function retryAssistantCall(produce: () => Promise<AssistantMessage>, policy: RetryPolicy | undefined, signal: AbortSignal | undefined, callbacks?: RetryCallOptions): Promise<AssistantMessage>;
65
69
  /**
66
70
  * Classifies whether a failed assistant message looks like a transient provider
67
71
  * or transport error, so callers can decide if the last assistant turn should be
@@ -1 +1 @@
1
- {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAyIpD;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,qFAAqF;IACrF,UAAU,EAAE,MAAM,CAAC;IACnB,0FAA0F;IAC1F,WAAW,EAAE,MAAM,CAAC;IACpB,sEAAsE;IACtE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,eAAO,MAAM,gCAAgC,QAAS,CAAC;AAEvD,wBAAgB,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,aAAa,GAAG,iBAAiB,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAIlH;AAED,KAAK,YAAY,GAAG,IAAI,CAAC,gBAAgB,EAAE,YAAY,GAAG,cAAc,GAAG,cAAc,GAAG,aAAa,CAAC,CAAC;AAE3G;;;GAGG;AACH,wBAAgB,mBAAmB,CAClC,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,aAAa,GAAG,iBAAiB,GAAG,iBAAiB,CAAC,EAChF,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,IAAI,CAAC,gBAAgB,EAAE,cAAc,CAAC,GAC7C,MAAM,CAMR;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,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CAAC,EAAE,aAAa,CAAC;CAC9B;AA0BD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,kBAAkB,CACvC,OAAO,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,EACxC,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,SAAS,CAAC,EAAE,gBAAgB,GAC1B,OAAO,CAAC,gBAAgB,CAAC,CAkD3B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAOxE"}
@@ -1,5 +1,6 @@
1
1
  import { getGitHubCopilotError } from "../providers/github-copilot-errors.js";
2
2
  import { DEFAULT_MAX_RETRY_DELAY_MS } from "./provider-retry.js";
3
+ import { retryDeadlineReached } from "./retry-sleep.js";
3
4
  function buildProviderErrorPattern(patterns) {
4
5
  return new RegExp(patterns.join("|"), "i");
5
6
  }
@@ -223,7 +224,14 @@ export async function retryAssistantCall(produce, policy, signal, callbacks) {
223
224
  }
224
225
  throw error;
225
226
  }
226
- await callbacks?.onRetryAttemptStart?.();
227
+ if (!retryDeadlineReached(callbacks?.retryDeadline)) {
228
+ await callbacks?.onRetryAttemptStart?.();
229
+ // The callback can itself wait past the deadline.
230
+ if (!retryDeadlineReached(callbacks?.retryDeadline))
231
+ continue;
232
+ }
233
+ await callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);
234
+ return { ...response, stopReason: "aborted", errorMessage: undefined };
227
235
  }
228
236
  }
229
237
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AAEjE,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,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,eAAe,EAAE,CAAC;QAChF,MAAM,SAAS,EAAE,gBAAgB,EAAE,CAAC,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;QAE3F,8EAA8E;QAC9E,qFAAqF;QACrF,IAAI,CAAC;YACJ,MAAM,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,SAAS,EAAE,eAAe,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;YAC3E,IAAI,KAAK,YAAY,oBAAoB,EAAE,CAAC;gBAC3C,OAAO,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;YACxE,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;QACD,MAAM,SAAS,EAAE,mBAAmB,EAAE,EAAE,CAAC;IAC1C,CAAC;AACF,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB;IAC9D,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;QAAE,OAAO,KAAK,CAAC;IAC1E,MAAM,YAAY,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;IACpD,IAAI,YAAY,KAAK,SAAS;QAAE,OAAO,YAAY,CAAC,SAAS,CAAC;IAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC1C,IAAI,0CAA0C,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IAChF,OAAO,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import { getGitHubCopilotError } from \"../providers/github-copilot-errors.ts\";\nimport type { AssistantMessage } from \"../types.ts\";\nimport { DEFAULT_MAX_RETRY_DELAY_MS } from \"./provider-retry.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\t\"subscription_sharing_usage_limit_exceeded\",\n\t// Sign in with ChatGPT on a ChatGPT Business plan: a usage limit set by the\n\t// workspace admin. Only the admin can raise it.\n\t\"subscription_sharing_workplace_individual_usage_limit_exceeded\",\n\n\t// Zhipu/Z.ai (open.bigmodel.cn) error code 1308: the plan's usage limit is\n\t// reached, sent as HTTP 429. It resets after hours, not seconds (#11537).\n\t'\"code\"\\\\s*:\\\\s*\"?1308(?![0-9])',\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"server_busy\",\n\t\"servers are currently busy\",\n\t\"currently experiencing high demand\",\n\t\"model is at capacity\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t// Status codes must not be part of a longer word or number, e.g. a request id or byte count (#11057).\n\t// 521-523 are Cloudflare origin errors (#3623); 529 is an overload response.\n\t\"(?<![a-z0-9])(?:429|500|502|503|504|52[0-4]|529)(?![a-z0-9])\",\n\t// Also matches \"The service is temporarily unavailable\" (#10965).\n\t\"service.?(?:is.?)?(?:temporarily.?)?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?(?:an.?)?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\t\"unable to forward upstream\",\n\t\"upstream.?request.?failed\",\n\t\"upstream_stream_read_error\",\n\t\"stream was interrupted\",\n\t\"http/?2 stream failed\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"connection.?closed\",\n\t\"(?<![a-z0-9_])(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|ETIMEDOUT|EPIPE)(?![a-z0-9_])\",\n\t\"connection reset by peer\",\n\t\"connection.?reset\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"request to \\\\S+ failed, reason:\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Response-body decompression failures. Node/Bun zlib rejects a body whose\n\t// Content-Encoding lied or whose compressed bytes were corrupted, and the\n\t// fetch/WebSocket layer wraps it with a \"Library error:\" prefix. GitHub\n\t// Copilot on the default `transport: \"auto\"` reports this as\n\t// \"Library error: zlib error: incorrect header check\" (#2553). The transfer\n\t// is already unusable, and a fresh attempt normally succeeds, so treat every\n\t// variant as a transient transport failure rather than a deterministic error.\n\t\"zlib\",\n\t\"incorrect header check\",\n\t\"decompress\",\n\t\"library error\",\n\n\t// Idle-stream deadline enforced below the HTTP layer by `withStreamDeadline`\n\t// so a stream that never settles cannot hang an attempt forever (#2553).\n\t\"stream deadline exceeded\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\t// Codex CLI mid-stream disconnect, relayed by proxies that wrap the Codex CLI,\n\t// e.g. \"stream disconnected before completion: stream closed before response.completed\" (#11057).\n\t\"stream disconnected before completion\",\n\t// Magpie gateway relaying a dropped upstream Anthropic stream, e.g.\n\t// \"Claude Code's stream from Anthropic was cut short after the reply had begun\" (#11879).\n\t\"cut short after the reply had begun\",\n\t\"pending stream has been canceled\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\t\"subscription_sharing_usage_unavailable\",\n\t\"subscription_sharing_user_unavailable\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * Each delay is capped by `maxAgentDelayMs` (60 seconds by default).\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n\t/**\n\t * Cap for a server retry hint (`Retry-After-Ms`, `Retry-After`, a body `retry_after`).\n\t * Defaults to 60 seconds; 0 caps the hint by `maxAgentDelayMs` instead.\n\t */\n\tmaxRetryDelayMs?: number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\nexport function retryDelayMs(policy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\">, attempt: number): number {\n\tconst delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst safeDelay = Number.isSafeInteger(delay) ? delay : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\ntype RetryFailure = Pick<AssistantMessage, \"stopReason\" | \"errorMessage\" | \"retryAfterMs\" | \"diagnostics\">;\n\n/**\n * Wait before retry `attempt` (1-indexed): the server retry hint when the failure\n * carries one, capped by `maxRetryDelayMs`, otherwise the exponential backoff.\n */\nexport function failureRetryDelayMs(\n\tpolicy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\" | \"maxRetryDelayMs\">,\n\tattempt: number,\n\tfailure: Pick<AssistantMessage, \"retryAfterMs\">,\n): number {\n\tconst hintMs = failure.retryAfterMs;\n\tif (hintMs === undefined || !Number.isFinite(hintMs) || hintMs <= 0) return retryDelayMs(policy, attempt);\n\tconst maxRetryDelayMs = policy.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n\tconst capMs = maxRetryDelayMs || (policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n\treturn Math.min(hintMs, capMs);\n}\n\n/**\n * Delay before retry `attempt` (1-indexed) of a failed assistant call, or `undefined`\n * when it is not retryable or `maxRetries` is spent.\n */\nexport function assistantRetryDelayMs(policy: RetryPolicy, attempt: number, message: RetryFailure): number | undefined {\n\tif (!policy.enabled || attempt > policy.maxRetries || !isRetryableAssistantError(message)) return undefined;\n\treturn failureRetryDelayMs(policy, attempt, message);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times, waiting for the server retry hint or\n * the exponential backoff (see {@link assistantRetryDelayMs}), emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tconst delayMs = policy ? assistantRetryDelayMs(policy, attempt + 1, response) : undefined;\n\t\tif (delayMs === undefined) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * A GitHub Copilot failure carries its typed error, whose `retryable` decides.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: RetryFailure): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst copilotError = getGitHubCopilotError(message);\n\tif (copilotError !== undefined) return copilotError.retryable;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n"]}
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,0CAA0C,GAAG,yBAAyB,CAAC;IAC5E,8EAA8E;IAC9E,2EAA2E;IAC3E,mBAAmB;IACnB,qBAAqB;IAErB,6EAA6E;IAC7E,yDAAyD;IACzD,6BAA6B;IAC7B,mBAAmB;IAEnB,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpB,eAAe;IACf,gBAAgB;IAChB,SAAS;IACT,2CAA2C;IAC3C,4EAA4E;IAC5E,gDAAgD;IAChD,gEAAgE;IAEhE,2EAA2E;IA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I,KAAK,YAAY,oBAAoB,EAAE,CAAC;gBAC3C,OAAO,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;YACxE,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;QACD,IAAI,CAAC,oBAAoB,CAAC,SAAS,EAAE,aAAa,CAAC,EAAE,CAAC;YACrD,MAAM,SAAS,EAAE,mBAAmB,EAAE,EAAE,CAAC;YACzC,kDAAkD;YAClD,IAAI,CAAC,oBAAoB,CAAC,SAAS,EAAE,aAAa,CAAC;gBAAE,SAAS;QAC/D,CAAC;QACD,MAAM,SAAS,EAAE,eAAe,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;QAC3E,OAAO,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;IACxE,CAAC;AACF,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB;IAC9D,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;QAAE,OAAO,KAAK,CAAC;IAC1E,MAAM,YAAY,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;IACpD,IAAI,YAAY,KAAK,SAAS;QAAE,OAAO,YAAY,CAAC,SAAS,CAAC;IAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC1C,IAAI,0CAA0C,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IAChF,OAAO,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import { getGitHubCopilotError } from \"../providers/github-copilot-errors.ts\";\nimport type { AssistantMessage, RetryDeadline } from \"../types.ts\";\nimport { DEFAULT_MAX_RETRY_DELAY_MS } from \"./provider-retry.ts\";\nimport { retryDeadlineReached } from \"./retry-sleep.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\t\"subscription_sharing_usage_limit_exceeded\",\n\t// Sign in with ChatGPT on a ChatGPT Business plan: a usage limit set by the\n\t// workspace admin. Only the admin can raise it.\n\t\"subscription_sharing_workplace_individual_usage_limit_exceeded\",\n\n\t// Zhipu/Z.ai (open.bigmodel.cn) error code 1308: the plan's usage limit is\n\t// reached, sent as HTTP 429. It resets after hours, not seconds (#11537).\n\t'\"code\"\\\\s*:\\\\s*\"?1308(?![0-9])',\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"server_busy\",\n\t\"servers are currently busy\",\n\t\"currently experiencing high demand\",\n\t\"model is at capacity\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t// Status codes must not be part of a longer word or number, e.g. a request id or byte count (#11057).\n\t// 521-523 are Cloudflare origin errors (#3623); 529 is an overload response.\n\t\"(?<![a-z0-9])(?:429|500|502|503|504|52[0-4]|529)(?![a-z0-9])\",\n\t// Also matches \"The service is temporarily unavailable\" (#10965).\n\t\"service.?(?:is.?)?(?:temporarily.?)?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?(?:an.?)?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\t\"unable to forward upstream\",\n\t\"upstream.?request.?failed\",\n\t\"upstream_stream_read_error\",\n\t\"stream was interrupted\",\n\t\"http/?2 stream failed\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"connection.?closed\",\n\t\"(?<![a-z0-9_])(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|ETIMEDOUT|EPIPE)(?![a-z0-9_])\",\n\t\"connection reset by peer\",\n\t\"connection.?reset\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"request to \\\\S+ failed, reason:\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Response-body decompression failures. Node/Bun zlib rejects a body whose\n\t// Content-Encoding lied or whose compressed bytes were corrupted, and the\n\t// fetch/WebSocket layer wraps it with a \"Library error:\" prefix. GitHub\n\t// Copilot on the default `transport: \"auto\"` reports this as\n\t// \"Library error: zlib error: incorrect header check\" (#2553). The transfer\n\t// is already unusable, and a fresh attempt normally succeeds, so treat every\n\t// variant as a transient transport failure rather than a deterministic error.\n\t\"zlib\",\n\t\"incorrect header check\",\n\t\"decompress\",\n\t\"library error\",\n\n\t// Idle-stream deadline enforced below the HTTP layer by `withStreamDeadline`\n\t// so a stream that never settles cannot hang an attempt forever (#2553).\n\t\"stream deadline exceeded\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\t// Codex CLI mid-stream disconnect, relayed by proxies that wrap the Codex CLI,\n\t// e.g. \"stream disconnected before completion: stream closed before response.completed\" (#11057).\n\t\"stream disconnected before completion\",\n\t// Magpie gateway relaying a dropped upstream Anthropic stream, e.g.\n\t// \"Claude Code's stream from Anthropic was cut short after the reply had begun\" (#11879).\n\t\"cut short after the reply had begun\",\n\t\"pending stream has been canceled\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\t\"subscription_sharing_usage_unavailable\",\n\t\"subscription_sharing_user_unavailable\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * Each delay is capped by `maxAgentDelayMs` (60 seconds by default).\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n\t/**\n\t * Cap for a server retry hint (`Retry-After-Ms`, `Retry-After`, a body `retry_after`).\n\t * Defaults to 60 seconds; 0 caps the hint by `maxAgentDelayMs` instead.\n\t */\n\tmaxRetryDelayMs?: number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\nexport function retryDelayMs(policy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\">, attempt: number): number {\n\tconst delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst safeDelay = Number.isSafeInteger(delay) ? delay : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\ntype RetryFailure = Pick<AssistantMessage, \"stopReason\" | \"errorMessage\" | \"retryAfterMs\" | \"diagnostics\">;\n\n/**\n * Wait before retry `attempt` (1-indexed): the server retry hint when the failure\n * carries one, capped by `maxRetryDelayMs`, otherwise the exponential backoff.\n */\nexport function failureRetryDelayMs(\n\tpolicy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\" | \"maxRetryDelayMs\">,\n\tattempt: number,\n\tfailure: Pick<AssistantMessage, \"retryAfterMs\">,\n): number {\n\tconst hintMs = failure.retryAfterMs;\n\tif (hintMs === undefined || !Number.isFinite(hintMs) || hintMs <= 0) return retryDelayMs(policy, attempt);\n\tconst maxRetryDelayMs = policy.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n\tconst capMs = maxRetryDelayMs || (policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n\treturn Math.min(hintMs, capMs);\n}\n\n/**\n * Delay before retry `attempt` (1-indexed) of a failed assistant call, or `undefined`\n * when it is not retryable or `maxRetries` is spent.\n */\nexport function assistantRetryDelayMs(policy: RetryPolicy, attempt: number, message: RetryFailure): number | undefined {\n\tif (!policy.enabled || attempt > policy.maxRetries || !isRetryableAssistantError(message)) return undefined;\n\treturn failureRetryDelayMs(policy, attempt, message);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nexport interface RetryCallOptions extends RetryCallbacks {\n\t/** Do not start a retry at or after this performance.now() timestamp. Does not cancel a running call. */\n\tretryDeadline?: RetryDeadline;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times, waiting for the server retry hint or\n * the exponential backoff (see {@link assistantRetryDelayMs}), emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallOptions,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tconst delayMs = policy ? assistantRetryDelayMs(policy, attempt + 1, response) : undefined;\n\t\tif (delayMs === undefined) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (!retryDeadlineReached(callbacks?.retryDeadline)) {\n\t\t\tawait callbacks?.onRetryAttemptStart?.();\n\t\t\t// The callback can itself wait past the deadline.\n\t\t\tif (!retryDeadlineReached(callbacks?.retryDeadline)) continue;\n\t\t}\n\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * A GitHub Copilot failure carries its typed error, whose `retryable` decides.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: RetryFailure): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst copilotError = getGitHubCopilotError(message);\n\tif (copilotError !== undefined) return copilotError.retryable;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n"]}
@@ -26,4 +26,15 @@ export declare class ServerSentEventDecoder {
26
26
  private decodeLine;
27
27
  private dispatch;
28
28
  }
29
+ /**
30
+ * Watches streamed responses for the `data: [DONE]` event that ends a complete Chat Completions stream, which the
31
+ * OpenAI SDK consumes without passing on. A stream that is cut off never delivers it. Bodies pass through unchanged.
32
+ */
33
+ export declare class DoneEventWatch {
34
+ #private;
35
+ /** Whether the body of the latest response delivered `[DONE]`. */
36
+ get received(): boolean;
37
+ /** `send`, with the body of each successful response watched. Each request starts with nothing received. */
38
+ watch(send: typeof globalThis.fetch): typeof globalThis.fetch;
39
+ }
29
40
  //# sourceMappingURL=sse.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/utils/sse.ts"],"names":[],"mappings":"AAAA,qHAAqH;AACrH,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,EAAE,CAAC;CACd;AAED;;;;;;;GAOG;AACH,qBAAa,sBAAsB;IAClC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAqB;IACjD,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,IAAI,CAAgB;IAC5B,OAAO,CAAC,GAAG,CAAgB;IAE3B,2EAA2E;IAC3E,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,eAAe,EAAE,CAG3C;IAED,kEAAkE;IAClE,GAAG,IAAI,eAAe,EAAE,CAMvB;IAED,OAAO,CAAC,YAAY;IAapB,OAAO,CAAC,UAAU;IAoBlB,OAAO,CAAC,QAAQ;CAYhB"}
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/utils/sse.ts"],"names":[],"mappings":"AAAA,qHAAqH;AACrH,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,EAAE,CAAC;CACd;AAED;;;;;;;GAOG;AACH,qBAAa,sBAAsB;IAClC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAqB;IACjD,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,IAAI,CAAgB;IAC5B,OAAO,CAAC,GAAG,CAAgB;IAE3B,2EAA2E;IAC3E,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,eAAe,EAAE,CAG3C;IAED,kEAAkE;IAClE,GAAG,IAAI,eAAe,EAAE,CAMvB;IAED,OAAO,CAAC,YAAY;IAapB,OAAO,CAAC,UAAU;IAoBlB,OAAO,CAAC,QAAQ;CAYhB;AAiFD;;;GAGG;AACH,qBAAa,cAAc;;IAG1B,kEAAkE;IAClE,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,4GAA4G;IAC5G,KAAK,CAAC,IAAI,EAAE,OAAO,UAAU,CAAC,KAAK,GAAG,OAAO,UAAU,CAAC,KAAK,CAK5D;CAmCD"}
package/dist/utils/sse.js CHANGED
@@ -70,4 +70,135 @@ export class ServerSentEventDecoder {
70
70
  this.raw = [];
71
71
  }
72
72
  }
73
+ const CR = 0x0d;
74
+ const LF = 0x0a;
75
+ const DONE_LINES = ["data: [DONE]", "data:[DONE]"].map((line) => new TextEncoder().encode(line));
76
+ const DATA_FIELD = new TextEncoder().encode("data");
77
+ const COLON = 0x3a;
78
+ /** The longest line that can be a `[DONE]` data line; only that much of each line is kept. */
79
+ const KEPT_LINE_BYTES = Math.max(...DONE_LINES.map((line) => line.length));
80
+ function startsWith(bytes, prefix) {
81
+ return bytes.length >= prefix.length && prefix.every((byte, index) => bytes[index] === byte);
82
+ }
83
+ /**
84
+ * Finds the `data: [DONE]` event of a Server-Sent Events stream as `ServerSentEventDecoder` would decode it: an event
85
+ * whose only data line is `[DONE]`. Keeps at most the first bytes of each line, so a long event costs one pass.
86
+ */
87
+ class DoneEventScanner {
88
+ found = false;
89
+ #line = new Uint8Array(KEPT_LINE_BYTES);
90
+ #lineLength = 0;
91
+ /** The previous chunk ended with CR, so an LF that starts this one ends the same line. */
92
+ #afterCR = false;
93
+ #dataLines = 0;
94
+ #doneData = false;
95
+ push(chunk) {
96
+ if (chunk.length === 0)
97
+ return;
98
+ let start = this.#afterCR && chunk[0] === LF ? 1 : 0;
99
+ this.#afterCR = false;
100
+ let nextCR = chunk.indexOf(CR, start);
101
+ let nextLF = chunk.indexOf(LF, start);
102
+ while (start < chunk.length && !this.found) {
103
+ if (nextCR !== -1 && nextCR < start)
104
+ nextCR = chunk.indexOf(CR, start);
105
+ if (nextLF !== -1 && nextLF < start)
106
+ nextLF = chunk.indexOf(LF, start);
107
+ const end = nextCR === -1 ? nextLF : nextLF === -1 ? nextCR : Math.min(nextCR, nextLF);
108
+ if (end === -1) {
109
+ this.#keep(chunk, start, chunk.length);
110
+ return;
111
+ }
112
+ this.#keep(chunk, start, end);
113
+ this.#endLine();
114
+ start = end + 1;
115
+ if (chunk[end] === CR) {
116
+ if (start === chunk.length)
117
+ this.#afterCR = true;
118
+ else if (chunk[start] === LF)
119
+ start += 1;
120
+ }
121
+ }
122
+ }
123
+ /** The stream ended: a pending line and event are dispatched, as the SDK does. */
124
+ end() {
125
+ if (this.#lineLength > 0)
126
+ this.#endLine();
127
+ this.#endLine();
128
+ }
129
+ #keep(chunk, start, end) {
130
+ const room = KEPT_LINE_BYTES - this.#lineLength;
131
+ if (room > 0)
132
+ this.#line.set(chunk.subarray(start, Math.min(end, start + room)), this.#lineLength);
133
+ this.#lineLength += end - start;
134
+ }
135
+ #endLine() {
136
+ const length = this.#lineLength;
137
+ this.#lineLength = 0;
138
+ if (length === 0) {
139
+ if (this.#dataLines === 1 && this.#doneData)
140
+ this.found = true;
141
+ this.#dataLines = 0;
142
+ this.#doneData = false;
143
+ return;
144
+ }
145
+ const kept = this.#line.subarray(0, Math.min(length, KEPT_LINE_BYTES));
146
+ const isData = startsWith(kept, DATA_FIELD) && (length === DATA_FIELD.length || kept[DATA_FIELD.length] === COLON);
147
+ if (!isData)
148
+ return;
149
+ this.#dataLines += 1;
150
+ this.#doneData = DONE_LINES.some((line) => line.length === length && startsWith(kept, line));
151
+ }
152
+ }
153
+ /**
154
+ * Watches streamed responses for the `data: [DONE]` event that ends a complete Chat Completions stream, which the
155
+ * OpenAI SDK consumes without passing on. A stream that is cut off never delivers it. Bodies pass through unchanged.
156
+ */
157
+ export class DoneEventWatch {
158
+ #received = false;
159
+ /** Whether the body of the latest response delivered `[DONE]`. */
160
+ get received() {
161
+ return this.#received;
162
+ }
163
+ /** `send`, with the body of each successful response watched. Each request starts with nothing received. */
164
+ watch(send) {
165
+ return Object.assign(async (...args) => {
166
+ this.#received = false;
167
+ return this.#watchBody(await send(...args));
168
+ }, send);
169
+ }
170
+ #watchBody(response) {
171
+ if (!response.ok || !response.body)
172
+ return response;
173
+ const scanner = new DoneEventScanner();
174
+ let reader;
175
+ // The body is locked only once it is read, and these callbacks hold `response` itself: a response nobody reads
176
+ // is collected with its body unlocked, which lets the runtime release its connection.
177
+ const body = new ReadableStream({
178
+ pull: async (controller) => {
179
+ reader ??= response.body.getReader();
180
+ const { done, value } = await reader.read();
181
+ if (done) {
182
+ if (!scanner.found)
183
+ scanner.end();
184
+ this.#received ||= scanner.found;
185
+ controller.close();
186
+ return;
187
+ }
188
+ if (!scanner.found)
189
+ scanner.push(value);
190
+ this.#received ||= scanner.found;
191
+ controller.enqueue(value);
192
+ },
193
+ cancel: (reason) => (reader ? reader.cancel(reason) : response.body?.cancel(reason)),
194
+ }, { highWaterMark: 0 });
195
+ const watched = new Response(body, {
196
+ status: response.status,
197
+ statusText: response.statusText,
198
+ headers: response.headers,
199
+ });
200
+ Object.defineProperty(watched, "url", { value: response.url });
201
+ return watched;
202
+ }
203
+ }
73
204
  //# sourceMappingURL=sse.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sse.js","sourceRoot":"","sources":["../../src/utils/sse.ts"],"names":[],"mappings":"AAOA;;;;;;;GAOG;AACH,MAAM,OAAO,sBAAsB;IACjB,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;IACzC,MAAM,GAAG,EAAE,CAAC;IACZ,KAAK,GAAkB,IAAI,CAAC;IAC5B,IAAI,GAAa,EAAE,CAAC;IACpB,GAAG,GAAa,EAAE,CAAC;IAE3B,2EAA2E;IAC3E,MAAM,CAAC,KAAiB;QACvB,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,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,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;QACf,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;IACf,CAAC;CACD","sourcesContent":["/** One dispatched Server-Sent Event: its `event` field, its `data` lines joined by \"\\n\", and the raw field lines. */\nexport interface ServerSentEvent {\n\tevent: string | null;\n\tdata: string;\n\traw: string[];\n}\n\n/**\n * Incremental Server-Sent Events decoder that yields the same events however the byte stream is chunked.\n *\n * Lines end with CRLF, LF, or a lone CR. A CR at the end of a chunk is held until the next chunk (or the end of\n * the stream) shows whether an LF follows, so a CRLF split across chunks is one line ending, not a line ending\n * plus an empty line. Bytes are decoded in streaming mode, so a multibyte character split across chunks is kept\n * whole. An event pending at the end of the stream is dispatched.\n */\nexport class ServerSentEventDecoder {\n\tprivate readonly textDecoder = new TextDecoder();\n\tprivate buffer = \"\";\n\tprivate event: string | null = null;\n\tprivate data: string[] = [];\n\tprivate raw: string[] = [];\n\n\t/** Decodes one chunk of the stream and returns the events it completed. */\n\tdecode(chunk: Uint8Array): ServerSentEvent[] {\n\t\tthis.buffer += this.textDecoder.decode(chunk, { stream: true });\n\t\treturn this.consumeLines(false);\n\t}\n\n\t/** Ends the stream and returns the events still pending in it. */\n\tend(): ServerSentEvent[] {\n\t\tthis.buffer += this.textDecoder.decode();\n\t\tconst events = this.consumeLines(true);\n\t\tthis.decodeLine(this.buffer, events);\n\t\tthis.dispatch(events);\n\t\treturn events;\n\t}\n\n\tprivate consumeLines(final: boolean): ServerSentEvent[] {\n\t\tconst events: ServerSentEvent[] = [];\n\t\tconst text = this.buffer;\n\t\tlet start = 0;\n\t\tfor (const lineBreak of text.matchAll(/\\r\\n|\\r|\\n/g)) {\n\t\t\tif (lineBreak[0] === \"\\r\" && lineBreak.index + 1 === text.length && !final) break;\n\t\t\tthis.decodeLine(text.slice(start, lineBreak.index), events);\n\t\t\tstart = lineBreak.index + lineBreak[0].length;\n\t\t}\n\t\tthis.buffer = text.slice(start);\n\t\treturn events;\n\t}\n\n\tprivate decodeLine(line: string, events: ServerSentEvent[]): void {\n\t\tif (line === \"\") {\n\t\t\tthis.dispatch(events);\n\t\t\treturn;\n\t\t}\n\n\t\t// A comment line (\":...\") has an empty field name, which is ignored like any unknown field.\n\t\tthis.raw.push(line);\n\t\tconst delimiterIndex = line.indexOf(\":\");\n\t\tconst fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);\n\t\tlet value = delimiterIndex === -1 ? \"\" : line.slice(delimiterIndex + 1);\n\t\tif (value.startsWith(\" \")) value = value.slice(1);\n\n\t\tif (fieldName === \"event\") {\n\t\t\tthis.event = value;\n\t\t} else if (fieldName === \"data\") {\n\t\t\tthis.data.push(value);\n\t\t}\n\t}\n\n\tprivate dispatch(events: ServerSentEvent[]): void {\n\t\tif (!this.event && this.data.length === 0) {\n\t\t\t// Comment-only blocks carry nothing to dispatch.\n\t\t\tthis.event = null;\n\t\t\tthis.raw = [];\n\t\t\treturn;\n\t\t}\n\t\tevents.push({ event: this.event, data: this.data.join(\"\\n\"), raw: this.raw });\n\t\tthis.event = null;\n\t\tthis.data = [];\n\t\tthis.raw = [];\n\t}\n}\n"]}
1
+ {"version":3,"file":"sse.js","sourceRoot":"","sources":["../../src/utils/sse.ts"],"names":[],"mappings":"AAOA;;;;;;;GAOG;AACH,MAAM,OAAO,sBAAsB;IACjB,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;IACzC,MAAM,GAAG,EAAE,CAAC;IACZ,KAAK,GAAkB,IAAI,CAAC;IAC5B,IAAI,GAAa,EAAE,CAAC;IACpB,GAAG,GAAa,EAAE,CAAC;IAE3B,2EAA2E;IAC3E,MAAM,CAAC,KAAiB;QACvB,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAChE,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,CA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,MAAM,CAAC,IAAI,EAAE,CAAC;gBAC5C,IAAI,IAAI,EAAE,CAAC;oBACV,IAAI,CAAC,OAAO,CAAC,KAAK;wBAAE,OAAO,CAAC,GAAG,EAAE,CAAC;oBAClC,IAAI,CAAC,SAAS,KAAK,OAAO,CAAC,KAAK,CAAC;oBACjC,UAAU,CAAC,KAAK,EAAE,CAAC;oBACnB,OAAO;gBACR,CAAC;gBACD,IAAI,CAAC,OAAO,CAAC,KAAK;oBAAE,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACxC,IAAI,CAAC,SAAS,KAAK,OAAO,CAAC,KAAK,CAAC;gBACjC,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC3B,CAAC;YACD,MAAM,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;SACpF,EACD,EAAE,aAAa,EAAE,CAAC,EAAE,CACpB,CAAC;QACF,MAAM,OAAO,GAAG,IAAI,QAAQ,CAAC,IAAI,EAAE;YAClC,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;YAC/B,OAAO,EAAE,QAAQ,CAAC,OAAO;SACzB,CAAC,CAAC;QACH,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC;QAC/D,OAAO,OAAO,CAAC;IAChB,CAAC;CACD","sourcesContent":["/** One dispatched Server-Sent Event: its `event` field, its `data` lines joined by \"\\n\", and the raw field lines. */\nexport interface ServerSentEvent {\n\tevent: string | null;\n\tdata: string;\n\traw: string[];\n}\n\n/**\n * Incremental Server-Sent Events decoder that yields the same events however the byte stream is chunked.\n *\n * Lines end with CRLF, LF, or a lone CR. A CR at the end of a chunk is held until the next chunk (or the end of\n * the stream) shows whether an LF follows, so a CRLF split across chunks is one line ending, not a line ending\n * plus an empty line. Bytes are decoded in streaming mode, so a multibyte character split across chunks is kept\n * whole. An event pending at the end of the stream is dispatched.\n */\nexport class ServerSentEventDecoder {\n\tprivate readonly textDecoder = new TextDecoder();\n\tprivate buffer = \"\";\n\tprivate event: string | null = null;\n\tprivate data: string[] = [];\n\tprivate raw: string[] = [];\n\n\t/** Decodes one chunk of the stream and returns the events it completed. */\n\tdecode(chunk: Uint8Array): ServerSentEvent[] {\n\t\tthis.buffer += this.textDecoder.decode(chunk, { stream: true });\n\t\treturn this.consumeLines(false);\n\t}\n\n\t/** Ends the stream and returns the events still pending in it. */\n\tend(): ServerSentEvent[] {\n\t\tthis.buffer += this.textDecoder.decode();\n\t\tconst events = this.consumeLines(true);\n\t\tthis.decodeLine(this.buffer, events);\n\t\tthis.dispatch(events);\n\t\treturn events;\n\t}\n\n\tprivate consumeLines(final: boolean): ServerSentEvent[] {\n\t\tconst events: ServerSentEvent[] = [];\n\t\tconst text = this.buffer;\n\t\tlet start = 0;\n\t\tfor (const lineBreak of text.matchAll(/\\r\\n|\\r|\\n/g)) {\n\t\t\tif (lineBreak[0] === \"\\r\" && lineBreak.index + 1 === text.length && !final) break;\n\t\t\tthis.decodeLine(text.slice(start, lineBreak.index), events);\n\t\t\tstart = lineBreak.index + lineBreak[0].length;\n\t\t}\n\t\tthis.buffer = text.slice(start);\n\t\treturn events;\n\t}\n\n\tprivate decodeLine(line: string, events: ServerSentEvent[]): void {\n\t\tif (line === \"\") {\n\t\t\tthis.dispatch(events);\n\t\t\treturn;\n\t\t}\n\n\t\t// A comment line (\":...\") has an empty field name, which is ignored like any unknown field.\n\t\tthis.raw.push(line);\n\t\tconst delimiterIndex = line.indexOf(\":\");\n\t\tconst fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);\n\t\tlet value = delimiterIndex === -1 ? \"\" : line.slice(delimiterIndex + 1);\n\t\tif (value.startsWith(\" \")) value = value.slice(1);\n\n\t\tif (fieldName === \"event\") {\n\t\t\tthis.event = value;\n\t\t} else if (fieldName === \"data\") {\n\t\t\tthis.data.push(value);\n\t\t}\n\t}\n\n\tprivate dispatch(events: ServerSentEvent[]): void {\n\t\tif (!this.event && this.data.length === 0) {\n\t\t\t// Comment-only blocks carry nothing to dispatch.\n\t\t\tthis.event = null;\n\t\t\tthis.raw = [];\n\t\t\treturn;\n\t\t}\n\t\tevents.push({ event: this.event, data: this.data.join(\"\\n\"), raw: this.raw });\n\t\tthis.event = null;\n\t\tthis.data = [];\n\t\tthis.raw = [];\n\t}\n}\n\nconst CR = 0x0d;\nconst LF = 0x0a;\nconst DONE_LINES = [\"data: [DONE]\", \"data:[DONE]\"].map((line) => new TextEncoder().encode(line));\nconst DATA_FIELD = new TextEncoder().encode(\"data\");\nconst COLON = 0x3a;\n/** The longest line that can be a `[DONE]` data line; only that much of each line is kept. */\nconst KEPT_LINE_BYTES = Math.max(...DONE_LINES.map((line) => line.length));\n\nfunction startsWith(bytes: Uint8Array, prefix: Uint8Array): boolean {\n\treturn bytes.length >= prefix.length && prefix.every((byte, index) => bytes[index] === byte);\n}\n\n/**\n * Finds the `data: [DONE]` event of a Server-Sent Events stream as `ServerSentEventDecoder` would decode it: an event\n * whose only data line is `[DONE]`. Keeps at most the first bytes of each line, so a long event costs one pass.\n */\nclass DoneEventScanner {\n\tfound = false;\n\treadonly #line = new Uint8Array(KEPT_LINE_BYTES);\n\t#lineLength = 0;\n\t/** The previous chunk ended with CR, so an LF that starts this one ends the same line. */\n\t#afterCR = false;\n\t#dataLines = 0;\n\t#doneData = false;\n\n\tpush(chunk: Uint8Array): void {\n\t\tif (chunk.length === 0) return;\n\t\tlet start = this.#afterCR && chunk[0] === LF ? 1 : 0;\n\t\tthis.#afterCR = false;\n\t\tlet nextCR = chunk.indexOf(CR, start);\n\t\tlet nextLF = chunk.indexOf(LF, start);\n\t\twhile (start < chunk.length && !this.found) {\n\t\t\tif (nextCR !== -1 && nextCR < start) nextCR = chunk.indexOf(CR, start);\n\t\t\tif (nextLF !== -1 && nextLF < start) nextLF = chunk.indexOf(LF, start);\n\t\t\tconst end = nextCR === -1 ? nextLF : nextLF === -1 ? nextCR : Math.min(nextCR, nextLF);\n\t\t\tif (end === -1) {\n\t\t\t\tthis.#keep(chunk, start, chunk.length);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#keep(chunk, start, end);\n\t\t\tthis.#endLine();\n\t\t\tstart = end + 1;\n\t\t\tif (chunk[end] === CR) {\n\t\t\t\tif (start === chunk.length) this.#afterCR = true;\n\t\t\t\telse if (chunk[start] === LF) start += 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The stream ended: a pending line and event are dispatched, as the SDK does. */\n\tend(): void {\n\t\tif (this.#lineLength > 0) this.#endLine();\n\t\tthis.#endLine();\n\t}\n\n\t#keep(chunk: Uint8Array, start: number, end: number): void {\n\t\tconst room = KEPT_LINE_BYTES - this.#lineLength;\n\t\tif (room > 0) this.#line.set(chunk.subarray(start, Math.min(end, start + room)), this.#lineLength);\n\t\tthis.#lineLength += end - start;\n\t}\n\n\t#endLine(): void {\n\t\tconst length = this.#lineLength;\n\t\tthis.#lineLength = 0;\n\t\tif (length === 0) {\n\t\t\tif (this.#dataLines === 1 && this.#doneData) this.found = true;\n\t\t\tthis.#dataLines = 0;\n\t\t\tthis.#doneData = false;\n\t\t\treturn;\n\t\t}\n\t\tconst kept = this.#line.subarray(0, Math.min(length, KEPT_LINE_BYTES));\n\t\tconst isData =\n\t\t\tstartsWith(kept, DATA_FIELD) && (length === DATA_FIELD.length || kept[DATA_FIELD.length] === COLON);\n\t\tif (!isData) return;\n\t\tthis.#dataLines += 1;\n\t\tthis.#doneData = DONE_LINES.some((line) => line.length === length && startsWith(kept, line));\n\t}\n}\n\n/**\n * Watches streamed responses for the `data: [DONE]` event that ends a complete Chat Completions stream, which the\n * OpenAI SDK consumes without passing on. A stream that is cut off never delivers it. Bodies pass through unchanged.\n */\nexport class DoneEventWatch {\n\t#received = false;\n\n\t/** Whether the body of the latest response delivered `[DONE]`. */\n\tget received(): boolean {\n\t\treturn this.#received;\n\t}\n\n\t/** `send`, with the body of each successful response watched. Each request starts with nothing received. */\n\twatch(send: typeof globalThis.fetch): typeof globalThis.fetch {\n\t\treturn Object.assign(async (...args: Parameters<typeof globalThis.fetch>) => {\n\t\t\tthis.#received = false;\n\t\t\treturn this.#watchBody(await send(...args));\n\t\t}, send);\n\t}\n\n\t#watchBody(response: Response): Response {\n\t\tif (!response.ok || !response.body) return response;\n\t\tconst scanner = new DoneEventScanner();\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t\t// The body is locked only once it is read, and these callbacks hold `response` itself: a response nobody reads\n\t\t// is collected with its body unlocked, which lets the runtime release its connection.\n\t\tconst body = new ReadableStream<Uint8Array>(\n\t\t\t{\n\t\t\t\tpull: async (controller) => {\n\t\t\t\t\treader ??= response.body!.getReader();\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tif (!scanner.found) scanner.end();\n\t\t\t\t\t\tthis.#received ||= scanner.found;\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!scanner.found) scanner.push(value);\n\t\t\t\t\tthis.#received ||= scanner.found;\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t},\n\t\t\t\tcancel: (reason) => (reader ? reader.cancel(reason) : response.body?.cancel(reason)),\n\t\t\t},\n\t\t\t{ highWaterMark: 0 },\n\t\t);\n\t\tconst watched = new Response(body, {\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText,\n\t\t\theaders: response.headers,\n\t\t});\n\t\tObject.defineProperty(watched, \"url\", { value: response.url });\n\t\treturn watched;\n\t}\n}\n"]}
@@ -1,2 +1,2 @@
1
- export declare const PI_AI_VERSION = "0.9.90";
1
+ export declare const PI_AI_VERSION = "0.10.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -1,3 +1,3 @@
1
1
  // The @bastani/atomic-ai package version. scripts/bump-version.ts keeps it in sync with package.json.
2
- export const PI_AI_VERSION = "0.9.90";
2
+ export const PI_AI_VERSION = "0.10.0";
3
3
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/utils/version.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,MAAM,CAAC,MAAM,aAAa,GAAG,QAAQ,CAAC","sourcesContent":["// The @bastani/atomic-ai package version. scripts/bump-version.ts keeps it in sync with package.json.\nexport const PI_AI_VERSION = \"0.9.90\";\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/utils/version.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,MAAM,CAAC,MAAM,aAAa,GAAG,QAAQ,CAAC","sourcesContent":["// The @bastani/atomic-ai package version. scripts/bump-version.ts keeps it in sync with package.json.\nexport const PI_AI_VERSION = \"0.10.0\";\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/atomic-ai",
3
- "version": "0.9.90",
3
+ "version": "0.10.0",
4
4
  "description": "Atomic's unified LLM API: providers, models, auth, streaming, tools, images and classification",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -90,8 +90,8 @@
90
90
  "dependencies": {
91
91
  "@anthropic-ai/sdk": "0.129.0",
92
92
  "@aws-sdk/client-bedrock-runtime": "3.1127.0",
93
- "@bastani/atomic-schema": "0.9.90",
94
- "@bastani/atomic-telemetry": "0.9.90",
93
+ "@bastani/atomic-schema": "0.10.0",
94
+ "@bastani/atomic-telemetry": "0.10.0",
95
95
  "@google/genai": "2.32.0",
96
96
  "@smithy/node-http-handler": "4.13.0",
97
97
  "http-proxy-agent": "9.1.0",