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,504 @@
1
+ "use strict";
2
+
3
+ const DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS = 32768;
4
+ const RESPONSES_REASONING_ITEMS = Symbol("ufoo.responsesReasoningItems");
5
+
6
+ function cloneJsonValue(value) {
7
+ try {
8
+ return JSON.parse(JSON.stringify(value));
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ function reasoningItemsFromResponse(response = null) {
15
+ const output = response && typeof response === "object" && Array.isArray(response.output)
16
+ ? response.output
17
+ : [];
18
+ return output
19
+ .filter((item) => (
20
+ item
21
+ && typeof item === "object"
22
+ && item.type === "reasoning"
23
+ && typeof item.encrypted_content === "string"
24
+ && item.encrypted_content.length > 0
25
+ ))
26
+ .map(cloneJsonValue)
27
+ .filter(Boolean);
28
+ }
29
+
30
+ function attachResponsesReasoningItems(message = null, response = null) {
31
+ if (!message || typeof message !== "object") return message;
32
+ const items = reasoningItemsFromResponse(response);
33
+ if (items.length === 0) return message;
34
+ Object.defineProperty(message, RESPONSES_REASONING_ITEMS, {
35
+ value: items,
36
+ enumerable: false,
37
+ configurable: false,
38
+ writable: false,
39
+ });
40
+ return message;
41
+ }
42
+
43
+ function getResponsesReasoningItems(message = null) {
44
+ const items = message && typeof message === "object"
45
+ ? message[RESPONSES_REASONING_ITEMS]
46
+ : null;
47
+ return (Array.isArray(items) ? items : [])
48
+ .map(cloneJsonValue)
49
+ .filter(Boolean);
50
+ }
51
+
52
+ function resolveResponsesUrl(baseUrl = "") {
53
+ const raw = String(baseUrl || "").trim();
54
+ if (!raw) return "";
55
+ const normalized = raw.replace(/\/+$/, "");
56
+ if (/\/responses$/i.test(normalized)) return normalized;
57
+ if (/\/v1$/i.test(normalized)) return `${normalized}/responses`;
58
+ if (/\/api$/i.test(normalized)) return `${normalized}/v1/responses`;
59
+ return `${normalized}/responses`;
60
+ }
61
+
62
+ function toJsonString(value) {
63
+ if (typeof value === "string") return value;
64
+ try {
65
+ return JSON.stringify(value == null ? {} : value);
66
+ } catch {
67
+ return "{}";
68
+ }
69
+ }
70
+
71
+ function normalizeArguments(value) {
72
+ if (value && typeof value === "object") return value;
73
+ const text = String(value || "").trim();
74
+ if (!text) return {};
75
+ try {
76
+ const parsed = JSON.parse(text);
77
+ return parsed && typeof parsed === "object" ? parsed : {};
78
+ } catch {
79
+ return {};
80
+ }
81
+ }
82
+
83
+ function normalizeContentParts(content, role = "user") {
84
+ const outputRole = role === "assistant" ? "output_text" : "input_text";
85
+ if (typeof content === "string") {
86
+ return content ? [{ type: outputRole, text: content }] : [];
87
+ }
88
+ if (!Array.isArray(content)) return [];
89
+
90
+ const parts = [];
91
+ for (const block of content) {
92
+ if (typeof block === "string") {
93
+ if (block) parts.push({ type: outputRole, text: block });
94
+ continue;
95
+ }
96
+ if (!block || typeof block !== "object") continue;
97
+ const type = String(block.type || "").trim().toLowerCase();
98
+ if (type === "text" || type === "input_text" || type === "output_text") {
99
+ const text = String(block.text || block.content || "");
100
+ if (text) parts.push({ type: type === "text" ? outputRole : type, text });
101
+ continue;
102
+ }
103
+ if (type === "image_url") {
104
+ const image = block.image_url;
105
+ const url = typeof image === "string" ? image : image && image.url;
106
+ if (url) parts.push({ type: "input_image", image_url: String(url) });
107
+ continue;
108
+ }
109
+ if (type === "image") {
110
+ const source = block.source && typeof block.source === "object" ? block.source : block;
111
+ if (source && source.type === "base64" && source.data) {
112
+ const mediaType = String(source.media_type || "application/octet-stream");
113
+ parts.push({
114
+ type: "input_image",
115
+ image_url: `data:${mediaType};base64,${String(source.data)}`,
116
+ });
117
+ } else if (block.url) {
118
+ parts.push({ type: "input_image", image_url: String(block.url) });
119
+ }
120
+ continue;
121
+ }
122
+ if (type === "reasoning" && block.encrypted_content) {
123
+ parts.push({ type: "reasoning", encrypted_content: String(block.encrypted_content) });
124
+ }
125
+ }
126
+ return parts;
127
+ }
128
+
129
+ function messagesToResponsesInput(messages = []) {
130
+ const input = [];
131
+ for (const message of Array.isArray(messages) ? messages : []) {
132
+ if (!message || typeof message !== "object") continue;
133
+ const role = String(message.role || "user").trim().toLowerCase() || "user";
134
+
135
+ if (role === "tool") {
136
+ const callId = String(message.tool_call_id || message.call_id || "").trim();
137
+ if (callId) {
138
+ input.push({
139
+ type: "function_call_output",
140
+ call_id: callId,
141
+ output: typeof message.content === "string" ? message.content : toJsonString(message.content),
142
+ });
143
+ }
144
+ continue;
145
+ }
146
+
147
+ if (role === "assistant" && Array.isArray(message.tool_calls)) {
148
+ // With store=false and no previous_response_id, encrypted reasoning
149
+ // output must be replayed before the corresponding function calls. The
150
+ // items live on a non-enumerable message property, so this projection is
151
+ // available only to the in-flight provider loop and cannot enter the
152
+ // Session Journal through JSON serialization.
153
+ input.push(...getResponsesReasoningItems(message));
154
+ for (const call of message.tool_calls) {
155
+ if (!call || typeof call !== "object") continue;
156
+ const fn = call.function && typeof call.function === "object" ? call.function : call;
157
+ const callId = String(call.id || call.call_id || "").trim();
158
+ const name = String(fn.name || "").trim();
159
+ if (!callId || !name) continue;
160
+ input.push({
161
+ type: "function_call",
162
+ call_id: callId,
163
+ name,
164
+ arguments: typeof fn.arguments === "string" ? fn.arguments : toJsonString(fn.arguments),
165
+ });
166
+ }
167
+ const assistantText = normalizeContentParts(message.content, "assistant");
168
+ if (assistantText.length > 0) {
169
+ input.push({ type: "message", role: "assistant", content: assistantText });
170
+ }
171
+ continue;
172
+ }
173
+
174
+ const responseRole = role === "system" ? "developer" : role;
175
+ const content = normalizeContentParts(message.content, role);
176
+ if (content.length > 0) {
177
+ input.push({ type: "message", role: responseRole, content });
178
+ }
179
+ }
180
+ return input;
181
+ }
182
+
183
+ function toolsToResponsesTools(tools = []) {
184
+ const result = [];
185
+ for (const tool of Array.isArray(tools) ? tools : []) {
186
+ if (!tool || typeof tool !== "object") continue;
187
+ if (tool.type && tool.type !== "function") {
188
+ // Hosted/namespace tools are provider-specific. Pass through only when
189
+ // they already use the Responses shape.
190
+ if (tool.type === "web_search" || tool.type === "x_search" || tool.type === "image_generation") {
191
+ result.push({ ...tool });
192
+ }
193
+ continue;
194
+ }
195
+ const fn = tool.function && typeof tool.function === "object" ? tool.function : tool;
196
+ const name = String(fn.name || "").trim();
197
+ if (!name) continue;
198
+ result.push({
199
+ type: "function",
200
+ name,
201
+ // Responses otherwise normalizes compatible schemas to strict mode,
202
+ // making optional fields required. AJV remains the local authority.
203
+ strict: typeof fn.strict === "boolean" ? fn.strict : false,
204
+ description: String(fn.description || ""),
205
+ parameters: fn.parameters && typeof fn.parameters === "object"
206
+ ? fn.parameters
207
+ : { type: "object", properties: {}, additionalProperties: true },
208
+ });
209
+ }
210
+ return result;
211
+ }
212
+
213
+ function buildResponsesPayload({
214
+ model = "",
215
+ instructions = "",
216
+ messages = [],
217
+ tools = [],
218
+ maxOutputTokens = DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS,
219
+ reasoningEffort = "",
220
+ provider = "",
221
+ } = {}) {
222
+ const payload = {
223
+ model: String(model || "").trim(),
224
+ instructions: String(instructions || ""),
225
+ input: messagesToResponsesInput(messages),
226
+ max_output_tokens: Math.max(1, Number(maxOutputTokens) || DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS),
227
+ stream: true,
228
+ store: false,
229
+ parallel_tool_calls: true,
230
+ };
231
+
232
+ const responseTools = toolsToResponsesTools(tools);
233
+ if (responseTools.length > 0) {
234
+ payload.tools = responseTools;
235
+ payload.tool_choice = "auto";
236
+ }
237
+
238
+ const normalizedProvider = String(provider || "").trim().toLowerCase();
239
+ if (normalizedProvider === "codex" || normalizedProvider === "openai"
240
+ || normalizedProvider === "grok-build" || normalizedProvider === "xai") {
241
+ payload.include = ["reasoning.encrypted_content"];
242
+ }
243
+ const effort = String(reasoningEffort || "").trim();
244
+ if (effort) {
245
+ payload.reasoning = { effort, summary: "auto" };
246
+ } else if (normalizedProvider === "codex") {
247
+ payload.reasoning = { effort: "medium", summary: "auto" };
248
+ }
249
+ return payload;
250
+ }
251
+
252
+ function parseJson(value) {
253
+ if (value && typeof value === "object") return value;
254
+ try {
255
+ return JSON.parse(String(value || ""));
256
+ } catch {
257
+ return null;
258
+ }
259
+ }
260
+
261
+ function isResponsesKeepalive(eventName = "", data = null) {
262
+ if (String(eventName || "").trim().toLowerCase() === "keepalive") return true;
263
+ const parsed = parseJson(data);
264
+ return Boolean(parsed && parsed.type === "keepalive");
265
+ }
266
+
267
+ function responseEventDelta(frame = {}) {
268
+ const data = parseJson(frame.data);
269
+ if (!data || isResponsesKeepalive(frame.event, data)) {
270
+ return { text: "", reasoning: "", type: "" };
271
+ }
272
+ const type = String(data.type || frame.event || "").trim();
273
+ if (type === "response.output_text.delta") {
274
+ return { text: String(data.delta || ""), reasoning: "", type };
275
+ }
276
+ if (/^response\.(?:reasoning|reasoning_text|reasoning_summary|reasoning_summary_text)\.(?:delta|text\.delta)$/.test(type)) {
277
+ return { text: "", reasoning: String(data.delta || data.text || ""), type };
278
+ }
279
+ return { text: "", reasoning: "", type };
280
+ }
281
+
282
+ function responseOutputText(output = []) {
283
+ const parts = [];
284
+ for (const item of Array.isArray(output) ? output : []) {
285
+ if (!item || typeof item !== "object") continue;
286
+ if (item.type === "message") {
287
+ for (const content of Array.isArray(item.content) ? item.content : []) {
288
+ if (content && (content.type === "output_text" || content.type === "text")) {
289
+ parts.push(String(content.text || ""));
290
+ }
291
+ }
292
+ } else if (item.type === "output_text") {
293
+ parts.push(String(item.text || ""));
294
+ }
295
+ }
296
+ return parts.join("");
297
+ }
298
+
299
+ function responseUsage(response = null) {
300
+ const usage = response && typeof response === "object" && response.usage && typeof response.usage === "object"
301
+ ? response.usage
302
+ : null;
303
+ if (!usage) return null;
304
+ const details = usage.input_tokens_details ?? usage.input_token_details;
305
+ const inputDetails = details && typeof details === "object"
306
+ ? details
307
+ : {};
308
+ const cached = inputDetails.cached_tokens ?? usage.cached_input_tokens ?? usage.cache_read_input_tokens;
309
+ if (![usage.input_tokens, usage.prompt_tokens, usage.output_tokens, usage.completion_tokens, cached]
310
+ .some(value => value != null && Number.isFinite(Number(value)))) return null;
311
+ return {
312
+ input: Number(usage.input_tokens || usage.prompt_tokens || 0) || 0,
313
+ output: Number(usage.output_tokens || usage.completion_tokens || 0) || 0,
314
+ cacheRead: cached != null && Number.isFinite(Number(cached)) ? Number(cached) : null,
315
+ cacheCreation: Number(inputDetails.cache_write_tokens ?? usage.cache_creation_input_tokens ?? usage.cache_creation_tokens ?? 0) || 0,
316
+ inputIncludesCache: true,
317
+ };
318
+ }
319
+
320
+ function responseToolKey(data = {}, item = null) {
321
+ return String(
322
+ data.item_id
323
+ || (item && item.id)
324
+ || data.output_index
325
+ || (item && (item.output_index || item.call_id))
326
+ || data.call_id
327
+ || "",
328
+ ).trim();
329
+ }
330
+
331
+ function mergeFunctionCall(toolMap, data = {}, item = null) {
332
+ const key = responseToolKey(data, item);
333
+ if (!key) return;
334
+ const existing = toolMap.get(key) || {
335
+ order: Number.isFinite(Number(data.output_index)) ? Number(data.output_index) : toolMap.size,
336
+ id: "",
337
+ name: "",
338
+ arguments: "",
339
+ };
340
+ const source = item && typeof item === "object" ? item : data;
341
+ existing.id = String(source.call_id || source.id || existing.id || data.call_id || "").trim();
342
+ existing.name = String(source.name || existing.name || data.name || "").trim();
343
+ if (typeof source.arguments === "string") existing.arguments = source.arguments;
344
+ if (typeof data.arguments === "string") existing.arguments = data.arguments;
345
+ if (typeof data.delta === "string" && data.type === "response.function_call_arguments.delta") {
346
+ existing.arguments += data.delta;
347
+ }
348
+ toolMap.set(key, existing);
349
+ }
350
+
351
+ function mergeResponseOutput(toolMap, output = []) {
352
+ for (const item of Array.isArray(output) ? output : []) {
353
+ if (!item || typeof item !== "object") continue;
354
+ if (item.type === "function_call") mergeFunctionCall(toolMap, item, item);
355
+ }
356
+ }
357
+
358
+ function mergeOutputItem(outputItemMap, data = {}, item = null) {
359
+ if (!item || typeof item !== "object") return;
360
+ const numericIndex = Number(data.output_index);
361
+ const hasIndex = Number.isFinite(numericIndex);
362
+ const key = hasIndex
363
+ ? `index:${numericIndex}`
364
+ : `id:${String(item.id || outputItemMap.size)}`;
365
+ outputItemMap.set(key, {
366
+ order: hasIndex ? numericIndex : outputItemMap.size,
367
+ item: cloneJsonValue(item),
368
+ });
369
+ }
370
+
371
+ function mergeCompletedOutput(outputItemMap, output = []) {
372
+ for (const [index, item] of (Array.isArray(output) ? output : []).entries()) {
373
+ if (!item || typeof item !== "object") continue;
374
+ const key = `index:${index}`;
375
+ if (!outputItemMap.has(key)) {
376
+ mergeOutputItem(outputItemMap, { output_index: index }, item);
377
+ }
378
+ }
379
+ }
380
+
381
+ function parseResponsesEvents(frames = [], { assumeCompleted = false } = {}) {
382
+ const events = [];
383
+ const textParts = [];
384
+ const reasoningParts = [];
385
+ const toolMap = new Map();
386
+ const outputItemMap = new Map();
387
+ let response = null;
388
+ let terminal = assumeCompleted ? "completed" : "";
389
+
390
+ for (const frame of Array.isArray(frames) ? frames : []) {
391
+ const data = parseJson(frame && frame.data);
392
+ if (!data || isResponsesKeepalive(frame && frame.event, data)) continue;
393
+ events.push(data);
394
+ const type = String(data.type || (frame && frame.event) || "").trim();
395
+ const delta = responseEventDelta({ event: type, data });
396
+ if (delta.text) textParts.push(delta.text);
397
+ if (delta.reasoning) reasoningParts.push(delta.reasoning);
398
+
399
+ if (type === "response.output_item.added" || type === "response.output_item.done") {
400
+ mergeFunctionCall(toolMap, data, data.item);
401
+ mergeOutputItem(outputItemMap, data, data.item);
402
+ } else if (type === "response.function_call_arguments.delta"
403
+ || type === "response.function_call_arguments.done") {
404
+ mergeFunctionCall(toolMap, data, null);
405
+ }
406
+
407
+ if (type === "response.completed" || type === "response.incomplete") {
408
+ terminal = type === "response.completed" ? "completed" : "incomplete";
409
+ if (data.response && typeof data.response === "object") {
410
+ response = data.response;
411
+ mergeResponseOutput(toolMap, response.output);
412
+ mergeCompletedOutput(outputItemMap, response.output);
413
+ if (!textParts.length) {
414
+ const fallbackText = responseOutputText(response.output);
415
+ if (fallbackText) textParts.push(fallbackText);
416
+ }
417
+ }
418
+ } else if (!response && data.object === "response") {
419
+ response = data;
420
+ mergeResponseOutput(toolMap, response.output);
421
+ mergeCompletedOutput(outputItemMap, response.output);
422
+ if (!textParts.length) {
423
+ const fallbackText = responseOutputText(response.output);
424
+ if (fallbackText) textParts.push(fallbackText);
425
+ }
426
+ if (data.status === "completed" || data.status === "incomplete") {
427
+ terminal = data.status;
428
+ }
429
+ }
430
+ }
431
+
432
+ const toolCalls = Array.from(toolMap.values())
433
+ .sort((left, right) => left.order - right.order)
434
+ .filter((call) => call.id && call.name)
435
+ .map((call) => ({
436
+ id: call.id,
437
+ type: "function",
438
+ function: {
439
+ name: call.name,
440
+ arguments: call.arguments || "{}",
441
+ },
442
+ }));
443
+ const outputItems = Array.from(outputItemMap.values())
444
+ .sort((left, right) => left.order - right.order)
445
+ .map((entry) => entry.item)
446
+ .filter(Boolean);
447
+
448
+ return {
449
+ text: textParts.join(""),
450
+ reasoning: reasoningParts.join(""),
451
+ toolCalls,
452
+ outputItems,
453
+ response,
454
+ responseId: String(response && response.id || "").trim(),
455
+ usage: responseUsage(response),
456
+ terminal,
457
+ incompleteDetails: response && response.incomplete_details ? response.incomplete_details : null,
458
+ events,
459
+ };
460
+ }
461
+
462
+ function parseSseBlocks(raw = "") {
463
+ const text = String(raw || "");
464
+ const blocks = text.split(/\r?\n\r?\n/);
465
+ const rest = blocks.pop() || "";
466
+ return { blocks: blocks.filter(Boolean), rest };
467
+ }
468
+
469
+ function parseSseFrame(block = "") {
470
+ let event = "";
471
+ const dataLines = [];
472
+ for (const line of String(block || "").split(/\r?\n/)) {
473
+ if (line.startsWith("event:")) event = line.slice(6).trim();
474
+ if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
475
+ }
476
+ return { event, data: dataLines.join("\n").trim() };
477
+ }
478
+
479
+ function parseResponsesSsePayload(payload = "") {
480
+ const frames = [];
481
+ let buffer = String(payload || "");
482
+ const parsed = parseSseBlocks(buffer);
483
+ for (const block of parsed.blocks) frames.push(parseSseFrame(block));
484
+ buffer = parsed.rest;
485
+ if (buffer.trim()) frames.push(parseSseFrame(buffer));
486
+ return parseResponsesEvents(frames);
487
+ }
488
+
489
+ module.exports = {
490
+ DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS,
491
+ attachResponsesReasoningItems,
492
+ getResponsesReasoningItems,
493
+ reasoningItemsFromResponse,
494
+ resolveResponsesUrl,
495
+ messagesToResponsesInput,
496
+ toolsToResponsesTools,
497
+ buildResponsesPayload,
498
+ isResponsesKeepalive,
499
+ responseEventDelta,
500
+ responseOutputText,
501
+ responseUsage,
502
+ parseResponsesEvents,
503
+ parseResponsesSsePayload,
504
+ };
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+
3
+ function systemBlocksToAnthropicPayload(blocks = []) {
4
+ const list = (Array.isArray(blocks) ? blocks : []).filter((b) => b && b.text);
5
+ const ANTHROPIC_CACHE_CONTROL = { type: "ephemeral" };
6
+ // Place cache breakpoints on every cacheable layer so Anthropic can reuse
7
+ // Immutable → SessionStable → Epoch prefixes independently. Turn-dynamic
8
+ // never gets cache_control.
9
+ return list.map((block) => {
10
+ const entry = { type: "text", text: block.text };
11
+ if (block.cacheable) entry.cache_control = { ...ANTHROPIC_CACHE_CONTROL };
12
+ return entry;
13
+ });
14
+ }
15
+
16
+ module.exports = { systemBlocksToAnthropicPayload };
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Transport contract for native Agent Loop Provider adapters.
5
+ *
6
+ * Transports own wire-format conversion and turn execution only.
7
+ * They must not decide Plan Mode, write leases, or tool batch policy.
8
+ *
9
+ * Required methods:
10
+ * - resolveUrl(baseUrl) → string
11
+ * - prepareMessages({ messages, systemPrompt?, prompt })
12
+ * - runTurn(params) → Promise<turnResult>
13
+ * - getToolCalls(turnResult) → array
14
+ * - appendFinalAssistantMessage({ messages, turnResult })
15
+ * - prepareToolCalls({ messages, turnResult?, toolCalls }) → pendingCalls|null
16
+ * - appendToolResult({ messages?, collected?, call, toolResult })
17
+ * - flushToolResults?({ messages, collected }) // Anthropic-style batch
18
+ */
19
+
20
+ const TRANSPORT_NAMES = Object.freeze([
21
+ "openai-chat",
22
+ "openai-responses",
23
+ "anthropic-messages",
24
+ ]);
25
+
26
+ function assertTransport(transport = null, name = "") {
27
+ if (!transport || typeof transport !== "object") {
28
+ throw new Error(`missing transport${name ? `: ${name}` : ""}`);
29
+ }
30
+ const required = [
31
+ "resolveUrl",
32
+ "prepareMessages",
33
+ "runTurn",
34
+ "getToolCalls",
35
+ "appendFinalAssistantMessage",
36
+ "prepareToolCalls",
37
+ "appendToolResult",
38
+ ];
39
+ for (const key of required) {
40
+ if (typeof transport[key] !== "function") {
41
+ throw new Error(`transport ${name || "?"} missing ${key}`);
42
+ }
43
+ }
44
+ return transport;
45
+ }
46
+
47
+ module.exports = {
48
+ TRANSPORT_NAMES,
49
+ assertTransport,
50
+ };