@linnlabs/linnkit 0.37.4 → 0.38.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 (68) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/cli.cjs +347 -179
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +347 -179
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +55 -11
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +55 -11
  9. package/dist/context-manager.js.map +1 -1
  10. package/dist/contracts/audit.d.cts +6 -6
  11. package/dist/contracts/audit.d.ts +6 -6
  12. package/dist/contracts/events.d.cts +532 -50
  13. package/dist/contracts/events.d.ts +532 -50
  14. package/dist/contracts/llm-retry.d.cts +47 -0
  15. package/dist/contracts/llm-retry.d.ts +47 -0
  16. package/dist/contracts/messages.d.cts +2 -2
  17. package/dist/contracts/messages.d.ts +2 -2
  18. package/dist/contracts/runtime-error.d.cts +26 -0
  19. package/dist/contracts/runtime-error.d.ts +26 -0
  20. package/dist/contracts/sse.d.cts +571 -55
  21. package/dist/contracts/sse.d.ts +571 -55
  22. package/dist/contracts/sub-run-trace-payload.d.cts +102 -6
  23. package/dist/contracts/sub-run-trace-payload.d.ts +102 -6
  24. package/dist/contracts/token-accounting.d.cts +18 -18
  25. package/dist/contracts/token-accounting.d.ts +18 -18
  26. package/dist/contracts.cjs +65 -10
  27. package/dist/contracts.cjs.map +1 -1
  28. package/dist/contracts.d.cts +4 -2
  29. package/dist/contracts.d.ts +4 -2
  30. package/dist/contracts.js +62 -11
  31. package/dist/contracts.js.map +1 -1
  32. package/dist/index.cjs +506 -286
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.js +506 -286
  35. package/dist/index.js.map +1 -1
  36. package/dist/ports/canonical-inference.d.cts +3 -0
  37. package/dist/ports/canonical-inference.d.ts +3 -0
  38. package/dist/ports/llm-call.d.cts +4 -0
  39. package/dist/ports/llm-call.d.ts +4 -0
  40. package/dist/quickstart.cjs +347 -179
  41. package/dist/quickstart.cjs.map +1 -1
  42. package/dist/quickstart.js +347 -179
  43. package/dist/quickstart.js.map +1 -1
  44. package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.cts +8 -0
  45. package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.ts +8 -0
  46. package/dist/runtime-kernel/events/agentEvents.d.cts +85 -4
  47. package/dist/runtime-kernel/events/agentEvents.d.ts +85 -4
  48. package/dist/runtime-kernel/events/eventGovernance.d.cts +1 -1
  49. package/dist/runtime-kernel/events/eventGovernance.d.ts +1 -1
  50. package/dist/runtime-kernel/events.cjs +55 -11
  51. package/dist/runtime-kernel/events.cjs.map +1 -1
  52. package/dist/runtime-kernel/events.js +55 -11
  53. package/dist/runtime-kernel/events.js.map +1 -1
  54. package/dist/runtime-kernel/llm/request-builder.d.cts +2 -0
  55. package/dist/runtime-kernel/llm/request-builder.d.ts +2 -0
  56. package/dist/runtime-kernel.cjs +468 -271
  57. package/dist/runtime-kernel.cjs.map +1 -1
  58. package/dist/runtime-kernel.js +468 -271
  59. package/dist/runtime-kernel.js.map +1 -1
  60. package/dist/shared/errorClassifier.d.cts +5 -0
  61. package/dist/shared/errorClassifier.d.ts +5 -0
  62. package/dist/testkit.cjs +466 -269
  63. package/dist/testkit.cjs.map +1 -1
  64. package/dist/testkit.js +466 -269
  65. package/dist/testkit.js.map +1 -1
  66. package/docs/integration/llm-provider.md +24 -0
  67. package/docs/integration/realtime.md +29 -0
  68. package/package.json +2 -2
package/dist/testkit.cjs CHANGED
@@ -318,11 +318,121 @@ var Logger = class {
318
318
  }
319
319
  }
320
320
  };
