@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/testkit.cjs
CHANGED
|
@@ -318,11 +318,121 @@ var Logger = class {
|
|
|
318
318
|
}
|
|
319
319
|
}
|
|
320
320
|
};
|
|
321
|
+
var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
|
|
322
|
+
(value) => value === value.trim(),
|
|
323
|
+
"identity must not contain leading or trailing whitespace"
|
|
324
|
+
);
|
|
325
|
+
var RuntimeEventIdSchema = NonEmptyIdentitySchema;
|
|
326
|
+
var AiMessageIdSchema = NonEmptyIdentitySchema;
|
|
327
|
+
var ConversationIdSchema = NonEmptyIdentitySchema;
|
|
328
|
+
var TurnIdSchema = NonEmptyIdentitySchema;
|
|
329
|
+
var RunIdSchema = NonEmptyIdentitySchema.brand();
|
|
330
|
+
var ExecutionIdSchema = NonEmptyIdentitySchema;
|
|
331
|
+
var TraceIdSchema = NonEmptyIdentitySchema;
|
|
332
|
+
var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
|
|
333
|
+
var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
|
|
334
|
+
var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
|
|
335
|
+
var InteractionIdSchema = NonEmptyIdentitySchema;
|
|
336
|
+
var SubrunIdSchema = NonEmptyIdentitySchema;
|
|
337
|
+
var ResumeTokenSchema = NonEmptyIdentitySchema;
|
|
338
|
+
var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
|
|
339
|
+
var SourceEventIdSchema = RuntimeEventIdSchema;
|
|
340
|
+
var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
|
|
341
|
+
var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
|
|
342
|
+
|
|
343
|
+
// src/contracts/identity/generators.ts
|
|
344
|
+
function randomIdentity(prefix) {
|
|
345
|
+
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
346
|
+
throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
|
|
347
|
+
}
|
|
348
|
+
return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
349
|
+
}
|
|
350
|
+
function generateRuntimeEventId() {
|
|
351
|
+
return randomIdentity("evt");
|
|
352
|
+
}
|
|
353
|
+
function generateAnswerSegmentId() {
|
|
354
|
+
return randomIdentity("answer");
|
|
355
|
+
}
|
|
356
|
+
function generateTurnId() {
|
|
357
|
+
return randomIdentity("turn");
|
|
358
|
+
}
|
|
359
|
+
function generateRunId() {
|
|
360
|
+
return RunIdSchema.parse(randomIdentity("run"));
|
|
361
|
+
}
|
|
362
|
+
function generateExecutionId() {
|
|
363
|
+
return randomIdentity("exec");
|
|
364
|
+
}
|
|
365
|
+
function generateTraceId() {
|
|
366
|
+
return randomIdentity("trace");
|
|
367
|
+
}
|
|
368
|
+
function generateInferenceAttemptId() {
|
|
369
|
+
return randomIdentity("inference-attempt");
|
|
370
|
+
}
|
|
371
|
+
function generateThoughtMessageId() {
|
|
372
|
+
return randomIdentity("thought");
|
|
373
|
+
}
|
|
374
|
+
function generateToolCallId() {
|
|
375
|
+
return ToolCallIdSchema.parse(randomIdentity("call"));
|
|
376
|
+
}
|
|
377
|
+
function generateInteractionId() {
|
|
378
|
+
return randomIdentity("interaction");
|
|
379
|
+
}
|
|
380
|
+
function generateResumeToken() {
|
|
381
|
+
return randomIdentity("resume");
|
|
382
|
+
}
|
|
383
|
+
function generateRunResumeClaimId() {
|
|
384
|
+
return randomIdentity("resume-claim");
|
|
385
|
+
}
|
|
386
|
+
function generateAuditEnvelopeId() {
|
|
387
|
+
return randomIdentity("audit");
|
|
388
|
+
}
|
|
389
|
+
function generateContextLedgerEntryId() {
|
|
390
|
+
return randomIdentity("context-ledger");
|
|
391
|
+
}
|
|
392
|
+
function runIdFromTurnId(turnId) {
|
|
393
|
+
return RunIdSchema.parse(turnId);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// src/contracts/identity/invariants.ts
|
|
397
|
+
function assertCanonicalFinalAnswerIdentity(input) {
|
|
398
|
+
const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
|
|
399
|
+
if (input.id !== answerId) {
|
|
400
|
+
throw new Error(
|
|
401
|
+
`final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
return answerId;
|
|
405
|
+
}
|
|
406
|
+
function assertDistinctAnswerChunkIdentity(input) {
|
|
407
|
+
if (input.id === input.answer_id) {
|
|
408
|
+
throw new Error(
|
|
409
|
+
`final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// src/contracts/llm-retry.ts
|
|
415
|
+
var LlmRetryCategory = zod.z.enum(["transport", "output", "rate_limit", "other"]);
|
|
416
|
+
var LlmRetryState = zod.z.object({
|
|
417
|
+
retry_id: TraceIdSchema,
|
|
418
|
+
status: zod.z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
|
|
419
|
+
category: LlmRetryCategory,
|
|
420
|
+
attempt: zod.z.number().int().nonnegative(),
|
|
421
|
+
max_retries: zod.z.number().int().nonnegative(),
|
|
422
|
+
total_attempts: zod.z.number().int().positive(),
|
|
423
|
+
started_at: zod.z.number().finite(),
|
|
424
|
+
delay_ms: zod.z.number().finite().nonnegative(),
|
|
425
|
+
next_retry_at: zod.z.number().finite().optional(),
|
|
426
|
+
/** 安全分类说明;不得放入供应商响应正文。 */
|
|
427
|
+
error: zod.z.string(),
|
|
428
|
+
error_code: zod.z.string().min(1)
|
|
429
|
+
}).strict();
|
|
321
430
|
|
|
322
431
|
// src/shared/errorClassifier.ts
|
|
323
432
|
var ENGINE_ERROR_CODES = {
|
|
324
433
|
LLM_RATE_LIMIT: "llm.rate_limit",
|
|
325
434
|
LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
|
|
435
|
+
LLM_EMPTY_RESPONSE: "llm.empty_response",
|
|
326
436
|
LLM_PROVIDER_DOWN: "llm.provider_down",
|
|
327
437
|
LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
|
|
328
438
|
LLM_AUTH_FAILED: "llm.auth_failed",
|
|
@@ -433,6 +543,8 @@ function readStructuredClassification(error) {
|
|
|
433
543
|
if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
|
|
434
544
|
if (typeof recoverable !== "boolean") return void 0;
|
|
435
545
|
const errorCode = rawErrorCode.trim();
|
|
546
|
+
const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
|
|
547
|
+
const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
|
|
436
548
|
const retryAfterMsValue = error["retryAfterMs"];
|
|
437
549
|
const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
|
|
438
550
|
const hintValue = error["hint"];
|
|
@@ -440,12 +552,13 @@ function readStructuredClassification(error) {
|
|
|
440
552
|
const metadataValue = error["metadata"];
|
|
441
553
|
const metadata = isRecord(metadataValue) ? metadataValue : void 0;
|
|
442
554
|
return createClassification(
|
|
443
|
-
recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
|
|
555
|
+
recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
|
|
444
556
|
`\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
|
|
445
557
|
recoverable ? retryAfterMs ?? 1e3 : null,
|
|
446
558
|
{
|
|
447
559
|
errorCode,
|
|
448
560
|
recoverable,
|
|
561
|
+
...retryCategory === void 0 ? {} : { retryCategory },
|
|
449
562
|
...retryAfterMs === void 0 ? {} : { retryAfterMs },
|
|
450
563
|
...hint === void 0 ? {} : { hint },
|
|
451
564
|
...metadata === void 0 ? {} : { metadata }
|
|
@@ -720,7 +833,7 @@ var ErrorClassifier = class {
|
|
|
720
833
|
if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
|
|
721
834
|
logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
|
|
722
835
|
return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
|
|
723
|
-
errorCode: ENGINE_ERROR_CODES.
|
|
836
|
+
errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
|
|
724
837
|
recoverable: true,
|
|
725
838
|
retryAfterMs: 1e3,
|
|
726
839
|
hint: "retry_with_backoff",
|
|
@@ -745,13 +858,21 @@ var ErrorClassifier = class {
|
|
|
745
858
|
const category = this.categorize(error);
|
|
746
859
|
return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
|
|
747
860
|
}
|
|
861
|
+
static getRetryCategory(classification) {
|
|
862
|
+
if (classification.retryCategory !== void 0) return classification.retryCategory;
|
|
863
|
+
if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
|
|
864
|
+
if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
|
|
865
|
+
if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
|
|
866
|
+
return "other";
|
|
867
|
+
}
|
|
748
868
|
static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
|
|
749
869
|
const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
|
|
750
870
|
if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
|
|
751
871
|
return 0;
|
|
752
872
|
}
|
|
753
|
-
|
|
754
|
-
|
|
873
|
+
const retryCategory = this.getRetryCategory(classification);
|
|
874
|
+
if (retryCategory === "rate_limit" || retryCategory === "transport") {
|
|
875
|
+
return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
|
|
755
876
|
}
|
|
756
877
|
return Math.max(baseDelay, classification.suggestedDelay ?? 0);
|
|
757
878
|
}
|
|
@@ -792,98 +913,6 @@ var RuntimeResourceRef = zod.z.object({
|
|
|
792
913
|
label: LabelSchema.optional()
|
|
793
914
|
}).strict();
|
|
794
915
|
var RuntimeResourceRefs = zod.z.array(RuntimeResourceRef).min(1);
|
|
795
|
-
var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
|
|
796
|
-
(value) => value === value.trim(),
|
|
797
|
-
"identity must not contain leading or trailing whitespace"
|
|
798
|
-
);
|
|
799
|
-
var RuntimeEventIdSchema = NonEmptyIdentitySchema;
|
|
800
|
-
var AiMessageIdSchema = NonEmptyIdentitySchema;
|
|
801
|
-
var ConversationIdSchema = NonEmptyIdentitySchema;
|
|
802
|
-
var TurnIdSchema = NonEmptyIdentitySchema;
|
|
803
|
-
var RunIdSchema = NonEmptyIdentitySchema.brand();
|
|
804
|
-
var ExecutionIdSchema = NonEmptyIdentitySchema;
|
|
805
|
-
var TraceIdSchema = NonEmptyIdentitySchema;
|
|
806
|
-
var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
|
|
807
|
-
var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
|
|
808
|
-
var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
|
|
809
|
-
var InteractionIdSchema = NonEmptyIdentitySchema;
|
|
810
|
-
var SubrunIdSchema = NonEmptyIdentitySchema;
|
|
811
|
-
var ResumeTokenSchema = NonEmptyIdentitySchema;
|
|
812
|
-
var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
|
|
813
|
-
var SourceEventIdSchema = RuntimeEventIdSchema;
|
|
814
|
-
var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
|
|
815
|
-
var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
|
|
816
|
-
|
|
817
|
-
// src/contracts/identity/generators.ts
|
|
818
|
-
function randomIdentity(prefix) {
|
|
819
|
-
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
820
|
-
throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
|
|
821
|
-
}
|
|
822
|
-
return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
823
|
-
}
|
|
824
|
-
function generateRuntimeEventId() {
|
|
825
|
-
return randomIdentity("evt");
|
|
826
|
-
}
|
|
827
|
-
function generateAnswerSegmentId() {
|
|
828
|
-
return randomIdentity("answer");
|
|
829
|
-
}
|
|
830
|
-
function generateTurnId() {
|
|
831
|
-
return randomIdentity("turn");
|
|
832
|
-
}
|
|
833
|
-
function generateRunId() {
|
|
834
|
-
return RunIdSchema.parse(randomIdentity("run"));
|
|
835
|
-
}
|
|
836
|
-
function generateExecutionId() {
|
|
837
|
-
return randomIdentity("exec");
|
|
838
|
-
}
|
|
839
|
-
function generateTraceId() {
|
|
840
|
-
return randomIdentity("trace");
|
|
841
|
-
}
|
|
842
|
-
function generateInferenceAttemptId() {
|
|
843
|
-
return randomIdentity("inference-attempt");
|
|
844
|
-
}
|
|
845
|
-
function generateThoughtMessageId() {
|
|
846
|
-
return randomIdentity("thought");
|
|
847
|
-
}
|
|
848
|
-
function generateToolCallId() {
|
|
849
|
-
return ToolCallIdSchema.parse(randomIdentity("call"));
|
|
850
|
-
}
|
|
851
|
-
function generateInteractionId() {
|
|
852
|
-
return randomIdentity("interaction");
|
|
853
|
-
}
|
|
854
|
-
function generateResumeToken() {
|
|
855
|
-
return randomIdentity("resume");
|
|
856
|
-
}
|
|
857
|
-
function generateRunResumeClaimId() {
|
|
858
|
-
return randomIdentity("resume-claim");
|
|
859
|
-
}
|
|
860
|
-
function generateAuditEnvelopeId() {
|
|
861
|
-
return randomIdentity("audit");
|
|
862
|
-
}
|
|
863
|
-
function generateContextLedgerEntryId() {
|
|
864
|
-
return randomIdentity("context-ledger");
|
|
865
|
-
}
|
|
866
|
-
function runIdFromTurnId(turnId) {
|
|
867
|
-
return RunIdSchema.parse(turnId);
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
// src/contracts/identity/invariants.ts
|
|
871
|
-
function assertCanonicalFinalAnswerIdentity(input) {
|
|
872
|
-
const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
|
|
873
|
-
if (input.id !== answerId) {
|
|
874
|
-
throw new Error(
|
|
875
|
-
`final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
|
|
876
|
-
);
|
|
877
|
-
}
|
|
878
|
-
return answerId;
|
|
879
|
-
}
|
|
880
|
-
function assertDistinctAnswerChunkIdentity(input) {
|
|
881
|
-
if (input.id === input.answer_id) {
|
|
882
|
-
throw new Error(
|
|
883
|
-
`final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
|
|
884
|
-
);
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
916
|
var FinalAnswerCompletionReason = zod.z.enum([
|
|
888
917
|
"terminal",
|
|
889
918
|
"tool_call",
|
|
@@ -1358,6 +1387,13 @@ var AuditEnvelope = zod.z.object({
|
|
|
1358
1387
|
costDelta: AuditCostDelta.optional(),
|
|
1359
1388
|
scope: AuditScope.optional()
|
|
1360
1389
|
});
|
|
1390
|
+
var RuntimeErrorState = zod.z.object({
|
|
1391
|
+
error: zod.z.string(),
|
|
1392
|
+
error_code: zod.z.string().optional(),
|
|
1393
|
+
retryable: zod.z.boolean().optional(),
|
|
1394
|
+
retry_id: TraceIdSchema.optional(),
|
|
1395
|
+
details: SerializableJsonValue.optional()
|
|
1396
|
+
}).strict();
|
|
1361
1397
|
var ToolCallPhase = zod.z.enum(["start", "update", "complete", "error"]);
|
|
1362
1398
|
var Status = zod.z.enum(["loading", "success", "error"]);
|
|
1363
1399
|
var SubRunTraceKind = zod.z.enum([
|
|
@@ -1368,7 +1404,9 @@ var SubRunTraceKind = zod.z.enum([
|
|
|
1368
1404
|
"tool_output",
|
|
1369
1405
|
"final_answer_chunk",
|
|
1370
1406
|
"final_answer",
|
|
1371
|
-
"history_summary"
|
|
1407
|
+
"history_summary",
|
|
1408
|
+
"llm_retry",
|
|
1409
|
+
"error"
|
|
1372
1410
|
]);
|
|
1373
1411
|
var SubRunTraceToolCallDecision = zod.z.object({
|
|
1374
1412
|
tool_call_id: ToolCallIdSchema,
|
|
@@ -1381,6 +1419,8 @@ var SubRunTracePayload = zod.z.object({
|
|
|
1381
1419
|
subrun_parent_id: SubrunIdSchema.optional(),
|
|
1382
1420
|
source_event_id: SourceEventIdSchema,
|
|
1383
1421
|
kind: SubRunTraceKind,
|
|
1422
|
+
retry: LlmRetryState.optional(),
|
|
1423
|
+
failure: RuntimeErrorState.optional(),
|
|
1384
1424
|
delta: zod.z.string().optional(),
|
|
1385
1425
|
content: zod.z.string().optional(),
|
|
1386
1426
|
answer_id: AnswerSegmentIdSchema.optional(),
|
|
@@ -1403,6 +1443,12 @@ var SubRunTracePayload = zod.z.object({
|
|
|
1403
1443
|
meta: SerializableJsonRecord.optional()
|
|
1404
1444
|
});
|
|
1405
1445
|
function validateSubRunTracePayloadSemantics(payload, ctx) {
|
|
1446
|
+
if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
|
|
1447
|
+
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
|
|
1448
|
+
}
|
|
1449
|
+
if (payload.kind === "error" !== (payload.failure !== void 0)) {
|
|
1450
|
+
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
|
|
1451
|
+
}
|
|
1406
1452
|
if (payload.kind === "thought_delta" && payload.delta === void 0) {
|
|
1407
1453
|
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
|
|
1408
1454
|
}
|
|
@@ -1756,12 +1802,10 @@ var RuntimeEventShape = zod.z.discriminatedUnion("type", [
|
|
|
1756
1802
|
compression_ratio: zod.z.number().min(0).max(1).optional(),
|
|
1757
1803
|
included_old_summary: zod.z.boolean().optional()
|
|
1758
1804
|
}),
|
|
1805
|
+
BaseEvent.extend({ type: zod.z.literal("llm_retry"), ...LlmRetryState.shape }),
|
|
1759
1806
|
BaseEvent.extend({
|
|
1760
1807
|
type: zod.z.literal("error"),
|
|
1761
|
-
|
|
1762
|
-
details: SerializableJsonValue.optional(),
|
|
1763
|
-
error_code: zod.z.string().optional(),
|
|
1764
|
-
retryable: zod.z.boolean().optional()
|
|
1808
|
+
...RuntimeErrorState.shape
|
|
1765
1809
|
}),
|
|
1766
1810
|
BaseEvent.extend({
|
|
1767
1811
|
type: zod.z.literal("control"),
|
|
@@ -2196,12 +2240,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
|
|
|
2196
2240
|
resume_token: ResumeTokenSchema,
|
|
2197
2241
|
interaction_status: zod.z.literal("pending")
|
|
2198
2242
|
});
|
|
2243
|
+
var SSELlmRetryEvent = BaseSSEEvent.extend({
|
|
2244
|
+
type: zod.z.literal("llm_retry"),
|
|
2245
|
+
...LlmRetryState.shape
|
|
2246
|
+
});
|
|
2199
2247
|
var SSEErrorEvent = BaseSSEEvent.extend({
|
|
2200
2248
|
type: zod.z.literal("error"),
|
|
2201
|
-
|
|
2202
|
-
details: SerializableJsonValue.optional(),
|
|
2203
|
-
error_code: zod.z.string().optional(),
|
|
2204
|
-
retryable: zod.z.boolean().optional()
|
|
2249
|
+
...RuntimeErrorState.shape
|
|
2205
2250
|
});
|
|
2206
2251
|
var SSETransportErrorEvent = BaseSSEEvent.extend({
|
|
2207
2252
|
type: zod.z.literal("transport_error"),
|
|
@@ -2284,6 +2329,7 @@ zod.z.discriminatedUnion("type", [
|
|
|
2284
2329
|
SSEToolOutputEvent,
|
|
2285
2330
|
SSESubRunTraceEvent,
|
|
2286
2331
|
SSERequiresUserInteractionEvent,
|
|
2332
|
+
SSELlmRetryEvent,
|
|
2287
2333
|
SSEErrorEvent,
|
|
2288
2334
|
SSETransportErrorEvent,
|
|
2289
2335
|
SSEContextUsageSnapshotEvent,
|
|
@@ -6655,6 +6701,8 @@ function getRuntimeEventUiProjectionKind(event) {
|
|
|
6655
6701
|
return "audit_envelope";
|
|
6656
6702
|
case "subrun_trace":
|
|
6657
6703
|
return "subrun_trace";
|
|
6704
|
+
case "llm_retry":
|
|
6705
|
+
return "llm_retry";
|
|
6658
6706
|
case "error":
|
|
6659
6707
|
return "error";
|
|
6660
6708
|
case "context_usage_snapshot":
|
|
@@ -6684,7 +6732,7 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
6684
6732
|
if (isContextUsageSnapshotRuntimeEvent(event)) {
|
|
6685
6733
|
return false;
|
|
6686
6734
|
}
|
|
6687
|
-
if (event.type === "error") {
|
|
6735
|
+
if (event.type === "error" || event.type === "llm_retry") {
|
|
6688
6736
|
return false;
|
|
6689
6737
|
}
|
|
6690
6738
|
if (isRequiresUserInteractionRuntimeEvent(event)) {
|
|
@@ -6727,6 +6775,7 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
6727
6775
|
case "tool_output":
|
|
6728
6776
|
case "requires_user_interaction":
|
|
6729
6777
|
case "subrun_trace":
|
|
6778
|
+
case "llm_retry":
|
|
6730
6779
|
case "error":
|
|
6731
6780
|
case "context_usage_snapshot":
|
|
6732
6781
|
case "run_execution_metrics":
|
|
@@ -6943,8 +6992,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
|
|
|
6943
6992
|
assistant_replay_parts: AssistantReplayParts.optional(),
|
|
6944
6993
|
meta: UnknownRecord.optional()
|
|
6945
6994
|
}).strict();
|
|
6995
|
+
var LlmRetryEventSchema = BaseAgentEvent.extend({
|
|
6996
|
+
type: zod.z.literal("llm_retry"),
|
|
6997
|
+
...LlmRetryState.shape
|
|
6998
|
+
}).strict();
|
|
6946
6999
|
var ErrorEventSchema = BaseAgentEvent.extend({
|
|
6947
7000
|
type: zod.z.literal("error"),
|
|
7001
|
+
retry_id: LlmRetryState.shape.retry_id.optional(),
|
|
6948
7002
|
error: zod.z.string(),
|
|
6949
7003
|
error_code: zod.z.string().optional(),
|
|
6950
7004
|
retryable: zod.z.boolean().optional(),
|
|
@@ -6974,6 +7028,7 @@ var AgentEventSchema = zod.z.discriminatedUnion("type", [
|
|
|
6974
7028
|
ToolProcessEventSchema,
|
|
6975
7029
|
ObservationEventSchema,
|
|
6976
7030
|
FinalAnswerEventSchema,
|
|
7031
|
+
LlmRetryEventSchema,
|
|
6977
7032
|
ErrorEventSchema,
|
|
6978
7033
|
StreamChunkEventSchema,
|
|
6979
7034
|
StreamResetEventSchema,
|
|
@@ -7074,13 +7129,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
|
|
|
7074
7129
|
if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
|
|
7075
7130
|
return event;
|
|
7076
7131
|
}
|
|
7132
|
+
case "llm_retry":
|
|
7133
|
+
return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
|
|
7077
7134
|
case "error": {
|
|
7078
7135
|
const errorEvent = typed;
|
|
7079
7136
|
const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
|
|
7080
7137
|
timestamp,
|
|
7081
7138
|
details: toSerializableJsonValue(errorEvent.details),
|
|
7082
7139
|
error_code: errorEvent.error_code,
|
|
7083
|
-
retryable: errorEvent.retryable
|
|
7140
|
+
retryable: errorEvent.retryable,
|
|
7141
|
+
retry_id: errorEvent.retry_id
|
|
7084
7142
|
});
|
|
7085
7143
|
if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
|
|
7086
7144
|
return event;
|
|
@@ -10049,6 +10107,51 @@ __export(tools_exports, {
|
|
|
10049
10107
|
stripRuntimeReservedToolContextPatch: () => stripRuntimeReservedToolContextPatch
|
|
10050
10108
|
});
|
|
10051
10109
|
|
|
10110
|
+
// src/runtime-kernel/tools/schema/functions/formatUnknownToolArguments.ts
|
|
10111
|
+
function spellingDistance(left, right) {
|
|
10112
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
10113
|
+
for (let row = 1; row <= left.length; row += 1) {
|
|
10114
|
+
const current = [row];
|
|
10115
|
+
for (let column = 1; column <= right.length; column += 1) {
|
|
10116
|
+
current[column] = Math.min(
|
|
10117
|
+
current[column - 1] + 1,
|
|
10118
|
+
previous[column] + 1,
|
|
10119
|
+
previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1)
|
|
10120
|
+
);
|
|
10121
|
+
}
|
|
10122
|
+
previous = current;
|
|
10123
|
+
}
|
|
10124
|
+
return previous[right.length];
|
|
10125
|
+
}
|
|
10126
|
+
function nearestField(field, allowedFields) {
|
|
10127
|
+
const threshold = field.length < 5 ? 1 : 2;
|
|
10128
|
+
let nearest;
|
|
10129
|
+
let bestDistance = threshold + 1;
|
|
10130
|
+
for (const candidate of allowedFields) {
|
|
10131
|
+
if (Math.abs(field.length - candidate.length) > threshold) continue;
|
|
10132
|
+
const distance = spellingDistance(field, candidate);
|
|
10133
|
+
if (distance < bestDistance) {
|
|
10134
|
+
bestDistance = distance;
|
|
10135
|
+
nearest = candidate;
|
|
10136
|
+
} else if (distance === bestDistance) {
|
|
10137
|
+
nearest = void 0;
|
|
10138
|
+
}
|
|
10139
|
+
}
|
|
10140
|
+
return bestDistance <= threshold ? nearest : void 0;
|
|
10141
|
+
}
|
|
10142
|
+
function formatUnknownToolArguments(fields, allowedFields) {
|
|
10143
|
+
const suggestions = fields.flatMap((field) => {
|
|
10144
|
+
const candidate = nearestField(field, allowedFields);
|
|
10145
|
+
return candidate ? [`${JSON.stringify(field)} \u2192 ${JSON.stringify(candidate)}`] : [];
|
|
10146
|
+
});
|
|
10147
|
+
return [
|
|
10148
|
+
`Additional properties not allowed: ${fields.map((field) => JSON.stringify(field)).join(", ")}.`,
|
|
10149
|
+
`Allowed parameters: ${allowedFields.map((field) => JSON.stringify(field)).join(", ") || "(none)"}.`,
|
|
10150
|
+
...suggestions.length > 0 ? [`Possible spelling corrections: ${suggestions.join("; ")}.`] : [],
|
|
10151
|
+
"Remove unsupported parameters before retrying; no arguments were changed or executed."
|
|
10152
|
+
].join(" ");
|
|
10153
|
+
}
|
|
10154
|
+
|
|
10052
10155
|
// src/runtime-kernel/tools/toolContracts.ts
|
|
10053
10156
|
var BaseTool = class {
|
|
10054
10157
|
idempotency;
|
|
@@ -10084,7 +10187,7 @@ var BaseTool = class {
|
|
|
10084
10187
|
if (unknownFields.length > 0) {
|
|
10085
10188
|
return {
|
|
10086
10189
|
success: false,
|
|
10087
|
-
error:
|
|
10190
|
+
error: formatUnknownToolArguments(unknownFields, [...allowed])
|
|
10088
10191
|
};
|
|
10089
10192
|
}
|
|
10090
10193
|
}
|
|
@@ -10551,7 +10654,7 @@ var EventBusEventPersistence = class {
|
|
|
10551
10654
|
if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
|
|
10552
10655
|
return;
|
|
10553
10656
|
}
|
|
10554
|
-
if (this.checkpointWritesActive) {
|
|
10657
|
+
if (this.checkpointWritesActive && event.type !== "llm_retry") {
|
|
10555
10658
|
this.scheduledEventIds.add(event.id);
|
|
10556
10659
|
this.checkpointEvents.push(event);
|
|
10557
10660
|
return;
|
|
@@ -10733,21 +10836,37 @@ function resolveLlmMaxTotalAttempts(config) {
|
|
|
10733
10836
|
function hasLlmAttemptBudgetRemaining(params) {
|
|
10734
10837
|
return params.actualAttempts < params.maxTotalAttempts;
|
|
10735
10838
|
}
|
|
10839
|
+
function validateLlmRetryConfig(config) {
|
|
10840
|
+
if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
|
|
10841
|
+
throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
|
|
10842
|
+
}
|
|
10843
|
+
if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
|
|
10844
|
+
throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
|
|
10845
|
+
}
|
|
10846
|
+
for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
|
|
10847
|
+
if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
|
|
10848
|
+
throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
|
|
10849
|
+
}
|
|
10850
|
+
}
|
|
10851
|
+
}
|
|
10736
10852
|
|
|
10737
10853
|
// src/runtime-kernel/llm/request-builder.ts
|
|
10738
10854
|
function buildLlmCallerDeps(options) {
|
|
10739
10855
|
const modelCatalog = options.modelCatalog;
|
|
10740
10856
|
const maxRetries = options.maxRetries ?? 3;
|
|
10741
|
-
|
|
10742
|
-
|
|
10857
|
+
const retryConfig = {
|
|
10858
|
+
maxRetries,
|
|
10859
|
+
maxRetriesByCategory: options.maxRetriesByCategory,
|
|
10860
|
+
maxTotalAttempts: resolveLlmMaxTotalAttempts({
|
|
10743
10861
|
maxRetries,
|
|
10744
|
-
maxTotalAttempts:
|
|
10745
|
-
|
|
10746
|
-
|
|
10747
|
-
|
|
10748
|
-
|
|
10749
|
-
|
|
10750
|
-
|
|
10862
|
+
maxTotalAttempts: options.maxTotalAttempts
|
|
10863
|
+
}),
|
|
10864
|
+
enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
|
|
10865
|
+
retryDelayMs: options.retryDelayMs ?? 1e3
|
|
10866
|
+
};
|
|
10867
|
+
validateLlmRetryConfig(retryConfig);
|
|
10868
|
+
return {
|
|
10869
|
+
retryConfig,
|
|
10751
10870
|
modelResolver: options.modelResolver ?? new ModelResolver({
|
|
10752
10871
|
fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
|
|
10753
10872
|
modelCatalog
|
|
@@ -11214,6 +11333,7 @@ var logger14 = new Logger("LlmCaller");
|
|
|
11214
11333
|
var CanonicalInferenceFailureError = class extends Error {
|
|
11215
11334
|
errorCode;
|
|
11216
11335
|
recoverable;
|
|
11336
|
+
retryCategory;
|
|
11217
11337
|
metadata;
|
|
11218
11338
|
constructor(failure3, abortReason) {
|
|
11219
11339
|
const message = failure3.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure3.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure3.code}`;
|
|
@@ -11221,6 +11341,7 @@ var CanonicalInferenceFailureError = class extends Error {
|
|
|
11221
11341
|
this.name = failure3.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
|
|
11222
11342
|
this.errorCode = `llm.${failure3.code}`;
|
|
11223
11343
|
this.recoverable = failure3.retryable;
|
|
11344
|
+
this.retryCategory = failure3.retry_category;
|
|
11224
11345
|
this.metadata = { failure_kind: failure3.kind, provider_code: failure3.code };
|
|
11225
11346
|
}
|
|
11226
11347
|
};
|
|
@@ -11456,6 +11577,57 @@ async function callLlmStream(params) {
|
|
|
11456
11577
|
};
|
|
11457
11578
|
}
|
|
11458
11579
|
|
|
11580
|
+
// src/runtime-kernel/llm/functions/llmRetryEpisode.ts
|
|
11581
|
+
var SAFE_RETRY_MESSAGES = {
|
|
11582
|
+
transport: "Network connection interrupted",
|
|
11583
|
+
output: "Model output could not be accepted",
|
|
11584
|
+
rate_limit: "Model request rate limit reached",
|
|
11585
|
+
other: "Model request temporarily failed"
|
|
11586
|
+
};
|
|
11587
|
+
var LlmRetryEpisode = class {
|
|
11588
|
+
constructor(id, emit) {
|
|
11589
|
+
this.id = id;
|
|
11590
|
+
this.emit = emit;
|
|
11591
|
+
}
|
|
11592
|
+
id;
|
|
11593
|
+
emit;
|
|
11594
|
+
state;
|
|
11595
|
+
ended = false;
|
|
11596
|
+
get activeId() {
|
|
11597
|
+
return this.state ? this.id : void 0;
|
|
11598
|
+
}
|
|
11599
|
+
waiting(params, delay) {
|
|
11600
|
+
const now = Date.now();
|
|
11601
|
+
this.state = {
|
|
11602
|
+
...params,
|
|
11603
|
+
retry_id: this.id,
|
|
11604
|
+
status: "waiting",
|
|
11605
|
+
started_at: this.state?.started_at ?? now,
|
|
11606
|
+
delay_ms: delay,
|
|
11607
|
+
next_retry_at: now + delay,
|
|
11608
|
+
error: SAFE_RETRY_MESSAGES[params.category]
|
|
11609
|
+
};
|
|
11610
|
+
this.publish();
|
|
11611
|
+
}
|
|
11612
|
+
retrying(totalAttempts) {
|
|
11613
|
+
if (!this.state || this.ended) return;
|
|
11614
|
+
const { next_retry_at: ignored, ...state } = this.state;
|
|
11615
|
+
this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
|
|
11616
|
+
this.publish();
|
|
11617
|
+
}
|
|
11618
|
+
finish(status, failure3) {
|
|
11619
|
+
if (!this.state || this.ended) return;
|
|
11620
|
+
this.ended = true;
|
|
11621
|
+
const { next_retry_at: ignored, ...state } = this.state;
|
|
11622
|
+
this.state = { ...state, ...failure3, status, delay_ms: 0, ...failure3 ? { error: SAFE_RETRY_MESSAGES[failure3.category] } : {} };
|
|
11623
|
+
this.publish();
|
|
11624
|
+
}
|
|
11625
|
+
publish() {
|
|
11626
|
+
if (!this.state) return;
|
|
11627
|
+
this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
|
|
11628
|
+
}
|
|
11629
|
+
};
|
|
11630
|
+
|
|
11459
11631
|
// src/runtime-kernel/llm/retry-fallback-routing.ts
|
|
11460
11632
|
var logger15 = new Logger("LlmCaller");
|
|
11461
11633
|
function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
|
|
@@ -11708,6 +11880,8 @@ async function callWithRetryFallback(params) {
|
|
|
11708
11880
|
maxTotalAttempts: deps.retryConfig.maxTotalAttempts
|
|
11709
11881
|
});
|
|
11710
11882
|
const traceId = generateTraceId();
|
|
11883
|
+
const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
|
|
11884
|
+
const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
|
|
11711
11885
|
let previousAttemptTracker;
|
|
11712
11886
|
if (!clientRetryEnabled) {
|
|
11713
11887
|
const activeCfg = deps.modelCatalog.getModelById(modelId);
|
|
@@ -11717,167 +11891,207 @@ async function callWithRetryFallback(params) {
|
|
|
11717
11891
|
reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
|
|
11718
11892
|
});
|
|
11719
11893
|
}
|
|
11720
|
-
|
|
11721
|
-
|
|
11722
|
-
|
|
11723
|
-
|
|
11724
|
-
|
|
11725
|
-
previousAttemptTracker = void 0;
|
|
11726
|
-
const resolvedMessages = await runLlmInputPreflight({
|
|
11727
|
-
activeModelId,
|
|
11728
|
-
messages,
|
|
11729
|
-
modelCatalog: deps.modelCatalog,
|
|
11730
|
-
materializer: deps.llmInputMaterializer,
|
|
11731
|
-
invocationContext,
|
|
11732
|
-
eventHandler,
|
|
11733
|
-
requirement
|
|
11734
|
-
});
|
|
11735
|
-
const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
|
|
11736
|
-
const isRetry = attempt > 0;
|
|
11737
|
-
let pendingErrorEvent = null;
|
|
11738
|
-
let streamedErrorClassification;
|
|
11739
|
-
const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
|
|
11740
|
-
pendingErrorEvent = evt;
|
|
11741
|
-
}) : void 0;
|
|
11742
|
-
try {
|
|
11743
|
-
if (isRetry) {
|
|
11744
|
-
logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
|
|
11745
|
-
}
|
|
11746
|
-
actualAttempts++;
|
|
11747
|
-
const llmResponse = attemptTracker ? await callLlmStream({
|
|
11748
|
-
inferencePort: deps.inferencePort,
|
|
11749
|
-
modelId: activeModelId,
|
|
11750
|
-
messages: resolvedMessages,
|
|
11751
|
-
options,
|
|
11752
|
-
eventHandler: attemptTracker.handle,
|
|
11753
|
-
onErrorClassification(classification) {
|
|
11754
|
-
streamedErrorClassification = classification;
|
|
11755
|
-
},
|
|
11756
|
-
signal,
|
|
11757
|
-
toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
|
|
11758
|
-
traceId
|
|
11759
|
-
}) : await callPlainCompletion(
|
|
11760
|
-
deps.inferencePort,
|
|
11761
|
-
activeModelId,
|
|
11762
|
-
resolvedMessages,
|
|
11763
|
-
options,
|
|
11764
|
-
signal,
|
|
11765
|
-
traceId
|
|
11766
|
-
);
|
|
11767
|
-
const responseContent = getLlmResultContent(llmResponse);
|
|
11768
|
-
const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
|
|
11769
|
-
if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
|
|
11770
|
-
throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
11771
|
-
}
|
|
11772
|
-
logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
|
|
11773
|
-
if (attemptContextUsage) {
|
|
11774
|
-
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
|
|
11775
|
-
} else {
|
|
11776
|
-
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
|
|
11894
|
+
try {
|
|
11895
|
+
for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
|
|
11896
|
+
throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
|
|
11897
|
+
if (previousAttemptTracker?.hasEmitted() && eventHandler) {
|
|
11898
|
+
eventHandler(previousAttemptTracker.buildResetEvent());
|
|
11777
11899
|
}
|
|
11778
|
-
|
|
11779
|
-
|
|
11780
|
-
|
|
11781
|
-
|
|
11782
|
-
|
|
11783
|
-
|
|
11784
|
-
|
|
11785
|
-
|
|
11786
|
-
|
|
11787
|
-
});
|
|
11788
|
-
throw lastError;
|
|
11789
|
-
}
|
|
11790
|
-
const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
|
|
11791
|
-
const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
|
|
11792
|
-
logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
|
|
11793
|
-
attempt: attempt + 1,
|
|
11794
|
-
maxAttempts: currentMaxRetries + 1,
|
|
11795
|
-
actualAttempts,
|
|
11796
|
-
maxTotalAttempts,
|
|
11797
|
-
error: lastError.message
|
|
11900
|
+
previousAttemptTracker = void 0;
|
|
11901
|
+
const resolvedMessages = await runLlmInputPreflight({
|
|
11902
|
+
activeModelId,
|
|
11903
|
+
messages,
|
|
11904
|
+
modelCatalog: deps.modelCatalog,
|
|
11905
|
+
materializer: deps.llmInputMaterializer,
|
|
11906
|
+
invocationContext,
|
|
11907
|
+
eventHandler,
|
|
11908
|
+
requirement
|
|
11798
11909
|
});
|
|
11799
|
-
|
|
11800
|
-
|
|
11801
|
-
|
|
11802
|
-
|
|
11803
|
-
|
|
11804
|
-
|
|
11805
|
-
|
|
11806
|
-
|
|
11807
|
-
|
|
11808
|
-
|
|
11809
|
-
|
|
11810
|
-
|
|
11910
|
+
const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
|
|
11911
|
+
const isRetry = attempt > 0;
|
|
11912
|
+
let pendingErrorEvent = null;
|
|
11913
|
+
let streamedErrorClassification;
|
|
11914
|
+
const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
|
|
11915
|
+
pendingErrorEvent = evt;
|
|
11916
|
+
}) : void 0;
|
|
11917
|
+
try {
|
|
11918
|
+
if (isRetry) {
|
|
11919
|
+
logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
|
|
11920
|
+
}
|
|
11921
|
+
actualAttempts++;
|
|
11922
|
+
retryEpisode.retrying(actualAttempts);
|
|
11923
|
+
const llmResponse = attemptTracker ? await callLlmStream({
|
|
11924
|
+
inferencePort: deps.inferencePort,
|
|
11925
|
+
modelId: activeModelId,
|
|
11926
|
+
messages: resolvedMessages,
|
|
11927
|
+
options,
|
|
11928
|
+
eventHandler: attemptTracker.handle,
|
|
11929
|
+
onErrorClassification(classification) {
|
|
11930
|
+
streamedErrorClassification = classification;
|
|
11931
|
+
},
|
|
11932
|
+
signal,
|
|
11933
|
+
toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
|
|
11934
|
+
traceId
|
|
11935
|
+
}) : await callPlainCompletion(
|
|
11936
|
+
deps.inferencePort,
|
|
11811
11937
|
activeModelId,
|
|
11812
|
-
|
|
11813
|
-
|
|
11814
|
-
|
|
11815
|
-
|
|
11816
|
-
invocationContext?.evaluateFallbackPromptCapacity
|
|
11938
|
+
resolvedMessages,
|
|
11939
|
+
options,
|
|
11940
|
+
signal,
|
|
11941
|
+
traceId
|
|
11817
11942
|
);
|
|
11818
|
-
|
|
11819
|
-
|
|
11820
|
-
|
|
11821
|
-
|
|
11822
|
-
|
|
11823
|
-
|
|
11943
|
+
const responseContent = getLlmResultContent(llmResponse);
|
|
11944
|
+
const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
|
|
11945
|
+
if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
|
|
11946
|
+
throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
11947
|
+
}
|
|
11948
|
+
logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
|
|
11949
|
+
if (attemptContextUsage) {
|
|
11950
|
+
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
|
|
11951
|
+
} else {
|
|
11952
|
+
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
|
|
11953
|
+
}
|
|
11954
|
+
retryEpisode.finish("succeeded");
|
|
11955
|
+
return llmResponse;
|
|
11956
|
+
} catch (error) {
|
|
11957
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
11958
|
+
if (lastError.name === "AbortError") {
|
|
11959
|
+
logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
|
|
11960
|
+
attempt: attempt + 1,
|
|
11961
|
+
actualAttempts,
|
|
11962
|
+
maxTotalAttempts,
|
|
11963
|
+
reason: lastError.message
|
|
11824
11964
|
});
|
|
11825
|
-
|
|
11826
|
-
excludedModelIds.add(policySwitchModelId);
|
|
11827
|
-
attempt -= 1;
|
|
11828
|
-
continue;
|
|
11965
|
+
throw lastError;
|
|
11829
11966
|
}
|
|
11830
|
-
const
|
|
11831
|
-
|
|
11832
|
-
|
|
11833
|
-
|
|
11834
|
-
|
|
11835
|
-
|
|
11836
|
-
|
|
11837
|
-
|
|
11838
|
-
|
|
11967
|
+
const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
|
|
11968
|
+
const category = ErrorClassifier.getRetryCategory(classification);
|
|
11969
|
+
const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
|
|
11970
|
+
const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
|
|
11971
|
+
const failedRetryState = {
|
|
11972
|
+
category,
|
|
11973
|
+
attempt: categoryRetries[category],
|
|
11974
|
+
max_retries: currentMaxRetries,
|
|
11975
|
+
total_attempts: actualAttempts,
|
|
11976
|
+
error_code: classification.errorCode
|
|
11977
|
+
};
|
|
11978
|
+
logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
|
|
11979
|
+
attempt: attempt + 1,
|
|
11980
|
+
maxAttempts: currentMaxRetries + 1,
|
|
11981
|
+
actualAttempts,
|
|
11982
|
+
maxTotalAttempts,
|
|
11983
|
+
error: lastError.message
|
|
11839
11984
|
});
|
|
11840
|
-
|
|
11841
|
-
|
|
11842
|
-
|
|
11843
|
-
|
|
11844
|
-
|
|
11845
|
-
policy: "cloud-quota"
|
|
11985
|
+
previousAttemptTracker = attemptTracker;
|
|
11986
|
+
if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
|
|
11987
|
+
logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
|
|
11988
|
+
actualAttempts,
|
|
11989
|
+
maxTotalAttempts
|
|
11846
11990
|
});
|
|
11847
|
-
|
|
11848
|
-
|
|
11849
|
-
|
|
11850
|
-
continue;
|
|
11991
|
+
retryEpisode.finish("exhausted", failedRetryState);
|
|
11992
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
11993
|
+
throw lastError;
|
|
11851
11994
|
}
|
|
11852
|
-
|
|
11853
|
-
|
|
11854
|
-
|
|
11855
|
-
|
|
11856
|
-
|
|
11857
|
-
|
|
11858
|
-
|
|
11859
|
-
|
|
11860
|
-
|
|
11861
|
-
|
|
11862
|
-
|
|
11863
|
-
|
|
11864
|
-
|
|
11865
|
-
|
|
11866
|
-
|
|
11867
|
-
|
|
11868
|
-
|
|
11869
|
-
|
|
11870
|
-
|
|
11871
|
-
|
|
11872
|
-
|
|
11873
|
-
|
|
11874
|
-
|
|
11875
|
-
|
|
11876
|
-
|
|
11995
|
+
if (options.allow_model_fallback !== false) {
|
|
11996
|
+
const policySwitchModelId = tryPolicyModelSwitch(
|
|
11997
|
+
deps,
|
|
11998
|
+
activeModelId,
|
|
11999
|
+
excludedModelIds,
|
|
12000
|
+
requirement,
|
|
12001
|
+
fallbackObserver,
|
|
12002
|
+
lastError,
|
|
12003
|
+
invocationContext?.evaluateFallbackPromptCapacity
|
|
12004
|
+
);
|
|
12005
|
+
if (policySwitchModelId) {
|
|
12006
|
+
fallbackObserver?.onModelFallbackApplied?.({
|
|
12007
|
+
fromModelId: activeModelId,
|
|
12008
|
+
toModelId: policySwitchModelId,
|
|
12009
|
+
reason: lastError.message,
|
|
12010
|
+
policy: "policy-switch"
|
|
12011
|
+
});
|
|
12012
|
+
activeModelId = policySwitchModelId;
|
|
12013
|
+
excludedModelIds.add(policySwitchModelId);
|
|
12014
|
+
attempt -= 1;
|
|
12015
|
+
continue;
|
|
12016
|
+
}
|
|
12017
|
+
const quotaFallbackModelId = tryCloudQuotaFallback({
|
|
12018
|
+
deps,
|
|
12019
|
+
activeModelId,
|
|
12020
|
+
options,
|
|
12021
|
+
excludedModelIds,
|
|
12022
|
+
requirement,
|
|
12023
|
+
error: lastError,
|
|
12024
|
+
fallbackObserver,
|
|
12025
|
+
evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
|
|
12026
|
+
});
|
|
12027
|
+
if (quotaFallbackModelId) {
|
|
12028
|
+
fallbackObserver?.onModelFallbackApplied?.({
|
|
12029
|
+
fromModelId: activeModelId,
|
|
12030
|
+
toModelId: quotaFallbackModelId,
|
|
12031
|
+
reason: lastError.message,
|
|
12032
|
+
policy: "cloud-quota"
|
|
12033
|
+
});
|
|
12034
|
+
activeModelId = quotaFallbackModelId;
|
|
12035
|
+
excludedModelIds.add(quotaFallbackModelId);
|
|
12036
|
+
attempt -= 1;
|
|
12037
|
+
continue;
|
|
12038
|
+
}
|
|
12039
|
+
}
|
|
12040
|
+
if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
|
|
12041
|
+
logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
|
|
12042
|
+
retryEpisode.finish("failed", failedRetryState);
|
|
12043
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
12044
|
+
throw lastError;
|
|
12045
|
+
}
|
|
12046
|
+
if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
|
|
12047
|
+
logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
|
|
12048
|
+
retryEpisode.finish("exhausted", failedRetryState);
|
|
12049
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
12050
|
+
throw lastError;
|
|
12051
|
+
}
|
|
12052
|
+
const retryDelay = ErrorClassifier.calculateRetryDelay(
|
|
12053
|
+
classification,
|
|
12054
|
+
categoryRetries[category],
|
|
12055
|
+
deps.retryConfig.retryDelayMs,
|
|
12056
|
+
6e4
|
|
12057
|
+
);
|
|
12058
|
+
if (classification.category === "rate_limit" /* RATE_LIMIT */) {
|
|
12059
|
+
logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
|
|
12060
|
+
} else if (classification.category === "retryable" /* RETRYABLE */) {
|
|
12061
|
+
logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
|
|
12062
|
+
}
|
|
12063
|
+
throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
|
|
12064
|
+
categoryRetries[category] += 1;
|
|
12065
|
+
retryEpisode.waiting({
|
|
12066
|
+
category,
|
|
12067
|
+
attempt: categoryRetries[category],
|
|
12068
|
+
max_retries: currentMaxRetries,
|
|
12069
|
+
total_attempts: actualAttempts,
|
|
12070
|
+
error_code: classification.errorCode
|
|
12071
|
+
}, retryDelay);
|
|
12072
|
+
if (retryDelay > 0) await waitForRetry(retryDelay, signal);
|
|
11877
12073
|
}
|
|
11878
12074
|
}
|
|
12075
|
+
throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
|
|
12076
|
+
} catch (error) {
|
|
12077
|
+
retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
|
|
12078
|
+
throw error;
|
|
11879
12079
|
}
|
|
11880
|
-
|
|
12080
|
+
}
|
|
12081
|
+
function waitForRetry(delayMs, signal) {
|
|
12082
|
+
throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
|
|
12083
|
+
return new Promise((resolve, reject) => {
|
|
12084
|
+
const onAbort = () => {
|
|
12085
|
+
clearTimeout(timer);
|
|
12086
|
+
signal?.removeEventListener("abort", onAbort);
|
|
12087
|
+
reject(new DOMException("Request interrupted during retry delay", "AbortError"));
|
|
12088
|
+
};
|
|
12089
|
+
const timer = setTimeout(() => {
|
|
12090
|
+
signal?.removeEventListener("abort", onAbort);
|
|
12091
|
+
resolve();
|
|
12092
|
+
}, delayMs);
|
|
12093
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
12094
|
+
});
|
|
11881
12095
|
}
|
|
11882
12096
|
function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
|
|
11883
12097
|
if (options.retry_policy === "none") return false;
|
|
@@ -11936,9 +12150,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
|
|
|
11936
12150
|
}
|
|
11937
12151
|
};
|
|
11938
12152
|
}
|
|
11939
|
-
function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
|
|
12153
|
+
function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
|
|
11940
12154
|
if (!eventHandler) return;
|
|
11941
|
-
|
|
12155
|
+
const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
|
|
12156
|
+
eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
|
|
11942
12157
|
}
|
|
11943
12158
|
|
|
11944
12159
|
// src/runtime-kernel/llm/caller.ts
|
|
@@ -12660,6 +12875,8 @@ var RuntimeEventSubRunTracePublisher = class {
|
|
|
12660
12875
|
subrun_parent_id: this.subrunParentId,
|
|
12661
12876
|
source_event_id: envelope.source_event_id,
|
|
12662
12877
|
// 载荷透传
|
|
12878
|
+
..."retry" in envelope ? { retry: envelope.retry } : {},
|
|
12879
|
+
..."failure" in envelope ? { failure: envelope.failure } : {},
|
|
12663
12880
|
..."delta" in envelope ? { delta: envelope.delta } : {},
|
|
12664
12881
|
..."content" in envelope ? { content: envelope.content } : {},
|
|
12665
12882
|
..."answer_id" in envelope ? { answer_id: envelope.answer_id } : {},
|
|
@@ -12699,6 +12916,31 @@ var RuntimeEventSubRunTracePublisher = class {
|
|
|
12699
12916
|
// src/runtime-kernel/child-run-trace/projectChildRuntimeEventToSubRunTrace.ts
|
|
12700
12917
|
function projectChildRuntimeEventToSubRunTrace(event) {
|
|
12701
12918
|
switch (event.type) {
|
|
12919
|
+
case "llm_retry":
|
|
12920
|
+
return {
|
|
12921
|
+
kind: "llm_retry",
|
|
12922
|
+
source_event_id: event.id,
|
|
12923
|
+
retry: {
|
|
12924
|
+
retry_id: event.retry_id,
|
|
12925
|
+
status: event.status,
|
|
12926
|
+
category: event.category,
|
|
12927
|
+
attempt: event.attempt,
|
|
12928
|
+
max_retries: event.max_retries,
|
|
12929
|
+
total_attempts: event.total_attempts,
|
|
12930
|
+
started_at: event.started_at,
|
|
12931
|
+
delay_ms: event.delay_ms,
|
|
12932
|
+
next_retry_at: event.next_retry_at,
|
|
12933
|
+
error: event.error,
|
|
12934
|
+
error_code: event.error_code
|
|
12935
|
+
}
|
|
12936
|
+
};
|
|
12937
|
+
case "error":
|
|
12938
|
+
return {
|
|
12939
|
+
kind: "error",
|
|
12940
|
+
source_event_id: event.id,
|
|
12941
|
+
// 父展示只需要安全错误与重试身份,不复制 child 的任意诊断 details。
|
|
12942
|
+
failure: { error: event.error, error_code: event.error_code, retryable: event.retryable, retry_id: event.retry_id }
|
|
12943
|
+
};
|
|
12702
12944
|
case "thought":
|
|
12703
12945
|
return event.is_complete ? {
|
|
12704
12946
|
kind: "thought_complete",
|