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