u-foo 3.1.7 → 4.0.1
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/OBSERVABILITY.md +65 -0
- package/README.md +238 -21
- package/README.zh-CN.md +165 -20
- package/SKILLS/ufoo/SKILL.md +40 -4
- package/SKILLS/ufoo-bus/SKILL.md +46 -3
- package/bin/uclaude.js +4 -0
- package/bin/ucodex.js +4 -0
- package/bin/ufoo.js +6 -4
- 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 +14 -7
- 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/activityDetector.js +1 -1
- package/src/agents/activity/activityStateWriter.js +37 -38
- package/src/agents/capabilities/agentManagement/index.js +4 -0
- package/src/agents/capabilities/agentManagement/service.js +140 -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 +40 -22
- package/src/agents/controller/index.js +1 -6
- package/src/agents/internal/internalRunner.js +181 -76
- package/src/agents/launch/index.js +0 -1
- package/src/agents/launch/launcher.js +96 -14
- package/src/agents/launch/nativeCapabilities.js +40 -0
- package/src/agents/launch/nativeMessages.js +362 -0
- package/src/agents/launch/notifier.js +15 -20
- package/src/agents/launch/readyDetector.js +28 -14
- 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/cooperation.js +14 -0
- package/src/agents/prompts/defaultBootstrap.js +1 -1
- package/src/agents/prompts/groupBootstrap.js +32 -6
- package/src/agents/prompts/mainAgent.js +48 -0
- package/src/agents/prompts/native/system.js +4 -1
- package/src/agents/prompts/native/tasks.js +2 -2
- package/src/agents/prompts/native/ufoo.js +14 -3
- package/src/agents/prompts/promptProfiles.js +2 -0
- package/src/agents/prompts/reporting.js +16 -0
- package/src/agents/providers/claudeEventTranslator.js +9 -1
- package/src/agents/providers/claudeThreadProvider.js +47 -4
- package/src/agents/providers/clientIdentity.js +75 -0
- package/src/agents/providers/codexEventTranslator.js +68 -7
- package/src/agents/providers/codexThreadProvider.js +18 -8
- package/src/agents/providers/credentials/claude.js +10 -3
- package/src/agents/providers/credentials/index.js +2 -0
- package/src/agents/providers/directAuthStatus.js +1 -1
- package/src/agents/providers/index.js +1 -1
- package/src/agents/providers/modelSettings.js +34 -0
- package/src/agents/providers/modelsCatalog.js +379 -0
- package/src/agents/providers/nativeTransport.js +1146 -0
- package/src/agents/providers/runtimeConfig.js +188 -0
- package/src/agents/providers/thinkingLevels.js +106 -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 +504 -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/upstreamRuntime.js +135 -0
- package/src/agents/runtime/composeCapabilities.js +89 -0
- package/src/agents/runtime/context/checkpointStore.js +38 -0
- package/src/agents/runtime/context/commandStore.js +43 -0
- package/src/agents/runtime/context/compaction.js +151 -0
- package/src/agents/runtime/context/contextBudget.js +93 -0
- package/src/agents/runtime/context/contextWindow.js +119 -0
- package/src/agents/runtime/context/fileLock.js +36 -0
- package/src/agents/runtime/context/replayHistory.js +28 -0
- package/src/agents/runtime/context/runtimeStore.js +127 -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 +351 -0
- package/src/agents/runtime/core/executionBudget.js +36 -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 +259 -0
- package/src/agents/runtime/index.js +14 -0
- package/src/agents/runtime/prompts/responseLanguage.js +12 -0
- package/src/agents/runtime/protocol/faultHarness.js +90 -0
- package/src/agents/runtime/protocol/materialize.js +107 -0
- package/src/agents/runtime/protocol/runObservation.js +24 -0
- package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
- package/src/agents/runtime/protocol/traceContext.js +9 -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 +29 -45
- package/src/app/chat/agentDirectory.js +9 -18
- package/src/app/chat/bootstrap.js +1 -2
- package/src/app/chat/commandExecutor.js +111 -313
- package/src/app/chat/commands.js +39 -45
- package/src/app/chat/daemonConnection.js +58 -5
- package/src/app/chat/daemonMessageRouter.js +61 -48
- package/src/app/chat/historyStore.js +12 -48
- package/src/app/chat/inputSubmitHandler.js +21 -35
- package/src/app/chat/internalAgentLogHistory.js +19 -60
- package/src/app/chat/launchRequestContext.js +42 -0
- package/src/app/chat/multiWindow/paneManager.js +91 -164
- package/src/app/chat/streamState.js +3 -7
- 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/init.js +5 -5
- package/src/app/cli/features/skills.js +16 -4
- package/src/app/cli/metricsCommands.js +68 -0
- package/src/app/cli/reportCoreCommands.js +37 -0
- package/src/app/cli/run.js +82 -42
- package/src/app/cli/traceCommands.js +36 -0
- package/src/code/agent.js +34 -17
- package/src/code/busConsumer.js +1 -3
- package/src/code/commands.js +1 -1
- package/src/code/context/artifacts.js +12 -11
- package/src/code/context/assembler.js +9 -9
- package/src/code/context/promptLayers.js +1 -13
- package/src/code/context/stableJson.js +2 -27
- package/src/code/context/stateCommit.js +2 -1
- package/src/code/contextWindow.js +2 -117
- package/src/code/conversation/sessionJournal.js +3 -349
- package/src/code/internalThread.js +107 -0
- package/src/code/launcher/ucode.js +1 -1
- package/src/code/launcher/ucodeBootstrap.js +1 -1
- package/src/code/modelCommand.js +11 -35
- package/src/code/nativeRunner.js +104 -2697
- 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/modelsCatalog.js +1 -317
- 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/repl.js +2 -11
- package/src/code/sessionStore.js +27 -99
- package/src/code/taskDecomposer.js +18 -0
- package/src/code/thinkingLevels.js +1 -130
- package/src/code/toolBudget.js +1 -17
- 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 +95 -131
- package/src/coordination/bus/deliveryQueue.js +16 -2
- package/src/coordination/bus/index.js +14 -9
- package/src/coordination/bus/inject.js +15 -7
- package/src/coordination/bus/message.js +15 -1
- package/src/coordination/bus/nativeReceipts.js +100 -0
- package/src/coordination/bus/nickname.js +1 -1
- package/src/coordination/bus/queue.js +1 -3
- package/src/coordination/bus/subscriber.js +3 -2
- package/src/coordination/bus/utils.js +8 -4
- package/src/coordination/history/agentPerformance.js +279 -0
- package/src/coordination/history/agentSurface.js +142 -0
- package/src/coordination/history/agentTrace.js +249 -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/orchestration/controller/index.js +1 -8
- package/src/orchestration/controller/launchRouting.js +1 -1
- package/src/orchestration/solo/commands.js +3 -1
- package/src/runtime/contracts/agentMode.js +26 -0
- package/src/runtime/contracts/eventContract.js +3 -0
- package/src/runtime/contracts/uiProtocol.js +20 -17
- package/src/runtime/daemon/agentHost.js +407 -0
- package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
- package/src/runtime/daemon/busBridge.js +396 -0
- package/src/runtime/daemon/claudeChannel.js +159 -0
- package/src/runtime/daemon/controlPlaneService.js +28 -18
- package/src/runtime/daemon/cronOps.js +25 -17
- package/src/runtime/daemon/deliveryScheduler.js +32 -5
- package/src/runtime/daemon/globalDaemon.js +28 -1
- package/src/runtime/daemon/groupOrchestrator.js +21 -5
- package/src/runtime/daemon/groupStatus.js +20 -0
- package/src/runtime/daemon/index.js +120 -375
- 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 +8 -5
- package/src/runtime/daemon/mcpStdioProxy.js +127 -10
- package/src/runtime/daemon/nicknameScope.js +1 -1
- package/src/runtime/daemon/ops.js +68 -40
- package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
- package/src/runtime/daemon/promptRequest.js +92 -570
- package/src/runtime/daemon/providerSessions.js +67 -33
- package/src/runtime/daemon/reportControlBus.js +59 -25
- package/src/runtime/daemon/status.js +9 -6
- 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 +28 -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/handlers/tier2.js +4 -2
- package/src/tools/index.js +1 -0
- package/src/tools/registry.js +6 -0
- package/src/tools/schemaFixtures.js +42 -5
- package/src/tools/tier0/readAgentMetrics.js +14 -0
- package/src/tools/tier0/readAgentTrace.js +12 -0
- 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/agentSettingsController.js +107 -0
- package/src/ui/agentSurface.js +270 -0
- package/src/ui/dashboardBridge.js +1 -1
- package/src/ui/format/banner.js +9 -15
- package/src/ui/format/index.js +14 -10
- package/src/ui/format/loopSummary.js +50 -0
- package/src/ui/format/markdownRenderer.js +3 -4
- package/src/ui/format/startupBanner.js +50 -0
- package/src/ui/multiPaneBusMirror.js +29 -3
- package/src/ui/rustChatHost.js +316 -599
- package/src/ui/rustMultiSession.js +288 -73
- package/src/ui/rustUcodeHost.js +21 -88
- package/src/ui/settingsBridge.js +34 -14
- package/src/ui/toolMergeBridge.js +0 -4
- package/src/ui/uiHostServer.js +5 -8
- package/src/agents/controller/loopObservability.js +0 -200
- package/src/agents/controller/loopRuntime.js +0 -472
- package/src/agents/controller/ufooAgent.js +0 -829
- package/src/agents/launch/ptyRunner.js +0 -1135
- package/src/agents/providers/upstreamTransport.js +0 -689
- package/src/app/chat/agentBar.js +0 -135
- package/src/app/chat/agentEnter.js +0 -70
- package/src/app/chat/agentSockets.js +0 -225
- package/src/app/chat/dashboardView.js +0 -405
- 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/app/chat/rawKeyMap.js +0 -42
- package/src/app/chat/settingsController.js +0 -111
- package/src/orchestration/controller/flags.js +0 -167
- package/src/orchestration/controller/gateRouter.js +0 -211
- package/src/orchestration/controller/routerFastPath.js +0 -22
- package/src/orchestration/controller/routerFinalize.js +0 -222
- package/src/orchestration/controller/shadowGuard.js +0 -280
- package/src/runtime/daemon/promptLoop.js +0 -136
- package/src/runtime/privacy/shadowDiff.js +0 -174
- package/src/ui/multiWindowHandoff.js +0 -232
- package/src/ui/ptyHandoff.js +0 -23
|
@@ -34,6 +34,7 @@ const { renderExecutionSegmentContext } = require("./executionSegment");
|
|
|
34
34
|
const { renderPlanModeContext } = require("./planMode");
|
|
35
35
|
const { drainAgentMailboxForTurn } = require("../runtime/agentWakeup");
|
|
36
36
|
const { stripVisionBase64, degradeVisionContent } = require("../providers/visionBlocks");
|
|
37
|
+
const { DEFAULT_CONTEXT_POLICY } = require("../../agents/runtime/context/compaction");
|
|
37
38
|
|
|
38
39
|
const DEFAULT_TRANSCRIPT_WINDOW = 12;
|
|
39
40
|
const DEFAULT_RECENT_TOOL_EVENTS = 4;
|
|
@@ -46,7 +47,7 @@ function resolveTranscriptWindow(env = process.env) {
|
|
|
46
47
|
|
|
47
48
|
function defaultContextPolicy(env = process.env) {
|
|
48
49
|
return {
|
|
49
|
-
|
|
50
|
+
...DEFAULT_CONTEXT_POLICY,
|
|
50
51
|
commitInterval: resolveCommitInterval(env),
|
|
51
52
|
};
|
|
52
53
|
}
|
|
@@ -389,14 +390,12 @@ function ensureTranscript(session = {}, workspaceRoot = process.cwd()) {
|
|
|
389
390
|
|
|
390
391
|
function assembleModelContext(session = {}, request = {}, env = process.env) {
|
|
391
392
|
const workspaceRoot = String(session.workspaceRoot || request.workspaceRoot || process.cwd());
|
|
392
|
-
const policy = {
|
|
393
|
-
...defaultContextPolicy(env),
|
|
394
|
-
...(session.contextPolicy && typeof session.contextPolicy === "object" ? session.contextPolicy : {}),
|
|
395
|
-
};
|
|
393
|
+
const policy = { ...defaultContextPolicy(env), ...(session.contextPolicy || {}) };
|
|
396
394
|
session.workingSet = pruneWorkingSetByRetention(session.workingSet, session);
|
|
397
395
|
const transcriptEvents = ensureTranscript(session, workspaceRoot);
|
|
398
|
-
|
|
399
|
-
|
|
396
|
+
// Semantic checkpointing lives in shared runtime, before each model call.
|
|
397
|
+
// Do not silently replace older conversation with a deterministic digest.
|
|
398
|
+
const summary = "";
|
|
400
399
|
|
|
401
400
|
const layered = buildLayeredSystemPrompt({
|
|
402
401
|
workspaceRoot,
|
|
@@ -428,7 +427,7 @@ function assembleModelContext(session = {}, request = {}, env = process.env) {
|
|
|
428
427
|
sessionStableExtras: request.sessionStableExtras || "",
|
|
429
428
|
});
|
|
430
429
|
|
|
431
|
-
const recentMessages =
|
|
430
|
+
const recentMessages = sanitizeModelMessages(transcriptEventsToMessages(transcriptEvents, { preferArtifact: true }));
|
|
432
431
|
|
|
433
432
|
return {
|
|
434
433
|
systemPrompt: layered.flatText,
|
|
@@ -447,6 +446,7 @@ function persistToolResultToContext({
|
|
|
447
446
|
args = {},
|
|
448
447
|
rawResult = {},
|
|
449
448
|
segmentId = "",
|
|
449
|
+
artifactNamespace = "ucode",
|
|
450
450
|
} = {}) {
|
|
451
451
|
const rawForStorage = stripVisionBase64(rawResult);
|
|
452
452
|
const saved = saveArtifact(workspaceRoot, sessionId, {
|
|
@@ -455,7 +455,7 @@ function persistToolResultToContext({
|
|
|
455
455
|
args,
|
|
456
456
|
raw: rawForStorage,
|
|
457
457
|
createdBy: tool,
|
|
458
|
-
});
|
|
458
|
+
}, { namespace: artifactNamespace });
|
|
459
459
|
const artifactId = saved.artifact && saved.artifact.artifactId
|
|
460
460
|
? saved.artifact.artifactId
|
|
461
461
|
: "";
|
|
@@ -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");
|
|
@@ -170,7 +170,8 @@ function renderStateEpoch(stateEpoch = null) {
|
|
|
170
170
|
"State Snapshot:",
|
|
171
171
|
`- Phase: ${snap.phase || "active"}`,
|
|
172
172
|
snap.currentObjective ? `- Current objective: ${snap.currentObjective}` : "",
|
|
173
|
-
snap.facts && snap.facts.length > 0 ? `-
|
|
173
|
+
snap.facts && snap.facts.length > 0 ? `- Recent facts: ${snap.facts.slice(-40).join("; ")}` : "",
|
|
174
|
+
snap.facts && snap.facts.length > 40 ? `- ${snap.facts.length - 40} older facts remain in durable state, conversation history and referenced artifacts.` : "",
|
|
174
175
|
snap.hypotheses && snap.hypotheses.length > 0 ? `- Hypotheses: ${snap.hypotheses.join("; ")}` : "",
|
|
175
176
|
snap.decisions && snap.decisions.length > 0 ? `- Decisions: ${snap.decisions.join("; ")}` : "",
|
|
176
177
|
snap.openQuestions && snap.openQuestions.length > 0 ? `- Open questions: ${snap.openQuestions.join("; ")}` : "",
|
|
@@ -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" });
|