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,767 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const path = require("path");
|
|
4
|
+
const { replayTurnMessages } = require("./replayHistory");
|
|
5
|
+
const { createHash } = require("crypto");
|
|
6
|
+
const { historyUnits, userInstruction } = require("./contextBudget");
|
|
7
|
+
const { normalizeTopic } = require("./turnIndexStore");
|
|
8
|
+
|
|
9
|
+
const WRITE_TOOLS = new Set([
|
|
10
|
+
"write",
|
|
11
|
+
"write_file",
|
|
12
|
+
"edit",
|
|
13
|
+
"edit_file",
|
|
14
|
+
"multi_edit",
|
|
15
|
+
"apply_patch",
|
|
16
|
+
"replace_file_content",
|
|
17
|
+
"create_file",
|
|
18
|
+
"delete_file",
|
|
19
|
+
"rm",
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
const READ_TOOLS = new Set([
|
|
23
|
+
"read",
|
|
24
|
+
"read_file",
|
|
25
|
+
"read_image",
|
|
26
|
+
"view_file",
|
|
27
|
+
"grep",
|
|
28
|
+
"search",
|
|
29
|
+
"find",
|
|
30
|
+
"glob",
|
|
31
|
+
"ls",
|
|
32
|
+
"list_dir",
|
|
33
|
+
"artifact_read",
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
const SYSTEM_REQUEST_KINDS = new Set([
|
|
37
|
+
"worker-report",
|
|
38
|
+
"task-result",
|
|
39
|
+
"system_wake",
|
|
40
|
+
"wake",
|
|
41
|
+
"cron",
|
|
42
|
+
"schedule",
|
|
43
|
+
"notification",
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
const GENERIC_PATH_SEGMENTS = new Set([
|
|
47
|
+
"src",
|
|
48
|
+
"lib",
|
|
49
|
+
"app",
|
|
50
|
+
"test",
|
|
51
|
+
"tests",
|
|
52
|
+
"unit",
|
|
53
|
+
"integration",
|
|
54
|
+
"spec",
|
|
55
|
+
"index",
|
|
56
|
+
"utils",
|
|
57
|
+
"helpers",
|
|
58
|
+
"common",
|
|
59
|
+
"shared",
|
|
60
|
+
"types",
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
const CONTINUATION_CUES = [
|
|
64
|
+
/^(继续|接着|好的|可以|行|对|嗯|改一下|修一下|再试|再测|然后|顺便|还有)/,
|
|
65
|
+
/^(continue|proceed|go ahead|yes|ok|okay|sure|fix that|fix it|try again|also|and then|now)\b/i,
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
function stripTurnContextWrapper(text) {
|
|
69
|
+
if (typeof text !== "string") return "";
|
|
70
|
+
return text.replace(/<turn_context(?:\s+[^>]*)?>[\s\S]*?<\/turn_context>\s*/gi, "").trim();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function stripTurnContextFromContent(content) {
|
|
74
|
+
if (typeof content === "string") return stripTurnContextWrapper(content);
|
|
75
|
+
if (!Array.isArray(content)) return content;
|
|
76
|
+
return content
|
|
77
|
+
.map((part) => {
|
|
78
|
+
if (!part || typeof part !== "object") return part;
|
|
79
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
80
|
+
const cleaned = stripTurnContextWrapper(part.text);
|
|
81
|
+
if (!cleaned) return null;
|
|
82
|
+
return cleaned === part.text ? part : { ...part, text: cleaned };
|
|
83
|
+
}
|
|
84
|
+
return part;
|
|
85
|
+
})
|
|
86
|
+
.filter(Boolean);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function extractTextFromMessage(message, { includeThinking = false } = {}) {
|
|
90
|
+
if (!message || typeof message !== "object") return "";
|
|
91
|
+
if (typeof message.content === "string") {
|
|
92
|
+
return message.role === "user" ? stripTurnContextWrapper(message.content) : message.content.trim();
|
|
93
|
+
}
|
|
94
|
+
if (!Array.isArray(message.content)) return "";
|
|
95
|
+
const chunks = [];
|
|
96
|
+
for (const part of message.content) {
|
|
97
|
+
if (!part || typeof part !== "object") continue;
|
|
98
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
99
|
+
const text = message.role === "user" ? stripTurnContextWrapper(part.text) : part.text;
|
|
100
|
+
if (text.trim()) chunks.push(text.trim());
|
|
101
|
+
} else if (includeThinking && part.type === "thinking" && typeof part.thinking === "string") {
|
|
102
|
+
if (part.thinking.trim()) chunks.push(part.thinking.trim());
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return chunks.join("\n").trim();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function extractToolCalls(message) {
|
|
109
|
+
const calls = [];
|
|
110
|
+
if (!message || typeof message !== "object") return calls;
|
|
111
|
+
if (Array.isArray(message.tool_calls)) {
|
|
112
|
+
for (const tc of message.tool_calls) {
|
|
113
|
+
if (!tc) continue;
|
|
114
|
+
const fn = tc.function || tc;
|
|
115
|
+
let parsedArgs = {};
|
|
116
|
+
if (fn.arguments && typeof fn.arguments === "object") parsedArgs = fn.arguments;
|
|
117
|
+
else if (typeof fn.arguments === "string") {
|
|
118
|
+
try { parsedArgs = JSON.parse(fn.arguments); } catch { parsedArgs = { raw: fn.arguments }; }
|
|
119
|
+
} else if (tc.input && typeof tc.input === "object") {
|
|
120
|
+
parsedArgs = tc.input;
|
|
121
|
+
}
|
|
122
|
+
calls.push({ id: tc.id || "", name: String(fn.name || tc.name || ""), args: parsedArgs });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (Array.isArray(message.content)) {
|
|
126
|
+
for (const part of message.content) {
|
|
127
|
+
if (!part || typeof part !== "object") continue;
|
|
128
|
+
if (part.type === "tool_use") {
|
|
129
|
+
calls.push({
|
|
130
|
+
id: part.id || "",
|
|
131
|
+
name: String(part.name || ""),
|
|
132
|
+
args: part.input && typeof part.input === "object" ? part.input : {},
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return calls;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function extractToolResultTexts(message) {
|
|
141
|
+
const texts = [];
|
|
142
|
+
if (!message || typeof message !== "object") return texts;
|
|
143
|
+
if (message.role === "tool") {
|
|
144
|
+
const content = typeof message.content === "string"
|
|
145
|
+
? message.content
|
|
146
|
+
: Array.isArray(message.content)
|
|
147
|
+
? message.content.map((p) => (p && typeof p.text === "string" ? p.text : "")).join("\n")
|
|
148
|
+
: "";
|
|
149
|
+
if (content.trim()) texts.push(content.trim());
|
|
150
|
+
}
|
|
151
|
+
if (Array.isArray(message.content)) {
|
|
152
|
+
for (const part of message.content) {
|
|
153
|
+
if (part && part.type === "tool_result") {
|
|
154
|
+
const body = typeof part.content === "string"
|
|
155
|
+
? part.content
|
|
156
|
+
: Array.isArray(part.content)
|
|
157
|
+
? part.content.map((p) => (p && typeof p.text === "string" ? p.text : "")).join("\n")
|
|
158
|
+
: "";
|
|
159
|
+
if (body.trim()) texts.push(body.trim());
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return texts;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function normalizeCandidatePath(raw) {
|
|
167
|
+
if (typeof raw !== "string") return "";
|
|
168
|
+
const cleaned = raw.trim().replace(/^["'`]|["'`]$/g, "").replace(/\\/g, "/");
|
|
169
|
+
if (!cleaned || cleaned.length > 260) return "";
|
|
170
|
+
if (/^https?:\/\//i.test(cleaned)) return "";
|
|
171
|
+
if (/\s/.test(cleaned) && !cleaned.includes("/")) return "";
|
|
172
|
+
return cleaned.replace(/^\.\//, "");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function addPathsFromArgs(args, targetSet, artifactSet) {
|
|
176
|
+
if (!args || typeof args !== "object") return;
|
|
177
|
+
const pathKeys = ["path", "file_path", "target_file", "file", "target", "source", "destination", "cwd"];
|
|
178
|
+
for (const key of pathKeys) {
|
|
179
|
+
if (typeof args[key] === "string") {
|
|
180
|
+
const normalized = normalizeCandidatePath(args[key]);
|
|
181
|
+
if (normalized && (normalized.includes("/") || /\.[a-zA-Z0-9]{1,8}$/.test(normalized))) {
|
|
182
|
+
targetSet.add(normalized);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (Array.isArray(args.paths)) {
|
|
187
|
+
for (const entry of args.paths) {
|
|
188
|
+
const normalized = normalizeCandidatePath(entry);
|
|
189
|
+
if (normalized) targetSet.add(normalized);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
for (const artKey of ["id", "artifact_id", "artifactId"]) {
|
|
193
|
+
if (typeof args[artKey] === "string" && args[artKey].trim()) {
|
|
194
|
+
artifactSet.add(args[artKey].trim());
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (typeof args.patch === "string" || typeof args.diff === "string" || typeof args.raw === "string") {
|
|
198
|
+
const patchBody = args.patch || args.diff || args.raw || "";
|
|
199
|
+
const patchMatches = patchBody.match(/(?:^\+\+\+\s+b\/|\*\*\*\s+(?:Update|Add|Delete)\s+File:\s+)([^\r\n]+)/gm) || [];
|
|
200
|
+
for (const line of patchMatches) {
|
|
201
|
+
const pathPart = line.replace(/^\+\+\+\s+b\//, "").replace(/^\*\*\*\s+(?:Update|Add|Delete)\s+File:\s+/, "").trim();
|
|
202
|
+
const normalized = normalizeCandidatePath(pathPart);
|
|
203
|
+
if (normalized) targetSet.add(normalized);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function summarizeAction(call) {
|
|
209
|
+
const name = call.name || "tool";
|
|
210
|
+
const args = call.args || {};
|
|
211
|
+
const target = args.path || args.file_path || args.target_file || args.file || args.id || args.artifact_id || args.query || args.pattern || args.command || args.cmd || "";
|
|
212
|
+
const compactTarget = String(target).replace(/\s+/g, " ").trim().slice(0, 72);
|
|
213
|
+
return compactTarget ? `${name}(${compactTarget})` : name;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function extractTechnicalKeywords(texts = []) {
|
|
217
|
+
const seen = new Set();
|
|
218
|
+
const keywords = [];
|
|
219
|
+
const push = (word) => {
|
|
220
|
+
const cleaned = String(word || "").trim();
|
|
221
|
+
if (!cleaned || cleaned.length < 3 || cleaned.length > 80 || seen.has(cleaned)) return;
|
|
222
|
+
seen.add(cleaned);
|
|
223
|
+
keywords.push(cleaned);
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const combined = texts.filter(Boolean).join("\n");
|
|
227
|
+
// Backtick-quoted identifiers and paths
|
|
228
|
+
const codeSpans = combined.match(/`([^`\n]{2,72})`/g) || [];
|
|
229
|
+
for (const span of codeSpans) {
|
|
230
|
+
push(span.slice(1, -1).trim());
|
|
231
|
+
if (keywords.length >= 40) break;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// camelCase, snake_case, UPPER_SNAKE_CASE, alphanumeric codes with digits/underscores
|
|
235
|
+
const idMatches = combined.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-Z]+-[a-zA-Z0-9-]*[0-9][a-zA-Z0-9-]*)\b/g) || [];
|
|
236
|
+
for (const id of idMatches) {
|
|
237
|
+
push(id);
|
|
238
|
+
if (keywords.length >= 48) break;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return keywords;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function compressSummary(text, maxChars = 280) {
|
|
245
|
+
const cleaned = String(text || "").replace(/\s+/g, " ").trim();
|
|
246
|
+
if (!cleaned) return "";
|
|
247
|
+
return cleaned.length > maxChars ? `${cleaned.slice(0, Math.max(0, maxChars - 3))}...` : cleaned;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function inferDeterministicTopic({
|
|
251
|
+
topicHint,
|
|
252
|
+
turnKind,
|
|
253
|
+
rawUserText,
|
|
254
|
+
touchedFiles,
|
|
255
|
+
modifiedFiles,
|
|
256
|
+
previousTurns,
|
|
257
|
+
}) {
|
|
258
|
+
if (topicHint && String(topicHint).trim()) {
|
|
259
|
+
return normalizeTopic(topicHint);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const prevUserTurns = (previousTurns || []).filter((item) => item && item.turnKind !== "system_wake");
|
|
263
|
+
const lastTurn = (previousTurns || [])[(previousTurns || []).length - 1] || null;
|
|
264
|
+
const lastUserTurn = prevUserTurns[prevUserTurns.length - 1] || lastTurn;
|
|
265
|
+
|
|
266
|
+
if (turnKind === "system_wake") {
|
|
267
|
+
if (lastUserTurn && lastUserTurn.topic && lastUserTurn.topic !== "general") {
|
|
268
|
+
return lastUserTurn.topic;
|
|
269
|
+
}
|
|
270
|
+
return "system-wake";
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (turnKind === "resumed_interaction" && lastUserTurn && lastUserTurn.topic) {
|
|
274
|
+
return lastUserTurn.topic;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const touchedSet = new Set([...(modifiedFiles || []), ...(touchedFiles || [])]);
|
|
278
|
+
if (lastUserTurn && lastUserTurn.topic && lastUserTurn.topic !== "general") {
|
|
279
|
+
const prevFiles = new Set([...(lastUserTurn.modifiedFiles || []), ...(lastUserTurn.touchedFiles || [])]);
|
|
280
|
+
for (const f of touchedSet) {
|
|
281
|
+
if (prevFiles.has(f)) return lastUserTurn.topic;
|
|
282
|
+
}
|
|
283
|
+
const textTrimmed = String(rawUserText || "").trim();
|
|
284
|
+
if (textTrimmed && textTrimmed.length <= 64 && CONTINUATION_CUES.some((re) => re.test(textTrimmed))) {
|
|
285
|
+
return lastUserTurn.topic;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const prioritizedPaths = [...(modifiedFiles || []), ...(touchedFiles || [])];
|
|
290
|
+
for (const filePath of prioritizedPaths) {
|
|
291
|
+
const segments = filePath.split("/").filter(Boolean);
|
|
292
|
+
const meaningful = [];
|
|
293
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
294
|
+
const rawSeg = i === segments.length - 1 ? segments[i].replace(/\.[a-z0-9]+$/i, "") : segments[i];
|
|
295
|
+
const lower = rawSeg.toLowerCase();
|
|
296
|
+
if (!lower || GENERIC_PATH_SEGMENTS.has(lower)) continue;
|
|
297
|
+
meaningful.push(lower);
|
|
298
|
+
}
|
|
299
|
+
if (meaningful.length >= 2) {
|
|
300
|
+
return normalizeTopic(`${meaningful[meaningful.length - 2]}-${meaningful[meaningful.length - 1]}`);
|
|
301
|
+
}
|
|
302
|
+
if (meaningful.length === 1) {
|
|
303
|
+
return normalizeTopic(meaningful[0]);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const asciiTerm = String(rawUserText || "").match(/\b([a-zA-Z][a-zA-Z0-9_-]{2,24})\b/);
|
|
308
|
+
if (asciiTerm && !/^(the|and|for|with|this|that|please|help|fix|add|check|run)$/i.test(asciiTerm[1])) {
|
|
309
|
+
return normalizeTopic(asciiTerm[1]);
|
|
310
|
+
}
|
|
311
|
+
const cjkTerm = String(rawUserText || "").match(/[\u4e00-\u9fff]{2,8}/);
|
|
312
|
+
if (cjkTerm) {
|
|
313
|
+
return normalizeTopic(cjkTerm[0]);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return "general";
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function classifyTurnKind({ requestKind = "user", prompt = "", turnMessages = [], resume = false } = {}) {
|
|
320
|
+
const normalizedKind = String(requestKind || "user").trim().toLowerCase();
|
|
321
|
+
if (SYSTEM_REQUEST_KINDS.has(normalizedKind)) {
|
|
322
|
+
return "system_wake";
|
|
323
|
+
}
|
|
324
|
+
if (resume || normalizedKind === "resumed_interaction") {
|
|
325
|
+
return "resumed_interaction";
|
|
326
|
+
}
|
|
327
|
+
const firstUser = (turnMessages || []).find((m) => m && m.role === "user");
|
|
328
|
+
const instruction = firstUser ? stripTurnContextWrapper(userInstruction(firstUser) || "") : "";
|
|
329
|
+
if (!instruction && !stripTurnContextWrapper(String(prompt || "")) && (turnMessages || []).length > 0) {
|
|
330
|
+
const hasToolResults = (turnMessages || []).some((m) => m && (m.role === "tool" || (Array.isArray(m.content) && m.content.some((p) => p && p.type === "tool_result"))));
|
|
331
|
+
if (hasToolResults) return "tool_continuation";
|
|
332
|
+
}
|
|
333
|
+
return "user";
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function buildDeterministicTurnRecord({
|
|
337
|
+
turnId,
|
|
338
|
+
turnIndex = 0,
|
|
339
|
+
historyOffset = 0,
|
|
340
|
+
historyEnd,
|
|
341
|
+
turnMessages = [],
|
|
342
|
+
requestKind = "user",
|
|
343
|
+
prompt = "",
|
|
344
|
+
outcome = "completed",
|
|
345
|
+
error = "",
|
|
346
|
+
startedAt,
|
|
347
|
+
endedAt,
|
|
348
|
+
previousTurns = [],
|
|
349
|
+
topicHint = "",
|
|
350
|
+
resume = false,
|
|
351
|
+
} = {}) {
|
|
352
|
+
const safeId = String(turnId || `turn_${String(turnIndex).padStart(4, "0")}`).trim();
|
|
353
|
+
const messages = Array.isArray(turnMessages) ? turnMessages : [];
|
|
354
|
+
const turnKind = classifyTurnKind({ requestKind, prompt, turnMessages: messages, resume });
|
|
355
|
+
|
|
356
|
+
const userTexts = [];
|
|
357
|
+
const assistantTexts = [];
|
|
358
|
+
const toolResultTexts = [];
|
|
359
|
+
const touchedFiles = new Set();
|
|
360
|
+
const modifiedFiles = new Set();
|
|
361
|
+
const artifactIds = new Set();
|
|
362
|
+
const keyActions = [];
|
|
363
|
+
const decisions = [];
|
|
364
|
+
|
|
365
|
+
for (const msg of messages) {
|
|
366
|
+
if (!msg || typeof msg !== "object") continue;
|
|
367
|
+
if (msg.role === "user") {
|
|
368
|
+
const instruction = stripTurnContextWrapper(userInstruction(msg) || extractTextFromMessage(msg));
|
|
369
|
+
if (instruction) userTexts.push(instruction);
|
|
370
|
+
} else if (msg.role === "assistant") {
|
|
371
|
+
const text = extractTextFromMessage(msg);
|
|
372
|
+
if (text) assistantTexts.push(text);
|
|
373
|
+
const calls = extractToolCalls(msg);
|
|
374
|
+
for (const call of calls) {
|
|
375
|
+
keyActions.push(summarizeAction(call));
|
|
376
|
+
const callFiles = new Set();
|
|
377
|
+
addPathsFromArgs(call.args, callFiles, artifactIds);
|
|
378
|
+
for (const file of callFiles) {
|
|
379
|
+
touchedFiles.add(file);
|
|
380
|
+
if (WRITE_TOOLS.has(call.name)) {
|
|
381
|
+
modifiedFiles.add(file);
|
|
382
|
+
} else if (!READ_TOOLS.has(call.name) && /write|edit|patch|create|delete/i.test(call.name)) {
|
|
383
|
+
modifiedFiles.add(file);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
for (const resultText of extractToolResultTexts(msg)) {
|
|
389
|
+
toolResultTexts.push(resultText);
|
|
390
|
+
const artifactMatch = resultText.match(/"artifactId"\s*:\s*"([^"]+)"|artifacts\/[^/\s]+\/([a-zA-Z0-9._-]+)/g) || [];
|
|
391
|
+
for (const hit of artifactMatch) {
|
|
392
|
+
const quoted = hit.match(/"artifactId"\s*:\s*"([^"]+)"/);
|
|
393
|
+
if (quoted && quoted[1]) artifactIds.add(quoted[1]);
|
|
394
|
+
const pathHit = hit.match(/artifacts\/[^/\s]+\/([a-zA-Z0-9._-]+)/);
|
|
395
|
+
if (pathHit && pathHit[1]) artifactIds.add(pathHit[1]);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const cleanedPrompt = stripTurnContextWrapper(String(prompt || ""));
|
|
401
|
+
const rawUserText = userTexts[0] || cleanedPrompt || (turnKind === "system_wake" ? `[${requestKind}]` : "");
|
|
402
|
+
const finalAssistantText = assistantTexts[assistantTexts.length - 1] || "";
|
|
403
|
+
|
|
404
|
+
let assistantSummary = compressSummary(finalAssistantText, 420);
|
|
405
|
+
if (!assistantSummary && error) {
|
|
406
|
+
assistantSummary = compressSummary(`[${outcome}] ${error}`, 420);
|
|
407
|
+
} else if (outcome !== "completed" && error && !assistantSummary.includes(error)) {
|
|
408
|
+
assistantSummary = compressSummary(`${assistantSummary ? `${assistantSummary} ` : ""}[${outcome}: ${error}]`, 420);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
if (outcome === "failed" && error) {
|
|
412
|
+
decisions.push(compressSummary(`Failed: ${error}`, 180));
|
|
413
|
+
} else if (outcome === "cancelled" || outcome === "interrupted") {
|
|
414
|
+
decisions.push(compressSummary(`${outcome}: ${error || "stopped before completion"}`, 180));
|
|
415
|
+
} else if (outcome === "paused") {
|
|
416
|
+
decisions.push("Paused waiting for user input");
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const userSummaryPrefix = turnKind === "system_wake" ? `[wake:${requestKind}] ` : "";
|
|
420
|
+
const userSummary = compressSummary(`${userSummaryPrefix}${rawUserText}`, 240);
|
|
421
|
+
const touchedList = [...touchedFiles];
|
|
422
|
+
const modifiedList = [...modifiedFiles];
|
|
423
|
+
const artifactList = [...artifactIds];
|
|
424
|
+
const topic = inferDeterministicTopic({
|
|
425
|
+
topicHint,
|
|
426
|
+
turnKind,
|
|
427
|
+
rawUserText,
|
|
428
|
+
touchedFiles: touchedList,
|
|
429
|
+
modifiedFiles: modifiedList,
|
|
430
|
+
previousTurns,
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
const keywords = extractTechnicalKeywords([
|
|
434
|
+
rawUserText,
|
|
435
|
+
finalAssistantText,
|
|
436
|
+
error,
|
|
437
|
+
...touchedList,
|
|
438
|
+
...toolResultTexts.slice(-2),
|
|
439
|
+
]);
|
|
440
|
+
|
|
441
|
+
const resolvedHistoryEnd = Number.isInteger(historyEnd) && historyEnd >= historyOffset
|
|
442
|
+
? historyEnd
|
|
443
|
+
: historyOffset + messages.length;
|
|
444
|
+
|
|
445
|
+
const contentHash = createHash("sha256")
|
|
446
|
+
.update(JSON.stringify({
|
|
447
|
+
turnKind,
|
|
448
|
+
outcome,
|
|
449
|
+
rawUserText,
|
|
450
|
+
assistantSummary,
|
|
451
|
+
modifiedList,
|
|
452
|
+
touchedList,
|
|
453
|
+
keyActions: keyActions.slice(0, 12),
|
|
454
|
+
}))
|
|
455
|
+
.digest("hex")
|
|
456
|
+
.slice(0, 16);
|
|
457
|
+
|
|
458
|
+
return {
|
|
459
|
+
turnId: safeId,
|
|
460
|
+
turnIndex,
|
|
461
|
+
historyOffset,
|
|
462
|
+
historyEnd: resolvedHistoryEnd,
|
|
463
|
+
turnKind,
|
|
464
|
+
outcome,
|
|
465
|
+
startedAt: startedAt || new Date().toISOString(),
|
|
466
|
+
endedAt: endedAt || new Date().toISOString(),
|
|
467
|
+
topic,
|
|
468
|
+
rawUserText,
|
|
469
|
+
userSummary,
|
|
470
|
+
assistantSummary,
|
|
471
|
+
keyActions: keyActions.slice(0, 24),
|
|
472
|
+
touchedFiles: touchedList,
|
|
473
|
+
modifiedFiles: modifiedList,
|
|
474
|
+
artifactIds: artifactList,
|
|
475
|
+
decisions,
|
|
476
|
+
keywords,
|
|
477
|
+
enrichmentVersion: 1,
|
|
478
|
+
enrichedAt: null,
|
|
479
|
+
contentHash,
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function backfillMissingTurns({
|
|
484
|
+
store,
|
|
485
|
+
runtimeEvents = null,
|
|
486
|
+
journalMessages = null,
|
|
487
|
+
} = {}) {
|
|
488
|
+
if (!store) return [];
|
|
489
|
+
const existingTurns = store.listTurns();
|
|
490
|
+
const byId = new Map(existingTurns.map((t) => [t.turnId, t]));
|
|
491
|
+
const runningTurns = [...existingTurns];
|
|
492
|
+
const added = [];
|
|
493
|
+
|
|
494
|
+
if (Array.isArray(runtimeEvents) && runtimeEvents.length) {
|
|
495
|
+
const accepted = new Map();
|
|
496
|
+
const terminalByTask = new Map();
|
|
497
|
+
for (const event of runtimeEvents) {
|
|
498
|
+
if (!event || !event.taskRunId) continue;
|
|
499
|
+
if (event.type === "request.accepted") {
|
|
500
|
+
accepted.set(event.taskRunId, event);
|
|
501
|
+
} else if (["task.completed", "task.failed", "task.cancelled", "task.interrupted"].includes(event.type)) {
|
|
502
|
+
terminalByTask.set(event.taskRunId, event);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
let cursor = 0;
|
|
506
|
+
let replayTurnIndex = 0;
|
|
507
|
+
// Match replayHistory: accepted order, one final event per task, no paused snapshots.
|
|
508
|
+
for (const [taskRunId, start] of accepted) {
|
|
509
|
+
const event = terminalByTask.get(taskRunId);
|
|
510
|
+
if (!event) continue;
|
|
511
|
+
const turnIndex = replayTurnIndex++;
|
|
512
|
+
const turnMessages = replayTurnMessages(start.request, event);
|
|
513
|
+
const historyOffset = cursor;
|
|
514
|
+
const historyEnd = cursor + turnMessages.length;
|
|
515
|
+
cursor = historyEnd;
|
|
516
|
+
const outcome = event.type.replace(/^task\./, "");
|
|
517
|
+
const existing = byId.get(event.taskRunId);
|
|
518
|
+
const shouldUpdate = !existing || existing.historyEnd !== historyEnd
|
|
519
|
+
|| existing.historyOffset !== historyOffset || existing.outcome !== outcome;
|
|
520
|
+
if (!shouldUpdate) continue;
|
|
521
|
+
const record = buildDeterministicTurnRecord({
|
|
522
|
+
turnId: event.taskRunId,
|
|
523
|
+
turnIndex: existing ? existing.turnIndex : turnIndex,
|
|
524
|
+
historyOffset,
|
|
525
|
+
historyEnd,
|
|
526
|
+
turnMessages,
|
|
527
|
+
requestKind: start.requestKind || (start.request?.report ? "worker-report" : start.request?.parentTaskRunId ? "task-result" : "user"),
|
|
528
|
+
prompt: start.request?.text || start.text || "",
|
|
529
|
+
outcome,
|
|
530
|
+
error: event.error || event.result?.error || "",
|
|
531
|
+
startedAt: start.ts || event.ts,
|
|
532
|
+
endedAt: event.ts,
|
|
533
|
+
previousTurns: runningTurns,
|
|
534
|
+
});
|
|
535
|
+
const saved = store.upsertTurn(record, { phase: "A" });
|
|
536
|
+
if (!existing) runningTurns.push(saved);
|
|
537
|
+
else {
|
|
538
|
+
const idx = runningTurns.findIndex((t) => t.turnId === saved.turnId);
|
|
539
|
+
if (idx >= 0) runningTurns[idx] = saved;
|
|
540
|
+
}
|
|
541
|
+
byId.set(saved.turnId, saved);
|
|
542
|
+
added.push(saved);
|
|
543
|
+
}
|
|
544
|
+
return added;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
if (Array.isArray(journalMessages) && journalMessages.length) {
|
|
548
|
+
// Reconcile any overshot historyEnd from in-turn ephemeral messages so
|
|
549
|
+
// adjacent indexed turns form a contiguous partition of journalMessages.
|
|
550
|
+
for (let k = 0; k < runningTurns.length; k += 1) {
|
|
551
|
+
const cur = runningTurns[k];
|
|
552
|
+
if (!cur || !Number.isInteger(cur.historyOffset)) continue;
|
|
553
|
+
const nextTurn = runningTurns[k + 1];
|
|
554
|
+
const maxEnd = nextTurn && Number.isInteger(nextTurn.historyOffset) && nextTurn.historyOffset > cur.historyOffset
|
|
555
|
+
? nextTurn.historyOffset
|
|
556
|
+
: (journalMessages.length >= cur.historyOffset ? journalMessages.length : cur.historyEnd);
|
|
557
|
+
if (Number.isInteger(maxEnd) && maxEnd > cur.historyOffset && cur.historyEnd > maxEnd) {
|
|
558
|
+
const repaired = store.upsertTurn({
|
|
559
|
+
...cur,
|
|
560
|
+
historyEnd: maxEnd,
|
|
561
|
+
}, { phase: "A" });
|
|
562
|
+
runningTurns[k] = repaired;
|
|
563
|
+
byId.set(repaired.turnId, repaired);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
const reconciledTurns = runningTurns.slice();
|
|
567
|
+
const units = historyUnits(journalMessages);
|
|
568
|
+
const groupedTurns = [];
|
|
569
|
+
for (const unit of units) {
|
|
570
|
+
if (!unit.complete) {
|
|
571
|
+
if (groupedTurns.length) {
|
|
572
|
+
const prev = groupedTurns[groupedTurns.length - 1];
|
|
573
|
+
prev.end = unit.end;
|
|
574
|
+
prev.messages.push(...unit.messages);
|
|
575
|
+
prev.complete = false;
|
|
576
|
+
}
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
const first = unit.messages[0];
|
|
580
|
+
const startsNewUserTurn = Boolean(first && first.role === "user" && userInstruction(first));
|
|
581
|
+
if (!groupedTurns.length || startsNewUserTurn) {
|
|
582
|
+
groupedTurns.push({
|
|
583
|
+
start: unit.start,
|
|
584
|
+
end: unit.end,
|
|
585
|
+
complete: unit.complete,
|
|
586
|
+
messages: [...unit.messages],
|
|
587
|
+
});
|
|
588
|
+
} else {
|
|
589
|
+
const prev = groupedTurns[groupedTurns.length - 1];
|
|
590
|
+
prev.end = unit.end;
|
|
591
|
+
prev.messages.push(...unit.messages);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
for (let i = 0; i < groupedTurns.length; i += 1) {
|
|
595
|
+
const group = groupedTurns[i];
|
|
596
|
+
if (!group.complete) continue;
|
|
597
|
+
const alreadyCovered = reconciledTurns.some(
|
|
598
|
+
(t) => t.historyOffset === group.start || (t.historyOffset <= group.start && t.historyEnd >= group.end)
|
|
599
|
+
);
|
|
600
|
+
if (alreadyCovered) continue;
|
|
601
|
+
const turnId = `journal_turn_${String(group.start).padStart(4, "0")}`;
|
|
602
|
+
const record = buildDeterministicTurnRecord({
|
|
603
|
+
turnId,
|
|
604
|
+
turnIndex: runningTurns.length,
|
|
605
|
+
historyOffset: group.start,
|
|
606
|
+
historyEnd: group.end,
|
|
607
|
+
turnMessages: group.messages,
|
|
608
|
+
requestKind: "user",
|
|
609
|
+
outcome: "completed",
|
|
610
|
+
previousTurns: runningTurns,
|
|
611
|
+
});
|
|
612
|
+
const saved = store.upsertTurn(record, { phase: "A" });
|
|
613
|
+
runningTurns.push(saved);
|
|
614
|
+
added.push(saved);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
return added;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function parseJsonObjectLenient(rawText) {
|
|
622
|
+
const text = String(rawText || "").trim();
|
|
623
|
+
if (!text) return null;
|
|
624
|
+
const fenced = text.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "").trim();
|
|
625
|
+
try {
|
|
626
|
+
const parsed = JSON.parse(fenced);
|
|
627
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
628
|
+
} catch {
|
|
629
|
+
const match = fenced.match(/\{[\s\S]*\}/);
|
|
630
|
+
if (!match) return null;
|
|
631
|
+
try {
|
|
632
|
+
const parsed = JSON.parse(match[0]);
|
|
633
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
634
|
+
} catch {
|
|
635
|
+
return null;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function createAsyncTurnEnricher({
|
|
641
|
+
store,
|
|
642
|
+
runAuxModel = null,
|
|
643
|
+
enabled = false,
|
|
644
|
+
timeoutMs = 8000,
|
|
645
|
+
maxQueue = 32,
|
|
646
|
+
onEvent = null,
|
|
647
|
+
} = {}) {
|
|
648
|
+
let closed = false;
|
|
649
|
+
let running = false;
|
|
650
|
+
let drainPromise = null;
|
|
651
|
+
let activeController = null;
|
|
652
|
+
let activeTimer = null;
|
|
653
|
+
const queue = [];
|
|
654
|
+
|
|
655
|
+
async function processOne(item) {
|
|
656
|
+
const { turn, expectedHash } = item;
|
|
657
|
+
if (closed || typeof runAuxModel !== "function") return;
|
|
658
|
+
activeController = new AbortController();
|
|
659
|
+
let timedOut = false;
|
|
660
|
+
activeTimer = setTimeout(() => {
|
|
661
|
+
timedOut = true;
|
|
662
|
+
if (activeController) activeController.abort();
|
|
663
|
+
}, Math.max(200, Number(timeoutMs) || 8000));
|
|
664
|
+
if (typeof activeTimer.unref === "function") activeTimer.unref();
|
|
665
|
+
|
|
666
|
+
try {
|
|
667
|
+
const raw = await runAuxModel({
|
|
668
|
+
purpose: "turn_enrich",
|
|
669
|
+
turn,
|
|
670
|
+
existingTopics: store.listTopics().slice(0, 12),
|
|
671
|
+
signal: activeController.signal,
|
|
672
|
+
});
|
|
673
|
+
if (closed || timedOut || !raw) return;
|
|
674
|
+
const parsed = typeof raw === "object" ? raw : parseJsonObjectLenient(raw);
|
|
675
|
+
if (!parsed) return;
|
|
676
|
+
store.upsertTurn({
|
|
677
|
+
turnId: turn.turnId,
|
|
678
|
+
topic: parsed.topic,
|
|
679
|
+
userSummary: parsed.userSummary,
|
|
680
|
+
assistantSummary: parsed.assistantSummary,
|
|
681
|
+
decisions: Array.isArray(parsed.decisions) ? parsed.decisions : [],
|
|
682
|
+
keywords: Array.isArray(parsed.keywords) ? parsed.keywords : [],
|
|
683
|
+
enrichmentVersion: 2,
|
|
684
|
+
enrichedAt: new Date().toISOString(),
|
|
685
|
+
}, { phase: "B", expectedHash });
|
|
686
|
+
if (typeof onEvent === "function") {
|
|
687
|
+
try { onEvent({ type: "context.turn_enriched", taskRunId: turn.turnId, turnId: turn.turnId, topic: parsed.topic || turn.topic }); } catch {}
|
|
688
|
+
}
|
|
689
|
+
} catch {
|
|
690
|
+
// Never break runtime loop on optional enrichment failure.
|
|
691
|
+
} finally {
|
|
692
|
+
if (activeTimer) {
|
|
693
|
+
clearTimeout(activeTimer);
|
|
694
|
+
activeTimer = null;
|
|
695
|
+
}
|
|
696
|
+
activeController = null;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function startDrain() {
|
|
701
|
+
if (running || closed || !queue.length) return;
|
|
702
|
+
running = true;
|
|
703
|
+
drainPromise = (async () => {
|
|
704
|
+
try {
|
|
705
|
+
while (!closed && queue.length) {
|
|
706
|
+
const next = queue.shift();
|
|
707
|
+
await processOne(next);
|
|
708
|
+
}
|
|
709
|
+
} finally {
|
|
710
|
+
running = false;
|
|
711
|
+
drainPromise = null;
|
|
712
|
+
}
|
|
713
|
+
})();
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function enqueue(turnRecord) {
|
|
717
|
+
if (closed || !enabled || typeof runAuxModel !== "function") return false;
|
|
718
|
+
if (!turnRecord || !turnRecord.turnId) return false;
|
|
719
|
+
const existingIdx = queue.findIndex((item) => item.turn.turnId === turnRecord.turnId);
|
|
720
|
+
const entry = { turn: turnRecord, expectedHash: turnRecord.contentHash || "" };
|
|
721
|
+
if (existingIdx >= 0) {
|
|
722
|
+
queue[existingIdx] = entry;
|
|
723
|
+
} else {
|
|
724
|
+
if (queue.length >= maxQueue) queue.shift();
|
|
725
|
+
queue.push(entry);
|
|
726
|
+
}
|
|
727
|
+
startDrain();
|
|
728
|
+
return true;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
async function flush() {
|
|
732
|
+
if (drainPromise) {
|
|
733
|
+
await drainPromise;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
function close() {
|
|
738
|
+
closed = true;
|
|
739
|
+
queue.length = 0;
|
|
740
|
+
if (activeTimer) {
|
|
741
|
+
clearTimeout(activeTimer);
|
|
742
|
+
activeTimer = null;
|
|
743
|
+
}
|
|
744
|
+
if (activeController) {
|
|
745
|
+
try { activeController.abort(); } catch {}
|
|
746
|
+
activeController = null;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
return Object.freeze({
|
|
751
|
+
enqueue,
|
|
752
|
+
flush,
|
|
753
|
+
close,
|
|
754
|
+
pendingCount: () => queue.length + (running ? 1 : 0),
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
module.exports = {
|
|
759
|
+
stripTurnContextWrapper,
|
|
760
|
+
stripTurnContextFromContent,
|
|
761
|
+
classifyTurnKind,
|
|
762
|
+
buildDeterministicTurnRecord,
|
|
763
|
+
backfillMissingTurns,
|
|
764
|
+
createAsyncTurnEnricher,
|
|
765
|
+
parseJsonObjectLenient,
|
|
766
|
+
extractTextFromMessage,
|
|
767
|
+
};
|