@linnlabs/linnkit 0.9.0 → 0.21.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 +168 -0
- package/bin/linnkit.cjs +7 -0
- package/dist/{agent-invocation-BHcNfrBV.d.cts → agent-invocation-CAlm9qOw.d.cts} +1 -1
- package/dist/{agent-invocation-BznDaXDs.d.ts → agent-invocation-DKoEDLkl.d.ts} +1 -1
- package/dist/{ai-engine.types-vZRnQcJa.d.ts → ai-engine.types-CeLoM624.d.cts} +9 -1
- package/dist/{ai-engine.types-BpeU_XQG.d.cts → ai-engine.types-LqmnfR2W.d.ts} +9 -1
- package/dist/{audit-CtcfART1.d.ts → audit-BuWHoMEr.d.ts} +4 -2
- package/dist/{audit-LeOrm2hX.d.cts → audit-DnzNQzwq.d.cts} +4 -2
- package/dist/cli.cjs +682 -258
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +682 -258
- package/dist/cli.js.map +1 -1
- package/dist/context-manager.cjs +823 -57
- package/dist/context-manager.cjs.map +1 -1
- package/dist/context-manager.d.cts +132 -18
- package/dist/context-manager.d.ts +132 -18
- package/dist/context-manager.js +823 -58
- package/dist/context-manager.js.map +1 -1
- package/dist/{context-trace-HE2qY5Q-.d.cts → context-trace-DrtvKac4.d.cts} +37 -4
- package/dist/{context-trace-DRi5M4lX.d.ts → context-trace-WV1HAZeB.d.ts} +37 -4
- package/dist/contracts.cjs +225 -2
- package/dist/contracts.cjs.map +1 -1
- package/dist/contracts.d.cts +6 -4
- package/dist/contracts.d.ts +6 -4
- package/dist/contracts.js +205 -3
- package/dist/contracts.js.map +1 -1
- package/dist/{defaultGraphExecutor-BIjJj7WF.d.cts → defaultGraphExecutor-L1ri3oij.d.cts} +48 -19
- package/dist/{defaultGraphExecutor-BBswR8wn.d.ts → defaultGraphExecutor-QzzdudLQ.d.ts} +48 -19
- package/dist/{index-BanRABEt.d.cts → index-BeQO0rx2.d.cts} +345 -268
- package/dist/{index-Cvr23YCl.d.cts → index-CDofGr_4.d.ts} +24 -6
- package/dist/{index-Dl5PLgAv.d.cts → index-Crl5E4eF.d.cts} +27 -4
- package/dist/{index-CJeWHopy.d.ts → index-DWGKvssS.d.ts} +3 -3
- package/dist/{index-CHqwkvGp.d.ts → index-X5lYU1Lj.d.ts} +27 -4
- package/dist/{index-DDzuSb0n.d.ts → index-uCNCpJBg.d.cts} +24 -6
- package/dist/{index-Z8NXKNwI.d.ts → index-wOZD-p2-.d.ts} +345 -268
- package/dist/{index-DO4dQgf2.d.cts → index-wXVAHZ0D.d.cts} +3 -3
- package/dist/index.cjs +1011 -329
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -16
- package/dist/index.d.ts +19 -16
- package/dist/index.js +1011 -329
- package/dist/index.js.map +1 -1
- package/dist/{messages-XthmnHZ3.d.cts → messages-Br5SiLD3.d.cts} +706 -1
- package/dist/{messages-XthmnHZ3.d.ts → messages-Br5SiLD3.d.ts} +706 -1
- package/dist/{ports-DnLuKfpE.d.ts → ports-Dugizzje.d.cts} +6 -2
- package/dist/{ports-DaatKJXp.d.cts → ports-fhp84x_C.d.ts} +6 -2
- package/dist/ports.d.cts +8 -5
- package/dist/ports.d.ts +8 -5
- package/dist/quickstart.cjs +683 -258
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.d.cts +11 -10
- package/dist/quickstart.d.ts +11 -10
- package/dist/quickstart.js +683 -258
- package/dist/quickstart.js.map +1 -1
- package/dist/{runAgent-CPj_9e58.d.ts → runAgent-BmMSju8I.d.ts} +6 -6
- package/dist/{runAgent-HYKlXbVr.d.cts → runAgent-CKgcRSRH.d.cts} +6 -6
- package/dist/{runHandle-D3gPsD7B.d.cts → runHandle-DH4VmQx6.d.cts} +6 -4
- package/dist/{runHandle-CyXvzgzk.d.ts → runHandle-o3p06Nva.d.ts} +6 -4
- package/dist/runtime-kernel/events.cjs +202 -1
- package/dist/runtime-kernel/events.cjs.map +1 -1
- package/dist/runtime-kernel/events.d.cts +5 -5
- package/dist/runtime-kernel/events.d.ts +5 -5
- package/dist/runtime-kernel/events.js +202 -1
- package/dist/runtime-kernel/events.js.map +1 -1
- package/dist/runtime-kernel.cjs +999 -340
- package/dist/runtime-kernel.cjs.map +1 -1
- package/dist/runtime-kernel.d.cts +16 -14
- package/dist/runtime-kernel.d.ts +16 -14
- package/dist/runtime-kernel.js +990 -341
- package/dist/runtime-kernel.js.map +1 -1
- package/dist/testkit.cjs +1003 -321
- package/dist/testkit.cjs.map +1 -1
- package/dist/testkit.d.cts +16 -14
- package/dist/testkit.d.ts +16 -14
- package/dist/testkit.js +1003 -321
- package/dist/testkit.js.map +1 -1
- package/dist/{todo-B1PmDlp3.d.cts → todo-Ca8llpRQ.d.cts} +1 -1
- package/dist/{todo-B1PmDlp3.d.ts → todo-Ca8llpRQ.d.ts} +1 -1
- package/dist/{agentSpec-EkmviZjy.d.cts → token-accounting-CwpSPg4y.d.cts} +1280 -1
- package/dist/{agentSpec-EkmviZjy.d.ts → token-accounting-CwpSPg4y.d.ts} +1280 -1
- package/dist/token-calibration-Cxv6dDYF.d.cts +327 -0
- package/dist/token-calibration-Cxv6dDYF.d.ts +327 -0
- package/dist/token-counter-CFfP8PQb.d.cts +26 -0
- package/dist/token-counter-SFyyTeaG.d.ts +26 -0
- package/dist/token-usage-CqwT7-5K.d.cts +133 -0
- package/dist/token-usage-CqwT7-5K.d.ts +133 -0
- package/dist/{tokenizer-DFL4I7-I.d.ts → tokenizer-BFJNCHFX.d.ts} +1 -1
- package/dist/{tokenizer-DH_JXv-H.d.cts → tokenizer-DoGsBE3A.d.cts} +1 -1
- package/dist/{toolContracts-CLkQmhTG.d.cts → toolContracts-Bm3EZ1UM.d.cts} +13 -2
- package/dist/{toolContracts-Blll0241.d.ts → toolContracts-f8lzZBNa.d.ts} +13 -2
- package/docs/README.md +1 -1
- package/docs/integration/README.md +3 -3
- package/docs/integration/agent-registration-guide.md +3 -1
- package/docs/integration/child-runs.md +4 -1
- package/docs/integration/context-engineering.md +83 -16
- package/docs/integration/context-fences.md +44 -3
- package/docs/integration/llm-provider.md +1 -1
- package/docs/integration/persistence.md +1 -0
- package/docs/integration/run-supervisor.md +3 -0
- package/docs/integration/tool-development-guide.md +7 -5
- package/docs/integration/tool-history.md +43 -17
- package/package.json +4 -3
package/dist/cli.js
CHANGED
|
@@ -76,6 +76,12 @@ z.object({
|
|
|
76
76
|
args: z.record(z.unknown()).optional(),
|
|
77
77
|
tool_call_id: z.string()
|
|
78
78
|
});
|
|
79
|
+
var ObservationTruncationMeta = z.object({
|
|
80
|
+
originalChars: z.number().int().nonnegative(),
|
|
81
|
+
previewChars: z.number().int().nonnegative(),
|
|
82
|
+
originalLines: z.number().int().nonnegative().optional(),
|
|
83
|
+
previewLines: z.number().int().nonnegative().optional()
|
|
84
|
+
});
|
|
79
85
|
var ImageInfoMeta = z.object({
|
|
80
86
|
url: z.string().optional(),
|
|
81
87
|
width: z.number().int().positive().optional(),
|
|
@@ -107,6 +113,7 @@ var PersistentMetadata = z.object({
|
|
|
107
113
|
tool_name: z.string().optional(),
|
|
108
114
|
args: z.record(z.unknown()).optional(),
|
|
109
115
|
tool_call_id: z.string().optional(),
|
|
116
|
+
observationTruncation: ObservationTruncationMeta.optional(),
|
|
110
117
|
raw_output: z.string().optional(),
|
|
111
118
|
image_info: ImageInfoMeta.optional(),
|
|
112
119
|
taskType: z.string().optional(),
|
|
@@ -200,6 +207,7 @@ var AgentSpecBudgetPolicy = z.object({
|
|
|
200
207
|
});
|
|
201
208
|
var AgentSpecToolHistoryPolicy = z.object({
|
|
202
209
|
strategy: z.enum(["per-pair", "per-run", "none"]).optional(),
|
|
210
|
+
retentionMode: z.enum(["drop", "compress"]).optional(),
|
|
203
211
|
keepLatestToolPairs: z.number().int().nonnegative().optional(),
|
|
204
212
|
keepLatestRuns: z.number().int().nonnegative().optional(),
|
|
205
213
|
maxInteractionGroups: z.number().int().nonnegative().optional(),
|
|
@@ -252,7 +260,17 @@ var AgentSpecReasoningRetentionPolicy = z.object({
|
|
|
252
260
|
var AgentSpecTokenEstimationPolicy = z.object({
|
|
253
261
|
encoding: z.string().min(1).optional(),
|
|
254
262
|
avgCharsPerToken: z.number().positive().optional(),
|
|
255
|
-
toolCallOverhead: z.number().int().nonnegative().optional()
|
|
263
|
+
toolCallOverhead: z.number().int().nonnegative().optional(),
|
|
264
|
+
calibration: z.object({
|
|
265
|
+
enabled: z.boolean().optional(),
|
|
266
|
+
minSamples: z.number().int().positive().optional(),
|
|
267
|
+
minCoefficient: z.number().positive().optional(),
|
|
268
|
+
maxCoefficient: z.number().positive().optional()
|
|
269
|
+
}).optional(),
|
|
270
|
+
remoteCount: z.object({
|
|
271
|
+
enabled: z.boolean().optional(),
|
|
272
|
+
failureBehavior: z.enum(["use-local-estimate", "fail-fast"]).optional()
|
|
273
|
+
}).optional()
|
|
256
274
|
});
|
|
257
275
|
var AgentSpecSystemReminderTrigger = z.object({
|
|
258
276
|
kind: z.string().min(1),
|
|
@@ -948,6 +966,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
|
|
|
948
966
|
error,
|
|
949
967
|
...options
|
|
950
968
|
});
|
|
969
|
+
var TokenCountSource = z.enum([
|
|
970
|
+
"local-estimate",
|
|
971
|
+
"provider-preflight-count",
|
|
972
|
+
"provider-response-usage",
|
|
973
|
+
"host-supplied",
|
|
974
|
+
"test-fixture"
|
|
975
|
+
]);
|
|
976
|
+
var TokenCountConfidence = z.enum([
|
|
977
|
+
"estimate",
|
|
978
|
+
"provider-estimate",
|
|
979
|
+
"actual"
|
|
980
|
+
]);
|
|
981
|
+
var TokenRouteCapabilities = z.object({
|
|
982
|
+
supportsRemoteTokenCount: z.boolean().optional(),
|
|
983
|
+
supportsResponseUsage: z.boolean().optional(),
|
|
984
|
+
supportsImageInput: z.boolean().optional(),
|
|
985
|
+
supportsCachedInputBilling: z.boolean().optional(),
|
|
986
|
+
supportsReasoningTokens: z.boolean().optional()
|
|
987
|
+
});
|
|
988
|
+
var TokenRoute = z.object({
|
|
989
|
+
providerId: z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
|
|
990
|
+
baseURL: z.string().optional().describe("\u4E2D\u8F6C\u5E73\u53F0\u6216\u79C1\u6709 endpoint\uFF1B\u7528\u4E8E\u533A\u5206\u540C\u540D\u6A21\u578B\u7684\u4E0D\u540C route"),
|
|
991
|
+
modelId: z.string().describe("host \u4FA7\u6A21\u578B id"),
|
|
992
|
+
providerModelId: z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
|
|
993
|
+
capabilities: TokenRouteCapabilities.optional()
|
|
994
|
+
});
|
|
995
|
+
var tokenCount = z.number().int().nonnegative();
|
|
996
|
+
var CanonicalLlmUsage = z.object({
|
|
997
|
+
inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
|
|
998
|
+
outputTokens: tokenCount.describe("\u8F93\u51FA token"),
|
|
999
|
+
reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
|
|
1000
|
+
cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
|
|
1001
|
+
cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
|
|
1002
|
+
totalTokens: tokenCount.optional().describe("provider \u62A5\u544A\u7684\u603B\u91CF\uFF1B\u53EF\u7F3A\u5931\uFF0C\u4E14\u4E0D\u4FDD\u8BC1\u7B49\u4E8E\u5404\u9879\u4E4B\u548C"),
|
|
1003
|
+
source: TokenCountSource,
|
|
1004
|
+
confidence: TokenCountConfidence,
|
|
1005
|
+
rawUsage: z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
|
|
1006
|
+
});
|
|
1007
|
+
var tokenCount2 = z.number().int().nonnegative();
|
|
1008
|
+
var tokenPrice = z.number().finite().nonnegative();
|
|
1009
|
+
z.enum([
|
|
1010
|
+
"llm-usage",
|
|
1011
|
+
"context-component"
|
|
1012
|
+
]);
|
|
1013
|
+
var ContextTokenComponentKind = z.enum([
|
|
1014
|
+
"system",
|
|
1015
|
+
"user",
|
|
1016
|
+
"assistant",
|
|
1017
|
+
"tool",
|
|
1018
|
+
"context-injection",
|
|
1019
|
+
"history-summary",
|
|
1020
|
+
"working-memory",
|
|
1021
|
+
"fence",
|
|
1022
|
+
"system-reminder",
|
|
1023
|
+
"other"
|
|
1024
|
+
]);
|
|
1025
|
+
var TokenUsageTotals = z.object({
|
|
1026
|
+
inputTokens: tokenCount2,
|
|
1027
|
+
outputTokens: tokenCount2,
|
|
1028
|
+
reasoningTokens: tokenCount2.optional(),
|
|
1029
|
+
cacheReadTokens: tokenCount2.optional(),
|
|
1030
|
+
cacheWriteTokens: tokenCount2.optional(),
|
|
1031
|
+
totalTokens: tokenCount2.optional(),
|
|
1032
|
+
usageCount: z.number().int().nonnegative()
|
|
1033
|
+
});
|
|
1034
|
+
var ContextTokenComponent = z.object({
|
|
1035
|
+
componentId: z.string().min(1),
|
|
1036
|
+
kind: ContextTokenComponentKind,
|
|
1037
|
+
tokens: tokenCount2,
|
|
1038
|
+
source: TokenCountSource,
|
|
1039
|
+
confidence: TokenCountConfidence,
|
|
1040
|
+
label: z.string().optional(),
|
|
1041
|
+
messageId: z.string().optional(),
|
|
1042
|
+
role: z.string().optional(),
|
|
1043
|
+
action: z.string().optional(),
|
|
1044
|
+
kept: z.boolean().optional(),
|
|
1045
|
+
truncatedAtExecution: z.boolean().optional(),
|
|
1046
|
+
originalTokensEstimate: tokenCount2.optional(),
|
|
1047
|
+
droppedTokensEstimate: tokenCount2.optional()
|
|
1048
|
+
});
|
|
1049
|
+
var TokenLedgerEntryBase = z.object({
|
|
1050
|
+
id: z.string().min(1),
|
|
1051
|
+
runId: z.string().optional(),
|
|
1052
|
+
parentRunId: z.string().optional(),
|
|
1053
|
+
conversationId: z.string().optional(),
|
|
1054
|
+
turnId: z.string().optional(),
|
|
1055
|
+
stepId: z.string().optional(),
|
|
1056
|
+
route: TokenRoute.optional(),
|
|
1057
|
+
createdAt: z.number().int().nonnegative().optional()
|
|
1058
|
+
});
|
|
1059
|
+
var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
|
|
1060
|
+
kind: z.literal("llm-usage"),
|
|
1061
|
+
modelId: z.string().optional(),
|
|
1062
|
+
usage: CanonicalLlmUsage
|
|
1063
|
+
});
|
|
1064
|
+
var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
|
|
1065
|
+
kind: z.literal("context-component"),
|
|
1066
|
+
components: z.array(ContextTokenComponent),
|
|
1067
|
+
totalTokens: tokenCount2
|
|
1068
|
+
});
|
|
1069
|
+
z.discriminatedUnion("kind", [
|
|
1070
|
+
LlmUsageTokenLedgerEntry,
|
|
1071
|
+
ContextComponentTokenLedgerEntry
|
|
1072
|
+
]);
|
|
1073
|
+
var TokenLedgerAggregate = z.object({
|
|
1074
|
+
llmUsage: TokenUsageTotals.optional(),
|
|
1075
|
+
contextTokens: tokenCount2,
|
|
1076
|
+
entryCount: z.number().int().nonnegative(),
|
|
1077
|
+
llmCallCount: z.number().int().nonnegative(),
|
|
1078
|
+
contextComponentCount: z.number().int().nonnegative()
|
|
1079
|
+
});
|
|
1080
|
+
z.object({
|
|
1081
|
+
/**
|
|
1082
|
+
* 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
|
|
1083
|
+
*/
|
|
1084
|
+
own: TokenLedgerAggregate,
|
|
1085
|
+
children: TokenLedgerAggregate.optional()
|
|
1086
|
+
});
|
|
1087
|
+
var TokenCostComponent = z.enum([
|
|
1088
|
+
"input",
|
|
1089
|
+
"output",
|
|
1090
|
+
"reasoning",
|
|
1091
|
+
"cacheRead",
|
|
1092
|
+
"cacheWrite"
|
|
1093
|
+
]);
|
|
1094
|
+
z.object({
|
|
1095
|
+
currency: z.string().min(1),
|
|
1096
|
+
unit: z.literal("per_1m_tokens"),
|
|
1097
|
+
input: tokenPrice.optional(),
|
|
1098
|
+
output: tokenPrice.optional(),
|
|
1099
|
+
reasoning: tokenPrice.optional(),
|
|
1100
|
+
cacheRead: tokenPrice.optional(),
|
|
1101
|
+
cacheWrite: tokenPrice.optional()
|
|
1102
|
+
});
|
|
1103
|
+
z.object({
|
|
1104
|
+
status: z.enum(["computed", "unknown"]),
|
|
1105
|
+
currency: z.string().optional(),
|
|
1106
|
+
inputCost: tokenPrice.optional(),
|
|
1107
|
+
outputCost: tokenPrice.optional(),
|
|
1108
|
+
reasoningCost: tokenPrice.optional(),
|
|
1109
|
+
cacheReadCost: tokenPrice.optional(),
|
|
1110
|
+
cacheWriteCost: tokenPrice.optional(),
|
|
1111
|
+
totalCost: tokenPrice.optional(),
|
|
1112
|
+
missingPriceComponents: z.array(TokenCostComponent).optional()
|
|
1113
|
+
});
|
|
1114
|
+
var tokenCount3 = z.number().int().nonnegative();
|
|
1115
|
+
var actualCalibrationSource = z.enum([
|
|
1116
|
+
"provider-response-usage",
|
|
1117
|
+
"host-supplied",
|
|
1118
|
+
"test-fixture"
|
|
1119
|
+
]);
|
|
1120
|
+
z.object({
|
|
1121
|
+
route: TokenRoute,
|
|
1122
|
+
localEstimateTokens: tokenCount3,
|
|
1123
|
+
actualInputTokens: tokenCount3,
|
|
1124
|
+
source: actualCalibrationSource,
|
|
1125
|
+
confidence: z.literal("actual"),
|
|
1126
|
+
observedAt: z.number().int().nonnegative().optional(),
|
|
1127
|
+
runId: z.string().optional(),
|
|
1128
|
+
ledgerEntryId: z.string().optional()
|
|
1129
|
+
});
|
|
1130
|
+
z.object({
|
|
1131
|
+
enabled: z.boolean(),
|
|
1132
|
+
applied: z.boolean(),
|
|
1133
|
+
route: TokenRoute.optional(),
|
|
1134
|
+
sampleCount: z.number().int().nonnegative(),
|
|
1135
|
+
coefficient: z.number().positive().optional(),
|
|
1136
|
+
minSamples: z.number().int().positive().optional(),
|
|
1137
|
+
minCoefficient: z.number().positive().optional(),
|
|
1138
|
+
maxCoefficient: z.number().positive().optional(),
|
|
1139
|
+
localEstimateTokens: tokenCount3.optional(),
|
|
1140
|
+
calibratedEstimateTokens: tokenCount3.optional(),
|
|
1141
|
+
deltaTokens: z.number().int().optional(),
|
|
1142
|
+
sampleLedgerEntryIds: z.array(z.string()).optional()
|
|
1143
|
+
});
|
|
1144
|
+
z.object({
|
|
1145
|
+
route: TokenRoute.optional(),
|
|
1146
|
+
localEstimateTokens: tokenCount3,
|
|
1147
|
+
calibratedEstimateTokens: tokenCount3,
|
|
1148
|
+
finalTokens: tokenCount3,
|
|
1149
|
+
source: z.literal("local-estimate"),
|
|
1150
|
+
confidence: z.literal("estimate")
|
|
1151
|
+
});
|
|
951
1152
|
|
|
952
1153
|
// src/quickstart/toolSchema.ts
|
|
953
1154
|
function serializeToolProperty(property) {
|
|
@@ -1081,6 +1282,7 @@ var Logger = class {
|
|
|
1081
1282
|
constructor(moduleName) {
|
|
1082
1283
|
this.moduleName = moduleName;
|
|
1083
1284
|
}
|
|
1285
|
+
moduleName;
|
|
1084
1286
|
debug(message, data) {
|
|
1085
1287
|
this.log(0 /* DEBUG */, "debug", message, data);
|
|
1086
1288
|
}
|
|
@@ -1153,6 +1355,17 @@ var logger = new Logger("GraphExecutor");
|
|
|
1153
1355
|
function asLocalRecord(local) {
|
|
1154
1356
|
return local && typeof local === "object" ? { ...local } : {};
|
|
1155
1357
|
}
|
|
1358
|
+
function readNonEmptyString(value) {
|
|
1359
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
1360
|
+
}
|
|
1361
|
+
function readRuntimeConversationId(state) {
|
|
1362
|
+
const local = state?.local && typeof state.local === "object" ? state.local : void 0;
|
|
1363
|
+
return readNonEmptyString(local?.conversationId);
|
|
1364
|
+
}
|
|
1365
|
+
function readRuntimeTurnId(state) {
|
|
1366
|
+
const local = state?.local && typeof state.local === "object" ? state.local : void 0;
|
|
1367
|
+
return readNonEmptyString(local?.turnId);
|
|
1368
|
+
}
|
|
1156
1369
|
var GraphExecutor = class {
|
|
1157
1370
|
constructor(checkpointer, config = {}) {
|
|
1158
1371
|
this.checkpointer = checkpointer;
|
|
@@ -1162,6 +1375,7 @@ var GraphExecutor = class {
|
|
|
1162
1375
|
};
|
|
1163
1376
|
this.telemetryPort = config.telemetryPort ?? noopTelemetry;
|
|
1164
1377
|
}
|
|
1378
|
+
checkpointer;
|
|
1165
1379
|
nodes = /* @__PURE__ */ new Map();
|
|
1166
1380
|
ephemeralLocals = /* @__PURE__ */ new Map();
|
|
1167
1381
|
config;
|
|
@@ -1169,8 +1383,8 @@ var GraphExecutor = class {
|
|
|
1169
1383
|
registerNode(node) {
|
|
1170
1384
|
this.nodes.set(node.id, node);
|
|
1171
1385
|
}
|
|
1172
|
-
async peekCheckpoint(
|
|
1173
|
-
return await this.checkpointer.load(
|
|
1386
|
+
async peekCheckpoint(checkpointKey) {
|
|
1387
|
+
return await this.checkpointer.load(checkpointKey);
|
|
1174
1388
|
}
|
|
1175
1389
|
sanitize(state) {
|
|
1176
1390
|
const local = asLocalRecord(state.local);
|
|
@@ -1182,8 +1396,8 @@ var GraphExecutor = class {
|
|
|
1182
1396
|
local
|
|
1183
1397
|
};
|
|
1184
1398
|
}
|
|
1185
|
-
async prime(
|
|
1186
|
-
this.ephemeralLocals.set(
|
|
1399
|
+
async prime(checkpointKey, local, nodeId = "user") {
|
|
1400
|
+
this.ephemeralLocals.set(checkpointKey, { ...local || {} });
|
|
1187
1401
|
const localSansMemory = { ...local || {} };
|
|
1188
1402
|
if ("memory" in localSansMemory) delete localSansMemory.memory;
|
|
1189
1403
|
const state = {
|
|
@@ -1191,10 +1405,10 @@ var GraphExecutor = class {
|
|
|
1191
1405
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1192
1406
|
local: localSansMemory
|
|
1193
1407
|
};
|
|
1194
|
-
await this.checkpointer.save(
|
|
1408
|
+
await this.checkpointer.save(checkpointKey, state);
|
|
1195
1409
|
}
|
|
1196
|
-
async setNode(
|
|
1197
|
-
const current = await this.checkpointer.load(
|
|
1410
|
+
async setNode(checkpointKey, nodeId, localPatch) {
|
|
1411
|
+
const current = await this.checkpointer.load(checkpointKey) || {
|
|
1198
1412
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1199
1413
|
local: {}
|
|
1200
1414
|
};
|
|
@@ -1205,19 +1419,46 @@ var GraphExecutor = class {
|
|
|
1205
1419
|
schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
1206
1420
|
local: mergedLocal
|
|
1207
1421
|
};
|
|
1208
|
-
await this.checkpointer.save(
|
|
1422
|
+
await this.checkpointer.save(checkpointKey, next);
|
|
1209
1423
|
}
|
|
1210
|
-
async runUntilYield(
|
|
1424
|
+
async runUntilYield(checkpointKey) {
|
|
1211
1425
|
const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1212
1426
|
let lifecyclePhase = "completed";
|
|
1427
|
+
let initialState = null;
|
|
1428
|
+
try {
|
|
1429
|
+
initialState = await this.loadInitialState(checkpointKey);
|
|
1430
|
+
} catch (err) {
|
|
1431
|
+
lifecyclePhase = "failed";
|
|
1432
|
+
this.telemetryPort.emit({
|
|
1433
|
+
kind: "run_lifecycle",
|
|
1434
|
+
runId,
|
|
1435
|
+
phase: "spawned",
|
|
1436
|
+
scope: {}
|
|
1437
|
+
});
|
|
1438
|
+
this.telemetryPort.emit({
|
|
1439
|
+
kind: "run_lifecycle",
|
|
1440
|
+
runId,
|
|
1441
|
+
phase: lifecyclePhase,
|
|
1442
|
+
scope: {}
|
|
1443
|
+
});
|
|
1444
|
+
throw err;
|
|
1445
|
+
}
|
|
1446
|
+
let lifecycleConversationId = readRuntimeConversationId(initialState);
|
|
1447
|
+
let lifecycleTurnId = readRuntimeTurnId(initialState);
|
|
1213
1448
|
this.telemetryPort.emit({
|
|
1214
1449
|
kind: "run_lifecycle",
|
|
1215
1450
|
runId,
|
|
1216
1451
|
phase: "spawned",
|
|
1217
|
-
scope: {
|
|
1452
|
+
scope: {
|
|
1453
|
+
conversationId: lifecycleConversationId,
|
|
1454
|
+
turnId: lifecycleTurnId
|
|
1455
|
+
}
|
|
1218
1456
|
});
|
|
1219
1457
|
try {
|
|
1220
|
-
|
|
1458
|
+
const result = await this.runUntilYieldInternal(checkpointKey, initialState);
|
|
1459
|
+
lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
|
|
1460
|
+
lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
|
|
1461
|
+
return result;
|
|
1221
1462
|
} catch (err) {
|
|
1222
1463
|
lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
|
|
1223
1464
|
throw err;
|
|
@@ -1226,17 +1467,23 @@ var GraphExecutor = class {
|
|
|
1226
1467
|
kind: "run_lifecycle",
|
|
1227
1468
|
runId,
|
|
1228
1469
|
phase: lifecyclePhase,
|
|
1229
|
-
scope: {
|
|
1470
|
+
scope: {
|
|
1471
|
+
conversationId: lifecycleConversationId,
|
|
1472
|
+
turnId: lifecycleTurnId
|
|
1473
|
+
}
|
|
1230
1474
|
});
|
|
1231
1475
|
}
|
|
1232
1476
|
}
|
|
1233
|
-
async
|
|
1234
|
-
|
|
1477
|
+
async loadInitialState(checkpointKey) {
|
|
1478
|
+
return await this.checkpointer.load(checkpointKey) || {
|
|
1235
1479
|
nodeId: "user",
|
|
1236
1480
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1237
1481
|
local: {}
|
|
1238
1482
|
};
|
|
1239
|
-
|
|
1483
|
+
}
|
|
1484
|
+
async runUntilYieldInternal(checkpointKey, initialState) {
|
|
1485
|
+
let state = initialState;
|
|
1486
|
+
const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
|
|
1240
1487
|
state = {
|
|
1241
1488
|
...state,
|
|
1242
1489
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
@@ -1265,7 +1512,7 @@ var GraphExecutor = class {
|
|
|
1265
1512
|
const signalRaw = state.local?.signal;
|
|
1266
1513
|
if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
|
|
1267
1514
|
logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
|
|
1268
|
-
this.ephemeralLocals.delete(
|
|
1515
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1269
1516
|
throwAbortError();
|
|
1270
1517
|
}
|
|
1271
1518
|
const isLastStep = cycleStepCount >= this.config.maxSteps;
|
|
@@ -1313,8 +1560,8 @@ var GraphExecutor = class {
|
|
|
1313
1560
|
checkpointCount
|
|
1314
1561
|
});
|
|
1315
1562
|
const cp2 = this.sanitize(state);
|
|
1316
|
-
await this.checkpointer.save(
|
|
1317
|
-
this.ephemeralLocals.delete(
|
|
1563
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1564
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1318
1565
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1319
1566
|
}
|
|
1320
1567
|
logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
|
|
@@ -1325,18 +1572,18 @@ var GraphExecutor = class {
|
|
|
1325
1572
|
});
|
|
1326
1573
|
const nodeRunStartedAt = Date.now();
|
|
1327
1574
|
const nodeIdForTelemetry = state.nodeId;
|
|
1575
|
+
const conversationIdForTelemetry = readRuntimeConversationId(state);
|
|
1328
1576
|
let result;
|
|
1329
1577
|
try {
|
|
1330
1578
|
result = await node.run(state);
|
|
1331
1579
|
} finally {
|
|
1332
|
-
const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
|
|
1333
1580
|
this.telemetryPort.emit({
|
|
1334
1581
|
kind: "graph_node",
|
|
1335
1582
|
nodeId: nodeIdForTelemetry,
|
|
1336
1583
|
durationMs: Date.now() - nodeRunStartedAt,
|
|
1337
1584
|
scope: {
|
|
1338
|
-
conversationId:
|
|
1339
|
-
turnId:
|
|
1585
|
+
conversationId: conversationIdForTelemetry,
|
|
1586
|
+
turnId: readRuntimeTurnId(state)
|
|
1340
1587
|
}
|
|
1341
1588
|
});
|
|
1342
1589
|
}
|
|
@@ -1375,7 +1622,7 @@ var GraphExecutor = class {
|
|
|
1375
1622
|
});
|
|
1376
1623
|
state = { ...state, nodeId: nextNodeId };
|
|
1377
1624
|
const cp2 = this.sanitize(state);
|
|
1378
|
-
await this.checkpointer.save(
|
|
1625
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1379
1626
|
continue;
|
|
1380
1627
|
}
|
|
1381
1628
|
if (result.kind === "yield") {
|
|
@@ -1386,7 +1633,7 @@ var GraphExecutor = class {
|
|
|
1386
1633
|
checkpointCount
|
|
1387
1634
|
});
|
|
1388
1635
|
const cp2 = this.sanitize(state);
|
|
1389
|
-
await this.checkpointer.save(
|
|
1636
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1390
1637
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1391
1638
|
}
|
|
1392
1639
|
if (result.kind === "pause") {
|
|
@@ -1397,7 +1644,7 @@ var GraphExecutor = class {
|
|
|
1397
1644
|
checkpointCount
|
|
1398
1645
|
});
|
|
1399
1646
|
const cp2 = this.sanitize(state);
|
|
1400
|
-
await this.checkpointer.save(
|
|
1647
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1401
1648
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1402
1649
|
}
|
|
1403
1650
|
}
|
|
@@ -1408,8 +1655,8 @@ var GraphExecutor = class {
|
|
|
1408
1655
|
checkpointCount
|
|
1409
1656
|
});
|
|
1410
1657
|
const cp = this.sanitize(state);
|
|
1411
|
-
await this.checkpointer.save(
|
|
1412
|
-
this.ephemeralLocals.delete(
|
|
1658
|
+
await this.checkpointer.save(checkpointKey, cp);
|
|
1659
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1413
1660
|
return { events: allEvents, checkpoint: cp, stepCount };
|
|
1414
1661
|
}
|
|
1415
1662
|
};
|
|
@@ -1505,6 +1752,190 @@ var noopAudit = {
|
|
|
1505
1752
|
flush() {
|
|
1506
1753
|
}
|
|
1507
1754
|
};
|
|
1755
|
+
var TokenCalculator = class {
|
|
1756
|
+
static BYTES_PER_TOKEN_LATIN = 4;
|
|
1757
|
+
static BYTES_PER_TOKEN_CJK = 3;
|
|
1758
|
+
static OVERHEAD_PER_MESSAGE = 5;
|
|
1759
|
+
static OVERHEAD_PER_TOOL_CALL = 10;
|
|
1760
|
+
static encoderCache = /* @__PURE__ */ new Map();
|
|
1761
|
+
static DEFAULT_ENCODING = "cl100k_base";
|
|
1762
|
+
static SUPPORTED_ENCODINGS = [
|
|
1763
|
+
"gpt2",
|
|
1764
|
+
"r50k_base",
|
|
1765
|
+
"p50k_base",
|
|
1766
|
+
"p50k_edit",
|
|
1767
|
+
"cl100k_base",
|
|
1768
|
+
"o200k_base"
|
|
1769
|
+
];
|
|
1770
|
+
static resolveEncodingFromModelIdentifier(modelIdentifier) {
|
|
1771
|
+
const normalized = (modelIdentifier || "").trim().toLowerCase();
|
|
1772
|
+
if (this.isSupportedEncodingName(normalized)) {
|
|
1773
|
+
return normalized;
|
|
1774
|
+
}
|
|
1775
|
+
if (normalized.includes("deepseek")) {
|
|
1776
|
+
return "cl100k_base";
|
|
1777
|
+
}
|
|
1778
|
+
if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
|
|
1779
|
+
return "o200k_base";
|
|
1780
|
+
}
|
|
1781
|
+
if (normalized.includes("gemini") || normalized.includes("claude")) {
|
|
1782
|
+
return "cl100k_base";
|
|
1783
|
+
}
|
|
1784
|
+
return this.DEFAULT_ENCODING;
|
|
1785
|
+
}
|
|
1786
|
+
static isSupportedEncodingName(value) {
|
|
1787
|
+
return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
|
|
1788
|
+
}
|
|
1789
|
+
static getEncoder(modelIdentifierOrEncoding) {
|
|
1790
|
+
const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
|
|
1791
|
+
const cached = this.encoderCache.get(encodingName);
|
|
1792
|
+
if (cached) {
|
|
1793
|
+
return cached;
|
|
1794
|
+
}
|
|
1795
|
+
const encoder = get_encoding(encodingName);
|
|
1796
|
+
this.encoderCache.set(encodingName, encoder);
|
|
1797
|
+
return encoder;
|
|
1798
|
+
}
|
|
1799
|
+
static estimateTokensRough(text, _modelIdentifier) {
|
|
1800
|
+
if (!text) return 0;
|
|
1801
|
+
const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
|
|
1802
|
+
const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
|
|
1803
|
+
const byteLength = new TextEncoder().encode(text).length;
|
|
1804
|
+
return Math.ceil(byteLength / ratio);
|
|
1805
|
+
}
|
|
1806
|
+
static estimateTokens(text, options = {}) {
|
|
1807
|
+
if (!text) return 0;
|
|
1808
|
+
if (options.encoding) {
|
|
1809
|
+
try {
|
|
1810
|
+
return this.estimateTokensPrecise(text, options.encoding);
|
|
1811
|
+
} catch {
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
|
|
1815
|
+
return Math.ceil(text.length / avgCharsPerToken);
|
|
1816
|
+
}
|
|
1817
|
+
static estimateTokensPrecise(text, modelIdentifier) {
|
|
1818
|
+
if (!text) return 0;
|
|
1819
|
+
const encoder = this.getEncoder(modelIdentifier);
|
|
1820
|
+
return encoder.encode(text).length;
|
|
1821
|
+
}
|
|
1822
|
+
static estimateMessageTokens(message, options = {}) {
|
|
1823
|
+
let totalTokens = this.OVERHEAD_PER_MESSAGE;
|
|
1824
|
+
if (message.content) {
|
|
1825
|
+
totalTokens += this.estimateTokens(String(message.content), options);
|
|
1826
|
+
}
|
|
1827
|
+
const toolCalls = this.extractToolCallsForTokenEstimate(message);
|
|
1828
|
+
const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
|
|
1829
|
+
for (const toolCall of toolCalls) {
|
|
1830
|
+
totalTokens += toolCallOverhead;
|
|
1831
|
+
const fn = toolCall["function"];
|
|
1832
|
+
if (fn && typeof fn === "object" && !Array.isArray(fn)) {
|
|
1833
|
+
const fnRecord = fn;
|
|
1834
|
+
totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
|
|
1835
|
+
totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
const toolCallId = this.extractToolCallIdForTokenEstimate(message);
|
|
1839
|
+
if (toolCallId) {
|
|
1840
|
+
totalTokens += this.estimateTokens(toolCallId, options);
|
|
1841
|
+
}
|
|
1842
|
+
return totalTokens;
|
|
1843
|
+
}
|
|
1844
|
+
static estimateMessageTokensPrecise(message, modelIdentifier) {
|
|
1845
|
+
return this.estimateMessageTokens(message, {
|
|
1846
|
+
encoding: modelIdentifier,
|
|
1847
|
+
toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
|
|
1848
|
+
});
|
|
1849
|
+
}
|
|
1850
|
+
static estimateMessagesTokensPrecise(messages, modelIdentifier) {
|
|
1851
|
+
return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
|
|
1852
|
+
}
|
|
1853
|
+
static extractToolCallsForTokenEstimate(message) {
|
|
1854
|
+
const direct = "tool_calls" in message ? message.tool_calls : void 0;
|
|
1855
|
+
if (Array.isArray(direct)) return direct;
|
|
1856
|
+
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1857
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
|
|
1858
|
+
const metadataRecord = metadata;
|
|
1859
|
+
const metadataToolCalls = metadataRecord["tool_calls"];
|
|
1860
|
+
return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
|
|
1861
|
+
}
|
|
1862
|
+
static extractToolCallIdForTokenEstimate(message) {
|
|
1863
|
+
if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
|
|
1864
|
+
return message.tool_call_id;
|
|
1865
|
+
}
|
|
1866
|
+
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1867
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
|
|
1868
|
+
const metadataRecord = metadata;
|
|
1869
|
+
const toolCallId = metadataRecord["tool_call_id"];
|
|
1870
|
+
return typeof toolCallId === "string" ? toolCallId : void 0;
|
|
1871
|
+
}
|
|
1872
|
+
static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
|
|
1873
|
+
if (!text || maxTokens <= 0) return "";
|
|
1874
|
+
const encoder = this.getEncoder(modelIdentifier);
|
|
1875
|
+
const tokens = encoder.encode(text);
|
|
1876
|
+
if (tokens.length <= maxTokens) {
|
|
1877
|
+
return text;
|
|
1878
|
+
}
|
|
1879
|
+
let truncatedTokens;
|
|
1880
|
+
const ellipsis = "...";
|
|
1881
|
+
switch (strategy) {
|
|
1882
|
+
case "start":
|
|
1883
|
+
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1884
|
+
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1885
|
+
case "end":
|
|
1886
|
+
truncatedTokens = tokens.slice(tokens.length - maxTokens);
|
|
1887
|
+
return ellipsis + encoder.decode(truncatedTokens);
|
|
1888
|
+
case "middle": {
|
|
1889
|
+
const half = Math.floor(maxTokens / 2);
|
|
1890
|
+
const head = tokens.slice(0, half);
|
|
1891
|
+
const tail = tokens.slice(tokens.length - (maxTokens - half));
|
|
1892
|
+
return encoder.decode(head) + ellipsis + encoder.decode(tail);
|
|
1893
|
+
}
|
|
1894
|
+
default:
|
|
1895
|
+
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1896
|
+
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
static cleanup() {
|
|
1900
|
+
for (const encoder of this.encoderCache.values()) {
|
|
1901
|
+
encoder.free();
|
|
1902
|
+
}
|
|
1903
|
+
this.encoderCache.clear();
|
|
1904
|
+
}
|
|
1905
|
+
};
|
|
1906
|
+
function normalizePositiveNumber(value, fallback) {
|
|
1907
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
1908
|
+
}
|
|
1909
|
+
function normalizeNonNegativeInteger(value, fallback) {
|
|
1910
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
1911
|
+
return fallback;
|
|
1912
|
+
}
|
|
1913
|
+
return Math.max(0, Math.floor(value));
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
// src/shared/defaultTokenizerPort.ts
|
|
1917
|
+
var DefaultTokenizerPort = class {
|
|
1918
|
+
constructor(config = {}) {
|
|
1919
|
+
this.config = config;
|
|
1920
|
+
}
|
|
1921
|
+
config;
|
|
1922
|
+
estimateText(text, _modelId) {
|
|
1923
|
+
return TokenCalculator.estimateTokens(text, {
|
|
1924
|
+
encoding: this.config.encoding,
|
|
1925
|
+
avgCharsPerToken: this.config.avgCharsPerToken
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
estimateMessage(message, _modelId) {
|
|
1929
|
+
return TokenCalculator.estimateMessageTokens(message, {
|
|
1930
|
+
encoding: this.config.encoding,
|
|
1931
|
+
avgCharsPerToken: this.config.avgCharsPerToken,
|
|
1932
|
+
toolCallOverhead: this.config.toolCallOverhead
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
};
|
|
1936
|
+
function createDefaultTokenizerPort(config = {}) {
|
|
1937
|
+
return new DefaultTokenizerPort(config);
|
|
1938
|
+
}
|
|
1508
1939
|
|
|
1509
1940
|
// src/runtime-kernel/llm/toolCallUtils.ts
|
|
1510
1941
|
function isRecord2(value) {
|
|
@@ -1572,15 +2003,15 @@ function splitConcatenatedJsonObjects(input) {
|
|
|
1572
2003
|
}
|
|
1573
2004
|
|
|
1574
2005
|
// src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
|
|
1575
|
-
function
|
|
2006
|
+
function readNonEmptyString2(value) {
|
|
1576
2007
|
if (typeof value !== "string") return void 0;
|
|
1577
2008
|
const trimmed = value.trim();
|
|
1578
2009
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
1579
2010
|
}
|
|
1580
2011
|
function resolveConversationIdForRuntimeEvents(toolContext) {
|
|
1581
|
-
const fromCamel =
|
|
2012
|
+
const fromCamel = readNonEmptyString2(toolContext?.conversationId);
|
|
1582
2013
|
if (fromCamel) return fromCamel;
|
|
1583
|
-
const fromSnake = toolContext ?
|
|
2014
|
+
const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
|
|
1584
2015
|
if (fromSnake) return fromSnake;
|
|
1585
2016
|
return generateMessageId();
|
|
1586
2017
|
}
|
|
@@ -1651,6 +2082,13 @@ function resolveUsage(response) {
|
|
|
1651
2082
|
}
|
|
1652
2083
|
return response.usage;
|
|
1653
2084
|
}
|
|
2085
|
+
function resolveCanonicalUsage(response) {
|
|
2086
|
+
if (!response || typeof response === "string") {
|
|
2087
|
+
return void 0;
|
|
2088
|
+
}
|
|
2089
|
+
const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
|
|
2090
|
+
return parsed.success ? parsed.data : void 0;
|
|
2091
|
+
}
|
|
1654
2092
|
function resolveToolCalls(response) {
|
|
1655
2093
|
if (!response || typeof response === "string") {
|
|
1656
2094
|
return void 0;
|
|
@@ -1705,181 +2143,54 @@ var contextAuditMiddleware = async (ctx, stage, next) => {
|
|
|
1705
2143
|
});
|
|
1706
2144
|
}
|
|
1707
2145
|
};
|
|
1708
|
-
var
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
static OVERHEAD_PER_TOOL_CALL = 10;
|
|
1713
|
-
static encoderCache = /* @__PURE__ */ new Map();
|
|
1714
|
-
static DEFAULT_ENCODING = "cl100k_base";
|
|
1715
|
-
static SUPPORTED_ENCODINGS = [
|
|
1716
|
-
"gpt2",
|
|
1717
|
-
"r50k_base",
|
|
1718
|
-
"p50k_base",
|
|
1719
|
-
"p50k_edit",
|
|
1720
|
-
"cl100k_base",
|
|
1721
|
-
"o200k_base"
|
|
1722
|
-
];
|
|
1723
|
-
static resolveEncodingFromModelIdentifier(modelIdentifier) {
|
|
1724
|
-
const normalized = (modelIdentifier || "").trim().toLowerCase();
|
|
1725
|
-
if (this.isSupportedEncodingName(normalized)) {
|
|
1726
|
-
return normalized;
|
|
1727
|
-
}
|
|
1728
|
-
if (normalized.includes("deepseek")) {
|
|
1729
|
-
return "cl100k_base";
|
|
1730
|
-
}
|
|
1731
|
-
if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
|
|
1732
|
-
return "o200k_base";
|
|
1733
|
-
}
|
|
1734
|
-
if (normalized.includes("gemini") || normalized.includes("claude")) {
|
|
1735
|
-
return "cl100k_base";
|
|
1736
|
-
}
|
|
1737
|
-
return this.DEFAULT_ENCODING;
|
|
1738
|
-
}
|
|
1739
|
-
static isSupportedEncodingName(value) {
|
|
1740
|
-
return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
|
|
1741
|
-
}
|
|
1742
|
-
static getEncoder(modelIdentifierOrEncoding) {
|
|
1743
|
-
const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
|
|
1744
|
-
const cached = this.encoderCache.get(encodingName);
|
|
1745
|
-
if (cached) {
|
|
1746
|
-
return cached;
|
|
1747
|
-
}
|
|
1748
|
-
const encoder = get_encoding(encodingName);
|
|
1749
|
-
this.encoderCache.set(encodingName, encoder);
|
|
1750
|
-
return encoder;
|
|
1751
|
-
}
|
|
1752
|
-
static estimateTokensRough(text, _modelIdentifier) {
|
|
1753
|
-
if (!text) return 0;
|
|
1754
|
-
const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
|
|
1755
|
-
const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
|
|
1756
|
-
const byteLength = new TextEncoder().encode(text).length;
|
|
1757
|
-
return Math.ceil(byteLength / ratio);
|
|
1758
|
-
}
|
|
1759
|
-
static estimateTokens(text, options = {}) {
|
|
1760
|
-
if (!text) return 0;
|
|
1761
|
-
if (options.encoding) {
|
|
1762
|
-
try {
|
|
1763
|
-
return this.estimateTokensPrecise(text, options.encoding);
|
|
1764
|
-
} catch {
|
|
1765
|
-
}
|
|
1766
|
-
}
|
|
1767
|
-
const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
|
|
1768
|
-
return Math.ceil(text.length / avgCharsPerToken);
|
|
1769
|
-
}
|
|
1770
|
-
static estimateTokensPrecise(text, modelIdentifier) {
|
|
1771
|
-
if (!text) return 0;
|
|
1772
|
-
const encoder = this.getEncoder(modelIdentifier);
|
|
1773
|
-
return encoder.encode(text).length;
|
|
1774
|
-
}
|
|
1775
|
-
static estimateMessageTokens(message, options = {}) {
|
|
1776
|
-
let totalTokens = this.OVERHEAD_PER_MESSAGE;
|
|
1777
|
-
if (message.content) {
|
|
1778
|
-
totalTokens += this.estimateTokens(String(message.content), options);
|
|
1779
|
-
}
|
|
1780
|
-
const toolCalls = this.extractToolCallsForTokenEstimate(message);
|
|
1781
|
-
const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
|
|
1782
|
-
for (const toolCall of toolCalls) {
|
|
1783
|
-
totalTokens += toolCallOverhead;
|
|
1784
|
-
const fn = toolCall["function"];
|
|
1785
|
-
if (fn && typeof fn === "object" && !Array.isArray(fn)) {
|
|
1786
|
-
const fnRecord = fn;
|
|
1787
|
-
totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
|
|
1788
|
-
totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
|
|
1789
|
-
}
|
|
1790
|
-
}
|
|
1791
|
-
const toolCallId = this.extractToolCallIdForTokenEstimate(message);
|
|
1792
|
-
if (toolCallId) {
|
|
1793
|
-
totalTokens += this.estimateTokens(toolCallId, options);
|
|
1794
|
-
}
|
|
1795
|
-
return totalTokens;
|
|
1796
|
-
}
|
|
1797
|
-
static estimateMessageTokensPrecise(message, modelIdentifier) {
|
|
1798
|
-
return this.estimateMessageTokens(message, {
|
|
1799
|
-
encoding: modelIdentifier,
|
|
1800
|
-
toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
|
|
1801
|
-
});
|
|
1802
|
-
}
|
|
1803
|
-
static estimateMessagesTokensPrecise(messages, modelIdentifier) {
|
|
1804
|
-
return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
|
|
1805
|
-
}
|
|
1806
|
-
static extractToolCallsForTokenEstimate(message) {
|
|
1807
|
-
const direct = "tool_calls" in message ? message.tool_calls : void 0;
|
|
1808
|
-
if (Array.isArray(direct)) return direct;
|
|
1809
|
-
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1810
|
-
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
|
|
1811
|
-
const metadataRecord = metadata;
|
|
1812
|
-
const metadataToolCalls = metadataRecord["tool_calls"];
|
|
1813
|
-
return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
|
|
1814
|
-
}
|
|
1815
|
-
static extractToolCallIdForTokenEstimate(message) {
|
|
1816
|
-
if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
|
|
1817
|
-
return message.tool_call_id;
|
|
1818
|
-
}
|
|
1819
|
-
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1820
|
-
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
|
|
1821
|
-
const metadataRecord = metadata;
|
|
1822
|
-
const toolCallId = metadataRecord["tool_call_id"];
|
|
1823
|
-
return typeof toolCallId === "string" ? toolCallId : void 0;
|
|
1824
|
-
}
|
|
1825
|
-
static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
|
|
1826
|
-
if (!text || maxTokens <= 0) return "";
|
|
1827
|
-
const encoder = this.getEncoder(modelIdentifier);
|
|
1828
|
-
const tokens = encoder.encode(text);
|
|
1829
|
-
if (tokens.length <= maxTokens) {
|
|
1830
|
-
return text;
|
|
1831
|
-
}
|
|
1832
|
-
let truncatedTokens;
|
|
1833
|
-
const ellipsis = "...";
|
|
1834
|
-
switch (strategy) {
|
|
1835
|
-
case "start":
|
|
1836
|
-
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1837
|
-
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1838
|
-
case "end":
|
|
1839
|
-
truncatedTokens = tokens.slice(tokens.length - maxTokens);
|
|
1840
|
-
return ellipsis + encoder.decode(truncatedTokens);
|
|
1841
|
-
case "middle": {
|
|
1842
|
-
const half = Math.floor(maxTokens / 2);
|
|
1843
|
-
const head = tokens.slice(0, half);
|
|
1844
|
-
const tail = tokens.slice(tokens.length - (maxTokens - half));
|
|
1845
|
-
return encoder.decode(head) + ellipsis + encoder.decode(tail);
|
|
1846
|
-
}
|
|
1847
|
-
default:
|
|
1848
|
-
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1849
|
-
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1850
|
-
}
|
|
1851
|
-
}
|
|
1852
|
-
static cleanup() {
|
|
1853
|
-
for (const encoder of this.encoderCache.values()) {
|
|
1854
|
-
encoder.free();
|
|
1855
|
-
}
|
|
1856
|
-
this.encoderCache.clear();
|
|
1857
|
-
}
|
|
1858
|
-
};
|
|
1859
|
-
function normalizePositiveNumber(value, fallback) {
|
|
1860
|
-
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
2146
|
+
var als = new AsyncLocalStorage();
|
|
2147
|
+
function readTokenCount(record, key) {
|
|
2148
|
+
const value = record[key];
|
|
2149
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
|
|
1861
2150
|
}
|
|
1862
|
-
function
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
return Math.max(0, Math.floor(value));
|
|
2151
|
+
function readRecord(record, key) {
|
|
2152
|
+
const value = record[key];
|
|
2153
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
2154
|
+
return Object.fromEntries(Object.entries(value));
|
|
1867
2155
|
}
|
|
1868
|
-
|
|
1869
|
-
|
|
2156
|
+
function normalizedUsageFromCanonical(canonicalUsage) {
|
|
2157
|
+
return {
|
|
2158
|
+
promptTokens: canonicalUsage.inputTokens,
|
|
2159
|
+
completionTokens: canonicalUsage.outputTokens,
|
|
2160
|
+
totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
|
|
2161
|
+
canonicalUsage
|
|
2162
|
+
};
|
|
2163
|
+
}
|
|
2164
|
+
function normalizeCanonicalLlmUsage(usage2) {
|
|
1870
2165
|
if (!usage2 || typeof usage2 !== "object" || Array.isArray(usage2)) return void 0;
|
|
1871
2166
|
const rec = usage2;
|
|
1872
|
-
const
|
|
1873
|
-
const
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
const
|
|
1878
|
-
const
|
|
1879
|
-
const
|
|
1880
|
-
const
|
|
1881
|
-
|
|
1882
|
-
|
|
2167
|
+
const inputTokens = readTokenCount(rec, "prompt_tokens");
|
|
2168
|
+
const outputTokens = readTokenCount(rec, "completion_tokens");
|
|
2169
|
+
if (inputTokens === void 0 || outputTokens === void 0) {
|
|
2170
|
+
return void 0;
|
|
2171
|
+
}
|
|
2172
|
+
const promptDetails = readRecord(rec, "prompt_tokens_details");
|
|
2173
|
+
const completionDetails = readRecord(rec, "completion_tokens_details");
|
|
2174
|
+
const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
|
|
2175
|
+
const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
|
|
2176
|
+
const totalTokens = readTokenCount(rec, "total_tokens");
|
|
2177
|
+
if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
|
|
2178
|
+
return void 0;
|
|
2179
|
+
}
|
|
2180
|
+
return {
|
|
2181
|
+
inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
|
|
2182
|
+
outputTokens,
|
|
2183
|
+
...reasoningTokens !== void 0 ? { reasoningTokens } : {},
|
|
2184
|
+
...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
|
|
2185
|
+
...totalTokens !== void 0 ? { totalTokens } : {},
|
|
2186
|
+
source: "provider-response-usage",
|
|
2187
|
+
confidence: "actual",
|
|
2188
|
+
rawUsage: usage2
|
|
2189
|
+
};
|
|
2190
|
+
}
|
|
2191
|
+
function normalizeLlmUsage(usage2) {
|
|
2192
|
+
const canonicalUsage = normalizeCanonicalLlmUsage(usage2);
|
|
2193
|
+
return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
|
|
1883
2194
|
}
|
|
1884
2195
|
function recordLlmCallTelemetry(entry) {
|
|
1885
2196
|
const store = als.getStore();
|
|
@@ -1893,17 +2204,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1893
2204
|
if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
|
|
1894
2205
|
return;
|
|
1895
2206
|
}
|
|
1896
|
-
const
|
|
2207
|
+
const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
|
|
2208
|
+
const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
|
|
1897
2209
|
const respText = extractResponseText(ctx.llmResp);
|
|
1898
2210
|
const normalizedUsage = normalizedUsageFromProvider ?? (() => {
|
|
1899
2211
|
try {
|
|
1900
|
-
const promptTokens =
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
2212
|
+
const promptTokens = ctx.llmMessages.reduce(
|
|
2213
|
+
(total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
|
|
2214
|
+
0
|
|
2215
|
+
);
|
|
2216
|
+
const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
|
|
2217
|
+
return normalizedUsageFromCanonical({
|
|
2218
|
+
inputTokens: promptTokens,
|
|
2219
|
+
outputTokens: completionTokens,
|
|
2220
|
+
totalTokens: promptTokens + completionTokens,
|
|
2221
|
+
source: "local-estimate",
|
|
2222
|
+
confidence: "estimate"
|
|
2223
|
+
});
|
|
1907
2224
|
} catch {
|
|
1908
2225
|
return void 0;
|
|
1909
2226
|
}
|
|
@@ -1913,7 +2230,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1913
2230
|
stream: ctx.input.stream === true,
|
|
1914
2231
|
startedAt: ctx.llmCallStartedAt,
|
|
1915
2232
|
durationMs: ctx.llmCallDurationMs,
|
|
1916
|
-
usage: normalizedUsage
|
|
2233
|
+
usage: normalizedUsage,
|
|
2234
|
+
...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
|
|
1917
2235
|
});
|
|
1918
2236
|
ctx.telemetry.emit({
|
|
1919
2237
|
kind: "llm_call",
|
|
@@ -1921,6 +2239,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1921
2239
|
stream: ctx.input.stream === true,
|
|
1922
2240
|
durationMs: ctx.llmCallDurationMs,
|
|
1923
2241
|
usage: normalizedUsage,
|
|
2242
|
+
...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
|
|
1924
2243
|
scope: {
|
|
1925
2244
|
conversationId: ctx.conversationId || void 0,
|
|
1926
2245
|
turnId: ctx.turnId,
|
|
@@ -1937,7 +2256,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
|
|
|
1937
2256
|
if (stage.id !== "execute_llm") {
|
|
1938
2257
|
return;
|
|
1939
2258
|
}
|
|
1940
|
-
const normalized =
|
|
2259
|
+
const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
|
|
1941
2260
|
if (!normalized) {
|
|
1942
2261
|
return;
|
|
1943
2262
|
}
|
|
@@ -2064,10 +2383,10 @@ var contextBudgetWarningTemplate = (ctx) => {
|
|
|
2064
2383
|
return [
|
|
2065
2384
|
`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u9884\u7B97\u544A\u8B66\uFF1A\u4F60\u5DF2\u6267\u884C\u4E86 ${displayStep}/${displayMax} \u6B65\uFF0C\u4E0A\u4E0B\u6587\u7A7A\u95F4\u5373\u5C06\u8017\u5C3D\u3002`,
|
|
2066
2385
|
"\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
|
|
2067
|
-
"1. \
|
|
2386
|
+
"1. \u5148\u786E\u8BA4\u5173\u952E\u8FDB\u5C55\u3001\u7EA6\u675F\u3001\u4E0B\u4E00\u6B65\u5DF2\u7ECF\u8FDB\u5165 TaskState\uFF1B\u5982\u679C\u6CA1\u6709\uFF0C\u8BF7\u8C03\u7528 taskstate_write \u66F4\u65B0\u3002",
|
|
2068
2387
|
`2. \u8C03\u7528 ${checkpointToolName} \u5DE5\u5177\uFF0C\u4F20\u5165 summary\uFF08\u9636\u6BB5\u8FC7\u6E21\u6458\u8981\uFF09\u548C taskstate\uFF08\u6700\u65B0\u4EFB\u52A1\u72B6\u6001\uFF09\u3002`,
|
|
2069
2388
|
' \u8FD9\u4F1A\u4E00\u6B21\u6027\u5B8C\u6210"\u4FDD\u5B58\u72B6\u6001 + \u6E05\u7406\u5386\u53F2"\uFF0Ccheckpoint tool_output \u4E2D\u4F1A\u4FDD\u7559\u4F60\u7684 TaskState \u5FEB\u7167\u3002',
|
|
2070
|
-
"3. \u6E05\u7406\u540E\u4F60\u7684\u4E0A\u4E0B\u6587\u5C06\u53EA\u4FDD\u7559\uFF1Acheckpoint \u5DE5\u5177\u5BF9\uFF08\u542B\u6458\u8981 + TaskState\uFF09+ \u6700\u8FD1 2 \u5BF9\u5DE5\u5177\u4EA4\u4E92\u3002\
|
|
2389
|
+
"3. \u6E05\u7406\u540E\u4F60\u7684\u4E0A\u4E0B\u6587\u5C06\u53EA\u4FDD\u7559\uFF1Acheckpoint \u5DE5\u5177\u5BF9\uFF08\u542B\u6458\u8981 + TaskState\uFF09+ \u6700\u8FD1 2 \u5BF9\u5DE5\u5177\u4EA4\u4E92\u3002\u9700\u8981\u957F\u671F\u4EA4\u4ED8\u7ED9\u7528\u6237\u7684\u5185\u5BB9\u8BF7\u5199\u5165 Workspace \u6587\u4EF6\u3002"
|
|
2071
2390
|
].join("\n");
|
|
2072
2391
|
};
|
|
2073
2392
|
var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
|
|
@@ -2375,6 +2694,16 @@ function createApplySystemReminderStage() {
|
|
|
2375
2694
|
};
|
|
2376
2695
|
}
|
|
2377
2696
|
|
|
2697
|
+
// src/runtime-kernel/token-accounting/functions.ts
|
|
2698
|
+
function createContextComponentLedgerEntry(input) {
|
|
2699
|
+
return {
|
|
2700
|
+
...input,
|
|
2701
|
+
kind: "context-component",
|
|
2702
|
+
components: [...input.components],
|
|
2703
|
+
totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
|
|
2704
|
+
};
|
|
2705
|
+
}
|
|
2706
|
+
|
|
2378
2707
|
// src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
|
|
2379
2708
|
var logger4 = new Logger("GraphAgentExecutor");
|
|
2380
2709
|
function createBuildContextStage(dependencies) {
|
|
@@ -2391,6 +2720,23 @@ function createBuildContextStage(dependencies) {
|
|
|
2391
2720
|
ctx.mode = contextBuildResult.mode;
|
|
2392
2721
|
ctx.llmMessages = contextBuildResult.llmMessages;
|
|
2393
2722
|
ctx.contextTrace = contextBuildResult.contextTrace;
|
|
2723
|
+
if (contextBuildResult.tokenEstimate) {
|
|
2724
|
+
const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
|
|
2725
|
+
ctx.telemetry.emit({
|
|
2726
|
+
kind: "context_build",
|
|
2727
|
+
modelId: ctx.modelId,
|
|
2728
|
+
mode: contextBuildResult.mode,
|
|
2729
|
+
tokenEstimate: contextBuildResult.tokenEstimate,
|
|
2730
|
+
...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
|
|
2731
|
+
...tokenLedgerEntry ? { tokenLedgerEntry } : {},
|
|
2732
|
+
scope: {
|
|
2733
|
+
conversationId: ctx.conversationId,
|
|
2734
|
+
runId: ctx.input.toolContext?.runId,
|
|
2735
|
+
parentRunId: ctx.input.toolContext?.parentRunId,
|
|
2736
|
+
turnId: ctx.turnId
|
|
2737
|
+
}
|
|
2738
|
+
});
|
|
2739
|
+
}
|
|
2394
2740
|
for (const event of contextBuildResult.summaryEvents) {
|
|
2395
2741
|
if (!isHistorySummaryEvent(event)) {
|
|
2396
2742
|
continue;
|
|
@@ -2405,6 +2751,24 @@ function createBuildContextStage(dependencies) {
|
|
|
2405
2751
|
}
|
|
2406
2752
|
};
|
|
2407
2753
|
}
|
|
2754
|
+
function createContextLedgerEntry(ctx, contextBuildResult) {
|
|
2755
|
+
const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
|
|
2756
|
+
if (keptComponents.length === 0) {
|
|
2757
|
+
return void 0;
|
|
2758
|
+
}
|
|
2759
|
+
const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
|
|
2760
|
+
const createdAt = Date.now();
|
|
2761
|
+
return createContextComponentLedgerEntry({
|
|
2762
|
+
id: `context_${runId}_${ctx.turnId}_${createdAt}`,
|
|
2763
|
+
conversationId: ctx.conversationId,
|
|
2764
|
+
runId,
|
|
2765
|
+
parentRunId: ctx.input.toolContext?.parentRunId,
|
|
2766
|
+
turnId: ctx.turnId,
|
|
2767
|
+
route: contextBuildResult.tokenEstimate?.route,
|
|
2768
|
+
createdAt,
|
|
2769
|
+
components: keptComponents
|
|
2770
|
+
});
|
|
2771
|
+
}
|
|
2408
2772
|
|
|
2409
2773
|
// src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
|
|
2410
2774
|
function createBuildDecisionStage(dependencies) {
|
|
@@ -2525,7 +2889,7 @@ function createExecuteLlmStage(dependencies) {
|
|
|
2525
2889
|
streamEventHandler,
|
|
2526
2890
|
ctx.signal,
|
|
2527
2891
|
(fallbackModelId) => {
|
|
2528
|
-
ctx.cloudQuotaFallbackAppliedModelId =
|
|
2892
|
+
ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
|
|
2529
2893
|
},
|
|
2530
2894
|
(info) => {
|
|
2531
2895
|
ctx.modelFallbackAudit = info;
|
|
@@ -2569,7 +2933,7 @@ function createPrepareCallStage(dependencies) {
|
|
|
2569
2933
|
return {
|
|
2570
2934
|
id: "prepare_call",
|
|
2571
2935
|
async run(ctx) {
|
|
2572
|
-
const lockedRunModelId =
|
|
2936
|
+
const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
|
|
2573
2937
|
const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
|
|
2574
2938
|
ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
|
|
2575
2939
|
await emitAuditEnvelope(ctx.audit, {
|
|
@@ -2635,19 +2999,21 @@ var GraphAgentExecutor = class {
|
|
|
2635
2999
|
modelCatalog;
|
|
2636
3000
|
telemetryPort;
|
|
2637
3001
|
auditPort;
|
|
3002
|
+
tokenizer;
|
|
2638
3003
|
stages;
|
|
2639
3004
|
middlewares;
|
|
2640
3005
|
constructor(dependencies) {
|
|
2641
3006
|
this.llmCaller = dependencies.llmCaller;
|
|
2642
3007
|
this.toolRuntime = dependencies.toolRuntime;
|
|
2643
3008
|
this.contextBuilder = dependencies.contextBuilder;
|
|
2644
|
-
this.cloudQuotaFallbackModelId =
|
|
3009
|
+
this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
|
|
2645
3010
|
this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
|
|
2646
3011
|
this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
|
|
2647
3012
|
modelCatalog: this.modelCatalog
|
|
2648
3013
|
});
|
|
2649
3014
|
this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
|
|
2650
3015
|
this.auditPort = dependencies.auditPort ?? noopAudit;
|
|
3016
|
+
this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
|
|
2651
3017
|
this.stages = [
|
|
2652
3018
|
createPrepareCallStage({
|
|
2653
3019
|
modelResolver: this.modelResolver,
|
|
@@ -2689,9 +3055,10 @@ var GraphAgentExecutor = class {
|
|
|
2689
3055
|
llmMessages: [],
|
|
2690
3056
|
mode: input.request.mode === "chat" ? "chat" : "agent",
|
|
2691
3057
|
conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
|
|
2692
|
-
turnId:
|
|
3058
|
+
turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
|
|
2693
3059
|
telemetry: this.telemetryPort,
|
|
2694
|
-
audit: this.auditPort
|
|
3060
|
+
audit: this.auditPort,
|
|
3061
|
+
tokenizer: this.tokenizer
|
|
2695
3062
|
};
|
|
2696
3063
|
logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
|
|
2697
3064
|
stream: input.stream === true,
|
|
@@ -2739,18 +3106,18 @@ function isSummarizationCallbacks(value) {
|
|
|
2739
3106
|
function isGraphSseSink(value) {
|
|
2740
3107
|
return typeof value === "function";
|
|
2741
3108
|
}
|
|
2742
|
-
function
|
|
3109
|
+
function readNonEmptyString3(value) {
|
|
2743
3110
|
if (typeof value !== "string") return void 0;
|
|
2744
3111
|
const trimmed = value.trim();
|
|
2745
3112
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
2746
3113
|
}
|
|
2747
3114
|
function readGraphAgentLocal(local) {
|
|
2748
3115
|
const source = local ?? {};
|
|
2749
|
-
const answerId =
|
|
3116
|
+
const answerId = readNonEmptyString3(source.answerId);
|
|
2750
3117
|
const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
|
|
2751
3118
|
return {
|
|
2752
|
-
conversationId:
|
|
2753
|
-
turnId:
|
|
3119
|
+
conversationId: readNonEmptyString3(source.conversationId) ?? "",
|
|
3120
|
+
turnId: readNonEmptyString3(source.turnId),
|
|
2754
3121
|
request: isAgentInvocationRequest(source.request) ? source.request : void 0,
|
|
2755
3122
|
toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
|
|
2756
3123
|
history: isRuntimeEventArray(source.history) ? source.history : [],
|
|
@@ -3515,7 +3882,7 @@ var LlmNode = class {
|
|
|
3515
3882
|
function isRecord8(value) {
|
|
3516
3883
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3517
3884
|
}
|
|
3518
|
-
function
|
|
3885
|
+
function readNonEmptyString4(value) {
|
|
3519
3886
|
if (typeof value !== "string") {
|
|
3520
3887
|
return void 0;
|
|
3521
3888
|
}
|
|
@@ -3537,7 +3904,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
|
|
|
3537
3904
|
return void 0;
|
|
3538
3905
|
}
|
|
3539
3906
|
if (toolName === "write_report") {
|
|
3540
|
-
const report =
|
|
3907
|
+
const report = readNonEmptyString4(data.report);
|
|
3541
3908
|
if (!report) {
|
|
3542
3909
|
throw new Error("[write_report] \u5DE5\u5177\u8F93\u51FA\u7F3A\u5C11 data.report\uFF08\u5FC5\u987B\u63D0\u4F9B\u5B8C\u6574\u62A5\u544A\u6B63\u6587\uFF09");
|
|
3543
3910
|
}
|
|
@@ -3547,7 +3914,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
|
|
|
3547
3914
|
if (data.success !== true) {
|
|
3548
3915
|
return void 0;
|
|
3549
3916
|
}
|
|
3550
|
-
const finalAnswer =
|
|
3917
|
+
const finalAnswer = readNonEmptyString4(data.final_answer);
|
|
3551
3918
|
if (!finalAnswer) {
|
|
3552
3919
|
throw new Error("[research_run_writer] \u5DE5\u5177\u8F93\u51FA\u7F3A\u5C11 data.final_answer\uFF08success=true \u65F6\u5FC5\u987B\u63D0\u4F9B\u6700\u7EC8\u62A5\u544A\u6B63\u6587\uFF09");
|
|
3553
3920
|
}
|
|
@@ -3656,11 +4023,11 @@ function buildToolOutputUiMeta(params) {
|
|
|
3656
4023
|
}
|
|
3657
4024
|
async function applyObservationGovernance(params) {
|
|
3658
4025
|
if (!params.structuredObservation || !isRecord9(params.parsed)) {
|
|
3659
|
-
return;
|
|
4026
|
+
return {};
|
|
3660
4027
|
}
|
|
3661
4028
|
const policy = resolveToolObservationGovernancePolicy(params.policy);
|
|
3662
4029
|
if (!policy.enabled) {
|
|
3663
|
-
return;
|
|
4030
|
+
return {};
|
|
3664
4031
|
}
|
|
3665
4032
|
const truncated = await params.observationPreview.truncateObservation({
|
|
3666
4033
|
context: params.toolContext,
|
|
@@ -3674,13 +4041,37 @@ async function applyObservationGovernance(params) {
|
|
|
3674
4041
|
})
|
|
3675
4042
|
});
|
|
3676
4043
|
if (!truncated.truncated) {
|
|
3677
|
-
return;
|
|
4044
|
+
return {};
|
|
3678
4045
|
}
|
|
3679
4046
|
params.parsed["observation"] = truncated.preview;
|
|
3680
4047
|
const data = params.parsed["data"];
|
|
3681
4048
|
if (isRecord9(data) && !("tool_output_store" in data)) {
|
|
3682
4049
|
data["tool_output_store"] = { blob_id: truncated.blob_id };
|
|
3683
4050
|
}
|
|
4051
|
+
return {
|
|
4052
|
+
observationTruncation: buildObservationTruncationMeta({
|
|
4053
|
+
originalText: params.structuredObservation,
|
|
4054
|
+
previewText: truncated.preview,
|
|
4055
|
+
originalChars: truncated.originalChars,
|
|
4056
|
+
previewChars: truncated.previewChars,
|
|
4057
|
+
originalLines: truncated.originalLines,
|
|
4058
|
+
previewLines: truncated.previewLines
|
|
4059
|
+
})
|
|
4060
|
+
};
|
|
4061
|
+
}
|
|
4062
|
+
function buildObservationTruncationMeta(input) {
|
|
4063
|
+
return {
|
|
4064
|
+
originalChars: input.originalChars ?? input.originalText.length,
|
|
4065
|
+
previewChars: input.previewChars ?? input.previewText.length,
|
|
4066
|
+
originalLines: input.originalLines ?? countLines(input.originalText),
|
|
4067
|
+
previewLines: input.previewLines ?? countLines(input.previewText)
|
|
4068
|
+
};
|
|
4069
|
+
}
|
|
4070
|
+
function countLines(value) {
|
|
4071
|
+
if (value.length === 0) {
|
|
4072
|
+
return 0;
|
|
4073
|
+
}
|
|
4074
|
+
return value.split(/\r\n|\r|\n/).length;
|
|
3684
4075
|
}
|
|
3685
4076
|
|
|
3686
4077
|
// src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
|
|
@@ -4556,7 +4947,7 @@ var ToolNode = class {
|
|
|
4556
4947
|
parentRunId: context.toolContext.parentRunId
|
|
4557
4948
|
});
|
|
4558
4949
|
applyProtocolFuseState(context.local);
|
|
4559
|
-
await applyObservationGovernance({
|
|
4950
|
+
const observationGovernance = await applyObservationGovernance({
|
|
4560
4951
|
parsed: context.parsed,
|
|
4561
4952
|
toolName: context.toolName,
|
|
4562
4953
|
toolContext: context.toolContext,
|
|
@@ -4583,6 +4974,12 @@ var ToolNode = class {
|
|
|
4583
4974
|
runtimeToolOutput,
|
|
4584
4975
|
execIdempotency: context.exec.idempotency
|
|
4585
4976
|
});
|
|
4977
|
+
if (runtimeToolOutput && observationGovernance.observationTruncation) {
|
|
4978
|
+
runtimeToolOutput.metadata = {
|
|
4979
|
+
...runtimeToolOutput.metadata ?? {},
|
|
4980
|
+
observationTruncation: observationGovernance.observationTruncation
|
|
4981
|
+
};
|
|
4982
|
+
}
|
|
4586
4983
|
const remainingCalls = context.calls.slice(1);
|
|
4587
4984
|
context.state.local = buildSuccessLocalState({
|
|
4588
4985
|
local: context.local,
|
|
@@ -4881,12 +5278,12 @@ function asRecord(value) {
|
|
|
4881
5278
|
}
|
|
4882
5279
|
return value;
|
|
4883
5280
|
}
|
|
4884
|
-
function summarizeCheckpoint(
|
|
5281
|
+
function summarizeCheckpoint(checkpointKey, state, savedAt) {
|
|
4885
5282
|
const local = asRecord(state.local);
|
|
4886
5283
|
const executorLocal = asRecord(local?.executorLocal);
|
|
4887
5284
|
const pendingToolCalls = local?.pendingToolCalls;
|
|
4888
5285
|
return {
|
|
4889
|
-
|
|
5286
|
+
checkpointKey,
|
|
4890
5287
|
schemaVersion: state.schemaVersion ?? 1,
|
|
4891
5288
|
savedAt,
|
|
4892
5289
|
currentNode: state.nodeId,
|
|
@@ -4905,25 +5302,25 @@ var MemoryCheckpointer = class {
|
|
|
4905
5302
|
local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
|
|
4906
5303
|
};
|
|
4907
5304
|
}
|
|
4908
|
-
async load(
|
|
4909
|
-
const entry = this.store.get(
|
|
5305
|
+
async load(checkpointKey) {
|
|
5306
|
+
const entry = this.store.get(checkpointKey);
|
|
4910
5307
|
return entry ? this.cloneState(entry.state) : null;
|
|
4911
5308
|
}
|
|
4912
|
-
async save(
|
|
4913
|
-
this.store.set(
|
|
5309
|
+
async save(checkpointKey, state) {
|
|
5310
|
+
this.store.set(checkpointKey, {
|
|
4914
5311
|
state: this.cloneState(state),
|
|
4915
5312
|
savedAt: Date.now()
|
|
4916
5313
|
});
|
|
4917
5314
|
}
|
|
4918
|
-
async clear(
|
|
4919
|
-
this.store.delete(
|
|
5315
|
+
async clear(checkpointKey) {
|
|
5316
|
+
this.store.delete(checkpointKey);
|
|
4920
5317
|
}
|
|
4921
|
-
async peekMeta(
|
|
4922
|
-
const entry = this.store.get(
|
|
4923
|
-
return entry ? summarizeCheckpoint(
|
|
5318
|
+
async peekMeta(checkpointKey) {
|
|
5319
|
+
const entry = this.store.get(checkpointKey);
|
|
5320
|
+
return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
|
|
4924
5321
|
}
|
|
4925
5322
|
async list(filter = {}) {
|
|
4926
|
-
const summaries = Array.from(this.store.entries()).map(([
|
|
5323
|
+
const summaries = Array.from(this.store.entries()).map(([checkpointKey, entry]) => summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt)).filter((summary) => filter.savedAfter === void 0 ? true : summary.savedAt > filter.savedAfter).sort((left, right) => right.savedAt - left.savedAt);
|
|
4927
5324
|
if (filter.limit === void 0) {
|
|
4928
5325
|
return summaries;
|
|
4929
5326
|
}
|
|
@@ -5944,6 +6341,7 @@ async function callLlmStream(params) {
|
|
|
5944
6341
|
const streamAnswerId = generateMessageId();
|
|
5945
6342
|
let streamChunkSeq = 0;
|
|
5946
6343
|
let capturedUsage = void 0;
|
|
6344
|
+
let capturedCanonicalUsage = void 0;
|
|
5947
6345
|
const toolAccumulator = new ToolCallStreamAccumulator([
|
|
5948
6346
|
"markdown_edit",
|
|
5949
6347
|
"text_to_image",
|
|
@@ -6002,6 +6400,10 @@ async function callLlmStream(params) {
|
|
|
6002
6400
|
if (typeof chunk !== "object" || chunk === null) {
|
|
6003
6401
|
return;
|
|
6004
6402
|
}
|
|
6403
|
+
const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
|
|
6404
|
+
if (parsedCanonicalUsage.success) {
|
|
6405
|
+
capturedCanonicalUsage = parsedCanonicalUsage.data;
|
|
6406
|
+
}
|
|
6005
6407
|
if (chunk.content) {
|
|
6006
6408
|
emitThoughtComplete(thoughtSegmenter.onBoundary());
|
|
6007
6409
|
fullResponse += chunk.content;
|
|
@@ -6086,6 +6488,12 @@ async function callLlmStream(params) {
|
|
|
6086
6488
|
const onUsage = (usage2) => {
|
|
6087
6489
|
capturedUsage = usage2;
|
|
6088
6490
|
};
|
|
6491
|
+
const onCanonicalUsage = (usage2) => {
|
|
6492
|
+
const parsed = CanonicalLlmUsage.safeParse(usage2);
|
|
6493
|
+
if (parsed.success) {
|
|
6494
|
+
capturedCanonicalUsage = parsed.data;
|
|
6495
|
+
}
|
|
6496
|
+
};
|
|
6089
6497
|
await aiEngine.chatCompletionStream(
|
|
6090
6498
|
modelId,
|
|
6091
6499
|
messages,
|
|
@@ -6098,7 +6506,8 @@ async function callLlmStream(params) {
|
|
|
6098
6506
|
onError,
|
|
6099
6507
|
onFinish,
|
|
6100
6508
|
onThought,
|
|
6101
|
-
onUsage
|
|
6509
|
+
onUsage,
|
|
6510
|
+
onCanonicalUsage
|
|
6102
6511
|
);
|
|
6103
6512
|
if (streamError) {
|
|
6104
6513
|
throw streamError;
|
|
@@ -6106,12 +6515,13 @@ async function callLlmStream(params) {
|
|
|
6106
6515
|
emitThoughtComplete(thoughtSegmenter.finalize());
|
|
6107
6516
|
const mergedToolCalls = toolAccumulator.getToolCalls();
|
|
6108
6517
|
assertToolCallsHaveValidJsonArguments(mergedToolCalls);
|
|
6109
|
-
if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
|
|
6518
|
+
if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
|
|
6110
6519
|
return {
|
|
6111
6520
|
content: fullResponse,
|
|
6112
6521
|
tool_calls: mergedToolCalls,
|
|
6113
6522
|
reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
|
|
6114
|
-
...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
|
|
6523
|
+
...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
|
|
6524
|
+
...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
|
|
6115
6525
|
};
|
|
6116
6526
|
}
|
|
6117
6527
|
return fullResponse;
|
|
@@ -6161,6 +6571,10 @@ function tryCloudQuotaFallback({
|
|
|
6161
6571
|
}
|
|
6162
6572
|
|
|
6163
6573
|
// src/runtime-kernel/llm/usage-telemetry.ts
|
|
6574
|
+
function parseCanonicalUsage(value) {
|
|
6575
|
+
const parsed = CanonicalLlmUsage.safeParse(value);
|
|
6576
|
+
return parsed.success ? parsed.data : void 0;
|
|
6577
|
+
}
|
|
6164
6578
|
async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
|
|
6165
6579
|
const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
|
|
6166
6580
|
return normalizeCompletionResponse(response);
|
|
@@ -6171,6 +6585,7 @@ function normalizeCompletionResponse(response) {
|
|
|
6171
6585
|
}
|
|
6172
6586
|
if (isRecord17(response)) {
|
|
6173
6587
|
const usage2 = response["usage"];
|
|
6588
|
+
const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
|
|
6174
6589
|
const parsedToolCalls = toToolCalls(response["tool_calls"]);
|
|
6175
6590
|
if (parsedToolCalls) {
|
|
6176
6591
|
const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
|
|
@@ -6178,7 +6593,8 @@ function normalizeCompletionResponse(response) {
|
|
|
6178
6593
|
content: typeof response["content"] === "string" ? response["content"] : "",
|
|
6179
6594
|
tool_calls: parsedToolCalls,
|
|
6180
6595
|
reasoning_details: reasoningDetails,
|
|
6181
|
-
...usage2 !== void 0 ? { usage: usage2 } : {}
|
|
6596
|
+
...usage2 !== void 0 ? { usage: usage2 } : {},
|
|
6597
|
+
...canonicalUsage !== void 0 ? { canonicalUsage } : {}
|
|
6182
6598
|
};
|
|
6183
6599
|
}
|
|
6184
6600
|
}
|
|
@@ -6188,10 +6604,12 @@ function normalizeCompletionResponse(response) {
|
|
|
6188
6604
|
if (typeof response === "object") {
|
|
6189
6605
|
if (isRecord17(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
|
|
6190
6606
|
const usage2 = response["usage"];
|
|
6607
|
+
const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
|
|
6191
6608
|
return {
|
|
6192
6609
|
content: typeof response["content"] === "string" ? response["content"] : "",
|
|
6193
6610
|
reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
|
|
6194
|
-
...usage2 !== void 0 ? { usage: usage2 } : {}
|
|
6611
|
+
...usage2 !== void 0 ? { usage: usage2 } : {},
|
|
6612
|
+
...canonicalUsage !== void 0 ? { canonicalUsage } : {}
|
|
6195
6613
|
};
|
|
6196
6614
|
}
|
|
6197
6615
|
if (isRecord17(response)) {
|
|
@@ -6463,7 +6881,7 @@ function cloneRunRecord(record) {
|
|
|
6463
6881
|
...record,
|
|
6464
6882
|
iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
|
|
6465
6883
|
errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
|
|
6466
|
-
metadata: record.metadata ?
|
|
6884
|
+
metadata: record.metadata ? structuredClone(record.metadata) : void 0
|
|
6467
6885
|
};
|
|
6468
6886
|
}
|
|
6469
6887
|
function matchesStatus(candidate, filter) {
|
|
@@ -6875,7 +7293,7 @@ function isTerminalStatus(status) {
|
|
|
6875
7293
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
6876
7294
|
}
|
|
6877
7295
|
function cloneMetadata(metadata) {
|
|
6878
|
-
return metadata ?
|
|
7296
|
+
return metadata ? structuredClone(metadata) : void 0;
|
|
6879
7297
|
}
|
|
6880
7298
|
function recordToSnapshot(record) {
|
|
6881
7299
|
return {
|
|
@@ -6962,7 +7380,7 @@ var DefaultRunSupervisor = class {
|
|
|
6962
7380
|
startedAt,
|
|
6963
7381
|
updatedAt: startedAt,
|
|
6964
7382
|
iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
|
|
6965
|
-
metadata: spec.metadata
|
|
7383
|
+
metadata: cloneMetadata(spec.metadata)
|
|
6966
7384
|
};
|
|
6967
7385
|
await this.registryStore.save(record);
|
|
6968
7386
|
const handle = new DefaultRunHandle({
|
|
@@ -7136,12 +7554,13 @@ var DefaultRunSupervisor = class {
|
|
|
7136
7554
|
}
|
|
7137
7555
|
try {
|
|
7138
7556
|
await handle.markRunning({ currentNode: "detached" });
|
|
7557
|
+
const registeredRecord = await this.registryStore.load(handle.runId);
|
|
7139
7558
|
const executorOutcome = await this.executor.execute({
|
|
7140
7559
|
runId: handle.runId,
|
|
7141
|
-
parentRunId:
|
|
7142
|
-
conversationId: spec.conversationId,
|
|
7143
|
-
agentSpec: spec
|
|
7144
|
-
request:
|
|
7560
|
+
parentRunId: handle.parentRunId,
|
|
7561
|
+
conversationId: registeredRecord?.conversationId ?? spec.conversationId,
|
|
7562
|
+
agentSpec: await handle.spec(),
|
|
7563
|
+
request: await handle.request(),
|
|
7145
7564
|
signal: handle.signal,
|
|
7146
7565
|
eventBus: spec.eventBus,
|
|
7147
7566
|
eventStore: spec.eventStore,
|
|
@@ -7150,7 +7569,7 @@ var DefaultRunSupervisor = class {
|
|
|
7150
7569
|
contextFences: spec.contextFences,
|
|
7151
7570
|
wakeSource: spec.wakeSource,
|
|
7152
7571
|
ephemeral: spec.ephemeral,
|
|
7153
|
-
metadata: spec.metadata
|
|
7572
|
+
metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
|
|
7154
7573
|
});
|
|
7155
7574
|
const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
|
|
7156
7575
|
this.notifyTerminalWaiters(outcome);
|
|
@@ -7214,10 +7633,14 @@ var DefaultRunSupervisor = class {
|
|
|
7214
7633
|
await this.registryStore.save(record);
|
|
7215
7634
|
}
|
|
7216
7635
|
const completedAt = executorOutcome?.completedAt ?? this.now();
|
|
7636
|
+
const fallbackMeta = record ? void 0 : await handle.meta();
|
|
7217
7637
|
const outcome = recordToTerminalOutcome(record ?? {
|
|
7218
7638
|
runId: handle.runId,
|
|
7219
7639
|
parentRunId: handle.parentRunId,
|
|
7220
|
-
|
|
7640
|
+
conversationId: fallbackMeta?.conversationId ?? "",
|
|
7641
|
+
agentSpecId: fallbackMeta?.agentSpecId,
|
|
7642
|
+
status: executorOutcome?.status ?? "completed",
|
|
7643
|
+
startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
|
|
7221
7644
|
const nextOutcome = {
|
|
7222
7645
|
...outcome,
|
|
7223
7646
|
metadata: {
|
|
@@ -7545,6 +7968,7 @@ async function emitRunEvent(event, sink) {
|
|
|
7545
7968
|
async function runAgent(agent, options) {
|
|
7546
7969
|
const modelId = resolveModelId(agent, options);
|
|
7547
7970
|
const conversationId = options.conversationId ?? `conv_${Date.now()}`;
|
|
7971
|
+
const checkpointKey = conversationId;
|
|
7548
7972
|
const runId = options.runId ?? generateRunId();
|
|
7549
7973
|
const turnId = runId;
|
|
7550
7974
|
const costCollector = new QuickstartRunCostCollector();
|
|
@@ -7599,7 +8023,7 @@ async function runAgent(agent, options) {
|
|
|
7599
8023
|
};
|
|
7600
8024
|
await handle.markRunning({ currentNode: "user" });
|
|
7601
8025
|
try {
|
|
7602
|
-
await executor.prime(
|
|
8026
|
+
await executor.prime(checkpointKey, {
|
|
7603
8027
|
conversationId,
|
|
7604
8028
|
turnId,
|
|
7605
8029
|
request: {
|
|
@@ -7624,7 +8048,7 @@ async function runAgent(agent, options) {
|
|
|
7624
8048
|
return void 0;
|
|
7625
8049
|
}
|
|
7626
8050
|
});
|
|
7627
|
-
const result = await executor.runUntilYield(
|
|
8051
|
+
const result = await executor.runUntilYield(checkpointKey);
|
|
7628
8052
|
runtimeEvents.push(...result.events);
|
|
7629
8053
|
for (const event of result.events) {
|
|
7630
8054
|
if (event.type === "final_answer_chunk") continue;
|
|
@@ -7787,7 +8211,7 @@ function createQuickstartTemplateFiles(projectName) {
|
|
|
7787
8211
|
start: 'linnkit run hello --input "\u4F60\u597D\uFF0C\u4ECB\u7ECD\u4E00\u4E0B\u4F60\u81EA\u5DF1"'
|
|
7788
8212
|
},
|
|
7789
8213
|
dependencies: {
|
|
7790
|
-
"@linnlabs/linnkit": "^0.
|
|
8214
|
+
"@linnlabs/linnkit": "^0.16.0",
|
|
7791
8215
|
zod: "^3.22.0"
|
|
7792
8216
|
},
|
|
7793
8217
|
devDependencies: {}
|