u-foo 4.0.0 → 4.0.2

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 (158) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +90 -30
  3. package/README.zh-CN.md +76 -26
  4. package/SKILLS/ufoo/SKILL.md +25 -1
  5. package/SKILLS/ufoo-bus/SKILL.md +25 -2
  6. package/bin/ucode.js +4 -0
  7. package/bin/ufoo.js +3 -3
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +6 -6
  13. package/src/agents/activity/activityDetector.js +1 -1
  14. package/src/agents/capabilities/agentManagement/service.js +40 -13
  15. package/src/agents/capabilities/coordination/index.js +1 -1
  16. package/src/agents/capabilities/taskReports/index.js +1 -1
  17. package/src/agents/controller/controllerToolExecutor.js +36 -20
  18. package/src/agents/controller/index.js +1 -6
  19. package/src/agents/internal/internalRunner.js +90 -56
  20. package/src/agents/launch/index.js +0 -1
  21. package/src/agents/launch/launcher.js +38 -29
  22. package/src/agents/launch/launcherReadiness.js +35 -0
  23. package/src/agents/launch/notifier.js +2 -2
  24. package/src/agents/launch/ptyWrapper.js +5 -2
  25. package/src/agents/launch/readyDetector.js +2 -2
  26. package/src/agents/profiles/main.js +1 -1
  27. package/src/agents/prompts/cooperation.js +14 -0
  28. package/src/agents/prompts/defaultBootstrap.js +1 -1
  29. package/src/agents/prompts/groupBootstrap.js +23 -7
  30. package/src/agents/prompts/mainAgent.js +11 -2
  31. package/src/agents/prompts/native/system.js +4 -1
  32. package/src/agents/prompts/native/ufoo.js +11 -3
  33. package/src/agents/prompts/promptProfiles.js +2 -0
  34. package/src/agents/prompts/reporting.js +16 -0
  35. package/src/agents/providers/claudeEventTranslator.js +3 -0
  36. package/src/agents/providers/claudeThreadProvider.js +3 -2
  37. package/src/agents/providers/clientIdentity.js +75 -0
  38. package/src/agents/providers/codexEventTranslator.js +23 -2
  39. package/src/agents/providers/codexThreadProvider.js +15 -6
  40. package/src/agents/providers/credentials/index.js +2 -0
  41. package/src/agents/providers/directAuthStatus.js +1 -1
  42. package/src/agents/providers/index.js +1 -1
  43. package/src/agents/providers/modelSettings.js +34 -0
  44. package/src/agents/providers/modelsCatalog.js +379 -0
  45. package/src/agents/providers/nativeTransport.js +58 -40
  46. package/src/agents/providers/runtimeConfig.js +10 -8
  47. package/src/agents/providers/thinkingLevels.js +10 -36
  48. package/src/agents/providers/transports/responsesProtocol.js +11 -6
  49. package/src/agents/providers/upstreamRuntime.js +135 -0
  50. package/src/agents/runtime/context/checkpointStore.js +38 -0
  51. package/src/agents/runtime/context/compaction.js +151 -0
  52. package/src/agents/runtime/context/contextBudget.js +93 -0
  53. package/src/agents/runtime/context/replayHistory.js +28 -0
  54. package/src/agents/runtime/context/runtimeStore.js +2 -1
  55. package/src/agents/runtime/core/agentLoop.js +99 -18
  56. package/src/agents/runtime/core/executionBudget.js +36 -0
  57. package/src/agents/runtime/createAgentRuntime.js +16 -4
  58. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  59. package/src/agents/runtime/protocol/runObservation.js +24 -0
  60. package/src/agents/runtime/protocol/traceContext.js +9 -0
  61. package/src/app/chat/ChatController.js +26 -53
  62. package/src/app/chat/agentDirectory.js +1 -16
  63. package/src/app/chat/bootstrap.js +1 -2
  64. package/src/app/chat/commandExecutor.js +93 -285
  65. package/src/app/chat/commands.js +32 -45
  66. package/src/app/chat/daemonMessageRouter.js +0 -45
  67. package/src/app/chat/historyStore.js +12 -48
  68. package/src/app/chat/inputSubmitHandler.js +7 -33
  69. package/src/app/chat/internalAgentLogHistory.js +19 -60
  70. package/src/app/chat/multiWindow/paneManager.js +10 -3
  71. package/src/app/chat/streamState.js +0 -4
  72. package/src/app/cli/features/init.js +5 -5
  73. package/src/app/cli/metricsCommands.js +68 -0
  74. package/src/app/cli/run.js +42 -3
  75. package/src/app/cli/traceCommands.js +36 -0
  76. package/src/code/agent.js +18 -13
  77. package/src/code/busConsumer.js +1 -3
  78. package/src/code/commands.js +1 -1
  79. package/src/code/context/assembler.js +7 -8
  80. package/src/code/context/stateCommit.js +2 -1
  81. package/src/code/internalThread.js +10 -3
  82. package/src/code/launcher/ucode.js +1 -1
  83. package/src/code/launcher/ucodeBootstrap.js +1 -1
  84. package/src/code/modelCommand.js +11 -35
  85. package/src/code/nativeRunner.js +55 -17
  86. package/src/code/providers/modelsCatalog.js +1 -317
  87. package/src/code/repl.js +4 -11
  88. package/src/code/sessionStore.js +3 -3
  89. package/src/code/taskDecomposer.js +18 -0
  90. package/src/code/toolBudget.js +1 -17
  91. package/src/config.js +22 -72
  92. package/src/coordination/bus/index.js +12 -3
  93. package/src/coordination/bus/inject.js +2 -2
  94. package/src/coordination/bus/message.js +15 -1
  95. package/src/coordination/bus/nickname.js +1 -1
  96. package/src/coordination/bus/subscriber.js +3 -2
  97. package/src/coordination/bus/utils.js +1 -1
  98. package/src/coordination/history/agentPerformance.js +279 -0
  99. package/src/coordination/history/agentTrace.js +249 -0
  100. package/src/coordination/state/workspaceAccess.js +1 -1
  101. package/src/orchestration/controller/index.js +1 -8
  102. package/src/orchestration/controller/launchRouting.js +1 -1
  103. package/src/orchestration/solo/commands.js +3 -1
  104. package/src/runtime/contracts/agentMode.js +11 -2
  105. package/src/runtime/contracts/uiProtocol.js +18 -19
  106. package/src/runtime/daemon/agentHost.js +57 -25
  107. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  108. package/src/runtime/daemon/busBridge.js +1 -1
  109. package/src/runtime/daemon/controlPlaneService.js +1 -1
  110. package/src/runtime/daemon/groupOrchestrator.js +20 -5
  111. package/src/runtime/daemon/groupStatus.js +20 -0
  112. package/src/runtime/daemon/index.js +19 -44
  113. package/src/runtime/daemon/mcpHttpServer.js +39 -10
  114. package/src/runtime/daemon/mcpServer.js +1 -1
  115. package/src/runtime/daemon/nicknameScope.js +1 -1
  116. package/src/runtime/daemon/ops.js +46 -23
  117. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  118. package/src/runtime/daemon/promptRequest.js +92 -589
  119. package/src/runtime/daemon/status.js +5 -6
  120. package/src/tools/controllerSchemas.js +6 -2
  121. package/src/tools/handlers/tier2.js +4 -2
  122. package/src/tools/registry.js +4 -0
  123. package/src/tools/schemaFixtures.js +26 -2
  124. package/src/tools/tier0/readAgentMetrics.js +14 -0
  125. package/src/tools/tier0/readAgentTrace.js +12 -0
  126. package/src/ui/agentSettingsController.js +107 -0
  127. package/src/ui/agentSurface.js +1 -1
  128. package/src/ui/dashboardBridge.js +1 -1
  129. package/src/ui/format/banner.js +1 -4
  130. package/src/ui/format/index.js +14 -10
  131. package/src/ui/format/loopSummary.js +50 -0
  132. package/src/ui/format/markdownRenderer.js +3 -4
  133. package/src/ui/rustChatHost.js +191 -206
  134. package/src/ui/rustMultiSession.js +77 -36
  135. package/src/ui/rustUcodeHost.js +6 -1
  136. package/src/ui/settingsBridge.js +33 -16
  137. package/src/ui/toolMergeBridge.js +0 -4
  138. package/src/ui/uiHostServer.js +5 -8
  139. package/src/agents/controller/loopObservability.js +0 -200
  140. package/src/agents/controller/loopRuntime.js +0 -336
  141. package/src/agents/controller/ufooAgent.js +0 -830
  142. package/src/agents/launch/ptyRunner.js +0 -1135
  143. package/src/agents/providers/controllerJsonTransport.js +0 -28
  144. package/src/agents/providers/upstreamTransport.js +0 -698
  145. package/src/app/chat/agentBar.js +0 -135
  146. package/src/app/chat/agentSockets.js +0 -225
  147. package/src/app/chat/dashboardView.js +0 -405
  148. package/src/app/chat/rawKeyMap.js +0 -42
  149. package/src/app/chat/settingsController.js +0 -111
  150. package/src/coordination/history/controllerSummary.js +0 -23
  151. package/src/orchestration/controller/flags.js +0 -167
  152. package/src/orchestration/controller/gateRouter.js +0 -211
  153. package/src/orchestration/controller/routerFastPath.js +0 -22
  154. package/src/orchestration/controller/routerFinalize.js +0 -222
  155. package/src/orchestration/controller/shadowGuard.js +0 -280
  156. package/src/runtime/daemon/executionPaths.js +0 -30
  157. package/src/runtime/daemon/promptLoop.js +0 -136
  158. package/src/runtime/privacy/shadowDiff.js +0 -174
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const os = require("os");
4
+ const { resolveCodexUserAgent, resolveGrokClientVersion } = require("./clientIdentity");
4
5
  const { randomUUID } = require("crypto");
