u-foo 3.1.6 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +172 -13
  2. package/README.zh-CN.md +108 -13
  3. package/SKILLS/ufoo/SKILL.md +15 -3
  4. package/SKILLS/ufoo-bus/SKILL.md +21 -1
  5. package/bin/uclaude.js +4 -0
  6. package/bin/ucodex.js +4 -0
  7. package/bin/ufoo.js +3 -1
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +10 -3
  13. package/scripts/postinstall-skills.js +53 -0
  14. package/scripts/postinstall.js +11 -16
  15. package/scripts/smoke-native-messages.js +214 -0
  16. package/src/agents/activity/activityStateWriter.js +37 -38
  17. package/src/agents/capabilities/agentManagement/index.js +4 -0
  18. package/src/agents/capabilities/agentManagement/service.js +113 -0
  19. package/src/agents/capabilities/agentRouting/index.js +4 -0
  20. package/src/agents/capabilities/coding/index.js +32 -0
  21. package/src/agents/capabilities/coordination/index.js +37 -0
  22. package/src/agents/capabilities/globalRouting/index.js +5 -0
  23. package/src/agents/capabilities/groups/index.js +3 -0
  24. package/src/agents/capabilities/index.js +25 -0
  25. package/src/agents/capabilities/planning/index.js +123 -0
  26. package/src/agents/capabilities/planning/main.js +28 -0
  27. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  28. package/src/agents/capabilities/scheduling/index.js +3 -0
  29. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  30. package/src/agents/capabilities/skills/index.js +12 -0
  31. package/src/agents/capabilities/taskExecution/index.js +3 -0
  32. package/src/agents/capabilities/taskReports/index.js +6 -0
  33. package/src/agents/controller/controllerToolExecutor.js +6 -4
  34. package/src/agents/controller/loopRuntime.js +85 -221
  35. package/src/agents/controller/ufooAgent.js +1 -0
  36. package/src/agents/internal/internalRunner.js +103 -32
  37. package/src/agents/launch/launcher.js +88 -6
  38. package/src/agents/launch/nativeCapabilities.js +40 -0
  39. package/src/agents/launch/nativeMessages.js +362 -0
  40. package/src/agents/launch/notifier.js +13 -18
  41. package/src/agents/launch/readyDetector.js +26 -12
  42. package/src/agents/profiles/coding.js +6 -0
  43. package/src/agents/profiles/globalRouter.js +2 -0
  44. package/src/agents/profiles/main.js +5 -0
  45. package/src/agents/prompts/groupBootstrap.js +10 -0
  46. package/src/agents/prompts/mainAgent.js +39 -0
  47. package/src/agents/prompts/native/tasks.js +2 -2
  48. package/src/agents/prompts/native/ufoo.js +3 -0
  49. package/src/agents/providers/claudeEventTranslator.js +6 -1
  50. package/src/agents/providers/claudeThreadProvider.js +44 -2
  51. package/src/agents/providers/codexEventTranslator.js +47 -7
  52. package/src/agents/providers/codexThreadProvider.js +3 -2
  53. package/src/agents/providers/controllerJsonTransport.js +28 -0
  54. package/src/agents/providers/credentials/claude.js +10 -3
  55. package/src/agents/providers/nativeTransport.js +1135 -0
  56. package/src/agents/providers/runtimeConfig.js +186 -0
  57. package/src/agents/providers/thinkingLevels.js +132 -0
  58. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  59. package/src/agents/providers/transports/index.js +10 -0
  60. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  61. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  62. package/src/agents/providers/transports/responsesProtocol.js +499 -0
  63. package/src/agents/providers/transports/systemBlocks.js +16 -0
  64. package/src/agents/providers/transports/transportContract.js +50 -0
  65. package/src/agents/providers/transports/visionBlocks.js +151 -0
  66. package/src/agents/providers/upstreamTransport.js +13 -4
  67. package/src/agents/runtime/composeCapabilities.js +89 -0
  68. package/src/agents/runtime/context/commandStore.js +43 -0
  69. package/src/agents/runtime/context/contextWindow.js +119 -0
  70. package/src/agents/runtime/context/fileLock.js +36 -0
  71. package/src/agents/runtime/context/runtimeStore.js +126 -0
  72. package/src/agents/runtime/context/sessionJournal.js +360 -0
  73. package/src/agents/runtime/context/sessionStore.js +57 -0
  74. package/src/agents/runtime/core/agentLoop.js +270 -0
  75. package/src/agents/runtime/core/stableJson.js +29 -0
  76. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  77. package/src/agents/runtime/createAgentRuntime.js +247 -0
  78. package/src/agents/runtime/index.js +14 -0
  79. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  80. package/src/agents/runtime/protocol/materialize.js +107 -0
  81. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  82. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  83. package/src/agents/runtime/tasks/scheduler.js +73 -0
  84. package/src/agents/runtime/tools/registry.js +57 -0
  85. package/src/app/chat/ChatController.js +14 -3
  86. package/src/app/chat/agentDirectory.js +8 -2
  87. package/src/app/chat/commandExecutor.js +36 -46
  88. package/src/app/chat/commands.js +14 -7
  89. package/src/app/chat/daemonConnection.js +58 -5
  90. package/src/app/chat/daemonMessageRouter.js +61 -3
  91. package/src/app/chat/inputSubmitHandler.js +14 -2
  92. package/src/app/chat/launchRequestContext.js +42 -0
  93. package/src/app/chat/multiWindow/paneManager.js +85 -165
  94. package/src/app/chat/streamState.js +3 -3
  95. package/src/app/chat/transport.js +1 -1
  96. package/src/app/cli/busCoreCommands.js +9 -0
  97. package/src/app/cli/features/doctor.js +33 -0
  98. package/src/app/cli/features/skills.js +16 -4
  99. package/src/app/cli/reportCoreCommands.js +37 -0
  100. package/src/app/cli/run.js +40 -39
  101. package/src/code/agent.js +16 -4
  102. package/src/code/context/artifacts.js +12 -11
  103. package/src/code/context/assembler.js +2 -1
  104. package/src/code/context/promptLayers.js +1 -13
  105. package/src/code/context/stableJson.js +2 -27
  106. package/src/code/contextWindow.js +2 -117
  107. package/src/code/conversation/sessionJournal.js +3 -349
  108. package/src/code/internalThread.js +100 -0
  109. package/src/code/nativeRunner.js +36 -2668
  110. package/src/code/protocol/faultHarness.js +2 -88
  111. package/src/code/protocol/materialize.js +2 -105
  112. package/src/code/protocol/toolCallLedger.js +5 -215
  113. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  114. package/src/code/providers/openaiChatTransport.js +2 -114
  115. package/src/code/providers/openaiResponsesTransport.js +2 -117
  116. package/src/code/providers/responsesProtocol.js +2 -497
  117. package/src/code/providers/transportContract.js +2 -48
  118. package/src/code/providers/visionBlocks.js +2 -149
  119. package/src/code/sessionStore.js +24 -96
  120. package/src/code/thinkingLevels.js +1 -130
  121. package/src/code/toolLoopGuard.js +3 -49
  122. package/src/code/tools/artifactRead.js +1 -1
  123. package/src/code/tools/executor.js +373 -0
  124. package/src/code/tools/specs.js +312 -0
  125. package/src/config.js +81 -67
  126. package/src/coordination/bus/deliveryQueue.js +16 -2
  127. package/src/coordination/bus/index.js +2 -6
  128. package/src/coordination/bus/inject.js +13 -5
  129. package/src/coordination/bus/nativeReceipts.js +100 -0
  130. package/src/coordination/bus/queue.js +1 -3
  131. package/src/coordination/bus/utils.js +7 -3
  132. package/src/coordination/history/agentSurface.js +142 -0
  133. package/src/coordination/history/controllerSummary.js +23 -0
  134. package/src/coordination/memory/index.js +5 -21
  135. package/src/coordination/report/store.js +103 -83
  136. package/src/coordination/state/agentsStore.js +57 -3
  137. package/src/coordination/state/fileLock.js +2 -0
  138. package/src/coordination/state/workspaceAccess.js +36 -0
  139. package/src/runtime/contracts/agentMode.js +17 -0
  140. package/src/runtime/contracts/eventContract.js +3 -0
  141. package/src/runtime/contracts/uiProtocol.js +4 -0
  142. package/src/runtime/daemon/agentHost.js +375 -0
  143. package/src/runtime/daemon/busBridge.js +396 -0
  144. package/src/runtime/daemon/claudeChannel.js +159 -0
  145. package/src/runtime/daemon/controlPlaneService.js +27 -17
  146. package/src/runtime/daemon/cronOps.js +25 -17
  147. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  148. package/src/runtime/daemon/executionPaths.js +30 -0
  149. package/src/runtime/daemon/globalDaemon.js +28 -1
  150. package/src/runtime/daemon/groupOrchestrator.js +1 -0
  151. package/src/runtime/daemon/index.js +114 -344
  152. package/src/runtime/daemon/ipcServer.js +32 -10
  153. package/src/runtime/daemon/mcpConfigure.js +113 -20
  154. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  155. package/src/runtime/daemon/mcpServer.js +7 -4
  156. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  157. package/src/runtime/daemon/ops.js +22 -17
  158. package/src/runtime/daemon/promptRequest.js +23 -4
  159. package/src/runtime/daemon/providerSessions.js +67 -33
  160. package/src/runtime/daemon/reportControlBus.js +59 -25
  161. package/src/runtime/daemon/status.js +4 -0
  162. package/src/runtime/privacy/redactor.js +2 -2
  163. package/src/runtime/projects/identity.js +2 -1
  164. package/src/runtime/projects/registry.js +98 -38
  165. package/src/tools/controllerSchemas.js +24 -0
  166. package/src/tools/handlers/dispatchMessage.js +5 -2
  167. package/src/tools/handlers/listAgents.js +3 -1
  168. package/src/tools/handlers/readBusSummary.js +3 -1
  169. package/src/tools/handlers/readProjectRegistry.js +29 -2
  170. package/src/tools/handlers/routeAgent.js +35 -0
  171. package/src/tools/index.js +1 -0
  172. package/src/tools/registry.js +2 -0
  173. package/src/tools/schemaFixtures.js +16 -3
  174. package/src/tools/tier1/routeAgent.js +2 -2
  175. package/src/tools/tier2/runtimeCoordination.js +38 -0
  176. package/src/tools/types.js +2 -0
  177. package/src/ui/agentPresentation.js +109 -0
  178. package/src/ui/agentSurface.js +270 -0
  179. package/src/ui/format/banner.js +8 -11
  180. package/src/ui/format/startupBanner.js +50 -0
  181. package/src/ui/multiPaneBusMirror.js +29 -3
  182. package/src/ui/rustChatHost.js +170 -438
  183. package/src/ui/rustMultiSession.js +225 -51
  184. package/src/ui/rustUcodeHost.js +20 -87
  185. package/src/ui/settingsBridge.js +7 -4
  186. package/src/app/chat/agentEnter.js +0 -70
  187. package/src/app/chat/multiWindow/index.js +0 -310
  188. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  189. package/src/app/chat/multiWindow/renderer.js +0 -420
  190. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  191. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  192. package/src/ui/multiWindowHandoff.js +0 -232
  193. package/src/ui/ptyHandoff.js +0 -23
