u-foo 3.1.6 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +172 -13
- package/README.zh-CN.md +108 -13
- package/SKILLS/ufoo/SKILL.md +15 -3
- package/SKILLS/ufoo-bus/SKILL.md +21 -1
- package/bin/uclaude.js +4 -0
- package/bin/ucodex.js +4 -0
- package/bin/ufoo.js +3 -1
- 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/package.json +10 -3
- package/scripts/postinstall-skills.js +53 -0
- package/scripts/postinstall.js +11 -16
- package/scripts/smoke-native-messages.js +214 -0
- package/src/agents/activity/activityStateWriter.js +37 -38
- package/src/agents/capabilities/agentManagement/index.js +4 -0
- package/src/agents/capabilities/agentManagement/service.js +113 -0
- package/src/agents/capabilities/agentRouting/index.js +4 -0
- package/src/agents/capabilities/coding/index.js +32 -0
- package/src/agents/capabilities/coordination/index.js +37 -0
- package/src/agents/capabilities/globalRouting/index.js +5 -0
- package/src/agents/capabilities/groups/index.js +3 -0
- package/src/agents/capabilities/index.js +25 -0
- package/src/agents/capabilities/planning/index.js +123 -0
- package/src/agents/capabilities/planning/main.js +28 -0
- package/src/agents/capabilities/projectDiscovery/index.js +3 -0
- package/src/agents/capabilities/scheduling/index.js +3 -0
- package/src/agents/capabilities/sharedMemory/index.js +4 -0
- package/src/agents/capabilities/skills/index.js +12 -0
- package/src/agents/capabilities/taskExecution/index.js +3 -0
- package/src/agents/capabilities/taskReports/index.js +6 -0
- package/src/agents/controller/controllerToolExecutor.js +6 -4
- package/src/agents/controller/loopRuntime.js +85 -221
- package/src/agents/controller/ufooAgent.js +1 -0
- package/src/agents/internal/internalRunner.js +103 -32
- package/src/agents/launch/launcher.js +88 -6
- package/src/agents/launch/nativeCapabilities.js +40 -0
- package/src/agents/launch/nativeMessages.js +362 -0
- package/src/agents/launch/notifier.js +13 -18
- package/src/agents/launch/readyDetector.js +26 -12
- package/src/agents/profiles/coding.js +6 -0
- package/src/agents/profiles/globalRouter.js +2 -0
- package/src/agents/profiles/main.js +5 -0
- package/src/agents/prompts/groupBootstrap.js +10 -0
- package/src/agents/prompts/mainAgent.js +39 -0
- package/src/agents/prompts/native/tasks.js +2 -2
- package/src/agents/prompts/native/ufoo.js +3 -0
- package/src/agents/providers/claudeEventTranslator.js +6 -1
- package/src/agents/providers/claudeThreadProvider.js +44 -2
- package/src/agents/providers/codexEventTranslator.js +47 -7
- package/src/agents/providers/codexThreadProvider.js +3 -2
- package/src/agents/providers/controllerJsonTransport.js +28 -0
- package/src/agents/providers/credentials/claude.js +10 -3
- package/src/agents/providers/nativeTransport.js +1135 -0
- package/src/agents/providers/runtimeConfig.js +186 -0
- package/src/agents/providers/thinkingLevels.js +132 -0
- package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
- package/src/agents/providers/transports/index.js +10 -0
- package/src/agents/providers/transports/openaiChatTransport.js +117 -0
- package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
- package/src/agents/providers/transports/responsesProtocol.js +499 -0
- package/src/agents/providers/transports/systemBlocks.js +16 -0
- package/src/agents/providers/transports/transportContract.js +50 -0
- package/src/agents/providers/transports/visionBlocks.js +151 -0
- package/src/agents/providers/upstreamTransport.js +13 -4
- package/src/agents/runtime/composeCapabilities.js +89 -0
- package/src/agents/runtime/context/commandStore.js +43 -0
- package/src/agents/runtime/context/contextWindow.js +119 -0
- package/src/agents/runtime/context/fileLock.js +36 -0
- package/src/agents/runtime/context/runtimeStore.js +126 -0
- package/src/agents/runtime/context/sessionJournal.js +360 -0
- package/src/agents/runtime/context/sessionStore.js +57 -0
- package/src/agents/runtime/core/agentLoop.js +270 -0
- package/src/agents/runtime/core/stableJson.js +29 -0
- package/src/agents/runtime/core/toolLoopGuard.js +55 -0
- package/src/agents/runtime/createAgentRuntime.js +247 -0
- package/src/agents/runtime/index.js +14 -0
- package/src/agents/runtime/protocol/faultHarness.js +90 -0
- package/src/agents/runtime/protocol/materialize.js +107 -0
- package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
- package/src/agents/runtime/tasks/resourceLease.js +66 -0
- package/src/agents/runtime/tasks/scheduler.js +73 -0
- package/src/agents/runtime/tools/registry.js +57 -0
- package/src/app/chat/ChatController.js +14 -3
- package/src/app/chat/agentDirectory.js +8 -2
- package/src/app/chat/commandExecutor.js +36 -46
- package/src/app/chat/commands.js +14 -7
- package/src/app/chat/daemonConnection.js +58 -5
- package/src/app/chat/daemonMessageRouter.js +61 -3
- package/src/app/chat/inputSubmitHandler.js +14 -2
- package/src/app/chat/launchRequestContext.js +42 -0
- package/src/app/chat/multiWindow/paneManager.js +85 -165
- package/src/app/chat/streamState.js +3 -3
- package/src/app/chat/transport.js +1 -1
- package/src/app/cli/busCoreCommands.js +9 -0
- package/src/app/cli/features/doctor.js +33 -0
- package/src/app/cli/features/skills.js +16 -4
- package/src/app/cli/reportCoreCommands.js +37 -0
- package/src/app/cli/run.js +40 -39
- package/src/code/agent.js +16 -4
- package/src/code/context/artifacts.js +12 -11
- package/src/code/context/assembler.js +2 -1
- package/src/code/context/promptLayers.js +1 -13
- package/src/code/context/stableJson.js +2 -27
- package/src/code/contextWindow.js +2 -117
- package/src/code/conversation/sessionJournal.js +3 -349
- package/src/code/internalThread.js +100 -0
- package/src/code/nativeRunner.js +36 -2668
- package/src/code/protocol/faultHarness.js +2 -88
- package/src/code/protocol/materialize.js +2 -105
- package/src/code/protocol/toolCallLedger.js +5 -215
- package/src/code/providers/anthropicMessagesTransport.js +2 -118
- package/src/code/providers/openaiChatTransport.js +2 -114
- package/src/code/providers/openaiResponsesTransport.js +2 -117
- package/src/code/providers/responsesProtocol.js +2 -497
- package/src/code/providers/transportContract.js +2 -48
- package/src/code/providers/visionBlocks.js +2 -149
- package/src/code/sessionStore.js +24 -96
- package/src/code/thinkingLevels.js +1 -130
- package/src/code/toolLoopGuard.js +3 -49
- package/src/code/tools/artifactRead.js +1 -1
- package/src/code/tools/executor.js +373 -0
- package/src/code/tools/specs.js +312 -0
- package/src/config.js +81 -67
- package/src/coordination/bus/deliveryQueue.js +16 -2
- package/src/coordination/bus/index.js +2 -6
- package/src/coordination/bus/inject.js +13 -5
- package/src/coordination/bus/nativeReceipts.js +100 -0
- package/src/coordination/bus/queue.js +1 -3
- package/src/coordination/bus/utils.js +7 -3
- package/src/coordination/history/agentSurface.js +142 -0
- package/src/coordination/history/controllerSummary.js +23 -0
- package/src/coordination/memory/index.js +5 -21
- package/src/coordination/report/store.js +103 -83
- package/src/coordination/state/agentsStore.js +57 -3
- package/src/coordination/state/fileLock.js +2 -0
- package/src/coordination/state/workspaceAccess.js +36 -0
- package/src/runtime/contracts/agentMode.js +17 -0
- package/src/runtime/contracts/eventContract.js +3 -0
- package/src/runtime/contracts/uiProtocol.js +4 -0
- package/src/runtime/daemon/agentHost.js +375 -0
- package/src/runtime/daemon/busBridge.js +396 -0
- package/src/runtime/daemon/claudeChannel.js +159 -0
- package/src/runtime/daemon/controlPlaneService.js +27 -17
- package/src/runtime/daemon/cronOps.js +25 -17
- package/src/runtime/daemon/deliveryScheduler.js +32 -5
- package/src/runtime/daemon/executionPaths.js +30 -0
- package/src/runtime/daemon/globalDaemon.js +28 -1
- package/src/runtime/daemon/groupOrchestrator.js +1 -0
- package/src/runtime/daemon/index.js +114 -344
- package/src/runtime/daemon/ipcServer.js +32 -10
- package/src/runtime/daemon/mcpConfigure.js +113 -20
- package/src/runtime/daemon/mcpHttpServer.js +27 -5
- package/src/runtime/daemon/mcpServer.js +7 -4
- package/src/runtime/daemon/mcpStdioProxy.js +127 -10
- package/src/runtime/daemon/ops.js +22 -17
- package/src/runtime/daemon/promptRequest.js +23 -4
- package/src/runtime/daemon/providerSessions.js +67 -33
- package/src/runtime/daemon/reportControlBus.js +59 -25
- package/src/runtime/daemon/status.js +4 -0
- package/src/runtime/privacy/redactor.js +2 -2
- package/src/runtime/projects/identity.js +2 -1
- package/src/runtime/projects/registry.js +98 -38
- package/src/tools/controllerSchemas.js +24 -0
- package/src/tools/handlers/dispatchMessage.js +5 -2
- package/src/tools/handlers/listAgents.js +3 -1
- package/src/tools/handlers/readBusSummary.js +3 -1
- package/src/tools/handlers/readProjectRegistry.js +29 -2
- package/src/tools/handlers/routeAgent.js +35 -0
- package/src/tools/index.js +1 -0
- package/src/tools/registry.js +2 -0
- package/src/tools/schemaFixtures.js +16 -3
- package/src/tools/tier1/routeAgent.js +2 -2
- package/src/tools/tier2/runtimeCoordination.js +38 -0
- package/src/tools/types.js +2 -0
- package/src/ui/agentPresentation.js +109 -0
- package/src/ui/agentSurface.js +270 -0
- package/src/ui/format/banner.js +8 -11
- package/src/ui/format/startupBanner.js +50 -0
- package/src/ui/multiPaneBusMirror.js +29 -3
- package/src/ui/rustChatHost.js +170 -438
- package/src/ui/rustMultiSession.js +225 -51
- package/src/ui/rustUcodeHost.js +20 -87
- package/src/ui/settingsBridge.js +7 -4
- package/src/app/chat/agentEnter.js +0 -70
- package/src/app/chat/multiWindow/index.js +0 -310
- package/src/app/chat/multiWindow/paneLayout.js +0 -84
- package/src/app/chat/multiWindow/renderer.js +0 -420
- package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
- package/src/app/chat/multiWindow/vtFrame.js +0 -93
- package/src/ui/multiWindowHandoff.js +0 -232
- package/src/ui/ptyHandoff.js +0 -23
package/src/code/agent.js
CHANGED
|
@@ -11,7 +11,8 @@ const {
|
|
|
11
11
|
saveSessionSnapshot,
|
|
12
12
|
loadSessionSnapshot,
|
|
13
13
|
} = require("./sessionStore");
|
|
14
|
-
const {
|
|
14
|
+
const { createSkillsCapability } = require("../agents/capabilities/skills");
|
|
15
|
+
const skillContextSource = createSkillsCapability().contextSources[0];
|
|
15
16
|
const {
|
|
16
17
|
assembleModelContext,
|
|
17
18
|
applyContextSideEffects,
|
|
@@ -570,7 +571,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
|
|
|
570
571
|
const taskPrompt = analysisTask
|
|
571
572
|
? `${taskText}\n\nAnalysis requirements:\n- Inspect repository evidence before concluding.\n- Cite concrete file observations.\n- Keep findings concise and actionable.`
|
|
572
573
|
: taskText;
|
|
573
|
-
const skillInjections =
|
|
574
|
+
const skillInjections = skillContextSource({
|
|
574
575
|
prompt: taskPrompt,
|
|
575
576
|
workspaceRoot,
|
|
576
577
|
sessionId: String(state.sessionId || ""),
|
|
@@ -677,6 +678,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
|
|
|
677
678
|
onToolEvent: (event) => {
|
|
678
679
|
toolEventsThisAttempt += 1;
|
|
679
680
|
pushToolLog(event);
|
|
681
|
+
if (typeof options.onToolEvent === "function") options.onToolEvent(event);
|
|
680
682
|
},
|
|
681
683
|
signal: options.signal,
|
|
682
684
|
});
|
|
@@ -715,7 +717,10 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
|
|
|
715
717
|
const decomposedResult = await runDecomposedTask({
|
|
716
718
|
task: effectiveTaskPrompt,
|
|
717
719
|
onProgress: options.onProgress,
|
|
718
|
-
onToolEvent:
|
|
720
|
+
onToolEvent: (event) => {
|
|
721
|
+
pushToolLog(event);
|
|
722
|
+
if (typeof options.onToolEvent === "function") options.onToolEvent(event);
|
|
723
|
+
},
|
|
719
724
|
signal: options.signal,
|
|
720
725
|
workspaceRoot,
|
|
721
726
|
provider,
|
|
@@ -1178,7 +1183,14 @@ async function resumeAfterUserInteraction(answerText = "", state = {}, options =
|
|
|
1178
1183
|
systemBlocks: assembled.systemBlocks || null,
|
|
1179
1184
|
messages,
|
|
1180
1185
|
sessionId: String(state.sessionId || ""),
|
|
1181
|
-
onToolEvent:
|
|
1186
|
+
onToolEvent: (event) => {
|
|
1187
|
+
pushToolLog(event);
|
|
1188
|
+
if (typeof options.onToolLog === "function") {
|
|
1189
|
+
const log = normalizeToolLogEvent(event);
|
|
1190
|
+
if (log) options.onToolLog(log);
|
|
1191
|
+
}
|
|
1192
|
+
if (typeof options.onToolEvent === "function") options.onToolEvent(event);
|
|
1193
|
+
},
|
|
1182
1194
|
maxToolCalls: state.maxToolCalls,
|
|
1183
1195
|
onStreamDelta: trackingOnDelta,
|
|
1184
1196
|
onThinkingDelta: typeof options.onThinkingDelta === "function" ? options.onThinkingDelta : null,
|
|
@@ -5,11 +5,12 @@ const path = require("path");
|
|
|
5
5
|
const crypto = require("crypto");
|
|
6
6
|
const { randomUUID } = require("crypto");
|
|
7
7
|
|
|
8
|
-
function getArtifactsDir(workspaceRoot = process.cwd(), sessionId = "") {
|
|
8
|
+
function getArtifactsDir(workspaceRoot = process.cwd(), sessionId = "", namespace = "ucode") {
|
|
9
9
|
const root = path.resolve(workspaceRoot || process.cwd());
|
|
10
10
|
const id = String(sessionId || "").trim();
|
|
11
|
-
if (
|
|
12
|
-
return path.join(root, ".ufoo", "agent",
|
|
11
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(namespace) || id && !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(id)) throw new Error("invalid artifact storage identity");
|
|
12
|
+
if (!id) return path.join(root, ".ufoo", "agent", namespace, "artifacts");
|
|
13
|
+
return path.join(root, ".ufoo", "agent", namespace, "artifacts", id);
|
|
13
14
|
}
|
|
14
15
|
|
|
15
16
|
function createArtifactId(prefix = "artifact") {
|
|
@@ -21,10 +22,10 @@ function hashContent(value = "") {
|
|
|
21
22
|
return crypto.createHash("sha256").update(String(value || ""), "utf8").digest("hex").slice(0, 16);
|
|
22
23
|
}
|
|
23
24
|
|
|
24
|
-
function getArtifactFilePath(workspaceRoot = process.cwd(), sessionId = "", artifactId = "") {
|
|
25
|
+
function getArtifactFilePath(workspaceRoot = process.cwd(), sessionId = "", artifactId = "", namespace = "ucode") {
|
|
25
26
|
const id = String(artifactId || "").trim();
|
|
26
|
-
if (
|
|
27
|
-
return path.join(getArtifactsDir(workspaceRoot, sessionId), `${id}.json`);
|
|
27
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(id)) return "";
|
|
28
|
+
return path.join(getArtifactsDir(workspaceRoot, sessionId, namespace), `${id}.json`);
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
function buildArtifactRecord({
|
|
@@ -66,15 +67,15 @@ function buildArtifactRecord({
|
|
|
66
67
|
};
|
|
67
68
|
}
|
|
68
69
|
|
|
69
|
-
function saveArtifact(workspaceRoot = process.cwd(), sessionId = "", record = {}) {
|
|
70
|
+
function saveArtifact(workspaceRoot = process.cwd(), sessionId = "", record = {}, options = {}) {
|
|
70
71
|
const payload = buildArtifactRecord(record);
|
|
71
|
-
const filePath = getArtifactFilePath(workspaceRoot, sessionId, payload.artifactId);
|
|
72
|
+
const filePath = getArtifactFilePath(workspaceRoot, sessionId, payload.artifactId, options.namespace || "ucode");
|
|
72
73
|
if (!filePath) {
|
|
73
74
|
return { ok: false, error: "invalid artifact id", artifact: null };
|
|
74
75
|
}
|
|
75
76
|
try {
|
|
76
77
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
77
|
-
fs.writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
|
|
78
|
+
fs.writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
78
79
|
return { ok: true, error: "", artifact: payload, filePath };
|
|
79
80
|
} catch (err) {
|
|
80
81
|
return {
|
|
@@ -86,8 +87,8 @@ function saveArtifact(workspaceRoot = process.cwd(), sessionId = "", record = {}
|
|
|
86
87
|
}
|
|
87
88
|
}
|
|
88
89
|
|
|
89
|
-
function loadArtifact(workspaceRoot = process.cwd(), sessionId = "", artifactId = "") {
|
|
90
|
-
const filePath = getArtifactFilePath(workspaceRoot, sessionId, artifactId);
|
|
90
|
+
function loadArtifact(workspaceRoot = process.cwd(), sessionId = "", artifactId = "", options = {}) {
|
|
91
|
+
const filePath = getArtifactFilePath(workspaceRoot, sessionId, artifactId, options.namespace || "ucode");
|
|
91
92
|
if (!filePath || !fs.existsSync(filePath)) {
|
|
92
93
|
return { ok: false, error: `artifact not found: ${artifactId}`, artifact: null, filePath };
|
|
93
94
|
}
|
|
@@ -447,6 +447,7 @@ function persistToolResultToContext({
|
|
|
447
447
|
args = {},
|
|
448
448
|
rawResult = {},
|
|
449
449
|
segmentId = "",
|
|
450
|
+
artifactNamespace = "ucode",
|
|
450
451
|
} = {}) {
|
|
451
452
|
const rawForStorage = stripVisionBase64(rawResult);
|
|
452
453
|
const saved = saveArtifact(workspaceRoot, sessionId, {
|
|
@@ -455,7 +456,7 @@ function persistToolResultToContext({
|
|
|
455
456
|
args,
|
|
456
457
|
raw: rawForStorage,
|
|
457
458
|
createdBy: tool,
|
|
458
|
-
});
|
|
459
|
+
}, { namespace: artifactNamespace });
|
|
459
460
|
const artifactId = saved.artifact && saved.artifact.artifactId
|
|
460
461
|
? saved.artifact.artifactId
|
|
461
462
|
: "";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { systemBlocksToAnthropicPayload } = require("../../agents/providers/transports/systemBlocks");
|
|
1
2
|
"use strict";
|
|
2
3
|
|
|
3
4
|
const {
|
|
@@ -158,19 +159,6 @@ function buildLayeredSystemPrompt({
|
|
|
158
159
|
};
|
|
159
160
|
}
|
|
160
161
|
|
|
161
|
-
function systemBlocksToAnthropicPayload(blocks = []) {
|
|
162
|
-
const list = (Array.isArray(blocks) ? blocks : []).filter((b) => b && b.text);
|
|
163
|
-
const ANTHROPIC_CACHE_CONTROL = { type: "ephemeral" };
|
|
164
|
-
// Place cache breakpoints on every cacheable layer so Anthropic can reuse
|
|
165
|
-
// Immutable → SessionStable → Epoch prefixes independently. Turn-dynamic
|
|
166
|
-
// never gets cache_control.
|
|
167
|
-
return list.map((block) => {
|
|
168
|
-
const entry = { type: "text", text: block.text };
|
|
169
|
-
if (block.cacheable) entry.cache_control = { ...ANTHROPIC_CACHE_CONTROL };
|
|
170
|
-
return entry;
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
|
|
174
162
|
module.exports = {
|
|
175
163
|
PROMPT_VERSION,
|
|
176
164
|
buildImmutablePrefix,
|
|
@@ -1,29 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
if (Array.isArray(value)) return value.map((item) => stableValue(item));
|
|
6
|
-
const keys = Object.keys(value).sort();
|
|
7
|
-
const out = {};
|
|
8
|
-
for (const key of keys) {
|
|
9
|
-
out[key] = stableValue(value[key]);
|
|
10
|
-
}
|
|
11
|
-
return out;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function stableStringify(value) {
|
|
15
|
-
try {
|
|
16
|
-
return JSON.stringify(stableValue(value));
|
|
17
|
-
} catch {
|
|
18
|
-
try {
|
|
19
|
-
return JSON.stringify(value);
|
|
20
|
-
} catch {
|
|
21
|
-
return String(value || "");
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
module.exports = {
|
|
27
|
-
stableValue,
|
|
28
|
-
stableStringify,
|
|
29
|
-
};
|
|
3
|
+
// Existing public entry; implementation belongs to the shared agent layer.
|
|
4
|
+
module.exports = require("../../agents/runtime/core/stableJson");
|
|
@@ -1,119 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
*
|
|
6
|
-
* usedTokens comes from the latest model request's prompt occupancy.
|
|
7
|
-
* limitTokens is resolved from the model id (provider catalogs rarely
|
|
8
|
-
* expose a reliable context_window field).
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
function toTokenCount(value) {
|
|
12
|
-
const parsed = Number(value);
|
|
13
|
-
if (!Number.isFinite(parsed) || parsed <= 0) return 0;
|
|
14
|
-
return Math.floor(parsed);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Prompt-side tokens currently occupying the context window.
|
|
19
|
-
* Anthropic splits input / cache_read / cache_creation; OpenAI folds
|
|
20
|
-
* cache hits into prompt_tokens (cached_tokens is a subset).
|
|
21
|
-
*/
|
|
22
|
-
function contextTokensFromUsage(usage = null) {
|
|
23
|
-
if (!usage || typeof usage !== "object") return 0;
|
|
24
|
-
const input = toTokenCount(usage.input);
|
|
25
|
-
const cacheRead = toTokenCount(usage.cacheRead);
|
|
26
|
-
const cacheCreation = toTokenCount(usage.cacheCreation);
|
|
27
|
-
if (usage.inputIncludesCache === true) return input;
|
|
28
|
-
if (usage.inputIncludesCache === false) return input + cacheRead + cacheCreation;
|
|
29
|
-
if (cacheCreation > 0) return input + cacheRead + cacheCreation;
|
|
30
|
-
// Anthropic exclusive split: input can be smaller than cache_read alone.
|
|
31
|
-
if (cacheRead > 0 && input < cacheRead) return input + cacheRead + cacheCreation;
|
|
32
|
-
// OpenAI-compatible: prompt_tokens already includes cached tokens.
|
|
33
|
-
return input;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function resolveModelContextLimit(model = "", options = {}) {
|
|
37
|
-
const override = toTokenCount(options.limit || options.contextLimit);
|
|
38
|
-
if (override > 0) return override;
|
|
39
|
-
|
|
40
|
-
const id = String(model || "").trim().toLowerCase();
|
|
41
|
-
if (!id) return 200000;
|
|
42
|
-
|
|
43
|
-
if (/\b1m\b|1000000|million|1\.0m/.test(id)) return 1000000;
|
|
44
|
-
if (/256k/.test(id)) return 256000;
|
|
45
|
-
if (/128k/.test(id)) return 128000;
|
|
46
|
-
if (/64k/.test(id)) return 64000;
|
|
47
|
-
if (/32k/.test(id)) return 32000;
|
|
48
|
-
|
|
49
|
-
if (/claude|anthropic|opus|sonnet|haiku/.test(id)) return 200000;
|
|
50
|
-
if (/gemini|gemma/.test(id)) return 1000000;
|
|
51
|
-
if (/kimi|moonshot|k2\.|k2-|k3/.test(id)) return 256000;
|
|
52
|
-
if (/gpt-5|o3|o4|codex/.test(id)) return 200000;
|
|
53
|
-
if (/gpt-4\.1|gpt-4o|gpt-4-turbo|o1/.test(id)) return 128000;
|
|
54
|
-
if (/gpt-4|gpt-3\.5/.test(id)) return 128000;
|
|
55
|
-
|
|
56
|
-
return 200000;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function formatTokensK(tokens = 0) {
|
|
60
|
-
const n = Math.max(0, Math.floor(Number(tokens) || 0));
|
|
61
|
-
if (n < 1000) return String(n);
|
|
62
|
-
const k = n / 1000;
|
|
63
|
-
if (k >= 100) return `${Math.round(k)}K`;
|
|
64
|
-
const tenths = Math.round(k * 10) / 10;
|
|
65
|
-
if (Number.isInteger(tenths)) return `${tenths}K`;
|
|
66
|
-
return `${tenths.toFixed(1)}K`;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function formatContextMeter({ usedTokens = 0, limitTokens = 0 } = {}) {
|
|
70
|
-
const used = Math.max(0, Math.floor(Number(usedTokens) || 0));
|
|
71
|
-
const limit = Math.max(0, Math.floor(Number(limitTokens) || 0));
|
|
72
|
-
if (limit > 0) return `${formatTokensK(used)} / ${formatTokensK(limit)}`;
|
|
73
|
-
return formatTokensK(used);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function buildContextMeter({
|
|
77
|
-
usage = null,
|
|
78
|
-
usedTokens = null,
|
|
79
|
-
model = "",
|
|
80
|
-
limitTokens = null,
|
|
81
|
-
} = {}) {
|
|
82
|
-
const used = usedTokens != null
|
|
83
|
-
? toTokenCount(usedTokens)
|
|
84
|
-
: contextTokensFromUsage(usage);
|
|
85
|
-
const limit = resolveModelContextLimit(model, { limit: limitTokens });
|
|
86
|
-
return {
|
|
87
|
-
usedTokens: used,
|
|
88
|
-
limitTokens: limit,
|
|
89
|
-
model: String(model || "").trim(),
|
|
90
|
-
label: formatContextMeter({ usedTokens: used, limitTokens: limit }),
|
|
91
|
-
updatedAt: new Date().toISOString(),
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function normalizeContextMeter(value = null, model = "") {
|
|
96
|
-
const source = value && typeof value === "object" ? value : {};
|
|
97
|
-
const used = toTokenCount(source.usedTokens);
|
|
98
|
-
const limit = resolveModelContextLimit(
|
|
99
|
-
String(source.model || model || "").trim(),
|
|
100
|
-
{ limit: source.limitTokens },
|
|
101
|
-
);
|
|
102
|
-
return {
|
|
103
|
-
usedTokens: used,
|
|
104
|
-
limitTokens: limit,
|
|
105
|
-
model: String(source.model || model || "").trim(),
|
|
106
|
-
label: formatContextMeter({ usedTokens: used, limitTokens: limit }),
|
|
107
|
-
updatedAt: String(source.updatedAt || "").trim(),
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
module.exports = {
|
|
112
|
-
toTokenCount,
|
|
113
|
-
contextTokensFromUsage,
|
|
114
|
-
resolveModelContextLimit,
|
|
115
|
-
formatTokensK,
|
|
116
|
-
formatContextMeter,
|
|
117
|
-
buildContextMeter,
|
|
118
|
-
normalizeContextMeter,
|
|
119
|
-
};
|
|
3
|
+
// Existing public entry; implementation belongs to the shared agent layer.
|
|
4
|
+
module.exports = require("../agents/runtime/context/contextWindow");
|
|
@@ -1,351 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const { stripVisionBase64, degradeVisionContent } = require("../providers/visionBlocks");
|
|
7
|
-
|
|
8
|
-
const JOURNAL_VERSION = 3;
|
|
9
|
-
|
|
10
|
-
function getJournalDir(workspaceRoot = process.cwd()) {
|
|
11
|
-
return path.join(path.resolve(workspaceRoot || process.cwd()), ".ufoo", "agent", "ucode", "journal");
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function getJournalPath(workspaceRoot = process.cwd(), sessionId = "") {
|
|
15
|
-
const id = String(sessionId || "").trim();
|
|
16
|
-
return id ? path.join(getJournalDir(workspaceRoot), `${id}.jsonl`) : "";
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function getLegacyTranscriptPath(workspaceRoot = process.cwd(), sessionId = "") {
|
|
20
|
-
const id = String(sessionId || "").trim();
|
|
21
|
-
return id
|
|
22
|
-
? path.join(path.resolve(workspaceRoot || process.cwd()), ".ufoo", "agent", "ucode", "transcripts", `${id}.jsonl`)
|
|
23
|
-
: "";
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function deleteSessionJournal(workspaceRoot = process.cwd(), sessionId = "") {
|
|
27
|
-
const filePath = getJournalPath(workspaceRoot, sessionId);
|
|
28
|
-
if (!filePath || !fs.existsSync(filePath)) return { ok: true, error: "" };
|
|
29
|
-
try {
|
|
30
|
-
fs.unlinkSync(filePath);
|
|
31
|
-
return { ok: true, error: "" };
|
|
32
|
-
} catch (err) {
|
|
33
|
-
return {
|
|
34
|
-
ok: false,
|
|
35
|
-
error: err && err.message ? err.message : "failed to delete session journal",
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function readJsonl(filePath = "") {
|
|
41
|
-
if (!filePath || !fs.existsSync(filePath)) return [];
|
|
42
|
-
try {
|
|
43
|
-
return fs.readFileSync(filePath, "utf8")
|
|
44
|
-
.split(/\r?\n/)
|
|
45
|
-
.map((line) => line.trim())
|
|
46
|
-
.filter(Boolean)
|
|
47
|
-
.flatMap((line) => {
|
|
48
|
-
try { return [JSON.parse(line)]; } catch { return []; }
|
|
49
|
-
});
|
|
50
|
-
} catch {
|
|
51
|
-
return [];
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function stablePayloadFingerprint(value) {
|
|
56
|
-
try {
|
|
57
|
-
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
58
|
-
} catch {
|
|
59
|
-
return "";
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function contentForStorage(content) {
|
|
64
|
-
if (typeof content === "string") return content;
|
|
65
|
-
if (Array.isArray(content)) {
|
|
66
|
-
const hasVision = content.some((block) => {
|
|
67
|
-
if (!block || typeof block !== "object") return false;
|
|
68
|
-
const type = String(block.type || "").trim().toLowerCase();
|
|
69
|
-
return type === "image" || type === "image_url"
|
|
70
|
-
|| (type === "tool_result" && Array.isArray(block.content));
|
|
71
|
-
});
|
|
72
|
-
return hasVision
|
|
73
|
-
? degradeVisionContent(stripVisionBase64(content))
|
|
74
|
-
: stripVisionBase64(content);
|
|
75
|
-
}
|
|
76
|
-
if (content && typeof content === "object") return stripVisionBase64(content);
|
|
77
|
-
return content;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function parseArtifactMessage(message = {}) {
|
|
81
|
-
if (typeof message.content !== "string" || !message.content.trim()) return null;
|
|
82
|
-
try {
|
|
83
|
-
const parsed = JSON.parse(message.content);
|
|
84
|
-
const artifactId = String(parsed && parsed.artifactId || "").trim();
|
|
85
|
-
if (!artifactId) return null;
|
|
86
|
-
return { artifactId, preview: String(parsed.preview || "").trim() };
|
|
87
|
-
} catch {
|
|
88
|
-
return null;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function messageEventType(message = {}) {
|
|
93
|
-
const role = String(message.role || "").trim().toLowerCase();
|
|
94
|
-
if (
|
|
95
|
-
role === "user"
|
|
96
|
-
&& Array.isArray(message.content)
|
|
97
|
-
&& message.content.some((block) => String(block && block.type || "").toLowerCase() === "tool_result")
|
|
98
|
-
) {
|
|
99
|
-
return "tool.result";
|
|
100
|
-
}
|
|
101
|
-
if (role === "user") return "user.message";
|
|
102
|
-
if (role === "assistant" && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
|
|
103
|
-
return "assistant.tool_calls";
|
|
104
|
-
}
|
|
105
|
-
if (role === "assistant") return "assistant.message";
|
|
106
|
-
if (role === "tool") return "tool.result";
|
|
107
|
-
return "conversation.item";
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function messageToJournalEvent(message = {}, options = {}) {
|
|
111
|
-
const role = String(message && message.role || "").trim().toLowerCase();
|
|
112
|
-
if (!role || role === "system") return null;
|
|
113
|
-
const turnId = String(options.turnId || "").trim();
|
|
114
|
-
const index = Number.isFinite(options.index) ? Math.max(0, Math.floor(options.index)) : 0;
|
|
115
|
-
const toolCallId = String(message.tool_call_id || "").trim();
|
|
116
|
-
const parsedArtifact = role === "tool" ? parseArtifactMessage(message) : null;
|
|
117
|
-
const artifactId = String(message.artifactId || (parsedArtifact && parsedArtifact.artifactId) || "").trim();
|
|
118
|
-
const artifactPreview = String(message.preview || (parsedArtifact && parsedArtifact.preview) || "").trim();
|
|
119
|
-
const payload = {
|
|
120
|
-
role,
|
|
121
|
-
content: artifactId ? undefined : contentForStorage(message.content),
|
|
122
|
-
toolCalls: Array.isArray(message.tool_calls) ? message.tool_calls : undefined,
|
|
123
|
-
toolCallId: toolCallId || undefined,
|
|
124
|
-
artifactId: artifactId || undefined,
|
|
125
|
-
preview: artifactId ? artifactPreview : undefined,
|
|
126
|
-
};
|
|
127
|
-
const itemId = String(options.itemId || toolCallId || `${turnId || "turn"}:${index}`).trim();
|
|
128
|
-
return {
|
|
129
|
-
version: JOURNAL_VERSION,
|
|
130
|
-
eventId: String(options.eventId || `evt_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`),
|
|
131
|
-
idempotencyKey: String(options.idempotencyKey || `${turnId || "legacy"}:${index}:${messageEventType(message)}`),
|
|
132
|
-
sessionId: String(options.sessionId || "").trim(),
|
|
133
|
-
turnId,
|
|
134
|
-
itemId,
|
|
135
|
-
type: messageEventType(message),
|
|
136
|
-
createdAt: String(options.createdAt || new Date().toISOString()),
|
|
137
|
-
payload,
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
function normalizeJournalEvent(event = {}, sessionId = "", seq = 0) {
|
|
142
|
-
const source = event && typeof event === "object" ? event : {};
|
|
143
|
-
return {
|
|
144
|
-
version: JOURNAL_VERSION,
|
|
145
|
-
seq: Number.isFinite(source.seq) ? Math.max(1, Math.floor(source.seq)) : Math.max(1, seq),
|
|
146
|
-
eventId: String(source.eventId || `evt_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`),
|
|
147
|
-
idempotencyKey: String(source.idempotencyKey || ""),
|
|
148
|
-
sessionId: String(source.sessionId || sessionId || "").trim(),
|
|
149
|
-
turnId: String(source.turnId || "").trim(),
|
|
150
|
-
itemId: String(source.itemId || "").trim(),
|
|
151
|
-
type: String(source.type || "conversation.item").trim(),
|
|
152
|
-
createdAt: String(source.createdAt || new Date().toISOString()),
|
|
153
|
-
payload: source.payload && typeof source.payload === "object" ? source.payload : {},
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
function loadJournal(workspaceRoot = process.cwd(), sessionId = "") {
|
|
158
|
-
const filePath = getJournalPath(workspaceRoot, sessionId);
|
|
159
|
-
const events = readJsonl(filePath)
|
|
160
|
-
.filter((event) => Number(event && event.version) === JOURNAL_VERSION)
|
|
161
|
-
.map((event, index) => normalizeJournalEvent(event, sessionId, index + 1))
|
|
162
|
-
.sort((left, right) => left.seq - right.seq);
|
|
163
|
-
return { filePath, events };
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function appendJournalEvents(workspaceRoot = process.cwd(), sessionId = "", events = []) {
|
|
167
|
-
const filePath = getJournalPath(workspaceRoot, sessionId);
|
|
168
|
-
if (!filePath) return { ok: false, error: "invalid session id", events: [] };
|
|
169
|
-
const existing = loadJournal(workspaceRoot, sessionId).events;
|
|
170
|
-
const eventIds = new Set(existing.map((event) => event.eventId).filter(Boolean));
|
|
171
|
-
const keys = new Set(existing.map((event) => event.idempotencyKey).filter(Boolean));
|
|
172
|
-
let seq = existing.reduce((max, event) => Math.max(max, Number(event.seq) || 0), 0);
|
|
173
|
-
const appended = [];
|
|
174
|
-
for (const candidate of Array.isArray(events) ? events : []) {
|
|
175
|
-
const normalized = normalizeJournalEvent(candidate, sessionId, seq + 1);
|
|
176
|
-
if (eventIds.has(normalized.eventId)) continue;
|
|
177
|
-
if (normalized.idempotencyKey && keys.has(normalized.idempotencyKey)) continue;
|
|
178
|
-
seq += 1;
|
|
179
|
-
normalized.seq = seq;
|
|
180
|
-
eventIds.add(normalized.eventId);
|
|
181
|
-
if (normalized.idempotencyKey) keys.add(normalized.idempotencyKey);
|
|
182
|
-
appended.push(normalized);
|
|
183
|
-
}
|
|
184
|
-
if (appended.length === 0) return { ok: true, error: "", events: [], filePath };
|
|
185
|
-
try {
|
|
186
|
-
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
187
|
-
fs.appendFileSync(filePath, `${appended.map((event) => JSON.stringify(event)).join("\n")}\n`, "utf8");
|
|
188
|
-
return { ok: true, error: "", events: appended, filePath };
|
|
189
|
-
} catch (err) {
|
|
190
|
-
return {
|
|
191
|
-
ok: false,
|
|
192
|
-
error: err && err.message ? err.message : "failed to append session journal",
|
|
193
|
-
events: [],
|
|
194
|
-
filePath,
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
function sameLegacyAssistant(left = {}, right = {}) {
|
|
200
|
-
if (String(left.role || "") !== "assistant" || String(right.role || "") !== "assistant") return false;
|
|
201
|
-
return stablePayloadFingerprint({ content: left.content, toolCalls: left.toolCalls })
|
|
202
|
-
=== stablePayloadFingerprint({ content: right.content, toolCalls: right.toolCalls });
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function legacyDuplicateIndexes(events = []) {
|
|
206
|
-
const duplicates = new Set();
|
|
207
|
-
for (let index = 1; index < events.length - 1; index += 1) {
|
|
208
|
-
const prior = events[index - 1] || {};
|
|
209
|
-
const candidate = events[index] || {};
|
|
210
|
-
const next = events[index + 1] || {};
|
|
211
|
-
if (!sameLegacyAssistant(prior, candidate) || String(next.role || "") !== "user") continue;
|
|
212
|
-
const candidateAt = Date.parse(String(candidate.createdAt || ""));
|
|
213
|
-
const priorAt = Date.parse(String(prior.createdAt || ""));
|
|
214
|
-
const nextAt = Date.parse(String(next.createdAt || ""));
|
|
215
|
-
if (
|
|
216
|
-
!Number.isFinite(priorAt)
|
|
217
|
-
|| !Number.isFinite(candidateAt)
|
|
218
|
-
|| !Number.isFinite(nextAt)
|
|
219
|
-
|| candidateAt - priorAt <= 2000
|
|
220
|
-
|| Math.abs(nextAt - candidateAt) > 2000
|
|
221
|
-
) {
|
|
222
|
-
continue;
|
|
223
|
-
}
|
|
224
|
-
duplicates.add(index);
|
|
225
|
-
}
|
|
226
|
-
return duplicates;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function readLegacyProjection(workspaceRoot = process.cwd(), sessionId = "") {
|
|
230
|
-
const filePath = getLegacyTranscriptPath(workspaceRoot, sessionId);
|
|
231
|
-
const events = readJsonl(filePath);
|
|
232
|
-
const duplicates = legacyDuplicateIndexes(events);
|
|
233
|
-
return {
|
|
234
|
-
filePath,
|
|
235
|
-
events: events.filter((_event, index) => !duplicates.has(index)),
|
|
236
|
-
suppressed: [...duplicates].map((index) => ({ duplicate: events[index], original: events[index - 1] })),
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function journalEventToTranscriptEvent(event = {}) {
|
|
241
|
-
const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
|
|
242
|
-
if (!payload.role || event.type === "history.corrected") return null;
|
|
243
|
-
return {
|
|
244
|
-
id: event.eventId,
|
|
245
|
-
role: payload.role,
|
|
246
|
-
content: payload.content,
|
|
247
|
-
toolCalls: payload.toolCalls,
|
|
248
|
-
toolCallId: payload.toolCallId,
|
|
249
|
-
artifactId: payload.artifactId,
|
|
250
|
-
preview: payload.preview,
|
|
251
|
-
segmentId: payload.segmentId,
|
|
252
|
-
turnId: event.turnId,
|
|
253
|
-
itemId: event.itemId,
|
|
254
|
-
createdAt: event.createdAt,
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
function loadTranscriptProjection(workspaceRoot = process.cwd(), sessionId = "") {
|
|
259
|
-
const journal = loadJournal(workspaceRoot, sessionId);
|
|
260
|
-
if (journal.events.length > 0) {
|
|
261
|
-
return {
|
|
262
|
-
filePath: journal.filePath,
|
|
263
|
-
events: journal.events.map(journalEventToTranscriptEvent).filter(Boolean),
|
|
264
|
-
source: "journal-v3",
|
|
265
|
-
suppressed: [],
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
const legacy = readLegacyProjection(workspaceRoot, sessionId);
|
|
269
|
-
return { ...legacy, source: "transcript-v2" };
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
function migrateLegacyJournal(workspaceRoot = process.cwd(), sessionId = "") {
|
|
273
|
-
const current = loadJournal(workspaceRoot, sessionId);
|
|
274
|
-
if (current.events.length > 0) return { ok: true, migrated: false, ...current };
|
|
275
|
-
const legacy = readLegacyProjection(workspaceRoot, sessionId);
|
|
276
|
-
if (legacy.events.length === 0 && legacy.suppressed.length === 0) {
|
|
277
|
-
return { ok: true, migrated: false, filePath: current.filePath, events: [] };
|
|
278
|
-
}
|
|
279
|
-
const imported = legacy.events.flatMap((message, index) => {
|
|
280
|
-
const event = messageToJournalEvent({
|
|
281
|
-
role: message.role,
|
|
282
|
-
content: message.content,
|
|
283
|
-
tool_calls: message.toolCalls,
|
|
284
|
-
tool_call_id: message.toolCallId,
|
|
285
|
-
artifactId: message.artifactId,
|
|
286
|
-
preview: message.preview,
|
|
287
|
-
}, {
|
|
288
|
-
sessionId,
|
|
289
|
-
turnId: String(message.turnId || message.segmentId || "legacy"),
|
|
290
|
-
index,
|
|
291
|
-
eventId: `migrated_${String(message.id || index)}`,
|
|
292
|
-
idempotencyKey: `legacy:${String(message.id || index)}`,
|
|
293
|
-
createdAt: message.createdAt,
|
|
294
|
-
});
|
|
295
|
-
return event ? [event] : [];
|
|
296
|
-
});
|
|
297
|
-
const corrections = legacy.suppressed.map(({ duplicate, original }, index) => ({
|
|
298
|
-
version: JOURNAL_VERSION,
|
|
299
|
-
eventId: `correction_${String(duplicate && duplicate.id || index)}`,
|
|
300
|
-
idempotencyKey: `correction:${String(duplicate && duplicate.id || index)}`,
|
|
301
|
-
sessionId,
|
|
302
|
-
turnId: "migration",
|
|
303
|
-
itemId: "",
|
|
304
|
-
type: "history.corrected",
|
|
305
|
-
createdAt: new Date().toISOString(),
|
|
306
|
-
payload: {
|
|
307
|
-
suppressedEventId: String(duplicate && duplicate.id || ""),
|
|
308
|
-
duplicateOf: String(original && original.id || ""),
|
|
309
|
-
reason: "legacy_system_baseline_shift",
|
|
310
|
-
},
|
|
311
|
-
}));
|
|
312
|
-
const result = appendJournalEvents(workspaceRoot, sessionId, imported.concat(corrections));
|
|
313
|
-
return { ...result, migrated: result.ok, suppressed: legacy.suppressed.length };
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
function appendTurnMessages(
|
|
317
|
-
workspaceRoot = process.cwd(),
|
|
318
|
-
sessionId = "",
|
|
319
|
-
turnId = "",
|
|
320
|
-
messages = [],
|
|
321
|
-
options = {},
|
|
322
|
-
) {
|
|
323
|
-
const migration = migrateLegacyJournal(workspaceRoot, sessionId);
|
|
324
|
-
if (!migration.ok) return migration;
|
|
325
|
-
const scope = String(options.scope || "items").trim() || "items";
|
|
326
|
-
const events = (Array.isArray(messages) ? messages : []).flatMap((message, index) => {
|
|
327
|
-
const event = messageToJournalEvent(message, {
|
|
328
|
-
sessionId,
|
|
329
|
-
turnId,
|
|
330
|
-
index,
|
|
331
|
-
idempotencyKey: `${turnId || "turn"}:${scope}:${index}:${messageEventType(message)}`,
|
|
332
|
-
});
|
|
333
|
-
return event ? [event] : [];
|
|
334
|
-
});
|
|
335
|
-
return appendJournalEvents(workspaceRoot, sessionId, events);
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
module.exports = {
|
|
339
|
-
JOURNAL_VERSION,
|
|
340
|
-
getJournalDir,
|
|
341
|
-
getJournalPath,
|
|
342
|
-
deleteSessionJournal,
|
|
343
|
-
loadJournal,
|
|
344
|
-
appendJournalEvents,
|
|
345
|
-
appendTurnMessages,
|
|
346
|
-
loadTranscriptProjection,
|
|
347
|
-
migrateLegacyJournal,
|
|
348
|
-
legacyDuplicateIndexes,
|
|
349
|
-
messageToJournalEvent,
|
|
350
|
-
journalEventToTranscriptEvent,
|
|
351
|
-
};
|
|
3
|
+
const { createSessionJournal } = require("../../agents/runtime/context/sessionJournal");
|
|
4
|
+
// Preserve existing ucode journal/transcript paths and exported functions.
|
|
5
|
+
module.exports = createSessionJournal({ namespace: "ucode" });
|