@linnlabs/linnkit 0.37.5 → 0.38.1

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