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