@@ -0,0 +1,1135 @@
1
+ "use strict";
2
+
3
+ const os = require("os");
4
+ const { randomUUID } = require("crypto");
5
+ const { Agent: UndiciAgent } = require("undici");
6
+ const { normalizeProvider, normalizeKimiModel, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl } = require("./runtimeConfig");
7
+ const { stableStringify } = require("../runtime/core/stableJson");
8
+ const { systemBlocksToAnthropicPayload } = require("./transports/systemBlocks");
9
+ const { buildResponsesPayload, isResponsesKeepalive, responseEventDelta, parseResponsesEvents, parseResponsesSsePayload } = require("./transports/responsesProtocol");
10
+
11
+ const DEFAULT_NATIVE_TIMEOUT_MS = 43200000;
12
+ const DEFAULT_OPENAI_MAX_TOKENS = 32768;
13
+ const DEFAULT_ANTHROPIC_MAX_TOKENS = 32768;
14
+ const NATIVE_SSE_DISPATCHER_OPTIONS = Object.freeze({ headersTimeout: 0, bodyTimeout: 0 });
15
+ const ANTHROPIC_CACHE_CONTROL = Object.freeze({ type: "ephemeral" });
16
+
17
+ function nowMs() {
18
+ return Date.now();
19
+ }
20
+
21
+ function normalizeTimeoutMs(value) {
22
+ const parsed = Number(value);
23
+ if (!Number.isFinite(parsed)) return DEFAULT_NATIVE_TIMEOUT_MS;
24
+ return Math.max(1000, Math.floor(parsed));
25
+ }
26
+
27
+ let nativeSseDispatcher = null;
28
+
29
+ function createNativeSseDispatcher() {
30
+ return new UndiciAgent({ ...NATIVE_SSE_DISPATCHER_OPTIONS });
31
+ }
32
+
33
+ function getNativeSseDispatcher() {
34
+ if (!nativeSseDispatcher || nativeSseDispatcher.destroyed) {
35
+ nativeSseDispatcher = createNativeSseDispatcher();
36
+ }
37
+ return nativeSseDispatcher;
38
+ }
39
+
40
+ function enrichProviderTransportError(err) {
41
+ if (!err || typeof err !== "object") return err;
42
+
43
+ const cause = err.cause && typeof err.cause === "object" ? err.cause : null;
44
+ const code = String((cause && cause.code) || err.code || "").trim();
45
+ const causeMessage = String((cause && cause.message) || "").trim();
46
+ if (!code && !causeMessage) return err;
47
+
48
+ const message = String(err.message || "provider transport failed").trim();
49
+ const details = [code, causeMessage]
50
+ .filter(Boolean)
51
+ .filter((value, index, values) => values.indexOf(value) === index)
52
+ .join(": ");
53
+ if (!details || message.includes(details)) return err;
54
+
55
+ const enriched = new Error(`${message} (${details})`);
56
+ enriched.code = code || err.code;
57
+ enriched.cause = err;
58
+ return enriched;
59
+ }
60
+
61
+ function normalizePositiveInt(value, fallback) {
62
+ const parsed = Number.parseInt(String(value || ""), 10);
63
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
64
+ return Math.floor(parsed);
65
+ }
66
+
67
+ function resolveMaxTokens(fallback) {
68
+ return normalizePositiveInt(process.env.UFOO_UCODE_MAX_TOKENS, fallback);
69
+ }
70
+
71
+ function resolveThinkingBudgetTokens(options = {}) {
72
+ const { resolveThinkingFromEnvAndConfig } = require("./thinkingLevels");
73
+ const { loadGlobalUcodeConfig } = require("../../config");
74
+ let configLevel = String(options.configLevel || "").trim();
75
+ if (!configLevel) {
76
+ try {
77
+ configLevel = String((loadGlobalUcodeConfig() || {}).ucodeThinking || "").trim();
78
+ } catch {
79
+ configLevel = "";
80
+ }
81
+ }
82
+ const resolved = resolveThinkingFromEnvAndConfig({
83
+ env: options.env || process.env,
84
+ configLevel,
85
+ });
86
+ return resolved.budgetTokens;
87
+ }
88
+
89
+ function resolveReasoningEffort(options = {}) {
90
+ const { resolveThinkingFromEnvAndConfig } = require("./thinkingLevels");
91
+ const { loadGlobalUcodeConfig } = require("../../config");
92
+ let configLevel = String(options.configLevel || "").trim();
93
+ if (!configLevel) {
94
+ try {
95
+ configLevel = String((loadGlobalUcodeConfig() || {}).ucodeThinking || "").trim();
96
+ } catch {
97
+ configLevel = "";
98
+ }
99
+ }
100
+ const resolved = resolveThinkingFromEnvAndConfig({
101
+ env: options.env || process.env,
102
+ configLevel,
103
+ });
104
+ return resolved.reasoningEffort || "";
105
+ }
106
+
107
+ function toUsageInt(value) {
108
+ const parsed = Number(value);
109
+ if (!Number.isFinite(parsed) || parsed <= 0) return 0;
110
+ return Math.floor(parsed);
111
+ }
112
+
113
+ function createUsageTotals() {
114
+ return {
115
+ turns: 0,
116
+ input: 0,
117
+ output: 0,
118
+ cacheRead: 0,
119
+ cacheCreation: 0,
120
+ lastContextTokens: 0,
121
+ };
122
+ }
123
+
124
+ function addUsageTotals(totals, usage = null) {
125
+ if (!usage || typeof usage !== "object") return totals;
126
+ totals.input += toUsageInt(usage.input);
127
+ totals.output += toUsageInt(usage.output);
128
+ totals.cacheRead += toUsageInt(usage.cacheRead);
129
+ totals.cacheCreation += toUsageInt(usage.cacheCreation);
130
+ return totals;
131
+ }
132
+
133
+ // OpenAI-compatible streams end with one usage chunk carrying whole-turn
134
+ // totals (prompt_tokens_details.cached_tokens counts the cache hits).
135
+ function readOpenAiUsage(raw) {
136
+ if (!raw || typeof raw !== "object") return null;
137
+ const details = raw.prompt_tokens_details && typeof raw.prompt_tokens_details === "object"
138
+ ? raw.prompt_tokens_details
139
+ : {};
140
+ return {
141
+ input: toUsageInt(raw.prompt_tokens),
142
+ output: toUsageInt(raw.completion_tokens),
143
+ cacheRead: toUsageInt(details.cached_tokens),
144
+ cacheCreation: toUsageInt(details.created_cache_tokens),
145
+ inputIncludesCache: true,
146
+ };
147
+ }
148
+
149
+ // Anthropic reports input/cache tokens once on message_start; output tokens
150
+ // arrive per message_delta. The non-streaming body carries the full totals.
151
+ function readAnthropicUsage(raw, { includeOutput = false } = {}) {
152
+ if (!raw || typeof raw !== "object") return null;
153
+ return {
154
+ input: toUsageInt(raw.input_tokens),
155
+ output: includeOutput ? toUsageInt(raw.output_tokens) : 0,
156
+ cacheRead: toUsageInt(raw.cache_read_input_tokens),
157
+ cacheCreation: toUsageInt(raw.cache_creation_input_tokens),
158
+ inputIncludesCache: false,
159
+ };
160
+ }
161
+
162
+ function clipText(value = "", maxChars = 6000) {
163
+ const text = String(value || "");
164
+ if (text.length <= maxChars) return text;
165
+ return `${text.slice(0, maxChars)}\n...[truncated]`;
166
+ }
167
+
168
+ function createRequestController({ signal = null, timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS } = {}) {
169
+ const controller = new AbortController();
170
+ let timedOut = false;
171
+
172
+ const timer = setTimeout(() => {
173
+ timedOut = true;
174
+ try {
175
+ controller.abort();
176
+ } catch {
177
+ // ignore
178
+ }
179
+ }, normalizeTimeoutMs(timeoutMs));
180
+
181
+ let abortHandler = null;
182
+ if (signal && typeof signal === "object") {
183
+ abortHandler = () => {
184
+ try {
185
+ controller.abort();
186
+ } catch {
187
+ // ignore
188
+ }
189
+ };
190
+ if (signal.aborted) {
191
+ abortHandler();
192
+ } else if (typeof signal.addEventListener === "function") {
193
+ signal.addEventListener("abort", abortHandler, { once: true });
194
+ }
195
+ }
196
+
197
+ return {
198
+ signal: controller.signal,
199
+ timedOut: () => timedOut,
200
+ cleanup: () => {
201
+ clearTimeout(timer);
202
+ if (signal && abortHandler && typeof signal.removeEventListener === "function") {
203
+ signal.removeEventListener("abort", abortHandler);
204
+ }
205
+ },
206
+ };
207
+ }
208
+
209
+ function parseJsonSafe(value = "", fallback = null) {
210
+ try {
211
+ return JSON.parse(String(value || ""));
212
+ } catch {
213
+ return fallback;
214
+ }
215
+ }
216
+
217
+ function cloneMessageList(value = []) {
218
+ const parsed = parseJsonSafe(toJsonString(value), []);
219
+ if (!Array.isArray(parsed)) return [];
220
+ return parsed.filter((entry) => entry && typeof entry === "object" && !Array.isArray(entry));
221
+ }
222
+
223
+ function toJsonString(value) {
224
+ return stableStringify(value);
225
+ }
226
+
227
+ function parseSseBlocks(text = "") {
228
+ const source = String(text || "");
229
+ const blocks = source.split(/\r?\n\r?\n/);
230
+ if (blocks.length <= 1) {
231
+ return { blocks: [], rest: source };
232
+ }
233
+ const rest = blocks.pop() || "";
234
+ return { blocks, rest };
235
+ }
236
+
237
+ function parseSseEventBlock(block = "") {
238
+ const lines = String(block || "").split(/\r?\n/);
239
+ let event = "message";
240
+ const data = [];
241
+
242
+ for (const line of lines) {
243
+ if (!line) continue;
244
+ if (line.startsWith("event:")) {
245
+ event = line.slice(6).trim() || "message";
246
+ continue;
247
+ }
248
+ if (line.startsWith("data:")) {
249
+ data.push(line.slice(5).trimStart());
250
+ }
251
+ }
252
+
253
+ return {
254
+ event,
255
+ data: data.join("\n"),
256
+ };
257
+ }
258
+
259
+ function parseSseDataBlock(block = "") {
260
+ return parseSseEventBlock(block).data;
261
+ }
262
+
263
+ function normalizeToolCallArgs(raw = "") {
264
+ const text = String(raw || "").trim();
265
+ if (!text) return {};
266
+ const parsed = parseJsonSafe(text, null);
267
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
268
+ return parsed;
269
+ }
270
+ return {};
271
+ }
272
+
273
+ function emitPhase(callback, event = {}) {
274
+ if (typeof callback !== "function") return;
275
+ try {
276
+ callback(event);
277
+ } catch {
278
+ // ignore phase callback failures
279
+ }
280
+ }
281
+
282
+ // Shared SSE transport skeleton: POST the payload, then read the stream as
283
+ // SSE blocks, dispatch each non-[DONE] block to onEvent, and stop after the
284
+ // batch that carried [DONE]. Timeout/cancel translation and request cleanup
285
+ // live here so each protocol turn only declares its event handling.
286
+ async function runSseRequest({
287
+ url = "",
288
+ headers = {},
289
+ payload = {},
290
+ signal = null,
291
+ timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
292
+ onPhase = null,
293
+ onNonStream,
294
+ onEvent,
295
+ onTail = null,
296
+ buildResult,
297
+ } = {}) {
298
+ const request = createRequestController({ signal, timeoutMs });
299
+
300
+ emitPhase(onPhase, { type: "request_start" });
301
+
302
+ try {
303
+ const response = await fetch(url, {
304
+ method: "POST",
305
+ headers,
306
+ body: JSON.stringify(payload),
307
+ signal: request.signal,
308
+ dispatcher: getNativeSseDispatcher(),
309
+ });
310
+
311
+ if (!response.ok) {
312
+ const body = await response.text().catch(() => "");
313
+ throw new Error(`provider request failed (${response.status}): ${clipText(body, 500)}`);
314
+ }
315
+
316
+ const contentType = String(response.headers && typeof response.headers.get === "function"
317
+ ? response.headers.get("content-type") || "" : "");
318
+ if (/application\/(?:[a-z0-9.+-]*\+)?json\b/i.test(contentType)
319
+ || !response.body || typeof response.body.getReader !== "function") {
320
+ const data = await response.json();
321
+ return onNonStream(data);
322
+ }
323
+
324
+ const reader = response.body.getReader();
325
+ const decoder = new TextDecoder();
326
+ let rawBuffer = "";
327
+ let sawDone = false;
328
+
329
+ while (true) {
330
+ const { done, value } = await reader.read();
331
+ if (done) break;
332
+
333
+ rawBuffer += decoder.decode(value, { stream: true });
334
+ const parsed = parseSseBlocks(rawBuffer);
335
+ rawBuffer = parsed.rest;
336
+
337
+ for (const block of parsed.blocks) {
338
+ const { event, data } = parseSseEventBlock(block);
339
+ if (!data) continue;
340
+ if (data === "[DONE]") {
341
+ // Stop reading after this batch instead of waiting for the server
342
+ // to close the connection, but keep the buffered tail and finish
343
+ // the blocks already parsed alongside [DONE] instead of silently
344
+ // dropping them.
345
+ sawDone = true;
346
+ continue;
347
+ }
348
+
349
+ onEvent({ event, data });
350
+ }
351
+
352
+ if (sawDone) break;
353
+ }
354
+
355
+ if (typeof onTail === "function") {
356
+ onTail(rawBuffer);
357
+ }
358
+
359
+ return buildResult();
360
+ } catch (err) {
361
+ if (request.timedOut()) {
362
+ const timeoutError = new Error(`CLI timeout (${normalizeTimeoutMs(timeoutMs)}ms)`);
363
+ timeoutError.code = "timeout";
364
+ throw timeoutError;
365
+ }
366
+ if (signal && typeof signal === "object" && signal.aborted) {
367
+ const cancelError = new Error("CLI cancelled");
368
+ cancelError.code = "cancelled";
369
+ throw cancelError;
370
+ }
371
+ throw enrichProviderTransportError(err);
372
+ } finally {
373
+ request.cleanup();
374
+ }
375
+ }
376
+
377
+ async function runOpenAiLikeTurn({
378
+ url = "",
379
+ apiKey = "",
380
+ requestHeaders = {},
381
+ model = "",
382
+ provider = "",
383
+ messages = [],
384
+ tools = [],
385
+ onTextDelta = null,
386
+ onThinkingDelta = null,
387
+ onPhase = null,
388
+ signal = null,
389
+ timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
390
+ } = {}) {
391
+ const normalizedProvider = normalizeProvider(provider);
392
+ const payload = {
393
+ model: normalizedProvider === "kimi" ? normalizeKimiModel(model) : model,
394
+ max_tokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
395
+ messages,
396
+ tools,
397
+ tool_choice: "auto",
398
+ stream: true,
399
+ // Ask for the terminal usage chunk so token/cache accounting works.
400
+ stream_options: { include_usage: true },
401
+ // Kimi k3 rejects any temperature other than 1.
402
+ temperature: normalizedProvider === "kimi" ? 1 : 0,
403
+ };
404
+ const reasoningEffort = resolveReasoningEffort();
405
+ if (reasoningEffort) {
406
+ // OpenAI-compatible gateways that support reasoning models accept this;
407
+ // unknown fields are typically ignored by plain chat models.
408
+ payload.reasoning_effort = reasoningEffort;
409
+ }
410
+
411
+ const headers = normalizedProvider === "kimi"
412
+ ? buildKimiHeaders({ apiKey, stream: true })
413
+ : { "content-type": "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) };
414
+ Object.assign(headers, requestHeaders);
415
+
416
+ const toolCallMap = new Map();
417
+ const announcedToolNames = new Set();
418
+ let responseText = "";
419
+ let nextSyntheticIndex = 0;
420
+ let lastSyntheticIndex = -1;
421
+ let streamUsage = null;
422
+
423
+ return runSseRequest({
424
+ url,
425
+ headers,
426
+ payload,
427
+ signal,
428
+ timeoutMs,
429
+ onPhase,
430
+ onNonStream: (data) => {
431
+ const message = data && data.choices && data.choices[0] && data.choices[0].message
432
+ ? data.choices[0].message
433
+ : {};
434
+ const text = typeof message.content === "string" ? message.content : "";
435
+ const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
436
+ if (text && typeof onTextDelta === "function") {
437
+ onTextDelta(text);
438
+ }
439
+ return {
440
+ text,
441
+ toolCalls,
442
+ usage: readOpenAiUsage(data && data.usage),
443
+ };
444
+ },
445
+ onEvent: ({ data }) => {
446
+ const chunk = parseJsonSafe(data, null);
447
+ if (!chunk || typeof chunk !== "object") return;
448
+
449
+ // The usage chunk carries empty choices, so read it before the
450
+ // choice guard below; latest wins (it reports whole-turn totals).
451
+ const chunkUsage = readOpenAiUsage(chunk.usage);
452
+ if (chunkUsage) streamUsage = chunkUsage;
453
+
454
+ const choice = chunk.choices && chunk.choices[0] ? chunk.choices[0] : null;
455
+ if (!choice || typeof choice !== "object") return;
456
+
457
+ const delta = choice.delta && typeof choice.delta === "object" ? choice.delta : {};
458
+
459
+ const reasoningChunk = typeof delta.reasoning_content === "string"
460
+ ? delta.reasoning_content
461
+ : (typeof delta.reasoning === "string" ? delta.reasoning : "");
462
+ if (reasoningChunk) {
463
+ emitPhase(onPhase, { type: "thinking_delta", text: reasoningChunk });
464
+ if (typeof onThinkingDelta === "function") {
465
+ onThinkingDelta(reasoningChunk);
466
+ }
467
+ }
468
+
469
+ if (typeof delta.content === "string" && delta.content) {
470
+ responseText += delta.content;
471
+ emitPhase(onPhase, { type: "text_delta", text: delta.content });
472
+ if (typeof onTextDelta === "function") {
473
+ onTextDelta(delta.content);
474
+ }
475
+ }
476
+
477
+ if (Array.isArray(delta.tool_calls)) {
478
+ for (const callPart of delta.tool_calls) {
479
+ let index;
480
+ if (Number.isFinite(callPart.index)) {
481
+ index = callPart.index;
482
+ } else if (typeof callPart.id === "string" && callPart.id) {
483
+ // Provider omitted index: a chunk carrying an id starts a new
484
+ // call, so give it its own synthetic index instead of
485
+ // collapsing every call into slot 0.
486
+ while (toolCallMap.has(nextSyntheticIndex)) nextSyntheticIndex += 1;
487
+ index = nextSyntheticIndex;
488
+ nextSyntheticIndex += 1;
489
+ lastSyntheticIndex = index;
490
+ } else if (lastSyntheticIndex >= 0) {
491
+ // No index and no id: continuation of the latest synthetic call.
492
+ index = lastSyntheticIndex;
493
+ } else {
494
+ index = 0;
495
+ }
496
+ const previous = toolCallMap.get(index) || {
497
+ id: "",
498
+ type: "function",
499
+ function: {
500
+ name: "",
501
+ arguments: "",
502
+ },
503
+ };
504
+
505
+ if (typeof callPart.id === "string" && callPart.id) previous.id = callPart.id;
506
+ if (callPart.function && typeof callPart.function === "object") {
507
+ if (typeof callPart.function.name === "string" && callPart.function.name) {
508
+ previous.function.name = callPart.function.name;
509
+ }
510
+ if (typeof callPart.function.arguments === "string" && callPart.function.arguments) {
511
+ previous.function.arguments += callPart.function.arguments;
512
+ }
513
+ }
514
+
515
+ toolCallMap.set(index, previous);
516
+
517
+ const toolName = previous.function.name;
518
+ const announceKey = `${index}:${toolName}`;
519
+ if (toolName && !announcedToolNames.has(announceKey)) {
520
+ announcedToolNames.add(announceKey);
521
+ emitPhase(onPhase, { type: "tool_request", name: toolName });
522
+ }
523
+ }
524
+ }
525
+ },
526
+ onTail: (rawBuffer) => {
527
+ if (!rawBuffer.trim()) return;
528
+ const fallbackBlock = parseSseDataBlock(rawBuffer);
529
+ if (fallbackBlock && fallbackBlock !== "[DONE]") {
530
+ const chunk = parseJsonSafe(fallbackBlock, null);
531
+ const tailUsage = readOpenAiUsage(chunk && chunk.usage);
532
+ if (tailUsage) streamUsage = tailUsage;
533
+ const choice = chunk && chunk.choices && chunk.choices[0] ? chunk.choices[0] : null;
534
+ if (choice && choice.delta && typeof choice.delta.content === "string" && choice.delta.content) {
535
+ responseText += choice.delta.content;
536
+ if (typeof onTextDelta === "function") {
537
+ onTextDelta(choice.delta.content);
538
+ }
539
+ }
540
+ }
541
+ },
542
+ buildResult: () => ({
543
+ text: responseText,
544
+ toolCalls: Array.from(toolCallMap.entries())
545
+ .sort((a, b) => a[0] - b[0])
546
+ .map((entry) => entry[1]),
547
+ usage: streamUsage,
548
+ }),
549
+ });
550
+ }
551
+
552
+ function currentGrokClientVersion() {
553
+ return String(process.env.UFOO_GROK_CLIENT_VERSION || "0.2.120").trim() || "0.2.120";
554
+ }
555
+
556
+ function isGrokCliProxyUrl(url = "") {
557
+ try {
558
+ return new URL(String(url || "")).hostname.toLowerCase() === "cli-chat-proxy.grok.com";
559
+ } catch {
560
+ return false;
561
+ }
562
+ }
563
+
564
+ function currentKimiClientVersion() {
565
+ try {
566
+ return String(process.env.UFOO_KIMI_CLIENT_VERSION || require("../../../package.json").version || "dev").trim() || "dev";
567
+ } catch {
568
+ return "dev";
569
+ }
570
+ }
571
+
572
+ function buildKimiHeaders({ apiKey = "", stream = true } = {}) {
573
+ const version = currentKimiClientVersion();
574
+ const headers = {
575
+ "content-type": "application/json",
576
+ "User-Agent": `ufoo/${version}`,
577
+ "X-Msh-Platform": "ufoo",
578
+ "X-Msh-Version": version,
579
+ "X-Msh-Device-Name": os.hostname(),
580
+ "X-Msh-Device-Model": `${process.platform} ${process.arch}`,
581
+ "X-Msh-Device-Id": String(process.env.KIMI_DEVICE_ID || "ufoo-kimi-device").trim() || "ufoo-kimi-device",
582
+ Accept: stream ? "text/event-stream" : "application/json",
583
+ };
584
+ if (apiKey) headers.authorization = `Bearer ${apiKey}`;
585
+ return headers;
586
+ }
587
+
588
+ function buildResponsesHeaders({ provider = "", apiKey = "", sessionId = "", accountId = "", url = "" } = {}) {
589
+ const normalizedProvider = normalizeProvider(provider);
590
+ const headers = {
591
+ "content-type": "application/json",
592
+ Accept: "text/event-stream",
593
+ Connection: "Keep-Alive",
594
+ };
595
+ if (apiKey) headers.authorization = `Bearer ${apiKey}`;
596
+
597
+ if (normalizedProvider === "codex") {
598
+ headers["User-Agent"] = String(
599
+ process.env.UFOO_CODEX_USER_AGENT
600
+ || "codex-tui/0.118.0 (Mac OS 26.3.1; arm64) iTerm.app/3.6.9 (codex-tui; 0.118.0)"
601
+ );
602
+ headers.Originator = "codex-tui";
603
+ headers["Session-Id"] = String(sessionId || randomUUID());
604
+ if (accountId) headers["Chatgpt-Account-Id"] = String(accountId);
605
+ }
606
+
607
+ if (normalizedProvider === "grok-build" || normalizedProvider === "xai") {
608
+ const version = currentGrokClientVersion();
609
+ if (sessionId) headers["x-grok-conv-id"] = String(sessionId);
610
+ if (isGrokCliProxyUrl(url)) {
611
+ headers["X-XAI-Token-Auth"] = "xai-grok-cli";
612
+ headers["x-grok-client-version"] = version;
613
+ headers["x-grok-client-identifier"] = "grok-shell";
614
+ headers["x-authenticateresponse"] = "authenticate-response";
615
+ headers["User-Agent"] = `xai-grok-workspace/${version}`;
616
+ } else if (normalizedProvider === "grok-build") {
617
+ // CLIProxyAPI selects the Grok Build route from this identity.
618
+ headers["User-Agent"] = `grok-shell/${version}`;
619
+ }
620
+ }
621
+
622
+ return headers;
623
+ }
624
+
625
+ async function runResponsesTurn({
626
+ url = "",
627
+ apiKey = "",
628
+ requestHeaders = {},
629
+ requestProfile = "",
630
+ model = "",
631
+ provider = "",
632
+ systemPrompt = "",
633
+ messages = [],
634
+ tools = [],
635
+ sessionId = "",
636
+ accountId = "",
637
+ onTextDelta = null,
638
+ onThinkingDelta = null,
639
+ onPhase = null,
640
+ signal = null,
641
+ timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
642
+ } = {}) {
643
+ const payload = buildResponsesPayload({
644
+ model,
645
+ instructions: systemPrompt,
646
+ messages,
647
+ tools,
648
+ maxOutputTokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
649
+ reasoningEffort: resolveReasoningEffort(),
650
+ provider: normalizeProvider(provider),
651
+ });
652
+ const headers = buildResponsesHeaders({ provider, apiKey, sessionId, accountId, url });
653
+ Object.assign(headers, requestHeaders);
654
+ if (requestProfile === "codex-subscription") delete payload.max_output_tokens;
655
+ const frames = [];
656
+
657
+ const consumeFrame = (frame = {}) => {
658
+ const data = frame && frame.data && typeof frame.data === "object"
659
+ ? frame.data
660
+ : parseJsonSafe(frame && frame.data, null);
661
+ if (!data || isResponsesKeepalive(frame && frame.event, data)) return;
662
+ frames.push({ event: String(frame.event || data.type || ""), data });
663
+
664
+ const delta = responseEventDelta({ event: data.type || frame.event, data });
665
+ if (delta.reasoning) {
666
+ emitPhase(onPhase, { type: "thinking_delta", text: delta.reasoning });
667
+ if (typeof onThinkingDelta === "function") onThinkingDelta(delta.reasoning);
668
+ }
669
+ if (delta.text) {
670
+ emitPhase(onPhase, { type: "text_delta", text: delta.text });
671
+ if (typeof onTextDelta === "function") onTextDelta(delta.text);
672
+ }
673
+
674
+ const item = data.item && typeof data.item === "object" ? data.item : null;
675
+ if (
676
+ item
677
+ && item.type === "function_call"
678
+ && item.name
679
+ && (data.type === "response.output_item.added" || data.type === "response.output_item.done")
680
+ ) {
681
+ emitPhase(onPhase, { type: "tool_request", name: String(item.name) });
682
+ }
683
+ };
684
+
685
+ return runSseRequest({
686
+ url,
687
+ headers,
688
+ payload,
689
+ signal,
690
+ timeoutMs,
691
+ onPhase,
692
+ onNonStream: (data) => {
693
+ const parsed = parseResponsesEvents([{ event: data && data.type ? data.type : "response", data }], {
694
+ assumeCompleted: true,
695
+ });
696
+ if (parsed.reasoning && typeof onThinkingDelta === "function") onThinkingDelta(parsed.reasoning);
697
+ if (parsed.text && typeof onTextDelta === "function") onTextDelta(parsed.text);
698
+ return {
699
+ text: parsed.text,
700
+ toolCalls: parsed.toolCalls,
701
+ outputItems: parsed.outputItems,
702
+ usage: parsed.usage,
703
+ response: parsed.response,
704
+ responseId: parsed.responseId,
705
+ };
706
+ },
707
+ onEvent: consumeFrame,
708
+ onTail: (rawBuffer) => {
709
+ if (!String(rawBuffer || "").trim()) return;
710
+ const tail = parseResponsesSsePayload(rawBuffer);
711
+ for (const data of tail.events || []) consumeFrame({ event: data.type, data });
712
+ },
713
+ buildResult: () => {
714
+ const parsed = parseResponsesEvents(frames);
715
+ if (!parsed.terminal) {
716
+ throw new Error("Responses stream ended before response.completed or response.incomplete");
717
+ }
718
+ return {
719
+ text: parsed.text,
720
+ toolCalls: parsed.toolCalls,
721
+ outputItems: parsed.outputItems,
722
+ usage: parsed.usage,
723
+ response: parsed.response,
724
+ responseId: parsed.responseId,
725
+ incompleteDetails: parsed.incompleteDetails,
726
+ };
727
+ },
728
+ });
729
+ }
730
+
731
+ function normalizeAnthropicMessageContent(raw = []) {
732
+ if (!Array.isArray(raw)) return [];
733
+ return raw
734
+ .map((item) => {
735
+ if (!item || typeof item !== "object") return null;
736
+ if (item.type === "text") {
737
+ return {
738
+ type: "text",
739
+ text: String(item.text || ""),
740
+ };
741
+ }
742
+ if (item.type === "thinking") {
743
+ return {
744
+ type: "thinking",
745
+ thinking: String(item.thinking || ""),
746
+ signature: String(item.signature || ""),
747
+ };
748
+ }
749
+ if (item.type === "tool_use") {
750
+ return {
751
+ type: "tool_use",
752
+ id: String(item.id || ""),
753
+ name: String(item.name || ""),
754
+ input: item.input && typeof item.input === "object" && !Array.isArray(item.input)
755
+ ? item.input
756
+ : {},
757
+ };
758
+ }
759
+ return null;
760
+ })
761
+ .filter(Boolean);
762
+ }
763
+
764
+ function extractAnthropicToolCalls(content = []) {
765
+ return normalizeAnthropicMessageContent(content)
766
+ .filter((item) => item.type === "tool_use")
767
+ .map((item) => ({
768
+ id: String(item.id || `tool_${randomUUID()}`),
769
+ name: String(item.name || ""),
770
+ args: item.input && typeof item.input === "object" && !Array.isArray(item.input)
771
+ ? item.input
772
+ : {},
773
+ }));
774
+ }
775
+
776
+ // Mark the newest message with a cache breakpoint so the append-only history
777
+ // prefix is served from the prompt cache. The payload gets a copy: stamping
778
+ // cache_control onto the shared history array would leave stale breakpoints
779
+ // behind as later turns append, eventually exceeding the 4-breakpoint limit.
780
+ function withAnthropicCacheBreakpoint(messages = []) {
781
+ if (!Array.isArray(messages) || messages.length === 0) return messages;
782
+ const copy = messages.slice();
783
+ const lastIndex = copy.length - 1;
784
+ const last = copy[lastIndex];
785
+ if (!last || typeof last !== "object" || Array.isArray(last)) return copy;
786
+ if (typeof last.content === "string") {
787
+ if (!last.content) return copy;
788
+ copy[lastIndex] = {
789
+ ...last,
790
+ content: [
791
+ {
792
+ type: "text",
793
+ text: last.content,
794
+ cache_control: { ...ANTHROPIC_CACHE_CONTROL },
795
+ },
796
+ ],
797
+ };
798
+ return copy;
799
+ }
800
+ if (Array.isArray(last.content) && last.content.length > 0) {
801
+ const blocks = last.content.slice();
802
+ const blockIndex = blocks.length - 1;
803
+ const block = blocks[blockIndex];
804
+ if (block && typeof block === "object" && !Array.isArray(block)) {
805
+ blocks[blockIndex] = {
806
+ ...block,
807
+ cache_control: { ...ANTHROPIC_CACHE_CONTROL },
808
+ };
809
+ copy[lastIndex] = {
810
+ ...last,
811
+ content: blocks,
812
+ };
813
+ }
814
+ }
815
+ return copy;
816
+ }
817
+
818
+ async function runAnthropicTurn({
819
+ url = "",
820
+ apiKey = "",
821
+ requestHeaders = {},
822
+ model = "",
823
+ systemPrompt = "",
824
+ systemBlocks = null,
825
+ messages = [],
826
+ tools = [],
827
+ onTextDelta = null,
828
+ onThinkingDelta = null,
829
+ onPhase = null,
830
+ signal = null,
831
+ timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
832
+ } = {}) {
833
+ const payload = {
834
+ model,
835
+ max_tokens: resolveMaxTokens(DEFAULT_ANTHROPIC_MAX_TOKENS),
836
+ messages: withAnthropicCacheBreakpoint(messages),
837
+ tools: tools.map((spec) => ({ name: spec.function.name, description: spec.function.description, input_schema: spec.function.parameters })),
838
+ stream: true,
839
+ };
840
+ const thinkingBudget = Math.min(resolveThinkingBudgetTokens(), payload.max_tokens - 1);
841
+ if (thinkingBudget >= 1024) {
842
+ payload.thinking = { type: "enabled", budget_tokens: thinkingBudget };
843
+ }
844
+ if (Array.isArray(systemBlocks) && systemBlocks.length > 0) {
845
+ payload.system = systemBlocksToAnthropicPayload(systemBlocks);
846
+ } else {
847
+ const systemText = String(systemPrompt || "").trim();
848
+ if (systemText) {
849
+ payload.system = [
850
+ {
851
+ type: "text",
852
+ text: systemText,
853
+ cache_control: { ...ANTHROPIC_CACHE_CONTROL },
854
+ },
855
+ ];
856
+ }
857
+ }
858
+
859
+ const headers = {
860
+ "content-type": "application/json",
861
+ "anthropic-version": "2023-06-01",
862
+ };
863
+ if (apiKey) {
864
+ headers["x-api-key"] = apiKey;
865
+ }
866
+ Object.assign(headers, requestHeaders);
867
+
868
+ const blockMap = new Map();
869
+ let responseText = "";
870
+ let nextSyntheticBlockIndex = 0;
871
+ let lastBlockIndex = -1;
872
+ const turnUsage = {
873
+ input: 0,
874
+ output: 0,
875
+ cacheRead: 0,
876
+ cacheCreation: 0,
877
+ inputIncludesCache: false,
878
+ };
879
+
880
+ return runSseRequest({
881
+ url,
882
+ headers,
883
+ payload,
884
+ signal,
885
+ timeoutMs,
886
+ onPhase,
887
+ onNonStream: (data) => {
888
+ const content = normalizeAnthropicMessageContent(data && data.content);
889
+ const text = content
890
+ .filter((item) => item.type === "text")
891
+ .map((item) => item.text)
892
+ .join("");
893
+ if (text && typeof onTextDelta === "function") {
894
+ onTextDelta(text);
895
+ }
896
+ addUsageTotals(turnUsage, readAnthropicUsage(data && data.usage, { includeOutput: true }));
897
+ return {
898
+ text,
899
+ assistantContent: content,
900
+ toolCalls: extractAnthropicToolCalls(content),
901
+ usage: turnUsage,
902
+ };
903
+ },
904
+ onEvent: ({ event, data }) => {
905
+ const payloadChunk = parseJsonSafe(data, null);
906
+ if (!payloadChunk || typeof payloadChunk !== "object") return;
907
+
908
+ if (event === "error") {
909
+ const errMsg = payloadChunk.error && payloadChunk.error.message
910
+ ? String(payloadChunk.error.message)
911
+ : "anthropic stream error";
912
+ throw new Error(errMsg);
913
+ }
914
+
915
+ if (event === "message_start") {
916
+ const messageUsage = readAnthropicUsage(
917
+ payloadChunk.message && typeof payloadChunk.message === "object"
918
+ ? payloadChunk.message.usage
919
+ : null
920
+ );
921
+ if (messageUsage) {
922
+ turnUsage.input = messageUsage.input;
923
+ turnUsage.cacheRead = messageUsage.cacheRead;
924
+ turnUsage.cacheCreation = messageUsage.cacheCreation;
925
+ }
926
+ return;
927
+ }
928
+
929
+ if (event === "message_delta") {
930
+ const deltaUsage = payloadChunk.usage && typeof payloadChunk.usage === "object"
931
+ ? payloadChunk.usage
932
+ : {};
933
+ turnUsage.output += toUsageInt(deltaUsage.output_tokens);
934
+ return;
935
+ }
936
+
937
+ if (event === "content_block_start") {
938
+ let index;
939
+ if (Number.isFinite(payloadChunk.index)) {
940
+ index = payloadChunk.index;
941
+ } else {
942
+ // Provider omitted index: each start opens a new block, so give
943
+ // it its own synthetic index instead of collapsing every block
944
+ // into slot 0.
945
+ while (blockMap.has(nextSyntheticBlockIndex)) nextSyntheticBlockIndex += 1;
946
+ index = nextSyntheticBlockIndex;
947
+ nextSyntheticBlockIndex += 1;
948
+ }
949
+ lastBlockIndex = index;
950
+ const contentBlock = payloadChunk.content_block && typeof payloadChunk.content_block === "object"
951
+ ? payloadChunk.content_block
952
+ : {};
953
+
954
+ if (contentBlock.type === "text") {
955
+ blockMap.set(index, {
956
+ order: index,
957
+ type: "text",
958
+ text: String(contentBlock.text || ""),
959
+ });
960
+ } else if (contentBlock.type === "thinking") {
961
+ blockMap.set(index, {
962
+ order: index,
963
+ type: "thinking",
964
+ text: String(contentBlock.thinking || ""),
965
+ signature: String(contentBlock.signature || ""),
966
+ });
967
+ } else if (contentBlock.type === "tool_use") {
968
+ blockMap.set(index, {
969
+ order: index,
970
+ type: "tool_use",
971
+ id: String(contentBlock.id || ""),
972
+ name: String(contentBlock.name || ""),
973
+ input: contentBlock.input && typeof contentBlock.input === "object" && !Array.isArray(contentBlock.input)
974
+ ? { ...contentBlock.input }
975
+ : {},
976
+ inputJson: "",
977
+ });
978
+ const toolName = String(contentBlock.name || "");
979
+ if (toolName) {
980
+ emitPhase(onPhase, { type: "tool_request", name: toolName });
981
+ }
982
+ }
983
+ return;
984
+ }
985
+
986
+ if (event === "content_block_delta") {
987
+ let index;
988
+ if (Number.isFinite(payloadChunk.index)) {
989
+ index = payloadChunk.index;
990
+ } else if (lastBlockIndex >= 0) {
991
+ // No index: continuation of the most recently started block.
992
+ index = lastBlockIndex;
993
+ } else {
994
+ index = 0;
995
+ }
996
+ const delta = payloadChunk.delta && typeof payloadChunk.delta === "object"
997
+ ? payloadChunk.delta
998
+ : {};
999
+ const current = blockMap.get(index) || { order: index, type: "text", text: "" };
1000
+
1001
+ if (delta.type === "text_delta") {
1002
+ const deltaText = String(delta.text || "");
1003
+ current.type = "text";
1004
+ current.text = `${String(current.text || "")}${deltaText}`;
1005
+ blockMap.set(index, current);
1006
+ if (deltaText) {
1007
+ responseText += deltaText;
1008
+ emitPhase(onPhase, { type: "text_delta", text: deltaText });
1009
+ if (typeof onTextDelta === "function") {
1010
+ onTextDelta(deltaText);
1011
+ }
1012
+ }
1013
+ return;
1014
+ }
1015
+
1016
+ if (delta.type === "thinking_delta") {
1017
+ const deltaText = String(delta.thinking || "");
1018
+ current.type = "thinking";
1019
+ current.text = `${String(current.text || "")}${deltaText}`;
1020
+ blockMap.set(index, current);
1021
+ if (deltaText) {
1022
+ emitPhase(onPhase, { type: "thinking_delta", text: deltaText });
1023
+ if (typeof onThinkingDelta === "function") {
1024
+ onThinkingDelta(deltaText);
1025
+ }
1026
+ }
1027
+ return;
1028
+ }
1029
+
1030
+ if (delta.type === "signature_delta") {
1031
+ // Signed thinking blocks must be replayed verbatim on later turns
1032
+ // (tool-use continuation contract), so accumulate the signature
1033
+ // alongside the thinking text.
1034
+ current.type = "thinking";
1035
+ current.signature = `${String(current.signature || "")}${String(delta.signature || "")}`;
1036
+ blockMap.set(index, current);
1037
+ return;
1038
+ }
1039
+
1040
+ if (delta.type === "input_json_delta") {
1041
+ current.type = "tool_use";
1042
+ current.inputJson = `${String(current.inputJson || "")}${String(delta.partial_json || "")}`;
1043
+ blockMap.set(index, current);
1044
+ return;
1045
+ }
1046
+ }
1047
+ },
1048
+ buildResult: () => {
1049
+ const assistantContent = Array.from(blockMap.values())
1050
+ .sort((a, b) => a.order - b.order)
1051
+ .map((item) => {
1052
+ if (item.type === "thinking") {
1053
+ // Kept (with signature) so tool-use continuation turns can
1054
+ // replay the thinking blocks the API requires.
1055
+ return {
1056
+ type: "thinking",
1057
+ thinking: String(item.text || ""),
1058
+ signature: String(item.signature || ""),
1059
+ };
1060
+ }
1061
+
1062
+ if (item.type === "text") {
1063
+ return {
1064
+ type: "text",
1065
+ text: String(item.text || ""),
1066
+ };
1067
+ }
1068
+
1069
+ const inputFromDelta = normalizeToolCallArgs(item.inputJson || "");
1070
+ const mergedInput = {
1071
+ ...(item.input && typeof item.input === "object" ? item.input : {}),
1072
+ ...(inputFromDelta && typeof inputFromDelta === "object" ? inputFromDelta : {}),
1073
+ };
1074
+ return {
1075
+ type: "tool_use",
1076
+ id: String(item.id || `tool_${randomUUID()}`),
1077
+ name: String(item.name || ""),
1078
+ input: mergedInput,
1079
+ };
1080
+ });
1081
+
1082
+ if (!responseText) {
1083
+ responseText = assistantContent
1084
+ .filter((item) => item.type === "text")
1085
+ .map((item) => item.text)
1086
+ .join("");
1087
+ }
1088
+
1089
+ return {
1090
+ text: responseText,
1091
+ assistantContent,
1092
+ toolCalls: extractAnthropicToolCalls(assistantContent),
1093
+ usage: turnUsage,
1094
+ };
1095
+ },
1096
+ });
1097
+ }
1098
+
1099
+ const {
1100
+ createOpenAiChatTransport,
1101
+ createOpenAiResponsesTransport,
1102
+ createAnthropicMessagesTransport,
1103
+ } = require("./transports");
1104
+
1105
+ // Transport descriptors: wire-format only. Plan Mode / leases / policy live in the loop.
1106
+ const TRANSPORTS = {
1107
+ "openai-chat": createOpenAiChatTransport({
1108
+ resolveUrl: resolveCompletionUrl,
1109
+ runTurn: runOpenAiLikeTurn,
1110
+ normalizeToolName: (name) => String(name || "").trim().toLowerCase(),
1111
+ normalizeToolCallArgs,
1112
+ toJsonString,
1113
+ clipText,
1114
+ }),
1115
+ "openai-responses": createOpenAiResponsesTransport({
1116
+ resolveUrl: resolveResponsesUrl,
1117
+ runTurn: runResponsesTurn,
1118
+ normalizeToolName: (name) => String(name || "").trim().toLowerCase(),
1119
+ normalizeToolCallArgs,
1120
+ toJsonString,
1121
+ clipText,
1122
+ }),
1123
+ "anthropic-messages": createAnthropicMessagesTransport({
1124
+ resolveUrl: resolveAnthropicMessagesUrl,
1125
+ runTurn: runAnthropicTurn,
1126
+ toJsonString,
1127
+ clipText,
1128
+ }),
1129
+ };
1130
+
1131
+ module.exports = {
1132
+ getNativeTransport: (name) => TRANSPORTS[name] || TRANSPORTS["openai-chat"],
1133
+ createNativeSseDispatcher, resolveThinkingBudgetTokens, resolveReasoningEffort,
1134
+ normalizeTimeoutMs, createUsageTotals, cloneMessageList,
1135
+ };