codex-copilot-dx 1.2.21 → 1.2.22
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 +77 -14
- package/docs/ARCHITECTURE.md +70 -3
- package/docs/REFERENCE.md +100 -2
- package/package.json +2 -1
- package/src/account-tools.mjs +1 -1
- package/src/adapter.mjs +17 -2
- package/src/api-catalog-refresh.mjs +1 -0
- package/src/api-secrets.mjs +28 -9
- package/src/auth.mjs +2 -0
- package/src/bounded-result-cache.mjs +12 -0
- package/src/client-gateway-keys.mjs +7 -3
- package/src/client-integration.mjs +3 -0
- package/src/connection-runtime.mjs +16 -5
- package/src/dashboard/console.js +6 -1
- package/src/dashboard/flow.js +17 -7
- package/src/dashboard/index.html +6 -0
- package/src/dashboard/language.js +24 -0
- package/src/dashboard/ui.css +16 -2
- package/src/dashboard/ui.js +4 -4
- package/src/dashboard/view-boundary.js +41 -0
- package/src/dashboard-tools.mjs +1 -0
- package/src/dashboard.mjs +26 -5
- package/src/image-mcp.mjs +3 -0
- package/src/image-references.mjs +9 -0
- package/src/local-tools.mjs +1 -1
- package/src/m365-settings.mjs +5 -0
- package/src/nightly-update.mjs +107 -0
- package/src/optional-routes.mjs +19 -5
- package/src/provider-runtime.mjs +3 -2
- package/src/providers/api.mjs +6 -4
- package/src/release-install.mjs +24 -12
- package/src/response-history.mjs +50 -0
- package/src/service-control.mjs +9 -3
- package/src/service-supervisor.mjs +168 -0
- package/src/service-worker.mjs +87 -0
- package/src/terminal-console.mjs +1 -0
- package/src/user-settings.mjs +15 -0
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# codex-copilot-dx
|
|
2
2
|
|
|
3
|
-
CCDX connects Codex App to GitHub Copilot by default: discovery, adapted model catalogs, Responses streaming, tool calls and conversation history. Eligible Microsoft 365 environments can also use a protocol-isolated Claude gateway on the main listener and manually select M365 as a Codex backup. Default Auto-review: **GPT-6.1 Sol / low**. Image generation is **off by default**. Native predictions are also **off by default**.
|
|
3
|
+
CCDX connects Codex App to GitHub Copilot by default: discovery, adapted model catalogs, Responses streaming, tool calls and conversation history. Eligible Microsoft 365 environments can also use a protocol-isolated Claude gateway on the main listener and manually select M365 as a Codex backup. Default Auto-review: **GPT-6.1 Sol / low**. Image generation is **off by default**. Native predictions and nightly software updates are also **off by default**.
|
|
4
4
|
|
|
5
5
|
## Install and run
|
|
6
6
|
|
|
@@ -11,13 +11,13 @@ npm install -g codex-copilot-dx@latest
|
|
|
11
11
|
ccdx
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
14
|
+
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.22/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.22/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
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.
|
|
19
19
|
|
|
20
|
-
Requests shows live app/source/model flow above existing summaries and finished records. 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).
|
|
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
|
|
|
22
22
|
## Commands
|
|
23
23
|
| Command | Purpose |
|
|
@@ -56,7 +56,7 @@ Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter t
|
|
|
56
56
|
|
|
57
57
|
Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving reads model metadata automatically, without inference. Startup and the existing model refresh cycle also refresh enabled APIs when the 30-minute cache expires; failed reads retain saved configuration. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
|
|
58
58
|
|
|
59
|
-
Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.
|
|
59
|
+
Model 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.22 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.22.md) cover isolated initialization, Web resilience and opt-in nightly updates while retaining native GitHub sign-in/model protections.
|
|
60
60
|
|
|
61
61
|
## Microsoft 365 access
|
|
62
62
|
|
|
@@ -110,9 +110,9 @@ See the [M365 reference](docs/REFERENCE.md#microsoft-365-provider) for ownership
|
|
|
110
110
|
expose it to the public internet. The dashboard is not an authentication wall
|
|
111
111
|
for the API. Inference rejects browser Origin headers; native clients remain supported. Diagnostic errors may contain sensitive upstream text.
|
|
112
112
|
|
|
113
|
-
Open `ccdx web` for source-specific account tools and Checks & repairs without signing in first. It starts a management-only service when needed; stop it before normal app startup. Safe reauth, config preview/backup, local reports, feature pause/resume and matching circle SVG status icons are described in the [account tools reference](docs/REFERENCE.md#account-and-repair-tools). Existing themes, layout and bilingual support are preserved. Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`. Settings → Version & updates shows the running version, release dates and newer releases, with copyable update and macOS/Windows recovery commands. This separate, cached GitHub metadata check never installs
|
|
113
|
+
Open `ccdx web` for source-specific account tools and Checks & repairs without signing in first. It starts a management-only service when needed; stop it before normal app startup. Safe reauth, config preview/backup, local reports, feature pause/resume and matching circle SVG status icons are described in the [account tools reference](docs/REFERENCE.md#account-and-repair-tools). Existing themes, layout and bilingual support are preserved. Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`. Settings → Version & updates shows the running version, release dates and newer releases, with copyable update and macOS/Windows recovery commands. This separate, cached GitHub metadata check never installs; failed checks remain unknown. The separate **Update overnight** switch defaults off and requires a normal CCDX restart after enabling. Its foreground supervisor checks during 00:00–04:00 local time after ten observed idle minutes, selects same-series stable patches at least 24 hours old, stages verified packages and attempts rollback on failure. Ctrl+C stops it; no OS service is installed. Review the displayed risk and [handoff limits](docs/REFERENCE.md#nightly-updates-opt-in) before enabling. See the [reference](docs/REFERENCE.md#version-and-update-information).
|
|
114
114
|
GitHub updates verify and install the exact Release tarball without Git; dependencies still use npm's configured registry. Lookup errors identify HTTP refusal, timeout, network failure or invalid redirects. For npm `EALLOWREMOTE`, only if policy permits and the update is trusted, use `ccdx update github --allow-remote`: explicit URL-download permission for that installation's whole dependency tree, not a hostname allowlist. Persistent npm settings stay unchanged.
|
|
115
|
-
Updates back up the discovered CCDX package and commands, restore them on install/runtime-check failure, and verify the installed version (exact for GitHub). Mismatched npm targets warn without changing PATH/prefix.
|
|
115
|
+
Updates back up the discovered CCDX package and commands, restore them on install/runtime-check failure, and verify the installed version (exact for GitHub). Mismatched npm targets warn without changing PATH/prefix. Manual updates require a separate adapter restart. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
|
|
116
116
|
Recent errors separate HTTP and model failures. By default HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged. Explicit, bounded error-excerpt collection is described in the [reference](docs/REFERENCE.md#http-error-diagnostics).
|
|
117
117
|
|
|
118
118
|
See [architecture boundaries](docs/ARCHITECTURE.md) and the [complete reference](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/REFERENCE.md) for authentication, configuration, limits, logging, images and compatibility. It is also included as `docs/REFERENCE.md` in the npm package.
|
package/bin/cli.mjs
CHANGED
|
@@ -14,7 +14,7 @@ import { runInBackground } from "../src/startup.mjs";
|
|
|
14
14
|
import { cliCommandName, cliHelp, parseAdapterAddressOptions, parseAdapterProbeOptions, parseCliArgs, parseRuntimeOptions } from "../src/cli-options.mjs";
|
|
15
15
|
import { formatAdapterStatus, readAdapterStatus } from "../src/cli-status.mjs";
|
|
16
16
|
import { closeHttpServer } from "../src/shutdown.mjs";
|
|
17
|
-
import { autoReviewModelPreference, autoReviewPreference, responseHistoryLimitPreference, terminalAnimationPreference, servicePreferences, serviceSettingsSnapshot } from "../src/user-settings.mjs";
|
|
17
|
+
import { autoReviewModelPreference, autoReviewPreference, responseHistoryLimitPreference, terminalAnimationPreference, servicePreferences, serviceSettingsSnapshot, nightlyUpdatePreference } from "../src/user-settings.mjs";
|
|
18
18
|
import { formatLiveCopilotModels } from "../src/cli-models.mjs";
|
|
19
19
|
import { runAuthCommand } from "../src/cli-auth.mjs";
|
|
20
20
|
import { createProfileRuntime } from "../src/profile-runtime.mjs";
|
|
@@ -305,6 +305,26 @@ if (CLI.command === "doctor" && CLI.configOnly) {
|
|
|
305
305
|
process.exit(checks.some((check) => check.kind === "err") ? 1 : 0);
|
|
306
306
|
}
|
|
307
307
|
|
|
308
|
+
let serviceWorker = null;
|
|
309
|
+
if (CLI.command === "start") {
|
|
310
|
+
if (process.send && process.env.CCDX_SUPERVISED_SERVICE === "1") {
|
|
311
|
+
const { createServiceWorker } = await import("../src/service-worker.mjs");
|
|
312
|
+
serviceWorker = await createServiceWorker();
|
|
313
|
+
} else if (nightlyUpdatePreference()) {
|
|
314
|
+
const { installedUpdateEnvironment } = await import("../src/nightly-update.mjs");
|
|
315
|
+
const address = parseAdapterProbeOptions(process.env);
|
|
316
|
+
const existing = await checkRunningAdapter({ host: address.adapterHost, port: address.adapterPort, timeoutMs: address.existingAdapterTimeoutMs });
|
|
317
|
+
let environment;
|
|
318
|
+
try { if (!existing.ok && !existing.incompatible) environment = installedUpdateEnvironment(); }
|
|
319
|
+
catch { console.warn(status("warn", "Nightly updates need a writable, matching npm installation. Starting without automatic updates.")); }
|
|
320
|
+
if (environment) {
|
|
321
|
+
const { runServiceSupervisor } = await import("../src/service-supervisor.mjs");
|
|
322
|
+
try { process.exit(await runServiceSupervisor({ environment })); }
|
|
323
|
+
catch { console.warn(status("warn", "Nightly runtime preparation failed. Starting without automatic updates.")); }
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
308
328
|
let RUNTIME;
|
|
309
329
|
try {
|
|
310
330
|
RUNTIME = parseRuntimeOptions(process.env);
|
|
@@ -318,7 +338,8 @@ const ADAPTER_PORT = RUNTIME.adapterPort;
|
|
|
318
338
|
const ADAPTER_HOST = RUNTIME.adapterHost;
|
|
319
339
|
const MODEL_REFRESH_TIMEOUT_MS = RUNTIME.modelRefreshTimeoutMs;
|
|
320
340
|
const EXISTING_ADAPTER_TIMEOUT_MS = RUNTIME.existingAdapterTimeoutMs;
|
|
321
|
-
|
|
341
|
+
let LOGGING = configureLogging({ env: serviceWorker?.warming ? { ...process.env, CCDX_LOG_PATH: "" } : process.env });
|
|
342
|
+
if (serviceWorker?.warming) LOGGING.setTerminalSink(() => {});
|
|
322
343
|
let activeServer = null;
|
|
323
344
|
let modelRefreshTimer = null;
|
|
324
345
|
let shuttingDown = false;
|
|
@@ -400,6 +421,7 @@ async function reuseRunningAdapterIfAvailable() {
|
|
|
400
421
|
}
|
|
401
422
|
|
|
402
423
|
async function configureCodexClient() {
|
|
424
|
+
if (serviceWorker?.preserving) return { compressionSetup: Promise.resolve(), imageEnabled: false, imageMcpSkipped: false };
|
|
403
425
|
return (await clientIntegrations()).configure();
|
|
404
426
|
}
|
|
405
427
|
|
|
@@ -440,9 +462,10 @@ try {
|
|
|
440
462
|
} catch { console.warn(startupCheck("warn", "Command", "Command setup skipped; service will start")); }
|
|
441
463
|
}
|
|
442
464
|
const updateNotice = runInBackground(printUpdateNotice);
|
|
443
|
-
if (await reuseRunningAdapterIfAvailable()) {
|
|
465
|
+
if (!serviceWorker?.warming && await reuseRunningAdapterIfAvailable()) {
|
|
444
466
|
// Ready is already displayed; finish the bounded check before this short-lived CLI exits.
|
|
445
467
|
await updateNotice;
|
|
468
|
+
serviceWorker?.reused();
|
|
446
469
|
await LOGGING.cleanup();
|
|
447
470
|
process.exit(0);
|
|
448
471
|
}
|
|
@@ -462,16 +485,16 @@ try {
|
|
|
462
485
|
log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "Models", message)),
|
|
463
486
|
});
|
|
464
487
|
providerRuntime = createProviderRuntime({ githubClient: profileRuntime.codexClient, githubRegistry: profileModels.codexRegistry,
|
|
465
|
-
corePort: ADAPTER_PORT,
|
|
488
|
+
corePort: ADAPTER_PORT, preserveClientConfiguration: () => serviceWorker?.preserving === true || serviceWorker?.draining === true,
|
|
466
489
|
clientAccessChanged: async enabled => { earlyIntegration.setPredictionActive(enabled && servicePreferences().prediction_enabled);if (enabled) await earlyIntegration.configure(); },
|
|
467
490
|
githubCredentialFingerprint: () => profileRuntime.codexCredentialFingerprint,
|
|
468
491
|
log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "M365", message)) });
|
|
469
492
|
const codexEnabled = providerRuntime.connections().clients.find(client => client.id === "codex").enabled;
|
|
470
|
-
const predictionSetup = codexEnabled ? runInBackground(() => earlyIntegration.start()) : Promise.resolve(null);
|
|
493
|
+
const predictionSetup = codexEnabled && !serviceWorker?.warming ? runInBackground(() => earlyIntegration.start()) : Promise.resolve(null);
|
|
471
494
|
const m365Setup = runInBackground(() => providerRuntime.start());
|
|
472
495
|
if (providerRuntime.selection().codex === "github") {
|
|
473
|
-
try { await ensureAuth({ log: startupLogger("Sign-in") }); }
|
|
474
|
-
catch (error) { console.warn(startupCheck("warn", "Sign-in", "Sign-in unavailable. Use the dashboard or ccdx auth login; saved credentials kept.")); }
|
|
496
|
+
try { await ensureAuth({ log: startupLogger("Sign-in"), interactive: serviceWorker?.preserving !== true }); }
|
|
497
|
+
catch (error) { if (serviceWorker?.preserving) throw error;console.warn(startupCheck("warn", "Sign-in", "Sign-in unavailable. Use the dashboard or ccdx auth login; saved credentials kept.")); }
|
|
475
498
|
} else {
|
|
476
499
|
if (providerRuntime.selection().codex === "m365") await m365Setup;
|
|
477
500
|
const source = providerRuntime.connections().providers.find(source => source.id === providerRuntime.selection().codex);
|
|
@@ -481,8 +504,9 @@ try {
|
|
|
481
504
|
|
|
482
505
|
// Refresh the VS Code version in the background; fallback is non-blocking.
|
|
483
506
|
void refreshVSCodeVersion();
|
|
484
|
-
if (providerRuntime.selection().codex === "github") {
|
|
507
|
+
if (providerRuntime.selection().codex === "github" || serviceWorker?.needsGithub) {
|
|
485
508
|
await profileModels.initialize();
|
|
509
|
+
if (serviceWorker?.warming) await profileModels.refreshAll();
|
|
486
510
|
// Provider setup can run before GitHub's directory exists. Reconcile again
|
|
487
511
|
// before opening the App, then join any existing stale-cache refresh.
|
|
488
512
|
const refreshing = profileModels.codexRegistry.refreshInFlight ? profileModels.refreshAll() : null;
|
|
@@ -502,9 +526,9 @@ try {
|
|
|
502
526
|
terminalConsole = createTerminalConsole({ baseUrl: webUiUrl, verbose: CLI.verbose === true || CLI.showRequestId === true || LOGGING.level === "debug",
|
|
503
527
|
snapshot: () => activeServer?.ccdxSnapshot?.() || {},
|
|
504
528
|
preferences: () => { const { saved, theme, color_theme } = serviceSettingsSnapshot();return { ...saved, theme, color_theme }; } });
|
|
505
|
-
const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole });
|
|
529
|
+
const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole, nightlyStatus: () => serviceWorker?.status() || null, nightlyChanged: enabled => serviceWorker?.preferenceChanged(enabled) });
|
|
506
530
|
const codexModelCatalog = createCodexModelCatalog();
|
|
507
|
-
activeServer = await startAdapter(ADAPTER_PORT, ADAPTER_HOST, {
|
|
531
|
+
activeServer = await startAdapter(serviceWorker?.warming ? 0 : ADAPTER_PORT, serviceWorker?.warming ? "127.0.0.1" : ADAPTER_HOST, {
|
|
508
532
|
log: startupLogger("Service"),
|
|
509
533
|
autoReviewModelResolver: () => autoReviewPreference(),
|
|
510
534
|
codexClient: profileRuntime.codexClient,
|
|
@@ -517,6 +541,7 @@ try {
|
|
|
517
541
|
streamIdleTimeoutMs: RUNTIME.streamIdleTimeoutMs,
|
|
518
542
|
terminalAnimationTheme,
|
|
519
543
|
terminalActivity: terminalConsole,
|
|
544
|
+
handoffState: serviceWorker?.takeState(), isDraining: () => serviceWorker?.draining === true,
|
|
520
545
|
dashboardOptions: { serviceControl, host: ADAPTER_HOST, port: ADAPTER_PORT,
|
|
521
546
|
credentialsChanged: () => { defaultCopilotClient.invalidateCredentials();profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient }); },
|
|
522
547
|
applyAnimation: theme => terminalConsole.apply({ theme }) },
|
|
@@ -555,20 +580,20 @@ try {
|
|
|
555
580
|
startupComplete = true;
|
|
556
581
|
console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
|
|
557
582
|
await launchDashboard();
|
|
558
|
-
terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
|
|
583
|
+
if (!serviceWorker?.warming) { terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args)); }
|
|
559
584
|
|
|
560
585
|
const shutdown = async (signal) => {
|
|
561
586
|
if (shuttingDown) return;
|
|
562
587
|
shuttingDown = true;
|
|
563
|
-
LOGGING.setTerminalSink(null);terminalConsole?.cleanup();
|
|
588
|
+
LOGGING.setTerminalSink(serviceWorker?.draining ? () => {} : null);terminalConsole?.cleanup();
|
|
564
589
|
console.log(`\n${status("wait", `Stopping: ${signal}`)}`);
|
|
565
590
|
let exitCode = 0;
|
|
566
591
|
try {
|
|
567
592
|
if (modelRefreshTimer) clearInterval(modelRefreshTimer);
|
|
568
|
-
await clientIntegration?.close();
|
|
569
|
-
await providerRuntime?.close();
|
|
570
593
|
const result = await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });
|
|
571
594
|
if (result.forced) console.warn(status("warn", "Remaining service connections closed"));
|
|
595
|
+
await clientIntegration?.close();
|
|
596
|
+
await providerRuntime?.close();
|
|
572
597
|
await flushUsageWrites();
|
|
573
598
|
} catch (e) {
|
|
574
599
|
exitCode = 1;
|
|
@@ -581,6 +606,44 @@ try {
|
|
|
581
606
|
process.once("SIGINT", () => { void shutdown("SIGINT"); });
|
|
582
607
|
process.once("SIGTERM", () => { void shutdown("SIGTERM"); });
|
|
583
608
|
await compressionSetup;
|
|
609
|
+
if (serviceWorker) {
|
|
610
|
+
const { clientStateFingerprint, serviceBusinessState } = await import("../src/service-worker.mjs");
|
|
611
|
+
if (serviceWorker.preserving) providerRuntime.validateLocalKeys();
|
|
612
|
+
await serviceWorker.ready({
|
|
613
|
+
notice: code => console.warn(status("warn", `Nightly update paused: ${code}. Run ccdx update github for details.`)),
|
|
614
|
+
stop: () => shutdown("supervisor"),
|
|
615
|
+
exportState: () => ({ ...activeServer.ccdxExportState(), providers: providerRuntime.exportPrivateState() }),
|
|
616
|
+
importState: async state => { await activeServer.ccdxImportState(state);providerRuntime.importPrivateState(state.providers); },
|
|
617
|
+
release: async () => {
|
|
618
|
+
terminalConsole.pause();await flushUsageWrites();await LOGGING.cleanup();
|
|
619
|
+
LOGGING = configureLogging({ env: { ...process.env, CCDX_LOG_PATH: "" } });LOGGING.setTerminalSink(() => {});
|
|
620
|
+
await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });await earlyIntegration.pauseForUpdate();
|
|
621
|
+
},
|
|
622
|
+
resume: async () => {
|
|
623
|
+
if (!activeServer.listening) await new Promise((resolve, reject) => { activeServer.once("error", reject);activeServer.listen(ADAPTER_PORT, ADAPTER_HOST, () => { activeServer.off("error", reject);resolve(); }); });
|
|
624
|
+
await earlyIntegration.start();earlyIntegration.setPredictionActive(servicePreferences().prediction_enabled);
|
|
625
|
+
await LOGGING.cleanup();LOGGING = configureLogging();terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
|
|
626
|
+
},
|
|
627
|
+
promote: async () => {
|
|
628
|
+
await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });
|
|
629
|
+
await new Promise((resolve, reject) => { activeServer.once("error", reject);activeServer.listen(ADAPTER_PORT, ADAPTER_HOST, () => { activeServer.off("error", reject);resolve(); }); });
|
|
630
|
+
if (codexEnabled) { nativePrediction = await earlyIntegration.start();await nativePrediction?.prepareRoute();earlyIntegration.setPredictionActive(servicePreferences().prediction_enabled); }
|
|
631
|
+
},
|
|
632
|
+
activate: async () => {
|
|
633
|
+
await LOGGING.cleanup();try { LOGGING = configureLogging(); } catch { LOGGING = configureLogging({ env: { ...process.env, CCDX_LOG_PATH: "" } }); }
|
|
634
|
+
terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
|
|
635
|
+
},
|
|
636
|
+
inspect: () => {
|
|
637
|
+
const data = activeServer.ccdxSnapshot(), routes = data.requests.by_route;
|
|
638
|
+
let fingerprint = null;try { fingerprint = clientStateFingerprint(); } catch {}
|
|
639
|
+
return { version: LOCAL_VERSION, fingerprint, business: serviceBusinessState(providerRuntime),
|
|
640
|
+
busy: !fingerprint || activeServer.ccdxBusy() || clientIntegration.busy() || data.models.refresh_in_flight === true || data.model_activity.active === null,
|
|
641
|
+
health: { github: profileRuntime.codexClient.runtimeStatus().token_cached === true && !profileModels.codexRegistry.lastError,
|
|
642
|
+
m365: data.providers?.m365?.state === "ready", prediction: earlyIntegration.bridgeHealthy() },
|
|
643
|
+
activity: { active: data.model_activity.active || 0, total: ["responses", "responses_compact", "messages"].reduce((n, key) => n + (routes[key]?.total || 0), data.image_generation?.total || 0) } };
|
|
644
|
+
},
|
|
645
|
+
});
|
|
646
|
+
}
|
|
584
647
|
} catch (e) {
|
|
585
648
|
LOGGING.setTerminalSink(null);terminalConsole?.cleanup();
|
|
586
649
|
console.error(status("err", e.message));
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -212,7 +212,7 @@ boundary, not a plugin framework, daemon, IPC protocol or package split.
|
|
|
212
212
|
The HTTP dispatch boundary rejects browser Origin-bearing inference requests
|
|
213
213
|
before body admission, credential use or provider dispatch; native LAN opt-in is unchanged.
|
|
214
214
|
|
|
215
|
-
|
|
215
|
+
Manual package installation is an explicit management operation in `package-update.mjs`,
|
|
216
216
|
not part of inference or optional client integration. Windows uses the system
|
|
217
217
|
command interpreter only for the fixed `npm.cmd` installer command; stable-tag
|
|
218
218
|
validation remains upstream of launch. macOS/Linux use direct npm argv. There
|
|
@@ -231,7 +231,7 @@ The source lock retains exact versions/integrities without binding smol-toml to
|
|
|
231
231
|
developer's corporate feed; omitted registry resolution is delegated to npm.
|
|
232
232
|
Readonly update preflight reports Node/npm, the running package and npm's selected
|
|
233
233
|
global target. A different target warns, but never changes PATH or prefix. Its
|
|
234
|
-
bounded npm probe is limited to explicit update and
|
|
234
|
+
bounded npm probe is limited to explicit update/full doctor commands and opted-in supervisor startup, never inference.
|
|
235
235
|
Its stdout/stderr are captured separately; npm configuration warnings do not
|
|
236
236
|
leak into doctor output. The real installer's inherited streams are unchanged.
|
|
237
237
|
After installation, the updater verifies bounded package metadata at that same
|
|
@@ -533,7 +533,7 @@ Byte-weighted request admission is not a simultaneous-stream limit. The 1.2.0 lo
|
|
|
533
533
|
and no-Node bootstraps. It bounds downloads/decompression, verifies the exact
|
|
534
534
|
release package and checksum, backs up only this package/commands under an
|
|
535
535
|
exclusive lock, restores on failure and validates the version/sharp/broker.
|
|
536
|
-
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
|
|
536
|
+
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
537
|
source choice, named npm-policy probes and fixed platform launch arguments;
|
|
538
538
|
verified filenames enter cmd.exe, while paths enter cwd. Private-runtime commands
|
|
539
539
|
are regenerated before committing a successful update. This provides error
|
|
@@ -701,3 +701,70 @@ backup during native reconciliation, before the config transaction commits.
|
|
|
701
701
|
Unknown/partial caches are not claimed. On config commit failure, the old cache
|
|
702
702
|
is restored only if the client has not created a new cache. This is a bounded
|
|
703
703
|
schema migration, not a periodic cache purge or a credential/session reset.
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
## Optional supervised nightly updates
|
|
707
|
+
|
|
708
|
+
`nightly-update.mjs` owns local-window/version eligibility, bounded public Release
|
|
709
|
+
lookup, policy-preserving staging and real runtime checks. It reuses
|
|
710
|
+
`release-install.mjs` package transactions, checksum checks and private command
|
|
711
|
+
writers. Rollback restores launcher symlinks by link text; it never follows a
|
|
712
|
+
relative symlink from its backup location. Completed rollback is idempotent and
|
|
713
|
+
cleanup errors do not conceal a successful restoration.
|
|
714
|
+
|
|
715
|
+
`service-supervisor.mjs` is loaded by normal `start` only after an explicit saved
|
|
716
|
+
opt-in and recognized/writable npm preflight. It keeps a foreground controller
|
|
717
|
+
and one active gateway worker, briefly warming a second candidate on an internal
|
|
718
|
+
loopback port. It stages beside the active immutable tree and serializes
|
|
719
|
+
one version transition. The controller carries no request-forwarding hot path.
|
|
720
|
+
Manual startup and all other commands retain their existing process model.
|
|
721
|
+
An unsupported copy/verification setup falls back to ordinary startup.
|
|
722
|
+
|
|
723
|
+
`service-worker.mjs` is the version-one private process protocol. It is enabled
|
|
724
|
+
only on an inherited IPC channel plus the worker marker, not by a WebUI request.
|
|
725
|
+
It exposes bounded inspect/quiesce/import/release/promote/resume/commit operations
|
|
726
|
+
to its parent and
|
|
727
|
+
forwards preference changes and notices; notices use the worker's existing
|
|
728
|
+
terminal sink. Source/model defaults, client files and sign-in fingerprints are
|
|
729
|
+
compared around the transition. Maintenance startup defers client synchronizers,
|
|
730
|
+
skips interactive login and client writes, checks selected GitHub discovery
|
|
731
|
+
without inference, and imports history before taking the original public port.
|
|
732
|
+
The old instance retains its provider state until the warmed replacement passes
|
|
733
|
+
validation; rollback resumes it rather than rebuilding a cold directory. GitHub
|
|
734
|
+
identity comparisons ignore refreshed verification timestamps.
|
|
735
|
+
|
|
736
|
+
`response-history.mjs` validates complete acyclic source-namespaced history and
|
|
737
|
+
its byte/entry budget before publication. `image-references.mjs` validates
|
|
738
|
+
provider-scoped image handles before importing its bounded LRU. `api-secrets.mjs` permits private transfer only of cached references still allowed
|
|
739
|
+
by the unchanged configuration. Those plaintext in-memory values remain confined
|
|
740
|
+
to inherited IPC; they are never written to a checkpoint, UI snapshot or log. The snapshot is consumed and released during
|
|
741
|
+
private handoff; no plaintext disk checkpoint or key-store rewrite is added.
|
|
742
|
+
`optional-routes.mjs` also counts pending optional requests so management/sign-in
|
|
743
|
+
work cannot be mistaken for an idle gateway. Ordinary shutdown drains HTTP
|
|
744
|
+
requests before closing providers. User stop/disconnect takes precedence over
|
|
745
|
+
updates; fallback is attempted once, not an unbounded restart loop.
|
|
746
|
+
|
|
747
|
+
The schema and failure limits, local schedule, install-owner checks and recovery
|
|
748
|
+
boundaries are normative in REFERENCE.md. Future patch releases accepted by this
|
|
749
|
+
channel must preserve private protocol v1 and the native client contracts.
|
|
750
|
+
|
|
751
|
+
## Incremental Web rendering and cold-start sharing
|
|
752
|
+
|
|
753
|
+
`dashboard/view-boundary.js` contains optional view failures without introducing
|
|
754
|
+
a plugin runtime. Only a fixed set of view methods is wrapped; a failed view
|
|
755
|
+
keeps the latest arguments per method for explicit retry. Shared refresh
|
|
756
|
+
generation checks and request cancellation remain in `refresh.js`.
|
|
757
|
+
`dashboard/flow.js` retains active detail rows by request ID. CSS alone rotates
|
|
758
|
+
the theme ring, with visibility/staleness and reduced-motion gates.
|
|
759
|
+
|
|
760
|
+
`dashboard.mjs` snapshots the static bundle lazily, checks its package version,
|
|
761
|
+
stamps HTML resource URLs, and computes byte-specific ETags once. Sensitive and
|
|
762
|
+
dynamic endpoints remain uncached. No shell/provider dependency is added to
|
|
763
|
+
rendering, and no content-bearing response is reused across credential scopes.
|
|
764
|
+
|
|
765
|
+
`api-secrets.mjs` joins concurrent reads of one reference and prevents late
|
|
766
|
+
reads from republishing after clear/set/remove. `providers/api.mjs` reuses the
|
|
767
|
+
existing cancellation-aware single-flight for transport initialization: one
|
|
768
|
+
waiter cannot abort another, while the last cancellation or provider closure
|
|
769
|
+
stops the shared setup. Existing native stream validation, byte admission,
|
|
770
|
+
connection reuse, bounded metrics/logging and pinned source semantics remain.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -1302,7 +1302,7 @@ Unknown support prevents an explicitly requested exception from starting.
|
|
|
1302
1302
|
For an older updater that still requires Git, install the Release tarball directly:
|
|
1303
1303
|
|
|
1304
1304
|
```sh
|
|
1305
|
-
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
1305
|
+
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.22/codex-copilot-dx-1.2.22.tgz
|
|
1306
1306
|
# Windows PowerShell: use npm.cmd instead of npm.
|
|
1307
1307
|
```
|
|
1308
1308
|
|
|
@@ -1806,7 +1806,7 @@ Set `CCDX_LOG_PATH=1` to record diagnostic logs independently of quiet terminal
|
|
|
1806
1806
|
|
|
1807
1807
|
Long computer-use sessions can accumulate screenshots that are sent again on later turns. This can increase local preparation time, upstream handshake latency, and the chance of a `413 Payload Too Large` response.
|
|
1808
1808
|
|
|
1809
|
-
The response-history cache is process-local and byte/entry bounded.
|
|
1809
|
+
The response-history cache is process-local and byte/entry bounded. Ordinary adapter restarts discard it; verified opt-in nightly handoff is the exception described below. Without such a handoff, a `previous_response_id` stored only in that process becomes unavailable. CCDX does not persist conversation history to disk. Near-limit status diagnostics report the largest tree and actual lookup misses, but do not recover an already evicted ID or change the cache budget. Clients can still submit explicit history in the request body, subject to the same limits.
|
|
1810
1810
|
|
|
1811
1811
|
CCDX attempts to downsample inline base64 images to model-appropriate pixel bounds, with a 2048 px long-edge fallback, and initially encodes them as WebP quality 82. It never replaces an image with a larger encoding and uses one global concurrency limit across direct images and function/custom-tool outputs. GIFs and non-inline references are not re-encoded. An encoding/decode failure keeps the original image; the final request-byte limit still applies.
|
|
1812
1812
|
|
|
@@ -1948,3 +1948,101 @@ The Responses WebSocket protocol is not implemented by CCDX. Upgrade requests
|
|
|
1948
1948
|
are refused promptly so supported native clients can fall back to HTTP/SSE.
|
|
1949
1949
|
This is tested separately from model-directory and provider-identity behavior;
|
|
1950
1950
|
SSE events are not relabeled as a WebSocket protocol.
|
|
1951
|
+
|
|
1952
|
+
|
|
1953
|
+
### Nightly updates (opt-in)
|
|
1954
|
+
|
|
1955
|
+
Available from 1.2.22 after one manual upgrade. Settings → Version & updates →
|
|
1956
|
+
Update overnight writes the boolean `nightly_updates`, false when absent. Enabling
|
|
1957
|
+
it requires a normal CCDX restart; disabling it cancels pending automatic work in
|
|
1958
|
+
a supervised service. Management-only `ccdx web` never installs updates. The risk
|
|
1959
|
+
text explains that automatic installation/restart can affect conversation
|
|
1960
|
+
continuation. The feature does not promise zero downtime or infallible rollback.
|
|
1961
|
+
|
|
1962
|
+
Only an owned, writable npm installation with recognized command launchers can
|
|
1963
|
+
use the supervisor. Standard execution stays unchanged when disabled. When enabled,
|
|
1964
|
+
a foreground parent runs the gateway from an immutable private package tree;
|
|
1965
|
+
Ctrl+C stops both, and no launchd/systemd/Windows service or boot task is installed.
|
|
1966
|
+
Stopping CCDX, sleeping or powering off does not start a separate updater. After
|
|
1967
|
+
a long observation gap, a new ten-minute idle interval is required.
|
|
1968
|
+
|
|
1969
|
+
The parent observes bounded local state once a minute. A release check occurs at
|
|
1970
|
+
most once per local calendar day, within 00:00–04:00, after ten observed idle
|
|
1971
|
+
minutes. The new version must be a stable patch in the same major/minor series
|
|
1972
|
+
and have been published at least 24 hours earlier. No prerelease or automatic
|
|
1973
|
+
minor/major migration is accepted. Active inference, image work, configuration
|
|
1974
|
+
operations, discovery or sign-in defer the update. New work during preparation
|
|
1975
|
+
also defers it. Checks do not invoke models.
|
|
1976
|
+
|
|
1977
|
+
Preparation uses the official pinned GitHub Release tarball and checksum, an
|
|
1978
|
+
independent npm prefix, the configured registry/proxy/CA/TLS/offline policy and
|
|
1979
|
+
ignored lifecycle scripts. Existing private-runtime launchers are regenerated;
|
|
1980
|
+
custom launchers are not silently claimed. No Git, new Node installation,
|
|
1981
|
+
permission override, certificate change or public-registry fallback is added.
|
|
1982
|
+
A policy refusal, unavailable dependency or runtime check failure leaves the
|
|
1983
|
+
current service running. The supported native broker is checked when already
|
|
1984
|
+
present in the original installation.
|
|
1985
|
+
|
|
1986
|
+
Before switching, the parent compares client/configuration fingerprints and
|
|
1987
|
+
authorized model/default selections, backs up the global package and commands,
|
|
1988
|
+
and validates the candidate on an internal loopback-only ephemeral listener while
|
|
1989
|
+
the current instance continues serving. Previously healthy selected sources must remain healthy, every previously
|
|
1990
|
+
published model must remain available, and defaults/credential scopes must match.
|
|
1991
|
+
Additional upstream models are allowed. API discovery publication and client
|
|
1992
|
+
writers are paused during this warmup. Only then is the old gateway quiesced.
|
|
1993
|
+
A bounded private IPC message transfers Responses
|
|
1994
|
+
history, source-scoped parent links/opaque items, image-edit references and
|
|
1995
|
+
already-cached API keys limited to unchanged configured references.
|
|
1996
|
+
Conversation payloads, image references and cached keys are never written to a
|
|
1997
|
+
handoff file or diagnostics. Ordinary process-local counters begin a new run;
|
|
1998
|
+
retained usage files remain available.
|
|
1999
|
+
The combined serialized state is limited to 64 MiB; oversized/busy state defers
|
|
2000
|
+
the update without eviction. New requests during the brief switching interval
|
|
2001
|
+
can receive a temporary failure with `Retry-After: 1`.
|
|
2002
|
+
|
|
2003
|
+
The warmed replacement imports state before taking over the same main port. Its
|
|
2004
|
+
maintenance startup preserves client configuration, skips interactive GitHub
|
|
2005
|
+
login, and opens neither browser nor client. Model/default selections and
|
|
2006
|
+
configuration fingerprints must match before it accepts normal traffic. Failed
|
|
2007
|
+
startup, discovery or a mismatched candidate leaves the original instance
|
|
2008
|
+
alive. A failed port/prediction handover attempts package rollback and resumes
|
|
2009
|
+
that same instance with its original caches. Cleanup of a retired runtime is
|
|
2010
|
+
best-effort; pending cleanup suspends further automatic transitions. The old
|
|
2011
|
+
process is retired only
|
|
2012
|
+
after the replacement has acknowledged acceptance. A deliberate Ctrl+C
|
|
2013
|
+
never starts another worker. Unexpected later worker exits are reported once;
|
|
2014
|
+
this is not a general crash-respawn mechanism.
|
|
2015
|
+
|
|
2016
|
+
The private `nightly-update-state.json` beside settings stores only the attempted
|
|
2017
|
+
local day and paused version. Installed candidates that fail verification are
|
|
2018
|
+
not repeatedly attempted; a newer version or explicit manual update is needed.
|
|
2019
|
+
Unreadable records pause automatic updates without stopping the gateway. A
|
|
2020
|
+
failed package rollback or failed restoration can require manual recovery;
|
|
2021
|
+
Settings retains the full platform installation commands.
|
|
2022
|
+
|
|
2023
|
+
### Web resilience and resource versions
|
|
2024
|
+
|
|
2025
|
+
Optional status/usage/animation views contain local initialization/render errors,
|
|
2026
|
+
retain the surrounding shell and expose a local retry. Retry replays only the
|
|
2027
|
+
latest bounded call state per view method. Network errors retain their existing
|
|
2028
|
+
last-successful snapshots and explicit unknown/error status. Request-flow detail
|
|
2029
|
+
rows are keyed and updated in place, retaining selection and DOM identity.
|
|
2030
|
+
|
|
2031
|
+
The flow atom's thin ring is static while idle and rotates once per five seconds
|
|
2032
|
+
while fresh active requests are observed, including waits/retries. The atom itself
|
|
2033
|
+
does not rotate; counts do not accelerate the ring. Hidden/stale views stop it,
|
|
2034
|
+
and reduced motion disables rotation. Existing curves, tables, palettes,
|
|
2035
|
+
client identification and authorization remain unchanged.
|
|
2036
|
+
|
|
2037
|
+
Static dashboard bytes are snapshotted together on first use and reused by the
|
|
2038
|
+
process. HTML remains `no-store` and stamps script/style URLs with the service
|
|
2039
|
+
version. Other assets use content-derived ETags and `no-cache` revalidation;
|
|
2040
|
+
matching validators return 304. A mismatched version query returns 409 rather
|
|
2041
|
+
than mixing resources, requiring a page reload. If the installed package changed
|
|
2042
|
+
before a coherent bundle could be loaded, the optional page fails explicitly;
|
|
2043
|
+
inference remains separate. Protected JSON/account/settings routes stay
|
|
2044
|
+
`no-store`. No API-body caching, compression worker or new dependency is added.
|
|
2045
|
+
|
|
2046
|
+
`CCDX_SUPERVISED_SERVICE` is an internal inherited worker marker. It is used only
|
|
2047
|
+
with a private parent IPC channel; do not set it as a user preference. It grants
|
|
2048
|
+
no network action and is not a replacement for the saved nightly-update opt-in.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-copilot-dx",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.22",
|
|
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",
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
"test": "node --test",
|
|
43
43
|
"test:smoke": "node scripts/offline-smoke.mjs && node scripts/sse-idle-replay.mjs",
|
|
44
44
|
"test:package": "node scripts/package-lifecycle-smoke.mjs",
|
|
45
|
+
"test:nightly-package": "node scripts/nightly-package-replay.mjs",
|
|
45
46
|
"test:e2e": "bash test/e2e.sh",
|
|
46
47
|
"bench": "node scripts/benchmark.mjs",
|
|
47
48
|
"bench:payload": "node scripts/benchmark.mjs --large-payload",
|
package/src/account-tools.mjs
CHANGED
|
@@ -116,6 +116,6 @@ export function createAccountTools({ home = os.homedir(), env = process.env, fet
|
|
|
116
116
|
online = null;checkedAt = null;checkedFingerprint = "";operation = null;await onChanged();
|
|
117
117
|
return snapshot();
|
|
118
118
|
}
|
|
119
|
-
return { snapshot, check, start, cancel, logout, wait: async () => { await operation?.task;return snapshot(); },
|
|
119
|
+
return { snapshot, check, start, cancel, logout, busy: () => Boolean(checkFlight || operation && ["starting", "authorizing", "verifying"].includes(operation.state)), wait: async () => { await operation?.task;return snapshot(); },
|
|
120
120
|
async reload() { await onChanged();return snapshot(); }, dispose() { operation?.controller.abort(); } };
|
|
121
121
|
}
|
package/src/adapter.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import { createRequestId, runWithRequestContext, currentRequestContext } from ".
|
|
|
12
12
|
import { requestApplication } from "./request-application.mjs";
|
|
13
13
|
import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
|
|
14
14
|
import { status } from "./status.mjs";
|
|
15
|
+
import { exportResponseHistory, importResponseHistory } from "./response-history.mjs";
|
|
15
16
|
import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
|
|
16
17
|
import { ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH } from "./running-adapter.mjs";
|
|
17
18
|
import { createManagementHandler, isManagementRoute } from "./management-routes.mjs";
|
|
@@ -264,6 +265,9 @@ export function createAdapterHandler(options = {}) {
|
|
|
264
265
|
return providerHandlers.get(provider);
|
|
265
266
|
}
|
|
266
267
|
const dispatch = async (req, res, pathname) => {
|
|
268
|
+
if (options.isDraining?.() && ![ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH].includes(pathname)) {
|
|
269
|
+
res.setHeader("Retry-After", "1");sendJsonError(res, httpError("CCDX is switching versions; retry shortly", 503));return;
|
|
270
|
+
}
|
|
267
271
|
if (pathname.startsWith("/anthropic/")) {
|
|
268
272
|
if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
|
|
269
273
|
|| Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Claude requires native local clients", 403));return; }
|
|
@@ -482,13 +486,20 @@ export function createAdapterHandler(options = {}) {
|
|
|
482
486
|
}
|
|
483
487
|
};
|
|
484
488
|
handler.snapshot = statusSnapshot;
|
|
489
|
+
handler.busy = () => optionalRoutes.busy() || options.providerRuntime?.busy?.() === true;
|
|
490
|
+
handler.exportState = () => ({ version: 1, history: exportResponseHistory(), optional: optionalRoutes.exportState() });
|
|
491
|
+
handler.importState = async state => {
|
|
492
|
+
if (state?.version !== 1) throw new Error("Unsupported service-state version");
|
|
493
|
+
importResponseHistory(state.history);await optionalRoutes.importState(state.optional);
|
|
494
|
+
};
|
|
485
495
|
handler.cleanup = () => optionalRoutes.dispose();
|
|
486
496
|
return handler;
|
|
487
497
|
}
|
|
488
498
|
|
|
489
499
|
// Public server entry point.
|
|
490
500
|
|
|
491
|
-
export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
|
|
501
|
+
export async function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
|
|
502
|
+
const handoffState = options.handoffState;options = { ...options };delete options.handoffState;
|
|
492
503
|
const ownsTerminalActivity = !Object.hasOwn(options, "terminalActivity");
|
|
493
504
|
const terminalActivity = ownsTerminalActivity
|
|
494
505
|
? createTerminalActivityIndicator({ theme: options.terminalAnimationTheme })
|
|
@@ -496,11 +507,15 @@ export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
|
|
|
496
507
|
const handler = createAdapterHandler({ ...options, terminalActivity, imageMcpHostname: host });
|
|
497
508
|
const server = http.createServer(handler);
|
|
498
509
|
server.ccdxSnapshot = handler.snapshot;
|
|
510
|
+
server.ccdxBusy = handler.busy;
|
|
511
|
+
server.ccdxExportState = handler.exportState;
|
|
512
|
+
server.ccdxImportState = handler.importState;
|
|
513
|
+
if (handoffState) await handler.importState(handoffState);
|
|
499
514
|
const cleanupTerminalActivity = () => {
|
|
500
515
|
if (ownsTerminalActivity) terminalActivity?.cleanup?.();
|
|
501
516
|
handler.cleanup?.();
|
|
502
517
|
};
|
|
503
|
-
server.
|
|
518
|
+
server.on("close", cleanupTerminalActivity);
|
|
504
519
|
|
|
505
520
|
server.on("upgrade", (req, socket) => {
|
|
506
521
|
// The responses_websockets upgrade expects a server-push protocol that this
|