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.
- package/OBSERVABILITY.md +65 -0
- package/README.md +90 -30
- package/README.zh-CN.md +76 -26
- package/SKILLS/ufoo/SKILL.md +25 -1
- package/SKILLS/ufoo-bus/SKILL.md +25 -2
- package/bin/ucode.js +4 -0
- package/bin/ufoo.js +3 -3
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/dist/tui/darwin-x64/ufoo-tui +0 -0
- package/dist/tui/linux-arm64/ufoo-tui +0 -0
- package/dist/tui/linux-x64/ufoo-tui +0 -0
- package/package.json +6 -6
- package/src/agents/activity/activityDetector.js +1 -1
- package/src/agents/capabilities/agentManagement/service.js +40 -13
- package/src/agents/capabilities/coordination/index.js +1 -1
- package/src/agents/capabilities/taskReports/index.js +1 -1
- package/src/agents/controller/controllerToolExecutor.js +36 -20
- package/src/agents/controller/index.js +1 -6
- package/src/agents/internal/internalRunner.js +90 -56
- package/src/agents/launch/index.js +0 -1
- package/src/agents/launch/launcher.js +38 -29
- package/src/agents/launch/launcherReadiness.js +35 -0
- package/src/agents/launch/notifier.js +2 -2
- package/src/agents/launch/ptyWrapper.js +5 -2
- package/src/agents/launch/readyDetector.js +2 -2
- package/src/agents/profiles/main.js +1 -1
- package/src/agents/prompts/cooperation.js +14 -0
- package/src/agents/prompts/defaultBootstrap.js +1 -1
- package/src/agents/prompts/groupBootstrap.js +23 -7
- package/src/agents/prompts/mainAgent.js +11 -2
- package/src/agents/prompts/native/system.js +4 -1
- package/src/agents/prompts/native/ufoo.js +11 -3
- package/src/agents/prompts/promptProfiles.js +2 -0
- package/src/agents/prompts/reporting.js +16 -0
- package/src/agents/providers/claudeEventTranslator.js +3 -0
- package/src/agents/providers/claudeThreadProvider.js +3 -2
- package/src/agents/providers/clientIdentity.js +75 -0
- package/src/agents/providers/codexEventTranslator.js +23 -2
- package/src/agents/providers/codexThreadProvider.js +15 -6
- package/src/agents/providers/credentials/index.js +2 -0
- package/src/agents/providers/directAuthStatus.js +1 -1
- package/src/agents/providers/index.js +1 -1
- package/src/agents/providers/modelSettings.js +34 -0
- package/src/agents/providers/modelsCatalog.js +379 -0
- package/src/agents/providers/nativeTransport.js +58 -40
- package/src/agents/providers/runtimeConfig.js +10 -8
- package/src/agents/providers/thinkingLevels.js +10 -36
- package/src/agents/providers/transports/responsesProtocol.js +11 -6
- package/src/agents/providers/upstreamRuntime.js +135 -0
- package/src/agents/runtime/context/checkpointStore.js +38 -0
- package/src/agents/runtime/context/compaction.js +151 -0
- package/src/agents/runtime/context/contextBudget.js +93 -0
- package/src/agents/runtime/context/replayHistory.js +28 -0
- package/src/agents/runtime/context/runtimeStore.js +2 -1
- package/src/agents/runtime/core/agentLoop.js +99 -18
- package/src/agents/runtime/core/executionBudget.js +36 -0
- package/src/agents/runtime/createAgentRuntime.js +16 -4
- package/src/agents/runtime/prompts/responseLanguage.js +12 -0
- package/src/agents/runtime/protocol/runObservation.js +24 -0
- package/src/agents/runtime/protocol/traceContext.js +9 -0
- package/src/app/chat/ChatController.js +26 -53
- package/src/app/chat/agentDirectory.js +1 -16
- package/src/app/chat/bootstrap.js +1 -2
- package/src/app/chat/commandExecutor.js +93 -285
- package/src/app/chat/commands.js +32 -45
- package/src/app/chat/daemonMessageRouter.js +0 -45
- package/src/app/chat/historyStore.js +12 -48
- package/src/app/chat/inputSubmitHandler.js +7 -33
- package/src/app/chat/internalAgentLogHistory.js +19 -60
- package/src/app/chat/multiWindow/paneManager.js +10 -3
- package/src/app/chat/streamState.js +0 -4
- package/src/app/cli/features/init.js +5 -5
- package/src/app/cli/metricsCommands.js +68 -0
- package/src/app/cli/run.js +42 -3
- package/src/app/cli/traceCommands.js +36 -0
- package/src/code/agent.js +18 -13
- package/src/code/busConsumer.js +1 -3
- package/src/code/commands.js +1 -1
- package/src/code/context/assembler.js +7 -8
- package/src/code/context/stateCommit.js +2 -1
- package/src/code/internalThread.js +10 -3
- package/src/code/launcher/ucode.js +1 -1
- package/src/code/launcher/ucodeBootstrap.js +1 -1
- package/src/code/modelCommand.js +11 -35
- package/src/code/nativeRunner.js +55 -17
- package/src/code/providers/modelsCatalog.js +1 -317
- package/src/code/repl.js +4 -11
- package/src/code/sessionStore.js +3 -3
- package/src/code/taskDecomposer.js +18 -0
- package/src/code/toolBudget.js +1 -17
- package/src/config.js +22 -72
- package/src/coordination/bus/index.js +12 -3
- package/src/coordination/bus/inject.js +2 -2
- package/src/coordination/bus/message.js +15 -1
- package/src/coordination/bus/nickname.js +1 -1
- package/src/coordination/bus/subscriber.js +3 -2
- package/src/coordination/bus/utils.js +1 -1
- package/src/coordination/history/agentPerformance.js +279 -0
- package/src/coordination/history/agentTrace.js +249 -0
- package/src/coordination/state/workspaceAccess.js +1 -1
- package/src/orchestration/controller/index.js +1 -8
- package/src/orchestration/controller/launchRouting.js +1 -1
- package/src/orchestration/solo/commands.js +3 -1
- package/src/runtime/contracts/agentMode.js +11 -2
- package/src/runtime/contracts/uiProtocol.js +18 -19
- package/src/runtime/daemon/agentHost.js +57 -25
- package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
- package/src/runtime/daemon/busBridge.js +1 -1
- package/src/runtime/daemon/controlPlaneService.js +1 -1
- package/src/runtime/daemon/groupOrchestrator.js +20 -5
- package/src/runtime/daemon/groupStatus.js +20 -0
- package/src/runtime/daemon/index.js +19 -44
- package/src/runtime/daemon/mcpHttpServer.js +39 -10
- package/src/runtime/daemon/mcpServer.js +1 -1
- package/src/runtime/daemon/nicknameScope.js +1 -1
- package/src/runtime/daemon/ops.js +46 -23
- package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
- package/src/runtime/daemon/promptRequest.js +92 -589
- package/src/runtime/daemon/status.js +5 -6
- package/src/tools/controllerSchemas.js +6 -2
- package/src/tools/handlers/tier2.js +4 -2
- package/src/tools/registry.js +4 -0
- package/src/tools/schemaFixtures.js +26 -2
- package/src/tools/tier0/readAgentMetrics.js +14 -0
- package/src/tools/tier0/readAgentTrace.js +12 -0
- package/src/ui/agentSettingsController.js +107 -0
- package/src/ui/agentSurface.js +1 -1
- package/src/ui/dashboardBridge.js +1 -1
- package/src/ui/format/banner.js +1 -4
- package/src/ui/format/index.js +14 -10
- package/src/ui/format/loopSummary.js +50 -0
- package/src/ui/format/markdownRenderer.js +3 -4
- package/src/ui/rustChatHost.js +191 -206
- package/src/ui/rustMultiSession.js +77 -36
- package/src/ui/rustUcodeHost.js +6 -1
- package/src/ui/settingsBridge.js +33 -16
- package/src/ui/toolMergeBridge.js +0 -4
- package/src/ui/uiHostServer.js +5 -8
- package/src/agents/controller/loopObservability.js +0 -200
- package/src/agents/controller/loopRuntime.js +0 -336
- package/src/agents/controller/ufooAgent.js +0 -830
- package/src/agents/launch/ptyRunner.js +0 -1135
- package/src/agents/providers/controllerJsonTransport.js +0 -28
- package/src/agents/providers/upstreamTransport.js +0 -698
- package/src/app/chat/agentBar.js +0 -135
- package/src/app/chat/agentSockets.js +0 -225
- package/src/app/chat/dashboardView.js +0 -405
- package/src/app/chat/rawKeyMap.js +0 -42
- package/src/app/chat/settingsController.js +0 -111
- package/src/coordination/history/controllerSummary.js +0 -23
- package/src/orchestration/controller/flags.js +0 -167
- package/src/orchestration/controller/gateRouter.js +0 -211
- package/src/orchestration/controller/routerFastPath.js +0 -22
- package/src/orchestration/controller/routerFinalize.js +0 -222
- package/src/orchestration/controller/shadowGuard.js +0 -280
- package/src/runtime/daemon/executionPaths.js +0 -30
- package/src/runtime/daemon/promptLoop.js +0 -136
- package/src/runtime/privacy/shadowDiff.js +0 -174
|
@@ -1,698 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
const os = require("os");
|
|
4
|
-
const { randomUUID } = require("crypto");
|
|
5
|
-
const {
|
|
6
|
-
loadConfig,
|
|
7
|
-
defaultAgentModelForProvider,
|
|
8
|
-
defaultRouterModelForProvider,
|
|
9
|
-
sameModelProvider,
|
|
10
|
-
} = require("../../config");
|
|
11
|
-
const {
|
|
12
|
-
resolveRuntimeConfig,
|
|
13
|
-
resolveCompletionUrl,
|
|
14
|
-
resolveAnthropicMessagesUrl,
|
|
15
|
-
} = require("./runtimeConfig");
|
|
16
|
-
const {
|
|
17
|
-
buildResponsesPayload,
|
|
18
|
-
parseResponsesEvents,
|
|
19
|
-
resolveResponsesUrl,
|
|
20
|
-
} = require("./transports/responsesProtocol");
|
|
21
|
-
const { resolveClaudeUpstreamCredentials } = require("./credentials/claude");
|
|
22
|
-
const { resolveCodexUpstreamCredentials } = require("./credentials/codex");
|
|
23
|
-
const { resolveKimiUpstreamCredentials } = require("./credentials/kimi");
|
|
24
|
-
const { buildUpstreamAuthFromCredential } = require("./credentials");
|
|
25
|
-
|
|
26
|
-
function normalizeProvider(value = "") {
|
|
27
|
-
const text = String(value || "").trim().toLowerCase();
|
|
28
|
-
if (!text) return "ucode";
|
|
29
|
-
if (text === "codex-cli" || text === "codex-code" || text === "codex" || text === "openai") return "codex";
|
|
30
|
-
if (text === "claude-cli" || text === "claude-code" || text === "claude" || text === "anthropic") return "claude";
|
|
31
|
-
if (text === "grok" || text === "grok-cli" || text === "grok-build" || text === "grok-shell" || text === "grok-api" || text === "xai") return "grok";
|
|
32
|
-
if (text === "ucode" || text === "ufoo" || text === "ufoo-code") return "ucode";
|
|
33
|
-
if (text === "kimi-cli" || text === "kimi-code" || text === "moonshot") return "kimi";
|
|
34
|
-
return text;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function clipText(value = "", maxChars = 500) {
|
|
38
|
-
const text = String(value || "");
|
|
39
|
-
if (text.length <= maxChars) return text;
|
|
40
|
-
return `${text.slice(0, maxChars)}...[truncated]`;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const CODEX_DEFAULT_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
44
|
-
const CODEX_DEFAULT_USER_AGENT = "codex-tui/0.118.0 (Mac OS 26.3.1; arm64) iTerm.app/3.6.9 (codex-tui; 0.118.0)";
|
|
45
|
-
const CODEX_DEFAULT_ORIGINATOR = "codex-tui";
|
|
46
|
-
const GROK_DEFAULT_CLIENT_VERSION = "0.2.120";
|
|
47
|
-
const KIMI_DEFAULT_CLIENT_VERSION = (() => {
|
|
48
|
-
try {
|
|
49
|
-
return String(require("../../../package.json").version || "dev").trim() || "dev";
|
|
50
|
-
} catch {
|
|
51
|
-
return "dev";
|
|
52
|
-
}
|
|
53
|
-
})();
|
|
54
|
-
|
|
55
|
-
function normalizeKimiUpstreamModel(value = "") {
|
|
56
|
-
const raw = String(value || "").trim();
|
|
57
|
-
if (!raw) return "";
|
|
58
|
-
const suffix = raw.match(/^(.*?)(\([^)]*\))$/);
|
|
59
|
-
const base = String(suffix ? suffix[1] : raw).trim().replace(/\[1m\]$/i, "");
|
|
60
|
-
const lower = base.toLowerCase();
|
|
61
|
-
let normalized = lower;
|
|
62
|
-
if (["kimi-k2.7-code", "k2.7-code", "kimi-for-coding", "for-coding"].includes(lower)) {
|
|
63
|
-
normalized = "kimi-for-coding";
|
|
64
|
-
} else if (["kimi-k2.7-code-highspeed", "k2.7-code-highspeed", "kimi-for-coding-highspeed", "for-coding-highspeed"].includes(lower)) {
|
|
65
|
-
normalized = "kimi-for-coding-highspeed";
|
|
66
|
-
} else if (normalized.startsWith("kimi-")) {
|
|
67
|
-
normalized = normalized.slice("kimi-".length);
|
|
68
|
-
}
|
|
69
|
-
return `${normalized}${suffix ? suffix[2] : ""}`;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function applyKimiHeaders(headers, { apiKey = "", stream = false } = {}) {
|
|
73
|
-
const version = String(process.env.UFOO_KIMI_CLIENT_VERSION || KIMI_DEFAULT_CLIENT_VERSION).trim()
|
|
74
|
-
|| KIMI_DEFAULT_CLIENT_VERSION;
|
|
75
|
-
if (apiKey) headers.authorization = `Bearer ${apiKey}`;
|
|
76
|
-
headers["User-Agent"] = `ufoo/${version}`;
|
|
77
|
-
headers["X-Msh-Platform"] = "ufoo";
|
|
78
|
-
headers["X-Msh-Version"] = version;
|
|
79
|
-
headers["X-Msh-Device-Name"] = os.hostname();
|
|
80
|
-
headers["X-Msh-Device-Model"] = `${process.platform} ${process.arch}`;
|
|
81
|
-
headers["X-Msh-Device-Id"] = String(process.env.KIMI_DEVICE_ID || "ufoo-kimi-device").trim() || "ufoo-kimi-device";
|
|
82
|
-
headers.Accept = stream ? "text/event-stream" : "application/json";
|
|
83
|
-
return headers;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
function isGrokCliProxyUrl(url = "") {
|
|
87
|
-
try {
|
|
88
|
-
return new URL(String(url || "")).hostname.toLowerCase() === "cli-chat-proxy.grok.com";
|
|
89
|
-
} catch {
|
|
90
|
-
return false;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function applyGrokResponsesHeaders(headers, { provider = "", baseUrl = "", sessionId = "" } = {}) {
|
|
95
|
-
const normalizedProvider = normalizeProvider(provider);
|
|
96
|
-
if (normalizedProvider !== "grok" && normalizedProvider !== "xai") return headers;
|
|
97
|
-
const version = String(process.env.UFOO_GROK_CLIENT_VERSION || GROK_DEFAULT_CLIENT_VERSION).trim()
|
|
98
|
-
|| GROK_DEFAULT_CLIENT_VERSION;
|
|
99
|
-
if (sessionId) headers["x-grok-conv-id"] = String(sessionId);
|
|
100
|
-
if (isGrokCliProxyUrl(baseUrl)) {
|
|
101
|
-
headers["X-XAI-Token-Auth"] = "xai-grok-cli";
|
|
102
|
-
headers["x-grok-client-version"] = version;
|
|
103
|
-
headers["x-grok-client-identifier"] = "grok-shell";
|
|
104
|
-
headers["x-authenticateresponse"] = "authenticate-response";
|
|
105
|
-
headers["User-Agent"] = `xai-grok-workspace/${version}`;
|
|
106
|
-
} else if (normalizedProvider === "grok") {
|
|
107
|
-
headers["User-Agent"] = `grok-shell/${version}`;
|
|
108
|
-
}
|
|
109
|
-
return headers;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function resolveConfiguredModelForProvider(config = {}, provider = "") {
|
|
113
|
-
if (config.routerProvider && sameModelProvider(config.routerProvider, provider)) {
|
|
114
|
-
return config.routerModel;
|
|
115
|
-
}
|
|
116
|
-
if (config.agentProvider && sameModelProvider(config.agentProvider, provider)) {
|
|
117
|
-
return config.agentModel;
|
|
118
|
-
}
|
|
119
|
-
return "";
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function buildOpenAiChatRequest({
|
|
123
|
-
model = "",
|
|
124
|
-
systemPrompt = "",
|
|
125
|
-
prompt = "",
|
|
126
|
-
messages = [],
|
|
127
|
-
tools = [],
|
|
128
|
-
temperature = 0,
|
|
129
|
-
} = {}) {
|
|
130
|
-
const requestMessages = Array.isArray(messages) ? messages.map((message) => ({ ...message })) : [];
|
|
131
|
-
if (!requestMessages.length) {
|
|
132
|
-
if (systemPrompt) requestMessages.push({ role: "system", content: String(systemPrompt) });
|
|
133
|
-
requestMessages.push({ role: "user", content: String(prompt || "") });
|
|
134
|
-
}
|
|
135
|
-
const request = {
|
|
136
|
-
model: String(model || "").trim(),
|
|
137
|
-
messages: requestMessages,
|
|
138
|
-
temperature,
|
|
139
|
-
};
|
|
140
|
-
if (Array.isArray(tools) && tools.length > 0) {
|
|
141
|
-
request.tools = tools.slice();
|
|
142
|
-
}
|
|
143
|
-
return request;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// Anthropic prompt caching allows up to 4 cache_control breakpoints; the
|
|
147
|
-
// system prompt is a stable prefix, so it is always marked, and once there
|
|
148
|
-
// is real history the last user message is marked too so follow-up turns
|
|
149
|
-
// reuse the cached conversation prefix.
|
|
150
|
-
const ANTHROPIC_CACHE_CONTROL = { type: "ephemeral" };
|
|
151
|
-
const ANTHROPIC_CACHE_MIN_HISTORY = 3;
|
|
152
|
-
|
|
153
|
-
function withAnthropicCacheControl(content) {
|
|
154
|
-
if (Array.isArray(content)) {
|
|
155
|
-
if (!content.length) return content;
|
|
156
|
-
return content.map((block, index) => (
|
|
157
|
-
index === content.length - 1 && block && typeof block === "object"
|
|
158
|
-
? { ...block, cache_control: { ...ANTHROPIC_CACHE_CONTROL } }
|
|
159
|
-
: block
|
|
160
|
-
));
|
|
161
|
-
}
|
|
162
|
-
return [{
|
|
163
|
-
type: "text",
|
|
164
|
-
text: String(content || ""),
|
|
165
|
-
cache_control: { ...ANTHROPIC_CACHE_CONTROL },
|
|
166
|
-
}];
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
function buildAnthropicMessagesRequest({
|
|
170
|
-
model = "",
|
|
171
|
-
systemPrompt = "",
|
|
172
|
-
prompt = "",
|
|
173
|
-
messages = [],
|
|
174
|
-
tools = [],
|
|
175
|
-
maxTokens = 4096,
|
|
176
|
-
temperature = 0,
|
|
177
|
-
} = {}) {
|
|
178
|
-
const requestMessages = Array.isArray(messages) ? messages.map((message) => ({ ...message })) : [];
|
|
179
|
-
if (!requestMessages.length) {
|
|
180
|
-
requestMessages.push({ role: "user", content: String(prompt || "") });
|
|
181
|
-
}
|
|
182
|
-
if (requestMessages.length >= ANTHROPIC_CACHE_MIN_HISTORY) {
|
|
183
|
-
for (let i = requestMessages.length - 1; i >= 0; i -= 1) {
|
|
184
|
-
if (requestMessages[i].role !== "user") continue;
|
|
185
|
-
requestMessages[i].content = withAnthropicCacheControl(requestMessages[i].content);
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
const request = {
|
|
190
|
-
model: String(model || "").trim(),
|
|
191
|
-
max_tokens: maxTokens,
|
|
192
|
-
messages: requestMessages,
|
|
193
|
-
temperature,
|
|
194
|
-
};
|
|
195
|
-
if (systemPrompt) request.system = withAnthropicCacheControl(String(systemPrompt));
|
|
196
|
-
if (Array.isArray(tools) && tools.length > 0) {
|
|
197
|
-
request.tools = tools.slice();
|
|
198
|
-
}
|
|
199
|
-
return request;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
function normalizeCodexContentPart(role = "user", text = "") {
|
|
203
|
-
return {
|
|
204
|
-
type: role === "assistant" ? "output_text" : "input_text",
|
|
205
|
-
text: String(text || ""),
|
|
206
|
-
};
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
function normalizeCodexMessage(role = "user", content = "") {
|
|
210
|
-
return {
|
|
211
|
-
type: "message",
|
|
212
|
-
role: role === "system" ? "developer" : role,
|
|
213
|
-
content: [normalizeCodexContentPart(role, content)],
|
|
214
|
-
};
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
function buildCodexResponsesRequest({
|
|
218
|
-
model = "",
|
|
219
|
-
systemPrompt = "",
|
|
220
|
-
prompt = "",
|
|
221
|
-
messages = [],
|
|
222
|
-
tools = [],
|
|
223
|
-
maxTokens = 131072,
|
|
224
|
-
reasoningEffort = "",
|
|
225
|
-
} = {}) {
|
|
226
|
-
const inputMessages = Array.isArray(messages) ? messages.slice() : [];
|
|
227
|
-
if (String(prompt || "").trim()) {
|
|
228
|
-
inputMessages.push({ role: "user", content: String(prompt || "") });
|
|
229
|
-
}
|
|
230
|
-
return buildResponsesPayload({
|
|
231
|
-
model,
|
|
232
|
-
instructions: systemPrompt,
|
|
233
|
-
messages: inputMessages,
|
|
234
|
-
tools,
|
|
235
|
-
maxOutputTokens: maxTokens,
|
|
236
|
-
reasoningEffort,
|
|
237
|
-
provider: "codex",
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
function resolveCodexResponseOutput(response = {}) {
|
|
242
|
-
const output = Array.isArray(response.output) ? response.output : [];
|
|
243
|
-
return output
|
|
244
|
-
.filter((item) => item && item.type === "message")
|
|
245
|
-
.flatMap((item) => (Array.isArray(item.content) ? item.content : []))
|
|
246
|
-
.filter((part) => part && part.type === "output_text")
|
|
247
|
-
.map((part) => String(part.text || ""))
|
|
248
|
-
.join("");
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
function parseCodexSsePayload(payload = "") {
|
|
252
|
-
const lines = String(payload || "").split(/\r?\n/);
|
|
253
|
-
const frames = [];
|
|
254
|
-
let currentEvent = "";
|
|
255
|
-
for (const line of lines) {
|
|
256
|
-
const trimmed = line.trim();
|
|
257
|
-
if (trimmed.startsWith("event:")) {
|
|
258
|
-
currentEvent = trimmed.slice(6).trim();
|
|
259
|
-
continue;
|
|
260
|
-
}
|
|
261
|
-
if (!trimmed.startsWith("data:")) continue;
|
|
262
|
-
const dataText = trimmed.slice(5).trim();
|
|
263
|
-
if (!dataText || dataText === "[DONE]") continue;
|
|
264
|
-
try {
|
|
265
|
-
const data = JSON.parse(dataText);
|
|
266
|
-
frames.push({ event: currentEvent || data.type || "", data });
|
|
267
|
-
currentEvent = "";
|
|
268
|
-
} catch {
|
|
269
|
-
continue;
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
const parsed = parseResponsesEvents(frames);
|
|
274
|
-
const rawUsage = parsed.response && parsed.response.usage && typeof parsed.response.usage === "object"
|
|
275
|
-
? parsed.response.usage
|
|
276
|
-
: null;
|
|
277
|
-
|
|
278
|
-
return {
|
|
279
|
-
text: String(parsed.text || "").trim(),
|
|
280
|
-
response: parsed.response,
|
|
281
|
-
usage: rawUsage,
|
|
282
|
-
normalizedUsage: parsed.usage,
|
|
283
|
-
toolCalls: parsed.toolCalls,
|
|
284
|
-
terminal: parsed.terminal,
|
|
285
|
-
incompleteDetails: parsed.incompleteDetails,
|
|
286
|
-
events: parsed.events,
|
|
287
|
-
};
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
function resolveUpstreamResponsesUsage(parsed = {}) {
|
|
291
|
-
const raw = parsed.response && parsed.response.usage && typeof parsed.response.usage === "object"
|
|
292
|
-
? parsed.response.usage
|
|
293
|
-
: null;
|
|
294
|
-
if (raw) return raw;
|
|
295
|
-
const normalized = parsed.usage && typeof parsed.usage === "object" ? parsed.usage : null;
|
|
296
|
-
if (!normalized) return null;
|
|
297
|
-
return {
|
|
298
|
-
input_tokens: Number(normalized.input || 0) || 0,
|
|
299
|
-
output_tokens: Number(normalized.output || 0) || 0,
|
|
300
|
-
cache_read_input_tokens: Number(normalized.cacheRead || 0) || 0,
|
|
301
|
-
cache_creation_input_tokens: Number(normalized.cacheCreation || 0) || 0,
|
|
302
|
-
};
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
async function resolveUpstreamRuntime({
|
|
306
|
-
projectRoot,
|
|
307
|
-
provider = "",
|
|
308
|
-
model = "",
|
|
309
|
-
env = process.env,
|
|
310
|
-
fetchImpl = global.fetch,
|
|
311
|
-
loadConfigImpl = loadConfig,
|
|
312
|
-
} = {}) {
|
|
313
|
-
const normalizedProvider = normalizeProvider(provider);
|
|
314
|
-
const config = loadConfigImpl(projectRoot);
|
|
315
|
-
|
|
316
|
-
if (normalizedProvider === "codex") {
|
|
317
|
-
const credential = await resolveCodexUpstreamCredentials({
|
|
318
|
-
authPath: config.codexAuthPath,
|
|
319
|
-
refreshWindowMs: Number(config.codexOauthRefreshWindowSec || 300) * 1000,
|
|
320
|
-
fetchImpl,
|
|
321
|
-
env,
|
|
322
|
-
});
|
|
323
|
-
const useCodexOAuth = credential.credentialKind === "oauth" && Boolean(credential.accessToken);
|
|
324
|
-
const baseUrl = useCodexOAuth
|
|
325
|
-
? String(env.UFOO_CODEX_BASE_URL || "").trim() || CODEX_DEFAULT_BASE_URL
|
|
326
|
-
: String(env.OPENAI_BASE_URL || "").trim() || "https://api.openai.com/v1";
|
|
327
|
-
const resolvedModel = String(
|
|
328
|
-
model
|
|
329
|
-
|| resolveConfiguredModelForProvider(config, "codex")
|
|
330
|
-
|| defaultRouterModelForProvider("codex")
|
|
331
|
-
).trim();
|
|
332
|
-
return {
|
|
333
|
-
provider: "codex",
|
|
334
|
-
transport: "codex-responses",
|
|
335
|
-
requestProfile: useCodexOAuth ? "codex-subscription" : "openai-responses",
|
|
336
|
-
model: resolvedModel,
|
|
337
|
-
baseUrl,
|
|
338
|
-
credential,
|
|
339
|
-
auth: buildUpstreamAuthFromCredential(credential),
|
|
340
|
-
credentialSource: String(credential.source || ""),
|
|
341
|
-
};
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
if (normalizedProvider === "claude") {
|
|
345
|
-
const credential = await resolveClaudeUpstreamCredentials({
|
|
346
|
-
profile: config.claudeOauthProfile,
|
|
347
|
-
tokenPath: config.claudeOauthTokenPath,
|
|
348
|
-
refreshWindowMs: Number(config.claudeOauthRefreshWindowSec || 300) * 1000,
|
|
349
|
-
env,
|
|
350
|
-
});
|
|
351
|
-
const baseUrl = String(env.ANTHROPIC_BASE_URL || credential.metadata?.baseUrl || "").trim() || "https://api.anthropic.com/v1";
|
|
352
|
-
const resolvedModel = String(
|
|
353
|
-
model
|
|
354
|
-
|| resolveConfiguredModelForProvider(config, "claude")
|
|
355
|
-
|| defaultRouterModelForProvider("claude")
|
|
356
|
-
).trim();
|
|
357
|
-
return {
|
|
358
|
-
provider: "claude",
|
|
359
|
-
transport: "anthropic-messages",
|
|
360
|
-
model: resolvedModel,
|
|
361
|
-
baseUrl,
|
|
362
|
-
credential,
|
|
363
|
-
auth: buildUpstreamAuthFromCredential(credential),
|
|
364
|
-
credentialSource: String(credential.source || ""),
|
|
365
|
-
};
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
if (normalizedProvider === "grok") {
|
|
369
|
-
const runtime = resolveRuntimeConfig({
|
|
370
|
-
workspaceRoot: projectRoot,
|
|
371
|
-
provider: "grok-build",
|
|
372
|
-
model: model || resolveConfiguredModelForProvider(config, "grok-build") || defaultRouterModelForProvider("grok-build"),
|
|
373
|
-
useCodingConfig: false,
|
|
374
|
-
});
|
|
375
|
-
const auth = runtime.apiKey ? { apiKey: String(runtime.apiKey).trim() } : { headers: {} };
|
|
376
|
-
return {
|
|
377
|
-
provider: "grok-build",
|
|
378
|
-
transport: "openai-responses",
|
|
379
|
-
model: String(runtime.model || model || "").trim(),
|
|
380
|
-
baseUrl: String(runtime.baseUrl || "").trim(),
|
|
381
|
-
credential: null,
|
|
382
|
-
auth,
|
|
383
|
-
credentialSource: runtime.apiKey ? "runtime-api-key" : "",
|
|
384
|
-
};
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
const runtime = resolveRuntimeConfig({
|
|
388
|
-
workspaceRoot: projectRoot,
|
|
389
|
-
provider: normalizedProvider === "ucode" ? "" : normalizedProvider,
|
|
390
|
-
model: model || resolveConfiguredModelForProvider(config, normalizedProvider) || defaultAgentModelForProvider(config.agentProvider),
|
|
391
|
-
useCodingConfig: normalizedProvider === "ucode",
|
|
392
|
-
});
|
|
393
|
-
let credential = null;
|
|
394
|
-
if (runtime.provider === "kimi" && runtime.apiKeySource === "kimi-credential") {
|
|
395
|
-
credential = await resolveKimiUpstreamCredentials({ env, fetchImpl });
|
|
396
|
-
runtime.apiKey = credential.accessToken;
|
|
397
|
-
}
|
|
398
|
-
const auth = runtime.apiKey ? { apiKey: String(runtime.apiKey || "").trim() } : { headers: {} };
|
|
399
|
-
return {
|
|
400
|
-
provider: String(runtime.provider || normalizedProvider || "ucode"),
|
|
401
|
-
transport: String(runtime.transport || "openai-chat"),
|
|
402
|
-
model: String(runtime.model || "").trim(),
|
|
403
|
-
baseUrl: String(runtime.baseUrl || "").trim(),
|
|
404
|
-
credential,
|
|
405
|
-
auth,
|
|
406
|
-
credentialSource: runtime.apiKey ? "runtime-api-key" : "",
|
|
407
|
-
};
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
async function sendUpstreamRequest({
|
|
411
|
-
runtime,
|
|
412
|
-
request,
|
|
413
|
-
sessionId = "",
|
|
414
|
-
timeoutMs = 120000,
|
|
415
|
-
fetchImpl = global.fetch,
|
|
416
|
-
} = {}) {
|
|
417
|
-
if (typeof fetchImpl !== "function") {
|
|
418
|
-
return { ok: false, error: "fetch is unavailable" };
|
|
419
|
-
}
|
|
420
|
-
const resolvedRuntime = runtime && typeof runtime === "object" ? runtime : {};
|
|
421
|
-
const rawRequestModel = String((request && request.model) || resolvedRuntime.model || "").trim();
|
|
422
|
-
const isKimi = normalizeProvider(resolvedRuntime.provider) === "kimi";
|
|
423
|
-
const requestModel = isKimi ? normalizeKimiUpstreamModel(rawRequestModel) : rawRequestModel;
|
|
424
|
-
if (!requestModel) {
|
|
425
|
-
return { ok: false, error: `${resolvedRuntime.provider || "provider"} model is not configured` };
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
const isAnthropic = resolvedRuntime.transport === "anthropic-messages";
|
|
429
|
-
const isCodexResponses = resolvedRuntime.transport === "codex-responses";
|
|
430
|
-
const isResponses = isCodexResponses || resolvedRuntime.transport === "openai-responses";
|
|
431
|
-
const url = isAnthropic
|
|
432
|
-
? resolveAnthropicMessagesUrl(resolvedRuntime.baseUrl)
|
|
433
|
-
: isResponses
|
|
434
|
-
? resolveResponsesUrl(resolvedRuntime.baseUrl)
|
|
435
|
-
: resolveCompletionUrl(resolvedRuntime.baseUrl);
|
|
436
|
-
|
|
437
|
-
if (!url) {
|
|
438
|
-
return { ok: false, error: `${resolvedRuntime.provider || "provider"} baseUrl is not configured` };
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
const headers = { "content-type": "application/json" };
|
|
442
|
-
if (resolvedRuntime.auth && resolvedRuntime.auth.headers && typeof resolvedRuntime.auth.headers === "object") {
|
|
443
|
-
Object.assign(headers, resolvedRuntime.auth.headers);
|
|
444
|
-
}
|
|
445
|
-
if (isAnthropic) {
|
|
446
|
-
headers["anthropic-version"] = "2023-06-01";
|
|
447
|
-
if (resolvedRuntime.auth && resolvedRuntime.auth.apiKey) headers["x-api-key"] = resolvedRuntime.auth.apiKey;
|
|
448
|
-
} else if (isResponses) {
|
|
449
|
-
headers.Accept = "text/event-stream";
|
|
450
|
-
headers.Connection = "Keep-Alive";
|
|
451
|
-
if (resolvedRuntime.auth && resolvedRuntime.auth.apiKey) {
|
|
452
|
-
headers.authorization = `Bearer ${resolvedRuntime.auth.apiKey}`;
|
|
453
|
-
}
|
|
454
|
-
const resolvedSessionId = String(
|
|
455
|
-
sessionId
|
|
456
|
-
|| (request && (request.sessionId || request.session_id))
|
|
457
|
-
|| resolvedRuntime.sessionId
|
|
458
|
-
|| ""
|
|
459
|
-
).trim() || randomUUID();
|
|
460
|
-
if (isCodexResponses) {
|
|
461
|
-
headers["User-Agent"] = CODEX_DEFAULT_USER_AGENT;
|
|
462
|
-
headers.Originator = CODEX_DEFAULT_ORIGINATOR;
|
|
463
|
-
if (resolvedRuntime.credential && resolvedRuntime.credential.accountId) {
|
|
464
|
-
headers["Chatgpt-Account-Id"] = String(resolvedRuntime.credential.accountId);
|
|
465
|
-
}
|
|
466
|
-
headers["Session-Id"] = resolvedSessionId;
|
|
467
|
-
} else {
|
|
468
|
-
applyGrokResponsesHeaders(headers, {
|
|
469
|
-
provider: resolvedRuntime.provider,
|
|
470
|
-
baseUrl: resolvedRuntime.baseUrl,
|
|
471
|
-
sessionId: resolvedSessionId,
|
|
472
|
-
});
|
|
473
|
-
}
|
|
474
|
-
} else {
|
|
475
|
-
if (isKimi) {
|
|
476
|
-
applyKimiHeaders(headers, {
|
|
477
|
-
apiKey: resolvedRuntime.auth && resolvedRuntime.auth.apiKey,
|
|
478
|
-
stream: Boolean(request && request.stream),
|
|
479
|
-
});
|
|
480
|
-
} else if (resolvedRuntime.auth && resolvedRuntime.auth.apiKey) {
|
|
481
|
-
headers.authorization = `Bearer ${resolvedRuntime.auth.apiKey}`;
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
const requestBody = request && typeof request === "object" ? { ...request } : {};
|
|
485
|
-
// The ChatGPT subscription Codex endpoint is Responses-shaped but does not
|
|
486
|
-
// accept the public Responses API's optional max_output_tokens field. Keep
|
|
487
|
-
// the limit for api.openai.com/API-key traffic and omit it only for the
|
|
488
|
-
// OAuth-backed Codex subscription profile.
|
|
489
|
-
if (isCodexResponses && resolvedRuntime.requestProfile === "codex-subscription") {
|
|
490
|
-
delete requestBody.max_output_tokens;
|
|
491
|
-
}
|
|
492
|
-
if (isKimi) requestBody.model = requestModel;
|
|
493
|
-
const body = JSON.stringify(requestBody);
|
|
494
|
-
|
|
495
|
-
const controller = new AbortController();
|
|
496
|
-
const timer = setTimeout(() => {
|
|
497
|
-
try { controller.abort(); } catch {}
|
|
498
|
-
}, timeoutMs);
|
|
499
|
-
|
|
500
|
-
try {
|
|
501
|
-
const response = await fetchImpl(url, {
|
|
502
|
-
method: "POST",
|
|
503
|
-
headers,
|
|
504
|
-
body,
|
|
505
|
-
signal: controller.signal,
|
|
506
|
-
});
|
|
507
|
-
|
|
508
|
-
if (!response.ok) {
|
|
509
|
-
const errBody = await response.text().catch(() => "");
|
|
510
|
-
return {
|
|
511
|
-
ok: false,
|
|
512
|
-
error: `provider request failed (${response.status}): ${clipText(errBody)}`,
|
|
513
|
-
provider: resolvedRuntime.provider,
|
|
514
|
-
model: requestModel,
|
|
515
|
-
transport: resolvedRuntime.transport,
|
|
516
|
-
credentialSource: resolvedRuntime.credentialSource,
|
|
517
|
-
};
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
if (isResponses) {
|
|
521
|
-
// Responses supports both the normal streaming form and a complete JSON
|
|
522
|
-
// response. The provider contract is still Responses-only here; the
|
|
523
|
-
// JSON branch is useful for non-streaming gateways and test doubles.
|
|
524
|
-
let parsed;
|
|
525
|
-
let rawData = null;
|
|
526
|
-
if (typeof response.text === "function") {
|
|
527
|
-
const raw = await response.text();
|
|
528
|
-
parsed = parseCodexSsePayload(raw);
|
|
529
|
-
if (!parsed.response && !parsed.text && parsed.toolCalls.length === 0) {
|
|
530
|
-
try {
|
|
531
|
-
rawData = JSON.parse(raw);
|
|
532
|
-
parsed = parseResponsesEvents([
|
|
533
|
-
{ event: rawData && rawData.type ? rawData.type : "response", data: rawData },
|
|
534
|
-
], { assumeCompleted: true });
|
|
535
|
-
} catch {
|
|
536
|
-
// Keep the SSE parse result; the caller will receive an empty
|
|
537
|
-
// completed response rather than falling back to Chat Completions.
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
} else if (typeof response.json === "function") {
|
|
541
|
-
rawData = await response.json();
|
|
542
|
-
parsed = parseResponsesEvents([
|
|
543
|
-
{ event: rawData && rawData.type ? rawData.type : "response", data: rawData },
|
|
544
|
-
], { assumeCompleted: true });
|
|
545
|
-
} else {
|
|
546
|
-
parsed = parseResponsesEvents([], { assumeCompleted: true });
|
|
547
|
-
}
|
|
548
|
-
return {
|
|
549
|
-
ok: true,
|
|
550
|
-
output: parsed.text,
|
|
551
|
-
provider: String(resolvedRuntime.provider || ""),
|
|
552
|
-
model: requestModel,
|
|
553
|
-
transport: resolvedRuntime.transport,
|
|
554
|
-
credentialSource: resolvedRuntime.credentialSource,
|
|
555
|
-
data: parsed.response || rawData,
|
|
556
|
-
usage: resolveUpstreamResponsesUsage(parsed),
|
|
557
|
-
toolCalls: parsed.toolCalls,
|
|
558
|
-
incompleteDetails: parsed.incompleteDetails,
|
|
559
|
-
};
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
const data = await response.json();
|
|
563
|
-
let text = "";
|
|
564
|
-
if (isAnthropic) {
|
|
565
|
-
const content = Array.isArray(data.content) ? data.content : [];
|
|
566
|
-
text = content
|
|
567
|
-
.filter((item) => item && item.type === "text")
|
|
568
|
-
.map((item) => String(item.text || ""))
|
|
569
|
-
.join("");
|
|
570
|
-
} else {
|
|
571
|
-
const choice = data.choices && data.choices[0];
|
|
572
|
-
text = choice && choice.message && typeof choice.message.content === "string"
|
|
573
|
-
? choice.message.content
|
|
574
|
-
: "";
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
return {
|
|
578
|
-
ok: true,
|
|
579
|
-
output: text.trim(),
|
|
580
|
-
provider: String(resolvedRuntime.provider || ""),
|
|
581
|
-
model: requestModel,
|
|
582
|
-
transport: resolvedRuntime.transport,
|
|
583
|
-
credentialSource: resolvedRuntime.credentialSource,
|
|
584
|
-
data,
|
|
585
|
-
usage: data && typeof data === "object" && data.usage && typeof data.usage === "object"
|
|
586
|
-
? data.usage
|
|
587
|
-
: null,
|
|
588
|
-
};
|
|
589
|
-
} catch (err) {
|
|
590
|
-
const message = err && err.message ? err.message : "upstream request failed";
|
|
591
|
-
return {
|
|
592
|
-
ok: false,
|
|
593
|
-
error: message,
|
|
594
|
-
provider: resolvedRuntime.provider,
|
|
595
|
-
model: requestModel,
|
|
596
|
-
transport: resolvedRuntime.transport,
|
|
597
|
-
credentialSource: resolvedRuntime.credentialSource,
|
|
598
|
-
};
|
|
599
|
-
} finally {
|
|
600
|
-
clearTimeout(timer);
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
async function sendUpstreamPrompt({
|
|
605
|
-
projectRoot,
|
|
606
|
-
prompt,
|
|
607
|
-
systemPrompt,
|
|
608
|
-
provider = "",
|
|
609
|
-
model = "",
|
|
610
|
-
messages = [],
|
|
611
|
-
tools = [],
|
|
612
|
-
maxTokens = 4096,
|
|
613
|
-
temperature = 0,
|
|
614
|
-
sessionId = "",
|
|
615
|
-
timeoutMs = 120000,
|
|
616
|
-
fetchImpl = global.fetch,
|
|
617
|
-
env = process.env,
|
|
618
|
-
loadConfigImpl = loadConfig,
|
|
619
|
-
} = {}) {
|
|
620
|
-
let runtime;
|
|
621
|
-
try {
|
|
622
|
-
runtime = await resolveUpstreamRuntime({
|
|
623
|
-
projectRoot,
|
|
624
|
-
provider,
|
|
625
|
-
model,
|
|
626
|
-
env,
|
|
627
|
-
fetchImpl,
|
|
628
|
-
loadConfigImpl,
|
|
629
|
-
});
|
|
630
|
-
} catch (err) {
|
|
631
|
-
return {
|
|
632
|
-
ok: false,
|
|
633
|
-
error: err && err.message ? err.message : "upstream runtime resolution failed",
|
|
634
|
-
errorCode: err && err.code ? err.code : "UPSTREAM_RUNTIME_RESOLUTION_FAILED",
|
|
635
|
-
provider: normalizeProvider(provider),
|
|
636
|
-
model: String(model || "").trim(),
|
|
637
|
-
};
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
const requestModel = String(runtime.model || "").trim();
|
|
641
|
-
const request = runtime.transport === "anthropic-messages"
|
|
642
|
-
? buildAnthropicMessagesRequest({
|
|
643
|
-
model: requestModel,
|
|
644
|
-
systemPrompt,
|
|
645
|
-
prompt,
|
|
646
|
-
messages,
|
|
647
|
-
tools,
|
|
648
|
-
maxTokens,
|
|
649
|
-
temperature,
|
|
650
|
-
})
|
|
651
|
-
: runtime.transport === "codex-responses"
|
|
652
|
-
? buildCodexResponsesRequest({
|
|
653
|
-
model: requestModel,
|
|
654
|
-
systemPrompt,
|
|
655
|
-
prompt,
|
|
656
|
-
messages,
|
|
657
|
-
tools,
|
|
658
|
-
maxTokens,
|
|
659
|
-
})
|
|
660
|
-
: runtime.transport === "openai-responses"
|
|
661
|
-
? buildCodexResponsesRequest({
|
|
662
|
-
model: requestModel,
|
|
663
|
-
systemPrompt,
|
|
664
|
-
prompt,
|
|
665
|
-
messages,
|
|
666
|
-
tools,
|
|
667
|
-
maxTokens,
|
|
668
|
-
})
|
|
669
|
-
: buildOpenAiChatRequest({
|
|
670
|
-
model: requestModel,
|
|
671
|
-
systemPrompt,
|
|
672
|
-
prompt,
|
|
673
|
-
messages,
|
|
674
|
-
tools,
|
|
675
|
-
temperature,
|
|
676
|
-
});
|
|
677
|
-
|
|
678
|
-
return sendUpstreamRequest({
|
|
679
|
-
runtime,
|
|
680
|
-
request,
|
|
681
|
-
sessionId,
|
|
682
|
-
timeoutMs,
|
|
683
|
-
fetchImpl,
|
|
684
|
-
});
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
module.exports = {
|
|
688
|
-
buildAnthropicMessagesRequest,
|
|
689
|
-
buildCodexResponsesRequest,
|
|
690
|
-
buildOpenAiChatRequest,
|
|
691
|
-
normalizeProvider,
|
|
692
|
-
normalizeKimiUpstreamModel,
|
|
693
|
-
parseCodexSsePayload,
|
|
694
|
-
resolveCodexResponseOutput,
|
|
695
|
-
resolveUpstreamRuntime,
|
|
696
|
-
sendUpstreamRequest,
|
|
697
|
-
sendUpstreamPrompt,
|
|
698
|
-
};
|