codex-copilot-dx 1.3.20 → 1.3.21

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 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) console.log(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 } }));
@@ -631,7 +631,9 @@ the lockfile fixes CI transitives, not consumers' future transitive resolution.
631
631
 
632
632
  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
633
 
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. Original upstream error status/body and protocol-specific stream bytes retain their existing path.
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. 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.
635
+
636
+ 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.
635
637
 
636
638
  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
639
 
package/docs/REFERENCE.md CHANGED
@@ -739,7 +739,7 @@ When expanded history exceeds Copilot's 50-image request limit, CCDX removes old
739
739
 
740
740
  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
741
 
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 pass through unchanged. CCDX does not decrypt that state locally.
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 are not retried. CCDX does not decrypt that state locally.
743
743
 
744
744
  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
745
 
@@ -759,6 +759,8 @@ Downstream backpressure waits also observe cancellation and the stream deadline.
759
759
 
760
760
  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
761
 
762
+ 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.
763
+
762
764
  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
765
 
764
766
  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 +803,7 @@ Covered text includes conversation instructions, message text, tool results, too
801
803
 
802
804
  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
805
 
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.
806
+ 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
807
 
806
808
  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
809
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.20",
3
+ "version": "1.3.21",
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",
@@ -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 }])) };
@@ -39,6 +39,25 @@ function send(res, code, value) {
39
39
  res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
40
40
  }
41
41
  const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
42
+ const MAX_TERMINAL_DRAIN_BYTES = 64 * 1024;
43
+ const TERMINAL_DRAIN_TIMEOUT_MS = 1000;
44
+ async function drainAfterMessageStop(reader) {
45
+ let bytes = 0, ended = false;
46
+ const cancel = () => { try { void reader.cancel().catch(() => {}); } catch {} };
47
+ const timer = setTimeout(cancel, TERMINAL_DRAIN_TIMEOUT_MS);timer.unref?.();
48
+ try {
49
+ while (true) {
50
+ const { done, value } = await reader.read();
51
+ if (done) { ended = true;break; }
52
+ bytes += value.byteLength;
53
+ if (bytes > MAX_TERMINAL_DRAIN_BYTES) break;
54
+ }
55
+ } catch { /* The response has already ended for the client. */ }
56
+ finally {
57
+ clearTimeout(timer);if (!ended) cancel();
58
+ try { reader.releaseLock(); } catch {}
59
+ }
60
+ }
42
61
  const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
43
62
  || typeof block.text === "string" && block.text.length || typeof block.thinking === "string" && block.thinking.length));
44
63
  function authenticated(headers, key) {
@@ -306,6 +325,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
306
325
  if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
307
326
  }, config.maxSseBufferBytes, clientModel);
308
327
  const reader = upstream.body.getReader();
328
+ let draining = false;
309
329
  try {
310
330
  while (true) {
311
331
  const { value, done } = await reader.read();if (done) break;
@@ -321,7 +341,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
321
341
  for (const chunk of tail) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
322
342
  if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
323
343
  if (!res.writableEnded) res.end();
324
- } finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
344
+ if (sawStop && !failedEvent && !abort.signal.aborted && !res.destroyed) {
345
+ draining = true;void drainAfterMessageStop(reader);
346
+ }
347
+ } finally {
348
+ if (!draining) { await reader.cancel().catch(() => {});reader.releaseLock(); }
349
+ }
325
350
  }
