@linnlabs/linnkit 0.37.4 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/cli.cjs +347 -179
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +347 -179
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +55 -11
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +55 -11
  9. package/dist/context-manager.js.map +1 -1
  10. package/dist/contracts/audit.d.cts +6 -6
  11. package/dist/contracts/audit.d.ts +6 -6
  12. package/dist/contracts/events.d.cts +532 -50
  13. package/dist/contracts/events.d.ts +532 -50
  14. package/dist/contracts/llm-retry.d.cts +47 -0
  15. package/dist/contracts/llm-retry.d.ts +47 -0
  16. package/dist/contracts/messages.d.cts +2 -2
  17. package/dist/contracts/messages.d.ts +2 -2
  18. package/dist/contracts/runtime-error.d.cts +26 -0
  19. package/dist/contracts/runtime-error.d.ts +26 -0
  20. package/dist/contracts/sse.d.cts +571 -55
  21. package/dist/contracts/sse.d.ts +571 -55
  22. package/dist/contracts/sub-run-trace-payload.d.cts +102 -6
  23. package/dist/contracts/sub-run-trace-payload.d.ts +102 -6
  24. package/dist/contracts/token-accounting.d.cts +18 -18
  25. package/dist/contracts/token-accounting.d.ts +18 -18
  26. package/dist/contracts.cjs +65 -10
  27. package/dist/contracts.cjs.map +1 -1
  28. package/dist/contracts.d.cts +4 -2
  29. package/dist/contracts.d.ts +4 -2
  30. package/dist/contracts.js +62 -11
  31. package/dist/contracts.js.map +1 -1
  32. package/dist/index.cjs +506 -286
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.js +506 -286
  35. package/dist/index.js.map +1 -1
  36. package/dist/ports/canonical-inference.d.cts +3 -0
  37. package/dist/ports/canonical-inference.d.ts +3 -0
  38. package/dist/ports/llm-call.d.cts +4 -0
  39. package/dist/ports/llm-call.d.ts +4 -0
  40. package/dist/quickstart.cjs +347 -179
  41. package/dist/quickstart.cjs.map +1 -1
  42. package/dist/quickstart.js +347 -179
  43. package/dist/quickstart.js.map +1 -1
  44. package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.cts +8 -0
  45. package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.ts +8 -0
  46. package/dist/runtime-kernel/events/agentEvents.d.cts +85 -4
  47. package/dist/runtime-kernel/events/agentEvents.d.ts +85 -4
  48. package/dist/runtime-kernel/events/eventGovernance.d.cts +1 -1
  49. package/dist/runtime-kernel/events/eventGovernance.d.ts +1 -1
  50. package/dist/runtime-kernel/events.cjs +55 -11
  51. package/dist/runtime-kernel/events.cjs.map +1 -1
  52. package/dist/runtime-kernel/events.js +55 -11
  53. package/dist/runtime-kernel/events.js.map +1 -1
  54. package/dist/runtime-kernel/llm/request-builder.d.cts +2 -0
  55. package/dist/runtime-kernel/llm/request-builder.d.ts +2 -0
  56. package/dist/runtime-kernel.cjs +468 -271
  57. package/dist/runtime-kernel.cjs.map +1 -1
  58. package/dist/runtime-kernel.js +468 -271
  59. package/dist/runtime-kernel.js.map +1 -1
  60. package/dist/shared/errorClassifier.d.cts +5 -0
  61. package/dist/shared/errorClassifier.d.ts +5 -0
  62. package/dist/testkit.cjs +466 -269
  63. package/dist/testkit.cjs.map +1 -1
  64. package/dist/testkit.js +466 -269
  65. package/dist/testkit.js.map +1 -1
  66. package/docs/integration/llm-provider.md +24 -0
  67. package/docs/integration/realtime.md +29 -0
  68. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -640,6 +640,28 @@ var AuditEnvelope = z.object({
640
640
  costDelta: AuditCostDelta.optional(),
641
641
  scope: AuditScope.optional()
642
642
  });
