codex-copilot-dx 1.2.22 → 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 +56 -0
- package/docs/REFERENCE.md +110 -5
- package/package.json +1 -1
- package/src/adapter.mjs +8 -5
- package/src/api-catalog-refresh.mjs +7 -4
- package/src/api-model-display.mjs +47 -0
- package/src/claude-gateway.mjs +35 -10
- package/src/cli-status.mjs +2 -2
- package/src/codex-memory-model.mjs +64 -0
- package/src/codex-memory-probe.mjs +25 -0
- package/src/connection-runtime.mjs +31 -9
- package/src/conversation-source-guard.mjs +3 -1
- package/src/dashboard/connections.js +61 -7
- package/src/dashboard/console.js +6 -1
- package/src/dashboard/flow.js +40 -26
- package/src/dashboard/index.html +7 -0
- package/src/dashboard/language.js +52 -0
- package/src/dashboard/status.js +42 -14
- package/src/dashboard/ui.css +31 -6
- package/src/dashboard/ui.js +5 -2
- package/src/provider-metadata.mjs +2 -2
- package/src/providers/api-token-count.mjs +66 -0
- package/src/providers/api.mjs +21 -7
- package/src/providers/m365.mjs +1 -1
- package/src/request-context.mjs +8 -0
- package/src/response-failures.mjs +34 -6
- package/src/responses-handler.mjs +5 -0
- package/src/stream-performance.mjs +10 -4
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. 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.
|
|
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
|
@@ -768,3 +768,59 @@ existing cancellation-aware single-flight for transport initialization: one
|
|
|
768
768
|
waiter cannot abort another, while the last cancellation or provider closure
|
|
769
769
|
stops the shared setup. Existing native stream validation, byte admission,
|
|
770
770
|
connection reuse, bounded metrics/logging and pinned source semantics remain.
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
## Request evidence and optional counting
|
|
774
|
+
|
|
775
|
+
The existing AsyncLocalStorage request context owns safe requested model and
|
|
776
|
+
client evidence before model resolution. Claude keeps the outer HTTP context,
|
|
777
|
+
while its generation metrics stay separate from count operations. Selected
|
|
778
|
+
source/model, logical upstream calls and fixed resolution reasons reach HTTP
|
|
779
|
+
diagnostics; no alternate route is chosen to improve a diagnostic result.
|
|
780
|
+
|
|
781
|
+
`providers/api-token-count.mjs` is owned by one immutable manual-API
|
|
782
|
+
configuration. It joins bounded identical count operations with independent
|
|
783
|
+
waiter cancellation and keeps only bounded, short-lived 404 observations.
|
|
784
|
+
It does not implement a general circuit breaker, protocol translation,
|
|
785
|
+
inference fallback or tokenizer. Counts have their own diagnostics category;
|
|
786
|
+
generation failure totals do not include this auxiliary capability.
|
|
787
|
+
|
|
788
|
+
Flow rendering caches geometry until observed element size, topology, model
|
|
789
|
+
labels or language change. Phase-only updates retain SVG path/circle nodes.
|
|
790
|
+
Hidden pages stop the two-second status timer and refresh on visibility return;
|
|
791
|
+
foreground freshness and the existing CSS motion remain unchanged. Catalog
|
|
792
|
+
failure backoff is source-revision scoped and never holds the configuration
|
|
793
|
+
transaction during network work. Existing body serialization ownership is
|
|
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
|
|
|
@@ -1693,11 +1693,14 @@ The protected `/_ccdx/ui/account` and `/_ccdx/ui/checks` APIs require loopback,
|
|
|
1693
1693
|
## HTTP error diagnostics
|
|
1694
1694
|
|
|
1695
1695
|
`http_errors.recent` keeps its 20-record rolling view. Independent
|
|
1696
|
-
`actionable_recent` (20
|
|
1697
|
-
|
|
1698
|
-
|
|
1696
|
+
`actionable_recent` (20 generation/other failures and actionable count errors),
|
|
1697
|
+
`capability_recent` (20 count/explicit-access notices), `route_recent` (eight path errors)
|
|
1698
|
+
and `protocol_recent` (eight image-MCP HTTP 405 records) prevent route/method noise from erasing inference
|
|
1699
|
+
evidence. `by_category` counts inference, capability, protocol, route and other HTTP failures;
|
|
1699
1700
|
classification does not discard errors, grant access or retry requests.
|
|
1700
|
-
The WebUI
|
|
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
|
+
|
|
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.
|
|
1701
1704
|
|
|
1702
1705
|
New records retain safe error code/type/parameter paths, method, an allowlisted
|
|
1703
1706
|
endpoint without a query, and upstream attempt count. Requested/served model
|
|
@@ -2046,3 +2049,105 @@ inference remains separate. Protected JSON/account/settings routes stay
|
|
|
2046
2049
|
`CCDX_SUPERVISED_SERVICE` is an internal inherited worker marker. It is used only
|
|
2047
2050
|
with a private parent IPC channel; do not set it as a user preference. It grants
|
|
2048
2051
|
no network action and is not a replacement for the saved nightly-update opt-in.
|
|
2052
|
+
|
|
2053
|
+
|
|
2054
|
+
### Manual API token counting
|
|
2055
|
+
|
|
2056
|
+
Messages support does not establish support for `POST /v1/messages/count_tokens`.
|
|
2057
|
+
CCDX forwards the configured Messages endpoint plus `/count_tokens`. A manual
|
|
2058
|
+
API's observed HTTP 404 is remembered in memory for 60 seconds, separately for
|
|
2059
|
+
each model and Anthropic version/beta-header scope. This is an observed endpoint
|
|
2060
|
+
failure, not a declaration that the model source is down. Cached and initial
|
|
2061
|
+
results return HTTP 404 with `ccdx_api_count_tokens_unavailable`; no estimated
|
|
2062
|
+
or synthetic count is returned. Changing the source configuration/key creates
|
|
2063
|
+
a new scope. Other statuses, including 401/403/405/429/5xx, are not cached by
|
|
2064
|
+
this compatibility mechanism; status and safe Retry-After metadata survive.
|
|
2065
|
+
|
|
2066
|
+
Identical concurrent count requests share one bounded upstream operation.
|
|
2067
|
+
Each caller cancels independently; the last cancelled waiter aborts shared
|
|
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
|
|
2078
|
+
after the operation. Counts neither invoke generation nor fail over to another
|
|
2079
|
+
source. This does not supply a missing tokenizer or guarantee every Claude App
|
|
2080
|
+
context-management feature on a third-party model.
|
|
2081
|
+
|
|
2082
|
+
Background manual-API catalog failures back off for 1, 5, 30 and then 120
|
|
2083
|
+
minutes; successful publication resets the sequence. Explicit refresh retains
|
|
2084
|
+
the existing one-minute minimum interval rather than the longer background
|
|
2085
|
+
backoff. A valid upstream Retry-After also applies, bounded to 24 hours. These
|
|
2086
|
+
are read eligibility gates, not added background retry timers. Revision changes
|
|
2087
|
+
invalidate prior eligibility and obsolete results never publish.
|
|
2088
|
+
|
|
2089
|
+
Claude Code's validated `x-claude-code-agent-id` separates a child task's local
|
|
2090
|
+
source guard from its parent's guard when a session is identified. Parent keys
|
|
2091
|
+
without that header remain unchanged. This header is correlation only: model
|
|
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
|
@@ -420,16 +420,18 @@ export function createAdapterHandler(options = {}) {
|
|
|
420
420
|
if (requestFinished) return;
|
|
421
421
|
requestFinished = true;
|
|
422
422
|
if (trackRequest && statusCode >= 400) {
|
|
423
|
-
try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model,
|
|
423
|
+
try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model || context?.requestedModel,
|
|
424
424
|
method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
|
|
425
425
|
target: ["/v1/responses", "/v1/responses/compact", "/anthropic/v1/messages", "/anthropic/v1/messages/count_tokens", "/anthropic/v1/models", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
|
|
426
|
-
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.(),
|
|
426
|
+
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts,
|
|
427
427
|
attempt_timings: streamPerformance?.attemptTimings?.(),
|
|
428
|
-
requested_model: context?.requestedModel, provider: context?.provider,
|
|
428
|
+
requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
|
|
429
|
+
capability_cached: context?.countObservation?.cached, shared_upstream: context?.countObservation?.shared,
|
|
429
430
|
})); } catch {}
|
|
430
431
|
}
|
|
431
432
|
try { complete({ statusCode, aborted }); } catch {}
|
|
432
|
-
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 {}
|
|
433
435
|
try { finishTerminalActivity(); } catch {}
|
|
434
436
|
try { context?.finishProvider?.(); } catch {}
|
|
435
437
|
};
|
|
@@ -466,13 +468,14 @@ export function createAdapterHandler(options = {}) {
|
|
|
466
468
|
showRequestId: options.showRequestId === true,
|
|
467
469
|
includeHttpErrorDetails: options.includeHttpErrorDetails === true || process.env.CCDX_HTTP_ERROR_DETAILS === "1",
|
|
468
470
|
streamPerformance,
|
|
471
|
+
upstreamAttempts: 0,
|
|
469
472
|
provider: undefined,
|
|
470
473
|
finishProvider: undefined,
|
|
471
474
|
historyNamespace: undefined,
|
|
472
475
|
historyTransferNamespace: undefined,
|
|
473
476
|
onHistoryStored: undefined,
|
|
474
477
|
clientHeaders: undefined,
|
|
475
|
-
onHttpError: evidence => { httpEvidence = evidence; },
|
|
478
|
+
onHttpError: evidence => { httpEvidence = { ...httpEvidence, ...evidence }; },
|
|
476
479
|
};
|
|
477
480
|
const result = runWithRequestContext(context, () => dispatchRequest(req, res, pathname));
|
|
478
481
|
if (result && typeof result.then === "function") {
|
|
@@ -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) {
|
|
@@ -21,13 +21,14 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
|
|
|
21
21
|
if (old?.revision === version && !old.controller.signal.aborted) return old.promise;
|
|
22
22
|
if (old) cancel(id);
|
|
23
23
|
const cached = reads.get(id), age = cached ? now() - cached.at : Infinity;
|
|
24
|
-
|
|
24
|
+
const retryDelay = cached?.error ? [60000, 5 * 60000, 30 * 60000, 2 * 60 * 60000][Math.min((cached.failures || 1) - 1, 3)] : 0;
|
|
25
|
+
if (cached?.revision === version && age >= 0 && age < Math.max(cached.retryAfterMs || 0, force ? 60000 : cached.error ? retryDelay : 30 * 60000)) {
|
|
25
26
|
if (cached.error) throw cached.error;
|
|
26
27
|
await commit(id, cached.models, version, new Date(cached.at).toISOString(), () => current(id, version));
|
|
27
28
|
onState(id, { state: "ready", checked_at: new Date(cached.at).toISOString() });return cached.models;
|
|
28
29
|
}
|
|
29
30
|
const savedAge = now() - Date.parse(selected.checked_at);
|
|
30
|
-
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;
|
|
31
32
|
const flight = { revision: version, controller: new AbortController() };
|
|
32
33
|
flights.set(id, flight);
|
|
33
34
|
const active = () => current(id, version) && flights.get(id) === flight && !flight.controller.signal.aborted;
|
|
@@ -48,7 +49,9 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
|
|
|
48
49
|
const code = /^ccdx_[a-z0-9_]+$/.test(error.code || "") ? error.code : "ccdx_api_catalog_unavailable";
|
|
49
50
|
const failure = accessError(code, [401, 403, 409].includes(error.statusCode) ? error.statusCode : 502);
|
|
50
51
|
if (active()) {
|
|
51
|
-
reads.set(id, { revision: version, at: now(), error: failure
|
|
52
|
+
reads.set(id, { revision: version, at: now(), error: failure,
|
|
53
|
+
retryAfterMs: Number.isFinite(error.retryAfterMs) ? Math.max(0, Math.min(error.retryAfterMs, 86400000)) : 0,
|
|
54
|
+
failures: cached?.revision === version ? Math.min((cached.failures || 0) + 1, 4) : 1 });
|
|
52
55
|
onState(id, { state: "stale", code, checked_at: new Date(now()).toISOString() });
|
|
53
56
|
}
|
|
54
57
|
throw failure;
|
|
@@ -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
|
@@ -7,8 +7,9 @@ import { createRequestAdmission } from "./request-admission.mjs";
|
|
|
7
7
|
import { loadRuntimeConfig } from "./runtime-config.mjs";
|
|
8
8
|
import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
|
|
9
9
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
10
|
-
import { runWithRequestContext, currentRequestContext } from "./request-context.mjs";
|
|
11
|
-
import {
|
|
10
|
+
import { runWithRequestContext, currentRequestContext, observeRequestedModel } from "./request-context.mjs";
|
|
11
|
+
import { upstreamErrorEvidence, requestOptionsEvidence } from "./response-failures.mjs";
|
|
12
|
+
import { createStreamPerformanceMetrics, isMessagesOutputDelta, markRequestObservation } from "./stream-performance.mjs";
|
|
12
13
|
import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
|
|
13
14
|
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
14
15
|
import { decodedBodyLimitPreference } from "./user-settings.mjs";
|
|
@@ -17,6 +18,8 @@ import { requestApplication } from "./request-application.mjs";
|
|
|
17
18
|
|
|
18
19
|
function send(res, code, value) {
|
|
19
20
|
if (res.destroyed || res.writableEnded) return;
|
|
21
|
+
const context = currentRequestContext();
|
|
22
|
+
if (code >= 400) context?.onHttpError?.({ code: value?.error?.code, origin: context.errorOrigin || "client_validation" });
|
|
20
23
|
res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
|
|
21
24
|
}
|
|
22
25
|
const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
|
|
@@ -113,17 +116,22 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
113
116
|
const parent = currentRequestContext();
|
|
114
117
|
if (parent) parent.provider = provider.id;
|
|
115
118
|
const countTokens = pathname.endsWith("/count_tokens"), requestId = parent?.requestId || randomUUID();
|
|
116
|
-
const tracker = countTokens ?
|
|
119
|
+
const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
|
|
117
120
|
if (!resolveRequest) tracker?.setProvider(provider.id);
|
|
118
121
|
const abort = createRequestAbort(req, res);
|
|
119
122
|
let release = () => {}, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
|
|
120
|
-
let terminalOrigin = "client_validation", failureStatus = null;
|
|
123
|
+
let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
|
|
121
124
|
if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
|
|
122
|
-
|
|
125
|
+
const context = parent || { requestId };
|
|
126
|
+
context.provider = selectedProvider.id;context.application = requestApplication(req.headers, "claude");
|
|
127
|
+
context.streamPerformance = tracker;context.route = countTokens ? "messages_count_tokens" : "messages";
|
|
128
|
+
await runWithRequestContext(context, async () => {
|
|
123
129
|
try {
|
|
124
130
|
release = await acquireRequest(req, { signal: abort.signal });
|
|
125
131
|
abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
|
|
126
132
|
let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
|
|
133
|
+
observeRequestedModel(body);
|
|
134
|
+
context.requestOptions = requestOptionsEvidence(body);
|
|
127
135
|
if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
|
|
128
136
|
send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
|
|
129
137
|
}
|
|
@@ -140,11 +148,21 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
140
148
|
if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
|
|
141
149
|
if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
|
|
142
150
|
stats.last_model = model;
|
|
151
|
+
context.model = configuredModel || model;
|
|
152
|
+
if (!countTokens) markRequestObservation({ max_output_tokens_requested: body.max_tokens });
|
|
143
153
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
|
|
144
154
|
validateConversation?.(body, req.headers, selectedProvider);
|
|
145
155
|
terminalOrigin = "transport";
|
|
146
156
|
const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
|
|
147
|
-
|
|
157
|
+
onCountObservation(value) {
|
|
158
|
+
context.countObservation = { ...context.countObservation, ...value };
|
|
159
|
+
if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
|
|
160
|
+
},
|
|
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
|
+
} });
|
|
148
166
|
body = null;
|
|
149
167
|
terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
|
|
150
168
|
tracker?.upstreamHeaders(upstream.status);
|
|
@@ -156,6 +174,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
156
174
|
const raw = await readBoundedResponseText(upstream, { maxBytes: upstream.ok ? config.maxUpstreamResponsesResponseBytes : MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
157
175
|
label: "Claude gateway response", signal: abort.signal });
|
|
158
176
|
let value;try { value = JSON.parse(raw); } catch {}
|
|
177
|
+
if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
|
|
178
|
+
origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
|
|
159
179
|
if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
|
|
160
180
|
model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
|
|
161
181
|
sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
|
|
@@ -191,14 +211,17 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
191
211
|
} finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
|
|
192
212
|
}
|
|
193
213
|
} catch (error) {
|
|
214
|
+
rejectionReason = error.jsonBody?.error?.reason || (error.code === "ccdx_client_source_disabled" ? error.code : undefined);
|
|
194
215
|
const detail = operationErrorDetails(error, { reason: abort.reason });
|
|
195
216
|
outcome = detail.source === "cancelled" ? "cancelled" : "failed";
|
|
196
217
|
const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
|
|
197
218
|
failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
|
|
219
|
+
context.errorOrigin = terminalOrigin;
|
|
198
220
|
const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
|
|
199
221
|
const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
|
|
200
222
|
log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
|
|
201
223
|
tracker?.setErrorOrigin(terminalOrigin);
|
|
224
|
+
context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(diagnostic ? { transport: diagnostic } : {}) });
|
|
202
225
|
if (outcome === "cancelled") return;
|
|
203
226
|
if (!res.headersSent) {
|
|
204
227
|
const value = apiError(error.code || abort.reason || "ccdx_gateway_error", message);
|
|
@@ -210,11 +233,13 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
210
233
|
release();abort.cleanup();finishProvider();
|
|
211
234
|
if (!countTokens) {
|
|
212
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 });
|
|
213
239
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
|
|
214
|
-
tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
|
|
215
|
-
tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode });
|
|
216
|
-
|
|
217
|
-
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 {}
|
|
218
243
|
}
|
|
219
244
|
}
|
|
220
245
|
});
|
package/src/cli-status.mjs
CHANGED
|
@@ -200,9 +200,9 @@ 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)}
|
|
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
|
-
lines.push(status("warn", `HTTP ${count(failure.http_status)} ${terminalCell(failure.model)} ${terminalCell(failure.code)}${failure.parameter ? ` param=${terminalCell(failure.parameter)}` : ""}; ${terminalCell(failure.origin)}; ${count(failure.upstream_attempts)} attempts`));
|
|
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
|
}
|
|
207
207
|
}
|
|
208
208
|
lines.push(status("info", `Models: ${count(models.models)} total; Copilot token ${copilot.token_cached ? `cached (${duration(copilot.token_expires_in_ms)} remaining)` : "not cached"}`));
|
|
@@ -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(); }
|