codex-copilot-dx 1.2.23 → 1.2.25

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 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.23/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.23/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).
14
+ No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.25/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.25/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 concurrent count requests share bounded upstream 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.
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
- 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.
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. Selecting no models pauses access; enable a source and select models to resume. 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.23 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.23.md) cover request attribution, bounded token-count compatibility and lower-cost flow rendering while retaining native GitHub sign-in/model protections.
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.25 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.25.md) cover paused-access recovery, installation-lock diagnostics, native memory-state labels, cancellable API preparation and isolated flow animation while retaining native GitHub sign-in/model protections.
60
60
 
61
61
  ## Microsoft 365 access
62
62
 
@@ -24,6 +24,15 @@ which owns grants, switches, versioned model-deployment bindings and lifecycle.
24
24
  validates strict versioned metadata and locked atomic writes; stale cross-process
25
25
  saves are rejected. Accepted inputs and public snapshots do not share mutable
26
26
  objects with the live graph. The built-in registry does not load external code.
27
+ One Codex access-mode calculation distinguishes disabled, paused (no selections),
28
+ native GitHub and gateway bindings. Sync and request authorization share that
29
+ calculation; paused access is rejected before credential checks without expanding
30
+ model visibility or changing sign-in.
31
+
32
+ Manual API setup uses abort-aware shared waits for credentials and transport.
33
+ A cancelled caller releases its wait independently; a late shared result cannot
34
+ resume its request. Messages keeps body upload, preparation and upstream budgets
35
+ separate using the existing request-abort boundary.
27
36
 
28
37
  `model-capabilities.mjs` owns neutral limits, reasoning/tool/input/search fields,
29
38
  strict manual values, per-field evidence and deployment revisions. It reads no
@@ -533,6 +542,8 @@ Byte-weighted request admission is not a simultaneous-stream limit. The 1.2.0 lo
533
542
  and no-Node bootstraps. It bounds downloads/decompression, verifies the exact
534
543
  release package and checksum, backs up only this package/commands under an
535
544
  exclusive lock, restores on failure and validates the version/sharp/broker.
545
+ The lock records its PID, timestamp and backup path; existing/legacy locks remain
546
+ explicit recovery barriers, while unrelated I/O failures keep their own cause.
536
547
  It reuses the selected npm's bundled downloader with named proxy/CA/TLS/offline settings and no retries; no new download dependency is added. No network installation runs on ordinary startup or inference paths. Opted-in supervisor startup copies/verifies its current immutable runtime; its separate night scheduler is described below. `package-update.mjs` keeps
537
548
  source choice, named npm-policy probes and fixed platform launch arguments;
538
549
  verified filenames enter cmd.exe, while paths enter cwd. Private-runtime commands
@@ -792,3 +803,35 @@ foreground freshness and the existing CSS motion remain unchanged. Catalog
792
803
  failure backoff is source-revision scoped and never holds the configuration
793
804
  transaction during network work. Existing body serialization ownership is
794
805
  retained: the ordinary manual Responses path serializes its final body once.
806
+
807
+
808
+ ## Display evidence and native memory dependency
809
+
810
+ Manual upstream identity declarations live in `api-model-display` cache owned
811
+ by the connection runtime, separate from strict connection v2 configuration and
812
+ capability values. `apiCatalog` no longer stamps Unknown as a maker. Public API
813
+ catalog projection decorates display data; native model IDs, auth, source/key
814
+ identity and capability constraints are unchanged. Catalog publication guards
815
+ also guard display evidence; failures cannot introduce an empty successful
816
+ catalog or extra upstream permissions.
817
+
818
+ The token counter separates unknown capability coordination from identical
819
+ result sharing. The first real admitted count owns the capability operation.
820
+ Different inputs may consume a 404 observation, but never another input's
821
+ successful count. Waiter cancellation is independent. Known support restores
822
+ normal parallel counts; state is bounded and source/configuration owned.
823
+
824
+ `codex-memory-model` owns optional extraction-role evidence. It reads explicit
825
+ native config and uses a separate bounded read-only SQLite helper only when
826
+ needed. It reports configuration, observation or uncertainty; it never selects
827
+ a model for Codex. WebUI owns the dependency notice/confirmation. The runtime
828
+ continues to reject requests outside selected deployments, including native
829
+ background jobs. Optional evidence is excluded from service handoff business
830
+ contracts and never modifies the client files.
831
+
832
+ Request observations retain scalar output budgets, usage and fixed stop/network
833
+ fields across protocol adapters. Generation, explicit access restrictions,
834
+ capability absence and protocol discovery remain distinct. Dashed flow motion
835
+ uses CSS stroke offset on retained paths; model nodes share the same left edge.
836
+ Geometry and SVG identity reuse from 1.2.23 remain in place, with hidden/stale/
837
+ reduced-motion behavior and summary tables preserved.
package/docs/REFERENCE.md CHANGED
@@ -92,6 +92,15 @@ starts. Its value is never returned by management or copied into client config.
92
92
  Private helpers omit unrelated credentials and Node hooks. API error bodies are
