codex-copilot-dx 0.9.38 → 0.9.39
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 +6 -6
- package/bin/cli.mjs +11 -1
- package/docs/ARCHITECTURE.md +19 -0
- package/docs/REFERENCE.md +54 -0
- package/package.json +1 -1
- package/src/auth-credentials.mjs +27 -10
- package/src/auth-sources.mjs +42 -0
- package/src/auth.mjs +42 -11
- package/src/cli-options.mjs +6 -2
- package/src/client-integration.mjs +2 -4
- package/src/codex-config-doctor.mjs +26 -0
- package/src/dashboard/index.html +1 -1
- package/src/dashboard/refresh.js +7 -3
- package/src/dashboard/ui.js +18 -2
- package/src/doctor-compat.mjs +160 -0
- package/src/doctor-repair.mjs +47 -0
- package/src/doctor.mjs +58 -148
- package/src/lock.mjs +11 -1
- package/src/native-prediction.mjs +1 -1
- package/src/package-update.mjs +8 -0
- package/src/prediction-retirement.mjs +5 -1
- package/src/startup-ui.mjs +7 -11
- package/src/windows-command.mjs +77 -0
package/README.md
CHANGED
|
@@ -18,11 +18,11 @@ ccdx
|
|
|
18
18
|
CCDX reuses a compatible local credential or starts GitHub Device Flow, listens
|
|
19
19
|
on `127.0.0.1:2026`, configures Codex, and opens the App. No client binary patch
|
|
20
20
|
is needed. On Windows, open the App manually unless native prediction setup is
|
|
21
|
-
enabled.
|
|
21
|
+
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`. No install script, alias or policy change is added; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
|
|
22
22
|
|
|
23
23
|
Open [the local dashboard](http://127.0.0.1:2026/) for status, model discovery,
|
|
24
24
|
usage, cache/limits, recent failures, request context and animation settings.
|
|
25
|
-
Auto refresh runs every 30 minutes while visible and can be switched off. Hidden pages pause; opening sections and manual refresh still work. Startup uses
|
|
25
|
+
Auto refresh runs every 30 minutes while visible and can be switched off. Hidden pages pause; opening sections and manual refresh still work. The atom rotates once on page load and manual refresh, respecting reduced motion. Startup uses a compact six-line atom and aligned checks; `Ready` refers to the core service. Narrow/non-color terminals use a plain title.
|
|
26
26
|
|
|
27
27
|
## Commands
|
|
28
28
|
|
|
@@ -32,6 +32,8 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
|
|
|
32
32
|
| `ccdx start` | Start or reuse the adapter and open Codex when auto-launch is enabled |
|
|
33
33
|
| `ccdx status` | Runtime, limits and bounded request diagnostics |
|
|
34
34
|
| `ccdx doctor` | Configuration, adapter and read-only App/catalog diagnostics |
|
|
35
|
+
| `ccdx doctor --fix` | Repair owned launchers/config, recover existing auth and enabled prediction routing once |
|
|
36
|
+
| `ccdx doctor --json` | Redacted structured diagnostics; combines with `--fix` |
|
|
35
37
|
| `ccdx doctor config` | Read-only configuration check |
|
|
36
38
|
| `ccdx doctor --compat` | Online inference/continuation compatibility probes |
|
|
37
39
|
| `ccdx auth status` | Saved account; add `--online` to verify access |
|
|
@@ -64,10 +66,8 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
|
|
|
64
66
|
break continuations. Generated images and Codex transcripts are not deleted.
|
|
65
67
|
- Optional image setup/maintenance never blocks the primary service. Disabled
|
|
66
68
|
users get no CCDX image skill or MCP installation.
|
|
67
|
-
-
|
|
68
|
-
|
|
69
|
-
settings. The optional image MCP remains unchanged. Modified old registrations
|
|
70
|
-
can use inert compatibility entrypoints; they no longer generate suggestions.
|
|
69
|
+
- Missing-token discovery includes legacy OpenCode Copilot OAuth and GitHub CLI. Reads are bounded and account-matched; incomplete/network-failed discovery does not start another login. Other apps' credentials stay read-only.
|
|
70
|
+
- `doctor --fix` does not start login, enable optional features, change company policy or force-restart Apps. It backs up changed config; missing-token repair can contact GitHub. Partial repairs exit 1. See the reference for exact scope.
|
|
71
71
|
- Native predictions are a separate, opt-in compatibility feature. Quit Codex,
|
|
72
72
|
run `ccdx prediction on`, then restart CCDX. This adds App-profile certificate
|
|
73
73
|
trust and an App-only route for `chatgpt.com` and `ab.chatgpt.com`; HTTPS on those
|
package/bin/cli.mjs
CHANGED
|
@@ -344,9 +344,11 @@ if (CLI.command === "doctor") {
|
|
|
344
344
|
host: ADAPTER_HOST,
|
|
345
345
|
online: CLI.online,
|
|
346
346
|
compat: CLI.compat,
|
|
347
|
+
fix: CLI.fix,
|
|
348
|
+
json: CLI.json,
|
|
347
349
|
});
|
|
348
350
|
await LOGGING.cleanup();
|
|
349
|
-
process.exit(checks.some((check) => check.kind === "err") ? 1 : 0);
|
|
351
|
+
process.exit(checks.some((check) => check.kind === "err" || (CLI.fix && check.result && check.kind === "warn")) ? 1 : 0);
|
|
350
352
|
}
|
|
351
353
|
|
|
352
354
|
console.log(`\n${startupBanner({ commandName: CLI_NAME, version: LOCAL_VERSION })}\n`);
|
|
@@ -364,6 +366,14 @@ async function printUpdateNotice() {
|
|
|
364
366
|
|
|
365
367
|
try {
|
|
366
368
|
assertSafeAdapterHost(ADAPTER_HOST, process.env);
|
|
369
|
+
if (process.platform === "win32") {
|
|
370
|
+
try {
|
|
371
|
+
const { inspectWindowsCommand } = await import("../src/windows-command.mjs");
|
|
372
|
+
const command = inspectWindowsCommand({ repair: true });
|
|
373
|
+
if (command.changed) console.log(startupCheck("ok", "Command", "Windows command entry updated; use ccdx next time"));
|
|
374
|
+
else if (command.status === "preserved") console.warn(startupCheck("warn", "Command", "Existing launcher preserved; use ccdx.cmd doctor to inspect it"));
|
|
375
|
+
} catch { console.warn(startupCheck("warn", "Command", "Optional command setup skipped; core startup will continue")); }
|
|
376
|
+
}
|
|
367
377
|
const updateNotice = runInBackground(printUpdateNotice);
|
|
368
378
|
if (await reuseRunningAdapterIfAvailable()) {
|
|
369
379
|
// Ready is already displayed; finish the bounded check before this short-lived CLI exits.
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -50,6 +50,25 @@ Authentication keeps its public facade in `auth.mjs`. Device-code polling and
|
|
|
50
50
|
cancellation live in `auth-device-flow.mjs`; local discovery and transactional
|
|
51
51
|
credential storage live in `auth-credentials.mjs`. These modules do not depend
|
|
52
52
|
on the CLI, dashboard or service composition root.
|
|
53
|
+
`auth-sources.mjs` isolates known external credential contracts: legacy OpenCode
|
|
54
|
+
Copilot OAuth and noninteractive GitHub CLI token retrieval. Provider-specific
|
|
55
|
+
readers do not validate or write credentials. The auth facade enforces bounded
|
|
56
|
+
GitHub/Copilot validation, account matching and ambiguity handling. Saved-token
|
|
57
|
+
startup does not scan sources or make new validation calls.
|
|
58
|
+
|
|
59
|
+
`windows-command.mjs` owns exact npm-generated CCDX PowerShell launcher cleanup.
|
|
60
|
+
Best-effort Windows startup, the verified updater target and explicit doctor
|
|
61
|
+
repair share it. No install-time lifecycle script is added. It never edits
|
|
62
|
+
profiles, aliases, execution policy or npm's own shim.
|
|
63
|
+
Custom launchers and unverifiable installations are preserved.
|
|
64
|
+
|
|
65
|
+
Doctor composition stays in `doctor.mjs`; inference probes live in
|
|
66
|
+
`doctor-compat.mjs` and explicit bounded repairs in `doctor-repair.mjs`.
|
|
67
|
+
Repairs reuse the startup config transformation and prediction management API;
|
|
68
|
+
they do not start another adapter or implement a second prediction lifecycle.
|
|
69
|
+
Configuration repair takes the existing lock and commits the previous-file
|
|
70
|
+
backup transactionally. Disabled optional features stay disabled. JSON reports
|
|
71
|
+
separate before checks from final repair evidence; HTTP 200 alone is not success.
|
|
53
72
|
|
|
54
73
|
Native prediction has a separate loopback transport and an isolated HTTPS agent.
|
|
55
74
|
Only its two selected hosts use the App-specific route. Non-configuration requests
|
package/docs/REFERENCE.md
CHANGED
|
@@ -728,6 +728,45 @@ If a configured npm mirror has not synchronized the current release yet, use the
|
|
|
728
728
|
|
|
729
729
|
## Diagnostics
|
|
730
730
|
|
|
731
|
+
`ccdx doctor` is read-only by default and makes no inference request. It checks
|
|
732
|
+
local credentials/configuration, Node/platform, installation target, Windows
|
|
733
|
+
command launchers, enabled optional feature settings and the running adapter.
|
|
734
|
+
Disabled image/prediction features do not trigger provider or routing setup.
|
|
735
|
+
`--online` checks GitHub/Copilot access and a nonempty model directory; `--compat`
|
|
736
|
+
explicitly consumes model usage and requires completed Responses/SSE, not just
|
|
737
|
+
HTTP 200. Probe bodies are bounded to 4 MiB.
|
|
738
|
+
|
|
739
|
+
`ccdx doctor --fix` makes one repair attempt per supported area and verifies its
|
|
740
|
+
result: exact owned Windows command shims, startup-managed Codex settings, a
|
|
741
|
+
verified existing GitHub credential when none is saved, and the already-enabled
|
|
742
|
+
prediction bridge through its existing management API. Credential recovery can
|
|
743
|
+
contact GitHub without `--online`, but never starts Device Flow. Existing tokens,
|
|
744
|
+
user-modified/invalid configuration, unrelated MCPs/hooks and company routing or
|
|
745
|
+
security policy are not replaced. Existing changed config is transactionally
|
|
746
|
+
backed up to `config.toml.ccdx-doctor.bak` (the latest repair backup only). Repairs
|
|
747
|
+
do not install optional image tools, enable prediction, renew certificates or
|
|
748
|
+
force-restart Apps. A required normal App/service restart remains an explicit
|
|
749
|
+
partial result. Partial repairs exit 1; no automatic retry loop is added.
|
|
750
|
+
|
|
751
|
+
`ccdx doctor --json` emits one redacted JSON report; combine with `--fix` to
|
|
752
|
+
include `before_checks` and final per-operation repair results. Inspect these
|
|
753
|
+
results rather than equating a configured bridge with a visible gray suggestion.
|
|
754
|
+
|
|
755
|
+
Windows adds no install-time lifecycle script, so npm 12's script-approval policy
|
|
756
|
+
is not expanded. In restricted PowerShell, install with `npm.cmd`, then first run
|
|
757
|
+
`ccdx.cmd` or `ccdx.cmd doctor --fix`. Startup recognizes only the exact npm
|
|
758
|
+
PowerShell shims for the two CCDX commands, checks their matching `.cmd` targets
|
|
759
|
+
and package identity, then removes those `.ps1` shims. Subsequent calls can use
|
|
760
|
+
bare `ccdx` without changing policy or profiles. The updater applies the same
|
|
761
|
+
check only after verifying its installed target/version. Customized, symlinked,
|
|
762
|
+
unexpected or unreadable shims are preserved; optional setup failures do not
|
|
763
|
+
block core startup or turn a verified update into failure. Direct npm reinstalls
|
|
764
|
+
can recreate the shims; a first `.cmd` invocation repairs them again. Read-only
|
|
765
|
+
commands such as version/help/status do not repair them. Aliases/functions and
|
|
766
|
+
another installation earlier in PATH can still override resolution. npm's own
|
|
767
|
+
`.ps1` shim is untouched, so `npm.cmd` may still be needed. macOS/Linux and source
|
|
768
|
+
checkouts are no-ops.
|
|
769
|
+
|
|
731
770
|
`ccdx status` and the dashboard show the sample count beside each timing. First
|
|
732
771
|
output is observed at the gateway from generated deltas, hidden-reasoning/tool
|
|
733
772
|
announcements or content snapshots; a runtime-only result is marked separately.
|
|
@@ -873,6 +912,21 @@ scan are retained. Rows render when opened, without another API call.
|
|
|
873
912
|
|
|
874
913
|
When the saved token is missing, `ccdx` looks for compatible local Copilot GitHub tokens, validates them with GitHub and Copilot, and imports a valid one before starting Device Flow. It checks explicit token sources (`CCDX_GITHUB_TOKEN`, `CCDX_GITHUB_TOKEN_PATH`, and `CCDX_GITHUB_TOKEN_PATHS`) plus common local `auth.json` layouts. Generic discovery refuses to choose silently when valid credentials for multiple GitHub accounts are found.
|
|
875
914
|
|
|
915
|
+
Discovery also reads legacy OpenCode's `$XDG_DATA_HOME/opencode/auth.json`
|
|
916
|
+
(otherwise `~/.local/share/opencode/auth.json`), specifically `github-copilot`
|
|
917
|
+
OAuth `refresh`, and an installed GitHub CLI's noninteractive
|
|
918
|
+
`gh auth token --hostname github.com`. It does not import unrelated API keys,
|
|
919
|
+
enterprise-host OAuth, browser cookies, subscription credentials or a newer
|
|
920
|
+
OpenCode database format. `APPDATA` and `LOCALAPPDATA` auth.json roots are included
|
|
921
|
+
where present. GitHub CLI is optional, not a runtime dependency; its output/time
|
|
922
|
+
are bounded and no login prompt is started. Other apps' files remain read-only.
|
|
923
|
+
Source reads are bounded, discovery validates at most 24 distinct tokens within
|
|
924
|
+
a 12-second overall validation budget, and each candidate has a 4-second budget.
|
|
925
|
+
Directory/profile scans have explicit caps; hitting a cap or a network failure
|
|
926
|
+
reports incomplete discovery rather than silently selecting an account or
|
|
927
|
+
starting another login. Set an explicit source/account to resolve ambiguity.
|
|
928
|
+
An existing saved-token startup path performs no extra discovery/network calls.
|
|
929
|
+
|
|
876
930
|
After an account is selected, automatic `401`/`403` recovery and in-process token rotation accept only that same GitHub account. Concurrent callers share token refresh work without sharing cancellation, and a still-valid Copilot token may be used briefly after a transient refresh failure. Explicit token variables remain the intentional way to select another account.
|
|
877
931
|
|
|
878
932
|
If refresh still fails with `401` or `403`, the saved GitHub OAuth credential may be expired, revoked, or missing Copilot access. After stopping the adapter, remove that exact saved token and start again to rerun authentication recovery:
|
package/package.json
CHANGED
package/src/auth-credentials.mjs
CHANGED
|
@@ -4,9 +4,11 @@ import os from "node:os";
|
|
|
4
4
|
import { atomicWriteFilePairSync, atomicWriteFileSync } from "./atomic-file.mjs";
|
|
5
5
|
import { githubTokenFingerprint, normalizeGithubIdentity } from "./github-identity.mjs";
|
|
6
6
|
import { readBoundedFileSync, MAX_TOKEN_FILE_BYTES } from "./bounded-file.mjs";
|
|
7
|
+
import { additionalGithubSources, readAdditionalGithubSource } from "./auth-sources.mjs";
|
|
7
8
|
|
|
8
9
|
const DISABLE_TOKEN_DISCOVERY_VALUES = new Set(["1", "true", "yes"]);
|
|
9
10
|
const MAX_AUTH_JSON_BYTES = 1024 * 1024;
|
|
11
|
+
const pathKey = value => process.platform === "win32" ? path.resolve(value).toLowerCase() : path.resolve(value);
|
|
10
12
|
|
|
11
13
|
export function githubTokenPath(home = os.homedir()) {
|
|
12
14
|
return path.join(home, ".local", "share", "copilot-api", "github_token");
|
|
@@ -50,15 +52,17 @@ function localAuthRoots(home, env = process.env) {
|
|
|
50
52
|
const roots = [
|
|
51
53
|
path.join(home, "Library", "Application Support"),
|
|
52
54
|
env.APPDATA ? expandHome(env.APPDATA, home) : "",
|
|
55
|
+
env.LOCALAPPDATA ? expandHome(env.LOCALAPPDATA, home) : "",
|
|
53
56
|
env.XDG_CONFIG_HOME ? expandHome(env.XDG_CONFIG_HOME, home) : path.join(home, ".config"),
|
|
54
57
|
].filter(Boolean);
|
|
55
|
-
|
|
58
|
+
const seen = new Set();
|
|
59
|
+
return roots.filter(root => { const key = pathKey(root);if (seen.has(key)) return false;seen.add(key);return true; });
|
|
56
60
|
}
|
|
57
61
|
|
|
58
62
|
function addAuthJsonSource(sources, seen, filePath) {
|
|
59
|
-
if (seen.has(filePath)) return;
|
|
63
|
+
if (seen.has(pathKey(filePath))) return;
|
|
60
64
|
if (!fs.existsSync(filePath)) return;
|
|
61
|
-
seen.add(filePath);
|
|
65
|
+
seen.add(pathKey(filePath));
|
|
62
66
|
sources.push({ type: "auth-json", path: filePath });
|
|
63
67
|
}
|
|
64
68
|
|
|
@@ -74,7 +78,11 @@ function localAuthJsonSources(home, env = process.env) {
|
|
|
74
78
|
continue;
|
|
75
79
|
}
|
|
76
80
|
|
|
77
|
-
|
|
81
|
+
if (appDirs.length > 256) Object.defineProperty(sources, "incomplete", { value: true, configurable: true });
|
|
82
|
+
for (const appDirent of appDirs.slice(0, 256)) {
|
|
83
|
+
if (sources.length >= 128) {
|
|
84
|
+
Object.defineProperty(sources, "incomplete", { value: true, configurable: true });return sources;
|
|
85
|
+
}
|
|
78
86
|
if (!appDirent.isDirectory()) continue;
|
|
79
87
|
const appDir = path.join(root, appDirent.name);
|
|
80
88
|
addAuthJsonSource(sources, seen, path.join(appDir, "auth.json"));
|
|
@@ -87,7 +95,11 @@ function localAuthJsonSources(home, env = process.env) {
|
|
|
87
95
|
continue;
|
|
88
96
|
}
|
|
89
97
|
|
|
90
|
-
|
|
98
|
+
if (profileDirs.length > 64) Object.defineProperty(sources, "incomplete", { value: true, configurable: true });
|
|
99
|
+
for (const profileDirent of profileDirs.slice(0, 64)) {
|
|
100
|
+
if (sources.length >= 128) {
|
|
101
|
+
Object.defineProperty(sources, "incomplete", { value: true, configurable: true });return sources;
|
|
102
|
+
}
|
|
91
103
|
if (!profileDirent.isDirectory()) continue;
|
|
92
104
|
addAuthJsonSource(sources, seen, path.join(profilesDir, profileDirent.name, "auth.json"));
|
|
93
105
|
}
|
|
@@ -108,8 +120,8 @@ function explicitTokenFileSources(home, env = process.env) {
|
|
|
108
120
|
return paths
|
|
109
121
|
.map((filePath) => expandHome(filePath, home))
|
|
110
122
|
.filter((filePath) => {
|
|
111
|
-
if (seen.has(filePath)) return false;
|
|
112
|
-
seen.add(filePath);
|
|
123
|
+
if (seen.has(pathKey(filePath))) return false;
|
|
124
|
+
seen.add(pathKey(filePath));
|
|
113
125
|
return true;
|
|
114
126
|
})
|
|
115
127
|
.map((filePath) => ({
|
|
@@ -141,7 +153,10 @@ export function githubTokenSources({
|
|
|
141
153
|
sources.push({ type: "env", name: "CCDX_GITHUB_TOKEN", token: env.CCDX_GITHUB_TOKEN.trim() });
|
|
142
154
|
}
|
|
143
155
|
sources.push(...explicitTokenFileSources(home, env));
|
|
144
|
-
|
|
156
|
+
const local = localAuthJsonSources(home, env);
|
|
157
|
+
sources.push(...local);
|
|
158
|
+
sources.push(...additionalGithubSources(home, env));
|
|
159
|
+
if (local.incomplete) Object.defineProperty(sources, "incomplete", { value: true });
|
|
145
160
|
return sources;
|
|
146
161
|
}
|
|
147
162
|
|
|
@@ -150,6 +165,8 @@ export function sourceDescription(source) {
|
|
|
150
165
|
if (source.type === "env") return source.name;
|
|
151
166
|
if (source.type === "token-file") return `${source.name} (${source.path})`;
|
|
152
167
|
if (source.type === "auth-json") return `local auth file (${source.path})`;
|
|
168
|
+
if (source.type === "opencode-auth") return `OpenCode Copilot auth (${source.path})`;
|
|
169
|
+
if (source.type === "github-cli") return "GitHub CLI (github.com)";
|
|
153
170
|
return source.path || source.name || "unknown source";
|
|
154
171
|
}
|
|
155
172
|
|
|
@@ -167,7 +184,7 @@ export function extractGithubTokenFromAuthJson(json) {
|
|
|
167
184
|
return candidates.find((value) => typeof value === "string" && value.trim())?.trim() || "";
|
|
168
185
|
}
|
|
169
186
|
|
|
170
|
-
export function readGithubTokenSource(source) {
|
|
187
|
+
export function readGithubTokenSource(source, options = {}) {
|
|
171
188
|
if (source?.type === "env") return source.token || "";
|
|
172
189
|
if (source?.type === "token-file") return readBoundedFileSync(source.path, { encoding: "utf8", maxBytes: MAX_TOKEN_FILE_BYTES }).trim();
|
|
173
190
|
if (source?.type === "auth-json") {
|
|
@@ -175,7 +192,7 @@ export function readGithubTokenSource(source) {
|
|
|
175
192
|
if (!looksLikeCopilotAuthJson(json)) return "";
|
|
176
193
|
return extractGithubTokenFromAuthJson(json);
|
|
177
194
|
}
|
|
178
|
-
return
|
|
195
|
+
return readAdditionalGithubSource(source, { readJson: readSmallJson, ...options });
|
|
179
196
|
}
|
|
180
197
|
|
|
181
198
|
export function readSavedGithubToken(home = os.homedir()) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
// Known provider contracts only; never treat unrelated API keys as GitHub tokens.
|
|
6
|
+
export function additionalGithubSources(home, env) {
|
|
7
|
+
const data = env.XDG_DATA_HOME || path.join(home, ".local", "share");
|
|
8
|
+
const sources = [];
|
|
9
|
+
const auth = path.join(data, "opencode", "auth.json");
|
|
10
|
+
if (fs.existsSync(auth)) sources.push({ type: "opencode-auth", path: auth });
|
|
11
|
+
const search = Object.entries(env).find(([key]) => key.toLowerCase() === "path")?.[1] || "";
|
|
12
|
+
const seen = new Set();
|
|
13
|
+
for (const item of search.split(path.delimiter)) {
|
|
14
|
+
const directory = item.trim().replace(/^"|"$/g, "");
|
|
15
|
+
if (!directory || !path.isAbsolute(directory)) continue;
|
|
16
|
+
const key = process.platform === "win32" ? directory.toLowerCase() : directory;
|
|
17
|
+
if (seen.has(key)) continue;
|
|
18
|
+
seen.add(key);
|
|
19
|
+
const command = path.join(directory, process.platform === "win32" ? "gh.exe" : "gh");
|
|
20
|
+
try {
|
|
21
|
+
if (fs.statSync(command).isFile()) { sources.push({ type: "github-cli", path: command });break; }
|
|
22
|
+
} catch {}
|
|
23
|
+
}
|
|
24
|
+
return sources;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function readAdditionalGithubSource(source, { readJson, env = process.env, exec = execFileSync } = {}) {
|
|
28
|
+
if (source.type === "opencode-auth") {
|
|
29
|
+
const credential = readJson(source.path)?.["github-copilot"];
|
|
30
|
+
// Legacy OpenCode auth.json stores GitHub's OAuth token in refresh, not the
|
|
31
|
+
// short-lived Copilot service token. Enterprise credentials have another audience.
|
|
32
|
+
if (credential?.type !== "oauth" || credential.enterpriseUrl || credential.enterprise_url) return "";
|
|
33
|
+
return typeof credential.refresh === "string" ? credential.refresh.trim() : "";
|
|
34
|
+
}
|
|
35
|
+
if (source.type === "github-cli") {
|
|
36
|
+
return exec(source.path, ["auth", "token", "--hostname", "github.com"], {
|
|
37
|
+
env: { ...env, GH_PROMPT_DISABLED: "1" }, encoding: "utf8", shell: false,
|
|
38
|
+
windowsHide: true, timeout: 1000, maxBuffer: 16 * 1024, stdio: ["ignore", "pipe", "pipe"],
|
|
39
|
+
}).trim();
|
|
40
|
+
}
|
|
41
|
+
return "";
|
|
42
|
+
}
|
package/src/auth.mjs
CHANGED
|
@@ -91,7 +91,18 @@ export async function ensureGithubTokenMetadata(token, {
|
|
|
91
91
|
export async function validateGithubToken(token, {
|
|
92
92
|
fetchImpl = fetch,
|
|
93
93
|
signal,
|
|
94
|
+
timeoutMs = 10000,
|
|
94
95
|
} = {}) {
|
|
96
|
+
const deadline = AbortSignal.timeout(parseTimerMs(timeoutMs, 10000));
|
|
97
|
+
const combined = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
98
|
+
try {
|
|
99
|
+
return await awaitWithSignal(() => validateGithubTokenRequest(token, { fetchImpl, signal: combined }), combined);
|
|
100
|
+
} catch {
|
|
101
|
+
return { ok: false, transient: true, reason: signal?.aborted ? "validation_cancelled" : "validation_timeout" };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function validateGithubTokenRequest(token, { fetchImpl, signal }) {
|
|
95
106
|
if (typeof token !== "string" || !token.trim()) {
|
|
96
107
|
return { ok: false, reason: "empty_token" };
|
|
97
108
|
}
|
|
@@ -99,37 +110,42 @@ export async function validateGithubToken(token, {
|
|
|
99
110
|
const headers = { Authorization: `token ${token.trim()}`, Accept: "application/json" };
|
|
100
111
|
let userResp;
|
|
101
112
|
try {
|
|
102
|
-
userResp = await fetchImpl(`${GITHUB_API}/user`, { headers, signal });
|
|
113
|
+
userResp = await awaitWithSignal(() => fetchImpl(`${GITHUB_API}/user`, { headers, signal, redirect: "error" }), signal);
|
|
103
114
|
} catch (e) {
|
|
104
115
|
return { ok: false, transient: true, reason: "github_user_request_failed", error: e };
|
|
105
116
|
}
|
|
106
117
|
|
|
107
118
|
if (!userResp.ok) {
|
|
119
|
+
cancelResponseBody(userResp);
|
|
108
120
|
return {
|
|
109
121
|
ok: false,
|
|
110
122
|
status: userResp.status,
|
|
123
|
+
transient: userResp.status === 429 || userResp.status >= 500 || userResp.headers?.get?.("x-ratelimit-remaining") === "0",
|
|
111
124
|
reason: userResp.status === 401 || userResp.status === 403 ? "github_token_invalid" : "github_user_failed",
|
|
112
125
|
};
|
|
113
126
|
}
|
|
114
127
|
|
|
115
128
|
let userData = {};
|
|
116
129
|
try {
|
|
117
|
-
userData = await userResp.json();
|
|
130
|
+
userData = await awaitWithSignal(() => userResp.json(), signal);
|
|
118
131
|
} catch {}
|
|
119
132
|
const login = typeof userData.login === "string" ? userData.login : "";
|
|
120
133
|
const id = userData.id === undefined || userData.id === null ? "" : String(userData.id);
|
|
134
|
+
if (!login && !id) return { ok: false, transient: true, reason: "github_identity_missing" };
|
|
121
135
|
|
|
122
136
|
let copilotResp;
|
|
123
137
|
try {
|
|
124
|
-
copilotResp = await fetchImpl(COPILOT_TOKEN_URL, { headers, signal });
|
|
138
|
+
copilotResp = await awaitWithSignal(() => fetchImpl(COPILOT_TOKEN_URL, { headers, signal, redirect: "error" }), signal);
|
|
125
139
|
} catch (e) {
|
|
126
140
|
return { ok: false, transient: true, reason: "copilot_token_request_failed", login, error: e };
|
|
127
141
|
}
|
|
128
142
|
|
|
129
143
|
if (!copilotResp.ok) {
|
|
144
|
+
cancelResponseBody(copilotResp);
|
|
130
145
|
return {
|
|
131
146
|
ok: false,
|
|
132
147
|
status: copilotResp.status,
|
|
148
|
+
transient: copilotResp.status === 429 || copilotResp.status >= 500,
|
|
133
149
|
reason: copilotResp.status === 401 || copilotResp.status === 403 ? "copilot_access_denied" : "copilot_token_failed",
|
|
134
150
|
login,
|
|
135
151
|
};
|
|
@@ -137,13 +153,13 @@ export async function validateGithubToken(token, {
|
|
|
137
153
|
|
|
138
154
|
let copilotTokenData = {};
|
|
139
155
|
try {
|
|
140
|
-
copilotTokenData = await copilotResp.json();
|
|
156
|
+
copilotTokenData = await awaitWithSignal(() => copilotResp.json(), signal);
|
|
141
157
|
} catch (e) {
|
|
142
|
-
return { ok: false, reason: "copilot_token_parse_failed", login, error: e };
|
|
158
|
+
return { ok: false, transient: true, reason: "copilot_token_parse_failed", login, error: e };
|
|
143
159
|
}
|
|
144
160
|
|
|
145
|
-
if (!copilotTokenData.token) {
|
|
146
|
-
return { ok: false, reason: "copilot_token_missing", login };
|
|
161
|
+
if (typeof copilotTokenData.token !== "string" || !copilotTokenData.token.trim()) {
|
|
162
|
+
return { ok: false, transient: true, reason: "copilot_token_missing", login };
|
|
147
163
|
}
|
|
148
164
|
|
|
149
165
|
return { ok: true, login, id, copilotTokenData };
|
|
@@ -158,25 +174,35 @@ export async function discoverGithubToken({
|
|
|
158
174
|
excludeIdentities = [],
|
|
159
175
|
expectedIdentity,
|
|
160
176
|
strictExpectedIdentity = false,
|
|
177
|
+
timeoutMs = 12000,
|
|
178
|
+
maxCandidates = 24,
|
|
179
|
+
sources = githubTokenSources({ home, env }),
|
|
180
|
+
readSource = readGithubTokenSource,
|
|
161
181
|
} = {}) {
|
|
182
|
+
const deadline = AbortSignal.timeout(parseTimerMs(timeoutMs, 12000));
|
|
183
|
+
const boundedSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
162
184
|
const excluded = new Set(excludeTokens);
|
|
163
185
|
const seen = new Set(excluded);
|
|
164
186
|
const failures = [];
|
|
165
187
|
const candidates = [];
|
|
166
188
|
|
|
167
|
-
for (const source of
|
|
189
|
+
for (const source of sources) {
|
|
190
|
+
if (boundedSignal.aborted || seen.size - excluded.size >= maxCandidates) {
|
|
191
|
+
return { ok: false, incomplete: true, transient: true, failures };
|
|
192
|
+
}
|
|
168
193
|
let token = "";
|
|
169
194
|
try {
|
|
170
|
-
token =
|
|
195
|
+
token = readSource(source, { env }).trim();
|
|
171
196
|
} catch (e) {
|
|
172
|
-
|
|
197
|
+
// Child-process errors may carry stdout containing a credential.
|
|
198
|
+
failures.push({ source: { type: source.type, path: source.path }, reason: "read_failed" });
|
|
173
199
|
continue;
|
|
174
200
|
}
|
|
175
201
|
|
|
176
202
|
if (!token || seen.has(token)) continue;
|
|
177
203
|
seen.add(token);
|
|
178
204
|
|
|
179
|
-
const validation = await validateGithubToken(token, { fetchImpl, signal });
|
|
205
|
+
const validation = await validateGithubToken(token, { fetchImpl, signal: boundedSignal, timeoutMs: 4000 });
|
|
180
206
|
if (validation.ok) {
|
|
181
207
|
if (excludeIdentities.some((identity) => githubIdentityMatchesExpected(validation, identity))) {
|
|
182
208
|
failures.push({ source, validation, reason: "github_account_excluded" });
|
|
@@ -196,6 +222,9 @@ export async function discoverGithubToken({
|
|
|
196
222
|
failures.push({ source, validation });
|
|
197
223
|
}
|
|
198
224
|
|
|
225
|
+
if (sources.incomplete || boundedSignal.aborted || failures.some(item => item.validation?.transient)) {
|
|
226
|
+
return { ok: false, incomplete: true, transient: true, failures };
|
|
227
|
+
}
|
|
199
228
|
if (candidates.length) {
|
|
200
229
|
const identities = new Set(candidates.map(({ validation, token }) => {
|
|
201
230
|
if (validation.id) return `id:${validation.id}`;
|
|
@@ -238,6 +267,7 @@ export async function importDiscoveredGithubToken({
|
|
|
238
267
|
return { ok: true, token: savedToken, source: { type: "saved-token" }, imported: false };
|
|
239
268
|
}
|
|
240
269
|
const validation = await validateGithubToken(savedToken, { fetchImpl, signal });
|
|
270
|
+
if (validation.transient) throw new Error("GitHub access could not be checked. The saved credential was preserved; check your network and retry.");
|
|
241
271
|
if (validation.ok && githubIdentityMatchesExpected(validation, expectedIdentity)) {
|
|
242
272
|
writeGithubTokenMetadata(validation, home, savedToken);
|
|
243
273
|
return { ok: true, token: savedToken, source: { type: "saved-token" }, validation, imported: false };
|
|
@@ -257,6 +287,7 @@ export async function importDiscoveredGithubToken({
|
|
|
257
287
|
const logins = [...new Set(discovered.candidates.map((candidate) => candidate.login || candidate.id || "unknown"))];
|
|
258
288
|
throw new Error(`Multiple GitHub Copilot accounts were found (${logins.join(", ")}). Set CCDX_GITHUB_LOGIN or CCDX_GITHUB_TOKEN_PATH to select one explicitly.`);
|
|
259
289
|
}
|
|
290
|
+
if (discovered.transient) throw new Error("Local GitHub credentials could not be fully checked. Check network access and retry; no new login was started.");
|
|
260
291
|
if (!discovered.ok) return null;
|
|
261
292
|
writeToken(discovered.token, home, discovered.validation);
|
|
262
293
|
const login = discovered.validation.login ? ` for ${discovered.validation.login}` : "";
|
package/src/cli-options.mjs
CHANGED
|
@@ -295,6 +295,8 @@ export function parseCliArgs(args = []) {
|
|
|
295
295
|
const options = parseOptions(rest, new Map([
|
|
296
296
|
["--online", "flag"],
|
|
297
297
|
["--compat", "flag"],
|
|
298
|
+
["--fix", "flag"],
|
|
299
|
+
["--json", "flag"],
|
|
298
300
|
["--profile", "value"],
|
|
299
301
|
]));
|
|
300
302
|
const profile = options["--profile"];
|
|
@@ -306,6 +308,8 @@ export function parseCliArgs(args = []) {
|
|
|
306
308
|
...baseCommand("doctor"),
|
|
307
309
|
online: Boolean(options["--online"]),
|
|
308
310
|
compat: Boolean(options["--compat"]),
|
|
311
|
+
...(options["--fix"] ? { fix: true } : {}),
|
|
312
|
+
...(options["--json"] ? { json: true } : {}),
|
|
309
313
|
};
|
|
310
314
|
}
|
|
311
315
|
if (RETIRED_CLAUDE_OPTIONS.has(command)) {
|
|
@@ -363,7 +367,7 @@ function topicHelp(name, topic) {
|
|
|
363
367
|
start: `Usage:\n ${name} [start] [--show-request-id]\n\nStarts or reuses the local adapter, updates Codex configuration, and attempts to open Codex App when auto-launch is enabled and supported.`,
|
|
364
368
|
auth: `Usage:\n ${name} auth status [--online] [--format table|plain]\n\nShows the saved GitHub Copilot account without exposing credentials. --online also verifies its entitlement and model catalog.`,
|
|
365
369
|
"auth status": `Usage:\n ${name} auth status [--online] [--format table|plain]\n\nShows the saved GitHub Copilot account without exposing credentials. --online also verifies its entitlement and model catalog. Interactive terminals use a table by default.`,
|
|
366
|
-
doctor: `Usage:\n ${name} doctor [--online] [--compat]\n ${name} doctor config\n\nChecks
|
|
370
|
+
doctor: `Usage:\n ${name} doctor [--online] [--compat] [--fix] [--json]\n ${name} doctor config\n\nChecks credentials, managed configuration, command launchers, adapter, enabled optional features and observed client catalog. Default is read-only; no inference requests. --online validates account entitlement; --compat sends minimal inference requests and consumes a small amount of Copilot usage, requiring successful model completion rather than HTTP 200 alone. --fix repairs owned Windows launchers and managed config, imports a verified existing credential only if none is saved, and asks the running adapter to repair enabled predictions once. No interactive login, client program edits, forced App restarts, policy changes or optional feature activation. Missing-credential repair can contact GitHub without --online. Changed existing config is backed up to config.toml.ccdx-doctor.bak. Partial repairs exit 1. --json emits a redacted report, including before_checks for repairs. App-internal cache and visible predictions are not externally verified. The config subcommand remains strictly read-only.`,
|
|
367
371
|
"doctor config": `Usage:\n ${name} doctor config\n\nReads ~/.codex/config.toml, checks TOML syntax and CCDX-managed settings, and previews the existing startup writer's changes. Does not merge Codex profiles or validate the complete installed Codex schema. No authentication, network requests, file writes, or adapter/GUI startup. Existing context_management=false is valid. Exit 1 for errors, 0 for OK/warnings; unsupported arguments exit 2.`,
|
|
368
372
|
status: `Usage:\n ${name} status\n\nShows bounded runtime, routing, performance, queue, and cache metrics from a running adapter.`,
|
|
369
373
|
models: `Usage:\n ${name} models [--format table|plain]\n\nPerforms a fresh, read-only Copilot model-directory lookup for the saved account. Interactive terminals use a table by default.`,
|
|
@@ -390,7 +394,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
|
|
|
390
394
|
return `Usage:
|
|
391
395
|
${name} [start] [--show-request-id]
|
|
392
396
|
${name} auth status [--online] [--format table|plain]
|
|
393
|
-
${name} doctor [--online] [--compat]
|
|
397
|
+
${name} doctor [--online] [--compat] [--fix] [--json]
|
|
394
398
|
${name} doctor config
|
|
395
399
|
${name} status
|
|
396
400
|
${name} models [--format table|plain]
|
|
@@ -49,10 +49,8 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
|
|
|
49
49
|
async configure() {
|
|
50
50
|
try {
|
|
51
51
|
const { retirePredictionIntegration } = await import("./prediction-retirement.mjs");
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (result.preserved) warning("Modified prediction settings were preserved");
|
|
55
|
-
} catch (error) { warning(`${error.message}. Core startup will continue.`); }
|
|
52
|
+
retirePredictionIntegration();
|
|
53
|
+
} catch { /* Legacy cleanup is optional; never interrupt or clutter core startup. */ }
|
|
56
54
|
const enabled = Boolean(readImageProviderConfig());
|
|
57
55
|
const { imageMcpSkipped } = ensureCodexConfig(port, { host, imageProviderEnabled: enabled, ...(configLog ? { log: configLog } : {}) });
|
|
58
56
|
if (enabled && !imageMcpSkipped) {
|
|
@@ -5,6 +5,8 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
5
5
|
import { parse } from "smol-toml";
|
|
6
6
|
import { computeUpdatedCodexConfig, initialCodexConfig } from "./config.mjs";
|
|
7
7
|
import { adapterBaseUrl } from "./running-adapter.mjs";
|
|
8
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
9
|
+
import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
8
10
|
|
|
9
11
|
const MANAGED_KEYS = [
|
|
10
12
|
"openai_base_url",
|
|
@@ -165,3 +167,27 @@ export function inspectCodexConfig({ home = os.homedir(), env: processEnv = proc
|
|
|
165
167
|
checks.push(startupPreview(content, config, host, port));
|
|
166
168
|
return checks;
|
|
167
169
|
}
|
|
170
|
+
|
|
171
|
+
export function repairCodexConfig(options = {}) {
|
|
172
|
+
const { host = "127.0.0.1", port = 2026 } = options;
|
|
173
|
+
const file = codexPaths(options).config;
|
|
174
|
+
return withFileLockSync(`${file}.ccdx.lock`, () => {
|
|
175
|
+
if (inspectCodexConfig(options).some(check => check.kind === "err")) {
|
|
176
|
+
return { status: "preserved", changed: false };
|
|
177
|
+
}
|
|
178
|
+
let content = null;
|
|
179
|
+
try { content = fs.readFileSync(file, "utf8"); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
180
|
+
const next = content === null ? { content: initialCodexConfig(port, host), changed: true }
|
|
181
|
+
: computeUpdatedCodexConfig(content, port, host);
|
|
182
|
+
if (!next.changed) return { status: "unchanged", changed: false };
|
|
183
|
+
const before = content === null ? {} : parseConfig(content);
|
|
184
|
+
if (!isDeepStrictEqual(unmanagedSettings(before), unmanagedSettings(parseConfig(next.content)))) {
|
|
185
|
+
return { status: "preserved", changed: false };
|
|
186
|
+
}
|
|
187
|
+
if (content === null) atomicWriteFileIfChangedSync(file, next.content, { mode: 0o600 });
|
|
188
|
+
else atomicWriteFilePairSync(file, next.content, `${file}.ccdx-doctor.bak`, content, { mode: 0o600 });
|
|
189
|
+
const verified = !inspectCodexConfig(options).some(check => check.kind === "err"
|
|
190
|
+
|| check.message.startsWith("Next startup would"));
|
|
191
|
+
return { status: verified ? "verified" : "needs_review", changed: true };
|
|
192
|
+
});
|
|
193
|
+
}
|
package/src/dashboard/index.html
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
|
|
24
24
|
<main>
|
|
25
25
|
<section class="intro">
|
|
26
|
-
<h1><svg class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg> ccdx status</h1>
|
|
26
|
+
<h1><svg id="status-icon" class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg> ccdx status</h1>
|
|
27
27
|
<div class="snapshot-meta"><p id="auth-account" role="status" data-i18n data-i18n-title title="Saved GitHub Copilot account / local credentials only; not an online entitlement check.">GitHub / READING</p><p id="updated" data-i18n>Reading status…</p></div>
|
|
28
28
|
</section>
|
|
29
29
|
|
package/src/dashboard/refresh.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
const interval = 30 * 60 * 1000;
|
|
3
3
|
const freshness = 30 * 1000;
|
|
4
4
|
|
|
5
|
-
function createController({ resources, visible, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
|
|
5
|
+
function createController({ resources, visible, onState = () => {}, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
|
|
6
6
|
const states = new Map(Object.keys(resources).map(key => [key, {
|
|
7
7
|
value: undefined, signature: undefined, variant: undefined, pending: null,
|
|
8
8
|
updatedAt: null, attemptedAt: null, error: null, generation: 0, abort: null,
|
|
@@ -12,7 +12,11 @@
|
|
|
12
12
|
let automatic = true;
|
|
13
13
|
const state = key => states.get(key);
|
|
14
14
|
const stopTimer = () => { if (timer !== null) clearTimer(timer); timer = null; };
|
|
15
|
-
const notify = key =>
|
|
15
|
+
const notify = key => {
|
|
16
|
+
resources[key].state?.(state(key));
|
|
17
|
+
const pendingKeys = [...states.keys()].filter(name => state(name).pending);
|
|
18
|
+
onState({ pending: pendingKeys.length > 0, pendingKeys });
|
|
19
|
+
};
|
|
16
20
|
|
|
17
21
|
function schedule() {
|
|
18
22
|
stopTimer();
|
|
@@ -44,7 +48,6 @@
|
|
|
44
48
|
entry.attemptedAt = now();
|
|
45
49
|
entry.attemptVariant = variant;
|
|
46
50
|
entry.pendingVariant = variant;
|
|
47
|
-
entry.error = null;
|
|
48
51
|
entry.pending = Promise.resolve().then(async () => {
|
|
49
52
|
try {
|
|
50
53
|
const value = await resource.load({ variant, signal: abort.signal });
|
|
@@ -56,6 +59,7 @@
|
|
|
56
59
|
entry.signature = signature;
|
|
57
60
|
entry.variant = variant;
|
|
58
61
|
entry.updatedAt = now();
|
|
62
|
+
entry.error = null;
|
|
59
63
|
return value;
|
|
60
64
|
} catch (error) {
|
|
61
65
|
if (active && generation === entry.generation) entry.error = error;
|