@anvia/core 0.13.3 → 0.13.5

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 (68) hide show
  1. package/dist/agent/index.d.ts +11 -11
  2. package/dist/agent/index.js +8 -8
  3. package/dist/{agent-3qSfIKIj.d.ts → agent-W8sT6P5T.d.ts} +27 -8
  4. package/dist/audio-generation/index.d.ts +1 -1
  5. package/dist/{chunk-VPRJIWTP.js → chunk-3LB36HON.js} +269 -30
  6. package/dist/chunk-3LB36HON.js.map +1 -0
  7. package/dist/{chunk-NS7W4G26.js → chunk-3LMKHICK.js} +2 -2
  8. package/dist/{chunk-AWTFWDMY.js → chunk-6FLW6XS6.js} +3 -3
  9. package/dist/{chunk-DC2GJDPR.js → chunk-77D7XBWL.js} +2 -2
  10. package/dist/{chunk-I7TM7TKX.js → chunk-F3C5653H.js} +4 -4
  11. package/dist/{chunk-CNTGKNZ3.js → chunk-FE5QL4G3.js} +32 -1
  12. package/dist/chunk-FE5QL4G3.js.map +1 -0
  13. package/dist/{chunk-YTF65GYU.js → chunk-IBKCOBAS.js} +2 -2
  14. package/dist/{chunk-J3R7WC2W.js → chunk-LJT67CFB.js} +5 -5
  15. package/dist/{chunk-AXBW7OYU.js → chunk-TTKCFLW6.js} +6 -6
  16. package/dist/{chunk-WHHQWT7D.js → chunk-XH6LZMGH.js} +6 -6
  17. package/dist/completion/index.d.ts +3 -3
  18. package/dist/completion/index.js +4 -2
  19. package/dist/evals/index.d.ts +8 -8
  20. package/dist/evals/index.js +9 -9
  21. package/dist/extractor/index.d.ts +8 -8
  22. package/dist/extractor/index.js +9 -9
  23. package/dist/guardrails/index.d.ts +1 -1
  24. package/dist/hooks/index.d.ts +3 -3
  25. package/dist/image-generation/index.d.ts +1 -1
  26. package/dist/{index-ZQAiHW5Q.d.ts → index-BtyK30mL.d.ts} +2 -2
  27. package/dist/index.d.ts +13 -13
  28. package/dist/index.js +13 -11
  29. package/dist/internal/agent.d.ts +8 -8
  30. package/dist/internal/agent.js +7 -7
  31. package/dist/{json-C5a6auAm.d.ts → json-BOHFS4AG.d.ts} +1 -1
  32. package/dist/loaders/index.d.ts +1 -1
  33. package/dist/mcp/index.d.ts +4 -4
  34. package/dist/memory/index.d.ts +3 -3
  35. package/dist/{middleware-Cc_-sosu.d.ts → middleware-D6p0Uzky.d.ts} +3 -3
  36. package/dist/observability/index.d.ts +3 -3
  37. package/dist/pipeline/index.d.ts +8 -8
  38. package/dist/request/index.d.ts +8 -8
  39. package/dist/request/index.js +6 -6
  40. package/dist/skills/index.d.ts +4 -4
  41. package/dist/skills/index.js +5 -5
  42. package/dist/{think-tool-DvhOlrL8.d.ts → think-tool-B7p_7_5P.d.ts} +1 -1
  43. package/dist/tool/index.d.ts +5 -5
  44. package/dist/tool/index.js +5 -5
  45. package/dist/{tool-6f9bK92X.d.ts → tool-DhT6kR0Z.d.ts} +1 -1
  46. package/dist/transcription/index.d.ts +1 -1
  47. package/dist/{types-C708DOhL.d.ts → types-9TeQF79I.d.ts} +1 -1
  48. package/dist/{types-DzdJOf35.d.ts → types-BNq9tWdA.d.ts} +7 -1
  49. package/dist/{types-BaYwqozV.d.ts → types-BjPcB4PA.d.ts} +1 -1
  50. package/dist/types-CaXSh3vK.d.ts +72 -0
  51. package/dist/{types-BG3s2WzI.d.ts → types-CibT6_rS.d.ts} +2 -2
  52. package/dist/{types-BZQlZ4Vs.d.ts → types-Cz24JCei.d.ts} +1 -1
  53. package/dist/ui/index.d.ts +1 -1
  54. package/dist/ui/index.js +2 -2
  55. package/dist/vector-store/index.d.ts +4 -4
  56. package/dist/vector-store/index.js +2 -2
  57. package/package.json +1 -1
  58. package/dist/chunk-CNTGKNZ3.js.map +0 -1
  59. package/dist/chunk-VPRJIWTP.js.map +0 -1
  60. package/dist/types-CNeDsGjw.d.ts +0 -42
  61. /package/dist/{chunk-NS7W4G26.js.map → chunk-3LMKHICK.js.map} +0 -0
  62. /package/dist/{chunk-AWTFWDMY.js.map → chunk-6FLW6XS6.js.map} +0 -0
  63. /package/dist/{chunk-DC2GJDPR.js.map → chunk-77D7XBWL.js.map} +0 -0
  64. /package/dist/{chunk-I7TM7TKX.js.map → chunk-F3C5653H.js.map} +0 -0
  65. /package/dist/{chunk-YTF65GYU.js.map → chunk-IBKCOBAS.js.map} +0 -0
  66. /package/dist/{chunk-J3R7WC2W.js.map → chunk-LJT67CFB.js.map} +0 -0
  67. /package/dist/{chunk-AXBW7OYU.js.map → chunk-TTKCFLW6.js.map} +0 -0
  68. /package/dist/{chunk-WHHQWT7D.js.map → chunk-XH6LZMGH.js.map} +0 -0
