@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/testkit.js
CHANGED
|
@@ -104,7 +104,11 @@ __export(runtime_kernel_exports, {
|
|
|
104
104
|
ToolNode: () => ToolNode,
|
|
105
105
|
UserNode: () => UserNode,
|
|
106
106
|
WaitUserNode: () => WaitUserNode,
|
|
107
|
+
addLedgerAggregate: () => addLedgerAggregate,
|
|
108
|
+
addUsageTotals: () => addUsageTotals,
|
|
107
109
|
agentHasToolTrigger: () => agentHasToolTrigger,
|
|
110
|
+
aggregateCanonicalUsage: () => aggregateCanonicalUsage,
|
|
111
|
+
aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
|
|
108
112
|
appendStreamingProviderReasoningDetails: () => appendStreamingProviderReasoningDetails,
|
|
109
113
|
applySystemReminders: () => applySystemReminders,
|
|
110
114
|
audit: () => audit_exports,
|
|
@@ -113,20 +117,25 @@ __export(runtime_kernel_exports, {
|
|
|
113
117
|
childRuns: () => child_runs_exports,
|
|
114
118
|
compactProviderReasoningDetails: () => compactProviderReasoningDetails,
|
|
115
119
|
compactReasoningDetailsInValue: () => compactReasoningDetailsInValue,
|
|
120
|
+
computeCost: () => computeCost,
|
|
116
121
|
computeToolIdempotencyKey: () => computeToolIdempotencyKey,
|
|
117
122
|
consoleAudit: () => consoleAudit,
|
|
118
123
|
contextBudgetWarningTemplate: () => contextBudgetWarningTemplate,
|
|
124
|
+
copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
|
|
119
125
|
countToolCallsInCurrentRequest: () => countToolCallsInCurrentRequest,
|
|
120
126
|
createCompositeAudit: () => createCompositeAudit,
|
|
121
127
|
createConsoleAudit: () => createConsoleAudit,
|
|
122
128
|
createContextCheckpointTool: () => createContextCheckpointTool,
|
|
129
|
+
createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
|
|
123
130
|
createDefaultGraphExecutor: () => createDefaultGraphExecutor,
|
|
124
131
|
createDefaultSystemReminderRegistry: () => createDefaultSystemReminderRegistry,
|
|
125
132
|
createDefaultTokenizerPort: () => createDefaultTokenizerPort,
|
|
126
133
|
createEventStoreAudit: () => createEventStoreAudit,
|
|
127
134
|
createFileAudit: () => createFileAudit,
|
|
128
135
|
createGraphLoopHarness: () => createGraphLoopHarness,
|
|
136
|
+
createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
|
|
129
137
|
createMonotonicEventIdFactory: () => createMonotonicEventIdFactory,
|
|
138
|
+
createRunTokenUsageAggregate: () => createRunTokenUsageAggregate,
|
|
130
139
|
createSystemReminderRules: () => createSystemReminderRules,
|
|
131
140
|
defaultPolicyEngine: () => defaultPolicyEngine,
|
|
132
141
|
defaultSystemReminderRegistry: () => defaultSystemReminderRegistry,
|
|
@@ -163,6 +172,7 @@ __export(runtime_kernel_exports, {
|
|
|
163
172
|
systemReminder: () => system_reminder_exports,
|
|
164
173
|
telemetry: () => telemetry_exports,
|
|
165
174
|
toDisplayStep: () => toDisplayStep,
|
|
175
|
+
tokenAccounting: () => token_accounting_exports,
|
|
166
176
|
toolCallStreakTemplate: () => toolCallStreakTemplate,
|
|
167
177
|
toolCallStreakTrigger: () => toolCallStreakTrigger,
|
|
168
178
|
tools: () => tools_exports
|
|
@@ -197,6 +207,7 @@ var Logger = class {
|
|
|
197
207
|
constructor(moduleName) {
|
|
198
208
|
this.moduleName = moduleName;
|
|
199
209
|
}
|
|
210
|
+
moduleName;
|
|
200
211
|
debug(message, data) {
|
|
201
212
|
this.log(0 /* DEBUG */, "debug", message, data);
|
|
202
213
|
}
|
|
@@ -295,6 +306,12 @@ z.object({
|
|
|
295
306
|
args: z.record(z.unknown()).optional(),
|
|
296
307
|
tool_call_id: z.string()
|
|
297
308
|
});
|
|
309
|
+
var ObservationTruncationMeta = z.object({
|
|
310
|
+
originalChars: z.number().int().nonnegative(),
|
|
311
|
+
previewChars: z.number().int().nonnegative(),
|
|
312
|
+
originalLines: z.number().int().nonnegative().optional(),
|
|
313
|
+
previewLines: z.number().int().nonnegative().optional()
|
|
314
|
+
});
|
|
298
315
|
var ImageInfoMeta = z.object({
|
|
299
316
|
url: z.string().optional(),
|
|
300
317
|
width: z.number().int().positive().optional(),
|
|
@@ -326,6 +343,7 @@ var PersistentMetadata = z.object({
|
|
|
326
343
|
tool_name: z.string().optional(),
|
|
327
344
|
args: z.record(z.unknown()).optional(),
|
|
328
345
|
tool_call_id: z.string().optional(),
|
|
346
|
+
observationTruncation: ObservationTruncationMeta.optional(),
|
|
329
347
|
raw_output: z.string().optional(),
|
|
330
348
|
image_info: ImageInfoMeta.optional(),
|
|
331
349
|
taskType: z.string().optional(),
|
|
@@ -419,6 +437,7 @@ var AgentSpecBudgetPolicy = z.object({
|
|
|
419
437
|
});
|
|
420
438
|
var AgentSpecToolHistoryPolicy = z.object({
|
|
421
439
|
strategy: z.enum(["per-pair", "per-run", "none"]).optional(),
|
|
440
|
+
retentionMode: z.enum(["drop", "compress"]).optional(),
|
|
422
441
|
keepLatestToolPairs: z.number().int().nonnegative().optional(),
|
|
423
442
|
keepLatestRuns: z.number().int().nonnegative().optional(),
|
|
424
443
|
maxInteractionGroups: z.number().int().nonnegative().optional(),
|
|
@@ -471,7 +490,17 @@ var AgentSpecReasoningRetentionPolicy = z.object({
|
|
|
471
490
|
var AgentSpecTokenEstimationPolicy = z.object({
|
|
472
491
|
encoding: z.string().min(1).optional(),
|
|
473
492
|
avgCharsPerToken: z.number().positive().optional(),
|
|
474
|
-
toolCallOverhead: z.number().int().nonnegative().optional()
|
|
493
|
+
toolCallOverhead: z.number().int().nonnegative().optional(),
|
|
494
|
+
calibration: z.object({
|
|
495
|
+
enabled: z.boolean().optional(),
|
|
496
|
+
minSamples: z.number().int().positive().optional(),
|
|
497
|
+
minCoefficient: z.number().positive().optional(),
|
|
498
|
+
maxCoefficient: z.number().positive().optional()
|
|
499
|
+
}).optional(),
|
|
500
|
+
remoteCount: z.object({
|
|
501
|
+
enabled: z.boolean().optional(),
|
|
502
|
+
failureBehavior: z.enum(["use-local-estimate", "fail-fast"]).optional()
|
|
503
|
+
}).optional()
|
|
475
504
|
});
|
|
476
505
|
var AgentSpecSystemReminderTrigger = z.object({
|
|
477
506
|
kind: z.string().min(1),
|
|
@@ -1169,12 +1198,206 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
|
|
|
1169
1198
|
error,
|
|
1170
1199
|
...options
|
|
1171
1200
|
});
|
|
1201
|
+
var TokenCountSource = z.enum([
|
|
1202
|
+
"local-estimate",
|
|
1203
|
+
"provider-preflight-count",
|
|
1204
|
+
"provider-response-usage",
|
|
1205
|
+
"host-supplied",
|
|
1206
|
+
"test-fixture"
|
|
1207
|
+
]);
|
|
1208
|
+
var TokenCountConfidence = z.enum([
|
|
1209
|
+
"estimate",
|
|
1210
|
+
"provider-estimate",
|
|
1211
|
+
"actual"
|
|
1212
|
+
]);
|
|
1213
|
+
var TokenRouteCapabilities = z.object({
|
|
1214
|
+
supportsRemoteTokenCount: z.boolean().optional(),
|
|
1215
|
+
supportsResponseUsage: z.boolean().optional(),
|
|
1216
|
+
supportsImageInput: z.boolean().optional(),
|
|
1217
|
+
supportsCachedInputBilling: z.boolean().optional(),
|
|
1218
|
+
supportsReasoningTokens: z.boolean().optional()
|
|
1219
|
+
});
|
|
1220
|
+
var TokenRoute = z.object({
|
|
1221
|
+
providerId: z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
|
|
1222
|
+
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"),
|
|
1223
|
+
modelId: z.string().describe("host \u4FA7\u6A21\u578B id"),
|
|
1224
|
+
providerModelId: z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
|
|
1225
|
+
capabilities: TokenRouteCapabilities.optional()
|
|
1226
|
+
});
|
|
1227
|
+
var tokenCount = z.number().int().nonnegative();
|
|
1228
|
+
var CanonicalLlmUsage = z.object({
|
|
1229
|
+
inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
|
|
1230
|
+
outputTokens: tokenCount.describe("\u8F93\u51FA token"),
|
|
1231
|
+
reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
|
|
1232
|
+
cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
|
|
1233
|
+
cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
|
|
1234
|
+
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"),
|
|
1235
|
+
source: TokenCountSource,
|
|
1236
|
+
confidence: TokenCountConfidence,
|
|
1237
|
+
rawUsage: z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
|
|
1238
|
+
});
|
|
1239
|
+
var tokenCount2 = z.number().int().nonnegative();
|
|
1240
|
+
var tokenPrice = z.number().finite().nonnegative();
|
|
1241
|
+
z.enum([
|
|
1242
|
+
"llm-usage",
|
|
1243
|
+
"context-component"
|
|
1244
|
+
]);
|
|
1245
|
+
var ContextTokenComponentKind = z.enum([
|
|
1246
|
+
"system",
|
|
1247
|
+
"user",
|
|
1248
|
+
"assistant",
|
|
1249
|
+
"tool",
|
|
1250
|
+
"context-injection",
|
|
1251
|
+
"history-summary",
|
|
1252
|
+
"working-memory",
|
|
1253
|
+
"fence",
|
|
1254
|
+
"system-reminder",
|
|
1255
|
+
"other"
|
|
1256
|
+
]);
|
|
1257
|
+
var TokenUsageTotals = z.object({
|
|
1258
|
+
inputTokens: tokenCount2,
|
|
1259
|
+
outputTokens: tokenCount2,
|
|
1260
|
+
reasoningTokens: tokenCount2.optional(),
|
|
1261
|
+
cacheReadTokens: tokenCount2.optional(),
|
|
1262
|
+
cacheWriteTokens: tokenCount2.optional(),
|
|
1263
|
+
totalTokens: tokenCount2.optional(),
|
|
1264
|
+
usageCount: z.number().int().nonnegative()
|
|
1265
|
+
});
|
|
1266
|
+
var ContextTokenComponent = z.object({
|
|
1267
|
+
componentId: z.string().min(1),
|
|
1268
|
+
kind: ContextTokenComponentKind,
|
|
1269
|
+
tokens: tokenCount2,
|
|
1270
|
+
source: TokenCountSource,
|
|
1271
|
+
confidence: TokenCountConfidence,
|
|
1272
|
+
label: z.string().optional(),
|
|
1273
|
+
messageId: z.string().optional(),
|
|
1274
|
+
role: z.string().optional(),
|
|
1275
|
+
action: z.string().optional(),
|
|
1276
|
+
kept: z.boolean().optional(),
|
|
1277
|
+
truncatedAtExecution: z.boolean().optional(),
|
|
1278
|
+
originalTokensEstimate: tokenCount2.optional(),
|
|
1279
|
+
droppedTokensEstimate: tokenCount2.optional()
|
|
1280
|
+
});
|
|
1281
|
+
var TokenLedgerEntryBase = z.object({
|
|
1282
|
+
id: z.string().min(1),
|
|
1283
|
+
runId: z.string().optional(),
|
|
1284
|
+
parentRunId: z.string().optional(),
|
|
1285
|
+
conversationId: z.string().optional(),
|
|
1286
|
+
turnId: z.string().optional(),
|
|
1287
|
+
stepId: z.string().optional(),
|
|
1288
|
+
route: TokenRoute.optional(),
|
|
1289
|
+
createdAt: z.number().int().nonnegative().optional()
|
|
1290
|
+
});
|
|
1291
|
+
var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
|
|
1292
|
+
kind: z.literal("llm-usage"),
|
|
1293
|
+
modelId: z.string().optional(),
|
|
1294
|
+
usage: CanonicalLlmUsage
|
|
1295
|
+
});
|
|
1296
|
+
var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
|
|
1297
|
+
kind: z.literal("context-component"),
|
|
1298
|
+
components: z.array(ContextTokenComponent),
|
|
1299
|
+
totalTokens: tokenCount2
|
|
1300
|
+
});
|
|
1301
|
+
z.discriminatedUnion("kind", [
|
|
1302
|
+
LlmUsageTokenLedgerEntry,
|
|
1303
|
+
ContextComponentTokenLedgerEntry
|
|
1304
|
+
]);
|
|
1305
|
+
var TokenLedgerAggregate = z.object({
|
|
1306
|
+
llmUsage: TokenUsageTotals.optional(),
|
|
1307
|
+
contextTokens: tokenCount2,
|
|
1308
|
+
entryCount: z.number().int().nonnegative(),
|
|
1309
|
+
llmCallCount: z.number().int().nonnegative(),
|
|
1310
|
+
contextComponentCount: z.number().int().nonnegative()
|
|
1311
|
+
});
|
|
1312
|
+
z.object({
|
|
1313
|
+
/**
|
|
1314
|
+
* 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
|
|
1315
|
+
*/
|
|
1316
|
+
own: TokenLedgerAggregate,
|
|
1317
|
+
children: TokenLedgerAggregate.optional()
|
|
1318
|
+
});
|
|
1319
|
+
var TokenCostComponent = z.enum([
|
|
1320
|
+
"input",
|
|
1321
|
+
"output",
|
|
1322
|
+
"reasoning",
|
|
1323
|
+
"cacheRead",
|
|
1324
|
+
"cacheWrite"
|
|
1325
|
+
]);
|
|
1326
|
+
z.object({
|
|
1327
|
+
currency: z.string().min(1),
|
|
1328
|
+
unit: z.literal("per_1m_tokens"),
|
|
1329
|
+
input: tokenPrice.optional(),
|
|
1330
|
+
output: tokenPrice.optional(),
|
|
1331
|
+
reasoning: tokenPrice.optional(),
|
|
1332
|
+
cacheRead: tokenPrice.optional(),
|
|
1333
|
+
cacheWrite: tokenPrice.optional()
|
|
1334
|
+
});
|
|
1335
|
+
z.object({
|
|
1336
|
+
status: z.enum(["computed", "unknown"]),
|
|
1337
|
+
currency: z.string().optional(),
|
|
1338
|
+
inputCost: tokenPrice.optional(),
|
|
1339
|
+
outputCost: tokenPrice.optional(),
|
|
1340
|
+
reasoningCost: tokenPrice.optional(),
|
|
1341
|
+
cacheReadCost: tokenPrice.optional(),
|
|
1342
|
+
cacheWriteCost: tokenPrice.optional(),
|
|
1343
|
+
totalCost: tokenPrice.optional(),
|
|
1344
|
+
missingPriceComponents: z.array(TokenCostComponent).optional()
|
|
1345
|
+
});
|
|
1346
|
+
var tokenCount3 = z.number().int().nonnegative();
|
|
1347
|
+
var actualCalibrationSource = z.enum([
|
|
1348
|
+
"provider-response-usage",
|
|
1349
|
+
"host-supplied",
|
|
1350
|
+
"test-fixture"
|
|
1351
|
+
]);
|
|
1352
|
+
z.object({
|
|
1353
|
+
route: TokenRoute,
|
|
1354
|
+
localEstimateTokens: tokenCount3,
|
|
1355
|
+
actualInputTokens: tokenCount3,
|
|
1356
|
+
source: actualCalibrationSource,
|
|
1357
|
+
confidence: z.literal("actual"),
|
|
1358
|
+
observedAt: z.number().int().nonnegative().optional(),
|
|
1359
|
+
runId: z.string().optional(),
|
|
1360
|
+
ledgerEntryId: z.string().optional()
|
|
1361
|
+
});
|
|
1362
|
+
z.object({
|
|
1363
|
+
enabled: z.boolean(),
|
|
1364
|
+
applied: z.boolean(),
|
|
1365
|
+
route: TokenRoute.optional(),
|
|
1366
|
+
sampleCount: z.number().int().nonnegative(),
|
|
1367
|
+
coefficient: z.number().positive().optional(),
|
|
1368
|
+
minSamples: z.number().int().positive().optional(),
|
|
1369
|
+
minCoefficient: z.number().positive().optional(),
|
|
1370
|
+
maxCoefficient: z.number().positive().optional(),
|
|
1371
|
+
localEstimateTokens: tokenCount3.optional(),
|
|
1372
|
+
calibratedEstimateTokens: tokenCount3.optional(),
|
|
1373
|
+
deltaTokens: z.number().int().optional(),
|
|
1374
|
+
sampleLedgerEntryIds: z.array(z.string()).optional()
|
|
1375
|
+
});
|
|
1376
|
+
z.object({
|
|
1377
|
+
route: TokenRoute.optional(),
|
|
1378
|
+
localEstimateTokens: tokenCount3,
|
|
1379
|
+
calibratedEstimateTokens: tokenCount3,
|
|
1380
|
+
finalTokens: tokenCount3,
|
|
1381
|
+
source: z.literal("local-estimate"),
|
|
1382
|
+
confidence: z.literal("estimate")
|
|
1383
|
+
});
|
|
1172
1384
|
|
|
1173
1385
|
// src/runtime-kernel/graph-engine/engine.ts
|
|
1174
1386
|
var logger = new Logger("GraphExecutor");
|
|
1175
1387
|
function asLocalRecord(local) {
|
|
1176
1388
|
return local && typeof local === "object" ? { ...local } : {};
|
|
1177
1389
|
}
|
|
1390
|
+
function readNonEmptyString(value) {
|
|
1391
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
1392
|
+
}
|
|
1393
|
+
function readRuntimeConversationId(state) {
|
|
1394
|
+
const local = state?.local && typeof state.local === "object" ? state.local : void 0;
|
|
1395
|
+
return readNonEmptyString(local?.conversationId);
|
|
1396
|
+
}
|
|
1397
|
+
function readRuntimeTurnId(state) {
|
|
1398
|
+
const local = state?.local && typeof state.local === "object" ? state.local : void 0;
|
|
1399
|
+
return readNonEmptyString(local?.turnId);
|
|
1400
|
+
}
|
|
1178
1401
|
var GraphExecutor = class {
|
|
1179
1402
|
constructor(checkpointer, config = {}) {
|
|
1180
1403
|
this.checkpointer = checkpointer;
|
|
@@ -1184,6 +1407,7 @@ var GraphExecutor = class {
|
|
|
1184
1407
|
};
|
|
1185
1408
|
this.telemetryPort = config.telemetryPort ?? noopTelemetry;
|
|
1186
1409
|
}
|
|
1410
|
+
checkpointer;
|
|
1187
1411
|
nodes = /* @__PURE__ */ new Map();
|
|
1188
1412
|
ephemeralLocals = /* @__PURE__ */ new Map();
|
|
1189
1413
|
config;
|
|
@@ -1191,8 +1415,8 @@ var GraphExecutor = class {
|
|
|
1191
1415
|
registerNode(node) {
|
|
1192
1416
|
this.nodes.set(node.id, node);
|
|
1193
1417
|
}
|
|
1194
|
-
async peekCheckpoint(
|
|
1195
|
-
return await this.checkpointer.load(
|
|
1418
|
+
async peekCheckpoint(checkpointKey) {
|
|
1419
|
+
return await this.checkpointer.load(checkpointKey);
|
|
1196
1420
|
}
|
|
1197
1421
|
sanitize(state) {
|
|
1198
1422
|
const local = asLocalRecord(state.local);
|
|
@@ -1204,8 +1428,8 @@ var GraphExecutor = class {
|
|
|
1204
1428
|
local
|
|
1205
1429
|
};
|
|
1206
1430
|
}
|
|
1207
|
-
async prime(
|
|
1208
|
-
this.ephemeralLocals.set(
|
|
1431
|
+
async prime(checkpointKey, local, nodeId = "user") {
|
|
1432
|
+
this.ephemeralLocals.set(checkpointKey, { ...local || {} });
|
|
1209
1433
|
const localSansMemory = { ...local || {} };
|
|
1210
1434
|
if ("memory" in localSansMemory) delete localSansMemory.memory;
|
|
1211
1435
|
const state = {
|
|
@@ -1213,10 +1437,10 @@ var GraphExecutor = class {
|
|
|
1213
1437
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1214
1438
|
local: localSansMemory
|
|
1215
1439
|
};
|
|
1216
|
-
await this.checkpointer.save(
|
|
1440
|
+
await this.checkpointer.save(checkpointKey, state);
|
|
1217
1441
|
}
|
|
1218
|
-
async setNode(
|
|
1219
|
-
const current = await this.checkpointer.load(
|
|
1442
|
+
async setNode(checkpointKey, nodeId, localPatch) {
|
|
1443
|
+
const current = await this.checkpointer.load(checkpointKey) || {
|
|
1220
1444
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1221
1445
|
local: {}
|
|
1222
1446
|
};
|
|
@@ -1227,19 +1451,46 @@ var GraphExecutor = class {
|
|
|
1227
1451
|
schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
1228
1452
|
local: mergedLocal
|
|
1229
1453
|
};
|
|
1230
|
-
await this.checkpointer.save(
|
|
1454
|
+
await this.checkpointer.save(checkpointKey, next);
|
|
1231
1455
|
}
|
|
1232
|
-
async runUntilYield(
|
|
1456
|
+
async runUntilYield(checkpointKey) {
|
|
1233
1457
|
const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1234
1458
|
let lifecyclePhase = "completed";
|
|
1459
|
+
let initialState = null;
|
|
1460
|
+
try {
|
|
1461
|
+
initialState = await this.loadInitialState(checkpointKey);
|
|
1462
|
+
} catch (err) {
|
|
1463
|
+
lifecyclePhase = "failed";
|
|
1464
|
+
this.telemetryPort.emit({
|
|
1465
|
+
kind: "run_lifecycle",
|
|
1466
|
+
runId,
|
|
1467
|
+
phase: "spawned",
|
|
1468
|
+
scope: {}
|
|
1469
|
+
});
|
|
1470
|
+
this.telemetryPort.emit({
|
|
1471
|
+
kind: "run_lifecycle",
|
|
1472
|
+
runId,
|
|
1473
|
+
phase: lifecyclePhase,
|
|
1474
|
+
scope: {}
|
|
1475
|
+
});
|
|
1476
|
+
throw err;
|
|
1477
|
+
}
|
|
1478
|
+
let lifecycleConversationId = readRuntimeConversationId(initialState);
|
|
1479
|
+
let lifecycleTurnId = readRuntimeTurnId(initialState);
|
|
1235
1480
|
this.telemetryPort.emit({
|
|
1236
1481
|
kind: "run_lifecycle",
|
|
1237
1482
|
runId,
|
|
1238
1483
|
phase: "spawned",
|
|
1239
|
-
scope: {
|
|
1484
|
+
scope: {
|
|
1485
|
+
conversationId: lifecycleConversationId,
|
|
1486
|
+
turnId: lifecycleTurnId
|
|
1487
|
+
}
|
|
1240
1488
|
});
|
|
1241
1489
|
try {
|
|
1242
|
-
|
|
1490
|
+
const result = await this.runUntilYieldInternal(checkpointKey, initialState);
|
|
1491
|
+
lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
|
|
1492
|
+
lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
|
|
1493
|
+
return result;
|
|
1243
1494
|
} catch (err) {
|
|
1244
1495
|
lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
|
|
1245
1496
|
throw err;
|
|
@@ -1248,17 +1499,23 @@ var GraphExecutor = class {
|
|
|
1248
1499
|
kind: "run_lifecycle",
|
|
1249
1500
|
runId,
|
|
1250
1501
|
phase: lifecyclePhase,
|
|
1251
|
-
scope: {
|
|
1502
|
+
scope: {
|
|
1503
|
+
conversationId: lifecycleConversationId,
|
|
1504
|
+
turnId: lifecycleTurnId
|
|
1505
|
+
}
|
|
1252
1506
|
});
|
|
1253
1507
|
}
|
|
1254
1508
|
}
|
|
1255
|
-
async
|
|
1256
|
-
|
|
1509
|
+
async loadInitialState(checkpointKey) {
|
|
1510
|
+
return await this.checkpointer.load(checkpointKey) || {
|
|
1257
1511
|
nodeId: "user",
|
|
1258
1512
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
1259
1513
|
local: {}
|
|
1260
1514
|
};
|
|
1261
|
-
|
|
1515
|
+
}
|
|
1516
|
+
async runUntilYieldInternal(checkpointKey, initialState) {
|
|
1517
|
+
let state = initialState;
|
|
1518
|
+
const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
|
|
1262
1519
|
state = {
|
|
1263
1520
|
...state,
|
|
1264
1521
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
@@ -1287,7 +1544,7 @@ var GraphExecutor = class {
|
|
|
1287
1544
|
const signalRaw = state.local?.signal;
|
|
1288
1545
|
if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
|
|
1289
1546
|
logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
|
|
1290
|
-
this.ephemeralLocals.delete(
|
|
1547
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1291
1548
|
throwAbortError();
|
|
1292
1549
|
}
|
|
1293
1550
|
const isLastStep = cycleStepCount >= this.config.maxSteps;
|
|
@@ -1335,8 +1592,8 @@ var GraphExecutor = class {
|
|
|
1335
1592
|
checkpointCount
|
|
1336
1593
|
});
|
|
1337
1594
|
const cp2 = this.sanitize(state);
|
|
1338
|
-
await this.checkpointer.save(
|
|
1339
|
-
this.ephemeralLocals.delete(
|
|
1595
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1596
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1340
1597
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1341
1598
|
}
|
|
1342
1599
|
logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
|
|
@@ -1347,18 +1604,18 @@ var GraphExecutor = class {
|
|
|
1347
1604
|
});
|
|
1348
1605
|
const nodeRunStartedAt = Date.now();
|
|
1349
1606
|
const nodeIdForTelemetry = state.nodeId;
|
|
1607
|
+
const conversationIdForTelemetry = readRuntimeConversationId(state);
|
|
1350
1608
|
let result;
|
|
1351
1609
|
try {
|
|
1352
1610
|
result = await node.run(state);
|
|
1353
1611
|
} finally {
|
|
1354
|
-
const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
|
|
1355
1612
|
this.telemetryPort.emit({
|
|
1356
1613
|
kind: "graph_node",
|
|
1357
1614
|
nodeId: nodeIdForTelemetry,
|
|
1358
1615
|
durationMs: Date.now() - nodeRunStartedAt,
|
|
1359
1616
|
scope: {
|
|
1360
|
-
conversationId:
|
|
1361
|
-
turnId:
|
|
1617
|
+
conversationId: conversationIdForTelemetry,
|
|
1618
|
+
turnId: readRuntimeTurnId(state)
|
|
1362
1619
|
}
|
|
1363
1620
|
});
|
|
1364
1621
|
}
|
|
@@ -1397,7 +1654,7 @@ var GraphExecutor = class {
|
|
|
1397
1654
|
});
|
|
1398
1655
|
state = { ...state, nodeId: nextNodeId };
|
|
1399
1656
|
const cp2 = this.sanitize(state);
|
|
1400
|
-
await this.checkpointer.save(
|
|
1657
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1401
1658
|
continue;
|
|
1402
1659
|
}
|
|
1403
1660
|
if (result.kind === "yield") {
|
|
@@ -1408,7 +1665,7 @@ var GraphExecutor = class {
|
|
|
1408
1665
|
checkpointCount
|
|
1409
1666
|
});
|
|
1410
1667
|
const cp2 = this.sanitize(state);
|
|
1411
|
-
await this.checkpointer.save(
|
|
1668
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1412
1669
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1413
1670
|
}
|
|
1414
1671
|
if (result.kind === "pause") {
|
|
@@ -1419,7 +1676,7 @@ var GraphExecutor = class {
|
|
|
1419
1676
|
checkpointCount
|
|
1420
1677
|
});
|
|
1421
1678
|
const cp2 = this.sanitize(state);
|
|
1422
|
-
await this.checkpointer.save(
|
|
1679
|
+
await this.checkpointer.save(checkpointKey, cp2);
|
|
1423
1680
|
return { events: allEvents, checkpoint: cp2, stepCount };
|
|
1424
1681
|
}
|
|
1425
1682
|
}
|
|
@@ -1430,8 +1687,8 @@ var GraphExecutor = class {
|
|
|
1430
1687
|
checkpointCount
|
|
1431
1688
|
});
|
|
1432
1689
|
const cp = this.sanitize(state);
|
|
1433
|
-
await this.checkpointer.save(
|
|
1434
|
-
this.ephemeralLocals.delete(
|
|
1690
|
+
await this.checkpointer.save(checkpointKey, cp);
|
|
1691
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
1435
1692
|
return { events: allEvents, checkpoint: cp, stepCount };
|
|
1436
1693
|
}
|
|
1437
1694
|
};
|
|
@@ -1527,6 +1784,190 @@ var noopAudit = {
|
|
|
1527
1784
|
flush() {
|
|
1528
1785
|
}
|
|
1529
1786
|
};
|
|
1787
|
+
var TokenCalculator = class {
|
|
1788
|
+
static BYTES_PER_TOKEN_LATIN = 4;
|
|
1789
|
+
static BYTES_PER_TOKEN_CJK = 3;
|
|
1790
|
+
static OVERHEAD_PER_MESSAGE = 5;
|
|
1791
|
+
static OVERHEAD_PER_TOOL_CALL = 10;
|
|
1792
|
+
static encoderCache = /* @__PURE__ */ new Map();
|
|
1793
|
+
static DEFAULT_ENCODING = "cl100k_base";
|
|
1794
|
+
static SUPPORTED_ENCODINGS = [
|
|
1795
|
+
"gpt2",
|
|
1796
|
+
"r50k_base",
|
|
1797
|
+
"p50k_base",
|
|
1798
|
+
"p50k_edit",
|
|
1799
|
+
"cl100k_base",
|
|
1800
|
+
"o200k_base"
|
|
1801
|
+
];
|
|
1802
|
+
static resolveEncodingFromModelIdentifier(modelIdentifier) {
|
|
1803
|
+
const normalized = (modelIdentifier || "").trim().toLowerCase();
|
|
1804
|
+
if (this.isSupportedEncodingName(normalized)) {
|
|
1805
|
+
return normalized;
|
|
1806
|
+
}
|
|
1807
|
+
if (normalized.includes("deepseek")) {
|
|
1808
|
+
return "cl100k_base";
|
|
1809
|
+
}
|
|
1810
|
+
if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
|
|
1811
|
+
return "o200k_base";
|
|
1812
|
+
}
|
|
1813
|
+
if (normalized.includes("gemini") || normalized.includes("claude")) {
|
|
1814
|
+
return "cl100k_base";
|
|
1815
|
+
}
|
|
1816
|
+
return this.DEFAULT_ENCODING;
|
|
1817
|
+
}
|
|
1818
|
+
static isSupportedEncodingName(value) {
|
|
1819
|
+
return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
|
|
1820
|
+
}
|
|
1821
|
+
static getEncoder(modelIdentifierOrEncoding) {
|
|
1822
|
+
const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
|
|
1823
|
+
const cached = this.encoderCache.get(encodingName);
|
|
1824
|
+
if (cached) {
|
|
1825
|
+
return cached;
|
|
1826
|
+
}
|
|
1827
|
+
const encoder = get_encoding(encodingName);
|
|
1828
|
+
this.encoderCache.set(encodingName, encoder);
|
|
1829
|
+
return encoder;
|
|
1830
|
+
}
|
|
1831
|
+
static estimateTokensRough(text, _modelIdentifier) {
|
|
1832
|
+
if (!text) return 0;
|
|
1833
|
+
const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
|
|
1834
|
+
const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
|
|
1835
|
+
const byteLength = new TextEncoder().encode(text).length;
|
|
1836
|
+
return Math.ceil(byteLength / ratio);
|
|
1837
|
+
}
|
|
1838
|
+
static estimateTokens(text, options = {}) {
|
|
1839
|
+
if (!text) return 0;
|
|
1840
|
+
if (options.encoding) {
|
|
1841
|
+
try {
|
|
1842
|
+
return this.estimateTokensPrecise(text, options.encoding);
|
|
1843
|
+
} catch {
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
|
|
1847
|
+
return Math.ceil(text.length / avgCharsPerToken);
|
|
1848
|
+
}
|
|
1849
|
+
static estimateTokensPrecise(text, modelIdentifier) {
|
|
1850
|
+
if (!text) return 0;
|
|
1851
|
+
const encoder = this.getEncoder(modelIdentifier);
|
|
1852
|
+
return encoder.encode(text).length;
|
|
1853
|
+
}
|
|
1854
|
+
static estimateMessageTokens(message, options = {}) {
|
|
1855
|
+
let totalTokens = this.OVERHEAD_PER_MESSAGE;
|
|
1856
|
+
if (message.content) {
|
|
1857
|
+
totalTokens += this.estimateTokens(String(message.content), options);
|
|
1858
|
+
}
|
|
1859
|
+
const toolCalls = this.extractToolCallsForTokenEstimate(message);
|
|
1860
|
+
const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
|
|
1861
|
+
for (const toolCall of toolCalls) {
|
|
1862
|
+
totalTokens += toolCallOverhead;
|
|
1863
|
+
const fn = toolCall["function"];
|
|
1864
|
+
if (fn && typeof fn === "object" && !Array.isArray(fn)) {
|
|
1865
|
+
const fnRecord = fn;
|
|
1866
|
+
totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
|
|
1867
|
+
totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
const toolCallId = this.extractToolCallIdForTokenEstimate(message);
|
|
1871
|
+
if (toolCallId) {
|
|
1872
|
+
totalTokens += this.estimateTokens(toolCallId, options);
|
|
1873
|
+
}
|
|
1874
|
+
return totalTokens;
|
|
1875
|
+
}
|
|
1876
|
+
static estimateMessageTokensPrecise(message, modelIdentifier) {
|
|
1877
|
+
return this.estimateMessageTokens(message, {
|
|
1878
|
+
encoding: modelIdentifier,
|
|
1879
|
+
toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
static estimateMessagesTokensPrecise(messages, modelIdentifier) {
|
|
1883
|
+
return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
|
|
1884
|
+
}
|
|
1885
|
+
static extractToolCallsForTokenEstimate(message) {
|
|
1886
|
+
const direct = "tool_calls" in message ? message.tool_calls : void 0;
|
|
1887
|
+
if (Array.isArray(direct)) return direct;
|
|
1888
|
+
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1889
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
|
|
1890
|
+
const metadataRecord = metadata;
|
|
1891
|
+
const metadataToolCalls = metadataRecord["tool_calls"];
|
|
1892
|
+
return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
|
|
1893
|
+
}
|
|
1894
|
+
static extractToolCallIdForTokenEstimate(message) {
|
|
1895
|
+
if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
|
|
1896
|
+
return message.tool_call_id;
|
|
1897
|
+
}
|
|
1898
|
+
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1899
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
|
|
1900
|
+
const metadataRecord = metadata;
|
|
1901
|
+
const toolCallId = metadataRecord["tool_call_id"];
|
|
1902
|
+
return typeof toolCallId === "string" ? toolCallId : void 0;
|
|
1903
|
+
}
|
|
1904
|
+
static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
|
|
1905
|
+
if (!text || maxTokens <= 0) return "";
|
|
1906
|
+
const encoder = this.getEncoder(modelIdentifier);
|
|
1907
|
+
const tokens = encoder.encode(text);
|
|
1908
|
+
if (tokens.length <= maxTokens) {
|
|
1909
|
+
return text;
|
|
1910
|
+
}
|
|
1911
|
+
let truncatedTokens;
|
|
1912
|
+
const ellipsis = "...";
|
|
1913
|
+
switch (strategy) {
|
|
1914
|
+
case "start":
|
|
1915
|
+
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1916
|
+
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1917
|
+
case "end":
|
|
1918
|
+
truncatedTokens = tokens.slice(tokens.length - maxTokens);
|
|
1919
|
+
return ellipsis + encoder.decode(truncatedTokens);
|
|
1920
|
+
case "middle": {
|
|
1921
|
+
const half = Math.floor(maxTokens / 2);
|
|
1922
|
+
const head = tokens.slice(0, half);
|
|
1923
|
+
const tail = tokens.slice(tokens.length - (maxTokens - half));
|
|
1924
|
+
return encoder.decode(head) + ellipsis + encoder.decode(tail);
|
|
1925
|
+
}
|
|
1926
|
+
default:
|
|
1927
|
+
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1928
|
+
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
static cleanup() {
|
|
1932
|
+
for (const encoder of this.encoderCache.values()) {
|
|
1933
|
+
encoder.free();
|
|
1934
|
+
}
|
|
1935
|
+
this.encoderCache.clear();
|
|
1936
|
+
}
|
|
1937
|
+
};
|
|
1938
|
+
function normalizePositiveNumber(value, fallback) {
|
|
1939
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
1940
|
+
}
|
|
1941
|
+
function normalizeNonNegativeInteger(value, fallback) {
|
|
1942
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
1943
|
+
return fallback;
|
|
1944
|
+
}
|
|
1945
|
+
return Math.max(0, Math.floor(value));
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
// src/shared/defaultTokenizerPort.ts
|
|
1949
|
+
var DefaultTokenizerPort = class {
|
|
1950
|
+
constructor(config = {}) {
|
|
1951
|
+
this.config = config;
|
|
1952
|
+
}
|
|
1953
|
+
config;
|
|
1954
|
+
estimateText(text, _modelId) {
|
|
1955
|
+
return TokenCalculator.estimateTokens(text, {
|
|
1956
|
+
encoding: this.config.encoding,
|
|
1957
|
+
avgCharsPerToken: this.config.avgCharsPerToken
|
|
1958
|
+
});
|
|
1959
|
+
}
|
|
1960
|
+
estimateMessage(message, _modelId) {
|
|
1961
|
+
return TokenCalculator.estimateMessageTokens(message, {
|
|
1962
|
+
encoding: this.config.encoding,
|
|
1963
|
+
avgCharsPerToken: this.config.avgCharsPerToken,
|
|
1964
|
+
toolCallOverhead: this.config.toolCallOverhead
|
|
1965
|
+
});
|
|
1966
|
+
}
|
|
1967
|
+
};
|
|
1968
|
+
function createDefaultTokenizerPort(config = {}) {
|
|
1969
|
+
return new DefaultTokenizerPort(config);
|
|
1970
|
+
}
|
|
1530
1971
|
|
|
1531
1972
|
// src/shared/ids.ts
|
|
1532
1973
|
function isoRandomUUID() {
|
|
@@ -1628,15 +2069,15 @@ function splitConcatenatedJsonObjects(input) {
|
|
|
1628
2069
|
}
|
|
1629
2070
|
|
|
1630
2071
|
// src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
|
|
1631
|
-
function
|
|
2072
|
+
function readNonEmptyString2(value) {
|
|
1632
2073
|
if (typeof value !== "string") return void 0;
|
|
1633
2074
|
const trimmed = value.trim();
|
|
1634
2075
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
1635
2076
|
}
|
|
1636
2077
|
function resolveConversationIdForRuntimeEvents(toolContext) {
|
|
1637
|
-
const fromCamel =
|
|
2078
|
+
const fromCamel = readNonEmptyString2(toolContext?.conversationId);
|
|
1638
2079
|
if (fromCamel) return fromCamel;
|
|
1639
|
-
const fromSnake = toolContext ?
|
|
2080
|
+
const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
|
|
1640
2081
|
if (fromSnake) return fromSnake;
|
|
1641
2082
|
return generateMessageId();
|
|
1642
2083
|
}
|
|
@@ -1707,6 +2148,13 @@ function resolveUsage(response) {
|
|
|
1707
2148
|
}
|
|
1708
2149
|
return response.usage;
|
|
1709
2150
|
}
|
|
2151
|
+
function resolveCanonicalUsage(response) {
|
|
2152
|
+
if (!response || typeof response === "string") {
|
|
2153
|
+
return void 0;
|
|
2154
|
+
}
|
|
2155
|
+
const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
|
|
2156
|
+
return parsed.success ? parsed.data : void 0;
|
|
2157
|
+
}
|
|
1710
2158
|
function resolveToolCalls(response) {
|
|
1711
2159
|
if (!response || typeof response === "string") {
|
|
1712
2160
|
return void 0;
|
|
@@ -1738,206 +2186,79 @@ function recordRunTranscript(params) {
|
|
|
1738
2186
|
|
|
1739
2187
|
// src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
|
|
1740
2188
|
var contextAuditMiddleware = async (ctx, stage, next) => {
|
|
1741
|
-
if (stage.id === "build_context") {
|
|
1742
|
-
recordBeforeContextManager({
|
|
1743
|
-
mode: ctx.request.mode === "chat" ? "chat" : "agent",
|
|
1744
|
-
payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
|
|
1745
|
-
});
|
|
1746
|
-
}
|
|
1747
|
-
await next();
|
|
1748
|
-
if (stage.id !== "apply_system_reminder") {
|
|
1749
|
-
return;
|
|
1750
|
-
}
|
|
1751
|
-
resolveToolNamesForAudit(ctx);
|
|
1752
|
-
recordAfterContextManager({
|
|
1753
|
-
mode: ctx.mode,
|
|
1754
|
-
llmMessages: ctx.llmMessages,
|
|
1755
|
-
contextTrace: ctx.contextTrace
|
|
1756
|
-
});
|
|
1757
|
-
if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
|
|
1758
|
-
recordAfterContextManagerOnSystemReminderHit({
|
|
1759
|
-
mode: ctx.mode,
|
|
1760
|
-
llmMessages: ctx.llmMessages,
|
|
1761
|
-
systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
|
|
1762
|
-
contextTrace: ctx.contextTrace
|
|
1763
|
-
});
|
|
1764
|
-
}
|
|
1765
|
-
};
|
|
1766
|
-
var TokenCalculator = class {
|
|
1767
|
-
static BYTES_PER_TOKEN_LATIN = 4;
|
|
1768
|
-
static BYTES_PER_TOKEN_CJK = 3;
|
|
1769
|
-
static OVERHEAD_PER_MESSAGE = 5;
|
|
1770
|
-
static OVERHEAD_PER_TOOL_CALL = 10;
|
|
1771
|
-
static encoderCache = /* @__PURE__ */ new Map();
|
|
1772
|
-
static DEFAULT_ENCODING = "cl100k_base";
|
|
1773
|
-
static SUPPORTED_ENCODINGS = [
|
|
1774
|
-
"gpt2",
|
|
1775
|
-
"r50k_base",
|
|
1776
|
-
"p50k_base",
|
|
1777
|
-
"p50k_edit",
|
|
1778
|
-
"cl100k_base",
|
|
1779
|
-
"o200k_base"
|
|
1780
|
-
];
|
|
1781
|
-
static resolveEncodingFromModelIdentifier(modelIdentifier) {
|
|
1782
|
-
const normalized = (modelIdentifier || "").trim().toLowerCase();
|
|
1783
|
-
if (this.isSupportedEncodingName(normalized)) {
|
|
1784
|
-
return normalized;
|
|
1785
|
-
}
|
|
1786
|
-
if (normalized.includes("deepseek")) {
|
|
1787
|
-
return "cl100k_base";
|
|
1788
|
-
}
|
|
1789
|
-
if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
|
|
1790
|
-
return "o200k_base";
|
|
1791
|
-
}
|
|
1792
|
-
if (normalized.includes("gemini") || normalized.includes("claude")) {
|
|
1793
|
-
return "cl100k_base";
|
|
1794
|
-
}
|
|
1795
|
-
return this.DEFAULT_ENCODING;
|
|
1796
|
-
}
|
|
1797
|
-
static isSupportedEncodingName(value) {
|
|
1798
|
-
return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
|
|
1799
|
-
}
|
|
1800
|
-
static getEncoder(modelIdentifierOrEncoding) {
|
|
1801
|
-
const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
|
|
1802
|
-
const cached = this.encoderCache.get(encodingName);
|
|
1803
|
-
if (cached) {
|
|
1804
|
-
return cached;
|
|
1805
|
-
}
|
|
1806
|
-
const encoder = get_encoding(encodingName);
|
|
1807
|
-
this.encoderCache.set(encodingName, encoder);
|
|
1808
|
-
return encoder;
|
|
1809
|
-
}
|
|
1810
|
-
static estimateTokensRough(text, _modelIdentifier) {
|
|
1811
|
-
if (!text) return 0;
|
|
1812
|
-
const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
|
|
1813
|
-
const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
|
|
1814
|
-
const byteLength = new TextEncoder().encode(text).length;
|
|
1815
|
-
return Math.ceil(byteLength / ratio);
|
|
1816
|
-
}
|
|
1817
|
-
static estimateTokens(text, options = {}) {
|
|
1818
|
-
if (!text) return 0;
|
|
1819
|
-
if (options.encoding) {
|
|
1820
|
-
try {
|
|
1821
|
-
return this.estimateTokensPrecise(text, options.encoding);
|
|
1822
|
-
} catch {
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
|
|
1826
|
-
return Math.ceil(text.length / avgCharsPerToken);
|
|
1827
|
-
}
|
|
1828
|
-
static estimateTokensPrecise(text, modelIdentifier) {
|
|
1829
|
-
if (!text) return 0;
|
|
1830
|
-
const encoder = this.getEncoder(modelIdentifier);
|
|
1831
|
-
return encoder.encode(text).length;
|
|
1832
|
-
}
|
|
1833
|
-
static estimateMessageTokens(message, options = {}) {
|
|
1834
|
-
let totalTokens = this.OVERHEAD_PER_MESSAGE;
|
|
1835
|
-
if (message.content) {
|
|
1836
|
-
totalTokens += this.estimateTokens(String(message.content), options);
|
|
1837
|
-
}
|
|
1838
|
-
const toolCalls = this.extractToolCallsForTokenEstimate(message);
|
|
1839
|
-
const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
|
|
1840
|
-
for (const toolCall of toolCalls) {
|
|
1841
|
-
totalTokens += toolCallOverhead;
|
|
1842
|
-
const fn = toolCall["function"];
|
|
1843
|
-
if (fn && typeof fn === "object" && !Array.isArray(fn)) {
|
|
1844
|
-
const fnRecord = fn;
|
|
1845
|
-
totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
|
|
1846
|
-
totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
|
|
1847
|
-
}
|
|
1848
|
-
}
|
|
1849
|
-
const toolCallId = this.extractToolCallIdForTokenEstimate(message);
|
|
1850
|
-
if (toolCallId) {
|
|
1851
|
-
totalTokens += this.estimateTokens(toolCallId, options);
|
|
1852
|
-
}
|
|
1853
|
-
return totalTokens;
|
|
1854
|
-
}
|
|
1855
|
-
static estimateMessageTokensPrecise(message, modelIdentifier) {
|
|
1856
|
-
return this.estimateMessageTokens(message, {
|
|
1857
|
-
encoding: modelIdentifier,
|
|
1858
|
-
toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
|
|
2189
|
+
if (stage.id === "build_context") {
|
|
2190
|
+
recordBeforeContextManager({
|
|
2191
|
+
mode: ctx.request.mode === "chat" ? "chat" : "agent",
|
|
2192
|
+
payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
|
|
1859
2193
|
});
|
|
1860
2194
|
}
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
static extractToolCallsForTokenEstimate(message) {
|
|
1865
|
-
const direct = "tool_calls" in message ? message.tool_calls : void 0;
|
|
1866
|
-
if (Array.isArray(direct)) return direct;
|
|
1867
|
-
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1868
|
-
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
|
|
1869
|
-
const metadataRecord = metadata;
|
|
1870
|
-
const metadataToolCalls = metadataRecord["tool_calls"];
|
|
1871
|
-
return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
|
|
1872
|
-
}
|
|
1873
|
-
static extractToolCallIdForTokenEstimate(message) {
|
|
1874
|
-
if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
|
|
1875
|
-
return message.tool_call_id;
|
|
1876
|
-
}
|
|
1877
|
-
const metadata = "metadata" in message ? message.metadata : void 0;
|
|
1878
|
-
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
|
|
1879
|
-
const metadataRecord = metadata;
|
|
1880
|
-
const toolCallId = metadataRecord["tool_call_id"];
|
|
1881
|
-
return typeof toolCallId === "string" ? toolCallId : void 0;
|
|
1882
|
-
}
|
|
1883
|
-
static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
|
|
1884
|
-
if (!text || maxTokens <= 0) return "";
|
|
1885
|
-
const encoder = this.getEncoder(modelIdentifier);
|
|
1886
|
-
const tokens = encoder.encode(text);
|
|
1887
|
-
if (tokens.length <= maxTokens) {
|
|
1888
|
-
return text;
|
|
1889
|
-
}
|
|
1890
|
-
let truncatedTokens;
|
|
1891
|
-
const ellipsis = "...";
|
|
1892
|
-
switch (strategy) {
|
|
1893
|
-
case "start":
|
|
1894
|
-
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1895
|
-
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1896
|
-
case "end":
|
|
1897
|
-
truncatedTokens = tokens.slice(tokens.length - maxTokens);
|
|
1898
|
-
return ellipsis + encoder.decode(truncatedTokens);
|
|
1899
|
-
case "middle": {
|
|
1900
|
-
const half = Math.floor(maxTokens / 2);
|
|
1901
|
-
const head = tokens.slice(0, half);
|
|
1902
|
-
const tail = tokens.slice(tokens.length - (maxTokens - half));
|
|
1903
|
-
return encoder.decode(head) + ellipsis + encoder.decode(tail);
|
|
1904
|
-
}
|
|
1905
|
-
default:
|
|
1906
|
-
truncatedTokens = tokens.slice(0, maxTokens);
|
|
1907
|
-
return encoder.decode(truncatedTokens) + ellipsis;
|
|
1908
|
-
}
|
|
2195
|
+
await next();
|
|
2196
|
+
if (stage.id !== "apply_system_reminder") {
|
|
2197
|
+
return;
|
|
1909
2198
|
}
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
2199
|
+
resolveToolNamesForAudit(ctx);
|
|
2200
|
+
recordAfterContextManager({
|
|
2201
|
+
mode: ctx.mode,
|
|
2202
|
+
llmMessages: ctx.llmMessages,
|
|
2203
|
+
contextTrace: ctx.contextTrace
|
|
2204
|
+
});
|
|
2205
|
+
if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
|
|
2206
|
+
recordAfterContextManagerOnSystemReminderHit({
|
|
2207
|
+
mode: ctx.mode,
|
|
2208
|
+
llmMessages: ctx.llmMessages,
|
|
2209
|
+
systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
|
|
2210
|
+
contextTrace: ctx.contextTrace
|
|
2211
|
+
});
|
|
1915
2212
|
}
|
|
1916
2213
|
};
|
|
1917
|
-
|
|
1918
|
-
|
|
2214
|
+
var als = new AsyncLocalStorage();
|
|
2215
|
+
function readTokenCount(record, key) {
|
|
2216
|
+
const value = record[key];
|
|
2217
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
|
|
1919
2218
|
}
|
|
1920
|
-
function
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
return Math.max(0, Math.floor(value));
|
|
2219
|
+
function readRecord(record, key) {
|
|
2220
|
+
const value = record[key];
|
|
2221
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
2222
|
+
return Object.fromEntries(Object.entries(value));
|
|
1925
2223
|
}
|
|
1926
|
-
|
|
1927
|
-
|
|
2224
|
+
function normalizedUsageFromCanonical(canonicalUsage) {
|
|
2225
|
+
return {
|
|
2226
|
+
promptTokens: canonicalUsage.inputTokens,
|
|
2227
|
+
completionTokens: canonicalUsage.outputTokens,
|
|
2228
|
+
totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
|
|
2229
|
+
canonicalUsage
|
|
2230
|
+
};
|
|
2231
|
+
}
|
|
2232
|
+
function normalizeCanonicalLlmUsage(usage) {
|
|
1928
2233
|
if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
|
|
1929
2234
|
const rec = usage;
|
|
1930
|
-
const
|
|
1931
|
-
const
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
const
|
|
1936
|
-
const
|
|
1937
|
-
const
|
|
1938
|
-
const
|
|
1939
|
-
|
|
1940
|
-
|
|
2235
|
+
const inputTokens = readTokenCount(rec, "prompt_tokens");
|
|
2236
|
+
const outputTokens = readTokenCount(rec, "completion_tokens");
|
|
2237
|
+
if (inputTokens === void 0 || outputTokens === void 0) {
|
|
2238
|
+
return void 0;
|
|
2239
|
+
}
|
|
2240
|
+
const promptDetails = readRecord(rec, "prompt_tokens_details");
|
|
2241
|
+
const completionDetails = readRecord(rec, "completion_tokens_details");
|
|
2242
|
+
const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
|
|
2243
|
+
const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
|
|
2244
|
+
const totalTokens = readTokenCount(rec, "total_tokens");
|
|
2245
|
+
if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
|
|
2246
|
+
return void 0;
|
|
2247
|
+
}
|
|
2248
|
+
return {
|
|
2249
|
+
inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
|
|
2250
|
+
outputTokens,
|
|
2251
|
+
...reasoningTokens !== void 0 ? { reasoningTokens } : {},
|
|
2252
|
+
...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
|
|
2253
|
+
...totalTokens !== void 0 ? { totalTokens } : {},
|
|
2254
|
+
source: "provider-response-usage",
|
|
2255
|
+
confidence: "actual",
|
|
2256
|
+
rawUsage: usage
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2259
|
+
function normalizeLlmUsage(usage) {
|
|
2260
|
+
const canonicalUsage = normalizeCanonicalLlmUsage(usage);
|
|
2261
|
+
return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
|
|
1941
2262
|
}
|
|
1942
2263
|
function recordLlmCallTelemetry(entry) {
|
|
1943
2264
|
const store = als.getStore();
|
|
@@ -1951,17 +2272,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1951
2272
|
if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
|
|
1952
2273
|
return;
|
|
1953
2274
|
}
|
|
1954
|
-
const
|
|
2275
|
+
const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
|
|
2276
|
+
const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
|
|
1955
2277
|
const respText = extractResponseText(ctx.llmResp);
|
|
1956
2278
|
const normalizedUsage = normalizedUsageFromProvider ?? (() => {
|
|
1957
2279
|
try {
|
|
1958
|
-
const promptTokens =
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
2280
|
+
const promptTokens = ctx.llmMessages.reduce(
|
|
2281
|
+
(total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
|
|
2282
|
+
0
|
|
2283
|
+
);
|
|
2284
|
+
const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
|
|
2285
|
+
return normalizedUsageFromCanonical({
|
|
2286
|
+
inputTokens: promptTokens,
|
|
2287
|
+
outputTokens: completionTokens,
|
|
2288
|
+
totalTokens: promptTokens + completionTokens,
|
|
2289
|
+
source: "local-estimate",
|
|
2290
|
+
confidence: "estimate"
|
|
2291
|
+
});
|
|
1965
2292
|
} catch {
|
|
1966
2293
|
return void 0;
|
|
1967
2294
|
}
|
|
@@ -1971,7 +2298,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1971
2298
|
stream: ctx.input.stream === true,
|
|
1972
2299
|
startedAt: ctx.llmCallStartedAt,
|
|
1973
2300
|
durationMs: ctx.llmCallDurationMs,
|
|
1974
|
-
usage: normalizedUsage
|
|
2301
|
+
usage: normalizedUsage,
|
|
2302
|
+
...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
|
|
1975
2303
|
});
|
|
1976
2304
|
ctx.telemetry.emit({
|
|
1977
2305
|
kind: "llm_call",
|
|
@@ -1979,6 +2307,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
|
|
|
1979
2307
|
stream: ctx.input.stream === true,
|
|
1980
2308
|
durationMs: ctx.llmCallDurationMs,
|
|
1981
2309
|
usage: normalizedUsage,
|
|
2310
|
+
...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
|
|
1982
2311
|
scope: {
|
|
1983
2312
|
conversationId: ctx.conversationId || void 0,
|
|
1984
2313
|
turnId: ctx.turnId,
|
|
@@ -1995,7 +2324,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
|
|
|
1995
2324
|
if (stage.id !== "execute_llm") {
|
|
1996
2325
|
return;
|
|
1997
2326
|
}
|
|
1998
|
-
const normalized =
|
|
2327
|
+
const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
|
|
1999
2328
|
if (!normalized) {
|
|
2000
2329
|
return;
|
|
2001
2330
|
}
|
|
@@ -2122,10 +2451,10 @@ var contextBudgetWarningTemplate = (ctx) => {
|
|
|
2122
2451
|
return [
|
|
2123
2452
|
`\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`,
|
|
2124
2453
|
"\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
|
|
2125
|
-
"1. \
|
|
2454
|
+
"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",
|
|
2126
2455
|
`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`,
|
|
2127
2456
|
' \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',
|
|
2128
|
-
"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\
|
|
2457
|
+
"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"
|
|
2129
2458
|
].join("\n");
|
|
2130
2459
|
};
|
|
2131
2460
|
var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
|
|
@@ -2433,6 +2762,219 @@ function createApplySystemReminderStage() {
|
|
|
2433
2762
|
};
|
|
2434
2763
|
}
|
|
2435
2764
|
|
|
2765
|
+
// src/runtime-kernel/token-accounting/index.ts
|
|
2766
|
+
var token_accounting_exports = {};
|
|
2767
|
+
__export(token_accounting_exports, {
|
|
2768
|
+
addLedgerAggregate: () => addLedgerAggregate,
|
|
2769
|
+
addUsageTotals: () => addUsageTotals,
|
|
2770
|
+
aggregateCanonicalUsage: () => aggregateCanonicalUsage,
|
|
2771
|
+
aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
|
|
2772
|
+
computeCost: () => computeCost,
|
|
2773
|
+
createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
|
|
2774
|
+
createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
|
|
2775
|
+
createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
|
|
2776
|
+
});
|
|
2777
|
+
|
|
2778
|
+
// src/runtime-kernel/token-accounting/functions.ts
|
|
2779
|
+
var EMPTY_LEDGER_AGGREGATE = {
|
|
2780
|
+
contextTokens: 0,
|
|
2781
|
+
entryCount: 0,
|
|
2782
|
+
llmCallCount: 0,
|
|
2783
|
+
contextComponentCount: 0
|
|
2784
|
+
};
|
|
2785
|
+
var TOKEN_PRICE_UNIT = 1e6;
|
|
2786
|
+
function sumReportedOptional(values) {
|
|
2787
|
+
const reported = values.filter((value) => value !== void 0);
|
|
2788
|
+
if (reported.length === 0) {
|
|
2789
|
+
return void 0;
|
|
2790
|
+
}
|
|
2791
|
+
return reported.reduce((total, value) => total + value, 0);
|
|
2792
|
+
}
|
|
2793
|
+
function sumTotalTokens(usages) {
|
|
2794
|
+
if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
|
|
2795
|
+
return void 0;
|
|
2796
|
+
}
|
|
2797
|
+
return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
|
|
2798
|
+
}
|
|
2799
|
+
function aggregateCanonicalUsage(usages) {
|
|
2800
|
+
if (usages.length === 0) {
|
|
2801
|
+
return void 0;
|
|
2802
|
+
}
|
|
2803
|
+
return {
|
|
2804
|
+
inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
|
|
2805
|
+
outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
|
|
2806
|
+
reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
|
|
2807
|
+
cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
|
|
2808
|
+
cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
|
|
2809
|
+
totalTokens: sumTotalTokens(usages),
|
|
2810
|
+
usageCount: usages.length
|
|
2811
|
+
};
|
|
2812
|
+
}
|
|
2813
|
+
function createLlmUsageLedgerEntry(input) {
|
|
2814
|
+
return {
|
|
2815
|
+
...input,
|
|
2816
|
+
kind: "llm-usage"
|
|
2817
|
+
};
|
|
2818
|
+
}
|
|
2819
|
+
function createContextComponentLedgerEntry(input) {
|
|
2820
|
+
return {
|
|
2821
|
+
...input,
|
|
2822
|
+
kind: "context-component",
|
|
2823
|
+
components: [...input.components],
|
|
2824
|
+
totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
|
|
2825
|
+
};
|
|
2826
|
+
}
|
|
2827
|
+
function addUsageTotals(left, right) {
|
|
2828
|
+
if (!left) {
|
|
2829
|
+
return right;
|
|
2830
|
+
}
|
|
2831
|
+
if (!right) {
|
|
2832
|
+
return left;
|
|
2833
|
+
}
|
|
2834
|
+
return {
|
|
2835
|
+
inputTokens: left.inputTokens + right.inputTokens,
|
|
2836
|
+
outputTokens: left.outputTokens + right.outputTokens,
|
|
2837
|
+
reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
|
|
2838
|
+
cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
|
|
2839
|
+
cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
|
|
2840
|
+
totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
|
|
2841
|
+
usageCount: left.usageCount + right.usageCount
|
|
2842
|
+
};
|
|
2843
|
+
}
|
|
2844
|
+
function addLedgerAggregate(left, right) {
|
|
2845
|
+
return {
|
|
2846
|
+
llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
|
|
2847
|
+
contextTokens: left.contextTokens + right.contextTokens,
|
|
2848
|
+
entryCount: left.entryCount + right.entryCount,
|
|
2849
|
+
llmCallCount: left.llmCallCount + right.llmCallCount,
|
|
2850
|
+
contextComponentCount: left.contextComponentCount + right.contextComponentCount
|
|
2851
|
+
};
|
|
2852
|
+
}
|
|
2853
|
+
function aggregateTokenLedgerEntries(entries) {
|
|
2854
|
+
const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
|
|
2855
|
+
return entries.reduce((aggregate, entry) => {
|
|
2856
|
+
if (entry.kind === "llm-usage") {
|
|
2857
|
+
return {
|
|
2858
|
+
...aggregate,
|
|
2859
|
+
entryCount: aggregate.entryCount + 1,
|
|
2860
|
+
llmCallCount: aggregate.llmCallCount + 1
|
|
2861
|
+
};
|
|
2862
|
+
}
|
|
2863
|
+
return {
|
|
2864
|
+
...aggregate,
|
|
2865
|
+
contextTokens: aggregate.contextTokens + entry.totalTokens,
|
|
2866
|
+
entryCount: aggregate.entryCount + 1,
|
|
2867
|
+
contextComponentCount: aggregate.contextComponentCount + entry.components.length
|
|
2868
|
+
};
|
|
2869
|
+
}, {
|
|
2870
|
+
...EMPTY_LEDGER_AGGREGATE,
|
|
2871
|
+
llmUsage: aggregateCanonicalUsage(llmUsages)
|
|
2872
|
+
});
|
|
2873
|
+
}
|
|
2874
|
+
function createRunTokenUsageAggregate(input) {
|
|
2875
|
+
const children = input.childAggregates?.reduce(
|
|
2876
|
+
(aggregate, child) => addLedgerAggregate(aggregate, child),
|
|
2877
|
+
EMPTY_LEDGER_AGGREGATE
|
|
2878
|
+
);
|
|
2879
|
+
return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
|
|
2880
|
+
}
|
|
2881
|
+
function componentCost(tokens, pricePerMillion) {
|
|
2882
|
+
return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
|
|
2883
|
+
}
|
|
2884
|
+
function needsPrice(tokens) {
|
|
2885
|
+
return tokens !== void 0 && tokens > 0;
|
|
2886
|
+
}
|
|
2887
|
+
function missingPriceComponents(usage, pricing) {
|
|
2888
|
+
const missing = [];
|
|
2889
|
+
if (!pricing) {
|
|
2890
|
+
if (needsPrice(usage.inputTokens)) {
|
|
2891
|
+
missing.push("input");
|
|
2892
|
+
}
|
|
2893
|
+
if (needsPrice(usage.outputTokens)) {
|
|
2894
|
+
missing.push("output");
|
|
2895
|
+
}
|
|
2896
|
+
if (needsPrice(usage.reasoningTokens)) {
|
|
2897
|
+
missing.push("reasoning");
|
|
2898
|
+
}
|
|
2899
|
+
if (needsPrice(usage.cacheReadTokens)) {
|
|
2900
|
+
missing.push("cacheRead");
|
|
2901
|
+
}
|
|
2902
|
+
if (needsPrice(usage.cacheWriteTokens)) {
|
|
2903
|
+
missing.push("cacheWrite");
|
|
2904
|
+
}
|
|
2905
|
+
return missing;
|
|
2906
|
+
}
|
|
2907
|
+
if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
|
|
2908
|
+
missing.push("input");
|
|
2909
|
+
}
|
|
2910
|
+
if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
|
|
2911
|
+
missing.push("output");
|
|
2912
|
+
}
|
|
2913
|
+
if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
|
|
2914
|
+
missing.push("reasoning");
|
|
2915
|
+
}
|
|
2916
|
+
if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
|
|
2917
|
+
missing.push("cacheRead");
|
|
2918
|
+
}
|
|
2919
|
+
if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
|
|
2920
|
+
missing.push("cacheWrite");
|
|
2921
|
+
}
|
|
2922
|
+
return missing;
|
|
2923
|
+
}
|
|
2924
|
+
function reportedComponentCost(tokens, pricePerMillion) {
|
|
2925
|
+
if (tokens === void 0) {
|
|
2926
|
+
return void 0;
|
|
2927
|
+
}
|
|
2928
|
+
if (tokens === 0) {
|
|
2929
|
+
return 0;
|
|
2930
|
+
}
|
|
2931
|
+
return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
|
|
2932
|
+
}
|
|
2933
|
+
function requiredComponentCost(tokens, pricePerMillion) {
|
|
2934
|
+
if (tokens === 0) {
|
|
2935
|
+
return 0;
|
|
2936
|
+
}
|
|
2937
|
+
return componentCost(tokens, pricePerMillion ?? 0);
|
|
2938
|
+
}
|
|
2939
|
+
function sumComputedCosts(costs) {
|
|
2940
|
+
let total = 0;
|
|
2941
|
+
for (const cost of costs) {
|
|
2942
|
+
total += cost ?? 0;
|
|
2943
|
+
}
|
|
2944
|
+
return total;
|
|
2945
|
+
}
|
|
2946
|
+
function computeCost(usage, pricing) {
|
|
2947
|
+
const missing = missingPriceComponents(usage, pricing);
|
|
2948
|
+
if (!pricing || missing.length > 0) {
|
|
2949
|
+
return {
|
|
2950
|
+
status: "unknown",
|
|
2951
|
+
...pricing ? { currency: pricing.currency } : {},
|
|
2952
|
+
...missing.length > 0 ? { missingPriceComponents: missing } : {}
|
|
2953
|
+
};
|
|
2954
|
+
}
|
|
2955
|
+
const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
|
|
2956
|
+
const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
|
|
2957
|
+
const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
|
|
2958
|
+
const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
|
|
2959
|
+
const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
|
|
2960
|
+
return {
|
|
2961
|
+
status: "computed",
|
|
2962
|
+
currency: pricing.currency,
|
|
2963
|
+
inputCost,
|
|
2964
|
+
outputCost,
|
|
2965
|
+
reasoningCost,
|
|
2966
|
+
cacheReadCost,
|
|
2967
|
+
cacheWriteCost,
|
|
2968
|
+
totalCost: sumComputedCosts([
|
|
2969
|
+
inputCost,
|
|
2970
|
+
outputCost,
|
|
2971
|
+
reasoningCost,
|
|
2972
|
+
cacheReadCost,
|
|
2973
|
+
cacheWriteCost
|
|
2974
|
+
])
|
|
2975
|
+
};
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2436
2978
|
// src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
|
|
2437
2979
|
var logger4 = new Logger("GraphAgentExecutor");
|
|
2438
2980
|
function createBuildContextStage(dependencies) {
|
|
@@ -2449,6 +2991,23 @@ function createBuildContextStage(dependencies) {
|
|
|
2449
2991
|
ctx.mode = contextBuildResult.mode;
|
|
2450
2992
|
ctx.llmMessages = contextBuildResult.llmMessages;
|
|
2451
2993
|
ctx.contextTrace = contextBuildResult.contextTrace;
|
|
2994
|
+
if (contextBuildResult.tokenEstimate) {
|
|
2995
|
+
const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
|
|
2996
|
+
ctx.telemetry.emit({
|
|
2997
|
+
kind: "context_build",
|
|
2998
|
+
modelId: ctx.modelId,
|
|
2999
|
+
mode: contextBuildResult.mode,
|
|
3000
|
+
tokenEstimate: contextBuildResult.tokenEstimate,
|
|
3001
|
+
...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
|
|
3002
|
+
...tokenLedgerEntry ? { tokenLedgerEntry } : {},
|
|
3003
|
+
scope: {
|
|
3004
|
+
conversationId: ctx.conversationId,
|
|
3005
|
+
runId: ctx.input.toolContext?.runId,
|
|
3006
|
+
parentRunId: ctx.input.toolContext?.parentRunId,
|
|
3007
|
+
turnId: ctx.turnId
|
|
3008
|
+
}
|
|
3009
|
+
});
|
|
3010
|
+
}
|
|
2452
3011
|
for (const event of contextBuildResult.summaryEvents) {
|
|
2453
3012
|
if (!isHistorySummaryEvent(event)) {
|
|
2454
3013
|
continue;
|
|
@@ -2463,6 +3022,24 @@ function createBuildContextStage(dependencies) {
|
|
|
2463
3022
|
}
|
|
2464
3023
|
};
|
|
2465
3024
|
}
|
|
3025
|
+
function createContextLedgerEntry(ctx, contextBuildResult) {
|
|
3026
|
+
const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
|
|
3027
|
+
if (keptComponents.length === 0) {
|
|
3028
|
+
return void 0;
|
|
3029
|
+
}
|
|
3030
|
+
const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
|
|
3031
|
+
const createdAt = Date.now();
|
|
3032
|
+
return createContextComponentLedgerEntry({
|
|
3033
|
+
id: `context_${runId}_${ctx.turnId}_${createdAt}`,
|
|
3034
|
+
conversationId: ctx.conversationId,
|
|
3035
|
+
runId,
|
|
3036
|
+
parentRunId: ctx.input.toolContext?.parentRunId,
|
|
3037
|
+
turnId: ctx.turnId,
|
|
3038
|
+
route: contextBuildResult.tokenEstimate?.route,
|
|
3039
|
+
createdAt,
|
|
3040
|
+
components: keptComponents
|
|
3041
|
+
});
|
|
3042
|
+
}
|
|
2466
3043
|
|
|
2467
3044
|
// src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
|
|
2468
3045
|
function createBuildDecisionStage(dependencies) {
|
|
@@ -2596,7 +3173,7 @@ function createExecuteLlmStage(dependencies) {
|
|
|
2596
3173
|
streamEventHandler,
|
|
2597
3174
|
ctx.signal,
|
|
2598
3175
|
(fallbackModelId) => {
|
|
2599
|
-
ctx.cloudQuotaFallbackAppliedModelId =
|
|
3176
|
+
ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
|
|
2600
3177
|
},
|
|
2601
3178
|
(info) => {
|
|
2602
3179
|
ctx.modelFallbackAudit = info;
|
|
@@ -2640,7 +3217,7 @@ function createPrepareCallStage(dependencies) {
|
|
|
2640
3217
|
return {
|
|
2641
3218
|
id: "prepare_call",
|
|
2642
3219
|
async run(ctx) {
|
|
2643
|
-
const lockedRunModelId =
|
|
3220
|
+
const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
|
|
2644
3221
|
const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
|
|
2645
3222
|
ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
|
|
2646
3223
|
await emitAuditEnvelope(ctx.audit, {
|
|
@@ -2706,19 +3283,21 @@ var GraphAgentExecutor = class {
|
|
|
2706
3283
|
modelCatalog;
|
|
2707
3284
|
telemetryPort;
|
|
2708
3285
|
auditPort;
|
|
3286
|
+
tokenizer;
|
|
2709
3287
|
stages;
|
|
2710
3288
|
middlewares;
|
|
2711
3289
|
constructor(dependencies) {
|
|
2712
3290
|
this.llmCaller = dependencies.llmCaller;
|
|
2713
3291
|
this.toolRuntime = dependencies.toolRuntime;
|
|
2714
3292
|
this.contextBuilder = dependencies.contextBuilder;
|
|
2715
|
-
this.cloudQuotaFallbackModelId =
|
|
3293
|
+
this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
|
|
2716
3294
|
this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
|
|
2717
3295
|
this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
|
|
2718
3296
|
modelCatalog: this.modelCatalog
|
|
2719
3297
|
});
|
|
2720
3298
|
this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
|
|
2721
3299
|
this.auditPort = dependencies.auditPort ?? noopAudit;
|
|
3300
|
+
this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
|
|
2722
3301
|
this.stages = [
|
|
2723
3302
|
createPrepareCallStage({
|
|
2724
3303
|
modelResolver: this.modelResolver,
|
|
@@ -2760,9 +3339,10 @@ var GraphAgentExecutor = class {
|
|
|
2760
3339
|
llmMessages: [],
|
|
2761
3340
|
mode: input.request.mode === "chat" ? "chat" : "agent",
|
|
2762
3341
|
conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
|
|
2763
|
-
turnId:
|
|
3342
|
+
turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
|
|
2764
3343
|
telemetry: this.telemetryPort,
|
|
2765
|
-
audit: this.auditPort
|
|
3344
|
+
audit: this.auditPort,
|
|
3345
|
+
tokenizer: this.tokenizer
|
|
2766
3346
|
};
|
|
2767
3347
|
logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
|
|
2768
3348
|
stream: input.stream === true,
|
|
@@ -2810,18 +3390,18 @@ function isSummarizationCallbacks(value) {
|
|
|
2810
3390
|
function isGraphSseSink(value) {
|
|
2811
3391
|
return typeof value === "function";
|
|
2812
3392
|
}
|
|
2813
|
-
function
|
|
3393
|
+
function readNonEmptyString3(value) {
|
|
2814
3394
|
if (typeof value !== "string") return void 0;
|
|
2815
3395
|
const trimmed = value.trim();
|
|
2816
3396
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
2817
3397
|
}
|
|
2818
3398
|
function readGraphAgentLocal(local) {
|
|
2819
3399
|
const source = local ?? {};
|
|
2820
|
-
const answerId =
|
|
3400
|
+
const answerId = readNonEmptyString3(source.answerId);
|
|
2821
3401
|
const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
|
|
2822
3402
|
return {
|
|
2823
|
-
conversationId:
|
|
2824
|
-
turnId:
|
|
3403
|
+
conversationId: readNonEmptyString3(source.conversationId) ?? "",
|
|
3404
|
+
turnId: readNonEmptyString3(source.turnId),
|
|
2825
3405
|
request: isAgentInvocationRequest(source.request) ? source.request : void 0,
|
|
2826
3406
|
toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
|
|
2827
3407
|
history: isRuntimeEventArray(source.history) ? source.history : [],
|
|
@@ -3586,7 +4166,7 @@ var LlmNode = class {
|
|
|
3586
4166
|
function isRecord8(value) {
|
|
3587
4167
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3588
4168
|
}
|
|
3589
|
-
function
|
|
4169
|
+
function readNonEmptyString4(value) {
|
|
3590
4170
|
if (typeof value !== "string") {
|
|
3591
4171
|
return void 0;
|
|
3592
4172
|
}
|
|
@@ -3608,7 +4188,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
|
|
|
3608
4188
|
return void 0;
|
|
3609
4189
|
}
|
|
3610
4190
|
if (toolName === "write_report") {
|
|
3611
|
-
const report =
|
|
4191
|
+
const report = readNonEmptyString4(data.report);
|
|
3612
4192
|
if (!report) {
|
|
3613
4193
|
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");
|
|
3614
4194
|
}
|
|
@@ -3618,7 +4198,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
|
|
|
3618
4198
|
if (data.success !== true) {
|
|
3619
4199
|
return void 0;
|
|
3620
4200
|
}
|
|
3621
|
-
const finalAnswer =
|
|
4201
|
+
const finalAnswer = readNonEmptyString4(data.final_answer);
|
|
3622
4202
|
if (!finalAnswer) {
|
|
3623
4203
|
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");
|
|
3624
4204
|
}
|
|
@@ -3727,11 +4307,11 @@ function buildToolOutputUiMeta(params) {
|
|
|
3727
4307
|
}
|
|
3728
4308
|
async function applyObservationGovernance(params) {
|
|
3729
4309
|
if (!params.structuredObservation || !isRecord9(params.parsed)) {
|
|
3730
|
-
return;
|
|
4310
|
+
return {};
|
|
3731
4311
|
}
|
|
3732
4312
|
const policy = resolveToolObservationGovernancePolicy(params.policy);
|
|
3733
4313
|
if (!policy.enabled) {
|
|
3734
|
-
return;
|
|
4314
|
+
return {};
|
|
3735
4315
|
}
|
|
3736
4316
|
const truncated = await params.observationPreview.truncateObservation({
|
|
3737
4317
|
context: params.toolContext,
|
|
@@ -3745,13 +4325,37 @@ async function applyObservationGovernance(params) {
|
|
|
3745
4325
|
})
|
|
3746
4326
|
});
|
|
3747
4327
|
if (!truncated.truncated) {
|
|
3748
|
-
return;
|
|
4328
|
+
return {};
|
|
3749
4329
|
}
|
|
3750
4330
|
params.parsed["observation"] = truncated.preview;
|
|
3751
4331
|
const data = params.parsed["data"];
|
|
3752
4332
|
if (isRecord9(data) && !("tool_output_store" in data)) {
|
|
3753
4333
|
data["tool_output_store"] = { blob_id: truncated.blob_id };
|
|
3754
4334
|
}
|
|
4335
|
+
return {
|
|
4336
|
+
observationTruncation: buildObservationTruncationMeta({
|
|
4337
|
+
originalText: params.structuredObservation,
|
|
4338
|
+
previewText: truncated.preview,
|
|
4339
|
+
originalChars: truncated.originalChars,
|
|
4340
|
+
previewChars: truncated.previewChars,
|
|
4341
|
+
originalLines: truncated.originalLines,
|
|
4342
|
+
previewLines: truncated.previewLines
|
|
4343
|
+
})
|
|
4344
|
+
};
|
|
4345
|
+
}
|
|
4346
|
+
function buildObservationTruncationMeta(input) {
|
|
4347
|
+
return {
|
|
4348
|
+
originalChars: input.originalChars ?? input.originalText.length,
|
|
4349
|
+
previewChars: input.previewChars ?? input.previewText.length,
|
|
4350
|
+
originalLines: input.originalLines ?? countLines(input.originalText),
|
|
4351
|
+
previewLines: input.previewLines ?? countLines(input.previewText)
|
|
4352
|
+
};
|
|
4353
|
+
}
|
|
4354
|
+
function countLines(value) {
|
|
4355
|
+
if (value.length === 0) {
|
|
4356
|
+
return 0;
|
|
4357
|
+
}
|
|
4358
|
+
return value.split(/\r\n|\r|\n/).length;
|
|
3755
4359
|
}
|
|
3756
4360
|
|
|
3757
4361
|
// src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
|
|
@@ -4163,6 +4767,31 @@ function ensureToolContextRuntimeCapability(params) {
|
|
|
4163
4767
|
function getToolContextRuntimeBinding(context) {
|
|
4164
4768
|
return readBinding(context);
|
|
4165
4769
|
}
|
|
4770
|
+
function copyToolContextRuntimeCapability(source, target) {
|
|
4771
|
+
const sourceBinding = readBinding(source);
|
|
4772
|
+
if (!sourceBinding) {
|
|
4773
|
+
return void 0;
|
|
4774
|
+
}
|
|
4775
|
+
const existingTargetBinding = readBinding(target);
|
|
4776
|
+
if (existingTargetBinding) {
|
|
4777
|
+
exposeCompatibilitySurface(target, existingTargetBinding);
|
|
4778
|
+
return existingTargetBinding;
|
|
4779
|
+
}
|
|
4780
|
+
const targetBinding = createRuntimeBinding({
|
|
4781
|
+
context: target,
|
|
4782
|
+
persistedHistory: () => sourceBinding.getPersistedHistoryEvents(),
|
|
4783
|
+
workingHistory: () => sourceBinding.getWorkingHistoryEvents(),
|
|
4784
|
+
executionMeta: sourceBinding.readExecutionMeta()
|
|
4785
|
+
});
|
|
4786
|
+
Object.defineProperty(target, TOOL_CONTEXT_RUNTIME_BINDING_KEY, {
|
|
4787
|
+
value: targetBinding,
|
|
4788
|
+
enumerable: false,
|
|
4789
|
+
configurable: true,
|
|
4790
|
+
writable: false
|
|
4791
|
+
});
|
|
4792
|
+
exposeCompatibilitySurface(target, targetBinding);
|
|
4793
|
+
return targetBinding;
|
|
4794
|
+
}
|
|
4166
4795
|
function readToolContextWorkingHistory(context) {
|
|
4167
4796
|
if (context.conversationView) {
|
|
4168
4797
|
return context.conversationView.getWorkingHistoryEvents();
|
|
@@ -4689,7 +5318,7 @@ var ToolNode = class {
|
|
|
4689
5318
|
parentRunId: context.toolContext.parentRunId
|
|
4690
5319
|
});
|
|
4691
5320
|
applyProtocolFuseState(context.local);
|
|
4692
|
-
await applyObservationGovernance({
|
|
5321
|
+
const observationGovernance = await applyObservationGovernance({
|
|
4693
5322
|
parsed: context.parsed,
|
|
4694
5323
|
toolName: context.toolName,
|
|
4695
5324
|
toolContext: context.toolContext,
|
|
@@ -4716,6 +5345,12 @@ var ToolNode = class {
|
|
|
4716
5345
|
runtimeToolOutput,
|
|
4717
5346
|
execIdempotency: context.exec.idempotency
|
|
4718
5347
|
});
|
|
5348
|
+
if (runtimeToolOutput && observationGovernance.observationTruncation) {
|
|
5349
|
+
runtimeToolOutput.metadata = {
|
|
5350
|
+
...runtimeToolOutput.metadata ?? {},
|
|
5351
|
+
observationTruncation: observationGovernance.observationTruncation
|
|
5352
|
+
};
|
|
5353
|
+
}
|
|
4719
5354
|
const remainingCalls = context.calls.slice(1);
|
|
4720
5355
|
context.state.local = buildSuccessLocalState({
|
|
4721
5356
|
local: context.local,
|
|
@@ -5014,12 +5649,12 @@ function asRecord(value) {
|
|
|
5014
5649
|
}
|
|
5015
5650
|
return value;
|
|
5016
5651
|
}
|
|
5017
|
-
function summarizeCheckpoint(
|
|
5652
|
+
function summarizeCheckpoint(checkpointKey, state, savedAt) {
|
|
5018
5653
|
const local = asRecord(state.local);
|
|
5019
5654
|
const executorLocal = asRecord(local?.executorLocal);
|
|
5020
5655
|
const pendingToolCalls = local?.pendingToolCalls;
|
|
5021
5656
|
return {
|
|
5022
|
-
|
|
5657
|
+
checkpointKey,
|
|
5023
5658
|
schemaVersion: state.schemaVersion ?? 1,
|
|
5024
5659
|
savedAt,
|
|
5025
5660
|
currentNode: state.nodeId,
|
|
@@ -5038,25 +5673,25 @@ var MemoryCheckpointer = class {
|
|
|
5038
5673
|
local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
|
|
5039
5674
|
};
|
|
5040
5675
|
}
|
|
5041
|
-
async load(
|
|
5042
|
-
const entry = this.store.get(
|
|
5676
|
+
async load(checkpointKey) {
|
|
5677
|
+
const entry = this.store.get(checkpointKey);
|
|
5043
5678
|
return entry ? this.cloneState(entry.state) : null;
|
|
5044
5679
|
}
|
|
5045
|
-
async save(
|
|
5046
|
-
this.store.set(
|
|
5680
|
+
async save(checkpointKey, state) {
|
|
5681
|
+
this.store.set(checkpointKey, {
|
|
5047
5682
|
state: this.cloneState(state),
|
|
5048
5683
|
savedAt: Date.now()
|
|
5049
5684
|
});
|
|
5050
5685
|
}
|
|
5051
|
-
async clear(
|
|
5052
|
-
this.store.delete(
|
|
5686
|
+
async clear(checkpointKey) {
|
|
5687
|
+
this.store.delete(checkpointKey);
|
|
5053
5688
|
}
|
|
5054
|
-
async peekMeta(
|
|
5055
|
-
const entry = this.store.get(
|
|
5056
|
-
return entry ? summarizeCheckpoint(
|
|
5689
|
+
async peekMeta(checkpointKey) {
|
|
5690
|
+
const entry = this.store.get(checkpointKey);
|
|
5691
|
+
return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
|
|
5057
5692
|
}
|
|
5058
5693
|
async list(filter = {}) {
|
|
5059
|
-
const summaries = Array.from(this.store.entries()).map(([
|
|
5694
|
+
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);
|
|
5060
5695
|
if (filter.limit === void 0) {
|
|
5061
5696
|
return summaries;
|
|
5062
5697
|
}
|
|
@@ -5128,6 +5763,7 @@ __export(tools_exports, {
|
|
|
5128
5763
|
CommonParameterTypes: () => CommonParameterTypes,
|
|
5129
5764
|
ContextCheckpointTool: () => ContextCheckpointTool,
|
|
5130
5765
|
computeToolIdempotencyKey: () => computeToolIdempotencyKey,
|
|
5766
|
+
copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
|
|
5131
5767
|
createContextCheckpointTool: () => createContextCheckpointTool,
|
|
5132
5768
|
ensureToolContextRuntimeCapability: () => ensureToolContextRuntimeCapability,
|
|
5133
5769
|
findCachedToolOutputByIdempotencyKey: () => findCachedToolOutputByIdempotencyKey,
|
|
@@ -5321,7 +5957,7 @@ function createContextCheckpointTool(options) {
|
|
|
5321
5957
|
function isRecord15(value) {
|
|
5322
5958
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
5323
5959
|
}
|
|
5324
|
-
function
|
|
5960
|
+
function readNonEmptyString5(value) {
|
|
5325
5961
|
if (typeof value !== "string") {
|
|
5326
5962
|
return void 0;
|
|
5327
5963
|
}
|
|
@@ -5341,13 +5977,13 @@ function readToolContextUserQuery(context) {
|
|
|
5341
5977
|
if (!context) {
|
|
5342
5978
|
return void 0;
|
|
5343
5979
|
}
|
|
5344
|
-
return
|
|
5980
|
+
return readNonEmptyString5(context["user_query"]);
|
|
5345
5981
|
}
|
|
5346
5982
|
function readToolContextModelId(context) {
|
|
5347
5983
|
if (!context) {
|
|
5348
5984
|
return void 0;
|
|
5349
5985
|
}
|
|
5350
|
-
return
|
|
5986
|
+
return readNonEmptyString5(context["modelId"]);
|
|
5351
5987
|
}
|
|
5352
5988
|
function readToolContextRunContext(context) {
|
|
5353
5989
|
if (!context) {
|
|
@@ -6549,6 +7185,7 @@ async function callLlmStream(params) {
|
|
|
6549
7185
|
const streamAnswerId = generateMessageId();
|
|
6550
7186
|
let streamChunkSeq = 0;
|
|
6551
7187
|
let capturedUsage = void 0;
|
|
7188
|
+
let capturedCanonicalUsage = void 0;
|
|
6552
7189
|
const toolAccumulator = new ToolCallStreamAccumulator([
|
|
6553
7190
|
"markdown_edit",
|
|
6554
7191
|
"text_to_image",
|
|
@@ -6607,6 +7244,10 @@ async function callLlmStream(params) {
|
|
|
6607
7244
|
if (typeof chunk !== "object" || chunk === null) {
|
|
6608
7245
|
return;
|
|
6609
7246
|
}
|
|
7247
|
+
const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
|
|
7248
|
+
if (parsedCanonicalUsage.success) {
|
|
7249
|
+
capturedCanonicalUsage = parsedCanonicalUsage.data;
|
|
7250
|
+
}
|
|
6610
7251
|
if (chunk.content) {
|
|
6611
7252
|
emitThoughtComplete(thoughtSegmenter.onBoundary());
|
|
6612
7253
|
fullResponse += chunk.content;
|
|
@@ -6691,6 +7332,12 @@ async function callLlmStream(params) {
|
|
|
6691
7332
|
const onUsage = (usage) => {
|
|
6692
7333
|
capturedUsage = usage;
|
|
6693
7334
|
};
|
|
7335
|
+
const onCanonicalUsage = (usage) => {
|
|
7336
|
+
const parsed = CanonicalLlmUsage.safeParse(usage);
|
|
7337
|
+
if (parsed.success) {
|
|
7338
|
+
capturedCanonicalUsage = parsed.data;
|
|
7339
|
+
}
|
|
7340
|
+
};
|
|
6694
7341
|
await aiEngine.chatCompletionStream(
|
|
6695
7342
|
modelId,
|
|
6696
7343
|
messages,
|
|
@@ -6703,7 +7350,8 @@ async function callLlmStream(params) {
|
|
|
6703
7350
|
onError,
|
|
6704
7351
|
onFinish,
|
|
6705
7352
|
onThought,
|
|
6706
|
-
onUsage
|
|
7353
|
+
onUsage,
|
|
7354
|
+
onCanonicalUsage
|
|
6707
7355
|
);
|
|
6708
7356
|
if (streamError) {
|
|
6709
7357
|
throw streamError;
|
|
@@ -6711,12 +7359,13 @@ async function callLlmStream(params) {
|
|
|
6711
7359
|
emitThoughtComplete(thoughtSegmenter.finalize());
|
|
6712
7360
|
const mergedToolCalls = toolAccumulator.getToolCalls();
|
|
6713
7361
|
assertToolCallsHaveValidJsonArguments(mergedToolCalls);
|
|
6714
|
-
if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
|
|
7362
|
+
if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
|
|
6715
7363
|
return {
|
|
6716
7364
|
content: fullResponse,
|
|
6717
7365
|
tool_calls: mergedToolCalls,
|
|
6718
7366
|
reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
|
|
6719
|
-
...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
|
|
7367
|
+
...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
|
|
7368
|
+
...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
|
|
6720
7369
|
};
|
|
6721
7370
|
}
|
|
6722
7371
|
return fullResponse;
|
|
@@ -6766,6 +7415,10 @@ function tryCloudQuotaFallback({
|
|
|
6766
7415
|
}
|
|
6767
7416
|
|
|
6768
7417
|
// src/runtime-kernel/llm/usage-telemetry.ts
|
|
7418
|
+
function parseCanonicalUsage(value) {
|
|
7419
|
+
const parsed = CanonicalLlmUsage.safeParse(value);
|
|
7420
|
+
return parsed.success ? parsed.data : void 0;
|
|
7421
|
+
}
|
|
6769
7422
|
async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
|
|
6770
7423
|
const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
|
|
6771
7424
|
return normalizeCompletionResponse(response);
|
|
@@ -6776,6 +7429,7 @@ function normalizeCompletionResponse(response) {
|
|
|
6776
7429
|
}
|
|
6777
7430
|
if (isRecord19(response)) {
|
|
6778
7431
|
const usage = response["usage"];
|
|
7432
|
+
const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
|
|
6779
7433
|
const parsedToolCalls = toToolCalls(response["tool_calls"]);
|
|
6780
7434
|
if (parsedToolCalls) {
|
|
6781
7435
|
const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
|
|
@@ -6783,7 +7437,8 @@ function normalizeCompletionResponse(response) {
|
|
|
6783
7437
|
content: typeof response["content"] === "string" ? response["content"] : "",
|
|
6784
7438
|
tool_calls: parsedToolCalls,
|
|
6785
7439
|
reasoning_details: reasoningDetails,
|
|
6786
|
-
...usage !== void 0 ? { usage } : {}
|
|
7440
|
+
...usage !== void 0 ? { usage } : {},
|
|
7441
|
+
...canonicalUsage !== void 0 ? { canonicalUsage } : {}
|
|
6787
7442
|
};
|
|
6788
7443
|
}
|
|
6789
7444
|
}
|
|
@@ -6793,10 +7448,12 @@ function normalizeCompletionResponse(response) {
|
|
|
6793
7448
|
if (typeof response === "object") {
|
|
6794
7449
|
if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
|
|
6795
7450
|
const usage = response["usage"];
|
|
7451
|
+
const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
|
|
6796
7452
|
return {
|
|
6797
7453
|
content: typeof response["content"] === "string" ? response["content"] : "",
|
|
6798
7454
|
reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
|
|
6799
|
-
...usage !== void 0 ? { usage } : {}
|
|
7455
|
+
...usage !== void 0 ? { usage } : {},
|
|
7456
|
+
...canonicalUsage !== void 0 ? { canonicalUsage } : {}
|
|
6800
7457
|
};
|
|
6801
7458
|
}
|
|
6802
7459
|
if (isRecord19(response)) {
|
|
@@ -7050,29 +7707,6 @@ var LlmCaller = class {
|
|
|
7050
7707
|
}
|
|
7051
7708
|
};
|
|
7052
7709
|
|
|
7053
|
-
// src/shared/defaultTokenizerPort.ts
|
|
7054
|
-
var DefaultTokenizerPort = class {
|
|
7055
|
-
constructor(config = {}) {
|
|
7056
|
-
this.config = config;
|
|
7057
|
-
}
|
|
7058
|
-
estimateText(text, _modelId) {
|
|
7059
|
-
return TokenCalculator.estimateTokens(text, {
|
|
7060
|
-
encoding: this.config.encoding,
|
|
7061
|
-
avgCharsPerToken: this.config.avgCharsPerToken
|
|
7062
|
-
});
|
|
7063
|
-
}
|
|
7064
|
-
estimateMessage(message, _modelId) {
|
|
7065
|
-
return TokenCalculator.estimateMessageTokens(message, {
|
|
7066
|
-
encoding: this.config.encoding,
|
|
7067
|
-
avgCharsPerToken: this.config.avgCharsPerToken,
|
|
7068
|
-
toolCallOverhead: this.config.toolCallOverhead
|
|
7069
|
-
});
|
|
7070
|
-
}
|
|
7071
|
-
};
|
|
7072
|
-
function createDefaultTokenizerPort(config = {}) {
|
|
7073
|
-
return new DefaultTokenizerPort(config);
|
|
7074
|
-
}
|
|
7075
|
-
|
|
7076
7710
|
// src/runtime-kernel/child-runs/index.ts
|
|
7077
7711
|
var child_runs_exports = {};
|
|
7078
7712
|
__export(child_runs_exports, {
|
|
@@ -7082,7 +7716,6 @@ __export(child_runs_exports, {
|
|
|
7082
7716
|
|
|
7083
7717
|
// src/runtime-kernel/child-runs/childToolContext.ts
|
|
7084
7718
|
function createChildRunToolContext(params) {
|
|
7085
|
-
const inheritedConversationId = typeof params.parentToolContext.conversationId === "string" && params.parentToolContext.conversationId.trim().length > 0 ? params.parentToolContext.conversationId.trim() : void 0;
|
|
7086
7719
|
const inheritedContext = stripRuntimeReservedToolContextPatch(params.parentToolContext);
|
|
7087
7720
|
const childToolContext = {
|
|
7088
7721
|
...inheritedContext,
|
|
@@ -7094,7 +7727,7 @@ function createChildRunToolContext(params) {
|
|
|
7094
7727
|
persistedHistory: params.seedHistory,
|
|
7095
7728
|
workingHistory: params.seedHistory,
|
|
7096
7729
|
executionMeta: {
|
|
7097
|
-
conversationId:
|
|
7730
|
+
conversationId: params.conversationId,
|
|
7098
7731
|
turnId: params.turnId,
|
|
7099
7732
|
runId: params.runId,
|
|
7100
7733
|
parentRunId: params.parentRunId
|
|
@@ -7196,6 +7829,8 @@ var FinalAnswerCollector = class {
|
|
|
7196
7829
|
this.conversationId = conversationId;
|
|
7197
7830
|
this.turnId = turnId;
|
|
7198
7831
|
}
|
|
7832
|
+
conversationId;
|
|
7833
|
+
turnId;
|
|
7199
7834
|
answerId;
|
|
7200
7835
|
chunks = [];
|
|
7201
7836
|
chunkCount = 0;
|
|
@@ -7412,7 +8047,7 @@ function readCheckpointHistory(checkpoint) {
|
|
|
7412
8047
|
});
|
|
7413
8048
|
}
|
|
7414
8049
|
async function recoverChildRunEventsFromCheckpoint(params) {
|
|
7415
|
-
const checkpoint = await params.checkpointer.load(params.
|
|
8050
|
+
const checkpoint = await params.checkpointer.load(params.checkpointKey);
|
|
7416
8051
|
const history = readCheckpointHistory(checkpoint);
|
|
7417
8052
|
if (history.length === 0) {
|
|
7418
8053
|
return [];
|
|
@@ -7420,7 +8055,7 @@ async function recoverChildRunEventsFromCheckpoint(params) {
|
|
|
7420
8055
|
if (hasSeedHistoryPrefix(history, params.seedHistory)) {
|
|
7421
8056
|
return history.slice(params.seedHistory.length);
|
|
7422
8057
|
}
|
|
7423
|
-
return history.filter((event) => event.conversation_id === params.
|
|
8058
|
+
return history.filter((event) => event.conversation_id === params.childConversationId);
|
|
7424
8059
|
}
|
|
7425
8060
|
|
|
7426
8061
|
// src/runtime-kernel/child-runs/childRunInvoker.ts
|
|
@@ -7449,6 +8084,7 @@ var ChildRunInvoker = class {
|
|
|
7449
8084
|
agentConfig,
|
|
7450
8085
|
userMessage,
|
|
7451
8086
|
parentToolContext,
|
|
8087
|
+
conversationId,
|
|
7452
8088
|
runId,
|
|
7453
8089
|
parentRunId,
|
|
7454
8090
|
subrunTracePublisher,
|
|
@@ -7457,12 +8093,18 @@ var ChildRunInvoker = class {
|
|
|
7457
8093
|
modelId,
|
|
7458
8094
|
abortSignal
|
|
7459
8095
|
} = config;
|
|
7460
|
-
const
|
|
8096
|
+
const internalCheckpointKey = `internal_${generateMessageId()}`;
|
|
8097
|
+
const runtimeConversationId = resolveChildRunConversationId({
|
|
8098
|
+
explicitConversationId: conversationId,
|
|
8099
|
+
parentToolContext,
|
|
8100
|
+
fallbackConversationId: internalCheckpointKey
|
|
8101
|
+
});
|
|
7461
8102
|
const turnId = `turn_${Date.now()}`;
|
|
7462
|
-
const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() :
|
|
8103
|
+
const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalCheckpointKey;
|
|
7463
8104
|
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;
|
|
7464
8105
|
logger13.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
|
|
7465
|
-
conversationId:
|
|
8106
|
+
conversationId: runtimeConversationId,
|
|
8107
|
+
checkpointKey: internalCheckpointKey,
|
|
7466
8108
|
maxSteps,
|
|
7467
8109
|
userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
|
|
7468
8110
|
});
|
|
@@ -7523,7 +8165,7 @@ var ChildRunInvoker = class {
|
|
|
7523
8165
|
const seedHistory = Array.isArray(seedHistoryEvents) ? seedHistoryEvents : [];
|
|
7524
8166
|
const childToolContext = createChildRunToolContext({
|
|
7525
8167
|
parentToolContext,
|
|
7526
|
-
|
|
8168
|
+
conversationId: runtimeConversationId,
|
|
7527
8169
|
turnId,
|
|
7528
8170
|
runId: childRunId,
|
|
7529
8171
|
parentRunId: resolvedParentRunId,
|
|
@@ -7532,13 +8174,13 @@ var ChildRunInvoker = class {
|
|
|
7532
8174
|
});
|
|
7533
8175
|
const subrunSseSink = subrunTracePublisher ? createChildRunTraceSink({
|
|
7534
8176
|
publisher: subrunTracePublisher,
|
|
7535
|
-
conversationId:
|
|
8177
|
+
conversationId: runtimeConversationId,
|
|
7536
8178
|
turnId
|
|
7537
8179
|
}) : void 0;
|
|
7538
8180
|
const initialLocal = {
|
|
7539
8181
|
request,
|
|
7540
8182
|
history: seedHistory,
|
|
7541
|
-
conversationId:
|
|
8183
|
+
conversationId: runtimeConversationId,
|
|
7542
8184
|
turnId,
|
|
7543
8185
|
toolContext: childToolContext,
|
|
7544
8186
|
...abortSignal ? { signal: abortSignal } : {},
|
|
@@ -7546,7 +8188,7 @@ var ChildRunInvoker = class {
|
|
|
7546
8188
|
...subrunSseSink ? { sseSink: subrunSseSink } : {},
|
|
7547
8189
|
systemPrompt
|
|
7548
8190
|
};
|
|
7549
|
-
await graphExecutor.prime(
|
|
8191
|
+
await graphExecutor.prime(internalCheckpointKey, initialLocal, "llm");
|
|
7550
8192
|
const allEvents = [];
|
|
7551
8193
|
let stepCount = 0;
|
|
7552
8194
|
let finalAnswer;
|
|
@@ -7558,7 +8200,7 @@ var ChildRunInvoker = class {
|
|
|
7558
8200
|
err.name = "AbortError";
|
|
7559
8201
|
throw err;
|
|
7560
8202
|
}
|
|
7561
|
-
const result = await graphExecutor.runUntilYield(
|
|
8203
|
+
const result = await graphExecutor.runUntilYield(internalCheckpointKey);
|
|
7562
8204
|
appendUniqueEvents(allEvents, result.events);
|
|
7563
8205
|
stepCount = result.stepCount;
|
|
7564
8206
|
if (subrunSseSink && typeof subrunSseSink.finalize === "function") {
|
|
@@ -7592,8 +8234,8 @@ var ChildRunInvoker = class {
|
|
|
7592
8234
|
}
|
|
7593
8235
|
const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
|
|
7594
8236
|
checkpointer,
|
|
7595
|
-
|
|
7596
|
-
|
|
8237
|
+
checkpointKey: internalCheckpointKey,
|
|
8238
|
+
childConversationId: runtimeConversationId,
|
|
7597
8239
|
seedHistory
|
|
7598
8240
|
});
|
|
7599
8241
|
appendUniqueEvents(allEvents, recoveredEvents);
|
|
@@ -7610,7 +8252,7 @@ var ChildRunInvoker = class {
|
|
|
7610
8252
|
stack: err.stack
|
|
7611
8253
|
} : { error: String(err) });
|
|
7612
8254
|
}
|
|
7613
|
-
await checkpointer.clear(
|
|
8255
|
+
await checkpointer.clear(internalCheckpointKey);
|
|
7614
8256
|
return {
|
|
7615
8257
|
success: !error,
|
|
7616
8258
|
runId: childRunId,
|
|
@@ -7623,6 +8265,16 @@ var ChildRunInvoker = class {
|
|
|
7623
8265
|
};
|
|
7624
8266
|
}
|
|
7625
8267
|
};
|
|
8268
|
+
function readNonEmptyString6(value) {
|
|
8269
|
+
if (typeof value !== "string") {
|
|
8270
|
+
return void 0;
|
|
8271
|
+
}
|
|
8272
|
+
const trimmed = value.trim();
|
|
8273
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
8274
|
+
}
|
|
8275
|
+
function resolveChildRunConversationId(params) {
|
|
8276
|
+
return readNonEmptyString6(params.explicitConversationId) ?? readNonEmptyString6(params.parentToolContext.conversationId) ?? params.fallbackConversationId;
|
|
8277
|
+
}
|
|
7626
8278
|
function resolveChildRunSystemReminderPolicy(agentConfig) {
|
|
7627
8279
|
const configured = agentConfig.systemReminderPolicy ?? agentConfig.contextPolicy?.systemReminder;
|
|
7628
8280
|
const threshold = agentConfig.stepPolicy?.lastStepsHintThreshold;
|
|
@@ -7813,7 +8465,7 @@ function cloneRunRecord(record) {
|
|
|
7813
8465
|
...record,
|
|
7814
8466
|
iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
|
|
7815
8467
|
errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
|
|
7816
|
-
metadata: record.metadata ?
|
|
8468
|
+
metadata: record.metadata ? structuredClone(record.metadata) : void 0
|
|
7817
8469
|
};
|
|
7818
8470
|
}
|
|
7819
8471
|
function matchesStatus(candidate, filter) {
|
|
@@ -8225,7 +8877,7 @@ function isTerminalStatus(status) {
|
|
|
8225
8877
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
8226
8878
|
}
|
|
8227
8879
|
function cloneMetadata(metadata) {
|
|
8228
|
-
return metadata ?
|
|
8880
|
+
return metadata ? structuredClone(metadata) : void 0;
|
|
8229
8881
|
}
|
|
8230
8882
|
function recordToSnapshot(record) {
|
|
8231
8883
|
return {
|
|
@@ -8312,7 +8964,7 @@ var DefaultRunSupervisor = class {
|
|
|
8312
8964
|
startedAt,
|
|
8313
8965
|
updatedAt: startedAt,
|
|
8314
8966
|
iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
|
|
8315
|
-
metadata: spec.metadata
|
|
8967
|
+
metadata: cloneMetadata(spec.metadata)
|
|
8316
8968
|
};
|
|
8317
8969
|
await this.registryStore.save(record);
|
|
8318
8970
|
const handle = new DefaultRunHandle({
|
|
@@ -8486,12 +9138,13 @@ var DefaultRunSupervisor = class {
|
|
|
8486
9138
|
}
|
|
8487
9139
|
try {
|
|
8488
9140
|
await handle.markRunning({ currentNode: "detached" });
|
|
9141
|
+
const registeredRecord = await this.registryStore.load(handle.runId);
|
|
8489
9142
|
const executorOutcome = await this.executor.execute({
|
|
8490
9143
|
runId: handle.runId,
|
|
8491
|
-
parentRunId:
|
|
8492
|
-
conversationId: spec.conversationId,
|
|
8493
|
-
agentSpec: spec
|
|
8494
|
-
request:
|
|
9144
|
+
parentRunId: handle.parentRunId,
|
|
9145
|
+
conversationId: registeredRecord?.conversationId ?? spec.conversationId,
|
|
9146
|
+
agentSpec: await handle.spec(),
|
|
9147
|
+
request: await handle.request(),
|
|
8495
9148
|
signal: handle.signal,
|
|
8496
9149
|
eventBus: spec.eventBus,
|
|
8497
9150
|
eventStore: spec.eventStore,
|
|
@@ -8500,7 +9153,7 @@ var DefaultRunSupervisor = class {
|
|
|
8500
9153
|
contextFences: spec.contextFences,
|
|
8501
9154
|
wakeSource: spec.wakeSource,
|
|
8502
9155
|
ephemeral: spec.ephemeral,
|
|
8503
|
-
metadata: spec.metadata
|
|
9156
|
+
metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
|
|
8504
9157
|
});
|
|
8505
9158
|
const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
|
|
8506
9159
|
this.notifyTerminalWaiters(outcome);
|
|
@@ -8564,10 +9217,14 @@ var DefaultRunSupervisor = class {
|
|
|
8564
9217
|
await this.registryStore.save(record);
|
|
8565
9218
|
}
|
|
8566
9219
|
const completedAt = executorOutcome?.completedAt ?? this.now();
|
|
9220
|
+
const fallbackMeta = record ? void 0 : await handle.meta();
|
|
8567
9221
|
const outcome = recordToTerminalOutcome(record ?? {
|
|
8568
9222
|
runId: handle.runId,
|
|
8569
9223
|
parentRunId: handle.parentRunId,
|
|
8570
|
-
|
|
9224
|
+
conversationId: fallbackMeta?.conversationId ?? "",
|
|
9225
|
+
agentSpecId: fallbackMeta?.agentSpecId,
|
|
9226
|
+
status: executorOutcome?.status ?? "completed",
|
|
9227
|
+
startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
|
|
8571
9228
|
const nextOutcome = {
|
|
8572
9229
|
...outcome,
|
|
8573
9230
|
metadata: {
|
|
@@ -8659,6 +9316,7 @@ __export(telemetry_exports, {
|
|
|
8659
9316
|
var TELEMETRY_EVENT_KINDS = [
|
|
8660
9317
|
"llm_call",
|
|
8661
9318
|
"tool_call",
|
|
9319
|
+
"context_build",
|
|
8662
9320
|
"graph_node",
|
|
8663
9321
|
"run_lifecycle"
|
|
8664
9322
|
];
|
|
@@ -8795,6 +9453,7 @@ function createGraphLoopHarness(options) {
|
|
|
8795
9453
|
};
|
|
8796
9454
|
return {
|
|
8797
9455
|
async run() {
|
|
9456
|
+
const checkpointKey = options.conversationId;
|
|
8798
9457
|
const executor = createDefaultGraphExecutor({
|
|
8799
9458
|
llmNode: options.createLlmNode({
|
|
8800
9459
|
llmCaller: options.llmCaller,
|
|
@@ -8823,8 +9482,8 @@ function createGraphLoopHarness(options) {
|
|
|
8823
9482
|
signal: options.signal ?? options.toolContext.abortSignal,
|
|
8824
9483
|
executorLocal
|
|
8825
9484
|
};
|
|
8826
|
-
await executor.prime(
|
|
8827
|
-
const result = await executor.runUntilYield(
|
|
9485
|
+
await executor.prime(checkpointKey, local, "user");
|
|
9486
|
+
const result = await executor.runUntilYield(checkpointKey);
|
|
8828
9487
|
return {
|
|
8829
9488
|
checkpointNodeId: result.checkpoint.nodeId,
|
|
8830
9489
|
stepCount: result.stepCount
|
|
@@ -9418,6 +10077,27 @@ var summarizeToolOutput = (toolName, output, toolSummaryProvider, toolArgs, conf
|
|
|
9418
10077
|
function isRecord25(value) {
|
|
9419
10078
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
9420
10079
|
}
|
|
10080
|
+
function readObservationTruncationMeta(value) {
|
|
10081
|
+
if (!isRecord25(value)) {
|
|
10082
|
+
return void 0;
|
|
10083
|
+
}
|
|
10084
|
+
const originalChars = value["originalChars"];
|
|
10085
|
+
const previewChars = value["previewChars"];
|
|
10086
|
+
if (typeof originalChars !== "number" || !Number.isInteger(originalChars) || originalChars < 0) {
|
|
10087
|
+
return void 0;
|
|
10088
|
+
}
|
|
10089
|
+
if (typeof previewChars !== "number" || !Number.isInteger(previewChars) || previewChars < 0) {
|
|
10090
|
+
return void 0;
|
|
10091
|
+
}
|
|
10092
|
+
const originalLines = value["originalLines"];
|
|
10093
|
+
const previewLines = value["previewLines"];
|
|
10094
|
+
return {
|
|
10095
|
+
originalChars,
|
|
10096
|
+
previewChars,
|
|
10097
|
+
...typeof originalLines === "number" && Number.isInteger(originalLines) && originalLines >= 0 ? { originalLines } : {},
|
|
10098
|
+
...typeof previewLines === "number" && Number.isInteger(previewLines) && previewLines >= 0 ? { previewLines } : {}
|
|
10099
|
+
};
|
|
10100
|
+
}
|
|
9421
10101
|
function isHistorySummaryEvent2(event) {
|
|
9422
10102
|
return "type" in event && event.type === "history_summary";
|
|
9423
10103
|
}
|
|
@@ -9530,6 +10210,7 @@ function convertEventToAiMessage(event) {
|
|
|
9530
10210
|
}
|
|
9531
10211
|
})();
|
|
9532
10212
|
const outputContent = observationFromPayload ?? rawOutput;
|
|
10213
|
+
const observationTruncation = readObservationTruncationMeta(event.metadata?.observationTruncation);
|
|
9533
10214
|
return {
|
|
9534
10215
|
id: event.id,
|
|
9535
10216
|
role: "tool",
|
|
@@ -9540,6 +10221,7 @@ function convertEventToAiMessage(event) {
|
|
|
9540
10221
|
tool_call_id: event.tool_call_id,
|
|
9541
10222
|
tool_name: event.tool_name,
|
|
9542
10223
|
raw_output: rawOutput,
|
|
10224
|
+
...observationTruncation ? { observationTruncation } : {},
|
|
9543
10225
|
...observationFromPayload ? { observation: observationFromPayload } : {}
|
|
9544
10226
|
}
|
|
9545
10227
|
};
|
|
@@ -10338,14 +11020,14 @@ function createRunSupervisorHarness(options = {}) {
|
|
|
10338
11020
|
function failure2(id, title, message, details) {
|
|
10339
11021
|
return details === void 0 ? { id, title, message } : { id, title, message, details };
|
|
10340
11022
|
}
|
|
10341
|
-
function
|
|
11023
|
+
function readRecord2(value) {
|
|
10342
11024
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
10343
11025
|
}
|
|
10344
11026
|
function readString4(value) {
|
|
10345
11027
|
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
10346
11028
|
}
|
|
10347
11029
|
function readEventRunId(event) {
|
|
10348
|
-
const metadata =
|
|
11030
|
+
const metadata = readRecord2(event.metadata);
|
|
10349
11031
|
if (!metadata) {
|
|
10350
11032
|
return void 0;
|
|
10351
11033
|
}
|
|
@@ -10353,7 +11035,7 @@ function readEventRunId(event) {
|
|
|
10353
11035
|
if (direct) {
|
|
10354
11036
|
return direct;
|
|
10355
11037
|
}
|
|
10356
|
-
const runContext =
|
|
11038
|
+
const runContext = readRecord2(metadata.run_context);
|
|
10357
11039
|
return runContext ? readString4(runContext.runId) ?? readString4(runContext.run_id) : void 0;
|
|
10358
11040
|
}
|
|
10359
11041
|
function runIds(records) {
|