codex-copilot-dx 1.3.6 → 1.3.7
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 +2 -2
- package/docs/ARCHITECTURE.md +4 -2
- package/docs/REFERENCE.md +4 -0
- package/package.json +6 -2
- package/src/claude-gateway.mjs +2 -1
- package/src/dashboard/language.js +1 -0
- package/src/dashboard/status.js +2 -1
- package/src/local-privacy.mjs +1 -0
- package/src/privacy-model.mjs +6 -4
- package/src/privacy-transform.mjs +39 -25
- package/src/response-failures.mjs +8 -2
- package/src/responses-handler.mjs +2 -2
- package/src/responses-proxy.mjs +1 -1
- package/src/stream-performance.mjs +2 -2
package/README.md
CHANGED
|
@@ -17,8 +17,8 @@ ccdx
|
|
|
17
17
|
|
|
18
18
|
Without Node.js, download and run the installer for your system:
|
|
19
19
|
|
|
20
|
-
- macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.
|
|
21
|
-
- Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.
|
|
20
|
+
- macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.7/install.sh), then `sh install.sh`.
|
|
21
|
+
- Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.7/install.ps1), then `./install.ps1` under your current shell policy.
|
|
22
22
|
|
|
23
23
|
The installer reuses a compatible Node.js or installs a private, verified copy. Git and a compiler are not required. Complete platform packages include their dependencies. Company registry, proxy, certificate and shell policies are kept.
|
|
24
24
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -1056,9 +1056,9 @@ changes, rotation, incomplete tails, warnings and oversized results rebuild thro
|
|
|
1056
1056
|
the original full scan. No persistent index, polling or per-token work is added.
|
|
1057
1057
|
### Local masking boundary
|
|
1058
1058
|
|
|
1059
|
-
`local-privacy.mjs` owns explicit consent, per-request policy snapshots, a private placeholder seed and bounded shared detection metadata. It wraps provider calls after authorization/model resolution without changing the prepared request used by local history. Completed history records restore client-visible values while signed and encrypted state stays opaque. `privacy-transform.mjs` projects
|
|
1059
|
+
`local-privacy.mjs` owns explicit consent, per-request policy snapshots, a private placeholder seed and bounded shared detection metadata. It wraps provider calls after authorization/model resolution without changing the prepared request used by local history. Completed history records restore client-visible values while signed and encrypted state stays opaque. `privacy-transform.mjs` projects supported text fields, including Responses Lite inline tool descriptions. Tool data has its own recursive restoration context, so field names and values that resemble protocol state do not exempt ordinary arguments. Restored SSE fragments retain their wire metadata; Responses custom tool input shares text's cross-fragment restoration. Tool JSON is emitted once complete, before its terminal block, and incomplete parameters are discarded on an upstream failure. It does not take ownership of credentials or select providers.
|
|
1060
1060
|
|
|
1061
|
-
`privacy-model.mjs` owns verified, optional downloads and a stdio-only child process. The npm dependency graph is unchanged. Model files are revision/SHA256 pinned; the executable is verified against the fixed component Release's checksum manifest. The downloader reuses the selected npm's network policy. Startup warms only already-downloaded, explicitly enabled protection; opening Settings never downloads a model.
|
|
1061
|
+
`privacy-model.mjs` owns verified, optional downloads and a stdio-only child process. The production npm dependency graph is unchanged. Model files are revision/SHA256 pinned; the executable is verified against the fixed component Release's checksum manifest. The downloader reuses the selected npm's network policy. Startup warms only already-downloaded, explicitly enabled protection; opening Settings never downloads a model.
|
|
1062
1062
|
|
|
1063
1063
|
Disabled calls retain their original provider function and body. Enabled calls await a complete check. A frontend check deadline rejects without contacting the provider; shared native work is bounded and may populate the metadata cache for another waiter. Cancellation does not cancel another request's shared work. Native input, jobs, cache and reply buffers have finite budgets; no prompt or mapping database is introduced. The child inherits only required system environment fields, not API keys or sign-in tokens.
|
|
1064
1064
|
|
|
@@ -1066,4 +1066,6 @@ The Magpie-derived Go tokenizer/INT8 classifier is built for four macOS/Windows
|
|
|
1066
1066
|
|
|
1067
1067
|
Progress and readiness share the existing coalesced activity SSE. The settings controller only reads status while visible and uses a bounded-action fallback when event updates are absent. Main-page preference revisions are refreshed after masking choices change. Protected request details add replacement count and local-check duration; other request rows retain their current layout.
|
|
1068
1068
|
|
|
1069
|
+
Local privacy failures carry a separate origin. Request-check and response-restoration messages state different outcomes. Explicit failed tool results in the latest Messages input add only a count to request metadata, without retaining their content or changing a successful model response into a claim of tool-workflow success. SDK tests use independent client parsers; native CLI replays execute a local MCP fixture in temporary profiles, return its result and require the following response to complete.
|
|
1070
|
+
|
|
1069
1071
|
Claude passthrough now holds incomplete SSE frames and validates complete data before forwarding. Malformed tails do not precede the terminal error; valid final JSON without a newline remains deliverable. Capability restoration and replacement writes use the existing ownership journal in one transaction, preserving both files and ownership on failure.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -746,10 +746,14 @@ Covered text includes conversation instructions, message text, tool results, too
|
|
|
746
746
|
|
|
747
747
|
Rules and a local model replace detected values with stable placeholders. Replies and tool arguments restore their values before delivery. The placeholder seed is private local configuration; original-value mappings live only with the request and are never added to CCDX logs or backups. A restart retains the seed, not the mappings. Local history keeps client-visible text rather than placeholders.
|
|
748
748
|
|
|
749
|
+
Tool data is interpreted in its own context: ordinary argument fields named `id`, `signature`, `data` or `type` are restored, while protocol identifiers and signed blocks remain unchanged. Streaming restoration retains SSE event metadata and restores Responses custom-tool text across fragments. Incomplete parameters are discarded when the upstream emits a failure rather than replacing that failure with a restoration error.
|
|
750
|
+
|
|
749
751
|
Each request pins its masking choice, including compatibility retries. A check exceeding 15 seconds is rejected before any upstream call; bounded local work can continue for up to five minutes so a retry can reuse its complete results. No request is sent using an incomplete model check. Model work is capped at eight jobs and 16 MiB queued input; text input per call is capped at 8 MiB. Detection metadata uses a 5,000-entry/4 MiB memory cache. CPU-only first checks of long histories can take substantially longer than cached checks.
|
|
750
752
|
|
|
751
753
|
Turning masking off affects subsequent requests. Existing protected replies keep their restoration mappings until they finish. The downloaded component can then be deleted separately. Settings reset backs up and resets masking choices while keeping accounts, model selections, client connections, images and prediction access. Older settings backups inherit masking off.
|
|
752
754
|
|
|
753
755
|
Try locally sends sample text only to the local component. Request records show the number of replacements and elapsed local-check time, never the original values. Download failures keep protection off; configured but unavailable protection refuses covered requests. Downloads retain the selected npm's proxy, certificate and offline policy, with no automatic policy relaxation or alternate downloader.
|
|
754
756
|
|
|
757
|
+
Privacy failures have a separate local diagnostic origin. Response-restoration failures report that the response was stopped; request-check failures report that nothing was sent. When the latest Messages input explicitly contains failed tool results, request details show their count without retaining their content. HTTP success describes the model response, not proof that a client executed its tools successfully.
|
|
758
|
+
|
|
755
759
|
The optional component is pinned to the v1.3.6 Release; later code-only updates can reuse it. Its source and license notices are in `native/privacy-guard` and `src/privacy-notices.txt`. AstrLink Guard model files use their publisher's Apache-2.0 license.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-copilot-dx",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.7",
|
|
4
4
|
"description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
|
|
5
5
|
"author": "Dale Xiao",
|
|
6
6
|
"type": "module",
|
|
@@ -67,5 +67,9 @@
|
|
|
67
67
|
"cpu": [
|
|
68
68
|
"x64",
|
|
69
69
|
"arm64"
|
|
70
|
-
]
|
|
70
|
+
],
|
|
71
|
+
"devDependencies": {
|
|
72
|
+
"@anthropic-ai/sdk": "1.3.0",
|
|
73
|
+
"openai": "7.43.0"
|
|
74
|
+
}
|
|
71
75
|
}
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -150,6 +150,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
150
150
|
abort.setTimeout(config.upstreamTimeoutMs, "messages_prepare_timeout");
|
|
151
151
|
observeRequestedModel(body);
|
|
152
152
|
context.requestOptions = requestOptionsEvidence(body);
|
|
153
|
+
if (context.requestOptions.client_tool_errors_received) markRequestObservation({ client_tool_errors_received: context.requestOptions.client_tool_errors_received });
|
|
153
154
|
if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
|
|
154
155
|
send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
|
|
155
156
|
}
|
|
@@ -257,7 +258,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
257
258
|
const detail = operationErrorDetails(error, { reason: abort.reason });
|
|
258
259
|
outcome = detail.source === "cancelled" ? "cancelled" : "failed";
|
|
259
260
|
const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
|
|
260
|
-
failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
|
|
261
|
+
failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : error.origin === "privacy" ? "privacy" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
|
|
261
262
|
context.errorOrigin = terminalOrigin;
|
|
262
263
|
const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
|
|
263
264
|
const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
|
|
@@ -142,6 +142,7 @@
|
|
|
142
142
|
"output_used": ["Returned output tokens", "返回输出用量"],
|
|
143
143
|
"stop_reason": ["Stop reason", "停止原因"],
|
|
144
144
|
"transport": ["Network details", "网络详情"],
|
|
145
|
+
"client_tool_errors_received": ["Client-reported tool errors", "客户端回传的工具错误"],
|
|
145
146
|
"output_limit_reached": ["Output limit reached.", "本次生成达到输出上限。"],
|
|
146
147
|
"source_connection_failed": ["Connection to the model source failed.", "与模型来源的连接失败。"],
|
|
147
148
|
"issue_category": ["Issue category", "问题分类"],
|
package/src/dashboard/status.js
CHANGED
|
@@ -389,7 +389,8 @@
|
|
|
389
389
|
["time", Number.isFinite(at) ? time(at, { date: true }) : "—"],
|
|
390
390
|
["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
|
|
391
391
|
["images", number(context.images)], ["model_window", number(context.context_window_tokens)], ["input_window", ratio],
|
|
392
|
-
["output_requested", number(context.max_output_tokens_requested)], ["output_sent", number(context.max_output_tokens_sent)], ["output_used", number(context.output_tokens)], ["stop_reason", request.stop_reason || "—"]
|
|
392
|
+
["output_requested", number(context.max_output_tokens_requested)], ["output_sent", number(context.max_output_tokens_sent)], ["output_used", number(context.output_tokens)], ["stop_reason", request.stop_reason || "—"],
|
|
393
|
+
...(context.client_tool_errors_received > 0 ? [["client_tool_errors_received", number(context.client_tool_errors_received)]] : [])]) {
|
|
393
394
|
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);detail.textContent = value;fields.append(term, detail);
|
|
394
395
|
}
|
|
395
396
|
row.children[5].append(details);body.append(row);
|
package/src/local-privacy.mjs
CHANGED
|
@@ -82,6 +82,7 @@ export function createLocalPrivacy(options = {}) {
|
|
|
82
82
|
current = { count: session.count, sessions,
|
|
83
83
|
restoreText: value => sessions.reduce((text, item) => item.restoreText(text), value),
|
|
84
84
|
restoreValue: value => sessions.reduce((text, item) => item.restoreValue(text), value),
|
|
85
|
+
restoreToolValue: value => sessions.reduce((text, item) => item.restoreToolValue(text), value),
|
|
85
86
|
release: () => { sessions.forEach(item => item.release());sessions.length = 0;responses.delete(res); } };
|
|
86
87
|
responses.set(res, current);sessions.push(session);protectPrivacyResponse(res, current);
|
|
87
88
|
} else current.sessions.push(session);
|
package/src/privacy-model.mjs
CHANGED
|
@@ -15,10 +15,12 @@ export const PRIVACY_MODEL_FILES = Object.freeze([
|
|
|
15
15
|
{ name: "tokenizer.json", bytes: 1502881, sha256: "0cf3b235ef125658015a6c8026a5fe6f28088bf825101a990ec18a10200feef4" },
|
|
16
16
|
]);
|
|
17
17
|
export const PRIVACY_DOWNLOAD_BYTES = PRIVACY_MODEL_FILES.reduce((n, file) => n + file.bytes, 0);
|
|
18
|
-
export
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
18
|
+
export function privacyFailure(code, phase = "check") {
|
|
19
|
+
const message = phase === "response" ? "Local privacy response restoration failed. The response was stopped; review Settings."
|
|
20
|
+
: "Local privacy check could not finish. Nothing was sent; review Settings.";
|
|
21
|
+
return Object.assign(new Error(message), { code: `ccdx_privacy_${code}`, statusCode: 503, origin: "privacy",
|
|
22
|
+
jsonBody: { error: { type: "api_error", code: `ccdx_privacy_${code}`, message } } });
|
|
23
|
+
}
|
|
22
24
|
const digest = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
23
25
|
export function privacyPaths({ home = os.homedir(), env = process.env, platform = process.platform, arch = process.arch } = {}) {
|
|
24
26
|
const root = path.join(env.XDG_CACHE_HOME || (platform === "win32" ? env.LOCALAPPDATA || path.join(home, "AppData", "Local") : path.join(home, ".cache")), "codex-copilot-dx", "privacy");
|
|
@@ -9,12 +9,12 @@ const secretPatterns = [
|
|
|
9
9
|
];
|
|
10
10
|
const secretField = /(?:["']?\b(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password)\b["']?\s*[:=]\s*)(?:"((?:\\.|[^"\\\r\n])+)"|'((?:\\.|[^'\\\r\n])+)'|([^\s,;\r\n}]+))/gdi;
|
|
11
11
|
const personalKinds = new Set(["email", "phone", "account", "payment_card", "private_address", "private_date", "private_person"]);
|
|
12
|
-
const kept = new Set(["model", "id", "type", "role", "name", "call_id", "tool_use_id", "signature", "encrypted_content", "thought_signature", "thoughtSignature", "data", "url", "file_id"]);
|
|
12
|
+
const kept = new Set(["model", "id", "type", "role", "name", "namespace", "server_label", "server_name", "call_id", "tool_use_id", "item_id", "signature", "encrypted_content", "thought_signature", "thoughtSignature", "data", "url", "file_id", "previous_response_id", "prompt_cache_key", "media_type", "mime_type", "stop_reason", "finish_reason", "status", "object", "event"]);
|
|
13
13
|
function leaves(value, add, inArguments = false) {
|
|
14
14
|
if (typeof value === "string") return;
|
|
15
15
|
if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) typeof value[i] === "string" ? add(value, i, value[i], inArguments) : leaves(value[i], add, inArguments);return; }
|
|
16
16
|
if (!value || typeof value !== "object") return;
|
|
17
|
-
if (value.encrypted_content || ["thinking", "reasoning"].includes(value.type)) return;
|
|
17
|
+
if (!inArguments && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return;
|
|
18
18
|
for (const [key, item] of Object.entries(value)) {
|
|
19
19
|
if (!inArguments && kept.has(key)) continue;
|
|
20
20
|
if (typeof item === "string") add(value, key, item, inArguments);
|
|
@@ -50,7 +50,8 @@ function requestTexts(body, protocol) {
|
|
|
50
50
|
text(body, "instructions");
|
|
51
51
|
if (typeof body.input === "string") add(body, "input", body.input);
|
|
52
52
|
else for (const item of body.input || []) {
|
|
53
|
-
if (item.type
|
|
53
|
+
if (["additional_tools", "tool_search_output"].includes(item.type)) descriptions(item.tools);
|
|
54
|
+
else if (item.type === "function_call") args(item, "arguments");
|
|
54
55
|
else if (["function_call_output", "custom_tool_call_output"].includes(item.type)) text(item, "output");
|
|
55
56
|
else if (item.type === "custom_tool_call") text(item, "input");
|
|
56
57
|
else text(item, "content");
|
|
@@ -97,38 +98,52 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
|
|
|
97
98
|
}
|
|
98
99
|
if (total.count) for (const item of nested) item.parent[item.key] = JSON.stringify(item.value);
|
|
99
100
|
const restoreText = text => text.replace(tokenPattern, token => values.get(token) ?? token);
|
|
100
|
-
function restoreValue(value) {
|
|
101
|
+
function restoreValue(value, inToolData = false) {
|
|
101
102
|
if (typeof value === "string") return restoreText(value);
|
|
102
|
-
if (Array.isArray(value)) return value.map(restoreValue);
|
|
103
|
+
if (Array.isArray(value)) return value.map(item => restoreValue(item, inToolData));
|
|
103
104
|
if (!value || typeof value !== "object") return value;
|
|
104
|
-
if (value.encrypted_content || ["thinking", "reasoning"].includes(value.type)) return value;
|
|
105
|
-
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key,
|
|
106
|
-
: key === "arguments" && typeof item === "string" && item ? restoreArguments(item)
|
|
105
|
+
if (!inToolData && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return value;
|
|
106
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, !inToolData && kept.has(key) ? item
|
|
107
|
+
: !inToolData && key === "arguments" && typeof item === "string" && item ? restoreArguments(item)
|
|
108
|
+
: restoreValue(item, inToolData || key === "input" && ["tool_use", "server_tool_use", "mcp_tool_use"].includes(value.type))]));
|
|
107
109
|
}
|
|
108
|
-
function restoreArguments(text) { try { return JSON.stringify(restoreValue(JSON.parse(text))); } catch { return restoreText(text); } }
|
|
109
|
-
return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue,
|
|
110
|
+
function restoreArguments(text) { try { return JSON.stringify(restoreValue(JSON.parse(text), true)); } catch { return restoreText(text); } }
|
|
111
|
+
return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue,
|
|
112
|
+
restoreToolValue: value => restoreValue(value, true), release: () => values.clear() };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function rewritePrivacyFrame(wire, value, named = false) {
|
|
116
|
+
let written = false;
|
|
117
|
+
const lines = wire.split(/(?<=\n)/).map(line => {
|
|
118
|
+
if (!line.startsWith("data:")) return line;
|
|
119
|
+
if (written) return "";
|
|
120
|
+
written = true;
|
|
121
|
+
return `data: ${JSON.stringify(value)}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : ""}`;
|
|
122
|
+
}).join("");
|
|
123
|
+
return named && !/^event:/m.test(wire) ? `event: ${value.type}\n${lines}` : lines;
|
|
110
124
|
}
|
|
111
125
|
|
|
112
126
|
export function createPrivacyStream(session) {
|
|
127
|
+
const fail = code => privacyFailure(code, "response");
|
|
113
128
|
let pending = "", bytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
|
|
114
|
-
const frame = value => `data: ${JSON.stringify(value)}\n\n`;
|
|
115
129
|
function transform(wire) {
|
|
116
130
|
const data = wire.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
117
131
|
if (!data || data === "[DONE]") return wire;
|
|
118
|
-
let event;try { event = JSON.parse(data); } catch { throw
|
|
132
|
+
let event;try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
|
|
133
|
+
if (["error", "response.failed", "response.incomplete"].includes(event.type)) { channels.clear();return rewritePrivacyFrame(wire, session.restoreValue(event)); }
|
|
119
134
|
if (["thinking_delta", "signature_delta"].includes(event.delta?.type) || /\.reasoning(?:_|\.)/.test(event.type || "")) return wire;
|
|
120
135
|
const isMessages = event.type === "content_block_delta", delta = isMessages ? event.delta : event;
|
|
121
136
|
const tool = delta?.type === "input_json_delta" || event.type === "response.function_call_arguments.delta";
|
|
122
|
-
const text = delta?.type === "text_delta" ||
|
|
137
|
+
const text = delta?.type === "text_delta" || ["response.output_text.delta", "response.custom_tool_call_input.delta"].includes(event.type);
|
|
123
138
|
let before = "";
|
|
124
139
|
const key = isMessages ? `m:${event.index}` : `r:${event.item_id || event.item?.id || event.output_index}:${event.content_index || 0}`;
|
|
125
140
|
if (tool || text) {
|
|
126
141
|
const field = tool ? isMessages ? "partial_json" : "delta" : isMessages ? "text" : "delta";
|
|
127
|
-
if (typeof delta[field] !== "string") throw
|
|
128
|
-
const channel = channels.get(key) || { tail: "", tool, field
|
|
142
|
+
if (typeof delta[field] !== "string") throw fail("stream_invalid");
|
|
143
|
+
const channel = channels.get(key) || { tail: "", tool, field };channel.template = event;channel.wire = wire;
|
|
129
144
|
let value = channel.tail + delta[field];
|
|
130
|
-
if (Buffer.byteLength(value) > 8 * 1024 * 1024) throw
|
|
131
|
-
if (tool) { channel.tail = value;
|
|
145
|
+
if (Buffer.byteLength(value) > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
146
|
+
if (tool) { channel.tail = value;channels.set(key, channel);return ""; }
|
|
132
147
|
else {
|
|
133
148
|
let cut = value.length;
|
|
134
149
|
const at = value.lastIndexOf("{{CCDX_");
|
|
@@ -143,24 +158,23 @@ export function createPrivacyStream(session) {
|
|
|
143
158
|
for (const [id, channel] of channels) if (terminal || id === stopKey) {
|
|
144
159
|
if (channel.tail) {
|
|
145
160
|
const value = structuredClone(channel.template), target = value.type === "content_block_delta" ? value.delta : value;
|
|
146
|
-
target[channel.field] = channel.tool ? JSON.stringify(session.
|
|
147
|
-
|
|
161
|
+
try { target[channel.field] = channel.tool ? JSON.stringify(session.restoreToolValue(JSON.parse(channel.tail))) : session.restoreText(channel.tail); }
|
|
162
|
+
catch { throw fail("stream_invalid"); }
|
|
163
|
+
before += rewritePrivacyFrame(channel.wire, value, true);
|
|
148
164
|
}
|
|
149
165
|
channels.delete(id);
|
|
150
166
|
}
|
|
151
167
|
event = session.restoreValue(event);
|
|
152
|
-
|
|
153
|
-
const changed = lines.map(line => { if (!line.startsWith("data:")) return line;if (written) return null;written = true;return `data: ${JSON.stringify(event)}`; }).filter(line => line !== null).join("\n");
|
|
154
|
-
return before + changed;
|
|
168
|
+
return before + rewritePrivacyFrame(wire, event);
|
|
155
169
|
}
|
|
156
170
|
return {
|
|
157
171
|
push(chunk) {
|
|
158
|
-
pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw
|
|
172
|
+
pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
159
173
|
let output = "", match;
|
|
160
174
|
while ((match = /\r?\n\r?\n/.exec(pending))) { const end = match.index + match[0].length;output += transform(pending.slice(0, end));pending = pending.slice(end);bytes = Buffer.byteLength(pending); }
|
|
161
175
|
return output;
|
|
162
176
|
},
|
|
163
|
-
finish() { pending += decoder.end();if (pending) { const output = transform(pending + "\n\n");pending = "";return output; }if (channels.size) throw
|
|
177
|
+
finish() { pending += decoder.end();if (pending) { const output = transform(pending + "\n\n");pending = "";return output; }if (channels.size) throw fail("stream_incomplete");return ""; },
|
|
164
178
|
};
|
|
165
179
|
}
|
|
166
180
|
|
|
@@ -178,7 +192,7 @@ export function protectPrivacyResponse(res, session) {
|
|
|
178
192
|
res.write = (value, encoding, callback) => {
|
|
179
193
|
const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value, typeof encoding === "string" ? encoding : undefined);
|
|
180
194
|
if (mode === "stream") { try { const output = stream.push(bytes);return output ? write(output, typeof encoding === "function" ? encoding : callback) : true; }catch (error) { detach();throw error; } }
|
|
181
|
-
size += bytes.length;if (size > 16 * 1024 * 1024) throw privacyFailure("response_limit");parts.push(bytes);return true;
|
|
195
|
+
size += bytes.length;if (size > 16 * 1024 * 1024) throw privacyFailure("response_limit", "response");parts.push(bytes);return true;
|
|
182
196
|
};
|
|
183
197
|
res.end = (value, encoding, callback) => {
|
|
184
198
|
if (value !== undefined && value !== null) res.write(value, encoding);
|
|
@@ -127,7 +127,12 @@ export function requestOptionsEvidence(body) {
|
|
|
127
127
|
if (["text", "json_object", "json_schema"].includes(body.text?.format?.type)) result.output_format = body.text.format.type;
|
|
128
128
|
if (Number.isSafeInteger(body.max_output_tokens) && body.max_output_tokens >= 0) result.max_output_tokens = body.max_output_tokens;
|
|
129
129
|
if (Number.isSafeInteger(body.max_tokens) && body.max_tokens >= 0) result.max_tokens = body.max_tokens;
|
|
130
|
-
|
|
130
|
+
const countTools = tools => Array.isArray(tools) ? tools.reduce((n, tool) => n + (tool?.type === "namespace" ? countTools(tool.tools) : 1), 0) : 0;
|
|
131
|
+
const inline = Array.isArray(body.input) ? body.input.filter(item => ["additional_tools", "tool_search_output"].includes(item?.type)) : [];
|
|
132
|
+
if (Array.isArray(body.tools) || inline.length) result.tools = countTools(body.tools) + inline.reduce((n, item) => n + countTools(item.tools), 0);
|
|
133
|
+
const last = Array.isArray(body.messages) ? body.messages.at(-1) : null;
|
|
134
|
+
const clientErrors = last?.role === "user" && Array.isArray(last.content) ? last.content.filter(block => block?.type === "tool_result" && block.is_error === true).length : 0;
|
|
135
|
+
if (clientErrors) result.client_tool_errors_received = clientErrors;
|
|
131
136
|
if (Array.isArray(body.input)) result.input_items = body.input.length;
|
|
132
137
|
return result;
|
|
133
138
|
}
|
|
@@ -192,7 +197,8 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
|
|
|
192
197
|
}
|
|
193
198
|
const message = (Object.hasOwn(reasons, reason) ? reasons[reason] : null) || (route === "messages_count_tokens" && statusCode === 404 ? "The source's token-count endpoint returned HTTP 404. Message generation is separate."
|
|
194
199
|
: code === "ccdx_api_network_unavailable" ? "Connection to the model source failed."
|
|
195
|
-
: origin === "
|
|
200
|
+
: origin === "privacy" ? "Local privacy processing failed. Review its error code and request timeline."
|
|
201
|
+
: origin === "client_validation" ? "The request was rejected locally before an upstream call."
|
|
196
202
|
: error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved.");
|
|
197
203
|
const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
|
|
198
204
|
message: model_error ? "The model source reported an error; the original HTTP response was preserved." : message } }, model_error ? "model.error" : "http.error", { headers, provider });
|
|
@@ -399,7 +399,7 @@ export function createResponsesHandler(options) {
|
|
|
399
399
|
res.end(JSON.stringify(response));
|
|
400
400
|
} catch (error) {
|
|
401
401
|
const responseError = applyAdaptiveTimeout(error);
|
|
402
|
-
markResponseErrorOrigin(responseError?.statusCode >= 400 && responseError.statusCode < 500
|
|
402
|
+
markResponseErrorOrigin(responseError?.origin === "privacy" ? "privacy" : responseError?.statusCode >= 400 && responseError.statusCode < 500
|
|
403
403
|
? "client_validation" : "transport");
|
|
404
404
|
logRequestFailure("Responses", responseError, abort);
|
|
405
405
|
sendJsonError(res, responseError, 502);
|
|
@@ -410,7 +410,7 @@ export function createResponsesHandler(options) {
|
|
|
410
410
|
}
|
|
411
411
|
} catch (error) {
|
|
412
412
|
const responseError = applyAdaptiveTimeout(error);
|
|
413
|
-
markResponseErrorOrigin(responseError?.statusCode >= 400 && responseError.statusCode < 500
|
|
413
|
+
markResponseErrorOrigin(responseError?.origin === "privacy" ? "privacy" : responseError?.statusCode >= 400 && responseError.statusCode < 500
|
|
414
414
|
? "client_validation" : "transport");
|
|
415
415
|
logRequestFailure("Responses", responseError, abort);
|
|
416
416
|
sendJsonError(res, responseError, 502);
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -520,7 +520,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
520
520
|
if (!res.writableEnded) res.end();
|
|
521
521
|
return { successful: Boolean(streamState.completed), compacted: false };
|
|
522
522
|
} catch (error) {
|
|
523
|
-
markResponseErrorOrigin("transport");
|
|
523
|
+
markResponseErrorOrigin(error.origin === "privacy" ? "privacy" : "transport");
|
|
524
524
|
markStreamFailure();
|
|
525
525
|
logRequestFailure("Responses", error, options.abort);
|
|
526
526
|
writeHeaders();
|
|
@@ -11,7 +11,7 @@ const TERMINAL_OUTCOMES = Object.freeze(["completed", "incomplete", "failed", "c
|
|
|
11
11
|
const INCOMPLETE_REASONS = new Set(["max_output_tokens", "max_messages", "content_filter", "steered"]);
|
|
12
12
|
const TERMINAL_ORIGINS = new Set([
|
|
13
13
|
"upstream_response", "upstream_event", "chat_completion", "client_validation",
|
|
14
|
-
"upstream_http", "transport", "client_disconnect", "unclassified",
|
|
14
|
+
"upstream_http", "transport", "privacy", "client_disconnect", "unclassified",
|
|
15
15
|
]);
|
|
16
16
|
const MAX_MODEL_OUTCOME_LABELS = 32;
|
|
17
17
|
const MAX_RECENT_REQUESTS = 20;
|
|
@@ -342,7 +342,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
342
342
|
observeContext(values) {
|
|
343
343
|
if (finished || !values || typeof values !== "object") return;
|
|
344
344
|
if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
|
|
345
|
-
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms"]) {
|
|
345
|
+
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "client_tool_errors_received"]) {
|
|
346
346
|
const value = values[key];
|
|
347
347
|
if (["capability_revision", "capability_constraints"].includes(key)) {
|
|
348
348
|
if (typeof value === "string" && /^[a-z0-9_,]{1,80}$/.test(value)) context[key] = value;continue;
|