@linnlabs/linnkit 0.37.5 → 0.38.1

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 (65) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/dist/cli.cjs +346 -178
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +346 -178
  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/events.d.cts +517 -35
  11. package/dist/contracts/events.d.ts +517 -35
  12. package/dist/contracts/llm-retry.d.cts +47 -0
  13. package/dist/contracts/llm-retry.d.ts +47 -0
  14. package/dist/contracts/runtime-error.d.cts +26 -0
  15. package/dist/contracts/runtime-error.d.ts +26 -0
  16. package/dist/contracts/sse.d.cts +555 -39
  17. package/dist/contracts/sse.d.ts +555 -39
  18. package/dist/contracts/sub-run-trace-payload.d.cts +102 -6
  19. package/dist/contracts/sub-run-trace-payload.d.ts +102 -6
  20. package/dist/contracts/token-accounting.d.cts +18 -18
  21. package/dist/contracts/token-accounting.d.ts +18 -18
  22. package/dist/contracts.cjs +65 -10
  23. package/dist/contracts.cjs.map +1 -1
  24. package/dist/contracts.d.cts +4 -2
  25. package/dist/contracts.d.ts +4 -2
  26. package/dist/contracts.js +62 -11
  27. package/dist/contracts.js.map +1 -1
  28. package/dist/index.cjs +551 -286
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.js +551 -286
  31. package/dist/index.js.map +1 -1
  32. package/dist/ports/canonical-inference.d.cts +3 -0
  33. package/dist/ports/canonical-inference.d.ts +3 -0
  34. package/dist/ports/llm-call.d.cts +4 -0
  35. package/dist/ports/llm-call.d.ts +4 -0
  36. package/dist/quickstart.cjs +346 -178
  37. package/dist/quickstart.cjs.map +1 -1
  38. package/dist/quickstart.js +346 -178
  39. package/dist/quickstart.js.map +1 -1
  40. package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.cts +8 -0
  41. package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.ts +8 -0
  42. package/dist/runtime-kernel/events/agentEvents.d.cts +85 -4
  43. package/dist/runtime-kernel/events/agentEvents.d.ts +85 -4
  44. package/dist/runtime-kernel/events/eventGovernance.d.cts +1 -1
  45. package/dist/runtime-kernel/events/eventGovernance.d.ts +1 -1
  46. package/dist/runtime-kernel/events.cjs +55 -11
  47. package/dist/runtime-kernel/events.cjs.map +1 -1
  48. package/dist/runtime-kernel/events.js +55 -11
  49. package/dist/runtime-kernel/events.js.map +1 -1
  50. package/dist/runtime-kernel/llm/request-builder.d.cts +2 -0
  51. package/dist/runtime-kernel/llm/request-builder.d.ts +2 -0
  52. package/dist/runtime-kernel.cjs +513 -271
  53. package/dist/runtime-kernel.cjs.map +1 -1
  54. package/dist/runtime-kernel.js +513 -271
  55. package/dist/runtime-kernel.js.map +1 -1
  56. package/dist/shared/errorClassifier.d.cts +5 -0
  57. package/dist/shared/errorClassifier.d.ts +5 -0
  58. package/dist/testkit.cjs +511 -269
  59. package/dist/testkit.cjs.map +1 -1
  60. package/dist/testkit.js +511 -269
  61. package/dist/testkit.js.map +1 -1
  62. package/docs/integration/llm-provider.md +24 -5
  63. package/docs/integration/realtime.md +29 -0
  64. package/docs/integration/tools.md +4 -0
  65. package/package.json +2 -2
@@ -130,11 +130,121 @@ var Logger = class {
130
130
  }
131
131
  }
132
132
  };
