@tickernelz/paperclip-pro-adapter-codex-local 2026.925.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/dist/cli/format-event.d.ts +2 -0
- package/dist/cli/format-event.d.ts.map +1 -0
- package/dist/cli/format-event.js +218 -0
- package/dist/cli/format-event.js.map +1 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +2 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/quota-probe.d.ts +3 -0
- package/dist/cli/quota-probe.d.ts.map +1 -0
- package/dist/cli/quota-probe.js +104 -0
- package/dist/cli/quota-probe.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +155 -0
- package/dist/index.js.map +1 -0
- package/dist/index.test.d.ts +2 -0
- package/dist/index.test.d.ts.map +1 -0
- package/dist/index.test.js +58 -0
- package/dist/index.test.js.map +1 -0
- package/dist/server/acp.d.ts +30 -0
- package/dist/server/acp.d.ts.map +1 -0
- package/dist/server/acp.js +532 -0
- package/dist/server/acp.js.map +1 -0
- package/dist/server/acp.test.d.ts +2 -0
- package/dist/server/acp.test.d.ts.map +1 -0
- package/dist/server/acp.test.js +1087 -0
- package/dist/server/acp.test.js.map +1 -0
- package/dist/server/adapter-auth-promotion.d.ts +102 -0
- package/dist/server/adapter-auth-promotion.d.ts.map +1 -0
- package/dist/server/adapter-auth-promotion.js +210 -0
- package/dist/server/adapter-auth-promotion.js.map +1 -0
- package/dist/server/adapter-auth-promotion.test.d.ts +2 -0
- package/dist/server/adapter-auth-promotion.test.d.ts.map +1 -0
- package/dist/server/adapter-auth-promotion.test.js +658 -0
- package/dist/server/adapter-auth-promotion.test.js.map +1 -0
- package/dist/server/auth-check.d.ts +8 -0
- package/dist/server/auth-check.d.ts.map +1 -0
- package/dist/server/auth-check.js +8 -0
- package/dist/server/auth-check.js.map +1 -0
- package/dist/server/auth-precedence.d.ts +16 -0
- package/dist/server/auth-precedence.d.ts.map +1 -0
- package/dist/server/auth-precedence.js +20 -0
- package/dist/server/auth-precedence.js.map +1 -0
- package/dist/server/auth-precedence.test.d.ts +2 -0
- package/dist/server/auth-precedence.test.d.ts.map +1 -0
- package/dist/server/auth-precedence.test.js +100 -0
- package/dist/server/auth-precedence.test.js.map +1 -0
- package/dist/server/codex-args.d.ts +13 -0
- package/dist/server/codex-args.d.ts.map +1 -0
- package/dist/server/codex-args.js +76 -0
- package/dist/server/codex-args.js.map +1 -0
- package/dist/server/codex-args.test.d.ts +2 -0
- package/dist/server/codex-args.test.d.ts.map +1 -0
- package/dist/server/codex-args.test.js +243 -0
- package/dist/server/codex-args.test.js.map +1 -0
- package/dist/server/codex-auth-cache.d.ts +206 -0
- package/dist/server/codex-auth-cache.d.ts.map +1 -0
- package/dist/server/codex-auth-cache.js +501 -0
- package/dist/server/codex-auth-cache.js.map +1 -0
- package/dist/server/codex-auth-cache.test.d.ts +2 -0
- package/dist/server/codex-auth-cache.test.d.ts.map +1 -0
- package/dist/server/codex-auth-cache.test.js +497 -0
- package/dist/server/codex-auth-cache.test.js.map +1 -0
- package/dist/server/codex-auth-copyback.d.ts +53 -0
- package/dist/server/codex-auth-copyback.d.ts.map +1 -0
- package/dist/server/codex-auth-copyback.js +123 -0
- package/dist/server/codex-auth-copyback.js.map +1 -0
- package/dist/server/codex-auth-copyback.test.d.ts +2 -0
- package/dist/server/codex-auth-copyback.test.d.ts.map +1 -0
- package/dist/server/codex-auth-copyback.test.js +507 -0
- package/dist/server/codex-auth-copyback.test.js.map +1 -0
- package/dist/server/codex-auth-merge-decision.cjs +170 -0
- package/dist/server/codex-auth-merge-decision.d.ts +22 -0
- package/dist/server/codex-auth-merge-decision.d.ts.map +1 -0
- package/dist/server/codex-auth-merge-decision.js +58 -0
- package/dist/server/codex-auth-merge-decision.js.map +1 -0
- package/dist/server/codex-auth-merge-decision.test.d.ts +2 -0
- package/dist/server/codex-auth-merge-decision.test.d.ts.map +1 -0
- package/dist/server/codex-auth-merge-decision.test.js +230 -0
- package/dist/server/codex-auth-merge-decision.test.js.map +1 -0
- package/dist/server/codex-auth-merge-extract.sh +73 -0
- package/dist/server/codex-auth-merge-scripts.d.ts +21 -0
- package/dist/server/codex-auth-merge-scripts.d.ts.map +1 -0
- package/dist/server/codex-auth-merge-scripts.js +40 -0
- package/dist/server/codex-auth-merge-scripts.js.map +1 -0
- package/dist/server/codex-auth-merge.test.d.ts +2 -0
- package/dist/server/codex-auth-merge.test.d.ts.map +1 -0
- package/dist/server/codex-auth-merge.test.js +714 -0
- package/dist/server/codex-auth-merge.test.js.map +1 -0
- package/dist/server/codex-auth-seed-write.d.ts +30 -0
- package/dist/server/codex-auth-seed-write.d.ts.map +1 -0
- package/dist/server/codex-auth-seed-write.js +41 -0
- package/dist/server/codex-auth-seed-write.js.map +1 -0
- package/dist/server/codex-home.d.ts +162 -0
- package/dist/server/codex-home.d.ts.map +1 -0
- package/dist/server/codex-home.js +771 -0
- package/dist/server/codex-home.js.map +1 -0
- package/dist/server/codex-home.test.d.ts +2 -0
- package/dist/server/codex-home.test.d.ts.map +1 -0
- package/dist/server/codex-home.test.js +1183 -0
- package/dist/server/codex-home.test.js.map +1 -0
- package/dist/server/config-schema.d.ts +3 -0
- package/dist/server/config-schema.d.ts.map +1 -0
- package/dist/server/config-schema.js +67 -0
- package/dist/server/config-schema.js.map +1 -0
- package/dist/server/device-login-export.d.ts +56 -0
- package/dist/server/device-login-export.d.ts.map +1 -0
- package/dist/server/device-login-export.js +230 -0
- package/dist/server/device-login-export.js.map +1 -0
- package/dist/server/device-login-export.test.d.ts +2 -0
- package/dist/server/device-login-export.test.d.ts.map +1 -0
- package/dist/server/device-login-export.test.js +245 -0
- package/dist/server/device-login-export.test.js.map +1 -0
- package/dist/server/device-login-parse.d.ts +20 -0
- package/dist/server/device-login-parse.d.ts.map +1 -0
- package/dist/server/device-login-parse.js +155 -0
- package/dist/server/device-login-parse.js.map +1 -0
- package/dist/server/device-login-parse.test.d.ts +2 -0
- package/dist/server/device-login-parse.test.d.ts.map +1 -0
- package/dist/server/device-login-parse.test.js +269 -0
- package/dist/server/device-login-parse.test.js.map +1 -0
- package/dist/server/device-login-runner.d.ts +69 -0
- package/dist/server/device-login-runner.d.ts.map +1 -0
- package/dist/server/device-login-runner.js +109 -0
- package/dist/server/device-login-runner.js.map +1 -0
- package/dist/server/device-login-runner.test.d.ts +2 -0
- package/dist/server/device-login-runner.test.d.ts.map +1 -0
- package/dist/server/device-login-runner.test.js +201 -0
- package/dist/server/device-login-runner.test.js.map +1 -0
- package/dist/server/engine-availability.test.d.ts +2 -0
- package/dist/server/engine-availability.test.d.ts.map +1 -0
- package/dist/server/engine-availability.test.js +41 -0
- package/dist/server/engine-availability.test.js.map +1 -0
- package/dist/server/execute.acp-fallback.test.d.ts +2 -0
- package/dist/server/execute.acp-fallback.test.d.ts.map +1 -0
- package/dist/server/execute.acp-fallback.test.js +123 -0
- package/dist/server/execute.acp-fallback.test.js.map +1 -0
- package/dist/server/execute.auth-precedence.test.d.ts +2 -0
- package/dist/server/execute.auth-precedence.test.d.ts.map +1 -0
- package/dist/server/execute.auth-precedence.test.js +137 -0
- package/dist/server/execute.auth-precedence.test.js.map +1 -0
- package/dist/server/execute.auth.test.d.ts +2 -0
- package/dist/server/execute.auth.test.d.ts.map +1 -0
- package/dist/server/execute.auth.test.js +197 -0
- package/dist/server/execute.auth.test.js.map +1 -0
- package/dist/server/execute.d.ts +40 -0
- package/dist/server/execute.d.ts.map +1 -0
- package/dist/server/execute.js +1290 -0
- package/dist/server/execute.js.map +1 -0
- package/dist/server/execute.remote.test.d.ts +2 -0
- package/dist/server/execute.remote.test.d.ts.map +1 -0
- package/dist/server/execute.remote.test.js +556 -0
- package/dist/server/execute.remote.test.js.map +1 -0
- package/dist/server/execute.stderr-error.test.d.ts +2 -0
- package/dist/server/execute.stderr-error.test.d.ts.map +1 -0
- package/dist/server/execute.stderr-error.test.js +142 -0
- package/dist/server/execute.stderr-error.test.js.map +1 -0
- package/dist/server/execute.test.d.ts +2 -0
- package/dist/server/execute.test.d.ts.map +1 -0
- package/dist/server/execute.test.js +240 -0
- package/dist/server/execute.test.js.map +1 -0
- package/dist/server/index.d.ts +18 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +71 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/output-inactivity-monitor.d.ts +62 -0
- package/dist/server/output-inactivity-monitor.d.ts.map +1 -0
- package/dist/server/output-inactivity-monitor.integration.test.d.ts +2 -0
- package/dist/server/output-inactivity-monitor.integration.test.d.ts.map +1 -0
- package/dist/server/output-inactivity-monitor.integration.test.js +136 -0
- package/dist/server/output-inactivity-monitor.integration.test.js.map +1 -0
- package/dist/server/output-inactivity-monitor.js +112 -0
- package/dist/server/output-inactivity-monitor.js.map +1 -0
- package/dist/server/output-inactivity-monitor.test.d.ts +2 -0
- package/dist/server/output-inactivity-monitor.test.d.ts.map +1 -0
- package/dist/server/output-inactivity-monitor.test.js +284 -0
- package/dist/server/output-inactivity-monitor.test.js.map +1 -0
- package/dist/server/parse.d.ts +51 -0
- package/dist/server/parse.d.ts.map +1 -0
- package/dist/server/parse.js +261 -0
- package/dist/server/parse.js.map +1 -0
- package/dist/server/parse.test.d.ts +2 -0
- package/dist/server/parse.test.d.ts.map +1 -0
- package/dist/server/parse.test.js +186 -0
- package/dist/server/parse.test.js.map +1 -0
- package/dist/server/process-activity-monitor.d.ts +21 -0
- package/dist/server/process-activity-monitor.d.ts.map +1 -0
- package/dist/server/process-activity-monitor.js +103 -0
- package/dist/server/process-activity-monitor.js.map +1 -0
- package/dist/server/process-activity-monitor.test.d.ts +2 -0
- package/dist/server/process-activity-monitor.test.d.ts.map +1 -0
- package/dist/server/process-activity-monitor.test.js +82 -0
- package/dist/server/process-activity-monitor.test.js.map +1 -0
- package/dist/server/quota-spawn-error.test.d.ts +2 -0
- package/dist/server/quota-spawn-error.test.d.ts.map +1 -0
- package/dist/server/quota-spawn-error.test.js +174 -0
- package/dist/server/quota-spawn-error.test.js.map +1 -0
- package/dist/server/quota.d.ts +66 -0
- package/dist/server/quota.d.ts.map +1 -0
- package/dist/server/quota.js +511 -0
- package/dist/server/quota.js.map +1 -0
- package/dist/server/runtime-config.d.ts +11 -0
- package/dist/server/runtime-config.d.ts.map +1 -0
- package/dist/server/runtime-config.js +380 -0
- package/dist/server/runtime-config.js.map +1 -0
- package/dist/server/runtime-config.test.d.ts +2 -0
- package/dist/server/runtime-config.test.d.ts.map +1 -0
- package/dist/server/runtime-config.test.js +367 -0
- package/dist/server/runtime-config.test.js.map +1 -0
- package/dist/server/skills.d.ts +8 -0
- package/dist/server/skills.d.ts.map +1 -0
- package/dist/server/skills.js +26 -0
- package/dist/server/skills.js.map +1 -0
- package/dist/server/test.d.ts +3 -0
- package/dist/server/test.d.ts.map +1 -0
- package/dist/server/test.js +458 -0
- package/dist/server/test.js.map +1 -0
- package/dist/server/test.remote.test.d.ts +2 -0
- package/dist/server/test.remote.test.d.ts.map +1 -0
- package/dist/server/test.remote.test.js +396 -0
- package/dist/server/test.remote.test.js.map +1 -0
- package/dist/ui/build-config.d.ts +5 -0
- package/dist/ui/build-config.d.ts.map +1 -0
- package/dist/ui/build-config.js +229 -0
- package/dist/ui/build-config.js.map +1 -0
- package/dist/ui/build-config.test.d.ts +2 -0
- package/dist/ui/build-config.test.d.ts.map +1 -0
- package/dist/ui/build-config.test.js +272 -0
- package/dist/ui/build-config.test.js.map +1 -0
- package/dist/ui/index.d.ts +4 -0
- package/dist/ui/index.d.ts.map +1 -0
- package/dist/ui/index.js +8 -0
- package/dist/ui/index.js.map +1 -0
- package/dist/ui/parse-stdout.d.ts +3 -0
- package/dist/ui/parse-stdout.d.ts.map +1 -0
- package/dist/ui/parse-stdout.js +265 -0
- package/dist/ui/parse-stdout.js.map +1 -0
- package/dist/ui/parse-stdout.test.d.ts +2 -0
- package/dist/ui/parse-stdout.test.d.ts.map +1 -0
- package/dist/ui/parse-stdout.test.js +77 -0
- package/dist/ui/parse-stdout.test.js.map +1 -0
- package/package.json +61 -0
- package/skills/agentmail/SKILL.md +70 -0
- package/skills/paperclip/SKILL.md +712 -0
- package/skills/paperclip/references/api-reference.md +1675 -0
- package/skills/paperclip/references/artifacts.md +158 -0
- package/skills/paperclip/references/cases.md +295 -0
- package/skills/paperclip/references/company-skills.md +266 -0
- package/skills/paperclip/references/issue-workspaces.md +80 -0
- package/skills/paperclip/references/routines.md +231 -0
- package/skills/paperclip/references/workflows.md +141 -0
- package/skills/paperclip/scripts/paperclip-upload-artifact.sh +592 -0
- package/skills/paperclip-board/SKILL.md +619 -0
- package/skills/paperclip-converting-plans-to-tasks/SKILL.md +60 -0
- package/skills/paperclip-create-agent/SKILL.md +179 -0
- package/skills/paperclip-create-agent/references/agent-instruction-templates.md +123 -0
- package/skills/paperclip-create-agent/references/agents/coder.md +64 -0
- package/skills/paperclip-create-agent/references/agents/qa.md +88 -0
- package/skills/paperclip-create-agent/references/agents/securityengineer.md +135 -0
- package/skills/paperclip-create-agent/references/agents/uxdesigner.md +115 -0
- package/skills/paperclip-create-agent/references/api-reference.md +110 -0
- package/skills/paperclip-create-agent/references/baseline-role-guide.md +168 -0
- package/skills/paperclip-create-agent/references/draft-review-checklist.md +95 -0
- package/skills/para-memory-files/SKILL.md +100 -0
- package/skills/para-memory-files/references/schemas.md +35 -0
- package/skills/slack/SKILL.md +65 -0
|
@@ -0,0 +1,1290 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { inferOpenAiCompatibleBiller } from "@tickernelz/paperclip-pro-adapter-utils";
|
|
5
|
+
import { buildCodexAuthInboundProvision } from "./codex-auth-merge-scripts.js";
|
|
6
|
+
import { copyBackCodexAuth } from "./codex-auth-copyback.js";
|
|
7
|
+
import { ensureCodexAuthCacheEntryDir, isCodexAuthCacheEnabled, resolveCodexAuthCacheEntryPath, selectVendCredential, } from "./codex-auth-cache.js";
|
|
8
|
+
import { adapterExecutionTargetIsRemote, adapterExecutionTargetRemoteCwd, overrideAdapterExecutionTargetRemoteCwd, adapterExecutionTargetSessionIdentity, adapterExecutionTargetSessionMatches, adapterExecutionTargetUsesPaperclipBridge, describeAdapterExecutionTarget, ensureAdapterExecutionTargetCommandResolvable, ensureAdapterExecutionTargetRuntimeCommandInstalled, prepareAdapterExecutionTargetRuntime, adapterExecutionTargetDuplexObservabilityRecorder, adapterExecutionTargetEnablesSandboxDuplexBridge, readAdapterExecutionTarget, resolveAdapterExecutionTargetTimeoutSec, resolveAdapterExecutionTargetCommandForLogs, runAdapterExecutionTargetProcess, runAdapterExecutionTargetShellCommand, startAdapterExecutionTargetPaperclipBridge, } from "@tickernelz/paperclip-pro-adapter-utils/execution-target";
|
|
9
|
+
import { asString, asNumber, parseObject, buildPaperclipEnv, buildInvocationEnvForLogs, ensureAbsoluteDirectory, ensurePaperclipSkillSymlink, ensurePathInEnv, refreshPaperclipWorkspaceEnvForExecution, isPaperclipSkillSourceMissing, readPaperclipRuntimeSkillEntries, readPaperclipIssueWorkModeFromContext, renderTemplate, renderPaperclipWakePrompt, selectPaperclipTaskMarkdown, isPaperclipRecoveryWakePayload, DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE, DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE, joinPromptSections, } from "@tickernelz/paperclip-pro-adapter-utils/server-utils";
|
|
10
|
+
import { parseLocalProcessFilesystemScope, parseLocalProcessSandboxExtraPaths, parseLocalProcessNetworkAllowlist, parseLocalProcessNetworkScope, } from "@tickernelz/paperclip-pro-adapter-utils/local-process-sandbox";
|
|
11
|
+
import { parseCodexJsonl, classifyCodexAuthRefreshFailure, extractCodexRetryNotBefore, isCodexHarnessCrash, isCodexProviderQuotaError, isCodexTransientUpstreamError, isCodexUnknownSessionError, } from "./parse.js";
|
|
12
|
+
import { codexHomeHasUsableAuth, evaluateCodexCredentialReadiness, isManagedCodexHomePath, pathExists, prepareManagedCodexHome, resolveManagedCodexHomeDir, resolveSharedCodexHomeDir, seedManagedCodexHome, stageCodexHomeForSync, mergeManagedCodexMcpGateways, writeManagedCodexMcpConfig, } from "./codex-home.js";
|
|
13
|
+
import { CODEX_SANDBOX_AUTH_EXISTS_COMMAND, CODEX_SANDBOX_AUTH_PRECEDENCE_WARNING, CODEX_SANDBOX_AUTH_PRECEDENCE_WARNING_LOG_LINE, resolveCodexAuthPrecedence, } from "./auth-precedence.js";
|
|
14
|
+
import { prepareCodexRuntimeConfig } from "./runtime-config.js";
|
|
15
|
+
import { resolveCodexDesiredSkillNames } from "./skills.js";
|
|
16
|
+
import { buildCodexExecArgs } from "./codex-args.js";
|
|
17
|
+
import { SANDBOX_INSTALL_COMMAND } from "../index.js";
|
|
18
|
+
import { CODEX_OUTPUT_INACTIVITY_MONITOR_SIGTERM_GRACE_MS, createCodexOutputInactivityMonitor, formatOutputInactivityMonitorErrorMessage, resolveCodexInactivityTimeout, } from "./output-inactivity-monitor.js";
|
|
19
|
+
import { CODEX_PROCESS_ACTIVITY_POLL_INTERVAL_MS, createCodexProcessActivityMonitor, } from "./process-activity-monitor.js";
|
|
20
|
+
import { createCodexAcpExecutor, resolveCodexExecutionEngineForRun, } from "./acp.js";
|
|
21
|
+
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
const executeCodexAcp = createCodexAcpExecutor();
|
|
23
|
+
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;
|
|
24
|
+
function stripCodexRolloutNoise(text) {
|
|
25
|
+
const parts = text.split(/\r?\n/);
|
|
26
|
+
const kept = [];
|
|
27
|
+
for (const part of parts) {
|
|
28
|
+
const trimmed = part.trim();
|
|
29
|
+
if (!trimmed) {
|
|
30
|
+
kept.push(part);
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (CODEX_ROLLOUT_NOISE_RE.test(trimmed))
|
|
34
|
+
continue;
|
|
35
|
+
kept.push(part);
|
|
36
|
+
}
|
|
37
|
+
return kept.join("\n");
|
|
38
|
+
}
|
|
39
|
+
function firstNonEmptyLine(text) {
|
|
40
|
+
return (text
|
|
41
|
+
.split(/\r?\n/)
|
|
42
|
+
.map((line) => line.trim())
|
|
43
|
+
.find(Boolean) ?? "");
|
|
44
|
+
}
|
|
45
|
+
// Benign stderr lines that never explain a nonzero exit and must not be
|
|
46
|
+
// surfaced as the run error: Codex always prints the YOLO approvals warning
|
|
47
|
+
// because this adapter passes the approvals-bypass flag itself, and
|
|
48
|
+
// "[paperclip] ..." lines are diagnostics the adapter injected (e.g. ACP
|
|
49
|
+
// fallback notes). Keep this list conservative so real errors are never
|
|
50
|
+
// skipped.
|
|
51
|
+
const BENIGN_CODEX_STDERR_LINE_RES = [
|
|
52
|
+
/^YOLO mode is enabled\b/i,
|
|
53
|
+
/^\[paperclip\]/,
|
|
54
|
+
];
|
|
55
|
+
function isBenignCodexStderrLine(line) {
|
|
56
|
+
return BENIGN_CODEX_STDERR_LINE_RES.some((re) => re.test(line));
|
|
57
|
+
}
|
|
58
|
+
export function firstMeaningfulStderrLine(text) {
|
|
59
|
+
const meaningful = text
|
|
60
|
+
.split(/\r?\n/)
|
|
61
|
+
.map((line) => line.trim())
|
|
62
|
+
.find((line) => line && !isBenignCodexStderrLine(line));
|
|
63
|
+
return meaningful ?? firstNonEmptyLine(text);
|
|
64
|
+
}
|
|
65
|
+
function signalCodexChild(target, signal) {
|
|
66
|
+
if (process.platform !== "win32" && target.processGroupId && target.processGroupId > 0) {
|
|
67
|
+
try {
|
|
68
|
+
process.kill(-target.processGroupId, signal);
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// Fall back to direct child signal if group signaling fails (e.g. group already gone).
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (target.pid && target.pid > 0) {
|
|
76
|
+
try {
|
|
77
|
+
process.kill(target.pid, signal);
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
function hasNonEmptyEnvValue(env, key) {
|
|
87
|
+
const raw = env[key];
|
|
88
|
+
return typeof raw === "string" && raw.trim().length > 0;
|
|
89
|
+
}
|
|
90
|
+
function resolveCodexBillingType(env) {
|
|
91
|
+
// Codex uses API-key auth when OPENAI_API_KEY is present; otherwise rely on local login/session auth.
|
|
92
|
+
return hasNonEmptyEnvValue(env, "OPENAI_API_KEY") ? "api" : "subscription";
|
|
93
|
+
}
|
|
94
|
+
function resolveCodexBiller(env, billingType) {
|
|
95
|
+
const openAiCompatibleBiller = inferOpenAiCompatibleBiller(env, "openai");
|
|
96
|
+
if (openAiCompatibleBiller === "openrouter")
|
|
97
|
+
return "openrouter";
|
|
98
|
+
return billingType === "subscription" ? "chatgpt" : openAiCompatibleBiller ?? "openai";
|
|
99
|
+
}
|
|
100
|
+
async function isLikelyPaperclipRepoRoot(candidate) {
|
|
101
|
+
const [hasWorkspace, hasPackageJson, hasServerDir, hasAdapterUtilsDir] = await Promise.all([
|
|
102
|
+
pathExists(path.join(candidate, "pnpm-workspace.yaml")),
|
|
103
|
+
pathExists(path.join(candidate, "package.json")),
|
|
104
|
+
pathExists(path.join(candidate, "server")),
|
|
105
|
+
pathExists(path.join(candidate, "packages", "adapter-utils")),
|
|
106
|
+
]);
|
|
107
|
+
return hasWorkspace && hasPackageJson && hasServerDir && hasAdapterUtilsDir;
|
|
108
|
+
}
|
|
109
|
+
async function isLikelyPaperclipRuntimeSkillPath(candidate, skillName, options = {}) {
|
|
110
|
+
if (path.basename(candidate) !== skillName)
|
|
111
|
+
return false;
|
|
112
|
+
const skillsRoot = path.dirname(candidate);
|
|
113
|
+
if (path.basename(skillsRoot) !== "skills")
|
|
114
|
+
return false;
|
|
115
|
+
if (options.requireSkillMarkdown !== false && !(await pathExists(path.join(candidate, "SKILL.md")))) {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
let cursor = path.dirname(skillsRoot);
|
|
119
|
+
for (let depth = 0; depth < 6; depth += 1) {
|
|
120
|
+
if (await isLikelyPaperclipRepoRoot(cursor))
|
|
121
|
+
return true;
|
|
122
|
+
const parent = path.dirname(cursor);
|
|
123
|
+
if (parent === cursor)
|
|
124
|
+
break;
|
|
125
|
+
cursor = parent;
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
async function pruneBrokenUnavailablePaperclipSkillSymlinks(skillsHome, allowedSkillNames, onLog) {
|
|
130
|
+
const allowed = new Set(Array.from(allowedSkillNames));
|
|
131
|
+
const entries = await fs.readdir(skillsHome, { withFileTypes: true }).catch(() => []);
|
|
132
|
+
for (const entry of entries) {
|
|
133
|
+
if (allowed.has(entry.name) || !entry.isSymbolicLink())
|
|
134
|
+
continue;
|
|
135
|
+
const target = path.join(skillsHome, entry.name);
|
|
136
|
+
const linkedPath = await fs.readlink(target).catch(() => null);
|
|
137
|
+
if (!linkedPath)
|
|
138
|
+
continue;
|
|
139
|
+
const resolvedLinkedPath = path.resolve(path.dirname(target), linkedPath);
|
|
140
|
+
if (await pathExists(resolvedLinkedPath))
|
|
141
|
+
continue;
|
|
142
|
+
if (!(await isLikelyPaperclipRuntimeSkillPath(resolvedLinkedPath, entry.name, {
|
|
143
|
+
requireSkillMarkdown: false,
|
|
144
|
+
}))) {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
await fs.unlink(target).catch(() => { });
|
|
148
|
+
await onLog("stdout", `[paperclip] Removed stale Codex skill "${entry.name}" from ${skillsHome}\n`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function resolveCodexSkillsDir(codexHome) {
|
|
152
|
+
return path.join(codexHome, "skills");
|
|
153
|
+
}
|
|
154
|
+
function readCodexTransientFallbackMode(context) {
|
|
155
|
+
const value = asString(context.codexTransientFallbackMode, "").trim();
|
|
156
|
+
switch (value) {
|
|
157
|
+
case "same_session":
|
|
158
|
+
case "safer_invocation":
|
|
159
|
+
case "fresh_session":
|
|
160
|
+
case "fresh_session_safer_invocation":
|
|
161
|
+
return value;
|
|
162
|
+
default:
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function fallbackModeUsesSaferInvocation(mode) {
|
|
167
|
+
return mode === "safer_invocation" || mode === "fresh_session_safer_invocation";
|
|
168
|
+
}
|
|
169
|
+
function fallbackModeUsesFreshSession(mode) {
|
|
170
|
+
return mode === "fresh_session" || mode === "fresh_session_safer_invocation";
|
|
171
|
+
}
|
|
172
|
+
function managedMcpGatewaysFromContext(context) {
|
|
173
|
+
const managedMcp = parseObject(context.paperclipManagedMcp);
|
|
174
|
+
if (managedMcp.managedMcpOnly !== true)
|
|
175
|
+
return [];
|
|
176
|
+
const gateways = Array.isArray(managedMcp.gateways) ? managedMcp.gateways : [];
|
|
177
|
+
return gateways
|
|
178
|
+
.map((raw) => {
|
|
179
|
+
const gateway = parseObject(raw);
|
|
180
|
+
const name = asString(gateway.name, "").trim();
|
|
181
|
+
const endpointPath = asString(gateway.endpointPath, "").trim();
|
|
182
|
+
const bearerToken = asString(gateway.bearerToken, "").trim();
|
|
183
|
+
if (!name || !endpointPath || !bearerToken)
|
|
184
|
+
return null;
|
|
185
|
+
return { name, endpointPath, bearerToken };
|
|
186
|
+
})
|
|
187
|
+
.filter((gateway) => Boolean(gateway));
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Probe the sandbox for its own `~/.codex/auth.json`. "unknown" means the
|
|
191
|
+
* probe itself failed (timeout, transport error, or a shell failure other
|
|
192
|
+
* than `test`'s clean false) — callers that gate on the result must not
|
|
193
|
+
* report that as a missing credential.
|
|
194
|
+
*/
|
|
195
|
+
async function probeSandboxCodexAuthJson(input) {
|
|
196
|
+
if (!input.target || input.target.kind !== "remote" || input.target.transport !== "sandbox") {
|
|
197
|
+
return "absent";
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
const result = await runAdapterExecutionTargetShellCommand(input.runId, input.target, CODEX_SANDBOX_AUTH_EXISTS_COMMAND, {
|
|
201
|
+
cwd: input.cwd,
|
|
202
|
+
env: {},
|
|
203
|
+
timeoutSec: 5,
|
|
204
|
+
});
|
|
205
|
+
if (result.timedOut)
|
|
206
|
+
return "unknown";
|
|
207
|
+
if (result.exitCode === 0)
|
|
208
|
+
return "present";
|
|
209
|
+
return result.exitCode === 1 ? "absent" : "unknown";
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return "unknown";
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async function sandboxCodexAuthJsonExists(input) {
|
|
216
|
+
return (await probeSandboxCodexAuthJson(input)) === "present";
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Execute-time credential gate. A managed home with no host-side credentials
|
|
220
|
+
* is still launchable when the run targets a sandbox whose image carries its
|
|
221
|
+
* own Codex login (`~/.codex/auth.json` baked in during image setup): the
|
|
222
|
+
* inbound auth merge ships the credential-less host home and keeps the
|
|
223
|
+
* sandbox's credential, so the host is not a required credential source —
|
|
224
|
+
* on managed cloud hosts a local Codex login never exists at all. The
|
|
225
|
+
* sandbox is probed before the run is declared unlaunchable; non-sandbox
|
|
226
|
+
* targets keep the strict host-side requirement.
|
|
227
|
+
*/
|
|
228
|
+
export async function assertCodexCredentialsLaunchable(input) {
|
|
229
|
+
const credentialReadiness = await evaluateCodexCredentialReadiness({
|
|
230
|
+
env: input.env ?? process.env,
|
|
231
|
+
companyId: input.companyId,
|
|
232
|
+
configuredCodexHome: input.configuredCodexHome,
|
|
233
|
+
configuredApiKey: input.configuredApiKey,
|
|
234
|
+
});
|
|
235
|
+
if (!credentialReadiness.managed || credentialReadiness.ready)
|
|
236
|
+
return;
|
|
237
|
+
const targetIsSandbox = input.target?.kind === "remote" && input.target.transport === "sandbox";
|
|
238
|
+
if (targetIsSandbox) {
|
|
239
|
+
const sandboxAuthJson = await probeSandboxCodexAuthJson({
|
|
240
|
+
runId: input.runId,
|
|
241
|
+
target: input.target,
|
|
242
|
+
cwd: input.cwd,
|
|
243
|
+
});
|
|
244
|
+
if (sandboxAuthJson === "present") {
|
|
245
|
+
await input.onLog("stdout", `Using the sandbox's own Codex login; managed home "${input.effectiveCodexHome}" has no host credentials.\n`);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (sandboxAuthJson === "unknown") {
|
|
249
|
+
// The probe failing is an operational problem, not evidence that the
|
|
250
|
+
// sandbox lacks a login — proceeding lets a genuinely credentialed
|
|
251
|
+
// sandbox run, and a credential-less one still fails at Codex's first
|
|
252
|
+
// request with the provider's own error.
|
|
253
|
+
await input.onLog("stderr", `Could not verify the sandbox's Codex login (probe failed); proceeding. ` +
|
|
254
|
+
`If the sandbox has no credentials, Codex will fail at its first request.\n`);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
throw new Error(`no Codex credentials provisioned for managed home "${input.effectiveCodexHome}" ` +
|
|
258
|
+
`(no usable auth.json, OPENAI_API_KEY is empty, and the sandbox has no Codex login). ` +
|
|
259
|
+
`Use a sandbox image that is signed in to Codex, configure a per-agent OPENAI_API_KEY, ` +
|
|
260
|
+
`or sign in to Codex on the host with a ChatGPT subscription.`);
|
|
261
|
+
}
|
|
262
|
+
throw new Error(`no Codex credentials provisioned for managed home "${input.effectiveCodexHome}" ` +
|
|
263
|
+
`(no usable auth.json and OPENAI_API_KEY is empty). ` +
|
|
264
|
+
`Sign in to Codex on the host with a ChatGPT subscription, or configure a per-agent ` +
|
|
265
|
+
`OPENAI_API_KEY.`);
|
|
266
|
+
}
|
|
267
|
+
async function emitSandboxAuthPrecedenceWarningIfNeeded(input) {
|
|
268
|
+
if (!input.target || input.target.kind !== "remote" || input.target.transport !== "sandbox") {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const sandboxAuthJson = await sandboxCodexAuthJsonExists({
|
|
272
|
+
runId: input.runId,
|
|
273
|
+
target: input.target,
|
|
274
|
+
cwd: input.cwd,
|
|
275
|
+
});
|
|
276
|
+
const resolution = resolveCodexAuthPrecedence({
|
|
277
|
+
configuredApiKey: input.configuredApiKey,
|
|
278
|
+
hostAuthJson: input.hostAuthJson,
|
|
279
|
+
sandboxAuthJson,
|
|
280
|
+
});
|
|
281
|
+
if (!resolution.shouldWarn)
|
|
282
|
+
return;
|
|
283
|
+
await input.onLog("stderr", CODEX_SANDBOX_AUTH_PRECEDENCE_WARNING_LOG_LINE);
|
|
284
|
+
await input.onEvent?.({
|
|
285
|
+
eventType: "codex.auth_precedence_warning",
|
|
286
|
+
stream: "system",
|
|
287
|
+
level: "warn",
|
|
288
|
+
message: CODEX_SANDBOX_AUTH_PRECEDENCE_WARNING,
|
|
289
|
+
payload: {
|
|
290
|
+
configuredApiKey: input.configuredApiKey,
|
|
291
|
+
hostAuthJson: input.hostAuthJson,
|
|
292
|
+
sandboxAuthJson,
|
|
293
|
+
winner: resolution.winner,
|
|
294
|
+
sandboxLoginShadowed: resolution.sandboxLoginShadowed,
|
|
295
|
+
},
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
function buildCodexTransientHandoffNote(input) {
|
|
299
|
+
return [
|
|
300
|
+
"Paperclip session handoff:",
|
|
301
|
+
input.previousSessionId ? `- Previous session: ${input.previousSessionId}` : "",
|
|
302
|
+
"- Rotation reason: repeated Codex transient remote-compaction failures",
|
|
303
|
+
`- Fallback mode: ${input.fallbackMode}`,
|
|
304
|
+
input.continuationSummaryBody
|
|
305
|
+
? `- Issue continuation summary: ${input.continuationSummaryBody.slice(0, 1_500)}`
|
|
306
|
+
: "",
|
|
307
|
+
"Continue from the current task state. Rebuild only the minimum context you need.",
|
|
308
|
+
]
|
|
309
|
+
.filter(Boolean)
|
|
310
|
+
.join("\n");
|
|
311
|
+
}
|
|
312
|
+
export async function ensureCodexSkillsInjected(onLog, options = {}) {
|
|
313
|
+
const allSkillsEntries = options.skillsEntries
|
|
314
|
+
?? (await readPaperclipRuntimeSkillEntries({}, __moduleDir)).filter((entry) => !isPaperclipSkillSourceMissing(entry));
|
|
315
|
+
const desiredSkillNames = options.desiredSkillNames ?? allSkillsEntries.map((entry) => entry.key);
|
|
316
|
+
const desiredSet = new Set(desiredSkillNames);
|
|
317
|
+
const skillsEntries = allSkillsEntries.filter((entry) => desiredSet.has(entry.key));
|
|
318
|
+
if (skillsEntries.length === 0)
|
|
319
|
+
return;
|
|
320
|
+
const skillsHome = options.skillsHome ?? resolveCodexSkillsDir(resolveSharedCodexHomeDir());
|
|
321
|
+
await fs.mkdir(skillsHome, { recursive: true });
|
|
322
|
+
const linkSkill = options.linkSkill;
|
|
323
|
+
for (const entry of skillsEntries) {
|
|
324
|
+
const target = path.join(skillsHome, entry.runtimeName);
|
|
325
|
+
try {
|
|
326
|
+
const existing = await fs.lstat(target).catch(() => null);
|
|
327
|
+
if (existing?.isSymbolicLink()) {
|
|
328
|
+
const linkedPath = await fs.readlink(target).catch(() => null);
|
|
329
|
+
const resolvedLinkedPath = linkedPath
|
|
330
|
+
? path.resolve(path.dirname(target), linkedPath)
|
|
331
|
+
: null;
|
|
332
|
+
if (resolvedLinkedPath &&
|
|
333
|
+
resolvedLinkedPath !== entry.source &&
|
|
334
|
+
(await isLikelyPaperclipRuntimeSkillPath(resolvedLinkedPath, entry.runtimeName))) {
|
|
335
|
+
await fs.unlink(target);
|
|
336
|
+
if (linkSkill) {
|
|
337
|
+
await linkSkill(entry.source, target);
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
await fs.symlink(entry.source, target);
|
|
341
|
+
}
|
|
342
|
+
await onLog("stdout", `[paperclip] Repaired Codex skill "${entry.runtimeName}" into ${skillsHome}\n`);
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
const result = await ensurePaperclipSkillSymlink(entry.source, target, linkSkill);
|
|
347
|
+
if (result === "skipped")
|
|
348
|
+
continue;
|
|
349
|
+
await onLog("stdout", `[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Codex skill "${entry.runtimeName}" into ${skillsHome}\n`);
|
|
350
|
+
}
|
|
351
|
+
catch (err) {
|
|
352
|
+
await onLog("stderr", `[paperclip] Failed to inject Codex skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
await pruneBrokenUnavailablePaperclipSkillSymlinks(skillsHome, skillsEntries.map((entry) => entry.runtimeName), onLog);
|
|
356
|
+
}
|
|
357
|
+
export async function execute(ctx) {
|
|
358
|
+
const engineSelection = await resolveCodexExecutionEngineForRun(ctx);
|
|
359
|
+
if (engineSelection.unavailableReason) {
|
|
360
|
+
return {
|
|
361
|
+
exitCode: 1,
|
|
362
|
+
signal: null,
|
|
363
|
+
timedOut: false,
|
|
364
|
+
errorCode: "adapter_engine_unavailable",
|
|
365
|
+
errorMessage: engineSelection.unavailableReason,
|
|
366
|
+
resultJson: {
|
|
367
|
+
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
368
|
+
},
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
if (engineSelection.engine === "acp") {
|
|
372
|
+
return executeCodexAcp(ctx);
|
|
373
|
+
}
|
|
374
|
+
const { runId, agent, runtime, config, context, onLog, onMeta, onEvent, onSpawn, authToken } = ctx;
|
|
375
|
+
const promptTemplate = asString(config.promptTemplate, context.conversationMode === true
|
|
376
|
+
? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
|
|
377
|
+
: DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE);
|
|
378
|
+
const command = asString(config.command, "codex");
|
|
379
|
+
const model = asString(config.model, "");
|
|
380
|
+
const workspaceContext = parseObject(context.paperclipWorkspace);
|
|
381
|
+
const workspaceCwd = asString(workspaceContext.cwd, "");
|
|
382
|
+
const workspaceSource = asString(workspaceContext.source, "");
|
|
383
|
+
const workspaceStrategy = asString(workspaceContext.strategy, "");
|
|
384
|
+
const workspaceId = asString(workspaceContext.workspaceId, "");
|
|
385
|
+
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
|
|
386
|
+
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
|
387
|
+
const workspaceBranch = asString(workspaceContext.branchName, "");
|
|
388
|
+
const workspaceWorktreePath = asString(workspaceContext.worktreePath, "");
|
|
389
|
+
const agentHome = asString(workspaceContext.agentHome, "");
|
|
390
|
+
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
|
391
|
+
? context.paperclipWorkspaces.filter((value) => typeof value === "object" && value !== null)
|
|
392
|
+
: [];
|
|
393
|
+
const runtimeServiceIntents = Array.isArray(context.paperclipRuntimeServiceIntents)
|
|
394
|
+
? context.paperclipRuntimeServiceIntents.filter((value) => typeof value === "object" && value !== null)
|
|
395
|
+
: [];
|
|
396
|
+
const runtimeServices = Array.isArray(context.paperclipRuntimeServices)
|
|
397
|
+
? context.paperclipRuntimeServices.filter((value) => typeof value === "object" && value !== null)
|
|
398
|
+
: [];
|
|
399
|
+
const runtimePrimaryUrl = asString(context.paperclipRuntimePrimaryUrl, "");
|
|
400
|
+
const executionTarget = readAdapterExecutionTarget({
|
|
401
|
+
executionTarget: ctx.executionTarget,
|
|
402
|
+
legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
|
|
403
|
+
});
|
|
404
|
+
const targetWorkspaceRealization = executionTarget?.workspaceRealization ?? null;
|
|
405
|
+
const configuredCwd = asString(config.cwd, "");
|
|
406
|
+
const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
|
|
407
|
+
const effectiveWorkspaceCwd = targetWorkspaceRealization?.mode === "in_place"
|
|
408
|
+
? targetWorkspaceRealization.authoritativeRoot
|
|
409
|
+
: useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
|
|
410
|
+
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
|
|
411
|
+
const envConfig = parseObject(config.env);
|
|
412
|
+
const executionTargetIsRemote = adapterExecutionTargetIsRemote(executionTarget);
|
|
413
|
+
let configuredCodexHome = typeof envConfig.CODEX_HOME === "string" && envConfig.CODEX_HOME.trim().length > 0
|
|
414
|
+
? path.resolve(envConfig.CODEX_HOME.trim())
|
|
415
|
+
: null;
|
|
416
|
+
const connectorSourceHome = configuredCodexHome;
|
|
417
|
+
const connectorSkillDigest = typeof config.paperclipConnectorSkillDigest === "string"
|
|
418
|
+
&& /^[a-f0-9]{64}$/.test(config.paperclipConnectorSkillDigest) ? config.paperclipConnectorSkillDigest : null;
|
|
419
|
+
if (connectorSkillDigest) {
|
|
420
|
+
// Never mount assignment-specific skills into the shared company/user home.
|
|
421
|
+
// A different skill revision gets a new home, so revoked/changed resources
|
|
422
|
+
// cannot survive as stale symlinks or bleed into another agent's session.
|
|
423
|
+
configuredCodexHome = path.join(resolveManagedCodexHomeDir(process.env, agent.companyId), "connector-runtimes", agent.id, connectorSkillDigest);
|
|
424
|
+
}
|
|
425
|
+
const codexSkillEntries = (await readPaperclipRuntimeSkillEntries(config, __moduleDir))
|
|
426
|
+
// A missing-source entry would become a dangling skill symlink; skip it.
|
|
427
|
+
.filter((entry) => !isPaperclipSkillSourceMissing(entry));
|
|
428
|
+
const desiredSkillNames = resolveCodexDesiredSkillNames(config, codexSkillEntries);
|
|
429
|
+
if (!executionTargetIsRemote) {
|
|
430
|
+
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
|
|
431
|
+
}
|
|
432
|
+
const configuredOpenAiApiKey = typeof envConfig.OPENAI_API_KEY === "string" && envConfig.OPENAI_API_KEY.trim().length > 0
|
|
433
|
+
? envConfig.OPENAI_API_KEY.trim()
|
|
434
|
+
: null;
|
|
435
|
+
// A configured CODEX_HOME that lives under the Paperclip-managed company tree
|
|
436
|
+
// (the per-agent home set by the server isolation guard) still needs auth
|
|
437
|
+
// seeded — it ships with no credentials and OPENAI_API_KEY="" by default.
|
|
438
|
+
// Only a genuine external/user-supplied override is treated as self-managed
|
|
439
|
+
// and left untouched.
|
|
440
|
+
const configuredHomeIsManaged = configuredCodexHome != null &&
|
|
441
|
+
isManagedCodexHomePath(process.env, agent.companyId, configuredCodexHome);
|
|
442
|
+
// Identity-anchored cache vend (host to sandbox). Before the managed home is
|
|
443
|
+
// seeded from the shared source `auth.json`, refresh the shared credential with
|
|
444
|
+
// a strictly-newer cached copy of the SAME identity. The vend reads the host
|
|
445
|
+
// identity first and resolves only that identity's cache slot; when the host
|
|
446
|
+
// holds no credential it does nothing (no random pick). This keeps the change
|
|
447
|
+
// additive: the managed home still symlinks the shared `auth.json`, now at its
|
|
448
|
+
// freshest same-identity copy. The off-switch (default on) skips the vend.
|
|
449
|
+
if (!config.managedAiConnection && isCodexAuthCacheEnabled(process.env)) {
|
|
450
|
+
const sharedHomeAuthPath = path.join(resolveSharedCodexHomeDir(process.env), "auth.json");
|
|
451
|
+
// This caller reads `process.env` directly and holds no separate `env`
|
|
452
|
+
// object, so `selectVendCredential` falls back to its own `process.env`
|
|
453
|
+
// default for the merge lock root.
|
|
454
|
+
await selectVendCredential(sharedHomeAuthPath, (accountId) => resolveCodexAuthCacheEntryPath(process.env, accountId, agent.companyId), (line) => onLog("stdout", `${line}\n`)).catch(async (error) => {
|
|
455
|
+
// The vend is best-effort and additive. A vend failure must never block a
|
|
456
|
+
// run: log and fall through to seed from the unrefreshed shared credential.
|
|
457
|
+
await onLog("stderr", `[paperclip] Codex auth cache: vend skipped after an error; using the shared credential as-is.\n`);
|
|
458
|
+
void error;
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
if (configuredCodexHome == null || (connectorSkillDigest && connectorSourceHome == null)) {
|
|
462
|
+
await prepareManagedCodexHome(process.env, onLog, agent.companyId, {
|
|
463
|
+
apiKey: configuredOpenAiApiKey,
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
if (configuredHomeIsManaged && configuredCodexHome) {
|
|
467
|
+
const seedEnv = connectorSkillDigest ? {
|
|
468
|
+
...process.env, CODEX_HOME: connectorSourceHome ?? resolveManagedCodexHomeDir(process.env, agent.companyId),
|
|
469
|
+
} : process.env;
|
|
470
|
+
await seedManagedCodexHome(configuredCodexHome, seedEnv, onLog, {
|
|
471
|
+
apiKey: configuredOpenAiApiKey,
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
const defaultCodexHome = resolveManagedCodexHomeDir(process.env, agent.companyId);
|
|
475
|
+
const effectiveCodexHome = configuredCodexHome ?? defaultCodexHome;
|
|
476
|
+
await fs.mkdir(effectiveCodexHome, { recursive: true });
|
|
477
|
+
// Never launch a managed CODEX_HOME with no credentials. Without auth.json
|
|
478
|
+
// and with OPENAI_API_KEY="" the provider rejects every request with
|
|
479
|
+
// "401 Missing bearer"; fail fast with a clear adapter error instead of
|
|
480
|
+
// emitting unauthenticated calls. External overrides manage their own auth.
|
|
481
|
+
// This is the execute-time backstop for the control plane's pre-dispatch
|
|
482
|
+
// configuration-incomplete gate (see server heartbeat); both decide host
|
|
483
|
+
// readiness through the same `evaluateCodexCredentialReadiness` predicate,
|
|
484
|
+
// and sandbox targets are additionally allowed to supply their own login
|
|
485
|
+
// (the pre-dispatch gate defers sandbox-destined runs here for exactly that
|
|
486
|
+
// probe).
|
|
487
|
+
await assertCodexCredentialsLaunchable({
|
|
488
|
+
runId,
|
|
489
|
+
companyId: agent.companyId,
|
|
490
|
+
configuredCodexHome,
|
|
491
|
+
configuredApiKey: configuredOpenAiApiKey,
|
|
492
|
+
effectiveCodexHome,
|
|
493
|
+
target: executionTarget,
|
|
494
|
+
cwd,
|
|
495
|
+
onLog,
|
|
496
|
+
});
|
|
497
|
+
// Merge custom model providers (PAPERCLIP_CODEX_PROVIDERS) into the managed
|
|
498
|
+
// CODEX_HOME's config.toml BEFORE the home is shipped to a remote execution
|
|
499
|
+
// target, so both local and sandboxed Codex processes pick up the routing.
|
|
500
|
+
// An explicit env.CODEX_HOME override is treated as user-managed and skipped.
|
|
501
|
+
const envConfigStrings = Object.fromEntries(Object.entries(envConfig).filter((entry) => typeof entry[1] === "string"));
|
|
502
|
+
const preparedRuntimeConfig = await prepareCodexRuntimeConfig({
|
|
503
|
+
env: envConfigStrings,
|
|
504
|
+
codexHome: configuredCodexHome ? null : effectiveCodexHome,
|
|
505
|
+
});
|
|
506
|
+
// Curated allowlist dir staged for the remote `home` asset (see below). Held
|
|
507
|
+
// here so the outer `finally` can remove it on every exit path (teardown and
|
|
508
|
+
// error), never only the happy path.
|
|
509
|
+
let stagedCodexHomeDir = null;
|
|
510
|
+
try {
|
|
511
|
+
for (const note of preparedRuntimeConfig.notes) {
|
|
512
|
+
await onLog("stdout", `[paperclip] ${note}\n`);
|
|
513
|
+
}
|
|
514
|
+
const paperclipBaseEnv = buildPaperclipEnv(agent);
|
|
515
|
+
const runtimeMcpGateways = (ctx.runtimeMcp?.getServers() ?? []).map((server) => ({
|
|
516
|
+
name: server.name,
|
|
517
|
+
endpointPath: server.url,
|
|
518
|
+
bearerToken: server.token,
|
|
519
|
+
}));
|
|
520
|
+
const managedMcpGateways = mergeManagedCodexMcpGateways(runtimeMcpGateways, managedMcpGatewaysFromContext(context));
|
|
521
|
+
const managedMcp = await writeManagedCodexMcpConfig({
|
|
522
|
+
codexHome: effectiveCodexHome,
|
|
523
|
+
apiBaseUrl: paperclipBaseEnv.PAPERCLIP_API_URL,
|
|
524
|
+
gateways: managedMcpGateways,
|
|
525
|
+
});
|
|
526
|
+
if (managedMcpGateways.length > 0) {
|
|
527
|
+
await onLog("stdout", `[paperclip] Wrote ${managedMcpGateways.length} managed MCP gateway(s) into Codex config "${managedMcp.configPath}".\n`);
|
|
528
|
+
}
|
|
529
|
+
for (const warning of managedMcp.warnings) {
|
|
530
|
+
await onLog("stderr", `[paperclip] ${warning}\n`);
|
|
531
|
+
}
|
|
532
|
+
// Inject skills into the same CODEX_HOME that Codex will actually run with
|
|
533
|
+
// (managed home in the default case, or an explicit override from adapter config).
|
|
534
|
+
const codexSkillsDir = resolveCodexSkillsDir(effectiveCodexHome);
|
|
535
|
+
await ensureCodexSkillsInjected(onLog, {
|
|
536
|
+
skillsHome: codexSkillsDir,
|
|
537
|
+
skillsEntries: codexSkillEntries,
|
|
538
|
+
desiredSkillNames,
|
|
539
|
+
});
|
|
540
|
+
const timeoutSec = resolveAdapterExecutionTargetTimeoutSec(executionTarget, asNumber(config.timeoutSec, 0));
|
|
541
|
+
const graceSec = asNumber(config.graceSec, 20);
|
|
542
|
+
let effectiveExecutionCwd = targetWorkspaceRealization?.mode === "in_place"
|
|
543
|
+
? targetWorkspaceRealization.authoritativeRoot
|
|
544
|
+
: adapterExecutionTargetRemoteCwd(executionTarget, cwd);
|
|
545
|
+
const preparedExecutionTargetRuntime = executionTargetIsRemote
|
|
546
|
+
? await (async () => {
|
|
547
|
+
await onLog("stdout", `[paperclip] Syncing ${targetWorkspaceRealization?.mode === "in_place" ? "CODEX_HOME" : "workspace and CODEX_HOME"} to ${describeAdapterExecutionTarget(executionTarget)}.\n`);
|
|
548
|
+
// Stage only the files Codex actually needs into a curated temp dir and
|
|
549
|
+
// ship THAT as the `home` asset, instead of the whole managed
|
|
550
|
+
// CODEX_HOME + a name denylist. Staged AFTER the config.toml rewrites
|
|
551
|
+
// (provider merge + MCP block splice above) and skills injection, so the
|
|
552
|
+
// staged config.toml/skills reflect their final state. Symlinks (incl.
|
|
553
|
+
// the single-use `auth.json`) are dereferenced to bytes. This drops the
|
|
554
|
+
// large runtime state (`sessions/`, `*.sqlite`, `plugins/`, …) that the
|
|
555
|
+
// 4-name denylist missed and that a sandbox run never needs.
|
|
556
|
+
stagedCodexHomeDir = await stageCodexHomeForSync(effectiveCodexHome, { runId });
|
|
557
|
+
return await prepareAdapterExecutionTargetRuntime({
|
|
558
|
+
runId,
|
|
559
|
+
target: executionTarget,
|
|
560
|
+
adapterKey: "codex",
|
|
561
|
+
timeoutSec,
|
|
562
|
+
workspaceLocalDir: cwd,
|
|
563
|
+
workspaceRemoteDir: targetWorkspaceRealization?.mode === "in_place"
|
|
564
|
+
? targetWorkspaceRealization.authoritativeRoot
|
|
565
|
+
: undefined,
|
|
566
|
+
syncWorkspace: targetWorkspaceRealization?.mode !== "in_place",
|
|
567
|
+
installCommand: SANDBOX_INSTALL_COMMAND,
|
|
568
|
+
detectCommand: command,
|
|
569
|
+
onProgress: (line) => onLog("stdout", line),
|
|
570
|
+
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
571
|
+
assets: [
|
|
572
|
+
{
|
|
573
|
+
key: "home",
|
|
574
|
+
localDir: stagedCodexHomeDir,
|
|
575
|
+
followSymlinks: true,
|
|
576
|
+
// Inbound (host→sandbox) auth-merge contribution: stages the two
|
|
577
|
+
// merge scripts and runs the merge-extract command so a sandbox
|
|
578
|
+
// that already carries a Codex `auth.json` keeps whichever
|
|
579
|
+
// credential is newer. The sandbox runtime core stays adapter-
|
|
580
|
+
// agnostic — it just invokes this generic `provision` seam.
|
|
581
|
+
provision: buildCodexAuthInboundProvision(),
|
|
582
|
+
// Outbound (sandbox→host) auth copy-back contribution: at
|
|
583
|
+
// teardown, read the sandbox's `auth.json` and — guarded by the
|
|
584
|
+
// same direction-agnostic decision predicate under a directory
|
|
585
|
+
// lock — atomically install it onto the shared host credential
|
|
586
|
+
// when it is a strictly-newer same-identity subscription copy.
|
|
587
|
+
// The sandbox core stays adapter-agnostic; it just awaits this
|
|
588
|
+
// generic `restore` seam per asset before destroying the sandbox.
|
|
589
|
+
// Target is the shared symlink SOURCE (what managed homes point
|
|
590
|
+
// `auth.json` at), not the in-sandbox symlink.
|
|
591
|
+
restore: async ({ assetDir, readFile }) => void (await copyBackCodexAuth({
|
|
592
|
+
readSandboxAuth: () => readFile(path.posix.join(assetDir, "auth.json")),
|
|
593
|
+
hostAuthPath: path.join(config.managedAiConnection ? effectiveCodexHome : resolveSharedCodexHomeDir(process.env), "auth.json"),
|
|
594
|
+
log: (line) => onLog("stdout", `${line}\n`),
|
|
595
|
+
// Additive cache write (sandbox to host): also cache the
|
|
596
|
+
// sandbox subscription credential in its per-identity slot,
|
|
597
|
+
// keyed by the real `account_id`. Company-scoped root; the
|
|
598
|
+
// helper ensures the slot directory private and containment-
|
|
599
|
+
// guarded. The off-switch (default on) is read inside.
|
|
600
|
+
resolveCacheEntryPath: config.managedAiConnection ? undefined : (accountId) => ensureCodexAuthCacheEntryDir(process.env, accountId, agent.companyId),
|
|
601
|
+
env: process.env,
|
|
602
|
+
})),
|
|
603
|
+
// No `exclude` denylist: `stagedCodexHomeDir` already contains
|
|
604
|
+
// ONLY the allowlisted files (auth/config/skills), so there is
|
|
605
|
+
// nothing to filter out.
|
|
606
|
+
},
|
|
607
|
+
],
|
|
608
|
+
});
|
|
609
|
+
})()
|
|
610
|
+
: null;
|
|
611
|
+
if (preparedExecutionTargetRuntime?.workspaceRemoteDir) {
|
|
612
|
+
effectiveExecutionCwd = preparedExecutionTargetRuntime.workspaceRemoteDir;
|
|
613
|
+
}
|
|
614
|
+
const runtimeExecutionTarget = overrideAdapterExecutionTargetRemoteCwd(executionTarget, effectiveExecutionCwd);
|
|
615
|
+
const executionTargetIsSandbox = runtimeExecutionTarget?.kind === "remote" && runtimeExecutionTarget.transport === "sandbox";
|
|
616
|
+
const restoreRemoteWorkspace = preparedExecutionTargetRuntime
|
|
617
|
+
? () => preparedExecutionTargetRuntime.restoreWorkspace((line) => onLog("stdout", line))
|
|
618
|
+
: null;
|
|
619
|
+
let paperclipBridge = null;
|
|
620
|
+
const remoteCodexHome = executionTargetIsRemote
|
|
621
|
+
? preparedExecutionTargetRuntime?.assetDirs.home ??
|
|
622
|
+
path.posix.join(effectiveExecutionCwd, ".paperclip-runtime", "codex", "home")
|
|
623
|
+
: null;
|
|
624
|
+
await emitSandboxAuthPrecedenceWarningIfNeeded({
|
|
625
|
+
runId,
|
|
626
|
+
target: runtimeExecutionTarget,
|
|
627
|
+
cwd: effectiveExecutionCwd,
|
|
628
|
+
configuredApiKey: Boolean(configuredOpenAiApiKey),
|
|
629
|
+
hostAuthJson: await codexHomeHasUsableAuth(effectiveCodexHome),
|
|
630
|
+
onLog,
|
|
631
|
+
onEvent,
|
|
632
|
+
});
|
|
633
|
+
const env = { ...paperclipBaseEnv };
|
|
634
|
+
env.PAPERCLIP_RUN_ID = runId;
|
|
635
|
+
const wakeTaskId = (typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
|
|
636
|
+
(typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim()) ||
|
|
637
|
+
null;
|
|
638
|
+
const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0
|
|
639
|
+
? context.wakeReason.trim()
|
|
640
|
+
: null;
|
|
641
|
+
const wakeCommentId = (typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim()) ||
|
|
642
|
+
(typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim()) ||
|
|
643
|
+
null;
|
|
644
|
+
const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0
|
|
645
|
+
? context.approvalId.trim()
|
|
646
|
+
: null;
|
|
647
|
+
const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0
|
|
648
|
+
? context.approvalStatus.trim()
|
|
649
|
+
: null;
|
|
650
|
+
const linkedIssueIds = Array.isArray(context.issueIds)
|
|
651
|
+
? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0)
|
|
652
|
+
: [];
|
|
653
|
+
const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
|
|
654
|
+
if (wakeTaskId) {
|
|
655
|
+
env.PAPERCLIP_TASK_ID = wakeTaskId;
|
|
656
|
+
}
|
|
657
|
+
if (issueWorkMode) {
|
|
658
|
+
env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
|
|
659
|
+
}
|
|
660
|
+
if (wakeReason) {
|
|
661
|
+
env.PAPERCLIP_WAKE_REASON = wakeReason;
|
|
662
|
+
}
|
|
663
|
+
if (wakeCommentId) {
|
|
664
|
+
env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
|
|
665
|
+
}
|
|
666
|
+
if (approvalId) {
|
|
667
|
+
env.PAPERCLIP_APPROVAL_ID = approvalId;
|
|
668
|
+
}
|
|
669
|
+
if (approvalStatus) {
|
|
670
|
+
env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
|
|
671
|
+
}
|
|
672
|
+
if (linkedIssueIds.length > 0) {
|
|
673
|
+
env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
|
|
674
|
+
}
|
|
675
|
+
refreshPaperclipWorkspaceEnvForExecution({
|
|
676
|
+
env,
|
|
677
|
+
envConfig,
|
|
678
|
+
workspaceCwd: effectiveWorkspaceCwd,
|
|
679
|
+
workspaceSource,
|
|
680
|
+
workspaceStrategy,
|
|
681
|
+
workspaceId,
|
|
682
|
+
workspaceRepoUrl,
|
|
683
|
+
workspaceRepoRef,
|
|
684
|
+
workspaceBranch,
|
|
685
|
+
workspaceWorktreePath,
|
|
686
|
+
workspaceHints,
|
|
687
|
+
agentHome,
|
|
688
|
+
executionTargetIsRemote,
|
|
689
|
+
executionCwd: effectiveExecutionCwd,
|
|
690
|
+
});
|
|
691
|
+
if (targetWorkspaceRealization) {
|
|
692
|
+
env.PAPERCLIP_WORKSPACE_REALIZATION_MODE = targetWorkspaceRealization.mode;
|
|
693
|
+
env.PAPERCLIP_WORKSPACE_AUTHORITATIVE_ROOT = targetWorkspaceRealization.authoritativeRoot;
|
|
694
|
+
}
|
|
695
|
+
if (runtimeServiceIntents.length > 0) {
|
|
696
|
+
env.PAPERCLIP_RUNTIME_SERVICE_INTENTS_JSON = JSON.stringify(runtimeServiceIntents);
|
|
697
|
+
}
|
|
698
|
+
if (runtimeServices.length > 0) {
|
|
699
|
+
env.PAPERCLIP_RUNTIME_SERVICES_JSON = JSON.stringify(runtimeServices);
|
|
700
|
+
}
|
|
701
|
+
if (runtimePrimaryUrl) {
|
|
702
|
+
env.PAPERCLIP_RUNTIME_PRIMARY_URL = runtimePrimaryUrl;
|
|
703
|
+
}
|
|
704
|
+
env.CODEX_HOME = remoteCodexHome ?? effectiveCodexHome;
|
|
705
|
+
if (authToken) {
|
|
706
|
+
env.PAPERCLIP_API_KEY = authToken;
|
|
707
|
+
}
|
|
708
|
+
if (executionTargetIsRemote && adapterExecutionTargetUsesPaperclipBridge(runtimeExecutionTarget)) {
|
|
709
|
+
paperclipBridge = await startAdapterExecutionTargetPaperclipBridge({
|
|
710
|
+
runId,
|
|
711
|
+
target: runtimeExecutionTarget,
|
|
712
|
+
enableSandboxDuplexBridge: adapterExecutionTargetEnablesSandboxDuplexBridge(runtimeExecutionTarget),
|
|
713
|
+
duplexObservabilityRecorder: adapterExecutionTargetDuplexObservabilityRecorder(runtimeExecutionTarget),
|
|
714
|
+
runtimeRootDir: preparedExecutionTargetRuntime?.runtimeRootDir,
|
|
715
|
+
adapterKey: "codex",
|
|
716
|
+
timeoutSec,
|
|
717
|
+
hostApiToken: env.PAPERCLIP_API_KEY,
|
|
718
|
+
onLog,
|
|
719
|
+
});
|
|
720
|
+
if (paperclipBridge) {
|
|
721
|
+
Object.assign(env, paperclipBridge.env);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
const effectiveEnv = Object.fromEntries(Object.entries({ ...process.env, ...env }).filter((entry) => typeof entry[1] === "string"));
|
|
725
|
+
const billingType = resolveCodexBillingType(effectiveEnv);
|
|
726
|
+
const networkScope = parseLocalProcessNetworkScope(config.networkScope);
|
|
727
|
+
const filesystemScope = parseLocalProcessFilesystemScope(config.filesystemScope);
|
|
728
|
+
const localProcessSandbox = (filesystemScope || networkScope) && !executionTargetIsRemote
|
|
729
|
+
? {
|
|
730
|
+
workspaceDir: effectiveExecutionCwd,
|
|
731
|
+
filesystemScope,
|
|
732
|
+
managedPaths: [{ path: effectiveCodexHome, access: "rw" }],
|
|
733
|
+
extraPaths: parseLocalProcessSandboxExtraPaths(config.filesystemExtraPaths),
|
|
734
|
+
pathAliases: targetWorkspaceRealization?.mode === "copy"
|
|
735
|
+
? targetWorkspaceRealization.pathAliases
|
|
736
|
+
: [],
|
|
737
|
+
outboundRestorePaths: targetWorkspaceRealization?.outboundRestorePaths ?? [],
|
|
738
|
+
homeDir: filesystemScope ? effectiveCodexHome : null,
|
|
739
|
+
networkScope,
|
|
740
|
+
networkAllowlist: parseLocalProcessNetworkAllowlist(config.networkAllowlist),
|
|
741
|
+
networkTrustedUrls: [
|
|
742
|
+
paperclipBaseEnv.PAPERCLIP_API_URL,
|
|
743
|
+
...runtimeMcpGateways.map((gateway) => gateway.endpointPath),
|
|
744
|
+
],
|
|
745
|
+
command: asString(config.filesystemSandboxCommand, "bwrap"),
|
|
746
|
+
}
|
|
747
|
+
: null;
|
|
748
|
+
if (localProcessSandbox) {
|
|
749
|
+
const scopes = [filesystemScope ? "workspace filesystem" : null, networkScope ? `${networkScope} network` : null]
|
|
750
|
+
.filter(Boolean)
|
|
751
|
+
.join(" and ");
|
|
752
|
+
await onLog("stdout", `[paperclip] Confining Codex with ${scopes} scope.\n`);
|
|
753
|
+
}
|
|
754
|
+
const runtimeEnv = Object.fromEntries(Object.entries(ensurePathInEnv(effectiveEnv)).filter((entry) => typeof entry[1] === "string"));
|
|
755
|
+
await ensureAdapterExecutionTargetRuntimeCommandInstalled({
|
|
756
|
+
runId,
|
|
757
|
+
target: executionTarget,
|
|
758
|
+
installCommand: ctx.runtimeCommandSpec?.installCommand,
|
|
759
|
+
detectCommand: ctx.runtimeCommandSpec?.detectCommand,
|
|
760
|
+
cwd,
|
|
761
|
+
env: runtimeEnv,
|
|
762
|
+
timeoutSec,
|
|
763
|
+
graceSec,
|
|
764
|
+
onLog,
|
|
765
|
+
});
|
|
766
|
+
await ensureAdapterExecutionTargetCommandResolvable(command, executionTarget, cwd, runtimeEnv);
|
|
767
|
+
const resolvedCommand = await resolveAdapterExecutionTargetCommandForLogs(command, executionTarget, cwd, runtimeEnv);
|
|
768
|
+
const loggedEnv = buildInvocationEnvForLogs(env, {
|
|
769
|
+
runtimeEnv,
|
|
770
|
+
includeRuntimeKeys: ["HOME"],
|
|
771
|
+
resolvedCommand,
|
|
772
|
+
});
|
|
773
|
+
const monitorResolution = resolveCodexInactivityTimeout(config.outputInactivityTimeoutMs);
|
|
774
|
+
if (monitorResolution.mode === "disabled") {
|
|
775
|
+
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`);
|
|
776
|
+
}
|
|
777
|
+
else if (monitorResolution.mode === "default" && "reason" in monitorResolution) {
|
|
778
|
+
await onLog("stdout", `[paperclip] Ignoring non-positive adapterConfig.outputInactivityTimeoutMs; falling back to default ${monitorResolution.timeoutMs}ms.\n`);
|
|
779
|
+
}
|
|
780
|
+
const runtimeSessionParams = parseObject(runtime.sessionParams);
|
|
781
|
+
const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? "");
|
|
782
|
+
const runtimeSessionCwd = asString(runtimeSessionParams.cwd, "");
|
|
783
|
+
const runtimeRemoteExecution = parseObject(runtimeSessionParams.remoteExecution);
|
|
784
|
+
const canResumeSession = runtimeSessionId.length > 0 &&
|
|
785
|
+
(runtimeSessionCwd.length === 0 || path.resolve(runtimeSessionCwd) === path.resolve(effectiveExecutionCwd)) &&
|
|
786
|
+
adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget);
|
|
787
|
+
const codexTransientFallbackMode = readCodexTransientFallbackMode(context);
|
|
788
|
+
const forceSaferInvocation = fallbackModeUsesSaferInvocation(codexTransientFallbackMode);
|
|
789
|
+
const forceFreshSession = fallbackModeUsesFreshSession(codexTransientFallbackMode);
|
|
790
|
+
const sessionId = canResumeSession && !forceFreshSession ? runtimeSessionId : null;
|
|
791
|
+
if (executionTargetIsRemote && runtimeSessionId && !canResumeSession) {
|
|
792
|
+
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`);
|
|
793
|
+
}
|
|
794
|
+
else if (runtimeSessionId && !canResumeSession) {
|
|
795
|
+
await onLog("stdout", `[paperclip] Codex session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${effectiveExecutionCwd}".\n`);
|
|
796
|
+
}
|
|
797
|
+
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
|
798
|
+
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
|
|
799
|
+
let instructionsPrefix = "";
|
|
800
|
+
let instructionsChars = 0;
|
|
801
|
+
if (instructionsFilePath) {
|
|
802
|
+
try {
|
|
803
|
+
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
|
|
804
|
+
instructionsPrefix =
|
|
805
|
+
`${instructionsContents}\n\n` +
|
|
806
|
+
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
|
|
807
|
+
`Resolve any relative file references from ${instructionsDir}.\n\n`;
|
|
808
|
+
instructionsChars = instructionsPrefix.length;
|
|
809
|
+
}
|
|
810
|
+
catch (err) {
|
|
811
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
812
|
+
await onLog("stdout", `[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
const repoAgentsNote = "Codex exec automatically applies repo-scoped AGENTS.md instructions from the current workspace; Paperclip does not currently suppress that discovery.";
|
|
816
|
+
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
|
817
|
+
const templateData = {
|
|
818
|
+
agentId: agent.id,
|
|
819
|
+
companyId: agent.companyId,
|
|
820
|
+
runId,
|
|
821
|
+
company: { id: agent.companyId },
|
|
822
|
+
agent,
|
|
823
|
+
run: { id: runId, source: "on_demand" },
|
|
824
|
+
context,
|
|
825
|
+
};
|
|
826
|
+
const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0
|
|
827
|
+
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
|
828
|
+
: "";
|
|
829
|
+
const taskContextNote = selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId) });
|
|
830
|
+
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
|
|
831
|
+
resumedSession: Boolean(sessionId),
|
|
832
|
+
conversationMode: context.conversationMode === true,
|
|
833
|
+
suppressIssueDescription: taskContextNote.length > 0,
|
|
834
|
+
});
|
|
835
|
+
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
|
|
836
|
+
const promptInstructionsPrefix = shouldUseResumeDeltaPrompt ? "" : instructionsPrefix;
|
|
837
|
+
instructionsChars = promptInstructionsPrefix.length;
|
|
838
|
+
const continuationSummary = parseObject(context.paperclipContinuationSummary);
|
|
839
|
+
const continuationSummaryBody = asString(continuationSummary.body, "").trim() || null;
|
|
840
|
+
const codexFallbackHandoffNote = forceFreshSession
|
|
841
|
+
? buildCodexTransientHandoffNote({
|
|
842
|
+
previousSessionId: runtimeSessionId || runtime.sessionId || null,
|
|
843
|
+
fallbackMode: codexTransientFallbackMode ?? "fresh_session",
|
|
844
|
+
continuationSummaryBody,
|
|
845
|
+
})
|
|
846
|
+
: "";
|
|
847
|
+
const commandNotes = (() => {
|
|
848
|
+
if (!instructionsFilePath) {
|
|
849
|
+
const notes = [repoAgentsNote];
|
|
850
|
+
if (forceSaferInvocation) {
|
|
851
|
+
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
|
|
852
|
+
}
|
|
853
|
+
if (forceFreshSession) {
|
|
854
|
+
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
|
|
855
|
+
}
|
|
856
|
+
return notes;
|
|
857
|
+
}
|
|
858
|
+
if (instructionsPrefix.length > 0) {
|
|
859
|
+
if (shouldUseResumeDeltaPrompt) {
|
|
860
|
+
const notes = [
|
|
861
|
+
`Loaded agent instructions from ${instructionsFilePath}`,
|
|
862
|
+
"Skipped stdin instruction reinjection because an existing Codex session is being resumed with a wake delta.",
|
|
863
|
+
repoAgentsNote,
|
|
864
|
+
];
|
|
865
|
+
if (forceSaferInvocation) {
|
|
866
|
+
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
|
|
867
|
+
}
|
|
868
|
+
if (forceFreshSession) {
|
|
869
|
+
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
|
|
870
|
+
}
|
|
871
|
+
return notes;
|
|
872
|
+
}
|
|
873
|
+
const notes = [
|
|
874
|
+
`Loaded agent instructions from ${instructionsFilePath}`,
|
|
875
|
+
`Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).`,
|
|
876
|
+
repoAgentsNote,
|
|
877
|
+
];
|
|
878
|
+
if (forceSaferInvocation) {
|
|
879
|
+
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
|
|
880
|
+
}
|
|
881
|
+
if (forceFreshSession) {
|
|
882
|
+
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
|
|
883
|
+
}
|
|
884
|
+
return notes;
|
|
885
|
+
}
|
|
886
|
+
const notes = [
|
|
887
|
+
`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`,
|
|
888
|
+
repoAgentsNote,
|
|
889
|
+
];
|
|
890
|
+
if (forceSaferInvocation) {
|
|
891
|
+
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
|
|
892
|
+
}
|
|
893
|
+
if (forceFreshSession) {
|
|
894
|
+
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
|
|
895
|
+
}
|
|
896
|
+
return notes;
|
|
897
|
+
})();
|
|
898
|
+
if (executionTargetIsSandbox) {
|
|
899
|
+
commandNotes.push("Added --skip-git-repo-check for sandbox execution because Codex requires an explicit trust bypass in headless remote workspaces.");
|
|
900
|
+
}
|
|
901
|
+
if (preparedRuntimeConfig.notes.length > 0) {
|
|
902
|
+
commandNotes.unshift(...preparedRuntimeConfig.notes);
|
|
903
|
+
}
|
|
904
|
+
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
|
|
905
|
+
? ""
|
|
906
|
+
: renderTemplate(promptTemplate, templateData);
|
|
907
|
+
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
|
908
|
+
const prompt = joinPromptSections([
|
|
909
|
+
promptInstructionsPrefix,
|
|
910
|
+
renderedBootstrapPrompt,
|
|
911
|
+
wakePrompt,
|
|
912
|
+
codexFallbackHandoffNote,
|
|
913
|
+
sessionHandoffNote,
|
|
914
|
+
taskContextNote,
|
|
915
|
+
renderedPrompt,
|
|
916
|
+
]);
|
|
917
|
+
const promptMetrics = {
|
|
918
|
+
promptChars: prompt.length,
|
|
919
|
+
instructionsChars,
|
|
920
|
+
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
|
921
|
+
wakePromptChars: wakePrompt.length,
|
|
922
|
+
sessionHandoffChars: sessionHandoffNote.length,
|
|
923
|
+
taskContextChars: taskContextNote.length,
|
|
924
|
+
heartbeatPromptChars: renderedPrompt.length,
|
|
925
|
+
};
|
|
926
|
+
const runAttempt = async (resumeSessionId) => {
|
|
927
|
+
const execArgs = buildCodexExecArgs(forceSaferInvocation ? { ...config, fastMode: false } : config, {
|
|
928
|
+
resumeSessionId,
|
|
929
|
+
skipGitRepoCheck: executionTargetIsSandbox,
|
|
930
|
+
networkAccess: env.PAPERCLIP_RUNNER_NETWORK_ACCESS !== "disabled",
|
|
931
|
+
});
|
|
932
|
+
const args = execArgs.args;
|
|
933
|
+
const commandNotesWithFastMode = execArgs.fastModeIgnoredReason == null
|
|
934
|
+
? commandNotes
|
|
935
|
+
: [...commandNotes, execArgs.fastModeIgnoredReason];
|
|
936
|
+
if (onMeta) {
|
|
937
|
+
await onMeta({
|
|
938
|
+
adapterType: "codex_local",
|
|
939
|
+
command: resolvedCommand,
|
|
940
|
+
cwd: effectiveExecutionCwd,
|
|
941
|
+
commandNotes: commandNotesWithFastMode,
|
|
942
|
+
commandArgs: args.map((value, idx) => {
|
|
943
|
+
if (idx === args.length - 1 && value !== "-")
|
|
944
|
+
return `<prompt ${prompt.length} chars>`;
|
|
945
|
+
return value;
|
|
946
|
+
}),
|
|
947
|
+
env: loggedEnv,
|
|
948
|
+
prompt,
|
|
949
|
+
promptMetrics,
|
|
950
|
+
context,
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
let monitorFired = false;
|
|
954
|
+
let monitorTerminationSignal = null;
|
|
955
|
+
let monitorElapsedMs = 0;
|
|
956
|
+
let monitorTimeoutMs = 0;
|
|
957
|
+
let killTarget = null;
|
|
958
|
+
let sigkillTimer = null;
|
|
959
|
+
let monitorLogPromise = null;
|
|
960
|
+
const processActivityMonitor = { current: null };
|
|
961
|
+
const resolvedMonitorTimeoutMs = monitorResolution.mode === "disabled" ? null : monitorResolution.timeoutMs;
|
|
962
|
+
const monitor = monitorResolution.mode === "disabled"
|
|
963
|
+
? null
|
|
964
|
+
: createCodexOutputInactivityMonitor({
|
|
965
|
+
timeoutMs: monitorResolution.timeoutMs,
|
|
966
|
+
onFire: (state) => {
|
|
967
|
+
monitorFired = true;
|
|
968
|
+
monitorElapsedMs = (state.firedAt ?? Date.now()) - state.lastEventAt;
|
|
969
|
+
monitorTimeoutMs = monitorResolution.timeoutMs;
|
|
970
|
+
const message = formatOutputInactivityMonitorErrorMessage(monitorElapsedMs);
|
|
971
|
+
const elapsedSec = Math.round(monitorElapsedMs / 1000);
|
|
972
|
+
const timeoutSecLabel = Math.round(monitorResolution.timeoutMs / 1000);
|
|
973
|
+
const logLine = `[paperclip] adapter.invoke ${message}; ` +
|
|
974
|
+
`timeoutMs=${monitorResolution.timeoutMs} elapsedSinceLastEventMs=${monitorElapsedMs} ` +
|
|
975
|
+
`outputChunkCount=${state.outputChunkCount} outputBytes=${state.outputBytes} ` +
|
|
976
|
+
`parsedEvents=${state.parsedEventCount} processActivityCount=${state.processActivityCount} ` +
|
|
977
|
+
`(timeout=${timeoutSecLabel}s elapsed=${elapsedSec}s); ` +
|
|
978
|
+
`terminating codex child via SIGTERM (5s grace, then SIGKILL).\n`;
|
|
979
|
+
// Issue the log without awaiting on the kill hot path, but capture
|
|
980
|
+
// the promise so the surrounding try/finally can await flush before
|
|
981
|
+
// the run resolves. Without this the diagnostic that explains the
|
|
982
|
+
// kill could be dropped if the child exits faster than onLog flushes.
|
|
983
|
+
monitorLogPromise = Promise.resolve(onLog("stderr", logLine)).catch(() => { });
|
|
984
|
+
const target = killTarget;
|
|
985
|
+
if (!target || (target.pid == null && target.processGroupId == null)) {
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
const sentSig = signalCodexChild(target, "SIGTERM");
|
|
989
|
+
if (sentSig)
|
|
990
|
+
monitorTerminationSignal = "SIGTERM";
|
|
991
|
+
sigkillTimer = setTimeout(() => {
|
|
992
|
+
sigkillTimer = null;
|
|
993
|
+
const stillSent = signalCodexChild(target, "SIGKILL");
|
|
994
|
+
if (stillSent)
|
|
995
|
+
monitorTerminationSignal = "SIGKILL";
|
|
996
|
+
}, CODEX_OUTPUT_INACTIVITY_MONITOR_SIGTERM_GRACE_MS);
|
|
997
|
+
if (typeof sigkillTimer.unref === "function") {
|
|
998
|
+
sigkillTimer.unref();
|
|
999
|
+
}
|
|
1000
|
+
},
|
|
1001
|
+
});
|
|
1002
|
+
const wrappedOnSpawn = async (meta) => {
|
|
1003
|
+
killTarget = { pid: meta.pid ?? null, processGroupId: meta.processGroupId };
|
|
1004
|
+
if (monitor && resolvedMonitorTimeoutMs !== null && !executionTargetIsRemote) {
|
|
1005
|
+
processActivityMonitor.current = createCodexProcessActivityMonitor({
|
|
1006
|
+
pid: meta.pid,
|
|
1007
|
+
processGroupId: meta.processGroupId,
|
|
1008
|
+
intervalMs: Math.min(CODEX_PROCESS_ACTIVITY_POLL_INTERVAL_MS, Math.max(1_000, Math.floor(resolvedMonitorTimeoutMs / 4))),
|
|
1009
|
+
onActivity: () => monitor.noteProcessActivity(),
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
if (onSpawn) {
|
|
1013
|
+
await onSpawn(meta);
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
1016
|
+
try {
|
|
1017
|
+
const proc = await runAdapterExecutionTargetProcess(runId, runtimeExecutionTarget, command, args, {
|
|
1018
|
+
cwd,
|
|
1019
|
+
env,
|
|
1020
|
+
stdin: prompt,
|
|
1021
|
+
timeoutSec,
|
|
1022
|
+
graceSec,
|
|
1023
|
+
onSpawn: wrappedOnSpawn,
|
|
1024
|
+
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
1025
|
+
onLog: async (stream, chunk) => {
|
|
1026
|
+
monitor?.noteOutputChunk(stream, chunk);
|
|
1027
|
+
if (stream === "stdout") {
|
|
1028
|
+
await onLog(stream, chunk);
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
const cleaned = stripCodexRolloutNoise(chunk);
|
|
1032
|
+
if (!cleaned.trim())
|
|
1033
|
+
return;
|
|
1034
|
+
await onLog(stream, cleaned);
|
|
1035
|
+
},
|
|
1036
|
+
runLogTail: paperclipBridge?.runLogTail,
|
|
1037
|
+
settleRunDisposition: paperclipBridge?.settleRunDisposition,
|
|
1038
|
+
localProcessSandbox,
|
|
1039
|
+
});
|
|
1040
|
+
const cleanedStderr = stripCodexRolloutNoise(proc.stderr);
|
|
1041
|
+
return {
|
|
1042
|
+
proc: {
|
|
1043
|
+
...proc,
|
|
1044
|
+
stderr: cleanedStderr,
|
|
1045
|
+
},
|
|
1046
|
+
rawStderr: proc.stderr,
|
|
1047
|
+
parsed: parseCodexJsonl(proc.stdout),
|
|
1048
|
+
monitor: monitorFired
|
|
1049
|
+
? {
|
|
1050
|
+
fired: true,
|
|
1051
|
+
terminationSignal: monitorTerminationSignal,
|
|
1052
|
+
elapsedMsSinceLastEvent: monitorElapsedMs,
|
|
1053
|
+
timeoutMs: monitorTimeoutMs,
|
|
1054
|
+
}
|
|
1055
|
+
: { fired: false },
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
finally {
|
|
1059
|
+
processActivityMonitor.current?.stop();
|
|
1060
|
+
monitor?.stop();
|
|
1061
|
+
if (sigkillTimer) {
|
|
1062
|
+
clearTimeout(sigkillTimer);
|
|
1063
|
+
sigkillTimer = null;
|
|
1064
|
+
}
|
|
1065
|
+
if (monitorLogPromise) {
|
|
1066
|
+
await monitorLogPromise;
|
|
1067
|
+
monitorLogPromise = null;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
const toResult = (attempt, clearSessionOnMissingSession = false, isRetry = false) => {
|
|
1072
|
+
if (attempt.monitor?.fired) {
|
|
1073
|
+
const errorMessage = formatOutputInactivityMonitorErrorMessage(attempt.monitor.elapsedMsSinceLastEvent);
|
|
1074
|
+
return {
|
|
1075
|
+
exitCode: null,
|
|
1076
|
+
signal: attempt.monitor.terminationSignal ?? attempt.proc.signal,
|
|
1077
|
+
timedOut: false,
|
|
1078
|
+
errorMessage,
|
|
1079
|
+
errorCode: "codex_output_inactivity_monitor",
|
|
1080
|
+
errorFamily: null,
|
|
1081
|
+
usage: attempt.parsed.usage,
|
|
1082
|
+
usageBasis: attempt.parsed.usageBasis,
|
|
1083
|
+
sessionId: null,
|
|
1084
|
+
sessionParams: null,
|
|
1085
|
+
sessionDisplayId: null,
|
|
1086
|
+
provider: "openai",
|
|
1087
|
+
biller: resolveCodexBiller(effectiveEnv, billingType),
|
|
1088
|
+
model,
|
|
1089
|
+
billingType,
|
|
1090
|
+
costUsd: null,
|
|
1091
|
+
resultJson: {
|
|
1092
|
+
stdout: attempt.proc.stdout,
|
|
1093
|
+
stderr: attempt.proc.stderr,
|
|
1094
|
+
outputInactivityMonitor: {
|
|
1095
|
+
kind: "output_inactivity",
|
|
1096
|
+
timeoutMs: attempt.monitor.timeoutMs,
|
|
1097
|
+
elapsedMsSinceLastEvent: attempt.monitor.elapsedMsSinceLastEvent,
|
|
1098
|
+
terminationSignal: attempt.monitor.terminationSignal,
|
|
1099
|
+
},
|
|
1100
|
+
},
|
|
1101
|
+
summary: attempt.parsed.summary,
|
|
1102
|
+
clearSession: clearSessionOnMissingSession,
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
if (attempt.proc.timedOut) {
|
|
1106
|
+
return {
|
|
1107
|
+
exitCode: attempt.proc.exitCode,
|
|
1108
|
+
signal: attempt.proc.signal,
|
|
1109
|
+
timedOut: true,
|
|
1110
|
+
errorMessage: `Timed out after ${timeoutSec}s`,
|
|
1111
|
+
clearSession: clearSessionOnMissingSession,
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
const canFallbackToRuntimeSession = !isRetry && !forceFreshSession;
|
|
1115
|
+
const resolvedSessionId = attempt.parsed.sessionId ??
|
|
1116
|
+
(canFallbackToRuntimeSession ? (runtimeSessionId ?? runtime.sessionId ?? null) : null);
|
|
1117
|
+
const resolvedSessionParams = resolvedSessionId
|
|
1118
|
+
? {
|
|
1119
|
+
sessionId: resolvedSessionId,
|
|
1120
|
+
cwd: effectiveExecutionCwd,
|
|
1121
|
+
...(executionTargetIsRemote
|
|
1122
|
+
? {
|
|
1123
|
+
remoteExecution: adapterExecutionTargetSessionIdentity(runtimeExecutionTarget),
|
|
1124
|
+
}
|
|
1125
|
+
: {}),
|
|
1126
|
+
...(workspaceId ? { workspaceId } : {}),
|
|
1127
|
+
...(workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}),
|
|
1128
|
+
...(workspaceRepoRef ? { repoRef: workspaceRepoRef } : {}),
|
|
1129
|
+
}
|
|
1130
|
+
: null;
|
|
1131
|
+
const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : "";
|
|
1132
|
+
const stderrLine = firstMeaningfulStderrLine(attempt.proc.stderr);
|
|
1133
|
+
const fallbackErrorMessage = parsedError ||
|
|
1134
|
+
stderrLine ||
|
|
1135
|
+
`Codex exited with code ${attempt.proc.exitCode ?? -1}`;
|
|
1136
|
+
const transientRetryNotBefore = (attempt.proc.exitCode ?? 0) !== 0
|
|
1137
|
+
? extractCodexRetryNotBefore({
|
|
1138
|
+
stdout: attempt.proc.stdout,
|
|
1139
|
+
stderr: attempt.proc.stderr,
|
|
1140
|
+
errorMessage: fallbackErrorMessage,
|
|
1141
|
+
})
|
|
1142
|
+
: null;
|
|
1143
|
+
const authRefreshFailure = (attempt.proc.exitCode ?? 0) !== 0
|
|
1144
|
+
? classifyCodexAuthRefreshFailure({
|
|
1145
|
+
stdout: attempt.proc.stdout,
|
|
1146
|
+
stderr: attempt.proc.stderr,
|
|
1147
|
+
errorMessage: fallbackErrorMessage,
|
|
1148
|
+
})
|
|
1149
|
+
: null;
|
|
1150
|
+
const providerQuota = (attempt.proc.exitCode ?? 0) !== 0 &&
|
|
1151
|
+
!authRefreshFailure &&
|
|
1152
|
+
isCodexProviderQuotaError({
|
|
1153
|
+
stdout: attempt.proc.stdout,
|
|
1154
|
+
stderr: attempt.proc.stderr,
|
|
1155
|
+
errorMessage: fallbackErrorMessage,
|
|
1156
|
+
});
|
|
1157
|
+
const transientUpstream = (attempt.proc.exitCode ?? 0) !== 0 &&
|
|
1158
|
+
!authRefreshFailure &&
|
|
1159
|
+
!providerQuota &&
|
|
1160
|
+
isCodexTransientUpstreamError({
|
|
1161
|
+
stdout: attempt.proc.stdout,
|
|
1162
|
+
stderr: attempt.proc.stderr,
|
|
1163
|
+
errorMessage: fallbackErrorMessage,
|
|
1164
|
+
});
|
|
1165
|
+
const harnessCrash = !authRefreshFailure &&
|
|
1166
|
+
!providerQuota &&
|
|
1167
|
+
!transientUpstream &&
|
|
1168
|
+
isCodexHarnessCrash({
|
|
1169
|
+
exitCode: attempt.proc.exitCode,
|
|
1170
|
+
sawProtocolEvent: attempt.parsed.sawProtocolEvent,
|
|
1171
|
+
sawProtocolTerminalEvent: attempt.parsed.sawProtocolTerminalEvent,
|
|
1172
|
+
});
|
|
1173
|
+
const errorFamily = authRefreshFailure ??
|
|
1174
|
+
(providerQuota ? "provider_quota" : transientUpstream || harnessCrash ? "transient_upstream" : null);
|
|
1175
|
+
return {
|
|
1176
|
+
exitCode: attempt.proc.exitCode,
|
|
1177
|
+
signal: attempt.proc.signal,
|
|
1178
|
+
timedOut: false,
|
|
1179
|
+
errorMessage: (attempt.proc.exitCode ?? 0) === 0
|
|
1180
|
+
? null
|
|
1181
|
+
: fallbackErrorMessage,
|
|
1182
|
+
errorCode:
|
|
1183
|
+
// Forward the transport-level error code from the run-disposition
|
|
1184
|
+
// seam first. A lost duplex control channel surfaces the typed
|
|
1185
|
+
// `duplex_channel_lost` code before any provider classification.
|
|
1186
|
+
attempt.proc.errorCode
|
|
1187
|
+
? attempt.proc.errorCode
|
|
1188
|
+
: authRefreshFailure
|
|
1189
|
+
? authRefreshFailure
|
|
1190
|
+
: providerQuota
|
|
1191
|
+
? "provider_quota"
|
|
1192
|
+
: transientUpstream
|
|
1193
|
+
? "codex_transient_upstream"
|
|
1194
|
+
: harnessCrash
|
|
1195
|
+
? "codex_harness_crash"
|
|
1196
|
+
: null,
|
|
1197
|
+
errorFamily,
|
|
1198
|
+
retryNotBefore: transientRetryNotBefore ? transientRetryNotBefore.toISOString() : null,
|
|
1199
|
+
usage: attempt.parsed.usage,
|
|
1200
|
+
usageBasis: attempt.parsed.usageBasis,
|
|
1201
|
+
sessionId: resolvedSessionId,
|
|
1202
|
+
sessionParams: resolvedSessionParams,
|
|
1203
|
+
sessionDisplayId: resolvedSessionId,
|
|
1204
|
+
provider: "openai",
|
|
1205
|
+
biller: resolveCodexBiller(effectiveEnv, billingType),
|
|
1206
|
+
model,
|
|
1207
|
+
billingType,
|
|
1208
|
+
costUsd: null,
|
|
1209
|
+
resultJson: {
|
|
1210
|
+
stdout: attempt.proc.stdout,
|
|
1211
|
+
stderr: attempt.proc.stderr,
|
|
1212
|
+
...(errorFamily ? { errorFamily } : {}),
|
|
1213
|
+
...(transientRetryNotBefore ? { retryNotBefore: transientRetryNotBefore.toISOString() } : {}),
|
|
1214
|
+
...(transientRetryNotBefore ? { transientRetryNotBefore: transientRetryNotBefore.toISOString() } : {}),
|
|
1215
|
+
...(providerQuota && transientRetryNotBefore ? { providerQuotaRetryNotBefore: transientRetryNotBefore.toISOString() } : {}),
|
|
1216
|
+
},
|
|
1217
|
+
summary: attempt.parsed.summary,
|
|
1218
|
+
clearSession: Boolean((clearSessionOnMissingSession || forceFreshSession) && !resolvedSessionId),
|
|
1219
|
+
};
|
|
1220
|
+
};
|
|
1221
|
+
let executionError = null;
|
|
1222
|
+
try {
|
|
1223
|
+
const initial = await runAttempt(sessionId);
|
|
1224
|
+
if (sessionId &&
|
|
1225
|
+
!initial.proc.timedOut &&
|
|
1226
|
+
!initial.proc.signal &&
|
|
1227
|
+
// A started session can emit stale-rollout warnings for other threads.
|
|
1228
|
+
// After Ctrl-C those warnings must not restart the cancelled turn.
|
|
1229
|
+
!initial.parsed.sessionId &&
|
|
1230
|
+
(initial.proc.exitCode ?? 0) !== 0 &&
|
|
1231
|
+
isCodexUnknownSessionError(initial.proc.stdout, initial.rawStderr)) {
|
|
1232
|
+
await onLog("stdout", `[paperclip] Codex resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`);
|
|
1233
|
+
const retry = await runAttempt(null);
|
|
1234
|
+
const retryResult = toResult(retry, true, true);
|
|
1235
|
+
if (retryResult.errorMessage) {
|
|
1236
|
+
executionError = new Error(retryResult.errorMessage);
|
|
1237
|
+
}
|
|
1238
|
+
return retryResult;
|
|
1239
|
+
}
|
|
1240
|
+
const result = toResult(initial, false, false);
|
|
1241
|
+
if (result.errorMessage) {
|
|
1242
|
+
executionError = new Error(result.errorMessage);
|
|
1243
|
+
}
|
|
1244
|
+
return result;
|
|
1245
|
+
}
|
|
1246
|
+
catch (error) {
|
|
1247
|
+
executionError = error;
|
|
1248
|
+
throw error;
|
|
1249
|
+
}
|
|
1250
|
+
finally {
|
|
1251
|
+
if (paperclipBridge) {
|
|
1252
|
+
await paperclipBridge.stop();
|
|
1253
|
+
}
|
|
1254
|
+
if (restoreRemoteWorkspace) {
|
|
1255
|
+
try {
|
|
1256
|
+
await onLog("stdout", `[paperclip] Restoring workspace changes from ${describeAdapterExecutionTarget(executionTarget)}.\n`);
|
|
1257
|
+
await restoreRemoteWorkspace();
|
|
1258
|
+
}
|
|
1259
|
+
catch (error) {
|
|
1260
|
+
await Promise.resolve(onLog("stderr", `[paperclip] Failed to restore workspace changes from ${describeAdapterExecutionTarget(executionTarget)}: ${error instanceof Error ? error.message : String(error)}\n`)).catch(() => undefined);
|
|
1261
|
+
// A provider failure remains the primary outcome. When provider work
|
|
1262
|
+
// succeeded, however, silently accepting a failed copy-back can lose
|
|
1263
|
+
// the only workspace edits before a replacement sandbox starts.
|
|
1264
|
+
if (executionError === null)
|
|
1265
|
+
throw error;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
finally {
|
|
1271
|
+
// Remove the staged CODEX_HOME allowlist temp dir on every exit path
|
|
1272
|
+
// (teardown AND error), never only the happy path. Cleanup failure is
|
|
1273
|
+
// logged, not fatal — a leaked temp dir must not crash the run.
|
|
1274
|
+
if (stagedCodexHomeDir) {
|
|
1275
|
+
await fs.rm(stagedCodexHomeDir, { recursive: true, force: true }).catch(async (error) => {
|
|
1276
|
+
await onLog("stderr", `[paperclip] Failed to remove staged Codex home "${stagedCodexHomeDir}": ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
// Restore the managed config.toml so PAPERCLIP_CODEX_PROVIDERS changes
|
|
1280
|
+
// (or removal) between runs never leave stale provider routing behind. This
|
|
1281
|
+
// finally starts the moment prepareCodexRuntimeConfig returns, so a throw
|
|
1282
|
+
// anywhere in the remaining setup (skill injection, remote runtime
|
|
1283
|
+
// preparation, command building) restores the original config.toml too.
|
|
1284
|
+
// If the process dies before reaching this, the next
|
|
1285
|
+
// prepareCodexRuntimeConfig restores the original from the pre-run backup
|
|
1286
|
+
// written at prepare time.
|
|
1287
|
+
await preparedRuntimeConfig.cleanup();
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
//# sourceMappingURL=execute.js.map
|