@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
@@ -128,11 +128,121 @@ var Logger = class {
128
128
  }
129
129
  }
130
130
  };
131
+ var NonEmptyIdentitySchema = z.string().min(1).refine(
132
+ (value) => value === value.trim(),
133
+ "identity must not contain leading or trailing whitespace"
134
+ );
135
+ var RuntimeEventIdSchema = NonEmptyIdentitySchema;
136
+ var AiMessageIdSchema = NonEmptyIdentitySchema;
137
+ var ConversationIdSchema = NonEmptyIdentitySchema;
138
+ var TurnIdSchema = NonEmptyIdentitySchema;
139
+ var RunIdSchema = NonEmptyIdentitySchema.brand();
140
+ var ExecutionIdSchema = NonEmptyIdentitySchema;
141
+ var TraceIdSchema = NonEmptyIdentitySchema;
142
+ var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
143
+ var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
144
+ var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
145
+ var InteractionIdSchema = NonEmptyIdentitySchema;
146
+ var SubrunIdSchema = NonEmptyIdentitySchema;
147
+ var ResumeTokenSchema = NonEmptyIdentitySchema;
148
+ var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
149
+ var SourceEventIdSchema = RuntimeEventIdSchema;
150
+ var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
151
+ var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
152
+
153
+ // src/contracts/identity/generators.ts
154
+ function randomIdentity(prefix) {
155
+ if (typeof globalThis.crypto?.randomUUID !== "function") {
156
+ throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
157
+ }
158
+ return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
159
+ }
160
+ function generateRuntimeEventId() {
161
+ return randomIdentity("evt");
162
+ }
163
+ function generateAnswerSegmentId() {
164
+ return randomIdentity("answer");
165
+ }
166
+ function generateTurnId() {
167
+ return randomIdentity("turn");
168
+ }
169
+ function generateRunId() {
170
+ return RunIdSchema.parse(randomIdentity("run"));
171
+ }
172
+ function generateExecutionId() {
173
+ return randomIdentity("exec");
174
+ }
175
+ function generateTraceId() {
176
+ return randomIdentity("trace");
177
+ }
178
+ function generateInferenceAttemptId() {
179
+ return randomIdentity("inference-attempt");
180
+ }
181
+ function generateThoughtMessageId() {
182
+ return randomIdentity("thought");
183
+ }
184
+ function generateToolCallId() {
185
+ return ToolCallIdSchema.parse(randomIdentity("call"));
186
+ }
187
+ function generateInteractionId() {
188
+ return randomIdentity("interaction");
189
+ }
190
+ function generateResumeToken() {
191
+ return randomIdentity("resume");
192
+ }
193
+ function generateRunResumeClaimId() {
194
+ return randomIdentity("resume-claim");
195
+ }
196
+ function generateAuditEnvelopeId() {
197
+ return randomIdentity("audit");
198
+ }
199
+ function generateContextLedgerEntryId() {
200
+ return randomIdentity("context-ledger");
201
+ }
202
+ function runIdFromTurnId(turnId) {
203
+ return RunIdSchema.parse(turnId);
204
+ }
205
+
206
+ // src/contracts/identity/invariants.ts
207
+ function assertCanonicalFinalAnswerIdentity(input) {
208
+ const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
209
+ if (input.id !== answerId) {
210
+ throw new Error(
211
+ `final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
212
+ );
213
+ }
214
+ return answerId;
215
+ }
216
+ function assertDistinctAnswerChunkIdentity(input) {
217
+ if (input.id === input.answer_id) {
218
+ throw new Error(
219
+ `final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
220
+ );
221
+ }
222
+ }
223
+
224
+ // src/contracts/llm-retry.ts
225
+ var LlmRetryCategory = z.enum(["transport", "output", "rate_limit", "other"]);
226
+ var LlmRetryState = z.object({
227
+ retry_id: TraceIdSchema,
228
+ status: z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
229
+ category: LlmRetryCategory,
230
+ attempt: z.number().int().nonnegative(),
231
+ max_retries: z.number().int().nonnegative(),
232
+ total_attempts: z.number().int().positive(),
233
+ started_at: z.number().finite(),
234
+ delay_ms: z.number().finite().nonnegative(),
235
+ next_retry_at: z.number().finite().optional(),
236
+ /** 安全分类说明;不得放入供应商响应正文。 */
237
+ error: z.string(),
238
+ error_code: z.string().min(1)
239
+ }).strict();
131
240
 
132
241
  // src/shared/errorClassifier.ts
