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
@@ -1,195 +1,33 @@
1
- const os = require("os");
1
+ "use strict";
2
+
2
3
  const { randomUUID } = require("crypto");
3
- const { Agent: UndiciAgent } = require("undici");
4
- const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../config");
5
- const {
6
- readKimiAccessToken,
7
- resolveKimiUpstreamCredentials,
8
- } = require("../agents/providers/credentials/kimi");
4
+ const { loadConfig } = require("../config");
5
+ const { resolveKimiUpstreamCredentials } = require("../agents/providers/credentials/kimi");
9
6
  const { resolveCodexUpstreamCredentials } = require("../agents/providers/credentials/codex");
10
- const dispatchTools = require("./dispatch");
11
- const runToolCall = dispatchTools.runToolCall;
12
- const runToolCallAsync = typeof dispatchTools.runToolCallAsync === "function"
13
- ? dispatchTools.runToolCallAsync
14
- : async (...args) => runToolCall(...args);
15
- const { runTaskRunTool } = require("./tools/taskRun");
16
- const { appendUsageRecord } = require("./usageStore");
17
- const {
18
- persistToolResultToContext,
19
- sanitizeModelMessages,
20
- } = require("./context/assembler");
21
- const { systemBlocksToAnthropicPayload } = require("./context/promptLayers");
22
- const { retireMessageImages } = require("./providers/visionBlocks");
7
+ const { resolveRuntimeConfig, resolveTransport, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl, DEFAULT_OPENAI_BASE_URL } = require("../agents/providers/runtimeConfig");
8
+ const { getNativeTransport, createNativeSseDispatcher, resolveThinkingBudgetTokens, resolveReasoningEffort, normalizeTimeoutMs, createUsageTotals, cloneMessageList } = require("../agents/providers/nativeTransport");
9
+ const { createAgentRuntime } = require("../agents/runtime/createAgentRuntime");
10
+ const { createCodingCapability } = require("../agents/capabilities/coding");
11
+ const { createPlanningCapability } = require("../agents/capabilities/planning");
12
+ const { createSkillsCapability } = require("../agents/capabilities/skills");
13
+ const codingProfile = require("../agents/profiles/coding");
14
+ const { runCoreToolAsync } = require("./tools/executor");
15
+ const { sanitizeModelMessages } = require("./context/assembler");
16
+ const { retireMessageImages } = require("../agents/providers/transports/visionBlocks");
23
17
  const { resolveMaxToolCalls } = require("./toolBudget");
24
- const { ToolLoopGuard } = require("./toolLoopGuard");
25
- const { parseStructuredSideEffects } = require("./context/stateCommit");
26
- const {
27
- emptyExecutionState,
28
- } = require("./context/executionSegment");
29
- const {
30
- normalizePlanGraphCommand,
31
- runPlanGraphCommand,
32
- activePlanRequiresExpansion,
33
- } = require("./context/planGraphService");
34
- const { planModeBlocksDirectTool } = require("./context/planMode");
35
- const {
36
- drainUserPrompts,
37
- clearUserPrompts,
38
- formatUserReminderMessage,
39
- ensurePendingUserPrompts,
40
- shouldAutoContinuePlan,
41
- buildPlanAutoContinueReminder,
42
- } = require("./context/userNudge");
43
- const {
44
- drainAgentMailboxForTurn,
45
- shouldAutoContinueForTaskWake,
46
- listTaskRunsAwaitingModel,
47
- } = require("./runtime/agentWakeup");
48
- const {
49
- shouldIsolateTaskFocusTurn,
50
- buildIsolatedTaskFocusTurn,
51
- sanitizeToolResultForModel,
52
- } = require("./runtime/taskFocusContext");
53
- const {
54
- runAskUserTool,
55
- syncInteractionFromPlanGraph,
56
- hasPendingUserInteraction,
57
- getPendingUserInteraction,
58
- } = require("./context/userInteraction");
59
- const { checkWriteAllowed } = require("./runtime/workspaceLease");
60
- const {
61
- createToolCallLedger,
62
- declareCalls,
63
- markExecuting,
64
- deferCall,
65
- resolveCall,
66
- snapshotLedger,
67
- runProviderTurnGate,
68
- withFaultPoint,
69
- checkFaultPoint,
70
- materializeResolvedToolResults,
71
- materializeAnswerToolResult,
72
- } = require("./protocol");
73
- const { stableStringify } = require("./context/stableJson");
74
- const { getReadToolDescription } = require("../agents/prompts/native/toolDescriptions/read");
75
- const { getReadImageToolDescription } = require("../agents/prompts/native/toolDescriptions/readImage");
76
- const { getWriteToolDescription } = require("../agents/prompts/native/toolDescriptions/write");
77
- const { getEditToolDescription } = require("../agents/prompts/native/toolDescriptions/edit");
78
- const { getBashToolDescription } = require("../agents/prompts/native/toolDescriptions/bash");
79
- const {
80
- buildResponsesPayload,
81
- isResponsesKeepalive,
82
- responseEventDelta,
83
- parseResponsesEvents,
84
- parseResponsesSsePayload,
85
- } = require("./providers/responsesProtocol");
18
+ const { clearUserPrompts } = require("./context/userNudge");
19
+ const { runProviderTurnGate, resolveCall, checkFaultPoint, materializeAnswerToolResult } = require("./protocol");
20
+ const { appendUsageRecord } = require("./usageStore");
21
+ const { buildCoreToolSpecs, buildAnthropicToolSpecs } = require("./tools/specs");
86
22
 
87
- const CORE_TOOL_NAMES = new Set([
88
- "read",
89
- "read_image",
90
- "write",
91
- "edit",
92
- "bash",
93
- "artifact_read",
94
- "plan_graph",
95
- "task_run",
96
- "ask_user",
97
- ]);
98
- const EXECUTABLE_GRAPH_TOOLS = new Set([
99
- "read",
100
- "read_image",
101
- "write",
102
- "edit",
103
- "bash",
104
- "artifact_read",
105
- ]);
106
- const CONTROL_PLANE_TOOLS = new Set(["plan_graph", "task_run"]);
107
- const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
108
- const DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1";
109
- const DEFAULT_KIMI_BASE_URL = "https://api.kimi.com/coding/v1";
110
- const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex";
111
- const DEFAULT_XAI_BASE_URL = "https://api.x.ai/v1";
112
- const DEFAULT_GROK_BUILD_BASE_URL = DEFAULT_XAI_BASE_URL;
113
- const DEFAULT_GROK_BUILD_MODEL = "grok-4.6";
114
- const DEFAULT_KIMI_MODEL = "k3";
115
- // No tool-call cap unless explicitly configured by the caller or environment.
116
- const DEFAULT_MAX_NATIVE_TOOL_CALLS = null;
23
+ const DEFAULT_NATIVE_TIMEOUT_MS = 43200000;
117
24
  const DEFAULT_MAX_NATIVE_TOOL_ERRORS = 20;
118
- const MAX_EMPTY_TERMINAL_RETRIES = 2;
119
- const DEFAULT_NATIVE_TIMEOUT_MS = 43200000; // 12 hours
120
- // Node's fetch is backed by Undici, whose default headers/body idle timeout is
121
- // 300 seconds. Reasoning providers can legitimately stay silent longer than
122
- // that between SSE chunks, so leave the absolute deadline to our existing
123
- // AbortController instead of inheriting Undici's shorter hidden deadline.
124
- const NATIVE_SSE_DISPATCHER_OPTIONS = Object.freeze({
125
- headersTimeout: 0,
126
- bodyTimeout: 0,
127
- });
128
- /** Max text-only auto-continues while a plan is waiting on a task (per user submit). */
129
25
  const DEFAULT_MAX_PLAN_AUTO_CONTINUES = 24;
130
- // Anthropic Messages rejects max_tokens above the model's real cap (64K on
131
- // current models), so the transports use different defaults. Override either
132
- // via UFOO_UCODE_MAX_TOKENS (positive integer).
133
- const DEFAULT_OPENAI_MAX_TOKENS = 131072;
134
- const DEFAULT_ANTHROPIC_MAX_TOKENS = 64000;
135
- // Extended thinking defaults live in thinkingLevels.js (medium = 10k).
136
- // UFOO_UCODE_THINKING=off|low|medium|high|max selects a preset; numeric
137
- // UFOO_UCODE_THINKING_BUDGET_TOKENS still overrides. 0 disables thinking.
138
- // Prompt caching is GA on the current Messages API: cache_control blocks need
139
- // no anthropic-beta header. Kept as a constant so the marker shape stays in
140
- // one place (system block + last history message, 2 of the 4 allowed
141
- // breakpoints).
142
- const ANTHROPIC_CACHE_CONTROL = Object.freeze({ type: "ephemeral" });
143
-
144
- function nowMs() {
145
- return Date.now();
146
- }
147
-
148
- function normalizeTimeoutMs(value) {
149
- const parsed = Number(value);
150
- if (!Number.isFinite(parsed)) return DEFAULT_NATIVE_TIMEOUT_MS;
151
- return Math.max(1000, Math.floor(parsed));
152
- }
153
-
154
- let nativeSseDispatcher = null;
155
-
156
- function createNativeSseDispatcher() {
157
- return new UndiciAgent({ ...NATIVE_SSE_DISPATCHER_OPTIONS });
158
- }
159
-
160
- function getNativeSseDispatcher() {
161
- if (!nativeSseDispatcher || nativeSseDispatcher.destroyed) {
162
- nativeSseDispatcher = createNativeSseDispatcher();
163
- }
164
- return nativeSseDispatcher;
165
- }
166
-
167
- function enrichProviderTransportError(err) {
168
- if (!err || typeof err !== "object") return err;
169
-
170
- const cause = err.cause && typeof err.cause === "object" ? err.cause : null;
171
- const code = String((cause && cause.code) || err.code || "").trim();
172
- const causeMessage = String((cause && cause.message) || "").trim();
173
- if (!code && !causeMessage) return err;
174
-
175
- const message = String(err.message || "provider transport failed").trim();
176
- const details = [code, causeMessage]
177
- .filter(Boolean)
178
- .filter((value, index, values) => values.indexOf(value) === index)
179
- .join(": ");
180
- if (!details || message.includes(details)) return err;
181
-
182
- const enriched = new Error(`${message} (${details})`);
183
- enriched.code = code || err.code;
184
- enriched.cause = err;
185
- return enriched;
186
- }
187
-
188
- function normalizePositiveInt(value, fallback) {
26
+ const normalizePositiveInt = (value, fallback) => {
189
27
  const parsed = Number.parseInt(String(value || ""), 10);
190
- if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
191
- return Math.floor(parsed);
192
- }
28
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
29
+ };
30
+ const nowMs = () => Date.now();
193
31
 
