@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
@@ -706,6 +706,28 @@ var AuditEnvelope = z.object({
706
706
  costDelta: AuditCostDelta.optional(),
707
707
  scope: AuditScope.optional()
708
708
  });
709
+ var LlmRetryCategory = z.enum(["transport", "output", "rate_limit", "other"]);
710
+ var LlmRetryState = z.object({
711
+ retry_id: TraceIdSchema,
712
+ status: z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
713
+ category: LlmRetryCategory,
714
+ attempt: z.number().int().nonnegative(),
715
+ max_retries: z.number().int().nonnegative(),
716
+ total_attempts: z.number().int().positive(),
717
+ started_at: z.number().finite(),
718
+ delay_ms: z.number().finite().nonnegative(),
719
+ next_retry_at: z.number().finite().optional(),
720
+ /** 安全分类说明;不得放入供应商响应正文。 */
721
+ error: z.string(),
722
+ error_code: z.string().min(1)
723
+ }).strict();
724
+ var RuntimeErrorState = z.object({
725
+ error: z.string(),
726
+ error_code: z.string().optional(),
727
+ retryable: z.boolean().optional(),
728
+ retry_id: TraceIdSchema.optional(),
729
+ details: SerializableJsonValue.optional()
730
+ }).strict();
709
731
  var ToolCallPhase = z.enum(["start", "update", "complete", "error"]);
710
732
  var Status = z.enum(["loading", "success", "error"]);