326
351
  } catch (error) {
327
352
  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
+ }
@@ -0,0 +1,264 @@
1
+ import { prepareSourceAccess, accessError, CLIENT_IDS } from "./access-settings.mjs";
2
+ import { publicModelCatalog } from "./provider-metadata.mjs";
3
+ import { createConnectionPolicy } from "./connection-policy.mjs";
4
+
5
+ const validObject = (value, keys) =>
6
+ value &&
7
+ typeof value === "object" &&
8
+ !Array.isArray(value) &&
9
+ Object.keys(value).every(key => keys.includes(key));
10
+ export function createConnectionManagement({ binding, catalogRefresh, save, discoveries, getSettings, env,
11
+ imageModels, enabled, getSource, legacy, capabilitySupport, capabilitySupportForSync, plan, snapshot, options, permitted, sourceImpact,
12
+ isManaged, isClosed, clientRevision, editable, syncClients, clientAccessChanged, setup, secrets, lifecycle, retire, memoryModel, enqueue, catalogVisibility }) {
13
+ const { removeApi, prepareApiSave, applyClientSelection, applyProviderEnabled } = createConnectionPolicy({
14
+ validObject, binding, catalogRefresh, save, discoveries, getSettings, env, imageModels, enabled, getSource, legacy,
15
+ capabilitySupport, capabilitySupportForSync, plan, snapshot, options, permitted, sourceImpact });
16
+
17
+ async function change(input) {
18
+ if (isClosed()) throw accessError("ccdx_connections_closed", 503);
19
+ if (
20
+ !validObject(input, [
21
+ "operation",
22
+ "id",
23
+ "config",
24
+ "key",
25
+ "allowed",
26
+ "source",
27
+ "enabled",
28
+ "replacements",
29
+ "impact_revision",
30
+ "model",
31
+ "auto_review_model",
32
+ "auto_review_effort",
33
+ "deployments",
34
+ "default_model",
35
+ "auto_sync",
36
+ "image_model",
37
+ "client_revision",
38
+ ])
39
+ )
40
+ throw accessError("ccdx_connections_action_invalid");
41
+ if (
42
+ ["client", "preview_client", "sync_client", "client_state", "image_model"].includes(input.operation) &&
43
+ input.client_revision !== undefined &&
44
+ (!CLIENT_IDS.includes(input.id) || input.client_revision !== clientRevision(input.id))
45
+ )
46
+ throw accessError("ccdx_connections_conflict", 409);
47
+ if (
48
+ !["client", "preview_client", "sync_client", "client_state", "image_model"].includes(input.operation) &&
49
+ input.impact_revision !== undefined &&
50
+ input.impact_revision !== sourceImpact(input.id).revision
51
+ )
52
+ throw accessError("ccdx_connections_conflict", 409);
53
+ if (input.operation === "image_model") {
54
+ if (!validObject(input, ["operation", "id", "model", "client_revision"]) || input.id !== "codex"
55
+ || !imageModels().models.some(model => model.id === input.model)) throw accessError("ccdx_api_model_unavailable");
56
+ const next = editable();next.clients.codex.image_model = input.model;save(next);
57
+ await syncClients(["codex"]);
58
+ return snapshot();
59
+ }
60
+ if (input.operation === "sync_client") {
61
+ if (
62
+ !validObject(input, ["operation", "id", "client_revision"]) ||
63
+ !CLIENT_IDS.includes(input.id) ||
64
+ typeof input.client_revision !== "string"
65
+ )
66
+ throw accessError("ccdx_connections_action_invalid");
67
+ await syncClients([input.id], { manual: true });
68
+ return snapshot();
69
+ }
70
+ if (input.operation === "client_state") {
71
+ if (
72
+ !validObject(input, ["operation", "id", "enabled", "client_revision"]) ||
73
+ !CLIENT_IDS.includes(input.id) ||
74
+ typeof input.enabled !== "boolean" ||
75
+ typeof input.client_revision !== "string"
76
+ )
77
+ throw accessError("ccdx_connections_action_invalid");
78
+ const next = editable();
79
+ next.clients[input.id].enabled = input.enabled;
80
+ save(next);
81
+ await syncClients([input.id]);
82
+ if (input.id === "codex") await clientAccessChanged?.(input.enabled);
83
+ return snapshot();
84
+ }
85
+ const next = editable();
86
+ let freshRef, previousRef;
87
+ if (input.operation === "source_access") {
88
+ const { targets, migrateClaude } = prepareSourceAccess(input, next);
89
+ save(next);
90
+ await syncClients([...targets]);
91
+ const retained = migrateClaude
92
+ ? [...targets].filter(
93
+ id => id !== "codex" && next.clients[id].enabled && next.clients[id].source === "m365"
94
+ )
95
+ : [];
96
+ return {
97
+ ...snapshot(),
98
+ client_refresh: retained.filter(id => setup[id] === "configured"),
99
+ client_review: retained.filter(id =>
100
+ ["preserved", "partially_preserved", "manual_sync", "configuration_unavailable"].includes(setup[id])
101
+ ),
102
+ };
103
+ } else if (input.operation === "remove_api") {
104
+ previousRef = removeApi(input, next);
105
+ } else if (input.operation === "save_api") {
106
+ ({ input, freshRef, previousRef } = prepareApiSave(input, next));
107
+ try {
108
+ if (freshRef) await secrets.set(freshRef, input.key);
109
+ save(next);
110
+ } catch (error) {
111
+ if (freshRef) await secrets.remove(freshRef).catch(() => {});
112
+ throw error;
113
+ }
114
+ } else if (["client", "preview_client"].includes(input.operation)) {
115
+ const preview = applyClientSelection(input, next);
116
+ if (input.operation === "preview_client") return preview;
117
+ } else if (input.operation === "provider") {
118
+ applyProviderEnabled(input, next);
119
+ if (input.id === "m365") {
120
+ if (input.enabled) await legacy.action({ action: "on" });
121
+ else {
122
+ const source = await legacy.pauseM365();
123
+ if (source) retire(source);
124
+ }
125
+ }
126
+ } else throw accessError("ccdx_connections_action_invalid");
127
+ await syncClients();
128
+ if (input.operation === "client" && input.id === "codex")
129
+ await clientAccessChanged?.(binding("codex").enabled);
130
+ if (previousRef && (freshRef || input.config?.key_env || input.operation === "remove_api")) {
131
+ lifecycle.retireSecret(input.id, previousRef);
132
+ }
133
+ return snapshot();
134
+ }
135
+ return {
136
+ async manageConnections(input) {
137
+ if (!input) {
138
+ if (binding("codex").enabled) void memoryModel.refresh();
139
+ return snapshot();
140
+ }
141
+ if (validObject(input, ["operation", "id"]) && input.operation === "source_catalog") {
142
+ if (!["github", "m365", ...getSettings().apis.map(api => api.id)].includes(input.id))
143
+ throw accessError("ccdx_connections_action_invalid");
144
+ const source = getSource(input.id),
145
+ raw = source?.catalog?.() || source?.registry?.models?.data;
146
+ return catalogVisibility({
147
+ source: input.id,
148
+ loaded: Array.isArray(raw),
149
+ evidence: input.id.startsWith("api_") ? "configured" : "cached",
150
+ access_checked: false,
151
+ models: publicModelCatalog(raw || []).map(({ selectable, clients, ...model }) => model),
152
+ }, input.id);
153
+ }
154
+ if (validObject(input, ["operation", "id"]) && input.operation === "discover") {
155
+ const models = await catalogRefresh.refresh(input.id, true);
156
+ return { ...snapshot(), discovered: models };
157
+ }
158
+ if (validObject(input, ["operation", "id"]) && input.operation === "cancel_discovery") {
159
+ catalogRefresh.cancel(input.id);
160
+ return snapshot();
161
+ }
162
+ const result = await enqueue(() => change(input));
163
+ if (input.operation === "save_api") {
164
+ const id =
165
+ input.id || result.providers.find(api => !api.builtin && api.name === input.config.name)?.id;
166
+ if (enabled(id)) void catalogRefresh.refresh(id).catch(() => {});
167
+ } else if (input.operation === "provider" && input.enabled && input.id?.startsWith("api_"))
168
+ void catalogRefresh.refresh(input.id).catch(() => {});
169
+ return input.operation === "save_api" ? snapshot() : result;
170
+ },
171
+ async action(input) {
172
+ if (isManaged() && input.action === "auto-review" && Array.isArray(binding("codex").deployments)) {
173
+ const c = binding("codex"),
174
+ compiled = plan("codex");
175
+ if (!c.enabled || input.provider !== c.source) throw accessError("ccdx_client_source_mismatch", 409);
176
+ const record = [...compiled.routes.values()].find(
177
+ record => record.source === input.provider && record.upstreamModel === input.model
178
+ );
179
+ if (!record) throw accessError("ccdx_api_model_unavailable");
180
+ if (input.effort && !record.model.capability.values.reasoning_efforts?.includes(input.effort))
181
+ throw accessError("ccdx_api_effort_unavailable");
182
+ const next = editable();
183
+ next.clients.codex.auto_review_model = record.model.route_id;
184
+ next.clients.codex.auto_review_effort = input.effort || null;
185
+ save(next);
186
+ return this.snapshot();
187
+ }
188
+ if (
189
+ isManaged() &&
190
+ input.action === "auto-review" &&
191
+ input.provider &&
192
+ input.provider !== this.selection().codex
193
+ )
194
+ throw accessError("ccdx_client_source_mismatch", 409);
195
+ if (
196
+ isManaged() &&
197
+ input.action === "auto-review" &&
198
+ (!binding("codex").enabled || !binding("codex").source)
199
+ )
200
+ throw accessError("ccdx_client_source_disabled", 503);
201
+ if (isManaged() && ["on", "off", "remove"].includes(input.action)) {
202
+ if (input.action === "remove" && legacy.snapshot().m365.active_requests > 0)
203
+ throw accessError("ccdx_source_busy", 409);
204
+ const replacements = Object.fromEntries(
205
+ CLIENT_IDS.filter(id => binding(id).source === "m365" && binding(id).enabled).map(id => [id, null])
206
+ );
207
+ await this.manageConnections({
208
+ operation: "provider",
209
+ id: "m365",
210
+ enabled: input.action === "on",
211
+ replacements,
212
+ });
213
+ if (input.action === "remove") legacy.removeM365SavedProfile();
214
+ return this.snapshot();
215
+ }
216
+ if (isManaged() && input.action === "switch" && !binding("codex").enabled)
217
+ throw accessError("ccdx_client_source_disabled", 503);
218
+ const { history_isolation, ...clientInput } = binding("codex");
219
+ if (input.action === "switch" && input.provider?.startsWith("api_")) {
220
+ await this.manageConnections({
221
+ operation: "client",
222
+ id: "codex",
223
+ ...clientInput,
224
+ deployments: null,
225
+ default_model: null,
226
+ source: input.provider,
227
+ model: input.model,
228
+ auto_review_model: input.auto_review_model,
229
+ auto_review_effort: input.auto_review_effort,
230
+ });
231
+ return this.snapshot();
232
+ }
233
+ if (input.action === "auto-review" && isManaged() && binding("codex").source !== "github") {
234
+ await this.manageConnections({
235
+ operation: "client",
236
+ id: "codex",
237
+ ...clientInput,
238
+ auto_review_model: input.model,
239
+ auto_review_effort: input.effort,
240
+ });
241
+ return this.snapshot();
242
+ }
243
+ if (input.action === "auto-review" && isManaged() && legacy.selection().codex !== "github")
244
+ await legacy.action({ action: "switch", provider: "github" });
245
+ if (isManaged() && input.action === "switch" && !enabled(input.provider))
246
+ throw accessError("ccdx_client_source_disabled", 503);
247
+ const result = await legacy.action(input);
248
+ if (isManaged() && input.action === "switch") {
249
+ const next = editable();
250
+ if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;
251
+ next.clients.codex.allowed = [...new Set([...next.clients.codex.allowed, input.provider])];
252
+ next.clients.codex.source = input.provider;
253
+ next.clients.codex.deployments = null;
254
+ next.clients.codex.default_model = null;
255
+ for (const key of ["model", "auto_review_model", "auto_review_effort"])
256
+ delete next.clients.codex[key];
257
+ if (input.provider === "m365") Object.assign(next.clients.codex, legacy.selection().m365);
258
+ save(next);
259
+ await syncClients(["codex"]);
260
+ }
261
+ return result;
262
+ },
263
+ };
264
+ }