Files
PaperClipAI/packages/paperclip-runner/test/acpx-sidecar-contract.test.mjs
Nicky LeachandClaude Opus 5.5 1332ab987f feat(prp): declare the contract for provider-started turns (#21422)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Runner runs Claude Code through the ACPX sidecar.
> - Claude can start a shell command in the background and end its turn.
When the command finishes, Claude Code starts a cycle of its own to
continue. Today the Runner stops Claude at the end of the turn, so the
command stops and the run fails with `native_finalization_missing`.
> - A stack of pull requests lets the Runner accept that cycle as a new
turn of the same run, when a controller asks for it.
> - The Runner, its sidecar and the controller speak two protocols with
schemas: PRP between the controller and the Runner, and the sidecar
protocol between `paperclip-runnerd` and the ACPX sidecar.
> - A turn that the provider starts needs new fields and one new command
in those protocols.
> - This pull request declares them and generates the readers again. It
changes no behavior.
> - The benefit is that the next two pull requests show behavior only,
with the contract already in review.

## Linked Issues or Issue Description

No public issue exists. The issue is described here.

This pull request is one part of a change that was first opened as one
large pull request (#21316). The parts, in stack order after #21311:

1. #21419: sidecar preparation (a refactor).
2. #21420: converter for raw ACP session updates.
3. #21421: cycle stream at the adapter.
4. #21422: contract for provider-started turns.
5. #21423: `paperclip-runnerd` waits for a provider-started turn.
6. #21316: the sidecar adopts a cycle.

This is part 4. Its base branch is `feat/claude-provider-cycle-stream`.
After each part, a production run does the same as today, because no
controller sends the opt-in. Refs #19912 (design).

**What existing behavior does this improve?**

Nothing in production. The protocol schemas.

**Subsystem affected**

Paperclip Runner: `protocol/` and the generated TypeScript and Rust
contract code.

**Current behavior**

- PRP has no way to say that a turn was started by the provider, or that
the Runner waits for such a turn.
- The sidecar protocol has no command to arm the sidecar and no event
for a turn that the provider starts.

**Proposed behavior**

- PRP (`schemas/provider-turn.schema.json`, new): `providerStartedTurns`
(boolean) in the payload of `turn.start`, `origin: "provider"` on
`turn.started`, and `awaitingProviderTurn: true` on `turn.completed`.
`command-v3` and `event-v3` refer to it.
- Sidecar protocol (`provider-schemas/acpx-sidecar.schema.json`): the
command `session.provider_turn` with `{ turnId, armed }`, the event
`runtime.turn_started` with `{ origin: "provider" }`, and the payload of
the diagnostic for a lost provider. The schema enforces that payload for
a `runtime.diagnostic` with the code `ACPX_PROVIDER_PROCESS_LOST`.
Diagnostics with other codes keep their open payload.
- `paperclip-runnerd` decodes `runtime.turn_started` and refuses it. No
sidecar sends it yet. The Runner of today refuses an unknown event too.
- No controller, Runner or sidecar uses the new fields in this pull
request.

**Reason and benefit**

The repository rule for Runner contracts says that new fields must be in
the schema with generated readers. A separate pull request lets a
reviewer read the contract alone.

## What Changed

- `protocol/schemas/provider-turn.schema.json` (new),
`command-v3.schema.json`, `event-v3.schema.json`,
`protocol/provider-schemas/acpx-sidecar.schema.json`,
`protocol/manifest.json`.
- `scripts/generate-acpx-sidecar-contract.mjs` and
`scripts/generate-protocol-schema-module.mjs`.
- Generated: `src/drivers/acpx/generated-sidecar-contract.ts`,
`src/protocol/generated/schema-bundle.ts`,
`src/protocol/generated/standalone-validators.ts`,
`runner/crates/runner-core/src/generated_acpx_sidecar_contract.rs`.
- `runner/crates/runner-core/src/acpx_event_payload.rs` (3 lines): the
Rust `match` on the event type must name the new event to compile.
- `test/protocol-contract.test.mjs`.
- The contract digests of the pack change (`prp.acpx-sidecar`,
`prp.command-v3`, `prp.event-v3`, `rust`, and the new
`prp.provider-turn`). No stored file refers to these digests. No
provider `commandDigest` and no profile version changes.

## Verification

At the head of this branch, from `packages/paperclip-runner`:

- `npx tsc --noEmit -p tsconfig.json`, `npx tsc --noEmit -p
tsconfig.test.json`, `pnpm run typecheck:typescript`, `pnpm run
build:typescript`, `node --test test/acpx-sidecar-contract.test.mjs
test/protocol-contract.test.mjs`, the server check `node
scripts/verify-runner-vendor-dependencies.mjs`, `node --test
scripts/__tests__/runner-release-crate-cache.test.mjs`, `cargo fmt
--check` and `cargo build -p paperclip-runner-core --bins` (no new
warning): all passed. The contract tests: 32 passed.
- The sidecar suite and the tracker tests: 141 passed.

Not run: the full suite. CI supplies that coverage.

## Risks

- **The pack contract digest changes.** Older image packs are not used
again.
- **The opt-in field is accepted by the schema but has no effect yet.**
A controller that sends it before part 5 gets the behavior of today.
- **State saved by the previous release:** this pull request changes no
persisted shape.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the
change and the split, reviewed the diff, and ran a part of the
verification again.
- Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with
tool use (shell, file edits, local test runs), wrote the change and the
tests and cut this slice from the full change.

## 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 00:20:45 +00:00

323 lines
17 KiB
JavaScript

import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import Ajv2020 from "ajv/dist/2020.js";
import { readAcpxSidecarProtocolVersion } from "../scripts/acpx-sidecar-contract.mjs";
const schema = JSON.parse(
await readFile(
new URL(
"../protocol/provider-schemas/acpx-sidecar.schema.json",
import.meta.url,
),
"utf8",
),
);
const providerFailureSchema = JSON.parse(await readFile(new URL("../protocol/schemas/provider-failure.schema.json", import.meta.url), "utf8"));
function compileSidecarSchema(value) {
return new Ajv2020({ allErrors: true, strict: true,
formats: { "date-time": /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/ },
}).addSchema(providerFailureSchema).compile(value);
}
const validate = compileSidecarSchema(schema);
const protocolVersion = readAcpxSidecarProtocolVersion(schema);
const messages = [
{
protocolVersion,
id: 1,
command: "initialize",
params: {},
},
{
protocolVersion,
id: 1,
ok: true,
result: {},
},
{
protocolVersion,
sequence: 1,
eventType: "runtime.event",
runId: "run-1",
turnId: "turn-1",
payload: {},
},
];
test("the ACPX sidecar schema accepts each versioned message family", () => {
for (const message of messages) {
assert.equal(validate(message), true, JSON.stringify(validate.errors));
}
});
test("usage prices declare turn or session scope without changing legacy cumulative prices", () => {
const event = cost => ({ protocolVersion, sequence: 1, eventType: "runtime.event", runId: "run-1", turnId: "turn-1",
payload: { type: "status", tag: "usage_update", cost } });
for (const cost of [null, { amount: 0.1, currency: "USD" }, { amount: 0.1, currency: "USD", basis: "turn" },
{ amount: 0.1, currency: "USD", basis: "session_cumulative" }]) {
assert.equal(validate(event(cost)), true, JSON.stringify(validate.errors));
}
for (const cost of [{ amount: -1 }, { amount: 0.1, basis: "estimated" }, { amount: 0.1, rawProviderReceipt: {} }]) {
assert.equal(validate(event(cost)), false);
}
});
test("failed responses accept the bounded provider cause and reject extra diagnostic fields", () => {
const failure = { schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup",
category: "rate_limit", message: "Account rate limit reached.", httpStatus: 429, retryability: "unknown" };
const response = { protocolVersion, id: 1, ok: false,
error: { code: "ACPX_SESSION_ENSURE_FAILED", message: "Internal error", retryable: false } };
assert.equal(validate(response), true);
const withCause = value => ({ ...response, error: { ...response.error, providerFailure: value } });
assert.equal(validate(withCause(failure)), true, JSON.stringify(validate.errors));
for (const change of [{ httpStatus: 999 }, { message: "x".repeat(4001) }, { headers: { authorization: "private" } }, { category: "invented" }]) {
assert.equal(validate(withCause({ ...failure, ...change })), false);
}
});
test("candidate startup and sidecar admission share one strict identity-bound JSON record", () => {
const candidateAdmission = { schema: "paperclip.acpx-candidate-admission.v1", companyId: "company-1", agent: "antigravity", model: "gemini-3.8-flash-low",
profileDigest: `sha256:${"a".repeat(64)}`, nativeClosureDigest: `sha256:${"b".repeat(64)}`, platform: "darwin", architecture: "arm64",
expiresAt: 1800000060000, runId: "run-1", normalizedSessionId: "session-1" };
const startup = compileSidecarSchema({ ...schema, oneOf: undefined, $ref: "#/$defs/candidateAdmission" });
assert.equal(startup(candidateAdmission), true, JSON.stringify(startup.errors));
for (const command of ["initialize", "session.open"]) {
const request = { protocolVersion, id: 1, command, params: { agent: "antigravity", model: candidateAdmission.model, candidateAdmission } };
assert.equal(validate(request), true, JSON.stringify(validate.errors));
for (const change of [{ unknown: true }, { runId: undefined }, { normalizedSessionId: "wrong session" }, { platform: "linux" }, { expiresAt: "1800000060000" }]) {
const altered = JSON.parse(JSON.stringify({ ...request, params: { ...request.params, candidateAdmission: { ...candidateAdmission, ...change } } }));
assert.equal(validate(altered), false);
assert.equal(startup(altered.params.candidateAdmission), false);
}
assert.equal(validate({ ...request, params: { ...request.params, agent: "codex" } }), false);
}
assert.equal(validate({ protocolVersion, id: 1, command: "turn.start", params: { candidateAdmission } }), false);
});
test("Pi session admission requires an explicit supported thinking level including recovery", () => {
const open = (params) => ({ protocolVersion, id: 1, command: "session.open", params });
for (const piThinkingLevel of ["off", "low", "high", "max"]) {
assert.equal(validate(open({ agent: "pi", piThinkingLevel })), true, JSON.stringify(validate.errors));
assert.equal(validate(open({ agent: "pi", piThinkingLevel, expectedIdentity: null })), true);
assert.equal(validate(open({ agent: "pi", piThinkingLevel, expectedIdentity: { piThinkingLevel } })), true);
}
for (const piThinkingLevel of [undefined, null, "medium", "minimal", "xhigh", " LOW ", 1]) {
assert.equal(validate(open({ agent: "pi", piThinkingLevel })), false);
assert.equal(validate(open({ agent: "pi", piThinkingLevel: "low", expectedIdentity: { piThinkingLevel } })), false);
}
for (const agent of ["claude", "codex", "grok", "cursor", "copilot"]) {
assert.equal(validate(open({ agent })), true);
assert.equal(validate(open({ agent, expectedIdentity: null })), true);
assert.equal(validate(open({ agent, piThinkingLevel: "low" })), false);
assert.equal(validate(open({ agent, expectedIdentity: { piThinkingLevel: "low" } })), false);
}
});
test("session.open accepts only the schema's closed parameter set", () => {
const open = (params) => ({ protocolVersion, id: 1, command: "session.open", params });
const names = Object.keys(schema.$defs.sessionOpenParams.properties);
assert.ok(names.includes("grokEffort") && names.includes("runtimeContext"));
for (const name of names.filter(name => !["agent", "piThinkingLevel", "claudeEffort", "candidateAdmission", "expectedIdentity", "providerPolicy"].includes(name))) {
assert.equal(validate(open({ agent: "codex", [name]: "value" })), true, name);
}
assert.equal(validate(open({ agent: "codex", unsupportedField: true })), false);
for (const providerPolicy of [null, { readOnly: true }, { readOnly: false }]) {
assert.equal(validate(open({ agent: "codex", providerPolicy })), true, JSON.stringify(providerPolicy));
}
for (const providerPolicy of [{}, { readOnly: "yes" }, { readOnly: true, extra: true }]) {
assert.equal(validate(open({ agent: "codex", providerPolicy })), false, JSON.stringify(providerPolicy));
}
});
test("the runtime context schema closes every nested object", async () => {
const runtimeSchema = JSON.parse(await readFile(new URL("../protocol/provider-schemas/runtime-context.schema.json", import.meta.url), "utf8"));
const validateContext = new Ajv2020({ allErrors: true, strict: true }).compile(runtimeSchema);
const hex = "a".repeat(64);
const asset = { schema: "paperclip.runtime-asset.v1", digest: hex, manifestDigest: hex, rootPath: "/bundle", fileCount: 1, totalBytes: 2 };
const context = {
prompt: { revision: "paperclip-execution.v8", text: "prompt", digest: hex },
instructions: { entryPath: "AGENTS.md", bundle: asset, workingCopy: { rootPath: "/work", entryPath: "AGENTS.md", kind: "agent_files" } },
skills: [{ key: "skill", runtimeName: "skill", versionId: null, bundle: asset }],
mcp: { assignmentSetId: "set", digest: hex, bindingId: null },
connectionInstructions: { text: "connect", digest: hex },
aggregateDigest: hex,
};
assert.equal(validateContext(context), true, JSON.stringify(validateContext.errors));
const nested = [[], ["prompt"], ["instructions"], ["instructions", "bundle"], ["instructions", "workingCopy"], ["mcp"], ["connectionInstructions"]];
for (const path of nested) {
const altered = structuredClone(context);
path.reduce((value, key) => value[key], altered).unexpected = true;
assert.equal(validateContext(altered), false, path.join("."));
}
const alteredSkill = structuredClone(context);
alteredSkill.skills[0].unexpected = true;
assert.equal(validateContext(alteredSkill), false);
});
test("public Pi descriptors preserve effective thinking levels without invalidating historical replay", async () => {
const descriptorSchema = JSON.parse(await readFile(new URL("../protocol/schemas/provider-descriptor.schema.json", import.meta.url), "utf8"));
const validateDescriptor = new Ajv2020({ allErrors: true, strict: true, strictRequired: false }).compile(descriptorSchema);
const historical = {
provider: "acpx", driver: "acpx_runtime", model: "model", executionKind: "local_process",
providerVersion: "0.22.0", agent: "pi", requestedModel: "model", acpProtocolVersion: 1,
agentServerPackage: "pi-acp", agentServerVersion: "0.0.33", acpxRecordId: null, agentProcessId: null,
};
assert.equal(validateDescriptor(historical), true, JSON.stringify(validateDescriptor.errors));
for (const piThinkingLevel of ["off", "low", "high", "max"]) {
assert.equal(validateDescriptor({ ...historical, piThinkingLevel }), true);
}
for (const piThinkingLevel of ["medium", null, "xhigh", 1]) {
assert.equal(validateDescriptor({ ...historical, piThinkingLevel }), false);
}
assert.equal(validateDescriptor({ ...historical, agent: "copilot", piThinkingLevel: "low" }), false);
assert.equal(validateDescriptor({ ...historical, provider: "codex", driver: "codex_app_server", piThinkingLevel: "low" }), false);
});
test("the ACPX sidecar schema shares the durable stable-identity boundary", () => {
const longestTurnId = "t".repeat(240);
assert.equal(validate({ ...messages[2], turnId: longestTurnId }), true);
assert.equal(validate({ ...messages[2], turnId: "t".repeat(241) }), false);
for (const turnId of ["turn 1", "réturn-1", "turn/1", "_turn-1"]) {
assert.equal(validate({ ...messages[2], turnId }), false, turnId);
}
assert.equal(validate({ ...messages[2], runId: "r".repeat(161) }), false);
for (const runId of ["run 1", "rún-1", "run/1", "_run-1"]) {
assert.equal(validate({ ...messages[2], runId }), false, runId);
}
});
test("rich activity has a closed display-only envelope and explicit run/turn scope", () => {
const message = {
...messages[2],
eventType: "runtime.rich_event",
payload: { eventType: "plan.updated", itemId: "display-1", payload: {} },
};
assert.equal(validate(message), true, JSON.stringify(validate.errors));
for (const field of ["runId", "turnId"]) {
assert.equal(validate({ ...message, [field]: null }), false);
}
for (const eventType of ["turn.completed", "run.result.proposed", "semantic_tool.input", "unknown"]) {
assert.equal(validate({ ...message, payload: { ...message.payload, eventType } }), false);
}
for (const field of ["sourceRef", "priority", "runId"]) {
assert.equal(validate({ ...message, payload: { ...message.payload, [field]: "forged" } }), false);
}
});
test("the ACPX sidecar schema fails closed on drift", () => {
for (const message of [
{ ...messages[0], protocolVersion: protocolVersion + 1 },
{ ...messages[0], command: "session.destroy" },
{ protocolVersion, id: 1, ok: true, result: {}, error: error() },
{ protocolVersion, id: 1, ok: true },
{ protocolVersion, id: 1, ok: false },
{ protocolVersion, id: 1, ok: false, result: {}, error: error() },
{ ...messages[2], unexpected: true },
]) {
assert.equal(validate(message), false);
}
});
test("every ACPX sidecar message family uses the shared version", () => {
for (const family of ["request", "response", "event"]) {
assert.deepEqual(schema.$defs[family].properties.protocolVersion, {
$ref: "#/$defs/protocolVersion",
});
}
});
test("the ACPX sidecar schema id carries the declared protocol version", () => {
assert.equal(
schema.$id,
`https://paperclip.dev/schemas/acpx-sidecar/v${protocolVersion}/message.schema.json`,
);
});
test("a coordinated family-version upgrade cannot outpace the schema id", () => {
const driftedSchema = structuredClone(schema);
driftedSchema.$defs.protocolVersion.const = protocolVersion + 1;
assert.throws(
() => readAcpxSidecarProtocolVersion(driftedSchema),
/must match its authoritative schema \$id/,
);
});
function error() {
return {
code: "runtime_failed",
message: "The runtime failed.",
retryable: false,
};
}
test("turn control schema preserves explicit modes and rejects open-ended dispatch", () => {
const message = { protocolVersion, id: 1, command: "turn.steer", params: {
turnId: "turn-1", controlId: "control-1", mode: "follow_up", message: "Then validate",
} };
assert.equal(validate(message), true, JSON.stringify(validate.errors));
for (const params of [ { ...message.params, mode: "cancel" }, { ...message.params, method: "arbitrary" },
{ ...message.params, controlId: "" }, { ...message.params, turnId: "wrong turn" }, { ...message.params, mode: undefined } ]) {
assert.equal(validate({ ...message, params }), false);
}
});
// Runtime payloads are provider-owned; the sidecar envelope stays closed.
// Pi validates native provenance before creating these boundary/history fields.
test("Pi native empty message boundaries and replay history fit the strict sidecar envelope", () => {
for (const payload of [
{ type: "text_delta", stream: "output", text: "", messageId: "message-1", piMessageBoundary: { phase: "start" } },
{ type: "text_delta", stream: "output", text: "", messageId: "message-1", piMessageBoundary: { phase: "end", stopReason: "toolUse" } },
{ type: "text_delta", stream: "output", text: "Prior assistant reply", messageId: "history-1", piMessageHistory: true },
]) {
assert.equal(validate({ ...messages[2], payload }), true, JSON.stringify(validate.errors));
assert.equal(validate({ ...messages[2], payload, piMessageBoundary: { phase: "start" } }), false);
}
});
test("a terminal's background task report matches the shared accepted and rejected vectors", async () => {
const vectors = JSON.parse(await readFile(new URL("../protocol/fixtures/provider-boundary/acpx-background-tasks.json", import.meta.url), "utf8"));
const terminal = (payload) => ({ ...messages[2], eventType: "runtime.turn_terminal", payload });
assert.equal(validate(terminal({ status: "completed" })), true, JSON.stringify(validate.errors));
for (const { value } of vectors.accepted) {
assert.equal(validate(terminal({ status: "completed", backgroundTasks: value })), true, JSON.stringify(value));
}
for (const { value, case: name } of vectors.rejected) {
assert.equal(validate(terminal({ status: "completed", backgroundTasks: value })), false, name);
}
});
test("provider-started turn frames are closed and the provider-lost diagnostic is enforced only for its code", () => {
const event = (eventType, payload, extra = {}) => ({ ...messages[2], eventType, payload, ...extra });
assert.equal(validate(event("runtime.turn_started", { origin: "provider" }, { turnId: "provider-1" })), true, JSON.stringify(validate.errors));
assert.equal(validate(event("runtime.turn_started", { origin: "controller" })), false);
assert.equal(validate(event("runtime.turn_started", { origin: "provider", extra: true })), false);
assert.equal(validate(event("runtime.turn_started", { origin: "provider" }, { turnId: null })), false);
const diagnostic = (payload) => event("runtime.diagnostic", payload, { turnId: null });
assert.equal(validate(diagnostic({ code: "ACPX_PROVIDER_PROCESS_LOST", message: "The provider exited." })), true, JSON.stringify(validate.errors));
assert.equal(validate(diagnostic({ code: "ACPX_PROVIDER_PROCESS_LOST", message: "x".repeat(8_192) })), true, JSON.stringify(validate.errors));
for (const payload of [
{ code: "ACPX_PROVIDER_PROCESS_LOST" },
{ code: "ACPX_PROVIDER_PROCESS_LOST", message: "x".repeat(8_193) },
{ code: "ACPX_PROVIDER_PROCESS_LOST", message: 7 },
{ code: "ACPX_PROVIDER_PROCESS_LOST", message: "The provider exited.", detail: "extra" },
]) {
assert.equal(validate(diagnostic(payload)), false, JSON.stringify(payload));
}
for (const payload of [
{ code: "sidecar_input_failed", message: "Bad input." },
{ code: "sidecar_shutdown_requested", message: "x".repeat(9_000) },
{ code: "malformed_frame" },
{ code: "acpx_terminal_usage_unavailable", message: "Unavailable.", detail: "extra" },
]) {
assert.equal(validate(diagnostic(payload)), true, JSON.stringify(payload));
}
const command = (params) => ({ ...messages[0], command: "session.provider_turn", params });
assert.equal(validate(command({ turnId: "turn-1", armed: true })), true, JSON.stringify(validate.errors));
assert.equal(validate(command({ turnId: "turn-1" })), false);
assert.equal(validate(command({ turnId: "turn-1", armed: true, extra: 1 })), false);
});