133
+ var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
134
+ (value) => value === value.trim(),
135
+ "identity must not contain leading or trailing whitespace"
136
+ );
137
+ var RuntimeEventIdSchema = NonEmptyIdentitySchema;
138
+ var AiMessageIdSchema = NonEmptyIdentitySchema;
139
+ var ConversationIdSchema = NonEmptyIdentitySchema;
140
+ var TurnIdSchema = NonEmptyIdentitySchema;
141
+ var RunIdSchema = NonEmptyIdentitySchema.brand();
142
+ var ExecutionIdSchema = NonEmptyIdentitySchema;
143
+ var TraceIdSchema = NonEmptyIdentitySchema;
144
+ var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
145
+ var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
146
+ var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
147
+ var InteractionIdSchema = NonEmptyIdentitySchema;
148
+ var SubrunIdSchema = NonEmptyIdentitySchema;
149
+ var ResumeTokenSchema = NonEmptyIdentitySchema;
150
+ var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
151
+ var SourceEventIdSchema = RuntimeEventIdSchema;
152
+ var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
153
+ var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
154
+
155
+ // src/contracts/identity/generators.ts
156
+ function randomIdentity(prefix) {
157
+ if (typeof globalThis.crypto?.randomUUID !== "function") {
158
+ throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
159
+ }
160
+ return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
161
+ }
162
+ function generateRuntimeEventId() {
163
+ return randomIdentity("evt");
164
+ }
165
+ function generateAnswerSegmentId() {
166
+ return randomIdentity("answer");
167
+ }
168
+ function generateTurnId() {
169
+ return randomIdentity("turn");
170
+ }
171
+ function generateRunId() {
172
+ return RunIdSchema.parse(randomIdentity("run"));
173
+ }
174
+ function generateExecutionId() {
175
+ return randomIdentity("exec");
176
+ }
177
+ function generateTraceId() {
178
+ return randomIdentity("trace");
179
+ }
180
+ function generateInferenceAttemptId() {
181
+ return randomIdentity("inference-attempt");
182
+ }
183
+ function generateThoughtMessageId() {
184
+ return randomIdentity("thought");
185
+ }
186
+ function generateToolCallId() {
187
+ return ToolCallIdSchema.parse(randomIdentity("call"));
188
+ }
189
+ function generateInteractionId() {
190
+ return randomIdentity("interaction");
191
+ }
192
+ function generateResumeToken() {
193
+ return randomIdentity("resume");
194
+ }
195
+ function generateRunResumeClaimId() {
196
+ return randomIdentity("resume-claim");
197
+ }
198
+ function generateAuditEnvelopeId() {
199
+ return randomIdentity("audit");
200
+ }
201
+ function generateContextLedgerEntryId() {
202
+ return randomIdentity("context-ledger");
203
+ }
204
+ function runIdFromTurnId(turnId) {
205
+ return RunIdSchema.parse(turnId);
206
+ }
207
+
208
+ // src/contracts/identity/invariants.ts
209
+ function assertCanonicalFinalAnswerIdentity(input) {
210
+ const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
211
+ if (input.id !== answerId) {
212
+ throw new Error(
213
+ `final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
214
+ );
215
+ }
216
+ return answerId;
217
+ }
218
+ function assertDistinctAnswerChunkIdentity(input) {
219
+ if (input.id === input.answer_id) {
220
+ throw new Error(
221
+ `final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
222
+ );
223
+ }
224
+ }
225
+
226
+ // src/contracts/llm-retry.ts
227
+ var LlmRetryCategory = zod.z.enum(["transport", "output", "rate_limit", "other"]);
228
+ var LlmRetryState = zod.z.object({
229
+ retry_id: TraceIdSchema,
230
+ status: zod.z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
231
+ category: LlmRetryCategory,
232
+ attempt: zod.z.number().int().nonnegative(),
233
+ max_retries: zod.z.number().int().nonnegative(),
234
+ total_attempts: zod.z.number().int().positive(),
235
+ started_at: zod.z.number().finite(),
236
+ delay_ms: zod.z.number().finite().nonnegative(),
237
+ next_retry_at: zod.z.number().finite().optional(),
238
+ /** 安全分类说明;不得放入供应商响应正文。 */
239
+ error: zod.z.string(),
240
+ error_code: zod.z.string().min(1)
241
+ }).strict();
133
242
 
134
243
  // src/shared/errorClassifier.ts
