codex-copilot-dx 1.2.23 → 1.2.24
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 +4 -4
- package/docs/ARCHITECTURE.md +32 -0
- package/docs/REFERENCE.md +74 -7
- package/package.json +1 -1
- package/src/adapter.mjs +2 -1
- package/src/api-catalog-refresh.mjs +2 -2
- package/src/api-model-display.mjs +47 -0
- package/src/claude-gateway.mjs +18 -9
- package/src/cli-status.mjs +1 -1
- package/src/codex-memory-model.mjs +64 -0
- package/src/codex-memory-probe.mjs +25 -0
- package/src/connection-runtime.mjs +22 -8
- package/src/dashboard/connections.js +61 -7
- package/src/dashboard/flow.js +3 -8
- package/src/dashboard/index.html +5 -0
- package/src/dashboard/language.js +31 -2
- package/src/dashboard/status.js +14 -7
- package/src/dashboard/ui.css +29 -6
- package/src/dashboard/ui.js +5 -2
- package/src/provider-metadata.mjs +2 -2
- package/src/providers/api-token-count.mjs +52 -47
- package/src/providers/api.mjs +11 -5
- package/src/providers/m365.mjs +1 -1
- package/src/response-failures.mjs +13 -5
- package/src/responses-handler.mjs +2 -0
- package/src/stream-performance.mjs +7 -3
package/README.md
CHANGED
|
@@ -11,11 +11,11 @@ npm install -g codex-copilot-dx@latest
|
|
|
11
11
|
ccdx
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
14
|
+
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.24/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.24/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
|
|
15
15
|
|
|
16
16
|
CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
|
|
17
17
|
|
|
18
|
-
The [local control console](http://127.0.0.1:2026/) separates Overview, Codex/Claude, Model sources, Usage, Requests, Checks & repairs and Settings, with a stable sticky header. Model sources owns API accounts, keys and model capabilities; application pages own visible models and defaults. Settings owns independent web/terminal colors (classic green, Klein blue or Soft pink), startup and updates. Accounts and model catalogs stay with Model sources; client-specific tools stay with their application. CLI remains English; WebUI supports English/Chinese. An interactive terminal shows bounded startup checks, source/client state, a usage table with approximate cache hit rate, notices and animation. Plain/NO_COLOR/narrow output remains supported; `--verbose` retains request detail.
|
|
18
|
+
The [local control console](http://127.0.0.1:2026/) separates Overview, Codex/Claude, Model sources, Usage, Requests, Checks & repairs and Settings, with a stable sticky header. Model sources owns API accounts, keys and model capabilities; application pages own visible models and defaults. Settings owns independent web/terminal colors (classic green, Klein blue or Soft pink), startup and updates. Accounts and model catalogs stay with Model sources; client-specific tools stay with their application. CLI remains English; WebUI supports English/Chinese. Codex shows evidenced memory-model dependencies and warns before closing them; native memory settings remain yours. An interactive terminal shows bounded startup checks, source/client state, a usage table with approximate cache hit rate, notices and animation. Plain/NO_COLOR/narrow output remains supported; `--verbose` retains request detail.
|
|
19
19
|
|
|
20
20
|
Requests shows live app/source/model flow above existing summaries and finished records; a thin theme-colored ring rotates around its atom while requests are active. Usage offers animated bars or curves; reduced motion stays static. Hidden pages stop scheduled reads; status refreshes about every two seconds and source/settings evidence about every 16 seconds. Catalogs and retained usage load on demand or every 30 minutes while open. The UI does not add inference calls. Ready means local service availability, not verified model access. First output uses ms, speed token/s, and partial/unknown usage remains explicit. Images/predictions stay opt-in; their first setup uses CLI. 1.2.18 preserves Codex sign-in and unavailable model selections after saving bindings. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings), [1.2.18 fixes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.18.md) and [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md).
|
|
21
21
|
|
|
@@ -52,11 +52,11 @@ Requests shows live app/source/model flow above existing summaries and finished
|
|
|
52
52
|
|
|
53
53
|
## Add your own API
|
|
54
54
|
|
|
55
|
-
Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. Token counting is separate from message generation. For manual APIs, an observed count-endpoint 404 is remembered for one minute per model/API-header scope; CCDX returns a clear 404 without inventing a token count. Identical
|
|
55
|
+
Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. Token counting is separate from message generation. For manual APIs, an observed count-endpoint 404 is remembered for one minute per model/API-header scope; CCDX returns a clear 404 without inventing a token count. Unknown count capabilities share their first admitted request; a 404 prevents distinct waiting inputs from fanning out. A supported endpoint still counts each distinct input separately. Identical small count requests share bounded work. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
|
|
56
56
|
|
|
57
57
|
Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving reads model metadata automatically, without inference. Startup and the existing model refresh cycle also refresh enabled APIs when the 30-minute cache expires; failed reads retain saved configuration. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
|
|
58
58
|
|
|
59
|
-
Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.
|
|
59
|
+
Model lists/details preserve the upstream maker declaration separately from your API source name. Missing maker metadata shows Not provided; model names are never used to guess a maker. Maker evidence is rebuildable display cache and does not change the strict connection schema or routing identity. Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.24 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.24.md) cover upstream maker metadata, first-wave token-count compatibility, memory-model dependency notices and dashed flow activity while retaining native GitHub sign-in/model protections.
|
|
60
60
|
|
|
61
61
|
## Microsoft 365 access
|
|
62
62
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -792,3 +792,35 @@ foreground freshness and the existing CSS motion remain unchanged. Catalog
|
|
|
792
792
|
failure backoff is source-revision scoped and never holds the configuration
|
|
793
793
|
transaction during network work. Existing body serialization ownership is
|
|
794
794
|
retained: the ordinary manual Responses path serializes its final body once.
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
## Display evidence and native memory dependency
|
|
798
|
+
|
|
799
|
+
Manual upstream identity declarations live in `api-model-display` cache owned
|
|
800
|
+
by the connection runtime, separate from strict connection v2 configuration and
|
|
801
|
+
capability values. `apiCatalog` no longer stamps Unknown as a maker. Public API
|
|
802
|
+
catalog projection decorates display data; native model IDs, auth, source/key
|
|
803
|
+
identity and capability constraints are unchanged. Catalog publication guards
|
|
804
|
+
also guard display evidence; failures cannot introduce an empty successful
|
|
805
|
+
catalog or extra upstream permissions.
|
|
806
|
+
|
|
807
|
+
The token counter separates unknown capability coordination from identical
|
|
808
|
+
result sharing. The first real admitted count owns the capability operation.
|
|
809
|
+
Different inputs may consume a 404 observation, but never another input's
|
|
810
|
+
successful count. Waiter cancellation is independent. Known support restores
|
|
811
|
+
normal parallel counts; state is bounded and source/configuration owned.
|
|
812
|
+
|
|
813
|
+
`codex-memory-model` owns optional extraction-role evidence. It reads explicit
|
|
814
|
+
native config and uses a separate bounded read-only SQLite helper only when
|
|
815
|
+
needed. It reports configuration, observation or uncertainty; it never selects
|
|
816
|
+
a model for Codex. WebUI owns the dependency notice/confirmation. The runtime
|
|
817
|
+
continues to reject requests outside selected deployments, including native
|
|
818
|
+
background jobs. Optional evidence is excluded from service handoff business
|
|
819
|
+
contracts and never modifies the client files.
|
|
820
|
+
|
|
821
|
+
Request observations retain scalar output budgets, usage and fixed stop/network
|
|
822
|
+
fields across protocol adapters. Generation, explicit access restrictions,
|
|
823
|
+
capability absence and protocol discovery remain distinct. Dashed flow motion
|
|
824
|
+
uses CSS stroke offset on retained paths; model nodes share the same left edge.
|
|
825
|
+
Geometry and SVG identity reuse from 1.2.23 remain in place, with hidden/stale/
|
|
826
|
+
reduced-motion behavior and summary tables preserved.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -1302,7 +1302,7 @@ Unknown support prevents an explicitly requested exception from starting.
|
|
|
1302
1302
|
For an older updater that still requires Git, install the Release tarball directly:
|
|
1303
1303
|
|
|
1304
1304
|
```sh
|
|
1305
|
-
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
1305
|
+
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.24/codex-copilot-dx-1.2.24.tgz
|
|
1306
1306
|
# Windows PowerShell: use npm.cmd instead of npm.
|
|
1307
1307
|
```
|
|
1308
1308
|
|
|
@@ -1694,11 +1694,11 @@ The protected `/_ccdx/ui/account` and `/_ccdx/ui/checks` APIs require loopback,
|
|
|
1694
1694
|
|
|
1695
1695
|
`http_errors.recent` keeps its 20-record rolling view. Independent
|
|
1696
1696
|
`actionable_recent` (20 generation/other failures and actionable count errors),
|
|
1697
|
-
`capability_recent` (20
|
|
1697
|
+
`capability_recent` (20 count/explicit-access notices), `route_recent` (eight path errors)
|
|
1698
1698
|
and `protocol_recent` (eight image-MCP HTTP 405 records) prevent route/method noise from erasing inference
|
|
1699
1699
|
evidence. `by_category` counts inference, capability, protocol, route and other HTTP failures;
|
|
1700
1700
|
classification does not discard errors, grant access or retry requests.
|
|
1701
|
-
The WebUI defaults to reply issues and provides separate capability and connection/path views. Repeated capability/path notices are grouped within the bounded retained records, with their occurrence count and latest request details; raw HTTP counters remain visible. A count-endpoint 404 is not a failed generation. Count authentication, rate-limit and server failures remain actionable.
|
|
1701
|
+
The WebUI defaults to reply issues and provides separate capability/access and connection/path views. Explicitly unselected models and turned-off access remain refused with their original HTTP status, but are notices rather than model-generation failures. Client disconnects remain in recent requests rather than being promoted to the issue list. Known non-model HTTP paths show Not applicable in the UI; unknown paths are retained, not assumed harmless. Repeated capability/path notices are grouped within the bounded retained records, with their occurrence count and latest request details; raw HTTP counters remain visible. A count-endpoint 404 is not a failed generation. Count authentication, rate-limit and server failures remain actionable.
|
|
1702
1702
|
|
|
1703
1703
|
Before model resolution, safe requested model IDs and the client hint are retained even for local rejection. Known binding failures include a specific reason: model not selected, ambiguous name, unavailable catalog entry or disabled access. These diagnostics never authorize a model or replace it with a default. Claude records propagate the actual model/source and distinguish a cached capability result from an upstream HTTP failure. Upstream attempts count logical calls; shared counts are marked `shared_upstream`, and cached 404s report zero calls. No prompt or key is retained.
|
|
1704
1704
|
|
|
@@ -2065,10 +2065,16 @@ this compatibility mechanism; status and safe Retry-After metadata survive.
|
|
|
2065
2065
|
|
|
2066
2066
|
Identical concurrent count requests share one bounded upstream operation.
|
|
2067
2067
|
Each caller cancels independently; the last cancelled waiter aborts shared
|
|
2068
|
-
work.
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2068
|
+
work. Before a model/header scope has a capability observation, distinct inputs
|
|
2069
|
+
wait for its first real admitted count request. An observed 404 is reused by
|
|
2070
|
+
those waiters; success is reused only for identical inputs. Distinct inputs
|
|
2071
|
+
then run their own counts. Capability waiting has at most 16 in-flight scopes
|
|
2072
|
+
and remains under normal gateway body/queue admission. Capability waiting and
|
|
2073
|
+
the caller's own count share its existing upstream timeout budget. Identical-result sharing
|
|
2074
|
+
is limited to bodies up to 1 MiB, 16 operations and 4 MiB of shared request text.
|
|
2075
|
+
Larger supported inputs and overflow use their normal admitted path. Count responses are capped at 64 KiB. At most 128 capability observations are retained. A 404 expires after one
|
|
2076
|
+
minute; a positive observation permits normal concurrency and a later 404 can
|
|
2077
|
+
replace it. Successful results and request bodies are not retained
|
|
2072
2078
|
after the operation. Counts neither invoke generation nor fail over to another
|
|
2073
2079
|
source. This does not supply a missing tokenizer or guarantee every Claude App
|
|
2074
2080
|
context-management feature on a third-party model.
|
|
@@ -2084,3 +2090,64 @@ Claude Code's validated `x-claude-code-agent-id` separates a child task's local
|
|
|
2084
2090
|
source guard from its parent's guard when a session is identified. Parent keys
|
|
2085
2091
|
without that header remain unchanged. This header is correlation only: model
|
|
2086
2092
|
access and the company's account/history checks remain authoritative.
|
|
2093
|
+
|
|
2094
|
+
|
|
2095
|
+
### Upstream maker metadata
|
|
2096
|
+
|
|
2097
|
+
Manual API discovery accepts bounded text from publisher, vendor and owned_by.
|
|
2098
|
+
The model maker shown in lists/details prefers publisher, then vendor; owned_by
|
|
2099
|
+
is shown separately as ownership and is not treated as the maker. Absent maker
|
|
2100
|
+
information is Not provided; no name-based inference is performed. These are
|
|
2101
|
+
upstream declarations, not proof of backend identity.
|
|
2102
|
+
|
|
2103
|
+
Rebuildable per-source files under `api-model-display/` beside settings are
|
|
2104
|
+
scoped by source ID and deployment revision. They preserve at most 500 models,
|
|
2105
|
+
512 KiB per file and 16 in-memory sources. They contain only model IDs and
|
|
2106
|
+
identity declarations, no key or response body. Old versions ignore them;
|
|
2107
|
+
connection v2 metadata remains readable during rollback. The new read-only
|
|
2108
|
+
`model_display` source field and per-discovery `display` field are ignored if
|
|
2109
|
+
round-tripped into Save API; unknown configuration fields still fail validation. Missing display
|
|
2110
|
+
evidence triggers the existing normal catalog read rather than requiring key
|
|
2111
|
+
entry or model reselection. Failed discovery retains valid prior evidence for
|
|
2112
|
+
the same revision; invalid optional display cache does not block inference.
|
|
2113
|
+
|
|
2114
|
+
### Memory-extraction dependency notices
|
|
2115
|
+
|
|
2116
|
+
The Codex model editor reads [`memories.extract_model`](https://learn.chatgpt.com/docs/customization/memories#configure-local-memories) when explicitly configured
|
|
2117
|
+
in the native Codex config. Otherwise, it may show a recently observed extraction
|
|
2118
|
+
model from a bounded read-only correlation of native Phase 1 task failures and
|
|
2119
|
+
one unambiguous local HTTP 400 model. No prompt, memory text or model-name
|
|
2120
|
+
heuristic is used. Explicit configuration is labelled Configured in Codex;
|
|
2121
|
+
observations are Recently observed. The current client does not expose its
|
|
2122
|
+
compiled default in the queried interface, so CCDX does not label a guessed
|
|
2123
|
+
model as Codex default. Without evidence it shows Not detected.
|
|
2124
|
+
|
|
2125
|
+
The optional native log helper runs only on startup/connection-view reads (including an explicit WebUI refresh),
|
|
2126
|
+
coalesced and at least one minute apart, with a 2.5-second limit. It reads up to
|
|
2127
|
+
eight task records and sixteen candidate HTTP records each, clipped to 8 KiB,
|
|
2128
|
+
from the prior 24 hours. It uses the bundled Node SQLite API in a separate
|
|
2129
|
+
read-only process; missing/locked/unsupported stores remain optional. Only a
|
|
2130
|
+
model ID and observation time can enter `codex-memory-observed.json`, scoped by
|
|
2131
|
+
the Codex profile, with a 24-hour freshness bound. No periodic log scanner,
|
|
2132
|
+
account lookup, native Codex process or inference is started by this helper.
|
|
2133
|
+
|
|
2134
|
+
Closing a known extraction model or its source in WebUI prompts about new-memory
|
|
2135
|
+
generation and preserves your explicit decision. The draft is separate from the
|
|
2136
|
+
saved selection. Existing memories are not deleted. Native memory generation
|
|
2137
|
+
settings, model aliases, defaults, authentication and authorization are not
|
|
2138
|
+
changed to satisfy a dependency. Confirmations are WebUI guidance, not a new
|
|
2139
|
+
requirement on existing CLI/API operations. A notice does not identify every
|
|
2140
|
+
background task or prove that memory generation succeeded.
|
|
2141
|
+
|
|
2142
|
+
### Messages stop and network evidence
|
|
2143
|
+
|
|
2144
|
+
Recent Messages records retain declared context size, requested and forwarded
|
|
2145
|
+
output budgets, normalized returned input/output usage, and an allowlisted stop
|
|
2146
|
+
reason when supplied. Missing values remain unknown. `max_tokens` is shown as
|
|
2147
|
+
output-limit termination; CCDX does not raise an undeclared GLM output limit or
|
|
2148
|
+
use context length as an output ceiling. HTTP success and complete generation
|
|
2149
|
+
remain distinct.
|
|
2150
|
+
|
|
2151
|
+
API transport errors retain fixed safe code, DNS/connect/TLS/request/response
|
|
2152
|
+
phase and reused-socket state in HTTP diagnostics. They do not retain raw
|
|
2153
|
+
exceptions or URLs, and do not trigger automatic POST or cross-source retries.
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -430,7 +430,8 @@ export function createAdapterHandler(options = {}) {
|
|
|
430
430
|
})); } catch {}
|
|
431
431
|
}
|
|
432
432
|
try { complete({ statusCode, aborted }); } catch {}
|
|
433
|
-
try { streamPerformance?.finish({ failed: aborted || statusCode >= 400, aborted, statusCode
|
|
433
|
+
try { streamPerformance?.finish({ failed: aborted || statusCode >= 400, aborted, statusCode,
|
|
434
|
+
rejectionReason: httpEvidence.reason || (httpEvidence.code === "ccdx_client_source_disabled" ? httpEvidence.code : undefined) }); } catch {}
|
|
434
435
|
try { finishTerminalActivity(); } catch {}
|
|
435
436
|
try { context?.finishProvider?.(); } catch {}
|
|
436
437
|
};
|
|
@@ -2,7 +2,7 @@ import { accessError } from "./access-settings.mjs";
|
|
|
2
2
|
|
|
3
3
|
// Network work never holds the configuration transaction. Only publication
|
|
4
4
|
// enters the caller's short, version-checked commit boundary.
|
|
5
|
-
export function createApiCatalogRefresh({ config, source, track, revision, commit, onState, now = Date.now }) {
|
|
5
|
+
export function createApiCatalogRefresh({ config, source, track, revision, commit, onState, complete = () => true, now = Date.now }) {
|
|
6
6
|
const reads = new Map(), flights = new Map(), pending = new Set();let closed = false, batch;
|
|
7
7
|
const current = (id, version) => !closed && config(id)?.enabled && revision(config(id)) === version;
|
|
8
8
|
function cancel(id) {
|
|
@@ -28,7 +28,7 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
|
|
|
28
28
|
onState(id, { state: "ready", checked_at: new Date(cached.at).toISOString() });return cached.models;
|
|
29
29
|
}
|
|
30
30
|
const savedAge = now() - Date.parse(selected.checked_at);
|
|
31
|
-
if (!force && !cached && savedAge >= 0 && savedAge < 30 * 60000 && selected.models.every(model => model.metadata?.state && model.metadata.deployment === version)) return selected.models;
|
|
31
|
+
if (!force && !cached && savedAge >= 0 && savedAge < 30 * 60000 && complete(selected) && selected.models.every(model => model.metadata?.state && model.metadata.deployment === version)) return selected.models;
|
|
32
32
|
const flight = { revision: version, controller: new AbortController() };
|
|
33
33
|
flights.set(id, flight);
|
|
34
34
|
const active = () => current(id, version) && flights.get(id) === flight && !flight.controller.signal.aborted;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { accessSettingsPath } from "./access-settings.mjs";
|
|
4
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
5
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
6
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
7
|
+
|
|
8
|
+
export function apiModelDisplay(model) {
|
|
9
|
+
return Object.fromEntries(["publisher", "vendor", "owned_by"].flatMap(key => {
|
|
10
|
+
const value = model?.[key];
|
|
11
|
+
return typeof value === "string" && value.trim() && value.length <= 160
|
|
12
|
+
&& !/[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/.test(value) && redactDiagnosticText(value) === value ? [[key, value.trim()]] : [];
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Display-only evidence lives outside the strict connection schema. Older
|
|
17
|
+
// versions ignore it; losing this cache never changes routing or credentials.
|
|
18
|
+
export function createApiModelDisplayStore(options = {}) {
|
|
19
|
+
const directory = path.join(path.dirname(accessSettingsPath(options)), "api-model-display"), cache = new Map();
|
|
20
|
+
const file = id => { if (!/^api_[a-zA-Z0-9_-]{1,60}$/.test(id)) throw Error("Invalid model display source");return path.join(directory, id + ".json"); };
|
|
21
|
+
const validate = (value, revision) => {
|
|
22
|
+
if (value?.version !== 1 || value.revision !== revision || !Array.isArray(value.models) || value.models.length > 500) return null;
|
|
23
|
+
const map = new Map();
|
|
24
|
+
for (const item of value.models) {
|
|
25
|
+
if (typeof item?.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(item.id) || map.has(item.id)) return null;
|
|
26
|
+
map.set(item.id, apiModelDisplay(item));
|
|
27
|
+
}
|
|
28
|
+
return map;
|
|
29
|
+
};
|
|
30
|
+
function read(id, revision) {
|
|
31
|
+
const old = cache.get(id);if (old?.revision === revision) return old.models;
|
|
32
|
+
let models = null;
|
|
33
|
+
try { models = validate(JSON.parse(readBoundedFileSync(file(id), { encoding: "utf8", maxBytes: 512 * 1024 })), revision); } catch {}
|
|
34
|
+
cache.set(id, { revision, models });while (cache.size > 16) cache.delete(cache.keys().next().value);
|
|
35
|
+
return models;
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
has: (id, revision) => read(id, revision) !== null,
|
|
39
|
+
get: (id, revision, model) => read(id, revision)?.get(model) || {},
|
|
40
|
+
set(id, revision, models) {
|
|
41
|
+
const value = { version: 1, revision, models: models.map(model => ({ id: model.id, ...apiModelDisplay(model.display) })) };
|
|
42
|
+
const checked = validate(value, revision), text = JSON.stringify(value) + "\n";
|
|
43
|
+
if (!checked || Buffer.byteLength(text) > 512 * 1024) throw Error("Invalid model display cache");
|
|
44
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });atomicWriteFileSync(file(id), text, { mode: 0o600 });cache.set(id, { revision, models: checked });while (cache.size > 16) cache.delete(cache.keys().next().value);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -8,8 +8,8 @@ import { loadRuntimeConfig } from "./runtime-config.mjs";
|
|
|
8
8
|
import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
|
|
9
9
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
10
10
|
import { runWithRequestContext, currentRequestContext, observeRequestedModel } from "./request-context.mjs";
|
|
11
|
-
import { upstreamErrorEvidence } from "./response-failures.mjs";
|
|
12
|
-
import { createStreamPerformanceMetrics, isMessagesOutputDelta } from "./stream-performance.mjs";
|
|
11
|
+
import { upstreamErrorEvidence, requestOptionsEvidence } from "./response-failures.mjs";
|
|
12
|
+
import { createStreamPerformanceMetrics, isMessagesOutputDelta, markRequestObservation } from "./stream-performance.mjs";
|
|
13
13
|
import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
|
|
14
14
|
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
15
15
|
import { decodedBodyLimitPreference } from "./user-settings.mjs";
|
|
@@ -120,7 +120,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
120
120
|
if (!resolveRequest) tracker?.setProvider(provider.id);
|
|
121
121
|
const abort = createRequestAbort(req, res);
|
|
122
122
|
let release = () => {}, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
|
|
123
|
-
let terminalOrigin = "client_validation", failureStatus = null;
|
|
123
|
+
let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
|
|
124
124
|
if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
|
|
125
125
|
const context = parent || { requestId };
|
|
126
126
|
context.provider = selectedProvider.id;context.application = requestApplication(req.headers, "claude");
|
|
@@ -131,6 +131,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
131
131
|
abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
|
|
132
132
|
let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
|
|
133
133
|
observeRequestedModel(body);
|
|
134
|
+
context.requestOptions = requestOptionsEvidence(body);
|
|
134
135
|
if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
|
|
135
136
|
send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
|
|
136
137
|
}
|
|
@@ -148,6 +149,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
148
149
|
if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
|
|
149
150
|
stats.last_model = model;
|
|
150
151
|
context.model = configuredModel || model;
|
|
152
|
+
if (!countTokens) markRequestObservation({ max_output_tokens_requested: body.max_tokens });
|
|
151
153
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
|
|
152
154
|
validateConversation?.(body, req.headers, selectedProvider);
|
|
153
155
|
terminalOrigin = "transport";
|
|
@@ -156,7 +158,11 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
156
158
|
context.countObservation = { ...context.countObservation, ...value };
|
|
157
159
|
if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
|
|
158
160
|
},
|
|
159
|
-
onUpstreamStart() {
|
|
161
|
+
onUpstreamStart() {
|
|
162
|
+
const timeout = streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs;
|
|
163
|
+
if (countTokens) countDeadline ??= Date.now() + timeout;
|
|
164
|
+
abort.setTimeout(countTokens ? Math.max(1, countDeadline - Date.now()) : timeout, "upstream_timeout");
|
|
165
|
+
} });
|
|
160
166
|
body = null;
|
|
161
167
|
terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
|
|
162
168
|
tracker?.upstreamHeaders(upstream.status);
|
|
@@ -205,6 +211,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
205
211
|
} finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
|
|
206
212
|
}
|
|
207
213
|
} catch (error) {
|
|
214
|
+
rejectionReason = error.jsonBody?.error?.reason || (error.code === "ccdx_client_source_disabled" ? error.code : undefined);
|
|
208
215
|
const detail = operationErrorDetails(error, { reason: abort.reason });
|
|
209
216
|
outcome = detail.source === "cancelled" ? "cancelled" : "failed";
|
|
210
217
|
const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
|
|
@@ -214,7 +221,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
214
221
|
const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
|
|
215
222
|
log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
|
|
216
223
|
tracker?.setErrorOrigin(terminalOrigin);
|
|
217
|
-
context.onHttpError?.({ code: detail.code, origin: terminalOrigin });
|
|
224
|
+
context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(diagnostic ? { transport: diagnostic } : {}) });
|
|
218
225
|
if (outcome === "cancelled") return;
|
|
219
226
|
if (!res.headersSent) {
|
|
220
227
|
const value = apiError(error.code || abort.reason || "ccdx_gateway_error", message);
|
|
@@ -226,11 +233,13 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
226
233
|
release();abort.cleanup();finishProvider();
|
|
227
234
|
if (!countTokens) {
|
|
228
235
|
stats.active--;stats[outcome]++;
|
|
236
|
+
const usageRecord = buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json",
|
|
237
|
+
client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude", provider: selectedProvider.id });
|
|
238
|
+
markRequestObservation({ input_tokens: usageRecord?.usage?.input_tokens, output_tokens: usageRecord?.usage?.output_tokens });
|
|
229
239
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
|
|
230
|
-
tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
|
|
231
|
-
tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode });
|
|
232
|
-
|
|
233
|
-
try { void Promise.resolve(record(buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json", client, provider: selectedProvider.id }))).catch(() => {}); } catch {}
|
|
240
|
+
tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, stopReason, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
|
|
241
|
+
tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode, rejectionReason });
|
|
242
|
+
try { void Promise.resolve(record(usageRecord)).catch(() => {}); } catch {}
|
|
234
243
|
}
|
|
235
244
|
}
|
|
236
245
|
});
|
package/src/cli-status.mjs
CHANGED
|
@@ -200,7 +200,7 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
|
|
|
200
200
|
if (data.http_errors) {
|
|
201
201
|
lines.push(status("info", `HTTP failures: ${count(data.http_errors.total)} observed (separate from model terminal events)`));
|
|
202
202
|
const categories = data.http_errors.by_category;
|
|
203
|
-
if (categories) lines.push(status("info", `HTTP categories: ${count(categories.inference)} generation, ${count(categories.capability)}
|
|
203
|
+
if (categories) lines.push(status("info", `HTTP categories: ${count(categories.inference)} generation, ${count(categories.capability)} capability/access, ${count(categories.protocol)} unsupported MCP methods, ${count(categories.route)} unmatched routes, ${count(categories.other)} other`));
|
|
204
204
|
for (const failure of (data.http_errors.actionable_recent || []).slice(-3).reverse()) {
|
|
205
205
|
lines.push(status("warn", `HTTP ${count(failure.http_status)} ${terminalCell(failure.model)} ${terminalCell(failure.code)}${failure.reason ? ` reason=${terminalCell(failure.reason)}` : ""}${failure.parameter ? ` param=${terminalCell(failure.parameter)}` : ""}; ${terminalCell(failure.origin)}; ${count(failure.upstream_attempts)} attempts`));
|
|
206
206
|
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { parse } from "smol-toml";
|
|
8
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
9
|
+
import { accessSettingsPath } from "./access-settings.mjs";
|
|
10
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
11
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
12
|
+
import { privateHelperEnvironment } from "./private-helper-environment.mjs";
|
|
13
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
14
|
+
|
|
15
|
+
const modelId = value => typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value) && redactDiagnosticText(value) === value;
|
|
16
|
+
export function createCodexMemoryModel({ corePort = 2026, probe, now = Date.now, ...options } = {}) {
|
|
17
|
+
const paths = codexPaths(options), file = path.join(path.dirname(accessSettingsPath(options)), "codex-memory-observed.json");
|
|
18
|
+
const profile = createHash("sha256").update(paths.directory).digest("hex"), controller = new AbortController();
|
|
19
|
+
let observation, state = { model: null, basis: "unknown", enabled: null }, flight, lastRead = -Infinity;
|
|
20
|
+
try {
|
|
21
|
+
const saved = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 4096 }));
|
|
22
|
+
if (saved.version === 1 && saved.profile === profile && modelId(saved.model) && Number.isFinite(saved.at) && now() - saved.at >= 0 && now() - saved.at < 86400000) observation = { model: saved.model, at: saved.at };
|
|
23
|
+
} catch {}
|
|
24
|
+
const inspect = probe || (async directory => {
|
|
25
|
+
const { stdout } = await promisify(execFile)(process.execPath, ["--disable-warning=ExperimentalWarning", fileURLToPath(new URL("./codex-memory-probe.mjs", import.meta.url)), directory,
|
|
26
|
+
`http://127.0.0.1:${corePort}/v1`, String(Math.floor((now() - 86400000) / 1000))],
|
|
27
|
+
{ env: privateHelperEnvironment(options.env || process.env), signal: controller.signal, timeout: 2500, maxBuffer: 16384, windowsHide: true });
|
|
28
|
+
return JSON.parse(stdout);
|
|
29
|
+
});
|
|
30
|
+
return {
|
|
31
|
+
snapshot: () => ({ ...state }),
|
|
32
|
+
refresh() {
|
|
33
|
+
if (flight) return flight;
|
|
34
|
+
if (controller.signal.aborted || now() - lastRead < 60000) return Promise.resolve();
|
|
35
|
+
lastRead = now();
|
|
36
|
+
if (observation && (now() - observation.at < 0 || now() - observation.at >= 86400000)) observation = null;
|
|
37
|
+
flight = (async () => {
|
|
38
|
+
let config = {};
|
|
39
|
+
try { config = parse(readBoundedFileSync(paths.config, { encoding: "utf8", maxBytes: 1024 * 1024 })); }
|
|
40
|
+
catch (error) { if (error.code !== "ENOENT") { state = { model: null, basis: "unavailable", enabled: null };return; } }
|
|
41
|
+
const enabled = config.features?.memories === false || config.memories?.generate_memories === false ? false
|
|
42
|
+
: config.features?.memories === true ? true : null;
|
|
43
|
+
const configured = config.memories?.extract_model;
|
|
44
|
+
if (configured !== undefined && !modelId(configured)) { state = { model: null, basis: "unavailable", enabled };return; }
|
|
45
|
+
if (modelId(configured)) { state = { model: configured, basis: "configured", enabled };return; }
|
|
46
|
+
state = { model: observation?.model || null, basis: observation ? "observed" : "unknown", enabled,
|
|
47
|
+
...(observation ? { observed_at: new Date(observation.at).toISOString() } : {}) };
|
|
48
|
+
const directory = typeof config.sqlite_home === "string" ? path.resolve(config.sqlite_home) : paths.directory;
|
|
49
|
+
if (enabled === false || !probe && !fs.existsSync(path.join(directory, "logs_2.sqlite"))) return;
|
|
50
|
+
try {
|
|
51
|
+
const seen = await inspect(directory);
|
|
52
|
+
if (!modelId(seen?.model) || !Number.isFinite(seen.at) || now() - seen.at < 0 || now() - seen.at >= 86400000 || controller.signal.aborted) return;
|
|
53
|
+
const changed = observation?.model !== seen.model || observation?.at !== seen.at;
|
|
54
|
+
observation = { model: seen.model, at: seen.at };state = { model: seen.model, basis: "observed", enabled, observed_at: new Date(seen.at).toISOString() };
|
|
55
|
+
if (changed && !options.preserveClientConfiguration?.()) {
|
|
56
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });atomicWriteFileSync(file, JSON.stringify({ version: 1, profile, ...observation }) + "\n", { mode: 0o600 });
|
|
57
|
+
}
|
|
58
|
+
} catch {}
|
|
59
|
+
})().finally(() => { flight = null; });
|
|
60
|
+
return flight;
|
|
61
|
+
},
|
|
62
|
+
async close() { controller.abort();await flight; },
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Read-only, bounded native task metadata. This helper never reads memories or
|
|
2
|
+
// invokes Codex. It runs separately so unavailable/locked databases stay optional.
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
let db;
|
|
7
|
+
try {
|
|
8
|
+
const [directory, base, since] = process.argv.slice(2);
|
|
9
|
+
db = new DatabaseSync(path.join(directory, "logs_2.sqlite"), { readOnly: true });
|
|
10
|
+
const jobs = db.prepare("SELECT ts, process_uuid, substr(feedback_log_body,1,8192) AS body FROM logs WHERE ts>=? AND target='codex_memories_write::phase1::job::result' ORDER BY ts DESC LIMIT 8").all(Number(since));
|
|
11
|
+
let result = null;
|
|
12
|
+
for (const job of jobs) {
|
|
13
|
+
if (!job.body?.includes("ccdx_api_model_unavailable")) continue;
|
|
14
|
+
const calls = db.prepare("SELECT ts, substr(feedback_log_body,1,8192) AS body FROM logs WHERE ts BETWEEN ? AND ? AND process_uuid=? AND target='codex_http_client::client' ORDER BY ts DESC LIMIT 16").all(job.ts - 2, job.ts + 1, job.process_uuid);
|
|
15
|
+
const models = new Set();
|
|
16
|
+
for (const call of calls) {
|
|
17
|
+
if (!call.body?.includes("url=" + base + "/responses ") || !call.body.includes("status=400 ")) continue;
|
|
18
|
+
const model = /model_client\.stream_responses_api\{model=([\w./:@+-]{1,160})(?:\s|\})/.exec(call.body)?.[1];
|
|
19
|
+
if (model) models.add(model);
|
|
20
|
+
}
|
|
21
|
+
if (models.size === 1) { result = { model: [...models][0], at: job.ts * 1000 };break; }
|
|
22
|
+
}
|
|
23
|
+
console.log(JSON.stringify(result));
|
|
24
|
+
} catch { console.log("null"); }
|
|
25
|
+
finally { db?.close(); }
|
|
@@ -4,6 +4,8 @@ import { accessSettingsPath, readAccessSettings, updateAccessSettings, checkedAp
|
|
|
4
4
|
import { createApiSecretStore, checkedApiKey } from "./api-secrets.mjs";
|
|
5
5
|
import { createApiCatalogRefresh } from "./api-catalog-refresh.mjs";
|
|
6
6
|
import { createApiProvider } from "./providers/api.mjs";
|
|
7
|
+
import { createApiModelDisplayStore } from "./api-model-display.mjs";
|
|
8
|
+
import { createCodexMemoryModel } from "./codex-memory-model.mjs";
|
|
7
9
|
import { readClientGatewayKeys, gatewayClient } from "./client-gateway-keys.mjs";
|
|
8
10
|
import { createClaudeGatewayHandler } from "./claude-gateway.mjs";
|
|
9
11
|
import { configureClaudeClients, restoreClaudeClients, inspectClaudeDesktopPolicy } from "./claude-client-config.mjs";
|
|
@@ -21,12 +23,14 @@ const validObject = (value, keys) => value && typeof value === "object" && !Arra
|
|
|
21
23
|
export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
|
|
22
24
|
secretStore, createApi = createApiProvider, configureClaude = configureClaudeClients, restoreClaude = restoreClaudeClients,
|
|
23
25
|
configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, preserveClientConfiguration, now = Date.now, log = () => {} } = {}) {
|
|
24
|
-
const options = { home, env, platform, preserveClientConfiguration }, secrets = secretStore || createApiSecretStore(options);
|
|
26
|
+
const options = { home, env, platform, preserveClientConfiguration }, secrets = secretStore || createApiSecretStore(options), modelDisplay = createApiModelDisplayStore(options);
|
|
25
27
|
const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
|
|
28
|
+
const memoryModel = createCodexMemoryModel({ ...options, corePort });
|
|
26
29
|
let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
|
|
27
30
|
const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
|
|
28
31
|
const retiredSecrets = new Map(), cleanups = new Set(), plans = new Map(), discoveries = new Map();
|
|
29
32
|
const catalogRefresh = createApiCatalogRefresh({ config: id => settings.apis.find(api => api.id === id), source: getSource, track,
|
|
33
|
+
complete: api => modelDisplay.has(api.id, deploymentRevision(api, env)),
|
|
30
34
|
revision: api => deploymentRevision(api, env), now,
|
|
31
35
|
commit: (...args) => enqueue(() => applyCatalog(...args)),
|
|
32
36
|
onState: (id, state) => state ? discoveries.set(id, state) : discoveries.delete(id) });
|
|
@@ -61,7 +65,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
61
65
|
const previous = instances.get(id), revision = deploymentRevision(config, env);if (previous?.config === config && previous.revision === revision) return previous.source;
|
|
62
66
|
const signature = JSON.stringify(config) + revision;
|
|
63
67
|
if (previous?.signature === signature) return previous.source;
|
|
64
|
-
const source = createApi({ config, secrets, env: { ...env }, platform });instances.set(id, { signature, source, config, revision });sourceSecrets.set(source, config.secret_ref);
|
|
68
|
+
const source = createApi({ config, secrets, env: { ...env }, platform, modelDisplay: model => modelDisplay.get(id, revision, model) });instances.set(id, { signature, source, config, revision });sourceSecrets.set(source, config.secret_ref);
|
|
65
69
|
if (previous) retire(previous.source);return source;
|
|
66
70
|
}
|
|
67
71
|
function plan(id) {
|
|
@@ -121,9 +125,11 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
121
125
|
return structuredClone({ source: "connections", providers: [
|
|
122
126
|
{ id: "github", name: "GitHub Copilot", enabled: config.providers.github, builtin: true, protocols: ["responses"] },
|
|
123
127
|
{ id: "m365", name: "Microsoft 365", enabled: config.providers.m365, builtin: true, protocols: ["messages", "responses"] },
|
|
124
|
-
...config.apis.map(api => { const { secret_ref, ...publicApi } = api;return { ...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
|
|
125
|
-
...summary(api), ...(compact ? {} : { deployment_revision:
|
|
128
|
+
...config.apis.map(api => { const { secret_ref, ...publicApi } = api, revision = compact ? null : deploymentRevision(api, env);return { ...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
|
|
129
|
+
...summary(api), ...(compact ? {} : { deployment_revision: revision,
|
|
130
|
+
model_display: Object.fromEntries(api.models.map(model => [model.id, modelDisplay.get(api.id, revision, model.id)])) }), discovery: discoveries.get(api.id) || null, builtin: false, key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref) }; }),
|
|
126
131
|
], clients: CLIENT_IDS.map(id => ({ id, name: CLIENT_NAMES[id], ...config.clients[id], setup: setup[id] || null,
|
|
132
|
+
...(id === "codex" ? { memory_model: memoryModel.snapshot() } : {}),
|
|
127
133
|
observed_at: lastClients[id] || null, ...(compact ? {} : { model_plan: { default_model: plan(id).defaultModel, default_unavailable: plan(id).defaultUnavailable,
|
|
128
134
|
models: plan(id).models.map(model => ({ source: model.source_id, id: model.id, public_id: model.public_id, route_id: model.route_id, capability: model.capability })),
|
|
129
135
|
unavailable: (config.clients[id].deployments || []).filter(item => !plan(id).models.some(model => model.source_id === item.source && model.id === item.model))
|
|
@@ -194,6 +200,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
194
200
|
const next = editable(), current = next.apis.find(api => api.id === id);
|
|
195
201
|
if (!current?.enabled || deploymentRevision(current, env) !== revision) throw accessError("ccdx_connections_conflict", 409);
|
|
196
202
|
const byId = new Map(models.map(model => [model.id, model]));
|
|
203
|
+
try { modelDisplay.set(id, revision, models); } catch { log("warn", "Model maker metadata could not be saved; routing is unchanged"); }
|
|
197
204
|
for (const model of current.models) if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
|
|
198
205
|
current.checked_at = checkedAt;
|
|
199
206
|
if (JSON.stringify(current) !== JSON.stringify(settings.apis.find(api => api.id === id))) {
|
|
@@ -209,7 +216,14 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
209
216
|
if (input.operation === "save_api") {
|
|
210
217
|
const existing = next.apis.find(api => api.id === input.id);
|
|
211
218
|
if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
|
|
212
|
-
if (!validObject(input.config, ["name", "base_url", "endpoints", "auth_header", "models", "key_env"])) throw accessError("ccdx_api_config_invalid");
|
|
219
|
+
if (!validObject(input.config, ["name", "base_url", "endpoints", "auth_header", "models", "key_env", "model_display"])) throw accessError("ccdx_api_config_invalid");
|
|
220
|
+
// Existing clients round-trip catalog data. New display-only fields must
|
|
221
|
+
// remain readable without becoming editable connection configuration.
|
|
222
|
+
const { model_display, ...editableConfig } = input.config;
|
|
223
|
+
input = { ...input, config: { ...editableConfig, models: Array.isArray(editableConfig.models) ? editableConfig.models.map(model => {
|
|
224
|
+
if (!model || typeof model !== "object" || Array.isArray(model)) return model;
|
|
225
|
+
const { display, ...editable } = model;return editable;
|
|
226
|
+
}) : editableConfig.models } };
|
|
213
227
|
const id = existing?.id || "api_" + randomBytes(8).toString("hex");
|
|
214
228
|
if (input.key !== undefined && input.key !== "") { checkedApiKey(input.key);freshRef = randomBytes(16).toString("hex"); }
|
|
215
229
|
if (input.config.key_env && freshRef || !input.config.key_env && !freshRef && !existing?.secret_ref) throw accessError("ccdx_api_key_invalid");
|
|
@@ -336,7 +350,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
336
350
|
busy: () => operations > 0 || active.size > 0 || Boolean(syncFlight) || catalogRefresh.busy() || legacy.snapshot().m365.account_change_in_flight === true || legacy.snapshot().m365.state === "checking",
|
|
337
351
|
syncClients,
|
|
338
352
|
async manageConnections(input) {
|
|
339
|
-
if (!input) return snapshot();
|
|
353
|
+
if (!input) { if (binding("codex").enabled) void memoryModel.refresh();return snapshot(); }
|
|
340
354
|
if (validObject(input, ["operation", "id"]) && input.operation === "discover") {
|
|
341
355
|
const models = await catalogRefresh.refresh(input.id, true);return { ...snapshot(), discovered: models };
|
|
342
356
|
}
|
|
@@ -348,7 +362,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
348
362
|
} else if (input.operation === "provider" && input.enabled && input.id?.startsWith("api_")) void catalogRefresh.refresh(input.id).catch(() => {});
|
|
349
363
|
return input.operation === "save_api" ? snapshot() : result;
|
|
350
364
|
},
|
|
351
|
-
async start() { const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();void refreshApis();return result; },
|
|
365
|
+
async start() { if (binding("codex").enabled) void memoryModel.refresh();const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();void refreshApis();return result; },
|
|
352
366
|
async refresh() { const result = await Promise.allSettled([!managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(), refreshApis()]);if (result[0].status === "rejected") throw result[0].reason; },
|
|
353
367
|
selection() { return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null }; },
|
|
354
368
|
providerPreference(id) {
|
|
@@ -492,6 +506,6 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
492
506
|
if (managed && input.action === "switch") { const next = editable();if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;next.clients.codex.source = input.provider;next.clients.codex.deployments = null;next.clients.codex.default_model = null;for (const key of ["model", "auto_review_model", "auto_review_effort"]) delete next.clients.codex[key];if (input.provider === "m365") Object.assign(next.clients.codex, legacy.selection().m365);save(next);await syncClients(); }
|
|
493
507
|
return result;
|
|
494
508
|
},
|
|
495
|
-
async close() { closed = true;await catalogRefresh.close();await serial;await syncFlight;for (const { source } of instances.values()) source.close();for (const source of retired) source.close();active.clear();for (const id of retiredSecrets.keys()) cleanSecrets(id);await Promise.allSettled([...cleanups]);secrets.close();await legacy.close(); },
|
|
509
|
+
async close() { closed = true;await memoryModel.close();await catalogRefresh.close();await serial;await syncFlight;for (const { source } of instances.values()) source.close();for (const source of retired) source.close();active.clear();for (const id of retiredSecrets.keys()) cleanSecrets(id);await Promise.allSettled([...cleanups]);secrets.close();await legacy.close(); },
|
|
496
510
|
};
|
|
497
511
|
}
|