133
242
  var ENGINE_ERROR_CODES = {
134
243
  LLM_RATE_LIMIT: "llm.rate_limit",
135
244
  LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
245
+ LLM_EMPTY_RESPONSE: "llm.empty_response",
136
246
  LLM_PROVIDER_DOWN: "llm.provider_down",
137
247
  LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
138
248
  LLM_AUTH_FAILED: "llm.auth_failed",
@@ -243,6 +353,8 @@ function readStructuredClassification(error) {
243
353
  if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
244
354
  if (typeof recoverable !== "boolean") return void 0;
245
355
  const errorCode = rawErrorCode.trim();
356
+ const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
357
+ const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
246
358
  const retryAfterMsValue = error["retryAfterMs"];
247
359
  const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
248
360
  const hintValue = error["hint"];
@@ -250,12 +362,13 @@ function readStructuredClassification(error) {
250
362
  const metadataValue = error["metadata"];
251
363
  const metadata = isRecord(metadataValue) ? metadataValue : void 0;
252
364
  return createClassification(
253
- recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
365
+ recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
254
366
  `\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
255
367
  recoverable ? retryAfterMs ?? 1e3 : null,
256
368
  {
257
369
  errorCode,
258
370
  recoverable,
371
+ ...retryCategory === void 0 ? {} : { retryCategory },
259
372
  ...retryAfterMs === void 0 ? {} : { retryAfterMs },
260
373
  ...hint === void 0 ? {} : { hint },
261
374
  ...metadata === void 0 ? {} : { metadata }
@@ -530,7 +643,7 @@ var ErrorClassifier = class {
530
643
  if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
531
644
  logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
532
645
  return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
533
- errorCode: ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN,
646
+ errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
534
647
  recoverable: true,
535
648
  retryAfterMs: 1e3,
536
649
  hint: "retry_with_backoff",
@@ -555,15 +668,23 @@ var ErrorClassifier = class {
555
668
  const category = this.categorize(error);
556
669
  return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
557
670
  }
671
+ static getRetryCategory(classification) {
672
+ if (classification.retryCategory !== void 0) return classification.retryCategory;
673
+ if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
674
+ if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
675
+ if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
676
+ return "other";
677
+ }
558
678
  static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
559
679
  const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
560
680
  if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
561
681
  return 0;
562
682
  }
563
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
564
- return Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay);
683
+ const retryCategory = this.getRetryCategory(classification);
684
+ if (retryCategory === "rate_limit" || retryCategory === "transport") {
685
+ return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
565
686
  }
566
- return classification.suggestedDelay || baseDelay;
687
+ return Math.max(baseDelay, classification.suggestedDelay ?? 0);
567
688
  }
568
689
  static isCloudQuotaError(error) {
569
690
  const msg = (error.message || "").toLowerCase();
@@ -602,98 +723,6 @@ var RuntimeResourceRef = z.object({
602
723
  label: LabelSchema.optional()
603
724
  }).strict();
604
725
  var RuntimeResourceRefs = z.array(RuntimeResourceRef).min(1);
605
- var NonEmptyIdentitySchema = z.string().min(1).refine(
606
- (value) => value === value.trim(),
607
- "identity must not contain leading or trailing whitespace"
608
- );
609
- var RuntimeEventIdSchema = NonEmptyIdentitySchema;
610
- var AiMessageIdSchema = NonEmptyIdentitySchema;
611
- var ConversationIdSchema = NonEmptyIdentitySchema;
612
- var TurnIdSchema = NonEmptyIdentitySchema;
613
- var RunIdSchema = NonEmptyIdentitySchema.brand();
614
- var ExecutionIdSchema = NonEmptyIdentitySchema;
615
- var TraceIdSchema = NonEmptyIdentitySchema;
616
- var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
617
- var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
618
- var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
619
- var InteractionIdSchema = NonEmptyIdentitySchema;
620
- var SubrunIdSchema = NonEmptyIdentitySchema;
621
- var ResumeTokenSchema = NonEmptyIdentitySchema;
622
- var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
623
- var SourceEventIdSchema = RuntimeEventIdSchema;
624
- var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
625
- var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
626
-
627
- // src/contracts/identity/generators.ts
628
- function randomIdentity(prefix) {
629
- if (typeof globalThis.crypto?.randomUUID !== "function") {
630
- throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
631
- }
632
- return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
633
- }
634
- function generateRuntimeEventId() {
635
- return randomIdentity("evt");
636
- }
637
- function generateAnswerSegmentId() {
638
- return randomIdentity("answer");
639
- }
640
- function generateTurnId() {
641
- return randomIdentity("turn");
642
- }
643
- function generateRunId() {
644
- return RunIdSchema.parse(randomIdentity("run"));
645
- }
646
- function generateExecutionId() {
647
- return randomIdentity("exec");
648
- }
649
- function generateTraceId() {
650
- return randomIdentity("trace");
651
- }
652
- function generateInferenceAttemptId() {
653
- return randomIdentity("inference-attempt");
654
- }
655
- function generateThoughtMessageId() {
656
- return randomIdentity("thought");
657
- }
658
- function generateToolCallId() {
659
- return ToolCallIdSchema.parse(randomIdentity("call"));
660
- }
661
- function generateInteractionId() {
662
- return randomIdentity("interaction");
663
- }
664
- function generateResumeToken() {
665
- return randomIdentity("resume");
666
- }
667
- function generateRunResumeClaimId() {
668
- return randomIdentity("resume-claim");
669
- }
670
- function generateAuditEnvelopeId() {
671
- return randomIdentity("audit");
672
- }
673
- function generateContextLedgerEntryId() {
674
- return randomIdentity("context-ledger");
675
- }
676
- function runIdFromTurnId(turnId) {
677
- return RunIdSchema.parse(turnId);
678
- }
679
-
680
- // src/contracts/identity/invariants.ts
681
- function assertCanonicalFinalAnswerIdentity(input) {
682
- const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
683
- if (input.id !== answerId) {
684
- throw new Error(
685
- `final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
686
- );
687
- }
688
- return answerId;
689
- }
690
- function assertDistinctAnswerChunkIdentity(input) {
691
- if (input.id === input.answer_id) {
692
- throw new Error(
693
- `final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
694
- );
695
- }
696
- }
697
726
  var FinalAnswerCompletionReason = z.enum([
698
727
  "terminal",
699
728
  "tool_call",
@@ -1168,6 +1197,13 @@ var AuditEnvelope = z.object({
1168
1197
  costDelta: AuditCostDelta.optional(),
1169
1198
  scope: AuditScope.optional()
1170
1199
  });
1200
+ var RuntimeErrorState = z.object({
1201
+ error: z.string(),
1202
+ error_code: z.string().optional(),
1203
+ retryable: z.boolean().optional(),
1204
+ retry_id: TraceIdSchema.optional(),
1205
+ details: SerializableJsonValue.optional()
1206
+ }).strict();
1171
1207
  var ToolCallPhase = z.enum(["start", "update", "complete", "error"]);
1172
1208
  var Status = z.enum(["loading", "success", "error"]);
1173
1209
  var SubRunTraceKind = z.enum([
@@ -1178,7 +1214,9 @@ var SubRunTraceKind = z.enum([
1178
1214
  "tool_output",
1179
1215
  "final_answer_chunk",
1180
1216
  "final_answer",
1181
- "history_summary"
1217
+ "history_summary",
1218
+ "llm_retry",
1219
+ "error"
1182
1220
  ]);
1183
1221
  var SubRunTraceToolCallDecision = z.object({
1184
1222
  tool_call_id: ToolCallIdSchema,
@@ -1191,6 +1229,8 @@ var SubRunTracePayload = z.object({
1191
1229
  subrun_parent_id: SubrunIdSchema.optional(),
1192
1230
  source_event_id: SourceEventIdSchema,
1193
1231
  kind: SubRunTraceKind,
1232
+ retry: LlmRetryState.optional(),
1233
+ failure: RuntimeErrorState.optional(),
1194
1234
  delta: z.string().optional(),
1195
1235
  content: z.string().optional(),
1196
1236
  answer_id: AnswerSegmentIdSchema.optional(),
@@ -1213,6 +1253,12 @@ var SubRunTracePayload = z.object({
1213
1253
  meta: SerializableJsonRecord.optional()
1214
1254
  });
1215
1255
  function validateSubRunTracePayloadSemantics(payload, ctx) {
1256
+ if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
1257
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
1258
+ }
1259
+ if (payload.kind === "error" !== (payload.failure !== void 0)) {
1260
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
1261
+ }
1216
1262
  if (payload.kind === "thought_delta" && payload.delta === void 0) {
1217
1263
  ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
1218
1264
  }
@@ -1566,12 +1612,10 @@ var RuntimeEventShape = z.discriminatedUnion("type", [
1566
1612
  compression_ratio: z.number().min(0).max(1).optional(),
1567
1613
  included_old_summary: z.boolean().optional()
1568
1614
  }),
1615
+ BaseEvent.extend({ type: z.literal("llm_retry"), ...LlmRetryState.shape }),
1569
1616
  BaseEvent.extend({
1570
1617
  type: z.literal("error"),
1571
- error: z.string(),
1572
- details: SerializableJsonValue.optional(),
1573
- error_code: z.string().optional(),
1574
- retryable: z.boolean().optional()
1618
+ ...RuntimeErrorState.shape
1575
1619
  }),
1576
1620
  BaseEvent.extend({
1577
1621
  type: z.literal("control"),
@@ -2006,12 +2050,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
2006
2050
  resume_token: ResumeTokenSchema,
2007
2051
  interaction_status: z.literal("pending")
2008
2052
  });
2053
+ var SSELlmRetryEvent = BaseSSEEvent.extend({
2054
+ type: z.literal("llm_retry"),
2055
+ ...LlmRetryState.shape
2056
+ });
2009
2057
  var SSEErrorEvent = BaseSSEEvent.extend({
2010
2058
  type: z.literal("error"),
2011
- error: z.string(),
2012
- details: SerializableJsonValue.optional(),
2013
- error_code: z.string().optional(),
2014
- retryable: z.boolean().optional()
2059
+ ...RuntimeErrorState.shape
2015
2060
  });
2016
2061
  var SSETransportErrorEvent = BaseSSEEvent.extend({
2017
2062
  type: z.literal("transport_error"),
@@ -2094,6 +2139,7 @@ z.discriminatedUnion("type", [
2094
2139
  SSEToolOutputEvent,
2095
2140
  SSESubRunTraceEvent,
2096
2141
  SSERequiresUserInteractionEvent,
2142
+ SSELlmRetryEvent,
2097
2143
  SSEErrorEvent,
2098
2144
  SSETransportErrorEvent,
2099
2145
  SSEContextUsageSnapshotEvent,
@@ -6465,6 +6511,8 @@ function getRuntimeEventUiProjectionKind(event) {
6465
6511
  return "audit_envelope";
6466
6512
  case "subrun_trace":
6467
6513
  return "subrun_trace";
6514
+ case "llm_retry":
6515
+ return "llm_retry";
6468
6516
  case "error":
6469
6517
  return "error";
6470
6518
  case "context_usage_snapshot":
@@ -6494,7 +6542,7 @@ function describeRuntimeEventLifecycle(event) {
6494
6542
  if (isContextUsageSnapshotRuntimeEvent(event)) {
6495
6543
  return false;
6496
6544
  }
6497
- if (event.type === "error") {
6545
+ if (event.type === "error" || event.type === "llm_retry") {
6498
6546
  return false;
6499
6547
  }
6500
6548
  if (isRequiresUserInteractionRuntimeEvent(event)) {
@@ -6537,6 +6585,7 @@ function describeRuntimeEventLifecycle(event) {
6537
6585
  case "tool_output":
6538
6586
  case "requires_user_interaction":
6539
6587
  case "subrun_trace":
6588
+ case "llm_retry":
6540
6589
  case "error":
6541
6590
  case "context_usage_snapshot":
6542
6591
  case "run_execution_metrics":
@@ -6753,8 +6802,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
6753
6802
  assistant_replay_parts: AssistantReplayParts.optional(),
6754
6803
  meta: UnknownRecord.optional()
6755
6804
  }).strict();
6805
+ var LlmRetryEventSchema = BaseAgentEvent.extend({
6806
+ type: z.literal("llm_retry"),
6807
+ ...LlmRetryState.shape
6808
+ }).strict();
6756
6809
  var ErrorEventSchema = BaseAgentEvent.extend({
6757
6810
  type: z.literal("error"),
6811
+ retry_id: LlmRetryState.shape.retry_id.optional(),
6758
6812
  error: z.string(),
6759
6813
  error_code: z.string().optional(),
6760
6814
  retryable: z.boolean().optional(),
@@ -6784,6 +6838,7 @@ var AgentEventSchema = z.discriminatedUnion("type", [
6784
6838
  ToolProcessEventSchema,
6785
6839
  ObservationEventSchema,
6786
6840
  FinalAnswerEventSchema,
6841
+ LlmRetryEventSchema,
6787
6842
  ErrorEventSchema,
6788
6843
  StreamChunkEventSchema,
6789
6844
  StreamResetEventSchema,
@@ -6884,13 +6939,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
6884
6939
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
6885
6940
  return event;
6886
6941
  }
6942
+ case "llm_retry":
6943
+ return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
6887
6944
  case "error": {
6888
6945
  const errorEvent = typed;
6889
6946
  const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
6890
6947
  timestamp,
6891
6948
  details: toSerializableJsonValue(errorEvent.details),
6892
6949
  error_code: errorEvent.error_code,
6893
- retryable: errorEvent.retryable
6950
+ retryable: errorEvent.retryable,
6951
+ retry_id: errorEvent.retry_id
6894
6952
  });
6895
6953
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
6896
6954
  return event;
@@ -10361,7 +10419,7 @@ var EventBusEventPersistence = class {
10361
10419
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10362
10420
  return;
10363
10421
  }
10364
- if (this.checkpointWritesActive) {
10422
+ if (this.checkpointWritesActive && event.type !== "llm_retry") {
10365
10423
  this.scheduledEventIds.add(event.id);
10366
10424
  this.checkpointEvents.push(event);
10367
10425
  return;
@@ -10543,21 +10601,37 @@ function resolveLlmMaxTotalAttempts(config) {
10543
10601
  function hasLlmAttemptBudgetRemaining(params) {
10544
10602
  return params.actualAttempts < params.maxTotalAttempts;
10545
10603
  }
10604
+ function validateLlmRetryConfig(config) {
10605
+ if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
10606
+ throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
10607
+ }
10608
+ if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
10609
+ throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
10610
+ }
10611
+ for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
10612
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
10613
+ throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
10614
+ }
10615
+ }
10616
+ }
10546
10617
 
10547
10618
  // src/runtime-kernel/llm/request-builder.ts
10548
10619
  function buildLlmCallerDeps(options) {
10549
10620
  const modelCatalog = options.modelCatalog;
10550
10621
  const maxRetries = options.maxRetries ?? 3;
10551
- return {
10552
- retryConfig: {
10622
+ const retryConfig = {
10623
+ maxRetries,
10624
+ maxRetriesByCategory: options.maxRetriesByCategory,
10625
+ maxTotalAttempts: resolveLlmMaxTotalAttempts({
10553
10626
  maxRetries,
10554
- maxTotalAttempts: resolveLlmMaxTotalAttempts({
10555
- maxRetries,
10556
- maxTotalAttempts: options.maxTotalAttempts
10557
- }),
10558
- enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10559
- retryDelayMs: options.retryDelayMs ?? 1e3
10560
- },
10627
+ maxTotalAttempts: options.maxTotalAttempts
10628
+ }),
10629
+ enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10630
+ retryDelayMs: options.retryDelayMs ?? 1e3
10631
+ };
10632
+ validateLlmRetryConfig(retryConfig);
10633
+ return {
10634
+ retryConfig,
10561
10635
  modelResolver: options.modelResolver ?? new ModelResolver({
10562
10636
  fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
10563
10637
  modelCatalog
@@ -11024,6 +11098,7 @@ var logger14 = new Logger("LlmCaller");
11024
11098
  var CanonicalInferenceFailureError = class extends Error {
11025
11099
  errorCode;
11026
11100
  recoverable;
11101
+ retryCategory;
11027
11102
  metadata;
11028
11103
  constructor(failure, abortReason) {
11029
11104
  const message = failure.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure.code}`;
@@ -11031,6 +11106,7 @@ var CanonicalInferenceFailureError = class extends Error {
11031
11106
  this.name = failure.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
11032
11107
  this.errorCode = `llm.${failure.code}`;
11033
11108
  this.recoverable = failure.retryable;
11109
+ this.retryCategory = failure.retry_category;
11034
11110
  this.metadata = { failure_kind: failure.kind, provider_code: failure.code };
11035
11111
  }
11036
11112
  };
@@ -11266,6 +11342,57 @@ async function callLlmStream(params) {
11266
11342
  };
11267
11343
  }
11268
11344
 
11345
+ // src/runtime-kernel/llm/functions/llmRetryEpisode.ts
11346
+ var SAFE_RETRY_MESSAGES = {
11347
+ transport: "Network connection interrupted",
11348
+ output: "Model output could not be accepted",
11349
+ rate_limit: "Model request rate limit reached",
11350
+ other: "Model request temporarily failed"
11351
+ };
11352
+ var LlmRetryEpisode = class {
11353
+ constructor(id, emit) {
11354
+ this.id = id;
11355
+ this.emit = emit;
11356
+ }
11357
+ id;
11358
+ emit;
11359
+ state;
11360
+ ended = false;
11361
+ get activeId() {
11362
+ return this.state ? this.id : void 0;
11363
+ }
11364
+ waiting(params, delay) {
11365
+ const now = Date.now();
11366
+ this.state = {
11367
+ ...params,
11368
+ retry_id: this.id,
11369
+ status: "waiting",
11370
+ started_at: this.state?.started_at ?? now,
11371
+ delay_ms: delay,
11372
+ next_retry_at: now + delay,
11373
+ error: SAFE_RETRY_MESSAGES[params.category]
11374
+ };
11375
+ this.publish();
11376
+ }
11377
+ retrying(totalAttempts) {
11378
+ if (!this.state || this.ended) return;
11379
+ const { next_retry_at: ignored, ...state } = this.state;
11380
+ this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
11381
+ this.publish();
11382
+ }
11383
+ finish(status, failure) {
11384
+ if (!this.state || this.ended) return;
11385
+ this.ended = true;
11386
+ const { next_retry_at: ignored, ...state } = this.state;
11387
+ this.state = { ...state, ...failure, status, delay_ms: 0, ...failure ? { error: SAFE_RETRY_MESSAGES[failure.category] } : {} };
11388
+ this.publish();
11389
+ }
11390
+ publish() {
11391
+ if (!this.state) return;
11392
+ this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
11393
+ }
11394
+ };
11395
+
11269
11396
  // src/runtime-kernel/llm/retry-fallback-routing.ts
11270
11397
  var logger15 = new Logger("LlmCaller");
11271
11398
  function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
@@ -11518,6 +11645,8 @@ async function callWithRetryFallback(params) {
11518
11645
  maxTotalAttempts: deps.retryConfig.maxTotalAttempts
11519
11646
  });
11520
11647
  const traceId = generateTraceId();
11648
+ const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
11649
+ const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
11521
11650
  let previousAttemptTracker;
11522
11651
  if (!clientRetryEnabled) {
11523
11652
  const activeCfg = deps.modelCatalog.getModelById(modelId);
@@ -11527,167 +11656,207 @@ async function callWithRetryFallback(params) {
11527
11656
  reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
11528
11657
  });
11529
11658
  }