135
244
  var ENGINE_ERROR_CODES = {
136
245
  LLM_RATE_LIMIT: "llm.rate_limit",
137
246
  LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
247
+ LLM_EMPTY_RESPONSE: "llm.empty_response",
138
248
  LLM_PROVIDER_DOWN: "llm.provider_down",
139
249
  LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
140
250
  LLM_AUTH_FAILED: "llm.auth_failed",
@@ -245,6 +355,8 @@ function readStructuredClassification(error) {
245
355
  if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
246
356
  if (typeof recoverable !== "boolean") return void 0;
247
357
  const errorCode = rawErrorCode.trim();
358
+ const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
359
+ const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
248
360
  const retryAfterMsValue = error["retryAfterMs"];
249
361
  const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
250
362
  const hintValue = error["hint"];
@@ -252,12 +364,13 @@ function readStructuredClassification(error) {
252
364
  const metadataValue = error["metadata"];
253
365
  const metadata = isRecord(metadataValue) ? metadataValue : void 0;
254
366
  return createClassification(
255
- recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
367
+ recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
256
368
  `\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
257
369
  recoverable ? retryAfterMs ?? 1e3 : null,
258
370
  {
259
371
  errorCode,
260
372
  recoverable,
373
+ ...retryCategory === void 0 ? {} : { retryCategory },
261
374
  ...retryAfterMs === void 0 ? {} : { retryAfterMs },
262
375
  ...hint === void 0 ? {} : { hint },
263
376
  ...metadata === void 0 ? {} : { metadata }
@@ -532,7 +645,7 @@ var ErrorClassifier = class {
532
645
  if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
533
646
  logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
534
647
  return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
535
- errorCode: ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN,
648
+ errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
536
649
  recoverable: true,
537
650
  retryAfterMs: 1e3,
538
651
  hint: "retry_with_backoff",
@@ -557,13 +670,21 @@ var ErrorClassifier = class {
557
670
  const category = this.categorize(error);
558
671
  return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
559
672
  }
673
+ static getRetryCategory(classification) {
674
+ if (classification.retryCategory !== void 0) return classification.retryCategory;
675
+ if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
676
+ if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
677
+ if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
678
+ return "other";
679
+ }
560
680
  static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
561
681
  const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
562
682
  if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
563
683
  return 0;
564
684
  }
565
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
566
- return Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay);
685
+ const retryCategory = this.getRetryCategory(classification);
686
+ if (retryCategory === "rate_limit" || retryCategory === "transport") {
687
+ return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
567
688
  }
568
689
  return Math.max(baseDelay, classification.suggestedDelay ?? 0);
569
690
  }
@@ -604,98 +725,6 @@ var RuntimeResourceRef = zod.z.object({
604
725
  label: LabelSchema.optional()
605
726
  }).strict();
606
727
  var RuntimeResourceRefs = zod.z.array(RuntimeResourceRef).min(1);
607
- var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
608
- (value) => value === value.trim(),
609
- "identity must not contain leading or trailing whitespace"
610
- );
611
- var RuntimeEventIdSchema = NonEmptyIdentitySchema;
612
- var AiMessageIdSchema = NonEmptyIdentitySchema;
613
- var ConversationIdSchema = NonEmptyIdentitySchema;
614
- var TurnIdSchema = NonEmptyIdentitySchema;
615
- var RunIdSchema = NonEmptyIdentitySchema.brand();
616
- var ExecutionIdSchema = NonEmptyIdentitySchema;
617
- var TraceIdSchema = NonEmptyIdentitySchema;
618
- var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
619
- var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
620
- var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
621
- var InteractionIdSchema = NonEmptyIdentitySchema;
622
- var SubrunIdSchema = NonEmptyIdentitySchema;
623
- var ResumeTokenSchema = NonEmptyIdentitySchema;
624
- var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
625
- var SourceEventIdSchema = RuntimeEventIdSchema;
626
- var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
627
- var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
628
-
629
- // src/contracts/identity/generators.ts
630
- function randomIdentity(prefix) {
631
- if (typeof globalThis.crypto?.randomUUID !== "function") {
632
- throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
633
- }
634
- return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
635
- }
636
- function generateRuntimeEventId() {
637
- return randomIdentity("evt");
638
- }
639
- function generateAnswerSegmentId() {
640
- return randomIdentity("answer");
641
- }
642
- function generateTurnId() {
643
- return randomIdentity("turn");
644
- }
645
- function generateRunId() {
646
- return RunIdSchema.parse(randomIdentity("run"));
647
- }
648
- function generateExecutionId() {
649
- return randomIdentity("exec");
650
- }
651
- function generateTraceId() {
652
- return randomIdentity("trace");
653
- }
654
- function generateInferenceAttemptId() {
655
- return randomIdentity("inference-attempt");
656
- }
657
- function generateThoughtMessageId() {
658
- return randomIdentity("thought");
659
- }
660
- function generateToolCallId() {
661
- return ToolCallIdSchema.parse(randomIdentity("call"));
662
- }
663
- function generateInteractionId() {
664
- return randomIdentity("interaction");
665
- }
666
- function generateResumeToken() {
667
- return randomIdentity("resume");
668
- }
669
- function generateRunResumeClaimId() {
670
- return randomIdentity("resume-claim");
671
- }
672
- function generateAuditEnvelopeId() {
673
- return randomIdentity("audit");
674
- }
675
- function generateContextLedgerEntryId() {
676
- return randomIdentity("context-ledger");
677
- }
678
- function runIdFromTurnId(turnId) {
679
- return RunIdSchema.parse(turnId);
680
- }
681
-
682
- // src/contracts/identity/invariants.ts
683
- function assertCanonicalFinalAnswerIdentity(input) {
684
- const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
685
- if (input.id !== answerId) {
686
- throw new Error(
687
- `final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
688
- );
689
- }
690
- return answerId;
691
- }
692
- function assertDistinctAnswerChunkIdentity(input) {
693
- if (input.id === input.answer_id) {
694
- throw new Error(
695
- `final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
696
- );
697
- }
698
- }
699
728
  var FinalAnswerCompletionReason = zod.z.enum([
700
729
  "terminal",
701
730
  "tool_call",
@@ -1170,6 +1199,13 @@ var AuditEnvelope = zod.z.object({
1170
1199
  costDelta: AuditCostDelta.optional(),
1171
1200
  scope: AuditScope.optional()
1172
1201
  });
1202
+ var RuntimeErrorState = zod.z.object({
1203
+ error: zod.z.string(),
1204
+ error_code: zod.z.string().optional(),
1205
+ retryable: zod.z.boolean().optional(),
1206
+ retry_id: TraceIdSchema.optional(),
1207
+ details: SerializableJsonValue.optional()
1208
+ }).strict();
1173
1209
  var ToolCallPhase = zod.z.enum(["start", "update", "complete", "error"]);
1174
1210
  var Status = zod.z.enum(["loading", "success", "error"]);
1175
1211
  var SubRunTraceKind = zod.z.enum([
@@ -1180,7 +1216,9 @@ var SubRunTraceKind = zod.z.enum([
1180
1216
  "tool_output",
1181
1217
  "final_answer_chunk",
1182
1218
  "final_answer",
1183
- "history_summary"
1219
+ "history_summary",
1220
+ "llm_retry",
1221
+ "error"
1184
1222
  ]);
1185
1223
  var SubRunTraceToolCallDecision = zod.z.object({
1186
1224
  tool_call_id: ToolCallIdSchema,
@@ -1193,6 +1231,8 @@ var SubRunTracePayload = zod.z.object({
1193
1231
  subrun_parent_id: SubrunIdSchema.optional(),
1194
1232
  source_event_id: SourceEventIdSchema,
1195
1233
  kind: SubRunTraceKind,
1234
+ retry: LlmRetryState.optional(),
1235
+ failure: RuntimeErrorState.optional(),
1196
1236
  delta: zod.z.string().optional(),
1197
1237
  content: zod.z.string().optional(),
1198
1238
  answer_id: AnswerSegmentIdSchema.optional(),
@@ -1215,6 +1255,12 @@ var SubRunTracePayload = zod.z.object({
1215
1255
  meta: SerializableJsonRecord.optional()
1216
1256
  });
1217
1257
  function validateSubRunTracePayloadSemantics(payload, ctx) {
1258
+ if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
1259
+ ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
1260
+ }
1261
+ if (payload.kind === "error" !== (payload.failure !== void 0)) {
1262
+ ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
1263
+ }
1218
1264
  if (payload.kind === "thought_delta" && payload.delta === void 0) {
1219
1265
  ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
1220
1266
  }
@@ -1568,12 +1614,10 @@ var RuntimeEventShape = zod.z.discriminatedUnion("type", [
1568
1614
  compression_ratio: zod.z.number().min(0).max(1).optional(),
1569
1615
  included_old_summary: zod.z.boolean().optional()
1570
1616
  }),
1617
+ BaseEvent.extend({ type: zod.z.literal("llm_retry"), ...LlmRetryState.shape }),
1571
1618
  BaseEvent.extend({
1572
1619
  type: zod.z.literal("error"),
1573
- error: zod.z.string(),
1574
- details: SerializableJsonValue.optional(),
1575
- error_code: zod.z.string().optional(),
1576
- retryable: zod.z.boolean().optional()
1620
+ ...RuntimeErrorState.shape
1577
1621
  }),
1578
1622
  BaseEvent.extend({
1579
1623
  type: zod.z.literal("control"),
@@ -2008,12 +2052,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
2008
2052
  resume_token: ResumeTokenSchema,
2009
2053
  interaction_status: zod.z.literal("pending")
2010
2054
  });
2055
+ var SSELlmRetryEvent = BaseSSEEvent.extend({
2056
+ type: zod.z.literal("llm_retry"),
2057
+ ...LlmRetryState.shape
2058
+ });
2011
2059
  var SSEErrorEvent = BaseSSEEvent.extend({
2012
2060
  type: zod.z.literal("error"),
2013
- error: zod.z.string(),
2014
- details: SerializableJsonValue.optional(),
2015
- error_code: zod.z.string().optional(),
2016
- retryable: zod.z.boolean().optional()
2061
+ ...RuntimeErrorState.shape
2017
2062
  });
2018
2063
  var SSETransportErrorEvent = BaseSSEEvent.extend({
2019
2064
  type: zod.z.literal("transport_error"),
@@ -2096,6 +2141,7 @@ zod.z.discriminatedUnion("type", [
2096
2141
  SSEToolOutputEvent,
2097
2142
  SSESubRunTraceEvent,
2098
2143
  SSERequiresUserInteractionEvent,
2144
+ SSELlmRetryEvent,
2099
2145
  SSEErrorEvent,
2100
2146
  SSETransportErrorEvent,
2101
2147
  SSEContextUsageSnapshotEvent,
@@ -6467,6 +6513,8 @@ function getRuntimeEventUiProjectionKind(event) {
6467
6513
  return "audit_envelope";
6468
6514
  case "subrun_trace":
6469
6515
  return "subrun_trace";
6516
+ case "llm_retry":
6517
+ return "llm_retry";
6470
6518
  case "error":
6471
6519
  return "error";
6472
6520
  case "context_usage_snapshot":
@@ -6496,7 +6544,7 @@ function describeRuntimeEventLifecycle(event) {
6496
6544
  if (isContextUsageSnapshotRuntimeEvent(event)) {
6497
6545
  return false;
6498
6546
  }
6499
- if (event.type === "error") {
6547
+ if (event.type === "error" || event.type === "llm_retry") {
6500
6548
  return false;
6501
6549
  }
6502
6550
  if (isRequiresUserInteractionRuntimeEvent(event)) {
@@ -6539,6 +6587,7 @@ function describeRuntimeEventLifecycle(event) {
6539
6587
  case "tool_output":
6540
6588
  case "requires_user_interaction":
6541
6589
  case "subrun_trace":
6590
+ case "llm_retry":
6542
6591
  case "error":
6543
6592
  case "context_usage_snapshot":
6544
6593
  case "run_execution_metrics":
@@ -6755,8 +6804,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
6755
6804
  assistant_replay_parts: AssistantReplayParts.optional(),
6756
6805
  meta: UnknownRecord.optional()
6757
6806
  }).strict();
6807
+ var LlmRetryEventSchema = BaseAgentEvent.extend({
6808
+ type: zod.z.literal("llm_retry"),
6809
+ ...LlmRetryState.shape
6810
+ }).strict();
6758
6811
  var ErrorEventSchema = BaseAgentEvent.extend({
6759
6812
  type: zod.z.literal("error"),
6813
+ retry_id: LlmRetryState.shape.retry_id.optional(),
6760
6814
  error: zod.z.string(),
6761
6815
  error_code: zod.z.string().optional(),
6762
6816
  retryable: zod.z.boolean().optional(),
@@ -6786,6 +6840,7 @@ var AgentEventSchema = zod.z.discriminatedUnion("type", [
6786
6840
  ToolProcessEventSchema,
6787
6841
  ObservationEventSchema,
6788
6842
  FinalAnswerEventSchema,
6843
+ LlmRetryEventSchema,
6789
6844
  ErrorEventSchema,
6790
6845
  StreamChunkEventSchema,
6791
6846
  StreamResetEventSchema,
@@ -6886,13 +6941,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
6886
6941
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
6887
6942
  return event;
6888
6943
  }
6944
+ case "llm_retry":
6945
+ return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
6889
6946
  case "error": {
6890
6947
  const errorEvent = typed;
6891
6948
  const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
6892
6949
  timestamp,
6893
6950
  details: toSerializableJsonValue(errorEvent.details),
6894
6951
  error_code: errorEvent.error_code,
6895
- retryable: errorEvent.retryable
6952
+ retryable: errorEvent.retryable,
6953
+ retry_id: errorEvent.retry_id
6896
6954
  });
6897
6955
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
6898
6956
  return event;
@@ -9861,6 +9919,51 @@ __export(tools_exports, {
9861
9919
  stripRuntimeReservedToolContextPatch: () => stripRuntimeReservedToolContextPatch
9862
9920
  });
9863
9921
 
9922
+ // src/runtime-kernel/tools/schema/functions/formatUnknownToolArguments.ts
9923
+ function spellingDistance(left, right) {
9924
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
9925
+ for (let row = 1; row <= left.length; row += 1) {
9926
+ const current = [row];
9927
+ for (let column = 1; column <= right.length; column += 1) {
9928
+ current[column] = Math.min(
9929
+ current[column - 1] + 1,
9930
+ previous[column] + 1,
9931
+ previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1)
9932
+ );
9933
+ }
9934
+ previous = current;
9935
+ }
9936
+ return previous[right.length];
9937
+ }
9938
+ function nearestField(field, allowedFields) {
9939
+ const threshold = field.length < 5 ? 1 : 2;
9940
+ let nearest;
9941
+ let bestDistance = threshold + 1;
9942
+ for (const candidate of allowedFields) {
9943
+ if (Math.abs(field.length - candidate.length) > threshold) continue;
9944
+ const distance = spellingDistance(field, candidate);
9945
+ if (distance < bestDistance) {
9946
+ bestDistance = distance;
9947
+ nearest = candidate;
9948
+ } else if (distance === bestDistance) {
9949
+ nearest = void 0;
9950
+ }
9951
+ }
9952
+ return bestDistance <= threshold ? nearest : void 0;
9953
+ }
9954
+ function formatUnknownToolArguments(fields, allowedFields) {
9955
+ const suggestions = fields.flatMap((field) => {
9956
+ const candidate = nearestField(field, allowedFields);
9957
+ return candidate ? [`${JSON.stringify(field)} \u2192 ${JSON.stringify(candidate)}`] : [];
9958
+ });
9959
+ return [
9960
+ `Additional properties not allowed: ${fields.map((field) => JSON.stringify(field)).join(", ")}.`,
9961
+ `Allowed parameters: ${allowedFields.map((field) => JSON.stringify(field)).join(", ") || "(none)"}.`,
9962
+ ...suggestions.length > 0 ? [`Possible spelling corrections: ${suggestions.join("; ")}.`] : [],
9963
+ "Remove unsupported parameters before retrying; no arguments were changed or executed."
9964
+ ].join(" ");
9965
+ }
9966
+
9864
9967
  // src/runtime-kernel/tools/toolContracts.ts
9865
9968
  var BaseTool = class {
9866
9969
  idempotency;
@@ -9896,7 +9999,7 @@ var BaseTool = class {
9896
9999
  if (unknownFields.length > 0) {
9897
10000
  return {
9898
10001
  success: false,
9899
- error: `Additional properties not allowed: ${unknownFields.join(", ")}`
10002
+ error: formatUnknownToolArguments(unknownFields, [...allowed])
9900
10003
  };
9901
10004
  }
9902
10005
  }
@@ -10363,7 +10466,7 @@ var EventBusEventPersistence = class {
10363
10466
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10364
10467
  return;
10365
10468
  }
10366
- if (this.checkpointWritesActive) {
10469
+ if (this.checkpointWritesActive && event.type !== "llm_retry") {
10367
10470
  this.scheduledEventIds.add(event.id);
10368
10471
  this.checkpointEvents.push(event);
10369
10472
  return;
@@ -10545,21 +10648,37 @@ function resolveLlmMaxTotalAttempts(config) {
10545
10648
  function hasLlmAttemptBudgetRemaining(params) {
10546
10649
  return params.actualAttempts < params.maxTotalAttempts;
10547
10650
  }
10651
+ function validateLlmRetryConfig(config) {
10652
+ if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
10653
+ throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
10654
+ }
10655
+ if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
10656
+ throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
10657
+ }
10658
+ for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
10659
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
10660
+ throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
10661
+ }
10662
+ }
10663
+ }
10548
10664
 
10549
10665
  // src/runtime-kernel/llm/request-builder.ts
10550
10666
  function buildLlmCallerDeps(options) {
10551
10667
  const modelCatalog = options.modelCatalog;
10552
10668
  const maxRetries = options.maxRetries ?? 3;
10553
- return {
10554
- retryConfig: {
10669
+ const retryConfig = {
10670
+ maxRetries,
10671
+ maxRetriesByCategory: options.maxRetriesByCategory,
10672
+ maxTotalAttempts: resolveLlmMaxTotalAttempts({
10555
10673
  maxRetries,
10556
- maxTotalAttempts: resolveLlmMaxTotalAttempts({
10557
- maxRetries,
10558
- maxTotalAttempts: options.maxTotalAttempts
10559
- }),
10560
- enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10561
- retryDelayMs: options.retryDelayMs ?? 1e3
10562
- },
10674
+ maxTotalAttempts: options.maxTotalAttempts
10675
+ }),
10676
+ enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10677
+ retryDelayMs: options.retryDelayMs ?? 1e3
10678
+ };
10679
+ validateLlmRetryConfig(retryConfig);
10680
+ return {
10681
+ retryConfig,
10563
10682
  modelResolver: options.modelResolver ?? new ModelResolver({
10564
10683
  fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
10565
10684
  modelCatalog
@@ -11026,6 +11145,7 @@ var logger14 = new Logger("LlmCaller");
11026
11145
  var CanonicalInferenceFailureError = class extends Error {
11027
11146
  errorCode;
11028
11147
  recoverable;
11148
+ retryCategory;
11029
11149
  metadata;
11030
11150
  constructor(failure, abortReason) {
11031
11151
  const message = failure.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure.code}`;
@@ -11033,6 +11153,7 @@ var CanonicalInferenceFailureError = class extends Error {
11033
11153
  this.name = failure.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
11034
11154
  this.errorCode = `llm.${failure.code}`;
11035
11155
  this.recoverable = failure.retryable;
11156
+ this.retryCategory = failure.retry_category;
11036
11157
  this.metadata = { failure_kind: failure.kind, provider_code: failure.code };
11037
11158
  }
11038
11159
  };
@@ -11268,6 +11389,57 @@ async function callLlmStream(params) {
11268
11389
  };
11269
11390
  }
11270
11391
 
11392
+ // src/runtime-kernel/llm/functions/llmRetryEpisode.ts
11393
+ var SAFE_RETRY_MESSAGES = {
11394
+ transport: "Network connection interrupted",
11395
+ output: "Model output could not be accepted",
11396
+ rate_limit: "Model request rate limit reached",
11397
+ other: "Model request temporarily failed"
11398
+ };
11399
+ var LlmRetryEpisode = class {
11400
+ constructor(id, emit) {
11401
+ this.id = id;
11402
+ this.emit = emit;
11403
+ }
11404
+ id;
11405
+ emit;
11406
+ state;
11407
+ ended = false;
11408
+ get activeId() {
11409
+ return this.state ? this.id : void 0;
11410
+ }
11411
+ waiting(params, delay) {
11412
+ const now = Date.now();
11413
+ this.state = {
11414
+ ...params,
11415
+ retry_id: this.id,
11416
+ status: "waiting",
11417
+ started_at: this.state?.started_at ?? now,
11418
+ delay_ms: delay,
11419
+ next_retry_at: now + delay,
11420
+ error: SAFE_RETRY_MESSAGES[params.category]
11421
+ };
11422
+ this.publish();
11423
+ }
11424
+ retrying(totalAttempts) {
11425
+ if (!this.state || this.ended) return;
11426
+ const { next_retry_at: ignored, ...state } = this.state;
11427
+ this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
11428
+ this.publish();
11429
+ }
11430
+ finish(status, failure) {
11431
+ if (!this.state || this.ended) return;
11432
+ this.ended = true;
11433
+ const { next_retry_at: ignored, ...state } = this.state;
11434
+ this.state = { ...state, ...failure, status, delay_ms: 0, ...failure ? { error: SAFE_RETRY_MESSAGES[failure.category] } : {} };
11435
+ this.publish();
11436
+ }
11437
+ publish() {
11438
+ if (!this.state) return;
11439
+ this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
11440
+ }
11441
+ };
11442
+
11271
11443
  // src/runtime-kernel/llm/retry-fallback-routing.ts
11272
11444
  var logger15 = new Logger("LlmCaller");
11273
11445
  function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
@@ -11520,6 +11692,8 @@ async function callWithRetryFallback(params) {
11520
11692
  maxTotalAttempts: deps.retryConfig.maxTotalAttempts
11521
11693
  });
11522
11694
  const traceId = generateTraceId();
11695
+ const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
11696
+ const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
11523
11697
  let previousAttemptTracker;
11524
11698
  if (!clientRetryEnabled) {
11525
11699
  const activeCfg = deps.modelCatalog.getModelById(modelId);
@@ -11529,167 +11703,207 @@ async function callWithRetryFallback(params) {
11529
11703
  reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
11530
11704
  });
11531
11705
  }
