codex-copilot-dx 0.9.24 → 0.9.26

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.
Files changed (40) hide show
  1. package/README.md +15 -12
  2. package/bin/cli.mjs +24 -32
  3. package/docs/ARCHITECTURE.md +69 -0
  4. package/docs/README.md +6 -0
  5. package/docs/REFERENCE.md +112 -10
  6. package/package.json +3 -2
  7. package/src/adapter.mjs +1 -0
  8. package/src/cli-image.mjs +13 -10
  9. package/src/cli-options.mjs +1 -1
  10. package/src/cli-status.mjs +5 -0
  11. package/src/client-integration.mjs +41 -0
  12. package/src/codex-config-doctor.mjs +3 -3
  13. package/src/codex-paths.mjs +10 -0
  14. package/src/codex-thread-compression.mjs +11 -6
  15. package/src/config.mjs +10 -6
  16. package/src/copilot-responses-compat.mjs +30 -2
  17. package/src/copilot-responses-policy.mjs +14 -3
  18. package/src/dashboard/index.html +18 -9
  19. package/src/dashboard/language.js +14 -0
  20. package/src/dashboard/ui.css +2 -0
  21. package/src/dashboard/ui.js +10 -0
  22. package/src/launcher.mjs +50 -2
  23. package/src/lock.mjs +29 -0
  24. package/src/native-prediction-profile.mjs +46 -23
  25. package/src/native-prediction-state.mjs +29 -0
  26. package/src/native-prediction-transport.mjs +24 -9
  27. package/src/native-prediction-windows.mjs +174 -0
  28. package/src/native-prediction.mjs +102 -28
  29. package/src/network-route.mjs +102 -0
  30. package/src/observability.mjs +2 -0
  31. package/src/operation-error.mjs +37 -0
  32. package/src/package-update.mjs +2 -3
  33. package/src/prediction-retirement.mjs +13 -2
  34. package/src/proxy-tunnel.mjs +102 -0
  35. package/src/responses-proxy.mjs +13 -3
  36. package/src/responses-request.mjs +35 -2
  37. package/src/user-settings.mjs +17 -4
  38. package/src/version.mjs +23 -46
  39. package/src/windows-prediction-network.cs +154 -0
  40. package/src/windows-prediction-network.mjs +123 -0
@@ -0,0 +1,41 @@
1
+ import { ensureCodexConfig } from "./config.mjs";
2
+ import { readImageProviderConfig } from "./image-provider-config.mjs";
3
+ import { ensureCodexThreadCompression } from "./codex-thread-compression.mjs";
4
+ import { runInBackground } from "./startup.mjs";
5
+ import { createPredictionState } from "./native-prediction-state.mjs";
6
+
7
+ // The CLI composes the services; this module owns optional client integration
8
+ // lifecycle. It never forwards model requests or depends on dashboard rendering.
9
+ export function createClientIntegration({ port, host, info = () => {}, warning = () => {} } = {}) {
10
+ const prediction = createPredictionState();
11
+ let native = null;
12
+ return {
13
+ async configure() {
14
+ try {
15
+ const { retirePredictionIntegration } = await import("./prediction-retirement.mjs");
16
+ const result = retirePredictionIntegration();
17
+ if (result.changed) info("Removed the retired CCDX prediction integration");
18
+ if (result.preserved) warning("Modified prediction settings were preserved");
19
+ } catch (error) { warning(`${error.message}. Core startup will continue.`); }
20
+ const enabled = Boolean(readImageProviderConfig());
21
+ const { imageMcpSkipped } = ensureCodexConfig(port, { host, imageProviderEnabled: enabled });
22
+ if (enabled && !imageMcpSkipped) {
23
+ try {
24
+ const { syncEnabledImageSkill } = await import("./cli-image.mjs");
25
+ syncEnabledImageSkill({ adapterPort: port, adapterHost: host });
26
+ } catch (error) { warning(`Image guidance could not be updated: ${error.message}`); }
27
+ }
28
+ return { compressionSetup: runInBackground(ensureCodexThreadCompression) };
29
+ },
30
+ async start() {
31
+ try {
32
+ const { startNativePrediction } = await import("./native-prediction.mjs");
33
+ native = await startNativePrediction({ state: prediction, warning: info });
34
+ } catch (error) { prediction.unavailable(error); warning(`${error.message}. Core startup will continue.`); }
35
+ return native;
36
+ },
37
+ pacUrl() { return native?.pacUrl || null; },
38
+ snapshot() { return { prediction: prediction.snapshot() }; },
39
+ async close() { await native?.close(); native = null; },
40
+ };
41
+ }
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
- import path from "node:path";
3
+ import { codexPaths } from "./codex-paths.mjs";
4
4
  import { isDeepStrictEqual } from "node:util";
5
5
  import { parse } from "smol-toml";
6
6
  import { computeUpdatedCodexConfig, initialCodexConfig } from "./config.mjs";
@@ -87,8 +87,8 @@ function checkUrl(value, expected, label) {
87
87
  : { kind: "warn", message: `${label} differs from the CCDX address ${expected}` };
88
88
  }
89
89
 
