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