Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions cli/openai-bridge-retry.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
const DEFAULT_BRIDGE_MAX_RETRIES = 2;
const MIN_BRIDGE_MAX_RETRIES = 2;
const MAX_BRIDGE_MAX_RETRIES = 10;
const DEFAULT_BRIDGE_MAX_RETRIES = Infinity;
const BASE_TRANSIENT_RETRY_DELAY_MS = 200;
const MAX_TRANSIENT_RETRY_DELAY_MS = 5000;

function normalizeBridgeMaxRetries(value, fallback = DEFAULT_BRIDGE_MAX_RETRIES) {
const raw = Number(value);
const fallbackRaw = Number(fallback);
const base = Number.isFinite(raw) ? raw : (Number.isFinite(fallbackRaw) ? fallbackRaw : DEFAULT_BRIDGE_MAX_RETRIES);
return Math.min(MAX_BRIDGE_MAX_RETRIES, Math.max(MIN_BRIDGE_MAX_RETRIES, Math.floor(base)));
if (Number.isFinite(raw) && raw >= 0) return Math.floor(raw);
if (Number.isFinite(fallbackRaw) && fallbackRaw >= 0) return Math.floor(fallbackRaw);
return DEFAULT_BRIDGE_MAX_RETRIES;
}


function isTransientHttpStatus(status) {
const code = Number(status);
if (code === 408 || code === 409 || code === 425 || code === 429) return true;
return code >= 500 && code <= 599;
}