90
- export function inspectCodexConfig({ home = os.homedir(), host = "127.0.0.1", port = 2026 } = {}) {
91
- const filePath = path.join(home, ".codex", "config.toml");
90
+ export function inspectCodexConfig({ home = os.homedir(), env: processEnv = process.env, host = "127.0.0.1", port = 2026 } = {}) {
91
+ const filePath = codexPaths({ env: processEnv, home }).config;
92
92
  let content;
93
93
  try {
94
94
  content = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(fs.readFileSync(filePath));
@@ -0,0 +1,10 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ export function codexPaths({ env = process.env, home = os.homedir() } = {}) {
5
+ const directory = path.resolve(String(env.CODEX_HOME || "").trim() || path.join(home, ".codex"));
6
+ const profile = path.resolve(String(env.CODEX_ELECTRON_USER_DATA_PATH || "").trim()
7
+ || path.join(home, "Library", "Application Support", "Codex"));
8
+ return { directory, config: path.join(directory, "config.toml"), profile,
9
+ certificateStore: path.join(profile, "Default", "ServerCertificate") };
10
+ }
@@ -6,6 +6,8 @@ import { promisify } from "node:util";
6
6
  import { CODEX_APP_BINARY_PATHS } from "./codex-model-catalog.mjs";
7
7
  import { parseCodexToml, codexTomlStatements, validateManagedConfigEdit } from "./config-toml.mjs";
8
8
  import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
9
+ import { codexPaths } from "./codex-paths.mjs";
10
+ import { withFileLockSync } from "./lock.mjs";
9
11
  import { status } from "./status.mjs";
10
12
 
11
13
  const FEATURE = "local_thread_store_compression";
@@ -70,7 +72,8 @@ export async function codexNeedsThreadCompressionDefault({
70
72
  }
71
73
 
72
74
  export async function ensureCodexThreadCompression({
73
- filePath = path.join(os.homedir(), ".codex", "config.toml"),
75
+ env = process.env, home = os.homedir(),
76
+ filePath = codexPaths({ env, home }).config,
74
77
  probe = codexNeedsThreadCompressionDefault,
75
78
  } = {}) {
76
79
  try {
@@ -79,11 +82,13 @@ export async function ensureCodexThreadCompression({
79
82
  if (!await probe()) return;
80
83
  // The client/user may edit the shared file while the asynchronous probe runs.
81
84
  // Recompute against its current bytes; explicit opt-outs always win.
82
- const updated = computeThreadCompressionDefault(read());
83
- if (updated.changed) {
84
- atomicWriteFileIfChangedSync(filePath, updated.content);
85
- console.log(status("ok", "Enabled Codex local history compression (experimental)"));
86
- }
85
+ withFileLockSync(`${filePath}.ccdx.lock`, () => {
86
+ const updated = computeThreadCompressionDefault(read());
87
+ if (updated.changed) {
88
+ atomicWriteFileIfChangedSync(filePath, updated.content);
89
+ console.log(status("ok", "Enabled Codex local history compression (experimental)"));
90
+ }
91
+ });
87
92
  } catch {
88
93
  console.warn(status("warn", "Optional Codex history compression setup was skipped; core proxy remains available"));
89
94
  }
package/src/config.mjs CHANGED
@@ -1,13 +1,12 @@
1
1
  import fs from "node:fs";
2
- import path from "node:path";
3
- import os from "node:os";
4
2
  import { status } from "./status.mjs";
5
3
  import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
6
4
  import { adapterBaseUrl } from "./running-adapter.mjs";
7
5
  import { isLoopbackHost } from "./security.mjs";
8
6
  import { codexTomlStatements, configValue, parseCodexToml, validateManagedConfigEdit } from "./config-toml.mjs";
7
+ import { codexPaths } from "./codex-paths.mjs";
8
+ import { withFileLockSync } from "./lock.mjs";
9
9
 
10
- const CONFIG_PATH = path.join(os.homedir(), ".codex", "config.toml");
11
10
  const MODEL_CONTEXT_WINDOW = 1_000_000;
12
11
  const MODEL_AUTO_COMPACT_TOKEN_LIMIT = 900_000;
13
12
  const IMAGE_MCP_START = "# ccdx:image-mcp:start";
@@ -278,8 +277,13 @@ export function computeImageMcpCodexConfig(content, options = {}) {
278
277
  return computeImageConfig(content, options);
279
278
  }
280
279
 
281
- export function ensureCodexConfig(adapterPort = 2026, {
282
- filePath = CONFIG_PATH,
280
+ export function ensureCodexConfig(adapterPort = 2026, options = {}) {
281
+ const filePath = options.filePath || codexPaths(options).config;
282
+ return withFileLockSync(`${filePath}.ccdx.lock`, () => ensureCodexConfigUnlocked(adapterPort, { ...options, filePath }));
283
+ }
284
+
285
+ function ensureCodexConfigUnlocked(adapterPort = 2026, {
286
+ filePath,
283
287
  host = "127.0.0.1",
284
288
  imageProviderEnabled = false,
285
289
  } = {}) {
@@ -303,7 +307,7 @@ export function ensureCodexConfig(adapterPort = 2026, {
303
307
  console.log(status("ok", `Codex already points to ${baseUrl}`));
304
308
  } else {
305
309
  atomicWriteFileIfChangedSync(filePath, core.content);
306
- console.log(status("ok", content === undefined ? "Created ~/.codex/config.toml" : `Configured Codex base URL: ${baseUrl}`));
310
+ console.log(status("ok", content === undefined ? `Created Codex configuration: ${filePath}` : `Configured Codex base URL: ${baseUrl}`));
307
311
  }
308
312
  // Disabled means no image maintenance, including no implicit removal of old
309
313
  // or user-owned entries. Explicit disable-image owns the cleanup operation.
@@ -1,6 +1,7 @@
1
1
  import { responses as copilotResponses } from "./copilot.mjs";
2
2
  import {
3
3
  isEncryptedContentVerificationError,
4
+ isConnectionOwnedInputError,
4
5
  isImageNamespaceCollisionError,
5
6
  sanitizeImageNamespaceCollisionRequest,
6
7
  } from "./copilot-responses-policy.mjs";
@@ -12,7 +13,9 @@ import { httpError } from "./http-errors.mjs";
12
13
  import {
13
14
  finalizeEncryptedHistoryRebase,
14
15
  sanitizeEncryptedReasoningRequest,
16
+ sanitizeConnectionOwnedReasoningRequest,
15
17
  } from "./responses-request.mjs";
18
+ import { responseFailureDetails } from "./response-failures.mjs";
16
19
  import { status } from "./status.mjs";
17
20
  import { markUpstreamHeaders } from "./stream-performance.mjs";
18
21
 
@@ -20,6 +23,12 @@ import { markUpstreamHeaders } from "./stream-performance.mjs";
20
23
  // by an exact upstream failure plus a request transformation that changes the
21
24
  // payload. Generic Responses preparation does not decide whether to retry.
22
25
  const RETRY_POLICIES = Object.freeze([
26
+ Object.freeze({
27
+ id: "encrypted-connection-rejected",
28
+ matches: isConnectionOwnedInputError,
29
+ apply: sanitizeConnectionOwnedReasoningRequest,
30
+ warning: "saved reasoning belongs to an unavailable connection; retrying once with visible history preserved",
31
+ }),
23
32
  Object.freeze({
24
33
  id: "image-namespace-collision",
25
34
  matches: isImageNamespaceCollisionError,
@@ -28,7 +37,7 @@ const RETRY_POLICIES = Object.freeze([
28
37
  }),
29
38
  Object.freeze({
30
39
  id: "encrypted-replay-rejected",
31
- matches: isEncryptedContentVerificationError,
40
+ matches: (statusCode, text) => !isConnectionOwnedInputError(statusCode, text) && isEncryptedContentVerificationError(statusCode, text),
32
41
  apply: sanitizeEncryptedReasoningRequest,
33
42
  warning: "encrypted replay content rejected by upstream; retrying without unavailable encrypted content",
34
43
  }),
@@ -54,6 +63,10 @@ export function selectCopilotResponseRetry(
54
63
  policyId: policy.id,
55
64
  warning: policy.warning,
56
65
  usedPolicies,
66
+ ...(policy.id === "encrypted-connection-rejected" ? { recovery: {
67
+ reasoning_items_removed: reqContext.body.input.length - candidate.body.input.length,
68
+ compaction_items_removed: 0,
69
+ } } : {}),
57
70
  };
58
71
  }
59
72
  return null;
@@ -84,7 +97,22 @@ export async function openCopilotResponse(reqContext, upstream = copilotResponse
84
97
  label: "Copilot Responses error body",
85
98
  });
86
99
  options.assertPrepareActive?.();
87
- const retry = selectCopilotResponseRetry(reqContext, resp.status, errorText, usedPolicies);
100
+ let retry;
101
+ try { retry = selectCopilotResponseRetry(reqContext, resp.status, errorText, usedPolicies); }
102
+ catch (error) {
103
+ if (error.code === "ccdx_history_rebuild_required") {
104
+ const details = responseFailureDetails({ error: error.jsonBody.error }, "upstream.http_error", {
105
+ model: reqContext.body.model, headers: resp.headers, retrySkipped: error.code });
106
+ error.jsonBody.error.upstream_request_id = details.upstream_request_id;
107
+ options.responseFailures?.record?.({ ...details, recovery: error.jsonBody.error.recovery });
108
+ }
109
+ throw error;
110
+ }
111
+ if (retry?.policyId === "encrypted-connection-rejected") {
112
+ options.responseFailures?.record?.({ ...responseFailureDetails(JSON.parse(errorText), "upstream.http_error", {
113
+ model: reqContext.body.model, headers: resp.headers, retried: true, retryPolicy: retry.policyId }),
114
+ recovery: retry.recovery });
115
+ }
88
116
  if (retry) {
89
117
  reqContext = retry.reqContext;
90
118
  console.warn(status("warn", retry.warning));
@@ -1,10 +1,21 @@
1
+ import { errorEvidenceText } from "./operation-error.mjs";
2
+
1
3
  function cloneJson(value) {
2
4
  return value === undefined ? undefined : structuredClone(value);
3
5
  }
4
6
 
7
+ export function isConnectionOwnedInputError(statusCode, text) {
8
+ if (statusCode !== 400 || !text) return false;
9
+ try {
10
+ const error = JSON.parse(text)?.error;
11
+ return typeof error?.message === "string"
12
+ && error.message.trim().toLowerCase() === "input item does not belong to this connection";
13
+ } catch { return false; }
14
+ }
15
+
5
16
  export function isEncryptedContentVerificationError(statusCode, text) {
6
17
  if (statusCode < 400 || !text) return false;
7
- const lower = String(text).toLowerCase();
18
+ const lower = errorEvidenceText(text).toLowerCase();
8
19
  const reasoningFailure = lower.includes("encrypted content")
9
20
  && lower.includes("could not be verified")
10
21
  && (lower.includes("could not be decrypted") || lower.includes("could not be parsed"));
@@ -12,12 +23,12 @@ export function isEncryptedContentVerificationError(statusCode, text) {
12
23
  && lower.includes("could not be decrypted or decoded");
13
24
  const missingEncryptedContent = statusCode < 500
14
25
  && /missing required parameter:\s*(['"]?)input\[\d+\](?:\.[a-z0-9_]+|\[\d+\])*\.encrypted_content\1(?=\.?(?:\s|$|["},\]]))/.test(lower);
15
- return reasoningFailure || functionOutputFailure || missingEncryptedContent;
26
+ return reasoningFailure || functionOutputFailure || missingEncryptedContent || isConnectionOwnedInputError(statusCode, text);
16
27
  }
17
28
 
18
29
  export function isImageNamespaceCollisionError(statusCode, text) {
19
30
  if (statusCode < 400 || !text) return false;
20
- const lower = String(text).toLowerCase();
31
+ const lower = errorEvidenceText(text).toLowerCase();
21
32
  return lower.includes("namespace")
22
33
  && lower.includes("image_gen")
23
34
  && lower.includes("collid");
@@ -50,6 +50,13 @@
50
50
  </article>
51
51
  </section>
52
52
 
53
+ <details class="panel dashboard-section" id="client-features" open>
54
+ <summary class="panel-heading"><h2 data-i18n>CLIENT FEATURES</h2><span data-i18n>OBSERVED STATE</span></summary>
55
+ <dl class="stats"><div><dt data-i18n>Native predictions</dt><dd id="prediction-preference">—</dd></div><div><dt data-i18n>Local bridge</dt><dd id="prediction-bridge">—</dd></div><div><dt data-i18n>Client route</dt><dd id="prediction-route">—</dd></div><div><dt data-i18n>Visible candidate</dt><dd id="prediction-candidate">—</dd></div></dl>
56
+ <p id="prediction-note" class="hint">—</p>
57
+ <p class="hint" data-i18n>Configured does not mean displayed. Use ccdx prediction status for details.</p>
58
+ </details>
59
+
53
60
  <details class="panel dashboard-section" id="request-context">
54
61
  <summary data-i18n>RECENT REQUEST CONTEXT</summary>
55
62
  <p id="context-note" class="table-note">—</p>
@@ -57,15 +64,17 @@
57
64
  <p class="hint" data-i18n>Recent upstream request metadata, not exact live session occupancy. Missing values are unknown. No prompt or image content is retained.</p>
58
65
  </details>
59
66
 
60
- <section class="panel dashboard-section" aria-label="Live upstream models" data-i18n-label>
61
- <div class="panel-heading"><h2 data-i18n>UPSTREAM GPT MODELS</h2><div class="heading-actions"><span id="models-state" data-i18n>CHECKING LIVE</span><button id="refresh-models" type="button" data-i18n>Refresh</button></div></div>
67
+ <details class="panel dashboard-section" id="upstream-models" open>
68
+ <summary class="panel-heading"><h2 data-i18n>UPSTREAM GPT MODELS</h2><span id="models-state" data-i18n>CHECKING LIVE</span></summary>
69
+ <div class="section-actions"><button id="refresh-models" type="button" data-i18n>Refresh</button></div>
62
70
  <p id="models-note" class="table-note" data-i18n>Querying GitHub Copilot…</p>
63
71
  <div class="table-wrap"><table><thead><tr><th scope="col" data-i18n>MODEL</th><th scope="col" data-i18n>VENDOR</th><th scope="col" data-i18n>API</th><th scope="col" data-i18n>FLAG</th></tr></thead><tbody id="live-models-body"><tr><td colspan="4" data-i18n>Loading…</td></tr></tbody></table></div>
64
72
  <p class="hint" data-i18n>Catalog listing does not guarantee inference access.</p>
65
- </section>
73
+ </details>
66
74
 
67
- <section class="panel dashboard-section" aria-label="Usage by model" data-i18n-label>
68
- <div class="panel-heading"><h2 data-i18n>USAGE</h2><div class="heading-actions"><span id="usage-state" data-i18n>READING LOG</span><button id="clear-usage-day" type="button" hidden data-i18n>All history</button><button id="refresh-usage" type="button" data-i18n>Refresh</button></div></div>
75
+ <details class="panel dashboard-section" id="model-usage" open>
76
+ <summary class="panel-heading"><h2 data-i18n>USAGE</h2><span id="usage-state" data-i18n>READING LOG</span></summary>
77
+ <div class="section-actions"><button id="clear-usage-day" type="button" hidden data-i18n>All history</button><button id="refresh-usage" type="button" data-i18n>Refresh</button></div>
69
78
  <p id="usage-note" class="table-note" data-i18n>Aggregating local usage metadata…</p>
70
79
  <div class="table-wrap"><table class="usage-table"><thead><tr><th scope="col" data-i18n>MODEL</th><th scope="col" data-i18n>CALLS</th><th scope="col" data-i18n>INPUT</th><th scope="col" data-i18n>CACHE READ</th><th scope="col" data-i18n>OUTPUT</th><th scope="col" data-i18n>TOTAL</th><th scope="col" data-i18n>CACHE HIT</th></tr></thead><tbody id="usage-body"><tr><td colspan="7" data-i18n>Loading…</td></tr></tbody></table></div>
71
80
  <p class="hint" data-i18n>Cache hit = recorded cached / input tokens. ~ = incomplete history. — = unavailable or invalid counts.</p>
@@ -85,13 +94,13 @@
85
94
  <div class="calendar-scroll"><div class="calendar-grid"><div id="calendar-months" class="calendar-months" aria-hidden="true"></div><div id="activity-calendar" class="activity-calendar" aria-label="Daily recorded request activity" data-i18n-label></div></div></div>
86
95
  <p id="analytics-selection" class="hint" role="status" data-i18n>Select a day to inspect its model totals. No history is distinct from zero recorded calls.</p>
87
96
  </details>
88
- </section>
97
+ </details>
89
98
 
90
- <section class="lower" aria-label="Recent failures" data-i18n-label>
91
- <div class="panel-heading"><h2 data-i18n>RECENT RESPONSE FAILURES</h2><span id="failure-count">requests + events</span></div>
99
+ <details class="lower" id="recent-failures" open>
100
+ <summary class="panel-heading"><h2 data-i18n>RECENT RESPONSE FAILURES</h2><span id="failure-count">requests + events</span></summary>
92
101
  <ol id="failures"><li class="empty" data-i18n>Reading…</li></ol>
93
102
  <p class="hint" data-i18n>Upstream messages may contain sensitive text.</p>
94
- </section>
103
+ </details>
95
104
 
96
105
  <details id="animation-settings" class="panel dashboard-section settings-panel">
97
106
  <summary class="panel-heading"><h2 data-i18n>TERMINAL ANIMATION</h2><span id="animation-state" data-i18n>READING</span></summary>
@@ -1,5 +1,18 @@
1
1
  (() => {
2
2
  const translations = {
3
+ "CLIENT FEATURES": ["CLIENT FEATURES", "接入能力"],
4
+ "OBSERVED STATE": ["OBSERVED STATE", "实际状态"],
5
+ "Native predictions": ["Native predictions", "输入建议"],
6
+ "Local bridge": ["Local bridge", "本地接入"],
7
+ "Client route": ["Client route", "配置请求"],
8
+ "Visible candidate": ["Visible candidate", "显示结果"],
9
+ "Configured does not mean displayed. Use ccdx prediction status for details.": ["Enabled is not proof of a visible suggestion. Check ccdx prediction status.", "开启不等于已显示。\n终端命令可查看详情。"],
10
+ "Enabled": ["Enabled", "已开启"],
11
+ "Disabled": ["Disabled", "已关闭"],
12
+ "Running": ["Running", "运行中"],
13
+ "Stopped": ["Stopped", "未运行"],
14
+ "Unavailable": ["Unavailable", "不可用"],
15
+ "Observed": ["Observed", "已收到配置请求"],
3
16
  "First output": ["First output", "首次输出"],
4
17
  "Token time": ["Token time", "输出耗时"],
5
18
  "Gateway timing. Token time is estimated.": ["Observed at the gateway. Token time is an estimate.", "网关观测时间。\n每Token耗时为估算值。"],
@@ -141,6 +154,7 @@
141
154
  "retry": ["Retry status", "重试情况"],
142
155
  "retry_policy": ["Retry rule", "重试规则"],
143
156
  "retry_skipped": ["Skip reason", "跳过原因"],
157
+ "recovery": ["Recovery", "恢复处理"],
144
158
  "attempted (outcome not recorded here)": ["Retried; result not recorded here.", "已重试;这里未记录结果。"],
145
159
  "attempted": ["retried", "已重试"],
146
160
  "not attempted": ["not retried", "未重试"],
@@ -95,6 +95,8 @@ details > summary::marker { content: ""; }
95
95
  details > summary::before { content: "+"; color: var(--heading); font-weight: 700; letter-spacing: 0; }
96
96
  details[open] > summary::before { content: "−"; }
97
97
  .settings-panel > summary { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; }
98
+ .dashboard-section > summary.panel-heading, .lower > summary.panel-heading { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; }
99
+ .dashboard-section > summary.panel-heading span, .lower > summary.panel-heading span { white-space: normal; text-align: right; }
98
100
  .failure-detail { display: grid; grid-template-columns: minmax(110px, auto) minmax(0, 1fr); gap: 7px 18px; margin: 14px 0; line-height: 1.6; }
99
101
  .failure-detail dt { color: var(--muted); }
100
102
  .failure-detail dd { margin: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
@@ -96,6 +96,7 @@ function renderFailures(recent, recentRequests = []) {
96
96
  message: failure.message, response_id: failure.response_id, upstream_request_id: failure.upstream_request_id,
97
97
  retry: failure.retried ? (timeline ? "attempted" : "attempted (outcome not recorded here)") : "not attempted",
98
98
  retry_policy: failure.retry_policy, retry_skipped: failure.retry_skipped,
99
+ recovery: failure.recovery ? JSON.stringify(failure.recovery) : undefined,
99
100
  request_id: failure.request_id, outcome: timeline?.outcome, origin: timeline?.origin,
100
101
  phase: timeline?.phase, http_status: timeline?.http_status, upstream_attempts: timeline?.upstream_attempts,
101
102
  timings_ms: timingText };
@@ -168,6 +169,15 @@ function render(data) {
168
169
 
169
170
  renderFailures(data.response_failures?.recent, data.stream_performance?.recent_requests);
170
171
  renderContext(data.stream_performance);
172
+ if (element("prediction-preference")) {
173
+ const prediction = data.client_integrations?.prediction;
174
+ text("prediction-preference", prediction ? prediction.configured ? "Enabled" : "Disabled" : "Unknown");
175
+ text("prediction-bridge", ({ running: "Running", stopped: "Stopped", unavailable: "Unavailable" })[prediction?.bridge] || "Unknown");
176
+ text("prediction-route", prediction?.client_route === "observed" ? "Observed" : "Unknown");
177
+ text("prediction-candidate", "Unknown");
178
+ const note = element("prediction-note");
179
+ if (note) note.textContent = prediction?.reason || "";
180
+ }
171
181
  text("updated", "Snapshot {time}", { time: new Date().toLocaleTimeString() });
172
182
  }
173
183
 
package/src/launcher.mjs CHANGED
@@ -1,4 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { installedWindowsPredictionApp, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
2
5
  import { status } from "./status.mjs";
3
6
 
4
7
  export { ensureAuth } from "./auth.mjs";
@@ -36,9 +39,54 @@ export function launchAttempts() {
36
39
  return [["-b", CODEX_BUNDLE_ID], ...APP_PATH_CANDIDATES.map((path) => [path])];
37
40
  }
38
41
 
39
- export async function openCodex({ env = process.env, spawnImpl = spawn, platform = process.platform, predictionPacUrl = null, predictionApp = null } = {}) {
42
+ export async function openCodex({ env = process.env, spawnImpl = spawn, platform = process.platform, predictionPacUrl = null, predictionApp = null, predictionProfile = null,
43
+ resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses } = {}) {
44
+ if (platform === "win32" && autoLaunchEnabled(env) && typeof predictionPacUrl === "string"
45
+ && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(predictionPacUrl)
46
+ && typeof predictionApp === "string" && path.win32.isAbsolute(predictionApp)) {
47
+ try {
48
+ if (typeof predictionProfile !== "string" || !path.win32.isAbsolute(predictionProfile)
49
+ || /[\0\r\n]/.test(predictionProfile) || !fs.existsSync(path.win32.join(predictionProfile, "Local State"))) {
50
+ throw new Error("Verified Windows browser profile is unavailable; prediction launch was skipped");
51
+ }
52
+ const override = String(env.CODEX_ELECTRON_USER_DATA_PATH || "").trim();
53
+ if (override && path.win32.resolve(override).toLowerCase() !== path.win32.normalize(predictionProfile).toLowerCase()) {
54
+ throw new Error("Existing browser profile override differs from prediction trust; it was preserved");
55
+ }
56
+ const current = resolveWindowsApp({ env });
57
+ if (path.win32.normalize(current.app).toLowerCase() !== path.win32.normalize(predictionApp).toLowerCase()) {
58
+ throw new Error("Windows Codex App changed; prediction launch was skipped");
59
+ }
60
+ const running = windowsAppProcesses(current.app, { env });
61
+ if (running.length) {
62
+ if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
63
+ console.log(status("ok", "Running Codex App uses the current prediction route"));return true;
64
+ }
65
+ throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then run ccdx again; no process was stopped");
66
+ }
67
+ const launched = await new Promise(resolve => {
68
+ const child = spawnImpl(current.app, [`--user-data-dir=${predictionProfile}`, `--proxy-pac-url=${predictionPacUrl}`], {
69
+ cwd: path.win32.dirname(current.app), env: { ...env, CODEX_ELECTRON_USER_DATA_PATH: predictionProfile },
70
+ stdio: "ignore", detached: true, shell: false,
71
+ });
72
+ child.once("error", () => resolve(false));
73
+ child.once("spawn", () => { child.unref(); resolve(true); });
74
+ });
75
+ if (!launched) { console.log(status("warn", "Could not launch the registered Windows Codex App"));return false; }
76
+ await new Promise(resolve => setTimeout(resolve, 300));
77
+ const actual = windowsAppProcesses(current.app, { env });
78
+ const routeRetained = actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl;
79
+ console.log(status(routeRetained ? "info" : "warn", routeRetained
80
+ ? "Codex launch route verified; prediction status will show when configuration traffic is observed"
81
+ : "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
82
+ return routeRetained;
83
+ } catch (error) {
84
+ console.log(status("warn", `Optional Windows prediction launch skipped: ${error.message}`));
85
+ return false;
86
+ }
87
+ }
40
88
  if (platform !== "darwin") {
41
- console.log(status("warn", "Auto-launch is only supported on macOS"));
89
+ console.log(status("warn", "Automatic launch requires macOS or an enabled Windows prediction setup"));
42
90
  console.log(status("info", "Open Codex App manually; it will connect to the adapter."));
43
91
  return false;
44
92
  }
package/src/lock.mjs CHANGED
@@ -6,6 +6,35 @@ function sleep(ms) {
6
6
  return new Promise((resolve) => setTimeout(resolve, ms));
7
7
  }
8
8
 
9
+ // Synchronous configuration writers share the same cross-process lock format.
10
+ // Readers never take the lock. A live lock is never stolen on timeout.
11
+ export function withFileLockSync(lockPath, fn, { timeoutMs = 1000, staleMs = 60_000 } = {}) {
12
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true, mode: 0o700 });
13
+ const started = Date.now(), owner = randomUUID();
14
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
15
+ while (true) {
16
+ if (lockPathExists(reclaimGuardPath(lockPath), fs)) {
17
+ if (Date.now() - started >= timeoutMs) throw new Error("Configuration lock recovery is in progress; retry shortly");
18
+ Atomics.wait(sleeper, 0, 0, 10);
19
+ continue;
20
+ }
21
+ try {
22
+ const fd = writeLockRecord(lockPath, { pid: process.pid, owner, created_at: new Date().toISOString() }, fs);
23
+ fs.closeSync(fd);
24
+ if (lockPathExists(reclaimGuardPath(lockPath), fs)) { removeOwnedLock(lockPath, owner, fs); continue; }
25
+ break;
26
+ } catch (error) {
27
+ if (error.code !== "EEXIST") throw error;
28
+ if (maybeRemoveStaleLock(lockPath, staleMs, Date.now(), fs, processIsAlive)) continue;
29
+ let sameProcess = false;
30
+ try { sameProcess = readLockSnapshot(lockPath).pid === process.pid; } catch {}
31
+ if (sameProcess || Date.now() - started >= timeoutMs) throw new Error("Configuration is being updated by another operation; retry shortly");
32
+ Atomics.wait(sleeper, 0, 0, 10);
33
+ }
34
+ }
35
+ try { return fn(); } finally { removeOwnedLock(lockPath, owner, fs); }
36
+ }
37
+
9
38
  function readLockSnapshot(lockPath) {
10
39
  const stat = fs.statSync(lockPath);
11
40
  let record = {};
@@ -5,13 +5,22 @@ import { execFileSync } from "node:child_process";
5
5
  import { createHash, X509Certificate, createPrivateKey, createPublicKey } from "node:crypto";
6
6
  import { atomicWriteFileSync } from "./atomic-file.mjs";
7
7
  import { userSettingsPath } from "./user-settings.mjs";
8
+ import { resolveNetworkRoute } from "./network-route.mjs";
9
+ import { codexPaths } from "./codex-paths.mjs";
10
+ import { assertWindowsCodexClosed, installedWindowsPredictionApp, windowsPredictionProfile,
11
+ windowsPredictionOpenSSL, windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
8
12
 
9
- export function predictionPaths({ env = process.env, home = os.homedir() } = {}) {
13
+ export function predictionPaths({ env = process.env, home = os.homedir(), platform = process.platform, app } = {}) {
10
14
  const directory = path.join(path.dirname(userSettingsPath({ env, home })), "native-prediction");
11
- const profile = env.CODEX_ELECTRON_USER_DATA_PATH?.trim()
12
- || path.join(home, "Library", "Application Support", "Codex");
15
+ let { profile, certificateStore } = codexPaths({ env, home });
16
+ if (platform === "win32") {
17
+ const override = String(env.CODEX_ELECTRON_USER_DATA_PATH || "").trim();
18
+ profile = override ? path.resolve(override)
19
+ : app?.profile || path.join(env.APPDATA || path.join(home, "AppData", "Roaming"), "Codex");
20
+ certificateStore = path.join(profile, "Default", "ServerCertificate");
21
+ }
13
22
  return { directory, settings: path.join(directory, "settings.json"), profile,
14
- store: path.join(profile, "Default", "ServerCertificate") };
23
+ store: certificateStore };
15
24
  }
16
25
 
17
26
  export function readPredictionSettings(options = {}) {
@@ -31,14 +40,11 @@ export function writePredictionSettings(value, options = {}) {
31
40
  }
32
41
 
33
42
  export function assertPredictionProxyCompatible({ env = process.env, systemProxy = "" } = {}) {
34
- if (["HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy", "CODEX_API_BASE_URL"]
35
- .some((key) => env[key]?.trim())
36
- || /(?:HTTPEnable|HTTPSEnable|SOCKSEnable|ProxyAutoConfigEnable|ProxyAutoDiscoveryEnable)\s*:\s*1/.test(systemProxy)) {
37
- throw new Error("Native prediction setup skipped: an existing proxy or API route is configured; it was not replaced");
38
- }
43
+ return resolveNetworkRoute({ env, systemProxy });
39
44
  }
40
45
 
41
- export function assertCodexClosed({ exec = execFileSync } = {}) {
46
+ export function assertCodexClosed({ exec = execFileSync, platform = process.platform, ...options } = {}) {
47
+ if (platform === "win32") return assertWindowsCodexClosed({ ...options, exec });
42
48
  for (const name of ["ChatGPT", "Codex"]) {
43
49
  try {
44
50
  exec("/usr/bin/pgrep", ["-x", name], { stdio: "pipe", timeout: 2000 });
@@ -50,9 +56,11 @@ export function assertCodexClosed({ exec = execFileSync } = {}) {
50
56
  }
51
57
  }
52
58
 
53
- export function installedPredictionApp({ exec = execFileSync } = {}) {
54
- for (const app of ["/Applications/ChatGPT.app", "/Applications/Codex.app"]) {
55
- const archive = path.join(app, "Contents", "Resources", "app.asar");
59
+ export function installedPredictionApp({ exec = execFileSync, platform = process.platform, ...options } = {}) {
60
+ const candidates = platform === "win32" ? [installedWindowsPredictionApp({ ...options, exec })]
61
+ : ["/Applications/ChatGPT.app", "/Applications/Codex.app"].map(app => ({ app, archive: path.join(app, "Contents", "Resources", "app.asar") }));
62
+ for (const candidate of candidates) {
63
+ const { app, archive } = candidate;
56
64
  if (!fs.existsSync(archive)) continue;
57
65
  // Check only during explicit setup; startup uses the cheap identity check.
58
66
  const fd = fs.openSync(archive, "r");
@@ -74,8 +82,13 @@ export function installedPredictionApp({ exec = execFileSync } = {}) {
74
82
  const rendererBytes = Buffer.alloc(renderer.size);
75
83
  fs.readSync(fd, rendererBytes, 0, rendererBytes.length, 8 + prefix.readUInt32LE(4) + Number(renderer.offset));
76
84
  if (!rendererBytes.includes(Buffer.from("4290031608"))) continue;
77
- exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
85
+ if (platform !== "win32") exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
78
86
  const stat = fs.statSync(archive);
87
+ if (platform === "win32") {
88
+ const executable = fs.statSync(app);
89
+ return { ...candidate, profile: windowsPredictionProfile({ app: candidate, env: options.env, preferredProfile: options.preferredProfile }),
90
+ size: stat.size, mtimeMs: stat.mtimeMs, executableSize: executable.size, executableMtimeMs: executable.mtimeMs };
91
+ }
79
92
  return { app, archive, size: stat.size, mtimeMs: stat.mtimeMs };
80
93
  } finally { fs.closeSync(fd); }
81
94
  }
@@ -83,24 +96,33 @@ export function installedPredictionApp({ exec = execFileSync } = {}) {
83
96
  }
84
97
 
85
98
  export function predictionAppMatches(app) {
86
- try { const stat = fs.statSync(app.archive); return stat.size === app.size && stat.mtimeMs === app.mtimeMs; }
99
+ try {
100
+ const stat = fs.statSync(app.archive);
101
+ if (app.executableSize !== undefined) {
102
+ const executable = fs.statSync(app.app);
103
+ if (executable.size !== app.executableSize || executable.mtimeMs !== app.executableMtimeMs) return false;
104
+ }
105
+ return stat.size === app.size && stat.mtimeMs === app.mtimeMs;
106
+ }
87
107
  catch { return false; }
88
108
  }
89
109
 
90
- function privateDirectory(directory) {
110
+ function privateDirectory(directory, { platform = process.platform, ...options } = {}) {
91
111
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
92
112
  const stat = fs.lstatSync(directory);
93
- if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077)) {
113
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (platform !== "win32" && (stat.mode & 0o077))) {
94
114
  throw new Error("Prediction key directory must be private and must not be a symlink");
95
115
  }
116
+ if (platform === "win32") windowsPrivatePredictionPath(directory, { ...options, create: fs.readdirSync(directory).length === 0 });
96
117
  }
97
118
 
98
- export function readPredictionCertificate(directory, { allowExpired = false } = {}) {
119
+ export function readPredictionCertificate(directory, { allowExpired = false, platform = process.platform, ...options } = {}) {
99
120
  const cert = fs.readFileSync(path.join(directory, "bridge.pem"));
100
121
  const ca = new X509Certificate(fs.readFileSync(path.join(directory, "ca.pem")));
101
122
  const keyFile = path.join(directory, "bridge.key");
102
123
  const info = fs.lstatSync(keyFile);
103
- if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o077)) throw new Error("Prediction key is not private");
124
+ if (!info.isFile() || info.isSymbolicLink() || (platform !== "win32" && (info.mode & 0o077))) throw new Error("Prediction key is not private");
125
+ if (platform === "win32") windowsPrivatePredictionPath(keyFile, options);
104
126
  const key = fs.readFileSync(keyFile);
105
127
  const x509 = new X509Certificate(cert);
106
128
  const publicKey = createPublicKey(createPrivateKey(key)).export({ type: "spki", format: "der" });
@@ -112,8 +134,9 @@ export function readPredictionCertificate(directory, { allowExpired = false } =
112
134
  return { cert, key, ca: ca.toString(), hash: createHash("sha256").update(ca.raw).digest("hex").toUpperCase(), der: ca.raw };
113
135
  }
114
136
 
115
- export function createPredictionCertificate(directory, { exec = execFileSync } = {}) {
116
- privateDirectory(directory);
137
+ export function createPredictionCertificate(directory, { exec = execFileSync, platform = process.platform, ...options } = {}) {
138
+ privateDirectory(directory, { ...options, exec, platform });
139
+ const openssl = platform === "win32" ? windowsPredictionOpenSSL({ ...options, exec }) : "/usr/bin/openssl";
117
140
  const temporary = fs.mkdtempSync(path.join(directory, "certificate-"));
118
141
  try {
119
142
  const config = `[req]\nprompt=no\ndistinguished_name=dn\nx509_extensions=ext\n[dn]\nCN=CCDX native prediction local bridge\n[ext]\nbasicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:chatgpt.com,DNS:ab.chatgpt.com\nnameConstraints=critical,permitted;DNS:chatgpt.com\n`;
@@ -121,7 +144,7 @@ export function createPredictionCertificate(directory, { exec = execFileSync } =
121
144
  atomicWriteFileSync(configFile, config);
122
145
  const certFile = path.join(temporary, "cert.pem"), keyFile = path.join(temporary, "key.pem");
123
146
  const caFile = path.join(temporary, "ca.pem"), caKey = path.join(temporary, "ca.key");
124
- const run = (args) => exec("/usr/bin/openssl", args, { stdio: "pipe", timeout: 15_000 });
147
+ const run = (args) => exec(openssl, args, { stdio: "pipe", timeout: 15_000, windowsHide: true });
125
148
  run(["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "90", "-config", configFile, "-out", caFile, "-keyout", caKey]);
126
149
  const csr = path.join(temporary, "leaf.csr"), extensions = path.join(temporary, "leaf.cnf");
127
150
  atomicWriteFileSync(extensions, "basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:chatgpt.com,DNS:ab.chatgpt.com\n");
@@ -130,7 +153,7 @@ export function createPredictionCertificate(directory, { exec = execFileSync } =
130
153
  atomicWriteFileSync(path.join(directory, "bridge.key"), fs.readFileSync(keyFile), { preserveMode: false });
131
154
  atomicWriteFileSync(path.join(directory, "bridge.pem"), fs.readFileSync(certFile), { preserveMode: false });
132
155
  atomicWriteFileSync(path.join(directory, "ca.pem"), fs.readFileSync(caFile), { preserveMode: false });
133
- return readPredictionCertificate(directory);
156
+ return readPredictionCertificate(directory, { ...options, exec, platform });
134
157
  } finally { fs.rmSync(temporary, { recursive: true, force: true }); }
135
158
  }
136
159