mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-07 06:16:06 -10:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents run through coding-agent adapters and the native runner. Both use the same installed provider CLIs, model catalogs, and reasoning controls. > - OpenAI released GPT-6.1 Sol (`gpt-6.1-sol`) in Codex. Anthropic released Claude Sonnet 5.5. The static Codex, Bedrock, and OpenCode catalogs do not list these IDs. > - The shared provider pack pins Codex 0.156.0 and OpenCode 1.18.32. The evaluation image pins older Grok, Gemini, Kimi, Cursor, and GitHub CLI releases. Codex 0.156.0 has no bundled metadata for GPT-6.1 Sol. > - A model entry without a current harness, or a harness pin without its runner integrity checks, fails at run time. > - This pull request adds the verified model IDs and moves the harness pins, executable digests, controller checks, and image pins together. > - The benefit is that operators can select the current models, and the native and local adapters share one current CLI installation. ## Linked Issues or Issue Description Refs #13829 and #13838 (the September 22, 2026 model and harness refresh). Related pull requests: #14993 (merged October 5, 2026, superseding #14816) added the direct Claude Sonnet 5.5 entry and refreshed the Claude runtime to Agent SDK 0.3.286 / Claude Code 2.1.286. This pull request does not change the Claude runtime or the direct Claude model list; it keeps the #14993 pins and adds only the Bedrock Sonnet 5.5 ID. After #14993 merged, this branch was rebased onto `master` (October 5, 2026). The six overlapping pin regions (`docker/daytona-runner/Dockerfile`, `docker/daytona-runner/README.md`, `package.json`, `pnpm-workspace.yaml`, `packages/adapters/claude-local/src/index.test.ts`, `packages/paperclip-runner/src/backends/native-backend-factory.test.ts`) were resolved by keeping this pull request's Codex 0.160.0 and OpenCode 1.18.34 pins next to #14993's Claude 0.3.286 / 2.1.286 pins, taking the union of the Sonnet 5.5 model IDs in the Claude test, and merging both README paragraphs. The Sonnet 5.5 effort and CLI-gate lines in the Claude adapter were identical in both pull requests and merged without a diff. #14917 and #14918 reordered the Claude and Codex model lists earlier; the new entries sit where those ordering rules put them. Sources checked on 2026-10-02: - [OpenAI Codex models](https://learn.chatgpt.com/docs/models): GPT-6.1 Sol uses `gpt-6.1-sol`, supports reasoning efforts from Light to Ultra, and has Standard and Fast modes at launch. The page also records that `gpt-5.4` and `gpt-5.4-mini` retired from Codex with ChatGPT sign-in on August 31, 2026, and that `gpt-5.5` retires on October 14, 2026. Neither retirement applies to the OpenAI API. - [Codex CLI releases](https://github.com/openai/codex/releases) 0.157.0 through 0.160.0. The bundled model metadata in the 0.160.0 Linux binary contains `gpt-6.1-sol`. - [Claude Sonnet 5.5](https://platform.claude.com/docs/en/models/sonnet-5-5/overview): Bedrock ID `anthropic.claude-sonnet-5-5`, released September 28, 2026. - [OpenCode releases](https://github.com/anomalyco/opencode/releases) 1.18.33 and 1.18.34 (fixes only). The OpenCode model registry lists both added provider-qualified IDs. - npm `latest` tags for `@xai-official/grok` 1.0.46, `@google/gemini-cli` 0.62.0, and `@moonshot-ai/kimi-code` 2.1.1. [xAI](https://docs.x.ai/docs/models), [Google](https://ai.google.dev/gemini-api/docs/models), and [Kimi](https://www.kimi.com/code/docs/en/kimi-code/models.html) list no newer coding models. - Cursor CLI 2026.10.01-e373342 is the version the official installer resolves. The pinned digest is the SHA-256 of the versioned Linux x64 archive. - [GitHub CLI 2.102.0](https://github.com/cli/cli/releases/tag/v2.102.0) (security fixes). The pinned digest matches the release `checksums.txt`. ## What Changed - Codex adapter: add `gpt-6.1-sol` to the model list, the Fast mode list, and the Ultra effort set. It is the first entry: #14918 orders the list newest version first, and its description notes the ChatGPT app lists GPT-6.1 Sol first. Update the adapter documentation text. - Claude adapter: add `us.anthropic.claude-sonnet-5-5` (Bedrock Sonnet 5.5) to the Bedrock catalog in the newest-Sonnet slot after Opus 5.5; `us.anthropic.claude-sonnet-5` moves into the older-Sonnet group, matching what `sortClaudeModels` from #14917 produces at runtime. Any Sonnet 5.5 ID (direct or Bedrock-qualified) now gets the documented `xhigh` and `max` efforts and requires Claude Code 2.1.284 or later on the CLI lane (the Claude Code changelog entry for 2.1.284 adds `claude-sonnet-5-5`). These two lines are identical to the ones #14993 merged, so the branch carries no diff for them. - OpenCode adapter: add `openai/gpt-6.1-sol` and `anthropic/claude-sonnet-5-5` to the static fallback catalog. - Codex runtime pin 0.156.0 → 0.160.0 in the root and workspace overrides, the runner package, the Codex ACP package patch, the qualified ACPX profiles, the Linux x64 executable digest, the Rust provider backend and its tests, the provider-pack manifest pins, the remote controller pins, the sandbox npm install spec, and the opt-in qualification scripts. - Remote Codex compatibility window: upper bound 0.157.0 → 0.161.0. The minimum stays at 0.149.0. - OpenCode runtime pin 1.18.32 → 1.18.34 in the runner package, the materialization script, the server and Rust qualified versions, the eval and live-session labels, fixtures, and the configuration label. - Evaluation image (`docker/daytona-runner/Dockerfile`): Grok CLI 1.0.46, Gemini CLI 0.62.0, Kimi Code 2.1.1, Cursor CLI 2026.10.01-e373342 with its digest, GitHub CLI 2.102.0 with its digest, Codex and OpenCode version probes, and the refreshed lockfile digest. The Claude Code 2.1.286 probe comes from #14993 and is unchanged here. - `pnpm-lock.yaml` is not part of this pull request. The repository's pull request gate rejects lockfile edits, and the refresh bot regenerates the lockfile on master (the same flow #13838 used). The Dockerfile `PAPERCLIP_RUNNER_LOCK_SHA256` default is the digest of the lockfile that `pnpm install --resolution-only --ignore-scripts --no-frozen-lockfile` (the refresh workflow's command) produces for the combined pins on the rebased branch (`e1856797…`); that lockfile differs from master only in the `@openai/codex` 0.160.0 platform packages, the `@anthropic-ai/claude-agent-sdk` 0.3.286 override that #14993 introduced (the open refresh-bot pull request #14872 carries that part), `opencode-ai` 1.18.34 with its Linux x64 baseline, and the `codex-acp` patch hash. - Documentation: runner README, runner compatibility doc, environment variable example, and a new `doc/adapter-model-audit-2026-10-02.md` with sources and deferred items. - Tests: Codex adapter catalog, server adapter models, Codex compatibility window, native session executor pins, runner package contract, OpenCode materialization, and UI effort options. Unchanged on purpose: Claude Agent SDK 0.3.286 / Claude Code 2.1.286 (already on `master` from #14993), ACP bridges (`acpx` 0.13.1, `claude-agent-acp` 0.73.0, `codex-acp` 1.6.2; newer upstream releases need a separate qualification), the native Grok runtime 1.0.13, Pi 0.84.2 / 0.87.1 (the Pi 1.0 runner stack covers it), and Hermes 0.19.0 (current). `gpt-5.4` and `gpt-5.4-mini` stay in the picker because the OpenAI API still serves them. ## Verification Run on Linux x64 with Node 25.9.0 and pnpm 9.15.4 after `pnpm install --no-frozen-lockfile` (the refreshed lockfile stays local; see above). The results below were re-run on the rebased head (October 5, 2026) for the suites the conflict resolution touches; the other rows are from the original run and are covered by CI on every push: - Rebased head: `packages/adapters/codex-local` 482 passed; `packages/adapters/claude-local` 340 passed, 4 failed (`execute.remote`, `test.probe`, `execute.acp-fallback`, `acp` spawn/env-hardening cases that fail identically on unchanged `master` in this host environment); `server` adapter-models + codex-runtime-compatibility + native-session-executor + adapter-registry 607 passed, 1 failed (the same adapter-registry override-pause case as before, also failing on `master` here); `packages/paperclip-runner` native-backend-factory + qualified-profiles 36 passed; `ui` codex-reasoning-effort + config-fields + model-utils 19 passed. Rust, full typecheck, build, and the Docker image are left to CI as before. - `vitest run` in `packages/adapters/codex-local`: 13 passed. `vitest run` in `packages/adapters/claude-local` (whole package, including the new Sonnet 5.5 gate and effort tests): see the latest CI run and the comment below. `vitest run` in `packages/adapters/opencode-local`: 48 passed, 1 failed (`runtime-config.test.ts` reads the host `PAPERCLIP_OPENCODE_PROVIDERS` variable; it fails the same way on the unchanged base). - `vitest run src/__tests__/adapter-models.test.ts src/services/native-runtime/codex-runtime-compatibility.test.ts src/__tests__/adapter-registry.test.ts` in `server`: 84 passed, 1 failed (`adapter-registry.test.ts` override pause test; it fails the same way on the unchanged base). - `vitest run` in `ui` for `codex-reasoning-effort`, `agent-setup-fields`, `config-fields`, and `ComposerRunSettingsPicker`: 25 passed. - `node --test test/acpx-codex-package-contract.test.mjs scripts/materialize-opencode-binary.test.mjs scripts/runner-protocol-eval-campaign.test.mjs` in `packages/paperclip-runner`: 23 passed. The package contract test verifies the installed Codex ACP executable digest and the 0.160.0 patch pin. - `vitest run src/drivers/acpx src/backends src/drivers/opencode src/live/live-session.test.ts` in `packages/paperclip-runner`: 626 passed, 5 failed, 1 skipped. The 5 failures (`installation-integrity.test.ts` `/proc/self/fd` module loading and one OpenCode answer-selection test) also fail on the unchanged base under Node 25; Linux CI runs Node 24. - `pnpm run test:opencode:qualification` in `packages/paperclip-runner` against the installed OpenCode 1.18.34 executable: passed. - `codex --version` from the installed pack prints `codex-cli 0.160.0`. The Linux x64 executable digest `12eb3e81…652aad` was computed from the `@openai/[email protected].0-linux-x64` archive after checking its registry `dist.integrity`. - `pnpm check:token-gates`: all gates clean. - `pnpm run typecheck:typescript` in `packages/paperclip-runner`: passed. Package typechecks ran one at a time; see the comment below for the server and UI results. Not run here, and needed from CI: - Rust tests and `pnpm -r typecheck` / `pnpm build` for the server (no `cargo` in this environment; the server typecheck prepares the runner vendor build). - The Docker evaluation image build and the real-binary Codex startup and session-resume probes (no Docker; the probes need the compiled `paperclip-runnerd`). The trusted CI runner workflow covers them. - Authenticated inference with any new model. This change is metadata and startup validation only. ## Risks - Codex 0.160.0 changes the bundled model catalog and app-server behaviour (authoritative provider catalogs, incremental running-turn tracking). The patched `codex-acp` 1.6.2 bridge is unchanged and declares `^0.148.0`; it worked with 0.156.0 under the same override. If CI probes show a protocol change, the pin can return to 0.156.0 by reverting this pull request. - The compatibility window upper bound moves to `<0.161.0`. Remote images with Codex 0.157 to 0.160 become accepted. Older images stay accepted down to 0.149.0. - Until the refresh bot lands the regenerated lockfile on master, the Dockerfile lockfile digest default does not match the committed lockfile. The trusted CI workflow computes the digest from its own resolution at build time, so this affects only a local build that passes no digest. - Existing saved model selections and effort settings are not changed. Agents on `gpt-5.4` or `gpt-5.5` with ChatGPT sign-in need a model change before the OpenAI retirement dates; that is documented, not enforced. - Rollout order: deploy the controller and runner from this change before promoting a sandbox image that carries these pins. Older controllers reject the new provider-pack pins. ## Model Used - Claude Fable 5.1 (Anthropic, model ID `claude-fable-5-1`), 1M context window, adaptive thinking, tool use. The model ran as a Paperclip agent through the Claude Code harness, performed the web research, edited the code, and ran the tests listed above. ## 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) <[email protected]> Co-authored-by: devinfoley <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]>
1474 lines
53 KiB
TypeScript
1474 lines
53 KiB
TypeScript
import fs from "node:fs/promises";
|
|
import { randomUUID } from "node:crypto";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import type { AdapterExecutionContext, AdapterInvocationMeta } from "@paperclipai/adapter-utils";
|
|
import { runChildProcess } from "@paperclipai/adapter-utils/server-utils";
|
|
|
|
// Every test in this file needs a real teardown, so the mock below delegates
|
|
// to the actual factory by default. Only the wiring test further down reads
|
|
// the call arguments; it does not change this behavior.
|
|
const mockCreateWorkspaceRestoreTeardown = vi.hoisted(() => vi.fn());
|
|
|
|
vi.mock("@paperclipai/adapter-utils/workspace-restore-teardown", async (importOriginal) => {
|
|
const actual = await importOriginal<Record<string, unknown>>();
|
|
mockCreateWorkspaceRestoreTeardown.mockImplementation(
|
|
actual.createWorkspaceRestoreTeardown as (...args: unknown[]) => unknown,
|
|
);
|
|
return {
|
|
...actual,
|
|
createWorkspaceRestoreTeardown: mockCreateWorkspaceRestoreTeardown,
|
|
};
|
|
});
|
|
|
|
import {
|
|
buildCodexAcpConfig,
|
|
createCodexAcpExecutor,
|
|
nodeVersionMeetsCodexAcpMinimum,
|
|
resolveCodexAcpBillingIdentity,
|
|
resolveCodexExecutionEngine,
|
|
resolveCodexExecutionEngineForRun,
|
|
testCodexAcpEnvironment,
|
|
} from "./acp.js";
|
|
|
|
// A local stand-in for a sandbox runner: runs the managed-runtime staging
|
|
// scripts (mkdir/tar/find) as real child processes so the remote ACP lane can
|
|
// be exercised end-to-end against the host filesystem.
|
|
function createLocalSandboxRunner() {
|
|
let counter = 0;
|
|
return {
|
|
execute: async (input: {
|
|
command: string;
|
|
args?: string[];
|
|
cwd?: string;
|
|
env?: Record<string, string>;
|
|
stdin?: string;
|
|
timeoutMs?: number;
|
|
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
|
|
}) => {
|
|
counter += 1;
|
|
const command = input.command === "bash" ? "/bin/bash" : input.command;
|
|
return await runChildProcess(`codex-acp-sandbox-run-${counter}`, command, input.args ?? [], {
|
|
cwd: input.cwd ?? process.cwd(),
|
|
env: input.env ?? {},
|
|
stdin: input.stdin,
|
|
timeoutSec: Math.max(1, Math.ceil((input.timeoutMs ?? 30_000) / 1000)),
|
|
graceSec: 5,
|
|
onLog: input.onLog ?? (async () => {}),
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
type FakeRuntimeOptions = Record<string, unknown>;
|
|
type FakeRuntimeEvent = { type: string; text?: string; stream?: string; tag?: string };
|
|
type FakeRuntimeHandle = {
|
|
sessionKey: string;
|
|
backend: string;
|
|
runtimeSessionName: string;
|
|
cwd?: string;
|
|
acpxRecordId: string;
|
|
backendSessionId: string;
|
|
agentSessionId: string;
|
|
};
|
|
type FakeRuntimeTurnResult = { status: "completed" | "failed" | "cancelled"; stopReason?: string };
|
|
type FakeRuntimeTurn = {
|
|
requestId: string;
|
|
events: AsyncIterable<FakeRuntimeEvent>;
|
|
result: Promise<FakeRuntimeTurnResult>;
|
|
cancel: () => Promise<void>;
|
|
closeStream: () => Promise<void>;
|
|
};
|
|
|
|
const tempRoots: string[] = [];
|
|
const originalNodeVersion = process.version;
|
|
const originalPaperclipHome = process.env.PAPERCLIP_HOME;
|
|
const originalPaperclipInstanceId = process.env.PAPERCLIP_INSTANCE_ID;
|
|
const originalCodexHome = process.env.CODEX_HOME;
|
|
const originalOpenAiApiKey = process.env.OPENAI_API_KEY;
|
|
|
|
// Older/newer ISO timestamps for the copy-back monotonic (strictly-newer)
|
|
// decision predicate, plus a subscription-shaped auth.json fixture matching the
|
|
// predicate's parseAuth contract (tokens.account_id + token material +
|
|
// last_refresh).
|
|
const OLDER_REFRESH = "2026-01-01T00:00:00.000Z";
|
|
const NEWER_REFRESH = "2026-06-01T00:00:00.000Z";
|
|
|
|
function subscriptionAuthJson(accountId: string, lastRefresh: string, marker: string): string {
|
|
return JSON.stringify(
|
|
{
|
|
tokens: {
|
|
id_token: `id-${marker}`,
|
|
access_token: `acc-${marker}`,
|
|
refresh_token: `ref-${marker}`,
|
|
account_id: accountId,
|
|
},
|
|
last_refresh: lastRefresh,
|
|
},
|
|
null,
|
|
2,
|
|
);
|
|
}
|
|
|
|
// Enumerate the host staged-home temp dirs `stageCodexHomeForSync` created for a
|
|
// given runId (`paperclip-codex-home-sync-<runId>-<random>` under os.tmpdir()).
|
|
// A unique per-test runId scopes the match to this run's staging dirs only, so
|
|
// the assertion is not disturbed by other tests/processes sharing the tmp dir.
|
|
async function listCodexHomeSyncDirs(runId: string): Promise<string[]> {
|
|
const prefix = `paperclip-codex-home-sync-${runId}-`;
|
|
const entries = await fs.readdir(os.tmpdir());
|
|
return entries.filter((name) => name.startsWith(prefix)).map((name) => path.join(os.tmpdir(), name));
|
|
}
|
|
|
|
function setNodeVersion(version: string): void {
|
|
Object.defineProperty(process, "version", {
|
|
configurable: true,
|
|
enumerable: true,
|
|
value: version,
|
|
});
|
|
}
|
|
|
|
afterEach(async () => {
|
|
setNodeVersion(originalNodeVersion);
|
|
if (originalPaperclipHome === undefined) delete process.env.PAPERCLIP_HOME;
|
|
else process.env.PAPERCLIP_HOME = originalPaperclipHome;
|
|
if (originalPaperclipInstanceId === undefined) delete process.env.PAPERCLIP_INSTANCE_ID;
|
|
else process.env.PAPERCLIP_INSTANCE_ID = originalPaperclipInstanceId;
|
|
if (originalCodexHome === undefined) delete process.env.CODEX_HOME;
|
|
else process.env.CODEX_HOME = originalCodexHome;
|
|
if (originalOpenAiApiKey === undefined) delete process.env.OPENAI_API_KEY;
|
|
else process.env.OPENAI_API_KEY = originalOpenAiApiKey;
|
|
await Promise.all(tempRoots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
class FakeRuntime {
|
|
ensureInputs: Array<{
|
|
sessionKey: string;
|
|
agent: string;
|
|
mode: "persistent" | "oneshot";
|
|
cwd?: string;
|
|
resumeSessionId?: string;
|
|
}> = [];
|
|
startInputs: Array<{ handle: FakeRuntimeHandle; text: string; requestId: string; timeoutMs?: number }> = [];
|
|
closeInputs: Array<{ handle: FakeRuntimeHandle; reason: string; discardPersistentState?: boolean }> = [];
|
|
setConfigInputs: Array<{ handle: FakeRuntimeHandle; key: string; value: string }> = [];
|
|
ensureCount = 0;
|
|
|
|
constructor(
|
|
readonly options: FakeRuntimeOptions,
|
|
readonly events: FakeRuntimeEvent[] = [
|
|
{ type: "text_delta", text: "hello", stream: "output", tag: "agent_message_chunk" },
|
|
],
|
|
readonly terminal: FakeRuntimeTurnResult = { status: "completed", stopReason: "end_turn" },
|
|
) {}
|
|
|
|
async ensureSession(input: {
|
|
sessionKey: string;
|
|
agent: string;
|
|
mode: "persistent" | "oneshot";
|
|
cwd?: string;
|
|
resumeSessionId?: string;
|
|
}): Promise<FakeRuntimeHandle> {
|
|
this.ensureInputs.push(input);
|
|
this.ensureCount += 1;
|
|
return {
|
|
sessionKey: input.sessionKey,
|
|
backend: "acpx",
|
|
runtimeSessionName: `runtime-${this.ensureCount}`,
|
|
cwd: input.cwd,
|
|
acpxRecordId: `record-${this.ensureCount}`,
|
|
backendSessionId: `acp-${this.ensureCount}`,
|
|
agentSessionId: `agent-${this.ensureCount}`,
|
|
};
|
|
}
|
|
|
|
startTurn(input: {
|
|
handle: FakeRuntimeHandle;
|
|
text: string;
|
|
requestId: string;
|
|
timeoutMs?: number;
|
|
}): FakeRuntimeTurn {
|
|
this.startInputs.push(input);
|
|
const events = this.events;
|
|
const terminal = this.terminal;
|
|
return {
|
|
requestId: input.requestId,
|
|
events: {
|
|
[Symbol.asyncIterator]: async function* () {
|
|
for (const event of events) yield event;
|
|
},
|
|
},
|
|
result: Promise.resolve(terminal),
|
|
cancel: async () => {},
|
|
closeStream: async () => {},
|
|
};
|
|
}
|
|
|
|
runTurn(): AsyncIterable<FakeRuntimeEvent> {
|
|
throw new Error("not used");
|
|
}
|
|
|
|
getCapabilities() {
|
|
return { controls: [] };
|
|
}
|
|
|
|
getStatus() {
|
|
return Promise.resolve({});
|
|
}
|
|
|
|
async setConfigOption(input: { handle: FakeRuntimeHandle; key: string; value: string }) {
|
|
this.setConfigInputs.push(input);
|
|
}
|
|
|
|
async setMode() {}
|
|
|
|
async cancel() {}
|
|
|
|
async close(input: { handle: FakeRuntimeHandle; reason: string; discardPersistentState?: boolean }) {
|
|
this.closeInputs.push(input);
|
|
}
|
|
}
|
|
|
|
async function makeTempRoot(prefix: string) {
|
|
const root = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
|
|
tempRoots.push(root);
|
|
process.env.PAPERCLIP_HOME = path.join(root, "paperclip-home");
|
|
process.env.PAPERCLIP_INSTANCE_ID = "test";
|
|
return root;
|
|
}
|
|
|
|
async function createRuntimeSkill(root: string) {
|
|
const source = path.join(root, "skills", "review");
|
|
await fs.mkdir(source, { recursive: true });
|
|
await fs.writeFile(path.join(source, "SKILL.md"), "---\n---\nUse the review skill.\n", "utf8");
|
|
return {
|
|
key: "company/review",
|
|
runtimeName: "review",
|
|
source,
|
|
};
|
|
}
|
|
|
|
function buildContext(root: string, overrides: Partial<AdapterExecutionContext> = {}): AdapterExecutionContext {
|
|
return {
|
|
runId: "run-1",
|
|
agent: {
|
|
id: "agent-1",
|
|
companyId: "company-1",
|
|
name: "Codex ACP",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
},
|
|
runtime: {
|
|
sessionId: null,
|
|
sessionParams: null,
|
|
sessionDisplayId: null,
|
|
taskKey: "PAP-1",
|
|
},
|
|
config: {
|
|
engine: "acp",
|
|
cwd: root,
|
|
stateDir: path.join(root, "state"),
|
|
env: {
|
|
CODEX_HOME: path.join(root, "codex-home"),
|
|
},
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipTaskMarkdown: "Task context",
|
|
paperclipWorkspace: {
|
|
cwd: root,
|
|
source: "project_workspace",
|
|
workspaceId: "workspace-1",
|
|
},
|
|
},
|
|
onLog: async () => {},
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
describe("codex_local ACP lane", () => {
|
|
it("keeps ACP selected and reports unavailable prerequisites for default and explicit engines", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-default-");
|
|
const commandPath = path.join(root, "bin", "codex-acp");
|
|
await fs.mkdir(path.dirname(commandPath), { recursive: true });
|
|
await fs.writeFile(commandPath, "#!/usr/bin/env sh\n", "utf8");
|
|
setNodeVersion("v24.11.0");
|
|
|
|
expect(resolveCodexExecutionEngine({})).toEqual({ engine: "acp", explicit: false });
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { agentCommand: commandPath },
|
|
executionTarget: null,
|
|
}),
|
|
).resolves.toEqual({ engine: "acp", explicit: false });
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { engine: "cli", agentCommand: commandPath },
|
|
executionTarget: null,
|
|
}),
|
|
).resolves.toEqual({ engine: "cli", explicit: true });
|
|
expect(resolveCodexExecutionEngine({ engine: "acp" })).toEqual({
|
|
engine: "acp",
|
|
explicit: true,
|
|
});
|
|
|
|
setNodeVersion("v24.10.0");
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { agentCommand: commandPath },
|
|
executionTarget: null,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
engine: "acp",
|
|
explicit: false,
|
|
unavailableReason: expect.stringContaining("Node"),
|
|
});
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { engine: "acp", agentCommand: "/missing/codex-acp" },
|
|
executionTarget: null,
|
|
}),
|
|
).resolves.toMatchObject({ engine: "acp", explicit: true, unavailableReason: expect.stringContaining("Node") });
|
|
});
|
|
|
|
it("requires explicit CLI selection for local filesystem or network scope", async () => {
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { filesystemScope: "workspace" },
|
|
executionTarget: null,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
engine: "acp",
|
|
explicit: false,
|
|
unavailableReason: expect.stringContaining("confinement"),
|
|
});
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { engine: "acp", filesystemScope: "workspace" },
|
|
executionTarget: null,
|
|
}),
|
|
).resolves.toMatchObject({ engine: "acp", unavailableReason: expect.stringContaining("ACP confinement is not supported") });
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { networkScope: "allowlist" },
|
|
executionTarget: null,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
engine: "acp",
|
|
explicit: false,
|
|
unavailableReason: expect.stringContaining("confinement"),
|
|
});
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { filesystemScope: "workpace" },
|
|
executionTarget: null,
|
|
}),
|
|
).rejects.toThrow('filesystemScope must be "workspace"');
|
|
});
|
|
|
|
it("requires explicit CLI selection for in-place realization", async () => {
|
|
const executionTarget = {
|
|
kind: "remote" as const,
|
|
transport: "sandbox" as const,
|
|
remoteCwd: "/app",
|
|
workspaceRealization: {
|
|
mode: "in_place" as const,
|
|
authoritativeRoot: "/app",
|
|
pathAliases: [],
|
|
outboundRestorePaths: [],
|
|
},
|
|
};
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({ config: {}, executionTarget }),
|
|
).resolves.toMatchObject({
|
|
engine: "acp",
|
|
explicit: false,
|
|
unavailableReason: expect.stringContaining("ACP archive staging"),
|
|
});
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({ config: { engine: "acp" }, executionTarget }),
|
|
).resolves.toMatchObject({ engine: "acp", unavailableReason: expect.stringContaining("In-place workspace realization requires the Codex CLI engine") });
|
|
});
|
|
|
|
it("uses ACP for bridged sandbox auto runs when the ACP command is configured as a shell command", async () => {
|
|
setNodeVersion("v24.11.0");
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { agentCommand: "codex-acp" },
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd: "/work",
|
|
runner: {
|
|
execute: async () => ({
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
stdout: "",
|
|
stderr: "",
|
|
pid: null,
|
|
startedAt: new Date().toISOString(),
|
|
}),
|
|
},
|
|
},
|
|
}),
|
|
).resolves.toEqual({ engine: "acp", explicit: false });
|
|
});
|
|
|
|
it("reports unavailable ACP for one-shot sandbox auto runs", async () => {
|
|
setNodeVersion("v24.11.0");
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: {},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd: "/work",
|
|
},
|
|
}),
|
|
).resolves.toMatchObject({
|
|
engine: "acp",
|
|
explicit: false,
|
|
unavailableReason: expect.stringContaining("bidirectional remote process"),
|
|
});
|
|
});
|
|
|
|
it("reports unavailable ACP for non-sandbox remote auto runs", async () => {
|
|
setNodeVersion("v24.11.0");
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: {},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "ssh",
|
|
remoteCwd: "/work",
|
|
spec: {
|
|
host: "127.0.0.1",
|
|
port: 22,
|
|
username: "fixture",
|
|
remoteCwd: "/work",
|
|
remoteWorkspacePath: "/work",
|
|
privateKey: null,
|
|
knownHosts: null,
|
|
strictHostKeyChecking: true,
|
|
},
|
|
},
|
|
}),
|
|
).resolves.toMatchObject({
|
|
engine: "acp",
|
|
explicit: false,
|
|
unavailableReason: expect.stringContaining("sandbox remote targets only"),
|
|
});
|
|
});
|
|
|
|
it("enables workspace networking for ACP without changing other env settings", () => {
|
|
expect(buildCodexAcpConfig({ env: { CUSTOM: "kept" } })).toMatchObject({
|
|
env: { CUSTOM: "kept", PAPERCLIP_CODEX_ACP_NETWORK_ACCESS: "true" },
|
|
});
|
|
});
|
|
|
|
it.each([
|
|
{ env: { PAPERCLIP_CODEX_ACP_NETWORK_ACCESS: "false" } },
|
|
{ extraArgs: ["-c", "sandbox_workspace_write.network_access=false"] },
|
|
{ extraArgs: ["--config=sandbox_workspace_write.network_access=false"] },
|
|
{ args: ["-csandbox_workspace_write.network_access=false"] },
|
|
{ extraArgs: ["-c", "sandbox_workspace_write.network_access=true", "-c", "sandbox_workspace_write.network_access=false"] },
|
|
])("preserves explicit ACP network denial %j", (config) => {
|
|
expect(buildCodexAcpConfig(config)).toMatchObject({
|
|
env: { PAPERCLIP_CODEX_ACP_NETWORK_ACCESS: "false" },
|
|
});
|
|
});
|
|
|
|
it("maps Codex config to the ACPX Codex target", () => {
|
|
expect(buildCodexAcpConfig({
|
|
engine: "acp",
|
|
cwd: "/repo",
|
|
command: "codex",
|
|
model: "gpt-5.5",
|
|
modelReasoningEffort: "high",
|
|
fastMode: true,
|
|
agentCommand: "custom-codex-acp",
|
|
warmHandleIdleMs: 25,
|
|
})).toMatchObject({
|
|
agent: "codex",
|
|
cwd: "/repo",
|
|
command: "codex",
|
|
model: "gpt-5.5",
|
|
modelReasoningEffort: "high",
|
|
fastMode: true,
|
|
agentCommand: "custom-codex-acp",
|
|
mode: "persistent",
|
|
permissionMode: "approve-all",
|
|
nonInteractivePermissions: "deny",
|
|
warmHandleIdleMs: 25,
|
|
});
|
|
});
|
|
|
|
it.each([["gpt-6-astra", "ultra"], ["gpt-6.1-sol", "ultra"], ["gpt-6-sol", "ultra"], ["gpt-6-luna", "max"], ["gpt-5.6-sol", "ultra"], ["gpt-5.6-terra", "ultra"], ["gpt-5.6-luna", "max"]])("forwards %s controls to the ACPX Codex target", (model, effort) => {
|
|
expect(buildCodexAcpConfig({
|
|
engine: "acp",
|
|
model,
|
|
modelReasoningEffort: effort,
|
|
fastMode: true,
|
|
})).toMatchObject({
|
|
model,
|
|
modelReasoningEffort: effort,
|
|
fastMode: true,
|
|
});
|
|
});
|
|
|
|
it("normalizes the legacy bare gpt-5.6 alias to gpt-5.6-sol", () => {
|
|
expect(buildCodexAcpConfig({ engine: "acp", model: "gpt-5.6" })).toMatchObject({
|
|
model: "gpt-5.6-sol",
|
|
});
|
|
});
|
|
|
|
it("checks the Node version required by the ACPX runtime", () => {
|
|
setNodeVersion("v24.10.0");
|
|
expect(nodeVersionMeetsCodexAcpMinimum()).toBe(false);
|
|
setNodeVersion("v24.11.0");
|
|
expect(nodeVersionMeetsCodexAcpMinimum()).toBe(true);
|
|
});
|
|
|
|
it("reports ACP prerequisites for the ACP lane", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-env-");
|
|
const commandPath = path.join(root, "bin", "codex-acp");
|
|
await fs.mkdir(path.dirname(commandPath), { recursive: true });
|
|
await fs.writeFile(commandPath, "#!/usr/bin/env sh\n", "utf8");
|
|
setNodeVersion("v24.11.0");
|
|
|
|
const result = await testCodexAcpEnvironment({
|
|
adapterType: "codex_local",
|
|
companyId: "company-1",
|
|
config: {
|
|
engine: "acp",
|
|
cwd: root,
|
|
agentCommand: commandPath,
|
|
env: { OPENAI_API_KEY: "test-key" },
|
|
},
|
|
});
|
|
|
|
expect(result.status).toBe("pass");
|
|
expect(result.checks).toContainEqual(
|
|
expect.objectContaining({
|
|
code: "codex_engine_selected",
|
|
level: "info",
|
|
}),
|
|
);
|
|
expect(result.checks).toContainEqual(
|
|
expect.objectContaining({
|
|
code: "codex_acp_command_resolvable",
|
|
level: "info",
|
|
}),
|
|
);
|
|
expect(result.checks).toContainEqual(
|
|
expect.objectContaining({
|
|
code: "codex_acp_runtime_scaffold",
|
|
level: "info",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("detects shared managed Codex auth in ACP environment tests", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-managed-auth-");
|
|
const commandPath = path.join(root, "bin", "codex-acp");
|
|
const sharedCodexHome = path.join(root, "shared-codex-home");
|
|
const managedAgentHome = path.join(
|
|
root,
|
|
"paperclip-home",
|
|
"instances",
|
|
"test",
|
|
"companies",
|
|
"company-1",
|
|
"agents",
|
|
"agent-1",
|
|
"codex-home",
|
|
);
|
|
await fs.mkdir(path.dirname(commandPath), { recursive: true });
|
|
await fs.writeFile(commandPath, "#!/usr/bin/env sh\n", "utf8");
|
|
await fs.mkdir(sharedCodexHome, { recursive: true });
|
|
await fs.writeFile(path.join(sharedCodexHome, "auth.json"), '{"OPENAI_API_KEY":"sk-shared"}', "utf8");
|
|
setNodeVersion("v24.11.0");
|
|
process.env.CODEX_HOME = sharedCodexHome;
|
|
delete process.env.OPENAI_API_KEY;
|
|
|
|
const result = await testCodexAcpEnvironment({
|
|
adapterType: "codex_local",
|
|
companyId: "company-1",
|
|
config: {
|
|
engine: "acp",
|
|
cwd: root,
|
|
agentCommand: commandPath,
|
|
env: { CODEX_HOME: managedAgentHome, OPENAI_API_KEY: "" },
|
|
},
|
|
});
|
|
|
|
expect(result.status).toBe("pass");
|
|
expect(result.checks).toContainEqual(
|
|
expect.objectContaining({
|
|
code: "codex_acp_native_auth_detected",
|
|
level: "info",
|
|
detail: expect.stringContaining(sharedCodexHome),
|
|
}),
|
|
);
|
|
expect(result.checks).not.toContainEqual(
|
|
expect.objectContaining({
|
|
code: "codex_acp_credentials_missing",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("explains the Paperclip server credential boundary when ACP auth is missing", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-missing-auth-");
|
|
const commandPath = path.join(root, "bin", "codex-acp");
|
|
const sharedCodexHome = path.join(root, "shared-codex-home");
|
|
const managedAgentHome = path.join(
|
|
root,
|
|
"paperclip-home",
|
|
"instances",
|
|
"test",
|
|
"companies",
|
|
"company-1",
|
|
"agents",
|
|
"agent-1",
|
|
"codex-home",
|
|
);
|
|
await fs.mkdir(path.dirname(commandPath), { recursive: true });
|
|
await fs.writeFile(commandPath, "#!/usr/bin/env sh\n", "utf8");
|
|
await fs.mkdir(sharedCodexHome, { recursive: true });
|
|
setNodeVersion("v24.11.0");
|
|
process.env.CODEX_HOME = sharedCodexHome;
|
|
delete process.env.OPENAI_API_KEY;
|
|
|
|
const result = await testCodexAcpEnvironment({
|
|
adapterType: "codex_local",
|
|
companyId: "company-1",
|
|
config: {
|
|
engine: "acp",
|
|
cwd: root,
|
|
agentCommand: commandPath,
|
|
env: { CODEX_HOME: managedAgentHome, OPENAI_API_KEY: "" },
|
|
},
|
|
});
|
|
|
|
expect(result.status).toBe("warn");
|
|
expect(result.checks).toContainEqual(
|
|
expect.objectContaining({
|
|
code: "codex_acp_credentials_missing",
|
|
level: "warn",
|
|
message: expect.stringContaining("Paperclip server"),
|
|
hint: expect.stringContaining("separate Codex/chat session"),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("emits the canonical adapter_auth_missing check for a missing-auth sandbox target", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-sandbox-missing-auth-");
|
|
const sharedCodexHome = path.join(root, "shared-codex-home");
|
|
const managedAgentHome = path.join(
|
|
root,
|
|
"paperclip-home",
|
|
"instances",
|
|
"test",
|
|
"companies",
|
|
"company-1",
|
|
"agents",
|
|
"agent-1",
|
|
"codex-home",
|
|
);
|
|
await fs.mkdir(sharedCodexHome, { recursive: true });
|
|
setNodeVersion("v24.11.0");
|
|
process.env.CODEX_HOME = sharedCodexHome;
|
|
delete process.env.OPENAI_API_KEY;
|
|
|
|
const result = await testCodexAcpEnvironment({
|
|
adapterType: "codex_local",
|
|
companyId: "company-1",
|
|
config: {
|
|
engine: "acp",
|
|
cwd: root,
|
|
// A shell-style command resolves without a real binary in the sandbox.
|
|
agentCommand: "node ./fake-acp.js",
|
|
env: { CODEX_HOME: managedAgentHome, OPENAI_API_KEY: "" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd: "/work",
|
|
runner: {
|
|
execute: async () => ({
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
stdout: "",
|
|
stderr: "",
|
|
pid: null,
|
|
startedAt: new Date().toISOString(),
|
|
}),
|
|
},
|
|
} as never,
|
|
});
|
|
|
|
// A missing-auth sandbox is a warning, not a failure, and it carries the
|
|
// neutral canonical check code for the user interface.
|
|
expect(result.status).toBe("warn");
|
|
expect(result.checks).toContainEqual(
|
|
expect.objectContaining({
|
|
code: "adapter_auth_missing",
|
|
level: "warn",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("executes through ACPX with Codex session config and ephemeral skills", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-exec-");
|
|
const skill = await createRuntimeSkill(root);
|
|
const runtimes: FakeRuntime[] = [];
|
|
const meta: AdapterInvocationMeta[] = [];
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => {
|
|
const runtime = new FakeRuntime(options);
|
|
runtimes.push(runtime);
|
|
return runtime as never;
|
|
},
|
|
});
|
|
|
|
const result = await execute(buildContext(root, {
|
|
config: {
|
|
engine: "acp",
|
|
cwd: root,
|
|
stateDir: path.join(root, "state"),
|
|
env: {
|
|
CODEX_HOME: path.join(root, "codex-home"),
|
|
},
|
|
model: "gpt-5.5",
|
|
modelReasoningEffort: "high",
|
|
fastMode: true,
|
|
promptTemplate: "Do the assigned work.",
|
|
paperclipRuntimeSkills: [skill],
|
|
paperclipSkillSync: { desiredSkills: [skill.key] },
|
|
},
|
|
onMeta: async (payload: AdapterInvocationMeta) => {
|
|
meta.push(payload);
|
|
},
|
|
}));
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.sessionParams).toMatchObject({
|
|
agent: "codex",
|
|
mode: "persistent",
|
|
acpSessionId: "acp-1",
|
|
workspaceId: "workspace-1",
|
|
});
|
|
expect(result.sessionParams?.skills).toMatchObject({
|
|
mode: "codex",
|
|
selectedSkills: ["review"],
|
|
});
|
|
const skillsHome = (result.sessionParams?.skills as { skillsHome?: string }).skillsHome;
|
|
expect(skillsHome).toBeTruthy();
|
|
await expect(fs.readFile(path.join(skillsHome!, "review", "SKILL.md"), "utf8")).resolves.toContain("review skill");
|
|
expect(runtimes[0]?.ensureInputs[0]).toMatchObject({
|
|
agent: "codex",
|
|
mode: "persistent",
|
|
cwd: root,
|
|
});
|
|
expect(runtimes[0]?.setConfigInputs).toEqual([]);
|
|
expect(meta[0]?.commandNotes?.join("\n")).toContain("Prepared ACPX Codex skill home");
|
|
expect(meta[0]?.env?.CODEX_HOME).toBe(path.join(root, "codex-home"));
|
|
expect(JSON.parse(String(meta[0]?.env?.CODEX_CONFIG))).toEqual({
|
|
model: "gpt-5.5",
|
|
model_reasoning_effort: "high",
|
|
service_tier: "fast",
|
|
features: { fast_mode: true },
|
|
});
|
|
});
|
|
|
|
it("sends assignment-owned markdown and ordered distinct wake comments at the ACP boundary", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-context-owner-");
|
|
const runtimes: FakeRuntime[] = [];
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => {
|
|
const runtime = new FakeRuntime(options);
|
|
runtimes.push(runtime);
|
|
return runtime as never;
|
|
},
|
|
});
|
|
const issue = {
|
|
id: "issue-1",
|
|
identifier: "PAP-901",
|
|
title: "Repeat phrase Repeat phrase",
|
|
description: "Repeat phrase Repeat phrase",
|
|
};
|
|
const comments = [
|
|
{ id: "comment-a", body: "Same event body." },
|
|
{ id: "comment-b", body: "Same event body." },
|
|
];
|
|
// The adapter receives server-rendered fields. Keep the server builder's
|
|
// own tests in the server package; adapter packages compile independently.
|
|
const assignmentMarkdown = [
|
|
"Paperclip task context:",
|
|
`- Issue: ${JSON.stringify(issue.identifier)}`,
|
|
`- Title: ${JSON.stringify(issue.title)}`,
|
|
"", "Issue description:", "```text", issue.description, "```",
|
|
].join("\n");
|
|
const historicalMarkdown = [
|
|
assignmentMarkdown,
|
|
...comments.map((comment) => `${comment.id}: ${comment.body}`),
|
|
].join("\n");
|
|
const result = await execute(buildContext(root, {
|
|
context: {
|
|
issueId: issue.id,
|
|
paperclipTaskMarkdown: historicalMarkdown,
|
|
paperclipTaskMarkdownAssignment: assignmentMarkdown,
|
|
paperclipWake: {
|
|
reason: "issue_commented",
|
|
issue: { ...issue, status: "in_progress" },
|
|
comments: comments.map((comment, index) => ({
|
|
...comment,
|
|
issueId: issue.id,
|
|
createdAt: `2026-09-21T00:0${index}:00.000Z`,
|
|
})),
|
|
commentWindow: { requestedCount: 2, includedCount: 2, missingCount: 0 },
|
|
fallbackFetchNeeded: false,
|
|
},
|
|
paperclipTurnContext: {
|
|
version: 1,
|
|
assignment: { owner: "task_markdown" },
|
|
events: {
|
|
owner: "wake_prompt",
|
|
comments: [
|
|
{ id: "comment-a", revision: "a" },
|
|
{ id: "comment-b", revision: "b" },
|
|
],
|
|
},
|
|
},
|
|
paperclipWorkspace: { cwd: root, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
}));
|
|
expect(result.exitCode).toBe(0);
|
|
const prompt = String(runtimes[0]?.startInputs[0]?.text ?? "");
|
|
expect(prompt.split("Same event body.")).toHaveLength(3);
|
|
expect(prompt.indexOf("comment comment-a")).toBeLessThan(prompt.indexOf("comment comment-b"));
|
|
expect(prompt).toContain("Repeat phrase Repeat phrase");
|
|
});
|
|
|
|
it("creates the ACP session on the in-sandbox workspace cwd for runner-backed remote runs", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-remote-cwd-");
|
|
const localCwd = path.join(root, "worktree");
|
|
const remoteCwd = path.join(root, "remote-workspace");
|
|
await fs.mkdir(localCwd, { recursive: true });
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
await fs.writeFile(path.join(localCwd, "hello.txt"), "hi", "utf8");
|
|
|
|
const runtimes: FakeRuntime[] = [];
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => {
|
|
const runtime = new FakeRuntime(options);
|
|
runtimes.push(runtime);
|
|
return runtime as never;
|
|
},
|
|
});
|
|
|
|
const result = await execute(
|
|
buildContext(localCwd, {
|
|
config: {
|
|
engine: "acp",
|
|
cwd: localCwd,
|
|
// Use a throwaway ACP command so the process-session bridge does not
|
|
// require a real codex-acp binary in the local sandbox stand-in.
|
|
agentCommand: "node ./fake-acp.js",
|
|
stateDir: path.join(root, "state"),
|
|
env: { CODEX_HOME: path.join(root, "codex-home") },
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipTaskMarkdown: "Task context",
|
|
paperclipWorkspace: { cwd: localCwd, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd,
|
|
runner: createLocalSandboxRunner(),
|
|
} as never,
|
|
authToken: "real-run-jwt",
|
|
}),
|
|
);
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
// The workspace was shipped into the sandbox and session/new was created on
|
|
// the in-sandbox workspace dir — not the HOST worktree path.
|
|
await expect(fs.readFile(path.join(remoteCwd, "hello.txt"), "utf8")).resolves.toBe("hi");
|
|
expect(runtimes[0]?.ensureInputs[0]?.cwd).toBe(remoteCwd);
|
|
expect(runtimes[0]?.ensureInputs[0]?.cwd).not.toBe(localCwd);
|
|
});
|
|
|
|
it("seeds the managed Codex home into the sandbox and repoints CODEX_HOME to the in-sandbox path", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-home-seed-");
|
|
const localCwd = path.join(root, "worktree");
|
|
const remoteCwd = path.join(root, "remote-workspace");
|
|
const sourceHome = path.join(root, "codex-home");
|
|
// A separate shared host home with no auth.json so the teardown copy-back is
|
|
// a benign no-op here (this test asserts the inbound seed + remap only).
|
|
const sharedHostHome = path.join(root, "shared-codex-home");
|
|
await fs.mkdir(localCwd, { recursive: true });
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
await fs.mkdir(sourceHome, { recursive: true });
|
|
await fs.mkdir(sharedHostHome, { recursive: true });
|
|
await fs.writeFile(
|
|
path.join(sourceHome, "auth.json"),
|
|
subscriptionAuthJson("acct-seed", NEWER_REFRESH, "seed"),
|
|
{ mode: 0o600 },
|
|
);
|
|
process.env.CODEX_HOME = sharedHostHome;
|
|
|
|
const meta: AdapterInvocationMeta[] = [];
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => new FakeRuntime(options) as never,
|
|
});
|
|
|
|
const result = await execute(
|
|
buildContext(localCwd, {
|
|
config: {
|
|
engine: "acp",
|
|
cwd: localCwd,
|
|
agentCommand: "node ./fake-acp.js",
|
|
stateDir: path.join(root, "state"),
|
|
env: { CODEX_HOME: sourceHome },
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipWorkspace: { cwd: localCwd, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd,
|
|
runner: createLocalSandboxRunner(),
|
|
} as never,
|
|
authToken: "real-run-jwt",
|
|
onMeta: async (payload: AdapterInvocationMeta) => {
|
|
meta.push(payload);
|
|
},
|
|
}),
|
|
);
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
const remappedCodexHome = String(meta[0]?.env?.CODEX_HOME ?? "");
|
|
// C2 — the managed home was repointed onto an in-sandbox path, distinct from
|
|
// the host managed home; it is NOT the host CODEX_HOME.
|
|
expect(remappedCodexHome).not.toBe(sourceHome);
|
|
expect(remappedCodexHome).not.toBe(sharedHostHome);
|
|
expect(remappedCodexHome).toContain(".paperclip-runtime");
|
|
// Seeded: the credential materialized into the in-sandbox home (the local
|
|
// runner uses the host FS, so the in-sandbox path is a real host path).
|
|
await expect(fs.readFile(path.join(remappedCodexHome, "auth.json"), "utf8")).resolves.toContain(
|
|
"account_id",
|
|
);
|
|
// C4 — no XDG_* variable is introduced for in-sandbox credential discovery.
|
|
expect(Object.keys(meta[0]?.env ?? {}).filter((key) => key.startsWith("XDG_"))).toEqual([]);
|
|
});
|
|
|
|
it("copies a strictly-newer sandbox Codex auth back to the shared host on teardown", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-copyback-newer-");
|
|
const localCwd = path.join(root, "worktree");
|
|
const remoteCwd = path.join(root, "remote-workspace");
|
|
const sourceHome = path.join(root, "codex-home");
|
|
const sharedHostHome = path.join(root, "shared-codex-home");
|
|
await fs.mkdir(localCwd, { recursive: true });
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
await fs.mkdir(sourceHome, { recursive: true });
|
|
await fs.mkdir(sharedHostHome, { recursive: true });
|
|
// The home staged into the sandbox carries a strictly-newer, same-identity
|
|
// credential (simulating an in-sandbox token rotation); the shared host copy
|
|
// is older.
|
|
await fs.writeFile(
|
|
path.join(sourceHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", NEWER_REFRESH, "sandbox-newer"),
|
|
{ mode: 0o600 },
|
|
);
|
|
await fs.writeFile(
|
|
path.join(sharedHostHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", OLDER_REFRESH, "host-older"),
|
|
{ mode: 0o600 },
|
|
);
|
|
process.env.CODEX_HOME = sharedHostHome;
|
|
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => new FakeRuntime(options) as never,
|
|
});
|
|
const result = await execute(
|
|
buildContext(localCwd, {
|
|
config: {
|
|
engine: "acp",
|
|
cwd: localCwd,
|
|
agentCommand: "node ./fake-acp.js",
|
|
stateDir: path.join(root, "state"),
|
|
env: { CODEX_HOME: sourceHome },
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipWorkspace: { cwd: localCwd, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd,
|
|
runner: createLocalSandboxRunner(),
|
|
} as never,
|
|
authToken: "real-run-jwt",
|
|
}),
|
|
);
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
// C5 — copy-back fired on teardown and installed the strictly-newer sandbox
|
|
// credential onto the shared host under the merge-lock / monotonic guard.
|
|
const hostAuth = JSON.parse(await fs.readFile(path.join(sharedHostHome, "auth.json"), "utf8"));
|
|
expect(hostAuth.last_refresh).toBe(NEWER_REFRESH);
|
|
expect(hostAuth.tokens.refresh_token).toBe("ref-sandbox-newer");
|
|
// Mode preserved at 0600 by the atomic same-directory rename.
|
|
const mode = (await fs.stat(path.join(sharedHostHome, "auth.json"))).mode & 0o777;
|
|
expect(mode).toBe(0o600);
|
|
});
|
|
|
|
it("does not copy an API-key run's sandbox auth into the shared subscription home", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-key-copyback-");
|
|
const localCwd = path.join(root, "worktree");
|
|
const remoteCwd = path.join(root, "remote-workspace");
|
|
const keyHome = path.join(root, "api-key-home");
|
|
const sharedHostHome = path.join(root, "shared-codex-home");
|
|
await Promise.all([localCwd, remoteCwd, keyHome, sharedHostHome].map((dir) => fs.mkdir(dir, { recursive: true })));
|
|
const sharedAuth = subscriptionAuthJson("acct-same", OLDER_REFRESH, "host-older");
|
|
await fs.writeFile(path.join(sharedHostHome, "auth.json"), sharedAuth, { mode: 0o600 });
|
|
// A subscription-shaped sandbox credential must never be considered for
|
|
// the shared home when this run explicitly authenticates with an API key.
|
|
await fs.writeFile(
|
|
path.join(keyHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", NEWER_REFRESH, "sandbox-newer"),
|
|
{ mode: 0o600 },
|
|
);
|
|
process.env.CODEX_HOME = sharedHostHome;
|
|
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => new FakeRuntime(options) as never,
|
|
});
|
|
const result = await execute(buildContext(localCwd, {
|
|
config: {
|
|
engine: "acp",
|
|
cwd: localCwd,
|
|
agentCommand: "node ./fake-acp.js",
|
|
stateDir: path.join(root, "state"),
|
|
env: { CODEX_HOME: keyHome, OPENAI_API_KEY: "sk-test-key" },
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipWorkspace: { cwd: localCwd, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd,
|
|
runner: createLocalSandboxRunner(),
|
|
} as never,
|
|
authToken: "real-run-jwt",
|
|
}));
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
expect(await fs.readFile(path.join(sharedHostHome, "auth.json"), "utf8")).toBe(sharedAuth);
|
|
});
|
|
|
|
it("keeps the shared host Codex auth when the sandbox copy is not strictly newer", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-copyback-older-");
|
|
const localCwd = path.join(root, "worktree");
|
|
const remoteCwd = path.join(root, "remote-workspace");
|
|
const sourceHome = path.join(root, "codex-home");
|
|
const sharedHostHome = path.join(root, "shared-codex-home");
|
|
await fs.mkdir(localCwd, { recursive: true });
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
await fs.mkdir(sourceHome, { recursive: true });
|
|
await fs.mkdir(sharedHostHome, { recursive: true });
|
|
// The staged/sandbox credential is OLDER than the shared host copy: the
|
|
// strictly-newer guard must keep the host credential (never overwrite a good
|
|
// token with a spent one).
|
|
await fs.writeFile(
|
|
path.join(sourceHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", OLDER_REFRESH, "sandbox-older"),
|
|
{ mode: 0o600 },
|
|
);
|
|
await fs.writeFile(
|
|
path.join(sharedHostHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", NEWER_REFRESH, "host-newer"),
|
|
{ mode: 0o600 },
|
|
);
|
|
process.env.CODEX_HOME = sharedHostHome;
|
|
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => new FakeRuntime(options) as never,
|
|
});
|
|
const result = await execute(
|
|
buildContext(localCwd, {
|
|
config: {
|
|
engine: "acp",
|
|
cwd: localCwd,
|
|
agentCommand: "node ./fake-acp.js",
|
|
stateDir: path.join(root, "state"),
|
|
env: { CODEX_HOME: sourceHome },
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipWorkspace: { cwd: localCwd, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd,
|
|
runner: createLocalSandboxRunner(),
|
|
} as never,
|
|
authToken: "real-run-jwt",
|
|
}),
|
|
);
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
const hostAuth = JSON.parse(await fs.readFile(path.join(sharedHostHome, "auth.json"), "utf8"));
|
|
expect(hostAuth.last_refresh).toBe(NEWER_REFRESH);
|
|
expect(hostAuth.tokens.refresh_token).toBe("ref-host-newer");
|
|
});
|
|
|
|
it("keeps the host staged Codex home after a clean teardown so a compatible resume can reuse it", async () => {
|
|
// Session-re-staging guardrail: the per-run copy-back (`teardown`) must NOT
|
|
// remove the host staged-home temp dir — that removal moved to the one-time
|
|
// `disposeStaged`, fired only when the runtime is dropped. So after a CLEAN
|
|
// turn the engine caches the staged runtime warm and its host staged home is
|
|
// still on disk for the next compatible resume to reuse.
|
|
const runId = `run-keep-staged-home-${randomUUID()}`;
|
|
const root = await makeTempRoot("paperclip-codex-acp-keep-staged-");
|
|
const localCwd = path.join(root, "worktree");
|
|
const remoteCwd = path.join(root, "remote-workspace");
|
|
const sourceHome = path.join(root, "codex-home");
|
|
const sharedHostHome = path.join(root, "shared-codex-home");
|
|
await fs.mkdir(localCwd, { recursive: true });
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
await fs.mkdir(sourceHome, { recursive: true });
|
|
await fs.mkdir(sharedHostHome, { recursive: true });
|
|
// Strictly-newer sandbox credential so the per-run copy-back has real work.
|
|
await fs.writeFile(
|
|
path.join(sourceHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", NEWER_REFRESH, "sandbox-newer"),
|
|
{ mode: 0o600 },
|
|
);
|
|
await fs.writeFile(
|
|
path.join(sharedHostHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", OLDER_REFRESH, "host-older"),
|
|
{ mode: 0o600 },
|
|
);
|
|
process.env.CODEX_HOME = sharedHostHome;
|
|
|
|
// Isolated staged-runtime cache so this test observes only its own entry.
|
|
const stagedRuntimes = new Map();
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => new FakeRuntime(options) as never,
|
|
stagedRuntimes,
|
|
stagingLocks: new Map(),
|
|
});
|
|
const result = await execute(
|
|
buildContext(localCwd, {
|
|
runId,
|
|
config: {
|
|
engine: "acp",
|
|
cwd: localCwd,
|
|
agentCommand: "node ./fake-acp.js",
|
|
stateDir: path.join(root, "state"),
|
|
env: { CODEX_HOME: sourceHome },
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipWorkspace: { cwd: localCwd, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd,
|
|
runner: createLocalSandboxRunner(),
|
|
} as never,
|
|
authToken: "real-run-jwt",
|
|
}),
|
|
);
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
// Guardrail: `teardown` ran the copy-back but left the host staged home in
|
|
// place, and the clean turn cached the staged runtime warm for reuse.
|
|
const stagedDirs = await listCodexHomeSyncDirs(runId);
|
|
expect(stagedDirs).toHaveLength(1);
|
|
await expect(fs.stat(stagedDirs[0]!)).resolves.toBeDefined();
|
|
expect(stagedRuntimes.size).toBe(1);
|
|
// The per-run copy-back still fired: the strictly-newer sandbox credential
|
|
// landed on the shared host under the monotonic guard.
|
|
const hostAuth = JSON.parse(await fs.readFile(path.join(sharedHostHome, "auth.json"), "utf8"));
|
|
expect(hostAuth.last_refresh).toBe(NEWER_REFRESH);
|
|
expect(hostAuth.tokens.refresh_token).toBe("ref-sandbox-newer");
|
|
// No `disposeStaged` fires while the entry stays warm, so remove the
|
|
// intentionally-persisted staged temp ourselves to avoid leaking it.
|
|
await Promise.all(stagedDirs.map((dir) => fs.rm(dir, { recursive: true, force: true })));
|
|
});
|
|
|
|
it("removes the host staged Codex home when a failed turn drops the staged runtime", async () => {
|
|
// The complementary guardrail: when the staged runtime IS dropped (here, a
|
|
// failed turn), the one-time `disposeStaged` fires and removes the host
|
|
// staged-home temp dir — while the per-run copy-back (`teardown`) STILL fires
|
|
// on the unclean exit path, so a rotated sandbox credential is never lost.
|
|
const runId = `run-drop-staged-home-${randomUUID()}`;
|
|
const root = await makeTempRoot("paperclip-codex-acp-drop-staged-");
|
|
const localCwd = path.join(root, "worktree");
|
|
const remoteCwd = path.join(root, "remote-workspace");
|
|
const sourceHome = path.join(root, "codex-home");
|
|
const sharedHostHome = path.join(root, "shared-codex-home");
|
|
await fs.mkdir(localCwd, { recursive: true });
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
await fs.mkdir(sourceHome, { recursive: true });
|
|
await fs.mkdir(sharedHostHome, { recursive: true });
|
|
await fs.writeFile(
|
|
path.join(sourceHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", NEWER_REFRESH, "sandbox-newer"),
|
|
{ mode: 0o600 },
|
|
);
|
|
await fs.writeFile(
|
|
path.join(sharedHostHome, "auth.json"),
|
|
subscriptionAuthJson("acct-same", OLDER_REFRESH, "host-older"),
|
|
{ mode: 0o600 },
|
|
);
|
|
process.env.CODEX_HOME = sharedHostHome;
|
|
|
|
const stagedRuntimes = new Map();
|
|
const execute = createCodexAcpExecutor({
|
|
// A failed turn drives the drop path (discard staged runtime + dispose).
|
|
createRuntime: (options: FakeRuntimeOptions) =>
|
|
new FakeRuntime(options, [], { status: "failed", stopReason: "error" }) as never,
|
|
stagedRuntimes,
|
|
stagingLocks: new Map(),
|
|
});
|
|
const result = await execute(
|
|
buildContext(localCwd, {
|
|
runId,
|
|
config: {
|
|
engine: "acp",
|
|
cwd: localCwd,
|
|
agentCommand: "node ./fake-acp.js",
|
|
stateDir: path.join(root, "state"),
|
|
env: { CODEX_HOME: sourceHome },
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipWorkspace: { cwd: localCwd, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd,
|
|
runner: createLocalSandboxRunner(),
|
|
} as never,
|
|
authToken: "real-run-jwt",
|
|
}),
|
|
);
|
|
|
|
expect(result.exitCode).toBe(1);
|
|
// Guardrail: the dropped staged runtime disposed its host staged home and
|
|
// left nothing cached for reuse.
|
|
await expect(listCodexHomeSyncDirs(runId)).resolves.toEqual([]);
|
|
expect(stagedRuntimes.size).toBe(0);
|
|
// ...yet the per-run copy-back still ran on the failure teardown path, so the
|
|
// strictly-newer sandbox credential was not lost.
|
|
const hostAuth = JSON.parse(await fs.readFile(path.join(sharedHostHome, "auth.json"), "utf8"));
|
|
expect(hostAuth.last_refresh).toBe(NEWER_REFRESH);
|
|
expect(hostAuth.tokens.refresh_token).toBe("ref-sandbox-newer");
|
|
});
|
|
|
|
it("passes the Codex-specific teardown messages to the shared workspace-restore-teardown factory", async () => {
|
|
// Wiring test only: `createWorkspaceRestoreTeardown` owns the
|
|
// classify-and-redact contract, proven once for all three adapters by its
|
|
// own table-driven test in `packages/adapter-utils`. This test proves only
|
|
// that the Codex adapter passes its own two message strings to it.
|
|
// Clear the shared, hoisted mock first: earlier tests in this file also
|
|
// call through it, and a leftover call could hide a real wiring bug.
|
|
mockCreateWorkspaceRestoreTeardown.mockClear();
|
|
const root = await makeTempRoot("paperclip-codex-acp-teardown-wiring-");
|
|
const localCwd = path.join(root, "worktree");
|
|
const remoteCwd = path.join(root, "remote-workspace");
|
|
await fs.mkdir(localCwd, { recursive: true });
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => new FakeRuntime(options) as never,
|
|
stagedRuntimes: new Map(),
|
|
stagingLocks: new Map(),
|
|
});
|
|
const result = await execute(
|
|
buildContext(localCwd, {
|
|
config: {
|
|
engine: "acp",
|
|
cwd: localCwd,
|
|
agentCommand: "node ./fake-acp.js",
|
|
stateDir: path.join(root, "state"),
|
|
env: { CODEX_HOME: path.join(root, "codex-home") },
|
|
promptTemplate: "Do the assigned work.",
|
|
},
|
|
context: {
|
|
issueId: "issue-1",
|
|
paperclipWorkspace: { cwd: localCwd, source: "project_workspace", workspaceId: "workspace-1" },
|
|
},
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd,
|
|
runner: createLocalSandboxRunner(),
|
|
} as never,
|
|
authToken: "real-run-jwt",
|
|
}),
|
|
);
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
expect(mockCreateWorkspaceRestoreTeardown).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
startMessage: "[paperclip] Restoring workspace changes and Codex auth from the sandbox.\n",
|
|
failurePrefix: "[paperclip] Codex ACP teardown restore/copy-back failed",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("reports unavailable ACP for a runner-less sandbox even when the ACP command is set", async () => {
|
|
setNodeVersion("v24.11.0");
|
|
// Isolate the missing bidirectional runner as the sole fallback cause:
|
|
// provide a valid ACP command and Node version so the only difference from
|
|
// the runner-backed ACP case is the absent `runner`.
|
|
await expect(
|
|
resolveCodexExecutionEngineForRun({
|
|
config: { agentCommand: "codex-acp" },
|
|
executionTarget: {
|
|
kind: "remote",
|
|
transport: "sandbox",
|
|
providerKey: "fake-plugin",
|
|
remoteCwd: "/work",
|
|
},
|
|
}),
|
|
).resolves.toMatchObject({
|
|
engine: "acp",
|
|
explicit: false,
|
|
unavailableReason: expect.stringContaining("bidirectional remote process"),
|
|
});
|
|
});
|
|
|
|
it("classifies ACP refresh-token auth failures", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-refresh-token-");
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => new FakeRuntime(
|
|
options,
|
|
[],
|
|
{
|
|
status: "failed",
|
|
error: { message: "OAuth failed: refresh_token_invalidated" },
|
|
} as unknown as FakeRuntimeTurnResult,
|
|
) as never,
|
|
});
|
|
|
|
const result = await execute(buildContext(root));
|
|
|
|
expect(result.exitCode).toBe(1);
|
|
expect(result.errorCode).toBe("refresh_token_invalidated");
|
|
expect(result.errorFamily).toBe("refresh_token_invalidated");
|
|
expect(result.resultJson?.errorFamily).toBe("refresh_token_invalidated");
|
|
expect(result.resultJson).not.toHaveProperty("codexCredentialTelemetry");
|
|
});
|
|
|
|
it("resumes compatible ACP sessions on later Codex ACP runs", async () => {
|
|
const root = await makeTempRoot("paperclip-codex-acp-resume-");
|
|
const runtimes: FakeRuntime[] = [];
|
|
const execute = createCodexAcpExecutor({
|
|
createRuntime: (options: FakeRuntimeOptions) => {
|
|
const runtime = new FakeRuntime(options);
|
|
runtimes.push(runtime);
|
|
return runtime as never;
|
|
},
|
|
});
|
|
|
|
const first = await execute(buildContext(root));
|
|
const second = await execute(buildContext(root, {
|
|
runtime: {
|
|
sessionId: first.sessionId ?? null,
|
|
sessionParams: first.sessionParams ?? null,
|
|
sessionDisplayId: first.sessionDisplayId ?? null,
|
|
taskKey: "PAP-1",
|
|
},
|
|
}));
|
|
|
|
expect(second.exitCode).toBe(0);
|
|
expect(runtimes).toHaveLength(2);
|
|
expect(runtimes[1]?.ensureInputs[0]?.resumeSessionId).toBe("acp-1");
|
|
});
|
|
});
|
|
|
|
describe("resolveCodexAcpBillingIdentity", () => {
|
|
const originalOpenAiKey = process.env.OPENAI_API_KEY;
|
|
const originalOpenRouterKey = process.env.OPENROUTER_API_KEY;
|
|
|
|
afterEach(() => {
|
|
if (originalOpenAiKey === undefined) delete process.env.OPENAI_API_KEY;
|
|
else process.env.OPENAI_API_KEY = originalOpenAiKey;
|
|
if (originalOpenRouterKey === undefined) delete process.env.OPENROUTER_API_KEY;
|
|
else process.env.OPENROUTER_API_KEY = originalOpenRouterKey;
|
|
});
|
|
|
|
it("classifies an adapter-config API key as api billing to openai", () => {
|
|
delete process.env.OPENROUTER_API_KEY;
|
|
expect(
|
|
resolveCodexAcpBillingIdentity({ config: { env: { OPENAI_API_KEY: "sk-test" } } }),
|
|
).toEqual({ provider: "openai", biller: "openai", billingType: "api" });
|
|
});
|
|
|
|
it("falls back to chatgpt subscription without an API key", () => {
|
|
delete process.env.OPENAI_API_KEY;
|
|
delete process.env.OPENROUTER_API_KEY;
|
|
expect(resolveCodexAcpBillingIdentity({ config: {} })).toEqual({
|
|
provider: "openai",
|
|
biller: "chatgpt",
|
|
billingType: "subscription",
|
|
});
|
|
});
|
|
|
|
it("bills OpenRouter-backed runs to openrouter", () => {
|
|
expect(
|
|
resolveCodexAcpBillingIdentity({
|
|
config: { env: { OPENAI_API_KEY: "sk-test", OPENROUTER_API_KEY: "or-test" } },
|
|
}),
|
|
).toEqual({ provider: "openai", biller: "openrouter", billingType: "api" });
|
|
});
|
|
|
|
it("ignores host env for remote execution targets", () => {
|
|
process.env.OPENAI_API_KEY = "sk-host-only";
|
|
expect(
|
|
resolveCodexAcpBillingIdentity({
|
|
config: {},
|
|
executionTarget: { kind: "remote", transport: "sandbox", remoteCwd: "/work" },
|
|
} as never).billingType,
|
|
).toBe("subscription");
|
|
});
|
|
});
|