u-foo 4.0.5 → 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 +224 -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 +5 -3
- 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 +36 -20
- package/src/agents/providers/providerId.js +17 -0
- package/src/agents/providers/runtimeConfig.js +26 -19
- 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 -2
- 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 +95 -32
- 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/features/doctor.js +21 -0
- package/src/app/cli/metricsCommands.js +1 -1
- package/src/app/cli/run.js +80 -1
- package/src/app/cli/setupCommands.js +200 -0
- package/src/code/UcodeController.js +31 -1
- package/src/code/agent.js +41 -7
- 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 +83 -9
- 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/nativeRunner.js +221 -10
- 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 +13 -7
- package/src/code/tools/backgroundProcess.js +23 -0
- package/src/code/tools/bash.js +764 -12
- package/src/code/tools/executor.js +12 -4
- package/src/code/tools/specs.js +60 -3
- package/src/code/tools/taskRun.js +38 -0
- package/src/config.js +92 -6
- package/src/coordination/bus/subscriber.js +1 -1
- package/src/coordination/history/agentPerformance.js +18 -18
- package/src/coordination/history/agentTrace.js +7 -3
- 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 -30
- package/src/runtime/daemon/busBridge.js +2 -1
- package/src/runtime/daemon/globalDaemon.js +20 -0
- package/src/runtime/daemon/groupOrchestrator.js +20 -1
- package/src/runtime/daemon/index.js +5 -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 +26 -3
- package/src/ui/format/index.js +34 -2
- package/src/ui/rustChatHost.js +22 -7
- package/src/ui/rustMultiSession.js +14 -2
- package/src/ui/rustUcodeHost.js +246 -77
- 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 -52
- package/src/agents/runtime/context/compaction.js +0 -171
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { normalizeTopic, tokenizeForSearch } = require("./turnIndexStore");
|
|
4
|
+
const { stripTurnContextWrapper, parseJsonObjectLenient } = require("./turnAnalyzer");
|
|
5
|
+
|
|
6
|
+
const TEMPORAL_ANCHORS = [
|
|
7
|
+
/刚才|刚刚|上一步|上一个|上一轮|前面|之前那个|刚才那个|上面那个/,
|
|
8
|
+
/\b(just now|earlier|previous|last step|last turn|before that|above)\b/i,
|
|
9
|
+
];
|
|
10
|
+
|
|
11
|
+
const ERROR_CUES = [
|
|
12
|
+
/报错|错误|失败|崩溃|异常|为什么挂|修一下|排查/,
|
|
13
|
+
/\b(error|fail|failed|exception|crash|broken|bug|why did it)\b/i,
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
const CONTINUATION_SHORT_CUES = [
|
|
17
|
+
/^(继续|接着|好的|可以|行|嗯|改一下|再试|再测|然后|好)/,
|
|
18
|
+
/^(continue|proceed|go ahead|yes|ok|okay|sure|try again|next)\b/i,
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
function extractQueryIdentifiers(query) {
|
|
22
|
+
const paths = new Set((String(query || "").match(/[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)+/g) || []).map((s) => s.replace(/^\.\//, "").toLowerCase()));
|
|
23
|
+
const ids = new Set((String(query || "").match(/\b(?:[a-z]+(?:[A-Z][a-zA-Z0-9]*)+|[a-zA-Z]+_[a-zA-Z0-9_]+|[A-Z]{2,}_[A-Z0-9_]+|[a-zA-Z0-9]+_[0-9a-zA-Z]{3,}|[a-zA-Z0-9-]+\.[a-zA-Z]{1,6})\b/g) || []).map((s) => s.toLowerCase()));
|
|
24
|
+
return { paths, ids };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function createTopicSelector({
|
|
28
|
+
runAuxModel = null,
|
|
29
|
+
enableModelSelector = false,
|
|
30
|
+
modelTimeoutMs = 1200,
|
|
31
|
+
recentBypassThreshold = 6,
|
|
32
|
+
maxSelectedTurns = 5,
|
|
33
|
+
} = {}) {
|
|
34
|
+
async function select({
|
|
35
|
+
currentQuery = "",
|
|
36
|
+
requestKind = "user",
|
|
37
|
+
resume = false,
|
|
38
|
+
allTurns = [],
|
|
39
|
+
windowTurnIds = [],
|
|
40
|
+
store = null,
|
|
41
|
+
forceTier2 = false,
|
|
42
|
+
signal = null,
|
|
43
|
+
} = {}) {
|
|
44
|
+
const startMs = Date.now();
|
|
45
|
+
const cleanedQuery = stripTurnContextWrapper(String(currentQuery || "")).trim();
|
|
46
|
+
const turns = Array.isArray(allTurns) ? allTurns.slice().sort((a, b) => (a.turnIndex || 0) - (b.turnIndex || 0)) : [];
|
|
47
|
+
const inWindow = new Set(windowTurnIds || []);
|
|
48
|
+
const offWindowTurns = turns.filter((t) => t && !inWindow.has(t.turnId));
|
|
49
|
+
const nonWakeTurns = turns.filter((t) => t && t.turnKind !== "system_wake");
|
|
50
|
+
const lastUserTurn = nonWakeTurns[nonWakeTurns.length - 1] || turns[turns.length - 1] || null;
|
|
51
|
+
const defaultActiveTopic = lastUserTurn ? normalizeTopic(lastUserTurn.topic) : "general";
|
|
52
|
+
|
|
53
|
+
const isSystemWake = ["worker-report", "task-result", "system_wake", "wake", "cron", "schedule", "notification"]
|
|
54
|
+
.includes(String(requestKind || "").toLowerCase());
|
|
55
|
+
|
|
56
|
+
// Tier 0: Bypass when small history, zero off-window turns, resume, or system wake.
|
|
57
|
+
if (!turns.length || offWindowTurns.length === 0 || turns.length <= recentBypassThreshold || isSystemWake || resume) {
|
|
58
|
+
const selected = [];
|
|
59
|
+
const seenSelected = new Set();
|
|
60
|
+
if (offWindowTurns.length > 0) {
|
|
61
|
+
const sessionFounding = offWindowTurns.find((t) => t.turnKind !== "system_wake") || offWindowTurns[0];
|
|
62
|
+
if (sessionFounding) {
|
|
63
|
+
selected.push(sessionFounding);
|
|
64
|
+
seenSelected.add(sessionFounding.turnId);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if ((isSystemWake || resume) && offWindowTurns.length > 0 && lastUserTurn && !inWindow.has(lastUserTurn.turnId) && !seenSelected.has(lastUserTurn.turnId)) {
|
|
68
|
+
selected.push(lastUserTurn);
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
mode: "bypass",
|
|
72
|
+
isNewTopic: false,
|
|
73
|
+
activeTopics: defaultActiveTopic && defaultActiveTopic !== "general" ? [defaultActiveTopic] : [],
|
|
74
|
+
selectedTurns: selected,
|
|
75
|
+
confidence: 1,
|
|
76
|
+
latencyMs: Date.now() - startMs,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const { paths: queryPaths, ids: queryIds } = extractQueryIdentifiers(cleanedQuery);
|
|
81
|
+
|
|
82
|
+
// Tier 0 short continuation cue bypass (when no explicit new file/symbol anchor).
|
|
83
|
+
if (cleanedQuery.length <= 48 && !queryPaths.size && !queryIds.size && CONTINUATION_SHORT_CUES.some((re) => re.test(cleanedQuery))) {
|
|
84
|
+
const sameTopicOffWindow = offWindowTurns.filter((t) => normalizeTopic(t.topic) === defaultActiveTopic);
|
|
85
|
+
const picked = [];
|
|
86
|
+
const seenPicked = new Set();
|
|
87
|
+
const pushPicked = (turn) => {
|
|
88
|
+
if (!turn || seenPicked.has(turn.turnId) || picked.length >= maxSelectedTurns) return;
|
|
89
|
+
seenPicked.add(turn.turnId);
|
|
90
|
+
picked.push(turn);
|
|
91
|
+
};
|
|
92
|
+
const sessionFounding = offWindowTurns.find((t) => t.turnKind !== "system_wake") || offWindowTurns[0];
|
|
93
|
+
pushPicked(sessionFounding);
|
|
94
|
+
if (sameTopicOffWindow.length) {
|
|
95
|
+
pushPicked(sameTopicOffWindow[0]); // founding turn of active topic
|
|
96
|
+
if (sameTopicOffWindow.length > 1) {
|
|
97
|
+
pushPicked(sameTopicOffWindow[sameTopicOffWindow.length - 1]);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (offWindowTurns.length > picked.length) {
|
|
101
|
+
pushPicked(offWindowTurns[offWindowTurns.length - 1]);
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
mode: "bypass",
|
|
105
|
+
isNewTopic: false,
|
|
106
|
+
activeTopics: defaultActiveTopic !== "general" ? [defaultActiveTopic] : [],
|
|
107
|
+
selectedTurns: picked,
|
|
108
|
+
confidence: 0.95,
|
|
109
|
+
latencyMs: Date.now() - startMs,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Tier 1: Local deterministic scoring over off-window turns.
|
|
114
|
+
const hasTemporalCue = TEMPORAL_ANCHORS.some((re) => re.test(cleanedQuery));
|
|
115
|
+
const hasErrorCue = ERROR_CUES.some((re) => re.test(cleanedQuery));
|
|
116
|
+
|
|
117
|
+
let lexicalHits = [];
|
|
118
|
+
if (store && typeof store.search === "function") {
|
|
119
|
+
lexicalHits = store.search(cleanedQuery, {
|
|
120
|
+
limit: Math.max(maxSelectedTurns * 3, 12),
|
|
121
|
+
excludeTurnIds: [...inWindow],
|
|
122
|
+
});
|
|
123
|
+
} else if (cleanedQuery) {
|
|
124
|
+
// Pure in-memory fallback tokenizer scoring if store wasn't passed.
|
|
125
|
+
const qTerms = new Set(tokenizeForSearch(cleanedQuery).map((t) => t.term));
|
|
126
|
+
lexicalHits = offWindowTurns.map((turn) => {
|
|
127
|
+
const docText = [
|
|
128
|
+
turn.topic,
|
|
129
|
+
turn.rawUserText,
|
|
130
|
+
turn.userSummary,
|
|
131
|
+
turn.assistantSummary,
|
|
132
|
+
...(turn.touchedFiles || []),
|
|
133
|
+
...(turn.modifiedFiles || []),
|
|
134
|
+
...(turn.keywords || []),
|
|
135
|
+
].join(" ");
|
|
136
|
+
const dTerms = new Set(tokenizeForSearch(docText).map((t) => t.term));
|
|
137
|
+
let hits = 0;
|
|
138
|
+
for (const term of qTerms) if (dTerms.has(term)) hits += 1;
|
|
139
|
+
return { turn, score: hits, matchedTerms: [] };
|
|
140
|
+
}).filter((x) => x.score > 0);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const scoreById = new Map();
|
|
144
|
+
for (const hit of lexicalHits) {
|
|
145
|
+
if (hit && hit.turn && !inWindow.has(hit.turn.turnId)) {
|
|
146
|
+
scoreById.set(hit.turn.turnId, Number(hit.score) || 0);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Structural boosts across off-window turns.
|
|
151
|
+
for (let i = 0; i < offWindowTurns.length; i += 1) {
|
|
152
|
+
const turn = offWindowTurns[i];
|
|
153
|
+
let score = scoreById.get(turn.turnId) || 0;
|
|
154
|
+
const fileHaystack = new Set([
|
|
155
|
+
...(turn.modifiedFiles || []).map((f) => f.toLowerCase()),
|
|
156
|
+
...(turn.touchedFiles || []).map((f) => f.toLowerCase()),
|
|
157
|
+
]);
|
|
158
|
+
const keywordSet = new Set((turn.keywords || []).map((k) => k.toLowerCase()));
|
|
159
|
+
const rawLower = `${turn.rawUserText || ""}\n${turn.assistantSummary || ""}`.toLowerCase();
|
|
160
|
+
|
|
161
|
+
for (const qp of queryPaths) {
|
|
162
|
+
for (const tf of fileHaystack) {
|
|
163
|
+
if (tf === qp || tf.endsWith(`/${qp}`) || tf.includes(qp)) score += 5.0;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
for (const qid of queryIds) {
|
|
167
|
+
if (keywordSet.has(qid) || rawLower.includes(qid)) {
|
|
168
|
+
score += 4.5;
|
|
169
|
+
} else {
|
|
170
|
+
for (const tf of fileHaystack) {
|
|
171
|
+
if (tf.endsWith(`/${qid}`) || tf === qid) score += 4.0;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (hasTemporalCue && i >= offWindowTurns.length - 2 && turn.turnKind !== "system_wake") {
|
|
177
|
+
score += 2.2 + (i === offWindowTurns.length - 1 ? 1.0 : 0);
|
|
178
|
+
}
|
|
179
|
+
if (hasErrorCue && (turn.outcome === "failed" || turn.outcome === "cancelled" || turn.outcome === "interrupted")) {
|
|
180
|
+
score += 1.8;
|
|
181
|
+
}
|
|
182
|
+
if (normalizeTopic(turn.topic) === defaultActiveTopic && defaultActiveTopic !== "general") {
|
|
183
|
+
score += 0.8;
|
|
184
|
+
}
|
|
185
|
+
if (score > 0) scoreById.set(turn.turnId, Number(score.toFixed(4)));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const ranked = offWindowTurns
|
|
189
|
+
.map((turn) => ({ turn, score: scoreById.get(turn.turnId) || 0 }))
|
|
190
|
+
.filter((entry) => entry.score > 0)
|
|
191
|
+
.sort((a, b) => (b.score - a.score) || ((b.turn.turnIndex || 0) - (a.turn.turnIndex || 0)));
|
|
192
|
+
|
|
193
|
+
const topScore = ranked.length ? ranked[0].score : 0;
|
|
194
|
+
const activeTopics = [];
|
|
195
|
+
const seenTopics = new Set();
|
|
196
|
+
const pushTopic = (topic) => {
|
|
197
|
+
const norm = normalizeTopic(topic);
|
|
198
|
+
if (!norm || norm === "general" || seenTopics.has(norm)) return;
|
|
199
|
+
seenTopics.add(norm);
|
|
200
|
+
activeTopics.push(norm);
|
|
201
|
+
};
|
|
202
|
+
for (const item of ranked.slice(0, 3)) {
|
|
203
|
+
if (item.score >= Math.max(1.2, topScore * 0.5)) pushTopic(item.turn.topic);
|
|
204
|
+
}
|
|
205
|
+
if (!activeTopics.length && defaultActiveTopic !== "general") {
|
|
206
|
+
pushTopic(defaultActiveTopic);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Determine whether Tier 1 is confident or ambiguous.
|
|
210
|
+
const hasExactAnchor = queryPaths.size > 0 || queryIds.size > 0 || hasTemporalCue || topScore >= 3.5;
|
|
211
|
+
const confidence = hasExactAnchor ? 0.9 : (topScore >= 1.5 ? 0.65 : 0.3);
|
|
212
|
+
|
|
213
|
+
let mode = "tier1_local";
|
|
214
|
+
let isNewTopic = activeTopics.length === 0;
|
|
215
|
+
const selectedMap = new Map();
|
|
216
|
+
|
|
217
|
+
// Founding turn preservation for active topics & session start if off-window.
|
|
218
|
+
for (const topic of activeTopics.slice(0, 2)) {
|
|
219
|
+
const founding = offWindowTurns.find((t) => normalizeTopic(t.topic) === topic && t.turnKind !== "system_wake");
|
|
220
|
+
if (founding && !selectedMap.has(founding.turnId)) {
|
|
221
|
+
selectedMap.set(founding.turnId, founding);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
for (const entry of ranked) {
|
|
225
|
+
if (selectedMap.size >= maxSelectedTurns) break;
|
|
226
|
+
if (!selectedMap.has(entry.turn.turnId)) {
|
|
227
|
+
selectedMap.set(entry.turn.turnId, entry.turn);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (offWindowTurns.length > 0 && selectedMap.size < maxSelectedTurns) {
|
|
231
|
+
const sessionFounding = offWindowTurns.find((t) => t.turnKind !== "system_wake") || offWindowTurns[0];
|
|
232
|
+
if (sessionFounding && !selectedMap.has(sessionFounding.turnId)) {
|
|
233
|
+
selectedMap.set(sessionFounding.turnId, sessionFounding);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Optional Tier 2 fast model selector when enabled and Tier 1 is ambiguous.
|
|
238
|
+
const shouldInvokeTier2 = enableModelSelector
|
|
239
|
+
&& typeof runAuxModel === "function"
|
|
240
|
+
&& offWindowTurns.length >= 3
|
|
241
|
+
&& (forceTier2 || confidence < 0.7);
|
|
242
|
+
|
|
243
|
+
if (shouldInvokeTier2 && !(signal && signal.aborted)) {
|
|
244
|
+
const controller = new AbortController();
|
|
245
|
+
const onParentAbort = () => controller.abort();
|
|
246
|
+
if (signal) signal.addEventListener("abort", onParentAbort, { once: true });
|
|
247
|
+
const timer = setTimeout(() => controller.abort(), Math.max(200, Number(modelTimeoutMs) || 1200));
|
|
248
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
249
|
+
|
|
250
|
+
try {
|
|
251
|
+
const candidateTurns = offWindowTurns.slice(-16).map((t) => ({
|
|
252
|
+
turnId: t.turnId,
|
|
253
|
+
topic: t.topic,
|
|
254
|
+
outcome: t.outcome,
|
|
255
|
+
userSummary: t.userSummary,
|
|
256
|
+
modifiedFiles: (t.modifiedFiles || []).slice(0, 4),
|
|
257
|
+
}));
|
|
258
|
+
const raw = await runAuxModel({
|
|
259
|
+
purpose: "topic_select",
|
|
260
|
+
currentQuery: cleanedQuery,
|
|
261
|
+
activeTopics,
|
|
262
|
+
candidates: candidateTurns,
|
|
263
|
+
signal: controller.signal,
|
|
264
|
+
});
|
|
265
|
+
const parsed = typeof raw === "object" && raw !== null ? raw : parseJsonObjectLenient(raw);
|
|
266
|
+
if (parsed) {
|
|
267
|
+
mode = "tier2_model";
|
|
268
|
+
if (typeof parsed.isNewTopic === "boolean") isNewTopic = parsed.isNewTopic;
|
|
269
|
+
const byId = new Map(offWindowTurns.map((t) => [t.turnId, t]));
|
|
270
|
+
const validTopicSet = new Set(offWindowTurns.map((t) => normalizeTopic(t.topic)));
|
|
271
|
+
const tier2Turns = [];
|
|
272
|
+
const seenTier2 = new Set();
|
|
273
|
+
|
|
274
|
+
if (Array.isArray(parsed.matchedTopics)) {
|
|
275
|
+
const matchedTopics = [];
|
|
276
|
+
for (const rawTopic of parsed.matchedTopics) {
|
|
277
|
+
const norm = normalizeTopic(rawTopic);
|
|
278
|
+
if (validTopicSet.has(norm)) matchedTopics.push(norm);
|
|
279
|
+
}
|
|
280
|
+
if (matchedTopics.length) {
|
|
281
|
+
activeTopics.length = 0;
|
|
282
|
+
seenTopics.clear();
|
|
283
|
+
for (const t of matchedTopics) pushTopic(t);
|
|
284
|
+
for (const t of matchedTopics.slice(0, 2)) {
|
|
285
|
+
const founding = offWindowTurns.find((turn) => normalizeTopic(turn.topic) === t);
|
|
286
|
+
if (founding && !seenTier2.has(founding.turnId)) {
|
|
287
|
+
seenTier2.add(founding.turnId);
|
|
288
|
+
tier2Turns.push(founding);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (Array.isArray(parsed.referencedTurnIds)) {
|
|
295
|
+
for (const id of parsed.referencedTurnIds) {
|
|
296
|
+
const hit = byId.get(String(id || "").trim());
|
|
297
|
+
if (hit && !seenTier2.has(hit.turnId)) {
|
|
298
|
+
seenTier2.add(hit.turnId);
|
|
299
|
+
tier2Turns.push(hit);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (tier2Turns.length) {
|
|
305
|
+
selectedMap.clear();
|
|
306
|
+
for (const turn of tier2Turns.slice(0, maxSelectedTurns)) {
|
|
307
|
+
selectedMap.set(turn.turnId, turn);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
} catch {
|
|
312
|
+
// Fallback to Tier 1 cleanly on timeout or model failure.
|
|
313
|
+
} finally {
|
|
314
|
+
clearTimeout(timer);
|
|
315
|
+
if (signal) signal.removeEventListener("abort", onParentAbort);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const selectedTurns = [...selectedMap.values()]
|
|
320
|
+
.sort((a, b) => (a.turnIndex || 0) - (b.turnIndex || 0))
|
|
321
|
+
.slice(0, maxSelectedTurns);
|
|
322
|
+
|
|
323
|
+
return {
|
|
324
|
+
mode,
|
|
325
|
+
isNewTopic,
|
|
326
|
+
activeTopics: activeTopics.slice(0, 3),
|
|
327
|
+
selectedTurns,
|
|
328
|
+
confidence,
|
|
329
|
+
latencyMs: Date.now() - startMs,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
return Object.freeze({ select });
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
module.exports = {
|
|
337
|
+
createTopicSelector,
|
|
338
|
+
};
|