11530
- for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11531
- throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11532
- if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11533
- eventHandler(previousAttemptTracker.buildResetEvent());
11534
- }
11535
- previousAttemptTracker = void 0;
11536
- const resolvedMessages = await runLlmInputPreflight({
11537
- activeModelId,
11538
- messages,
11539
- modelCatalog: deps.modelCatalog,
11540
- materializer: deps.llmInputMaterializer,
11541
- invocationContext,
11542
- eventHandler,
11543
- requirement
11544
- });
11545
- const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11546
- const isRetry = attempt > 0;
11547
- let pendingErrorEvent = null;
11548
- let streamedErrorClassification;
11549
- const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11550
- pendingErrorEvent = evt;
11551
- }) : void 0;
11552
- try {
11553
- if (isRetry) {
11554
- logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11555
- }
11556
- actualAttempts++;
11557
- const llmResponse = attemptTracker ? await callLlmStream({
11558
- inferencePort: deps.inferencePort,
11559
- modelId: activeModelId,
11560
- messages: resolvedMessages,
11561
- options,
11562
- eventHandler: attemptTracker.handle,
11563
- onErrorClassification(classification) {
11564
- streamedErrorClassification = classification;
11565
- },
11566
- signal,
11567
- toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11568
- traceId
11569
- }) : await callPlainCompletion(
11570
- deps.inferencePort,
11571
- activeModelId,
11572
- resolvedMessages,
11573
- options,
11574
- signal,
11575
- traceId
11576
- );
11577
- const responseContent = getLlmResultContent(llmResponse);
11578
- const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11579
- if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11580
- throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11581
- }
11582
- logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11583
- if (attemptContextUsage) {
11584
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11585
- } else {
11586
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11659
+ try {
11660
+ for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11661
+ throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11662
+ if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11663
+ eventHandler(previousAttemptTracker.buildResetEvent());
11587
11664
  }
11588
- return llmResponse;
11589
- } catch (error) {
11590
- lastError = error instanceof Error ? error : new Error(String(error));
11591
- if (lastError.name === "AbortError") {
11592
- logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11593
- attempt: attempt + 1,
11594
- actualAttempts,
11595
- maxTotalAttempts,
11596
- reason: lastError.message
11597
- });
11598
- throw lastError;
11599
- }
11600
- const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11601
- const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
11602
- logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11603
- attempt: attempt + 1,
11604
- maxAttempts: currentMaxRetries + 1,
11605
- actualAttempts,
11606
- maxTotalAttempts,
11607
- error: lastError.message
11665
+ previousAttemptTracker = void 0;
11666
+ const resolvedMessages = await runLlmInputPreflight({
11667
+ activeModelId,
11668
+ messages,
11669
+ modelCatalog: deps.modelCatalog,
11670
+ materializer: deps.llmInputMaterializer,
11671
+ invocationContext,
11672
+ eventHandler,
11673
+ requirement
11608
11674
  });
