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.
Files changed (193) hide show
  1. package/README.md +172 -13
  2. package/README.zh-CN.md +108 -13
  3. package/SKILLS/ufoo/SKILL.md +15 -3
  4. package/SKILLS/ufoo-bus/SKILL.md +21 -1
  5. package/bin/uclaude.js +4 -0
  6. package/bin/ucodex.js +4 -0
  7. package/bin/ufoo.js +3 -1
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +10 -3
  13. package/scripts/postinstall-skills.js +53 -0
  14. package/scripts/postinstall.js +11 -16
  15. package/scripts/smoke-native-messages.js +214 -0
  16. package/src/agents/activity/activityStateWriter.js +37 -38
  17. package/src/agents/capabilities/agentManagement/index.js +4 -0
  18. package/src/agents/capabilities/agentManagement/service.js +113 -0
  19. package/src/agents/capabilities/agentRouting/index.js +4 -0
  20. package/src/agents/capabilities/coding/index.js +32 -0
  21. package/src/agents/capabilities/coordination/index.js +37 -0
  22. package/src/agents/capabilities/globalRouting/index.js +5 -0
  23. package/src/agents/capabilities/groups/index.js +3 -0
  24. package/src/agents/capabilities/index.js +25 -0
  25. package/src/agents/capabilities/planning/index.js +123 -0
  26. package/src/agents/capabilities/planning/main.js +28 -0
  27. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  28. package/src/agents/capabilities/scheduling/index.js +3 -0
  29. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  30. package/src/agents/capabilities/skills/index.js +12 -0
  31. package/src/agents/capabilities/taskExecution/index.js +3 -0
  32. package/src/agents/capabilities/taskReports/index.js +6 -0
  33. package/src/agents/controller/controllerToolExecutor.js +6 -4
  34. package/src/agents/controller/loopRuntime.js +85 -221
  35. package/src/agents/controller/ufooAgent.js +1 -0
  36. package/src/agents/internal/internalRunner.js +103 -32
  37. package/src/agents/launch/launcher.js +88 -6
  38. package/src/agents/launch/nativeCapabilities.js +40 -0
  39. package/src/agents/launch/nativeMessages.js +362 -0
  40. package/src/agents/launch/notifier.js +13 -18
  41. package/src/agents/launch/readyDetector.js +26 -12
  42. package/src/agents/profiles/coding.js +6 -0
  43. package/src/agents/profiles/globalRouter.js +2 -0
  44. package/src/agents/profiles/main.js +5 -0
  45. package/src/agents/prompts/groupBootstrap.js +10 -0
  46. package/src/agents/prompts/mainAgent.js +39 -0
  47. package/src/agents/prompts/native/tasks.js +2 -2
  48. package/src/agents/prompts/native/ufoo.js +3 -0
  49. package/src/agents/providers/claudeEventTranslator.js +6 -1
  50. package/src/agents/providers/claudeThreadProvider.js +44 -2
  51. package/src/agents/providers/codexEventTranslator.js +47 -7
  52. package/src/agents/providers/codexThreadProvider.js +3 -2
  53. package/src/agents/providers/controllerJsonTransport.js +28 -0
  54. package/src/agents/providers/credentials/claude.js +10 -3
  55. package/src/agents/providers/nativeTransport.js +1135 -0
  56. package/src/agents/providers/runtimeConfig.js +186 -0
  57. package/src/agents/providers/thinkingLevels.js +132 -0
  58. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  59. package/src/agents/providers/transports/index.js +10 -0
  60. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  61. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  62. package/src/agents/providers/transports/responsesProtocol.js +499 -0
  63. package/src/agents/providers/transports/systemBlocks.js +16 -0
  64. package/src/agents/providers/transports/transportContract.js +50 -0
  65. package/src/agents/providers/transports/visionBlocks.js +151 -0
  66. package/src/agents/providers/upstreamTransport.js +13 -4
  67. package/src/agents/runtime/composeCapabilities.js +89 -0
  68. package/src/agents/runtime/context/commandStore.js +43 -0
  69. package/src/agents/runtime/context/contextWindow.js +119 -0
  70. package/src/agents/runtime/context/fileLock.js +36 -0
  71. package/src/agents/runtime/context/runtimeStore.js +126 -0
  72. package/src/agents/runtime/context/sessionJournal.js +360 -0
  73. package/src/agents/runtime/context/sessionStore.js +57 -0
  74. package/src/agents/runtime/core/agentLoop.js +270 -0
  75. package/src/agents/runtime/core/stableJson.js +29 -0
  76. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  77. package/src/agents/runtime/createAgentRuntime.js +247 -0
  78. package/src/agents/runtime/index.js +14 -0
  79. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  80. package/src/agents/runtime/protocol/materialize.js +107 -0
  81. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  82. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  83. package/src/agents/runtime/tasks/scheduler.js +73 -0
  84. package/src/agents/runtime/tools/registry.js +57 -0
  85. package/src/app/chat/ChatController.js +14 -3
  86. package/src/app/chat/agentDirectory.js +8 -2
  87. package/src/app/chat/commandExecutor.js +36 -46
  88. package/src/app/chat/commands.js +14 -7
  89. package/src/app/chat/daemonConnection.js +58 -5
  90. package/src/app/chat/daemonMessageRouter.js +61 -3
  91. package/src/app/chat/inputSubmitHandler.js +14 -2
  92. package/src/app/chat/launchRequestContext.js +42 -0
  93. package/src/app/chat/multiWindow/paneManager.js +85 -165
  94. package/src/app/chat/streamState.js +3 -3
  95. package/src/app/chat/transport.js +1 -1
  96. package/src/app/cli/busCoreCommands.js +9 -0
  97. package/src/app/cli/features/doctor.js +33 -0
  98. package/src/app/cli/features/skills.js +16 -4
  99. package/src/app/cli/reportCoreCommands.js +37 -0
  100. package/src/app/cli/run.js +40 -39
  101. package/src/code/agent.js +16 -4
  102. package/src/code/context/artifacts.js +12 -11
  103. package/src/code/context/assembler.js +2 -1
  104. package/src/code/context/promptLayers.js +1 -13
  105. package/src/code/context/stableJson.js +2 -27
  106. package/src/code/contextWindow.js +2 -117
  107. package/src/code/conversation/sessionJournal.js +3 -349
  108. package/src/code/internalThread.js +100 -0
  109. package/src/code/nativeRunner.js +36 -2668
  110. package/src/code/protocol/faultHarness.js +2 -88
  111. package/src/code/protocol/materialize.js +2 -105
  112. package/src/code/protocol/toolCallLedger.js +5 -215
  113. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  114. package/src/code/providers/openaiChatTransport.js +2 -114
  115. package/src/code/providers/openaiResponsesTransport.js +2 -117
  116. package/src/code/providers/responsesProtocol.js +2 -497
  117. package/src/code/providers/transportContract.js +2 -48
  118. package/src/code/providers/visionBlocks.js +2 -149
  119. package/src/code/sessionStore.js +24 -96
  120. package/src/code/thinkingLevels.js +1 -130
  121. package/src/code/toolLoopGuard.js +3 -49
  122. package/src/code/tools/artifactRead.js +1 -1
  123. package/src/code/tools/executor.js +373 -0
  124. package/src/code/tools/specs.js +312 -0
  125. package/src/config.js +81 -67
  126. package/src/coordination/bus/deliveryQueue.js +16 -2
  127. package/src/coordination/bus/index.js +2 -6
  128. package/src/coordination/bus/inject.js +13 -5
  129. package/src/coordination/bus/nativeReceipts.js +100 -0
  130. package/src/coordination/bus/queue.js +1 -3
  131. package/src/coordination/bus/utils.js +7 -3
  132. package/src/coordination/history/agentSurface.js +142 -0
  133. package/src/coordination/history/controllerSummary.js +23 -0
  134. package/src/coordination/memory/index.js +5 -21
  135. package/src/coordination/report/store.js +103 -83
  136. package/src/coordination/state/agentsStore.js +57 -3
  137. package/src/coordination/state/fileLock.js +2 -0
  138. package/src/coordination/state/workspaceAccess.js +36 -0
  139. package/src/runtime/contracts/agentMode.js +17 -0
  140. package/src/runtime/contracts/eventContract.js +3 -0
  141. package/src/runtime/contracts/uiProtocol.js +4 -0
  142. package/src/runtime/daemon/agentHost.js +375 -0
  143. package/src/runtime/daemon/busBridge.js +396 -0
  144. package/src/runtime/daemon/claudeChannel.js +159 -0
  145. package/src/runtime/daemon/controlPlaneService.js +27 -17
  146. package/src/runtime/daemon/cronOps.js +25 -17
  147. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  148. package/src/runtime/daemon/executionPaths.js +30 -0
  149. package/src/runtime/daemon/globalDaemon.js +28 -1
  150. package/src/runtime/daemon/groupOrchestrator.js +1 -0
  151. package/src/runtime/daemon/index.js +114 -344
  152. package/src/runtime/daemon/ipcServer.js +32 -10
  153. package/src/runtime/daemon/mcpConfigure.js +113 -20
  154. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  155. package/src/runtime/daemon/mcpServer.js +7 -4
  156. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  157. package/src/runtime/daemon/ops.js +22 -17
  158. package/src/runtime/daemon/promptRequest.js +23 -4
  159. package/src/runtime/daemon/providerSessions.js +67 -33
  160. package/src/runtime/daemon/reportControlBus.js +59 -25
  161. package/src/runtime/daemon/status.js +4 -0
  162. package/src/runtime/privacy/redactor.js +2 -2
  163. package/src/runtime/projects/identity.js +2 -1
  164. package/src/runtime/projects/registry.js +98 -38
  165. package/src/tools/controllerSchemas.js +24 -0
  166. package/src/tools/handlers/dispatchMessage.js +5 -2
  167. package/src/tools/handlers/listAgents.js +3 -1
  168. package/src/tools/handlers/readBusSummary.js +3 -1
  169. package/src/tools/handlers/readProjectRegistry.js +29 -2
  170. package/src/tools/handlers/routeAgent.js +35 -0
  171. package/src/tools/index.js +1 -0
  172. package/src/tools/registry.js +2 -0
  173. package/src/tools/schemaFixtures.js +16 -3
  174. package/src/tools/tier1/routeAgent.js +2 -2
  175. package/src/tools/tier2/runtimeCoordination.js +38 -0
  176. package/src/tools/types.js +2 -0
  177. package/src/ui/agentPresentation.js +109 -0
  178. package/src/ui/agentSurface.js +270 -0
  179. package/src/ui/format/banner.js +8 -11
  180. package/src/ui/format/startupBanner.js +50 -0
  181. package/src/ui/multiPaneBusMirror.js +29 -3
  182. package/src/ui/rustChatHost.js +170 -438
  183. package/src/ui/rustMultiSession.js +225 -51
  184. package/src/ui/rustUcodeHost.js +20 -87
  185. package/src/ui/settingsBridge.js +7 -4
  186. package/src/app/chat/agentEnter.js +0 -70
  187. package/src/app/chat/multiWindow/index.js +0 -310
  188. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  189. package/src/app/chat/multiWindow/renderer.js +0 -420
  190. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  191. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  192. package/src/ui/multiWindowHandoff.js +0 -232
  193. package/src/ui/ptyHandoff.js +0 -23