93
93
  replaced with stable codes; valid Retry-After metadata is retained.
94
94
 
95
+ An explicit empty Codex deployment array pauses CCDX access, including after a
96
+ restart or disabling the last selected source. Models, Responses and compact
97
+ requests return `503 ccdx_client_source_disabled` before checking a client key;
98
+ no upstream call, automatic model selection or login repair is attempted. Enable
99
+ the app/source and select at least one model to resume. GitHub-only selections
100
+ retain native OpenAI mode; nonempty mixed/API deployments retain private-key
101
+ authentication. With automatic sync enabled, pausing restores only owned Codex
102
+ configuration; manual sync leaves native files unchanged. Neither changes login.
103
+
95
104
  `client-gateway-keys.json` holds local credentials separately. Disabled sources leave normal source lists. **Model sources** owns **Disabled sources**; application access cards own **Disabled clients**. App navigation remains available while access is closed, so its restoration control stays reachable. Each
96
105
  collapsed list appears only when it has entries and provides **Enable again**.
97
106
  Closing a client stops CCDX access, not the app. Disabling an in-use source
@@ -1264,8 +1273,13 @@ Before npm changes a discovered global target, CCDX backs up only its package
1264
1273
  and two command entries and acquires an exclusive install lock. A linked target
1265
1274
  is preserved and refused. Installer or runtime-verification failure restores the
1266
1275
  old package/commands; successful installation removes the backup. A failed restore
1267
- reports the retained backup and lock for manual recovery. A lock left by a killed
1268
- installer requires checking that no installation is running before removing it.
1276
+ reports the retained backup and lock for manual recovery. New lock records include
1277
+ the installer PID, creation time and backup directory. Existing-lock errors name
1278
+ the exact file; other lock-creation failures retain their actual I/O error rather
1279
+ than claiming another install. Old empty locks remain owner-unknown. A lock left
1280
+ by a killed installer requires checking that no installation is running and
1281
+ inspecting its retained backup before recovery. Locks are not removed merely
1282
+ because they are old; an incomplete restore must be completed first.
1269
1283
  There is no promise of crash/power-loss atomicity. Other apps, credentials,
1270
1284
  settings, caches and the running service are not replaced. Readonly/busy Windows
1271
1285
  files can prevent installation; finish use of that installation and retry.
@@ -1302,7 +1316,7 @@ Unknown support prevents an explicitly requested exception from starting.
1302
1316
  For an older updater that still requires Git, install the Release tarball directly:
1303
1317
 
1304
1318
  ```sh
1305
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.23/codex-copilot-dx-1.2.23.tgz
1319
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.25/codex-copilot-dx-1.2.25.tgz
1306
1320
  # Windows PowerShell: use npm.cmd instead of npm.
1307
1321
  ```
1308
1322
 
@@ -1694,11 +1708,11 @@ The protected `/_ccdx/ui/account` and `/_ccdx/ui/checks` APIs require loopback,
1694
1708
 
1695
1709
  `http_errors.recent` keeps its 20-record rolling view. Independent
1696
1710
  `actionable_recent` (20 generation/other failures and actionable count errors),
1697
- `capability_recent` (20 token-count errors), `route_recent` (eight path errors)
1711
+ `capability_recent` (20 count/explicit-access notices), `route_recent` (eight path errors)
1698
1712
  and `protocol_recent` (eight image-MCP HTTP 405 records) prevent route/method noise from erasing inference
1699
1713
  evidence. `by_category` counts inference, capability, protocol, route and other HTTP failures;
1700
1714
  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.
1715
+ 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
1716
 
1703
1717
  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
1718
 
@@ -1749,7 +1763,7 @@ unset the variable after the investigation. Records disappear on service exit.
1749
1763
  | `CCDX_REQUEST_BODY_TIMEOUT_MS` | `120000` | Maximum time to receive and decode a request body before returning `408` |
