mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 03:36:57 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Companies use several agent harnesses and execution environments. > - Operators need one place to select where native agent logs and traces go. > - An inference proxy would add a dependency to the agent request path. > - This pull request supplies native OpenTelemetry settings to managed Codex and Claude Code processes. > - Company secrets protect destination credentials. Export failure does not change the task result. ## Linked Issues or Issue Description **Subsystem affected** Company settings, shared contracts, database, server, adapters, and runner. **Problem or motivation** An operator cannot configure a company destination for native agent logs and traces. Manual harness configuration is hard to apply across local and remote execution. **Proposed solution** Add one company destination: Braintrust or a custom OTLP HTTP/protobuf endpoint. Apply a transient snapshot when execution preparation starts. Keep credentials out of API reads, task environment manifests, recovery files, and command arguments. Replace a warm process when its export settings change and preserve its conversation. **Alternatives considered** Multiple destinations can use a user-operated collector for fan-out. This change does not add a collector, an inference proxy, or transcript scraping. **Roadmap alignment** This extends company settings, secret management, and support for multiple harnesses. The maintainer requested this implementation. Searches for observability and Braintrust found no duplicate company destination feature. Related infrastructure tracing work in #16236 has a separate content-free contract. ## What Changed - Add strict schemas, revision checks, encrypted secret storage, activity records, and board-only settings routes. - Add explicit synthetic logs and traces tests with a bounded HTTP request and sanitized results. - Supply native Codex configuration and Claude Code environment values through local and remote launch paths. - Preserve Codex login refresh through the existing managed credential link. Retain unsaved drafts across background reads. Require complete custom header re-entry when the endpoint origin changes. - Separate process export compatibility from conversation identity. Isolate generated Codex configuration and preserve resumable sessions, including remote home refresh after export changes. - Advance the immutable Pi/Copilot source attestations for shared environment and sidecar code changes. Keep their provider payloads unchanged and retain prior identities for decoding. - Redact destination credentials throughout launch diagnostics and HTTP logs. - Add the production settings form, Storybook states and journey, documentation, and feature/access map entries. ## Verification - Real managed local Codex 0.160.0 and Claude Code 2.1.286 tasks exported to Braintrust. API readback and the Braintrust UI showed the test records. A real remote Daytona Codex task exported through the legacy `exec` path. - Live tests exercised content capture off, export disabled, warm conversation reuse, and a destination that accepted connections but never replied. Agent work succeeded and export requests stopped at the configured three-second timeout. The UI connection test returned “Test payload accepted”; the saved API key stayed masked after reload. - All current-head CI test lanes, typechecks, packaging/build checks, and required aggregates passed on `71e994b2be9c8fb6d6e938a4ad7cf4c95fdafe31` ([CI run](https://github.com/paperclipai/paperclip/actions/runs/39319194318)). Greptile completed on that exact commit at 5/5, with zero unresolved review threads. The additional optional Paperclip Review check remains queued waiting for its assigned agent. - Local workspace typecheck and build passed. Focused verification included 239 combined runner tests, 789 API/native-session tests, 107 Codex home/ACP/sandbox-site tests, 204 feature/privacy tests, and the affected Rust suites. Migration, token, map, Storybook catalog, and Storybook build checks passed during acceptance. These checks ran at the relevant implementation or merge boundary; the current-head CI is the complete final gate. - Managed AI credential projections now receive enabled and disabled company export settings; genuine caller-owned Codex homes remain untouched. Two regressions reproduced the skip before the repair. All 276 engine/lifecycle tests and adapter-utils typecheck pass afterward. The launched TOML retains provider/MCP settings, credential continuity, and redaction. - Settings saves, removal, and the real company-deletion owner acquire secret mutation ownership before database locks. PostgreSQL NOWAIT probes cover all three paths; concurrent save/rotation/removal/deletion requests settle correctly. The affected suites passed 137 tests, followed by all 32 service/connection cases after expanded deletion coverage. Server and Codex adapter typechecks pass. - Codex source profiles use the effective CLI argument list. A spawned fixture CLI reproduced both ignored-argument failures; all three precedence/fallback cases now pass. - Real tar staging reproduced remote conversation loss in both API-key and subscription modes before the repair. Both now pass: changing managed settings preserves sessions, archives, native indexes, and refreshed subscription credentials. A corrupt upload preserves the prior config and conversation. - Preserved failure evidence: initial CI caught stale Pi/Copilot source attestations, a missing test-harness helper, and packaging fixture/probe mismatches; those were corrected and covered by focused checks. Superseded heads had intermittent attachment-composer timeouts despite successful uploads; [the original trace and screenshot remain available](https://github.com/paperclipai/paperclip/actions/runs/39309701089/artifacts/12215109203). The same attachment case passed on the final head: [25/25 tests in shard 3](https://github.com/paperclipai/paperclip/actions/runs/39319194318/job/118288637051). - A connection-fault fixture also exposed a stale pooled socket after its hang case; closing fixture responses isolated scenarios and the full affected suite passed. - The broad local test run was not clean: database resource failures, timeouts, an older cached module graph, and a stale optional-resource manifest assumption were recorded. Focused checks passed after the documented fixes. This does not establish a clean full local pass. - Native remote Codex, remote Claude, and the full ACPX Codex bridge remain unqualified. The direct Codex resume test does not establish full bridge acceptance. ## Risks - Native exporters perform network requests from each execution environment. A server connection test does not prove remote reachability. - Prompts, assistant responses, and tool content are enabled by default when supported. Native caps and harness-specific controls still apply. - Caller-owned Codex homes are unsupported for automatic configuration and remain untouched. - Native harnesses and their tool processes can inspect export credentials. The settings form and documentation advise using ingestion-scoped credentials. Retained headers remain bound to their saved scheme, host, and port; changing origin requires fresh values or removal. - Migration 0357 adds a company-scoped row and secret reference. It is safe to reapply. Secret removal and company deletion use the existing secret lifecycle. - Slow or unavailable destinations must not block task settlement. Export settings take effect at the next execution preparation boundary. ## Model Used OpenAI Codex, GPT-6, with reasoning, tool use, code execution, and browser verification. The exact serving model ID and context window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
706 lines
29 KiB
TypeScript
706 lines
29 KiB
TypeScript
import fs from "node:fs/promises";
|
||
import path from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import type {
|
||
AdapterBillingType,
|
||
AdapterEnvironmentCheck,
|
||
AdapterEnvironmentTestContext,
|
||
AdapterEnvironmentTestResult,
|
||
AdapterExecutionContext,
|
||
AdapterExecutionResult,
|
||
} from "@paperclipai/adapter-utils";
|
||
import {
|
||
parseLocalProcessFilesystemScope,
|
||
parseLocalProcessNetworkScope,
|
||
} from "@paperclipai/adapter-utils/local-process-sandbox";
|
||
import { inferOpenAiCompatibleBiller, resolveManagedOpenAiBilling } from "@paperclipai/adapter-utils";
|
||
import {
|
||
ensureAdapterExecutionTargetCommandResolvable,
|
||
readAdapterExecutionTarget,
|
||
resolveAdapterExecutionTargetCwd,
|
||
} from "@paperclipai/adapter-utils/execution-target";
|
||
import {
|
||
DEFAULT_ACP_ENGINE_MODE,
|
||
DEFAULT_ACP_ENGINE_NON_INTERACTIVE_PERMISSIONS,
|
||
DEFAULT_ACP_ENGINE_PERMISSION_MODE,
|
||
DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS,
|
||
} from "@paperclipai/adapter-utils/acpx-engine/constants";
|
||
import type {
|
||
AcpxEngineExecutorOptions,
|
||
AcpxRemoteManagedHomeContext,
|
||
AcpxRemoteManagedHomeResult,
|
||
AcpxTerminalFailureClassification,
|
||
AcpxTerminalSessionFailure,
|
||
} from "@paperclipai/adapter-utils/acpx-engine/execute";
|
||
import {
|
||
asNumber,
|
||
asString,
|
||
asStringArray,
|
||
parseObject,
|
||
} from "@paperclipai/adapter-utils/server-utils";
|
||
import { createWorkspaceRestoreTeardown } from "@paperclipai/adapter-utils/workspace-restore-teardown";
|
||
import { normalizeCodexModel } from "../index.js";
|
||
import { classifyCodexAuthRefreshFailure, extractCodexRetryNotBefore } from "./parse.js";
|
||
import { copyBackCodexAuth } from "./codex-auth-copyback.js";
|
||
import {
|
||
buildCodexHomeRefreshProvision,
|
||
evaluateCodexCredentialReadiness,
|
||
resolveSharedCodexHomeDir,
|
||
stageCodexHomeForSync,
|
||
} from "./codex-home.js";
|
||
import { ADAPTER_AUTH_MISSING_CHECK_CODE } from "./auth-check.js";
|
||
import { checkCodexCliVersionForModel } from "./cli-version.js";
|
||
|
||
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||
const packageRootDir = path.resolve(moduleDir, "../..");
|
||
const MIN_ACP_NODE_VERSION = "24.11.0";
|
||
|
||
export type CodexExecutionEngine = "cli" | "acp";
|
||
|
||
export interface CodexEngineSelection {
|
||
engine: CodexExecutionEngine;
|
||
explicit: boolean;
|
||
unavailableReason?: string;
|
||
}
|
||
|
||
type CodexEngineResolutionInput =
|
||
Pick<AdapterExecutionContext, "config"> &
|
||
Partial<Pick<AdapterExecutionContext, "executionTarget" | "executionTransport">>;
|
||
|
||
type CodexAcpExecutorOptions = Omit<
|
||
AcpxEngineExecutorOptions,
|
||
"adapterType" | "moduleDir" | "packageRootDir"
|
||
>;
|
||
|
||
type CodexAcpExecutor = (ctx: AdapterExecutionContext) => Promise<AdapterExecutionResult>;
|
||
|
||
function normalizeEngine(value: unknown): CodexEngineSelection {
|
||
const raw = typeof value === "string" ? value.trim().toLowerCase() : "";
|
||
if (raw === "acp") return { engine: "acp", explicit: true };
|
||
if (raw === "cli") return { engine: "cli", explicit: true };
|
||
return { engine: "acp", explicit: false };
|
||
}
|
||
|
||
export function resolveCodexExecutionEngine(config: Record<string, unknown>): CodexEngineSelection {
|
||
return normalizeEngine(config.engine);
|
||
}
|
||
|
||
export async function resolveCodexExecutionEngineForRun(
|
||
input: CodexEngineResolutionInput,
|
||
): Promise<CodexEngineSelection> {
|
||
const selection = normalizeEngine(input.config.engine);
|
||
// Engine availability must never change the agent's execution or permission contract.
|
||
if (selection.engine === "cli") return selection;
|
||
const unavailable = (reason: string): CodexEngineSelection => ({
|
||
...selection,
|
||
unavailableReason: `${reason} Repair the ACP setup, or explicitly set engine=cli to use the CLI engine.`,
|
||
});
|
||
const target = readAdapterExecutionTarget({
|
||
executionTarget: input.executionTarget,
|
||
legacyRemoteExecution: input.executionTransport?.remoteExecution,
|
||
});
|
||
if (target?.workspaceRealization?.mode === "in_place") {
|
||
return unavailable("In-place workspace realization requires the Codex CLI engine; ACP archive staging is not supported.");
|
||
}
|
||
const filesystemScope = parseLocalProcessFilesystemScope(input.config.filesystemScope);
|
||
const networkScope = parseLocalProcessNetworkScope(input.config.networkScope);
|
||
if (filesystemScope || networkScope) {
|
||
return unavailable("Local filesystem/network confinement requires the Codex CLI engine; ACP confinement is not supported.");
|
||
}
|
||
|
||
const reason = await codexAcpUnavailableReason(input);
|
||
return reason ? unavailable(reason) : selection;
|
||
}
|
||
|
||
function firstNonEmptyString(...values: unknown[]): string | undefined {
|
||
for (const value of values) {
|
||
if (typeof value !== "string") continue;
|
||
const trimmed = value.trim();
|
||
if (trimmed.length > 0) return trimmed;
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
export function buildCodexAcpConfig(config: Record<string, unknown>): Record<string, unknown> {
|
||
const agentCommand = firstNonEmptyString(config.agentCommand, config.acpAgentCommand);
|
||
const stateDir = firstNonEmptyString(config.stateDir, config.acpStateDir);
|
||
const mode = firstNonEmptyString(config.mode, config.acpMode) ?? DEFAULT_ACP_ENGINE_MODE;
|
||
const permissionMode =
|
||
firstNonEmptyString(config.permissionMode, config.acpPermissionMode) ??
|
||
DEFAULT_ACP_ENGINE_PERMISSION_MODE;
|
||
const nonInteractivePermissions =
|
||
firstNonEmptyString(config.nonInteractivePermissions, config.acpNonInteractivePermissions) ??
|
||
DEFAULT_ACP_ENGINE_NON_INTERACTIVE_PERMISSIONS;
|
||
const warmHandleIdleMs =
|
||
config.warmHandleIdleMs ??
|
||
config.acpWarmHandleIdleMs ??
|
||
DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS;
|
||
// Rewrite legacy model aliases (e.g. bare gpt-5.6) to the concrete slug Codex has metadata for,
|
||
// so the ACP session config matches the CLI lane and avoids the fallback-metadata warning.
|
||
const normalizedModel = normalizeCodexModel(
|
||
typeof config.model === "string" ? config.model : "",
|
||
);
|
||
|
||
const env = parseObject(config.env);
|
||
let networkAccess = env.PAPERCLIP_CODEX_ACP_NETWORK_ACCESS !== "false";
|
||
const extraArgs = asStringArray(config.extraArgs);
|
||
for (const arg of extraArgs.length > 0 ? extraArgs : asStringArray(config.args)) {
|
||
const match = /^(?:(?:--config=|-c=?)\s*)?sandbox_workspace_write\.network_access\s*=\s*(true|false)\s*$/.exec(arg);
|
||
if (match) networkAccess = match[1] === "true";
|
||
}
|
||
|
||
return {
|
||
...config,
|
||
env: { ...env, PAPERCLIP_CODEX_ACP_NETWORK_ACCESS: String(networkAccess) },
|
||
agent: "codex",
|
||
mode,
|
||
permissionMode,
|
||
nonInteractivePermissions,
|
||
warmHandleIdleMs,
|
||
...(normalizedModel ? { model: normalizedModel } : {}),
|
||
...(agentCommand ? { agentCommand } : {}),
|
||
...(stateDir ? { stateDir } : {}),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Codex remote managed-home seed + auth copy-back for the runner-backed remote
|
||
* sandbox ACP lane. Mirrors the codex CLI lane (`codex-local/execute.ts`): stage
|
||
* the managed `CODEX_HOME` (auth.json + config.toml + skills) into the sandbox
|
||
* as the `home` asset, then repoint `CODEX_HOME` onto the in-sandbox
|
||
* `assetDirs.home` path. Subscription runs also use inbound auth merge and
|
||
* outbound copy-back through `restoreWorkspace()` at teardown.
|
||
*
|
||
* The engine already resolved+seeded the host managed Codex home and set
|
||
* `env.CODEX_HOME` to it (a HOST path) before this seam runs, so `env.CODEX_HOME`
|
||
* is exactly the home to stage. Subscription auth merge and copy-back stay
|
||
* paired: Codex refresh tokens are single-use, so a refreshed sandbox token
|
||
* that is never copied back would spend the host's token. API-key runs skip
|
||
* both auth seams and never touch the shared subscription credential.
|
||
*/
|
||
async function prepareCodexRemoteManagedHome(
|
||
input: AcpxRemoteManagedHomeContext,
|
||
): Promise<AcpxRemoteManagedHomeResult> {
|
||
const { env, runId, onLog } = input;
|
||
// The host managed Codex home the engine seeded and set on env.CODEX_HOME.
|
||
const effectiveCodexHome = env.CODEX_HOME;
|
||
if (!effectiveCodexHome) {
|
||
// No managed home resolved (e.g. custom CODEX_HOME cleared) — stage the
|
||
// workspace with no home asset, identical to the no-seam fallback.
|
||
return { stagedRuntime: await input.stage([]) };
|
||
}
|
||
// API-key runs do not rotate a subscription refresh token. Keep their
|
||
// sandbox auth out of the shared subscription copy-back path altogether.
|
||
const apiKeyAuth = Boolean(
|
||
env.OPENAI_API_KEY?.trim() || env.CODEX_API_KEY?.trim()
|
||
|| process.env.OPENAI_API_KEY?.trim() || process.env.CODEX_API_KEY?.trim(),
|
||
);
|
||
// Curated allowlist temp dir (auth/config/skills only); caller owns cleanup.
|
||
const stagedCodexHomeDir = await stageCodexHomeForSync(effectiveCodexHome, { runId });
|
||
let stagedRuntime;
|
||
try {
|
||
stagedRuntime = await input.stage([
|
||
{
|
||
key: "home",
|
||
localDir: stagedCodexHomeDir,
|
||
followSymlinks: true,
|
||
// Refresh managed config/auth while retaining remote conversation files.
|
||
provision: buildCodexHomeRefreshProvision({ mergeAuth: !apiKeyAuth }),
|
||
// Subscription-only outbound copy-back at teardown, under the same
|
||
// direction-agnostic decision predicate + directory merge-lock +
|
||
// atomic-rename + 0600 guard. Target is the SHARED host auth.json
|
||
// (the symlink source managed homes point at), never an in-sandbox copy.
|
||
restore: apiKeyAuth ? undefined : async ({ assetDir, readFile }) =>
|
||
void (await copyBackCodexAuth({
|
||
readSandboxAuth: () => readFile(path.posix.join(assetDir, "auth.json")),
|
||
hostAuthPath: path.join(input.config.managedAiConnection ? effectiveCodexHome : resolveSharedCodexHomeDir(process.env), "auth.json"),
|
||
log: (line) => onLog("stdout", `${line}\n`),
|
||
})),
|
||
},
|
||
]);
|
||
} catch (err) {
|
||
await fs.rm(stagedCodexHomeDir, { recursive: true, force: true }).catch(() => {});
|
||
throw err;
|
||
}
|
||
// Repoint CODEX_HOME from the HOST path onto the seeded in-sandbox home.
|
||
env.CODEX_HOME =
|
||
stagedRuntime.assetDirs.home ??
|
||
path.posix.join(stagedRuntime.runtimeRootDir ?? "", "home");
|
||
|
||
return {
|
||
stagedRuntime,
|
||
// Subscription copy-back fires on EVERY run's teardown (including a compatible
|
||
// resume that reuses this staged runtime). It reads the sandbox auth.json /
|
||
// workspace live and copies back to the host; it does NOT remove the staged
|
||
// in-sandbox home, so re-running it across resumes can't leave a later run
|
||
// without its staged home. Host staged-temp removal is deliberately NOT here
|
||
// — see `disposeStaged` — so caching this runtime for reuse never destroys
|
||
// resources the next resume needs.
|
||
// Fail-soft: a teardown copy-back miss loses this rotation and surfaces
|
||
// loudly as refresh_token_reused on the next host Codex use (re-auth
|
||
// recovers) — never silent host-credential corruption, so it must not
|
||
// mask the run result.
|
||
teardown: createWorkspaceRestoreTeardown({
|
||
stagedRuntime,
|
||
onLog,
|
||
startMessage: apiKeyAuth
|
||
? "[paperclip] Restoring workspace changes from the sandbox.\n"
|
||
: "[paperclip] Restoring workspace changes and Codex auth from the sandbox.\n",
|
||
failurePrefix: "[paperclip] Codex ACP teardown restore/copy-back failed",
|
||
}),
|
||
// One-time cleanup of the HOST staged home temp dir. Fired ONLY when the
|
||
// staged runtime is dropped (failed/cancelled/timed-out turn, incompatible
|
||
// re-stage, idle eviction) — never on a clean turn that keeps the runtime
|
||
// warm — so it can't remove the staged home while a reuse still depends on
|
||
// it. Idempotent: `force: true` no-ops if it was already removed.
|
||
disposeStaged: async () => {
|
||
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`,
|
||
);
|
||
});
|
||
},
|
||
};
|
||
}
|
||
|
||
const CODEX_MODEL_CAPACITY_RE =
|
||
/\b(?:selected model is at capacity|model is at capacity|at capacity for this model|serverOverloaded|server overloaded)\b/i;
|
||
|
||
export function classifyCodexTerminalSessionFailure(
|
||
failure: AcpxTerminalSessionFailure,
|
||
now: Date,
|
||
): AcpxTerminalFailureClassification | null {
|
||
if (failure.category === "service") {
|
||
const text = [failure.title, failure.details].filter(Boolean).join("\n");
|
||
return CODEX_MODEL_CAPACITY_RE.test(text)
|
||
? { errorCode: "codex_transient_upstream", errorFamily: "transient_upstream" }
|
||
: null;
|
||
}
|
||
// ACP's `limit` also covers context, turn, rate and configured budget limits.
|
||
// Require explicit usage exhaustion; the CLI's broader capacity matcher would
|
||
// also match a context/storage capacity limit and defer the wrong failure.
|
||
if (failure.category !== "limit") return null;
|
||
const surface = { errorMessage: [failure.title, failure.details].filter(Boolean).join("\n") };
|
||
if (!/\b(?:you(?:'|’)ve hit your usage limit|usage limit (?:reached|exceeded))\b/i.test(surface.errorMessage)) {
|
||
return null;
|
||
}
|
||
const retryNotBefore = extractCodexRetryNotBefore(surface, now)?.toISOString();
|
||
return {
|
||
errorCode: "provider_quota",
|
||
errorFamily: "provider_quota",
|
||
...(retryNotBefore ? { retryNotBefore } : {}),
|
||
};
|
||
}
|
||
|
||
function withCodexAcpDefaults(options: CodexAcpExecutorOptions): AcpxEngineExecutorOptions {
|
||
return {
|
||
resolveBillingIdentity: resolveCodexAcpBillingIdentity,
|
||
prepareRemoteManagedHome: prepareCodexRemoteManagedHome,
|
||
classifyTerminalSessionFailure: classifyCodexTerminalSessionFailure,
|
||
...options,
|
||
adapterType: "codex_local",
|
||
moduleDir,
|
||
packageRootDir,
|
||
};
|
||
}
|
||
|
||
function withCodexAuthRefreshFailureClassification(result: AdapterExecutionResult): AdapterExecutionResult {
|
||
if ((result.exitCode ?? 0) === 0) return result;
|
||
const resultJson = parseObject(result.resultJson);
|
||
const stopReason = asString(resultJson.stopReason, "");
|
||
const authFailure = classifyCodexAuthRefreshFailure({
|
||
errorMessage: [result.errorMessage ?? "", result.summary ?? "", stopReason]
|
||
.map((line) => line.trim())
|
||
.filter(Boolean)
|
||
.join("\n"),
|
||
});
|
||
if (!authFailure) return result;
|
||
|
||
return {
|
||
...result,
|
||
errorCode: authFailure,
|
||
errorFamily: authFailure,
|
||
resultJson: {
|
||
...(result.resultJson ?? {}),
|
||
errorFamily: authFailure,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Classify billing the same way the Codex CLI lane does so ACP runs land in
|
||
* the cost ledger with a real provider/billingType instead of acpx/unknown.
|
||
* Host env only counts for local execution targets; remote targets see just
|
||
* the adapter-config env.
|
||
*/
|
||
export function resolveCodexAcpBillingIdentity(
|
||
ctx: Pick<AdapterExecutionContext, "config"> &
|
||
Partial<Pick<AdapterExecutionContext, "executionTarget" | "executionTransport">>,
|
||
): { provider: string; biller: string; billingType: AdapterBillingType } {
|
||
const managedBilling = resolveManagedOpenAiBilling(ctx.config.managedAiRouting);
|
||
if (managedBilling) return managedBilling;
|
||
const envConfig = parseObject(parseObject(ctx.config).env);
|
||
const target = readAdapterExecutionTarget({
|
||
executionTarget: ctx.executionTarget,
|
||
legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
|
||
});
|
||
const considerHostEnv = target?.kind !== "remote";
|
||
const mergedEnv: NodeJS.ProcessEnv = {
|
||
...(considerHostEnv ? process.env : {}),
|
||
...Object.fromEntries(
|
||
Object.entries(envConfig).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
|
||
),
|
||
};
|
||
const apiKey = typeof mergedEnv.OPENAI_API_KEY === "string" && mergedEnv.OPENAI_API_KEY.trim().length > 0;
|
||
const billingType: AdapterBillingType = apiKey ? "api" : "subscription";
|
||
const openAiCompatibleBiller = inferOpenAiCompatibleBiller(mergedEnv, "openai");
|
||
const biller =
|
||
openAiCompatibleBiller === "openrouter"
|
||
? "openrouter"
|
||
: billingType === "subscription"
|
||
? "chatgpt"
|
||
: openAiCompatibleBiller ?? "openai";
|
||
return { provider: "openai", biller, billingType };
|
||
}
|
||
|
||
export function createCodexAcpExecutor(options: CodexAcpExecutorOptions = {}): CodexAcpExecutor {
|
||
let executor: CodexAcpExecutor | null = null;
|
||
return async (ctx) => {
|
||
let currentExecutor = executor;
|
||
if (!currentExecutor) {
|
||
const { createAcpxEngineExecutor } = await import("@paperclipai/adapter-utils/acpx-engine/execute");
|
||
currentExecutor = createAcpxEngineExecutor(withCodexAcpDefaults(options));
|
||
executor = currentExecutor;
|
||
}
|
||
const result = await currentExecutor({
|
||
...ctx,
|
||
config: buildCodexAcpConfig(ctx.config),
|
||
});
|
||
return withCodexAuthRefreshFailureClassification(result);
|
||
};
|
||
}
|
||
|
||
function parseVersion(version: string): [number, number, number] {
|
||
const match = version.match(/^v?(\d+)\.(\d+)\.(\d+)/);
|
||
if (!match) return [0, 0, 0];
|
||
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
||
}
|
||
|
||
export function nodeVersionMeetsCodexAcpMinimum(version = process.version): boolean {
|
||
const [major, minor, patch] = parseVersion(version);
|
||
const [minMajor, minMinor, minPatch] = parseVersion(MIN_ACP_NODE_VERSION);
|
||
if (major !== minMajor) return major > minMajor;
|
||
if (minor !== minMinor) return minor > minMinor;
|
||
return patch >= minPatch;
|
||
}
|
||
|
||
async function pathExists(candidate: string): Promise<boolean> {
|
||
return fs.access(candidate).then(() => true).catch(() => false);
|
||
}
|
||
|
||
function hasPathSeparator(command: string): boolean {
|
||
return command.includes("/") || command.includes("\\");
|
||
}
|
||
|
||
function looksLikeShellCommand(command: string): boolean {
|
||
return /\s/.test(command.trim());
|
||
}
|
||
|
||
async function findCommandOnPath(binName: string): Promise<string | null> {
|
||
const pathValue = process.env.PATH ?? "";
|
||
for (const segment of pathValue.split(path.delimiter)) {
|
||
if (!segment) continue;
|
||
const candidate = path.join(segment, binName);
|
||
if (await pathExists(candidate)) return candidate;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
async function findAncestorBin(startDir: string, binName: string): Promise<string | null> {
|
||
let current = path.resolve(startDir);
|
||
while (true) {
|
||
const candidate = path.join(current, "node_modules", ".bin", binName);
|
||
if (await pathExists(candidate)) return candidate;
|
||
const parent = path.dirname(current);
|
||
if (parent === current) return null;
|
||
current = parent;
|
||
}
|
||
}
|
||
|
||
async function commandIsResolvable(
|
||
command: string,
|
||
input?: CodexEngineResolutionInput,
|
||
): Promise<boolean> {
|
||
const trimmed = command.trim();
|
||
if (!trimmed) return false;
|
||
if (looksLikeShellCommand(trimmed)) return true;
|
||
const target = readAdapterExecutionTarget({
|
||
executionTarget: input?.executionTarget,
|
||
legacyRemoteExecution: input?.executionTransport?.remoteExecution,
|
||
});
|
||
if (target?.kind === "remote") {
|
||
try {
|
||
await ensureAdapterExecutionTargetCommandResolvable(
|
||
trimmed,
|
||
target,
|
||
resolveAdapterExecutionTargetCwd(target, asString(input?.config.cwd, ""), process.cwd()),
|
||
process.env,
|
||
);
|
||
return true;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
if (path.isAbsolute(trimmed) || hasPathSeparator(trimmed)) return pathExists(trimmed);
|
||
return (await findCommandOnPath(trimmed)) !== null;
|
||
}
|
||
|
||
async function resolveCodexAcpCommand(config: Record<string, unknown>): Promise<string> {
|
||
const configured = firstNonEmptyString(config.agentCommand, config.acpAgentCommand);
|
||
if (configured) return configured;
|
||
return (
|
||
(await findAncestorBin(packageRootDir, "codex-acp")) ??
|
||
(await findCommandOnPath("codex-acp")) ??
|
||
path.join(packageRootDir, "node_modules", ".bin", "codex-acp")
|
||
);
|
||
}
|
||
|
||
function sandboxTargetHasProcessSessionBridge(
|
||
target: ReturnType<typeof readAdapterExecutionTarget>,
|
||
): boolean {
|
||
return target?.kind === "remote" && target.transport === "sandbox" && Boolean(target.runner);
|
||
}
|
||
|
||
async function resolveCodexAcpCommandForTarget(
|
||
config: Record<string, unknown>,
|
||
target: ReturnType<typeof readAdapterExecutionTarget>,
|
||
): Promise<string> {
|
||
const configured = firstNonEmptyString(config.agentCommand, config.acpAgentCommand);
|
||
if (configured) return configured;
|
||
if (target?.kind === "remote") return "codex-acp";
|
||
return resolveCodexAcpCommand(config);
|
||
}
|
||
|
||
async function codexAcpUnavailableReason(
|
||
input: CodexEngineResolutionInput,
|
||
): Promise<string | null> {
|
||
const target = readAdapterExecutionTarget({
|
||
executionTarget: input.executionTarget,
|
||
legacyRemoteExecution: input.executionTransport?.remoteExecution,
|
||
});
|
||
if (target?.kind === "remote" && !sandboxTargetHasProcessSessionBridge(target)) {
|
||
if (target.transport === "sandbox") {
|
||
return "Codex ACP requires a bidirectional remote process target; this sandbox exposes only one-shot command execution.";
|
||
}
|
||
return "Codex ACP supports sandbox remote targets only; this run targets a non-sandbox remote environment.";
|
||
}
|
||
if (!nodeVersionMeetsCodexAcpMinimum()) {
|
||
return `Node ${process.version} (${process.execPath}) does not satisfy Codex ACP's Node >=${MIN_ACP_NODE_VERSION} prerequisite.`;
|
||
}
|
||
const command = await resolveCodexAcpCommandForTarget(input.config, target);
|
||
if (!(await commandIsResolvable(command, input))) {
|
||
return `Codex ACP server command is not available: ${command}.`;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function summarizeStatus(checks: AdapterEnvironmentCheck[]): AdapterEnvironmentTestResult["status"] {
|
||
if (checks.some((check) => check.level === "error")) return "fail";
|
||
if (checks.some((check) => check.level === "warn")) return "warn";
|
||
return "pass";
|
||
}
|
||
|
||
function isNonEmpty(value: unknown): value is string {
|
||
return typeof value === "string" && value.trim().length > 0;
|
||
}
|
||
|
||
export async function testCodexAcpEnvironment(
|
||
ctx: AdapterEnvironmentTestContext,
|
||
): Promise<AdapterEnvironmentTestResult> {
|
||
const checks: AdapterEnvironmentCheck[] = [];
|
||
const config = parseObject(ctx.config);
|
||
const target = ctx.executionTarget ?? null;
|
||
const targetIsRemote = target?.kind === "remote";
|
||
const targetIsSandbox = target?.kind === "remote" && target.transport === "sandbox";
|
||
|
||
checks.push({
|
||
code: "codex_engine_selected",
|
||
level: "info",
|
||
message: "Execution engine selected: ACP.",
|
||
hint: "Set engine=cli to use the existing Codex CLI lane.",
|
||
});
|
||
|
||
if (targetIsRemote) {
|
||
checks.push({
|
||
code: "codex_acp_remote_target",
|
||
level: "info",
|
||
message: "Codex ACP will run against the remote execution environment.",
|
||
hint: "Remote ACP requires a bidirectional process target such as SSH or Paperclip's sandbox process-session bridge.",
|
||
});
|
||
}
|
||
|
||
const cwd = asString(config.cwd, process.cwd());
|
||
try {
|
||
await fs.mkdir(cwd, { recursive: true });
|
||
checks.push({
|
||
code: "codex_acp_cwd_valid",
|
||
level: "info",
|
||
message: `Working directory is valid: ${cwd}`,
|
||
});
|
||
} catch (err) {
|
||
checks.push({
|
||
code: "codex_acp_cwd_invalid",
|
||
level: "error",
|
||
message: err instanceof Error ? err.message : "Invalid working directory",
|
||
detail: cwd,
|
||
});
|
||
}
|
||
|
||
checks.push({
|
||
code: nodeVersionMeetsCodexAcpMinimum() ? "codex_acp_node_supported" : "codex_acp_node_unsupported",
|
||
level: nodeVersionMeetsCodexAcpMinimum() ? "info" : "error",
|
||
message: nodeVersionMeetsCodexAcpMinimum()
|
||
? `Node ${process.version} satisfies ACP runtime requirements.`
|
||
: `Node ${process.version} (${process.execPath}) does not satisfy ACP runtime requirements.`,
|
||
hint: nodeVersionMeetsCodexAcpMinimum()
|
||
? undefined
|
||
: `Run Codex ACP with Node >=${MIN_ACP_NODE_VERSION} or switch engine=cli.`,
|
||
});
|
||
|
||
const command = await resolveCodexAcpCommandForTarget(config, target);
|
||
const commandResolvable = await commandIsResolvable(command, {
|
||
config,
|
||
executionTarget: ctx.executionTarget,
|
||
});
|
||
checks.push({
|
||
code: commandResolvable ? "codex_acp_command_resolvable" : "codex_acp_command_missing",
|
||
level: commandResolvable ? "info" : "error",
|
||
message: commandResolvable
|
||
? `Codex ACP server command is executable: ${command}`
|
||
: `Codex ACP server command is not available: ${command}`,
|
||
hint: commandResolvable
|
||
? undefined
|
||
: "Install dependencies so @agentclientprotocol/codex-acp is present, or set agentCommand to a valid Codex ACP server command.",
|
||
});
|
||
|
||
const envConfig = parseObject(config.env);
|
||
if (!targetIsRemote) {
|
||
const configApiKey = isNonEmpty(envConfig.OPENAI_API_KEY) ? envConfig.OPENAI_API_KEY : null;
|
||
const hostApiKey =
|
||
Object.prototype.hasOwnProperty.call(envConfig, "OPENAI_API_KEY")
|
||
? null
|
||
: isNonEmpty(process.env.OPENAI_API_KEY)
|
||
? process.env.OPENAI_API_KEY
|
||
: null;
|
||
const configuredApiKey = configApiKey ?? hostApiKey;
|
||
const configuredCodexHome = isNonEmpty(envConfig.CODEX_HOME) ? envConfig.CODEX_HOME : null;
|
||
const credentialReadiness = await evaluateCodexCredentialReadiness({
|
||
env: process.env,
|
||
companyId: ctx.companyId,
|
||
configuredCodexHome,
|
||
configuredApiKey,
|
||
});
|
||
|
||
if (credentialReadiness.ready && credentialReadiness.authMode === "api") {
|
||
checks.push({
|
||
code: "codex_acp_openai_api_key_detected",
|
||
level: "info",
|
||
message: "OPENAI_API_KEY is set for Codex ACP authentication.",
|
||
detail: `Detected in ${configApiKey ? "adapter config env" : "server environment"}.`,
|
||
});
|
||
} else if (credentialReadiness.ready && !credentialReadiness.managed) {
|
||
checks.push({
|
||
code: "codex_acp_external_home_configured",
|
||
level: "info",
|
||
message: "Codex ACP will use an externally managed CODEX_HOME.",
|
||
detail: credentialReadiness.effectiveHome,
|
||
});
|
||
} else if (credentialReadiness.ready) {
|
||
checks.push({
|
||
code: "codex_acp_native_auth_detected",
|
||
level: "info",
|
||
message: "Codex ACP can use Codex native authentication.",
|
||
detail: `Credentials are available through ${credentialReadiness.effectiveHome} or shared source ${credentialReadiness.sharedSourceHome}.`,
|
||
});
|
||
} else {
|
||
checks.push({
|
||
code: "codex_acp_credentials_missing",
|
||
level: "warn",
|
||
message: "No Codex ACP credentials visible to the Paperclip server were detected.",
|
||
hint: "Set OPENAI_API_KEY in the agent adapter env, set it in the Paperclip server environment, or run `codex login` for the same OS user that runs the Paperclip server before starting a Codex ACP agent. A `/login` in a separate Codex/chat session does not authenticate the server.",
|
||
});
|
||
}
|
||
} else if (targetIsSandbox) {
|
||
// The ACP Test does not probe the sandbox, so it predicts readiness from the
|
||
// credentials the Paperclip server can seed into the sandbox. The host
|
||
// environment is not seeded, so only the adapter config key counts here.
|
||
const configApiKey = isNonEmpty(envConfig.OPENAI_API_KEY) ? envConfig.OPENAI_API_KEY : null;
|
||
const configuredCodexHome = isNonEmpty(envConfig.CODEX_HOME) ? envConfig.CODEX_HOME : null;
|
||
const credentialReadiness = await evaluateCodexCredentialReadiness({
|
||
env: process.env,
|
||
companyId: ctx.companyId,
|
||
configuredCodexHome,
|
||
configuredApiKey: configApiKey,
|
||
});
|
||
if (!credentialReadiness.ready) {
|
||
// Emit the neutral canonical check so the user interface can decide login
|
||
// eligibility from a stable code. The user interface does not read the
|
||
// message text or the top-level status.
|
||
checks.push({
|
||
code: ADAPTER_AUTH_MISSING_CHECK_CODE,
|
||
level: "warn",
|
||
message: "This environment has no ready authentication for this adapter.",
|
||
hint: "Provide credentials for this adapter, or start login in the environment.",
|
||
});
|
||
}
|
||
}
|
||
|
||
if (targetIsRemote && commandResolvable) {
|
||
// The ACP server spawns the shared `codex` installed in the environment.
|
||
// Models with a verified CLI floor are checked against that executable so
|
||
// a stale sandbox image is named here, before a run fails on every turn
|
||
// with the backend's "not supported when using Codex with a ChatGPT
|
||
// account" rejection. Models without a floor skip the probe.
|
||
//
|
||
// Remote ACP runs receive the adapter's string-valued env entries (see
|
||
// buildCodexAcpConfig), so the probe gets the same ones. An agent that
|
||
// selects its Codex install through PATH is then measured against that
|
||
// install rather than the image default.
|
||
const probeEnv: Record<string, string> = {};
|
||
for (const [key, value] of Object.entries(envConfig)) {
|
||
if (typeof value === "string") probeEnv[key] = value;
|
||
}
|
||
const versionCheck = await checkCodexCliVersionForModel({
|
||
runId: `codex-acp-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`,
|
||
model: asString(config.model, ""),
|
||
command: "codex",
|
||
target,
|
||
cwd: resolveAdapterExecutionTargetCwd(target, asString(config.cwd, ""), process.cwd()),
|
||
env: probeEnv,
|
||
});
|
||
if (versionCheck) checks.push(versionCheck.check);
|
||
}
|
||
|
||
const mode = firstNonEmptyString(config.mode, config.acpMode) ?? DEFAULT_ACP_ENGINE_MODE;
|
||
const warmHandleIdleMs = asNumber(
|
||
config.warmHandleIdleMs ?? config.acpWarmHandleIdleMs,
|
||
DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS,
|
||
);
|
||
checks.push({
|
||
code: "codex_acp_runtime_scaffold",
|
||
level: "info",
|
||
message: "Codex ACP runtime execution is available through the shared ACP engine.",
|
||
detail: `mode=${mode}; warmHandleIdleMs=${warmHandleIdleMs}`,
|
||
});
|
||
|
||
return {
|
||
adapterType: ctx.adapterType,
|
||
status: summarizeStatus(checks),
|
||
checks,
|
||
testedAt: new Date().toISOString(),
|
||
};
|
||
}
|