711
733
  var SubRunTraceKind = z.enum([
@@ -716,7 +738,9 @@ var SubRunTraceKind = z.enum([
716
738
  "tool_output",
717
739
  "final_answer_chunk",
718
740
  "final_answer",
719
- "history_summary"
741
+ "history_summary",
742
+ "llm_retry",
743
+ "error"
720
744
  ]);
721
745
  var SubRunTraceToolCallDecision = z.object({
722
746
  tool_call_id: ToolCallIdSchema,
@@ -729,6 +753,8 @@ var SubRunTracePayload = z.object({
729
753
  subrun_parent_id: SubrunIdSchema.optional(),
730
754
  source_event_id: SourceEventIdSchema,
731
755
  kind: SubRunTraceKind,
756
+ retry: LlmRetryState.optional(),
757
+ failure: RuntimeErrorState.optional(),
732
758
  delta: z.string().optional(),
733
759
  content: z.string().optional(),
734
760
  answer_id: AnswerSegmentIdSchema.optional(),
@@ -751,6 +777,12 @@ var SubRunTracePayload = z.object({
751
777
  meta: SerializableJsonRecord.optional()
752
778
  });
753
779
  function validateSubRunTracePayloadSemantics(payload, ctx) {
780
+ if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
781
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
782
+ }
783
+ if (payload.kind === "error" !== (payload.failure !== void 0)) {
784
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
785
+ }
754
786
  if (payload.kind === "thought_delta" && payload.delta === void 0) {
755
787
  ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
756
788
  }
@@ -1104,12 +1136,10 @@ var RuntimeEventShape = z.discriminatedUnion("type", [
1104
1136
  compression_ratio: z.number().min(0).max(1).optional(),
1105
1137
  included_old_summary: z.boolean().optional()
1106
1138
  }),
1139
+ BaseEvent.extend({ type: z.literal("llm_retry"), ...LlmRetryState.shape }),
1107
1140
  BaseEvent.extend({
1108
1141
  type: z.literal("error"),
1109
- error: z.string(),
1110
- details: SerializableJsonValue.optional(),
1111
- error_code: z.string().optional(),
1112
- retryable: z.boolean().optional()
1142
+ ...RuntimeErrorState.shape
1113
1143
  }),
1114
1144
  BaseEvent.extend({
1115
1145
  type: z.literal("control"),
@@ -1531,12 +1561,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
1531
1561
  resume_token: ResumeTokenSchema,
1532
1562
  interaction_status: z.literal("pending")
1533
1563
  });
1564
+ var SSELlmRetryEvent = BaseSSEEvent.extend({
1565
+ type: z.literal("llm_retry"),
1566
+ ...LlmRetryState.shape
1567
+ });
1534
1568
  var SSEErrorEvent = BaseSSEEvent.extend({
1535
1569
  type: z.literal("error"),
1536
- error: z.string(),
1537
- details: SerializableJsonValue.optional(),
1538
- error_code: z.string().optional(),
1539
- retryable: z.boolean().optional()
1570
+ ...RuntimeErrorState.shape
1540
1571
  });
1541
1572
  var SSETransportErrorEvent = BaseSSEEvent.extend({
1542
1573
  type: z.literal("transport_error"),
@@ -1619,6 +1650,7 @@ z.discriminatedUnion("type", [
1619
1650
  SSEToolOutputEvent,
1620
1651
  SSESubRunTraceEvent,
1621
1652
  SSERequiresUserInteractionEvent,
1653
+ SSELlmRetryEvent,
1622
1654
  SSEErrorEvent,
1623
1655
  SSETransportErrorEvent,
1624
1656
  SSEContextUsageSnapshotEvent,
@@ -2116,6 +2148,7 @@ var Logger = class {
2116
2148
  var ENGINE_ERROR_CODES = {
2117
2149
  LLM_RATE_LIMIT: "llm.rate_limit",
2118
2150
  LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
2151
+ LLM_EMPTY_RESPONSE: "llm.empty_response",
2119
2152
  LLM_PROVIDER_DOWN: "llm.provider_down",
2120
2153
  LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
2121
2154
  LLM_AUTH_FAILED: "llm.auth_failed",
@@ -2222,6 +2255,8 @@ function readStructuredClassification(error) {
2222
2255
  if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
2223
2256
  if (typeof recoverable !== "boolean") return void 0;
2224
2257
  const errorCode = rawErrorCode.trim();
2258
+ const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
2259
+ const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
2225
2260
  const retryAfterMsValue = error["retryAfterMs"];
2226
2261
  const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
2227
2262
  const hintValue = error["hint"];
@@ -2229,12 +2264,13 @@ function readStructuredClassification(error) {
2229
2264
  const metadataValue = error["metadata"];
2230
2265
  const metadata = isRecord(metadataValue) ? metadataValue : void 0;
2231
2266
  return createClassification(
2232
- recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
2267
+ recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
2233
2268
  `\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
2234
2269
  recoverable ? retryAfterMs ?? 1e3 : null,
2235
2270
  {
2236
2271
  errorCode,
2237
2272
  recoverable,
2273
+ ...retryCategory === void 0 ? {} : { retryCategory },
2238
2274
  ...retryAfterMs === void 0 ? {} : { retryAfterMs },
2239
2275
  ...hint === void 0 ? {} : { hint },
2240
2276
  ...metadata === void 0 ? {} : { metadata }
@@ -2509,7 +2545,7 @@ var ErrorClassifier = class {
2509
2545
  if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
2510
2546
  logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
2511
2547
  return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
2512
- errorCode: ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN,
2548
+ errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
2513
2549
  recoverable: true,
2514
2550
  retryAfterMs: 1e3,
2515
2551
  hint: "retry_with_backoff",
@@ -2534,15 +2570,23 @@ var ErrorClassifier = class {
2534
2570
  const category = this.categorize(error);
2535
2571
  return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
2536
2572
  }
2573
+ static getRetryCategory(classification) {
2574
+ if (classification.retryCategory !== void 0) return classification.retryCategory;
2575
+ if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
2576
+ if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
2577
+ if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
2578
+ return "other";
2579
+ }
2537
2580
  static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
2538
2581
  const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
2539
2582
  if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
2540
2583
  return 0;
2541
2584
  }
2542
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
2543
- return Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay);
2585
+ const retryCategory = this.getRetryCategory(classification);
2586
+ if (retryCategory === "rate_limit" || retryCategory === "transport") {
2587
+ return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
2544
2588
  }
2545
- return classification.suggestedDelay || baseDelay;
2589
+ return Math.max(baseDelay, classification.suggestedDelay ?? 0);
2546
2590
  }
2547
2591
  static isCloudQuotaError(error) {
2548
2592
  const msg = (error.message || "").toLowerCase();
@@ -6456,6 +6500,8 @@ function getRuntimeEventUiProjectionKind(event) {
6456
6500
  return "audit_envelope";
6457
6501
  case "subrun_trace":
6458
6502
  return "subrun_trace";
6503
+ case "llm_retry":
6504
+ return "llm_retry";
6459
6505
  case "error":
6460
6506
  return "error";
6461
6507
  case "context_usage_snapshot":
@@ -6485,7 +6531,7 @@ function describeRuntimeEventLifecycle(event) {
6485
6531
  if (isContextUsageSnapshotRuntimeEvent(event)) {
6486
6532
  return false;
6487
6533
  }
6488
- if (event.type === "error") {
6534
+ if (event.type === "error" || event.type === "llm_retry") {
6489
6535
  return false;
6490
6536
  }
6491
6537
  if (isRequiresUserInteractionRuntimeEvent(event)) {
@@ -6528,6 +6574,7 @@ function describeRuntimeEventLifecycle(event) {
6528
6574
  case "tool_output":
6529
6575
  case "requires_user_interaction":
6530
6576
  case "subrun_trace":
6577
+ case "llm_retry":
6531
6578
  case "error":
6532
6579
  case "context_usage_snapshot":
6533
6580
  case "run_execution_metrics":
@@ -6744,8 +6791,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
6744
6791
  assistant_replay_parts: AssistantReplayParts.optional(),
6745
6792
  meta: UnknownRecord.optional()
6746
6793
  }).strict();
6794
+ var LlmRetryEventSchema = BaseAgentEvent.extend({
6795
+ type: z.literal("llm_retry"),
6796
+ ...LlmRetryState.shape
6797
+ }).strict();
6747
6798
  var ErrorEventSchema = BaseAgentEvent.extend({
6748
6799
  type: z.literal("error"),
6800
+ retry_id: LlmRetryState.shape.retry_id.optional(),
6749
6801
  error: z.string(),
6750
6802
  error_code: z.string().optional(),
6751
6803
  retryable: z.boolean().optional(),
@@ -6775,6 +6827,7 @@ var AgentEventSchema = z.discriminatedUnion("type", [
6775
6827
  ToolProcessEventSchema,
6776
6828
  ObservationEventSchema,
6777
6829
  FinalAnswerEventSchema,
6830
+ LlmRetryEventSchema,
6778
6831
  ErrorEventSchema,
6779
6832
  StreamChunkEventSchema,
6780
6833
  StreamResetEventSchema,
@@ -6875,13 +6928,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
6875
6928
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
6876
6929
  return event;
6877
6930
  }
6931
+ case "llm_retry":
6932
+ return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
6878
6933
  case "error": {
6879
6934
  const errorEvent = typed;
6880
6935
  const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
6881
6936
  timestamp,
6882
6937
  details: toSerializableJsonValue(errorEvent.details),
6883
6938
  error_code: errorEvent.error_code,
6884
- retryable: errorEvent.retryable
6939
+ retryable: errorEvent.retryable,
6940
+ retry_id: errorEvent.retry_id
6885
6941
  });
6886
6942
  if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
6887
6943
  return event;
@@ -10080,7 +10136,7 @@ var EventBusEventPersistence = class {
10080
10136
  if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
10081
10137
  return;
10082
10138
  }
10083
- if (this.checkpointWritesActive) {
10139
+ if (this.checkpointWritesActive && event.type !== "llm_retry") {
10084
10140
  this.scheduledEventIds.add(event.id);
10085
10141
  this.checkpointEvents.push(event);
10086
10142
  return;
@@ -10217,21 +10273,37 @@ function resolveLlmMaxTotalAttempts(config) {
10217
10273
  function hasLlmAttemptBudgetRemaining(params) {
10218
10274
  return params.actualAttempts < params.maxTotalAttempts;
10219
10275
  }
10276
+ function validateLlmRetryConfig(config) {
10277
+ if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
10278
+ throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
10279
+ }
10280
+ if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
10281
+ throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
10282
+ }
10283
+ for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
10284
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
10285
+ throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
10286
+ }
10287
+ }
10288
+ }
10220
10289
 
10221
10290
  // src/runtime-kernel/llm/request-builder.ts
10222
10291
  function buildLlmCallerDeps(options) {
10223
10292
  const modelCatalog = options.modelCatalog;
10224
10293
  const maxRetries = options.maxRetries ?? 3;
10225
- return {
10226
- retryConfig: {
10294
+ const retryConfig = {
10295
+ maxRetries,
10296
+ maxRetriesByCategory: options.maxRetriesByCategory,
10297
+ maxTotalAttempts: resolveLlmMaxTotalAttempts({
10227
10298
  maxRetries,
10228
- maxTotalAttempts: resolveLlmMaxTotalAttempts({
10229
- maxRetries,
10230
- maxTotalAttempts: options.maxTotalAttempts
10231
- }),
10232
- enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10233
- retryDelayMs: options.retryDelayMs ?? 1e3
10234
- },
10299
+ maxTotalAttempts: options.maxTotalAttempts
10300
+ }),
10301
+ enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
10302
+ retryDelayMs: options.retryDelayMs ?? 1e3
10303
+ };
10304
+ validateLlmRetryConfig(retryConfig);
10305
+ return {
10306
+ retryConfig,
10235
10307
  modelResolver: options.modelResolver ?? new ModelResolver({
10236
10308
  fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
10237
10309
  modelCatalog
@@ -10698,6 +10770,7 @@ var logger14 = new Logger("LlmCaller");
10698
10770
  var CanonicalInferenceFailureError = class extends Error {
10699
10771
  errorCode;
10700
10772
  recoverable;
10773
+ retryCategory;
10701
10774
  metadata;
10702
10775
  constructor(failure, abortReason) {
10703
10776
  const message = failure.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure.code}`;
@@ -10705,6 +10778,7 @@ var CanonicalInferenceFailureError = class extends Error {
10705
10778
  this.name = failure.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
10706
10779
  this.errorCode = `llm.${failure.code}`;
10707
10780
  this.recoverable = failure.retryable;
10781
+ this.retryCategory = failure.retry_category;
10708
10782
  this.metadata = { failure_kind: failure.kind, provider_code: failure.code };
10709
10783
  }
10710
10784
  };
@@ -10940,6 +11014,57 @@ async function callLlmStream(params) {
10940
11014
  };
10941
11015
  }
10942
11016
 
11017
+ // src/runtime-kernel/llm/functions/llmRetryEpisode.ts
11018
+ var SAFE_RETRY_MESSAGES = {
11019
+ transport: "Network connection interrupted",
11020
+ output: "Model output could not be accepted",
11021
+ rate_limit: "Model request rate limit reached",
11022
+ other: "Model request temporarily failed"
11023
+ };
11024
+ var LlmRetryEpisode = class {
11025
+ constructor(id, emit) {
11026
+ this.id = id;
11027
+ this.emit = emit;
11028
+ }
11029
+ id;
11030
+ emit;
11031
+ state;
11032
+ ended = false;
11033
+ get activeId() {
11034
+ return this.state ? this.id : void 0;
11035
+ }
11036
+ waiting(params, delay) {
11037
+ const now = Date.now();
11038
+ this.state = {
11039
+ ...params,
11040
+ retry_id: this.id,
11041
+ status: "waiting",
11042
+ started_at: this.state?.started_at ?? now,
11043
+ delay_ms: delay,
11044
+ next_retry_at: now + delay,
11045
+ error: SAFE_RETRY_MESSAGES[params.category]
11046
+ };
11047
+ this.publish();
11048
+ }
11049
+ retrying(totalAttempts) {
11050
+ if (!this.state || this.ended) return;
11051
+ const { next_retry_at: ignored, ...state } = this.state;
11052
+ this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
11053
+ this.publish();
11054
+ }
11055
+ finish(status, failure) {
11056
+ if (!this.state || this.ended) return;
11057
+ this.ended = true;
11058
+ const { next_retry_at: ignored, ...state } = this.state;
11059
+ this.state = { ...state, ...failure, status, delay_ms: 0, ...failure ? { error: SAFE_RETRY_MESSAGES[failure.category] } : {} };
11060
+ this.publish();
11061
+ }
11062
+ publish() {
11063
+ if (!this.state) return;
11064
+ this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
11065
+ }
11066
+ };
11067
+
10943
11068
  // src/runtime-kernel/llm/retry-fallback-routing.ts
10944
11069
  var logger15 = new Logger("LlmCaller");
10945
11070
  function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
@@ -11172,6 +11297,8 @@ async function callWithRetryFallback(params) {
11172
11297
  maxTotalAttempts: deps.retryConfig.maxTotalAttempts
11173
11298
  });
11174
11299
  const traceId = generateTraceId();
11300
+ const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
11301
+ const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
11175
11302
  let previousAttemptTracker;
11176
11303
  if (!clientRetryEnabled) {
11177
11304
  const activeCfg = deps.modelCatalog.getModelById(modelId);
@@ -11181,167 +11308,207 @@ async function callWithRetryFallback(params) {
11181
11308
  reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
11182
11309
  });
11183
11310
  }
11184
- for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11185
- throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11186
- if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11187
- eventHandler(previousAttemptTracker.buildResetEvent());
11188
- }
11189
- previousAttemptTracker = void 0;
11190
- const resolvedMessages = await runLlmInputPreflight({
11191
- activeModelId,
11192
- messages,
11193
- modelCatalog: deps.modelCatalog,
11194
- materializer: deps.llmInputMaterializer,
11195
- invocationContext,
11196
- eventHandler,
11197
- requirement
11198
- });
11199
- const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11200
- const isRetry = attempt > 0;
11201
- let pendingErrorEvent = null;
11202
- let streamedErrorClassification;
11203
- const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11204
- pendingErrorEvent = evt;
11205
- }) : void 0;
11206
- try {
11207
- if (isRetry) {
11208
- logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11209
- }
11210
- actualAttempts++;
11211
- const llmResponse = attemptTracker ? await callLlmStream({
11212
- inferencePort: deps.inferencePort,
11213
- modelId: activeModelId,
11214
- messages: resolvedMessages,
11215
- options,
11216
- eventHandler: attemptTracker.handle,
11217
- onErrorClassification(classification) {
11218
- streamedErrorClassification = classification;
11219
- },
11220
- signal,
11221
- toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11222
- traceId
11223
- }) : await callPlainCompletion(
11224
- deps.inferencePort,
11225
- activeModelId,
11226
- resolvedMessages,
11227
- options,
11228
- signal,
11229
- traceId
11230
- );
11231
- const responseContent = getLlmResultContent(llmResponse);
11232
- const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11233
- if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11234
- throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11235
- }
11236
- logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11237
- if (attemptContextUsage) {
11238
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11239
- } else {
11240
- fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11311
+ try {
11312
+ for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
11313
+ throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
11314
+ if (previousAttemptTracker?.hasEmitted() && eventHandler) {
11315
+ eventHandler(previousAttemptTracker.buildResetEvent());
11241
11316
  }
11242
- return llmResponse;
11243
- } catch (error) {
11244
- lastError = error instanceof Error ? error : new Error(String(error));
11245
- if (lastError.name === "AbortError") {
11246
- logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11247
- attempt: attempt + 1,
11248
- actualAttempts,
11249
- maxTotalAttempts,
11250
- reason: lastError.message
11251
- });
11252
- throw lastError;
11253
- }
11254
- const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11255
- const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
11256
- logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11257
- attempt: attempt + 1,
11258
- maxAttempts: currentMaxRetries + 1,
11259
- actualAttempts,
11260
- maxTotalAttempts,
11261
- error: lastError.message
11317
+ previousAttemptTracker = void 0;
11318
+ const resolvedMessages = await runLlmInputPreflight({
11319
+ activeModelId,
11320
+ messages,
11321
+ modelCatalog: deps.modelCatalog,
11322
+ materializer: deps.llmInputMaterializer,
11323
+ invocationContext,
11324
+ eventHandler,
11325
+ requirement
11262
11326
  });
11263
- previousAttemptTracker = attemptTracker;
11264
- if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11265
- logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11266
- actualAttempts,
11267
- maxTotalAttempts
11268
- });
11269
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11270
- throw lastError;
11271
- }
11272
- if (options.allow_model_fallback !== false) {
11273
- const policySwitchModelId = tryPolicyModelSwitch(
11274
- deps,
11327
+ const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11328
+ const isRetry = attempt > 0;
11329
+ let pendingErrorEvent = null;
11330
+ let streamedErrorClassification;
11331
+ const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
11332
+ pendingErrorEvent = evt;
11333
+ }) : void 0;
11334
+ try {
11335
+ if (isRetry) {
11336
+ logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
11337
+ }
11338
+ actualAttempts++;
11339
+ retryEpisode.retrying(actualAttempts);
11340
+ const llmResponse = attemptTracker ? await callLlmStream({
11341
+ inferencePort: deps.inferencePort,
11342
+ modelId: activeModelId,
11343
+ messages: resolvedMessages,
11344
+ options,
11345
+ eventHandler: attemptTracker.handle,
11346
+ onErrorClassification(classification) {
11347
+ streamedErrorClassification = classification;
11348
+ },
11349
+ signal,
11350
+ toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
11351
+ traceId
11352
+ }) : await callPlainCompletion(
11353
+ deps.inferencePort,
11275
11354
  activeModelId,
11276
- excludedModelIds,
11277
- requirement,
11278
- fallbackObserver,
11279
- lastError,
11280
- invocationContext?.evaluateFallbackPromptCapacity
11355
+ resolvedMessages,
11356
+ options,
11357
+ signal,
11358
+ traceId
11281
11359
  );
11282
- if (policySwitchModelId) {
11283
- fallbackObserver?.onModelFallbackApplied?.({
11284
- fromModelId: activeModelId,
11285
- toModelId: policySwitchModelId,
11286
- reason: lastError.message,
11287
- policy: "policy-switch"
11360
+ const responseContent = getLlmResultContent(llmResponse);
11361
+ const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
11362
+ if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
11363
+ throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
11364
+ }
11365
+ logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
11366
+ if (attemptContextUsage) {
11367
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
11368
+ } else {
11369
+ fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
11370
+ }
11371
+ retryEpisode.finish("succeeded");
11372
+ return llmResponse;
11373
+ } catch (error) {
11374
+ lastError = error instanceof Error ? error : new Error(String(error));
11375
+ if (lastError.name === "AbortError") {
11376
+ logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
11377
+ attempt: attempt + 1,
11378
+ actualAttempts,
11379
+ maxTotalAttempts,
11380
+ reason: lastError.message
11288
11381
  });
11289
- activeModelId = policySwitchModelId;
11290
- excludedModelIds.add(policySwitchModelId);
11291
- attempt -= 1;
11292
- continue;
11382
+ throw lastError;
11293
11383
  }
11294
- const quotaFallbackModelId = tryCloudQuotaFallback({
11295
- deps,
11296
- activeModelId,
11297
- options,
11298
- excludedModelIds,
11299
- requirement,
11300
- error: lastError,
11301
- fallbackObserver,
11302
- evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11384
+ const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
11385
+ const category = ErrorClassifier.getRetryCategory(classification);
11386
+ const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
11387
+ const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
11388
+ const failedRetryState = {
11389
+ category,
11390
+ attempt: categoryRetries[category],
11391
+ max_retries: currentMaxRetries,
11392
+ total_attempts: actualAttempts,
11393
+ error_code: classification.errorCode
11394
+ };
11395
+ logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
11396
+ attempt: attempt + 1,
11397
+ maxAttempts: currentMaxRetries + 1,
11398
+ actualAttempts,
11399
+ maxTotalAttempts,
11400
+ error: lastError.message
11303
11401
  });
11304
- if (quotaFallbackModelId) {
11305
- fallbackObserver?.onModelFallbackApplied?.({
11306
- fromModelId: activeModelId,
11307
- toModelId: quotaFallbackModelId,
11308
- reason: lastError.message,
11309
- policy: "cloud-quota"
11402
+ previousAttemptTracker = attemptTracker;
11403
+ if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
11404
+ logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
11405
+ actualAttempts,
11406
+ maxTotalAttempts
11310
11407
  });
11311
- activeModelId = quotaFallbackModelId;
11312
- excludedModelIds.add(quotaFallbackModelId);
11313
- attempt -= 1;
11314
- continue;
11408
+ retryEpisode.finish("exhausted", failedRetryState);
11409
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11410
+ throw lastError;
11315
11411
  }
11316
- }
11317
- if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11318
- logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11319
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11320
- throw lastError;
11321
- }
11322
- if (attempt >= currentMaxRetries) {
11323
- logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11324
- emitFinalError(eventHandler, pendingErrorEvent, lastError, classification);
11325
- throw lastError;
11326
- }
11327
- const retryDelay = ErrorClassifier.calculateRetryDelay(
11328
- classification,
11329
- attempt,
11330
- deps.retryConfig.retryDelayMs,
11331
- 6e4
11332
- );
11333
- if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11334
- logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11335
- } else if (classification.category === "retryable" /* RETRYABLE */) {
11336
- logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11337
- }
11338
- throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11339
- if (retryDelay > 0) {
11340
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
11341
- }
11342
- }
11412
+ if (options.allow_model_fallback !== false) {
11413
+ const policySwitchModelId = tryPolicyModelSwitch(
11414
+ deps,
11415
+ activeModelId,
11416
+ excludedModelIds,
11417
+ requirement,
11418
+ fallbackObserver,
11419
+ lastError,
11420
+ invocationContext?.evaluateFallbackPromptCapacity
11421
+ );
11422
+ if (policySwitchModelId) {
11423
+ fallbackObserver?.onModelFallbackApplied?.({
11424
+ fromModelId: activeModelId,
11425
+ toModelId: policySwitchModelId,
11426
+ reason: lastError.message,
11427
+ policy: "policy-switch"
11428
+ });
11429
+ activeModelId = policySwitchModelId;
11430
+ excludedModelIds.add(policySwitchModelId);
11431
+ attempt -= 1;
11432
+ continue;
11433
+ }
11434
+ const quotaFallbackModelId = tryCloudQuotaFallback({
11435
+ deps,
11436
+ activeModelId,
11437
+ options,
11438
+ excludedModelIds,
11439
+ requirement,
11440
+ error: lastError,
11441
+ fallbackObserver,
11442
+ evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
11443
+ });
11444
+ if (quotaFallbackModelId) {
11445
+ fallbackObserver?.onModelFallbackApplied?.({
11446
+ fromModelId: activeModelId,
11447
+ toModelId: quotaFallbackModelId,
11448
+ reason: lastError.message,
11449
+ policy: "cloud-quota"
11450
+ });
11451
+ activeModelId = quotaFallbackModelId;
11452
+ excludedModelIds.add(quotaFallbackModelId);
11453
+ attempt -= 1;
11454
+ continue;
11455
+ }
11456
+ }
11457
+ if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
11458
+ logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
11459
+ retryEpisode.finish("failed", failedRetryState);
11460
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11461
+ throw lastError;
11462
+ }
11463
+ if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
11464
+ logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
11465
+ retryEpisode.finish("exhausted", failedRetryState);
11466
+ emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
11467
+ throw lastError;
11468
+ }
11469
+ const retryDelay = ErrorClassifier.calculateRetryDelay(
11470
+ classification,
11471
+ categoryRetries[category],
11472
+ deps.retryConfig.retryDelayMs,
11473
+ 6e4
11474
+ );
11475
+ if (classification.category === "rate_limit" /* RATE_LIMIT */) {
11476
+ logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11477
+ } else if (classification.category === "retryable" /* RETRYABLE */) {
11478
+ logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
11479
+ }
11480
+ throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
11481
+ categoryRetries[category] += 1;
11482
+ retryEpisode.waiting({
11483
+ category,
11484
+ attempt: categoryRetries[category],
11485
+ max_retries: currentMaxRetries,
11486
+ total_attempts: actualAttempts,
11487
+ error_code: classification.errorCode
11488
+ }, retryDelay);
11489
+ if (retryDelay > 0) await waitForRetry(retryDelay, signal);
11490
+ }
11491
+ }
11492
+ throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
11493
+ } catch (error) {
11494
+ retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
11495
+ throw error;
11343
11496
  }
11344
- throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
11497
+ }
11498
+ function waitForRetry(delayMs, signal) {
11499
+ throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
11500
+ return new Promise((resolve, reject) => {
11501
+ const onAbort = () => {
11502
+ clearTimeout(timer);
11503
+ signal?.removeEventListener("abort", onAbort);
11504
+ reject(new DOMException("Request interrupted during retry delay", "AbortError"));
11505
+ };
11506
+ const timer = setTimeout(() => {
11507
+ signal?.removeEventListener("abort", onAbort);
11508
+ resolve();
11509
+ }, delayMs);
11510
+ signal?.addEventListener("abort", onAbort, { once: true });
11511
+ });
11345
11512
  }
11346
11513
  function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
11347
11514
  if (options.retry_policy === "none") return false;
@@ -11400,9 +11567,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
11400
11567
  }
11401
11568
  };
11402
11569
  }
11403
- function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
11570
+ function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
11404
11571
  if (!eventHandler) return;
11405
- eventHandler(pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification));
11572
+ const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
11573
+ eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
11406
11574
  }
11407
11575
 
11408
11576
  // src/runtime-kernel/llm/caller.ts