Files
PaperClipAI/doc/architecture/paperclip-runner.md
T
Devin FoleyandPaperclip 28ed2f1db0 fix(runner): support native OpenCode on macOS SSH hosts (#22534)
## Thinking Path
> - Paperclip coordinates agents across local, SSH, and sandbox
environments.
> - Native Runner must launch artifacts for the execution host.
> - A Linux controller currently selects Linux OpenCode assets for a
macOS SSH host.
> - Remote launch-file validation also accepts only ELF executables.
> - The standard Core image must carry a verified Mac runtime for this
host pair.
> - This pull request adds that runtime and selects it for Apple Silicon
SSH hosts.
> - Self-hosted and hosted controllers can use the same generic
implementation.

## Linked Issues or Issue Description
**What happened?**
A native OpenCode run on an Apple Silicon SSH host receives Linux
controller artifacts. Its private launch-file verifier also rejects
Mach-O files. A working legacy CLI agent does not exercise this path.

**Expected behavior**
The controller must select and verify the target's native daemon, Node,
OpenCode executable, and proxy. Existing Linux targets and legacy agents
must keep their current behavior.

**Steps to reproduce**
1. Run a standard Linux Core image.
2. Select an SSH environment on an Apple Silicon Mac.
3. Start a native OpenCode agent with a compatible model connection.
4. Observe the incompatible runtime selection before useful agent work.

**Paperclip version or commit**
Base: `324ec1f537a9ba1e84239faa81bcef326a5dd1b7`.

**Deployment mode**
Docker or another Linux controller, with macOS ARM64 execution over SSH.

Related work: #21662 covers local OpenCode confinement. #22236 covers
SSH process cleanup. This change does not depend on either PR. No
duplicate macOS OpenCode runtime PR was found.

## What Changed
- Select a verified `darwin-arm64` runtime for OpenCode SSH targets.
Preserve the Linux image default and explicit operator overrides.
- Verify Mach-O launch files against the admitted architecture, file
digests, and remote account. Keep existing Linux receipt and recovery
behavior.
- Build the Mac runtime on an Apple Silicon CI host with standalone Node
24.21.0. Keep OpenCode pinned to 1.18.34.
- Package the sealed OpenCode runtime artifacts and required package
metadata. Omit other harness distributions and their optional
qualification inventories.
- Verify archive provenance and safe extraction on Linux. Include the
runtime in standard and merge-queue Core images. Avoid storing the
transport archive in an image layer.
- Reuse artifacts only from successful protected master image builds
with identical runtime inputs. Test cache trust boundaries and register
the script tests in CI.
- Document runtime delivery, manual image inputs, and the initial Apple
Silicon scope. No Cloud source, schema, or agent configuration changes.

## Verification
- `pnpm -r typecheck` — passed.
- `pnpm build` — passed.
- Focused OpenCode artifact selection and private staging tests — 21
passed.
- Focused native executor tests for OpenCode, SSH, and provider packs —
60 passed.
- Real Rust daemon transport tests with the OpenCode protocol fixture —
4 passed.
- Installed OpenCode 1.18.34 server qualification with a local provider
fixture — 3 passed.
- Runtime packaging, cache trust, workflow, image-contract, and
merge-queue tests — 26 passed.
- The CI release-workflow test group, including canary reuse and
provenance — 218 passed.
- Docker workflow and build-stamp guards — 29 passed after adding the
Mac digest expectation, updating the excluded-source COPY expectation,
and removing the redundant production commit ARG.
- The source SDK registry, public-type, and evidence checks — 59 passed
after updating only the root package metadata hash. Lock, compiler,
parser, and model pins did not change.
- Fresh-host provider-pack upload harness — 7 passed. The new regression
first failed with `package_version:acpx`, then passed after the required
metadata was preserved.
- Node version policy — passed against a clean tracked-file snapshot.
Generated local provider assets make the direct workspace scan fail;
they are absent from the CI checkout.
- Built, packaged, installed, and verified the actual Mac runtime. Both
the controller verifier and the remote startup verifier accept its pins,
target, sealed files, manifest, and package metadata. The pre-change
private launch verifier rejects the real Mach-O files; the candidate
accepts those same files. The dedicated archive is about 101 MB.
- Live native smoke: real Mac daemon, private staged Mach-O files,
OpenCode 1.18.34, and a local GLM-5.3 backend. The model read two files,
edited the implementation, ran three tests, completed the semantic
finish call, and summarized the three passes. An independent test run
passed. The test file stayed unchanged. This used the existing `allow`
mode and a scratch account-home fixture on a Mac. It does not prove
hosted SSH dispatch.
- The full CI workflow passed on
`ae74808631f1933edec89aa1e80db7f2b756aca3`: server test shards, Runner
Rust and native server tests, type checking, builds, browser suites,
image checks, the native Mac producer, and Linux runtime installation.
Greptile is 5/5 with no unresolved threads.
- Local `pnpm test:run` used a disposable PostgreSQL 18 fixture after
embedded Postgres failed to start because its macOS package lacks
dynamic libraries. All six chat shards passed (1,971 tests). The
redundant unsharded local run was interrupted during the general-server
group after all current-head CI test jobs passed. The later local
workspace and serialized groups did not run. The owned PostgreSQL
fixture is stopped. This is not a local full-suite pass.

Retained review failures: the first PR revision omitted package metadata
and did not ignore downloaded image inputs. The fresh-host upload
regression reproduced the metadata failure before its fix. Generated
inputs are now ignored. CI also exposed a missing Node policy exception
for the pinned Mac producer; the exception is limited to that producer
job. A later policy attempt exposed an old exact-dependency assertion in
canary reuse tests. The assertion now covers the added runtime and
evaluates the publication gate for success, failure, cancellation, and
skip outcomes. The Runner support suite then found that the new test
registration changed a pinned root package input; the standard source
registry generator updated that one hash, and all 59 affected tests
passed. The server matrix then found four outdated image guard
expectations and a duplicate production commit ARG. The focused image
guards now pass after updating those expectations and keeping one commit
ARG before Mac verification.

Retained failures: the first producer attempt used Homebrew Node, which
failed the relocation check. The successful producer used standalone
Node 24.21.0. Live smoke attempts also encountered a stopped tunnel, an
upstream model failure, and the existing Rust restriction on OpenCode
permission requests in `ask` mode. The successful tool trace used the
existing `allow` mode. Its initial reporter looked for tool names in
generic item events; verification of the retained canonical tool events
and an independent rerun confirmed the result. The upstream model
failure is not explained by a later pass.

Not run locally: a full Docker image build, because the existing Docker
daemon does not respond. The PR adds native producer qualification and
Linux installation verification to CI. Hosted deployment, remote
service-account dispatch, and hosted continuation remain acceptance
steps after deployment.

## Risks
- A cold Mac runtime build adds CI time when Runner or producer inputs
change. Reuse is bounded and accepts only a successful protected master
producer. The artifact digest and runtime input identity remain
verified.
- Standard images gain a dedicated Mac runtime payload. Manual image
builds can omit it; Mac OpenCode SSH runs then fail with a named
missing-runtime error. Linux behavior remains available.
- This release covers Apple Silicon SSH distribution. It does not
qualify Intel Mac distribution or expand other harness support.
- The OpenCode permission bridge keeps its existing behavior. This PR
does not add `ask` approval support.
- No saved run/session schema or provider pin changes. Existing Linux
receipts retain their interpretation. A surviving admitted Runner
bypasses new artifact discovery. Legacy agents are not converted.
Existing account-change and old-receipt restoration tests remain in
coverage.
- No migration, cluster change, new sandbox image requirement, or Cloud
control-plane change. A staging application rebuild and deployment are
separate from this PR.

## Model Used
OpenAI GPT-6, through Codex, with repository tools, code execution,
tests, and SSH inspection. The session does not expose a more specific
model ID or context-window size.

## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-22 00:07:34 -08:00

13 KiB

ADR: Paperclip Runner architecture

Context

Paperclip is a control plane. It owns companies, agents, issues, budgets, approvals, and durable workflow state. Agent providers remain execution services. Existing adapters invoke those services directly from the Paperclip server.

Paperclip Runner introduces a separate execution process for provider sessions. This process needs durable delivery, restart recovery, and governed access to Paperclip actions. It must not become a second control plane. It must also land without changing the behavior of existing adapters.

The implementation remains behind one explicit experimental adapter and one default-off instance flag. Its qualified provider catalog includes Codex, OpenCode, Claude Managed, AWS AgentCore, and pinned Claude/Codex ACPX profiles.

Decision

Add a standalone package named @paperclipai/paperclip-runner. The package owns the language-neutral Paperclip Runner Protocol (PRP), the Rust runner process, provider drivers, deterministic replay, and semantic action dispatch contracts.

Add one explicit adapter named paperclip_runner. The adapter is available only when an instance-level, default-off rollout flag is enabled. Provider selection is persisted per run and may use only a qualified provider profile.

Do not route existing adapters through Paperclip Runner. A direct adapter keeps its current invocation, transcript, interaction, cancellation, and finalization paths.

Goals

  • Keep runner process ownership outside the Paperclip server process.
  • Preserve Paperclip as the authority for identity, policy, and workflow state.
  • Recover a run after runner or network interruption without duplicate effects.
  • Expose only actions that the current run is allowed to use.
  • Make protocol behavior deterministic across TypeScript and Rust.
  • Keep existing adapter behavior unchanged while the runner is experimental.

Non-goals

  • Replace existing direct adapters.
  • Move business authorization or issue status policy into Rust.
  • Give runnerd a broad Paperclip API credential.
  • Support unqualified provider versions, arbitrary ACPX agents, or editable remote-resource identity in agent configuration.
  • Expose browser SDK, React SDK, eval, lab, or scenario-explorer package entry points in the initial release.
  • Commit recorded screenshots, stress logs, or construction history as product architecture.

Topology

The initial local topology is:

Paperclip server
  |  authenticated PRP v1 WebSocket
  v
paperclip-runnerd
  |  qualified native provider protocol
  v
Codex / OpenCode / ACPX / Claude Managed / AWS AgentCore

The server opens a native run and launches a verified runnerd artifact in the realized execution environment. Runnerd opens the outbound PRP connection. It then owns the provider process group and the durable transport state for that run.

The browser does not connect to runnerd. It reads projections from the existing Paperclip APIs and task-thread models.

Dependency direction

The runner package must build and test without importing Paperclip server, UI, CLI, database, or other private workspace implementation modules.

JSON Schema and fixtures
          |
          +------------------+
          v                  v
 TypeScript contracts   Rust runner core
          |                  |
          +--------+---------+
                   v
         deterministic parity

Paperclip server ----implements----> runner public ports

The dependency points from an implementation to a contract. The Paperclip server may implement a public runner port. The runner package must not import the server implementation.

The initial public package surfaces are:

  • @paperclipai/paperclip-runner for runtime contracts and clients.
  • @paperclipai/paperclip-runner/testing for deterministic fakes and conformance helpers.

Every export must have an implementation and a clean-consumer test before it is published. Later SDK, eval, and lab surfaces require separate decisions.

Protocol boundary

PRP v1 uses a WebSocket at:

/api/runner/v1/connect/:runId

JSON Schema is the language-neutral protocol authority. TypeScript and Rust use the same canonical fixtures and must produce the same replay result.

Protocol rules are fail closed:

  • Unknown required protocol or schema versions are rejected.
  • Unknown required discriminators and enum values are rejected.
  • Additive optional object fields may be accepted when v1 consumers can ignore them safely.
  • Frames, headers, durable state, diagnostic tails, and replay windows are bounded.
  • Event identity and ordering remain stable across reconnect and restart.

Provider-native messages do not cross this boundary. Drivers translate them to provider-neutral PRP events, results, usage, cancellations, and structured input.

Trust boundary

The Paperclip server is authoritative for:

  • company, agent, issue, run, session, and user attribution;
  • rollout and runtime selection;
  • action discovery and authorization;
  • approval, budget, secret, revision, and workspace policy;
  • durable application records and activity history;
  • result acceptance, finalization, and issue status.

Runnerd is authoritative only for its local responsibilities:

  • provider process supervision;
  • provider session and turn transport;
  • durable PRP outbox and command receipts;
  • stable runner-side event identity;
  • bounded process diagnostics.

Runnerd receives a short-lived, one-use bootstrap ticket. The ticket is bound to the company, agent, issue, run, runner, session, turn, and verified artifact. The server exchanges it for a short-lived connection lease. Raw tickets are never stored. Runnerd never receives a broad Paperclip API key.

The server rejects expired, replayed, revoked, cross-company, mismatched, malformed, oversized, or protocol-incompatible connections. Cancellation, timeout, supersession, and environment-lease loss revoke runner authority.

Durable delivery and recovery

Runnerd persists an event before it sends the event. The server acknowledges a cumulative source cursor. Runnerd removes acknowledged data only after it validates that cursor.

A reconnect reports the last processed command, the next source sequence, the last acknowledged source sequence, and the unacknowledged range. The server may then replay one pending command and accept byte-equivalent event retries.

Command identity is idempotent. Reusing a command ID with the same canonical input returns the stored result. Reusing the ID with different input fails closed. A repeated semantic tool call cannot repeat an application effect.

Recovery is bounded. Exhausted storage, reconnect, command, or time limits end the run with a classified failure instead of an unbounded loop.

Semantic actions

PRP carries provider-neutral semantic operation IDs. The package may define an operation catalog, but catalog presence does not grant authority.

For each run, the server projects only operations that have a production binding and that the current actor may discover. An unbound or unauthorized operation is absent from discovery. The server validates inputs, executes the existing application authority, and returns a redacted receipt.

This keeps these invariants in one place:

  • company scoping;
  • actor and run attribution;
  • authorization and approval;
  • revision and idempotency checks;
  • budget and secret policy;
  • activity logging and safe error details.

Runnerd cannot forge identity through tool input. Identity and scope come from the authenticated connection binding.

Structured input

Questions use paperclip.question_set.v1. Responses use the matching canonical response contract. Drivers translate between these provider-neutral records and provider-native input APIs.

The server validates a response at the untrusted API edge and again against the persisted question set before delivery. A process loss may materialize a durable task-thread interaction, but cancellation and an already resolved request must not create a second interaction or continuation.

Persistence and finalization

Native run records are additive. Existing heartbeat and issue records remain readable. A runner result is an untrusted claim. It does not directly update an issue status.

The server validates the result, classifies durable evidence, applies status policy, commits workflow effects, and records finalization. Each phase is idempotent and recoverable. Existing direct adapters keep their existing finalization paths and do not invoke native status arbitration.

Disabling the rollout flag blocks fresh runner starts. It does not make an already persisted native run unreadable or prevent bounded recovery and finalization of that run.

OpenCode on macOS SSH hosts

A Linux controller can launch native OpenCode on an Apple Silicon Mac over SSH. This uses the existing SSH environment and its remote account. It does not require a sandbox image or change an existing legacy agent.

The standard image workflow builds the macOS daemon and provider pack on a native Apple Silicon host. It tests the pinned OpenCode 1.18.34 server, then ships the daemon, Node, proxy and OpenCode executable as a separate runtime. The runtime omits other harness distributions and their optional inventories. The image verifies the archive digest and source revision before installation. Merge-queue images use the same producer, so promotion retains these artifacts. Unchanged runtime inputs can reuse an artifact from a successful protected master image build. The input digest covers the Runner build inputs and the macOS build recipe. Pull request artifacts never supply this reuse authority.

For a macOS SSH target, Core selects the darwin-arm64 runtime under /opt/paperclip-runner/remote-runtimes. Operators can set PAPERCLIP_RUNNER_REMOTE_RUNTIMES_PATH to another absolute runtime parent. The existing default Linux provider pack remains in place for Linux targets. Explicit custom provider-pack or daemon overrides keep their existing meaning.

Runner verifies the selected daemon and pack, then stages private launch files under the SSH account's home. Node and OpenCode must have Mach-O headers for the admitted architecture. Saved artifact and account bindings still apply to continuation and recovery. The agent uses the model endpoint from its own execution environment, such as a loopback SSH tunnel.

A manual Docker build can omit the optional runtime inputs. Such an image continues to support its existing targets, but a macOS OpenCode SSH run fails with a missing-runtime diagnostic. To include the runtime, place the same-source producer's darwin-arm64.json and darwin-arm64.tar.gz in docker/remote-runtimes/ before the image build. Keep these generated files out of Git. Intel Mac SSH runtime distribution is outside this release.

Rollout

The rollout has three gates:

  1. The instance flag is enabled.
  2. The agent explicitly selects paperclip_runner.
  3. The adapter selects a provider from the qualified catalog: Codex, OpenCode, pinned Claude/Codex ACPX, Claude Managed, or AWS AgentCore.

The adapter is hidden from creation and selection surfaces while the flag is off. Server validation also rejects a fresh runner selection or start while the flag is off. UI hiding is not the security boundary.

Runtime selection is persisted before launch. Later setting changes cannot silently move an in-flight run between the direct and native execution paths.

The detailed compatibility rules are in Paperclip Runner compatibility and rollout.

Observability

The server records structured runner, provider, semantic action, interaction, usage, and terminal events. Logs and receipts must not contain bootstrap tickets, leases, provider credentials, secret values, complete environments, or private host paths.

The task page may project these records through existing thread components. A runner-only control must depend on persisted runtime facts. It must not depend only on the agent adapter profile.

Consequences

This design adds process, protocol, and recovery complexity. In return, it gives provider sessions a durable and testable execution boundary without moving Paperclip governance into the runner.

The default-off, explicit-adapter rollout duplicates some provider configuration during the experiment. This is intentional. It keeps comparison and rollback simple and prevents a global migration of existing agents.

The standalone package boundary requires generated artifacts, clean-consumer tests, and cross-language parity gates. These checks add build cost, but they prevent server implementation details from becoming accidental public API.

Required proof before general availability

  • TypeScript and Rust accept and reject the same protocol fixtures.
  • Lost acknowledgements, reconnects, runner restarts, and duplicate commands do not duplicate events or effects.
  • Bootstrap replay, binding mismatch, and cross-company access fail closed.
  • Only authorized and production-bound actions appear in discovery.
  • Cancellation settles provider, runner, transport, and application state.
  • Flag-off direct-adapter runs create no native records and start no runner process.
  • Persisted native runs remain readable and recoverable after the flag changes.
  • Codex completes the server to PRP to runnerd to provider to server path.
  • Existing adapter compatibility tests remain byte stable where specified.