11532
- for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11533
- throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11534
- if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11535
- eventHandler(previousAttemptTracker.buildResetEvent());
11536
- }
11537
- previousAttemptTracker = void 0;
11538
- const resolvedMessages = await runLlmInputPreflight({
11539
- activeModelId,
11540
- messages,
11541
- modelCatalog: deps.modelCatalog,
11542
- materializer: deps.llmInputMaterializer,
11543
- invocationContext,
11544
- eventHandler,
11545
- requirement
11546
- });
11547
- const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11548
- const isRetry = attempt > 0;
11549
- let pendingErrorEvent = null;
11550
- let streamedErrorClassification;
11551
- const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11552
- pendingErrorEvent = evt;
11553
- }) : void 0;
11554
- try {
11555
- if (isRetry) {
11556
- logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11557
- }
11558
- actualAttempts++;
11559
- const llmResponse = attemptTracker ? await callLlmStream({
11560
- inferencePort: deps.inferencePort,
11561
- modelId: activeModelId,
11562
- messages: resolvedMessages,
11563
- options,
11564
- eventHandler: attemptTracker.handle,
11565
- onErrorClassification(classification) {
11566
- streamedErrorClassification = classification;
11567
- },
11568
- signal,
11569
- toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11570
- traceId
11571
- }) : await callPlainCompletion(
11572
- deps.inferencePort,
11573
- activeModelId,
11574
- resolvedMessages,
11575
- options,
11576
- signal,
11577
- traceId
11578
- );
11579
- const responseContent = getLlmResultContent(llmResponse);
11580
- const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11581
- if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11582
- throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11583
- }
11584
- logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11585
- if (attemptContextUsage) {
11586
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11587
- } else {
11588
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11706
+ try {
11707
+ for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11708
+ throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11709
+ if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11710
+ eventHandler(previousAttemptTracker.buildResetEvent());
11589
11711
  }
11590
- return llmResponse;
11591
- } catch (error) {
11592
- lastError = error instanceof Error ? error : new Error(String(error));
11593
- if (lastError.name === "AbortError") {
11594
- logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11595
- attempt: attempt + 1,
11596
- actualAttempts,
11597
- maxTotalAttempts,
11598
- reason: lastError.message
11599
- });
11600
- throw lastError;
11601
- }
11602
- const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11603
- const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
11604
- logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11605
- attempt: attempt + 1,
11606
- maxAttempts: currentMaxRetries + 1,
11607
- actualAttempts,
11608
- maxTotalAttempts,
11609
- error: lastError.message
11712
+ previousAttemptTracker = void 0;
11713
+ const resolvedMessages = await runLlmInputPreflight({
11714
+ activeModelId,
11715
+ messages,
11716
+ modelCatalog: deps.modelCatalog,
11717
+ materializer: deps.llmInputMaterializer,
11718
+ invocationContext,
11719
+ eventHandler,
11720
+ requirement
11610
11721
  });