@@ -1,16 +1,16 @@
1
- import { D as DynamicContextOptions, a as DynamicToolOptions, b as AgentEventStore, c as AgentEventStoreOptions, A as Agent } from '../agent-3qSfIKIj.js';
2
- export { d as AgentEventAppendInput, e as AgentEventRecord, f as AgentEventStoreInclude, g as AgentSession, h as AgentToolOptions } from '../agent-3qSfIKIj.js';
1
+ import { D as DynamicContextOptions, b as DynamicToolOptions, c as AgentEventStore, d as AgentEventStoreOptions, A as Agent } from '../agent-W8sT6P5T.js';
2
+ export { e as AgentEventAppendInput, f as AgentEventRecord, g as AgentEventStoreInclude, h as AgentSession, i as AgentToolOptions } from '../agent-W8sT6P5T.js';
3
3
  import { Z as ZodSchema } from '../zod-schema-C7F4clpm.js';
4
- import { C as CompletionModel, f as JsonValue, t as ToolChoice } from '../types-DzdJOf35.js';
4
+ import { C as CompletionModel, g as JsonValue, v as ToolChoice } from '../types-BNq9tWdA.js';
5
5
  import { GuardrailPolicyInput } from '../guardrails/index.js';
6
- import { P as PromptHook } from '../types-BaYwqozV.js';
7
- import { a as McpServer } from '../types-BG3s2WzI.js';
8
- import { M as MemoryStore, a as MemoryOptions } from '../types-CNeDsGjw.js';
9
- import { b as AgentObserver, O as ObserveOptions } from '../index-ZQAiHW5Q.js';
10
- import { a as SkillSet } from '../types-BZQlZ4Vs.js';
11
- import { k as ToolSearchDocument, l as ToolSet, A as AgentMiddleware, e as ToolMiddleware } from '../middleware-Cc_-sosu.js';
12
- import { A as AnyTool, e as ToolApprovalsOptions } from '../tool-6f9bK92X.js';
13
- import { a as VectorSearchIndex } from '../types-C708DOhL.js';
6
+ import { P as PromptHook } from '../types-BjPcB4PA.js';
7
+ import { a as McpServer } from '../types-CibT6_rS.js';
8
+ import { e as MemoryStore, f as MemoryOptions } from '../types-CaXSh3vK.js';
9
+ import { b as AgentObserver, O as ObserveOptions } from '../index-BtyK30mL.js';
10
+ import { a as SkillSet } from '../types-Cz24JCei.js';
11
+ import { k as ToolSearchDocument, l as ToolSet, A as AgentMiddleware, e as ToolMiddleware } from '../middleware-D6p0Uzky.js';
12
+ import { A as AnyTool, e as ToolApprovalsOptions } from '../tool-DhT6kR0Z.js';
13
+ import { a as VectorSearchIndex } from '../types-9TeQF79I.js';
14
14
  import 'zod';