5
6
  const { Agent: UndiciAgent } = require("undici");
6
7
  const { normalizeProvider, normalizeKimiModel, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl } = require("./runtimeConfig");
@@ -9,9 +10,16 @@ const { systemBlocksToAnthropicPayload } = require("./transports/systemBlocks");
9
10
  const { buildResponsesPayload, isResponsesKeepalive, responseEventDelta, parseResponsesEvents, parseResponsesSsePayload } = require("./transports/responsesProtocol");
10
11
 
11
12
  const DEFAULT_NATIVE_TIMEOUT_MS = 43200000;
13
+ const DEFAULT_NATIVE_CONNECT_TIMEOUT_MS = 10 * 60 * 1000;
12
14
  const DEFAULT_OPENAI_MAX_TOKENS = 32768;
13
15
  const DEFAULT_ANTHROPIC_MAX_TOKENS = 32768;
14
- const NATIVE_SSE_DISPATCHER_OPTIONS = Object.freeze({ headersTimeout: 0, bodyTimeout: 0 });
16
+ // Undici otherwise imposes its own 10-second connection deadline, regardless
17
+ // of the model task budget. Explicit cancellation/task deadlines still apply.
18
+ const NATIVE_SSE_DISPATCHER_OPTIONS = Object.freeze({
19
+ connectTimeout: DEFAULT_NATIVE_CONNECT_TIMEOUT_MS,
20
+ headersTimeout: 0,
21
+ bodyTimeout: 0,
22
+ });
15
23
  const ANTHROPIC_CACHE_CONTROL = Object.freeze({ type: "ephemeral" });