@@ -0,0 +1,360 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { randomUUID, createHash } = require("crypto");
6
+ const { stripVisionBase64, degradeVisionContent } = require("../../providers/transports/visionBlocks");
7
+
8
+ function createSessionJournal({ namespace = "runtime" } = {}) {
9
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(namespace)) {
10
+ throw new Error("invalid session namespace");
11
+ }
12
+ const JOURNAL_VERSION = 3;
13
+
14
+ function getJournalDir(workspaceRoot = process.cwd()) {
15
+ return path.join(path.resolve(workspaceRoot || process.cwd()), ".ufoo", "agent", namespace, "journal");
16
+ }
17
+
18
+ function getJournalPath(workspaceRoot = process.cwd(), sessionId = "") {
19
+ const rawId = String(sessionId || "").trim();
20
+ const id = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(rawId) ? rawId : "";
21
+ return id ? path.join(getJournalDir(workspaceRoot), `${id}.jsonl`) : "";
22
+ }
23
+
24
+ function getLegacyTranscriptPath(workspaceRoot = process.cwd(), sessionId = "") {
25
+ const rawId = String(sessionId || "").trim();
26
+ const id = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(rawId) ? rawId : "";
27
+ return id
28
+ ? path.join(path.resolve(workspaceRoot || process.cwd()), ".ufoo", "agent", namespace, "transcripts", `${id}.jsonl`)
29
+ : "";
30
+ }
31
+
32
+ function deleteSessionJournal(workspaceRoot = process.cwd(), sessionId = "") {
33
+ const filePath = getJournalPath(workspaceRoot, sessionId);
34
+ if (!filePath || !fs.existsSync(filePath)) return { ok: true, error: "" };
35
+ try {
36
+ fs.unlinkSync(filePath);
37
+ return { ok: true, error: "" };
38
+ } catch (err) {
39
+ return {
40
+ ok: false,
41
+ error: err && err.message ? err.message : "failed to delete session journal",
42
+ };
43
+ }
44
+ }
45
+
46
+ function readJsonl(filePath = "") {
47
+ if (!filePath || !fs.existsSync(filePath)) return [];
48
+ try {
49
+ return fs.readFileSync(filePath, "utf8")
50
+ .split(/\r?\n/)
51
+ .map((line) => line.trim())
52
+ .filter(Boolean)
53
+ .flatMap((line) => {
54
+ try { return [JSON.parse(line)]; } catch { return []; }
55
+ });
56
+ } catch {
57
+ return [];
58
+ }
59
+ }
60
+
61
+ function stablePayloadFingerprint(value) {
62
+ try {
63
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
64
+ } catch {
65
+ return "";
66
+ }
67
+ }
68
+
69
+ function contentForStorage(content) {
70
+ if (typeof content === "string") return content;
71
+ if (Array.isArray(content)) {
72
+ const hasVision = content.some((block) => {
73
+ if (!block || typeof block !== "object") return false;
74
+ const type = String(block.type || "").trim().toLowerCase();
75
+ return type === "image" || type === "image_url"
76
+ || (type === "tool_result" && Array.isArray(block.content));
77
+ });
78
+ return hasVision
79
+ ? degradeVisionContent(stripVisionBase64(content))
80
+ : stripVisionBase64(content);
81
+ }
82
+ if (content && typeof content === "object") return stripVisionBase64(content);
83
+ return content;
84
+ }
85
+
86
+ function parseArtifactMessage(message = {}) {
87
+ if (typeof message.content !== "string" || !message.content.trim()) return null;
88
+ try {
89
+ const parsed = JSON.parse(message.content);
90
+ const artifactId = String(parsed && parsed.artifactId || "").trim();
91
+ if (!artifactId) return null;
92
+ return { artifactId, preview: String(parsed.preview || "").trim() };
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
97
+
98
+ function messageEventType(message = {}) {
99
+ const role = String(message.role || "").trim().toLowerCase();
100
+ if (
101
+ role === "user"
102
+ && Array.isArray(message.content)
103
+ && message.content.some((block) => String(block && block.type || "").toLowerCase() === "tool_result")
104
+ ) {
105
+ return "tool.result";
106
+ }
107
+ if (role === "user") return "user.message";
108
+ if (role === "assistant" && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
109
+ return "assistant.tool_calls";
110
+ }
111
+ if (role === "assistant") return "assistant.message";
112
+ if (role === "tool") return "tool.result";
113
+ return "conversation.item";
114
+ }
115
+
116
+ function messageToJournalEvent(message = {}, options = {}) {
117
+ const role = String(message && message.role || "").trim().toLowerCase();
118
+ if (!role || role === "system") return null;
119
+ const turnId = String(options.turnId || "").trim();
120
+ const index = Number.isFinite(options.index) ? Math.max(0, Math.floor(options.index)) : 0;
121
+ const toolCallId = String(message.tool_call_id || "").trim();
122
+ const parsedArtifact = role === "tool" ? parseArtifactMessage(message) : null;
123
+ const artifactId = String(message.artifactId || (parsedArtifact && parsedArtifact.artifactId) || "").trim();
124
+ const artifactPreview = String(message.preview || (parsedArtifact && parsedArtifact.preview) || "").trim();
125
+ const payload = {
126
+ role,
127
+ content: artifactId ? undefined : contentForStorage(message.content),
128
+ toolCalls: Array.isArray(message.tool_calls) ? message.tool_calls : undefined,
129
+ toolCallId: toolCallId || undefined,
130
+ artifactId: artifactId || undefined,
131
+ preview: artifactId ? artifactPreview : undefined,
132
+ };
133
+ const itemId = String(options.itemId || toolCallId || `${turnId || "turn"}:${index}`).trim();
134
+ return {
135
+ version: JOURNAL_VERSION,
136
+ eventId: String(options.eventId || `evt_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`),
137
+ idempotencyKey: String(options.idempotencyKey || `${turnId || "legacy"}:${index}:${messageEventType(message)}`),
138
+ sessionId: String(options.sessionId || "").trim(),
139
+ turnId,
140
+ itemId,
141
+ type: messageEventType(message),
142
+ createdAt: String(options.createdAt || new Date().toISOString()),
143
+ payload,
144
+ };
145
+ }
146
+
147
+ function normalizeJournalEvent(event = {}, sessionId = "", seq = 0) {
148
+ const source = event && typeof event === "object" ? event : {};
149
+ return {
150
+ version: JOURNAL_VERSION,
151
+ seq: Number.isFinite(source.seq) ? Math.max(1, Math.floor(source.seq)) : Math.max(1, seq),
152
+ eventId: String(source.eventId || `evt_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`),
153
+ idempotencyKey: String(source.idempotencyKey || ""),
154
+ sessionId: String(source.sessionId || sessionId || "").trim(),
155
+ turnId: String(source.turnId || "").trim(),
156
+ itemId: String(source.itemId || "").trim(),
157
+ type: String(source.type || "conversation.item").trim(),
158
+ createdAt: String(source.createdAt || new Date().toISOString()),
159
+ payload: source.payload && typeof source.payload === "object" ? source.payload : {},
160
+ };
161
+ }
162
+
163
+ function loadJournal(workspaceRoot = process.cwd(), sessionId = "") {
164
+ const filePath = getJournalPath(workspaceRoot, sessionId);
165
+ const events = readJsonl(filePath)
166
+ .filter((event) => Number(event && event.version) === JOURNAL_VERSION)
167
+ .map((event, index) => normalizeJournalEvent(event, sessionId, index + 1))
168
+ .sort((left, right) => left.seq - right.seq);
169
+ return { filePath, events };
170
+ }
171
+
172
+ function appendJournalEvents(workspaceRoot = process.cwd(), sessionId = "", events = []) {
173
+ const filePath = getJournalPath(workspaceRoot, sessionId);
174
+ if (!filePath) return { ok: false, error: "invalid session id", events: [] };
175
+ const existing = loadJournal(workspaceRoot, sessionId).events;
176
+ const eventIds = new Set(existing.map((event) => event.eventId).filter(Boolean));
177
+ const keys = new Set(existing.map((event) => event.idempotencyKey).filter(Boolean));
178
+ let seq = existing.reduce((max, event) => Math.max(max, Number(event.seq) || 0), 0);
179
+ const appended = [];
180
+ for (const candidate of Array.isArray(events) ? events : []) {
181
+ const normalized = normalizeJournalEvent(candidate, sessionId, seq + 1);
182
+ if (eventIds.has(normalized.eventId)) continue;
183
+ if (normalized.idempotencyKey && keys.has(normalized.idempotencyKey)) continue;
184
+ seq += 1;
185
+ normalized.seq = seq;
186
+ eventIds.add(normalized.eventId);
187
+ if (normalized.idempotencyKey) keys.add(normalized.idempotencyKey);
188
+ appended.push(normalized);
189
+ }
190
+ if (appended.length === 0) return { ok: true, error: "", events: [], filePath };
191
+ try {
192
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
193
+ fs.appendFileSync(filePath, `${appended.map((event) => JSON.stringify(event)).join("\n")}\n`, "utf8");
194
+ return { ok: true, error: "", events: appended, filePath };
195
+ } catch (err) {
196
+ return {
197
+ ok: false,
198
+ error: err && err.message ? err.message : "failed to append session journal",
199
+ events: [],
200
+ filePath,
201
+ };
202
+ }
203
+ }
204
+
205
+ function sameLegacyAssistant(left = {}, right = {}) {
206
+ if (String(left.role || "") !== "assistant" || String(right.role || "") !== "assistant") return false;
207
+ return stablePayloadFingerprint({ content: left.content, toolCalls: left.toolCalls })
208
+ === stablePayloadFingerprint({ content: right.content, toolCalls: right.toolCalls });
209
+ }
210
+
211
+ function legacyDuplicateIndexes(events = []) {
212
+ const duplicates = new Set();
213
+ for (let index = 1; index < events.length - 1; index += 1) {
214
+ const prior = events[index - 1] || {};
215
+ const candidate = events[index] || {};
216
+ const next = events[index + 1] || {};
217
+ if (!sameLegacyAssistant(prior, candidate) || String(next.role || "") !== "user") continue;
218
+ const candidateAt = Date.parse(String(candidate.createdAt || ""));
219
+ const priorAt = Date.parse(String(prior.createdAt || ""));
220
+ const nextAt = Date.parse(String(next.createdAt || ""));
221
+ if (
222
+ !Number.isFinite(priorAt)
223
+ || !Number.isFinite(candidateAt)
224
+ || !Number.isFinite(nextAt)
225
+ || candidateAt - priorAt <= 2000
226
+ || Math.abs(nextAt - candidateAt) > 2000
227
+ ) {
228
+ continue;
229
+ }
230
+ duplicates.add(index);
231
+ }
232
+ return duplicates;
233
+ }
234
+
235
+ function readLegacyProjection(workspaceRoot = process.cwd(), sessionId = "") {
236
+ const filePath = getLegacyTranscriptPath(workspaceRoot, sessionId);
237
+ const events = readJsonl(filePath);
238
+ const duplicates = legacyDuplicateIndexes(events);
239
+ return {
240
+ filePath,
241
+ events: events.filter((_event, index) => !duplicates.has(index)),
242
+ suppressed: [...duplicates].map((index) => ({ duplicate: events[index], original: events[index - 1] })),
243
+ };
244
+ }
245
+
246
+ function journalEventToTranscriptEvent(event = {}) {
247
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
248
+ if (!payload.role || event.type === "history.corrected") return null;
249
+ return {
250
+ id: event.eventId,
251
+ role: payload.role,
252
+ content: payload.content,
253
+ toolCalls: payload.toolCalls,
254
+ toolCallId: payload.toolCallId,
255
+ artifactId: payload.artifactId,
256
+ preview: payload.preview,
257
+ segmentId: payload.segmentId,
258
+ turnId: event.turnId,
259
+ itemId: event.itemId,
260
+ createdAt: event.createdAt,
261
+ };
262
+ }
263
+
264
+ function loadTranscriptProjection(workspaceRoot = process.cwd(), sessionId = "") {
265
+ const journal = loadJournal(workspaceRoot, sessionId);
266
+ if (journal.events.length > 0) {
267
+ return {
268
+ filePath: journal.filePath,
269
+ events: journal.events.map(journalEventToTranscriptEvent).filter(Boolean),
270
+ source: "journal-v3",
271
+ suppressed: [],
272
+ };
273
+ }
274
+ const legacy = readLegacyProjection(workspaceRoot, sessionId);
275
+ return { ...legacy, source: "transcript-v2" };
276
+ }
277
+
278
+ function migrateLegacyJournal(workspaceRoot = process.cwd(), sessionId = "") {
279
+ const current = loadJournal(workspaceRoot, sessionId);
280
+ if (current.events.length > 0) return { ok: true, migrated: false, ...current };
281
+ const legacy = readLegacyProjection(workspaceRoot, sessionId);
282
+ if (legacy.events.length === 0 && legacy.suppressed.length === 0) {
283
+ return { ok: true, migrated: false, filePath: current.filePath, events: [] };
284
+ }
285
+ const imported = legacy.events.flatMap((message, index) => {
286
+ const event = messageToJournalEvent({
287
+ role: message.role,
288
+ content: message.content,
289
+ tool_calls: message.toolCalls,
290
+ tool_call_id: message.toolCallId,
291
+ artifactId: message.artifactId,
292
+ preview: message.preview,
293
+ }, {
294
+ sessionId,
295
+ turnId: String(message.turnId || message.segmentId || "legacy"),
296
+ index,
297
+ eventId: `migrated_${String(message.id || index)}`,
298
+ idempotencyKey: `legacy:${String(message.id || index)}`,
299
+ createdAt: message.createdAt,
300
+ });
301
+ return event ? [event] : [];
302
+ });
303
+ const corrections = legacy.suppressed.map(({ duplicate, original }, index) => ({
304
+ version: JOURNAL_VERSION,
305
+ eventId: `correction_${String(duplicate && duplicate.id || index)}`,
306
+ idempotencyKey: `correction:${String(duplicate && duplicate.id || index)}`,
307
+ sessionId,
308
+ turnId: "migration",
309
+ itemId: "",
310
+ type: "history.corrected",
311
+ createdAt: new Date().toISOString(),
312
+ payload: {
313
+ suppressedEventId: String(duplicate && duplicate.id || ""),
314
+ duplicateOf: String(original && original.id || ""),
315
+ reason: "legacy_system_baseline_shift",
316
+ },
317
+ }));
318
+ const result = appendJournalEvents(workspaceRoot, sessionId, imported.concat(corrections));
319
+ return { ...result, migrated: result.ok, suppressed: legacy.suppressed.length };
320
+ }
321
+
322
+ function appendTurnMessages(
323
+ workspaceRoot = process.cwd(),
324
+ sessionId = "",
325
+ turnId = "",
326
+ messages = [],
327
+ options = {},
328
+ ) {
329
+ const migration = migrateLegacyJournal(workspaceRoot, sessionId);
330
+ if (!migration.ok) return migration;
331
+ const scope = String(options.scope || "items").trim() || "items";
332
+ const events = (Array.isArray(messages) ? messages : []).flatMap((message, index) => {
333
+ const event = messageToJournalEvent(message, {
334
+ sessionId,
335
+ turnId,
336
+ index,
337
+ idempotencyKey: `${turnId || "turn"}:${scope}:${index}:${messageEventType(message)}`,
338
+ });
339
+ return event ? [event] : [];
340
+ });
341
+ return appendJournalEvents(workspaceRoot, sessionId, events);
342
+ }
343
+
344
+ return Object.freeze({
345
+ JOURNAL_VERSION,
346
+ getJournalDir,
347
+ getJournalPath,
348
+ deleteSessionJournal,
349
+ loadJournal,
350
+ appendJournalEvents,
351
+ appendTurnMessages,
352
+ loadTranscriptProjection,
353
+ migrateLegacyJournal,
354
+ legacyDuplicateIndexes,
355
+ messageToJournalEvent,
356
+ journalEventToTranscriptEvent,
357
+ });
358
+ }
359
+
360
+ module.exports = { createSessionJournal };
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { randomUUID } = require("crypto");
6
+
7
+ /** Storage mechanism only: product fields, history hydration and GC are host codecs. */
8
+ function createSessionStore({
9
+ namespace = "runtime", encode = (snapshot) => ({ ...snapshot }),
10
+ toDisk = (snapshot) => snapshot, decode = (snapshot) => snapshot,
11
+ prepareSave = () => {},
12
+ } = {}) {
13
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(namespace)) throw new Error("invalid session namespace");
14
+ const normalizeId = (id) => /^[a-zA-Z0-9][a-zA-Z0-9._:-]{2,127}$/.test(String(id || "").trim()) ? String(id).trim() : "";
15
+ const getDirectory = (root = process.cwd()) => path.join(path.resolve(root || process.cwd()), ".ufoo", "agent", namespace, "sessions");
16
+ const getFilePath = (root, id) => normalizeId(id) ? path.join(getDirectory(root), `${normalizeId(id)}.json`) : "";
17
+ return Object.freeze({
18
+ getDirectory, getFilePath,
19
+ save(root = process.cwd(), input = {}) {
20
+ const workspaceRoot = path.resolve(root || process.cwd());
21
+ let payload;
22
+ let filePath = "";
23
+ let temporary = "";
24
+ try {
25
+ payload = encode(input, { workspaceRoot });
26
+ filePath = getFilePath(workspaceRoot, payload.sessionId);
27
+ if (!filePath) return { ok: false, error: "invalid session id", sessionId: "", filePath: "" };
28
+ const stored = toDisk(payload);
29
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
30
+ prepareSave(workspaceRoot);
31
+ temporary = `${filePath}.${process.pid}-${randomUUID()}.tmp`;
32
+ fs.writeFileSync(temporary, `${JSON.stringify(stored, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
33
+ fs.renameSync(temporary, filePath);
34
+ return { ok: true, error: "", sessionId: payload.sessionId, filePath, snapshot: payload };
35
+ } catch (error) {
36
+ return { ok: false, error: error.message || "failed to save session", sessionId: payload && payload.sessionId || "", filePath };
37
+ } finally {
38
+ if (temporary && fs.existsSync(temporary)) fs.rmSync(temporary, { force: true });
39
+ }
40
+ },
41
+ load(root = process.cwd(), id = "") {
42
+ const workspaceRoot = path.resolve(root || process.cwd());
43
+ const sessionId = normalizeId(id);
44
+ const filePath = getFilePath(workspaceRoot, sessionId);
45
+ if (!sessionId) return { ok: false, error: "invalid session id", sessionId: "", snapshot: null, filePath: "" };
46
+ if (!fs.existsSync(filePath)) return { ok: false, error: `session not found: ${sessionId}`, sessionId, snapshot: null, filePath };
47
+ try {
48
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
49
+ return { ok: true, error: "", sessionId, filePath, snapshot: decode(parsed, { workspaceRoot, sessionId }) };
50
+ } catch (error) {
51
+ return { ok: false, error: error.message || "failed to load session", sessionId, snapshot: null, filePath };
52
+ }
53
+ },
54
+ });
55
+ }
56
+
57
+ module.exports = { createSessionStore };