1750
1764
  | `CCDX_MAX_UPSTREAM_BODY_BYTES` | `31457280` | Strict maximum forwarded Responses body size; larger payloads are adapted locally or rejected with `413` |
1751
1765
  | `CCDX_MAX_SSE_BUFFER_BYTES` | `8388608` | Maximum buffered bytes for one unterminated upstream SSE line or event |
1752
- | `CCDX_UPSTREAM_TIMEOUT_MS` | `120000` | Per-phase timeout for Responses preparation and non-streaming upstream requests |
1766
+ | `CCDX_UPSTREAM_TIMEOUT_MS` | `120000` | Per-phase timeout for Responses/Messages preparation and non-streaming upstream requests |
1753
1767
  | `CCDX_STREAM_HANDSHAKE_TIMEOUT_MS` | `120000` | Timeout while waiting for upstream streaming response headers |
1754
1768
  | `CCDX_STREAM_IDLE_TIMEOUT_MS` | `120000` | Maximum idle time between upstream streaming body chunks |
1755
1769
  | `CCDX_UPSTREAM_RETRIES` | `2` | Retries for safe requests and clearly pre-connect POST failures; capped at `5` |
@@ -1829,6 +1843,16 @@ Native Responses forwards Codex `agent_message` items unchanged. When a model re
1829
1843
 
1830
1844
  After the stream handshake succeeds, stream liveness uses the idle timeout rather than the expired handshake deadline. Eligible HTTP-200 failure recovery acquires a bounded preparation budget and history admission before rebuilding its payload, then releases those reservations when the retry opens upstream or fails. Normal streams still release preparation admission after their response headers arrive.
1831
1845
 
1846
+ Messages and token counting stop the body-upload timer after JSON is read, then
1847
+ use `CCDX_UPSTREAM_TIMEOUT_MS` for preparation. A preparation timeout returns
1848
+ `504 messages_prepare_timeout`; a slow body upload remains governed by its own
1849
+ body timeout. Upstream dispatch starts the existing handshake/non-streaming
1850
+ budget, and counting keeps its shared dispatch deadline across capability waits.
1851
+ Cancelling a manual API credential waiter returns promptly without cancelling
1852
+ other callers or forwarding after a late credential result. The shared OS secret
1853
+ read may finish under its existing ten-second bound. No new timeout setting or
1854
+ inference retry is added.
1855
+
1832
1856
  Downstream backpressure waits also observe cancellation and the stream deadline. A client that stops reading cannot retain the pending stream indefinitely after timeout; CCDX closes that connection without retrying its request. Final error-frame delivery has a separate one-second maximum drain wait.
1833
1857
 
1834
1858
  Successful streaming responses are accepted only when the upstream body is SSE and reaches its protocol terminal event. Unexpected EOF becomes a protocol-native stream error, and repeated blank tool-argument deltas are stopped per tool call. Allowlisted rate-limit, retry, model, trace, and upstream request-ID metadata are forwarded; cookies, authorization, body-length, and encoding headers are not.
@@ -2065,10 +2089,16 @@ this compatibility mechanism; status and safe Retry-After metadata survive.
2065
2089
 
2066
2090
  Identical concurrent count requests share one bounded upstream operation.
2067
2091
  Each caller cancels independently; the last cancelled waiter aborts shared
2068
- work. Joining is limited to bodies up to 1 MiB, 16 shared operations and 4 MiB
2069
- of shared request text. Larger/overflow requests use their normal admitted
2070
- path. Count responses are capped at 64 KiB. At most 128 recent unavailable
2071
- scopes are retained. Successful results and request bodies are not retained
2092
+ work. Before a model/header scope has a capability observation, distinct inputs
2093
+ wait for its first real admitted count request. An observed 404 is reused by
2094
+ those waiters; success is reused only for identical inputs. Distinct inputs
2095
+ then run their own counts. Capability waiting has at most 16 in-flight scopes
2096
+ and remains under normal gateway body/queue admission. Capability waiting and
2097
+ the caller's own count share its existing upstream timeout budget. Identical-result sharing
2098
+ is limited to bodies up to 1 MiB, 16 operations and 4 MiB of shared request text.
2099
+ 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
2100
+ minute; a positive observation permits normal concurrency and a later 404 can
2101
+ replace it. Successful results and request bodies are not retained
2072
2102
  after the operation. Counts neither invoke generation nor fail over to another
2073
2103
  source. This does not supply a missing tokenizer or guarantee every Claude App
2074
2104
  context-management feature on a third-party model.