15
15
  import '@modelcontextprotocol/sdk/client/sse.js';
16
16
  import '@modelcontextprotocol/sdk/client/stdio.js';
@@ -1,19 +1,19 @@
1
1
  import {
2
2
  AgentBuilder
3
- } from "../chunk-AWTFWDMY.js";
4
- import "../chunk-J3R7WC2W.js";
5
- import "../chunk-VPRJIWTP.js";
3
+ } from "../chunk-6FLW6XS6.js";
4
+ import "../chunk-LJT67CFB.js";
5
+ import "../chunk-3LB36HON.js";
6
6
  import "../chunk-YK4WAAS4.js";
7
7
  import "../chunk-XUUY2L2D.js";
8
- import "../chunk-WHHQWT7D.js";
9
- import "../chunk-I7TM7TKX.js";
8
+ import "../chunk-XH6LZMGH.js";
9
+ import "../chunk-F3C5653H.js";
10
10
  import "../chunk-2ODTMRHP.js";
11
11
  import "../chunk-M6RPFHG7.js";
12
- import "../chunk-YTF65GYU.js";
13
- import "../chunk-CNTGKNZ3.js";
14
- import "../chunk-WQKHFADH.js";
15
12
  import "../chunk-YBBD4HZ3.js";
16
13
  import "../chunk-OIMLU4SF.js";
14
+ import "../chunk-IBKCOBAS.js";
15
+ import "../chunk-FE5QL4G3.js";
16
+ import "../chunk-WQKHFADH.js";
17
17
  import "../chunk-CWUJUSOS.js";
