@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
@@ -1,13 +1,16 @@
1
- import { A as AiMessage, a as AssistantMessage } from './messages-XthmnHZ3.cjs';
2
- import { C as ChatMessage, P as ProviderContext$2, M as MessageProcessingState, B as BaseContextProvider$2, a as ProviderResult, I as IContextProvider$2, b as ContextTraceCollector, S as SummarizationCallbacks, G as GenerateRequest, c as GenerateResponse, d as ContextTrace } from './context-trace-HE2qY5Q-.cjs';
3
- export { e as ChatDocumentMetadata, f as ChatProjectMetadata, g as ChatUserQuote, h as ContextProviderError, i as ContextProviderErrorCode, j as ContextProviderErrorOptions, k as ContextTraceEvent, l as ContextTraceMessageDecisionEvent, m as ContextTraceProviderEvent, n as MessageRole, o as MessageType, R as RecentRejection, p as SUMMARIZATION_FAILED_ERROR_CODE, T as TOOL_HISTORY_OVERFLOW_ERROR_CODE, q as isContextProviderError } from './context-trace-HE2qY5Q-.cjs';
1
+ import { A as AiMessage, a as AssistantMessage } from './messages-Br5SiLD3.cjs';
2
+ import { C as ChatMessage, P as ProviderContext$2, M as MessageProcessingState, B as BaseContextProvider$2, a as ProviderResult, I as IContextProvider$2, R as RemoteTokenCountTrace, b as ContextTraceCollector, S as SummarizationCallbacks, G as GenerateRequest, c as GenerateResponse, d as ContextTrace } from './context-trace-DrtvKac4.cjs';
3
+ export { e as ChatDocumentMetadata, f as ChatProjectMetadata, g as ChatUserQuote, h as ContextProviderError, i as ContextProviderErrorCode, j as ContextProviderErrorOptions, k as ContextTraceEvent, l as ContextTraceMessageDecisionEvent, m as ContextTraceProviderEvent, n as MessageRole, o as MessageType, p as RecentRejection, q as SUMMARIZATION_FAILED_ERROR_CODE, T as TOOL_HISTORY_OVERFLOW_ERROR_CODE, r as isContextProviderError } from './context-trace-DrtvKac4.cjs';
4
4
  export { C as CHECKPOINT_MARKER_TYPE } from './checkpointMarker-DAI3wUQu.cjs';
5
- import { u as AgentSpecToolOutputPolicy, l as AgentSpecProviderReplayPolicy, d as AgentSpecCheckpointPolicy, n as AgentSpecSummarizationPolicy, g as AgentSpecContextTracePolicy, p as AgentSpecSystemReminderPolicy, a as AgentSpec, e as AgentSpecContextPolicy, f as AgentSpecContextPolicyInput } from './agentSpec-EkmviZjy.cjs';
6
- import { e as RuntimeEvent } from './todo-B1PmDlp3.cjs';
7
- import { T as TokenizerPort } from './tokenizer-DH_JXv-H.cjs';
8
- import { a as ToolArgs } from './toolContracts-CLkQmhTG.cjs';
5
+ import { A as AgentSpecToolOutputPolicy, a as AgentSpecProviderReplayPolicy, b as AgentSpecCheckpointPolicy, c as AgentSpecSummarizationPolicy, d as AgentSpecContextTracePolicy, e as AgentSpecSystemReminderPolicy, f as AgentSpec, g as AgentSpecContextPolicy, h as AgentSpecContextPolicyInput, i as AgentSpecTokenEstimationPolicy, C as ContextTokenComponent } from './token-accounting-CwpSPg4y.cjs';
6
+ import { R as RuntimeEvent } from './todo-Ca8llpRQ.cjs';
7
+ import { T as TokenRoute } from './token-usage-CqwT7-5K.cjs';
8
+ import { T as TokenUsageCalibrationTrace, a as TokenUsageCalibrationSample, C as ContextBuildTokenEstimate } from './token-calibration-Cxv6dDYF.cjs';
9
+ import { T as TokenCounterPort } from './token-counter-CFfP8PQb.cjs';
10
+ import { T as TokenizerPort } from './tokenizer-DoGsBE3A.cjs';
11
+ import { T as ToolArgs } from './toolContracts-Bm3EZ1UM.cjs';
9
12
  import 'zod';
10
- import './ai-engine.types-BpeU_XQG.cjs';
13
+ import './ai-engine.types-CeLoM624.cjs';
11
14
 
