@linnlabs/linnkit 0.8.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 (123) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/LICENSE +21 -0
  3. package/README.md +178 -0
  4. package/README.zh-CN.md +182 -0
  5. package/dist/agent-invocation-BHcNfrBV.d.cts +30 -0
  6. package/dist/agent-invocation-BznDaXDs.d.ts +30 -0
  7. package/dist/agentEvents-DEB7Fy_J.d.cts +81 -0
  8. package/dist/agentEvents-DEB7Fy_J.d.ts +81 -0
  9. package/dist/agentSpec-EkmviZjy.d.cts +2621 -0
  10. package/dist/agentSpec-EkmviZjy.d.ts +2621 -0
  11. package/dist/ai-engine.types-BpeU_XQG.d.cts +158 -0
  12. package/dist/ai-engine.types-vZRnQcJa.d.ts +158 -0
  13. package/dist/audit-BaRUGaqv.d.cts +307 -0
  14. package/dist/audit-BaRUGaqv.d.ts +307 -0
  15. package/dist/audit-CtcfART1.d.ts +33 -0
  16. package/dist/audit-LeOrm2hX.d.cts +33 -0
  17. package/dist/checkpointMarker-DAI3wUQu.d.cts +8 -0
  18. package/dist/checkpointMarker-DAI3wUQu.d.ts +8 -0
  19. package/dist/cli.cjs +8028 -0
  20. package/dist/cli.cjs.map +1 -0
  21. package/dist/cli.d.cts +4 -0
  22. package/dist/cli.d.ts +4 -0
  23. package/dist/cli.js +8025 -0
  24. package/dist/cli.js.map +1 -0
  25. package/dist/context-manager.cjs +8704 -0
  26. package/dist/context-manager.cjs.map +1 -0
  27. package/dist/context-manager.d.cts +2190 -0
  28. package/dist/context-manager.d.ts +2190 -0
  29. package/dist/context-manager.js +8650 -0
  30. package/dist/context-manager.js.map +1 -0
  31. package/dist/context-trace-DRi5M4lX.d.ts +239 -0
  32. package/dist/context-trace-HE2qY5Q-.d.cts +239 -0
  33. package/dist/contracts.cjs +1333 -0
  34. package/dist/contracts.cjs.map +1 -0
  35. package/dist/contracts.d.cts +8 -0
  36. package/dist/contracts.d.ts +8 -0
  37. package/dist/contracts.js +1214 -0
  38. package/dist/contracts.js.map +1 -0
  39. package/dist/defaultGraphExecutor-BBswR8wn.d.ts +624 -0
  40. package/dist/defaultGraphExecutor-BIjJj7WF.d.cts +624 -0
  41. package/dist/execution-CAIypb41.d.cts +129 -0
  42. package/dist/execution-CAIypb41.d.ts +129 -0
  43. package/dist/index-CHqwkvGp.d.ts +149 -0
  44. package/dist/index-CJeWHopy.d.ts +584 -0
  45. package/dist/index-Cm-JbzTH.d.cts +1450 -0
  46. package/dist/index-Cvr23YCl.d.cts +23 -0
  47. package/dist/index-DDzuSb0n.d.ts +23 -0
  48. package/dist/index-DO4dQgf2.d.cts +584 -0
  49. package/dist/index-DRBWi1fy.d.ts +1450 -0
  50. package/dist/index-Dl5PLgAv.d.cts +149 -0
  51. package/dist/index.cjs +9577 -0
  52. package/dist/index.cjs.map +1 -0
  53. package/dist/index.d.cts +89 -0
  54. package/dist/index.d.ts +89 -0
  55. package/dist/index.js +9563 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/messages-XthmnHZ3.d.cts +8007 -0
  58. package/dist/messages-XthmnHZ3.d.ts +8007 -0
  59. package/dist/ports-DaatKJXp.d.cts +90 -0
  60. package/dist/ports-DnLuKfpE.d.ts +90 -0
  61. package/dist/ports.cjs +4 -0
  62. package/dist/ports.cjs.map +1 -0
  63. package/dist/ports.d.cts +7 -0
  64. package/dist/ports.d.ts +7 -0
  65. package/dist/ports.js +3 -0
  66. package/dist/ports.js.map +1 -0
  67. package/dist/quickstart.cjs +7697 -0
  68. package/dist/quickstart.cjs.map +1 -0
  69. package/dist/quickstart.d.cts +24 -0
  70. package/dist/quickstart.d.ts +24 -0
  71. package/dist/quickstart.js +7691 -0
  72. package/dist/quickstart.js.map +1 -0
  73. package/dist/runAgent-CPj_9e58.d.ts +88 -0
  74. package/dist/runAgent-HYKlXbVr.d.cts +88 -0
  75. package/dist/runHandle-CyXvzgzk.d.ts +239 -0
  76. package/dist/runHandle-D3gPsD7B.d.cts +239 -0
  77. package/dist/runtime-kernel/events.cjs +1485 -0
  78. package/dist/runtime-kernel/events.cjs.map +1 -0
  79. package/dist/runtime-kernel/events.d.cts +8 -0
  80. package/dist/runtime-kernel/events.d.ts +8 -0
  81. package/dist/runtime-kernel/events.js +1475 -0
  82. package/dist/runtime-kernel/events.js.map +1 -0
  83. package/dist/runtime-kernel.cjs +8656 -0
  84. package/dist/runtime-kernel.cjs.map +1 -0
  85. package/dist/runtime-kernel.d.cts +19 -0
  86. package/dist/runtime-kernel.d.ts +19 -0
  87. package/dist/runtime-kernel.js +8568 -0
  88. package/dist/runtime-kernel.js.map +1 -0
  89. package/dist/sse-vPyrOPa0.d.cts +1687 -0
  90. package/dist/sse-vPyrOPa0.d.ts +1687 -0
  91. package/dist/testkit.cjs +10613 -0
  92. package/dist/testkit.cjs.map +1 -0
  93. package/dist/testkit.d.cts +284 -0
  94. package/dist/testkit.d.ts +284 -0
  95. package/dist/testkit.js +10593 -0
  96. package/dist/testkit.js.map +1 -0
  97. package/dist/todo-B1PmDlp3.d.cts +2253 -0
  98. package/dist/todo-B1PmDlp3.d.ts +2253 -0
  99. package/dist/tokenizer-DFL4I7-I.d.ts +28 -0
  100. package/dist/tokenizer-DH_JXv-H.d.cts +28 -0
  101. package/dist/toolContracts-Blll0241.d.ts +463 -0
  102. package/dist/toolContracts-CLkQmhTG.d.cts +463 -0
  103. package/docs/README.md +76 -0
  104. package/docs/integration/01-installation.md +94 -0
  105. package/docs/integration/02-quickstart.md +104 -0
  106. package/docs/integration/README.md +223 -0
  107. package/docs/integration/agent-registration-guide.md +330 -0
  108. package/docs/integration/audit.md +64 -0
  109. package/docs/integration/child-runs.md +87 -0
  110. package/docs/integration/constraints-and-pitfalls.md +87 -0
  111. package/docs/integration/context-engineering.md +650 -0
  112. package/docs/integration/context-fences.md +289 -0
  113. package/docs/integration/glossary.md +69 -0
  114. package/docs/integration/llm-provider.md +76 -0
  115. package/docs/integration/persistence.md +44 -0
  116. package/docs/integration/realtime.md +76 -0
  117. package/docs/integration/run-supervisor.md +69 -0
  118. package/docs/integration/telemetry.md +48 -0
  119. package/docs/integration/testing.md +95 -0
  120. package/docs/integration/tool-development-guide.md +362 -0
  121. package/docs/integration/tool-history.md +202 -0
  122. package/docs/integration/tools.md +188 -0
  123. package/package.json +115 -0