321
+ var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
322
+ (value) => value === value.trim(),
323
+ "identity must not contain leading or trailing whitespace"
324
+ );
325
+ var RuntimeEventIdSchema = NonEmptyIdentitySchema;
326
+ var AiMessageIdSchema = NonEmptyIdentitySchema;
327
+ var ConversationIdSchema = NonEmptyIdentitySchema;
328
+ var TurnIdSchema = NonEmptyIdentitySchema;
329
+ var RunIdSchema = NonEmptyIdentitySchema.brand();
330
+ var ExecutionIdSchema = NonEmptyIdentitySchema;
331
+ var TraceIdSchema = NonEmptyIdentitySchema;
332
+ var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
333
+ var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
334
+ var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
335
+ var InteractionIdSchema = NonEmptyIdentitySchema;
336
+ var SubrunIdSchema = NonEmptyIdentitySchema;
337
+ var ResumeTokenSchema = NonEmptyIdentitySchema;
338
+ var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
339
+ var SourceEventIdSchema = RuntimeEventIdSchema;
340
+ var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
341
+ var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
342
+
343
+ // src/contracts/identity/generators.ts
344
+ function randomIdentity(prefix) {
345
+ if (typeof globalThis.crypto?.randomUUID !== "function") {
346
+ throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
347
+ }
348
+ return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
349
+ }
350
+ function generateRuntimeEventId() {
351
+ return randomIdentity("evt");
352
+ }
353
+ function generateAnswerSegmentId() {
354
+ return randomIdentity("answer");
355
+ }
356
+ function generateTurnId() {
357
+ return randomIdentity("turn");
358
+ }
359
+ function generateRunId() {
360
+ return RunIdSchema.parse(randomIdentity("run"));
361
+ }
362
+ function generateExecutionId() {
363
+ return randomIdentity("exec");
364
+ }
365
+ function generateTraceId() {
366
+ return randomIdentity("trace");
367
+ }
368
+ function generateInferenceAttemptId() {
369
+ return randomIdentity("inference-attempt");
370
+ }
371
+ function generateThoughtMessageId() {
372
+ return randomIdentity("thought");
373
+ }
374
+ function generateToolCallId() {
375
+ return ToolCallIdSchema.parse(randomIdentity("call"));
376
+ }
377
+ function generateInteractionId() {
378
+ return randomIdentity("interaction");
379
+ }
380
+ function generateResumeToken() {
381
+ return randomIdentity("resume");
382
+ }
383
+ function generateRunResumeClaimId() {
384
+ return randomIdentity("resume-claim");
385
+ }
386
+ function generateAuditEnvelopeId() {
387
+ return randomIdentity("audit");
388
+ }
389
+ function generateContextLedgerEntryId() {
390
+ return randomIdentity("context-ledger");
391
+ }
392
+ function runIdFromTurnId(turnId) {
393
+ return RunIdSchema.parse(turnId);
394
+ }
395
+
396
+ // src/contracts/identity/invariants.ts
397
+ function assertCanonicalFinalAnswerIdentity(input) {
398
+ const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
399
+ if (input.id !== answerId) {
400
+ throw new Error(
401
+ `final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
402
+ );
403
+ }
404
+ return answerId;
405
+ }
406
+ function assertDistinctAnswerChunkIdentity(input) {
407
+ if (input.id === input.answer_id) {
408
+ throw new Error(
409
+ `final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
410
+ );
411
+ }
412
+ }
413
+
414
+ // src/contracts/llm-retry.ts
415
+ var LlmRetryCategory = zod.z.enum(["transport", "output", "rate_limit", "other"]);
416
+ var LlmRetryState = zod.z.object({
417
+ retry_id: TraceIdSchema,
418
+ status: zod.z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
419
+ category: LlmRetryCategory,
420
+ attempt: zod.z.number().int().nonnegative(),
421
+ max_retries: zod.z.number().int().nonnegative(),
422
+ total_attempts: zod.z.number().int().positive(),
423
+ started_at: zod.z.number().finite(),
424
+ delay_ms: zod.z.number().finite().nonnegative(),
425
+ next_retry_at: zod.z.number().finite().optional(),
426
+ /** 安全分类说明;不得放入供应商响应正文。 */
427
+ error: zod.z.string(),
428
+ error_code: zod.z.string().min(1)
429
+ }).strict();
321
430
 
322
431
  // src/shared/errorClassifier.ts
