u-foo 3.0.28 → 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/contextWindow.js +2 -0
- package/src/code/dispatch.js +9 -1
- package/src/code/index.js +9 -2
- package/src/code/nativeRunner.js +427 -18
- 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/code/usageStore.js +19 -2
- 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 +123 -18
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,12 +103,17 @@ 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
|
|
96
113
|
// for non-trivial tasks while still catching runaway loops. Override via env.
|
|
97
114
|
const DEFAULT_MAX_NATIVE_TOOL_CALLS = 100;
|
|
98
115
|
const DEFAULT_MAX_NATIVE_TOOL_ERRORS = 20;
|
|
116
|
+
const MAX_EMPTY_TERMINAL_RETRIES = 2;
|
|
99
117
|
const DEFAULT_NATIVE_TIMEOUT_MS = 43200000; // 12 hours
|
|
100
118
|
/** Max text-only auto-continues while a plan is waiting on a task (per user submit). */
|
|
101
119
|
const DEFAULT_MAX_PLAN_AUTO_CONTINUES = 24;
|
|
@@ -213,7 +231,8 @@ function readOpenAiUsage(raw) {
|
|
|
213
231
|
input: toUsageInt(raw.prompt_tokens),
|
|
214
232
|
output: toUsageInt(raw.completion_tokens),
|
|
215
233
|
cacheRead: toUsageInt(details.cached_tokens),
|
|
216
|
-
cacheCreation:
|
|
234
|
+
cacheCreation: toUsageInt(details.created_cache_tokens),
|
|
235
|
+
inputIncludesCache: true,
|
|
217
236
|
};
|
|
218
237
|
}
|
|
219
238
|
|
|
@@ -226,6 +245,7 @@ function readAnthropicUsage(raw, { includeOutput = false } = {}) {
|
|
|
226
245
|
output: includeOutput ? toUsageInt(raw.output_tokens) : 0,
|
|
227
246
|
cacheRead: toUsageInt(raw.cache_read_input_tokens),
|
|
228
247
|
cacheCreation: toUsageInt(raw.cache_creation_input_tokens),
|
|
248
|
+
inputIncludesCache: false,
|
|
229
249
|
};
|
|
230
250
|
}
|
|
231
251
|
|
|
@@ -289,19 +309,42 @@ function clipText(value = "", maxChars = 6000) {
|
|
|
289
309
|
function normalizeProvider(value = "") {
|
|
290
310
|
const text = String(value || "").trim().toLowerCase();
|
|
291
311
|
if (!text) return "";
|
|
292
|
-
if (text === "codex" || text === "codex-cli" || text === "codex-code") return "
|
|
312
|
+
if (text === "codex" || text === "codex-cli" || text === "codex-code") return "codex";
|
|
293
313
|
if (text === "claude" || text === "claude-cli" || text === "claude-code") return "anthropic";
|
|
294
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";
|
|
295
317
|
if (text === "openai" || text === "anthropic") return text;
|
|
296
318
|
return text;
|
|
297
319
|
}
|
|
298
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
|
+
|
|
299
338
|
function resolveTransport({ provider = "", baseUrl = "" } = {}) {
|
|
300
339
|
const normalizedProvider = normalizeProvider(provider);
|
|
301
340
|
const url = String(baseUrl || "").trim().toLowerCase();
|
|
302
341
|
|
|
342
|
+
if (normalizedProvider === "codex" || normalizedProvider === "grok-build" || normalizedProvider === "xai") {
|
|
343
|
+
return "openai-responses";
|
|
344
|
+
}
|
|
303
345
|
if (normalizedProvider === "anthropic") return "anthropic-messages";
|
|
304
346
|
if (normalizedProvider === "kimi") return "openai-chat";
|
|
347
|
+
if (/\/responses(?:$|[/?#])/.test(url)) return "openai-responses";
|
|
305
348
|
if (url.includes("anthropic.com")) return "anthropic-messages";
|
|
306
349
|
if (/\/messages(?:$|[/?#])/.test(url) && !/\/chat\/completions(?:$|[/?#])/.test(url)) {
|
|
307
350
|
return "anthropic-messages";
|
|
@@ -327,16 +370,28 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
|
|
|
327
370
|
model
|
|
328
371
|
|| process.env.UFOO_UCODE_MODEL
|
|
329
372
|
|| configuredModel
|
|
330
|
-
|| (selectedProvider === "kimi"
|
|
373
|
+
|| (selectedProvider === "kimi"
|
|
374
|
+
? DEFAULT_KIMI_MODEL
|
|
375
|
+
: (selectedProvider === "grok-build" ? DEFAULT_GROK_BUILD_MODEL : defaultAgentModelForProvider(selectedProvider)))
|
|
331
376
|
).trim();
|
|
332
377
|
|
|
333
378
|
const defaultBaseUrl = selectedProvider === "anthropic"
|
|
334
379
|
? String(process.env.ANTHROPIC_BASE_URL || DEFAULT_ANTHROPIC_BASE_URL)
|
|
335
380
|
: selectedProvider === "kimi"
|
|
336
|
-
? DEFAULT_KIMI_BASE_URL
|
|
337
|
-
:
|
|
338
|
-
|
|
339
|
-
|
|
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(
|
|
340
395
|
process.env.UFOO_UCODE_BASE_URL
|
|
341
396
|
|| config.ucodeBaseUrl
|
|
342
397
|
|| defaultBaseUrl
|
|
@@ -362,11 +417,26 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
|
|
|
362
417
|
apiKey = String(
|
|
363
418
|
(selectedProvider === "openai" ? process.env.OPENAI_API_KEY : "")
|
|
364
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 : "")
|
|
365
423
|
|| ""
|
|
366
424
|
).trim();
|
|
367
425
|
if (apiKey) apiKeySource = "env";
|
|
368
426
|
}
|
|
369
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
|
+
|
|
370
440
|
return {
|
|
371
441
|
provider: selectedProvider,
|
|
372
442
|
model: selectedModel,
|
|
@@ -388,6 +458,16 @@ function resolveCompletionUrl(baseUrl = "") {
|
|
|
388
458
|
return `${normalized}/chat/completions`;
|
|
389
459
|
}
|
|
390
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
|
+
|
|
391
471
|
function resolveAnthropicMessagesUrl(baseUrl = "") {
|
|
392
472
|
const raw = String(baseUrl || "").trim() || DEFAULT_ANTHROPIC_BASE_URL;
|
|
393
473
|
const normalized = raw.replace(/\/+$/, "");
|
|
@@ -1019,6 +1099,88 @@ function runCoreTool({
|
|
|
1019
1099
|
return result;
|
|
1020
1100
|
}
|
|
1021
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
|
+
|
|
1022
1184
|
function emitPhase(callback, event = {}) {
|
|
1023
1185
|
if (typeof callback !== "function") return;
|
|
1024
1186
|
try {
|
|
@@ -1131,8 +1293,9 @@ async function runOpenAiLikeTurn({
|
|
|
1131
1293
|
signal = null,
|
|
1132
1294
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
1133
1295
|
} = {}) {
|
|
1296
|
+
const normalizedProvider = normalizeProvider(provider);
|
|
1134
1297
|
const payload = {
|
|
1135
|
-
model,
|
|
1298
|
+
model: normalizedProvider === "kimi" ? normalizeKimiModel(model) : model,
|
|
1136
1299
|
max_tokens: resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
|
|
1137
1300
|
messages,
|
|
1138
1301
|
tools: buildCoreToolSpecs(),
|
|
@@ -1141,7 +1304,7 @@ async function runOpenAiLikeTurn({
|
|
|
1141
1304
|
// Ask for the terminal usage chunk so token/cache accounting works.
|
|
1142
1305
|
stream_options: { include_usage: true },
|
|
1143
1306
|
// Kimi k3 rejects any temperature other than 1.
|
|
1144
|
-
temperature:
|
|
1307
|
+
temperature: normalizedProvider === "kimi" ? 1 : 0,
|
|
1145
1308
|
};
|
|
1146
1309
|
const reasoningEffort = resolveReasoningEffort();
|
|
1147
1310
|
if (reasoningEffort) {
|
|
@@ -1150,12 +1313,9 @@ async function runOpenAiLikeTurn({
|
|
|
1150
1313
|
payload.reasoning_effort = reasoningEffort;
|
|
1151
1314
|
}
|
|
1152
1315
|
|
|
1153
|
-
const headers =
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
if (apiKey) {
|
|
1157
|
-
headers.authorization = `Bearer ${apiKey}`;
|
|
1158
|
-
}
|
|
1316
|
+
const headers = normalizedProvider === "kimi"
|
|
1317
|
+
? buildKimiHeaders({ apiKey, stream: true })
|
|
1318
|
+
: { "content-type": "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) };
|
|
1159
1319
|
|
|
1160
1320
|
const toolCallMap = new Map();
|
|
1161
1321
|
const announcedToolNames = new Set();
|
|
@@ -1293,6 +1453,180 @@ async function runOpenAiLikeTurn({
|
|
|
1293
1453
|
});
|
|
1294
1454
|
}
|
|
1295
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
|
+
|
|
1296
1630
|
function normalizeAnthropicMessageContent(raw = []) {
|
|
1297
1631
|
if (!Array.isArray(raw)) return [];
|
|
1298
1632
|
return raw
|
|
@@ -1431,7 +1765,13 @@ async function runAnthropicTurn({
|
|
|
1431
1765
|
let responseText = "";
|
|
1432
1766
|
let nextSyntheticBlockIndex = 0;
|
|
1433
1767
|
let lastBlockIndex = -1;
|
|
1434
|
-
const turnUsage = {
|
|
1768
|
+
const turnUsage = {
|
|
1769
|
+
input: 0,
|
|
1770
|
+
output: 0,
|
|
1771
|
+
cacheRead: 0,
|
|
1772
|
+
cacheCreation: 0,
|
|
1773
|
+
inputIncludesCache: false,
|
|
1774
|
+
};
|
|
1435
1775
|
|
|
1436
1776
|
return runSseRequest({
|
|
1437
1777
|
url,
|
|
@@ -1654,6 +1994,7 @@ async function runAnthropicTurn({
|
|
|
1654
1994
|
|
|
1655
1995
|
const {
|
|
1656
1996
|
createOpenAiChatTransport,
|
|
1997
|
+
createOpenAiResponsesTransport,
|
|
1657
1998
|
createAnthropicMessagesTransport,
|
|
1658
1999
|
} = require("./providers");
|
|
1659
2000
|
|
|
@@ -1667,6 +2008,14 @@ const TRANSPORTS = {
|
|
|
1667
2008
|
toJsonString,
|
|
1668
2009
|
clipText,
|
|
1669
2010
|
}),
|
|
2011
|
+
"openai-responses": createOpenAiResponsesTransport({
|
|
2012
|
+
resolveUrl: resolveResponsesUrl,
|
|
2013
|
+
runTurn: runResponsesTurn,
|
|
2014
|
+
normalizeToolName,
|
|
2015
|
+
normalizeToolCallArgs,
|
|
2016
|
+
toJsonString,
|
|
2017
|
+
clipText,
|
|
2018
|
+
}),
|
|
1670
2019
|
"anthropic-messages": createAnthropicMessagesTransport({
|
|
1671
2020
|
resolveUrl: resolveAnthropicMessagesUrl,
|
|
1672
2021
|
runTurn: runAnthropicTurn,
|
|
@@ -1734,6 +2083,7 @@ async function runNativeLoop({
|
|
|
1734
2083
|
baseUrl = "",
|
|
1735
2084
|
apiKey = "",
|
|
1736
2085
|
provider = "",
|
|
2086
|
+
accountId = "",
|
|
1737
2087
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
1738
2088
|
onStreamDelta = null,
|
|
1739
2089
|
onThinkingDelta = null,
|
|
@@ -1806,6 +2156,7 @@ async function runNativeLoop({
|
|
|
1806
2156
|
let streamed = false;
|
|
1807
2157
|
let toolCallsExecuted = 0;
|
|
1808
2158
|
let toolErrors = 0;
|
|
2159
|
+
let emptyTerminalRetries = 0;
|
|
1809
2160
|
let executionState = initialExecutionState && typeof initialExecutionState === "object"
|
|
1810
2161
|
? initialExecutionState
|
|
1811
2162
|
: emptyExecutionState();
|
|
@@ -1953,9 +2304,11 @@ async function runNativeLoop({
|
|
|
1953
2304
|
apiKey,
|
|
1954
2305
|
model: requestModel,
|
|
1955
2306
|
provider,
|
|
2307
|
+
accountId,
|
|
1956
2308
|
systemPrompt,
|
|
1957
2309
|
systemBlocks,
|
|
1958
2310
|
messages: providerMessages,
|
|
2311
|
+
sessionId,
|
|
1959
2312
|
signal,
|
|
1960
2313
|
timeoutMs,
|
|
1961
2314
|
onPhase,
|
|
@@ -1979,9 +2332,26 @@ async function runNativeLoop({
|
|
|
1979
2332
|
|
|
1980
2333
|
if (toolCalls.length === 0) {
|
|
1981
2334
|
const text = String(turnResult.text || "").trim();
|
|
2335
|
+
if (!text && toolCallsExecuted > 0) {
|
|
2336
|
+
if (emptyTerminalRetries >= MAX_EMPTY_TERMINAL_RETRIES) {
|
|
2337
|
+
throw new Error("model returned an empty response after tool execution");
|
|
2338
|
+
}
|
|
2339
|
+
emptyTerminalRetries += 1;
|
|
2340
|
+
providerMessages.push({
|
|
2341
|
+
role: "user",
|
|
2342
|
+
content: [
|
|
2343
|
+
"Continue the current task after the tool results.",
|
|
2344
|
+
"Call any remaining tools, or provide a concrete final answer to the user.",
|
|
2345
|
+
"Do not end the turn with an empty response.",
|
|
2346
|
+
].join(" "),
|
|
2347
|
+
});
|
|
2348
|
+
continue;
|
|
2349
|
+
}
|
|
2350
|
+
emptyTerminalRetries = 0;
|
|
1982
2351
|
const sideEffects = parseStructuredSideEffects(text);
|
|
1983
2352
|
const planCommand = sideEffects ? normalizePlanGraphCommand(sideEffects) : null;
|
|
1984
2353
|
if (planCommand) {
|
|
2354
|
+
guards.ensureActive();
|
|
1985
2355
|
transport.appendFinalAssistantMessage({ messages: providerMessages, turnResult });
|
|
1986
2356
|
const planResult = runCoreTool({
|
|
1987
2357
|
tool: "plan_graph",
|
|
@@ -1993,6 +2363,7 @@ async function runNativeLoop({
|
|
|
1993
2363
|
executionState,
|
|
1994
2364
|
origin: { kind: "legacy_side_effect", source: planCommand.source || "legacy" },
|
|
1995
2365
|
});
|
|
2366
|
+
guards.ensureActive();
|
|
1996
2367
|
if (planResult && planResult.executionState) {
|
|
1997
2368
|
executionState = planResult.executionState;
|
|
1998
2369
|
}
|
|
@@ -2032,6 +2403,7 @@ async function runNativeLoop({
|
|
|
2032
2403
|
|
|
2033
2404
|
// A tool-using turn resets the empty auto-continue streak (progress possible).
|
|
2034
2405
|
consecutiveEmptyAutoContinues = 0;
|
|
2406
|
+
emptyTerminalRetries = 0;
|
|
2035
2407
|
|
|
2036
2408
|
const pendingCalls = transport.prepareToolCalls({
|
|
2037
2409
|
messages: providerMessages,
|
|
@@ -2170,7 +2542,8 @@ async function runNativeLoop({
|
|
|
2170
2542
|
: null;
|
|
2171
2543
|
|
|
2172
2544
|
markExecuting(activeLedger, pendingToolCallId(pending));
|
|
2173
|
-
|
|
2545
|
+
guards.ensureActive();
|
|
2546
|
+
const toolResult = await runCoreToolAsync({
|
|
2174
2547
|
tool: pending.name,
|
|
2175
2548
|
args: pending.args,
|
|
2176
2549
|
workspaceRoot,
|
|
@@ -2179,7 +2552,9 @@ async function runNativeLoop({
|
|
|
2179
2552
|
onArtifactPersisted,
|
|
2180
2553
|
executionState,
|
|
2181
2554
|
resume: resumeForAsk,
|
|
2555
|
+
signal,
|
|
2182
2556
|
});
|
|
2557
|
+
guards.ensureActive();
|
|
2183
2558
|
if (toolResult && toolResult.executionState) {
|
|
2184
2559
|
executionState = toolResult.executionState;
|
|
2185
2560
|
}
|
|
@@ -2327,6 +2702,37 @@ async function runNativeAgentTask({
|
|
|
2327
2702
|
model,
|
|
2328
2703
|
});
|
|
2329
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
|
+
|
|
2330
2736
|
// Kimi tokens expire; resolveRuntimeConfig reads the credential file
|
|
2331
2737
|
// synchronously, so refresh it here (async) when the key came from that
|
|
2332
2738
|
// file and the token is outside the fresh window.
|
|
@@ -2357,6 +2763,7 @@ async function runNativeAgentTask({
|
|
|
2357
2763
|
baseUrl: runtime.baseUrl,
|
|
2358
2764
|
apiKey: runtime.apiKey,
|
|
2359
2765
|
provider: runtime.provider,
|
|
2766
|
+
accountId,
|
|
2360
2767
|
timeoutMs,
|
|
2361
2768
|
onStreamDelta: trackingStreamDelta,
|
|
2362
2769
|
onThinkingDelta,
|
|
@@ -2431,9 +2838,11 @@ async function runNativeAgentTask({
|
|
|
2431
2838
|
|
|
2432
2839
|
module.exports = {
|
|
2433
2840
|
runNativeAgentTask,
|
|
2841
|
+
runCoreToolAsync,
|
|
2434
2842
|
appendAnswerToolResult,
|
|
2435
2843
|
resolveRuntimeConfig,
|
|
2436
2844
|
resolveCompletionUrl,
|
|
2845
|
+
resolveResponsesUrl,
|
|
2437
2846
|
resolveAnthropicMessagesUrl,
|
|
2438
2847
|
resolveTransport,
|
|
2439
2848
|
resolveThinkingBudgetTokens,
|