Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(codex): preserve recall on Windows spawn failure (#3308)

huangruiteng379c19f66ea6
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjs
index 24d6fd4c2..0a2fd44d9 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs
@@ -13,11 +13,11 @@
* is just `{}`.
*/
-import { spawn } from "node:child_process";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { loadConfig } from "./config.mjs";
+import { trySpawnCodex } from "./codex-launch.mjs";
import { createLogger } from "./debug-log.mjs";
import {
buildCodexExecArgs,
@@ -415,11 +415,11 @@ async function runCodexCompressor(prompt, profile) {
OPENVIKING_AUTO_CAPTURE: "0",
OPENVIKING_RECALL_COMPRESS: "0",
};
+ let child = null;
+ let timer = null;
let done = false;
let timedOut = false;
let stderr = "";
- const child = spawn("codex", args, { env, stdio: ["pipe", "ignore", "pipe"] });
- activeCompressor = child;
const finish = (value, { runtimeFailed = false } = {}) => {
if (done) return;
done = true;
@@ -438,7 +438,15 @@ async function runCodexCompressor(prompt, profile) {
}
resolve(value);
};
- const timer = setTimeout(() => {
+ const launch = trySpawnCodex(args, { env, stdio: ["pipe", "ignore", "pipe"] });
+ if (launch.error) {
+ logError("compress_spawn", launch.error);
+ finish(null, { runtimeFailed: true });
+ return;
+ }
+ child = launch.child;
+ activeCompressor = child;
+ timer = setTimeout(() => {
timedOut = true;
logError("compress_timeout", `timed out after ${cfg.recallCompressTimeoutMs}ms`);
try {
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
index 2089b8775..a1ca93139 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
@@ -6,9 +6,37 @@ import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
+import { resolveCodexLaunch, trySpawnCodex } from "./codex-launch.mjs";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
+test("Windows Codex launch bypasses the npm POSIX shim", () => {
+ const npmBin = String.raw`C:\Users\test\AppData\Roaming\npm`;
+ const npmEntryPoint = String.raw`C:\Users\test\AppData\Roaming\npm\node_modules\@openai\codex\bin\codex.js`;
+ const launch = resolveCodexLaunch({
+ platform: "win32",
+ pathValue: `${npmBin};C:\\Windows\\System32`,
+ execPath: String.raw`C:\Program Files\nodejs\node.exe`,
+ pathExists: (candidate) => candidate === npmEntryPoint,
+ });
+
+ assert.deepEqual(launch, {
+ command: String.raw`C:\Program Files\nodejs\node.exe`,
+ argsPrefix: [npmEntryPoint],
+ });
+});
+
+test("Codex launch converts a synchronous spawn failure into a fallback signal", () => {
+ const failure = Object.assign(new Error("spawn EPERM"), { code: "EPERM" });
+ const result = trySpawnCodex(["exec"], { stdio: "pipe" }, {
+ resolveLaunch: () => ({ command: "codex", argsPrefix: [] }),
+ spawnImpl: () => { throw failure; },
+ });
+
+ assert.equal(result.child, null);
+ assert.equal(result.error, failure);
+});
+
function readRequestBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
@@ -113,7 +141,14 @@ printf '%s' "$FAKE_CODEX_OUTPUT" > "$output_path"
}
}
-async function runEndpointCompressionCase({ prompt, entry, rendered, compressorOutput, exitCode = 0 }) {
+async function runEndpointCompressionCase({
+ prompt,
+ entry,
+ rendered,
+ compressorOutput,
+ exitCode = 0,
+ extraEnv = {},
+}) {
const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-endpoint-compress-"));
let requestBody = null;
try {
@@ -149,11 +184,13 @@ async function runEndpointCompressionCase({ prompt, entry, rendered, compressorO
OPENVIKING_SCORE_THRESHOLD: "0",
OPENVIKING_TIMEOUT_MS: "5000",
OPENVIKING_URL: baseUrl,
+ ...extraEnv,
},
));
+ const compressorCallLog = await readFile(callLog, "utf-8").catch(() => "");
return {
output: JSON.parse(result.stdout.trim()),
- compressorCalls: (await readFile(callLog, "utf-8")).trim().split("\n").length,
+ compressorCalls: compressorCallLog.trim().split("\n").filter(Boolean).length,
requestBody,
};
}, { exitCode });
@@ -349,6 +386,45 @@ test("auto-recall falls back to a bounded deterministic digest when endpoint com
assert.equal(result.compressorCalls, 1);
});
+test("auto-recall preserves recalled memory when compressor spawn throws synchronously", async () => {
+ const preloadDir = await mkdtemp(join(tmpdir(), "ov-sync-spawn-failure-"));
+ const preloadPath = join(preloadDir, "throw-codex-spawn.cjs");
+ await writeFile(preloadPath, `
+const childProcess = require("node:child_process");
+const { syncBuiltinESMExports } = require("node:module");
+const originalSpawn = childProcess.spawn;
+childProcess.spawn = function patchedSpawn(command, ...args) {
+ if (command === "codex") {
+ throw Object.assign(new Error("spawn EPERM"), { code: "EPERM" });
+ }
+ return originalSpawn.call(this, command, ...args);
+};
+syncBuiltinESMExports();
+`);
+
+ try {
+ const result = await runEndpointCompressionCase({
+ prompt: "Which editor do I prefer?",
+ entry: {
+ uri: "viking://user/zeus/memories/preferences/editor.md",
+ score: 0.91,
+ type: "preferences",
+ mode: "summary",
+ summary: "Use Vim",
+ },
+ rendered: "<memory_group>Use Vim</memory_group>",
+ compressorOutput: "unused",
+ extraEnv: { NODE_OPTIONS: `--require=${preloadPath}` },
+ });
+
+ assert.match(result.output.hookSpecificOutput.additionalContext, /Use Vim/);
+ assert.doesNotMatch(result.output.hookSpecificOutput.additionalContext, /<memory_group>/);
+ assert.equal(result.compressorCalls, 0);
+ } finally {
+ await rm(preloadDir, { recursive: true, force: true });
+ }
+});
+
test("auto-recall expands configured user in memory search target", async () => {
const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-user-target-"));
const requests = [];
diff --git a/examples/codex-memory-plugin/scripts/codex-launch.mjs b/examples/codex-memory-plugin/scripts/codex-launch.mjs
new file mode 100644
index 000000000..98dd06506
--- /dev/null
+++ b/examples/codex-memory-plugin/scripts/codex-launch.mjs
@@ -0,0 +1,75 @@
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import { win32 } from "node:path";
+
+function stripPathQuotes(value) {
+ const entry = String(value || "").trim();
+ if (entry.length >= 2 && entry.startsWith('"') && entry.endsWith('"')) {
+ return entry.slice(1, -1);
+ }
+ return entry;
+}
+
+/**
+ * Resolve a launch target for the Codex CLI.
+ *
+ * npm installs on Windows put a POSIX `codex` shim, `codex.cmd`, and the
+ * package's JavaScript entry point beside each other. `spawn("codex")` may
+ * select the POSIX shim and fail with EPERM, so prefer an executable or launch
+ * the JavaScript entry point directly through the current Node runtime.
+ */
+export function resolveCodexLaunch({
+ platform = process.platform,
+ pathValue = process.env.PATH || "",
+ execPath = process.execPath,
+ pathExists = existsSync,
+} = {}) {
+ if (platform !== "win32") {
+ return { command: "codex", argsPrefix: [] };
+ }
+
+ const entries = pathValue
+ .split(";")
+ .map(stripPathQuotes)
+ .filter(Boolean);
+
+ for (const entry of entries) {
+ const executable = win32.join(entry, "codex.exe");
+ if (pathExists(executable)) {
+ return { command: executable, argsPrefix: [] };
+ }
+
+ const npmEntryPoint = win32.join(
+ entry,
+ "node_modules",
+ "@openai",
+ "codex",
+ "bin",
+ "codex.js",
+ );
+ if (pathExists(npmEntryPoint)) {
+ return { command: execPath, argsPrefix: [npmEntryPoint] };
+ }
+ }
+
+ // Keep the normal lookup as a last resort. The caller treats either a
+ // synchronous throw or the child's asynchronous error as a compressor
+ // runtime failure and preserves the deterministic recall fallback.
+ return { command: "codex", argsPrefix: [] };
+}
+
+export function trySpawnCodex(args, options, {
+ spawnImpl = spawn,
+ resolveLaunch = resolveCodexLaunch,
+} = {}) {
+ const launch = resolveLaunch();
+ try {
+ return {
+ ...launch,
+ child: spawnImpl(launch.command, [...launch.argsPrefix, ...args], options),
+ error: null,
+ };
+ } catch (error) {
+ return { ...launch, child: null, error };
+ }
+}