323
432
  var ENGINE_ERROR_CODES = {
324
433
  LLM_RATE_LIMIT: "llm.rate_limit",
325
434
  LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
435
+ LLM_EMPTY_RESPONSE: "llm.empty_response",
326
436
  LLM_PROVIDER_DOWN: "llm.provider_down",
327
437
  LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
328
438
  LLM_AUTH_FAILED: "llm.auth_failed",
@@ -433,6 +543,8 @@ function readStructuredClassification(error) {
433
543
  if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
434
544
  if (typeof recoverable !== "boolean") return void 0;
435
545
  const errorCode = rawErrorCode.trim();
546
+ const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
547
+ const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
436
548
  const retryAfterMsValue = error["retryAfterMs"];
437
549
  const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
438
550
  const hintValue = error["hint"];
@@ -440,12 +552,13 @@ function readStructuredClassification(error) {
440
552
  const metadataValue = error["metadata"];
441
553
  const metadata = isRecord(metadataValue) ? metadataValue : void 0;
442
554
  return createClassification(
443
- recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
555
+ recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
444
556
  `\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
445
557
  recoverable ? retryAfterMs ?? 1e3 : null,
446
558
  {
447
559
  errorCode,
448
560
  recoverable,
561
+ ...retryCategory === void 0 ? {} : { retryCategory },
449
562
  ...retryAfterMs === void 0 ? {} : { retryAfterMs },
450
563
  ...hint === void 0 ? {} : { hint },
451
564
  ...metadata === void 0 ? {} : { metadata }
@@ -720,7 +833,7 @@ var ErrorClassifier = class {
720
833
  if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
721
834
  logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
722
835
  return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
723
- errorCode: ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN,
836
+ errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
724
837
  recoverable: true,
725
838
  retryAfterMs: 1e3,
726
839
  hint: "retry_with_backoff",
@@ -745,15 +858,23 @@ var ErrorClassifier = class {
745
858
  const category = this.categorize(error);
746
859
  return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
747
860
  }
861
+ static getRetryCategory(classification) {
862
+ if (classification.retryCategory !== void 0) return classification.retryCategory;
863
+ if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
864
+ if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
865
+ if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
866
+ return "other";
867
+ }
748
868
  static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
749
869
  const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
750
870
  if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
751
871
  return 0;
752
872
  }
753
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
754
- return Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay);
873
+ const retryCategory = this.getRetryCategory(classification);
874
+ if (retryCategory === "rate_limit" || retryCategory === "transport") {
875
+ return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
755
876
  }
756
- return classification.suggestedDelay || baseDelay;
877
+ return Math.max(baseDelay, classification.suggestedDelay ?? 0);
757
878
  }
758
879
  static isCloudQuotaError(error) {
759
880
  const msg = (error.message || "").toLowerCase();
@@ -792,98 +913,6 @@ var RuntimeResourceRef = zod.z.object({
792
913
  label: LabelSchema.optional()
793
914
  }).strict();
794
915
  var RuntimeResourceRefs = zod.z.array(RuntimeResourceRef).min(1);
795
- var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
796
- (value) => value === value.trim(),
797
- "identity must not contain leading or trailing whitespace"
798
- );
799
- var RuntimeEventIdSchema = NonEmptyIdentitySchema;
800
- var AiMessageIdSchema = NonEmptyIdentitySchema;
801
- var ConversationIdSchema = NonEmptyIdentitySchema;
802
- var TurnIdSchema = NonEmptyIdentitySchema;
803
- var RunIdSchema = NonEmptyIdentitySchema.brand();
804
- var ExecutionIdSchema = NonEmptyIdentitySchema;
805
- var TraceIdSchema = NonEmptyIdentitySchema;
806
- var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
807
- var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
808
- var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
809
- var InteractionIdSchema = NonEmptyIdentitySchema;
810
- var SubrunIdSchema = NonEmptyIdentitySchema;
811
- var ResumeTokenSchema = NonEmptyIdentitySchema;
812
- var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
813
- var SourceEventIdSchema = RuntimeEventIdSchema;
814
- var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
815
- var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
816
-
817
- // src/contracts/identity/generators.ts
818
- function randomIdentity(prefix) {
819
- if (typeof globalThis.crypto?.randomUUID !== "function") {
820
- throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
821
- }
822
- return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
823
- }
824
- function generateRuntimeEventId() {
825
- return randomIdentity("evt");
826
- }
827
- function generateAnswerSegmentId() {
828
- return randomIdentity("answer");
829
- }
830
- function generateTurnId() {
831
- return randomIdentity("turn");
832
- }
833
- function generateRunId() {
834
- return RunIdSchema.parse(randomIdentity("run"));
835
- }
836
- function generateExecutionId() {
837
- return randomIdentity("exec");
838
- }
839
- function generateTraceId() {
840
- return randomIdentity("trace");
841
- }
842
- function generateInferenceAttemptId() {
843
- return randomIdentity("inference-attempt");
844
- }
845
- function generateThoughtMessageId() {
846
- return randomIdentity("thought");
847
- }
848
- function generateToolCallId() {
849
- return ToolCallIdSchema.parse(randomIdentity("call"));
850
- }
851
- function generateInteractionId() {
852
- return randomIdentity("interaction");
853
- }
854
- function generateResumeToken() {
855
- return randomIdentity("resume");
856
- }
857
- function generateRunResumeClaimId() {
858
- return randomIdentity("resume-claim");
859
- }
860
- function generateAuditEnvelopeId() {
861
- return randomIdentity("audit");
862
- }
863
- function generateContextLedgerEntryId() {
864
- return randomIdentity("context-ledger");
865
- }
866
- function runIdFromTurnId(turnId) {
867
- return RunIdSchema.parse(turnId);
868
- }
869
-
870
- // src/contracts/identity/invariants.ts
871
- function assertCanonicalFinalAnswerIdentity(input) {
872
- const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
873
- if (input.id !== answerId) {
874
- throw new Error(
875
- `final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
876
- );
877
- }
878
- return answerId;
879
- }
880
- function assertDistinctAnswerChunkIdentity(input) {
881
- if (input.id === input.answer_id) {
882
- throw new Error(
883
- `final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
884
- );
885
- }
886
- }
887
916
  var FinalAnswerCompletionReason = zod.z.enum([
888
917
  "terminal",
889
918
  "tool_call",
@@ -1358,6 +1387,13 @@ var AuditEnvelope = zod.z.object({
1358
1387
  costDelta: AuditCostDelta.optional(),
1359
1388
  scope: AuditScope.optional()
1360
1389
  });
1390
+ var RuntimeErrorState = zod.z.object({
1391
+ error: zod.z.string(),
1392
+ error_code: zod.z.string().optional(),
1393
+ retryable: zod.z.boolean().optional(),
1394
+ retry_id: TraceIdSchema.optional(),
1395
+ details: SerializableJsonValue.optional()
1396
+ }).strict();
1361
1397
  var ToolCallPhase = zod.z.enum(["start", "update", "complete", "error"]);
1362
1398
  var Status = zod.z.enum(["loading", "success", "error"]);
1363
1399
  var SubRunTraceKind = zod.z.enum([
@@ -1368,7 +1404,9 @@ var SubRunTraceKind = zod.z.enum([
1368
1404
  "tool_output",
1369
1405
  "final_answer_chunk",
1370
1406
  "final_answer",
1371
- "history_summary"
1407
+ "history_summary",
1408
+ "llm_retry",
1409
+ "error"
1372
1410
  ]);
1373
1411
  var SubRunTraceToolCallDecision = zod.z.object({
1374
1412
  tool_call_id: ToolCallIdSchema,
@@ -1381,6 +1419,8 @@ var SubRunTracePayload = zod.z.object({
1381
1419
  subrun_parent_id: SubrunIdSchema.optional(),
1382
1420
  source_event_id: SourceEventIdSchema,
1383
1421
  kind: SubRunTraceKind,
1422
+ retry: LlmRetryState.optional(),
1423
+ failure: RuntimeErrorState.optional(),
1384
1424
  delta: zod.z.string().optional(),
1385
1425
  content: zod.z.string().optional(),
1386
1426
  answer_id: AnswerSegmentIdSchema.optional(),
@@ -1403,6 +1443,12 @@ var SubRunTracePayload = zod.z.object({
1403
1443
  meta: SerializableJsonRecord.optional()
1404
1444
  });
1405
1445
  function validateSubRunTracePayloadSemantics(payload, ctx) {
1446
+ if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
1447
+ ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
1448
+ }
1449
+ if (payload.kind === "error" !== (payload.failure !== void 0)) {
1450
+ ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
1451
+ }
1406
1452
  if (payload.kind === "thought_delta" && payload.delta === void 0) {
1407
1453
  ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
1408
1454
  }
@@ -1756,12 +1802,10 @@ var RuntimeEventShape = zod.z.discriminatedUnion("type", [
1756
1802
  compression_ratio: zod.z.number().min(0).max(1).optional(),
1757
1803
  included_old_summary: zod.z.boolean().optional()
1758
1804
  }),
1805
+ BaseEvent.extend({ type: zod.z.literal("llm_retry"), ...LlmRetryState.shape }),
1759
1806
  BaseEvent.extend({
1760
1807
  type: zod.z.literal("error"),
1761
- error: zod.z.string(),
1762
- details: SerializableJsonValue.optional(),
1763
- error_code: zod.z.string().optional(),
1764
- retryable: zod.z.boolean().optional()
1808
+ ...RuntimeErrorState.shape
1765
1809
  }),
1766
1810
  BaseEvent.extend({
1767
1811
  type: zod.z.literal("control"),
@@ -2196,12 +2240,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
2196
2240
  resume_token: ResumeTokenSchema,
2197
2241
  interaction_status: zod.z.literal("pending")
2198
2242
  });
2243
+ var SSELlmRetryEvent = BaseSSEEvent.extend({
2244
+ type: zod.z.literal("llm_retry"),
2245
+ ...LlmRetryState.shape
2246
+ });
2199
2247
  var SSEErrorEvent = BaseSSEEvent.extend({
2200
2248
  type: zod.z.literal("error"),
2201
- error: zod.z.string(),
2202
- details: SerializableJsonValue.optional(),
2203
- error_code: zod.z.string().optional(),
2204
- retryable: zod.z.boolean().optional()
2249
+ ...RuntimeErrorState.shape
2205
2250
  });
2206
2251
  var SSETransportErrorEvent = BaseSSEEvent.extend({
2207
2252
  type: zod.z.literal("transport_error"),
@@ -2284,6 +2329,7 @@ zod.z.discriminatedUnion("type", [
2284
2329
  SSEToolOutputEvent,
2285
2330
  SSESubRunTraceEvent,
2286
2331
  SSERequiresUserInteractionEvent,
2332
+ SSELlmRetryEvent,
2287
2333
  SSEErrorEvent,
2288
2334
  SSETransportErrorEvent,
2289
2335
  SSEContextUsageSnapshotEvent,
@@ -6655,6 +6701,8 @@ function getRuntimeEventUiProjectionKind(event) {
6655
6701
  return "audit_envelope";
6656
6702
  case "subrun_trace":
6657
6703
  return "subrun_trace";
6704
+ case "llm_retry":
6705
+ return "llm_retry";
6658
6706
  case "error":
6659
6707
  return "error";
6660
6708
  case "context_usage_snapshot":
@@ -6684,7 +6732,7 @@ function describeRuntimeEventLifecycle(event) {
6684
6732
  if (isContextUsageSnapshotRuntimeEvent(event)) {
6685
6733
  return false;
6686
6734
  }
6687
- if (event.type === "error") {
6735
+ if (event.type === "error" || event.type === "llm_retry") {
6688
6736
  return false;
6689
6737
  }
6690
6738
  if (isRequiresUserInteractionRuntimeEvent(event)) {
@@ -6727,6 +6775,7 @@ function describeRuntimeEventLifecycle(event) {
6727
6775
  case "tool_output":
6728
6776
  case "requires_user_interaction":
6729
6777
  case "subrun_trace":
6778
+ case "llm_retry":
6730
6779
  case "error":
6731
6780
  case "context_usage_snapshot":
6732
6781
  case "run_execution_metrics":
@@ -6943,8 +6992,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
6943
6992
  assistant_replay_parts: AssistantReplayParts.optional(),
6944
6993
  meta: UnknownRecord.optional()
6945
6994
  }).strict();
6995
+ var LlmRetryEventSchema = BaseAgentEvent.extend({
6996
+ type: zod.z.literal("llm_retry"),
6997
+ ...LlmRetryState.shape
6998
+ }).strict();
6946
6999
  var ErrorEventSchema = BaseAgentEvent.extend({
6947
7000
  type: zod.z.literal("error"),
7001
+ retry_id: LlmRetryState.shape.retry_id.optional(),
6948
7002
  error: zod.z.string(),
6949
7003
  error_code: zod.z.string().optional(),
6950
7004
  retryable: zod.z.boolean().optional(),
@@ -6974,6 +7028,7 @@ var AgentEventSchema = zod.z.discriminatedUnion("type", [
6974
7028
  ToolProcessEventSchema,
6975
7029
  ObservationEventSchema,
6976
7030
  FinalAnswerEventSchema,
7031
+ LlmRetryEventSchema,
6977
7032
  ErrorEventSchema,
6978
7033
  StreamChunkEventSchema,
6979
7034
  StreamResetEventSchema,
@@ -7074,13 +7129,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
7074
7129
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
7075
7130
  return event;
7076
7131
  }
7132
+ case "llm_retry":
7133
+ return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
7077
7134
  case "error": {
7078
7135
  const errorEvent = typed;
7079
7136
  const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
7080
7137
  timestamp,
7081
7138
  details: toSerializableJsonValue(errorEvent.details),
7082
7139
  error_code: errorEvent.error_code,
7083
- retryable: errorEvent.retryable
7140
+ retryable: errorEvent.retryable,
7141
+ retry_id: errorEvent.retry_id
7084
7142
  });
7085
7143
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
7086
7144
  return event;
@@ -10551,7 +10609,7 @@ var EventBusEventPersistence = class {
10551
10609
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10552
10610
  return;
10553
10611
  }
10554
- if (this.checkpointWritesActive) {
10612
+ if (this.checkpointWritesActive && event.type !== "llm_retry") {
10555
10613
  this.scheduledEventIds.add(event.id);
10556
10614
  this.checkpointEvents.push(event);
10557
10615
  return;
@@ -10733,21 +10791,37 @@ function resolveLlmMaxTotalAttempts(config) {
10733
10791
  function hasLlmAttemptBudgetRemaining(params) {
10734
10792
  return params.actualAttempts < params.maxTotalAttempts;
10735
10793
  }
10794
+ function validateLlmRetryConfig(config) {
10795
+ if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
10796
+ throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
10797
+ }
10798
+ if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
10799
+ throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
10800
+ }
10801
+ for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
10802
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
10803
+ throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
10804
+ }
10805
+ }
10806
+ }
10736
10807
 
10737
10808
  // src/runtime-kernel/llm/request-builder.ts
10738
10809
  function buildLlmCallerDeps(options) {
10739
10810
  const modelCatalog = options.modelCatalog;
10740
10811
  const maxRetries = options.maxRetries ?? 3;
10741
- return {
10742
- retryConfig: {
10812
+ const retryConfig = {
10813
+ maxRetries,
10814
+ maxRetriesByCategory: options.maxRetriesByCategory,
10815
+ maxTotalAttempts: resolveLlmMaxTotalAttempts({
10743
10816
  maxRetries,
10744
- maxTotalAttempts: resolveLlmMaxTotalAttempts({
10745
- maxRetries,
10746
- maxTotalAttempts: options.maxTotalAttempts
10747
- }),
10748
- enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10749
- retryDelayMs: options.retryDelayMs ?? 1e3
10750
- },
10817
+ maxTotalAttempts: options.maxTotalAttempts
10818
+ }),
10819
+ enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10820
+ retryDelayMs: options.retryDelayMs ?? 1e3
10821
+ };
10822
+ validateLlmRetryConfig(retryConfig);
10823
+ return {
10824
+ retryConfig,
10751
10825
  modelResolver: options.modelResolver ?? new ModelResolver({
10752
10826
  fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
10753
10827
  modelCatalog
@@ -11214,6 +11288,7 @@ var logger14 = new Logger("LlmCaller");
11214
11288
  var CanonicalInferenceFailureError = class extends Error {
11215
11289
  errorCode;
11216
11290
  recoverable;
11291
+ retryCategory;
11217
11292
  metadata;
11218
11293
  constructor(failure3, abortReason) {
11219
11294
  const message = failure3.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure3.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure3.code}`;
@@ -11221,6 +11296,7 @@ var CanonicalInferenceFailureError = class extends Error {
11221
11296
  this.name = failure3.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
11222
11297
  this.errorCode = `llm.${failure3.code}`;
11223
11298
  this.recoverable = failure3.retryable;
11299
+ this.retryCategory = failure3.retry_category;
11224
11300
  this.metadata = { failure_kind: failure3.kind, provider_code: failure3.code };
11225
11301
  }
11226
11302
  };
@@ -11456,6 +11532,57 @@ async function callLlmStream(params) {
11456
11532
  };
11457
11533
  }
11458
11534
 
11535
+ // src/runtime-kernel/llm/functions/llmRetryEpisode.ts
11536
+ var SAFE_RETRY_MESSAGES = {
11537
+ transport: "Network connection interrupted",
11538
+ output: "Model output could not be accepted",
11539
+ rate_limit: "Model request rate limit reached",
11540
+ other: "Model request temporarily failed"
11541
+ };
11542
+ var LlmRetryEpisode = class {
11543
+ constructor(id, emit) {
11544
+ this.id = id;
11545
+ this.emit = emit;
11546
+ }
11547
+ id;
11548
+ emit;
11549
+ state;
11550
+ ended = false;
11551
+ get activeId() {
11552
+ return this.state ? this.id : void 0;
11553
+ }
11554
+ waiting(params, delay) {
11555
+ const now = Date.now();
11556
+ this.state = {
11557
+ ...params,
11558
+ retry_id: this.id,
11559
+ status: "waiting",
11560
+ started_at: this.state?.started_at ?? now,
11561
+ delay_ms: delay,
11562
+ next_retry_at: now + delay,
11563
+ error: SAFE_RETRY_MESSAGES[params.category]
11564
+ };
11565
+ this.publish();
11566
+ }
11567
+ retrying(totalAttempts) {
11568
+ if (!this.state || this.ended) return;
11569
+ const { next_retry_at: ignored, ...state } = this.state;
11570
+ this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
11571
+ this.publish();
11572
+ }
11573
+ finish(status, failure3) {
11574
+ if (!this.state || this.ended) return;
11575
+ this.ended = true;
11576
+ const { next_retry_at: ignored, ...state } = this.state;
11577
+ this.state = { ...state, ...failure3, status, delay_ms: 0, ...failure3 ? { error: SAFE_RETRY_MESSAGES[failure3.category] } : {} };
11578
+ this.publish();
11579
+ }
11580
+ publish() {
11581
+ if (!this.state) return;
11582
+ this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
11583
+ }
11584
+ };
11585
+
11459
11586
  // src/runtime-kernel/llm/retry-fallback-routing.ts
11460
11587
  var logger15 = new Logger("LlmCaller");
11461
11588
  function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
@@ -11708,6 +11835,8 @@ async function callWithRetryFallback(params) {
11708
11835
  maxTotalAttempts: deps.retryConfig.maxTotalAttempts
11709
11836
  });
11710
11837
  const traceId = generateTraceId();
11838
+ const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
11839
+ const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
11711
11840
  let previousAttemptTracker;
11712
11841
  if (!clientRetryEnabled) {
11713
11842
  const activeCfg = deps.modelCatalog.getModelById(modelId);
@@ -11717,167 +11846,207 @@ async function callWithRetryFallback(params) {
11717
11846
  reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
11718
11847
  });
11719
11848
  }
