Files
PaperClipAI/packages/paperclip-runner/scripts/generate-acpx-sidecar-contract.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

137 lines
11 KiB
JavaScript

import { readFile, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { readAcpxSidecarProtocolVersion } from "./acpx-sidecar-contract.mjs";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const schema = JSON.parse(
await readFile(
resolve(root, "protocol/provider-schemas/acpx-sidecar.schema.json"),
"utf8",
),
);
const commands = schema.$defs.command.enum;
const events = schema.$defs.eventType.enum;
// The sidecar enforces exactly the schema's closed session.open parameter set.
const openParamsSchema = schema.$defs.sessionOpenParams;
if (openParamsSchema?.additionalProperties !== false || !openParamsSchema.properties) {
throw new Error("ACPX sidecar session.open parameters must be a closed object schema");
}
const openParams = Object.keys(openParamsSchema.properties);
const providerPolicySchema = schema.$defs.providerPolicy;
if (providerPolicySchema?.additionalProperties !== false || !providerPolicySchema.properties) {
throw new Error("ACPX sidecar providerPolicy must be a closed object schema");
}
const providerPolicyFields = Object.keys(providerPolicySchema.properties);
const providerTurnOrigin = schema.$defs.providerTurnStarted?.properties?.origin?.const;
const providerTurnLostCode = schema.$defs.providerTurnLost?.properties?.code?.const;
if (typeof providerTurnLostCode !== "string" || schema.$defs.providerTurnLost?.additionalProperties !== false) {
throw new Error("ACPX provider-turn loss diagnostic must be a closed object with a constant code");
}
if (typeof providerTurnOrigin !== "string" || schema.$defs.providerTurnStarted?.additionalProperties !== false) {
throw new Error("ACPX provider-started turn payload must be a closed object with a constant origin");
}
// Mutation wins for compound provider kinds so create-target attestation and
// the normalized readOnly flag cannot disagree across the sidecar boundary.
const toolOperationPrecedence = [
["edit", ["edit", "write", "patch"]],
["read", ["read"]],
["search", ["search", "grep", "find"]],
["list", ["list", "glob"]],
];
const protocolVersion = readAcpxSidecarProtocolVersion(schema);
// The prompt-dispatch journal is a file contract between the sidecar (writer)
// and the Runner (reader after the sidecar is proven gone).
const turnDispatchJournalFile = schema.$defs.turnDispatchJournalFile?.const;
const turnDispatchRecord = schema.$defs.turnDispatchJournalRecord;
const turnDispatchSchema = turnDispatchRecord?.properties?.schema?.const;
const turnDispatchPhases = turnDispatchRecord?.properties?.phase?.enum;
if (
typeof turnDispatchJournalFile !== "string" ||
!/^[a-z0-9.-]+$/.test(turnDispatchJournalFile) ||
typeof turnDispatchSchema !== "string" ||
JSON.stringify(turnDispatchPhases) !== JSON.stringify(["received", "dispatched"]) ||
turnDispatchRecord?.additionalProperties !== false
) {
throw new Error("ACPX turn dispatch journal contract must declare its file, schema and closed phases");
}
const backgroundTasksSchema = schema.$defs.backgroundTasks;
const backgroundLive = backgroundTasksSchema?.properties?.live;
if (
backgroundTasksSchema?.type !== "object" ||
backgroundTasksSchema.additionalProperties !== false ||
JSON.stringify(Object.keys(backgroundTasksSchema.properties ?? {})) !== JSON.stringify(["live"]) ||
JSON.stringify(backgroundTasksSchema.required) !== JSON.stringify(["live"]) ||
backgroundLive?.type !== "integer" ||
backgroundLive.minimum !== 0 ||
!Number.isSafeInteger(backgroundLive.maximum)
) {
throw new Error("ACPX background tasks must be a closed object with one non-negative integer live count");
}
const backgroundLiveMaximum = backgroundLive.maximum;
const quote = (value) => JSON.stringify(value);
const rustVariant = (value) =>
value
.split(/[._-]/)
.map((part) => part[0].toUpperCase() + part.slice(1))
.join("");
const typescript = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\nexport const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION = ${protocolVersion} as const;\nexport const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE = ${quote(turnDispatchJournalFile)};\nexport const GENERATED_ACPX_TURN_DISPATCH_SCHEMA = ${quote(turnDispatchSchema)};\nexport const GENERATED_ACPX_PROVIDER_TURN_ORIGIN = ${quote(providerTurnOrigin)};\nexport const GENERATED_ACPX_PROVIDER_TURN_LOST_CODE = ${quote(providerTurnLostCode)};\nexport const GENERATED_ACPX_SIDECAR_COMMANDS = [\n${commands.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarCommand =\n (typeof GENERATED_ACPX_SIDECAR_COMMANDS)[number];\n\nexport const GENERATED_ACPX_SIDECAR_EVENT_TYPES = [\n${events.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarEventType =\n (typeof GENERATED_ACPX_SIDECAR_EVENT_TYPES)[number];\n\nexport const GENERATED_ACPX_SIDECAR_OPEN_PARAMS = [\n${openParams.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport const GENERATED_ACPX_SIDECAR_PROVIDER_POLICY_FIELDS = [\n${providerPolicyFields.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport const GENERATED_ACPX_BACKGROUND_TASKS_MAX_LIVE = ${backgroundLiveMaximum};\n\nexport type GeneratedAcpxBackgroundTasks = { live: number };\n\nexport function readGeneratedAcpxBackgroundTasks(value: unknown): GeneratedAcpxBackgroundTasks | null {\n if (value === null || typeof value !== "object" || Array.isArray(value)) return null;\n const keys = Object.keys(value);\n const live = (value as Record<string, unknown>).live;\n if (keys.length !== 1 || keys[0] !== "live" || typeof live !== "number" || !Number.isInteger(live)) return null;\n return live >= 0 && live <= GENERATED_ACPX_BACKGROUND_TASKS_MAX_LIVE ? { live } : null;\n}\n\nexport type GeneratedAcpxToolOperation =\n | "read"\n | "search"\n | "list"\n | "edit"\n | "execute"\n | "unknown";\n\nexport const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE = [\n${toolOperationPrecedence.map(([operation, tokens]) => ` { operation: ${quote(operation)}, tokens: [${tokens.map(quote).join(", ")}] },`).join("\n")}\n] as const;\n\nexport function classifyGeneratedAcpxToolOperation(\n toolKind: unknown,\n toolTitle: unknown,\n): GeneratedAcpxToolOperation {\n const candidate =\n typeof toolKind === "string" && toolKind\n ? toolKind\n : typeof toolTitle === "string"\n ? toolTitle\n : "";\n const normalized = candidate.slice(0, 240).toLowerCase();\n for (const { operation, tokens } of GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE) {\n if (tokens.some((token) => normalized.includes(token))) return operation;\n }\n return normalized ? "execute" : "unknown";\n}\n`;
const rust = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\npub const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION: u64 = ${protocolVersion};\npub const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE: &str = ${quote(turnDispatchJournalFile)};\npub const GENERATED_ACPX_TURN_DISPATCH_SCHEMA: &str = ${quote(turnDispatchSchema)};\npub const GENERATED_ACPX_PROVIDER_TURN_ORIGIN: &str = ${quote(providerTurnOrigin)};\npub const GENERATED_ACPX_PROVIDER_TURN_LOST_CODE: &str = ${quote(providerTurnLostCode)};\npub const GENERATED_ACPX_BACKGROUND_TASKS_MAX_LIVE: u64 = ${backgroundLiveMaximum};\n\npub fn read_generated_acpx_background_tasks(value: &serde_json::Value) -> Option<u64> {\n let tasks = value.as_object()?;\n if tasks.len() != 1 {\n return None;\n }\n tasks\n .get("live")?\n .as_u64()\n .filter(|live| *live <= GENERATED_ACPX_BACKGROUND_TASKS_MAX_LIVE)\n}\n\npub const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE: &[(&str, &[&str])] = &[\n${toolOperationPrecedence.map(([operation, tokens]) => ` (${quote(operation)}, &[${tokens.map(quote).join(", ")}]),`).join("\n")}\n];\n\npub fn classify_generated_acpx_tool_operation(kind: &str, title: &str) -> &'static str {\n let kind = kind.to_ascii_lowercase();\n let title = title.to_ascii_lowercase();\n let candidate = if kind.is_empty() { &title } else { &kind };\n for (operation, tokens) in GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE {\n if tokens.iter().any(|token| candidate.contains(token)) {\n return operation;\n }\n }\n if candidate.is_empty() {\n "unknown"\n } else {\n "execute"\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum GeneratedAcpxSidecarCommand {\n${commands.map((value) => ` ${rustVariant(value)},`).join("\n")}\n}\n\nimpl GeneratedAcpxSidecarCommand {\n pub const fn as_str(self) -> &'static str {\n match self {\n${commands.map((value) => ` Self::${rustVariant(value)} => ${quote(value)},`).join("\n")}\n }\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]\npub enum GeneratedAcpxSidecarEventType {\n${events.map((value) => ` #[serde(rename = ${quote(value)})]\n ${rustVariant(value)},`).join("\n")}\n}\n`;
// Classification must inspect the same complete provider value in both
// languages. Display-field truncation happens only after operation selection.
const typescriptWithAsciiLowercase = typescript.replace(
"export function classifyGeneratedAcpxToolOperation(",
`function lowercaseGeneratedAcpxAscii(value: string): string {
return value.replace(/[A-Z]/g, (character) =>
String.fromCharCode(character.charCodeAt(0) + 32),
);
}
export function classifyGeneratedAcpxToolOperation(`,
);
if (typescriptWithAsciiLowercase === typescript) {
throw new Error("generated TypeScript ACPX classifier export drifted");
}
const typescriptClassifier = typescriptWithAsciiLowercase.replace(
"candidate.slice(0, 240).toLowerCase()",
"lowercaseGeneratedAcpxAscii(candidate)",
);
if (typescriptClassifier === typescriptWithAsciiLowercase) {
throw new Error("generated TypeScript ACPX classifier template drifted");
}
const outputs = [
[
resolve(root, "src/drivers/acpx/generated-sidecar-contract.ts"),
typescriptClassifier,
],
[
resolve(
root,
"runner/crates/runner-core/src/generated_acpx_sidecar_contract.rs",
),
rust,
],
];
if (process.argv.includes("--check")) {
const stale = [];
for (const [path, content] of outputs)
if ((await readFile(path, "utf8").catch(() => "")) !== content)
stale.push(path);
if (stale.length > 0) {
process.stderr.write(
`Generated ACPX sidecar contracts are stale: ${stale.join(", ")}\n`,
);
process.exitCode = 1;
} else
process.stdout.write(
"Generated TypeScript/Rust ACPX sidecar contracts match the schema.\n",
);
} else {
await Promise.all(outputs.map(([path, content]) => writeFile(path, content)));
process.stdout.write("Generated TypeScript/Rust ACPX sidecar contracts.\n");
}