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