11611
- previousAttemptTracker = attemptTracker;
11612
- if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11613
- logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11614
- actualAttempts,
11615
- maxTotalAttempts
11616
- });
11617
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11618
- throw lastError;
11619
- }
11620
- if (options.allow_model_fallback !== false) {
11621
- const policySwitchModelId = tryPolicyModelSwitch(
11622
- deps,
11722
+ const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11723
+ const isRetry = attempt > 0;
11724
+ let pendingErrorEvent = null;
11725
+ let streamedErrorClassification;
11726
+ const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11727
+ pendingErrorEvent = evt;
11728
+ }) : void 0;
11729
+ try {
11730
+ if (isRetry) {
11731
+ logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11732
+ }
11733
+ actualAttempts++;
11734
+ retryEpisode.retrying(actualAttempts);
11735
+ const llmResponse = attemptTracker ? await callLlmStream({
11736
+ inferencePort: deps.inferencePort,
11737
+ modelId: activeModelId,
11738
+ messages: resolvedMessages,
11739
+ options,
11740
+ eventHandler: attemptTracker.handle,
11741
+ onErrorClassification(classification) {
11742
+ streamedErrorClassification = classification;
11743
+ },
11744
+ signal,
11745
+ toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11746
+ traceId
11747
+ }) : await callPlainCompletion(
11748
+ deps.inferencePort,
11623
11749
  activeModelId,
11624
- excludedModelIds,
11625
- requirement,
11626
- fallbackObserver,
11627
- lastError,
11628
- invocationContext?.evaluateFallbackPromptCapacity
11750
+ resolvedMessages,
11751
+ options,
11752
+ signal,
11753
+ traceId
11629
11754
  );
11630
- if (policySwitchModelId) {
11631
- fallbackObserver?.onModelFallbackApplied?.({
11632
- fromModelId: activeModelId,
11633
- toModelId: policySwitchModelId,
11634
- reason: lastError.message,
11635
- policy: "policy-switch"
11755
+ const responseContent = getLlmResultContent(llmResponse);
11756
+ const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11757
+ if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11758
+ throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11759
+ }
11760
+ logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11761
+ if (attemptContextUsage) {
11762
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11763
+ } else {
11764
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11765
+ }
11766
+ retryEpisode.finish("succeeded");
11767
+ return llmResponse;
11768
+ } catch (error) {
11769
+ lastError = error instanceof Error ? error : new Error(String(error));
11770
+ if (lastError.name === "AbortError") {
11771
+ logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11772
+ attempt: attempt + 1,
11773
+ actualAttempts,
11774
+ maxTotalAttempts,
11775
+ reason: lastError.message
11636
11776
  });
11637
- activeModelId = policySwitchModelId;
11638
- excludedModelIds.add(policySwitchModelId);
11639
- attempt -= 1;
11640
- continue;
11777
+ throw lastError;
11641
11778
  }
11642
- const quotaFallbackModelId = tryCloudQuotaFallback({
11643
- deps,
11644
- activeModelId,
11645
- options,
11646
- excludedModelIds,
11647
- requirement,
11648
- error: lastError,
11649
- fallbackObserver,
11650
- evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11779
+ const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11780
+ const category = ErrorClassifier.getRetryCategory(classification);
11781
+ const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
11782
+ const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
11783
+ const failedRetryState = {
11784
+ category,
11785
+ attempt: categoryRetries[category],
11786
+ max_retries: currentMaxRetries,
11787
+ total_attempts: actualAttempts,
11788
+ error_code: classification.errorCode
11789
+ };
11790
+ logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11791
+ attempt: attempt + 1,
11792
+ maxAttempts: currentMaxRetries + 1,
11793
+ actualAttempts,
11794
+ maxTotalAttempts,
11795
+ error: lastError.message
11651
11796
  });
11652
- if (quotaFallbackModelId) {
11653
- fallbackObserver?.onModelFallbackApplied?.({
11654
- fromModelId: activeModelId,
11655
- toModelId: quotaFallbackModelId,
11656
- reason: lastError.message,
11657
- policy: "cloud-quota"
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
11658
11802
  });
11659
- activeModelId = quotaFallbackModelId;
11660
- excludedModelIds.add(quotaFallbackModelId);
11661
- attempt -= 1;
11662
- continue;
11803
+ retryEpisode.finish("exhausted", failedRetryState);
11804
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11805
+ throw lastError;
11663
11806
  }
11664
- }
11665
- if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11666
- logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11667
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11668
- throw lastError;
11669
- }
11670
- if (attempt >= currentMaxRetries) {
11671
- logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11672
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11673
- throw lastError;
11674
- }
11675
- const retryDelay = ErrorClassifier.calculateRetryDelay(
11676
- classification,
11677
- attempt,
11678
- deps.retryConfig.retryDelayMs,
11679
- 6e4
11680
- );
11681
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11682
- logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11683
- } else if (classification.category === "retryable" /* RETRYABLE */) {
11684
- logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11685
- }
11686
- throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11687
- if (retryDelay > 0) {
11688
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
11689
- }
11690
- }
11807
+ if (options.allow_model_fallback !== false) {
11808
+ const policySwitchModelId = tryPolicyModelSwitch(
11809
+ deps,
11810
+ activeModelId,
11811
+ excludedModelIds,
11812
+ requirement,
11813
+ fallbackObserver,
11814
+ lastError,
11815
+ invocationContext?.evaluateFallbackPromptCapacity
11816
+ );
11817
+ if (policySwitchModelId) {
11818
+ fallbackObserver?.onModelFallbackApplied?.({
11819
+ fromModelId: activeModelId,
11820
+ toModelId: policySwitchModelId,
11821
+ reason: lastError.message,
11822
+ policy: "policy-switch"
11823
+ });
11824
+ activeModelId = policySwitchModelId;
11825
+ excludedModelIds.add(policySwitchModelId);
11826
+ attempt -= 1;
11827
+ continue;
11828
+ }
11829
+ const quotaFallbackModelId = tryCloudQuotaFallback({
11830
+ deps,
11831
+ activeModelId,
11832
+ options,
11833
+ excludedModelIds,
11834
+ requirement,
11835
+ error: lastError,
11836
+ fallbackObserver,
11837
+ evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11838
+ });
11839
+ if (quotaFallbackModelId) {
11840
+ fallbackObserver?.onModelFallbackApplied?.({
11841
+ fromModelId: activeModelId,
11842
+ toModelId: quotaFallbackModelId,
11843
+ reason: lastError.message,
11844
+ policy: "cloud-quota"
11845
+ });
11846
+ activeModelId = quotaFallbackModelId;
11847
+ excludedModelIds.add(quotaFallbackModelId);
11848
+ attempt -= 1;
11849
+ continue;
11850
+ }
11851
+ }
11852
+ if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11853
+ logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11854
+ retryEpisode.finish("failed", failedRetryState);
11855
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11856
+ throw lastError;
11857
+ }
11858
+ if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
11859
+ logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11860
+ retryEpisode.finish("exhausted", failedRetryState);
11861
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11862
+ throw lastError;
11863
+ }
11864
+ const retryDelay = ErrorClassifier.calculateRetryDelay(
11865
+ classification,
11866
+ categoryRetries[category],
11867
+ deps.retryConfig.retryDelayMs,
11868
+ 6e4
11869
+ );
11870
+ if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11871
+ logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11872
+ } else if (classification.category === "retryable" /* RETRYABLE */) {
11873
+ logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11874
+ }
11875
+ throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11876
+ categoryRetries[category] += 1;
11877
+ retryEpisode.waiting({
11878
+ category,
11879
+ attempt: categoryRetries[category],
11880
+ max_retries: currentMaxRetries,
11881
+ total_attempts: actualAttempts,
11882
+ error_code: classification.errorCode
11883
+ }, retryDelay);
11884
+ if (retryDelay > 0) await waitForRetry(retryDelay, signal);
11885
+ }
11886
+ }
11887
+ throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
11888
+ } catch (error) {
11889
+ retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
11890
+ throw error;
11691
11891
  }
