@linnlabs/linnkit 0.9.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +168 -0
- package/bin/linnkit.cjs +7 -0
- package/dist/{agent-invocation-BHcNfrBV.d.cts → agent-invocation-CAlm9qOw.d.cts} +1 -1
- package/dist/{agent-invocation-BznDaXDs.d.ts → agent-invocation-DKoEDLkl.d.ts} +1 -1
- package/dist/{ai-engine.types-vZRnQcJa.d.ts → ai-engine.types-CeLoM624.d.cts} +9 -1
- package/dist/{ai-engine.types-BpeU_XQG.d.cts → ai-engine.types-LqmnfR2W.d.ts} +9 -1
- package/dist/{audit-CtcfART1.d.ts → audit-BuWHoMEr.d.ts} +4 -2
- package/dist/{audit-LeOrm2hX.d.cts → audit-DnzNQzwq.d.cts} +4 -2
- package/dist/cli.cjs +682 -258
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +682 -258
- package/dist/cli.js.map +1 -1
- package/dist/context-manager.cjs +823 -57
- package/dist/context-manager.cjs.map +1 -1
- package/dist/context-manager.d.cts +132 -18
- package/dist/context-manager.d.ts +132 -18
- package/dist/context-manager.js +823 -58
- package/dist/context-manager.js.map +1 -1
- package/dist/{context-trace-HE2qY5Q-.d.cts → context-trace-DrtvKac4.d.cts} +37 -4
- package/dist/{context-trace-DRi5M4lX.d.ts → context-trace-WV1HAZeB.d.ts} +37 -4
- package/dist/contracts.cjs +225 -2
- package/dist/contracts.cjs.map +1 -1
- package/dist/contracts.d.cts +6 -4
- package/dist/contracts.d.ts +6 -4
- package/dist/contracts.js +205 -3
- package/dist/contracts.js.map +1 -1
- package/dist/{defaultGraphExecutor-BIjJj7WF.d.cts → defaultGraphExecutor-L1ri3oij.d.cts} +48 -19
- package/dist/{defaultGraphExecutor-BBswR8wn.d.ts → defaultGraphExecutor-QzzdudLQ.d.ts} +48 -19
- package/dist/{index-BanRABEt.d.cts → index-BeQO0rx2.d.cts} +345 -268
- package/dist/{index-Cvr23YCl.d.cts → index-CDofGr_4.d.ts} +24 -6
- package/dist/{index-Dl5PLgAv.d.cts → index-Crl5E4eF.d.cts} +27 -4
- package/dist/{index-CJeWHopy.d.ts → index-DWGKvssS.d.ts} +3 -3
- package/dist/{index-CHqwkvGp.d.ts → index-X5lYU1Lj.d.ts} +27 -4
- package/dist/{index-DDzuSb0n.d.ts → index-uCNCpJBg.d.cts} +24 -6
- package/dist/{index-Z8NXKNwI.d.ts → index-wOZD-p2-.d.ts} +345 -268
- package/dist/{index-DO4dQgf2.d.cts → index-wXVAHZ0D.d.cts} +3 -3
- package/dist/index.cjs +1011 -329
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -16
- package/dist/index.d.ts +19 -16
- package/dist/index.js +1011 -329
- package/dist/index.js.map +1 -1
- package/dist/{messages-XthmnHZ3.d.cts → messages-Br5SiLD3.d.cts} +706 -1
- package/dist/{messages-XthmnHZ3.d.ts → messages-Br5SiLD3.d.ts} +706 -1
- package/dist/{ports-DnLuKfpE.d.ts → ports-Dugizzje.d.cts} +6 -2
- package/dist/{ports-DaatKJXp.d.cts → ports-fhp84x_C.d.ts} +6 -2
- package/dist/ports.d.cts +8 -5
- package/dist/ports.d.ts +8 -5
- package/dist/quickstart.cjs +683 -258
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.d.cts +11 -10
- package/dist/quickstart.d.ts +11 -10
- package/dist/quickstart.js +683 -258
- package/dist/quickstart.js.map +1 -1
- package/dist/{runAgent-CPj_9e58.d.ts → runAgent-BmMSju8I.d.ts} +6 -6
- package/dist/{runAgent-HYKlXbVr.d.cts → runAgent-CKgcRSRH.d.cts} +6 -6
- package/dist/{runHandle-D3gPsD7B.d.cts → runHandle-DH4VmQx6.d.cts} +6 -4
- package/dist/{runHandle-CyXvzgzk.d.ts → runHandle-o3p06Nva.d.ts} +6 -4
- package/dist/runtime-kernel/events.cjs +202 -1
- package/dist/runtime-kernel/events.cjs.map +1 -1
- package/dist/runtime-kernel/events.d.cts +5 -5
- package/dist/runtime-kernel/events.d.ts +5 -5
- package/dist/runtime-kernel/events.js +202 -1
- package/dist/runtime-kernel/events.js.map +1 -1
- package/dist/runtime-kernel.cjs +999 -340
- package/dist/runtime-kernel.cjs.map +1 -1
- package/dist/runtime-kernel.d.cts +16 -14
- package/dist/runtime-kernel.d.ts +16 -14
- package/dist/runtime-kernel.js +990 -341
- package/dist/runtime-kernel.js.map +1 -1
- package/dist/testkit.cjs +1003 -321
- package/dist/testkit.cjs.map +1 -1
- package/dist/testkit.d.cts +16 -14
- package/dist/testkit.d.ts +16 -14
- package/dist/testkit.js +1003 -321
- package/dist/testkit.js.map +1 -1
- package/dist/{todo-B1PmDlp3.d.cts → todo-Ca8llpRQ.d.cts} +1 -1
- package/dist/{todo-B1PmDlp3.d.ts → todo-Ca8llpRQ.d.ts} +1 -1
- package/dist/{agentSpec-EkmviZjy.d.cts → token-accounting-CwpSPg4y.d.cts} +1280 -1
- package/dist/{agentSpec-EkmviZjy.d.ts → token-accounting-CwpSPg4y.d.ts} +1280 -1
- package/dist/token-calibration-Cxv6dDYF.d.cts +327 -0
- package/dist/token-calibration-Cxv6dDYF.d.ts +327 -0
- package/dist/token-counter-CFfP8PQb.d.cts +26 -0
- package/dist/token-counter-SFyyTeaG.d.ts +26 -0
- package/dist/token-usage-CqwT7-5K.d.cts +133 -0
- package/dist/token-usage-CqwT7-5K.d.ts +133 -0
- package/dist/{tokenizer-DFL4I7-I.d.ts → tokenizer-BFJNCHFX.d.ts} +1 -1
- package/dist/{tokenizer-DH_JXv-H.d.cts → tokenizer-DoGsBE3A.d.cts} +1 -1
- package/dist/{toolContracts-CLkQmhTG.d.cts → toolContracts-Bm3EZ1UM.d.cts} +13 -2
- package/dist/{toolContracts-Blll0241.d.ts → toolContracts-f8lzZBNa.d.ts} +13 -2
- package/docs/README.md +1 -1
- package/docs/integration/README.md +3 -3
- package/docs/integration/agent-registration-guide.md +3 -1
- package/docs/integration/child-runs.md +4 -1
- package/docs/integration/context-engineering.md +83 -16
- package/docs/integration/context-fences.md +44 -3
- package/docs/integration/llm-provider.md +1 -1
- package/docs/integration/persistence.md +1 -0
- package/docs/integration/run-supervisor.md +3 -0
- package/docs/integration/tool-development-guide.md +7 -5
- package/docs/integration/tool-history.md +43 -17
- package/package.json +4 -3
package/dist/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(),
|
|
@@ -499,6 +506,7 @@ var AgentSpecBudgetPolicy = zod.z.object({
|
|
|
499
506
|
});
|
|
500
507
|
var AgentSpecToolHistoryPolicy = zod.z.object({
|
|
501
508
|
strategy: zod.z.enum(["per-pair", "per-run", "none"]).optional(),
|
|
509
|
+
retentionMode: zod.z.enum(["drop", "compress"]).optional(),
|
|
502
510
|
keepLatestToolPairs: zod.z.number().int().nonnegative().optional(),
|
|
503
511
|
keepLatestRuns: zod.z.number().int().nonnegative().optional(),
|
|
504
512
|
maxInteractionGroups: zod.z.number().int().nonnegative().optional(),
|
|
@@ -551,7 +559,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
|
|
|
551
559
|
var AgentSpecTokenEstimationPolicy = zod.z.object({
|
|
552
560
|
encoding: zod.z.string().min(1).optional(),
|
|
553
561
|
avgCharsPerToken: zod.z.number().positive().optional(),
|
|
554
|
-
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()
|
|
555
573
|
});
|
|
556
574
|
var AgentSpecSystemReminderTrigger = zod.z.object({
|
|
557
575
|
kind: zod.z.string().min(1),
|
|
@@ -613,12 +631,13 @@ var AgentSpecContextPolicy = zod.z.object({
|
|
|
613
631
|
var DEFAULT_CONTEXT_POLICY = {
|
|
614
632
|
profileId: "agent",
|
|
615
633
|
budget: {
|
|
616
|
-
maxTokens:
|
|
634
|
+
maxTokens: 232e3,
|
|
617
635
|
reservedForResponse: 2400,
|
|
618
636
|
workingMemoryBudgetPercentage: 0.7
|
|
619
637
|
},
|
|
620
638
|
toolHistory: {
|
|
621
639
|
strategy: "per-run",
|
|
640
|
+
retentionMode: "drop",
|
|
622
641
|
keepLatestToolPairs: 2,
|
|
623
642
|
keepLatestRuns: 1,
|
|
624
643
|
maxInteractionGroups: 12,
|
|
@@ -1325,6 +1344,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
|
|
|
1325
1344
|
error,
|
|
1326
1345
|
...options
|
|
1327
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
|
+
});
|
|
1328
1530
|
|
|
1329
1531
|
// src/context-manager/shared/contextPolicyMerge.ts
|
|
1330
1532
|
function mergeContextPolicy(params) {
|
|
@@ -1356,7 +1558,7 @@ function mergePolicyLayer(base, override) {
|
|
|
1356
1558
|
workingMemory: mergeObject(base.workingMemory, override.workingMemory),
|
|
1357
1559
|
checkpoint: mergeObject(base.checkpoint, override.checkpoint),
|
|
1358
1560
|
reasoningRetention: mergeObject(base.reasoningRetention, override.reasoningRetention),
|
|
1359
|
-
tokenEstimation:
|
|
1561
|
+
tokenEstimation: mergeTokenEstimation(base.tokenEstimation, override.tokenEstimation),
|
|
1360
1562
|
systemReminder: mergeSystemReminder(base.systemReminder, override.systemReminder),
|
|
1361
1563
|
contextTrace: mergeObject(base.contextTrace, override.contextTrace)
|
|
1362
1564
|
};
|
|
@@ -1391,6 +1593,17 @@ function mergeToolOutput(base, override) {
|
|
|
1391
1593
|
observationGovernance: mergeObject(base?.observationGovernance, override?.observationGovernance)
|
|
1392
1594
|
};
|
|
1393
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
|
+
}
|
|
1394
1607
|
|
|
1395
1608
|
// src/context-manager/shared/context-trace.ts
|
|
1396
1609
|
var ContextTraceCollector = class _ContextTraceCollector {
|
|
@@ -1400,6 +1613,9 @@ var ContextTraceCollector = class _ContextTraceCollector {
|
|
|
1400
1613
|
effectivePolicy;
|
|
1401
1614
|
totalBudget;
|
|
1402
1615
|
originalCount;
|
|
1616
|
+
tokenCalibration;
|
|
1617
|
+
remoteTokenCount;
|
|
1618
|
+
tokenComponents;
|
|
1403
1619
|
events = [];
|
|
1404
1620
|
overflowed = false;
|
|
1405
1621
|
constructor(options) {
|
|
@@ -1409,6 +1625,8 @@ var ContextTraceCollector = class _ContextTraceCollector {
|
|
|
1409
1625
|
this.effectivePolicy = options.effectivePolicy;
|
|
1410
1626
|
this.totalBudget = options.totalBudget;
|
|
1411
1627
|
this.originalCount = options.originalCount;
|
|
1628
|
+
this.tokenCalibration = options.tokenCalibration;
|
|
1629
|
+
this.remoteTokenCount = options.remoteTokenCount;
|
|
1412
1630
|
}
|
|
1413
1631
|
static create(options) {
|
|
1414
1632
|
if (options.policy?.enabled !== true) {
|
|
@@ -1448,10 +1666,20 @@ var ContextTraceCollector = class _ContextTraceCollector {
|
|
|
1448
1666
|
tokens: this.includeTokenBreakdown ? state.tokens : 0,
|
|
1449
1667
|
kept,
|
|
1450
1668
|
reason: buildDecisionReason(state, kept),
|
|
1451
|
-
...state.replacementSourceIds ? { replacementSourceIds: [...state.replacementSourceIds] } : {}
|
|
1669
|
+
...state.replacementSourceIds ? { replacementSourceIds: [...state.replacementSourceIds] } : {},
|
|
1670
|
+
...this.includeTokenBreakdown && state.tokenCalibration ? { tokenCalibration: state.tokenCalibration } : {}
|
|
1452
1671
|
});
|
|
1453
1672
|
}
|
|
1454
1673
|
}
|
|
1674
|
+
recordRemoteTokenCount(trace) {
|
|
1675
|
+
this.remoteTokenCount = trace;
|
|
1676
|
+
}
|
|
1677
|
+
recordTokenComponents(components) {
|
|
1678
|
+
if (!this.includeTokenBreakdown) {
|
|
1679
|
+
return;
|
|
1680
|
+
}
|
|
1681
|
+
this.tokenComponents = [...components];
|
|
1682
|
+
}
|
|
1455
1683
|
build(finalMessages, finalTokens) {
|
|
1456
1684
|
return {
|
|
1457
1685
|
enabled: true,
|
|
@@ -1464,6 +1692,9 @@ var ContextTraceCollector = class _ContextTraceCollector {
|
|
|
1464
1692
|
originalCount: this.originalCount,
|
|
1465
1693
|
finalCount: finalMessages.length,
|
|
1466
1694
|
finalTokens,
|
|
1695
|
+
...this.tokenCalibration ? { tokenCalibration: this.tokenCalibration } : {},
|
|
1696
|
+
...this.remoteTokenCount ? { remoteTokenCount: this.remoteTokenCount } : {},
|
|
1697
|
+
...this.tokenComponents ? { tokenComponents: [...this.tokenComponents] } : {},
|
|
1467
1698
|
truncated: this.originalCount !== finalMessages.length,
|
|
1468
1699
|
events: [...this.events]
|
|
1469
1700
|
};
|
|
@@ -1774,6 +2005,161 @@ function findLastIndex(items, predicate) {
|
|
|
1774
2005
|
return -1;
|
|
1775
2006
|
}
|
|
1776
2007
|
|
|
2008
|
+
// src/context-manager/shared/preprocessors/currentTurnMessageAssembler.ts
|
|
2009
|
+
var CurrentTurnMessageAssembler = class extends BasePreprocessor {
|
|
2010
|
+
name = "CurrentTurnMessageAssembler";
|
|
2011
|
+
description = "Assembles current-turn fences into system_prompt and user_input messages";
|
|
2012
|
+
priority = 10;
|
|
2013
|
+
fenceRegistry;
|
|
2014
|
+
constructor(options) {
|
|
2015
|
+
super();
|
|
2016
|
+
this.fenceRegistry = options.fenceRegistry;
|
|
2017
|
+
}
|
|
2018
|
+
async process(messages, _context) {
|
|
2019
|
+
const systemResult = assembleSystemPrompt({ messages, fenceRegistry: this.fenceRegistry });
|
|
2020
|
+
const userResult = assembleCurrentUserInput({
|
|
2021
|
+
messages: systemResult.messages,
|
|
2022
|
+
fenceRegistry: this.fenceRegistry
|
|
2023
|
+
});
|
|
2024
|
+
const modifiedCount = systemResult.modifiedCount + userResult.modifiedCount;
|
|
2025
|
+
return this.createResult(
|
|
2026
|
+
messages,
|
|
2027
|
+
userResult.messages,
|
|
2028
|
+
modifiedCount > 0 ? ["current_turn_message_assembly"] : [],
|
|
2029
|
+
modifiedCount
|
|
2030
|
+
);
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
function assembleSystemPrompt(params) {
|
|
2034
|
+
const systemIndex = params.messages.findIndex(
|
|
2035
|
+
(message) => message.role === "system" && message.type === "system_prompt"
|
|
2036
|
+
);
|
|
2037
|
+
if (systemIndex === -1) {
|
|
2038
|
+
return { messages: [...params.messages], modifiedCount: 0 };
|
|
2039
|
+
}
|
|
2040
|
+
const fences = collectAdjacentFences({
|
|
2041
|
+
messages: params.messages,
|
|
2042
|
+
startIndex: systemIndex + 1,
|
|
2043
|
+
direction: 1,
|
|
2044
|
+
fenceRegistry: params.fenceRegistry,
|
|
2045
|
+
matches: (descriptor) => descriptor.llmRole === "system" && descriptor.placement === "after-system"
|
|
2046
|
+
});
|
|
2047
|
+
if (fences.length === 0) {
|
|
2048
|
+
return { messages: [...params.messages], modifiedCount: 0 };
|
|
2049
|
+
}
|
|
2050
|
+
const indexesToRemove = new Set(fences.map((fence) => fence.index));
|
|
2051
|
+
const systemPrompt = params.messages[systemIndex];
|
|
2052
|
+
const assembledSystemPrompt = {
|
|
2053
|
+
...systemPrompt,
|
|
2054
|
+
content: [
|
|
2055
|
+
systemPrompt.content,
|
|
2056
|
+
...fences.map(formatFence)
|
|
2057
|
+
].join("\n\n"),
|
|
2058
|
+
metadata: {
|
|
2059
|
+
...systemPrompt.metadata,
|
|
2060
|
+
assembledFenceKinds: fences.map((fence) => fence.message.metadata?.fenceKind).filter((kind) => typeof kind === "string")
|
|
2061
|
+
}
|
|
2062
|
+
};
|
|
2063
|
+
return {
|
|
2064
|
+
messages: params.messages.map(
|
|
2065
|
+
(message, index) => index === systemIndex ? assembledSystemPrompt : message
|
|
2066
|
+
).filter((_, index) => !indexesToRemove.has(index)),
|
|
2067
|
+
modifiedCount: fences.length + 1
|
|
2068
|
+
};
|
|
2069
|
+
}
|
|
2070
|
+
function assembleCurrentUserInput(params) {
|
|
2071
|
+
const currentUserIndex = findLastUserInputIndex(params.messages);
|
|
2072
|
+
if (currentUserIndex === -1) {
|
|
2073
|
+
return { messages: [...params.messages], modifiedCount: 0 };
|
|
2074
|
+
}
|
|
2075
|
+
const beforeFences = collectAdjacentFences({
|
|
2076
|
+
messages: params.messages,
|
|
2077
|
+
startIndex: currentUserIndex - 1,
|
|
2078
|
+
direction: -1,
|
|
2079
|
+
fenceRegistry: params.fenceRegistry,
|
|
2080
|
+
matches: (descriptor) => isUserCurrentTurnPlacement(descriptor, "before-current-user")
|
|
2081
|
+
}).reverse();
|
|
2082
|
+
const afterFences = collectAdjacentFences({
|
|
2083
|
+
messages: params.messages,
|
|
2084
|
+
startIndex: currentUserIndex + 1,
|
|
2085
|
+
direction: 1,
|
|
2086
|
+
fenceRegistry: params.fenceRegistry,
|
|
2087
|
+
matches: (descriptor) => isUserCurrentTurnPlacement(descriptor, "after-current-user")
|
|
2088
|
+
});
|
|
2089
|
+
if (beforeFences.length === 0 && afterFences.length === 0) {
|
|
2090
|
+
return { messages: [...params.messages], modifiedCount: 0 };
|
|
2091
|
+
}
|
|
2092
|
+
const indexesToRemove = /* @__PURE__ */ new Set([
|
|
2093
|
+
...beforeFences.map((fence) => fence.index),
|
|
2094
|
+
...afterFences.map((fence) => fence.index)
|
|
2095
|
+
]);
|
|
2096
|
+
const currentUser = params.messages[currentUserIndex];
|
|
2097
|
+
const assembledUser = {
|
|
2098
|
+
...currentUser,
|
|
2099
|
+
content: [
|
|
2100
|
+
...beforeFences.map(formatFence),
|
|
2101
|
+
wrapUserRequest(currentUser.content),
|
|
2102
|
+
...afterFences.map(formatFence)
|
|
2103
|
+
].join("\n\n"),
|
|
2104
|
+
metadata: {
|
|
2105
|
+
...currentUser.metadata,
|
|
2106
|
+
assembledFenceKinds: [
|
|
2107
|
+
...beforeFences.map((fence) => fence.message.metadata?.fenceKind),
|
|
2108
|
+
...afterFences.map((fence) => fence.message.metadata?.fenceKind)
|
|
2109
|
+
].filter((kind) => typeof kind === "string")
|
|
2110
|
+
}
|
|
2111
|
+
};
|
|
2112
|
+
return {
|
|
2113
|
+
messages: params.messages.map(
|
|
2114
|
+
(message, index) => index === currentUserIndex ? assembledUser : message
|
|
2115
|
+
).filter((_, index) => !indexesToRemove.has(index)),
|
|
2116
|
+
modifiedCount: indexesToRemove.size + 1
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
function findLastUserInputIndex(messages) {
|
|
2120
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
2121
|
+
const message = messages[index];
|
|
2122
|
+
if (message.role === "user" && message.type === "user_input") {
|
|
2123
|
+
return index;
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
return -1;
|
|
2127
|
+
}
|
|
2128
|
+
function collectAdjacentFences(params) {
|
|
2129
|
+
const result = [];
|
|
2130
|
+
for (let index = params.startIndex; index >= 0 && index < params.messages.length; index += params.direction) {
|
|
2131
|
+
const message = params.messages[index];
|
|
2132
|
+
if (message.type !== "context_injection") {
|
|
2133
|
+
break;
|
|
2134
|
+
}
|
|
2135
|
+
const fenceKind = message.metadata?.fenceKind;
|
|
2136
|
+
if (!fenceKind) {
|
|
2137
|
+
break;
|
|
2138
|
+
}
|
|
2139
|
+
const descriptor = params.fenceRegistry.get(fenceKind);
|
|
2140
|
+
if (!descriptor || !params.matches(descriptor)) {
|
|
2141
|
+
break;
|
|
2142
|
+
}
|
|
2143
|
+
result.push({ index, message, descriptor });
|
|
2144
|
+
}
|
|
2145
|
+
return result;
|
|
2146
|
+
}
|
|
2147
|
+
function isUserCurrentTurnPlacement(descriptor, placement) {
|
|
2148
|
+
return descriptor.llmRole === "user" && descriptor.placement === placement;
|
|
2149
|
+
}
|
|
2150
|
+
function formatFence(fence) {
|
|
2151
|
+
return fence.descriptor.formatter(fence.message.content, fence.message.metadata?.fenceAttrs ?? {});
|
|
2152
|
+
}
|
|
2153
|
+
function wrapUserRequest(content) {
|
|
2154
|
+
const trimmed = content.trim();
|
|
2155
|
+
if (/<user_request(?:\s[^>]*)?>[\s\S]*<\/user_request>/.test(trimmed)) {
|
|
2156
|
+
return trimmed;
|
|
2157
|
+
}
|
|
2158
|
+
return `<user_request>
|
|
2159
|
+
${trimmed}
|
|
2160
|
+
</user_request>`;
|
|
2161
|
+
}
|
|
2162
|
+
|
|
1777
2163
|
// src/context-manager/shared/providers/base.ts
|
|
1778
2164
|
var TOOL_HISTORY_OVERFLOW_ERROR_CODE = "TOOL_HISTORY_OVERFLOW";
|
|
1779
2165
|
var SUMMARIZATION_FAILED_ERROR_CODE = "SUMMARIZATION_FAILED";
|
|
@@ -2576,7 +2962,7 @@ __export(config_exports, {
|
|
|
2576
2962
|
var AGENT_CONTEXT_BUILDER_CONFIG = {
|
|
2577
2963
|
// === 绝对Token限制设置 ===
|
|
2578
2964
|
/** 默认最大Token预算上限 */
|
|
2579
|
-
DEFAULT_MAX_TOKENS:
|
|
2965
|
+
DEFAULT_MAX_TOKENS: 232e3,
|
|
2580
2966
|
/** 响应预留Token数 */
|
|
2581
2967
|
RESERVED_FOR_RESPONSE: 2400,
|
|
2582
2968
|
// === Agent专用工作记忆填充策略 ===
|
|
@@ -2885,7 +3271,11 @@ var AgentCoreContextProvider = class extends BaseContextProvider2 {
|
|
|
2885
3271
|
state.processedContent = processedContent;
|
|
2886
3272
|
state.contentType = contentType;
|
|
2887
3273
|
state.phase = "CORE_CONTEXT";
|
|
2888
|
-
|
|
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
|
+
}
|
|
2889
3279
|
coreTokens += state.tokens;
|
|
2890
3280
|
processedCount++;
|
|
2891
3281
|
this.debug(`\u2705 \u6807\u8BB0\u4E3A\u6838\u5FC3\u6D88\u606F`, {
|
|
@@ -3189,6 +3579,7 @@ var ToolPairMatcher = class {
|
|
|
3189
3579
|
constructor(config) {
|
|
3190
3580
|
this.config = config;
|
|
3191
3581
|
}
|
|
3582
|
+
config;
|
|
3192
3583
|
/**
|
|
3193
3584
|
* 判断是否为"预处理阶段压缩的工具历史摘要消息"
|
|
3194
3585
|
* - 该类消息不再是 tool_calls/tool_output 的原始结构,而是 assistant 的自然语言记录
|
|
@@ -3369,6 +3760,7 @@ var ToolPairTruncator = class {
|
|
|
3369
3760
|
constructor(config) {
|
|
3370
3761
|
this.config = config;
|
|
3371
3762
|
}
|
|
3763
|
+
config;
|
|
3372
3764
|
/**
|
|
3373
3765
|
* 智能截断超大的工具对
|
|
3374
3766
|
*
|
|
@@ -3965,7 +4357,7 @@ var AgentWorkingMemoryProvider = class extends BaseContextProvider2 {
|
|
|
3965
4357
|
let workingMemoryTokens = coreTokens;
|
|
3966
4358
|
let processedCount = 0;
|
|
3967
4359
|
const strategiesApplied = [];
|
|
3968
|
-
const workingMemoryBudget = Math.floor(
|
|
4360
|
+
const workingMemoryBudget = Math.floor(context.totalBudget * config.WORKING_MEMORY_BUDGET_PERCENTAGE);
|
|
3969
4361
|
const remainingBudget = workingMemoryBudget - coreTokens;
|
|
3970
4362
|
if (remainingBudget <= 0 && config.MIN_TOOL_INTERACTIONS_TO_KEEP <= 0) {
|
|
3971
4363
|
this.debug("\u26A0\uFE0F \u6838\u5FC3\u4E0A\u4E0B\u6587\u5DF2\u7528\u5C3D\u9884\u7B97\uFF0C\u8DF3\u8FC7\u5DE5\u4F5C\u8BB0\u5FC6\u586B\u5145", {
|
|
@@ -4100,6 +4492,7 @@ var Logger = class {
|
|
|
4100
4492
|
constructor(moduleName) {
|
|
4101
4493
|
this.moduleName = moduleName;
|
|
4102
4494
|
}
|
|
4495
|
+
moduleName;
|
|
4103
4496
|
debug(message, data) {
|
|
4104
4497
|
this.log(0 /* DEBUG */, "debug", message, data);
|
|
4105
4498
|
}
|
|
@@ -4347,6 +4740,7 @@ var DefaultTokenizerPort = class {
|
|
|
4347
4740
|
constructor(config = {}) {
|
|
4348
4741
|
this.config = config;
|
|
4349
4742
|
}
|
|
4743
|
+
config;
|
|
4350
4744
|
estimateText(text, _modelId) {
|
|
4351
4745
|
return TokenCalculator.estimateTokens(text, {
|
|
4352
4746
|
encoding: this.config.encoding,
|
|
@@ -4382,7 +4776,7 @@ async function runContextPipeline(options) {
|
|
|
4382
4776
|
message,
|
|
4383
4777
|
originalIndex: index,
|
|
4384
4778
|
action: "skip",
|
|
4385
|
-
|
|
4779
|
+
...estimateTokens(message)
|
|
4386
4780
|
}));
|
|
4387
4781
|
const providers = providerRegistry.getAllProviders();
|
|
4388
4782
|
let availableBudget = totalBudget;
|
|
@@ -4458,7 +4852,7 @@ async function runContextPipeline(options) {
|
|
|
4458
4852
|
buildStats.messageStats.afterWorkingMemory = states.filter((state) => state.action.startsWith("keep_")).length;
|
|
4459
4853
|
buildStats.messageStats.afterSummarization = states.filter((state) => state.action !== "skip").length;
|
|
4460
4854
|
const finalMessages = generateFinalMessages(states);
|
|
4461
|
-
const finalTokens = finalMessages.reduce((total, message) => total + estimateTokens(message), 0);
|
|
4855
|
+
const finalTokens = finalMessages.reduce((total, message) => total + estimateTokens(message).tokens, 0);
|
|
4462
4856
|
contextTrace?.recordMessageDecisions(states);
|
|
4463
4857
|
return {
|
|
4464
4858
|
finalMessages,
|
|
@@ -4511,6 +4905,85 @@ function isFatalProviderError(error) {
|
|
|
4511
4905
|
return isContextProviderError(error) && error.code === SUMMARIZATION_FAILED_ERROR_CODE && error.fatal === true;
|
|
4512
4906
|
}
|
|
4513
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
|
+
|
|
4514
4987
|
// src/context-manager/shared/context-manager-base.ts
|
|
4515
4988
|
var ContextManagerBase = class {
|
|
4516
4989
|
config;
|
|
@@ -4519,6 +4992,10 @@ var ContextManagerBase = class {
|
|
|
4519
4992
|
logger;
|
|
4520
4993
|
tokenizer;
|
|
4521
4994
|
tokenizerModelId;
|
|
4995
|
+
tokenCounter;
|
|
4996
|
+
tokenRoute;
|
|
4997
|
+
remoteCountPolicy;
|
|
4998
|
+
tokenCalibrationState;
|
|
4522
4999
|
validateConfigFn;
|
|
4523
5000
|
invalidConfigMessage;
|
|
4524
5001
|
hasCustomTokenizer;
|
|
@@ -4532,6 +5009,10 @@ var ContextManagerBase = class {
|
|
|
4532
5009
|
this.hasCustomTokenizer = options.tokenizer !== void 0;
|
|
4533
5010
|
this.tokenizer = options.tokenizer ?? this.createDefaultTokenizer();
|
|
4534
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 ?? {});
|
|
4535
5016
|
if (!this.validateConfigFn(this.config)) {
|
|
4536
5017
|
throw new Error(this.invalidConfigMessage);
|
|
4537
5018
|
}
|
|
@@ -4544,7 +5025,85 @@ var ContextManagerBase = class {
|
|
|
4544
5025
|
});
|
|
4545
5026
|
}
|
|
4546
5027
|
estimateTokens(message) {
|
|
4547
|
-
|
|
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
|
+
}
|
|
4548
5107
|
}
|
|
4549
5108
|
debug(message, data) {
|
|
4550
5109
|
if (this.debugMode) {
|
|
@@ -4558,7 +5117,13 @@ var ContextManagerBase = class {
|
|
|
4558
5117
|
buildStats: options.buildStats,
|
|
4559
5118
|
providerRegistry: this.providerRegistry,
|
|
4560
5119
|
providerContext: options.providerContext,
|
|
4561
|
-
estimateTokens: (message) =>
|
|
5120
|
+
estimateTokens: (message) => {
|
|
5121
|
+
const estimate = this.estimateTokensWithCalibrationTrace(message);
|
|
5122
|
+
return {
|
|
5123
|
+
tokens: estimate.tokens,
|
|
5124
|
+
tokenCalibration: estimate.calibrationTrace
|
|
5125
|
+
};
|
|
5126
|
+
},
|
|
4562
5127
|
getPhaseByProviderName: options.getPhaseByProviderName,
|
|
4563
5128
|
debug: (message, data) => this.debug(message, data),
|
|
4564
5129
|
contextTrace: options.contextTrace
|
|
@@ -4585,6 +5150,9 @@ var ContextManagerBase = class {
|
|
|
4585
5150
|
updateTokenizerModelId(modelId) {
|
|
4586
5151
|
this.tokenizerModelId = modelId;
|
|
4587
5152
|
}
|
|
5153
|
+
updateTokenCalibration(input) {
|
|
5154
|
+
this.tokenCalibrationState = buildTokenUsageCalibrationState(input ?? {});
|
|
5155
|
+
}
|
|
4588
5156
|
};
|
|
4589
5157
|
|
|
4590
5158
|
// src/context-manager/shared/context-result.ts
|
|
@@ -4601,7 +5169,9 @@ function buildContextResult(options) {
|
|
|
4601
5169
|
coreTypes,
|
|
4602
5170
|
recommendations,
|
|
4603
5171
|
events = [],
|
|
4604
|
-
contextTrace
|
|
5172
|
+
contextTrace,
|
|
5173
|
+
tokenEstimate,
|
|
5174
|
+
tokenComponents
|
|
4605
5175
|
} = options;
|
|
4606
5176
|
const tokenDistribution = calculateTokenDistribution(
|
|
4607
5177
|
finalMessages,
|
|
@@ -4628,7 +5198,9 @@ function buildContextResult(options) {
|
|
|
4628
5198
|
recommendations
|
|
4629
5199
|
},
|
|
4630
5200
|
events,
|
|
4631
|
-
...contextTrace ? { contextTrace } : {}
|
|
5201
|
+
...contextTrace ? { contextTrace } : {},
|
|
5202
|
+
...tokenEstimate ? { tokenEstimate } : {},
|
|
5203
|
+
...tokenComponents ? { tokenComponents } : {}
|
|
4632
5204
|
};
|
|
4633
5205
|
}
|
|
4634
5206
|
function generateContextRecommendations(stats, options) {
|
|
@@ -4672,6 +5244,70 @@ function calculateTokenDistribution(finalMessages, estimateTokens, coreTypes) {
|
|
|
4672
5244
|
return tokenDistribution;
|
|
4673
5245
|
}
|
|
4674
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
|
+
|
|
4675
5311
|
// src/context-manager/profiles/agent/context/AgentContextManager.ts
|
|
4676
5312
|
var AgentContextManager = class extends ContextManagerBase {
|
|
4677
5313
|
constructor(options = {}) {
|
|
@@ -4708,6 +5344,13 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4708
5344
|
config: this.config,
|
|
4709
5345
|
debugMode: this.debugMode,
|
|
4710
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
|
+
},
|
|
4711
5354
|
summarizationCallbacks: callbacks,
|
|
4712
5355
|
generate,
|
|
4713
5356
|
agentRequest: request
|
|
@@ -4716,9 +5359,10 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4716
5359
|
policy: traceOptions?.policy,
|
|
4717
5360
|
effectivePolicy: traceOptions?.effectiveContextPolicy,
|
|
4718
5361
|
totalBudget,
|
|
4719
|
-
originalCount: preprocessedMessages.length
|
|
5362
|
+
originalCount: preprocessedMessages.length,
|
|
5363
|
+
tokenCalibration: this.getTokenCalibrationTrace()
|
|
4720
5364
|
});
|
|
4721
|
-
const { finalMessages, finalTokens, strategiesApplied, events } = await this.runPipeline({
|
|
5365
|
+
const { finalMessages, finalTokens, strategiesApplied, events, states } = await this.runPipeline({
|
|
4722
5366
|
messages: preprocessedMessages,
|
|
4723
5367
|
totalBudget,
|
|
4724
5368
|
buildStats,
|
|
@@ -4726,6 +5370,14 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4726
5370
|
getPhaseByProviderName: (providerName) => this.getPhaseByProviderName(providerName),
|
|
4727
5371
|
contextTrace
|
|
4728
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);
|
|
4729
5381
|
const endTime = performance.now();
|
|
4730
5382
|
buildStats.totalTime = endTime - startTime;
|
|
4731
5383
|
const summarizationThreshold2 = this.config.SUMMARIZATION_TRIGGER_THRESHOLD;
|
|
@@ -4733,22 +5385,24 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4733
5385
|
this.debug("\u2705 [Agent\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5B8C\u6210", {
|
|
4734
5386
|
\u9884\u5904\u7406\u6D88\u606F: preprocessedMessages.length,
|
|
4735
5387
|
\u6700\u7EC8\u6D88\u606F: finalMessages.length,
|
|
4736
|
-
Token\u4F7F\u7528:
|
|
5388
|
+
Token\u4F7F\u7528: remoteCount.tokens,
|
|
4737
5389
|
\u603B\u9884\u7B97: totalBudget,
|
|
4738
|
-
\u4F7F\u7528\u7387: `${(
|
|
5390
|
+
\u4F7F\u7528\u7387: `${(remoteCount.tokens / totalBudget * 100).toFixed(1)}%`,
|
|
4739
5391
|
\u6458\u8981\u89E6\u53D1\u9608\u503C: `${(summarizationThreshold2 * 100).toFixed(0)}%`,
|
|
4740
5392
|
\u6458\u8981Token\u9608\u503C: summarizationTokenThreshold2,
|
|
4741
5393
|
\u603B\u8017\u65F6: `${buildStats.totalTime.toFixed(2)}ms`
|
|
4742
5394
|
});
|
|
4743
5395
|
return this.buildFinalResult(
|
|
4744
5396
|
finalMessages,
|
|
4745
|
-
|
|
5397
|
+
remoteCount.tokens,
|
|
4746
5398
|
totalBudget,
|
|
4747
5399
|
preprocessedMessages.length,
|
|
4748
5400
|
strategiesApplied,
|
|
4749
5401
|
buildStats,
|
|
4750
5402
|
events,
|
|
4751
|
-
contextTrace?.build(finalMessages, finalTokens)
|
|
5403
|
+
contextTrace?.build(finalMessages, finalTokens),
|
|
5404
|
+
tokenEstimate,
|
|
5405
|
+
tokenComponents
|
|
4752
5406
|
);
|
|
4753
5407
|
} catch (error) {
|
|
4754
5408
|
this.debug("\u274C [Agent\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5931\u8D25", { error });
|
|
@@ -4796,7 +5450,7 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4796
5450
|
totalTime: 0
|
|
4797
5451
|
};
|
|
4798
5452
|
}
|
|
4799
|
-
buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], contextTrace) {
|
|
5453
|
+
buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], contextTrace, tokenEstimate, tokenComponents) {
|
|
4800
5454
|
const recommendations = this.generateRecommendations(buildStats, totalBudget);
|
|
4801
5455
|
return buildContextResult({
|
|
4802
5456
|
finalMessages,
|
|
@@ -4810,9 +5464,21 @@ var AgentContextManager = class extends ContextManagerBase {
|
|
|
4810
5464
|
coreTypes: this.config.CORE_MESSAGE_TYPES,
|
|
4811
5465
|
recommendations,
|
|
4812
5466
|
events,
|
|
4813
|
-
contextTrace
|
|
5467
|
+
contextTrace,
|
|
5468
|
+
tokenEstimate,
|
|
5469
|
+
tokenComponents
|
|
4814
5470
|
});
|
|
4815
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
|
+
}
|
|
4816
5482
|
/**
|
|
4817
5483
|
* 生成优化建议
|
|
4818
5484
|
*/
|
|
@@ -5106,6 +5772,7 @@ __export(orchestration_exports, {
|
|
|
5106
5772
|
var preprocessors_exports = {};
|
|
5107
5773
|
__export(preprocessors_exports, {
|
|
5108
5774
|
BasePreprocessor: () => BasePreprocessor2,
|
|
5775
|
+
CurrentTurnMessageAssembler: () => CurrentTurnMessageAssembler,
|
|
5109
5776
|
FenceLifetimePreprocessor: () => FenceLifetimePreprocessor,
|
|
5110
5777
|
HistoryPurificationPreprocessor: () => HistoryPurificationPreprocessor,
|
|
5111
5778
|
PreprocessorPipeline: () => PreprocessorPipeline,
|
|
@@ -5157,7 +5824,7 @@ var DEFAULT_KEEP_LATEST_RUNS = 1;
|
|
|
5157
5824
|
var DEFAULT_MAX_INTERACTION_GROUPS = 12;
|
|
5158
5825
|
var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
|
|
5159
5826
|
name = "ToolHistoryCompressorPreprocessor";
|
|
5160
|
-
description = "\u5DE5\u5177\u5386\u53F2\
|
|
5827
|
+
description = "\u5DE5\u5177\u5386\u53F2\u4FDD\u7559\u5904\u7406\u5668 - \u6309\u7B56\u7565\u4FDD\u7559\u3001\u5220\u9664\u6216\u538B\u7F29\u8F83\u65E9\u7684\u5386\u53F2\u5DE5\u5177\u8C03\u7528\u5BF9";
|
|
5161
5828
|
priority = 0;
|
|
5162
5829
|
summarizer = createDefaultToolOutputSummarizer();
|
|
5163
5830
|
options;
|
|
@@ -5165,6 +5832,7 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
|
|
|
5165
5832
|
super();
|
|
5166
5833
|
this.options = {
|
|
5167
5834
|
strategy: options.strategy ?? "per-run",
|
|
5835
|
+
retentionMode: options.retentionMode ?? "drop",
|
|
5168
5836
|
keepLatestToolPairs: normalizeNonNegativeInteger4(
|
|
5169
5837
|
options.keepLatestToolPairs,
|
|
5170
5838
|
DEFAULT_KEEP_LATEST_TOOL_PAIRS
|
|
@@ -5181,7 +5849,7 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
|
|
|
5181
5849
|
};
|
|
5182
5850
|
}
|
|
5183
5851
|
async process(messages, context) {
|
|
5184
|
-
this.debug("\u{1F527} \u5F00\u59CB\u5DE5\u5177\u5386\u53F2\
|
|
5852
|
+
this.debug("\u{1F527} \u5F00\u59CB\u5DE5\u5177\u5386\u53F2\u4FDD\u7559\u5904\u7406", {
|
|
5185
5853
|
\u539F\u59CB\u6D88\u606F\u6570: messages.length
|
|
5186
5854
|
}, context);
|
|
5187
5855
|
const currentRunStartIndex = findCurrentRunStartIndex(messages);
|
|
@@ -5191,17 +5859,18 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
|
|
|
5191
5859
|
\u5386\u53F2\u6D88\u606F\u6570: historyMessages.length,
|
|
5192
5860
|
\u5F53\u524D\u8F6E\u6B21\u6D88\u606F\u6570: currentRunMessages.length,
|
|
5193
5861
|
\u5F53\u524D\u8F6E\u6B21\u8D77\u70B9\u7D22\u5F15: currentRunStartIndex,
|
|
5194
|
-
\u5DE5\u5177\
|
|
5862
|
+
\u5DE5\u5177\u4FDD\u7559\u7B56\u7565: this.options.strategy,
|
|
5863
|
+
\u5386\u53F2\u5DE5\u5177\u4FDD\u7559\u6A21\u5F0F: this.options.retentionMode
|
|
5195
5864
|
}, context);
|
|
5196
|
-
const
|
|
5197
|
-
const finalMessages = [...
|
|
5865
|
+
const processedHistory = this.processToolCallPairsInHistory(historyMessages, context);
|
|
5866
|
+
const finalMessages = [...processedHistory, ...currentRunMessages];
|
|
5198
5867
|
const originalCount = messages.length;
|
|
5199
|
-
const
|
|
5200
|
-
const removedCount = originalCount -
|
|
5201
|
-
const appliedStrategies = removedCount > 0 ? ["tool_history_compression"] : [];
|
|
5202
|
-
this.debug("\u2705 \u5DE5\u5177\u5386\u53F2\
|
|
5868
|
+
const processedCount = finalMessages.length;
|
|
5869
|
+
const removedCount = originalCount - processedCount;
|
|
5870
|
+
const appliedStrategies = removedCount > 0 ? [this.options.retentionMode === "compress" ? "tool_history_compression" : "tool_history_drop"] : [];
|
|
5871
|
+
this.debug("\u2705 \u5DE5\u5177\u5386\u53F2\u4FDD\u7559\u5904\u7406\u5B8C\u6210", {
|
|
5203
5872
|
\u539F\u59CB\u6D88\u606F: originalCount,
|
|
5204
|
-
\
|
|
5873
|
+
\u5904\u7406\u540E\u6D88\u606F: processedCount,
|
|
5205
5874
|
\u51CF\u5C11\u6D88\u606F: removedCount,
|
|
5206
5875
|
Token\u8282\u7701\u4F30\u8BA1: `\u7EA6${removedCount * 50}\u4E2AToken`
|
|
5207
5876
|
}, context);
|
|
@@ -5222,7 +5891,7 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
|
|
|
5222
5891
|
}
|
|
5223
5892
|
return false;
|
|
5224
5893
|
}
|
|
5225
|
-
|
|
5894
|
+
processToolCallPairsInHistory(historyMessages, context) {
|
|
5226
5895
|
if (historyMessages.length < 2) {
|
|
5227
5896
|
return historyMessages;
|
|
5228
5897
|
}
|
|
@@ -5243,8 +5912,10 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
|
|
|
5243
5912
|
if (!group.isComplete || keepAnchorIds.has(group.anchorId)) {
|
|
5244
5913
|
continue;
|
|
5245
5914
|
}
|
|
5246
|
-
|
|
5247
|
-
|
|
5915
|
+
if (this.options.retentionMode === "compress") {
|
|
5916
|
+
const compressedMessage = this.compressToolInteractionGroup(group, context);
|
|
5917
|
+
replacementMap.set(group.assistantIndex, compressedMessage);
|
|
5918
|
+
}
|
|
5248
5919
|
for (const messageIndex of group.messageIndexes) {
|
|
5249
5920
|
messagesToRemove.add(messageIndex);
|
|
5250
5921
|
}
|
|
@@ -5663,6 +6334,7 @@ function createDefaultAgentPreprocessorRegistry(options = {}) {
|
|
|
5663
6334
|
registry.register(new ToolReplayProtocolGuardPreprocessor({ policy: options.providerReplay }));
|
|
5664
6335
|
registry.register(new HistoryPurificationPreprocessor({ logPrefix: "Agent-HistoryPurification" }));
|
|
5665
6336
|
if (options.fenceRegistry) {
|
|
6337
|
+
registry.register(new CurrentTurnMessageAssembler({ fenceRegistry: options.fenceRegistry }));
|
|
5666
6338
|
registry.register(new FenceLifetimePreprocessor({ fenceRegistry: options.fenceRegistry }));
|
|
5667
6339
|
}
|
|
5668
6340
|
return registry;
|
|
@@ -5770,10 +6442,10 @@ var contextBudgetWarningTemplate = (ctx) => {
|
|
|
5770
6442
|
return [
|
|
5771
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`,
|
|
5772
6444
|
"\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
|
|
5773
|
-
"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",
|
|
5774
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`,
|
|
5775
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',
|
|
5776
|
-
"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"
|
|
5777
6449
|
].join("\n");
|
|
5778
6450
|
};
|
|
5779
6451
|
var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
|
|
@@ -6510,6 +7182,27 @@ createConsoleAudit();
|
|
|
6510
7182
|
function isRecord7(value) {
|
|
6511
7183
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
6512
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
|
+
}
|
|
6513
7206
|
function isHistorySummaryEvent2(event) {
|
|
6514
7207
|
return "type" in event && event.type === "history_summary";
|
|
6515
7208
|
}
|
|
@@ -6622,6 +7315,7 @@ function convertEventToAiMessage(event) {
|
|
|
6622
7315
|
}
|
|
6623
7316
|
})();
|
|
6624
7317
|
const outputContent = observationFromPayload ?? rawOutput;
|
|
7318
|
+
const observationTruncation = readObservationTruncationMeta(event.metadata?.observationTruncation);
|
|
6625
7319
|
return {
|
|
6626
7320
|
id: event.id,
|
|
6627
7321
|
role: "tool",
|
|
@@ -6632,6 +7326,7 @@ function convertEventToAiMessage(event) {
|
|
|
6632
7326
|
tool_call_id: event.tool_call_id,
|
|
6633
7327
|
tool_name: event.tool_name,
|
|
6634
7328
|
raw_output: rawOutput,
|
|
7329
|
+
...observationTruncation ? { observationTruncation } : {},
|
|
6635
7330
|
...observationFromPayload ? { observation: observationFromPayload } : {}
|
|
6636
7331
|
}
|
|
6637
7332
|
};
|
|
@@ -6742,7 +7437,8 @@ var AgentMessageOrchestrator = class {
|
|
|
6742
7437
|
customConfig: this.baseContextConfig,
|
|
6743
7438
|
providerRegistry: options.providerRegistry,
|
|
6744
7439
|
tokenizer: options.tokenizer,
|
|
6745
|
-
tokenizerModelId: options.model
|
|
7440
|
+
tokenizerModelId: options.model,
|
|
7441
|
+
tokenCounter: options.tokenCounter
|
|
6746
7442
|
});
|
|
6747
7443
|
}
|
|
6748
7444
|
buildPreprocessorPipelineForRequest(toolManager, request, contextPolicy) {
|
|
@@ -6771,13 +7467,44 @@ var AgentMessageOrchestrator = class {
|
|
|
6771
7467
|
contextPolicy,
|
|
6772
7468
|
contextBuilderConfig
|
|
6773
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;
|
|
6774
7481
|
this.agentContextManager = new AgentContextManager({
|
|
6775
7482
|
debugMode: this.options.processing.debugMode,
|
|
6776
7483
|
customConfig: contextBuilderConfig,
|
|
6777
7484
|
providerRegistry,
|
|
6778
7485
|
tokenizer: this.options.tokenizer,
|
|
6779
|
-
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
|
+
}
|
|
6780
7495
|
});
|
|
7496
|
+
return contextBuilderConfig;
|
|
7497
|
+
}
|
|
7498
|
+
resolveEffectiveContextBudget(contextBuilderConfig) {
|
|
7499
|
+
const maxTokens = contextBuilderConfig.DEFAULT_MAX_TOKENS ?? this.options.tokenBudget.maxTokens;
|
|
7500
|
+
const reservedForResponse = contextBuilderConfig.RESERVED_FOR_RESPONSE ?? this.options.tokenBudget.reservedForResponse;
|
|
7501
|
+
return {
|
|
7502
|
+
maxTokens,
|
|
7503
|
+
reservedForResponse,
|
|
7504
|
+
// 中文备注:ContextManager 接收的是“可放入上下文的输入预算”,不是模型完整窗口。
|
|
7505
|
+
// 因此单个 agent 通过 contextPolicy.budget 覆盖预算时,这里必须同步使用覆盖后的值。
|
|
7506
|
+
totalBudget: maxTokens - reservedForResponse
|
|
7507
|
+
};
|
|
6781
7508
|
}
|
|
6782
7509
|
async processAgentConversation(request, history, toolManager, callbacks, extraOptions) {
|
|
6783
7510
|
const historyCount = history.length;
|
|
@@ -6796,7 +7523,8 @@ var AgentMessageOrchestrator = class {
|
|
|
6796
7523
|
const allMessages = this.buildCompleteMessageList(request, historyMessages);
|
|
6797
7524
|
this.debug("Built complete message list", { totalCount: allMessages.length });
|
|
6798
7525
|
const contextPolicy = this.resolveContextPolicy(request);
|
|
6799
|
-
this.applyContextPolicy(request, contextPolicy);
|
|
7526
|
+
const contextBuilderConfig = this.applyContextPolicy(request, contextPolicy);
|
|
7527
|
+
const effectiveContextBudget = this.resolveEffectiveContextBudget(contextBuilderConfig);
|
|
6800
7528
|
const preprocessorPipeline = this.buildPreprocessorPipelineForRequest(toolManager, request, contextPolicy);
|
|
6801
7529
|
const modelId = this.resolvePreprocessorModel(request);
|
|
6802
7530
|
preprocessorPipeline.updateContext({
|
|
@@ -6824,7 +7552,8 @@ var AgentMessageOrchestrator = class {
|
|
|
6824
7552
|
callbacks,
|
|
6825
7553
|
void 0,
|
|
6826
7554
|
extraOptions?.generate,
|
|
6827
|
-
contextPolicy
|
|
7555
|
+
contextPolicy,
|
|
7556
|
+
effectiveContextBudget.totalBudget
|
|
6828
7557
|
);
|
|
6829
7558
|
this.debug("Context built", { afterContextCount: contextResult.messages.length });
|
|
6830
7559
|
if (this.options.processing.debugMode) {
|
|
@@ -6857,7 +7586,7 @@ var AgentMessageOrchestrator = class {
|
|
|
6857
7586
|
processedCount: contextResult.messages.length,
|
|
6858
7587
|
tokenUsage: {
|
|
6859
7588
|
estimated: contextResult.tokenUsage.used,
|
|
6860
|
-
budget:
|
|
7589
|
+
budget: effectiveContextBudget.totalBudget,
|
|
6861
7590
|
remaining: contextResult.tokenUsage.remaining
|
|
6862
7591
|
},
|
|
6863
7592
|
processingStats: contextResult.processingStats,
|
|
@@ -6877,13 +7606,13 @@ var AgentMessageOrchestrator = class {
|
|
|
6877
7606
|
async runPreprocessorPipeline(preprocessorPipeline, messages) {
|
|
6878
7607
|
return preprocessorPipeline.process(messages);
|
|
6879
7608
|
}
|
|
6880
|
-
async buildContextFromPreprocessedMessages(request, conversationSession, messages, callbacks, phaseOverride, generate, contextPolicy) {
|
|
6881
|
-
const
|
|
7609
|
+
async buildContextFromPreprocessedMessages(request, conversationSession, messages, callbacks, phaseOverride, generate, contextPolicy, totalBudget) {
|
|
7610
|
+
const resolvedTotalBudget = totalBudget ?? this.options.tokenBudget.maxTokens - this.options.tokenBudget.reservedForResponse;
|
|
6882
7611
|
const contextResult = await this.agentContextManager.buildContextFromPreprocessedMessages(
|
|
6883
7612
|
request,
|
|
6884
7613
|
conversationSession,
|
|
6885
7614
|
messages,
|
|
6886
|
-
|
|
7615
|
+
resolvedTotalBudget,
|
|
6887
7616
|
callbacks,
|
|
6888
7617
|
phaseOverride,
|
|
6889
7618
|
generate,
|
|
@@ -6964,22 +7693,33 @@ var BaseAgentTask = class {
|
|
|
6964
7693
|
});
|
|
6965
7694
|
}
|
|
6966
7695
|
messages.push(...fenceMessages["after-system"]);
|
|
7696
|
+
const currentUserIndex = findCurrentUserInputIndex(history, request.query);
|
|
7697
|
+
const historyBeforeCurrentUser = currentUserIndex === -1 ? history : history.slice(0, currentUserIndex);
|
|
7698
|
+
const currentUserMessage = currentUserIndex === -1 ? this.createCurrentUserMessage(request.query) : history[currentUserIndex];
|
|
7699
|
+
const historyAfterCurrentUser = currentUserIndex === -1 ? [] : history.slice(currentUserIndex + 1);
|
|
7700
|
+
messages.push(...historyBeforeCurrentUser);
|
|
6967
7701
|
messages.push(...fenceMessages["before-current-user"]);
|
|
6968
|
-
|
|
6969
|
-
|
|
6970
|
-
messages.push({
|
|
6971
|
-
id: generateMessageId(),
|
|
6972
|
-
role: "user",
|
|
6973
|
-
type: "user_input",
|
|
6974
|
-
content: request.query.trim(),
|
|
6975
|
-
timestamp: Date.now()
|
|
6976
|
-
});
|
|
7702
|
+
if (currentUserMessage) {
|
|
7703
|
+
messages.push(currentUserMessage);
|
|
6977
7704
|
}
|
|
6978
7705
|
messages.push(...fenceMessages["after-current-user"]);
|
|
6979
|
-
messages.push(...
|
|
7706
|
+
messages.push(...historyAfterCurrentUser);
|
|
6980
7707
|
this.insertAfterLastToolResult(messages, fenceMessages["after-last-tool-result"]);
|
|
6981
7708
|
return messages;
|
|
6982
7709
|
}
|
|
7710
|
+
createCurrentUserMessage(query) {
|
|
7711
|
+
const content = query.trim();
|
|
7712
|
+
if (!content) {
|
|
7713
|
+
return null;
|
|
7714
|
+
}
|
|
7715
|
+
return {
|
|
7716
|
+
id: generateMessageId(),
|
|
7717
|
+
role: "user",
|
|
7718
|
+
type: "user_input",
|
|
7719
|
+
content,
|
|
7720
|
+
timestamp: Date.now()
|
|
7721
|
+
};
|
|
7722
|
+
}
|
|
6983
7723
|
createFenceMessages(fences) {
|
|
6984
7724
|
const grouped = {
|
|
6985
7725
|
"after-system": [],
|
|
@@ -7044,6 +7784,19 @@ function findLastIndex2(items, predicate) {
|
|
|
7044
7784
|
}
|
|
7045
7785
|
return -1;
|
|
7046
7786
|
}
|
|
7787
|
+
function findCurrentUserInputIndex(history, query) {
|
|
7788
|
+
const normalizedQuery = query.trim();
|
|
7789
|
+
if (!normalizedQuery) {
|
|
7790
|
+
return -1;
|
|
7791
|
+
}
|
|
7792
|
+
for (let index = history.length - 1; index >= 0; index -= 1) {
|
|
7793
|
+
const message = history[index];
|
|
7794
|
+
if (message.role === "user" && message.type === "user_input" && message.content.trim() === normalizedQuery) {
|
|
7795
|
+
return index;
|
|
7796
|
+
}
|
|
7797
|
+
}
|
|
7798
|
+
return -1;
|
|
7799
|
+
}
|
|
7047
7800
|
|
|
7048
7801
|
// src/context-manager/profiles/agent/tools/index.ts
|
|
7049
7802
|
var tools_exports2 = {};
|
|
@@ -7663,6 +8416,7 @@ var ContextManager = class extends ContextManagerBase {
|
|
|
7663
8416
|
providerContext,
|
|
7664
8417
|
getPhaseByProviderName: (providerName) => this.getPhaseByProviderName(providerName)
|
|
7665
8418
|
});
|
|
8419
|
+
const tokenEstimate = this.buildContextTokenEstimate(finalMessages, finalTokens);
|
|
7666
8420
|
const endTime = performance.now();
|
|
7667
8421
|
buildStats.totalTime = endTime - startTime;
|
|
7668
8422
|
const summarizationThreshold2 = this.config.SUMMARIZATION_TRIGGER_THRESHOLD;
|
|
@@ -7684,8 +8438,9 @@ var ContextManager = class extends ContextManagerBase {
|
|
|
7684
8438
|
messages.length,
|
|
7685
8439
|
strategiesApplied,
|
|
7686
8440
|
buildStats,
|
|
7687
|
-
events
|
|
8441
|
+
events,
|
|
7688
8442
|
// 🔥 传递收集的事件
|
|
8443
|
+
tokenEstimate
|
|
7689
8444
|
);
|
|
7690
8445
|
} catch (error) {
|
|
7691
8446
|
this.debug("\u274C [Chat\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5931\u8D25", { error });
|
|
@@ -7721,7 +8476,7 @@ var ContextManager = class extends ContextManagerBase {
|
|
|
7721
8476
|
totalTime: 0
|
|
7722
8477
|
};
|
|
7723
8478
|
}
|
|
7724
|
-
buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = []) {
|
|
8479
|
+
buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], tokenEstimate) {
|
|
7725
8480
|
const recommendations = this.generateRecommendations(buildStats, totalBudget);
|
|
7726
8481
|
return buildContextResult({
|
|
7727
8482
|
finalMessages,
|
|
@@ -7734,9 +8489,19 @@ var ContextManager = class extends ContextManagerBase {
|
|
|
7734
8489
|
estimateTokens: (message) => this.estimateTokens(message),
|
|
7735
8490
|
coreTypes: this.config.CORE_MESSAGE_TYPES,
|
|
7736
8491
|
recommendations,
|
|
7737
|
-
events
|
|
8492
|
+
events,
|
|
8493
|
+
tokenEstimate
|
|
7738
8494
|
});
|
|
7739
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
|
+
}
|
|
7740
8505
|
/**
|
|
7741
8506
|
* 生成优化建议
|
|
7742
8507
|
*/
|
|
@@ -8657,6 +9422,7 @@ exports.ChatWorkingMemoryProvider = WorkingMemoryProvider;
|
|
|
8657
9422
|
exports.ContextProviderError = ContextProviderError;
|
|
8658
9423
|
exports.ContextProviderRegistry = ContextProviderRegistry;
|
|
8659
9424
|
exports.ContextTraceCollector = ContextTraceCollector;
|
|
9425
|
+
exports.CurrentTurnMessageAssembler = CurrentTurnMessageAssembler;
|
|
8660
9426
|
exports.DEFAULT_MUST_KEEP_POLICY = DEFAULT_MUST_KEEP_POLICY;
|
|
8661
9427
|
exports.FenceLifetimePreprocessor = FenceLifetimePreprocessor;
|
|
8662
9428
|
exports.HistoryPurificationPreprocessor = HistoryPurificationPreprocessor;
|