The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(runner): bound Codex workspace values (#12366)
Dotta905177c93b2c
diff --git a/packages/paperclip-runner/src/drivers/codex/codex-boundaries.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-boundaries.test.tsnew file mode 100644index 0000000000..e960d2989a--- /dev/null+++ b/packages/paperclip-runner/src/drivers/codex/codex-boundaries.test.ts@@ -0,0 +1,130 @@+import {+ mkdirSync,+ mkdtempSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join, parse } from "node:path";+import { describe, expect, it } from "vitest";++import {+ boundedCodexPayload,+ codexToolAcceptsDisposition,+ isCodexSemanticTool,+ isRetainableCodexPayload,+ redactCodexValue,+ validateCodexWorkingDirectory,+} from "./codex-boundaries.js";++describe("Codex value and workspace boundaries", () => {+ it("accepts only an assigned non-root workspace that does not contain host state", () => {+ const fixture = mkdtempSync(join(tmpdir(), "paperclip-codex-boundaries-"));+ try {+ const workspaceRoot = join(fixture, "workspaces");+ const workspace = join(workspaceRoot, "run-1");+ const outside = join(fixture, "outside");+ const hostRoot = join(fixture, "host");+ const hostHome = join(hostRoot, "home");+ const protectedHomeDirectory = join(hostHome, ".ssh");+ const codexHome = join(fixture, "codex-home");+ const codexWorkspace = join(codexHome, "run");+ for (const directory of [+ workspace,+ outside,+ protectedHomeDirectory,+ codexWorkspace,+ ]) {+ mkdirSync(directory, { recursive: true });+ }++ expect(+ validateCodexWorkingDirectory(workspace, {+ HOME: hostHome,+ CODEX_HOME: codexHome,+ PAPERCLIP_WORKSPACE_CWD: workspaceRoot,+ }),+ ).toBe(realpathSync.native(workspace));+ expect(() =>+ validateCodexWorkingDirectory(join(workspaceRoot, "future-run"), {+ PAPERCLIP_WORKSPACE_CWD: workspaceRoot,+ }),+ ).toThrow("must exist before provider admission");++ expect(() =>+ validateCodexWorkingDirectory(parse(fixture).root, {}),+ ).toThrow("filesystem root");+ expect(() =>+ validateCodexWorkingDirectory(hostRoot, { HOME: hostHome }),+ ).toThrow("cannot contain the host HOME");+ expect(() =>+ validateCodexWorkingDirectory(protectedHomeDirectory, { HOME: hostHome }),+ ).toThrow("cannot overlap the host HOME");+ expect(() =>+ validateCodexWorkingDirectory(outside, {+ PAPERCLIP_WORKSPACE_CWD: workspaceRoot,+ }),+ ).toThrow("outside the assigned workspace");+ expect(() =>+ validateCodexWorkingDirectory(codexWorkspace, {+ CODEX_HOME: codexHome,+ }),+ ).toThrow("cannot overlap host CODEX_HOME");++ const escaped = join(workspaceRoot, "escaped");+ symlinkSync(outside, escaped, "dir");+ expect(() =>+ validateCodexWorkingDirectory(escaped, {+ PAPERCLIP_WORKSPACE_CWD: workspaceRoot,+ }),+ ).toThrow("outside the assigned workspace");++ const file = join(workspaceRoot, "not-a-directory");+ writeFileSync(file, "not a directory");+ expect(() =>+ validateCodexWorkingDirectory(file, {+ PAPERCLIP_WORKSPACE_CWD: workspaceRoot,+ }),+ ).toThrow("must be a directory");+ } finally {+ rmSync(fixture, { recursive: true, force: true });+ }+ });++ it("bounds retained values and redacts protected diagnostics", () => {+ const bounded = boundedCodexPayload({+ short: "ok",+ long: "x".repeat(40_000),+ many: Array.from({ length: 140 }, (_, index) => index),+ });+ expect(String(bounded.long)).toContain("[truncated]");+ expect(bounded.many).toHaveLength(129);+ expect(isRetainableCodexPayload({ value: "x".repeat(70_000) })).toBe(false);++ expect(+ redactCodexValue({+ token: "sensitive",+ message: "Authorization: Bearer abcdefghijklmnop",+ }),+ ).toEqual({+ token: "[REDACTED]",+ message: "Authorization: Bearer [REDACTED]",+ });+ });++ it("keeps completion and block dispositions distinct", () => {+ expect(isCodexSemanticTool("paperclip_finish")).toBe(true);+ expect(isCodexSemanticTool("paperclip_block")).toBe(true);+ expect(isCodexSemanticTool("shell")).toBe(false);+ expect(codexToolAcceptsDisposition("paperclip_finish", "done")).toBe(true);+ expect(codexToolAcceptsDisposition("paperclip_finish", "blocked")).toBe(+ false,+ );+ expect(codexToolAcceptsDisposition("paperclip_block", "blocked")).toBe(+ true,+ );+ expect(codexToolAcceptsDisposition("unknown_tool", "done")).toBe(false);+ });+});diff --git a/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts b/packages/paperclip-runner/src/drivers/codex/codex-boundaries.tsnew file mode 100644index 0000000000..49e95d7b85--- /dev/null+++ b/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts@@ -0,0 +1,213 @@+import { realpathSync, statSync } from "node:fs";+import {+ basename,+ dirname,+ isAbsolute,+ parse,+ relative,+ resolve,+ sep,+} from "node:path";++import {+ CODEX_BLOCK_TOOL_NAME,+ CODEX_COMPLETION_TOOL_NAME,+} from "../../contracts/codex.js";+import type { PrpStructuredRunResult } from "../../protocol/replay-contract.js";+import { redactCodexDiagnostic } from "./app-server-transport.js";++const MAX_RETAINED_CODEX_PAYLOAD_BYTES = 64 * 1024;+const MAX_RETAINED_CODEX_STRING_CHARS = 32 * 1024;++function record(value: unknown): Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++export function validateCodexWorkingDirectory(+ workingDirectory: string,+ environment: NodeJS.ProcessEnv = process.env,+): string {+ if (workingDirectory.trim().length === 0) {+ throw new Error("Codex working directory is required");+ }+ const requested = resolve(workingDirectory);+ let resolved: string;+ try {+ resolved = realpathSync.native(requested);+ if (!statSync(resolved).isDirectory()) {+ throw new Error("Codex working directory must be a directory");+ }+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === "ENOENT") {+ throw new Error(+ "Codex working directory must exist before provider admission",+ );+ }+ throw error;+ }+ if (resolved === parse(resolved).root) {+ throw new Error("Codex working directory cannot be a filesystem root");+ }+ const hostHome = canonicalConfiguredPath(environment.HOME);+ if (hostHome && pathContains(resolved, hostHome)) {+ throw new Error("Codex working directory cannot contain the host HOME");+ }+ if (hostHome && pathContains(hostHome, resolved)) {+ throw new Error("Codex working directory cannot overlap the host HOME");+ }+ const codexHome = canonicalConfiguredPath(environment.CODEX_HOME);+ if (codexHome) {+ if (+ pathContains(resolved, codexHome) ||+ pathContains(codexHome, resolved)+ ) {+ throw new Error("Codex working directory cannot overlap host CODEX_HOME");+ }+ }+ const configuredRoot = environment.PAPERCLIP_WORKSPACE_CWD;+ if (configuredRoot !== undefined && configuredRoot.trim().length > 0) {+ const root = canonicalConfiguredPath(configuredRoot)!;+ const pathFromRoot = relative(root, resolved);+ if (+ pathFromRoot === ".." ||+ pathFromRoot.startsWith(`..${sep}`) ||+ isAbsolute(pathFromRoot)+ ) {+ throw new Error(+ "Codex working directory is outside the assigned workspace",+ );+ }+ }+ return resolved;+}++function canonicalConfiguredPath(value: string | undefined): string | null {+ const configured = value?.trim();+ if (!configured) return null;+ return canonicalPathWithMissingTail(resolve(configured));+}++function canonicalPathWithMissingTail(path: string): string {+ let cursor = path;+ const missing: string[] = [];+ while (true) {+ try {+ return resolve(realpathSync.native(cursor), ...missing);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ const parent = dirname(cursor);+ if (parent === cursor) return resolve(path);+ missing.unshift(basename(cursor));+ cursor = parent;+ }+ }+}++function pathContains(parent: string, candidate: string): boolean {+ const fromParent = relative(parent, candidate);+ return (+ fromParent === "" ||+ (fromParent !== ".." &&+ !fromParent.startsWith(`..${sep}`) &&+ !isAbsolute(fromParent))+ );+}++function boundedCodexValue(value: unknown, depth = 0): unknown {+ if (depth > 8) return { truncated: true, reason: "maximum depth" };+ if (typeof value === "string") {+ return value.length <= MAX_RETAINED_CODEX_STRING_CHARS+ ? value+ : `${value.slice(0, MAX_RETAINED_CODEX_STRING_CHARS)}...[truncated]`;+ }+ if (Array.isArray(value)) {+ const bounded = value+ .slice(0, 128)+ .map((entry) => boundedCodexValue(entry, depth + 1));+ if (value.length > 128) {+ bounded.push({ truncated: true, omittedItems: value.length - 128 });+ }+ return bounded;+ }+ if (typeof value !== "object" || value === null) return value;+ const object = record(value);+ const bounded = Object.fromEntries(+ Object.entries(object)+ .slice(0, 128)+ .map(([key, entry]) => [key, boundedCodexValue(entry, depth + 1)]),+ );+ if (Object.keys(object).length > 128) {+ bounded.truncatedEntries = Object.keys(object).length - 128;+ }+ const serialized = JSON.stringify(bounded);+ return Buffer.byteLength(serialized) <= MAX_RETAINED_CODEX_PAYLOAD_BYTES+ ? bounded+ : { truncated: true, byteSize: Buffer.byteLength(serialized) };+}++export function boundedCodexPayload(+ value: Record<string, unknown>,+): Record<string, unknown> {+ return record(boundedCodexValue(value));+}++export function isRetainableCodexPayload(value: unknown): boolean {+ try {+ return (+ Buffer.byteLength(JSON.stringify(value)) <=+ MAX_RETAINED_CODEX_PAYLOAD_BYTES+ );+ } catch {+ return false;+ }+}++export function isCodexSemanticTool(tool: string): boolean {+ return tool === CODEX_COMPLETION_TOOL_NAME || tool === CODEX_BLOCK_TOOL_NAME;+}++export function codexToolAcceptsDisposition(+ tool: string,+ disposition: PrpStructuredRunResult["reportedWorkDisposition"],+): boolean {+ if (tool === CODEX_BLOCK_TOOL_NAME) {+ return disposition === "blocked";+ }+ if (tool === CODEX_COMPLETION_TOOL_NAME) {+ return disposition === "done" || disposition === "needs_review";+ }+ return false;+}++export function redactCodexValue(value: unknown, depth = 0): unknown {+ if (depth > 8) return "[TRUNCATED]";+ if (typeof value === "string") return redactCodexDiagnostic(value);+ if (Array.isArray(value)) {+ return value+ .slice(0, 128)+ .map((entry) => redactCodexValue(entry, depth + 1));+ }+ const object = record(value);+ return Object.fromEntries(+ Object.entries(object)+ .slice(0, 128)+ .map(([key, entry]) => [+ key,+ /(?:api[_-]?key|token|secret|password|authorization)/i.test(key)+ ? "[REDACTED]"+ : redactCodexValue(entry, depth + 1),+ ]),+ );+}++export function rejectedCodexToolCall(+ message: string,+): Record<string, unknown> {+ return {+ success: false,+ contentItems: [{ type: "inputText", text: message }],+ };+}