fix(runner): restore native Claude context and read permissions (#13422)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native runner supplies each agent with instructions, assigned
skills, and tools.
> - Native Claude lost its skill snapshot before provider launch. It
also changed exact model IDs to aliases.
> - The read permission mode denied ordinary Paperclip reads because
this runner has no interactive approval handler.
> - This pull request restores the missing context and permits only
assigned tools that Paperclip defines as reads.
> - Other requests that need approval stop with a clear action for the
operator. They do not retry automatically.
> - Agents can complete read tasks. Users can see why a restricted task
stopped.

## Linked Issues or Issue Description

**What happened?**

Native Claude could not find assigned skills. The ACP layer could
replace an exact model ID with an alias and then fail identity
verification. The default `approve-reads` mode denied Paperclip read
tools. A denied write showed a generic transport failure.

The tool descriptions also called live operations “mock” operations. The
completion prompt said to call a completion tool once, although the
protocol can reject a claim and require a corrected call.

**Expected behavior**

Load assigned skills before launch. Keep the selected model ID. Allow
assigned Paperclip reads. Stop an operation that needs approval with
clear instructions when no approval handler exists.

**Steps to reproduce**

1. Configure a native Paperclip Runner agent with ACPX Claude and an
exact model ID.
2. Assign a skill and ask the agent to use it.
3. Select the read permission mode and ask the agent to read task
context and list documents.
4. Ask the agent to write a document. Check the task state and recovery
message.

**Paperclip version or commit**

Reproduced from `d351e08deee1b49d3467a950d1a3f01131943441`.

**Deployment mode**

Local native runner with real Claude, Rust runnerd, the Paperclip
server, and embedded PostgreSQL.

Related: #13196 fixed remote skill staging in the legacy `claude_local`
adapter. The native runner uses a separate path, which this pull request
fixes.

## What Changed

- Carry the runtime context through Rust and the ACPX sidecar. Load
assigned Claude skills after the provider lifetime lease is held.
Refresh the files on each open.
- Write the exact requested model ID into the isolated Claude settings.
- Grant exact MCP permissions for the intersection of assigned tools and
Paperclip's read catalog. Provider hints cannot grant access. Existing
task-control permissions stay in place.
- Stop requests that need an unavailable approval handler. Preserve the
typed error through the server. Show “Approval required” on the task and
require operator action without automatic retry.
- Label the setting “Allow Paperclip reads.” Remove “mock” from live
tool descriptions and regenerate the contracts.
- Change one completion-prompt sentence to require one accepted result.
Add regression tests and update the runner documentation.

## Verification

- Red/green regression tests cover read admission, unavailable approval
handling, server recovery, and the task error message.
- A real Claude read trial failed before the fix and completed after it:
[red
trace](https://www.braintrust.dev/app/Paperclip/object?object_type=project_logs&object_id=fda74078-b00d-495a-90d3-ea1be019d71b&id=95e6a326e24437f1),
[green
trace](https://www.braintrust.dev/app/Paperclip/object?object_type=project_logs&object_id=fda74078-b00d-495a-90d3-ea1be019d71b&id=85a1f347db5604d1).
- Full browser tests used real Claude and the production tool authority.
Reads completed. A write stopped with “Approval required.” No document
was created and no automatic retry was scheduled. All nine checks
passed: [events and
screenshots](https://www.braintrust.dev/app/Paperclip/object?object_type=project_logs&object_id=fda74078-b00d-495a-90d3-ea1be019d71b&id=1c4ff10be0d779cc).
- A separate full browser test assigned a skill, invoked it, and
completed with a marker absent from the task prompt: [skill
evidence](https://www.braintrust.dev/app/Paperclip/object?object_type=project_logs&object_id=fda74078-b00d-495a-90d3-ea1be019d71b&id=ba5fbcb29a60be52).
- Post-rebase checks passed: 128 targeted runner tests, 46 Rust tests,
27 sidecar/protocol contract tests, `pnpm -r typecheck`, and `pnpm
build`. The server/UI red-green checks and `pnpm check:token-gates` also
passed. The full suite passed in CI, including all general and
serialized test shards, all three browser shards, and runner
`check:all`. The duplicate unsharded local full-suite run was stopped
after CI passed.

Braintrust links require project access. The traces contain
provider/runner events and app outcomes. They do not contain raw model
HTTP requests.

## Risks

- `approve-reads` now allows assigned Paperclip reads. Other operations
that need approval stop the turn. Users must review the operation and
change permissions before retrying.
- The Claude settings depend on the pinned ACP and SDK behavior.
Automated tests and real Claude trials cover this boundary.
- The native Codex path is unchanged. The ACPX Codex fallback shares the
clearer approval failure handling.
- Local execution was tested end to end. Remote execution was not run.
This change has no database migration.

## Model Used

OpenAI GPT-6 through Codex. The agent used reasoning, code execution,
and browser tools. The exact deployment ID and context-window size were
not exposed in the session. Live acceptance tests used
`claude-sonnet-5`.

## 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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-14 10:56:24 -05:00
1 parent 728f7185f6
commit 78ce96a48b
52 files changed
+485 -110

No files matched your search

@@ -117,9 +117,9 @@ export const PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES = {
},
{
value: "approve-reads",
label: "Conservative (fail closed)",
label: "Allow Paperclip reads",
description:
"Delegate ACPX permission requests and fail closed until a verified interactive approval bridge is available.",
"Automatically allow assigned Paperclip read tools. Other operations stop with an approval-required message because this runner has no interactive approval handler.",
},
{
value: "deny-all",
+29
View File
@@ -56,6 +56,35 @@ stdin/stdout bridge admits the pinned Claude and Codex ACPX profiles. It
validates the exact model, session identity, tool catalog, structured input,
and terminal settlement at the process boundary. Pi remains unavailable.
Native Claude skill assignments travel in the runtime-context snapshot through
runnerd to the ACPX sidecar. After acquiring the provider lifetime lease, the
host materializes the assigned bundles under the isolated Claude home's
`skills/` directory before launch. Reopening a provider refreshes that snapshot;
project and ambient host settings remain excluded. This path is separate from
the legacy `claude_local` adapter's remote skill staging.
The isolated Claude settings pin both `model` and `availableModels` to the
user's requested ID. This keeps ACP from replacing an exact ID with a picker
alias during selection and verification. Users can keep selecting models from
the normal Claude catalog or entering custom IDs; unavailable models still fail
at the provider rather than silently falling back.
For ACPX Claude, `approve-reads` is shown as **Allow Paperclip reads**. The host
intersects the run's public tools with the implementation catalog's read effects
and writes exact MCP permission rules into the isolated Claude settings. The
`paperclip` connection is always the runner's authenticated tool bridge; ambient
MCP configuration is excluded. Tool hints and provider permission metadata cannot
grant access. Unassigned tools, writes, external tools, and provider-native
operations do not receive automatic read permission. Protocol completion and
task-delivery controls keep their existing separate allowance.
This runtime has no interactive permission handler. An operation that still
requires approval stops the turn with `approval_required`. The server marks the
task blocked, exposes the permission action to the operator, and disables
automatic retry. The operator must review the operation and the agent's
permission setting before retrying. Company access checks still run when each
Paperclip tool executes.
Runnerd selects only qualified provider profiles. Claude Managed and AWS
AgentCore receive immutable company-profile snapshots with explicit retention,
spend, and invocation limits. No provider process receives a Paperclip API
@@ -1 +1 @@
[{"annotations":{"exposure":"always","operationId":"get_task_context","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the active task and actor, including the exact approved Markdown revision when this issue has an accepted plan.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"get_task_context","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"get_task_history","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded comments on the active mock task.","inputSchema":{"additionalProperties":false,"properties":{"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":[],"type":"object"},"name":"get_task_history","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_documents","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List revisioned documents on the active mock task.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_documents","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"read_document","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the current revision of one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable issue-document key.","maxLength":120,"minLength":1,"type":"string"}},"required":["key"],"type":"object"},"name":"read_document","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_document_revisions","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded revision history for one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable issue-document key.","maxLength":120,"minLength":1,"type":"string"},"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":["key"],"type":"object"},"name":"list_document_revisions","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"report_progress","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Append a durable progress comment to the active mock task.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Multiline progress update.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"report_progress","outputSchema":{"additionalProperties":false,"properties":{"commandId":{"description":"Stable mock command identifier.","maxLength":200,"minLength":1,"type":"string"},"disposition":{"enum":["applied","duplicate"]},"entityRefs":{"description":"Mock entities affected by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"scheduledWakeIds":{"description":"Wake identifiers scheduled by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"stateRevision":{"minimum":0,"type":"integer"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds"],"type":"object"}},{"annotations":{"exposure":"always","operationId":"answer_status_question","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Append the answer to a status-only wake without changing task disposition.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Concise status answer.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"answer_status_question","outputSchema":{"additionalProperties":false,"properties":{"commandId":{"description":"Stable mock command identifier.","maxLength":200,"minLength":1,"type":"string"},"disposition":{"enum":["applied","duplicate"]},"entityRefs":{"description":"Mock entities affected by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"scheduledWakeIds":{"description":"Wake identifiers scheduled by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"stateRevision":{"minimum":0,"type":"integer"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds"],"type":"object"}},{"annotations":{"exposure":"always","operationLine truncated
[{"annotations":{"exposure":"always","operationId":"get_task_context","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the active task and actor, including the exact approved Markdown revision when this issue has an accepted plan.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"get_task_context","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"get_task_history","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded comments on the active task.","inputSchema":{"additionalProperties":false,"properties":{"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":[],"type":"object"},"name":"get_task_history","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_documents","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List revisioned documents on the active task.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_documents","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"read_document","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the current revision of one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable issue-document key.","maxLength":120,"minLength":1,"type":"string"}},"required":["key"],"type":"object"},"name":"read_document","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_document_revisions","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded revision history for one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable issue-document key.","maxLength":120,"minLength":1,"type":"string"},"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":["key"],"type":"object"},"name":"list_document_revisions","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"report_progress","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Append a durable progress comment to the active task.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Multiline progress update.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"report_progress","outputSchema":{"additionalProperties":false,"properties":{"commandId":{"description":"Stable command identifier.","maxLength":200,"minLength":1,"type":"string"},"disposition":{"enum":["applied","duplicate"]},"entityRefs":{"description":"Entities affected by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"scheduledWakeIds":{"description":"Wake identifiers scheduled by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"stateRevision":{"minimum":0,"type":"integer"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds"],"type":"object"}},{"annotations":{"exposure":"always","operationId":"answer_status_question","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Append the answer to a status-only wake without changing task disposition.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Concise status answer.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"answer_status_question","outputSchema":{"additionalProperties":false,"properties":{"commandId":{"description":"Stable command identifier.","maxLength":200,"minLength":1,"type":"string"},"disposition":{"enum":["applied","duplicate"]},"entityRefs":{"description":"Entities affected by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"scheduledWakeIds":{"description":"Wake identifiers scheduled by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"stateRevision":{"minimum":0,"type":"integer"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds"],"type":"object"}},{"annotations":{"exposure":"always","operationId":"write_document","requiredClaimLine truncated
@@ -24,7 +24,7 @@
"prpVersion": 1,
"nativeExecutionVersion": 1,
"catalogVersion": 1,
"catalogSha256": "sha256:155849f666fffed8133d497c4323d42639eae7696699f9df049649f836e2edbc",
"catalogSha256": "sha256:d86fe304faa341cb46f92c93b6c80a6b8666770ebd915ffe61c7c9d3399e6524",
"driverContractVersion": 1,
"driverKind": "paperclip-deterministic",
"driverVersion": "1.0.0"
@@ -160,7 +160,7 @@
},
{
"path": "fixtures/evals/native-execution-seeded.json",
"sha256": "43bda8e713605d690a5e755f2d47eaea012d28fef81bd7dc787a5f9cacc507a7",
"sha256": "dcba9c50475b86260067a7e0789577fc7a5c0624fe3e3552bf3e111c8f9da0ac",
"expectation": "accept",
"compatibilityCase": "canonical"
},
@@ -248,6 +248,7 @@ impl AcpxProviderDescriptor {
permission_mode: self.permission_mode,
permission_mode_pinned: self.permission_mode_pinned,
system_instructions: self.instructions.clone(),
runtime_context: self.runtime_context.clone(),
tool_set,
expected_identity,
})
@@ -63,6 +63,7 @@ pub struct AcpxProviderSessionConfig {
pub permission_mode: AcpxPermissionMode,
pub permission_mode_pinned: bool,
pub system_instructions: String,
pub runtime_context: Value,
pub tool_set: AuthorizedToolSet,
pub expected_identity: Option<AcpxProviderSessionIdentity>,
}
@@ -992,7 +993,7 @@ fn bootstrap(
"permissionMode": config.permission_mode,
"permissionModePinned": config.permission_mode_pinned,
"systemInstructions": config.system_instructions,
"runtimeContext": Value::Null,
"runtimeContext": config.runtime_context,
"tools": &sidecar_tools,
"expectedIdentity": config.expected_identity,
}),
@@ -52,6 +52,7 @@ fn config(directory: &std::path::Path) -> AcpxProviderSessionConfig {
permission_mode: AcpxPermissionMode::ApproveReads,
permission_mode_pinned: true,
system_instructions: "Complete the supplied task.".to_owned(),
runtime_context: serde_json::Value::Null,
tool_set: AuthorizedToolSet {
schema: "paperclip.runner.authorized-tools.v1".to_owned(),
schema_version: 1,
@@ -51,6 +51,7 @@ fn config(mode: &str) -> AcpxProviderSessionConfig {
permission_mode: AcpxPermissionMode::ApproveReads,
permission_mode_pinned: true,
system_instructions: "Complete the supplied task.".to_owned(),
runtime_context: serde_json::Value::Null,
tool_set: tool_set(),
expected_identity: None,
}
@@ -46,6 +46,7 @@ fn config(mode: &str) -> AcpxProviderSessionConfig {
permission_mode: AcpxPermissionMode::ApproveReads,
permission_mode_pinned: true,
system_instructions: "Complete the supplied task.".to_owned(),
runtime_context: serde_json::Value::Null,
tool_set: tool_set(),
expected_identity: None,
}
@@ -27,6 +27,7 @@ fn config(mode: &str) -> AcpxProviderSessionConfig {
permission_mode: AcpxPermissionMode::ApproveReads,
permission_mode_pinned: true,
system_instructions: "Complete the supplied task.".to_owned(),
runtime_context: serde_json::Value::Null,
tool_set: AuthorizedToolSet {
schema: "paperclip.runner.authorized-tools.v1".to_owned(),
schema_version: 1,
@@ -46,6 +46,7 @@ fn config(mode: &str) -> AcpxProviderSessionConfig {
permission_mode: AcpxPermissionMode::ApproveReads,
permission_mode_pinned: true,
system_instructions: "Complete the supplied task.".to_owned(),
runtime_context: serde_json::Value::Null,
tool_set: tool_set(),
expected_identity: None,
}
@@ -60,7 +60,7 @@ describe("native runtime context files", () => {
).join("\n");
expect(constraints).toContain(
"Invoke paperclip_finish or paperclip_block exactly once before writing",
"Obtain one accepted result from paperclip_finish or paperclip_block before writing",
);
expect(constraints).toContain("do not call another tool");
expect(constraints).not.toContain(
@@ -27,7 +27,7 @@ export function nativeSystemInstructions(input: NativeExecutionInput): string {
export function nativeTaskConstraints(input: NativeExecutionInput): string[] {
const finalResponseConstraint =
"Invoke paperclip_finish or paperclip_block exactly once before writing the complete user-facing final response. Use paperclip_finish with yielded and a response_wake continuation only when explicitly waiting for the next response. If the tool rejects an incomplete report, correct it and retry. When it succeeds, read its outcome and explain any pending approval with the supplied link and required action. Do not claim the task is done when completion is still gated. Then write the final response exactly once and do not call another tool.";
"Obtain one accepted result from paperclip_finish or paperclip_block before writing the complete user-facing final response. Use paperclip_finish with yielded and a response_wake continuation only when explicitly waiting for the next response. If the tool rejects an incomplete report, correct it and retry. When it succeeds, read its outcome and explain any pending approval with the supplied link and required action. Do not claim the task is done when completion is still gated. Then write the final response exactly once and do not call another tool.";
const answeredQuestions = Array.isArray(input.interactionResponses)
? input.interactionResponses.flatMap((response, responseIndex) => {
if (
@@ -10,6 +10,7 @@ import type {
} from "acpx/runtime";
import { createAcpxToolEventNormalizer } from "../provider-events.js";
import { parseNativeRuntimeContext } from "../contracts/runtime-context.js";
import {
PRP_BLOCK_TOOL_NAME,
PRP_COMPLETION_TOOL_NAME,
@@ -23,6 +24,7 @@ import {
type NormalizedAcpForm,
} from "../drivers/acpx/acp-question-adapter.js";
import { openCodexAcpxRuntime } from "../drivers/acpx/codex-runtime-adapter.js";
import { AcpxApprovalRequiredError } from "../drivers/acpx/permission-policy.js";
import { acpxGoalProjection } from "../drivers/acpx/session-goals.js";
import { acpxProviderSessionIdentity } from "../drivers/acpx/recovery-identity.js";
import {
@@ -261,6 +263,7 @@ async function dispatch(
model: params.model,
permissionMode: params.permissionMode,
systemInstructions: params.systemInstructions,
runtimeContext: params.runtimeContext,
environment: process.env,
expectedIdentity: params.expectedIdentity,
semanticTools: {
@@ -563,7 +566,11 @@ async function pumpTurn(
} catch (error) {
terminal = {
status: "failed",
error: { message: safeMessage(error), retryable: false },
error: {
...(error instanceof AcpxApprovalRequiredError ? { code: error.code } : {}),
message: safeMessage(error),
retryable: false,
},
};
} finally {
rejectTurnWaiters(currentTurnId, "ACPX turn became terminal");
@@ -1012,9 +1019,6 @@ function parseOpenParams(
const agent = requireQualifiedAgent(value.agent);
const model = requiredText(value.model, "model");
resolveQualifiedAcpxProfile(agent, model);
if (value.runtimeContext !== undefined && value.runtimeContext !== null) {
throw new Error("ACPX sidecar runtime context must be pre-materialized");
}
if (
value.providerSessionKey !== undefined &&
value.providerSessionKey !== null
@@ -1039,7 +1043,9 @@ function parseOpenParams(
"systemInstructions",
1024 * 1024,
),
runtimeContext: null,
runtimeContext: value.runtimeContext == null
? null
: parseNativeRuntimeContext(value.runtimeContext),
tools: parseTools(value.tools),
...(value.expectedIdentity === undefined || value.expectedIdentity === null
? {}
@@ -28,6 +28,46 @@ const HANDLE: AcpRuntimeHandle = {
};
describe("Codex ACPX runtime adapter", () => {
it("stops a turn with an actionable error when approval has no handler", async () => {
const runtime = fakeRuntime();
let runtimeOptions: AcpRuntimeOptions | undefined;
let signal: AbortSignal | undefined;
let settle!: () => void;
const finished = new Promise<void>((resolve) => { settle = resolve; });
vi.mocked(runtime.startTurn).mockImplementation((input) => {
signal = input.signal;
signal?.addEventListener("abort", settle, { once: true });
return {
requestId: "permission-test",
promptStarted: Promise.resolve(),
events: (async function* () { await finished; })(),
result: finished.then(() => ({ status: "cancelled" as const })),
cancel: async () => settle(),
closeStream: async () => settle(),
} as ReturnType<AcpRuntime["startTurn"]>;
});
const options = openOptions(fakeCommand());
options.permissionMode = "approve-reads";
const port = await openCodexAcpxRuntime(options, {
createRegistry: () => registry(),
createStore: () => store(),
createRuntime: (created) => { runtimeOptions = created; return runtime; },
});
const turn = port.startTurn({ text: "Attempt a write.", requestId: "permission-test" });
try {
await runtimeOptions!.onPermissionRequest!({
sessionId: "backend-1", inferredKind: "write", raw: {},
}, { signal: new AbortController().signal });
expect(signal?.aborted).toBe(true);
await expect(turn.result).rejects.toThrow("Approval required");
await expect((async () => { for await (const _event of turn.events) { /* drain */ } })())
.rejects.toThrow("Approval required");
} finally {
settle();
await port.close({ reason: "permission failure verified" });
}
});
it("rejects a pre-aborted admission before constructing or spawning ACPX", async () => {
const cancellation = new Error("runtime admission cancelled");
const controller = new AbortController();
@@ -1334,7 +1374,7 @@ describe("Codex ACPX runtime adapter", () => {
text: "Complete the task.",
mode: "prompt",
requestId: "turn-1",
signal,
signal: expect.any(AbortSignal),
onElicitation,
});
});
@@ -1564,7 +1604,7 @@ describe("Codex ACPX runtime adapter", () => {
await port.close({ reason: "complete" });
});
it("delegates permissions that require an unavailable coordinator", async () => {
it("rejects permissions that require an unavailable coordinator", async () => {
const runtime = fakeRuntime();
let runtimeOptions: AcpRuntimeOptions | undefined;
const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), {
@@ -1585,16 +1625,16 @@ describe("Codex ACPX runtime adapter", () => {
},
{ signal: new AbortController().signal },
),
).resolves.toBeUndefined();
).resolves.toEqual({ outcome: "reject_once" });
await port.close({ reason: "complete" });
});
it.each([
["codex", "gpt-5.6-sol", "approve-all", { outcome: "allow_once" }],
["codex", "gpt-5.6-sol", "approve-reads", undefined],
["codex", "gpt-5.6-sol", "approve-reads", { outcome: "reject_once" }],
["codex", "gpt-5.6-sol", "deny-all", { outcome: "reject_once" }],
["claude", "claude-sonnet-5", "approve-all", { outcome: "allow_once" }],
["claude", "claude-sonnet-5", "approve-reads", undefined],
["claude", "claude-sonnet-5", "approve-reads", { outcome: "reject_once" }],
["claude", "claude-sonnet-5", "deny-all", { outcome: "reject_once" }],
] as const)(
"applies the %s/%s ACPX profile's %s mode without an implicit prompt bridge",
@@ -27,7 +27,7 @@ import {
awaitVerifiedAcpxProviderOwnership,
} from "./installation-integrity.js";
import type { AcpxModelStatus } from "./model-verification.js";
import { decideAcpxPermission } from "./permission-policy.js";
import { AcpxApprovalRequiredError, decideAcpxPermission } from "./permission-policy.js";
const VERIFIED_COMMAND_SENTINEL = "paperclip-verified-acpx-command";
const DEFAULT_RUNTIME_CLOSE_TIMEOUT_MS = 2_000;
@@ -245,6 +245,7 @@ export async function openQualifiedAcpxRuntime(
.filter((server) => server.runnerOwned)
.map((server) => server.name),
);
const permissionBoundary: { active: AbortController | null } = { active: null };
const goalState: AcpxRuntimeGoalState = {
capability: null,
snapshot: null,
@@ -308,7 +309,14 @@ export async function openQualifiedAcpxRuntime(
options.mcpServers.every((server) => server.runnerOwned),
},
);
return disposition === "delegate" ? undefined : { outcome: disposition };
if (disposition === "delegate") {
// This runtime has no interactive approval bridge. Stop the active
// turn instead of asking the model to recover from an unexplained
// denial or wait for an approval that nobody can answer.
permissionBoundary.active?.abort(new AcpxApprovalRequiredError());
return { outcome: "reject_once" };
}
return { outcome: disposition };
},
onAgentInitialize: (result) => {
const capability = goalCapabilityFromAcpMessage({ result });
@@ -441,6 +449,7 @@ export async function openQualifiedAcpxRuntime(
runtimeCloseTimeoutMs,
goalState,
commandLaunches,
permissionBoundary,
);
} catch (error) {
const cleanupReason = "ACPX runtime identity validation failed";
@@ -868,6 +877,7 @@ function runtimePort(
runtimeCloseTimeoutMs: number,
goalState: AcpxRuntimeGoalState,
commandLaunches: { count: number; refreshConsumedCommand?: () => Promise<void> },
permissionBoundary: { active: AbortController | null },
): AcpxRuntimePort {
type RuntimeCloseAttempt = {
readonly outcome: Promise<unknown | null>;
@@ -1191,6 +1201,8 @@ function runtimePort(
}
: {}),
startTurn(input) {
const approval = new AbortController();
permissionBoundary.active = approval;
const finishOwnershipAdmission =
children.beginLifetimeOwnershipAdmission();
let turn: AcpxRuntimeTurn;
@@ -1200,16 +1212,42 @@ function runtimePort(
text: input.text,
mode: "prompt",
requestId: input.requestId,
...(input.signal ? { signal: input.signal } : {}),
signal: input.signal
? AbortSignal.any([input.signal, approval.signal])
: approval.signal,
...(input.onElicitation
? { onElicitation: input.onElicitation }
: {}),
});
} catch (error) {
if (permissionBoundary.active === approval) permissionBoundary.active = null;
void finishOwnershipAdmission().catch(() => undefined);
throw error;
}
return turnWithVerifiedLifetimeOwnership(turn, finishOwnershipAdmission);
const guarded = turnWithVerifiedLifetimeOwnership(turn, finishOwnershipAdmission);
const result = guarded.result.then(
(value) => { approval.signal.throwIfAborted(); return value; },
(error: unknown) => { approval.signal.throwIfAborted(); throw error; },
).finally(() => {
if (permissionBoundary.active === approval) permissionBoundary.active = null;
});
void result.catch(() => undefined);
return {
...guarded,
result,
events: (async function* () {
try {
for await (const event of guarded.events) {
approval.signal.throwIfAborted();
yield event;
}
} catch (error) {
approval.signal.throwIfAborted();
throw error;
}
approval.signal.throwIfAborted();
})(),
};
},
close: closeRuntime,
};
@@ -2,10 +2,22 @@ import { describe, expect, it } from "vitest";
import {
acpxRuntimePermissionPolicy,
claudeReadPermissionRules,
decideAcpxPermission,
} from "./permission-policy.js";
describe("ACPX permission policy", () => {
it("uses only catalogued reads assigned to this run, regardless of tool hints", () => {
const tools = [
"paperclip__get_task_context", "read_document", "write_document",
"call_api", "request_approval", "unknown_read", "mcp__other__get_task_context",
].map((name) => ({ name, annotations: { readOnlyHint: true, effect: "read" } }));
expect(claudeReadPermissionRules(tools)).toEqual([
"mcp__paperclip__get_task_context", "mcp__paperclip__read_document",
]);
expect(claudeReadPermissionRules([])).toEqual([]);
});
it("maps each configured mode to a closed ACP runtime policy", () => {
expect(acpxRuntimePermissionPolicy("approve-all")).toEqual({
defaultAction: "approve",
@@ -1,6 +1,37 @@
import type { NativeAcpxPermissionMode } from "../../contracts/native-execution.js";
import { paperclipSemanticAction } from "../../catalog/semantic-action-catalog.js";
import { canonicalRunnerToolName } from "../runner-tool-bridge.js";
import type { QualifiedAcpxAgent } from "./qualified-profiles.js";
export class AcpxApprovalRequiredError extends Error {
readonly code = "approval_required";
constructor() {
super(
"Approval required. This operation is not an automatically allowed Paperclip read, " +
"and this runner has no interactive approval handler. Review the operation and " +
"update the agent's permission setting before retrying.",
);
this.name = "AcpxApprovalRequiredError";
}
}
/** Exact SDK rules for the run's runner-owned Paperclip MCP connection. */
export function claudeReadPermissionRules(
tools: readonly Readonly<Record<string, unknown>>[],
): string[] {
const names = tools.flatMap((tool) => {
if (typeof tool.name !== "string") return [];
const name = canonicalRunnerToolName(tool.name);
// Effects come from Paperclip's implementation catalog, never tool hints
// or the provider's permission-request metadata. Unknown operations stay
// subject to approval even when their names or annotations claim a read.
return paperclipSemanticAction(name)?.effect === "read"
? [`mcp__paperclip__${name}`]
: [];
});
return [...new Set(names)].sort();
}
export interface AcpxPermissionRequestLike {
inferredKind?: unknown;
raw?: unknown;
@@ -29,8 +60,8 @@ export function acpxRuntimePermissionPolicy(
if (mode === "deny-all") return { defaultAction: "deny" };
// ACPX derives permission kinds from provider-originated requests. Until the
// host can bind a request to independent authority, no kind is safe to
// auto-approve. Escalation delegates to the coordinator and otherwise fails
// closed through the non-interactive permission policy.
// auto-approve here. Verified Paperclip reads are allowed earlier at the
// Claude SDK dispatch boundary. Other requests require an approval handler.
return { defaultAction: "escalate" };
}
@@ -48,7 +79,7 @@ export function decideAcpxPermission(
if (mode === "approve-all") return "allow_once";
// inferredKind and raw semantic/MCP metadata both originate outside the
// runner trust boundary. Neither can grant local read or semantic authority.
// A future verified decision must carry runner-issued call identity bound to
// the run-scoped catalog; absent that proof, the coordinator decides.
// Verified Paperclip reads use exact SDK rules on the runner-owned MCP
// connection. Anything reaching this fallback still requires approval.
return "delegate";
}
@@ -1,9 +1,18 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
NATIVE_RUNTIME_ASSET_SCHEMA,
PAPERCLIP_EXECUTION_PROMPT,
PAPERCLIP_EXECUTION_PROMPT_REVISION,
canonicalNativeRuntimeContextDigest,
nativeRuntimePromptDigest,
type NativeRuntimeContextSnapshot,
} from "../../contracts/runtime-context.js";
import { releaseMaterializedNativeRuntimeSkills } from "../runtime-context-materializer.js";
import { openCodexAcpxRuntime } from "./codex-runtime-adapter.js";
import { stageManagedCodexCredential } from "./codex-credentials.js";
import type {
@@ -166,6 +175,112 @@ afterEach(async () => {
});
describe("ACPX runtime host", () => {
it("automatically permits only admitted Paperclip reads in the Claude SDK", async () => {
const fixture = await hostFixture();
const dependencies = fixture.dependencies({
openRuntime: async (options) => {
const settings = JSON.parse(await readFile(
join(options.launchEnvironment.CLAUDE_CONFIG_DIR!, "settings.json"),
"utf8",
));
expect(settings.permissions).toEqual({
allow: ["mcp__paperclip__get_task_context"],
});
expect(options.mcpServers).toMatchObject([
{ name: "paperclip", runnerOwned: true },
]);
return runtimePort({
getStatus: async () => ({ models: { currentModelId: "claude-sonnet-5" } }),
});
},
});
const host = await AcpxRuntimeHost.open({
...fixture.options,
agent: "claude",
model: "claude-sonnet-5",
permissionMode: "approve-reads",
semanticTools: {
tools: ["get_task_context", "write_document", "unknown_read"].map((name) => ({
name,
inputSchema: { type: "object" },
// Supplied hints cannot grant write or unknown operations read access.
annotations: { readOnlyHint: true, effect: "read" },
})),
handler: async () => ({}),
},
}, dependencies);
await host.close({ reason: "read permission verified" });
});
it("loads assigned Claude skills before launch and refreshes them when reopening", async () => {
const fixture = await hostFixture();
const skillRoot = join(fixture.root, "assigned-source");
await mkdir(join(skillRoot, "references"), { recursive: true });
await writeFile(join(skillRoot, "SKILL.md"), "---\nname: assigned\ndescription: Read the reference.\n---\nRead references/answer.txt.");
await writeFile(join(skillRoot, "references", "answer.txt"), "ASSIGNED_SKILL_MARKER");
const digest = "0".repeat(64);
const bundle = {
schema: NATIVE_RUNTIME_ASSET_SCHEMA,
digest,
manifestDigest: digest,
rootPath: skillRoot,
fileCount: 2,
totalBytes: 100,
};
const snapshot = {
prompt: {
revision: PAPERCLIP_EXECUTION_PROMPT_REVISION,
text: PAPERCLIP_EXECUTION_PROMPT,
digest: nativeRuntimePromptDigest(),
},
instructions: { entryPath: "AGENTS.md", bundle },
skills: [{ key: "assigned", runtimeName: "assigned", versionId: "v1", bundle }],
mcp: { assignmentSetId: "none", digest, bindingId: null },
} satisfies Omit<NativeRuntimeContextSnapshot, "aggregateDigest">;
const context = {
...snapshot,
aggregateDigest: canonicalNativeRuntimeContextDigest(snapshot),
};
let skillsHome = "";
let assigned = true;
const dependencies = fixture.dependencies({
openRuntime: async (options) => {
skillsHome = join(options.launchEnvironment.CLAUDE_CONFIG_DIR!, "skills");
expect(await readdir(skillsHome)).toEqual(assigned ? ["assigned"] : []);
if (assigned) {
const reference = join(skillsHome, "assigned", "references", "answer.txt");
expect(await readFile(reference, "utf8")).toBe("ASSIGNED_SKILL_MARKER");
expect((await stat(reference)).mode & 0o222).toBe(0);
}
return runtimePort({
getStatus: async () => ({ models: { currentModelId: "claude-sonnet-5" } }),
});
},
});
const options = {
...fixture.options,
agent: "claude" as const,
model: "claude-sonnet-5",
permissionMode: "deny-all" as const,
};
try {
// Fresh open and a provider reopen both have the complete bundle.
for (let index = 0; index < 2; index += 1) {
const host = await AcpxRuntimeHost.open(
{ ...options, runtimeContext: context },
dependencies,
);
await host.close({ reason: "reopen test" });
}
// No stale assignment survives a later launch without runtime context.
assigned = false;
const host = await AcpxRuntimeHost.open(options, dependencies);
await host.close({ reason: "test complete" });
} finally {
if (skillsHome) await releaseMaterializedNativeRuntimeSkills(skillsHome);
}
});
it("rejects a pre-aborted admission before acquiring provider resources", async () => {
const fixture = await hostFixture();
const controller = trackedAdmissionController();
@@ -1,3 +1,5 @@
import { join } from "node:path";
import type {
AcpElicitationHandler,
AcpRuntimeEvent,
@@ -5,6 +7,11 @@ import type {
} from "acpx/runtime";
import type { NativeAcpxPermissionMode } from "../../contracts/native-execution.js";
import type { NativeRuntimeContextSnapshot } from "../../contracts/runtime-context.js";
import {
materializeNativeRuntimeSkills,
releaseMaterializedNativeRuntimeSkills,
} from "../runtime-context-materializer.js";
import {
startRunnerToolBridge,
type RunnerToolBridge,
@@ -195,6 +202,7 @@ export interface OpenAcpxRuntimeHostOptions {
model: string;
permissionMode: NativeAcpxPermissionMode;
systemInstructions?: string;
runtimeContext?: NativeRuntimeContextSnapshot | null;
environment?: NodeJS.ProcessEnv;
managedCodexCredentialSourcePath?: string;
expectedIdentity?: AcpxExpectedSessionIdentity;
@@ -366,6 +374,7 @@ export class AcpxRuntimeHost {
binding,
agent: options.agent,
environment: options.environment,
tools: options.semanticTools?.tools,
}),
dependencies.retainAdmissionCleanup,
);
@@ -396,6 +405,18 @@ export class AcpxRuntimeHost {
dependencies.reportRetainedCleanupFailure(failure),
});
}
if (options.agent === "claude") {
// The lifetime lease proves the previous provider has stopped. Refresh
// the assigned snapshot before every launch, including durable resume;
// Claude discovers user skills beneath its isolated CLAUDE_CONFIG_DIR.
const skillsHome = join(sandbox.agentHomeDirectory, "skills");
await releaseMaterializedNativeRuntimeSkills(skillsHome);
await materializeNativeRuntimeSkills(
options.runtimeContext ?? null,
skillsHome,
);
options.signal?.throwIfAborted();
}
command = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: () => installation.openCommand(),
@@ -34,6 +34,23 @@ afterEach(async () => {
});
describe("ACPX runtime sandbox", () => {
it.each(["claude-sonnet-5", "sonnet", "custom-deployment-id"])(
"preserves the requested Claude model %s in its isolated settings",
async (model) => {
const fixture = await sandboxFixture("claude");
const sandbox = await prepareAcpxRuntimeSandbox({
binding: { ...fixture.binding, requestedModel: model },
agent: "claude",
});
const settingsPath = join(sandbox.agentHomeDirectory, "settings.json");
expect(JSON.parse(await readFile(settingsPath, "utf8"))).toMatchObject({
model,
availableModels: [model],
});
expect((await stat(settingsPath)).mode & 0o777).toBe(0o600);
},
);
it.each([
["pi", "OPENROUTER_API_KEY", "pi-home"],
["claude", "ANTHROPIC_API_KEY", "claude-home"],
@@ -28,6 +28,7 @@ import {
} from "node:path";
import { createSanitizedAcpxSpawnInput } from "./environment.js";
import { claudeReadPermissionRules } from "./permission-policy.js";
import type { QualifiedAcpxAgent } from "./qualified-profiles.js";
import {
resolveAcpxRuntimeRoot,
@@ -324,6 +325,8 @@ export async function prepareAcpxRuntimeSandbox(input: {
binding: AcpxRecoveryBinding;
agent: QualifiedAcpxAgent;
environment?: NodeJS.ProcessEnv;
/** Public operations on the runner-owned Paperclip MCP bridge only. */
tools?: readonly Readonly<Record<string, unknown>>[];
}): Promise<AcpxRuntimeSandbox> {
const expectedRoot = input.binding.runtimeRoot;
if (resolve(expectedRoot) !== expectedRoot) {
@@ -366,6 +369,21 @@ export async function prepareAcpxRuntimeSandbox(input: {
workspaceRecordPath,
`${input.binding.workspacePath}\n`,
);
if (input.agent === "claude") {
// ACP otherwise rewrites exact IDs (including user-entered model IDs) to
// picker aliases such as "sonnet". Its supported availableModels setting
// preserves our requested ID through selection and model verification.
await writePrivateFile(
join(agentHomeDirectory, "settings.json"),
`${JSON.stringify({
model: input.binding.requestedModel,
availableModels: [input.binding.requestedModel],
...(input.binding.permissionMode === "approve-reads"
? { permissions: { allow: claudeReadPermissionRules(input.tools ?? []) } }
: {}),
})}\n`,
);
}
if (input.agent === "pi") {
await writePrivateFile(
join(agentHomeDirectory, "settings.json"),
@@ -104,7 +104,7 @@ export const answerStatusQuestionAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -120,7 +120,7 @@ export const answerStatusQuestionAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -25,7 +25,7 @@ export const blockTaskAction = {
},
"documentation": {
"title": "Block active task",
"description": "Block the active mock task with a durable reason and optional first-class dependencies.",
"description": "Block the active task with a durable reason and optional first-class dependencies.",
"note": null
},
"examples": {
@@ -66,7 +66,7 @@ export const blockTaskAction = {
"operationId": "block_task",
"version": 1,
"title": "Block active task",
"description": "Block the active mock task with a durable reason and optional first-class dependencies.",
"description": "Block the active task with a durable reason and optional first-class dependencies.",
"exposure": "always",
"requiredClaims": [],
"allowedModes": [
@@ -90,7 +90,7 @@ export const blockTaskAction = {
},
"blockedByTaskIds": {
"type": "array",
"description": "Internal mock task ids that block this task.",
"description": "Internal task ids that block this task.",
"items": {
"type": "string",
"minLength": 1
@@ -110,7 +110,7 @@ export const blockTaskAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -126,7 +126,7 @@ export const blockTaskAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -29,7 +29,7 @@ export const commentOnApprovalAction = {
},
"documentation": {
"title": "Comment on approval",
"description": "Add a durable comment to a mock approval.",
"description": "Add a durable comment to an approval.",
"note": null
},
"examples": {
@@ -72,7 +72,7 @@ export const commentOnApprovalAction = {
"operationId": "comment_on_approval",
"version": 1,
"title": "Comment on approval",
"description": "Add a durable comment to a mock approval.",
"description": "Add a durable comment to an approval.",
"exposure": "optional",
"requiredClaims": [
"governance:approvals:comment"
@@ -94,7 +94,7 @@ export const commentOnApprovalAction = {
},
"approvalId": {
"type": "string",
"description": "Mock approval id.",
"description": "Approval id.",
"minLength": 1,
"maxLength": 200
},
@@ -117,7 +117,7 @@ export const commentOnApprovalAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -133,7 +133,7 @@ export const commentOnApprovalAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -27,7 +27,7 @@ export const controlWorkspaceServiceAction = {
},
"documentation": {
"title": "Control workspace service",
"description": "Start, stop, or fault one active-task mock workspace service.",
"description": "Start, stop, or fault one active-task workspace service.",
"note": null
},
"examples": {
@@ -70,7 +70,7 @@ export const controlWorkspaceServiceAction = {
"operationId": "control_workspace_service",
"version": 1,
"title": "Control workspace service",
"description": "Start, stop, or fault one active-task mock workspace service.",
"description": "Start, stop, or fault one active-task workspace service.",
"exposure": "optional",
"requiredClaims": [
"workspace:control"
@@ -90,7 +90,7 @@ export const controlWorkspaceServiceAction = {
},
"serviceId": {
"type": "string",
"description": "Mock workspace service id.",
"description": "Workspace service id.",
"minLength": 1,
"maxLength": 200
},
@@ -106,7 +106,7 @@ export const controlWorkspaceServiceAction = {
"string",
"null"
],
"description": "Optional mock service URL.",
"description": "Optional service URL.",
"maxLength": 20000
}
},
@@ -122,7 +122,7 @@ export const controlWorkspaceServiceAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -138,7 +138,7 @@ export const controlWorkspaceServiceAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -162,7 +162,7 @@ export const createTaskAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -178,7 +178,7 @@ export const createTaskAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -32,7 +32,7 @@ export const decideApprovalAction = {
},
"documentation": {
"title": "Decide approval",
"description": "Decide a mock approval as an explicitly authorized approver.",
"description": "Decide an approval as an explicitly authorized approver.",
"note": null
},
"examples": {
@@ -77,7 +77,7 @@ export const decideApprovalAction = {
"operationId": "decide_approval",
"version": 1,
"title": "Decide approval",
"description": "Decide a mock approval as an explicitly authorized approver.",
"description": "Decide an approval as an explicitly authorized approver.",
"exposure": "optional",
"requiredClaims": [
"governance:approvals:decide"
@@ -102,7 +102,7 @@ export const decideApprovalAction = {
},
"approvalId": {
"type": "string",
"description": "Mock approval id.",
"description": "Approval id.",
"minLength": 1,
"maxLength": 200
},
@@ -133,7 +133,7 @@ export const decideApprovalAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -149,7 +149,7 @@ export const decideApprovalAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -25,7 +25,7 @@ export const finishTaskAction = {
},
"documentation": {
"title": "Finish active task",
"description": "Finish the active mock task with a durable summary.",
"description": "Finish the active task with a durable summary.",
"note": null
},
"examples": {
@@ -66,7 +66,7 @@ export const finishTaskAction = {
"operationId": "finish_task",
"version": 1,
"title": "Finish active task",
"description": "Finish the active mock task with a durable summary.",
"description": "Finish the active task with a durable summary.",
"exposure": "always",
"requiredClaims": [],
"allowedModes": [
@@ -100,7 +100,7 @@ export const finishTaskAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -116,7 +116,7 @@ export const finishTaskAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -31,7 +31,7 @@ export const getAgentAction = {
},
"documentation": {
"title": "Get company agent",
"description": "Read one redacted mock actor profile.",
"description": "Read one redacted actor profile.",
"note": "Live-only single-actor read; the scenario suite covers actor discovery through list_agents."
},
"examples": {
@@ -54,7 +54,7 @@ export const getAgentAction = {
"operationId": "get_agent",
"version": 1,
"title": "Get company agent",
"description": "Read one redacted mock actor profile.",
"description": "Read one redacted actor profile.",
"exposure": "optional",
"requiredClaims": [
"discovery:agents:read"
@@ -70,7 +70,7 @@ export const getAgentAction = {
"properties": {
"actorId": {
"type": "string",
"description": "Mock actor id.",
"description": "Actor id.",
"minLength": 1,
"maxLength": 200
}
@@ -29,7 +29,7 @@ export const getApprovalContextAction = {
},
"documentation": {
"title": "Get approval context",
"description": "Read one approval, its comments, and linked mock tasks.",
"description": "Read one approval, its comments, and linked tasks.",
"note": "Live-only approval-plus-linked-tasks read; no scenario counterpart."
},
"examples": {
@@ -52,7 +52,7 @@ export const getApprovalContextAction = {
"operationId": "get_approval_context",
"version": 1,
"title": "Get approval context",
"description": "Read one approval, its comments, and linked mock tasks.",
"description": "Read one approval, its comments, and linked tasks.",
"exposure": "optional",
"requiredClaims": [
"governance:approvals:read"
@@ -68,7 +68,7 @@ export const getApprovalContextAction = {
"properties": {
"approvalId": {
"type": "string",
"description": "Mock approval id.",
"description": "Approval id.",
"minLength": 1,
"maxLength": 200
}
@@ -29,7 +29,7 @@ export const getApprovalAction = {
},
"documentation": {
"title": "Get approval",
"description": "Read one mock approval without protected data.",
"description": "Read one approval without protected data.",
"note": "Live-only single-approval read; the scenario suite covers approvals through list_approvals."
},
"examples": {
@@ -52,7 +52,7 @@ export const getApprovalAction = {
"operationId": "get_approval",
"version": 1,
"title": "Get approval",
"description": "Read one mock approval without protected data.",
"description": "Read one approval without protected data.",
"exposure": "optional",
"requiredClaims": [
"governance:approvals:read"
@@ -68,7 +68,7 @@ export const getApprovalAction = {
"properties": {
"approvalId": {
"type": "string",
"description": "Mock approval id.",
"description": "Approval id.",
"minLength": 1,
"maxLength": 200
}
@@ -27,7 +27,7 @@ export const getTaskHistoryAction = {
},
"documentation": {
"title": "Get active task history",
"description": "Read bounded comments on the active mock task.",
"description": "Read bounded comments on the active task.",
"note": null
},
"examples": {
@@ -48,7 +48,7 @@ export const getTaskHistoryAction = {
"operationId": "get_task_history",
"version": 1,
"title": "Get active task history",
"description": "Read bounded comments on the active mock task.",
"description": "Read bounded comments on the active task.",
"exposure": "always",
"requiredClaims": [],
"allowedModes": [
@@ -29,7 +29,7 @@ export const getWorkspaceRuntimeAction = {
},
"documentation": {
"title": "Get workspace runtime",
"description": "Read active-task mock workspace services.",
"description": "Read active-task workspace services.",
"note": null
},
"examples": {
@@ -50,7 +50,7 @@ export const getWorkspaceRuntimeAction = {
"operationId": "get_workspace_runtime",
"version": 1,
"title": "Get workspace runtime",
"description": "Read active-task mock workspace services.",
"description": "Read active-task workspace services.",
"exposure": "optional",
"requiredClaims": [
"workspace:read"
@@ -31,7 +31,7 @@ export const listAgentsAction = {
},
"documentation": {
"title": "List company agents",
"description": "List redacted mock actor profiles.",
"description": "List redacted actor profiles.",
"note": null
},
"examples": {
@@ -52,7 +52,7 @@ export const listAgentsAction = {
"operationId": "list_agents",
"version": 1,
"title": "List company agents",
"description": "List redacted mock actor profiles.",
"description": "List redacted actor profiles.",
"exposure": "optional",
"requiredClaims": [
"discovery:agents:read"
@@ -29,7 +29,7 @@ export const listApprovalsAction = {
},
"documentation": {
"title": "List approvals",
"description": "List mock approvals in the run company.",
"description": "List approvals in the run company.",
"note": null
},
"examples": {
@@ -50,7 +50,7 @@ export const listApprovalsAction = {
"operationId": "list_approvals",
"version": 1,
"title": "List approvals",
"description": "List mock approvals in the run company.",
"description": "List approvals in the run company.",
"exposure": "optional",
"requiredClaims": [
"governance:approvals:read"
@@ -27,7 +27,7 @@ export const listDocumentsAction = {
},
"documentation": {
"title": "List task documents",
"description": "List revisioned documents on the active mock task.",
"description": "List revisioned documents on the active task.",
"note": null
},
"examples": {
@@ -48,7 +48,7 @@ export const listDocumentsAction = {
"operationId": "list_documents",
"version": 1,
"title": "List task documents",
"description": "List revisioned documents on the active mock task.",
"description": "List revisioned documents on the active task.",
"exposure": "always",
"requiredClaims": [],
"allowedModes": [
@@ -26,7 +26,7 @@ export const registerDeliverableAction = {
},
"documentation": {
"title": "Register inspectable deliverable",
"description": "Register mock attachment metadata and its artifact work product without credentials or bytes in the tool result.",
"description": "Register attachment metadata and its artifact work product without credentials or bytes in the tool result.",
"note": null
},
"examples": {
@@ -77,7 +77,7 @@ export const registerDeliverableAction = {
"operationId": "register_deliverable",
"version": 1,
"title": "Register inspectable deliverable",
"description": "Register mock attachment metadata and its artifact work product without credentials or bytes in the tool result.",
"description": "Register attachment metadata and its artifact work product without credentials or bytes in the tool result.",
"exposure": "always",
"requiredClaims": [],
"allowedModes": [
@@ -144,7 +144,7 @@ export const registerDeliverableAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -160,7 +160,7 @@ export const registerDeliverableAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -29,7 +29,7 @@ export const reportProgressAction = {
},
"documentation": {
"title": "Report durable progress",
"description": "Append a durable progress comment to the active mock task.",
"description": "Append a durable progress comment to the active task.",
"note": null
},
"examples": {
@@ -70,7 +70,7 @@ export const reportProgressAction = {
"operationId": "report_progress",
"version": 1,
"title": "Report durable progress",
"description": "Append a durable progress comment to the active mock task.",
"description": "Append a durable progress comment to the active task.",
"exposure": "always",
"requiredClaims": [],
"allowedModes": [
@@ -106,7 +106,7 @@ export const reportProgressAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -122,7 +122,7 @@ export const reportProgressAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -27,7 +27,7 @@ export const requestApprovalAction = {
},
"documentation": {
"title": "Request approval",
"description": "Create a governed mock approval and waiting posture.",
"description": "Create a governed approval and waiting posture.",
"note": null
},
"examples": {
@@ -70,7 +70,7 @@ export const requestApprovalAction = {
"operationId": "request_approval",
"version": 1,
"title": "Request approval",
"description": "Create a governed mock approval and waiting posture.",
"description": "Create a governed approval and waiting posture.",
"exposure": "optional",
"requiredClaims": [
"governance:approvals:request"
@@ -111,7 +111,7 @@ export const requestApprovalAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -127,7 +127,7 @@ export const requestApprovalAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -27,7 +27,7 @@ export const requestHumanInputAction = {
},
"documentation": {
"title": "Request structured human input",
"description": "Create a typed, durable interaction on the active mock task.",
"description": "Create a typed, durable interaction on the active task.",
"note": null
},
"examples": {
@@ -74,7 +74,7 @@ export const requestHumanInputAction = {
"operationId": "request_human_input",
"version": 1,
"title": "Request structured human input",
"description": "Create a typed, durable interaction on the active mock task.",
"description": "Create a typed, durable interaction on the active task.",
"exposure": "always",
"requiredClaims": [],
"allowedModes": [
@@ -148,7 +148,7 @@ export const requestHumanInputAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -164,7 +164,7 @@ export const requestHumanInputAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -25,7 +25,7 @@ export const requestReviewAction = {
},
"documentation": {
"title": "Request task review",
"description": "Move the active mock task to review with a durable summary.",
"description": "Move the active task to review with a durable summary.",
"note": null
},
"examples": {
@@ -66,7 +66,7 @@ export const requestReviewAction = {
"operationId": "request_review",
"version": 1,
"title": "Request task review",
"description": "Move the active mock task to review with a durable summary.",
"description": "Move the active task to review with a durable summary.",
"exposure": "always",
"requiredClaims": [],
"allowedModes": [
@@ -100,7 +100,7 @@ export const requestReviewAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -116,7 +116,7 @@ export const requestReviewAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -27,7 +27,7 @@ export const scheduleWakeAction = {
},
"documentation": {
"title": "Schedule bounded wake",
"description": "Schedule a deterministic mock continuation wake.",
"description": "Schedule a deterministic continuation wake.",
"note": "Bounded, deterministic mock wake scheduling; requires the control_plane:wakes claim. Live-only continuation primitive."
},
"examples": {
@@ -62,7 +62,7 @@ export const scheduleWakeAction = {
"operationId": "schedule_wake",
"version": 1,
"title": "Schedule bounded wake",
"description": "Schedule a deterministic mock continuation wake.",
"description": "Schedule a deterministic continuation wake.",
"exposure": "optional",
"requiredClaims": [
"control_plane:wakes"
@@ -113,7 +113,7 @@ export const scheduleWakeAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -129,7 +129,7 @@ export const scheduleWakeAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -31,7 +31,7 @@ export const searchTasksAction = {
},
"documentation": {
"title": "Search company tasks",
"description": "Search mock tasks by text and status within the run company.",
"description": "Search tasks by text and status within the run company.",
"note": null
},
"examples": {
@@ -52,7 +52,7 @@ export const searchTasksAction = {
"operationId": "search_tasks",
"version": 1,
"title": "Search company tasks",
"description": "Search mock tasks by text and status within the run company.",
"description": "Search tasks by text and status within the run company.",
"exposure": "optional",
"requiredClaims": [
"discovery:tasks:read"
@@ -112,7 +112,7 @@ export const setDependenciesAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -128,7 +128,7 @@ export const setDependenciesAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -139,7 +139,7 @@ export const writeDocumentAction = {
"properties": {
"commandId": {
"type": "string",
"description": "Stable mock command identifier.",
"description": "Stable command identifier.",
"minLength": 1,
"maxLength": 200
},
@@ -155,7 +155,7 @@ export const writeDocumentAction = {
},
"entityRefs": {
"type": "array",
"description": "Mock entities affected by the operation.",
"description": "Entities affected by the operation.",
"items": {
"type": "string",
"minLength": 1
@@ -6468,6 +6468,21 @@ describe("native session bounded recovery", () => {
).toBe("native_current_wake_comments_changed_after_read");
});
it("requires operator action without retrying an approval-required terminal", () => {
const code = nativeSessionFailureSourceCode(
new NativeProviderTerminalFailure("approval_required", false, "Approval required"),
);
expect(code).toBe("native_provider_approval_required");
expect(nativeSessionFailureDisposition(1, new Date(), code)).toEqual({
phase: "terminal_failure",
failureCode: "native_provider_approval_required",
nextAttemptAt: null,
});
expect(nativeSessionRecoveryProjection({
phase: "terminal_failure", failureCode: code, agentId: "agent-1",
})).toMatchObject({ issueStatus: "blocked", recoveryOwner: { kind: "board" } });
});
it("retries the same run twice and stops at the third failed attempt", () => {
const now = new Date("2026-08-09T00:00:00.000Z");
expect(
@@ -5674,6 +5674,7 @@ export function nativeSessionFailureDisposition(
) {
const permanentFailure =
sourceFailureCode === "native_provider_model_rejected" ||
sourceFailureCode === "native_provider_approval_required" ||
sourceFailureCode === "native_event_replay_conflict" ||
sourceFailureCode === "runner_remote_provider_artifact_incompatible" ||
sourceFailureCode === "native_provider_terminal_failed" ||
@@ -5725,6 +5726,7 @@ export function nativeSessionFailureSourceCode(
error: unknown,
):
| "native_provider_terminal_failed"
| "native_provider_approval_required"
| "native_provider_usage_limit"
| "native_session_cleanup_quarantined"
| "native_adopted_runner_authentication_timeout"
@@ -5747,6 +5749,7 @@ export function nativeSessionFailureSourceCode(
| "native_current_wake_comments_changed_after_read"
| "native_session_interrupted" {
if (error instanceof NativeProviderTerminalFailure) {
if (error.providerCode === "approval_required") return "native_provider_approval_required";
// Failed terminals retain their security meaning across the provider facade.
// A stopped process is insufficient evidence to recover an integrity breach.
if (
@@ -8274,7 +8277,9 @@ async function executePaperclipNativeSessionWithinScope(
checkpointExists: recoveryEvidence.checkpointExists,
recoveryOwner: recoveryProjection.recoveryOwner,
nextAction:
sourceFailureCode === "native_session_cleanup_quarantined"
sourceFailureCode === "native_provider_approval_required"
? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler."
: sourceFailureCode === "native_session_cleanup_quarantined"
? NATIVE_CLEANUP_OPERATOR_RECOVERY_MESSAGE
: sourceFailureCode === "native_provider_terminal_failed"
? "The provider session is permanently unusable. Verify stopped execution, completed actions, and task context before starting a linked continuation."
@@ -8434,7 +8439,9 @@ async function executePaperclipNativeSessionWithinScope(
recoveryEvidence.providerSessionEstablished,
},
nextAction:
sourceFailureCode === "native_session_cleanup_quarantined"
sourceFailureCode === "native_provider_approval_required"
? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler."
: sourceFailureCode === "native_session_cleanup_quarantined"
? NATIVE_CLEANUP_OPERATOR_RECOVERY_MESSAGE
: sourceFailureCode === "native_provider_terminal_failed"
? "Verify that the failed provider stopped and reconcile its action outcomes. A linked continuation can proceed only after these checks succeed."
@@ -66,7 +66,7 @@ describe("Paperclip Runner Codex configuration", () => {
expect(html).not.toContain("Codex via ACPX");
expect(html).not.toContain("ACPX Codex");
expect(html).not.toContain("Pi via ACPX");
expect(html).toContain("Conservative (fail closed)");
expect(html).toContain("Allow Paperclip reads");
});
it("falls back to the fail-closed Codex permission mode", () => {
+15
View File
@@ -1281,6 +1281,21 @@ describe("TaskChatThread runtime transcript selection", () => {
},
);
it("shows an actionable approval-required reason for a stopped native run", () => {
render(<TaskChatThread comments={[]} onAdd={async () => {}} linkedRuns={[{
runId: "approval-required", runtimeMode: "native", status: "failed",
errorCode: "native_provider_approval_required",
agentId: "agent-1", agentName: "Runner", adapterType: "paperclip_runner",
startedAt: "2026-09-14T15:00:00.000Z", createdAt: "2026-09-14T15:00:00.000Z",
finishedAt: "2026-09-14T15:00:02.000Z",
}]} />);
const marker = container.querySelector('[data-testid="task-chat-collapsible-marker"]');
expect(marker?.textContent).toContain("Approval required");
flushSync(() => marker!.querySelector<HTMLButtonElement>('button[aria-expanded="false"]')!.click());
expect(container.textContent).toContain("Review the operation and update the agent's permission setting before retrying");
expect(container.textContent).not.toContain("The runner stopped");
});
it("keeps workspace contention out of the conversation's cancellation markers", () => {
render(<TaskChatThread comments={[]} onAdd={async () => {}} linkedRuns={[{
runId: "workspace-wait", runtimeMode: "native", status: "cancelled", errorCode: "workspace_busy",
+6 -2
View File
@@ -1558,7 +1558,9 @@ export function TaskChatThread(props: TaskChatThreadProps) {
? "native_runner_timed_out"
: "native_runner_process_exited");
const label =
code === "native_provider_usage_limit" && source.status === "failed"
code === "native_provider_approval_required" && source.status === "failed"
? "Approval required"
: code === "native_provider_usage_limit" && source.status === "failed"
? "Usage limit reached"
: source.status === "cancelled"
? "Run cancelled"
@@ -1575,7 +1577,9 @@ export function TaskChatThread(props: TaskChatThreadProps) {
? `The run was cancelled ${responseBoundary}.`
: source.status === "interrupted"
? `The run was interrupted ${responseBoundary}.`
: code === "native_provider_model_rejected"
: code === "native_provider_approval_required"
? "This operation requires approval, but this runner has no interactive approval handler. Review the operation and update the agent's permission setting before retrying."
: code === "native_provider_model_rejected"
? "The provider rejected the selected model. Check the model ID and your account's access, save the agent configuration, then retry. View the run for the provider's full error."
: code === "native_provider_usage_limit" &&
source.status === "failed"