u-foo 3.1.7 → 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 -2667
  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,151 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Helpers for expanding read_image tool results into provider vision blocks.
5
+ */
6
+
7
+ function extractVisionPayload(toolResult = null) {
8
+ if (!toolResult || typeof toolResult !== "object") return null;
9
+ const base64 = String(toolResult.base64 || "").trim();
10
+ const mediaType = String(toolResult.mediaType || "").trim().toLowerCase();
11
+ if (!base64 || !mediaType.startsWith("image/")) return null;
12
+ if (toolResult.ok === false) return null;
13
+ return {
14
+ path: String(toolResult.path || "").trim(),
15
+ mediaType,
16
+ bytes: Number.isFinite(toolResult.bytes) ? toolResult.bytes : null,
17
+ base64,
18
+ artifactId: String(toolResult.artifactId || "").trim(),
19
+ };
20
+ }
21
+
22
+ function isVisionToolResult(toolResult = null) {
23
+ return Boolean(extractVisionPayload(toolResult));
24
+ }
25
+
26
+ function stripVisionBase64(value) {
27
+ if (Array.isArray(value)) {
28
+ return value.map((item) => stripVisionBase64(item));
29
+ }
30
+ if (!value || typeof value !== "object") return value;
31
+ const out = {};
32
+ for (const [key, entry] of Object.entries(value)) {
33
+ if (key === "base64") continue;
34
+ out[key] = stripVisionBase64(entry);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ function visionSummaryText(vision = null, toolResult = null) {
40
+ const pathText = (vision && vision.path) || (toolResult && toolResult.path) || "image";
41
+ const mediaType = (vision && vision.mediaType) || (toolResult && toolResult.mediaType) || "image/*";
42
+ const bytes = (vision && vision.bytes) != null
43
+ ? vision.bytes
44
+ : (toolResult && toolResult.bytes);
45
+ const parts = [
46
+ `Image loaded for vision: ${pathText}`,
47
+ `mediaType=${mediaType}`,
48
+ ];
49
+ if (Number.isFinite(bytes)) parts.push(`bytes=${bytes}`);
50
+ if (vision && vision.artifactId) parts.push(`artifactId=${vision.artifactId}`);
51
+ parts.push("Visual content is attached for this model call only; call read_image again later if needed.");
52
+ return parts.join(" | ");
53
+ }
54
+
55
+ function toAnthropicImageBlock(vision = null) {
56
+ if (!vision) return null;
57
+ return {
58
+ type: "image",
59
+ source: {
60
+ type: "base64",
61
+ media_type: vision.mediaType,
62
+ data: vision.base64,
63
+ },
64
+ };
65
+ }
66
+
67
+ function toOpenAiImagePart(vision = null) {
68
+ if (!vision) return null;
69
+ return {
70
+ type: "image_url",
71
+ image_url: {
72
+ url: `data:${vision.mediaType};base64,${vision.base64}`,
73
+ },
74
+ };
75
+ }
76
+
77
+ function degradeVisionContent(content) {
78
+ if (typeof content === "string") return content;
79
+ if (!Array.isArray(content)) return content;
80
+ const texts = [];
81
+ for (const block of content) {
82
+ if (!block || typeof block !== "object") continue;
83
+ const type = String(block.type || "").trim().toLowerCase();
84
+ if (type === "text" && block.text) {
85
+ texts.push(String(block.text));
86
+ continue;
87
+ }
88
+ if (type === "image" || type === "image_url") {
89
+ const pathHint = block.path
90
+ || (block.source && block.source.path)
91
+ || "";
92
+ texts.push(pathHint ? `[image: ${pathHint}]` : "[image]");
93
+ continue;
94
+ }
95
+ if (type === "tool_result" && Array.isArray(block.content)) {
96
+ texts.push(degradeVisionContent(block.content));
97
+ }
98
+ }
99
+ return texts.filter(Boolean).join("\n") || "[multimodal content]";
100
+ }
101
+
102
+ // Retire only visual blocks after a successful model call. In particular,
103
+ // preserve Anthropic tool_result envelopes and their tool_use_id linkage.
104
+ function retireVisionContent(content) {
105
+ if (!Array.isArray(content)) return content;
106
+ let changed = false;
107
+ const retired = content.map((block) => {
108
+ if (!block || typeof block !== "object") return block;
109
+ const type = String(block.type || "").toLowerCase();
110
+ if (type === "image" || type === "image_url" || type === "input_image") {
111
+ changed = true;
112
+ const pathHint = block.path || (block.source && block.source.path) || "";
113
+ return {
114
+ type: "text",
115
+ text: pathHint
116
+ ? `[image already viewed: ${pathHint}; use read_image to view again]`
117
+ : "[image already viewed; use read_image with the recorded path to view again]",
118
+ };
119
+ }
120
+ if (Array.isArray(block.content)) {
121
+ const nested = retireVisionContent(block.content);
122
+ if (nested !== block.content) {
123
+ changed = true;
124
+ return { ...block, content: nested };
125
+ }
126
+ }
127
+ return block;
128
+ });
129
+ return changed ? retired : content;
130
+ }
131
+
132
+ function retireMessageImages(messages = []) {
133
+ for (let i = 0; i < messages.length; i += 1) {
134
+ const message = messages[i];
135
+ if (message && Array.isArray(message.content)) {
136
+ const content = retireVisionContent(message.content);
137
+ if (content !== message.content) messages[i] = { ...message, content };
138
+ }
139
+ }
140
+ }
141
+
142
+ module.exports = {
143
+ extractVisionPayload,
144
+ isVisionToolResult,
145
+ stripVisionBase64,
146
+ visionSummaryText,
147
+ toAnthropicImageBlock,
148
+ toOpenAiImagePart,
149
+ degradeVisionContent,
150
+ retireMessageImages,
151
+ };
@@ -12,14 +12,15 @@ const {
12
12
  resolveRuntimeConfig,
13
13
  resolveCompletionUrl,
14
14
  resolveAnthropicMessagesUrl,
15
- } = require("../../code/nativeRunner");
15
+ } = require("./runtimeConfig");
16
16
  const {
17
17
  buildResponsesPayload,
18
18
  parseResponsesEvents,
19
19
  resolveResponsesUrl,
20
- } = require("../../code/providers/responsesProtocol");
20
+ } = require("./transports/responsesProtocol");
21
21
  const { resolveClaudeUpstreamCredentials } = require("./credentials/claude");
