codex-copilot-dx 1.3.14 → 1.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/cli.mjs +2 -0
- package/bin/codex-image-host.mjs +11 -0
- package/docs/ARCHITECTURE.md +2 -2
- package/docs/REFERENCE.md +9 -4
- package/package.json +1 -1
- package/src/claude-capability-config.mjs +3 -2
- package/src/claude-models.mjs +3 -1
- package/src/cli-image.mjs +1 -1
- package/src/client-integration.mjs +4 -0
- package/src/clients/claude-models.mjs +3 -3
- package/src/codex-image-host-launch.mjs +38 -0
- package/src/codex-image-host.mjs +216 -0
- package/src/launcher.mjs +7 -4
- package/src/model-capabilities.mjs +9 -0
- package/src/prediction-control.mjs +1 -0
package/README.md
CHANGED
|
@@ -63,7 +63,7 @@ Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; th
|
|
|
63
63
|
Use the Web UI for accounts, APIs, models, client access, input suggestions, native images, local masking, appearance, diagnostics and updates. CLI commands remain available for automation and recovery. See the [control reference](docs/REFERENCE.md#webui-and-cli-controls).
|
|
64
64
|
|
|
65
65
|
- **Input suggestions:** new integrations attempt setup by default when Codex is closed. Saved off choices are retained. The Web UI can enable, disable, finish setup, open Codex and repair the bridge. Setup synchronizes Show predictions, adds App-profile trust and locally decrypts the prediction hosts' HTTPS traffic. App/thread eligibility still applies. [Details](docs/REFERENCE.md#optional-native-predictions).
|
|
66
|
-
- **Images:** Codex
|
|
66
|
+
- **Images:** Codex native host tools use the selected GitHub image model, with GPT Image 2.5 Flare as the default. Images start enabled; saved off choices are retained. On macOS with Codex 0.166+, start Codex through CCDX and use a new chat to activate host tools without changing ChatGPT sign-in or Apps. The Web UI provides model selection without an extra API key, MCP or CCDX image skill. [Details](docs/REFERENCE.md#native-image-generation).
|
|
67
67
|
- **Updates:** Settings → Install update downloads and verifies a stable release, then switches the installed service when idle. Busy work postpones the switch. Unmanaged launches require the installer or an installed command. [Details](docs/REFERENCE.md#installation-and-updates).
|
|
68
68
|
|
|
69
69
|
Web UI activity updates through server push; the terminal uses the same in-process activity feed. Reconnecting restores current state and bounded recent records.
|
package/bin/cli.mjs
CHANGED
|
@@ -376,6 +376,7 @@ async function reuseRunningAdapterIfAvailable() {
|
|
|
376
376
|
}
|
|
377
377
|
} catch (error) { console.warn(status("warn", error.message)); }
|
|
378
378
|
if (codexEnabled) await openCodex({ predictionPacUrl, predictionApp, predictionProfile, persistedPredictionRoute,
|
|
379
|
+
imageHost: imageEnabled ? await (await clientIntegrations()).imageHostLaunch() : null,
|
|
379
380
|
onPredictionRoute: route => { launchRoute = route; }, log: startupLogger("App") });
|
|
380
381
|
console.log(predictionStartupCheck({ configured: predictionConfigured, bridge: predictionPacUrl ? "running" : "unknown", launch_route: launchRoute }));
|
|
381
382
|
console.log(startupCheck(imageEnabled && imageMcpSkipped ? "warn" : "info", "Images", imageEnabled
|
|
@@ -533,6 +534,7 @@ try {
|
|
|
533
534
|
|
|
534
535
|
// Launch Codex when available. A running App is never forcibly restarted.
|
|
535
536
|
if (codexEnabled) await openCodex({ predictionPacUrl: nativePrediction?.pacUrl, predictionApp: nativePrediction?.app, predictionProfile: nativePrediction?.profile,
|
|
537
|
+
imageHost: imageEnabled ? await clientIntegration.imageHostLaunch() : null,
|
|
536
538
|
preparePredictionRoute: () => nativePrediction?.prepareRoute(), persistedPredictionRoute: persistentRoute?.status === "installed",
|
|
537
539
|
onPredictionRoute: route => clientIntegration?.launched(route), log: startupLogger("App") });
|
|
538
540
|
console.log(predictionStartupCheck(clientIntegration?.snapshot().prediction));
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { runCodexImageHost } from "../src/codex-image-host.mjs";
|
|
4
|
+
|
|
5
|
+
const args = process.argv.slice(2), split = args.indexOf("--");
|
|
6
|
+
const hostArgs = args.slice(0, split), argv = args.slice(split + 1);
|
|
7
|
+
const codex = hostArgs[hostArgs.indexOf("--codex") + 1];
|
|
8
|
+
const baseUrl = hostArgs[hostArgs.indexOf("--base-url") + 1];
|
|
9
|
+
if (split < 0 || !path.isAbsolute(codex || "") || !baseUrl) { console.error("Invalid CCDX image host launch configuration");process.exit(2); }
|
|
10
|
+
try { process.exitCode = await runCodexImageHost({ codex, argv, baseUrl }); }
|
|
11
|
+
catch { console.error("CCDX image host could not start the configured Codex runtime");process.exitCode = 1; }
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -11,7 +11,7 @@ Client integration, image tools and the dashboard are not a general plugin frame
|
|
|
11
11
|
| Provider composition | `provider-runtime.mjs`, `connection-runtime.mjs`, provider/access settings | Explicit selection, lifecycle, history namespaces and snapshots |
|
|
12
12
|
| Claude clients | `claude-gateway.mjs`, `claude-client-lifecycle.mjs`, `claude-client-config.mjs`, `claude-models.mjs` | Native Messages relay and field-owned reversible client setup |
|
|
13
13
|
| Client integration | `client-integration.mjs`, Codex config, native prediction | Client setup, optional start/stop, diagnostic snapshots |
|
|
14
|
-
| Native images | Images routes, GHC client, preference controls and legacy retirement | Native
|
|
14
|
+
| Native images | Images routes, native SDK host tools, GHC client, preference controls and legacy retirement | Native tool progress and generated-gallery images through the existing GitHub account; ChatGPT Apps and sign-in retained, no image MCP or separate credential |
|
|
15
15
|
| Management | CLI, dashboard, observability, package updates | Bounded metadata and explicit user actions |
|
|
16
16
|
| Shared foundations | Codex paths, file locks, atomic files, network routes | No dependency on inference or dashboard rendering |
|
|
17
17
|
|
|
@@ -1105,6 +1105,6 @@ Performance comparison is separate from runtime logic and reports paired timing
|
|
|
1105
1105
|
|
|
1106
1106
|
The 1.3.13 native helper groups uncached short CPU sequences under the existing shared core budget. Groups retain at most 512 total tokens and 16 KiB text. The existing core budget is divided between sequence workers, including its remainder, instead of repeatedly creating a full-budget partition for every short field. Tokenization, position IDs, attention scope and dynamic quantization remain per sequence. Already-known windows and single uncached sequences retain their previous paths; long and accelerator-eligible windows use the existing reader. Cancellation waits for physical acknowledgement, completed windows remain reusable, and the complete check still precedes upstream calls. Status advertises cpu_short_batch and reports cpu_batch_groups/cpu_batch_windows without retaining values.
|
|
1107
1107
|
|
|
1108
|
-
Claude App 3.x and 4.x share the inspected effort-capable adapter. Later unknown major versions retain conservative routes and preserve existing shared capability settings.
|
|
1108
|
+
Claude App 3.x and 4.x share the inspected effort-capable adapter. Later unknown major versions retain conservative routes and preserve existing shared capability settings. Contiguous effort declarations select the source-qualified reasoning route; a gapped declaration with at least two lower contiguous levels can expose that safe prefix with an App maximum cap, while retaining the complete upstream declaration and reporting the hidden levels as limited. Prior route spellings remain accepted for existing conversations. Resynchronization carries long-context preference and model order between the two known source-qualified spellings, and replaces only owned shared capability fields. No undeclared effort is added. The sidebar brand places its shared atom icon and text in one grid row so the intro icon's two-row span cannot offset the label.
|
|
1109
1109
|
|
|
1110
1110
|
Usage presentation maps configured api_ identifiers to current provider labels after aggregation. Rows, chart filters and historical statistics keep their original keys. Provider-label changes refresh only the table/model labels, preserving the selected raw model key, day and existing chart nodes. The native capability replay disables usage persistence and gives its process a temporary usage path; no production filter recognizes test model names or response IDs.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -212,9 +212,12 @@ heuristic or original-vendor limit is applied to an arbitrary relay deployment.
|
|
|
212
212
|
Claude configuration and gateway catalogs use the same compiled model plan.
|
|
213
213
|
Explicit App bindings use opaque source-qualified aliases and actual model/source
|
|
214
214
|
labels. Verified 3.x and 4.x App adapters can use a reasoning-compatible route when the
|
|
215
|
-
advertised levels form a client-expressible contiguous set.
|
|
216
|
-
|
|
217
|
-
levels are reported as limited
|
|
215
|
+
advertised levels form a client-expressible contiguous set. When a declaration has
|
|
216
|
+
a gap after at least two lower levels, the App can select that safe lower prefix;
|
|
217
|
+
the higher levels are reported as limited and remain in the source declaration.
|
|
218
|
+
For example, `low/medium/high/max` shows `low/medium/high` without inventing
|
|
219
|
+
`xhigh`. Older compatibility routes remain resolvable for that authorized
|
|
220
|
+
deployment. Unsupported effort requests fail explicitly.
|
|
218
221
|
No tool permission or safety-review setting is disabled for compatibility.
|
|
219
222
|
|
|
220
223
|
The App Code host and independent Code share some settings. CCDX plans them once,
|
|
@@ -579,7 +582,9 @@ was recreated on the original address, not that gray text appeared.
|
|
|
579
582
|
|
|
580
583
|
Codex’s built-in `image_gen.imagegen` tool uses the current CCDX address for separate Images API requests. CCDX serves `POST /v1/images/generations` and `POST /v1/images/edits`, reuses the existing GitHub Copilot authentication, and maps the native client’s `gpt-image-2` request to the selected available GHC image model. GPT Image 2.5 Flare is the default when advertised. The `X-CCDX-Image-Model` response header identifies the actual model. Image usage counts toward the GitHub account’s image credits; organization model policies still apply. The image model does not replace the selected conversation model.
|
|
581
584
|
|
|
582
|
-
Codex
|
|
585
|
+
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 keeps image results in the chat history; the App treats successful image output as generated-gallery media. 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.
|
|
586
|
+
|
|
587
|
+
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. Start Codex through CCDX and use a new chat to register the host tool; a running App is never forcibly restarted. 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.
|
|
583
588
|
|
|
584
589
|
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:
|
|
585
590
|
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
4
4
|
import { m365Paths, readM365Json } from "./m365-settings.mjs";
|
|
5
|
-
import { claudeEffortsExpressible } from "./model-capabilities.mjs";
|
|
5
|
+
import { claudeEffortsExpressible, claudeEffortPrefix } from "./model-capabilities.mjs";
|
|
6
6
|
import { claudeModelEntries } from "./claude-models.mjs";
|
|
7
7
|
import { claudeClientPaths, reconcileClaudeConfiguration } from "./claude-client-config.mjs";
|
|
8
8
|
|
|
@@ -41,7 +41,8 @@ export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} }
|
|
|
41
41
|
output = Math.max(output, values.max_output_tokens || 0);
|
|
42
42
|
const efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
|
|
43
43
|
if (efforts.length && !claudeEffortsExpressible(values)) limitations.push({ model: model.id, code: "reasoning_levels_limited" });
|
|
44
|
-
|
|
44
|
+
const visibleEfforts = desktop && /^mythos-ccdx-\d+$/.test(id) ? claudeEffortPrefix(values) : claudeEffortsExpressible(values) ? efforts : [];
|
|
45
|
+
if (visibleEfforts.length) caps.push(`${id.toLowerCase()}=${["effort", ...(visibleEfforts.includes("xhigh") ? ["xhigh_effort"] : []), ...(visibleEfforts.includes("max") ? ["max_effort"] : [])].join(",")}`);
|
|
45
46
|
if (values.web_search && !values.web_search.includes("messages")) limitations.push({ model: model.id, code: "search_messages_unavailable" });
|
|
46
47
|
}
|
|
47
48
|
if (!safeContext) context = 0;
|
package/src/claude-models.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { modelReasoningEfforts } from "./provider-metadata.mjs";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import { modelDisplayName } from "./model-display.mjs";
|
|
4
|
+
import { claudeEffortPrefix } from "./model-capabilities.mjs";
|
|
4
5
|
|
|
5
6
|
const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
6
7
|
|
|
@@ -25,7 +26,8 @@ export function claudeModelEntries(models, { desktopAliases = false } = {}) {
|
|
|
25
26
|
if (ids.has(name) || name !== model.id && upstreamIds.has(name)) throw Object.assign(new Error("Claude model aliases collide; refresh the provider catalog"), { code: "claude_model_alias_collision", statusCode: 503 });
|
|
26
27
|
ids.add(name);
|
|
27
28
|
const advertised = model.capability?.values.reasoning === false ? [] : model.capability?.values.reasoning_efforts || modelReasoningEfforts(model);
|
|
28
|
-
const
|
|
29
|
+
const prefix = /^mythos-ccdx-\d+$/.test(name) ? claudeEffortPrefix(model.capability?.values) : [];
|
|
30
|
+
const maxEffort = prefix.at(-1) || EFFORTS.filter(value => advertised?.includes(value)).at(-1);
|
|
29
31
|
return { name, ...(model.display_name || name !== claudeClientModelId(model.id) ? { labelOverride: modelDisplayName(model) } : {}),
|
|
30
32
|
...(model.capability?.values.context_window >= 1000000 ? { supports1m: true } : {}), ...(maxEffort ? { maxEffort } : {}) };
|
|
31
33
|
});
|
package/src/cli-image.mjs
CHANGED
|
@@ -22,6 +22,6 @@ export async function runImageCommand({ action, model, output = process.stdout,
|
|
|
22
22
|
if (result.availability === "selected_unavailable") output.write("Saved image model is unavailable; choose an available model.\n");
|
|
23
23
|
for (const item of result.models || []) output.write(`${item.id === result.selected_model ? "*" : " "} ${terminalCell(item.name || item.id)} (${terminalCell(item.id)})\n`);
|
|
24
24
|
if (!result.models?.length) output.write("Read the GitHub catalog in Model sources or use source github models --refresh.\n");
|
|
25
|
-
output.write("Uses
|
|
25
|
+
output.write("Uses Codex native host tools and the existing GitHub account. Start Codex through CCDX, then use a new chat.\n");
|
|
26
26
|
return result;
|
|
27
27
|
}
|
|
@@ -60,6 +60,10 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
|
|
|
60
60
|
} catch { warning("Legacy image cleanup was incomplete; review the old image files before the next CCDX start. The old image service is retired."); }
|
|
61
61
|
}
|
|
62
62
|
return {
|
|
63
|
+
async imageHostLaunch(options = {}) {
|
|
64
|
+
try { return await (await import("./codex-image-host-launch.mjs")).prepareImageHostLaunch({ host, port, ...options }); }
|
|
65
|
+
catch (error) { warning(error.message);return null; }
|
|
66
|
+
},
|
|
63
67
|
retireImages,
|
|
64
68
|
async configure() {
|
|
65
69
|
try {
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { claudeModelEntries } from "../claude-models.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { claudeEffortPrefix } from "../model-capabilities.mjs";
|
|
3
3
|
|
|
4
4
|
export function claudeDeploymentId(model, route, { desktopEffortAliases = false } = {}) {
|
|
5
5
|
const number = route.slice("ccdx/model-".length);
|
|
6
6
|
const native = /^claude-(?:opus|sonnet|haiku)-\d[\d.-]*(?:-latest)?$/.test(model.id);
|
|
7
|
-
// This host alias is used only when
|
|
7
|
+
// This host alias is used only when a safe contiguous effort menu is supported.
|
|
8
8
|
// Both spellings remain accepted routes when capability evidence changes.
|
|
9
9
|
return native ? `ccdx-${number}.anthropic.${model.id.replace(/(\d)\.(\d)/g, "$1-$2")}`
|
|
10
|
-
: desktopEffortAliases &&
|
|
10
|
+
: desktopEffortAliases && claudeEffortPrefix(model.capability?.values).length ? `mythos-ccdx-${number}` : `ccdx/claude-compatible-${number}`;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
export function claudeRouteAliases(model, route, desktop) {
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { userSettingsPath, servicePreferences } from "./user-settings.mjs";
|
|
7
|
+
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
8
|
+
import { installedPredictionApp } from "./native-prediction-app.mjs";
|
|
9
|
+
import { autoLaunchEnabled } from "./launcher.mjs";
|
|
10
|
+
import { adapterBaseUrl } from "./running-adapter.mjs";
|
|
11
|
+
|
|
12
|
+
const execute = promisify(execFile);
|
|
13
|
+
const PREFIX = "#!/bin/sh\n# CCDX native image host\n";
|
|
14
|
+
const quote = value => "'" + value.replaceAll("'", "'\"'\"'") + "'";
|
|
15
|
+
|
|
16
|
+
export function imageHostLauncherPath(options = {}) {
|
|
17
|
+
return path.join(path.dirname(userSettingsPath(options)), "native-image-host", "codex-cli");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function prepareImageHostLaunch({ env = process.env, home, platform = process.platform, host = "127.0.0.1", port = 2026,
|
|
21
|
+
discoverApp = installedPredictionApp, exec = execute, node = process.execPath,
|
|
22
|
+
entry = fileURLToPath(new URL("../bin/codex-image-host.mjs", import.meta.url)) } = {}) {
|
|
23
|
+
if (platform !== "darwin" || !autoLaunchEnabled(env) || !servicePreferences({ env, home }).image_enabled) return null;
|
|
24
|
+
const wrapper = imageHostLauncherPath({ env, home });
|
|
25
|
+
if (env.CODEX_CLI_PATH?.trim() && path.resolve(env.CODEX_CLI_PATH) !== wrapper) throw new Error("A custom Codex CLI route is already configured; image host setup was preserved");
|
|
26
|
+
const app = await discoverApp({ env, platform });
|
|
27
|
+
const codex = path.join(app.app, "Contents", "Resources", "codex-cli", "CodexCLI.app", "Contents", "MacOS", "codex");
|
|
28
|
+
if (!fs.statSync(codex).isFile()) throw new Error("The verified App has no native Codex runtime");
|
|
29
|
+
const result = await exec(codex, ["--version"], { encoding: "utf8", timeout: 3000, maxBuffer: 4096 });
|
|
30
|
+
const match = /codex-cli\s+0\.(\d+)\./.exec(String(result?.stdout ?? result));
|
|
31
|
+
if (!match || Number(match[1]) < 166) throw new Error("Native host tools require Codex 0.166 or later");
|
|
32
|
+
for (const value of [node, entry, codex]) if (!path.isAbsolute(value) || /[\0\r\n]/.test(value)) throw new Error("Invalid image host executable path");
|
|
33
|
+
if (fs.existsSync(wrapper) && !fs.readFileSync(wrapper, "utf8").startsWith(PREFIX)) throw new Error("Image host launcher ownership conflict; existing file preserved");
|
|
34
|
+
const content = PREFIX + "exec " + [node, entry, "--codex", codex, "--base-url", adapterBaseUrl(host, port) + "/v1", "--"].map(quote).join(" ") + ' "$@"\n';
|
|
35
|
+
fs.mkdirSync(path.dirname(wrapper), { recursive: true, mode: 0o700 });
|
|
36
|
+
atomicWriteFileIfChangedSync(wrapper, content, { mode: 0o700 });fs.chmodSync(wrapper, 0o700);
|
|
37
|
+
return { app: app.app, env: { CODEX_CLI_PATH: wrapper } };
|
|
38
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { once } from "node:events";
|
|
6
|
+
import { StringDecoder } from "node:string_decoder";
|
|
7
|
+
|
|
8
|
+
export const IMAGE_HOST_NAMESPACE = "ccdx_images";
|
|
9
|
+
export const IMAGE_HOST_TOOL = Object.freeze({
|
|
10
|
+
type: "namespace", name: IMAGE_HOST_NAMESPACE,
|
|
11
|
+
description: "Codex host image generation and editing through CCDX. Generated images appear in the native image gallery.",
|
|
12
|
+
tools: [{ type: "function", name: "imagegen", deferLoading: false,
|
|
13
|
+
description: "Generate an image or edit reference images. Use this host tool for image requests in this chat. Edit defaults to the last generated image when no references are supplied. Results include native image content and a saved local file.",
|
|
14
|
+
inputSchema: { type: "object", additionalProperties: false, required: ["mode", "prompt"], properties: {
|
|
15
|
+
mode: { type: "string", enum: ["generate", "edit"] }, prompt: { type: "string" },
|
|
16
|
+
transparent_background: { type: "boolean" },
|
|
17
|
+
referenced_image_paths: { type: "array", maxItems: 5, items: { type: "string" }, description: "Images within this workspace, attached by the user, or generated in this chat." },
|
|
18
|
+
num_last_images_to_include: { type: "integer", minimum: 0, maximum: 5 },
|
|
19
|
+
quality: { type: "string", enum: ["auto", "low", "medium", "high"] },
|
|
20
|
+
size: { type: "string", enum: ["auto", "1024x1024", "1536x1024", "1024x1536"] },
|
|
21
|
+
} } }],
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export function addImageHostTool(params) {
|
|
25
|
+
const existing = params.dynamicTools || [];
|
|
26
|
+
if (!Array.isArray(existing) || existing.some(tool => tool?.name === IMAGE_HOST_NAMESPACE)) {
|
|
27
|
+
throw new Error("The CCDX image host namespace is already configured");
|
|
28
|
+
}
|
|
29
|
+
return { ...params, dynamicTools: [...existing, IMAGE_HOST_TOOL] };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function imageHostBaseUrl(value) {
|
|
33
|
+
const url = new URL(value);
|
|
34
|
+
if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)
|
|
35
|
+
|| url.pathname !== "/v1" || url.username || url.password || url.search || url.hash) {
|
|
36
|
+
throw new Error("Image host requires the local CCDX /v1 endpoint");
|
|
37
|
+
}
|
|
38
|
+
return url.href.replace(/\/$/, "");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function boundedJson(response) {
|
|
42
|
+
let size = 0;const chunks = [];
|
|
43
|
+
for await (const chunk of response.body) {
|
|
44
|
+
size += chunk.length;
|
|
45
|
+
if (size > 48 * 1024 * 1024) throw new Error("Image backend response exceeds its limit");
|
|
46
|
+
chunks.push(chunk);
|
|
47
|
+
}
|
|
48
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function imageType(bytes) {
|
|
52
|
+
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return ["png", "image/png"];
|
|
53
|
+
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return ["jpg", "image/jpeg"];
|
|
54
|
+
if (bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") return ["webp", "image/webp"];
|
|
55
|
+
throw new Error("The image backend did not return a supported image");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const inside = (root, file) => file === root || file.startsWith(root + path.sep);
|
|
59
|
+
|
|
60
|
+
export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchImpl = fetch, imageEnabled,
|
|
61
|
+
now = Date.now } = {}) {
|
|
62
|
+
baseUrl = imageHostBaseUrl(baseUrl);
|
|
63
|
+
const requests = new Map(), threads = new Map(), active = new Map();
|
|
64
|
+
let experimental = false, sequence = 0;
|
|
65
|
+
const root = path.join(codexHome, "generated_images", "ccdx");
|
|
66
|
+
const folder = id => path.join(root, createHash("sha256").update(id).digest("hex").slice(0, 32));
|
|
67
|
+
const enabled = imageEnabled || (async () => {
|
|
68
|
+
try {
|
|
69
|
+
const response = await fetchImpl(baseUrl.replace(/\/v1$/, "/_ccdx/settings"), { signal: AbortSignal.timeout(1000) });
|
|
70
|
+
if (!response.ok) return false;
|
|
71
|
+
const settings = await boundedJson(response);return settings.features?.image?.enabled === true;
|
|
72
|
+
} catch { return false; }
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
async function readReference(value, context, id) {
|
|
76
|
+
if (value.startsWith("data:image/")) return value;
|
|
77
|
+
let file;
|
|
78
|
+
try {
|
|
79
|
+
file = await fs.realpath(path.resolve(context.cwd, value));
|
|
80
|
+
const own = await fs.realpath(folder(id)).catch(() => folder(id));
|
|
81
|
+
const attached = await Promise.all(context.attachments.filter(v => !v.startsWith("data:")).map(v => fs.realpath(v).catch(() => null)));
|
|
82
|
+
const roots = await Promise.all([context.cwd, ...context.roots].map(v => fs.realpath(v).catch(() => null)));
|
|
83
|
+
const generated = await Promise.all(context.generated.map(v => fs.realpath(v).catch(() => null)));
|
|
84
|
+
if (!inside(own, file) && !generated.includes(file) && !attached.includes(file)
|
|
85
|
+
&& !roots.some(v => v && inside(v, file))) throw new Error("scope");
|
|
86
|
+
const stat = await fs.stat(file);
|
|
87
|
+
if (!stat.isFile() || stat.size > 10 * 1024 * 1024) throw new Error("size");
|
|
88
|
+
const bytes = await fs.readFile(file), [, mime] = imageType(bytes);
|
|
89
|
+
return "data:" + mime + ";base64," + bytes.toString("base64");
|
|
90
|
+
} catch { throw new Error("Reference images must be readable images in this workspace, user attachments, or this chat"); }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function recentImages(id, context, count) {
|
|
94
|
+
let disk = [];
|
|
95
|
+
try { disk = (await fs.readdir(folder(id))).filter(v => /\.(png|jpg|webp)$/.test(v)).sort().map(v => path.join(folder(id), v)); }
|
|
96
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
97
|
+
return [...new Set([...disk, ...context.generated])].slice(-count);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function runImage(params, signal) {
|
|
101
|
+
const args = params.arguments;
|
|
102
|
+
if (!args || typeof args !== "object" || Array.isArray(args) || !["generate", "edit"].includes(args.mode)
|
|
103
|
+
|| typeof args.prompt !== "string" || !args.prompt.trim()) throw new Error("Choose generate or edit and supply an image prompt");
|
|
104
|
+
const id = params.threadId, context = threads.get(id);
|
|
105
|
+
if (!context) throw new Error("Resume this chat through CCDX before using the image host");
|
|
106
|
+
const references = args.referenced_image_paths || [];
|
|
107
|
+
if (!Array.isArray(references) || references.some(v => typeof v !== "string") || references.length > 5) throw new Error("Choose up to five image references");
|
|
108
|
+
const count = args.num_last_images_to_include;
|
|
109
|
+
if (count !== undefined && (!Number.isInteger(count) || count < 0 || count > 5)) throw new Error("Choose zero to five recent images");
|
|
110
|
+
const body = { model: "gpt-image-2", prompt: args.prompt,
|
|
111
|
+
background: args.transparent_background === true ? "transparent" : "auto",
|
|
112
|
+
quality: args.quality || "auto", size: args.size || "auto" };
|
|
113
|
+
if (args.mode === "edit") {
|
|
114
|
+
let selected = references.length ? references : context.attachments;
|
|
115
|
+
if (count !== undefined ? count > 0 : !selected.length) selected = [...selected, ...await recentImages(id, context, count ?? 1)];
|
|
116
|
+
if (!selected.length || selected.length > 5) throw new Error("Editing requires one to five images");
|
|
117
|
+
body.images = await Promise.all(selected.map(async value => ({ image_url: await readReference(value, context, id) })));
|
|
118
|
+
} else if (references.length || count) throw new Error("Use edit mode with image references");
|
|
119
|
+
const response = await fetchImpl(baseUrl + "/images/" + (args.mode === "edit" ? "edits" : "generations"), {
|
|
120
|
+
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal,
|
|
121
|
+
});
|
|
122
|
+
const result = await boundedJson(response);
|
|
123
|
+
if (!response.ok) throw new Error(result.error?.message || "Image backend returned HTTP " + response.status);
|
|
124
|
+
const pixels = result.data?.[0]?.b64_json;
|
|
125
|
+
if (typeof pixels !== "string") throw new Error("Image backend returned no image");
|
|
126
|
+
const bytes = Buffer.from(pixels, "base64");
|
|
127
|
+
if (!bytes.length || bytes.length > 32 * 1024 * 1024 || bytes.toString("base64") !== pixels) throw new Error("Image backend returned invalid image data");
|
|
128
|
+
const [ext, mime] = imageType(bytes);
|
|
129
|
+
signal.throwIfAborted();
|
|
130
|
+
const directory = folder(id);await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
131
|
+
const savedPath = path.join(directory, String(now()).padStart(16, "0") + "-" + String(sequence++).padStart(6, "0") + "-" + randomUUID() + "." + ext);
|
|
132
|
+
await fs.writeFile(savedPath, bytes, { mode: 0o600, flag: "wx" });
|
|
133
|
+
if (signal.aborted) { await fs.unlink(savedPath);signal.throwIfAborted(); }
|
|
134
|
+
context.generated.push(savedPath);
|
|
135
|
+
return { success: true, contentItems: [{ type: "inputImage", imageUrl: "data:" + mime + ";base64," + pixels },
|
|
136
|
+
{ type: "inputText", text: JSON.stringify({ savedPath, model: response.headers.get("x-ccdx-image-model") || "selected GitHub image model" }) }] };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
async client(message) {
|
|
141
|
+
if (message.method === "initialize") experimental = message.params?.capabilities?.experimentalApi === true;
|
|
142
|
+
if (["thread/start", "thread/resume", "thread/fork"].includes(message.method)) {
|
|
143
|
+
requests.set(JSON.stringify(message.id), { method: message.method, params: message.params || {} });
|
|
144
|
+
if (message.method === "thread/start" && experimental && await enabled()) return { ...message, params: addImageHostTool(message.params || {}) };
|
|
145
|
+
}
|
|
146
|
+
if (message.method === "turn/start") {
|
|
147
|
+
const context = threads.get(message.params?.threadId);
|
|
148
|
+
if (context) context.attachments = (message.params.input || []).flatMap(value => value.type === "localImage" ? [path.resolve(context.cwd, value.path)]
|
|
149
|
+
: value.type === "image" && typeof value.url === "string" && value.url.startsWith("data:image/") ? [value.url] : []);
|
|
150
|
+
}
|
|
151
|
+
if (message.method === "turn/interrupt") for (const value of active.values()) if (value.threadId === message.params?.threadId) value.controller.abort(new Error("Image request cancelled"));
|
|
152
|
+
return message;
|
|
153
|
+
},
|
|
154
|
+
codex(message) {
|
|
155
|
+
const pending = requests.get(JSON.stringify(message.id));
|
|
156
|
+
if (pending && !message.method) {
|
|
157
|
+
requests.delete(JSON.stringify(message.id));const thread = message.result?.thread;
|
|
158
|
+
if (thread?.id && thread.cwd) threads.set(thread.id, { cwd: thread.cwd, roots: pending.params.runtimeWorkspaceRoots || [], attachments: [], generated: [] });
|
|
159
|
+
}
|
|
160
|
+
if (message.method === "item/completed" && message.params?.item?.type === "imageGeneration" && message.params.item.savedPath) {
|
|
161
|
+
threads.get(message.params.threadId)?.generated.push(message.params.item.savedPath);
|
|
162
|
+
}
|
|
163
|
+
if (message.id === undefined || message.method !== "item/tool/call" || message.params?.namespace !== IMAGE_HOST_NAMESPACE || message.params?.tool !== "imagegen") return false;
|
|
164
|
+
const controller = new AbortController(), key = JSON.stringify(message.id);
|
|
165
|
+
active.set(key, { controller, threadId: message.params.threadId });
|
|
166
|
+
void runImage(message.params, AbortSignal.any([controller.signal, AbortSignal.timeout(180000)]))
|
|
167
|
+
.then(result => sendToCodex({ id: message.id, result }))
|
|
168
|
+
.catch(error => sendToCodex({ id: message.id, result: { success: false, contentItems: [{ type: "inputText", text: error.message }] } }))
|
|
169
|
+
.finally(() => active.delete(key));
|
|
170
|
+
return true;
|
|
171
|
+
},
|
|
172
|
+
close() { for (const value of active.values()) value.controller.abort(new Error("Image host closed")); },
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function lines(stream, accept) {
|
|
177
|
+
const decoder = new StringDecoder("utf8");let buffer = "";
|
|
178
|
+
const data = chunk => {
|
|
179
|
+
buffer += decoder.write(chunk);let boundary;
|
|
180
|
+
while ((boundary = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, boundary);buffer = buffer.slice(boundary + 1);accept(line); }
|
|
181
|
+
};
|
|
182
|
+
const end = () => { buffer += decoder.end();if (buffer) accept(buffer); };
|
|
183
|
+
stream.on("data", data);stream.on("end", end);
|
|
184
|
+
return () => { stream.removeListener("data", data);stream.removeListener("end", end); };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export async function runCodexImageHost({ codex, argv, baseUrl, env = process.env, input = process.stdin, output = process.stdout, error = process.stderr, spawnImpl = spawn } = {}) {
|
|
188
|
+
const args = argv || [], at = args.indexOf("app-server"), rest = args.slice(at + 1);
|
|
189
|
+
const stdio = at >= 0 && !["daemon", "proxy", "generate-ts", "generate-json-schema"].includes(rest[0])
|
|
190
|
+
&& !rest.some(value => /^--listen=(?!stdio:\/\/)/.test(value))
|
|
191
|
+
&& (rest.indexOf("--listen") < 0 || rest[rest.indexOf("--listen") + 1] === "stdio://");
|
|
192
|
+
const childEnv = { ...env, CODEX_APP_RUNTIME_CLI_PATH: codex };delete childEnv.CODEX_CLI_PATH;
|
|
193
|
+
const child = spawnImpl(codex, args, { env: childEnv, stdio: ["pipe", "pipe", "pipe"] });
|
|
194
|
+
child.stdin.on("error", () => {});child.stderr.pipe(error, { end: false });
|
|
195
|
+
let bridge, queue = Promise.resolve();const cleanups = [];
|
|
196
|
+
const write = message => { if (!child.stdin.destroyed) child.stdin.write(JSON.stringify(message) + "\n"); };
|
|
197
|
+
if (!stdio) { input.pipe(child.stdin);child.stdout.pipe(output, { end: false }); }
|
|
198
|
+
else {
|
|
199
|
+
bridge = createImageHostBridge({ baseUrl, codexHome: path.resolve(env.CODEX_HOME || path.join(env.HOME || process.env.HOME, ".codex")), sendToCodex: write });
|
|
200
|
+
cleanups.push(lines(input, raw => {
|
|
201
|
+
queue = queue.then(async () => {
|
|
202
|
+
let message;try { message = JSON.parse(raw); } catch { child.stdin.write(raw + "\n");return; }
|
|
203
|
+
try { const next = await bridge.client(message);if (next === message) child.stdin.write(raw + "\n");else write(next); }
|
|
204
|
+
catch (failure) { output.write(JSON.stringify({ id: message.id, error: { code: -32602, message: failure.message } }) + "\n"); }
|
|
205
|
+
});
|
|
206
|
+
}));
|
|
207
|
+
cleanups.push(lines(child.stdout, raw => { let value;try { value = JSON.parse(raw); } catch {}if (!value || !bridge.codex(value)) output.write(raw + "\n"); }));
|
|
208
|
+
const end = () => { void queue.finally(() => { bridge.close();child.stdin.end(); }); };
|
|
209
|
+
input.on("end", end);cleanups.push(() => input.removeListener("end", end));
|
|
210
|
+
}
|
|
211
|
+
const stop = signal => { bridge?.close();child.kill(signal); };
|
|
212
|
+
const interrupt = () => stop("SIGINT"), terminate = () => stop("SIGTERM");
|
|
213
|
+
process.once("SIGINT", interrupt);process.once("SIGTERM", terminate);
|
|
214
|
+
try { const [code, signal] = await once(child, "exit");await queue;return code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 1); }
|
|
215
|
+
finally { bridge?.close();for (const cleanup of cleanups) cleanup();input.unpipe(child.stdin);input.pause();process.removeListener("SIGINT", interrupt);process.removeListener("SIGTERM", terminate); }
|
|
216
|
+
}
|
package/src/launcher.mjs
CHANGED
|
@@ -61,7 +61,7 @@ export function macPredictionAppProcesses(app, { exec = execFileSync } = {}) {
|
|
|
61
61
|
return rows;
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
export async function openCodex({ env = process.env, spawnImpl = spawn, platform = process.platform, predictionPacUrl = null, predictionApp = null, predictionProfile = null,
|
|
64
|
+
export async function openCodex({ env = process.env, spawnImpl = spawn, platform = process.platform, predictionPacUrl = null, predictionApp = null, predictionProfile = null, imageHost = null,
|
|
65
65
|
preparePredictionRoute, persistedPredictionRoute = false, onPredictionRoute = () => {}, log = console.log,
|
|
66
66
|
resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses,
|
|
67
67
|
macAppProcesses = macPredictionAppProcesses } = {}) {
|
|
@@ -124,6 +124,9 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
124
124
|
return false;
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
+
const imageArgs = platform === "darwin" && imageHost?.env?.CODEX_CLI_PATH
|
|
128
|
+
? ["--env", "CODEX_CLI_PATH=" + imageHost.env.CODEX_CLI_PATH] : [];
|
|
129
|
+
if (imageArgs.length) log(status("info", "Image host configured for the next Codex launch and new chats; a running App is not restarted"));
|
|
127
130
|
const extraArgs = isPredictionPacUrl(predictionPacUrl)
|
|
128
131
|
&& APP_PATH_CANDIDATES.includes(predictionApp)
|
|
129
132
|
? ["--args", `--proxy-pac-url=${predictionPacUrl}`] : [];
|
|
@@ -140,7 +143,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
140
143
|
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");
|
|
141
144
|
}
|
|
142
145
|
await preparePredictionRoute?.();
|
|
143
|
-
if (!await tryOpen([predictionApp, ...extraArgs], { spawnImpl })) {
|
|
146
|
+
if (!await tryOpen([predictionApp, ...imageArgs, ...extraArgs], { spawnImpl })) {
|
|
144
147
|
onPredictionRoute("unverified");log(status("warn", "Could not open Codex App"));return false;
|
|
145
148
|
}
|
|
146
149
|
for (let attempt = 0; attempt < 10; attempt++) {
|
|
@@ -157,9 +160,9 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
157
160
|
onPredictionRoute("unverified");log(status("warn", `Optional macOS prediction launch skipped: ${error.message}`));return false;
|
|
158
161
|
}
|
|
159
162
|
}
|
|
160
|
-
const attempts = launchAttempts();
|
|
163
|
+
const attempts = imageArgs.length && APP_PATH_CANDIDATES.includes(imageHost.app) ? [[imageHost.app]] : launchAttempts();
|
|
161
164
|
for (const attempt of attempts) {
|
|
162
|
-
const args = [...attempt, ...extraArgs];
|
|
165
|
+
const args = [...attempt, ...imageArgs, ...extraArgs];
|
|
163
166
|
if (await tryOpen(args, { spawnImpl })) {
|
|
164
167
|
log(status("ok", "Codex opened"));
|
|
165
168
|
return true;
|
|
@@ -75,6 +75,15 @@ export function claudeEffortsExpressible(values = {}) {
|
|
|
75
75
|
return levels.length > 0 && levels.every(value => native.includes(value)) && native.slice(0, Math.max(...levels.map(value => native.indexOf(value))) + 1).every(value => levels.includes(value));
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
export function claudeEffortPrefix(values = {}) {
|
|
79
|
+
const levels = values.reasoning === false ? [] : values.reasoning_efforts || [];
|
|
80
|
+
const native = ["low", "medium", "high", "xhigh", "max"];
|
|
81
|
+
if (!Array.isArray(levels) || !levels.length || new Set(levels).size !== levels.length || levels.some(value => !native.includes(value))) return [];
|
|
82
|
+
const missing = native.findIndex(value => !levels.includes(value));
|
|
83
|
+
const prefix = native.slice(0, missing < 0 ? native.length : missing);
|
|
84
|
+
return prefix.length === levels.length || prefix.length >= 2 ? prefix : [];
|
|
85
|
+
}
|
|
86
|
+
|
|
78
87
|
export function constrainModelRequest(body, capability, protocol) {
|
|
79
88
|
const values = capability?.values || {}, outputKey = protocol === "messages" ? "max_tokens" : protocol === "responses" ? "max_output_tokens" : "max_completion_tokens";
|
|
80
89
|
let result = body;const applied = [];
|
|
@@ -29,6 +29,7 @@ export async function controlPrediction(operation, { integration, nativeOperatio
|
|
|
29
29
|
if (!native) throw new Error("Prediction bridge is unavailable");
|
|
30
30
|
await native.prepareRoute?.();
|
|
31
31
|
return { opened: await openCodex({ predictionPacUrl: native.pacUrl, predictionApp: native.app, predictionProfile: native.profile,
|
|
32
|
+
imageHost: await integration.imageHostLaunch?.({ env: { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" } }),
|
|
32
33
|
env: { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" }, persistedPredictionRoute: false,
|
|
33
34
|
preparePredictionRoute: () => native.prepareRoute?.(), onPredictionRoute: value => integration.launched(value) }) };
|
|
34
35
|
}
|