Skip to content

The open-source app everyone uses to manage agents at work

10.1 KB
Raw Blame
import { describeRunnerdMuseDriver } from "../drivers/muse/runnerd-muse-driver.js";
import { createCodexTaskEnvelope } from "../contracts/codex.js";
import { ACPX_CAPABILITY_PROFILES } from "../drivers/acpx/capability-profiles.js";
import { NATIVE_EXECUTION_INPUT_SCHEMA, NATIVE_EXECUTION_INPUT_SCHEMA_V7, NATIVE_EXECUTION_INPUT_SCHEMA_V9 } from "../contracts/native-execution.js";
import type { NativeExecutionInput } from "../contracts/native-execution.js";
import type { PersistedHarnessSession } from "../contracts/harness-driver.js";
import type {
  NativeSessionBackend,
  NativeSessionBackendDescriptor,
  PersistedNativeSession,
} from "../contracts/native-session-backend.js";
import type { CodexAppServerTransport } from "../drivers/codex/app-server-transport.js";
import { CodexAppServerDriver } from "../drivers/codex/codex-app-server-driver.js";
import type { CodexWorkingDirectoryAuthority } from "../drivers/codex/codex-boundaries.js";
import { describeRunnerdExternalBotDriver } from "../drivers/dot/runnerd-dot-driver.js";
import { HarnessDriverBackend } from "./harness-driver-backend.js";
import {
  nativeSystemInstructions,
  nativeTaskSkillInputs,
  nativeTaskConstraints,
} from "./runtime-context.js";

export interface CodexNativeSessionBackendOptions {
  /** Effective provider environment, including the assigned workspace boundary. */
  environment?: NodeJS.ProcessEnv;
  observability?: import("../drivers/agent-observability.js").ProviderObservabilityLaunch;
  /** Filesystem that authoritatively admits the workspace path. */
  workingDirectoryAuthority?: CodexWorkingDirectoryAuthority;
  runnerInstanceId?: string;
  onSpawn?: (meta: {
    pid: number;
    processGroupId: number | null;
    startedAt: string;
  }) => Promise<void>;
  transportFactory?: (context?: {
    baseInstructions?: string;
    providerRecoveryPolicy?: PersistedNativeSession["providerRecoveryPolicy"];
    persistedSession?: Pick<
      PersistedHarnessSession,
      | "driverSessionId"
      | "providerSessionId"
      | "providerIdentity"
      | "activeTurnId"
    >;
  }) => CodexAppServerTransport;
  /** Current server constraints; does not commit task status before the turn ends. */
  completionFeedback?: (result: import("../protocol/replay-contract.js").PrpStructuredRunResult) => Promise<string>;
  dynamicTools?: readonly Readonly<Record<string, unknown>>[];
  dynamicToolHandler?: (call: {
    tool: string;
    callId: string;
    threadId: string;
    turnId: string;
    arguments: unknown;
  }) => Promise<unknown>;
}

function transportDriverIdentity(input: NativeExecutionInput): {
  kind:
    | "codex_app_server"
    | "opencode_server"
    | "claude_managed_agents_api"
    | "aws_agentcore_harness_api"
    | "acpx_runtime";
  displayName: string;
  version: string;
} {
  switch (input.provider.kind) {
    case "codex":
      return {
        kind: "codex_app_server",
        displayName: "Codex app-server",
        version: "codex-v2",
      };
    case "opencode":
      return {
        kind: "opencode_server",
        displayName: "OpenCode server",
        version: "1.18.34",
      };
    case "claude_managed":
      return {
        kind: "claude_managed_agents_api",
        displayName: "Claude Managed Agent",
        version: input.provider.managedProfile.betaVersion,
      };
    case "aws_agentcore":
      return {
        kind: "aws_agentcore_harness_api",
        displayName: "AWS AgentCore Harness",
        version: input.provider.agentCoreProfile.qualificationRevision,
      };
    case "acpx":
      return {
        kind: "acpx_runtime",
        displayName: `${ACPX_CAPABILITY_PROFILES[input.provider.agent].displayName} via ACPX`,
        version: "0.13.1",
      };
    default:
      throw new Error(
        "Native provider is not available through the local runnerd transport",
      );
  }
}