11720
- for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11721
- throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11722
- if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11723
- eventHandler(previousAttemptTracker.buildResetEvent());
11724
- }
11725
- previousAttemptTracker = void 0;
11726
- const resolvedMessages = await runLlmInputPreflight({
11727
- activeModelId,
11728
- messages,
11729
- modelCatalog: deps.modelCatalog,
11730
- materializer: deps.llmInputMaterializer,
11731
- invocationContext,
11732
- eventHandler,
11733
- requirement
11734
- });
11735
- const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11736
- const isRetry = attempt > 0;
11737
- let pendingErrorEvent = null;
11738
- let streamedErrorClassification;
11739
- const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11740
- pendingErrorEvent = evt;
11741
- }) : void 0;
11742
- try {
11743
- if (isRetry) {
11744
- logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11745
- }
11746
- actualAttempts++;
11747
- const llmResponse = attemptTracker ? await callLlmStream({
11748
- inferencePort: deps.inferencePort,
11749
- modelId: activeModelId,
11750
- messages: resolvedMessages,
11751
- options,
11752
- eventHandler: attemptTracker.handle,
11753
- onErrorClassification(classification) {
11754
- streamedErrorClassification = classification;
11755
- },
11756
- signal,
11757
- toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11758
- traceId
11759
- }) : await callPlainCompletion(
11760
- deps.inferencePort,
11761
- activeModelId,
11762
- resolvedMessages,
11763
- options,
11764
- signal,
11765
- traceId
11766
- );
11767
- const responseContent = getLlmResultContent(llmResponse);
11768
- const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11769
- if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11770
- throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11771
- }
11772
- logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11773
- if (attemptContextUsage) {
11774
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11775
- } else {
11776
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11849
+ try {
11850
+ for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11851
+ throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11852
+ if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11853
+ eventHandler(previousAttemptTracker.buildResetEvent());
11777
11854
  }
11778
- return llmResponse;
11779
- } catch (error) {
11780
- lastError = error instanceof Error ? error : new Error(String(error));
11781
- if (lastError.name === "AbortError") {
11782
- logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11783
- attempt: attempt + 1,
11784
- actualAttempts,
11785
- maxTotalAttempts,
11786
- reason: lastError.message
11787
- });
11788
- throw lastError;
11789
- }
11790
- const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11791
- const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
11792
- logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11793
- attempt: attempt + 1,
11794
- maxAttempts: currentMaxRetries + 1,
11795
- actualAttempts,
11796
- maxTotalAttempts,
11797
- error: lastError.message
11855
+ previousAttemptTracker = void 0;
11856
+ const resolvedMessages = await runLlmInputPreflight({
11857
+ activeModelId,
11858
+ messages,
11859
+ modelCatalog: deps.modelCatalog,
11860
+ materializer: deps.llmInputMaterializer,
11861
+ invocationContext,
11862
+ eventHandler,
11863
+ requirement
11798
11864
  });
