@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.
- package/CHANGELOG.md +36 -1
- package/dist/cli.cjs +346 -178
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +346 -178
- 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/events.d.cts +517 -35
- package/dist/contracts/events.d.ts +517 -35
- package/dist/contracts/llm-retry.d.cts +47 -0
- package/dist/contracts/llm-retry.d.ts +47 -0
- package/dist/contracts/runtime-error.d.cts +26 -0
- package/dist/contracts/runtime-error.d.ts +26 -0
- package/dist/contracts/sse.d.cts +555 -39
- package/dist/contracts/sse.d.ts +555 -39
- 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 +551 -286
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +551 -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 +346 -178
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.js +346 -178
- 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 +513 -271
- package/dist/runtime-kernel.cjs.map +1 -1
- package/dist/runtime-kernel.js +513 -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 +511 -269
- package/dist/testkit.cjs.map +1 -1
- package/dist/testkit.js +511 -269
- package/dist/testkit.js.map +1 -1
- package/docs/integration/llm-provider.md +24 -5
- package/docs/integration/realtime.md +29 -0
- package/docs/integration/tools.md +4 -0
- package/package.json +2 -2
package/dist/runtime-kernel.js
CHANGED
|
@@ -128,11 +128,121 @@ var Logger = class {
|
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
130
|
};
|
|
131
|
+
var NonEmptyIdentitySchema = z.string().min(1).refine(
|
|
132
|
+
(value) => value === value.trim(),
|
|
133
|
+
"identity must not contain leading or trailing whitespace"
|
|
134
|
+
);
|
|
135
|
+
var RuntimeEventIdSchema = NonEmptyIdentitySchema;
|
|
136
|
+
var AiMessageIdSchema = NonEmptyIdentitySchema;
|
|
137
|
+
var ConversationIdSchema = NonEmptyIdentitySchema;
|
|
138
|
+
var TurnIdSchema = NonEmptyIdentitySchema;
|
|
139
|
+
var RunIdSchema = NonEmptyIdentitySchema.brand();
|
|
140
|
+
var ExecutionIdSchema = NonEmptyIdentitySchema;
|
|
141
|
+
var TraceIdSchema = NonEmptyIdentitySchema;
|
|
142
|
+
var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
|
|
143
|
+
var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
|
|
144
|
+
var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
|
|
145
|
+
var InteractionIdSchema = NonEmptyIdentitySchema;
|
|
146
|
+
var SubrunIdSchema = NonEmptyIdentitySchema;
|
|
147
|
+
var ResumeTokenSchema = NonEmptyIdentitySchema;
|
|
148
|
+
var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
|
|
149
|
+
var SourceEventIdSchema = RuntimeEventIdSchema;
|
|
150
|
+
var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
|
|
151
|
+
var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
|
|
152
|
+
|
|
153
|
+
// src/contracts/identity/generators.ts
|
|
154
|
+
function randomIdentity(prefix) {
|
|
155
|
+
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
156
|
+
throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
|
|
157
|
+
}
|
|
158
|
+
return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
159
|
+
}
|
|
160
|
+
function generateRuntimeEventId() {
|
|
161
|
+
return randomIdentity("evt");
|
|
162
|
+
}
|
|
163
|
+
function generateAnswerSegmentId() {
|
|
164
|
+
return randomIdentity("answer");
|
|
165
|
+
}
|
|
166
|
+
function generateTurnId() {
|
|
167
|
+
return randomIdentity("turn");
|
|
168
|
+
}
|
|
169
|
+
function generateRunId() {
|
|
170
|
+
return RunIdSchema.parse(randomIdentity("run"));
|
|
171
|
+
}
|
|
172
|
+
function generateExecutionId() {
|
|
173
|
+
return randomIdentity("exec");
|
|
174
|
+
}
|
|
175
|
+
function generateTraceId() {
|
|
176
|
+
return randomIdentity("trace");
|
|
177
|
+
}
|
|
178
|
+
function generateInferenceAttemptId() {
|
|
179
|
+
return randomIdentity("inference-attempt");
|
|
180
|
+
}
|
|
181
|
+
function generateThoughtMessageId() {
|
|
182
|
+
return randomIdentity("thought");
|
|
183
|
+
}
|
|
184
|
+
function generateToolCallId() {
|
|
185
|
+
return ToolCallIdSchema.parse(randomIdentity("call"));
|
|
186
|
+
}
|
|
187
|
+
function generateInteractionId() {
|
|
188
|
+
return randomIdentity("interaction");
|
|
189
|
+
}
|
|
190
|
+
function generateResumeToken() {
|
|
191
|
+
return randomIdentity("resume");
|
|
192
|
+
}
|
|
193
|
+
function generateRunResumeClaimId() {
|
|
194
|
+
return randomIdentity("resume-claim");
|
|
195
|
+
}
|
|
196
|
+
function generateAuditEnvelopeId() {
|
|
197
|
+
return randomIdentity("audit");
|
|
198
|
+
}
|
|
199
|
+
function generateContextLedgerEntryId() {
|
|
200
|
+
return randomIdentity("context-ledger");
|
|
201
|
+
}
|
|
202
|
+
function runIdFromTurnId(turnId) {
|
|
203
|
+
return RunIdSchema.parse(turnId);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// src/contracts/identity/invariants.ts
|
|
207
|
+
function assertCanonicalFinalAnswerIdentity(input) {
|
|
208
|
+
const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
|
|
209
|
+
if (input.id !== answerId) {
|
|
210
|
+
throw new Error(
|
|
211
|
+
`final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
return answerId;
|
|
215
|
+
}
|
|
216
|
+
function assertDistinctAnswerChunkIdentity(input) {
|
|
217
|
+
if (input.id === input.answer_id) {
|
|
218
|
+
throw new Error(
|
|
219
|
+
`final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// src/contracts/llm-retry.ts
|
|
225
|
+
var LlmRetryCategory = z.enum(["transport", "output", "rate_limit", "other"]);
|
|
226
|
+
var LlmRetryState = z.object({
|
|
227
|
+
retry_id: TraceIdSchema,
|
|
228
|
+
status: z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
|
|
229
|
+
category: LlmRetryCategory,
|
|
230
|
+
attempt: z.number().int().nonnegative(),
|
|
231
|
+
max_retries: z.number().int().nonnegative(),
|
|
232
|
+
total_attempts: z.number().int().positive(),
|
|
233
|
+
started_at: z.number().finite(),
|
|
234
|
+
delay_ms: z.number().finite().nonnegative(),
|
|
235
|
+
next_retry_at: z.number().finite().optional(),
|
|
236
|
+
/** 安全分类说明;不得放入供应商响应正文。 */
|
|
237
|
+
error: z.string(),
|
|
238
|
+
error_code: z.string().min(1)
|
|
239
|
+
}).strict();
|
|
131
240
|
|
|
132
241
|
// src/shared/errorClassifier.ts
|
|
133
242
|
var ENGINE_ERROR_CODES = {
|
|
134
243
|
LLM_RATE_LIMIT: "llm.rate_limit",
|
|
135
244
|
LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
|
|
245
|
+
LLM_EMPTY_RESPONSE: "llm.empty_response",
|
|
136
246
|
LLM_PROVIDER_DOWN: "llm.provider_down",
|
|
137
247
|
LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
|
|
138
248
|
LLM_AUTH_FAILED: "llm.auth_failed",
|
|
@@ -243,6 +353,8 @@ function readStructuredClassification(error) {
|
|
|
243
353
|
if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
|
|
244
354
|
if (typeof recoverable !== "boolean") return void 0;
|
|
245
355
|
const errorCode = rawErrorCode.trim();
|
|
356
|
+
const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
|
|
357
|
+
const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
|
|
246
358
|
const retryAfterMsValue = error["retryAfterMs"];
|
|
247
359
|
const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
|
|
248
360
|
const hintValue = error["hint"];
|
|
@@ -250,12 +362,13 @@ function readStructuredClassification(error) {
|
|
|
250
362
|
const metadataValue = error["metadata"];
|
|
251
363
|
const metadata = isRecord(metadataValue) ? metadataValue : void 0;
|
|
252
364
|
return createClassification(
|
|
253
|
-
recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
|
|
365
|
+
recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
|
|
254
366
|
`\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
|
|
255
367
|
recoverable ? retryAfterMs ?? 1e3 : null,
|
|
256
368
|
{
|
|
257
369
|
errorCode,
|
|
258
370
|
recoverable,
|
|
371
|
+
...retryCategory === void 0 ? {} : { retryCategory },
|
|
259
372
|
...retryAfterMs === void 0 ? {} : { retryAfterMs },
|
|
260
373
|
...hint === void 0 ? {} : { hint },
|
|
261
374
|
...metadata === void 0 ? {} : { metadata }
|
|
@@ -530,7 +643,7 @@ var ErrorClassifier = class {
|
|
|
530
643
|
if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
|
|
531
644
|
logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
|
|
532
645
|
return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
|
|
533
|
-
errorCode: ENGINE_ERROR_CODES.
|
|
646
|
+
errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
|
|
534
647
|
recoverable: true,
|
|
535
648
|
retryAfterMs: 1e3,
|
|
536
649
|
hint: "retry_with_backoff",
|
|
@@ -555,13 +668,21 @@ var ErrorClassifier = class {
|
|
|
555
668
|
const category = this.categorize(error);
|
|
556
669
|
return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
|
|
557
670
|
}
|
|
671
|
+
static getRetryCategory(classification) {
|
|
672
|
+
if (classification.retryCategory !== void 0) return classification.retryCategory;
|
|
673
|
+
if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
|
|
674
|
+
if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
|
|
675
|
+
if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
|
|
676
|
+
return "other";
|
|
677
|
+
}
|
|
558
678
|
static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
|
|
559
679
|
const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
|
|
560
680
|
if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
|
|
561
681
|
return 0;
|
|
562
682
|
}
|
|
563
|
-
|
|
564
|
-
|
|
683
|
+
const retryCategory = this.getRetryCategory(classification);
|
|
684
|
+
if (retryCategory === "rate_limit" || retryCategory === "transport") {
|
|
685
|
+
return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
|
|
565
686
|
}
|
|
566
687
|
return Math.max(baseDelay, classification.suggestedDelay ?? 0);
|
|
567
688
|
}
|
|
@@ -602,98 +723,6 @@ var RuntimeResourceRef = z.object({
|
|
|
602
723
|
label: LabelSchema.optional()
|
|
603
724
|
}).strict();
|
|
604
725
|
var RuntimeResourceRefs = z.array(RuntimeResourceRef).min(1);
|
|
605
|
-
var NonEmptyIdentitySchema = z.string().min(1).refine(
|
|
606
|
-
(value) => value === value.trim(),
|
|
607
|
-
"identity must not contain leading or trailing whitespace"
|
|
608
|
-
);
|
|
609
|
-
var RuntimeEventIdSchema = NonEmptyIdentitySchema;
|
|
610
|
-
var AiMessageIdSchema = NonEmptyIdentitySchema;
|
|
611
|
-
var ConversationIdSchema = NonEmptyIdentitySchema;
|
|
612
|
-
var TurnIdSchema = NonEmptyIdentitySchema;
|
|
613
|
-
var RunIdSchema = NonEmptyIdentitySchema.brand();
|
|
614
|
-
var ExecutionIdSchema = NonEmptyIdentitySchema;
|
|
615
|
-
var TraceIdSchema = NonEmptyIdentitySchema;
|
|
616
|
-
var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
|
|
617
|
-
var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
|
|
618
|
-
var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
|
|
619
|
-
var InteractionIdSchema = NonEmptyIdentitySchema;
|
|
620
|
-
var SubrunIdSchema = NonEmptyIdentitySchema;
|
|
621
|
-
var ResumeTokenSchema = NonEmptyIdentitySchema;
|
|
622
|
-
var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
|
|
623
|
-
var SourceEventIdSchema = RuntimeEventIdSchema;
|
|
624
|
-
var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
|
|
625
|
-
var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
|
|
626
|
-
|
|
627
|
-
// src/contracts/identity/generators.ts
|
|
628
|
-
function randomIdentity(prefix) {
|
|
629
|
-
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
630
|
-
throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
|
|
631
|
-
}
|
|
632
|
-
return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
633
|
-
}
|
|
634
|
-
function generateRuntimeEventId() {
|
|
635
|
-
return randomIdentity("evt");
|
|
636
|
-
}
|
|
637
|
-
function generateAnswerSegmentId() {
|
|
638
|
-
return randomIdentity("answer");
|
|
639
|
-
}
|
|
640
|
-
function generateTurnId() {
|
|
641
|
-
return randomIdentity("turn");
|
|
642
|
-
}
|
|
643
|
-
function generateRunId() {
|
|
644
|
-
return RunIdSchema.parse(randomIdentity("run"));
|
|
645
|
-
}
|
|
646
|
-
function generateExecutionId() {
|
|
647
|
-
return randomIdentity("exec");
|
|
648
|
-
}
|
|
649
|
-
function generateTraceId() {
|
|
650
|
-
return randomIdentity("trace");
|
|
651
|
-
}
|
|
652
|
-
function generateInferenceAttemptId() {
|
|
653
|
-
return randomIdentity("inference-attempt");
|
|
654
|
-
}
|
|
655
|
-
function generateThoughtMessageId() {
|
|
656
|
-
return randomIdentity("thought");
|
|
657
|
-
}
|
|
658
|
-
function generateToolCallId() {
|
|
659
|
-
return ToolCallIdSchema.parse(randomIdentity("call"));
|
|
660
|
-
}
|
|
661
|
-
function generateInteractionId() {
|
|
662
|
-
return randomIdentity("interaction");
|
|
663
|
-
}
|
|
664
|
-
function generateResumeToken() {
|
|
665
|
-
return randomIdentity("resume");
|
|
666
|
-
}
|
|
667
|
-
function generateRunResumeClaimId() {
|
|
668
|
-
return randomIdentity("resume-claim");
|
|
669
|
-
}
|
|
670
|
-
function generateAuditEnvelopeId() {
|
|
671
|
-
return randomIdentity("audit");
|
|
672
|
-
}
|
|
673
|
-
function generateContextLedgerEntryId() {
|
|
674
|
-
return randomIdentity("context-ledger");
|
|
675
|
-
}
|
|
676
|
-
function runIdFromTurnId(turnId) {
|
|
677
|
-
return RunIdSchema.parse(turnId);
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
// src/contracts/identity/invariants.ts
|
|
681
|
-
function assertCanonicalFinalAnswerIdentity(input) {
|
|
682
|
-
const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
|
|
683
|
-
if (input.id !== answerId) {
|
|
684
|
-
throw new Error(
|
|
685
|
-
`final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
|
|
686
|
-
);
|
|
687
|
-
}
|
|
688
|
-
return answerId;
|
|
689
|
-
}
|
|
690
|
-
function assertDistinctAnswerChunkIdentity(input) {
|
|
691
|
-
if (input.id === input.answer_id) {
|
|
692
|
-
throw new Error(
|
|
693
|
-
`final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
|
|
694
|
-
);
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
726
|
var FinalAnswerCompletionReason = z.enum([
|
|
698
727
|
"terminal",
|
|
699
728
|
"tool_call",
|
|
@@ -1168,6 +1197,13 @@ var AuditEnvelope = z.object({
|
|
|
1168
1197
|
costDelta: AuditCostDelta.optional(),
|
|
1169
1198
|
scope: AuditScope.optional()
|
|
1170
1199
|
});
|
|
1200
|
+
var RuntimeErrorState = z.object({
|
|
1201
|
+
error: z.string(),
|
|
1202
|
+
error_code: z.string().optional(),
|
|
1203
|
+
retryable: z.boolean().optional(),
|
|
1204
|
+
retry_id: TraceIdSchema.optional(),
|
|
1205
|
+
details: SerializableJsonValue.optional()
|
|
1206
|
+
}).strict();
|
|
1171
1207
|
var ToolCallPhase = z.enum(["start", "update", "complete", "error"]);
|
|
1172
1208
|
var Status = z.enum(["loading", "success", "error"]);
|
|
1173
1209
|
var SubRunTraceKind = z.enum([
|
|
@@ -1178,7 +1214,9 @@ var SubRunTraceKind = z.enum([
|
|
|
1178
1214
|
"tool_output",
|
|
1179
1215
|
"final_answer_chunk",
|
|
1180
1216
|
"final_answer",
|
|
1181
|
-
"history_summary"
|
|
1217
|
+
"history_summary",
|
|
1218
|
+
"llm_retry",
|
|
1219
|
+
"error"
|
|
1182
1220
|
]);
|
|
1183
1221
|
var SubRunTraceToolCallDecision = z.object({
|
|
1184
1222
|
tool_call_id: ToolCallIdSchema,
|
|
@@ -1191,6 +1229,8 @@ var SubRunTracePayload = z.object({
|
|
|
1191
1229
|
subrun_parent_id: SubrunIdSchema.optional(),
|
|
1192
1230
|
source_event_id: SourceEventIdSchema,
|
|
1193
1231
|
kind: SubRunTraceKind,
|
|
1232
|
+
retry: LlmRetryState.optional(),
|
|
1233
|
+
failure: RuntimeErrorState.optional(),
|
|
1194
1234
|
delta: z.string().optional(),
|
|
1195
1235
|
content: z.string().optional(),
|
|
1196
1236
|
answer_id: AnswerSegmentIdSchema.optional(),
|
|
@@ -1213,6 +1253,12 @@ var SubRunTracePayload = z.object({
|
|
|
1213
1253
|
meta: SerializableJsonRecord.optional()
|
|
1214
1254
|
});
|
|
1215
1255
|
function validateSubRunTracePayloadSemantics(payload, ctx) {
|
|
1256
|
+
if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
|
|
1257
|
+
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
|
|
1258
|
+
}
|
|
1259
|
+
if (payload.kind === "error" !== (payload.failure !== void 0)) {
|
|
1260
|
+
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
|
|
1261
|
+
}
|
|
1216
1262
|
if (payload.kind === "thought_delta" && payload.delta === void 0) {
|
|
1217
1263
|
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
|
|
1218
1264
|
}
|
|
@@ -1566,12 +1612,10 @@ var RuntimeEventShape = z.discriminatedUnion("type", [
|
|
|
1566
1612
|
compression_ratio: z.number().min(0).max(1).optional(),
|
|
1567
1613
|
included_old_summary: z.boolean().optional()
|
|
1568
1614
|
}),
|
|
1615
|
+
BaseEvent.extend({ type: z.literal("llm_retry"), ...LlmRetryState.shape }),
|
|
1569
1616
|
BaseEvent.extend({
|
|
1570
1617
|
type: z.literal("error"),
|
|
1571
|
-
|
|
1572
|
-
details: SerializableJsonValue.optional(),
|
|
1573
|
-
error_code: z.string().optional(),
|
|
1574
|
-
retryable: z.boolean().optional()
|
|
1618
|
+
...RuntimeErrorState.shape
|
|
1575
1619
|
}),
|
|
1576
1620
|
BaseEvent.extend({
|
|
1577
1621
|
type: z.literal("control"),
|
|
@@ -2006,12 +2050,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
|
|
|
2006
2050
|
resume_token: ResumeTokenSchema,
|
|
2007
2051
|
interaction_status: z.literal("pending")
|
|
2008
2052
|
});
|
|
2053
|
+
var SSELlmRetryEvent = BaseSSEEvent.extend({
|
|
2054
|
+
type: z.literal("llm_retry"),
|
|
2055
|
+
...LlmRetryState.shape
|
|
2056
|
+
});
|
|
2009
2057
|
var SSEErrorEvent = BaseSSEEvent.extend({
|
|
2010
2058
|
type: z.literal("error"),
|
|
2011
|
-
|
|
2012
|
-
details: SerializableJsonValue.optional(),
|
|
2013
|
-
error_code: z.string().optional(),
|
|
2014
|
-
retryable: z.boolean().optional()
|
|
2059
|
+
...RuntimeErrorState.shape
|
|
2015
2060
|
});
|
|
2016
2061
|
var SSETransportErrorEvent = BaseSSEEvent.extend({
|
|
2017
2062
|
type: z.literal("transport_error"),
|
|
@@ -2094,6 +2139,7 @@ z.discriminatedUnion("type", [
|
|
|
2094
2139
|
SSEToolOutputEvent,
|
|
2095
2140
|
SSESubRunTraceEvent,
|
|
2096
2141
|
SSERequiresUserInteractionEvent,
|
|
2142
|
+
SSELlmRetryEvent,
|
|
2097
2143
|
SSEErrorEvent,
|
|
2098
2144
|
SSETransportErrorEvent,
|
|
2099
2145
|
SSEContextUsageSnapshotEvent,
|
|
@@ -6465,6 +6511,8 @@ function getRuntimeEventUiProjectionKind(event) {
|
|
|
6465
6511
|
return "audit_envelope";
|
|
6466
6512
|
case "subrun_trace":
|
|
6467
6513
|
return "subrun_trace";
|
|
6514
|
+
case "llm_retry":
|
|
6515
|
+
return "llm_retry";
|
|
6468
6516
|
case "error":
|
|
6469
6517
|
return "error";
|
|
6470
6518
|
case "context_usage_snapshot":
|
|
@@ -6494,7 +6542,7 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
6494
6542
|
if (isContextUsageSnapshotRuntimeEvent(event)) {
|
|
6495
6543
|
return false;
|
|
6496
6544
|
}
|
|
6497
|
-
if (event.type === "error") {
|
|
6545
|
+
if (event.type === "error" || event.type === "llm_retry") {
|
|
6498
6546
|
return false;
|
|
6499
6547
|
}
|
|
6500
6548
|
if (isRequiresUserInteractionRuntimeEvent(event)) {
|
|
@@ -6537,6 +6585,7 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
6537
6585
|
case "tool_output":
|
|
6538
6586
|
case "requires_user_interaction":
|
|
6539
6587
|
case "subrun_trace":
|
|
6588
|
+
case "llm_retry":
|
|
6540
6589
|
case "error":
|
|
6541
6590
|
case "context_usage_snapshot":
|
|
6542
6591
|
case "run_execution_metrics":
|
|
@@ -6753,8 +6802,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
|
|
|
6753
6802
|
assistant_replay_parts: AssistantReplayParts.optional(),
|
|
6754
6803
|
meta: UnknownRecord.optional()
|
|
6755
6804
|
}).strict();
|
|
6805
|
+
var LlmRetryEventSchema = BaseAgentEvent.extend({
|
|
6806
|
+
type: z.literal("llm_retry"),
|
|
6807
|
+
...LlmRetryState.shape
|
|
6808
|
+
}).strict();
|
|
6756
6809
|
var ErrorEventSchema = BaseAgentEvent.extend({
|
|
6757
6810
|
type: z.literal("error"),
|
|
6811
|
+
retry_id: LlmRetryState.shape.retry_id.optional(),
|
|
6758
6812
|
error: z.string(),
|
|
6759
6813
|
error_code: z.string().optional(),
|
|
6760
6814
|
retryable: z.boolean().optional(),
|
|
@@ -6784,6 +6838,7 @@ var AgentEventSchema = z.discriminatedUnion("type", [
|
|
|
6784
6838
|
ToolProcessEventSchema,
|
|
6785
6839
|
ObservationEventSchema,
|
|
6786
6840
|
FinalAnswerEventSchema,
|
|
6841
|
+
LlmRetryEventSchema,
|
|
6787
6842
|
ErrorEventSchema,
|
|
6788
6843
|
StreamChunkEventSchema,
|
|
6789
6844
|
StreamResetEventSchema,
|
|
@@ -6884,13 +6939,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
|
|
|
6884
6939
|
if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
|
|
6885
6940
|
return event;
|
|
6886
6941
|
}
|
|
6942
|
+
case "llm_retry":
|
|
6943
|
+
return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
|
|
6887
6944
|
case "error": {
|
|
6888
6945
|
const errorEvent = typed;
|
|
6889
6946
|
const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
|
|
6890
6947
|
timestamp,
|
|
6891
6948
|
details: toSerializableJsonValue(errorEvent.details),
|
|
6892
6949
|
error_code: errorEvent.error_code,
|
|
6893
|
-
retryable: errorEvent.retryable
|
|
6950
|
+
retryable: errorEvent.retryable,
|
|
6951
|
+
retry_id: errorEvent.retry_id
|
|
6894
6952
|
});
|
|
6895
6953
|
if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
|
|
6896
6954
|
return event;
|
|
@@ -9859,6 +9917,51 @@ __export(tools_exports, {
|
|
|
9859
9917
|
stripRuntimeReservedToolContextPatch: () => stripRuntimeReservedToolContextPatch
|
|
9860
9918
|
});
|
|
9861
9919
|
|
|
9920
|
+
// src/runtime-kernel/tools/schema/functions/formatUnknownToolArguments.ts
|
|
9921
|
+
function spellingDistance(left, right) {
|
|
9922
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
9923
|
+
for (let row = 1; row <= left.length; row += 1) {
|
|
9924
|
+
const current = [row];
|
|
9925
|
+
for (let column = 1; column <= right.length; column += 1) {
|
|
9926
|
+
current[column] = Math.min(
|
|
9927
|
+
current[column - 1] + 1,
|
|
9928
|
+
previous[column] + 1,
|
|
9929
|
+
previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1)
|
|
9930
|
+
);
|
|
9931
|
+
}
|
|
9932
|
+
previous = current;
|
|
9933
|
+
}
|
|
9934
|
+
return previous[right.length];
|
|
9935
|
+
}
|
|
9936
|
+
function nearestField(field, allowedFields) {
|
|
9937
|
+
const threshold = field.length < 5 ? 1 : 2;
|
|
9938
|
+
let nearest;
|
|
9939
|
+
let bestDistance = threshold + 1;
|
|
9940
|
+
for (const candidate of allowedFields) {
|
|
9941
|
+
if (Math.abs(field.length - candidate.length) > threshold) continue;
|
|
9942
|
+
const distance = spellingDistance(field, candidate);
|
|
9943
|
+
if (distance < bestDistance) {
|
|
9944
|
+
bestDistance = distance;
|
|
9945
|
+
nearest = candidate;
|
|
9946
|
+
} else if (distance === bestDistance) {
|
|
9947
|
+
nearest = void 0;
|
|
9948
|
+
}
|
|
9949
|
+
}
|
|
9950
|
+
return bestDistance <= threshold ? nearest : void 0;
|
|
9951
|
+
}
|
|
9952
|
+
function formatUnknownToolArguments(fields, allowedFields) {
|
|
9953
|
+
const suggestions = fields.flatMap((field) => {
|
|
9954
|
+
const candidate = nearestField(field, allowedFields);
|
|
9955
|
+
return candidate ? [`${JSON.stringify(field)} \u2192 ${JSON.stringify(candidate)}`] : [];
|
|
9956
|
+
});
|
|
9957
|
+
return [
|
|
9958
|
+
`Additional properties not allowed: ${fields.map((field) => JSON.stringify(field)).join(", ")}.`,
|
|
9959
|
+
`Allowed parameters: ${allowedFields.map((field) => JSON.stringify(field)).join(", ") || "(none)"}.`,
|
|
9960
|
+
...suggestions.length > 0 ? [`Possible spelling corrections: ${suggestions.join("; ")}.`] : [],
|
|
9961
|
+
"Remove unsupported parameters before retrying; no arguments were changed or executed."
|
|
9962
|
+
].join(" ");
|
|
9963
|
+
}
|
|
9964
|
+
|
|
9862
9965
|
// src/runtime-kernel/tools/toolContracts.ts
|
|
9863
9966
|
var BaseTool = class {
|
|
9864
9967
|
idempotency;
|
|
@@ -9894,7 +9997,7 @@ var BaseTool = class {
|
|
|
9894
9997
|
if (unknownFields.length > 0) {
|
|
9895
9998
|
return {
|
|
9896
9999
|
success: false,
|
|
9897
|
-
error:
|
|
10000
|
+
error: formatUnknownToolArguments(unknownFields, [...allowed])
|
|
9898
10001
|
};
|
|
9899
10002
|
}
|
|
9900
10003
|
}
|
|
@@ -10361,7 +10464,7 @@ var EventBusEventPersistence = class {
|
|
|
10361
10464
|
if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
|
|
10362
10465
|
return;
|
|
10363
10466
|
}
|
|
10364
|
-
if (this.checkpointWritesActive) {
|
|
10467
|
+
if (this.checkpointWritesActive && event.type !== "llm_retry") {
|
|
10365
10468
|
this.scheduledEventIds.add(event.id);
|
|
10366
10469
|
this.checkpointEvents.push(event);
|
|
10367
10470
|
return;
|
|
@@ -10543,21 +10646,37 @@ function resolveLlmMaxTotalAttempts(config) {
|
|
|
10543
10646
|
function hasLlmAttemptBudgetRemaining(params) {
|
|
10544
10647
|
return params.actualAttempts < params.maxTotalAttempts;
|
|
10545
10648
|
}
|
|
10649
|
+
function validateLlmRetryConfig(config) {
|
|
10650
|
+
if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
|
|
10651
|
+
throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
|
|
10652
|
+
}
|
|
10653
|
+
if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
|
|
10654
|
+
throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
|
|
10655
|
+
}
|
|
10656
|
+
for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
|
|
10657
|
+
if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
|
|
10658
|
+
throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
|
|
10659
|
+
}
|
|
10660
|
+
}
|
|
10661
|
+
}
|
|
10546
10662
|
|
|
10547
10663
|
// src/runtime-kernel/llm/request-builder.ts
|
|
10548
10664
|
function buildLlmCallerDeps(options) {
|
|
10549
10665
|
const modelCatalog = options.modelCatalog;
|
|
10550
10666
|
const maxRetries = options.maxRetries ?? 3;
|
|
10551
|
-
|
|
10552
|
-
|
|
10667
|
+
const retryConfig = {
|
|
10668
|
+
maxRetries,
|
|
10669
|
+
maxRetriesByCategory: options.maxRetriesByCategory,
|
|
10670
|
+
maxTotalAttempts: resolveLlmMaxTotalAttempts({
|
|
10553
10671
|
maxRetries,
|
|
10554
|
-
maxTotalAttempts:
|
|
10555
|
-
|
|
10556
|
-
|
|
10557
|
-
|
|
10558
|
-
|
|
10559
|
-
|
|
10560
|
-
|
|
10672
|
+
maxTotalAttempts: options.maxTotalAttempts
|
|
10673
|
+
}),
|
|
10674
|
+
enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
|
|
10675
|
+
retryDelayMs: options.retryDelayMs ?? 1e3
|
|
10676
|
+
};
|
|
10677
|
+
validateLlmRetryConfig(retryConfig);
|
|
10678
|
+
return {
|
|
10679
|
+
retryConfig,
|
|
10561
10680
|
modelResolver: options.modelResolver ?? new ModelResolver({
|
|
10562
10681
|
fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
|
|
10563
10682
|
modelCatalog
|
|
@@ -11024,6 +11143,7 @@ var logger14 = new Logger("LlmCaller");
|
|
|
11024
11143
|
var CanonicalInferenceFailureError = class extends Error {
|
|
11025
11144
|
errorCode;
|
|
11026
11145
|
recoverable;
|
|
11146
|
+
retryCategory;
|
|
11027
11147
|
metadata;
|
|
11028
11148
|
constructor(failure, abortReason) {
|
|
11029
11149
|
const message = failure.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure.code}`;
|
|
@@ -11031,6 +11151,7 @@ var CanonicalInferenceFailureError = class extends Error {
|
|
|
11031
11151
|
this.name = failure.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
|
|
11032
11152
|
this.errorCode = `llm.${failure.code}`;
|
|
11033
11153
|
this.recoverable = failure.retryable;
|
|
11154
|
+
this.retryCategory = failure.retry_category;
|
|
11034
11155
|
this.metadata = { failure_kind: failure.kind, provider_code: failure.code };
|
|
11035
11156
|
}
|
|
11036
11157
|
};
|
|
@@ -11266,6 +11387,57 @@ async function callLlmStream(params) {
|
|
|
11266
11387
|
};
|
|
11267
11388
|
}
|
|
11268
11389
|
|
|
11390
|
+
// src/runtime-kernel/llm/functions/llmRetryEpisode.ts
|
|
11391
|
+
var SAFE_RETRY_MESSAGES = {
|
|
11392
|
+
transport: "Network connection interrupted",
|
|
11393
|
+
output: "Model output could not be accepted",
|
|
11394
|
+
rate_limit: "Model request rate limit reached",
|
|
11395
|
+
other: "Model request temporarily failed"
|
|
11396
|
+
};
|
|
11397
|
+
var LlmRetryEpisode = class {
|
|
11398
|
+
constructor(id, emit) {
|
|
11399
|
+
this.id = id;
|
|
11400
|
+
this.emit = emit;
|
|
11401
|
+
}
|
|
11402
|
+
id;
|
|
11403
|
+
emit;
|
|
11404
|
+
state;
|
|
11405
|
+
ended = false;
|
|
11406
|
+
get activeId() {
|
|
11407
|
+
return this.state ? this.id : void 0;
|
|
11408
|
+
}
|
|
11409
|
+
waiting(params, delay) {
|
|
11410
|
+
const now = Date.now();
|
|
11411
|
+
this.state = {
|
|
11412
|
+
...params,
|
|
11413
|
+
retry_id: this.id,
|
|
11414
|
+
status: "waiting",
|
|
11415
|
+
started_at: this.state?.started_at ?? now,
|
|
11416
|
+
delay_ms: delay,
|
|
11417
|
+
next_retry_at: now + delay,
|
|
11418
|
+
error: SAFE_RETRY_MESSAGES[params.category]
|
|
11419
|
+
};
|
|
11420
|
+
this.publish();
|
|
11421
|
+
}
|
|
11422
|
+
retrying(totalAttempts) {
|
|
11423
|
+
if (!this.state || this.ended) return;
|
|
11424
|
+
const { next_retry_at: ignored, ...state } = this.state;
|
|
11425
|
+
this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
|
|
11426
|
+
this.publish();
|
|
11427
|
+
}
|
|
11428
|
+
finish(status, failure) {
|
|
11429
|
+
if (!this.state || this.ended) return;
|
|
11430
|
+
this.ended = true;
|
|
11431
|
+
const { next_retry_at: ignored, ...state } = this.state;
|
|
11432
|
+
this.state = { ...state, ...failure, status, delay_ms: 0, ...failure ? { error: SAFE_RETRY_MESSAGES[failure.category] } : {} };
|
|
11433
|
+
this.publish();
|
|
11434
|
+
}
|
|
11435
|
+
publish() {
|
|
11436
|
+
if (!this.state) return;
|
|
11437
|
+
this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
|
|
11438
|
+
}
|
|
11439
|
+
};
|
|
11440
|
+
|
|
11269
11441
|
// src/runtime-kernel/llm/retry-fallback-routing.ts
|
|
11270
11442
|
var logger15 = new Logger("LlmCaller");
|
|
11271
11443
|
function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
|
|
@@ -11518,6 +11690,8 @@ async function callWithRetryFallback(params) {
|
|
|
11518
11690
|
maxTotalAttempts: deps.retryConfig.maxTotalAttempts
|
|
11519
11691
|
});
|
|
11520
11692
|
const traceId = generateTraceId();
|
|
11693
|
+
const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
|
|
11694
|
+
const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
|
|
11521
11695
|
let previousAttemptTracker;
|
|
11522
11696
|
if (!clientRetryEnabled) {
|
|
11523
11697
|
const activeCfg = deps.modelCatalog.getModelById(modelId);
|
|
@@ -11527,167 +11701,207 @@ async function callWithRetryFallback(params) {
|
|
|
11527
11701
|
reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
|
|
11528
11702
|
});
|
|
11529
11703
|
}
|
|
11530
|
-
|
|
11531
|
-
|
|
11532
|
-
|
|
11533
|
-
|
|
11534
|
-
|
|
11535
|
-
previousAttemptTracker = void 0;
|
|
11536
|
-
const resolvedMessages = await runLlmInputPreflight({
|
|
11537
|
-
activeModelId,
|
|
11538
|
-
messages,
|
|
11539
|
-
modelCatalog: deps.modelCatalog,
|
|
11540
|
-
materializer: deps.llmInputMaterializer,
|
|
11541
|
-
invocationContext,
|
|
11542
|
-
eventHandler,
|
|
11543
|
-
requirement
|
|
11544
|
-
});
|
|
11545
|
-
const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
|
|
11546
|
-
const isRetry = attempt > 0;
|
|
11547
|
-
let pendingErrorEvent = null;
|
|
11548
|
-
let streamedErrorClassification;
|
|
11549
|
-
const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
|
|
11550
|
-
pendingErrorEvent = evt;
|
|
11551
|
-
}) : void 0;
|
|
11552
|
-
try {
|
|
11553
|
-
if (isRetry) {
|
|
11554
|
-
logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
|
|
11555
|
-
}
|
|
11556
|
-
actualAttempts++;
|
|
11557
|
-
const llmResponse = attemptTracker ? await callLlmStream({
|
|
11558
|
-
inferencePort: deps.inferencePort,
|
|
11559
|
-
modelId: activeModelId,
|
|
11560
|
-
messages: resolvedMessages,
|
|
11561
|
-
options,
|
|
11562
|
-
eventHandler: attemptTracker.handle,
|
|
11563
|
-
onErrorClassification(classification) {
|
|
11564
|
-
streamedErrorClassification = classification;
|
|
11565
|
-
},
|
|
11566
|
-
signal,
|
|
11567
|
-
toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
|
|
11568
|
-
traceId
|
|
11569
|
-
}) : await callPlainCompletion(
|
|
11570
|
-
deps.inferencePort,
|
|
11571
|
-
activeModelId,
|
|
11572
|
-
resolvedMessages,
|
|
11573
|
-
options,
|
|
11574
|
-
signal,
|
|
11575
|
-
traceId
|
|
11576
|
-
);
|
|
11577
|
-
const responseContent = getLlmResultContent(llmResponse);
|
|
11578
|
-
const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
|
|
11579
|
-
if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
|
|
11580
|
-
throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
11581
|
-
}
|
|
11582
|
-
logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
|
|
11583
|
-
if (attemptContextUsage) {
|
|
11584
|
-
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
|
|
11585
|
-
} else {
|
|
11586
|
-
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
|
|
11704
|
+
try {
|
|
11705
|
+
for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
|
|
11706
|
+
throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
|
|
11707
|
+
if (previousAttemptTracker?.hasEmitted() && eventHandler) {
|
|
11708
|
+
eventHandler(previousAttemptTracker.buildResetEvent());
|
|
11587
11709
|
}
|
|
11588
|
-
|
|
11589
|
-
|
|
11590
|
-
|
|
11591
|
-
|
|
11592
|
-
|
|
11593
|
-
|
|
11594
|
-
|
|
11595
|
-
|
|
11596
|
-
|
|
11597
|
-
});
|
|
11598
|
-
throw lastError;
|
|
11599
|
-
}
|
|
11600
|
-
const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
|
|
11601
|
-
const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
|
|
11602
|
-
logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
|
|
11603
|
-
attempt: attempt + 1,
|
|
11604
|
-
maxAttempts: currentMaxRetries + 1,
|
|
11605
|
-
actualAttempts,
|
|
11606
|
-
maxTotalAttempts,
|
|
11607
|
-
error: lastError.message
|
|
11710
|
+
previousAttemptTracker = void 0;
|
|
11711
|
+
const resolvedMessages = await runLlmInputPreflight({
|
|
11712
|
+
activeModelId,
|
|
11713
|
+
messages,
|
|
11714
|
+
modelCatalog: deps.modelCatalog,
|
|
11715
|
+
materializer: deps.llmInputMaterializer,
|
|
11716
|
+
invocationContext,
|
|
11717
|
+
eventHandler,
|
|
11718
|
+
requirement
|
|
11608
11719
|
});
|
|
11609
|
-
|
|
11610
|
-
|
|
11611
|
-
|
|
11612
|
-
|
|
11613
|
-
|
|
11614
|
-
|
|
11615
|
-
|
|
11616
|
-
|
|
11617
|
-
|
|
11618
|
-
|
|
11619
|
-
|
|
11620
|
-
|
|
11720
|
+
const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
|
|
11721
|
+
const isRetry = attempt > 0;
|
|
11722
|
+
let pendingErrorEvent = null;
|
|
11723
|
+
let streamedErrorClassification;
|
|
11724
|
+
const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
|
|
11725
|
+
pendingErrorEvent = evt;
|
|
11726
|
+
}) : void 0;
|
|
11727
|
+
try {
|
|
11728
|
+
if (isRetry) {
|
|
11729
|
+
logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
|
|
11730
|
+
}
|
|
11731
|
+
actualAttempts++;
|
|
11732
|
+
retryEpisode.retrying(actualAttempts);
|
|
11733
|
+
const llmResponse = attemptTracker ? await callLlmStream({
|
|
11734
|
+
inferencePort: deps.inferencePort,
|
|
11735
|
+
modelId: activeModelId,
|
|
11736
|
+
messages: resolvedMessages,
|
|
11737
|
+
options,
|
|
11738
|
+
eventHandler: attemptTracker.handle,
|
|
11739
|
+
onErrorClassification(classification) {
|
|
11740
|
+
streamedErrorClassification = classification;
|
|
11741
|
+
},
|
|
11742
|
+
signal,
|
|
11743
|
+
toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
|
|
11744
|
+
traceId
|
|
11745
|
+
}) : await callPlainCompletion(
|
|
11746
|
+
deps.inferencePort,
|
|
11621
11747
|
activeModelId,
|
|
11622
|
-
|
|
11623
|
-
|
|
11624
|
-
|
|
11625
|
-
|
|
11626
|
-
invocationContext?.evaluateFallbackPromptCapacity
|
|
11748
|
+
resolvedMessages,
|
|
11749
|
+
options,
|
|
11750
|
+
signal,
|
|
11751
|
+
traceId
|
|
11627
11752
|
);
|
|
11628
|
-
|
|
11629
|
-
|
|
11630
|
-
|
|
11631
|
-
|
|
11632
|
-
|
|
11633
|
-
|
|
11753
|
+
const responseContent = getLlmResultContent(llmResponse);
|
|
11754
|
+
const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
|
|
11755
|
+
if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
|
|
11756
|
+
throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
11757
|
+
}
|
|
11758
|
+
logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
|
|
11759
|
+
if (attemptContextUsage) {
|
|
11760
|
+
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
|
|
11761
|
+
} else {
|
|
11762
|
+
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
|
|
11763
|
+
}
|
|
11764
|
+
retryEpisode.finish("succeeded");
|
|
11765
|
+
return llmResponse;
|
|
11766
|
+
} catch (error) {
|
|
11767
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
11768
|
+
if (lastError.name === "AbortError") {
|
|
11769
|
+
logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
|
|
11770
|
+
attempt: attempt + 1,
|
|
11771
|
+
actualAttempts,
|
|
11772
|
+
maxTotalAttempts,
|
|
11773
|
+
reason: lastError.message
|
|
11634
11774
|
});
|
|
11635
|
-
|
|
11636
|
-
excludedModelIds.add(policySwitchModelId);
|
|
11637
|
-
attempt -= 1;
|
|
11638
|
-
continue;
|
|
11775
|
+
throw lastError;
|
|
11639
11776
|
}
|
|
11640
|
-
const
|
|
11641
|
-
|
|
11642
|
-
|
|
11643
|
-
|
|
11644
|
-
|
|
11645
|
-
|
|
11646
|
-
|
|
11647
|
-
|
|
11648
|
-
|
|
11777
|
+
const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
|
|
11778
|
+
const category = ErrorClassifier.getRetryCategory(classification);
|
|
11779
|
+
const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
|
|
11780
|
+
const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
|
|
11781
|
+
const failedRetryState = {
|
|
11782
|
+
category,
|
|
11783
|
+
attempt: categoryRetries[category],
|
|
11784
|
+
max_retries: currentMaxRetries,
|
|
11785
|
+
total_attempts: actualAttempts,
|
|
11786
|
+
error_code: classification.errorCode
|
|
11787
|
+
};
|
|
11788
|
+
logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
|
|
11789
|
+
attempt: attempt + 1,
|
|
11790
|
+
maxAttempts: currentMaxRetries + 1,
|
|
11791
|
+
actualAttempts,
|
|
11792
|
+
maxTotalAttempts,
|
|
11793
|
+
error: lastError.message
|
|
11649
11794
|
});
|
|
11650
|
-
|
|
11651
|
-
|
|
11652
|
-
|
|
11653
|
-
|
|
11654
|
-
|
|
11655
|
-
policy: "cloud-quota"
|
|
11795
|
+
previousAttemptTracker = attemptTracker;
|
|
11796
|
+
if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
|
|
11797
|
+
logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
|
|
11798
|
+
actualAttempts,
|
|
11799
|
+
maxTotalAttempts
|
|
11656
11800
|
});
|
|
11657
|
-
|
|
11658
|
-
|
|
11659
|
-
|
|
11660
|
-
continue;
|
|
11801
|
+
retryEpisode.finish("exhausted", failedRetryState);
|
|
11802
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
11803
|
+
throw lastError;
|
|
11661
11804
|
}
|
|
11662
|
-
|
|
11663
|
-
|
|
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
|
-
|
|
11805
|
+
if (options.allow_model_fallback !== false) {
|
|
11806
|
+
const policySwitchModelId = tryPolicyModelSwitch(
|
|
11807
|
+
deps,
|
|
11808
|
+
activeModelId,
|
|
11809
|
+
excludedModelIds,
|
|
11810
|
+
requirement,
|
|
11811
|
+
fallbackObserver,
|
|
11812
|
+
lastError,
|
|
11813
|
+
invocationContext?.evaluateFallbackPromptCapacity
|
|
11814
|
+
);
|
|
11815
|
+
if (policySwitchModelId) {
|
|
11816
|
+
fallbackObserver?.onModelFallbackApplied?.({
|
|
11817
|
+
fromModelId: activeModelId,
|
|
11818
|
+
toModelId: policySwitchModelId,
|
|
11819
|
+
reason: lastError.message,
|
|
11820
|
+
policy: "policy-switch"
|
|
11821
|
+
});
|
|
11822
|
+
activeModelId = policySwitchModelId;
|
|
11823
|
+
excludedModelIds.add(policySwitchModelId);
|
|
11824
|
+
attempt -= 1;
|
|
11825
|
+
continue;
|
|
11826
|
+
}
|
|
11827
|
+
const quotaFallbackModelId = tryCloudQuotaFallback({
|
|
11828
|
+
deps,
|
|
11829
|
+
activeModelId,
|
|
11830
|
+
options,
|
|
11831
|
+
excludedModelIds,
|
|
11832
|
+
requirement,
|
|
11833
|
+
error: lastError,
|
|
11834
|
+
fallbackObserver,
|
|
11835
|
+
evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
|
|
11836
|
+
});
|
|
11837
|
+
if (quotaFallbackModelId) {
|
|
11838
|
+
fallbackObserver?.onModelFallbackApplied?.({
|
|
11839
|
+
fromModelId: activeModelId,
|
|
11840
|
+
toModelId: quotaFallbackModelId,
|
|
11841
|
+
reason: lastError.message,
|
|
11842
|
+
policy: "cloud-quota"
|
|
11843
|
+
});
|
|
11844
|
+
activeModelId = quotaFallbackModelId;
|
|
11845
|
+
excludedModelIds.add(quotaFallbackModelId);
|
|
11846
|
+
attempt -= 1;
|
|
11847
|
+
continue;
|
|
11848
|
+
}
|
|
11849
|
+
}
|
|
11850
|
+
if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
|
|
11851
|
+
logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
|
|
11852
|
+
retryEpisode.finish("failed", failedRetryState);
|
|
11853
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
11854
|
+
throw lastError;
|
|
11855
|
+
}
|
|
11856
|
+
if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
|
|
11857
|
+
logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
|
|
11858
|
+
retryEpisode.finish("exhausted", failedRetryState);
|
|
11859
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
11860
|
+
throw lastError;
|
|
11861
|
+
}
|
|
11862
|
+
const retryDelay = ErrorClassifier.calculateRetryDelay(
|
|
11863
|
+
classification,
|
|
11864
|
+
categoryRetries[category],
|
|
11865
|
+
deps.retryConfig.retryDelayMs,
|
|
11866
|
+
6e4
|
|
11867
|
+
);
|
|
11868
|
+
if (classification.category === "rate_limit" /* RATE_LIMIT */) {
|
|
11869
|
+
logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
|
|
11870
|
+
} else if (classification.category === "retryable" /* RETRYABLE */) {
|
|
11871
|
+
logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
|
|
11872
|
+
}
|
|
11873
|
+
throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
|
|
11874
|
+
categoryRetries[category] += 1;
|
|
11875
|
+
retryEpisode.waiting({
|
|
11876
|
+
category,
|
|
11877
|
+
attempt: categoryRetries[category],
|
|
11878
|
+
max_retries: currentMaxRetries,
|
|
11879
|
+
total_attempts: actualAttempts,
|
|
11880
|
+
error_code: classification.errorCode
|
|
11881
|
+
}, retryDelay);
|
|
11882
|
+
if (retryDelay > 0) await waitForRetry(retryDelay, signal);
|
|
11883
|
+
}
|
|
11884
|
+
}
|
|
11885
|
+
throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
|
|
11886
|
+
} catch (error) {
|
|
11887
|
+
retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
|
|
11888
|
+
throw error;
|
|
11689
11889
|
}
|
|
11690
|
-
|
|
11890
|
+
}
|
|
11891
|
+
function waitForRetry(delayMs, signal) {
|
|
11892
|
+
throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
|
|
11893
|
+
return new Promise((resolve, reject) => {
|
|
11894
|
+
const onAbort = () => {
|
|
11895
|
+
clearTimeout(timer);
|
|
11896
|
+
signal?.removeEventListener("abort", onAbort);
|
|
11897
|
+
reject(new DOMException("Request interrupted during retry delay", "AbortError"));
|
|
11898
|
+
};
|
|
11899
|
+
const timer = setTimeout(() => {
|
|
11900
|
+
signal?.removeEventListener("abort", onAbort);
|
|
11901
|
+
resolve();
|
|
11902
|
+
}, delayMs);
|
|
11903
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
11904
|
+
});
|
|
11691
11905
|
}
|
|
11692
11906
|
function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
|
|
11693
11907
|
if (options.retry_policy === "none") return false;
|
|
@@ -11746,9 +11960,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
|
|
|
11746
11960
|
}
|
|
11747
11961
|
};
|
|
11748
11962
|
}
|
|
11749
|
-
function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
|
|
11963
|
+
function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
|
|
11750
11964
|
if (!eventHandler) return;
|
|
11751
|
-
|
|
11965
|
+
const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
|
|
11966
|
+
eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
|
|
11752
11967
|
}
|
|
11753
11968
|
|
|
11754
11969
|
// src/runtime-kernel/llm/caller.ts
|
|
@@ -12470,6 +12685,8 @@ var RuntimeEventSubRunTracePublisher = class {
|
|
|
12470
12685
|
subrun_parent_id: this.subrunParentId,
|
|
12471
12686
|
source_event_id: envelope.source_event_id,
|
|
12472
12687
|
// 载荷透传
|
|
12688
|
+
..."retry" in envelope ? { retry: envelope.retry } : {},
|
|
12689
|
+
..."failure" in envelope ? { failure: envelope.failure } : {},
|
|
12473
12690
|
..."delta" in envelope ? { delta: envelope.delta } : {},
|
|
12474
12691
|
..."content" in envelope ? { content: envelope.content } : {},
|
|
12475
12692
|
..."answer_id" in envelope ? { answer_id: envelope.answer_id } : {},
|
|
@@ -12509,6 +12726,31 @@ var RuntimeEventSubRunTracePublisher = class {
|
|
|
12509
12726
|
// src/runtime-kernel/child-run-trace/projectChildRuntimeEventToSubRunTrace.ts
|
|
12510
12727
|
function projectChildRuntimeEventToSubRunTrace(event) {
|
|
12511
12728
|
switch (event.type) {
|
|
12729
|
+
case "llm_retry":
|
|
12730
|
+
return {
|
|
12731
|
+
kind: "llm_retry",
|
|
12732
|
+
source_event_id: event.id,
|
|
12733
|
+
retry: {
|
|
12734
|
+
retry_id: event.retry_id,
|
|
12735
|
+
status: event.status,
|
|
12736
|
+
category: event.category,
|
|
12737
|
+
attempt: event.attempt,
|
|
12738
|
+
max_retries: event.max_retries,
|
|
12739
|
+
total_attempts: event.total_attempts,
|
|
12740
|
+
started_at: event.started_at,
|
|
12741
|
+
delay_ms: event.delay_ms,
|
|
12742
|
+
next_retry_at: event.next_retry_at,
|
|
12743
|
+
error: event.error,
|
|
12744
|
+
error_code: event.error_code
|
|
12745
|
+
}
|
|
12746
|
+
};
|
|
12747
|
+
case "error":
|
|
12748
|
+
return {
|
|
12749
|
+
kind: "error",
|
|
12750
|
+
source_event_id: event.id,
|
|
12751
|
+
// 父展示只需要安全错误与重试身份,不复制 child 的任意诊断 details。
|
|
12752
|
+
failure: { error: event.error, error_code: event.error_code, retryable: event.retryable, retry_id: event.retry_id }
|
|
12753
|
+
};
|
|
12512
12754
|
case "thought":
|
|
12513
12755
|
return event.is_complete ? {
|
|
12514
12756
|
kind: "thought_complete",
|