u-foo 4.0.10 → 4.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/OPTIONAL_SKILLS/ufoo-bus-poll/SKILL.md +27 -0
- package/README.md +279 -789
- package/README.zh-CN.md +290 -439
- package/SKILLS/ufoo/SKILL.md +7 -0
- package/bin/ufoo.js +36 -3
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/docs/OBSERVABILITY.md +4 -2
- package/docs/README.md +1 -0
- package/package.json +6 -2
- package/scripts/pack-desktop.js +174 -0
- package/src/agents/capabilities/coding/index.js +26 -3
- package/src/agents/capabilities/index.js +2 -1
- package/src/agents/capabilities/mac/index.js +145 -0
- package/src/agents/capabilities/planning/index.js +1 -1
- package/src/agents/capabilities/turnRecall/index.js +5 -16
- package/src/agents/profiles/coding.js +1 -1
- package/src/agents/profiles/main.js +1 -1
- package/src/agents/providers/nativeTransport.js +105 -116
- package/src/agents/providers/runtimeConfig.js +15 -4
- package/src/agents/providers/transports/anthropicCache.js +78 -0
- package/src/agents/providers/transports/antigravityTransport.js +3 -2
- package/src/agents/providers/transports/openaiResponsesTransport.js +7 -12
- package/src/agents/providers/transports/requestCacheObservation.js +61 -0
- package/src/agents/providers/transports/responsesProtocol.js +54 -46
- package/src/agents/providers/upstreamRuntime.js +2 -2
- package/src/agents/runtime/context/contextWindow.js +10 -0
- package/src/agents/runtime/context/slidingWindowManager.js +97 -41
- package/src/agents/runtime/context/topicSelector.js +4 -2
- package/src/agents/runtime/context/turnAnalyzer.js +17 -29
- package/src/agents/runtime/core/agentLoop.js +23 -7
- package/src/agents/runtime/createAgentRuntime.js +1 -1
- package/src/agents/runtime/protocol/auxiliaryModelRequest.js +28 -0
- package/src/app/chat/ChatController.js +1 -0
- package/src/app/chat/commandExecutor.js +25 -0
- package/src/app/chat/commands.js +2 -0
- package/src/app/chat/daemonMessageRouter.js +30 -3
- package/src/app/cli/appCommands.js +107 -0
- package/src/app/cli/features/skills.js +2 -0
- package/src/app/cli/macCommands.js +321 -0
- package/src/app/cli/metricsCommands.js +6 -1
- package/src/app/cli/run.js +26 -0
- package/src/app/cli/setupCommands.js +1 -0
- package/src/code/agent.js +1 -0
- package/src/code/context/assembler.js +8 -6
- package/src/code/context/promptLayers.js +3 -1
- package/src/code/context/stateCommit.js +2 -2
- package/src/code/context/transcript.js +11 -5
- package/src/code/nativeRunner.js +25 -5
- package/src/code/skills/loader.js +10 -2
- package/src/code/skills/render.js +8 -1
- package/src/config.js +42 -0
- package/src/coordination/bus/activate.js +44 -19
- package/src/coordination/history/agentPerformance.js +88 -11
- package/src/coordination/history/agentTrace.js +2 -0
- package/src/coordination/history/modelInputCost.js +52 -0
- package/src/runtime/contracts/uiProtocol.js +26 -0
- package/src/runtime/daemon/agentHost.js +35 -12
- package/src/runtime/daemon/mcpStdioProxy.js +3 -2
- package/src/runtime/mac/helperClient.js +279 -0
- package/src/runtime/mac/helperCompiler.js +235 -0
- package/src/runtime/mac/macSession.js +866 -0
- package/src/runtime/mac/native/ufoo_mac_helper.swift +2493 -0
- package/src/runtime/mac/paths.js +63 -0
- package/src/ui/agentSettingsController.js +12 -5
- package/src/ui/cliHandoff.js +484 -0
- package/src/ui/desktopArchive.js +41 -0
- package/src/ui/desktopUiHost.js +1601 -0
- package/src/ui/desktopUiHostCli.js +66 -0
- package/src/ui/format/index.js +17 -0
- package/src/ui/rustChatHost.js +45 -6
- package/src/ui/workspaceInspector.js +621 -0
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
const os = require("os");
|
|
4
4
|
const { resolveCodexUserAgent, resolveGrokClientVersion } = require("./clientIdentity");
|
|
5
|
-
const { randomUUID } = require("crypto");
|
|
6
|
-
const { Agent: UndiciAgent } = require("undici");
|
|
7
|
-
const { normalizeProvider, normalizeKimiModel, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl } = require("./runtimeConfig");
|
|
5
|
+
const { createHash, randomUUID } = require("crypto");
|
|
6
|
+
const { Agent: UndiciAgent, fetch: undiciFetch } = require("undici");
|
|
7
|
+
const { normalizeProvider, normalizeKimiModel, resolveResponsesRequestProfile, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl } = require("./runtimeConfig");
|
|
8
8
|
const { stableStringify } = require("../runtime/core/stableJson");
|
|
9
|
+
const { observeWireRequest } = require("./transports/requestCacheObservation");
|
|
10
|
+
const { applyAnthropicCacheBreakpoints } = require("./transports/anthropicCache");
|
|
9
11
|
const { systemBlocksToAnthropicPayload } = require("./transports/systemBlocks");
|
|
10
12
|
const { buildResponsesPayload, isResponsesKeepalive, responseEventDelta, parseResponsesEvents, parseResponsesSsePayload } = require("./transports/responsesProtocol");
|
|
11
13
|
|
|
@@ -121,15 +123,6 @@ function createUsageTotals() {
|
|
|
121
123
|
};
|
|
122
124
|
}
|
|
123
125
|
|
|
124
|
-
function addUsageTotals(totals, usage = null) {
|
|
125
|
-
if (!usage || typeof usage !== "object") return totals;
|
|
126
|
-
totals.input += toUsageInt(usage.input);
|
|
127
|
-
totals.output += toUsageInt(usage.output);
|
|
128
|
-
totals.cacheRead += toUsageInt(usage.cacheRead);
|
|
129
|
-
totals.cacheCreation += toUsageInt(usage.cacheCreation);
|
|
130
|
-
return totals;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
126
|
// OpenAI-compatible streams end with one usage chunk carrying whole-turn
|
|
134
127
|
// totals (prompt_tokens_details.cached_tokens counts the cache hits).
|
|
135
128
|
function readOpenAiUsage(raw) {
|
|
@@ -138,27 +131,31 @@ function readOpenAiUsage(raw) {
|
|
|
138
131
|
const details = raw.prompt_tokens_details && typeof raw.prompt_tokens_details === "object"
|
|
139
132
|
? raw.prompt_tokens_details
|
|
140
133
|
: {};
|
|
134
|
+
const writes = details.cache_write_tokens ?? details.created_cache_tokens;
|
|
141
135
|
return {
|
|
142
136
|
input: toUsageInt(raw.prompt_tokens),
|
|
143
137
|
output: toUsageInt(raw.completion_tokens),
|
|
144
138
|
cacheRead: details.cached_tokens != null && Number.isFinite(Number(details.cached_tokens)) ? toUsageInt(details.cached_tokens) : null,
|
|
145
|
-
cacheCreation: toUsageInt(
|
|
139
|
+
cacheCreation: writes != null && Number.isFinite(Number(writes)) ? toUsageInt(writes) : null,
|
|
146
140
|
inputIncludesCache: true,
|
|
147
141
|
};
|
|
148
142
|
}
|
|
149
143
|
|
|
150
|
-
// Anthropic
|
|
151
|
-
//
|
|
152
|
-
function readAnthropicUsage(raw
|
|
144
|
+
// Anthropic's streaming counters are cumulative. Preserve missing fields
|
|
145
|
+
// so proxies that omit cache usage do not get credited with a zero hit rate.
|
|
146
|
+
function readAnthropicUsage(raw) {
|
|
153
147
|
if (!raw || typeof raw !== "object") return null;
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
input:
|
|
157
|
-
output:
|
|
158
|
-
cacheRead:
|
|
159
|
-
cacheCreation:
|
|
160
|
-
inputIncludesCache: false,
|
|
148
|
+
const count = value => value != null && Number.isFinite(Number(value)) && Number(value) >= 0 ? Number(value) : null;
|
|
149
|
+
const usage = {
|
|
150
|
+
input: count(raw.input_tokens),
|
|
151
|
+
output: count(raw.output_tokens),
|
|
152
|
+
cacheRead: count(raw.cache_read_input_tokens),
|
|
153
|
+
cacheCreation: count(raw.cache_creation_input_tokens),
|
|
161
154
|
};
|
|
155
|
+
const ttl5m = count(raw.cache_creation?.ephemeral_5m_input_tokens);
|
|
156
|
+
const ttl1h = count(raw.cache_creation?.ephemeral_1h_input_tokens);
|
|
157
|
+
if (ttl5m !== null || ttl1h !== null) usage.cacheWriteByTtl = { "5m": ttl5m, "1h": ttl1h };
|
|
158
|
+
return Object.values(usage).some(value => value !== null) ? { ...usage, inputIncludesCache: false } : null;
|
|
162
159
|
}
|
|
163
160
|
|
|
164
161
|
function clipText(value = "", maxChars = 6000) {
|
|
@@ -319,6 +316,8 @@ async function runSseRequest({
|
|
|
319
316
|
signal = null,
|
|
320
317
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
321
318
|
onPhase = null,
|
|
319
|
+
onRequest = null,
|
|
320
|
+
requestObservation = {},
|
|
322
321
|
onNonStream,
|
|
323
322
|
onEvent,
|
|
324
323
|
onTail = null,
|
|
@@ -332,9 +331,15 @@ async function runSseRequest({
|
|
|
332
331
|
// Protocol handlers retain their own accumulators. Once any event has
|
|
333
332
|
// reached one, replay would duplicate text/tool arguments; stop retrying.
|
|
334
333
|
let consumed = false;
|
|
334
|
+
if (attempt === 0 && typeof onRequest === "function") {
|
|
335
|
+
const startedAt = nowMs();
|
|
336
|
+
const credentials = String(headers.authorization || headers.Authorization || headers["x-api-key"] || "");
|
|
337
|
+
try { onRequest(observeWireRequest({ payload, url, startedAt, credentials, ...requestObservation })); } catch { /* observer only */ }
|
|
338
|
+
}
|
|
335
339
|
emitPhase(onPhase, { type: "request_start" });
|
|
336
340
|
try {
|
|
337
|
-
|
|
341
|
+
// Use the dependency's fetch so its handler matches the Agent's dispatcher API.
|
|
342
|
+
response = await undiciFetch(url, {
|
|
338
343
|
method: "POST",
|
|
339
344
|
headers,
|
|
340
345
|
body: JSON.stringify(payload),
|
|
@@ -439,6 +444,11 @@ async function runOpenAiLikeTurn({
|
|
|
439
444
|
onTextDelta = null,
|
|
440
445
|
onThinkingDelta = null,
|
|
441
446
|
onPhase = null,
|
|
447
|
+
onRequest = null,
|
|
448
|
+
requestScope = "",
|
|
449
|
+
requestPurpose = "",
|
|
450
|
+
strategyVersion = 1,
|
|
451
|
+
sessionId = "",
|
|
442
452
|
signal = null,
|
|
443
453
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
444
454
|
} = {}) {
|
|
@@ -446,7 +456,7 @@ async function runOpenAiLikeTurn({
|
|
|
446
456
|
const payload = {
|
|
447
457
|
model: normalizedProvider === "kimi" ? normalizeKimiModel(model) : model,
|
|
448
458
|
max_tokens: maxOutputTokens || resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
|
|
449
|
-
messages,
|
|
459
|
+
messages: messages.map(({ responsesContinuation: _continuation, ...message }) => message),
|
|
450
460
|
...(tools.length ? { tools, tool_choice: "auto" } : {}),
|
|
451
461
|
stream: true,
|
|
452
462
|
// Ask for the terminal usage chunk so token/cache accounting works.
|
|
@@ -481,6 +491,8 @@ async function runOpenAiLikeTurn({
|
|
|
481
491
|
signal,
|
|
482
492
|
timeoutMs,
|
|
483
493
|
onPhase,
|
|
494
|
+
onRequest,
|
|
495
|
+
requestObservation: { transport: "openai-chat", sessionId, requestScope, requestPurpose, strategyVersion, requestProfile: normalizedProvider === "kimi" ? "kimi-chat" : "" },
|
|
484
496
|
onNonStream: (data) => {
|
|
485
497
|
const message = data && data.choices && data.choices[0] && data.choices[0].message
|
|
486
498
|
? data.choices[0].message
|
|
@@ -639,7 +651,7 @@ function buildKimiHeaders({ apiKey = "", stream = true } = {}) {
|
|
|
639
651
|
return headers;
|
|
640
652
|
}
|
|
641
653
|
|
|
642
|
-
function buildResponsesHeaders({ provider = "", apiKey = "", sessionId = "", accountId = "", url = "" } = {}) {
|
|
654
|
+
function buildResponsesHeaders({ provider = "", requestProfile = "", apiKey = "", sessionId = "", accountId = "", url = "" } = {}) {
|
|
643
655
|
const normalizedProvider = normalizeProvider(provider);
|
|
644
656
|
const headers = {
|
|
645
657
|
"content-type": "application/json",
|
|
@@ -648,11 +660,11 @@ function buildResponsesHeaders({ provider = "", apiKey = "", sessionId = "", acc
|
|
|
648
660
|
};
|
|
649
661
|
if (apiKey) headers.authorization = `Bearer ${apiKey}`;
|
|
650
662
|
|
|
651
|
-
if (
|
|
663
|
+
if (requestProfile === "codex-subscription") {
|
|
652
664
|
headers["User-Agent"] = resolveCodexUserAgent();
|
|
653
665
|
headers.Originator = "codex-tui";
|
|
654
666
|
headers["Session-Id"] = String(sessionId || randomUUID());
|
|
655
|
-
if (accountId) headers["
|
|
667
|
+
if (accountId) headers["chatgpt-account-id"] = String(accountId);
|
|
656
668
|
}
|
|
657
669
|
|
|
658
670
|
if (normalizedProvider === "grok-build" || normalizedProvider === "xai") {
|
|
@@ -682,6 +694,7 @@ async function runResponsesTurn({
|
|
|
682
694
|
provider = "",
|
|
683
695
|
thinkingLevel = "",
|
|
684
696
|
systemPrompt = "",
|
|
697
|
+
systemBlocks = null,
|
|
685
698
|
messages = [],
|
|
686
699
|
tools = [],
|
|
687
700
|
maxOutputTokens = null,
|
|
@@ -690,19 +703,30 @@ async function runResponsesTurn({
|
|
|
690
703
|
onTextDelta = null,
|
|
691
704
|
onThinkingDelta = null,
|
|
692
705
|
onPhase = null,
|
|
706
|
+
onRequest = null,
|
|
707
|
+
requestScope = "",
|
|
708
|
+
requestPurpose = "",
|
|
709
|
+
strategyVersion = 1,
|
|
693
710
|
signal = null,
|
|
694
711
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
695
712
|
} = {}) {
|
|
713
|
+
const channel = requestProfile || resolveResponsesRequestProfile(url);
|
|
714
|
+
const endpointKey = createHash("sha256").update(url).digest("hex");
|
|
715
|
+
const responsesRequest = { model, channel, endpointKey };
|
|
696
716
|
const payload = buildResponsesPayload({
|
|
697
717
|
model,
|
|
698
718
|
instructions: systemPrompt,
|
|
719
|
+
systemBlocks,
|
|
699
720
|
messages,
|
|
700
721
|
tools,
|
|
701
722
|
maxOutputTokens: maxOutputTokens || resolveMaxTokens(DEFAULT_OPENAI_MAX_TOKENS),
|
|
702
723
|
reasoningEffort: thinkingLevel === "off" ? "none" : resolveReasoningEffort(thinkingOptions(thinkingLevel)),
|
|
703
724
|
provider: normalizeProvider(provider),
|
|
725
|
+
requestProfile: channel,
|
|
726
|
+
endpointKey,
|
|
727
|
+
strategyVersion,
|
|
704
728
|
});
|
|
705
|
-
const headers = buildResponsesHeaders({ provider, apiKey, sessionId, accountId, url });
|
|
729
|
+
const headers = buildResponsesHeaders({ provider, requestProfile, apiKey, sessionId, accountId, url });
|
|
706
730
|
Object.assign(headers, requestHeaders);
|
|
707
731
|
if (requestProfile === "codex-subscription") delete payload.max_output_tokens;
|
|
708
732
|
const frames = [];
|
|
@@ -742,6 +766,8 @@ async function runResponsesTurn({
|
|
|
742
766
|
signal,
|
|
743
767
|
timeoutMs,
|
|
744
768
|
onPhase,
|
|
769
|
+
onRequest,
|
|
770
|
+
requestObservation: { transport: "openai-responses", sessionId, requestScope, requestPurpose, strategyVersion, requestProfile: channel },
|
|
745
771
|
onNonStream: (data) => {
|
|
746
772
|
const parsed = parseResponsesEvents([{ event: data && data.type ? data.type : "response", data }], {
|
|
747
773
|
assumeCompleted: true,
|
|
@@ -755,6 +781,8 @@ async function runResponsesTurn({
|
|
|
755
781
|
usage: parsed.usage,
|
|
756
782
|
response: parsed.response,
|
|
757
783
|
responseId: parsed.responseId,
|
|
784
|
+
actualModel: parsed.response?.model,
|
|
785
|
+
responsesRequest,
|
|
758
786
|
};
|
|
759
787
|
},
|
|
760
788
|
onEvent: consumeFrame,
|
|
@@ -775,6 +803,8 @@ async function runResponsesTurn({
|
|
|
775
803
|
usage: parsed.usage,
|
|
776
804
|
response: parsed.response,
|
|
777
805
|
responseId: parsed.responseId,
|
|
806
|
+
actualModel: parsed.response?.model,
|
|
807
|
+
responsesRequest,
|
|
778
808
|
incompleteDetails: parsed.incompleteDetails,
|
|
779
809
|
};
|
|
780
810
|
},
|
|
@@ -826,62 +856,6 @@ function extractAnthropicToolCalls(content = []) {
|
|
|
826
856
|
}));
|
|
827
857
|
}
|
|
828
858
|
|
|
829
|
-
const STABLE_HISTORY_BOUNDARY_SYMBOL = Symbol.for("ufoo.stableHistoryBoundary");
|
|
830
|
-
|
|
831
|
-
function stampAnthropicCacheBlock(msg) {
|
|
832
|
-
if (!msg || typeof msg !== "object" || Array.isArray(msg)) return msg;
|
|
833
|
-
if (typeof msg.content === "string") {
|
|
834
|
-
if (!msg.content) return msg;
|
|
835
|
-
return {
|
|
836
|
-
...msg,
|
|
837
|
-
content: [
|
|
838
|
-
{
|
|
839
|
-
type: "text",
|
|
840
|
-
text: msg.content,
|
|
841
|
-
cache_control: { ...ANTHROPIC_CACHE_CONTROL },
|
|
842
|
-
},
|
|
843
|
-
],
|
|
844
|
-
};
|
|
845
|
-
}
|
|
846
|
-
if (Array.isArray(msg.content) && msg.content.length > 0) {
|
|
847
|
-
const blocks = msg.content.slice();
|
|
848
|
-
const blockIndex = blocks.length - 1;
|
|
849
|
-
const block = blocks[blockIndex];
|
|
850
|
-
if (block && typeof block === "object" && !Array.isArray(block)) {
|
|
851
|
-
blocks[blockIndex] = {
|
|
852
|
-
...block,
|
|
853
|
-
cache_control: { ...ANTHROPIC_CACHE_CONTROL },
|
|
854
|
-
};
|
|
855
|
-
return {
|
|
856
|
-
...msg,
|
|
857
|
-
content: blocks,
|
|
858
|
-
};
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
return msg;
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
// Mark the ShortStableSnapshot boundary (when present) and the newest message
|
|
865
|
-
// with cache breakpoints so both the cross-turn sliding window prefix and the
|
|
866
|
-
// intra-turn append-only tool loop prefix are served from the prompt cache.
|
|
867
|
-
function withAnthropicCacheBreakpoint(messages = []) {
|
|
868
|
-
if (!Array.isArray(messages) || messages.length === 0) return messages;
|
|
869
|
-
const copy = messages.slice();
|
|
870
|
-
const lastIndex = copy.length - 1;
|
|
871
|
-
let boundaryIndex = -1;
|
|
872
|
-
for (let i = lastIndex - 1; i >= 0; i -= 1) {
|
|
873
|
-
if (copy[i] && copy[i][STABLE_HISTORY_BOUNDARY_SYMBOL]) {
|
|
874
|
-
boundaryIndex = i;
|
|
875
|
-
break;
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
if (boundaryIndex >= 0) {
|
|
879
|
-
copy[boundaryIndex] = stampAnthropicCacheBlock(copy[boundaryIndex]);
|
|
880
|
-
}
|
|
881
|
-
copy[lastIndex] = stampAnthropicCacheBlock(copy[lastIndex]);
|
|
882
|
-
return copy;
|
|
883
|
-
}
|
|
884
|
-
|
|
885
859
|
async function runAnthropicTurn({
|
|
886
860
|
url = "",
|
|
887
861
|
apiKey = "",
|
|
@@ -896,14 +870,28 @@ async function runAnthropicTurn({
|
|
|
896
870
|
onTextDelta = null,
|
|
897
871
|
onThinkingDelta = null,
|
|
898
872
|
onPhase = null,
|
|
873
|
+
onRequest = null,
|
|
874
|
+
requestScope = "",
|
|
875
|
+
requestPurpose = "",
|
|
876
|
+
strategyVersion = 1,
|
|
877
|
+
sessionId = "",
|
|
899
878
|
signal = null,
|
|
900
879
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
901
880
|
} = {}) {
|
|
902
881
|
const payload = {
|
|
903
882
|
model,
|
|
904
883
|
max_tokens: maxOutputTokens || resolveMaxTokens(DEFAULT_ANTHROPIC_MAX_TOKENS),
|
|
905
|
-
messages:
|
|
906
|
-
|
|
884
|
+
messages: messages.map(message => {
|
|
885
|
+
if (!message.responsesContinuation) return message;
|
|
886
|
+
const { responsesContinuation: _continuation, ...clean } = message;
|
|
887
|
+
const stableBoundary = Symbol.for("ufoo.stableHistoryBoundary");
|
|
888
|
+
if (message[stableBoundary]) clean[stableBoundary] = true;
|
|
889
|
+
return clean;
|
|
890
|
+
}),
|
|
891
|
+
tools: tools.map(({ function: spec, cache_control }) => ({
|
|
892
|
+
name: spec.name, description: spec.description, input_schema: spec.parameters,
|
|
893
|
+
...((cache_control || spec.cache_control) ? { cache_control: cache_control || spec.cache_control } : {}),
|
|
894
|
+
})),
|
|
907
895
|
stream: true,
|
|
908
896
|
};
|
|
909
897
|
const isOpus55 = /^(?:claude-)?opus-5[.-]5(?:$|-)/i.test(model);
|
|
@@ -939,6 +927,10 @@ async function runAnthropicTurn({
|
|
|
939
927
|
}
|
|
940
928
|
}
|
|
941
929
|
|
|
930
|
+
applyAnthropicCacheBreakpoints(payload);
|
|
931
|
+
|
|
932
|
+
const channel = /^https:\/\/api\.anthropic\.com\/v1\/messages(?:$|[?#])/.test(url)
|
|
933
|
+
? (apiKey ? "anthropic-messages" : "claude-subscription") : "anthropic-compatible";
|
|
942
934
|
const headers = {
|
|
943
935
|
"content-type": "application/json",
|
|
944
936
|
"anthropic-version": "2023-06-01",
|
|
@@ -952,14 +944,17 @@ async function runAnthropicTurn({
|
|
|
952
944
|
let responseText = "";
|
|
953
945
|
let nextSyntheticBlockIndex = 0;
|
|
954
946
|
let lastBlockIndex = -1;
|
|
955
|
-
let
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
947
|
+
let turnUsage = null;
|
|
948
|
+
let responseId;
|
|
949
|
+
let actualModel;
|
|
950
|
+
function consumeUsage(raw) {
|
|
951
|
+
const usage = readAnthropicUsage(raw);
|
|
952
|
+
if (!usage) return;
|
|
953
|
+
turnUsage ||= usage;
|
|
954
|
+
for (const [key, value] of Object.entries(usage)) {
|
|
955
|
+
if (value !== null) turnUsage[key] = value;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
963
958
|
|
|
964
959
|
return runSseRequest({
|
|
965
960
|
url,
|
|
@@ -968,6 +963,8 @@ async function runAnthropicTurn({
|
|
|
968
963
|
signal,
|
|
969
964
|
timeoutMs,
|
|
970
965
|
onPhase,
|
|
966
|
+
onRequest,
|
|
967
|
+
requestObservation: { transport: "anthropic-messages", sessionId, requestScope, requestPurpose, strategyVersion, requestProfile: channel },
|
|
971
968
|
onNonStream: (data) => {
|
|
972
969
|
const content = normalizeAnthropicMessageContent(data && data.content);
|
|
973
970
|
const text = content
|
|
@@ -977,14 +974,16 @@ async function runAnthropicTurn({
|
|
|
977
974
|
if (text && typeof onTextDelta === "function") {
|
|
978
975
|
onTextDelta(text);
|
|
979
976
|
}
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
977
|
+
consumeUsage(data?.usage);
|
|
978
|
+
responseId = data?.id;
|
|
979
|
+
actualModel = data?.model;
|
|
983
980
|
return {
|
|
984
981
|
text,
|
|
985
982
|
assistantContent: content,
|
|
986
983
|
toolCalls: extractAnthropicToolCalls(content),
|
|
987
|
-
usage:
|
|
984
|
+
usage: turnUsage,
|
|
985
|
+
responseId,
|
|
986
|
+
actualModel,
|
|
988
987
|
};
|
|
989
988
|
},
|
|
990
989
|
onEvent: ({ event, data }) => {
|
|
@@ -999,26 +998,14 @@ async function runAnthropicTurn({
|
|
|
999
998
|
}
|
|
1000
999
|
|
|
1001
1000
|
if (event === "message_start") {
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
: null
|
|
1006
|
-
);
|
|
1007
|
-
if (messageUsage) {
|
|
1008
|
-
usageObserved = true;
|
|
1009
|
-
turnUsage.input = messageUsage.input;
|
|
1010
|
-
turnUsage.cacheRead = messageUsage.cacheRead;
|
|
1011
|
-
turnUsage.cacheCreation = messageUsage.cacheCreation;
|
|
1012
|
-
}
|
|
1001
|
+
consumeUsage(payloadChunk.message?.usage);
|
|
1002
|
+
responseId = payloadChunk.message?.id;
|
|
1003
|
+
actualModel = payloadChunk.message?.model;
|
|
1013
1004
|
return;
|
|
1014
1005
|
}
|
|
1015
1006
|
|
|
1016
1007
|
if (event === "message_delta") {
|
|
1017
|
-
|
|
1018
|
-
? payloadChunk.usage
|
|
1019
|
-
: {};
|
|
1020
|
-
if (deltaUsage.output_tokens != null && Number.isFinite(Number(deltaUsage.output_tokens))) usageObserved = true;
|
|
1021
|
-
turnUsage.output += toUsageInt(deltaUsage.output_tokens);
|
|
1008
|
+
consumeUsage(payloadChunk.usage);
|
|
1022
1009
|
return;
|
|
1023
1010
|
}
|
|
1024
1011
|
|
|
@@ -1178,7 +1165,9 @@ async function runAnthropicTurn({
|
|
|
1178
1165
|
text: responseText,
|
|
1179
1166
|
assistantContent,
|
|
1180
1167
|
toolCalls: extractAnthropicToolCalls(assistantContent),
|
|
1181
|
-
usage:
|
|
1168
|
+
usage: turnUsage,
|
|
1169
|
+
responseId,
|
|
1170
|
+
actualModel,
|
|
1182
1171
|
};
|
|
1183
1172
|
},
|
|
1184
1173
|
});
|
|
@@ -15,6 +15,16 @@ const DEFAULT_KIMI_MODEL = "k3";
|
|
|
15
15
|
|
|
16
16
|
const { normalizeProvider } = require("./providerId");
|
|
17
17
|
|
|
18
|
+
function resolveResponsesRequestProfile(baseUrl, credentialKind = "") {
|
|
19
|
+
let url;
|
|
20
|
+
try { url = new URL(baseUrl); } catch { return "responses-compatible"; }
|
|
21
|
+
if (url.origin === "https://chatgpt.com" && /^\/backend-api\/codex(?:\/responses)?\/?$/.test(url.pathname)
|
|
22
|
+
&& credentialKind === "oauth") return "codex-subscription";
|
|
23
|
+
if (url.origin === "https://api.openai.com" && /^\/v1(?:\/responses)?\/?$/.test(url.pathname)
|
|
24
|
+
&& credentialKind !== "oauth") return "openai-responses";
|
|
25
|
+
return "responses-compatible";
|
|
26
|
+
}
|
|
27
|
+
|
|
18
28
|
function normalizeKimiModel(value = "") {
|
|
19
29
|
const raw = String(value || "").trim();
|
|
20
30
|
if (!raw) return "";
|
|
@@ -159,6 +169,7 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
|
|
|
159
169
|
apiKeySource,
|
|
160
170
|
kimiCredentialState,
|
|
161
171
|
transport: resolveTransport({ provider: selectedProvider, baseUrl }),
|
|
172
|
+
requestProfile: selectedProvider === "codex" ? resolveResponsesRequestProfile(baseUrl, apiKey ? "api-key" : "") : "",
|
|
162
173
|
allowUnlistedModels: custom,
|
|
163
174
|
};
|
|
164
175
|
}
|
|
@@ -185,11 +196,11 @@ async function resolveAuthenticatedRuntime(options = {}) {
|
|
|
185
196
|
runtime.apiKeySource = String(credential.source || "codex-credential");
|
|
186
197
|
}
|
|
187
198
|
if (credential?.credentialKind === "api-key"
|
|
188
|
-
&& !String(process.env.UFOO_UCODE_BASE_URL || "").trim()
|
|
189
|
-
&& !String(config.ucodeBaseUrl || "").trim()) {
|
|
199
|
+
&& !(options.useCodingConfig !== false && String(process.env.UFOO_UCODE_BASE_URL || config.ucodeBaseUrl || "").trim())) {
|
|
190
200
|
runtime.baseUrl = String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL).trim();
|
|
191
201
|
}
|
|
192
|
-
|
|
202
|
+
runtime.requestProfile = resolveResponsesRequestProfile(runtime.baseUrl, credential?.credentialKind);
|
|
203
|
+
if (runtime.requestProfile === "codex-subscription") accountId = String(credential.accountId || "").trim();
|
|
193
204
|
} catch { /* Requests surface missing/invalid credentials. */ }
|
|
194
205
|
}
|
|
195
206
|
if (runtime.provider === "kimi" && runtime.apiKeySource === "kimi-credential" && runtime.kimiCredentialState !== "fresh") {
|
|
@@ -232,4 +243,4 @@ function resolveAnthropicMessagesUrl(baseUrl = "") {
|
|
|
232
243
|
return `${normalized}/messages`;
|
|
233
244
|
}
|
|
234
245
|
|
|
235
|
-
module.exports = { normalizeProvider, normalizeKimiModel, resolveTransport, resolveRuntimeConfig, resolveAuthenticatedRuntime, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl, DEFAULT_OPENAI_BASE_URL };
|
|
246
|
+
module.exports = { normalizeProvider, normalizeKimiModel, resolveTransport, resolveRuntimeConfig, resolveAuthenticatedRuntime, resolveResponsesRequestProfile, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl, DEFAULT_OPENAI_BASE_URL };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const MAX_BREAKPOINTS = 4;
|
|
4
|
+
const CACHE_CONTROL = Object.freeze({ type: "ephemeral" });
|
|
5
|
+
const STABLE_HISTORY_BOUNDARY = Symbol.for("ufoo.stableHistoryBoundary");
|
|
6
|
+
const CACHEABLE_MESSAGE_BLOCKS = new Set(["text", "image", "document", "tool_use", "tool_result", "search_result"]);
|
|
7
|
+
|
|
8
|
+
function withoutCacheControl(block) {
|
|
9
|
+
if (!block || typeof block !== "object" || Array.isArray(block)) return block;
|
|
10
|
+
const { cache_control: ignored, ...clean } = block;
|
|
11
|
+
if (Array.isArray(clean.content)) clean.content = clean.content.map(withoutCacheControl);
|
|
12
|
+
return clean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function messageBlockCanCache(block) {
|
|
16
|
+
return CACHEABLE_MESSAGE_BLOCKS.has(block?.type)
|
|
17
|
+
&& (block.type !== "text" || typeof block.text === "string" && Boolean(block.text.trim()));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function applyAnthropicCacheBreakpoints(payload) {
|
|
21
|
+
const selected = new Set();
|
|
22
|
+
const explicit = [];
|
|
23
|
+
const order = [];
|
|
24
|
+
function boundary(block, write, cacheable = true) {
|
|
25
|
+
if (!cacheable) return null;
|
|
26
|
+
const control = block?.cache_control;
|
|
27
|
+
const entry = { write, control: control?.type === "ephemeral" ? control : CACHE_CONTROL };
|
|
28
|
+
order.push(entry);
|
|
29
|
+
if (control?.type === "ephemeral") explicit.push(entry);
|
|
30
|
+
return entry;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
payload.tools = payload.tools.map((tool, index) => {
|
|
34
|
+
boundary(tool, control => { payload.tools[index].cache_control = control; }, !tool.defer_loading);
|
|
35
|
+
return withoutCacheControl(tool);
|
|
36
|
+
});
|
|
37
|
+
const system = [];
|
|
38
|
+
if (Array.isArray(payload.system)) {
|
|
39
|
+
payload.system = payload.system.map((block, index) => {
|
|
40
|
+
if (block.cache_control) system.push(boundary(block, control => { payload.system[index].cache_control = control; }, messageBlockCanCache(block)));
|
|
41
|
+
return withoutCacheControl(block);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let history = null;
|
|
46
|
+
let latest = null;
|
|
47
|
+
payload.messages = payload.messages.map((message, messageIndex) => {
|
|
48
|
+
if (!message || typeof message !== "object") return message;
|
|
49
|
+
const original = message.content;
|
|
50
|
+
const blocks = typeof original === "string" ? [{ type: "text", text: original }] : original;
|
|
51
|
+
if (!Array.isArray(blocks)) return message;
|
|
52
|
+
const clean = blocks.map(withoutCacheControl);
|
|
53
|
+
for (const [blockIndex, block] of blocks.entries()) {
|
|
54
|
+
const entry = boundary(block, control => {
|
|
55
|
+
clean[blockIndex].cache_control = control;
|
|
56
|
+
payload.messages[messageIndex].content = clean;
|
|
57
|
+
}, messageBlockCanCache(block));
|
|
58
|
+
if (entry) latest = entry;
|
|
59
|
+
}
|
|
60
|
+
if (message[STABLE_HISTORY_BOUNDARY]) history = latest;
|
|
61
|
+
return { ...message, content: typeof original === "string" ? original : clean };
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
for (const entry of [system.at(-1), history, latest, ...system.slice(0, -1).reverse(), ...explicit.reverse()]) {
|
|
65
|
+
if (selected.size === MAX_BREAKPOINTS) break;
|
|
66
|
+
if (entry) selected.add(entry);
|
|
67
|
+
}
|
|
68
|
+
// The wire API requires all longer-lived breakpoints to precede short ones.
|
|
69
|
+
let sawShort = false;
|
|
70
|
+
for (const entry of order) {
|
|
71
|
+
if (!selected.has(entry)) continue;
|
|
72
|
+
if (entry.control.ttl === "1h" && sawShort) continue;
|
|
73
|
+
entry.write(entry.control);
|
|
74
|
+
if (entry.control.ttl !== "1h") sawShort = true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = { applyAnthropicCacheBreakpoints };
|
|
@@ -126,7 +126,7 @@ function agyThinkingConfig(model, effort) {
|
|
|
126
126
|
function createAntigravityTransport({ runSseRequest, parseSseEventBlock, ...messageDeps }) {
|
|
127
127
|
async function runTurn({
|
|
128
128
|
url, apiKey, model, sessionId, messages = [], tools = [], systemPrompt = "", systemBlocks = null,
|
|
129
|
-
thinkingLevel, maxOutputTokens, signal, timeoutMs, onTextDelta, onThinkingDelta, onPhase,
|
|
129
|
+
thinkingLevel, maxOutputTokens, signal, timeoutMs, onTextDelta, onThinkingDelta, onPhase, onRequest, requestScope, requestPurpose, strategyVersion,
|
|
130
130
|
}) {
|
|
131
131
|
const credential = await resolveAgyCredentials({ apiKey, baseUrl: url, signal });
|
|
132
132
|
const claude = /^claude-/i.test(model);
|
|
@@ -176,7 +176,7 @@ function createAntigravityTransport({ runSseRequest, parseSseEventBlock, ...mess
|
|
|
176
176
|
input: Number(stats.promptTokenCount) || 0,
|
|
177
177
|
output: (Number(stats.candidatesTokenCount) || 0) + (Number(stats.thoughtsTokenCount) || 0),
|
|
178
178
|
cacheRead: stats.cachedContentTokenCount == null ? null : Number(stats.cachedContentTokenCount) || 0,
|
|
179
|
-
cacheCreation:
|
|
179
|
+
cacheCreation: null,
|
|
180
180
|
inputIncludesCache: true,
|
|
181
181
|
};
|
|
182
182
|
}
|
|
@@ -221,6 +221,7 @@ function createAntigravityTransport({ runSseRequest, parseSseEventBlock, ...mess
|
|
|
221
221
|
const onEvent = ({ data }) => consume(JSON.parse(data));
|
|
222
222
|
return runSseRequest({
|
|
223
223
|
url, headers: { ...buildAgyHeaders(credential), Accept: "text/event-stream" }, payload, signal, timeoutMs, onPhase,
|
|
224
|
+
onRequest, requestObservation: { transport: "antigravity", sessionId, requestScope, requestPurpose, strategyVersion },
|
|
224
225
|
onNonStream(data) {
|
|
225
226
|
for (const chunk of Array.isArray(data) ? data : [data]) consume(chunk);
|
|
226
227
|
return buildResult();
|
|
@@ -14,9 +14,8 @@ const { attachResponsesReasoningItems } = require("./responsesProtocol");
|
|
|
14
14
|
* OpenAI Responses transport adapter.
|
|
15
15
|
*
|
|
16
16
|
* The loop keeps the public, provider-neutral message projection in the same
|
|
17
|
-
* shape as the Chat transport. The
|
|
18
|
-
*
|
|
19
|
-
* Session Journal.
|
|
17
|
+
* shape as the Chat transport. The versioned continuation field carries the
|
|
18
|
+
* ordered Responses items needed to rebuild a later stateless request.
|
|
20
19
|
*/
|
|
21
20
|
function createOpenAiResponsesTransport(deps = {}) {
|
|
22
21
|
const {
|
|
@@ -27,6 +26,8 @@ function createOpenAiResponsesTransport(deps = {}) {
|
|
|
27
26
|
toJsonString,
|
|
28
27
|
clipText,
|
|
29
28
|
} = deps;
|
|
29
|
+
const appendContinuation = (message, result) => attachResponsesReasoningItems(message,
|
|
30
|
+
Array.isArray(result?.outputItems) ? { output: result.outputItems } : result?.response, result?.responsesRequest);
|
|
30
31
|
|
|
31
32
|
const transport = {
|
|
32
33
|
name: "openai-responses",
|
|
@@ -47,10 +48,10 @@ function createOpenAiResponsesTransport(deps = {}) {
|
|
|
47
48
|
appendFinalAssistantMessage({ messages, turnResult }) {
|
|
48
49
|
const text = String(turnResult.text || "").trim();
|
|
49
50
|
if (text) {
|
|
50
|
-
messages.push({
|
|
51
|
+
messages.push(appendContinuation({
|
|
51
52
|
role: "assistant",
|
|
52
53
|
content: text,
|
|
53
|
-
});
|
|
54
|
+
}, turnResult));
|
|
54
55
|
}
|
|
55
56
|
},
|
|
56
57
|
prepareToolCalls({ messages, turnResult, toolCalls }) {
|
|
@@ -79,13 +80,7 @@ function createOpenAiResponsesTransport(deps = {}) {
|
|
|
79
80
|
content: text || null,
|
|
80
81
|
tool_calls: assistantToolCalls,
|
|
81
82
|
};
|
|
82
|
-
|
|
83
|
-
assistantMessage,
|
|
84
|
-
turnResult && Array.isArray(turnResult.outputItems)
|
|
85
|
-
? { output: turnResult.outputItems }
|
|
86
|
-
: (turnResult && turnResult.response),
|
|
87
|
-
);
|
|
88
|
-
messages.push(assistantMessage);
|
|
83
|
+
messages.push(appendContinuation(assistantMessage, turnResult));
|
|
89
84
|
|
|
90
85
|
return assistantToolCalls.map((toolCall) => ({
|
|
91
86
|
name: toolCall.function.name,
|