@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/runtime-kernel.js
CHANGED
|
@@ -40,6 +40,7 @@ var Logger = class {
|
|
|
40
40
|
constructor(moduleName) {
|
|
41
41
|
this.moduleName = moduleName;
|
|
42
42
|
}
|
|
43
|
+
moduleName;
|
|
43
44
|
debug(message, data) {
|
|
44
45
|
this.log(0 /* DEBUG */, "debug", message, data);
|
|
45
46
|
}
|
|
@@ -138,6 +139,12 @@ z.object({
|
|
|
138
139
|
args: z.record(z.unknown()).optional(),
|
|
139
140
|
tool_call_id: z.string()
|
|
140
141
|
});
|
|
142
|
+
var ObservationTruncationMeta = z.object({
|
|
143
|
+
originalChars: z.number().int().nonnegative(),
|
|
144
|
+
previewChars: z.number().int().nonnegative(),
|
|
145
|
+
originalLines: z.number().int().nonnegative().optional(),
|
|
146
|
+
previewLines: z.number().int().nonnegative().optional()
|
|
147
|
+
});
|
|
141
148
|
var ImageInfoMeta = z.object({
|
|
142
149
|
url: z.string().optional(),
|
|
143
150
|
width: z.number().int().positive().optional(),
|
|
@@ -169,6 +176,7 @@ var PersistentMetadata = z.object({
|
|
|
169
176
|
tool_name: z.string().optional(),
|
|
170
177
|
args: z.record(z.unknown()).optional(),
|
|
171
178
|
tool_call_id: z.string().optional(),
|
|
179
|
+
observationTruncation: ObservationTruncationMeta.optional(),
|
|
172
180
|
raw_output: z.string().optional(),
|
|
173
181
|
image_info: ImageInfoMeta.optional(),
|
|
174
182
|
taskType: z.string().optional(),
|
|
@@ -262,6 +270,7 @@ var AgentSpecBudgetPolicy = z.object({
|
|
|
262
270
|
});
|
|
263
271
|
var AgentSpecToolHistoryPolicy = z.object({
|
|
264
272
|
strategy: z.enum(["per-pair", "per-run", "none"]).optional(),
|
|
273
|
+
retentionMode: z.enum(["drop", "compress"]).optional(),
|
|
265
274
|
keepLatestToolPairs: z.number().int().nonnegative().optional(),
|
|
266
275
|
keepLatestRuns: z.number().int().nonnegative().optional(),
|
|
267
276
|
maxInteractionGroups: z.number().int().nonnegative().optional(),
|
|
@@ -314,7 +323,17 @@ var AgentSpecReasoningRetentionPolicy = z.object({
|
|
|
314
323
|
var AgentSpecTokenEstimationPolicy = z.object({
|
|
315
324
|
encoding: z.string().min(1).optional(),
|
|
316
325
|
avgCharsPerToken: z.number().positive().optional(),
|
|
317
|
-
toolCallOverhead: z.number().int().nonnegative().optional()
|
|
326
|
+
toolCallOverhead: z.number().int().nonnegative().optional(),
|
|
327
|
+
calibration: z.object({
|
|
328
|
+
enabled: z.boolean().optional(),
|
|
329
|
+
minSamples: z.number().int().positive().optional(),
|
|
330
|
+
minCoefficient: z.number().positive().optional(),
|
|
331
|
+
maxCoefficient: z.number().positive().optional()
|
|
332
|
+
}).optional(),
|
|
333
|
+
remoteCount: z.object({
|
|
334
|
+
enabled: z.boolean().optional(),
|
|
335
|
+
failureBehavior: z.enum(["use-local-estimate", "fail-fast"]).optional()
|
|
336
|
+
}).optional()
|
|
318
337
|
});
|
|
319
338
|
var AgentSpecSystemReminderTrigger = z.object({
|
|
320
339
|
kind: z.string().min(1),
|
|
@@ -1012,12 +1031,206 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
|
|
|
1012
1031
|
error,
|
|
1013
1032
|
...options
|
|
1014
1033
|
});
|
|
1034
|
+
var TokenCountSource = z.enum([
|
|
1035
|
+
"local-estimate",
|
|
1036
|
+
"provider-preflight-count",
|
|
1037
|
+
"provider-response-usage",
|
|
1038
|
+
"host-supplied",
|
|
1039
|
+
"test-fixture"
|
|
1040
|
+
]);
|
|
1041
|
+
var TokenCountConfidence = z.enum([
|
|
1042
|
+
"estimate",
|
|
1043
|
+
"provider-estimate",
|
|
1044
|
+
"actual"
|
|
1045
|
+
]);
|
|
1046
|
+
var TokenRouteCapabilities = z.object({
|
|
1047
|
+
supportsRemoteTokenCount: z.boolean().optional(),
|
|
1048
|
+
supportsResponseUsage: z.boolean().optional(),
|
|
1049
|
+
supportsImageInput: z.boolean().optional(),
|
|
1050
|
+
supportsCachedInputBilling: z.boolean().optional(),
|
|
1051
|
+
supportsReasoningTokens: z.boolean().optional()
|
|
1052
|
+
});
|
|
1053
|
+
var TokenRoute = z.object({
|
|
1054
|
+
providerId: z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
|
|
1055
|
+
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"),
|
|
1056
|
+
modelId: z.string().describe("host \u4FA7\u6A21\u578B id"),
|
|
1057
|
+
providerModelId: z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
|
|
1058
|
+
capabilities: TokenRouteCapabilities.optional()
|
|
1059
|
+
});
|
|
1060
|
+
var tokenCount = z.number().int().nonnegative();
|
|
1061
|
+
var CanonicalLlmUsage = z.object({
|
|
1062
|
+
inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
|
|
1063
|
+
outputTokens: tokenCount.describe("\u8F93\u51FA token"),
|
|
1064
|
+
reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
|
|
1065
|
+
cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
|
|
1066
|
+
cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
|
|
1067
|
+
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"),
|
|
1068
|
+
source: TokenCountSource,
|
|
1069
|
+
confidence: TokenCountConfidence,
|
|
1070
|
+
rawUsage: z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
|
|
1071
|
+
});
|
|
1072
|
+
var tokenCount2 = z.number().int().nonnegative();
|
|
1073
|
+
var tokenPrice = z.number().finite().nonnegative();
|
|
1074
|
+
z.enum([
|
|
1075
|
+
"llm-usage",
|
|
1076
|
+
"context-component"
|
|
1077
|
+
]);
|
|
1078
|
+
var ContextTokenComponentKind = z.enum([
|
|
1079
|
+
"system",
|
|
1080
|
+
"user",
|
|
1081
|
+
"assistant",
|
|
1082
|
+
"tool",
|
|
1083
|
+
"context-injection",
|
|
1084
|
+
"history-summary",
|
|
1085
|
+
"working-memory",
|
|
1086
|
+
"fence",
|
|
1087
|
+
"system-reminder",
|
|
1088
|
+
"other"
|
|
1089
|
+
]);
|
|
1090
|
+
var TokenUsageTotals = z.object({
|
|
1091
|
+
inputTokens: tokenCount2,
|
|
1092
|
+
outputTokens: tokenCount2,
|
|
1093
|
+
reasoningTokens: tokenCount2.optional(),
|
|
1094
|
+
cacheReadTokens: tokenCount2.optional(),
|
|
1095
|
+
cacheWriteTokens: tokenCount2.optional(),
|
|
1096
|
+
totalTokens: tokenCount2.optional(),
|
|
1097
|
+
usageCount: z.number().int().nonnegative()
|
|
1098
|
+
});
|
|
1099
|
+
var ContextTokenComponent = z.object({
|
|
1100
|
+
componentId: z.string().min(1),
|
|
1101
|
+
kind: ContextTokenComponentKind,
|
|
1102
|
+
tokens: tokenCount2,
|
|
1103
|
+
source: TokenCountSource,
|
|
1104
|
+
confidence: TokenCountConfidence,
|
|
1105
|
+
label: z.string().optional(),
|
|
1106
|
+
messageId: z.string().optional(),
|
|
1107
|
+
role: z.string().optional(),
|
|
1108
|
+
action: z.string().optional(),
|
|
1109
|
+
kept: z.boolean().optional(),
|
|
1110
|
+
truncatedAtExecution: z.boolean().optional(),
|
|
1111
|
+
originalTokensEstimate: tokenCount2.optional(),
|
|
1112
|
+
droppedTokensEstimate: tokenCount2.optional()
|
|
1113
|
+
});
|
|
1114
|
+
var TokenLedgerEntryBase = z.object({
|
|
1115
|
+
id: z.string().min(1),
|
|
1116
|
+
runId: z.string().optional(),
|
|
1117
|
+
parentRunId: z.string().optional(),
|
|
1118
|
+
conversationId: z.string().optional(),
|
|
1119
|
+
turnId: z.string().optional(),
|
|
1120
|
+
stepId: z.string().optional(),
|
|
1121
|
+
route: TokenRoute.optional(),
|
|
1122
|
+
createdAt: z.number().int().nonnegative().optional()
|
|
1123
|
+
});
|
|
1124
|
+
var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
|
|
1125
|
+
kind: z.literal("llm-usage"),
|
|
1126
|
+
modelId: z.string().optional(),
|
|
1127
|
+
usage: CanonicalLlmUsage
|
|
1128
|
+
});
|
|
1129
|
+
var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
|
|
1130
|
+
kind: z.literal("context-component"),
|
|
1131
|
+
components: z.array(ContextTokenComponent),
|
|
1132
|
+
totalTokens: tokenCount2
|
|
1133
|
+
});
|
|
1134
|
+
z.discriminatedUnion("kind", [
|
|
1135
|
+
LlmUsageTokenLedgerEntry,
|
|
1136
|
+
ContextComponentTokenLedgerEntry
|
|
1137
|
+
]);
|
|
1138
|
+
var TokenLedgerAggregate = z.object({
|
|
1139
|
+
llmUsage: TokenUsageTotals.optional(),
|
|
1140
|
+
contextTokens: tokenCount2,
|
|
1141
|
+
entryCount: z.number().int().nonnegative(),
|
|
1142
|
+
llmCallCount: z.number().int().nonnegative(),
|
|
1143
|
+
contextComponentCount: z.number().int().nonnegative()
|
|
1144
|
+
});
|
|
1145
|
+
z.object({
|
|
1146
|
+
/**
|
|
1147
|
+
* 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
|
|
1148
|
+
*/
|
|
1149
|
+
own: TokenLedgerAggregate,
|
|
1150
|
+
children: TokenLedgerAggregate.optional()
|
|
1151
|
+
});
|
|
1152
|
+
var TokenCostComponent = z.enum([
|
|
1153
|
+
"input",
|
|
1154
|
+
"output",
|
|
1155
|
+
"reasoning",
|
|
1156
|
+
"cacheRead",
|
|
1157
|
+
"cacheWrite"
|
|
1158
|
+
]);
|
|
1159
|
+
z.object({
|
|
1160
|
+
currency: z.string().min(1),
|
|
1161
|
+
unit: z.literal("per_1m_tokens"),
|
|
1162
|
+
input: tokenPrice.optional(),
|
|
1163
|
+
output: tokenPrice.optional(),
|
|
1164
|
+
reasoning: tokenPrice.optional(),
|
|
1165
|
+
cacheRead: tokenPrice.optional(),
|
|
1166
|
+
cacheWrite: tokenPrice.optional()
|
|
1167
|
+
});
|
|
1168
|
+
z.object({
|
|
1169
|
+
status: z.enum(["computed", "unknown"]),
|
|
1170
|
+
currency: z.string().optional(),
|
|
1171
|
+
inputCost: tokenPrice.optional(),
|
|
1172
|
+
outputCost: tokenPrice.optional(),
|
|
1173
|
+
reasoningCost: tokenPrice.optional(),
|
|
1174
|
+
cacheReadCost: tokenPrice.optional(),
|
|
1175
|
+
cacheWriteCost: tokenPrice.optional(),
|
|
1176
|
+
totalCost: tokenPrice.optional(),
|
|
1177
|
+
missingPriceComponents: z.array(TokenCostComponent).optional()
|
|
1178
|
+
});
|
|
1179
|
+
var tokenCount3 = z.number().int().nonnegative();
|
|
1180
|
+
var actualCalibrationSource = z.enum([
|
|
1181
|
+
"provider-response-usage",
|
|
1182
|
+
"host-supplied",
|
|
1183
|
+
"test-fixture"
|
|
1184
|
+
]);
|
|
1185
|
+
z.object({
|
|
1186
|
+
route: TokenRoute,
|
|
1187
|
+
localEstimateTokens: tokenCount3,
|
|
1188
|
+
actualInputTokens: tokenCount3,
|
|
1189
|
+
source: actualCalibrationSource,
|
|
1190
|
+
confidence: z.literal("actual"),
|
|
1191
|
+
observedAt: z.number().int().nonnegative().optional(),
|
|
1192
|
+
runId: z.string().optional(),
|
|
1193
|
+
ledgerEntryId: z.string().optional()
|
|
1194
|
+
});
|
|
1195
|
+
z.object({
|
|
1196
|
+
enabled: z.boolean(),
|
|
1197
|
+
applied: z.boolean(),
|
|
1198
|
+
route: TokenRoute.optional(),
|
|
1199
|
+
sampleCount: z.number().int().nonnegative(),
|
|
1200
|
+
coefficient: z.number().positive().optional(),
|
|
1201
|
+
minSamples: z.number().int().positive().optional(),
|
|
1202
|
+
minCoefficient: z.number().positive().optional(),
|
|
1203
|
+
maxCoefficient: z.number().positive().optional(),
|
|
1204
|
+
localEstimateTokens: tokenCount3.optional(),
|
|
1205
|
+
calibratedEstimateTokens: tokenCount3.optional(),
|
|
1206
|
+
deltaTokens: z.number().int().optional(),
|
|
1207
|
+
sampleLedgerEntryIds: z.array(z.string()).optional()
|
|
1208
|
+
});
|
|
1209
|
+
z.object({
|
|
1210
|
+
route: TokenRoute.optional(),
|
|
1211
|
+
localEstimateTokens: tokenCount3,
|
|
1212
|
+
calibratedEstimateTokens: tokenCount3,
|
|
1213
|
+
finalTokens: tokenCount3,
|
|
1214
|
+
source: z.literal("local-estimate"),
|
|
1215
|
+
confidence: z.literal("estimate")
|
|
1216
|
+
});
|
|
1015
1217
|
|
|
1016
1218
|
// src/runtime-kernel/graph-engine/engine.ts
|
|
1017
1219
|
var logger = new Logger("GraphExecutor");
|
|
1018
1220
|
function asLocalRecord(local) {
|
|
1019
1221
|
return local && typeof local === "object" ? { ...local } : {};
|
|
1020
1222
|
}
|
|
1223
|
+
function readNonEmptyString(value) {
|
|
1224
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
1225
|
+
}
|
|
1226
|
+
function readRuntimeConversationId(state) {
|
|
1227
|
+
const local = state?.local && typeof state.local === "object" ? state.local : void 0;
|
|
1228
|
+
return readNonEmptyString(local?.conversationId);
|
|
1229
|
+
}
|
|
1230
|
+
function readRuntimeTurnId(state) {
|
|
1231
|
+
const local = state?.local && typeof state.local === "object" ? state.local : void 0;
|
|
1232
|
+
return readNonEmptyString(local?.turnId);
|
|
1233
|
+
}
|
|
1021
1234
|
var GraphExecutor = class {
|
|
1022
1235
|
constructor(checkpointer, config = {}) {
|
|
1023
1236
|
this.checkpointer = checkpointer;
|
|
@@ -1027,6 +1240,7 @@ var GraphExecutor = class {
|
|
|
1027
1240
|
};
|
|
1028
1241
|
this.telemetryPort = config.telemetryPort ?? noopTelemetry;
|
|
1029
1242
|
}
|
|
1243
|
+
checkpointer;
|
|
1030
1244
|
nodes = /* @__PURE__ */ new Map();
|
|
1031
1245
|
ephemeralLocals = /* @__PURE__ */ new Map();
|
|
1032
1246
|
config;
|
|
@@ -1034,8 +1248,8 @@ var GraphExecutor = class {
|
|
|
1034
1248
|
registerNode(node) {
|
|
1035
1249
|
this.nodes.set(node.id, node);
|
|
1036
1250
|
}
|
|
1037
|
-
async peekCheckpoint(
|
|
1038
|
-
return await this.checkpointer.load(
|
|
1251
|
+
async peekCheckpoint(checkpointKey) {
|
|
1252
|
+
return await this.checkpointer.load(checkpointKey);
|
|
1039
1253
|
}
|
|
1040
1254
|
sanitize(state) {
|
|
1041
1255
|
const local = asLocalRecord(state.local);
|
|
@@ -1047,8 +1261,8 @@ var GraphExecutor = class {
|
|
|
1047
1261
|
local
|
|
1048
1262
|
};
|
|
1049
1263
|
}
|
|
1050
|
-
async prime(
|
|
1051
|
-
this.ephemeralLocals.set(
|
|
1264
|
+
async prime(checkpointKey, local, nodeId = "user") {
|
|
1265
|
+
this.ephemeralLocals.set(checkpointKey, { ...local || {} });
|
|
1052
1266
|
const localSansMemory = { ...local || {} };
|
|
1053
1267
|
if ("memory" in localSansMemory) delete localSansMemory.memory;
|
|
1054
1268
|
const state = {
|
|
@@ -1056,10 +1270,10 @@ var GraphExecutor = class {
|
|
|
1056
1270
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1057
1271
|
local: localSansMemory
|
|
1058
1272
|
};
|
|
1059
|
-
await this.checkpointer.save(
|
|
1273
|
+
await this.checkpointer.save(checkpointKey, state);
|
|
1060
1274
|
}
|
|
1061
|
-
async setNode(
|
|
1062
|
-
const current = await this.checkpointer.load(
|
|
1275
|
+
async setNode(checkpointKey, nodeId, localPatch) {
|
|
1276
|
+
const current = await this.checkpointer.load(checkpointKey) || {
|
|
1063
1277
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1064
1278
|
local: {}
|
|
1065
1279
|
};
|
|
@@ -1070,19 +1284,46 @@ var GraphExecutor = class {
|
|
|
1070
1284
|
schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
1071
1285
|
local: mergedLocal
|
|
1072
1286
|
};
|
|
1073
|
-
await this.checkpointer.save(
|
|
1287
|
+
await this.checkpointer.save(checkpointKey, next);
|
|
1074
1288
|
}
|
|
1075
|
-
async runUntilYield(
|
|
1289
|
+
async runUntilYield(checkpointKey) {
|
|
1076
1290
|
const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1077
1291
|
let lifecyclePhase = "completed";
|
|
1292
|
+
let initialState = null;
|
|
1293
|
+
try {
|
|
1294
|
+
initialState = await this.loadInitialState(checkpointKey);
|
|
1295
|
+
} catch (err) {
|
|
1296
|
+
lifecyclePhase = "failed";
|
|
1297
|
+
this.telemetryPort.emit({
|
|
1298
|
+
kind: "run_lifecycle",
|
|
1299
|
+
runId,
|
|
1300
|
+
phase: "spawned",
|
|
1301
|
+
scope: {}
|
|
1302
|
+
});
|
|
1303
|
+
this.telemetryPort.emit({
|
|
1304
|
+
kind: "run_lifecycle",
|
|
1305
|
+
runId,
|
|
1306
|
+
phase: lifecyclePhase,
|
|
1307
|
+
scope: {}
|
|
1308
|
+
});
|
|
1309
|
+
throw err;
|
|
1310
|
+
}
|
|
1311
|
+
let lifecycleConversationId = readRuntimeConversationId(initialState);
|
|
1312
|
+
let lifecycleTurnId = readRuntimeTurnId(initialState);
|
|
1078
1313
|
this.telemetryPort.emit({
|
|
1079
1314
|
kind: "run_lifecycle",
|
|
1080
1315
|
runId,
|
|
1081
1316
|
phase: "spawned",
|
|
1082
|
-
scope: {
|
|
1317
|
+
scope: {
|
|
1318
|
+
conversationId: lifecycleConversationId,
|
|
1319
|
+
turnId: lifecycleTurnId
|
|
1320
|
+
}
|
|
1083
1321
|
});
|
|
1084
1322
|
try {
|
|
1085
|
-
|
|
1323
|
+
const result = await this.runUntilYieldInternal(checkpointKey, initialState);
|
|
1324
|
+
lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
|
|
1325
|
+
lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
|
|
1326
|
+
return result;
|
|
1086
1327
|
} catch (err) {
|
|
1087
1328
|
lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
|
|
1088
1329
|
throw err;
|
|
@@ -1091,17 +1332,23 @@ var GraphExecutor = class {
|
|
|
1091
1332
|
kind: "run_lifecycle",
|
|
1092
1333
|
runId,
|
|
1093
1334
|
phase: lifecyclePhase,
|
|
1094
|
-
scope: {
|
|
1335
|
+
scope: {
|
|
1336
|
+
conversationId: lifecycleConversationId,
|
|
1337
|
+
turnId: lifecycleTurnId
|
|
1338
|
+
}
|
|
1095
1339
|
});
|
|
1096
1340
|
}
|
|
1097
1341
|
}
|
|
1098
|
-
async
|
|
1099
|
-
|
|
1342
|
+
async loadInitialState(checkpointKey) {
|
|
1343
|
+
return await this.checkpointer.load(checkpointKey) || {
|
|
1100
1344
|
nodeId: "user",
|
|
1101
1345
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1102
1346
|
local: {}
|
|
1103
1347
|
};
|
|
1104
|
-
|
|
1348
|
+
}
|
|
1349
|
+
async runUntilYieldInternal(checkpointKey, initialState) {
|
|
1350
|
+
let state = initialState;
|
|
1351
|
+
const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
|
|
1105
1352
|
state = {
|
|
1106
1353
|
...state,
|
|
1107
1354
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
@@ -1130,7 +1377,7 @@ var GraphExecutor = class {
|
|
|
1130
1377
|
const signalRaw = state.local?.signal;
|
|
1131
1378
|
if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
|
|
1132
1379
|
logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
|
|
1133
|
-
this.ephemeralLocals.delete(
|
|
1380
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1134
1381
|
throwAbortError();
|
|
1135
1382
|
}
|
|
1136
1383
|
const isLastStep = cycleStepCount >= this.config.maxSteps;
|
|
@@ -1178,8 +1425,8 @@ var GraphExecutor = class {
|
|
|
1178
1425
|
checkpointCount
|
|
1179
1426
|
});
|
|
1180
1427
|
const cp2 = this.sanitize(state);
|
|
1181
|
-
await this.checkpointer.save(
|
|
1182
|
-
this.ephemeralLocals.delete(
|
|
1428
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1429
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1183
1430
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1184
1431
|
}
|
|
1185
1432
|
logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
|
|
@@ -1190,18 +1437,18 @@ var GraphExecutor = class {
|
|
|
1190
1437
|
});
|
|
1191
1438
|
const nodeRunStartedAt = Date.now();
|
|
1192
1439
|
const nodeIdForTelemetry = state.nodeId;
|
|
1440
|
+
const conversationIdForTelemetry = readRuntimeConversationId(state);
|
|
1193
1441
|
let result;
|
|
1194
1442
|
try {
|
|
1195
1443
|
result = await node.run(state);
|
|
1196
1444
|
} finally {
|
|
1197
|
-
const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
|
|
1198
1445
|
this.telemetryPort.emit({
|
|
1199
1446
|
kind: "graph_node",
|
|
1200
1447
|
nodeId: nodeIdForTelemetry,
|
|
1201
1448
|
durationMs: Date.now() - nodeRunStartedAt,
|
|
1202
1449
|
scope: {
|
|
1203
|
-
conversationId:
|
|
1204
|
-
turnId:
|
|
1450
|
+
conversationId: conversationIdForTelemetry,
|
|
1451
|
+
turnId: readRuntimeTurnId(state)
|
|
1205
1452
|
}
|
|
1206
1453
|
});
|
|
1207
1454
|
}
|
|
@@ -1240,7 +1487,7 @@ var GraphExecutor = class {
|
|
|
1240
1487
|
});
|
|
1241
1488
|
state = { ...state, nodeId: nextNodeId };
|
|
1242
1489
|
const cp2 = this.sanitize(state);
|
|
1243
|
-
await this.checkpointer.save(
|
|
1490
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1244
1491
|
continue;
|
|
1245
1492
|
}
|
|
1246
1493
|
if (result.kind === "yield") {
|
|
@@ -1251,7 +1498,7 @@ var GraphExecutor = class {
|
|
|
1251
1498
|
checkpointCount
|
|
1252
1499
|
});
|
|
1253
1500
|
const cp2 = this.sanitize(state);
|
|
1254
|
-
await this.checkpointer.save(
|
|
1501
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1255
1502
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1256
1503
|
}
|
|
1257
1504
|
if (result.kind === "pause") {
|
|
@@ -1262,7 +1509,7 @@ var GraphExecutor = class {
|
|
|
1262
1509
|
checkpointCount
|
|
1263
1510
|
});
|
|
1264
1511
|
const cp2 = this.sanitize(state);
|
|
1265
|
-
await this.checkpointer.save(
|
|
1512
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1266
1513
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1267
1514
|
}
|
|
1268
1515
|
}
|
|
@@ -1273,8 +1520,8 @@ var GraphExecutor = class {
|
|
|
1273
1520
|
checkpointCount
|
|
1274
1521
|
});
|
|
1275
1522
|
const cp = this.sanitize(state);
|
|
1276
|
-
await this.checkpointer.save(
|
|
1277
|
-
this.ephemeralLocals.delete(
|
|
1523
|
+
await this.checkpointer.save(checkpointKey, cp);
|
|
1524
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1278
1525
|
return { events: allEvents, checkpoint: cp, stepCount };
|
|
1279
1526
|
}
|
|
1280
1527
|
};
|
|
@@ -1370,6 +1617,190 @@ var noopAudit = {
|
|
|
1370
1617
|
flush() {
|
|
1371
1618
|
}
|
|
1372
1619
|
};
|
|
1620
|
+
var TokenCalculator = class {
|
|
1621
|
+
static BYTES_PER_TOKEN_LATIN = 4;
|
|
1622
|
+
static BYTES_PER_TOKEN_CJK = 3;
|
|
1623
|
+
static OVERHEAD_PER_MESSAGE = 5;
|
|
1624
|
+
static OVERHEAD_PER_TOOL_CALL = 10;
|
|
1625
|
+
static encoderCache = /* @__PURE__ */ new Map();
|
|
1626
|
+
static DEFAULT_ENCODING = "cl100k_base";
|
|
1627
|
+
static SUPPORTED_ENCODINGS = [
|
|
1628
|
+
"gpt2",
|
|
1629
|
+
"r50k_base",
|
|
1630
|
+
"p50k_base",
|
|
1631
|
+
"p50k_edit",
|
|
1632
|
+
"cl100k_base",
|
|
1633
|
+
"o200k_base"
|
|
1634
|
+
];
|
|
1635
|
+
static resolveEncodingFromModelIdentifier(modelIdentifier) {
|
|
1636
|
+
const normalized = (modelIdentifier || "").trim().toLowerCase();
|
|
1637
|
+
if (this.isSupportedEncodingName(normalized)) {
|
|
1638
|
+
return normalized;
|
|
1639
|
+
}
|
|
1640
|
+
if (normalized.includes("deepseek")) {
|
|
1641
|
+
return "cl100k_base";
|
|
1642
|
+
}
|
|
1643
|
+
if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
|
|
1644
|
+
return "o200k_base";
|
|
1645
|
+
}
|
|
1646
|
+
if (normalized.includes("gemini") || normalized.includes("claude")) {
|
|
1647
|
+
return "cl100k_base";
|
|
1648
|
+
}
|
|
1649
|
+
return this.DEFAULT_ENCODING;
|
|
1650
|
+
}
|
|
1651
|
+
static isSupportedEncodingName(value) {
|
|
1652
|
+
return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
|
|
1653
|
+
}
|
|
1654
|
+
static getEncoder(modelIdentifierOrEncoding) {
|
|
1655
|
+
const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
|
|
1656
|
+
const cached = this.encoderCache.get(encodingName);
|
|
1657
|
+
if (cached) {
|
|
1658
|
+
return cached;
|
|
1659
|
+
}
|
|
1660
|
+
const encoder = get_encoding(encodingName);
|
|
1661
|
+
this.encoderCache.set(encodingName, encoder);
|
|
1662
|
+
return encoder;
|
|
1663
|
+
}
|
|
1664
|
+
static estimateTokensRough(text, _modelIdentifier) {
|
|
1665
|
+
if (!text) return 0;
|
|
1666
|
+
const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
|
|
1667
|
+
const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
|
|
1668
|
+
const byteLength = new TextEncoder().encode(text).length;
|
|
1669
|
+
return Math.ceil(byteLength / ratio);
|
|
1670
|
+
}
|
|
1671
|
+
static estimateTokens(text, options = {}) {
|
|
1672
|
+
if (!text) return 0;
|
|
1673
|
+
if (options.encoding) {
|
|
1674
|
+
try {
|
|
1675
|
+
return this.estimateTokensPrecise(text, options.encoding);
|
|
1676
|
+
} catch {
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
|
|
1680
|
+
return Math.ceil(text.length / avgCharsPerToken);
|
|
1681
|
+
}
|
|
1682
|
+
static estimateTokensPrecise(text, modelIdentifier) {
|
|
1683
|
+
if (!text) return 0;
|
|
1684
|
+
const encoder = this.getEncoder(modelIdentifier);
|
|
1685
|
+
return encoder.encode(text).length;
|
|
1686
|
+
}
|
|
1687
|
+
static estimateMessageTokens(message, options = {}) {
|
|
1688
|
+
let totalTokens = this.OVERHEAD_PER_MESSAGE;
|
|
1689
|
+
if (message.content) {
|
|
1690
|
+
totalTokens += this.estimateTokens(String(message.content), options);
|
|
1691
|
+
}
|
|
1692
|
+
const toolCalls = this.extractToolCallsForTokenEstimate(message);
|
|
1693
|
+
const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
|
|
1694
|
+
for (const toolCall of toolCalls) {
|
|
1695
|
+
totalTokens += toolCallOverhead;
|
|
1696
|
+
const fn = toolCall["function"];
|
|
1697
|
+
if (fn && typeof fn === "object" && !Array.isArray(fn)) {
|
|
1698
|
+
const fnRecord = fn;
|
|
1699
|
+
totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
|
|
1700
|
+
totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
const toolCallId = this.extractToolCallIdForTokenEstimate(message);
|
|
1704
|
+
if (toolCallId) {
|
|
1705
|
+
totalTokens += this.estimateTokens(toolCallId, options);
|
|
1706
|
+
}
|
|
1707
|
+
return totalTokens;
|
|
1708
|
+
}
|
|
1709
|
+
static estimateMessageTokensPrecise(message, modelIdentifier) {
|
|
1710
|
+
return this.estimateMessageTokens(message, {
|
|
1711
|
+
encoding: modelIdentifier,
|
|
1712
|
+
toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
static estimateMessagesTokensPrecise(messages, modelIdentifier) {
|
|
1716
|
+
return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
|
|
1717
|
+
}
|
|
1718
|
+
static extractToolCallsForTokenEstimate(message) {
|
|
1719
|
+
const direct = "tool_calls" in message ? message.tool_calls : void 0;
|
|
1720
|
+
if (Array.isArray(direct)) return direct;
|
|
1721
|
+
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1722
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
|
|
1723
|
+
const metadataRecord = metadata;
|
|
1724
|
+
const metadataToolCalls = metadataRecord["tool_calls"];
|
|
1725
|
+
return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
|
|
1726
|
+
}
|
|
1727
|
+
static extractToolCallIdForTokenEstimate(message) {
|
|
1728
|
+
if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
|
|
1729
|
+
return message.tool_call_id;
|
|
1730
|
+
}
|
|
1731
|
+
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1732
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
|
|
1733
|
+
const metadataRecord = metadata;
|
|
1734
|
+
const toolCallId = metadataRecord["tool_call_id"];
|
|
1735
|
+
return typeof toolCallId === "string" ? toolCallId : void 0;
|
|
1736
|
+
}
|
|
1737
|
+
static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
|
|
1738
|
+
if (!text || maxTokens <= 0) return "";
|
|
1739
|
+
const encoder = this.getEncoder(modelIdentifier);
|
|
1740
|
+
const tokens = encoder.encode(text);
|
|
1741
|
+
if (tokens.length <= maxTokens) {
|
|
1742
|
+
return text;
|
|
1743
|
+
}
|
|
1744
|
+
let truncatedTokens;
|
|
1745
|
+
const ellipsis = "...";
|
|
1746
|
+
switch (strategy) {
|
|
1747
|
+
case "start":
|
|
1748
|
+
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1749
|
+
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1750
|
+
case "end":
|
|
1751
|
+
truncatedTokens = tokens.slice(tokens.length - maxTokens);
|
|
1752
|
+
return ellipsis + encoder.decode(truncatedTokens);
|
|
1753
|
+
case "middle": {
|
|
1754
|
+
const half = Math.floor(maxTokens / 2);
|
|
1755
|
+
const head = tokens.slice(0, half);
|
|
1756
|
+
const tail = tokens.slice(tokens.length - (maxTokens - half));
|
|
1757
|
+
return encoder.decode(head) + ellipsis + encoder.decode(tail);
|
|
1758
|
+
}
|
|
1759
|
+
default:
|
|
1760
|
+
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1761
|
+
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
static cleanup() {
|
|
1765
|
+
for (const encoder of this.encoderCache.values()) {
|
|
1766
|
+
encoder.free();
|
|
1767
|
+
}
|
|
1768
|
+
this.encoderCache.clear();
|
|
1769
|
+
}
|
|
1770
|
+
};
|
|
1771
|
+
function normalizePositiveNumber(value, fallback) {
|
|
1772
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
1773
|
+
}
|
|
1774
|
+
function normalizeNonNegativeInteger(value, fallback) {
|
|
1775
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
1776
|
+
return fallback;
|
|
1777
|
+
}
|
|
1778
|
+
return Math.max(0, Math.floor(value));
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
// src/shared/defaultTokenizerPort.ts
|
|
1782
|
+
var DefaultTokenizerPort = class {
|
|
1783
|
+
constructor(config = {}) {
|
|
1784
|
+
this.config = config;
|
|
1785
|
+
}
|
|
1786
|
+
config;
|
|
1787
|
+
estimateText(text, _modelId) {
|
|
1788
|
+
return TokenCalculator.estimateTokens(text, {
|
|
1789
|
+
encoding: this.config.encoding,
|
|
1790
|
+
avgCharsPerToken: this.config.avgCharsPerToken
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
estimateMessage(message, _modelId) {
|
|
1794
|
+
return TokenCalculator.estimateMessageTokens(message, {
|
|
1795
|
+
encoding: this.config.encoding,
|
|
1796
|
+
avgCharsPerToken: this.config.avgCharsPerToken,
|
|
1797
|
+
toolCallOverhead: this.config.toolCallOverhead
|
|
1798
|
+
});
|
|
1799
|
+
}
|
|
1800
|
+
};
|
|
1801
|
+
function createDefaultTokenizerPort(config = {}) {
|
|
1802
|
+
return new DefaultTokenizerPort(config);
|
|
1803
|
+
}
|
|
1373
1804
|
|
|
1374
1805
|
// src/shared/ids.ts
|
|
1375
1806
|
function isoRandomUUID() {
|
|
@@ -1471,15 +1902,15 @@ function splitConcatenatedJsonObjects(input) {
|
|
|
1471
1902
|
}
|
|
1472
1903
|
|
|
1473
1904
|
// src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
|
|
1474
|
-
function
|
|
1905
|
+
function readNonEmptyString2(value) {
|
|
1475
1906
|
if (typeof value !== "string") return void 0;
|
|
1476
1907
|
const trimmed = value.trim();
|
|
1477
1908
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
1478
1909
|
}
|
|
1479
1910
|
function resolveConversationIdForRuntimeEvents(toolContext) {
|
|
1480
|
-
const fromCamel =
|
|
1911
|
+
const fromCamel = readNonEmptyString2(toolContext?.conversationId);
|
|
1481
1912
|
if (fromCamel) return fromCamel;
|
|
1482
|
-
const fromSnake = toolContext ?
|
|
1913
|
+
const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
|
|
1483
1914
|
if (fromSnake) return fromSnake;
|
|
1484
1915
|
return generateMessageId();
|
|
1485
1916
|
}
|
|
@@ -1550,6 +1981,13 @@ function resolveUsage(response) {
|
|
|
1550
1981
|
}
|
|
1551
1982
|
return response.usage;
|
|
1552
1983
|
}
|
|
1984
|
+
function resolveCanonicalUsage(response) {
|
|
1985
|
+
if (!response || typeof response === "string") {
|
|
1986
|
+
return void 0;
|
|
1987
|
+
}
|
|
1988
|
+
const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
|
|
1989
|
+
return parsed.success ? parsed.data : void 0;
|
|
1990
|
+
}
|
|
1553
1991
|
function resolveToolCalls(response) {
|
|
1554
1992
|
if (!response || typeof response === "string") {
|
|
1555
1993
|
return void 0;
|
|
@@ -1560,227 +1998,100 @@ function resolveReasoningDetails(response) {
|
|
|
1560
1998
|
if (!response || typeof response === "string") {
|
|
1561
1999
|
return void 0;
|
|
1562
2000
|
}
|
|
1563
|
-
return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
|
|
1564
|
-
}
|
|
1565
|
-
function resolveToolNamesForAudit(ctx) {
|
|
1566
|
-
if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
|
|
1567
|
-
return [];
|
|
1568
|
-
}
|
|
1569
|
-
return ctx.toolSchemas.map((tool) => tool.function.name);
|
|
1570
|
-
}
|
|
1571
|
-
function recordBeforeContextManager(params) {
|
|
1572
|
-
}
|
|
1573
|
-
function recordAfterContextManager(params) {
|
|
1574
|
-
}
|
|
1575
|
-
function recordAfterContextManagerOnSystemReminderHit(params) {
|
|
1576
|
-
}
|
|
1577
|
-
function recordToolProtocolError(params) {
|
|
1578
|
-
}
|
|
1579
|
-
function recordRunTranscript(params) {
|
|
1580
|
-
}
|
|
1581
|
-
|
|
1582
|
-
// src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
|
|
1583
|
-
var contextAuditMiddleware = async (ctx, stage, next) => {
|
|
1584
|
-
if (stage.id === "build_context") {
|
|
1585
|
-
recordBeforeContextManager({
|
|
1586
|
-
mode: ctx.request.mode === "chat" ? "chat" : "agent",
|
|
1587
|
-
payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
|
|
1588
|
-
});
|
|
1589
|
-
}
|
|
1590
|
-
await next();
|
|
1591
|
-
if (stage.id !== "apply_system_reminder") {
|
|
1592
|
-
return;
|
|
1593
|
-
}
|
|
1594
|
-
resolveToolNamesForAudit(ctx);
|
|
1595
|
-
recordAfterContextManager({
|
|
1596
|
-
mode: ctx.mode,
|
|
1597
|
-
llmMessages: ctx.llmMessages,
|
|
1598
|
-
contextTrace: ctx.contextTrace
|
|
1599
|
-
});
|
|
1600
|
-
if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
|
|
1601
|
-
recordAfterContextManagerOnSystemReminderHit({
|
|
1602
|
-
mode: ctx.mode,
|
|
1603
|
-
llmMessages: ctx.llmMessages,
|
|
1604
|
-
systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
|
|
1605
|
-
contextTrace: ctx.contextTrace
|
|
1606
|
-
});
|
|
1607
|
-
}
|
|
1608
|
-
};
|
|
1609
|
-
var TokenCalculator = class {
|
|
1610
|
-
static BYTES_PER_TOKEN_LATIN = 4;
|
|
1611
|
-
static BYTES_PER_TOKEN_CJK = 3;
|
|
1612
|
-
static OVERHEAD_PER_MESSAGE = 5;
|
|
1613
|
-
static OVERHEAD_PER_TOOL_CALL = 10;
|
|
1614
|
-
static encoderCache = /* @__PURE__ */ new Map();
|
|
1615
|
-
static DEFAULT_ENCODING = "cl100k_base";
|
|
1616
|
-
static SUPPORTED_ENCODINGS = [
|
|
1617
|
-
"gpt2",
|
|
1618
|
-
"r50k_base",
|
|
1619
|
-
"p50k_base",
|
|
1620
|
-
"p50k_edit",
|
|
1621
|
-
"cl100k_base",
|
|
1622
|
-
"o200k_base"
|
|
1623
|
-
];
|
|
1624
|
-
static resolveEncodingFromModelIdentifier(modelIdentifier) {
|
|
1625
|
-
const normalized = (modelIdentifier || "").trim().toLowerCase();
|
|
1626
|
-
if (this.isSupportedEncodingName(normalized)) {
|
|
1627
|
-
return normalized;
|
|
1628
|
-
}
|
|
1629
|
-
if (normalized.includes("deepseek")) {
|
|
1630
|
-
return "cl100k_base";
|
|
1631
|
-
}
|
|
1632
|
-
if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
|
|
1633
|
-
return "o200k_base";
|
|
1634
|
-
}
|
|
1635
|
-
if (normalized.includes("gemini") || normalized.includes("claude")) {
|
|
1636
|
-
return "cl100k_base";
|
|
1637
|
-
}
|
|
1638
|
-
return this.DEFAULT_ENCODING;
|
|
1639
|
-
}
|
|
1640
|
-
static isSupportedEncodingName(value) {
|
|
1641
|
-
return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
|
|
1642
|
-
}
|
|
1643
|
-
static getEncoder(modelIdentifierOrEncoding) {
|
|
1644
|
-
const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
|
|
1645
|
-
const cached = this.encoderCache.get(encodingName);
|
|
1646
|
-
if (cached) {
|
|
1647
|
-
return cached;
|
|
1648
|
-
}
|
|
1649
|
-
const encoder = get_encoding(encodingName);
|
|
1650
|
-
this.encoderCache.set(encodingName, encoder);
|
|
1651
|
-
return encoder;
|
|
1652
|
-
}
|
|
1653
|
-
static estimateTokensRough(text, _modelIdentifier) {
|
|
1654
|
-
if (!text) return 0;
|
|
1655
|
-
const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
|
|
1656
|
-
const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
|
|
1657
|
-
const byteLength = new TextEncoder().encode(text).length;
|
|
1658
|
-
return Math.ceil(byteLength / ratio);
|
|
1659
|
-
}
|
|
1660
|
-
static estimateTokens(text, options = {}) {
|
|
1661
|
-
if (!text) return 0;
|
|
1662
|
-
if (options.encoding) {
|
|
1663
|
-
try {
|
|
1664
|
-
return this.estimateTokensPrecise(text, options.encoding);
|
|
1665
|
-
} catch {
|
|
1666
|
-
}
|
|
1667
|
-
}
|
|
1668
|
-
const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
|
|
1669
|
-
return Math.ceil(text.length / avgCharsPerToken);
|
|
1670
|
-
}
|
|
1671
|
-
static estimateTokensPrecise(text, modelIdentifier) {
|
|
1672
|
-
if (!text) return 0;
|
|
1673
|
-
const encoder = this.getEncoder(modelIdentifier);
|
|
1674
|
-
return encoder.encode(text).length;
|
|
1675
|
-
}
|
|
1676
|
-
static estimateMessageTokens(message, options = {}) {
|
|
1677
|
-
let totalTokens = this.OVERHEAD_PER_MESSAGE;
|
|
1678
|
-
if (message.content) {
|
|
1679
|
-
totalTokens += this.estimateTokens(String(message.content), options);
|
|
1680
|
-
}
|
|
1681
|
-
const toolCalls = this.extractToolCallsForTokenEstimate(message);
|
|
1682
|
-
const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
|
|
1683
|
-
for (const toolCall of toolCalls) {
|
|
1684
|
-
totalTokens += toolCallOverhead;
|
|
1685
|
-
const fn = toolCall["function"];
|
|
1686
|
-
if (fn && typeof fn === "object" && !Array.isArray(fn)) {
|
|
1687
|
-
const fnRecord = fn;
|
|
1688
|
-
totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
|
|
1689
|
-
totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
|
|
1690
|
-
}
|
|
1691
|
-
}
|
|
1692
|
-
const toolCallId = this.extractToolCallIdForTokenEstimate(message);
|
|
1693
|
-
if (toolCallId) {
|
|
1694
|
-
totalTokens += this.estimateTokens(toolCallId, options);
|
|
1695
|
-
}
|
|
1696
|
-
return totalTokens;
|
|
1697
|
-
}
|
|
1698
|
-
static estimateMessageTokensPrecise(message, modelIdentifier) {
|
|
1699
|
-
return this.estimateMessageTokens(message, {
|
|
1700
|
-
encoding: modelIdentifier,
|
|
1701
|
-
toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
|
|
1702
|
-
});
|
|
1703
|
-
}
|
|
1704
|
-
static estimateMessagesTokensPrecise(messages, modelIdentifier) {
|
|
1705
|
-
return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
|
|
1706
|
-
}
|
|
1707
|
-
static extractToolCallsForTokenEstimate(message) {
|
|
1708
|
-
const direct = "tool_calls" in message ? message.tool_calls : void 0;
|
|
1709
|
-
if (Array.isArray(direct)) return direct;
|
|
1710
|
-
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1711
|
-
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
|
|
1712
|
-
const metadataRecord = metadata;
|
|
1713
|
-
const metadataToolCalls = metadataRecord["tool_calls"];
|
|
1714
|
-
return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
|
|
1715
|
-
}
|
|
1716
|
-
static extractToolCallIdForTokenEstimate(message) {
|
|
1717
|
-
if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
|
|
1718
|
-
return message.tool_call_id;
|
|
1719
|
-
}
|
|
1720
|
-
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1721
|
-
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
|
|
1722
|
-
const metadataRecord = metadata;
|
|
1723
|
-
const toolCallId = metadataRecord["tool_call_id"];
|
|
1724
|
-
return typeof toolCallId === "string" ? toolCallId : void 0;
|
|
2001
|
+
return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
|
|
2002
|
+
}
|
|
2003
|
+
function resolveToolNamesForAudit(ctx) {
|
|
2004
|
+
if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
|
|
2005
|
+
return [];
|
|
1725
2006
|
}
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
return encoder.decode(head) + ellipsis + encoder.decode(tail);
|
|
1747
|
-
}
|
|
1748
|
-
default:
|
|
1749
|
-
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1750
|
-
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1751
|
-
}
|
|
2007
|
+
return ctx.toolSchemas.map((tool) => tool.function.name);
|
|
2008
|
+
}
|
|
2009
|
+
function recordBeforeContextManager(params) {
|
|
2010
|
+
}
|
|
2011
|
+
function recordAfterContextManager(params) {
|
|
2012
|
+
}
|
|
2013
|
+
function recordAfterContextManagerOnSystemReminderHit(params) {
|
|
2014
|
+
}
|
|
2015
|
+
function recordToolProtocolError(params) {
|
|
2016
|
+
}
|
|
2017
|
+
function recordRunTranscript(params) {
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
// src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
|
|
2021
|
+
var contextAuditMiddleware = async (ctx, stage, next) => {
|
|
2022
|
+
if (stage.id === "build_context") {
|
|
2023
|
+
recordBeforeContextManager({
|
|
2024
|
+
mode: ctx.request.mode === "chat" ? "chat" : "agent",
|
|
2025
|
+
payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
|
|
2026
|
+
});
|
|
1752
2027
|
}
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
2028
|
+
await next();
|
|
2029
|
+
if (stage.id !== "apply_system_reminder") {
|
|
2030
|
+
return;
|
|
2031
|
+
}
|
|
2032
|
+
resolveToolNamesForAudit(ctx);
|
|
2033
|
+
recordAfterContextManager({
|
|
2034
|
+
mode: ctx.mode,
|
|
2035
|
+
llmMessages: ctx.llmMessages,
|
|
2036
|
+
contextTrace: ctx.contextTrace
|
|
2037
|
+
});
|
|
2038
|
+
if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
|
|
2039
|
+
recordAfterContextManagerOnSystemReminderHit({
|
|
2040
|
+
mode: ctx.mode,
|
|
2041
|
+
llmMessages: ctx.llmMessages,
|
|
2042
|
+
systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
|
|
2043
|
+
contextTrace: ctx.contextTrace
|
|
2044
|
+
});
|
|
1758
2045
|
}
|
|
1759
2046
|
};
|
|
1760
|
-
|
|
1761
|
-
|
|
2047
|
+
var als = new AsyncLocalStorage();
|
|
2048
|
+
function readTokenCount(record, key) {
|
|
2049
|
+
const value = record[key];
|
|
2050
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
|
|
1762
2051
|
}
|
|
1763
|
-
function
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
return Math.max(0, Math.floor(value));
|
|
2052
|
+
function readRecord(record, key) {
|
|
2053
|
+
const value = record[key];
|
|
2054
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
2055
|
+
return Object.fromEntries(Object.entries(value));
|
|
1768
2056
|
}
|
|
1769
|
-
|
|
1770
|
-
|
|
2057
|
+
function normalizedUsageFromCanonical(canonicalUsage) {
|
|
2058
|
+
return {
|
|
2059
|
+
promptTokens: canonicalUsage.inputTokens,
|
|
2060
|
+
completionTokens: canonicalUsage.outputTokens,
|
|
2061
|
+
totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
|
|
2062
|
+
canonicalUsage
|
|
2063
|
+
};
|
|
2064
|
+
}
|
|
2065
|
+
function normalizeCanonicalLlmUsage(usage) {
|
|
1771
2066
|
if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
|
|
1772
2067
|
const rec = usage;
|
|
1773
|
-
const
|
|
1774
|
-
const
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
const
|
|
1779
|
-
const
|
|
1780
|
-
const
|
|
1781
|
-
const
|
|
1782
|
-
|
|
1783
|
-
|
|
2068
|
+
const inputTokens = readTokenCount(rec, "prompt_tokens");
|
|
2069
|
+
const outputTokens = readTokenCount(rec, "completion_tokens");
|
|
2070
|
+
if (inputTokens === void 0 || outputTokens === void 0) {
|
|
2071
|
+
return void 0;
|
|
2072
|
+
}
|
|
2073
|
+
const promptDetails = readRecord(rec, "prompt_tokens_details");
|
|
2074
|
+
const completionDetails = readRecord(rec, "completion_tokens_details");
|
|
2075
|
+
const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
|
|
2076
|
+
const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
|
|
2077
|
+
const totalTokens = readTokenCount(rec, "total_tokens");
|
|
2078
|
+
if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
|
|
2079
|
+
return void 0;
|
|
2080
|
+
}
|
|
2081
|
+
return {
|
|
2082
|
+
inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
|
|
2083
|
+
outputTokens,
|
|
2084
|
+
...reasoningTokens !== void 0 ? { reasoningTokens } : {},
|
|
2085
|
+
...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
|
|
2086
|
+
...totalTokens !== void 0 ? { totalTokens } : {},
|
|
2087
|
+
source: "provider-response-usage",
|
|
2088
|
+
confidence: "actual",
|
|
2089
|
+
rawUsage: usage
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
function normalizeLlmUsage(usage) {
|
|
2093
|
+
const canonicalUsage = normalizeCanonicalLlmUsage(usage);
|
|
2094
|
+
return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
|
|
1784
2095
|
}
|
|
1785
2096
|
function recordLlmCallTelemetry(entry) {
|
|
1786
2097
|
const store = als.getStore();
|
|
@@ -1794,17 +2105,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1794
2105
|
if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
|
|
1795
2106
|
return;
|
|
1796
2107
|
}
|
|
1797
|
-
const
|
|
2108
|
+
const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
|
|
2109
|
+
const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
|
|
1798
2110
|
const respText = extractResponseText(ctx.llmResp);
|
|
1799
2111
|
const normalizedUsage = normalizedUsageFromProvider ?? (() => {
|
|
1800
2112
|
try {
|
|
1801
|
-
const promptTokens =
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
2113
|
+
const promptTokens = ctx.llmMessages.reduce(
|
|
2114
|
+
(total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
|
|
2115
|
+
0
|
|
2116
|
+
);
|
|
2117
|
+
const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
|
|
2118
|
+
return normalizedUsageFromCanonical({
|
|
2119
|
+
inputTokens: promptTokens,
|
|
2120
|
+
outputTokens: completionTokens,
|
|
2121
|
+
totalTokens: promptTokens + completionTokens,
|
|
2122
|
+
source: "local-estimate",
|
|
2123
|
+
confidence: "estimate"
|
|
2124
|
+
});
|
|
1808
2125
|
} catch {
|
|
1809
2126
|
return void 0;
|
|
1810
2127
|
}
|
|
@@ -1814,7 +2131,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1814
2131
|
stream: ctx.input.stream === true,
|
|
1815
2132
|
startedAt: ctx.llmCallStartedAt,
|
|
1816
2133
|
durationMs: ctx.llmCallDurationMs,
|
|
1817
|
-
usage: normalizedUsage
|
|
2134
|
+
usage: normalizedUsage,
|
|
2135
|
+
...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
|
|
1818
2136
|
});
|
|
1819
2137
|
ctx.telemetry.emit({
|
|
1820
2138
|
kind: "llm_call",
|
|
@@ -1822,6 +2140,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1822
2140
|
stream: ctx.input.stream === true,
|
|
1823
2141
|
durationMs: ctx.llmCallDurationMs,
|
|
1824
2142
|
usage: normalizedUsage,
|
|
2143
|
+
...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
|
|
1825
2144
|
scope: {
|
|
1826
2145
|
conversationId: ctx.conversationId || void 0,
|
|
1827
2146
|
turnId: ctx.turnId,
|
|
@@ -1838,7 +2157,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
|
|
|
1838
2157
|
if (stage.id !== "execute_llm") {
|
|
1839
2158
|
return;
|
|
1840
2159
|
}
|
|
1841
|
-
const normalized =
|
|
2160
|
+
const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
|
|
1842
2161
|
if (!normalized) {
|
|
1843
2162
|
return;
|
|
1844
2163
|
}
|
|
@@ -1965,10 +2284,10 @@ var contextBudgetWarningTemplate = (ctx) => {
|
|
|
1965
2284
|
return [
|
|
1966
2285
|
`\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`,
|
|
1967
2286
|
"\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
|
|
1968
|
-
"1. \
|
|
2287
|
+
"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",
|
|
1969
2288
|
`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`,
|
|
1970
2289
|
' \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',
|
|
1971
|
-
"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\
|
|
2290
|
+
"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"
|
|
1972
2291
|
].join("\n");
|
|
1973
2292
|
};
|
|
1974
2293
|
var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
|
|
@@ -2276,6 +2595,219 @@ function createApplySystemReminderStage() {
|
|
|
2276
2595
|
};
|
|
2277
2596
|
}
|
|
2278
2597
|
|
|
2598
|
+
// src/runtime-kernel/token-accounting/index.ts
|
|
2599
|
+
var token_accounting_exports = {};
|
|
2600
|
+
__export(token_accounting_exports, {
|
|
2601
|
+
addLedgerAggregate: () => addLedgerAggregate,
|
|
2602
|
+
addUsageTotals: () => addUsageTotals,
|
|
2603
|
+
aggregateCanonicalUsage: () => aggregateCanonicalUsage,
|
|
2604
|
+
aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
|
|
2605
|
+
computeCost: () => computeCost,
|
|
2606
|
+
createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
|
|
2607
|
+
createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
|
|
2608
|
+
createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
|
|
2609
|
+
});
|
|
2610
|
+
|
|
2611
|
+
// src/runtime-kernel/token-accounting/functions.ts
|
|
2612
|
+
var EMPTY_LEDGER_AGGREGATE = {
|
|
2613
|
+
contextTokens: 0,
|
|
2614
|
+
entryCount: 0,
|
|
2615
|
+
llmCallCount: 0,
|
|
2616
|
+
contextComponentCount: 0
|
|
2617
|
+
};
|
|
2618
|
+
var TOKEN_PRICE_UNIT = 1e6;
|
|
2619
|
+
function sumReportedOptional(values) {
|
|
2620
|
+
const reported = values.filter((value) => value !== void 0);
|
|
2621
|
+
if (reported.length === 0) {
|
|
2622
|
+
return void 0;
|
|
2623
|
+
}
|
|
2624
|
+
return reported.reduce((total, value) => total + value, 0);
|
|
2625
|
+
}
|
|
2626
|
+
function sumTotalTokens(usages) {
|
|
2627
|
+
if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
|
|
2628
|
+
return void 0;
|
|
2629
|
+
}
|
|
2630
|
+
return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
|
|
2631
|
+
}
|
|
2632
|
+
function aggregateCanonicalUsage(usages) {
|
|
2633
|
+
if (usages.length === 0) {
|
|
2634
|
+
return void 0;
|
|
2635
|
+
}
|
|
2636
|
+
return {
|
|
2637
|
+
inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
|
|
2638
|
+
outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
|
|
2639
|
+
reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
|
|
2640
|
+
cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
|
|
2641
|
+
cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
|
|
2642
|
+
totalTokens: sumTotalTokens(usages),
|
|
2643
|
+
usageCount: usages.length
|
|
2644
|
+
};
|
|
2645
|
+
}
|
|
2646
|
+
function createLlmUsageLedgerEntry(input) {
|
|
2647
|
+
return {
|
|
2648
|
+
...input,
|
|
2649
|
+
kind: "llm-usage"
|
|
2650
|
+
};
|
|
2651
|
+
}
|
|
2652
|
+
function createContextComponentLedgerEntry(input) {
|
|
2653
|
+
return {
|
|
2654
|
+
...input,
|
|
2655
|
+
kind: "context-component",
|
|
2656
|
+
components: [...input.components],
|
|
2657
|
+
totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
|
|
2658
|
+
};
|
|
2659
|
+
}
|
|
2660
|
+
function addUsageTotals(left, right) {
|
|
2661
|
+
if (!left) {
|
|
2662
|
+
return right;
|
|
2663
|
+
}
|
|
2664
|
+
if (!right) {
|
|
2665
|
+
return left;
|
|
2666
|
+
}
|
|
2667
|
+
return {
|
|
2668
|
+
inputTokens: left.inputTokens + right.inputTokens,
|
|
2669
|
+
outputTokens: left.outputTokens + right.outputTokens,
|
|
2670
|
+
reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
|
|
2671
|
+
cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
|
|
2672
|
+
cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
|
|
2673
|
+
totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
|
|
2674
|
+
usageCount: left.usageCount + right.usageCount
|
|
2675
|
+
};
|
|
2676
|
+
}
|
|
2677
|
+
function addLedgerAggregate(left, right) {
|
|
2678
|
+
return {
|
|
2679
|
+
llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
|
|
2680
|
+
contextTokens: left.contextTokens + right.contextTokens,
|
|
2681
|
+
entryCount: left.entryCount + right.entryCount,
|
|
2682
|
+
llmCallCount: left.llmCallCount + right.llmCallCount,
|
|
2683
|
+
contextComponentCount: left.contextComponentCount + right.contextComponentCount
|
|
2684
|
+
};
|
|
2685
|
+
}
|
|
2686
|
+
function aggregateTokenLedgerEntries(entries) {
|
|
2687
|
+
const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
|
|
2688
|
+
return entries.reduce((aggregate, entry) => {
|
|
2689
|
+
if (entry.kind === "llm-usage") {
|
|
2690
|
+
return {
|
|
2691
|
+
...aggregate,
|
|
2692
|
+
entryCount: aggregate.entryCount + 1,
|
|
2693
|
+
llmCallCount: aggregate.llmCallCount + 1
|
|
2694
|
+
};
|
|
2695
|
+
}
|
|
2696
|
+
return {
|
|
2697
|
+
...aggregate,
|
|
2698
|
+
contextTokens: aggregate.contextTokens + entry.totalTokens,
|
|
2699
|
+
entryCount: aggregate.entryCount + 1,
|
|
2700
|
+
contextComponentCount: aggregate.contextComponentCount + entry.components.length
|
|
2701
|
+
};
|
|
2702
|
+
}, {
|
|
2703
|
+
...EMPTY_LEDGER_AGGREGATE,
|
|
2704
|
+
llmUsage: aggregateCanonicalUsage(llmUsages)
|
|
2705
|
+
});
|
|
2706
|
+
}
|
|
2707
|
+
function createRunTokenUsageAggregate(input) {
|
|
2708
|
+
const children = input.childAggregates?.reduce(
|
|
2709
|
+
(aggregate, child) => addLedgerAggregate(aggregate, child),
|
|
2710
|
+
EMPTY_LEDGER_AGGREGATE
|
|
2711
|
+
);
|
|
2712
|
+
return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
|
|
2713
|
+
}
|
|
2714
|
+
function componentCost(tokens, pricePerMillion) {
|
|
2715
|
+
return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
|
|
2716
|
+
}
|
|
2717
|
+
function needsPrice(tokens) {
|
|
2718
|
+
return tokens !== void 0 && tokens > 0;
|
|
2719
|
+
}
|
|
2720
|
+
function missingPriceComponents(usage, pricing) {
|
|
2721
|
+
const missing = [];
|
|
2722
|
+
if (!pricing) {
|
|
2723
|
+
if (needsPrice(usage.inputTokens)) {
|
|
2724
|
+
missing.push("input");
|
|
2725
|
+
}
|
|
2726
|
+
if (needsPrice(usage.outputTokens)) {
|
|
2727
|
+
missing.push("output");
|
|
2728
|
+
}
|
|
2729
|
+
if (needsPrice(usage.reasoningTokens)) {
|
|
2730
|
+
missing.push("reasoning");
|
|
2731
|
+
}
|
|
2732
|
+
if (needsPrice(usage.cacheReadTokens)) {
|
|
2733
|
+
missing.push("cacheRead");
|
|
2734
|
+
}
|
|
2735
|
+
if (needsPrice(usage.cacheWriteTokens)) {
|
|
2736
|
+
missing.push("cacheWrite");
|
|
2737
|
+
}
|
|
2738
|
+
return missing;
|
|
2739
|
+
}
|
|
2740
|
+
if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
|
|
2741
|
+
missing.push("input");
|
|
2742
|
+
}
|
|
2743
|
+
if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
|
|
2744
|
+
missing.push("output");
|
|
2745
|
+
}
|
|
2746
|
+
if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
|
|
2747
|
+
missing.push("reasoning");
|
|
2748
|
+
}
|
|
2749
|
+
if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
|
|
2750
|
+
missing.push("cacheRead");
|
|
2751
|
+
}
|
|
2752
|
+
if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
|
|
2753
|
+
missing.push("cacheWrite");
|
|
2754
|
+
}
|
|
2755
|
+
return missing;
|
|
2756
|
+
}
|
|
2757
|
+
function reportedComponentCost(tokens, pricePerMillion) {
|
|
2758
|
+
if (tokens === void 0) {
|
|
2759
|
+
return void 0;
|
|
2760
|
+
}
|
|
2761
|
+
if (tokens === 0) {
|
|
2762
|
+
return 0;
|
|
2763
|
+
}
|
|
2764
|
+
return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
|
|
2765
|
+
}
|
|
2766
|
+
function requiredComponentCost(tokens, pricePerMillion) {
|
|
2767
|
+
if (tokens === 0) {
|
|
2768
|
+
return 0;
|
|
2769
|
+
}
|
|
2770
|
+
return componentCost(tokens, pricePerMillion ?? 0);
|
|
2771
|
+
}
|
|
2772
|
+
function sumComputedCosts(costs) {
|
|
2773
|
+
let total = 0;
|
|
2774
|
+
for (const cost of costs) {
|
|
2775
|
+
total += cost ?? 0;
|
|
2776
|
+
}
|
|
2777
|
+
return total;
|
|
2778
|
+
}
|
|
2779
|
+
function computeCost(usage, pricing) {
|
|
2780
|
+
const missing = missingPriceComponents(usage, pricing);
|
|
2781
|
+
if (!pricing || missing.length > 0) {
|
|
2782
|
+
return {
|
|
2783
|
+
status: "unknown",
|
|
2784
|
+
...pricing ? { currency: pricing.currency } : {},
|
|
2785
|
+
...missing.length > 0 ? { missingPriceComponents: missing } : {}
|
|
2786
|
+
};
|
|
2787
|
+
}
|
|
2788
|
+
const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
|
|
2789
|
+
const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
|
|
2790
|
+
const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
|
|
2791
|
+
const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
|
|
2792
|
+
const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
|
|
2793
|
+
return {
|
|
2794
|
+
status: "computed",
|
|
2795
|
+
currency: pricing.currency,
|
|
2796
|
+
inputCost,
|
|
2797
|
+
outputCost,
|
|
2798
|
+
reasoningCost,
|
|
2799
|
+
cacheReadCost,
|
|
2800
|
+
cacheWriteCost,
|
|
2801
|
+
totalCost: sumComputedCosts([
|
|
2802
|
+
inputCost,
|
|
2803
|
+
outputCost,
|
|
2804
|
+
reasoningCost,
|
|
2805
|
+
cacheReadCost,
|
|
2806
|
+
cacheWriteCost
|
|
2807
|
+
])
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
|
|
2279
2811
|
// src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
|
|
2280
2812
|
var logger4 = new Logger("GraphAgentExecutor");
|
|
2281
2813
|
function createBuildContextStage(dependencies) {
|
|
@@ -2292,6 +2824,23 @@ function createBuildContextStage(dependencies) {
|
|
|
2292
2824
|
ctx.mode = contextBuildResult.mode;
|
|
2293
2825
|
ctx.llmMessages = contextBuildResult.llmMessages;
|
|
2294
2826
|
ctx.contextTrace = contextBuildResult.contextTrace;
|
|
2827
|
+
if (contextBuildResult.tokenEstimate) {
|
|
2828
|
+
const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
|
|
2829
|
+
ctx.telemetry.emit({
|
|
2830
|
+
kind: "context_build",
|
|
2831
|
+
modelId: ctx.modelId,
|
|
2832
|
+
mode: contextBuildResult.mode,
|
|
2833
|
+
tokenEstimate: contextBuildResult.tokenEstimate,
|
|
2834
|
+
...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
|
|
2835
|
+
...tokenLedgerEntry ? { tokenLedgerEntry } : {},
|
|
2836
|
+
scope: {
|
|
2837
|
+
conversationId: ctx.conversationId,
|
|
2838
|
+
runId: ctx.input.toolContext?.runId,
|
|
2839
|
+
parentRunId: ctx.input.toolContext?.parentRunId,
|
|
2840
|
+
turnId: ctx.turnId
|
|
2841
|
+
}
|
|
2842
|
+
});
|
|
2843
|
+
}
|
|
2295
2844
|
for (const event of contextBuildResult.summaryEvents) {
|
|
2296
2845
|
if (!isHistorySummaryEvent(event)) {
|
|
2297
2846
|
continue;
|
|
@@ -2306,6 +2855,24 @@ function createBuildContextStage(dependencies) {
|
|
|
2306
2855
|
}
|
|
2307
2856
|
};
|
|
2308
2857
|
}
|
|
2858
|
+
function createContextLedgerEntry(ctx, contextBuildResult) {
|
|
2859
|
+
const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
|
|
2860
|
+
if (keptComponents.length === 0) {
|
|
2861
|
+
return void 0;
|
|
2862
|
+
}
|
|
2863
|
+
const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
|
|
2864
|
+
const createdAt = Date.now();
|
|
2865
|
+
return createContextComponentLedgerEntry({
|
|
2866
|
+
id: `context_${runId}_${ctx.turnId}_${createdAt}`,
|
|
2867
|
+
conversationId: ctx.conversationId,
|
|
2868
|
+
runId,
|
|
2869
|
+
parentRunId: ctx.input.toolContext?.parentRunId,
|
|
2870
|
+
turnId: ctx.turnId,
|
|
2871
|
+
route: contextBuildResult.tokenEstimate?.route,
|
|
2872
|
+
createdAt,
|
|
2873
|
+
components: keptComponents
|
|
2874
|
+
});
|
|
2875
|
+
}
|
|
2309
2876
|
|
|
2310
2877
|
// src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
|
|
2311
2878
|
function createBuildDecisionStage(dependencies) {
|
|
@@ -2439,7 +3006,7 @@ function createExecuteLlmStage(dependencies) {
|
|
|
2439
3006
|
streamEventHandler,
|
|
2440
3007
|
ctx.signal,
|
|
2441
3008
|
(fallbackModelId) => {
|
|
2442
|
-
ctx.cloudQuotaFallbackAppliedModelId =
|
|
3009
|
+
ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
|
|
2443
3010
|
},
|
|
2444
3011
|
(info) => {
|
|
2445
3012
|
ctx.modelFallbackAudit = info;
|
|
@@ -2483,7 +3050,7 @@ function createPrepareCallStage(dependencies) {
|
|
|
2483
3050
|
return {
|
|
2484
3051
|
id: "prepare_call",
|
|
2485
3052
|
async run(ctx) {
|
|
2486
|
-
const lockedRunModelId =
|
|
3053
|
+
const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
|
|
2487
3054
|
const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
|
|
2488
3055
|
ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
|
|
2489
3056
|
await emitAuditEnvelope(ctx.audit, {
|
|
@@ -2549,19 +3116,21 @@ var GraphAgentExecutor = class {
|
|
|
2549
3116
|
modelCatalog;
|
|
2550
3117
|
telemetryPort;
|
|
2551
3118
|
auditPort;
|
|
3119
|
+
tokenizer;
|
|
2552
3120
|
stages;
|
|
2553
3121
|
middlewares;
|
|
2554
3122
|
constructor(dependencies) {
|
|
2555
3123
|
this.llmCaller = dependencies.llmCaller;
|
|
2556
3124
|
this.toolRuntime = dependencies.toolRuntime;
|
|
2557
3125
|
this.contextBuilder = dependencies.contextBuilder;
|
|
2558
|
-
this.cloudQuotaFallbackModelId =
|
|
3126
|
+
this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
|
|
2559
3127
|
this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
|
|
2560
3128
|
this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
|
|
2561
3129
|
modelCatalog: this.modelCatalog
|
|
2562
3130
|
});
|
|
2563
3131
|
this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
|
|
2564
3132
|
this.auditPort = dependencies.auditPort ?? noopAudit;
|
|
3133
|
+
this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
|
|
2565
3134
|
this.stages = [
|
|
2566
3135
|
createPrepareCallStage({
|
|
2567
3136
|
modelResolver: this.modelResolver,
|
|
@@ -2603,9 +3172,10 @@ var GraphAgentExecutor = class {
|
|
|
2603
3172
|
llmMessages: [],
|
|
2604
3173
|
mode: input.request.mode === "chat" ? "chat" : "agent",
|
|
2605
3174
|
conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
|
|
2606
|
-
turnId:
|
|
3175
|
+
turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
|
|
2607
3176
|
telemetry: this.telemetryPort,
|
|
2608
|
-
audit: this.auditPort
|
|
3177
|
+
audit: this.auditPort,
|
|
3178
|
+
tokenizer: this.tokenizer
|
|
2609
3179
|
};
|
|
2610
3180
|
logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
|
|
2611
3181
|
stream: input.stream === true,
|
|
@@ -2653,18 +3223,18 @@ function isSummarizationCallbacks(value) {
|
|
|
2653
3223
|
function isGraphSseSink(value) {
|
|
2654
3224
|
return typeof value === "function";
|
|
2655
3225
|
}
|
|
2656
|
-
function
|
|
3226
|
+
function readNonEmptyString3(value) {
|
|
2657
3227
|
if (typeof value !== "string") return void 0;
|
|
2658
3228
|
const trimmed = value.trim();
|
|
2659
3229
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
2660
3230
|
}
|
|
2661
3231
|
function readGraphAgentLocal(local) {
|
|
2662
3232
|
const source = local ?? {};
|
|
2663
|
-
const answerId =
|
|
3233
|
+
const answerId = readNonEmptyString3(source.answerId);
|
|
2664
3234
|
const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
|
|
2665
3235
|
return {
|
|
2666
|
-
conversationId:
|
|
2667
|
-
turnId:
|
|
3236
|
+
conversationId: readNonEmptyString3(source.conversationId) ?? "",
|
|
3237
|
+
turnId: readNonEmptyString3(source.turnId),
|
|
2668
3238
|
request: isAgentInvocationRequest(source.request) ? source.request : void 0,
|
|
2669
3239
|
toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
|
|
2670
3240
|
history: isRuntimeEventArray(source.history) ? source.history : [],
|
|
@@ -3429,7 +3999,7 @@ var LlmNode = class {
|
|
|
3429
3999
|
function isRecord8(value) {
|
|
3430
4000
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3431
4001
|
}
|
|
3432
|
-
function
|
|
4002
|
+
function readNonEmptyString4(value) {
|
|
3433
4003
|
if (typeof value !== "string") {
|
|
3434
4004
|
return void 0;
|
|
3435
4005
|
}
|
|
@@ -3451,7 +4021,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
|
|
|
3451
4021
|
return void 0;
|
|
3452
4022
|
}
|
|
3453
4023
|
if (toolName === "write_report") {
|
|
3454
|
-
const report =
|
|
4024
|
+
const report = readNonEmptyString4(data.report);
|
|
3455
4025
|
if (!report) {
|
|
3456
4026
|
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");
|
|
3457
4027
|
}
|
|
@@ -3461,7 +4031,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
|
|
|
3461
4031
|
if (data.success !== true) {
|
|
3462
4032
|
return void 0;
|
|
3463
4033
|
}
|
|
3464
|
-
const finalAnswer =
|
|
4034
|
+
const finalAnswer = readNonEmptyString4(data.final_answer);
|
|
3465
4035
|
if (!finalAnswer) {
|
|
3466
4036
|
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");
|
|
3467
4037
|
}
|
|
@@ -3570,11 +4140,11 @@ function buildToolOutputUiMeta(params) {
|
|
|
3570
4140
|
}
|
|
3571
4141
|
async function applyObservationGovernance(params) {
|
|
3572
4142
|
if (!params.structuredObservation || !isRecord9(params.parsed)) {
|
|
3573
|
-
return;
|
|
4143
|
+
return {};
|
|
3574
4144
|
}
|
|
3575
4145
|
const policy = resolveToolObservationGovernancePolicy(params.policy);
|
|
3576
4146
|
if (!policy.enabled) {
|
|
3577
|
-
return;
|
|
4147
|
+
return {};
|
|
3578
4148
|
}
|
|
3579
4149
|
const truncated = await params.observationPreview.truncateObservation({
|
|
3580
4150
|
context: params.toolContext,
|
|
@@ -3588,13 +4158,37 @@ async function applyObservationGovernance(params) {
|
|
|
3588
4158
|
})
|
|
3589
4159
|
});
|
|
3590
4160
|
if (!truncated.truncated) {
|
|
3591
|
-
return;
|
|
4161
|
+
return {};
|
|
3592
4162
|
}
|
|
3593
4163
|
params.parsed["observation"] = truncated.preview;
|
|
3594
4164
|
const data = params.parsed["data"];
|
|
3595
4165
|
if (isRecord9(data) && !("tool_output_store" in data)) {
|
|
3596
4166
|
data["tool_output_store"] = { blob_id: truncated.blob_id };
|
|
3597
4167
|
}
|
|
4168
|
+
return {
|
|
4169
|
+
observationTruncation: buildObservationTruncationMeta({
|
|
4170
|
+
originalText: params.structuredObservation,
|
|
4171
|
+
previewText: truncated.preview,
|
|
4172
|
+
originalChars: truncated.originalChars,
|
|
4173
|
+
previewChars: truncated.previewChars,
|
|
4174
|
+
originalLines: truncated.originalLines,
|
|
4175
|
+
previewLines: truncated.previewLines
|
|
4176
|
+
})
|
|
4177
|
+
};
|
|
4178
|
+
}
|
|
4179
|
+
function buildObservationTruncationMeta(input) {
|
|
4180
|
+
return {
|
|
4181
|
+
originalChars: input.originalChars ?? input.originalText.length,
|
|
4182
|
+
previewChars: input.previewChars ?? input.previewText.length,
|
|
4183
|
+
originalLines: input.originalLines ?? countLines(input.originalText),
|
|
4184
|
+
previewLines: input.previewLines ?? countLines(input.previewText)
|
|
4185
|
+
};
|
|
4186
|
+
}
|
|
4187
|
+
function countLines(value) {
|
|
4188
|
+
if (value.length === 0) {
|
|
4189
|
+
return 0;
|
|
4190
|
+
}
|
|
4191
|
+
return value.split(/\r\n|\r|\n/).length;
|
|
3598
4192
|
}
|
|
3599
4193
|
|
|
3600
4194
|
// src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
|
|
@@ -4006,6 +4600,31 @@ function ensureToolContextRuntimeCapability(params) {
|
|
|
4006
4600
|
function getToolContextRuntimeBinding(context) {
|
|
4007
4601
|
return readBinding(context);
|
|
4008
4602
|
}
|
|
4603
|
+
function copyToolContextRuntimeCapability(source, target) {
|
|
4604
|
+
const sourceBinding = readBinding(source);
|
|
4605
|
+
if (!sourceBinding) {
|
|
4606
|
+
return void 0;
|
|
4607
|
+
}
|
|
4608
|
+
const existingTargetBinding = readBinding(target);
|
|
4609
|
+
if (existingTargetBinding) {
|
|
4610
|
+
exposeCompatibilitySurface(target, existingTargetBinding);
|
|
4611
|
+
return existingTargetBinding;
|
|
4612
|
+
}
|
|
4613
|
+
const targetBinding = createRuntimeBinding({
|
|
4614
|
+
context: target,
|
|
4615
|
+
persistedHistory: () => sourceBinding.getPersistedHistoryEvents(),
|
|
4616
|
+
workingHistory: () => sourceBinding.getWorkingHistoryEvents(),
|
|
4617
|
+
executionMeta: sourceBinding.readExecutionMeta()
|
|
4618
|
+
});
|
|
4619
|
+
Object.defineProperty(target, TOOL_CONTEXT_RUNTIME_BINDING_KEY, {
|
|
4620
|
+
value: targetBinding,
|
|
4621
|
+
enumerable: false,
|
|
4622
|
+
configurable: true,
|
|
4623
|
+
writable: false
|
|
4624
|
+
});
|
|
4625
|
+
exposeCompatibilitySurface(target, targetBinding);
|
|
4626
|
+
return targetBinding;
|
|
4627
|
+
}
|
|
4009
4628
|
function readToolContextWorkingHistory(context) {
|
|
4010
4629
|
if (context.conversationView) {
|
|
4011
4630
|
return context.conversationView.getWorkingHistoryEvents();
|
|
@@ -4532,7 +5151,7 @@ var ToolNode = class {
|
|
|
4532
5151
|
parentRunId: context.toolContext.parentRunId
|
|
4533
5152
|
});
|
|
4534
5153
|
applyProtocolFuseState(context.local);
|
|
4535
|
-
await applyObservationGovernance({
|
|
5154
|
+
const observationGovernance = await applyObservationGovernance({
|
|
4536
5155
|
parsed: context.parsed,
|
|
4537
5156
|
toolName: context.toolName,
|
|
4538
5157
|
toolContext: context.toolContext,
|
|
@@ -4559,6 +5178,12 @@ var ToolNode = class {
|
|
|
4559
5178
|
runtimeToolOutput,
|
|
4560
5179
|
execIdempotency: context.exec.idempotency
|
|
4561
5180
|
});
|
|
5181
|
+
if (runtimeToolOutput && observationGovernance.observationTruncation) {
|
|
5182
|
+
runtimeToolOutput.metadata = {
|
|
5183
|
+
...runtimeToolOutput.metadata ?? {},
|
|
5184
|
+
observationTruncation: observationGovernance.observationTruncation
|
|
5185
|
+
};
|
|
5186
|
+
}
|
|
4562
5187
|
const remainingCalls = context.calls.slice(1);
|
|
4563
5188
|
context.state.local = buildSuccessLocalState({
|
|
4564
5189
|
local: context.local,
|
|
@@ -4857,12 +5482,12 @@ function asRecord(value) {
|
|
|
4857
5482
|
}
|
|
4858
5483
|
return value;
|
|
4859
5484
|
}
|
|
4860
|
-
function summarizeCheckpoint(
|
|
5485
|
+
function summarizeCheckpoint(checkpointKey, state, savedAt) {
|
|
4861
5486
|
const local = asRecord(state.local);
|
|
4862
5487
|
const executorLocal = asRecord(local?.executorLocal);
|
|
4863
5488
|
const pendingToolCalls = local?.pendingToolCalls;
|
|
4864
5489
|
return {
|
|
4865
|
-
|
|
5490
|
+
checkpointKey,
|
|
4866
5491
|
schemaVersion: state.schemaVersion ?? 1,
|
|
4867
5492
|
savedAt,
|
|
4868
5493
|
currentNode: state.nodeId,
|
|
@@ -4881,25 +5506,25 @@ var MemoryCheckpointer = class {
|
|
|
4881
5506
|
local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
|
|
4882
5507
|
};
|
|
4883
5508
|
}
|
|
4884
|
-
async load(
|
|
4885
|
-
const entry = this.store.get(
|
|
5509
|
+
async load(checkpointKey) {
|
|
5510
|
+
const entry = this.store.get(checkpointKey);
|
|
4886
5511
|
return entry ? this.cloneState(entry.state) : null;
|
|
4887
5512
|
}
|
|
4888
|
-
async save(
|
|
4889
|
-
this.store.set(
|
|
5513
|
+
async save(checkpointKey, state) {
|
|
5514
|
+
this.store.set(checkpointKey, {
|
|
4890
5515
|
state: this.cloneState(state),
|
|
4891
5516
|
savedAt: Date.now()
|
|
4892
5517
|
});
|
|
4893
5518
|
}
|
|
4894
|
-
async clear(
|
|
4895
|
-
this.store.delete(
|
|
5519
|
+
async clear(checkpointKey) {
|
|
5520
|
+
this.store.delete(checkpointKey);
|
|
4896
5521
|
}
|
|
4897
|
-
async peekMeta(
|
|
4898
|
-
const entry = this.store.get(
|
|
4899
|
-
return entry ? summarizeCheckpoint(
|
|
5522
|
+
async peekMeta(checkpointKey) {
|
|
5523
|
+
const entry = this.store.get(checkpointKey);
|
|
5524
|
+
return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
|
|
4900
5525
|
}
|
|
4901
5526
|
async list(filter = {}) {
|
|
4902
|
-
const summaries = Array.from(this.store.entries()).map(([
|
|
5527
|
+
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);
|
|
4903
5528
|
if (filter.limit === void 0) {
|
|
4904
5529
|
return summaries;
|
|
4905
5530
|
}
|
|
@@ -4971,6 +5596,7 @@ __export(tools_exports, {
|
|
|
4971
5596
|
CommonParameterTypes: () => CommonParameterTypes,
|
|
4972
5597
|
ContextCheckpointTool: () => ContextCheckpointTool,
|
|
4973
5598
|
computeToolIdempotencyKey: () => computeToolIdempotencyKey,
|
|
5599
|
+
copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
|
|
4974
5600
|
createContextCheckpointTool: () => createContextCheckpointTool,
|
|
4975
5601
|
ensureToolContextRuntimeCapability: () => ensureToolContextRuntimeCapability,
|
|
4976
5602
|
findCachedToolOutputByIdempotencyKey: () => findCachedToolOutputByIdempotencyKey,
|
|
@@ -5164,7 +5790,7 @@ function createContextCheckpointTool(options) {
|
|
|
5164
5790
|
function isRecord15(value) {
|
|
5165
5791
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
5166
5792
|
}
|
|
5167
|
-
function
|
|
5793
|
+
function readNonEmptyString5(value) {
|
|
5168
5794
|
if (typeof value !== "string") {
|
|
5169
5795
|
return void 0;
|
|
5170
5796
|
}
|
|
@@ -5184,13 +5810,13 @@ function readToolContextUserQuery(context) {
|
|
|
5184
5810
|
if (!context) {
|
|
5185
5811
|
return void 0;
|
|
5186
5812
|
}
|
|
5187
|
-
return
|
|
5813
|
+
return readNonEmptyString5(context["user_query"]);
|
|
5188
5814
|
}
|
|
5189
5815
|
function readToolContextModelId(context) {
|
|
5190
5816
|
if (!context) {
|
|
5191
5817
|
return void 0;
|
|
5192
5818
|
}
|
|
5193
|
-
return
|
|
5819
|
+
return readNonEmptyString5(context["modelId"]);
|
|
5194
5820
|
}
|
|
5195
5821
|
function readToolContextRunContext(context) {
|
|
5196
5822
|
if (!context) {
|
|
@@ -6392,6 +7018,7 @@ async function callLlmStream(params) {
|
|
|
6392
7018
|
const streamAnswerId = generateMessageId();
|
|
6393
7019
|
let streamChunkSeq = 0;
|
|
6394
7020
|
let capturedUsage = void 0;
|
|
7021
|
+
let capturedCanonicalUsage = void 0;
|
|
6395
7022
|
const toolAccumulator = new ToolCallStreamAccumulator([
|
|
6396
7023
|
"markdown_edit",
|
|
6397
7024
|
"text_to_image",
|
|
@@ -6450,6 +7077,10 @@ async function callLlmStream(params) {
|
|
|
6450
7077
|
if (typeof chunk !== "object" || chunk === null) {
|
|
6451
7078
|
return;
|
|
6452
7079
|
}
|
|
7080
|
+
const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
|
|
7081
|
+
if (parsedCanonicalUsage.success) {
|
|
7082
|
+
capturedCanonicalUsage = parsedCanonicalUsage.data;
|
|
7083
|
+
}
|
|
6453
7084
|
if (chunk.content) {
|
|
6454
7085
|
emitThoughtComplete(thoughtSegmenter.onBoundary());
|
|
6455
7086
|
fullResponse += chunk.content;
|
|
@@ -6534,6 +7165,12 @@ async function callLlmStream(params) {
|
|
|
6534
7165
|
const onUsage = (usage) => {
|
|
6535
7166
|
capturedUsage = usage;
|
|
6536
7167
|
};
|
|
7168
|
+
const onCanonicalUsage = (usage) => {
|
|
7169
|
+
const parsed = CanonicalLlmUsage.safeParse(usage);
|
|
7170
|
+
if (parsed.success) {
|
|
7171
|
+
capturedCanonicalUsage = parsed.data;
|
|
7172
|
+
}
|
|
7173
|
+
};
|
|
6537
7174
|
await aiEngine.chatCompletionStream(
|
|
6538
7175
|
modelId,
|
|
6539
7176
|
messages,
|
|
@@ -6546,7 +7183,8 @@ async function callLlmStream(params) {
|
|
|
6546
7183
|
onError,
|
|
6547
7184
|
onFinish,
|
|
6548
7185
|
onThought,
|
|
6549
|
-
onUsage
|
|
7186
|
+
onUsage,
|
|
7187
|
+
onCanonicalUsage
|
|
6550
7188
|
);
|
|
6551
7189
|
if (streamError) {
|
|
6552
7190
|
throw streamError;
|
|
@@ -6554,12 +7192,13 @@ async function callLlmStream(params) {
|
|
|
6554
7192
|
emitThoughtComplete(thoughtSegmenter.finalize());
|
|
6555
7193
|
const mergedToolCalls = toolAccumulator.getToolCalls();
|
|
6556
7194
|
assertToolCallsHaveValidJsonArguments(mergedToolCalls);
|
|
6557
|
-
if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
|
|
7195
|
+
if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
|
|
6558
7196
|
return {
|
|
6559
7197
|
content: fullResponse,
|
|
6560
7198
|
tool_calls: mergedToolCalls,
|
|
6561
7199
|
reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
|
|
6562
|
-
...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
|
|
7200
|
+
...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
|
|
7201
|
+
...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
|
|
6563
7202
|
};
|
|
6564
7203
|
}
|
|
6565
7204
|
return fullResponse;
|
|
@@ -6609,6 +7248,10 @@ function tryCloudQuotaFallback({
|
|
|
6609
7248
|
}
|
|
6610
7249
|
|
|
6611
7250
|
// src/runtime-kernel/llm/usage-telemetry.ts
|
|
7251
|
+
function parseCanonicalUsage(value) {
|
|
7252
|
+
const parsed = CanonicalLlmUsage.safeParse(value);
|
|
7253
|
+
return parsed.success ? parsed.data : void 0;
|
|
7254
|
+
}
|
|
6612
7255
|
async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
|
|
6613
7256
|
const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
|
|
6614
7257
|
return normalizeCompletionResponse(response);
|
|
@@ -6619,6 +7262,7 @@ function normalizeCompletionResponse(response) {
|
|
|
6619
7262
|
}
|
|
6620
7263
|
if (isRecord19(response)) {
|
|
6621
7264
|
const usage = response["usage"];
|
|
7265
|
+
const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
|
|
6622
7266
|
const parsedToolCalls = toToolCalls(response["tool_calls"]);
|
|
6623
7267
|
if (parsedToolCalls) {
|
|
6624
7268
|
const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
|
|
@@ -6626,7 +7270,8 @@ function normalizeCompletionResponse(response) {
|
|
|
6626
7270
|
content: typeof response["content"] === "string" ? response["content"] : "",
|
|
6627
7271
|
tool_calls: parsedToolCalls,
|
|
6628
7272
|
reasoning_details: reasoningDetails,
|
|
6629
|
-
...usage !== void 0 ? { usage } : {}
|
|
7273
|
+
...usage !== void 0 ? { usage } : {},
|
|
7274
|
+
...canonicalUsage !== void 0 ? { canonicalUsage } : {}
|
|
6630
7275
|
};
|
|
6631
7276
|
}
|
|
6632
7277
|
}
|
|
@@ -6636,10 +7281,12 @@ function normalizeCompletionResponse(response) {
|
|
|
6636
7281
|
if (typeof response === "object") {
|
|
6637
7282
|
if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
|
|
6638
7283
|
const usage = response["usage"];
|
|
7284
|
+
const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
|
|
6639
7285
|
return {
|
|
6640
7286
|
content: typeof response["content"] === "string" ? response["content"] : "",
|
|
6641
7287
|
reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
|
|
6642
|
-
...usage !== void 0 ? { usage } : {}
|
|
7288
|
+
...usage !== void 0 ? { usage } : {},
|
|
7289
|
+
...canonicalUsage !== void 0 ? { canonicalUsage } : {}
|
|
6643
7290
|
};
|
|
6644
7291
|
}
|
|
6645
7292
|
if (isRecord19(response)) {
|
|
@@ -6893,29 +7540,6 @@ var LlmCaller = class {
|
|
|
6893
7540
|
}
|
|
6894
7541
|
};
|
|
6895
7542
|
|
|
6896
|
-
// src/shared/defaultTokenizerPort.ts
|
|
6897
|
-
var DefaultTokenizerPort = class {
|
|
6898
|
-
constructor(config = {}) {
|
|
6899
|
-
this.config = config;
|
|
6900
|
-
}
|
|
6901
|
-
estimateText(text, _modelId) {
|
|
6902
|
-
return TokenCalculator.estimateTokens(text, {
|
|
6903
|
-
encoding: this.config.encoding,
|
|
6904
|
-
avgCharsPerToken: this.config.avgCharsPerToken
|
|
6905
|
-
});
|
|
6906
|
-
}
|
|
6907
|
-
estimateMessage(message, _modelId) {
|
|
6908
|
-
return TokenCalculator.estimateMessageTokens(message, {
|
|
6909
|
-
encoding: this.config.encoding,
|
|
6910
|
-
avgCharsPerToken: this.config.avgCharsPerToken,
|
|
6911
|
-
toolCallOverhead: this.config.toolCallOverhead
|
|
6912
|
-
});
|
|
6913
|
-
}
|
|
6914
|
-
};
|
|
6915
|
-
function createDefaultTokenizerPort(config = {}) {
|
|
6916
|
-
return new DefaultTokenizerPort(config);
|
|
6917
|
-
}
|
|
6918
|
-
|
|
6919
7543
|
// src/runtime-kernel/child-runs/index.ts
|
|
6920
7544
|
var child_runs_exports = {};
|
|
6921
7545
|
__export(child_runs_exports, {
|
|
@@ -6925,7 +7549,6 @@ __export(child_runs_exports, {
|
|
|
6925
7549
|
|
|
6926
7550
|
// src/runtime-kernel/child-runs/childToolContext.ts
|
|
6927
7551
|
function createChildRunToolContext(params) {
|
|
6928
|
-
const inheritedConversationId = typeof params.parentToolContext.conversationId === "string" && params.parentToolContext.conversationId.trim().length > 0 ? params.parentToolContext.conversationId.trim() : void 0;
|
|
6929
7552
|
const inheritedContext = stripRuntimeReservedToolContextPatch(params.parentToolContext);
|
|
6930
7553
|
const childToolContext = {
|
|
6931
7554
|
...inheritedContext,
|
|
@@ -6937,7 +7560,7 @@ function createChildRunToolContext(params) {
|
|
|
6937
7560
|
persistedHistory: params.seedHistory,
|
|
6938
7561
|
workingHistory: params.seedHistory,
|
|
6939
7562
|
executionMeta: {
|
|
6940
|
-
conversationId:
|
|
7563
|
+
conversationId: params.conversationId,
|
|
6941
7564
|
turnId: params.turnId,
|
|
6942
7565
|
runId: params.runId,
|
|
6943
7566
|
parentRunId: params.parentRunId
|
|
@@ -7039,6 +7662,8 @@ var FinalAnswerCollector = class {
|
|
|
7039
7662
|
this.conversationId = conversationId;
|
|
7040
7663
|
this.turnId = turnId;
|
|
7041
7664
|
}
|
|
7665
|
+
conversationId;
|
|
7666
|
+
turnId;
|
|
7042
7667
|
answerId;
|
|
7043
7668
|
chunks = [];
|
|
7044
7669
|
chunkCount = 0;
|
|
@@ -7255,7 +7880,7 @@ function readCheckpointHistory(checkpoint) {
|
|
|
7255
7880
|
});
|
|
7256
7881
|
}
|
|
7257
7882
|
async function recoverChildRunEventsFromCheckpoint(params) {
|
|
7258
|
-
const checkpoint = await params.checkpointer.load(params.
|
|
7883
|
+
const checkpoint = await params.checkpointer.load(params.checkpointKey);
|
|
7259
7884
|
const history = readCheckpointHistory(checkpoint);
|
|
7260
7885
|
if (history.length === 0) {
|
|
7261
7886
|
return [];
|
|
@@ -7263,7 +7888,7 @@ async function recoverChildRunEventsFromCheckpoint(params) {
|
|
|
7263
7888
|
if (hasSeedHistoryPrefix(history, params.seedHistory)) {
|
|
7264
7889
|
return history.slice(params.seedHistory.length);
|
|
7265
7890
|
}
|
|
7266
|
-
return history.filter((event) => event.conversation_id === params.
|
|
7891
|
+
return history.filter((event) => event.conversation_id === params.childConversationId);
|
|
7267
7892
|
}
|
|
7268
7893
|
|
|
7269
7894
|
// src/runtime-kernel/child-runs/childRunInvoker.ts
|
|
@@ -7292,6 +7917,7 @@ var ChildRunInvoker = class {
|
|
|
7292
7917
|
agentConfig,
|
|
7293
7918
|
userMessage,
|
|
7294
7919
|
parentToolContext,
|
|
7920
|
+
conversationId,
|
|
7295
7921
|
runId,
|
|
7296
7922
|
parentRunId,
|
|
7297
7923
|
subrunTracePublisher,
|
|
@@ -7300,12 +7926,18 @@ var ChildRunInvoker = class {
|
|
|
7300
7926
|
modelId,
|
|
7301
7927
|
abortSignal
|
|
7302
7928
|
} = config;
|
|
7303
|
-
const
|
|
7929
|
+
const internalCheckpointKey = `internal_${generateMessageId()}`;
|
|
7930
|
+
const runtimeConversationId = resolveChildRunConversationId({
|
|
7931
|
+
explicitConversationId: conversationId,
|
|
7932
|
+
parentToolContext,
|
|
7933
|
+
fallbackConversationId: internalCheckpointKey
|
|
7934
|
+
});
|
|
7304
7935
|
const turnId = `turn_${Date.now()}`;
|
|
7305
|
-
const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() :
|
|
7936
|
+
const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalCheckpointKey;
|
|
7306
7937
|
const resolvedParentRunId = typeof parentRunId === "string" && parentRunId.trim().length > 0 ? parentRunId.trim() : typeof parentToolContext.runId === "string" && parentToolContext.runId.trim().length > 0 ? parentToolContext.runId.trim() : void 0;
|
|
7307
7938
|
logger13.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
|
|
7308
|
-
conversationId:
|
|
7939
|
+
conversationId: runtimeConversationId,
|
|
7940
|
+
checkpointKey: internalCheckpointKey,
|
|
7309
7941
|
maxSteps,
|
|
7310
7942
|
userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
|
|
7311
7943
|
});
|
|
@@ -7366,7 +7998,7 @@ var ChildRunInvoker = class {
|
|
|
7366
7998
|
const seedHistory = Array.isArray(seedHistoryEvents) ? seedHistoryEvents : [];
|
|
7367
7999
|
const childToolContext = createChildRunToolContext({
|
|
7368
8000
|
parentToolContext,
|
|
7369
|
-
|
|
8001
|
+
conversationId: runtimeConversationId,
|
|
7370
8002
|
turnId,
|
|
7371
8003
|
runId: childRunId,
|
|
7372
8004
|
parentRunId: resolvedParentRunId,
|
|
@@ -7375,13 +8007,13 @@ var ChildRunInvoker = class {
|
|
|
7375
8007
|
});
|
|
7376
8008
|
const subrunSseSink = subrunTracePublisher ? createChildRunTraceSink({
|
|
7377
8009
|
publisher: subrunTracePublisher,
|
|
7378
|
-
conversationId:
|
|
8010
|
+
conversationId: runtimeConversationId,
|
|
7379
8011
|
turnId
|
|
7380
8012
|
}) : void 0;
|
|
7381
8013
|
const initialLocal = {
|
|
7382
8014
|
request,
|
|
7383
8015
|
history: seedHistory,
|
|
7384
|
-
conversationId:
|
|
8016
|
+
conversationId: runtimeConversationId,
|
|
7385
8017
|
turnId,
|
|
7386
8018
|
toolContext: childToolContext,
|
|
7387
8019
|
...abortSignal ? { signal: abortSignal } : {},
|
|
@@ -7389,7 +8021,7 @@ var ChildRunInvoker = class {
|
|
|
7389
8021
|
...subrunSseSink ? { sseSink: subrunSseSink } : {},
|
|
7390
8022
|
systemPrompt
|
|
7391
8023
|
};
|
|
7392
|
-
await graphExecutor.prime(
|
|
8024
|
+
await graphExecutor.prime(internalCheckpointKey, initialLocal, "llm");
|
|
7393
8025
|
const allEvents = [];
|
|
7394
8026
|
let stepCount = 0;
|
|
7395
8027
|
let finalAnswer;
|
|
@@ -7401,7 +8033,7 @@ var ChildRunInvoker = class {
|
|
|
7401
8033
|
err.name = "AbortError";
|
|
7402
8034
|
throw err;
|
|
7403
8035
|
}
|
|
7404
|
-
const result = await graphExecutor.runUntilYield(
|
|
8036
|
+
const result = await graphExecutor.runUntilYield(internalCheckpointKey);
|
|
7405
8037
|
appendUniqueEvents(allEvents, result.events);
|
|
7406
8038
|
stepCount = result.stepCount;
|
|
7407
8039
|
if (subrunSseSink && typeof subrunSseSink.finalize === "function") {
|
|
@@ -7435,8 +8067,8 @@ var ChildRunInvoker = class {
|
|
|
7435
8067
|
}
|
|
7436
8068
|
const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
|
|
7437
8069
|
checkpointer,
|
|
7438
|
-
|
|
7439
|
-
|
|
8070
|
+
checkpointKey: internalCheckpointKey,
|
|
8071
|
+
childConversationId: runtimeConversationId,
|
|
7440
8072
|
seedHistory
|
|
7441
8073
|
});
|
|
7442
8074
|
appendUniqueEvents(allEvents, recoveredEvents);
|
|
@@ -7453,7 +8085,7 @@ var ChildRunInvoker = class {
|
|
|
7453
8085
|
stack: err.stack
|
|
7454
8086
|
} : { error: String(err) });
|
|
7455
8087
|
}
|
|
7456
|
-
await checkpointer.clear(
|
|
8088
|
+
await checkpointer.clear(internalCheckpointKey);
|
|
7457
8089
|
return {
|
|
7458
8090
|
success: !error,
|
|
7459
8091
|
runId: childRunId,
|
|
@@ -7466,6 +8098,16 @@ var ChildRunInvoker = class {
|
|
|
7466
8098
|
};
|
|
7467
8099
|
}
|
|
7468
8100
|
};
|
|
8101
|
+
function readNonEmptyString6(value) {
|
|
8102
|
+
if (typeof value !== "string") {
|
|
8103
|
+
return void 0;
|
|
8104
|
+
}
|
|
8105
|
+
const trimmed = value.trim();
|
|
8106
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
8107
|
+
}
|
|
8108
|
+
function resolveChildRunConversationId(params) {
|
|
8109
|
+
return readNonEmptyString6(params.explicitConversationId) ?? readNonEmptyString6(params.parentToolContext.conversationId) ?? params.fallbackConversationId;
|
|
8110
|
+
}
|
|
7469
8111
|
function resolveChildRunSystemReminderPolicy(agentConfig) {
|
|
7470
8112
|
const configured = agentConfig.systemReminderPolicy ?? agentConfig.contextPolicy?.systemReminder;
|
|
7471
8113
|
const threshold = agentConfig.stepPolicy?.lastStepsHintThreshold;
|
|
@@ -7656,7 +8298,7 @@ function cloneRunRecord(record) {
|
|
|
7656
8298
|
...record,
|
|
7657
8299
|
iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
|
|
7658
8300
|
errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
|
|
7659
|
-
metadata: record.metadata ?
|
|
8301
|
+
metadata: record.metadata ? structuredClone(record.metadata) : void 0
|
|
7660
8302
|
};
|
|
7661
8303
|
}
|
|
7662
8304
|
function matchesStatus(candidate, filter) {
|
|
@@ -8068,7 +8710,7 @@ function isTerminalStatus(status) {
|
|
|
8068
8710
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
8069
8711
|
}
|
|
8070
8712
|
function cloneMetadata(metadata) {
|
|
8071
|
-
return metadata ?
|
|
8713
|
+
return metadata ? structuredClone(metadata) : void 0;
|
|
8072
8714
|
}
|
|
8073
8715
|
function recordToSnapshot(record) {
|
|
8074
8716
|
return {
|
|
@@ -8155,7 +8797,7 @@ var DefaultRunSupervisor = class {
|
|
|
8155
8797
|
startedAt,
|
|
8156
8798
|
updatedAt: startedAt,
|
|
8157
8799
|
iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
|
|
8158
|
-
metadata: spec.metadata
|
|
8800
|
+
metadata: cloneMetadata(spec.metadata)
|
|
8159
8801
|
};
|
|
8160
8802
|
await this.registryStore.save(record);
|
|
8161
8803
|
const handle = new DefaultRunHandle({
|
|
@@ -8329,12 +8971,13 @@ var DefaultRunSupervisor = class {
|
|
|
8329
8971
|
}
|
|
8330
8972
|
try {
|
|
8331
8973
|
await handle.markRunning({ currentNode: "detached" });
|
|
8974
|
+
const registeredRecord = await this.registryStore.load(handle.runId);
|
|
8332
8975
|
const executorOutcome = await this.executor.execute({
|
|
8333
8976
|
runId: handle.runId,
|
|
8334
|
-
parentRunId:
|
|
8335
|
-
conversationId: spec.conversationId,
|
|
8336
|
-
agentSpec: spec
|
|
8337
|
-
request:
|
|
8977
|
+
parentRunId: handle.parentRunId,
|
|
8978
|
+
conversationId: registeredRecord?.conversationId ?? spec.conversationId,
|
|
8979
|
+
agentSpec: await handle.spec(),
|
|
8980
|
+
request: await handle.request(),
|
|
8338
8981
|
signal: handle.signal,
|
|
8339
8982
|
eventBus: spec.eventBus,
|
|
8340
8983
|
eventStore: spec.eventStore,
|
|
@@ -8343,7 +8986,7 @@ var DefaultRunSupervisor = class {
|
|
|
8343
8986
|
contextFences: spec.contextFences,
|
|
8344
8987
|
wakeSource: spec.wakeSource,
|
|
8345
8988
|
ephemeral: spec.ephemeral,
|
|
8346
|
-
metadata: spec.metadata
|
|
8989
|
+
metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
|
|
8347
8990
|
});
|
|
8348
8991
|
const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
|
|
8349
8992
|
this.notifyTerminalWaiters(outcome);
|
|
@@ -8407,10 +9050,14 @@ var DefaultRunSupervisor = class {
|
|
|
8407
9050
|
await this.registryStore.save(record);
|
|
8408
9051
|
}
|
|
8409
9052
|
const completedAt = executorOutcome?.completedAt ?? this.now();
|
|
9053
|
+
const fallbackMeta = record ? void 0 : await handle.meta();
|
|
8410
9054
|
const outcome = recordToTerminalOutcome(record ?? {
|
|
8411
9055
|
runId: handle.runId,
|
|
8412
9056
|
parentRunId: handle.parentRunId,
|
|
8413
|
-
|
|
9057
|
+
conversationId: fallbackMeta?.conversationId ?? "",
|
|
9058
|
+
agentSpecId: fallbackMeta?.agentSpecId,
|
|
9059
|
+
status: executorOutcome?.status ?? "completed",
|
|
9060
|
+
startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
|
|
8414
9061
|
const nextOutcome = {
|
|
8415
9062
|
...outcome,
|
|
8416
9063
|
metadata: {
|
|
@@ -8502,6 +9149,7 @@ __export(telemetry_exports, {
|
|
|
8502
9149
|
var TELEMETRY_EVENT_KINDS = [
|
|
8503
9150
|
"llm_call",
|
|
8504
9151
|
"tool_call",
|
|
9152
|
+
"context_build",
|
|
8505
9153
|
"graph_node",
|
|
8506
9154
|
"run_lifecycle"
|
|
8507
9155
|
];
|
|
@@ -8638,6 +9286,7 @@ function createGraphLoopHarness(options) {
|
|
|
8638
9286
|
};
|
|
8639
9287
|
return {
|
|
8640
9288
|
async run() {
|
|
9289
|
+
const checkpointKey = options.conversationId;
|
|
8641
9290
|
const executor = createDefaultGraphExecutor({
|
|
8642
9291
|
llmNode: options.createLlmNode({
|
|
8643
9292
|
llmCaller: options.llmCaller,
|
|
@@ -8666,8 +9315,8 @@ function createGraphLoopHarness(options) {
|
|
|
8666
9315
|
signal: options.signal ?? options.toolContext.abortSignal,
|
|
8667
9316
|
executorLocal
|
|
8668
9317
|
};
|
|
8669
|
-
await executor.prime(
|
|
8670
|
-
const result = await executor.runUntilYield(
|
|
9318
|
+
await executor.prime(checkpointKey, local, "user");
|
|
9319
|
+
const result = await executor.runUntilYield(checkpointKey);
|
|
8671
9320
|
return {
|
|
8672
9321
|
checkpointNodeId: result.checkpoint.nodeId,
|
|
8673
9322
|
stepCount: result.stepCount
|
|
@@ -8676,6 +9325,6 @@ function createGraphLoopHarness(options) {
|
|
|
8676
9325
|
};
|
|
8677
9326
|
}
|
|
8678
9327
|
|
|
8679
|
-
export { AnswerNode, AuditEnvelopePersistenceError, BUILTIN_SYSTEM_REMINDER_TEMPLATES, BUILTIN_SYSTEM_REMINDER_TRIGGERS, BaseTool, CommonParameterTypes, CompositeAuditPort, ContextCheckpointTool, DEFAULT_CONTEXT_CHECKPOINT_TOOL_NAME, DefaultTokenizerPort, ENGINE_ERROR_CODES, ENGINE_STATE_SCHEMA_VERSION, EventBusSubRunTracePublisher, EventStoreAuditPort, FileAuditPort, GraphAgentExecutor, GraphExecutor, LLMPolicyEngine, LlmCaller, LlmNode, MemoryCheckpointer, MemoryEventStore, ModelResolver, SYSTEM_REMINDER_RULES, SystemReminderRegistry, ToolNode, UserNode, WaitUserNode, agentHasToolTrigger, appendStreamingProviderReasoningDetails, applySystemReminders, audit_exports as audit, budgetWarningTrigger, child_run_trace_exports as childRunTrace, child_runs_exports as childRuns, compactProviderReasoningDetails, compactReasoningDetailsInValue, computeToolIdempotencyKey, consoleAudit, contextBudgetWarningTemplate, countToolCallsInCurrentRequest, createCompositeAudit, createConsoleAudit, createContextCheckpointTool, createDefaultGraphExecutor, createDefaultSystemReminderRegistry, createDefaultTokenizerPort, createEventStoreAudit, createFileAudit, createGraphLoopHarness, createMonotonicEventIdFactory, createSystemReminderRules, defaultPolicyEngine, defaultSystemReminderRegistry, emitAuditEnvelope, emitSandboxDecisionAudit, enrichment_exports as enrichment, ensureToolContextRuntimeCapability, events_exports as events, execution_exports as execution, findCachedToolOutputByIdempotencyKey, getToolContextRuntimeBinding, graph_engine_exports as graph, lastStepsHintTemplate, llm_exports as llm, maxStepsForceFinalAnswerTemplate, noopAudit, normalizeToolArgs, periodicTaskstateReflectionTemplate, phaseEqualsTrigger, readContextCheckpointToolName, readNonEmptyStrings, readToolContextModelId, readToolContextPersistedHistory, readToolContextRunContext, readToolContextUserQuery, readToolContextWorkingHistory, remainingStepsLeqTrigger, requestEnricherRegistry, run_context_exports as runContext, run_supervisor_exports as runSupervisor, stepCountModuloTrigger, stripRuntimeReservedToolContextPatch, summarizeCheckpoint, system_reminder_exports as systemReminder, telemetry_exports as telemetry, toDisplayStep, toolCallStreakTemplate, toolCallStreakTrigger, tools_exports as tools };
|
|
9328
|
+
export { AnswerNode, AuditEnvelopePersistenceError, BUILTIN_SYSTEM_REMINDER_TEMPLATES, BUILTIN_SYSTEM_REMINDER_TRIGGERS, BaseTool, CommonParameterTypes, CompositeAuditPort, ContextCheckpointTool, DEFAULT_CONTEXT_CHECKPOINT_TOOL_NAME, DefaultTokenizerPort, ENGINE_ERROR_CODES, ENGINE_STATE_SCHEMA_VERSION, EventBusSubRunTracePublisher, EventStoreAuditPort, FileAuditPort, GraphAgentExecutor, GraphExecutor, LLMPolicyEngine, LlmCaller, LlmNode, MemoryCheckpointer, MemoryEventStore, ModelResolver, SYSTEM_REMINDER_RULES, SystemReminderRegistry, ToolNode, UserNode, WaitUserNode, addLedgerAggregate, addUsageTotals, agentHasToolTrigger, aggregateCanonicalUsage, aggregateTokenLedgerEntries, appendStreamingProviderReasoningDetails, applySystemReminders, audit_exports as audit, budgetWarningTrigger, child_run_trace_exports as childRunTrace, child_runs_exports as childRuns, compactProviderReasoningDetails, compactReasoningDetailsInValue, computeCost, computeToolIdempotencyKey, consoleAudit, contextBudgetWarningTemplate, copyToolContextRuntimeCapability, countToolCallsInCurrentRequest, createCompositeAudit, createConsoleAudit, createContextCheckpointTool, createContextComponentLedgerEntry, createDefaultGraphExecutor, createDefaultSystemReminderRegistry, createDefaultTokenizerPort, createEventStoreAudit, createFileAudit, createGraphLoopHarness, createLlmUsageLedgerEntry, createMonotonicEventIdFactory, createRunTokenUsageAggregate, createSystemReminderRules, defaultPolicyEngine, defaultSystemReminderRegistry, emitAuditEnvelope, emitSandboxDecisionAudit, enrichment_exports as enrichment, ensureToolContextRuntimeCapability, events_exports as events, execution_exports as execution, findCachedToolOutputByIdempotencyKey, getToolContextRuntimeBinding, graph_engine_exports as graph, lastStepsHintTemplate, llm_exports as llm, maxStepsForceFinalAnswerTemplate, noopAudit, normalizeToolArgs, periodicTaskstateReflectionTemplate, phaseEqualsTrigger, readContextCheckpointToolName, readNonEmptyStrings, readToolContextModelId, readToolContextPersistedHistory, readToolContextRunContext, readToolContextUserQuery, readToolContextWorkingHistory, remainingStepsLeqTrigger, requestEnricherRegistry, run_context_exports as runContext, run_supervisor_exports as runSupervisor, stepCountModuloTrigger, stripRuntimeReservedToolContextPatch, summarizeCheckpoint, system_reminder_exports as systemReminder, telemetry_exports as telemetry, toDisplayStep, token_accounting_exports as tokenAccounting, toolCallStreakTemplate, toolCallStreakTrigger, tools_exports as tools };
|
|
8680
9329
|
//# sourceMappingURL=runtime-kernel.js.map
|
|
8681
9330
|
//# sourceMappingURL=runtime-kernel.js.map
|