18
18
  export {
19
19
  AgentBuilder
@@ -1,11 +1,25 @@
1
- import { C as CompletionModel, M as Message, D as Document, f as JsonValue, t as ToolChoice, J as JsonObject } from './types-DzdJOf35.js';
1
+ import { C as CompletionModel, M as Message, D as Document, g as JsonValue, v as ToolChoice, J as JsonObject } from './types-BNq9tWdA.js';
2
2
  import { GuardrailPolicyInput, GuardrailPolicy } from './guardrails/index.js';
3
- import { P as PromptHook } from './types-BaYwqozV.js';
4
- import { c as MemoryContext, e as MemoryRegistration, S as SessionOptions } from './types-CNeDsGjw.js';
5
- import { c as AgentTraceOptions, P as PromptResponse, a as AgentStreamEvent, d as AgentObserverRegistration } from './index-ZQAiHW5Q.js';
6
- import { e as ToolApprovalsOptions, T as Tool, A as AnyTool, f as ToolCallContext, N as NormalizedToolOutput } from './tool-6f9bK92X.js';
7
- import { A as AgentMiddleware, e as ToolMiddleware, k as ToolSearchDocument, l as ToolSet } from './middleware-Cc_-sosu.js';
8
- import { V as VectorFilter, c as VectorSearchResult, a as VectorSearchIndex } from './types-C708DOhL.js';
3
+ import { P as PromptHook } from './types-BjPcB4PA.js';
4
+ import { h as MemoryContext, j as MemoryRegistration, S as SessionOptions } from './types-CaXSh3vK.js';
5
+ import { c as AgentTraceOptions, P as PromptResponse, a as AgentStreamEvent, d as AgentObserverRegistration } from './index-BtyK30mL.js';
6
+ import { e as ToolApprovalsOptions, T as Tool, A as AnyTool, f as ToolCallContext, N as NormalizedToolOutput } from './tool-DhT6kR0Z.js';
7
+ import { A as AgentMiddleware, e as ToolMiddleware, k as ToolSearchDocument, l as ToolSet } from './middleware-D6p0Uzky.js';
8
+ import { V as VectorFilter, c as VectorSearchResult, a as VectorSearchIndex } from './types-9TeQF79I.js';
9
+
10
+ type CompletionRetryContext = {
11
+ error: unknown;
12
+ attempt: number;
13
+ maxAttempts: number;
14
+ turn: number;
15
+ streaming: boolean;
16
+ };
17
+ type CompletionRetryOptions = {
18
+ maxAttempts?: number | undefined;
19
+ initialDelayMs?: number | undefined;
20
+ maxDelayMs?: number | undefined;
21
+ shouldRetry?: ((context: CompletionRetryContext) => boolean) | undefined;
22
+ };
9
23
 
10
24
  declare class PromptRequest<M extends CompletionModel = CompletionModel> {
11
25
  private readonly agent;
@@ -19,6 +33,7 @@ declare class PromptRequest<M extends CompletionModel = CompletionModel> {
19
33
  private guardrailDecisions;
20
34
  private concurrency;
21
35
  private traceOptions;
36
+ private completionRetryOptions;
22
37
  private requestMiddlewares;
23
38
  private readonly steeringMessages;
24
39
  private runState;
@@ -28,6 +43,7 @@ declare class PromptRequest<M extends CompletionModel = CompletionModel> {
28
43
  memoryContext?: MemoryContext | undefined;
29
44
  }): PromptRequest<M>;
30
45
  maxTurns(maxTurns: number): this;
46
+ withCompletionRetries(options?: CompletionRetryOptions): this;
31
47
  withHook(hook: PromptHook): this;
32
48
  approvals(options: ToolApprovalsOptions): this;
33
49
  guardrails(policies: GuardrailPolicyInput): this;
@@ -52,8 +68,11 @@ declare class PromptRequest<M extends CompletionModel = CompletionModel> {
52
68
  stream(): AsyncIterable<AgentStreamEvent>;
53
69
  readableStream(): ReadableStream<Uint8Array>;
54
70
  private runCompletion;
71
+ private generatedAssistantMessage;
55
72
  private providerTraceRequest;
56
73
  private generationStartArgs;
74
+ private retryOptionsForFailure;
75
+ private scheduleCompletionRetry;
57
76
  private executeToolCalls;
58
77
  private runOutputGuardrailsForResponse;
59
78
  private recordGuardrailDecision;
@@ -209,4 +228,4 @@ declare class AgentSession<M extends CompletionModel = CompletionModel> {
209
228
  clear(): Promise<void>;
210
229
  }
211
230
 
212
- export { Agent as A, type DynamicContextOptions as D, PromptRequest as P, type DynamicToolOptions as a, type AgentEventStore as b, type AgentEventStoreOptions as c, type AgentEventAppendInput as d, type AgentEventRecord as e, type AgentEventStoreInclude as f, AgentSession as g, type AgentToolOptions as h, type AgentEventStoreRegistration as i, type AgentOptions as j, DEFAULT_MAX_TURNS as k, type DynamicContextRegistration as l, type DynamicToolRegistration as m };
231
+ export { Agent as A, type CompletionRetryContext as C, type DynamicContextOptions as D, PromptRequest as P, type CompletionRetryOptions as a, type DynamicToolOptions as b, type AgentEventStore as c, type AgentEventStoreOptions as d, type AgentEventAppendInput as e, type AgentEventRecord as f, type AgentEventStoreInclude as g, AgentSession as h, type AgentToolOptions as i, type AgentEventStoreRegistration as j, type AgentOptions as k, DEFAULT_MAX_TURNS as l, type DynamicContextRegistration as m, type DynamicToolRegistration as n };
@@ -1,4 +1,4 @@
1
- import { f as JsonValue } from '../types-DzdJOf35.js';
1
+ import { g as JsonValue } from '../types-BNq9tWdA.js';
2
2
 
3
3
  type AudioGenerationRequest = {
4
4
  text: string;
@@ -4,15 +4,18 @@ import {
4
4
  import {
5
5
  parseToolArgs,
6
6
  toolResultContentToText
7
- } from "./chunk-WHHQWT7D.js";
7
+ } from "./chunk-XH6LZMGH.js";
8
8
  import {
9
9
  runControl,
10
10
  toolCallControl
11
11
  } from "./chunk-2ODTMRHP.js";
12
+ import {
13
+ mapWithConcurrency
14
+ } from "./chunk-OIMLU4SF.js";
12
15
  import {
13
16
  CompletionRequestBuilder,
14
17
  isStreamingCompletionModel
15
- } from "./chunk-YTF65GYU.js";
18
+ } from "./chunk-IBKCOBAS.js";
16
19
  import {
17
20
  AssistantContent,
18
21
  Message,
@@ -20,10 +23,7 @@ import {
20
23
  Usage,
21
24
  assertCompletionRequestSupported,
22
25
  textFromAssistantContent
23
- } from "./chunk-CNTGKNZ3.js";
24
- import {
25
- mapWithConcurrency
26
- } from "./chunk-OIMLU4SF.js";
26
+ } from "./chunk-FE5QL4G3.js";
27
27
  import {
28
28
  appendGuardrailPolicies,
29
29
  hasEnforcedOutputGuardrails,
@@ -1277,6 +1277,155 @@ var ActiveToolObservers = class {
1277
1277
  }
1278
1278
  };
1279
1279
 
1280
+ // src/request/retry.ts
1281
+ var DEFAULT_MAX_ATTEMPTS = 3;
1282
+ var DEFAULT_INITIAL_DELAY_MS = 100;
1283
+ var DEFAULT_MAX_DELAY_MS = 1e3;
1284
+ var MAX_TIMER_DELAY_MS = 2147483647;
1285
+ var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 409, 425, 429]);
1286
+ var RETRYABLE_NUMERIC_ERROR_CODES = /* @__PURE__ */ new Set([4, 8, 14]);
1287
+ var RETRYABLE_ERROR_NAMES = /* @__PURE__ */ new Set([
1288
+ "APIConnectionError",
1289
+ "APIConnectionTimeoutError",
1290
+ "TimeoutError"
1291
+ ]);
1292
+ var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
1293
+ "DEADLINE_EXCEEDED",
1294
+ "EAI_AGAIN",
1295
+ "ECONNREFUSED",
1296
+ "ECONNRESET",
1297
+ "EHOSTUNREACH",
1298
+ "ENETDOWN",
1299
+ "ENETUNREACH",
1300
+ "EPIPE",
1301
+ "ETIMEDOUT",
1302
+ "RESOURCE_EXHAUSTED",
1303
+ "UNAVAILABLE",
1304
+ "UND_ERR_CONNECT_TIMEOUT",
1305
+ "UND_ERR_HEADERS_TIMEOUT",
1306
+ "UND_ERR_SOCKET"
1307
+ ]);
1308
+ function resolveCompletionRetryOptions(options) {
1309
+ const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
1310
+ const initialDelayMs = options.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
1311
+ const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
1312
+ if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1) {
1313
+ throw new RangeError("Completion retry maxAttempts must be a positive integer.");
1314
+ }
1315
+ assertDelay(initialDelayMs, "initialDelayMs");
1316
+ assertDelay(maxDelayMs, "maxDelayMs");
1317
+ if (maxDelayMs < initialDelayMs) {
1318
+ throw new RangeError(
1319
+ "Completion retry maxDelayMs must be greater than or equal to initialDelayMs."
1320
+ );
1321
+ }
1322
+ if (options.shouldRetry !== void 0 && typeof options.shouldRetry !== "function") {
1323
+ throw new TypeError("Completion retry shouldRetry must be a function.");
1324
+ }
1325
+ return {
1326
+ maxAttempts,
1327
+ initialDelayMs,
1328
+ maxDelayMs,
1329
+ shouldRetry: options.shouldRetry ?? defaultShouldRetry
1330
+ };
1331
+ }
1332
+ function completionRetryDelayMs(options, failedAttempt) {
1333
+ const exponentialDelay = options.initialDelayMs * 2 ** (failedAttempt - 1);
1334
+ const cappedDelay = Math.min(options.maxDelayMs, exponentialDelay);
1335
+ return Math.random() * cappedDelay;
1336
+ }
1337
+ function completionRetryErrorAttributes(error) {
1338
+ const errors = errorChain(error);
1339
+ const errorName = errors.map((candidate) => stringProperty(candidate, "name")).find((value) => value !== void 0);
1340
+ const statusCode = firstStatusCode(errors);
1341
+ const errorCode = errors.map((candidate) => errorCodeProperty(candidate)).find((value) => value !== void 0);
1342
+ return {
1343
+ errorName,
1344
+ statusCode,
1345
+ errorCode
1346
+ };
1347
+ }
1348
+ async function waitForCompletionRetry(delayMs) {
1349
+ if (delayMs === 0) {
1350
+ return;
1351
+ }
1352
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1353
+ }
1354
+ function defaultShouldRetry(context) {
1355
+ const errors = errorChain(context.error);
1356
+ if (errors.some((error) => stringProperty(error, "name") === "AbortError")) {
1357
+ return false;
1358
+ }
1359
+ const statusCode = firstStatusCode(errors);
1360
+ if (statusCode !== void 0) {
1361
+ return RETRYABLE_STATUS_CODES.has(statusCode) || statusCode >= 500 && statusCode <= 599;
1362
+ }
1363
+ return errors.some((error) => {
1364
+ const name = stringProperty(error, "name");
1365
+ if (name !== void 0 && RETRYABLE_ERROR_NAMES.has(name)) {
1366
+ return true;
1367
+ }
1368
+ const code = stringProperty(error, "code")?.toUpperCase();
1369
+ if (code !== void 0 && RETRYABLE_ERROR_CODES.has(code)) {
1370
+ return true;
1371
+ }
1372
+ const numericCode = numberProperty(error, "code");
1373
+ return numericCode !== void 0 && RETRYABLE_NUMERIC_ERROR_CODES.has(numericCode);
1374
+ });
1375
+ }
1376
+ function firstStatusCode(errors) {
1377
+ for (const error of errors) {
1378
+ const status = numberProperty(error, "status") ?? numberProperty(error, "statusCode");
1379
+ if (status !== void 0) {
1380
+ return status;
1381
+ }
1382
+ const code = numberProperty(error, "code");
1383
+ if (code !== void 0 && code >= 100 && code <= 599) {
1384
+ return code;
1385
+ }
1386
+ }
1387
+ return void 0;
1388
+ }
1389
+ function errorChain(error) {
1390
+ const errors = [];
1391
+ const seen = /* @__PURE__ */ new Set();
1392
+ let current = error;
1393
+ while (isObject(current) && !seen.has(current)) {
1394
+ seen.add(current);
1395
+ errors.push(current);
1396
+ current = property(current, "cause");
1397
+ }
1398
+ return errors;
1399
+ }
1400
+ function assertDelay(value, name) {
1401
+ if (!Number.isFinite(value) || value < 0 || value > MAX_TIMER_DELAY_MS) {
1402
+ throw new RangeError(
1403
+ `Completion retry ${name} must be between 0 and ${MAX_TIMER_DELAY_MS} milliseconds.`
1404
+ );
1405
+ }
1406
+ }
1407
+ function numberProperty(value, name) {
1408
+ const candidate = property(value, name);
1409
+ return typeof candidate === "number" && Number.isFinite(candidate) ? candidate : void 0;
1410
+ }
1411
+ function stringProperty(value, name) {
1412
+ const candidate = property(value, name);
1413
+ return typeof candidate === "string" && candidate.length > 0 ? candidate : void 0;
1414
+ }
1415
+ function errorCodeProperty(value) {
1416
+ return stringProperty(value, "code") ?? numberProperty(value, "code");
1417
+ }
1418
+ function property(value, name) {
1419
+ try {
1420
+ return value[name];
1421
+ } catch {
1422
+ return void 0;
1423
+ }
1424
+ }
1425
+ function isObject(value) {
1426
+ return typeof value === "object" && value !== null;
1427
+ }
1428
+
1280
1429
  // src/request/prompt-request.ts