643
+ var LlmRetryCategory = z.enum(["transport", "output", "rate_limit", "other"]);
644
+ var LlmRetryState = z.object({
645
+ retry_id: TraceIdSchema,
646
+ status: z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
647
+ category: LlmRetryCategory,
648
+ attempt: z.number().int().nonnegative(),
649
+ max_retries: z.number().int().nonnegative(),
650
+ total_attempts: z.number().int().positive(),
651
+ started_at: z.number().finite(),
652
+ delay_ms: z.number().finite().nonnegative(),
653
+ next_retry_at: z.number().finite().optional(),
654
+ /** 安全分类说明;不得放入供应商响应正文。 */
655
+ error: z.string(),
656
+ error_code: z.string().min(1)
657
+ }).strict();
658
+ var RuntimeErrorState = z.object({
659
+ error: z.string(),
660
+ error_code: z.string().optional(),
661
+ retryable: z.boolean().optional(),
662
+ retry_id: TraceIdSchema.optional(),
663
+ details: SerializableJsonValue.optional()
664
+ }).strict();
643
665
  var ToolCallPhase = z.enum(["start", "update", "complete", "error"]);
644
666
  var Status = z.enum(["loading", "success", "error"]);
645
667
  var SubRunTraceKind = z.enum([
@@ -650,7 +672,9 @@ var SubRunTraceKind = z.enum([
650
672
  "tool_output",
651
673
  "final_answer_chunk",
652
674
  "final_answer",
653
- "history_summary"
675
+ "history_summary",
676
+ "llm_retry",
677
+ "error"
654
678
  ]);
655
679
  var SubRunTraceToolCallDecision = z.object({
656
680
  tool_call_id: ToolCallIdSchema,
@@ -663,6 +687,8 @@ var SubRunTracePayload = z.object({
663
687
  subrun_parent_id: SubrunIdSchema.optional(),
664
688
  source_event_id: SourceEventIdSchema,
665
689
  kind: SubRunTraceKind,
690
+ retry: LlmRetryState.optional(),
691
+ failure: RuntimeErrorState.optional(),
666
692
  delta: z.string().optional(),
667
693
  content: z.string().optional(),
668
694
  answer_id: AnswerSegmentIdSchema.optional(),
@@ -685,6 +711,12 @@ var SubRunTracePayload = z.object({
685
711
  meta: SerializableJsonRecord.optional()
686
712
  });
687
713
  function validateSubRunTracePayloadSemantics(payload, ctx) {
714
+ if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
715
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
716
+ }
717
+ if (payload.kind === "error" !== (payload.failure !== void 0)) {
718
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
719
+ }
688
720
  if (payload.kind === "thought_delta" && payload.delta === void 0) {
689
721
  ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
690
722
  }
@@ -1038,12 +1070,10 @@ var RuntimeEventShape = z.discriminatedUnion("type", [
1038
1070
  compression_ratio: z.number().min(0).max(1).optional(),
1039
1071
  included_old_summary: z.boolean().optional()
1040
1072
  }),
1073
+ BaseEvent.extend({ type: z.literal("llm_retry"), ...LlmRetryState.shape }),
1041
1074
  BaseEvent.extend({
1042
1075
  type: z.literal("error"),
1043
- error: z.string(),
1044
- details: SerializableJsonValue.optional(),
1045
- error_code: z.string().optional(),
1046
- retryable: z.boolean().optional()
1076
+ ...RuntimeErrorState.shape
1047
1077
  }),
1048
1078
  BaseEvent.extend({
1049
1079
  type: z.literal("control"),
@@ -1465,12 +1495,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
1465
1495
  resume_token: ResumeTokenSchema,
1466
1496
  interaction_status: z.literal("pending")
1467
1497
  });
1498
+ var SSELlmRetryEvent = BaseSSEEvent.extend({
1499
+ type: z.literal("llm_retry"),
1500
+ ...LlmRetryState.shape
1501
+ });
1468
1502
  var SSEErrorEvent = BaseSSEEvent.extend({
1469
1503
  type: z.literal("error"),
1470
- error: z.string(),
1471
- details: SerializableJsonValue.optional(),
1472
- error_code: z.string().optional(),
1473
- retryable: z.boolean().optional()
1504
+ ...RuntimeErrorState.shape
1474
1505
  });
1475
1506
  var SSETransportErrorEvent = BaseSSEEvent.extend({
1476
1507
  type: z.literal("transport_error"),
@@ -1553,6 +1584,7 @@ z.discriminatedUnion("type", [
1553
1584
  SSEToolOutputEvent,
1554
1585
  SSESubRunTraceEvent,
1555
1586
  SSERequiresUserInteractionEvent,
1587
+ SSELlmRetryEvent,
1556
1588
  SSEErrorEvent,
1557
1589
  SSETransportErrorEvent,
1558
1590
  SSEContextUsageSnapshotEvent,
@@ -2002,6 +2034,7 @@ var Logger = class {
2002
2034
  var ENGINE_ERROR_CODES = {
2003
2035
  LLM_RATE_LIMIT: "llm.rate_limit",
2004
2036
  LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
2037
+ LLM_EMPTY_RESPONSE: "llm.empty_response",
2005
2038
  LLM_PROVIDER_DOWN: "llm.provider_down",
2006
2039
  LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
2007
2040
  LLM_AUTH_FAILED: "llm.auth_failed",
@@ -2108,6 +2141,8 @@ function readStructuredClassification(error) {
2108
2141
  if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
2109
2142
  if (typeof recoverable !== "boolean") return void 0;
2110
2143
  const errorCode = rawErrorCode.trim();
2144
+ const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
2145
+ const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
2111
2146
  const retryAfterMsValue = error["retryAfterMs"];
2112
2147
  const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
2113
2148
  const hintValue = error["hint"];
@@ -2115,12 +2150,13 @@ function readStructuredClassification(error) {
2115
2150
  const metadataValue = error["metadata"];
2116
2151
  const metadata = isRecord(metadataValue) ? metadataValue : void 0;
2117
2152
  return createClassification(
2118
- recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
2153
+ recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
2119
2154
  `\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
2120
2155
  recoverable ? retryAfterMs ?? 1e3 : null,
2121
2156
  {
2122
2157
  errorCode,
2123
2158
  recoverable,
2159
+ ...retryCategory === void 0 ? {} : { retryCategory },
2124
2160
  ...retryAfterMs === void 0 ? {} : { retryAfterMs },
2125
2161
  ...hint === void 0 ? {} : { hint },
2126
2162
  ...metadata === void 0 ? {} : { metadata }
@@ -2395,7 +2431,7 @@ var ErrorClassifier = class {
2395
2431
  if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
2396
2432
  logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
2397
2433
  return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
2398
- errorCode: ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN,
2434
+ errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
2399
2435
  recoverable: true,
2400
2436
  retryAfterMs: 1e3,
2401
2437
  hint: "retry_with_backoff",
@@ -2420,15 +2456,23 @@ var ErrorClassifier = class {
2420
2456
  const category = this.categorize(error);
2421
2457
  return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
2422
2458
  }
2459
+ static getRetryCategory(classification) {
2460
+ if (classification.retryCategory !== void 0) return classification.retryCategory;
2461
+ if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
2462
+ if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
2463
+ if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
2464
+ return "other";
2465
+ }
2423
2466
  static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
2424
2467
  const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
2425
2468
  if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
2426
2469
  return 0;
2427
2470
  }
2428
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
2429
- return Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay);
2471
+ const retryCategory = this.getRetryCategory(classification);
2472
+ if (retryCategory === "rate_limit" || retryCategory === "transport") {
2473
+ return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
2430
2474
  }
2431
- return classification.suggestedDelay || baseDelay;
2475
+ return Math.max(baseDelay, classification.suggestedDelay ?? 0);
2432
2476
  }
2433
2477
  static isCloudQuotaError(error) {
2434
2478
  const msg = (error.message || "").toLowerCase();
@@ -6342,6 +6386,8 @@ function getRuntimeEventUiProjectionKind(event) {
6342
6386
  return "audit_envelope";
6343
6387
  case "subrun_trace":
6344
6388
  return "subrun_trace";
6389
+ case "llm_retry":
6390
+ return "llm_retry";
6345
6391
  case "error":
6346
6392
  return "error";
6347
6393
  case "context_usage_snapshot":
@@ -6371,7 +6417,7 @@ function describeRuntimeEventLifecycle(event) {
6371
6417
  if (isContextUsageSnapshotRuntimeEvent(event)) {
6372
6418
  return false;
6373
6419
  }
6374
- if (event.type === "error") {
6420
+ if (event.type === "error" || event.type === "llm_retry") {
6375
6421
  return false;
6376
6422
  }
6377
6423
  if (isRequiresUserInteractionRuntimeEvent(event)) {
@@ -6414,6 +6460,7 @@ function describeRuntimeEventLifecycle(event) {
6414
6460
  case "tool_output":
6415
6461
  case "requires_user_interaction":
6416
6462
  case "subrun_trace":
6463
+ case "llm_retry":
6417
6464
  case "error":
6418
6465
  case "context_usage_snapshot":
6419
6466
  case "run_execution_metrics":
@@ -6630,8 +6677,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
6630
6677
  assistant_replay_parts: AssistantReplayParts.optional(),
6631
6678
  meta: UnknownRecord.optional()
6632
6679
  }).strict();
6680
+ var LlmRetryEventSchema = BaseAgentEvent.extend({
6681
+ type: z.literal("llm_retry"),
6682
+ ...LlmRetryState.shape
6683
+ }).strict();
6633
6684
  var ErrorEventSchema = BaseAgentEvent.extend({
6634
6685
  type: z.literal("error"),
6686
+ retry_id: LlmRetryState.shape.retry_id.optional(),
6635
6687
  error: z.string(),
6636
6688
  error_code: z.string().optional(),
6637
6689
  retryable: z.boolean().optional(),
@@ -6661,6 +6713,7 @@ var AgentEventSchema = z.discriminatedUnion("type", [
6661
6713
  ToolProcessEventSchema,
6662
6714
  ObservationEventSchema,
6663
6715
  FinalAnswerEventSchema,
6716
+ LlmRetryEventSchema,
6664
6717
  ErrorEventSchema,
6665
6718
  StreamChunkEventSchema,
6666
6719
  StreamResetEventSchema,
@@ -6761,13 +6814,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
6761
6814
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
6762
6815
  return event;
6763
6816
  }
6817
+ case "llm_retry":
6818
+ return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
6764
6819
  case "error": {
6765
6820
  const errorEvent = typed;
6766
6821
  const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
6767
6822
  timestamp,
6768
6823
  details: toSerializableJsonValue(errorEvent.details),
6769
6824
  error_code: errorEvent.error_code,
6770
- retryable: errorEvent.retryable
6825
+ retryable: errorEvent.retryable,
6826
+ retry_id: errorEvent.retry_id
6771
6827
  });
6772
6828
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
6773
6829
  return event;
@@ -9966,7 +10022,7 @@ var EventBusEventPersistence = class {
9966
10022
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
9967
10023
  return;
9968
10024
  }
9969
- if (this.checkpointWritesActive) {
10025
+ if (this.checkpointWritesActive && event.type !== "llm_retry") {
9970
10026
  this.scheduledEventIds.add(event.id);
9971
10027
  this.checkpointEvents.push(event);
9972
10028
  return;
@@ -10103,21 +10159,37 @@ function resolveLlmMaxTotalAttempts(config) {
10103
10159
  function hasLlmAttemptBudgetRemaining(params) {
10104
10160
  return params.actualAttempts < params.maxTotalAttempts;
10105
10161
  }
10162
+ function validateLlmRetryConfig(config) {
10163
+ if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
10164
+ throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
10165
+ }
10166
+ if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
10167
+ throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
10168
+ }
10169
+ for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
10170
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
10171
+ throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
10172
+ }
10173
+ }
10174
+ }
10106
10175
 
10107
10176
  // src/runtime-kernel/llm/request-builder.ts
10108
10177
  function buildLlmCallerDeps(options) {
10109
10178
  const modelCatalog = options.modelCatalog;
10110
10179
  const maxRetries = options.maxRetries ?? 3;
10111
- return {
10112
- retryConfig: {
10180
+ const retryConfig = {
10181
+ maxRetries,
10182
+ maxRetriesByCategory: options.maxRetriesByCategory,
10183
+ maxTotalAttempts: resolveLlmMaxTotalAttempts({
10113
10184
  maxRetries,
10114
- maxTotalAttempts: resolveLlmMaxTotalAttempts({
10115
- maxRetries,
10116
- maxTotalAttempts: options.maxTotalAttempts
10117
- }),
10118
- enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10119
- retryDelayMs: options.retryDelayMs ?? 1e3
10120
- },
10185
+ maxTotalAttempts: options.maxTotalAttempts
10186
+ }),
10187
+ enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10188
+ retryDelayMs: options.retryDelayMs ?? 1e3
10189
+ };
10190
+ validateLlmRetryConfig(retryConfig);
10191
+ return {
10192
+ retryConfig,
10121
10193
  modelResolver: options.modelResolver ?? new ModelResolver({
10122
10194
  fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
10123
10195
  modelCatalog
@@ -10584,6 +10656,7 @@ var logger14 = new Logger("LlmCaller");
10584
10656
  var CanonicalInferenceFailureError = class extends Error {
10585
10657
  errorCode;
10586
10658
  recoverable;
10659
+ retryCategory;
10587
10660
  metadata;
10588
10661
  constructor(failure, abortReason) {
10589
10662
  const message = failure.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure.code}`;
@@ -10591,6 +10664,7 @@ var CanonicalInferenceFailureError = class extends Error {
10591
10664
  this.name = failure.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
10592
10665
  this.errorCode = `llm.${failure.code}`;
10593
10666
  this.recoverable = failure.retryable;
10667
+ this.retryCategory = failure.retry_category;
10594
10668
  this.metadata = { failure_kind: failure.kind, provider_code: failure.code };
10595
10669
  }
10596
10670
  };
@@ -10826,6 +10900,57 @@ async function callLlmStream(params) {
10826
10900
  };
10827
10901
  }
10828
10902
 
10903
+ // src/runtime-kernel/llm/functions/llmRetryEpisode.ts
10904
+ var SAFE_RETRY_MESSAGES = {
10905
+ transport: "Network connection interrupted",
10906
+ output: "Model output could not be accepted",
10907
+ rate_limit: "Model request rate limit reached",
10908
+ other: "Model request temporarily failed"
10909
+ };
10910
+ var LlmRetryEpisode = class {
10911
+ constructor(id, emit) {
10912
+ this.id = id;
10913
+ this.emit = emit;
10914
+ }
10915
+ id;
10916
+ emit;
10917
+ state;
10918
+ ended = false;
10919
+ get activeId() {
10920
+ return this.state ? this.id : void 0;
10921
+ }
10922
+ waiting(params, delay) {
10923
+ const now = Date.now();
10924
+ this.state = {
10925
+ ...params,
10926
+ retry_id: this.id,
10927
+ status: "waiting",
10928
+ started_at: this.state?.started_at ?? now,
10929
+ delay_ms: delay,
10930
+ next_retry_at: now + delay,
10931
+ error: SAFE_RETRY_MESSAGES[params.category]
10932
+ };
10933
+ this.publish();
10934
+ }
10935
+ retrying(totalAttempts) {
10936
+ if (!this.state || this.ended) return;
10937
+ const { next_retry_at: ignored, ...state } = this.state;
10938
+ this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
10939
+ this.publish();
10940
+ }
10941
+ finish(status, failure) {
10942
+ if (!this.state || this.ended) return;
10943
+ this.ended = true;
10944
+ const { next_retry_at: ignored, ...state } = this.state;
10945
+ this.state = { ...state, ...failure, status, delay_ms: 0, ...failure ? { error: SAFE_RETRY_MESSAGES[failure.category] } : {} };
10946
+ this.publish();
10947
+ }
10948
+ publish() {
10949
+ if (!this.state) return;
10950
+ this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
10951
+ }
10952
+ };
10953
+
10829
10954
  // src/runtime-kernel/llm/retry-fallback-routing.ts
10830
10955
  var logger15 = new Logger("LlmCaller");
10831
10956
  function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
@@ -11058,6 +11183,8 @@ async function callWithRetryFallback(params) {
11058
11183
  maxTotalAttempts: deps.retryConfig.maxTotalAttempts
11059
11184
  });
11060
11185
  const traceId = generateTraceId();
11186
+ const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
11187
+ const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
11061
11188
  let previousAttemptTracker;
11062
11189
  if (!clientRetryEnabled) {
11063
11190
  const activeCfg = deps.modelCatalog.getModelById(modelId);
@@ -11067,167 +11194,207 @@ async function callWithRetryFallback(params) {
11067
11194
  reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
11068
11195
  });
11069
11196
  }
11070
- for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11071
- throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11072
- if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11073
- eventHandler(previousAttemptTracker.buildResetEvent());
11074
- }
11075
- previousAttemptTracker = void 0;
11076
- const resolvedMessages = await runLlmInputPreflight({
11077
- activeModelId,
11078
- messages,
11079
- modelCatalog: deps.modelCatalog,
11080
- materializer: deps.llmInputMaterializer,
11081
- invocationContext,
11082
- eventHandler,
11083
- requirement
11084
- });
11085
- const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11086
- const isRetry = attempt > 0;
11087
- let pendingErrorEvent = null;
11088
- let streamedErrorClassification;
11089
- const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11090
- pendingErrorEvent = evt;
11091
- }) : void 0;
11092
- try {
11093
- if (isRetry) {
11094
- logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11095
- }
11096
- actualAttempts++;
11097
- const llmResponse = attemptTracker ? await callLlmStream({
11098
- inferencePort: deps.inferencePort,
11099
- modelId: activeModelId,
11100
- messages: resolvedMessages,
11101
- options,
11102
- eventHandler: attemptTracker.handle,
11103
- onErrorClassification(classification) {
11104
- streamedErrorClassification = classification;
11105
- },
11106
- signal,
11107
- toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11108
- traceId
11109
- }) : await callPlainCompletion(
11110
- deps.inferencePort,
11111
- activeModelId,
11112
- resolvedMessages,
11113
- options,
11114
- signal,
11115
- traceId
11116
- );
11117
- const responseContent = getLlmResultContent(llmResponse);
11118
- const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11119
- if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11120
- throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11121
- }
11122
- logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11123
- if (attemptContextUsage) {
11124
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11125
- } else {
11126
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11197
+ try {
11198
+ for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11199
+ throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11200
+ if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11201
+ eventHandler(previousAttemptTracker.buildResetEvent());
11127
11202
  }
11128
- return llmResponse;
11129
- } catch (error) {
11130
- lastError = error instanceof Error ? error : new Error(String(error));
11131
- if (lastError.name === "AbortError") {
11132
- logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11133
- attempt: attempt + 1,
11134
- actualAttempts,
11135
- maxTotalAttempts,
11136
- reason: lastError.message
11137
- });
11138
- throw lastError;
11139
- }
11140
- const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11141
- const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
11142
- logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11143
- attempt: attempt + 1,
11144
- maxAttempts: currentMaxRetries + 1,
11145
- actualAttempts,
11146
- maxTotalAttempts,
11147
- error: lastError.message
11203
+ previousAttemptTracker = void 0;
11204
+ const resolvedMessages = await runLlmInputPreflight({
11205
+ activeModelId,
11206
+ messages,
11207
+ modelCatalog: deps.modelCatalog,
11208
+ materializer: deps.llmInputMaterializer,
11209
+ invocationContext,
11210
+ eventHandler,
11211
+ requirement
11148
11212
  });
11149
- previousAttemptTracker = attemptTracker;
11150
- if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11151
- logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11152
- actualAttempts,
11153
- maxTotalAttempts
11154
- });
11155
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11156
- throw lastError;
11157
- }
11158
- if (options.allow_model_fallback !== false) {
11159
- const policySwitchModelId = tryPolicyModelSwitch(
11160
- deps,
11213
+ const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11214
+ const isRetry = attempt > 0;
11215
+ let pendingErrorEvent = null;
11216
+ let streamedErrorClassification;
11217
+ const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11218
+ pendingErrorEvent = evt;
11219
+ }) : void 0;
11220
+ try {
11221
+ if (isRetry) {
11222
+ logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11223
+ }
11224
+ actualAttempts++;
11225
+ retryEpisode.retrying(actualAttempts);
11226
+ const llmResponse = attemptTracker ? await callLlmStream({
11227
+ inferencePort: deps.inferencePort,
11228
+ modelId: activeModelId,
11229
+ messages: resolvedMessages,
11230
+ options,
11231
+ eventHandler: attemptTracker.handle,
11232
+ onErrorClassification(classification) {
11233
+ streamedErrorClassification = classification;
11234
+ },
11235
+ signal,
11236
+ toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11237
+ traceId
11238
+ }) : await callPlainCompletion(
11239
+ deps.inferencePort,
11161
11240
  activeModelId,
11162
- excludedModelIds,
11163
- requirement,
11164
- fallbackObserver,
11165
- lastError,
11166
- invocationContext?.evaluateFallbackPromptCapacity
11241
+ resolvedMessages,
11242
+ options,
11243
+ signal,
11244
+ traceId
11167
11245
  );
11168
- if (policySwitchModelId) {
11169
- fallbackObserver?.onModelFallbackApplied?.({
11170
- fromModelId: activeModelId,
11171
- toModelId: policySwitchModelId,
11172
- reason: lastError.message,
11173
- policy: "policy-switch"
11246
+ const responseContent = getLlmResultContent(llmResponse);
11247
+ const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11248
+ if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11249
+ throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11250
+ }
11251
+ logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11252
+ if (attemptContextUsage) {
11253
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11254
+ } else {
11255
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11256
+ }
11257
+ retryEpisode.finish("succeeded");
11258
+ return llmResponse;
11259
+ } catch (error) {
11260
+ lastError = error instanceof Error ? error : new Error(String(error));
11261
+ if (lastError.name === "AbortError") {
11262
+ logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11263
+ attempt: attempt + 1,
11264
+ actualAttempts,
11265
+ maxTotalAttempts,
11266
+ reason: lastError.message
11174
11267
  });
11175
- activeModelId = policySwitchModelId;
11176
- excludedModelIds.add(policySwitchModelId);
11177
- attempt -= 1;
11178
- continue;
11268
+ throw lastError;
11179
11269
  }
11180
- const quotaFallbackModelId = tryCloudQuotaFallback({
11181
- deps,
11182
- activeModelId,
11183
- options,
11184
- excludedModelIds,
11185
- requirement,
11186
- error: lastError,
11187
- fallbackObserver,
11188
- evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11270
+ const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11271
+ const category = ErrorClassifier.getRetryCategory(classification);
11272
+ const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
11273
+ const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
11274
+ const failedRetryState = {
11275
+ category,
11276
+ attempt: categoryRetries[category],
11277
+ max_retries: currentMaxRetries,
11278
+ total_attempts: actualAttempts,
11279
+ error_code: classification.errorCode
11280
+ };
11281
+ logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11282
+ attempt: attempt + 1,
11283
+ maxAttempts: currentMaxRetries + 1,
11284
+ actualAttempts,
11285
+ maxTotalAttempts,
11286
+ error: lastError.message
11189
11287
  });
11190
- if (quotaFallbackModelId) {
11191
- fallbackObserver?.onModelFallbackApplied?.({
11192
- fromModelId: activeModelId,
11193
- toModelId: quotaFallbackModelId,
11194
- reason: lastError.message,
11195
- policy: "cloud-quota"
11288
+ previousAttemptTracker = attemptTracker;
11289
+ if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11290
+ logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11291
+ actualAttempts,
11292
+ maxTotalAttempts
11196
11293
  });
11197
- activeModelId = quotaFallbackModelId;
11198
- excludedModelIds.add(quotaFallbackModelId);
11199
- attempt -= 1;
11200
- continue;
11294
+ retryEpisode.finish("exhausted", failedRetryState);
11295
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11296
+ throw lastError;
11201
11297
  }
11202
- }
11203
- if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11204
- logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11205
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11206
- throw lastError;
11207
- }
11208
- if (attempt >= currentMaxRetries) {
11209
- logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11210
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11211
- throw lastError;
11212
- }
11213
- const retryDelay = ErrorClassifier.calculateRetryDelay(
11214
- classification,
11215
- attempt,
11216
- deps.retryConfig.retryDelayMs,
11217
- 6e4
11218
- );
11219
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11220
- logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11221
- } else if (classification.category === "retryable" /* RETRYABLE */) {
11222
- logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11223
- }
11224
- throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11225
- if (retryDelay > 0) {
11226
- await new Promise((resolve5) => setTimeout(resolve5, retryDelay));
11227
- }
11228
- }
11298
+ if (options.allow_model_fallback !== false) {
11299
+ const policySwitchModelId = tryPolicyModelSwitch(
11300
+ deps,
11301
+ activeModelId,
11302
+ excludedModelIds,
11303
+ requirement,
11304
+ fallbackObserver,
11305
+ lastError,
11306
+ invocationContext?.evaluateFallbackPromptCapacity
11307
+ );
11308
+ if (policySwitchModelId) {
11309
+ fallbackObserver?.onModelFallbackApplied?.({
11310
+ fromModelId: activeModelId,
11311
+ toModelId: policySwitchModelId,
11312
+ reason: lastError.message,
11313
+ policy: "policy-switch"
11314
+ });
11315
+ activeModelId = policySwitchModelId;
11316
+ excludedModelIds.add(policySwitchModelId);
11317
+ attempt -= 1;
11318
+ continue;
11319
+ }
11320
+ const quotaFallbackModelId = tryCloudQuotaFallback({
11321
+ deps,
11322
+ activeModelId,
11323
+ options,
11324
+ excludedModelIds,
11325
+ requirement,
11326
+ error: lastError,
11327
+ fallbackObserver,
11328
+ evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11329
+ });
11330
+ if (quotaFallbackModelId) {
11331
+ fallbackObserver?.onModelFallbackApplied?.({
11332
+ fromModelId: activeModelId,
11333
+ toModelId: quotaFallbackModelId,
11334
+ reason: lastError.message,
11335
+ policy: "cloud-quota"
11336
+ });
11337
+ activeModelId = quotaFallbackModelId;
11338
+ excludedModelIds.add(quotaFallbackModelId);
11339
+ attempt -= 1;
11340
+ continue;
11341
+ }
11342
+ }
11343
+ if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11344
+ logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11345
+ retryEpisode.finish("failed", failedRetryState);
11346
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11347
+ throw lastError;
11348
+ }
11349
+ if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
11350
+ logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11351
+ retryEpisode.finish("exhausted", failedRetryState);
11352
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11353
+ throw lastError;
11354
+ }
11355
+ const retryDelay = ErrorClassifier.calculateRetryDelay(
11356
+ classification,
11357
+ categoryRetries[category],
11358
+ deps.retryConfig.retryDelayMs,
11359
+ 6e4
11360
+ );
11361
+ if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11362
+ logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11363
+ } else if (classification.category === "retryable" /* RETRYABLE */) {
11364
+ logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11365
+ }
11366
+ throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11367
+ categoryRetries[category] += 1;
11368
+ retryEpisode.waiting({
11369
+ category,
11370
+ attempt: categoryRetries[category],
11371
+ max_retries: currentMaxRetries,
11372
+ total_attempts: actualAttempts,
11373
+ error_code: classification.errorCode
11374
+ }, retryDelay);
11375
+ if (retryDelay > 0) await waitForRetry(retryDelay, signal);
11376
+ }
11377
+ }
11378
+ throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
11379
+ } catch (error) {
11380
+ retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
11381
+ throw error;
11229
11382
  }
11230
- throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
11383
+ }
11384
+ function waitForRetry(delayMs, signal) {
11385
+ throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
11386
+ return new Promise((resolve5, reject) => {
11387
+ const onAbort = () => {
11388
+ clearTimeout(timer);
11389
+ signal?.removeEventListener("abort", onAbort);
11390
+ reject(new DOMException("Request interrupted during retry delay", "AbortError"));
11391
+ };
11392
+ const timer = setTimeout(() => {
11393
+ signal?.removeEventListener("abort", onAbort);
11394
+ resolve5();
11395
+ }, delayMs);
11396
+ signal?.addEventListener("abort", onAbort, { once: true });
11397
+ });
11231
11398
  }
11232
11399
  function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
11233
11400
  if (options.retry_policy === "none") return false;
@@ -11286,9 +11453,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
11286
11453
  }
11287
11454
  };
11288
11455
  }
11289
- function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
11456
+ function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
11290
11457
  if (!eventHandler) return;
11291
- eventHandler(pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification));
11458
+ const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
11459
+ eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
11292
11460
  }
11293
11461
 
11294
11462
  // src/runtime-kernel/llm/caller.ts