@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.
Files changed (102) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/bin/linnkit.cjs +7 -0
  3. package/dist/{agent-invocation-BHcNfrBV.d.cts → agent-invocation-CAlm9qOw.d.cts} +1 -1
  4. package/dist/{agent-invocation-BznDaXDs.d.ts → agent-invocation-DKoEDLkl.d.ts} +1 -1
  5. package/dist/{ai-engine.types-vZRnQcJa.d.ts → ai-engine.types-CeLoM624.d.cts} +9 -1
  6. package/dist/{ai-engine.types-BpeU_XQG.d.cts → ai-engine.types-LqmnfR2W.d.ts} +9 -1
  7. package/dist/{audit-CtcfART1.d.ts → audit-BuWHoMEr.d.ts} +4 -2
  8. package/dist/{audit-LeOrm2hX.d.cts → audit-DnzNQzwq.d.cts} +4 -2
  9. package/dist/cli.cjs +682 -258
  10. package/dist/cli.cjs.map +1 -1
  11. package/dist/cli.js +682 -258
  12. package/dist/cli.js.map +1 -1
  13. package/dist/context-manager.cjs +823 -57
  14. package/dist/context-manager.cjs.map +1 -1
  15. package/dist/context-manager.d.cts +132 -18
  16. package/dist/context-manager.d.ts +132 -18
  17. package/dist/context-manager.js +823 -58
  18. package/dist/context-manager.js.map +1 -1
  19. package/dist/{context-trace-HE2qY5Q-.d.cts → context-trace-DrtvKac4.d.cts} +37 -4
  20. package/dist/{context-trace-DRi5M4lX.d.ts → context-trace-WV1HAZeB.d.ts} +37 -4
  21. package/dist/contracts.cjs +225 -2
  22. package/dist/contracts.cjs.map +1 -1
  23. package/dist/contracts.d.cts +6 -4
  24. package/dist/contracts.d.ts +6 -4
  25. package/dist/contracts.js +205 -3
  26. package/dist/contracts.js.map +1 -1
  27. package/dist/{defaultGraphExecutor-BIjJj7WF.d.cts → defaultGraphExecutor-L1ri3oij.d.cts} +48 -19
  28. package/dist/{defaultGraphExecutor-BBswR8wn.d.ts → defaultGraphExecutor-QzzdudLQ.d.ts} +48 -19
  29. package/dist/{index-BanRABEt.d.cts → index-BeQO0rx2.d.cts} +345 -268
  30. package/dist/{index-Cvr23YCl.d.cts → index-CDofGr_4.d.ts} +24 -6
  31. package/dist/{index-Dl5PLgAv.d.cts → index-Crl5E4eF.d.cts} +27 -4
  32. package/dist/{index-CJeWHopy.d.ts → index-DWGKvssS.d.ts} +3 -3
  33. package/dist/{index-CHqwkvGp.d.ts → index-X5lYU1Lj.d.ts} +27 -4
  34. package/dist/{index-DDzuSb0n.d.ts → index-uCNCpJBg.d.cts} +24 -6
  35. package/dist/{index-Z8NXKNwI.d.ts → index-wOZD-p2-.d.ts} +345 -268
  36. package/dist/{index-DO4dQgf2.d.cts → index-wXVAHZ0D.d.cts} +3 -3
  37. package/dist/index.cjs +1011 -329
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +19 -16
  40. package/dist/index.d.ts +19 -16
  41. package/dist/index.js +1011 -329
  42. package/dist/index.js.map +1 -1
  43. package/dist/{messages-XthmnHZ3.d.cts → messages-Br5SiLD3.d.cts} +706 -1
  44. package/dist/{messages-XthmnHZ3.d.ts → messages-Br5SiLD3.d.ts} +706 -1
  45. package/dist/{ports-DnLuKfpE.d.ts → ports-Dugizzje.d.cts} +6 -2
  46. package/dist/{ports-DaatKJXp.d.cts → ports-fhp84x_C.d.ts} +6 -2
  47. package/dist/ports.d.cts +8 -5
  48. package/dist/ports.d.ts +8 -5
  49. package/dist/quickstart.cjs +683 -258
  50. package/dist/quickstart.cjs.map +1 -1
  51. package/dist/quickstart.d.cts +11 -10
  52. package/dist/quickstart.d.ts +11 -10
  53. package/dist/quickstart.js +683 -258
  54. package/dist/quickstart.js.map +1 -1
  55. package/dist/{runAgent-CPj_9e58.d.ts → runAgent-BmMSju8I.d.ts} +6 -6
  56. package/dist/{runAgent-HYKlXbVr.d.cts → runAgent-CKgcRSRH.d.cts} +6 -6
  57. package/dist/{runHandle-D3gPsD7B.d.cts → runHandle-DH4VmQx6.d.cts} +6 -4
  58. package/dist/{runHandle-CyXvzgzk.d.ts → runHandle-o3p06Nva.d.ts} +6 -4
  59. package/dist/runtime-kernel/events.cjs +202 -1
  60. package/dist/runtime-kernel/events.cjs.map +1 -1
  61. package/dist/runtime-kernel/events.d.cts +5 -5
  62. package/dist/runtime-kernel/events.d.ts +5 -5
  63. package/dist/runtime-kernel/events.js +202 -1
  64. package/dist/runtime-kernel/events.js.map +1 -1
  65. package/dist/runtime-kernel.cjs +999 -340
  66. package/dist/runtime-kernel.cjs.map +1 -1
  67. package/dist/runtime-kernel.d.cts +16 -14
  68. package/dist/runtime-kernel.d.ts +16 -14
  69. package/dist/runtime-kernel.js +990 -341
  70. package/dist/runtime-kernel.js.map +1 -1
  71. package/dist/testkit.cjs +1003 -321
  72. package/dist/testkit.cjs.map +1 -1
  73. package/dist/testkit.d.cts +16 -14
  74. package/dist/testkit.d.ts +16 -14
  75. package/dist/testkit.js +1003 -321
  76. package/dist/testkit.js.map +1 -1
  77. package/dist/{todo-B1PmDlp3.d.cts → todo-Ca8llpRQ.d.cts} +1 -1
  78. package/dist/{todo-B1PmDlp3.d.ts → todo-Ca8llpRQ.d.ts} +1 -1
  79. package/dist/{agentSpec-EkmviZjy.d.cts → token-accounting-CwpSPg4y.d.cts} +1280 -1
  80. package/dist/{agentSpec-EkmviZjy.d.ts → token-accounting-CwpSPg4y.d.ts} +1280 -1
  81. package/dist/token-calibration-Cxv6dDYF.d.cts +327 -0
  82. package/dist/token-calibration-Cxv6dDYF.d.ts +327 -0
  83. package/dist/token-counter-CFfP8PQb.d.cts +26 -0
  84. package/dist/token-counter-SFyyTeaG.d.ts +26 -0
  85. package/dist/token-usage-CqwT7-5K.d.cts +133 -0
  86. package/dist/token-usage-CqwT7-5K.d.ts +133 -0
  87. package/dist/{tokenizer-DFL4I7-I.d.ts → tokenizer-BFJNCHFX.d.ts} +1 -1
  88. package/dist/{tokenizer-DH_JXv-H.d.cts → tokenizer-DoGsBE3A.d.cts} +1 -1
  89. package/dist/{toolContracts-CLkQmhTG.d.cts → toolContracts-Bm3EZ1UM.d.cts} +13 -2
  90. package/dist/{toolContracts-Blll0241.d.ts → toolContracts-f8lzZBNa.d.ts} +13 -2
  91. package/docs/README.md +1 -1
  92. package/docs/integration/README.md +3 -3
  93. package/docs/integration/agent-registration-guide.md +3 -1
  94. package/docs/integration/child-runs.md +4 -1
  95. package/docs/integration/context-engineering.md +83 -16
  96. package/docs/integration/context-fences.md +44 -3
  97. package/docs/integration/llm-provider.md +1 -1
  98. package/docs/integration/persistence.md +1 -0
  99. package/docs/integration/run-supervisor.md +3 -0
  100. package/docs/integration/tool-development-guide.md +7 -5
  101. package/docs/integration/tool-history.md +43 -17
  102. package/package.json +4 -3