1281
1430
  var PromptRequest = class _PromptRequest {
1282
1431
  constructor(agent, promptMessage, initialHistory = [], memoryContext = void 0) {
@@ -1301,6 +1450,7 @@ var PromptRequest = class _PromptRequest {
1301
1450
  guardrailDecisions = [];
1302
1451
  concurrency = 1;
1303
1452
  traceOptions;
1453
+ completionRetryOptions;
1304
1454
  requestMiddlewares = [];
1305
1455
  steeringMessages = [];
1306
1456
  runState = "idle";
@@ -1313,6 +1463,10 @@ var PromptRequest = class _PromptRequest {
1313
1463
  this.maxTurnCount = maxTurns;
1314
1464
  return this;
1315
1465
  }
1466
+ withCompletionRetries(options = {}) {
1467
+ this.completionRetryOptions = resolveCompletionRetryOptions(options);
1468
+ return this;
1469
+ }
1316
1470
  withHook(hook) {
1317
1471
  this.activeHook = hook;
1318
1472
  return this;
@@ -1433,7 +1587,7 @@ var PromptRequest = class _PromptRequest {
1433
1587
  const toolCalls = response.choice.filter(
1434
1588
  (item) => item.type === "tool_call"
1435
1589
  );
1436
- const assistantMessage = Message.assistant(response.choice, response.messageId);
1590
+ const assistantMessage = this.generatedAssistantMessage(response, request);
1437
1591
  newMessages.push(assistantMessage);
1438
1592
  if (toolCalls.length === 0) {
1439
1593
  if (this.steeringMessages.length > 0) {
@@ -1456,7 +1610,7 @@ var PromptRequest = class _PromptRequest {
1456
1610
  runObservers
1457
1611
  );
1458
1612
  response = guardedOutput.response;
1459
- const finalAssistantMessage = Message.assistant(response.choice, response.messageId);
1613
+ const finalAssistantMessage = this.generatedAssistantMessage(response, request);
1460
1614
  newMessages[newMessages.length - 1] = finalAssistantMessage;
1461
1615
  await this.memoryRecorder.commitMessages(
1462
1616
  runId,
@@ -1608,26 +1762,46 @@ var PromptRequest = class _PromptRequest {
1608
1762
  const emittedToolCallIds = /* @__PURE__ */ new Set();
1609
1763
  let response;
1610
1764
  try {
1611
- for await (const event of this.agent.model.streamCompletion(request)) {
1612
- if (firstDeltaMs === void 0 && isGenerationDeltaEvent(event.type)) {
1613
- firstDeltaMs = Date.now() - generationStartedAt;
1614
- }
1615
- const mapped = accumulator.accept(event);
1616
- if (event.type === "error") {
1617
- throw event.error;
1618
- }
1619
- if (mapped !== void 0) {
1620
- await generationObservers.update?.({ turn: currentTurns, delta: mapped });
1621
- if (mapped.type === "tool_call") {
1622
- emittedToolCallIds.add(mapped.toolCall.id);
1765
+ for (let attempt = 1; ; attempt += 1) {
1766
+ let hasProviderProgress = false;
1767
+ try {
1768
+ for await (const event of this.agent.model.streamCompletion(request)) {
1769
+ if (event.type === "error") {
1770
+ throw event.error;
1771
+ }
1772
+ hasProviderProgress = true;
1773
+ if (firstDeltaMs === void 0 && isGenerationDeltaEvent(event.type)) {
1774
+ firstDeltaMs = Date.now() - generationStartedAt;
1775
+ }
1776
+ const mapped = accumulator.accept(event);
1777
+ if (mapped !== void 0) {
1778
+ await generationObservers.update?.({ turn: currentTurns, delta: mapped });
1779
+ if (mapped.type === "tool_call") {
1780
+ emittedToolCallIds.add(mapped.toolCall.id);
1781
+ }
1782
+ const shouldBuffer = bufferResponseEvents || bufferOutputDeltas && (mapped.type === "text_delta" || mapped.type === "reasoning_delta");
1783
+ if (!shouldBuffer) {
1784
+ yield await emit(addTurn(currentTurns, mapped));
1785
+ }
1786
+ }
1623
1787
  }
1624
- const shouldBuffer = bufferResponseEvents || bufferOutputDeltas && (mapped.type === "text_delta" || mapped.type === "reasoning_delta");
1625
- if (!shouldBuffer) {
1626
- yield await emit(addTurn(currentTurns, mapped));
1788
+ response = accumulator.response();
1789
+ break;
1790
+ } catch (error) {
1791
+ const retryOptions = hasProviderProgress ? void 0 : this.retryOptionsForFailure(error, attempt, currentTurns, true);
1792
+ if (retryOptions === void 0) {
1793
+ throw error;
1627
1794
  }
1795
+ await this.scheduleCompletionRetry(
1796
+ error,
1797
+ attempt,
1798
+ currentTurns,
1799
+ true,
1800
+ retryOptions,
1801
+ runObservers
1802
+ );
1628
1803
  }
1629
1804
  }
1630
- response = accumulator.response();
1631
1805
  } catch (error) {
1632
1806
  await generationObservers.error({ turn: currentTurns, error });
1633
1807
  await this.runCompletionErrorHook(prompt, error, newMessages);
@@ -1648,7 +1822,7 @@ var PromptRequest = class _PromptRequest {
1648
1822
  const toolCalls = response.choice.filter(
1649
1823
  (item) => item.type === "tool_call"
1650
1824
  );
1651
- let assistantMessage = Message.assistant(response.choice, response.messageId);
1825
+ let assistantMessage = this.generatedAssistantMessage(response, request);
1652
1826
  newMessages.push(assistantMessage);
1653
1827
  if (toolCalls.length === 0) {
1654
1828
  let emittedTurnEnd = false;
@@ -1684,7 +1858,7 @@ var PromptRequest = class _PromptRequest {
1684
1858
  yield await emit({ type: "guardrail_decision", decision });
1685
1859
  }
1686
1860
  response = guardedOutput.response;
1687
- assistantMessage = Message.assistant(response.choice, response.messageId);
1861
+ assistantMessage = this.generatedAssistantMessage(response, request);
1688
1862
  newMessages[newMessages.length - 1] = assistantMessage;
1689
1863
  await this.memoryRecorder.commitMessages(
1690
1864
  runId,
@@ -1801,14 +1975,48 @@ var PromptRequest = class _PromptRequest {
1801
1975
  this.generationStartArgs(turn, request, providerRequest)
1802
1976
  );
1803
1977
  try {
1804
- const response = await this.agent.model.completion(request);
1805
- await generationObservers.end({ turn, response });
1806
- return response;
1978
+ for (let attempt = 1; ; attempt += 1) {
1979
+ let response;
1980
+ try {
1981
+ response = await this.agent.model.completion(request);
1982
+ } catch (error) {
1983
+ const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
1984
+ if (retryOptions === void 0) {
1985
+ throw error;
1986
+ }
1987
+ await this.scheduleCompletionRetry(
1988
+ error,
1989
+ attempt,
1990
+ turn,
1991
+ false,
1992
+ retryOptions,
1993
+ runObservers
1994
+ );
1995
+ continue;
1996
+ }
1997
+ await generationObservers.end({ turn, response });
1998
+ return response;
1999
+ }
1807
2000
  } catch (error) {
1808
2001
  await generationObservers.error({ turn, error });
1809
2002
  throw error;
1810
2003
  }
1811
2004
  }
2005
+ generatedAssistantMessage(response, request) {
2006
+ const metadata = {
2007
+ anvia: {
2008
+ generation: {
2009
+ provider: this.agent.model.provider,
2010
+ model: request.model ?? this.agent.model.defaultModel,
2011
+ usage: { ...response.usage }
2012
+ }
2013
+ }
2014
+ };
2015
+ return Message.assistant(response.choice, {
2016
+ ...response.messageId === void 0 ? {} : { id: response.messageId },
2017
+ metadata
2018
+ });
2019
+ }
1812
2020
  providerTraceRequest(request, options = {}) {
1813
2021
  try {
1814
2022
  return this.agent.model.traceRequest?.(request, options);
@@ -1833,6 +2041,37 @@ var PromptRequest = class _PromptRequest {
1833
2041
  }
1834
2042
  return args;
1835
2043
  }
2044
+ retryOptionsForFailure(error, attempt, turn, streaming) {
2045
+ const options = this.completionRetryOptions;
2046
+ if (options === void 0 || attempt >= options.maxAttempts) {
2047
+ return void 0;
2048
+ }
2049
+ const shouldRetry = options.shouldRetry({
2050
+ error,
2051
+ attempt,
2052
+ maxAttempts: options.maxAttempts,
2053
+ turn,
2054
+ streaming
2055
+ });
2056
+ return shouldRetry ? options : void 0;
2057
+ }
2058
+ async scheduleCompletionRetry(error, attempt, turn, streaming, options, runObservers) {
2059
+ const delayMs = completionRetryDelayMs(options, attempt);
2060
+ await runObservers.event({
2061
+ name: "completion.retry",
2062
+ level: "WARNING",
2063
+ attributes: {
2064
+ turn,
2065
+ attempt,
2066
+ nextAttempt: attempt + 1,
2067
+ maxAttempts: options.maxAttempts,
2068
+ delayMs,
2069
+ streaming,
2070
+ ...completionRetryErrorAttributes(error)
2071
+ }
2072
+ });
2073
+ await waitForCompletionRetry(delayMs);
2074
+ }
1836
2075
  async executeToolCalls(runId, toolCalls, newMessages, onResult, onStreamEvent, observation) {
1837
2076
  const executor = new ToolCallExecutor(
1838
2077
  this.agent,
@@ -2203,4 +2442,4 @@ export {
2203
2442
  extractRagText,
2204
2443
  PromptRequest
2205
2444
  };
2206
- //# sourceMappingURL=chunk-VPRJIWTP.js.map
2445
+ //# sourceMappingURL=chunk-3LB36HON.js.map