@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.
- package/CHANGELOG.md +38 -0
- package/dist/cli.cjs +347 -179
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +347 -179
- package/dist/cli.js.map +1 -1
- package/dist/context-manager.cjs +55 -11
- package/dist/context-manager.cjs.map +1 -1
- package/dist/context-manager.js +55 -11
- package/dist/context-manager.js.map +1 -1
- package/dist/contracts/audit.d.cts +6 -6
- package/dist/contracts/audit.d.ts +6 -6
- package/dist/contracts/events.d.cts +532 -50
- package/dist/contracts/events.d.ts +532 -50
- package/dist/contracts/llm-retry.d.cts +47 -0
- package/dist/contracts/llm-retry.d.ts +47 -0
- package/dist/contracts/messages.d.cts +2 -2
- package/dist/contracts/messages.d.ts +2 -2
- package/dist/contracts/runtime-error.d.cts +26 -0
- package/dist/contracts/runtime-error.d.ts +26 -0
- package/dist/contracts/sse.d.cts +571 -55
- package/dist/contracts/sse.d.ts +571 -55
- package/dist/contracts/sub-run-trace-payload.d.cts +102 -6
- package/dist/contracts/sub-run-trace-payload.d.ts +102 -6
- package/dist/contracts/token-accounting.d.cts +18 -18
- package/dist/contracts/token-accounting.d.ts +18 -18
- package/dist/contracts.cjs +65 -10
- package/dist/contracts.cjs.map +1 -1
- package/dist/contracts.d.cts +4 -2
- package/dist/contracts.d.ts +4 -2
- package/dist/contracts.js +62 -11
- package/dist/contracts.js.map +1 -1
- package/dist/index.cjs +506 -286
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +506 -286
- package/dist/index.js.map +1 -1
- package/dist/ports/canonical-inference.d.cts +3 -0
- package/dist/ports/canonical-inference.d.ts +3 -0
- package/dist/ports/llm-call.d.cts +4 -0
- package/dist/ports/llm-call.d.ts +4 -0
- package/dist/quickstart.cjs +347 -179
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.js +347 -179
- package/dist/quickstart.js.map +1 -1
- package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.cts +8 -0
- package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.ts +8 -0
- package/dist/runtime-kernel/events/agentEvents.d.cts +85 -4
- package/dist/runtime-kernel/events/agentEvents.d.ts +85 -4
- package/dist/runtime-kernel/events/eventGovernance.d.cts +1 -1
- package/dist/runtime-kernel/events/eventGovernance.d.ts +1 -1
- package/dist/runtime-kernel/events.cjs +55 -11
- package/dist/runtime-kernel/events.cjs.map +1 -1
- package/dist/runtime-kernel/events.js +55 -11
- package/dist/runtime-kernel/events.js.map +1 -1
- package/dist/runtime-kernel/llm/request-builder.d.cts +2 -0
- package/dist/runtime-kernel/llm/request-builder.d.ts +2 -0
- package/dist/runtime-kernel.cjs +468 -271
- package/dist/runtime-kernel.cjs.map +1 -1
- package/dist/runtime-kernel.js +468 -271
- package/dist/runtime-kernel.js.map +1 -1
- package/dist/shared/errorClassifier.d.cts +5 -0
- package/dist/shared/errorClassifier.d.ts +5 -0
- package/dist/testkit.cjs +466 -269
- package/dist/testkit.cjs.map +1 -1
- package/dist/testkit.js +466 -269
- package/dist/testkit.js.map +1 -1
- package/docs/integration/llm-provider.md +24 -0
- package/docs/integration/realtime.md +29 -0
- package/package.json +2 -2
package/dist/runtime-kernel.cjs
CHANGED
|
@@ -130,11 +130,121 @@ var Logger = class {
|
|
|
130
130
|
}
|
|
131
131
|
}
|
|
132
132
|
};
|
|
133
|
+
var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
|
|
134
|
+
(value) => value === value.trim(),
|
|
135
|
+
"identity must not contain leading or trailing whitespace"
|
|
136
|
+
);
|
|
137
|
+
var RuntimeEventIdSchema = NonEmptyIdentitySchema;
|
|
138
|
+
var AiMessageIdSchema = NonEmptyIdentitySchema;
|
|
139
|
+
var ConversationIdSchema = NonEmptyIdentitySchema;
|
|
140
|
+
var TurnIdSchema = NonEmptyIdentitySchema;
|
|
141
|
+
var RunIdSchema = NonEmptyIdentitySchema.brand();
|
|
142
|
+
var ExecutionIdSchema = NonEmptyIdentitySchema;
|
|
143
|
+
var TraceIdSchema = NonEmptyIdentitySchema;
|
|
144
|
+
var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
|
|
145
|
+
var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
|
|
146
|
+
var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
|
|
147
|
+
var InteractionIdSchema = NonEmptyIdentitySchema;
|
|
148
|
+
var SubrunIdSchema = NonEmptyIdentitySchema;
|
|
149
|
+
var ResumeTokenSchema = NonEmptyIdentitySchema;
|
|
150
|
+
var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
|
|
151
|
+
var SourceEventIdSchema = RuntimeEventIdSchema;
|
|
152
|
+
var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
|
|
153
|
+
var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
|
|
154
|
+
|
|
155
|
+
// src/contracts/identity/generators.ts
|
|
156
|
+
function randomIdentity(prefix) {
|
|
157
|
+
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
158
|
+
throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
|
|
159
|
+
}
|
|
160
|
+
return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
161
|
+
}
|
|
162
|
+
function generateRuntimeEventId() {
|
|
163
|
+
return randomIdentity("evt");
|
|
164
|
+
}
|
|
165
|
+
function generateAnswerSegmentId() {
|
|
166
|
+
return randomIdentity("answer");
|
|
167
|
+
}
|
|
168
|
+
function generateTurnId() {
|
|
169
|
+
return randomIdentity("turn");
|
|
170
|
+
}
|
|
171
|
+
function generateRunId() {
|
|
172
|
+
return RunIdSchema.parse(randomIdentity("run"));
|
|
173
|
+
}
|
|
174
|
+
function generateExecutionId() {
|
|
175
|
+
return randomIdentity("exec");
|
|
176
|
+
}
|
|
177
|
+
function generateTraceId() {
|
|
178
|
+
return randomIdentity("trace");
|
|
179
|
+
}
|
|
180
|
+
function generateInferenceAttemptId() {
|
|
181
|
+
return randomIdentity("inference-attempt");
|
|
182
|
+
}
|
|
183
|
+
function generateThoughtMessageId() {
|
|
184
|
+
return randomIdentity("thought");
|
|
185
|
+
}
|
|
186
|
+
function generateToolCallId() {
|
|
187
|
+
return ToolCallIdSchema.parse(randomIdentity("call"));
|
|
188
|
+
}
|
|
189
|
+
function generateInteractionId() {
|
|
190
|
+
return randomIdentity("interaction");
|
|
191
|
+
}
|
|
192
|
+
function generateResumeToken() {
|
|
193
|
+
return randomIdentity("resume");
|
|
194
|
+
}
|
|
195
|
+
function generateRunResumeClaimId() {
|
|
196
|
+
return randomIdentity("resume-claim");
|
|
197
|
+
}
|
|
198
|
+
function generateAuditEnvelopeId() {
|
|
199
|
+
return randomIdentity("audit");
|
|
200
|
+
}
|
|
201
|
+
function generateContextLedgerEntryId() {
|
|
202
|
+
return randomIdentity("context-ledger");
|
|
203
|
+
}
|
|
204
|
+
function runIdFromTurnId(turnId) {
|
|
205
|
+
return RunIdSchema.parse(turnId);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// src/contracts/identity/invariants.ts
|
|
209
|
+
function assertCanonicalFinalAnswerIdentity(input) {
|
|
210
|
+
const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
|
|
211
|
+
if (input.id !== answerId) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
`final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
return answerId;
|
|
217
|
+
}
|
|
218
|
+
function assertDistinctAnswerChunkIdentity(input) {
|
|
219
|
+
if (input.id === input.answer_id) {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// src/contracts/llm-retry.ts
|
|
227
|
+
var LlmRetryCategory = zod.z.enum(["transport", "output", "rate_limit", "other"]);
|
|
228
|
+
var LlmRetryState = zod.z.object({
|
|
229
|
+
retry_id: TraceIdSchema,
|
|
230
|
+
status: zod.z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
|
|
231
|
+
category: LlmRetryCategory,
|
|
232
|
+
attempt: zod.z.number().int().nonnegative(),
|
|
233
|
+
max_retries: zod.z.number().int().nonnegative(),
|
|
234
|
+
total_attempts: zod.z.number().int().positive(),
|
|
235
|
+
started_at: zod.z.number().finite(),
|
|
236
|
+
delay_ms: zod.z.number().finite().nonnegative(),
|
|
237
|
+
next_retry_at: zod.z.number().finite().optional(),
|
|
238
|
+
/** 安全分类说明;不得放入供应商响应正文。 */
|
|
239
|
+
error: zod.z.string(),
|
|
240
|
+
error_code: zod.z.string().min(1)
|
|
241
|
+
}).strict();
|
|
133
242
|
|
|
134
243
|
// src/shared/errorClassifier.ts
|
|
135
244
|
var ENGINE_ERROR_CODES = {
|
|
136
245
|
LLM_RATE_LIMIT: "llm.rate_limit",
|
|
137
246
|
LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
|
|
247
|
+
LLM_EMPTY_RESPONSE: "llm.empty_response",
|
|
138
248
|
LLM_PROVIDER_DOWN: "llm.provider_down",
|
|
139
249
|
LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
|
|
140
250
|
LLM_AUTH_FAILED: "llm.auth_failed",
|
|
@@ -245,6 +355,8 @@ function readStructuredClassification(error) {
|
|
|
245
355
|
if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
|
|
246
356
|
if (typeof recoverable !== "boolean") return void 0;
|
|
247
357
|
const errorCode = rawErrorCode.trim();
|
|
358
|
+
const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
|
|
359
|
+
const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
|
|
248
360
|
const retryAfterMsValue = error["retryAfterMs"];
|
|
249
361
|
const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
|
|
250
362
|
const hintValue = error["hint"];
|
|
@@ -252,12 +364,13 @@ function readStructuredClassification(error) {
|
|
|
252
364
|
const metadataValue = error["metadata"];
|
|
253
365
|
const metadata = isRecord(metadataValue) ? metadataValue : void 0;
|
|
254
366
|
return createClassification(
|
|
255
|
-
recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
|
|
367
|
+
recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
|
|
256
368
|
`\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
|
|
257
369
|
recoverable ? retryAfterMs ?? 1e3 : null,
|
|
258
370
|
{
|
|
259
371
|
errorCode,
|
|
260
372
|
recoverable,
|
|
373
|
+
...retryCategory === void 0 ? {} : { retryCategory },
|
|
261
374
|
...retryAfterMs === void 0 ? {} : { retryAfterMs },
|
|
262
375
|
...hint === void 0 ? {} : { hint },
|
|
263
376
|
...metadata === void 0 ? {} : { metadata }
|
|
@@ -532,7 +645,7 @@ var ErrorClassifier = class {
|
|
|
532
645
|
if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
|
|
533
646
|
logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
|
|
534
647
|
return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
|
|
535
|
-
errorCode: ENGINE_ERROR_CODES.
|
|
648
|
+
errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
|
|
536
649
|
recoverable: true,
|
|
537
650
|
retryAfterMs: 1e3,
|
|
538
651
|
hint: "retry_with_backoff",
|
|
@@ -557,15 +670,23 @@ var ErrorClassifier = class {
|
|
|
557
670
|
const category = this.categorize(error);
|
|
558
671
|
return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
|
|
559
672
|
}
|
|
673
|
+
static getRetryCategory(classification) {
|
|
674
|
+
if (classification.retryCategory !== void 0) return classification.retryCategory;
|
|
675
|
+
if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
|
|
676
|
+
if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
|
|
677
|
+
if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
|
|
678
|
+
return "other";
|
|
679
|
+
}
|
|
560
680
|
static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
|
|
561
681
|
const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
|
|
562
682
|
if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
|
|
563
683
|
return 0;
|
|
564
684
|
}
|
|
565
|
-
|
|
566
|
-
|
|
685
|
+
const retryCategory = this.getRetryCategory(classification);
|
|
686
|
+
if (retryCategory === "rate_limit" || retryCategory === "transport") {
|
|
687
|
+
return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
|
|
567
688
|
}
|
|
568
|
-
return classification.suggestedDelay
|
|
689
|
+
return Math.max(baseDelay, classification.suggestedDelay ?? 0);
|
|
569
690
|
}
|
|
570
691
|
static isCloudQuotaError(error) {
|
|
571
692
|
const msg = (error.message || "").toLowerCase();
|
|
@@ -604,98 +725,6 @@ var RuntimeResourceRef = zod.z.object({
|
|
|
604
725
|
label: LabelSchema.optional()
|
|
605
726
|
}).strict();
|
|
606
727
|
var RuntimeResourceRefs = zod.z.array(RuntimeResourceRef).min(1);
|
|
607
|
-
var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
|
|
608
|
-
(value) => value === value.trim(),
|
|
609
|
-
"identity must not contain leading or trailing whitespace"
|
|
610
|
-
);
|
|
611
|
-
var RuntimeEventIdSchema = NonEmptyIdentitySchema;
|
|
612
|
-
var AiMessageIdSchema = NonEmptyIdentitySchema;
|
|
613
|
-
var ConversationIdSchema = NonEmptyIdentitySchema;
|
|
614
|
-
var TurnIdSchema = NonEmptyIdentitySchema;
|
|
615
|
-
var RunIdSchema = NonEmptyIdentitySchema.brand();
|
|
616
|
-
var ExecutionIdSchema = NonEmptyIdentitySchema;
|
|
617
|
-
var TraceIdSchema = NonEmptyIdentitySchema;
|
|
618
|
-
var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
|
|
619
|
-
var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
|
|
620
|
-
var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
|
|
621
|
-
var InteractionIdSchema = NonEmptyIdentitySchema;
|
|
622
|
-
var SubrunIdSchema = NonEmptyIdentitySchema;
|
|
623
|
-
var ResumeTokenSchema = NonEmptyIdentitySchema;
|
|
624
|
-
var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
|
|
625
|
-
var SourceEventIdSchema = RuntimeEventIdSchema;
|
|
626
|
-
var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
|
|
627
|
-
var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
|
|
628
|
-
|
|
629
|
-
// src/contracts/identity/generators.ts
|
|
630
|
-
function randomIdentity(prefix) {
|
|
631
|
-
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
632
|
-
throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
|
|
633
|
-
}
|
|
634
|
-
return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
635
|
-
}
|
|
636
|
-
function generateRuntimeEventId() {
|
|
637
|
-
return randomIdentity("evt");
|
|
638
|
-
}
|
|
639
|
-
function generateAnswerSegmentId() {
|
|
640
|
-
return randomIdentity("answer");
|
|
641
|
-
}
|
|
642
|
-
function generateTurnId() {
|
|
643
|
-
return randomIdentity("turn");
|
|
644
|
-
}
|
|
645
|
-
function generateRunId() {
|
|
646
|
-
return RunIdSchema.parse(randomIdentity("run"));
|
|
647
|
-
}
|
|
648
|
-
function generateExecutionId() {
|
|
649
|
-
return randomIdentity("exec");
|
|
650
|
-
}
|
|
651
|
-
function generateTraceId() {
|
|
652
|
-
return randomIdentity("trace");
|
|
653
|
-
}
|
|
654
|
-
function generateInferenceAttemptId() {
|
|
655
|
-
return randomIdentity("inference-attempt");
|
|
656
|
-
}
|
|
657
|
-
function generateThoughtMessageId() {
|
|
658
|
-
return randomIdentity("thought");
|
|
659
|
-
}
|
|
660
|
-
function generateToolCallId() {
|
|
661
|
-
return ToolCallIdSchema.parse(randomIdentity("call"));
|
|
662
|
-
}
|
|
663
|
-
function generateInteractionId() {
|
|
664
|
-
return randomIdentity("interaction");
|
|
665
|
-
}
|
|
666
|
-
function generateResumeToken() {
|
|
667
|
-
return randomIdentity("resume");
|
|
668
|
-
}
|
|
669
|
-
function generateRunResumeClaimId() {
|
|
670
|
-
return randomIdentity("resume-claim");
|
|
671
|
-
}
|
|
672
|
-
function generateAuditEnvelopeId() {
|
|
673
|
-
return randomIdentity("audit");
|
|
674
|
-
}
|
|
675
|
-
function generateContextLedgerEntryId() {
|
|
676
|
-
return randomIdentity("context-ledger");
|
|
677
|
-
}
|
|
678
|
-
function runIdFromTurnId(turnId) {
|
|
679
|
-
return RunIdSchema.parse(turnId);
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
// src/contracts/identity/invariants.ts
|
|
683
|
-
function assertCanonicalFinalAnswerIdentity(input) {
|
|
684
|
-
const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
|
|
685
|
-
if (input.id !== answerId) {
|
|
686
|
-
throw new Error(
|
|
687
|
-
`final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
|
|
688
|
-
);
|
|
689
|
-
}
|
|
690
|
-
return answerId;
|
|
691
|
-
}
|
|
692
|
-
function assertDistinctAnswerChunkIdentity(input) {
|
|
693
|
-
if (input.id === input.answer_id) {
|
|
694
|
-
throw new Error(
|
|
695
|
-
`final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
|
|
696
|
-
);
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
728
|
var FinalAnswerCompletionReason = zod.z.enum([
|
|
700
729
|
"terminal",
|
|
701
730
|
"tool_call",
|
|
@@ -1170,6 +1199,13 @@ var AuditEnvelope = zod.z.object({
|
|
|
1170
1199
|
costDelta: AuditCostDelta.optional(),
|
|
1171
1200
|
scope: AuditScope.optional()
|
|
1172
1201
|
});
|
|
1202
|
+
var RuntimeErrorState = zod.z.object({
|
|
1203
|
+
error: zod.z.string(),
|
|
1204
|
+
error_code: zod.z.string().optional(),
|
|
1205
|
+
retryable: zod.z.boolean().optional(),
|
|
1206
|
+
retry_id: TraceIdSchema.optional(),
|
|
1207
|
+
details: SerializableJsonValue.optional()
|
|
1208
|
+
}).strict();
|
|
1173
1209
|
var ToolCallPhase = zod.z.enum(["start", "update", "complete", "error"]);
|
|
1174
1210
|
var Status = zod.z.enum(["loading", "success", "error"]);
|
|
1175
1211
|
var SubRunTraceKind = zod.z.enum([
|
|
@@ -1180,7 +1216,9 @@ var SubRunTraceKind = zod.z.enum([
|
|
|
1180
1216
|
"tool_output",
|
|
1181
1217
|
"final_answer_chunk",
|
|
1182
1218
|
"final_answer",
|
|
1183
|
-
"history_summary"
|
|
1219
|
+
"history_summary",
|
|
1220
|
+
"llm_retry",
|
|
1221
|
+
"error"
|
|
1184
1222
|
]);
|
|
1185
1223
|
var SubRunTraceToolCallDecision = zod.z.object({
|
|
1186
1224
|
tool_call_id: ToolCallIdSchema,
|
|
@@ -1193,6 +1231,8 @@ var SubRunTracePayload = zod.z.object({
|
|
|
1193
1231
|
subrun_parent_id: SubrunIdSchema.optional(),
|
|
1194
1232
|
source_event_id: SourceEventIdSchema,
|
|
1195
1233
|
kind: SubRunTraceKind,
|
|
1234
|
+
retry: LlmRetryState.optional(),
|
|
1235
|
+
failure: RuntimeErrorState.optional(),
|
|
1196
1236
|
delta: zod.z.string().optional(),
|
|
1197
1237
|
content: zod.z.string().optional(),
|
|
1198
1238
|
answer_id: AnswerSegmentIdSchema.optional(),
|
|
@@ -1215,6 +1255,12 @@ var SubRunTracePayload = zod.z.object({
|
|
|
1215
1255
|
meta: SerializableJsonRecord.optional()
|
|
1216
1256
|
});
|
|
1217
1257
|
function validateSubRunTracePayloadSemantics(payload, ctx) {
|
|
1258
|
+
if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
|
|
1259
|
+
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
|
|
1260
|
+
}
|
|
1261
|
+
if (payload.kind === "error" !== (payload.failure !== void 0)) {
|
|
1262
|
+
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
|
|
1263
|
+
}
|
|
1218
1264
|
if (payload.kind === "thought_delta" && payload.delta === void 0) {
|
|
1219
1265
|
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
|
|
1220
1266
|
}
|
|
@@ -1568,12 +1614,10 @@ var RuntimeEventShape = zod.z.discriminatedUnion("type", [
|
|
|
1568
1614
|
compression_ratio: zod.z.number().min(0).max(1).optional(),
|
|
1569
1615
|
included_old_summary: zod.z.boolean().optional()
|
|
1570
1616
|
}),
|
|
1617
|
+
BaseEvent.extend({ type: zod.z.literal("llm_retry"), ...LlmRetryState.shape }),
|
|
1571
1618
|
BaseEvent.extend({
|
|
1572
1619
|
type: zod.z.literal("error"),
|
|
1573
|
-
|
|
1574
|
-
details: SerializableJsonValue.optional(),
|
|
1575
|
-
error_code: zod.z.string().optional(),
|
|
1576
|
-
retryable: zod.z.boolean().optional()
|
|
1620
|
+
...RuntimeErrorState.shape
|
|
1577
1621
|
}),
|
|
1578
1622
|
BaseEvent.extend({
|
|
1579
1623
|
type: zod.z.literal("control"),
|
|
@@ -2008,12 +2052,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
|
|
|
2008
2052
|
resume_token: ResumeTokenSchema,
|
|
2009
2053
|
interaction_status: zod.z.literal("pending")
|
|
2010
2054
|
});
|
|
2055
|
+
var SSELlmRetryEvent = BaseSSEEvent.extend({
|
|
2056
|
+
type: zod.z.literal("llm_retry"),
|
|
2057
|
+
...LlmRetryState.shape
|
|
2058
|
+
});
|
|
2011
2059
|
var SSEErrorEvent = BaseSSEEvent.extend({
|
|
2012
2060
|
type: zod.z.literal("error"),
|
|
2013
|
-
|
|
2014
|
-
details: SerializableJsonValue.optional(),
|
|
2015
|
-
error_code: zod.z.string().optional(),
|
|
2016
|
-
retryable: zod.z.boolean().optional()
|
|
2061
|
+
...RuntimeErrorState.shape
|
|
2017
2062
|
});
|
|
2018
2063
|
var SSETransportErrorEvent = BaseSSEEvent.extend({
|
|
2019
2064
|
type: zod.z.literal("transport_error"),
|
|
@@ -2096,6 +2141,7 @@ zod.z.discriminatedUnion("type", [
|
|
|
2096
2141
|
SSEToolOutputEvent,
|
|
2097
2142
|
SSESubRunTraceEvent,
|
|
2098
2143
|
SSERequiresUserInteractionEvent,
|
|
2144
|
+
SSELlmRetryEvent,
|
|
2099
2145
|
SSEErrorEvent,
|
|
2100
2146
|
SSETransportErrorEvent,
|
|
2101
2147
|
SSEContextUsageSnapshotEvent,
|
|
@@ -6467,6 +6513,8 @@ function getRuntimeEventUiProjectionKind(event) {
|
|
|
6467
6513
|
return "audit_envelope";
|
|
6468
6514
|
case "subrun_trace":
|
|
6469
6515
|
return "subrun_trace";
|
|
6516
|
+
case "llm_retry":
|
|
6517
|
+
return "llm_retry";
|
|
6470
6518
|
case "error":
|
|
6471
6519
|
return "error";
|
|
6472
6520
|
case "context_usage_snapshot":
|
|
@@ -6496,7 +6544,7 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
6496
6544
|
if (isContextUsageSnapshotRuntimeEvent(event)) {
|
|
6497
6545
|
return false;
|
|
6498
6546
|
}
|
|
6499
|
-
if (event.type === "error") {
|
|
6547
|
+
if (event.type === "error" || event.type === "llm_retry") {
|
|
6500
6548
|
return false;
|
|
6501
6549
|
}
|
|
6502
6550
|
if (isRequiresUserInteractionRuntimeEvent(event)) {
|
|
@@ -6539,6 +6587,7 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
6539
6587
|
case "tool_output":
|
|
6540
6588
|
case "requires_user_interaction":
|
|
6541
6589
|
case "subrun_trace":
|
|
6590
|
+
case "llm_retry":
|
|
6542
6591
|
case "error":
|
|
6543
6592
|
case "context_usage_snapshot":
|
|
6544
6593
|
case "run_execution_metrics":
|
|
@@ -6755,8 +6804,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
|
|
|
6755
6804
|
assistant_replay_parts: AssistantReplayParts.optional(),
|
|
6756
6805
|
meta: UnknownRecord.optional()
|
|
6757
6806
|
}).strict();
|
|
6807
|
+
var LlmRetryEventSchema = BaseAgentEvent.extend({
|
|
6808
|
+
type: zod.z.literal("llm_retry"),
|
|
6809
|
+
...LlmRetryState.shape
|
|
6810
|
+
}).strict();
|
|
6758
6811
|
var ErrorEventSchema = BaseAgentEvent.extend({
|
|
6759
6812
|
type: zod.z.literal("error"),
|
|
6813
|
+
retry_id: LlmRetryState.shape.retry_id.optional(),
|
|
6760
6814
|
error: zod.z.string(),
|
|
6761
6815
|
error_code: zod.z.string().optional(),
|
|
6762
6816
|
retryable: zod.z.boolean().optional(),
|
|
@@ -6786,6 +6840,7 @@ var AgentEventSchema = zod.z.discriminatedUnion("type", [
|
|
|
6786
6840
|
ToolProcessEventSchema,
|
|
6787
6841
|
ObservationEventSchema,
|
|
6788
6842
|
FinalAnswerEventSchema,
|
|
6843
|
+
LlmRetryEventSchema,
|
|
6789
6844
|
ErrorEventSchema,
|
|
6790
6845
|
StreamChunkEventSchema,
|
|
6791
6846
|
StreamResetEventSchema,
|
|
@@ -6886,13 +6941,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
|
|
|
6886
6941
|
if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
|
|
6887
6942
|
return event;
|
|
6888
6943
|
}
|
|
6944
|
+
case "llm_retry":
|
|
6945
|
+
return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
|
|
6889
6946
|
case "error": {
|
|
6890
6947
|
const errorEvent = typed;
|
|
6891
6948
|
const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
|
|
6892
6949
|
timestamp,
|
|
6893
6950
|
details: toSerializableJsonValue(errorEvent.details),
|
|
6894
6951
|
error_code: errorEvent.error_code,
|
|
6895
|
-
retryable: errorEvent.retryable
|
|
6952
|
+
retryable: errorEvent.retryable,
|
|
6953
|
+
retry_id: errorEvent.retry_id
|
|
6896
6954
|
});
|
|
6897
6955
|
if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
|
|
6898
6956
|
return event;
|
|
@@ -10363,7 +10421,7 @@ var EventBusEventPersistence = class {
|
|
|
10363
10421
|
if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
|
|
10364
10422
|
return;
|
|
10365
10423
|
}
|
|
10366
|
-
if (this.checkpointWritesActive) {
|
|
10424
|
+
if (this.checkpointWritesActive && event.type !== "llm_retry") {
|
|
10367
10425
|
this.scheduledEventIds.add(event.id);
|
|
10368
10426
|
this.checkpointEvents.push(event);
|
|
10369
10427
|
return;
|
|
@@ -10545,21 +10603,37 @@ function resolveLlmMaxTotalAttempts(config) {
|
|
|
10545
10603
|
function hasLlmAttemptBudgetRemaining(params) {
|
|
10546
10604
|
return params.actualAttempts < params.maxTotalAttempts;
|
|
10547
10605
|
}
|
|
10606
|
+
function validateLlmRetryConfig(config) {
|
|
10607
|
+
if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
|
|
10608
|
+
throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
|
|
10609
|
+
}
|
|
10610
|
+
if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
|
|
10611
|
+
throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
|
|
10612
|
+
}
|
|
10613
|
+
for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
|
|
10614
|
+
if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
|
|
10615
|
+
throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
|
|
10616
|
+
}
|
|
10617
|
+
}
|
|
10618
|
+
}
|
|
10548
10619
|
|
|
10549
10620
|
// src/runtime-kernel/llm/request-builder.ts
|
|
10550
10621
|
function buildLlmCallerDeps(options) {
|
|
10551
10622
|
const modelCatalog = options.modelCatalog;
|
|
10552
10623
|
const maxRetries = options.maxRetries ?? 3;
|
|
10553
|
-
|
|
10554
|
-
|
|
10624
|
+
const retryConfig = {
|
|
10625
|
+
maxRetries,
|
|
10626
|
+
maxRetriesByCategory: options.maxRetriesByCategory,
|
|
10627
|
+
maxTotalAttempts: resolveLlmMaxTotalAttempts({
|
|
10555
10628
|
maxRetries,
|
|
10556
|
-
maxTotalAttempts:
|
|
10557
|
-
|
|
10558
|
-
|
|
10559
|
-
|
|
10560
|
-
|
|
10561
|
-
|
|
10562
|
-
|
|
10629
|
+
maxTotalAttempts: options.maxTotalAttempts
|
|
10630
|
+
}),
|
|
10631
|
+
enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
|
|
10632
|
+
retryDelayMs: options.retryDelayMs ?? 1e3
|
|
10633
|
+
};
|
|
10634
|
+
validateLlmRetryConfig(retryConfig);
|
|
10635
|
+
return {
|
|
10636
|
+
retryConfig,
|
|
10563
10637
|
modelResolver: options.modelResolver ?? new ModelResolver({
|
|
10564
10638
|
fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
|
|
10565
10639
|
modelCatalog
|
|
@@ -11026,6 +11100,7 @@ var logger14 = new Logger("LlmCaller");
|
|
|
11026
11100
|
var CanonicalInferenceFailureError = class extends Error {
|
|
11027
11101
|
errorCode;
|
|
11028
11102
|
recoverable;
|
|
11103
|
+
retryCategory;
|
|
11029
11104
|
metadata;
|
|
11030
11105
|
constructor(failure, abortReason) {
|
|
11031
11106
|
const message = failure.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure.code}`;
|
|
@@ -11033,6 +11108,7 @@ var CanonicalInferenceFailureError = class extends Error {
|
|
|
11033
11108
|
this.name = failure.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
|
|
11034
11109
|
this.errorCode = `llm.${failure.code}`;
|
|
11035
11110
|
this.recoverable = failure.retryable;
|
|
11111
|
+
this.retryCategory = failure.retry_category;
|
|
11036
11112
|
this.metadata = { failure_kind: failure.kind, provider_code: failure.code };
|
|
11037
11113
|
}
|
|
11038
11114
|
};
|
|
@@ -11268,6 +11344,57 @@ async function callLlmStream(params) {
|
|
|
11268
11344
|
};
|
|
11269
11345
|
}
|
|
11270
11346
|
|
|
11347
|
+
// src/runtime-kernel/llm/functions/llmRetryEpisode.ts
|
|
11348
|
+
var SAFE_RETRY_MESSAGES = {
|
|
11349
|
+
transport: "Network connection interrupted",
|
|
11350
|
+
output: "Model output could not be accepted",
|
|
11351
|
+
rate_limit: "Model request rate limit reached",
|
|
11352
|
+
other: "Model request temporarily failed"
|
|
11353
|
+
};
|
|
11354
|
+
var LlmRetryEpisode = class {
|
|
11355
|
+
constructor(id, emit) {
|
|
11356
|
+
this.id = id;
|
|
11357
|
+
this.emit = emit;
|
|
11358
|
+
}
|
|
11359
|
+
id;
|
|
11360
|
+
emit;
|
|
11361
|
+
state;
|
|
11362
|
+
ended = false;
|
|
11363
|
+
get activeId() {
|
|
11364
|
+
return this.state ? this.id : void 0;
|
|
11365
|
+
}
|
|
11366
|
+
waiting(params, delay) {
|
|
11367
|
+
const now = Date.now();
|
|
11368
|
+
this.state = {
|
|
11369
|
+
...params,
|
|
11370
|
+
retry_id: this.id,
|
|
11371
|
+
status: "waiting",
|
|
11372
|
+
started_at: this.state?.started_at ?? now,
|
|
11373
|
+
delay_ms: delay,
|
|
11374
|
+
next_retry_at: now + delay,
|
|
11375
|
+
error: SAFE_RETRY_MESSAGES[params.category]
|
|
11376
|
+
};
|
|
11377
|
+
this.publish();
|
|
11378
|
+
}
|
|
11379
|
+
retrying(totalAttempts) {
|
|
11380
|
+
if (!this.state || this.ended) return;
|
|
11381
|
+
const { next_retry_at: ignored, ...state } = this.state;
|
|
11382
|
+
this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
|
|
11383
|
+
this.publish();
|
|
11384
|
+
}
|
|
11385
|
+
finish(status, failure) {
|
|
11386
|
+
if (!this.state || this.ended) return;
|
|
11387
|
+
this.ended = true;
|
|
11388
|
+
const { next_retry_at: ignored, ...state } = this.state;
|
|
11389
|
+
this.state = { ...state, ...failure, status, delay_ms: 0, ...failure ? { error: SAFE_RETRY_MESSAGES[failure.category] } : {} };
|
|
11390
|
+
this.publish();
|
|
11391
|
+
}
|
|
11392
|
+
publish() {
|
|
11393
|
+
if (!this.state) return;
|
|
11394
|
+
this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
|
|
11395
|
+
}
|
|
11396
|
+
};
|
|
11397
|
+
|
|
11271
11398
|
// src/runtime-kernel/llm/retry-fallback-routing.ts
|
|
11272
11399
|
var logger15 = new Logger("LlmCaller");
|
|
11273
11400
|
function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
|
|
@@ -11520,6 +11647,8 @@ async function callWithRetryFallback(params) {
|
|
|
11520
11647
|
maxTotalAttempts: deps.retryConfig.maxTotalAttempts
|
|
11521
11648
|
});
|
|
11522
11649
|
const traceId = generateTraceId();
|
|
11650
|
+
const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
|
|
11651
|
+
const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
|
|
11523
11652
|
let previousAttemptTracker;
|
|
11524
11653
|
if (!clientRetryEnabled) {
|
|
11525
11654
|
const activeCfg = deps.modelCatalog.getModelById(modelId);
|
|
@@ -11529,167 +11658,207 @@ async function callWithRetryFallback(params) {
|
|
|
11529
11658
|
reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
|
|
11530
11659
|
});
|
|
11531
11660
|
}
|
|
11532
|
-
|
|
11533
|
-
|
|
11534
|
-
|
|
11535
|
-
|
|
11536
|
-
|
|
11537
|
-
previousAttemptTracker = void 0;
|
|
11538
|
-
const resolvedMessages = await runLlmInputPreflight({
|
|
11539
|
-
activeModelId,
|
|
11540
|
-
messages,
|
|
11541
|
-
modelCatalog: deps.modelCatalog,
|
|
11542
|
-
materializer: deps.llmInputMaterializer,
|
|
11543
|
-
invocationContext,
|
|
11544
|
-
eventHandler,
|
|
11545
|
-
requirement
|
|
11546
|
-
});
|
|
11547
|
-
const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
|
|
11548
|
-
const isRetry = attempt > 0;
|
|
11549
|
-
let pendingErrorEvent = null;
|
|
11550
|
-
let streamedErrorClassification;
|
|
11551
|
-
const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
|
|
11552
|
-
pendingErrorEvent = evt;
|
|
11553
|
-
}) : void 0;
|
|
11554
|
-
try {
|
|
11555
|
-
if (isRetry) {
|
|
11556
|
-
logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
|
|
11557
|
-
}
|
|
11558
|
-
actualAttempts++;
|
|
11559
|
-
const llmResponse = attemptTracker ? await callLlmStream({
|
|
11560
|
-
inferencePort: deps.inferencePort,
|
|
11561
|
-
modelId: activeModelId,
|
|
11562
|
-
messages: resolvedMessages,
|
|
11563
|
-
options,
|
|
11564
|
-
eventHandler: attemptTracker.handle,
|
|
11565
|
-
onErrorClassification(classification) {
|
|
11566
|
-
streamedErrorClassification = classification;
|
|
11567
|
-
},
|
|
11568
|
-
signal,
|
|
11569
|
-
toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
|
|
11570
|
-
traceId
|
|
11571
|
-
}) : await callPlainCompletion(
|
|
11572
|
-
deps.inferencePort,
|
|
11573
|
-
activeModelId,
|
|
11574
|
-
resolvedMessages,
|
|
11575
|
-
options,
|
|
11576
|
-
signal,
|
|
11577
|
-
traceId
|
|
11578
|
-
);
|
|
11579
|
-
const responseContent = getLlmResultContent(llmResponse);
|
|
11580
|
-
const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
|
|
11581
|
-
if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
|
|
11582
|
-
throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
11583
|
-
}
|
|
11584
|
-
logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
|
|
11585
|
-
if (attemptContextUsage) {
|
|
11586
|
-
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
|
|
11587
|
-
} else {
|
|
11588
|
-
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
|
|
11661
|
+
try {
|
|
11662
|
+
for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
|
|
11663
|
+
throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
|
|
11664
|
+
if (previousAttemptTracker?.hasEmitted() && eventHandler) {
|
|
11665
|
+
eventHandler(previousAttemptTracker.buildResetEvent());
|
|
11589
11666
|
}
|
|
11590
|
-
|
|
11591
|
-
|
|
11592
|
-
|
|
11593
|
-
|
|
11594
|
-
|
|
11595
|
-
|
|
11596
|
-
|
|
11597
|
-
|
|
11598
|
-
|
|
11599
|
-
});
|
|
11600
|
-
throw lastError;
|
|
11601
|
-
}
|
|
11602
|
-
const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
|
|
11603
|
-
const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
|
|
11604
|
-
logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
|
|
11605
|
-
attempt: attempt + 1,
|
|
11606
|
-
maxAttempts: currentMaxRetries + 1,
|
|
11607
|
-
actualAttempts,
|
|
11608
|
-
maxTotalAttempts,
|
|
11609
|
-
error: lastError.message
|
|
11667
|
+
previousAttemptTracker = void 0;
|
|
11668
|
+
const resolvedMessages = await runLlmInputPreflight({
|
|
11669
|
+
activeModelId,
|
|
11670
|
+
messages,
|
|
11671
|
+
modelCatalog: deps.modelCatalog,
|
|
11672
|
+
materializer: deps.llmInputMaterializer,
|
|
11673
|
+
invocationContext,
|
|
11674
|
+
eventHandler,
|
|
11675
|
+
requirement
|
|
11610
11676
|
});
|
|
11611
|
-
|
|
11612
|
-
|
|
11613
|
-
|
|
11614
|
-
|
|
11615
|
-
|
|
11616
|
-
|
|
11617
|
-
|
|
11618
|
-
|
|
11619
|
-
|
|
11620
|
-
|
|
11621
|
-
|
|
11622
|
-
|
|
11677
|
+
const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
|
|
11678
|
+
const isRetry = attempt > 0;
|
|
11679
|
+
let pendingErrorEvent = null;
|
|
11680
|
+
let streamedErrorClassification;
|
|
11681
|
+
const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
|
|
11682
|
+
pendingErrorEvent = evt;
|
|
11683
|
+
}) : void 0;
|
|
11684
|
+
try {
|
|
11685
|
+
if (isRetry) {
|
|
11686
|
+
logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
|
|
11687
|
+
}
|
|
11688
|
+
actualAttempts++;
|
|
11689
|
+
retryEpisode.retrying(actualAttempts);
|
|
11690
|
+
const llmResponse = attemptTracker ? await callLlmStream({
|
|
11691
|
+
inferencePort: deps.inferencePort,
|
|
11692
|
+
modelId: activeModelId,
|
|
11693
|
+
messages: resolvedMessages,
|
|
11694
|
+
options,
|
|
11695
|
+
eventHandler: attemptTracker.handle,
|
|
11696
|
+
onErrorClassification(classification) {
|
|
11697
|
+
streamedErrorClassification = classification;
|
|
11698
|
+
},
|
|
11699
|
+
signal,
|
|
11700
|
+
toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
|
|
11701
|
+
traceId
|
|
11702
|
+
}) : await callPlainCompletion(
|
|
11703
|
+
deps.inferencePort,
|
|
11623
11704
|
activeModelId,
|
|
11624
|
-
|
|
11625
|
-
|
|
11626
|
-
|
|
11627
|
-
|
|
11628
|
-
invocationContext?.evaluateFallbackPromptCapacity
|
|
11705
|
+
resolvedMessages,
|
|
11706
|
+
options,
|
|
11707
|
+
signal,
|
|
11708
|
+
traceId
|
|
11629
11709
|
);
|
|
11630
|
-
|
|
11631
|
-
|
|
11632
|
-
|
|
11633
|
-
|
|
11634
|
-
|
|
11635
|
-
|
|
11710
|
+
const responseContent = getLlmResultContent(llmResponse);
|
|
11711
|
+
const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
|
|
11712
|
+
if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
|
|
11713
|
+
throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
11714
|
+
}
|
|
11715
|
+
logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
|
|
11716
|
+
if (attemptContextUsage) {
|
|
11717
|
+
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
|
|
11718
|
+
} else {
|
|
11719
|
+
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
|
|
11720
|
+
}
|
|
11721
|
+
retryEpisode.finish("succeeded");
|
|
11722
|
+
return llmResponse;
|
|
11723
|
+
} catch (error) {
|
|
11724
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
11725
|
+
if (lastError.name === "AbortError") {
|
|
11726
|
+
logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
|
|
11727
|
+
attempt: attempt + 1,
|
|
11728
|
+
actualAttempts,
|
|
11729
|
+
maxTotalAttempts,
|
|
11730
|
+
reason: lastError.message
|
|
11636
11731
|
});
|
|
11637
|
-
|
|
11638
|
-
excludedModelIds.add(policySwitchModelId);
|
|
11639
|
-
attempt -= 1;
|
|
11640
|
-
continue;
|
|
11732
|
+
throw lastError;
|
|
11641
11733
|
}
|
|
11642
|
-
const
|
|
11643
|
-
|
|
11644
|
-
|
|
11645
|
-
|
|
11646
|
-
|
|
11647
|
-
|
|
11648
|
-
|
|
11649
|
-
|
|
11650
|
-
|
|
11734
|
+
const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
|
|
11735
|
+
const category = ErrorClassifier.getRetryCategory(classification);
|
|
11736
|
+
const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
|
|
11737
|
+
const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
|
|
11738
|
+
const failedRetryState = {
|
|
11739
|
+
category,
|
|
11740
|
+
attempt: categoryRetries[category],
|
|
11741
|
+
max_retries: currentMaxRetries,
|
|
11742
|
+
total_attempts: actualAttempts,
|
|
11743
|
+
error_code: classification.errorCode
|
|
11744
|
+
};
|
|
11745
|
+
logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
|
|
11746
|
+
attempt: attempt + 1,
|
|
11747
|
+
maxAttempts: currentMaxRetries + 1,
|
|
11748
|
+
actualAttempts,
|
|
11749
|
+
maxTotalAttempts,
|
|
11750
|
+
error: lastError.message
|
|
11651
11751
|
});
|
|
11652
|
-
|
|
11653
|
-
|
|
11654
|
-
|
|
11655
|
-
|
|
11656
|
-
|
|
11657
|
-
policy: "cloud-quota"
|
|
11752
|
+
previousAttemptTracker = attemptTracker;
|
|
11753
|
+
if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
|
|
11754
|
+
logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
|
|
11755
|
+
actualAttempts,
|
|
11756
|
+
maxTotalAttempts
|
|
11658
11757
|
});
|
|
11659
|
-
|
|
11660
|
-
|
|
11661
|
-
|
|
11662
|
-
continue;
|
|
11758
|
+
retryEpisode.finish("exhausted", failedRetryState);
|
|
11759
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
11760
|
+
throw lastError;
|
|
11663
11761
|
}
|
|
11664
|
-
|
|
11665
|
-
|
|
11666
|
-
|
|
11667
|
-
|
|
11668
|
-
|
|
11669
|
-
|
|
11670
|
-
|
|
11671
|
-
|
|
11672
|
-
|
|
11673
|
-
|
|
11674
|
-
|
|
11675
|
-
|
|
11676
|
-
|
|
11677
|
-
|
|
11678
|
-
|
|
11679
|
-
|
|
11680
|
-
|
|
11681
|
-
|
|
11682
|
-
|
|
11683
|
-
|
|
11684
|
-
|
|
11685
|
-
|
|
11686
|
-
|
|
11687
|
-
|
|
11688
|
-
|
|
11689
|
-
|
|
11690
|
-
|
|
11762
|
+
if (options.allow_model_fallback !== false) {
|
|
11763
|
+
const policySwitchModelId = tryPolicyModelSwitch(
|
|
11764
|
+
deps,
|
|
11765
|
+
activeModelId,
|
|
11766
|
+
excludedModelIds,
|
|
11767
|
+
requirement,
|
|
11768
|
+
fallbackObserver,
|
|
11769
|
+
lastError,
|
|
11770
|
+
invocationContext?.evaluateFallbackPromptCapacity
|
|
11771
|
+
);
|
|
11772
|
+
if (policySwitchModelId) {
|
|
11773
|
+
fallbackObserver?.onModelFallbackApplied?.({
|
|
11774
|
+
fromModelId: activeModelId,
|
|
11775
|
+
toModelId: policySwitchModelId,
|
|
11776
|
+
reason: lastError.message,
|
|
11777
|
+
policy: "policy-switch"
|
|
11778
|
+
});
|
|
11779
|
+
activeModelId = policySwitchModelId;
|
|
11780
|
+
excludedModelIds.add(policySwitchModelId);
|
|
11781
|
+
attempt -= 1;
|
|
11782
|
+
continue;
|
|
11783
|
+
}
|
|
11784
|
+
const quotaFallbackModelId = tryCloudQuotaFallback({
|
|
11785
|
+
deps,
|
|
11786
|
+
activeModelId,
|
|
11787
|
+
options,
|
|
11788
|
+
excludedModelIds,
|
|
11789
|
+
requirement,
|
|
11790
|
+
error: lastError,
|
|
11791
|
+
fallbackObserver,
|
|
11792
|
+
evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
|
|
11793
|
+
});
|
|
11794
|
+
if (quotaFallbackModelId) {
|
|
11795
|
+
fallbackObserver?.onModelFallbackApplied?.({
|
|
11796
|
+
fromModelId: activeModelId,
|
|
11797
|
+
toModelId: quotaFallbackModelId,
|
|
11798
|
+
reason: lastError.message,
|
|
11799
|
+
policy: "cloud-quota"
|
|
11800
|
+
});
|
|
11801
|
+
activeModelId = quotaFallbackModelId;
|
|
11802
|
+
excludedModelIds.add(quotaFallbackModelId);
|
|
11803
|
+
attempt -= 1;
|
|
11804
|
+
continue;
|
|
11805
|
+
}
|
|
11806
|
+
}
|
|
11807
|
+
if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
|
|
11808
|
+
logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
|
|
11809
|
+
retryEpisode.finish("failed", failedRetryState);
|
|
11810
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
11811
|
+
throw lastError;
|
|
11812
|
+
}
|
|
11813
|
+
if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
|
|
11814
|
+
logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
|
|
11815
|
+
retryEpisode.finish("exhausted", failedRetryState);
|
|
11816
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
11817
|
+
throw lastError;
|
|
11818
|
+
}
|
|
11819
|
+
const retryDelay = ErrorClassifier.calculateRetryDelay(
|
|
11820
|
+
classification,
|
|
11821
|
+
categoryRetries[category],
|
|
11822
|
+
deps.retryConfig.retryDelayMs,
|
|
11823
|
+
6e4
|
|
11824
|
+
);
|
|
11825
|
+
if (classification.category === "rate_limit" /* RATE_LIMIT */) {
|
|
11826
|
+
logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
|
|
11827
|
+
} else if (classification.category === "retryable" /* RETRYABLE */) {
|
|
11828
|
+
logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
|
|
11829
|
+
}
|
|
11830
|
+
throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
|
|
11831
|
+
categoryRetries[category] += 1;
|
|
11832
|
+
retryEpisode.waiting({
|
|
11833
|
+
category,
|
|
11834
|
+
attempt: categoryRetries[category],
|
|
11835
|
+
max_retries: currentMaxRetries,
|
|
11836
|
+
total_attempts: actualAttempts,
|
|
11837
|
+
error_code: classification.errorCode
|
|
11838
|
+
}, retryDelay);
|
|
11839
|
+
if (retryDelay > 0) await waitForRetry(retryDelay, signal);
|
|
11840
|
+
}
|
|
11841
|
+
}
|
|
11842
|
+
throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
|
|
11843
|
+
} catch (error) {
|
|
11844
|
+
retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
|
|
11845
|
+
throw error;
|
|
11691
11846
|
}
|
|
11692
|
-
|
|
11847
|
+
}
|
|
11848
|
+
function waitForRetry(delayMs, signal) {
|
|
11849
|
+
throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
|
|
11850
|
+
return new Promise((resolve, reject) => {
|
|
11851
|
+
const onAbort = () => {
|
|
11852
|
+
clearTimeout(timer);
|
|
11853
|
+
signal?.removeEventListener("abort", onAbort);
|
|
11854
|
+
reject(new DOMException("Request interrupted during retry delay", "AbortError"));
|
|
11855
|
+
};
|
|
11856
|
+
const timer = setTimeout(() => {
|
|
11857
|
+
signal?.removeEventListener("abort", onAbort);
|
|
11858
|
+
resolve();
|
|
11859
|
+
}, delayMs);
|
|
11860
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
11861
|
+
});
|
|
11693
11862
|
}
|
|
11694
11863
|
function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
|
|
11695
11864
|
if (options.retry_policy === "none") return false;
|
|
@@ -11748,9 +11917,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
|
|
|
11748
11917
|
}
|
|
11749
11918
|
};
|
|
11750
11919
|
}
|
|
11751
|
-
function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
|
|
11920
|
+
function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
|
|
11752
11921
|
if (!eventHandler) return;
|
|
11753
|
-
|
|
11922
|
+
const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
|
|
11923
|
+
eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
|
|
11754
11924
|
}
|
|
11755
11925
|
|
|
11756
11926
|
// src/runtime-kernel/llm/caller.ts
|
|
@@ -12472,6 +12642,8 @@ var RuntimeEventSubRunTracePublisher = class {
|
|
|
12472
12642
|
subrun_parent_id: this.subrunParentId,
|
|
12473
12643
|
source_event_id: envelope.source_event_id,
|
|
12474
12644
|
// 载荷透传
|
|
12645
|
+
..."retry" in envelope ? { retry: envelope.retry } : {},
|
|
12646
|
+
..."failure" in envelope ? { failure: envelope.failure } : {},
|
|
12475
12647
|
..."delta" in envelope ? { delta: envelope.delta } : {},
|
|
12476
12648
|
..."content" in envelope ? { content: envelope.content } : {},
|
|
12477
12649
|
..."answer_id" in envelope ? { answer_id: envelope.answer_id } : {},
|
|
@@ -12511,6 +12683,31 @@ var RuntimeEventSubRunTracePublisher = class {
|
|
|
12511
12683
|
// src/runtime-kernel/child-run-trace/projectChildRuntimeEventToSubRunTrace.ts
|
|
12512
12684
|
function projectChildRuntimeEventToSubRunTrace(event) {
|
|
12513
12685
|
switch (event.type) {
|
|
12686
|
+
case "llm_retry":
|
|
12687
|
+
return {
|
|
12688
|
+
kind: "llm_retry",
|
|
12689
|
+
source_event_id: event.id,
|
|
12690
|
+
retry: {
|
|
12691
|
+
retry_id: event.retry_id,
|
|
12692
|
+
status: event.status,
|
|
12693
|
+
category: event.category,
|
|
12694
|
+
attempt: event.attempt,
|
|
12695
|
+
max_retries: event.max_retries,
|
|
12696
|
+
total_attempts: event.total_attempts,
|
|
12697
|
+
started_at: event.started_at,
|
|
12698
|
+
delay_ms: event.delay_ms,
|
|
12699
|
+
next_retry_at: event.next_retry_at,
|
|
12700
|
+
error: event.error,
|
|
12701
|
+
error_code: event.error_code
|
|
12702
|
+
}
|
|
12703
|
+
};
|
|
12704
|
+
case "error":
|
|
12705
|
+
return {
|
|
12706
|
+
kind: "error",
|
|
12707
|
+
source_event_id: event.id,
|
|
12708
|
+
// 父展示只需要安全错误与重试身份,不复制 child 的任意诊断 details。
|
|
12709
|
+
failure: { error: event.error, error_code: event.error_code, retryable: event.retryable, retry_id: event.retry_id }
|
|
12710
|
+
};
|
|
12514
12711
|
case "thought":
|
|
12515
12712
|
return event.is_complete ? {
|
|
12516
12713
|
kind: "thought_complete",
|