@aigne/core 1.72.0-beta.7 → 1.72.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/lib/cjs/agents/agent.d.ts +2 -21
- package/lib/cjs/agents/agent.js +10 -15
- package/lib/cjs/agents/ai-agent.d.ts +20 -4
- package/lib/cjs/agents/ai-agent.js +37 -35
- package/lib/cjs/agents/image-model.d.ts +4 -4
- package/lib/cjs/agents/mcp-agent.d.ts +2 -2
- package/lib/cjs/agents/video-model.d.ts +4 -4
- package/lib/cjs/index.d.ts +1 -0
- package/lib/cjs/index.js +1 -0
- package/lib/cjs/loader/agent-yaml.d.ts +1 -2
- package/lib/cjs/loader/agent-yaml.js +0 -8
- package/lib/cjs/loader/index.d.ts +2 -2
- package/lib/cjs/memory/recorder.d.ts +4 -4
- package/lib/cjs/memory/retriever.d.ts +4 -4
- package/lib/cjs/prompt/agent-session.d.ts +53 -0
- package/lib/cjs/prompt/agent-session.js +345 -0
- package/lib/cjs/prompt/compact/compactor.d.ts +7 -0
- package/lib/cjs/prompt/compact/compactor.js +48 -0
- package/lib/cjs/prompt/compact/types.d.ts +79 -0
- package/lib/cjs/prompt/compact/types.js +19 -0
- package/lib/cjs/prompt/context/afs/history.js +1 -1
- package/lib/cjs/prompt/prompt-builder.d.ts +6 -8
- package/lib/cjs/prompt/prompt-builder.js +67 -123
- package/lib/cjs/prompt/skills/afs/agent-skill/skill-loader.js +1 -0
- package/lib/cjs/prompt/template.d.ts +16 -16
- package/lib/dts/agents/agent.d.ts +2 -21
- package/lib/dts/agents/ai-agent.d.ts +20 -4
- package/lib/dts/agents/image-model.d.ts +4 -4
- package/lib/dts/agents/mcp-agent.d.ts +2 -2
- package/lib/dts/agents/video-model.d.ts +4 -4
- package/lib/dts/index.d.ts +1 -0
- package/lib/dts/loader/agent-yaml.d.ts +1 -2
- package/lib/dts/loader/index.d.ts +2 -2
- package/lib/dts/memory/recorder.d.ts +4 -4
- package/lib/dts/memory/retriever.d.ts +4 -4
- package/lib/dts/prompt/agent-session.d.ts +53 -0
- package/lib/dts/prompt/compact/compactor.d.ts +7 -0
- package/lib/dts/prompt/compact/types.d.ts +79 -0
- package/lib/dts/prompt/prompt-builder.d.ts +6 -8
- package/lib/dts/prompt/template.d.ts +16 -16
- package/lib/esm/agents/agent.d.ts +2 -21
- package/lib/esm/agents/agent.js +10 -15
- package/lib/esm/agents/ai-agent.d.ts +20 -4
- package/lib/esm/agents/ai-agent.js +37 -35
- package/lib/esm/agents/image-model.d.ts +4 -4
- package/lib/esm/agents/mcp-agent.d.ts +2 -2
- package/lib/esm/agents/video-model.d.ts +4 -4
- package/lib/esm/index.d.ts +1 -0
- package/lib/esm/index.js +1 -0
- package/lib/esm/loader/agent-yaml.d.ts +1 -2
- package/lib/esm/loader/agent-yaml.js +0 -8
- package/lib/esm/loader/index.d.ts +2 -2
- package/lib/esm/memory/recorder.d.ts +4 -4
- package/lib/esm/memory/retriever.d.ts +4 -4
- package/lib/esm/prompt/agent-session.d.ts +53 -0
- package/lib/esm/prompt/agent-session.js +308 -0
- package/lib/esm/prompt/compact/compactor.d.ts +7 -0
- package/lib/esm/prompt/compact/compactor.js +44 -0
- package/lib/esm/prompt/compact/types.d.ts +79 -0
- package/lib/esm/prompt/compact/types.js +16 -0
- package/lib/esm/prompt/context/afs/history.js +1 -1
- package/lib/esm/prompt/prompt-builder.d.ts +6 -8
- package/lib/esm/prompt/prompt-builder.js +68 -124
- package/lib/esm/prompt/skills/afs/agent-skill/skill-loader.js +1 -0
- package/lib/esm/prompt/template.d.ts +16 -16
- package/package.json +4 -4
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { AFSHistory } from "@aigne/afs-history";
|
|
2
|
+
import { v7 } from "@aigne/uuid";
|
|
3
|
+
import { joinURL } from "ufo";
|
|
4
|
+
import { estimateTokens } from "../utils/token-estimator.js";
|
|
5
|
+
import { isNonNullable } from "../utils/type-utils.js";
|
|
6
|
+
import { DEFAULT_COMPACT_ASYNC, DEFAULT_COMPACT_MODE, DEFAULT_KEEP_RECENT_RATIO, DEFAULT_MAX_TOKENS, } from "./compact/types.js";
|
|
7
|
+
export class AgentSession {
|
|
8
|
+
sessionId;
|
|
9
|
+
userId;
|
|
10
|
+
agentId;
|
|
11
|
+
afs;
|
|
12
|
+
historyModulePath;
|
|
13
|
+
compactConfig;
|
|
14
|
+
runtimeState;
|
|
15
|
+
initialized;
|
|
16
|
+
compactionPromise;
|
|
17
|
+
constructor(options) {
|
|
18
|
+
this.sessionId = options.sessionId;
|
|
19
|
+
this.userId = options.userId;
|
|
20
|
+
this.agentId = options.agentId;
|
|
21
|
+
this.afs = options.afs;
|
|
22
|
+
this.compactConfig = options.compact ?? {};
|
|
23
|
+
this.runtimeState = {
|
|
24
|
+
historyEntries: [],
|
|
25
|
+
currentEntry: null,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
async setSystemMessages(...messages) {
|
|
29
|
+
await this.ensureInitialized();
|
|
30
|
+
this.runtimeState.systemMessages = messages;
|
|
31
|
+
}
|
|
32
|
+
async getMessages() {
|
|
33
|
+
await this.ensureInitialized();
|
|
34
|
+
const { systemMessages, compactSummary, historyEntries, currentEntry } = this.runtimeState;
|
|
35
|
+
const messages = [
|
|
36
|
+
...(systemMessages ?? []),
|
|
37
|
+
...(compactSummary
|
|
38
|
+
? [
|
|
39
|
+
{
|
|
40
|
+
role: "system",
|
|
41
|
+
content: `Previous conversation summary:\n${compactSummary}`,
|
|
42
|
+
},
|
|
43
|
+
]
|
|
44
|
+
: []),
|
|
45
|
+
...historyEntries.flatMap((entry) => entry.content?.messages ?? []),
|
|
46
|
+
...(currentEntry?.messages ?? []),
|
|
47
|
+
];
|
|
48
|
+
// Filter out thinking messages from content
|
|
49
|
+
return messages
|
|
50
|
+
.map((msg) => {
|
|
51
|
+
if (!msg.content || typeof msg.content === "string") {
|
|
52
|
+
return msg;
|
|
53
|
+
}
|
|
54
|
+
// Filter out thinking from UnionContent[]
|
|
55
|
+
const filteredContent = msg.content.filter((c) => !(c.type === "text" && c.isThinking));
|
|
56
|
+
if (filteredContent.length === 0)
|
|
57
|
+
return null;
|
|
58
|
+
return { ...msg, content: filteredContent };
|
|
59
|
+
})
|
|
60
|
+
.filter(isNonNullable);
|
|
61
|
+
}
|
|
62
|
+
async startMessage(input, message, options) {
|
|
63
|
+
await this.ensureInitialized();
|
|
64
|
+
await this.maybeAutoCompact(options);
|
|
65
|
+
// Always wait for compaction to complete before starting a new message
|
|
66
|
+
// This ensures data consistency even in async compact mode
|
|
67
|
+
if (this.compactionPromise)
|
|
68
|
+
await this.compactionPromise;
|
|
69
|
+
this.runtimeState.currentEntry = { input, messages: [message] };
|
|
70
|
+
}
|
|
71
|
+
async endMessage(output, options) {
|
|
72
|
+
await this.ensureInitialized();
|
|
73
|
+
if (!this.runtimeState.currentEntry?.input ||
|
|
74
|
+
!this.runtimeState.currentEntry.messages?.length) {
|
|
75
|
+
throw new Error("No current entry to end. Call startMessage() first.");
|
|
76
|
+
}
|
|
77
|
+
this.runtimeState.currentEntry.output = output;
|
|
78
|
+
let newEntry;
|
|
79
|
+
if (this.afs && this.historyModulePath) {
|
|
80
|
+
newEntry = (await this.afs.write(joinURL(this.historyModulePath, "new"), {
|
|
81
|
+
userId: this.userId,
|
|
82
|
+
sessionId: this.sessionId,
|
|
83
|
+
agentId: this.agentId,
|
|
84
|
+
content: this.runtimeState.currentEntry,
|
|
85
|
+
})).data;
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
const id = v7();
|
|
89
|
+
newEntry = {
|
|
90
|
+
id,
|
|
91
|
+
path: `/history/${id}`,
|
|
92
|
+
userId: this.userId,
|
|
93
|
+
sessionId: this.sessionId,
|
|
94
|
+
agentId: this.agentId,
|
|
95
|
+
content: this.runtimeState.currentEntry,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
this.runtimeState.historyEntries.push(newEntry);
|
|
99
|
+
this.runtimeState.currentEntry = null;
|
|
100
|
+
// Check if auto-compact should be triggered
|
|
101
|
+
await this.maybeAutoCompact(options);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Manually trigger compaction
|
|
105
|
+
*/
|
|
106
|
+
async compact(options) {
|
|
107
|
+
await this.ensureInitialized();
|
|
108
|
+
// If compaction is already in progress, wait for it to complete
|
|
109
|
+
if (this.compactionPromise) {
|
|
110
|
+
return this.compactionPromise;
|
|
111
|
+
}
|
|
112
|
+
// Start new compaction task
|
|
113
|
+
this.compactionPromise = this.doCompact(options).finally(() => {
|
|
114
|
+
this.compactionPromise = undefined;
|
|
115
|
+
});
|
|
116
|
+
return this.compactionPromise;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Internal method that performs the actual compaction
|
|
120
|
+
*/
|
|
121
|
+
async doCompact(options) {
|
|
122
|
+
const { compactor, keepRecentRatio } = this.compactConfig ?? {};
|
|
123
|
+
if (!compactor) {
|
|
124
|
+
throw new Error("Cannot compact without a compactor agent configured.");
|
|
125
|
+
}
|
|
126
|
+
const historyEntries = this.runtimeState.historyEntries;
|
|
127
|
+
if (historyEntries.length === 0)
|
|
128
|
+
return;
|
|
129
|
+
// Calculate token budget for keeping recent messages
|
|
130
|
+
const ratio = keepRecentRatio ?? DEFAULT_KEEP_RECENT_RATIO;
|
|
131
|
+
const maxTokens = this.compactConfig?.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
132
|
+
let keepTokenBudget = Math.floor(maxTokens * ratio);
|
|
133
|
+
// Calculate tokens for system messages
|
|
134
|
+
const systemTokens = (this.runtimeState.systemMessages ?? []).reduce((sum, msg) => {
|
|
135
|
+
const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content ?? "");
|
|
136
|
+
return sum + estimateTokens(content);
|
|
137
|
+
}, 0);
|
|
138
|
+
// Calculate tokens for current entry messages
|
|
139
|
+
const currentTokens = (this.runtimeState.currentEntry?.messages ?? []).reduce((sum, msg) => {
|
|
140
|
+
const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content ?? "");
|
|
141
|
+
return sum + estimateTokens(content);
|
|
142
|
+
}, 0);
|
|
143
|
+
// Subtract system and current tokens from budget
|
|
144
|
+
// This ensures total tokens (system + current + kept history) stays within ratio budget
|
|
145
|
+
keepTokenBudget = Math.max(0, keepTokenBudget - systemTokens - currentTokens);
|
|
146
|
+
// Find split point by iterating backwards from most recent entry
|
|
147
|
+
// The split point divides history into: [compact] | [keep]
|
|
148
|
+
let splitIndex = historyEntries.length; // Default: keep all (no compaction)
|
|
149
|
+
let accumulatedTokens = 0;
|
|
150
|
+
for (let i = historyEntries.length - 1; i >= 0; i--) {
|
|
151
|
+
const entry = historyEntries[i];
|
|
152
|
+
if (!entry)
|
|
153
|
+
continue;
|
|
154
|
+
const entryTokens = this.estimateMessagesTokens(entry.content?.messages ?? []);
|
|
155
|
+
// Check if adding this entry would exceed token budget
|
|
156
|
+
if (accumulatedTokens + entryTokens > keepTokenBudget) {
|
|
157
|
+
// Would exceed budget, split here (this entry and earlier ones will be compacted)
|
|
158
|
+
splitIndex = i + 1;
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
// Can keep this entry, accumulate and continue
|
|
162
|
+
accumulatedTokens += entryTokens;
|
|
163
|
+
splitIndex = i;
|
|
164
|
+
}
|
|
165
|
+
// Split history at the found point
|
|
166
|
+
const entriesToCompact = historyEntries.slice(0, splitIndex);
|
|
167
|
+
const entriesToKeep = historyEntries.slice(splitIndex);
|
|
168
|
+
// If nothing to compact, return
|
|
169
|
+
if (entriesToCompact.length === 0) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const latestCompactedEntry = entriesToCompact.at(-1);
|
|
173
|
+
if (!latestCompactedEntry)
|
|
174
|
+
return;
|
|
175
|
+
// Split into batches to avoid context overflow
|
|
176
|
+
const batches = this.splitIntoBatches(entriesToCompact, maxTokens);
|
|
177
|
+
// Process batches incrementally, each summary becomes input for the next
|
|
178
|
+
let currentSummary = this.runtimeState.compactSummary;
|
|
179
|
+
for (const batch of batches) {
|
|
180
|
+
const result = await options.context.invoke(compactor, {
|
|
181
|
+
previousSummary: [currentSummary].filter(isNonNullable),
|
|
182
|
+
messages: batch.flatMap((e) => e.content?.messages ?? []).filter(isNonNullable),
|
|
183
|
+
});
|
|
184
|
+
currentSummary = result.summary;
|
|
185
|
+
}
|
|
186
|
+
// Write compact entry to AFS
|
|
187
|
+
if (this.afs && this.historyModulePath) {
|
|
188
|
+
await this.afs.write(joinURL(this.historyModulePath, "by-session", this.sessionId, "@metadata/compact/new"), {
|
|
189
|
+
userId: this.userId,
|
|
190
|
+
agentId: this.agentId,
|
|
191
|
+
content: { summary: currentSummary },
|
|
192
|
+
metadata: {
|
|
193
|
+
latestEntryId: latestCompactedEntry.id,
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
// Update runtime state: keep the summary and recent entries
|
|
198
|
+
this.runtimeState.compactSummary = currentSummary;
|
|
199
|
+
this.runtimeState.historyEntries = entriesToKeep;
|
|
200
|
+
}
|
|
201
|
+
async maybeAutoCompact(options) {
|
|
202
|
+
if (this.compactionPromise)
|
|
203
|
+
await this.compactionPromise;
|
|
204
|
+
if (!this.compactConfig)
|
|
205
|
+
return;
|
|
206
|
+
// Check if compaction is disabled
|
|
207
|
+
const mode = this.compactConfig.mode ?? DEFAULT_COMPACT_MODE;
|
|
208
|
+
if (mode === "disabled")
|
|
209
|
+
return;
|
|
210
|
+
const { compactor } = this.compactConfig;
|
|
211
|
+
const maxTokens = this.compactConfig.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
212
|
+
if (!compactor)
|
|
213
|
+
return;
|
|
214
|
+
const currentTokens = this.estimateMessagesTokens(await this.getMessages());
|
|
215
|
+
if (currentTokens >= maxTokens) {
|
|
216
|
+
this.compact(options);
|
|
217
|
+
const isAsync = this.compactConfig.async ?? DEFAULT_COMPACT_ASYNC;
|
|
218
|
+
if (!isAsync)
|
|
219
|
+
await this.compactionPromise;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Estimate token count for an array of messages
|
|
224
|
+
*/
|
|
225
|
+
estimateMessagesTokens(messages) {
|
|
226
|
+
return messages.reduce((sum, msg) => {
|
|
227
|
+
const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content ?? "");
|
|
228
|
+
return sum + estimateTokens(content);
|
|
229
|
+
}, 0);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Split entries into batches based on token limit
|
|
233
|
+
* Each batch will not exceed the specified maxTokens
|
|
234
|
+
*/
|
|
235
|
+
splitIntoBatches(entries, maxTokens) {
|
|
236
|
+
const batches = [];
|
|
237
|
+
let currentBatch = [];
|
|
238
|
+
let currentTokens = 0;
|
|
239
|
+
for (const entry of entries) {
|
|
240
|
+
const entryTokens = this.estimateMessagesTokens(entry.content?.messages ?? []);
|
|
241
|
+
// If adding this entry exceeds limit and we have entries in current batch, start new batch
|
|
242
|
+
if (currentTokens + entryTokens > maxTokens && currentBatch.length > 0) {
|
|
243
|
+
batches.push(currentBatch);
|
|
244
|
+
currentBatch = [entry];
|
|
245
|
+
currentTokens = entryTokens;
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
currentBatch.push(entry);
|
|
249
|
+
currentTokens += entryTokens;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
// Add remaining entries
|
|
253
|
+
if (currentBatch.length > 0) {
|
|
254
|
+
batches.push(currentBatch);
|
|
255
|
+
}
|
|
256
|
+
return batches;
|
|
257
|
+
}
|
|
258
|
+
async appendCurrentMessages(...messages) {
|
|
259
|
+
await this.ensureInitialized();
|
|
260
|
+
if (!this.runtimeState.currentEntry || !this.runtimeState.currentEntry.messages?.length) {
|
|
261
|
+
throw new Error("No current entry to append messages. Call startMessage() first.");
|
|
262
|
+
}
|
|
263
|
+
this.runtimeState.currentEntry.messages.push(...messages);
|
|
264
|
+
}
|
|
265
|
+
async ensureInitialized() {
|
|
266
|
+
this.initialized ??= this.initialize();
|
|
267
|
+
await this.initialized;
|
|
268
|
+
}
|
|
269
|
+
async initialize() {
|
|
270
|
+
if (this.initialized)
|
|
271
|
+
return;
|
|
272
|
+
await this.initializeDefaultCompactor();
|
|
273
|
+
const historyModule = (await this.afs?.listModules())?.find((m) => m.module instanceof AFSHistory);
|
|
274
|
+
this.historyModulePath = historyModule?.path;
|
|
275
|
+
if (this.afs && this.historyModulePath) {
|
|
276
|
+
// Load latest compact entry if exists
|
|
277
|
+
const compactPath = joinURL(this.historyModulePath, "by-session", this.sessionId, "@metadata/compact");
|
|
278
|
+
const compactResult = await this.afs.list(compactPath, {
|
|
279
|
+
filter: { userId: this.userId, agentId: this.agentId },
|
|
280
|
+
orderBy: [["createdAt", "desc"]],
|
|
281
|
+
limit: 1,
|
|
282
|
+
});
|
|
283
|
+
const latestCompact = compactResult.data[0];
|
|
284
|
+
if (latestCompact?.content?.summary) {
|
|
285
|
+
this.runtimeState.compactSummary = latestCompact.content.summary;
|
|
286
|
+
}
|
|
287
|
+
// Load history entries (after compact point if exists)
|
|
288
|
+
const afsEntries = (await this.afs.list(joinURL(this.historyModulePath, "by-session", this.sessionId), {
|
|
289
|
+
filter: {
|
|
290
|
+
userId: this.userId,
|
|
291
|
+
agentId: this.agentId,
|
|
292
|
+
// Only load entries after the latest compact
|
|
293
|
+
after: latestCompact?.createdAt?.toISOString(),
|
|
294
|
+
},
|
|
295
|
+
orderBy: [["createdAt", "desc"]],
|
|
296
|
+
// Set a very large limit to load all history entries
|
|
297
|
+
// The default limit is 10 which would cause history truncation
|
|
298
|
+
limit: 10000,
|
|
299
|
+
})).data;
|
|
300
|
+
this.runtimeState.historyEntries = afsEntries
|
|
301
|
+
.reverse()
|
|
302
|
+
.filter((entry) => isNonNullable(entry.content));
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
async initializeDefaultCompactor() {
|
|
306
|
+
this.compactConfig.compactor ??= await import("./compact/compactor.js").then((m) => new m.AISessionCompactor());
|
|
307
|
+
}
|
|
308
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { AIAgent, type AIAgentOptions } from "../../agents/ai-agent.js";
|
|
2
|
+
import type { CompactContent, CompactorInput } from "./types.js";
|
|
3
|
+
export interface CreateCompactorOptions extends AIAgentOptions<CompactorInput, CompactContent> {
|
|
4
|
+
}
|
|
5
|
+
export declare class AISessionCompactor extends AIAgent<CompactorInput, CompactContent> {
|
|
6
|
+
constructor(options?: CreateCompactorOptions);
|
|
7
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { optional, z } from "zod";
|
|
2
|
+
import { AIAgent } from "../../agents/ai-agent.js";
|
|
3
|
+
import { isNil, omitBy } from "../../utils/type-utils.js";
|
|
4
|
+
const COMPACTOR_INSTRUCTIONS = `\
|
|
5
|
+
You are a conversation summarizer. Your task is to create a concise but comprehensive summary of the conversation history provided.
|
|
6
|
+
|
|
7
|
+
## Conversation history
|
|
8
|
+
|
|
9
|
+
${"```"}yaml alt="previous-summary"
|
|
10
|
+
{{ previousSummary | yaml.stringify }}
|
|
11
|
+
${"```"}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
${"```"}yaml alt="conversation-histories"
|
|
15
|
+
{{ messages | yaml.stringify }}
|
|
16
|
+
${"```"}
|
|
17
|
+
|
|
18
|
+
## Guidelines
|
|
19
|
+
|
|
20
|
+
1. Preserve key information, decisions, and context that would be needed for future conversation continuity
|
|
21
|
+
2. Include important facts, names, dates, and specific details mentioned
|
|
22
|
+
3. Summarize the user's goals and preferences expressed in the conversation
|
|
23
|
+
4. Note any pending tasks or follow-up items
|
|
24
|
+
5. Keep the summary focused and avoid unnecessary verbosity
|
|
25
|
+
6. Write in a neutral, factual tone
|
|
26
|
+
|
|
27
|
+
Output a single summary that captures the essence of the conversation.`;
|
|
28
|
+
export class AISessionCompactor extends AIAgent {
|
|
29
|
+
constructor(options) {
|
|
30
|
+
super({
|
|
31
|
+
name: "SessionCompactor",
|
|
32
|
+
description: "Generates conversation summaries for session compaction",
|
|
33
|
+
inputSchema: z.object({
|
|
34
|
+
previousSummary: optional(z.array(z.string()).describe("List of previous conversation summaries")),
|
|
35
|
+
messages: z.array(z.any()),
|
|
36
|
+
}),
|
|
37
|
+
outputSchema: z.object({
|
|
38
|
+
summary: z.string().describe("A comprehensive summary of the conversation history"),
|
|
39
|
+
}),
|
|
40
|
+
instructions: COMPACTOR_INSTRUCTIONS,
|
|
41
|
+
...omitBy(options ?? {}, (v) => isNil(v)),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { Agent, Message } from "../../agents/agent.js";
|
|
2
|
+
import type { ChatModelInputMessage } from "../../agents/chat-model.js";
|
|
3
|
+
/**
|
|
4
|
+
* Default compaction mode
|
|
5
|
+
*/
|
|
6
|
+
export declare const DEFAULT_COMPACT_MODE: "auto";
|
|
7
|
+
/**
|
|
8
|
+
* Default maximum tokens before triggering compaction
|
|
9
|
+
*/
|
|
10
|
+
export declare const DEFAULT_MAX_TOKENS = 80000;
|
|
11
|
+
/**
|
|
12
|
+
* Default ratio of maxTokens to reserve for keeping recent messages
|
|
13
|
+
*/
|
|
14
|
+
export declare const DEFAULT_KEEP_RECENT_RATIO = 0.5;
|
|
15
|
+
/**
|
|
16
|
+
* Default async mode for compaction
|
|
17
|
+
*/
|
|
18
|
+
export declare const DEFAULT_COMPACT_ASYNC = true;
|
|
19
|
+
/**
|
|
20
|
+
* Content structure for history entries
|
|
21
|
+
*/
|
|
22
|
+
export interface EntryContent {
|
|
23
|
+
input?: unknown;
|
|
24
|
+
output?: unknown;
|
|
25
|
+
messages?: ChatModelInputMessage[];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Output structure from the compactor agent
|
|
29
|
+
*/
|
|
30
|
+
export interface CompactContent extends Message {
|
|
31
|
+
summary: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Input structure for the compactor agent
|
|
35
|
+
*/
|
|
36
|
+
export interface CompactorInput extends Message {
|
|
37
|
+
previousSummary?: string[];
|
|
38
|
+
messages: ChatModelInputMessage[];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Type alias for a compactor agent
|
|
42
|
+
*/
|
|
43
|
+
export type Compactor = Agent<CompactorInput, CompactContent>;
|
|
44
|
+
/**
|
|
45
|
+
* Configuration for session compaction
|
|
46
|
+
*/
|
|
47
|
+
export interface CompactConfig {
|
|
48
|
+
/**
|
|
49
|
+
* Compaction mode
|
|
50
|
+
* @default DEFAULT_COMPACT_MODE ("auto")
|
|
51
|
+
*/
|
|
52
|
+
mode?: "auto" | "disabled";
|
|
53
|
+
/**
|
|
54
|
+
* Maximum tokens before triggering compaction
|
|
55
|
+
* @default DEFAULT_MAX_TOKENS (80000)
|
|
56
|
+
*/
|
|
57
|
+
maxTokens?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Ratio of maxTokens to reserve for keeping recent messages (0-1)
|
|
60
|
+
*
|
|
61
|
+
* Defines what portion of maxTokens budget should be allocated for
|
|
62
|
+
* preserving recent conversation history without compaction.
|
|
63
|
+
*
|
|
64
|
+
* @default 0.5 (50% of maxTokens)
|
|
65
|
+
* @example 0.5 means if maxTokens=80000, keep up to 40000 tokens of recent messages
|
|
66
|
+
*/
|
|
67
|
+
keepRecentRatio?: number;
|
|
68
|
+
/**
|
|
69
|
+
* Whether to perform compaction asynchronously
|
|
70
|
+
* @default DEFAULT_COMPACT_ASYNC (true)
|
|
71
|
+
*/
|
|
72
|
+
async?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Agent that generates summaries from conversation entries
|
|
75
|
+
* Input: { entries: EntryContent[] }
|
|
76
|
+
* Output: { summary: string }
|
|
77
|
+
*/
|
|
78
|
+
compactor?: Compactor;
|
|
79
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default compaction mode
|
|
3
|
+
*/
|
|
4
|
+
export const DEFAULT_COMPACT_MODE = "auto";
|
|
5
|
+
/**
|
|
6
|
+
* Default maximum tokens before triggering compaction
|
|
7
|
+
*/
|
|
8
|
+
export const DEFAULT_MAX_TOKENS = 80000;
|
|
9
|
+
/**
|
|
10
|
+
* Default ratio of maxTokens to reserve for keeping recent messages
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_KEEP_RECENT_RATIO = 0.5;
|
|
13
|
+
/**
|
|
14
|
+
* Default async mode for compaction
|
|
15
|
+
*/
|
|
16
|
+
export const DEFAULT_COMPACT_ASYNC = true;
|
|
@@ -9,7 +9,7 @@ export async function getHistories({ filter, agent, }) {
|
|
|
9
9
|
return [];
|
|
10
10
|
const history = (await afs.list(historyModule.path, {
|
|
11
11
|
filter,
|
|
12
|
-
limit:
|
|
12
|
+
limit: 10,
|
|
13
13
|
orderBy: [["createdAt", "desc"]],
|
|
14
14
|
})).data;
|
|
15
15
|
return history
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { GetPromptResult } from "@modelcontextprotocol/sdk/types.js";
|
|
2
2
|
import { Agent, type Message } from "../agents/agent.js";
|
|
3
3
|
import { type AIAgent } from "../agents/ai-agent.js";
|
|
4
|
-
import {
|
|
4
|
+
import type { ChatModel, ChatModelInput, ChatModelInputMessage } from "../agents/chat-model.js";
|
|
5
5
|
import { type FileUnionContent } from "../agents/model.js";
|
|
6
6
|
import type { Context } from "../aigne/context.js";
|
|
7
|
+
import { AgentSession } from "./agent-session.js";
|
|
7
8
|
import { ChatMessagesTemplate } from "./template.js";
|
|
8
9
|
export interface PromptBuilderOptions {
|
|
9
10
|
instructions?: string | ChatMessagesTemplate;
|
|
@@ -28,7 +29,9 @@ export declare class PromptBuilder {
|
|
|
28
29
|
instructions?: string | ChatMessagesTemplate;
|
|
29
30
|
workingDir?: string;
|
|
30
31
|
copy(): PromptBuilder;
|
|
31
|
-
build(options: PromptBuildOptions): Promise<ChatModelInput & {
|
|
32
|
+
build(options: PromptBuildOptions): Promise<Omit<ChatModelInput, "messages"> & {
|
|
33
|
+
session: AgentSession;
|
|
34
|
+
userMessage: ChatModelInputMessage;
|
|
32
35
|
toolAgents?: Agent[];
|
|
33
36
|
}>;
|
|
34
37
|
buildPrompt(options: Pick<PromptBuildOptions, "input" | "context"> & {
|
|
@@ -39,13 +42,8 @@ export declare class PromptBuilder {
|
|
|
39
42
|
}>;
|
|
40
43
|
private getTemplateVariables;
|
|
41
44
|
private buildMessages;
|
|
45
|
+
private mergeMessages;
|
|
42
46
|
protected deprecatedMemories(message: string | undefined, options: PromptBuildOptions): Promise<ChatModelInputMessage[]>;
|
|
43
|
-
getHistories({ agentId, userId, sessionId, ...options }: PromptBuildOptions & {
|
|
44
|
-
agentId?: string;
|
|
45
|
-
userId?: string;
|
|
46
|
-
sessionId?: string;
|
|
47
|
-
}): Promise<ChatModelInputMessage[]>;
|
|
48
|
-
private refineMessages;
|
|
49
47
|
private convertMemoriesToMessages;
|
|
50
48
|
private buildResponseFormat;
|
|
51
49
|
private buildTools;
|