Files
PaperClipAI/packages/adapters/codex-local/src/server/test.remote.test.ts
T
9fb955e9a2 fix(codex): gate models on the Codex CLI floor before the ChatGPT backend rejects them (#15399)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Codex adapter and the native runner run Codex in local hosts and
in managed sandboxes, and the model catalog lists the models an operator
can select
> - The Codex backend accepts a new model with ChatGPT sign-in only from
a recent enough Codex CLI. An older CLI fails every turn with `The
'<model>' model is not supported when using Codex with a ChatGPT
account.`
> - After #14942 added `gpt-6.1-sol`, an operator selected it for an
agent in a managed Daytona sandbox. The sandbox image still shipped
Codex 0.156.0. The connection test and runs failed with that sentence,
which reads like an account problem
> - Paperclip only checked the Codex compatibility window (`>=0.149.0
<0.161.0`), so 0.156.0 passed and the failure surfaced from the backend
without a cause
> - This pull request records the verified Codex CLI floor for each
gated model, compares the installed `codex --version` with that floor in
the environment Test and in the remote runner, and names the backend
rejection when it still happens
> - The benefit is a precise, actionable message ("gpt-6.1-sol requires
Codex CLI 0.159.0 or newer; detected 0.156.0; promote a sandbox image
with Codex 0.160.0") instead of an opaque 400, and no doomed hello probe

## Linked Issues or Issue Description

Refs #14942

**Bug: selecting `gpt-6.1-sol` in a managed sandbox fails with a ChatGPT
account error.**

**Steps to reproduce**
1. Promote a sandbox image that ships Codex CLI 0.156.0.
2. Create a Codex agent with a ChatGPT sign-in connection, select
`gpt-6.1-sol`, and run the environment Test or a task in that sandbox.

**Expected behavior**
The Test or the run tells the operator that the Codex CLI in the sandbox
is older than the model needs.

**Actual behavior**
The Test reports `codex_hello_probe_failed` with
`{"type":"error","status":400,"error":{"type":"invalid_request_error","message":"The
'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT
account."}}`. A run fails with "The selected model is not supported by
the current ChatGPT connection."

**Evidence**
- Codex 0.156.1 and older are rejected for `gpt-6.1-sol` with ChatGPT
sign-in: https://github.com/openai/codex/issues/49396
- Codex 0.159.0 and 0.159.2 are accepted:
https://github.com/openai/codex/issues/49464 and
https://github.com/decolua/9router/issues/4471 (same error, fixed by
raising the client version identity from 0.155.0 to 0.159.0)
- Codex 0.157.0 release notes: "Add GPT-6 Sol and Luna to the model
catalog": https://github.com/openai/codex/releases/tag/rust-v0.157.0
- GPT-6.1 Sol is included for Plus, Pro, Business, Enterprise, and Edu
with ChatGPT sign-in: https://learn.chatgpt.com/docs/models

## What Changed

- `packages/adapters/codex-local/src/index.ts`: add
`minimumCodexCliVersionForModel` (`gpt-6.1-sol` → 0.159.0, `gpt-6-sol`
and `gpt-6-luna` → 0.157.0, with the sources above),
`parseCodexCliVersionOutput`, `codexCliVersionAtLeast`, and
`CODEX_CHATGPT_MODEL_REJECTION_RE`. Models without a verified floor
return `null`, so nothing probes them. The agent configuration doc
describes the floors.
- `packages/adapters/codex-local/src/server/cli-version.ts` (new): run
`codex --version` where the run would execute it (local, SSH, or
sandbox), compare it with the model floor, and build the
`codex_cli_version_compatible` / `codex_cli_version_incompatible`
checks. Map the backend rejection sentence to
`codex_hello_probe_model_rejected` with the detected CLI version and a
hint that separates a stale CLI from a plan that does not include the
model.
- `packages/adapters/codex-local/src/server/test.ts` (CLI lane Test):
run the version check before the hello probe when the model has a floor.
Skip the hello probe when the CLI is too old
(`codex_hello_probe_skipped_cli_version`). When the probe still fails
with the backend sentence, report `codex_hello_probe_model_rejected`
instead of the generic `codex_hello_probe_failed`. The new codes do not
match the auth-failure patterns, so a managed connection is not
invalidated.
- `packages/adapters/codex-local/src/server/acp.ts` (ACP lane Test): for
remote targets, run the same version check against the shared `codex`
the ACP server spawns.
- `server/src/services/native-runtime/native-session-executor.ts`: after
the compatibility-window check, compare the remote Codex with the
configured model's floor and fail with
`runner_remote_provider_artifact_incompatible: <model> requires Codex
<floor> or newer with ChatGPT sign-in, received <version> from the
sandbox image; promote a sandbox image with Codex 0.160.0 or configure
PAPERCLIP_RUNNER_REMOTE_CODEX_NPM_SPEC=...`. When a preinstalled Codex
fails this check and an npm spec is configured, the existing fallback
installs the pinned release.
- Tests: adapter metadata, CLI-lane Test (too old, compatible, no floor,
backend rejection), ACP-lane Test (too old, compatible, no floor), and
the remote runner floor (nine version/model cases).
- `doc/adapter-model-audit-2026-10-02.md`: record the floors and the
reason.

No catalog entry, default model, saved agent configuration, pin,
lockfile, or image definition changes.

## Verification

Local (Node 25.9, pnpm 9.15.4 via corepack):

```sh
pnpm --filter @paperclipai/adapter-codex-local typecheck
pnpm --filter @paperclipai/adapter-codex-local exec vitest run            # 81 passed
pnpm --filter @paperclipai/server exec vitest run \
  src/services/native-runtime/native-session-executor.test.ts \
  src/services/native-runtime/codex-runtime-compatibility.test.ts -t Codex   # 84 passed
```

Also run locally: the full `native-session-executor.test.ts` file (533
passed) and the full Codex adapter suite (81 passed).

Follow-up commit `9fd4d3b25` (Greptile P2: the ACP-lane version probe
ignored the agent's configured env): the probe now receives the
adapter's string-valued `env` entries, the same ones
`buildCodexAcpConfig` hands to remote ACP runs, so a `PATH` override
selects the same `codex` for the Test as for the run. New test covers a
`PATH` + `CODEX_HOME` override and a dropped non-string entry. Re-run on
that head: `pnpm --filter @paperclipai/adapter-codex-local typecheck`
clean; full Codex adapter suite 503 passed (31 files).

Not run here: `pnpm -r typecheck` for `server` (the direct `tsc
--noEmit` was killed by the sandbox memory cap; the adapter package
typecheck passes and CI covers the server), `pnpm build`, browser
suites, and a live sandbox probe. No UI files changed, so token gates do
not apply.

Manual check for a reviewer: set an agent's Codex model to
`gpt-6.1-sol`, point its environment at a sandbox whose `codex
--version` prints `codex-cli 0.156.0`, and run the environment Test. The
result contains `codex_cli_version_incompatible` with `Detected Codex
CLI 0.156.0.` and no hello probe check. With Codex 0.160.0 the Test
contains `codex_cli_version_compatible` and runs the hello probe.

## Risks

- A floor is enforced for all authentication modes, because the runner
does not know the credential method at verification time. An OpenAI API
key on Codex 0.157.0 or 0.158.0 with `gpt-6.1-sol` is now rejected
before launch. Paperclip pins Codex 0.160.0 everywhere, so this only
affects installs that lag the pin, and the message names the fix.
- The 0.159.0 floor for `gpt-6.1-sol` is the oldest stable release
verified to work; 0.157.0 and 0.158.0 were not verified either way. If
OpenAI accepts an older client, the floor can be lowered in one table.
- The `codex --version` probe adds one short process run to the Test
only for models with a floor.
- Rollback: revert this pull request. No data or configuration migrates.

## Model Used

Claude Fable 5.1 (`claude-fable-5-1`), Anthropic, with extended
thinking, tool use, and web research, operating as a Paperclip agent
through Claude Code.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Bender (Fable) <noreply@paperclip.ing>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 10:37:55 -07:00

585 lines
24 KiB
TypeScript

import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
const {
ensureAdapterExecutionTargetDirectory,
ensureAdapterExecutionTargetCommandResolvable,
maybeRunSandboxInstallCommand,
runAdapterExecutionTargetProcess,
describeAdapterExecutionTarget,
resolveAdapterExecutionTargetCwd,
prepareAdapterExecutionTargetRuntime,
prepareManagedCodexHome,
restoreWorkspace,
capturedHomeAssetFiles,
capturedHomeAssetAuthJson,
} = vi.hoisted(() => {
const restoreWorkspace = vi.fn(async () => {});
// Records the files staged in the uploaded "home" asset at call time, before
// the probe's cleanup deletes the temp dir. Lets tests assert the upload is a
// minimal credentials-only home and not the full managed CODEX_HOME.
const capturedHomeAssetFiles: { value: string[] | null } = { value: null };
// Records the staged auth.json content, so tests can assert WHICH home's
// credential the probe uploaded (the effective home a run would use).
const capturedHomeAssetAuthJson: { value: string | null } = { value: null };
return {
capturedHomeAssetFiles,
capturedHomeAssetAuthJson,
ensureAdapterExecutionTargetDirectory: vi.fn(async () => {}),
ensureAdapterExecutionTargetCommandResolvable: vi.fn(async () => {}),
maybeRunSandboxInstallCommand: vi.fn(async () => null),
runAdapterExecutionTargetProcess: vi.fn(async () => ({
exitCode: 0,
signal: null,
timedOut: false,
stdout: [
"{\"type\":\"thread.started\",\"thread_id\":\"thread-1\"}",
"{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"hello\"}}",
"{\"type\":\"turn.completed\",\"usage\":{\"input_tokens\":1,\"cached_input_tokens\":0,\"output_tokens\":1}}",
].join("\n"),
stderr: "",
pid: 123,
startedAt: new Date().toISOString(),
})),
describeAdapterExecutionTarget: vi.fn(() => "QA SSH"),
resolveAdapterExecutionTargetCwd: vi.fn((target, configuredCwd, fallbackCwd) => {
if (typeof configuredCwd === "string" && configuredCwd.trim().length > 0) return configuredCwd;
if (target && typeof target === "object" && "remoteCwd" in target && typeof target.remoteCwd === "string") {
return target.remoteCwd;
}
return fallbackCwd;
}),
prepareAdapterExecutionTargetRuntime: vi.fn(async (input: { assets?: Array<{ key: string; localDir: string }> }) => {
const homeAsset = input?.assets?.find((asset) => asset.key === "home");
if (homeAsset) {
capturedHomeAssetFiles.value = (await fs.readdir(homeAsset.localDir)).sort();
capturedHomeAssetAuthJson.value = await fs
.readFile(`${homeAsset.localDir}/auth.json`, "utf8")
.catch(() => null);
}
return {
target: null,
workspaceRemoteDir: "/remote/workspace/.paperclip-runtime/runs/test/workspace",
runtimeRootDir: "/remote/workspace/.paperclip-runtime/runs/test/workspace/.paperclip-runtime/codex",
assetDirs: {
home: "/remote/workspace/.paperclip-runtime/runs/test/workspace/.paperclip-runtime/codex/home",
},
restoreWorkspace,
};
}),
prepareManagedCodexHome: vi.fn(async () => {
// Return a real managed home seeded with credentials so the probe's
// minimal-home copy step (auth.json/config.toml) has something to read.
const dir = await fs.mkdtemp(`${os.tmpdir()}/paperclip-managed-codex-home-`);
await fs.writeFile(`${dir}/auth.json`, JSON.stringify({ OPENAI_API_KEY: "sk-managed" }));
await fs.writeFile(`${dir}/config.toml`, "model = \"gpt-5\"\n");
return dir;
}),
restoreWorkspace,
};
});
vi.mock("@paperclipai/adapter-utils/execution-target", async () => {
const actual = await vi.importActual<typeof import("@paperclipai/adapter-utils/execution-target")>(
"@paperclipai/adapter-utils/execution-target",
);
return {
...actual,
ensureAdapterExecutionTargetDirectory,
ensureAdapterExecutionTargetCommandResolvable,
maybeRunSandboxInstallCommand,
runAdapterExecutionTargetProcess,
describeAdapterExecutionTarget,
resolveAdapterExecutionTargetCwd,
prepareAdapterExecutionTargetRuntime,
};
});
vi.mock("./codex-home.js", async () => {
const actual = await vi.importActual<typeof import("./codex-home.js")>("./codex-home.js");
return {
...actual,
prepareManagedCodexHome,
};
});
import { testEnvironment } from "./test.js";
describe("codex remote environment diagnostics", () => {
const scratchDirs: string[] = [];
async function makeScratchDir(prefix: string): Promise<string> {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
scratchDirs.push(dir);
return dir;
}
beforeEach(async () => {
// The probe mirrors execute's home preparation, which reads the shared
// source home and the auth cache from `process.env`. Pin both to empty
// scratch locations so no test ever reads or writes the real ~/.codex or
// the real instance tree.
vi.stubEnv("CODEX_HOME", await makeScratchDir("paperclip-test-shared-codex-"));
vi.stubEnv("PAPERCLIP_HOME", await makeScratchDir("paperclip-test-instance-"));
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "default");
});
afterEach(async () => {
vi.clearAllMocks();
vi.unstubAllEnvs();
delete process.env.OPENAI_API_KEY;
capturedHomeAssetFiles.value = null;
capturedHomeAssetAuthJson.value = null;
while (scratchDirs.length > 0) {
const dir = scratchDirs.pop();
if (dir) await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
}
});
it("stages managed CODEX_HOME in an isolated runtime dir and keeps the probe cwd on the original remote workspace", async () => {
const remoteTarget: AdapterExecutionTarget = {
kind: "remote",
transport: "ssh",
remoteCwd: "/remote/workspace",
spec: {
host: "127.0.0.1",
port: 22,
username: "agent",
privateKey: "PRIVATE KEY",
knownHosts: "KNOWN HOSTS",
remoteCwd: "/remote/workspace",
remoteWorkspacePath: "/remote/workspace",
strictHostKeyChecking: false,
},
};
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: {
engine: "cli",
command: "codex",
},
executionTarget: remoteTarget,
environmentName: "QA SSH",
});
expect(result.status).toBe("pass");
expect(result.checks.some((check) => check.code === "codex_hello_probe_passed")).toBe(true);
expect(prepareManagedCodexHome).toHaveBeenCalledTimes(1);
expect(prepareAdapterExecutionTargetRuntime).toHaveBeenCalledTimes(1);
const runtimeCalls = prepareAdapterExecutionTargetRuntime.mock.calls as unknown as Array<[
{
workspaceLocalDir: string;
target?: { remoteCwd?: string };
workspaceRemoteDir?: string;
assets?: Array<{ key: string; localDir: string }>;
},
]>;
const runtimeInput = runtimeCalls[0]?.[0];
// The probe must upload only a minimal credentials-only home, never the
// full managed CODEX_HOME (which can be hundreds of MB of session history).
const homeAsset = runtimeInput?.assets?.find((asset) => asset.key === "home");
expect(homeAsset?.localDir).toContain(`${os.tmpdir()}/paperclip-codex-probe-home-`);
expect(capturedHomeAssetFiles.value).toEqual(["auth.json", "config.toml"]);
expect(runtimeInput?.workspaceLocalDir).toContain(`${os.tmpdir()}/paperclip-codex-envtest-`);
expect(runtimeInput?.workspaceLocalDir).not.toBe("/remote/workspace");
expect(await fs.stat(runtimeInput!.workspaceLocalDir).catch(() => null)).toBeNull();
expect(runtimeInput?.target?.remoteCwd).toBe("/remote/workspace");
// `workspaceRemoteDir` is the base path passed to the runtime; the
// helper's per-run subdirectory is appended internally inside
// `prepareRemoteManagedRuntime`. Pre-building a per-run prefix here
// would double-nest the run id in the final path.
expect(runtimeInput?.workspaceRemoteDir).toBe("/remote/workspace");
expect(runAdapterExecutionTargetProcess).toHaveBeenCalledTimes(1);
const probeCall = runAdapterExecutionTargetProcess.mock.calls[0] as unknown as
| [string, { kind: string; remoteCwd: string }, string, string[], { cwd: string; env: Record<string, string> }]
| undefined;
expect(probeCall?.[1]).toMatchObject({
kind: "remote",
remoteCwd: "/remote/workspace",
});
expect(probeCall?.[4]).toMatchObject({
cwd: "/remote/workspace",
env: expect.objectContaining({
CODEX_HOME: "/remote/workspace/.paperclip-runtime/runs/test/workspace/.paperclip-runtime/codex/home",
}),
});
expect(restoreWorkspace).toHaveBeenCalledTimes(1);
});
it("avoids /tmp CODEX_HOME for remote API-key hello probes", async () => {
const remoteTarget: AdapterExecutionTarget = {
kind: "remote",
transport: "sandbox",
providerKey: "cloudflare",
remoteCwd: "/remote/workspace",
runner: {
execute: async () => ({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
pid: null,
startedAt: new Date().toISOString(),
}),
},
};
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: {
engine: "cli",
command: "codex",
env: {
OPENAI_API_KEY: "sk-test",
},
},
executionTarget: remoteTarget,
environmentName: "QA Cloudflare",
});
expect(result.status).toBe("pass");
const probeCall = runAdapterExecutionTargetProcess.mock.calls[0] as unknown as
| [string, AdapterExecutionTarget, string, string[], { cwd: string; env: Record<string, string> }]
| undefined;
expect(probeCall?.[4].env.CODEX_HOME).toContain("/remote/workspace/.paperclip-runtime/codex/probe-home-codex-envtest-");
expect(probeCall?.[4].env.CODEX_HOME?.startsWith("/tmp/")).toBe(false);
expect(probeCall?.[3]).toContain("--skip-git-repo-check");
});
// `sandboxTarget()` is declared later in this describe block; function
// declarations hoist, so the version-floor cases below reuse it.
function versionProbeResult(stdout: string) {
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout,
stderr: "",
pid: 111,
startedAt: new Date().toISOString(),
};
}
it("fails before the hello probe when the sandbox Codex CLI is older than the model's floor", async () => {
// A sandbox image baked before gpt-6.1-sol reached the catalog still runs
// Codex 0.156.0. The backend would reject every turn with "not supported
// when using Codex with a ChatGPT account"; the Test must name the real
// gap (the CLI in the image) instead of running that doomed probe.
runAdapterExecutionTargetProcess.mockResolvedValueOnce(versionProbeResult("codex-cli 0.156.0\n"));
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: { engine: "cli", command: "codex", model: "gpt-6.1-sol" },
executionTarget: sandboxTarget(),
environmentName: "QA Daytona",
});
expect(result.status).toBe("fail");
const incompatible = result.checks.find((check) => check.code === "codex_cli_version_incompatible");
expect(incompatible).toMatchObject({
level: "error",
message: "gpt-6.1-sol requires Codex CLI 0.159.0 or newer with ChatGPT sign-in.",
detail: "Detected Codex CLI 0.156.0.",
});
expect(incompatible?.hint).toContain("sandbox image");
expect(result.checks.some((check) => check.code === "codex_hello_probe_skipped_cli_version")).toBe(true);
expect(result.checks.some((check) => check.code.startsWith("codex_hello_probe_") && !check.code.includes("skipped"))).toBe(false);
expect(runAdapterExecutionTargetProcess).toHaveBeenCalledTimes(1);
const versionCall = runAdapterExecutionTargetProcess.mock.calls[0] as unknown as [string, AdapterExecutionTarget, string, string[]];
expect(versionCall[2]).toBe("codex");
expect(versionCall[3]).toEqual(["--version"]);
expect(prepareAdapterExecutionTargetRuntime).not.toHaveBeenCalled();
});
it("runs the hello probe when the sandbox Codex CLI satisfies the model's floor", async () => {
runAdapterExecutionTargetProcess.mockResolvedValueOnce(versionProbeResult("codex-cli 0.160.0\n"));
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: { engine: "cli", command: "codex", model: "gpt-6.1-sol" },
executionTarget: sandboxTarget(),
environmentName: "QA Daytona",
});
expect(result.status).toBe("pass");
expect(result.checks.find((check) => check.code === "codex_cli_version_compatible")).toMatchObject({
level: "info",
message: "Codex CLI 0.160.0 satisfies the 0.159.0 minimum for gpt-6.1-sol.",
});
expect(result.checks.some((check) => check.code === "codex_hello_probe_passed")).toBe(true);
expect(runAdapterExecutionTargetProcess).toHaveBeenCalledTimes(2);
});
it("skips the version probe for models without a verified floor", async () => {
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: { engine: "cli", command: "codex", model: "gpt-5.6-sol" },
executionTarget: sandboxTarget(),
environmentName: "QA Daytona",
});
expect(result.status).toBe("pass");
expect(result.checks.some((check) => check.code.startsWith("codex_cli_version_"))).toBe(false);
expect(runAdapterExecutionTargetProcess).toHaveBeenCalledTimes(1);
const helloCall = runAdapterExecutionTargetProcess.mock.calls[0] as unknown as [string, AdapterExecutionTarget, string, string[]];
expect(helloCall[3]).not.toEqual(["--version"]);
});
it("names the backend's ChatGPT model rejection instead of a generic probe failure", async () => {
// The CLI is new enough, but the account's plan or rollout does not include
// the model. The backend answers with one fixed sentence; surface it with
// the detected CLI version so the operator can tell the two causes apart.
runAdapterExecutionTargetProcess.mockResolvedValueOnce(versionProbeResult("codex-cli 0.160.0\n"));
runAdapterExecutionTargetProcess.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "ERROR: {\"type\":\"error\",\"status\":400,\"error\":{\"type\":\"invalid_request_error\",\"message\":\"The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.\"}}",
pid: 222,
startedAt: new Date().toISOString(),
});
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: { engine: "cli", command: "codex", model: "gpt-6.1-sol" },
executionTarget: sandboxTarget(),
environmentName: "QA Daytona",
});
expect(result.status).toBe("fail");
const rejected = result.checks.find((check) => check.code === "codex_hello_probe_model_rejected");
expect(rejected).toMatchObject({
level: "error",
message: "The Codex backend rejected gpt-6.1-sol for this ChatGPT account.",
detail: "The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account. Detected Codex CLI 0.160.0.",
});
expect(rejected?.hint).toContain("0.159.0");
expect(rejected?.hint).toContain("plan");
expect(result.checks.some((check) => check.code === "codex_hello_probe_failed")).toBe(false);
// Not an auth failure: the managed-connection flow must not invalidate the credential.
expect(result.checks.some((check) => check.code === "codex_hello_probe_auth_required")).toBe(false);
});
it("emits the canonical adapter_auth_missing check when a sandbox hello probe reports missing auth", async () => {
// The sandbox has no seedable credentials, so the hello probe returns an
// authentication-required error. The Test must emit the neutral canonical
// check code. The user interface reads this code to decide login
// eligibility; it does not parse the message text or the top-level status.
prepareManagedCodexHome.mockImplementationOnce(async () => {
const dir = await fs.mkdtemp(`${os.tmpdir()}/paperclip-managed-codex-home-noauth-`);
await fs.writeFile(`${dir}/config.toml`, "model = \"gpt-5\"\n");
return dir;
});
runAdapterExecutionTargetProcess.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "Not logged in. Please run `codex login` to authenticate.",
pid: 321,
startedAt: new Date().toISOString(),
});
const remoteTarget: AdapterExecutionTarget = {
kind: "remote",
transport: "sandbox",
providerKey: "daytona",
remoteCwd: "/remote/workspace",
runner: {
execute: async () => ({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
pid: null,
startedAt: new Date().toISOString(),
}),
},
};
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: { engine: "cli", command: "codex" },
executionTarget: remoteTarget,
environmentName: "QA Daytona",
});
// A missing-auth probe is a warning, not a failure, so the environment stays
// testable and the user interface can offer login.
expect(result.status).toBe("warn");
expect(result.checks.some((check) => check.code === "adapter_auth_missing")).toBe(true);
// The descriptive probe check stays, so existing diagnostics keep working.
expect(result.checks.some((check) => check.code === "codex_hello_probe_auth_required")).toBe(true);
});
it("does not override CODEX_HOME when the host has no credentials to seed", async () => {
// Custom-image flow: the login lives inside the captured snapshot, and the
// host has no Codex auth.json. The probe must not upload an empty home or
// set CODEX_HOME, so Codex falls back to the sandbox's baked-in login.
prepareManagedCodexHome.mockImplementationOnce(async () => {
const dir = await fs.mkdtemp(`${os.tmpdir()}/paperclip-managed-codex-home-noauth-`);
// No auth.json — only a config file.
await fs.writeFile(`${dir}/config.toml`, "model = \"gpt-5\"\n");
return dir;
});
const remoteTarget: AdapterExecutionTarget = {
kind: "remote",
transport: "sandbox",
providerKey: "daytona",
remoteCwd: "/remote/workspace",
runner: {
execute: async () => ({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
pid: null,
startedAt: new Date().toISOString(),
}),
},
};
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: { engine: "cli", command: "codex" },
executionTarget: remoteTarget,
environmentName: "QA Daytona",
});
expect(result.status).toBe("pass");
// No managed-home upload, so the full-runtime staging is skipped entirely.
expect(prepareAdapterExecutionTargetRuntime).not.toHaveBeenCalled();
const probeCall = runAdapterExecutionTargetProcess.mock.calls[0] as unknown as
| [string, AdapterExecutionTarget, string, string[], { cwd: string; env: Record<string, string> }]
| undefined;
expect(probeCall?.[4].env.CODEX_HOME).toBeUndefined();
});
const subscriptionAuth = (accountId: string, marker: string, lastRefresh: string) =>
JSON.stringify({
tokens: {
id_token: `synthetic-id-token-${marker}`,
access_token: `synthetic-access-token-${marker}`,
refresh_token: `synthetic-refresh-token-${marker}`,
account_id: accountId,
},
last_refresh: lastRefresh,
});
function sandboxTarget(): AdapterExecutionTarget {
return {
kind: "remote",
transport: "sandbox",
providerKey: "daytona",
remoteCwd: "/remote/workspace",
runner: {
execute: async () => ({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
pid: null,
startedAt: new Date().toISOString(),
}),
},
};
}
it("stages a configured managed per-agent CODEX_HOME instead of the company default home", async () => {
// Execute honors env.CODEX_HOME, so the probe must exercise that same home
// — otherwise the Test and real runs authenticate with different
// credentials and can disagree in both directions.
const perAgentHome = path.join(
process.env.PAPERCLIP_HOME!,
"instances",
"default",
"companies",
"company-1",
"agents",
"agent-x",
"codex-home",
);
const promoted = subscriptionAuth("acct-agent", "promoted", "2026-07-09T02:00:00Z");
await fs.mkdir(perAgentHome, { recursive: true });
await fs.writeFile(path.join(perAgentHome, "auth.json"), promoted, "utf8");
await fs.writeFile(path.join(perAgentHome, "config.toml"), 'model = "gpt-5"\n', "utf8");
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: {
engine: "cli",
command: "codex",
env: { CODEX_HOME: perAgentHome },
},
executionTarget: sandboxTarget(),
environmentName: "QA Daytona",
});
expect(result.status).toBe("pass");
// The company default home preparation never ran; the configured managed
// home was seeded in place and its credential is what got staged.
expect(prepareManagedCodexHome).not.toHaveBeenCalled();
expect(capturedHomeAssetAuthJson.value).toBe(promoted);
// The real seeding pass ran on the per-agent home and kept the promoted
// regular-file credential (the shared source scratch home is empty).
const stat = await fs.lstat(path.join(perAgentHome, "auth.json"));
expect(stat.isSymbolicLink()).toBe(false);
expect(await fs.readFile(path.join(perAgentHome, "auth.json"), "utf8")).toBe(promoted);
});
it("stages an external CODEX_HOME's credentials as-is and never seeds or mutates it", async () => {
const externalHome = await makeScratchDir("paperclip-test-external-codex-");
const external = subscriptionAuth("acct-ext", "external", "2026-07-09T01:00:00Z");
await fs.writeFile(path.join(externalHome, "auth.json"), external, "utf8");
// Plant a same-identity, strictly-fresher credential in the shared source
// home: if the probe wrongly ran the managed seeding pass on the external
// home, the heal would swap its auth.json for a symlink to this file. The
// regular-file assertion below is therefore proof no seeding happened.
await fs.writeFile(
path.join(process.env.CODEX_HOME!, "auth.json"),
subscriptionAuth("acct-ext", "shared", "2026-07-09T02:00:00Z"),
"utf8",
);
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: {
engine: "cli",
command: "codex",
env: { CODEX_HOME: externalHome },
},
executionTarget: sandboxTarget(),
environmentName: "QA Daytona",
});
expect(result.status).toBe("pass");
expect(prepareManagedCodexHome).not.toHaveBeenCalled();
// The external home's own credential is what got staged — not the shared
// source's fresher copy, because an external override manages its own auth.
expect(capturedHomeAssetAuthJson.value).toBe(external);
const stat = await fs.lstat(path.join(externalHome, "auth.json"));
expect(stat.isSymbolicLink()).toBe(false);
expect(await fs.readFile(path.join(externalHome, "auth.json"), "utf8")).toBe(external);
});
});