@linnlabs/linnkit 0.37.4 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/dist/cli.cjs +347 -179
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +347 -179
- package/dist/cli.js.map +1 -1
- package/dist/context-manager.cjs +55 -11
- package/dist/context-manager.cjs.map +1 -1
- package/dist/context-manager.js +55 -11
- package/dist/context-manager.js.map +1 -1
- package/dist/contracts/audit.d.cts +6 -6
- package/dist/contracts/audit.d.ts +6 -6
- package/dist/contracts/events.d.cts +532 -50
- package/dist/contracts/events.d.ts +532 -50
- package/dist/contracts/llm-retry.d.cts +47 -0
- package/dist/contracts/llm-retry.d.ts +47 -0
- package/dist/contracts/messages.d.cts +2 -2
- package/dist/contracts/messages.d.ts +2 -2
- package/dist/contracts/runtime-error.d.cts +26 -0
- package/dist/contracts/runtime-error.d.ts +26 -0
- package/dist/contracts/sse.d.cts +571 -55
- package/dist/contracts/sse.d.ts +571 -55
- package/dist/contracts/sub-run-trace-payload.d.cts +102 -6
- package/dist/contracts/sub-run-trace-payload.d.ts +102 -6
- package/dist/contracts/token-accounting.d.cts +18 -18
- package/dist/contracts/token-accounting.d.ts +18 -18
- package/dist/contracts.cjs +65 -10
- package/dist/contracts.cjs.map +1 -1
- package/dist/contracts.d.cts +4 -2
- package/dist/contracts.d.ts +4 -2
- package/dist/contracts.js +62 -11
- package/dist/contracts.js.map +1 -1
- package/dist/index.cjs +506 -286
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +506 -286
- package/dist/index.js.map +1 -1
- package/dist/ports/canonical-inference.d.cts +3 -0
- package/dist/ports/canonical-inference.d.ts +3 -0
- package/dist/ports/llm-call.d.cts +4 -0
- package/dist/ports/llm-call.d.ts +4 -0
- package/dist/quickstart.cjs +347 -179
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.js +347 -179
- package/dist/quickstart.js.map +1 -1
- package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.cts +8 -0
- package/dist/runtime-kernel/child-run-trace/subrunTrace.types.d.ts +8 -0
- package/dist/runtime-kernel/events/agentEvents.d.cts +85 -4
- package/dist/runtime-kernel/events/agentEvents.d.ts +85 -4
- package/dist/runtime-kernel/events/eventGovernance.d.cts +1 -1
- package/dist/runtime-kernel/events/eventGovernance.d.ts +1 -1
- package/dist/runtime-kernel/events.cjs +55 -11
- package/dist/runtime-kernel/events.cjs.map +1 -1
- package/dist/runtime-kernel/events.js +55 -11
- package/dist/runtime-kernel/events.js.map +1 -1
- package/dist/runtime-kernel/llm/request-builder.d.cts +2 -0
- package/dist/runtime-kernel/llm/request-builder.d.ts +2 -0
- package/dist/runtime-kernel.cjs +468 -271
- package/dist/runtime-kernel.cjs.map +1 -1
- package/dist/runtime-kernel.js +468 -271
- package/dist/runtime-kernel.js.map +1 -1
- package/dist/shared/errorClassifier.d.cts +5 -0
- package/dist/shared/errorClassifier.d.ts +5 -0
- package/dist/testkit.cjs +466 -269
- package/dist/testkit.cjs.map +1 -1
- package/dist/testkit.js +466 -269
- package/dist/testkit.js.map +1 -1
- package/docs/integration/llm-provider.md +24 -0
- package/docs/integration/realtime.md +29 -0
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -265,11 +265,135 @@ var Logger = class {
|
|
|
265
265
|
}
|
|
266
266
|
}
|
|
267
267
|
};
|
|
268
|
+
var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
|
|
269
|
+
(value) => value === value.trim(),
|
|
270
|
+
"identity must not contain leading or trailing whitespace"
|
|
271
|
+
);
|
|
272
|
+
var RuntimeEventIdSchema = NonEmptyIdentitySchema;
|
|
273
|
+
var AiMessageIdSchema = NonEmptyIdentitySchema;
|
|
274
|
+
var ConversationIdSchema = NonEmptyIdentitySchema;
|
|
275
|
+
var TurnIdSchema = NonEmptyIdentitySchema;
|
|
276
|
+
var RunIdSchema = NonEmptyIdentitySchema.brand();
|
|
277
|
+
var ExecutionIdSchema = NonEmptyIdentitySchema;
|
|
278
|
+
var TraceIdSchema = NonEmptyIdentitySchema;
|
|
279
|
+
var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
|
|
280
|
+
var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
|
|
281
|
+
var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
|
|
282
|
+
var InteractionIdSchema = NonEmptyIdentitySchema;
|
|
283
|
+
var SubrunIdSchema = NonEmptyIdentitySchema;
|
|
284
|
+
var ResumeTokenSchema = NonEmptyIdentitySchema;
|
|
285
|
+
var RunResumeClaimIdSchema = NonEmptyIdentitySchema;
|
|
286
|
+
var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
|
|
287
|
+
var ContextLedgerEntryIdSchema = NonEmptyIdentitySchema;
|
|
288
|
+
var SourceEventIdSchema = RuntimeEventIdSchema;
|
|
289
|
+
var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
|
|
290
|
+
var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
|
|
291
|
+
|
|
292
|
+
// src/contracts/identity/generators.ts
|
|
293
|
+
function randomIdentity(prefix) {
|
|
294
|
+
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
295
|
+
throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
|
|
296
|
+
}
|
|
297
|
+
return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
298
|
+
}
|
|
299
|
+
function generateRuntimeEventId() {
|
|
300
|
+
return randomIdentity("evt");
|
|
301
|
+
}
|
|
302
|
+
function generateAiMessageId() {
|
|
303
|
+
return randomIdentity("aimsg");
|
|
304
|
+
}
|
|
305
|
+
function generateAnswerSegmentId() {
|
|
306
|
+
return randomIdentity("answer");
|
|
307
|
+
}
|
|
308
|
+
function generateConversationId() {
|
|
309
|
+
return randomIdentity("conv");
|
|
310
|
+
}
|
|
311
|
+
function generateTurnId() {
|
|
312
|
+
return randomIdentity("turn");
|
|
313
|
+
}
|
|
314
|
+
function generateRunId() {
|
|
315
|
+
return RunIdSchema.parse(randomIdentity("run"));
|
|
316
|
+
}
|
|
317
|
+
function generateExecutionId() {
|
|
318
|
+
return randomIdentity("exec");
|
|
319
|
+
}
|
|
320
|
+
function generateTraceId() {
|
|
321
|
+
return randomIdentity("trace");
|
|
322
|
+
}
|
|
323
|
+
function generateInferenceAttemptId() {
|
|
324
|
+
return randomIdentity("inference-attempt");
|
|
325
|
+
}
|
|
326
|
+
function generateThoughtMessageId() {
|
|
327
|
+
return randomIdentity("thought");
|
|
328
|
+
}
|
|
329
|
+
function generateToolCallId() {
|
|
330
|
+
return ToolCallIdSchema.parse(randomIdentity("call"));
|
|
331
|
+
}
|
|
332
|
+
function generateInteractionId() {
|
|
333
|
+
return randomIdentity("interaction");
|
|
334
|
+
}
|
|
335
|
+
function generateResumeToken() {
|
|
336
|
+
return randomIdentity("resume");
|
|
337
|
+
}
|
|
338
|
+
function generateSubrunId() {
|
|
339
|
+
return randomIdentity("subrun");
|
|
340
|
+
}
|
|
341
|
+
function generateRunResumeClaimId() {
|
|
342
|
+
return randomIdentity("resume-claim");
|
|
343
|
+
}
|
|
344
|
+
function generateAuditEnvelopeId() {
|
|
345
|
+
return randomIdentity("audit");
|
|
346
|
+
}
|
|
347
|
+
function generateContextLedgerEntryId() {
|
|
348
|
+
return randomIdentity("context-ledger");
|
|
349
|
+
}
|
|
350
|
+
function runIdFromTurnId(turnId) {
|
|
351
|
+
return RunIdSchema.parse(turnId);
|
|
352
|
+
}
|
|
353
|
+
function runIdFromSubrunId(subrunId) {
|
|
354
|
+
return RunIdSchema.parse(subrunId);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// src/contracts/identity/invariants.ts
|
|
358
|
+
function assertCanonicalFinalAnswerIdentity(input) {
|
|
359
|
+
const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
|
|
360
|
+
if (input.id !== answerId) {
|
|
361
|
+
throw new Error(
|
|
362
|
+
`final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
return answerId;
|
|
366
|
+
}
|
|
367
|
+
function assertDistinctAnswerChunkIdentity(input) {
|
|
368
|
+
if (input.id === input.answer_id) {
|
|
369
|
+
throw new Error(
|
|
370
|
+
`final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// src/contracts/llm-retry.ts
|
|
376
|
+
var LlmRetryCategory = zod.z.enum(["transport", "output", "rate_limit", "other"]);
|
|
377
|
+
var LlmRetryState = zod.z.object({
|
|
378
|
+
retry_id: TraceIdSchema,
|
|
379
|
+
status: zod.z.enum(["waiting", "retrying", "succeeded", "exhausted", "failed", "cancelled"]),
|
|
380
|
+
category: LlmRetryCategory,
|
|
381
|
+
attempt: zod.z.number().int().nonnegative(),
|
|
382
|
+
max_retries: zod.z.number().int().nonnegative(),
|
|
383
|
+
total_attempts: zod.z.number().int().positive(),
|
|
384
|
+
started_at: zod.z.number().finite(),
|
|
385
|
+
delay_ms: zod.z.number().finite().nonnegative(),
|
|
386
|
+
next_retry_at: zod.z.number().finite().optional(),
|
|
387
|
+
/** 安全分类说明;不得放入供应商响应正文。 */
|
|
388
|
+
error: zod.z.string(),
|
|
389
|
+
error_code: zod.z.string().min(1)
|
|
390
|
+
}).strict();
|
|
268
391
|
|
|
269
392
|
// src/shared/errorClassifier.ts
|
|
270
393
|
var ENGINE_ERROR_CODES = {
|
|
271
394
|
LLM_RATE_LIMIT: "llm.rate_limit",
|
|
272
395
|
LLM_INVALID_TOOL_ARGS: "llm.invalid_tool_args",
|
|
396
|
+
LLM_EMPTY_RESPONSE: "llm.empty_response",
|
|
273
397
|
LLM_PROVIDER_DOWN: "llm.provider_down",
|
|
274
398
|
LLM_UNSUPPORTED_CAPABILITY: "llm.unsupported_capability",
|
|
275
399
|
LLM_AUTH_FAILED: "llm.auth_failed",
|
|
@@ -380,6 +504,8 @@ function readStructuredClassification(error) {
|
|
|
380
504
|
if (typeof rawErrorCode !== "string" || rawErrorCode.trim().length === 0) return void 0;
|
|
381
505
|
if (typeof recoverable !== "boolean") return void 0;
|
|
382
506
|
const errorCode = rawErrorCode.trim();
|
|
507
|
+
const explicitRetryCategory = LlmRetryCategory.safeParse(error["retryCategory"]);
|
|
508
|
+
const retryCategory = explicitRetryCategory.success ? explicitRetryCategory.data : void 0;
|
|
383
509
|
const retryAfterMsValue = error["retryAfterMs"];
|
|
384
510
|
const retryAfterMs = typeof retryAfterMsValue === "number" && Number.isFinite(retryAfterMsValue) && retryAfterMsValue >= 0 ? retryAfterMsValue : void 0;
|
|
385
511
|
const hintValue = error["hint"];
|
|
@@ -387,12 +513,13 @@ function readStructuredClassification(error) {
|
|
|
387
513
|
const metadataValue = error["metadata"];
|
|
388
514
|
const metadata = isRecord(metadataValue) ? metadataValue : void 0;
|
|
389
515
|
return createClassification(
|
|
390
|
-
recoverable ? "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
|
|
516
|
+
recoverable ? retryCategory === "rate_limit" ? "rate_limit" /* RATE_LIMIT */ : "retryable" /* RETRYABLE */ : "non_retryable" /* NON_RETRYABLE */,
|
|
391
517
|
`\u7ED3\u6784\u5316\u9519\u8BEF: ${errorCode}`,
|
|
392
518
|
recoverable ? retryAfterMs ?? 1e3 : null,
|
|
393
519
|
{
|
|
394
520
|
errorCode,
|
|
395
521
|
recoverable,
|
|
522
|
+
...retryCategory === void 0 ? {} : { retryCategory },
|
|
396
523
|
...retryAfterMs === void 0 ? {} : { retryAfterMs },
|
|
397
524
|
...hint === void 0 ? {} : { hint },
|
|
398
525
|
...metadata === void 0 ? {} : { metadata }
|
|
@@ -667,7 +794,7 @@ var ErrorClassifier = class {
|
|
|
667
794
|
if (errorMessage.includes("\u7A7A\u54CD\u5E94") || errorMessage.includes("empty response")) {
|
|
668
795
|
logClassification(context, "\u68C0\u6D4B\u5230\u7A7A\u54CD\u5E94\u9519\u8BEF\uFF0C\u53EF\u4EE5\u91CD\u8BD5");
|
|
669
796
|
return createClassification("retryable" /* RETRYABLE */, "\u7A7A\u54CD\u5E94\u9519\u8BEF", 1e3, {
|
|
670
|
-
errorCode: ENGINE_ERROR_CODES.
|
|
797
|
+
errorCode: ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE,
|
|
671
798
|
recoverable: true,
|
|
672
799
|
retryAfterMs: 1e3,
|
|
673
800
|
hint: "retry_with_backoff",
|
|
@@ -692,15 +819,23 @@ var ErrorClassifier = class {
|
|
|
692
819
|
const category = this.categorize(error);
|
|
693
820
|
return category === "retryable" /* RETRYABLE */ || category === "rate_limit" /* RATE_LIMIT */;
|
|
694
821
|
}
|
|
822
|
+
static getRetryCategory(classification) {
|
|
823
|
+
if (classification.retryCategory !== void 0) return classification.retryCategory;
|
|
824
|
+
if (classification.errorCode === ENGINE_ERROR_CODES.LLM_INVALID_TOOL_ARGS || classification.errorCode === ENGINE_ERROR_CODES.LLM_EMPTY_RESPONSE) return "output";
|
|
825
|
+
if (classification.category === "rate_limit" /* RATE_LIMIT */ || classification.errorCode === ENGINE_ERROR_CODES.LLM_RATE_LIMIT) return "rate_limit";
|
|
826
|
+
if (classification.metadata?.failure_kind === "transport" || classification.errorCode === ENGINE_ERROR_CODES.LLM_PROVIDER_DOWN) return "transport";
|
|
827
|
+
return "other";
|
|
828
|
+
}
|
|
695
829
|
static calculateRetryDelay(errorOrClassification, attemptNumber, baseDelay = 1e3, maxDelay = 6e4) {
|
|
696
830
|
const classification = errorOrClassification instanceof Error ? this.classify(errorOrClassification) : errorOrClassification;
|
|
697
831
|
if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
|
|
698
832
|
return 0;
|
|
699
833
|
}
|
|
700
|
-
|
|
701
|
-
|
|
834
|
+
const retryCategory = this.getRetryCategory(classification);
|
|
835
|
+
if (retryCategory === "rate_limit" || retryCategory === "transport") {
|
|
836
|
+
return Math.max(Math.min(baseDelay * Math.pow(2, attemptNumber), maxDelay), classification.suggestedDelay ?? 0);
|
|
702
837
|
}
|
|
703
|
-
return classification.suggestedDelay
|
|
838
|
+
return Math.max(baseDelay, classification.suggestedDelay ?? 0);
|
|
704
839
|
}
|
|
705
840
|
static isCloudQuotaError(error) {
|
|
706
841
|
const msg = (error.message || "").toLowerCase();
|
|
@@ -774,6 +909,8 @@ __export(contracts_exports, {
|
|
|
774
909
|
HistoryMessageReferenceIdSchema: () => HistoryMessageReferenceIdSchema,
|
|
775
910
|
HistorySummaryMeta: () => HistorySummaryMeta,
|
|
776
911
|
InteractionIdSchema: () => InteractionIdSchema,
|
|
912
|
+
LlmRetryCategory: () => LlmRetryCategory,
|
|
913
|
+
LlmRetryState: () => LlmRetryState,
|
|
777
914
|
LlmUsageTokenLedgerEntry: () => LlmUsageTokenLedgerEntry,
|
|
778
915
|
ObservationTruncationMeta: () => ObservationTruncationMeta,
|
|
779
916
|
PersistentMetadata: () => PersistentMetadata,
|
|
@@ -787,6 +924,7 @@ __export(contracts_exports, {
|
|
|
787
924
|
RunIdSchema: () => RunIdSchema,
|
|
788
925
|
RunResumeClaimIdSchema: () => RunResumeClaimIdSchema,
|
|
789
926
|
RunTokenUsageAggregate: () => RunTokenUsageAggregate,
|
|
927
|
+
RuntimeErrorState: () => RuntimeErrorState,
|
|
790
928
|
RuntimeEvent: () => RuntimeEvent,
|
|
791
929
|
RuntimeEventIdSchema: () => RuntimeEventIdSchema,
|
|
792
930
|
RuntimeEventRoutingIdentity: () => RuntimeEventRoutingIdentity,
|
|
@@ -803,6 +941,7 @@ __export(contracts_exports, {
|
|
|
803
941
|
SSEFinalAnswerEvent: () => SSEFinalAnswerEvent,
|
|
804
942
|
SSEFinalAnswerResetEvent: () => SSEFinalAnswerResetEvent,
|
|
805
943
|
SSEHistorySummaryEvent: () => SSEHistorySummaryEvent,
|
|
944
|
+
SSELlmRetryEvent: () => SSELlmRetryEvent,
|
|
806
945
|
SSEMarkdownChunkEvent: () => SSEMarkdownChunkEvent,
|
|
807
946
|
SSERequiresUserInteractionEvent: () => SSERequiresUserInteractionEvent,
|
|
808
947
|
SSERunExecutionMetricsEvent: () => SSERunExecutionMetricsEvent,
|
|
@@ -959,112 +1098,6 @@ var RuntimeResourceRef = zod.z.object({
|
|
|
959
1098
|
label: LabelSchema.optional()
|
|
960
1099
|
}).strict();
|
|
961
1100
|
var RuntimeResourceRefs = zod.z.array(RuntimeResourceRef).min(1);
|
|
962
|
-
var NonEmptyIdentitySchema = zod.z.string().min(1).refine(
|
|
963
|
-
(value) => value === value.trim(),
|
|
964
|
-
"identity must not contain leading or trailing whitespace"
|
|
965
|
-
);
|
|
966
|
-
var RuntimeEventIdSchema = NonEmptyIdentitySchema;
|
|
967
|
-
var AiMessageIdSchema = NonEmptyIdentitySchema;
|
|
968
|
-
var ConversationIdSchema = NonEmptyIdentitySchema;
|
|
969
|
-
var TurnIdSchema = NonEmptyIdentitySchema;
|
|
970
|
-
var RunIdSchema = NonEmptyIdentitySchema.brand();
|
|
971
|
-
var ExecutionIdSchema = NonEmptyIdentitySchema;
|
|
972
|
-
var TraceIdSchema = NonEmptyIdentitySchema;
|
|
973
|
-
var AnswerSegmentIdSchema = NonEmptyIdentitySchema;
|
|
974
|
-
var ThoughtMessageIdSchema = NonEmptyIdentitySchema;
|
|
975
|
-
var ToolCallIdSchema = NonEmptyIdentitySchema.brand();
|
|
976
|
-
var InteractionIdSchema = NonEmptyIdentitySchema;
|
|
977
|
-
var SubrunIdSchema = NonEmptyIdentitySchema;
|
|
978
|
-
var ResumeTokenSchema = NonEmptyIdentitySchema;
|
|
979
|
-
var RunResumeClaimIdSchema = NonEmptyIdentitySchema;
|
|
980
|
-
var AuditEnvelopeIdSchema = NonEmptyIdentitySchema;
|
|
981
|
-
var ContextLedgerEntryIdSchema = NonEmptyIdentitySchema;
|
|
982
|
-
var SourceEventIdSchema = RuntimeEventIdSchema;
|
|
983
|
-
var HistoryMessageReferenceIdSchema = AiMessageIdSchema;
|
|
984
|
-
var ControlTargetReferenceIdSchema = NonEmptyIdentitySchema;
|
|
985
|
-
|
|
986
|
-
// src/contracts/identity/generators.ts
|
|
987
|
-
function randomIdentity(prefix) {
|
|
988
|
-
if (typeof globalThis.crypto?.randomUUID !== "function") {
|
|
989
|
-
throw new Error("Runtime identity generation requires globalThis.crypto.randomUUID.");
|
|
990
|
-
}
|
|
991
|
-
return `${prefix}-${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
992
|
-
}
|
|
993
|
-
function generateRuntimeEventId() {
|
|
994
|
-
return randomIdentity("evt");
|
|
995
|
-
}
|
|
996
|
-
function generateAiMessageId() {
|
|
997
|
-
return randomIdentity("aimsg");
|
|
998
|
-
}
|
|
999
|
-
function generateAnswerSegmentId() {
|
|
1000
|
-
return randomIdentity("answer");
|
|
1001
|
-
}
|
|
1002
|
-
function generateConversationId() {
|
|
1003
|
-
return randomIdentity("conv");
|
|
1004
|
-
}
|
|
1005
|
-
function generateTurnId() {
|
|
1006
|
-
return randomIdentity("turn");
|
|
1007
|
-
}
|
|
1008
|
-
function generateRunId() {
|
|
1009
|
-
return RunIdSchema.parse(randomIdentity("run"));
|
|
1010
|
-
}
|
|
1011
|
-
function generateExecutionId() {
|
|
1012
|
-
return randomIdentity("exec");
|
|
1013
|
-
}
|
|
1014
|
-
function generateTraceId() {
|
|
1015
|
-
return randomIdentity("trace");
|
|
1016
|
-
}
|
|
1017
|
-
function generateInferenceAttemptId() {
|
|
1018
|
-
return randomIdentity("inference-attempt");
|
|
1019
|
-
}
|
|
1020
|
-
function generateThoughtMessageId() {
|
|
1021
|
-
return randomIdentity("thought");
|
|
1022
|
-
}
|
|
1023
|
-
function generateToolCallId() {
|
|
1024
|
-
return ToolCallIdSchema.parse(randomIdentity("call"));
|
|
1025
|
-
}
|
|
1026
|
-
function generateInteractionId() {
|
|
1027
|
-
return randomIdentity("interaction");
|
|
1028
|
-
}
|
|
1029
|
-
function generateResumeToken() {
|
|
1030
|
-
return randomIdentity("resume");
|
|
1031
|
-
}
|
|
1032
|
-
function generateSubrunId() {
|
|
1033
|
-
return randomIdentity("subrun");
|
|
1034
|
-
}
|
|
1035
|
-
function generateRunResumeClaimId() {
|
|
1036
|
-
return randomIdentity("resume-claim");
|
|
1037
|
-
}
|
|
1038
|
-
function generateAuditEnvelopeId() {
|
|
1039
|
-
return randomIdentity("audit");
|
|
1040
|
-
}
|
|
1041
|
-
function generateContextLedgerEntryId() {
|
|
1042
|
-
return randomIdentity("context-ledger");
|
|
1043
|
-
}
|
|
1044
|
-
function runIdFromTurnId(turnId) {
|
|
1045
|
-
return RunIdSchema.parse(turnId);
|
|
1046
|
-
}
|
|
1047
|
-
function runIdFromSubrunId(subrunId) {
|
|
1048
|
-
return RunIdSchema.parse(subrunId);
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
// src/contracts/identity/invariants.ts
|
|
1052
|
-
function assertCanonicalFinalAnswerIdentity(input) {
|
|
1053
|
-
const answerId = AnswerSegmentIdSchema.parse(input.answer_id);
|
|
1054
|
-
if (input.id !== answerId) {
|
|
1055
|
-
throw new Error(
|
|
1056
|
-
`final_answer identity mismatch: event.id=${input.id}, answer_id=${answerId}`
|
|
1057
|
-
);
|
|
1058
|
-
}
|
|
1059
|
-
return answerId;
|
|
1060
|
-
}
|
|
1061
|
-
function assertDistinctAnswerChunkIdentity(input) {
|
|
1062
|
-
if (input.id === input.answer_id) {
|
|
1063
|
-
throw new Error(
|
|
1064
|
-
`final_answer_chunk identity collision: event.id must differ from answer_id=${input.answer_id}`
|
|
1065
|
-
);
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
1101
|
var FinalAnswerCompletionReason = zod.z.enum([
|
|
1069
1102
|
"terminal",
|
|
1070
1103
|
"tool_call",
|
|
@@ -1752,6 +1785,13 @@ var AuditEnvelope = zod.z.object({
|
|
|
1752
1785
|
costDelta: AuditCostDelta.optional(),
|
|
1753
1786
|
scope: AuditScope.optional()
|
|
1754
1787
|
});
|
|
1788
|
+
var RuntimeErrorState = zod.z.object({
|
|
1789
|
+
error: zod.z.string(),
|
|
1790
|
+
error_code: zod.z.string().optional(),
|
|
1791
|
+
retryable: zod.z.boolean().optional(),
|
|
1792
|
+
retry_id: TraceIdSchema.optional(),
|
|
1793
|
+
details: SerializableJsonValue.optional()
|
|
1794
|
+
}).strict();
|
|
1755
1795
|
var ToolCallPhase = zod.z.enum(["start", "update", "complete", "error"]);
|
|
1756
1796
|
var Status = zod.z.enum(["loading", "success", "error"]);
|
|
1757
1797
|
var SubRunTraceKind = zod.z.enum([
|
|
@@ -1762,7 +1802,9 @@ var SubRunTraceKind = zod.z.enum([
|
|
|
1762
1802
|
"tool_output",
|
|
1763
1803
|
"final_answer_chunk",
|
|
1764
1804
|
"final_answer",
|
|
1765
|
-
"history_summary"
|
|
1805
|
+
"history_summary",
|
|
1806
|
+
"llm_retry",
|
|
1807
|
+
"error"
|
|
1766
1808
|
]);
|
|
1767
1809
|
var SubRunTraceToolCallDecision = zod.z.object({
|
|
1768
1810
|
tool_call_id: ToolCallIdSchema,
|
|
@@ -1775,6 +1817,8 @@ var SubRunTracePayload = zod.z.object({
|
|
|
1775
1817
|
subrun_parent_id: SubrunIdSchema.optional(),
|
|
1776
1818
|
source_event_id: SourceEventIdSchema,
|
|
1777
1819
|
kind: SubRunTraceKind,
|
|
1820
|
+
retry: LlmRetryState.optional(),
|
|
1821
|
+
failure: RuntimeErrorState.optional(),
|
|
1778
1822
|
delta: zod.z.string().optional(),
|
|
1779
1823
|
content: zod.z.string().optional(),
|
|
1780
1824
|
answer_id: AnswerSegmentIdSchema.optional(),
|
|
@@ -1797,6 +1841,12 @@ var SubRunTracePayload = zod.z.object({
|
|
|
1797
1841
|
meta: SerializableJsonRecord.optional()
|
|
1798
1842
|
});
|
|
1799
1843
|
function validateSubRunTracePayloadSemantics(payload, ctx) {
|
|
1844
|
+
if (payload.kind === "llm_retry" !== (payload.retry !== void 0)) {
|
|
1845
|
+
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["retry"], message: "retry is required only for llm_retry trace" });
|
|
1846
|
+
}
|
|
1847
|
+
if (payload.kind === "error" !== (payload.failure !== void 0)) {
|
|
1848
|
+
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["failure"], message: "failure is required only for error trace" });
|
|
1849
|
+
}
|
|
1800
1850
|
if (payload.kind === "thought_delta" && payload.delta === void 0) {
|
|
1801
1851
|
ctx.addIssue({ code: zod.z.ZodIssueCode.custom, path: ["delta"], message: "thought_delta requires delta" });
|
|
1802
1852
|
}
|
|
@@ -2150,12 +2200,10 @@ var RuntimeEventShape = zod.z.discriminatedUnion("type", [
|
|
|
2150
2200
|
compression_ratio: zod.z.number().min(0).max(1).optional(),
|
|
2151
2201
|
included_old_summary: zod.z.boolean().optional()
|
|
2152
2202
|
}),
|
|
2203
|
+
BaseEvent.extend({ type: zod.z.literal("llm_retry"), ...LlmRetryState.shape }),
|
|
2153
2204
|
BaseEvent.extend({
|
|
2154
2205
|
type: zod.z.literal("error"),
|
|
2155
|
-
|
|
2156
|
-
details: SerializableJsonValue.optional(),
|
|
2157
|
-
error_code: zod.z.string().optional(),
|
|
2158
|
-
retryable: zod.z.boolean().optional()
|
|
2206
|
+
...RuntimeErrorState.shape
|
|
2159
2207
|
}),
|
|
2160
2208
|
BaseEvent.extend({
|
|
2161
2209
|
type: zod.z.literal("control"),
|
|
@@ -2621,12 +2669,13 @@ var SSERequiresUserInteractionEvent = BaseSSEEvent.extend({
|
|
|
2621
2669
|
resume_token: ResumeTokenSchema,
|
|
2622
2670
|
interaction_status: zod.z.literal("pending")
|
|
2623
2671
|
});
|
|
2672
|
+
var SSELlmRetryEvent = BaseSSEEvent.extend({
|
|
2673
|
+
type: zod.z.literal("llm_retry"),
|
|
2674
|
+
...LlmRetryState.shape
|
|
2675
|
+
});
|
|
2624
2676
|
var SSEErrorEvent = BaseSSEEvent.extend({
|
|
2625
2677
|
type: zod.z.literal("error"),
|
|
2626
|
-
|
|
2627
|
-
details: SerializableJsonValue.optional(),
|
|
2628
|
-
error_code: zod.z.string().optional(),
|
|
2629
|
-
retryable: zod.z.boolean().optional()
|
|
2678
|
+
...RuntimeErrorState.shape
|
|
2630
2679
|
});
|
|
2631
2680
|
var SSETransportErrorEvent = BaseSSEEvent.extend({
|
|
2632
2681
|
type: zod.z.literal("transport_error"),
|
|
@@ -2709,6 +2758,7 @@ var SSEEvent = zod.z.discriminatedUnion("type", [
|
|
|
2709
2758
|
SSEToolOutputEvent,
|
|
2710
2759
|
SSESubRunTraceEvent,
|
|
2711
2760
|
SSERequiresUserInteractionEvent,
|
|
2761
|
+
SSELlmRetryEvent,
|
|
2712
2762
|
SSEErrorEvent,
|
|
2713
2763
|
SSETransportErrorEvent,
|
|
2714
2764
|
SSEContextUsageSnapshotEvent,
|
|
@@ -2828,6 +2878,8 @@ function runtimeEventToSSEEvent(event) {
|
|
|
2828
2878
|
subrun_parent_id: event.subrun_parent_id,
|
|
2829
2879
|
source_event_id: event.source_event_id,
|
|
2830
2880
|
kind: event.kind,
|
|
2881
|
+
retry: event.retry,
|
|
2882
|
+
failure: event.failure,
|
|
2831
2883
|
delta: event.delta,
|
|
2832
2884
|
content: event.content,
|
|
2833
2885
|
answer_id: event.answer_id,
|
|
@@ -2900,6 +2952,22 @@ function runtimeEventToSSEEvent(event) {
|
|
|
2900
2952
|
compression_ratio: event.compression_ratio,
|
|
2901
2953
|
included_old_summary: event.included_old_summary
|
|
2902
2954
|
};
|
|
2955
|
+
case "llm_retry":
|
|
2956
|
+
return {
|
|
2957
|
+
...base,
|
|
2958
|
+
type: "llm_retry",
|
|
2959
|
+
retry_id: event.retry_id,
|
|
2960
|
+
status: event.status,
|
|
2961
|
+
category: event.category,
|
|
2962
|
+
attempt: event.attempt,
|
|
2963
|
+
max_retries: event.max_retries,
|
|
2964
|
+
total_attempts: event.total_attempts,
|
|
2965
|
+
started_at: event.started_at,
|
|
2966
|
+
delay_ms: event.delay_ms,
|
|
2967
|
+
next_retry_at: event.next_retry_at,
|
|
2968
|
+
error: event.error,
|
|
2969
|
+
error_code: event.error_code
|
|
2970
|
+
};
|
|
2903
2971
|
case "error":
|
|
2904
2972
|
return {
|
|
2905
2973
|
...base,
|
|
@@ -2907,7 +2975,8 @@ function runtimeEventToSSEEvent(event) {
|
|
|
2907
2975
|
error: event.error,
|
|
2908
2976
|
details: event.details,
|
|
2909
2977
|
error_code: event.error_code,
|
|
2910
|
-
retryable: event.retryable
|
|
2978
|
+
retryable: event.retryable,
|
|
2979
|
+
retry_id: event.retry_id
|
|
2911
2980
|
};
|
|
2912
2981
|
case "context_usage_snapshot":
|
|
2913
2982
|
return {
|
|
@@ -7467,6 +7536,8 @@ function getRuntimeEventUiProjectionKind(event) {
|
|
|
7467
7536
|
return "audit_envelope";
|
|
7468
7537
|
case "subrun_trace":
|
|
7469
7538
|
return "subrun_trace";
|
|
7539
|
+
case "llm_retry":
|
|
7540
|
+
return "llm_retry";
|
|
7470
7541
|
case "error":
|
|
7471
7542
|
return "error";
|
|
7472
7543
|
case "context_usage_snapshot":
|
|
@@ -7496,7 +7567,7 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
7496
7567
|
if (isContextUsageSnapshotRuntimeEvent(event)) {
|
|
7497
7568
|
return false;
|
|
7498
7569
|
}
|
|
7499
|
-
if (event.type === "error") {
|
|
7570
|
+
if (event.type === "error" || event.type === "llm_retry") {
|
|
7500
7571
|
return false;
|
|
7501
7572
|
}
|
|
7502
7573
|
if (isRequiresUserInteractionRuntimeEvent(event)) {
|
|
@@ -7539,6 +7610,7 @@ function describeRuntimeEventLifecycle(event) {
|
|
|
7539
7610
|
case "tool_output":
|
|
7540
7611
|
case "requires_user_interaction":
|
|
7541
7612
|
case "subrun_trace":
|
|
7613
|
+
case "llm_retry":
|
|
7542
7614
|
case "error":
|
|
7543
7615
|
case "context_usage_snapshot":
|
|
7544
7616
|
case "run_execution_metrics":
|
|
@@ -7755,8 +7827,13 @@ var FinalAnswerEventSchema = BaseAgentEvent.extend({
|
|
|
7755
7827
|
assistant_replay_parts: AssistantReplayParts.optional(),
|
|
7756
7828
|
meta: UnknownRecord.optional()
|
|
7757
7829
|
}).strict();
|
|
7830
|
+
var LlmRetryEventSchema = BaseAgentEvent.extend({
|
|
7831
|
+
type: zod.z.literal("llm_retry"),
|
|
7832
|
+
...LlmRetryState.shape
|
|
7833
|
+
}).strict();
|
|
7758
7834
|
var ErrorEventSchema = BaseAgentEvent.extend({
|
|
7759
7835
|
type: zod.z.literal("error"),
|
|
7836
|
+
retry_id: LlmRetryState.shape.retry_id.optional(),
|
|
7760
7837
|
error: zod.z.string(),
|
|
7761
7838
|
error_code: zod.z.string().optional(),
|
|
7762
7839
|
retryable: zod.z.boolean().optional(),
|
|
@@ -7786,6 +7863,7 @@ var AgentEventSchema = zod.z.discriminatedUnion("type", [
|
|
|
7786
7863
|
ToolProcessEventSchema,
|
|
7787
7864
|
ObservationEventSchema,
|
|
7788
7865
|
FinalAnswerEventSchema,
|
|
7866
|
+
LlmRetryEventSchema,
|
|
7789
7867
|
ErrorEventSchema,
|
|
7790
7868
|
StreamChunkEventSchema,
|
|
7791
7869
|
StreamResetEventSchema,
|
|
@@ -7886,13 +7964,16 @@ function mapAgentEventToRuntime(agentEvent, context, options) {
|
|
|
7886
7964
|
if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
|
|
7887
7965
|
return event;
|
|
7888
7966
|
}
|
|
7967
|
+
case "llm_retry":
|
|
7968
|
+
return { ...typed, conversation_id: conversationId, turn_id: turnId, version: 1, ephemeral: false, ...contextMeta ? { metadata: contextMeta } : {} };
|
|
7889
7969
|
case "error": {
|
|
7890
7970
|
const errorEvent = typed;
|
|
7891
7971
|
const event = createErrorEvent(id, conversationId, turnId, errorEvent.error, {
|
|
7892
7972
|
timestamp,
|
|
7893
7973
|
details: toSerializableJsonValue(errorEvent.details),
|
|
7894
7974
|
error_code: errorEvent.error_code,
|
|
7895
|
-
retryable: errorEvent.retryable
|
|
7975
|
+
retryable: errorEvent.retryable,
|
|
7976
|
+
retry_id: errorEvent.retry_id
|
|
7896
7977
|
});
|
|
7897
7978
|
if (contextMeta) event.metadata = { ...event.metadata ?? {}, ...contextMeta };
|
|
7898
7979
|
return event;
|
|
@@ -11370,7 +11451,7 @@ var EventBusEventPersistence = class {
|
|
|
11370
11451
|
if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
|
|
11371
11452
|
return;
|
|
11372
11453
|
}
|
|
11373
|
-
if (this.checkpointWritesActive) {
|
|
11454
|
+
if (this.checkpointWritesActive && event.type !== "llm_retry") {
|
|
11374
11455
|
this.scheduledEventIds.add(event.id);
|
|
11375
11456
|
this.checkpointEvents.push(event);
|
|
11376
11457
|
return;
|
|
@@ -11552,21 +11633,37 @@ function resolveLlmMaxTotalAttempts(config) {
|
|
|
11552
11633
|
function hasLlmAttemptBudgetRemaining(params) {
|
|
11553
11634
|
return params.actualAttempts < params.maxTotalAttempts;
|
|
11554
11635
|
}
|
|
11636
|
+
function validateLlmRetryConfig(config) {
|
|
11637
|
+
if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0) {
|
|
11638
|
+
throw new Error("[LlmCaller] maxRetries must be a non-negative integer.");
|
|
11639
|
+
}
|
|
11640
|
+
if (!Number.isFinite(config.retryDelayMs) || config.retryDelayMs < 0) {
|
|
11641
|
+
throw new Error("[LlmCaller] retryDelayMs must be finite and non-negative.");
|
|
11642
|
+
}
|
|
11643
|
+
for (const [category, limit] of Object.entries(config.maxRetriesByCategory ?? {})) {
|
|
11644
|
+
if (limit !== void 0 && (!Number.isInteger(limit) || limit < 0 || limit > config.maxRetries)) {
|
|
11645
|
+
throw new Error(`[LlmCaller] maxRetriesByCategory.${category} must be an integer between 0 and maxRetries.`);
|
|
11646
|
+
}
|
|
11647
|
+
}
|
|
11648
|
+
}
|
|
11555
11649
|
|
|
11556
11650
|
// src/runtime-kernel/llm/request-builder.ts
|
|
11557
11651
|
function buildLlmCallerDeps(options) {
|
|
11558
11652
|
const modelCatalog = options.modelCatalog;
|
|
11559
11653
|
const maxRetries = options.maxRetries ?? 3;
|
|
11560
|
-
|
|
11561
|
-
|
|
11654
|
+
const retryConfig = {
|
|
11655
|
+
maxRetries,
|
|
11656
|
+
maxRetriesByCategory: options.maxRetriesByCategory,
|
|
11657
|
+
maxTotalAttempts: resolveLlmMaxTotalAttempts({
|
|
11562
11658
|
maxRetries,
|
|
11563
|
-
maxTotalAttempts:
|
|
11564
|
-
|
|
11565
|
-
|
|
11566
|
-
|
|
11567
|
-
|
|
11568
|
-
|
|
11569
|
-
|
|
11659
|
+
maxTotalAttempts: options.maxTotalAttempts
|
|
11660
|
+
}),
|
|
11661
|
+
enableEmptyResponseRetry: options.enableEmptyResponseRetry ?? true,
|
|
11662
|
+
retryDelayMs: options.retryDelayMs ?? 1e3
|
|
11663
|
+
};
|
|
11664
|
+
validateLlmRetryConfig(retryConfig);
|
|
11665
|
+
return {
|
|
11666
|
+
retryConfig,
|
|
11570
11667
|
modelResolver: options.modelResolver ?? new ModelResolver({
|
|
11571
11668
|
fallbackModelPreferredOrder: options.fallbackModelPreferredOrder,
|
|
11572
11669
|
modelCatalog
|
|
@@ -12033,6 +12130,7 @@ var logger14 = new Logger("LlmCaller");
|
|
|
12033
12130
|
var CanonicalInferenceFailureError = class extends Error {
|
|
12034
12131
|
errorCode;
|
|
12035
12132
|
recoverable;
|
|
12133
|
+
retryCategory;
|
|
12036
12134
|
metadata;
|
|
12037
12135
|
constructor(failure, abortReason) {
|
|
12038
12136
|
const message = failure.kind === "aborted" && typeof abortReason === "string" ? abortReason : failure.kind === "aborted" && abortReason instanceof Error ? abortReason.message : `Canonical inference failed: ${failure.code}`;
|
|
@@ -12040,6 +12138,7 @@ var CanonicalInferenceFailureError = class extends Error {
|
|
|
12040
12138
|
this.name = failure.kind === "aborted" ? "AbortError" : "CanonicalInferenceFailureError";
|
|
12041
12139
|
this.errorCode = `llm.${failure.code}`;
|
|
12042
12140
|
this.recoverable = failure.retryable;
|
|
12141
|
+
this.retryCategory = failure.retry_category;
|
|
12043
12142
|
this.metadata = { failure_kind: failure.kind, provider_code: failure.code };
|
|
12044
12143
|
}
|
|
12045
12144
|
};
|
|
@@ -12275,6 +12374,57 @@ async function callLlmStream(params) {
|
|
|
12275
12374
|
};
|
|
12276
12375
|
}
|
|
12277
12376
|
|
|
12377
|
+
// src/runtime-kernel/llm/functions/llmRetryEpisode.ts
|
|
12378
|
+
var SAFE_RETRY_MESSAGES = {
|
|
12379
|
+
transport: "Network connection interrupted",
|
|
12380
|
+
output: "Model output could not be accepted",
|
|
12381
|
+
rate_limit: "Model request rate limit reached",
|
|
12382
|
+
other: "Model request temporarily failed"
|
|
12383
|
+
};
|
|
12384
|
+
var LlmRetryEpisode = class {
|
|
12385
|
+
constructor(id, emit) {
|
|
12386
|
+
this.id = id;
|
|
12387
|
+
this.emit = emit;
|
|
12388
|
+
}
|
|
12389
|
+
id;
|
|
12390
|
+
emit;
|
|
12391
|
+
state;
|
|
12392
|
+
ended = false;
|
|
12393
|
+
get activeId() {
|
|
12394
|
+
return this.state ? this.id : void 0;
|
|
12395
|
+
}
|
|
12396
|
+
waiting(params, delay) {
|
|
12397
|
+
const now = Date.now();
|
|
12398
|
+
this.state = {
|
|
12399
|
+
...params,
|
|
12400
|
+
retry_id: this.id,
|
|
12401
|
+
status: "waiting",
|
|
12402
|
+
started_at: this.state?.started_at ?? now,
|
|
12403
|
+
delay_ms: delay,
|
|
12404
|
+
next_retry_at: now + delay,
|
|
12405
|
+
error: SAFE_RETRY_MESSAGES[params.category]
|
|
12406
|
+
};
|
|
12407
|
+
this.publish();
|
|
12408
|
+
}
|
|
12409
|
+
retrying(totalAttempts) {
|
|
12410
|
+
if (!this.state || this.ended) return;
|
|
12411
|
+
const { next_retry_at: ignored, ...state } = this.state;
|
|
12412
|
+
this.state = { ...state, status: "retrying", total_attempts: totalAttempts, delay_ms: 0 };
|
|
12413
|
+
this.publish();
|
|
12414
|
+
}
|
|
12415
|
+
finish(status, failure) {
|
|
12416
|
+
if (!this.state || this.ended) return;
|
|
12417
|
+
this.ended = true;
|
|
12418
|
+
const { next_retry_at: ignored, ...state } = this.state;
|
|
12419
|
+
this.state = { ...state, ...failure, status, delay_ms: 0, ...failure ? { error: SAFE_RETRY_MESSAGES[failure.category] } : {} };
|
|
12420
|
+
this.publish();
|
|
12421
|
+
}
|
|
12422
|
+
publish() {
|
|
12423
|
+
if (!this.state) return;
|
|
12424
|
+
this.emit?.({ type: "llm_retry", id: generateRuntimeEventId(), timestamp: Date.now(), ...this.state });
|
|
12425
|
+
}
|
|
12426
|
+
};
|
|
12427
|
+
|
|
12278
12428
|
// src/runtime-kernel/llm/retry-fallback-routing.ts
|
|
12279
12429
|
var logger15 = new Logger("LlmCaller");
|
|
12280
12430
|
function tryPolicyModelSwitch(deps, activeModelId, excludedModelIds, requirement, fallbackObserver, error, evaluateFallbackPromptCapacity2) {
|
|
@@ -12527,6 +12677,8 @@ async function callWithRetryFallback(params) {
|
|
|
12527
12677
|
maxTotalAttempts: deps.retryConfig.maxTotalAttempts
|
|
12528
12678
|
});
|
|
12529
12679
|
const traceId = generateTraceId();
|
|
12680
|
+
const categoryRetries = { transport: 0, output: 0, rate_limit: 0, other: 0 };
|
|
12681
|
+
const retryEpisode = new LlmRetryEpisode(traceId, eventHandler);
|
|
12530
12682
|
let previousAttemptTracker;
|
|
12531
12683
|
if (!clientRetryEnabled) {
|
|
12532
12684
|
const activeCfg = deps.modelCatalog.getModelById(modelId);
|
|
@@ -12536,167 +12688,207 @@ async function callWithRetryFallback(params) {
|
|
|
12536
12688
|
reason: options.retry_policy === "none" ? "options.retry_policy=none" : "model config (cloud billing or enable_client_retry=false)"
|
|
12537
12689
|
});
|
|
12538
12690
|
}
|
|
12539
|
-
|
|
12540
|
-
|
|
12541
|
-
|
|
12542
|
-
|
|
12543
|
-
|
|
12544
|
-
previousAttemptTracker = void 0;
|
|
12545
|
-
const resolvedMessages = await runLlmInputPreflight({
|
|
12546
|
-
activeModelId,
|
|
12547
|
-
messages,
|
|
12548
|
-
modelCatalog: deps.modelCatalog,
|
|
12549
|
-
materializer: deps.llmInputMaterializer,
|
|
12550
|
-
invocationContext,
|
|
12551
|
-
eventHandler,
|
|
12552
|
-
requirement
|
|
12553
|
-
});
|
|
12554
|
-
const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
|
|
12555
|
-
const isRetry = attempt > 0;
|
|
12556
|
-
let pendingErrorEvent = null;
|
|
12557
|
-
let streamedErrorClassification;
|
|
12558
|
-
const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
|
|
12559
|
-
pendingErrorEvent = evt;
|
|
12560
|
-
}) : void 0;
|
|
12561
|
-
try {
|
|
12562
|
-
if (isRetry) {
|
|
12563
|
-
logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
|
|
12564
|
-
}
|
|
12565
|
-
actualAttempts++;
|
|
12566
|
-
const llmResponse = attemptTracker ? await callLlmStream({
|
|
12567
|
-
inferencePort: deps.inferencePort,
|
|
12568
|
-
modelId: activeModelId,
|
|
12569
|
-
messages: resolvedMessages,
|
|
12570
|
-
options,
|
|
12571
|
-
eventHandler: attemptTracker.handle,
|
|
12572
|
-
onErrorClassification(classification) {
|
|
12573
|
-
streamedErrorClassification = classification;
|
|
12574
|
-
},
|
|
12575
|
-
signal,
|
|
12576
|
-
toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
|
|
12577
|
-
traceId
|
|
12578
|
-
}) : await callPlainCompletion(
|
|
12579
|
-
deps.inferencePort,
|
|
12580
|
-
activeModelId,
|
|
12581
|
-
resolvedMessages,
|
|
12582
|
-
options,
|
|
12583
|
-
signal,
|
|
12584
|
-
traceId
|
|
12585
|
-
);
|
|
12586
|
-
const responseContent = getLlmResultContent(llmResponse);
|
|
12587
|
-
const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
|
|
12588
|
-
if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
|
|
12589
|
-
throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
12590
|
-
}
|
|
12591
|
-
logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
|
|
12592
|
-
if (attemptContextUsage) {
|
|
12593
|
-
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
|
|
12594
|
-
} else {
|
|
12595
|
-
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
|
|
12691
|
+
try {
|
|
12692
|
+
for (let attempt = 0; attempt <= configuredMaxRetries; attempt++) {
|
|
12693
|
+
throwIfAborted(signal, "\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62AI\u6D3B\u52A8");
|
|
12694
|
+
if (previousAttemptTracker?.hasEmitted() && eventHandler) {
|
|
12695
|
+
eventHandler(previousAttemptTracker.buildResetEvent());
|
|
12596
12696
|
}
|
|
12597
|
-
|
|
12598
|
-
|
|
12599
|
-
|
|
12600
|
-
|
|
12601
|
-
|
|
12602
|
-
|
|
12603
|
-
|
|
12604
|
-
|
|
12605
|
-
|
|
12606
|
-
});
|
|
12607
|
-
throw lastError;
|
|
12608
|
-
}
|
|
12609
|
-
const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
|
|
12610
|
-
const currentMaxRetries = clientRetryEnabled ? configuredMaxRetries : 0;
|
|
12611
|
-
logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
|
|
12612
|
-
attempt: attempt + 1,
|
|
12613
|
-
maxAttempts: currentMaxRetries + 1,
|
|
12614
|
-
actualAttempts,
|
|
12615
|
-
maxTotalAttempts,
|
|
12616
|
-
error: lastError.message
|
|
12697
|
+
previousAttemptTracker = void 0;
|
|
12698
|
+
const resolvedMessages = await runLlmInputPreflight({
|
|
12699
|
+
activeModelId,
|
|
12700
|
+
messages,
|
|
12701
|
+
modelCatalog: deps.modelCatalog,
|
|
12702
|
+
materializer: deps.llmInputMaterializer,
|
|
12703
|
+
invocationContext,
|
|
12704
|
+
eventHandler,
|
|
12705
|
+
requirement
|
|
12617
12706
|
});
|
|
12618
|
-
|
|
12619
|
-
|
|
12620
|
-
|
|
12621
|
-
|
|
12622
|
-
|
|
12623
|
-
|
|
12624
|
-
|
|
12625
|
-
|
|
12626
|
-
|
|
12627
|
-
|
|
12628
|
-
|
|
12629
|
-
|
|
12707
|
+
const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
|
|
12708
|
+
const isRetry = attempt > 0;
|
|
12709
|
+
let pendingErrorEvent = null;
|
|
12710
|
+
let streamedErrorClassification;
|
|
12711
|
+
const attemptTracker = eventHandler ? createLiveAttemptStreamTracker(eventHandler, (evt) => {
|
|
12712
|
+
pendingErrorEvent = evt;
|
|
12713
|
+
}) : void 0;
|
|
12714
|
+
try {
|
|
12715
|
+
if (isRetry) {
|
|
12716
|
+
logger16.info("LLM \u8C03\u7528\u91CD\u8BD5", { attempt, configuredMaxRetries });
|
|
12717
|
+
}
|
|
12718
|
+
actualAttempts++;
|
|
12719
|
+
retryEpisode.retrying(actualAttempts);
|
|
12720
|
+
const llmResponse = attemptTracker ? await callLlmStream({
|
|
12721
|
+
inferencePort: deps.inferencePort,
|
|
12722
|
+
modelId: activeModelId,
|
|
12723
|
+
messages: resolvedMessages,
|
|
12724
|
+
options,
|
|
12725
|
+
eventHandler: attemptTracker.handle,
|
|
12726
|
+
onErrorClassification(classification) {
|
|
12727
|
+
streamedErrorClassification = classification;
|
|
12728
|
+
},
|
|
12729
|
+
signal,
|
|
12730
|
+
toolCallStreamingPolicies: invocationContext?.toolCallStreamingPolicies,
|
|
12731
|
+
traceId
|
|
12732
|
+
}) : await callPlainCompletion(
|
|
12733
|
+
deps.inferencePort,
|
|
12630
12734
|
activeModelId,
|
|
12631
|
-
|
|
12632
|
-
|
|
12633
|
-
|
|
12634
|
-
|
|
12635
|
-
invocationContext?.evaluateFallbackPromptCapacity
|
|
12735
|
+
resolvedMessages,
|
|
12736
|
+
options,
|
|
12737
|
+
signal,
|
|
12738
|
+
traceId
|
|
12636
12739
|
);
|
|
12637
|
-
|
|
12638
|
-
|
|
12639
|
-
|
|
12640
|
-
|
|
12641
|
-
|
|
12642
|
-
|
|
12740
|
+
const responseContent = getLlmResultContent(llmResponse);
|
|
12741
|
+
const toolCallsFromLLM = getLlmResultToolCalls(llmResponse);
|
|
12742
|
+
if (deps.retryConfig.enableEmptyResponseRetry && !responseContent?.trim() && !toolCallsFromLLM?.length) {
|
|
12743
|
+
throw new Error("LLM\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
12744
|
+
}
|
|
12745
|
+
logger16.debug("LLM \u8C03\u7528\u6210\u529F", { attempts: actualAttempts, maxTotalAttempts });
|
|
12746
|
+
if (attemptContextUsage) {
|
|
12747
|
+
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId, attemptContextUsage);
|
|
12748
|
+
} else {
|
|
12749
|
+
fallbackObserver?.onLlmAttemptSucceeded?.(activeModelId);
|
|
12750
|
+
}
|
|
12751
|
+
retryEpisode.finish("succeeded");
|
|
12752
|
+
return llmResponse;
|
|
12753
|
+
} catch (error) {
|
|
12754
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
12755
|
+
if (lastError.name === "AbortError") {
|
|
12756
|
+
logger16.info("LLM \u8C03\u7528\u5DF2\u53D6\u6D88\uFF0C\u4E0D\u8FDB\u5165 provider failure \u5206\u7C7B\u4E0E\u91CD\u8BD5\u6D41\u7A0B", {
|
|
12757
|
+
attempt: attempt + 1,
|
|
12758
|
+
actualAttempts,
|
|
12759
|
+
maxTotalAttempts,
|
|
12760
|
+
reason: lastError.message
|
|
12643
12761
|
});
|
|
12644
|
-
|
|
12645
|
-
excludedModelIds.add(policySwitchModelId);
|
|
12646
|
-
attempt -= 1;
|
|
12647
|
-
continue;
|
|
12762
|
+
throw lastError;
|
|
12648
12763
|
}
|
|
12649
|
-
const
|
|
12650
|
-
|
|
12651
|
-
|
|
12652
|
-
|
|
12653
|
-
|
|
12654
|
-
|
|
12655
|
-
|
|
12656
|
-
|
|
12657
|
-
|
|
12764
|
+
const classification = streamedErrorClassification ?? ErrorClassifier.classify(lastError, { logPrefix: "[LlmCaller]" });
|
|
12765
|
+
const category = ErrorClassifier.getRetryCategory(classification);
|
|
12766
|
+
const categoryLimit = deps.retryConfig.maxRetriesByCategory?.[category] ?? configuredMaxRetries;
|
|
12767
|
+
const currentMaxRetries = clientRetryEnabled ? categoryLimit : 0;
|
|
12768
|
+
const failedRetryState = {
|
|
12769
|
+
category,
|
|
12770
|
+
attempt: categoryRetries[category],
|
|
12771
|
+
max_retries: currentMaxRetries,
|
|
12772
|
+
total_attempts: actualAttempts,
|
|
12773
|
+
error_code: classification.errorCode
|
|
12774
|
+
};
|
|
12775
|
+
logger16.error("LLM \u8C03\u7528\u5931\u8D25", {
|
|
12776
|
+
attempt: attempt + 1,
|
|
12777
|
+
maxAttempts: currentMaxRetries + 1,
|
|
12778
|
+
actualAttempts,
|
|
12779
|
+
maxTotalAttempts,
|
|
12780
|
+
error: lastError.message
|
|
12658
12781
|
});
|
|
12659
|
-
|
|
12660
|
-
|
|
12661
|
-
|
|
12662
|
-
|
|
12663
|
-
|
|
12664
|
-
policy: "cloud-quota"
|
|
12782
|
+
previousAttemptTracker = attemptTracker;
|
|
12783
|
+
if (!hasLlmAttemptBudgetRemaining({ actualAttempts, maxTotalAttempts })) {
|
|
12784
|
+
logger16.error("\u5DF2\u8FBE\u5230 LLM \u603B\u8C03\u7528\u6B21\u6570\u4E0A\u9650\uFF0C\u505C\u6B62\u91CD\u8BD5/\u5207\u6A21\u578B", {
|
|
12785
|
+
actualAttempts,
|
|
12786
|
+
maxTotalAttempts
|
|
12665
12787
|
});
|
|
12666
|
-
|
|
12667
|
-
|
|
12668
|
-
|
|
12669
|
-
continue;
|
|
12788
|
+
retryEpisode.finish("exhausted", failedRetryState);
|
|
12789
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
12790
|
+
throw lastError;
|
|
12670
12791
|
}
|
|
12671
|
-
|
|
12672
|
-
|
|
12673
|
-
|
|
12674
|
-
|
|
12675
|
-
|
|
12676
|
-
|
|
12677
|
-
|
|
12678
|
-
|
|
12679
|
-
|
|
12680
|
-
|
|
12681
|
-
|
|
12682
|
-
|
|
12683
|
-
|
|
12684
|
-
|
|
12685
|
-
|
|
12686
|
-
|
|
12687
|
-
|
|
12688
|
-
|
|
12689
|
-
|
|
12690
|
-
|
|
12691
|
-
|
|
12692
|
-
|
|
12693
|
-
|
|
12694
|
-
|
|
12695
|
-
|
|
12696
|
-
|
|
12697
|
-
|
|
12792
|
+
if (options.allow_model_fallback !== false) {
|
|
12793
|
+
const policySwitchModelId = tryPolicyModelSwitch(
|
|
12794
|
+
deps,
|
|
12795
|
+
activeModelId,
|
|
12796
|
+
excludedModelIds,
|
|
12797
|
+
requirement,
|
|
12798
|
+
fallbackObserver,
|
|
12799
|
+
lastError,
|
|
12800
|
+
invocationContext?.evaluateFallbackPromptCapacity
|
|
12801
|
+
);
|
|
12802
|
+
if (policySwitchModelId) {
|
|
12803
|
+
fallbackObserver?.onModelFallbackApplied?.({
|
|
12804
|
+
fromModelId: activeModelId,
|
|
12805
|
+
toModelId: policySwitchModelId,
|
|
12806
|
+
reason: lastError.message,
|
|
12807
|
+
policy: "policy-switch"
|
|
12808
|
+
});
|
|
12809
|
+
activeModelId = policySwitchModelId;
|
|
12810
|
+
excludedModelIds.add(policySwitchModelId);
|
|
12811
|
+
attempt -= 1;
|
|
12812
|
+
continue;
|
|
12813
|
+
}
|
|
12814
|
+
const quotaFallbackModelId = tryCloudQuotaFallback({
|
|
12815
|
+
deps,
|
|
12816
|
+
activeModelId,
|
|
12817
|
+
options,
|
|
12818
|
+
excludedModelIds,
|
|
12819
|
+
requirement,
|
|
12820
|
+
error: lastError,
|
|
12821
|
+
fallbackObserver,
|
|
12822
|
+
evaluateFallbackPromptCapacity: invocationContext?.evaluateFallbackPromptCapacity
|
|
12823
|
+
});
|
|
12824
|
+
if (quotaFallbackModelId) {
|
|
12825
|
+
fallbackObserver?.onModelFallbackApplied?.({
|
|
12826
|
+
fromModelId: activeModelId,
|
|
12827
|
+
toModelId: quotaFallbackModelId,
|
|
12828
|
+
reason: lastError.message,
|
|
12829
|
+
policy: "cloud-quota"
|
|
12830
|
+
});
|
|
12831
|
+
activeModelId = quotaFallbackModelId;
|
|
12832
|
+
excludedModelIds.add(quotaFallbackModelId);
|
|
12833
|
+
attempt -= 1;
|
|
12834
|
+
continue;
|
|
12835
|
+
}
|
|
12836
|
+
}
|
|
12837
|
+
if (classification.category === "non_retryable" /* NON_RETRYABLE */) {
|
|
12838
|
+
logger16.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\uFF0C\u76F4\u63A5\u5931\u8D25", { reason: classification.reason });
|
|
12839
|
+
retryEpisode.finish("failed", failedRetryState);
|
|
12840
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
12841
|
+
throw lastError;
|
|
12842
|
+
}
|
|
12843
|
+
if (attempt >= configuredMaxRetries || categoryRetries[category] >= currentMaxRetries) {
|
|
12844
|
+
logger16.error("\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u653E\u5F03\u91CD\u8BD5", { maxRetries: currentMaxRetries });
|
|
12845
|
+
retryEpisode.finish("exhausted", failedRetryState);
|
|
12846
|
+
emitFinalError(eventHandler, pendingErrorEvent, lastError, classification, retryEpisode.activeId);
|
|
12847
|
+
throw lastError;
|
|
12848
|
+
}
|
|
12849
|
+
const retryDelay = ErrorClassifier.calculateRetryDelay(
|
|
12850
|
+
classification,
|
|
12851
|
+
categoryRetries[category],
|
|
12852
|
+
deps.retryConfig.retryDelayMs,
|
|
12853
|
+
6e4
|
|
12854
|
+
);
|
|
12855
|
+
if (classification.category === "rate_limit" /* RATE_LIMIT */) {
|
|
12856
|
+
logger16.warn("\u901F\u7387\u9650\u5236\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
|
|
12857
|
+
} else if (classification.category === "retryable" /* RETRYABLE */) {
|
|
12858
|
+
logger16.warn("\u53EF\u91CD\u8BD5\u9519\u8BEF\uFF0C\u5EF6\u8FDF\u540E\u91CD\u8BD5", { retryDelay, reason: classification.reason });
|
|
12859
|
+
}
|
|
12860
|
+
throwIfAborted(signal, "\u5EF6\u8FDF\u7B49\u5F85\u524D\u68C0\u6D4B\u5230\u53D6\u6D88\u4FE1\u53F7\uFF0C\u505C\u6B62\u91CD\u8BD5");
|
|
12861
|
+
categoryRetries[category] += 1;
|
|
12862
|
+
retryEpisode.waiting({
|
|
12863
|
+
category,
|
|
12864
|
+
attempt: categoryRetries[category],
|
|
12865
|
+
max_retries: currentMaxRetries,
|
|
12866
|
+
total_attempts: actualAttempts,
|
|
12867
|
+
error_code: classification.errorCode
|
|
12868
|
+
}, retryDelay);
|
|
12869
|
+
if (retryDelay > 0) await waitForRetry(retryDelay, signal);
|
|
12870
|
+
}
|
|
12871
|
+
}
|
|
12872
|
+
throw lastError || new Error("LLM\u8C03\u7528\u5728\u6240\u6709\u91CD\u8BD5\u540E\u90FD\u5931\u8D25\u4E86");
|
|
12873
|
+
} catch (error) {
|
|
12874
|
+
retryEpisode.finish(error instanceof Error && error.name === "AbortError" ? "cancelled" : "failed");
|
|
12875
|
+
throw error;
|
|
12698
12876
|
}
|
|
12699
|
-
|
|
12877
|
+
}
|
|
12878
|
+
function waitForRetry(delayMs, signal) {
|
|
12879
|
+
throwIfAborted(signal, "\u7B49\u5F85\u91CD\u8BD5\u524D\u5DF2\u53D6\u6D88");
|
|
12880
|
+
return new Promise((resolve, reject) => {
|
|
12881
|
+
const onAbort = () => {
|
|
12882
|
+
clearTimeout(timer);
|
|
12883
|
+
signal?.removeEventListener("abort", onAbort);
|
|
12884
|
+
reject(new DOMException("Request interrupted during retry delay", "AbortError"));
|
|
12885
|
+
};
|
|
12886
|
+
const timer = setTimeout(() => {
|
|
12887
|
+
signal?.removeEventListener("abort", onAbort);
|
|
12888
|
+
resolve();
|
|
12889
|
+
}, delayMs);
|
|
12890
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
12891
|
+
});
|
|
12700
12892
|
}
|
|
12701
12893
|
function isClientRetryEnabledForModel(modelCatalog, modelId, options) {
|
|
12702
12894
|
if (options.retry_policy === "none") return false;
|
|
@@ -12755,9 +12947,10 @@ function createLiveAttemptStreamTracker(eventHandler, setPendingErrorEvent) {
|
|
|
12755
12947
|
}
|
|
12756
12948
|
};
|
|
12757
12949
|
}
|
|
12758
|
-
function emitFinalError(eventHandler, pendingErrorEvent, error, classification) {
|
|
12950
|
+
function emitFinalError(eventHandler, pendingErrorEvent, error, classification, retryId) {
|
|
12759
12951
|
if (!eventHandler) return;
|
|
12760
|
-
|
|
12952
|
+
const event = pendingErrorEvent ?? createLlmAgentErrorEvent(error, classification);
|
|
12953
|
+
eventHandler(retryId === void 0 ? event : { ...event, retry_id: retryId });
|
|
12761
12954
|
}
|
|
12762
12955
|
|
|
12763
12956
|
// src/runtime-kernel/llm/caller.ts
|
|
@@ -13479,6 +13672,8 @@ var RuntimeEventSubRunTracePublisher = class {
|
|
|
13479
13672
|
subrun_parent_id: this.subrunParentId,
|
|
13480
13673
|
source_event_id: envelope.source_event_id,
|
|
13481
13674
|
// 载荷透传
|
|
13675
|
+
..."retry" in envelope ? { retry: envelope.retry } : {},
|
|
13676
|
+
..."failure" in envelope ? { failure: envelope.failure } : {},
|
|
13482
13677
|
..."delta" in envelope ? { delta: envelope.delta } : {},
|
|
13483
13678
|
..."content" in envelope ? { content: envelope.content } : {},
|
|
13484
13679
|
..."answer_id" in envelope ? { answer_id: envelope.answer_id } : {},
|
|
@@ -13518,6 +13713,31 @@ var RuntimeEventSubRunTracePublisher = class {
|
|
|
13518
13713
|
// src/runtime-kernel/child-run-trace/projectChildRuntimeEventToSubRunTrace.ts
|
|
13519
13714
|
function projectChildRuntimeEventToSubRunTrace(event) {
|
|
13520
13715
|
switch (event.type) {
|
|
13716
|
+
case "llm_retry":
|
|
13717
|
+
return {
|
|
13718
|
+
kind: "llm_retry",
|
|
13719
|
+
source_event_id: event.id,
|
|
13720
|
+
retry: {
|
|
13721
|
+
retry_id: event.retry_id,
|
|
13722
|
+
status: event.status,
|
|
13723
|
+
category: event.category,
|
|
13724
|
+
attempt: event.attempt,
|
|
13725
|
+
max_retries: event.max_retries,
|
|
13726
|
+
total_attempts: event.total_attempts,
|
|
13727
|
+
started_at: event.started_at,
|
|
13728
|
+
delay_ms: event.delay_ms,
|
|
13729
|
+
next_retry_at: event.next_retry_at,
|
|
13730
|
+
error: event.error,
|
|
13731
|
+
error_code: event.error_code
|
|
13732
|
+
}
|
|
13733
|
+
};
|
|
13734
|
+
case "error":
|
|
13735
|
+
return {
|
|
13736
|
+
kind: "error",
|
|
13737
|
+
source_event_id: event.id,
|
|
13738
|
+
// 父展示只需要安全错误与重试身份,不复制 child 的任意诊断 details。
|
|
13739
|
+
failure: { error: event.error, error_code: event.error_code, retryable: event.retryable, retry_id: event.retry_id }
|
|
13740
|
+
};
|
|
13521
13741
|
case "thought":
|
|
13522
13742
|
return event.is_complete ? {
|
|
13523
13743
|
kind: "thought_complete",
|