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.
Files changed (266) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +238 -21
  3. package/README.zh-CN.md +165 -20
  4. package/SKILLS/ufoo/SKILL.md +40 -4
  5. package/SKILLS/ufoo-bus/SKILL.md +46 -3
  6. package/bin/uclaude.js +4 -0
  7. package/bin/ucodex.js +4 -0
  8. package/bin/ufoo.js +6 -4
  9. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  10. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  11. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  12. package/dist/tui/linux-x64/ufoo-tui +0 -0
  13. package/package.json +14 -7
  14. package/scripts/postinstall-skills.js +53 -0
  15. package/scripts/postinstall.js +11 -16
  16. package/scripts/smoke-native-messages.js +214 -0
  17. package/src/agents/activity/activityDetector.js +1 -1
  18. package/src/agents/activity/activityStateWriter.js +37 -38
  19. package/src/agents/capabilities/agentManagement/index.js +4 -0
  20. package/src/agents/capabilities/agentManagement/service.js +140 -0
  21. package/src/agents/capabilities/agentRouting/index.js +4 -0
  22. package/src/agents/capabilities/coding/index.js +32 -0
  23. package/src/agents/capabilities/coordination/index.js +37 -0
  24. package/src/agents/capabilities/globalRouting/index.js +5 -0
  25. package/src/agents/capabilities/groups/index.js +3 -0
  26. package/src/agents/capabilities/index.js +25 -0
  27. package/src/agents/capabilities/planning/index.js +123 -0
  28. package/src/agents/capabilities/planning/main.js +28 -0
  29. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  30. package/src/agents/capabilities/scheduling/index.js +3 -0
  31. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  32. package/src/agents/capabilities/skills/index.js +12 -0
  33. package/src/agents/capabilities/taskExecution/index.js +3 -0
  34. package/src/agents/capabilities/taskReports/index.js +6 -0
  35. package/src/agents/controller/controllerToolExecutor.js +40 -22
  36. package/src/agents/controller/index.js +1 -6
  37. package/src/agents/internal/internalRunner.js +181 -76
  38. package/src/agents/launch/index.js +0 -1
  39. package/src/agents/launch/launcher.js +96 -14
  40. package/src/agents/launch/nativeCapabilities.js +40 -0
  41. package/src/agents/launch/nativeMessages.js +362 -0
  42. package/src/agents/launch/notifier.js +15 -20
  43. package/src/agents/launch/readyDetector.js +28 -14
  44. package/src/agents/profiles/coding.js +6 -0
  45. package/src/agents/profiles/globalRouter.js +2 -0
  46. package/src/agents/profiles/main.js +5 -0
  47. package/src/agents/prompts/cooperation.js +14 -0
  48. package/src/agents/prompts/defaultBootstrap.js +1 -1
  49. package/src/agents/prompts/groupBootstrap.js +32 -6
  50. package/src/agents/prompts/mainAgent.js +48 -0
  51. package/src/agents/prompts/native/system.js +4 -1
  52. package/src/agents/prompts/native/tasks.js +2 -2
  53. package/src/agents/prompts/native/ufoo.js +14 -3
  54. package/src/agents/prompts/promptProfiles.js +2 -0
  55. package/src/agents/prompts/reporting.js +16 -0
  56. package/src/agents/providers/claudeEventTranslator.js +9 -1
  57. package/src/agents/providers/claudeThreadProvider.js +47 -4
  58. package/src/agents/providers/clientIdentity.js +75 -0
  59. package/src/agents/providers/codexEventTranslator.js +68 -7
  60. package/src/agents/providers/codexThreadProvider.js +18 -8
  61. package/src/agents/providers/credentials/claude.js +10 -3
  62. package/src/agents/providers/credentials/index.js +2 -0
  63. package/src/agents/providers/directAuthStatus.js +1 -1
  64. package/src/agents/providers/index.js +1 -1
  65. package/src/agents/providers/modelSettings.js +34 -0
  66. package/src/agents/providers/modelsCatalog.js +379 -0
  67. package/src/agents/providers/nativeTransport.js +1146 -0
  68. package/src/agents/providers/runtimeConfig.js +188 -0
  69. package/src/agents/providers/thinkingLevels.js +106 -0
  70. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  71. package/src/agents/providers/transports/index.js +10 -0
  72. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  73. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  74. package/src/agents/providers/transports/responsesProtocol.js +504 -0
  75. package/src/agents/providers/transports/systemBlocks.js +16 -0
  76. package/src/agents/providers/transports/transportContract.js +50 -0
  77. package/src/agents/providers/transports/visionBlocks.js +151 -0
  78. package/src/agents/providers/upstreamRuntime.js +135 -0
  79. package/src/agents/runtime/composeCapabilities.js +89 -0
  80. package/src/agents/runtime/context/checkpointStore.js +38 -0
  81. package/src/agents/runtime/context/commandStore.js +43 -0
  82. package/src/agents/runtime/context/compaction.js +151 -0
  83. package/src/agents/runtime/context/contextBudget.js +93 -0
  84. package/src/agents/runtime/context/contextWindow.js +119 -0
  85. package/src/agents/runtime/context/fileLock.js +36 -0
  86. package/src/agents/runtime/context/replayHistory.js +28 -0
  87. package/src/agents/runtime/context/runtimeStore.js +127 -0
  88. package/src/agents/runtime/context/sessionJournal.js +360 -0
  89. package/src/agents/runtime/context/sessionStore.js +57 -0
  90. package/src/agents/runtime/core/agentLoop.js +351 -0
  91. package/src/agents/runtime/core/executionBudget.js +36 -0
  92. package/src/agents/runtime/core/stableJson.js +29 -0
  93. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  94. package/src/agents/runtime/createAgentRuntime.js +259 -0
  95. package/src/agents/runtime/index.js +14 -0
  96. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  97. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  98. package/src/agents/runtime/protocol/materialize.js +107 -0
  99. package/src/agents/runtime/protocol/runObservation.js +24 -0
  100. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  101. package/src/agents/runtime/protocol/traceContext.js +9 -0
  102. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  103. package/src/agents/runtime/tasks/scheduler.js +73 -0
  104. package/src/agents/runtime/tools/registry.js +57 -0
  105. package/src/app/chat/ChatController.js +29 -45
  106. package/src/app/chat/agentDirectory.js +9 -18
  107. package/src/app/chat/bootstrap.js +1 -2
  108. package/src/app/chat/commandExecutor.js +111 -313
  109. package/src/app/chat/commands.js +39 -45
  110. package/src/app/chat/daemonConnection.js +58 -5
  111. package/src/app/chat/daemonMessageRouter.js +61 -48
  112. package/src/app/chat/historyStore.js +12 -48
  113. package/src/app/chat/inputSubmitHandler.js +21 -35
  114. package/src/app/chat/internalAgentLogHistory.js +19 -60
  115. package/src/app/chat/launchRequestContext.js +42 -0
  116. package/src/app/chat/multiWindow/paneManager.js +91 -164
  117. package/src/app/chat/streamState.js +3 -7
  118. package/src/app/chat/transport.js +1 -1
  119. package/src/app/cli/busCoreCommands.js +9 -0
  120. package/src/app/cli/features/doctor.js +33 -0
  121. package/src/app/cli/features/init.js +5 -5
  122. package/src/app/cli/features/skills.js +16 -4
  123. package/src/app/cli/metricsCommands.js +68 -0
  124. package/src/app/cli/reportCoreCommands.js +37 -0
  125. package/src/app/cli/run.js +82 -42
  126. package/src/app/cli/traceCommands.js +36 -0
  127. package/src/code/agent.js +34 -17
  128. package/src/code/busConsumer.js +1 -3
  129. package/src/code/commands.js +1 -1
  130. package/src/code/context/artifacts.js +12 -11
  131. package/src/code/context/assembler.js +9 -9
  132. package/src/code/context/promptLayers.js +1 -13
  133. package/src/code/context/stableJson.js +2 -27
  134. package/src/code/context/stateCommit.js +2 -1
  135. package/src/code/contextWindow.js +2 -117
  136. package/src/code/conversation/sessionJournal.js +3 -349
  137. package/src/code/internalThread.js +107 -0
  138. package/src/code/launcher/ucode.js +1 -1
  139. package/src/code/launcher/ucodeBootstrap.js +1 -1
  140. package/src/code/modelCommand.js +11 -35
  141. package/src/code/nativeRunner.js +104 -2697
  142. package/src/code/protocol/faultHarness.js +2 -88
  143. package/src/code/protocol/materialize.js +2 -105
  144. package/src/code/protocol/toolCallLedger.js +5 -215
  145. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  146. package/src/code/providers/modelsCatalog.js +1 -317
  147. package/src/code/providers/openaiChatTransport.js +2 -114
  148. package/src/code/providers/openaiResponsesTransport.js +2 -117
  149. package/src/code/providers/responsesProtocol.js +2 -497
  150. package/src/code/providers/transportContract.js +2 -48
  151. package/src/code/providers/visionBlocks.js +2 -149
  152. package/src/code/repl.js +2 -11
  153. package/src/code/sessionStore.js +27 -99
  154. package/src/code/taskDecomposer.js +18 -0
  155. package/src/code/thinkingLevels.js +1 -130
  156. package/src/code/toolBudget.js +1 -17
  157. package/src/code/toolLoopGuard.js +3 -49
  158. package/src/code/tools/artifactRead.js +1 -1
  159. package/src/code/tools/executor.js +373 -0
  160. package/src/code/tools/specs.js +312 -0
  161. package/src/config.js +95 -131
  162. package/src/coordination/bus/deliveryQueue.js +16 -2
  163. package/src/coordination/bus/index.js +14 -9
  164. package/src/coordination/bus/inject.js +15 -7
  165. package/src/coordination/bus/message.js +15 -1
  166. package/src/coordination/bus/nativeReceipts.js +100 -0
  167. package/src/coordination/bus/nickname.js +1 -1
  168. package/src/coordination/bus/queue.js +1 -3
  169. package/src/coordination/bus/subscriber.js +3 -2
  170. package/src/coordination/bus/utils.js +8 -4
  171. package/src/coordination/history/agentPerformance.js +279 -0
  172. package/src/coordination/history/agentSurface.js +142 -0
  173. package/src/coordination/history/agentTrace.js +249 -0
  174. package/src/coordination/memory/index.js +5 -21
  175. package/src/coordination/report/store.js +103 -83
  176. package/src/coordination/state/agentsStore.js +57 -3
  177. package/src/coordination/state/fileLock.js +2 -0
  178. package/src/coordination/state/workspaceAccess.js +36 -0
  179. package/src/orchestration/controller/index.js +1 -8
  180. package/src/orchestration/controller/launchRouting.js +1 -1
  181. package/src/orchestration/solo/commands.js +3 -1
  182. package/src/runtime/contracts/agentMode.js +26 -0
  183. package/src/runtime/contracts/eventContract.js +3 -0
  184. package/src/runtime/contracts/uiProtocol.js +20 -17
  185. package/src/runtime/daemon/agentHost.js +407 -0
  186. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  187. package/src/runtime/daemon/busBridge.js +396 -0
  188. package/src/runtime/daemon/claudeChannel.js +159 -0
  189. package/src/runtime/daemon/controlPlaneService.js +28 -18
  190. package/src/runtime/daemon/cronOps.js +25 -17
  191. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  192. package/src/runtime/daemon/globalDaemon.js +28 -1
  193. package/src/runtime/daemon/groupOrchestrator.js +21 -5
  194. package/src/runtime/daemon/groupStatus.js +20 -0
  195. package/src/runtime/daemon/index.js +120 -375
  196. package/src/runtime/daemon/ipcServer.js +32 -10
  197. package/src/runtime/daemon/mcpConfigure.js +113 -20
  198. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  199. package/src/runtime/daemon/mcpServer.js +8 -5
  200. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  201. package/src/runtime/daemon/nicknameScope.js +1 -1
  202. package/src/runtime/daemon/ops.js +68 -40
  203. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  204. package/src/runtime/daemon/promptRequest.js +92 -570
  205. package/src/runtime/daemon/providerSessions.js +67 -33
  206. package/src/runtime/daemon/reportControlBus.js +59 -25
  207. package/src/runtime/daemon/status.js +9 -6
  208. package/src/runtime/privacy/redactor.js +2 -2
  209. package/src/runtime/projects/identity.js +2 -1
  210. package/src/runtime/projects/registry.js +98 -38
  211. package/src/tools/controllerSchemas.js +28 -0
  212. package/src/tools/handlers/dispatchMessage.js +5 -2
  213. package/src/tools/handlers/listAgents.js +3 -1
  214. package/src/tools/handlers/readBusSummary.js +3 -1
  215. package/src/tools/handlers/readProjectRegistry.js +29 -2
  216. package/src/tools/handlers/routeAgent.js +35 -0
  217. package/src/tools/handlers/tier2.js +4 -2
  218. package/src/tools/index.js +1 -0
  219. package/src/tools/registry.js +6 -0
  220. package/src/tools/schemaFixtures.js +42 -5
  221. package/src/tools/tier0/readAgentMetrics.js +14 -0
  222. package/src/tools/tier0/readAgentTrace.js +12 -0
  223. package/src/tools/tier1/routeAgent.js +2 -2
  224. package/src/tools/tier2/runtimeCoordination.js +38 -0
  225. package/src/tools/types.js +2 -0
  226. package/src/ui/agentPresentation.js +109 -0
  227. package/src/ui/agentSettingsController.js +107 -0
  228. package/src/ui/agentSurface.js +270 -0
  229. package/src/ui/dashboardBridge.js +1 -1
  230. package/src/ui/format/banner.js +9 -15
  231. package/src/ui/format/index.js +14 -10
  232. package/src/ui/format/loopSummary.js +50 -0
  233. package/src/ui/format/markdownRenderer.js +3 -4
  234. package/src/ui/format/startupBanner.js +50 -0
  235. package/src/ui/multiPaneBusMirror.js +29 -3
  236. package/src/ui/rustChatHost.js +316 -599
  237. package/src/ui/rustMultiSession.js +288 -73
  238. package/src/ui/rustUcodeHost.js +21 -88
  239. package/src/ui/settingsBridge.js +34 -14
  240. package/src/ui/toolMergeBridge.js +0 -4
  241. package/src/ui/uiHostServer.js +5 -8
  242. package/src/agents/controller/loopObservability.js +0 -200
  243. package/src/agents/controller/loopRuntime.js +0 -472
  244. package/src/agents/controller/ufooAgent.js +0 -829
  245. package/src/agents/launch/ptyRunner.js +0 -1135
  246. package/src/agents/providers/upstreamTransport.js +0 -689
  247. package/src/app/chat/agentBar.js +0 -135
  248. package/src/app/chat/agentEnter.js +0 -70
  249. package/src/app/chat/agentSockets.js +0 -225
  250. package/src/app/chat/dashboardView.js +0 -405
  251. package/src/app/chat/multiWindow/index.js +0 -310
  252. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  253. package/src/app/chat/multiWindow/renderer.js +0 -420
  254. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  255. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  256. package/src/app/chat/rawKeyMap.js +0 -42
  257. package/src/app/chat/settingsController.js +0 -111
  258. package/src/orchestration/controller/flags.js +0 -167
  259. package/src/orchestration/controller/gateRouter.js +0 -211
  260. package/src/orchestration/controller/routerFastPath.js +0 -22
  261. package/src/orchestration/controller/routerFinalize.js +0 -222
  262. package/src/orchestration/controller/shadowGuard.js +0 -280
  263. package/src/runtime/daemon/promptLoop.js +0 -136
  264. package/src/runtime/privacy/shadowDiff.js +0 -174
  265. package/src/ui/multiWindowHandoff.js +0 -232
  266. package/src/ui/ptyHandoff.js +0 -23
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+
3
+ const { createHash } = require("crypto");
4
+ const { stripVisionBase64, retireMessageImages } = require("../../providers/transports/visionBlocks");
5
+ const { stableStringify } = require("../core/stableJson");
6
+
7
+ // Conservative local estimate; provider usage calibrates it in the loop.
8
+ function estimateTextTokens(text = "") {
9
+ let tokens = 0;
10
+ for (const character of String(text)) {
11
+ const code = character.codePointAt(0);
12
+ tokens += code >= 0x2e80 ? 1.5 : 0.35;
13
+ }
14
+ return Math.ceil(tokens);
15
+ }
16
+
17
+ function summaryMessage(message) {
18
+ const retired = [stripVisionBase64(message)];
19
+ retireMessageImages(retired);
20
+ const value = retired[0];
21
+ return { role: value.role, content: value.content, tool_calls: value.tool_calls,
22
+ tool_call_id: value.tool_call_id };
23
+ }
24
+
25
+ function imageCount(value) {
26
+ if (Array.isArray(value)) return value.reduce((sum, item) => sum + imageCount(item), 0);
27
+ if (!value || typeof value !== "object") return 0;
28
+ if (["image", "image_url", "input_image"].includes(value.type)) return 1;
29
+ return imageCount(value.content);
30
+ }
31
+
32
+ function estimateMessagesTokens(messages = []) {
33
+ // Encoded image bytes are neither text tokens nor summary input. Reserve a
34
+ // conservative visual allowance while retaining live images for the model.
35
+ return messages.reduce((sum, message) => sum + 12 + imageCount(message) * 2000
36
+ + estimateTextTokens(JSON.stringify(summaryMessage(message))), 0);
37
+ }
38
+
39
+ function historyDigest(messages = []) {
40
+ // Artifact previews can change after restoration; their immutable artifact
41
+ // identity stays stable. Non-artifact results still hash their full text.
42
+ const identity = messages.map(message => {
43
+ const value = summaryMessage(message);
44
+ if (value.role === "tool" && value.tool_call_id && typeof value.content === "string") {
45
+ try {
46
+ const artifactId = JSON.parse(value.content)?.artifactId;
47
+ if (artifactId) value.content = { artifactId };
48
+ } catch { /* Plain results use their original content. */ }
49
+ }
50
+ return value;
51
+ });
52
+ return createHash("sha256").update(stableStringify(identity)).digest("hex");
53
+ }
54
+
55
+ function toolCalls(message = {}) {
56
+ return Array.isArray(message.tool_calls) ? message.tool_calls.map(call => call.id)
57
+ : Array.isArray(message.content) ? message.content.filter(block => block.type === "tool_use").map(block => block.id) : [];
58
+ }
59
+
60
+ function toolResults(message = {}) {
61
+ if (message.role === "tool") return [message.tool_call_id];
62
+ return Array.isArray(message.content) ? message.content.filter(block => block.type === "tool_result").map(block => block.tool_use_id) : [];
63
+ }
64
+
65
+ // A multi-call assistant turn and all its results are one indivisible unit.
66
+ function historyUnits(messages = []) {
67
+ const units = [];
68
+ for (let start = 0; start < messages.length;) {
69
+ let end = start + 1;
70
+ const ids = toolCalls(messages[start]);
71
+ let complete = toolResults(messages[start]).length === 0;
72
+ if (ids.length) {
73
+ const pending = new Set(ids);
74
+ while (end < messages.length && toolResults(messages[end]).length) {
75
+ for (const id of toolResults(messages[end])) pending.delete(id);
76
+ end++;
77
+ }
78
+ complete = pending.size === 0;
79
+ }
80
+ units.push({ start, end, complete, messages: messages.slice(start, end) });
81
+ start = end;
82
+ }
83
+ return units;
84
+ }
85
+
86
+ function userInstruction(message = {}) {
87
+ if (message.role !== "user" || toolResults(message).length) return "";
88
+ if (typeof message.content === "string") return message.content;
89
+ if (!Array.isArray(message.content)) return "";
90
+ return message.content.filter(block => block.type === "text").map(block => block.text || "").join("\n");
91
+ }
92
+
93
+ module.exports = { estimateTextTokens, estimateMessagesTokens, summaryMessage, historyDigest, historyUnits, userInstruction };
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Context-window helpers for the ucode TUI meter (used / limit in K).
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
+ };
@@ -0,0 +1,36 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const lockfile = require("proper-lockfile");
4
+
5
+ const held = new Set();
6
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
7
+
8
+ // Keep the existing synchronous store APIs. Critical sections may only contain
9
+ // synchronous local file work; never hold these locks across an await or RPC.
10
+ function withFileLock(file, callback, options = {}) {
11
+ const key = path.resolve(file);
12
+ const lockKey = options.lockfilePath ? path.resolve(options.lockfilePath) : key;
13
+ if (held.has(lockKey)) return callback();
14
+ fs.mkdirSync(path.dirname(key), { recursive: true });
15
+ const deadline = Date.now() + 11000;
16
+ let release;
17
+ while (!release) {
18
+ try {
19
+ release = lockfile.lockSync(key, { realpath: false, stale: 10000, ...options });
20
+ } catch (error) {
21
+ if (error.code !== "ELOCKED" || Date.now() >= deadline) throw error;
22
+ Atomics.wait(sleeper, 0, 0, 5);
23
+ }
24
+ }
25
+ held.add(lockKey);
26
+ try {
27
+ const result = callback();
28
+ if (result && typeof result.then === "function") throw new Error("File transactions must be synchronous");
29
+ return result;
30
+ } finally {
31
+ held.delete(lockKey);
32
+ release();
33
+ }
34
+ }
35
+
36
+ module.exports = { withFileLock };
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+
3
+ /** Derive full conversation inputs from accepted requests and terminal events. */
4
+ function replayHistory(events = [], excludeTask = "") {
5
+ const requests = new Map();
6
+ const terminal = new Map();
7
+ for (const event of events) {
8
+ if (event.type === "request.accepted") requests.set(event.taskRunId, event.request);
9
+ if (["task.completed", "task.failed", "task.cancelled", "task.interrupted"].includes(event.type)) terminal.set(event.taskRunId, event);
10
+ }
11
+ const history = [];
12
+ for (const [id, request] of requests) {
13
+ const event = terminal.get(id);
14
+ if (id === excludeTask || !event) continue;
15
+ const result = event.result;
16
+ if (Array.isArray(result?.messages) && Number.isInteger(result.historyOffset)) {
17
+ history.push(...result.messages.filter(message => message.role !== "system").slice(result.historyOffset));
18
+ } else {
19
+ history.push({ role: "user", content: request.text });
20
+ if (Array.isArray(result?.turnItems)) history.push(...result.turnItems);
21
+ else if (result?.text) history.push({ role: "assistant", content: result.text });
22
+ else history.push({ role: "assistant", content: `Previous request ended ${event.type.split(".")[1]}: ${event.error || "no verified result"}` });
23
+ }
24
+ }
25
+ return history;
26
+ }
27
+
28
+ module.exports = { replayHistory };
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { randomUUID } = require("crypto");
6
+ const { withFileLock } = require("./fileLock");
7
+
8
+ const copy = (value) => JSON.parse(JSON.stringify(value));
9
+ const validId = (value) => /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(String(value || ""));
10
+
11
+ function trimTornAppend(fd) {
12
+ let end = fs.fstatSync(fd).size;
13
+ if (!end) return;
14
+ const last = Buffer.alloc(1);
15
+ fs.readSync(fd, last, 0, 1, end - 1);
16
+ if (last[0] === 10) return;
17
+ while (end > 0) {
18
+ const start = Math.max(0, end - 4096);
19
+ const tail = Buffer.alloc(end - start);
20
+ fs.readSync(fd, tail, 0, tail.length, start);
21
+ const newline = tail.lastIndexOf(10);
22
+ if (newline >= 0) { fs.ftruncateSync(fd, start + newline + 1); return; }
23
+ end = start;
24
+ }
25
+ fs.ftruncateSync(fd, 0);
26
+ }
27
+
28
+ function projectEvent(state, event) {
29
+ state.sequence = event.sequence;
30
+ if (event.type === "runtime.opened") state.owner = event.owner;
31
+ if (event.type === "runtime.opened" && !state.profile) state.profile = event.owner.profile;
32
+ if (event.type === "runtime.opened" && !state.capabilities) state.capabilities = event.owner.capabilities;
33
+ if (event.type === "runtime.closed") state.owner = null;
34
+ if (event.type === "runtime.binding") state.binding = event.binding;
35
+ if (event.type === "context.checkpoint") state.contextCheckpoint = event.checkpoint;
36
+ if (event.type === "capability.state_committed") state.capabilityState[event.capabilityId] = { version: event.version, value: event.value };
37
+ if (event.type === "command.started") state.commands[event.commandId] = { ...event, status: "uncertain" };
38
+ if (event.type === "command.resolved") Object.assign(state.commands[event.commandId], { status: "resolved", result: event.result });
39
+ if (event.type === "request.accepted") {
40
+ state.requests[event.request.requestId] = event.taskRunId;
41
+ state.tasks[event.taskRunId] = { taskRunId: event.taskRunId, request: event.request, status: "queued", effects: {}, sequence: event.sequence };
42
+ }
43
+ const task = state.tasks[event.taskRunId];
44
+ if (!task) return;
45
+ if (event.type === "task.started") Object.assign(task, { status: "running", attemptId: event.attemptId });
46
+ if (event.type === "tool.started") task.effects[event.toolCallId] = { toolName: event.toolName, status: "uncertain" };
47
+ if (event.type === "tool.completed") delete task.effects[event.toolCallId];
48
+ if (event.type === "task.paused") Object.assign(task, { status: "waiting_user", result: event.result, interactionId: event.result.interactionId });
49
+ if (event.type === "interaction.answered") {
50
+ const callId = task.result?.executionState?.pendingUserInteraction?.resume?.toolCallId;
51
+ if (callId) delete task.effects[callId];
52
+ Object.assign(task, { status: "queued", answer: event.answer, answeredInteractionId: event.interactionId });
53
+ }
54
+ if (["task.completed", "task.failed", "task.cancelled", "task.interrupted"].includes(event.type)) {
55
+ const result = event.result ? { text: event.result.text, ...(typeof event.result.finalText === "string" ? { finalText: event.result.finalText } : {}), usage: event.result.usage, toolCallsExecuted: event.result.toolCallsExecuted,
56
+ streamed: event.result.streamed } : null;
57
+ // Full terminal transcripts remain in the journal; projections carry only summaries.
58
+ Object.assign(task, { status: event.type.split(".")[1], result, error: event.error || "", interactionId: "" });
59
+ }
60
+ task.sequence = event.sequence;
61
+ }
62
+
63
+ /** Append-only truth; snapshot is a replaceable projection. No await under the lock. */
64
+ function createRuntimeStore({ workspaceRoot, namespace = "runtime", sessionId, redact = (value) => value } = {}) {
65
+ if (!validId(namespace) || !validId(sessionId)) throw new Error("invalid runtime store identity");
66
+ const directory = path.join(path.resolve(workspaceRoot), ".ufoo", "agent", namespace, "runtimes", sessionId);
67
+ const journal = path.join(directory, "events.jsonl");
68
+ const projection = path.join(directory, "snapshot.json");
69
+ let cache = null;
70
+ function journalStamp() {
71
+ try { const stat = fs.statSync(journal); return `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`; }
72
+ catch (error) { if (error.code === "ENOENT") return "missing"; throw error; }
73
+ }
74
+ function readEvents() {
75
+ const stamp = journalStamp();
76
+ if (cache && cache.stamp === stamp) return cache.events;
77
+ if (stamp === "missing") { cache = { stamp, events: [], state: null }; return cache.events; }
78
+ const text = fs.readFileSync(journal, "utf8");
79
+ const lines = text.split("\n");
80
+ // A torn final append is never interpreted as a committed event.
81
+ lines.pop();
82
+ const events = lines.filter(Boolean).map((line, index) => {
83
+ const event = JSON.parse(line);
84
+ if (event.sequence !== index + 1) throw new Error("runtime journal sequence mismatch");
85
+ return event;
86
+ });
87
+ cache = { stamp, events, state: null }; return events;
88
+ }
89
+ function replay(events) {
90
+ if (cache && cache.events === events && cache.state) return copy(cache.state);
91
+ const state = { version: 1, sessionId, namespace, sequence: 0, owner: null, profile: "", requests: {}, tasks: {}, commands: {}, capabilityState: {} };
92
+ events.forEach((event) => projectEvent(state, event));
93
+ if (cache && cache.events === events) cache.state = copy(state);
94
+ return state;
95
+ }
96
+ function transaction(mutator) {
97
+ return withFileLock(journal, () => {
98
+ const events = readEvents();
99
+ const state = replay(events);
100
+ const additions = mutator(copy(state)) || [];
101
+ if (!Array.isArray(additions)) throw new Error("runtime transaction must return events");
102
+ if (!additions.length) return state;
103
+ fs.mkdirSync(directory, { recursive: true });
104
+ const committed = additions.map((event, index) => ({ ...redact(event), sequence: state.sequence + index + 1, eventId: randomUUID(), time: new Date().toISOString() }));
105
+ const fd = fs.openSync(journal, "a+", 0o600);
106
+ try { trimTornAppend(fd); fs.writeSync(fd, committed.map((event) => JSON.stringify(event)).join("\n") + "\n"); fs.fsyncSync(fd); }
107
+ finally { fs.closeSync(fd); }
108
+ committed.forEach((event) => projectEvent(state, event));
109
+ events.push(...committed);
110
+ cache = { stamp: journalStamp(), events, state: copy(state) };
111
+ const temporary = `${projection}.${randomUUID()}.tmp`;
112
+ try {
113
+ fs.writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 });
114
+ fs.renameSync(temporary, projection);
115
+ } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
116
+ return state;
117
+ });
118
+ }
119
+ return Object.freeze({ directory, journal,
120
+ read: () => replay(readEvents()),
121
+ events: ({ after = 0 } = {}) => copy(readEvents().filter((event) => event.sequence > after)),
122
+ transaction,
123
+ append: (event) => transaction(() => [event]),
124
+ });
125
+ }
126
+
127
+ module.exports = { createRuntimeStore, projectEvent };