12
15
  type FenceLlmRole = 'user' | 'system';
13
16
  type FencePlacement = 'after-system' | 'before-current-user' | 'after-current-user' | 'after-last-tool-result';
@@ -118,6 +121,7 @@ interface AgentContextBuilderConfigOverrides {
118
121
  interface AgentSpecPreprocessorOptions {
119
122
  toolHistory?: {
120
123
  strategy?: 'per-pair' | 'per-run' | 'none';
124
+ retentionMode?: 'drop' | 'compress';
121
125
  keepLatestToolPairs?: number;
122
126
  keepLatestRuns?: number;
123
127
  maxInteractionGroups?: number;
@@ -243,6 +247,26 @@ declare class FenceLifetimePreprocessor extends BasePreprocessor$1 {
243
247
  process(messages: AiMessage[], context: PreprocessorContext$1): Promise<PreprocessorResult$1>;
244
248
  }
245
249
 
250
+ interface CurrentTurnMessageAssemblerOptions {
251
+ fenceRegistry: FenceRegistry;
252
+ }
253
+ /**
254
+ * 组装当前轮 prompt block。
255
+ *
256
+ * 中文说明:
257
+ * - formatter 只负责把单条消息转成 wire 形态,不负责猜测相邻消息是否应该合并;
258
+ * - 当前轮 system-side fence 在这里合入 system_prompt;
259
+ * - 当前轮 user-side fence 在这里合入同一条 user_input,未注入的 fence 不产生空标签。
260
+ */
261
+ declare class CurrentTurnMessageAssembler extends BasePreprocessor$1 {
262
+ readonly name = "CurrentTurnMessageAssembler";
263
+ readonly description = "Assembles current-turn fences into system_prompt and user_input messages";
264
+ readonly priority = 10;
265
+ private readonly fenceRegistry;
266
+ constructor(options: CurrentTurnMessageAssemblerOptions);
267
+ process(messages: AiMessage[], _context: PreprocessorContext$1): Promise<PreprocessorResult$1>;
268
+ }
269
+
246
270
  interface SummarizationConfig {
247
271
  SUMMARIZATION_TRIGGER_THRESHOLD: number;
248
272
  SUMMARY_OLDEST_MESSAGES_PERCENTAGE: number;
@@ -372,6 +396,11 @@ interface AgentConfig {
372
396
  defaultTools: string[];
373
397
  timeoutMs: number;
374
398
  debug: boolean;
399
+ /**
400
+ * @deprecated 不再参与上下文裁剪。
401
+ * 中文备注:Agent 历史保留现在由 `contextPolicy.budget` 与 `contextPolicy.toolHistory`
402
+ * 共同决定;保留这个字段只是为了兼容可能读取 `DEFAULT_AGENT_CONFIG` 的旧接入方。
403
+ */
375
404
  maxHistoryLength: number;
376
405
  tokenBudget: {
377
406
  maxTokens: number;
@@ -821,8 +850,8 @@ declare class AgentCoreContextProvider extends BaseContextProvider$1 {
821
850
  * @file src/agent/context/providers/AgentWorkingMemoryProvider.ts
822
851
  * @description Agent专用工作记忆填充层Provider - 第二阶段上下文构建
823
852
  *
824
- * 🎯 职责: 实现Agent的P1-P4优先级填充策略
825
- * 📖 策略: P1(工具交互) > P2(纯文本对话) > P3(历史工具交互) > P4(循环填充)
853
+ * 🎯 职责: 实现Agent的P1-P3优先级填充策略
854
+ * 📖 策略: P1(工具交互) > P2(纯文本对话) > P3(历史工具交互)
826
855
  * ✨ Agent特性: 工具调用优先级、配对保留策略
827
856
  * 🔧 核心逻辑: 保留工具调用时,必须确保其对应的另一半也被保留
828
857
  */
@@ -947,6 +976,26 @@ interface RunContextPipelineResult {
947
976
  states: MessageProcessingState[];
948
977
  }
949
978
 
979
+ interface TokenUsageCalibrationState {
980
+ enabled: boolean;
981
+ route?: TokenRoute;
982
+ sampleCount: number;
983
+ coefficient?: number;
984
+ minSamples?: number;
985
+ minCoefficient?: number;
986
+ maxCoefficient?: number;
987
+ sampleLedgerEntryIds?: string[];
988
+ }
989
+ interface CalibrateTokenEstimateInput {
990
+ localEstimateTokens: number;
991
+ state: TokenUsageCalibrationState;
992
+ }
993
+ interface CalibratedTokenEstimate {
994
+ tokens: number;
995
+ trace: TokenUsageCalibrationTrace;
996
+ }
997
+ declare function calibrateTokenEstimate(input: CalibrateTokenEstimateInput): CalibratedTokenEstimate;
998
+
950
999
  interface ContextManagerBaseConfig {
951
1000
  AVG_CHARS_PER_TOKEN: number;
952
1001
  TOOL_CALL_OVERHEAD_TOKENS?: number;
@@ -958,6 +1007,14 @@ interface ContextManagerBaseOptions<TConfig, TRegistry> {
958
1007
  providerRegistry?: TRegistry;
959
1008
  tokenizer?: TokenizerPort;
960
1009
  tokenizerModelId?: string;
1010
+ tokenCounter?: TokenCounterPort;
1011
+ tokenRoute?: TokenRoute;
1012
+ remoteCount?: AgentSpecTokenEstimationPolicy['remoteCount'];
1013
+ tokenCalibration?: {
1014
+ policy?: AgentSpecTokenEstimationPolicy['calibration'];
1015
+ route?: TokenRoute;
1016
+ samples?: readonly TokenUsageCalibrationSample[];
1017
+ };
961
1018
  }
962
1019
  interface ContextManagerBaseInit<TConfig, TRegistry> {
963
1020
  defaultConfig: TConfig;
@@ -973,12 +1030,31 @@ declare abstract class ContextManagerBase<TConfig extends ContextManagerBaseConf
973
1030
  protected logger: Logger;
974
1031
  protected tokenizer: TokenizerPort;
975
1032
  protected tokenizerModelId?: string;
1033
+ private readonly tokenCounter?;
1034
+ private readonly tokenRoute?;
1035
+ private readonly remoteCountPolicy?;
1036
+ private tokenCalibrationState;
976
1037
  private readonly validateConfigFn;
977
1038
  private readonly invalidConfigMessage;
978
1039
  private readonly hasCustomTokenizer;
979
1040
  protected constructor(options: ContextManagerBaseOptions<TConfig, TRegistry>, init: ContextManagerBaseInit<TConfig, TRegistry>);
980
1041
  private createDefaultTokenizer;
981
1042
  protected estimateTokens(message: AiMessage): number;
1043
+ protected estimateTokensWithCalibrationTrace(message: AiMessage): {
1044
+ tokens: number;
1045
+ calibrationTrace: ReturnType<typeof calibrateTokenEstimate>['trace'];
1046
+ };
1047
+ protected getTokenCalibrationTrace(): ReturnType<typeof calibrateTokenEstimate>['trace'];
1048
+ protected getTokenRoute(): TokenRoute | undefined;
1049
+ protected estimateLocalTokens(messages: readonly AiMessage[]): number;
1050
+ protected countMessagesWithRemoteCounter(input: {
1051
+ messages: readonly AiMessage[];
1052
+ localEstimateTokens: number;
1053
+ signal?: AbortSignal;
1054
+ }): Promise<{
1055
+ tokens: number;
1056
+ trace: RemoteTokenCountTrace;
1057
+ }>;
982
1058
  protected debug(message: string, data?: Record<string, unknown>): void;
983
1059
  protected runPipeline<TContext extends ProviderContext$2<TConfig>, TPhase extends PropertyKey, TStats extends ContextPipelineStats<TPhase>>(options: {
984
1060
  messages: AiMessage[];
@@ -997,6 +1073,7 @@ declare abstract class ContextManagerBase<TConfig extends ContextManagerBaseConf
997
1073
  * AgentMessageOrchestrator 会按 request 自动处理,直接使用 ContextManager 的高级接入方才需要手动调用。
998
1074
  */
999
1075
  updateTokenizerModelId(modelId: string | undefined): void;
1076
+ updateTokenCalibration(input: ContextManagerBaseOptions<TConfig, TRegistry>['tokenCalibration']): void;
1000
1077
  }
1001
1078
 
1002
1079
  /**
@@ -1033,6 +1110,10 @@ interface ContextBuildResult$1 {
1033
1110
  events?: RuntimeEvent[];
1034
1111
  /** ContextTrace:解释本次上下文构建如何保留/裁剪消息。 */
1035
1112
  contextTrace?: ContextTrace;
1113
+ /** 构建期 token 估算快照,用于 host 把本地估算与响应后 actual usage 配对。 */
1114
+ tokenEstimate?: ContextBuildTokenEstimate;
1115
+ /** 构建期上下文分项 token 估算,用于 trace、账本与 host 面板后端。 */
1116
+ tokenComponents?: ContextTokenComponent[];
1036
1117
  }
1037
1118
  /**
1038
1119
  * Agent专用智能上下文管理器
@@ -1054,6 +1135,10 @@ declare class AgentContextManager extends ContextManagerBase<AgentContextBuilder
1054
1135
  providerRegistry?: ContextProviderRegistry$1;
1055
1136
  tokenizer?: TokenizerPort;
1056
1137
  tokenizerModelId?: string;
1138
+ tokenCounter?: TokenCounterPort;
1139
+ tokenRoute?: TokenRoute;
1140
+ remoteCount?: ContextManagerBaseOptions<AgentContextBuilderConfig, ContextProviderRegistry$1>['remoteCount'];
1141
+ tokenCalibration?: ContextManagerBaseOptions<AgentContextBuilderConfig, ContextProviderRegistry$1>['tokenCalibration'];
1057
1142
  });
1058
1143
  /**
1059
1144
  * 主入口:为Agent构建智能上下文
@@ -1070,6 +1155,7 @@ declare class AgentContextManager extends ContextManagerBase<AgentContextBuilder
1070
1155
  private getPhaseByProviderName;
1071
1156
  private initializeBuildStats;
1072
1157
  private buildFinalResult;
1158
+ private buildContextTokenEstimate;
1073
1159
  /**
1074
1160
  * 生成优化建议
1075
1161
  */
@@ -1190,8 +1276,10 @@ declare abstract class BasePreprocessor implements IPreprocessor {
1190
1276
 
1191
1277
  type ToolHistoryCompressionStrategy = 'per-pair' | 'per-run' | 'none';
1192
1278
  type ToolHistoryOverflowStrategy = 'keep-latest' | 'fail-fast';
1279
+ type ToolHistoryRetentionMode = 'drop' | 'compress';
1193
1280
  interface ToolHistoryCompressorOptions {
1194
1281
  strategy?: ToolHistoryCompressionStrategy;
1282
+ retentionMode?: ToolHistoryRetentionMode;
1195
1283
  keepLatestToolPairs?: number;
1196
1284
  keepLatestRuns?: number;
1197
1285
  maxInteractionGroups?: number;
@@ -1200,26 +1288,30 @@ interface ToolHistoryCompressorOptions {
1200
1288
  maxOutputSummaryTokens?: number;
1201
1289
  }
1202
1290
  /**
1203
- * 工具历史压缩预处理器。
1291
+ * 工具历史保留预处理器。
1204
1292
  *
1205
1293
  * 三种策略边界:
1206
- * - per-pair:旧行为,按全局最近 N 组完整工具交互保留,其余压成自然语言记录。
1294
+ * - per-pair:按全局最近 N 组完整工具交互保留,其余按 retentionMode 处理。
1207
1295
  * - per-run:按 user_input 划分 run,完整保留最近 K 个历史 run 内的工具组,避免腰斩同一轮工具链。
1208
1296
  * - none:不做常规压缩,仅在 maxInteractionGroups 显式触发时执行安全阀。
1209
1297
  *
1298
+ * retentionMode 边界:
1299
+ * - drop:默认行为。旧工具组超过保留窗口后直接移除,避免改写历史前缀和制造伪 final_answer。
1300
+ * - compress:兼容旧行为。把旧工具组替换为自然语言摘要,用于小上下文或审计友好的历史线索保留。
1301
+ *
1210
1302
  * 注意:单个 tool_output 的 token 截断不在这里做,那是 WorkingMemory 阶段
1211
- * ToolPairTruncator 的职责;本处理器只决定“工具组是原样保留还是压缩为摘要消息”。
1303
+ * ToolPairTruncator 的职责;本处理器只决定“工具组是原样保留、删除,还是压缩为摘要消息”。
1212
1304
  */
1213
1305
  declare class ToolHistoryCompressorPreprocessor extends BasePreprocessor {
1214
1306
  readonly name = "ToolHistoryCompressorPreprocessor";
1215
- readonly 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";
1307
+ readonly 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";
1216
1308
  readonly priority = 0;
1217
1309
  private summarizer;
1218
1310
  private readonly options;
1219
1311
  constructor(options?: ToolHistoryCompressorOptions);
1220
1312
  process(messages: AiMessage[], context: PreprocessorContext): Promise<PreprocessorResult>;
1221
1313
  shouldSkip(messages: AiMessage[], context: PreprocessorContext): boolean;
1222
- private compressToolCallPairsInHistory;
1314
+ private processToolCallPairsInHistory;
1223
1315
  private selectGroupsToKeep;
1224
1316
  private enforceMaxInteractionGroups;
1225
1317
  private compressToolInteractionGroup;
@@ -1335,7 +1427,7 @@ interface PreprocessorPipelineResult {
1335
1427
  * 创建默认的Agent预处理器注册表
1336
1428
  *
1337
1429
  * 🔥 这里定义了Agent预处理管道的默认配置:
1338
- * 1. ToolHistoryCompressorPreprocessor (priority: 0) - 工具历史压缩,最先执行
1430
+ * 1. ToolHistoryCompressorPreprocessor (priority: 0) - 工具历史保留/删除,最先执行
1339
1431
  * 2. ToolReplayProtocolGuardPreprocessor (priority: 0.5) - 工具回放协议守卫,仅治理历史轮次
1340
1432
  * 3. HistoryPurificationPreprocessor (priority: 1) - Agent历史净化,在压缩后执行
1341
1433
  *
@@ -1354,6 +1446,8 @@ declare function createDefaultAgentPreprocessorPipeline(context?: PreprocessorCo
1354
1446
 
1355
1447
  type index$4_BasePreprocessor = BasePreprocessor;
1356
1448
  declare const index$4_BasePreprocessor: typeof BasePreprocessor;
1449
+ type index$4_CurrentTurnMessageAssembler = CurrentTurnMessageAssembler;
1450
+ declare const index$4_CurrentTurnMessageAssembler: typeof CurrentTurnMessageAssembler;
1357
1451
  type index$4_DefaultAgentPreprocessorRegistryOptions = DefaultAgentPreprocessorRegistryOptions;
1358
1452
  type index$4_FenceLifetimePreprocessor = FenceLifetimePreprocessor;
1359
1453
  declare const index$4_FenceLifetimePreprocessor: typeof FenceLifetimePreprocessor;
@@ -1373,6 +1467,7 @@ type index$4_ToolHistoryCompressorOptions = ToolHistoryCompressorOptions;
1373
1467
  type index$4_ToolHistoryCompressorPreprocessor = ToolHistoryCompressorPreprocessor;
1374
1468
  declare const index$4_ToolHistoryCompressorPreprocessor: typeof ToolHistoryCompressorPreprocessor;
1375
1469
  type index$4_ToolHistoryOverflowStrategy = ToolHistoryOverflowStrategy;
1470
+ type index$4_ToolHistoryRetentionMode = ToolHistoryRetentionMode;
1376
1471
  type index$4_ToolReplayProtocolGuardOptions = ToolReplayProtocolGuardOptions;
1377
1472
  type index$4_ToolReplayProtocolGuardPreprocessor = ToolReplayProtocolGuardPreprocessor;
1378
1473
  declare const index$4_ToolReplayProtocolGuardPreprocessor: typeof ToolReplayProtocolGuardPreprocessor;
@@ -1381,7 +1476,7 @@ declare const index$4_createDefaultAgentPreprocessorPipeline: typeof createDefau
1381
1476
  declare const index$4_createDefaultAgentPreprocessorRegistry: typeof createDefaultAgentPreprocessorRegistry;
1382
1477
  declare const index$4_resolveToolReplayProtocolPolicy: typeof resolveToolReplayProtocolPolicy;
1383
1478
  declare namespace index$4 {
1384
- export { index$4_BasePreprocessor as BasePreprocessor, type index$4_DefaultAgentPreprocessorRegistryOptions as DefaultAgentPreprocessorRegistryOptions, index$4_FenceLifetimePreprocessor as FenceLifetimePreprocessor, index$4_HistoryPurificationPreprocessor as HistoryPurificationPreprocessor, type index$4_IPreprocessor as IPreprocessor, type index$4_MissingSidecarBehavior as MissingSidecarBehavior, type index$4_PreprocessorContext as PreprocessorContext, index$4_PreprocessorPipeline as PreprocessorPipeline, type index$4_PreprocessorPipelineResult as PreprocessorPipelineResult, index$4_PreprocessorRegistry as PreprocessorRegistry, type index$4_PreprocessorResult as PreprocessorResult, type index$4_ToolHistoryCompressionStrategy as ToolHistoryCompressionStrategy, type index$4_ToolHistoryCompressorOptions as ToolHistoryCompressorOptions, index$4_ToolHistoryCompressorPreprocessor as ToolHistoryCompressorPreprocessor, type index$4_ToolHistoryOverflowStrategy as ToolHistoryOverflowStrategy, type index$4_ToolReplayProtocolGuardOptions as ToolReplayProtocolGuardOptions, index$4_ToolReplayProtocolGuardPreprocessor as ToolReplayProtocolGuardPreprocessor, type index$4_ToolReplayProtocolPolicy as ToolReplayProtocolPolicy, index$4_createDefaultAgentPreprocessorPipeline as createDefaultAgentPreprocessorPipeline, index$4_createDefaultAgentPreprocessorRegistry as createDefaultAgentPreprocessorRegistry, index$4_resolveToolReplayProtocolPolicy as resolveToolReplayProtocolPolicy };
1479
+ export { index$4_BasePreprocessor as BasePreprocessor, index$4_CurrentTurnMessageAssembler as CurrentTurnMessageAssembler, type index$4_DefaultAgentPreprocessorRegistryOptions as DefaultAgentPreprocessorRegistryOptions, index$4_FenceLifetimePreprocessor as FenceLifetimePreprocessor, index$4_HistoryPurificationPreprocessor as HistoryPurificationPreprocessor, type index$4_IPreprocessor as IPreprocessor, type index$4_MissingSidecarBehavior as MissingSidecarBehavior, type index$4_PreprocessorContext as PreprocessorContext, index$4_PreprocessorPipeline as PreprocessorPipeline, type index$4_PreprocessorPipelineResult as PreprocessorPipelineResult, index$4_PreprocessorRegistry as PreprocessorRegistry, type index$4_PreprocessorResult as PreprocessorResult, type index$4_ToolHistoryCompressionStrategy as ToolHistoryCompressionStrategy, type index$4_ToolHistoryCompressorOptions as ToolHistoryCompressorOptions, index$4_ToolHistoryCompressorPreprocessor as ToolHistoryCompressorPreprocessor, type index$4_ToolHistoryOverflowStrategy as ToolHistoryOverflowStrategy, type index$4_ToolHistoryRetentionMode as ToolHistoryRetentionMode, type index$4_ToolReplayProtocolGuardOptions as ToolReplayProtocolGuardOptions, index$4_ToolReplayProtocolGuardPreprocessor as ToolReplayProtocolGuardPreprocessor, type index$4_ToolReplayProtocolPolicy as ToolReplayProtocolPolicy, index$4_createDefaultAgentPreprocessorPipeline as createDefaultAgentPreprocessorPipeline, index$4_createDefaultAgentPreprocessorRegistry as createDefaultAgentPreprocessorRegistry, index$4_resolveToolReplayProtocolPolicy as resolveToolReplayProtocolPolicy };
1385
1480
  }
1386
1481
 
1387
1482
  interface ToolManagerRegistry extends ToolSummaryProvider {
@@ -1439,10 +1534,24 @@ interface AgentOrchestratorOptions {
1439
1534
  contextPolicy: AgentSpecContextPolicy | undefined;
1440
1535
  contextBuilderConfig: Partial<AgentContextBuilderConfig>;
1441
1536
  }) => ContextProviderRegistry$1;
1537
+ resolveTokenCalibration?: (params: {
1538
+ request: AgentProfileRequest;
1539
+ modelId: string;
1540
+ contextPolicy: AgentSpecContextPolicy | undefined;
1541
+ }) => {
1542
+ route?: TokenRoute;
1543
+ samples?: readonly TokenUsageCalibrationSample[];
1544
+ } | undefined;
1442
1545
  taskResolver: AgentTaskResolver;
1443
1546
  providerRegistry: ContextProviderRegistry$1;
1444
1547
  fenceRegistry?: FenceRegistry;
1445
1548
  tokenizer?: TokenizerPort;
1549
+ tokenCounter?: TokenCounterPort;
1550
+ resolveTokenRoute?: (params: {
1551
+ request: AgentProfileRequest;
1552
+ modelId: string;
1553
+ contextPolicy: AgentSpecContextPolicy | undefined;
1554
+ }) => TokenRoute | undefined;
1446
1555
  }
1447
1556
  interface AgentProcessingResult {
1448
1557
  messages: AiMessage[];
@@ -1470,6 +1579,7 @@ declare class AgentMessageOrchestrator {
1470
1579
  private resolvePreprocessorModel;
1471
1580
  private resolveContextPolicy;
1472
1581
  private applyContextPolicy;
1582
+ private resolveEffectiveContextBudget;
1473
1583
  processAgentConversation(request: AgentProfileRequest, history: RuntimeEvent[], toolManager: ToolManager, callbacks?: SummarizationCallbacks, extraOptions?: {
1474
1584
  generate?: (request: GenerateRequest) => Promise<GenerateResponse>;
1475
1585
  }): Promise<AgentProcessingResult>;
@@ -1521,6 +1631,7 @@ declare abstract class BaseAgentTask implements IAgentTask {
1521
1631
  protected abstract getSystemPrompt(request: AgentProfileRequest): string;
1522
1632
  getSystemPromptForRequest(request: AgentProfileRequest): string;
1523
1633
  buildMessages(request: AgentProfileRequest, history: AiMessage[]): AiMessage[];
1634
+ private createCurrentUserMessage;
1524
1635
  private createFenceMessages;
1525
1636
  private createFenceMessage;
1526
1637
  private insertAfterLastToolResult;
@@ -1849,6 +1960,8 @@ interface ContextBuildResult {
1849
1960
  };
1850
1961
  /** 🔥 新增:Provider生成的运行时事件(如摘要事件) */
1851
1962
  events?: RuntimeEvent[];
1963
+ /** 构建期 token 估算快照。Chat 目前无 route,host 可只读 token 数。 */
1964
+ tokenEstimate?: ContextBuildTokenEstimate;
1852
1965
  }
1853
1966
  /**
1854
1967
  * 智能上下文管理器 - Provider编排器
@@ -1874,6 +1987,7 @@ declare class ContextManager extends ContextManagerBase<ContextBuilderConfig, Co
1874
1987
  private getPhaseByProviderName;
1875
1988
  private initializeBuildStats;
1876
1989
  private buildFinalResult;
1990
+ private buildContextTokenEstimate;
1877
1991
  /**
1878
1992
  * 生成优化建议
1879
1993
  */
@@ -2187,4 +2301,4 @@ interface ChatGenerateRequestAdapterInput extends AgentProfileRequest {
2187
2301
  */
2188
2302
  declare function buildGenerateRequestFromAgentRequest(request: ChatGenerateRequestAdapterInput, conversationHistory: AiMessage[]): GenerateRequest;
2189
2303
 
2190
- export { AGENT_CONSTANTS, AGENT_CONTEXT_BUILDER_CONFIG, AISummaryGenerator, type AgentContextBuilderConfigOverrides, type AgentSpecExecutionOptions, type AgentSpecPreprocessorOptions, type AgentSpecProviderOptions, type AgentSpecRuntimeOptions, BaseContextProvider$1 as BaseContextProvider, BaseConversationalTask, BasePreprocessor$1 as BasePreprocessor, ContextProviderRegistry as ChatContextProviderRegistry, CoreContextProvider as ChatCoreContextProvider, ChatMessage, MessageOrchestrator as ChatMessageOrchestrator, type OrchestratorOptions as ChatOrchestratorOptions, type ChatTaskResolver, WorkingMemoryProvider as ChatWorkingMemoryProvider, ContextProviderRegistry$2 as ContextProviderRegistry, ContextTrace, ContextTraceCollector, DEFAULT_MUST_KEEP_POLICY, type FenceDescriptor, type FenceInjection, type FenceLifetime, FenceLifetimePreprocessor, type FenceLifetimePreprocessorOptions, type FenceLlmRole, type FencePlacement, type FenceRegistry, GenerateRequest, GenerateResponse, type HistoryPurificationConfig, HistoryPurificationPreprocessor, type IChatTask, type IContextProvider$1 as IContextProvider, type IPreprocessor$1 as IPreprocessor, type LlmMessage, type MergeContextPolicyParams, type MessageFormatOptions, type MessageFormatterOptions, MessageProcessingState, type MustKeepPolicy, type MustKeepTruncationRule, type NativeToolCallingMessage, type PreprocessorContext$1 as PreprocessorContext, type PreprocessorResult$1 as PreprocessorResult, type ProviderContext$1 as ProviderContext, ProviderResult, SummarizationCallbacks, SummarizationCandidateSelector, type SummarizationOptions, SummarizationProvider, SummarizationStateUtils, SummarizationTrigger, type ToolSummaryProvider, config as agentConfig, index$5 as agentContext, contracts as agentContracts, index$3 as agentOrchestration, index$4 as agentPreprocessors, agentSpecToContextBuilderConfig, agentSpecToRuntimeOptions, index$2 as agentTasks, index$1 as agentTools, index as agentUtils, aiMessageToChatMessage, buildGenerateRequestFromAgentRequest, chatMessageToAiMessage, contextPolicyToContextBuilderConfig, contextPolicyToExecutionOptions, contextPolicyToMustKeepPolicy, contextPolicyToPreprocessorOptions, contextPolicyToProviderOptions, contextPolicyToRuntimeOptions, contextPolicyToSystemReminderOptions, convertEventToChatMessage, convertEventsToChatMessages, createFenceRegistry, createMessageFormatter, findMatchingTruncationRule, formatAgentLlmMessages, getDefaultTokenConfig, mergeContextPolicy, messageFormatter };
2304
+ export { AGENT_CONSTANTS, AGENT_CONTEXT_BUILDER_CONFIG, AISummaryGenerator, type AgentContextBuilderConfigOverrides, type AgentSpecExecutionOptions, type AgentSpecPreprocessorOptions, type AgentSpecProviderOptions, type AgentSpecRuntimeOptions, BaseContextProvider$1 as BaseContextProvider, BaseConversationalTask, BasePreprocessor$1 as BasePreprocessor, ContextProviderRegistry as ChatContextProviderRegistry, CoreContextProvider as ChatCoreContextProvider, ChatMessage, MessageOrchestrator as ChatMessageOrchestrator, type OrchestratorOptions as ChatOrchestratorOptions, type ChatTaskResolver, WorkingMemoryProvider as ChatWorkingMemoryProvider, ContextProviderRegistry$2 as ContextProviderRegistry, ContextTrace, ContextTraceCollector, CurrentTurnMessageAssembler, type CurrentTurnMessageAssemblerOptions, DEFAULT_MUST_KEEP_POLICY, type FenceDescriptor, type FenceInjection, type FenceLifetime, FenceLifetimePreprocessor, type FenceLifetimePreprocessorOptions, type FenceLlmRole, type FencePlacement, type FenceRegistry, GenerateRequest, GenerateResponse, type HistoryPurificationConfig, HistoryPurificationPreprocessor, type IChatTask, type IContextProvider$1 as IContextProvider, type IPreprocessor$1 as IPreprocessor, type LlmMessage, type MergeContextPolicyParams, type MessageFormatOptions, type MessageFormatterOptions, MessageProcessingState, type MustKeepPolicy, type MustKeepTruncationRule, type NativeToolCallingMessage, type PreprocessorContext$1 as PreprocessorContext, type PreprocessorResult$1 as PreprocessorResult, type ProviderContext$1 as ProviderContext, ProviderResult, RemoteTokenCountTrace, SummarizationCallbacks, SummarizationCandidateSelector, type SummarizationOptions, SummarizationProvider, SummarizationStateUtils, SummarizationTrigger, type ToolSummaryProvider, config as agentConfig, index$5 as agentContext, contracts as agentContracts, index$3 as agentOrchestration, index$4 as agentPreprocessors, agentSpecToContextBuilderConfig, agentSpecToRuntimeOptions, index$2 as agentTasks, index$1 as agentTools, index as agentUtils, aiMessageToChatMessage, buildGenerateRequestFromAgentRequest, chatMessageToAiMessage, contextPolicyToContextBuilderConfig, contextPolicyToExecutionOptions, contextPolicyToMustKeepPolicy, contextPolicyToPreprocessorOptions, contextPolicyToProviderOptions, contextPolicyToRuntimeOptions, contextPolicyToSystemReminderOptions, convertEventToChatMessage, convertEventsToChatMessages, createFenceRegistry, createMessageFormatter, findMatchingTruncationRule, formatAgentLlmMessages, getDefaultTokenConfig, mergeContextPolicy, messageFormatter };