11799
- previousAttemptTracker = attemptTracker;
11800
- if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11801
- logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11802
- actualAttempts,
11803
- maxTotalAttempts
11804
- });
11805
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11806
- throw lastError;
11807
- }
11808
- if (options.allow_model_fallback !== false) {
11809
- const policySwitchModelId = tryPolicyModelSwitch(
11810
- deps,
11865
+ const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11866
+ const isRetry = attempt > 0;
11867
+ let pendingErrorEvent = null;
11868
+ let streamedErrorClassification;
11869
+ const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11870
+ pendingErrorEvent = evt;
11871
+ }) : void 0;
11872
+ try {
11873
+ if (isRetry) {
11874
+ logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11875
+ }
11876
+ actualAttempts++;
11877
+ retryEpisode.retrying(actualAttempts);
11878
+ const llmResponse = attemptTracker ? await callLlmStream({
11879
+ inferencePort: deps.inferencePort,
11880
+ modelId: activeModelId,
11881
+ messages: resolvedMessages,
11882
+ options,
11883
+ eventHandler: attemptTracker.handle,
11884
+ onErrorClassification(classification) {
11885
+ streamedErrorClassification = classification;
11886
+ },
11887
+ signal,
11888
+ toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11889
+ traceId
11890
+ }) : await callPlainCompletion(
11891
+ deps.inferencePort,
11811
11892
  activeModelId,
11812
- excludedModelIds,
11813
- requirement,
11814
- fallbackObserver,
11815
- lastError,
11816
- invocationContext?.evaluateFallbackPromptCapacity
11893
+ resolvedMessages,
11894
+ options,
11895
+ signal,
11896
+ traceId
11817
11897
  );
11818
- if (policySwitchModelId) {
11819
- fallbackObserver?.onModelFallbackApplied?.({
11820
- fromModelId: activeModelId,
11821
- toModelId: policySwitchModelId,
11822
- reason: lastError.message,
11823
- policy: "policy-switch"
11898
+ const responseContent = getLlmResultContent(llmResponse);
11899
+ const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11900
+ if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11901
+ throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11902
+ }
11903
+ logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11904
+ if (attemptContextUsage) {
11905
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11906
+ } else {
11907
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11908
+ }
11909
+ retryEpisode.finish("succeeded");
11910
+ return llmResponse;
11911
+ } catch (error) {
11912
+ lastError = error instanceof Error ? error : new Error(String(error));
11913
+ if (lastError.name === "AbortError") {
11914
+ logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11915
+ attempt: attempt + 1,
11916
+ actualAttempts,
11917
+ maxTotalAttempts,
11918
+ reason: lastError.message
11824
11919
  });
11825
- activeModelId = policySwitchModelId;
11826
- excludedModelIds.add(policySwitchModelId);
11827
- attempt -= 1;
11828
- continue;
11920
+ throw lastError;
11829
11921
  }
11830
- const quotaFallbackModelId = tryCloudQuotaFallback({
11831
- deps,
11832
- activeModelId,
11833
- options,
11834
- excludedModelIds,
11835
- requirement,
11836
- error: lastError,
11837
- fallbackObserver,
11838
- evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11922
+ const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11923
+ const category = ErrorClassifier.getRetryCategory(classification);
11924
+ const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
11925
+ const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
11926
+ const failedRetryState = {
11927
+ category,
11928
+ attempt: categoryRetries[category],
11929
+ max_retries: currentMaxRetries,
11930
+ total_attempts: actualAttempts,
11931
+ error_code: classification.errorCode
11932
+ };
11933
+ logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11934
+ attempt: attempt + 1,
11935
+ maxAttempts: currentMaxRetries + 1,
11936
+ actualAttempts,
11937
+ maxTotalAttempts,
11938
+ error: lastError.message
11839
11939
  });
11840
- if (quotaFallbackModelId) {
11841
- fallbackObserver?.onModelFallbackApplied?.({
11842
- fromModelId: activeModelId,
11843
- toModelId: quotaFallbackModelId,
11844
- reason: lastError.message,
11845
- policy: "cloud-quota"
11940
+ previousAttemptTracker = attemptTracker;
11941
+ if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11942
+ logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11943
+ actualAttempts,
11944
+ maxTotalAttempts
11846
11945
  });
11847
- activeModelId = quotaFallbackModelId;
11848
- excludedModelIds.add(quotaFallbackModelId);
11849
- attempt -= 1;
11850
- continue;
11946
+ retryEpisode.finish("exhausted", failedRetryState);
11947
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11948
+ throw lastError;
11851
11949
  }
11852
- }
11853
- if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11854
- logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11855
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11856
- throw lastError;
11857
- }
11858
- if (attempt >= currentMaxRetries) {
11859
- logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11860
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11861
- throw lastError;
11862
- }
11863
- const retryDelay = ErrorClassifier.calculateRetryDelay(
11864
- classification,
11865
- attempt,
11866
- deps.retryConfig.retryDelayMs,
11867
- 6e4
11868
- );
11869
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11870
- logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11871
- } else if (classification.category === "retryable" /* RETRYABLE */) {
11872
- logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11873
- }
11874
- throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11875
- if (retryDelay > 0) {
11876
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
11950
+ if (options.allow_model_fallback !== false) {
11951
+ const policySwitchModelId = tryPolicyModelSwitch(
11952
+ deps,
11953
+ activeModelId,
11954
+ excludedModelIds,
11955
+ requirement,
11956
+ fallbackObserver,
11957
+ lastError,
11958
+ invocationContext?.evaluateFallbackPromptCapacity
11959
+ );
11960
+ if (policySwitchModelId) {
11961
+ fallbackObserver?.onModelFallbackApplied?.({
11962
+ fromModelId: activeModelId,
11963
+ toModelId: policySwitchModelId,
11964
+ reason: lastError.message,
11965
+ policy: "policy-switch"
11966
+ });
11967
+ activeModelId = policySwitchModelId;
11968
+ excludedModelIds.add(policySwitchModelId);
11969
+ attempt -= 1;
11970
+ continue;
11971
+ }
11972
+ const quotaFallbackModelId = tryCloudQuotaFallback({
11973
+ deps,
11974
+ activeModelId,
11975
+ options,
11976
+ excludedModelIds,
11977
+ requirement,
11978
+ error: lastError,
11979
+ fallbackObserver,
11980
+ evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11981
+ });
11982
+ if (quotaFallbackModelId) {
11983
+ fallbackObserver?.onModelFallbackApplied?.({
11984
+ fromModelId: activeModelId,
11985
+ toModelId: quotaFallbackModelId,
11986
+ reason: lastError.message,
11987
+ policy: "cloud-quota"
11988
+ });
11989
+ activeModelId = quotaFallbackModelId;
11990
+ excludedModelIds.add(quotaFallbackModelId);
11991
+ attempt -= 1;
11992
+ continue;
11993
+ }
11994
+ }
11995
+ if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11996
+ logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11997
+ retryEpisode.finish("failed", failedRetryState);
11998
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11999
+ throw lastError;
12000
+ }
12001
+ if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
12002
+ logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
12003
+ retryEpisode.finish("exhausted", failedRetryState);
12004
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
12005
+ throw lastError;
12006
+ }
12007
+ const retryDelay = ErrorClassifier.calculateRetryDelay(
12008
+ classification,
12009
+ categoryRetries[category],
12010
+ deps.retryConfig.retryDelayMs,
12011
+ 6e4
12012
+ );
12013
+ if (classification.category === "rate_limit" /* RATE_LIMIT */) {
12014
+ logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
12015
+ } else if (classification.category === "retryable" /* RETRYABLE */) {
12016
+ logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
12017
+ }
12018
+ throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
12019
+ categoryRetries[category] += 1;
12020
+ retryEpisode.waiting({
12021
+ category,
12022
+ attempt: categoryRetries[category],
12023
+ max_retries: currentMaxRetries,
12024
+ total_attempts: actualAttempts,
12025
+ error_code: classification.errorCode
12026
+ }, retryDelay);
12027
+ if (retryDelay > 0) await waitForRetry(retryDelay, signal);
11877
12028
  }