@@ -2084,3 +2114,68 @@ Claude Code's validated `x-claude-code-agent-id` separates a child task's local
2084
2114
  source guard from its parent's guard when a session is identified. Parent keys
2085
2115
  without that header remain unchanged. This header is correlation only: model
2086
2116
  access and the company's account/history checks remain authoritative.
2117
+
2118
+
2119
+ ### Upstream maker metadata
2120
+
2121
+ Manual API discovery accepts bounded text from publisher, vendor and owned_by.
2122
+ The model maker shown in lists/details prefers publisher, then vendor; owned_by
2123
+ is shown separately as ownership and is not treated as the maker. Absent maker
2124
+ information is Not provided; no name-based inference is performed. These are
2125
+ upstream declarations, not proof of backend identity.
2126
+
2127
+ Rebuildable per-source files under `api-model-display/` beside settings are
2128
+ scoped by source ID and deployment revision. They preserve at most 500 models,
2129
+ 512 KiB per file and 16 in-memory sources. They contain only model IDs and
2130
+ identity declarations, no key or response body. Old versions ignore them;
2131
+ connection v2 metadata remains readable during rollback. The new read-only
2132
+ `model_display` source field and per-discovery `display` field are ignored if
2133
+ round-tripped into Save API; unknown configuration fields still fail validation. Missing display
2134
+ evidence triggers the existing normal catalog read rather than requiring key
2135
+ entry or model reselection. Failed discovery retains valid prior evidence for
2136
+ the same revision; invalid optional display cache does not block inference.
2137
+
2138
+ ### Memory-extraction dependency notices
2139
+
2140
+ The Codex model editor reads [`memories.extract_model`](https://learn.chatgpt.com/docs/customization/memories#configure-local-memories) when explicitly configured
2141
+ in the native Codex config. Otherwise, it may show a recently observed extraction
2142
+ model from a bounded read-only correlation of native Phase 1 task failures and
2143
+ one unambiguous local HTTP 400 model. No prompt, memory text or model-name
2144
+ heuristic is used. Explicit configuration is labelled Configured in Codex;
2145
+ observations are Recently observed. The current client does not expose its
2146
+ compiled default in the queried interface, so CCDX does not label a guessed
2147
+ model as Codex default. With memory generation explicitly enabled but no model
2148
+ evidence, the editor shows Chosen by Codex and Default model ID not available;
2149
+ this does not infer a model from the checked model list or claim a successful
2150
+ memory write. With generation explicitly disabled it shows Memory generation is
2151
+ off. Unknown generation state and no model evidence remain Not detected.
2152
+
2153
+ The optional native log helper runs only on startup/connection-view reads (including an explicit WebUI refresh),
2154
+ coalesced and at least one minute apart, with a 2.5-second limit. It reads up to
2155
+ eight task records and sixteen candidate HTTP records each, clipped to 8 KiB,
2156
+ from the prior 24 hours. It uses the bundled Node SQLite API in a separate
2157
+ read-only process; missing/locked/unsupported stores remain optional. Only a
2158
+ model ID and observation time can enter `codex-memory-observed.json`, scoped by
2159
+ the Codex profile, with a 24-hour freshness bound. No periodic log scanner,
2160
+ account lookup, native Codex process or inference is started by this helper.
2161
+
2162
+ Closing a known extraction model or its source in WebUI prompts about new-memory
2163
+ generation and preserves your explicit decision. The draft is separate from the
2164
+ saved selection. Existing memories are not deleted. Native memory generation
2165
+ settings, model aliases, defaults, authentication and authorization are not
2166
+ changed to satisfy a dependency. Confirmations are WebUI guidance, not a new
2167
+ requirement on existing CLI/API operations. A notice does not identify every
2168
+ background task or prove that memory generation succeeded.
2169
+
2170
+ ### Messages stop and network evidence
2171
+
2172
+ Recent Messages records retain declared context size, requested and forwarded
2173
+ output budgets, normalized returned input/output usage, and an allowlisted stop
2174
+ reason when supplied. Missing values remain unknown. `max_tokens` is shown as
2175
+ output-limit termination; CCDX does not raise an undeclared GLM output limit or
2176
+ use context length as an output ceiling. HTTP success and complete generation
2177
+ remain distinct.
2178
+
2179
+ API transport errors retain fixed safe code, DNS/connect/TLS/request/response
2180
+ phase and reused-socket state in HTTP diagnostics. They do not retain raw
2181
+ exceptions or URLs, and do not trigger automatic POST or cross-source retries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.23",
3
+ "version": "1.2.25",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -13,7 +13,7 @@ export const CLIENT_NAMES = Object.freeze({ codex: "Codex App", claude_app: "Cla
13
13
  const APIS = ["messages", "responses", "chat"];
14
14
  const messages = {
15
15
  ccdx_codex_catalog_cache_unavailable: "Codex model cache could not be refreshed safely. Close Codex App and try again; existing files were kept.",
16
- ccdx_client_source_disabled: "This client's CCDX access or selected source is disabled. Review Settings.",
16
+ ccdx_client_source_disabled: "CCDX access is paused. Enable the app and source, then select a model in the WebUI.",
17
17
  ccdx_client_credential_required: "The client's local CCDX credential is missing or outdated. Reopen the client after setup.",
18
18
  ccdx_conversation_source_changed: "This conversation was observed on another source or key. Start a new conversation.",
19
19
  ccdx_conversation_state_invalid: "Conversation source records are unreadable. The existing file was preserved.",
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 }); } catch {}
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
+ }
@@ -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");
@@ -130,7 +130,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
130
130
  release = await acquireRequest(req, { signal: abort.signal });
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
+ abort.setTimeout(config.upstreamTimeoutMs, "messages_prepare_timeout");
133
134
  observeRequestedModel(body);
