u-foo 4.0.0 → 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 (154) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +88 -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/ufoo.js +3 -3
  7. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  8. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  9. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  10. package/dist/tui/linux-x64/ufoo-tui +0 -0
  11. package/package.json +6 -6
  12. package/src/agents/activity/activityDetector.js +1 -1
  13. package/src/agents/capabilities/agentManagement/service.js +40 -13
  14. package/src/agents/capabilities/coordination/index.js +1 -1
  15. package/src/agents/capabilities/taskReports/index.js +1 -1
  16. package/src/agents/controller/controllerToolExecutor.js +36 -20
  17. package/src/agents/controller/index.js +1 -6
  18. package/src/agents/internal/internalRunner.js +90 -56
  19. package/src/agents/launch/index.js +0 -1
  20. package/src/agents/launch/launcher.js +8 -8
  21. package/src/agents/launch/notifier.js +2 -2
  22. package/src/agents/launch/readyDetector.js +2 -2
  23. package/src/agents/profiles/main.js +1 -1
  24. package/src/agents/prompts/cooperation.js +14 -0
  25. package/src/agents/prompts/defaultBootstrap.js +1 -1
  26. package/src/agents/prompts/groupBootstrap.js +23 -7
  27. package/src/agents/prompts/mainAgent.js +11 -2
  28. package/src/agents/prompts/native/system.js +4 -1
  29. package/src/agents/prompts/native/ufoo.js +11 -3
  30. package/src/agents/prompts/promptProfiles.js +2 -0
  31. package/src/agents/prompts/reporting.js +16 -0
  32. package/src/agents/providers/claudeEventTranslator.js +3 -0
  33. package/src/agents/providers/claudeThreadProvider.js +3 -2
  34. package/src/agents/providers/clientIdentity.js +75 -0
  35. package/src/agents/providers/codexEventTranslator.js +23 -2
  36. package/src/agents/providers/codexThreadProvider.js +15 -6
  37. package/src/agents/providers/credentials/index.js +2 -0
  38. package/src/agents/providers/directAuthStatus.js +1 -1
  39. package/src/agents/providers/index.js +1 -1
  40. package/src/agents/providers/modelSettings.js +34 -0
  41. package/src/agents/providers/modelsCatalog.js +379 -0
  42. package/src/agents/providers/nativeTransport.js +50 -39
  43. package/src/agents/providers/runtimeConfig.js +10 -8
  44. package/src/agents/providers/thinkingLevels.js +10 -36
  45. package/src/agents/providers/transports/responsesProtocol.js +11 -6
  46. package/src/agents/providers/upstreamRuntime.js +135 -0
  47. package/src/agents/runtime/context/checkpointStore.js +38 -0
  48. package/src/agents/runtime/context/compaction.js +151 -0
  49. package/src/agents/runtime/context/contextBudget.js +93 -0
  50. package/src/agents/runtime/context/replayHistory.js +28 -0
  51. package/src/agents/runtime/context/runtimeStore.js +2 -1
  52. package/src/agents/runtime/core/agentLoop.js +99 -18
  53. package/src/agents/runtime/core/executionBudget.js +36 -0
  54. package/src/agents/runtime/createAgentRuntime.js +16 -4
  55. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  56. package/src/agents/runtime/protocol/runObservation.js +24 -0
  57. package/src/agents/runtime/protocol/traceContext.js +9 -0
  58. package/src/app/chat/ChatController.js +26 -53
  59. package/src/app/chat/agentDirectory.js +1 -16
  60. package/src/app/chat/bootstrap.js +1 -2
  61. package/src/app/chat/commandExecutor.js +93 -285
  62. package/src/app/chat/commands.js +32 -45
  63. package/src/app/chat/daemonMessageRouter.js +0 -45
  64. package/src/app/chat/historyStore.js +12 -48
  65. package/src/app/chat/inputSubmitHandler.js +7 -33
  66. package/src/app/chat/internalAgentLogHistory.js +19 -60
  67. package/src/app/chat/multiWindow/paneManager.js +10 -3
  68. package/src/app/chat/streamState.js +0 -4
  69. package/src/app/cli/features/init.js +5 -5
  70. package/src/app/cli/metricsCommands.js +68 -0
  71. package/src/app/cli/run.js +42 -3
  72. package/src/app/cli/traceCommands.js +36 -0
  73. package/src/code/agent.js +18 -13
  74. package/src/code/busConsumer.js +1 -3
  75. package/src/code/commands.js +1 -1
  76. package/src/code/context/assembler.js +7 -8
  77. package/src/code/context/stateCommit.js +2 -1
  78. package/src/code/internalThread.js +10 -3
  79. package/src/code/launcher/ucode.js +1 -1
  80. package/src/code/launcher/ucodeBootstrap.js +1 -1
  81. package/src/code/modelCommand.js +11 -35
  82. package/src/code/nativeRunner.js +55 -17
  83. package/src/code/providers/modelsCatalog.js +1 -317
  84. package/src/code/repl.js +2 -11
  85. package/src/code/sessionStore.js +3 -3
  86. package/src/code/taskDecomposer.js +18 -0
  87. package/src/code/toolBudget.js +1 -17
  88. package/src/config.js +22 -72
  89. package/src/coordination/bus/index.js +12 -3
  90. package/src/coordination/bus/inject.js +2 -2
  91. package/src/coordination/bus/message.js +15 -1
  92. package/src/coordination/bus/nickname.js +1 -1
  93. package/src/coordination/bus/subscriber.js +3 -2
  94. package/src/coordination/bus/utils.js +1 -1
  95. package/src/coordination/history/agentPerformance.js +279 -0
  96. package/src/coordination/history/agentTrace.js +249 -0
  97. package/src/coordination/state/workspaceAccess.js +1 -1
  98. package/src/orchestration/controller/index.js +1 -8
  99. package/src/orchestration/controller/launchRouting.js +1 -1
  100. package/src/orchestration/solo/commands.js +3 -1
  101. package/src/runtime/contracts/agentMode.js +11 -2
  102. package/src/runtime/contracts/uiProtocol.js +18 -19
  103. package/src/runtime/daemon/agentHost.js +57 -25
  104. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  105. package/src/runtime/daemon/busBridge.js +1 -1
  106. package/src/runtime/daemon/controlPlaneService.js +1 -1
  107. package/src/runtime/daemon/groupOrchestrator.js +20 -5
  108. package/src/runtime/daemon/groupStatus.js +20 -0
  109. package/src/runtime/daemon/index.js +19 -44
  110. package/src/runtime/daemon/mcpServer.js +1 -1
  111. package/src/runtime/daemon/nicknameScope.js +1 -1
  112. package/src/runtime/daemon/ops.js +46 -23
  113. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  114. package/src/runtime/daemon/promptRequest.js +92 -589
  115. package/src/runtime/daemon/status.js +5 -6
  116. package/src/tools/controllerSchemas.js +6 -2
  117. package/src/tools/handlers/tier2.js +4 -2
  118. package/src/tools/registry.js +4 -0
  119. package/src/tools/schemaFixtures.js +26 -2
  120. package/src/tools/tier0/readAgentMetrics.js +14 -0
  121. package/src/tools/tier0/readAgentTrace.js +12 -0
  122. package/src/ui/agentSettingsController.js +107 -0
  123. package/src/ui/agentSurface.js +1 -1
  124. package/src/ui/dashboardBridge.js +1 -1
  125. package/src/ui/format/banner.js +1 -4
  126. package/src/ui/format/index.js +14 -10
  127. package/src/ui/format/loopSummary.js +50 -0
  128. package/src/ui/format/markdownRenderer.js +3 -4
  129. package/src/ui/rustChatHost.js +191 -206
  130. package/src/ui/rustMultiSession.js +77 -36
  131. package/src/ui/rustUcodeHost.js +1 -1
  132. package/src/ui/settingsBridge.js +33 -16
  133. package/src/ui/toolMergeBridge.js +0 -4
  134. package/src/ui/uiHostServer.js +5 -8
  135. package/src/agents/controller/loopObservability.js +0 -200
  136. package/src/agents/controller/loopRuntime.js +0 -336
  137. package/src/agents/controller/ufooAgent.js +0 -830
  138. package/src/agents/launch/ptyRunner.js +0 -1135
  139. package/src/agents/providers/controllerJsonTransport.js +0 -28
  140. package/src/agents/providers/upstreamTransport.js +0 -698
  141. package/src/app/chat/agentBar.js +0 -135
  142. package/src/app/chat/agentSockets.js +0 -225
  143. package/src/app/chat/dashboardView.js +0 -405
  144. package/src/app/chat/rawKeyMap.js +0 -42
  145. package/src/app/chat/settingsController.js +0 -111
  146. package/src/coordination/history/controllerSummary.js +0 -23
  147. package/src/orchestration/controller/flags.js +0 -167
  148. package/src/orchestration/controller/gateRouter.js +0 -211
  149. package/src/orchestration/controller/routerFastPath.js +0 -22
  150. package/src/orchestration/controller/routerFinalize.js +0 -222
  151. package/src/orchestration/controller/shadowGuard.js +0 -280
  152. package/src/runtime/daemon/executionPaths.js +0 -30
  153. package/src/runtime/daemon/promptLoop.js +0 -136
  154. package/src/runtime/privacy/shadowDiff.js +0 -174
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ const { loadConfig } = require("../../config");
4
+ const { resolveUpstreamRuntime } = require("./upstreamRuntime");
5
+ const { listProviderModels, confirmModelSupported, usesCustomModelEndpoint } = require("./modelsCatalog");
6
+
7
+ async function resolveAgentModelCatalog(projectRoot, options = {}) {
8
+ const config = options.config || loadConfig(projectRoot);
9
+ if (config.agentProvider === "custom") {
10
+ const { resolveTransport } = require("./runtimeConfig");
11
+ return { provider: "openai", transport: resolveTransport({ provider: "openai", baseUrl: config.agentBaseUrl }),
12
+ baseUrl: config.agentBaseUrl, apiKey: config.agentApiKey || "", allowUnlistedModels: true, fetchImpl: options.fetchImpl,
13
+ timeoutMs: options.timeoutMs, skipCache: options.skipCache };
14
+ }
15
+ const runtime = await (options.resolveRuntime || resolveUpstreamRuntime)({
16
+ projectRoot, provider: config.agentProvider, model: config.agentModel,
17
+ loadConfigImpl: () => config,
18
+ });
19
+ return { provider: runtime.provider, transport: runtime.transport, baseUrl: runtime.baseUrl,
20
+ apiKey: runtime.auth?.apiKey || "", requestHeaders: { ...runtime.auth?.headers,
21
+ ...(runtime.provider === "codex" && runtime.credential?.accountId ? { "chatgpt-account-id": runtime.credential.accountId } : {}) },
22
+ fetchImpl: options.fetchImpl, timeoutMs: options.timeoutMs, skipCache: options.skipCache };
23
+ }
24
+
25
+ async function listAgentModels(projectRoot, options = {}) {
26
+ const runtime = await resolveAgentModelCatalog(projectRoot, options);
27
+ return { ...await listProviderModels(runtime), allowUnlistedModels: usesCustomModelEndpoint(runtime) };
28
+ }
29
+
30
+ async function confirmAgentModel(projectRoot, model, options = {}) {
31
+ return confirmModelSupported({ ...await resolveAgentModelCatalog(projectRoot, options), model });
32
+ }
33
+
34
+ module.exports = { listAgentModels, confirmAgentModel, resolveAgentModelCatalog };
@@ -0,0 +1,379 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Live provider model catalog via the OpenAI-compatible / Anthropic models route.
5
+ *
6
+ * Shared by ucode /model and dashboard settings so model choices follow the
7
+ * configured provider's catalog.
8
+ */
9
+
10
+ const DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1";
11
+ const DEFAULT_TIMEOUT_MS = 8000;
12
+ const CACHE_TTL_MS = 60_000;
13
+ const { createHash } = require("crypto");
14
+ const { resolveCodexClientVersion, resolveCodexUserAgent, resolveGrokClientVersion } = require("./clientIdentity");
15
+ const { normalizeProvider } = require("./runtimeConfig");
16
+
17
+ const OFFICIAL_MODEL_ORIGINS = Object.freeze({
18
+ openai: ["https://api.openai.com"],
19
+ codex: ["https://chatgpt.com", "https://api.openai.com"],
20
+ anthropic: ["https://api.anthropic.com"],
21
+ kimi: ["https://api.kimi.com"],
22
+ "grok-build": ["https://api.x.ai"],
23
+ xai: ["https://api.x.ai"],
24
+ });
25
+
26
+ function usesCustomModelEndpoint({ provider = "", transport = "", baseUrl = "", allowUnlistedModels = false } = {}) {
27
+ if (allowUnlistedModels || provider === "custom") return true;
28
+ if (!String(baseUrl || "").trim()) return false;
29
+ const normalizedProvider = normalizeProvider(provider)
30
+ || (transport === "anthropic-messages" ? "anthropic" : "openai");
31
+ try {
32
+ const origin = new URL(baseUrl).origin;
33
+ return !(OFFICIAL_MODEL_ORIGINS[normalizedProvider] || []).includes(origin);
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ /** @type {Map<string, { at: number, result: object }>} */
40
+ const modelsCache = new Map();
41
+
42
+ function clipText(value = "", maxChars = 400) {
43
+ const text = String(value || "");
44
+ if (text.length <= maxChars) return text;
45
+ return `${text.slice(0, maxChars)}…`;
46
+ }
47
+
48
+ function resolveOpenAiModelsUrl(baseUrl = "") {
49
+ const raw = String(baseUrl || "").trim();
50
+ if (!raw) return "";
51
+ const normalized = raw.replace(/\/+$/, "");
52
+ if (/\/models$/i.test(normalized)) return normalized;
53
+ if (/\/chat\/completions$/i.test(normalized)) {
54
+ return normalized.replace(/\/chat\/completions$/i, "/models");
55
+ }
56
+ if (/\/responses$/i.test(normalized)) return normalized.replace(/\/responses$/i, "/models");
57
+ if (/\/v1$/i.test(normalized)) return `${normalized}/models`;
58
+ if (/\/api$/i.test(normalized)) return `${normalized}/v1/models`;
59
+ return `${normalized}/models`;
60
+ }
61
+
62
+ function resolveAnthropicModelsUrl(baseUrl = "") {
63
+ const raw = String(baseUrl || "").trim() || DEFAULT_ANTHROPIC_BASE_URL;
64
+ const normalized = raw.replace(/\/+$/, "");
65
+ if (/\/models$/i.test(normalized)) return normalized;
66
+ if (/\/messages$/i.test(normalized)) {
67
+ return normalized.replace(/\/messages$/i, "/models");
68
+ }
69
+ if (/\/v1$/i.test(normalized)) return `${normalized}/models`;
70
+ if (/\/api$/i.test(normalized)) return `${normalized}/v1/models`;
71
+ return `${normalized}/models`;
72
+ }
73
+
74
+ function resolveModelsUrl({ transport = "", baseUrl = "", provider = "", clientVersion = "", codexHome = "" } = {}) {
75
+ let url;
76
+ if (String(transport || "") === "anthropic-messages") {
77
+ url = resolveAnthropicModelsUrl(baseUrl);
78
+ } else {
79
+ url = resolveOpenAiModelsUrl(baseUrl);
80
+ }
81
+ const normalizedProvider = String(provider || "").trim().toLowerCase();
82
+ if (normalizedProvider === "codex" && /\/codex(?:\/|$)/.test(url)) {
83
+ const version = resolveCodexClientVersion({ codexHome, clientVersion });
84
+ if (!version) return url;
85
+ const separator = url.includes("?") ? "&" : "?";
86
+ return `${url}${separator}client_version=${encodeURIComponent(version)}`;
87
+ }
88
+ if (normalizedProvider === "grok" || normalizedProvider === "grok-build" || normalizedProvider === "grok-shell") {
89
+ const separator = url.includes("?") ? "&" : "?";
90
+ const version = resolveGrokClientVersion();
91
+ return `${url}${separator}client_version=${encodeURIComponent(version)}`;
92
+ }
93
+ return url;
94
+ }
95
+
96
+ function cacheKey({ transport = "", baseUrl = "", url = "", apiKey = "", provider = "", requestHeaders = {} } = {}) {
97
+ const authHash = createHash("sha256").update(JSON.stringify([apiKey, requestHeaders])).digest("hex");
98
+ return `${provider}|${transport}|${url || baseUrl}|${authHash}`;
99
+ }
100
+
101
+ function extractModelIds(payload, { visibleOnly = false } = {}) {
102
+ const ids = [];
103
+ const seen = new Set();
104
+ const push = (value) => {
105
+ const id = String(value || "").trim();
106
+ if (!id || seen.has(id)) return;
107
+ seen.add(id);
108
+ ids.push(id);
109
+ };
110
+
111
+ if (!payload || typeof payload !== "object") return ids;
112
+
113
+ if (Array.isArray(payload.data)) {
114
+ for (const item of payload.data) {
115
+ if (!item) continue;
116
+ if (typeof item === "string") push(item);
117
+ else if (!visibleOnly || !item.visibility || item.visibility === "list") push(item.id || item.slug || item.model || item.name);
118
+ }
119
+ }
120
+
121
+ if (Array.isArray(payload.models)) {
122
+ for (const item of payload.models) {
123
+ if (!item) continue;
124
+ if (typeof item === "string") push(item);
125
+ else if (!visibleOnly || !item.visibility || item.visibility === "list") push(item.id || item.slug || item.model || item.name);
126
+ }
127
+ }
128
+
129
+ return ids;
130
+ }
131
+
132
+ function buildListHeaders({ transport = "", apiKey = "", provider = "", clientVersion = "", codexHome = "" } = {}) {
133
+ const headers = {
134
+ Accept: "application/json",
135
+ };
136
+ const normalizedProvider = String(provider || "").trim().toLowerCase();
137
+ if (normalizedProvider === "grok" || normalizedProvider === "grok-build" || normalizedProvider === "grok-shell") {
138
+ const version = resolveGrokClientVersion();
139
+ headers["User-Agent"] = `grok-shell/${version}`;
140
+ }
141
+ if (normalizedProvider === "codex") {
142
+ headers["User-Agent"] = resolveCodexUserAgent({ clientVersion, codexHome });
143
+ headers.Originator = "codex-tui";
144
+ }
145
+ const key = String(apiKey || "").trim();
146
+
147
+ if (String(transport || "") === "anthropic-messages") {
148
+ if (key) headers["x-api-key"] = key;
149
+ headers["anthropic-version"] = "2023-06-01";
150
+ } else if (key) {
151
+ headers.Authorization = `Bearer ${key}`;
152
+ }
153
+ return headers;
154
+ }
155
+
156
+ /**
157
+ * Fetch the provider's models catalog.
158
+ * @returns {Promise<{
159
+ * ok: boolean,
160
+ * models: string[],
161
+ * url: string,
162
+ * error: string,
163
+ * status: number,
164
+ * cached: boolean,
165
+ * }>}
166
+ */
167
+ async function listProviderModels(options = {}) {
168
+ const transport = String(options.transport || "openai-chat").trim() || "openai-chat";
169
+ const baseUrl = String(options.baseUrl || "").trim();
170
+ const apiKey = String(options.apiKey || "").trim();
171
+ const provider = String(options.provider || "").trim();
172
+ const requestHeaders = options.requestHeaders || {};
173
+ const timeoutMs = Math.max(1000, Number(options.timeoutMs) || DEFAULT_TIMEOUT_MS);
174
+ const fetchImpl = typeof options.fetchImpl === "function" ? options.fetchImpl : fetch;
175
+ const skipCache = options.skipCache === true;
176
+ const url = resolveModelsUrl({ transport, baseUrl, provider, clientVersion: options.clientVersion, codexHome: options.codexHome });
177
+
178
+ if (!url) {
179
+ return {
180
+ ok: false,
181
+ models: [],
182
+ url: "",
183
+ error: "models url unavailable (configure the provider API URL)",
184
+ status: 0,
185
+ cached: false,
186
+ };
187
+ }
188
+
189
+ const key = cacheKey({ transport, baseUrl, url, apiKey, provider, requestHeaders });
190
+ if (!skipCache) {
191
+ const hit = modelsCache.get(key);
192
+ if (hit && (Date.now() - hit.at) < CACHE_TTL_MS) {
193
+ return { ...hit.result, cached: true };
194
+ }
195
+ }
196
+
197
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
198
+ const timer = controller
199
+ ? setTimeout(() => {
200
+ try { controller.abort(); } catch { /* ignore */ }
201
+ }, timeoutMs)
202
+ : null;
203
+ if (timer && typeof timer.unref === "function") timer.unref();
204
+
205
+ try {
206
+ let nextUrl = url;
207
+ const models = [];
208
+ const seenPages = new Set();
209
+ let status = 0;
210
+ do {
211
+ if (seenPages.has(nextUrl)) throw new Error("models route repeated a pagination cursor");
212
+ seenPages.add(nextUrl);
213
+ const response = await fetchImpl(nextUrl, {
214
+ method: "GET",
215
+ headers: { ...buildListHeaders({ transport, apiKey, provider, clientVersion: options.clientVersion, codexHome: options.codexHome }), ...requestHeaders },
216
+ signal: controller ? controller.signal : undefined,
217
+ });
218
+ status = Number(response && response.status) || 0;
219
+ const bodyText = await response.text().catch(() => "");
220
+ let payload = null;
221
+ try {
222
+ payload = bodyText ? JSON.parse(bodyText) : null;
223
+ } catch {
224
+ payload = null;
225
+ }
226
+
227
+ if (!response.ok) {
228
+ const result = {
229
+ ok: false,
230
+ models: [],
231
+ url,
232
+ error: `models route failed (${status}): ${clipText(bodyText || response.statusText || "unknown")}`,
233
+ status,
234
+ cached: false,
235
+ };
236
+ return result;
237
+ }
238
+
239
+ for (const id of extractModelIds(payload, { visibleOnly: provider.toLowerCase() === "codex" })) {
240
+ if (!models.includes(id)) models.push(id);
241
+ }
242
+ nextUrl = "";
243
+ if (payload && payload.has_more) {
244
+ const cursor = payload.last_id || payload.data?.at(-1)?.id;
245
+ if (!cursor) throw new Error("models route omitted its pagination cursor");
246
+ const pageUrl = new URL(url);
247
+ pageUrl.searchParams.set(transport === "anthropic-messages" ? "after_id" : "after", cursor);
248
+ nextUrl = pageUrl.toString();
249
+ }
250
+ } while (nextUrl);
251
+ const result = {
252
+ ok: true,
253
+ models,
254
+ url,
255
+ error: models.length === 0 ? "models route returned an empty catalog" : "",
256
+ status,
257
+ cached: false,
258
+ };
259
+ // Cache successful responses even when empty — avoids hammering a broken gateway.
260
+ modelsCache.set(key, { at: Date.now(), result: { ...result, cached: false } });
261
+ return result;
262
+ } catch (err) {
263
+ const message = err && err.name === "AbortError"
264
+ ? `models route timed out after ${timeoutMs}ms`
265
+ : (err && err.message ? err.message : String(err || "models route failed"));
266
+ return {
267
+ ok: false,
268
+ models: [],
269
+ url,
270
+ error: message,
271
+ status: 0,
272
+ cached: false,
273
+ };
274
+ } finally {
275
+ if (timer) clearTimeout(timer);
276
+ }
277
+ }
278
+
279
+ function modelSupported(model = "", models = []) {
280
+ const needle = String(model || "").trim();
281
+ if (!needle) return false;
282
+ const list = Array.isArray(models) ? models : [];
283
+ return list.some((id) => String(id || "").trim() === needle);
284
+ }
285
+
286
+ /**
287
+ * Validate a model id against the live catalog.
288
+ * Custom endpoints accept any nonempty id; their catalog is only a suggestion.
289
+ * Soft mode: when the catalog cannot be fetched, allow with a warning.
290
+ */
291
+ async function confirmModelSupported(options = {}) {
292
+ const model = String(options.model || "").trim();
293
+ if (!model) {
294
+ return {
295
+ ok: false,
296
+ allowed: false,
297
+ model: "",
298
+ models: [],
299
+ error: "model id is empty",
300
+ warning: "",
301
+ catalog: null,
302
+ };
303
+ }
304
+
305
+ if (usesCustomModelEndpoint(options)) {
306
+ return { ok: true, allowed: true, model, models: [], error: "", warning: "", catalog: null };
307
+ }
308
+
309
+ const catalog = await listProviderModels(options);
310
+ if (!catalog.ok) {
311
+ return {
312
+ ok: false,
313
+ allowed: options.strict === true ? false : true,
314
+ model,
315
+ models: [],
316
+ error: catalog.error || "models route unavailable",
317
+ warning: options.strict === true
318
+ ? ""
319
+ : `could not confirm model via models route (${catalog.error || "unavailable"}); accepting ${model}`,
320
+ catalog,
321
+ };
322
+ }
323
+
324
+ if (catalog.models.length === 0) {
325
+ return {
326
+ ok: false,
327
+ allowed: options.strict === true ? false : true,
328
+ model,
329
+ models: [],
330
+ error: catalog.error || "empty models catalog",
331
+ warning: options.strict === true
332
+ ? ""
333
+ : `models route returned no models; accepting ${model}`,
334
+ catalog,
335
+ };
336
+ }
337
+
338
+ if (!modelSupported(model, catalog.models)) {
339
+ const sample = catalog.models.slice(0, 8).join(", ");
340
+ const more = catalog.models.length > 8 ? ` (+${catalog.models.length - 8} more)` : "";
341
+ return {
342
+ ok: false,
343
+ allowed: false,
344
+ model,
345
+ models: catalog.models,
346
+ error: `model "${model}" is not in the provider catalog${sample ? ` (available: ${sample}${more})` : ""}`,
347
+ warning: "",
348
+ catalog,
349
+ };
350
+ }
351
+
352
+ return {
353
+ ok: true,
354
+ allowed: true,
355
+ model,
356
+ models: catalog.models,
357
+ error: "",
358
+ warning: "",
359
+ catalog,
360
+ };
361
+ }
362
+
363
+ function clearModelsCache() {
364
+ modelsCache.clear();
365
+ }
366
+
367
+ module.exports = {
368
+ resolveCodexClientVersion,
369
+ resolveOpenAiModelsUrl,
370
+ resolveAnthropicModelsUrl,
371
+ resolveModelsUrl,
372
+ listProviderModels,
373
+ usesCustomModelEndpoint,
374
+ confirmModelSupported,
375
+ modelSupported,
376
+ extractModelIds,
377
+ clearModelsCache,
378
+ CACHE_TTL_MS,
379
+ };
@@ -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");
@@ -68,24 +69,6 @@ function resolveMaxTokens(fallback) {
68
69
  return normalizePositiveInt(process.env.UFOO_UCODE_MAX_TOKENS, fallback);
69
70
  }
70
71
 
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
72
  function resolveReasoningEffort(options = {}) {
90
73
  const { resolveThinkingFromEnvAndConfig } = require("./thinkingLevels");
91
74
  const { loadGlobalUcodeConfig } = require("../../config");
@@ -104,6 +87,10 @@ function resolveReasoningEffort(options = {}) {
104
87
  return resolved.reasoningEffort || "";
105
88
  }
106
89
 
90
+ function thinkingOptions(thinkingLevel) {
91
+ return thinkingLevel ? { configLevel: thinkingLevel, env: {} } : {};
92
+ }
93
+
107
94
  function toUsageInt(value) {
108
95
  const parsed = Number(value);
109
96
  if (!Number.isFinite(parsed) || parsed <= 0) return 0;
@@ -134,14 +121,15 @@ function addUsageTotals(totals, usage = null) {
134
121
  // totals (prompt_tokens_details.cached_tokens counts the cache hits).
135
122
  function readOpenAiUsage(raw) {
136
123
  if (!raw || typeof raw !== "object") return null;
124
+ if (![raw.prompt_tokens, raw.completion_tokens, raw.prompt_tokens_details?.cached_tokens].some(value => value != null && Number.isFinite(Number(value)))) return null;
137
125
  const details = raw.prompt_tokens_details && typeof raw.prompt_tokens_details === "object"
138
126
  ? raw.prompt_tokens_details
139
127
  : {};
140
128
  return {
141
129
  input: toUsageInt(raw.prompt_tokens),
142
130
  output: toUsageInt(raw.completion_tokens),
143
- cacheRead: toUsageInt(details.cached_tokens),
144
- cacheCreation: toUsageInt(details.created_cache_tokens),
131
+ cacheRead: details.cached_tokens != null && Number.isFinite(Number(details.cached_tokens)) ? toUsageInt(details.cached_tokens) : null,
132
+ cacheCreation: toUsageInt(details.cache_write_tokens ?? details.created_cache_tokens),
145
133
  inputIncludesCache: true,
146
134
  };
147
135
  }
@@ -150,6 +138,7 @@ function readOpenAiUsage(raw) {
150
138
  // arrive per message_delta. The non-streaming body carries the full totals.
151
139
  function readAnthropicUsage(raw, { includeOutput = false } = {}) {
152
140
  if (!raw || typeof raw !== "object") return null;
141
+ 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
142
  return {
154
143
  input: toUsageInt(raw.input_tokens),
155
144
  output: includeOutput ? toUsageInt(raw.output_tokens) : 0,
@@ -380,8 +369,10 @@ async function runOpenAiLikeTurn({
380
369
  requestHeaders = {},
381
370
  model = "",
382
371
  provider = "",
372
+ thinkingLevel = "",
383
373
  messages = [],
384
374
  tools = [],
375
+ maxOutputTokens = null,
385
376
  onTextDelta = null,
386
377
  onThinkingDelta = null,
387
378
  onPhase = null,
@@ -391,21 +382,21 @@ async function runOpenAiLikeTurn({
391
382
  const normalizedProvider = normalizeProvider(provider);
392
383
  const payload = {
393
384
  model: normalizedProvider === "kimi" ? normalizeKimiModel(model) : model,
394
- max_tokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
385
+ max_tokens: maxOutputTokens || resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
395
386
  messages,
396
- tools,
397
- tool_choice: "auto",
387
+ ...(tools.length ? { tools, tool_choice: "auto" } : {}),
398
388
  stream: true,
399
389
  // Ask for the terminal usage chunk so token/cache accounting works.
400
390
  stream_options: { include_usage: true },
401
391
  // Kimi k3 rejects any temperature other than 1.
402
392
  temperature: normalizedProvider === "kimi" ? 1 : 0,
403
393
  };
404
- const reasoningEffort = resolveReasoningEffort();
394
+ const reasoningEffort = thinkingLevel === "off" ? "none" : resolveReasoningEffort(thinkingOptions(thinkingLevel));
405
395
  if (reasoningEffort) {
406
396
  // OpenAI-compatible gateways that support reasoning models accept this;
407
397
  // unknown fields are typically ignored by plain chat models.
408
398
  payload.reasoning_effort = reasoningEffort;
399
+ if (thinkingLevel && normalizedProvider === "openai" && reasoningEffort !== "none") delete payload.temperature;
409
400
  }
410
401
 
411
402
  const headers = normalizedProvider === "kimi"
@@ -550,7 +541,7 @@ async function runOpenAiLikeTurn({
550
541
  }
551
542
 
552
543
  function currentGrokClientVersion() {
553
- return String(process.env.UFOO_GROK_CLIENT_VERSION || "0.2.120").trim() || "0.2.120";
544
+ return resolveGrokClientVersion();
554
545
  }
555
546
 
556
547
  function isGrokCliProxyUrl(url = "") {
@@ -595,10 +586,7 @@ function buildResponsesHeaders({ provider = "", apiKey = "", sessionId = "", acc
595
586
  if (apiKey) headers.authorization = `Bearer ${apiKey}`;
596
587
 
597
588
  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
- );
589
+ headers["User-Agent"] = resolveCodexUserAgent();
602
590
  headers.Originator = "codex-tui";
603
591
  headers["Session-Id"] = String(sessionId || randomUUID());
604
592
  if (accountId) headers["Chatgpt-Account-Id"] = String(accountId);
@@ -629,9 +617,11 @@ async function runResponsesTurn({
629
617
  requestProfile = "",
630
618
  model = "",
631
619
  provider = "",
620
+ thinkingLevel = "",
632
621
  systemPrompt = "",
633
622
  messages = [],
634
623
  tools = [],
624
+ maxOutputTokens = null,
635
625
  sessionId = "",
636
626
  accountId = "",
637
627
  onTextDelta = null,
@@ -645,8 +635,8 @@ async function runResponsesTurn({
645
635
  instructions: systemPrompt,
646
636
  messages,
647
637
  tools,
648
- maxOutputTokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
649
- reasoningEffort: resolveReasoningEffort(),
638
+ maxOutputTokens: maxOutputTokens || resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
639
+ reasoningEffort: thinkingLevel === "off" ? "none" : resolveReasoningEffort(thinkingOptions(thinkingLevel)),
650
640
  provider: normalizeProvider(provider),
651
641
  });
652
642
  const headers = buildResponsesHeaders({ provider, apiKey, sessionId, accountId, url });
@@ -820,10 +810,12 @@ async function runAnthropicTurn({
820
810
  apiKey = "",
821
811
  requestHeaders = {},
822
812
  model = "",
813
+ thinkingLevel = "",
823
814
  systemPrompt = "",
824
815
  systemBlocks = null,
825
816
  messages = [],
826
817
  tools = [],
818
+ maxOutputTokens = null,
827
819
  onTextDelta = null,
828
820
  onThinkingDelta = null,
829
821
  onPhase = null,
@@ -832,14 +824,28 @@ async function runAnthropicTurn({
832
824
  } = {}) {
833
825
  const payload = {
834
826
  model,
835
- max_tokens: resolveMaxTokens(DEFAULT_ANTHROPIC_MAX_TOKENS),
827
+ max_tokens: maxOutputTokens || resolveMaxTokens(DEFAULT_ANTHROPIC_MAX_TOKENS),
836
828
  messages: withAnthropicCacheBreakpoint(messages),
837
829
  tools: tools.map((spec) => ({ name: spec.function.name, description: spec.function.description, input_schema: spec.function.parameters })),
838
830
  stream: true,
839
831
  };
840
- const thinkingBudget = Math.min(resolveThinkingBudgetTokens(), payload.max_tokens - 1);
841
- if (thinkingBudget >= 1024) {
842
- payload.thinking = { type: "enabled", budget_tokens: thinkingBudget };
832
+ const isOpus55 = /^(?:claude-)?opus-5[.-]5(?:$|-)/i.test(model);
833
+ const supportsAdaptiveThinking = /^(?:claude-)?(?:(?:opus|sonnet)-(?:4[.-][678]|5(?:[.-]5)?)|haiku-5[.-]5)(?:$|-)/i.test(model);
834
+ const reasoningEffort = thinkingLevel === "off" ? "" : resolveReasoningEffort(thinkingOptions(thinkingLevel));
835
+ if (isOpus55) {
836
+ // Opus 5.5 always uses adaptive thinking and rejects manual budgets.
837
+ // Summaries keep its progress visible in the shared agent transcript.
838
+ payload.thinking = { type: "adaptive", display: "summarized" };
839
+ payload.output_config = {
840
+ // This model cannot disable thinking; low is the smallest supported effort.
841
+ effort: thinkingLevel === "off" ? "low" : (reasoningEffort || "medium"),
842
+ };
843
+ } else if (supportsAdaptiveThinking && reasoningEffort) {
844
+ payload.thinking = { type: "adaptive" };
845
+ payload.output_config = {
846
+ // The 4.6 models predate xhigh effort.
847
+ effort: /-4[.-]6(?:$|-)/i.test(model) && reasoningEffort === "xhigh" ? "high" : reasoningEffort,
848
+ };
843
849
  }
844
850
  if (Array.isArray(systemBlocks) && systemBlocks.length > 0) {
845
851
  payload.system = systemBlocksToAnthropicPayload(systemBlocks);
@@ -869,6 +875,7 @@ async function runAnthropicTurn({
869
875
  let responseText = "";
870
876
  let nextSyntheticBlockIndex = 0;
871
877
  let lastBlockIndex = -1;
878
+ let usageObserved = false;
872
879
  const turnUsage = {
873
880
  input: 0,
874
881
  output: 0,
@@ -893,12 +900,14 @@ async function runAnthropicTurn({
893
900
  if (text && typeof onTextDelta === "function") {
894
901
  onTextDelta(text);
895
902
  }
896
- addUsageTotals(turnUsage, readAnthropicUsage(data && data.usage, { includeOutput: true }));
903
+ const usage = readAnthropicUsage(data && data.usage, { includeOutput: true });
904
+ usageObserved = Boolean(usage);
905
+ addUsageTotals(turnUsage, usage);
897
906
  return {
898
907
  text,
899
908
  assistantContent: content,
900
909
  toolCalls: extractAnthropicToolCalls(content),
901
- usage: turnUsage,
910
+ usage: usageObserved ? turnUsage : null,
902
911
  };
903
912
  },
904
913
  onEvent: ({ event, data }) => {
@@ -919,6 +928,7 @@ async function runAnthropicTurn({
919
928
  : null
920
929
  );
921
930
  if (messageUsage) {
931
+ usageObserved = true;
922
932
  turnUsage.input = messageUsage.input;
923
933
  turnUsage.cacheRead = messageUsage.cacheRead;
924
934
  turnUsage.cacheCreation = messageUsage.cacheCreation;
@@ -930,6 +940,7 @@ async function runAnthropicTurn({
930
940
  const deltaUsage = payloadChunk.usage && typeof payloadChunk.usage === "object"
931
941
  ? payloadChunk.usage
932
942
  : {};
943
+ if (deltaUsage.output_tokens != null && Number.isFinite(Number(deltaUsage.output_tokens))) usageObserved = true;
933
944
  turnUsage.output += toUsageInt(deltaUsage.output_tokens);
934
945
  return;
935
946
  }
@@ -1090,7 +1101,7 @@ async function runAnthropicTurn({
1090
1101
  text: responseText,
1091
1102
  assistantContent,
1092
1103
  toolCalls: extractAnthropicToolCalls(assistantContent),
1093
- usage: turnUsage,
1104
+ usage: usageObserved ? turnUsage : null,
1094
1105
  };
1095
1106
  },
1096
1107
  });
@@ -1130,6 +1141,6 @@ const TRANSPORTS = {
1130
1141
 
1131
1142
  module.exports = {
1132
1143
  getNativeTransport: (name) => TRANSPORTS[name] || TRANSPORTS["openai-chat"],
1133
- createNativeSseDispatcher, resolveThinkingBudgetTokens, resolveReasoningEffort,
1144
+ createNativeSseDispatcher, resolveReasoningEffort,
1134
1145
  normalizeTimeoutMs, createUsageTotals, cloneMessageList,
1135
1146
  };