11878
12029
  }
12030
+ throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
12031
+ } catch (error) {
12032
+ retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
12033
+ throw error;
11879
12034
  }
11880
- throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
12035
+ }
12036
+ function waitForRetry(delayMs, signal) {
12037
+ throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
12038
+ return new Promise((resolve, reject) => {
12039
+ const onAbort = () => {
12040
+ clearTimeout(timer);
12041
+ signal?.removeEventListener("abort", onAbort);
12042
+ reject(new DOMException("Request interrupted during retry delay", "AbortError"));
12043
+ };
12044
+ const timer = setTimeout(() => {
12045
+ signal?.removeEventListener("abort", onAbort);
12046
+ resolve();
12047
+ }, delayMs);
12048
+ signal?.addEventListener("abort", onAbort, { once: true });
12049
+ });
11881
12050
  }
11882
12051
  function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
11883
12052
  if (options.retry_policy === "none") return false;
@@ -11936,9 +12105,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
11936
12105
  }
11937
12106
  };
11938
12107
  }
11939
- function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
12108
+ function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
11940
12109
  if (!eventHandler) return;
11941
- eventHandler(pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification));
12110
+ const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
12111
+ eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
11942
12112
  }
11943
12113
 
11944
12114
  // src/runtime-kernel/llm/caller.ts
