u-foo 3.1.7 → 4.0.1

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