11609
- previousAttemptTracker = attemptTracker;
11610
- if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11611
- logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11612
- actualAttempts,
11613
- maxTotalAttempts
11614
- });
11615
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11616
- throw lastError;
11617
- }
11618
- if (options.allow_model_fallback !== false) {
11619
- const policySwitchModelId = tryPolicyModelSwitch(
11620
- deps,
11675
+ const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11676
+ const isRetry = attempt > 0;
11677
+ let pendingErrorEvent = null;
11678
+ let streamedErrorClassification;
11679
+ const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11680
+ pendingErrorEvent = evt;
11681
+ }) : void 0;
11682
+ try {
11683
+ if (isRetry) {
11684
+ logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11685
+ }
11686
+ actualAttempts++;
11687
+ retryEpisode.retrying(actualAttempts);
11688
+ const llmResponse = attemptTracker ? await callLlmStream({
11689
+ inferencePort: deps.inferencePort,
11690
+ modelId: activeModelId,
11691
+ messages: resolvedMessages,
11692
+ options,
11693
+ eventHandler: attemptTracker.handle,
11694
+ onErrorClassification(classification) {
11695
+ streamedErrorClassification = classification;
11696
+ },
11697
+ signal,
11698
+ toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11699
+ traceId
11700
+ }) : await callPlainCompletion(
11701
+ deps.inferencePort,
11621
11702
  activeModelId,
11622
- excludedModelIds,
11623
- requirement,
11624
- fallbackObserver,
11625
- lastError,
11626
- invocationContext?.evaluateFallbackPromptCapacity
11703
+ resolvedMessages,
11704
+ options,
11705
+ signal,
11706
+ traceId
11627
11707
  );
11628
- if (policySwitchModelId) {
11629
- fallbackObserver?.onModelFallbackApplied?.({
11630
- fromModelId: activeModelId,
11631
- toModelId: policySwitchModelId,
11632
- reason: lastError.message,
11633
- policy: "policy-switch"
11708
+ const responseContent = getLlmResultContent(llmResponse);
11709
+ const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11710
+ if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11711
+ throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11712
+ }
11713
+ logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11714
+ if (attemptContextUsage) {
11715
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11716
+ } else {
11717
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11718
+ }
11719
+ retryEpisode.finish("succeeded");
11720
+ return llmResponse;
11721
+ } catch (error) {
11722
+ lastError = error instanceof Error ? error : new Error(String(error));
11723
+ if (lastError.name === "AbortError") {
11724
+ logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11725
+ attempt: attempt + 1,
11726
+ actualAttempts,
11727
+ maxTotalAttempts,
11728
+ reason: lastError.message
11634
11729
  });
11635
- activeModelId = policySwitchModelId;
11636
- excludedModelIds.add(policySwitchModelId);
11637
- attempt -= 1;
11638
- continue;
11730
+ throw lastError;
11639
11731
  }
11640
- const quotaFallbackModelId = tryCloudQuotaFallback({
11641
- deps,
11642
- activeModelId,
11643
- options,
11644
- excludedModelIds,
11645
- requirement,
11646
- error: lastError,
11647
- fallbackObserver,
11648
- evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11732
+ const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11733
+ const category = ErrorClassifier.getRetryCategory(classification);
11734
+ const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
11735
+ const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
11736
+ const failedRetryState = {
11737
+ category,
11738
+ attempt: categoryRetries[category],
11739
+ max_retries: currentMaxRetries,
11740
+ total_attempts: actualAttempts,
11741
+ error_code: classification.errorCode
11742
+ };
11743
+ logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11744
+ attempt: attempt + 1,
11745
+ maxAttempts: currentMaxRetries + 1,
11746
+ actualAttempts,
11747
+ maxTotalAttempts,
11748
+ error: lastError.message
11649
11749
  });
11650
- if (quotaFallbackModelId) {
11651
- fallbackObserver?.onModelFallbackApplied?.({
11652
- fromModelId: activeModelId,
11653
- toModelId: quotaFallbackModelId,
11654
- reason: lastError.message,
11655
- policy: "cloud-quota"
11750
+ previousAttemptTracker = attemptTracker;
11751
+ if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11752
+ logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11753
+ actualAttempts,
11754
+ maxTotalAttempts
11656
11755
  });
11657
- activeModelId = quotaFallbackModelId;
11658
- excludedModelIds.add(quotaFallbackModelId);
11659
- attempt -= 1;
11660
- continue;
11756
+ retryEpisode.finish("exhausted", failedRetryState);
11757
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11758
+ throw lastError;
11661
11759
  }
11662
- }
11663
- if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11664
- logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11665
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11666
- throw lastError;
11667
- }
11668
- if (attempt >= currentMaxRetries) {
11669
- logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11670
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11671
- throw lastError;
11672
- }
11673
- const retryDelay = ErrorClassifier.calculateRetryDelay(
11674
- classification,
11675
- attempt,
11676
- deps.retryConfig.retryDelayMs,
11677
- 6e4
11678
- );
11679
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11680
- logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11681
- } else if (classification.category === "retryable" /* RETRYABLE */) {
11682
- logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11683
- }
11684
- throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11685
- if (retryDelay > 0) {
11686
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
11687
- }
11688
- }
11760
+ if (options.allow_model_fallback !== false) {
11761
+ const policySwitchModelId = tryPolicyModelSwitch(
11762
+ deps,
11763
+ activeModelId,
11764
+ excludedModelIds,
11765
+ requirement,
11766
+ fallbackObserver,
11767
+ lastError,
11768
+ invocationContext?.evaluateFallbackPromptCapacity
11769
+ );
11770
+ if (policySwitchModelId) {
11771
+ fallbackObserver?.onModelFallbackApplied?.({
11772
+ fromModelId: activeModelId,
11773
+ toModelId: policySwitchModelId,
11774
+ reason: lastError.message,
11775
+ policy: "policy-switch"
11776
+ });
11777
+ activeModelId = policySwitchModelId;
11778
+ excludedModelIds.add(policySwitchModelId);
11779
+ attempt -= 1;
11780
+ continue;
11781
+ }
11782
+ const quotaFallbackModelId = tryCloudQuotaFallback({
11783
+ deps,
11784
+ activeModelId,
11785
+ options,
11786
+ excludedModelIds,
11787
+ requirement,
11788
+ error: lastError,
11789
+ fallbackObserver,
11790
+ evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11791
+ });
11792
+ if (quotaFallbackModelId) {
11793
+ fallbackObserver?.onModelFallbackApplied?.({
11794
+ fromModelId: activeModelId,
11795
+ toModelId: quotaFallbackModelId,
11796
+ reason: lastError.message,
11797
+ policy: "cloud-quota"
11798
+ });
11799
+ activeModelId = quotaFallbackModelId;
11800
+ excludedModelIds.add(quotaFallbackModelId);
11801
+ attempt -= 1;
11802
+ continue;
11803
+ }
11804
+ }
11805
+ if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11806
+ logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11807
+ retryEpisode.finish("failed", failedRetryState);
11808
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11809
+ throw lastError;
11810
+ }
11811
+ if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
11812
+ logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11813
+ retryEpisode.finish("exhausted", failedRetryState);
11814
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11815
+ throw lastError;
11816
+ }
11817
+ const retryDelay = ErrorClassifier.calculateRetryDelay(
11818
+ classification,
11819
+ categoryRetries[category],
11820
+ deps.retryConfig.retryDelayMs,
11821
+ 6e4
11822
+ );
11823
+ if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11824
+ logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11825
+ } else if (classification.category === "retryable" /* RETRYABLE */) {
11826
+ logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11827
+ }
11828
+ throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11829
+ categoryRetries[category] += 1;
11830
+ retryEpisode.waiting({
11831
+ category,
11832
+ attempt: categoryRetries[category],
11833
+ max_retries: currentMaxRetries,
11834
+ total_attempts: actualAttempts,
11835
+ error_code: classification.errorCode
11836
+ }, retryDelay);
11837
+ if (retryDelay > 0) await waitForRetry(retryDelay, signal);
11838
+ }
11839
+ }
11840
+ throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
11841
+ } catch (error) {
11842
+ retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
11843
+ throw error;
11689
11844
  }
