Files
PaperClipAI/packages/adapter-utils/src/paperclip-runner-permissions.ts
T
DottaandClaude Opus 5.5 fc6e1b0346 perf(native): keep local Codex and OpenCode runners warm by default (#19888)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When someone messages an agent, the turn must start fast. Time to
first token (TTFT) is a first-class metric.
> - The Phase 0 baseline (#19846) found that every local turn launches a
new runner and loads the provider session again, because `per_turn` is
the default lifecycle. That made a follow-up message slower than a new
task.
> - Warm runners keep the runner and provider session alive between
runs. #19874 fixed the defect that broke warm OpenCode follow-ups, and
#19879 bounds an idle warm runner whose controller dies.
> - This pull request makes warm the default for local Codex and
OpenCode agents, and migrates existing agents that only carried the old
creation default.
> - The benefit: follow-up TTFT p50 drops from 12.0 s to 4.7 s (Codex)
and from 21.7 s to 4.2 s (OpenCode), with no new restart-chaos failures.

## Linked Issues or Issue Description

Refs #19846 (TTFT baseline), #19852 (startup sub-spans), #19874 (warm
completion contract), #19879 (warm reconnect grace).

**What existing behavior does this improve?**
The default runner lifecycle for native agents, and how a follow-up
message starts.

**Current behavior**
Agent creation writes `lifecycleMode: "per_turn"` into every native
agent. Every follow-up launches a new runner and restores the provider
session: 4.2 s (Codex) and 16.3 s (OpenCode) at p50 before the turn
starts.

**Proposed behavior**
New native agents store no lifecycle. On a local target, an unset
lifecycle resolves to `warm` with the default 5-minute idle window for
Codex and OpenCode. Other harnesses, remote targets and managed
providers without warm support stay `per_turn`. An explicit choice
always wins. Migration 0443 clears the stored creation default from
existing agents, except where an edit set "Turn by turn" explicitly.

**Reason and benefit**
Measured locally (`doc/plans/2026-11-07-warm-follow-up-ttft.md`). Warm
follow-ups are 2.6–5× faster for Codex and OpenCode, and restart
recovery latency is equal or lower.

## What Changed

- `native-lifecycle.ts`: an unset `agentMode` resolves to warm (5-minute
idle window) for local `codex_app_server` and `opencode_server` agents.
`runtime-selection.ts` passes `localTarget`. Explicit `per_turn` or
`warm` wins. An admitted session keeps its persisted policy. ACPX Claude
stays `per_turn`: it relaunches its provider process on every follow-up
by design, so warm did not shorten its follow-up (10.7 s warm vs 10.5 s
per_turn).
- Creation and configuration writes no longer store `lifecycleMode:
"per_turn"` for Codex, Claude or OpenCode. This covers
`normalizePaperclipRunnerAdapterConfig` (runs on every create and
update), `paperclipRunnerTransitionConfig` (switching to the native
runner), `agent-runner-selection.ts`, `codex-local` `build-config.ts`,
and the simplified new-agent setup (`paperclipRunnerCreationLifecycle`
in `@paperclipai/shared`). Grok, Pi and Cursor keep their explicit
value.
- Agent form: the Runner lifecycle field shows the unset state as
"Automatic". "Turn by turn" and "Warm session" remain.
- Migration `0443_native_warm_follow_up_default.sql`: clears
`lifecycleMode = 'per_turn'` from native Codex, OpenCode and Claude
agents unless `agent_config_revisions` shows an edit that set it to
`per_turn`. Each migrated agent gets an `agent.updated` activity entry
with the old value (`actor_id =
migration:native-warm-follow-up-default`). Creation records no revision,
so a "Turn by turn" pick made at creation cannot be told apart from the
old default. The product owner approved migrating those agents. Claude
agents follow the default, which is `per_turn` today.
- Restart chaos harness and TTFT driver: `--lifecycle
per_turn|warm|default` (saved in the wave plan). `default` removes the
catalog's pinned lifecycle, so a wave exercises the real default path.
- Docs: `doc/DEVELOPING.md` "Runner lifecycle default", and the results
in `doc/plans/2026-11-07-warm-follow-up-ttft.md`, which also documents
baseline finding 4 (Claude's resumed turn-start gap is ACPX's per-turn
process generation, not the provider).

## Verification

- `server`: `native-lifecycle.test.ts` (new default cases: local Codex
and OpenCode warm, Claude, remote, unknown target, unmeasured harness,
managed Claude, admitted per-turn session, explicit choices, non-native
adapter), `agent-runner-selection.test.ts`, `runtime-selection.test.ts`
(335 pass).
- `packages/db`: `native-warm-follow-up-default-migration.test.ts` on
embedded Postgres. Default agents are cleared, the explicit edit is
kept, other harnesses and legacy adapters are untouched, audit rows are
written once, and a rerun is a no-op. Without the explicit-edit filter
the test fails. `check:migrations` passes.
- `codex-local` `build-config.test.ts` (65), `ui`
`config-fields.test.tsx` (40), restart-chaos unit tests (134), `tsc
--noEmit` for `server`.
- `adapter-utils` `paperclip-runner-lifecycle-default.test.ts`:
configuration writes and adapter conversion store no lifecycle for
Codex, OpenCode and Claude, keep `per_turn` for the others, and preserve
explicit choices. It fails without the fix.
- End-to-end default check on this branch (`ttft-baseline.ts --lifecycle
default`, codex and opencode, 2 samples): the agents read back with no
stored lifecycle, and every follow-up reused the runner and provider
session (no `runner.process.launch`). Follow-up TTFT was 3.6–4.8 s. This
check found the per-write `per_turn` injection fixed here.
- Restart chaos (codex and opencode, A1/B1/B5, K1/K2/K6, seed 4242), 8/8
PASS each with no open signatures: forced warm, forced per_turn, and
`--lifecycle default` on this branch (agents created without a
lifecycle).
- `pnpm verify` selects broader CI (harness config is a global input),
so required CI supplies the broad coverage.

## Risks

- Behavior change: local Codex and OpenCode agents keep a runner and
provider process for up to 5 minutes after a run. Instance sleep waits
for that idle window. The process is reaped by the idle timer, by
graceful shutdown, or by the #19879 reconnect grace if its controller
dies.
- Migration: agents whose "Turn by turn" was chosen at creation become
Automatic. The activity entry records the old value; choosing "Turn by
turn" restores it.
- Previous-release story (`rules/upgrade-safe-run-state.mdc`): a task
session keeps the lifecycle policy it was admitted with, so sessions
saved before this change stay `per_turn`. New sessions get the default.
No run, checkpoint or launch state changes 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

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use (shell, file edit, test execution).

## 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
- [ ] All Paperclip CI gates are green
- [ ] 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-07 14:37:36 -06:00

285 lines
12 KiB
TypeScript

export type PaperclipRunnerProvider =
"codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx" | "openai_dot" | "grok_bot" | "muse" | "cursor_cloud";
export type CodexPermissionMode = "never" | "on-request" | "untrusted";
export type OpenCodePermissionMode = "allow" | "ask" | "deny";
export type AcpxPermissionMode = "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all";
export type PaperclipRunnerPermissionMode =
CodexPermissionMode | OpenCodePermissionMode | AcpxPermissionMode;
export const PAPERCLIP_RUNNER_IDLE_TIMEOUT_DEFAULT_MS = 300_000;
export const PAPERCLIP_RUNNER_IDLE_TIMEOUT_MAX_MS = 86_400_000;
export const PAPERCLIP_RUNNER_DEFAULT_MODELS = {
codex: "gpt-6.1-sol",
acpx: "claude-opus-5-5",
opencode: "openrouter/deepseek/deepseek-v4-flash-0731",
} as const;
export interface PaperclipRunnerPermissionOption<
TMode extends string = string,
> {
value: TMode;
label: string;
description: string;
}
export type PaperclipRunnerPermissionCapability =
| {
configurable: true;
configKey:
"codexPermissionMode" | "opencodePermissionMode" | "acpxPermissionMode";
defaultMode: PaperclipRunnerPermissionMode;
options: readonly PaperclipRunnerPermissionOption<PaperclipRunnerPermissionMode>[];
description: string;
}
| {
configurable: false;
defaultMode: "provider-managed";
options: readonly [];
description: string;
};
/**
* Control-plane catalog for Paperclip Runner permission UX and validation.
* Runtime contracts validate the same native values again at the process
* boundary; this catalog must remain browser-safe.
*/
export const PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES = {
codex: {
configurable: true,
configKey: "codexPermissionMode",
defaultMode: "never",
// `never` disables provider approval pauses; it does not disable the
// runner's independent security boundary. Native Codex may use this mode
// only through the root-denied, workspace-scoped, network-disabled, and
// environment-allowlisted profile assembled by codex-security-config.ts.
description:
"Codex runs automatically inside a root-denied, workspace-scoped, network-disabled Paperclip environment.",
options: [
{
value: "never",
label: "Automatic (isolated)",
description:
"Run without Codex approval pauses while Paperclip keeps its independent workspace, network, and environment restrictions.",
},
],
},
opencode: {
configurable: true,
configKey: "opencodePermissionMode",
defaultMode: "allow",
description:
"Controls OpenCode tool permissions inside the assigned Paperclip environment.",
options: [
{
value: "allow",
label: "Full auto (allow)",
description: "Allow OpenCode operations without approval pauses.",
},
{
value: "ask",
label: "Ask for permission",
description: "Prompt before protected OpenCode operations.",
},
{
value: "deny",
label: "Deny operations",
description: "Reject protected OpenCode operations.",
},
],
},
claude_managed: {
configurable: false,
defaultMode: "provider-managed",
options: [],
description:
"Claude Managed runs non-interactively under its qualified provider profile and Paperclip policy.",
},
aws_agentcore: {
configurable: false,
defaultMode: "provider-managed",
options: [],
description:
"AWS AgentCore runs non-interactively under its qualified harness profile and Paperclip policy.",
},
grok_bot: { configurable: false, defaultMode: "provider-managed", options: [], description: "Grok Bot uses first-party Paperclip tools and retains its native apps. Grok manages its model; spending, live steering, provider transcript streaming and remote interruption are unavailable." },
muse: { configurable: false, defaultMode: "provider-managed", options: [], description: "Muse uses the admitted Paperclip tool catalog and its own approved tools. Provider usage is unavailable and remote stop is best effort." },
openai_dot: { configurable: false, defaultMode: "provider-managed", options: [], description: "Dot uses the admitted Paperclip tool catalog. OpenAI manages its model and other tools; provider usage and global interruption are unavailable." },
cursor_cloud: { configurable: false, defaultMode: "provider-managed", options: [], description: "Cursor manages commands and files in its cloud environment. Assigned Paperclip tools retain company permissions. Provider command approvals and verified model identity are unavailable." },
acpx: {
configurable: true,
configKey: "acpxPermissionMode",
defaultMode: "approve-all",
description:
"Controls ACPX agent operations inside the assigned Paperclip environment.",
options: [
{
value: "approve-all",
label: "Full auto (approve all)",
description: "Approve ACPX operations without approval pauses.",
},
{
value: "approve-paperclip",
label: "Automatic Paperclip actions",
description:
"Automatically run assigned Paperclip planning and task tools, including reassignment. Company permissions and approval requirements still apply. Other operations require permission.",
},
{
value: "approve-reads",
label: "Allow Paperclip reads",
description:
"Automatically allow assigned Paperclip read tools. Other operations request a supported permission decision. Company permissions and execution boundaries still apply.",
},
{
value: "deny-all",
label: "Deny all",
description: "Reject harness permission requests.",
},
],
},
} as const satisfies Record<
PaperclipRunnerProvider,
PaperclipRunnerPermissionCapability
>;
export function isPaperclipRunnerProvider(
value: unknown,
): value is PaperclipRunnerProvider {
return (
value === "codex" ||
value === "opencode" ||
value === "claude_managed" ||
value === "aws_agentcore" ||
value === "acpx" || value === "openai_dot" || value === "grok_bot" || value === "muse" || value === "cursor_cloud"
);
}
export function resolvePaperclipRunnerPermissionMode(
provider: PaperclipRunnerProvider,
value: unknown,
): PaperclipRunnerPermissionMode | "provider-managed" {
const capability = PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[provider];
if (!capability.configurable) return capability.defaultMode;
return capability.options.some((option) => option.value === value)
? (value as PaperclipRunnerPermissionMode)
: capability.defaultMode;
}
/** Native session behavior is independent of tool permission policy. */
export function resolvePaperclipRunnerCursorMode(
provider: unknown,
agent: unknown,
value: unknown,
): "agent" | "plan" | "ask" | undefined {
if (provider !== "acpx" || agent !== "cursor") {
if (value !== undefined) throw new Error("acpxSessionMode is supported only for Cursor");
return undefined;
}
if (value === undefined) return "agent";
if (value === "agent" || value === "plan" || value === "ask") return value;
throw new Error("Cursor session mode must be agent, plan, or ask");
}
export function resolvePaperclipRunnerModel(
provider: keyof typeof PAPERCLIP_RUNNER_DEFAULT_MODELS,
value: unknown,
): string {
return typeof value === "string" && value.trim().length > 0
? value.trim()
: PAPERCLIP_RUNNER_DEFAULT_MODELS[provider];
}
export function resolvePaperclipRunnerIdleTimeoutMs(value: unknown): number {
return typeof value === "number" &&
Number.isSafeInteger(value) &&
value > 0 &&
value <= PAPERCLIP_RUNNER_IDLE_TIMEOUT_MAX_MS
? value
: PAPERCLIP_RUNNER_IDLE_TIMEOUT_DEFAULT_MS;
}
/**
* Native providers that store no lifecycle so the server applies the product
* default (warm on a local target for Codex and OpenCode; per-turn for Claude
* until its follow-up relaunch is removed). Others keep an explicit per_turn.
*/
export function paperclipRunnerFollowsLifecycleDefault(config: Record<string, unknown>): boolean {
return config.provider === "codex" || config.provider === "opencode"
|| (config.provider === "acpx" && config.acpxAgent === "claude");
}
/** Defaults for converting a local adapter; the operator may override the provider. */
export function paperclipRunnerTransitionConfig(
previousAdapterType: string,
previousModel: unknown,
providerOverride?: unknown,
): Record<string, unknown> {
if (previousAdapterType === "cursor_cloud" && (providerOverride === undefined || providerOverride === "cursor_cloud")) {
return { provider: "cursor_cloud", model: typeof previousModel === "string" ? previousModel.trim() : "", lifecycleMode: "per_turn" };
}
const previousProvider =
(["claude_local", "pi_local", "grok_local"].includes(previousAdapterType))
? "acpx"
: previousAdapterType === "opencode_local"
? "opencode"
: "codex";
const provider =
providerOverride === "codex" ||
providerOverride === "opencode" ||
providerOverride === "acpx"
? providerOverride
: previousProvider;
const converted: Record<string, unknown> = {
provider,
model: provider === "acpx" && previousAdapterType === "grok_local"
? typeof previousModel === "string" && previousModel.trim() && previousModel.trim() !== "grok-build" ? previousModel.trim() : "grok-4.7"
: provider === "acpx" && previousAdapterType === "pi_local"
? typeof previousModel === "string" ? previousModel.trim() : ""
: resolvePaperclipRunnerModel(
provider,
provider === previousProvider ? previousModel : undefined,
),
...(provider === "acpx" ? { acpxAgent: previousAdapterType === "grok_local" ? "grok" : previousAdapterType === "pi_local" ? "pi" : "claude" } : {}),
[PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[provider].configKey]:
PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[provider].defaultMode,
};
return paperclipRunnerFollowsLifecycleDefault(converted) ? converted : { ...converted, lifecycleMode: "per_turn" };
}
/** Old ACPX Codex agent settings use native Codex on their next configuration write. */
export function normalizeLegacyRunnerProvider(
config: Record<string, unknown>,
): Record<string, unknown> {
if (config.provider !== "acpx" || config.acpxAgent !== "codex") return config;
const {
acpxAgent: _agent,
acpxPermissionMode: _permission,
...rest
} = config;
return { ...rest, provider: "codex", codexPermissionMode: "never" };
}
/** Qualification is a release property, never an operator-configurable bypass. */
export const PAPERCLIP_RUNNER_ACPX_PROFILES = Object.freeze([
{ value: "grok", label: "Grok Build", qualified: true, credentialEnvironment: ["XAI_API_KEY"] },
{ value: "claude", label: "Claude", qualified: true, credentialEnvironment: ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"] },
{ value: "cursor", label: "Cursor", qualified: true, credentialEnvironment: ["CURSOR_API_KEY", "CURSOR_AUTH_TOKEN"] },
{ value: "copilot", label: "GitHub Copilot", qualified: true, credentialEnvironment: ["COPILOT_GITHUB_TOKEN"] },
{ value: "pi", label: "Pi", qualified: true, credentialEnvironment: ["OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"] },
{ value: "kimi", label: "Kimi Code", qualified: true, credentialEnvironment: ["KIMI_API_KEY"] },
{ value: "antigravity", label: "Google Antigravity", qualified: false, credentialEnvironment: ["GEMINI_API_KEY"] },
] as const);
/** Exact Pi native thinking levels; aliases that silently clamp are not configuration. */
export type PaperclipRunnerPiThinkingLevel = "off" | "low" | "high" | "max";
export function resolvePaperclipRunnerPiThinkingLevel(provider: unknown, agent: unknown, value: unknown): PaperclipRunnerPiThinkingLevel | undefined {
if (provider !== "acpx" || agent !== "pi") {
if (value !== undefined) throw new Error("piThinkingLevel is supported only for Pi");
return undefined;
}
if (value === undefined) return "low";
if (value === "off" || value === "low" || value === "high" || value === "max") return value;
throw new Error("Pi thinking level must be off, low, high, or max");
}