135
+ context.requestOptions = requestOptionsEvidence(body);
134
136
  if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
135
137
  send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
136
138
  }
@@ -148,6 +150,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
148
150
  if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
149
151
  stats.last_model = model;
150
152
  context.model = configuredModel || model;
153
+ if (!countTokens) markRequestObservation({ max_output_tokens_requested: body.max_tokens });
151
154
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
152
155
  validateConversation?.(body, req.headers, selectedProvider);
153
156
  terminalOrigin = "transport";
@@ -156,7 +159,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
156
159
  context.countObservation = { ...context.countObservation, ...value };
157
160
  if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
158
161
  },
159
- onUpstreamStart() { abort.setTimeout(streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs, "upstream_timeout"); } });
162
+ onUpstreamStart() {
163
+ if (abort.signal.aborted) throw abort.signal.reason;
164
+ const timeout = streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs;
165
+ if (countTokens) countDeadline ??= Date.now() + timeout;
166
+ abort.setTimeout(countTokens ? Math.max(1, countDeadline - Date.now()) : timeout, "upstream_timeout");
167
+ } });
160
168
  body = null;
161
169
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
162
170
  tracker?.upstreamHeaders(upstream.status);
@@ -205,6 +213,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
205
213
  } finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
206
214
  }
207
215
  } catch (error) {
216
+ rejectionReason = error.jsonBody?.error?.reason || (error.code === "ccdx_client_source_disabled" ? error.code : undefined);
208
217
  const detail = operationErrorDetails(error, { reason: abort.reason });
209
218
  outcome = detail.source === "cancelled" ? "cancelled" : "failed";
210
219
  const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
@@ -214,10 +223,10 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
214
223
  const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
215
224
  log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
216
225
  tracker?.setErrorOrigin(terminalOrigin);
217
- context.onHttpError?.({ code: detail.code, origin: terminalOrigin });
226
+ context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(diagnostic ? { transport: diagnostic } : {}) });
218
227
  if (outcome === "cancelled") return;
219
228
  if (!res.headersSent) {
220
- const value = apiError(error.code || abort.reason || "ccdx_gateway_error", message);
229
+ const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
221
230
  if (diagnostic) value.error.diagnostic = diagnostic;
222
231
  send(res, statusCode, value);
223
232
  }
@@ -226,11 +235,13 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
226
235
  release();abort.cleanup();finishProvider();
227
236
  if (!countTokens) {
228
237
  stats.active--;stats[outcome]++;
238
+ const usageRecord = buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json",
239
+ client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude", provider: selectedProvider.id });
240
+ markRequestObservation({ input_tokens: usageRecord?.usage?.input_tokens, output_tokens: usageRecord?.usage?.output_tokens });
229
241
  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
- const client = req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude";
233
- try { void Promise.resolve(record(buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json", client, provider: selectedProvider.id }))).catch(() => {}); } catch {}
242
+ tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, stopReason, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
243
+ tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode, rejectionReason });
244
+ try { void Promise.resolve(record(usageRecord)).catch(() => {}); } catch {}
234
245
  }
235
246
  }
236
247
  });
@@ -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)} token counts, ${count(categories.protocol)} unsupported MCP methods, ${count(categories.route)} unmatched routes, ${count(categories.other)} other`));
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(); }