@linnlabs/linnkit 0.10.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 +156 -1
- 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 +565 -194
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +565 -194
- package/dist/cli.js.map +1 -1
- package/dist/context-manager.cjs +590 -26
- package/dist/context-manager.cjs.map +1 -1
- package/dist/context-manager.d.cts +84 -7
- package/dist/context-manager.d.ts +84 -7
- package/dist/context-manager.js +590 -26
- package/dist/context-manager.js.map +1 -1
- package/dist/{context-trace-BHKDS-eq.d.cts → context-trace-DrtvKac4.d.cts} +36 -3
- package/dist/{context-trace-CHbqHmyE.d.ts → context-trace-WV1HAZeB.d.ts} +36 -3
- package/dist/contracts.cjs +222 -1
- package/dist/contracts.cjs.map +1 -1
- package/dist/contracts.d.cts +5 -3
- package/dist/contracts.d.ts +5 -3
- package/dist/contracts.js +202 -2
- package/dist/contracts.js.map +1 -1
- package/dist/{defaultGraphExecutor-C2E59v_R.d.cts → defaultGraphExecutor-L1ri3oij.d.cts} +35 -7
- package/dist/{defaultGraphExecutor-B29_qTHy.d.ts → defaultGraphExecutor-QzzdudLQ.d.ts} +35 -7
- package/dist/{index-BAaUP9yU.d.cts → index-BeQO0rx2.d.cts} +328 -263
- package/dist/{index-Cvr23YCl.d.cts → index-CDofGr_4.d.ts} +24 -6
- package/dist/{index-CKQzzZ5Y.d.cts → index-Crl5E4eF.d.cts} +26 -3
- package/dist/{index-C0DAjsdX.d.ts → index-DWGKvssS.d.ts} +2 -2
- package/dist/{index-D0mKxTR5.d.ts → index-X5lYU1Lj.d.ts} +26 -3
- package/dist/{index-DDzuSb0n.d.ts → index-uCNCpJBg.d.cts} +24 -6
- package/dist/{index-BaVpVNi2.d.ts → index-wOZD-p2-.d.ts} +328 -263
- package/dist/{index-BnYCS8Zg.d.cts → index-wXVAHZ0D.d.cts} +2 -2
- package/dist/index.cjs +893 -312
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -14
- package/dist/index.d.ts +17 -14
- package/dist/index.js +893 -312
- 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-s-tSp3sB.d.cts → ports-Dugizzje.d.cts} +4 -0
- package/dist/{ports-DpPTFhSd.d.ts → ports-fhp84x_C.d.ts} +4 -0
- package/dist/ports.d.cts +8 -5
- package/dist/ports.d.ts +8 -5
- package/dist/quickstart.cjs +564 -193
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.d.cts +9 -8
- package/dist/quickstart.d.ts +9 -8
- package/dist/quickstart.js +564 -193
- package/dist/quickstart.js.map +1 -1
- package/dist/{runAgent-C6F-399C.d.ts → runAgent-BmMSju8I.d.ts} +4 -4
- package/dist/{runAgent-ilEj66Ik.d.cts → runAgent-CKgcRSRH.d.cts} +4 -4
- package/dist/{runHandle-BNOqS-Bl.d.cts → runHandle-DH4VmQx6.d.cts} +4 -2
- package/dist/{runHandle-BdLXOFqF.d.ts → runHandle-o3p06Nva.d.ts} +4 -2
- package/dist/runtime-kernel/events.cjs +201 -1
- package/dist/runtime-kernel/events.cjs.map +1 -1
- package/dist/runtime-kernel/events.d.cts +3 -3
- package/dist/runtime-kernel/events.d.ts +3 -3
- package/dist/runtime-kernel/events.js +201 -1
- package/dist/runtime-kernel/events.js.map +1 -1
- package/dist/runtime-kernel.cjs +824 -264
- package/dist/runtime-kernel.cjs.map +1 -1
- package/dist/runtime-kernel.d.cts +14 -12
- package/dist/runtime-kernel.d.ts +14 -12
- package/dist/runtime-kernel.js +816 -265
- package/dist/runtime-kernel.js.map +1 -1
- package/dist/testkit.cjs +847 -264
- package/dist/testkit.cjs.map +1 -1
- package/dist/testkit.d.cts +14 -12
- package/dist/testkit.d.ts +14 -12
- package/dist/testkit.js +847 -264
- package/dist/testkit.js.map +1 -1
- package/dist/{agentSpec-Du4Iye0q.d.cts → token-accounting-CwpSPg4y.d.cts} +1265 -1
- package/dist/{agentSpec-Du4Iye0q.d.ts → token-accounting-CwpSPg4y.d.ts} +1265 -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/docs/README.md +1 -1
- package/docs/integration/README.md +2 -2
- package/docs/integration/agent-registration-guide.md +2 -0
- package/docs/integration/context-engineering.md +53 -1
- package/docs/integration/context-fences.md +12 -0
- package/package.json +2 -2
package/dist/context-manager.cjs
CHANGED
|
@@ -375,6 +375,12 @@ zod.z.object({
|
|
|
375
375
|
args: zod.z.record(zod.z.unknown()).optional(),
|
|
376
376
|
tool_call_id: zod.z.string()
|
|
377
377
|
});
|
|
378
|
+
var ObservationTruncationMeta = zod.z.object({
|
|
379
|
+
originalChars: zod.z.number().int().nonnegative(),
|
|
380
|
+
previewChars: zod.z.number().int().nonnegative(),
|
|
381
|
+
originalLines: zod.z.number().int().nonnegative().optional(),
|
|
382
|
+
previewLines: zod.z.number().int().nonnegative().optional()
|
|
383
|
+
});
|
|
378
384
|
var ImageInfoMeta = zod.z.object({
|
|
379
385
|
url: zod.z.string().optional(),
|
|
380
386
|
width: zod.z.number().int().positive().optional(),
|
|
@@ -406,6 +412,7 @@ var PersistentMetadata = zod.z.object({
|
|
|
406
412
|
tool_name: zod.z.string().optional(),
|
|
407
413
|
args: zod.z.record(zod.z.unknown()).optional(),
|
|
408
414
|
tool_call_id: zod.z.string().optional(),
|
|
415
|
+
observationTruncation: ObservationTruncationMeta.optional(),
|
|
409
416
|
raw_output: zod.z.string().optional(),
|
|
410
417
|
image_info: ImageInfoMeta.optional(),
|
|
411
418
|
taskType: zod.z.string().optional(),
|
|
@@ -552,7 +559,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
|
|
|
552
559
|
var AgentSpecTokenEstimationPolicy = zod.z.object({
|
|
553
560
|
encoding: zod.z.string().min(1).optional(),
|
|
554
561
|
avgCharsPerToken: zod.z.number().positive().optional(),
|
|
555
|
-
toolCallOverhead: zod.z.number().int().nonnegative().optional()
|
|
562
|
+
toolCallOverhead: zod.z.number().int().nonnegative().optional(),
|
|
563
|
+
calibration: zod.z.object({
|
|
564
|
+
enabled: zod.z.boolean().optional(),
|
|
565
|
+
minSamples: zod.z.number().int().positive().optional(),
|
|
566
|
+
minCoefficient: zod.z.number().positive().optional(),
|
|
567
|
+
maxCoefficient: zod.z.number().positive().optional()
|
|
568
|
+
}).optional(),
|
|
569
|
+
remoteCount: zod.z.object({
|
|
570
|
+
enabled: zod.z.boolean().optional(),
|
|
571
|
+
failureBehavior: zod.z.enum(["use-local-estimate", "fail-fast"]).optional()
|
|
572
|
+
}).optional()
|
|
556
573
|
});
|
|
557
574
|
var AgentSpecSystemReminderTrigger = zod.z.object({
|
|
558
575
|
kind: zod.z.string().min(1),
|
|
@@ -1327,6 +1344,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
|
|
|
1327
1344
|
error,
|
|
1328
1345
|
...options
|
|
1329
1346
|
});
|
|
1347
|
+
var TokenCountSource = zod.z.enum([
|
|
1348
|
+
"local-estimate",
|
|
1349
|
+
"provider-preflight-count",
|
|
1350
|
+
"provider-response-usage",
|
|
1351
|
+
"host-supplied",
|
|
1352
|
+
"test-fixture"
|
|
1353
|
+
]);
|
|
1354
|
+
var TokenCountConfidence = zod.z.enum([
|
|
1355
|
+
"estimate",
|
|
1356
|
+
"provider-estimate",
|
|
1357
|
+
"actual"
|
|
1358
|
+
]);
|
|
1359
|
+
var TokenRouteCapabilities = zod.z.object({
|
|
1360
|
+
supportsRemoteTokenCount: zod.z.boolean().optional(),
|
|
1361
|
+
supportsResponseUsage: zod.z.boolean().optional(),
|
|
1362
|
+
supportsImageInput: zod.z.boolean().optional(),
|
|
1363
|
+
supportsCachedInputBilling: zod.z.boolean().optional(),
|
|
1364
|
+
supportsReasoningTokens: zod.z.boolean().optional()
|
|
1365
|
+
});
|
|
1366
|
+
var TokenRoute = zod.z.object({
|
|
1367
|
+
providerId: zod.z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
|
|
1368
|
+
baseURL: zod.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"),
|
|
1369
|
+
modelId: zod.z.string().describe("host \u4FA7\u6A21\u578B id"),
|
|
1370
|
+
providerModelId: zod.z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
|
|
1371
|
+
capabilities: TokenRouteCapabilities.optional()
|
|
1372
|
+
});
|
|
1373
|
+
var tokenCount = zod.z.number().int().nonnegative();
|
|
1374
|
+
var CanonicalLlmUsage = zod.z.object({
|
|
1375
|
+
inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
|
|
1376
|
+
outputTokens: tokenCount.describe("\u8F93\u51FA token"),
|
|
1377
|
+
reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
|
|
1378
|
+
cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
|
|
1379
|
+
cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
|
|
1380
|
+
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"),
|
|
1381
|
+
source: TokenCountSource,
|
|
1382
|
+
confidence: TokenCountConfidence,
|
|
1383
|
+
rawUsage: zod.z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
|
|
1384
|
+
});
|
|
1385
|
+
var tokenCount2 = zod.z.number().int().nonnegative();
|
|
1386
|
+
var tokenPrice = zod.z.number().finite().nonnegative();
|
|
1387
|
+
zod.z.enum([
|
|
1388
|
+
"llm-usage",
|
|
1389
|
+
"context-component"
|
|
1390
|
+
]);
|
|
1391
|
+
var ContextTokenComponentKind = zod.z.enum([
|
|
1392
|
+
"system",
|
|
1393
|
+
"user",
|
|
1394
|
+
"assistant",
|
|
1395
|
+
"tool",
|
|
1396
|
+
"context-injection",
|
|
1397
|
+
"history-summary",
|
|
1398
|
+
"working-memory",
|
|
1399
|
+
"fence",
|
|
1400
|
+
"system-reminder",
|
|
1401
|
+
"other"
|
|
1402
|
+
]);
|
|
1403
|
+
var TokenUsageTotals = zod.z.object({
|
|
1404
|
+
inputTokens: tokenCount2,
|
|
1405
|
+
outputTokens: tokenCount2,
|
|
1406
|
+
reasoningTokens: tokenCount2.optional(),
|
|
1407
|
+
cacheReadTokens: tokenCount2.optional(),
|
|
1408
|
+
cacheWriteTokens: tokenCount2.optional(),
|
|
1409
|
+
totalTokens: tokenCount2.optional(),
|
|
1410
|
+
usageCount: zod.z.number().int().nonnegative()
|
|
1411
|
+
});
|
|
1412
|
+
var ContextTokenComponent = zod.z.object({
|
|
1413
|
+
componentId: zod.z.string().min(1),
|
|
1414
|
+
kind: ContextTokenComponentKind,
|
|
1415
|
+
tokens: tokenCount2,
|
|
1416
|
+
source: TokenCountSource,
|
|
1417
|
+
confidence: TokenCountConfidence,
|
|
1418
|
+
label: zod.z.string().optional(),
|
|
1419
|
+
messageId: zod.z.string().optional(),
|
|
1420
|
+
role: zod.z.string().optional(),
|
|
1421
|
+
action: zod.z.string().optional(),
|
|
1422
|
+
kept: zod.z.boolean().optional(),
|
|
1423
|
+
truncatedAtExecution: zod.z.boolean().optional(),
|
|
1424
|
+
originalTokensEstimate: tokenCount2.optional(),
|
|
1425
|
+
droppedTokensEstimate: tokenCount2.optional()
|
|
1426
|
+
});
|
|
1427
|
+
var TokenLedgerEntryBase = zod.z.object({
|
|
1428
|
+
id: zod.z.string().min(1),
|
|
1429
|
+
runId: zod.z.string().optional(),
|
|
1430
|
+
parentRunId: zod.z.string().optional(),
|
|
1431
|
+
conversationId: zod.z.string().optional(),
|
|
1432
|
+
turnId: zod.z.string().optional(),
|
|
1433
|
+
stepId: zod.z.string().optional(),
|
|
1434
|
+
route: TokenRoute.optional(),
|
|
1435
|
+
createdAt: zod.z.number().int().nonnegative().optional()
|
|
1436
|
+
});
|
|
1437
|
+
var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
|
|
1438
|
+
kind: zod.z.literal("llm-usage"),
|
|
1439
|
+
modelId: zod.z.string().optional(),
|
|
1440
|
+
usage: CanonicalLlmUsage
|
|
1441
|
+
});
|
|
1442
|
+
var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
|
|
1443
|
+
kind: zod.z.literal("context-component"),
|
|
1444
|
+
components: zod.z.array(ContextTokenComponent),
|
|
1445
|
+
totalTokens: tokenCount2
|
|
1446
|
+
});
|
|
1447
|
+
zod.z.discriminatedUnion("kind", [
|
|
1448
|
+
LlmUsageTokenLedgerEntry,
|
|
1449
|
+
ContextComponentTokenLedgerEntry
|
|
1450
|
+
]);
|
|
1451
|
+
var TokenLedgerAggregate = zod.z.object({
|
|
1452
|
+
llmUsage: TokenUsageTotals.optional(),
|
|
1453
|
+
contextTokens: tokenCount2,
|
|
1454
|
+
entryCount: zod.z.number().int().nonnegative(),
|
|
1455
|
+
llmCallCount: zod.z.number().int().nonnegative(),
|
|
1456
|
+
contextComponentCount: zod.z.number().int().nonnegative()
|
|
1457
|
+
});
|
|
1458
|
+
zod.z.object({
|
|
1459
|
+
/**
|
|
1460
|
+
* 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
|
|
1461
|
+
*/
|
|
1462
|
+
own: TokenLedgerAggregate,
|
|
1463
|
+
children: TokenLedgerAggregate.optional()
|
|
1464
|
+
});
|
|
1465
|
+
var TokenCostComponent = zod.z.enum([
|
|
1466
|
+
"input",
|
|
1467
|
+
"output",
|
|
1468
|
+
"reasoning",
|
|
1469
|
+
"cacheRead",
|
|
1470
|
+
"cacheWrite"
|
|
1471
|
+
]);
|
|
1472
|
+
zod.z.object({
|
|
1473
|
+
currency: zod.z.string().min(1),
|
|
1474
|
+
unit: zod.z.literal("per_1m_tokens"),
|
|
1475
|
+
input: tokenPrice.optional(),
|
|
1476
|
+
output: tokenPrice.optional(),
|
|
1477
|
+
reasoning: tokenPrice.optional(),
|
|
1478
|
+
cacheRead: tokenPrice.optional(),
|
|
1479
|
+
cacheWrite: tokenPrice.optional()
|
|
1480
|
+
});
|
|
1481
|
+
zod.z.object({
|
|
1482
|
+
status: zod.z.enum(["computed", "unknown"]),
|
|
1483
|
+
currency: zod.z.string().optional(),
|
|
1484
|
+
inputCost: tokenPrice.optional(),
|
|
1485
|
+
outputCost: tokenPrice.optional(),
|
|
1486
|
+
reasoningCost: tokenPrice.optional(),
|
|
1487
|
+
cacheReadCost: tokenPrice.optional(),
|
|
1488
|
+
cacheWriteCost: tokenPrice.optional(),
|
|
1489
|
+
totalCost: tokenPrice.optional(),
|
|
1490
|
+
missingPriceComponents: zod.z.array(TokenCostComponent).optional()
|
|
1491
|
+
});
|
|
1492
|
+
var tokenCount3 = zod.z.number().int().nonnegative();
|
|
1493
|
+
var actualCalibrationSource = zod.z.enum([
|
|
1494
|
+
"provider-response-usage",
|
|
1495
|
+
"host-supplied",
|
|
1496
|
+
"test-fixture"
|
|
1497
|
+
]);
|
|
1498
|
+
zod.z.object({
|
|
1499
|
+
route: TokenRoute,
|
|
1500
|
+
localEstimateTokens: tokenCount3,
|
|
1501
|
+
actualInputTokens: tokenCount3,
|
|
1502
|
+
source: actualCalibrationSource,
|
|
1503
|
+
confidence: zod.z.literal("actual"),
|
|
1504
|
+
observedAt: zod.z.number().int().nonnegative().optional(),
|
|
1505
|
+
runId: zod.z.string().optional(),
|
|
1506
|
+
ledgerEntryId: zod.z.string().optional()
|
|
1507
|
+
});
|
|
1508
|
+
zod.z.object({
|
|
1509
|
+
enabled: zod.z.boolean(),
|
|
1510
|
+
applied: zod.z.boolean(),
|
|
1511
|
+
route: TokenRoute.optional(),
|
|
1512
|
+
sampleCount: zod.z.number().int().nonnegative(),
|
|
1513
|
+
coefficient: zod.z.number().positive().optional(),
|
|
1514
|
+
minSamples: zod.z.number().int().positive().optional(),
|
|
1515
|
+
minCoefficient: zod.z.number().positive().optional(),
|
|
1516
|
+
maxCoefficient: zod.z.number().positive().optional(),
|
|
1517
|
+
localEstimateTokens: tokenCount3.optional(),
|
|
1518
|
+
calibratedEstimateTokens: tokenCount3.optional(),
|
|
1519
|
+
deltaTokens: zod.z.number().int().optional(),
|
|
1520
|
+
sampleLedgerEntryIds: zod.z.array(zod.z.string()).optional()
|
|
1521
|
+
});
|
|
1522
|
+
zod.z.object({
|
|
1523
|
+
route: TokenRoute.optional(),
|
|
1524
|
+
localEstimateTokens: tokenCount3,
|
|
1525
|
+
calibratedEstimateTokens: tokenCount3,
|
|
1526
|
+
finalTokens: tokenCount3,
|
|
1527
|
+
source: zod.z.literal("local-estimate"),
|
|
1528
|
+
confidence: zod.z.literal("estimate")
|
|
1529
|
+
});
|
|
1330
1530
|
|
|
1331
1531
|
// src/context-manager/shared/contextPolicyMerge.ts
|
|
1332
1532
|
function mergeContextPolicy(params) {
|
|
@@ -1358,7 +1558,7 @@ function mergePolicyLayer(base, override) {
|
|
|
1358
1558
|
workingMemory: mergeObject(base.workingMemory, override.workingMemory),
|
|
1359
1559
|
checkpoint: mergeObject(base.checkpoint, override.checkpoint),
|
|
1360
1560
|
reasoningRetention: mergeObject(base.reasoningRetention, override.reasoningRetention),
|
|
1361
|
-
tokenEstimation:
|
|
1561
|
+
tokenEstimation: mergeTokenEstimation(base.tokenEstimation, override.tokenEstimation),
|
|
1362
1562
|
systemReminder: mergeSystemReminder(base.systemReminder, override.systemReminder),
|
|
1363
1563
|
contextTrace: mergeObject(base.contextTrace, override.contextTrace)
|
|
1364
1564
|
};
|
|
@@ -1393,6 +1593,17 @@ function mergeToolOutput(base, override) {
|
|
|
1393
1593
|
observationGovernance: mergeObject(base?.observationGovernance, override?.observationGovernance)
|
|
1394
1594
|
};
|
|
1395
1595
|
}
|
|
1596
|
+
function mergeTokenEstimation(base, override) {
|
|
1597
|
+
if (!base && !override) {
|
|
1598
|
+
return void 0;
|
|
1599
|
+
}
|
|
1600
|
+
return {
|
|
1601
|
+
...base,
|
|
1602
|
+
...override,
|
|
1603
|
+
calibration: mergeObject(base?.calibration, override?.calibration),
|
|
1604
|
+
remoteCount: mergeObject(base?.remoteCount, override?.remoteCount)
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1396
1607
|
|
|
1397
1608
|
// src/context-manager/shared/context-trace.ts
|
|
1398
1609
|
var ContextTraceCollector = class _ContextTraceCollector {
|
|
@@ -1402,6 +1613,9 @@ var ContextTraceCollector = class _ContextTraceCollector {
|
|
|
1402
1613
|
effectivePolicy;
|
|
1403
1614
|
totalBudget;
|
|
1404
1615
|
originalCount;
|
|
1616
|
+
tokenCalibration;
|
|
1617
|
+
remoteTokenCount;
|
|
1618
|
+
tokenComponents;
|
|
1405
1619
|
events = [];
|
|
1406
1620
|
overflowed = false;
|
|
1407
1621
|
constructor(options) {
|
|
@@ -1411,6 +1625,8 @@ var ContextTraceCollector = class _ContextTraceCollector {
|
|
|
1411
1625
|
this.effectivePolicy = options.effectivePolicy;
|
|
1412
1626
|
this.totalBudget = options.totalBudget;
|
|
1413
1627
|
this.originalCount = options.originalCount;
|
|
1628
|
+
this.tokenCalibration = options.tokenCalibration;
|
|
1629
|
+
this.remoteTokenCount = options.remoteTokenCount;
|
|
1414
1630
|
}
|
|
1415
1631
|
static create(options) {
|
|
1416
1632
|
if (options.policy?.enabled !== true) {
|
|
@@ -1450,10 +1666,20 @@ var ContextTraceCollector = class _ContextTraceCollector {
|
|
|
1450
1666
|
tokens: this.includeTokenBreakdown ? state.tokens : 0,
|
|
1451
1667
|
kept,
|
|
1452
1668
|
reason: buildDecisionReason(state, kept),
|
|
1453
|
-
...state.replacementSourceIds ? { replacementSourceIds: [...state.replacementSourceIds] } : {}
|
|
1669
|
+
...state.replacementSourceIds ? { replacementSourceIds: [...state.replacementSourceIds] } : {},
|
|
1670
|
+
...this.includeTokenBreakdown && state.tokenCalibration ? { tokenCalibration: state.tokenCalibration } : {}
|
|
1454
1671
|
});
|
|
1455
1672
|
}
|
|
1456
1673
|
}
|
|
1674
|
+
recordRemoteTokenCount(trace) {
|
|
1675
|
+
this.remoteTokenCount = trace;
|
|
1676
|
+
}
|
|
1677
|
+
recordTokenComponents(components) {
|
|
1678
|
+
if (!this.includeTokenBreakdown) {
|
|
1679
|
+
return;
|
|
1680
|
+
}
|
|
1681
|
+
this.tokenComponents = [...components];
|
|
1682
|
+
}
|
|
1457
1683
|
build(finalMessages, finalTokens) {
|
|
1458
1684
|
return {
|
|
1459
1685
|
enabled: true,
|
|
@@ -1466,6 +1692,9 @@ var ContextTraceCollector = class _ContextTraceCollector {
|
|
|
1466
1692
|
originalCount: this.originalCount,
|
|
1467
1693
|
finalCount: finalMessages.length,
|
|
1468
1694
|
finalTokens,
|
|
1695
|
+
...this.tokenCalibration ? { tokenCalibration: this.tokenCalibration } : {},
|
|
1696
|
+
...this.remoteTokenCount ? { remoteTokenCount: this.remoteTokenCount } : {},
|
|
1697
|
+
...this.tokenComponents ? { tokenComponents: [...this.tokenComponents] } : {},
|
|
1469
1698
|
truncated: this.originalCount !== finalMessages.length,
|
|
1470
1699
|
events: [...this.events]
|
|
1471
1700
|
};
|
|
@@ -1922,8 +2151,12 @@ function formatFence(fence) {
|
|
|
1922
2151
|
return fence.descriptor.formatter(fence.message.content, fence.message.metadata?.fenceAttrs ?? {});
|
|
1923
2152
|
}
|
|
1924
2153
|
function wrapUserRequest(content) {
|
|
2154
|
+
const trimmed = content.trim();
|
|
2155
|
+
if (/<user_request(?:\s[^>]*)?>[\s\S]*<\/user_request>/.test(trimmed)) {
|
|
2156
|
+
return trimmed;
|
|
2157
|
+
}
|
|
1925
2158
|
return `<user_request>
|
|
1926
|
-
${
|
|
2159
|
+
${trimmed}
|
|
1927
2160
|
</user_request>`;
|
|
1928
2161
|
}
|
|
1929
2162
|
|
|
@@ -3038,7 +3271,11 @@ var AgentCoreContextProvider = class extends BaseContextProvider2 {
|
|
|
3038
3271
|
state.processedContent = processedContent;
|
|
3039
3272
|
state.contentType = contentType;
|
|
3040
3273
|
state.phase = "CORE_CONTEXT";
|
|
3041
|
-
|
|
3274
|
+
const tokenEstimate = context.estimateTokensWithTrace?.({ ...msg, content: processedContent });
|
|
3275
|
+
state.tokens = tokenEstimate?.tokens ?? context.estimateTokens({ ...msg, content: processedContent });
|
|
3276
|
+
if (tokenEstimate?.tokenCalibration) {
|
|
3277
|
+
state.tokenCalibration = tokenEstimate.tokenCalibration;
|
|
3278
|
+
}
|
|
3042
3279
|
coreTokens += state.tokens;
|
|
3043
3280
|
processedCount++;
|
|
3044
3281
|
this.debug(`\u2705 \u6807\u8BB0\u4E3A\u6838\u5FC3\u6D88\u606F`, {
|
|
@@ -4539,7 +4776,7 @@ async function runContextPipeline(options) {
|
|
|
4539
4776
|
message,
|
|
4540
4777
|
originalIndex: index,
|
|
4541
4778
|
action: "skip",
|
|
4542
|
-
|
|
4779
|
+
...estimateTokens(message)
|
|
4543
4780
|
}));
|
|
4544
4781
|
const providers = providerRegistry.getAllProviders();
|
|
4545
4782
|
let availableBudget = totalBudget;
|
|
@@ -4615,7 +4852,7 @@ async function runContextPipeline(options) {
|
|
|
4615
4852
|
buildStats.messageStats.afterWorkingMemory = states.filter((state) => state.action.startsWith("keep_")).length;
|
|
4616
4853
|
buildStats.messageStats.afterSummarization = states.filter((state) => state.action !== "skip").length;
|
|
4617
4854
|
const finalMessages = generateFinalMessages(states);
|
|
4618
|
-
const finalTokens = finalMessages.reduce((total, message) => total + estimateTokens(message), 0);
|
|
4855
|
+
const finalTokens = finalMessages.reduce((total, message) => total + estimateTokens(message).tokens, 0);
|
|
4619
4856
|
contextTrace?.recordMessageDecisions(states);
|
|
4620
4857
|
return {
|
|
4621
4858
|
finalMessages,
|
|
@@ -4668,6 +4905,85 @@ function isFatalProviderError(error) {
|
|
|
4668
4905
|
return isContextProviderError(error) && error.code === SUMMARIZATION_FAILED_ERROR_CODE && error.fatal === true;
|
|
4669
4906
|
}
|
|
4670
4907
|
|
|
4908
|
+
// src/context-manager/shared/token-calibration.ts
|
|
4909
|
+
var DEFAULT_MIN_SAMPLES = 3;
|
|
4910
|
+
var DEFAULT_MIN_COEFFICIENT = 1;
|
|
4911
|
+
var DEFAULT_MAX_COEFFICIENT = 4;
|
|
4912
|
+
function buildTokenUsageCalibrationState(input) {
|
|
4913
|
+
const enabled = input.policy?.enabled === true;
|
|
4914
|
+
const minSamples = input.policy?.minSamples ?? DEFAULT_MIN_SAMPLES;
|
|
4915
|
+
const minCoefficient = input.policy?.minCoefficient ?? DEFAULT_MIN_COEFFICIENT;
|
|
4916
|
+
const maxCoefficient = input.policy?.maxCoefficient ?? DEFAULT_MAX_COEFFICIENT;
|
|
4917
|
+
const route = input.route;
|
|
4918
|
+
if (!enabled || !route) {
|
|
4919
|
+
return {
|
|
4920
|
+
enabled,
|
|
4921
|
+
route,
|
|
4922
|
+
sampleCount: 0,
|
|
4923
|
+
minSamples,
|
|
4924
|
+
minCoefficient,
|
|
4925
|
+
maxCoefficient
|
|
4926
|
+
};
|
|
4927
|
+
}
|
|
4928
|
+
const matchingSamples = (input.samples ?? []).filter((sample) => sample.confidence === "actual" && sample.localEstimateTokens > 0 && sample.actualInputTokens > 0 && routeEquals(sample.route, route));
|
|
4929
|
+
if (matchingSamples.length < minSamples) {
|
|
4930
|
+
return {
|
|
4931
|
+
enabled,
|
|
4932
|
+
route,
|
|
4933
|
+
sampleCount: matchingSamples.length,
|
|
4934
|
+
minSamples,
|
|
4935
|
+
minCoefficient,
|
|
4936
|
+
maxCoefficient,
|
|
4937
|
+
sampleLedgerEntryIds: collectLedgerEntryIds(matchingSamples)
|
|
4938
|
+
};
|
|
4939
|
+
}
|
|
4940
|
+
const localTotal = matchingSamples.reduce((total, sample) => total + sample.localEstimateTokens, 0);
|
|
4941
|
+
const actualTotal = matchingSamples.reduce((total, sample) => total + sample.actualInputTokens, 0);
|
|
4942
|
+
const coefficient = clampCoefficient(actualTotal / localTotal, minCoefficient, maxCoefficient);
|
|
4943
|
+
return {
|
|
4944
|
+
enabled,
|
|
4945
|
+
route,
|
|
4946
|
+
sampleCount: matchingSamples.length,
|
|
4947
|
+
coefficient,
|
|
4948
|
+
minSamples,
|
|
4949
|
+
minCoefficient,
|
|
4950
|
+
maxCoefficient,
|
|
4951
|
+
sampleLedgerEntryIds: collectLedgerEntryIds(matchingSamples)
|
|
4952
|
+
};
|
|
4953
|
+
}
|
|
4954
|
+
function calibrateTokenEstimate(input) {
|
|
4955
|
+
const { localEstimateTokens, state } = input;
|
|
4956
|
+
const coefficient = state.coefficient;
|
|
4957
|
+
const shouldApply = state.enabled && coefficient !== void 0;
|
|
4958
|
+
const calibratedEstimateTokens = shouldApply ? Math.ceil(localEstimateTokens * coefficient) : localEstimateTokens;
|
|
4959
|
+
return {
|
|
4960
|
+
tokens: calibratedEstimateTokens,
|
|
4961
|
+
trace: {
|
|
4962
|
+
enabled: state.enabled,
|
|
4963
|
+
applied: shouldApply,
|
|
4964
|
+
...state.route ? { route: state.route } : {},
|
|
4965
|
+
sampleCount: state.sampleCount,
|
|
4966
|
+
...state.coefficient !== void 0 ? { coefficient: state.coefficient } : {},
|
|
4967
|
+
...state.minSamples !== void 0 ? { minSamples: state.minSamples } : {},
|
|
4968
|
+
...state.minCoefficient !== void 0 ? { minCoefficient: state.minCoefficient } : {},
|
|
4969
|
+
...state.maxCoefficient !== void 0 ? { maxCoefficient: state.maxCoefficient } : {},
|
|
4970
|
+
localEstimateTokens,
|
|
4971
|
+
calibratedEstimateTokens,
|
|
4972
|
+
deltaTokens: calibratedEstimateTokens - localEstimateTokens,
|
|
4973
|
+
...state.sampleLedgerEntryIds && state.sampleLedgerEntryIds.length > 0 ? { sampleLedgerEntryIds: state.sampleLedgerEntryIds } : {}
|
|
4974
|
+
}
|
|
4975
|
+
};
|
|
4976
|
+
}
|
|
4977
|
+
function clampCoefficient(value, min, max) {
|
|
4978
|
+
return Math.min(Math.max(value, min), max);
|
|
4979
|
+
}
|
|
4980
|
+
function routeEquals(left, right) {
|
|
4981
|
+
return left.providerId === right.providerId && left.baseURL === right.baseURL && left.modelId === right.modelId && left.providerModelId === right.providerModelId;
|
|
4982
|
+
}
|
|
4983
|
+
function collectLedgerEntryIds(samples) {
|
|
4984
|
+
return samples.map((sample) => sample.ledgerEntryId).filter((id) => id !== void 0);
|
|
4985
|
+
}
|
|
4986
|
+
|
|
4671
4987
|
// src/context-manager/shared/context-manager-base.ts
|
|
4672
4988
|
var ContextManagerBase = class {
|
|
4673
4989
|
config;
|
|
@@ -4676,6 +4992,10 @@ var ContextManagerBase = class {
|
|
|
4676
4992
|
logger;
|
|
4677
4993
|
tokenizer;
|
|
4678
4994
|
tokenizerModelId;
|
|
4995
|
+
tokenCounter;
|
|
4996
|
+
tokenRoute;
|
|
4997
|
+
remoteCountPolicy;
|
|
4998
|
+
tokenCalibrationState;
|
|
4679
4999
|
validateConfigFn;
|
|
4680
5000
|
invalidConfigMessage;
|
|
4681
5001
|
hasCustomTokenizer;
|
|
@@ -4689,6 +5009,10 @@ var ContextManagerBase = class {
|
|
|
4689
5009
|
this.hasCustomTokenizer = options.tokenizer !== void 0;
|
|
4690
5010
|
this.tokenizer = options.tokenizer ?? this.createDefaultTokenizer();
|
|
4691
5011
|
this.tokenizerModelId = options.tokenizerModelId;
|
|
5012
|
+
this.tokenCounter = options.tokenCounter;
|
|
5013
|
+
this.tokenRoute = options.tokenRoute;
|
|
5014
|
+
this.remoteCountPolicy = options.remoteCount;
|
|
5015
|
+
this.tokenCalibrationState = buildTokenUsageCalibrationState(options.tokenCalibration ?? {});
|
|
4692
5016
|
if (!this.validateConfigFn(this.config)) {
|
|
4693
5017
|
throw new Error(this.invalidConfigMessage);
|
|
4694
5018
|
}
|
|
@@ -4701,7 +5025,85 @@ var ContextManagerBase = class {
|
|
|
4701
5025
|
});
|
|
4702
5026
|
}
|
|
4703
5027
|
estimateTokens(message) {
|
|
4704
|
-
|
|
5028
|
+
const localEstimateTokens = this.tokenizer.estimateMessage(message, this.tokenizerModelId);
|
|
5029
|
+
return calibrateTokenEstimate({
|
|
5030
|
+
localEstimateTokens,
|
|
5031
|
+
state: this.tokenCalibrationState
|
|
5032
|
+
}).tokens;
|
|
5033
|
+
}
|
|
5034
|
+
estimateTokensWithCalibrationTrace(message) {
|
|
5035
|
+
const localEstimateTokens = this.tokenizer.estimateMessage(message, this.tokenizerModelId);
|
|
5036
|
+
const calibrated = calibrateTokenEstimate({
|
|
5037
|
+
localEstimateTokens,
|
|
5038
|
+
state: this.tokenCalibrationState
|
|
5039
|
+
});
|
|
5040
|
+
return {
|
|
5041
|
+
tokens: calibrated.tokens,
|
|
5042
|
+
calibrationTrace: calibrated.trace
|
|
5043
|
+
};
|
|
5044
|
+
}
|
|
5045
|
+
getTokenCalibrationTrace() {
|
|
5046
|
+
return calibrateTokenEstimate({
|
|
5047
|
+
localEstimateTokens: 0,
|
|
5048
|
+
state: this.tokenCalibrationState
|
|
5049
|
+
}).trace;
|
|
5050
|
+
}
|
|
5051
|
+
getTokenRoute() {
|
|
5052
|
+
return this.tokenRoute ?? this.tokenCalibrationState.route;
|
|
5053
|
+
}
|
|
5054
|
+
estimateLocalTokens(messages) {
|
|
5055
|
+
return messages.reduce(
|
|
5056
|
+
(total, message) => total + this.tokenizer.estimateMessage(message, this.tokenizerModelId),
|
|
5057
|
+
0
|
|
5058
|
+
);
|
|
5059
|
+
}
|
|
5060
|
+
async countMessagesWithRemoteCounter(input) {
|
|
5061
|
+
const failureBehavior = this.remoteCountPolicy?.failureBehavior ?? "use-local-estimate";
|
|
5062
|
+
const baseTrace = {
|
|
5063
|
+
enabled: this.remoteCountPolicy?.enabled === true,
|
|
5064
|
+
attempted: false,
|
|
5065
|
+
applied: false,
|
|
5066
|
+
...this.tokenRoute ? { route: this.tokenRoute } : {},
|
|
5067
|
+
localEstimateTokens: input.localEstimateTokens,
|
|
5068
|
+
failureBehavior
|
|
5069
|
+
};
|
|
5070
|
+
if (this.remoteCountPolicy?.enabled !== true || !this.tokenCounter || !this.tokenRoute || this.tokenRoute.capabilities?.supportsRemoteTokenCount !== true) {
|
|
5071
|
+
return {
|
|
5072
|
+
tokens: input.localEstimateTokens,
|
|
5073
|
+
trace: baseTrace
|
|
5074
|
+
};
|
|
5075
|
+
}
|
|
5076
|
+
try {
|
|
5077
|
+
const result = await this.tokenCounter.countMessages({
|
|
5078
|
+
route: this.tokenRoute,
|
|
5079
|
+
messages: [...input.messages],
|
|
5080
|
+
...input.signal ? { signal: input.signal } : {}
|
|
5081
|
+
});
|
|
5082
|
+
return {
|
|
5083
|
+
tokens: result.inputTokens,
|
|
5084
|
+
trace: {
|
|
5085
|
+
...baseTrace,
|
|
5086
|
+
attempted: true,
|
|
5087
|
+
applied: true,
|
|
5088
|
+
inputTokens: result.inputTokens,
|
|
5089
|
+
deltaTokens: result.inputTokens - input.localEstimateTokens,
|
|
5090
|
+
source: result.source,
|
|
5091
|
+
confidence: result.confidence
|
|
5092
|
+
}
|
|
5093
|
+
};
|
|
5094
|
+
} catch (error) {
|
|
5095
|
+
if (failureBehavior === "fail-fast") {
|
|
5096
|
+
throw error;
|
|
5097
|
+
}
|
|
5098
|
+
return {
|
|
5099
|
+
tokens: input.localEstimateTokens,
|
|
5100
|
+
trace: {
|
|
5101
|
+
...baseTrace,
|
|
5102
|
+
attempted: true,
|
|
5103
|
+
failureReason: error instanceof Error ? error.message : String(error)
|
|
5104
|
+
}
|
|
5105
|
+
};
|
|
5106
|
+
}
|
|
4705
5107
|
}
|
|
4706
5108
|
debug(message, data) {
|
|
4707
5109
|
if (this.debugMode) {
|
|
@@ -4715,7 +5117,13 @@ var ContextManagerBase = class {
|
|
|
4715
5117
|
buildStats: options.buildStats,
|
|
4716
5118
|
providerRegistry: this.providerRegistry,
|
|
4717
5119
|
providerContext: options.providerContext,
|
|
4718
|
-
estimateTokens: (message) =>
|
|
5120
|
+
estimateTokens: (message) => {
|
|
5121
|
+
const estimate = this.estimateTokensWithCalibrationTrace(message);
|
|
5122
|
+
return {
|
|
5123
|
+
tokens: estimate.tokens,
|
|
5124
|
+
tokenCalibration: estimate.calibrationTrace
|
|
5125
|
+
};
|
|
5126
|
+
},
|
|
4719
5127
|
getPhaseByProviderName: options.getPhaseByProviderName,
|
|
4720
5128
|
debug: (message, data) => this.debug(message, data),
|
|
4721
5129
|
contextTrace: options.contextTrace
|
|
@@ -4742,6 +5150,9 @@ var ContextManagerBase = class {
|
|
|
4742
5150
|
updateTokenizerModelId(modelId) {
|
|
4743
5151
|
this.tokenizerModelId = modelId;
|
|
4744
5152
|
}
|
|
5153
|
+
updateTokenCalibration(input) {
|
|
5154
|
+
this.tokenCalibrationState = buildTokenUsageCalibrationState(input ?? {});
|
|
5155
|
+
}
|
|
4745
5156
|
};
|
|
4746
5157
|
|
|
4747
5158
|
// src/context-manager/shared/context-result.ts
|
|
@@ -4758,7 +5169,9 @@ function buildContextResult(options) {
|
|
|
4758
5169
|
coreTypes,
|
|
4759
5170
|
recommendations,
|
|
4760
5171
|
events = [],
|
|
4761
|
-
contextTrace
|
|
5172
|
+
contextTrace,
|
|
5173
|
+
tokenEstimate,
|
|
5174
|
+
tokenComponents
|
|
4762
5175
|
} = options;
|
|
4763
5176
|
const tokenDistribution = calculateTokenDistribution(
|
|
4764
5177
|
finalMessages,
|
|
@@ -4785,7 +5198,9 @@ function buildContextResult(options) {
|
|
|
4785
5198
|
recommendations
|
|
4786
5199
|
},
|
|
4787
5200
|
events,
|
|
4788
|
-
...contextTrace ? { contextTrace } : {}
|
|
5201
|
+
...contextTrace ? { contextTrace } : {},
|
|
5202
|
+
...tokenEstimate ? { tokenEstimate } : {},
|
|
5203
|
+
...tokenComponents ? { tokenComponents } : {}
|
|
4789
5204
|
};
|
|
4790
5205
|
}
|
|
4791
5206
|
function generateContextRecommendations(stats, options) {
|
|
@@ -4829,6 +5244,70 @@ function calculateTokenDistribution(finalMessages, estimateTokens, coreTypes) {
|
|
|
4829
5244
|
return tokenDistribution;
|
|
4830
5245
|
}
|
|
4831
5246
|
|
|
5247
|
+
// src/context-manager/shared/context-token-components.ts
|
|
5248
|
+
function isKept(action) {
|
|
5249
|
+
return action.startsWith("keep_");
|
|
5250
|
+
}
|
|
5251
|
+
function classifyMessage(message) {
|
|
5252
|
+
const metadata = message.metadata;
|
|
5253
|
+
if (metadata?.fenceKind) {
|
|
5254
|
+
return "fence";
|
|
5255
|
+
}
|
|
5256
|
+
if (message.type === "history_summary" || metadata?.messageType === "summary") {
|
|
5257
|
+
return "history-summary";
|
|
5258
|
+
}
|
|
5259
|
+
if (message.role === "tool" || message.type === "tool_output" || message.type === "tool_calls" || message.type === "tool_code") {
|
|
5260
|
+
return "tool";
|
|
5261
|
+
}
|
|
5262
|
+
if (message.type === "context_injection" || message.type === "context_before" || message.type === "context_after") {
|
|
5263
|
+
return "context-injection";
|
|
5264
|
+
}
|
|
5265
|
+
if (message.role === "system") {
|
|
5266
|
+
return "system";
|
|
5267
|
+
}
|
|
5268
|
+
if (message.role === "user") {
|
|
5269
|
+
return "user";
|
|
5270
|
+
}
|
|
5271
|
+
if (message.role === "assistant") {
|
|
5272
|
+
return "assistant";
|
|
5273
|
+
}
|
|
5274
|
+
return "other";
|
|
5275
|
+
}
|
|
5276
|
+
function buildLabel(message, metadata) {
|
|
5277
|
+
return metadata?.fenceKind ?? metadata?.tool_name ?? metadata?.messageType ?? message.type;
|
|
5278
|
+
}
|
|
5279
|
+
function buildTruncationFields(state) {
|
|
5280
|
+
const truncation = state.message.metadata?.observationTruncation;
|
|
5281
|
+
if (!truncation || truncation.originalChars <= truncation.previewChars || truncation.previewChars === 0) {
|
|
5282
|
+
return {};
|
|
5283
|
+
}
|
|
5284
|
+
const originalTokensEstimate = Math.max(
|
|
5285
|
+
state.tokens,
|
|
5286
|
+
Math.ceil(state.tokens * truncation.originalChars / truncation.previewChars)
|
|
5287
|
+
);
|
|
5288
|
+
const droppedTokensEstimate = Math.max(0, originalTokensEstimate - state.tokens);
|
|
5289
|
+
return {
|
|
5290
|
+
truncatedAtExecution: true,
|
|
5291
|
+
originalTokensEstimate,
|
|
5292
|
+
droppedTokensEstimate
|
|
5293
|
+
};
|
|
5294
|
+
}
|
|
5295
|
+
function buildContextTokenComponents(states) {
|
|
5296
|
+
return states.map((state) => ({
|
|
5297
|
+
componentId: `${state.originalIndex}:${state.message.id}`,
|
|
5298
|
+
kind: classifyMessage(state.message),
|
|
5299
|
+
tokens: state.tokens,
|
|
5300
|
+
source: "local-estimate",
|
|
5301
|
+
confidence: "estimate",
|
|
5302
|
+
label: buildLabel(state.message, state.message.metadata),
|
|
5303
|
+
messageId: state.message.id,
|
|
5304
|
+
role: state.message.role,
|
|
5305
|
+
action: state.action,
|
|
5306
|
+
kept: isKept(state.action),
|
|
5307
|
+
...buildTruncationFields(state)
|
|
5308
|
+
}));
|
|
5309
|
+
}
|
|
5310
|
+
|
|
4832
5311
|
// src/context-manager/profiles/agent/context/AgentContextManager.ts
|
|
4833
5312
|
var AgentContextManager = class extends ContextManagerBase {
|
|
4834
5313
|
constructor(options = {}) {
|
|
@@ -4865,6 +5344,13 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4865
5344
|
config: this.config,
|
|
4866
5345
|
debugMode: this.debugMode,
|
|
4867
5346
|
estimateTokens: (msg) => this.estimateTokens(msg),
|
|
5347
|
+
estimateTokensWithTrace: (msg) => {
|
|
5348
|
+
const estimate = this.estimateTokensWithCalibrationTrace(msg);
|
|
5349
|
+
return {
|
|
5350
|
+
tokens: estimate.tokens,
|
|
5351
|
+
tokenCalibration: estimate.calibrationTrace
|
|
5352
|
+
};
|
|
5353
|
+
},
|
|
4868
5354
|
summarizationCallbacks: callbacks,
|
|
4869
5355
|
generate,
|
|
4870
5356
|
agentRequest: request
|
|
@@ -4873,9 +5359,10 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4873
5359
|
policy: traceOptions?.policy,
|
|
4874
5360
|
effectivePolicy: traceOptions?.effectiveContextPolicy,
|
|
4875
5361
|
totalBudget,
|
|
4876
|
-
originalCount: preprocessedMessages.length
|
|
5362
|
+
originalCount: preprocessedMessages.length,
|
|
5363
|
+
tokenCalibration: this.getTokenCalibrationTrace()
|
|
4877
5364
|
});
|
|
4878
|
-
const { finalMessages, finalTokens, strategiesApplied, events } = await this.runPipeline({
|
|
5365
|
+
const { finalMessages, finalTokens, strategiesApplied, events, states } = await this.runPipeline({
|
|
4879
5366
|
messages: preprocessedMessages,
|
|
4880
5367
|
totalBudget,
|
|
4881
5368
|
buildStats,
|
|
@@ -4883,6 +5370,14 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4883
5370
|
getPhaseByProviderName: (providerName) => this.getPhaseByProviderName(providerName),
|
|
4884
5371
|
contextTrace
|
|
4885
5372
|
});
|
|
5373
|
+
const remoteCount = await this.countMessagesWithRemoteCounter({
|
|
5374
|
+
messages: finalMessages,
|
|
5375
|
+
localEstimateTokens: finalTokens
|
|
5376
|
+
});
|
|
5377
|
+
contextTrace?.recordRemoteTokenCount(remoteCount.trace);
|
|
5378
|
+
const tokenComponents = buildContextTokenComponents(states);
|
|
5379
|
+
contextTrace?.recordTokenComponents(tokenComponents);
|
|
5380
|
+
const tokenEstimate = this.buildContextTokenEstimate(finalMessages, finalTokens);
|
|
4886
5381
|
const endTime = performance.now();
|
|
4887
5382
|
buildStats.totalTime = endTime - startTime;
|
|
4888
5383
|
const summarizationThreshold2 = this.config.SUMMARIZATION_TRIGGER_THRESHOLD;
|
|
@@ -4890,22 +5385,24 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4890
5385
|
this.debug("\u2705 [Agent\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5B8C\u6210", {
|
|
4891
5386
|
\u9884\u5904\u7406\u6D88\u606F: preprocessedMessages.length,
|
|
4892
5387
|
\u6700\u7EC8\u6D88\u606F: finalMessages.length,
|
|
4893
|
-
Token\u4F7F\u7528:
|
|
5388
|
+
Token\u4F7F\u7528: remoteCount.tokens,
|
|
4894
5389
|
\u603B\u9884\u7B97: totalBudget,
|
|
4895
|
-
\u4F7F\u7528\u7387: `${(
|
|
5390
|
+
\u4F7F\u7528\u7387: `${(remoteCount.tokens / totalBudget * 100).toFixed(1)}%`,
|
|
4896
5391
|
\u6458\u8981\u89E6\u53D1\u9608\u503C: `${(summarizationThreshold2 * 100).toFixed(0)}%`,
|
|
4897
5392
|
\u6458\u8981Token\u9608\u503C: summarizationTokenThreshold2,
|
|
4898
5393
|
\u603B\u8017\u65F6: `${buildStats.totalTime.toFixed(2)}ms`
|
|
4899
5394
|
});
|
|
4900
5395
|
return this.buildFinalResult(
|
|
4901
5396
|
finalMessages,
|
|
4902
|
-
|
|
5397
|
+
remoteCount.tokens,
|
|
4903
5398
|
totalBudget,
|
|
4904
5399
|
preprocessedMessages.length,
|
|
4905
5400
|
strategiesApplied,
|
|
4906
5401
|
buildStats,
|
|
4907
5402
|
events,
|
|
4908
|
-
contextTrace?.build(finalMessages, finalTokens)
|
|
5403
|
+
contextTrace?.build(finalMessages, finalTokens),
|
|
5404
|
+
tokenEstimate,
|
|
5405
|
+
tokenComponents
|
|
4909
5406
|
);
|
|
4910
5407
|
} catch (error) {
|
|
4911
5408
|
this.debug("\u274C [Agent\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5931\u8D25", { error });
|
|
@@ -4953,7 +5450,7 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4953
5450
|
totalTime: 0
|
|
4954
5451
|
};
|
|
4955
5452
|
}
|
|
4956
|
-
buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], contextTrace) {
|
|
5453
|
+
buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], contextTrace, tokenEstimate, tokenComponents) {
|
|
4957
5454
|
const recommendations = this.generateRecommendations(buildStats, totalBudget);
|
|
4958
5455
|
return buildContextResult({
|
|
4959
5456
|
finalMessages,
|
|
@@ -4967,9 +5464,21 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4967
5464
|
coreTypes: this.config.CORE_MESSAGE_TYPES,
|
|
4968
5465
|
recommendations,
|
|
4969
5466
|
events,
|
|
4970
|
-
contextTrace
|
|
5467
|
+
contextTrace,
|
|
5468
|
+
tokenEstimate,
|
|
5469
|
+
tokenComponents
|
|
4971
5470
|
});
|
|
4972
5471
|
}
|
|
5472
|
+
buildContextTokenEstimate(finalMessages, calibratedEstimateTokens) {
|
|
5473
|
+
return {
|
|
5474
|
+
...this.getTokenRoute() ? { route: this.getTokenRoute() } : {},
|
|
5475
|
+
localEstimateTokens: this.estimateLocalTokens(finalMessages),
|
|
5476
|
+
calibratedEstimateTokens,
|
|
5477
|
+
finalTokens: calibratedEstimateTokens,
|
|
5478
|
+
source: "local-estimate",
|
|
5479
|
+
confidence: "estimate"
|
|
5480
|
+
};
|
|
5481
|
+
}
|
|
4973
5482
|
/**
|
|
4974
5483
|
* 生成优化建议
|
|
4975
5484
|
*/
|
|
@@ -5933,10 +6442,10 @@ var contextBudgetWarningTemplate = (ctx) => {
|
|
|
5933
6442
|
return [
|
|
5934
6443
|
`\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`,
|
|
5935
6444
|
"\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
|
|
5936
|
-
"1. \
|
|
6445
|
+
"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",
|
|
5937
6446
|
`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`,
|
|
5938
6447
|
' \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',
|
|
5939
|
-
"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\
|
|
6448
|
+
"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"
|
|
5940
6449
|
].join("\n");
|
|
5941
6450
|
};
|
|
5942
6451
|
var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
|
|
@@ -6673,6 +7182,27 @@ createConsoleAudit();
|
|
|
6673
7182
|
function isRecord7(value) {
|
|
6674
7183
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
6675
7184
|
}
|
|
7185
|
+
function readObservationTruncationMeta(value) {
|
|
7186
|
+
if (!isRecord7(value)) {
|
|
7187
|
+
return void 0;
|
|
7188
|
+
}
|
|
7189
|
+
const originalChars = value["originalChars"];
|
|
7190
|
+
const previewChars = value["previewChars"];
|
|
7191
|
+
if (typeof originalChars !== "number" || !Number.isInteger(originalChars) || originalChars < 0) {
|
|
7192
|
+
return void 0;
|
|
7193
|
+
}
|
|
7194
|
+
if (typeof previewChars !== "number" || !Number.isInteger(previewChars) || previewChars < 0) {
|
|
7195
|
+
return void 0;
|
|
7196
|
+
}
|
|
7197
|
+
const originalLines = value["originalLines"];
|
|
7198
|
+
const previewLines = value["previewLines"];
|
|
7199
|
+
return {
|
|
7200
|
+
originalChars,
|
|
7201
|
+
previewChars,
|
|
7202
|
+
...typeof originalLines === "number" && Number.isInteger(originalLines) && originalLines >= 0 ? { originalLines } : {},
|
|
7203
|
+
...typeof previewLines === "number" && Number.isInteger(previewLines) && previewLines >= 0 ? { previewLines } : {}
|
|
7204
|
+
};
|
|
7205
|
+
}
|
|
6676
7206
|
function isHistorySummaryEvent2(event) {
|
|
6677
7207
|
return "type" in event && event.type === "history_summary";
|
|
6678
7208
|
}
|
|
@@ -6785,6 +7315,7 @@ function convertEventToAiMessage(event) {
|
|
|
6785
7315
|
}
|
|
6786
7316
|
})();
|
|
6787
7317
|
const outputContent = observationFromPayload ?? rawOutput;
|
|
7318
|
+
const observationTruncation = readObservationTruncationMeta(event.metadata?.observationTruncation);
|
|
6788
7319
|
return {
|
|
6789
7320
|
id: event.id,
|
|
6790
7321
|
role: "tool",
|
|
@@ -6795,6 +7326,7 @@ function convertEventToAiMessage(event) {
|
|
|
6795
7326
|
tool_call_id: event.tool_call_id,
|
|
6796
7327
|
tool_name: event.tool_name,
|
|
6797
7328
|
raw_output: rawOutput,
|
|
7329
|
+
...observationTruncation ? { observationTruncation } : {},
|
|
6798
7330
|
...observationFromPayload ? { observation: observationFromPayload } : {}
|
|
6799
7331
|
}
|
|
6800
7332
|
};
|
|
@@ -6905,7 +7437,8 @@ var AgentMessageOrchestrator = class {
|
|
|
6905
7437
|
customConfig: this.baseContextConfig,
|
|
6906
7438
|
providerRegistry: options.providerRegistry,
|
|
6907
7439
|
tokenizer: options.tokenizer,
|
|
6908
|
-
tokenizerModelId: options.model
|
|
7440
|
+
tokenizerModelId: options.model,
|
|
7441
|
+
tokenCounter: options.tokenCounter
|
|
6909
7442
|
});
|
|
6910
7443
|
}
|
|
6911
7444
|
buildPreprocessorPipelineForRequest(toolManager, request, contextPolicy) {
|
|
@@ -6934,12 +7467,31 @@ var AgentMessageOrchestrator = class {
|
|
|
6934
7467
|
contextPolicy,
|
|
6935
7468
|
contextBuilderConfig
|
|
6936
7469
|
}) ?? this.options.providerRegistry;
|
|
7470
|
+
const modelId = this.resolvePreprocessorModel(request);
|
|
7471
|
+
const tokenCalibration = this.options.resolveTokenCalibration?.({
|
|
7472
|
+
request,
|
|
7473
|
+
modelId,
|
|
7474
|
+
contextPolicy
|
|
7475
|
+
});
|
|
7476
|
+
const tokenRoute = this.options.resolveTokenRoute?.({
|
|
7477
|
+
request,
|
|
7478
|
+
modelId,
|
|
7479
|
+
contextPolicy
|
|
7480
|
+
}) ?? tokenCalibration?.route;
|
|
6937
7481
|
this.agentContextManager = new AgentContextManager({
|
|
6938
7482
|
debugMode: this.options.processing.debugMode,
|
|
6939
7483
|
customConfig: contextBuilderConfig,
|
|
6940
7484
|
providerRegistry,
|
|
6941
7485
|
tokenizer: this.options.tokenizer,
|
|
6942
|
-
tokenizerModelId:
|
|
7486
|
+
tokenizerModelId: modelId,
|
|
7487
|
+
tokenCounter: this.options.tokenCounter,
|
|
7488
|
+
tokenRoute,
|
|
7489
|
+
remoteCount: contextPolicy?.tokenEstimation?.remoteCount,
|
|
7490
|
+
tokenCalibration: {
|
|
7491
|
+
policy: contextPolicy?.tokenEstimation?.calibration,
|
|
7492
|
+
route: tokenCalibration?.route,
|
|
7493
|
+
samples: tokenCalibration?.samples
|
|
7494
|
+
}
|
|
6943
7495
|
});
|
|
6944
7496
|
return contextBuilderConfig;
|
|
6945
7497
|
}
|
|
@@ -7864,6 +8416,7 @@ var ContextManager = class extends ContextManagerBase {
|
|
|
7864
8416
|
providerContext,
|
|
7865
8417
|
getPhaseByProviderName: (providerName) => this.getPhaseByProviderName(providerName)
|
|
7866
8418
|
});
|
|
8419
|
+
const tokenEstimate = this.buildContextTokenEstimate(finalMessages, finalTokens);
|
|
7867
8420
|
const endTime = performance.now();
|
|
7868
8421
|
buildStats.totalTime = endTime - startTime;
|
|
7869
8422
|
const summarizationThreshold2 = this.config.SUMMARIZATION_TRIGGER_THRESHOLD;
|
|
@@ -7885,8 +8438,9 @@ var ContextManager = class extends ContextManagerBase {
|
|
|
7885
8438
|
messages.length,
|
|
7886
8439
|
strategiesApplied,
|
|
7887
8440
|
buildStats,
|
|
7888
|
-
events
|
|
8441
|
+
events,
|
|
7889
8442
|
// 🔥 传递收集的事件
|
|
8443
|
+
tokenEstimate
|
|
7890
8444
|
);
|
|
7891
8445
|
} catch (error) {
|
|
7892
8446
|
this.debug("\u274C [Chat\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5931\u8D25", { error });
|
|
@@ -7922,7 +8476,7 @@ var ContextManager = class extends ContextManagerBase {
|
|
|
7922
8476
|
totalTime: 0
|
|
7923
8477
|
};
|
|
7924
8478
|
}
|
|
7925
|
-
buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = []) {
|
|
8479
|
+
buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], tokenEstimate) {
|
|
7926
8480
|
const recommendations = this.generateRecommendations(buildStats, totalBudget);
|
|
7927
8481
|
return buildContextResult({
|
|
7928
8482
|
finalMessages,
|
|
@@ -7935,9 +8489,19 @@ var ContextManager = class extends ContextManagerBase {
|
|
|
7935
8489
|
estimateTokens: (message) => this.estimateTokens(message),
|
|
7936
8490
|
coreTypes: this.config.CORE_MESSAGE_TYPES,
|
|
7937
8491
|
recommendations,
|
|
7938
|
-
events
|
|
8492
|
+
events,
|
|
8493
|
+
tokenEstimate
|
|
7939
8494
|
});
|
|
7940
8495
|
}
|
|
8496
|
+
buildContextTokenEstimate(finalMessages, calibratedEstimateTokens) {
|
|
8497
|
+
return {
|
|
8498
|
+
localEstimateTokens: this.estimateLocalTokens(finalMessages),
|
|
8499
|
+
calibratedEstimateTokens,
|
|
8500
|
+
finalTokens: calibratedEstimateTokens,
|
|
8501
|
+
source: "local-estimate",
|
|
8502
|
+
confidence: "estimate"
|
|
8503
|
+
};
|
|
8504
|
+
}
|
|
7941
8505
|
/**
|
|
7942
8506
|
* 生成优化建议
|
|
7943
8507
|
*/
|