@@ -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(),
@@ -497,6 +504,7 @@ var AgentSpecBudgetPolicy = z.object({
497
504
  });
498
505
  var AgentSpecToolHistoryPolicy = z.object({
499
506
  strategy: z.enum(["per-pair", "per-run", "none"]).optional(),
507
+ retentionMode: z.enum(["drop", "compress"]).optional(),
500
508
  keepLatestToolPairs: z.number().int().nonnegative().optional(),
501
509
  keepLatestRuns: z.number().int().nonnegative().optional(),
502
510
  maxInteractionGroups: z.number().int().nonnegative().optional(),
@@ -549,7 +557,17 @@ var AgentSpecReasoningRetentionPolicy = z.object({
549
557
  var AgentSpecTokenEstimationPolicy = z.object({
550
558
  encoding: z.string().min(1).optional(),
551
559
  avgCharsPerToken: z.number().positive().optional(),
552
- 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()
553
571
  });
554
572
  var AgentSpecSystemReminderTrigger = z.object({
555
573
  kind: z.string().min(1),
@@ -611,12 +629,13 @@ var AgentSpecContextPolicy = z.object({
611
629
  var DEFAULT_CONTEXT_POLICY = {
612
630
  profileId: "agent",
613
631
  budget: {
614
- maxTokens: 12e4,
632
+ maxTokens: 232e3,
615
633
  reservedForResponse: 2400,
616
634
  workingMemoryBudgetPercentage: 0.7
617
635
  },
618
636
  toolHistory: {
619
637
  strategy: "per-run",
638
+ retentionMode: "drop",
620
639
  keepLatestToolPairs: 2,
621
640
  keepLatestRuns: 1,
622
641
  maxInteractionGroups: 12,
@@ -1323,6 +1342,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
1323
1342
  error,
1324
1343
  ...options
1325
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
+ });
1326
1528
 
1327
1529
  // src/context-manager/shared/contextPolicyMerge.ts
1328
1530
  function mergeContextPolicy(params) {
@@ -1354,7 +1556,7 @@ function mergePolicyLayer(base, override) {
1354
1556
  workingMemory: mergeObject(base.workingMemory, override.workingMemory),
1355
1557
  checkpoint: mergeObject(base.checkpoint, override.checkpoint),
1356
1558
  reasoningRetention: mergeObject(base.reasoningRetention, override.reasoningRetention),
1357
- tokenEstimation: mergeObject(base.tokenEstimation, override.tokenEstimation),
1559
+ tokenEstimation: mergeTokenEstimation(base.tokenEstimation, override.tokenEstimation),
1358
1560
  systemReminder: mergeSystemReminder(base.systemReminder, override.systemReminder),
1359
1561
  contextTrace: mergeObject(base.contextTrace, override.contextTrace)
1360
1562
  };
@@ -1389,6 +1591,17 @@ function mergeToolOutput(base, override) {
1389
1591
  observationGovernance: mergeObject(base?.observationGovernance, override?.observationGovernance)
1390
1592
  };
1391
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
+ }
1392
1605
 
1393
1606
  // src/context-manager/shared/context-trace.ts
1394
1607
  var ContextTraceCollector = class _ContextTraceCollector {
@@ -1398,6 +1611,9 @@ var ContextTraceCollector = class _ContextTraceCollector {
1398
1611
  effectivePolicy;
1399
1612
  totalBudget;
1400
1613
  originalCount;
1614
+ tokenCalibration;
1615
+ remoteTokenCount;
1616
+ tokenComponents;
1401
1617
  events = [];
1402
1618
  overflowed = false;
1403
1619
  constructor(options) {
@@ -1407,6 +1623,8 @@ var ContextTraceCollector = class _ContextTraceCollector {
1407
1623
  this.effectivePolicy = options.effectivePolicy;
1408
1624
  this.totalBudget = options.totalBudget;
1409
1625
  this.originalCount = options.originalCount;
1626
+ this.tokenCalibration = options.tokenCalibration;
1627
+ this.remoteTokenCount = options.remoteTokenCount;
1410
1628
  }
1411
1629
  static create(options) {
1412
1630
  if (options.policy?.enabled !== true) {
@@ -1446,10 +1664,20 @@ var ContextTraceCollector = class _ContextTraceCollector {
1446
1664
  tokens: this.includeTokenBreakdown ? state.tokens : 0,
1447
1665
  kept,
1448
1666
  reason: buildDecisionReason(state, kept),
1449
- ...state.replacementSourceIds ? { replacementSourceIds: [...state.replacementSourceIds] } : {}
1667
+ ...state.replacementSourceIds ? { replacementSourceIds: [...state.replacementSourceIds] } : {},
1668
+ ...this.includeTokenBreakdown && state.tokenCalibration ? { tokenCalibration: state.tokenCalibration } : {}
1450
1669
  });
1451
1670
  }
1452
1671
  }
1672
+ recordRemoteTokenCount(trace) {
1673
+ this.remoteTokenCount = trace;
1674
+ }
1675
+ recordTokenComponents(components) {
1676
+ if (!this.includeTokenBreakdown) {
1677
+ return;
1678
+ }
1679
+ this.tokenComponents = [...components];
1680
+ }
1453
1681
  build(finalMessages, finalTokens) {
1454
1682
  return {
1455
1683
  enabled: true,
@@ -1462,6 +1690,9 @@ var ContextTraceCollector = class _ContextTraceCollector {
1462
1690
  originalCount: this.originalCount,
1463
1691
  finalCount: finalMessages.length,
1464
1692
  finalTokens,
1693
+ ...this.tokenCalibration ? { tokenCalibration: this.tokenCalibration } : {},
1694
+ ...this.remoteTokenCount ? { remoteTokenCount: this.remoteTokenCount } : {},
1695
+ ...this.tokenComponents ? { tokenComponents: [...this.tokenComponents] } : {},
1465
1696
  truncated: this.originalCount !== finalMessages.length,
1466
1697
  events: [...this.events]
1467
1698
  };
@@ -1772,6 +2003,161 @@ function findLastIndex(items, predicate) {
1772
2003
  return -1;
1773
2004
  }
1774
2005
 
2006
+ // src/context-manager/shared/preprocessors/currentTurnMessageAssembler.ts
2007
+ var CurrentTurnMessageAssembler = class extends BasePreprocessor {
2008
+ name = "CurrentTurnMessageAssembler";
2009
+ description = "Assembles current-turn fences into system_prompt and user_input messages";
2010
+ priority = 10;
2011
+ fenceRegistry;
2012
+ constructor(options) {
2013
+ super();
2014
+ this.fenceRegistry = options.fenceRegistry;
2015
+ }
2016
+ async process(messages, _context) {
2017
+ const systemResult = assembleSystemPrompt({ messages, fenceRegistry: this.fenceRegistry });
2018
+ const userResult = assembleCurrentUserInput({
2019
+ messages: systemResult.messages,
2020
+ fenceRegistry: this.fenceRegistry
2021
+ });
2022
+ const modifiedCount = systemResult.modifiedCount + userResult.modifiedCount;
2023
+ return this.createResult(
2024
+ messages,
2025
+ userResult.messages,
2026
+ modifiedCount > 0 ? ["current_turn_message_assembly"] : [],
2027
+ modifiedCount
2028
+ );
2029
+ }
2030
+ };
2031
+ function assembleSystemPrompt(params) {
2032
+ const systemIndex = params.messages.findIndex(
2033
+ (message) => message.role === "system" && message.type === "system_prompt"
2034
+ );
2035
+ if (systemIndex === -1) {
2036
+ return { messages: [...params.messages], modifiedCount: 0 };
2037
+ }
2038
+ const fences = collectAdjacentFences({
2039
+ messages: params.messages,
2040
+ startIndex: systemIndex + 1,
2041
+ direction: 1,
2042
+ fenceRegistry: params.fenceRegistry,
2043
+ matches: (descriptor) => descriptor.llmRole === "system" && descriptor.placement === "after-system"
2044
+ });
2045
+ if (fences.length === 0) {
2046
+ return { messages: [...params.messages], modifiedCount: 0 };
2047
+ }
2048
+ const indexesToRemove = new Set(fences.map((fence) => fence.index));
2049
+ const systemPrompt = params.messages[systemIndex];
2050
+ const assembledSystemPrompt = {
2051
+ ...systemPrompt,
2052
+ content: [
2053
+ systemPrompt.content,
2054
+ ...fences.map(formatFence)
2055
+ ].join("\n\n"),
2056
+ metadata: {
2057
+ ...systemPrompt.metadata,
2058
+ assembledFenceKinds: fences.map((fence) => fence.message.metadata?.fenceKind).filter((kind) => typeof kind === "string")
2059
+ }
2060
+ };
2061
+ return {
2062
+ messages: params.messages.map(
2063
+ (message, index) => index === systemIndex ? assembledSystemPrompt : message
2064
+ ).filter((_, index) => !indexesToRemove.has(index)),
2065
+ modifiedCount: fences.length + 1
2066
+ };
2067
+ }
2068
+ function assembleCurrentUserInput(params) {
2069
+ const currentUserIndex = findLastUserInputIndex(params.messages);
2070
+ if (currentUserIndex === -1) {
2071
+ return { messages: [...params.messages], modifiedCount: 0 };
2072
+ }
2073
+ const beforeFences = collectAdjacentFences({
2074
+ messages: params.messages,
2075
+ startIndex: currentUserIndex - 1,
2076
+ direction: -1,
2077
+ fenceRegistry: params.fenceRegistry,
2078
+ matches: (descriptor) => isUserCurrentTurnPlacement(descriptor, "before-current-user")
2079
+ }).reverse();
2080
+ const afterFences = collectAdjacentFences({
2081
+ messages: params.messages,
2082
+ startIndex: currentUserIndex + 1,
2083
+ direction: 1,
2084
+ fenceRegistry: params.fenceRegistry,
2085
+ matches: (descriptor) => isUserCurrentTurnPlacement(descriptor, "after-current-user")
2086
+ });
2087
+ if (beforeFences.length === 0 && afterFences.length === 0) {
2088
+ return { messages: [...params.messages], modifiedCount: 0 };
2089
+ }
2090
+ const indexesToRemove = /* @__PURE__ */ new Set([
2091
+ ...beforeFences.map((fence) => fence.index),
2092
+ ...afterFences.map((fence) => fence.index)
2093
+ ]);
2094
+ const currentUser = params.messages[currentUserIndex];
2095
+ const assembledUser = {
2096
+ ...currentUser,
2097
+ content: [
2098
+ ...beforeFences.map(formatFence),
2099
+ wrapUserRequest(currentUser.content),
2100
+ ...afterFences.map(formatFence)
2101
+ ].join("\n\n"),
2102
+ metadata: {
2103
+ ...currentUser.metadata,
2104
+ assembledFenceKinds: [
2105
+ ...beforeFences.map((fence) => fence.message.metadata?.fenceKind),
2106
+ ...afterFences.map((fence) => fence.message.metadata?.fenceKind)
2107
+ ].filter((kind) => typeof kind === "string")
2108
+ }
2109
+ };
2110
+ return {
2111
+ messages: params.messages.map(
2112
+ (message, index) => index === currentUserIndex ? assembledUser : message
2113
+ ).filter((_, index) => !indexesToRemove.has(index)),
2114
+ modifiedCount: indexesToRemove.size + 1
2115
+ };
2116
+ }
2117
+ function findLastUserInputIndex(messages) {
2118
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
2119
+ const message = messages[index];
2120
+ if (message.role === "user" && message.type === "user_input") {
2121
+ return index;
2122
+ }
2123
+ }
2124
+ return -1;
2125
+ }
2126
+ function collectAdjacentFences(params) {
2127
+ const result = [];
2128
+ for (let index = params.startIndex; index >= 0 && index < params.messages.length; index += params.direction) {
2129
+ const message = params.messages[index];
2130
+ if (message.type !== "context_injection") {
2131
+ break;
2132
+ }
2133
+ const fenceKind = message.metadata?.fenceKind;
2134
+ if (!fenceKind) {
2135
+ break;
2136
+ }
2137
+ const descriptor = params.fenceRegistry.get(fenceKind);
2138
+ if (!descriptor || !params.matches(descriptor)) {
2139
+ break;
2140
+ }
2141
+ result.push({ index, message, descriptor });
2142
+ }
2143
+ return result;
2144
+ }
2145
+ function isUserCurrentTurnPlacement(descriptor, placement) {
2146
+ return descriptor.llmRole === "user" && descriptor.placement === placement;
2147
+ }
2148
+ function formatFence(fence) {
2149
+ return fence.descriptor.formatter(fence.message.content, fence.message.metadata?.fenceAttrs ?? {});
2150
+ }
2151
+ function wrapUserRequest(content) {
2152
+ const trimmed = content.trim();
2153
+ if (/<user_request(?:\s[^>]*)?>[\s\S]*<\/user_request>/.test(trimmed)) {
2154
+ return trimmed;
2155
+ }
2156
+ return `<user_request>
2157
+ ${trimmed}
2158
+ </user_request>`;
2159
+ }
2160
+
1775
2161
  // src/context-manager/shared/providers/base.ts
1776
2162
  var TOOL_HISTORY_OVERFLOW_ERROR_CODE = "TOOL_HISTORY_OVERFLOW";
1777
2163
  var SUMMARIZATION_FAILED_ERROR_CODE = "SUMMARIZATION_FAILED";
@@ -2574,7 +2960,7 @@ __export(config_exports, {
2574
2960
  var AGENT_CONTEXT_BUILDER_CONFIG = {
2575
2961
  // === 绝对Token限制设置 ===
2576
2962
  /** 默认最大Token预算上限 */
2577
- DEFAULT_MAX_TOKENS: 12e4,
2963
+ DEFAULT_MAX_TOKENS: 232e3,
2578
2964
  /** 响应预留Token数 */
2579
2965
  RESERVED_FOR_RESPONSE: 2400,
2580
2966
  // === Agent专用工作记忆填充策略 ===
@@ -2883,7 +3269,11 @@ var AgentCoreContextProvider = class extends BaseContextProvider2 {
2883
3269
  state.processedContent = processedContent;
2884
3270
  state.contentType = contentType;
2885
3271
  state.phase = "CORE_CONTEXT";
2886
- state.tokens = context.estimateTokens({ ...msg, content: processedContent });
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
+ }
2887
3277
  coreTokens += state.tokens;
2888
3278
  processedCount++;
2889
3279
  this.debug(`\u2705 \u6807\u8BB0\u4E3A\u6838\u5FC3\u6D88\u606F`, {
@@ -3187,6 +3577,7 @@ var ToolPairMatcher = class {
3187
3577
  constructor(config) {
3188
3578
  this.config = config;
3189
3579
  }
3580
+ config;
3190
3581
  /**
3191
3582
  * 判断是否为"预处理阶段压缩的工具历史摘要消息"
3192
3583
  * - 该类消息不再是 tool_calls/tool_output 的原始结构,而是 assistant 的自然语言记录
@@ -3367,6 +3758,7 @@ var ToolPairTruncator = class {
3367
3758
  constructor(config) {
3368
3759
  this.config = config;
3369
3760
  }
3761
+ config;
3370
3762
  /**
3371
3763
  * 智能截断超大的工具对
3372
3764
  *
@@ -3963,7 +4355,7 @@ var AgentWorkingMemoryProvider = class extends BaseContextProvider2 {
3963
4355
  let workingMemoryTokens = coreTokens;
3964
4356
  let processedCount = 0;
3965
4357
  const strategiesApplied = [];
3966
- const workingMemoryBudget = Math.floor(availableBudget * config.WORKING_MEMORY_BUDGET_PERCENTAGE);
4358
+ const workingMemoryBudget = Math.floor(context.totalBudget * config.WORKING_MEMORY_BUDGET_PERCENTAGE);
3967
4359
  const remainingBudget = workingMemoryBudget - coreTokens;
3968
4360
  if (remainingBudget <= 0 && config.MIN_TOOL_INTERACTIONS_TO_KEEP <= 0) {
3969
4361
  this.debug("\u26A0\uFE0F \u6838\u5FC3\u4E0A\u4E0B\u6587\u5DF2\u7528\u5C3D\u9884\u7B97\uFF0C\u8DF3\u8FC7\u5DE5\u4F5C\u8BB0\u5FC6\u586B\u5145", {
@@ -4098,6 +4490,7 @@ var Logger = class {
4098
4490
  constructor(moduleName) {
4099
4491
  this.moduleName = moduleName;
4100
4492
  }
4493
+ moduleName;
4101
4494
  debug(message, data) {
4102
4495
  this.log(0 /* DEBUG */, "debug", message, data);
4103
4496
  }
@@ -4345,6 +4738,7 @@ var DefaultTokenizerPort = class {
4345
4738
  constructor(config = {}) {
4346
4739
  this.config = config;
4347
4740
  }
4741
+ config;
4348
4742
  estimateText(text, _modelId) {
4349
4743
  return TokenCalculator.estimateTokens(text, {
4350
4744
  encoding: this.config.encoding,
@@ -4380,7 +4774,7 @@ async function runContextPipeline(options) {
4380
4774
  message,
4381
4775
  originalIndex: index,
4382
4776
  action: "skip",
4383
- tokens: estimateTokens(message)
4777
+ ...estimateTokens(message)
4384
4778
  }));
4385
4779
  const providers = providerRegistry.getAllProviders();
4386
4780
  let availableBudget = totalBudget;
@@ -4456,7 +4850,7 @@ async function runContextPipeline(options) {
4456
4850
  buildStats.messageStats.afterWorkingMemory = states.filter((state) => state.action.startsWith("keep_")).length;
4457
4851
  buildStats.messageStats.afterSummarization = states.filter((state) => state.action !== "skip").length;
4458
4852
  const finalMessages = generateFinalMessages(states);
4459
- const finalTokens = finalMessages.reduce((total, message) => total + estimateTokens(message), 0);
4853
+ const finalTokens = finalMessages.reduce((total, message) => total + estimateTokens(message).tokens, 0);
4460
4854
  contextTrace?.recordMessageDecisions(states);
4461
4855
  return {
4462
4856
  finalMessages,
@@ -4509,6 +4903,85 @@ function isFatalProviderError(error) {
4509
4903
  return isContextProviderError(error) && error.code === SUMMARIZATION_FAILED_ERROR_CODE && error.fatal === true;
4510
4904
  }
4511
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
+
4512
4985
  // src/context-manager/shared/context-manager-base.ts
4513
4986
  var ContextManagerBase = class {
4514
4987
  config;
@@ -4517,6 +4990,10 @@ var ContextManagerBase = class {
4517
4990
  logger;
4518
4991
  tokenizer;
4519
4992
  tokenizerModelId;
4993
+ tokenCounter;
4994
+ tokenRoute;
4995
+ remoteCountPolicy;
4996
+ tokenCalibrationState;
4520
4997
  validateConfigFn;
4521
4998
  invalidConfigMessage;
4522
4999
  hasCustomTokenizer;
@@ -4530,6 +5007,10 @@ var ContextManagerBase = class {
4530
5007
  this.hasCustomTokenizer = options.tokenizer !== void 0;
4531
5008
  this.tokenizer = options.tokenizer ?? this.createDefaultTokenizer();
4532
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 ?? {});
4533
5014
  if (!this.validateConfigFn(this.config)) {
4534
5015
  throw new Error(this.invalidConfigMessage);
4535
5016
  }
@@ -4542,7 +5023,85 @@ var ContextManagerBase = class {
4542
5023
  });
4543
5024
  }
4544
5025
  estimateTokens(message) {
4545
- return this.tokenizer.estimateMessage(message, this.tokenizerModelId);
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
+ }
4546
5105
  }
4547
5106
  debug(message, data) {
4548
5107
  if (this.debugMode) {
@@ -4556,7 +5115,13 @@ var ContextManagerBase = class {
4556
5115
  buildStats: options.buildStats,
4557
5116
  providerRegistry: this.providerRegistry,
4558
5117
  providerContext: options.providerContext,
4559
- estimateTokens: (message) => this.estimateTokens(message),
5118
+ estimateTokens: (message) => {
5119
+ const estimate = this.estimateTokensWithCalibrationTrace(message);
5120
+ return {
5121
+ tokens: estimate.tokens,
5122
+ tokenCalibration: estimate.calibrationTrace
5123
+ };
5124
+ },
4560
5125
  getPhaseByProviderName: options.getPhaseByProviderName,
4561
5126
  debug: (message, data) => this.debug(message, data),
4562
5127
  contextTrace: options.contextTrace
@@ -4583,6 +5148,9 @@ var ContextManagerBase = class {
4583
5148
  updateTokenizerModelId(modelId) {
4584
5149
  this.tokenizerModelId = modelId;
4585
5150
  }
5151
+ updateTokenCalibration(input) {
5152
+ this.tokenCalibrationState = buildTokenUsageCalibrationState(input ?? {});
5153
+ }
4586
5154
  };
4587
5155
 
4588
5156
  // src/context-manager/shared/context-result.ts
@@ -4599,7 +5167,9 @@ function buildContextResult(options) {
4599
5167
  coreTypes,
4600
5168
  recommendations,
4601
5169
  events = [],
4602
- contextTrace
5170
+ contextTrace,
5171
+ tokenEstimate,
5172
+ tokenComponents
4603
5173
  } = options;
4604
5174
  const tokenDistribution = calculateTokenDistribution(
4605
5175
  finalMessages,
@@ -4626,7 +5196,9 @@ function buildContextResult(options) {
4626
5196
  recommendations
4627
5197
  },
4628
5198
  events,
4629
- ...contextTrace ? { contextTrace } : {}
5199
+ ...contextTrace ? { contextTrace } : {},
5200
+ ...tokenEstimate ? { tokenEstimate } : {},
5201
+ ...tokenComponents ? { tokenComponents } : {}
4630
5202
  };
4631
5203
  }
4632
5204
  function generateContextRecommendations(stats, options) {
@@ -4670,6 +5242,70 @@ function calculateTokenDistribution(finalMessages, estimateTokens, coreTypes) {
4670
5242
  return tokenDistribution;
4671
5243
  }
4672
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
+
4673
5309
  // src/context-manager/profiles/agent/context/AgentContextManager.ts
4674
5310
  var AgentContextManager = class extends ContextManagerBase {
4675
5311
  constructor(options = {}) {
@@ -4706,6 +5342,13 @@ var AgentContextManager = class extends ContextManagerBase {
4706
5342
  config: this.config,
4707
5343
  debugMode: this.debugMode,
4708
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
+ },
4709
5352
  summarizationCallbacks: callbacks,
4710
5353
  generate,
4711
5354
  agentRequest: request
@@ -4714,9 +5357,10 @@ var AgentContextManager = class extends ContextManagerBase {
4714
5357
  policy: traceOptions?.policy,
4715
5358
  effectivePolicy: traceOptions?.effectiveContextPolicy,
4716
5359
  totalBudget,
4717
- originalCount: preprocessedMessages.length
5360
+ originalCount: preprocessedMessages.length,
5361
+ tokenCalibration: this.getTokenCalibrationTrace()
4718
5362
  });
4719
- const { finalMessages, finalTokens, strategiesApplied, events } = await this.runPipeline({
5363
+ const { finalMessages, finalTokens, strategiesApplied, events, states } = await this.runPipeline({
4720
5364
  messages: preprocessedMessages,
4721
5365
  totalBudget,
4722
5366
  buildStats,
@@ -4724,6 +5368,14 @@ var AgentContextManager = class extends ContextManagerBase {
4724
5368
  getPhaseByProviderName: (providerName) => this.getPhaseByProviderName(providerName),
4725
5369
  contextTrace
4726
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);
4727
5379
  const endTime = performance.now();
4728
5380
  buildStats.totalTime = endTime - startTime;
4729
5381
  const summarizationThreshold2 = this.config.SUMMARIZATION_TRIGGER_THRESHOLD;
@@ -4731,22 +5383,24 @@ var AgentContextManager = class extends ContextManagerBase {
4731
5383
  this.debug("\u2705 [Agent\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5B8C\u6210", {
4732
5384
  \u9884\u5904\u7406\u6D88\u606F: preprocessedMessages.length,
4733
5385
  \u6700\u7EC8\u6D88\u606F: finalMessages.length,
4734
- Token\u4F7F\u7528: finalTokens,
5386
+ Token\u4F7F\u7528: remoteCount.tokens,
4735
5387
  \u603B\u9884\u7B97: totalBudget,
4736
- \u4F7F\u7528\u7387: `${(finalTokens / totalBudget * 100).toFixed(1)}%`,
5388
+ \u4F7F\u7528\u7387: `${(remoteCount.tokens / totalBudget * 100).toFixed(1)}%`,
4737
5389
  \u6458\u8981\u89E6\u53D1\u9608\u503C: `${(summarizationThreshold2 * 100).toFixed(0)}%`,
4738
5390
  \u6458\u8981Token\u9608\u503C: summarizationTokenThreshold2,
4739
5391
  \u603B\u8017\u65F6: `${buildStats.totalTime.toFixed(2)}ms`
4740
5392
  });
4741
5393
  return this.buildFinalResult(
4742
5394
  finalMessages,
4743
- finalTokens,
5395
+ remoteCount.tokens,
4744
5396
  totalBudget,
4745
5397
  preprocessedMessages.length,
4746
5398
  strategiesApplied,
4747
5399
  buildStats,
4748
5400
  events,
4749
- contextTrace?.build(finalMessages, finalTokens)
5401
+ contextTrace?.build(finalMessages, finalTokens),
5402
+ tokenEstimate,
5403
+ tokenComponents
4750
5404
  );
4751
5405
  } catch (error) {
4752
5406
  this.debug("\u274C [Agent\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5931\u8D25", { error });
@@ -4794,7 +5448,7 @@ var AgentContextManager = class extends ContextManagerBase {
4794
5448
  totalTime: 0
4795
5449
  };
4796
5450
  }
4797
- buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], contextTrace) {
5451
+ buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], contextTrace, tokenEstimate, tokenComponents) {
4798
5452
  const recommendations = this.generateRecommendations(buildStats, totalBudget);
4799
5453
  return buildContextResult({
4800
5454
  finalMessages,
@@ -4808,9 +5462,21 @@ var AgentContextManager = class extends ContextManagerBase {
4808
5462
  coreTypes: this.config.CORE_MESSAGE_TYPES,
4809
5463
  recommendations,
4810
5464
  events,
4811
- contextTrace
5465
+ contextTrace,
5466
+ tokenEstimate,
5467
+ tokenComponents
4812
5468
  });
4813
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
+ }
4814
5480
  /**
4815
5481
  * 生成优化建议
4816
5482
  */
@@ -5104,6 +5770,7 @@ __export(orchestration_exports, {
5104
5770
  var preprocessors_exports = {};
5105
5771
  __export(preprocessors_exports, {
5106
5772
  BasePreprocessor: () => BasePreprocessor2,
5773
+ CurrentTurnMessageAssembler: () => CurrentTurnMessageAssembler,
5107
5774
  FenceLifetimePreprocessor: () => FenceLifetimePreprocessor,
5108
5775
  HistoryPurificationPreprocessor: () => HistoryPurificationPreprocessor,
5109
5776
  PreprocessorPipeline: () => PreprocessorPipeline,
@@ -5155,7 +5822,7 @@ var DEFAULT_KEEP_LATEST_RUNS = 1;
5155
5822
  var DEFAULT_MAX_INTERACTION_GROUPS = 12;
5156
5823
  var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
5157
5824
  name = "ToolHistoryCompressorPreprocessor";
5158
- description = "\u5DE5\u5177\u5386\u53F2\u538B\u7F29\u5904\u7406\u5668 - \u5C06\u8F83\u65E9\u7684\u5386\u53F2\u5DE5\u5177\u8C03\u7528\u5BF9\u538B\u7F29\u4E3A\u81EA\u7136\u8BED\u8A00\u8BB0\u5F55\u6D88\u606F";
5825
+ 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";
5159
5826
  priority = 0;
5160
5827
  summarizer = createDefaultToolOutputSummarizer();
5161
5828
  options;
@@ -5163,6 +5830,7 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
5163
5830
  super();
5164
5831
  this.options = {
5165
5832
  strategy: options.strategy ?? "per-run",
5833
+ retentionMode: options.retentionMode ?? "drop",
5166
5834
  keepLatestToolPairs: normalizeNonNegativeInteger4(
5167
5835
  options.keepLatestToolPairs,
5168
5836
  DEFAULT_KEEP_LATEST_TOOL_PAIRS
@@ -5179,7 +5847,7 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
5179
5847
  };
5180
5848
  }
5181
5849
  async process(messages, context) {
5182
- this.debug("\u{1F527} \u5F00\u59CB\u5DE5\u5177\u5386\u53F2\u538B\u7F29\u5904\u7406", {
5850
+ this.debug("\u{1F527} \u5F00\u59CB\u5DE5\u5177\u5386\u53F2\u4FDD\u7559\u5904\u7406", {
5183
5851
  \u539F\u59CB\u6D88\u606F\u6570: messages.length
5184
5852
  }, context);
5185
5853
  const currentRunStartIndex = findCurrentRunStartIndex(messages);
@@ -5189,17 +5857,18 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
5189
5857
  \u5386\u53F2\u6D88\u606F\u6570: historyMessages.length,
5190
5858
  \u5F53\u524D\u8F6E\u6B21\u6D88\u606F\u6570: currentRunMessages.length,
5191
5859
  \u5F53\u524D\u8F6E\u6B21\u8D77\u70B9\u7D22\u5F15: currentRunStartIndex,
5192
- \u5DE5\u5177\u538B\u7F29\u7B56\u7565: this.options.strategy
5860
+ \u5DE5\u5177\u4FDD\u7559\u7B56\u7565: this.options.strategy,
5861
+ \u5386\u53F2\u5DE5\u5177\u4FDD\u7559\u6A21\u5F0F: this.options.retentionMode
5193
5862
  }, context);
5194
- const compressedHistory = this.compressToolCallPairsInHistory(historyMessages, context);
5195
- const finalMessages = [...compressedHistory, ...currentRunMessages];
5863
+ const processedHistory = this.processToolCallPairsInHistory(historyMessages, context);
5864
+ const finalMessages = [...processedHistory, ...currentRunMessages];
5196
5865
  const originalCount = messages.length;
5197
- const compressedCount = finalMessages.length;
5198
- const removedCount = originalCount - compressedCount;
5199
- const appliedStrategies = removedCount > 0 ? ["tool_history_compression"] : [];
5200
- this.debug("\u2705 \u5DE5\u5177\u5386\u53F2\u538B\u7F29\u5B8C\u6210", {
5866
+ const processedCount = finalMessages.length;
5867
+ const removedCount = originalCount - processedCount;
5868
+ const appliedStrategies = removedCount > 0 ? [this.options.retentionMode === "compress" ? "tool_history_compression" : "tool_history_drop"] : [];
5869
+ this.debug("\u2705 \u5DE5\u5177\u5386\u53F2\u4FDD\u7559\u5904\u7406\u5B8C\u6210", {
5201
5870
  \u539F\u59CB\u6D88\u606F: originalCount,
5202
- \u538B\u7F29\u540E\u6D88\u606F: compressedCount,
5871
+ \u5904\u7406\u540E\u6D88\u606F: processedCount,
5203
5872
  \u51CF\u5C11\u6D88\u606F: removedCount,
5204
5873
  Token\u8282\u7701\u4F30\u8BA1: `\u7EA6${removedCount * 50}\u4E2AToken`
5205
5874
  }, context);
@@ -5220,7 +5889,7 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
5220
5889
  }
5221
5890
  return false;
5222
5891
  }
5223
- compressToolCallPairsInHistory(historyMessages, context) {
5892
+ processToolCallPairsInHistory(historyMessages, context) {
5224
5893
  if (historyMessages.length < 2) {
5225
5894
  return historyMessages;
5226
5895
  }
@@ -5241,8 +5910,10 @@ var ToolHistoryCompressorPreprocessor = class extends BasePreprocessor2 {
5241
5910
  if (!group.isComplete || keepAnchorIds.has(group.anchorId)) {
5242
5911
  continue;
5243
5912
  }
5244
- const compressedMessage = this.compressToolInteractionGroup(group, context);
5245
- replacementMap.set(group.assistantIndex, compressedMessage);
5913
+ if (this.options.retentionMode === "compress") {
5914
+ const compressedMessage = this.compressToolInteractionGroup(group, context);
5915
+ replacementMap.set(group.assistantIndex, compressedMessage);
5916
+ }
5246
5917
  for (const messageIndex of group.messageIndexes) {
5247
5918
  messagesToRemove.add(messageIndex);
5248
5919
  }
@@ -5661,6 +6332,7 @@ function createDefaultAgentPreprocessorRegistry(options = {}) {
5661
6332
  registry.register(new ToolReplayProtocolGuardPreprocessor({ policy: options.providerReplay }));
5662
6333
  registry.register(new HistoryPurificationPreprocessor({ logPrefix: "Agent-HistoryPurification" }));
5663
6334
  if (options.fenceRegistry) {
6335
+ registry.register(new CurrentTurnMessageAssembler({ fenceRegistry: options.fenceRegistry }));
5664
6336
  registry.register(new FenceLifetimePreprocessor({ fenceRegistry: options.fenceRegistry }));
5665
6337
  }
5666
6338
  return registry;
@@ -5768,10 +6440,10 @@ var contextBudgetWarningTemplate = (ctx) => {
5768
6440
  return [
5769
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`,
5770
6442
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
5771
- "1. \u8C03\u7528sharedmemory_write\u5DE5\u5177\uFF0C\u5C06\u5F53\u524D\u53D1\u73B0\u3001\u603B\u7ED3\u3001\u601D\u8003\u6216\u8005\u4EFB\u4F55\u91CD\u8981\u4FE1\u606F\u8BE6\u7EC6\u5199\u5165sharedmemory\u3002",
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",
5772
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`,
5773
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',
5774
- "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\u91CD\u8981\u4FE1\u606F\u4F1A\u901A\u8FC7sharedmemory\u4FDD\u5B58\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"
5775
6447
  ].join("\n");
5776
6448
  };
5777
6449
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -6508,6 +7180,27 @@ createConsoleAudit();
6508
7180
  function isRecord7(value) {
6509
7181
  return !!value && typeof value === "object" && !Array.isArray(value);
6510
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
+ }
6511
7204
  function isHistorySummaryEvent2(event) {
6512
7205
  return "type" in event && event.type === "history_summary";
6513
7206
  }
@@ -6620,6 +7313,7 @@ function convertEventToAiMessage(event) {
6620
7313
  }
6621
7314
  })();
6622
7315
  const outputContent = observationFromPayload ?? rawOutput;
7316
+ const observationTruncation = readObservationTruncationMeta(event.metadata?.observationTruncation);
6623
7317
  return {
6624
7318
  id: event.id,
6625
7319
  role: "tool",
@@ -6630,6 +7324,7 @@ function convertEventToAiMessage(event) {
6630
7324
  tool_call_id: event.tool_call_id,
6631
7325
  tool_name: event.tool_name,
6632
7326
  raw_output: rawOutput,
7327
+ ...observationTruncation ? { observationTruncation } : {},
6633
7328
  ...observationFromPayload ? { observation: observationFromPayload } : {}
6634
7329
  }
6635
7330
  };
@@ -6740,7 +7435,8 @@ var AgentMessageOrchestrator = class {
6740
7435
  customConfig: this.baseContextConfig,
6741
7436
  providerRegistry: options.providerRegistry,
6742
7437
  tokenizer: options.tokenizer,
6743
- tokenizerModelId: options.model
7438
+ tokenizerModelId: options.model,
7439
+ tokenCounter: options.tokenCounter
6744
7440
  });
6745
7441
  }
6746
7442
  buildPreprocessorPipelineForRequest(toolManager, request, contextPolicy) {
@@ -6769,13 +7465,44 @@ var AgentMessageOrchestrator = class {
6769
7465
  contextPolicy,
6770
7466
  contextBuilderConfig
6771
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;
6772
7479
  this.agentContextManager = new AgentContextManager({
6773
7480
  debugMode: this.options.processing.debugMode,
6774
7481
  customConfig: contextBuilderConfig,
6775
7482
  providerRegistry,
6776
7483
  tokenizer: this.options.tokenizer,
6777
- tokenizerModelId: this.resolvePreprocessorModel(request)
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
+ }
6778
7493
  });
7494
+ return contextBuilderConfig;
7495
+ }
7496
+ resolveEffectiveContextBudget(contextBuilderConfig) {
7497
+ const maxTokens = contextBuilderConfig.DEFAULT_MAX_TOKENS ?? this.options.tokenBudget.maxTokens;
7498
+ const reservedForResponse = contextBuilderConfig.RESERVED_FOR_RESPONSE ?? this.options.tokenBudget.reservedForResponse;
7499
+ return {
7500
+ maxTokens,
7501
+ reservedForResponse,
7502
+ // 中文备注:ContextManager 接收的是“可放入上下文的输入预算”,不是模型完整窗口。
7503
+ // 因此单个 agent 通过 contextPolicy.budget 覆盖预算时,这里必须同步使用覆盖后的值。
7504
+ totalBudget: maxTokens - reservedForResponse
7505
+ };
6779
7506
  }
6780
7507
  async processAgentConversation(request, history, toolManager, callbacks, extraOptions) {
6781
7508
  const historyCount = history.length;
@@ -6794,7 +7521,8 @@ var AgentMessageOrchestrator = class {
6794
7521
  const allMessages = this.buildCompleteMessageList(request, historyMessages);
6795
7522
  this.debug("Built complete message list", { totalCount: allMessages.length });
6796
7523
  const contextPolicy = this.resolveContextPolicy(request);
6797
- this.applyContextPolicy(request, contextPolicy);
7524
+ const contextBuilderConfig = this.applyContextPolicy(request, contextPolicy);
7525
+ const effectiveContextBudget = this.resolveEffectiveContextBudget(contextBuilderConfig);
6798
7526
  const preprocessorPipeline = this.buildPreprocessorPipelineForRequest(toolManager, request, contextPolicy);
6799
7527
  const modelId = this.resolvePreprocessorModel(request);
6800
7528
  preprocessorPipeline.updateContext({
@@ -6822,7 +7550,8 @@ var AgentMessageOrchestrator = class {
6822
7550
  callbacks,
6823
7551
  void 0,
6824
7552
  extraOptions?.generate,
6825
- contextPolicy
7553
+ contextPolicy,
7554
+ effectiveContextBudget.totalBudget
6826
7555
  );
6827
7556
  this.debug("Context built", { afterContextCount: contextResult.messages.length });
6828
7557
  if (this.options.processing.debugMode) {
@@ -6855,7 +7584,7 @@ var AgentMessageOrchestrator = class {
6855
7584
  processedCount: contextResult.messages.length,
6856
7585
  tokenUsage: {
6857
7586
  estimated: contextResult.tokenUsage.used,
6858
- budget: this.options.tokenBudget.maxTokens,
7587
+ budget: effectiveContextBudget.totalBudget,
6859
7588
  remaining: contextResult.tokenUsage.remaining
6860
7589
  },
6861
7590
  processingStats: contextResult.processingStats,
@@ -6875,13 +7604,13 @@ var AgentMessageOrchestrator = class {
6875
7604
  async runPreprocessorPipeline(preprocessorPipeline, messages) {
6876
7605
  return preprocessorPipeline.process(messages);
6877
7606
  }
6878
- async buildContextFromPreprocessedMessages(request, conversationSession, messages, callbacks, phaseOverride, generate, contextPolicy) {
6879
- const totalBudget = this.options.tokenBudget.maxTokens - this.options.tokenBudget.reservedForResponse;
7607
+ async buildContextFromPreprocessedMessages(request, conversationSession, messages, callbacks, phaseOverride, generate, contextPolicy, totalBudget) {
7608
+ const resolvedTotalBudget = totalBudget ?? this.options.tokenBudget.maxTokens - this.options.tokenBudget.reservedForResponse;
6880
7609
  const contextResult = await this.agentContextManager.buildContextFromPreprocessedMessages(
6881
7610
  request,
6882
7611
  conversationSession,
6883
7612
  messages,
6884
- totalBudget,
7613
+ resolvedTotalBudget,
6885
7614
  callbacks,
6886
7615
  phaseOverride,
6887
7616
  generate,
@@ -6962,22 +7691,33 @@ var BaseAgentTask = class {
6962
7691
  });
6963
7692
  }
6964
7693
  messages.push(...fenceMessages["after-system"]);
7694
+ const currentUserIndex = findCurrentUserInputIndex(history, request.query);
7695
+ const historyBeforeCurrentUser = currentUserIndex === -1 ? history : history.slice(0, currentUserIndex);
7696
+ const currentUserMessage = currentUserIndex === -1 ? this.createCurrentUserMessage(request.query) : history[currentUserIndex];
7697
+ const historyAfterCurrentUser = currentUserIndex === -1 ? [] : history.slice(currentUserIndex + 1);
7698
+ messages.push(...historyBeforeCurrentUser);
6965
7699
  messages.push(...fenceMessages["before-current-user"]);
6966
- const hasUserMessageInHistory = history.some((m) => m.role === "user");
6967
- if (!hasUserMessageInHistory && request.query && request.query.trim()) {
6968
- messages.push({
6969
- id: generateMessageId(),
6970
- role: "user",
6971
- type: "user_input",
6972
- content: request.query.trim(),
6973
- timestamp: Date.now()
6974
- });
7700
+ if (currentUserMessage) {
7701
+ messages.push(currentUserMessage);
6975
7702
  }
6976
7703
  messages.push(...fenceMessages["after-current-user"]);
6977
- messages.push(...history);
7704
+ messages.push(...historyAfterCurrentUser);
6978
7705
  this.insertAfterLastToolResult(messages, fenceMessages["after-last-tool-result"]);
6979
7706
  return messages;
6980
7707
  }
7708
+ createCurrentUserMessage(query) {
7709
+ const content = query.trim();
7710
+ if (!content) {
7711
+ return null;
7712
+ }
7713
+ return {
7714
+ id: generateMessageId(),
7715
+ role: "user",
7716
+ type: "user_input",
7717
+ content,
7718
+ timestamp: Date.now()
7719
+ };
7720
+ }
6981
7721
  createFenceMessages(fences) {
6982
7722
  const grouped = {
6983
7723
  "after-system": [],
@@ -7042,6 +7782,19 @@ function findLastIndex2(items, predicate) {
7042
7782
  }
7043
7783
  return -1;
7044
7784
  }
7785
+ function findCurrentUserInputIndex(history, query) {
7786
+ const normalizedQuery = query.trim();
7787
+ if (!normalizedQuery) {
7788
+ return -1;
7789
+ }
7790
+ for (let index = history.length - 1; index >= 0; index -= 1) {
7791
+ const message = history[index];
7792
+ if (message.role === "user" && message.type === "user_input" && message.content.trim() === normalizedQuery) {
7793
+ return index;
7794
+ }
7795
+ }
7796
+ return -1;
7797
+ }
7045
7798
 
7046
7799
  // src/context-manager/profiles/agent/tools/index.ts
7047
7800
  var tools_exports2 = {};
@@ -7661,6 +8414,7 @@ var ContextManager = class extends ContextManagerBase {
7661
8414
  providerContext,
7662
8415
  getPhaseByProviderName: (providerName) => this.getPhaseByProviderName(providerName)
7663
8416
  });
8417
+ const tokenEstimate = this.buildContextTokenEstimate(finalMessages, finalTokens);
7664
8418
  const endTime = performance.now();
7665
8419
  buildStats.totalTime = endTime - startTime;
7666
8420
  const summarizationThreshold2 = this.config.SUMMARIZATION_TRIGGER_THRESHOLD;
@@ -7682,8 +8436,9 @@ var ContextManager = class extends ContextManagerBase {
7682
8436
  messages.length,
7683
8437
  strategiesApplied,
7684
8438
  buildStats,
7685
- events
8439
+ events,
7686
8440
  // 🔥 传递收集的事件
8441
+ tokenEstimate
7687
8442
  );
7688
8443
  } catch (error) {
7689
8444
  this.debug("\u274C [Chat\u4E0A\u4E0B\u6587\u7BA1\u7406\u5668] \u4E0A\u4E0B\u6587\u6784\u5EFA\u5931\u8D25", { error });
@@ -7719,7 +8474,7 @@ var ContextManager = class extends ContextManagerBase {
7719
8474
  totalTime: 0
7720
8475
  };
7721
8476
  }
7722
- buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = []) {
8477
+ buildFinalResult(finalMessages, finalTokens, totalBudget, originalCount, strategiesApplied, buildStats, events = [], tokenEstimate) {
7723
8478
  const recommendations = this.generateRecommendations(buildStats, totalBudget);
7724
8479
  return buildContextResult({
7725
8480
  finalMessages,
@@ -7732,9 +8487,19 @@ var ContextManager = class extends ContextManagerBase {
7732
8487
  estimateTokens: (message) => this.estimateTokens(message),
7733
8488
  coreTypes: this.config.CORE_MESSAGE_TYPES,
7734
8489
  recommendations,
7735
- events
8490
+ events,
8491
+ tokenEstimate
7736
8492
  });
7737
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
+ }
7738
8503
  /**
7739
8504
  * 生成优化建议
7740
8505
  */
@@ -8641,6 +9406,6 @@ function convertEventsToChatMessages(events) {
8641
9406
  return messages;
8642
9407
  }
8643
9408
 
8644
- export { AGENT_CONSTANTS, AGENT_CONTEXT_BUILDER_CONFIG, AISummaryGenerator, BaseContextProvider2 as BaseContextProvider, BaseConversationalTask, BasePreprocessor, CHECKPOINT_MARKER_TYPE, ContextProviderRegistry3 as ChatContextProviderRegistry, CoreContextProvider as ChatCoreContextProvider, MessageOrchestrator as ChatMessageOrchestrator, WorkingMemoryProvider as ChatWorkingMemoryProvider, ContextProviderError, ContextProviderRegistry, ContextTraceCollector, DEFAULT_MUST_KEEP_POLICY, FenceLifetimePreprocessor, HistoryPurificationPreprocessor, SUMMARIZATION_FAILED_ERROR_CODE, SummarizationCandidateSelector, SummarizationProvider, SummarizationStateUtils, SummarizationTrigger, TOOL_HISTORY_OVERFLOW_ERROR_CODE, config_exports as agentConfig, context_exports as agentContext, contracts_exports as agentContracts, orchestration_exports as agentOrchestration, preprocessors_exports as agentPreprocessors, agentSpecToContextBuilderConfig, agentSpecToRuntimeOptions, tasks_exports as agentTasks, tools_exports2 as agentTools, utils_exports as agentUtils, aiMessageToChatMessage, buildGenerateRequestFromAgentRequest, chatMessageToAiMessage, contextPolicyToContextBuilderConfig, contextPolicyToExecutionOptions, contextPolicyToMustKeepPolicy, contextPolicyToPreprocessorOptions, contextPolicyToProviderOptions, contextPolicyToRuntimeOptions, contextPolicyToSystemReminderOptions, convertEventToChatMessage, convertEventsToChatMessages, createFenceRegistry, createMessageFormatter, findMatchingTruncationRule, formatAgentLlmMessages, getDefaultTokenConfig, isContextProviderError, mergeContextPolicy, messageFormatter };
9409
+ export { AGENT_CONSTANTS, AGENT_CONTEXT_BUILDER_CONFIG, AISummaryGenerator, BaseContextProvider2 as BaseContextProvider, BaseConversationalTask, BasePreprocessor, CHECKPOINT_MARKER_TYPE, ContextProviderRegistry3 as ChatContextProviderRegistry, CoreContextProvider as ChatCoreContextProvider, MessageOrchestrator as ChatMessageOrchestrator, WorkingMemoryProvider as ChatWorkingMemoryProvider, ContextProviderError, ContextProviderRegistry, ContextTraceCollector, CurrentTurnMessageAssembler, DEFAULT_MUST_KEEP_POLICY, FenceLifetimePreprocessor, HistoryPurificationPreprocessor, SUMMARIZATION_FAILED_ERROR_CODE, SummarizationCandidateSelector, SummarizationProvider, SummarizationStateUtils, SummarizationTrigger, TOOL_HISTORY_OVERFLOW_ERROR_CODE, config_exports as agentConfig, context_exports as agentContext, contracts_exports as agentContracts, orchestration_exports as agentOrchestration, preprocessors_exports as agentPreprocessors, agentSpecToContextBuilderConfig, agentSpecToRuntimeOptions, tasks_exports as agentTasks, tools_exports2 as agentTools, utils_exports as agentUtils, aiMessageToChatMessage, buildGenerateRequestFromAgentRequest, chatMessageToAiMessage, contextPolicyToContextBuilderConfig, contextPolicyToExecutionOptions, contextPolicyToMustKeepPolicy, contextPolicyToPreprocessorOptions, contextPolicyToProviderOptions, contextPolicyToRuntimeOptions, contextPolicyToSystemReminderOptions, convertEventToChatMessage, convertEventsToChatMessages, createFenceRegistry, createMessageFormatter, findMatchingTruncationRule, formatAgentLlmMessages, getDefaultTokenConfig, isContextProviderError, mergeContextPolicy, messageFormatter };
8645
9410
  //# sourceMappingURL=context-manager.js.map
8646
9411
  //# sourceMappingURL=context-manager.js.map