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