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