22
22
  const { resolveCodexUpstreamCredentials } = require("./credentials/codex");
23
+ const { resolveKimiUpstreamCredentials } = require("./credentials/kimi");
23
24
  const { buildUpstreamAuthFromCredential } = require("./credentials");
24
25
 
25
26
  function normalizeProvider(value = "") {
@@ -29,6 +30,7 @@ function normalizeProvider(value = "") {
29
30
  if (text === "claude-cli" || text === "claude-code" || text === "claude" || text === "anthropic") return "claude";
30
31
  if (text === "grok" || text === "grok-cli" || text === "grok-build" || text === "grok-shell" || text === "grok-api" || text === "xai") return "grok";
31
32
  if (text === "ucode" || text === "ufoo" || text === "ufoo-code") return "ucode";
33
+ if (text === "kimi-cli" || text === "kimi-code" || text === "moonshot") return "kimi";
32
34
  return text;
33
35
  }
34
36
 
@@ -346,7 +348,7 @@ async function resolveUpstreamRuntime({
346
348
  refreshWindowMs: Number(config.claudeOauthRefreshWindowSec || 300) * 1000,
347
349
  env,
348
350
  });
349
- const baseUrl = String(env.ANTHROPIC_BASE_URL || "").trim() || "https://api.anthropic.com/v1";
351
+ const baseUrl = String(env.ANTHROPIC_BASE_URL || credential.metadata?.baseUrl || "").trim() || "https://api.anthropic.com/v1";
350
352
  const resolvedModel = String(
351
353
  model
352
354
  || resolveConfiguredModelForProvider(config, "claude")
@@ -368,6 +370,7 @@ async function resolveUpstreamRuntime({
368
370
  workspaceRoot: projectRoot,
369
371
  provider: "grok-build",
370
372
  model: model || resolveConfiguredModelForProvider(config, "grok-build") || defaultRouterModelForProvider("grok-build"),
373
+ useCodingConfig: false,
371
374
  });
372
375
  const auth = runtime.apiKey ? { apiKey: String(runtime.apiKey).trim() } : { headers: {} };
373
376
  return {
@@ -385,14 +388,20 @@ async function resolveUpstreamRuntime({
385
388
  workspaceRoot: projectRoot,
386
389
  provider: normalizedProvider === "ucode" ? "" : normalizedProvider,
387
390
  model: model || resolveConfiguredModelForProvider(config, normalizedProvider) || defaultAgentModelForProvider(config.agentProvider),
391
+ useCodingConfig: normalizedProvider === "ucode",
388
392
  });
393
+ let credential = null;
394
+ if (runtime.provider === "kimi" && runtime.apiKeySource === "kimi-credential") {
395
+ credential = await resolveKimiUpstreamCredentials({ env, fetchImpl });
396
+ runtime.apiKey = credential.accessToken;
397
+ }
389
398
  const auth = runtime.apiKey ? { apiKey: String(runtime.apiKey || "").trim() } : { headers: {} };
390
399
  return {
391
400
  provider: String(runtime.provider || normalizedProvider || "ucode"),
392
401
  transport: String(runtime.transport || "openai-chat"),
393
402
  model: String(runtime.model || "").trim(),
394
403
  baseUrl: String(runtime.baseUrl || "").trim(),
395
- credential: null,
404
+ credential,
396
405
  auth,
397
406
  credentialSource: runtime.apiKey ? "runtime-api-key" : "",
398
407
  };
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+
3
+ const { createToolRegistry } = require("./tools/registry");
4
+
5
+ /** Explicit, trusted modules only. This composition is not a code sandbox. */
6
+ function composeCapabilities({ capabilities = [], host = {}, profile = {}, providerFeatures = [] } = {}) {
7
+ const byId = new Map();
8
+ for (const capability of capabilities) {
9
+ if (!capability || !/^[a-z][a-z0-9-]{0,63}$/.test(capability.id || "") || !capability.version) throw new Error("capability id/version required");
10
+ if (byId.has(capability.id)) throw new Error(`duplicate capability: ${capability.id}`);
11
+ byId.set(capability.id, capability);
12
+ }
13
+ const selected = profile.capabilities || [...byId.keys()];
14
+ const ordered = [];
15
+ const visiting = new Set();
16
+ const visited = new Set();
17
+ function visit(id) {
18
+ if (visiting.has(id)) throw new Error(`circular capability dependency: ${id}`);
19
+ if (visited.has(id)) return;
20
+ const capability = byId.get(id);
21
+ if (!capability) throw new Error(`missing capability: ${id}`);
22
+ visiting.add(id);
23
+ for (const dependency of capability.requires && capability.requires.capabilities || []) visit(dependency);
24
+ for (const port of capability.requires && capability.requires.ports || []) {
25
+ if (host[port] == null) throw new Error(`capability ${id} requires host port: ${port}`);
26
+ }
27
+ for (const permission of capability.requestedPermissions || []) {
28
+ if (!(host.grantedPermissions || []).includes(permission)) {
29
+ throw new Error(`capability ${id} requires permission: ${permission}`);
30
+ }
31
+ }
32
+ for (const feature of capability.requires && capability.requires.providerFeatures || []) {
33
+ if (!providerFeatures.includes(feature)) throw new Error(`capability ${id} requires provider feature: ${feature}`);
34
+ }
35
+ visiting.delete(id);
36
+ visited.add(id);
37
+ ordered.push(capability);
38
+ }
39
+ selected.forEach(visit);
40
+ const tools = createToolRegistry({
41
+ tools: ordered.flatMap((capability) => capability.tools || []),
42
+ grantedPermissions: host.grantedPermissions || [],
43
+ authorize: host.authorizeTool || null,
44
+ });
45
+ const policies = ordered.map((capability) => capability.policy).filter(Boolean);
46
+ return Object.freeze({
47
+ capabilities: Object.freeze(ordered.slice()),
48
+ tools,
49
+ policies: Object.freeze(policies),
50
+ reduceState(records = {}, event) {
51
+ const updates = [];
52
+ for (const capability of ordered) {
53
+ if (!capability.reducer) continue;
54
+ const previous = Object.prototype.hasOwnProperty.call(records, capability.id) ? records[capability.id] : null;
55
+ const codec = capability.stateCodec;
56
+ if (previous && String(previous.version) !== String(capability.version) && (!codec || !codec.decode)) {
57
+ throw new Error(`unsupported capability state version: ${capability.id}`);
58
+ }
59
+ const value = previous ? codec && codec.decode ? codec.decode(previous.value, previous.version) : previous.value : undefined;
60
+ const next = capability.reducer(value, event);
61
+ if (next && typeof next.then === "function") throw new Error(`capability reducer must be synchronous: ${capability.id}`);
62
+ if (next !== undefined) updates.push({ capabilityId: capability.id, version: capability.version, value: codec && codec.encode ? codec.encode(next) : next });
63
+ }
64
+ return updates;
65
+ },
66
+ async handleEvent(event) {
67
+ const commands = [];
68
+ for (const capability of ordered) {
69
+ if (!capability.handleEvent) continue;
70
+ const proposals = await capability.handleEvent(event);
71
+ if (proposals != null && !Array.isArray(proposals)) throw new Error(`capability event handler must return commands: ${capability.id}`);
72
+ for (const command of proposals || []) commands.push({ ...command, capabilityId: capability.id });
73
+ }
74
+ return commands;
75
+ },
76
+ promptSections: Object.freeze(ordered.flatMap((capability) => capability.promptSections || [])),
77
+ async buildContext(input) {
78
+ const result = [];
79
+ for (const capability of ordered) {
80
+ for (const source of capability.contextSources || []) {
81
+ result.push({ capabilityId: capability.id, value: await source(input, host) });
82
+ }
83
+ }
84
+ return result;
85
+ },
86
+ });
87
+ }
88
+
89
+ module.exports = { composeCapabilities };
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+
3
+ const { createHash } = require("crypto");
4
+ const { stableStringify } = require("../core/stableJson");
5
+
6
+ /** Durable effect receipts. A missing receipt requires reconciliation, never replay. */
7
+ function createCommandStore(store) {
8
+ const inFlight = new Map();
9
+ return Object.freeze({
10
+ execute({ commandId, kind, args }, operation) {
11
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(commandId || "")) throw new Error("safe commandId is required");
12
+ const fingerprint = createHash("sha256").update(stableStringify({ kind, args })).digest("hex");
13
+ const key = `${commandId}:${fingerprint}`;
14
+ if (inFlight.has(key)) return inFlight.get(key);
15
+ let previous = null;
16
+ store.transaction((state) => {
17
+ previous = Object.prototype.hasOwnProperty.call(state.commands, commandId) ? state.commands[commandId] : null;
18
+ if (previous) {
19
+ if (previous.fingerprint !== fingerprint) throw Object.assign(new Error("commandId reused with different content"), { code: "command_conflict" });
20
+ return [];
21
+ }
22
+ return [{ type: "command.started", commandId, kind, fingerprint }];
23
+ });
24
+ if (previous) return Promise.resolve(previous.status === "resolved" ? previous.result
25
+ : { ok: false, code: "uncertain_effect", commandId, error: "Effect has no durable receipt; reconcile before retrying." });
26
+ const pending = Promise.resolve().then(operation).then((result) => {
27
+ store.append({ type: "command.resolved", commandId, result });
28
+ return result;
29
+ }).finally(() => inFlight.delete(key));
30
+ inFlight.set(key, pending);
31
+ return pending;
32
+ },
33
+ resolve(commandId, result) {
34
+ return store.transaction((state) => {
35
+ if (!Object.prototype.hasOwnProperty.call(state.commands, commandId)) throw new Error("command not found");
36
+ if (state.commands[commandId].status === "resolved") throw new Error("command already resolved");
37
+ return [{ type: "command.resolved", commandId, result }];
38
+ });
39
+ },
40
+ });
41
+ }
42
+
43
+ module.exports = { createCommandStore };
@@ -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,126 @@
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 === "capability.state_committed") state.capabilityState[event.capabilityId] = { version: event.version, value: event.value };
36
+ if (event.type === "command.started") state.commands[event.commandId] = { ...event, status: "uncertain" };
37
+ if (event.type === "command.resolved") Object.assign(state.commands[event.commandId], { status: "resolved", result: event.result });
38
+ if (event.type === "request.accepted") {
39
+ state.requests[event.request.requestId] = event.taskRunId;
40
+ state.tasks[event.taskRunId] = { taskRunId: event.taskRunId, request: event.request, status: "queued", effects: {}, sequence: event.sequence };
41
+ }
42
+ const task = state.tasks[event.taskRunId];
43
+ if (!task) return;
44
+ if (event.type === "task.started") Object.assign(task, { status: "running", attemptId: event.attemptId });
45
+ if (event.type === "tool.started") task.effects[event.toolCallId] = { toolName: event.toolName, status: "uncertain" };
46
+ if (event.type === "tool.completed") delete task.effects[event.toolCallId];
47
+ if (event.type === "task.paused") Object.assign(task, { status: "waiting_user", result: event.result, interactionId: event.result.interactionId });
48
+ if (event.type === "interaction.answered") {
49
+ const callId = task.result?.executionState?.pendingUserInteraction?.resume?.toolCallId;
50
+ if (callId) delete task.effects[callId];
51
+ Object.assign(task, { status: "queued", answer: event.answer, answeredInteractionId: event.interactionId });
52
+ }
53
+ if (["task.completed", "task.failed", "task.cancelled", "task.interrupted"].includes(event.type)) {
54
+ const result = event.result ? { text: event.result.text, usage: event.result.usage, toolCallsExecuted: event.result.toolCallsExecuted,
55
+ streamed: event.result.streamed } : null;
56
+ // Full terminal transcripts remain in the journal; projections carry only summaries.
57
+ Object.assign(task, { status: event.type.split(".")[1], result, error: event.error || "", interactionId: "" });
58
+ }
59
+ task.sequence = event.sequence;
60
+ }
61
+
62
+ /** Append-only truth; snapshot is a replaceable projection. No await under the lock. */
63
+ function createRuntimeStore({ workspaceRoot, namespace = "runtime", sessionId, redact = (value) => value } = {}) {
64
+ if (!validId(namespace) || !validId(sessionId)) throw new Error("invalid runtime store identity");
65
+ const directory = path.join(path.resolve(workspaceRoot), ".ufoo", "agent", namespace, "runtimes", sessionId);
66
+ const journal = path.join(directory, "events.jsonl");
67
+ const projection = path.join(directory, "snapshot.json");
68
+ let cache = null;
69
+ function journalStamp() {
70
+ try { const stat = fs.statSync(journal); return `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`; }
71
+ catch (error) { if (error.code === "ENOENT") return "missing"; throw error; }
72
+ }
73
+ function readEvents() {
74
+ const stamp = journalStamp();
75
+ if (cache && cache.stamp === stamp) return cache.events;
76
+ if (stamp === "missing") { cache = { stamp, events: [], state: null }; return cache.events; }
77
+ const text = fs.readFileSync(journal, "utf8");
78
+ const lines = text.split("\n");
79
+ // A torn final append is never interpreted as a committed event.
80
+ lines.pop();
81
+ const events = lines.filter(Boolean).map((line, index) => {
82
+ const event = JSON.parse(line);
83
+ if (event.sequence !== index + 1) throw new Error("runtime journal sequence mismatch");
84
+ return event;
85
+ });
86
+ cache = { stamp, events, state: null }; return events;
87
+ }
88
+ function replay(events) {
89
+ if (cache && cache.events === events && cache.state) return copy(cache.state);
90
+ const state = { version: 1, sessionId, namespace, sequence: 0, owner: null, profile: "", requests: {}, tasks: {}, commands: {}, capabilityState: {} };
91
+ events.forEach((event) => projectEvent(state, event));
92
+ if (cache && cache.events === events) cache.state = copy(state);
93
+ return state;
94
+ }
95
+ function transaction(mutator) {
96
+ return withFileLock(journal, () => {
97
+ const events = readEvents();
98
+ const state = replay(events);
99
+ const additions = mutator(copy(state)) || [];
100
+ if (!Array.isArray(additions)) throw new Error("runtime transaction must return events");
101
+ if (!additions.length) return state;
102
+ fs.mkdirSync(directory, { recursive: true });
103
+ const committed = additions.map((event, index) => ({ ...redact(event), sequence: state.sequence + index + 1, eventId: randomUUID(), time: new Date().toISOString() }));
104
+ const fd = fs.openSync(journal, "a+", 0o600);
105
+ try { trimTornAppend(fd); fs.writeSync(fd, committed.map((event) => JSON.stringify(event)).join("\n") + "\n"); fs.fsyncSync(fd); }
106
+ finally { fs.closeSync(fd); }
107
+ committed.forEach((event) => projectEvent(state, event));
108
+ events.push(...committed);
109
+ cache = { stamp: journalStamp(), events, state: copy(state) };
110
+ const temporary = `${projection}.${randomUUID()}.tmp`;
111
+ try {
112
+ fs.writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 });
113
+ fs.renameSync(temporary, projection);
114
+ } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
115
+ return state;
116
+ });
117
+ }
118
+ return Object.freeze({ directory, journal,
119
+ read: () => replay(readEvents()),
120
+ events: ({ after = 0 } = {}) => copy(readEvents().filter((event) => event.sequence > after)),
121
+ transaction,
122
+ append: (event) => transaction(() => [event]),
123
+ });
124
+ }
125
+
126
+ module.exports = { createRuntimeStore, projectEvent };