16
24
 
17
25
  function nowMs() {
@@ -68,24 +76,6 @@ function resolveMaxTokens(fallback) {
68
76
  return normalizePositiveInt(process.env.UFOO_UCODE_MAX_TOKENS, fallback);
69
77
  }
70
78
 
71
- function resolveThinkingBudgetTokens(options = {}) {
72
- const { resolveThinkingFromEnvAndConfig } = require("./thinkingLevels");
73
- const { loadGlobalUcodeConfig } = require("../../config");
74
- let configLevel = String(options.configLevel || "").trim();
75
- if (!configLevel) {
76
- try {
77
- configLevel = String((loadGlobalUcodeConfig() || {}).ucodeThinking || "").trim();
78
- } catch {
79
- configLevel = "";
80
- }
81
- }
82
- const resolved = resolveThinkingFromEnvAndConfig({
83
- env: options.env || process.env,
84
- configLevel,
85
- });
86
- return resolved.budgetTokens;
87
- }
88
-
89
79
  function resolveReasoningEffort(options = {}) {
90
80
  const { resolveThinkingFromEnvAndConfig } = require("./thinkingLevels");
91
81
  const { loadGlobalUcodeConfig } = require("../../config");
@@ -104,6 +94,10 @@ function resolveReasoningEffort(options = {}) {
104
94
  return resolved.reasoningEffort || "";
105
95
  }
106
96
 
97
+ function thinkingOptions(thinkingLevel) {
98
+ return thinkingLevel ? { configLevel: thinkingLevel, env: {} } : {};
99
+ }
100
+
107
101
  function toUsageInt(value) {
108
102
  const parsed = Number(value);
109
103
  if (!Number.isFinite(parsed) || parsed <= 0) return 0;
@@ -134,14 +128,15 @@ function addUsageTotals(totals, usage = null) {
134
128
  // totals (prompt_tokens_details.cached_tokens counts the cache hits).
135
129
  function readOpenAiUsage(raw) {
136
130
  if (!raw || typeof raw !== "object") return null;
131
+ if (![raw.prompt_tokens, raw.completion_tokens, raw.prompt_tokens_details?.cached_tokens].some(value => value != null && Number.isFinite(Number(value)))) return null;
137
132
  const details = raw.prompt_tokens_details && typeof raw.prompt_tokens_details === "object"
138
133
  ? raw.prompt_tokens_details
139
134
  : {};
140
135
  return {
141
136
  input: toUsageInt(raw.prompt_tokens),
142
137
  output: toUsageInt(raw.completion_tokens),
143
- cacheRead: toUsageInt(details.cached_tokens),
144
- cacheCreation: toUsageInt(details.created_cache_tokens),
138
+ cacheRead: details.cached_tokens != null && Number.isFinite(Number(details.cached_tokens)) ? toUsageInt(details.cached_tokens) : null,
139
+ cacheCreation: toUsageInt(details.cache_write_tokens ?? details.created_cache_tokens),
145
140
  inputIncludesCache: true,
146
141
  };
147
142
  }
@@ -150,6 +145,7 @@ function readOpenAiUsage(raw) {
150
145
  // arrive per message_delta. The non-streaming body carries the full totals.
151
146
  function readAnthropicUsage(raw, { includeOutput = false } = {}) {
152
147
  if (!raw || typeof raw !== "object") return null;
148
+ if (!["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"].some(key => raw[key] != null && Number.isFinite(Number(raw[key])))) return null;
153
149
  return {
154
150
  input: toUsageInt(raw.input_tokens),
155
151
  output: includeOutput ? toUsageInt(raw.output_tokens) : 0,
@@ -380,8 +376,10 @@ async function runOpenAiLikeTurn({
380
376
  requestHeaders = {},
381
377
  model = "",
382
378
  provider = "",
379
+ thinkingLevel = "",
383
380
  messages = [],
384
381
  tools = [],
382
+ maxOutputTokens = null,
385
383
  onTextDelta = null,
386
384
  onThinkingDelta = null,
387
385
  onPhase = null,
@@ -391,21 +389,21 @@ async function runOpenAiLikeTurn({
391
389
  const normalizedProvider = normalizeProvider(provider);
392
390
  const payload = {
393
391
  model: normalizedProvider === "kimi" ? normalizeKimiModel(model) : model,
394
- max_tokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
392
+ max_tokens: maxOutputTokens || resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
395
393
  messages,
396
- tools,
397
- tool_choice: "auto",
394
+ ...(tools.length ? { tools, tool_choice: "auto" } : {}),
398
395
  stream: true,
399
396
  // Ask for the terminal usage chunk so token/cache accounting works.
400
397
  stream_options: { include_usage: true },
401
398
  // Kimi k3 rejects any temperature other than 1.
402
399
  temperature: normalizedProvider === "kimi" ? 1 : 0,
403
400
  };
404
- const reasoningEffort = resolveReasoningEffort();
401
+ const reasoningEffort = thinkingLevel === "off" ? "none" : resolveReasoningEffort(thinkingOptions(thinkingLevel));
405
402
  if (reasoningEffort) {
406
403
  // OpenAI-compatible gateways that support reasoning models accept this;
407
404
  // unknown fields are typically ignored by plain chat models.
408
405
  payload.reasoning_effort = reasoningEffort;
406
+ if (thinkingLevel && normalizedProvider === "openai" && reasoningEffort !== "none") delete payload.temperature;
409
407
  }
410
408
 
411
409
  const headers = normalizedProvider === "kimi"
@@ -550,7 +548,7 @@ async function runOpenAiLikeTurn({
550
548
  }
551
549
 
552
550
  function currentGrokClientVersion() {
553
- return String(process.env.UFOO_GROK_CLIENT_VERSION || "0.2.120").trim() || "0.2.120";
551
+ return resolveGrokClientVersion();
554
552
  }
555
553
 
556
554
  function isGrokCliProxyUrl(url = "") {
@@ -595,10 +593,7 @@ function buildResponsesHeaders({ provider = "", apiKey = "", sessionId = "", acc
595
593
  if (apiKey) headers.authorization = `Bearer ${apiKey}`;
596
594
 
597
595
  if (normalizedProvider === "codex") {
598
- headers["User-Agent"] = String(
599
- process.env.UFOO_CODEX_USER_AGENT
600
- || "codex-tui/0.118.0 (Mac OS 26.3.1; arm64) iTerm.app/3.6.9 (codex-tui; 0.118.0)"
601
- );
596
+ headers["User-Agent"] = resolveCodexUserAgent();
602
597
  headers.Originator = "codex-tui";
603
598
  headers["Session-Id"] = String(sessionId || randomUUID());
604
599
  if (accountId) headers["Chatgpt-Account-Id"] = String(accountId);
@@ -629,9 +624,11 @@ async function runResponsesTurn({
629
624
  requestProfile = "",
630
625
  model = "",
631
626
  provider = "",
627
+ thinkingLevel = "",
632
628
  systemPrompt = "",
633
629
  messages = [],
634
630
  tools = [],
631
+ maxOutputTokens = null,
635
632
  sessionId = "",
636
633
  accountId = "",
637
634
  onTextDelta = null,
@@ -645,8 +642,8 @@ async function runResponsesTurn({
645
642
  instructions: systemPrompt,
646
643
  messages,
647
644
  tools,
648
- maxOutputTokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
649
- reasoningEffort: resolveReasoningEffort(),
645
+ maxOutputTokens: maxOutputTokens || resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
646
+ reasoningEffort: thinkingLevel === "off" ? "none" : resolveReasoningEffort(thinkingOptions(thinkingLevel)),
650
647
  provider: normalizeProvider(provider),
651
648
  });
652
649
  const headers = buildResponsesHeaders({ provider, apiKey, sessionId, accountId, url });
@@ -820,10 +817,12 @@ async function runAnthropicTurn({
820
817
  apiKey = "",
821
818
  requestHeaders = {},
822
819
  model = "",
820
+ thinkingLevel = "",
823
821
  systemPrompt = "",
824
822
  systemBlocks = null,
825
823
  messages = [],
826
824
  tools = [],
825
+ maxOutputTokens = null,
827
826
  onTextDelta = null,
828
827
  onThinkingDelta = null,
829
828
  onPhase = null,
@@ -832,14 +831,28 @@ async function runAnthropicTurn({
832
831
  } = {}) {
833
832
  const payload = {
834
833
  model,
835
- max_tokens: resolveMaxTokens(DEFAULT_ANTHROPIC_MAX_TOKENS),
834
+ max_tokens: maxOutputTokens || resolveMaxTokens(DEFAULT_ANTHROPIC_MAX_TOKENS),
836
835
  messages: withAnthropicCacheBreakpoint(messages),
837
836
  tools: tools.map((spec) => ({ name: spec.function.name, description: spec.function.description, input_schema: spec.function.parameters })),
838
837
  stream: true,
839
838
  };
840
- const thinkingBudget = Math.min(resolveThinkingBudgetTokens(), payload.max_tokens - 1);
841
- if (thinkingBudget >= 1024) {
842
- payload.thinking = { type: "enabled", budget_tokens: thinkingBudget };
839
+ const isOpus55 = /^(?:claude-)?opus-5[.-]5(?:$|-)/i.test(model);
840
+ const supportsAdaptiveThinking = /^(?:claude-)?(?:(?:opus|sonnet)-(?:4[.-][678]|5(?:[.-]5)?)|haiku-5[.-]5)(?:$|-)/i.test(model);
841
+ const reasoningEffort = thinkingLevel === "off" ? "" : resolveReasoningEffort(thinkingOptions(thinkingLevel));
842
+ if (isOpus55) {
843
+ // Opus 5.5 always uses adaptive thinking and rejects manual budgets.
844
+ // Summaries keep its progress visible in the shared agent transcript.
845
+ payload.thinking = { type: "adaptive", display: "summarized" };
846
+ payload.output_config = {
847
+ // This model cannot disable thinking; low is the smallest supported effort.
848
+ effort: thinkingLevel === "off" ? "low" : (reasoningEffort || "medium"),
849
+ };
850
+ } else if (supportsAdaptiveThinking && reasoningEffort) {
851
+ payload.thinking = { type: "adaptive" };
852
+ payload.output_config = {
853
+ // The 4.6 models predate xhigh effort.
854
+ effort: /-4[.-]6(?:$|-)/i.test(model) && reasoningEffort === "xhigh" ? "high" : reasoningEffort,
855
+ };
843
856
  }
844
857
  if (Array.isArray(systemBlocks) && systemBlocks.length > 0) {
845
858
  payload.system = systemBlocksToAnthropicPayload(systemBlocks);
@@ -869,6 +882,7 @@ async function runAnthropicTurn({
869
882
  let responseText = "";
870
883
  let nextSyntheticBlockIndex = 0;
871
884
  let lastBlockIndex = -1;
885
+ let usageObserved = false;
872
886
  const turnUsage = {
873
887
  input: 0,
874
888
  output: 0,
@@ -893,12 +907,14 @@ async function runAnthropicTurn({
893
907
  if (text && typeof onTextDelta === "function") {
894
908
  onTextDelta(text);
895
909
  }
896
- addUsageTotals(turnUsage, readAnthropicUsage(data && data.usage, { includeOutput: true }));
910
+ const usage = readAnthropicUsage(data && data.usage, { includeOutput: true });
911
+ usageObserved = Boolean(usage);
912
+ addUsageTotals(turnUsage, usage);
897
913
  return {
898
914
  text,
899
915
  assistantContent: content,
900
916
  toolCalls: extractAnthropicToolCalls(content),
901
- usage: turnUsage,
917
+ usage: usageObserved ? turnUsage : null,
902
918
  };
903
919
  },
904
920
  onEvent: ({ event, data }) => {
@@ -919,6 +935,7 @@ async function runAnthropicTurn({
919
935
  : null
920
936
  );
921
937
  if (messageUsage) {
938
+ usageObserved = true;
922
939
  turnUsage.input = messageUsage.input;
923
940
  turnUsage.cacheRead = messageUsage.cacheRead;
924
941
  turnUsage.cacheCreation = messageUsage.cacheCreation;
@@ -930,6 +947,7 @@ async function runAnthropicTurn({
930
947
  const deltaUsage = payloadChunk.usage && typeof payloadChunk.usage === "object"
931
948
  ? payloadChunk.usage
932
949
  : {};
950
+ if (deltaUsage.output_tokens != null && Number.isFinite(Number(deltaUsage.output_tokens))) usageObserved = true;
933
951
  turnUsage.output += toUsageInt(deltaUsage.output_tokens);
934
952
  return;
935
953
  }
@@ -1090,7 +1108,7 @@ async function runAnthropicTurn({
1090
1108
  text: responseText,
1091
1109
  assistantContent,
1092
1110
  toolCalls: extractAnthropicToolCalls(assistantContent),
1093
- usage: turnUsage,
1111
+ usage: usageObserved ? turnUsage : null,
1094
1112
  };
1095
1113
  },
1096
1114
  });
@@ -1130,6 +1148,6 @@ const TRANSPORTS = {
1130
1148
 
1131
1149
  module.exports = {
1132
1150
  getNativeTransport: (name) => TRANSPORTS[name] || TRANSPORTS["openai-chat"],
1133
- createNativeSseDispatcher, resolveThinkingBudgetTokens, resolveReasoningEffort,
1151
+ createNativeSseDispatcher, resolveReasoningEffort,
1134
1152
  normalizeTimeoutMs, createUsageTotals, cloneMessageList,
1135
1153
  };
@@ -15,6 +15,7 @@ const DEFAULT_KIMI_MODEL = "k3";
15
15
  function normalizeProvider(value = "") {
16
16
  const text = String(value || "").trim().toLowerCase();
17
17
  if (!text) return "";
18
+ if (text === "custom") return "openai";
18
19
  if (text === "codex" || text === "codex-cli" || text === "codex-code") return "codex";
19
20
  if (text === "claude" || text === "claude-cli" || text === "claude-code") return "anthropic";
20
21
  if (text === "kimi" || text === "kimi-code" || text === "moonshot") return "kimi";
@@ -51,10 +52,6 @@ function resolveTransport({ provider = "", baseUrl = "" } = {}) {
51
52
  if (normalizedProvider === "anthropic") return "anthropic-messages";
52
53
  if (normalizedProvider === "kimi") return "openai-chat";
53
54
  if (/\/responses(?:$|[/?#])/.test(url)) return "openai-responses";
54
- if (url.includes("anthropic.com")) return "anthropic-messages";
55
- if (/\/messages(?:$|[/?#])/.test(url) && !/\/chat\/completions(?:$|[/?#])/.test(url)) {
56
- return "anthropic-messages";
57
- }
58
55
 
59
56
  return "openai-chat";
60
57
  }
@@ -68,6 +65,8 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
68
65
  || configuredProvider
69
66
  || "openai"
70
67
  ) || "openai";
68
+ const custom = selectedProvider === "openai" && config.agentProvider === "custom"
69
+ && (!useCodingConfig || !(config.ucodeProvider || process.env.UFOO_UCODE_PROVIDER));
71
70
  const configuredModel = sameModelProvider((useCodingConfig ? config.ucodeProvider : "") || config.agentProvider, selectedProvider)
72
71
  ? ((useCodingConfig ? config.ucodeModel : "") || config.agentModel)
73
72
  : "";
@@ -78,7 +77,7 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
78
77
  || configuredModel
79
78
  || (selectedProvider === "kimi"
80
79
  ? DEFAULT_KIMI_MODEL
81
- : (selectedProvider === "grok-build" ? DEFAULT_GROK_BUILD_MODEL : defaultAgentModelForProvider(selectedProvider)))
80
+ : (selectedProvider === "grok-build" ? DEFAULT_GROK_BUILD_MODEL : custom ? "" : defaultAgentModelForProvider(selectedProvider)))
82
81
  ).trim();
83
82
 
84
83
  const defaultBaseUrl = selectedProvider === "anthropic"
@@ -98,12 +97,14 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
98
97
  : String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL);
99
98
 
100
99
  let baseUrl = String(
101
- (useCodingConfig ? process.env.UFOO_UCODE_BASE_URL : "")
100
+ (custom ? process.env.UFOO_AGENT_BASE_URL || config.agentBaseUrl : "")
101
+ || (useCodingConfig ? process.env.UFOO_UCODE_BASE_URL : "")
102
102
  || (useCodingConfig ? config.ucodeBaseUrl : "")
103
103
  || defaultBaseUrl
104
104
  ).trim();
105
+ if (custom) baseUrl = String(process.env.UFOO_AGENT_BASE_URL || config.agentBaseUrl || "").trim();
105
106
 
106
- const explicitApiKey = String(
107
+ const explicitApiKey = String(custom ? process.env.UFOO_AGENT_API_KEY || config.agentApiKey || "" :
107
108
  (useCodingConfig ? process.env.UFOO_UCODE_API_KEY : "")
108
109
  || (useCodingConfig ? config.ucodeApiKey : "")
109
110
  || ""
@@ -119,7 +120,7 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
119
120
  kimiCredentialState = String(credential.state || "");
120
121
  }
121
122
  }
122
- if (!apiKey) {
123
+ if (!apiKey && !custom) {
123
124
  apiKey = String(
124
125
  (selectedProvider === "openai" ? process.env.OPENAI_API_KEY : "")
125
126
  || (selectedProvider === "anthropic" ? process.env.ANTHROPIC_API_KEY : "")
@@ -151,6 +152,7 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
151
152
  apiKeySource,
152
153
  kimiCredentialState,
153
154
  transport: resolveTransport({ provider: selectedProvider, baseUrl }),
155
+ allowUnlistedModels: custom,
154
156
  };
155
157
  }
156
158
 
@@ -4,40 +4,40 @@
4
4
  * Ucode thinking-intensity levels.
5
5
  *
6
6
  * Used as the secondary `/model <id> <level>` menu after picking a model.
7
- * Maps to Anthropic extended-thinking budget_tokens and OpenAI-compatible
8
- * reasoning_effort where the transport supports it.
7
+ * Maps to Anthropic effort and OpenAI-compatible reasoning_effort where
8
+ * the transport supports it.
9
9
  */
10
10
 
11
11
  const THINKING_LEVELS = Object.freeze([
12
12
  {
13
13
  id: "off",
14
14
  desc: "disable extended thinking",
15
- budgetTokens: 0,
16
15
  reasoningEffort: "",
17
16
  },
18
17
  {
19
18
  id: "low",
20
19
  desc: "light thinking",
21
- budgetTokens: 2048,
22
20
  reasoningEffort: "low",
23
21
  },
24
22
  {
25
23
  id: "medium",
26
24
  desc: "default thinking",
27
- budgetTokens: 10000,
28
25
  reasoningEffort: "medium",
29
26
  },
30
27
  {
31
28
  id: "high",
32
29
  desc: "deeper thinking",
33
- budgetTokens: 32000,
34
30
  reasoningEffort: "high",
35
31
  },
32
+ {
33
+ id: "xhigh",
34
+ desc: "extra high thinking",
35
+ reasoningEffort: "xhigh",
36
+ },
36
37
  {
37
38
  id: "max",
38
- desc: "maximum thinking budget",
39
- budgetTokens: 48000,
40
- reasoningEffort: "high",
39
+ desc: "maximum thinking",
40
+ reasoningEffort: "max",
41
41
  },
42
42
  ]);
43
43
 
@@ -49,7 +49,7 @@ function normalizeThinkingLevel(value = "") {
49
49
  if (!raw) return "";
50
50
  if (raw === "none" || raw === "disable" || raw === "disabled" || raw === "0") return "off";
51
51
  if (raw === "med" || raw === "default") return "medium";
52
- if (raw === "maximum" || raw === "xhigh" || raw === "ultra") return "max";
52
+ if (raw === "maximum" || raw === "ultra") return "max";
53
53
  if (THINKING_LEVEL_IDS.has(raw)) return raw;
54
54
  return "";
55
55
  }
@@ -71,33 +71,12 @@ function resolveThinkingFromEnvAndConfig({
71
71
  env = process.env,
72
72
  configLevel = "",
73
73
  } = {}) {
74
- // Explicit numeric budget still wins (advanced override).
75
- const rawBudget = env && env.UFOO_UCODE_THINKING_BUDGET_TOKENS;
76
- if (rawBudget !== undefined && rawBudget !== null && String(rawBudget).trim() !== "") {
77
- const parsed = Number.parseInt(String(rawBudget), 10);
78
- if (!Number.isFinite(parsed) || parsed <= 0) {
79
- return {
80
- level: "off",
81
- budgetTokens: 0,
82
- reasoningEffort: "",
83
- source: "env-budget",
84
- };
85
- }
86
- return {
87
- level: "",
88
- budgetTokens: Math.floor(parsed),
89
- reasoningEffort: "",
90
- source: "env-budget",
91
- };
92
- }
93
-
94
74
  const fromEnv = normalizeThinkingLevel(env && env.UFOO_UCODE_THINKING);
95
75
  const fromConfig = normalizeThinkingLevel(configLevel);
96
76
  const level = fromEnv || fromConfig || DEFAULT_THINKING_LEVEL;
97
77
  const spec = getThinkingLevel(level);
98
78
  return {
99
79
  level: spec.id,
100
- budgetTokens: spec.budgetTokens,
101
80
  reasoningEffort: spec.reasoningEffort,
102
81
  source: fromEnv ? "env" : (fromConfig ? "config" : "default"),
103
82
  };
@@ -109,11 +88,6 @@ function applyThinkingLevelToEnv(level = "", env = process.env) {
109
88
  const spec = getThinkingLevel(normalized);
110
89
  try {
111
90
  env.UFOO_UCODE_THINKING = spec.id;
112
- if (spec.budgetTokens > 0) {
113
- env.UFOO_UCODE_THINKING_BUDGET_TOKENS = String(spec.budgetTokens);
114
- } else {
115
- env.UFOO_UCODE_THINKING_BUDGET_TOKENS = "0";
116
- }
117
91
  } catch {
118
92
  // ignore env write failures
119
93
  }
@@ -198,6 +198,9 @@ function toolsToResponsesTools(tools = []) {
198
198
  result.push({
199
199
  type: "function",
200
200
  name,
201
+ // Responses otherwise normalizes compatible schemas to strict mode,
202
+ // making optional fields required. AJV remains the local authority.
203
+ strict: typeof fn.strict === "boolean" ? fn.strict : false,
201
204
  description: String(fn.description || ""),
202
205
  parameters: fn.parameters && typeof fn.parameters === "object"
203
206
  ? fn.parameters
@@ -298,16 +301,18 @@ function responseUsage(response = null) {
298
301
  ? response.usage
299
302
  : null;
300
303
  if (!usage) return null;
301
- const inputDetails = usage.input_token_details && typeof usage.input_token_details === "object"
302
- ? usage.input_token_details
304
+ const details = usage.input_tokens_details ?? usage.input_token_details;
305
+ const inputDetails = details && typeof details === "object"
306
+ ? details
303
307
  : {};
308
+ const cached = inputDetails.cached_tokens ?? usage.cached_input_tokens ?? usage.cache_read_input_tokens;
309
+ if (![usage.input_tokens, usage.prompt_tokens, usage.output_tokens, usage.completion_tokens, cached]
310
+ .some(value => value != null && Number.isFinite(Number(value)))) return null;
304
311
  return {
305
312
  input: Number(usage.input_tokens || usage.prompt_tokens || 0) || 0,
306
313
  output: Number(usage.output_tokens || usage.completion_tokens || 0) || 0,
307
- cacheRead: Number(
308
- inputDetails.cached_tokens || usage.cached_input_tokens || usage.cache_read_input_tokens || 0,
309
- ) || 0,
310
- cacheCreation: Number(usage.cache_creation_input_tokens || usage.cache_creation_tokens || 0) || 0,
314
+ cacheRead: cached != null && Number.isFinite(Number(cached)) ? Number(cached) : null,
315
+ cacheCreation: Number(inputDetails.cache_write_tokens ?? usage.cache_creation_input_tokens ?? usage.cache_creation_tokens ?? 0) || 0,
311
316
  inputIncludesCache: true,
312
317
  };
313
318
  }
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+
3
+ const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../../config");
4
+ const { resolveRuntimeConfig } = require("./runtimeConfig");
5
+ const { resolveClaudeUpstreamCredentials } = require("./credentials/claude");
6
+ const { resolveCodexUpstreamCredentials } = require("./credentials/codex");
7
+ const { resolveKimiUpstreamCredentials } = require("./credentials/kimi");
8
+ const { buildUpstreamAuthFromCredential } = require("./credentials");
9
+
10
+ const CODEX_DEFAULT_BASE_URL = "https://chatgpt.com/backend-api/codex";
11
+
12
+ function normalizeProvider(value = "") {
13
+ const text = String(value || "").trim().toLowerCase();
14
+ if (!text) return "ucode";
15
+ if (text === "codex-cli" || text === "codex-code" || text === "codex" || text === "openai") return "codex";
16
+ if (text === "claude-cli" || text === "claude-code" || text === "claude" || text === "anthropic") return "claude";
17
+ if (text === "grok" || text === "grok-cli" || text === "grok-build" || text === "grok-shell" || text === "grok-api" || text === "xai") return "grok";
18
+ if (text === "ucode") return "ucode";
19
+ if (text === "kimi-cli" || text === "kimi-code" || text === "moonshot") return "kimi";
20
+ return text;
21
+ }
22
+
23
+ function resolveConfiguredModelForProvider(config = {}, provider = "") {
24
+ if (config.agentProvider && sameModelProvider(config.agentProvider, provider)) {
25
+ return config.agentModel;
26
+ }
27
+ return "";
28
+ }
29
+
30
+ async function resolveUpstreamRuntime({
31
+ projectRoot,
32
+ provider = "",
33
+ model = "",
34
+ env = process.env,
35
+ fetchImpl = global.fetch,
36
+ loadConfigImpl = loadConfig,
37
+ } = {}) {
38
+ const normalizedProvider = normalizeProvider(provider);
39
+ const config = loadConfigImpl(projectRoot);
40
+
41
+ if (normalizedProvider === "codex") {
42
+ const credential = await resolveCodexUpstreamCredentials({
43
+ authPath: config.codexAuthPath,
44
+ refreshWindowMs: Number(config.codexOauthRefreshWindowSec || 300) * 1000,
45
+ fetchImpl,
46
+ env,
47
+ });
48
+ const useCodexOAuth = credential.credentialKind === "oauth" && Boolean(credential.accessToken);
49
+ const baseUrl = useCodexOAuth
50
+ ? String(env.UFOO_CODEX_BASE_URL || "").trim() || CODEX_DEFAULT_BASE_URL
51
+ : String(env.OPENAI_BASE_URL || "").trim() || "https://api.openai.com/v1";
52
+ const resolvedModel = String(
53
+ model
54
+ || resolveConfiguredModelForProvider(config, "codex")
55
+ || defaultAgentModelForProvider("codex")
56
+ ).trim();
57
+ return {
58
+ provider: "codex",
59
+ transport: "codex-responses",
60
+ requestProfile: useCodexOAuth ? "codex-subscription" : "openai-responses",
61
+ model: resolvedModel,
62
+ baseUrl,
63
+ credential,
64
+ auth: buildUpstreamAuthFromCredential(credential),
65
+ credentialSource: String(credential.source || ""),
66
+ };
67
+ }
68
+
69
+ if (normalizedProvider === "claude") {
70
+ const credential = await resolveClaudeUpstreamCredentials({
71
+ profile: config.claudeOauthProfile,
72
+ tokenPath: config.claudeOauthTokenPath,
73
+ refreshWindowMs: Number(config.claudeOauthRefreshWindowSec || 300) * 1000,
74
+ env,
75
+ });
76
+ const baseUrl = String(env.ANTHROPIC_BASE_URL || credential.metadata?.baseUrl || "").trim() || "https://api.anthropic.com/v1";
77
+ const resolvedModel = String(
78
+ model
79
+ || resolveConfiguredModelForProvider(config, "claude")
80
+ || defaultAgentModelForProvider("claude")
81
+ ).trim();
82
+ return {
83
+ provider: "claude",
84
+ transport: "anthropic-messages",
85
+ model: resolvedModel,
86
+ baseUrl,
87
+ credential,
88
+ auth: buildUpstreamAuthFromCredential(credential),
89
+ credentialSource: String(credential.source || ""),
90
+ };
91
+ }
92
+
93
+ if (normalizedProvider === "grok") {
94
+ const runtime = resolveRuntimeConfig({
95
+ workspaceRoot: projectRoot,
96
+ provider: "grok-build",
97
+ model: model || resolveConfiguredModelForProvider(config, "grok-build") || defaultAgentModelForProvider("grok-build"),
98
+ useCodingConfig: false,
99
+ });
100
+ const auth = runtime.apiKey ? { apiKey: String(runtime.apiKey).trim() } : { headers: {} };
101
+ return {
102
+ provider: "grok-build",
103
+ transport: "openai-responses",
104
+ model: String(runtime.model || model || "").trim(),
105
+ baseUrl: String(runtime.baseUrl || "").trim(),
106
+ credential: null,
107
+ auth,
108
+ credentialSource: runtime.apiKey ? "runtime-api-key" : "",
109
+ };
110
+ }
111
+
112
+ const runtime = resolveRuntimeConfig({
113
+ workspaceRoot: projectRoot,
114
+ provider: normalizedProvider === "ucode" ? "" : normalizedProvider,
115
+ model: model || resolveConfiguredModelForProvider(config, normalizedProvider) || defaultAgentModelForProvider(config.agentProvider),
116
+ useCodingConfig: normalizedProvider === "ucode",
117
+ });
118
+ let credential = null;
119
+ if (runtime.provider === "kimi" && runtime.apiKeySource === "kimi-credential") {
120
+ credential = await resolveKimiUpstreamCredentials({ env, fetchImpl });
121
+ runtime.apiKey = credential.accessToken;
122
+ }
123
+ const auth = runtime.apiKey ? { apiKey: String(runtime.apiKey || "").trim() } : { headers: {} };
124
+ return {
125
+ provider: String(runtime.provider || normalizedProvider || "ucode"),
126
+ transport: String(runtime.transport || "openai-chat"),
127
+ model: String(runtime.model || "").trim(),
128
+ baseUrl: String(runtime.baseUrl || "").trim(),
129
+ credential,
130
+ auth,
131
+ credentialSource: runtime.apiKey ? "runtime-api-key" : "",
132
+ };
133
+ }
134
+
135
+ module.exports = { normalizeProvider, resolveUpstreamRuntime };
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { withFileLock } = require("./fileLock");
6
+
7
+ /** Append-only checkpoints also preserve source batches from in-flight turns. */
8
+ function createCheckpointStore({ workspaceRoot, namespace = "ucode", sessionId, redact = value => value } = {}) {
9
+ if (![namespace, sessionId].every(value => /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(value || ""))) throw new Error("invalid checkpoint identity");
10
+ const file = path.join(path.resolve(workspaceRoot), ".ufoo", "agent", namespace, "context", `${sessionId}.jsonl`);
11
+ const records = () => {
12
+ if (!fs.existsSync(file)) return [];
13
+ const lines = fs.readFileSync(file, "utf8").split("\n");
14
+ lines.pop(); // An interrupted final append has never been committed.
15
+ return lines.filter(Boolean).map(line => JSON.parse(line));
16
+ };
17
+ return {
18
+ file,
19
+ load: () => records().at(-1)?.checkpoint || null,
20
+ archive: () => records().flatMap(record => record.sourceBatch || []),
21
+ commit(checkpoint, sourceBatch, expectedVersion) {
22
+ return withFileLock(file, () => {
23
+ if ((records().at(-1)?.checkpoint.version || 0) !== expectedVersion) return false;
24
+ const fd = fs.openSync(file, "a+", 0o600);
25
+ try {
26
+ const bytes = fs.readFileSync(file);
27
+ if (bytes.length && bytes[bytes.length - 1] !== 10) fs.ftruncateSync(fd, bytes.lastIndexOf(10) + 1);
28
+ fs.writeSync(fd, JSON.stringify(redact({ checkpoint, sourceBatch })) + "\n");
29
+ fs.fsyncSync(fd);
30
+ } finally { fs.closeSync(fd); }
31
+ return true;
32
+ });
33
+ },
34
+ remove() { if (fs.existsSync(file)) fs.unlinkSync(file); },
35
+ };
36
+ }
37
+
38
+ module.exports = { createCheckpointStore };