codex-copilot-dx 1.3.18 → 1.3.19
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/docs/ARCHITECTURE.md +8 -0
- package/docs/REFERENCE.md +11 -4
- package/package.json +1 -1
- package/src/claude-gateway.mjs +4 -2
- package/src/clients/codex-models.mjs +17 -6
- package/src/codex-app-control.mjs +67 -0
- package/src/codex-launch-control.mjs +132 -0
- package/src/connection-runtime.mjs +1 -1
- package/src/dashboard/console.js +2 -2
- package/src/dashboard/features.js +55 -10
- package/src/dashboard/index.html +2 -0
- package/src/dashboard/language.js +28 -0
- package/src/dashboard/status.js +5 -1
- package/src/http-transport.mjs +1 -1
- package/src/image-control.mjs +11 -24
- package/src/image-host-state.mjs +3 -1
- package/src/native-images.mjs +12 -7
- package/src/providers/api-token-count.mjs +12 -2
- package/src/providers/api.mjs +9 -4
- package/src/response-failures.mjs +8 -3
- package/src/safe-upstream-error.mjs +79 -0
- package/src/service-control.mjs +18 -5
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -1124,3 +1124,11 @@ Native image failures cancel the vendor response and project safe JSON; API Resp
|
|
|
1124
1124
|
The stdio host uses a paused-source line pump only while a destination is blocked or a frame requires asynchronous work. Passthrough stays synchronous. Both directions serialize destination writes; output batching is bounded by the destination high-water mark plus one complete frame. Child close, input cancellation and stdout drain are coordinated before removing listeners. Host-tool registration, image return items, account/approval traffic and App launch ownership are unchanged.
|
|
1125
1125
|
|
|
1126
1126
|
`bounded-file.mjs` and `atomic-file.mjs` provide asynchronous bounded reads and durable single/paired writes for request-path state. Other synchronous configuration callers retain their APIs. Conversation admission and company-account guards use abortable asynchronous lock waiting with their prior timeout/stale policy. Messages transfer plans reserve in-process ownership while committing; primary and marker writes retain rollback behavior. JSON/SSE delivery awaits the applicable commit, and settled source checks keep a synchronous cached path. No new cache, file format or provider-selection policy is introduced.
|
|
1127
|
+
|
|
1128
|
+
## Shared Codex App restart and source reliability (1.3.19)
|
|
1129
|
+
|
|
1130
|
+
The image and input-suggestion panels share `codex-launch-control.mjs`. `codex-app-control.mjs` associates live host reports with the verified macOS App by process ancestry and checks its prediction PAC argument without treating another process's host or an unobserved chat as proof. Its AppKit control targets only the verified bundle path and PID. A restart requires an explicit user action, prepares enabled routes, asks the App to quit normally, waits for exit, applies any pending prediction display setting and then uses the existing launcher. A refusal, unknown identity, multiple Apps or timeout stops the action without force-quit. A failed post-close display write stays pending and is reported after the App is reopened. Host evidence is accepted independently of serialized settings operations so a restarting App's short-lived report is not lost behind its own restart. Later host tool events also re-establish evidence if CCDX restarted while the host remained live.
|
|
1131
|
+
|
|
1132
|
+
The managed Codex catalog projects explicit source input modalities ahead of native templates and checks GitHub priority eligibility against the full live source registry. Unknown modality metadata keeps the prior fallback. Source identities, selected models and routing remain unchanged.
|
|
1133
|
+
|
|
1134
|
+
`safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks release request admission before the optional body read; image processing slots are released at the same point. Count-token singleflight forwards those callbacks only to the appropriate waiters. Successful requests never invoke the reader.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -208,6 +208,11 @@ metadata and records a bounded error; a changed endpoint/key invalidates prior
|
|
|
208
208
|
catalog evidence. A listing or minimal successful reply is not a capability test.
|
|
209
209
|
Ordinary page reads use saved data and never probe each model. No public model-name
|
|
210
210
|
heuristic or original-vendor limit is applied to an arbitrary relay deployment.
|
|
211
|
+
The managed Codex catalog uses an explicitly declared input modality in preference
|
|
212
|
+
to the native template. Unknown modalities retain the existing template fallback.
|
|
213
|
+
For GitHub models, fast/priority tiers are shown only when the full source catalog
|
|
214
|
+
supports the existing priority route, including an eligible fast variant that is
|
|
215
|
+
not itself selected in the model picker.
|
|
211
216
|
|
|
212
217
|
Claude configuration and gateway catalogs use the same compiled model plan.
|
|
213
218
|
Explicit App bindings use opaque source-qualified aliases and actual model/source
|
|
@@ -274,7 +279,7 @@ CLI-only interaction forms include JSON output, file input, key stdin and shell
|
|
|
274
279
|
|
|
275
280
|
## Prediction controls
|
|
276
281
|
|
|
277
|
-
WebUI → Codex → Input suggestions is the complete enable/disable control. Setup and explicit enable write only `desktop.composer-predictions-enabled` in Codex TOML and its legacy persisted-atom equivalent; unrelated configuration/state remains intact. Writes require Codex to be closed. An open App keeps a pending display change
|
|
282
|
+
WebUI → Codex → Input suggestions is the complete enable/disable control. Setup and explicit enable write only `desktop.composer-predictions-enabled` in Codex TOML and its legacy persisted-atom equivalent; unrelated configuration/state remains intact. Writes require Codex to be closed. An open App keeps a pending display change. On macOS, the WebUI can apply it during an explicitly requested normal Codex restart; alternatively, quit the App and Continue setup. Windows retains its existing open and manual-close flow. No running App is forcibly closed.
|
|
278
283
|
|
|
279
284
|
Native configuration and startup environment checks use temporary work threads so OS/crypto work does not block the core service. Missing Apps are checked before trust/proxy setup. A normal cold startup attempts setup once when no CCDX prediction record exists, prediction access is allowed, and the App display preference is not saved off. Failed setup leaves core startup available and can be completed in WebUI. Saved off records and App off choices are preserved. Explicit enable intentionally overrides a prior App display-off setting. Repair keeps the selected on/off intent. Disable retains trust and routing; Remove setup owns trust/route cleanup and may defer cleanup until Codex closes. Visible predictions still require native App/thread eligibility and an actual returned suggestion.
|
|
280
285
|
|
|
@@ -580,7 +585,7 @@ was recreated on the original address, not that gray text appeared.
|
|
|
580
585
|
|
|
581
586
|
## Error delivery and conversation commits
|
|
582
587
|
|
|
583
|
-
Image
|
|
588
|
+
Image and custom API HTTP errors keep their stable `ccdx_images_http_<status>` or `ccdx_api_http_<status>` code, status and validated Retry-After. A failure-only reader can retain a small allowlist of structured source codes in `upstream_code`; source messages and bodies are not forwarded. Reads are limited to 64 KiB and a 200 ms timer, with at most four concurrent readers. Unknown or unfinished bodies fall back to the existing generic error. Request admission and image-generation slots are released before this optional read. Successful responses do not enter the reader. These changes do not introduce retries.
|
|
584
589
|
|
|
585
590
|
Conversation-source admission and Messages checkpoint commits wait asynchronously for the existing cross-process locks. Cancellation ends lock waits. Checkpoint writes retain the primary/marker ordering and rollback behavior; the gateway awaits a successful commit before forwarding corresponding usable JSON or SSE output. Cached source checks keep their synchronous fast path. CLI configuration writers retain their existing synchronous behavior.
|
|
586
591
|
|
|
@@ -590,13 +595,15 @@ The native image host uses the current CCDX address for separate Images API requ
|
|
|
590
595
|
|
|
591
596
|
On macOS with Codex 0.166 or later, CCDX launches the unchanged Codex CLI through a local stdio host adapter. The adapter registers `ccdx_images.imagegen` using Codex’s native `dynamicTools` interface. Codex emits native tool progress and includes image content in the chat history; display in the signed App depends on the client and requires a real-window check. CCDX saves image files under the active Codex home’s `generated_images/ccdx/` directory and uses these files for later edits, including after a host restart. No separate image address or key, image MCP registration, or CCDX image skill is required. Windows continues to expose the Images API; automatic host activation on Windows is not yet provided.
|
|
592
597
|
|
|
593
|
-
The Web UI image panel and terminal `check`, `repair`, and `open` controls
|
|
598
|
+
The Web UI image panel and terminal `check`, `repair`, and `open` controls use the service's image setup and launch controls. `check` verifies the Node loopback response with a fresh nonce and checks the launcher and runtime evidence; it does not prove the Codex App's proxy route. `repair` prepares owned launch files and client configuration without opening or closing the App. The terminal `open` command opens Codex only when it is closed. Disabled image settings and custom launch routes are preserved.
|
|
599
|
+
|
|
600
|
+
On macOS, the image and input-suggestion panels use the same App state and launch control. If Codex is closed, the button opens it; if the enabled integrations are ready, it switches to Codex; if they need a restart or their route is unconfirmed, it offers **Restart Codex to connect** with a warning that running tasks can be interrupted. The restart happens only when that button is clicked. CCDX prepares enabled routes first, requests a normal App exit, waits for it to close, applies a pending suggestion display change, and opens it through the existing launcher. It does not force-quit the App or restart CCDX. If the App refuses to close, its identity changes, or preparation fails, the action stops and reports the reason. If a post-close display change fails, CCDX retains it as pending and reports it when reopening. A successful launch request does not prove that the current chat has the image tool; an older chat without the tool still needs a new chat.
|
|
594
601
|
|
|
595
602
|
The stdio host pauses each input source when its destination is blocked or an asynchronous frame operation is pending. Ordinary frames retain their synchronous path and original wire text; output batching follows the destination high-water mark. Shutdown waits for child close and queued stdout delivery, including a final frame without a newline. No arbitrary new protocol-frame byte limit is imposed.
|
|
596
603
|
|
|
597
604
|
The runtime separately reports host initialization, accepted new-chat registration and image-call outcomes. Reports contain only host PID, anonymous host/chat identifiers, event type and time, remain in bounded process memory, and are not an automatic image-generation probe. Registration evidence applies to observed chats, not every existing conversation. Dead host processes are unconfirmed. The TUI exposes the repair command; terminal image status includes the same host state. Request details show anonymous session correlation and the previous retained request's outcome when supplied session metadata allows it; missing identity stays unassigned.
|
|
598
605
|
|
|
599
|
-
The adapter uses `CODEX_CLI_PATH` only for the App launch requested by CCDX. It does not modify App binaries, ChatGPT authentication files, credential storage mode or account-plan declarations. All other app-server traffic, including Apps and approval requests, passes through to the original CLI. Existing custom CLI routes and unowned launcher files are preserved. A running App retains its existing launch environment.
|
|
606
|
+
The adapter uses `CODEX_CLI_PATH` only for the App launch requested by CCDX. It does not modify App binaries, ChatGPT authentication files, credential storage mode or account-plan declarations. All other app-server traffic, including Apps and approval requests, passes through to the original CLI. Existing custom CLI routes and unowned launcher files are preserved. A running App retains its existing launch environment. Use the image panel's explicit restart when that App has not loaded the host, then use a new chat if the existing chat lacks the tool. CCDX does not forcibly restart the App. Native built-in image tool availability still depends on the installed client and thread. A successful direct API request alone does not establish visible App behavior.
|
|
600
607
|
|
|
601
608
|
The WebUI’s image switch is on by default and pauses or resumes new requests. A previously saved off choice is preserved. Available GHC image models appear below the switch; multiple models use one radio selection. The same image purpose appears in Model sources and Codex model configuration. Image models stay out of Codex’s conversation-model picker and conversation default selection. Saved pause choices survive upgrades, and active calls may finish. The CLI uses the same preference:
|
|
602
609
|
|
package/package.json
CHANGED
package/src/claude-gateway.mjs
CHANGED
|
@@ -179,7 +179,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
179
179
|
if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
|
|
180
180
|
terminalOrigin = "transport";
|
|
181
181
|
const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
|
|
182
|
+
let upstreamHeadersObserved = false;
|
|
182
183
|
const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
|
|
184
|
+
onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
|
|
183
185
|
onCountObservation(value) {
|
|
184
186
|
context.countObservation = { ...context.countObservation, ...value };
|
|
185
187
|
if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
|
|
@@ -201,7 +203,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
201
203
|
} else upstream = await call(body, callOptions);
|
|
202
204
|
body = null;
|
|
203
205
|
terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
|
|
204
|
-
tracker?.upstreamHeaders(upstream.status);
|
|
206
|
+
if (!upstreamHeadersObserved) tracker?.upstreamHeaders(upstream.status);
|
|
205
207
|
release();release = () => {};
|
|
206
208
|
try { onRequest({ client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude" }); } catch {}
|
|
207
209
|
const headers = safeUpstreamResponseHeaders(upstream.headers);
|
|
@@ -217,7 +219,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
217
219
|
const evidence = upstreamErrorEvidence(raw);
|
|
218
220
|
context.onHttpError?.({ ...evidence, code: evidence.code || evidence.error_type || "upstream_error", model_error: true, origin: "upstream_response", headers: upstream.headers });
|
|
219
221
|
}
|
|
220
|
-
if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
|
|
222
|
+
if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw, { status: upstream.status }),
|
|
221
223
|
origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
|
|
222
224
|
if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
|
|
223
225
|
if (value.content.some(hasMessageState)) await conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
|
|
@@ -1,19 +1,30 @@
|
|
|
1
|
+
import { resolveCopilotPriorityTierModel } from "../models.mjs";
|
|
2
|
+
|
|
1
3
|
// Codex's native catalog is an application projection, not provider metadata.
|
|
2
4
|
export function codexModelEntry(model, { priority = 0, name = "", template = {} } = {}) {
|
|
3
5
|
const values = model.capability?.values || {}, efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
|
|
4
6
|
return { shell_type: "unified_exec", availability_nux: null, upgrade: null, additional_speed_tiers: [], service_tiers: [],
|
|
5
7
|
base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
|
|
6
8
|
supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
|
|
7
|
-
experimental_supported_tools: [],
|
|
9
|
+
experimental_supported_tools: [], ...template,
|
|
10
|
+
input_modalities: values.input_modalities || template.input_modalities || ["text"],
|
|
8
11
|
slug: model.public_id || model.id, display_name: model.display_name || template.display_name || model.name || model.id, description: model.description || template.description || name, visibility: "list", supported_in_api: true, priority,
|
|
9
12
|
default_reasoning_level: efforts[0] || null, supported_reasoning_levels: efforts.map(effort => ({ effort, description: effort })),
|
|
10
13
|
context_window: values.context_window || template.context_window || null, max_context_window: values.context_window || template.max_context_window || null };
|
|
11
14
|
}
|
|
12
|
-
export function codexClientCatalog(plan) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
export function codexClientCatalog(plan, githubModels = () => null) {
|
|
16
|
+
const needsNativeCatalog = plan.models.some(model => model.source_id === "github");
|
|
17
|
+
return Object.assign((value, nativeCatalog) => {
|
|
18
|
+
const github = needsNativeCatalog ? githubModels() : null;
|
|
19
|
+
return { ...value, models: plan.models.map((model, priority) => {
|
|
20
|
+
const template = model.source_id === "github" ? nativeCatalog?.models?.find(entry => entry.slug === model.id) : undefined;
|
|
21
|
+
const entry = codexModelEntry(model, { priority, template, name: model.source_name || model.source_id });
|
|
22
|
+
if (model.source_id === "github" && !resolveCopilotPriorityTierModel(model.id, "priority", github)) {
|
|
23
|
+
entry.additional_speed_tiers = [];entry.service_tiers = [];delete entry.default_service_tier;
|
|
24
|
+
}
|
|
25
|
+
return entry;
|
|
26
|
+
}) };
|
|
27
|
+
}, { needsNativeCatalog });
|
|
17
28
|
}
|
|
18
29
|
|
|
19
30
|
export function codexSourceCatalog(source) {
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { isPredictionPacUrl } from "./prediction-pac.mjs";
|
|
4
|
+
|
|
5
|
+
const execute = promisify(execFile);
|
|
6
|
+
const apps = new Set(["/Applications/Codex.app", "/Applications/ChatGPT.app"]);
|
|
7
|
+
|
|
8
|
+
// AppKit asks an existing application to quit normally or become active. It
|
|
9
|
+
// never launches a new process and never force-quits an application.
|
|
10
|
+
const appScript = `ObjC.import("AppKit");
|
|
11
|
+
function run(argv) {
|
|
12
|
+
var app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(argv[0]));
|
|
13
|
+
if (app.isNil()) return "absent";
|
|
14
|
+
if (ObjC.unwrap(app.bundleIdentifier) !== "com.openai.codex" || ObjC.unwrap(app.bundleURL.path) !== argv[1]) return "different";
|
|
15
|
+
var sent = argv[2] === "quit" ? app.terminate : app.activateWithOptions($.NSApplicationActivateIgnoringOtherApps);
|
|
16
|
+
return sent ? "sent" : "refused";
|
|
17
|
+
}`;
|
|
18
|
+
|
|
19
|
+
export async function inspectCodexApp(app, hosts = [], { platform = process.platform, exec = execute, predictionPacUrl } = {}) {
|
|
20
|
+
if (platform !== "darwin") return { status: "unsupported" };
|
|
21
|
+
if (!apps.has(app)) throw new Error("Unrecognized Codex App path");
|
|
22
|
+
const result = await exec("/bin/ps", ["-axo", "pid=,ppid=,comm="], { encoding: "utf8", timeout: 3000, maxBuffer: 4 * 1024 * 1024 });
|
|
23
|
+
const processes = new Map();
|
|
24
|
+
for (const line of String(result?.stdout ?? result).split("\n")) {
|
|
25
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
|
|
26
|
+
if (match) processes.set(Number(match[1]), { pid: Number(match[1]), parent: Number(match[2]), command: match[3] });
|
|
27
|
+
}
|
|
28
|
+
const matches = [...processes.values()].filter(row => [`${app}/Contents/MacOS/ChatGPT`, `${app}/Contents/MacOS/Codex`].includes(row.command));
|
|
29
|
+
if (!matches.length) return { status: "stopped" };
|
|
30
|
+
if (matches.length !== 1) return { status: "multiple" };
|
|
31
|
+
const pid = matches[0].pid;
|
|
32
|
+
const belongsToApp = host => {
|
|
33
|
+
if (!host.connected) return false;
|
|
34
|
+
let node = processes.get(host.pid);const visited = new Set();
|
|
35
|
+
while (node && !visited.has(node.pid)) {
|
|
36
|
+
if (node.pid === pid) return true;
|
|
37
|
+
visited.add(node.pid);node = processes.get(node.parent);
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
};
|
|
41
|
+
const linked = hosts.filter(belongsToApp);
|
|
42
|
+
let predictionRoute;
|
|
43
|
+
if (isPredictionPacUrl(predictionPacUrl)) {
|
|
44
|
+
predictionRoute = "unconfirmed";
|
|
45
|
+
try {
|
|
46
|
+
const result = await exec("/bin/ps", ["-p", String(pid), "-o", "args="], { encoding: "utf8", timeout: 3000, maxBuffer: 64 * 1024 });
|
|
47
|
+
const args = String(result?.stdout ?? result).trim(), executable = matches[0].command;
|
|
48
|
+
const route = /(?:^|\s)--proxy-pac-url=(?:"(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?)"|(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?)(?=\s|$))/.exec(args);
|
|
49
|
+
if ((args === executable || args.startsWith(executable + " ")) && (args.match(/(?:^|\s)--proxy-pac-url=/g) || []).length === 1
|
|
50
|
+
&& (route?.[1] || route?.[2]) === predictionPacUrl) predictionRoute = "verified";
|
|
51
|
+
} catch { /* A missing route is not proof that the App uses one. */ }
|
|
52
|
+
}
|
|
53
|
+
return { status: "running", pid, host: linked.length ? "connected" : "unconfirmed",
|
|
54
|
+
...(predictionRoute ? { prediction_route: predictionRoute } : {}),
|
|
55
|
+
tool_registration: linked.some(host => host.threads?.length) ? "observed" : "unconfirmed" };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function controlCodexApp(app, pid, action, { platform = process.platform, exec = execute } = {}) {
|
|
59
|
+
if (platform !== "darwin" || !apps.has(app) || !Number.isSafeInteger(pid) || pid <= 0 || !["quit", "activate"].includes(action)) {
|
|
60
|
+
throw new Error("Invalid Codex App control request");
|
|
61
|
+
}
|
|
62
|
+
const result = await exec("/usr/bin/osascript", ["-l", "JavaScript", "-e", appScript, String(pid), app, action],
|
|
63
|
+
{ encoding: "utf8", timeout: 5000, maxBuffer: 4096 });
|
|
64
|
+
const value = String(result?.stdout ?? result).trim();
|
|
65
|
+
if (!["sent", "absent", "different", "refused"].includes(value)) throw new Error("Could not control the verified Codex App");
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { prepareImageHostLaunch } from "./codex-image-host-launch.mjs";
|
|
2
|
+
import { imageSetupSummary } from "./image-setup.mjs";
|
|
3
|
+
import { openCodex } from "./launcher.mjs";
|
|
4
|
+
import { installedPredictionApp } from "./native-prediction-app.mjs";
|
|
5
|
+
import { inspectCodexApp, controlCodexApp } from "./codex-app-control.mjs";
|
|
6
|
+
import { predictionControlSnapshot } from "./prediction-control.mjs";
|
|
7
|
+
import { predictionPaths, readPredictionSettings, writePredictionSettings } from "./native-prediction-profile.mjs";
|
|
8
|
+
import { servicePreferences } from "./user-settings.mjs";
|
|
9
|
+
import { runPredictionOperation } from "./prediction-operations.mjs";
|
|
10
|
+
import { withFileLock } from "./lock.mjs";
|
|
11
|
+
|
|
12
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
13
|
+
const publicAppState = value => ({ status: value.status, ...(value.host ? { host: value.host } : {}),
|
|
14
|
+
...(value.tool_registration ? { tool_registration: value.tool_registration } : {}),
|
|
15
|
+
...(value.prediction_route ? { prediction_route: value.prediction_route } : {}),
|
|
16
|
+
...(typeof value.needs_restart === "boolean" ? { needs_restart: value.needs_restart } : {}) });
|
|
17
|
+
|
|
18
|
+
async function applyPendingPrediction(options, nativeOperation) {
|
|
19
|
+
try {
|
|
20
|
+
if (!readPredictionSettings(options).displayPending) return true;
|
|
21
|
+
const enabled = servicePreferences(options).prediction_enabled;
|
|
22
|
+
const result = await nativeOperation("display", { ...options, enabled, requireClosed: true });
|
|
23
|
+
if (result?.pending !== false) return false;
|
|
24
|
+
return await withFileLock(`${predictionPaths(options).settings}.lock`, () => {
|
|
25
|
+
const current = readPredictionSettings(options);
|
|
26
|
+
if (!current.displayPending) return true;
|
|
27
|
+
if (servicePreferences(options).prediction_enabled !== enabled) return false;
|
|
28
|
+
writePredictionSettings({ ...current, displayPending: false }, options);return true;
|
|
29
|
+
});
|
|
30
|
+
} catch { return false; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function controlCodexLaunch(operation, { intent = "image", integration, state, host, port, models = [],
|
|
34
|
+
prepare = prepareImageHostLaunch, launch = openCodex, readSummary = imageSetupSummary,
|
|
35
|
+
readPrediction = predictionControlSnapshot, nativeOperation = runPredictionOperation,
|
|
36
|
+
discover = installedPredictionApp, inspect = inspectCodexApp, appControl = controlCodexApp,
|
|
37
|
+
confirmed = false, wait = sleep, now = Date.now, quitTimeoutMs = 10000, ...options } = {}) {
|
|
38
|
+
if (!["check", "repair", "open", "focus", "restart"].includes(operation) || !["image", "prediction"].includes(intent)) throw new Error("Unknown Codex App control");
|
|
39
|
+
if (operation === "restart" && confirmed !== true) throw new Error("Confirm that restarting Codex can interrupt its running tasks");
|
|
40
|
+
const platform = options.platform || process.platform;
|
|
41
|
+
let image, prediction;
|
|
42
|
+
try { image = readSummary({ ...options, models }); }
|
|
43
|
+
catch { image = { enabled: servicePreferences(options).image_enabled, configured: false, selected_available: false, availability: "unavailable" }; }
|
|
44
|
+
try { prediction = readPrediction(options); }
|
|
45
|
+
catch { prediction = { enabled: false, configured: false, status: "unavailable" }; }
|
|
46
|
+
const runtime = () => state?.snapshot();
|
|
47
|
+
const inspectApp = async app => {
|
|
48
|
+
const current = await inspect(app, runtime()?.hosts || [], { ...options, predictionPacUrl: integration?.pacUrl?.() });
|
|
49
|
+
if (current.status === "running") {
|
|
50
|
+
const imagePending = image.enabled && image.configured && image.selected_available && current.host !== "connected";
|
|
51
|
+
const predictionPending = prediction.display_pending || prediction.configured && prediction.enabled && current.prediction_route !== "verified";
|
|
52
|
+
current.needs_restart = Boolean(imagePending || predictionPending);
|
|
53
|
+
}
|
|
54
|
+
return current;
|
|
55
|
+
};
|
|
56
|
+
if (operation === "check") {
|
|
57
|
+
let app = { status: platform === "darwin" ? "unknown" : "unsupported" };
|
|
58
|
+
if (platform === "darwin") try { app = await inspectApp((await discover(options)).app); } catch { /* Unknown is not stopped. */ }
|
|
59
|
+
return { status: "checked", app: publicAppState(app), prediction, image: { enabled: image.enabled, availability: image.availability } };
|
|
60
|
+
}
|
|
61
|
+
if (operation === "focus") {
|
|
62
|
+
if (platform !== "darwin") return { status: "unsupported", app: { status: "unsupported" } };
|
|
63
|
+
let app, current;
|
|
64
|
+
try { app = (await discover(options)).app;current = await inspectApp(app); }
|
|
65
|
+
catch { return { status: "app_check_failed", app: { status: "unknown" } }; }
|
|
66
|
+
if (current.status !== "running") return { status: "app_not_running", app: publicAppState(current) };
|
|
67
|
+
let result;
|
|
68
|
+
try { result = await appControl(app, current.pid, "activate", options); }
|
|
69
|
+
catch { return { status: "focus_unavailable", app: { status: "unknown" } }; }
|
|
70
|
+
return { status: result === "sent" ? "focused" : "focus_unavailable", app: result === "sent" ? publicAppState(current) : { status: "unknown" } };
|
|
71
|
+
}
|
|
72
|
+
if (!integration) throw new Error("Start CCDX before opening Codex from this control");
|
|
73
|
+
if (intent === "image" && !image.enabled) throw new Error("Enable images before repairing image access");
|
|
74
|
+
if (intent === "prediction" && !prediction.configured && !prediction.display_pending) throw new Error("Enable predictions before opening Codex");
|
|
75
|
+
const env = { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" };
|
|
76
|
+
await integration.configure();
|
|
77
|
+
let imageHost = null, imagePrepFailed = false, imageWarning = intent === "prediction" && image.enabled && (!image.configured || !image.selected_available);
|
|
78
|
+
if (image.enabled) {
|
|
79
|
+
try { imageHost = await prepare({ ...options, env, host, port }); }
|
|
80
|
+
catch (error) { if (intent === "image") throw error;imageWarning = true;imagePrepFailed = true; }
|
|
81
|
+
if (!imageHost) { if (intent === "image") return { status: "unsupported", prepared: false };imageWarning = true;imagePrepFailed = true; }
|
|
82
|
+
}
|
|
83
|
+
let app = imageHost?.app;
|
|
84
|
+
if (!app) { try { app = (await discover(options)).app; } catch { return { status: "app_check_failed", prepared: false }; } }
|
|
85
|
+
let current;
|
|
86
|
+
try { current = await inspectApp(app); } catch { return { status: "app_check_failed", prepared: true }; }
|
|
87
|
+
if (current.status === "unsupported") return { status: "unsupported", prepared: true };
|
|
88
|
+
if (current.status === "multiple") return { status: "multiple_apps", prepared: true, app: publicAppState(current) };
|
|
89
|
+
if (!["running", "stopped"].includes(current.status)) return { status: "app_check_failed", prepared: true };
|
|
90
|
+
if (operation !== "restart" && current.status === "running") return { status: current.needs_restart ? "needs_app_relaunch" : "already_connected",
|
|
91
|
+
prepared: true, runtime: runtime(), app: publicAppState(current) };
|
|
92
|
+
if (operation === "repair") return { status: "prepared", prepared: true, runtime: runtime(), app: publicAppState(current) };
|
|
93
|
+
if (operation === "restart" && intent === "image" && (!image.configured || !image.selected_available)) return { status: "image_unavailable", prepared: true, app: publicAppState(current) };
|
|
94
|
+
if (operation === "restart" && current.status === "running" && !current.needs_restart) return { status: "already_connected", prepared: true, app: publicAppState(current) };
|
|
95
|
+
// Never lose a currently connected image host due to a failed preparation.
|
|
96
|
+
if (imagePrepFailed && current.status === "running" && current.host === "connected") return { status: "image_unavailable", prepared: true, app: publicAppState(current) };
|
|
97
|
+
const native = await integration.start();
|
|
98
|
+
if (prediction.status === "unavailable") return { status: "prediction_unavailable", prepared: true, app: publicAppState(current) };
|
|
99
|
+
if (!native && prediction.configured && prediction.enabled) return { status: "prediction_unavailable", prepared: true, app: publicAppState(current) };
|
|
100
|
+
await native?.prepareRoute?.();
|
|
101
|
+
if (native?.pacUrl && native.app && native.app !== app) return { status: "app_route_conflict", prepared: true };
|
|
102
|
+
if (operation === "restart") {
|
|
103
|
+
const previous = current;
|
|
104
|
+
try { current = await inspectApp(app); } catch { return { status: "app_check_failed", prepared: true }; }
|
|
105
|
+
if (current.status === "running" && !current.needs_restart) return { status: "already_connected", prepared: true, app: publicAppState(current) };
|
|
106
|
+
if (!["running", "stopped"].includes(current.status) || current.status === "running" && (previous.status !== "running" || current.pid !== previous.pid)) {
|
|
107
|
+
return { status: "app_changed", prepared: true, app: publicAppState(current) };
|
|
108
|
+
}
|
|
109
|
+
if (current.status === "running") {
|
|
110
|
+
const originalPid = current.pid;
|
|
111
|
+
let requested;
|
|
112
|
+
try { requested = await appControl(app, originalPid, "quit", options); }
|
|
113
|
+
catch { return { status: "quit_refused", prepared: true, app: publicAppState(current) }; }
|
|
114
|
+
if (!["sent", "absent"].includes(requested)) return { status: "quit_refused", prepared: true, app: publicAppState(current) };
|
|
115
|
+
const deadline = now() + quitTimeoutMs;
|
|
116
|
+
do {
|
|
117
|
+
try { current = await inspectApp(app); } catch { return { status: "app_check_failed", prepared: true }; }
|
|
118
|
+
if (current.status === "stopped") break;
|
|
119
|
+
if (current.status !== "running" || current.pid !== originalPid) return { status: "app_changed", prepared: true, app: publicAppState(current) };
|
|
120
|
+
if (now() >= deadline) return { status: "quit_timeout", prepared: true, app: publicAppState(current) };
|
|
121
|
+
await wait(Math.min(250, Math.max(1, deadline - now())));
|
|
122
|
+
} while (true);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const predictionReady = await applyPendingPrediction(options, nativeOperation);
|
|
126
|
+
const opened = await launch({ env, imageHost, predictionPacUrl: native?.pacUrl, predictionApp: native?.app,
|
|
127
|
+
predictionProfile: native?.profile, preparePredictionRoute: () => native?.prepareRoute?.(),
|
|
128
|
+
onPredictionRoute: value => integration.launched?.(value) });
|
|
129
|
+
return { status: opened ? !predictionReady || imageWarning ? "opened_with_pending" : "opened_new_chat_required" : "open_failed",
|
|
130
|
+
prepared: true, runtime: runtime(), app: { status: "unknown" }, ...(opened && !predictionReady ? { prediction_pending: true } : {}),
|
|
131
|
+
...(opened && imageWarning ? { image_pending: true } : {}) };
|
|
132
|
+
}
|
|
@@ -1413,7 +1413,7 @@ export function createConnectionRuntime({
|
|
|
1413
1413
|
}),
|
|
1414
1414
|
}),
|
|
1415
1415
|
},
|
|
1416
|
-
codexCatalog: codexClientCatalog(compiled),
|
|
1416
|
+
codexCatalog: codexClientCatalog(compiled, () => getSource("github")?.registry?.models),
|
|
1417
1417
|
};
|
|
1418
1418
|
}
|
|
1419
1419
|
if (Array.isArray(c.deployments) && compiled.defaultUnavailable) {
|
package/src/dashboard/console.js
CHANGED
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
async function api(body) {
|
|
69
69
|
const response = await fetch("/_ccdx/ui/settings", { method: body ? "POST" : "GET", cache: "no-store",
|
|
70
70
|
headers: { "X-CCDX-Dashboard": "1", ...(body ? { "Content-Type": "application/json" } : {}) },
|
|
71
|
-
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout((body?.action === "prediction" || body?.action
|
|
71
|
+
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout((body?.action === "prediction" || ["image", "codex_app"].includes(body?.action) && ["open", "restart"].includes(body?.operation)) ? 210000 : ["image", "codex_app"].includes(body?.action) || body?.operation === "account" ? 65000 : 15000) });
|
|
72
72
|
const data = await response.json();if (!response.ok) throw Object.assign(new Error(data.error || `HTTP ${response.status}`), { code: data.code });return data;
|
|
73
73
|
}
|
|
74
74
|
const preferences = globalThis.ccdxDashboardPreferences?.create({ element: el, api, applied: applySettings, time,
|
|
@@ -200,7 +200,7 @@
|
|
|
200
200
|
syncAccountControls();
|
|
201
201
|
const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-enabled, #prediction-continue, #prediction-open, #prediction-setup, #prediction-remove, #image-models input, #image-check, #image-repair, #image-open, #decoded-limit, #decoded-limit-save, #decoded-limit-default, #install-update")];
|
|
202
202
|
controls.forEach(input => { input.disabled = true; });
|
|
203
|
-
const note = el(body.action === "prediction" ? "prediction-action-note" : body.action === "image" ? "effect-image_enabled" : body.action === "update" ? "manual-update-note" : body.action === "decoded_limit" ? "decoded-limit-note" : body.action === "nightly_update" ? "nightly-state" : body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
|
|
203
|
+
const note = el(body.action === "codex_app" ? body.intent === "prediction" ? "prediction-action-note" : "image-action-note" : body.action === "prediction" ? "prediction-action-note" : body.action === "image" ? "effect-image_enabled" : body.action === "update" ? "manual-update-note" : body.action === "decoded_limit" ? "decoded-limit-note" : body.action === "nightly_update" ? "nightly-state" : body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
|
|
204
204
|
: body.action.startsWith("history_") ? "effect-history" : body.action === "prediction_fix" ? "prediction-note"
|
|
205
205
|
: body.operation === "switch" ? "source-control-note" : body.operation === "auto-review" ? "review-control-note"
|
|
206
206
|
: body.operation === "account" ? "m365-account-note" : "m365-control-note");
|
|
@@ -1,20 +1,63 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
function create({ element: el, change, localize }) {
|
|
3
|
-
let saved = null, limitDirty = false, imageSignature = "";
|
|
4
|
-
|
|
5
|
-
const
|
|
3
|
+
let saved = null, limitDirty = false, imageSignature = "", imageApp = { status: "unknown" }, appInspectionStarted = false;
|
|
4
|
+
function renderImageApp() {
|
|
5
|
+
const connected = imageApp.status === "running" && imageApp.host === "connected";
|
|
6
|
+
const restart = imageApp.status === "running" && (imageApp.needs_restart === true || saved?.features?.prediction?.display_pending === true);
|
|
7
|
+
const action = restart ? "image_restart" : imageApp.status === "running" ? "image_focus" : imageApp.status === "stopped" ? "image_open" : "image_inspect";
|
|
8
|
+
localize(el("image-open"), action);
|
|
9
|
+
localize(el("prediction-open"), imageApp.status === "unsupported" ? "prediction_open" : action);
|
|
10
|
+
el("image-restart-warning").hidden = !restart;
|
|
11
|
+
el("prediction-restart-warning").hidden = !restart;
|
|
12
|
+
localize(el("image-host-note"), imageApp.status === "stopped" ? "image_app_stopped" : imageApp.status === "multiple" ? "image_action_multiple_apps"
|
|
13
|
+
: connected ? imageApp.tool_registration === "observed" ? "image_host_registered" : "image_host_connected" : "image_host_unconfirmed");
|
|
14
|
+
}
|
|
15
|
+
async function codexAction(operation, intent, button, { quiet = false } = {}) {
|
|
16
|
+
const data = await change({ action: "codex_app", operation, intent, ...(operation === "restart" ? { confirmed: true } : {}) }, button);
|
|
17
|
+
const result = data?.last_operation?.feature === "codex_app" ? data.last_operation.result : null;
|
|
18
|
+
if (!result) return;
|
|
19
|
+
if (result.app) imageApp = result.app;
|
|
20
|
+
if (!quiet) {
|
|
21
|
+
const note = el(intent === "prediction" ? "prediction-action-note" : "image-action-note");
|
|
22
|
+
note.dataset.operation = operation;note.hidden = false;
|
|
23
|
+
const key = operation === "check" ? "codex_action_checked" : result.status === "opened_with_pending"
|
|
24
|
+
? result.prediction_pending && result.image_pending ? "codex_action_both_pending" : result.prediction_pending ? "codex_action_prediction_pending" : "codex_action_image_pending"
|
|
25
|
+
: result.status === "already_connected" ? "codex_action_ready"
|
|
26
|
+
: result.status === "opened_new_chat_required" && intent === "prediction" ? "codex_action_opened" : "image_action_" + result.status;
|
|
27
|
+
localize(note, key);
|
|
28
|
+
}
|
|
29
|
+
renderImageApp();
|
|
30
|
+
}
|
|
31
|
+
async function imageAction(operation, button, { quiet = false } = {}) {
|
|
32
|
+
const data = await change({ action: "image", operation, ...(operation === "restart" ? { confirmed: true } : {}) }, button);
|
|
6
33
|
const result = data?.last_operation?.feature === "image" ? data.last_operation.result : null;
|
|
7
34
|
if (result) {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
35
|
+
if (result.app) imageApp = result.app;
|
|
36
|
+
if (!quiet) {
|
|
37
|
+
el("image-action-note").dataset.operation = operation;
|
|
38
|
+
el("image-action-note").hidden = false;
|
|
39
|
+
localize(el("image-action-note"), operation === "check" ? "image_connection_" + result.connection?.state : "image_action_" + result.status);
|
|
40
|
+
}
|
|
41
|
+
renderImageApp();
|
|
11
42
|
}
|
|
43
|
+
}
|
|
44
|
+
el("image-check").addEventListener("click", () => void imageAction("check", el("image-check")));
|
|
45
|
+
el("image-repair").addEventListener("click", () => void imageAction("repair", el("image-repair")));
|
|
46
|
+
const appButton = (intent, button) => {
|
|
47
|
+
if (imageApp.status === "unsupported" && intent === "prediction") { void prediction("open");return; }
|
|
48
|
+
const operation = imageApp.status === "running" ? imageApp.needs_restart || saved?.features?.prediction?.display_pending ? "restart" : "focus"
|
|
49
|
+
: imageApp.status === "stopped" ? "open" : "check";
|
|
50
|
+
void codexAction(operation, intent, button);
|
|
51
|
+
};
|
|
52
|
+
el("image-open").addEventListener("click", () => appButton("image", el("image-open")));
|
|
53
|
+
el("additional-capabilities").addEventListener("toggle", () => {
|
|
54
|
+
if (el("additional-capabilities").open) void codexAction("check", "image", el("image-check"), { quiet: true });
|
|
12
55
|
});
|
|
13
56
|
const prediction = operation => change({ action: "prediction", operation }, el("prediction-continue"));
|
|
14
57
|
el("setting-prediction_enabled").addEventListener("change", () => void prediction(el("setting-prediction_enabled").checked ? "enable" : "disable"));
|
|
15
58
|
el("prediction-continue").addEventListener("click", () => void prediction(saved?.features?.prediction?.enabled ? "enable" : "disable"));
|
|
16
59
|
el("fix-prediction").addEventListener("click", () => void prediction("repair"));
|
|
17
|
-
el("prediction-open").addEventListener("click", () =>
|
|
60
|
+
el("prediction-open").addEventListener("click", () => appButton("prediction", el("prediction-open")));
|
|
18
61
|
el("prediction-setup").addEventListener("click", () => void prediction("setup"));
|
|
19
62
|
el("prediction-remove").addEventListener("click", () => { if (window.confirm(globalThis.ccdxLanguage.format("prediction_remove_confirm"))) void prediction("remove"); });
|
|
20
63
|
el("decoded-limit").addEventListener("input", () => { limitDirty = true; });
|
|
@@ -35,13 +78,12 @@
|
|
|
35
78
|
el("setting-prediction_enabled").disabled = !value || value.status === "unavailable";
|
|
36
79
|
const pending = value?.display_pending || value?.enabled && (!value.configured || value.display?.enabled === false);
|
|
37
80
|
el("prediction-continue").hidden = !pending;
|
|
38
|
-
el("prediction-open").disabled = !value?.configured;
|
|
81
|
+
el("prediction-open").disabled = !value?.configured && !value?.display_pending;
|
|
39
82
|
el("prediction-remove").disabled = !value?.configured;
|
|
40
83
|
if (notes) localize(el("prediction-action-note"), !value ? "feature_unavailable" : value.status === "unavailable" ? "feature_read_failed" : pending ? "prediction_quit_continue" : value.enabled && value.bridge !== "running" ? "prediction_bridge_missing" : value.enabled ? "prediction_ready" : "prediction_disabled");
|
|
41
84
|
el("effect-prediction_enabled").hidden = !pending;
|
|
42
85
|
if (pending) localize(el("effect-prediction_enabled"), "feature_pending");
|
|
43
|
-
|
|
44
|
-
localize(el("image-host-note"), runtime?.tool_registration === "observed" ? "image_host_registered" : runtime?.connected ? "image_host_connected" : "image_host_unconfirmed");
|
|
86
|
+
renderImageApp();
|
|
45
87
|
const image = data.features?.image, signature = JSON.stringify(image ? { ...image, runtime: undefined } : null);
|
|
46
88
|
if (signature !== imageSignature) {
|
|
47
89
|
imageSignature = signature;
|
|
@@ -68,6 +110,9 @@
|
|
|
68
110
|
el("install-update").disabled = !data.manual_update?.available;
|
|
69
111
|
const update = data.nightly_update;
|
|
70
112
|
if (notes) localize(el("manual-update-note"), !data.manual_update?.available ? "update_external_launch" : update?.manual ? `manual_update_${update.phase}` : "update_idle_switch");
|
|
113
|
+
if (!appInspectionStarted && el("prediction-open").closest('[data-view="codex"]')?.hidden === false) {
|
|
114
|
+
appInspectionStarted = true;setTimeout(() => void codexAction("check", "prediction", el("prediction-open"), { quiet: true }), 0);
|
|
115
|
+
}
|
|
71
116
|
}
|
|
72
117
|
return { render };
|
|
73
118
|
}
|
package/src/dashboard/index.html
CHANGED
|
@@ -122,6 +122,7 @@
|
|
|
122
122
|
<summary class="panel-heading"><h2 data-i18n="codex_input_predictions">INPUT SUGGESTIONS</h2></summary>
|
|
123
123
|
<div class="setting-row"><label for="setting-prediction_enabled" data-i18n="predictions_enable">Input suggestions</label><input id="setting-prediction_enabled" type="checkbox" role="switch" disabled><span id="effect-prediction_enabled" class="hint" role="status"></span></div>
|
|
124
124
|
<p id="prediction-action-note" class="hint" role="status"></p><div class="section-actions"><button id="prediction-continue" type="button" data-i18n="feature_continue" hidden>Continue setup</button><button id="prediction-open" type="button" data-i18n="prediction_open">Open Codex</button></div>
|
|
125
|
+
<p id="prediction-restart-warning" class="hint" role="status" data-i18n="image_restart_warning" hidden>Restarting Codex interrupts its running tasks. Finish or save them first.</p>
|
|
125
126
|
<details class="tool-details"><summary data-i18n="status_and_repair">Status and repair</summary>
|
|
126
127
|
<dl class="stats"><div><dt data-i18n="prediction_integration_setup">Suggestion setup</dt><dd id="prediction-preference">—</dd></div><div><dt data-i18n="local_bridge">Local service</dt><dd id="prediction-bridge">—</dd></div><div><dt data-i18n="client_route">App settings requests</dt><dd id="prediction-route">—</dd></div><div><dt data-i18n="visible_candidate">Suggestion displayed</dt><dd id="prediction-candidate">—</dd></div></dl>
|
|
127
128
|
<p id="prediction-note" class="hint">—</p>
|
|
@@ -135,6 +136,7 @@
|
|
|
135
136
|
<div class="setting-row"><label for="setting-image_enabled" data-i18n="allow_new_image_calls">Allow image requests</label><input id="setting-image_enabled" type="checkbox" role="switch" disabled><span id="effect-image_enabled" class="hint" role="status"></span></div>
|
|
136
137
|
<div id="image-models" class="image-models" role="group" aria-label="Image model" data-i18n-label="image_model"></div>
|
|
137
138
|
<div class="section-actions"><button id="image-check" type="button" data-i18n="image_check">Check access</button><button id="image-repair" type="button" data-i18n="image_repair">Repair access</button><button id="image-open" type="button" data-i18n="image_open">Open Codex</button></div>
|
|
139
|
+
<p id="image-restart-warning" class="hint" role="status" data-i18n="image_restart_warning" hidden>Restarting Codex interrupts its running tasks. Finish or save them first.</p>
|
|
138
140
|
<p id="image-host-note" class="hint" role="status"></p>
|
|
139
141
|
<p id="image-action-note" class="hint" role="status" hidden></p>
|
|
140
142
|
<p id="image-model-note" class="hint" role="status" hidden></p>
|
|
@@ -13,6 +13,11 @@
|
|
|
13
13
|
image_check: ["Check access", "检查接入"],
|
|
14
14
|
image_repair: ["Repair access", "修复接入"],
|
|
15
15
|
image_open: ["Open Codex", "打开 Codex"],
|
|
16
|
+
image_focus: ["Switch to Codex", "切换到 Codex"],
|
|
17
|
+
image_restart: ["Restart Codex to connect", "重启 Codex 以接入"],
|
|
18
|
+
image_inspect: ["Check Codex", "检查 Codex"],
|
|
19
|
+
image_restart_warning: ["Restarting Codex interrupts its running tasks. Finish or save them first.", "重启 Codex 会中断正在执行的任务,请先完成或保存。"],
|
|
20
|
+
image_app_stopped: ["Codex is not running. Image access is checked when it opens.", "Codex 未运行,启动后会检查图片接入。"],
|
|
16
21
|
image_host_unconfirmed: ["App host connection unconfirmed.", "尚未确认 App 图片宿主连接。"],
|
|
17
22
|
image_host_connected: ["App host connected; new chat tool registration unconfirmed.", "App 宿主已连接;尚未确认新聊天工具注册。"],
|
|
18
23
|
image_host_registered: ["Image tool registration observed in a connected host. Other chats may differ.", "已在连接的宿主中观察到图片工具注册,其他聊天可能不同。"],
|
|
@@ -24,6 +29,24 @@
|
|
|
24
29
|
image_action_opened_new_chat_required: ["Codex launch requested. Use a new chat; registration remains unconfirmed until observed.", "已请求打开 Codex。请使用新聊天;观察到注册前仍显示未确认。"],
|
|
25
30
|
image_action_open_failed: ["Could not open Codex. Check the App installation.", "未能打开 Codex,请检查 App 安装。"],
|
|
26
31
|
image_action_unsupported: ["Native image host launch is unavailable on this platform.", "当前平台无法准备原生图片宿主启动。"],
|
|
32
|
+
image_action_focused: ["Requested to switch to Codex.", "已请求切换到 Codex。"],
|
|
33
|
+
image_action_focus_unavailable: ["Could not switch to Codex. Check its current state.", "无法切换到 Codex,请检查当前状态。"],
|
|
34
|
+
image_action_app_not_running: ["Codex is not running. Check its state and open it here.", "Codex 当前未运行,请检查状态后从这里打开。"],
|
|
35
|
+
image_action_already_connected: ["The running Codex App has an image host. A chat may still need a new conversation.", "运行中的 Codex 已连接图片宿主,部分聊天仍需新建对话。"],
|
|
36
|
+
image_action_image_unavailable: ["Image access or the selected model is unavailable. Codex was not restarted.", "图片访问或所选模型不可用,Codex 未重启。"],
|
|
37
|
+
image_action_app_route_conflict: ["The Codex App and suggestion route differ. Codex was not restarted.", "Codex App 与输入建议的接入目标不一致,未重启。"],
|
|
38
|
+
image_action_prediction_unavailable: ["Input suggestions could not be prepared. Codex was not restarted.", "输入建议暂时无法准备,Codex 未重启。"],
|
|
39
|
+
image_action_app_check_failed: ["Could not verify the Codex App state. Codex was not restarted.", "无法确认 Codex App 状态,未重启。"],
|
|
40
|
+
image_action_multiple_apps: ["Multiple Codex App processes were found. Close the extra App, then check again.", "检测到多个 Codex App 进程,请关闭多余的 App 后重新检查。"],
|
|
41
|
+
image_action_quit_refused: ["Codex could not be closed normally. It was not force-quit.", "无法正常退出 Codex,未强制结束。"],
|
|
42
|
+
image_action_quit_timeout: ["Codex did not close in time. Finish its tasks and try again.", "Codex 未在预期时间内退出,请完成任务后重试。"],
|
|
43
|
+
image_action_app_changed: ["The running Codex App changed while restarting. Check it before trying again.", "重启期间 Codex App 状态发生变化,请检查后再试。"],
|
|
44
|
+
codex_action_checked: ["Codex App state checked.", "已检查 Codex App 状态。"],
|
|
45
|
+
codex_action_ready: ["The running Codex App has the selected integrations ready.", "运行中的 Codex 已具备所选接入。"],
|
|
46
|
+
codex_action_opened: ["Codex launch requested. Verify the input suggestions in the App.", "已请求打开 Codex,请在 App 中确认输入建议。"],
|
|
47
|
+
codex_action_prediction_pending: ["Codex opened, but input suggestions still need repair.", "Codex 已打开,但输入建议仍需修复。"],
|
|
48
|
+
codex_action_image_pending: ["Codex opened, but image access still needs repair.", "Codex 已打开,但图片接入仍需修复。"],
|
|
49
|
+
codex_action_both_pending: ["Codex opened, but image access and input suggestions need repair.", "Codex 已打开,但图片接入和输入建议仍需修复。"],
|
|
27
50
|
image_model: ["Image model", "图片模型"],
|
|
28
51
|
image_models: ["Image models", "图片模型"],
|
|
29
52
|
image_needs_github: ["Allow GitHub Copilot access for Codex.", "请允许 Codex 使用 GitHub Copilot。"],
|
|
@@ -93,6 +116,10 @@
|
|
|
93
116
|
"issue_brief": ["{cause} · {model} · {time}", "{cause} · {model} · {time}"],
|
|
94
117
|
"issue_count_unavailable": ["Token counting unavailable", "令牌计数接口不可用"],
|
|
95
118
|
"issue_source_limit": ["Source usage limit reached", "模型来源用量受限"],
|
|
119
|
+
"issue_source_quota": ["Source credits or quota exhausted", "模型来源余额或配额不足"],
|
|
120
|
+
"issue_source_rate": ["Source request rate limited", "模型来源请求频率受限"],
|
|
121
|
+
"issue_context_limit": ["Source reports context too long", "模型来源报告上下文过长"],
|
|
122
|
+
"issue_content_policy": ["Source content policy rejected the request", "模型来源内容策略拒绝了请求"],
|
|
96
123
|
"issue_catalog_unavailable": ["Model catalog could not be read", "模型目录读取失败"],
|
|
97
124
|
"issue_model_not_selected": ["Model not selected for this app", "应用尚未选用此模型"],
|
|
98
125
|
"issue_access_denied": ["Access was denied", "请求被拒绝访问"],
|
|
@@ -989,6 +1016,7 @@
|
|
|
989
1016
|
"message": ["Error details", "错误详情"],
|
|
990
1017
|
"response_id": ["Response ID", "回答编号"],
|
|
991
1018
|
"upstream_request_id": ["Source request ID", "来源编号"],
|
|
1019
|
+
"upstream_code": ["Source error code", "来源错误码"],
|
|
992
1020
|
"request_id": ["CCDX request ID", "本机编号"],
|
|
993
1021
|
"outcome_25a63": ["Result", "处理结果"],
|
|
994
1022
|
"origin": ["Result source", "结果来源"],
|
package/src/dashboard/status.js
CHANGED
|
@@ -134,6 +134,10 @@
|
|
|
134
134
|
details.open = expanded.has(details.dataset.key);
|
|
135
135
|
const title = document.createElement("summary");
|
|
136
136
|
const cause = failure.route === "messages_count_tokens" && [404, 405, 501].includes(failure.http_status) ? "issue_count_unavailable"
|
|
137
|
+
: ["credit_balance_exhausted", "insufficient_quota", "quota_exceeded"].includes(failure.upstream_code) ? "issue_source_quota"
|
|
138
|
+
: ["rate_limit_exceeded", "rate_limit_error"].includes(failure.upstream_code) ? "issue_source_rate"
|
|
139
|
+
: ["context_length_exceeded", "context_window_exceeded"].includes(failure.upstream_code) ? "issue_context_limit"
|
|
140
|
+
: failure.upstream_code === "content_policy_violation" ? "issue_content_policy"
|
|
137
141
|
: ["rate_limit_error", "rate_limit_exceeded", "insufficient_quota", "http_429"].includes(failure.code) ? "issue_source_limit"
|
|
138
142
|
: /^m365_catalog_http_/.test(failure.code || "") ? "issue_catalog_unavailable"
|
|
139
143
|
: failure.reason === "ccdx_model_not_selected" ? "issue_model_not_selected"
|
|
@@ -169,7 +173,7 @@
|
|
|
169
173
|
request_id: failure.request_id, outcome: timeline?.outcome, origin: failure.origin || timeline?.origin,
|
|
170
174
|
phase: timeline?.phase, http_status: failure.http_status ?? timeline?.http_status, route: failure.route,
|
|
171
175
|
upstream_attempts: failure.upstream_attempts ?? timeline?.upstream_attempts,
|
|
172
|
-
error_type: failure.error_type, parameter: failure.parameter, error_body: failure.error_body,
|
|
176
|
+
error_type: failure.error_type, upstream_code: failure.upstream_code, parameter: failure.parameter, error_body: failure.error_body,
|
|
173
177
|
diagnostic_message: failure.diagnostic_message, method: failure.method, target: failure.target,
|
|
174
178
|
request_options: failure.request_options ? JSON.stringify(failure.request_options) : undefined,
|
|
175
179
|
transport: failure.transport ? JSON.stringify(failure.transport) : undefined,
|
package/src/http-transport.mjs
CHANGED
|
@@ -280,7 +280,7 @@ export function sendJsonError(res, err, fallbackStatus = 400) {
|
|
|
280
280
|
export function sendUpstreamError(res, response, text) {
|
|
281
281
|
const context = currentRequestContext();
|
|
282
282
|
if (context?.onHttpError) context.onHttpError({
|
|
283
|
-
...upstreamErrorEvidence(text, { includeMessage: context.includeHttpErrorDetails === true }),
|
|
283
|
+
...upstreamErrorEvidence(text, { includeMessage: context.includeHttpErrorDetails === true, status: response.status }),
|
|
284
284
|
origin: "upstream_http", headers: response.headers,
|
|
285
285
|
});
|
|
286
286
|
if (!res.headersSent) {
|
package/src/image-control.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { adapterBaseUrl, ADAPTER_PROTOCOL_VERSION } from "./running-adapter.mjs";
|
|
4
|
-
import { imageHostLauncherPath
|
|
4
|
+
import { imageHostLauncherPath } from "./codex-image-host-launch.mjs";
|
|
5
5
|
import { imageSetupSummary } from "./image-setup.mjs";
|
|
6
|
-
import { openCodex, macPredictionAppProcesses } from "./launcher.mjs";
|
|
7
6
|
import { readBoundedResponseText } from "./upstream-body.mjs";
|
|
7
|
+
import { controlCodexLaunch } from "./codex-launch-control.mjs";
|
|
8
8
|
|
|
9
9
|
export async function checkImageConnection({ host = "127.0.0.1", port = 2026, fetchImpl = fetch } = {}) {
|
|
10
10
|
const nonce = randomUUID();
|
|
@@ -17,26 +17,13 @@ export async function checkImageConnection({ host = "127.0.0.1", port = 2026, fe
|
|
|
17
17
|
} catch { return { state: "unreachable", scope: "node_loopback", app_path: "unconfirmed" }; }
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
-
export async function controlImage(operation, {
|
|
21
|
-
|
|
22
|
-
if (
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
await integration.configure();
|
|
30
|
-
const imageHost = await prepare({ ...options, env, host, port });
|
|
31
|
-
if (!imageHost) return { status: "unsupported", prepared: false };
|
|
32
|
-
const running = appProcesses(imageHost.app).length > 0;
|
|
33
|
-
if (running) return { status: "needs_app_relaunch", prepared: true, runtime: state?.snapshot() };
|
|
34
|
-
if (operation === "repair") return { status: "prepared", prepared: true, runtime: state?.snapshot() };
|
|
35
|
-
// Share the established prediction launch route; never strip it during repair.
|
|
36
|
-
const native = await integration.start();
|
|
37
|
-
await native?.prepareRoute?.();
|
|
38
|
-
const opened = await launch({ env, imageHost, predictionPacUrl: native?.pacUrl, predictionApp: native?.app,
|
|
39
|
-
predictionProfile: native?.profile, preparePredictionRoute: () => native?.prepareRoute?.(),
|
|
40
|
-
onPredictionRoute: value => integration.launched?.(value) });
|
|
41
|
-
return { status: opened ? "opened_new_chat_required" : "open_failed", prepared: true, runtime: state?.snapshot() };
|
|
20
|
+
export async function controlImage(operation, { connection = checkImageConnection, readSummary = imageSetupSummary, ...options } = {}) {
|
|
21
|
+
if (!["check", "repair", "open", "focus", "restart"].includes(operation)) throw new Error("Unknown image control");
|
|
22
|
+
if (operation === "check") {
|
|
23
|
+
const checked = await controlCodexLaunch("check", { ...options, readSummary, intent: "image" });
|
|
24
|
+
const summary = readSummary({ ...options, models: options.models || [] });
|
|
25
|
+
return { status: "checked", connection: await connection({ host: options.host, port: options.port }),
|
|
26
|
+
launcher_present: fs.existsSync(imageHostLauncherPath(options)), runtime: options.state?.snapshot(), app: checked.app, ...summary };
|
|
27
|
+
}
|
|
28
|
+
return controlCodexLaunch(operation, { ...options, readSummary, intent: "image" });
|
|
42
29
|
}
|
package/src/image-host-state.mjs
CHANGED
|
@@ -10,7 +10,9 @@ export function createImageHostState({ now = Date.now, alive = pid => { try { pr
|
|
|
10
10
|
const previous = hosts.get(value.id);
|
|
11
11
|
if (previous && previous.pid !== value.pid) throw new Error("Image host identity changed");
|
|
12
12
|
const host = previous || { id: value.id, pid: value.pid, connected: false, threads: [] };
|
|
13
|
-
|
|
13
|
+
// A later tool event also proves this host is live, including when CCDX
|
|
14
|
+
// restarted after the host's initial connection report.
|
|
15
|
+
if (["connected", "registered", "generated", "failed"].includes(value.event)) host.connected = true;
|
|
14
16
|
if (value.event === "closed") host.connected = false;
|
|
15
17
|
if (value.event === "registered" && value.thread && !host.threads.includes(value.thread)) host.threads = [...host.threads, value.thread].slice(-32);
|
|
16
18
|
host.event = value.event;host.updated_at = now();
|
package/src/native-images.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { readAccessSettings } from "./access-settings.mjs";
|
|
|
6
6
|
import { servicePreferences } from "./user-settings.mjs";
|
|
7
7
|
import { observeRequestedModel, currentRequestContext } from "./request-context.mjs";
|
|
8
8
|
import { recordResponsesUsage } from "./usage-store.mjs";
|
|
9
|
+
import { readSafeUpstreamReason } from "./safe-upstream-error.mjs";
|
|
9
10
|
|
|
10
11
|
export const NATIVE_IMAGE_MODEL = DEFAULT_IMAGE_MODEL;
|
|
11
12
|
export const IMAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
@@ -57,11 +58,11 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
57
58
|
models = () => [], selection = () => readAccessSettings({ env, home }).clients.codex.image_model,
|
|
58
59
|
requestBodyTimeoutMs = 120000, timeoutMs = 180000, enabled = () => servicePreferences({ env, home }).image_enabled,
|
|
59
60
|
allowed = () => nativeImageAccess({ env, home }) } = {}) {
|
|
60
|
-
let active = 0;
|
|
61
|
+
let active = 0, processing = 0;
|
|
61
62
|
const metrics = { total: 0, succeeded: 0, failed: 0, busy: 0, cancelled: 0 };
|
|
62
63
|
const handler = async (req, res, operation) => {
|
|
63
64
|
const abort = createRequestAbort(req, res);
|
|
64
|
-
let release = () => {}, admitted = false;
|
|
65
|
+
let release = () => {}, admitted = false, processingSlot = false;
|
|
65
66
|
metrics.total++;
|
|
66
67
|
try {
|
|
67
68
|
if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers.host !== undefined && !isLoopbackHostHeader(req.headers.host)
|
|
@@ -69,8 +70,8 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
69
70
|
if (String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase() !== "application/json") throw httpError("Images require application/json", 415);
|
|
70
71
|
if (!allowed()) throw httpError("GitHub Copilot access is disabled for Codex", 403);
|
|
71
72
|
if (!enabled()) throw httpError("Image requests are paused", 503);
|
|
72
|
-
if (
|
|
73
|
-
active++;admitted = true;
|
|
73
|
+
if (processing >= 2) { metrics.busy++;throw httpError("Two image requests are already active", 503); }
|
|
74
|
+
active++;processing++;admitted = true;processingSlot = true;
|
|
74
75
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
75
76
|
release = await acquireRequest(req, { signal: abort.signal });
|
|
76
77
|
const parsed = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: BODY_MAX_BYTES, maxDecodedBodyBytes: BODY_MAX_BYTES });
|
|
@@ -89,11 +90,15 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
89
90
|
const response = await call({ input: body.prompt }, { signal: abort.signal });
|
|
90
91
|
if (!response.ok) {
|
|
91
92
|
metrics.failed++;
|
|
92
|
-
|
|
93
|
+
// The upstream request has finished. Do not hold image concurrency or
|
|
94
|
+
// body admission while an optional error reason is read.
|
|
95
|
+
release();release = () => {};processing--;processingSlot = false;
|
|
96
|
+
const reason = await readSafeUpstreamReason(response, { signal: abort.signal });
|
|
93
97
|
abort.signal.throwIfAborted();
|
|
94
98
|
const code = `ccdx_images_http_${response.status}`, headers = new Headers(response.headers);
|
|
95
99
|
headers.set("Content-Type", "application/json");
|
|
96
|
-
sendUpstreamError(res, { status: response.status, headers }, JSON.stringify({ error: { type: "upstream_error", code,
|
|
100
|
+
sendUpstreamError(res, { status: response.status, headers }, JSON.stringify({ error: { type: "upstream_error", code,
|
|
101
|
+
message: reason?.message || code, ...(reason ? { upstream_code: reason.code } : {}) } }));
|
|
97
102
|
return;
|
|
98
103
|
}
|
|
99
104
|
const text = await readBoundedResponseText(response, { maxBytes: RESPONSE_MAX_BYTES, signal: abort.signal, label: "Copilot image response" });
|
|
@@ -112,7 +117,7 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
112
117
|
if (abort.reason === "client_closed" || abort.reason === "client_aborted") metrics.cancelled++;
|
|
113
118
|
logRequestFailure("images", error, abort);
|
|
114
119
|
sendJsonError(res, error, error.statusCode || 502);
|
|
115
|
-
} finally { release();if (admitted) active--;abort.cleanup(); }
|
|
120
|
+
} finally { release();if (admitted) active--;if (processingSlot) processing--;abort.cleanup(); }
|
|
116
121
|
};
|
|
117
122
|
handler.stats = () => ({ ...metrics, active, native: true, model: imageModelSelection(models(), selection()).selected_model });
|
|
118
123
|
return handler;
|
|
@@ -19,7 +19,8 @@ export function createApiTokenCounter({ request, now = Date.now }) {
|
|
|
19
19
|
const serialized = JSON.stringify(body), size = Buffer.byteLength(serialized), hash = size <= 1024 * 1024 ? createHash("sha256").update(scope).update(serialized).digest("hex") : null;
|
|
20
20
|
const identity = hash || {};
|
|
21
21
|
async function run(probe) {
|
|
22
|
-
const key = probe ? "probe:" + scope : "body:" + hash, waiter = { start: options.onUpstreamStart, observe: options.onCountObservation,
|
|
22
|
+
const key = probe ? "probe:" + scope : "body:" + hash, waiter = { start: options.onUpstreamStart, observe: options.onCountObservation,
|
|
23
|
+
errorHeaders: options.onUpstreamErrorHeaders, signal: options.signal, identity };
|
|
23
24
|
let flight = flights.get(key);
|
|
24
25
|
if (flight && [...flight.waiters].every(item => item.signal?.aborted)) { flights.delete(key);bytes -= flight.bytes;flight = null; }
|
|
25
26
|
const joinable = (probe || hash !== null) && (Boolean(flight) || flights.size < 16 && (probe || bytes + size <= 4 * 1024 * 1024));
|
|
@@ -33,11 +34,20 @@ export function createApiTokenCounter({ request, now = Date.now }) {
|
|
|
33
34
|
item.observe?.(item.identity === flight.identity ? { upstream: true, shared: flight.shared } : { waited: true });
|
|
34
35
|
};
|
|
35
36
|
if (flight.started) start(waiter);
|
|
37
|
+
if (flight.errorStatus && (flight.errorStatus === 404 || waiter.identity === flight.identity)) {
|
|
38
|
+
try { waiter.errorHeaders?.(flight.errorStatus); } catch {}
|
|
39
|
+
}
|
|
36
40
|
const task = async signal => {
|
|
37
41
|
try {
|
|
38
42
|
if (signal?.aborted) throw signal.reason;
|
|
39
43
|
const response = await request(body, { ...options, bodyText: serialized, signal, observeUpstream: false,
|
|
40
|
-
onUpstreamStart() { flight.started = true;for (const item of flight.waiters) if (!item.signal?.aborted) start(item); }
|
|
44
|
+
onUpstreamStart() { flight.started = true;for (const item of flight.waiters) if (!item.signal?.aborted) start(item); },
|
|
45
|
+
onUpstreamErrorHeaders(status) {
|
|
46
|
+
flight.errorStatus = status;
|
|
47
|
+
for (const item of flight.waiters) if (!item.signal?.aborted && (status === 404 || item.identity === flight.identity)) {
|
|
48
|
+
try { item.errorHeaders?.(status); } catch {}
|
|
49
|
+
}
|
|
50
|
+
} });
|
|
41
51
|
if (signal?.aborted) { await response.body?.cancel();throw signal.reason; }
|
|
42
52
|
if (response.status === 404) {
|
|
43
53
|
await response.body?.cancel();observe(scope, 404);const result = missed();
|
package/src/providers/api.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { markUpstreamHeaders } from "../stream-performance.mjs";
|
|
|
10
10
|
import { createApiNetwork } from "./api-network.mjs";
|
|
11
11
|
import { checkedApiKey } from "../api-secrets.mjs";
|
|
12
12
|
import { transportErrorDetails } from "../operation-error.mjs";
|
|
13
|
+
import { readSafeUpstreamReason } from "../safe-upstream-error.mjs";
|
|
13
14
|
import { resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
|
|
14
15
|
import { apiModelMetadata } from "./api-model-metadata.mjs";
|
|
15
16
|
import { markRequestObservation, markUpstreamStarted } from "../stream-performance.mjs";
|
|
@@ -85,11 +86,13 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
85
86
|
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
86
87
|
if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
|
|
87
88
|
if (!result.ok) {
|
|
88
|
-
|
|
89
|
+
try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Optional admission release cannot hide the upstream response. */ }
|
|
90
|
+
const reason = await readSafeUpstreamReason(result, { signal: options.signal });const code = `ccdx_api_http_${result.status}`;
|
|
89
91
|
const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
|
|
90
92
|
if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
|
|
91
93
|
else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
|
|
92
|
-
return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message:
|
|
94
|
+
return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: reason?.message || code,
|
|
95
|
+
...(reason ? { upstream_code: reason.code } : {}) } }), { status: result.status, headers: safeHeaders });
|
|
93
96
|
}
|
|
94
97
|
return result;
|
|
95
98
|
} catch (error) {
|
|
@@ -160,8 +163,10 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
160
163
|
applyRequestPolicies() {},
|
|
161
164
|
compatibility: { hasRetry: () => false, selectRetry: async () => null,
|
|
162
165
|
async openResponse(context, upstream, options) {
|
|
163
|
-
|
|
164
|
-
|
|
166
|
+
let headersObserved = false;
|
|
167
|
+
const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart,
|
|
168
|
+
onUpstreamErrorHeaders(status) { headersObserved = true;markUpstreamHeaders(status);options.releaseRequest?.(context); } });
|
|
169
|
+
if (!headersObserved) markUpstreamHeaders(resp.status);
|
|
165
170
|
// request() already discarded the vendor body and projected a safe error.
|
|
166
171
|
if (!resp.ok) {
|
|
167
172
|
const errorText = await readBoundedResponseText(resp, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, signal: options.signal, label: "API error response" });
|
|
@@ -2,6 +2,7 @@ import { boundedDiagnosticText, redactDiagnosticText } from "./diagnostic-text.m
|
|
|
2
2
|
import { currentRequestContext } from "./request-context.mjs";
|
|
3
3
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
4
4
|
import { transportErrorDetails } from "./operation-error.mjs";
|
|
5
|
+
import { safeUpstreamReason } from "./safe-upstream-error.mjs";
|
|
5
6
|
|
|
6
7
|
const DEFAULT_RECENT_FAILURES = 10;
|
|
7
8
|
|
|
@@ -104,7 +105,7 @@ export function createResponseFailureDiagnostics({
|
|
|
104
105
|
};
|
|
105
106
|
}
|
|
106
107
|
|
|
107
|
-
export function upstreamErrorEvidence(text, { includeMessage = false } = {}) {
|
|
108
|
+
export function upstreamErrorEvidence(text, { includeMessage = false, status = null } = {}) {
|
|
108
109
|
const errorBody = !String(text || "").trim() ? "empty" : "unstructured";
|
|
109
110
|
let error;
|
|
110
111
|
try { const parsed = JSON.parse(text); error = parsed?.error; } catch {}
|
|
@@ -115,7 +116,10 @@ export function upstreamErrorEvidence(text, { includeMessage = false } = {}) {
|
|
|
115
116
|
const param = typeof error.param === "string" && error.param.length <= 160
|
|
116
117
|
&& /^(?:model|input|tools|tool_choice|reasoning|text|temperature|top_p|max_output_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
|
|
117
118
|
? error.param : undefined;
|
|
119
|
+
const upstreamCode = (safeUpstreamReason(error.upstream_code, status) || safeUpstreamReason(error.code, status)
|
|
120
|
+
|| safeUpstreamReason(error.type, status))?.code;
|
|
118
121
|
return { error_body: "structured", code: technical(error.code), error_type: technical(error.type),
|
|
122
|
+
...(upstreamCode ? { upstream_code: upstreamCode } : {}),
|
|
119
123
|
parameter: param, ...(includeMessage && typeof error.message === "string" ? { diagnostic_message: safeFailureMessage(error.message) } : {}) };
|
|
120
124
|
}
|
|
121
125
|
|
|
@@ -179,7 +183,7 @@ export function isDiscoveryRequest(method, pathname) {
|
|
|
179
183
|
}
|
|
180
184
|
|
|
181
185
|
export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers, model_error,
|
|
182
|
-
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
186
|
+
error_body, error_type, upstream_code, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
183
187
|
application, reason, capability_cached, shared_upstream, transport }) {
|
|
184
188
|
if (!reason && code === "ccdx_client_source_disabled" && upstream_attempts === 0 && origin !== "upstream_http") {
|
|
185
189
|
reason = code;origin = "client_validation";
|
|
@@ -204,7 +208,8 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
|
|
|
204
208
|
message: model_error ? "The model source reported an error; the original HTTP response was preserved." : message } }, model_error ? "model.error" : "http.error", { headers, provider });
|
|
205
209
|
return { ...details, request_id: requestId, http_status: statusCode, route,
|
|
206
210
|
origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
|
|
207
|
-
...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}),
|
|
211
|
+
...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}),
|
|
212
|
+
...(safeUpstreamReason(upstream_code, statusCode) ? { upstream_code } : {}), ...(parameter ? { parameter } : {}),
|
|
208
213
|
...(diagnostic_message ? { diagnostic_message } : {}),
|
|
209
214
|
...(method ? { method } : {}), ...(target ? { target } : {}),
|
|
210
215
|
...(request_options ? { request_options } : {}),
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Only fixed, documented-shaped codes leave this module; vendor messages and
|
|
2
|
+
// request data are never returned or logged.
|
|
3
|
+
const reasons = new Map([
|
|
4
|
+
["credit_balance_exhausted", { statuses: [429], message: "The source account has no remaining credits." }],
|
|
5
|
+
["insufficient_quota", { statuses: [429], message: "The source account has insufficient quota." }],
|
|
6
|
+
["quota_exceeded", { statuses: [429], message: "The source account has exceeded its quota." }],
|
|
7
|
+
["rate_limit_exceeded", { statuses: [429], message: "The source request rate limit was reached." }],
|
|
8
|
+
["rate_limit_error", { statuses: [429], message: "The source request rate limit was reached." }],
|
|
9
|
+
["context_length_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
|
|
10
|
+
["context_window_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
|
|
11
|
+
["content_policy_violation", { statuses: [400, 403, 422], message: "The source rejected the request under its content policy." }],
|
|
12
|
+
]);
|
|
13
|
+
const MAX_ACTIVE_READS = 4;
|
|
14
|
+
let activeReads = 0;
|
|
15
|
+
|
|
16
|
+
function cancelBody(body) {
|
|
17
|
+
try { void Promise.resolve(body?.cancel()).catch(() => {}); } catch {}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function safeUpstreamReason(code, status) {
|
|
21
|
+
const reason = typeof code === "string" ? reasons.get(code) : null;
|
|
22
|
+
return reason?.statuses.includes(status) ? { code, message: reason.message } : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readChunk(reader, signal) {
|
|
26
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
let settled = false;
|
|
29
|
+
const finish = (fn, value) => { if (settled) return;settled = true;signal.removeEventListener("abort", onAbort);fn(value); };
|
|
30
|
+
const onAbort = () => finish(reject, signal.reason);
|
|
31
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
32
|
+
reader.read().then(value => finish(resolve, value), error => finish(reject, error));
|
|
33
|
+
if (signal.aborted) onAbort();
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Failure responses only. A stalled body or a stalled cancellation cannot delay
|
|
38
|
+
// the caller beyond the budget. The original request's cancellation wins.
|
|
39
|
+
export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024 } = {}) {
|
|
40
|
+
if (signal?.aborted) {
|
|
41
|
+
cancelBody(response?.body);
|
|
42
|
+
signal.throwIfAborted();
|
|
43
|
+
}
|
|
44
|
+
if (!response?.body) return null;
|
|
45
|
+
if (activeReads >= MAX_ACTIVE_READS) { cancelBody(response.body);return null; }
|
|
46
|
+
activeReads++;
|
|
47
|
+
const deadline = performance.now() + timeoutMs;
|
|
48
|
+
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
49
|
+
const readSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
50
|
+
let reader, finished = false;
|
|
51
|
+
try {
|
|
52
|
+
const length = Number(response.headers?.get?.("content-length"));
|
|
53
|
+
if (Number.isFinite(length) && length > maxBytes) return null;
|
|
54
|
+
reader = response.body.getReader();const chunks = [];let bytes = 0;
|
|
55
|
+
while (true) {
|
|
56
|
+
if (performance.now() >= deadline) controller.abort();
|
|
57
|
+
const { done, value } = await readChunk(reader, readSignal);
|
|
58
|
+
if (done) { finished = true;break; }
|
|
59
|
+
if (Number.isFinite(value?.byteLength) && bytes + value.byteLength > maxBytes) return null;
|
|
60
|
+
const chunk = Buffer.from(value);bytes += chunk.length;
|
|
61
|
+
if (bytes > maxBytes) return null;
|
|
62
|
+
chunks.push(chunk);
|
|
63
|
+
}
|
|
64
|
+
let value;try { value = JSON.parse(Buffer.concat(chunks, bytes).toString("utf8")); } catch { return null; }
|
|
65
|
+
const error = value?.error;
|
|
66
|
+
if (!error || typeof error !== "object" || Array.isArray(error)) return null;
|
|
67
|
+
return safeUpstreamReason(error.code, response.status) || safeUpstreamReason(error.type, response.status);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (signal?.aborted) signal.throwIfAborted();
|
|
70
|
+
return null;
|
|
71
|
+
} finally {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
if (!finished) {
|
|
74
|
+
try { void Promise.resolve(reader ? reader.cancel() : response.body.cancel()).catch(() => {}); } catch {}
|
|
75
|
+
}
|
|
76
|
+
try { reader?.releaseLock(); } catch {}
|
|
77
|
+
activeReads--;
|
|
78
|
+
}
|
|
79
|
+
}
|
package/src/service-control.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createImageHostState } from "./image-host-state.mjs";
|
|
2
2
|
import { controlImage } from "./image-control.mjs";
|
|
3
|
+
import { controlCodexLaunch } from "./codex-launch-control.mjs";
|
|
3
4
|
import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
|
|
4
5
|
writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
|
|
5
6
|
nightlyUpdatePreference, writeNightlyUpdatePreference, decodedBodyLimitPreference, writeDecodedBodyLimitMib } from "./user-settings.mjs";
|
|
@@ -12,7 +13,7 @@ import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
|
|
|
12
13
|
|
|
13
14
|
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
14
15
|
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
15
|
-
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage,
|
|
16
|
+
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage, codexLaunchControl = controlCodexLaunch,
|
|
16
17
|
adapterPort = 2026, adapterHost = "127.0.0.1",
|
|
17
18
|
readImages = () => imageSetupSummary({ env, home }).configured, readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
18
19
|
const options = { env, home };
|
|
@@ -46,17 +47,20 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
46
47
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
47
48
|
const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
|
|
48
49
|
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
49
|
-
prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence"],
|
|
50
|
+
prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence", "confirmed"],
|
|
51
|
+
codex_app: ["action", "operation", "intent", "confirmed"],
|
|
50
52
|
update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
|
|
51
53
|
preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
|
|
52
54
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
53
55
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
54
56
|
lastOperation = null;
|
|
55
|
-
if (input.action === "
|
|
57
|
+
if (input.action === "codex_app") {
|
|
58
|
+
lastOperation = { feature: "codex_app", result: await codexLaunchControl(input.operation, { ...options, host: adapterHost, port: adapterPort,
|
|
59
|
+
integration: clientIntegration, state: imageHostState, intent: input.intent, confirmed: input.confirmed, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
60
|
+
} else if (input.action === "prediction") {
|
|
56
61
|
lastOperation = { feature: "prediction", result: await predictionControl(input.operation, { ...options, integration: clientIntegration }) };
|
|
57
62
|
} else if (input.action === "image") {
|
|
58
|
-
if (input.operation
|
|
59
|
-
else if (["check", "repair", "open"].includes(input.operation)) lastOperation = { feature: "image", result: await imageHostControl(input.operation, { ...options, host: adapterHost, port: adapterPort, integration: clientIntegration, state: imageHostState, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
63
|
+
if (["check", "repair", "open", "focus", "restart"].includes(input.operation)) lastOperation = { feature: "image", result: await imageHostControl(input.operation, { ...options, host: adapterHost, port: adapterPort, integration: clientIntegration, state: imageHostState, confirmed: input.confirmed, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
60
64
|
else if (["pause", "resume"].includes(input.operation)) writeServicePreference("image_enabled", input.operation === "resume", options);
|
|
61
65
|
else lastOperation = { feature: "image", result: await imageControl(input, { ...options, providerRuntime, adapterPort, adapterHost }) };
|
|
62
66
|
} else if (input.action === "update") {
|
|
@@ -108,6 +112,15 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
108
112
|
return snapshot();
|
|
109
113
|
}
|
|
110
114
|
return { snapshot, busy: () => pending > 0, action(input) {
|
|
115
|
+
// Image-host evidence must not wait behind a user-initiated App restart:
|
|
116
|
+
// the host sends it with a short deadline as the new App starts.
|
|
117
|
+
if (input?.action === "image" && input.operation === "report") {
|
|
118
|
+
try {
|
|
119
|
+
if (Object.keys(input).some(key => !["action", "operation", "evidence"].includes(key))) throw new Error("Unknown setting action or field");
|
|
120
|
+
imageHostState.report(input.evidence);terminal?.image?.(imageHostState.snapshot());
|
|
121
|
+
return Promise.resolve(snapshot());
|
|
122
|
+
} catch (error) { return Promise.reject(error); }
|
|
123
|
+
}
|
|
111
124
|
const counted = input?.action !== "update";if (counted) pending++;
|
|
112
125
|
const operation = serial.then(() => apply(input)).finally(() => { if (counted) pending--; });serial = operation.catch(() => {});return operation;
|
|
113
126
|
} };
|