codex-copilot-dx 1.3.20 → 1.3.22
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/bin/cli.mjs +10 -1
- package/docs/ARCHITECTURE.md +23 -2
- package/docs/REFERENCE.md +9 -3
- package/package.json +2 -1
- package/src/access-settings.mjs +48 -0
- package/src/claude-gateway.mjs +66 -4
- package/src/connection-client-sync.mjs +182 -0
- package/src/connection-management.mjs +264 -0
- package/src/connection-policy.mjs +321 -0
- package/src/connection-routing.mjs +183 -0
- package/src/connection-runtime.mjs +43 -1334
- package/src/connection-view.mjs +320 -0
- package/src/copilot-responses-compat.mjs +9 -1
- package/src/messages-tool-schema.mjs +155 -0
- package/src/privacy-transform.mjs +32 -7
- package/src/providers/api-network.mjs +1 -1
- package/src/providers/api.mjs +27 -3
- package/src/providers/github.mjs +5 -4
- package/src/proxy-tunnel.mjs +17 -1
- package/src/responses-bridge.mjs +61 -5
- package/src/responses-chat-payload.mjs +6 -5
- package/src/responses-handler.mjs +13 -4
- package/src/responses-proxy.mjs +30 -9
- package/src/responses-tool-output.mjs +42 -0
- package/src/safe-upstream-error.mjs +8 -2
- package/src/source-lifecycle.mjs +61 -0
- package/src/stream-errors.mjs +29 -5
package/bin/cli.mjs
CHANGED
|
@@ -30,7 +30,16 @@ if (CLI.command === "manage") {
|
|
|
30
30
|
const { runManagementCommand } = await import("../src/cli-management.mjs");
|
|
31
31
|
const address = parseAdapterAddressOptions(process.env);
|
|
32
32
|
const result = await runManagementCommand(CLI, { host: address.adapterHost, port: address.adapterPort, version: LOCAL_VERSION });
|
|
33
|
-
if (result)
|
|
33
|
+
if (result) {
|
|
34
|
+
const error = await new Promise(resolve => {
|
|
35
|
+
process.stdout.once("error", resolve);
|
|
36
|
+
process.stdout.write(`${result}\n`, resolve);
|
|
37
|
+
});
|
|
38
|
+
if (error) {
|
|
39
|
+
if (error.code !== "EPIPE") console.error(status("err", `Could not write command output: ${error.message}`));
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
34
43
|
process.exit(0);
|
|
35
44
|
} catch (error) {
|
|
36
45
|
if (CLI.flags?.format === "json") console.log(JSON.stringify({ error: { code: error.code || "ccdx_command_failed", message: error.message } }));
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -91,6 +91,10 @@ failed call; retirement waits for unrelated active responses to drain. Shutdown
|
|
|
91
91
|
still closes all current/retiring transports. HTTP error statuses and intentional
|
|
92
92
|
cancellation do not invalidate the transport. Node response streams are pulled
|
|
93
93
|
on demand to avoid eager delivery into an already-cancelled Web stream.
|
|
94
|
+
For the API's Node HTTPS agent, idle sockets expire after at most 60 seconds,
|
|
95
|
+
or earlier when the server supplies a shorter keep-alive hint. The idle timeout
|
|
96
|
+
is removed on reuse, before an active request is attached. WinHTTP keeps its
|
|
97
|
+
existing OS-managed transport. Neither path retries an ambiguous sent request.
|
|
94
98
|
`operation-error.mjs` projects fixed transport phases, a local error-code
|
|
95
99
|
allowlist and socket-reuse evidence. API errors preserve their private cause,
|
|
96
100
|
but client diagnostics/logs expose only those bounded fields, not raw causes,
|
|
@@ -631,7 +635,24 @@ the lockfile fixes CI transitives, not consumers' future transitive resolution.
|
|
|
631
635
|
|
|
632
636
|
Stream performance retains existing route totals and adds `by_route.<route>.by_provider`. Each source has started/active/finished counts, terminal totals, bounded model outcomes, request-to-first-output timing and preparation histograms. Source assignment is pinned once. There are at most 18 source labels (two built-ins and 16 APIs) plus `other`, and 32 model labels plus `other` per source. Unassigned finished requests use `unknown`; request IDs, accounts and URLs never become metric labels. Recent requests remain capped at 20. `runtime_usage.by_provider` has at most 18 labels plus `other`; unknown usage stays partial and persisted historical records retain their source.
|
|
633
637
|
|
|
634
|
-
`operation-error.mjs` distinguishes client cancellation, unspecified abort, timeout, network/TLS/proxy, authentication and access denial. HTTP 403 is not proof of credential expiry. Claude and Codex cancellations are informational; request-body timeouts use 408, upstream/idle timeouts 504, and local client cancellation diagnostics 499.
|
|
638
|
+
`operation-error.mjs` distinguishes client cancellation, unspecified abort, timeout, network/TLS/proxy, authentication and access denial. HTTP 403 is not proof of credential expiry. Claude and Codex cancellations are informational; request-body timeouts use 408, upstream/idle timeouts 504, and local client cancellation diagnostics 499. Upstream HTTP error status and body retain their existing path. Responses SSE failures use a complete `response.failed` event, including locally supplied metadata when the upstream did not provide it.
|
|
639
|
+
|
|
640
|
+
After Claude `message_stop`, the downstream response ends before an upstream drain. A complete drain permits connection reuse; cancellation, failure, one second or more than 64 KiB of tail bytes closes the reader. The last received chunk can exceed the byte threshold. Privacy masking preserves numeric literals in JSON-encoded tool arguments while restoring only mapped string values.
|
|
641
|
+
|
|
642
|
+
Responses compatibility only rewrites a standalone tool output after an explicit
|
|
643
|
+
missing-call-ID HTTP validation failure; the Chat bridge represents it as marked
|
|
644
|
+
untrusted context. Valid paired outputs are unchanged. Tool-search, deferred and
|
|
645
|
+
namespaced functions use native Responses when confirmed; Chat-only routes reject
|
|
646
|
+
them instead of discarding those semantics. Allowed function lists retain their
|
|
647
|
+
restriction and returned Chat calls are checked before completion. Chat cache
|
|
648
|
+
fields are forwarded only when the catalog explicitly advertises each field.
|
|
649
|
+
|
|
650
|
+
For an explicit root-combiner schema validation failure, the custom Messages
|
|
651
|
+
provider may send a bounded, model-facing object schema while retaining the
|
|
652
|
+
original validator for the response. Guarded tool frames are buffered until the
|
|
653
|
+
complete input passes that validator; invalid or numerically unsafe input is not
|
|
654
|
+
delivered as a tool call. Unsupported, complex or regular-expression schemas are
|
|
655
|
+
left unchanged. Ordinary accepted requests and streams bypass this adaptation.
|
|
635
656
|
|
|
636
657
|
Byte-weighted request admission is not a simultaneous-stream limit. The 1.2.0 load replay exercises 16/64/128 small-body held streams, management responsiveness and downstream cancellation against 1.1.1. It does not establish a universal safe concurrency maximum. Existing defaults remain unchanged; see the release receipt for measured bounds.
|
|
637
658
|
|
|
@@ -1131,7 +1152,7 @@ The image and input-suggestion panels share `codex-launch-control.mjs`. `codex-a
|
|
|
1131
1152
|
|
|
1132
1153
|
The managed Codex catalog projects explicit source input modalities ahead of native templates and checks GitHub priority eligibility against the full live source registry. Unknown modality metadata keeps the prior fallback. Source identities, selected models and routing remain unchanged.
|
|
1133
1154
|
|
|
1134
|
-
`safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks release request admission before the optional body read;
|
|
1155
|
+
`safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks normally release request admission before the optional body read; an eligible explicit compatibility rejection retains admission through its one retry. Image processing slots are released before their error read. Count-token singleflight forwards callbacks only to the appropriate waiters. Successful requests never invoke the reader.
|
|
1135
1156
|
|
|
1136
1157
|
## Client updates and streaming boundaries (1.3.20)
|
|
1137
1158
|
|
package/docs/REFERENCE.md
CHANGED
|
@@ -588,7 +588,11 @@ was recreated on the original address, not that gray text appeared.
|
|
|
588
588
|
|
|
589
589
|
## Error delivery and conversation commits
|
|
590
590
|
|
|
591
|
-
Image and custom API HTTP errors keep their stable `ccdx_images_http_<status>` or `ccdx_api_http_<status>` code, status and validated Retry-After. A failure-only reader can retain a small allowlist of structured source codes in `upstream_code`; source messages and bodies are not forwarded. Reads are limited to 64 KiB and a 200 ms timer, with at most four concurrent readers. Unknown or unfinished bodies fall back to the existing generic error.
|
|
591
|
+
Image and custom API HTTP errors keep their stable `ccdx_images_http_<status>` or `ccdx_api_http_<status>` code, status and validated Retry-After. A failure-only reader can retain a small allowlist of structured source codes in `upstream_code`; source messages and bodies are not forwarded. Reads are limited to 64 KiB and a 200 ms timer, with at most four concurrent readers. Unknown or unfinished bodies fall back to the existing generic error. Admission is normally released before this read; a recognized compatibility rejection may hold it through one retry. Image-generation slots are still released before the read.
|
|
592
|
+
|
|
593
|
+
An explicit source validation error for a standalone tool output without a call ID can trigger one compatibility retry. An explicit rejection of a supported root-union tool schema can trigger one Messages retry; tool inputs are checked against the original schema before delivery. Schemas that cannot be checked safely remain unchanged. Other failures, including a silent connection, are not retried by these adaptations.
|
|
594
|
+
|
|
595
|
+
For custom APIs using the Node HTTPS agent, idle pooled connections are retired after 60 seconds at most, or earlier when the server declares a shorter keep-alive period. Active streams and their existing timeouts are unchanged. Windows WinHTTP continues to use its own connection handling. A connection can still fail within the idle period; reconnecting an expired connection can add setup time.
|
|
592
596
|
|
|
593
597
|
Conversation-source admission and Messages checkpoint commits wait asynchronously for the existing cross-process locks. Cancellation ends lock waits. Checkpoint writes retain the primary/marker ordering and rollback behavior; the gateway awaits a successful commit before forwarding corresponding usable JSON or SSE output. Cached source checks keep their synchronous fast path. CLI configuration writers retain their existing synchronous behavior.
|
|
594
598
|
|
|
@@ -739,7 +743,7 @@ When expanded history exceeds Copilot's 50-image request limit, CCDX removes old
|
|
|
739
743
|
|
|
740
744
|
For `/v1/responses/compact`, CCDX sends one terminal `compaction_trigger`, validates completed compaction state, and preserves the complete returned window as the canonical next context. Only a validated window becomes a new local history root. Existing older branches remain available until normal history eviction.
|
|
741
745
|
|
|
742
|
-
Changing the model or transport of a continuation can require removing incompatible encrypted history from the forwarded request. A specific upstream encrypted-state verification failure can also trigger one sanitized retry, including when a nominally successful HTTP response ends with `response.failed`. CCDX withholds only the pre-output prelude of an encrypted continuation while evaluating that terminal event; it never retries after visible model output, so it cannot duplicate an already-started answer. Unrelated failures
|
|
746
|
+
Changing the model or transport of a continuation can require removing incompatible encrypted history from the forwarded request. A specific upstream encrypted-state verification failure can also trigger one sanitized retry, including when a nominally successful HTTP response ends with `response.failed`. CCDX withholds only the pre-output prelude of an encrypted continuation while evaluating that terminal event; it never retries after visible model output, so it cannot duplicate an already-started answer. Unrelated failures are not retried. CCDX does not decrypt that state locally.
|
|
743
747
|
|
|
744
748
|
Native Responses forwards Codex `agent_message` items unchanged. When a model requires Chat Completions, CCDX frames them as messages from another agent, not human input or approval, retaining author/recipient, typed text/refusal/reasoning and representable image/screenshot content. Content unsupported by Chat, including file, audio or opaque encrypted parts, receives an explicit compatibility error instead of being serialized into ordinary text. This projection does not introduce another model request or change native Responses, Fast, Auto-review or compaction routing.
|
|
745
749
|
|
|
@@ -759,6 +763,8 @@ Downstream backpressure waits also observe cancellation and the stream deadline.
|
|
|
759
763
|
|
|
760
764
|
Successful streaming responses are accepted only when the upstream body is SSE and reaches its protocol terminal event. Unexpected EOF becomes a protocol-native stream error, and repeated blank tool-argument deltas are stopped per tool call. Allowlisted rate-limit, retry, model, trace, and upstream request-ID metadata are forwarded; cookies, authorization, body-length, and encoding headers are not.
|
|
761
765
|
|
|
766
|
+
Responses stream errors, including untyped upstream error frames and interrupted streams, end in a `response.failed` event carrying the failure message. Missing response IDs and creation times are supplied locally. After a successful Claude `message_stop`, the client response ends immediately; CCDX reads toward upstream EOF to allow connection reuse. The reader is canceled after one second or when received tail bytes exceed 64 KiB; the last chunk can exceed that threshold. Errors and cancellation also close the reader.
|
|
767
|
+
|
|
762
768
|
Responses, Chat fallback, Messages and local response restoration accept LF, CRLF and CR SSE line endings. Existing comment heartbeats, upstream timeouts, retry eligibility, output and usage remain unchanged.
|
|
763
769
|
|
|
764
770
|
CCDX keeps each native Responses message on its first upstream ID when Copilot changes that ID during streaming. Message deltas, completion events, and cached history stay consistent, addressing this cause of duplicate live messages in Codex App. Tool identities, reasoning/encrypted content, message phases, and speed-tier routing are unchanged by this ID normalization. Stable events retain their original SSE bytes; changed events are rewritten with bounded, backpressured streaming.
|
|
@@ -801,7 +807,7 @@ Covered text includes conversation instructions, message text, tool results, too
|
|
|
801
807
|
|
|
802
808
|
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.
|
|
803
809
|
|
|
804
|
-
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.
|
|
810
|
+
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. JSON-encoded Responses and Chat tool arguments retain their numeric values, including integers beyond JavaScript's safe range, when masked or restored. 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.
|
|
805
811
|
|
|
806
812
|
Each request pins its masking choice, including compatibility retries. Checks normally wait up to 15 seconds; a plan with at least one 16 KiB batch of uncached or in-flight text, or more than one pending native window, receives a bounded 60-second wait. A request still exceeding its wait is rejected before any upstream call. Submitted native batches finish and remain reusable; callers share in-flight work, and unused queued work stops. The 1.3.13 component reuses exact natural token-window predictions. Independent short CPU sequences run in bounded groups, with at most 512 total tokens including sequence markers and 16 KiB text. Each sequence keeps its tokenization, positions, attention and quantization scale; fields are not joined into a shared context. A single uncached sequence and accelerator-eligible windows retain their previous execution path. CPU batch-group and computed-window counts are exposed in the existing status metadata. Sparse non-O labels and exact scores use a separate 4 MiB/5,000-entry memory cache; original tokenization, window overlaps and current-text byte offsets are unchanged. Up to two text batches run concurrently, toward 16 KiB or 64 entries, keeping a larger individual text whole. Exact completed texts retain hot aliases. When the last waiter leaves, supporting components finish current windows, cache them and acknowledge cancellation before releasing the native slot. A waiter joining during cancellation resumes after acknowledgement; older compatible components finish whole batches as before. No request uses an incomplete model check. A native job retains its five-minute deadline and the native eight-job/16 MiB limits; the detection queue adds a 16 MiB/8,192-entry bound. Cache metadata remains within 5,000 entries/4 MiB, without storing detection history on disk. Cold-check cost and recovery are measured separately from hot reuse. Fully cached checks do not create native-work wait timers or cancellation listeners; they still honor caller cancellation before returning. CPU intermediate matrices are reused only within one inference. CoreML reuses one C-owned input array/provider per model under its existing mutex and clears its buffers after every successful or failed prediction. Go input memory is not retained by CoreML; classification mathematics and thread budgets are unchanged.
|
|
807
813
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-copilot-dx",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.22",
|
|
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",
|
|
@@ -54,6 +54,7 @@
|
|
|
54
54
|
"test:release-network": "node scripts/release-network-replay.mjs"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
+
"ajv": "8.18.0",
|
|
57
58
|
"sharp": "0.35.5",
|
|
58
59
|
"smol-toml": "1.9.1"
|
|
59
60
|
},
|
package/src/access-settings.mjs
CHANGED
|
@@ -64,6 +64,54 @@ export function checkedApi(value) {
|
|
|
64
64
|
if (value.checked_at !== undefined && (typeof value.checked_at !== "string" || !Number.isFinite(Date.parse(value.checked_at)))) throw accessError("ccdx_api_config_invalid");
|
|
65
65
|
return value;
|
|
66
66
|
}
|
|
67
|
+
export function prepareSourceAccess(input, next) {
|
|
68
|
+
if (
|
|
69
|
+
!["github", "m365", ...next.apis.map(api => api.id)].includes(input.id) ||
|
|
70
|
+
!Array.isArray(input.allowed) ||
|
|
71
|
+
new Set(input.allowed).size !== input.allowed.length ||
|
|
72
|
+
input.allowed.some(id => !CLIENT_IDS.includes(id))
|
|
73
|
+
)
|
|
74
|
+
throw accessError("ccdx_connections_action_invalid");
|
|
75
|
+
const api = next.apis.find(api => api.id === input.id);
|
|
76
|
+
if (
|
|
77
|
+
input.allowed.some(
|
|
78
|
+
id =>
|
|
79
|
+
(input.id === "github" && id !== "codex") ||
|
|
80
|
+
(api && !api.endpoints[id === "codex" ? "responses" : "messages"])
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
throw accessError("ccdx_api_protocol_required");
|
|
84
|
+
const affected = CLIENT_IDS.filter(
|
|
85
|
+
id => next.clients[id].allowed.includes(input.id) !== input.allowed.includes(id)
|
|
86
|
+
);
|
|
87
|
+
const sharedClaude = ["claude_app", "claude_code"].filter(
|
|
88
|
+
id => next.clients[id].enabled && next.clients[id].source === "m365"
|
|
89
|
+
);
|
|
90
|
+
const migrateClaude =
|
|
91
|
+
input.id === "m365" &&
|
|
92
|
+
!next.claude_private_keys &&
|
|
93
|
+
sharedClaude.length > 0 &&
|
|
94
|
+
affected.some(id => id !== "codex");
|
|
95
|
+
const targets = new Set();
|
|
96
|
+
for (const id of affected) {
|
|
97
|
+
const c = next.clients[id];
|
|
98
|
+
c.allowed = [
|
|
99
|
+
...c.allowed.filter(source => source !== input.id),
|
|
100
|
+
...(input.allowed.includes(id) ? [input.id] : []),
|
|
101
|
+
];
|
|
102
|
+
if (!input.allowed.includes(id)) {
|
|
103
|
+
if (c.source === input.id || c.deployments?.some(item => item.source === input.id)) targets.add(id);
|
|
104
|
+
if (c.source === input.id) c.source = null;
|
|
105
|
+
if (Array.isArray(c.deployments))
|
|
106
|
+
c.deployments = c.deployments.filter(item => item.source !== input.id);
|
|
107
|
+
c.history_isolation = true;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (migrateClaude) next.claude_private_keys = true;
|
|
111
|
+
if (migrateClaude)
|
|
112
|
+
for (const id of ["claude_app", "claude_code"]) if (next.clients[id].source === "m365") targets.add(id);
|
|
113
|
+
return { targets, migrateClaude };
|
|
114
|
+
}
|
|
67
115
|
export function defaultAccessSettings() {
|
|
68
116
|
return { version: 2, claude_private_keys: false, providers: { github: true, m365: true }, apis: [], clients: Object.fromEntries(CLIENT_IDS.map(id => [id,
|
|
69
117
|
{ enabled: true, allowed: id === "codex" ? ["github", "m365"] : ["m365"], source: null }])) };
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -19,6 +19,7 @@ import { observeContextSession } from "./context-metrics.mjs";
|
|
|
19
19
|
import { catalogCapabilities } from "./model-capabilities.mjs";
|
|
20
20
|
import { applyMessagesSystemPolicy } from "./messages-system-policy.mjs";
|
|
21
21
|
import { createApiTokenCounter } from "./providers/api-token-count.mjs";
|
|
22
|
+
import { MESSAGES_TOOL_GUARD } from "./messages-tool-schema.mjs";
|
|
22
23
|
|
|
23
24
|
function observeMessagesWindow(provider, model, capability, entry) {
|
|
24
25
|
try {
|
|
@@ -39,6 +40,25 @@ function send(res, code, value) {
|
|
|
39
40
|
res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
|
|
40
41
|
}
|
|
41
42
|
const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
|
|
43
|
+
const MAX_TERMINAL_DRAIN_BYTES = 64 * 1024;
|
|
44
|
+
const TERMINAL_DRAIN_TIMEOUT_MS = 1000;
|
|
45
|
+
async function drainAfterMessageStop(reader) {
|
|
46
|
+
let bytes = 0, ended = false;
|
|
47
|
+
const cancel = () => { try { void reader.cancel().catch(() => {}); } catch {} };
|
|
48
|
+
const timer = setTimeout(cancel, TERMINAL_DRAIN_TIMEOUT_MS);timer.unref?.();
|
|
49
|
+
try {
|
|
50
|
+
while (true) {
|
|
51
|
+
const { done, value } = await reader.read();
|
|
52
|
+
if (done) { ended = true;break; }
|
|
53
|
+
bytes += value.byteLength;
|
|
54
|
+
if (bytes > MAX_TERMINAL_DRAIN_BYTES) break;
|
|
55
|
+
}
|
|
56
|
+
} catch { /* The response has already ended for the client. */ }
|
|
57
|
+
finally {
|
|
58
|
+
clearTimeout(timer);if (!ended) cancel();
|
|
59
|
+
try { reader.releaseLock(); } catch {}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
42
62
|
const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
|
|
43
63
|
|| typeof block.text === "string" && block.text.length || typeof block.thinking === "string" && block.thinking.length));
|
|
44
64
|
function authenticated(headers, key) {
|
|
@@ -147,6 +167,35 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
|
|
|
147
167
|
if (fragments.length) completeLine("");if (wire.length) wire.push("\n\n");frame();return output; } };
|
|
148
168
|
}
|
|
149
169
|
|
|
170
|
+
// Only schema-recovery responses need this extra frame pass. Keep the ordinary
|
|
171
|
+
// Messages parser unchanged so normal streams do not pay for tool validation.
|
|
172
|
+
function createGuardedMessagesObserver(onEvent, maxBytes, clientModel, guard, restore) {
|
|
173
|
+
const pending = [], observer = createMessagesObserver(event => pending.push(event), maxBytes, clientModel);
|
|
174
|
+
const filter = frames => {
|
|
175
|
+
const output = [];
|
|
176
|
+
for (const chunk of frames) {
|
|
177
|
+
const parts = chunk.toString("utf8").split(/\r\n|\r|\n/).filter(line => line.startsWith("data:"))
|
|
178
|
+
.map(line => line.slice(5).replace(/^ /, ""));
|
|
179
|
+
if (parts.length && !pending.length) throw new Error("Missing Claude stream event");
|
|
180
|
+
const event = parts.length ? pending.shift() : undefined;
|
|
181
|
+
for (const result of guard.frame(event, chunk, parts.join("\n"), restore)) {
|
|
182
|
+
if (result.event !== undefined) onEvent(result.event);
|
|
183
|
+
output.push(result.chunk);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (pending.length) throw new Error("Missing Claude stream frame");
|
|
187
|
+
return output;
|
|
188
|
+
};
|
|
189
|
+
const run = (method, chunk) => {
|
|
190
|
+
try { return filter(method === "write" ? observer.write(chunk) : observer.finish()); }
|
|
191
|
+
catch (error) {
|
|
192
|
+
for (const event of pending.splice(0)) if (event?.type === "error") onEvent(event);
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
return { write: chunk => run("write", chunk), finish: () => run("finish") };
|
|
197
|
+
}
|
|
198
|
+
|
|
150
199
|
export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
|
|
151
200
|
resolveRequest, privacy, privacyClient = "claude", record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
|
|
152
201
|
if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
|
|
@@ -246,6 +295,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
246
295
|
}
|
|
247
296
|
upstream = await counter.count(body, { ...callOptions, perform: call });
|
|
248
297
|
} else upstream = await call(body, callOptions);
|
|
298
|
+
const toolGuard = upstream[MESSAGES_TOOL_GUARD];
|
|
299
|
+
const restoreToolInput = toolGuard && privacy?.restoreResponse ? value => privacy.restoreResponse(res, value) : null;
|
|
249
300
|
body = null;
|
|
250
301
|
terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
|
|
251
302
|
if (!upstreamHeadersObserved) tracker?.upstreamHeaders(upstream.status);
|
|
@@ -256,7 +307,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
256
307
|
if (!upstream.ok || !streamed) {
|
|
257
308
|
const raw = await readBoundedResponseText(upstream, { maxBytes: upstream.ok ? config.maxUpstreamResponsesResponseBytes : MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
258
309
|
label: "Claude gateway response", signal: abort.signal });
|
|
259
|
-
let value;
|
|
310
|
+
let value;
|
|
311
|
+
if (toolGuard && upstream.ok && !countTokens) value = toolGuard.validateMessage(raw, restoreToolInput);
|
|
312
|
+
else try { value = JSON.parse(raw); } catch {}
|
|
260
313
|
const modelFailure = upstream.ok && (!value?.type || value.type === "error") && value?.error && typeof value.error === "object" && !Array.isArray(value.error)
|
|
261
314
|
&& ["code", "type", "message"].some(key => typeof value.error[key] === "string" && value.error[key].trim())
|
|
262
315
|
&& !["content", "output", "choices", "candidates"].some(key => Array.isArray(value[key]) && value[key].length);
|
|
@@ -286,7 +339,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
286
339
|
}
|
|
287
340
|
commitState = null;
|
|
288
341
|
};
|
|
289
|
-
const
|
|
342
|
+
const observe = event => {
|
|
290
343
|
if (event.type === "error") {
|
|
291
344
|
failedEvent = true;outcome = "failed";
|
|
292
345
|
const evidence = upstreamErrorEvidence(JSON.stringify(event));
|
|
@@ -304,8 +357,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
304
357
|
stopReason = event.delta?.stop_reason || stopReason;
|
|
305
358
|
}
|
|
306
359
|
if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
|
|
307
|
-
}
|
|
360
|
+
};
|
|
361
|
+
const observer = toolGuard
|
|
362
|
+
? createGuardedMessagesObserver(observe, config.maxSseBufferBytes, clientModel, toolGuard, restoreToolInput)
|
|
363
|
+
: createMessagesObserver(observe, config.maxSseBufferBytes, clientModel);
|
|
308
364
|
const reader = upstream.body.getReader();
|
|
365
|
+
let draining = false;
|
|
309
366
|
try {
|
|
310
367
|
while (true) {
|
|
311
368
|
const { value, done } = await reader.read();if (done) break;
|
|
@@ -321,7 +378,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
321
378
|
for (const chunk of tail) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
|
|
322
379
|
if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
|
|
323
380
|
if (!res.writableEnded) res.end();
|
|
324
|
-
|
|
381
|
+
if (sawStop && !failedEvent && !abort.signal.aborted && !res.destroyed) {
|
|
382
|
+
draining = true;void drainAfterMessageStop(reader);
|
|
383
|
+
}
|
|
384
|
+
} finally {
|
|
385
|
+
if (!draining) { await reader.cancel().catch(() => {});reader.releaseLock(); }
|
|
386
|
+
}
|
|
325
387
|
}
|
|
326
388
|
} catch (error) {
|
|
327
389
|
rejectionReason = error.jsonBody?.error?.reason || (error.code === "ccdx_client_source_disabled" ? error.code : undefined);
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { CLIENT_IDS } from "./access-settings.mjs";
|
|
2
|
+
import { claudeSharedCapabilityPlan, claudeSupportForSync, syncClaudeCapabilities } from "./claude-capability-config.mjs";
|
|
3
|
+
|
|
4
|
+
export function createConnectionClientSync({ options, corePort, configureCodex, configureClaude, restoreClaude, inspectDesktop,
|
|
5
|
+
binding, plan, permitted, getSource, identities, codexAccessMode, capabilitySupport, clientVersionsSnapshot, setup, credentialStates,
|
|
6
|
+
isManaged, isClosed, getSettings }) {
|
|
7
|
+
let sharedSync = null, syncFlight = null, syncAgain = false;
|
|
8
|
+
const syncTargets = new Set(), manualTargets = new Set();
|
|
9
|
+
function capabilitySupportForSync() {
|
|
10
|
+
try {
|
|
11
|
+
return claudeSupportForSync(capabilitySupport, clientVersionsSnapshot?.());
|
|
12
|
+
} catch { /* Optional observations cannot change routing or interrupt synchronization. */ }
|
|
13
|
+
return capabilitySupport;
|
|
14
|
+
}
|
|
15
|
+
async function syncClients(ids = CLIENT_IDS, { manual = false } = {}) {
|
|
16
|
+
if (!ids.length) return;
|
|
17
|
+
for (const id of ids) {
|
|
18
|
+
syncTargets.add(id);
|
|
19
|
+
if (manual) manualTargets.add(id);
|
|
20
|
+
}
|
|
21
|
+
syncAgain = true;
|
|
22
|
+
if (syncFlight) return syncFlight;
|
|
23
|
+
syncFlight = (async () => {
|
|
24
|
+
do {
|
|
25
|
+
syncAgain = false;
|
|
26
|
+
const targets = new Set(syncTargets);
|
|
27
|
+
syncTargets.clear();
|
|
28
|
+
const requested = new Set(manualTargets);
|
|
29
|
+
manualTargets.clear();
|
|
30
|
+
await performClientSync(targets, requested);
|
|
31
|
+
} while (syncAgain && !isClosed());
|
|
32
|
+
})();
|
|
33
|
+
try {
|
|
34
|
+
return await syncFlight;
|
|
35
|
+
} finally {
|
|
36
|
+
syncFlight = null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function syncCodexClient(codex, compiledCodex, requested, mode) {
|
|
40
|
+
const explicit = Array.isArray(codex.deployments),
|
|
41
|
+
native = mode === "native";
|
|
42
|
+
try {
|
|
43
|
+
if (mode === "paused" || mode === "disabled") {
|
|
44
|
+
if (mode === "disabled" || codex.auto_sync !== false || requested.has("codex"))
|
|
45
|
+
configureCodex({ ...options, restore: true });
|
|
46
|
+
setup.codex = mode;
|
|
47
|
+
} else if (codex.auto_sync === false && !requested.has("codex")) setup.codex = "manual_sync";
|
|
48
|
+
else if (codex.enabled && compiledCodex.defaultUnavailable && !native)
|
|
49
|
+
setup.codex = "default_unavailable";
|
|
50
|
+
else {
|
|
51
|
+
setup.codex = configureCodex({
|
|
52
|
+
...options,
|
|
53
|
+
...(codex.enabled &&
|
|
54
|
+
(native || (explicit && codex.deployments.length) || codex.source?.startsWith("api_"))
|
|
55
|
+
? {
|
|
56
|
+
baseUrl: `http://127.0.0.1:${corePort}/v1`,
|
|
57
|
+
native,
|
|
58
|
+
...(native ? { nativeModels: compiledCodex.models } : {}),
|
|
59
|
+
...(!native ? { apiKey: identities().codex } : {}),
|
|
60
|
+
...(explicit || !native
|
|
61
|
+
? {
|
|
62
|
+
model:
|
|
63
|
+
compiledCodex.defaultModel ||
|
|
64
|
+
(!compiledCodex.defaultUnavailable ? codex.model : undefined),
|
|
65
|
+
}
|
|
66
|
+
: {}),
|
|
67
|
+
}
|
|
68
|
+
: { restore: true }),
|
|
69
|
+
}).state;
|
|
70
|
+
if (codex.enabled && compiledCodex.defaultUnavailable && setup.codex === "configured")
|
|
71
|
+
setup.codex = "default_unavailable";
|
|
72
|
+
}
|
|
73
|
+
} catch {
|
|
74
|
+
setup.codex = "configuration_unavailable";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function prepareClaudeSync(id, requested) {
|
|
78
|
+
const selected = binding(id),
|
|
79
|
+
compiled = plan(id);
|
|
80
|
+
const source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
|
|
81
|
+
try {
|
|
82
|
+
if (selected.enabled && compiled.defaultUnavailable) {
|
|
83
|
+
setup[id] = "default_unavailable";
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
if (!selected.enabled || !compiled.models.length) {
|
|
87
|
+
const result = restoreClaude({ ...options, client: id });
|
|
88
|
+
setup[id] = result.preserved ? "preserved" : "not_configured";
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
if (selected.auto_sync === false && !requested.has(id)) {
|
|
92
|
+
setup[id] = "manual_sync";
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
return { selected, compiled, source };
|
|
96
|
+
} catch {
|
|
97
|
+
setup[id] = "configuration_unavailable";
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function writeClaudeSync(id, { selected, compiled, source }, desktopManaged) {
|
|
102
|
+
const m365Only = compiled.models.every(model => model.source_id === "m365");
|
|
103
|
+
const result = configureClaude({
|
|
104
|
+
...options,
|
|
105
|
+
client: id,
|
|
106
|
+
profileName: "CCDX",
|
|
107
|
+
desktopAliases: id === "claude_app" && source?.id.startsWith("api_"),
|
|
108
|
+
disableExperimentalBetas: m365Only,
|
|
109
|
+
desktopManaged: id === "claude_app" ? desktopManaged : false,
|
|
110
|
+
baseUrl: `http://127.0.0.1:${corePort}/anthropic`,
|
|
111
|
+
apiKey: identities()[id],
|
|
112
|
+
models: compiled.models,
|
|
113
|
+
defaultModel: Array.isArray(selected.deployments) ? compiled.defaultModel : undefined,
|
|
114
|
+
});
|
|
115
|
+
setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
|
|
116
|
+
if (id === "claude_app" && result.app_credential) credentialStates[id] = result.app_credential;
|
|
117
|
+
}
|
|
118
|
+
function syncSharedClaudeCapabilities(targets) {
|
|
119
|
+
if (["claude_app", "claude_code"].some(id => setup[id] === "default_unavailable")) {
|
|
120
|
+
sharedSync = {
|
|
121
|
+
...sharedSync,
|
|
122
|
+
state: "partially_preserved",
|
|
123
|
+
limitations: [{ code: "default_model_unavailable" }],
|
|
124
|
+
};
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (!["claude_app", "claude_code"].some(id => targets.has(id))) return;
|
|
128
|
+
if (
|
|
129
|
+
["claude_app", "claude_code"].some(
|
|
130
|
+
id => !targets.has(id) && !setup[id] && binding(id).enabled && plan(id).models.length
|
|
131
|
+
)
|
|
132
|
+
) {
|
|
133
|
+
sharedSync = { state: "partially_preserved", limitations: [{ code: "other_client_not_checked" }] };
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const shared = claudeSharedCapabilityPlan({
|
|
137
|
+
app: setup.claude_app === "configured" ? plan("claude_app").models : [],
|
|
138
|
+
code: setup.claude_code === "configured" ? plan("claude_code").models : [],
|
|
139
|
+
support: capabilitySupportForSync(),
|
|
140
|
+
});
|
|
141
|
+
if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
|
|
142
|
+
sharedSync = {
|
|
143
|
+
...shared,
|
|
144
|
+
state: "partially_preserved",
|
|
145
|
+
limitations: [...shared.limitations, { code: "manual_sync" }],
|
|
146
|
+
};
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
sharedSync = { ...shared, ...syncClaudeCapabilities(shared, options) };
|
|
151
|
+
} catch {
|
|
152
|
+
sharedSync = { state: "configuration_unavailable", limitations: shared.limitations };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async function performClientSync(targets, requested = new Set()) {
|
|
156
|
+
if (!isManaged() || isClosed()) return;
|
|
157
|
+
for (const id of targets) delete credentialStates[id];
|
|
158
|
+
if (options.preserveClientConfiguration?.()) {
|
|
159
|
+
for (const id of targets) setup[id] = "preserved";
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const codex = binding("codex"),
|
|
163
|
+
compiledCodex = plan("codex"),
|
|
164
|
+
mode = codexAccessMode();
|
|
165
|
+
if (targets.has("codex")) syncCodexClient(codex, compiledCodex, requested, mode);
|
|
166
|
+
if (!getSettings().claude_private_keys || !["claude_app", "claude_code"].some(id => targets.has(id))) return;
|
|
167
|
+
let desktopManaged;
|
|
168
|
+
for (const id of ["claude_app", "claude_code"]) {
|
|
169
|
+
if (!targets.has(id)) continue;
|
|
170
|
+
const sync = prepareClaudeSync(id, requested);
|
|
171
|
+
if (!sync) continue;
|
|
172
|
+
try {
|
|
173
|
+
if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
|
|
174
|
+
writeClaudeSync(id, sync, desktopManaged);
|
|
175
|
+
} catch {
|
|
176
|
+
setup[id] = "configuration_unavailable";
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
syncSharedClaudeCapabilities(targets);
|
|
180
|
+
}
|
|
181
|
+
return { syncClients, capabilitySupportForSync, shared: () => sharedSync, busy: () => Boolean(syncFlight), pending: () => syncFlight };
|
|
182
|
+
}
|