@@ -0,0 +1,2190 @@
1
+ import { A as AiMessage, a as AssistantMessage } from './messages-XthmnHZ3.js';
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-DRi5M4lX.js';
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-DRi5M4lX.js';
4
+ export { C as CHECKPOINT_MARKER_TYPE } from './checkpointMarker-DAI3wUQu.js';
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.js';
6
+ import { e as RuntimeEvent } from './todo-B1PmDlp3.js';
7
+ import { T as TokenizerPort } from './tokenizer-DFL4I7-I.js';
8
+ import { a as ToolArgs } from './toolContracts-Blll0241.js';
9
+ import 'zod';
10
+ import './ai-engine.types-vZRnQcJa.js';
11
+
12
+ type FenceLlmRole = 'user' | 'system';
13
+ type FencePlacement = 'after-system' | 'before-current-user' | 'after-current-user' | 'after-last-tool-result';
14
+ type FenceLifetime = 'turn-only' | 'persisted';
15
+ interface FenceDescriptor {
16
+ kind: string;
17
+ llmRole: FenceLlmRole;
18
+ placement: FencePlacement;
19
+ lifetime: FenceLifetime;
20
+ mustKeep?: boolean;
21
+ maxBudgetFraction?: number;
22
+ formatter: (content: string, attrs: Record<string, unknown>) => string;
23
+ }
24
+ interface FenceInjection {
25
+ kind: string;
26
+ content: string;
27
+ attrs?: Record<string, unknown>;
28
+ metadata?: Record<string, unknown>;
29
+ }
30
+ interface FenceRegistry {
31
+ register(descriptor: FenceDescriptor): void;
32
+ get(kind: string): FenceDescriptor | undefined;
33
+ list(): FenceDescriptor[];
34
+ }
35
+ declare function createFenceRegistry(descriptors?: FenceDescriptor[]): FenceRegistry;
36
+
37
+ interface MessageFormatOptions {
38
+ nativeTools?: boolean;
39
+ mode?: 'agent' | 'chat';
40
+ fenceRegistry?: FenceRegistry;
41
+ }
42
+ interface MessageFormatterOptions {
43
+ fenceRegistry?: FenceRegistry;
44
+ }
45
+ type NativeToolCallingMessage = {
46
+ role: 'system' | 'user';
47
+ content: string;
48
+ } | {
49
+ role: 'assistant';
50
+ content: string;
51
+ reasoning_details?: unknown[];
52
+ provider_empty_replay_field?: true;
53
+ } | {
54
+ role: 'assistant';
55
+ content: string | null;
56
+ tool_calls: unknown[];
57
+ reasoning_details?: unknown[];
58
+ provider_empty_replay_field?: true;
59
+ } | {
60
+ role: 'tool';
61
+ tool_call_id: string;
62
+ content: string;
63
+ };
64
+ declare class MessageFormatter {
65
+ private readonly fenceRegistry?;
66
+ constructor(options?: MessageFormatterOptions);
67
+ format(messages: AiMessage[], options: {
68
+ nativeTools: true;
69
+ mode?: 'agent' | 'chat';
70
+ }): NativeToolCallingMessage[];
71
+ format(messages: AiMessage[], options?: {
72
+ nativeTools?: false;
73
+ mode?: 'agent' | 'chat';
74
+ }): ChatMessage[];
75
+ private mergeThoughtAndAnswer;
76
+ private shouldMergeWithNext;
77
+ private performMerge;
78
+ private formatSingleMessage;
79
+ }
80
+ declare const messageFormatter: MessageFormatter;
81
+ declare function createMessageFormatter(options?: MessageFormatterOptions): MessageFormatter;
82
+ declare function formatAgentLlmMessages(messages: AiMessage[], options?: Pick<MessageFormatOptions, 'fenceRegistry'>): NativeToolCallingMessage[];
83
+ type LlmMessage = ChatMessage | NativeToolCallingMessage;
84
+
85
+ interface MustKeepTruncationRule {
86
+ messageType?: AiMessage['type'] | string;
87
+ metadataFragmentType?: string;
88
+ fenceKind?: string;
89
+ maxBudgetFraction: number;
90
+ strategyName: string;
91
+ }
92
+ interface MustKeepPolicy {
93
+ alwaysKeepTypes: Array<AiMessage['type'] | string>;
94
+ alwaysKeepFenceKinds: string[];
95
+ truncationRules: MustKeepTruncationRule[];
96
+ }
97
+ declare const DEFAULT_MUST_KEEP_POLICY: MustKeepPolicy;
98
+ declare function findMatchingTruncationRule(message: AiMessage, policy: MustKeepPolicy): MustKeepTruncationRule | undefined;
99
+
100
+ interface AgentContextBuilderConfigOverrides {
101
+ DEFAULT_MAX_TOKENS?: number;
102
+ RESERVED_FOR_RESPONSE?: number;
103
+ WORKING_MEMORY_BUDGET_PERCENTAGE?: number;
104
+ SUMMARIZATION_TRIGGER_THRESHOLD?: number;
105
+ SUMMARY_BUDGET_PERCENTAGE?: number;
106
+ SUMMARY_OLDEST_MESSAGES_PERCENTAGE?: number;
107
+ MAX_THOUGHTS_TO_KEEP?: number;
108
+ TOOL_PAIRING_SEARCH_RANGE?: number;
109
+ MAX_TOOL_PAIR_TOKENS?: number;
110
+ MAX_TOOL_OUTPUT_SUMMARY_TOKENS?: number;
111
+ MIN_TOOL_INTERACTIONS_TO_KEEP?: number;
112
+ MAX_RECENT_TOOL_INTERACTIONS_TO_KEEP?: number;
113
+ MAX_TOOL_INTERACTION_GROUPS_TO_KEEP?: number;
114
+ AVG_CHARS_PER_TOKEN?: number;
115
+ TOOL_CALL_OVERHEAD_TOKENS?: number;
116
+ TOKEN_ENCODING_NAME?: string;
117
+ }
118
+ interface AgentSpecPreprocessorOptions {
119
+ toolHistory?: {
120
+ strategy?: 'per-pair' | 'per-run' | 'none';
121
+ keepLatestToolPairs?: number;
122
+ keepLatestRuns?: number;
123
+ maxInteractionGroups?: number;
124
+ overflowStrategy?: 'keep-latest' | 'fail-fast';
125
+ maxPairTokens?: number;
126
+ maxOutputSummaryTokens?: number;
127
+ };
128
+ providerReplay?: AgentSpecProviderReplayPolicy;
129
+ }
130
+ interface AgentSpecProviderOptions {
131
+ mustKeep?: MustKeepPolicy;
132
+ checkpoint?: AgentSpecCheckpointPolicy;
133
+ summarization?: Pick<AgentSpecSummarizationPolicy, 'agentId' | 'failureBehavior'>;
134
+ contextTrace?: AgentSpecContextTracePolicy;
135
+ }
136
+ interface AgentSpecExecutionOptions {
137
+ toolOutput?: AgentSpecToolOutputPolicy;
138
+ }
139
+ interface AgentSpecRuntimeOptions {
140
+ contextBuilderConfig: AgentContextBuilderConfigOverrides;
141
+ preprocessorOptions: AgentSpecPreprocessorOptions;
142
+ providerOptions: AgentSpecProviderOptions;
143
+ executionOptions: AgentSpecExecutionOptions;
144
+ systemReminder?: AgentSpecSystemReminderPolicy;
145
+ }
146
+ /**
147
+ * 把 AgentSpec 的上下文策略转换成 AgentContextManager 能识别的配置覆盖。
148
+ * 注意:profileId 只用于宿主路由,这里不消费。
149
+ */
150
+ declare function agentSpecToContextBuilderConfig(spec: AgentSpec): AgentContextBuilderConfigOverrides;
151
+ declare function contextPolicyToContextBuilderConfig(policy: AgentSpecContextPolicy): AgentContextBuilderConfigOverrides;
152
+ /**
153
+ * 把 contextPolicy.toolHistory 原样转成交给 agent preprocessor registry 的配置。
154
+ */
155
+ declare function contextPolicyToPreprocessorOptions(policy: AgentSpecContextPolicy | undefined): AgentSpecPreprocessorOptions;
156
+ /**
157
+ * 提供给后续 provider registry 重建链路使用。
158
+ * F1.2 只做映射,不在这里创建 provider,避免 shared 层反向依赖 agent profile 实现。
159
+ */
160
+ declare function contextPolicyToProviderOptions(policy: AgentSpecContextPolicy | undefined): AgentSpecProviderOptions;
161
+ declare function contextPolicyToMustKeepPolicy(policy: AgentSpecContextPolicy | undefined): MustKeepPolicy | undefined;
162
+ declare function contextPolicyToSystemReminderOptions(policy: AgentSpecContextPolicy | undefined): AgentSpecSystemReminderPolicy | undefined;
163
+ declare function contextPolicyToExecutionOptions(policy: AgentSpecContextPolicy | undefined): AgentSpecExecutionOptions;
164
+ declare function agentSpecToRuntimeOptions(spec: AgentSpec): AgentSpecRuntimeOptions;
165
+ declare function contextPolicyToRuntimeOptions(policy: AgentSpecContextPolicy): AgentSpecRuntimeOptions;
166
+
167
+ interface MergeContextPolicyParams {
168
+ frameworkDefault?: AgentSpecContextPolicyInput;
169
+ hostFallback?: AgentSpecContextPolicyInput;
170
+ agentSpec?: AgentSpecContextPolicyInput;
171
+ }
172
+ /**
173
+ * 合并三层 contextPolicy。
174
+ *
175
+ * 中文备注:
176
+ * - 优先级:frameworkDefault < hostFallback < agentSpec;
177
+ * - 按分组做字段级合并;
178
+ * - 数组字段整体替换,不做 concat,避免 host/agent 的规则顺序变得不可预测。
179
+ */
180
+ declare function mergeContextPolicy(params: MergeContextPolicyParams): AgentSpecContextPolicy;
181
+
182
+ interface ToolSummaryProvider {
183
+ getTool(toolName: string): {
184
+ getExecutionSummary?: (output: string) => string;
185
+ } | undefined;
186
+ }
187
+ interface PreprocessorContext$1 {
188
+ debugMode?: boolean;
189
+ model?: string;
190
+ toolSummaryProvider?: ToolSummaryProvider;
191
+ }
192
+ interface PreprocessorResult$1 {
193
+ messages: AiMessage[];
194
+ stats: {
195
+ originalCount: number;
196
+ processedCount: number;
197
+ removedCount: number;
198
+ modifiedCount: number;
199
+ };
200
+ appliedStrategies: string[];
201
+ }
202
+ interface IPreprocessor$1 {
203
+ readonly name: string;
204
+ readonly description: string;
205
+ readonly priority: number;
206
+ process(messages: AiMessage[], context: PreprocessorContext$1): Promise<PreprocessorResult$1>;
207
+ shouldSkip?(messages: AiMessage[], context: PreprocessorContext$1): boolean;
208
+ }
209
+ declare abstract class BasePreprocessor$1 implements IPreprocessor$1 {
210
+ abstract readonly name: string;
211
+ abstract readonly description: string;
212
+ abstract readonly priority: number;
213
+ abstract process(messages: AiMessage[], context: PreprocessorContext$1): Promise<PreprocessorResult$1>;
214
+ shouldSkip?(messages: AiMessage[], context: PreprocessorContext$1): boolean;
215
+ protected createResult(originalMessages: AiMessage[], processedMessages: AiMessage[], appliedStrategies: string[], modifiedCount?: number): PreprocessorResult$1;
216
+ protected debug(message: string, data?: Record<string, unknown>, context?: PreprocessorContext$1): void;
217
+ }
218
+
219
+ interface HistoryPurificationConfig {
220
+ logPrefix?: string;
221
+ }
222
+ declare class HistoryPurificationPreprocessor extends BasePreprocessor$1 {
223
+ readonly name = "HistoryPurificationPreprocessor";
224
+ readonly description = "\u57FA\u4E8E\u6458\u8981ID\u5217\u8868\u7684\u5386\u53F2\u51C0\u5316\u5904\u7406\u5668";
225
+ readonly priority = 1;
226
+ private logPrefix;
227
+ constructor(config?: HistoryPurificationConfig);
228
+ process(messages: AiMessage[], context: PreprocessorContext$1): Promise<PreprocessorResult$1>;
229
+ shouldSkip(messages: AiMessage[], context: PreprocessorContext$1): boolean;
230
+ private findLatestSummary;
231
+ private cleanHistoryWithSummaryReplacement;
232
+ }
233
+
234
+ interface FenceLifetimePreprocessorOptions {
235
+ fenceRegistry: FenceRegistry;
236
+ }
237
+ declare class FenceLifetimePreprocessor extends BasePreprocessor$1 {
238
+ readonly name = "FenceLifetimePreprocessor";
239
+ readonly description = "Removes expired turn-only context injection messages from history";
240
+ readonly priority = 15;
241
+ private readonly fenceRegistry;
242
+ constructor(options: FenceLifetimePreprocessorOptions);
243
+ process(messages: AiMessage[], context: PreprocessorContext$1): Promise<PreprocessorResult$1>;
244
+ }
245
+
246
+ interface SummarizationConfig {
247
+ SUMMARIZATION_TRIGGER_THRESHOLD: number;
248
+ SUMMARY_OLDEST_MESSAGES_PERCENTAGE: number;
249
+ TOKEN_ENCODING_NAME: string;
250
+ }
251
+ type SummarizationProviderContext = ProviderContext$2<SummarizationConfig>;
252
+
253
+ /**
254
+ * @file AISummaryGenerator.ts
255
+ * @description AI摘要生成器 - 负责与AI模型交互生成摘要
256
+ */
257
+
258
+ interface SummarizationOptions {
259
+ maxSummaryTokens: number;
260
+ targetCompressionRatio?: number;
261
+ /**
262
+ * 执行摘要的已注册 agent/chat ID。
263
+ *
264
+ * 中文备注:linnkit 不持有 prompt 正文,也不直接决定模型调用;这里只携带注册引用,
265
+ * 真正的 prompt 构建与模型策略由 host 的注册表解释。
266
+ */
267
+ agentId: string;
268
+ modelId: string | null;
269
+ fallbackModelId?: string | null;
270
+ language: 'zh' | 'en' | 'auto';
271
+ failureBehavior?: 'fail-fast' | 'continue-if-within-budget';
272
+ /** 内部调参与测试注入,默认保持生产重试行为。 */
273
+ maxRetries?: number;
274
+ /** 内部调参与测试注入,默认 1000ms。 */
275
+ retryDelayMs?: number;
276
+ }
277
+ declare class AISummaryGenerator {
278
+ private readonly defaultOptions;
279
+ private readonly fallbackModelId;
280
+ private readonly MAX_RETRIES;
281
+ private readonly RETRY_DELAY_MS;
282
+ constructor(options: SummarizationOptions);
283
+ generateHistorySummary(candidates: MessageProcessingState[], context: SummarizationProviderContext, debugFn: (message: string, data: Record<string, unknown>, context: SummarizationProviderContext) => void): Promise<string>;
284
+ private tryGenerateSummaryWithRetries;
285
+ private formatMessagesForSummary;
286
+ private sleep;
287
+ }
288
+
289
+ declare class SummarizationTrigger {
290
+ static shouldSkip(states: MessageProcessingState[], availableBudget: number, context: SummarizationProviderContext): boolean;
291
+ static shouldTriggerSummarization(states: MessageProcessingState[], remainingBudget: number, totalBudget: number, context: SummarizationProviderContext, debugFn: (message: string, data: Record<string, unknown>, context: SummarizationProviderContext) => void): boolean;
292
+ static calculateUsedTokens(states: MessageProcessingState[]): number;
293
+ }
294
+
295
+ declare class SummarizationCandidateSelector {
296
+ static identifySummarizationCandidates(workingMemoryStates: MessageProcessingState[], context: SummarizationProviderContext, options?: {
297
+ fullStateList?: MessageProcessingState[];
298
+ }): {
299
+ allCandidates: MessageProcessingState[];
300
+ coreCandidates: MessageProcessingState[];
301
+ };
302
+ static selectCompleteConversationPairs(candidates: MessageProcessingState[], workingSet: MessageProcessingState[]): MessageProcessingState[];
303
+ }
304
+
305
+ declare class SummarizationStateUtils {
306
+ static collectReplacedIds(candidates: MessageProcessingState[]): string[];
307
+ static generateSummarySeq(allMessages: AiMessage[]): number;
308
+ static createSummaryMessageState(summary: string, candidates: MessageProcessingState[], context: ProviderContext$2, allMessages: AiMessage[], includedOldSummary?: boolean): {
309
+ state: MessageProcessingState;
310
+ event: RuntimeEvent;
311
+ };
312
+ static replaceWithSummary(allStates: MessageProcessingState[], candidatesForSummarization: MessageProcessingState[], summaryState: MessageProcessingState): MessageProcessingState[];
313
+ static calculateOriginalTokens(candidates: MessageProcessingState[]): number;
314
+ }
315
+
316
+ /**
317
+ * @file src/agent/context-manager/shared/providers/SummarizationProvider.ts
318
+ * @description 统一摘要化处理层Provider - Chat 和 Agent 通用
319
+ */
320
+
321
+ declare class SummarizationProvider extends BaseContextProvider$2<SummarizationConfig> {
322
+ readonly name = "SummarizationProvider";
323
+ readonly description = "\u6458\u8981\u5316\u5904\u7406\u5C42 - \u6838\u5FC3\u5BF9\u8BDD\u538B\u7F29\uFF0C\u805A\u7126\u7528\u6237\u610F\u56FE\u4E0EAI\u56DE\u7B54";
324
+ readonly priority = 3;
325
+ private aiGenerator;
326
+ private readonly failureBehavior;
327
+ constructor(options: SummarizationOptions);
328
+ provide(states: MessageProcessingState[], availableBudget: number, context: SummarizationProviderContext): Promise<ProviderResult>;
329
+ shouldSkip(states: MessageProcessingState[], availableBudget: number, context: SummarizationProviderContext): boolean;
330
+ }
331
+
332
+ declare class ContextProviderRegistry$2<TConfig = unknown> {
333
+ private providers;
334
+ register(provider: IContextProvider$2<TConfig>): void;
335
+ getAllProviders(): IContextProvider$2<TConfig>[];
336
+ getProvider(name: string): IContextProvider$2<TConfig> | undefined;
337
+ clear(): void;
338
+ }
339
+
340
+ /**
341
+ * @file src/agent/context-manager/profiles/agent/contracts.ts
342
+ */
343
+
344
+ /**
345
+ * Minimal request contract used by package-neutral agent profile code.
346
+ * Product-specific invoke requests can extend this shape.
347
+ */
348
+ interface AgentProfileRequest {
349
+ query: string;
350
+ promptKey: string;
351
+ model_id?: string;
352
+ modelId?: string;
353
+ availableTools?: string[];
354
+ conversationHistory?: AiMessage[];
355
+ fences?: FenceInjection[];
356
+ }
357
+
358
+ type contracts_AgentProfileRequest = AgentProfileRequest;
359
+ declare namespace contracts {
360
+ export type { contracts_AgentProfileRequest as AgentProfileRequest };
361
+ }
362
+
363
+ declare const AGENT_CONSTANTS: {
364
+ readonly DEFAULT_MAX_STEPS: 80;
365
+ readonly DEFAULT_TIMEOUT_MS: 300000;
366
+ readonly DEFAULT_MAX_RETRIES: 3;
367
+ readonly DEFAULT_RETRY_DELAY_MS: 1000;
368
+ };
369
+ interface AgentConfig {
370
+ defaultModelId: string;
371
+ maxSteps: number;
372
+ defaultTools: string[];
373
+ timeoutMs: number;
374
+ debug: boolean;
375
+ maxHistoryLength: number;
376
+ tokenBudget: {
377
+ maxTokens: number;
378
+ reservedForResponse: number;
379
+ };
380
+ contextProcessingTimeoutMs: number;
381
+ retry: {
382
+ maxRetries: number;
383
+ enableEmptyResponseRetry: boolean;
384
+ retryDelayMs: number;
385
+ };
386
+ }
387
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
388
+
389
+ declare const config_AGENT_CONSTANTS: typeof AGENT_CONSTANTS;
390
+ type config_AgentConfig = AgentConfig;
391
+ declare const config_DEFAULT_AGENT_CONFIG: typeof DEFAULT_AGENT_CONFIG;
392
+ declare namespace config {
393
+ export { config_AGENT_CONSTANTS as AGENT_CONSTANTS, type config_AgentConfig as AgentConfig, config_DEFAULT_AGENT_CONFIG as DEFAULT_AGENT_CONFIG };
394
+ }
395
+
396
+ /**
397
+ * 对话会话管理类
398
+ *
399
+ * 单一职责:管理当前会话的消息存储和基础CRUD操作
400
+ * - 存储和检索消息
401
+ * - 维护对话历史的完整性
402
+ * - 提供基础的消息查询功能
403
+ *
404
+ * 不负责:Token管理、智能截断、优先级分析(这些由WorkingContextManager处理)
405
+ */
406
+ declare class ConversationSession {
407
+ private messages;
408
+ private systemPrompt;
409
+ /**
410
+ * 构造函数
411
+ * @param systemPrompt 系统提示词
412
+ */
413
+ constructor(systemPrompt: string);
414
+ /**
415
+ * 添加消息到会话
416
+ * @param role 消息角色
417
+ * @param content 消息内容
418
+ */
419
+ addMessage(role: 'user' | 'assistant', content: string): void;
420
+ /**
421
+ * 添加用户消息
422
+ * @param content 用户消息内容
423
+ * @param id 可选的消息ID,如果不提供则自动生成
424
+ */
425
+ addUserMessage(content: string, id?: string): void;
426
+ /**
427
+ * 添加助手消息,可能包含工具调用
428
+ * @param content 文本内容(可选)
429
+ * @param type 消息类型
430
+ * @param metadata 消息元数据(可选)
431
+ * @param id 可选的消息ID,如果不提供则自动生成
432
+ */
433
+ addAssistantMessage(content: string | null, type: AssistantMessage['type'], metadata?: AiMessage['metadata'], id?: string): void;
434
+ /**
435
+ * 添加从历史记录加载的工具输出消息
436
+ * @param content 消息内容
437
+ * @param metadata 消息元数据
438
+ */
439
+ addToolOutputMessage(content: string, metadata: AiMessage['metadata']): void;
440
+ /**
441
+ * 添加工具调用的响应结果
442
+ * @param toolCallId 工具调用的唯一ID
443
+ * @param content 工具执行返回的结果(通常是字符串格式)
444
+ * @param toolName 工具名称(可选)
445
+ * @param id 可选的消息ID,如果不提供则自动生成
446
+ */
447
+ addToolResponse(toolCallId: string, content: string, toolName?: string, id?: string): void;
448
+ /**
449
+ * 追加一条已构造完成的消息。
450
+ *
451
+ * 中文备注:
452
+ * - 该方法用于回放阶段写入“已是最终形态”的消息,例如 `history_summary`;
453
+ * - 这样 core 侧只依赖最小写入端口,不需要直接感知 `ConversationSession` 的私有字段结构。
454
+ */
455
+ appendMessage(message: AiMessage): void;
456
+ /**
457
+ * 获取完整的对话历史记录
458
+ * @returns 消息数组
459
+ */
460
+ getHistory(): AiMessage[];
461
+ /**
462
+ * 清空对话历史,只保留系统提示词
463
+ */
464
+ clear(): void;
465
+ /**
466
+ * 更新系统提示词
467
+ * @param newSystemPrompt 新的系统提示词
468
+ */
469
+ updateSystemPrompt(newSystemPrompt: string): void;
470
+ /**
471
+ * 获取当前系统提示词
472
+ * @returns 系统提示词字符串
473
+ */
474
+ getSystemPrompt(): string;
475
+ /**
476
+ * 获取消息总数(不包括系统消息)
477
+ * @returns 消息数量
478
+ */
479
+ getMessageCount(): number;
480
+ /**
481
+ * 获取最近的n条用户消息
482
+ * @param n 消息数量
483
+ * @returns 用户消息数组
484
+ */
485
+ getRecentUserMessages(n: number): AiMessage[];
486
+ /**
487
+ * 获取最近的n条助手消息
488
+ * @param n 消息数量
489
+ * @returns 助手消息数组
490
+ */
491
+ getRecentAssistantMessages(n: number): AiMessage[];
492
+ /**
493
+ * 检查是否有待处理的工具调用
494
+ * @returns 是否有未响应的工具调用
495
+ */
496
+ hasPendingToolCalls(): boolean;
497
+ /**
498
+ * 获取待处理的工具调用
499
+ * @returns 待处理的工具调用数组
500
+ */
501
+ getPendingToolCalls(): Array<{
502
+ id: string;
503
+ type: 'function';
504
+ function: {
505
+ name: string;
506
+ arguments: string;
507
+ };
508
+ }>;
509
+ /**
510
+ * 将历史记录序列化为JSON
511
+ * @returns JSON字符串
512
+ */
513
+ serialize(): string;
514
+ /**
515
+ * 从JSON反序列化历史记录
516
+ * @param json JSON字符串
517
+ * @returns ConversationSession实例
518
+ */
519
+ static deserialize(json: string): ConversationSession;
520
+ }
521
+
522
+ /**
523
+ * @file src/agent/context/config.ts
524
+ * @description Agent上下文构建策略配置 - Agent专用三阶段智能填充配置中心
525
+ *
526
+ * 🎯 目的: 为Agent的ContextManager提供所有策略参数的可配置中心
527
+ * 📖 详情: 实现Agent README中描述的3阶段上下文构建策略,专注于工具交互优化
528
+ * 🔧 特色: P1-P4优先级填充策略,工具调用配对保留机制
529
+ */
530
+ /**
531
+ * Agent上下文构建器核心配置
532
+ *
533
+ * 🎯 统一管理Agent专用的Token限制、触发条件和策略参数
534
+ * 🔧 特别针对工具交互场景进行优化
535
+ */
536
+ declare const AGENT_CONTEXT_BUILDER_CONFIG: {
537
+ /** 默认最大Token预算上限 */
538
+ DEFAULT_MAX_TOKENS: number;
539
+ /** 响应预留Token数 */
540
+ RESERVED_FOR_RESPONSE: number;
541
+ /**
542
+ * 工作记忆填充目标百分比
543
+ * - **基准**: 可用上下文总预算
544
+ * - **说明**: Agent工作记忆层会尽力填充到此百分比,为摘要预留空间
545
+ */
546
+ WORKING_MEMORY_BUDGET_PERCENTAGE: number;
547
+ /**
548
+ * 摘要触发阈值百分比
549
+ * - **基准**: 可用上下文总预算
550
+ * - **说明**: 当已用Token总量超过此百分比时,将触发摘要机制
551
+ */
552
+ SUMMARIZATION_TRIGGER_THRESHOLD: number;
553
+ /**
554
+ * P1优先级:工具交互配对保留
555
+ * - 工具调用(tool_calls)和工具结果(tool)必须配对保留
556
+ * - 最高优先级,确保工具交互完整性
557
+ */
558
+ P1_TOOL_INTERACTION_PRIORITY: number;
559
+ /**
560
+ * P2优先级:纯文本对话
561
+ * - 不包含工具调用的user和assistant消息
562
+ * - 按时间倒序填充
563
+ */
564
+ P2_TEXT_CONVERSATION_PRIORITY: number;
565
+ /**
566
+ * P3优先级:历史工具交互
567
+ * - 较旧的工具调用记录
568
+ * - 仍然需要配对保留
569
+ */
570
+ P3_HISTORICAL_TOOL_PRIORITY: number;
571
+ /**
572
+ * P4优先级:循环填充
573
+ * - 剩余预算的循环填充策略
574
+ */
575
+ P4_CIRCULAR_FILL_PRIORITY: number;
576
+ /**
577
+ * P2优先级:工作记忆中保留的最近'thought'消息数量
578
+ */
579
+ MAX_THOUGHTS_TO_KEEP: number;
580
+ /**
581
+ * 摘要消息长度上限百分比
582
+ * - **基准**: 可用上下文总预算
583
+ * - **说明**: AI生成的摘要文本Token长度限制
584
+ */
585
+ SUMMARY_BUDGET_PERCENTAGE: number;
586
+ /**
587
+ * 选取摘要候选消息的比例
588
+ * - **基准**: 符合摘要条件的消息数量
589
+ * - **说明**: 选取最老的多少比例消息进行摘要
590
+ */
591
+ SUMMARY_OLDEST_MESSAGES_PERCENTAGE: number;
592
+ /**
593
+ * 工具调用配对搜索范围
594
+ * - 在多少条消息范围内搜索工具调用的配对
595
+ */
596
+ TOOL_PAIRING_SEARCH_RANGE: number;
597
+ /**
598
+ * 单个工具交互对的最大Token数
599
+ *
600
+ * 中文说明:
601
+ * - 这里是上下文构建期的 token 预算兜底,作用对象是整组 `tool_calls + tool_output`;
602
+ * - 它不负责工具执行后的原始 observation 落盘预览;
603
+ * - 执行期落盘阈值在 ToolNode observation governance 中维护,二者不要混成一个配置。
604
+ */
605
+ MAX_TOOL_PAIR_TOKENS: number;
606
+ /**
607
+ * 工具输出(tool_output)在“工作记忆层截断”时的摘要长度上限(Token)
608
+ * - 该值用于控制 `ToolOutputSummarizer` 生成摘要的“信息密度”,避免摘要过短导致信息丢失
609
+ * - 仅影响:超大工具交互对触发截断时(tool_output 会被摘要替换)
610
+ */
611
+ MAX_TOOL_OUTPUT_SUMMARY_TOKENS: number;
612
+ /**
613
+ * 工具交互保留的最小数量
614
+ * - 即使预算不足,也要保留最近的几组工具交互
615
+ */
616
+ MIN_TOOL_INTERACTIONS_TO_KEEP: number;
617
+ /**
618
+ * P1:最近工具交互(原始 tool_calls/tool_output)的最大保留组数
619
+ * - 目的:只让“最近的行动链”以原始结构进入上下文,避免工具消息膨胀
620
+ * - 注意:这里只统计“工具交互组”(一组 = 一次 tool_calls ↔ tool_output 配对)
621
+ */
622
+ MAX_RECENT_TOOL_INTERACTIONS_TO_KEEP: number;
623
+ /**
624
+ * P1+P3:工作记忆层最多保留的工具交互组总数(超过则直接丢弃)
625
+ * - 目的:对 user 之前的“历史工具交互”做硬上限,避免工具历史过长污染上下文
626
+ * - 注意:这里的“工具交互组”既包括原始 tool_calls/tool_output 配对,也包括被预处理压缩成
627
+ * assistant 文本的“工具执行记录摘要”(metadata.isCompressedToolHistory === true)
628
+ */
629
+ MAX_TOOL_INTERACTION_GROUPS_TO_KEEP: number;
630
+ /** 核心上下文保留层消息类型 - 第一阶段 */
631
+ CORE_MESSAGE_TYPES: readonly ["system_prompt", "user_input"];
632
+ /** P1优先级内容类型 - Agent专用 */
633
+ P1_CONTENT_TYPES: readonly ["tool_calls", "tool_output"];
634
+ /** P2优先级内容类型 - Agent专用 */
635
+ P2_CONTENT_TYPES: readonly ["final_answer", "user_input"];
636
+ /** P3优先级内容类型 - Agent专用 */
637
+ P3_CONTENT_TYPES: readonly ["historical_tool_calls", "historical_tool_result"];
638
+ /** 平均每个字符的token估算比例 */
639
+ AVG_CHARS_PER_TOKEN: number;
640
+ /** 工具调用的额外Token开销估算 */
641
+ TOOL_CALL_OVERHEAD_TOKENS: number;
642
+ /**
643
+ * Token 精确估算用的“模型标识”(用于映射到 tiktoken encoding)
644
+ *
645
+ * 说明:
646
+ * - 这里只用于 `TokenCalculator.estimateTokensPrecise(...)` 的 encoding 选择,不用于真实 LLM 调用;
647
+ * - 为避免把某个具体业务模型写死在这里,统一使用 tiktoken 的默认 encoding:cl100k_base。
648
+ */
649
+ TOKEN_ENCODING_NAME: string;
650
+ /** 是否启用详细的构建统计 */
651
+ ENABLE_BUILD_STATS: boolean;
652
+ /** 是否启用阶段执行时间统计 */
653
+ ENABLE_TIMING_STATS: boolean;
654
+ /** 上下文构建超时阈值 (毫秒) */
655
+ PROCESSING_TIMEOUT_MS: number;
656
+ /** 工具交互配对失败警告阈值 */
657
+ TOOL_PAIRING_FAILURE_WARNING_THRESHOLD: number;
658
+ };
659
+ /**
660
+ * Agent上下文构建策略配置的类型定义
661
+ */
662
+ interface AgentContextBuilderConfig {
663
+ DEFAULT_MAX_TOKENS: number;
664
+ RESERVED_FOR_RESPONSE: number;
665
+ WORKING_MEMORY_BUDGET_PERCENTAGE: number;
666
+ SUMMARIZATION_TRIGGER_THRESHOLD: number;
667
+ P1_TOOL_INTERACTION_PRIORITY: number;
668
+ P2_TEXT_CONVERSATION_PRIORITY: number;
669
+ P3_HISTORICAL_TOOL_PRIORITY: number;
670
+ P4_CIRCULAR_FILL_PRIORITY: number;
671
+ MAX_THOUGHTS_TO_KEEP: number;
672
+ SUMMARY_BUDGET_PERCENTAGE: number;
673
+ SUMMARY_OLDEST_MESSAGES_PERCENTAGE: number;
674
+ TOOL_PAIRING_SEARCH_RANGE: number;
675
+ MAX_TOOL_PAIR_TOKENS: number;
676
+ MAX_TOOL_OUTPUT_SUMMARY_TOKENS: number;
677
+ MIN_TOOL_INTERACTIONS_TO_KEEP: number;
678
+ MAX_RECENT_TOOL_INTERACTIONS_TO_KEEP: number;
679
+ MAX_TOOL_INTERACTION_GROUPS_TO_KEEP: number;
680
+ CORE_MESSAGE_TYPES: readonly string[];
681
+ P1_CONTENT_TYPES: readonly string[];
682
+ P2_CONTENT_TYPES: readonly string[];
683
+ P3_CONTENT_TYPES: readonly string[];
684
+ AVG_CHARS_PER_TOKEN: number;
685
+ TOOL_CALL_OVERHEAD_TOKENS: number;
686
+ TOKEN_ENCODING_NAME: string;
687
+ ENABLE_BUILD_STATS: boolean;
688
+ ENABLE_TIMING_STATS: boolean;
689
+ PROCESSING_TIMEOUT_MS: number;
690
+ TOOL_PAIRING_FAILURE_WARNING_THRESHOLD: number;
691
+ }
692
+ /**
693
+ * Agent专用阶段执行优先级枚举
694
+ */
695
+ declare enum AgentBuildPhase {
696
+ /** 阶段1: 核心上下文保留层 */
697
+ CORE_CONTEXT = 1,
698
+ /** 阶段2: 工作记忆填充层 (P1-P4优先级) */
699
+ WORKING_MEMORY = 2,
700
+ /** 阶段3: 历史摘要触发层 */
701
+ SUMMARIZATION = 3
702
+ }
703
+ /**
704
+ * Agent专用消息优先级枚举
705
+ */
706
+ declare enum AgentMessagePriority {
707
+ /** P1: 工具交互 - 最高优先级 */
708
+ TOOL_INTERACTION = 1,
709
+ /** P2: 纯文本对话 - 高优先级 */
710
+ TEXT_CONVERSATION = 2,
711
+ /** P3: 历史工具交互 - 中优先级 */
712
+ HISTORICAL_TOOL = 3,
713
+ /** P4: 循环填充 - 低优先级 */
714
+ CIRCULAR_FILL = 4
715
+ }
716
+ /**
717
+ * Agent上下文构建统计接口
718
+ */
719
+ interface AgentContextBuildStats {
720
+ /** 构建开始时间 */
721
+ startTime: number;
722
+ /** 各阶段执行时间 */
723
+ phaseTiming: Record<AgentBuildPhase, number>;
724
+ /** 各阶段token使用情况 */
725
+ phaseTokenUsage: Record<AgentBuildPhase, {
726
+ used: number;
727
+ percentage: number;
728
+ }>;
729
+ /** 消息数量统计 */
730
+ messageStats: {
731
+ original: number;
732
+ afterCoreContext: number;
733
+ afterWorkingMemory: number;
734
+ afterSummarization: number;
735
+ };
736
+ /** 优先级处理统计 */
737
+ priorityStats: {
738
+ p1ToolInteractions: number;
739
+ p2TextConversations: number;
740
+ p3HistoricalTools: number;
741
+ p4CircularFill: number;
742
+ };
743
+ /** 工具交互统计 */
744
+ toolStats: {
745
+ totalToolCalls: number;
746
+ pairedToolCalls: number;
747
+ unpairedToolCalls: number;
748
+ toolPairingSuccessRate: number;
749
+ };
750
+ /** 是否触发了摘要机制 */
751
+ summarizationTriggered: boolean;
752
+ /** 被摘要的消息数量 */
753
+ summarizedCount?: number;
754
+ /** 文档片段是否被截断 */
755
+ documentTruncated: boolean;
756
+ /** 总构建时间 */
757
+ totalTime: number;
758
+ }
759
+ /**
760
+ * 创建自定义Agent上下文构建配置的辅助函数
761
+ */
762
+ declare function createAgentContextBuilderConfig(overrides: Partial<AgentContextBuilderConfig>): AgentContextBuilderConfig;
763
+ /**
764
+ * 验证Agent配置有效性的辅助函数
765
+ */
766
+ declare function validateAgentConfig(config: AgentContextBuilderConfig): boolean;
767
+
768
+ type ProviderContext$1 = ProviderContext$2<AgentContextBuilderConfig>;
769
+ interface IContextProvider$1 extends IContextProvider$2<AgentContextBuilderConfig> {
770
+ }
771
+ declare abstract class BaseContextProvider$1 extends BaseContextProvider$2<AgentContextBuilderConfig> implements IContextProvider$1 {
772
+ }
773
+
774
+ /**
775
+ * @file src/agent/context/providers/AgentCoreContextProvider.ts
776
+ * @description Agent专用核心上下文保留层Provider - 第一阶段上下文构建
777
+ *
778
+ * 🎯 职责: 识别并保留必须保留的核心消息(Agent专用逻辑)
779
+ * 📖 规则: 系统提示词、工具描述、最新用户输入、注入的上下文始终无条件保留
780
+ * ✨ Agent特性: 支持宿主通过 MustKeepPolicy 声明必保留 fence,确保工具调用上下文的完整性
781
+ * 🔧 工具优先: 优先保留工具调用相关的核心消息
782
+ *
783
+ * 🏗️ 架构优化: 工具描述现在由 AgentContextManager 统一管理,而不是在 MessageFormatter 中特殊处理
784
+ * 这确保了架构的一致性和调试的透明性
785
+ */
786
+
787
+ interface AgentCoreContextProviderOptions {
788
+ mustKeepPolicy?: MustKeepPolicy;
789
+ }
790
+ /**
791
+ * Agent专用核心上下文保留层Provider
792
+ *
793
+ * 实现Agent README中描述的第一阶段:核心上下文保留层 (Must-Keep)
794
+ * 内容包括:系统提示词、用户当前请求、宿主显式声明的必保留 fence。
795
+ */
796
+ declare class AgentCoreContextProvider extends BaseContextProvider$1 {
797
+ readonly name = "AgentCoreContextProvider";
798
+ readonly description = "Agent\u6838\u5FC3\u4E0A\u4E0B\u6587\u4FDD\u7559\u5C42 - \u8BC6\u522B\u5E76\u4FDD\u7559\u7CFB\u7EDF\u63D0\u793A\u8BCD\u3001\u6700\u65B0\u7528\u6237\u8F93\u5165\u548C\u6CE8\u5165\u7684\u4E0A\u4E0B\u6587";
799
+ readonly priority = 1;
800
+ private readonly mustKeepPolicy;
801
+ constructor(options?: AgentCoreContextProviderOptions);
802
+ provide(states: MessageProcessingState[], availableBudget: number, context: ProviderContext$1): Promise<ProviderResult>;
803
+ /**
804
+ * 判断是否为核心消息 - Agent专用逻辑
805
+ *
806
+ * 🎯 Agent核心上下文保留规则:
807
+ * 1. 保留 system_prompt(系统级消息)
808
+ * 2. 保留最新的 user 消息 (current_user_request)
809
+ * 3. 保留 MustKeepPolicy 指定的 fence
810
+ * 4. 对命中的 MustKeepPolicy.truncationRules 做 Token 截断
811
+ */
812
+ private isCoreMessage;
813
+ /**
814
+ * 内容截断 - 保持完整词汇
815
+ * 复用ContextManager中的逻辑
816
+ */
817
+ private truncateContent;
818
+ }
819
+
820
+ /**
821
+ * @file src/agent/context/providers/AgentWorkingMemoryProvider.ts
822
+ * @description Agent专用工作记忆填充层Provider - 第二阶段上下文构建
823
+ *
824
+ * 🎯 职责: 实现Agent的P1-P4优先级填充策略
825
+ * 📖 策略: P1(工具交互) > P2(纯文本对话) > P3(历史工具交互) > P4(循环填充)
826
+ * ✨ Agent特性: 工具调用优先级、配对保留策略
827
+ * 🔧 核心逻辑: 保留工具调用时,必须确保其对应的另一半也被保留
828
+ */
829
+
830
+ /**
831
+ * Agent专用工作记忆填充层Provider
832
+ *
833
+ * 实现Agent README中描述的第二阶段:工作记忆填充层 (Working Memory)
834
+ * 工具调用为最高优先级,确保工具交互的完整性
835
+ */
836
+ declare class AgentWorkingMemoryProvider extends BaseContextProvider$1 {
837
+ readonly name = "AgentWorkingMemoryProvider";
838
+ readonly description = "Agent\u5DE5\u4F5C\u8BB0\u5FC6\u586B\u5145\u5C42 - \u5DE5\u5177\u4F18\u5148\u7684\u53CD\u5411\u586B\u5145\u7B56\u7565\uFF0C\u652F\u6301\u914D\u5BF9\u4FDD\u7559";
839
+ readonly priority = 2;
840
+ private readonly matcher;
841
+ private readonly truncator;
842
+ private readonly tagger;
843
+ private readonly config;
844
+ constructor(customConfig?: Partial<AgentContextBuilderConfig>);
845
+ /**
846
+ * 类型守卫:用于安全读取 ProviderContext 上的"扩展字段"
847
+ * 注意:ProviderContext 本身是稳定契约,扩展字段来自编排层(不应污染接口定义)。
848
+ */
849
+ private isRecord;
850
+ /**
851
+ * 读取当前上下文阶段(如果编排层提供了 currentPhase)
852
+ * - 禁止 any 类型断言:这里用 Record 逐层收窄。
853
+ */
854
+ private readCurrentPhase;
855
+ /**
856
+ * 创建调试函数
857
+ */
858
+ private createDebugFn;
859
+ provide(states: MessageProcessingState[], availableBudget: number, context: ProviderContext$1): Promise<ProviderResult>;
860
+ /**
861
+ * 计算当前已使用的Token数
862
+ */
863
+ private calculateUsedTokens;
864
+ }
865
+
866
+ /**
867
+ * @file src/agent/context-manager/profiles/agent/context/providers/CheckpointSummarizationProvider.ts
868
+ * @description 上下文检查点 Provider(根因级语义修正版):
869
+ *
870
+ * ✅ checkpoint 是一个“正常工具调用”,必须以 tool_calls → tool_output 的形式按顺序保留在历史中,
871
+ * 也必须按顺序进入发送给 LLM 的 messages(而不是被替换成 system history_summary 顶置到最前)。
872
+ *
873
+ * 🎯 checkpoint 的职责是“清理 checkpoint 之前的旧历史”,而不是“把 checkpoint 本身变成摘要”:
874
+ * - 保留:Must-Keep(system_prompt / 最新 user_input / 必保留 fence 等)、checkpoint 工具对、
875
+ * 以及 checkpoint 之前最近 N 对工具交互(默认 N=2)。
876
+ * - 清理:checkpoint 之前更旧的工具对 / final_answer / thought / 旧 history_summary 等。
877
+ *
878
+ * ✅ 设计原则:
879
+ * - checkpoint 只影响“本轮发给 LLM 的 messages 选择”,不生成任何 system 摘要事件;
880
+ * - 数据库仍然落全量事实历史:裁剪不会影响持久化/回放,只影响本轮 LLM 输入。
881
+ */
882
+
883
+ interface CheckpointSummarizationProviderOptions {
884
+ /** checkpoint 之前保留的最近工具交互轮数。 */
885
+ keepPairsBefore?: number;
886
+ /** 触发 checkpoint 裁剪的工具名。默认 context_checkpoint。 */
887
+ triggerToolName?: string;
888
+ }
889
+ declare class CheckpointSummarizationProvider extends BaseContextProvider$1 {
890
+ readonly name = "CheckpointSummarizationProvider";
891
+ readonly description = "\u4E0A\u4E0B\u6587\u68C0\u67E5\u70B9 - \u4FDD\u7559 checkpoint \u5DE5\u5177\u5BF9\uFF0C\u88C1\u526A\u5176\u4E4B\u524D\u65E7\u5386\u53F2";
892
+ readonly priority = 2.5;
893
+ private readonly keepPairsBefore;
894
+ private readonly triggerToolName;
895
+ constructor(options?: CheckpointSummarizationProviderOptions);
896
+ provide(states: MessageProcessingState[], availableBudget: number, context: ProviderContext$1): Promise<ProviderResult>;
897
+ /**
898
+ * 在 states 中查找 context_checkpoint 工具的 observation
899
+ * 返回 { summary, checkpointStateIndex } 或 null
900
+ */
901
+ private findCheckpoint;
902
+ /**
903
+ * 找到 checkpoint 之前最近 N 轮工具交互 indices
904
+ * - 仅扫描 checkpoint tool_calls 之前的历史段
905
+ */
906
+ private findRecentToolPairIndicesBeforeCheckpoint;
907
+ private extractCheckpointSummaryFromGroup;
908
+ }
909
+
910
+ /**
911
+ * @file src/agent/context-manager/profiles/agent/context/providers/index.ts
912
+ * @description Agent profile provider 协议与实现导出
913
+ */
914
+
915
+ declare class ContextProviderRegistry$1 extends ContextProviderRegistry$2<AgentContextBuilderConfig> {
916
+ }
917
+
918
+ type LogPayload = Record<string, unknown> | undefined;
919
+ declare class Logger {
920
+ private readonly moduleName;
921
+ constructor(moduleName: string);
922
+ debug(message: string, data?: LogPayload): void;
923
+ info(message: string, data?: LogPayload): void;
924
+ warn(message: string, data?: LogPayload): void;
925
+ error(message: string, data?: LogPayload): void;
926
+ private log;
927
+ }
928
+
929
+ interface ContextPipelineStats<TPhase extends PropertyKey> {
930
+ phaseTiming: Record<TPhase, number>;
931
+ phaseTokenUsage: Record<TPhase, {
932
+ used: number;
933
+ percentage: number;
934
+ }>;
935
+ messageStats: {
936
+ original: number;
937
+ afterCoreContext: number;
938
+ afterWorkingMemory: number;
939
+ afterSummarization: number;
940
+ };
941
+ }
942
+ interface RunContextPipelineResult {
943
+ finalMessages: AiMessage[];
944
+ finalTokens: number;
945
+ strategiesApplied: string[];
946
+ events: RuntimeEvent[];
947
+ states: MessageProcessingState[];
948
+ }
949
+
950
+ interface ContextManagerBaseConfig {
951
+ AVG_CHARS_PER_TOKEN: number;
952
+ TOOL_CALL_OVERHEAD_TOKENS?: number;
953
+ TOKEN_ENCODING_NAME?: string;
954
+ }
955
+ interface ContextManagerBaseOptions<TConfig, TRegistry> {
956
+ debugMode?: boolean;
957
+ customConfig?: Partial<TConfig>;
958
+ providerRegistry?: TRegistry;
959
+ tokenizer?: TokenizerPort;
960
+ tokenizerModelId?: string;
961
+ }
962
+ interface ContextManagerBaseInit<TConfig, TRegistry> {
963
+ defaultConfig: TConfig;
964
+ validateConfig: (config: TConfig) => boolean;
965
+ createRegistry: () => TRegistry;
966
+ loggerName: string;
967
+ invalidConfigMessage: string;
968
+ }
969
+ declare abstract class ContextManagerBase<TConfig extends ContextManagerBaseConfig, TRegistry extends ContextProviderRegistry$2<TConfig>> {
970
+ protected config: TConfig;
971
+ protected debugMode: boolean;
972
+ protected providerRegistry: TRegistry;
973
+ protected logger: Logger;
974
+ protected tokenizer: TokenizerPort;
975
+ protected tokenizerModelId?: string;
976
+ private readonly validateConfigFn;
977
+ private readonly invalidConfigMessage;
978
+ private readonly hasCustomTokenizer;
979
+ protected constructor(options: ContextManagerBaseOptions<TConfig, TRegistry>, init: ContextManagerBaseInit<TConfig, TRegistry>);
980
+ private createDefaultTokenizer;
981
+ protected estimateTokens(message: AiMessage): number;
982
+ protected debug(message: string, data?: Record<string, unknown>): void;
983
+ protected runPipeline<TContext extends ProviderContext$2<TConfig>, TPhase extends PropertyKey, TStats extends ContextPipelineStats<TPhase>>(options: {
984
+ messages: AiMessage[];
985
+ totalBudget: number;
986
+ buildStats: TStats;
987
+ providerContext: TContext;
988
+ getPhaseByProviderName: (providerName: string) => TPhase | null;
989
+ contextTrace?: ContextTraceCollector;
990
+ }): Promise<RunContextPipelineResult>;
991
+ getConfig(): TConfig;
992
+ updateConfig(newConfig: Partial<TConfig>): void;
993
+ /**
994
+ * 更新传给 TokenizerPort 的模型 ID。
995
+ *
996
+ * 中文备注:同一个 context manager 被复用到不同模型时,host 必须同步更新这里;
997
+ * AgentMessageOrchestrator 会按 request 自动处理,直接使用 ContextManager 的高级接入方才需要手动调用。
998
+ */
999
+ updateTokenizerModelId(modelId: string | undefined): void;
1000
+ }
1001
+
1002
+ /**
1003
+ * 上下文构建结果接口
1004
+ */
1005
+ interface ContextBuildResult$1 {
1006
+ /** 构建后的消息列表 */
1007
+ messages: AiMessage[];
1008
+ /** Token使用情况 */
1009
+ tokenUsage: {
1010
+ used: number;
1011
+ remaining: number;
1012
+ };
1013
+ /** 处理统计信息 */
1014
+ processingStats: {
1015
+ originalCount: number;
1016
+ keptCount: number;
1017
+ truncatedCount: number;
1018
+ tokenDistribution: Record<string, number>;
1019
+ strategiesApplied: string[];
1020
+ recommendations: string[];
1021
+ buildStats?: AgentContextBuildStats;
1022
+ };
1023
+ /** 是否进行了截断 */
1024
+ truncated: boolean;
1025
+ /** 截断的消息数量 */
1026
+ truncatedCount?: number;
1027
+ /** 应用的策略列表 */
1028
+ strategies: {
1029
+ applied: string[];
1030
+ recommendations: string[];
1031
+ };
1032
+ /** 🔥 新增:Provider生成的运行时事件(如摘要事件) */
1033
+ events?: RuntimeEvent[];
1034
+ /** ContextTrace:解释本次上下文构建如何保留/裁剪消息。 */
1035
+ contextTrace?: ContextTrace;
1036
+ }
1037
+ /**
1038
+ * Agent专用智能上下文管理器
1039
+ *
1040
+ * 🎯 核心职责:
1041
+ * 1. 编排Provider执行,构建优化的上下文
1042
+ * 2. 保证工具调用的完整性和配对保留
1043
+ * 3. 使用统一配置,不感知对话阶段
1044
+ *
1045
+ * 🏗️ 架构特性:
1046
+ * - Provider策略模式: 实现高内聚、低耦合
1047
+ * - 责任链模式: 按优先级编排Provider
1048
+ * - 专注于Provider编排,不负责消息构建
1049
+ */
1050
+ declare class AgentContextManager extends ContextManagerBase<AgentContextBuilderConfig, ContextProviderRegistry$1> {
1051
+ constructor(options?: {
1052
+ debugMode?: boolean;
1053
+ customConfig?: Partial<AgentContextBuilderConfig>;
1054
+ providerRegistry?: ContextProviderRegistry$1;
1055
+ tokenizer?: TokenizerPort;
1056
+ tokenizerModelId?: string;
1057
+ });
1058
+ /**
1059
+ * 主入口:为Agent构建智能上下文
1060
+ * 专门处理预处理过的消息,专注于上下文优化
1061
+ */
1062
+ buildContextFromPreprocessedMessages(request: AgentProfileRequest, conversationSession: ConversationSession, preprocessedMessages: AiMessage[], totalBudget: number, callbacks?: SummarizationCallbacks, phaseOverride?: AgentBuildPhase, // 保留参数兼容性,但不再使用
1063
+ generate?: (request: GenerateRequest) => Promise<GenerateResponse>, traceOptions?: {
1064
+ policy?: AgentSpecContextTracePolicy;
1065
+ effectiveContextPolicy?: AgentSpecContextPolicy;
1066
+ }): Promise<ContextBuildResult$1>;
1067
+ /**
1068
+ * 根据Provider名称获取对应的阶段名称
1069
+ */
1070
+ private getPhaseByProviderName;
1071
+ private initializeBuildStats;
1072
+ private buildFinalResult;
1073
+ /**
1074
+ * 生成优化建议
1075
+ */
1076
+ private generateRecommendations;
1077
+ }
1078
+
1079
+ declare const index$5_AGENT_CONTEXT_BUILDER_CONFIG: typeof AGENT_CONTEXT_BUILDER_CONFIG;
1080
+ type index$5_AgentBuildPhase = AgentBuildPhase;
1081
+ declare const index$5_AgentBuildPhase: typeof AgentBuildPhase;
1082
+ type index$5_AgentContextBuildStats = AgentContextBuildStats;
1083
+ type index$5_AgentContextBuilderConfig = AgentContextBuilderConfig;
1084
+ type index$5_AgentContextManager = AgentContextManager;
1085
+ declare const index$5_AgentContextManager: typeof AgentContextManager;
1086
+ type index$5_AgentCoreContextProvider = AgentCoreContextProvider;
1087
+ declare const index$5_AgentCoreContextProvider: typeof AgentCoreContextProvider;
1088
+ type index$5_AgentMessagePriority = AgentMessagePriority;
1089
+ declare const index$5_AgentMessagePriority: typeof AgentMessagePriority;
1090
+ type index$5_AgentWorkingMemoryProvider = AgentWorkingMemoryProvider;
1091
+ declare const index$5_AgentWorkingMemoryProvider: typeof AgentWorkingMemoryProvider;
1092
+ type index$5_CheckpointSummarizationProvider = CheckpointSummarizationProvider;
1093
+ declare const index$5_CheckpointSummarizationProvider: typeof CheckpointSummarizationProvider;
1094
+ type index$5_ConversationSession = ConversationSession;
1095
+ declare const index$5_ConversationSession: typeof ConversationSession;
1096
+ declare const index$5_MessageProcessingState: typeof MessageProcessingState;
1097
+ declare const index$5_ProviderResult: typeof ProviderResult;
1098
+ declare const index$5_SummarizationCallbacks: typeof SummarizationCallbacks;
1099
+ type index$5_SummarizationProvider = SummarizationProvider;
1100
+ declare const index$5_SummarizationProvider: typeof SummarizationProvider;
1101
+ declare const index$5_createAgentContextBuilderConfig: typeof createAgentContextBuilderConfig;
1102
+ declare const index$5_validateAgentConfig: typeof validateAgentConfig;
1103
+ declare namespace index$5 {
1104
+ export { index$5_AGENT_CONTEXT_BUILDER_CONFIG as AGENT_CONTEXT_BUILDER_CONFIG, index$5_AgentBuildPhase as AgentBuildPhase, type index$5_AgentContextBuildStats as AgentContextBuildStats, type index$5_AgentContextBuilderConfig as AgentContextBuilderConfig, index$5_AgentContextManager as AgentContextManager, index$5_AgentCoreContextProvider as AgentCoreContextProvider, index$5_AgentMessagePriority as AgentMessagePriority, index$5_AgentWorkingMemoryProvider as AgentWorkingMemoryProvider, BaseContextProvider$1 as BaseContextProvider, index$5_CheckpointSummarizationProvider as CheckpointSummarizationProvider, type ContextBuildResult$1 as ContextBuildResult, ContextProviderRegistry$1 as ContextProviderRegistry, index$5_ConversationSession as ConversationSession, type IContextProvider$1 as IContextProvider, index$5_MessageProcessingState as MessageProcessingState, type ProviderContext$1 as ProviderContext, index$5_ProviderResult as ProviderResult, index$5_SummarizationCallbacks as SummarizationCallbacks, index$5_SummarizationProvider as SummarizationProvider, index$5_createAgentContextBuilderConfig as createAgentContextBuilderConfig, index$5_validateAgentConfig as validateAgentConfig };
1105
+ }
1106
+
1107
+ type MissingSidecarBehavior = 'allow' | 'degrade_to_text' | 'provider_empty_replay_field';
1108
+ interface ToolReplayProtocolPolicy {
1109
+ provider?: string;
1110
+ requiresReasoningDetailsForToolReplay?: boolean;
1111
+ missingSidecarBehavior?: MissingSidecarBehavior;
1112
+ }
1113
+ /**
1114
+ * Preprocessor context object
1115
+ */
1116
+ interface PreprocessorContext {
1117
+ debugMode?: boolean;
1118
+ model?: string;
1119
+ toolReplayProtocolPolicy?: ToolReplayProtocolPolicy;
1120
+ toolSummaryProvider?: ToolSummaryProvider;
1121
+ }
1122
+ /**
1123
+ * Result of a preprocessor run
1124
+ */
1125
+ interface PreprocessorResult {
1126
+ /** 预处理后的消息列表 */
1127
+ messages: AiMessage[];
1128
+ /** 预处理统计信息 */
1129
+ stats: {
1130
+ /** 原始消息数量 */
1131
+ originalCount: number;
1132
+ /** 处理后消息数量 */
1133
+ processedCount: number;
1134
+ /** 被移除的消息数量 */
1135
+ removedCount: number;
1136
+ /** 被修改的消息数量 */
1137
+ modifiedCount: number;
1138
+ };
1139
+ /** 应用的策略列表 */
1140
+ appliedStrategies: string[];
1141
+ }
1142
+ /**
1143
+ * 预处理器接口 - 管道模式的核心契约
1144
+ */
1145
+ interface IPreprocessor {
1146
+ /** 预处理器名称 */
1147
+ readonly name: string;
1148
+ /** 预处理器描述 */
1149
+ readonly description: string;
1150
+ /** 执行顺序优先级 (数字越小越先执行) */
1151
+ readonly priority: number;
1152
+ /**
1153
+ * 预处理方法 - 管道模式的核心方法
1154
+ *
1155
+ * @param messages 输入的消息列表
1156
+ * @param context 预处理上下文
1157
+ * @returns 预处理结果
1158
+ */
1159
+ process(messages: AiMessage[], context: PreprocessorContext): Promise<PreprocessorResult>;
1160
+ /**
1161
+ * 可选:判断是否应该跳过此预处理器
1162
+ *
1163
+ * @param messages 输入的消息列表
1164
+ * @param context 预处理上下文
1165
+ * @returns true表示跳过,false表示执行
1166
+ */
1167
+ shouldSkip?(messages: AiMessage[], context: PreprocessorContext): boolean;
1168
+ }
1169
+ /**
1170
+ * 预处理器基类 - 提供通用功能实现
1171
+ */
1172
+ declare abstract class BasePreprocessor implements IPreprocessor {
1173
+ abstract readonly name: string;
1174
+ abstract readonly description: string;
1175
+ abstract readonly priority: number;
1176
+ abstract process(messages: AiMessage[], context: PreprocessorContext): Promise<PreprocessorResult>;
1177
+ /**
1178
+ * 默认的跳过逻辑 - 子类可以覆盖
1179
+ */
1180
+ shouldSkip?(messages: AiMessage[], context: PreprocessorContext): boolean;
1181
+ /**
1182
+ * 创建预处理结果的辅助方法
1183
+ */
1184
+ protected createResult(originalMessages: AiMessage[], processedMessages: AiMessage[], appliedStrategies: string[], modifiedCount?: number): PreprocessorResult;
1185
+ /**
1186
+ * 调试日志辅助方法
1187
+ */
1188
+ protected debug(message: string, data?: Record<string, unknown>, context?: PreprocessorContext): void;
1189
+ }
1190
+
1191
+ type ToolHistoryCompressionStrategy = 'per-pair' | 'per-run' | 'none';
1192
+ type ToolHistoryOverflowStrategy = 'keep-latest' | 'fail-fast';
1193
+ interface ToolHistoryCompressorOptions {
1194
+ strategy?: ToolHistoryCompressionStrategy;
1195
+ keepLatestToolPairs?: number;
1196
+ keepLatestRuns?: number;
1197
+ maxInteractionGroups?: number;
1198
+ overflowStrategy?: ToolHistoryOverflowStrategy;
1199
+ maxPairTokens?: number;
1200
+ maxOutputSummaryTokens?: number;
1201
+ }
1202
+ /**
1203
+ * 工具历史压缩预处理器。
1204
+ *
1205
+ * 三种策略边界:
1206
+ * - per-pair:旧行为,按全局最近 N 组完整工具交互保留,其余压成自然语言记录。
1207
+ * - per-run:按 user_input 划分 run,完整保留最近 K 个历史 run 内的工具组,避免腰斩同一轮工具链。
1208
+ * - none:不做常规压缩,仅在 maxInteractionGroups 显式触发时执行安全阀。
1209
+ *
1210
+ * 注意:单个 tool_output 的 token 截断不在这里做,那是 WorkingMemory 阶段
1211
+ * ToolPairTruncator 的职责;本处理器只决定“工具组是原样保留还是压缩为摘要消息”。
1212
+ */
1213
+ declare class ToolHistoryCompressorPreprocessor extends BasePreprocessor {
1214
+ 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";
1216
+ readonly priority = 0;
1217
+ private summarizer;
1218
+ private readonly options;
1219
+ constructor(options?: ToolHistoryCompressorOptions);
1220
+ process(messages: AiMessage[], context: PreprocessorContext): Promise<PreprocessorResult>;
1221
+ shouldSkip(messages: AiMessage[], context: PreprocessorContext): boolean;
1222
+ private compressToolCallPairsInHistory;
1223
+ private selectGroupsToKeep;
1224
+ private enforceMaxInteractionGroups;
1225
+ private compressToolInteractionGroup;
1226
+ }
1227
+
1228
+ interface ToolReplayProtocolGuardOptions {
1229
+ policy?: ToolReplayProtocolPolicy;
1230
+ priority?: number;
1231
+ }
1232
+ declare function resolveToolReplayProtocolPolicy(context: PreprocessorContext, explicitPolicy?: ToolReplayProtocolPolicy): ToolReplayProtocolPolicy;
1233
+ /**
1234
+ * Agent 工具回放协议守卫。
1235
+ *
1236
+ * 中文说明:
1237
+ * - 正向链路必须优先保证真实 provider sidecar 不丢;
1238
+ * - 这里仅处理“已经进入历史轮次”的旧工具组,避免它们继续伪装成结构化 replay;
1239
+ * - 当前轮次的工具组不在这里降级,否则会掩盖新链路丢 sidecar 的根因。
1240
+ */
1241
+ declare class ToolReplayProtocolGuardPreprocessor extends BasePreprocessor {
1242
+ readonly name = "ToolReplayProtocolGuardPreprocessor";
1243
+ readonly description = "\u5DE5\u5177\u56DE\u653E\u534F\u8BAE\u5B88\u536B - \u5BF9\u8981\u6C42 provider sidecar \u7684\u5386\u53F2\u5DE5\u5177\u7EC4\u6267\u884C\u7ED3\u6784\u5316\u56DE\u653E\u6CBB\u7406";
1244
+ readonly priority: number;
1245
+ private readonly explicitPolicy?;
1246
+ constructor(options?: ToolReplayProtocolGuardOptions);
1247
+ shouldSkip(messages: AiMessage[], context: PreprocessorContext): boolean;
1248
+ process(messages: AiMessage[], context: PreprocessorContext): Promise<PreprocessorResult>;
1249
+ }
1250
+
1251
+ interface DefaultAgentPreprocessorRegistryOptions {
1252
+ fenceRegistry?: FenceRegistry;
1253
+ toolHistory?: ToolHistoryCompressorOptions;
1254
+ providerReplay?: ToolReplayProtocolPolicy;
1255
+ }
1256
+ /**
1257
+ * 预处理器注册表 - 管理所有预处理器及其执行顺序
1258
+ */
1259
+ declare class PreprocessorRegistry {
1260
+ private preprocessors;
1261
+ /**
1262
+ * 注册预处理器
1263
+ */
1264
+ register(preprocessor: IPreprocessor): void;
1265
+ /**
1266
+ * 获取指定名称的预处理器
1267
+ */
1268
+ getPreprocessor(name: string): IPreprocessor | undefined;
1269
+ /**
1270
+ * 获取所有预处理器,按优先级排序
1271
+ */
1272
+ getAllPreprocessors(): IPreprocessor[];
1273
+ /**
1274
+ * 获取已注册的预处理器名称列表
1275
+ */
1276
+ getRegisteredNames(): string[];
1277
+ /**
1278
+ * 检查是否已注册指定预处理器
1279
+ */
1280
+ isRegistered(name: string): boolean;
1281
+ /**
1282
+ * 获取注册的预处理器数量
1283
+ */
1284
+ getCount(): number;
1285
+ }
1286
+ /**
1287
+ * 预处理管道 - 按顺序执行所有预处理器
1288
+ */
1289
+ declare class PreprocessorPipeline {
1290
+ private registry;
1291
+ private context;
1292
+ constructor(registry: PreprocessorRegistry, context?: PreprocessorContext);
1293
+ /**
1294
+ * 执行完整的预处理管道
1295
+ *
1296
+ * @param messages 输入消息列表
1297
+ * @returns 预处理管道的汇总结果
1298
+ */
1299
+ process(messages: AiMessage[]): Promise<PreprocessorPipelineResult>;
1300
+ /**
1301
+ * 更新预处理上下文
1302
+ */
1303
+ updateContext(newContext: Partial<PreprocessorContext>): void;
1304
+ /**
1305
+ * 获取当前上下文
1306
+ */
1307
+ getContext(): PreprocessorContext;
1308
+ /**
1309
+ * 调试日志
1310
+ */
1311
+ private debug;
1312
+ }
1313
+ /**
1314
+ * 预处理管道结果接口
1315
+ */
1316
+ interface PreprocessorPipelineResult {
1317
+ /** 预处理后的消息列表 */
1318
+ messages: AiMessage[];
1319
+ /** 管道级别的统计信息 */
1320
+ pipelineStats: {
1321
+ originalCount: number;
1322
+ finalCount: number;
1323
+ totalRemovedCount: number;
1324
+ processingTime: number;
1325
+ preprocessorsExecuted: number;
1326
+ appliedStrategies: string[];
1327
+ };
1328
+ /** 各个预处理器的详细结果 */
1329
+ individualResults: Array<{
1330
+ preprocessor: string;
1331
+ result: PreprocessorResult;
1332
+ }>;
1333
+ }
1334
+ /**
1335
+ * 创建默认的Agent预处理器注册表
1336
+ *
1337
+ * 🔥 这里定义了Agent预处理管道的默认配置:
1338
+ * 1. ToolHistoryCompressorPreprocessor (priority: 0) - 工具历史压缩,最先执行
1339
+ * 2. ToolReplayProtocolGuardPreprocessor (priority: 0.5) - 工具回放协议守卫,仅治理历史轮次
1340
+ * 3. HistoryPurificationPreprocessor (priority: 1) - Agent历史净化,在压缩后执行
1341
+ *
1342
+ * 💡 未来可扩展:
1343
+ * 3. AgentToolCallValidationPreprocessor (priority: 2) - 工具调用验证
1344
+ * 4. AgentContextOptimizationPreprocessor (priority: 3) - 上下文优化
1345
+ */
1346
+ declare function createDefaultAgentPreprocessorRegistry(options?: DefaultAgentPreprocessorRegistryOptions): PreprocessorRegistry;
1347
+ /**
1348
+ * 创建默认的Agent预处理管道
1349
+ *
1350
+ * @param context 预处理上下文配置
1351
+ * @returns 配置好的Agent预处理管道实例
1352
+ */
1353
+ declare function createDefaultAgentPreprocessorPipeline(context?: PreprocessorContext, options?: DefaultAgentPreprocessorRegistryOptions): PreprocessorPipeline;
1354
+
1355
+ type index$4_BasePreprocessor = BasePreprocessor;
1356
+ declare const index$4_BasePreprocessor: typeof BasePreprocessor;
1357
+ type index$4_DefaultAgentPreprocessorRegistryOptions = DefaultAgentPreprocessorRegistryOptions;
1358
+ type index$4_FenceLifetimePreprocessor = FenceLifetimePreprocessor;
1359
+ declare const index$4_FenceLifetimePreprocessor: typeof FenceLifetimePreprocessor;
1360
+ type index$4_HistoryPurificationPreprocessor = HistoryPurificationPreprocessor;
1361
+ declare const index$4_HistoryPurificationPreprocessor: typeof HistoryPurificationPreprocessor;
1362
+ type index$4_IPreprocessor = IPreprocessor;
1363
+ type index$4_MissingSidecarBehavior = MissingSidecarBehavior;
1364
+ type index$4_PreprocessorContext = PreprocessorContext;
1365
+ type index$4_PreprocessorPipeline = PreprocessorPipeline;
1366
+ declare const index$4_PreprocessorPipeline: typeof PreprocessorPipeline;
1367
+ type index$4_PreprocessorPipelineResult = PreprocessorPipelineResult;
1368
+ type index$4_PreprocessorRegistry = PreprocessorRegistry;
1369
+ declare const index$4_PreprocessorRegistry: typeof PreprocessorRegistry;
1370
+ type index$4_PreprocessorResult = PreprocessorResult;
1371
+ type index$4_ToolHistoryCompressionStrategy = ToolHistoryCompressionStrategy;
1372
+ type index$4_ToolHistoryCompressorOptions = ToolHistoryCompressorOptions;
1373
+ type index$4_ToolHistoryCompressorPreprocessor = ToolHistoryCompressorPreprocessor;
1374
+ declare const index$4_ToolHistoryCompressorPreprocessor: typeof ToolHistoryCompressorPreprocessor;
1375
+ type index$4_ToolHistoryOverflowStrategy = ToolHistoryOverflowStrategy;
1376
+ type index$4_ToolReplayProtocolGuardOptions = ToolReplayProtocolGuardOptions;
1377
+ type index$4_ToolReplayProtocolGuardPreprocessor = ToolReplayProtocolGuardPreprocessor;
1378
+ declare const index$4_ToolReplayProtocolGuardPreprocessor: typeof ToolReplayProtocolGuardPreprocessor;
1379
+ type index$4_ToolReplayProtocolPolicy = ToolReplayProtocolPolicy;
1380
+ declare const index$4_createDefaultAgentPreprocessorPipeline: typeof createDefaultAgentPreprocessorPipeline;
1381
+ declare const index$4_createDefaultAgentPreprocessorRegistry: typeof createDefaultAgentPreprocessorRegistry;
1382
+ declare const index$4_resolveToolReplayProtocolPolicy: typeof resolveToolReplayProtocolPolicy;
1383
+ 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 };
1385
+ }
1386
+
1387
+ interface ToolManagerRegistry extends ToolSummaryProvider {
1388
+ getAvailableToolNames(toolNames?: string[]): string[];
1389
+ validateToolCall(toolName: string, args: ToolArgs): {
1390
+ success: boolean;
1391
+ error?: string;
1392
+ };
1393
+ }
1394
+ interface DynamicToolContext {
1395
+ request: AgentProfileRequest;
1396
+ }
1397
+ declare class ToolManager {
1398
+ private readonly registry;
1399
+ constructor(registry: ToolManagerRegistry);
1400
+ getAvailableToolNames(context: DynamicToolContext): string[];
1401
+ validateToolCall(toolName: string, args: ToolArgs, context: DynamicToolContext): {
1402
+ success: boolean;
1403
+ error?: string;
1404
+ };
1405
+ getSummaryProvider(): ToolSummaryProvider;
1406
+ }
1407
+
1408
+ interface IAgentTask {
1409
+ readonly name: string;
1410
+ buildMessages(request: AgentProfileRequest, history: AiMessage[]): AiMessage[];
1411
+ processResponse(rawResponse: string): string;
1412
+ processStreamChunk(chunk: string): string;
1413
+ getPreferredModelCapability?(): string;
1414
+ }
1415
+ type AgentTaskResolver = (promptKey: string) => IAgentTask;
1416
+ interface IAgentTaskRegistry {
1417
+ register(promptKey: string, task: IAgentTask): void;
1418
+ getTask(promptKey: string): IAgentTask | null;
1419
+ getAllTaskKeys(): string[];
1420
+ }
1421
+
1422
+ interface AgentOrchestratorOptions {
1423
+ tokenBudget: {
1424
+ maxTokens: number;
1425
+ reservedForResponse: number;
1426
+ };
1427
+ processing: {
1428
+ debugMode?: boolean;
1429
+ preserveMetadata?: boolean;
1430
+ };
1431
+ model?: string;
1432
+ resolveToolReplayProtocolPolicy?: (params: {
1433
+ request: AgentProfileRequest;
1434
+ modelId: string;
1435
+ }) => ToolReplayProtocolPolicy | undefined;
1436
+ resolveContextPolicy?: (request: AgentProfileRequest) => AgentSpecContextPolicy | undefined;
1437
+ createProviderRegistry?: (params: {
1438
+ request: AgentProfileRequest;
1439
+ contextPolicy: AgentSpecContextPolicy | undefined;
1440
+ contextBuilderConfig: Partial<AgentContextBuilderConfig>;
1441
+ }) => ContextProviderRegistry$1;
1442
+ taskResolver: AgentTaskResolver;
1443
+ providerRegistry: ContextProviderRegistry$1;
1444
+ fenceRegistry?: FenceRegistry;
1445
+ tokenizer?: TokenizerPort;
1446
+ }
1447
+ interface AgentProcessingResult {
1448
+ messages: AiMessage[];
1449
+ contextBuildResult: ContextBuildResult$1;
1450
+ metadata: {
1451
+ originalCount: number;
1452
+ processedCount: number;
1453
+ tokenUsage: {
1454
+ estimated: number;
1455
+ budget: number;
1456
+ remaining: number;
1457
+ };
1458
+ processingStats: ContextBuildResult$1['processingStats'];
1459
+ truncated: boolean;
1460
+ truncatedCount?: number;
1461
+ };
1462
+ }
1463
+ declare class AgentMessageOrchestrator {
1464
+ private agentContextManager;
1465
+ private options;
1466
+ private readonly taskResolver;
1467
+ private baseContextConfig;
1468
+ constructor(options: AgentOrchestratorOptions);
1469
+ private buildPreprocessorPipelineForRequest;
1470
+ private resolvePreprocessorModel;
1471
+ private resolveContextPolicy;
1472
+ private applyContextPolicy;
1473
+ processAgentConversation(request: AgentProfileRequest, history: RuntimeEvent[], toolManager: ToolManager, callbacks?: SummarizationCallbacks, extraOptions?: {
1474
+ generate?: (request: GenerateRequest) => Promise<GenerateResponse>;
1475
+ }): Promise<AgentProcessingResult>;
1476
+ private buildCompleteMessageList;
1477
+ private runPreprocessorPipeline;
1478
+ private buildContextFromPreprocessedMessages;
1479
+ private debug;
1480
+ updateOptions(newOptions: Partial<AgentOrchestratorOptions>): void;
1481
+ getContextManager(): AgentContextManager;
1482
+ getContextInfo(): {
1483
+ config: AgentContextBuilderConfig;
1484
+ };
1485
+ }
1486
+
1487
+ type index$3_AgentMessageOrchestrator = AgentMessageOrchestrator;
1488
+ declare const index$3_AgentMessageOrchestrator: typeof AgentMessageOrchestrator;
1489
+ type index$3_AgentOrchestratorOptions = AgentOrchestratorOptions;
1490
+ type index$3_AgentProcessingResult = AgentProcessingResult;
1491
+ declare namespace index$3 {
1492
+ export { index$3_AgentMessageOrchestrator as AgentMessageOrchestrator, type index$3_AgentOrchestratorOptions as AgentOrchestratorOptions, type index$3_AgentProcessingResult as AgentProcessingResult };
1493
+ }
1494
+
1495
+ /**
1496
+ * @file src/agent/context-manager/profiles/agent/tasks/BaseAgentTask.ts
1497
+ * @description Agent任务的抽象基类 - 处理Agent通用逻辑
1498
+ *
1499
+ * 🔥 重构:借鉴 BaseConversationalTask 的轻量级设计
1500
+ * 专注于核心消息构建,将复杂的上下文管理交给 AgentContextManager
1501
+ */
1502
+
1503
+ interface BaseAgentTaskOptions {
1504
+ fenceRegistry?: FenceRegistry;
1505
+ }
1506
+ /**
1507
+ * Agent任务的抽象基类
1508
+ *
1509
+ * @abstract
1510
+ * @description
1511
+ * 现在只负责构建 Agent 任务的核心消息骨架:
1512
+ * - system prompt
1513
+ * - host-provided context injection messages
1514
+ * - 当前 user query
1515
+ * - 按时序附加 history
1516
+ */
1517
+ declare abstract class BaseAgentTask implements IAgentTask {
1518
+ abstract readonly name: string;
1519
+ private readonly fenceRegistry?;
1520
+ constructor(options?: BaseAgentTaskOptions);
1521
+ protected abstract getSystemPrompt(request: AgentProfileRequest): string;
1522
+ getSystemPromptForRequest(request: AgentProfileRequest): string;
1523
+ buildMessages(request: AgentProfileRequest, history: AiMessage[]): AiMessage[];
1524
+ private createFenceMessages;
1525
+ private createFenceMessage;
1526
+ private insertAfterLastToolResult;
1527
+ processResponse(rawResponse: string): string;
1528
+ processStreamChunk(chunk: string): string;
1529
+ }
1530
+
1531
+ type index$2_AgentTaskResolver = AgentTaskResolver;
1532
+ type index$2_BaseAgentTask = BaseAgentTask;
1533
+ declare const index$2_BaseAgentTask: typeof BaseAgentTask;
1534
+ type index$2_IAgentTask = IAgentTask;
1535
+ type index$2_IAgentTaskRegistry = IAgentTaskRegistry;
1536
+ declare namespace index$2 {
1537
+ export { type index$2_AgentTaskResolver as AgentTaskResolver, index$2_BaseAgentTask as BaseAgentTask, type index$2_IAgentTask as IAgentTask, type index$2_IAgentTaskRegistry as IAgentTaskRegistry };
1538
+ }
1539
+
1540
+ type index$1_DynamicToolContext = DynamicToolContext;
1541
+ type index$1_ToolManager = ToolManager;
1542
+ declare const index$1_ToolManager: typeof ToolManager;
1543
+ type index$1_ToolManagerRegistry = ToolManagerRegistry;
1544
+ declare namespace index$1 {
1545
+ export { type index$1_DynamicToolContext as DynamicToolContext, index$1_ToolManager as ToolManager, type index$1_ToolManagerRegistry as ToolManagerRegistry };
1546
+ }
1547
+
1548
+ declare function convertEventToAiMessage(event: RuntimeEvent): AiMessage;
1549
+ declare function convertEventsToAiMessages(events: RuntimeEvent[]): AiMessage[];
1550
+ declare function convertAiMessageToEvent(message: AiMessage, overrides?: Partial<RuntimeEvent>): RuntimeEvent;
1551
+
1552
+ type ToolCallRecord = {
1553
+ id: string;
1554
+ type?: string;
1555
+ function?: {
1556
+ name?: string;
1557
+ arguments?: string;
1558
+ };
1559
+ };
1560
+ interface ToolInteractionGroupBuildOptions {
1561
+ /**
1562
+ * 工具调用与工具结果允许相隔的最大消息数。
1563
+ *
1564
+ * 中文备注:超过窗口的 tool_output 不再配对,避免很旧的 tool_calls 被远处结果误粘连。
1565
+ */
1566
+ maxPairingDistance?: number;
1567
+ /** 识别 checkpoint 工具组的工具名。默认保持 0.5.x 的 context_checkpoint。 */
1568
+ checkpointToolName?: string;
1569
+ }
1570
+ interface ToolInteractionGroupItem<T> {
1571
+ toolCallId: string;
1572
+ toolName: string;
1573
+ toolArgs: Record<string, unknown>;
1574
+ toolCall: ToolCallRecord;
1575
+ toolOutputs: T[];
1576
+ toolOutputMessages: AiMessage[];
1577
+ rawOutputs: string[];
1578
+ }
1579
+ interface ToolInteractionGroup<T> {
1580
+ anchorId: string;
1581
+ /** 工具组所属的用户轮次序号:0 表示第一条 user_input 之前,之后每遇到一条 user_input 递增。 */
1582
+ runOrdinal: number;
1583
+ assistantState: T;
1584
+ assistantMessage: AiMessage;
1585
+ assistantIndex: number;
1586
+ toolOutputs: T[];
1587
+ toolOutputMessages: AiMessage[];
1588
+ toolOutputIndexes: number[];
1589
+ toolCallIds: string[];
1590
+ toolNames: string[];
1591
+ sourceMessageIds: string[];
1592
+ messageIndexes: number[];
1593
+ startIndex: number;
1594
+ endIndex: number;
1595
+ isCheckpointGroup: boolean;
1596
+ isComplete: boolean;
1597
+ isCompressed: boolean;
1598
+ items: ToolInteractionGroupItem<T>[];
1599
+ messages: T[];
1600
+ }
1601
+ declare function collectToolInteractionGroups<T extends MessageProcessingState>(states: T[]): ToolInteractionGroup<T>[];
1602
+ declare function buildToolInteractionGroupsFromMessages(messages: AiMessage[], options?: {
1603
+ startIndex?: number;
1604
+ endIndexExclusive?: number;
1605
+ }): ToolInteractionGroup<AiMessage>[];
1606
+ declare function buildToolInteractionGroupsFromStates(states: MessageProcessingState[], options?: ToolInteractionGroupBuildOptions): ToolInteractionGroup<MessageProcessingState>[];
1607
+ declare function findCurrentRunStartIndex(messages: AiMessage[]): number;
1608
+ /** @deprecated 使用 findCurrentRunStartIndex。旧名保留一个 sprint,避免下游 deep import 立刻断裂。 */
1609
+ declare const findCurrentRoundStartIndex: typeof findCurrentRunStartIndex;
1610
+ declare function findLastUserInputOriginalIndex(states: MessageProcessingState[]): number | null;
1611
+
1612
+ type UnknownRecord = Record<string, unknown>;
1613
+ interface SummarizerConfig {
1614
+ fullContentThreshold: number;
1615
+ textPreviewLength: number;
1616
+ arrayPreviewCount: number;
1617
+ objectPreviewFieldCount: number;
1618
+ }
1619
+ declare const DEFAULT_SUMMARIZER_CONFIG: SummarizerConfig;
1620
+ declare class ToolOutputSummarizer {
1621
+ private config;
1622
+ constructor(config?: Partial<SummarizerConfig>);
1623
+ getSummary(toolName: string, output: string, toolSummaryProvider?: ToolSummaryProvider, toolArgs?: UnknownRecord): string;
1624
+ formatToolArgs(args: UnknownRecord): string;
1625
+ private tryToolSpecificSummary;
1626
+ private createGenericSummary;
1627
+ private summarizeArray;
1628
+ private summarizeObject;
1629
+ private summarizeText;
1630
+ }
1631
+ declare const createDefaultToolOutputSummarizer: (config?: Partial<SummarizerConfig>) => ToolOutputSummarizer;
1632
+ declare const summarizeToolOutput: (toolName: string, output: string, toolSummaryProvider?: ToolSummaryProvider, toolArgs?: UnknownRecord, config?: Partial<SummarizerConfig>) => string;
1633
+
1634
+ declare const index_DEFAULT_SUMMARIZER_CONFIG: typeof DEFAULT_SUMMARIZER_CONFIG;
1635
+ type index_SummarizerConfig = SummarizerConfig;
1636
+ type index_ToolInteractionGroup<T> = ToolInteractionGroup<T>;
1637
+ type index_ToolInteractionGroupItem<T> = ToolInteractionGroupItem<T>;
1638
+ type index_ToolOutputSummarizer = ToolOutputSummarizer;
1639
+ declare const index_ToolOutputSummarizer: typeof ToolOutputSummarizer;
1640
+ declare const index_buildToolInteractionGroupsFromMessages: typeof buildToolInteractionGroupsFromMessages;
1641
+ declare const index_buildToolInteractionGroupsFromStates: typeof buildToolInteractionGroupsFromStates;
1642
+ declare const index_collectToolInteractionGroups: typeof collectToolInteractionGroups;
1643
+ declare const index_convertAiMessageToEvent: typeof convertAiMessageToEvent;
1644
+ declare const index_convertEventToAiMessage: typeof convertEventToAiMessage;
1645
+ declare const index_convertEventsToAiMessages: typeof convertEventsToAiMessages;
1646
+ declare const index_createDefaultToolOutputSummarizer: typeof createDefaultToolOutputSummarizer;
1647
+ declare const index_findCurrentRoundStartIndex: typeof findCurrentRoundStartIndex;
1648
+ declare const index_findCurrentRunStartIndex: typeof findCurrentRunStartIndex;
1649
+ declare const index_findLastUserInputOriginalIndex: typeof findLastUserInputOriginalIndex;
1650
+ declare const index_summarizeToolOutput: typeof summarizeToolOutput;
1651
+ declare namespace index {
1652
+ export { index_DEFAULT_SUMMARIZER_CONFIG as DEFAULT_SUMMARIZER_CONFIG, type index_SummarizerConfig as SummarizerConfig, type index_ToolInteractionGroup as ToolInteractionGroup, type index_ToolInteractionGroupItem as ToolInteractionGroupItem, index_ToolOutputSummarizer as ToolOutputSummarizer, index_buildToolInteractionGroupsFromMessages as buildToolInteractionGroupsFromMessages, index_buildToolInteractionGroupsFromStates as buildToolInteractionGroupsFromStates, index_collectToolInteractionGroups as collectToolInteractionGroups, index_convertAiMessageToEvent as convertAiMessageToEvent, index_convertEventToAiMessage as convertEventToAiMessage, index_convertEventsToAiMessages as convertEventsToAiMessages, index_createDefaultToolOutputSummarizer as createDefaultToolOutputSummarizer, index_findCurrentRoundStartIndex as findCurrentRoundStartIndex, index_findCurrentRunStartIndex as findCurrentRunStartIndex, index_findLastUserInputOriginalIndex as findLastUserInputOriginalIndex, index_summarizeToolOutput as summarizeToolOutput };
1653
+ }
1654
+
1655
+ /**
1656
+ * 上下文构建策略配置的类型定义
1657
+ * 使用通用类型(如 number)而不是字面量类型,以增加灵活性
1658
+ */
1659
+ type ContextBuilderConfig = {
1660
+ readonly DEFAULT_MAX_TOKENS: number;
1661
+ readonly RESERVED_FOR_RESPONSE: number;
1662
+ readonly SUMMARIZATION_TRIGGER_THRESHOLD: number;
1663
+ readonly SUMMARY_BUDGET_PERCENTAGE: number;
1664
+ readonly SUMMARY_OLDEST_MESSAGES_PERCENTAGE: number;
1665
+ readonly DOCUMENT_FRAGMENT_MAX_PERCENTAGE: number;
1666
+ readonly THINKING_RECALL_COUNT: number;
1667
+ readonly CORE_MESSAGE_TYPES: readonly ('system_prompt' | 'user_input' | 'document_fragment')[];
1668
+ readonly PRIORITY_CONTENT_TYPES: readonly ('final_answer' | 'task_completion' | 'user_input')[];
1669
+ readonly SECONDARY_CONTENT_TYPES: readonly ('thought')[];
1670
+ readonly AVG_CHARS_PER_TOKEN: number;
1671
+ readonly TOKEN_ENCODING_NAME: string;
1672
+ readonly ENABLE_BUILD_STATS: boolean;
1673
+ readonly ENABLE_TIMING_STATS: boolean;
1674
+ readonly PROCESSING_TIMEOUT_MS: number;
1675
+ readonly LARGE_SUMMARIZATION_WARNING_THRESHOLD: number;
1676
+ };
1677
+ /**
1678
+ * 阶段执行优先级枚举
1679
+ * 用于标识和排序3个构建阶段
1680
+ */
1681
+ declare enum BuildPhase {
1682
+ /** 阶段1: 核心上下文保留层 */
1683
+ CORE_CONTEXT = 1,
1684
+ /** 阶段2: 工作记忆填充层 */
1685
+ WORKING_MEMORY = 2,
1686
+ /** 阶段3: 历史摘要触发层 */
1687
+ SUMMARIZATION = 3
1688
+ }
1689
+ /**
1690
+ * 上下文构建统计接口
1691
+ */
1692
+ interface ContextBuildStats {
1693
+ /** 构建开始时间 */
1694
+ startTime: number;
1695
+ /** 各阶段执行时间 */
1696
+ phaseTiming: Record<BuildPhase, number>;
1697
+ /** 各阶段token使用情况 */
1698
+ phaseTokenUsage: Record<BuildPhase, {
1699
+ used: number;
1700
+ percentage: number;
1701
+ }>;
1702
+ /** 消息数量统计 */
1703
+ messageStats: {
1704
+ original: number;
1705
+ afterCoreContext: number;
1706
+ afterWorkingMemory: number;
1707
+ afterSummarization: number;
1708
+ };
1709
+ /** 是否触发了摘要机制 */
1710
+ summarizationTriggered: boolean;
1711
+ /** 被摘要的消息数量 */
1712
+ summarizedCount?: number;
1713
+ /** 文档片段是否被截断 */
1714
+ documentTruncated: boolean;
1715
+ /** 总构建时间 */
1716
+ totalTime: number;
1717
+ }
1718
+ /**
1719
+ * 获取默认Token配置的辅助函数
1720
+ * @returns Token预算配置对象
1721
+ */
1722
+ declare function getDefaultTokenConfig(): {
1723
+ maxTokens: number;
1724
+ reservedForResponse: number;
1725
+ availableForContext: number;
1726
+ };
1727
+
1728
+ type ProviderContext = ProviderContext$2<ContextBuilderConfig>;
1729
+ interface IContextProvider extends IContextProvider$2<ContextBuilderConfig> {
1730
+ }
1731
+ declare abstract class BaseContextProvider extends BaseContextProvider$2<ContextBuilderConfig> implements IContextProvider {
1732
+ }
1733
+
1734
+ /**
1735
+ * @file src/chat/context/providers/CoreContextProvider.ts
1736
+ * @description 核心上下文保留层Provider - 第一阶段上下文构建
1737
+ *
1738
+ * 🎯 职责: 识别并保留必须保留的核心消息
1739
+ * 📖 规则: 系统提示词、最新用户输入、文档片段始终无条件保留
1740
+ * ✨ 特性: 支持文档片段智能截断,确保核心请求的完整性
1741
+ */
1742
+
1743
+ /**
1744
+ * 核心上下文保留层Provider
1745
+ *
1746
+ * 实现README中描述的第一阶段:核心上下文保留层 (Must-Keep)
1747
+ * 内容包括:系统提示词、用户意图块(最新用户输入+相关上下文信息)
1748
+ */
1749
+ declare class CoreContextProvider extends BaseContextProvider {
1750
+ readonly name = "CoreContextProvider";
1751
+ readonly description = "\u6838\u5FC3\u4E0A\u4E0B\u6587\u4FDD\u7559\u5C42 - \u8BC6\u522B\u5E76\u4FDD\u7559\u7CFB\u7EDF\u63D0\u793A\u8BCD\u3001\u6700\u65B0\u7528\u6237\u8F93\u5165\u548C\u6587\u6863\u7247\u6BB5";
1752
+ readonly priority = 1;
1753
+ provide(states: MessageProcessingState[], availableBudget: number, context: ProviderContext): Promise<ProviderResult>;
1754
+ /**
1755
+ * 判断是否为核心消息
1756
+ * 🔥 关键设计:只保留真正的核心消息
1757
+ */
1758
+ private isCoreMessage;
1759
+ /**
1760
+ * 内容截断 - 保持完整词汇
1761
+ * 复用ContextManager中的逻辑
1762
+ */
1763
+ private truncateContent;
1764
+ }
1765
+
1766
+ /**
1767
+ * @file src/chat/context/providers/WorkingMemoryProvider.ts
1768
+ * @description 工作记忆填充层Provider - 第二阶段上下文构建
1769
+ *
1770
+ * 🎯 职责: 使用剩余预算,从最近的历史消息开始反向逐条填充
1771
+ * 📖 策略: P1优先级(最终回答) + P2优先级(思维链回补)
1772
+ * ✨ 特性: 智能内容提取,最大化保留对话的"事实"和"结论"
1773
+ *
1774
+ * 🧩 说明(Chat 与工具消息):
1775
+ * - Chat 模式下,来自 Agent 历史的 `tool_calls/tool_output` 默认会被 `ToolHistoryFilterPreprocessor` 过滤掉,
1776
+ * 因此本 Provider 不承担“工具交互优先级/配对保留”等职责(这些属于 AgentWorkingMemoryProvider)。
1777
+ */
1778
+
1779
+ /**
1780
+ * 工作记忆填充层Provider
1781
+ *
1782
+ * 实现README中描述的第二阶段:工作记忆填充层 (Working Memory)
1783
+ * 使用剩余预算反向填充,优先保留最终回答,其次回补思维链
1784
+ */
1785
+ declare class WorkingMemoryProvider extends BaseContextProvider {
1786
+ readonly name = "WorkingMemoryProvider";
1787
+ readonly description = "\u5DE5\u4F5C\u8BB0\u5FC6\u586B\u5145\u5C42 - \u53CD\u5411\u586B\u5145\u6700\u7EC8\u56DE\u7B54\u548C\u601D\u7EF4\u94FE\uFF0C\u6700\u5927\u5316\u4FDD\u7559\u5BF9\u8BDD\u4E8B\u5B9E";
1788
+ readonly priority = 2;
1789
+ provide(states: MessageProcessingState[], availableBudget: number, context: ProviderContext): Promise<ProviderResult>;
1790
+ /**
1791
+ * P1优先级处理:反向填充最终回答部分
1792
+ */
1793
+ private processP1Priority;
1794
+ /**
1795
+ * P2优先级处理:回补思维链 + 历史摘要
1796
+ *
1797
+ * 💬 处理顺序(参考 AgentWorkingMemoryProvider):
1798
+ * 1. 首先处理 history_summary(如果有)
1799
+ * 2. 然后回补思维链
1800
+ */
1801
+ private processP2Priority;
1802
+ /**
1803
+ * 计算当前已使用的Token数
1804
+ */
1805
+ private calculateUsedTokens;
1806
+ /**
1807
+ * 提取AI消息的最终回答部分(移除<think>标签内容)
1808
+ */
1809
+ private extractFinalAnswerContent;
1810
+ }
1811
+
1812
+ /**
1813
+ * @file src/agent/context-manager/profiles/chat/context/providers/index.ts
1814
+ * @description Chat profile provider 协议与实现导出
1815
+ */
1816
+
1817
+ declare class ContextProviderRegistry extends ContextProviderRegistry$2<ContextBuilderConfig> {
1818
+ }
1819
+
1820
+ /**
1821
+ * 上下文构建结果接口 - 与TokenBudgetManager保持兼容
1822
+ */
1823
+ interface ContextBuildResult {
1824
+ /** 构建后的消息列表 */
1825
+ messages: AiMessage[];
1826
+ /** Token使用情况 */
1827
+ tokenUsage: {
1828
+ used: number;
1829
+ remaining: number;
1830
+ };
1831
+ /** 处理统计信息 - 兼容TokenBudgetManager格式 */
1832
+ processingStats: {
1833
+ originalCount: number;
1834
+ keptCount: number;
1835
+ truncatedCount: number;
1836
+ tokenDistribution: Record<string, number>;
1837
+ strategiesApplied: string[];
1838
+ recommendations: string[];
1839
+ buildStats?: ContextBuildStats;
1840
+ };
1841
+ /** 是否进行了截断 */
1842
+ truncated: boolean;
1843
+ /** 截断的消息数量 */
1844
+ truncatedCount?: number;
1845
+ /** 应用的策略列表 */
1846
+ strategies: {
1847
+ applied: string[];
1848
+ recommendations: string[];
1849
+ };
1850
+ /** 🔥 新增:Provider生成的运行时事件(如摘要事件) */
1851
+ events?: RuntimeEvent[];
1852
+ }
1853
+ /**
1854
+ * 智能上下文管理器 - Provider编排器
1855
+ *
1856
+ * 🎯 职责: 编排各个ContextProvider,协调3阶段上下文构建流程
1857
+ * 🏗️ 架构: 策略模式 + 责任链模式,实现高内聚、低耦合
1858
+ */
1859
+ declare class ContextManager extends ContextManagerBase<ContextBuilderConfig, ContextProviderRegistry> {
1860
+ constructor(options?: {
1861
+ debugMode?: boolean;
1862
+ customConfig?: Partial<ContextBuilderConfig>;
1863
+ providerRegistry?: ContextProviderRegistry;
1864
+ tokenizer?: TokenizerPort;
1865
+ tokenizerModelId?: string;
1866
+ });
1867
+ /**
1868
+ * 主入口:构建智能上下文 - Provider编排模式
1869
+ */
1870
+ buildContext(messages: AiMessage[], totalBudget: number, callbacks?: SummarizationCallbacks, generate?: (request: GenerateRequest) => Promise<GenerateResponse>): Promise<ContextBuildResult>;
1871
+ /**
1872
+ * 根据Provider名称获取对应的阶段名称
1873
+ */
1874
+ private getPhaseByProviderName;
1875
+ private initializeBuildStats;
1876
+ private buildFinalResult;
1877
+ /**
1878
+ * 生成优化建议
1879
+ */
1880
+ private generateRecommendations;
1881
+ /**
1882
+ * 获取Provider注册表(用于测试或调试)
1883
+ */
1884
+ getProviderRegistry(): ContextProviderRegistry;
1885
+ /**
1886
+ * 注册新的Provider
1887
+ */
1888
+ registerProvider(provider: IContextProvider): void;
1889
+ }
1890
+
1891
+ /**
1892
+ * @file src/agent/context-manager/profiles/chat/tasks/base.ts
1893
+ *
1894
+ * @brief 定义所有聊天任务处理器必须遵守的接口。
1895
+ *
1896
+ * @description
1897
+ * 每个业务场景(如自动补全、批注、标准聊天)都应实现此接口。
1898
+ * 这确保了 ChatService 可以用统一的方式调用它们。
1899
+ */
1900
+
1901
+ interface IChatTask {
1902
+ /**
1903
+ * 根据前端请求构建发送给大模型的完整消息数组。
1904
+ *
1905
+ * @param request 前端发来的生成请求
1906
+ * @returns 格式化后的 ChatMessage 数组
1907
+ */
1908
+ buildMessages(request: GenerateRequest): ChatMessage[];
1909
+ /**
1910
+ * (可选) 声明此任务是否应走“短链路”处理,
1911
+ * 即绕过复杂的上下文管理,直接将 buildMessages 的结果发送给 AI。
1912
+ * @default false
1913
+ */
1914
+ useSimpleProcessing?: boolean;
1915
+ /**
1916
+ * [新增] 声明此任务偏好使用的模型能力。
1917
+ * 如果设置了此项,并且用户没有在请求中明确指定 modelId,
1918
+ * ChatService会优先查找并使用具备该能力的模型。
1919
+ * @example 'fast_assistant'
1920
+ */
1921
+ preferredModelCapability?: string;
1922
+ /**
1923
+ * 对LLM返回的完整响应进行后处理。
1924
+ * @param rawResponse LLM返回的原始字符串
1925
+ * @returns 经过处理后的、适合返回给前端的文本
1926
+ *
1927
+ * @description
1928
+ * 不同的任务场景对响应内容有不同的处理需求:
1929
+ * - 聊天/批注:保留 <think>...</think> 标签,让用户看到思考过程
1930
+ * - 自动补全:过滤掉所有思考内容,只返回干净的补全文本
1931
+ */
1932
+ processResponse(rawResponse: string): string;
1933
+ /**
1934
+ * 对流式生成的单个内容块进行处理。
1935
+ *
1936
+ * @param chunk 流式生成的单个内容块
1937
+ * @returns 处理后的内容块,如果应该跳过则返回空字符串
1938
+ *
1939
+ * @description
1940
+ * 用于流式生成场景,让每个任务决定是否要过滤某些流式块:
1941
+ * - 聊天/批注:直接返回原块,保留所有内容
1942
+ * - 自动补全:过滤掉包含 <think> 标签的块
1943
+ */
1944
+ processStreamChunk(chunk: string): string;
1945
+ }
1946
+ type ChatTaskResolver = (promptKey?: string) => IChatTask;
1947
+
1948
+ /**
1949
+ * 编排器配置选项
1950
+ */
1951
+ interface OrchestratorOptions {
1952
+ /** Token预算配置 (现在由ContextManager内部管理,但保留API以兼容旧用法) */
1953
+ tokenBudget: {
1954
+ maxTokens: number;
1955
+ reservedForResponse: number;
1956
+ };
1957
+ /** 处理选项 */
1958
+ processing: {
1959
+ enableMerge?: boolean;
1960
+ enableBatch?: boolean;
1961
+ debugMode?: boolean;
1962
+ preserveMetadata?: boolean;
1963
+ };
1964
+ /** 系统提示词 */
1965
+ systemPrompt?: string;
1966
+ /** 模型名称 (用于精确Token计算) */
1967
+ model?: string;
1968
+ /** 任务解析器 */
1969
+ taskResolver: ChatTaskResolver;
1970
+ providerRegistry: ContextProviderRegistry;
1971
+ tokenizer?: TokenizerPort;
1972
+ }
1973
+ /**
1974
+ * 处理结果接口
1975
+ */
1976
+ interface ProcessingResult {
1977
+ /** 处理后的消息 (AI引擎格式) */
1978
+ messages: ChatMessage[];
1979
+ /** 完整的上下文构建结果,包含详细统计信息 */
1980
+ contextBuildResult: ContextBuildResult;
1981
+ /** 处理元信息 */
1982
+ metadata: {
1983
+ originalCount: number;
1984
+ processedCount: number;
1985
+ tokenUsage: {
1986
+ estimated: number;
1987
+ budget: number;
1988
+ remaining: number;
1989
+ };
1990
+ processingStats: ContextBuildResult['processingStats'];
1991
+ truncated: boolean;
1992
+ truncatedCount?: number;
1993
+ };
1994
+ }
1995
+ /**
1996
+ * 消息处理编排器
1997
+ *
1998
+ * 实现完整的处理流程:解析 → 分发 → 上下文构建 → 注入系统提示词 → 转换
1999
+ */
2000
+ declare class MessageOrchestrator {
2001
+ private contextManager;
2002
+ private preprocessorPipeline;
2003
+ private options;
2004
+ private readonly taskResolver;
2005
+ constructor(options: OrchestratorOptions);
2006
+ /**
2007
+ * 🔥 新增:与 AgentOrchestrator 对称的主方法
2008
+ * 负责从 AgentProfileRequest 构建完整的初始消息列表,然后进行处理
2009
+ */
2010
+ processChatConversation(request: AgentProfileRequest, callbacks?: SummarizationCallbacks, generate?: (request: GenerateRequest) => Promise<GenerateResponse>): Promise<ProcessingResult>;
2011
+ /**
2012
+ * 核心编排方法 - 处理一个预构建好的对话历史
2013
+ */
2014
+ processConversation(messages: AiMessage[], callbacks?: SummarizationCallbacks, generate?: (request: GenerateRequest) => Promise<GenerateResponse>): Promise<ProcessingResult>;
2015
+ /**
2016
+ * 封装了 buildContext 和 convertToChatMessages 的逻辑
2017
+ */
2018
+ private buildAndFinalizeContext;
2019
+ /**
2020
+ * 1. 解析和验证消息 - 直接使用原始消息,不进行格式转换
2021
+ */
2022
+ private parseAndValidateMessages;
2023
+ /**
2024
+ * 🔥 2. [预处理管道] - 运行所有注册的预处理器
2025
+ */
2026
+ private runPreprocessorPipeline;
2027
+ private resolveTokenizerModelId;
2028
+ /**
2029
+ * 3. [上下文构建] - 调用ContextManager进行智能Token预算和消息构建
2030
+ */
2031
+ private buildContext;
2032
+ /**
2033
+ * 4. [最终格式化] - 将内部AiMessage格式转换为外部API的ChatMessage格式
2034
+ */
2035
+ private convertToChatMessages;
2036
+ /**
2037
+ * 调试日志
2038
+ */
2039
+ private debug;
2040
+ /**
2041
+ * 更新配置
2042
+ */
2043
+ updateOptions(newOptions: Partial<OrchestratorOptions>): void;
2044
+ /**
2045
+ * 获取预算管理器 (用于高级配置) - 已更新为上下文管理器
2046
+ */
2047
+ getContextManager(): ContextManager;
2048
+ /**
2049
+ * 获取预算管理状态 - 已更新为上下文管理状态
2050
+ */
2051
+ getContextInfo(): {
2052
+ config: ContextBuilderConfig;
2053
+ };
2054
+ }
2055
+
2056
+ /**
2057
+ * @file src/agent/context-manager/profiles/chat/tasks/BaseConversationalTask.ts
2058
+ *
2059
+ * @brief 对话型任务的抽象基类 - 处理多轮对话场景的通用逻辑
2060
+ *
2061
+ * @description
2062
+ * BaseConversationalTask 是所有需要处理对话历史的任务的抽象基类。
2063
+ *
2064
+ * 🔥 设计理念(参考 BaseAgentTask):
2065
+ * - Task层:构建核心的、必须的消息(系统提示词 + 文档上下文 + 当前用户输入)
2066
+ * - ContextManager层:处理复杂的上下文管理、历史编排、Token优化
2067
+ *
2068
+ * 它封装了对话型任务的标准流程:
2069
+ * 1. 添加系统提示词(由子类实现)
2070
+ * 2. 添加文档上下文(如果提供)
2071
+ * 3. 添加当前用户输入(如果历史中没有用户消息)
2072
+ * 4. 附加完整的对话历史(不做任何过滤,保留所有消息包括 history_summary)
2073
+ *
2074
+ * 与工具型任务的区别:
2075
+ * - 工具型任务:使用 useSimpleProcessing=true,不处理对话历史,专注于单次请求
2076
+ * - 对话型任务:处理完整的对话上下文,支持多轮对话
2077
+ */
2078
+
2079
+ /**
2080
+ * 对话型任务的抽象基类
2081
+ *
2082
+ * @abstract
2083
+ * @description
2084
+ * 🔥 参考 BaseAgentTask 的轻量级设计,专注于核心消息构建
2085
+ *
2086
+ * 所有需要处理对话历史的任务都应该继承此类。
2087
+ * 该基类实现了标准的对话上下文构建流程,子类只需要实现系统提示词的获取。
2088
+ *
2089
+ * 重要特性:
2090
+ * - 不过滤任何历史消息,完整保留对话历史(包括 history_summary)
2091
+ * - 复杂的上下文管理由 ContextManager 层处理
2092
+ */
2093
+ declare abstract class BaseConversationalTask implements IChatTask {
2094
+ /**
2095
+ * 对话型任务默认使用完整处理链路(MessageOrchestrator)
2096
+ */
2097
+ readonly useSimpleProcessing = false;
2098
+ /**
2099
+ * 抽象方法:子类必须实现此方法来提供特定的系统提示词
2100
+ *
2101
+ * @abstract
2102
+ * @returns 系统提示词字符串
2103
+ */
2104
+ protected abstract getSystemPrompt(request: GenerateRequest): string;
2105
+ /**
2106
+ * 构建对话消息的标准流程
2107
+ *
2108
+ * @description
2109
+ * 🔥 参考 BaseAgentTask 的实现,实现了所有对话型任务都需要的标准流程:
2110
+ * 1. 添加系统提示词 - Task层拥有对系统指令的完全控制权
2111
+ * 2. 添加文档片段(如果有)
2112
+ * 3. 添加当前用户输入(仅当历史中没有用户消息时)
2113
+ * 4. 附加完整的对话历史(不做任何过滤,保留所有消息包括 history_summary)
2114
+ *
2115
+ * @param request 生成请求
2116
+ * @returns 构建好的消息数组
2117
+ */
2118
+ buildMessages(request: GenerateRequest): ChatMessage[];
2119
+ /**
2120
+ * 默认的响应处理 - 保留完整内容包括思考过程
2121
+ *
2122
+ * @description
2123
+ * 对话型任务通常保留完整的响应内容,包括 <think> 标签,
2124
+ * 让用户看到AI的思考过程。子类可以覆盖此方法来实现特定的处理逻辑。
2125
+ *
2126
+ * @param rawResponse LLM返回的原始响应
2127
+ * @returns 处理后的响应文本
2128
+ */
2129
+ processResponse(rawResponse: string): string;
2130
+ /**
2131
+ * 默认的流式块处理 - 直接返回原块
2132
+ *
2133
+ * @description
2134
+ * 对话型任务通常直接返回原始流式块,保留所有内容包括思考过程。
2135
+ * 子类可以覆盖此方法来实现特定的处理逻辑。
2136
+ *
2137
+ * @param chunk 流式内容块
2138
+ * @returns 处理后的内容块
2139
+ */
2140
+ processStreamChunk(chunk: string): string;
2141
+ }
2142
+
2143
+ /**
2144
+ * 将 RuntimeEvent 转换为 ChatMessage
2145
+ * (供 HistoryBuilder 使用,用于 Chat 模式的历史构建)
2146
+ */
2147
+ declare function convertEventToChatMessage(event: RuntimeEvent): ChatMessage | null;
2148
+ /**
2149
+ * 批量转换 RuntimeEvent 数组为 ChatMessage 数组
2150
+ * (用于 Chat 模式的历史构建)
2151
+ */
2152
+ declare function convertEventsToChatMessages(events: RuntimeEvent[]): ChatMessage[];
2153
+
2154
+ declare function aiMessageToChatMessage(aiMessage: AiMessage): ChatMessage;
2155
+ declare function chatMessageToAiMessage(chatMessage: ChatMessage, options?: {
2156
+ id?: string;
2157
+ timestamp?: number;
2158
+ }): AiMessage;
2159
+
2160
+ interface ChatGenerateRequestAdapterInput extends AgentProfileRequest {
2161
+ context_before?: string;
2162
+ context_after?: string;
2163
+ current_paragraph?: string;
2164
+ document_fragment?: string;
2165
+ document_title?: string;
2166
+ project_metadata?: {
2167
+ id?: string;
2168
+ name?: string;
2169
+ description?: string;
2170
+ };
2171
+ document_metadata?: {
2172
+ id?: string;
2173
+ title?: string;
2174
+ };
2175
+ user_quote?: {
2176
+ text: string;
2177
+ source?: Record<string, unknown>;
2178
+ display_label?: string;
2179
+ };
2180
+ completionLengthHint?: string;
2181
+ recentRejections?: GenerateRequest['recentRejections'];
2182
+ }
2183
+ /**
2184
+ * Product request adapter:
2185
+ * - keeps AgentInvokeRequest -> GenerateRequest conversion out of orchestrator core
2186
+ * - makes the remaining app-specific request shape explicit and replaceable
2187
+ */
2188
+ declare function buildGenerateRequestFromAgentRequest(request: ChatGenerateRequestAdapterInput, conversationHistory: AiMessage[]): GenerateRequest;
2189
+
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 };