function isTransientNetworkError(error) {
Expand All @@ -30,7 +36,7 @@ function getTransientRetryDelayMs(attempt) {
async function retryTransientRequest(executor, options = {}) {
const maxRetries = normalizeBridgeMaxRetries(options && options.maxRetries);
let lastResult = null;
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
for (let attempt = 0; attempt === 0 || attempt <= maxRetries; attempt += 1) {
if (attempt > 0) {
const delay = getTransientRetryDelayMs(attempt);
// eslint-disable-next-line no-await-in-loop
Expand All @@ -43,20 +49,22 @@ async function retryTransientRequest(executor, options = {}) {
const result = await executor(attempt);
lastResult = result;
if (!result) return result;
if (result.status && result.status > 0) {
if (!isTransientHttpStatus(result.status)) return result;
continue;
}
if (result.ok) return result;
if (result.retry) return result;
if (result.status && result.status > 0) return result;
if (!isTransientNetworkError(result.error)) return result;
}
return lastResult;
}

module.exports = {
DEFAULT_BRIDGE_MAX_RETRIES,
MIN_BRIDGE_MAX_RETRIES,
MAX_BRIDGE_MAX_RETRIES,
normalizeBridgeMaxRetries,
isTransientNetworkError,
isTransientHttpStatus,
getTransientRetryDelayMs,
retryTransientRequest
};
15 changes: 14 additions & 1 deletion cli/openai-bridge-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -1472,7 +1472,20 @@ function streamChatCompletionsAsResponsesSse(targetUrl, options = {}) {
response: {
id: state.responseId,
model: state.model,
created_at: state.createdAt
created_at: state.createdAt,
status: 'in_progress',
output: []
}
});
writeSse(res, 'response.in_progress', {
type: 'response.in_progress',
sequence_number: state.nextSeq(),
response: {
id: state.responseId,
model: state.model,
created_at: state.createdAt,
status: 'in_progress',
output: []
Comment on lines +1475 to +1488

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu
sed -n '1468,1492p' cli/openai-bridge-runtime.js
rg -n -A8 -B4 'response\.created|response\.in_progress|sequence_number' tests/unit/openai-bridge-upstream-responses.test.mjs

Repository: SakuraByteCore/codexmate

Length of output: 997


🏁 Script executed:

#!/bin/bash
set -eu

printf '\n== response event emitters ==\n'
rg -n -A6 -B4 "writeSse\\(res, 'response\\.(created|in_progress|completed|failed|incomplete)'" cli/openai-bridge-runtime.js

printf '\n== sequence number helpers/usages ==\n'
rg -n "nextSeq\\(|sequence_number" cli tests --glob '!**/node_modules/**'

printf '\n== response streaming tests ==\n'
sed -n '1,260p' tests/unit/openai-bridge-upstream-responses.test.mjs

Repository: SakuraByteCore/codexmate

Length of output: 17661


🏁 Script executed:

#!/bin/bash
set -eu

printf '\n== shared Responses SSE emitter ==\n'
sed -n '800,920p' cli/openai-bridge-runtime.js

printf '\n== tests mentioning response.created or sequence_number ==\n'
rg -n -A4 -B4 "response\\.created|response\\.in_progress|sequence_number" tests cli/openai-bridge-runtime.js cli/openai-bridge.js

printf '\n== response SSE parsing helpers in tests ==\n'
rg -n -A5 -B5 "event: 'response\\.|type: 'response\\.|sequence_number" tests/unit/openai-bridge-upstream-responses.test.mjs

Repository: SakuraByteCore/codexmate

Length of output: 18992


🌐 Web query:

OpenAI Responses streaming schema response.created sequence_number required response.in_progress

💡 Result:

In the OpenAI Responses API, streaming events follow a structured schema that includes both type and sequence_number fields [1][2]. Key Event Types: - response.created: Emitted immediately after a response is created. It includes the response object and the sequence_number [2][3]. - response.in_progress: Emitted while the response is being generated. Like other lifecycle events, it includes the response object and the sequence_number [2][3]. Sequence Number: The sequence_number is a required integer field for streaming events in the Responses API [1][4][5]. It is monotonically increasing for each stream and is used by clients to enforce correct event ordering and to ignore duplicate events [6]. Documentation and Implementation: Official OpenAI documentation defines these events with a specific schema [1]. Client libraries, such as the official Node.js SDK, define these events in their type definitions (e.g., ResponseCreatedEvent and ResponseInProgressEvent) as requiring both a type and a sequence_number [7][2]. While the API specification mandates these fields, developers have noted that implementation behavior can occasionally deviate from the spec in specific scenarios (such as error events), requiring robust handling in client implementations [5]. Note: This structure specifically applies to the Responses API (often used in the context of the Assistants API/Realtime capabilities) and differs from the traditional Chat Completions streaming API, which utilizes a different chunk-based structure (chat.completion.chunk) [8][9][10].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu

printf '\n== local docs for Responses sequencing ==\n'
rg -n "sequence_number|response\\.created|response\\.in_progress|Responses streaming|streaming schema" README* docs cli tests --glob '!**/node_modules/**'

printf '\n== all response.created emitters ==\n'
rg -n -A5 -B3 "writeSse\\(res, 'response\\.created'" cli tests

Repository: SakuraByteCore/codexmate

Length of output: 4152


Add sequence_number to response.created. This lifecycle event is missing the top-level ordering field, so it doesn’t match the Responses streaming schema; response.in_progress should keep the next sequence value.

Proposed fix
                     created_at: state.createdAt,
                     status: 'in_progress',
                     output: []
-                }
+                },
+                sequence_number: state.nextSeq()
             });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
created_at: state.createdAt,
status: 'in_progress',
output: []
}
});
writeSse(res, 'response.in_progress', {
type: 'response.in_progress',
sequence_number: state.nextSeq(),
response: {
id: state.responseId,
model: state.model,
created_at: state.createdAt,
status: 'in_progress',
output: []
created_at: state.createdAt,
status: 'in_progress',
output: []
},
sequence_number: state.nextSeq()
});
writeSse(res, 'response.in_progress', {
type: 'response.in_progress',
sequence_number: state.nextSeq(),
response: {
id: state.responseId,
model: state.model,
created_at: state.createdAt,
status: 'in_progress',
output: []
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/openai-bridge-runtime.js` around lines 1475 - 1488, Add the next sequence
value to the top-level payload of the response.created event, matching the
Responses streaming schema. Keep response.in_progress using its existing
state.nextSeq() call and do not alter its ordering behavior.

Source: MCP tools

}
});

Expand Down
30 changes: 20 additions & 10 deletions cli/openai-bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ function normalizeOpenaiUpstreamBaseUrl(rawValue) {
}

const {
normalizeBridgeMaxRetries,
parseJsonOrError,
extractChatCompletionResult,
convertResponsesRequestToChatCompletions,
Expand All @@ -114,11 +113,10 @@ function normalizeUpstreamEntry(entry) {
const apiKey = normalizeText(entry.apiKey || entry.api_key || entry.key || '');
const headersRaw = entry.headers || entry.extraHeaders || entry.extra_headers || null;
const headers = normalizeHeadersMap(headersRaw);
const maxRetries = normalizeBridgeMaxRetries(entry.maxRetries ?? entry.max_retries);
if (!baseUrl || !isValidHttpUrl(baseUrl)) {
return null;
}
return { baseUrl, apiKey, headers, maxRetries };
return { baseUrl, apiKey, headers };
}

function normalizeHeadersMap(value) {
Expand Down Expand Up @@ -169,7 +167,6 @@ function upsertOpenaiBridgeProvider(filePath, providerName, upstreamBaseUrl, api
const baseUrl = normalizeOpenaiUpstreamBaseUrl(upstreamBaseUrl);
const key = normalizeText(apiKey);
const nextHeaders = normalizeHeadersMap(headers);
const maxRetries = normalizeBridgeMaxRetries(options && options.maxRetries);

if (!name) {
return { error: 'Provider name is required' };
Expand All @@ -191,7 +188,6 @@ function upsertOpenaiBridgeProvider(filePath, providerName, upstreamBaseUrl, api
baseUrl,
apiKey: key,
headers: Object.keys(nextHeaders).length ? nextHeaders : existingHeaders,
maxRetries
}
}
};
Expand Down Expand Up @@ -384,7 +380,7 @@ function createOpenaiBridgeHttpHandler(options = {}) {
maxBytes: maxUpstreamBytes,
httpAgent,
httpsAgent
}), { maxRetries: upstream.maxRetries });
}));
if (!result.ok) {
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ error: `Upstream request failed: ${result.error}` }));
Expand Down Expand Up @@ -446,7 +442,7 @@ function createOpenaiBridgeHttpHandler(options = {}) {
res,
model: typeof chatBody.model === 'string' ? chatBody.model : '',
toolTypesByName: converted.toolTypesByName || {}
}), { maxRetries: upstream.maxRetries });
}));
if (!streamed.ok) {
if (res.writableEnded || res.destroyed) {
return;
Expand All @@ -471,7 +467,7 @@ function createOpenaiBridgeHttpHandler(options = {}) {
maxBytes: maxUpstreamBytes,
httpAgent,
httpsAgent
}), { maxRetries: upstream.maxRetries });
}));
if (!upstreamResult.ok) {
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
Expand Down Expand Up @@ -514,8 +510,23 @@ function createOpenaiBridgeHttpHandler(options = {}) {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(ensureResponseMetadata(responsesPayload)));
} catch (e) {
if (res.writableEnded || res.destroyed) {
return;
}
const message = e && e.message ? e.message : 'Internal Error';
if (res.headersSent) {
try {
res.end();
} catch (_) {
// Headers are already committed. Close the socket instead of leaving the client waiting forever.
if (!res.destroyed && typeof res.destroy === 'function') {
res.destroy(e);
}
}
return;
}
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
res.end(JSON.stringify({ error: message }));
}
})();

Expand Down Expand Up @@ -543,7 +554,6 @@ module.exports = {
extractChatCompletionResult,
buildResponsesPayloadFromChatResult,
retryTransientRequest,
normalizeBridgeMaxRetries,
normalizeOpenaiUpstreamBaseUrl,
extractResponsesOutputText,
shouldFallbackFromUpstreamResponses,
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "codexmate",
"version": "0.1.1",
"version": "0.1.2",
"description": "Codex/Claude Code/OpenClaw 配置、会话与任务编排 CLI + Web 工具",
"main": "cli.js",
"bin": {
Expand Down
Loading
Loading