@@ -12660,6 +12830,8 @@ var RuntimeEventSubRunTracePublisher = class {
12660
12830
  subrun_parent_id: this.subrunParentId,
12661
12831
  source_event_id: envelope.source_event_id,
12662
12832
  // 载荷透传
12833
+ ..."retry" in envelope ? { retry: envelope.retry } : {},
12834
+ ..."failure" in envelope ? { failure: envelope.failure } : {},
12663
12835
  ..."delta" in envelope ? { delta: envelope.delta } : {},
12664
12836
  ..."content" in envelope ? { content: envelope.content } : {},
12665
12837
  ..."answer_id" in envelope ? { answer_id: envelope.answer_id } : {},
@@ -12699,6 +12871,31 @@ var RuntimeEventSubRunTracePublisher = class {
12699
12871
  // src/runtime-kernel/child-run-trace/projectChildRuntimeEventToSubRunTrace.ts
12700
12872
  function projectChildRuntimeEventToSubRunTrace(event) {
12701
12873
  switch (event.type) {
12874
+ case "llm_retry":
12875
+ return {
12876
+ kind: "llm_retry",
12877
+ source_event_id: event.id,
12878
+ retry: {
12879
+ retry_id: event.retry_id,
12880
+ status: event.status,
12881
+ category: event.category,
12882
+ attempt: event.attempt,
12883
+ max_retries: event.max_retries,
12884
+ total_attempts: event.total_attempts,
12885
+ started_at: event.started_at,
12886
+ delay_ms: event.delay_ms,
12887
+ next_retry_at: event.next_retry_at,
12888
+ error: event.error,
12889
+ error_code: event.error_code
12890
+ }
12891
+ };
12892
+ case "error":
12893
+ return {
12894
+ kind: "error",
12895
+ source_event_id: event.id,
12896
+ // 父展示只需要安全错误与重试身份,不复制 child 的任意诊断 details。
12897
+ failure: { error: event.error, error_code: event.error_code, retryable: event.retryable, retry_id: event.retry_id }
12898
+ };
12702
12899
  case "thought":
12703
12900
  return event.is_complete ? {
12704
12901
  kind: "thought_complete",