codex-copilot-dx 0.9.36 → 0.9.38
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 +3 -3
- package/bin/cli.mjs +1 -1
- package/docs/ARCHITECTURE.md +32 -2
- package/docs/REFERENCE.md +84 -6
- package/package.json +1 -1
- package/src/cli-options.mjs +9 -5
- package/src/cli-status.mjs +2 -0
- package/src/client-integration.mjs +49 -6
- package/src/codex-client-doctor.mjs +3 -0
- package/src/native-prediction-environment.mjs +59 -0
- package/src/native-prediction-fix.mjs +1 -1
- package/src/native-prediction-recovery.mjs +2 -0
- package/src/native-prediction-state.mjs +17 -0
- package/src/native-prediction.mjs +20 -21
- package/src/network-bypass.mjs +79 -0
- package/src/network-route.mjs +14 -30
- package/src/package-update.mjs +45 -4
- package/src/startup-ui.mjs +4 -2
package/README.md
CHANGED
|
@@ -39,7 +39,7 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
|
|
|
39
39
|
| `ccdx usage` | Recorded tokens and upstream prompt-cache hit rate |
|
|
40
40
|
| `ccdx auto-review-model` | Select model, then reasoning effort; `0` follows client |
|
|
41
41
|
| `ccdx animation` | Preview and select terminal animation |
|
|
42
|
-
| `ccdx prediction fix` |
|
|
42
|
+
| `ccdx prediction fix` | Recheck system routing and repair enabled predictions; report required restarts |
|
|
43
43
|
| `ccdx cache --limit 128` | Set the history-cache budget in MiB |
|
|
44
44
|
| `ccdx cache --clean` | Clear the rebuildable image-transform cache |
|
|
45
45
|
| `ccdx limits --decoded 256` | Set the decoded request-body budget; restart to apply |
|
|
@@ -86,11 +86,11 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
|
|
|
86
86
|
for the API. Inference rejects browser Origin headers; native clients remain supported. Diagnostic errors may contain sensitive upstream text.
|
|
87
87
|
|
|
88
88
|
Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`.
|
|
89
|
-
Updates install the exact stable tag; dependencies still use npm's configured registry. Lookup errors identify HTTP refusal, timeout, network failure or invalid redirects.
|
|
89
|
+
Updates install the exact stable tag; 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.
|
|
90
90
|
Updates warn about mismatched npm targets without changing PATH/prefix and verify the installed target version (exact tag for GitHub). Restart the adapter separately. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
|
|
91
91
|
Recent errors separate HTTP and model failures. HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged.
|
|
92
92
|
|
|
93
|
-
The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown.
|
|
93
|
+
The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown. See [architecture boundaries](docs/ARCHITECTURE.md) for separate inference, integration, image and management ownership.
|
|
94
94
|
|
|
95
95
|
See 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.
|
|
96
96
|
|
package/bin/cli.mjs
CHANGED
|
@@ -228,7 +228,7 @@ if (CLI.command === "auto-review-model") {
|
|
|
228
228
|
if (CLI.command === "update") {
|
|
229
229
|
try {
|
|
230
230
|
const { runPackageUpdateCommand } = await import("../src/package-update.mjs");
|
|
231
|
-
await runPackageUpdateCommand({ commandName: CLI_NAME, source: CLI.updateSource });
|
|
231
|
+
await runPackageUpdateCommand({ commandName: CLI_NAME, source: CLI.updateSource, allowRemote: CLI.allowRemote });
|
|
232
232
|
process.exit(0);
|
|
233
233
|
} catch (e) {
|
|
234
234
|
console.error(status("err", e.message));
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -26,6 +26,17 @@ command interpreter only for the fixed `npm.cmd` installer command; stable-tag
|
|
|
26
26
|
validation remains upstream of launch. macOS/Linux use direct npm argv. There
|
|
27
27
|
is no generic shell runner or package-manager framework, and npm's configured
|
|
28
28
|
registry/proxy environment remains owned by the user.
|
|
29
|
+
Readonly npm policy discovery is update-only and uses the same global context as
|
|
30
|
+
the installer, not an unrelated working project's `.npmrc`. It queries version,
|
|
31
|
+
`allow-remote` and registry only, never the complete credential-bearing config.
|
|
32
|
+
Default installer argv preserves the saved download policy. The boolean
|
|
33
|
+
`--allow-remote` opt-in adds one fixed permission argument only when supported;
|
|
34
|
+
it applies to that installation's entire dependency tree, not selected hosts.
|
|
35
|
+
Unknown support fails before an explicitly requested override. Installation
|
|
36
|
+
streams remain inherited; conditional failure guidance is not an assertion that
|
|
37
|
+
every nonzero exit is a policy error. There is no automatic retry or policy write.
|
|
38
|
+
The source lock retains exact versions/integrities without binding smol-toml to a
|
|
39
|
+
developer's corporate feed; omitted registry resolution is delegated to npm.
|
|
29
40
|
Readonly update preflight reports Node/npm, the running package and npm's selected
|
|
30
41
|
global target. A different target warns, but never changes PATH or prefix. Its
|
|
31
42
|
bounded npm probe is limited to explicit update and full doctor commands.
|
|
@@ -44,8 +55,9 @@ Native prediction has a separate loopback transport and an isolated HTTPS agent.
|
|
|
44
55
|
Only its two selected hosts use the App-specific route. Non-configuration requests
|
|
45
56
|
on those hosts are forwarded unchanged. The bridge does not replace Copilot or
|
|
46
57
|
image-provider networking, modify client program files, or install system trust.
|
|
47
|
-
Static upstream proxy routes and bypass rules are preserved.
|
|
48
|
-
|
|
58
|
+
Static upstream proxy routes and bypass rules are preserved. IPv4/IPv6 CIDRs
|
|
59
|
+
match URL IP literals, without DNS. macOS dynamic PAC/WPAD remains unsupported
|
|
60
|
+
and is reported rather than discarded.
|
|
49
61
|
The Windows adapter isolates registration, process, proxy and NTFS
|
|
50
62
|
interfaces in `native-prediction-windows.mjs`. The bridge, overlay, model selection
|
|
51
63
|
and lifecycle remain shared. Windows discovery requires verified registration
|
|
@@ -98,6 +110,24 @@ enforces loopback/Host/Origin/method/media/body boundaries before dispatch. No n
|
|
|
98
110
|
inference-path work, watcher, runtime dependency, forced App restart or unverified
|
|
99
111
|
hot-attachment mechanism is introduced.
|
|
100
112
|
|
|
113
|
+
`network-bypass.mjs` compiles static host/IP/port/CIDR rules. The exact pure
|
|
114
|
+
address/matching functions are embedded in the PAC and called by Node, with no
|
|
115
|
+
DNS or system calls. Matching IP literals instead of resolving domains preserves
|
|
116
|
+
Chromium's manual bypass semantics and SOCKS remote DNS. Existing domain matching
|
|
117
|
+
and per-protocol source priority are retained; unused lower-priority static proxy
|
|
118
|
+
addresses do not override selected routes.
|
|
119
|
+
|
|
120
|
+
`native-prediction-environment.mjs` owns bounded, read-only discovery for the
|
|
121
|
+
optional feature. Only enabled startup, explicit fix and failed-listener recovery
|
|
122
|
+
read system policy. Private comparison hashes include effective proxy settings
|
|
123
|
+
and Node trust inputs; public snapshots contain source/type/counts and diagnostic
|
|
124
|
+
states, not addresses, credentials, file paths or hashes. Trust-file inspection is
|
|
125
|
+
diagnostic, not loading or modifying certificate trust. Changed trust inputs need
|
|
126
|
+
a service restart. A changed network snapshot reuses the port but marks a running
|
|
127
|
+
App for PAC reload until it is observed closed or with a different readable PID.
|
|
128
|
+
Failed rechecks preserve the existing bridge and return a non-success result.
|
|
129
|
+
There is no new watcher, global environment owner or inference/image dispatcher.
|
|
130
|
+
|
|
101
131
|
`startup-ui.mjs` is pure terminal presentation: a static A atom, aligned checks
|
|
102
132
|
and the common new/reused-service footer. It depends only on terminal/status
|
|
103
133
|
utilities, not on inference or platform probes. The CLI feeds existing lifecycle
|
package/docs/REFERENCE.md
CHANGED
|
@@ -140,15 +140,21 @@ remain in memory, are never included in PAC responses or diagnostics, and are
|
|
|
140
140
|
sent only to the proxy. TLS verification remains enabled for both proxy and target.
|
|
141
141
|
Other App domains keep the resolved original route; if a bridge fails, its PAC
|
|
142
142
|
fallback uses that route rather than adding an unrequested direct connection.
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
143
|
+
Bypass lists support host/domain patterns, optional ports and IPv4/IPv6 CIDRs.
|
|
144
|
+
CIDRs match only IP literals in URLs, not the resolved addresses of domain names,
|
|
145
|
+
following Chromium's manual bypass semantics. No DNS request is added to proxy
|
|
146
|
+
selection, and SOCKS remote name resolution is not replaced by local resolution.
|
|
147
|
+
IPv6 CIDRs use unbracketed notation (`2001:db8::/32`); IPv6 host/port rules use
|
|
148
|
+
brackets (`[2001:db8::1]:443`). Malformed rules fail explicitly without echoing
|
|
149
|
+
their contents. Node and the generated PAC use the same matcher. Legal unused
|
|
150
|
+
exceptions do not block a direct environment or change it into a proxied route.
|
|
146
151
|
|
|
147
152
|
macOS dynamic PAC/WPAD remains unsupported and is not overwritten. Windows
|
|
148
153
|
automatic routing is opt-in and requires the native worker; a failed worker
|
|
149
154
|
closes its optional bridge while core inference continues. Restart CCDX and Codex
|
|
150
|
-
after changing
|
|
151
|
-
watcher.
|
|
155
|
+
after changing company PAC contents at an unchanged URL; this is not a live
|
|
156
|
+
network-policy watcher. Static/system-setting changes can be rechecked by
|
|
157
|
+
`prediction fix` as described below. Native composer behavior was verified on one Windows machine. Its
|
|
152
158
|
observed upstream route was direct; arbitrary company PAC, integrated-authentication
|
|
153
159
|
and client-certificate policies are not claimed as live-tested. A non-default `CODEX_API_BASE_URL` is
|
|
154
160
|
also preserved and reported as a custom-route conflict; setting it to the normal
|
|
@@ -212,13 +218,39 @@ overlay switch still observes explicit on/off changes independently.
|
|
|
212
218
|
|
|
213
219
|
`ccdx prediction fix` asks the running adapter for one explicit repair, without
|
|
214
220
|
starting another core service or forcibly restarting Codex. Disabled predictions
|
|
215
|
-
remain off. Healthy/current bridges are kept; a failed bridge or changed App identity
|
|
221
|
+
remain off. Healthy/current bridges with unchanged environments are kept; a failed bridge or changed App identity
|
|
216
222
|
reuses the saved port, certificate and verified profile. Compatibility, certificate,
|
|
217
223
|
company proxy and port-ownership checks are not bypassed. Certificates are not renewed
|
|
218
224
|
by fix; setup problems can still require a normal closed-App `prediction on` action.
|
|
219
225
|
An explicit successful recreation starts a fresh three-attempt automatic recovery
|
|
220
226
|
lifecycle; it is not an automatic retry loop for initialization failures.
|
|
221
227
|
|
|
228
|
+
Since `0.9.37`, fix rechecks system proxy settings and compares the effective
|
|
229
|
+
network snapshot before replacing a listener. A changed valid snapshot recreates
|
|
230
|
+
only the optional bridge on its saved port, retaining certificate/profile checks.
|
|
231
|
+
A running App may cache its earlier PAC, so `needs_app_relaunch` (exit 1) remains
|
|
232
|
+
until inspection observes it closed or with a different readable main PID. No App
|
|
233
|
+
is forced closed. A failed recheck reports `environment_preserved` (exit 1) and
|
|
234
|
+
keeps the previous bridge; this is not a successful application of the new policy.
|
|
235
|
+
|
|
236
|
+
Environment variables belong to the running service's process. A new terminal's
|
|
237
|
+
variables are not copied into it by fix. Node trust inputs, including
|
|
238
|
+
`NODE_EXTRA_CA_CERTS`, are startup settings, not a hot-reload interface. Changed
|
|
239
|
+
inputs or changed readable extra-CA content report `needs_service_restart` (exit 1)
|
|
240
|
+
without recreating certificates or claiming new trust was loaded. Extra-CA files
|
|
241
|
+
are inspected read-only up to 1 MiB; `configured` means readable PEM certificates,
|
|
242
|
+
not proof that they were loaded or trusted. Missing/invalid/oversized bundles are
|
|
243
|
+
reported diagnostically; no root is imported and TLS verification remains required.
|
|
244
|
+
|
|
245
|
+
Startup, `status`, `prediction status/fix` and a running-adapter `doctor` use the
|
|
246
|
+
same sanitized environment summary: source/type, exception/CIDR counts, trust-file
|
|
247
|
+
state and adaptation/restart status. They do not print proxy credentials, internal
|
|
248
|
+
rules, CA paths or private comparison hashes. Status/doctor reuse runtime evidence
|
|
249
|
+
instead of spawning another proxy probe. Disabled predictions perform no prediction
|
|
250
|
+
environment discovery, CA-file inspection or worker/timer startup. Existing App
|
|
251
|
+
paths, user settings, npm/PATH/prefix, permissions and terminal policies remain
|
|
252
|
+
owned by their existing modules; there is no global auto-configuration framework.
|
|
253
|
+
|
|
222
254
|
The command checks the adapter's advertised `prediction-fix-v1` capability before
|
|
223
255
|
posting bounded JSON to the native-loopback-only `/_ccdx/prediction/fix` endpoint.
|
|
224
256
|
Browser Origin headers, remote peers and non-JSON bodies are refused. A repair does
|
|
@@ -646,6 +678,52 @@ displayed before waiting for any remaining check budget.
|
|
|
646
678
|
|
|
647
679
|
GitHub is the package source, not a replacement for the npm installer. Dependencies such as `sharp` may still need the configured npm registry during an explicit update; use a company-approved mirror/cache where required. GitHub updates do not promise an entirely registry-free installation.
|
|
648
680
|
|
|
681
|
+
Since `0.9.38`, update reads the npm version and named global `allow-remote` and
|
|
682
|
+
registry settings using bounded probes. It never reads the full configuration or
|
|
683
|
+
prints registry credentials. The global context matches `npm install --global`;
|
|
684
|
+
an unrelated project's `.npmrc` cannot silently grant update permission. Old npm
|
|
685
|
+
versions without this restriction do not receive an unsupported option. Failed
|
|
686
|
+
policy discovery does not block an ordinary installation; explicitly requesting
|
|
687
|
+
an override with unknown support fails before installation.
|
|
688
|
+
|
|
689
|
+
npm 12 normally sets `allow-remote=none`. A company registry may return a tarball
|
|
690
|
+
URL on a different origin/path, which can trigger `EALLOWREMOTE` even for a named
|
|
691
|
+
dependency such as sharp. The default update does not weaken this policy. When
|
|
692
|
+
the installation fails under a restrictive policy, CCDX gives conditional guidance
|
|
693
|
+
to check npm's actual error; it does not label every failure a remote-policy error.
|
|
694
|
+
|
|
695
|
+
Only if permitted by company policy and you trust the package/dependency tree,
|
|
696
|
+
grant URL downloads for one explicit update:
|
|
697
|
+
|
|
698
|
+
```sh
|
|
699
|
+
ccdx update github --allow-remote
|
|
700
|
+
# Or, for the configured npm registry:
|
|
701
|
+
ccdx update npm --allow-remote
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
The option permits URL dependencies throughout that one installation, including
|
|
705
|
+
transitive dependencies. It is **not** an allowlist for one registry or tarball
|
|
706
|
+
host. It neither changes `.npmrc`/registry/proxy/prefix nor automatically retries
|
|
707
|
+
the failed install. npm still enforces package integrity and its other policies;
|
|
708
|
+
this is not permission to run every package script. Windows uses the same fixed
|
|
709
|
+
system `cmd.exe` launch; use `ccdx.cmd` if PowerShell blocks `.ps1` shims.
|
|
710
|
+
|
|
711
|
+
An older CCDX executable cannot gain this option before it is upgraded. To
|
|
712
|
+
bootstrap `0.9.38` from a version that fails with `EALLOWREMOTE`, the equivalent
|
|
713
|
+
explicit per-install command is, only with the same policy/trust approval:
|
|
714
|
+
|
|
715
|
+
```sh
|
|
716
|
+
npm install -g --allow-git=all --allow-remote=all 'github:DaleXiao/codex-copilot-dx#v0.9.38'
|
|
717
|
+
# Windows PowerShell: use npm.cmd instead of npm.
|
|
718
|
+
```
|
|
719
|
+
|
|
720
|
+
Check `ccdx version`, then restart CCDX. This does not guarantee access through
|
|
721
|
+
every company mirror: authentication, offline/cache-only rules, unsynchronized
|
|
722
|
+
packages and administrator-enforced policies still apply. If URL permission
|
|
723
|
+
cannot be granted, the registry must expose compatible allowed tarball URLs;
|
|
724
|
+
CCDX does not bypass that boundary. The source lock pins versions and integrity
|
|
725
|
+
without a developer-specific corporate smol-toml URL.
|
|
726
|
+
|
|
649
727
|
If a configured npm mirror has not synchronized the current release yet, use the GitHub source. A running adapter keeps its loaded version until it is stopped and restarted.
|
|
650
728
|
|
|
651
729
|
## Diagnostics
|
package/package.json
CHANGED
package/src/cli-options.mjs
CHANGED
|
@@ -277,14 +277,18 @@ export function parseCliArgs(args = []) {
|
|
|
277
277
|
return baseCommand("auto-review-model");
|
|
278
278
|
}
|
|
279
279
|
if (command === "update") {
|
|
280
|
-
|
|
281
|
-
|
|
280
|
+
const permission = rest.filter(value => value === "--allow-remote");
|
|
281
|
+
if (permission.length > 1) throw new Error("--allow-remote may be specified only once");
|
|
282
|
+
const sources = rest.filter(value => value !== "--allow-remote");
|
|
283
|
+
if (sources.length > 1) unexpectedArgs(sources.slice(1));
|
|
284
|
+
const source = sources[0];
|
|
282
285
|
if (source && !new Set(["npm", "github", "gh"]).has(source)) {
|
|
283
286
|
throw new Error(`Update source must be npm or github: ${source}`);
|
|
284
287
|
}
|
|
285
288
|
return {
|
|
286
289
|
...baseCommand("update"),
|
|
287
290
|
updateSource: source === "gh" ? "github" : source,
|
|
291
|
+
allowRemote: permission.length === 1,
|
|
288
292
|
};
|
|
289
293
|
}
|
|
290
294
|
if (command === "doctor" || command === "--doctor") {
|
|
@@ -372,8 +376,8 @@ function topicHelp(name, topic) {
|
|
|
372
376
|
"image-status": `Usage:\n ${name} image-status\n\nShows provider configuration and locally advertised generation/editing tools without generating an image or exposing its API key.`,
|
|
373
377
|
"auto-review-model": `Usage:\n ${name} auto-review-model\n\nSelect a Responses model, then an advertised reasoning effort. Enter keeps the default/current choice; q cancels both steps without saving. Effort 0 follows the client (low when omitted). Settings apply only to Auto-review on the next request; no client patch or restart is required for adapters running 0.9.13 or newer.`,
|
|
374
378
|
"suggestion": `The CCDX prediction panel has been retired. Run ${name} suggestion off to safely remove unchanged CCDX registrations. This cleanup does not change native predictions; see ${name} prediction --help for that separate opt-in feature.`,
|
|
375
|
-
prediction: `Usage:\n ${name} prediction [status|on|off|fix]\n\nOptional native next-message predictions; off by default. macOS and Windows. Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup. Quit Codex before on/off, then restart ccdx. On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com. HTTPS on those hosts is decrypted locally; only prediction configuration is changed. No client program files, OS trust, account permissions, MCP or Hooks are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved. Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD
|
|
376
|
-
update: `Usage:\n ${name} update [npm|github]\n\nUpdates the global package from the configured npm registry or the latest stable GitHub release. With no source, an interactive terminal prompts for one. Windows uses system cmd.exe to run npm.cmd without changing PowerShell policy; use the .cmd entrypoint if scripts are blocked. GitHub installs require Git on PATH and dependencies may still use the configured npm registry. Restart the running adapter after installation.`,
|
|
379
|
+
prediction: `Usage:\n ${name} prediction [status|on|off|fix]\n\nOptional native next-message predictions; off by default. macOS and Windows. Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup. Quit Codex before on/off, then restart ccdx. On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com. HTTPS on those hosts is decrypted locally; only prediction configuration is changed. No client program files, OS trust, account permissions, MCP or Hooks are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved. Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD remains unsupported. Static IPv4/IPv6 CIDRs match URL IP literals without DNS. The bridge port persists across restarts/updates; a busy saved port disables only predictions. Launch/reuse checks the App's actual route; an older random or missing route may require one full App quit. Official prediction configuration is preserved; the conversation's model is used. App updates require another compatibility check. Status distinguishes saved preference and observed config traffic from unverified candidate visibility.\n\nFix asks a compatible running CCDX adapter to repair the enabled bridge once on its saved port. It never enables predictions, renews certificates or force-restarts Codex. Healthy unchanged bridges are retained. Fix rechecks system proxy settings. Changed routes may need a normal App relaunch to reload cached PAC; failed rechecks preserve the previous bridge with a nonzero exit. Process environment variables and Node trust are not hot-reloaded; changed trust inputs need a CCDX service restart. Startup, status and doctor share sanitized environment diagnostics. Missing App routes require a normal full quit and ccdx launch; partial repair exits 1. An older adapter must first be upgraded and restarted once to gain this repair endpoint.`,
|
|
380
|
+
update: `Usage:\n ${name} update [npm|github] [--allow-remote]\n\nUpdates the global package from the configured npm registry or the latest stable GitHub release. With no source, an interactive terminal prompts for one. Windows uses system cmd.exe to run npm.cmd without changing PowerShell policy; use the .cmd entrypoint if scripts are blocked. GitHub installs require Git on PATH and dependencies may still use the configured npm registry. By default npm's remote-download policy is preserved. If npm reports EALLOWREMOTE for a trusted mirror tarball, --allow-remote explicitly permits URL dependencies for this one installation's entire dependency tree; it is not a hostname allowlist. No .npmrc, registry or persistent policy is changed, and failed installations are not retried automatically. Use this only if company policy permits it. Restart the running adapter after installation.`,
|
|
377
381
|
version: `Usage:\n ${name} --version`,
|
|
378
382
|
};
|
|
379
383
|
return sections[topic];
|
|
@@ -399,7 +403,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
|
|
|
399
403
|
${name} image-status
|
|
400
404
|
${name} auto-review-model
|
|
401
405
|
${name} prediction [status|on|off|fix]
|
|
402
|
-
${name} update [npm|github]
|
|
406
|
+
${name} update [npm|github] [--allow-remote]
|
|
403
407
|
${name} --version
|
|
404
408
|
${name} --help
|
|
405
409
|
|
package/src/cli-status.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ADAPTER_STATUS_PATH, adapterBaseUrl } from "./running-adapter.mjs";
|
|
2
2
|
import { status } from "./status.mjs";
|
|
3
3
|
import { terminalCell } from "./cli-table.mjs";
|
|
4
|
+
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
4
5
|
|
|
5
6
|
function finiteNumber(value) {
|
|
6
7
|
const number = Number(value);
|
|
@@ -194,6 +195,7 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
|
|
|
194
195
|
lines.push(status("info", `Native predictions: ${prediction.configured ? "on" : "off"}; bridge ${prediction.bridge}; client route ${prediction.client_route}; visible candidate unknown`));
|
|
195
196
|
if (prediction.launch_route) lines.push(status("info", `Prediction self-check: App route ${prediction.launch_route}; persistent route ${prediction.persistence || "unknown"}; ${count(prediction.recovery?.recovered)} bridge recoveries, ${count(prediction.recovery?.attempts)}/3 attempts used`));
|
|
196
197
|
if (prediction.reason) lines.push(status("warn", terminalCell(prediction.reason).slice(0, 400)));
|
|
198
|
+
if (prediction.environment) lines.push(status("info", formatPredictionEnvironment(prediction.environment)));
|
|
197
199
|
}
|
|
198
200
|
if (data.profiles?.codex) {
|
|
199
201
|
lines.push(status("info", `Profile: ${profileSummary("Codex", data.profiles.codex)}`));
|
|
@@ -4,6 +4,7 @@ import { ensureCodexThreadCompression } from "./codex-thread-compression.mjs";
|
|
|
4
4
|
import { runInBackground } from "./startup.mjs";
|
|
5
5
|
import { createPredictionState } from "./native-prediction-state.mjs";
|
|
6
6
|
import { supervisePrediction } from "./native-prediction-recovery.mjs";
|
|
7
|
+
import { operationErrorDetails } from "./operation-error.mjs";
|
|
7
8
|
|
|
8
9
|
// The CLI composes the services; this module owns optional client integration
|
|
9
10
|
// lifecycle. It never forwards model requests or depends on dashboard rendering.
|
|
@@ -12,14 +13,30 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
|
|
|
12
13
|
const prediction = createPredictionState();
|
|
13
14
|
let native = null;
|
|
14
15
|
let operation = null, operationName = null, closed = false;
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
let pendingRoutePid = null;
|
|
17
|
+
async function startPredictionBridge(expectedPort, environment) {
|
|
18
|
+
const started = await startPrediction({ state: prediction, warning: info,
|
|
19
|
+
...(environment ? { environment } : {}), ...(expectedPort ? { expectedPort } : {}) });
|
|
17
20
|
if (!started) return null;
|
|
18
21
|
if (closed) { await started.close();return null; }
|
|
19
22
|
const port = Number(new URL(started.pacUrl).port);
|
|
20
23
|
prediction.supervising();
|
|
24
|
+
let latest = started;
|
|
21
25
|
return supervisePrediction({ native: started, state: prediction, warning,
|
|
22
|
-
restart: () =>
|
|
26
|
+
restart: async () => {
|
|
27
|
+
const check = await latest.inspectEnvironment?.();
|
|
28
|
+
if (check?.requiresServiceRestart) throw Object.assign(new Error("Node trust settings changed; restart CCDX before restoring the prediction bridge"), {
|
|
29
|
+
code: "tls_restart_required", predictionEnvironment: { ...check.next.summary, status: "needs_service_restart" } });
|
|
30
|
+
const resumed = await startPrediction({ state: prediction, warning: info, expectedPort: port, ...(check ? { environment: check.next } : {}) });
|
|
31
|
+
if (resumed) latest = resumed;
|
|
32
|
+
if (check?.changed && resumed) {
|
|
33
|
+
let route;try { route = await resumed.inspectRoute?.(); } catch {}
|
|
34
|
+
const pid = resumed.routeProcessId?.();pendingRoutePid = route === "closed" ? null : Number.isInteger(pid) ? pid : "unknown";
|
|
35
|
+
prediction.environment({ ...check.next.summary, status: pendingRoutePid === null ? "adapted" : "needs_app_relaunch" }, { resetTraffic: true });
|
|
36
|
+
if (pendingRoutePid !== null) warning("Prediction network settings changed; normally relaunch Codex to reload its PAC. No App was restarted");
|
|
37
|
+
}
|
|
38
|
+
return resumed;
|
|
39
|
+
} });
|
|
23
40
|
}
|
|
24
41
|
function serialize(name, task) {
|
|
25
42
|
if (closed) return Promise.reject(new Error("Client integration is closing; repair was skipped"));
|
|
@@ -54,11 +71,29 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
|
|
|
54
71
|
}); },
|
|
55
72
|
fix() { return serialize("fix", async () => {
|
|
56
73
|
let restarted = false, route = "unknown";
|
|
74
|
+
let environmentCheck;
|
|
75
|
+
if (native?.enabled?.() !== false && native?.inspectEnvironment) {
|
|
76
|
+
try {
|
|
77
|
+
environmentCheck = await native.inspectEnvironment();
|
|
78
|
+
if (environmentCheck?.requiresServiceRestart) {
|
|
79
|
+
prediction.environment({ ...prediction.snapshot().environment, tls: environmentCheck.next.summary.tls,
|
|
80
|
+
checked_at: environmentCheck.next.summary.checked_at, status: "needs_service_restart" });
|
|
81
|
+
return { status: "needs_service_restart", bridge_restarted: false, app_route: route, prediction: prediction.snapshot() };
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
const details = operationErrorDetails(error);
|
|
85
|
+
prediction.environment({ ...prediction.snapshot().environment, status: "preserved", error: details, checked_at: new Date().toISOString() });
|
|
86
|
+
return { status: "environment_preserved", bridge_restarted: false, app_route: route,
|
|
87
|
+
environment_error: details, prediction: prediction.snapshot() };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
57
90
|
try {
|
|
58
|
-
if (!native?.healthy() || native.enabled?.() === false || native.appCurrent?.() === false) {
|
|
91
|
+
if (!native?.healthy() || native.enabled?.() === false || native.appCurrent?.() === false || environmentCheck?.changed) {
|
|
59
92
|
const expectedPort = native ? Number(new URL(native.pacUrl).port) : undefined;
|
|
60
93
|
await native?.close();native = null;
|
|
61
|
-
native = await startPredictionBridge(expectedPort);restarted = Boolean(native);
|
|
94
|
+
native = await startPredictionBridge(expectedPort, environmentCheck?.next);restarted = Boolean(native);
|
|
95
|
+
} else if (environmentCheck) {
|
|
96
|
+
prediction.environment(environmentCheck.next.summary);
|
|
62
97
|
}
|
|
63
98
|
} catch (error) { prediction.unavailable(error); }
|
|
64
99
|
let routeError = false;
|
|
@@ -68,9 +103,17 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
|
|
|
68
103
|
route = await native.inspectRoute?.() || "unverified";
|
|
69
104
|
} catch { routeError = true;warning("Prediction bridge is ready, but App route inspection failed"); }
|
|
70
105
|
}
|
|
106
|
+
const pid = native?.routeProcessId?.();
|
|
107
|
+
if (pendingRoutePid !== null && (route === "closed" || (Number.isInteger(pendingRoutePid) && Number.isInteger(pid) && pid !== pendingRoutePid))) pendingRoutePid = null;
|
|
108
|
+
if (environmentCheck?.changed && native) {
|
|
109
|
+
pendingRoutePid = route === "closed" ? null : Number.isInteger(pid) ? pid : "unknown";
|
|
110
|
+
prediction.environment({ ...environmentCheck.next.summary, status: pendingRoutePid === null ? "adapted" : "needs_app_relaunch" }, { resetTraffic: true });
|
|
111
|
+
} else if (pendingRoutePid !== null && native) {
|
|
112
|
+
prediction.environment({ ...prediction.snapshot().environment, status: "needs_app_relaunch" });
|
|
113
|
+
}
|
|
71
114
|
const snapshot = prediction.snapshot();
|
|
72
115
|
const status = !snapshot.configured && snapshot.bridge !== "unavailable" ? "disabled" : snapshot.bridge !== "running" ? "failed"
|
|
73
|
-
: route === "verified" || route === "closed" ? "ready" : route === "missing" ? "needs_app_relaunch" : "route_unverified";
|
|
116
|
+
: pendingRoutePid !== null ? "needs_app_relaunch" : route === "verified" || route === "closed" ? "ready" : route === "missing" ? "needs_app_relaunch" : "route_unverified";
|
|
74
117
|
return { status, bridge_restarted: restarted, app_route: route, ...(routeError ? { route_error: true } : {}), prediction: snapshot };
|
|
75
118
|
}); },
|
|
76
119
|
pacUrl() { return native?.pacUrl || null; },
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { execFile } from "node:child_process";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
6
|
import { readAdapterStatus } from "./cli-status.mjs";
|
|
7
|
+
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
7
8
|
|
|
8
9
|
export function parseRunningCodexApps(stdout) {
|
|
9
10
|
const apps = new Map();
|
|
@@ -51,6 +52,8 @@ export async function inspectCodexClient({
|
|
|
51
52
|
const { data } = await readStatus({ host, port, fetchImpl, timeoutMs: 1500 });
|
|
52
53
|
const source = ["live", "cache", "built-in"].includes(data.models?.source) ? data.models.source : "unknown";
|
|
53
54
|
checks.push({ kind: "info", message: `Running adapter ${data.version}; upstream model directory source: ${source}` });
|
|
55
|
+
const prediction = data.client_integrations?.prediction;
|
|
56
|
+
if (prediction?.environment) checks.push({ kind: prediction.environment.status === "adapted" ? "info" : "warn", message: formatPredictionEnvironment(prediction.environment) });
|
|
54
57
|
const catalog = data.models?.client_catalog;
|
|
55
58
|
const observed = catalog?.last_request;
|
|
56
59
|
if (!catalog) {
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { createHash, X509Certificate } from "node:crypto";
|
|
3
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
4
|
+
import { resolveNetworkRoute, networkRouteSnapshot } from "./network-route.mjs";
|
|
5
|
+
import { windowsProxySettings, windowsProxyText } from "./native-prediction-windows.mjs";
|
|
6
|
+
|
|
7
|
+
const digest = value => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
8
|
+
|
|
9
|
+
function trustSnapshot(env, readFile) {
|
|
10
|
+
let extraCa = "not_set", content = null;
|
|
11
|
+
if (env.NODE_EXTRA_CA_CERTS) {
|
|
12
|
+
try {
|
|
13
|
+
const pem = readFile(env.NODE_EXTRA_CA_CERTS, { maxBytes: 1024 * 1024, encoding: "utf8" });
|
|
14
|
+
content = digest(pem);
|
|
15
|
+
const certificates = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) || [];
|
|
16
|
+
if (!certificates.length) throw new Error("invalid");
|
|
17
|
+
for (const certificate of certificates) new X509Certificate(certificate);
|
|
18
|
+
extraCa = "configured";
|
|
19
|
+
} catch { extraCa = "unreadable_or_invalid"; }
|
|
20
|
+
}
|
|
21
|
+
// Keys and paths participate only in a private comparison, never diagnostics.
|
|
22
|
+
return { key: digest([env.NODE_EXTRA_CA_CERTS, env.NODE_OPTIONS, env.NODE_USE_SYSTEM_CA,
|
|
23
|
+
env.SSL_CERT_FILE, env.SSL_CERT_DIR, content]),
|
|
24
|
+
summary: { extra_ca: extraCa, tls_verification: "required", changes_require_service_restart: true } };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Called only for enabled prediction startup or an explicit fix. No system
|
|
28
|
+
// policy, trust store, environment, PATH or account is written by discovery.
|
|
29
|
+
export function inspectPredictionEnvironment({ env = process.env, platform = process.platform,
|
|
30
|
+
exec = execFileSync, readFile = readBoundedFileSync, now = () => new Date().toISOString() } = {}) {
|
|
31
|
+
const trust = trustSnapshot(env, readFile);
|
|
32
|
+
let network;
|
|
33
|
+
try {
|
|
34
|
+
if (platform === "win32") {
|
|
35
|
+
const settings = windowsProxySettings({ exec, env });
|
|
36
|
+
if (!settings.autoDetect && !settings.pac) network = { networkRoute: resolveNetworkRoute({ env, systemProxy: windowsProxyText(settings) }) };
|
|
37
|
+
else {
|
|
38
|
+
const explicit = resolveNetworkRoute({ env });
|
|
39
|
+
if (explicit.http || explicit.https || explicit.bypass.length) {
|
|
40
|
+
throw Object.assign(new Error("Windows automatic proxy and explicit proxy environment rules require separate routing; existing routes were preserved"), { code: "proxy_route_conflict" });
|
|
41
|
+
}
|
|
42
|
+
network = { settings };
|
|
43
|
+
}
|
|
44
|
+
} else {
|
|
45
|
+
const systemProxy = exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2000, maxBuffer: 64 * 1024 });
|
|
46
|
+
network = { networkRoute: resolveNetworkRoute({ env, systemProxy }) };
|
|
47
|
+
}
|
|
48
|
+
} catch (error) {
|
|
49
|
+
error.predictionEnvironment = { status: "unavailable", checked_at: now(), tls: trust.summary };
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
const plan = network.networkRoute;
|
|
53
|
+
const summary = { status: "adapted", checked_at: now(),
|
|
54
|
+
network: plan ? { ...networkRouteSnapshot(plan), cidr_rules: plan.bypass.filter(rule => rule.includes("/")).length,
|
|
55
|
+
dns: "system_or_proxy", http_source: plan.http?.source || "direct" }
|
|
56
|
+
: { source: "system", type: "auto", bypass_rules: null, cidr_rules: null, dns: "native_policy" },
|
|
57
|
+
tls: trust.summary };
|
|
58
|
+
return { network, networkKey: digest(network), trustKey: trust.key, summary };
|
|
59
|
+
}
|
|
@@ -18,7 +18,7 @@ export async function requestPredictionFix({ host = "127.0.0.1", port = 2026, fe
|
|
|
18
18
|
const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, label: "Prediction repair response", signal });
|
|
19
19
|
if (!response.ok) throw new Error(`Prediction repair returned HTTP ${response.status}; no App was restarted`);
|
|
20
20
|
let value;try { value = JSON.parse(text); } catch {}
|
|
21
|
-
if (!["ready", "disabled", "failed", "needs_app_relaunch", "route_unverified"].includes(value?.status)
|
|
21
|
+
if (!["ready", "disabled", "failed", "needs_app_relaunch", "route_unverified", "needs_service_restart", "environment_preserved"].includes(value?.status)
|
|
22
22
|
|| !["running", "stopped", "unavailable", "recovering"].includes(value?.prediction?.bridge)
|
|
23
23
|
|| value.prediction.candidate !== "unknown"
|
|
24
24
|
|| (["ready", "needs_app_relaunch", "route_unverified"].includes(value.status) && value.prediction.bridge !== "running")
|
|
@@ -36,6 +36,8 @@ export function supervisePrediction({ native, restart, state, warning = () => {}
|
|
|
36
36
|
healthy() { return !closed && current.healthy(); },
|
|
37
37
|
enabled() { return !closed && current.enabled?.() !== false; },
|
|
38
38
|
appCurrent() { return current.appCurrent?.() !== false; },
|
|
39
|
+
inspectEnvironment() { return current.inspectEnvironment?.(); },
|
|
40
|
+
routeProcessId() { return current.routeProcessId?.(); },
|
|
39
41
|
inspectRoute() { return current.inspectRoute?.(); },
|
|
40
42
|
prepareRoute() { return current.prepareRoute?.(); },
|
|
41
43
|
async close() { closed = true;clearIntervalImpl(timer);await flight;await current?.close(); },
|
|
@@ -7,6 +7,10 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
|
|
|
7
7
|
configuration: {}, counters: { configuration_responses: 0, modified: 0, tls_errors: 0, upstream_errors: 0 }, last_event_at: null };
|
|
8
8
|
return {
|
|
9
9
|
configure(enabled) { state.configured = enabled === true; },
|
|
10
|
+
environment(value, { resetTraffic = false } = {}) {
|
|
11
|
+
state.environment = structuredClone(value);
|
|
12
|
+
if (resetTraffic) { state.client_route = "unknown";state.configuration = {}; }
|
|
13
|
+
},
|
|
10
14
|
running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy;delete state.error; },
|
|
11
15
|
stopped() { state.bridge = "stopped"; },
|
|
12
16
|
launch(route) { state.launch_route = ["verified", "persisted"].includes(route) ? route : "unverified"; },
|
|
@@ -19,6 +23,7 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
|
|
|
19
23
|
state.bridge = "unavailable";
|
|
20
24
|
state.reason = redactDiagnosticText(String(error?.message || "Prediction setup failed")).slice(0, 400);
|
|
21
25
|
state.error = operationErrorDetails(error);
|
|
26
|
+
if (error?.predictionEnvironment) state.environment = structuredClone(error.predictionEnvironment);
|
|
22
27
|
},
|
|
23
28
|
event(event) {
|
|
24
29
|
state.last_event_at = now();
|
|
@@ -34,3 +39,15 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
|
|
|
34
39
|
snapshot() { return structuredClone(state); },
|
|
35
40
|
};
|
|
36
41
|
}
|
|
42
|
+
|
|
43
|
+
export function formatPredictionEnvironment(environment) {
|
|
44
|
+
if (!environment) return "";
|
|
45
|
+
const statuses = ["adapted", "preserved", "unavailable", "needs_service_restart", "needs_app_relaunch"];
|
|
46
|
+
const state = statuses.includes(environment.status) ? environment.status : "unknown";
|
|
47
|
+
const network = environment.network;
|
|
48
|
+
const type = ["http", "https", "socks5", "socks5h", "direct", "auto"].includes(network?.type) ? network.type : "unknown";
|
|
49
|
+
const source = ["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy", "system HTTPS", "system SOCKS", "system", "direct"].includes(network?.source) ? network.source : "unknown";
|
|
50
|
+
const count = value => Number.isSafeInteger(value) && value >= 0 ? String(value) : "unknown";
|
|
51
|
+
const ca = ["not_set", "configured", "unreadable_or_invalid"].includes(environment.tls?.extra_ca) ? environment.tls.extra_ca : "unknown";
|
|
52
|
+
return `Prediction environment: ${state}; proxy ${source}/${type}; bypass ${count(network?.bypass_rules)} (${count(network?.cidr_rules)} CIDR); extra CA ${ca}; TLS verification required`;
|
|
53
|
+
}
|
|
@@ -1,30 +1,15 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { execFileSync } from "node:child_process";
|
|
4
3
|
import { predictionPaths, readPredictionSettings, writePredictionSettings, assertPredictionProxyCompatible,
|
|
5
4
|
assertCodexClosed, installedPredictionApp, predictionAppMatches, readPredictionCertificate,
|
|
6
5
|
createPredictionCertificate, updatePredictionTrust } from "./native-prediction-profile.mjs";
|
|
7
6
|
import { retirePredictionIntegration } from "./prediction-retirement.mjs";
|
|
8
7
|
import { networkRouteSnapshot } from "./network-route.mjs";
|
|
9
8
|
import { withFileLock } from "./lock.mjs";
|
|
10
|
-
import {
|
|
9
|
+
import { windowsProxyText, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
|
|
11
10
|
import { updatePredictionRoute } from "./native-prediction-route.mjs";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
if (platform === "win32") return windowsSystemProxy({ exec, env });
|
|
15
|
-
return exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2000, maxBuffer: 64 * 1024 });
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function predictionNetworkOptions(options) {
|
|
19
|
-
if (options.platform !== "win32") return { networkRoute: assertPredictionProxyCompatible({ env: options.env, systemProxy: systemProxy(options.exec, options) }) };
|
|
20
|
-
const settings = windowsProxySettings(options);
|
|
21
|
-
if (!settings.autoDetect && !settings.pac) return { networkRoute: assertPredictionProxyCompatible({ env: options.env, systemProxy: windowsProxyText(settings) }) };
|
|
22
|
-
const environment = assertPredictionProxyCompatible({ env: options.env });
|
|
23
|
-
if (environment.http || environment.https || environment.bypass.length) {
|
|
24
|
-
throw new Error("Windows automatic proxy and explicit proxy environment rules require separate routing; existing routes were preserved");
|
|
25
|
-
}
|
|
26
|
-
return { settings };
|
|
27
|
-
}
|
|
11
|
+
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
12
|
+
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
28
13
|
|
|
29
14
|
function certificateDirectory(settings, paths) {
|
|
30
15
|
if (!settings.credentialsDirectory) return paths.directory;
|
|
@@ -56,8 +41,12 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
56
41
|
const result = await repairRuntime();
|
|
57
42
|
const prediction = result.prediction;
|
|
58
43
|
output(`Prediction repair: ${result.status}; bridge: ${prediction.bridge}; candidate: ${prediction.candidate}`);
|
|
44
|
+
if (prediction.environment) output(formatPredictionEnvironment(prediction.environment));
|
|
59
45
|
if (result.status === "disabled") output("The running adapter has predictions off; no feature was enabled.");
|
|
46
|
+
else if (result.status === "needs_service_restart") output("Node trust settings changed. Restart the CCDX service to apply them; no certificate or App was changed.");
|
|
47
|
+
else if (result.status === "environment_preserved") output(`Network recheck failed; the existing bridge and routes were preserved. ${result.environment_error?.message || "Check ccdx prediction status."}`);
|
|
60
48
|
else if (prediction.bridge !== "running") output(prediction.reason || "Prediction bridge is unavailable; core service was not changed.");
|
|
49
|
+
else if (prediction.environment?.status === "needs_app_relaunch") output("Network settings changed. The bridge uses the new snapshot, but the App may cache its earlier PAC. Fully quit Codex, then run ccdx; no App was restarted.");
|
|
61
50
|
else if (result.app_route === "verified") output("App launch route verified. A visible suggestion still needs an App-side check.");
|
|
62
51
|
else if (result.app_route === "closed") output("Bridge is ready. Run ccdx to open Codex with its prediction route.");
|
|
63
52
|
else if (result.status === "route_unverified") output("Bridge is ready, but App route inspection was unavailable or ambiguous. Check ccdx prediction status; no App was restarted.");
|
|
@@ -76,6 +65,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
76
65
|
if (runtime.launch_route) output(`App launch route: ${runtime.launch_route}; persistent route: ${runtime.persistence || "unknown"}`);
|
|
77
66
|
if (runtime.recovery) output(`Bridge recovery: ${runtime.recovery.recovered} recovered; ${runtime.recovery.attempts}/3 attempts used`);
|
|
78
67
|
if (runtime.reason) output(runtime.reason);
|
|
68
|
+
if (runtime.environment) output(formatPredictionEnvironment(runtime.environment));
|
|
79
69
|
for (const [name, event] of Object.entries(runtime.configuration || {})) output(`${name}: HTTP ${event.status}${event.modified ? " (local compatibility)" : " (upstream)"}`);
|
|
80
70
|
} else output("Runtime prediction state: unavailable; status is a saved preference, not proof of a visible suggestion.");
|
|
81
71
|
} catch { output("Runtime prediction state: unavailable; start ccdx and check again."); }
|
|
@@ -112,7 +102,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
112
102
|
return { ...settings, enabled: false };
|
|
113
103
|
}
|
|
114
104
|
assertCodexClosed(opts);
|
|
115
|
-
|
|
105
|
+
inspectPredictionEnvironment(opts);
|
|
116
106
|
const app = resolveApp({ ...opts, ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
|
|
117
107
|
paths = predictionPaths({ ...opts, app });
|
|
118
108
|
if (settings.store && settings.store !== paths.store) throw new Error("Codex profile changed; disable the previous profile before enabling another");
|
|
@@ -165,7 +155,9 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
165
155
|
state?.configure(settings.enabled);
|
|
166
156
|
if (!settings.enabled) return null;
|
|
167
157
|
if (!["darwin", "win32"].includes(platform)) throw new Error("Native predictions were skipped: unsupported platform");
|
|
168
|
-
const
|
|
158
|
+
const environment = options.environment || inspectPredictionEnvironment(opts);
|
|
159
|
+
state?.environment(environment.summary);
|
|
160
|
+
const network = environment.network;
|
|
169
161
|
let networkRoute = network.networkRoute;
|
|
170
162
|
if (settings.bridgePort !== undefined
|
|
171
163
|
&& (!Number.isInteger(settings.bridgePort) || settings.bridgePort < 1024 || settings.bridgePort > 65535)) {
|
|
@@ -250,17 +242,24 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
250
242
|
throw error;
|
|
251
243
|
}
|
|
252
244
|
state?.running(windowsNetwork ? { source: "system", type: "auto", bypass_rules: null, proxy_credentials: false } : networkRouteSnapshot(networkRoute));
|
|
245
|
+
let routeProcessId = null;
|
|
253
246
|
return {
|
|
254
247
|
app: settings.app.app,
|
|
255
248
|
...(platform === "win32" ? { profile: paths.profile } : {}),
|
|
256
249
|
pacUrl: transport.pacUrl,
|
|
257
250
|
enabled() { return enabled; },
|
|
258
251
|
appCurrent() { return predictionAppMatches(settings.app); },
|
|
252
|
+
inspectEnvironment() {
|
|
253
|
+
const next = inspectPredictionEnvironment(opts);
|
|
254
|
+
return { changed: next.networkKey !== environment.networkKey, requiresServiceRestart: next.trustKey !== environment.trustKey, next };
|
|
255
|
+
},
|
|
256
|
+
routeProcessId() { return routeProcessId; },
|
|
259
257
|
healthy() { return transport.healthy() && (!windowsNetwork || windowsNetwork.healthy()); },
|
|
260
258
|
async inspectRoute() {
|
|
261
259
|
const inspect = options.inspectAppProcesses || (platform === "win32" ? windowsPredictionAppProcesses
|
|
262
260
|
: (await import("./launcher.mjs")).macPredictionAppProcesses);
|
|
263
261
|
const rows = inspect(settings.app.app, opts);
|
|
262
|
+
routeProcessId = rows.length === 1 && rows[0].readable ? rows[0].pid : null;
|
|
264
263
|
const route = rows.length === 0 ? "closed" : rows.length !== 1 || !rows[0].readable ? "unverified"
|
|
265
264
|
: rows[0].route === transport.pacUrl ? "verified" : "missing";
|
|
266
265
|
state?.launch(route);
|
|
@@ -268,7 +267,7 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
268
267
|
},
|
|
269
268
|
async prepareRoute() {
|
|
270
269
|
try {
|
|
271
|
-
const direct = !windowsNetwork && !networkRoute?.http && !networkRoute?.https
|
|
270
|
+
const direct = !windowsNetwork && !networkRoute?.http && !networkRoute?.https;
|
|
272
271
|
if (!direct) {
|
|
273
272
|
// A profile previously configured on a direct network must not pin
|
|
274
273
|
// that local PAC after the environment switches to company routing.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Pure matching shared by Node and the generated PAC. CIDRs apply to URL IP
|
|
2
|
+
// literals, as in Chromium's manual bypass rules; they never trigger DNS.
|
|
3
|
+
export function literalAddress(value) {
|
|
4
|
+
var text = String(value).toLowerCase().replace(/^\[|\]$/g, "");
|
|
5
|
+
var ipv4 = function (s) {
|
|
6
|
+
if (!/^(0|[1-9][0-9]{0,2})(\.(0|[1-9][0-9]{0,2})){3}$/.test(s)) return null;
|
|
7
|
+
var bytes = s.split(".").map(Number);
|
|
8
|
+
return bytes.every(function (n) { return n <= 255; }) ? bytes : null;
|
|
9
|
+
};
|
|
10
|
+
if (text.indexOf(":") < 0) return ipv4(text);
|
|
11
|
+
if (text.indexOf(".") >= 0) {
|
|
12
|
+
var last = text.lastIndexOf(":"), tail = ipv4(text.slice(last + 1));
|
|
13
|
+
if (!tail) return null;
|
|
14
|
+
text = text.slice(0, last + 1) + (tail[0] * 256 + tail[1]).toString(16) + ":" + (tail[2] * 256 + tail[3]).toString(16);
|
|
15
|
+
}
|
|
16
|
+
if (!/^[0-9a-f:]+$/.test(text) || text.indexOf(":::") >= 0) return null;
|
|
17
|
+
var halves = text.split("::");
|
|
18
|
+
if (halves.length > 2) return null;
|
|
19
|
+
var left = halves[0] ? halves[0].split(":") : [], right = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
|
|
20
|
+
var missing = 8 - left.length - right.length;
|
|
21
|
+
if (halves.length === 1 ? left.length !== 8 : missing < 1) return null;
|
|
22
|
+
var groups = left.slice();
|
|
23
|
+
if (halves.length === 2) for (var i = 0; i < missing; i++) groups.push("0");
|
|
24
|
+
groups = groups.concat(right);
|
|
25
|
+
var result = [];
|
|
26
|
+
for (var j = 0; j < groups.length; j++) {
|
|
27
|
+
if (!/^[0-9a-f]{1,4}$/.test(groups[j])) return null;
|
|
28
|
+
var number = parseInt(groups[j], 16);result.push(number >>> 8, number & 255);
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function compileBypassRules(values) {
|
|
34
|
+
return values.map(raw => {
|
|
35
|
+
if (raw.includes("/")) {
|
|
36
|
+
const parts = raw.split("/"), address = literalAddress(parts[0]);
|
|
37
|
+
if (parts.length !== 2 || !address || /[\[\]]/.test(parts[0]) || !/^\d{1,3}$/.test(parts[1]) || Number(parts[1]) > address.length * 8) {
|
|
38
|
+
throw Object.assign(new Error("Invalid proxy bypass CIDR rule; existing routes were preserved"), { code: "proxy_bypass_invalid" });
|
|
39
|
+
}
|
|
40
|
+
return { address, prefix: Number(parts[1]), port: null };
|
|
41
|
+
}
|
|
42
|
+
let host = raw, port = null;
|
|
43
|
+
const bracket = /^\[([^\]]+)\](?::(\d+))?$/.exec(raw);
|
|
44
|
+
const suffix = !literalAddress(raw) && /^(.*):(\d+)$/.exec(raw);
|
|
45
|
+
if (bracket) { host = bracket[1];port = bracket[2] ? Number(bracket[2]) : null; }
|
|
46
|
+
else if (suffix) { host = suffix[1];port = Number(suffix[2]); }
|
|
47
|
+
if ((port !== null && (port < 1 || port > 65535)) || /[\s/@?#\\\[\]]/.test(host) || !host) {
|
|
48
|
+
throw Object.assign(new Error("Invalid proxy bypass host or port; existing routes were preserved"), { code: "proxy_bypass_invalid" });
|
|
49
|
+
}
|
|
50
|
+
const address = literalAddress(host);
|
|
51
|
+
if (bracket && address?.length !== 16) throw Object.assign(new Error("Invalid proxy bypass IPv6 literal; existing routes were preserved"), { code: "proxy_bypass_invalid" });
|
|
52
|
+
if (host.includes(":") && !address) throw Object.assign(new Error("Invalid proxy bypass IP literal; existing routes were preserved"), { code: "proxy_bypass_invalid" });
|
|
53
|
+
return address ? { address, prefix: address.length * 8, port }
|
|
54
|
+
: { host, port, ...(host.includes("*") ? { expression: "^" + host.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*") + "$" } : {}) };
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function matchesBypass(hostname, port, rules, excludeSimple) {
|
|
59
|
+
var host = hostname.toLowerCase().replace(/^\[|\]$/g, ""), address = literalAddress(host);
|
|
60
|
+
if (host === "localhost" || host === "127.0.0.1" || (address && address.length === 16 && address.slice(0, 15).every(function (n) { return n === 0; }) && address[15] === 1)
|
|
61
|
+
|| (excludeSimple && !address && host.indexOf(".") < 0)) return true;
|
|
62
|
+
for (var i = 0; i < rules.length; i++) {
|
|
63
|
+
var rule = rules[i];
|
|
64
|
+
if (rule.port !== null && rule.port !== Number(port)) continue;
|
|
65
|
+
if (rule.address) {
|
|
66
|
+
if (!address || address.length !== rule.address.length) continue;
|
|
67
|
+
var equal = true;
|
|
68
|
+
for (var index = 0; index < Math.ceil(rule.prefix / 8); index++) {
|
|
69
|
+
var mask = (255 << Math.max(0, 8 - (rule.prefix - index * 8))) & 255;
|
|
70
|
+
if ((address[index] & mask) !== (rule.address[index] & mask)) { equal = false;break; }
|
|
71
|
+
}
|
|
72
|
+
if (equal) return true;
|
|
73
|
+
} else if (rule.expression ? new RegExp(rule.expression).test(host)
|
|
74
|
+
: host === rule.host.replace(/^\*?\./, "") || host.slice(-(rule.host.replace(/^\*?\./, "").length + 1)) === "." + rule.host.replace(/^\*?\./, "")) return true;
|
|
75
|
+
}
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function bypassPacSource() { return literalAddress.toString() + "\n" + matchesBypass.toString(); }
|
package/src/network-route.mjs
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import net from "node:net";
|
|
2
|
+
import { compileBypassRules, matchesBypass, bypassPacSource } from "./network-bypass.mjs";
|
|
2
3
|
|
|
3
4
|
const OFFICIAL_API = "https://chatgpt.com/backend-api";
|
|
5
|
+
const routeError = (code, message) => Object.assign(new Error(message), { code });
|
|
4
6
|
|
|
5
7
|
function proxy(value, source) {
|
|
6
8
|
if (!value) return null;
|
|
7
9
|
let url;
|
|
8
|
-
try { url = new URL(value); } catch { throw
|
|
10
|
+
try { url = new URL(value); } catch { throw routeError("proxy_address_invalid", `Invalid proxy address in ${source}`); }
|
|
9
11
|
if (!["http:", "https:", "socks5:", "socks5h:"].includes(url.protocol)
|
|
10
12
|
|| !url.hostname || !["", "/"].includes(url.pathname) || url.search || url.hash) {
|
|
11
|
-
throw
|
|
13
|
+
throw routeError("proxy_address_unsupported", `Unsupported proxy address in ${source}; expected HTTP, HTTPS or SOCKS5`);
|
|
12
14
|
}
|
|
13
15
|
return { url, source };
|
|
14
16
|
}
|
|
@@ -21,50 +23,33 @@ function variable(env, lower, upper) {
|
|
|
21
23
|
export function resolveNetworkRoute({ env = process.env, systemProxy = "", checkApi = true } = {}) {
|
|
22
24
|
const api = String(env.CODEX_API_BASE_URL || "").trim().replace(/\/+$/, "");
|
|
23
25
|
if (checkApi && api && api !== OFFICIAL_API) {
|
|
24
|
-
throw
|
|
26
|
+
throw routeError("prediction_route_conflict", "Native prediction setup skipped: CODEX_API_BASE_URL selects a custom API route; it was preserved");
|
|
25
27
|
}
|
|
26
28
|
const settings = Object.fromEntries([...systemProxy.matchAll(/^\s*([A-Za-z]+)\s*:\s*(.+?)\s*$/gm)].map((m) => [m[1], m[2]]));
|
|
27
29
|
for (const key of ["ProxyAutoConfigEnable", "ProxyAutoDiscoveryEnable"]) {
|
|
28
|
-
if (settings[key] === "1") throw
|
|
30
|
+
if (settings[key] === "1") throw routeError("proxy_dynamic_unsupported", `Native prediction setup skipped: system ${key === "ProxyAutoConfigEnable" ? "PAC" : "WPAD"} (${key}) needs dynamic routing; its rules were preserved`);
|
|
29
31
|
}
|
|
30
32
|
const system = (prefix, scheme) => {
|
|
31
33
|
if (settings[`${prefix}Enable`] !== "1") return null;
|
|
32
34
|
const host = settings[`${prefix}Proxy`], port = settings[`${prefix}Port`];
|
|
33
35
|
if (!host || !/^\d+$/.test(port || "") || Number(port) < 1 || Number(port) > 65535) {
|
|
34
|
-
throw
|
|
36
|
+
throw routeError("proxy_system_invalid", `Invalid system ${prefix} proxy settings`);
|
|
35
37
|
}
|
|
36
38
|
return proxy(`${scheme}://${net.isIP(host) === 6 ? `[${host}]` : host}:${port}`, `system ${prefix}`);
|
|
37
39
|
};
|
|
38
40
|
const httpEnv = variable(env, "http_proxy", "HTTP_PROXY"), httpsEnv = variable(env, "https_proxy", "HTTPS_PROXY");
|
|
39
41
|
const allEnv = variable(env, "all_proxy", "ALL_PROXY");
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
const systemHttp = system("HTTP", "http"), systemHttps = system("HTTPS", "http");
|
|
43
|
-
const http = proxy(httpEnv.value, httpEnv.source) || all || systemHttp || systemSocks;
|
|
44
|
-
const https = proxy(httpsEnv.value, httpsEnv.source) || all || systemHttps || systemSocks;
|
|
42
|
+
const http = proxy(httpEnv.value, httpEnv.source) || proxy(allEnv.value, allEnv.source) || system("HTTP", "http") || system("SOCKS", "socks5");
|
|
43
|
+
const https = proxy(httpsEnv.value, httpsEnv.source) || proxy(allEnv.value, allEnv.source) || system("HTTPS", "http") || system("SOCKS", "socks5");
|
|
45
44
|
const noProxy = variable(env, "no_proxy", "NO_PROXY").value;
|
|
46
45
|
const exceptions = /ExceptionsList\s*:\s*<array>\s*\{([^}]+)\}/.exec(systemProxy)?.[1] || "";
|
|
47
46
|
const bypass = [...new Set([...noProxy.split(","), ...[...exceptions.matchAll(/\d+\s*:\s*([^\n]+)/g)].map((m) => m[1])]
|
|
48
47
|
.map((s) => s.trim().toLowerCase()).filter(Boolean))];
|
|
49
|
-
|
|
50
|
-
return { http, https, bypass, excludeSimple: settings.ExcludeSimpleHostnames === "1" };
|
|
48
|
+
return { http, https, bypass, rules: compileBypassRules(bypass), excludeSimple: settings.ExcludeSimpleHostnames === "1" };
|
|
51
49
|
}
|
|
52
50
|
|
|
53
51
|
export function bypassNetworkProxy(hostname, port, plan) {
|
|
54
|
-
|
|
55
|
-
if (["localhost", "127.0.0.1", "::1"].includes(host) || (plan.excludeSimple && !host.includes("."))) return true;
|
|
56
|
-
return plan.bypass.some((raw) => {
|
|
57
|
-
if (raw === "*") return true;
|
|
58
|
-
const match = /^(.*):(\d+)$/.exec(raw);
|
|
59
|
-
const rule = match ? match[1] : raw;
|
|
60
|
-
if (match && Number(match[2]) !== Number(port)) return false;
|
|
61
|
-
const suffix = rule.replace(/^\*?\./, "");
|
|
62
|
-
if (rule.includes("*")) {
|
|
63
|
-
const expression = rule.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*");
|
|
64
|
-
return new RegExp(`^${expression}$`).test(host);
|
|
65
|
-
}
|
|
66
|
-
return host === suffix || host.endsWith(`.${suffix}`);
|
|
67
|
-
});
|
|
52
|
+
return matchesBypass(hostname, port, plan.rules || compileBypassRules(plan.bypass), plan.excludeSimple);
|
|
68
53
|
}
|
|
69
54
|
|
|
70
55
|
export function networkProxyFor(url, plan) {
|
|
@@ -88,13 +73,12 @@ function pacProxy(route) {
|
|
|
88
73
|
export function networkPredictionPac(port, plan) {
|
|
89
74
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid prediction proxy port");
|
|
90
75
|
// Embed only routing rules, never proxy passwords or API credentials.
|
|
91
|
-
return
|
|
76
|
+
return `${bypassPacSource()}
|
|
77
|
+
var ccdxRoute=${JSON.stringify({ http: pacProxy(plan.http), https: pacProxy(plan.https), rules: plan.rules || compileBypassRules(plan.bypass), excludeSimple: plan.excludeSimple })};
|
|
92
78
|
function FindProxyForURL(url,host) {
|
|
93
79
|
var secure=url.indexOf('https:')===0, p=secure?443:80;
|
|
94
80
|
var authority=url.split('/')[2]||'', explicit=/:([0-9]+)$/.exec(authority);if(explicit)p=Number(explicit[1]);
|
|
95
|
-
var skip=host
|
|
96
|
-
for(var i=0;i<ccdxRoute.bypass.length&&!skip;i++){var raw=ccdxRoute.bypass[i],m=/^(.*):([0-9]+)$/.exec(raw),r=m?m[1]:raw;if(m&&Number(m[2])!==p)continue;
|
|
97
|
-
var suffix=r.indexOf('*.')===0?r.slice(2):r[0]==='.'?r.slice(1):r;skip=r==='*'||(r.indexOf('*')>=0?shExpMatch(host,r):host===suffix||dnsDomainIs(host,'.'+suffix));}
|
|
81
|
+
var skip=matchesBypass(host,p,ccdxRoute.rules,ccdxRoute.excludeSimple);
|
|
98
82
|
var original=skip?'DIRECT':secure?ccdxRoute.https:ccdxRoute.http;
|
|
99
83
|
if(secure&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return 'PROXY 127.0.0.1:${port}; '+original;
|
|
100
84
|
return original;
|
package/src/package-update.mjs
CHANGED
|
@@ -51,10 +51,36 @@ export function normalizeUpdateSource(value) {
|
|
|
51
51
|
return Object.hasOwn(UPDATE_SPECS, source) ? source : "";
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
// Read only named, non-secret fields. Never inspect the complete npm config,
|
|
55
|
+
// rewrite .npmrc, or probe this policy on the adapter's startup/request path.
|
|
56
|
+
export function inspectNpmDownloadPolicy({ env = process.env, platform = process.platform, exec = execFileSync } = {}) {
|
|
57
|
+
const result = { version: null, allowRemote: null, registryOrigin: null, supported: null };
|
|
58
|
+
const query = args => {
|
|
59
|
+
const launch = npmLaunch(args, { platform, env });
|
|
60
|
+
return exec(launch.command, launch.args, { env, shell: false, stdio: ["ignore", "pipe", "pipe"],
|
|
61
|
+
encoding: "utf8", timeout: 3000, maxBuffer: 64 * 1024, ...launch.options }).trim();
|
|
62
|
+
};
|
|
63
|
+
try {
|
|
64
|
+
const version = query(["--version"]);
|
|
65
|
+
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) return result;
|
|
66
|
+
result.version = version;
|
|
67
|
+
if (Number(version.split(".")[0]) < 11) { result.supported = false;return result; }
|
|
68
|
+
const values = Object.fromEntries(query(["config", "get", "--global", "allow-remote", "registry"]).split(/\r?\n/)
|
|
69
|
+
.map(line => /^(allow-remote|registry)=(.*)$/.exec(line)).filter(Boolean).map(match => [match[1], match[2]]));
|
|
70
|
+
if (["all", "none", "root"].includes(values["allow-remote"])) {
|
|
71
|
+
result.allowRemote = values["allow-remote"];result.supported = true;
|
|
72
|
+
} else if (values["allow-remote"] === "undefined") result.supported = false;
|
|
73
|
+
try { const url = new URL(values.registry);if (["https:", "http:"].includes(url.protocol)) result.registryOrigin = url.origin; } catch {}
|
|
74
|
+
} catch { /* A failed readonly probe must not replace npm's own error handling. */ }
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function globalUpdateCommand(source, { platform = process.platform, releaseTag, allowRemote = false } = {}) {
|
|
79
|
+
if (typeof allowRemote !== "boolean") throw new Error("Remote download permission must be a boolean");
|
|
55
80
|
const normalized = normalizeUpdateSource(source);
|
|
56
81
|
if (!normalized) throw new Error(`Update source must be npm or github: ${source}`);
|
|
57
82
|
const args = ["install", "--global"];
|
|
83
|
+
if (allowRemote) args.push("--allow-remote=all");
|
|
58
84
|
if (normalized === "github") {
|
|
59
85
|
if (!githubReleaseVersion(releaseTag)) throw new Error("A valid stable GitHub release tag is required");
|
|
60
86
|
args.push("--allow-git=all", `${UPDATE_SPECS.github}#${releaseTag}`);
|
|
@@ -79,7 +105,7 @@ function waitForExit(child) {
|
|
|
79
105
|
child.once("error", (error) => finish(reject, error));
|
|
80
106
|
child.once("exit", (code, signal) => {
|
|
81
107
|
if (signal) finish(reject, new Error(`npm update was interrupted by ${signal}`));
|
|
82
|
-
else if (code !== 0) finish(reject, new Error(`npm update exited with status ${code}`));
|
|
108
|
+
else if (code !== 0) finish(reject, Object.assign(new Error(`npm update exited with status ${code}`), { npmExitCode: code }));
|
|
83
109
|
else finish(resolve);
|
|
84
110
|
});
|
|
85
111
|
});
|
|
@@ -104,11 +130,14 @@ export async function runPackageUpdateCommand({
|
|
|
104
130
|
platform = process.platform,
|
|
105
131
|
prompt,
|
|
106
132
|
source,
|
|
133
|
+
allowRemote = false,
|
|
107
134
|
spawnImpl = spawn,
|
|
108
135
|
fetchImpl = fetch,
|
|
109
136
|
inspectEnvironmentFn = inspectPackageUpdateEnvironment,
|
|
137
|
+
inspectPolicyFn = inspectNpmDownloadPolicy,
|
|
110
138
|
verifyInstalledFn = verifyInstalledPackage,
|
|
111
139
|
} = {}) {
|
|
140
|
+
if (typeof allowRemote !== "boolean") throw new Error("Remote download permission must be a boolean");
|
|
112
141
|
let selectedSource = normalizeUpdateSource(source);
|
|
113
142
|
if (source && !selectedSource) throw new Error(`Update source must be npm or github: ${source}`);
|
|
114
143
|
|
|
@@ -147,9 +176,15 @@ export async function runPackageUpdateCommand({
|
|
|
147
176
|
output.write("Checking the latest stable GitHub release...\n");
|
|
148
177
|
release = await lookupLatestRelease({ fetchImpl, timeoutMs: 10000 });
|
|
149
178
|
}
|
|
150
|
-
const
|
|
179
|
+
const policy = inspectPolicyFn({ env, platform });
|
|
180
|
+
if (allowRemote && policy.supported === null) throw new Error("Could not verify npm's remote-download option; no installation was started. Check npm --version and npm config get allow-remote.");
|
|
181
|
+
const permitRemote = allowRemote && policy.supported === true;
|
|
182
|
+
const update = globalUpdateCommand(selectedSource, { platform, releaseTag: release?.tagName, allowRemote: permitRemote });
|
|
151
183
|
const sourceLabel = selectedSource === "npm" ? "npm registry" : `GitHub release ${release.tagName}`;
|
|
152
184
|
output.write(`Updating ${PACKAGE_NAME} from ${sourceLabel}...\n`);
|
|
185
|
+
if (policy.allowRemote) output.write(`npm ${terminalCell(policy.version)}: saved allow-remote=${policy.allowRemote}${policy.registryOrigin ? `; registry ${terminalCell(policy.registryOrigin)}` : ""}.\n`);
|
|
186
|
+
if (permitRemote) output.write("Explicit permission for this update only: npm may download URL dependencies throughout the selected package's dependency tree. Registry and persistent npm settings are unchanged.\n");
|
|
187
|
+
else if (allowRemote) output.write("This npm does not expose the remote-download restriction; no unsupported permission flag was added.\n");
|
|
153
188
|
const environment = inspectEnvironmentFn({ env, platform });
|
|
154
189
|
if (environment?.state === "different") {
|
|
155
190
|
output.write(`Warning: npm targets ${terminalCell(environment.target)}, not the running package at ${terminalCell(environment.package_root)}. Existing PATH and prefix choices were preserved.\n`);
|
|
@@ -163,7 +198,13 @@ export async function runPackageUpdateCommand({
|
|
|
163
198
|
stdio: "inherit",
|
|
164
199
|
...launch.options,
|
|
165
200
|
});
|
|
166
|
-
await waitForExit(child);
|
|
201
|
+
try { await waitForExit(child); }
|
|
202
|
+
catch (error) {
|
|
203
|
+
if (Number.isInteger(error.npmExitCode) && !allowRemote && ["none", "root"].includes(policy.allowRemote)) {
|
|
204
|
+
error.message += `. npm allow-remote=${policy.allowRemote} was preserved. If npm reported EALLOWREMOTE, its registry/mirror tarball URL was refused; only if you trust this update and policy permits it, retry explicitly with ${terminalCell(commandName)} update ${selectedSource} --allow-remote. This grants URL downloads to this installation's dependency tree, not just one hostname. No automatic retry or config change was made.`;
|
|
205
|
+
}
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
167
208
|
const installedVersion = verifyInstalledFn(environment?.target, { expectedVersion: release?.version });
|
|
168
209
|
if (installedVersion) {
|
|
169
210
|
output.write(`Updated ${PACKAGE_NAME}: installed v${terminalCell(installedVersion)} at ${terminalCell(environment.target)}.\n`);
|
package/src/startup-ui.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { status } from "./status.mjs";
|
|
2
2
|
import { terminalCell } from "./terminal-text.mjs";
|
|
3
|
+
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
3
4
|
|
|
4
5
|
// The favicon's three ellipses, rasterized as terminal half-blocks. No runtime
|
|
5
6
|
// graphics library or terminal cursor control is needed.
|
|
@@ -45,10 +46,11 @@ export function startupLogger(name, output = console.log) {
|
|
|
45
46
|
|
|
46
47
|
export function predictionStartupCheck(prediction) {
|
|
47
48
|
if (!prediction?.configured) return startupCheck("info", "Prediction", "Off");
|
|
48
|
-
|
|
49
|
+
const details = prediction.environment ? `\n${startupCheck("info", "Environment", formatPredictionEnvironment(prediction.environment))}` : "";
|
|
50
|
+
if (prediction.bridge !== "running") return startupCheck("warn", "Prediction", prediction.reason || "Bridge unavailable; core service is available") + details;
|
|
49
51
|
const route = prediction.launch_route;
|
|
50
52
|
const summary = startupCheck(route === "unverified" ? "warn" : "info", "Prediction", route === "verified"
|
|
51
53
|
? "Bridge running; App route verified; suggestion not checked"
|
|
52
54
|
: "Bridge running; App route not verified; suggestion not checked");
|
|
53
|
-
return prediction.recovery ? `${summary}\n${startupCheck("info", "Recovery", `${prediction.recovery.attempts}/3 attempts used; persistent route ${prediction.persistence || "unknown"}`)}` : summary;
|
|
55
|
+
return (prediction.recovery ? `${summary}\n${startupCheck("info", "Recovery", `${prediction.recovery.attempts}/3 attempts used; persistent route ${prediction.persistence || "unknown"}`)}` : summary) + details;
|
|
54
56
|
}
|