11690
- throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
11845
+ }
11846
+ function waitForRetry(delayMs, signal) {
11847
+ throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
11848
+ return new Promise((resolve, reject) => {
11849
+ const onAbort = () => {
11850
+ clearTimeout(timer);
11851
+ signal?.removeEventListener("abort", onAbort);
11852
+ reject(new DOMException("Request interrupted during retry delay", "AbortError"));
11853
+ };
11854
+ const timer = setTimeout(() => {
11855
+ signal?.removeEventListener("abort", onAbort);
11856
+ resolve();
11857
+ }, delayMs);
11858
+ signal?.addEventListener("abort", onAbort, { once: true });
11859
+ });
11691
11860
  }
11692
11861
  function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
11693
11862
  if (options.retry_policy === "none") return false;
@@ -11746,9 +11915,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
11746
11915
  }
11747
11916
  };
11748
11917
  }
11749
- function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
11918
+ function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
11750
11919
  if (!eventHandler) return;
11751
- eventHandler(pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification));
11920
+ const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
11921
+ eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
11752
11922
  }
11753
11923
 
11754
11924
  // src/runtime-kernel/llm/caller.ts
@@ -12470,6 +12640,8 @@ var RuntimeEventSubRunTracePublisher = class {
12470
12640
  subrun_parent_id: this.subrunParentId,
12471
12641
  source_event_id: envelope.source_event_id,
12472
12642
  // 载荷透传
12643
+ ..."retry" in envelope ? { retry: envelope.retry } : {},
12644
+ ..."failure" in envelope ? { failure: envelope.failure } : {},
12473
12645
  ..."delta" in envelope ? { delta: envelope.delta } : {},
12474
12646
  ..."content" in envelope ? { content: envelope.content } : {},
12475
12647
  ..."answer_id" in envelope ? { answer_id: envelope.answer_id } : {},
@@ -12509,6 +12681,31 @@ var RuntimeEventSubRunTracePublisher = class {
12509
12681
  // src/runtime-kernel/child-run-trace/projectChildRuntimeEventToSubRunTrace.ts
12510
12682
  function projectChildRuntimeEventToSubRunTrace(event) {
12511
12683
  switch (event.type) {
12684
+ case "llm_retry":
12685
+ return {
12686
+ kind: "llm_retry",
12687
+ source_event_id: event.id,
12688
+ retry: {
12689
+ retry_id: event.retry_id,
12690
+ status: event.status,
12691
+ category: event.category,
12692
+ attempt: event.attempt,
12693
+ max_retries: event.max_retries,
12694
+ total_attempts: event.total_attempts,
12695
+ started_at: event.started_at,
12696
+ delay_ms: event.delay_ms,
12697
+ next_retry_at: event.next_retry_at,
12698
+ error: event.error,
12699
+ error_code: event.error_code
12700
+ }
12701
+ };
12702
+ case "error":
12703
+ return {
12704
+ kind: "error",
12705
+ source_event_id: event.id,
12706
+ // 父展示只需要安全错误与重试身份,不复制 child 的任意诊断 details。
12707
+ failure: { error: event.error, error_code: event.error_code, retryable: event.retryable, retry_id: event.retry_id }
12708
+ };
12512
12709
  case "thought":
12513
12710
  return event.is_complete ? {
12514
12711
  kind: "thought_complete",