function createTransportBackedNativeSessionBackend(
  input: NativeExecutionInput,
  options: CodexNativeSessionBackendOptions,
): NativeSessionBackend {
  if (
    (options.workingDirectoryAuthority === "remote_runner" ||
      options.workingDirectoryAuthority === "runner_prepared_launch") &&
    !options.transportFactory
  ) {
    throw new Error(
      "Remote runner workspace authority requires a runnerd transport",
    );
  }
  const driverIdentity = transportDriverIdentity(input);
  const isCodex = input.provider.kind === "codex";
  const preparedContext = input.schema === NATIVE_EXECUTION_INPUT_SCHEMA
    || input.schema === NATIVE_EXECUTION_INPUT_SCHEMA_V7
    || input.schema === NATIVE_EXECUTION_INPUT_SCHEMA_V9;
  const supportsCollaborativePlanning =
    isCodex ||
    input.provider.kind === "opencode" ||
    input.provider.kind === "acpx";
  if (
    input.provider.kind === "codex" &&
    input.provider.approvalPolicy !== undefined &&
    input.provider.approvalPolicy !== "never"
  ) {
    throw new Error(
      "paperclip_runner_codex_permission_mode_unqualified: set codexPermissionMode to never before starting or recovering this native run",
    );
  }

  const constraints = [
    ...(supportsCollaborativePlanning &&
    "executionMode" in input &&
    input.executionMode === "plan"
      ? [
          "Use native plan collaboration mode and do not modify workspace files.",
          "Treat the supplied Paperclip planning context as the canonical pinned base revision.",
          "Complete one structured provider plan item; Paperclip will synchronize it after completion.",
          "Keep the final response to a short synchronization summary instead of repeating the full plan.",
        ]
      : []),
    ...nativeTaskConstraints(input),
  ];

  const baseInstructions = nativeSystemInstructions(input);
  const transportFactory = options.transportFactory;
  return new HarnessDriverBackend(
    new CodexAppServerDriver({
      ...(input.provider.model ? { model: input.provider.model } : {}),
      ...(input.provider.kind === "codex" && "reasoningEffort" in input.provider && input.provider.reasoningEffort
        ? { reasoningEffort: input.provider.reasoningEffort }
        : {}),
      // Runnerd owns provider permissions for non-Codex facades. Their
      // Codex-compatible surface must never open a second approval channel.
      approvalPolicy:
        input.provider.kind === "codex"
          ? (input.provider.approvalPolicy ?? "never")
          : "never",
      baseInstructions,
      instructionWorkingCopyRoot: "runtimeContext" in input ? input.runtimeContext.instructions.workingCopy?.rootPath : undefined,
      includeSkillInstructions: isCodex && "runtimeContext" in input,
      skillInputs: isCodex
        ? nativeTaskSkillInputs(
            input.task.description,
            "runtimeContext" in input ? input.runtimeContext : null,
          )
        : [],
      requestedCollaborationMode:
        supportsCollaborativePlanning && "executionMode" in input
          ? input.executionMode
          : "default",
      taskEnvelope: createCodexTaskEnvelope({
        objective: input.completionContract.contract.objective,
        contractRevision: input.completionContract.contract.revision,
        criteria: input.completionContract.contract.criteria,
        constraints,
      }),
      conversationMode: preparedContext ? "prepared" : "task",
      runnerInstanceId:
        options.runnerInstanceId ?? `paperclip-native-${input.binding.runId}`,
      onSpawn: options.onSpawn,
      transportFactory: transportFactory
        ? (context) => transportFactory({ ...context, baseInstructions })
        : undefined,
      dynamicTools: options.dynamicTools,
      dynamicToolHandler: options.dynamicToolHandler,
      completionFeedback: options.completionFeedback,
      environment: options.environment,
      observability: options.observability,
      workingDirectoryAuthority: options.workingDirectoryAuthority,
      driverIdentity,
      capabilities: isCodex
        ? {}
        : { steering: false, goals: false, threadLineage: false,
            toolRefreshOnResume: input.provider.kind !== "acpx"
              || ACPX_CAPABILITY_PROFILES[input.provider.agent].toolRefreshOnResume === true },
      collaborationModes: supportsCollaborativePlanning
        ? ["default", "plan"]
        : ["default"],
      requireProviderSessionIdentity: options.transportFactory !== undefined,
    }),
    preparedContext ? constraints : undefined,
  );
}

/** Inspect the selected runnerd harness without starting a provider process. */
export function describeRunnerdNativeSessionBackend(
  input: NativeExecutionInput,
): Promise<NativeSessionBackendDescriptor> {
  if (input.schema === "paperclip.native-execution-input.v6" || input.schema === "paperclip.native-execution-input.v8") {
    // External bots use the shared Rust bridge and retain their provider identity.
    const descriptor = input.schema === "paperclip.native-execution-input.v8"
      ? describeRunnerdMuseDriver() : describeRunnerdExternalBotDriver(input.provider.kind);
    return Promise.resolve({
      kind: "runner",
      name: descriptor.kind,
      version: descriptor.version,
      capabilities: descriptor.capabilities,
      runtimeContextCapabilities: descriptor.runtimeContextCapabilities,
    });
  }
  return createTransportBackedNativeSessionBackend(input, {}).descriptor();
}

/**
 * Uses the Codex JSON-RPC facade strictly as the TypeScript transport shape.
 * Runnerd still selects and owns the real provider process from run.prepare.
 */
export function createRunnerdNativeSessionBackend(
  input: NativeExecutionInput,
  options: CodexNativeSessionBackendOptions,
): NativeSessionBackend {
  if (!options.transportFactory) {
    throw new Error("Runnerd native backend requires a transport factory");
  }
  return createTransportBackedNativeSessionBackend(input, options);
}

/**
 * Constructs the first production-native provider boundary. Other provider
 * contracts may already be persisted, but their runtime implementations are
 * deliberately shipped in separate provider slices.
 */
export function createCodexNativeSessionBackend(
  input: NativeExecutionInput,
  options: CodexNativeSessionBackendOptions = {},
): NativeSessionBackend {
  if (input.provider.kind !== "codex") {
    throw new Error("Codex native backend requires provider kind codex");
  }
  return createTransportBackedNativeSessionBackend(input, options);
}