mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 14:20:12 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner runs Claude and Codex agents from one shared provider pack. The pack pins an exact Claude Agent SDK (which bundles Claude Code) and an exact Codex CLI. > - #22222 added Claude Fable 5.2 (minimum Claude Code 2.1.321) and GPT-6.2 Sol and Astra (minimum Codex 0.169.1). The pack still bundles Claude Code 2.1.286 and Codex 0.160.0. > - Because of this, Paperclip Runner stops these models with a named version error, and native remote Codex accepts only `>=0.149.0 <0.161.0`. > - This pull request moves the provider pack to Agent SDK 0.3.328 (Claude Code 2.1.328) and Codex 0.170.0. It moves every constant that depends on these pins, and the remote Codex window to `<0.171.0`. > - The benefit is that Fable 5.2 and GPT-6.2 run on Paperclip Runner after a sandbox image with this pack is promoted. ## Linked Issues or Issue Description Refs #22222 (adds the models and the version floors; this pull request makes them runnable on Paperclip Runner). Refs #18488 (moves only the Codex pin to 0.166.0 and the window to `<0.167.0`; it is not updated since November 1 and has conflicts with `master`). Refs #18486 (GPT-6.1 Terra needs Codex 0.165.0; Codex 0.170.0 satisfies it). **Overlap with #18488.** #18488 changes the same Codex pin locations. This pull request uses a newer pin (0.170.0) and also moves the Claude runtime. If this pull request merges first, #18488 has no remaining change. I did not change the #18488 branch. ## What Changed - Claude runtime: `@anthropic-ai/claude-agent-sdk` 0.3.286 → 0.3.328 (Claude Code 2.1.286 → 2.1.328). This changes the root `pnpm.overrides`, `pnpm-workspace.yaml`, the ACPX `claude` profile, and the qualified Claude runtime in `installation-integrity.ts`, with new executable digests for Linux x64, Linux ARM64, macOS ARM64, and macOS x64. - Codex runtime: `@openai/codex` 0.160.0 → 0.170.0. This changes the runner dependency, the `codex-acp@1.6.2>@openai/codex` override, the `codex-acp` patch dependency line, the ACPX `codex` profile, and the qualified Linux x64 runtime with its new executable digest. - The ACP bridges do not change: `claude-agent-acp` 0.73.0 and the patched `codex-acp` 1.6.2. Their `commandDigest` values and profile versions do not change. - Generated declarations: `generated-profiles.ts` and `generated_acpx_profiles.rs` are regenerated with `generate:acpx-profiles`. - Remote native Codex window: `REMOTE_CODEX_MAXIMUM_VERSION_EXCLUSIVE` 0.161.0 → 0.171.0. The minimum stays at 0.149.0. Images with Codex 0.149.0 through 0.170.x are accepted. - Codex company observability: the qualified-version check moves to `codex-cli 0.170.0`. The `otel` configuration keys that Paperclip writes (`exporter`, `trace_exporter`, `metrics_exporter`) are present in the 0.170.0 configuration schema. The `OtelExporterKind`, `OtelHttpProtocol`, and `OtelTlsConfig` definitions are identical to 0.160.0. - Daytona runner image probes (`Dockerfile`, `Dockerfile.release`) expect `codex-cli 0.170.0` and `2.1.328 (Claude Code)`. The remote npm install spec in `server/src/adapters/registry.ts` is `@openai/codex@0.170.0`. - Tests: fixtures and assertions that mirror the pins use the new versions. The window tests accept 0.161.0 through 0.170.99 and reject 0.171.0. The ACPX gate tests now show that Fable 5.2 and GPT-6.2 are admitted. A new test mocks an older bundled runtime and keeps the named version-gap errors covered. The fallback test shows that GPT-6.2 stays on 0.170.0 and still falls back on 0.160.0. - Opt-in qualification scripts (`scripts/tests/native-cleanup-paginated-codex.mjs`, `native-provider-startup-codex.mjs`) require Codex 0.170.0. - Documentation: `docker/daytona-runner/README.md`, `doc/architecture/paperclip-runner-compatibility.md`, `doc/agent-observability.md`, `docs/deploy/environment-variables.md`, and the deferred item in `doc/adapter-model-audit-2026-11-18.md`. - `pnpm-lock.yaml` is not part of this pull request. The refresh bot regenerates it on `master`, as for the previous pin refreshes (#14942, #14993). ## Verification Sources, checked on 2026-11-19: - npm registry: `@openai/codex@0.170.0` (published 2026-11-18T03:45Z) and `@anthropic-ai/claude-agent-sdk@0.3.328` (published 2026-11-18T23:13Z, `claudeCodeVersion` 2.1.328). Both are the `latest` tags. - [Codex releases](https://github.com/openai/codex/releases) 0.161.0 through 0.170.0. The notes record no app-server protocol break. 0.169.0 keeps project configuration disabled for `codex exec` in untrusted directories; Paperclip's CLI path already uses `--skip-git-repo-check`, and the native path uses `app-server`. - [Claude Code changelog](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md) 2.1.287 through 2.1.328. See "Risks" for the headless changes that I reviewed. Digests and package shape: - I downloaded each platform archive with `npm pack`, which verifies registry integrity, and computed the SHA-256 of the executable. As a method check, the same command on the 0.3.286 Linux x64 archive gives the digest that is on `master` (`fe503f65…`). The Codex 0.160.0 archive also gives the `master` digest (`12eb3e81…`). - The extracted executables report `codex-cli 0.170.0` and `2.1.328 (Claude Code)`. - The Codex 0.170.0 Linux x64 archive no longer contains `codex-resources/zsh/bin/zsh`. Paperclip does not reference that path. - The Agent SDK 0.3.328 `optionalDependencies` have the same platform set as 0.3.286. The Codex 0.170.0 `optionalDependencies` use the same `npm:@openai/codex@<version>-<platform>` aliases. - Bridge link check: I installed `@agentclientprotocol/claude-agent-acp@0.73.0` with an override to Agent SDK 0.3.328 and imported its entry module. Node linked all of the named SDK imports, and the import completed. Real Codex qualification (no model turn, no credentials): - `PAPERCLIP_TEST_CODEX_BINARY=<installed 0.170.0 Linux x64 binary> node --import ./server/node_modules/tsx/dist/loader.mjs scripts/tests/native-cleanup-paginated-codex.mjs` passed: `green: true`, with the expected red control and paginated `thread/resume` through the real 0.170.0 `app-server`. The installed binary digest matches the pinned digest. Focused suites (Linux x64, Node 25.9.0, local `pnpm install --no-frozen-lockfile`): - `cd packages/paperclip-runner && pnpm run typecheck:typescript` passed, including `check:acpx-profiles`. - `npx tsc --noEmit` passed in `packages/adapters/codex-local` and `packages/adapters/claude-local`. - `packages/adapters/codex-local`: 625 passed. `packages/adapters/claude-local`: 419 passed, 1 skipped. - `node --test`: `acpx-codex-package-contract` 9 passed, `controlled-evals/controller` 77 passed, `scripts/acpx-patch-packaging` 26 passed, `scripts/__tests__/grok-public-install-sandbox` 27 passed. - `server`: `acpx-qualification`, `codex-runtime-compatibility`, and `codex-model-fallback` 110 passed. `native-session-executor` 1541 passed, 1 failed. The failure (`compares export process compatibility … db.transaction is not a function`) also fails on unchanged `master` on this host. - `packages/paperclip-runner` vitest (`installation-integrity`, `qualified-profiles`, `codex-security-config`, `native-execution`, `native-backend-factory`): 283 passed, 25 failed. All 25 failures are in `installation-integrity.test.ts` with "ACPX provider lifetime guardian failed to start". The same 25 tests fail on unchanged `master` on this host (master fails 30 here). Rust (toolchain 1.97.1 from `rust-toolchain.toml`, Linux x64): - `cargo test -p paperclip-runner-core --lib`: 658 passed, 2 failed, 4 ignored. `warm_run_attachment_reuses_the_provider_ingress_listener` also fails on unchanged `master` on this host. `reaping_stops_a_dead_runners_provider_and_its_escaped_tool_job` is flaky here: on this branch it passed 2 of 3 reruns. - `cargo test -p paperclip-runner-core --test acpx_warm_attachment --test native_provider_backend`: 7 and 45 passed. - The new and changed saved-session tests pass: `a_session_saved_by_the_previous_agent_runtime_is_refused_by_name`, `unrestorable_saved_sessions_keep_strict_bindings_and_name_their_class`, and `a_settled_session_saved_by_the_previous_acpx_release_continues`. `rustfmt --check` passes. - `server`: `native-session-resume.test.ts` and `acpx-qualification.test.ts` 110 passed, 2 skipped. Both new resume cases run and pass. Not run here: - `native-provider-startup-codex.mjs`, because it needs a compiled `paperclip-runnerd`. The trusted CI runner workflow covers startup and session-resume probes. - The Docker image build and any live model turn. A live Fable 5.2 and GPT-6.2 test follows the staging image rollout. ## Saved sessions from the previous release This change keeps the ACPX bridge command digests and profile versions. It changes `agentRuntimeVersion` in the `claude` and `codex` ACPX profiles. That field is part of the saved session identity. The previous release saved sessions with Agent SDK 0.3.286 or Codex 0.160.0. This build refuses those saved sessions. It does not migrate them. - **Next run (the usual case):** the saved provider descriptor names the old runtime. `rebindNativeSessionCheckpoint` does not match it, so the next run starts a fresh provider session in the same workspace with the complete handoff prompt. No run fails. The earlier provider conversation does not carry over. - **A run in flight at the deploy (settled or mid-turn):** the runner restore refuses the saved descriptor with the permanent class `provider_state_incompatible`. The server reports it as `native_provider_state_incompatible` and stops automatic retries. The runner opens no provider and keeps the saved state bytes and the workspace. The next run on the task starts a fresh provider session. - **Native Codex (`codex_app_server`) and OpenCode** sessions do not record this field, so their resume decision does not change. After a new image is promoted, native Codex resumes a saved thread with Codex 0.170.0 instead of 0.160.0. This pull request does not test that cross-version thread resume. New tests: - `acpx_provider_backend.rs`: `a_session_saved_by_the_previous_agent_runtime_is_refused_by_name` covers settled Claude and Codex sessions and a Claude turn interrupted mid-run by the deploy. `unrestorable_saved_sessions_keep_strict_bindings_and_name_their_class` has a new `agent_runtime_release` case. Each case checks the named class, that no provider session opens, and that the saved bytes do not change. - `native-session-resume.test.ts`: "a session saved by the previous Claude or Codex ACPX runtime" checks that a same-release session resumes, and that a session saved with Agent SDK 0.3.286 or Codex 0.160.0 starts fresh in the same workspace. ## Risks - Medium. Every Paperclip Runner Claude and Codex run uses the new executables. The digests, generated profiles, image probes, and window must agree. They agree locally, and CI runs the Rust and runner suites again. - Claude Code 2.1.287 through 2.1.328 change some headless defaults. I checked each one against Paperclip: - 2.1.302: `-p` and Agent SDK sessions with no permission mode start in `default` mode on third-party providers. Paperclip always sets a mode (`bypassPermissions` or `default`), so this does not apply. - 2.1.299: MCP allow rules now match only the whole server name. Paperclip already writes `mcp__<server>__*` and exact `mcp__paperclip__<tool>` rules. - 2.1.302: fork subagents are on by default in `-p` and the Agent SDK, as in the terminal. This pull request keeps the upstream default and does not set `CLAUDE_CODE_FORK_SUBAGENT=0`. Reviewers can ask to keep them off. - 2.1.299 and later: stdio MCP connections negotiate MCP protocol 2026-07-28 first and fall back to the older protocol for servers that do not answer. - Agent SDK 0.3.328 is less than one day old. If a regression appears, revert this pull request to return to 0.3.286 and Codex 0.160.0. - Sandbox images built before this change still carry Codex 0.160.0 and Claude Code 2.1.286. They stay accepted. On those images, Fable 5.2 and GPT-6.2 keep the existing named errors and fallbacks until a new image is promoted. - Until the refresh bot updates `pnpm-lock.yaml` on `master`, a local `--frozen-lockfile` install fails, as with the previous pin refreshes. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude, model ID `claude-opus-5-5`, through Claude Code with tool use (shell, file edit, `gh`) and code execution. The context window and reasoning mode are not reported in this session. - The registry archives, digests, release notes, configuration schemas, and changelog were read directly. No model output was used as a source for those facts. ## 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 - [ ] 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: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1806 lines
81 KiB
TypeScript
1806 lines
81 KiB
TypeScript
import { asStringArray } from "@paperclipai/adapter-utils/server-utils";
|
|
import { applyObservabilityEnvironment } from "@paperclipai/adapter-utils/agent-observability";
|
|
import { prepareCodexObservabilityProfile, selectedCodexProfile, replaceCodexProfileArgs, disableCodexObservabilityArgs } from "@paperclipai/adapter-utils/codex-observability-profile";
|
|
import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary";
|
|
import { createUsageCheckpointLog } from "@paperclipai/adapter-utils/usage-checkpoint";
|
|
import { createHash } from "node:crypto";
|
|
import fs from "node:fs/promises";
|
|
import path from "node:path";
|
|
import os from "node:os";
|
|
import { fileURLToPath } from "node:url";
|
|
import { inferOpenAiCompatibleBiller, resolveManagedOpenAiBilling, type AdapterExecutionContext, type AdapterExecutionResult } from "@paperclipai/adapter-utils";
|
|
import { buildCodexAuthInboundProvision } from "./codex-auth-merge-scripts.js";
|
|
import { copyBackCodexAuth } from "./codex-auth-copyback.js";
|
|
import { prepareCodexSshSessionState } from "./ssh-session-state.js";
|
|
import { readCodexSshHostHome, readCodexSshHostProfile, buildCodexSshHostRuntimeInstall } from "./ssh-host-runtime.js";
|
|
import { shellQuote } from "@paperclipai/adapter-utils/ssh";
|
|
import {
|
|
ensureCodexAuthCacheEntryDir,
|
|
isCodexAuthCacheEnabled,
|
|
readSubscriptionAccountId,
|
|
resolveCodexAuthCacheEntryPath,
|
|
selectVendCredential,
|
|
} from "./codex-auth-cache.js";
|
|
import {
|
|
managedRemoteHomeEnvironment,
|
|
adapterExecutionTargetIsRemote,
|
|
adapterExecutionTargetRemoteCwd,
|
|
overrideAdapterExecutionTargetRemoteCwd,
|
|
adapterExecutionTargetSessionIdentity,
|
|
adapterExecutionTargetSessionMatches,
|
|
adapterExecutionTargetUsesPaperclipBridge,
|
|
describeAdapterExecutionTarget,
|
|
ensureAdapterExecutionTargetCommandResolvable,
|
|
ensureAdapterExecutionTargetRuntimeCommandInstalled,
|
|
prepareAdapterExecutionTargetRuntime,
|
|
adapterExecutionTargetDuplexObservabilityRecorder,
|
|
adapterExecutionTargetEnablesSandboxDuplexBridge,
|
|
readAdapterExecutionTarget,
|
|
resolveAdapterExecutionTargetTimeoutSec,
|
|
resolveAdapterExecutionTargetCommandForLogs,
|
|
runAdapterExecutionTargetProcess,
|
|
runAdapterExecutionTargetShellCommand,
|
|
startAdapterExecutionTargetPaperclipBridge,
|
|
} from "@paperclipai/adapter-utils/execution-target";
|
|
import {
|
|
asString,
|
|
asNumber,
|
|
parseObject,
|
|
buildPaperclipEnv,
|
|
buildInvocationEnvForLogs,
|
|
ensureAbsoluteDirectory,
|
|
ensurePaperclipSkillSymlink,
|
|
ensurePathInEnv,
|
|
refreshPaperclipWorkspaceEnvForExecution,
|
|
isPaperclipSkillSourceMissing,
|
|
readPaperclipRuntimeSkillEntries,
|
|
readPaperclipIssueWorkModeFromContext,
|
|
renderTemplate,
|
|
hydrateFreshSessionHandoff,
|
|
selectInitialCommunicationGuidance,
|
|
selectPaperclipPromptSections,
|
|
isPaperclipRecoveryWakePayload,
|
|
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
|
|
DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE,
|
|
joinPromptSections,
|
|
} from "@paperclipai/adapter-utils/server-utils";
|
|
import {
|
|
parseLocalProcessFilesystemScope,
|
|
parseLocalProcessSandboxExtraPaths,
|
|
parseLocalProcessNetworkAllowlist,
|
|
parseLocalProcessNetworkScope,
|
|
type LocalProcessSandboxOptions,
|
|
} from "@paperclipai/adapter-utils/local-process-sandbox";
|
|
import {
|
|
parseCodexJsonl, createCodexJsonlParser,
|
|
classifyCodexAuthRefreshFailure,
|
|
extractCodexRetryNotBefore,
|
|
isCodexHarnessCrash,
|
|
isCodexProviderQuotaError,
|
|
isCodexTransientUpstreamError,
|
|
isCodexUnknownSessionError,
|
|
} from "./parse.js";
|
|
import {
|
|
codexHomeHasUsableAuth,
|
|
evaluateCodexCredentialReadiness,
|
|
isManagedCodexHomePath,
|
|
pathExists,
|
|
prepareManagedCodexHome,
|
|
resolveManagedCodexHomeDir,
|
|
resolveSharedCodexHomeDir,
|
|
seedManagedCodexHome,
|
|
stageCodexHomeForSync,
|
|
mergeManagedCodexMcpGateways,
|
|
writeManagedCodexMcpConfig,
|
|
type ManagedCodexMcpGateway,
|
|
} from "./codex-home.js";
|
|
import {
|
|
CODEX_SANDBOX_AUTH_EXISTS_COMMAND,
|
|
CODEX_SANDBOX_AUTH_PRECEDENCE_WARNING,
|
|
CODEX_SANDBOX_AUTH_PRECEDENCE_WARNING_LOG_LINE,
|
|
resolveCodexAuthPrecedence,
|
|
} from "./auth-precedence.js";
|
|
import { prepareCodexRuntimeConfig } from "./runtime-config.js";
|
|
import { resolveCodexDesiredSkillNames } from "./skills.js";
|
|
import { buildCodexExecArgs } from "./codex-args.js";
|
|
import { SANDBOX_INSTALL_COMMAND } from "../index.js";
|
|
import {
|
|
CODEX_OUTPUT_INACTIVITY_MONITOR_SIGTERM_GRACE_MS,
|
|
createCodexOutputInactivityMonitor,
|
|
formatOutputInactivityMonitorErrorMessage,
|
|
resolveCodexInactivityTimeout,
|
|
} from "./output-inactivity-monitor.js";
|
|
import {
|
|
CODEX_PROCESS_ACTIVITY_POLL_INTERVAL_MS,
|
|
createCodexProcessActivityMonitor,
|
|
type CodexProcessActivityMonitorHandle,
|
|
} from "./process-activity-monitor.js";
|
|
import {
|
|
createCodexAcpExecutor,
|
|
resolveCodexExecutionEngineForRun,
|
|
} from "./acp.js";
|
|
import { codexShellEnvironmentKeys } from "@paperclipai/adapter-utils/codex-shell-environment";
|
|
|
|
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
const executeCodexAcp = createCodexAcpExecutor();
|
|
const CODEX_ROLLOUT_NOISE_RE =
|
|
/^\d{4}-\d{2}-\d{2}T[^\s]+\s+ERROR\s+codex_core::rollout::list:\s+state db missing rollout path for thread\s+[a-z0-9-]+$/i;
|
|
|
|
function stripCodexRolloutNoise(text: string): string {
|
|
const parts = text.split(/\r?\n/);
|
|
const kept: string[] = [];
|
|
for (const part of parts) {
|
|
const trimmed = part.trim();
|
|
if (!trimmed) {
|
|
kept.push(part);
|
|
continue;
|
|
}
|
|
if (CODEX_ROLLOUT_NOISE_RE.test(trimmed)) continue;
|
|
kept.push(part);
|
|
}
|
|
return kept.join("\n");
|
|
}
|
|
|
|
function firstNonEmptyLine(text: string): string {
|
|
return (
|
|
text
|
|
.split(/\r?\n/)
|
|
.map((line) => line.trim())
|
|
.find(Boolean) ?? ""
|
|
);
|
|
}
|
|
|
|
// Benign stderr lines that never explain a nonzero exit and must not be
|
|
// surfaced as the run error: Codex always prints the YOLO approvals warning
|
|
// because this adapter passes the approvals-bypass flag itself, and
|
|
// "[paperclip] ..." lines are diagnostics the adapter injected (e.g. ACP
|
|
// fallback notes). Keep this list conservative so real errors are never
|
|
// skipped.
|
|
const BENIGN_CODEX_STDERR_LINE_RES: readonly RegExp[] = [
|
|
/^YOLO mode is enabled\b/i,
|
|
/^\[paperclip\]/,
|
|
];
|
|
|
|
function isBenignCodexStderrLine(line: string): boolean {
|
|
return BENIGN_CODEX_STDERR_LINE_RES.some((re) => re.test(line));
|
|
}
|
|
|
|
export function firstMeaningfulStderrLine(text: string): string {
|
|
const meaningful = text
|
|
.split(/\r?\n/)
|
|
.map((line) => line.trim())
|
|
.find((line) => line && !isBenignCodexStderrLine(line));
|
|
return meaningful ?? firstNonEmptyLine(text);
|
|
}
|
|
|
|
function signalCodexChild(
|
|
target: { pid: number | null; processGroupId: number | null },
|
|
signal: NodeJS.Signals,
|
|
): boolean {
|
|
if (process.platform !== "win32" && target.processGroupId && target.processGroupId > 0) {
|
|
try {
|
|
process.kill(-target.processGroupId, signal);
|
|
return true;
|
|
} catch {
|
|
// Fall back to direct child signal if group signaling fails (e.g. group already gone).
|
|
}
|
|
}
|
|
if (target.pid && target.pid > 0) {
|
|
try {
|
|
process.kill(target.pid, signal);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function hasNonEmptyEnvValue(env: Record<string, string>, key: string): boolean {
|
|
const raw = env[key];
|
|
return typeof raw === "string" && raw.trim().length > 0;
|
|
}
|
|
|
|
function resolveCodexBillingType(env: Record<string, string>): "api" | "subscription" {
|
|
// Codex uses API-key auth when OPENAI_API_KEY is present; otherwise rely on local login/session auth.
|
|
return hasNonEmptyEnvValue(env, "OPENAI_API_KEY") ? "api" : "subscription";
|
|
}
|
|
|
|
function resolveCodexBiller(env: Record<string, string>, billingType: "api" | "subscription"): string {
|
|
const openAiCompatibleBiller = inferOpenAiCompatibleBiller(env, "openai");
|
|
if (openAiCompatibleBiller === "openrouter") return "openrouter";
|
|
return billingType === "subscription" ? "chatgpt" : openAiCompatibleBiller ?? "openai";
|
|
}
|
|
|
|
async function isLikelyPaperclipRepoRoot(candidate: string): Promise<boolean> {
|
|
const [hasWorkspace, hasPackageJson, hasServerDir, hasAdapterUtilsDir] = await Promise.all([
|
|
pathExists(path.join(candidate, "pnpm-workspace.yaml")),
|
|
pathExists(path.join(candidate, "package.json")),
|
|
pathExists(path.join(candidate, "server")),
|
|
pathExists(path.join(candidate, "packages", "adapter-utils")),
|
|
]);
|
|
|
|
return hasWorkspace && hasPackageJson && hasServerDir && hasAdapterUtilsDir;
|
|
}
|
|
|
|
async function isLikelyPaperclipRuntimeSkillPath(
|
|
candidate: string,
|
|
skillName: string,
|
|
options: { requireSkillMarkdown?: boolean } = {},
|
|
): Promise<boolean> {
|
|
if (path.basename(candidate) !== skillName) return false;
|
|
const skillsRoot = path.dirname(candidate);
|
|
if (path.basename(skillsRoot) !== "skills") return false;
|
|
if (options.requireSkillMarkdown !== false && !(await pathExists(path.join(candidate, "SKILL.md")))) {
|
|
return false;
|
|
}
|
|
|
|
let cursor = path.dirname(skillsRoot);
|
|
for (let depth = 0; depth < 6; depth += 1) {
|
|
if (await isLikelyPaperclipRepoRoot(cursor)) return true;
|
|
const parent = path.dirname(cursor);
|
|
if (parent === cursor) break;
|
|
cursor = parent;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
async function pruneBrokenUnavailablePaperclipSkillSymlinks(
|
|
skillsHome: string,
|
|
allowedSkillNames: Iterable<string>,
|
|
onLog: AdapterExecutionContext["onLog"],
|
|
) {
|
|
const allowed = new Set(Array.from(allowedSkillNames));
|
|
const entries = await fs.readdir(skillsHome, { withFileTypes: true }).catch(() => []);
|
|
|
|
for (const entry of entries) {
|
|
if (allowed.has(entry.name) || !entry.isSymbolicLink()) continue;
|
|
|
|
const target = path.join(skillsHome, entry.name);
|
|
const linkedPath = await fs.readlink(target).catch(() => null);
|
|
if (!linkedPath) continue;
|
|
|
|
const resolvedLinkedPath = path.resolve(path.dirname(target), linkedPath);
|
|
if (await pathExists(resolvedLinkedPath)) continue;
|
|
if (
|
|
!(await isLikelyPaperclipRuntimeSkillPath(resolvedLinkedPath, entry.name, {
|
|
requireSkillMarkdown: false,
|
|
}))
|
|
) {
|
|
continue;
|
|
}
|
|
|
|
await fs.unlink(target).catch(() => {});
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Removed stale Codex skill "${entry.name}" from ${skillsHome}\n`,
|
|
);
|
|
}
|
|
}
|
|
|
|
function resolveCodexSkillsDir(codexHome: string): string {
|
|
return path.join(codexHome, "skills");
|
|
}
|
|
|
|
type EnsureCodexSkillsInjectedOptions = {
|
|
skillsHome?: string;
|
|
skillsEntries?: Array<{ key: string; runtimeName: string; source: string }>;
|
|
desiredSkillNames?: string[];
|
|
linkSkill?: (source: string, target: string) => Promise<void>;
|
|
};
|
|
|
|
type CodexTransientFallbackMode =
|
|
| "same_session"
|
|
| "safer_invocation"
|
|
| "fresh_session"
|
|
| "fresh_session_safer_invocation";
|
|
|
|
function readCodexTransientFallbackMode(context: Record<string, unknown>): CodexTransientFallbackMode | null {
|
|
const value = asString(context.codexTransientFallbackMode, "").trim();
|
|
switch (value) {
|
|
case "same_session":
|
|
case "safer_invocation":
|
|
case "fresh_session":
|
|
case "fresh_session_safer_invocation":
|
|
return value;
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function fallbackModeUsesSaferInvocation(mode: CodexTransientFallbackMode | null): boolean {
|
|
return mode === "safer_invocation" || mode === "fresh_session_safer_invocation";
|
|
}
|
|
|
|
function fallbackModeUsesFreshSession(mode: CodexTransientFallbackMode | null): boolean {
|
|
return mode === "fresh_session" || mode === "fresh_session_safer_invocation";
|
|
}
|
|
|
|
function managedMcpGatewaysFromContext(context: Record<string, unknown>): ManagedCodexMcpGateway[] {
|
|
const managedMcp = parseObject(context.paperclipManagedMcp);
|
|
if (managedMcp.managedMcpOnly !== true) return [];
|
|
const gateways = Array.isArray(managedMcp.gateways) ? managedMcp.gateways : [];
|
|
return gateways
|
|
.map((raw): ManagedCodexMcpGateway | null => {
|
|
const gateway = parseObject(raw);
|
|
const name = asString(gateway.name, "").trim();
|
|
const endpointPath = asString(gateway.endpointPath, "").trim();
|
|
const bearerToken = asString(gateway.bearerToken, "").trim();
|
|
if (!name || !endpointPath || !bearerToken) return null;
|
|
return { name, endpointPath, bearerToken };
|
|
})
|
|
.filter((gateway): gateway is ManagedCodexMcpGateway => Boolean(gateway));
|
|
}
|
|
|
|
type ResolvedExecutionTarget = ReturnType<typeof readAdapterExecutionTarget>;
|
|
type MaybeResolvedExecutionTarget = ResolvedExecutionTarget | undefined;
|
|
|
|
type SandboxCodexAuthProbeResult = "present" | "absent" | "unknown";
|
|
|
|
/**
|
|
* Probe the sandbox for its own `~/.codex/auth.json`. "unknown" means the
|
|
* probe itself failed (timeout, transport error, or a shell failure other
|
|
* than `test`'s clean false) — callers that gate on the result must not
|
|
* report that as a missing credential.
|
|
*/
|
|
async function probeSandboxCodexAuthJson(input: {
|
|
runId: string;
|
|
target: MaybeResolvedExecutionTarget;
|
|
cwd: string;
|
|
}): Promise<SandboxCodexAuthProbeResult> {
|
|
if (!input.target || input.target.kind !== "remote" || input.target.transport !== "sandbox") {
|
|
return "absent";
|
|
}
|
|
|
|
try {
|
|
const result = await runAdapterExecutionTargetShellCommand(
|
|
input.runId,
|
|
input.target,
|
|
CODEX_SANDBOX_AUTH_EXISTS_COMMAND,
|
|
{
|
|
cwd: input.cwd,
|
|
env: {},
|
|
timeoutSec: 5,
|
|
},
|
|
);
|
|
if (result.timedOut) return "unknown";
|
|
if (result.exitCode === 0) return "present";
|
|
return result.exitCode === 1 ? "absent" : "unknown";
|
|
} catch {
|
|
return "unknown";
|
|
}
|
|
}
|
|
|
|
async function sandboxCodexAuthJsonExists(input: {
|
|
runId: string;
|
|
target: MaybeResolvedExecutionTarget;
|
|
cwd: string;
|
|
}): Promise<boolean> {
|
|
return (await probeSandboxCodexAuthJson(input)) === "present";
|
|
}
|
|
|
|
/**
|
|
* Execute-time credential gate. A managed home with no host-side credentials
|
|
* is still launchable when the run targets a sandbox whose image carries its
|
|
* own Codex login (`~/.codex/auth.json` baked in during image setup): the
|
|
* inbound auth merge ships the credential-less host home and keeps the
|
|
* sandbox's credential, so the host is not a required credential source —
|
|
* on managed cloud hosts a local Codex login never exists at all. The
|
|
* sandbox is probed before the run is declared unlaunchable; non-sandbox
|
|
* targets keep the strict host-side requirement.
|
|
*/
|
|
export async function assertCodexCredentialsLaunchable(input: {
|
|
runId: string;
|
|
companyId: string;
|
|
configuredCodexHome: string | null;
|
|
configuredApiKey: string | null;
|
|
effectiveCodexHome: string;
|
|
target: MaybeResolvedExecutionTarget;
|
|
cwd: string;
|
|
env?: NodeJS.ProcessEnv;
|
|
onLog: AdapterExecutionContext["onLog"];
|
|
}): Promise<void> {
|
|
const credentialReadiness = await evaluateCodexCredentialReadiness({
|
|
env: input.env ?? process.env,
|
|
companyId: input.companyId,
|
|
configuredCodexHome: input.configuredCodexHome,
|
|
configuredApiKey: input.configuredApiKey,
|
|
});
|
|
if (!credentialReadiness.managed || credentialReadiness.ready) return;
|
|
|
|
const targetIsSandbox =
|
|
input.target?.kind === "remote" && input.target.transport === "sandbox";
|
|
if (targetIsSandbox) {
|
|
const sandboxAuthJson = await probeSandboxCodexAuthJson({
|
|
runId: input.runId,
|
|
target: input.target,
|
|
cwd: input.cwd,
|
|
});
|
|
if (sandboxAuthJson === "present") {
|
|
await input.onLog(
|
|
"stdout",
|
|
`Using the sandbox's own Codex login; managed home "${input.effectiveCodexHome}" has no host credentials.\n`,
|
|
);
|
|
return;
|
|
}
|
|
if (sandboxAuthJson === "unknown") {
|
|
// The probe failing is an operational problem, not evidence that the
|
|
// sandbox lacks a login — proceeding lets a genuinely credentialed
|
|
// sandbox run, and a credential-less one still fails at Codex's first
|
|
// request with the provider's own error.
|
|
await input.onLog(
|
|
"stderr",
|
|
`Could not verify the sandbox's Codex login (probe failed); proceeding. ` +
|
|
`If the sandbox has no credentials, Codex will fail at its first request.\n`,
|
|
);
|
|
return;
|
|
}
|
|
throw new Error(
|
|
`no Codex credentials provisioned for managed home "${input.effectiveCodexHome}" ` +
|
|
`(no usable auth.json, OPENAI_API_KEY is empty, and the sandbox has no Codex login). ` +
|
|
`Use a sandbox image that is signed in to Codex, configure a per-agent OPENAI_API_KEY, ` +
|
|
`or sign in to Codex on the host with a ChatGPT subscription.`,
|
|
);
|
|
}
|
|
|
|
throw new Error(
|
|
`no Codex credentials provisioned for managed home "${input.effectiveCodexHome}" ` +
|
|
`(no usable auth.json and OPENAI_API_KEY is empty). ` +
|
|
`Sign in to Codex on the host with a ChatGPT subscription, or configure a per-agent ` +
|
|
`OPENAI_API_KEY.`,
|
|
);
|
|
}
|
|
|
|
async function emitSandboxAuthPrecedenceWarningIfNeeded(input: {
|
|
runId: string;
|
|
target: MaybeResolvedExecutionTarget;
|
|
cwd: string;
|
|
configuredApiKey: boolean;
|
|
hostAuthJson: boolean;
|
|
onLog: AdapterExecutionContext["onLog"];
|
|
onEvent: AdapterExecutionContext["onEvent"];
|
|
}): Promise<void> {
|
|
if (!input.target || input.target.kind !== "remote" || input.target.transport !== "sandbox") {
|
|
return;
|
|
}
|
|
|
|
const sandboxAuthJson = await sandboxCodexAuthJsonExists({
|
|
runId: input.runId,
|
|
target: input.target,
|
|
cwd: input.cwd,
|
|
});
|
|
const resolution = resolveCodexAuthPrecedence({
|
|
configuredApiKey: input.configuredApiKey,
|
|
hostAuthJson: input.hostAuthJson,
|
|
sandboxAuthJson,
|
|
});
|
|
if (!resolution.shouldWarn) return;
|
|
|
|
await input.onLog("stderr", CODEX_SANDBOX_AUTH_PRECEDENCE_WARNING_LOG_LINE);
|
|
await input.onEvent?.({
|
|
eventType: "codex.auth_precedence_warning",
|
|
stream: "system",
|
|
level: "warn",
|
|
message: CODEX_SANDBOX_AUTH_PRECEDENCE_WARNING,
|
|
payload: {
|
|
configuredApiKey: input.configuredApiKey,
|
|
hostAuthJson: input.hostAuthJson,
|
|
sandboxAuthJson,
|
|
winner: resolution.winner,
|
|
sandboxLoginShadowed: resolution.sandboxLoginShadowed,
|
|
},
|
|
});
|
|
}
|
|
|
|
function buildCodexTransientHandoffNote(input: {
|
|
previousSessionId: string | null;
|
|
fallbackMode: CodexTransientFallbackMode;
|
|
continuationSummaryBody: string | null;
|
|
}): string {
|
|
return [
|
|
"Paperclip session handoff:",
|
|
input.previousSessionId ? `- Previous session: ${input.previousSessionId}` : "",
|
|
"- Rotation reason: repeated Codex transient remote-compaction failures",
|
|
`- Fallback mode: ${input.fallbackMode}`,
|
|
input.continuationSummaryBody
|
|
? `- Issue continuation summary: ${input.continuationSummaryBody.slice(0, 1_500)}`
|
|
: "",
|
|
"Continue from the current task state. Rebuild only the minimum context you need.",
|
|
]
|
|
.filter(Boolean)
|
|
.join("\n");
|
|
}
|
|
|
|
export async function ensureCodexSkillsInjected(
|
|
onLog: AdapterExecutionContext["onLog"],
|
|
options: EnsureCodexSkillsInjectedOptions = {},
|
|
) {
|
|
const allSkillsEntries = options.skillsEntries
|
|
?? (await readPaperclipRuntimeSkillEntries({}, __moduleDir)).filter(
|
|
(entry) => !isPaperclipSkillSourceMissing(entry),
|
|
);
|
|
const desiredSkillNames =
|
|
options.desiredSkillNames ?? allSkillsEntries.map((entry) => entry.key);
|
|
const desiredSet = new Set(desiredSkillNames);
|
|
const skillsEntries = allSkillsEntries.filter((entry) => desiredSet.has(entry.key));
|
|
if (skillsEntries.length === 0) return;
|
|
|
|
const skillsHome = options.skillsHome ?? resolveCodexSkillsDir(resolveSharedCodexHomeDir());
|
|
await fs.mkdir(skillsHome, { recursive: true });
|
|
const linkSkill = options.linkSkill;
|
|
for (const entry of skillsEntries) {
|
|
const target = path.join(skillsHome, entry.runtimeName);
|
|
|
|
try {
|
|
const existing = await fs.lstat(target).catch(() => null);
|
|
if (existing?.isSymbolicLink()) {
|
|
const linkedPath = await fs.readlink(target).catch(() => null);
|
|
const resolvedLinkedPath = linkedPath
|
|
? path.resolve(path.dirname(target), linkedPath)
|
|
: null;
|
|
if (
|
|
resolvedLinkedPath &&
|
|
resolvedLinkedPath !== entry.source &&
|
|
(await isLikelyPaperclipRuntimeSkillPath(resolvedLinkedPath, entry.runtimeName))
|
|
) {
|
|
await fs.unlink(target);
|
|
if (linkSkill) {
|
|
await linkSkill(entry.source, target);
|
|
} else {
|
|
await fs.symlink(entry.source, target);
|
|
}
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Repaired Codex skill "${entry.runtimeName}" into ${skillsHome}\n`,
|
|
);
|
|
continue;
|
|
}
|
|
}
|
|
|
|
const result = await ensurePaperclipSkillSymlink(entry.source, target, linkSkill);
|
|
if (result === "skipped") continue;
|
|
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Codex skill "${entry.runtimeName}" into ${skillsHome}\n`,
|
|
);
|
|
} catch (err) {
|
|
await onLog(
|
|
"stderr",
|
|
`[paperclip] Failed to inject Codex skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`,
|
|
);
|
|
}
|
|
}
|
|
|
|
await pruneBrokenUnavailablePaperclipSkillSymlinks(
|
|
skillsHome,
|
|
skillsEntries.map((entry) => entry.runtimeName),
|
|
onLog,
|
|
);
|
|
}
|
|
|
|
export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecutionResult> {
|
|
const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped);
|
|
const engineSelection = await resolveCodexExecutionEngineForRun(ctx);
|
|
if (engineSelection.unavailableReason) {
|
|
return {
|
|
exitCode: 1,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorCode: "adapter_engine_unavailable",
|
|
errorMessage: engineSelection.unavailableReason,
|
|
resultJson: {
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
},
|
|
};
|
|
}
|
|
if (engineSelection.engine === "acp") {
|
|
return executeCodexAcp(ctx);
|
|
}
|
|
|
|
const { runId, agent, runtime, config, context, onLog, onMeta, onEvent, onSpawn, authToken } = ctx;
|
|
|
|
const promptTemplate = asString(
|
|
config.promptTemplate,
|
|
context.conversationMode === true
|
|
? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
|
|
: DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
|
|
);
|
|
const command = asString(config.command, "codex");
|
|
const model = asString(config.model, "");
|
|
|
|
const workspaceContext = parseObject(context.paperclipWorkspace);
|
|
const workspaceCwd = asString(workspaceContext.cwd, "");
|
|
const workspaceSource = asString(workspaceContext.source, "");
|
|
const workspaceStrategy = asString(workspaceContext.strategy, "");
|
|
const workspaceId = asString(workspaceContext.workspaceId, "");
|
|
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
|
|
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
|
const workspaceBranch = asString(workspaceContext.branchName, "");
|
|
const workspaceWorktreePath = asString(workspaceContext.worktreePath, "");
|
|
const agentHome = asString(workspaceContext.agentHome, "");
|
|
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
|
? context.paperclipWorkspaces.filter(
|
|
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
|
)
|
|
: [];
|
|
const runtimeServiceIntents = Array.isArray(context.paperclipRuntimeServiceIntents)
|
|
? context.paperclipRuntimeServiceIntents.filter(
|
|
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
|
)
|
|
: [];
|
|
const runtimeServices = Array.isArray(context.paperclipRuntimeServices)
|
|
? context.paperclipRuntimeServices.filter(
|
|
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
|
)
|
|
: [];
|
|
const runtimePrimaryUrl = asString(context.paperclipRuntimePrimaryUrl, "");
|
|
const executionTarget = readAdapterExecutionTarget({
|
|
executionTarget: ctx.executionTarget,
|
|
legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
|
|
});
|
|
const targetWorkspaceRealization = executionTarget?.workspaceRealization ?? null;
|
|
const configuredCwd = asString(config.cwd, "");
|
|
const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
|
|
const effectiveWorkspaceCwd = targetWorkspaceRealization?.mode === "in_place"
|
|
? targetWorkspaceRealization.authoritativeRoot
|
|
: useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
|
|
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
|
|
const envConfig = parseObject(config.env);
|
|
const executionTargetIsRemote = adapterExecutionTargetIsRemote(executionTarget);
|
|
const useSshHostAuth = executionTarget?.kind === "remote" && executionTarget.transport === "ssh" && executionTarget.spec.useHostAuth === true;
|
|
let configuredCodexHome =
|
|
!useSshHostAuth && typeof envConfig.CODEX_HOME === "string" && envConfig.CODEX_HOME.trim().length > 0
|
|
? path.resolve(envConfig.CODEX_HOME.trim())
|
|
: null;
|
|
const configuredOpenAiApiKey =
|
|
typeof envConfig.OPENAI_API_KEY === "string" && envConfig.OPENAI_API_KEY.trim().length > 0
|
|
? envConfig.OPENAI_API_KEY.trim()
|
|
: null;
|
|
const skillSourceHome = configuredCodexHome;
|
|
const connectorSkillDigest = typeof config.paperclipConnectorSkillDigest === "string"
|
|
&& /^[a-f0-9]{64}$/.test(config.paperclipConnectorSkillDigest) ? config.paperclipConnectorSkillDigest : null;
|
|
const codexSkillEntries = (await readPaperclipRuntimeSkillEntries(config, __moduleDir))
|
|
.filter((entry) => !isPaperclipSkillSourceMissing(entry));
|
|
const desiredSkillNames = resolveCodexDesiredSkillNames(config, codexSkillEntries);
|
|
const desiredSet = new Set(desiredSkillNames);
|
|
// An explicit inventory is the server's authorized execution selection. Include
|
|
// empty inventories: revocation must not fall back to a previously populated home.
|
|
let runtimeSkillDigest = Array.isArray(config.paperclipRuntimeSkills)
|
|
? createHash("sha256").update(JSON.stringify({ connectorSkillDigest,
|
|
skills: codexSkillEntries.filter(entry => desiredSet.has(entry.key))
|
|
.map(entry => [entry.key, entry.source]).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
|
|
})).digest("hex")
|
|
: connectorSkillDigest;
|
|
const runtimeCredentialHome = runtimeSkillDigest && !useSshHostAuth
|
|
? skillSourceHome ?? await prepareManagedCodexHome(process.env, onLog, agent.companyId, { apiKey: configuredOpenAiApiKey })
|
|
: null;
|
|
if (runtimeSkillDigest && !useSshHostAuth) {
|
|
const credentialHome = runtimeCredentialHome!;
|
|
const credentialBytes = await fs.readFile(path.join(credentialHome, "auth.json")).catch(() => null);
|
|
const selectedConfig = await fs.readFile(path.join(credentialHome, "config.toml")).catch(() => null);
|
|
// Keep selected-home provider/MCP edits (and removals) in the launched home.
|
|
const selectedConfigDigest = selectedConfig ? createHash("sha256").update(selectedConfig).digest("hex") : null;
|
|
// Copy-back may retain a refreshed regular credential in a generated home.
|
|
// Account switches must select a different home, while token refreshes for
|
|
// the same subscription identity preserve its cache and session state.
|
|
const credentialIdentity = credentialBytes
|
|
? readSubscriptionAccountId(credentialBytes) ?? createHash("sha256").update(credentialBytes).digest("hex") : null;
|
|
runtimeSkillDigest = createHash("sha256").update(JSON.stringify({
|
|
runtimeSkillDigest, credentialHome, credentialIdentity, selectedConfigDigest, apiKey: envConfig.OPENAI_API_KEY ?? null,
|
|
})).digest("hex");
|
|
// Different authorized versions/assignments get separate homes, including
|
|
// session state. Previously permitted private links cannot survive revocation.
|
|
configuredCodexHome = path.join(resolveManagedCodexHomeDir(process.env, agent.companyId),
|
|
connectorSkillDigest ? "connector-runtimes" : "skill-runtimes", agent.id, runtimeSkillDigest);
|
|
}
|
|
if (!executionTargetIsRemote) {
|
|
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
|
|
}
|
|
// A configured CODEX_HOME that lives under the Paperclip-managed company tree
|
|
// (the per-agent home set by the server isolation guard) still needs auth
|
|
// seeded — it ships with no credentials and OPENAI_API_KEY="" by default.
|
|
// Only a genuine external/user-supplied override is treated as self-managed
|
|
// and left untouched.
|
|
const configuredHomeIsManaged =
|
|
configuredCodexHome != null &&
|
|
isManagedCodexHomePath(process.env, agent.companyId, configuredCodexHome);
|
|
// Identity-anchored cache vend (host to sandbox). Before the managed home is
|
|
// seeded from the shared source `auth.json`, refresh the shared credential with
|
|
// a strictly-newer cached copy of the SAME identity. The vend reads the host
|
|
// identity first and resolves only that identity's cache slot; when the host
|
|
// holds no credential it does nothing (no random pick). This keeps the change
|
|
// additive: the managed home still symlinks the shared `auth.json`, now at its
|
|
// freshest same-identity copy. The off-switch (default on) skips the vend.
|
|
if (!useSshHostAuth && !config.managedAiConnection && isCodexAuthCacheEnabled(process.env)) {
|
|
const sharedHomeAuthPath = path.join(resolveSharedCodexHomeDir(process.env), "auth.json");
|
|
// This caller reads `process.env` directly and holds no separate `env`
|
|
// object, so `selectVendCredential` falls back to its own `process.env`
|
|
// default for the merge lock root.
|
|
await selectVendCredential(
|
|
sharedHomeAuthPath,
|
|
(accountId) => resolveCodexAuthCacheEntryPath(process.env, accountId, agent.companyId),
|
|
(line) => onLog("stdout", `${line}\n`),
|
|
).catch(async (error) => {
|
|
// The vend is best-effort and additive. A vend failure must never block a
|
|
// run: log and fall through to seed from the unrefreshed shared credential.
|
|
await onLog(
|
|
"stderr",
|
|
`[paperclip] Codex auth cache: vend skipped after an error; using the shared credential as-is.\n`,
|
|
);
|
|
void error;
|
|
});
|
|
}
|
|
if (!useSshHostAuth && configuredCodexHome == null) {
|
|
await prepareManagedCodexHome(process.env, onLog, agent.companyId, {
|
|
apiKey: configuredOpenAiApiKey,
|
|
});
|
|
}
|
|
if (!useSshHostAuth && configuredHomeIsManaged && configuredCodexHome) {
|
|
const seedEnv = runtimeSkillDigest ? {
|
|
...process.env, CODEX_HOME: runtimeCredentialHome ?? resolveManagedCodexHomeDir(process.env, agent.companyId),
|
|
} : process.env;
|
|
await seedManagedCodexHome(configuredCodexHome, seedEnv, onLog, {
|
|
apiKey: configuredOpenAiApiKey,
|
|
});
|
|
}
|
|
const defaultCodexHome = resolveManagedCodexHomeDir(process.env, agent.companyId);
|
|
const effectiveCodexHome = configuredCodexHome ?? defaultCodexHome;
|
|
await fs.mkdir(effectiveCodexHome, { recursive: true });
|
|
|
|
// Never launch a managed CODEX_HOME with no credentials. Without auth.json
|
|
// and with OPENAI_API_KEY="" the provider rejects every request with
|
|
// "401 Missing bearer"; fail fast with a clear adapter error instead of
|
|
// emitting unauthenticated calls. External overrides manage their own auth.
|
|
// This is the execute-time backstop for the control plane's pre-dispatch
|
|
// configuration-incomplete gate (see server heartbeat); both decide host
|
|
// readiness through the same `evaluateCodexCredentialReadiness` predicate,
|
|
// and sandbox targets are additionally allowed to supply their own login
|
|
// (the pre-dispatch gate defers sandbox-destined runs here for exactly that
|
|
// probe).
|
|
if (!useSshHostAuth) await assertCodexCredentialsLaunchable({
|
|
runId,
|
|
companyId: agent.companyId,
|
|
configuredCodexHome,
|
|
configuredApiKey: configuredOpenAiApiKey,
|
|
effectiveCodexHome,
|
|
target: executionTarget,
|
|
cwd,
|
|
onLog,
|
|
});
|
|
// Merge custom model providers (PAPERCLIP_CODEX_PROVIDERS) into the managed
|
|
// CODEX_HOME's config.toml BEFORE the home is shipped to a remote execution
|
|
// target, so both local and sandboxed Codex processes pick up the routing.
|
|
// A caller-owned home stays untouched. A generated skill home receives the
|
|
// configured provider routing even when it seeds credentials from that home.
|
|
const envConfigStrings = Object.fromEntries(
|
|
Object.entries(envConfig).filter(
|
|
(entry): entry is [string, string] => typeof entry[1] === "string",
|
|
),
|
|
);
|
|
const preparedRuntimeConfig = await prepareCodexRuntimeConfig({
|
|
env: envConfigStrings,
|
|
codexHome: useSshHostAuth || (configuredCodexHome && !runtimeSkillDigest) ? null : effectiveCodexHome,
|
|
});
|
|
// Curated allowlist dir staged for the remote `home` asset (see below). Held
|
|
// here so the outer `finally` can remove it on every exit path (teardown and
|
|
// error), never only the happy path.
|
|
let stagedCodexHomeDir: string | null = null;
|
|
let sshHostHome: Awaited<ReturnType<typeof readCodexSshHostHome>> | null = null;
|
|
let sshHostProfilePath: string | null = null;
|
|
let sshSessionState: Awaited<ReturnType<typeof prepareCodexSshSessionState>> | null = null;
|
|
let observabilityProfile: Awaited<ReturnType<typeof prepareCodexObservabilityProfile>> | null = null;
|
|
let observabilityPreparationFailed = false;
|
|
const runSshHostConfigurationCommand = async (command: string) => {
|
|
const result = await runAdapterExecutionTargetShellCommand(runId, executionTarget, command, { cwd: "/", env: {}, timeoutSec: 15 });
|
|
if (result.exitCode !== 0 || result.timedOut) throw new Error("Cannot read remote Codex configuration");
|
|
return result;
|
|
};
|
|
try {
|
|
if (useSshHostAuth) {
|
|
stagedCodexHomeDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-codex-host-runtime-"));
|
|
sshHostHome = await readCodexSshHostHome({
|
|
configuredHome: asString(envConfig.CODEX_HOME, "") || undefined,
|
|
run: runSshHostConfigurationCommand,
|
|
});
|
|
await fs.writeFile(path.join(stagedCodexHomeDir, "config.toml"), sshHostHome.config, { mode: 0o600 });
|
|
await fs.writeFile(path.join(stagedCodexHomeDir, ".paperclip-native-config-before"), sshHostHome.config, { mode: 0o600 });
|
|
}
|
|
const runtimeConfigurationHome = stagedCodexHomeDir ?? effectiveCodexHome;
|
|
if (ctx.observability) {
|
|
if (useSshHostAuth || isManagedCodexHomePath(process.env, agent.companyId, effectiveCodexHome)) {
|
|
try {
|
|
const sourceProfile = selectedCodexProfile(buildCodexExecArgs(config).args);
|
|
if (sshHostHome && sourceProfile) {
|
|
const content = await readCodexSshHostProfile({ home: sshHostHome.home, profile: sourceProfile, run: runSshHostConfigurationCommand });
|
|
await fs.writeFile(path.join(runtimeConfigurationHome, `${sourceProfile}.config.toml`), content, { mode: 0o600 });
|
|
}
|
|
observabilityProfile = await prepareCodexObservabilityProfile({ home: runtimeConfigurationHome, runId,
|
|
launch: ctx.observability, sourceProfile });
|
|
} catch {
|
|
observabilityPreparationFailed = true;
|
|
await onLog("stderr", "[paperclip] Company observability configuration could not be prepared; execution continues with export disabled.\n");
|
|
}
|
|
} else await onLog("stderr", "[paperclip] Company observability is unavailable for a caller-owned Codex home.\n");
|
|
}
|
|
for (const note of preparedRuntimeConfig.notes) {
|
|
await onLog("stdout", `[paperclip] ${note}\n`);
|
|
}
|
|
const paperclipBaseEnv = buildPaperclipEnv(agent, ctx.agentIdentity);
|
|
const runtimeMcpGateways = (ctx.runtimeMcp?.getServers() ?? []).map((server) => ({
|
|
name: server.name,
|
|
endpointPath: server.url,
|
|
bearerToken: server.token,
|
|
}));
|
|
const managedMcpGateways = mergeManagedCodexMcpGateways(
|
|
runtimeMcpGateways,
|
|
managedMcpGatewaysFromContext(context),
|
|
);
|
|
const managedMcp = await writeManagedCodexMcpConfig({
|
|
codexHome: runtimeConfigurationHome,
|
|
apiBaseUrl: paperclipBaseEnv.PAPERCLIP_API_URL,
|
|
gateways: managedMcpGateways,
|
|
});
|
|
if (managedMcpGateways.length > 0) {
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Wrote ${managedMcpGateways.length} managed MCP gateway(s) into Codex config "${managedMcp.configPath}".\n`,
|
|
);
|
|
}
|
|
for (const warning of managedMcp.warnings) {
|
|
await onLog("stderr", `[paperclip] ${warning}\n`);
|
|
}
|
|
// Inject skills into the same CODEX_HOME that Codex will actually run with
|
|
// (managed home in the default case, or an explicit override from adapter config).
|
|
const codexSkillsDir = resolveCodexSkillsDir(runtimeConfigurationHome);
|
|
await ensureCodexSkillsInjected(
|
|
onLog,
|
|
{
|
|
skillsHome: codexSkillsDir,
|
|
skillsEntries: codexSkillEntries,
|
|
desiredSkillNames,
|
|
},
|
|
);
|
|
const timeoutSec = resolveAdapterExecutionTargetTimeoutSec(
|
|
executionTarget,
|
|
asNumber(config.timeoutSec, 0),
|
|
);
|
|
const graceSec = asNumber(config.graceSec, 20);
|
|
let effectiveExecutionCwd = targetWorkspaceRealization?.mode === "in_place"
|
|
? targetWorkspaceRealization.authoritativeRoot
|
|
: adapterExecutionTargetRemoteCwd(executionTarget, cwd);
|
|
const preparedExecutionTargetRuntime = executionTargetIsRemote
|
|
? await (async () => {
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Syncing ${targetWorkspaceRealization?.mode === "in_place" ? "CODEX_HOME" : "workspace and CODEX_HOME"} to ${describeAdapterExecutionTarget(executionTarget)}.\n`,
|
|
);
|
|
// Stage only the files Codex actually needs into a curated temp dir and
|
|
// ship THAT as the `home` asset, instead of the whole managed
|
|
// CODEX_HOME + a name denylist. Staged AFTER the config.toml rewrites
|
|
// (provider merge + MCP block splice above) and skills injection, so the
|
|
// staged config.toml/skills reflect their final state. Symlinks (incl.
|
|
// the single-use `auth.json`) are dereferenced to bytes. This drops the
|
|
// large runtime state (`sessions/`, `*.sqlite`, `plugins/`, …) that the
|
|
// 4-name denylist missed and that a sandbox run never needs.
|
|
if (!useSshHostAuth) stagedCodexHomeDir = await stageCodexHomeForSync(effectiveCodexHome, { runId, additionalFiles: observabilityProfile ? [observabilityProfile.filename] : [] });
|
|
const prepared = await prepareAdapterExecutionTargetRuntime({
|
|
privateRuntime: useSshHostAuth || Boolean(config.managedAiConnection),
|
|
runId,
|
|
target: executionTarget,
|
|
adapterKey: "codex",
|
|
timeoutSec,
|
|
workspaceLocalDir: cwd,
|
|
workspaceRemoteDir:
|
|
targetWorkspaceRealization?.mode === "in_place"
|
|
? targetWorkspaceRealization.authoritativeRoot
|
|
: undefined,
|
|
syncWorkspace: targetWorkspaceRealization?.mode !== "in_place",
|
|
installCommand: SANDBOX_INSTALL_COMMAND,
|
|
detectCommand: command,
|
|
onProgress: (line) => onLog("stdout", line),
|
|
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
assets: stagedCodexHomeDir ? [
|
|
{
|
|
key: "home",
|
|
localDir: stagedCodexHomeDir,
|
|
followSymlinks: true,
|
|
// Inbound (host→sandbox) auth-merge contribution: stages the two
|
|
// merge scripts and runs the merge-extract command so a sandbox
|
|
// that already carries a Codex `auth.json` keeps whichever
|
|
// credential is newer. The sandbox runtime core stays adapter-
|
|
// agnostic — it just invokes this generic `provision` seam.
|
|
provision: useSshHostAuth ? undefined : buildCodexAuthInboundProvision(),
|
|
// Outbound (sandbox→host) auth copy-back contribution: at
|
|
// teardown, read the sandbox's `auth.json` and — guarded by the
|
|
// same direction-agnostic decision predicate under a directory
|
|
// lock — atomically install it onto the shared host credential
|
|
// when it is a strictly-newer same-identity subscription copy.
|
|
// The sandbox core stays adapter-agnostic; it just awaits this
|
|
// generic `restore` seam per asset before destroying the sandbox.
|
|
// Target is the shared symlink SOURCE (what managed homes point
|
|
// `auth.json` at), not the in-sandbox symlink.
|
|
restore: useSshHostAuth ? async ({ assetDir }) => {
|
|
const result = await runAdapterExecutionTargetShellCommand(runId, executionTarget,
|
|
`rm -rf -- ${shellQuote(assetDir)}${sshHostProfilePath ? ` && rm -f -- ${shellQuote(sshHostProfilePath)}` : ""}`, { cwd: "/", env: {}, timeoutSec: 15 });
|
|
if (result.exitCode !== 0 || result.timedOut) throw new Error("Cannot remove remote Codex runtime files");
|
|
} : async ({ assetDir, readFile }) => {
|
|
try { await copyBackCodexAuth({
|
|
readSandboxAuth: () => readFile(path.posix.join(sshSessionState?.home ?? assetDir, "auth.json")),
|
|
hostAuthPath: path.join(config.managedAiConnection ? effectiveCodexHome : resolveSharedCodexHomeDir(process.env), "auth.json"),
|
|
log: (line) => onLog("stdout", `${line}\n`),
|
|
// Additive cache write (sandbox to host): also cache the
|
|
// sandbox subscription credential in its per-identity slot,
|
|
// keyed by the real `account_id`. Company-scoped root; the
|
|
// helper ensures the slot directory private and containment-
|
|
// guarded. The off-switch (default on) is read inside.
|
|
resolveCacheEntryPath: config.managedAiConnection ? undefined : (accountId) =>
|
|
ensureCodexAuthCacheEntryDir(process.env, accountId, agent.companyId),
|
|
env: process.env,
|
|
}); } finally { await sshSessionState?.cleanup(); }
|
|
},
|
|
// No `exclude` denylist: `stagedCodexHomeDir` already contains
|
|
// ONLY the allowlisted files (auth/config/skills), so there is
|
|
// nothing to filter out.
|
|
},
|
|
] : [],
|
|
});
|
|
try {
|
|
if (sshHostHome) {
|
|
const result = await runAdapterExecutionTargetShellCommand(runId, executionTarget,
|
|
buildCodexSshHostRuntimeInstall({ ...sshHostHome, assetDir: prepared.assetDirs.home!, profileFilename: observabilityProfile?.filename }),
|
|
{ cwd: "/", env: {}, timeoutSec: 15 });
|
|
if (result.exitCode !== 0 || result.timedOut) throw new Error("Cannot install remote Codex runtime configuration");
|
|
sshHostProfilePath = observabilityProfile ? path.posix.join(sshHostHome.home, observabilityProfile.filename) : null;
|
|
}
|
|
} catch (error) {
|
|
try { await prepared.restoreWorkspace(line => onLog("stdout", line)); }
|
|
catch (cleanup) { throw new AggregateError([error, cleanup], "Codex SSH setup and cleanup failed"); }
|
|
throw error;
|
|
}
|
|
return prepared;
|
|
})()
|
|
: null;
|
|
if (preparedExecutionTargetRuntime?.workspaceRemoteDir) {
|
|
effectiveExecutionCwd = preparedExecutionTargetRuntime.workspaceRemoteDir;
|
|
}
|
|
const runtimeExecutionTarget = overrideAdapterExecutionTargetRemoteCwd(executionTarget, effectiveExecutionCwd);
|
|
const executionTargetIsSandbox =
|
|
runtimeExecutionTarget?.kind === "remote" && runtimeExecutionTarget.transport === "sandbox";
|
|
const restoreRemoteWorkspace = preparedExecutionTargetRuntime
|
|
? () => preparedExecutionTargetRuntime.restoreWorkspace((line) => onLog("stdout", line))
|
|
: null;
|
|
let paperclipBridge: Awaited<ReturnType<typeof startAdapterExecutionTargetPaperclipBridge>> = null;
|
|
let executionError: unknown = null;
|
|
try {
|
|
let remoteCodexHome = executionTargetIsRemote && !useSshHostAuth
|
|
? preparedExecutionTargetRuntime?.assetDirs.home ??
|
|
path.posix.join(effectiveExecutionCwd, ".paperclip-runtime", "codex", "home")
|
|
: null;
|
|
if (executionTarget?.kind === "remote" && executionTarget.transport === "ssh" && executionTarget.spec.useHostAuth === false
|
|
&& config.managedAiConnection && targetWorkspaceRealization?.mode === "in_place" && remoteCodexHome) {
|
|
const account = parseObject(config.managedAiConnection);
|
|
const identity = asString(account.sessionIdentity, asString(account.identity, ""));
|
|
if (!identity) throw new Error("Managed SSH Codex execution requires an account identity");
|
|
sshSessionState = await prepareCodexSshSessionState({
|
|
remoteRoot: executionTarget.spec.remoteWorkspacePath, companyId: agent.companyId, agentId: agent.id,
|
|
accountIdentity: identity, executionIdentity: adapterExecutionTargetSessionIdentity(runtimeExecutionTarget),
|
|
runId, saved: parseObject(runtime.sessionParams), stagedHome: remoteCodexHome,
|
|
run: async command => {
|
|
const result = await runAdapterExecutionTargetShellCommand(runId, runtimeExecutionTarget, command, { cwd: effectiveExecutionCwd, env: {}, timeoutSec: 15 });
|
|
if (result.exitCode !== 0 || result.timedOut) throw new Error("Cannot prepare or clean up SSH Codex conversation state");
|
|
},
|
|
});
|
|
remoteCodexHome = sshSessionState.home;
|
|
}
|
|
await emitSandboxAuthPrecedenceWarningIfNeeded({
|
|
runId,
|
|
target: runtimeExecutionTarget,
|
|
cwd: effectiveExecutionCwd,
|
|
configuredApiKey: Boolean(configuredOpenAiApiKey),
|
|
hostAuthJson: await codexHomeHasUsableAuth(effectiveCodexHome),
|
|
onLog,
|
|
onEvent,
|
|
});
|
|
const env: Record<string, string> = { ...paperclipBaseEnv };
|
|
env.PAPERCLIP_RUN_ID = runId;
|
|
const wakeTaskId =
|
|
(typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
|
|
(typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim()) ||
|
|
null;
|
|
const wakeReason =
|
|
typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0
|
|
? context.wakeReason.trim()
|
|
: null;
|
|
const wakeCommentId =
|
|
(typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim()) ||
|
|
(typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim()) ||
|
|
null;
|
|
const approvalId =
|
|
typeof context.approvalId === "string" && context.approvalId.trim().length > 0
|
|
? context.approvalId.trim()
|
|
: null;
|
|
const approvalStatus =
|
|
typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0
|
|
? context.approvalStatus.trim()
|
|
: null;
|
|
const linkedIssueIds = Array.isArray(context.issueIds)
|
|
? context.issueIds.filter((value): value is string => typeof value === "string" && value.trim().length > 0)
|
|
: [];
|
|
const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
|
|
if (wakeTaskId) {
|
|
env.PAPERCLIP_TASK_ID = wakeTaskId;
|
|
}
|
|
if (issueWorkMode) {
|
|
env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
|
|
}
|
|
if (wakeReason) {
|
|
env.PAPERCLIP_WAKE_REASON = wakeReason;
|
|
}
|
|
if (wakeCommentId) {
|
|
env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
|
|
}
|
|
if (approvalId) {
|
|
env.PAPERCLIP_APPROVAL_ID = approvalId;
|
|
}
|
|
if (approvalStatus) {
|
|
env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
|
|
}
|
|
if (linkedIssueIds.length > 0) {
|
|
env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
|
|
}
|
|
refreshPaperclipWorkspaceEnvForExecution({
|
|
env,
|
|
envConfig,
|
|
workspaceCwd: effectiveWorkspaceCwd,
|
|
workspaceSource,
|
|
workspaceStrategy,
|
|
workspaceId,
|
|
workspaceRepoUrl,
|
|
workspaceRepoRef,
|
|
workspaceBranch,
|
|
workspaceWorktreePath,
|
|
workspaceHints,
|
|
agentHome,
|
|
executionTargetIsRemote,
|
|
executionCwd: effectiveExecutionCwd,
|
|
});
|
|
if (targetWorkspaceRealization) {
|
|
env.PAPERCLIP_WORKSPACE_REALIZATION_MODE = targetWorkspaceRealization.mode;
|
|
env.PAPERCLIP_WORKSPACE_AUTHORITATIVE_ROOT = targetWorkspaceRealization.authoritativeRoot;
|
|
}
|
|
if (runtimeServiceIntents.length > 0) {
|
|
env.PAPERCLIP_RUNTIME_SERVICE_INTENTS_JSON = JSON.stringify(runtimeServiceIntents);
|
|
}
|
|
if (runtimeServices.length > 0) {
|
|
env.PAPERCLIP_RUNTIME_SERVICES_JSON = JSON.stringify(runtimeServices);
|
|
}
|
|
if (runtimePrimaryUrl) {
|
|
env.PAPERCLIP_RUNTIME_PRIMARY_URL = runtimePrimaryUrl;
|
|
}
|
|
if (executionTarget?.kind === "remote" && executionTarget.transport === "ssh" && executionTarget.spec.useHostAuth === false && config.managedAiConnection && preparedExecutionTargetRuntime?.runtimeRootDir) Object.assign(env, managedRemoteHomeEnvironment(preparedExecutionTargetRuntime.runtimeRootDir));
|
|
if (useSshHostAuth) {
|
|
if (!sshHostHome) throw new Error("Remote Codex home was not resolved");
|
|
env.CODEX_HOME = sshHostHome.home;
|
|
} else env.CODEX_HOME = remoteCodexHome ?? effectiveCodexHome;
|
|
if (ctx.observability && (observabilityProfile || observabilityPreparationFailed)) applyObservabilityEnvironment(env, ctx.observability);
|
|
if (authToken) {
|
|
env.PAPERCLIP_API_KEY = authToken;
|
|
}
|
|
if (executionTargetIsRemote && adapterExecutionTargetUsesPaperclipBridge(runtimeExecutionTarget)) {
|
|
paperclipBridge = await startAdapterExecutionTargetPaperclipBridge({
|
|
runId,
|
|
target: runtimeExecutionTarget,
|
|
enableSandboxDuplexBridge: adapterExecutionTargetEnablesSandboxDuplexBridge(runtimeExecutionTarget),
|
|
duplexObservabilityRecorder: adapterExecutionTargetDuplexObservabilityRecorder(runtimeExecutionTarget),
|
|
runtimeRootDir: preparedExecutionTargetRuntime?.runtimeRootDir,
|
|
adapterKey: "codex",
|
|
timeoutSec,
|
|
hostApiToken: env.PAPERCLIP_API_KEY,
|
|
onLog,
|
|
});
|
|
if (paperclipBridge) {
|
|
Object.assign(env, paperclipBridge.env);
|
|
}
|
|
}
|
|
const effectiveEnv = Object.fromEntries(
|
|
Object.entries({ ...process.env, ...env }).filter(
|
|
(entry): entry is [string, string] => typeof entry[1] === "string",
|
|
),
|
|
);
|
|
const managedBilling = resolveManagedOpenAiBilling(config.managedAiRouting);
|
|
const billingType = managedBilling?.billingType ?? resolveCodexBillingType(effectiveEnv);
|
|
const biller = managedBilling?.biller ?? resolveCodexBiller(effectiveEnv, billingType);
|
|
const networkScope = parseLocalProcessNetworkScope(config.networkScope);
|
|
const filesystemScope = parseLocalProcessFilesystemScope(config.filesystemScope);
|
|
const localProcessSandbox: LocalProcessSandboxOptions | null =
|
|
(filesystemScope || networkScope) && !executionTargetIsRemote
|
|
? {
|
|
workspaceDir: effectiveExecutionCwd,
|
|
filesystemScope,
|
|
managedPaths: [{ path: effectiveCodexHome, access: "rw" }],
|
|
extraPaths: parseLocalProcessSandboxExtraPaths(config.filesystemExtraPaths),
|
|
pathAliases: targetWorkspaceRealization?.mode === "copy"
|
|
? targetWorkspaceRealization.pathAliases
|
|
: [],
|
|
outboundRestorePaths: targetWorkspaceRealization?.outboundRestorePaths ?? [],
|
|
homeDir: filesystemScope ? effectiveCodexHome : null,
|
|
networkScope,
|
|
networkAllowlist: parseLocalProcessNetworkAllowlist(config.networkAllowlist),
|
|
networkTrustedUrls: [
|
|
paperclipBaseEnv.PAPERCLIP_API_URL,
|
|
...runtimeMcpGateways.map((gateway) => gateway.endpointPath),
|
|
],
|
|
command: asString(config.filesystemSandboxCommand, "bwrap"),
|
|
}
|
|
: null;
|
|
if (localProcessSandbox) {
|
|
const scopes = [filesystemScope ? "workspace filesystem" : null, networkScope ? `${networkScope} network` : null]
|
|
.filter(Boolean)
|
|
.join(" and ");
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Confining Codex with ${scopes} scope.\n`,
|
|
);
|
|
}
|
|
const runtimeEnv = Object.fromEntries(
|
|
Object.entries(ensurePathInEnv(effectiveEnv)).filter(
|
|
(entry): entry is [string, string] => typeof entry[1] === "string",
|
|
),
|
|
);
|
|
await ensureAdapterExecutionTargetRuntimeCommandInstalled({
|
|
runId,
|
|
target: executionTarget,
|
|
installCommand: ctx.runtimeCommandSpec?.installCommand,
|
|
detectCommand: ctx.runtimeCommandSpec?.detectCommand,
|
|
cwd,
|
|
env: runtimeEnv,
|
|
timeoutSec,
|
|
graceSec,
|
|
onLog,
|
|
});
|
|
await ensureAdapterExecutionTargetCommandResolvable(command, executionTarget, cwd, runtimeEnv);
|
|
const resolvedCommand = await resolveAdapterExecutionTargetCommandForLogs(command, executionTarget, cwd, runtimeEnv);
|
|
if (observabilityProfile) {
|
|
let qualified = false;
|
|
try {
|
|
const version = await runAdapterExecutionTargetProcess(`${runId}-observability-version`, executionTarget, command, ["--version"], {
|
|
cwd, env: runtimeEnv, timeoutSec: 5, graceSec: 1, onLog: async () => {},
|
|
});
|
|
qualified = version.exitCode === 0 && /^codex-cli 0\.170\.0\s*$/.test(version.stdout.trim());
|
|
} catch { /* Export qualification must not block baseline work. */ }
|
|
if (!qualified) {
|
|
await observabilityProfile.cleanup();
|
|
observabilityProfile = null;
|
|
await onLog("stderr", "[paperclip] Company observability was not applied: this Codex executable is not the qualified 0.170.0 release.\n");
|
|
}
|
|
}
|
|
const loggedEnv = buildInvocationEnvForLogs(env, {
|
|
runtimeEnv,
|
|
includeRuntimeKeys: ["HOME"],
|
|
resolvedCommand,
|
|
});
|
|
|
|
const monitorResolution = resolveCodexInactivityTimeout(config.outputInactivityTimeoutMs);
|
|
if (monitorResolution.mode === "disabled") {
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Codex output inactivity monitor is DISABLED via adapterConfig.outputInactivityTimeoutMs=null. Hung codex runs will only be detected by the platform-level silent-run safety net.\n`,
|
|
);
|
|
} else if (monitorResolution.mode === "default" && "reason" in monitorResolution) {
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Ignoring non-positive adapterConfig.outputInactivityTimeoutMs; falling back to default ${monitorResolution.timeoutMs}ms.\n`,
|
|
);
|
|
}
|
|
const runtimeSessionParams = parseObject(runtime.sessionParams);
|
|
const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? "");
|
|
const runtimeSessionCwd = asString(runtimeSessionParams.cwd, "");
|
|
const runtimeRemoteExecution = parseObject(runtimeSessionParams.remoteExecution);
|
|
const canResumeSession =
|
|
runtimeSessionId.length > 0 &&
|
|
(!sshSessionState || sshSessionState.canResume) &&
|
|
(runtimeSessionCwd.length === 0 || path.resolve(runtimeSessionCwd) === path.resolve(effectiveExecutionCwd)) &&
|
|
adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget);
|
|
const codexTransientFallbackMode = readCodexTransientFallbackMode(context);
|
|
const forceSaferInvocation = fallbackModeUsesSaferInvocation(codexTransientFallbackMode);
|
|
const forceFreshSession = fallbackModeUsesFreshSession(codexTransientFallbackMode);
|
|
const sessionId = canResumeSession && !forceFreshSession ? runtimeSessionId : null;
|
|
if (executionTargetIsRemote && runtimeSessionId && !canResumeSession) {
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Codex session "${runtimeSessionId}" does not match the current remote execution identity and will not be resumed in "${effectiveExecutionCwd}". Starting a fresh remote session.\n`,
|
|
);
|
|
} else if (runtimeSessionId && !canResumeSession) {
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Codex session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${effectiveExecutionCwd}".\n`,
|
|
);
|
|
}
|
|
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
|
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
|
|
let instructionsPrefix = "";
|
|
if (instructionsFilePath) {
|
|
try {
|
|
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
|
|
instructionsPrefix =
|
|
`${instructionsContents}\n\n` +
|
|
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
|
|
`Resolve any relative file references from ${instructionsDir}.\n\n`;
|
|
} catch (err) {
|
|
const reason = err instanceof Error ? err.message : String(err);
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`,
|
|
);
|
|
}
|
|
}
|
|
const repoAgentsNote =
|
|
"Codex exec automatically applies repo-scoped AGENTS.md instructions from the current workspace; Paperclip does not currently suppress that discovery.";
|
|
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
|
const templateData = {
|
|
agentId: agent.id,
|
|
companyId: agent.companyId,
|
|
runId,
|
|
company: { id: agent.companyId },
|
|
agent,
|
|
run: { id: runId, source: "on_demand" },
|
|
context,
|
|
};
|
|
const continuationSummary = parseObject(context.paperclipContinuationSummary);
|
|
const continuationSummaryBody = asString(continuationSummary.body, "").trim() || null;
|
|
const codexFallbackHandoffNote =
|
|
forceFreshSession
|
|
? buildCodexTransientHandoffNote({
|
|
previousSessionId: runtimeSessionId || runtime.sessionId || null,
|
|
fallbackMode: codexTransientFallbackMode ?? "fresh_session",
|
|
continuationSummaryBody,
|
|
})
|
|
: "";
|
|
const runAttempt = async (resumeSessionId: string | null) => {
|
|
await hydrateFreshSessionHandoff(ctx, { resumedSession: Boolean(resumeSessionId) });
|
|
const renderedBootstrapPrompt =
|
|
!resumeSessionId && bootstrapPromptTemplate.trim().length > 0
|
|
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
|
: "";
|
|
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
|
|
resumedSession: Boolean(resumeSessionId),
|
|
includeCommunicationGuidance: false,
|
|
});
|
|
const shouldUseResumeDeltaPrompt = Boolean(resumeSessionId) && wakePrompt.length > 0;
|
|
const promptInstructionsPrefix = shouldUseResumeDeltaPrompt ? "" : instructionsPrefix;
|
|
const commandNotes = (() => {
|
|
if (!instructionsFilePath) {
|
|
const notes = [repoAgentsNote];
|
|
if (forceSaferInvocation) {
|
|
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
|
|
}
|
|
if (forceFreshSession) {
|
|
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
|
|
}
|
|
return notes;
|
|
}
|
|
if (instructionsPrefix.length > 0) {
|
|
if (shouldUseResumeDeltaPrompt) {
|
|
const notes = [
|
|
`Loaded agent instructions from ${instructionsFilePath}`,
|
|
"Skipped stdin instruction reinjection because an existing Codex session is being resumed with a wake delta.",
|
|
repoAgentsNote,
|
|
];
|
|
if (forceSaferInvocation) {
|
|
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
|
|
}
|
|
if (forceFreshSession) {
|
|
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
|
|
}
|
|
return notes;
|
|
}
|
|
const notes = [
|
|
`Loaded agent instructions from ${instructionsFilePath}`,
|
|
`Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).`,
|
|
repoAgentsNote,
|
|
];
|
|
if (forceSaferInvocation) {
|
|
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
|
|
}
|
|
if (forceFreshSession) {
|
|
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
|
|
}
|
|
return notes;
|
|
}
|
|
const notes = [
|
|
`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`,
|
|
repoAgentsNote,
|
|
];
|
|
if (forceSaferInvocation) {
|
|
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
|
|
}
|
|
if (forceFreshSession) {
|
|
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
|
|
}
|
|
return notes;
|
|
})();
|
|
if (executionTargetIsSandbox) {
|
|
commandNotes.push(
|
|
"Added --skip-git-repo-check for sandbox execution because Codex requires an explicit trust bypass in headless remote workspaces.",
|
|
);
|
|
}
|
|
if (preparedRuntimeConfig.notes.length > 0) {
|
|
commandNotes.unshift(...preparedRuntimeConfig.notes);
|
|
}
|
|
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
|
|
? ""
|
|
: renderTemplate(promptTemplate, templateData);
|
|
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
|
const prompt = joinPromptSections([
|
|
promptInstructionsPrefix,
|
|
renderedBootstrapPrompt,
|
|
selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
|
|
wakePrompt,
|
|
codexFallbackHandoffNote,
|
|
sessionHandoffNote,
|
|
taskContextNote,
|
|
renderedPrompt,
|
|
]);
|
|
const promptMetrics = {
|
|
promptChars: prompt.length,
|
|
instructionsChars: promptInstructionsPrefix.length,
|
|
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
|
wakePromptChars: wakePrompt.length,
|
|
sessionHandoffChars: sessionHandoffNote.length,
|
|
taskContextChars: taskContextNote.length,
|
|
heartbeatPromptChars: renderedPrompt.length,
|
|
};
|
|
const execArgs = buildCodexExecArgs(
|
|
forceSaferInvocation ? { ...config, fastMode: false } : config,
|
|
{
|
|
resumeSessionId,
|
|
skipGitRepoCheck: executionTargetIsSandbox,
|
|
networkAccess: env.PAPERCLIP_RUNNER_NETWORK_ACCESS !== "disabled",
|
|
},
|
|
);
|
|
const args = execArgs.args;
|
|
if (observabilityProfile) replaceCodexProfileArgs(args, observabilityProfile.name);
|
|
else if (observabilityPreparationFailed) disableCodexObservabilityArgs(args);
|
|
const pricingContext = execArgs.fastModeApplied ? { serviceTier: "fast" } : undefined;
|
|
const shellKeys = codexShellEnvironmentKeys(env, envConfigStrings, Boolean(ctx.agentIdentity));
|
|
args.unshift("-c", "features.shell_snapshot=false", "-c", 'shell_environment_policy.inherit="all"', "-c", "shell_environment_policy.ignore_default_excludes=true",
|
|
"-c", `shell_environment_policy.include_only=${JSON.stringify(shellKeys)}`);
|
|
const commandNotesWithFastMode =
|
|
execArgs.fastModeIgnoredReason == null
|
|
? commandNotes
|
|
: [...commandNotes, execArgs.fastModeIgnoredReason];
|
|
if (onMeta) {
|
|
await onMeta({
|
|
adapterType: "codex_local",
|
|
command: resolvedCommand,
|
|
cwd: effectiveExecutionCwd,
|
|
commandNotes: commandNotesWithFastMode,
|
|
commandArgs: args.map((value, idx) => {
|
|
if (idx === args.length - 1 && value !== "-") return `<prompt ${prompt.length} chars>`;
|
|
return value;
|
|
}),
|
|
env: loggedEnv,
|
|
prompt,
|
|
promptMetrics,
|
|
context,
|
|
});
|
|
}
|
|
|
|
let monitorFired = false;
|
|
let monitorTerminationSignal: NodeJS.Signals | null = null;
|
|
let monitorElapsedMs = 0;
|
|
let monitorTimeoutMs = 0;
|
|
let killTarget: { pid: number | null; processGroupId: number | null } | null = null;
|
|
let sigkillTimer: ReturnType<typeof setTimeout> | null = null;
|
|
let monitorLogPromise: Promise<unknown> | null = null;
|
|
const processActivityMonitor: { current: CodexProcessActivityMonitorHandle | null } = { current: null };
|
|
const resolvedMonitorTimeoutMs = monitorResolution.mode === "disabled" ? null : monitorResolution.timeoutMs;
|
|
|
|
const monitor =
|
|
monitorResolution.mode === "disabled"
|
|
? null
|
|
: createCodexOutputInactivityMonitor({
|
|
timeoutMs: monitorResolution.timeoutMs,
|
|
onFire: (state) => {
|
|
monitorFired = true;
|
|
monitorElapsedMs = (state.firedAt ?? Date.now()) - state.lastEventAt;
|
|
monitorTimeoutMs = monitorResolution.timeoutMs;
|
|
const message = formatOutputInactivityMonitorErrorMessage(monitorElapsedMs);
|
|
const elapsedSec = Math.round(monitorElapsedMs / 1000);
|
|
const timeoutSecLabel = Math.round(monitorResolution.timeoutMs / 1000);
|
|
const logLine =
|
|
`[paperclip] adapter.invoke ${message}; ` +
|
|
`timeoutMs=${monitorResolution.timeoutMs} elapsedSinceLastEventMs=${monitorElapsedMs} ` +
|
|
`outputChunkCount=${state.outputChunkCount} outputBytes=${state.outputBytes} ` +
|
|
`parsedEvents=${state.parsedEventCount} processActivityCount=${state.processActivityCount} ` +
|
|
`(timeout=${timeoutSecLabel}s elapsed=${elapsedSec}s); ` +
|
|
`terminating codex child via SIGTERM (5s grace, then SIGKILL).\n`;
|
|
// Issue the log without awaiting on the kill hot path, but capture
|
|
// the promise so the surrounding try/finally can await flush before
|
|
// the run resolves. Without this the diagnostic that explains the
|
|
// kill could be dropped if the child exits faster than onLog flushes.
|
|
monitorLogPromise = Promise.resolve(onLog("stderr", logLine)).catch(() => {});
|
|
const target = killTarget;
|
|
if (!target || (target.pid == null && target.processGroupId == null)) {
|
|
return;
|
|
}
|
|
const sentSig = signalCodexChild(target, "SIGTERM");
|
|
if (sentSig) monitorTerminationSignal = "SIGTERM";
|
|
sigkillTimer = setTimeout(() => {
|
|
sigkillTimer = null;
|
|
const stillSent = signalCodexChild(target, "SIGKILL");
|
|
if (stillSent) monitorTerminationSignal = "SIGKILL";
|
|
}, CODEX_OUTPUT_INACTIVITY_MONITOR_SIGTERM_GRACE_MS);
|
|
if (typeof (sigkillTimer as { unref?: () => void }).unref === "function") {
|
|
(sigkillTimer as { unref: () => void }).unref();
|
|
}
|
|
},
|
|
});
|
|
|
|
const wrappedOnSpawn = async (meta: { pid: number; processGroupId: number | null; startedAt: string }) => {
|
|
killTarget = { pid: meta.pid ?? null, processGroupId: meta.processGroupId };
|
|
if (monitor && resolvedMonitorTimeoutMs !== null && !executionTargetIsRemote) {
|
|
processActivityMonitor.current = createCodexProcessActivityMonitor({
|
|
pid: meta.pid,
|
|
processGroupId: meta.processGroupId,
|
|
intervalMs: Math.min(
|
|
CODEX_PROCESS_ACTIVITY_POLL_INTERVAL_MS,
|
|
Math.max(1_000, Math.floor(resolvedMonitorTimeoutMs / 4)),
|
|
),
|
|
onActivity: () => monitor.noteProcessActivity(),
|
|
});
|
|
}
|
|
if (onSpawn) {
|
|
await onSpawn(meta);
|
|
}
|
|
};
|
|
|
|
const consumeAccounting = createCodexJsonlParser();
|
|
const accountingLog = createUsageCheckpointLog(onLog, ctx.onUsage, stdout => {
|
|
const parsed = consumeAccounting(stdout);
|
|
return { usage: parsed.usageReported ? parsed.usage : undefined, costStatus: parsed.usageComplete ? undefined : "unpriced", usageBasis: "per_run", provider: "openai", biller, billingType, model, pricingContext, costUsd: null, complete: parsed.usageComplete };
|
|
});
|
|
try {
|
|
const proc = await runAdapterExecutionTargetProcess(runId, runtimeExecutionTarget, command, args, {
|
|
onProcessStopped: providerStop.beginInvocation(),
|
|
cwd,
|
|
env,
|
|
stdin: prompt,
|
|
timeoutSec,
|
|
graceSec,
|
|
onSpawn: wrappedOnSpawn,
|
|
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
onLog: async (stream, chunk) => {
|
|
monitor?.noteOutputChunk(stream, chunk);
|
|
if (stream === "stdout") {
|
|
await accountingLog(stream, chunk);
|
|
return;
|
|
}
|
|
const cleaned = stripCodexRolloutNoise(chunk);
|
|
if (!cleaned.trim()) return;
|
|
await onLog(stream, cleaned);
|
|
},
|
|
runLogTail: paperclipBridge?.runLogTail,
|
|
settleRunDisposition: paperclipBridge?.settleRunDisposition,
|
|
localProcessSandbox,
|
|
});
|
|
await accountingLog.flush();
|
|
const cleanedStderr = stripCodexRolloutNoise(proc.stderr);
|
|
return {
|
|
proc: {
|
|
...proc,
|
|
stderr: cleanedStderr,
|
|
},
|
|
rawStderr: proc.stderr,
|
|
parsed: parseCodexJsonl(proc.stdout),
|
|
pricingContext,
|
|
monitor: monitorFired
|
|
? {
|
|
fired: true as const,
|
|
terminationSignal: monitorTerminationSignal,
|
|
elapsedMsSinceLastEvent: monitorElapsedMs,
|
|
timeoutMs: monitorTimeoutMs,
|
|
}
|
|
: { fired: false as const },
|
|
};
|
|
} finally {
|
|
processActivityMonitor.current?.stop();
|
|
monitor?.stop();
|
|
if (sigkillTimer) {
|
|
clearTimeout(sigkillTimer);
|
|
sigkillTimer = null;
|
|
}
|
|
if (monitorLogPromise) {
|
|
await monitorLogPromise;
|
|
monitorLogPromise = null;
|
|
}
|
|
}
|
|
};
|
|
|
|
const toResult = (
|
|
attempt: {
|
|
proc: { exitCode: number | null; signal: string | null; timedOut: boolean; stdout: string; stderr: string; errorCode?: string | null };
|
|
rawStderr: string;
|
|
parsed: ReturnType<typeof parseCodexJsonl>;
|
|
pricingContext?: AdapterExecutionResult["pricingContext"];
|
|
monitor?:
|
|
| { fired: false }
|
|
| { fired: true; terminationSignal: NodeJS.Signals | null; elapsedMsSinceLastEvent: number; timeoutMs: number };
|
|
},
|
|
clearSessionOnMissingSession = false,
|
|
isRetry = false,
|
|
): AdapterExecutionResult => {
|
|
if (attempt.monitor?.fired) {
|
|
const errorMessage = formatOutputInactivityMonitorErrorMessage(attempt.monitor.elapsedMsSinceLastEvent);
|
|
return {
|
|
exitCode: null,
|
|
signal: attempt.monitor.terminationSignal ?? attempt.proc.signal,
|
|
timedOut: false,
|
|
usageComplete: attempt.parsed.usageComplete,
|
|
costStatus: attempt.parsed.usageComplete ? undefined : "unpriced",
|
|
errorMessage,
|
|
errorCode: "codex_output_inactivity_monitor",
|
|
errorFamily: null,
|
|
usage: attempt.parsed.usageReported ? attempt.parsed.usage : undefined,
|
|
usageBasis: attempt.parsed.usageBasis,
|
|
sessionId: null,
|
|
sessionParams: null,
|
|
sessionDisplayId: null,
|
|
provider: "openai",
|
|
biller,
|
|
model,
|
|
billingType,
|
|
costUsd: null,
|
|
pricingContext: attempt.pricingContext,
|
|
resultJson: {
|
|
stdout: attempt.proc.stdout,
|
|
stderr: attempt.proc.stderr,
|
|
outputInactivityMonitor: {
|
|
kind: "output_inactivity",
|
|
timeoutMs: attempt.monitor.timeoutMs,
|
|
elapsedMsSinceLastEvent: attempt.monitor.elapsedMsSinceLastEvent,
|
|
terminationSignal: attempt.monitor.terminationSignal,
|
|
},
|
|
},
|
|
summary: attempt.parsed.summary,
|
|
clearSession: clearSessionOnMissingSession,
|
|
};
|
|
}
|
|
if (attempt.proc.timedOut) {
|
|
return {
|
|
exitCode: attempt.proc.exitCode,
|
|
signal: attempt.proc.signal,
|
|
timedOut: true,
|
|
usageComplete: attempt.parsed.usageComplete,
|
|
costStatus: attempt.parsed.usageComplete ? undefined : "unpriced",
|
|
usage: attempt.parsed.usageReported ? attempt.parsed.usage : undefined,
|
|
usageBasis: "per_run",
|
|
provider: "openai",
|
|
biller,
|
|
model,
|
|
billingType,
|
|
costUsd: null,
|
|
pricingContext: attempt.pricingContext,
|
|
errorMessage: `Timed out after ${timeoutSec}s`,
|
|
clearSession: clearSessionOnMissingSession,
|
|
};
|
|
}
|
|
|
|
const canFallbackToRuntimeSession = !isRetry && !forceFreshSession && (!sshSessionState || sshSessionState.canResume);
|
|
const resolvedSessionId =
|
|
attempt.parsed.sessionId ??
|
|
(canFallbackToRuntimeSession ? (runtimeSessionId ?? runtime.sessionId ?? null) : null);
|
|
const resolvedSessionParams = resolvedSessionId
|
|
? ({
|
|
sessionId: resolvedSessionId,
|
|
cwd: effectiveExecutionCwd,
|
|
...(sshSessionState ? { sshCodexConversationId: sshSessionState.conversationId, sshCodexAccountScope: sshSessionState.scope } : {}),
|
|
...(executionTargetIsRemote
|
|
? {
|
|
remoteExecution: adapterExecutionTargetSessionIdentity(runtimeExecutionTarget),
|
|
}
|
|
: {}),
|
|
...(workspaceId ? { workspaceId } : {}),
|
|
...(workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}),
|
|
...(workspaceRepoRef ? { repoRef: workspaceRepoRef } : {}),
|
|
} as Record<string, unknown>)
|
|
: null;
|
|
const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : "";
|
|
const stderrLine = firstMeaningfulStderrLine(attempt.proc.stderr);
|
|
const fallbackErrorMessage =
|
|
parsedError ||
|
|
stderrLine ||
|
|
`Codex exited with code ${attempt.proc.exitCode ?? -1}`;
|
|
const transientRetryNotBefore =
|
|
(attempt.proc.exitCode ?? 0) !== 0
|
|
? extractCodexRetryNotBefore({
|
|
stdout: attempt.proc.stdout,
|
|
stderr: attempt.proc.stderr,
|
|
errorMessage: fallbackErrorMessage,
|
|
})
|
|
: null;
|
|
const authRefreshFailure =
|
|
(attempt.proc.exitCode ?? 0) !== 0
|
|
? classifyCodexAuthRefreshFailure({
|
|
stdout: attempt.proc.stdout,
|
|
stderr: attempt.proc.stderr,
|
|
errorMessage: fallbackErrorMessage,
|
|
})
|
|
: null;
|
|
const providerQuota =
|
|
(attempt.proc.exitCode ?? 0) !== 0 &&
|
|
!authRefreshFailure &&
|
|
isCodexProviderQuotaError({
|
|
stdout: attempt.proc.stdout,
|
|
stderr: attempt.proc.stderr,
|
|
errorMessage: fallbackErrorMessage,
|
|
});
|
|
const transientUpstream =
|
|
(attempt.proc.exitCode ?? 0) !== 0 &&
|
|
!authRefreshFailure &&
|
|
!providerQuota &&
|
|
isCodexTransientUpstreamError({
|
|
stdout: attempt.proc.stdout,
|
|
stderr: attempt.proc.stderr,
|
|
errorMessage: fallbackErrorMessage,
|
|
});
|
|
const harnessCrash =
|
|
!authRefreshFailure &&
|
|
!providerQuota &&
|
|
!transientUpstream &&
|
|
isCodexHarnessCrash({
|
|
exitCode: attempt.proc.exitCode,
|
|
sawProtocolEvent: attempt.parsed.sawProtocolEvent,
|
|
sawProtocolTerminalEvent: attempt.parsed.sawProtocolTerminalEvent,
|
|
});
|
|
const errorFamily =
|
|
authRefreshFailure ??
|
|
(providerQuota ? "provider_quota" : transientUpstream || harnessCrash ? "transient_upstream" : null);
|
|
|
|
return {
|
|
exitCode: attempt.proc.exitCode,
|
|
signal: attempt.proc.signal,
|
|
timedOut: false,
|
|
usageComplete: attempt.parsed.usageComplete,
|
|
costStatus: attempt.parsed.usageComplete ? undefined : "unpriced",
|
|
errorMessage:
|
|
(attempt.proc.exitCode ?? 0) === 0
|
|
? null
|
|
: fallbackErrorMessage,
|
|
errorCode:
|
|
// Forward the transport-level error code from the run-disposition
|
|
// seam first. A lost duplex control channel surfaces the typed
|
|
// `duplex_channel_lost` code before any provider classification.
|
|
attempt.proc.errorCode
|
|
? attempt.proc.errorCode
|
|
: authRefreshFailure
|
|
? authRefreshFailure
|
|
: providerQuota
|
|
? "provider_quota"
|
|
: transientUpstream
|
|
? "codex_transient_upstream"
|
|
: harnessCrash
|
|
? "codex_harness_crash"
|
|
: null,
|
|
errorFamily,
|
|
retryNotBefore: transientRetryNotBefore ? transientRetryNotBefore.toISOString() : null,
|
|
usage: attempt.parsed.usageReported ? attempt.parsed.usage : undefined,
|
|
usageBasis: attempt.parsed.usageBasis,
|
|
sessionId: resolvedSessionId,
|
|
sessionParams: resolvedSessionParams,
|
|
sessionDisplayId: resolvedSessionId,
|
|
provider: "openai",
|
|
biller,
|
|
model,
|
|
billingType,
|
|
costUsd: null,
|
|
pricingContext: attempt.pricingContext,
|
|
resultJson: {
|
|
stdout: attempt.proc.stdout,
|
|
stderr: attempt.proc.stderr,
|
|
...(sshSessionState && runtimeSessionId && !sshSessionState.canResume
|
|
? { sessionReset: { code: "codex_ssh_session_state_unavailable" } } : {}),
|
|
...(errorFamily ? { errorFamily } : {}),
|
|
...(transientRetryNotBefore ? { retryNotBefore: transientRetryNotBefore.toISOString() } : {}),
|
|
...(transientRetryNotBefore ? { transientRetryNotBefore: transientRetryNotBefore.toISOString() } : {}),
|
|
...(providerQuota && transientRetryNotBefore ? { providerQuotaRetryNotBefore: transientRetryNotBefore.toISOString() } : {}),
|
|
},
|
|
summary: attempt.parsed.summary,
|
|
clearSession: Boolean((clearSessionOnMissingSession || forceFreshSession) && !resolvedSessionId),
|
|
};
|
|
};
|
|
|
|
const initial = await runAttempt(sessionId);
|
|
if (
|
|
sessionId &&
|
|
!initial.proc.timedOut &&
|
|
!initial.proc.signal &&
|
|
// A started session can emit stale-rollout warnings for other threads.
|
|
// After Ctrl-C those warnings must not restart the cancelled turn.
|
|
!initial.parsed.sessionId &&
|
|
(initial.proc.exitCode ?? 0) !== 0 &&
|
|
isCodexUnknownSessionError(initial.proc.stdout, initial.rawStderr)
|
|
) {
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Codex resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`,
|
|
);
|
|
const retry = await runAttempt(null);
|
|
const retryResult = toResult(retry, true, true);
|
|
if (retryResult.errorMessage) {
|
|
executionError = new Error(retryResult.errorMessage);
|
|
}
|
|
return retryResult;
|
|
}
|
|
|
|
const result = toResult(initial, false, false);
|
|
if (result.errorMessage) {
|
|
executionError = new Error(result.errorMessage);
|
|
}
|
|
return result;
|
|
} catch (error) {
|
|
executionError = error;
|
|
throw error;
|
|
} finally {
|
|
try {
|
|
await providerStop.collectBeforeRestore();
|
|
} finally {
|
|
try {
|
|
if (paperclipBridge) {
|
|
await paperclipBridge.stop();
|
|
}
|
|
} finally {
|
|
if (restoreRemoteWorkspace) {
|
|
try {
|
|
await onLog(
|
|
"stdout",
|
|
`[paperclip] Restoring workspace changes from ${describeAdapterExecutionTarget(executionTarget)}.\n`,
|
|
).catch(() => undefined);
|
|
await restoreRemoteWorkspace();
|
|
} catch (error) {
|
|
await Promise.resolve(
|
|
onLog(
|
|
"stderr",
|
|
`[paperclip] Failed to restore workspace changes from ${describeAdapterExecutionTarget(
|
|
executionTarget,
|
|
)}: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
),
|
|
).catch(() => undefined);
|
|
// A provider failure remains the primary outcome. When provider work
|
|
// succeeded, however, silently accepting a failed copy-back can lose
|
|
// the only workspace edits before a replacement sandbox starts.
|
|
if (executionError === null) throw error;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} finally {
|
|
// Remove the staged CODEX_HOME allowlist temp dir on every exit path
|
|
// (teardown AND error), never only the happy path. Cleanup failure is
|
|
// logged, not fatal — a leaked temp dir must not crash the run.
|
|
if (stagedCodexHomeDir) {
|
|
await fs.rm(stagedCodexHomeDir, { recursive: true, force: true }).catch(async (error) => {
|
|
await onLog(
|
|
"stderr",
|
|
`[paperclip] Failed to remove staged Codex home "${stagedCodexHomeDir}": ${
|
|
error instanceof Error ? error.message : String(error)
|
|
}\n`,
|
|
);
|
|
});
|
|
}
|
|
// Restore the managed config.toml so PAPERCLIP_CODEX_PROVIDERS changes
|
|
// (or removal) between runs never leave stale provider routing behind. This
|
|
// finally starts the moment prepareCodexRuntimeConfig returns, so a throw
|
|
// anywhere in the remaining setup (skill injection, remote runtime
|
|
// preparation, command building) restores the original config.toml too.
|
|
// If the process dies before reaching this, the next
|
|
// prepareCodexRuntimeConfig restores the original from the pre-run backup
|
|
// written at prepare time.
|
|
await observabilityProfile?.cleanup();
|
|
await preparedRuntimeConfig.cleanup();
|
|
}
|
|
}
|