194
32
  function resolveNativeToolBudget(maxToolCalls, env = process.env) {
195
33
  return {
@@ -198,118 +36,6 @@ function resolveNativeToolBudget(maxToolCalls, env = process.env) {
198
36
  };
199
37
  }
200
38
 
201
- function resolveMaxTokens(fallback) {
202
- return normalizePositiveInt(process.env.UFOO_UCODE_MAX_TOKENS, fallback);
203
- }
204
-
205
- function resolveThinkingBudgetTokens(options = {}) {
206
- const { resolveThinkingFromEnvAndConfig } = require("./thinkingLevels");
207
- const { loadGlobalUcodeConfig } = require("../config");
208
- let configLevel = String(options.configLevel || "").trim();
209
- if (!configLevel) {
210
- try {
211
- configLevel = String((loadGlobalUcodeConfig() || {}).ucodeThinking || "").trim();
212
- } catch {
213
- configLevel = "";
214
- }
215
- }
216
- const resolved = resolveThinkingFromEnvAndConfig({
217
- env: options.env || process.env,
218
- configLevel,
219
- });
220
- return resolved.budgetTokens;
221
- }
222
-
223
- function resolveReasoningEffort(options = {}) {
224
- const { resolveThinkingFromEnvAndConfig } = require("./thinkingLevels");
225
- const { loadGlobalUcodeConfig } = require("../config");
226
- let configLevel = String(options.configLevel || "").trim();
227
- if (!configLevel) {
228
- try {
229
- configLevel = String((loadGlobalUcodeConfig() || {}).ucodeThinking || "").trim();
230
- } catch {
231
- configLevel = "";
232
- }
233
- }
234
- const resolved = resolveThinkingFromEnvAndConfig({
235
- env: options.env || process.env,
236
- configLevel,
237
- });
238
- return resolved.reasoningEffort || "";
239
- }
240
-
241
- function toUsageInt(value) {
242
- const parsed = Number(value);
243
- if (!Number.isFinite(parsed) || parsed <= 0) return 0;
244
- return Math.floor(parsed);
245
- }
246
-
247
- function createUsageTotals() {
248
- return {
249
- turns: 0,
250
- input: 0,
251
- output: 0,
252
- cacheRead: 0,
253
- cacheCreation: 0,
254
- lastContextTokens: 0,
255
- };
256
- }
257
-
258
- function addUsageTotals(totals, usage = null) {
259
- if (!usage || typeof usage !== "object") return totals;
260
- totals.input += toUsageInt(usage.input);
261
- totals.output += toUsageInt(usage.output);
262
- totals.cacheRead += toUsageInt(usage.cacheRead);
263
- totals.cacheCreation += toUsageInt(usage.cacheCreation);
264
- return totals;
265
- }
266
-
267
- // OpenAI-compatible streams end with one usage chunk carrying whole-turn
268
- // totals (prompt_tokens_details.cached_tokens counts the cache hits).
269
- function readOpenAiUsage(raw) {
270
- if (!raw || typeof raw !== "object") return null;
271
- const details = raw.prompt_tokens_details && typeof raw.prompt_tokens_details === "object"
272
- ? raw.prompt_tokens_details
273
- : {};
274
- return {
275
- input: toUsageInt(raw.prompt_tokens),
276
- output: toUsageInt(raw.completion_tokens),
277
- cacheRead: toUsageInt(details.cached_tokens),
278
- cacheCreation: toUsageInt(details.created_cache_tokens),
279
- inputIncludesCache: true,
280
- };
281
- }
282
-
283
- // Anthropic reports input/cache tokens once on message_start; output tokens
284
- // arrive per message_delta. The non-streaming body carries the full totals.
285
- function readAnthropicUsage(raw, { includeOutput = false } = {}) {
286
- if (!raw || typeof raw !== "object") return null;
287
- return {
288
- input: toUsageInt(raw.input_tokens),
289
- output: includeOutput ? toUsageInt(raw.output_tokens) : 0,
290
- cacheRead: toUsageInt(raw.cache_read_input_tokens),
291
- cacheCreation: toUsageInt(raw.cache_creation_input_tokens),
292
- inputIncludesCache: false,
293
- };
294
- }
295
-
296
- function enforceNativeToolBudget({
297
- toolCallsExecuted = 0,
298
- toolErrors = 0,
299
- maxToolCalls = DEFAULT_MAX_NATIVE_TOOL_CALLS,
300
- maxToolErrors = DEFAULT_MAX_NATIVE_TOOL_ERRORS,
301
- lastTool = "",
302
- lastError = "",
303
- } = {}) {
304
- if (maxToolCalls != null && toolCallsExecuted >= maxToolCalls) {
305
- throw new Error(`tool call budget exceeded (${maxToolCalls})`);
306
- }
307
- if (toolErrors >= maxToolErrors) {
308
- const detail = [lastTool, lastError].filter(Boolean).join(": ");
309
- throw new Error(`tool error budget exceeded (${maxToolErrors})${detail ? `: ${detail}` : ""}`);
310
- }
311
- }
312
-
313
39
  function createGuards({ signal = null, timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS } = {}) {
314
40
  const startedAt = nowMs();
315
41
  const budgetMs = normalizeTimeoutMs(timeoutMs);
@@ -333,2378 +59,20 @@ function createGuards({ signal = null, timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS } =
333
59
  };
334
60
  }
335
61
 
336
- function emitToolEvent(callback, event = {}) {
337
- if (typeof callback !== "function") return;
338
- try {
339
- const payload = event && typeof event === "object" ? { ...event } : {};
340
- if (payload.origin == null) delete payload.origin;
341
- callback(payload);
342
- } catch {
343
- // ignore callback failures
344
- }
345
- }
346
-
347
- function clipText(value = "", maxChars = 6000) {
348
- const text = String(value || "");
349
- if (text.length <= maxChars) return text;
350
- return `${text.slice(0, maxChars)}\n...[truncated]`;
351
- }
352
-
353
- function normalizeProvider(value = "") {
354
- const text = String(value || "").trim().toLowerCase();
355
- if (!text) return "";
356
- if (text === "codex" || text === "codex-cli" || text === "codex-code") return "codex";
357
- if (text === "claude" || text === "claude-cli" || text === "claude-code") return "anthropic";
358
- if (text === "kimi" || text === "kimi-code" || text === "moonshot") return "kimi";
359
- if (text === "grok" || text === "grok-build" || text === "grok-shell" || text === "grok-api") return "grok-build";
360
- if (text === "xai") return "xai";
361
- if (text === "openai" || text === "anthropic") return text;
362
- return text;
363
- }
364
-
365
- function normalizeKimiModel(value = "") {
366
- const raw = String(value || "").trim();
367
- if (!raw) return "";
368
- const suffix = raw.match(/^(.*?)(\([^)]*\))$/);
369
- const base = String(suffix ? suffix[1] : raw).trim().replace(/\[1m\]$/i, "");
370
- const lower = base.toLowerCase();
371
- let normalized = lower;
372
- if (["kimi-k2.7-code", "k2.7-code", "kimi-for-coding", "for-coding"].includes(lower)) {
373
- normalized = "kimi-for-coding";
374
- } else if (["kimi-k2.7-code-highspeed", "k2.7-code-highspeed", "kimi-for-coding-highspeed", "for-coding-highspeed"].includes(lower)) {
375
- normalized = "kimi-for-coding-highspeed";
376
- } else if (normalized.startsWith("kimi-")) {
377
- normalized = normalized.slice("kimi-".length);
378
- }
379
- return `${normalized}${suffix ? suffix[2] : ""}`;
380
- }
381
-
382
- function resolveTransport({ provider = "", baseUrl = "" } = {}) {
383
- const normalizedProvider = normalizeProvider(provider);
384
- const url = String(baseUrl || "").trim().toLowerCase();
385
-
386
- if (normalizedProvider === "codex" || normalizedProvider === "grok-build" || normalizedProvider === "xai") {
387
- return "openai-responses";
388
- }
389
- if (normalizedProvider === "anthropic") return "anthropic-messages";
390
- if (normalizedProvider === "kimi") return "openai-chat";
391
- if (/\/responses(?:$|[/?#])/.test(url)) return "openai-responses";
392
- if (url.includes("anthropic.com")) return "anthropic-messages";
393
- if (/\/messages(?:$|[/?#])/.test(url) && !/\/chat\/completions(?:$|[/?#])/.test(url)) {
394
- return "anthropic-messages";
395
- }
396
-
397
- return "openai-chat";
398
- }
399
-
400
- function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", model = "" } = {}) {
401
- const config = loadConfig(workspaceRoot);
402
- const configuredProvider = normalizeProvider(config.ucodeProvider || config.agentProvider || "");
403
- const selectedProvider = normalizeProvider(
404
- provider
405
- || process.env.UFOO_UCODE_PROVIDER
406
- || configuredProvider
407
- || "openai"
408
- ) || "openai";
409
- const configuredModel = sameModelProvider(config.ucodeProvider || config.agentProvider, selectedProvider)
410
- ? (config.ucodeModel || config.agentModel)
411
- : "";
412
-
413
- const selectedModel = String(
414
- model
415
- || process.env.UFOO_UCODE_MODEL
416
- || configuredModel
417
- || (selectedProvider === "kimi"
418
- ? DEFAULT_KIMI_MODEL
419
- : (selectedProvider === "grok-build" ? DEFAULT_GROK_BUILD_MODEL : defaultAgentModelForProvider(selectedProvider)))
420
- ).trim();
421
-
422
- const defaultBaseUrl = selectedProvider === "anthropic"
423
- ? String(process.env.ANTHROPIC_BASE_URL || DEFAULT_ANTHROPIC_BASE_URL)
424
- : selectedProvider === "kimi"
425
- ? String(process.env.KIMI_BASE_URL || DEFAULT_KIMI_BASE_URL)
426
- : selectedProvider === "codex"
427
- ? String(process.env.UFOO_CODEX_BASE_URL || DEFAULT_CODEX_BASE_URL)
428
- : selectedProvider === "grok-build"
429
- ? String(
430
- process.env.UFOO_GROK_BUILD_BASE_URL
431
- || process.env.GROK_BUILD_BASE_URL
432
- || DEFAULT_GROK_BUILD_BASE_URL
433
- )
434
- : selectedProvider === "xai"
435
- ? String(process.env.XAI_BASE_URL || DEFAULT_XAI_BASE_URL)
436
- : String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL);
437
-
438
- let baseUrl = String(
439
- process.env.UFOO_UCODE_BASE_URL
440
- || config.ucodeBaseUrl
441
- || defaultBaseUrl
442
- ).trim();
443
-
444
- const explicitApiKey = String(
445
- process.env.UFOO_UCODE_API_KEY
446
- || config.ucodeApiKey
447
- || ""
448
- ).trim();
449
- let apiKey = explicitApiKey;
450
- let apiKeySource = explicitApiKey ? "explicit" : "";
451
- let kimiCredentialState = "";
452
- if (!apiKey && selectedProvider === "kimi") {
453
- const credential = readKimiAccessToken({ env: process.env });
454
- if (credential && credential.accessToken) {
455
- apiKey = String(credential.accessToken).trim();
456
- apiKeySource = "kimi-credential";
457
- kimiCredentialState = String(credential.state || "");
458
- }
459
- }
460
- if (!apiKey) {
461
- apiKey = String(
462
- (selectedProvider === "openai" ? process.env.OPENAI_API_KEY : "")
463
- || (selectedProvider === "anthropic" ? process.env.ANTHROPIC_API_KEY : "")
464
- || (selectedProvider === "codex" ? process.env.OPENAI_API_KEY : "")
465
- || (selectedProvider === "grok-build" ? (process.env.GROK_BUILD_API_KEY || process.env.XAI_API_KEY) : "")
466
- || (selectedProvider === "xai" ? process.env.XAI_API_KEY : "")
467
- || ""
468
- ).trim();
469
- if (apiKey) apiKeySource = "env";
470
- }
471
-
472
- // ChatGPT's Codex backend accepts Codex OAuth credentials, while standard
473
- // OpenAI API keys belong on the public OpenAI API. Generic ucode base URL
474
- // overrides remain authoritative for an explicitly configured gateway.
475
- if (
476
- selectedProvider === "codex"
477
- && apiKey
478
- && !String(process.env.UFOO_UCODE_BASE_URL || "").trim()
479
- && !String(config.ucodeBaseUrl || "").trim()
480
- ) {
481
- baseUrl = String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL).trim();
482
- }
483
-
484
- return {
485
- provider: selectedProvider,
486
- model: selectedModel,
487
- baseUrl,
488
- apiKey,
489
- apiKeySource,
490
- kimiCredentialState,
491
- transport: resolveTransport({ provider: selectedProvider, baseUrl }),
492
- };
493
- }
494
-
495
- function resolveCompletionUrl(baseUrl = "") {
496
- const raw = String(baseUrl || "").trim();
497
- if (!raw) return "";
498
- const normalized = raw.replace(/\/+$/, "");
499
- if (/\/chat\/completions$/i.test(normalized)) return normalized;
500
- if (/\/v1$/i.test(normalized)) return `${normalized}/chat/completions`;
501
- if (/\/api$/i.test(normalized)) return `${normalized}/v1/chat/completions`;
502
- return `${normalized}/chat/completions`;
503
- }
504
-
505
- function resolveResponsesUrl(baseUrl = "") {
506
- const raw = String(baseUrl || "").trim();
507
- if (!raw) return "";
508
- const normalized = raw.replace(/\/+$/, "");
509
- if (/\/responses$/i.test(normalized)) return normalized;
510
- if (/\/v1$/i.test(normalized)) return `${normalized}/responses`;
511
- if (/\/api$/i.test(normalized)) return `${normalized}/v1/responses`;
512
- return `${normalized}/responses`;
513
- }
514
-
515
- function resolveAnthropicMessagesUrl(baseUrl = "") {
516
- const raw = String(baseUrl || "").trim() || DEFAULT_ANTHROPIC_BASE_URL;
517
- const normalized = raw.replace(/\/+$/, "");
518
- if (/\/messages$/i.test(normalized)) return normalized;
519
- if (/\/v1$/i.test(normalized)) return `${normalized}/messages`;
520
- if (/\/api$/i.test(normalized)) return `${normalized}/v1/messages`;
521
- return `${normalized}/messages`;
522
- }
523
-
524
- function buildCoreToolSpecs() {
525
- return [
526
- {
527
- type: "function",
528
- function: {
529
- name: "read",
530
- description: getReadToolDescription(),
531
- parameters: {
532
- type: "object",
533
- properties: {
534
- path: { type: "string" },
535
- startLine: { type: "integer" },
536
- endLine: { type: "integer" },
537
- maxBytes: { type: "integer" },
538
- },
539
- required: ["path"],
540
- },
541
- },
542
- },
543
- {
544
- type: "function",
545
- function: {
546
- name: "read_image",
547
- description: getReadImageToolDescription(),
548
- parameters: {
549
- type: "object",
550
- properties: {
551
- path: {
552
- type: "string",
553
- description: "Workspace-relative path to a png, jpeg, gif, or webp image.",
554
- },
555
- },
556
- required: ["path"],
557
- },
558
- },
559
- },
560
- {
561
- type: "function",
562
- function: {
563
- name: "write",
564
- description: getWriteToolDescription(),
565
- parameters: {
566
- type: "object",
567
- properties: {
568
- path: { type: "string" },
569
- content: { type: "string" },
570
- mode: {
571
- type: "string",
572
- enum: ["overwrite", "append"],
573
- description: 'Write mode: "overwrite" replaces the file (default), "append" adds to its end.',
574
- },
575
- append: { type: "boolean" },
576
- },
577
- required: ["path", "content"],
578
- },
579
- },
580
- },
581
- {
582
- type: "function",
583
- function: {
584
- name: "edit",
585
- description: getEditToolDescription(),
586
- parameters: {
587
- type: "object",
588
- properties: {
589
- path: { type: "string" },
590
- find: { type: "string" },
591
- replace: { type: "string" },
592
- all: { type: "boolean" },
593
- },
594
- required: ["path", "find", "replace"],
595
- },
596
- },
597
- },
598
- {
599
- type: "function",
600
- function: {
601
- name: "bash",
602
- description: getBashToolDescription(),
603
- parameters: {
604
- type: "object",
605
- properties: {
606
- command: { type: "string" },
607
- timeoutMs: { type: "integer" },
608
- },
609
- required: ["command"],
610
- },
611
- },
612
- },
613
- {
614
- type: "function",
615
- function: {
616
- name: "artifact_read",
617
- description: [
618
- "Read previously stored tool output by artifactId.",
619
- "This does not read workspace files; use `read` for repository paths.",
620
- "Optionally read a slice with startLine/endLine, maxChars, or tailLines.",
621
- ].join(" "),
622
- parameters: {
623
- type: "object",
624
- properties: {
625
- artifactId: { type: "string" },
626
- sessionId: { type: "string" },
627
- startLine: { type: "integer" },
628
- endLine: { type: "integer" },
629
- maxChars: { type: "integer" },
630
- tailLines: { type: "integer" },
631
- },
632
- required: ["artifactId"],
633
- },
634
- },
635
- },
636
- {
637
- type: "function",
638
- function: {
639
- name: "plan_graph",
640
- description: [
641
- "Manage the persistent Plan Graph and graph-bound TaskRuns.",
642
- "TaskRuns are orthogonal to Plan Mode; for a standalone TaskRun without a plan, use `task_run` instead.",
643
- "Use create, patch, inspect, or cancel_graph for graph operations, and control for graph-bound TaskRun lifecycle.",
644
- "`control.start_task` starts a graph `task_loop` asynchronously and returns immediately.",
645
- "Use `inline_llm` for work handled by the current graph owner,",
646
- "`expand` for tasks that must be lowered into child nodes,",
647
- "and `task_loop` for asynchronous work in an independent TaskLoop attached to a plan node.",
648
- "Do not call `plan_graph` together with data-plane tools in the same assistant turn.",
649
- ].join(" "),
650
- parameters: {
651
- type: "object",
652
- properties: {
653
- operation: {
654
- type: "string",
655
- enum: [
656
- "create",
657
- "patch",
658
- "inspect",
659
- "clear",
660
- "cancel_graph",
661
- "control",
662
- ],
663
- description: [
664
- "create/patch/inspect/cancel_graph mutate or inspect the graph spec;",
665
- "control runs TaskRun lifecycle and node status actions.",
666
- ].join(" "),
667
- },
668
- graph: {
669
- type: "object",
670
- description: "Full graph for create (objective + nodes). group is input sugar only.",
671
- },
672
- operations: {
673
- type: "array",
674
- description: [
675
- "Patch ops only: add_node, expand_node, add_dependency, remove_dependency.",
676
- "Status actions (complete_task, skip_node, cancel_subtree) belong under control.actions.",
677
- ].join(" "),
678
- items: { type: "object" },
679
- },
680
- actions: {
681
- type: "array",
682
- description: [
683
- "Control actions: start_task, cancel_task, fail_task, complete_task, skip_node, cancel_subtree.",
684
- "complete_task with taskRunId finishes a TaskLoop TaskRun;",
685
- "complete_task with nodeId finishes a waiting_llm inline task owned by the graph owner.",
686
- ].join(" "),
687
- items: { type: "object" },
688
- },
689
- reason: {
690
- type: "string",
691
- description: "Optional reason for cancel_graph or fail/cancel task.",
692
- },
693
- commandId: {
694
- type: "string",
695
- description: [
696
- "Optional idempotency key for explicit replay.",
697
- "When omitted, the Runtime should derive one from the tool invocation when available.",
698
- ].join(" "),
699
- },
700
- expectedSpecRevision: {
701
- type: "integer",
702
- description: "Optional optimistic concurrency token for patch.",
703
- },
704
- graphId: {
705
- type: "string",
706
- description: "Optional graph id check for patch/control.",
707
- },
708
- },
709
- required: ["operation"],
710
- },
711
- },
712
- },
713
- {
714
- type: "function",
715
- function: {
716
- name: "task_run",
717
- description: [
718
- "Start, inspect, cancel, fail, or complete a TaskRun.",
719
- "TaskRuns are orthogonal to Plan Mode and do not require a plan_graph.",
720
- "Use operation=start with an objective for a standalone single-point TaskRun; it returns immediately.",
721
- "On complex multi-goal work, decompose into concrete objectives and start one or more TaskRuns.",
722
- "Use plan_graph control.start_task only when the TaskRun is attached to a plan_graph task_loop node.",
723
- "Do not call `task_run` together with data-plane tools in the same assistant turn.",
724
- ].join(" "),
725
- parameters: {
726
- type: "object",
727
- properties: {
728
- operation: {
729
- type: "string",
730
- enum: ["start", "cancel", "fail", "complete", "inspect"],
731
- description: [
732
- "start creates a standalone TaskRun from objective;",
733
- "cancel/fail/complete/inspect address an existing taskRunId",
734
- "(cancel/fail may also use nodeId for graph-bound runs).",
735
- ].join(" "),
736
- },
737
- objective: {
738
- type: "string",
739
- description: "Required for start: concrete TaskRun objective.",
740
- },
741
- title: {
742
- type: "string",
743
- description: "Optional short title for start.",
744
- },
745
- taskRunId: {
746
- type: "string",
747
- description: "TaskRun id for cancel, fail, complete, or inspect.",
748
- },
749
- nodeId: {
750
- type: "string",
751
- description: "Optional graph node id for cancel/fail of a graph-bound TaskRun.",
752
- },
753
- reason: {
754
- type: "string",
755
- description: "Optional reason for cancel or fail.",
756
- },
757
- result: {
758
- type: "object",
759
- description: "Optional result payload for complete (TaskLoop owner).",
760
- },
761
- commandId: {
762
- type: "string",
763
- description: "Optional idempotency key for explicit replay.",
764
- },
765
- },
766
- required: ["operation"],
767
- },
768
- },
769
- },
770
- {
771
- type: "function",
772
- function: {
773
- name: "ask_user",
774
- description: [
775
- "Ask the user for input and pause the current Agent loop until the reply arrives.",
776
- "Use only when user input is required to proceed, not for routine updates or decisions the agent can safely make.",
777
- "`kind=approval` requests yes/no confirmation; `kind=choice` presents the supplied options; `kind=chat` requests free text.",
778
- "This must be the only tool call in the turn.",
779
- "The reply is returned only as this tool result, not as a separate user message or pending user prompt.",
780
- "After the tool returns, continue from the answer and do not ask the same question again.",
781
- "Running TaskRuns are not paused automatically.",
782
- ].join(" "),
783
- parameters: {
784
- type: "object",
785
- properties: {
786
- kind: {
787
- type: "string",
788
- enum: ["approval", "choice", "chat"],
789
- description: "Interaction type.",
790
- },
791
- prompt: {
792
- type: "string",
793
- description: "Question shown to the user.",
794
- },
795
- options: {
796
- type: "array",
797
- description: "For choice: option labels (or {key,label} objects). Ignored for chat.",
798
- items: {
799
- oneOf: [
800
- { type: "string" },
801
- {
802
- type: "object",
803
- properties: {
804
- key: { type: "string" },
805
- label: { type: "string" },
806
- },
807
- },
808
- ],
809
- },
810
- },
811
- },
812
- required: ["kind", "prompt"],
813
- },
814
- },
815
- },
816
- ];
817
- }
818
-
819
- function buildAnthropicToolSpecs() {
820
- return buildCoreToolSpecs().map((spec) => ({
821
- name: spec.function.name,
822
- description: spec.function.description,
823
- input_schema: spec.function.parameters,
824
- }));
825
- }
826
-
827
- function createRequestController({ signal = null, timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS } = {}) {
828
- const controller = new AbortController();
829
- let timedOut = false;
830
-
831
- const timer = setTimeout(() => {
832
- timedOut = true;
833
- try {
834
- controller.abort();
835
- } catch {
836
- // ignore
837
- }
838
- }, normalizeTimeoutMs(timeoutMs));
839
-
840
- let abortHandler = null;
841
- if (signal && typeof signal === "object") {
842
- abortHandler = () => {
843
- try {
844
- controller.abort();
845
- } catch {
846
- // ignore
847
- }
848
- };
849
- if (signal.aborted) {
850
- abortHandler();
851
- } else if (typeof signal.addEventListener === "function") {
852
- signal.addEventListener("abort", abortHandler, { once: true });
853
- }
854
- }
855
-
856
- return {
857
- signal: controller.signal,
858
- timedOut: () => timedOut,
859
- cleanup: () => {
860
- clearTimeout(timer);
861
- if (signal && abortHandler && typeof signal.removeEventListener === "function") {
862
- signal.removeEventListener("abort", abortHandler);
863
- }
62
+ async function runNativeLoop(options = {}) {
63
+ const runtime = createAgentRuntime({
64
+ profile: codingProfile,
65
+ transport: options.transport,
66
+ capabilities: [createCodingCapability(), createPlanningCapability(), createSkillsCapability()],
67
+ host: { grantedPermissions: ["workspace.read", "workspace.write", "workspace.execute", "execution.control", "interaction.request"] },
68
+ defaults: {
69
+ sanitizeMessages: sanitizeModelMessages,
70
+ retireImages: retireMessageImages,
71
+ providerTurnGate: runProviderTurnGate,
72
+ maxAutoContinues: DEFAULT_MAX_PLAN_AUTO_CONTINUES,
864
73
  },
865
- };
866
- }
867
-
868
- function parseJsonSafe(value = "", fallback = null) {
869
- try {
870
- return JSON.parse(String(value || ""));
871
- } catch {
872
- return fallback;
873
- }
874
- }
875
-
876
- function cloneMessageList(value = []) {
877
- const parsed = parseJsonSafe(toJsonString(value), []);
878
- if (!Array.isArray(parsed)) return [];
879
- return parsed.filter((entry) => entry && typeof entry === "object" && !Array.isArray(entry));
880
- }
881
-
882
- function normalizeToolName(value = "") {
883
- const name = String(value || "").trim().toLowerCase();
884
- if (!CORE_TOOL_NAMES.has(name)) return "";
885
- return name;
886
- }
887
-
888
- function toJsonString(value) {
889
- return stableStringify(value);
890
- }
891
-
892
- function parseSseBlocks(text = "") {
893
- const source = String(text || "");
894
- const blocks = source.split(/\r?\n\r?\n/);
895
- if (blocks.length <= 1) {
896
- return { blocks: [], rest: source };
897
- }
898
- const rest = blocks.pop() || "";
899
- return { blocks, rest };
900
- }
901
-
902
- function parseSseEventBlock(block = "") {
903
- const lines = String(block || "").split(/\r?\n/);
904
- let event = "message";
905
- const data = [];
906
-
907
- for (const line of lines) {
908
- if (!line) continue;
909
- if (line.startsWith("event:")) {
910
- event = line.slice(6).trim() || "message";
911
- continue;
912
- }
913
- if (line.startsWith("data:")) {
914
- data.push(line.slice(5).trimStart());
915
- }
916
- }
917
-
918
- return {
919
- event,
920
- data: data.join("\n"),
921
- };
922
- }
923
-
924
- function parseSseDataBlock(block = "") {
925
- return parseSseEventBlock(block).data;
926
- }
927
-
928
- function normalizeToolCallArgs(raw = "") {
929
- const text = String(raw || "").trim();
930
- if (!text) return {};
931
- const parsed = parseJsonSafe(text, null);
932
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
933
- return parsed;
934
- }
935
- return {};
936
- }
937
-
938
- function runCoreTool({
939
- tool = "",
940
- args = {},
941
- workspaceRoot = process.cwd(),
942
- onToolEvent = null,
943
- sessionId = "",
944
- onArtifactPersisted = null,
945
- executionState = null,
946
- origin = null,
947
- resume = null,
948
- } = {}) {
949
- const normalizedTool = normalizeToolName(tool);
950
- if (!normalizedTool) {
951
- emitToolEvent(onToolEvent, {
952
- tool: String(tool || "unknown"),
953
- phase: "error",
954
- args: args && typeof args === "object" ? { ...args } : {},
955
- error: `unsupported tool: ${tool}`,
956
- origin,
957
- });
958
- return {
959
- ok: false,
960
- error: `unsupported tool: ${tool}`,
961
- };
962
- }
963
-
964
- const safeArgs = args && typeof args === "object" ? { ...args } : {};
965
- if (normalizedTool === "artifact_read" && sessionId && !safeArgs.sessionId) {
966
- safeArgs.sessionId = sessionId;
967
- }
968
- emitToolEvent(onToolEvent, {
969
- tool: normalizedTool,
970
- phase: "start",
971
- args: safeArgs,
972
- error: "",
973
- origin,
974
- });
975
-
976
- if (normalizedTool === "plan_graph") {
977
- const state = executionState && typeof executionState === "object"
978
- ? executionState
979
- : emptyExecutionState();
980
- const result = runPlanGraphCommand(safeArgs, {
981
- executionState: state,
982
- autoAdvance: true,
983
- parallel: true,
984
- runTool: ({ node, args: nestedArgs, tool: nestedTool, stepId }) => {
985
- const nested = runCoreTool({
986
- tool: nestedTool,
987
- args: nestedArgs,
988
- workspaceRoot,
989
- onToolEvent,
990
- sessionId,
991
- onArtifactPersisted,
992
- executionState: state,
993
- origin: {
994
- kind: "plan_graph",
995
- graphId: String(state.planGraph && state.planGraph.graphId || ""),
996
- graphRevision: Number(state.planGraph && state.planGraph.specRevision) || 0,
997
- commandRevision: Number(state.planGraph && state.planGraph.specRevision) || 0,
998
- nodeId: stepId || (node && node.id) || "",
999
- attempt: Number(node && node.attempt) || 0,
1000
- },
1001
- });
1002
- return nested;
1003
- },
1004
- });
1005
- if (result.ok === false) {
1006
- emitToolEvent(onToolEvent, {
1007
- tool: "plan_graph",
1008
- phase: "error",
1009
- args: safeArgs,
1010
- error: Array.isArray(result.errors)
1011
- ? result.errors.map((e) => e.message || e.code).join("; ")
1012
- : "plan_graph rejected",
1013
- origin,
1014
- });
1015
- } else {
1016
- syncInteractionFromPlanGraph(result.executionState || state);
1017
- }
1018
- return {
1019
- ...result.modelPayload,
1020
- ok: result.status === "accepted",
1021
- // Keep executionState for the runner only; sanitizeToolResultForModel
1022
- // strips it before the payload enters provider messages.
1023
- executionState: result.executionState || state,
1024
- };
1025
- }
1026
-
1027
- if (normalizedTool === "task_run") {
1028
- const state = executionState && typeof executionState === "object"
1029
- ? executionState
1030
- : emptyExecutionState();
1031
- const result = runTaskRunTool(safeArgs, {
1032
- executionState: state,
1033
- runTool: ({ node, args: nestedArgs, tool: nestedTool, stepId }) => {
1034
- const nested = runCoreTool({
1035
- tool: nestedTool,
1036
- args: nestedArgs,
1037
- workspaceRoot,
1038
- onToolEvent,
1039
- sessionId,
1040
- onArtifactPersisted,
1041
- executionState: state,
1042
- origin: {
1043
- kind: "task_run",
1044
- taskRunId: String(safeArgs.taskRunId || ""),
1045
- nodeId: stepId || (node && node.id) || "",
1046
- attempt: Number(node && node.attempt) || 0,
1047
- },
1048
- });
1049
- return nested;
1050
- },
1051
- });
1052
- const ok = result.ok !== false && result.status !== "rejected";
1053
- emitToolEvent(onToolEvent, {
1054
- tool: "task_run",
1055
- phase: ok ? "end" : "error",
1056
- args: safeArgs,
1057
- result,
1058
- error: ok
1059
- ? ""
1060
- : (Array.isArray(result.errors)
1061
- ? result.errors.map((e) => e.message || e.code).join("; ")
1062
- : (result.error || "task_run rejected")),
1063
- origin,
1064
- });
1065
- return {
1066
- ...result,
1067
- ok,
1068
- executionState: result.executionState || state,
1069
- };
1070
- }
1071
-
1072
- if (normalizedTool === "ask_user") {
1073
- const state = executionState && typeof executionState === "object"
1074
- ? executionState
1075
- : emptyExecutionState();
1076
- const result = runAskUserTool(safeArgs, {
1077
- executionState: state,
1078
- resume: resume || null,
1079
- });
1080
- const ok = result.ok !== false && result.status !== "rejected";
1081
- emitToolEvent(onToolEvent, {
1082
- tool: "ask_user",
1083
- phase: ok ? "end" : "error",
1084
- args: safeArgs,
1085
- result: result.modelPayload || result,
1086
- error: ok ? "" : (result.error || "ask_user rejected"),
1087
- origin,
1088
- });
1089
- return {
1090
- ...(result.modelPayload || result),
1091
- ok,
1092
- status: result.status,
1093
- waiting_user: Boolean(result.waiting_user || result.status === "waiting_user"),
1094
- interactionId: result.interactionId || "",
1095
- executionState: result.executionState || state,
1096
- deferToolResult: ok && result.status === "waiting_user",
1097
- };
1098
- }
1099
-
1100
- const toolOptions = { workspaceRoot, cwd: workspaceRoot };
1101
- if (normalizedTool === "artifact_read" && sessionId) {
1102
- toolOptions.sessionId = sessionId;
1103
- }
1104
- const result = runToolCall(
1105
- { tool: normalizedTool, args: safeArgs },
1106
- toolOptions,
1107
- );
1108
-
1109
- if (!result || result.ok === false) {
1110
- emitToolEvent(onToolEvent, {
1111
- tool: normalizedTool,
1112
- phase: "error",
1113
- args: safeArgs,
1114
- error: String((result && result.error) || `${normalizedTool} failed`),
1115
- origin,
1116
- });
1117
- return result;
1118
- }
1119
-
1120
- if (normalizedTool !== "artifact_read" && EXECUTABLE_GRAPH_TOOLS.has(normalizedTool)) {
1121
- const persisted = persistToolResultToContext({
1122
- workspaceRoot,
1123
- sessionId,
1124
- tool: normalizedTool,
1125
- args: safeArgs,
1126
- rawResult: result,
1127
- });
1128
- if (typeof onArtifactPersisted === "function") {
1129
- try {
1130
- onArtifactPersisted(persisted);
1131
- } catch {
1132
- // ignore
1133
- }
1134
- }
1135
- const payload = persisted.modelPayload || result;
1136
- if (origin) payload.origin = origin;
1137
- return payload;
1138
- }
1139
-
1140
- if (origin && result && typeof result === "object") {
1141
- return { ...result, origin };
1142
- }
1143
- return result;
1144
- }
1145
-
1146
- /**
1147
- * Async companion for the native loop. Control-plane tools intentionally keep
1148
- * their synchronous scheduler for now; data-plane tools use the async
1149
- * dispatcher so bash can terminate on the caller's AbortSignal.
1150
- */
1151
- async function runCoreToolAsync(options = {}) {
1152
- const normalizedTool = normalizeToolName(options.tool);
1153
- if (!normalizedTool || CONTROL_PLANE_TOOLS.has(normalizedTool) || normalizedTool === "ask_user") {
1154
- return runCoreTool(options);
1155
- }
1156
-
1157
- const {
1158
- args = {},
1159
- workspaceRoot = process.cwd(),
1160
- onToolEvent = null,
1161
- sessionId = "",
1162
- onArtifactPersisted = null,
1163
- origin = null,
1164
- signal = null,
1165
- } = options;
1166
- const safeArgs = args && typeof args === "object" ? { ...args } : {};
1167
- if (normalizedTool === "artifact_read" && sessionId && !safeArgs.sessionId) {
1168
- safeArgs.sessionId = sessionId;
1169
- }
1170
- emitToolEvent(onToolEvent, {
1171
- tool: normalizedTool,
1172
- phase: "start",
1173
- args: safeArgs,
1174
- error: "",
1175
- origin,
1176
74
  });
1177
-
1178
- const toolOptions = {
1179
- workspaceRoot,
1180
- cwd: workspaceRoot,
1181
- };
1182
- if (signal) toolOptions.signal = signal;
1183
- if (normalizedTool === "artifact_read" && sessionId) {
1184
- toolOptions.sessionId = sessionId;
1185
- }
1186
- const result = await runToolCallAsync(
1187
- { tool: normalizedTool, args: safeArgs },
1188
- toolOptions,
1189
- );
1190
-
1191
- if (!result || result.ok === false) {
1192
- emitToolEvent(onToolEvent, {
1193
- tool: normalizedTool,
1194
- phase: "error",
1195
- args: safeArgs,
1196
- error: String((result && result.error) || `${normalizedTool} failed`),
1197
- origin,
1198
- });
1199
- return result;
1200
- }
1201
-
1202
- if (normalizedTool !== "artifact_read" && EXECUTABLE_GRAPH_TOOLS.has(normalizedTool)) {
1203
- const persisted = persistToolResultToContext({
1204
- workspaceRoot,
1205
- sessionId,
1206
- tool: normalizedTool,
1207
- args: safeArgs,
1208
- rawResult: result,
1209
- });
1210
- if (typeof onArtifactPersisted === "function") {
1211
- try {
1212
- onArtifactPersisted(persisted);
1213
- } catch {
1214
- // ignore
1215
- }
1216
- }
1217
- const payload = persisted.modelPayload || result;
1218
- if (origin) payload.origin = origin;
1219
- return payload;
1220
- }
1221
-
1222
- if (origin && result && typeof result === "object") {
1223
- return { ...result, origin };
1224
- }
1225
- return result;
1226
- }
1227
-
1228
- function emitPhase(callback, event = {}) {
1229
- if (typeof callback !== "function") return;
1230
- try {
1231
- callback(event);
1232
- } catch {
1233
- // ignore phase callback failures
1234
- }
1235
- }
1236
-
1237
- // Shared SSE transport skeleton: POST the payload, then read the stream as
1238
- // SSE blocks, dispatch each non-[DONE] block to onEvent, and stop after the
1239
- // batch that carried [DONE]. Timeout/cancel translation and request cleanup
1240
- // live here so each protocol turn only declares its event handling.
1241
- async function runSseRequest({
1242
- url = "",
1243
- headers = {},
1244
- payload = {},
1245
- signal = null,
1246
- timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
1247
- onPhase = null,
1248
- onNonStream,
1249
- onEvent,
1250
- onTail = null,
1251
- buildResult,
1252
- } = {}) {
1253
- const request = createRequestController({ signal, timeoutMs });
1254
-
1255
- emitPhase(onPhase, { type: "request_start" });
1256
-
1257
- try {
1258
- const response = await fetch(url, {
1259
- method: "POST",
1260
- headers,
1261
- body: JSON.stringify(payload),
1262
- signal: request.signal,
1263
- dispatcher: getNativeSseDispatcher(),
1264
- });
1265
-
1266
- if (!response.ok) {
1267
- const body = await response.text().catch(() => "");
1268
- throw new Error(`provider request failed (${response.status}): ${clipText(body, 500)}`);
1269
- }
1270
-
1271
- if (!response.body || typeof response.body.getReader !== "function") {
1272
- const data = await response.json();
1273
- return onNonStream(data);
1274
- }
1275
-
1276
- const reader = response.body.getReader();
1277
- const decoder = new TextDecoder();
1278
- let rawBuffer = "";
1279
- let sawDone = false;
1280
-
1281
- while (true) {
1282
- const { done, value } = await reader.read();
1283
- if (done) break;
1284
-
1285
- rawBuffer += decoder.decode(value, { stream: true });
1286
- const parsed = parseSseBlocks(rawBuffer);
1287
- rawBuffer = parsed.rest;
1288
-
1289
- for (const block of parsed.blocks) {
1290
- const { event, data } = parseSseEventBlock(block);
1291
- if (!data) continue;
1292
- if (data === "[DONE]") {
1293
- // Stop reading after this batch instead of waiting for the server
1294
- // to close the connection, but keep the buffered tail and finish
1295
- // the blocks already parsed alongside [DONE] instead of silently
1296
- // dropping them.
1297
- sawDone = true;
1298
- continue;
1299
- }
1300
-
1301
- onEvent({ event, data });
1302
- }
1303
-
1304
- if (sawDone) break;
1305
- }
1306
-
1307
- if (typeof onTail === "function") {
1308
- onTail(rawBuffer);
1309
- }
1310
-
1311
- return buildResult();
1312
- } catch (err) {
1313
- if (request.timedOut()) {
1314
- const timeoutError = new Error(`CLI timeout (${normalizeTimeoutMs(timeoutMs)}ms)`);
1315
- timeoutError.code = "timeout";
1316
- throw timeoutError;
1317
- }
1318
- if (signal && typeof signal === "object" && signal.aborted) {
1319
- const cancelError = new Error("CLI cancelled");
1320
- cancelError.code = "cancelled";
1321
- throw cancelError;
1322
- }
1323
- throw enrichProviderTransportError(err);
1324
- } finally {
1325
- request.cleanup();
1326
- }
1327
- }
1328
-
1329
- async function runOpenAiLikeTurn({
1330
- url = "",
1331
- apiKey = "",
1332
- model = "",
1333
- provider = "",
1334
- messages = [],
1335
- onTextDelta = null,
1336
- onThinkingDelta = null,
1337
- onPhase = null,
1338
- signal = null,
1339
- timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
1340
- } = {}) {
1341
- const normalizedProvider = normalizeProvider(provider);
1342
- const payload = {
1343
- model: normalizedProvider === "kimi" ? normalizeKimiModel(model) : model,
1344
- max_tokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
1345
- messages,
1346
- tools: buildCoreToolSpecs(),
1347
- tool_choice: "auto",
1348
- stream: true,
1349
- // Ask for the terminal usage chunk so token/cache accounting works.
1350
- stream_options: { include_usage: true },
1351
- // Kimi k3 rejects any temperature other than 1.
1352
- temperature: normalizedProvider === "kimi" ? 1 : 0,
1353
- };
1354
- const reasoningEffort = resolveReasoningEffort();
1355
- if (reasoningEffort) {
1356
- // OpenAI-compatible gateways that support reasoning models accept this;
1357
- // unknown fields are typically ignored by plain chat models.
1358
- payload.reasoning_effort = reasoningEffort;
1359
- }
1360
-
1361
- const headers = normalizedProvider === "kimi"
1362
- ? buildKimiHeaders({ apiKey, stream: true })
1363
- : { "content-type": "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) };
1364
-
1365
- const toolCallMap = new Map();
1366
- const announcedToolNames = new Set();
1367
- let responseText = "";
1368
- let nextSyntheticIndex = 0;
1369
- let lastSyntheticIndex = -1;
1370
- let streamUsage = null;
1371
-
1372
- return runSseRequest({
1373
- url,
1374
- headers,
1375
- payload,
1376
- signal,
1377
- timeoutMs,
1378
- onPhase,
1379
- onNonStream: (data) => {
1380
- const message = data && data.choices && data.choices[0] && data.choices[0].message
1381
- ? data.choices[0].message
1382
- : {};
1383
- const text = typeof message.content === "string" ? message.content : "";
1384
- const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
1385
- if (text && typeof onTextDelta === "function") {
1386
- onTextDelta(text);
1387
- }
1388
- return {
1389
- text,
1390
- toolCalls,
1391
- usage: readOpenAiUsage(data && data.usage),
1392
- };
1393
- },
1394
- onEvent: ({ data }) => {
1395
- const chunk = parseJsonSafe(data, null);
1396
- if (!chunk || typeof chunk !== "object") return;
1397
-
1398
- // The usage chunk carries empty choices, so read it before the
1399
- // choice guard below; latest wins (it reports whole-turn totals).
1400
- const chunkUsage = readOpenAiUsage(chunk.usage);
1401
- if (chunkUsage) streamUsage = chunkUsage;
1402
-
1403
- const choice = chunk.choices && chunk.choices[0] ? chunk.choices[0] : null;
1404
- if (!choice || typeof choice !== "object") return;
1405
-
1406
- const delta = choice.delta && typeof choice.delta === "object" ? choice.delta : {};
1407
-
1408
- const reasoningChunk = typeof delta.reasoning_content === "string"
1409
- ? delta.reasoning_content
1410
- : (typeof delta.reasoning === "string" ? delta.reasoning : "");
1411
- if (reasoningChunk) {
1412
- emitPhase(onPhase, { type: "thinking_delta", text: reasoningChunk });
1413
- if (typeof onThinkingDelta === "function") {
1414
- onThinkingDelta(reasoningChunk);
1415
- }
1416
- }
1417
-
1418
- if (typeof delta.content === "string" && delta.content) {
1419
- responseText += delta.content;
1420
- emitPhase(onPhase, { type: "text_delta", text: delta.content });
1421
- if (typeof onTextDelta === "function") {
1422
- onTextDelta(delta.content);
1423
- }
1424
- }
1425
-
1426
- if (Array.isArray(delta.tool_calls)) {
1427
- for (const callPart of delta.tool_calls) {
1428
- let index;
1429
- if (Number.isFinite(callPart.index)) {
1430
- index = callPart.index;
1431
- } else if (typeof callPart.id === "string" && callPart.id) {
1432
- // Provider omitted index: a chunk carrying an id starts a new
1433
- // call, so give it its own synthetic index instead of
1434
- // collapsing every call into slot 0.
1435
- while (toolCallMap.has(nextSyntheticIndex)) nextSyntheticIndex += 1;
1436
- index = nextSyntheticIndex;
1437
- nextSyntheticIndex += 1;
1438
- lastSyntheticIndex = index;
1439
- } else if (lastSyntheticIndex >= 0) {
1440
- // No index and no id: continuation of the latest synthetic call.
1441
- index = lastSyntheticIndex;
1442
- } else {
1443
- index = 0;
1444
- }
1445
- const previous = toolCallMap.get(index) || {
1446
- id: "",
1447
- type: "function",
1448
- function: {
1449
- name: "",
1450
- arguments: "",
1451
- },
1452
- };
1453
-
1454
- if (typeof callPart.id === "string" && callPart.id) previous.id = callPart.id;
1455
- if (callPart.function && typeof callPart.function === "object") {
1456
- if (typeof callPart.function.name === "string" && callPart.function.name) {
1457
- previous.function.name = callPart.function.name;
1458
- }
1459
- if (typeof callPart.function.arguments === "string" && callPart.function.arguments) {
1460
- previous.function.arguments += callPart.function.arguments;
1461
- }
1462
- }
1463
-
1464
- toolCallMap.set(index, previous);
1465
-
1466
- const toolName = previous.function.name;
1467
- const announceKey = `${index}:${toolName}`;
1468
- if (toolName && !announcedToolNames.has(announceKey)) {
1469
- announcedToolNames.add(announceKey);
1470
- emitPhase(onPhase, { type: "tool_request", name: toolName });
1471
- }
1472
- }
1473
- }
1474
- },
1475
- onTail: (rawBuffer) => {
1476
- if (!rawBuffer.trim()) return;
1477
- const fallbackBlock = parseSseDataBlock(rawBuffer);
1478
- if (fallbackBlock && fallbackBlock !== "[DONE]") {
1479
- const chunk = parseJsonSafe(fallbackBlock, null);
1480
- const tailUsage = readOpenAiUsage(chunk && chunk.usage);
1481
- if (tailUsage) streamUsage = tailUsage;
1482
- const choice = chunk && chunk.choices && chunk.choices[0] ? chunk.choices[0] : null;
1483
- if (choice && choice.delta && typeof choice.delta.content === "string" && choice.delta.content) {
1484
- responseText += choice.delta.content;
1485
- if (typeof onTextDelta === "function") {
1486
- onTextDelta(choice.delta.content);
1487
- }
1488
- }
1489
- }
1490
- },
1491
- buildResult: () => ({
1492
- text: responseText,
1493
- toolCalls: Array.from(toolCallMap.entries())
1494
- .sort((a, b) => a[0] - b[0])
1495
- .map((entry) => entry[1]),
1496
- usage: streamUsage,
1497
- }),
1498
- });
1499
- }
1500
-
1501
- function currentGrokClientVersion() {
1502
- return String(process.env.UFOO_GROK_CLIENT_VERSION || "0.2.120").trim() || "0.2.120";
1503
- }
1504
-
1505
- function isGrokCliProxyUrl(url = "") {
1506
- try {
1507
- return new URL(String(url || "")).hostname.toLowerCase() === "cli-chat-proxy.grok.com";
1508
- } catch {
1509
- return false;
1510
- }
1511
- }
1512
-
1513
- function currentKimiClientVersion() {
1514
- try {
1515
- return String(process.env.UFOO_KIMI_CLIENT_VERSION || require("../../package.json").version || "dev").trim() || "dev";
1516
- } catch {
1517
- return "dev";
1518
- }
1519
- }
1520
-
1521
- function buildKimiHeaders({ apiKey = "", stream = true } = {}) {
1522
- const version = currentKimiClientVersion();
1523
- const headers = {
1524
- "content-type": "application/json",
1525
- "User-Agent": `ufoo/${version}`,
1526
- "X-Msh-Platform": "ufoo",
1527
- "X-Msh-Version": version,
1528
- "X-Msh-Device-Name": os.hostname(),
1529
- "X-Msh-Device-Model": `${process.platform} ${process.arch}`,
1530
- "X-Msh-Device-Id": String(process.env.KIMI_DEVICE_ID || "ufoo-kimi-device").trim() || "ufoo-kimi-device",
1531
- Accept: stream ? "text/event-stream" : "application/json",
1532
- };
1533
- if (apiKey) headers.authorization = `Bearer ${apiKey}`;
1534
- return headers;
1535
- }
1536
-
1537
- function buildResponsesHeaders({ provider = "", apiKey = "", sessionId = "", accountId = "", url = "" } = {}) {
1538
- const normalizedProvider = normalizeProvider(provider);
1539
- const headers = {
1540
- "content-type": "application/json",
1541
- Accept: "text/event-stream",
1542
- Connection: "Keep-Alive",
1543
- };
1544
- if (apiKey) headers.authorization = `Bearer ${apiKey}`;
1545
-
1546
- if (normalizedProvider === "codex") {
1547
- headers["User-Agent"] = String(
1548
- process.env.UFOO_CODEX_USER_AGENT
1549
- || "codex-tui/0.118.0 (Mac OS 26.3.1; arm64) iTerm.app/3.6.9 (codex-tui; 0.118.0)"
1550
- );
1551
- headers.Originator = "codex-tui";
1552
- headers["Session-Id"] = String(sessionId || randomUUID());
1553
- if (accountId) headers["Chatgpt-Account-Id"] = String(accountId);
1554
- }
1555
-
1556
- if (normalizedProvider === "grok-build" || normalizedProvider === "xai") {
1557
- const version = currentGrokClientVersion();
1558
- if (sessionId) headers["x-grok-conv-id"] = String(sessionId);
1559
- if (isGrokCliProxyUrl(url)) {
1560
- headers["X-XAI-Token-Auth"] = "xai-grok-cli";
1561
- headers["x-grok-client-version"] = version;
1562
- headers["x-grok-client-identifier"] = "grok-shell";
1563
- headers["x-authenticateresponse"] = "authenticate-response";
1564
- headers["User-Agent"] = `xai-grok-workspace/${version}`;
1565
- } else if (normalizedProvider === "grok-build") {
1566
- // CLIProxyAPI selects the Grok Build route from this identity.
1567
- headers["User-Agent"] = `grok-shell/${version}`;
1568
- }
1569
- }
1570
-
1571
- return headers;
1572
- }
1573
-
1574
- async function runResponsesTurn({
1575
- url = "",
1576
- apiKey = "",
1577
- model = "",
1578
- provider = "",
1579
- systemPrompt = "",
1580
- messages = [],
1581
- sessionId = "",
1582
- accountId = "",
1583
- onTextDelta = null,
1584
- onThinkingDelta = null,
1585
- onPhase = null,
1586
- signal = null,
1587
- timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
1588
- } = {}) {
1589
- const payload = buildResponsesPayload({
1590
- model,
1591
- instructions: systemPrompt,
1592
- messages,
1593
- tools: buildCoreToolSpecs(),
1594
- maxOutputTokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
1595
- reasoningEffort: resolveReasoningEffort(),
1596
- provider: normalizeProvider(provider),
1597
- });
1598
- const headers = buildResponsesHeaders({ provider, apiKey, sessionId, accountId, url });
1599
- const frames = [];
1600
-
1601
- const consumeFrame = (frame = {}) => {
1602
- const data = frame && frame.data && typeof frame.data === "object"
1603
- ? frame.data
1604
- : parseJsonSafe(frame && frame.data, null);
1605
- if (!data || isResponsesKeepalive(frame && frame.event, data)) return;
1606
- frames.push({ event: String(frame.event || data.type || ""), data });
1607
-
1608
- const delta = responseEventDelta({ event: data.type || frame.event, data });
1609
- if (delta.reasoning) {
1610
- emitPhase(onPhase, { type: "thinking_delta", text: delta.reasoning });
1611
- if (typeof onThinkingDelta === "function") onThinkingDelta(delta.reasoning);
1612
- }
1613
- if (delta.text) {
1614
- emitPhase(onPhase, { type: "text_delta", text: delta.text });
1615
- if (typeof onTextDelta === "function") onTextDelta(delta.text);
1616
- }
1617
-
1618
- const item = data.item && typeof data.item === "object" ? data.item : null;
1619
- if (
1620
- item
1621
- && item.type === "function_call"
1622
- && item.name
1623
- && (data.type === "response.output_item.added" || data.type === "response.output_item.done")
1624
- ) {
1625
- emitPhase(onPhase, { type: "tool_request", name: String(item.name) });
1626
- }
1627
- };
1628
-
1629
- return runSseRequest({
1630
- url,
1631
- headers,
1632
- payload,
1633
- signal,
1634
- timeoutMs,
1635
- onPhase,
1636
- onNonStream: (data) => {
1637
- const parsed = parseResponsesEvents([{ event: data && data.type ? data.type : "response", data }], {
1638
- assumeCompleted: true,
1639
- });
1640
- if (parsed.reasoning && typeof onThinkingDelta === "function") onThinkingDelta(parsed.reasoning);
1641
- if (parsed.text && typeof onTextDelta === "function") onTextDelta(parsed.text);
1642
- return {
1643
- text: parsed.text,
1644
- toolCalls: parsed.toolCalls,
1645
- outputItems: parsed.outputItems,
1646
- usage: parsed.usage,
1647
- response: parsed.response,
1648
- responseId: parsed.responseId,
1649
- };
1650
- },
1651
- onEvent: consumeFrame,
1652
- onTail: (rawBuffer) => {
1653
- if (!String(rawBuffer || "").trim()) return;
1654
- const tail = parseResponsesSsePayload(rawBuffer);
1655
- for (const data of tail.events || []) consumeFrame({ event: data.type, data });
1656
- },
1657
- buildResult: () => {
1658
- const parsed = parseResponsesEvents(frames);
1659
- if (!parsed.terminal) {
1660
- throw new Error("Responses stream ended before response.completed or response.incomplete");
1661
- }
1662
- return {
1663
- text: parsed.text,
1664
- toolCalls: parsed.toolCalls,
1665
- outputItems: parsed.outputItems,
1666
- usage: parsed.usage,
1667
- response: parsed.response,
1668
- responseId: parsed.responseId,
1669
- incompleteDetails: parsed.incompleteDetails,
1670
- };
1671
- },
1672
- });
1673
- }
1674
-
1675
- function normalizeAnthropicMessageContent(raw = []) {
1676
- if (!Array.isArray(raw)) return [];
1677
- return raw
1678
- .map((item) => {
1679
- if (!item || typeof item !== "object") return null;
1680
- if (item.type === "text") {
1681
- return {
1682
- type: "text",
1683
- text: String(item.text || ""),
1684
- };
1685
- }
1686
- if (item.type === "thinking") {
1687
- return {
1688
- type: "thinking",
1689
- thinking: String(item.thinking || ""),
1690
- signature: String(item.signature || ""),
1691
- };
1692
- }
1693
- if (item.type === "tool_use") {
1694
- return {
1695
- type: "tool_use",
1696
- id: String(item.id || ""),
1697
- name: String(item.name || ""),
1698
- input: item.input && typeof item.input === "object" && !Array.isArray(item.input)
1699
- ? item.input
1700
- : {},
1701
- };
1702
- }
1703
- return null;
1704
- })
1705
- .filter(Boolean);
1706
- }
1707
-
1708
- function extractAnthropicToolCalls(content = []) {
1709
- return normalizeAnthropicMessageContent(content)
1710
- .filter((item) => item.type === "tool_use")
1711
- .map((item) => ({
1712
- id: String(item.id || `tool_${randomUUID()}`),
1713
- name: String(item.name || ""),
1714
- args: item.input && typeof item.input === "object" && !Array.isArray(item.input)
1715
- ? item.input
1716
- : {},
1717
- }));
1718
- }
1719
-
1720
- // Mark the newest message with a cache breakpoint so the append-only history
1721
- // prefix is served from the prompt cache. The payload gets a copy: stamping
1722
- // cache_control onto the shared history array would leave stale breakpoints
1723
- // behind as later turns append, eventually exceeding the 4-breakpoint limit.
1724
- function withAnthropicCacheBreakpoint(messages = []) {
1725
- if (!Array.isArray(messages) || messages.length === 0) return messages;
1726
- const copy = messages.slice();
1727
- const lastIndex = copy.length - 1;
1728
- const last = copy[lastIndex];
1729
- if (!last || typeof last !== "object" || Array.isArray(last)) return copy;
1730
- if (typeof last.content === "string") {
1731
- if (!last.content) return copy;
1732
- copy[lastIndex] = {
1733
- ...last,
1734
- content: [
1735
- {
1736
- type: "text",
1737
- text: last.content,
1738
- cache_control: { ...ANTHROPIC_CACHE_CONTROL },
1739
- },
1740
- ],
1741
- };
1742
- return copy;
1743
- }
1744
- if (Array.isArray(last.content) && last.content.length > 0) {
1745
- const blocks = last.content.slice();
1746
- const blockIndex = blocks.length - 1;
1747
- const block = blocks[blockIndex];
1748
- if (block && typeof block === "object" && !Array.isArray(block)) {
1749
- blocks[blockIndex] = {
1750
- ...block,
1751
- cache_control: { ...ANTHROPIC_CACHE_CONTROL },
1752
- };
1753
- copy[lastIndex] = {
1754
- ...last,
1755
- content: blocks,
1756
- };
1757
- }
1758
- }
1759
- return copy;
1760
- }
1761
-
1762
- async function runAnthropicTurn({
1763
- url = "",
1764
- apiKey = "",
1765
- model = "",
1766
- systemPrompt = "",
1767
- systemBlocks = null,
1768
- messages = [],
1769
- onTextDelta = null,
1770
- onThinkingDelta = null,
1771
- onPhase = null,
1772
- signal = null,
1773
- timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
1774
- } = {}) {
1775
- const payload = {
1776
- model,
1777
- max_tokens: resolveMaxTokens(DEFAULT_ANTHROPIC_MAX_TOKENS),
1778
- messages: withAnthropicCacheBreakpoint(messages),
1779
- tools: buildAnthropicToolSpecs(),
1780
- stream: true,
1781
- };
1782
- const thinkingBudget = resolveThinkingBudgetTokens();
1783
- if (thinkingBudget > 0) {
1784
- payload.thinking = { type: "enabled", budget_tokens: thinkingBudget };
1785
- }
1786
- if (Array.isArray(systemBlocks) && systemBlocks.length > 0) {
1787
- payload.system = systemBlocksToAnthropicPayload(systemBlocks);
1788
- } else {
1789
- const systemText = String(systemPrompt || "").trim();
1790
- if (systemText) {
1791
- payload.system = [
1792
- {
1793
- type: "text",
1794
- text: systemText,
1795
- cache_control: { ...ANTHROPIC_CACHE_CONTROL },
1796
- },
1797
- ];
1798
- }
1799
- }
1800
-
1801
- const headers = {
1802
- "content-type": "application/json",
1803
- "anthropic-version": "2023-06-01",
1804
- };
1805
- if (apiKey) {
1806
- headers["x-api-key"] = apiKey;
1807
- }
1808
-
1809
- const blockMap = new Map();
1810
- let responseText = "";
1811
- let nextSyntheticBlockIndex = 0;
1812
- let lastBlockIndex = -1;
1813
- const turnUsage = {
1814
- input: 0,
1815
- output: 0,
1816
- cacheRead: 0,
1817
- cacheCreation: 0,
1818
- inputIncludesCache: false,
1819
- };
1820
-
1821
- return runSseRequest({
1822
- url,
1823
- headers,
1824
- payload,
1825
- signal,
1826
- timeoutMs,
1827
- onPhase,
1828
- onNonStream: (data) => {
1829
- const content = normalizeAnthropicMessageContent(data && data.content);
1830
- const text = content
1831
- .filter((item) => item.type === "text")
1832
- .map((item) => item.text)
1833
- .join("");
1834
- if (text && typeof onTextDelta === "function") {
1835
- onTextDelta(text);
1836
- }
1837
- addUsageTotals(turnUsage, readAnthropicUsage(data && data.usage, { includeOutput: true }));
1838
- return {
1839
- text,
1840
- assistantContent: content,
1841
- toolCalls: extractAnthropicToolCalls(content),
1842
- usage: turnUsage,
1843
- };
1844
- },
1845
- onEvent: ({ event, data }) => {
1846
- const payloadChunk = parseJsonSafe(data, null);
1847
- if (!payloadChunk || typeof payloadChunk !== "object") return;
1848
-
1849
- if (event === "error") {
1850
- const errMsg = payloadChunk.error && payloadChunk.error.message
1851
- ? String(payloadChunk.error.message)
1852
- : "anthropic stream error";
1853
- throw new Error(errMsg);
1854
- }
1855
-
1856
- if (event === "message_start") {
1857
- const messageUsage = readAnthropicUsage(
1858
- payloadChunk.message && typeof payloadChunk.message === "object"
1859
- ? payloadChunk.message.usage
1860
- : null
1861
- );
1862
- if (messageUsage) {
1863
- turnUsage.input = messageUsage.input;
1864
- turnUsage.cacheRead = messageUsage.cacheRead;
1865
- turnUsage.cacheCreation = messageUsage.cacheCreation;
1866
- }
1867
- return;
1868
- }
1869
-
1870
- if (event === "message_delta") {
1871
- const deltaUsage = payloadChunk.usage && typeof payloadChunk.usage === "object"
1872
- ? payloadChunk.usage
1873
- : {};
1874
- turnUsage.output += toUsageInt(deltaUsage.output_tokens);
1875
- return;
1876
- }
1877
-
1878
- if (event === "content_block_start") {
1879
- let index;
1880
- if (Number.isFinite(payloadChunk.index)) {
1881
- index = payloadChunk.index;
1882
- } else {
1883
- // Provider omitted index: each start opens a new block, so give
1884
- // it its own synthetic index instead of collapsing every block
1885
- // into slot 0.
1886
- while (blockMap.has(nextSyntheticBlockIndex)) nextSyntheticBlockIndex += 1;
1887
- index = nextSyntheticBlockIndex;
1888
- nextSyntheticBlockIndex += 1;
1889
- }
1890
- lastBlockIndex = index;
1891
- const contentBlock = payloadChunk.content_block && typeof payloadChunk.content_block === "object"
1892
- ? payloadChunk.content_block
1893
- : {};
1894
-
1895
- if (contentBlock.type === "text") {
1896
- blockMap.set(index, {
1897
- order: index,
1898
- type: "text",
1899
- text: String(contentBlock.text || ""),
1900
- });
1901
- } else if (contentBlock.type === "thinking") {
1902
- blockMap.set(index, {
1903
- order: index,
1904
- type: "thinking",
1905
- text: String(contentBlock.thinking || ""),
1906
- signature: String(contentBlock.signature || ""),
1907
- });
1908
- } else if (contentBlock.type === "tool_use") {
1909
- blockMap.set(index, {
1910
- order: index,
1911
- type: "tool_use",
1912
- id: String(contentBlock.id || ""),
1913
- name: String(contentBlock.name || ""),
1914
- input: contentBlock.input && typeof contentBlock.input === "object" && !Array.isArray(contentBlock.input)
1915
- ? { ...contentBlock.input }
1916
- : {},
1917
- inputJson: "",
1918
- });
1919
- const toolName = String(contentBlock.name || "");
1920
- if (toolName) {
1921
- emitPhase(onPhase, { type: "tool_request", name: toolName });
1922
- }
1923
- }
1924
- return;
1925
- }
1926
-
1927
- if (event === "content_block_delta") {
1928
- let index;
1929
- if (Number.isFinite(payloadChunk.index)) {
1930
- index = payloadChunk.index;
1931
- } else if (lastBlockIndex >= 0) {
1932
- // No index: continuation of the most recently started block.
1933
- index = lastBlockIndex;
1934
- } else {
1935
- index = 0;
1936
- }
1937
- const delta = payloadChunk.delta && typeof payloadChunk.delta === "object"
1938
- ? payloadChunk.delta
1939
- : {};
1940
- const current = blockMap.get(index) || { order: index, type: "text", text: "" };
1941
-
1942
- if (delta.type === "text_delta") {
1943
- const deltaText = String(delta.text || "");
1944
- current.type = "text";
1945
- current.text = `${String(current.text || "")}${deltaText}`;
1946
- blockMap.set(index, current);
1947
- if (deltaText) {
1948
- responseText += deltaText;
1949
- emitPhase(onPhase, { type: "text_delta", text: deltaText });
1950
- if (typeof onTextDelta === "function") {
1951
- onTextDelta(deltaText);
1952
- }
1953
- }
1954
- return;
1955
- }
1956
-
1957
- if (delta.type === "thinking_delta") {
1958
- const deltaText = String(delta.thinking || "");
1959
- current.type = "thinking";
1960
- current.text = `${String(current.text || "")}${deltaText}`;
1961
- blockMap.set(index, current);
1962
- if (deltaText) {
1963
- emitPhase(onPhase, { type: "thinking_delta", text: deltaText });
1964
- if (typeof onThinkingDelta === "function") {
1965
- onThinkingDelta(deltaText);
1966
- }
1967
- }
1968
- return;
1969
- }
1970
-
1971
- if (delta.type === "signature_delta") {
1972
- // Signed thinking blocks must be replayed verbatim on later turns
1973
- // (tool-use continuation contract), so accumulate the signature
1974
- // alongside the thinking text.
1975
- current.type = "thinking";
1976
- current.signature = `${String(current.signature || "")}${String(delta.signature || "")}`;
1977
- blockMap.set(index, current);
1978
- return;
1979
- }
1980
-
1981
- if (delta.type === "input_json_delta") {
1982
- current.type = "tool_use";
1983
- current.inputJson = `${String(current.inputJson || "")}${String(delta.partial_json || "")}`;
1984
- blockMap.set(index, current);
1985
- return;
1986
- }
1987
- }
1988
- },
1989
- buildResult: () => {
1990
- const assistantContent = Array.from(blockMap.values())
1991
- .sort((a, b) => a.order - b.order)
1992
- .map((item) => {
1993
- if (item.type === "thinking") {
1994
- // Kept (with signature) so tool-use continuation turns can
1995
- // replay the thinking blocks the API requires.
1996
- return {
1997
- type: "thinking",
1998
- thinking: String(item.text || ""),
1999
- signature: String(item.signature || ""),
2000
- };
2001
- }
2002
-
2003
- if (item.type === "text") {
2004
- return {
2005
- type: "text",
2006
- text: String(item.text || ""),
2007
- };
2008
- }
2009
-
2010
- const inputFromDelta = normalizeToolCallArgs(item.inputJson || "");
2011
- const mergedInput = {
2012
- ...(item.input && typeof item.input === "object" ? item.input : {}),
2013
- ...(inputFromDelta && typeof inputFromDelta === "object" ? inputFromDelta : {}),
2014
- };
2015
- return {
2016
- type: "tool_use",
2017
- id: String(item.id || `tool_${randomUUID()}`),
2018
- name: String(item.name || ""),
2019
- input: mergedInput,
2020
- };
2021
- });
2022
-
2023
- if (!responseText) {
2024
- responseText = assistantContent
2025
- .filter((item) => item.type === "text")
2026
- .map((item) => item.text)
2027
- .join("");
2028
- }
2029
-
2030
- return {
2031
- text: responseText,
2032
- assistantContent,
2033
- toolCalls: extractAnthropicToolCalls(assistantContent),
2034
- usage: turnUsage,
2035
- };
2036
- },
2037
- });
2038
- }
2039
-
2040
- const {
2041
- createOpenAiChatTransport,
2042
- createOpenAiResponsesTransport,
2043
- createAnthropicMessagesTransport,
2044
- } = require("./providers");
2045
-
2046
- // Transport descriptors: wire-format only. Plan Mode / leases / policy live in the loop.
2047
- const TRANSPORTS = {
2048
- "openai-chat": createOpenAiChatTransport({
2049
- resolveUrl: resolveCompletionUrl,
2050
- runTurn: runOpenAiLikeTurn,
2051
- normalizeToolName,
2052
- normalizeToolCallArgs,
2053
- toJsonString,
2054
- clipText,
2055
- }),
2056
- "openai-responses": createOpenAiResponsesTransport({
2057
- resolveUrl: resolveResponsesUrl,
2058
- runTurn: runResponsesTurn,
2059
- normalizeToolName,
2060
- normalizeToolCallArgs,
2061
- toJsonString,
2062
- clipText,
2063
- }),
2064
- "anthropic-messages": createAnthropicMessagesTransport({
2065
- resolveUrl: resolveAnthropicMessagesUrl,
2066
- runTurn: runAnthropicTurn,
2067
- toJsonString,
2068
- clipText,
2069
- }),
2070
- };
2071
-
2072
- function pendingToolCallId(pending = null) {
2073
- if (!pending || !pending.source) return "";
2074
- return String(pending.source.id || "").trim();
2075
- }
2076
-
2077
- function shadowDeclarePendingCalls(ledger, pendingCalls = []) {
2078
- const entries = (Array.isArray(pendingCalls) ? pendingCalls : []).map((pending) => ({
2079
- callId: pendingToolCallId(pending) || `call_${randomUUID()}`,
2080
- name: String(pending && pending.name || "").trim().toLowerCase(),
2081
- args: pending && pending.args != null ? pending.args : {},
2082
- }));
2083
- // Keep source ids aligned when we had to synthesize.
2084
- for (let i = 0; i < entries.length; i += 1) {
2085
- const pending = pendingCalls[i];
2086
- if (pending && pending.source && !pending.source.id) {
2087
- pending.source.id = entries[i].callId;
2088
- }
2089
- }
2090
- return declareCalls(ledger, entries);
2091
- }
2092
-
2093
- function shadowResolvePending(ledger, pending, toolResult) {
2094
- if (!ledger) return;
2095
- const callId = pendingToolCallId(pending);
2096
- if (!callId) return;
2097
- resolveCall(ledger, callId, {
2098
- result: sanitizeToolResultForModel(toolResult),
2099
- isError: Boolean(!toolResult || toolResult.ok === false),
2100
- });
2101
- }
2102
-
2103
- function pendingByIdMap(pendingCalls = []) {
2104
- const map = Object.create(null);
2105
- for (const pending of pendingCalls) {
2106
- const id = pendingToolCallId(pending);
2107
- if (id) map[id] = pending;
2108
- }
2109
- return map;
2110
- }
2111
-
2112
- function flushLedgerToolResults(ledger, transport, messages, pendingCalls) {
2113
- return materializeResolvedToolResults(ledger, {
2114
- transport,
2115
- messages,
2116
- pendingById: pendingByIdMap(pendingCalls),
2117
- });
2118
- }
2119
-
2120
- async function runNativeLoop({
2121
- transport,
2122
- workspaceRoot = process.cwd(),
2123
- prompt = "",
2124
- systemPrompt = "",
2125
- systemBlocks = null,
2126
- historyMessages = [],
2127
- model = "",
2128
- baseUrl = "",
2129
- apiKey = "",
2130
- provider = "",
2131
- accountId = "",
2132
- timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
2133
- maxToolCalls = undefined,
2134
- onStreamDelta = null,
2135
- onThinkingDelta = null,
2136
- onPhase = null,
2137
- onToolEvent = null,
2138
- onArtifactPersisted = null,
2139
- onContextUsage = null,
2140
- sessionId = "",
2141
- signal = null,
2142
- guards,
2143
- executionState: initialExecutionState = null,
2144
- resume = false,
2145
- } = {}) {
2146
- const requestModel = String(model || "").trim();
2147
- if (!requestModel) {
2148
- throw new Error("ucode model is not configured");
2149
- }
2150
- const {
2151
- contextTokensFromUsage,
2152
- buildContextMeter,
2153
- } = require("./contextWindow");
2154
- function emitContextUsage(turnUsage = null) {
2155
- const contextTokens = contextTokensFromUsage(turnUsage);
2156
- usage.lastContextTokens = contextTokens;
2157
- if (typeof onContextUsage !== "function") return;
2158
- try {
2159
- onContextUsage(buildContextMeter({
2160
- usedTokens: contextTokens,
2161
- model: requestModel,
2162
- }));
2163
- } catch {
2164
- // ignore UI callback failures
2165
- }
2166
- }
2167
-
2168
- const requestUrl = transport.resolveUrl(baseUrl);
2169
- if (!requestUrl) {
2170
- throw new Error("ucode baseUrl is not configured");
2171
- }
2172
-
2173
- // Durable Agent Loop transcript (returned + synced to session). Provider
2174
- // turns that serve TaskFocus use a fresh providerMessages list instead.
2175
- const messages = sanitizeModelMessages(cloneMessageList(historyMessages));
2176
- if (!resume) {
2177
- transport.prepareMessages({ messages, systemPrompt, prompt });
2178
- }
2179
- // Request history is provider-local. Capture the boundary only after the
2180
- // provider has prepared system/user input, then expose new model/tool items
2181
- // as an explicit current-turn delta. Durable history never infers a delta
2182
- // by comparing this mutable wire array with a persisted transcript.
2183
- const turnOutputStart = messages.length;
2184
- const isProviderToolResultUserMessage = (message) => (
2185
- String(message && message.role || "").toLowerCase() === "user"
2186
- && Array.isArray(message.content)
2187
- && message.content.some((block) => {
2188
- const type = String(block && block.type || "").toLowerCase();
2189
- return type === "tool_result" || type === "image" || type === "image_url";
2190
- })
2191
- );
2192
- const currentTurnItems = () => cloneMessageList(messages.slice(turnOutputStart))
2193
- // External user input is committed by the turn coordinator before this
2194
- // loop starts. Any later user-role messages are runtime nudges/mailbox
2195
- // controls for the provider and must not appear as user chat history.
2196
- .filter((message) => (
2197
- String(message && message.role || "").toLowerCase() !== "user"
2198
- || isProviderToolResultUserMessage(message)
2199
- ));
2200
-
2201
- let aggregated = "";
2202
- let streamed = false;
2203
- let toolCallsExecuted = 0;
2204
- let toolErrors = 0;
2205
- let emptyTerminalRetries = 0;
2206
- let executionState = initialExecutionState && typeof initialExecutionState === "object"
2207
- ? initialExecutionState
2208
- : emptyExecutionState();
2209
- if (typeof executionState.planMode !== "boolean") executionState.planMode = false;
2210
- ensurePendingUserPrompts(executionState);
2211
- const toolBudget = resolveNativeToolBudget(maxToolCalls);
2212
- const toolLoopGuard = new ToolLoopGuard();
2213
- const usage = createUsageTotals();
2214
- // Shadow Tool Call Ledger (R1). Observes declare/defer/resolve; does not
2215
- // materialize Provider messages yet. STRICT via UFOO_UCODE_PROTOCOL_STRICT=1.
2216
- let activeLedger = null;
2217
- let lastProtocolLedger = null;
2218
- let planAutoContinues = 0;
2219
- let lastAutoContinueWaitingId = "";
2220
- let consecutiveEmptyAutoContinues = 0;
2221
- let providerMessages = messages;
2222
- let isolatedActive = false;
2223
- let isolatedPrefixLength = 0;
2224
-
2225
- if (resume) {
2226
- await withFaultPoint("before_provider_resume", () => {});
2227
- }
2228
-
2229
- function injectPendingUserReminders() {
2230
- const nudges = drainUserPrompts(executionState);
2231
- if (nudges.length === 0) return "";
2232
- toolLoopGuard.reset();
2233
- const waiting = executionState.planGraph && executionState.planGraph.waitingFor
2234
- ? executionState.planGraph.waitingFor
2235
- : null;
2236
- return formatUserReminderMessage(nudges, { waitingFor: waiting }) || "";
2237
- }
2238
-
2239
- /** Deliver mid-loop TaskRun runtime events before the next model call. */
2240
- function injectRuntimeMailboxEvents(targetMessages) {
2241
- const drained = drainAgentMailboxForTurn(executionState);
2242
- if (!drained.text) return false;
2243
- toolLoopGuard.reset();
2244
- targetMessages.push({ role: "user", content: drained.text });
2245
- return true;
2246
- }
2247
-
2248
- /**
2249
- * Mirror provider-only TaskFocus deltas onto the durable transcript so
2250
- * session sync / ask_user resume still see tool_use pairs, without feeding
2251
- * the full Agent Loop history back into the next isolated provider turn.
2252
- */
2253
- function mirrorIsolatedDeltaToDurable() {
2254
- if (!isolatedActive || providerMessages === messages) return;
2255
- const delta = providerMessages.slice(isolatedPrefixLength);
2256
- for (const entry of delta) {
2257
- messages.push(cloneMessageList([entry])[0]);
2258
- }
2259
- isolatedPrefixLength = providerMessages.length;
2260
- }
2261
-
2262
- /**
2263
- * Serve waiting TaskRun / plan-task turns on a fresh one-message context.
2264
- * Durable `messages` is left intact for transcript sync.
2265
- */
2266
- function applyIsolatedTaskFocusContext() {
2267
- if (!shouldIsolateTaskFocusTurn(executionState)) {
2268
- isolatedActive = false;
2269
- providerMessages = messages;
2270
- isolatedPrefixLength = 0;
2271
- return false;
2272
- }
2273
- const drained = drainAgentMailboxForTurn(executionState);
2274
- const userNudge = injectPendingUserReminders();
2275
- if (drained.events && drained.events.length > 0) toolLoopGuard.reset();
2276
- const isolated = buildIsolatedTaskFocusTurn(executionState, {
2277
- mailboxEvents: drained.events || [],
2278
- userNudge,
2279
- });
2280
- providerMessages = isolated.messages;
2281
- isolatedActive = true;
2282
- isolatedPrefixLength = providerMessages.length;
2283
- return true;
2284
- }
2285
-
2286
- function nextAutoContinueKey() {
2287
- const waitingId = String(
2288
- (executionState.planGraph && executionState.planGraph.waitingFor
2289
- && executionState.planGraph.waitingFor.id) || ""
2290
- ).trim();
2291
- if (waitingId) return `plan:${waitingId}`;
2292
- const runs = listTaskRunsAwaitingModel(executionState);
2293
- if (runs.length > 0) {
2294
- return `task:${runs.map((run) => run.id).sort().join(",")}`;
2295
- }
2296
- return "mailbox";
2297
- }
2298
-
2299
- function tryInjectAgentAutoContinue() {
2300
- if (planAutoContinues >= DEFAULT_MAX_PLAN_AUTO_CONTINUES) return false;
2301
- const continueKey = nextAutoContinueKey();
2302
- if (
2303
- consecutiveEmptyAutoContinues >= 2
2304
- && continueKey
2305
- && continueKey === lastAutoContinueWaitingId
2306
- ) {
2307
- return false;
2308
- }
2309
-
2310
- // TaskFocus isolation rebuilds providerMessages at the top of the next
2311
- // loop iteration — just signal continue when a task/plan still needs service.
2312
- if (shouldIsolateTaskFocusTurn(executionState) || shouldAutoContinueForTaskWake(executionState)) {
2313
- planAutoContinues += 1;
2314
- lastAutoContinueWaitingId = continueKey;
2315
- consecutiveEmptyAutoContinues += 1;
2316
- return true;
2317
- }
2318
-
2319
- if (injectRuntimeMailboxEvents(messages)) {
2320
- planAutoContinues += 1;
2321
- lastAutoContinueWaitingId = continueKey;
2322
- consecutiveEmptyAutoContinues += 1;
2323
- return true;
2324
- }
2325
-
2326
- if (shouldAutoContinuePlan(executionState)) {
2327
- const reminder = buildPlanAutoContinueReminder(executionState);
2328
- if (!reminder) return false;
2329
- messages.push({ role: "user", content: reminder });
2330
- planAutoContinues += 1;
2331
- lastAutoContinueWaitingId = continueKey;
2332
- consecutiveEmptyAutoContinues += 1;
2333
- return true;
2334
- }
2335
-
2336
- return false;
2337
- }
2338
-
2339
- while (true) {
2340
- guards.ensureActive();
2341
-
2342
- if (!applyIsolatedTaskFocusContext()) {
2343
- const nudge = injectPendingUserReminders();
2344
- if (nudge) messages.push({ role: "user", content: nudge });
2345
- injectRuntimeMailboxEvents(messages);
2346
- }
2347
-
2348
- if (activeLedger) {
2349
- runProviderTurnGate(activeLedger);
2350
- }
2351
-
2352
- // Check only after the preceding batch has been fully materialized. A
2353
- // warning must never split tool calls from their results, and a stop must
2354
- // return the completed transcript instead of losing it through an exception.
2355
- const loopAction = toolLoopGuard.nextAction();
2356
- if (loopAction && loopAction.kind === "stop") {
2357
- return {
2358
- error: loopAction.message,
2359
- stopReason: "repeated_tool_calls",
2360
- text: aggregated,
2361
- streamed,
2362
- toolCallsExecuted,
2363
- messages,
2364
- turnItems: currentTurnItems(),
2365
- usage,
2366
- executionState,
2367
- protocolLedger: lastProtocolLedger,
2368
- };
2369
- }
2370
- if (loopAction && loopAction.kind === "warn") {
2371
- providerMessages.push({ role: "user", content: loopAction.message });
2372
- }
2373
-
2374
- const turnResult = await transport.runTurn({
2375
- url: requestUrl,
2376
- apiKey,
2377
- model: requestModel,
2378
- provider,
2379
- accountId,
2380
- systemPrompt,
2381
- systemBlocks,
2382
- messages: providerMessages,
2383
- sessionId,
2384
- signal,
2385
- timeoutMs,
2386
- onPhase,
2387
- onThinkingDelta,
2388
- onTextDelta: (chunk) => {
2389
- const text = String(chunk || "");
2390
- if (!text) return;
2391
- aggregated += text;
2392
- if (typeof onStreamDelta === "function") {
2393
- streamed = true;
2394
- onStreamDelta(text);
2395
- }
2396
- },
2397
- });
2398
-
2399
- // Images belong to the request that just completed, not subsequent tool
2400
- // iterations. Run only after success so failed requests retain their images.
2401
- // TaskFocus may already have mirrored these blocks into the main transcript.
2402
- retireMessageImages(providerMessages);
2403
- if (providerMessages !== messages) retireMessageImages(messages);
2404
-
2405
- usage.turns += 1;
2406
- addUsageTotals(usage, turnResult && turnResult.usage);
2407
- emitContextUsage(turnResult && turnResult.usage);
2408
-
2409
- const toolCalls = transport.getToolCalls(turnResult);
2410
-
2411
- if (toolCalls.length === 0) {
2412
- toolLoopGuard.reset();
2413
- const text = String(turnResult.text || "").trim();
2414
- if (!text && toolCallsExecuted > 0) {
2415
- if (emptyTerminalRetries >= MAX_EMPTY_TERMINAL_RETRIES) {
2416
- throw new Error("model returned an empty response after tool execution");
2417
- }
2418
- emptyTerminalRetries += 1;
2419
- providerMessages.push({
2420
- role: "user",
2421
- content: [
2422
- "Continue the current task after the tool results.",
2423
- "Call any remaining tools, or provide a concrete final answer to the user.",
2424
- "Do not end the turn with an empty response.",
2425
- ].join(" "),
2426
- });
2427
- continue;
2428
- }
2429
- emptyTerminalRetries = 0;
2430
- const sideEffects = parseStructuredSideEffects(text);
2431
- const planCommand = sideEffects ? normalizePlanGraphCommand(sideEffects) : null;
2432
- if (planCommand) {
2433
- guards.ensureActive();
2434
- transport.appendFinalAssistantMessage({ messages: providerMessages, turnResult });
2435
- const planResult = runCoreTool({
2436
- tool: "plan_graph",
2437
- args: planCommand,
2438
- workspaceRoot,
2439
- onToolEvent,
2440
- sessionId,
2441
- onArtifactPersisted,
2442
- executionState,
2443
- origin: { kind: "legacy_side_effect", source: planCommand.source || "legacy" },
2444
- });
2445
- guards.ensureActive();
2446
- if (planResult && planResult.executionState) {
2447
- executionState = planResult.executionState;
2448
- }
2449
- providerMessages.push({
2450
- role: "user",
2451
- content: JSON.stringify({
2452
- type: "plan_graph_result",
2453
- ...sanitizeToolResultForModel(
2454
- (planResult && planResult.status)
2455
- ? planResult
2456
- : { status: "rejected", ok: false, error: "plan_graph failed" },
2457
- ),
2458
- }),
2459
- });
2460
- mirrorIsolatedDeltaToDurable();
2461
- continue;
2462
- }
2463
- transport.appendFinalAssistantMessage({ messages: providerMessages, turnResult });
2464
- mirrorIsolatedDeltaToDurable();
2465
- if (!aggregated.trim() && text) {
2466
- aggregated = text;
2467
- }
2468
- if (tryInjectAgentAutoContinue()) {
2469
- continue;
2470
- }
2471
- return {
2472
- text: aggregated,
2473
- streamed,
2474
- toolCallsExecuted,
2475
- messages,
2476
- turnItems: currentTurnItems(),
2477
- usage,
2478
- executionState,
2479
- protocolLedger: lastProtocolLedger || snapshotLedger(activeLedger),
2480
- };
2481
- }
2482
-
2483
- // A tool-using turn resets the empty auto-continue streak (progress possible).
2484
- consecutiveEmptyAutoContinues = 0;
2485
- emptyTerminalRetries = 0;
2486
-
2487
- const pendingCalls = transport.prepareToolCalls({
2488
- messages: providerMessages,
2489
- turnResult,
2490
- toolCalls,
2491
- });
2492
- if (!pendingCalls) {
2493
- mirrorIsolatedDeltaToDurable();
2494
- return {
2495
- text: aggregated,
2496
- streamed,
2497
- toolCallsExecuted,
2498
- messages,
2499
- turnItems: currentTurnItems(),
2500
- usage,
2501
- executionState,
2502
- protocolLedger: lastProtocolLedger || snapshotLedger(activeLedger),
2503
- };
2504
- }
2505
-
2506
- toolLoopGuard.observe(pendingCalls);
2507
- activeLedger = createToolCallLedger({ provider, sessionId });
2508
- shadowDeclarePendingCalls(activeLedger, pendingCalls);
2509
- lastProtocolLedger = snapshotLedger(activeLedger);
2510
- await withFaultPoint("after_prepare_tool_calls", () => {});
2511
- await withFaultPoint("before_tool_exec", () => {});
2512
-
2513
- const callNames = pendingCalls.map((call) => String(call.name || "").trim().toLowerCase());
2514
- const hasControlPlane = callNames.some((name) => CONTROL_PLANE_TOOLS.has(name));
2515
- const hasAskUser = callNames.includes("ask_user");
2516
- const hasDataTool = callNames.some((name) => EXECUTABLE_GRAPH_TOOLS.has(name));
2517
- if (hasControlPlane && hasDataTool) {
2518
- // prepareToolCalls already appended the assistant tool_calls / tool_use
2519
- // message; every declared call must get a contiguous tool result via ledger.
2520
- const rejected = {
2521
- ok: false,
2522
- status: "rejected",
2523
- error: "Do not mix plan_graph/task_run with data-plane tools in the same turn",
2524
- code: "MIXED_PLAN_AND_DATA_TOOLS",
2525
- };
2526
- for (const pending of pendingCalls) {
2527
- shadowResolvePending(activeLedger, pending, rejected);
2528
- toolCallsExecuted += 1;
2529
- toolErrors += 1;
2530
- }
2531
- flushLedgerToolResults(activeLedger, transport, providerMessages, pendingCalls);
2532
- mirrorIsolatedDeltaToDurable();
2533
- lastProtocolLedger = snapshotLedger(activeLedger);
2534
- continue;
2535
- }
2536
- if (hasAskUser && pendingCalls.length > 1) {
2537
- const rejected = {
2538
- ok: false,
2539
- status: "rejected",
2540
- error: "ask_user must be the only tool call in the turn",
2541
- code: "ASK_USER_MUST_BE_ALONE",
2542
- };
2543
- for (const pending of pendingCalls) {
2544
- shadowResolvePending(activeLedger, pending, rejected);
2545
- toolCallsExecuted += 1;
2546
- toolErrors += 1;
2547
- }
2548
- flushLedgerToolResults(activeLedger, transport, providerMessages, pendingCalls);
2549
- mirrorIsolatedDeltaToDurable();
2550
- lastProtocolLedger = snapshotLedger(activeLedger);
2551
- continue;
2552
- }
2553
-
2554
- let deferredAskUser = null;
2555
- for (const pending of pendingCalls) {
2556
- const pendingName = String(pending.name || "").trim().toLowerCase();
2557
- if (
2558
- EXECUTABLE_GRAPH_TOOLS.has(pendingName)
2559
- && activePlanRequiresExpansion(executionState.planGraph)
2560
- ) {
2561
- const blocked = {
2562
- ok: false,
2563
- status: "rejected",
2564
- errors: [{
2565
- code: "ACTIVE_PLAN_REQUIRES_EXPANSION",
2566
- message: "Active plan is waiting on a task; use plan_graph expand_node or control.complete_task instead of direct tools",
2567
- }],
2568
- };
2569
- toolCallsExecuted += 1;
2570
- toolErrors += 1;
2571
- shadowResolvePending(activeLedger, pending, blocked);
2572
- continue;
2573
- }
2574
- if (planModeBlocksDirectTool(pendingName, executionState)) {
2575
- const blocked = {
2576
- ok: false,
2577
- status: "rejected",
2578
- errors: [{
2579
- code: "PLAN_MODE_BLOCKS_SIDE_EFFECT",
2580
- message: "Plan mode is on; use plan_graph for write/edit/bash, or ask the user to /plan off",
2581
- }],
2582
- };
2583
- toolCallsExecuted += 1;
2584
- toolErrors += 1;
2585
- shadowResolvePending(activeLedger, pending, blocked);
2586
- continue;
2587
- }
2588
- const leaseCheck = checkWriteAllowed(executionState, {
2589
- tool: pendingName,
2590
- originKind: "agent_loop",
2591
- });
2592
- if (!leaseCheck.ok) {
2593
- const blocked = {
2594
- ok: false,
2595
- status: "rejected",
2596
- errors: [{
2597
- code: leaseCheck.code || "WORKSPACE_WRITE_LEASE_HELD",
2598
- message: leaseCheck.message
2599
- || "Workspace write lease held by an active TaskRun",
2600
- owner: leaseCheck.owner || null,
2601
- }],
2602
- };
2603
- toolCallsExecuted += 1;
2604
- toolErrors += 1;
2605
- shadowResolvePending(activeLedger, pending, blocked);
2606
- continue;
2607
- }
2608
-
2609
- const toolCallId = pending.source && (pending.source.id || (pending.source.function && pending.source.id))
2610
- ? String(pending.source.id || "")
2611
- : "";
2612
- const resumeForAsk = pendingName === "ask_user"
2613
- ? {
2614
- toolCallId: toolCallId || String((pending.source && pending.source.id) || `call_${randomUUID()}`),
2615
- toolName: "ask_user",
2616
- call: {
2617
- name: pending.name,
2618
- args: pending.args,
2619
- source: pending.source,
2620
- },
2621
- }
2622
- : null;
2623
-
2624
- markExecuting(activeLedger, pendingToolCallId(pending));
2625
- guards.ensureActive();
2626
- const toolResult = await runCoreToolAsync({
2627
- tool: pending.name,
2628
- args: pending.args,
2629
- workspaceRoot,
2630
- onToolEvent,
2631
- sessionId,
2632
- onArtifactPersisted,
2633
- executionState,
2634
- resume: resumeForAsk,
2635
- signal,
2636
- });
2637
- guards.ensureActive();
2638
- if (toolResult && toolResult.executionState) {
2639
- executionState = toolResult.executionState;
2640
- }
2641
- toolCallsExecuted += 1;
2642
- if (!toolResult || toolResult.ok === false) {
2643
- toolErrors += 1;
2644
- }
2645
-
2646
- if (pendingName === "ask_user" && toolResult && toolResult.deferToolResult) {
2647
- // Attach resume metadata onto pending interaction for contiguous tool_result later.
2648
- const pendingInteraction = getPendingUserInteraction(executionState);
2649
- if (pendingInteraction) {
2650
- pendingInteraction.resume = {
2651
- ...(pendingInteraction.resume || {}),
2652
- ...(resumeForAsk || {}),
2653
- mode: "ask_user",
2654
- transport: provider === "anthropic" ? "anthropic-messages" : "openai-chat",
2655
- };
2656
- }
2657
- deferCall(activeLedger, pendingToolCallId(pending), { reason: "ask_user" });
2658
- deferredAskUser = { call: pending, interactionId: toolResult.interactionId || "" };
2659
- continue;
2660
- }
2661
-
2662
- enforceNativeToolBudget({
2663
- toolCallsExecuted,
2664
- toolErrors,
2665
- maxToolCalls: toolBudget.maxToolCalls,
2666
- maxToolErrors: toolBudget.maxToolErrors,
2667
- lastTool: pending.name,
2668
- lastError: toolResult && toolResult.error ? String(toolResult.error) : "",
2669
- });
2670
- shadowResolvePending(activeLedger, pending, toolResult);
2671
- }
2672
-
2673
- flushLedgerToolResults(activeLedger, transport, providerMessages, pendingCalls);
2674
- mirrorIsolatedDeltaToDurable();
2675
- lastProtocolLedger = snapshotLedger(activeLedger);
2676
-
2677
- if (deferredAskUser) {
2678
- return {
2679
- text: aggregated,
2680
- streamed,
2681
- toolCallsExecuted,
2682
- messages,
2683
- turnItems: currentTurnItems(),
2684
- usage,
2685
- executionState,
2686
- waitingUserInteraction: true,
2687
- interactionId: deferredAskUser.interactionId || "",
2688
- protocolLedger: lastProtocolLedger,
2689
- };
2690
- }
2691
-
2692
- if (hasPendingUserInteraction(executionState)) {
2693
- // Checkpoint approval synced from plan_graph — pause for TUI.
2694
- return {
2695
- text: aggregated,
2696
- streamed,
2697
- toolCallsExecuted,
2698
- messages,
2699
- turnItems: currentTurnItems(),
2700
- usage,
2701
- executionState,
2702
- waitingUserInteraction: true,
2703
- interactionId: (getPendingUserInteraction(executionState) || {}).id || "",
2704
- protocolLedger: lastProtocolLedger,
2705
- };
2706
- }
2707
- }
75
+ return runtime.run({ ...options, toolBudget: resolveNativeToolBudget(options.maxToolCalls) });
2708
76
  }
2709
77
 
2710
78
  function appendAnswerToolResult(messages = [], resume = null, answer = {}, options = {}) {
@@ -2831,7 +199,7 @@ async function runNativeAgentTask({
2831
199
  }
2832
200
  }
2833
201
 
2834
- const transport = TRANSPORTS[runtime.transport] || TRANSPORTS["openai-chat"];
202
+ const transport = getNativeTransport(runtime.transport);
2835
203
 
2836
204
  const runResult = await runNativeLoop({
2837
205
  transport,