11692
- throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
11892
+ }
11893
+ function waitForRetry(delayMs, signal) {
11894
+ throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
11895
+ return new Promise((resolve, reject) => {
11896
+ const onAbort = () => {
11897
+ clearTimeout(timer);
11898
+ signal?.removeEventListener("abort", onAbort);
11899
+ reject(new DOMException("Request interrupted during retry delay", "AbortError"));
11900
+ };
11901
+ const timer = setTimeout(() => {
11902
+ signal?.removeEventListener("abort", onAbort);
11903
+ resolve();
11904
+ }, delayMs);
11905
+ signal?.addEventListener("abort", onAbort, { once: true });
11906
+ });
11693
11907
  }
11694
11908
  function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
11695
11909
  if (options.retry_policy === "none") return false;
@@ -11748,9 +11962,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
11748
11962
  }
11749
11963
  };
11750
11964
  }
11751
- function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
11965
+ function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
11752
11966
  if (!eventHandler) return;
11753
- eventHandler(pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification));
11967
+ const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
11968
+ eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
11754
11969
  }
11755
11970
 
11756
11971
  // src/runtime-kernel/llm/caller.ts
@@ -12472,6 +12687,8 @@ var RuntimeEventSubRunTracePublisher = class {
12472
12687
  subrun_parent_id: this.subrunParentId,
12473
12688
  source_event_id: envelope.source_event_id,
12474
12689
  // 载荷透传
12690
+ ..."retry" in envelope ? { retry: envelope.retry } : {},
12691
+ ..."failure" in envelope ? { failure: envelope.failure } : {},
12475
12692
  ..."delta" in envelope ? { delta: envelope.delta } : {},
12476
12693
  ..."content" in envelope ? { content: envelope.content } : {},
12477
12694
  ..."answer_id" in envelope ? { answer_id: envelope.answer_id } : {},
@@ -12511,6 +12728,31 @@ var RuntimeEventSubRunTracePublisher = class {
12511
12728
  // src/runtime-kernel/child-run-trace/projectChildRuntimeEventToSubRunTrace.ts
12512
12729
  function projectChildRuntimeEventToSubRunTrace(event) {
12513
12730
  switch (event.type) {
12731
+ case "llm_retry":
12732
+ return {
12733
+ kind: "llm_retry",
12734
+ source_event_id: event.id,
12735
+ retry: {
12736
+ retry_id: event.retry_id,
12737
+ status: event.status,
12738
+ category: event.category,
12739
+ attempt: event.attempt,
12740
+ max_retries: event.max_retries,
12741
+ total_attempts: event.total_attempts,
12742
+ started_at: event.started_at,
12743
+ delay_ms: event.delay_ms,
12744
+ next_retry_at: event.next_retry_at,
12745
+ error: event.error,
12746
+ error_code: event.error_code
12747
+ }
12748
+ };
12749
+ case "error":
12750
+ return {
12751
+ kind: "error",
12752
+ source_event_id: event.id,
12753
+ // 父展示只需要安全错误与重试身份,不复制 child 的任意诊断 details。
12754
+ failure: { error: event.error, error_code: event.error_code, retryable: event.retryable, retry_id: event.retry_id }
12755
+ };
12514
12756
  case "thought":
12515
12757
  return event.is_complete ? {
12516
12758
  kind: "thought_complete",