u-foo 4.0.3 → 4.0.10
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/README.md +239 -19
- package/README.zh-CN.md +3 -3
- package/bin/ucode.js +10 -2
- package/bin/ufoo.js +3 -0
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/dist/tui/darwin-x64/ufoo-tui +0 -0
- package/dist/tui/linux-arm64/ufoo-tui +0 -0
- package/dist/tui/linux-x64/ufoo-tui +0 -0
- package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
- package/docs/README.md +27 -0
- package/extensions/ufoo-browser/LICENSE +152 -0
- package/extensions/ufoo-browser/NOTICE +10 -0
- package/extensions/ufoo-browser/README.md +30 -0
- package/extensions/ufoo-browser/background.js +409 -0
- package/extensions/ufoo-browser/icons/icon-128.png +0 -0
- package/extensions/ufoo-browser/icons/icon-16.png +0 -0
- package/extensions/ufoo-browser/icons/icon-256.png +0 -0
- package/extensions/ufoo-browser/icons/icon-32.png +0 -0
- package/extensions/ufoo-browser/icons/icon-48.png +0 -0
- package/extensions/ufoo-browser/icons/logo.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
- package/extensions/ufoo-browser/manifest.json +30 -0
- package/extensions/ufoo-browser/popup.css +71 -0
- package/extensions/ufoo-browser/popup.html +44 -0
- package/extensions/ufoo-browser/popup.js +153 -0
- package/package.json +7 -5
- package/scripts/postinstall.js +6 -0
- package/src/agents/capabilities/browser/index.js +49 -0
- package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
- package/src/agents/capabilities/coding/index.js +30 -1
- package/src/agents/capabilities/index.js +5 -2
- package/src/agents/capabilities/planning/index.js +44 -5
- package/src/agents/capabilities/turnRecall/index.js +341 -0
- package/src/agents/controller/controllerToolExecutor.js +2 -2
- package/src/agents/internal/internalRunner.js +30 -8
- package/src/agents/internal/taskControl.js +107 -0
- package/src/agents/profiles/coding.js +1 -1
- package/src/agents/profiles/main.js +1 -1
- package/src/agents/prompts/mainAgent.js +1 -0
- package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
- package/src/agents/providers/claudeSessionFiles.js +1 -1
- package/src/agents/providers/codexThreadProvider.js +6 -1
- package/src/agents/providers/credentials/agy.js +171 -0
- package/src/agents/providers/directAuthStatus.js +20 -2
- package/src/agents/providers/modelsCatalog.js +26 -5
- package/src/agents/providers/nativeTransport.js +145 -73
- package/src/agents/providers/providerId.js +17 -0
- package/src/agents/providers/runtimeConfig.js +67 -20
- package/src/agents/providers/transports/antigravityTransport.js +242 -0
- package/src/agents/providers/transports/index.js +1 -0
- package/src/agents/providers/transports/openaiChatTransport.js +3 -2
- package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
- package/src/agents/providers/transports/responsesProtocol.js +119 -18
- package/src/agents/providers/transports/transportContract.js +1 -0
- package/src/agents/providers/upstreamRuntime.js +3 -1
- package/src/agents/runtime/context/contextBudget.js +1 -19
- package/src/agents/runtime/context/contextWindow.js +5 -0
- package/src/agents/runtime/context/replayHistory.js +16 -10
- package/src/agents/runtime/context/runtimeStore.js +0 -1
- package/src/agents/runtime/context/sessionJournal.js +1 -1
- package/src/agents/runtime/context/slidingWindowManager.js +792 -0
- package/src/agents/runtime/context/topicSelector.js +338 -0
- package/src/agents/runtime/context/turnAnalyzer.js +767 -0
- package/src/agents/runtime/context/turnIndexStore.js +515 -0
- package/src/agents/runtime/core/agentLoop.js +140 -35
- package/src/agents/runtime/core/executionBudget.js +2 -1
- package/src/agents/runtime/core/toolErrorGuard.js +39 -0
- package/src/agents/runtime/createAgentRuntime.js +80 -7
- package/src/agents/runtime/index.js +5 -0
- package/src/agents/runtime/protocol/materialize.js +1 -1
- package/src/agents/runtime/tasks/hooks.js +137 -0
- package/src/app/chat/ChatController.js +8 -4
- package/src/app/chat/daemonMessageRouter.js +3 -1
- package/src/app/chat/inputSubmitHandler.js +2 -2
- package/src/app/chat/transport.js +1 -1
- package/src/app/cli/browserCommands.js +340 -0
- package/src/app/cli/busCoreCommands.js +63 -3
- package/src/app/cli/features/doctor.js +21 -0
- package/src/app/cli/metricsCommands.js +1 -1
- package/src/app/cli/run.js +81 -1
- package/src/app/cli/setupCommands.js +200 -0
- package/src/code/UcodeController.js +31 -1
- package/src/code/agent.js +76 -25
- package/src/code/busConsumer.js +13 -12
- package/src/code/commands.js +0 -1
- package/src/code/context/assembler.js +11 -88
- package/src/code/context/planGraphService.js +121 -6
- package/src/code/context/planProjection.js +10 -2
- package/src/code/context/reducers.js +172 -4
- package/src/code/context/stateCommit.js +0 -32
- package/src/code/context/transcript.js +7 -4
- package/src/code/internalThread.js +9 -1
- package/src/code/launcher/ucode.js +4 -2
- package/src/code/modelCommand.js +6 -5
- package/src/code/nativeRunner.js +232 -62
- package/src/code/repl.js +27 -1
- package/src/code/runtime/agentWakeup.js +20 -3
- package/src/code/runtime/backgroundWakeHost.js +45 -0
- package/src/code/runtime/taskFocusContext.js +7 -0
- package/src/code/runtime/taskLoop.js +24 -1
- package/src/code/sessionStore.js +14 -10
- package/src/code/taskDecomposer.js +16 -7
- package/src/code/tools/backgroundProcess.js +23 -0
- package/src/code/tools/bash.js +764 -12
- package/src/code/tools/executor.js +13 -4
- package/src/code/tools/planGraph.js +1 -0
- package/src/code/tools/specs.js +62 -4
- package/src/code/tools/taskRun.js +38 -0
- package/src/config.js +92 -6
- package/src/coordination/bus/index.js +2 -2
- package/src/coordination/bus/message.js +10 -1
- package/src/coordination/bus/nickname.js +3 -1
- package/src/coordination/bus/subscriber.js +25 -10
- package/src/coordination/bus/utils.js +4 -0
- package/src/coordination/bus/wakeEndpoint.js +198 -0
- package/src/coordination/history/agentPerformance.js +18 -18
- package/src/coordination/history/agentTrace.js +7 -3
- package/src/coordination/state/paths.js +4 -0
- package/src/coordination/state/workspaceAccess.js +3 -1
- package/src/orchestration/groups/modelConfig.js +66 -0
- package/src/orchestration/groups/validateTemplate.js +2 -0
- package/src/runtime/browser/broker.js +1027 -0
- package/src/runtime/browser/brokerClient.js +108 -0
- package/src/runtime/browser/componentInstaller.js +275 -0
- package/src/runtime/browser/installState.js +329 -0
- package/src/runtime/browser/manifest.js +145 -0
- package/src/runtime/browser/native-host-runner.js +198 -0
- package/src/runtime/browser/nativeHost.js +213 -0
- package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
- package/src/runtime/browser/paths.js +134 -0
- package/src/runtime/browser/playwrightSession.js +614 -0
- package/src/runtime/daemon/agentHost.js +175 -28
- package/src/runtime/daemon/busBridge.js +2 -1
- package/src/runtime/daemon/deliveryScheduler.js +70 -2
- package/src/runtime/daemon/globalDaemon.js +20 -0
- package/src/runtime/daemon/groupOrchestrator.js +20 -1
- package/src/runtime/daemon/index.js +6 -4
- package/src/runtime/daemon/ops.js +14 -8
- package/src/tools/handlers/listAgents.js +1 -1
- package/src/tools/handlers/readBusSummary.js +1 -1
- package/src/tools/handlers/routeAgent.js +122 -5
- package/src/tools/schemaFixtures.js +1 -1
- package/src/ui/agentSurface.js +60 -6
- package/src/ui/format/index.js +34 -2
- package/src/ui/format/markdownRenderer.js +4 -2
- package/src/ui/rustChatHost.js +22 -7
- package/src/ui/rustMultiSession.js +14 -2
- package/src/ui/rustUcodeHost.js +249 -80
- package/src/ui/ucodeAgentSession.js +88 -0
- package/templates/groups/build-lane.json +57 -3
- package/templates/groups/build-ultra.json +114 -6
- package/templates/groups/design-system.json +57 -3
- package/templates/groups/product-discovery.json +57 -3
- package/templates/groups/ui-plan-review.json +57 -3
- package/templates/groups/ui-polish.json +57 -3
- package/templates/groups/verify-ship.json +57 -3
- package/src/agents/runtime/context/checkpointStore.js +0 -38
- package/src/agents/runtime/context/compaction.js +0 -151
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { estimateTextTokens, estimateMessagesTokens, historyUnits, userInstruction } = require("./contextBudget");
|
|
4
|
+
const { resolveModelContextLimit } = require("./contextWindow");
|
|
5
|
+
const { createTopicSelector } = require("./topicSelector");
|
|
6
|
+
const { normalizeTopic } = require("./turnIndexStore");
|
|
7
|
+
const {
|
|
8
|
+
stripTurnContextWrapper,
|
|
9
|
+
stripTurnContextFromContent,
|
|
10
|
+
extractTextFromMessage,
|
|
11
|
+
} = require("./turnAnalyzer");
|
|
12
|
+
|
|
13
|
+
const STABLE_HISTORY_BOUNDARY_SYMBOL = Symbol.for("ufoo.stableHistoryBoundary");
|
|
14
|
+
|
|
15
|
+
const DEFAULT_V2_POLICY = Object.freeze({
|
|
16
|
+
rawTurnCount: 5,
|
|
17
|
+
hardMaxTurns: 10,
|
|
18
|
+
stepSize: 2,
|
|
19
|
+
hotTopicThreshold: 3,
|
|
20
|
+
hotWindowLookback: 5,
|
|
21
|
+
hardHotBudgetRatio: 0.45,
|
|
22
|
+
maxSystemWakeTurns: 2,
|
|
23
|
+
minKeepTurns: 2,
|
|
24
|
+
maxOutputTokens: 32768,
|
|
25
|
+
triggerRatio: 0.85,
|
|
26
|
+
maxTurnContextRatio: 0.25,
|
|
27
|
+
maxToolResultCharsLevel1: 1200,
|
|
28
|
+
maxToolResultCharsLevel3: 480,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
function copyOwnSymbols(source, target) {
|
|
32
|
+
if (!source || !target || typeof source !== "object" || typeof target !== "object") return target;
|
|
33
|
+
for (const sym of Object.getOwnPropertySymbols(source)) {
|
|
34
|
+
const desc = Object.getOwnPropertyDescriptor(source, sym);
|
|
35
|
+
if (desc) Object.defineProperty(target, sym, desc);
|
|
36
|
+
}
|
|
37
|
+
return target;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function cloneMessageClean(msg) {
|
|
41
|
+
if (!msg || typeof msg !== "object") return msg;
|
|
42
|
+
if (msg.role !== "user") return msg;
|
|
43
|
+
if (typeof msg.content === "string") {
|
|
44
|
+
const stripped = stripTurnContextWrapper(msg.content);
|
|
45
|
+
if (stripped === msg.content) return msg;
|
|
46
|
+
return copyOwnSymbols(msg, { ...msg, content: stripped });
|
|
47
|
+
}
|
|
48
|
+
if (Array.isArray(msg.content)) {
|
|
49
|
+
const stripped = stripTurnContextFromContent(msg.content);
|
|
50
|
+
const changed = stripped.length !== msg.content.length || stripped.some((part, idx) => part !== msg.content[idx]);
|
|
51
|
+
if (!changed) return msg;
|
|
52
|
+
return copyOwnSymbols(msg, { ...msg, content: stripped });
|
|
53
|
+
}
|
|
54
|
+
return msg;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function attachTurnContextToMessage(msg, turnContextXml) {
|
|
58
|
+
if (!turnContextXml || !msg || typeof msg !== "object") return msg;
|
|
59
|
+
const cleaned = cloneMessageClean(msg);
|
|
60
|
+
const base = cleaned === msg ? copyOwnSymbols(msg, { ...msg }) : cleaned;
|
|
61
|
+
if (typeof base.content === "string") {
|
|
62
|
+
base.content = base.content ? `${turnContextXml}\n\n${base.content}` : turnContextXml;
|
|
63
|
+
return base;
|
|
64
|
+
}
|
|
65
|
+
if (Array.isArray(base.content)) {
|
|
66
|
+
const parts = base.content.slice();
|
|
67
|
+
// Place <turn_context> before regular user text while keeping tool_result blocks intact.
|
|
68
|
+
const firstNonToolIdx = parts.findIndex((p) => !p || p.type !== "tool_result");
|
|
69
|
+
const block = { type: "text", text: turnContextXml };
|
|
70
|
+
if (firstNonToolIdx === -1) {
|
|
71
|
+
parts.push(block);
|
|
72
|
+
} else {
|
|
73
|
+
parts.splice(firstNonToolIdx, 0, block);
|
|
74
|
+
}
|
|
75
|
+
base.content = parts;
|
|
76
|
+
return base;
|
|
77
|
+
}
|
|
78
|
+
base.content = turnContextXml;
|
|
79
|
+
return base;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function clampString(text, maxChars) {
|
|
83
|
+
const s = String(text || "");
|
|
84
|
+
if (s.length <= maxChars) return s;
|
|
85
|
+
const marker = "\n...[truncated; re-read source or recall earlier turns]...\n";
|
|
86
|
+
const remaining = Math.max(0, maxChars - marker.length);
|
|
87
|
+
const head = Math.floor(remaining * 0.6);
|
|
88
|
+
const tail = remaining - head;
|
|
89
|
+
return `${s.slice(0, head)}${marker}${tail ? s.slice(-tail) : ""}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function truncateToolResultsInMessage(msg, maxChars) {
|
|
93
|
+
if (!msg || typeof msg !== "object") return msg;
|
|
94
|
+
if (msg.role === "tool") {
|
|
95
|
+
if (typeof msg.content === "string" && msg.content.length > maxChars) {
|
|
96
|
+
return copyOwnSymbols(msg, { ...msg, content: clampString(msg.content, maxChars) });
|
|
97
|
+
}
|
|
98
|
+
if (Array.isArray(msg.content)) {
|
|
99
|
+
let changed = false;
|
|
100
|
+
const next = msg.content.map((part) => {
|
|
101
|
+
if (part && part.type === "text" && typeof part.text === "string" && part.text.length > maxChars) {
|
|
102
|
+
changed = true;
|
|
103
|
+
return { ...part, text: clampString(part.text, maxChars) };
|
|
104
|
+
}
|
|
105
|
+
return part;
|
|
106
|
+
});
|
|
107
|
+
return changed ? copyOwnSymbols(msg, { ...msg, content: next }) : msg;
|
|
108
|
+
}
|
|
109
|
+
return msg;
|
|
110
|
+
}
|
|
111
|
+
if (msg.role === "user" && Array.isArray(msg.content)) {
|
|
112
|
+
let changed = false;
|
|
113
|
+
const next = msg.content.map((part) => {
|
|
114
|
+
if (part && part.type === "tool_result") {
|
|
115
|
+
if (typeof part.content === "string" && part.content.length > maxChars) {
|
|
116
|
+
changed = true;
|
|
117
|
+
return { ...part, content: clampString(part.content, maxChars) };
|
|
118
|
+
}
|
|
119
|
+
if (Array.isArray(part.content)) {
|
|
120
|
+
let innerChanged = false;
|
|
121
|
+
const inner = part.content.map((sub) => {
|
|
122
|
+
if (sub && sub.type === "text" && typeof sub.text === "string" && sub.text.length > maxChars) {
|
|
123
|
+
innerChanged = true;
|
|
124
|
+
return { ...sub, text: clampString(sub.text, maxChars) };
|
|
125
|
+
}
|
|
126
|
+
return sub;
|
|
127
|
+
});
|
|
128
|
+
if (innerChanged) {
|
|
129
|
+
changed = true;
|
|
130
|
+
return { ...part, content: inner };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return part;
|
|
135
|
+
});
|
|
136
|
+
return changed ? copyOwnSymbols(msg, { ...msg, content: next }) : msg;
|
|
137
|
+
}
|
|
138
|
+
return msg;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function buildTopicMapBlock(offWindowTurns = [], maxTopics = 16) {
|
|
142
|
+
if (!offWindowTurns.length) return "";
|
|
143
|
+
const byTopic = new Map();
|
|
144
|
+
for (const turn of offWindowTurns) {
|
|
145
|
+
const topic = normalizeTopic(turn.topic);
|
|
146
|
+
const existing = byTopic.get(topic);
|
|
147
|
+
if (!existing) {
|
|
148
|
+
byTopic.set(topic, {
|
|
149
|
+
topic,
|
|
150
|
+
count: 1,
|
|
151
|
+
files: new Set(turn.modifiedFiles || []),
|
|
152
|
+
lastTurnIndex: turn.turnIndex || 0,
|
|
153
|
+
});
|
|
154
|
+
} else {
|
|
155
|
+
existing.count += 1;
|
|
156
|
+
existing.lastTurnIndex = Math.max(existing.lastTurnIndex, turn.turnIndex || 0);
|
|
157
|
+
for (const f of turn.modifiedFiles || []) existing.files.add(f);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const rows = [...byTopic.values()]
|
|
161
|
+
.sort((a, b) => b.lastTurnIndex - a.lastTurnIndex)
|
|
162
|
+
.slice(0, maxTopics)
|
|
163
|
+
.map((entry) => {
|
|
164
|
+
const files = [...entry.files].slice(0, 3);
|
|
165
|
+
const filePart = files.length ? ` | modified: ${files.join(", ")}` : "";
|
|
166
|
+
return `- ${entry.topic} (${entry.count} turns${filePart})`;
|
|
167
|
+
});
|
|
168
|
+
return [
|
|
169
|
+
`<topic_map off_window_turns="${offWindowTurns.length}">`,
|
|
170
|
+
...rows,
|
|
171
|
+
"Note: Use recall_turn(query/topic/turn_id) to inspect older turn details not shown verbatim below.",
|
|
172
|
+
"</topic_map>",
|
|
173
|
+
].join("\n");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function buildSelectedTurnsBlock(selectedTurns = [], maxCharsPerTurn = 480) {
|
|
177
|
+
if (!selectedTurns.length) return "";
|
|
178
|
+
const blocks = selectedTurns.map((turn) => {
|
|
179
|
+
const parts = [
|
|
180
|
+
`[${turn.turnId} | topic=${turn.topic || "general"} | kind=${turn.turnKind || "user"} | outcome=${turn.outcome || "completed"}]`,
|
|
181
|
+
];
|
|
182
|
+
if (turn.userSummary || turn.rawUserText) {
|
|
183
|
+
parts.push(`User: ${String(turn.userSummary || turn.rawUserText).slice(0, 180)}`);
|
|
184
|
+
}
|
|
185
|
+
if (turn.assistantSummary) {
|
|
186
|
+
parts.push(`Result: ${String(turn.assistantSummary).slice(0, 220)}`);
|
|
187
|
+
}
|
|
188
|
+
const files = [...new Set([...(turn.modifiedFiles || []), ...(turn.touchedFiles || [])])].slice(0, 5);
|
|
189
|
+
if (files.length) parts.push(`Files: ${files.join(", ")}`);
|
|
190
|
+
if (Array.isArray(turn.decisions) && turn.decisions.length) {
|
|
191
|
+
parts.push(`Notes: ${turn.decisions.slice(0, 2).join("; ").slice(0, 160)}`);
|
|
192
|
+
}
|
|
193
|
+
if (Array.isArray(turn.keywords) && turn.keywords.length) {
|
|
194
|
+
parts.push(`Keywords: ${turn.keywords.slice(0, 6).join(", ")}`);
|
|
195
|
+
}
|
|
196
|
+
const joined = parts.join("\n");
|
|
197
|
+
return joined.length > maxCharsPerTurn ? `${joined.slice(0, maxCharsPerTurn - 3)}...` : joined;
|
|
198
|
+
});
|
|
199
|
+
return [
|
|
200
|
+
`<relevant_turns count="${selectedTurns.length}">`,
|
|
201
|
+
...blocks,
|
|
202
|
+
"</relevant_turns>",
|
|
203
|
+
].join("\n");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function buildTurnContextXml({
|
|
207
|
+
offWindowTurns = [],
|
|
208
|
+
selectedTurns = [],
|
|
209
|
+
maxTopics = 16,
|
|
210
|
+
maxSelected = 5,
|
|
211
|
+
maxCharsPerTurn = 480,
|
|
212
|
+
} = {}) {
|
|
213
|
+
if (!offWindowTurns.length) return "";
|
|
214
|
+
const sections = [];
|
|
215
|
+
const topicMap = buildTopicMapBlock(offWindowTurns, maxTopics);
|
|
216
|
+
if (topicMap) sections.push(topicMap);
|
|
217
|
+
const l2 = buildSelectedTurnsBlock(selectedTurns.slice(0, maxSelected), maxCharsPerTurn);
|
|
218
|
+
if (l2) sections.push(l2);
|
|
219
|
+
if (!sections.length) return "";
|
|
220
|
+
return `<turn_context>\n${sections.join("\n")}\n</turn_context>`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function groupMessagesIntoTurnUnits(messages = [], baseOffset = 0, idPrefix = "tail") {
|
|
224
|
+
if (!Array.isArray(messages) || !messages.length) return [];
|
|
225
|
+
const rawUnits = historyUnits(messages);
|
|
226
|
+
const grouped = [];
|
|
227
|
+
for (const unit of rawUnits) {
|
|
228
|
+
const first = unit.messages[0];
|
|
229
|
+
const startsNewTurn = Boolean(first && first.role === "user" && userInstruction(first));
|
|
230
|
+
if (!grouped.length || startsNewTurn) {
|
|
231
|
+
grouped.push({
|
|
232
|
+
start: baseOffset + unit.start,
|
|
233
|
+
end: baseOffset + unit.end,
|
|
234
|
+
messages: unit.messages.map(cloneMessageClean),
|
|
235
|
+
});
|
|
236
|
+
} else {
|
|
237
|
+
const prev = grouped[grouped.length - 1];
|
|
238
|
+
prev.end = baseOffset + unit.end;
|
|
239
|
+
prev.messages.push(...unit.messages.map(cloneMessageClean));
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return grouped.map((g) => ({
|
|
243
|
+
turnId: `${idPrefix}_${g.start}`,
|
|
244
|
+
turnKind: "user",
|
|
245
|
+
topic: "general",
|
|
246
|
+
start: g.start,
|
|
247
|
+
end: g.end,
|
|
248
|
+
messages: g.messages,
|
|
249
|
+
}));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function partitionHistoricalMessages(historicalMessages = [], indexedTurns = []) {
|
|
253
|
+
if (!historicalMessages.length) return [];
|
|
254
|
+
const total = historicalMessages.length;
|
|
255
|
+
|
|
256
|
+
// Prefer turn-aligned slices from turnIndexStore when offsets fit cleanly within history.
|
|
257
|
+
const alignedUnits = [];
|
|
258
|
+
let cursor = 0;
|
|
259
|
+
const byOffset = new Map();
|
|
260
|
+
for (const t of indexedTurns) {
|
|
261
|
+
if (!t || !Number.isInteger(t.historyOffset) || !Number.isInteger(t.historyEnd)) continue;
|
|
262
|
+
if (t.historyEnd <= t.historyOffset || t.historyOffset >= total) continue;
|
|
263
|
+
byOffset.set(t.historyOffset, t);
|
|
264
|
+
}
|
|
265
|
+
const sortedTurns = [...byOffset.values()].sort((a, b) => a.historyOffset - b.historyOffset);
|
|
266
|
+
|
|
267
|
+
for (let i = 0; i < sortedTurns.length; i += 1) {
|
|
268
|
+
const turn = sortedTurns[i];
|
|
269
|
+
const nextStart = i + 1 < sortedTurns.length ? sortedTurns[i + 1].historyOffset : total;
|
|
270
|
+
if (turn.historyOffset > cursor) {
|
|
271
|
+
const gapEnd = Math.min(turn.historyOffset, total);
|
|
272
|
+
alignedUnits.push(...groupMessagesIntoTurnUnits(historicalMessages.slice(cursor, gapEnd), cursor, "gap"));
|
|
273
|
+
cursor = gapEnd;
|
|
274
|
+
}
|
|
275
|
+
const effectiveStart = Math.max(cursor, turn.historyOffset);
|
|
276
|
+
const effectiveEnd = Math.min(turn.historyEnd, nextStart, total);
|
|
277
|
+
if (effectiveEnd > effectiveStart) {
|
|
278
|
+
alignedUnits.push({
|
|
279
|
+
turnId: turn.turnId,
|
|
280
|
+
turnKind: turn.turnKind || "user",
|
|
281
|
+
topic: normalizeTopic(turn.topic),
|
|
282
|
+
start: effectiveStart,
|
|
283
|
+
end: effectiveEnd,
|
|
284
|
+
messages: historicalMessages.slice(effectiveStart, effectiveEnd).map(cloneMessageClean),
|
|
285
|
+
});
|
|
286
|
+
cursor = effectiveEnd;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (cursor < total) {
|
|
291
|
+
alignedUnits.push(...groupMessagesIntoTurnUnits(historicalMessages.slice(cursor), cursor, "tail"));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return alignedUnits;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function selectWindowUnits({
|
|
298
|
+
units = [],
|
|
299
|
+
policy = DEFAULT_V2_POLICY,
|
|
300
|
+
windowState = null,
|
|
301
|
+
availableHistoryBudget = 32000,
|
|
302
|
+
targetKeepOverride = null,
|
|
303
|
+
} = {}) {
|
|
304
|
+
if (!units.length) {
|
|
305
|
+
return { keptUnits: [], keptUserTurnCount: 0, targetKeep: policy.rawTurnCount, anchorTurnId: "" };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Hot-topic expansion: >= hotTopicThreshold of recent user turns share same non-general topic.
|
|
309
|
+
const userUnits = units.filter((u) => u.turnKind !== "system_wake");
|
|
310
|
+
const recentForHot = userUnits.slice(-policy.hotWindowLookback);
|
|
311
|
+
const topicCounts = new Map();
|
|
312
|
+
for (const unit of recentForHot) {
|
|
313
|
+
if (!unit.topic || unit.topic === "general") continue;
|
|
314
|
+
topicCounts.set(unit.topic, (topicCounts.get(unit.topic) || 0) + 1);
|
|
315
|
+
}
|
|
316
|
+
let hasHotTopic = false;
|
|
317
|
+
for (const count of topicCounts.values()) {
|
|
318
|
+
if (count >= policy.hotTopicThreshold) {
|
|
319
|
+
hasHotTopic = true;
|
|
320
|
+
break;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
let targetUserTurns = targetKeepOverride !== null ? targetKeepOverride : policy.rawTurnCount;
|
|
325
|
+
if (targetKeepOverride === null && hasHotTopic) {
|
|
326
|
+
// Expand up to hardMaxTurns while respecting 45% hard hot budget cap.
|
|
327
|
+
const hotBudget = Math.floor(availableHistoryBudget * policy.hardHotBudgetRatio);
|
|
328
|
+
let cumulative = 0;
|
|
329
|
+
let expanded = 0;
|
|
330
|
+
for (let i = userUnits.length - 1; i >= 0 && expanded < policy.hardMaxTurns; i -= 1) {
|
|
331
|
+
const unitTokens = estimateMessagesTokens(userUnits[i].messages);
|
|
332
|
+
if (expanded >= policy.rawTurnCount && cumulative + unitTokens > hotBudget) break;
|
|
333
|
+
cumulative += unitTokens;
|
|
334
|
+
expanded += 1;
|
|
335
|
+
}
|
|
336
|
+
targetUserTurns = Math.max(policy.rawTurnCount, Math.min(policy.hardMaxTurns, expanded));
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Step-aligned anchor calculation over user units.
|
|
340
|
+
const stepSize = targetKeepOverride !== null ? 1 : Math.max(1, policy.stepSize || 2);
|
|
341
|
+
let anchorUserIdx = Math.max(0, userUnits.length - targetUserTurns);
|
|
342
|
+
if (targetKeepOverride === null && windowState && windowState.anchorTurnId) {
|
|
343
|
+
const prevIdx = userUnits.findIndex((u) => u.turnId === windowState.anchorTurnId);
|
|
344
|
+
if (prevIdx >= 0) {
|
|
345
|
+
const keptWithPrevAnchor = userUnits.length - prevIdx;
|
|
346
|
+
if (keptWithPrevAnchor >= targetUserTurns && keptWithPrevAnchor < targetUserTurns + stepSize) {
|
|
347
|
+
anchorUserIdx = prevIdx;
|
|
348
|
+
} else if (keptWithPrevAnchor >= targetUserTurns + stepSize) {
|
|
349
|
+
// Slide forward by stepSize cleanly while keeping >= targetUserTurns.
|
|
350
|
+
anchorUserIdx = Math.min(userUnits.length - targetUserTurns, prevIdx + stepSize);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const anchorUnit = userUnits[anchorUserIdx] || units[0];
|
|
356
|
+
const anchorStartIndex = units.indexOf(anchorUnit);
|
|
357
|
+
const candidateUnits = anchorStartIndex >= 0 ? units.slice(anchorStartIndex) : units.slice();
|
|
358
|
+
|
|
359
|
+
// Enforce maxSystemWakeTurns cap in the kept tail while preserving user turns.
|
|
360
|
+
const keptSystemIndices = [];
|
|
361
|
+
for (let i = 0; i < candidateUnits.length; i += 1) {
|
|
362
|
+
if (candidateUnits[i].turnKind === "system_wake") keptSystemIndices.push(i);
|
|
363
|
+
}
|
|
364
|
+
const dropSystemSet = new Set();
|
|
365
|
+
if (keptSystemIndices.length > policy.maxSystemWakeTurns) {
|
|
366
|
+
const excess = keptSystemIndices.length - policy.maxSystemWakeTurns;
|
|
367
|
+
for (let i = 0; i < excess; i += 1) {
|
|
368
|
+
dropSystemSet.add(keptSystemIndices[i]);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const keptUnits = candidateUnits.filter((_, idx) => !dropSystemSet.has(idx));
|
|
373
|
+
return {
|
|
374
|
+
keptUnits,
|
|
375
|
+
keptUserTurnCount: Math.max(0, userUnits.length - anchorUserIdx),
|
|
376
|
+
targetKeep: targetUserTurns,
|
|
377
|
+
anchorTurnId: anchorUnit ? anchorUnit.turnId : "",
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function splitHistoryAndCurrentTurn(messages = [], explicitOffset) {
|
|
382
|
+
if (Number.isInteger(explicitOffset) && explicitOffset >= 0 && explicitOffset <= messages.length) {
|
|
383
|
+
return {
|
|
384
|
+
historyOffset: explicitOffset,
|
|
385
|
+
historicalMessages: messages.slice(0, explicitOffset),
|
|
386
|
+
currentTurnMessages: messages.slice(explicitOffset),
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
const markedIndex = messages.findIndex((msg) => {
|
|
390
|
+
if (!msg || msg.role !== "user") return false;
|
|
391
|
+
if (typeof msg.content === "string") return /<turn_context(?:\s+[^>]*)?>/i.test(msg.content);
|
|
392
|
+
if (Array.isArray(msg.content)) {
|
|
393
|
+
return msg.content.some((p) => p && p.type === "text" && typeof p.text === "string" && /<turn_context(?:\s+[^>]*)?>/i.test(p.text));
|
|
394
|
+
}
|
|
395
|
+
return false;
|
|
396
|
+
});
|
|
397
|
+
if (markedIndex >= 0) {
|
|
398
|
+
return {
|
|
399
|
+
historyOffset: markedIndex,
|
|
400
|
+
historicalMessages: messages.slice(0, markedIndex),
|
|
401
|
+
currentTurnMessages: messages.slice(markedIndex),
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
const units = historyUnits(messages);
|
|
405
|
+
if (units.length <= 1) {
|
|
406
|
+
return {
|
|
407
|
+
historyOffset: 0,
|
|
408
|
+
historicalMessages: [],
|
|
409
|
+
currentTurnMessages: messages.slice(),
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
const lastUnit = units[units.length - 1];
|
|
413
|
+
return {
|
|
414
|
+
historyOffset: lastUnit.start,
|
|
415
|
+
historicalMessages: messages.slice(0, lastUnit.start),
|
|
416
|
+
currentTurnMessages: messages.slice(lastUnit.start),
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function createSlidingWindowManager({
|
|
421
|
+
policy = {},
|
|
422
|
+
turnIndexStore = null,
|
|
423
|
+
topicSelector = null,
|
|
424
|
+
} = {}) {
|
|
425
|
+
const cfg = { ...DEFAULT_V2_POLICY, ...policy };
|
|
426
|
+
|
|
427
|
+
async function prepare({
|
|
428
|
+
messages = [],
|
|
429
|
+
model = "",
|
|
430
|
+
systemPrompt = "",
|
|
431
|
+
systemBlocks = null,
|
|
432
|
+
tools = [],
|
|
433
|
+
historyOffset: explicitHistoryOffset,
|
|
434
|
+
requestKind = "user",
|
|
435
|
+
turnId = "",
|
|
436
|
+
resume = false,
|
|
437
|
+
isolated = false,
|
|
438
|
+
lastUsage = 0,
|
|
439
|
+
lastEstimate = 0,
|
|
440
|
+
force = false,
|
|
441
|
+
signal = null,
|
|
442
|
+
onEvent = null,
|
|
443
|
+
} = {}) {
|
|
444
|
+
const {
|
|
445
|
+
historyOffset,
|
|
446
|
+
historicalMessages: rawHistoricalMessages,
|
|
447
|
+
currentTurnMessages,
|
|
448
|
+
} = splitHistoryAndCurrentTurn(messages, explicitHistoryOffset);
|
|
449
|
+
|
|
450
|
+
let leadingSystemCount = 0;
|
|
451
|
+
while (leadingSystemCount < rawHistoricalMessages.length && rawHistoricalMessages[leadingSystemCount]?.role === "system") {
|
|
452
|
+
leadingSystemCount += 1;
|
|
453
|
+
}
|
|
454
|
+
const pinnedSystemMessages = rawHistoricalMessages.slice(0, leadingSystemCount);
|
|
455
|
+
const historicalMessages = rawHistoricalMessages.slice(leadingSystemCount);
|
|
456
|
+
const adjustedHistoryOffset = Math.max(0, historyOffset - leadingSystemCount);
|
|
457
|
+
|
|
458
|
+
let indexedTurns = [];
|
|
459
|
+
let windowState = null;
|
|
460
|
+
if (turnIndexStore && !isolated) {
|
|
461
|
+
try { indexedTurns = turnIndexStore.listTurns(); } catch { indexedTurns = []; }
|
|
462
|
+
try { windowState = turnIndexStore.loadWindowState(); } catch { windowState = null; }
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const units = partitionHistoricalMessages(historicalMessages, indexedTurns);
|
|
466
|
+
const limitOption = cfg.contextWindowTokens || cfg.limitTokens || Number(process.env.UFOO_CONTEXT_LIMIT_TOKENS) || 0;
|
|
467
|
+
const modelLimit = resolveModelContextLimit(model, { limit: limitOption });
|
|
468
|
+
const outputOverride = Number(process.env.UFOO_UCODE_MAX_TOKENS);
|
|
469
|
+
const configuredOutput = Number.isFinite(outputOverride) && outputOverride > 0
|
|
470
|
+
? Math.floor(outputOverride)
|
|
471
|
+
: (cfg.maxOutputTokens || 32768);
|
|
472
|
+
const reserveOutput = Math.max(
|
|
473
|
+
1,
|
|
474
|
+
Math.min(modelLimit - 1, cfg.outputReserveTokens ?? Math.min(configuredOutput, Math.floor(modelLimit * 0.2))),
|
|
475
|
+
);
|
|
476
|
+
const rawMaxInputTokens = Math.max(512, Math.floor((modelLimit - reserveOutput) * cfg.triggerRatio));
|
|
477
|
+
|
|
478
|
+
const sysTokens = systemBlocks
|
|
479
|
+
? estimateTextTokens(JSON.stringify(systemBlocks))
|
|
480
|
+
: estimateTextTokens(systemPrompt);
|
|
481
|
+
const inlineSysTokens = pinnedSystemMessages.length ? estimateMessagesTokens(pinnedSystemMessages) : 0;
|
|
482
|
+
const toolTokens = Array.isArray(tools) && tools.length
|
|
483
|
+
? estimateTextTokens(JSON.stringify(tools))
|
|
484
|
+
: 0;
|
|
485
|
+
|
|
486
|
+
// Calibrate token multiplier if provider usage reported higher than prior char estimate.
|
|
487
|
+
const scaleFactor = (lastUsage > 0 && lastEstimate > 0 && lastUsage > lastEstimate)
|
|
488
|
+
? Math.min(2.5, Math.max(1, lastUsage / lastEstimate))
|
|
489
|
+
: 1;
|
|
490
|
+
const estTokens = (msgs) => Math.ceil(estimateMessagesTokens(msgs) * scaleFactor);
|
|
491
|
+
const estText = (text) => Math.ceil(estimateTextTokens(text) * scaleFactor);
|
|
492
|
+
|
|
493
|
+
const cleanedCurrent = currentTurnMessages.map(cloneMessageClean);
|
|
494
|
+
const currentFirstMsg = cleanedCurrent[0] || null;
|
|
495
|
+
const currentQueryText = currentFirstMsg ? (userInstruction(currentFirstMsg) || extractTextFromMessage(currentFirstMsg)) : "";
|
|
496
|
+
const effectiveTurnId = String(turnId || (currentQueryText ? `turn_${adjustedHistoryOffset}` : "")).trim();
|
|
497
|
+
|
|
498
|
+
const maxInputTokens = force
|
|
499
|
+
? Math.max(400, Math.floor(rawMaxInputTokens * 0.8))
|
|
500
|
+
: rawMaxInputTokens;
|
|
501
|
+
const fixedOverhead = Math.ceil((sysTokens + toolTokens) * scaleFactor);
|
|
502
|
+
const currentTurnTokens = estTokens(cleanedCurrent);
|
|
503
|
+
const initialHistoryBudget = Math.max(0, maxInputTokens - fixedOverhead - Math.ceil(inlineSysTokens * scaleFactor) - currentTurnTokens);
|
|
504
|
+
|
|
505
|
+
// Level 0 initial window selection.
|
|
506
|
+
let windowSelection = selectWindowUnits({
|
|
507
|
+
units,
|
|
508
|
+
policy: cfg,
|
|
509
|
+
windowState,
|
|
510
|
+
availableHistoryBudget: initialHistoryBudget,
|
|
511
|
+
});
|
|
512
|
+
const sameTurnState = windowState?.cachedTurnContext?.turnId === effectiveTurnId ? windowState : null;
|
|
513
|
+
let keptUnits = windowSelection.keptUnits;
|
|
514
|
+
// Once evicted in this logical turn, never restore a prefix on a later tool round.
|
|
515
|
+
if (sameTurnState?.evictionLevel > 0 && Array.isArray(sameTurnState.keptTurnIds)) {
|
|
516
|
+
const retained = new Set(sameTurnState.keptTurnIds);
|
|
517
|
+
keptUnits = units.filter((unit) => retained.has(unit.turnId)).map((unit) => ({
|
|
518
|
+
...unit,
|
|
519
|
+
messages: unit.messages.map((m) => truncateToolResultsInMessage(m, cfg.maxToolResultCharsLevel1)),
|
|
520
|
+
}));
|
|
521
|
+
}
|
|
522
|
+
let windowTurnIds = new Set(keptUnits.map((u) => u.turnId));
|
|
523
|
+
let offWindowTurns = indexedTurns.filter((t) => !windowTurnIds.has(t.turnId) && (t.historyOffset || 0) < adjustedHistoryOffset);
|
|
524
|
+
|
|
525
|
+
// Use cached <turn_context> within the same turn (multi-round tool loops) to keep prefix cache stable.
|
|
526
|
+
let selectionResult = null;
|
|
527
|
+
let turnContextXml = "";
|
|
528
|
+
const canReuseCachedContext = Boolean(
|
|
529
|
+
!force
|
|
530
|
+
&& windowState
|
|
531
|
+
&& windowState.cachedTurnContext
|
|
532
|
+
&& effectiveTurnId
|
|
533
|
+
&& windowState.cachedTurnContext.turnId === effectiveTurnId
|
|
534
|
+
&& JSON.stringify(windowState.keptTurnIds) === JSON.stringify(keptUnits.map((u) => u.turnId))
|
|
535
|
+
);
|
|
536
|
+
|
|
537
|
+
if (canReuseCachedContext) {
|
|
538
|
+
turnContextXml = windowState.cachedTurnContext.xml || "";
|
|
539
|
+
selectionResult = {
|
|
540
|
+
mode: windowState.cachedTurnContext.mode || "cached",
|
|
541
|
+
activeTopics: windowState.cachedTurnContext.activeTopics || [],
|
|
542
|
+
selectedTurns: indexedTurns.filter((t) => (windowState.cachedTurnContext.selectedTurnIds || []).includes(t.turnId)),
|
|
543
|
+
latencyMs: 0,
|
|
544
|
+
cached: true,
|
|
545
|
+
};
|
|
546
|
+
} else if (offWindowTurns.length > 0) {
|
|
547
|
+
if (topicSelector && typeof topicSelector.select === "function") {
|
|
548
|
+
selectionResult = await topicSelector.select({
|
|
549
|
+
currentQuery: currentQueryText,
|
|
550
|
+
requestKind,
|
|
551
|
+
resume,
|
|
552
|
+
allTurns: indexedTurns.filter((t) => (t.historyOffset || 0) < adjustedHistoryOffset),
|
|
553
|
+
windowTurnIds: [...windowTurnIds],
|
|
554
|
+
store: turnIndexStore,
|
|
555
|
+
signal,
|
|
556
|
+
});
|
|
557
|
+
} else {
|
|
558
|
+
selectionResult = {
|
|
559
|
+
mode: "tier1_local",
|
|
560
|
+
activeTopics: [],
|
|
561
|
+
selectedTurns: offWindowTurns.slice(-3),
|
|
562
|
+
latencyMs: 0,
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
turnContextXml = buildTurnContextXml({
|
|
566
|
+
offWindowTurns,
|
|
567
|
+
selectedTurns: selectionResult.selectedTurns || [],
|
|
568
|
+
});
|
|
569
|
+
} else {
|
|
570
|
+
selectionResult = { mode: "bypass", activeTopics: [], selectedTurns: [], latencyMs: 0 };
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// Clamp <turn_context> size proportionally on tight windows.
|
|
574
|
+
const maxTurnContextTokens = Math.max(200, Math.floor(maxInputTokens * cfg.maxTurnContextRatio));
|
|
575
|
+
if (turnContextXml && estText(turnContextXml) > maxTurnContextTokens) {
|
|
576
|
+
turnContextXml = buildTurnContextXml({
|
|
577
|
+
offWindowTurns,
|
|
578
|
+
selectedTurns: (selectionResult.selectedTurns || []).slice(0, 2),
|
|
579
|
+
maxTopics: 8,
|
|
580
|
+
maxSelected: 2,
|
|
581
|
+
maxCharsPerTurn: 280,
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
let evictionLevel = Math.max(sameTurnState?.evictionLevel || 0, force ? 1 : 0);
|
|
586
|
+
const currentToolLimits = { ...(sameTurnState?.currentToolLimits || {}) };
|
|
587
|
+
let workingCurrent = cleanedCurrent.map((msg, idx) => currentToolLimits[idx]
|
|
588
|
+
? truncateToolResultsInMessage(msg, currentToolLimits[idx]) : msg);
|
|
589
|
+
const truncateCurrent = (idx, maxChars) => {
|
|
590
|
+
const before = workingCurrent[idx];
|
|
591
|
+
workingCurrent[idx] = truncateToolResultsInMessage(before, maxChars);
|
|
592
|
+
if (workingCurrent[idx] !== before) currentToolLimits[idx] = maxChars;
|
|
593
|
+
};
|
|
594
|
+
const refreshTurnContext = async (compact = false) => {
|
|
595
|
+
windowTurnIds = new Set(keptUnits.map((u) => u.turnId));
|
|
596
|
+
offWindowTurns = indexedTurns.filter((t) => !windowTurnIds.has(t.turnId) && (t.historyOffset || 0) < adjustedHistoryOffset);
|
|
597
|
+
// Eviction must not introduce extra model calls on the foreground path.
|
|
598
|
+
selectionResult = await createTopicSelector().select({
|
|
599
|
+
currentQuery: currentQueryText, requestKind, resume,
|
|
600
|
+
allTurns: indexedTurns.filter((t) => (t.historyOffset || 0) < adjustedHistoryOffset),
|
|
601
|
+
windowTurnIds: [...windowTurnIds], store: turnIndexStore,
|
|
602
|
+
});
|
|
603
|
+
turnContextXml = buildTurnContextXml({
|
|
604
|
+
offWindowTurns, selectedTurns: selectionResult.selectedTurns || [],
|
|
605
|
+
...(compact ? { maxTopics: 6, maxSelected: 1, maxCharsPerTurn: 220 } : {}),
|
|
606
|
+
});
|
|
607
|
+
if (estText(turnContextXml) > maxTurnContextTokens) {
|
|
608
|
+
turnContextXml = buildTurnContextXml({ offWindowTurns, selectedTurns: selectionResult.selectedTurns || [],
|
|
609
|
+
maxTopics: 6, maxSelected: 1, maxCharsPerTurn: 220 });
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
|
|
613
|
+
const assembleCandidate = (candidateUnits, candidateCurrent, xml) => {
|
|
614
|
+
const histMsgs = [...pinnedSystemMessages];
|
|
615
|
+
for (const unit of candidateUnits) {
|
|
616
|
+
for (const msg of unit.messages) histMsgs.push(msg);
|
|
617
|
+
}
|
|
618
|
+
if (histMsgs.length > pinnedSystemMessages.length && candidateCurrent.length > 0 && (xml || candidateCurrent.length > 1)) {
|
|
619
|
+
const boundaryIdx = histMsgs.length - 1;
|
|
620
|
+
const boundaryMsg = copyOwnSymbols(histMsgs[boundaryIdx], { ...histMsgs[boundaryIdx] });
|
|
621
|
+
Object.defineProperty(boundaryMsg, STABLE_HISTORY_BOUNDARY_SYMBOL, {
|
|
622
|
+
value: true,
|
|
623
|
+
enumerable: false,
|
|
624
|
+
configurable: true,
|
|
625
|
+
});
|
|
626
|
+
histMsgs[boundaryIdx] = boundaryMsg;
|
|
627
|
+
}
|
|
628
|
+
const curMsgs = candidateCurrent.slice();
|
|
629
|
+
if (xml && curMsgs.length) {
|
|
630
|
+
curMsgs[0] = attachTurnContextToMessage(curMsgs[0], xml);
|
|
631
|
+
}
|
|
632
|
+
const all = [...histMsgs, ...curMsgs];
|
|
633
|
+
return {
|
|
634
|
+
messages: all,
|
|
635
|
+
histCount: histMsgs.length,
|
|
636
|
+
estimatedTokens: fixedOverhead + estTokens(all),
|
|
637
|
+
};
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
let assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
|
|
641
|
+
const initialTokens = assembled.estimatedTokens;
|
|
642
|
+
const initialKeptCount = keptUnits.length;
|
|
643
|
+
const prevForcedLevel = force && windowState ? Number(windowState.evictionLevel || 0) : 0;
|
|
644
|
+
|
|
645
|
+
// Deterministic Eviction Ladder when overflow detected or forced retry.
|
|
646
|
+
if (force || assembled.estimatedTokens > maxInputTokens) {
|
|
647
|
+
// Level 1: Drop to minKeepTurns (2) user turns, drop system wakes in L1, truncate large older tool outputs in L1.
|
|
648
|
+
evictionLevel = Math.max(evictionLevel, 1);
|
|
649
|
+
const shrunkSelection = selectWindowUnits({
|
|
650
|
+
units: keptUnits,
|
|
651
|
+
policy: { ...cfg, maxSystemWakeTurns: 0 },
|
|
652
|
+
windowState: null,
|
|
653
|
+
availableHistoryBudget: initialHistoryBudget,
|
|
654
|
+
targetKeepOverride: cfg.minKeepTurns,
|
|
655
|
+
});
|
|
656
|
+
keptUnits = shrunkSelection.keptUnits.map((unit) => ({
|
|
657
|
+
...unit,
|
|
658
|
+
messages: unit.messages.map((m) => truncateToolResultsInMessage(m, cfg.maxToolResultCharsLevel1)),
|
|
659
|
+
}));
|
|
660
|
+
await refreshTurnContext();
|
|
661
|
+
assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const level1DidNotShrink = force && assembled.estimatedTokens >= Math.floor(initialTokens * 0.9);
|
|
665
|
+
if (assembled.estimatedTokens > maxInputTokens || (force && (prevForcedLevel >= 1 || level1DidNotShrink))) {
|
|
666
|
+
// Level 2: Trim <turn_context> and peel off oldest L1 units cleanly.
|
|
667
|
+
evictionLevel = Math.max(evictionLevel, 2);
|
|
668
|
+
if (force) keptUnits = keptUnits.slice(-1);
|
|
669
|
+
await refreshTurnContext(true);
|
|
670
|
+
assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
|
|
671
|
+
while (keptUnits.length > 0 && assembled.estimatedTokens > maxInputTokens) {
|
|
672
|
+
keptUnits = keptUnits.slice(1);
|
|
673
|
+
await refreshTurnContext(true);
|
|
674
|
+
assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
|
|
675
|
+
}
|
|
676
|
+
if (assembled.estimatedTokens > maxInputTokens) {
|
|
677
|
+
turnContextXml = "";
|
|
678
|
+
assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const level2DidNotShrink = force && assembled.estimatedTokens >= Math.floor(initialTokens * 0.9);
|
|
683
|
+
if (assembled.estimatedTokens > maxInputTokens || (force && (prevForcedLevel >= 2 || level2DidNotShrink))) {
|
|
684
|
+
// Level 3: Emergency compression of intermediate tool outputs inside currentTurnMessages (preserve round 0 user + latest round + thinking signatures).
|
|
685
|
+
evictionLevel = 3;
|
|
686
|
+
keptUnits = [];
|
|
687
|
+
await refreshTurnContext(true);
|
|
688
|
+
const currentSubUnits = historyUnits(workingCurrent);
|
|
689
|
+
const preserveStart = currentSubUnits.length > 1
|
|
690
|
+
? currentSubUnits[currentSubUnits.length - 1].start
|
|
691
|
+
: Math.max(1, workingCurrent.length - 2);
|
|
692
|
+
for (let idx = 1; idx < preserveStart; idx += 1) {
|
|
693
|
+
truncateCurrent(idx, cfg.maxToolResultCharsLevel3);
|
|
694
|
+
}
|
|
695
|
+
assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
|
|
696
|
+
// Latest results are preferred intact, but cannot be exempt from the hard budget.
|
|
697
|
+
if (assembled.estimatedTokens > maxInputTokens) {
|
|
698
|
+
for (const cap of [cfg.maxToolResultCharsLevel3, 240]) {
|
|
699
|
+
for (let idx = 1; idx < workingCurrent.length; idx += 1) truncateCurrent(idx, cap);
|
|
700
|
+
assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
|
|
701
|
+
if (assembled.estimatedTokens <= maxInputTokens) break;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
if (assembled.estimatedTokens > maxInputTokens) {
|
|
705
|
+
turnContextXml = "";
|
|
706
|
+
assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const didShrink = assembled.estimatedTokens < initialTokens
|
|
711
|
+
|| keptUnits.length < initialKeptCount;
|
|
712
|
+
if (assembled.estimatedTokens > maxInputTokens || (force && !didShrink)) {
|
|
713
|
+
throw Object.assign(
|
|
714
|
+
new Error("context exceeds the configured input budget; original history retained"),
|
|
715
|
+
{ code: "context_budget_exceeded" },
|
|
716
|
+
);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const finalAnchorTurnId = (keptUnits.find((u) => u.turnKind !== "system_wake") || keptUnits[0])?.turnId || "";
|
|
720
|
+
if (typeof onEvent === "function") {
|
|
721
|
+
try {
|
|
722
|
+
await onEvent("context.select.completed", {
|
|
723
|
+
mode: selectionResult.mode,
|
|
724
|
+
activeTopics: selectionResult.activeTopics || [],
|
|
725
|
+
selectedTurnIds: (selectionResult.selectedTurns || []).map((t) => t.turnId),
|
|
726
|
+
latencyMs: selectionResult.latencyMs || 0,
|
|
727
|
+
cached: Boolean(selectionResult.cached),
|
|
728
|
+
});
|
|
729
|
+
} catch {}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
if (turnIndexStore && !isolated) {
|
|
733
|
+
try {
|
|
734
|
+
turnIndexStore.saveWindowState({
|
|
735
|
+
anchorTurnId: finalAnchorTurnId,
|
|
736
|
+
evictionLevel,
|
|
737
|
+
currentToolLimits,
|
|
738
|
+
keptTurnIds: keptUnits.map((u) => u.turnId),
|
|
739
|
+
cachedTurnContext: effectiveTurnId ? {
|
|
740
|
+
turnId: effectiveTurnId,
|
|
741
|
+
anchorTurnId: finalAnchorTurnId,
|
|
742
|
+
xml: turnContextXml,
|
|
743
|
+
mode: selectionResult.mode,
|
|
744
|
+
activeTopics: selectionResult.activeTopics || [],
|
|
745
|
+
selectedTurnIds: (selectionResult.selectedTurns || []).map((t) => t.turnId),
|
|
746
|
+
} : null,
|
|
747
|
+
});
|
|
748
|
+
} catch {
|
|
749
|
+
// Window state persistence must never fail the active LLM call.
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (typeof onEvent === "function") {
|
|
754
|
+
try {
|
|
755
|
+
await onEvent("context.window.projected", {
|
|
756
|
+
evictionLevel,
|
|
757
|
+
rawTurnCount: keptUnits.length,
|
|
758
|
+
totalTurns: indexedTurns.length,
|
|
759
|
+
offWindowCount: offWindowTurns.length,
|
|
760
|
+
estimatedTokens: assembled.estimatedTokens,
|
|
761
|
+
maxOutputTokens: reserveOutput,
|
|
762
|
+
anchorTurnId: finalAnchorTurnId,
|
|
763
|
+
});
|
|
764
|
+
} catch {}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
return {
|
|
768
|
+
messages: assembled.messages,
|
|
769
|
+
historyOffset: assembled.histCount,
|
|
770
|
+
estimatedTokens: assembled.estimatedTokens,
|
|
771
|
+
maxOutputTokens: reserveOutput,
|
|
772
|
+
meta: {
|
|
773
|
+
evictionLevel,
|
|
774
|
+
rawTurnCount: keptUnits.length,
|
|
775
|
+
offWindowCount: offWindowTurns.length,
|
|
776
|
+
selectionMode: selectionResult.mode,
|
|
777
|
+
activeTopics: selectionResult.activeTopics || [],
|
|
778
|
+
},
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
return Object.freeze({ prepare });
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
module.exports = {
|
|
786
|
+
DEFAULT_V2_POLICY,
|
|
787
|
+
createSlidingWindowManager,
|
|
788
|
+
buildTurnContextXml,
|
|
789
|
+
attachTurnContextToMessage,
|
|
790
|
+
partitionHistoricalMessages,
|
|
791
|
+
selectWindowUnits,
|
|
792
|
+
};
|