u-foo 3.0.29 → 3.0.31
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/README.md +13 -8
- package/bin/ufoo.js +7 -2
- package/bin/ugrok.js +68 -0
- 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 +2 -1
- package/src/agents/activity/activityDetector.js +95 -0
- package/src/agents/controller/ufooAgent.js +3 -3
- package/src/agents/launch/launcher.js +17 -11
- package/src/agents/launch/ptyRunner.js +34 -12
- package/src/agents/launch/readyDetector.js +27 -0
- package/src/agents/prompts/defaultBootstrap.js +126 -1
- package/src/agents/providers/directAuthStatus.js +79 -0
- package/src/agents/providers/upstreamTransport.js +234 -85
- package/src/app/chat/commandExecutor.js +18 -10
- package/src/app/chat/commands.js +4 -2
- package/src/app/cli/run.js +7 -5
- package/src/code/UcodeController.js +201 -40
- package/src/code/agent.js +9 -2
- package/src/code/commands.js +13 -0
- package/src/code/dispatch.js +9 -1
- package/src/code/index.js +9 -2
- package/src/code/nativeRunner.js +398 -16
- package/src/code/providers/index.js +1 -0
- package/src/code/providers/modelsCatalog.js +21 -6
- package/src/code/providers/openaiResponsesTransport.js +119 -0
- package/src/code/providers/responsesProtocol.js +499 -0
- package/src/code/providers/transportContract.js +5 -1
- package/src/code/repl.js +95 -2
- package/src/code/tools/bash.js +159 -6
- package/src/code/ucodeSlashDispatch.js +13 -0
- package/src/config.js +6 -0
- package/src/coordination/bus/inject.js +2 -2
- package/src/coordination/bus/utils.js +4 -1
- package/src/orchestration/controller/gateRouter.js +2 -2
- package/src/orchestration/controller/launchRouting.js +2 -1
- package/src/orchestration/groups/validateTemplate.js +1 -1
- package/src/orchestration/solo/commands.js +1 -0
- package/src/runtime/daemon/index.js +12 -4
- package/src/runtime/daemon/nicknameScope.js +4 -1
- package/src/runtime/daemon/ops.js +8 -2
- package/src/ui/rustUcodeHost.js +86 -10
package/src/code/nativeRunner.js
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
+
const os = require("os");
|
|
1
2
|
const { randomUUID } = require("crypto");
|
|
2
3
|
const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../config");
|
|
3
4
|
const {
|
|
4
5
|
readKimiAccessToken,
|
|
5
6
|
resolveKimiUpstreamCredentials,
|
|
6
7
|
} = require("../agents/providers/credentials/kimi");
|
|
7
|
-
const {
|
|
8
|
+
const { resolveCodexUpstreamCredentials } = require("../agents/providers/credentials/codex");
|
|
9
|
+
const dispatchTools = require("./dispatch");
|
|
10
|
+
const runToolCall = dispatchTools.runToolCall;
|
|
11
|
+
const runToolCallAsync = typeof dispatchTools.runToolCallAsync === "function"
|
|
12
|
+
? dispatchTools.runToolCallAsync
|
|
13
|
+
: async (...args) => runToolCall(...args);
|
|
8
14
|
const { runTaskRunTool } = require("./tools/taskRun");
|
|
9
15
|
const { appendUsageRecord } = require("./usageStore");
|
|
10
16
|
const {
|
|
@@ -66,6 +72,13 @@ const { getReadImageToolDescription } = require("../agents/prompts/native/toolDe
|
|
|
66
72
|
const { getWriteToolDescription } = require("../agents/prompts/native/toolDescriptions/write");
|
|
67
73
|
const { getEditToolDescription } = require("../agents/prompts/native/toolDescriptions/edit");
|
|
68
74
|
const { getBashToolDescription } = require("../agents/prompts/native/toolDescriptions/bash");
|
|
75
|
+
const {
|
|
76
|
+
buildResponsesPayload,
|
|
77
|
+
isResponsesKeepalive,
|
|
78
|
+
responseEventDelta,
|
|
79
|
+
parseResponsesEvents,
|
|
80
|
+
parseResponsesSsePayload,
|
|
81
|
+
} = require("./providers/responsesProtocol");
|
|
69
82
|
|
|
70
83
|
const CORE_TOOL_NAMES = new Set([
|
|
71
84
|
"read",
|
|
@@ -90,6 +103,10 @@ const CONTROL_PLANE_TOOLS = new Set(["plan_graph", "task_run"]);
|
|
|
90
103
|
const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
|
|
91
104
|
const DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1";
|
|
92
105
|
const DEFAULT_KIMI_BASE_URL = "https://api.kimi.com/coding/v1";
|
|
106
|
+
const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
107
|
+
const DEFAULT_XAI_BASE_URL = "https://api.x.ai/v1";
|
|
108
|
+
const DEFAULT_GROK_BUILD_BASE_URL = DEFAULT_XAI_BASE_URL;
|
|
109
|
+
const DEFAULT_GROK_BUILD_MODEL = "grok-4.6";
|
|
93
110
|
const DEFAULT_KIMI_MODEL = "k3";
|
|
94
111
|
// Claude Code SDK defaults to no turn limit; built-in agents cap at 30 (DreamTask)
|
|
95
112
|
// to 200 (fork). We count individual tool calls (not turns), so 100 leaves headroom
|
|
@@ -292,19 +309,42 @@ function clipText(value = "", maxChars = 6000) {
|
|
|
292
309
|
function normalizeProvider(value = "") {
|
|
293
310
|
const text = String(value || "").trim().toLowerCase();
|
|
294
311
|
if (!text) return "";
|
|
295
|
-
if (text === "codex" || text === "codex-cli" || text === "codex-code") return "
|
|
312
|
+
if (text === "codex" || text === "codex-cli" || text === "codex-code") return "codex";
|
|
296
313
|
if (text === "claude" || text === "claude-cli" || text === "claude-code") return "anthropic";
|
|
297
314
|
if (text === "kimi" || text === "kimi-code" || text === "moonshot") return "kimi";
|
|
315
|
+
if (text === "grok" || text === "grok-build" || text === "grok-shell" || text === "grok-api") return "grok-build";
|
|
316
|
+
if (text === "xai") return "xai";
|
|
298
317
|
if (text === "openai" || text === "anthropic") return text;
|
|
299
318
|
return text;
|
|
300
319
|
}
|
|
301
320
|
|
|
321
|
+
function normalizeKimiModel(value = "") {
|
|
322
|
+
const raw = String(value || "").trim();
|
|
323
|
+
if (!raw) return "";
|
|
324
|
+
const suffix = raw.match(/^(.*?)(\([^)]*\))$/);
|
|
325
|
+
const base = String(suffix ? suffix[1] : raw).trim().replace(/\[1m\]$/i, "");
|
|
326
|
+
const lower = base.toLowerCase();
|
|
327
|
+
let normalized = lower;
|
|
328
|
+
if (["kimi-k2.7-code", "k2.7-code", "kimi-for-coding", "for-coding"].includes(lower)) {
|
|
329
|
+
normalized = "kimi-for-coding";
|
|
330
|
+
} else if (["kimi-k2.7-code-highspeed", "k2.7-code-highspeed", "kimi-for-coding-highspeed", "for-coding-highspeed"].includes(lower)) {
|
|
331
|
+
normalized = "kimi-for-coding-highspeed";
|
|
332
|
+
} else if (normalized.startsWith("kimi-")) {
|
|
333
|
+
normalized = normalized.slice("kimi-".length);
|
|
334
|
+
}
|
|
335
|
+
return `${normalized}${suffix ? suffix[2] : ""}`;
|
|
336
|
+
}
|
|
337
|
+
|
|
302
338
|
function resolveTransport({ provider = "", baseUrl = "" } = {}) {
|
|
303
339
|
const normalizedProvider = normalizeProvider(provider);
|
|
304
340
|
const url = String(baseUrl || "").trim().toLowerCase();
|
|
305
341
|
|
|
342
|
+
if (normalizedProvider === "codex" || normalizedProvider === "grok-build" || normalizedProvider === "xai") {
|
|
343
|
+
return "openai-responses";
|
|
344
|
+
}
|
|
306
345
|
if (normalizedProvider === "anthropic") return "anthropic-messages";
|
|
307
346
|
if (normalizedProvider === "kimi") return "openai-chat";
|
|
347
|
+
if (/\/responses(?:$|[/?#])/.test(url)) return "openai-responses";
|
|
308
348
|
if (url.includes("anthropic.com")) return "anthropic-messages";
|
|
309
349
|
if (/\/messages(?:$|[/?#])/.test(url) && !/\/chat\/completions(?:$|[/?#])/.test(url)) {
|
|
310
350
|
return "anthropic-messages";
|
|
@@ -330,16 +370,28 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
|
|
|
330
370
|
model
|
|
331
371
|
|| process.env.UFOO_UCODE_MODEL
|
|
332
372
|
|| configuredModel
|
|
333
|
-
|| (selectedProvider === "kimi"
|
|
373
|
+
|| (selectedProvider === "kimi"
|
|
374
|
+
? DEFAULT_KIMI_MODEL
|
|
375
|
+
: (selectedProvider === "grok-build" ? DEFAULT_GROK_BUILD_MODEL : defaultAgentModelForProvider(selectedProvider)))
|
|
334
376
|
).trim();
|
|
335
377
|
|
|
336
378
|
const defaultBaseUrl = selectedProvider === "anthropic"
|
|
337
379
|
? String(process.env.ANTHROPIC_BASE_URL || DEFAULT_ANTHROPIC_BASE_URL)
|
|
338
380
|
: selectedProvider === "kimi"
|
|
339
|
-
? DEFAULT_KIMI_BASE_URL
|
|
340
|
-
:
|
|
341
|
-
|
|
342
|
-
|
|
381
|
+
? String(process.env.KIMI_BASE_URL || DEFAULT_KIMI_BASE_URL)
|
|
382
|
+
: selectedProvider === "codex"
|
|
383
|
+
? String(process.env.UFOO_CODEX_BASE_URL || DEFAULT_CODEX_BASE_URL)
|
|
384
|
+
: selectedProvider === "grok-build"
|
|
385
|
+
? String(
|
|
386
|
+
process.env.UFOO_GROK_BUILD_BASE_URL
|
|
387
|
+
|| process.env.GROK_BUILD_BASE_URL
|
|
388
|
+
|| DEFAULT_GROK_BUILD_BASE_URL
|
|
389
|
+
)
|
|
390
|
+
: selectedProvider === "xai"
|
|
391
|
+
? String(process.env.XAI_BASE_URL || DEFAULT_XAI_BASE_URL)
|
|
392
|
+
: String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL);
|
|
393
|
+
|
|
394
|
+
let baseUrl = String(
|
|
343
395
|
process.env.UFOO_UCODE_BASE_URL
|
|
344
396
|
|| config.ucodeBaseUrl
|
|
345
397
|
|| defaultBaseUrl
|
|
@@ -365,11 +417,26 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
|
|
|
365
417
|
apiKey = String(
|
|
366
418
|
(selectedProvider === "openai" ? process.env.OPENAI_API_KEY : "")
|
|
367
419
|
|| (selectedProvider === "anthropic" ? process.env.ANTHROPIC_API_KEY : "")
|
|
420
|
+
|| (selectedProvider === "codex" ? process.env.OPENAI_API_KEY : "")
|
|
421
|
+
|| (selectedProvider === "grok-build" ? (process.env.GROK_BUILD_API_KEY || process.env.XAI_API_KEY) : "")
|
|
422
|
+
|| (selectedProvider === "xai" ? process.env.XAI_API_KEY : "")
|
|
368
423
|
|| ""
|
|
369
424
|
).trim();
|
|
370
425
|
if (apiKey) apiKeySource = "env";
|
|
371
426
|
}
|
|
372
427
|
|
|
428
|
+
// ChatGPT's Codex backend accepts Codex OAuth credentials, while standard
|
|
429
|
+
// OpenAI API keys belong on the public OpenAI API. Generic ucode base URL
|
|
430
|
+
// overrides remain authoritative for an explicitly configured gateway.
|
|
431
|
+
if (
|
|
432
|
+
selectedProvider === "codex"
|
|
433
|
+
&& apiKey
|
|
434
|
+
&& !String(process.env.UFOO_UCODE_BASE_URL || "").trim()
|
|
435
|
+
&& !String(config.ucodeBaseUrl || "").trim()
|
|
436
|
+
) {
|
|
437
|
+
baseUrl = String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL).trim();
|
|
438
|
+
}
|
|
439
|
+
|
|
373
440
|
return {
|
|
374
441
|
provider: selectedProvider,
|
|
375
442
|
model: selectedModel,
|
|
@@ -391,6 +458,16 @@ function resolveCompletionUrl(baseUrl = "") {
|
|
|
391
458
|
return `${normalized}/chat/completions`;
|
|
392
459
|
}
|
|
393
460
|
|
|
461
|
+
function resolveResponsesUrl(baseUrl = "") {
|
|
462
|
+
const raw = String(baseUrl || "").trim();
|
|
463
|
+
if (!raw) return "";
|
|
464
|
+
const normalized = raw.replace(/\/+$/, "");
|
|
465
|
+
if (/\/responses$/i.test(normalized)) return normalized;
|
|
466
|
+
if (/\/v1$/i.test(normalized)) return `${normalized}/responses`;
|
|
467
|
+
if (/\/api$/i.test(normalized)) return `${normalized}/v1/responses`;
|
|
468
|
+
return `${normalized}/responses`;
|
|
469
|
+
}
|
|
470
|
+
|
|
394
471
|
function resolveAnthropicMessagesUrl(baseUrl = "") {
|
|
395
472
|
const raw = String(baseUrl || "").trim() || DEFAULT_ANTHROPIC_BASE_URL;
|
|
396
473
|
const normalized = raw.replace(/\/+$/, "");
|
|
@@ -1022,6 +1099,88 @@ function runCoreTool({
|
|
|
1022
1099
|
return result;
|
|
1023
1100
|
}
|
|
1024
1101
|
|
|
1102
|
+
/**
|
|
1103
|
+
* Async companion for the native loop. Control-plane tools intentionally keep
|
|
1104
|
+
* their synchronous scheduler for now; data-plane tools use the async
|
|
1105
|
+
* dispatcher so bash can terminate on the caller's AbortSignal.
|
|
1106
|
+
*/
|
|
1107
|
+
async function runCoreToolAsync(options = {}) {
|
|
1108
|
+
const normalizedTool = normalizeToolName(options.tool);
|
|
1109
|
+
if (!normalizedTool || CONTROL_PLANE_TOOLS.has(normalizedTool) || normalizedTool === "ask_user") {
|
|
1110
|
+
return runCoreTool(options);
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
const {
|
|
1114
|
+
args = {},
|
|
1115
|
+
workspaceRoot = process.cwd(),
|
|
1116
|
+
onToolEvent = null,
|
|
1117
|
+
sessionId = "",
|
|
1118
|
+
onArtifactPersisted = null,
|
|
1119
|
+
origin = null,
|
|
1120
|
+
signal = null,
|
|
1121
|
+
} = options;
|
|
1122
|
+
const safeArgs = args && typeof args === "object" ? { ...args } : {};
|
|
1123
|
+
if (normalizedTool === "artifact_read" && sessionId && !safeArgs.sessionId) {
|
|
1124
|
+
safeArgs.sessionId = sessionId;
|
|
1125
|
+
}
|
|
1126
|
+
emitToolEvent(onToolEvent, {
|
|
1127
|
+
tool: normalizedTool,
|
|
1128
|
+
phase: "start",
|
|
1129
|
+
args: safeArgs,
|
|
1130
|
+
error: "",
|
|
1131
|
+
origin,
|
|
1132
|
+
});
|
|
1133
|
+
|
|
1134
|
+
const toolOptions = {
|
|
1135
|
+
workspaceRoot,
|
|
1136
|
+
cwd: workspaceRoot,
|
|
1137
|
+
};
|
|
1138
|
+
if (signal) toolOptions.signal = signal;
|
|
1139
|
+
if (normalizedTool === "artifact_read" && sessionId) {
|
|
1140
|
+
toolOptions.sessionId = sessionId;
|
|
1141
|
+
}
|
|
1142
|
+
const result = await runToolCallAsync(
|
|
1143
|
+
{ tool: normalizedTool, args: safeArgs },
|
|
1144
|
+
toolOptions,
|
|
1145
|
+
);
|
|
1146
|
+
|
|
1147
|
+
if (!result || result.ok === false) {
|
|
1148
|
+
emitToolEvent(onToolEvent, {
|
|
1149
|
+
tool: normalizedTool,
|
|
1150
|
+
phase: "error",
|
|
1151
|
+
args: safeArgs,
|
|
1152
|
+
error: String((result && result.error) || `${normalizedTool} failed`),
|
|
1153
|
+
origin,
|
|
1154
|
+
});
|
|
1155
|
+
return result;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
if (normalizedTool !== "artifact_read" && EXECUTABLE_GRAPH_TOOLS.has(normalizedTool)) {
|
|
1159
|
+
const persisted = persistToolResultToContext({
|
|
1160
|
+
workspaceRoot,
|
|
1161
|
+
sessionId,
|
|
1162
|
+
tool: normalizedTool,
|
|
1163
|
+
args: safeArgs,
|
|
1164
|
+
rawResult: result,
|
|
1165
|
+
});
|
|
1166
|
+
if (typeof onArtifactPersisted === "function") {
|
|
1167
|
+
try {
|
|
1168
|
+
onArtifactPersisted(persisted);
|
|
1169
|
+
} catch {
|
|
1170
|
+
// ignore
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
const payload = persisted.modelPayload || result;
|
|
1174
|
+
if (origin) payload.origin = origin;
|
|
1175
|
+
return payload;
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
if (origin && result && typeof result === "object") {
|
|
1179
|
+
return { ...result, origin };
|
|
1180
|
+
}
|
|
1181
|
+
return result;
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1025
1184
|
function emitPhase(callback, event = {}) {
|
|
1026
1185
|
if (typeof callback !== "function") return;
|
|
1027
1186
|
try {
|
|
@@ -1134,8 +1293,9 @@ async function runOpenAiLikeTurn({
|
|
|
1134
1293
|
signal = null,
|
|
1135
1294
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
1136
1295
|
} = {}) {
|
|
1296
|
+
const normalizedProvider = normalizeProvider(provider);
|
|
1137
1297
|
const payload = {
|
|
1138
|
-
model,
|
|
1298
|
+
model: normalizedProvider === "kimi" ? normalizeKimiModel(model) : model,
|
|
1139
1299
|
max_tokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
|
|
1140
1300
|
messages,
|
|
1141
1301
|
tools: buildCoreToolSpecs(),
|
|
@@ -1144,7 +1304,7 @@ async function runOpenAiLikeTurn({
|
|
|
1144
1304
|
// Ask for the terminal usage chunk so token/cache accounting works.
|
|
1145
1305
|
stream_options: { include_usage: true },
|
|
1146
1306
|
// Kimi k3 rejects any temperature other than 1.
|
|
1147
|
-
temperature:
|
|
1307
|
+
temperature: normalizedProvider === "kimi" ? 1 : 0,
|
|
1148
1308
|
};
|
|
1149
1309
|
const reasoningEffort = resolveReasoningEffort();
|
|
1150
1310
|
if (reasoningEffort) {
|
|
@@ -1153,12 +1313,9 @@ async function runOpenAiLikeTurn({
|
|
|
1153
1313
|
payload.reasoning_effort = reasoningEffort;
|
|
1154
1314
|
}
|
|
1155
1315
|
|
|
1156
|
-
const headers =
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
if (apiKey) {
|
|
1160
|
-
headers.authorization = `Bearer ${apiKey}`;
|
|
1161
|
-
}
|
|
1316
|
+
const headers = normalizedProvider === "kimi"
|
|
1317
|
+
? buildKimiHeaders({ apiKey, stream: true })
|
|
1318
|
+
: { "content-type": "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) };
|
|
1162
1319
|
|
|
1163
1320
|
const toolCallMap = new Map();
|
|
1164
1321
|
const announcedToolNames = new Set();
|
|
@@ -1296,6 +1453,180 @@ async function runOpenAiLikeTurn({
|
|
|
1296
1453
|
});
|
|
1297
1454
|
}
|
|
1298
1455
|
|
|
1456
|
+
function currentGrokClientVersion() {
|
|
1457
|
+
return String(process.env.UFOO_GROK_CLIENT_VERSION || "0.2.120").trim() || "0.2.120";
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
function isGrokCliProxyUrl(url = "") {
|
|
1461
|
+
try {
|
|
1462
|
+
return new URL(String(url || "")).hostname.toLowerCase() === "cli-chat-proxy.grok.com";
|
|
1463
|
+
} catch {
|
|
1464
|
+
return false;
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
function currentKimiClientVersion() {
|
|
1469
|
+
try {
|
|
1470
|
+
return String(process.env.UFOO_KIMI_CLIENT_VERSION || require("../../package.json").version || "dev").trim() || "dev";
|
|
1471
|
+
} catch {
|
|
1472
|
+
return "dev";
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
function buildKimiHeaders({ apiKey = "", stream = true } = {}) {
|
|
1477
|
+
const version = currentKimiClientVersion();
|
|
1478
|
+
const headers = {
|
|
1479
|
+
"content-type": "application/json",
|
|
1480
|
+
"User-Agent": `ufoo/${version}`,
|
|
1481
|
+
"X-Msh-Platform": "ufoo",
|
|
1482
|
+
"X-Msh-Version": version,
|
|
1483
|
+
"X-Msh-Device-Name": os.hostname(),
|
|
1484
|
+
"X-Msh-Device-Model": `${process.platform} ${process.arch}`,
|
|
1485
|
+
"X-Msh-Device-Id": String(process.env.KIMI_DEVICE_ID || "ufoo-kimi-device").trim() || "ufoo-kimi-device",
|
|
1486
|
+
Accept: stream ? "text/event-stream" : "application/json",
|
|
1487
|
+
};
|
|
1488
|
+
if (apiKey) headers.authorization = `Bearer ${apiKey}`;
|
|
1489
|
+
return headers;
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
function buildResponsesHeaders({ provider = "", apiKey = "", sessionId = "", accountId = "", url = "" } = {}) {
|
|
1493
|
+
const normalizedProvider = normalizeProvider(provider);
|
|
1494
|
+
const headers = {
|
|
1495
|
+
"content-type": "application/json",
|
|
1496
|
+
Accept: "text/event-stream",
|
|
1497
|
+
Connection: "Keep-Alive",
|
|
1498
|
+
};
|
|
1499
|
+
if (apiKey) headers.authorization = `Bearer ${apiKey}`;
|
|
1500
|
+
|
|
1501
|
+
if (normalizedProvider === "codex") {
|
|
1502
|
+
headers["User-Agent"] = String(
|
|
1503
|
+
process.env.UFOO_CODEX_USER_AGENT
|
|
1504
|
+
|| "codex-tui/0.118.0 (Mac OS 26.3.1; arm64) iTerm.app/3.6.9 (codex-tui; 0.118.0)"
|
|
1505
|
+
);
|
|
1506
|
+
headers.Originator = "codex-tui";
|
|
1507
|
+
headers["Session-Id"] = String(sessionId || randomUUID());
|
|
1508
|
+
if (accountId) headers["Chatgpt-Account-Id"] = String(accountId);
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
if (normalizedProvider === "grok-build" || normalizedProvider === "xai") {
|
|
1512
|
+
const version = currentGrokClientVersion();
|
|
1513
|
+
if (sessionId) headers["x-grok-conv-id"] = String(sessionId);
|
|
1514
|
+
if (isGrokCliProxyUrl(url)) {
|
|
1515
|
+
headers["X-XAI-Token-Auth"] = "xai-grok-cli";
|
|
1516
|
+
headers["x-grok-client-version"] = version;
|
|
1517
|
+
headers["x-grok-client-identifier"] = "grok-shell";
|
|
1518
|
+
headers["x-authenticateresponse"] = "authenticate-response";
|
|
1519
|
+
headers["User-Agent"] = `xai-grok-workspace/${version}`;
|
|
1520
|
+
} else if (normalizedProvider === "grok-build") {
|
|
1521
|
+
// CLIProxyAPI selects the Grok Build route from this identity.
|
|
1522
|
+
headers["User-Agent"] = `grok-shell/${version}`;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
return headers;
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
async function runResponsesTurn({
|
|
1530
|
+
url = "",
|
|
1531
|
+
apiKey = "",
|
|
1532
|
+
model = "",
|
|
1533
|
+
provider = "",
|
|
1534
|
+
systemPrompt = "",
|
|
1535
|
+
messages = [],
|
|
1536
|
+
sessionId = "",
|
|
1537
|
+
accountId = "",
|
|
1538
|
+
onTextDelta = null,
|
|
1539
|
+
onThinkingDelta = null,
|
|
1540
|
+
onPhase = null,
|
|
1541
|
+
signal = null,
|
|
1542
|
+
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
1543
|
+
} = {}) {
|
|
1544
|
+
const payload = buildResponsesPayload({
|
|
1545
|
+
model,
|
|
1546
|
+
instructions: systemPrompt,
|
|
1547
|
+
messages,
|
|
1548
|
+
tools: buildCoreToolSpecs(),
|
|
1549
|
+
maxOutputTokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
|
|
1550
|
+
reasoningEffort: resolveReasoningEffort(),
|
|
1551
|
+
provider: normalizeProvider(provider),
|
|
1552
|
+
});
|
|
1553
|
+
const headers = buildResponsesHeaders({ provider, apiKey, sessionId, accountId, url });
|
|
1554
|
+
const frames = [];
|
|
1555
|
+
|
|
1556
|
+
const consumeFrame = (frame = {}) => {
|
|
1557
|
+
const data = frame && frame.data && typeof frame.data === "object"
|
|
1558
|
+
? frame.data
|
|
1559
|
+
: parseJsonSafe(frame && frame.data, null);
|
|
1560
|
+
if (!data || isResponsesKeepalive(frame && frame.event, data)) return;
|
|
1561
|
+
frames.push({ event: String(frame.event || data.type || ""), data });
|
|
1562
|
+
|
|
1563
|
+
const delta = responseEventDelta({ event: data.type || frame.event, data });
|
|
1564
|
+
if (delta.reasoning) {
|
|
1565
|
+
emitPhase(onPhase, { type: "thinking_delta", text: delta.reasoning });
|
|
1566
|
+
if (typeof onThinkingDelta === "function") onThinkingDelta(delta.reasoning);
|
|
1567
|
+
}
|
|
1568
|
+
if (delta.text) {
|
|
1569
|
+
emitPhase(onPhase, { type: "text_delta", text: delta.text });
|
|
1570
|
+
if (typeof onTextDelta === "function") onTextDelta(delta.text);
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
const item = data.item && typeof data.item === "object" ? data.item : null;
|
|
1574
|
+
if (
|
|
1575
|
+
item
|
|
1576
|
+
&& item.type === "function_call"
|
|
1577
|
+
&& item.name
|
|
1578
|
+
&& (data.type === "response.output_item.added" || data.type === "response.output_item.done")
|
|
1579
|
+
) {
|
|
1580
|
+
emitPhase(onPhase, { type: "tool_request", name: String(item.name) });
|
|
1581
|
+
}
|
|
1582
|
+
};
|
|
1583
|
+
|
|
1584
|
+
return runSseRequest({
|
|
1585
|
+
url,
|
|
1586
|
+
headers,
|
|
1587
|
+
payload,
|
|
1588
|
+
signal,
|
|
1589
|
+
timeoutMs,
|
|
1590
|
+
onPhase,
|
|
1591
|
+
onNonStream: (data) => {
|
|
1592
|
+
const parsed = parseResponsesEvents([{ event: data && data.type ? data.type : "response", data }], {
|
|
1593
|
+
assumeCompleted: true,
|
|
1594
|
+
});
|
|
1595
|
+
if (parsed.reasoning && typeof onThinkingDelta === "function") onThinkingDelta(parsed.reasoning);
|
|
1596
|
+
if (parsed.text && typeof onTextDelta === "function") onTextDelta(parsed.text);
|
|
1597
|
+
return {
|
|
1598
|
+
text: parsed.text,
|
|
1599
|
+
toolCalls: parsed.toolCalls,
|
|
1600
|
+
outputItems: parsed.outputItems,
|
|
1601
|
+
usage: parsed.usage,
|
|
1602
|
+
response: parsed.response,
|
|
1603
|
+
responseId: parsed.responseId,
|
|
1604
|
+
};
|
|
1605
|
+
},
|
|
1606
|
+
onEvent: consumeFrame,
|
|
1607
|
+
onTail: (rawBuffer) => {
|
|
1608
|
+
if (!String(rawBuffer || "").trim()) return;
|
|
1609
|
+
const tail = parseResponsesSsePayload(rawBuffer);
|
|
1610
|
+
for (const data of tail.events || []) consumeFrame({ event: data.type, data });
|
|
1611
|
+
},
|
|
1612
|
+
buildResult: () => {
|
|
1613
|
+
const parsed = parseResponsesEvents(frames);
|
|
1614
|
+
if (!parsed.terminal) {
|
|
1615
|
+
throw new Error("Responses stream ended before response.completed or response.incomplete");
|
|
1616
|
+
}
|
|
1617
|
+
return {
|
|
1618
|
+
text: parsed.text,
|
|
1619
|
+
toolCalls: parsed.toolCalls,
|
|
1620
|
+
outputItems: parsed.outputItems,
|
|
1621
|
+
usage: parsed.usage,
|
|
1622
|
+
response: parsed.response,
|
|
1623
|
+
responseId: parsed.responseId,
|
|
1624
|
+
incompleteDetails: parsed.incompleteDetails,
|
|
1625
|
+
};
|
|
1626
|
+
},
|
|
1627
|
+
});
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1299
1630
|
function normalizeAnthropicMessageContent(raw = []) {
|
|
1300
1631
|
if (!Array.isArray(raw)) return [];
|
|
1301
1632
|
return raw
|
|
@@ -1663,6 +1994,7 @@ async function runAnthropicTurn({
|
|
|
1663
1994
|
|
|
1664
1995
|
const {
|
|
1665
1996
|
createOpenAiChatTransport,
|
|
1997
|
+
createOpenAiResponsesTransport,
|
|
1666
1998
|
createAnthropicMessagesTransport,
|
|
1667
1999
|
} = require("./providers");
|
|
1668
2000
|
|
|
@@ -1676,6 +2008,14 @@ const TRANSPORTS = {
|
|
|
1676
2008
|
toJsonString,
|
|
1677
2009
|
clipText,
|
|
1678
2010
|
}),
|
|
2011
|
+
"openai-responses": createOpenAiResponsesTransport({
|
|
2012
|
+
resolveUrl: resolveResponsesUrl,
|
|
2013
|
+
runTurn: runResponsesTurn,
|
|
2014
|
+
normalizeToolName,
|
|
2015
|
+
normalizeToolCallArgs,
|
|
2016
|
+
toJsonString,
|
|
2017
|
+
clipText,
|
|
2018
|
+
}),
|
|
1679
2019
|
"anthropic-messages": createAnthropicMessagesTransport({
|
|
1680
2020
|
resolveUrl: resolveAnthropicMessagesUrl,
|
|
1681
2021
|
runTurn: runAnthropicTurn,
|
|
@@ -1743,6 +2083,7 @@ async function runNativeLoop({
|
|
|
1743
2083
|
baseUrl = "",
|
|
1744
2084
|
apiKey = "",
|
|
1745
2085
|
provider = "",
|
|
2086
|
+
accountId = "",
|
|
1746
2087
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
1747
2088
|
onStreamDelta = null,
|
|
1748
2089
|
onThinkingDelta = null,
|
|
@@ -1963,9 +2304,11 @@ async function runNativeLoop({
|
|
|
1963
2304
|
apiKey,
|
|
1964
2305
|
model: requestModel,
|
|
1965
2306
|
provider,
|
|
2307
|
+
accountId,
|
|
1966
2308
|
systemPrompt,
|
|
1967
2309
|
systemBlocks,
|
|
1968
2310
|
messages: providerMessages,
|
|
2311
|
+
sessionId,
|
|
1969
2312
|
signal,
|
|
1970
2313
|
timeoutMs,
|
|
1971
2314
|
onPhase,
|
|
@@ -2008,6 +2351,7 @@ async function runNativeLoop({
|
|
|
2008
2351
|
const sideEffects = parseStructuredSideEffects(text);
|
|
2009
2352
|
const planCommand = sideEffects ? normalizePlanGraphCommand(sideEffects) : null;
|
|
2010
2353
|
if (planCommand) {
|
|
2354
|
+
guards.ensureActive();
|
|
2011
2355
|
transport.appendFinalAssistantMessage({ messages: providerMessages, turnResult });
|
|
2012
2356
|
const planResult = runCoreTool({
|
|
2013
2357
|
tool: "plan_graph",
|
|
@@ -2019,6 +2363,7 @@ async function runNativeLoop({
|
|
|
2019
2363
|
executionState,
|
|
2020
2364
|
origin: { kind: "legacy_side_effect", source: planCommand.source || "legacy" },
|
|
2021
2365
|
});
|
|
2366
|
+
guards.ensureActive();
|
|
2022
2367
|
if (planResult && planResult.executionState) {
|
|
2023
2368
|
executionState = planResult.executionState;
|
|
2024
2369
|
}
|
|
@@ -2197,7 +2542,8 @@ async function runNativeLoop({
|
|
|
2197
2542
|
: null;
|
|
2198
2543
|
|
|
2199
2544
|
markExecuting(activeLedger, pendingToolCallId(pending));
|
|
2200
|
-
|
|
2545
|
+
guards.ensureActive();
|
|
2546
|
+
const toolResult = await runCoreToolAsync({
|
|
2201
2547
|
tool: pending.name,
|
|
2202
2548
|
args: pending.args,
|
|
2203
2549
|
workspaceRoot,
|
|
@@ -2206,7 +2552,9 @@ async function runNativeLoop({
|
|
|
2206
2552
|
onArtifactPersisted,
|
|
2207
2553
|
executionState,
|
|
2208
2554
|
resume: resumeForAsk,
|
|
2555
|
+
signal,
|
|
2209
2556
|
});
|
|
2557
|
+
guards.ensureActive();
|
|
2210
2558
|
if (toolResult && toolResult.executionState) {
|
|
2211
2559
|
executionState = toolResult.executionState;
|
|
2212
2560
|
}
|
|
@@ -2354,6 +2702,37 @@ async function runNativeAgentTask({
|
|
|
2354
2702
|
model,
|
|
2355
2703
|
});
|
|
2356
2704
|
|
|
2705
|
+
let accountId = "";
|
|
2706
|
+
if (runtime.provider === "codex" && !runtime.apiKey) {
|
|
2707
|
+
try {
|
|
2708
|
+
const config = loadConfig(workspaceRoot) || {};
|
|
2709
|
+
const credential = await resolveCodexUpstreamCredentials({
|
|
2710
|
+
authPath: config.codexAuthPath,
|
|
2711
|
+
refreshWindowMs: Number(config.codexOauthRefreshWindowSec || 300) * 1000,
|
|
2712
|
+
env: process.env,
|
|
2713
|
+
});
|
|
2714
|
+
const token = String(credential && (credential.accessToken || credential.apiKey) || "").trim();
|
|
2715
|
+
if (token) {
|
|
2716
|
+
runtime.apiKey = token;
|
|
2717
|
+
runtime.apiKeySource = String(credential.source || "codex-credential");
|
|
2718
|
+
}
|
|
2719
|
+
const credentialKind = String(credential && credential.credentialKind || "").trim();
|
|
2720
|
+
if (
|
|
2721
|
+
credentialKind === "api-key"
|
|
2722
|
+
&& !String(process.env.UFOO_UCODE_BASE_URL || "").trim()
|
|
2723
|
+
&& !String(config.ucodeBaseUrl || "").trim()
|
|
2724
|
+
) {
|
|
2725
|
+
runtime.baseUrl = String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL).trim();
|
|
2726
|
+
}
|
|
2727
|
+
if (credentialKind === "oauth") {
|
|
2728
|
+
accountId = String(credential && credential.accountId || "").trim();
|
|
2729
|
+
}
|
|
2730
|
+
} catch {
|
|
2731
|
+
// The request will report the provider's auth error when no Codex
|
|
2732
|
+
// credential is available; keep runtime resolution non-throwing.
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2357
2736
|
// Kimi tokens expire; resolveRuntimeConfig reads the credential file
|
|
2358
2737
|
// synchronously, so refresh it here (async) when the key came from that
|
|
2359
2738
|
// file and the token is outside the fresh window.
|
|
@@ -2384,6 +2763,7 @@ async function runNativeAgentTask({
|
|
|
2384
2763
|
baseUrl: runtime.baseUrl,
|
|
2385
2764
|
apiKey: runtime.apiKey,
|
|
2386
2765
|
provider: runtime.provider,
|
|
2766
|
+
accountId,
|
|
2387
2767
|
timeoutMs,
|
|
2388
2768
|
onStreamDelta: trackingStreamDelta,
|
|
2389
2769
|
onThinkingDelta,
|
|
@@ -2458,9 +2838,11 @@ async function runNativeAgentTask({
|
|
|
2458
2838
|
|
|
2459
2839
|
module.exports = {
|
|
2460
2840
|
runNativeAgentTask,
|
|
2841
|
+
runCoreToolAsync,
|
|
2461
2842
|
appendAnswerToolResult,
|
|
2462
2843
|
resolveRuntimeConfig,
|
|
2463
2844
|
resolveCompletionUrl,
|
|
2845
|
+
resolveResponsesUrl,
|
|
2464
2846
|
resolveAnthropicMessagesUrl,
|
|
2465
2847
|
resolveTransport,
|
|
2466
2848
|
resolveThinkingBudgetTokens,
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
const DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1";
|
|
11
11
|
const DEFAULT_TIMEOUT_MS = 8000;
|
|
12
12
|
const CACHE_TTL_MS = 60_000;
|
|
13
|
+
const DEFAULT_GROK_CLIENT_VERSION = "0.2.120";
|
|
13
14
|
|
|
14
15
|
/** @type {Map<string, { at: number, result: object }>} */
|
|
15
16
|
const modelsCache = new Map();
|
|
@@ -45,11 +46,20 @@ function resolveAnthropicModelsUrl(baseUrl = "") {
|
|
|
45
46
|
return `${normalized}/models`;
|
|
46
47
|
}
|
|
47
48
|
|
|
48
|
-
function resolveModelsUrl({ transport = "", baseUrl = "" } = {}) {
|
|
49
|
+
function resolveModelsUrl({ transport = "", baseUrl = "", provider = "" } = {}) {
|
|
50
|
+
let url;
|
|
49
51
|
if (String(transport || "") === "anthropic-messages") {
|
|
50
|
-
|
|
52
|
+
url = resolveAnthropicModelsUrl(baseUrl);
|
|
53
|
+
} else {
|
|
54
|
+
url = resolveOpenAiModelsUrl(baseUrl);
|
|
55
|
+
}
|
|
56
|
+
const normalizedProvider = String(provider || "").trim().toLowerCase();
|
|
57
|
+
if (normalizedProvider === "grok" || normalizedProvider === "grok-build" || normalizedProvider === "grok-shell") {
|
|
58
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
59
|
+
const version = String(process.env.UFOO_GROK_CLIENT_VERSION || DEFAULT_GROK_CLIENT_VERSION).trim();
|
|
60
|
+
return `${url}${separator}client_version=${encodeURIComponent(version || DEFAULT_GROK_CLIENT_VERSION)}`;
|
|
51
61
|
}
|
|
52
|
-
return
|
|
62
|
+
return url;
|
|
53
63
|
}
|
|
54
64
|
|
|
55
65
|
function cacheKey({ transport = "", baseUrl = "", apiKey = "", provider = "" } = {}) {
|
|
@@ -88,10 +98,15 @@ function extractModelIds(payload) {
|
|
|
88
98
|
return ids;
|
|
89
99
|
}
|
|
90
100
|
|
|
91
|
-
function buildListHeaders({ transport = "", apiKey = "" } = {}) {
|
|
101
|
+
function buildListHeaders({ transport = "", apiKey = "", provider = "" } = {}) {
|
|
92
102
|
const headers = {
|
|
93
103
|
Accept: "application/json",
|
|
94
104
|
};
|
|
105
|
+
const normalizedProvider = String(provider || "").trim().toLowerCase();
|
|
106
|
+
if (normalizedProvider === "grok" || normalizedProvider === "grok-build" || normalizedProvider === "grok-shell") {
|
|
107
|
+
const version = String(process.env.UFOO_GROK_CLIENT_VERSION || DEFAULT_GROK_CLIENT_VERSION).trim();
|
|
108
|
+
headers["User-Agent"] = `grok-shell/${version || DEFAULT_GROK_CLIENT_VERSION}`;
|
|
109
|
+
}
|
|
95
110
|
const key = String(apiKey || "").trim();
|
|
96
111
|
if (!key) return headers;
|
|
97
112
|
|
|
@@ -123,7 +138,7 @@ async function listProviderModels(options = {}) {
|
|
|
123
138
|
const timeoutMs = Math.max(1000, Number(options.timeoutMs) || DEFAULT_TIMEOUT_MS);
|
|
124
139
|
const fetchImpl = typeof options.fetchImpl === "function" ? options.fetchImpl : fetch;
|
|
125
140
|
const skipCache = options.skipCache === true;
|
|
126
|
-
const url = resolveModelsUrl({ transport, baseUrl });
|
|
141
|
+
const url = resolveModelsUrl({ transport, baseUrl, provider });
|
|
127
142
|
|
|
128
143
|
if (!url) {
|
|
129
144
|
return {
|
|
@@ -155,7 +170,7 @@ async function listProviderModels(options = {}) {
|
|
|
155
170
|
try {
|
|
156
171
|
const response = await fetchImpl(url, {
|
|
157
172
|
method: "GET",
|
|
158
|
-
headers: buildListHeaders({ transport, apiKey }),
|
|
173
|
+
headers: buildListHeaders({ transport, apiKey, provider }),
|
|
159
174
|
signal: controller ? controller.signal : undefined,
|
|
160
175
|
});
|
|
161
176
|
const status = Number(response && response.status) || 0;
|